@skedulo/memory-hub-mcp 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createStalenessChecker = exports.citedPaths = void 0;
4
+ const promises_1 = require("fs/promises");
5
+ const path_1 = require("path");
6
+ const HEX_SHA = /^[0-9a-f]{7,64}$/i;
7
+ const TARGET_CANDIDATES = ['origin/HEAD', 'origin/main', 'origin/master', 'HEAD'];
8
+ const ENTRY_ID = /\*\*([A-Z][A-Z0-9]*-[RCD]\d+)\*\*/g;
9
+ const LISTED_PATH = /\s*,\s*([A-Za-z0-9_./-]+\.[A-Za-z0-9]+)(?![A-Za-z0-9])/y;
10
+ const CITATION = /\b(?:code|doc):\s*([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{7,64})\s+([^\s,·]+)/gi;
11
+ const URL = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s)]*/g;
12
+ // Mirrors EXTRAS_DEF in memory-hub-hook/session-start.sh, but a lookahead replaces \b so `src/a.ts_` (markdown italics) still matches.
13
+ const BARE_PATH = /[A-Za-z0-9_./-]+\.(?:tsx|ts|jsx|js|mjs|sh|py|json|md|yml|yaml|cls|java|kt|swift|go|rb)(?![A-Za-z0-9])/g;
14
+ function cleanPath(raw) {
15
+ return raw.replace(/[_*.)\]:;]+$/, '').replace(/^\.\//, '');
16
+ }
17
+ function entryBefore(ids, at) {
18
+ let found;
19
+ for (const entry of ids) {
20
+ if (entry.at < at)
21
+ found = entry.id;
22
+ }
23
+ return found;
24
+ }
25
+ function blank(line, start, end) {
26
+ return line.slice(0, start) + ' '.repeat(end - start) + line.slice(end);
27
+ }
28
+ function citedPaths(text, defaultRepo) {
29
+ const citations = [];
30
+ const seen = new Set();
31
+ const add = (citation) => {
32
+ if (!citation.path)
33
+ return;
34
+ const key = [citation.repo ?? '', citation.sha ?? '', citation.path, citation.entryId ?? ''].join('\0').toLowerCase();
35
+ if (seen.has(key))
36
+ return;
37
+ seen.add(key);
38
+ citations.push(citation);
39
+ };
40
+ for (const original of text.split('\n')) {
41
+ const ids = [...original.matchAll(ENTRY_ID)].map((m) => ({ id: m[1], at: m.index ?? 0 }));
42
+ const withId = (citation, at) => {
43
+ const entryId = entryBefore(ids, at);
44
+ return entryId ? { ...citation, entryId } : citation;
45
+ };
46
+ let line = original;
47
+ for (const match of original.matchAll(CITATION)) {
48
+ const at = match.index ?? 0;
49
+ const [, repo, sha] = match;
50
+ add(withId({ repo, sha, path: cleanPath(match[3]) }, at));
51
+ let end = at + match[0].length;
52
+ LISTED_PATH.lastIndex = end;
53
+ for (let listed = LISTED_PATH.exec(original); listed; listed = LISTED_PATH.exec(original)) {
54
+ add(withId({ repo, sha, path: cleanPath(listed[1]) }, at));
55
+ end = LISTED_PATH.lastIndex;
56
+ }
57
+ line = blank(line, at, end);
58
+ }
59
+ line = line.replace(URL, (url) => ' '.repeat(url.length));
60
+ for (const match of line.matchAll(BARE_PATH)) {
61
+ add(withId({ ...(defaultRepo ? { repo: defaultRepo } : {}), path: cleanPath(match[0]) }, match.index ?? 0));
62
+ }
63
+ }
64
+ return citations;
65
+ }
66
+ exports.citedPaths = citedPaths;
67
+ function changedFor(path, comparison) {
68
+ return comparison.changed.filter((file) => file === path || file.endsWith(`/${path}`));
69
+ }
70
+ function createStalenessChecker(deps) {
71
+ const { exec } = deps;
72
+ const here = deps.repo?.trim().toLowerCase() || undefined;
73
+ const comparisons = new Map();
74
+ let targetPromise;
75
+ let fetchedAtPromise;
76
+ const target = () => {
77
+ targetPromise ??= (async () => {
78
+ for (const ref of TARGET_CANDIDATES) {
79
+ const ok = await exec(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then(() => true, () => false);
80
+ if (ok)
81
+ return ref;
82
+ }
83
+ return undefined;
84
+ })();
85
+ return targetPromise;
86
+ };
87
+ const fetchedAt = () => {
88
+ fetchedAtPromise ??= exec(['rev-parse', '--absolute-git-dir'])
89
+ .then((out) => (0, promises_1.stat)((0, path_1.join)(out.trim(), 'FETCH_HEAD')))
90
+ .then((s) => s.mtime.toISOString(), () => undefined);
91
+ return fetchedAtPromise;
92
+ };
93
+ const compare = (sha, ref) => {
94
+ const key = `${sha.toLowerCase()}\0${ref}`;
95
+ let pending = comparisons.get(key);
96
+ if (!pending) {
97
+ pending = (async () => {
98
+ const commits = await exec(['rev-list', '--count', `${sha}..${ref}`]).then((out) => Number.parseInt(out.trim(), 10), () => undefined);
99
+ if (commits === undefined || Number.isNaN(commits))
100
+ return undefined;
101
+ const changed = await exec(['diff', '--name-only', sha, ref]).then((out) => out.split('\n').map((line) => line.trim()).filter(Boolean), () => undefined);
102
+ return changed ? { commits, changed } : undefined;
103
+ })();
104
+ comparisons.set(key, pending);
105
+ }
106
+ return pending;
107
+ };
108
+ const check = async (item) => {
109
+ const citations = citedPaths(item.text, item.source?.repo);
110
+ if (citations.length === 0)
111
+ return { status: 'nothing-cited' };
112
+ const local = citations.filter((c) => (c.repo ? c.repo.trim().toLowerCase() === here : true));
113
+ if (local.length === 0)
114
+ return { status: 'other-repo' };
115
+ const ref = await target();
116
+ if (!ref)
117
+ return { status: 'unknown-commit' };
118
+ const sourceSha = item.source?.commit?.trim();
119
+ let anyKnown = false;
120
+ const changedBySha = new Map();
121
+ const entries = new Set();
122
+ for (const citation of local) {
123
+ const sha = citation.sha ?? sourceSha;
124
+ if (!sha || !HEX_SHA.test(sha))
125
+ continue;
126
+ const comparison = await compare(sha, ref);
127
+ if (!comparison)
128
+ continue;
129
+ anyKnown = true;
130
+ const files = changedFor(citation.path, comparison);
131
+ if (files.length === 0)
132
+ continue;
133
+ const group = changedBySha.get(sha) ?? { comparison, files: new Set() };
134
+ files.forEach((file) => group.files.add(file));
135
+ changedBySha.set(sha, group);
136
+ if (citation.entryId)
137
+ entries.add(citation.entryId);
138
+ }
139
+ if (changedBySha.size === 0)
140
+ return { status: anyKnown ? 'unchanged' : 'unknown-commit' };
141
+ const since = sourceSha && changedBySha.has(sourceSha) ? sourceSha : [...changedBySha.keys()][0];
142
+ const changed = [...new Set([...changedBySha.values()].flatMap((group) => [...group.files]))];
143
+ const when = await fetchedAt();
144
+ return {
145
+ status: 'changed',
146
+ since,
147
+ target: ref,
148
+ commits: changedBySha.get(since).comparison.commits,
149
+ changed,
150
+ ...(entries.size > 0 ? { entries: [...entries] } : {}),
151
+ ...(when ? { fetchedAt: when } : {}),
152
+ };
153
+ };
154
+ return { check, target };
155
+ }
156
+ exports.createStalenessChecker = createStalenessChecker;
package/dist/sweep.js ADDED
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runSweep = exports.gitIn = exports.performSweep = exports.REPO_NAME = exports.SWEEP_USAGE = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const path_1 = require("path");
6
+ const check_sources_1 = require("./check-sources");
7
+ const client_1 = require("./client");
8
+ const git_remote_1 = require("./git-remote");
9
+ const staleness_1 = require("./staleness");
10
+ exports.SWEEP_USAGE = 'memory-hub-mcp sweep --repo <owner/name> --checkout <path> [--stamp]';
11
+ const HEX_SHA = /^[0-9a-f]{7,64}$/i;
12
+ exports.REPO_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;
13
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
14
+ const GIT_TIMEOUT_MS = 60_000;
15
+ const GIT_MAX_BUFFER = 64 * 1024 * 1024;
16
+ async function fetchItem(client, item) {
17
+ const uid = item.uid;
18
+ switch (item.type) {
19
+ case 'Fact': {
20
+ const got = await client.getFact({ uid });
21
+ return { text: got.content, source: got.source, lastModifiedDate: got.lastModifiedDate };
22
+ }
23
+ case 'Skill': {
24
+ const got = await client.getSkill({ uid });
25
+ return { text: got.content, source: got.source, lastModifiedDate: got.lastModifiedDate };
26
+ }
27
+ case 'Scenario': {
28
+ const got = await client.getScenario({ uid });
29
+ return { text: got.summary, source: got.source, lastModifiedDate: got.lastModifiedDate };
30
+ }
31
+ case 'Wiki': {
32
+ const got = await client.getWikiPage({ uid });
33
+ return { text: got.content, source: got.source, lastModifiedDate: got.lastModifiedDate };
34
+ }
35
+ }
36
+ }
37
+ async function stampSource(client, item, source, expectedLastModified) {
38
+ const input = { uid: item.uid, source: { repo: source.repo, commit: source.commit, ...(source.verifiedAt ? { verifiedAt: source.verifiedAt } : {}) }, expectedLastModified };
39
+ switch (item.type) {
40
+ case 'Fact':
41
+ await client.updateFact(input);
42
+ return;
43
+ case 'Skill':
44
+ await client.updateSkill(input);
45
+ return;
46
+ case 'Scenario':
47
+ await client.updateScenario(input);
48
+ return;
49
+ case 'Wiki':
50
+ await client.updateWikiPage(input);
51
+ return;
52
+ }
53
+ }
54
+ function countLines(out) {
55
+ if (!out)
56
+ return 0;
57
+ const lines = out.split('\n');
58
+ return out.endsWith('\n') ? lines.length - 1 : lines.length;
59
+ }
60
+ function message(error) {
61
+ return error instanceof Error ? error.message : String(error);
62
+ }
63
+ async function performSweep(deps, input) {
64
+ const { client, exec } = deps;
65
+ const repo = input.repo.trim();
66
+ const checker = (0, staleness_1.createStalenessChecker)({ exec, repo });
67
+ const ref = await checker.target();
68
+ const target = ref ? await exec(['rev-parse', `${ref}^{commit}`]).then((out) => out.trim(), () => undefined) : undefined;
69
+ if (!target) {
70
+ throw new Error('The checkout has no origin/HEAD, origin/main, origin/master or HEAD to compare against. Pass --checkout <path> of a clone of the repo.');
71
+ }
72
+ if (input.stamp && ref === 'HEAD') {
73
+ throw new Error('--stamp needs origin/HEAD, origin/main or origin/master; this checkout has only HEAD, which may hold unpushed commits. Clone the repo fresh, or run without --stamp.');
74
+ }
75
+ const result = { repo, target, unchanged: [], changed: [], nothingCited: [], unknownCommit: [], otherRepo: [], errors: [] };
76
+ const toStamp = [];
77
+ const now = deps.now().getTime();
78
+ for (const item of await (0, check_sources_1.listBySourceRepo)(client, repo)) {
79
+ try {
80
+ const full = await fetchItem(client, item);
81
+ const source = full.source ?? item.source;
82
+ const lastModifiedDate = full.lastModifiedDate ?? item.lastModifiedDate;
83
+ const staleness = await checker.check({ source, text: full.text });
84
+ switch (staleness.status) {
85
+ case 'unchanged':
86
+ result.unchanged.push(item.uid);
87
+ if (source)
88
+ toStamp.push({ item, source, lastModifiedDate });
89
+ break;
90
+ case 'nothing-cited':
91
+ result.nothingCited.push(item.uid);
92
+ break;
93
+ case 'unknown-commit':
94
+ result.unknownCommit.push(item.uid);
95
+ break;
96
+ case 'other-repo':
97
+ result.otherRepo.push(item.uid);
98
+ break;
99
+ case 'changed': {
100
+ const diffLines = await exec(['diff', staleness.since, target, '--', ...staleness.changed]).then(countLines, () => -1);
101
+ const modified = lastModifiedDate ? Date.parse(lastModifiedDate) : NaN;
102
+ result.changed.push({
103
+ uid: item.uid,
104
+ type: item.type,
105
+ title: item.title,
106
+ changed: staleness.changed,
107
+ diffLines,
108
+ editable: item.mine || (item.visibility === 'Team' && !!item.repoId),
109
+ editedByOtherWithin7Days: !item.mine && !Number.isNaN(modified) && now - modified <= WEEK_MS,
110
+ });
111
+ break;
112
+ }
113
+ }
114
+ }
115
+ catch (error) {
116
+ result.errors.push({ uid: item.uid, error: message(error) });
117
+ }
118
+ }
119
+ if (!input.stamp)
120
+ return result;
121
+ result.stamped = [];
122
+ result.notEditable = [];
123
+ for (const { item, source, lastModifiedDate } of toStamp) {
124
+ const old = source.commit.trim();
125
+ if (!HEX_SHA.test(old) || old.toLowerCase() === target.toLowerCase())
126
+ continue;
127
+ const isAncestor = await exec(['merge-base', '--is-ancestor', '--end-of-options', old, target]).then(() => true, () => false);
128
+ if (!isAncestor)
129
+ continue;
130
+ if (!lastModifiedDate) {
131
+ result.errors.push({ uid: item.uid, error: 'No lastModifiedDate to guard the update with; not stamped.' });
132
+ continue;
133
+ }
134
+ try {
135
+ await stampSource(client, item, { ...source, commit: target }, lastModifiedDate);
136
+ result.stamped.push(item.uid);
137
+ }
138
+ catch (error) {
139
+ const text = message(error);
140
+ if (text.startsWith('Not found')) {
141
+ result.notEditable.push(item.uid);
142
+ }
143
+ else {
144
+ result.errors.push({ uid: item.uid, error: text });
145
+ }
146
+ }
147
+ }
148
+ return result;
149
+ }
150
+ exports.performSweep = performSweep;
151
+ function gitIn(checkout) {
152
+ return (args) => new Promise((done, fail) => {
153
+ (0, child_process_1.execFile)('git', ['-C', checkout, ...args], { encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (err, stdout) => err ? fail(err) : done(stdout));
154
+ });
155
+ }
156
+ exports.gitIn = gitIn;
157
+ function option(argv, name) {
158
+ const index = argv.indexOf(`--${name}`);
159
+ const value = index >= 0 ? argv[index + 1] : undefined;
160
+ return value && !value.startsWith('--') ? value : undefined;
161
+ }
162
+ async function runSweep(argv, deps) {
163
+ const repo = option(argv, 'repo');
164
+ const checkoutArg = option(argv, 'checkout');
165
+ if (!repo || !checkoutArg) {
166
+ deps.log(`--repo and --checkout are required.\n${exports.SWEEP_USAGE}`);
167
+ return 2;
168
+ }
169
+ if (!exports.REPO_NAME.test(repo)) {
170
+ deps.log(`--repo must be owner/name, got "${repo}".\n${exports.SWEEP_USAGE}`);
171
+ return 2;
172
+ }
173
+ const apiToken = deps.env.MEMORY_HUB_MCP_TOKEN;
174
+ if (!apiToken) {
175
+ deps.log('MEMORY_HUB_MCP_TOKEN is not set. Run `npx -y @skedulo/memory-hub-mcp setup` first.');
176
+ return 1;
177
+ }
178
+ const checkout = (0, path_1.resolve)(checkoutArg);
179
+ const found = (deps.detectRepoName ?? git_remote_1.detectRepoName)(checkout);
180
+ if (found && found.toLowerCase() !== repo.trim().toLowerCase()) {
181
+ deps.log(`${checkout} is a checkout of ${found}, not ${repo}.`);
182
+ return 1;
183
+ }
184
+ const baseUrl = deps.env.MEMORY_HUB_FUNCTION_URL || deps.functionUrl();
185
+ const client = (deps.makeClient ?? ((config) => new client_1.MemoryHubClient(config)))({ baseUrl, apiToken });
186
+ const exec = (deps.makeExec ?? gitIn)(checkout);
187
+ const result = await performSweep({ client, exec, now: deps.now ?? (() => new Date()) }, { repo, stamp: argv.includes('--stamp') });
188
+ deps.log(JSON.stringify(result, null, 2));
189
+ return 0;
190
+ }
191
+ exports.runSweep = runSweep;
package/dist/tags.js CHANGED
@@ -34,4 +34,6 @@ exports.TAG_VALUES = [
34
34
  'ProjectRules',
35
35
  // The old name for ProjectRules, still written by skills older than 0.2.16.
36
36
  'ProductRules',
37
+ 'Superseded',
38
+ 'SkillDrift',
37
39
  ];
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.packageVersion = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ // Same relative path from src (ts-jest) and from dist.
7
+ function packageVersion(dir = __dirname) {
8
+ try {
9
+ return JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(dir, '..', 'package.json'), 'utf8')).version ?? 'unknown';
10
+ }
11
+ catch {
12
+ return 'unknown';
13
+ }
14
+ }
15
+ exports.packageVersion = packageVersion;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.17",
4
- "description": "MCP server for the SE AI Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
3
+ "version": "0.2.19",
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": {
7
7
  "type": "git",