wyrm-mcp 9.2.0 → 9.2.2
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 +2 -0
- package/dist/auto-runs.js +1 -0
- package/dist/autoconfig.js +3 -3
- package/dist/capabilities.js +3 -3
- package/dist/causality.js +13 -8
- package/dist/cli.js +25 -22
- package/dist/cloud/cli.js +3 -3
- package/dist/cloud/sync-daemon-entrypoint.js +2 -2
- package/dist/cloud/sync-daemon.js +1 -1
- package/dist/color.js +1 -0
- package/dist/database.js +3 -3
- package/dist/deprecations.js +2 -2
- package/dist/events.js +6 -6
- package/dist/federation.js +10 -10
- package/dist/handlers/arg-keys.js +1 -0
- package/dist/handlers/capture.js +58 -58
- package/dist/handlers/causality.js +8 -8
- package/dist/handlers/cloud.js +85 -83
- package/dist/handlers/companion.js +10 -10
- package/dist/handlers/entity.js +1 -1
- package/dist/handlers/events.js +12 -12
- package/dist/handlers/failure.js +12 -12
- package/dist/handlers/goals.js +4 -4
- package/dist/handlers/intelligence.js +63 -63
- package/dist/handlers/mcpclient.js +1 -1
- package/dist/handlers/presence.js +3 -3
- package/dist/handlers/project-arg.js +1 -0
- package/dist/handlers/project.js +1 -1
- package/dist/handlers/quest.js +5 -3
- package/dist/handlers/recall.js +18 -18
- package/dist/handlers/registry.js +1 -1
- package/dist/handlers/resources.js +1 -1
- package/dist/handlers/review.js +3 -3
- package/dist/handlers/run.js +3 -3
- package/dist/handlers/search.js +3 -3
- package/dist/handlers/session.js +24 -24
- package/dist/handlers/share.js +5 -5
- package/dist/handlers/shims.js +1 -1
- package/dist/handlers/thread.js +2 -2
- package/dist/http-auth.js +1 -1
- package/dist/http-fast.js +15 -15
- package/dist/index.js +2 -2
- package/dist/logger.js +2 -2
- package/dist/receipt.js +1 -1
- package/dist/rehydration.js +24 -9
- package/dist/render.js +3 -3
- package/dist/setup.js +2 -3
- package/dist/sqlite-busy.js +1 -1
- package/dist/stale-servers.js +2 -0
- package/dist/stdio-lifecycle.js +1 -0
- package/dist/storage/index.js +3 -3
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/ui-dashboard.js +9 -8
- package/dist/validate.js +1 -1
- package/dist/vault-exec.js +4 -0
- package/dist/vault.js +1 -1
- package/dist/wyrm-cli.js +105 -142
- package/dist/wyrm-manifest.json +3 -3
- package/dist/wyrm-ui.js +14 -7
- package/dist/wyrm.js +2 -0
- package/package.json +6 -4
- package/scripts/hooks/wyrm-citation-audit.mjs +155 -46
- package/scripts/hooks/wyrm-prompt-context.mjs +300 -0
- package/scripts/hooks/wyrm-run-auto.mjs +148 -37
- package/scripts/hooks/wyrm-session-rehydrate.mjs +142 -24
package/dist/wyrm-manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"contract": "wyrm-cloud-memory-v1",
|
|
3
|
-
"version": "9.2.
|
|
3
|
+
"version": "9.2.2",
|
|
4
4
|
"generatedBy": "scripts/gen-tool-manifest.mjs (from the dist/ registry modules — never hand-edited)",
|
|
5
5
|
"tiers": {
|
|
6
6
|
"core": [
|
|
@@ -691,7 +691,7 @@
|
|
|
691
691
|
"cloudSupported": false,
|
|
692
692
|
"cloudSupportedV2": false,
|
|
693
693
|
"disposition": "alias",
|
|
694
|
-
"target": "
|
|
694
|
+
"target": "wyrm_capture"
|
|
695
695
|
},
|
|
696
696
|
{
|
|
697
697
|
"name": "wyrm_global_context",
|
|
@@ -1457,7 +1457,7 @@
|
|
|
1457
1457
|
"cloudSupported": false,
|
|
1458
1458
|
"cloudSupportedV2": false,
|
|
1459
1459
|
"disposition": "alias",
|
|
1460
|
-
"target": "
|
|
1460
|
+
"target": "wyrm_replication"
|
|
1461
1461
|
},
|
|
1462
1462
|
{
|
|
1463
1463
|
"name": "wyrm_usage",
|
package/dist/wyrm-ui.js
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
3
|
-
|
|
2
|
+
import{spawn as n}from"child_process";const t=parseInt(process.env.WYRM_PORT||process.env.WYRM_HTTP_PORT||"3333",10)||3333,o="127.0.0.1",c=`http://${o}:${t}`,a=`Usage: wyrm-ui
|
|
3
|
+
|
|
4
|
+
Open the Wyrm web dashboard in your browser. When no Wyrm HTTP server answers
|
|
5
|
+
on ${o}:<port>, one is started first (wyrm serve --ui --port <port>).
|
|
6
|
+
|
|
7
|
+
Environment:
|
|
8
|
+
WYRM_PORT port to probe and start on (default 3333; WYRM_HTTP_PORT is an alias)
|
|
9
|
+
`;async function p(){try{return(await fetch(`${c}/health`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}function u(r){switch(process.platform){case"darwin":return["open",[r]];case"win32":return["cmd",["/c","start",'""',r]];default:return["xdg-open",[r]]}}function d(r){const[e,i]=u(r);try{n(e,i,{detached:!0,stdio:"ignore"}).unref(),process.stdout.write(`\u{F115D} Opened ${r}
|
|
10
|
+
`)}catch(s){process.stderr.write(`[wyrm-ui] could not launch browser via ${e}: ${s.message}
|
|
4
11
|
`),process.stdout.write(`Open this URL manually: ${r}
|
|
5
|
-
`)}}async function
|
|
6
|
-
`);try{
|
|
7
|
-
`)}catch(
|
|
8
|
-
`),process.stdout.write(`Run it manually: wyrm serve --ui
|
|
9
|
-
`),process.exit(1)}}
|
|
12
|
+
`)}}async function w(){if(process.argv.slice(2).some(e=>e==="--help"||e==="-h")){process.stdout.write(a);return}const r=`${c}/ui`;if(await p()){d(r);return}process.stderr.write(`[wyrm-ui] starting \`wyrm serve --ui --port ${t}\` detached
|
|
13
|
+
`);try{n("wyrm",["serve","--ui","--port",String(t)],{detached:!0,stdio:"ignore"}).unref(),process.stdout.write(`\u{F115D} Launching the Wyrm dashboard at ${r}
|
|
14
|
+
`)}catch(e){process.stderr.write(`[wyrm-ui] could not start the server: ${e.message}
|
|
15
|
+
`),process.stdout.write(`Run it manually: wyrm serve --ui --port ${t}
|
|
16
|
+
`),process.exit(1)}}w().catch(r=>{process.stderr.write(`[wyrm-ui] fatal: ${r.message}
|
|
10
17
|
`),process.exit(1)});
|
package/dist/wyrm.js
ADDED
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wyrm-mcp",
|
|
3
|
-
"version": "9.2.
|
|
3
|
+
"version": "9.2.2",
|
|
4
4
|
"mcpName": "lk.ghosts/wyrm",
|
|
5
|
-
"description": "Local-first persistent memory for AI agents over MCP. Ground truths,
|
|
5
|
+
"description": "Local-first persistent memory for AI agents over MCP. Ground truths, a failure firewall that blocks repeated mistakes (negative learning), and hybrid recall, stored in SQLite on your machine. No cloud or LLM required. Proprietary license.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|
|
8
8
|
"bin": {
|
|
9
9
|
"wyrm-mcp": "dist/index.js",
|
|
10
|
-
"wyrm": "dist/wyrm
|
|
10
|
+
"wyrm": "dist/wyrm.js",
|
|
11
11
|
"wyrm-setup": "dist/setup.js",
|
|
12
12
|
"wyrm-loop": "dist/wyrm-loop.js",
|
|
13
13
|
"wyrm-ui": "dist/wyrm-ui.js",
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"scripts/hooks/wyrm-tool-call-trace.mjs",
|
|
32
32
|
"scripts/hooks/wyrm-run-auto.mjs",
|
|
33
33
|
"scripts/hooks/wyrm-citation-audit.mjs",
|
|
34
|
+
"scripts/hooks/wyrm-prompt-context.mjs",
|
|
34
35
|
"README.md",
|
|
35
36
|
"BENCHMARKS.md",
|
|
36
37
|
"COMPARISON.md",
|
|
@@ -43,7 +44,8 @@
|
|
|
43
44
|
"build": "tsc && chmod +x dist/*.js && node scripts/gen-tool-manifest.mjs && node scripts/check-annotation-coverage.mjs",
|
|
44
45
|
"build:official": "npm run build && node scripts/bake-official.mjs",
|
|
45
46
|
"build:closed": "npm run build:official && node scripts/minify-dist.mjs",
|
|
46
|
-
"prepack": "node scripts/check-publish-skills.mjs && node scripts/
|
|
47
|
+
"prepack": "node scripts/check-publish-skills.mjs && node scripts/pack-dist.mjs prepack",
|
|
48
|
+
"postpack": "node scripts/pack-dist.mjs postpack",
|
|
47
49
|
"start": "node dist/index.js",
|
|
48
50
|
"fast": "node dist/http-fast.js",
|
|
49
51
|
"setup": "node dist/setup.js",
|
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
*
|
|
19
19
|
* Claude Code passes a JSON payload on stdin including `transcript_path`.
|
|
20
20
|
*/
|
|
21
|
-
import { readFileSync } from 'node:fs';
|
|
21
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
22
|
+
import { basename, dirname, join } from 'node:path';
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
25
|
* Canonical citation form the grounding rules mandate: `mem:5508`, `truth:921`.
|
|
@@ -30,6 +31,31 @@ import { readFileSync } from 'node:fs';
|
|
|
30
31
|
*/
|
|
31
32
|
const CITE = /\b(mem|memory|truth|quest|failure)[ \t]*[:#][ \t]*(\d{1,7})\b/gi;
|
|
32
33
|
|
|
34
|
+
/**
|
|
35
|
+
* The bare id forms Wyrm's own tool output renders: `#7185: …` in search and
|
|
36
|
+
* prime listings, `"id":7143` in recall JSON. Neither names a kind, and in
|
|
37
|
+
* arbitrary text `#12` is an issue number or a list marker, so these count
|
|
38
|
+
* ONLY inside the result of a Wyrm MCP tool — and there they ground the number
|
|
39
|
+
* for any kind: an advisory audit that under-reports a mislabelled kind costs
|
|
40
|
+
* less than one that accuses a citation of a record it just served.
|
|
41
|
+
*/
|
|
42
|
+
const BARE = /(?<![\w&#])#(\d{1,7})\b|"id"[ \t]*:[ \t]*(\d{1,7})\b/g;
|
|
43
|
+
|
|
44
|
+
/** Wyrm tool names across install shapes: mcp__wyrm__*, mcp__claude_ai_wyrm__*, mcp__plugin_x_wyrm__*. */
|
|
45
|
+
const WYRM_TOOL = /^mcp__(?:[a-z0-9_]*_)?wyrm__/i;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* This hook's own earlier findings. They are injected back into the
|
|
49
|
+
* transcript as Stop-hook context, and they name the very ids they flagged:
|
|
50
|
+
* read as served, a fabricated citation would ground itself on the next turn.
|
|
51
|
+
*/
|
|
52
|
+
const AUDIT_BLOCK = /<wyrm-citation-audit>[\s\S]*?(?:<\/wyrm-citation-audit>|$)/g;
|
|
53
|
+
|
|
54
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
55
|
+
|
|
56
|
+
/** Parent transcripts folded in at most; a continuation chain is short. */
|
|
57
|
+
const MAX_PARENTS = 8;
|
|
58
|
+
|
|
33
59
|
/** Normalize the aliases Wyrm renders (`mem:` and `memory #` are one kind). */
|
|
34
60
|
function norm(kind) {
|
|
35
61
|
const k = kind.toLowerCase();
|
|
@@ -43,61 +69,144 @@ function idsIn(text) {
|
|
|
43
69
|
return out;
|
|
44
70
|
}
|
|
45
71
|
|
|
72
|
+
/** Plain text out of a transcript content value: a string, an array of blocks, or a block. */
|
|
73
|
+
function textOf(v, depth = 0) {
|
|
74
|
+
if (v == null || depth > 3) return '';
|
|
75
|
+
if (typeof v === 'string') return v;
|
|
76
|
+
if (Array.isArray(v)) return v.map((x) => textOf(x, depth + 1)).filter(Boolean).join('\n');
|
|
77
|
+
if (typeof v === 'object') {
|
|
78
|
+
return [v.text, v.content].map((x) => textOf(x, depth + 1)).filter(Boolean).join('\n');
|
|
79
|
+
}
|
|
80
|
+
return '';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Read one transcript into the shared served sets. Returns the ids of the
|
|
85
|
+
* sessions its records name, the sessions it says it continued into, and the
|
|
86
|
+
* final assistant reply — or null when the file cannot be read.
|
|
87
|
+
*/
|
|
88
|
+
function readLedger(path, served, bare, toolNames) {
|
|
89
|
+
let lines;
|
|
90
|
+
try { lines = readFileSync(path, 'utf8').split('\n'); } catch { return null; }
|
|
91
|
+
const sessionIds = new Set();
|
|
92
|
+
const continuedIn = new Set();
|
|
93
|
+
let reply = [];
|
|
94
|
+
|
|
95
|
+
const serve = (text, fromWyrmTool) => {
|
|
96
|
+
const t = String(text || '').replace(AUDIT_BLOCK, '');
|
|
97
|
+
if (!t) return;
|
|
98
|
+
for (const id of idsIn(t)) served.add(id);
|
|
99
|
+
if (fromWyrmTool) for (const m of t.matchAll(BARE)) bare.add(m[1] ?? m[2]);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
for (const line of lines) {
|
|
103
|
+
if (!line.trim()) continue;
|
|
104
|
+
let o;
|
|
105
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
106
|
+
if (!o || typeof o !== 'object') continue;
|
|
107
|
+
const type = o.type;
|
|
108
|
+
for (const key of ['sessionId', 'session_id']) {
|
|
109
|
+
if (typeof o[key] === 'string') sessionIds.add(o[key]);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (type === 'continued-in') {
|
|
113
|
+
if (typeof o.continuedInSessionId === 'string') continuedIn.add(o.continuedInSessionId);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Anything that is not the model's own prose is a hand-off TO the model:
|
|
118
|
+
// tool results, the SessionStart brief, injected context, attachments.
|
|
119
|
+
// Hook context (the SessionStart brief, per-prompt recall) is recorded as
|
|
120
|
+
// an attachment whose text lives at attachment.content, not message.content.
|
|
121
|
+
if (type === 'user' || type === 'system' || type === 'attachment') {
|
|
122
|
+
const content = type === 'attachment'
|
|
123
|
+
? (o.attachment?.content ?? o.attachment?.text)
|
|
124
|
+
: (o?.message?.content ?? o?.content ?? o?.text);
|
|
125
|
+
if (Array.isArray(content)) {
|
|
126
|
+
for (const c of content) {
|
|
127
|
+
const isWyrmResult = c?.type === 'tool_result' && WYRM_TOOL.test(toolNames.get(c.tool_use_id) ?? '');
|
|
128
|
+
serve(textOf(c), isWyrmResult);
|
|
129
|
+
}
|
|
130
|
+
} else {
|
|
131
|
+
serve(textOf(content), false);
|
|
132
|
+
}
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (type === 'assistant') {
|
|
137
|
+
const blocks = o?.message?.content;
|
|
138
|
+
if (!Array.isArray(blocks)) continue;
|
|
139
|
+
// A tool_use is the model asking, not asserting — its arguments echo ids
|
|
140
|
+
// it is looking up and must not count as a claim. Its name is what
|
|
141
|
+
// later tells us whether a tool_result came from Wyrm.
|
|
142
|
+
for (const c of blocks) {
|
|
143
|
+
if (c?.type === 'tool_use' && typeof c.id === 'string') toolNames.set(c.id, String(c.name ?? ''));
|
|
144
|
+
}
|
|
145
|
+
// A new assistant turn replaces the previous candidate: we audit the
|
|
146
|
+
// response the user actually ends up reading, not the whole conversation.
|
|
147
|
+
const texts = blocks.filter((c) => c?.type === 'text').map((c) => c.text ?? '');
|
|
148
|
+
if (texts.length) reply = texts;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return { sessionIds, continuedIn, reply };
|
|
152
|
+
}
|
|
153
|
+
|
|
46
154
|
let payload = {};
|
|
47
155
|
try { payload = JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { /* no/invalid stdin */ }
|
|
48
156
|
if (!payload || typeof payload !== 'object') payload = {};
|
|
49
157
|
|
|
50
158
|
const tpath = payload.transcript_path;
|
|
51
|
-
if (!tpath) process.exit(0);
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
159
|
+
if (!tpath || typeof tpath !== 'string') process.exit(0);
|
|
160
|
+
|
|
161
|
+
const served = new Set(); // every typed id Wyrm put in front of this session
|
|
162
|
+
const bare = new Set(); // numbers Wyrm tools rendered without a kind
|
|
163
|
+
const toolNames = new Map(); // tool_use id -> tool name, across folded transcripts
|
|
164
|
+
|
|
165
|
+
const main = readLedger(tpath, served, bare, toolNames);
|
|
166
|
+
if (!main) process.exit(0);
|
|
167
|
+
|
|
168
|
+
// A continued or resumed chat is written to a new transcript file. What was
|
|
169
|
+
// served before the hand-over lives in the parent file, which records a
|
|
170
|
+
// `continued-in` line naming this one; the child's records still carry the
|
|
171
|
+
// parent's id as session_id. Fold a parent in only when its own continued-in
|
|
172
|
+
// record points at a transcript already in the chain, so an unrelated sibling
|
|
173
|
+
// file can never ground anything.
|
|
174
|
+
try {
|
|
175
|
+
const dir = dirname(tpath);
|
|
176
|
+
const chain = new Set([basename(tpath).replace(/\.jsonl$/, '')]);
|
|
177
|
+
const pending = new Set([...main.sessionIds, payload.session_id]
|
|
178
|
+
.filter((id) => typeof id === 'string' && SESSION_ID.test(id) && !chain.has(id)));
|
|
179
|
+
const loaded = new Map(); // id -> { served, bare, ledger } read but not yet verified
|
|
180
|
+
let progress = true;
|
|
181
|
+
while (progress && chain.size <= MAX_PARENTS) {
|
|
182
|
+
progress = false;
|
|
183
|
+
for (const id of [...pending]) {
|
|
184
|
+
if (!loaded.has(id)) {
|
|
185
|
+
const p = join(dir, `${id}.jsonl`);
|
|
186
|
+
if (loaded.size >= MAX_PARENTS || !existsSync(p)) { pending.delete(id); continue; }
|
|
187
|
+
const s = new Set();
|
|
188
|
+
const b = new Set();
|
|
189
|
+
loaded.set(id, { served: s, bare: b, ledger: readLedger(p, s, b, toolNames) });
|
|
81
190
|
}
|
|
191
|
+
const entry = loaded.get(id);
|
|
192
|
+
if (!entry.ledger) { pending.delete(id); continue; }
|
|
193
|
+
if (![...entry.ledger.continuedIn].some((next) => chain.has(next))) continue;
|
|
194
|
+
for (const x of entry.served) served.add(x);
|
|
195
|
+
for (const x of entry.bare) bare.add(x);
|
|
196
|
+
chain.add(id);
|
|
197
|
+
pending.delete(id);
|
|
198
|
+
for (const more of entry.ledger.sessionIds) {
|
|
199
|
+
if (SESSION_ID.test(more) && !chain.has(more)) pending.add(more);
|
|
200
|
+
}
|
|
201
|
+
progress = true;
|
|
82
202
|
}
|
|
83
|
-
continue;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
if (type === 'assistant') {
|
|
87
|
-
const blocks = o?.message?.content;
|
|
88
|
-
if (!Array.isArray(blocks)) continue;
|
|
89
|
-
// A new assistant turn replaces the previous candidate: we audit the
|
|
90
|
-
// response the user actually ends up reading, not the whole conversation.
|
|
91
|
-
const texts = blocks.filter((c) => c?.type === 'text').map((c) => c.text ?? '');
|
|
92
|
-
if (texts.length) lastAssistantText = texts;
|
|
93
|
-
// A tool_use is the model asking, not asserting — its arguments echo ids
|
|
94
|
-
// it is looking up and must not count as a claim.
|
|
95
203
|
}
|
|
96
|
-
}
|
|
204
|
+
} catch { /* a parent we cannot read grounds nothing; the audit still runs */ }
|
|
97
205
|
|
|
98
|
-
|
|
206
|
+
const cited = new Set(); // every id the FINAL assistant turn asserted
|
|
207
|
+
for (const t of main.reply) for (const id of idsIn(t)) cited.add(id);
|
|
99
208
|
|
|
100
|
-
const fabricated = [...cited].filter((id) => !served.has(id));
|
|
209
|
+
const fabricated = [...cited].filter((id) => !served.has(id) && !bare.has(id.split(':')[1]));
|
|
101
210
|
|
|
102
211
|
if (fabricated.length === 0) process.exit(0);
|
|
103
212
|
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Wyrm per-prompt recall — Claude Code UserPromptSubmit hook.
|
|
4
|
+
*
|
|
5
|
+
* On each prompt, surface the few Wyrm memories that share words with what was
|
|
6
|
+
* just asked, so recall is present every turn, not only at SessionStart.
|
|
7
|
+
*
|
|
8
|
+
* Shipped from a machine-local predecessor that never received fixes. Measured
|
|
9
|
+
* over 7 days on a populated store, that version injected mostly noise: 59% of
|
|
10
|
+
* its records were [auto:SessionEnd]/[auto:PreCompact] session digests, 47% of
|
|
11
|
+
* its lines were fragments of a search table wrapped around multi-line cells,
|
|
12
|
+
* and 7% of its lines shared a content word with the prompt. So this one:
|
|
13
|
+
* - excludes [auto:*] digests (the SessionStart brief carries sessions);
|
|
14
|
+
* - emits one line per record: typed id, kind, ~200 chars of content;
|
|
15
|
+
* - dedupes by id, within the block and across the session;
|
|
16
|
+
* - requires a record to share content words with the prompt, not merely to
|
|
17
|
+
* be an FTS hit on one common word;
|
|
18
|
+
* - caps the block at ~1,500 chars;
|
|
19
|
+
* - ignores harness wrappers (task notifications, cross-session messages,
|
|
20
|
+
* reminder-only prompts): they are not the user's words, and searching on
|
|
21
|
+
* their tag soup injected unrelated memories.
|
|
22
|
+
*
|
|
23
|
+
* It reads the store directly through node:sqlite (read-only FTS5 over
|
|
24
|
+
* memory_artifacts with MemoryArtifacts.recall's eligibility filters), which
|
|
25
|
+
* skips the CLI's startup and embedding-model load. A hook has no run, so the
|
|
26
|
+
* run-scoped mute policy is the default no-op. When node:sqlite is missing
|
|
27
|
+
* (Node before 22.13 without its flag) or the store cannot be read, it falls
|
|
28
|
+
* back to `wyrm search`.
|
|
29
|
+
*
|
|
30
|
+
* Always exits 0 (a memory hook must never break a turn). Emits
|
|
31
|
+
* {"hookSpecificOutput": {"hookEventName": "UserPromptSubmit",
|
|
32
|
+
* "additionalContext": "..."}} or nothing.
|
|
33
|
+
*
|
|
34
|
+
* @copyright 2026 Ghost Protocol (Pvt) Ltd.
|
|
35
|
+
*/
|
|
36
|
+
import { readFileSync, existsSync, writeFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
|
|
37
|
+
import { spawnSync } from 'node:child_process';
|
|
38
|
+
import { basename, dirname, join } from 'node:path';
|
|
39
|
+
import { tmpdir, homedir } from 'node:os';
|
|
40
|
+
|
|
41
|
+
// Portable, self-healing `wyrm` resolution (fallback lane only): bare command
|
|
42
|
+
// first (honors PATH), then npm/user CLI-install locations that exist here.
|
|
43
|
+
// Deliberately NOT /usr/bin: a distro or global scoped-package can put an
|
|
44
|
+
// UNRELATED `wyrm` there (e.g. the http-server entrypoint).
|
|
45
|
+
function wyrmCandidates() {
|
|
46
|
+
const home = homedir();
|
|
47
|
+
return [
|
|
48
|
+
'wyrm',
|
|
49
|
+
join(home, '.npm-global', 'bin', 'wyrm'),
|
|
50
|
+
join(home, '.local', 'bin', 'wyrm'),
|
|
51
|
+
join(home, 'node_modules', '.bin', 'wyrm'),
|
|
52
|
+
'/usr/local/bin/wyrm',
|
|
53
|
+
'/opt/homebrew/bin/wyrm',
|
|
54
|
+
].filter((c) => c === 'wyrm' || existsSync(c));
|
|
55
|
+
}
|
|
56
|
+
function runWyrm(args, opts) {
|
|
57
|
+
for (const bin of wyrmCandidates()) {
|
|
58
|
+
const r = spawnSync(bin, args, opts);
|
|
59
|
+
if (!(r.error && r.error.code === 'ENOENT')) return r; // spawned (even if non-zero exit)
|
|
60
|
+
}
|
|
61
|
+
return { status: 127, stdout: '', error: new Error('wyrm not found') };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const MAX_CHARS = 1500; // whole injected block
|
|
65
|
+
const LINE_CHARS = 200; // content per record
|
|
66
|
+
const MAX_RECORDS = 5;
|
|
67
|
+
const CANDIDATES = 40; // FTS rows considered before the overlap filter
|
|
68
|
+
const MAX_TERMS = 12;
|
|
69
|
+
const MIN_CHARS = 24;
|
|
70
|
+
const STATE_PREFIX = 'wyrm-prompt-context-';
|
|
71
|
+
const STATE_TTL_MS = 6 * 60 * 60 * 1000;
|
|
72
|
+
const TRIVIAL = /^(hi|hey|hello|yo|thanks|thank you|ok|okay|yes|no|sure|nice|cool|yep|nope|got it)[\s!.?]*$/i;
|
|
73
|
+
|
|
74
|
+
// Function words and chat filler. Matching on these is what made an OR-joined
|
|
75
|
+
// FTS query return any record at all for any prompt.
|
|
76
|
+
const STOPWORDS = new Set(`
|
|
77
|
+
the and for are but not you your yours with this that from have has had was were will would could should
|
|
78
|
+
can may might must shall into onto over under about above below after before again then once here there
|
|
79
|
+
when where why how all any both each few more most other some such only own same than too very just also
|
|
80
|
+
now what which who whom whose these those them they their theirs his her hers its our ours out off does
|
|
81
|
+
did doing done being been get got let make made use used using want need like please thanks thank okay
|
|
82
|
+
yes see look check tell show give take way thing things one two lot able don doesn didn isn wasn aren
|
|
83
|
+
won couldn shouldn wouldn haven hasn let lets i'm let's into through while because until upon
|
|
84
|
+
`.split(/\s+/).filter(Boolean));
|
|
85
|
+
|
|
86
|
+
function done(obj) {
|
|
87
|
+
if (obj) process.stdout.write(JSON.stringify(obj) + '\n');
|
|
88
|
+
process.exit(0);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function stripReminders(text) {
|
|
92
|
+
return text.replace(/<system-reminder>[\s\S]*?(?:<\/system-reminder>|$)/g, '').trim();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A prompt the harness wrote, not the user: nothing in it is a recall query. */
|
|
96
|
+
function isHarnessWrapper(prompt) {
|
|
97
|
+
if (/^\[SYSTEM NOTIFICATION/i.test(prompt)) return true;
|
|
98
|
+
if (prompt.includes('<task-notification>') || prompt.includes('<cross-session-message')) return true;
|
|
99
|
+
return prompt.includes('<system-reminder>') && stripReminders(prompt).length === 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Distinct content words of the prompt, in order, lowercased. */
|
|
103
|
+
function contentTerms(text) {
|
|
104
|
+
const terms = [];
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
for (const m of text.slice(0, 2000).toLowerCase().matchAll(/[\p{L}\p{N}]{3,}/gu)) {
|
|
107
|
+
const t = m[0];
|
|
108
|
+
if (STOPWORDS.has(t) || /^\d+$/.test(t) || seen.has(t)) continue;
|
|
109
|
+
seen.add(t);
|
|
110
|
+
terms.push(t);
|
|
111
|
+
if (terms.length >= MAX_TERMS) break;
|
|
112
|
+
}
|
|
113
|
+
return terms;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function sharedTerms(text, terms) {
|
|
117
|
+
const words = new Set(String(text || '').toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) ?? []);
|
|
118
|
+
let n = 0;
|
|
119
|
+
for (const t of terms) if (words.has(t)) n++;
|
|
120
|
+
return n;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function oneLine(text, max) {
|
|
124
|
+
const flat = String(text || '').replace(/\s+/g, ' ').trim();
|
|
125
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 3).trimEnd()}...`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The store the CLI opens (src/database.ts getDbPath). */
|
|
129
|
+
function storePath() {
|
|
130
|
+
return process.env.WYRM_DB_PATH || process.env.WYRM_DB || join(homedir(), '.wyrm', 'wyrm.db');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The project this prompt belongs to: the registered path of the directory or
|
|
135
|
+
* its nearest registered ancestor, else a project named like the directory.
|
|
136
|
+
* null means search every project, as `wyrm search` does when none resolves.
|
|
137
|
+
*/
|
|
138
|
+
function resolveProjectId(db, cwd) {
|
|
139
|
+
const byPath = db.prepare('SELECT id FROM projects WHERE path = ?');
|
|
140
|
+
let dir = cwd;
|
|
141
|
+
for (let i = 0; dir && i < 32; i++) {
|
|
142
|
+
const row = byPath.get(dir);
|
|
143
|
+
if (row) return Number(row.id);
|
|
144
|
+
const up = dirname(dir);
|
|
145
|
+
if (up === dir) break;
|
|
146
|
+
dir = up;
|
|
147
|
+
}
|
|
148
|
+
const named = db.prepare('SELECT id FROM projects WHERE LOWER(name) = LOWER(?) LIMIT 1').get(basename(cwd));
|
|
149
|
+
return named ? Number(named.id) : null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Direct lane. Returns rows, or null when this lane cannot run here. */
|
|
153
|
+
async function searchStore(terms, cwd) {
|
|
154
|
+
const path = storePath();
|
|
155
|
+
if (!existsSync(path)) return null;
|
|
156
|
+
let DatabaseSync;
|
|
157
|
+
const emit = process.emitWarning;
|
|
158
|
+
try {
|
|
159
|
+
// node:sqlite announces itself as experimental on stderr, which would
|
|
160
|
+
// land in the harness's record of every prompt.
|
|
161
|
+
process.emitWarning = function (warning, ...rest) {
|
|
162
|
+
if (/sqlite/i.test(String(warning?.message ?? warning))) return undefined;
|
|
163
|
+
return emit.call(process, warning, ...rest);
|
|
164
|
+
};
|
|
165
|
+
({ DatabaseSync } = await import('node:sqlite'));
|
|
166
|
+
} catch {
|
|
167
|
+
return null;
|
|
168
|
+
} finally {
|
|
169
|
+
process.emitWarning = emit;
|
|
170
|
+
}
|
|
171
|
+
let db;
|
|
172
|
+
try {
|
|
173
|
+
db = new DatabaseSync(path, { readOnly: true });
|
|
174
|
+
db.exec('PRAGMA busy_timeout = 250');
|
|
175
|
+
const projectId = resolveProjectId(db, cwd);
|
|
176
|
+
// Terms are [\p{L}\p{N}]+ only, so quoting needs no escaping.
|
|
177
|
+
const match = terms.map((t) => `"${t}"`).join(' OR ');
|
|
178
|
+
// FTS first, materialized. Written as a plain join, SQLite's planner drove
|
|
179
|
+
// the query from memory_artifacts (via the supersedes_id index) and ran
|
|
180
|
+
// MATCH once per row: ~2 s on a 6,300-memory store. Collecting the matches
|
|
181
|
+
// first and joining on rowid takes ~25 ms with identical results.
|
|
182
|
+
const rows = db.prepare(`
|
|
183
|
+
WITH hits AS MATERIALIZED (
|
|
184
|
+
SELECT rowid AS id, rank FROM memory_artifacts_fts WHERE memory_artifacts_fts MATCH ?
|
|
185
|
+
)
|
|
186
|
+
SELECT a.id, a.kind, a.problem, a.validated_fix, a.constraints, a.why_it_worked, a.tags
|
|
187
|
+
FROM hits
|
|
188
|
+
JOIN memory_artifacts a ON a.id = hits.id
|
|
189
|
+
WHERE a.supersedes_id IS NULL
|
|
190
|
+
AND a.needs_review = 0
|
|
191
|
+
AND a.problem NOT LIKE '[auto:%'
|
|
192
|
+
AND (? IS NULL OR a.project_id = ?)
|
|
193
|
+
ORDER BY hits.rank
|
|
194
|
+
LIMIT ?
|
|
195
|
+
`).all(match, projectId, projectId, CANDIDATES);
|
|
196
|
+
return rows.map((r) => ({
|
|
197
|
+
id: Number(r.id),
|
|
198
|
+
kind: r.kind,
|
|
199
|
+
text: r.validated_fix ? `${r.problem} -> ${r.validated_fix}` : r.problem,
|
|
200
|
+
haystack: [r.problem, r.validated_fix, r.constraints, r.why_it_worked, r.tags].filter(Boolean).join(' '),
|
|
201
|
+
}));
|
|
202
|
+
} catch {
|
|
203
|
+
return null; // unreadable store, or no FTS table: let the CLI lane try
|
|
204
|
+
} finally {
|
|
205
|
+
try { db?.close(); } catch { /* already closed */ }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Fallback lane: the CLI's memory table. Content arrives clipped to 80 chars. */
|
|
210
|
+
function searchCli(terms, cwd) {
|
|
211
|
+
let r;
|
|
212
|
+
try {
|
|
213
|
+
r = runWyrm(['search', terms.join(' '), '--project', basename(cwd) || 'root', '--type', 'memories', '--limit', '10'],
|
|
214
|
+
{ timeout: 8000, encoding: 'utf8', env: { ...process.env, NO_COLOR: '1' } });
|
|
215
|
+
} catch { return []; }
|
|
216
|
+
if (r.status !== 0 || !r.stdout) return [];
|
|
217
|
+
const rows = [];
|
|
218
|
+
for (const line of r.stdout.replace(/\x1b\[[0-9;]*m/g, '').split('\n')) {
|
|
219
|
+
const m = line.match(/│\s*mem:(\d+)\s*│[^│]*│\s*([^│]*?)\s*│\s*(.*?)\s*│?\s*$/);
|
|
220
|
+
if (m) rows.push({ id: Number(m[1]), kind: m[2], text: m[3], haystack: m[3] });
|
|
221
|
+
}
|
|
222
|
+
return rows;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Drop other sessions' dedupe files once they are stale; best-effort. */
|
|
226
|
+
function reapStaleState() {
|
|
227
|
+
try {
|
|
228
|
+
const dir = tmpdir();
|
|
229
|
+
const now = Date.now();
|
|
230
|
+
for (const name of readdirSync(dir)) {
|
|
231
|
+
if (!name.startsWith(STATE_PREFIX) || !name.endsWith('.json')) continue;
|
|
232
|
+
const p = join(dir, name);
|
|
233
|
+
try { if (now - statSync(p).mtimeMs > STATE_TTL_MS) unlinkSync(p); } catch { /* raced; ignore */ }
|
|
234
|
+
}
|
|
235
|
+
} catch { /* never break the turn */ }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let payload = {};
|
|
239
|
+
try { payload = JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { /* no stdin */ }
|
|
240
|
+
if (!payload || typeof payload !== 'object') done();
|
|
241
|
+
|
|
242
|
+
const rawPrompt = typeof payload.prompt === 'string' ? payload.prompt.trim() : '';
|
|
243
|
+
if (isHarnessWrapper(rawPrompt)) done();
|
|
244
|
+
const prompt = stripReminders(rawPrompt);
|
|
245
|
+
if (prompt.length < MIN_CHARS || TRIVIAL.test(prompt)) done();
|
|
246
|
+
const terms = contentTerms(prompt);
|
|
247
|
+
if (terms.length === 0) done();
|
|
248
|
+
|
|
249
|
+
const cwd = (typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd()).replace(/\/+$/, '') || '/';
|
|
250
|
+
// The session id names a file; keep it to characters that cannot leave tmpdir.
|
|
251
|
+
const sessionKey = String(payload.session_id || 'nosession').replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64) || 'nosession';
|
|
252
|
+
const stateFile = join(tmpdir(), `${STATE_PREFIX}${sessionKey}.json`);
|
|
253
|
+
|
|
254
|
+
let sent = new Set();
|
|
255
|
+
try {
|
|
256
|
+
const prior = JSON.parse(readFileSync(stateFile, 'utf8'));
|
|
257
|
+
if (Array.isArray(prior)) sent = new Set(prior.map(String));
|
|
258
|
+
} catch {
|
|
259
|
+
reapStaleState(); // first prompt of this session: a cheap moment to tidy up
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let rows;
|
|
263
|
+
let lane = 'store';
|
|
264
|
+
try {
|
|
265
|
+
rows = await searchStore(terms, cwd);
|
|
266
|
+
if (!rows) { lane = 'cli'; rows = searchCli(terms, cwd); }
|
|
267
|
+
} catch { done(); }
|
|
268
|
+
|
|
269
|
+
// The CLI lane's content is clipped to 80 chars, so it cannot be held to the
|
|
270
|
+
// same overlap bar as full records.
|
|
271
|
+
const minShared = lane === 'store' && terms.length >= 3 ? 2 : 1;
|
|
272
|
+
const header = lane === 'store' ? '## Wyrm recall (auto, keyword match)' : '## Wyrm recall (auto)';
|
|
273
|
+
const lines = [];
|
|
274
|
+
const picked = [];
|
|
275
|
+
let used = header.length;
|
|
276
|
+
for (const r of rows) {
|
|
277
|
+
if (lines.length >= MAX_RECORDS) break;
|
|
278
|
+
if (!Number.isSafeInteger(r.id)) continue;
|
|
279
|
+
const typed = `mem:${r.id}`;
|
|
280
|
+
if (picked.includes(typed) || sent.has(typed)) continue;
|
|
281
|
+
if (/^\s*\[auto:/i.test(r.text)) continue;
|
|
282
|
+
if (sharedTerms(r.haystack, terms) < minShared) continue;
|
|
283
|
+
const line = `- ${typed} (${r.kind || 'memory'}) ${oneLine(r.text, LINE_CHARS)}`;
|
|
284
|
+
if (used + 1 + line.length > MAX_CHARS) break;
|
|
285
|
+
picked.push(typed);
|
|
286
|
+
lines.push(line);
|
|
287
|
+
used += 1 + line.length;
|
|
288
|
+
}
|
|
289
|
+
if (lines.length === 0) done();
|
|
290
|
+
|
|
291
|
+
// Commit only what was injected, so a record cut by the cap can still surface later.
|
|
292
|
+
for (const id of picked) sent.add(id);
|
|
293
|
+
try { writeFileSync(stateFile, JSON.stringify([...sent].slice(-2000))); } catch { /* never break the turn */ }
|
|
294
|
+
|
|
295
|
+
done({
|
|
296
|
+
hookSpecificOutput: {
|
|
297
|
+
hookEventName: 'UserPromptSubmit',
|
|
298
|
+
additionalContext: `${header}\n${lines.join('\n')}`,
|
|
299
|
+
},
|
|
300
|
+
});
|