@skedulo/memory-hub-mcp 0.2.32 → 0.2.33

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
@@ -30,6 +30,9 @@ const extension_update_1 = require("./extension-update");
30
30
  const asset_sync_1 = require("./asset-sync");
31
31
  const tags_1 = require("./tags");
32
32
  const ask_prompt_1 = require("./ask-prompt");
33
+ const change_tools_1 = require("./change-tools");
34
+ const check_tools_1 = require("./check-tools");
35
+ const watch_1 = require("./watch");
33
36
  const client = new client_1.MemoryHubClient({
34
37
  credentials: () => {
35
38
  const creds = (0, credentials_1.resolveCredentials)();
@@ -52,7 +55,7 @@ const INSTRUCTIONS = [
52
55
  'memory_list type=Wiki scope=all titlePrefix="<Project> ›", and when the hub has nothing, list the projects it holds and ask',
53
56
  'which was meant, then only if none fits ask for sources and say reading them costs tokens.',
54
57
  'Progress questions (how a project, WO/CR, release or ticket is going): follow "Progress reports" in memory_getSkillGuide;',
55
- "reuse a WO or CR status snapshot under 60 minutes old, else pull live through the user's own connections.",
58
+ "reuse a WO or CR status snapshot within the limit `check.reuseUntil` gives, else pull live through the user's own connections.",
56
59
  'Tenant questions (what a customer\'s tenant runs): follow "Tenant snapshots" in memory_getSkillGuide; answer from the saved tenant snapshot first and refresh it only with admin console access.',
57
60
  'Every save gets a deliberate visibility (see "What to share" in memory_getSkillGuide):',
58
61
  'Team for work knowledge about a project or customer, saved with repo: "<owner/name>"',
@@ -65,6 +68,7 @@ const INSTRUCTIONS = [
65
68
  ].join(' ');
66
69
  const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: (0, version_1.packageVersion)() }, { instructions: INSTRUCTIONS });
67
70
  (0, login_tool_1.guardTools)(server, { signedIn: () => (0, credentials_1.resolveCredentials)() !== undefined, exempt: ['memory_login', 'memory_getSkillGuide'] });
71
+ (0, check_tools_1.guardCheckRun)(server, process.env);
68
72
  // Detected from this process's own working directory, not from anything the model
69
73
  // types. Resolved lazily on the first save so startup never blocks on git or the
70
74
  // network, and degrades to undefined (an unscoped save) on any failure.
@@ -174,7 +178,7 @@ const saveShape = {
174
178
  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; every agent can find it with scope all, so keep customer specifics to what the lesson needs. 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.'),
175
179
  source: source_1.sourceSchema.optional().describe(source_1.SOURCE_DESCRIPTION),
176
180
  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.'),
177
- distinctFrom: zod_1.z.string().min(1).optional().describe('Fact only — the uid of your own Fact that a "Not saved: your Fact <uid> … says nearly the same" reply named, when this note is about something else. Skips that one check for that uid.'),
181
+ distinctFrom: zod_1.z.union([zod_1.z.string().min(1), zod_1.z.array(zod_1.z.string().min(1)).min(1)]).optional().describe('Fact, Skill and Scenario only — a uid, or a list of uids, that "Not saved: … says nearly the same" replies named, when this note is about something else. Skips the check for those uids only. Ignored for a Wiki page.'),
178
182
  };
179
183
  const saveDeps = {
180
184
  client,
@@ -182,7 +186,7 @@ const saveDeps = {
182
186
  currentRepoUid: () => repoContext.currentRepoUid(),
183
187
  resolveTaskUid: (ref, repoUid) => taskContext.resolveTaskUid(ref, repoUid),
184
188
  };
185
- 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 you pass by name on a team you are not on is refused, never joined (only the current folder\'s repo auto-joins). 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. A Fact that says nearly the same as one of your own Private Facts on the same repo is not saved: the reply gives the text of that Fact to merge with memory_update, or distinctFrom to save it as its own note. 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) => {
189
+ 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 you pass by name on a team you are not on is refused, never joined (only the current folder\'s repo auto-joins). 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. A Fact, Skill or Scenario that says nearly the same as one you can edit on the same repo is not saved: the reply gives its text to merge with memory_update, or distinctFrom to save it as its own note. 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) => {
186
190
  const outcome = await (0, bulk_1.performSaveItem)(saveDeps, input);
187
191
  if ('refused' in outcome) {
188
192
  return { content: [{ type: 'text', text: outcome.refused }] };
@@ -196,7 +200,7 @@ server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the Me
196
200
  ],
197
201
  };
198
202
  });
199
- 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, error or refused (a Fact that nearly repeats one of your own Private Facts on the same repo, with the text to merge), 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) => {
203
+ 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, error or refused (a Fact, Skill or Scenario that nearly repeats one you can edit on the same repo, with the text to merge), 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) => {
200
204
  const { results, similarNotices, similarClosing } = await (0, bulk_1.performSaveBatch)(saveDeps, input.items);
201
205
  const similarBlock = similarNotices.length
202
206
  ? [
@@ -304,6 +308,40 @@ server.tool('memory_whoCanRead', "Preview who can read one Fact/Scenario/Skill/W
304
308
  const result = await (0, teams_1.performWhoCanRead)({ client }, input);
305
309
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
306
310
  });
311
+ server.tool('memory_reportChange', change_tools_1.REPORT_CHANGE_DESCRIPTION, change_tools_1.reportChangeSchema, async (input) => {
312
+ const result = await (0, change_tools_1.performReportChange)({ client }, input);
313
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
314
+ });
315
+ server.tool('memory_listChanges', change_tools_1.LIST_CHANGES_DESCRIPTION, change_tools_1.listChangesSchema, async (input) => {
316
+ const result = await (0, change_tools_1.performListChanges)({ client }, input);
317
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
318
+ });
319
+ server.tool('memory_ackChange', change_tools_1.ACK_CHANGE_DESCRIPTION, change_tools_1.ackChangeSchema, async (input) => {
320
+ const result = await (0, change_tools_1.performAckChange)({ client }, input);
321
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
322
+ });
323
+ server.tool('memory_retractChange', change_tools_1.RETRACT_CHANGE_DESCRIPTION, change_tools_1.retractChangeSchema, async (input) => {
324
+ const result = await (0, change_tools_1.performRetractChange)({ client }, input);
325
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
326
+ });
327
+ const checkStore = (0, check_tools_1.createCheckStore)();
328
+ const checkDeps = () => ({
329
+ client,
330
+ exec: check_sources_1.execGit,
331
+ gh: (args) => (0, watch_1.runCommand)('gh', args),
332
+ localRepo: repoContext.repoName,
333
+ background: (0, check_tools_1.isCheckRun)(process.env),
334
+ now: Date.now,
335
+ store: checkStore,
336
+ });
337
+ server.tool('memory_checkStart', check_tools_1.CHECK_START_DESCRIPTION, check_tools_1.checkStartSchema, async (input) => {
338
+ const result = await (0, check_tools_1.performCheckStart)(checkDeps(), input);
339
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
340
+ });
341
+ server.tool('memory_checkFinish', check_tools_1.CHECK_FINISH_DESCRIPTION, check_tools_1.checkFinishSchema, async (input) => {
342
+ const result = await (0, check_tools_1.performCheckFinish)(checkDeps(), input);
343
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
344
+ });
307
345
  server.tool('memory_update', "Revise a memory (yours, or a Team item on your team's repo) 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. The author can update any of their items; any member of the team that owns the item's repo can update a Team-visible item, but only the author can change its repo, links or factIds. expectedLastModified (the lastModifiedDate from memory_get) is required when you are not the author: without it the update is treated as author-only and fails with Not found, so Not found on an item you can read usually means it was left out. If the item changed since you read it, the update fails with a Conflict error instead of overwriting it. When this repeats or corrects something you already saved, use this, not memory_save.", {
308
346
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
309
347
  uid: zod_1.z.string().min(1),
@@ -0,0 +1,304 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.probeTarget = exports.itemTargets = exports.decodeKey = exports.encodeKey = exports.PAIR_KEY = void 0;
4
+ const soft_1 = require("./soft");
5
+ const staleness_1 = require("./staleness");
6
+ const sweep_1 = require("./sweep");
7
+ const watch_1 = require("./watch");
8
+ // The identity rules below mirror src/functions/memory-hub/src/core/item-sources.ts; the shared vectors in __fixtures__/item-sources-cases.json hold the two together.
9
+ const PROJECT_PAGE_MARKER = ' › ';
10
+ const TICKET = /\b[A-Z][A-Z0-9]+-\d+\b/g;
11
+ const NOT_TICKETS = new Set(['WO', 'CR', 'ES', 'UTF', 'ISO', 'SHA', 'RFC', 'HTTP', 'HTTPS', 'TLS', 'SSL', 'MD', 'AES', 'RSA', 'X', 'Y', 'Z', 'UTC', 'GMT', 'CVE', 'COVID', 'PR']);
12
+ const REPO_REF = /\b([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{7,40})\b/g;
13
+ const DOCUMENT_LINKS = [
14
+ { scheme: 'confluence', pattern: /https?:\/\/[^\s/]+\/wiki\/\S*?\/pages\/(\d+)\S*/g },
15
+ { scheme: 'confluence', pattern: /https?:\/\/[^\s/]+\/\S*?[?&]pageId=(\d+)\S*/g },
16
+ { scheme: 'gdrive', pattern: /https?:\/\/(?:drive|docs)\.google\.com\/\S*?\/d\/([A-Za-z0-9_-]+)\S*/g },
17
+ { scheme: 'gdrive', pattern: /https?:\/\/drive\.google\.com\/\S*?[?&]id=([A-Za-z0-9_-]+)\S*/g },
18
+ ];
19
+ const TICKET_SCHEME = 'linear';
20
+ const HEX_SHA = /^[0-9a-f]{7,40}$/i;
21
+ exports.PAIR_KEY = /^[a-z0-9][a-z0-9+.-]*:[^\s@;A-Z]+$/;
22
+ const MAX_COMPARE_FILES = 300;
23
+ const MAX_DIFF_LINES = 300;
24
+ const LOCAL_REFS = ['origin/HEAD', 'origin/main', 'origin/master'];
25
+ function allMatches(pattern, text) {
26
+ const found = [];
27
+ const scan = new RegExp(pattern.source, pattern.flags);
28
+ let match;
29
+ while ((match = scan.exec(text)) !== null) {
30
+ found.push(match);
31
+ }
32
+ return found;
33
+ }
34
+ function ticketsIn(text) {
35
+ return allMatches(TICKET, text)
36
+ .map((match) => match[0])
37
+ .filter((ticket) => !NOT_TICKETS.has(ticket.slice(0, ticket.indexOf('-'))))
38
+ .map((ticket) => ticket.toLowerCase());
39
+ }
40
+ function withoutDocumentLinks(text, documents) {
41
+ let rest = text;
42
+ for (const { scheme, pattern } of DOCUMENT_LINKS) {
43
+ rest = rest.replace(new RegExp(pattern.source, pattern.flags), (_link, id) => {
44
+ documents.add(`${scheme}:${id.toLowerCase()}`);
45
+ return ' ';
46
+ });
47
+ }
48
+ return rest;
49
+ }
50
+ function isProjectPage(item) {
51
+ return item.type === 'Wiki' && item.title.includes(PROJECT_PAGE_MARKER);
52
+ }
53
+ const isDocument = (identity) => identity.includes(':');
54
+ function encodeKey(key) {
55
+ const colon = key.indexOf(':');
56
+ return colon < 0 ? key : key.slice(0, colon + 1) + key.slice(colon + 1).replace(/@/g, '%40');
57
+ }
58
+ exports.encodeKey = encodeKey;
59
+ function decodeKey(key) {
60
+ const colon = key.indexOf(':');
61
+ return colon < 0 ? key : key.slice(0, colon + 1) + key.slice(colon + 1).replace(/%40/gi, '@');
62
+ }
63
+ exports.decodeKey = decodeKey;
64
+ const schemeFree = (key) => key.slice(key.indexOf(':') + 1);
65
+ function sameInstant(a, b) {
66
+ const left = Date.parse(a);
67
+ const right = Date.parse(b);
68
+ return Number.isFinite(left) && Number.isFinite(right) ? left === right : a === b;
69
+ }
70
+ function checkedPairs(item) {
71
+ const { checkedAgainst, checkedItemModified } = item.check ?? {};
72
+ if (!checkedAgainst || !checkedItemModified || !sameInstant(checkedItemModified, item.lastModifiedDate))
73
+ return [];
74
+ return checkedAgainst
75
+ .split(';')
76
+ .map((part) => part.trim())
77
+ .filter((part) => part.indexOf('@') > 0)
78
+ .map((part) => ({ key: part.slice(0, part.indexOf('@')).toLowerCase(), state: part.slice(part.indexOf('@') + 1) }))
79
+ .filter((pair) => pair.key.includes(':') && pair.state !== '');
80
+ }
81
+ function checkedFor(pairs, identity) {
82
+ return pairs.find((pair) => pair.key === identity) ?? (isDocument(identity) ? undefined : pairs.find((pair) => schemeFree(pair.key) === identity));
83
+ }
84
+ function itemTargets(item, sourcesPageDocs) {
85
+ const documents = new Set();
86
+ const text = withoutDocumentLinks(`${item.title}\n${item.text}`, documents);
87
+ const pairs = checkedPairs(item);
88
+ const targets = new Map();
89
+ const sourceRepo = item.source?.repo?.trim().toLowerCase() || undefined;
90
+ const repos = new Set();
91
+ if (sourceRepo)
92
+ repos.add(sourceRepo);
93
+ for (const match of allMatches(REPO_REF, text))
94
+ repos.add(match[1].toLowerCase());
95
+ const citations = (0, staleness_1.citedPaths)(item.text, item.source?.repo);
96
+ const refs = (0, watch_1.citedRepoRefs)(text);
97
+ for (const identity of repos) {
98
+ const cited = citations.filter((c) => c.repo?.toLowerCase() === identity);
99
+ const paths = [...new Set(cited.map((c) => c.path))];
100
+ const named = refs.filter((ref) => ref.name.toLowerCase() === identity);
101
+ const citedSha = named[0]?.sha ?? cited.find((c) => c.sha)?.sha;
102
+ const version = named.find((ref) => ref.version)?.version;
103
+ const checked = checkedFor(pairs, identity);
104
+ const target = { key: `github:${identity}`, identity, kind: 'repo' };
105
+ if (paths.length > 0)
106
+ target.paths = paths;
107
+ if (checked && HEX_SHA.test(checked.state))
108
+ Object.assign(target, { baseline: checked.state, baselineFrom: 'checked' });
109
+ else if (citedSha)
110
+ Object.assign(target, { baseline: citedSha, baselineFrom: 'cited' });
111
+ else if (identity === sourceRepo && item.source?.commit)
112
+ Object.assign(target, { baseline: item.source.commit, baselineFrom: 'source' });
113
+ if (citedSha || version)
114
+ target.stated = true;
115
+ if (version)
116
+ target.version = version;
117
+ targets.set(identity, target);
118
+ }
119
+ for (const identity of ticketsIn(`${text}\n${item.externalRef ?? ''}`)) {
120
+ const checked = checkedFor(pairs, identity);
121
+ targets.set(identity, {
122
+ key: checked?.key ?? `${TICKET_SCHEME}:${identity}`,
123
+ identity,
124
+ kind: 'ticket',
125
+ ...(checked ? { baseline: checked.state, baselineFrom: 'checked' } : {}),
126
+ });
127
+ }
128
+ const listed = new Map();
129
+ if (isProjectPage(item)) {
130
+ for (const doc of sourcesPageDocs) {
131
+ const key = doc.key.toLowerCase();
132
+ listed.set(key, listed.get(key) ?? doc.version);
133
+ documents.add(key);
134
+ }
135
+ }
136
+ for (const identity of documents) {
137
+ const checked = checkedFor(pairs, identity);
138
+ const version = listed.get(identity);
139
+ const target = { key: identity, identity, kind: 'document' };
140
+ if (checked)
141
+ Object.assign(target, { baseline: checked.state, baselineFrom: 'checked' });
142
+ else if (version)
143
+ Object.assign(target, { baseline: version, baselineFrom: 'sources-page' });
144
+ else
145
+ Object.assign(target, { baseline: item.createdDate, baselineFrom: 'created' });
146
+ targets.set(identity, target);
147
+ }
148
+ for (const { key: raw } of item.upstream ?? []) {
149
+ const key = encodeKey(raw.trim().toLowerCase());
150
+ const github = key.startsWith('github:') && exports.PAIR_KEY.test(key);
151
+ const identity = github ? schemeFree(key) : key;
152
+ if (targets.has(identity))
153
+ continue;
154
+ const checked = exports.PAIR_KEY.test(key) ? pairs.find((pair) => pair.key === key) : undefined;
155
+ targets.set(identity, {
156
+ key,
157
+ identity,
158
+ kind: github ? 'repo' : 'upstream',
159
+ ...(checked && (!github || HEX_SHA.test(checked.state)) ? { baseline: checked.state, baselineFrom: 'checked' } : {}),
160
+ });
161
+ }
162
+ return [...targets.values()].sort((a, b) => (a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0));
163
+ }
164
+ exports.itemTargets = itemTargets;
165
+ function message(error) {
166
+ return error instanceof Error ? error.message : String(error);
167
+ }
168
+ function lines(out) {
169
+ return out.split('\n').map((line) => line.trim()).filter(Boolean);
170
+ }
171
+ function asRecord(value) {
172
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
173
+ }
174
+ function capDiff(diff, truncated = false) {
175
+ const all = diff.replace(/\n+$/, '').split('\n');
176
+ return all.length > MAX_DIFF_LINES ? { diff: all.slice(0, MAX_DIFF_LINES).join('\n'), truncated: true } : { diff: all.join('\n'), truncated };
177
+ }
178
+ function citesFile(file, path) {
179
+ if (path.endsWith('/'))
180
+ return file.startsWith(path) || file.includes(`/${path}`);
181
+ return file === path || file.endsWith(`/${path}`);
182
+ }
183
+ const succeeds = (run) => run.then(() => true, () => false);
184
+ async function localCompare(exec, base) {
185
+ if (!(await succeeds(exec(['rev-parse', '--verify', '--quiet', `${base}^{commit}`]))))
186
+ return undefined;
187
+ let ref;
188
+ for (const candidate of LOCAL_REFS) {
189
+ if (await succeeds(exec(['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`]))) {
190
+ ref = candidate;
191
+ break;
192
+ }
193
+ }
194
+ if (!ref)
195
+ return undefined;
196
+ const head = (await exec(['rev-parse', ref])).trim();
197
+ const remote = await exec(['ls-remote', 'origin', 'HEAD']).catch(() => '');
198
+ if (!head || remote.split(/\s/)[0] !== head)
199
+ return undefined;
200
+ const range = `${base}..${ref}`;
201
+ const isAncestor = await succeeds(exec(['merge-base', '--is-ancestor', base, ref]));
202
+ const diff = async (changed) => capDiff(await exec(['diff', '--no-renames', range, ...(changed ? ['--', ...changed] : [])]));
203
+ if (!isAncestor)
204
+ return { head, files: [], notAncestor: true, diff };
205
+ return { head, files: lines(await exec(['diff', '--name-only', '--no-renames', range])), diff };
206
+ }
207
+ async function ghCompare(gh, repo, base) {
208
+ const body = asRecord(JSON.parse(await gh(['api', `repos/${repo}/compare/${base}...HEAD`])));
209
+ const unread = async () => ({ diff: '', truncated: true });
210
+ if (body.status === 'diverged' || body.status === 'behind')
211
+ return { head: '', files: [], notAncestor: true, diff: unread };
212
+ const entries = (Array.isArray(body.files) ? body.files : []).map(asRecord);
213
+ if (entries.length >= MAX_COMPARE_FILES)
214
+ return { head: '', files: [], atCap: true, diff: unread };
215
+ const aheadBy = typeof body.ahead_by === 'number' ? body.ahead_by : undefined;
216
+ const commits = Array.isArray(body.commits) ? body.commits : [];
217
+ let head;
218
+ if (aheadBy === 0)
219
+ head = asRecord(body.merge_base_commit).sha;
220
+ else if (aheadBy !== undefined && commits.length >= aheadBy)
221
+ head = asRecord(commits[commits.length - 1]).sha;
222
+ if (typeof head !== 'string' || !HEX_SHA.test(head))
223
+ head = (await gh(['api', `repos/${repo}/commits/HEAD`, '--jq', '.sha'])).trim();
224
+ if (typeof head !== 'string' || !HEX_SHA.test(head))
225
+ throw new Error('could not read the head sha');
226
+ const patches = new Map();
227
+ const fileFor = new Map();
228
+ for (const entry of entries) {
229
+ if (typeof entry.filename !== 'string')
230
+ continue;
231
+ patches.set(entry.filename, typeof entry.patch === 'string' ? entry.patch : undefined);
232
+ fileFor.set(entry.filename, entry.filename);
233
+ if (typeof entry.previous_filename === 'string')
234
+ fileFor.set(entry.previous_filename, entry.filename);
235
+ }
236
+ const diff = async (changed) => {
237
+ const files = [...new Set((changed ?? [...patches.keys()]).map((name) => fileFor.get(name) ?? name))];
238
+ const missing = files.some((file) => patches.get(file) === undefined);
239
+ const parts = files.filter((file) => patches.get(file) !== undefined).map((file) => `diff --git a/${file} b/${file}\n${patches.get(file)}`);
240
+ return capDiff(parts.join('\n'), missing);
241
+ };
242
+ return { head: head.trim(), files: [...fileFor.keys()], diff };
243
+ }
244
+ async function compareRepo(repo, base, deps) {
245
+ if (deps.localRepo && deps.localRepo.trim().toLowerCase() === repo) {
246
+ const local = await localCompare(deps.exec, base);
247
+ if (local)
248
+ return local;
249
+ }
250
+ return ghCompare(deps.gh, repo, base);
251
+ }
252
+ async function versionStillMatches(repo, target, deps) {
253
+ const result = await (0, watch_1.probe)({
254
+ key: target.key,
255
+ label: repo,
256
+ aliases: [],
257
+ baselines: [{ sha: target.baseline, version: target.version }],
258
+ evidence: { memories: [], files: [] },
259
+ namedByMemory: true,
260
+ }, { exec: deps.exec, gh: deps.gh });
261
+ return result.state === 'unchanged';
262
+ }
263
+ async function probeNow(target, deps) {
264
+ const { key } = target;
265
+ const judge = (reason) => ({ key, state: 'needs-judgement', reason });
266
+ if (!exports.PAIR_KEY.test(key))
267
+ return judge(`${key} cannot be written as a checkedAgainst key`);
268
+ if (target.kind === 'ticket')
269
+ return judge('ticket: compare its updatedAt and status with the baseline');
270
+ if (target.kind === 'document')
271
+ return judge('document: compare its version or modifiedTime with the baseline');
272
+ const repo = key.startsWith('github:') ? schemeFree(key) : undefined;
273
+ if (!repo || !sweep_1.REPO_NAME.test(repo))
274
+ return judge('no fast path; judge it');
275
+ const base = target.baseline;
276
+ if (!base || !HEX_SHA.test(base))
277
+ return judge('no baseline sha to compare from');
278
+ const paths = target.paths && target.paths.length > 0 ? target.paths : undefined;
279
+ if (!paths && !target.stated)
280
+ return judge('cites no path and states no sha or version of the repo');
281
+ try {
282
+ const compared = await compareRepo(repo, base, deps);
283
+ if (compared.notAncestor)
284
+ return judge(`baseline ${base} is not an ancestor of the default branch head`);
285
+ if (compared.atCap)
286
+ return judge(`the compare lists ${MAX_COMPARE_FILES} or more changed files, so a cited path may be missing`);
287
+ const changed = paths ? compared.files.filter((file) => paths.some((path) => citesFile(file, path))) : compared.files;
288
+ if (changed.length === 0)
289
+ return { key, state: 'unchanged', to: compared.head, changed: [] };
290
+ if (!paths && target.version && target.baselineFrom === 'cited' && (await versionStillMatches(repo, target, deps))) {
291
+ return { key, state: 'unchanged', to: compared.head, changed };
292
+ }
293
+ const { diff, truncated } = await compared.diff(paths ? changed : undefined).catch(() => ({ diff: '', truncated: true }));
294
+ return { key, state: 'moved', to: compared.head, changed, ...(diff ? { diff } : {}), truncated };
295
+ }
296
+ catch (error) {
297
+ return { key, state: 'unreachable', reason: message(error) };
298
+ }
299
+ }
300
+ function probeTarget(target, deps) {
301
+ const timedOut = { key: target.key, state: 'unreachable', reason: `timed out after ${deps.timeoutMs}ms` };
302
+ return (0, soft_1.soft)(probeNow(target, deps), timedOut, deps.timeoutMs);
303
+ }
304
+ exports.probeTarget = probeTarget;
package/dist/near-copy.js CHANGED
@@ -1,22 +1,86 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nearCopyCheck = exports.NEAR_COPY_FLOOR = void 0;
3
+ exports.nearCopyCheck = exports.refusalMessage = exports.bothKeptNotice = exports.widerThan = exports.distinctList = exports.isExempt = exports.MAX_MERGE_CHARS = exports.NEAR_COPY_FLOOR = void 0;
4
4
  const capture_1 = require("./capture");
5
5
  exports.NEAR_COPY_FLOOR = 0.9;
6
- const REPEATS_ON_PURPOSE_PREFIXES = ['Delegated ', 'Folded '];
6
+ exports.MAX_MERGE_CHARS = 20000;
7
+ const REPEATS_ON_PURPOSE_PREFIXES = ['Delegated ', 'Folded ', '# Delivery plan:', 'Test coverage for '];
7
8
  const REPEATS_ON_PURPOSE_TITLES = ['status snapshot', 'tenant snapshot', 'tenant map'];
8
- function repeatsOnPurpose(content) {
9
- if (REPEATS_ON_PURPOSE_PREFIXES.some((prefix) => content.startsWith(prefix))) {
9
+ function namesSnapshot(text) {
10
+ const firstLine = (text.split('\n')[0] ?? '').toLowerCase();
11
+ return REPEATS_ON_PURPOSE_TITLES.some((title) => firstLine.includes(title));
12
+ }
13
+ function repeatsOnPurpose(text) {
14
+ return REPEATS_ON_PURPOSE_PREFIXES.some((prefix) => text.startsWith(prefix)) || namesSnapshot(text);
15
+ }
16
+ function isExempt(input, env = process.env) {
17
+ if ((0, capture_1.isCaptureMode)(env) || input.supersedes) {
10
18
  return true;
11
19
  }
12
- const firstLine = (content.split('\n')[0] ?? '').toLowerCase();
13
- return REPEATS_ON_PURPOSE_TITLES.some((title) => firstLine.includes(title));
20
+ switch (input.type) {
21
+ case 'Fact':
22
+ return repeatsOnPurpose(input.content ?? '');
23
+ case 'Scenario':
24
+ return repeatsOnPurpose(input.summary ?? '');
25
+ case 'Skill':
26
+ return repeatsOnPurpose(input.title ?? '') || namesSnapshot(input.content ?? '');
27
+ case 'Wiki':
28
+ return true;
29
+ }
30
+ }
31
+ exports.isExempt = isExempt;
32
+ function distinctList(input) {
33
+ return input.distinctFrom === undefined ? [] : [input.distinctFrom].flat();
34
+ }
35
+ exports.distinctList = distinctList;
36
+ const VISIBILITY_RANK = { Private: 0, Team: 1, Org: 2 };
37
+ function narrower(visibility, than) {
38
+ return visibility !== 'Restricted' && VISIBILITY_RANK[visibility] < VISIBILITY_RANK[than];
14
39
  }
40
+ function widerThan(visibility, than) {
41
+ return visibility === 'Restricted' || (than !== 'Restricted' && VISIBILITY_RANK[visibility] > VISIBILITY_RANK[than]);
42
+ }
43
+ exports.widerThan = widerThan;
44
+ function bothKeptNotice(uid, repoName) {
45
+ const where = repoName ? ` on ${repoName}` : '';
46
+ return `Your Fact ${uid}${where} says nearly the same. Both are kept: the other is that project's; this one is this project's.`;
47
+ }
48
+ exports.bothKeptNotice = bothKeptNotice;
49
+ function factIdsLine(mine) {
50
+ return mine
51
+ ? "This save's factIds were not linked. factIds in memory_update replaces the Scenario's whole list, so pass it only with every fact the Scenario should keep."
52
+ : "This save's factIds were not linked: only the author can change a Scenario's facts.";
53
+ }
54
+ function refusalMessage(args) {
55
+ const { type, match, existingText } = args;
56
+ const date = args.existingLastModified ?? match.lastModifiedDate;
57
+ const where = match.repoName ? ` on ${match.repoName}` : '';
58
+ const updated = date ? ` (updated ${date.slice(0, 10)})` : '';
59
+ const distinct = [...new Set([...args.distinct, match.uid])].map((uid) => JSON.stringify(uid)).join(', ');
60
+ const saveAgain = `If this note is about something else, save again with distinctFrom: [${distinct}].`;
61
+ const guard = !match.mine && date ? ` expectedLastModified=${date}` : '';
62
+ const update = `memory_update type=${type} uid=${match.uid}${guard} with the complete merged text.`;
63
+ const opening = match.mine
64
+ ? `Not saved: your ${type} ${match.uid}${where}${updated} says nearly the same.`
65
+ : `Not saved: a teammate's Team ${type} ${match.uid}${where}${updated} says nearly the same.`;
66
+ const keep = match.mine ? 'Keep everything below that is still true.' : 'Keep everything below that is still true and keep their wording where it is still right.';
67
+ const sentences = existingText === undefined
68
+ ? [opening, `Read it with memory_get type=${type} uid=${match.uid}, then merge what is new into it and call ${update}`, saveAgain]
69
+ : [opening, `Merge what is new into the text below and call ${update}`, keep, saveAgain];
70
+ if (match.mine && narrower(match.visibility, match.saveVisibility)) {
71
+ sentences.push(`It is ${match.visibility}; this save asked for ${match.saveVisibility}. Ask the person before sharing it with memory_setVisibility.`);
72
+ }
73
+ if (type === 'Scenario' && args.hasFactIds) {
74
+ sentences.push(factIdsLine(match.mine));
75
+ }
76
+ return existingText === undefined ? sentences.join(' ') : `${sentences.join(' ')}\n\n${existingText}`;
77
+ }
78
+ exports.refusalMessage = refusalMessage;
15
79
  function sameRepo(a, b) {
16
80
  return (a ?? '').toLowerCase() === (b ?? '').toLowerCase();
17
81
  }
18
82
  async function nearCopyCheck(deps, input, currentRepo, env = process.env) {
19
- if ((0, capture_1.isCaptureMode)(env) || input.type !== 'Fact' || !input.content || input.supersedes || repeatsOnPurpose(input.content)) {
83
+ if (input.type !== 'Fact' || !input.content || isExempt(input, env)) {
20
84
  return {};
21
85
  }
22
86
  try {
@@ -30,32 +94,32 @@ exports.nearCopyCheck = nearCopyCheck;
30
94
  async function findNearCopy(deps, input, currentRepo) {
31
95
  const queryEmbedding = await deps.embed(input.content);
32
96
  const { facts } = await deps.client.recall({ scope: 'self', queryEmbedding, minSimilarity: exports.NEAR_COPY_FLOOR, maxCharsPerItem: 1, maxTotalChars: 2000 });
97
+ const distinct = distinctList(input);
33
98
  // Checked here too, so a function that ignores minSimilarity can't turn a weak match into a refusal.
34
99
  const near = facts
35
- .filter((fact) => (fact.similarity ?? 0) >= exports.NEAR_COPY_FLOOR && fact.uid !== input.distinctFrom)
100
+ .filter((fact) => (fact.similarity ?? 0) >= exports.NEAR_COPY_FLOOR && !distinct.includes(fact.uid) && (fact.fullLength ?? fact.content.length) <= exports.MAX_MERGE_CHARS)
36
101
  .sort((a, b) => (b.similarity ?? 0) - (a.similarity ?? 0));
37
102
  const same = near.find((fact) => sameRepo(fact.repoId, currentRepo));
38
103
  if (same) {
39
104
  const existing = await deps.client.getFact({ uid: same.uid });
40
- if (typeof existing.content !== 'string') {
105
+ if (typeof existing.content !== 'string' || existing.content.length > exports.MAX_MERGE_CHARS) {
41
106
  return {};
42
107
  }
43
- const where = same.repoName ? ` on ${same.repoName}` : '';
44
- const updated = same.lastModifiedDate ? ` (updated ${same.lastModifiedDate.slice(0, 10)})` : '';
45
- return {
46
- refusal: `Not saved: your Fact ${same.uid}${where}${updated} says nearly the same. ` +
47
- `Merge what is new into the text below and call memory_update type=Fact uid=${same.uid} with the complete merged text. ` +
48
- 'Keep everything below that is still true. ' +
49
- `If this note is about something else, save again with distinctFrom: "${same.uid}".\n\n${existing.content}`,
108
+ const match = {
109
+ uid: same.uid,
110
+ similarity: same.similarity ?? exports.NEAR_COPY_FLOOR,
111
+ mine: true,
112
+ visibility: existing.visibility ?? 'Private',
113
+ repoId: same.repoId ?? null,
114
+ repoName: same.repoName,
115
+ lastModifiedDate: same.lastModifiedDate,
116
+ saveVisibility: input.visibility ?? (currentRepo ? 'Team' : 'Private'),
50
117
  };
118
+ return { refusal: refusalMessage({ type: 'Fact', match, existingText: existing.content, existingLastModified: existing.lastModifiedDate, distinct }) };
51
119
  }
52
120
  const other = near[0];
53
121
  if (other) {
54
- const where = other.repoName ? ` on ${other.repoName}` : '';
55
- return {
56
- notice: `Your Fact ${other.uid}${where} says nearly the same. Both are kept: the other is that project's; this one is this project's.`,
57
- matchUid: other.uid,
58
- };
122
+ return { notice: bothKeptNotice(other.uid, other.repoName), matchUid: other.uid };
59
123
  }
60
124
  return {};
61
125
  }
@@ -394,6 +394,7 @@ function convertPack(opts) {
394
394
  facts,
395
395
  flags: collectFlags(items),
396
396
  ...(source ? { source } : {}),
397
+ ...(source && opts.checkout?.committedAt ? { sourceCommittedAt: opts.checkout.committedAt } : {}),
397
398
  ...(warnings.length ? { warnings } : {}),
398
399
  };
399
400
  }
package/dist/routine.js CHANGED
@@ -6,7 +6,7 @@ const fs_1 = require("fs");
6
6
  const client_1 = require("./client");
7
7
  const sweep_1 = require("./sweep");
8
8
  exports.ROUTINE_NAME = 'Memory hub weekly sweep';
9
- exports.ROUTINE_USAGE = 'memory-hub-mcp routine --mode <dry-run|apply> --user <email> --environment <id> --repos <owner/name,...> [--connections-file <path>]';
9
+ exports.ROUTINE_USAGE = 'memory-hub-mcp routine --mode <dry-run|apply> --user <email> --environment <id> --repos <owner/name,...> [--watch-repos <owner/name,...>] [--connections-file <path>]';
10
10
  const HUB_REPO = 'Skedulo/se-ai-memory-hub';
11
11
  const TYPES = ['Fact', 'Skill', 'Scenario', 'Wiki'];
12
12
  const ALLOWED_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'Skill'];
@@ -23,7 +23,7 @@ exports.sweepPrompt = sweepPrompt;
23
23
  function buildSweepRoutine(input) {
24
24
  const seen = new Set();
25
25
  const sources = [];
26
- for (const repo of [HUB_REPO, ...input.repos]) {
26
+ for (const repo of [HUB_REPO, ...input.repos, ...(input.watchRepos ?? [])]) {
27
27
  const key = repo.trim().toLowerCase();
28
28
  if (seen.has(key))
29
29
  continue;
@@ -80,6 +80,7 @@ async function runRoutine(argv, deps) {
80
80
  const user = option(argv, 'user');
81
81
  const environmentId = option(argv, 'environment');
82
82
  const reposIndex = argv.indexOf('--repos');
83
+ const watchIndex = argv.indexOf('--watch-repos');
83
84
  const reposArg = reposIndex >= 0 ? (argv[reposIndex + 1] ?? '') : undefined;
84
85
  if (mode !== 'dry-run' && mode !== 'apply') {
85
86
  deps.log(`--mode must be dry-run or apply.\n${exports.ROUTINE_USAGE}`);
@@ -102,6 +103,17 @@ async function runRoutine(argv, deps) {
102
103
  deps.log(`--repos must be owner/name entries, got "${bad}".\n${exports.ROUTINE_USAGE}`);
103
104
  return 2;
104
105
  }
106
+ const watchRepos = watchIndex >= 0
107
+ ? (argv[watchIndex + 1] ?? '')
108
+ .split(',')
109
+ .map((repo) => repo.trim())
110
+ .filter(Boolean)
111
+ : [];
112
+ const badWatch = watchRepos.find((repo) => !sweep_1.REPO_NAME.test(repo));
113
+ if (badWatch) {
114
+ deps.log(`--watch-repos must be owner/name entries, got "${badWatch}".\n${exports.ROUTINE_USAGE}`);
115
+ return 2;
116
+ }
105
117
  let connections;
106
118
  const connectionsFile = option(argv, 'connections-file');
107
119
  if (connectionsFile) {
@@ -129,7 +141,7 @@ async function runRoutine(argv, deps) {
129
141
  deps.log('None of the repos has items in the hub, so there is nothing to sweep.');
130
142
  return 2;
131
143
  }
132
- const body = buildSweepRoutine({ mode, timeZone: deps.timeZone() || 'UTC', user, repos: withItems, environmentId, connections });
144
+ const body = buildSweepRoutine({ mode, timeZone: deps.timeZone() || 'UTC', user, repos: withItems, watchRepos, environmentId, connections });
133
145
  deps.log(JSON.stringify(body, null, 2));
134
146
  return 0;
135
147
  }