@skedulo/memory-hub-mcp 0.2.13 → 0.2.15

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,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runImport = exports.IMPORT_USAGE = void 0;
4
+ const fs_1 = require("fs");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const client_1 = require("./client");
8
+ const pack_import_1 = require("./pack-import");
9
+ const import_apply_1 = require("./import-apply");
10
+ const git_remote_1 = require("./git-remote");
11
+ exports.IMPORT_USAGE = `memory-hub-mcp import convert <packDir> --product <name> --prefix <PREFIX> [--by <name>] [--out <plan.json>] [--force]
12
+ memory-hub-mcp import apply <plan.json> --repo <owner/name>`;
13
+ function option(argv, name) {
14
+ const index = argv.indexOf(`--${name}`);
15
+ const value = index >= 0 ? argv[index + 1] : undefined;
16
+ return value && !value.startsWith('--') ? value : undefined;
17
+ }
18
+ // Holds flagged customer values; chmod also tightens a file an earlier run left readable.
19
+ function writePrivate(path, text) {
20
+ (0, fs_1.writeFileSync)(path, text, { mode: 0o600 });
21
+ (0, fs_1.chmodSync)(path, 0o600);
22
+ }
23
+ // apply rewrites the plan after every save; a rename means an interrupted write never loses the resume state.
24
+ function writePlan(path, plan) {
25
+ writePrivate(`${path}.tmp`, `${JSON.stringify(plan, null, 2)}\n`);
26
+ (0, fs_1.renameSync)(`${path}.tmp`, path);
27
+ }
28
+ function reviewPathFor(planPath) {
29
+ return `${planPath.replace(/\.json$/, '')}.md`;
30
+ }
31
+ function readPlan(path) {
32
+ let plan;
33
+ try {
34
+ plan = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
35
+ }
36
+ catch (error) {
37
+ throw new Error(`Could not read the plan ${path}: ${error instanceof Error ? error.message : String(error)}`);
38
+ }
39
+ if (plan.version !== 1 || !Array.isArray(plan.pages) || !Array.isArray(plan.facts) || !Array.isArray(plan.flags)) {
40
+ throw new Error(`${path} is not an import plan this version understands (expected version 1 with pages, facts and flags).`);
41
+ }
42
+ return plan;
43
+ }
44
+ function hasSavedItems(path) {
45
+ const plan = readPlan(path);
46
+ return [...plan.pages, ...plan.facts].some((item) => item.savedUid);
47
+ }
48
+ async function runImport(argv, deps) {
49
+ const [subcommand, rawTarget] = argv;
50
+ const target = rawTarget && !rawTarget.startsWith('--') ? rawTarget : undefined;
51
+ if (subcommand === 'convert' && target) {
52
+ const product = option(argv, 'product');
53
+ const prefix = option(argv, 'prefix');
54
+ if (!product || !prefix) {
55
+ deps.log(`--product and --prefix are required.\n${exports.IMPORT_USAGE}`);
56
+ return 2;
57
+ }
58
+ const packDir = (0, path_1.resolve)(target);
59
+ const plan = (0, pack_import_1.convertPack)({ packDir, product, prefix, by: option(argv, 'by') ?? 'memory-hub-mcp import', today: deps.today(), checkout: (0, git_remote_1.packCheckout)(packDir) });
60
+ const out = option(argv, 'out');
61
+ const planPath = (0, path_1.resolve)(out ?? (0, path_1.join)((0, os_1.tmpdir)(), 'memory-hub-import', `${prefix}.json`));
62
+ const reviewPath = reviewPathFor(planPath);
63
+ if ((0, fs_1.existsSync)(planPath) && !argv.includes('--force') && hasSavedItems(planPath)) {
64
+ deps.log(`${planPath} already records saved items; re-run apply to resume, or pass --force to start a new plan.`);
65
+ return 1;
66
+ }
67
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(planPath), { recursive: true, mode: 0o700 });
68
+ // Only the default folder is ours to tighten; a folder named with --out keeps the developer's own mode.
69
+ if (!out)
70
+ (0, fs_1.chmodSync)((0, path_1.dirname)(planPath), 0o700);
71
+ writePlan(planPath, plan);
72
+ writePrivate(reviewPath, (0, pack_import_1.renderReview)(plan, planPath));
73
+ for (const warning of plan.warnings ?? [])
74
+ deps.log(`Warning: ${warning}`);
75
+ deps.log(`${plan.pages.length} pages, ${plan.facts.length} facts, ${plan.flags.length} flags to review.\nPlan: ${planPath}\nReview: ${reviewPath}`);
76
+ return 0;
77
+ }
78
+ if (subcommand === 'apply' && target) {
79
+ const repoName = option(argv, 'repo');
80
+ if (!repoName) {
81
+ deps.log(`--repo is required.\n${exports.IMPORT_USAGE}`);
82
+ return 2;
83
+ }
84
+ const apiToken = deps.env.MEMORY_HUB_MCP_TOKEN;
85
+ if (!apiToken) {
86
+ deps.log('MEMORY_HUB_MCP_TOKEN is not set. Run `npx -y @skedulo/memory-hub-mcp setup` first.');
87
+ return 1;
88
+ }
89
+ const planPath = (0, path_1.resolve)(target);
90
+ const plan = readPlan(planPath);
91
+ const client = new client_1.MemoryHubClient({ baseUrl: deps.env.MEMORY_HUB_FUNCTION_URL || deps.functionUrl(), apiToken });
92
+ const { saved, skipped } = await (0, import_apply_1.applyPlan)({ client, embed: deps.embed, savePlan: (next) => writePlan(planPath, next), log: deps.log, reviewPath: reviewPathFor(planPath) }, plan, repoName);
93
+ deps.log(`Saved ${saved} item(s); ${skipped} skipped or already saved.`);
94
+ return 0;
95
+ }
96
+ deps.log(exports.IMPORT_USAGE);
97
+ return 2;
98
+ }
99
+ exports.runImport = runImport;
package/dist/index.js CHANGED
@@ -53,6 +53,7 @@ const TAG_VALUES = [
53
53
  'Infrastructure',
54
54
  'Security',
55
55
  'Messaging',
56
+ 'ProductRules',
56
57
  ];
57
58
  // The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
58
59
  // be set to override this (e.g. pointing at a local `sked function dev` instance).
@@ -130,7 +131,7 @@ server.tool('memory_recall', "Recall this developer's (or their team's) Facts, S
130
131
  const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed }, input);
131
132
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(result) }] };
132
133
  });
133
- 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). 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.", {
134
+ 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.", {
134
135
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
135
136
  uid: zod_1.z.string().min(1).describe('The uid from a memory_recall result.'),
136
137
  }, async (input) => {
@@ -283,7 +284,7 @@ server.tool('memory_whoCanRead', "Preview who can read one Fact/Scenario/Skill/W
283
284
  const result = await (0, teams_1.performWhoCanRead)({ client }, input);
284
285
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
285
286
  });
286
- server.tool('memory_update', "Revise a memory you saved, 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. Only the author can update. When this repeats or corrects something you already saved, use this, not memory_save.", {
287
+ 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.", {
287
288
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
288
289
  uid: zod_1.z.string().min(1),
289
290
  content: zod_1.z.string().min(1).optional().describe('Fact, Skill, Wiki: the full new text, not a patch.'),
@@ -294,6 +295,7 @@ server.tool('memory_update', "Revise a memory you saved, in place, instead of sa
294
295
  links: zod_1.z.array(zod_1.z.string().min(1)).optional().describe('Wiki only: the full new list of target wiki page uids; [] clears. Replaces, not appends.'),
295
296
  factIds: zod_1.z.array(zod_1.z.string().min(1)).optional().describe('Scenario only: the full new list of YOUR fact uids that belong to it; [] unlinks all. Facts that are not yours come back as skippedFactIds.'),
296
297
  source: source_1.sourceSchema.nullable().optional().describe(`${source_1.SOURCE_DESCRIPTION} Pass it after re-checking the item against the repo; null clears the source.`),
298
+ expectedLastModified: zod_1.z.string().min(1).optional().describe('The lastModifiedDate memory_get returned. Required when you are not the author. The update is refused if the item changed since.'),
297
299
  }, async (input) => {
298
300
  const result = await (0, revise_1.performUpdate)({ client, embed: embeddings_1.embed }, input);
299
301
  (0, capture_1.logCapture)({ action: 'updated', type: input.type, uid: result.uid });
@@ -0,0 +1,443 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderReview = exports.convertPack = exports.packBlocks = exports.flagText = exports.MAX_PAGE_CHARS = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const source_1 = require("./source");
8
+ exports.MAX_PAGE_CHARS = 20_000;
9
+ const MAX_TITLE_CHARS = 255;
10
+ const FLAG_PATTERNS = [
11
+ ['uuid', /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi],
12
+ ['email', /\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b/g],
13
+ ['phone', /\+\d{1,3}[\s-]?\(?\d{1,4}\)?[\s-]?\d{3,4}[\s-]?\d{3,4}\b/g],
14
+ ['currency', /[$€£]\s?\d[\d,]*(?:\.\d+)?|\b(?:USD|AUD|NZD|GBP|EUR|CAD)\s?\$?\d[\d,]*(?:\.\d+)?|\b\d[\d,]*(?:\.\d+)?\s?(?:USD|AUD|NZD|GBP|EUR|CAD)\b/g],
15
+ ['salesforce-id', /\b(?=\w*\d\w*\d\w*\d)(?:00[0-9A-Za-z]|a[0-9][0-9A-Za-z])[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?\b/g],
16
+ ];
17
+ const ATTRIBUTED_NAME = /\b(?:[Bb]y|[Pp]er|[Ff]rom|[Aa]sked|[Cc]onfirmed|[Aa]pproved|[Rr]equested|[Ss]aid|[Tt]old|[Cc]ontact|[Cc]c|[Ee]mailed|[Oo]wner:?)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)\b/g;
18
+ const NOT_NAMES = new Set([
19
+ 'Skedulo', 'Salesforce', 'Pulse', 'Horizon', 'Linear', 'Confluence', 'Google', 'Jira', 'Slack', 'Microsoft', 'Zoom',
20
+ 'The', 'This', 'That', 'These', 'Those', 'Each', 'All', 'Any', 'Default', 'Admin', 'Customer', 'Client', 'Product',
21
+ 'Engineering', 'Support', 'Design', 'Scheduler', 'Optimizer', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
22
+ 'Saturday', 'Sunday', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
23
+ 'November', 'December',
24
+ ]);
25
+ function flagText(text) {
26
+ const found = new Map();
27
+ const add = (kind, match) => found.set(`${kind}|${match}`, { kind, match });
28
+ for (const [kind, pattern] of FLAG_PATTERNS) {
29
+ for (const hit of text.matchAll(pattern))
30
+ add(kind, hit[0]);
31
+ }
32
+ for (const hit of text.matchAll(ATTRIBUTED_NAME)) {
33
+ if (!NOT_NAMES.has(hit[1].split(' ')[0]))
34
+ add('person-name', hit[1]);
35
+ }
36
+ return [...found.values()];
37
+ }
38
+ exports.flagText = flagText;
39
+ // A capitalised word used mid-sentence this often is a product term, not someone's name.
40
+ const TERM_MIN_USES = 5;
41
+ function midSentenceCapitals(text) {
42
+ const counts = new Map();
43
+ for (const hit of text.matchAll(/(?<=[a-z,;] )([A-Z][a-z]+)/g))
44
+ counts.set(hit[1], (counts.get(hit[1]) ?? 0) + 1);
45
+ return counts;
46
+ }
47
+ function collectFlags(items) {
48
+ const byValue = new Map();
49
+ for (const [target, text] of items) {
50
+ for (const hit of flagText(text)) {
51
+ const key = `${hit.kind}|${hit.match}`;
52
+ const flag = byValue.get(key) ?? { kind: hit.kind, match: hit.match, targets: [], line: lineOf(text, hit.match) };
53
+ flag.targets.push(target);
54
+ byValue.set(key, flag);
55
+ }
56
+ }
57
+ const capitals = midSentenceCapitals(items.map(([, text]) => text.replace(ATTRIBUTED_NAME, ' ')).join('\n'));
58
+ const flags = [...byValue.values()];
59
+ for (const flag of flags) {
60
+ if (flag.kind === 'person-name' && flag.match.split(' ').every((word) => (capitals.get(word) ?? 0) >= TERM_MIN_USES)) {
61
+ flag.likelyTerm = true;
62
+ }
63
+ }
64
+ return flags.sort((a, b) => Number(Boolean(a.likelyTerm)) - Number(Boolean(b.likelyTerm)));
65
+ }
66
+ function lineOf(text, match) {
67
+ const line = text.split('\n').find((candidate) => candidate.includes(match)) ?? match;
68
+ return line.trim().slice(0, 200);
69
+ }
70
+ function isHeadingOnly(text) {
71
+ const lines = text.trim().split('\n');
72
+ return lines[0] !== '' && lines.every((line) => line.trim() === '' || /^#{1,6} /.test(line));
73
+ }
74
+ function withHeadingsAttached(blocks) {
75
+ const out = [];
76
+ for (const block of blocks) {
77
+ if (out.length && isHeadingOnly(out[out.length - 1]))
78
+ out[out.length - 1] += block;
79
+ else
80
+ out.push(block);
81
+ }
82
+ return out;
83
+ }
84
+ function packBlocks(blocks, max) {
85
+ const pieces = withHeadingsAttached(blocks).flatMap((block) => (block.length <= max ? [block] : splitOversized(block, max)));
86
+ const parts = [];
87
+ let current = '';
88
+ for (const piece of pieces) {
89
+ if (current && current.length + piece.length > max) {
90
+ parts.push(current);
91
+ current = '';
92
+ }
93
+ current += piece;
94
+ }
95
+ if (current || parts.length === 0)
96
+ parts.push(current);
97
+ return parts;
98
+ }
99
+ exports.packBlocks = packBlocks;
100
+ function flagSpans(text) {
101
+ const spans = [];
102
+ for (const pattern of [...FLAG_PATTERNS.map(([, p]) => p), ATTRIBUTED_NAME]) {
103
+ for (const hit of text.matchAll(pattern))
104
+ spans.push([hit.index ?? 0, (hit.index ?? 0) + hit[0].length]);
105
+ }
106
+ return spans;
107
+ }
108
+ // A cut inside a flagged value would hide it from every later flag check, so cuts avoid those spans.
109
+ function splitOversized(block, max) {
110
+ const spans = flagSpans(block);
111
+ const insideFlag = (cut) => spans.some(([start, end]) => start < cut && cut < end);
112
+ const pieces = [];
113
+ let pos = 0;
114
+ while (block.length - pos > max) {
115
+ const window = block.slice(pos, pos + max);
116
+ let cut = 0;
117
+ for (const boundary of [/\n\n/g, /\n/g, /\s/g]) {
118
+ for (const hit of window.matchAll(boundary)) {
119
+ const at = pos + (hit.index ?? 0) + hit[0].length;
120
+ if (at > pos && !insideFlag(at) && !isHeadingOnly(block.slice(pos, at)))
121
+ cut = at;
122
+ }
123
+ if (cut)
124
+ break;
125
+ }
126
+ if (!cut) {
127
+ cut = pos + max;
128
+ if (/[\uD800-\uDBFF]/.test(block[cut - 1]))
129
+ cut--;
130
+ }
131
+ pieces.push(block.slice(pos, cut));
132
+ pos = cut;
133
+ }
134
+ pieces.push(block.slice(pos));
135
+ return pieces;
136
+ }
137
+ function oneLine(value) {
138
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
139
+ }
140
+ function featureKey(raw) {
141
+ return raw.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'general';
142
+ }
143
+ const PREFIXABLE_ID = /^[A-Z]+\d+$/;
144
+ function prefixed(prefix, id) {
145
+ const text = oneLine(id);
146
+ return PREFIXABLE_ID.test(text) ? `${prefix}-${text}` : text;
147
+ }
148
+ // bytes are kept as read so a hash of them matches `shasum -a 256`; the text is normalised for parsing and splitting.
149
+ function readSource(path) {
150
+ const bytes = (0, fs_1.readFileSync)(path);
151
+ return { raw: bytes.toString('utf8').replace(/^/, '').replace(/\r\n/g, '\n'), bytes };
152
+ }
153
+ function parseJson(raw, file) {
154
+ try {
155
+ return JSON.parse(raw);
156
+ }
157
+ catch (error) {
158
+ throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
159
+ }
160
+ }
161
+ function asList(value) {
162
+ if (typeof value === 'string')
163
+ return [value];
164
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
165
+ }
166
+ function walk(dir) {
167
+ return (0, fs_1.readdirSync)(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? walk((0, path_1.join)(dir, entry.name)) : [(0, path_1.join)(dir, entry.name)]);
168
+ }
169
+ const MEMORY_FILE = /^(rules|constraints|api|workflow)(?:-(.+))?\.json$/;
170
+ // Packs keep their JSON at the folder root; older packs kept it under memory/.
171
+ function readMemoryFiles(packDir) {
172
+ return ['', 'memory'].flatMap((sub) => {
173
+ const dir = (0, path_1.join)(packDir, sub);
174
+ return (0, fs_1.existsSync)(dir) ? readMemoryDir(dir, sub ? `${sub}/` : '') : [];
175
+ });
176
+ }
177
+ function readMemoryDir(dir, label) {
178
+ return (0, fs_1.readdirSync)(dir)
179
+ .sort()
180
+ .flatMap((name) => {
181
+ const match = MEMORY_FILE.exec(name);
182
+ if (!match)
183
+ return [];
184
+ const file = `${label}${name}`;
185
+ const { raw, bytes } = readSource((0, path_1.join)(dir, name));
186
+ const data = parseJson(raw, file);
187
+ const area = featureKey(typeof data.area === 'string' ? data.area : (match[2] ?? 'general'));
188
+ return [{ file, raw, bytes, kind: match[1], area, data }];
189
+ });
190
+ }
191
+ function entriesOf(data, key) {
192
+ const value = data[key];
193
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === 'object') : [];
194
+ }
195
+ function ruleLine(prefix, entry, source) {
196
+ const label = oneLine(entry.name ?? entry.category);
197
+ const body = oneLine(entry.description ?? entry.constraint);
198
+ const id = prefixed(prefix, entry.id ?? '(no id)');
199
+ return `- **${id}** · standard · unverified — ${label ? `${label}: ${body}` : body} _Source: ${source}_\n`;
200
+ }
201
+ const HEADINGS = { apis: 'APIs', workflows: 'Workflows', configuration_variables: 'Configuration variables' };
202
+ function renderEntry(prefix, entry) {
203
+ const heading = [entry.id ? prefixed(prefix, entry.id) : '', oneLine(entry.name)].filter(Boolean).join(' · ') || '(unnamed)';
204
+ const out = [`### ${heading}\n`];
205
+ if (entry.description)
206
+ out.push(`\n${oneLine(entry.description)}\n`);
207
+ const rest = Object.entries(entry).filter(([key]) => !['id', 'name', 'description'].includes(key));
208
+ if (rest.length)
209
+ out.push('\n');
210
+ for (const [key, value] of rest) {
211
+ if (Array.isArray(value)) {
212
+ out.push(`- **${key}:**\n`, ...value.map((item) => ` - ${typeof item === 'string' ? oneLine(item) : JSON.stringify(item)}\n`));
213
+ }
214
+ else {
215
+ out.push(`- **${key}:** ${typeof value === 'string' ? oneLine(value) : JSON.stringify(value)}\n`);
216
+ }
217
+ }
218
+ return `${out.join('')}\n`;
219
+ }
220
+ function toPages(id, title, tags, intro, blocks, changeLog) {
221
+ const footer = `\n## Change log\n\n${changeLog}\n`;
222
+ const parts = packBlocks(blocks, exports.MAX_PAGE_CHARS - intro.length - footer.length);
223
+ return parts.map((body, index) => ({
224
+ id: parts.length > 1 ? `${id}-${index + 1}` : id,
225
+ title: parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title,
226
+ tags,
227
+ content: `${intro}${body}${footer}`,
228
+ }));
229
+ }
230
+ function rulesPages(opts, memory, changeLog) {
231
+ const features = [...new Set(memory.filter((m) => m.kind === 'rules' || m.kind === 'constraints').map((m) => m.area))].sort();
232
+ return features.flatMap((feature) => {
233
+ const lines = (kind) => memory
234
+ .filter((m) => m.kind === kind && m.area === feature)
235
+ .flatMap((m) => entriesOf(m.data, kind).map((entry) => ruleLine(opts.prefix, entry, `knowledge pack ${(0, path_1.basename)(opts.packDir)}, ${m.file}`)));
236
+ const rules = lines('rules');
237
+ const constraints = lines('constraints');
238
+ const intro = `Rules and constraints for ${feature}. One per line: ID · tier · status — rule. Tiers: core (change only with the ` +
239
+ "developer's explicit confirmation), standard, detail (a tunable default). Imported entries stay unverified until a developer reviews them.\n";
240
+ const blocks = [
241
+ ...(rules.length ? ['\n## Rules\n\n', ...rules] : []),
242
+ ...(constraints.length ? ['\n## Constraints\n\n', ...constraints] : []),
243
+ ];
244
+ return toPages(`rules-${feature}`, `${opts.product} › Rules › ${feature}`, ['ProductRules'], intro, blocks, changeLog);
245
+ });
246
+ }
247
+ function entryPages(opts, memory, kind, changeLog) {
248
+ const base = kind === 'api' ? 'apis' : 'workflows';
249
+ return memory
250
+ .filter((m) => m.kind === kind)
251
+ .flatMap((m) => {
252
+ const topic = m.area === 'general' ? base : `${base}-${m.area}`;
253
+ const blocks = Object.keys(m.data)
254
+ .filter((key) => entriesOf(m.data, key).length > 0)
255
+ .flatMap((key) => [
256
+ `\n## ${HEADINGS[key] ?? key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' ')}\n\n`,
257
+ ...entriesOf(m.data, key).map((entry) => renderEntry(opts.prefix, entry)),
258
+ ]);
259
+ const intro = `Imported from knowledge pack ${(0, path_1.basename)(opts.packDir)}, ${m.file}.\n`;
260
+ return toPages(`ref-${topic}`, `${opts.product} › Reference › ${topic}`, [], intro, blocks, changeLog);
261
+ });
262
+ }
263
+ function knowledgeDocs(packDir) {
264
+ const root = (0, path_1.join)(packDir, 'knowledge');
265
+ if (!(0, fs_1.existsSync)(root))
266
+ return [];
267
+ return walk(root)
268
+ .map((path) => (0, path_1.relative)(root, path).split(path_1.sep).join('/'))
269
+ // README.md is the refresh log, not knowledge.
270
+ .filter((rel) => rel.endsWith('.md') && rel !== 'README.md')
271
+ .sort()
272
+ .map((rel) => ({
273
+ file: `knowledge/${rel}`,
274
+ ...readSource((0, path_1.join)(root, rel)),
275
+ topic: rel.replace(/\.md$/, '').toLowerCase().replace(/[^a-z0-9/]+/g, '-'),
276
+ }));
277
+ }
278
+ function clarificationFacts(opts) {
279
+ const dir = (0, path_1.join)(opts.packDir, 'docs', 'clarifications');
280
+ const paths = (0, fs_1.existsSync)(dir) ? walk(dir).filter((path) => path.endsWith('-qna.json')).sort() : [];
281
+ const facts = [];
282
+ const files = [];
283
+ for (const path of paths) {
284
+ const file = (0, path_1.relative)(opts.packDir, path).split(path_1.sep).join('/');
285
+ const source = readSource(path);
286
+ files.push({ file, ...source });
287
+ const data = parseJson(source.raw, file);
288
+ const received = new Map();
289
+ for (const batch of data.received ?? [])
290
+ for (const answer of batch.answers ?? [])
291
+ received.set(answer.id, answer);
292
+ for (const question of data.questions ?? []) {
293
+ if (question.status !== 'answered' && question.status !== 'applied')
294
+ continue;
295
+ const inline = question.answer;
296
+ const answer = inline?.text ? inline : received.get(question.id);
297
+ if (!answer?.text)
298
+ continue;
299
+ const refs = [...asList(question.tickets), ...asList(question.applied?.refs)];
300
+ const tickets = [...new Set(refs.filter((ref) => /^[A-Z][A-Z0-9]+-\d+$/.test(ref)))];
301
+ const date = answer.date ?? answer.answer_date;
302
+ // answer.by is a person's name, which the customer-data rules keep out of the hub.
303
+ const content = `${opts.product} clarification ${oneLine(question.id)}${question.topic ? ` (${oneLine(question.topic)})` : ''}: ` +
304
+ `${oneLine(question.question)} Answer${date ? ` (${oneLine(date)})` : ''}: ${oneLine(answer.text)}` +
305
+ `${answer.notes ? ` Notes: ${oneLine(answer.notes)}` : ''}${tickets.length ? ` Tickets: ${tickets.join(', ')}.` : ''}`;
306
+ facts.push({ id: `fact-${oneLine(question.id)}`, content });
307
+ }
308
+ }
309
+ return { facts, files };
310
+ }
311
+ function idWarnings(prefix, memory) {
312
+ const filesById = new Map();
313
+ for (const m of memory) {
314
+ const keys = m.kind === 'rules' || m.kind === 'constraints' ? [m.kind] : Object.keys(m.data);
315
+ for (const entry of keys.flatMap((key) => entriesOf(m.data, key))) {
316
+ const id = oneLine(entry.id);
317
+ if (id)
318
+ filesById.set(id, [...(filesById.get(id) ?? []), m.file]);
319
+ }
320
+ }
321
+ const unprefixed = [...filesById.keys()].filter((id) => !PREFIXABLE_ID.test(id));
322
+ const warnings = unprefixed.length
323
+ ? [`These IDs are not upper-case letters then digits (like R12), so they stay without the ${prefix}- prefix: ${unprefixed.join(', ')}.`]
324
+ : [];
325
+ for (const [id, files] of filesById) {
326
+ if (files.length > 1) {
327
+ warnings.push(`ID ${id} is used ${files.length} times (${[...new Set(files)].join(', ')}), so ${prefixed(prefix, id)} would name more than one entry. Renumber the extras in the plan before applying.`);
328
+ }
329
+ }
330
+ return warnings;
331
+ }
332
+ function packSource(checkout, warnings) {
333
+ if (!checkout)
334
+ return undefined;
335
+ const source = { repo: checkout.repo, commit: checkout.commit };
336
+ if (!source_1.sourceSchema.safeParse(source).success) {
337
+ warnings.push(`The pack's repo ${checkout.repo} is not an owner/name a source can hold, so items carry no source and the Sources page records a hash instead.`);
338
+ return undefined;
339
+ }
340
+ if (checkout.dirty) {
341
+ warnings.push(`${checkout.pathInRepo} has uncommitted changes, so commit ${checkout.commit.slice(0, 7)} does not match what was read. Commit or discard them, then convert again.`);
342
+ }
343
+ return source;
344
+ }
345
+ function convertPack(opts) {
346
+ if (!/^[A-Z][A-Z0-9]*$/.test(opts.prefix)) {
347
+ throw new Error(`prefix must be upper-case letters and digits, e.g. LMB; got: ${opts.prefix}`);
348
+ }
349
+ const pack = (0, path_1.basename)(opts.packDir);
350
+ const changeLog = `- ${opts.today} · ${opts.by} · Imported every entry as unverified · knowledge pack ${pack}`;
351
+ const memory = readMemoryFiles(opts.packDir);
352
+ const docs = knowledgeDocs(opts.packDir);
353
+ const { facts, files: qnaFiles } = clarificationFacts(opts);
354
+ if (memory.length === 0 && docs.length === 0 && facts.length === 0) {
355
+ throw new Error(`${opts.packDir} has no rules, constraints, api or workflow JSON files (or knowledge/ docs or clarification Q&A files) to import`);
356
+ }
357
+ const docPages = docs.flatMap((doc) => toPages(`ref-${doc.topic}`, `${opts.product} › Reference › ${doc.topic}`, [], `Imported from knowledge pack ${pack}, ${doc.file}.\n\n`, doc.raw.split(/(?=^## )/m), changeLog));
358
+ const warnings = idWarnings(opts.prefix, memory);
359
+ const source = packSource(opts.checkout, warnings);
360
+ const hash = (0, crypto_1.createHash)('sha256');
361
+ for (const file of [...memory, ...docs, ...qnaFiles])
362
+ hash.update(file.bytes);
363
+ const sourceLine = source && opts.checkout
364
+ ? `- \`pack\` · ${source.repo} ${opts.checkout.pathInRepo || '.'} · commit ${source.commit.slice(0, 7)} · read ${opts.today}\n`
365
+ : `- \`local\` · ${pack} · sha256 \`${hash.digest('hex')}\` · read ${opts.today}\n`;
366
+ const sourcesPage = toPages('sources', `${opts.product} › Sources`, [], "Every source this product's knowledge was built from, with its version or hash. product-knowledge update re-reads these and compares.\n\n", [sourceLine], changeLog);
367
+ const pages = [
368
+ ...rulesPages(opts, memory, changeLog),
369
+ ...entryPages(opts, memory, 'api', changeLog),
370
+ ...entryPages(opts, memory, 'workflow', changeLog),
371
+ ...docPages,
372
+ ...sourcesPage,
373
+ ];
374
+ const tooLong = pages.filter((page) => page.title.length > MAX_TITLE_CHARS);
375
+ if (tooLong.length) {
376
+ throw new Error(`These titles are over ${MAX_TITLE_CHARS} characters; use a shorter --product: ${tooLong.map((page) => page.title).join(', ')}`);
377
+ }
378
+ const ids = [...pages, ...facts].map((item) => item.id);
379
+ const duplicates = [...new Set(ids.filter((id, index) => ids.indexOf(id) !== index))];
380
+ if (duplicates.length) {
381
+ throw new Error(`These source files map to the same page or fact id, so one would hide the other: ${duplicates.join(', ')}. Rename or merge them first.`);
382
+ }
383
+ const items = [
384
+ ...pages.map((page) => [page.id, `${page.title}\n${page.content}`]),
385
+ ...facts.map((fact) => [fact.id, fact.content]),
386
+ ];
387
+ return {
388
+ version: 1,
389
+ product: opts.product,
390
+ prefix: opts.prefix,
391
+ pack,
392
+ createdAt: opts.today,
393
+ pages,
394
+ facts,
395
+ flags: collectFlags(items),
396
+ ...(source ? { source } : {}),
397
+ ...(warnings.length ? { warnings } : {}),
398
+ };
399
+ }
400
+ exports.convertPack = convertPack;
401
+ function renderReview(plan, planPath) {
402
+ const flagLine = (flag) => `- [ ] ${flag.kind} · \`${flag.match}\` · ${flag.targets.length} place(s): ${flag.targets.slice(0, 5).join(', ')}${flag.targets.length > 5 ? ', …' : ''} — ${flag.line}`;
403
+ const likely = plan.flags.filter((flag) => !flag.likelyTerm).map(flagLine);
404
+ const terms = plan.flags.filter((flag) => flag.likelyTerm).map(flagLine);
405
+ const pageLines = plan.pages.map((page) => {
406
+ const entries = (page.content.match(/^- \*\*/gm) ?? []).length;
407
+ return `- \`${page.id}\` · ${page.title} · ${page.content.length} chars${entries ? ` · ${entries} entries` : ''}${page.tags.length ? ` · tags ${page.tags.join(', ')}` : ''}`;
408
+ });
409
+ const factLines = plan.facts.map((fact) => `- \`${fact.id}\` · ${fact.content.slice(0, 120)}`);
410
+ return [
411
+ `# Import review: ${plan.product} (knowledge pack ${plan.pack})`,
412
+ '',
413
+ `Plan file: ${planPath}. Nothing is saved until \`memory-hub-mcp import apply ${planPath} --repo <owner/name>\`.`,
414
+ '',
415
+ 'An item with no flag is not proven clean: names are only caught after trigger words such as "by" or "approved", ' +
416
+ 'and some name shapes and local phone formats are missed. Read every page for customer data before applying.',
417
+ '',
418
+ ...(plan.warnings?.length ? [`## Warnings (${plan.warnings.length})`, '', ...plan.warnings.map((warning) => `- ${warning}`), ''] : []),
419
+ `## Flags to resolve (${plan.flags.length})`,
420
+ '',
421
+ 'For each value: remove it from the content of every item listed (or set `skip: true` on an item), ' +
422
+ 'or set the flag\'s `resolved` to true to keep it everywhere (Skedulo staff names, values that are not customer data). ' +
423
+ '`apply` refuses while a flagged value is still present and unresolved.',
424
+ '',
425
+ ...(likely.length ? likely : ['None.']),
426
+ '',
427
+ `### Probably product terms (${terms.length})`,
428
+ '',
429
+ 'These match the name pattern but are used as capitalised terms throughout the pack. Check the list, then resolve them together.',
430
+ '',
431
+ ...(terms.length ? terms : ['None.']),
432
+ '',
433
+ `## Pages (${plan.pages.length})`,
434
+ '',
435
+ ...pageLines,
436
+ '',
437
+ `## Facts (${plan.facts.length})`,
438
+ '',
439
+ ...(factLines.length ? factLines : ['None.']),
440
+ '',
441
+ ].join('\n');
442
+ }
443
+ exports.renderReview = renderReview;
package/dist/revise.js CHANGED
@@ -72,7 +72,14 @@ async function performUpdate(deps, input) {
72
72
  embedding = await embed(embeddedText(input.type, merged)).catch(() => undefined);
73
73
  }
74
74
  const { type, uid, repo: _repo, ...changes } = input;
75
- const body = { uid, ...changes, ...(repo !== undefined ? { repo } : {}), ...(embedding ? { embedding } : {}) };
75
+ const body = {
76
+ uid,
77
+ ...changes,
78
+ ...(repo !== undefined ? { repo } : {}),
79
+ ...(embedding ? { embedding } : {}),
80
+ // An unreviewed background run must never rewrite a teammate's item.
81
+ ...((0, capture_1.isCaptureMode)() ? { authorOnly: true } : {}),
82
+ };
76
83
  switch (type) {
77
84
  case 'Fact':
78
85
  return client.updateFact(body);
package/dist/setup.js CHANGED
@@ -297,9 +297,9 @@ function setCapture(settingsPath, on, mode) {
297
297
  }
298
298
  }
299
299
  exports.setCapture = setCapture;
300
- // Under the plugin a copied SKILL.md lists the skill twice. state/ and cli-path stay: the plugin's prompt hook uses them.
301
- function removeCopiedAssets(settingsPath, home = (0, os_1.homedir)()) {
302
- const { hookDir, skillFile } = (0, asset_sync_1.installDirs)(home);
300
+ // Under the plugin a copied skill is listed twice. state/ and cli-path stay: the plugin's prompt hook uses them.
301
+ function removeCopiedAssets(settingsPath, home = (0, os_1.homedir)(), assetsDir = ASSETS) {
302
+ const { hookDir, skillsDir } = (0, asset_sync_1.installDirs)(home);
303
303
  const referenced = JSON.stringify(readJson(settingsPath).hooks || {});
304
304
  // By suffix, so a hook written as ~/... or $HOME/... still protects its copy.
305
305
  const removed = [];
@@ -309,9 +309,11 @@ function removeCopiedAssets(settingsPath, home = (0, os_1.homedir)()) {
309
309
  (0, fs_1.unlinkSync)(path);
310
310
  removed.push(path);
311
311
  };
312
- remove(skillFile);
313
- if ((0, fs_1.existsSync)((0, path_1.dirname)(skillFile)) && (0, fs_1.readdirSync)((0, path_1.dirname)(skillFile)).length === 0)
314
- (0, fs_1.rmdirSync)((0, path_1.dirname)(skillFile));
312
+ for (const name of new Set([asset_sync_1.LEGACY_SKILL, ...(0, asset_sync_1.packagedSkills)(assetsDir), ...(0, asset_sync_1.markedSkills)(skillsDir)])) {
313
+ const srcRoot = (0, path_1.join)(assetsDir, 'skills', name);
314
+ const packaged = (0, fs_1.existsSync)(srcRoot) ? (0, asset_sync_1.filesUnder)(srcRoot).map((src) => (0, path_1.relative)(srcRoot, src)) : [];
315
+ removed.push(...(0, asset_sync_1.removeSkill)(skillsDir, name, packaged));
316
+ }
315
317
  for (const script of asset_sync_1.HOOK_SCRIPTS) {
316
318
  const path = (0, path_1.join)(hookDir, script);
317
319
  if (!referenced.includes(`memory-hub-hook/${script}`))
@@ -341,15 +343,14 @@ function registerPromptHook(path, hookPath) {
341
343
  }
342
344
  exports.registerPromptHook = registerPromptHook;
343
345
  function installAssets() {
344
- const { hookDir, skillFile } = (0, asset_sync_1.installDirs)();
346
+ const { hookDir, skillsDir } = (0, asset_sync_1.installDirs)();
345
347
  (0, fs_1.mkdirSync)(hookDir, { recursive: true });
346
- (0, fs_1.mkdirSync)((0, path_1.dirname)(skillFile), { recursive: true });
347
348
  for (const name of ['session-start.sh', 'session-stop.sh', 'user-prompt-submit.sh']) {
348
349
  const dest = (0, path_1.join)(hookDir, name);
349
350
  (0, fs_1.copyFileSync)((0, path_1.join)(ASSETS, name), dest);
350
351
  (0, fs_1.chmodSync)(dest, 0o755);
351
352
  }
352
- (0, fs_1.copyFileSync)((0, path_1.join)(ASSETS, 'SKILL.md'), skillFile);
353
+ (0, asset_sync_1.copySkills)(ASSETS, skillsDir, (line) => console.log(` ${line}`));
353
354
  (0, asset_sync_1.recordInstall)(hookDir, (0, asset_sync_1.packageVersion)(), (0, path_1.join)(__dirname, 'cli.js'));
354
355
  return { hookPath: (0, path_1.join)(hookDir, 'session-start.sh'), promptHookPath: (0, path_1.join)(hookDir, 'user-prompt-submit.sh') };
355
356
  }
@@ -575,7 +576,7 @@ async function runSetup(argv = []) {
575
576
  console.log(` SessionStart hook -> ${hookPath}${note}`);
576
577
  const prompt = registerPromptHook((0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json'), promptHookPath);
577
578
  console.log(` UserPromptSubmit hook -> ${promptHookPath}${prompt.already ? ' (already registered)' : ''}`);
578
- console.log(' skill -> ~/.claude/skills/se-ai-memory-hub/SKILL.md');
579
+ console.log(` skills -> ~/.claude/skills/ (${(0, asset_sync_1.packagedSkills)(ASSETS).join(', ')})`);
579
580
  }
580
581
  if (hosts.includes('code')) {
581
582
  warnHookTools();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "MCP server for the SE AI Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {