@skedulo/memory-hub-mcp 0.2.13 → 0.2.14
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/README.md +36 -4
- package/dist/asset-sync.js +158 -6
- package/dist/cli.js +29 -0
- package/dist/git-remote.js +19 -1
- package/dist/import-apply.js +88 -0
- package/dist/import-cli.js +99 -0
- package/dist/index.js +4 -2
- package/dist/pack-import.js +443 -0
- package/dist/revise.js +8 -1
- package/dist/setup.js +11 -10
- package/package.json +1 -1
- package/skill-guide.md +26 -6
- /package/assets/{SKILL.md → skills/se-ai-memory-hub/SKILL.md} +0 -0
package/README.md
CHANGED
|
@@ -79,7 +79,7 @@ mints a personal token from that session. For **Claude Code** it does everything
|
|
|
79
79
|
`scripts/setup-dev.sh` does for contributors: registers the MCP server in `~/.claude.json`, puts
|
|
80
80
|
the token in `~/.claude/settings.json`, installs the `SessionStart` hook into
|
|
81
81
|
`~/.claude/memory-hub-hook/` and registers it (appending, never stacking duplicates), and syncs
|
|
82
|
-
|
|
82
|
+
every skill folder into `~/.claude/skills/`. For **Claude Desktop** it writes
|
|
83
83
|
`claude_desktop_config.json` — no hook, because Desktop has none. Every file is merged, never
|
|
84
84
|
clobbered, and a `.bak` is left behind. Then it makes one real call to confirm the token works
|
|
85
85
|
before it says done.
|
|
@@ -97,8 +97,8 @@ Re-run `memory-hub-mcp setup` anytime — it keeps a token that's already config
|
|
|
97
97
|
### Updates
|
|
98
98
|
|
|
99
99
|
`setup` registers the server as `npx -y @skedulo/memory-hub-mcp@latest`, so every Claude start runs
|
|
100
|
-
the newest published version. On start, that server brings the hooks and
|
|
101
|
-
copied into `~/.claude` up to its own version (never down), so nobody re-runs anything after a
|
|
100
|
+
the newest published version. On start, that server brings the hooks and skills that `setup`
|
|
101
|
+
copied into `~/.claude` up to its own version (never down), adding any skill a release introduced, so nobody re-runs anything after a
|
|
102
102
|
release. Two exceptions: a release that adds a new kind of hook still needs `memory-hub-mcp setup`
|
|
103
103
|
once, and `setup --no-auto-update` pins the installed binary instead (update it with
|
|
104
104
|
`npm i -g @skedulo/memory-hub-mcp`, then re-run `setup`).
|
|
@@ -163,6 +163,38 @@ design, discovery). `memory_checkRepoStatus` will not work from Desktop. `memory
|
|
|
163
163
|
does, but only if you name the repo — pass `repoName` explicitly, since there is nothing to
|
|
164
164
|
detect; `memory_listTeams` shows the team names to link it to.
|
|
165
165
|
|
|
166
|
+
## Importing product knowledge
|
|
167
|
+
|
|
168
|
+
`memory-hub-mcp import` copies a knowledge pack into the hub as product knowledge pages. A pack is
|
|
169
|
+
one folder per core or project team, `domains/<name>/` in the shared memory repo, holding
|
|
170
|
+
`rules.json`, `constraints.json`, `api.json` and `workflow.json`, each optionally split into
|
|
171
|
+
`<kind>-<area>.json` shards. The product-knowledge skill runs the import and walks you through the
|
|
172
|
+
review; it has two steps, and only the second saves anything:
|
|
173
|
+
|
|
174
|
+
npx -y @skedulo/memory-hub-mcp@latest import convert <shared-memory-repo>/domains/<name> --product "<Product>" --prefix <PREFIX> --by "<your name>"
|
|
175
|
+
npx -y @skedulo/memory-hub-mcp@latest import apply <plan.json> --repo <owner/name>
|
|
176
|
+
|
|
177
|
+
`convert` writes a plan (JSON) and a review file (Markdown) that lists every value that looks like
|
|
178
|
+
customer data, both readable only by you; it will not overwrite a plan that already records saved
|
|
179
|
+
items unless you pass `--force`. It also warns about IDs it cannot prefix, IDs used twice, and
|
|
180
|
+
uncommitted changes in the pack. When the pack is in a git checkout, the Sources page records the
|
|
181
|
+
repo, the pack's path and the HEAD commit, and every saved item carries that repo and commit as its
|
|
182
|
+
`source`, so `memory_checkSources` run in a checkout of the shared memory repo shows when the pack
|
|
183
|
+
has moved on.
|
|
184
|
+
|
|
185
|
+
`apply` refuses until each flagged value is removed or marked `resolved`, and refuses a repo that
|
|
186
|
+
already has pages titled `<Product> ›` that this plan did not save, so a lost plan file cannot
|
|
187
|
+
cause a second import. It saves every page as Team on the repo with an embedding, and records each
|
|
188
|
+
saved uid in the plan, so running it again resumes. Packs in the older layout (JSON under
|
|
189
|
+
`memory/`, with `knowledge/` docs and clarification Q&A files) still convert; their clarifications
|
|
190
|
+
become facts that keep their ticket IDs in the text but link no hub task, so old tickets do not
|
|
191
|
+
appear as Open tasks. `apply` reads `MEMORY_HUB_MCP_TOKEN` and `MEMORY_HUB_FUNCTION_URL` from the
|
|
192
|
+
environment, as the hooks do.
|
|
193
|
+
|
|
194
|
+
After the import, the hub copy is the one developers edit. When the pack repo moves on,
|
|
195
|
+
product-knowledge update converts the pack again and proposes the differences through the usual
|
|
196
|
+
confirmed edits.
|
|
197
|
+
|
|
166
198
|
## Tags
|
|
167
199
|
|
|
168
200
|
`memory_save`/`memory_recall`'s `tags` parameter is a fixed picklist
|
|
@@ -170,7 +202,7 @@ matching the `AgentFacts`/`AgentSkills`/`AgentWikiPages` custom objects' `Tags`
|
|
|
170
202
|
`ConnectedFunction`, `HorizonComponent`, `TriggeredAction`, `ObjectModel`, `MobileExtension`,
|
|
171
203
|
`Deployment`, `Auth`, `Testing`, `BreezeUI`, `PSS`, `PSF`, `Optimization`, `Webhooks`, `Salesforce`,
|
|
172
204
|
`Other`, `ArchitectureMap`, `SOW`, `TDD`, `AI`, `API`, `Mobile`, `Infrastructure`, `Security`,
|
|
173
|
-
`Messaging` (
|
|
205
|
+
`Messaging`, `ProductRules` (25 in all; `TAG_VALUES` in `src/index.ts` is the source of truth). The tool's Zod schema enforces this — any other value fails validation
|
|
174
206
|
before the request reaches the connected function (which otherwise 400s with no indication of
|
|
175
207
|
what went wrong). If the underlying Picklist's `allowedValues` ever changes, update `TAG_VALUES`
|
|
176
208
|
in `src/index.ts` to match.
|
package/dist/asset-sync.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.refreshInstalledAssets = exports.syncInstalledAssets = exports.recordInstall = exports.recordCliPath = exports.compareVersions = exports.packageVersion = exports.installDirs = exports.CLI_PATH_FILE = exports.VERSION_FILE = exports.HOOK_SCRIPTS = void 0;
|
|
3
|
+
exports.refreshInstalledAssets = exports.syncInstalledAssets = exports.recordInstall = exports.recordCliPath = exports.compareVersions = exports.packageVersion = exports.copySkills = exports.ownsSkillDir = exports.removeSkill = exports.markedSkills = exports.listedSkillFiles = exports.packagedSkills = exports.filesUnder = exports.installDirs = exports.LEGACY_SKILL = exports.SKILL_MARKER = exports.CLI_PATH_FILE = exports.VERSION_FILE = exports.HOOK_SCRIPTS = void 0;
|
|
4
4
|
const fs_1 = require("fs");
|
|
5
5
|
const os_1 = require("os");
|
|
6
6
|
const path_1 = require("path");
|
|
@@ -8,13 +8,162 @@ exports.HOOK_SCRIPTS = ['session-start.sh', 'session-stop.sh', 'user-prompt-subm
|
|
|
8
8
|
exports.VERSION_FILE = '.installed-version';
|
|
9
9
|
// The prompt hook runs `embed` from this path, i.e. the build the host last launched.
|
|
10
10
|
exports.CLI_PATH_FILE = 'cli-path';
|
|
11
|
+
exports.SKILL_MARKER = '.memory-hub';
|
|
12
|
+
// Copied by setup before the marker existed, so it is ours without one.
|
|
13
|
+
exports.LEGACY_SKILL = 'se-ai-memory-hub';
|
|
11
14
|
function installDirs(home = (0, os_1.homedir)()) {
|
|
12
15
|
return {
|
|
13
16
|
hookDir: (0, path_1.join)(home, '.claude', 'memory-hub-hook'),
|
|
14
|
-
|
|
17
|
+
skillsDir: (0, path_1.join)(home, '.claude', 'skills'),
|
|
15
18
|
};
|
|
16
19
|
}
|
|
17
20
|
exports.installDirs = installDirs;
|
|
21
|
+
function filesUnder(dir) {
|
|
22
|
+
return (0, fs_1.readdirSync)(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? filesUnder((0, path_1.join)(dir, entry.name)) : [(0, path_1.join)(dir, entry.name)]);
|
|
23
|
+
}
|
|
24
|
+
exports.filesUnder = filesUnder;
|
|
25
|
+
function packagedSkills(assetsDir) {
|
|
26
|
+
const root = (0, path_1.join)(assetsDir, 'skills');
|
|
27
|
+
if (!(0, fs_1.existsSync)(root))
|
|
28
|
+
return [];
|
|
29
|
+
return (0, fs_1.readdirSync)(root, { withFileTypes: true })
|
|
30
|
+
.filter((entry) => entry.isDirectory())
|
|
31
|
+
.map((entry) => entry.name)
|
|
32
|
+
.sort();
|
|
33
|
+
}
|
|
34
|
+
exports.packagedSkills = packagedSkills;
|
|
35
|
+
function entryAt(path) {
|
|
36
|
+
try {
|
|
37
|
+
return (0, fs_1.lstatSync)(path);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// A symlinked folder or marker is never ours, so nothing is copied into or deleted through it.
|
|
44
|
+
function isMarked(dir) {
|
|
45
|
+
return !!entryAt(dir)?.isDirectory() && !!entryAt((0, path_1.join)(dir, exports.SKILL_MARKER))?.isFile();
|
|
46
|
+
}
|
|
47
|
+
function isLegacyCopy(dir) {
|
|
48
|
+
return (0, path_1.basename)(dir) === exports.LEGACY_SKILL && !!entryAt(dir)?.isDirectory() && !entryAt((0, path_1.join)(dir, exports.SKILL_MARKER));
|
|
49
|
+
}
|
|
50
|
+
// The marker lists the files setup copied, so a later release can delete the ones it no longer ships.
|
|
51
|
+
function listedSkillFiles(dir) {
|
|
52
|
+
if (!isMarked(dir))
|
|
53
|
+
return [];
|
|
54
|
+
return (0, fs_1.readFileSync)((0, path_1.join)(dir, exports.SKILL_MARKER), 'utf8')
|
|
55
|
+
.split('\n')
|
|
56
|
+
.map((line) => line.trim())
|
|
57
|
+
.filter((line) => line && line !== exports.SKILL_MARKER && !(0, path_1.isAbsolute)(line) && !line.split(/[\\/]/).includes('..'));
|
|
58
|
+
}
|
|
59
|
+
exports.listedSkillFiles = listedSkillFiles;
|
|
60
|
+
function writeSkillMarker(dir, files) {
|
|
61
|
+
(0, fs_1.writeFileSync)((0, path_1.join)(dir, exports.SKILL_MARKER), [...new Set(files)].sort().map((file) => `${file}\n`).join(''));
|
|
62
|
+
}
|
|
63
|
+
function skillFiles(srcRoot) {
|
|
64
|
+
return filesUnder(srcRoot).map((src) => (0, path_1.relative)(srcRoot, src).split(path_1.sep).join('/')).sort();
|
|
65
|
+
}
|
|
66
|
+
function markedSkills(skillsDir) {
|
|
67
|
+
if (!(0, fs_1.existsSync)(skillsDir))
|
|
68
|
+
return [];
|
|
69
|
+
return (0, fs_1.readdirSync)(skillsDir, { withFileTypes: true })
|
|
70
|
+
.filter((entry) => entry.isDirectory() && isMarked((0, path_1.join)(skillsDir, entry.name)))
|
|
71
|
+
.map((entry) => entry.name)
|
|
72
|
+
.sort();
|
|
73
|
+
}
|
|
74
|
+
exports.markedSkills = markedSkills;
|
|
75
|
+
// A symlinked subfolder would resolve elsewhere, so the file's folder must resolve to where its path reads.
|
|
76
|
+
function isOwnFile(dir, realDir, path) {
|
|
77
|
+
const folder = (0, path_1.relative)(dir, (0, path_1.dirname)(path));
|
|
78
|
+
if (folder === '..' || folder.startsWith(`..${path_1.sep}`) || (0, path_1.isAbsolute)(folder) || !entryAt(path)?.isFile())
|
|
79
|
+
return false;
|
|
80
|
+
try {
|
|
81
|
+
return (0, fs_1.realpathSync)((0, path_1.dirname)(path)) === (0, path_1.join)(realDir, folder);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Only the folders a removed file leaves empty, so an empty folder the developer made stays.
|
|
88
|
+
function removeEmptyParents(dir, path) {
|
|
89
|
+
for (let parent = (0, path_1.dirname)(path); parent !== dir && (0, fs_1.readdirSync)(parent).length === 0; parent = (0, path_1.dirname)(parent)) {
|
|
90
|
+
(0, fs_1.rmdirSync)(parent);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function removeFiles(dir, files) {
|
|
94
|
+
const realDir = (0, fs_1.realpathSync)(dir);
|
|
95
|
+
const removed = [];
|
|
96
|
+
for (const file of files) {
|
|
97
|
+
const path = (0, path_1.join)(dir, file);
|
|
98
|
+
if (!isOwnFile(dir, realDir, path))
|
|
99
|
+
continue;
|
|
100
|
+
(0, fs_1.unlinkSync)(path);
|
|
101
|
+
removed.push(path);
|
|
102
|
+
removeEmptyParents(dir, path);
|
|
103
|
+
}
|
|
104
|
+
return removed;
|
|
105
|
+
}
|
|
106
|
+
// Deletes only what the marker lists (plus `extra`), so a file the developer added keeps the folder.
|
|
107
|
+
function removeSkill(skillsDir, name, extra = []) {
|
|
108
|
+
const dir = (0, path_1.join)(skillsDir, name);
|
|
109
|
+
const legacy = isLegacyCopy(dir);
|
|
110
|
+
if (!legacy && !isMarked(dir))
|
|
111
|
+
return [];
|
|
112
|
+
const files = legacy ? ['SKILL.md'] : [...listedSkillFiles(dir), ...extra, exports.SKILL_MARKER];
|
|
113
|
+
const removed = removeFiles(dir, [...new Set(files)]);
|
|
114
|
+
if ((0, fs_1.readdirSync)(dir).length === 0)
|
|
115
|
+
(0, fs_1.rmdirSync)(dir);
|
|
116
|
+
return removed;
|
|
117
|
+
}
|
|
118
|
+
exports.removeSkill = removeSkill;
|
|
119
|
+
function ownsSkillDir(skillsDir, name) {
|
|
120
|
+
const dir = (0, path_1.join)(skillsDir, name);
|
|
121
|
+
return !entryAt(dir) || isMarked(dir) || isLegacyCopy(dir);
|
|
122
|
+
}
|
|
123
|
+
exports.ownsSkillDir = ownsSkillDir;
|
|
124
|
+
function copySkills(assetsDir, skillsDir, log = () => { }) {
|
|
125
|
+
const changed = [];
|
|
126
|
+
const packaged = packagedSkills(assetsDir);
|
|
127
|
+
for (const name of packaged) {
|
|
128
|
+
const srcRoot = (0, path_1.join)(assetsDir, 'skills', name);
|
|
129
|
+
const destRoot = (0, path_1.join)(skillsDir, name);
|
|
130
|
+
if (!ownsSkillDir(skillsDir, name)) {
|
|
131
|
+
log(`memory-hub-mcp: left ${destRoot} alone: memory-hub did not install it`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const files = skillFiles(srcRoot);
|
|
135
|
+
const listed = listedSkillFiles(destRoot);
|
|
136
|
+
// Marked first, listing old and new files, so an interrupted copy is finished and pruned by the next run.
|
|
137
|
+
(0, fs_1.mkdirSync)(destRoot, { recursive: true });
|
|
138
|
+
writeSkillMarker(destRoot, [...listed, ...files]);
|
|
139
|
+
// Before copying: on a case-insensitive disk, Foo.md renamed to foo.md is one file and would be deleted.
|
|
140
|
+
changed.push(...removeFiles(destRoot, listed.filter((file) => !files.includes(file))));
|
|
141
|
+
for (const file of files) {
|
|
142
|
+
const src = (0, path_1.join)(srcRoot, file);
|
|
143
|
+
const dest = (0, path_1.join)(destRoot, file);
|
|
144
|
+
if ((0, fs_1.existsSync)(dest) && (0, fs_1.readFileSync)(src).equals((0, fs_1.readFileSync)(dest)))
|
|
145
|
+
continue;
|
|
146
|
+
(0, fs_1.mkdirSync)((0, path_1.dirname)(dest), { recursive: true });
|
|
147
|
+
(0, fs_1.copyFileSync)(src, dest);
|
|
148
|
+
changed.push(dest);
|
|
149
|
+
}
|
|
150
|
+
writeSkillMarker(destRoot, files);
|
|
151
|
+
}
|
|
152
|
+
for (const name of new Set([exports.LEGACY_SKILL, ...markedSkills(skillsDir)])) {
|
|
153
|
+
if (packaged.includes(name))
|
|
154
|
+
continue;
|
|
155
|
+
const removed = removeSkill(skillsDir, name);
|
|
156
|
+
if (removed.length > 0)
|
|
157
|
+
log(`memory-hub-mcp: removed ${(0, path_1.join)(skillsDir, name)}: the package no longer ships it`);
|
|
158
|
+
changed.push(...removed);
|
|
159
|
+
}
|
|
160
|
+
return changed;
|
|
161
|
+
}
|
|
162
|
+
exports.copySkills = copySkills;
|
|
163
|
+
// setup --plugin removes the copied skills but can keep a hook script, so hooks alone do not mean skills are wanted.
|
|
164
|
+
function hasCopiedSkills(skillsDir) {
|
|
165
|
+
return ((0, fs_1.existsSync)((0, path_1.join)(skillsDir, exports.LEGACY_SKILL, 'SKILL.md')) || markedSkills(skillsDir).length > 0);
|
|
166
|
+
}
|
|
18
167
|
function packageVersion(distDir = __dirname) {
|
|
19
168
|
return JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(distDir, '..', 'package.json'), 'utf8')).version;
|
|
20
169
|
}
|
|
@@ -55,9 +204,8 @@ function syncInstalledAssets(options) {
|
|
|
55
204
|
const previous = (0, fs_1.existsSync)(marker) ? (0, fs_1.readFileSync)(marker, 'utf8').trim() : '';
|
|
56
205
|
if (previous && compareVersions(options.version, previous) < 0)
|
|
57
206
|
return { updated: [], skipped: 'newer-installed' };
|
|
58
|
-
const files = [...hooks, { src: (0, path_1.join)(options.assetsDir, 'SKILL.md'), dest: options.skillFile, executable: false }];
|
|
59
207
|
const updated = [];
|
|
60
|
-
for (const file of
|
|
208
|
+
for (const file of hooks) {
|
|
61
209
|
if (!(0, fs_1.existsSync)(file.src) || !(0, fs_1.existsSync)(file.dest))
|
|
62
210
|
continue;
|
|
63
211
|
if ((0, fs_1.readFileSync)(file.src).equals((0, fs_1.readFileSync)(file.dest)))
|
|
@@ -67,6 +215,10 @@ function syncInstalledAssets(options) {
|
|
|
67
215
|
(0, fs_1.chmodSync)(file.dest, 0o755);
|
|
68
216
|
updated.push(file.dest);
|
|
69
217
|
}
|
|
218
|
+
// Unlike a hook script, a skill the package added since setup is installed: it needs no registration to work.
|
|
219
|
+
if (hasCopiedSkills(options.skillsDir)) {
|
|
220
|
+
updated.push(...copySkills(options.assetsDir, options.skillsDir, options.log));
|
|
221
|
+
}
|
|
70
222
|
recordInstall(options.hookDir, options.version, options.cliPath);
|
|
71
223
|
return { updated };
|
|
72
224
|
}
|
|
@@ -77,9 +229,9 @@ function refreshInstalledAssets({ distDir = __dirname, home = (0, os_1.homedir)(
|
|
|
77
229
|
return undefined;
|
|
78
230
|
try {
|
|
79
231
|
const version = packageVersion(distDir);
|
|
80
|
-
const { hookDir,
|
|
232
|
+
const { hookDir, skillsDir } = installDirs(home);
|
|
81
233
|
const cliPath = (0, path_1.join)(distDir, 'cli.js');
|
|
82
|
-
const result = syncInstalledAssets({ assetsDir: (0, path_1.join)(distDir, '..', 'assets'), hookDir,
|
|
234
|
+
const result = syncInstalledAssets({ assetsDir: (0, path_1.join)(distDir, '..', 'assets'), hookDir, skillsDir, version, cliPath, log });
|
|
83
235
|
// A plugin install has no copied hooks, but its prompt hook still needs this to embed.
|
|
84
236
|
if (result.skipped === 'not-installed')
|
|
85
237
|
recordCliPath(hookDir, cliPath);
|
package/dist/cli.js
CHANGED
|
@@ -33,6 +33,28 @@ else if (command === 'embed') {
|
|
|
33
33
|
}
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
|
+
else if (command === 'import') {
|
|
37
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
38
|
+
const { runImport } = require('./import-cli');
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
40
|
+
const { embed } = require('./embeddings');
|
|
41
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
42
|
+
const { functionUrl } = require('./setup');
|
|
43
|
+
runImport(process.argv.slice(3), {
|
|
44
|
+
env: process.env,
|
|
45
|
+
log: (line) => console.log(line),
|
|
46
|
+
today: () => new Date().toISOString().slice(0, 10),
|
|
47
|
+
embed,
|
|
48
|
+
functionUrl,
|
|
49
|
+
}).then(
|
|
50
|
+
// Exit code, not process.exit: onnxruntime aborts if the process exits with its model session open.
|
|
51
|
+
(code) => {
|
|
52
|
+
process.exitCode = code;
|
|
53
|
+
}, (error) => {
|
|
54
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
55
|
+
process.exitCode = 1;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
36
58
|
else if (command === '--help' || command === '-h') {
|
|
37
59
|
console.log(`memory-hub-mcp — MCP server for the SE AI Memory Hub
|
|
38
60
|
|
|
@@ -49,6 +71,13 @@ else if (command === '--help' || command === '-h') {
|
|
|
49
71
|
end, a background Claude run, using your Claude usage, saves what
|
|
50
72
|
the session learned (new memories Private, updates keep their
|
|
51
73
|
visibility). setup also asks.
|
|
74
|
+
memory-hub-mcp import convert <packDir> --product <name> --prefix <PREFIX> [--by <name>] [--out <plan.json>] [--force]
|
|
75
|
+
turn a knowledge pack folder (domains/<name> in the shared memory
|
|
76
|
+
repo) into a plan of product knowledge pages, plus a review file
|
|
77
|
+
listing values that look like customer data. Saves nothing.
|
|
78
|
+
memory-hub-mcp import apply <plan.json> --repo <owner/name>
|
|
79
|
+
save a reviewed plan to the hub as Team items on that repo, with
|
|
80
|
+
embeddings. Re-running resumes where it stopped.
|
|
52
81
|
memory-hub-mcp embed print the embedding of the text on stdin (or the arguments) as JSON;
|
|
53
82
|
used by the UserPromptSubmit hook. Exits non-zero if it cannot.
|
|
54
83
|
memory-hub-mcp run the MCP server on stdio (how a host launches it)
|
package/dist/git-remote.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.detectRepoName = exports.canonicalizeRemoteUrl = void 0;
|
|
3
|
+
exports.packCheckout = exports.detectRepoName = exports.canonicalizeRemoteUrl = void 0;
|
|
4
4
|
// memory-hub-mcp/src/git-remote.ts
|
|
5
5
|
const child_process_1 = require("child_process");
|
|
6
|
+
const fs_1 = require("fs");
|
|
7
|
+
const path_1 = require("path");
|
|
6
8
|
/**
|
|
7
9
|
* Normalize a git remote URL to the canonical `owner/name` form, per the
|
|
8
10
|
* repo/team grouping spec §3. The host is deliberately dropped — this project
|
|
@@ -60,3 +62,19 @@ function detectRepoName(cwd = process.cwd()) {
|
|
|
60
62
|
return remoteUrl ? canonicalizeRemoteUrl(remoteUrl) : null;
|
|
61
63
|
}
|
|
62
64
|
exports.detectRepoName = detectRepoName;
|
|
65
|
+
function packCheckout(dir) {
|
|
66
|
+
const root = runGit(['rev-parse', '--show-toplevel'], dir);
|
|
67
|
+
const commit = runGit(['rev-parse', 'HEAD'], dir);
|
|
68
|
+
const repo = detectRepoName(dir);
|
|
69
|
+
if (!root || !commit || !repo) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
repo,
|
|
74
|
+
commit,
|
|
75
|
+
// git prints the real path, so a symlinked temp or home folder must be resolved before comparing.
|
|
76
|
+
pathInRepo: (0, path_1.relative)((0, fs_1.realpathSync)(root), (0, fs_1.realpathSync)(dir)).split(path_1.sep).join('/'),
|
|
77
|
+
dirty: runGit(['status', '--porcelain', '--', '.'], dir) !== null,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
exports.packCheckout = packCheckout;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.applyPlan = exports.unresolvedFlags = void 0;
|
|
4
|
+
const pack_import_1 = require("./pack-import");
|
|
5
|
+
const save_1 = require("./save");
|
|
6
|
+
function unresolvedFlags(plan) {
|
|
7
|
+
const kept = new Set(plan.flags.filter((flag) => flag.resolved).map((flag) => `${flag.kind}|${flag.match}`));
|
|
8
|
+
const items = [
|
|
9
|
+
...plan.pages.map((page) => ({ ...page, text: `${page.title}\n${page.content}` })),
|
|
10
|
+
...plan.facts.map((fact) => ({ ...fact, text: fact.content })),
|
|
11
|
+
];
|
|
12
|
+
return items
|
|
13
|
+
.filter((item) => !item.skip && !item.savedUid)
|
|
14
|
+
.flatMap((item) => (0, pack_import_1.flagText)(item.text)
|
|
15
|
+
.filter((flag) => !kept.has(`${flag.kind}|${flag.match}`))
|
|
16
|
+
.map((flag) => ({ target: item.id, ...flag })));
|
|
17
|
+
}
|
|
18
|
+
exports.unresolvedFlags = unresolvedFlags;
|
|
19
|
+
async function listWikiPages(client, repo, titlePrefix) {
|
|
20
|
+
const items = [];
|
|
21
|
+
for (;;) {
|
|
22
|
+
const page = await client.listResources({ type: 'Wiki', repo, titlePrefix, offset: items.length, limit: 200 });
|
|
23
|
+
items.push(...page.items);
|
|
24
|
+
if (page.items.length === 0 || items.length >= page.total)
|
|
25
|
+
return items;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
// One item per request, in sequence: the function allows 5 concurrent invocations of 12 s each.
|
|
29
|
+
async function applyPlan(deps, plan, repoName) {
|
|
30
|
+
const open = unresolvedFlags(plan);
|
|
31
|
+
if (open.length) {
|
|
32
|
+
const places = [...new Set(open.map((flag) => `${flag.target} ${flag.kind}`))];
|
|
33
|
+
throw new Error(`Nothing saved: ${open.length} flagged value(s) are unresolved: ${places.slice(0, 10).join('; ')}${places.length > 10 ? '; …' : ''}. ` +
|
|
34
|
+
`${deps.reviewPath} lists each value; resolve them in the plan file first.`);
|
|
35
|
+
}
|
|
36
|
+
const repo = await deps.client.resolveRepo({ name: repoName });
|
|
37
|
+
if (!repo.uid || !('devTeamId' in repo) || !repo.devTeamId) {
|
|
38
|
+
throw new Error(`Nothing saved: ${repoName} is not linked to a team. Link it to the product's team (memory_linkRepoTeam) first.`);
|
|
39
|
+
}
|
|
40
|
+
const repoUid = repo.uid;
|
|
41
|
+
const titlePrefix = `${plan.product} ›`;
|
|
42
|
+
const savedByPlan = new Set(plan.pages.map((page) => page.savedUid));
|
|
43
|
+
const foreign = (await listWikiPages(deps.client, repoUid, titlePrefix)).filter((page) => !savedByPlan.has(page.uid));
|
|
44
|
+
if (foreign.length) {
|
|
45
|
+
const sample = foreign.slice(0, 3).map((page) => `${page.title} (${page.uid})`);
|
|
46
|
+
throw new Error(`Nothing saved: ${repoName} already has ${foreign.length} Wiki page(s) titled "${titlePrefix}" that this plan did not save, e.g. ${sample.join('; ')}. ` +
|
|
47
|
+
'Resume an earlier import with its own plan file. If that plan is lost, delete those pages or use another --product before importing again.');
|
|
48
|
+
}
|
|
49
|
+
// resolve-task does not say whether it created the task, so an import links none rather than open one per historic ticket.
|
|
50
|
+
const resolveTaskUid = () => Promise.reject(new Error('An import never links a task; the ticket IDs stay in the fact text.'));
|
|
51
|
+
// performSave saves without an embedding when embedding fails; an imported page must stay searchable, so stop instead.
|
|
52
|
+
const save = async (id, embedText, input) => {
|
|
53
|
+
const embedding = await deps.embed(embedText).catch((err) => {
|
|
54
|
+
throw new Error(`Stopped before ${id}: the embedding model did not load (${err instanceof Error ? err.message : String(err)}), and imported pages must be searchable. Items already saved are recorded in the plan; re-run to resume.`);
|
|
55
|
+
});
|
|
56
|
+
const result = await (0, save_1.performSave)({ client: deps.client, embed: async () => embedding, currentRepoUid: async () => repoUid, resolveTaskUid }, input);
|
|
57
|
+
const similar = result.similar?.length ? result.similar : result.possibleDuplicate ? [result.possibleDuplicate] : [];
|
|
58
|
+
if (similar.length)
|
|
59
|
+
deps.log(` ${result.uid} resembles ${similar.map((match) => match.uid).join(', ')}; check for a duplicate`);
|
|
60
|
+
return result;
|
|
61
|
+
};
|
|
62
|
+
let saved = 0;
|
|
63
|
+
let skipped = 0;
|
|
64
|
+
for (const page of plan.pages) {
|
|
65
|
+
if (page.skip || page.savedUid) {
|
|
66
|
+
skipped++;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const result = await save(page.id, `${page.title}\n\n${page.content}`, { type: 'Wiki', title: page.title, content: page.content, tags: page.tags, repo: repoUid, visibility: 'Team', source: plan.source });
|
|
70
|
+
page.savedUid = result.uid;
|
|
71
|
+
deps.savePlan(plan);
|
|
72
|
+
deps.log(`saved ${page.title} -> ${result.uid}`);
|
|
73
|
+
saved++;
|
|
74
|
+
}
|
|
75
|
+
for (const fact of plan.facts) {
|
|
76
|
+
if (fact.skip || fact.savedUid) {
|
|
77
|
+
skipped++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const result = await save(fact.id, fact.content, { type: 'Fact', content: fact.content, repo: repoUid, visibility: 'Team', source: plan.source });
|
|
81
|
+
fact.savedUid = result.uid;
|
|
82
|
+
deps.savePlan(plan);
|
|
83
|
+
deps.log(`saved fact ${fact.id} -> ${result.uid}`);
|
|
84
|
+
saved++;
|
|
85
|
+
}
|
|
86
|
+
return { saved, skipped };
|
|
87
|
+
}
|
|
88
|
+
exports.applyPlan = applyPlan;
|
|
@@ -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
|
|
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 = {
|
|
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
|
|
301
|
-
function removeCopiedAssets(settingsPath, home = (0, os_1.homedir)()) {
|
|
302
|
-
const { hookDir,
|
|
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
|
-
|
|
313
|
-
|
|
314
|
-
(0, fs_1.
|
|
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,
|
|
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,
|
|
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(
|
|
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
package/skill-guide.md
CHANGED
|
@@ -74,7 +74,8 @@ Fact, Skill, or Wiki saves alike. Newer tags: `AI` (LLMs, agents, MCP, prompts),
|
|
|
74
74
|
`API` (REST/GraphQL endpoints and schemas), `Mobile` (the Skedulo mobile app/v3 —
|
|
75
75
|
not `MobileExtension`, which is MEX forms), `Infrastructure` (CI/CD, pipelines,
|
|
76
76
|
hosting, environments), `Security` (permissions, secrets, vulnerabilities),
|
|
77
|
-
`Messaging` (SMS, email, notifications, queues)
|
|
77
|
+
`Messaging` (SMS, email, notifications, queues), `ProductRules` (a product's rules and
|
|
78
|
+
don't-build wiki pages, written by the product-knowledge skill; see "Product knowledge"). The tool schema enforces this, so an invalid tag fails
|
|
78
79
|
with a clear validation error rather than reaching the backend — if this
|
|
79
80
|
list and the schema's actual error ever disagree, trust the error: this
|
|
80
81
|
list is prose, kept in sync by hand.
|
|
@@ -214,9 +215,15 @@ repeats a memory of yours, change that memory instead of saving another one:
|
|
|
214
215
|
`links` (target wiki uids) and `factIds` (uids of your facts that belong to
|
|
215
216
|
the scenario) replace the whole list; `[]` clears it. A fact that is not
|
|
216
217
|
yours comes back in `skippedFactIds` instead of failing; facts left out of the
|
|
217
|
-
new list are unlinked from the scenario. It re-embeds the text, so search keeps working.
|
|
218
|
-
|
|
219
|
-
|
|
218
|
+
new list are unlinked from the scenario. It re-embeds the text, so search keeps working. The
|
|
219
|
+
author can update any of their memories. Any member of the team that owns an item's repo can
|
|
220
|
+
update that item when it is Team-visible, but only the author can change its `repo`, `links` or
|
|
221
|
+
`factIds`; Private, Restricted, Org and repo-less items stay author-only. When you are not the
|
|
222
|
+
author, `expectedLastModified` (the `lastModifiedDate` from `memory_get`) is required: without it
|
|
223
|
+
the update is treated as author-only and fails with `Not found`, so a `Not found` on an item you
|
|
224
|
+
can read usually means it was left out. If the item changed since you read it, the update fails
|
|
225
|
+
with `Conflict:` instead of overwriting it. Read it again, re-apply your change, and retry.
|
|
226
|
+
- **`memory_delete`** removes one of your memories for good. Only the author can delete. Use it for a copy
|
|
220
227
|
you have just merged into another, or a memory that is wrong or obsolete.
|
|
221
228
|
Prefer `memory_update` while the memory is still partly right.
|
|
222
229
|
- **`memory_setTaskStatus`** with the ticket `externalRef` marks that ticket's
|
|
@@ -228,8 +235,9 @@ looks like an existing memory, the reply starts with `Saved as <uid>, but it
|
|
|
228
235
|
looks like …` and lists each match with its uid, a similarity score and whether
|
|
229
236
|
it is yours. When a match is yours and already covers the point, keep one copy:
|
|
230
237
|
`memory_update` the old one with the merged text, then `memory_delete` the one
|
|
231
|
-
you just saved.
|
|
232
|
-
it
|
|
238
|
+
you just saved. Editing a teammate's memory changes what the whole team reads, so
|
|
239
|
+
do it only when the human asks for it; otherwise keep your new one only if it adds
|
|
240
|
+
something theirs does not say. The check only warns, so a distinct
|
|
233
241
|
memory that shares vocabulary with another is saved either way.
|
|
234
242
|
|
|
235
243
|
Before saving a decision or root cause that you suspect was recorded before,
|
|
@@ -523,6 +531,18 @@ verbatim (or close to it) the one time it appears** — it's the only signal
|
|
|
523
531
|
they get that their saves are now shared with that team, and it won't
|
|
524
532
|
repeat later in the same session even though the join already happened.
|
|
525
533
|
|
|
534
|
+
## Product knowledge
|
|
535
|
+
|
|
536
|
+
A customer product's rules, don't-build list, reference pages and sources live as Team wiki pages on
|
|
537
|
+
the product's delivery repo, titled `<Product> › Rules › <feature>`, `<Product> › Don't build`,
|
|
538
|
+
`<Product> › Reference › <topic>` and `<Product> › Sources`; the rules and don't-build pages carry the
|
|
539
|
+
`ProductRules` tag. Find them with `memory_list type=Wiki titlePrefix="<Product> ›"`. Four skills work
|
|
540
|
+
on them: product-knowledge (create, refresh from sources, import a knowledge pack), plan-ticket,
|
|
541
|
+
delegate-ticket and fold-findings. Change these pages through those skills, which keep the entry
|
|
542
|
+
format and change log and always pass `expectedLastModified` to `memory_update`. Without those
|
|
543
|
+
skills, edit with `memory_update` directly, keep the page's entry format, add a change-log line, and
|
|
544
|
+
still pass `expectedLastModified`.
|
|
545
|
+
|
|
526
546
|
## If the tools aren't available
|
|
527
547
|
|
|
528
548
|
The memory-hub MCP tools require `memory-hub-mcp` to be registered as an
|
|
File without changes
|