@skedulo/memory-hub-mcp 0.2.31 → 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/watch.js ADDED
@@ -0,0 +1,570 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runWatch = exports.runCommand = exports.probe = exports.normalizeVersion = exports.deriveTargets = exports.citedRepoRefs = exports.WATCH_USAGE = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const check_sources_1 = require("./check-sources");
8
+ const client_1 = require("./client");
9
+ const git_remote_1 = require("./git-remote");
10
+ const sweep_1 = require("./sweep");
11
+ exports.WATCH_USAGE = 'memory-hub-mcp watch --repo <owner/name> --checkout <path> [--sources-dir <dir>] [--no-probe]';
12
+ const NO_FAST_PATH = 'no fast path; judge it';
13
+ const HEX_SHA = /^[0-9a-f]{7,40}$/i;
14
+ const NAMESPACE = /\b([a-z][a-z0-9]{1,14})__\w+?__(c|r|mdt|e|x|b)\b/g;
15
+ const REPO_REF = /\b([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{7,40})\b/g;
16
+ const SEMVER = /\b\d+\.\d+\.\d+\b/;
17
+ const SENTENCE_BREAK = /\. |\n/;
18
+ const MAX_EVIDENCE_FILES = 10;
19
+ const MAX_CHANGED = 300;
20
+ const MAX_BASELINES_PROBED = 5;
21
+ const MAX_MANIFESTS_READ = 3;
22
+ const MAX_FILE_BYTES = 1_000_000;
23
+ const MAX_FILES = 20_000;
24
+ const COMMAND_TIMEOUT_MS = 60_000;
25
+ const COMMAND_MAX_BUFFER = 64 * 1024 * 1024;
26
+ const SKIPPED_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'coverage', '.sfdx', '.sf', 'out', '.next']);
27
+ const SCANNED_EXTENSIONS = ['.cls', '.trigger', '.xml', '.json', '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.html', '.cmp', '.yml', '.yaml'];
28
+ function escapeRegExp(value) {
29
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
30
+ }
31
+ function repoMatcher(name) {
32
+ const body = name.trim().split(/[\s-]+/).map(escapeRegExp).join('[\\s-]+');
33
+ const pattern = new RegExp(`(?<![A-Za-z0-9_-])${body}(?![A-Za-z0-9-])`, 'i');
34
+ return (text) => pattern.test(text);
35
+ }
36
+ // A package or namespace name is often an ordinary word ("async", "jest", "skedulo"), so only its code forms count.
37
+ function codeMatcher(name, options = {}) {
38
+ const body = name.trim().split(/[\s-]+/).map(escapeRegExp).join('[\\s-]+');
39
+ const before = '(?<![A-Za-z0-9_@/.-])';
40
+ const forms = [`\`${body}\``, `${before}${body}@[\\^~=v]*\\d`, `${before}${body}\\s+v?\\d+\\.\\d+\\.\\d+`];
41
+ if (name.trim().startsWith('@'))
42
+ forms.push(`${before}${body}(?![A-Za-z0-9_/-])`);
43
+ if (options.namespace)
44
+ forms.push(`${before}${body}__\\w+?__(?:c|r|mdt|e|x|b)\\b`);
45
+ const pattern = new RegExp(forms.join('|'), options.namespace ? '' : 'i');
46
+ return (text) => pattern.test(text);
47
+ }
48
+ function parseJson(text) {
49
+ try {
50
+ const parsed = JSON.parse(text);
51
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined;
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ function asRecord(value) {
58
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
59
+ }
60
+ function basename(path) {
61
+ return path.slice(path.lastIndexOf('/') + 1);
62
+ }
63
+ function packageName(raw) {
64
+ return raw.replace(/@[^@]*$/, '').trim();
65
+ }
66
+ function sfpkgKey(name) {
67
+ return `sfpkg:${name.toLowerCase().replace(/\s+/g, '-')}`;
68
+ }
69
+ function sentenceRefs(sentence) {
70
+ return [...sentence.matchAll(REPO_REF)].map((m) => ({ name: m[1], sha: m[2], start: m.index ?? 0, end: (m.index ?? 0) + m[0].length }));
71
+ }
72
+ function versionFor(sentence, refs, index) {
73
+ const from = refs[index].end;
74
+ const to = index + 1 < refs.length ? refs[index + 1].start : sentence.length;
75
+ const following = SEMVER.exec(sentence.slice(from, to))?.[0];
76
+ if (following)
77
+ return following;
78
+ return refs.length === 1 ? SEMVER.exec(sentence)?.[0] : undefined;
79
+ }
80
+ function citedRepoRefs(text) {
81
+ return text.split(SENTENCE_BREAK).flatMap((sentence) => {
82
+ const refs = sentenceRefs(sentence);
83
+ return refs.map((ref, index) => {
84
+ const version = versionFor(sentence, refs, index);
85
+ return { name: ref.name, sha: ref.sha, ...(version ? { version } : {}) };
86
+ });
87
+ });
88
+ }
89
+ exports.citedRepoRefs = citedRepoRefs;
90
+ function deriveTargets(input) {
91
+ const selfRepo = input.repo.trim().toLowerCase();
92
+ const drafts = new Map();
93
+ const ownNamespaces = new Set();
94
+ const draft = (key, label, matches) => {
95
+ let found = drafts.get(key);
96
+ if (!found) {
97
+ found = { key, label, aliases: [], baselines: [], memories: new Set(), files: new Set(), matches };
98
+ drafts.set(key, found);
99
+ }
100
+ return found;
101
+ };
102
+ const scanned = input.files.filter((file) => !file.path.split('/').includes('node_modules'));
103
+ for (const file of scanned) {
104
+ if (basename(file.path) !== 'sfdx-project.json')
105
+ continue;
106
+ const namespace = asRecord(parseJson(file.text)).namespace;
107
+ if (typeof namespace === 'string' && namespace.trim())
108
+ ownNamespaces.add(namespace.trim().toLowerCase());
109
+ }
110
+ for (const file of scanned) {
111
+ const name = basename(file.path);
112
+ const json = name === 'sfdx-project.json' || name === 'package.json' ? parseJson(file.text) : undefined;
113
+ if (json && name === 'sfdx-project.json') {
114
+ const names = new Set();
115
+ const directories = Array.isArray(json.packageDirectories) ? json.packageDirectories : [];
116
+ for (const directory of directories) {
117
+ const dependencies = asRecord(directory).dependencies;
118
+ for (const dependency of Array.isArray(dependencies) ? dependencies : []) {
119
+ const pkg = asRecord(dependency).package;
120
+ if (typeof pkg === 'string')
121
+ names.add(packageName(pkg));
122
+ }
123
+ }
124
+ for (const alias of Object.keys(asRecord(json.packageAliases)))
125
+ names.add(packageName(alias));
126
+ for (const pkg of names) {
127
+ if (pkg)
128
+ draft(sfpkgKey(pkg), pkg, codeMatcher(pkg)).files.add(file.path);
129
+ }
130
+ }
131
+ else if (json && name === 'package.json') {
132
+ for (const section of [json.dependencies, json.devDependencies]) {
133
+ for (const dependency of Object.keys(asRecord(section))) {
134
+ draft(`npm:${dependency}`, dependency, codeMatcher(dependency)).files.add(file.path);
135
+ }
136
+ }
137
+ }
138
+ for (const match of file.text.matchAll(NAMESPACE)) {
139
+ const namespace = match[1];
140
+ if (ownNamespaces.has(namespace))
141
+ continue;
142
+ draft(`sfpkg-namespace:${namespace}`, `${namespace} package`, codeMatcher(namespace, { namespace: true })).files.add(file.path);
143
+ }
144
+ }
145
+ const githubDraft = (name, memoryUid) => {
146
+ if (!sweep_1.REPO_NAME.test(name) || name.toLowerCase() === selfRepo)
147
+ return undefined;
148
+ const found = draft(`github:${name.toLowerCase()}`, name, repoMatcher(name));
149
+ found.memories.add(memoryUid);
150
+ return found;
151
+ };
152
+ const addBaseline = (target, baseline) => {
153
+ const same = target.baselines.find((b) => b.memoryUid === baseline.memoryUid && b.sha === baseline.sha);
154
+ if (same)
155
+ same.version ??= baseline.version;
156
+ else
157
+ target.baselines.push(baseline);
158
+ };
159
+ const namesSelf = repoMatcher(input.repo);
160
+ const memories = input.memories.map((memory) => memory.source?.repo.trim().toLowerCase() === selfRepo
161
+ ? memory
162
+ : { type: memory.type, uid: memory.uid, text: memory.text.split(SENTENCE_BREAK).filter(namesSelf).join('\n') });
163
+ for (const memory of memories) {
164
+ for (const sentence of memory.text.split(SENTENCE_BREAK)) {
165
+ const refs = sentenceRefs(sentence);
166
+ refs.forEach((ref, index) => {
167
+ const target = githubDraft(ref.name, memory.uid);
168
+ if (!target)
169
+ return;
170
+ const version = versionFor(sentence, refs, index);
171
+ addBaseline(target, { memoryUid: memory.uid, sha: ref.sha.toLowerCase(), ...(version ? { version } : {}) });
172
+ });
173
+ }
174
+ }
175
+ for (const found of drafts.values()) {
176
+ for (const memory of memories) {
177
+ if (found.matches(memory.text))
178
+ found.memories.add(memory.uid);
179
+ }
180
+ }
181
+ mergeNamespaces(drafts, memories);
182
+ return [...drafts.values()]
183
+ .map((found) => ({
184
+ key: found.key,
185
+ label: found.label,
186
+ aliases: found.aliases,
187
+ baselines: found.baselines,
188
+ evidence: { memories: [...found.memories], files: [...found.files].sort().slice(0, MAX_EVIDENCE_FILES) },
189
+ namedByMemory: found.memories.size > 0,
190
+ }))
191
+ .sort((a, b) => b.evidence.memories.length - a.evidence.memories.length || a.key.localeCompare(b.key));
192
+ }
193
+ exports.deriveTargets = deriveTargets;
194
+ function mergeNamespaces(drafts, memories) {
195
+ const githubDrafts = [...drafts.values()].filter((d) => d.key.startsWith('github:'));
196
+ for (const target of [...drafts.values()]) {
197
+ if (!target.key.startsWith('sfpkg-namespace:'))
198
+ continue;
199
+ const namespace = target.key.slice('sfpkg-namespace:'.length);
200
+ const marked = new RegExp(`\`${escapeRegExp(namespace)}\`|namespace\\s+${escapeRegExp(namespace)}\\b|\\(${escapeRegExp(namespace)}\\)`, 'i');
201
+ const publishers = new Set();
202
+ for (const memory of memories) {
203
+ for (const sentence of memory.text.split(SENTENCE_BREAK)) {
204
+ if (!marked.test(sentence))
205
+ continue;
206
+ const candidates = githubDrafts.filter((d) => d.memories.has(memory.uid) && d.matches(sentence));
207
+ if (candidates.length === 1)
208
+ publishers.add(candidates[0]);
209
+ }
210
+ }
211
+ if (publishers.size !== 1)
212
+ continue;
213
+ const [publisher] = [...publishers];
214
+ publisher.aliases.push(namespace);
215
+ target.files.forEach((file) => publisher.files.add(file));
216
+ target.memories.forEach((uid) => publisher.memories.add(uid));
217
+ drafts.delete(target.key);
218
+ }
219
+ }
220
+ function message(error) {
221
+ return error instanceof Error ? error.message : String(error);
222
+ }
223
+ function lines(out) {
224
+ return out.split('\n').map((line) => line.trim()).filter(Boolean);
225
+ }
226
+ function ghUpstream(gh, repo) {
227
+ return {
228
+ async compare(sha) {
229
+ const body = asRecord(JSON.parse(await gh(['api', `repos/${repo}/compare/${sha}...HEAD`])));
230
+ const aheadBy = body.ahead_by;
231
+ if (typeof aheadBy !== 'number')
232
+ throw new Error('gh compare returned no ahead_by');
233
+ const files = Array.isArray(body.files) ? body.files : [];
234
+ const commits = Array.isArray(body.commits) ? body.commits : [];
235
+ const lastCommit = commits.length > 0 ? asRecord(commits[commits.length - 1]).sha : undefined;
236
+ let head;
237
+ if (aheadBy === 0)
238
+ head = asRecord(body.merge_base_commit).sha;
239
+ else if (commits.length >= aheadBy)
240
+ head = lastCommit;
241
+ if (!head)
242
+ head = (await gh(['api', `repos/${repo}/commits/HEAD`, '--jq', '.sha'])).trim();
243
+ if (!HEX_SHA.test(head))
244
+ throw new Error('could not read the head sha');
245
+ return {
246
+ aheadBy,
247
+ head,
248
+ changed: files.map((file) => asRecord(file).filename).filter((name) => typeof name === 'string').slice(0, MAX_CHANGED),
249
+ notAncestor: body.status === 'diverged' || body.status === 'behind',
250
+ };
251
+ },
252
+ async files(head) {
253
+ const body = asRecord(JSON.parse(await gh(['api', `repos/${repo}/git/trees/${head}?recursive=1`])));
254
+ const tree = Array.isArray(body.tree) ? body.tree : [];
255
+ return tree.map(asRecord).filter((entry) => entry.type === 'blob' && typeof entry.path === 'string').map((entry) => entry.path);
256
+ },
257
+ read(head, path) {
258
+ const encoded = path.split('/').map(encodeURIComponent).join('/');
259
+ return gh(['api', '-H', 'Accept: application/vnd.github.raw+json', `repos/${repo}/contents/${encoded}?ref=${head}`]);
260
+ },
261
+ };
262
+ }
263
+ async function localUpstream(exec, dir, repo) {
264
+ const origin = await exec(['-C', dir, 'remote', 'get-url', 'origin']).then((out) => (0, git_remote_1.canonicalizeRemoteUrl)(out.trim()), () => null);
265
+ if (!origin || origin.toLowerCase() !== repo.toLowerCase())
266
+ return undefined;
267
+ const git = (...args) => exec(['-C', dir, ...args]);
268
+ let prepared;
269
+ const prepare = () => {
270
+ prepared ??= (async () => {
271
+ if ((await git('rev-parse', '--is-shallow-repository')).trim() === 'true')
272
+ await git('fetch', '--unshallow', '--quiet');
273
+ for (const ref of ['origin/HEAD', 'origin/main', 'origin/master']) {
274
+ const found = await git('rev-parse', '--verify', `${ref}^{commit}`).then(() => ref, () => undefined);
275
+ if (found)
276
+ return found;
277
+ }
278
+ throw new Error(`${dir} has no origin/HEAD, origin/main or origin/master`);
279
+ })();
280
+ return prepared;
281
+ };
282
+ const headOf = async () => (await git('rev-parse', '--verify', `${await prepare()}^{commit}`)).trim();
283
+ return {
284
+ async compare(sha) {
285
+ const ref = await prepare();
286
+ const aheadBy = Number.parseInt((await git('rev-list', '--count', `${sha}..${ref}`)).trim(), 10);
287
+ if (Number.isNaN(aheadBy))
288
+ throw new Error('git rev-list returned no count');
289
+ const isAncestor = await git('merge-base', '--is-ancestor', sha, ref).then(() => true, () => false);
290
+ const head = await headOf();
291
+ if (!isAncestor)
292
+ return { aheadBy, head, changed: [], notAncestor: true };
293
+ return { aheadBy, head, changed: lines(await git('diff', '--name-only', sha, ref)).slice(0, MAX_CHANGED) };
294
+ },
295
+ async files(head) {
296
+ return lines(await git('ls-tree', '-r', '--name-only', head));
297
+ },
298
+ read(head, path) {
299
+ return git('show', `${head}:${path}`);
300
+ },
301
+ };
302
+ }
303
+ function normalizeVersion(version) {
304
+ const parts = version.trim().replace(/[.-]NEXT$/i, '').split('.');
305
+ if (parts.length === 4 && parts[3] === '0')
306
+ parts.pop();
307
+ return parts.join('.');
308
+ }
309
+ exports.normalizeVersion = normalizeVersion;
310
+ async function versionAtHead(upstream, head) {
311
+ const paths = (await upstream.files(head)).filter((path) => !path.split('/').includes('node_modules'));
312
+ const manifests = paths
313
+ .filter((path) => basename(path) === 'sfdx-project.json')
314
+ .sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b))
315
+ .slice(0, MAX_MANIFESTS_READ);
316
+ for (const path of manifests) {
317
+ const directories = asRecord(parseJson(await upstream.read(head, path))).packageDirectories;
318
+ for (const directory of Array.isArray(directories) ? directories : []) {
319
+ const versionNumber = asRecord(directory).versionNumber;
320
+ if (typeof versionNumber === 'string' && versionNumber.trim())
321
+ return normalizeVersion(versionNumber);
322
+ }
323
+ }
324
+ if (paths.includes('package.json')) {
325
+ const version = asRecord(parseJson(await upstream.read(head, 'package.json'))).version;
326
+ if (typeof version === 'string' && version.trim())
327
+ return normalizeVersion(version);
328
+ }
329
+ return undefined;
330
+ }
331
+ async function probeWith(upstream, target, shas) {
332
+ let oldest;
333
+ let firstError;
334
+ for (const sha of shas.slice(0, MAX_BASELINES_PROBED)) {
335
+ try {
336
+ const compared = await upstream.compare(sha);
337
+ if (compared.notAncestor)
338
+ throw new Error(`baseline ${sha} is not an ancestor of the default branch head; judge it`);
339
+ if (!oldest || compared.aheadBy > oldest.compared.aheadBy)
340
+ oldest = { sha, compared };
341
+ }
342
+ catch (error) {
343
+ firstError ??= error;
344
+ }
345
+ }
346
+ if (!oldest)
347
+ throw firstError;
348
+ const { sha, compared } = oldest;
349
+ const baselineVersion = (target.baselines.find((b) => b.sha === sha && b.version) ?? target.baselines.find((b) => b.version))?.version;
350
+ const common = { aheadBy: compared.aheadBy, changed: compared.changed };
351
+ if (compared.aheadBy === 0) {
352
+ return { state: 'unchanged', from: baselineVersion ?? sha, to: baselineVersion ?? compared.head, ...common };
353
+ }
354
+ const headVersion = baselineVersion ? await versionAtHead(upstream, compared.head) : undefined;
355
+ if (baselineVersion && headVersion) {
356
+ return { state: normalizeVersion(baselineVersion) === headVersion ? 'unchanged' : 'moved', from: baselineVersion, to: headVersion, ...common };
357
+ }
358
+ return { state: 'moved', from: sha, to: compared.head, ...common };
359
+ }
360
+ function githubRepo(target) {
361
+ if (!target.key.startsWith('github:'))
362
+ return undefined;
363
+ const lower = target.key.slice('github:'.length);
364
+ if (!sweep_1.REPO_NAME.test(lower))
365
+ return undefined;
366
+ return target.label.toLowerCase() === lower && sweep_1.REPO_NAME.test(target.label) ? target.label : lower;
367
+ }
368
+ async function probe(target, deps) {
369
+ try {
370
+ const repo = githubRepo(target);
371
+ if (!repo)
372
+ return { state: 'unknown', reason: NO_FAST_PATH };
373
+ const shas = [...new Set(target.baselines.map((b) => b.sha).filter((sha) => !!sha && HEX_SHA.test(sha)))];
374
+ if (shas.length === 0)
375
+ return { state: 'unknown', reason: 'no baseline sha to compare from' };
376
+ const reasons = [];
377
+ const upstreams = [];
378
+ if (deps.sourcesDir) {
379
+ const local = await localUpstream(deps.exec, (0, path_1.join)(deps.sourcesDir, repo.slice(repo.indexOf('/') + 1)), repo).catch(() => undefined);
380
+ if (local)
381
+ upstreams.push(local);
382
+ }
383
+ upstreams.push(ghUpstream(deps.gh, repo));
384
+ for (const upstream of upstreams) {
385
+ try {
386
+ return await probeWith(upstream, target, shas);
387
+ }
388
+ catch (error) {
389
+ reasons.push(message(error));
390
+ }
391
+ }
392
+ return { state: 'unknown', reason: reasons.join('; ') };
393
+ }
394
+ catch (error) {
395
+ return { state: 'unknown', reason: message(error) };
396
+ }
397
+ }
398
+ exports.probe = probe;
399
+ async function fetchFull(client, type, uid) {
400
+ switch (type) {
401
+ case 'Fact': {
402
+ const got = await client.getFact({ uid });
403
+ return { text: got.content, source: got.source };
404
+ }
405
+ case 'Skill': {
406
+ const got = await client.getSkill({ uid });
407
+ return { text: got.content, source: got.source };
408
+ }
409
+ case 'Scenario': {
410
+ const got = await client.getScenario({ uid });
411
+ return { text: got.summary, source: got.source };
412
+ }
413
+ case 'Wiki': {
414
+ const got = await client.getWikiPage({ uid });
415
+ return { text: got.content, source: got.source };
416
+ }
417
+ }
418
+ }
419
+ async function recallMentions(client, repo) {
420
+ const items = [];
421
+ const errors = [];
422
+ const attempt = async (type, run) => {
423
+ try {
424
+ items.push(...(await run()));
425
+ }
426
+ catch (error) {
427
+ errors.push({ uid: `recall:${type}`, error: message(error) });
428
+ }
429
+ };
430
+ const query = { scope: 'all', query: repo };
431
+ await attempt('Fact', async () => (await client.recall(query)).facts.map((m) => ({ type: 'Fact', uid: m.uid, text: m.content, source: m.source, truncated: m.truncated })));
432
+ await attempt('Skill', async () => (await client.listSkills(query)).skills.map((m) => ({ type: 'Skill', uid: m.uid, text: m.content, source: m.source, truncated: m.truncated })));
433
+ await attempt('Scenario', async () => (await client.recallScenarios(query)).scenarios.map((m) => ({ type: 'Scenario', uid: m.uid, text: m.summary, source: m.source, truncated: m.truncated })));
434
+ await attempt('Wiki', async () => (await client.recallWiki(query)).pages.map((m) => ({ type: 'Wiki', uid: m.uid, text: m.content, source: m.source, truncated: m.truncated })));
435
+ return { items, errors };
436
+ }
437
+ async function collectMemories(client, repo) {
438
+ const memories = new Map();
439
+ const errors = [];
440
+ for (const item of await (0, check_sources_1.listBySourceRepo)(client, repo)) {
441
+ try {
442
+ const full = await fetchFull(client, item.type, item.uid);
443
+ memories.set(item.uid, { type: item.type, uid: item.uid, text: full.text, source: full.source ?? item.source });
444
+ }
445
+ catch (error) {
446
+ errors.push({ uid: item.uid, error: message(error) });
447
+ }
448
+ }
449
+ const recalled = await recallMentions(client, repo);
450
+ errors.push(...recalled.errors);
451
+ for (const item of recalled.items) {
452
+ if (memories.has(item.uid))
453
+ continue;
454
+ try {
455
+ const full = item.truncated ? await fetchFull(client, item.type, item.uid) : { text: item.text, source: item.source };
456
+ memories.set(item.uid, { type: item.type, uid: item.uid, text: full.text, source: full.source ?? item.source });
457
+ }
458
+ catch (error) {
459
+ errors.push({ uid: item.uid, error: message(error) });
460
+ }
461
+ }
462
+ return { memories: [...memories.values()], errors };
463
+ }
464
+ function readCheckout(root) {
465
+ const files = [];
466
+ const stack = [''];
467
+ while (stack.length > 0 && files.length < MAX_FILES) {
468
+ const relative = stack.pop();
469
+ let entries;
470
+ try {
471
+ entries = (0, fs_1.readdirSync)((0, path_1.join)(root, relative), { withFileTypes: true });
472
+ }
473
+ catch {
474
+ continue;
475
+ }
476
+ for (const entry of entries) {
477
+ const path = relative ? `${relative}/${entry.name}` : entry.name;
478
+ if (entry.isDirectory()) {
479
+ if (!SKIPPED_DIRS.has(entry.name))
480
+ stack.push(path);
481
+ continue;
482
+ }
483
+ if (!entry.isFile() || entry.name === 'package-lock.json' || !SCANNED_EXTENSIONS.some((ext) => entry.name.endsWith(ext)))
484
+ continue;
485
+ try {
486
+ const full = (0, path_1.join)(root, path);
487
+ if ((0, fs_1.statSync)(full).size <= MAX_FILE_BYTES)
488
+ files.push({ path, text: (0, fs_1.readFileSync)(full, 'utf-8') });
489
+ }
490
+ catch {
491
+ continue;
492
+ }
493
+ }
494
+ }
495
+ return files.sort((a, b) => a.path.localeCompare(b.path));
496
+ }
497
+ function runCommand(file, args) {
498
+ return new Promise((done, fail) => {
499
+ (0, child_process_1.execFile)(file, args, { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS, maxBuffer: COMMAND_MAX_BUFFER }, (err, stdout) => (err ? fail(err) : done(stdout)));
500
+ });
501
+ }
502
+ exports.runCommand = runCommand;
503
+ function option(argv, name) {
504
+ const index = argv.indexOf(`--${name}`);
505
+ const value = index >= 0 ? argv[index + 1] : undefined;
506
+ return value && !value.startsWith('--') ? value : undefined;
507
+ }
508
+ async function runWatch(argv, deps) {
509
+ const repo = option(argv, 'repo');
510
+ const checkoutArg = option(argv, 'checkout');
511
+ const sourcesDirArg = option(argv, 'sources-dir');
512
+ if (!repo || !checkoutArg || (argv.includes('--sources-dir') && !sourcesDirArg)) {
513
+ deps.log(`--repo and --checkout are required, and --sources-dir needs a directory.\n${exports.WATCH_USAGE}`);
514
+ return 2;
515
+ }
516
+ if (!sweep_1.REPO_NAME.test(repo)) {
517
+ deps.log(`--repo must be owner/name, got "${repo}".\n${exports.WATCH_USAGE}`);
518
+ return 2;
519
+ }
520
+ const apiToken = deps.env.MEMORY_HUB_MCP_TOKEN;
521
+ if (!apiToken) {
522
+ deps.log('MEMORY_HUB_MCP_TOKEN is not set. Run `npx -y @skedulo/memory-hub-mcp setup` first.');
523
+ return 1;
524
+ }
525
+ const checkout = (0, path_1.resolve)(checkoutArg);
526
+ if (!(0, fs_1.statSync)(checkout, { throwIfNoEntry: false })?.isDirectory()) {
527
+ deps.log(`${checkout} is not a directory.`);
528
+ return 1;
529
+ }
530
+ const found = (deps.detectRepoName ?? git_remote_1.detectRepoName)(checkout);
531
+ if (found && found.toLowerCase() !== repo.trim().toLowerCase()) {
532
+ deps.log(`${checkout} is a checkout of ${found}, not ${repo}.`);
533
+ return 1;
534
+ }
535
+ const baseUrl = deps.env.MEMORY_HUB_FUNCTION_URL || deps.functionUrl();
536
+ const client = (deps.makeClient ?? ((config) => new client_1.MemoryHubClient(config)))({ baseUrl, apiToken });
537
+ const { memories, errors } = await collectMemories(client, repo.trim());
538
+ const targets = deriveTargets({ repo: repo.trim(), files: readCheckout(checkout), memories });
539
+ const probeDeps = {
540
+ exec: deps.exec ?? ((args) => runCommand('git', args)),
541
+ gh: deps.gh ?? ((args) => runCommand('gh', args)),
542
+ sourcesDir: sourcesDirArg ? (0, path_1.resolve)(sourcesDirArg) : undefined,
543
+ };
544
+ const noProbe = argv.includes('--no-probe');
545
+ const checked = [];
546
+ const nothingRestsOnIt = [];
547
+ const unresolved = [];
548
+ for (const target of targets) {
549
+ if (!target.namedByMemory) {
550
+ nothingRestsOnIt.push(target);
551
+ }
552
+ else if (target.key.startsWith('sfpkg-namespace:')) {
553
+ unresolved.push(target);
554
+ }
555
+ else {
556
+ const result = noProbe ? { state: 'unknown', reason: 'not probed (--no-probe)' } : await probe(target, probeDeps);
557
+ checked.push({ ...target, ...result });
558
+ }
559
+ }
560
+ const count = (state) => checked.filter((t) => t.state === state).length;
561
+ deps.log(JSON.stringify({
562
+ repo: repo.trim(),
563
+ discovered: targets.length,
564
+ buckets: { checked, nothingRestsOnIt, unresolved },
565
+ counts: { unchanged: count('unchanged'), moved: count('moved'), unknown: count('unknown'), nothingRestsOnIt: nothingRestsOnIt.length, unresolved: unresolved.length },
566
+ ...(errors.length > 0 ? { errors } : {}),
567
+ }, null, 2));
568
+ return 0;
569
+ }
570
+ exports.runWatch = runWatch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.31",
3
+ "version": "0.2.33",
4
4
  "description": "MCP server for the Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {