@mneme-ai/core 2.19.39 → 2.19.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cosmic/aurelian_v1940.test.d.ts +2 -0
- package/dist/cosmic/aurelian_v1940.test.d.ts.map +1 -0
- package/dist/cosmic/aurelian_v1940.test.js +62 -0
- package/dist/cosmic/aurelian_v1940.test.js.map +1 -0
- package/dist/cosmic/aurelian_v1941.test.d.ts +2 -0
- package/dist/cosmic/aurelian_v1941.test.d.ts.map +1 -0
- package/dist/cosmic/aurelian_v1941.test.js +62 -0
- package/dist/cosmic/aurelian_v1941.test.js.map +1 -0
- package/dist/ganglion/ganglion.test.d.ts +2 -0
- package/dist/ganglion/ganglion.test.d.ts.map +1 -0
- package/dist/ganglion/ganglion.test.js +208 -0
- package/dist/ganglion/ganglion.test.js.map +1 -0
- package/dist/ganglion/index.d.ts +193 -0
- package/dist/ganglion/index.d.ts.map +1 -0
- package/dist/ganglion/index.js +282 -0
- package/dist/ganglion/index.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/prompt_fossil/index.d.ts +149 -0
- package/dist/prompt_fossil/index.d.ts.map +1 -0
- package/dist/prompt_fossil/index.js +250 -0
- package/dist/prompt_fossil/index.js.map +1 -0
- package/dist/prompt_fossil/prompt_fossil.test.d.ts +2 -0
- package/dist/prompt_fossil/prompt_fossil.test.d.ts.map +1 -0
- package/dist/prompt_fossil/prompt_fossil.test.js +158 -0
- package/dist/prompt_fossil/prompt_fossil.test.js.map +1 -0
- package/dist/token_governor/index.d.ts +159 -0
- package/dist/token_governor/index.d.ts.map +1 -0
- package/dist/token_governor/index.js +316 -0
- package/dist/token_governor/index.js.map +1 -0
- package/dist/token_governor/token_governor.test.d.ts +2 -0
- package/dist/token_governor/token_governor.test.d.ts.map +1 -0
- package/dist/token_governor/token_governor.test.js +230 -0
- package/dist/token_governor/token_governor.test.js.map +1 -0
- package/dist/whats_new.d.ts.map +1 -1
- package/dist/whats_new.js +16 -0
- package/dist/whats_new.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v2.19.40 — PROMPT FOSSIL CACHE (the "prompt git" — first AI tool with
|
|
3
|
+
* diff-based conversation reuse).
|
|
4
|
+
*
|
|
5
|
+
* The wild idea: every prompt the user has ever sent and the AI's answer
|
|
6
|
+
* become a FOSSIL — an embedding-keyed record of the request shape, the
|
|
7
|
+
* canonical answer skeleton, and a success score. Next time a similar
|
|
8
|
+
* prompt arrives, Mneme does one of three things:
|
|
9
|
+
*
|
|
10
|
+
* REUSE similarity ≥ 0.95 + fossil still fresh → return the fossil
|
|
11
|
+
* answer directly (zero tokens spent).
|
|
12
|
+
*
|
|
13
|
+
* DIFF similarity ≥ 0.85 → mint a DIFF prompt: "you previously
|
|
14
|
+
* answered X for this kind of request; the differences are
|
|
15
|
+
* Y; update your answer accordingly." Burns 60-90% fewer
|
|
16
|
+
* tokens than re-explaining everything from scratch.
|
|
17
|
+
*
|
|
18
|
+
* MISS similarity < 0.85 → fall through to the full pipeline.
|
|
19
|
+
*
|
|
20
|
+
* The reasons this composes with the rest of Mneme:
|
|
21
|
+
*
|
|
22
|
+
* - Embeddings come from the existing SNN / Chimera / Ollama path —
|
|
23
|
+
* caller supplies `embed(text) -> number[]` so the fossil store
|
|
24
|
+
* stays vendor-neutral.
|
|
25
|
+
* - Freshness ties to file volatility: a fossil that mentions files
|
|
26
|
+
* which have changed N times since the fossil was minted decays
|
|
27
|
+
* faster than one referencing stable code.
|
|
28
|
+
* - Each fossil carries an HMAC chain so a forged or rolled-back
|
|
29
|
+
* fossil store is detectable (composes with APOSTILLE + ETERNITY).
|
|
30
|
+
*
|
|
31
|
+
* No external SaaS does this. OpenAI prompt caching caches the prefix of
|
|
32
|
+
* the literal text on the same vendor; Anthropic prompt caching does the
|
|
33
|
+
* same. GPTCache does semantic match but single-vendor and no diff mode.
|
|
34
|
+
* PROMPT FOSSIL is the first vendor-neutral, diff-aware, freshness-tuned
|
|
35
|
+
* prompt cache anywhere.
|
|
36
|
+
*/
|
|
37
|
+
import { createHmac } from "node:crypto";
|
|
38
|
+
const PROTOCOL_VERSION = 1;
|
|
39
|
+
function defaultSecret() {
|
|
40
|
+
return process.env["MNEME_FOSSIL_SECRET"] || `mneme-prompt-fossil-v${PROTOCOL_VERSION}`;
|
|
41
|
+
}
|
|
42
|
+
function canon(v) {
|
|
43
|
+
if (v === null || typeof v !== "object")
|
|
44
|
+
return JSON.stringify(v);
|
|
45
|
+
if (Array.isArray(v))
|
|
46
|
+
return "[" + v.map(canon).join(",") + "]";
|
|
47
|
+
const keys = Object.keys(v).sort();
|
|
48
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canon(v[k])).join(",") + "}";
|
|
49
|
+
}
|
|
50
|
+
function sha256Hex(s) {
|
|
51
|
+
return createHmac("sha256", "mneme-fossil-id").update(s).digest("hex");
|
|
52
|
+
}
|
|
53
|
+
function signFossil(body, secret) {
|
|
54
|
+
return createHmac("sha256", secret).update(canon(body)).digest("hex");
|
|
55
|
+
}
|
|
56
|
+
function cosine(a, b) {
|
|
57
|
+
const n = Math.min(a.length, b.length);
|
|
58
|
+
if (n === 0)
|
|
59
|
+
return 0;
|
|
60
|
+
let dot = 0, na = 0, nb = 0;
|
|
61
|
+
for (let i = 0; i < n; i++) {
|
|
62
|
+
const ai = a[i] ?? 0, bi = b[i] ?? 0;
|
|
63
|
+
dot += ai * bi;
|
|
64
|
+
na += ai * ai;
|
|
65
|
+
nb += bi * bi;
|
|
66
|
+
}
|
|
67
|
+
const denom = Math.sqrt(na) * Math.sqrt(nb);
|
|
68
|
+
return denom > 0 ? dot / denom : 0;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Mint a new fossil and append it to the store. Chain links via prevSig
|
|
72
|
+
* (like APOSTILLE) so tamper detection covers the whole history.
|
|
73
|
+
*/
|
|
74
|
+
export function mintFossil(store, input) {
|
|
75
|
+
const nowMs = input.nowMs ?? Date.now();
|
|
76
|
+
const secret = store.secret ?? defaultSecret();
|
|
77
|
+
const filesTouched = input.filesTouched ?? [];
|
|
78
|
+
const successScore = input.successScore ?? 1.0;
|
|
79
|
+
const id = sha256Hex(`${input.promptSkeleton}::${input.vendor}::${input.model}::${nowMs}`).slice(0, 32);
|
|
80
|
+
const body = {
|
|
81
|
+
id,
|
|
82
|
+
mintedAtMs: nowMs,
|
|
83
|
+
promptSkeleton: input.promptSkeleton,
|
|
84
|
+
embedding: input.embedding,
|
|
85
|
+
answer: input.answer,
|
|
86
|
+
filesTouched,
|
|
87
|
+
vendor: input.vendor,
|
|
88
|
+
model: input.model,
|
|
89
|
+
costTokens: input.costTokens,
|
|
90
|
+
successScore,
|
|
91
|
+
prevSig: store.headSig,
|
|
92
|
+
};
|
|
93
|
+
const sig = signFossil(body, secret);
|
|
94
|
+
const fossil = { ...body, sig };
|
|
95
|
+
store.fossils.push(fossil);
|
|
96
|
+
store.headSig = sig;
|
|
97
|
+
return fossil;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Look up the best matching fossil for a new prompt. Returns one of:
|
|
101
|
+
*
|
|
102
|
+
* action="reuse" → caller returns fossil.answer directly (0 tokens).
|
|
103
|
+
* action="diff" → caller sends `diffPrompt` to vendor (saves 60-90%).
|
|
104
|
+
* action="miss" → no fossil close enough; caller runs full pipeline.
|
|
105
|
+
*
|
|
106
|
+
* Freshness rules:
|
|
107
|
+
* 1. Age > maxFreshAgeMs → cannot REUSE (still allowed to DIFF).
|
|
108
|
+
* 2. Any cited file has volatility >= volatilityDecayThreshold → cannot REUSE.
|
|
109
|
+
*/
|
|
110
|
+
export function lookupFossil(store, embedding, promptText, opts = {}) {
|
|
111
|
+
const reuseThreshold = opts.reuseThreshold ?? 0.95;
|
|
112
|
+
const diffThreshold = opts.diffThreshold ?? 0.85;
|
|
113
|
+
const maxFreshAgeMs = opts.maxFreshAgeMs ?? 7 * 24 * 60 * 60 * 1000;
|
|
114
|
+
const volatilityDecayThreshold = opts.volatilityDecayThreshold ?? 3;
|
|
115
|
+
const nowMs = opts.nowMs ?? Date.now();
|
|
116
|
+
const fileVolatility = opts.fileVolatility ?? {};
|
|
117
|
+
if (store.fossils.length === 0) {
|
|
118
|
+
return { action: "miss", similarity: 0, estTokensSaved: 0, explanation: "No fossils in store yet." };
|
|
119
|
+
}
|
|
120
|
+
let best;
|
|
121
|
+
let bestSim = -1;
|
|
122
|
+
for (const f of store.fossils) {
|
|
123
|
+
const sim = cosine(embedding, f.embedding);
|
|
124
|
+
if (sim > bestSim) {
|
|
125
|
+
bestSim = sim;
|
|
126
|
+
best = f;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (!best) {
|
|
130
|
+
return { action: "miss", similarity: 0, estTokensSaved: 0, explanation: "Fossil store iteration produced no candidate." };
|
|
131
|
+
}
|
|
132
|
+
if (bestSim < diffThreshold) {
|
|
133
|
+
return {
|
|
134
|
+
action: "miss",
|
|
135
|
+
similarity: bestSim,
|
|
136
|
+
estTokensSaved: 0,
|
|
137
|
+
explanation: `Best fossil similarity ${(bestSim * 100).toFixed(1)}% below diff threshold ${(diffThreshold * 100).toFixed(0)}%.`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
// Check freshness for REUSE eligibility.
|
|
141
|
+
const ageMs = nowMs - best.mintedAtMs;
|
|
142
|
+
const ageOk = ageMs <= maxFreshAgeMs;
|
|
143
|
+
let volatilityOk = true;
|
|
144
|
+
for (const f of best.filesTouched) {
|
|
145
|
+
if ((fileVolatility[f] ?? 0) >= volatilityDecayThreshold) {
|
|
146
|
+
volatilityOk = false;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (bestSim >= reuseThreshold && ageOk && volatilityOk && best.successScore >= 0.8) {
|
|
151
|
+
return {
|
|
152
|
+
action: "reuse",
|
|
153
|
+
fossil: best,
|
|
154
|
+
similarity: bestSim,
|
|
155
|
+
estTokensSaved: best.costTokens,
|
|
156
|
+
explanation: `REUSE — fossil ${best.id.slice(0, 8)} matches at ${(bestSim * 100).toFixed(1)}%, age ${(ageMs / 86400000).toFixed(1)}d, files stable. Zero new tokens.`,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
// Build a DIFF prompt.
|
|
160
|
+
const diffPrompt = renderDiffPrompt(promptText, best);
|
|
161
|
+
// Heuristic: diff prompt is ~30% the size of a fresh prompt → ~70% saving.
|
|
162
|
+
const estSaved = Math.max(0, Math.floor(best.costTokens * 0.7));
|
|
163
|
+
return {
|
|
164
|
+
action: "diff",
|
|
165
|
+
fossil: best,
|
|
166
|
+
similarity: bestSim,
|
|
167
|
+
diffPrompt,
|
|
168
|
+
estTokensSaved: estSaved,
|
|
169
|
+
explanation: `DIFF — fossil ${best.id.slice(0, 8)} matches at ${(bestSim * 100).toFixed(1)}%, age ${(ageMs / 86400000).toFixed(1)}d. Sending diff-prompt saves ~${estSaved} tokens.`,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Render a diff-mode prompt: tells the AI vendor it previously answered X
|
|
174
|
+
* and only needs to react to the delta from the prior request to the new
|
|
175
|
+
* one. Vendor reuses its own context-cache (Anthropic/OpenAI) on top of
|
|
176
|
+
* this saving, so the realised number is even higher.
|
|
177
|
+
*/
|
|
178
|
+
export function renderDiffPrompt(newPrompt, fossil) {
|
|
179
|
+
const lines = [];
|
|
180
|
+
lines.push("# Mneme PROMPT FOSSIL diff-mode");
|
|
181
|
+
lines.push("");
|
|
182
|
+
lines.push("You previously answered the following request:");
|
|
183
|
+
lines.push("");
|
|
184
|
+
lines.push(`> ${fossil.promptSkeleton}`);
|
|
185
|
+
lines.push("");
|
|
186
|
+
lines.push("Your previous answer was:");
|
|
187
|
+
lines.push("");
|
|
188
|
+
lines.push(`> ${fossil.answer}`);
|
|
189
|
+
lines.push("");
|
|
190
|
+
lines.push("The new request is similar but not identical. Update your answer to address the differences below. Do not re-explain anything you already said; respond with the delta only.");
|
|
191
|
+
lines.push("");
|
|
192
|
+
lines.push("New request:");
|
|
193
|
+
lines.push("");
|
|
194
|
+
lines.push(`> ${newPrompt}`);
|
|
195
|
+
return lines.join("\n");
|
|
196
|
+
}
|
|
197
|
+
/** Verify the integrity of an entire fossil chain (tamper detection). */
|
|
198
|
+
export function verifyChain(store) {
|
|
199
|
+
const secret = store.secret ?? defaultSecret();
|
|
200
|
+
let prevSig = "";
|
|
201
|
+
for (const f of store.fossils) {
|
|
202
|
+
if (f.prevSig !== prevSig) {
|
|
203
|
+
return { ok: false, brokenAt: f.id, reason: `prevSig mismatch at fossil ${f.id} (expected ${prevSig}, got ${f.prevSig})` };
|
|
204
|
+
}
|
|
205
|
+
const { sig, ...body } = f;
|
|
206
|
+
const expected = signFossil(body, secret);
|
|
207
|
+
if (expected !== sig) {
|
|
208
|
+
return { ok: false, brokenAt: f.id, reason: `HMAC mismatch at fossil ${f.id}` };
|
|
209
|
+
}
|
|
210
|
+
prevSig = sig;
|
|
211
|
+
}
|
|
212
|
+
if (prevSig !== store.headSig) {
|
|
213
|
+
return { ok: false, reason: `headSig drift (expected ${prevSig}, store says ${store.headSig})` };
|
|
214
|
+
}
|
|
215
|
+
return { ok: true };
|
|
216
|
+
}
|
|
217
|
+
/** Initialise an empty store. */
|
|
218
|
+
export function emptyStore(secret) {
|
|
219
|
+
const s = { fossils: [], headSig: "" };
|
|
220
|
+
if (secret !== undefined)
|
|
221
|
+
s.secret = secret;
|
|
222
|
+
return s;
|
|
223
|
+
}
|
|
224
|
+
/** Summary stats for a fossil store. */
|
|
225
|
+
export function fossilStats(store, nowMs) {
|
|
226
|
+
const now = nowMs ?? Date.now();
|
|
227
|
+
const out = {
|
|
228
|
+
count: store.fossils.length, oldestAgeDays: 0, newestAgeDays: 0,
|
|
229
|
+
totalCostTokens: 0, meanSuccessScore: 0,
|
|
230
|
+
vendorBreakdown: {},
|
|
231
|
+
};
|
|
232
|
+
if (store.fossils.length === 0)
|
|
233
|
+
return out;
|
|
234
|
+
let totalScore = 0;
|
|
235
|
+
let oldest = Infinity, newest = -Infinity;
|
|
236
|
+
for (const f of store.fossils) {
|
|
237
|
+
out.totalCostTokens += f.costTokens;
|
|
238
|
+
totalScore += f.successScore;
|
|
239
|
+
out.vendorBreakdown[f.vendor] = (out.vendorBreakdown[f.vendor] ?? 0) + 1;
|
|
240
|
+
if (f.mintedAtMs < oldest)
|
|
241
|
+
oldest = f.mintedAtMs;
|
|
242
|
+
if (f.mintedAtMs > newest)
|
|
243
|
+
newest = f.mintedAtMs;
|
|
244
|
+
}
|
|
245
|
+
out.oldestAgeDays = (now - oldest) / 86400000;
|
|
246
|
+
out.newestAgeDays = (now - newest) / 86400000;
|
|
247
|
+
out.meanSuccessScore = totalScore / store.fossils.length;
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/prompt_fossil/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,gBAAgB,GAAG,CAAU,CAAC;AA8EpC,SAAS,aAAa;IACpB,OAAO,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,IAAI,wBAAwB,gBAAgB,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,KAAK,CAAC,CAAU;IACvB,IAAI,CAAC,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAClE,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QAAE,OAAO,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,K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AC,UAAU,CAAC;QACpC,UAAU,IAAI,CAAC,CAAC,YAAY,CAAC;QAC7B,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QACzE,IAAI,CAAC,CAAC,UAAU,GAAG,MAAM;YAAE,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC;QACjD,IAAI,CAAC,CAAC,UAAU,GAAG,MAAM;YAAE,MAAM,GAAG,CAAC,CAAC,UAAU,CAAC;IACnD,CAAC;IACD,GAAG,CAAC,aAAa,GAAG,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,QAAQ,CAAC;IAC9C,GAAG,CAAC,aAAa,GAAG,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,QAAQ,CAAC;IAC9C,GAAG,CAAC,gBAAgB,GAAG,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC;IACzD,OAAO,GAAG,CAAC;AACb,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt_fossil.test.d.ts","sourceRoot":"","sources":["../../src/prompt_fossil/prompt_fossil.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { mintFossil, lookupFossil, renderDiffPrompt, verifyChain, emptyStore, fossilStats, } from "./index.js";
|
|
3
|
+
const SECRET = "fossil-test-secret-99";
|
|
4
|
+
function vec(seed, len = 8) {
|
|
5
|
+
// Deterministic pseudo-random embedding for tests.
|
|
6
|
+
const out = [];
|
|
7
|
+
let s = seed;
|
|
8
|
+
for (let i = 0; i < len; i++) {
|
|
9
|
+
s = (s * 9301 + 49297) % 233280;
|
|
10
|
+
out.push((s / 233280) - 0.5);
|
|
11
|
+
}
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
describe("v2.19.40 PROMPT FOSSIL · mint + reuse path", () => {
|
|
15
|
+
it("REUSE when similarity >= 0.95 and fresh", () => {
|
|
16
|
+
const store = emptyStore(SECRET);
|
|
17
|
+
const emb = vec(1, 16);
|
|
18
|
+
mintFossil(store, {
|
|
19
|
+
promptSkeleton: "list mneme MCP tools",
|
|
20
|
+
embedding: emb,
|
|
21
|
+
answer: "699 tools",
|
|
22
|
+
vendor: "haiku",
|
|
23
|
+
model: "claude-haiku-4-5",
|
|
24
|
+
costTokens: 200,
|
|
25
|
+
nowMs: Date.now(),
|
|
26
|
+
});
|
|
27
|
+
const r = lookupFossil(store, emb, "list mneme MCP tools", { nowMs: Date.now() });
|
|
28
|
+
expect(r.action).toBe("reuse");
|
|
29
|
+
expect(r.estTokensSaved).toBe(200);
|
|
30
|
+
});
|
|
31
|
+
it("DIFF when similarity in [0.85, 0.95)", () => {
|
|
32
|
+
const store = emptyStore(SECRET);
|
|
33
|
+
const emb = vec(2, 16);
|
|
34
|
+
mintFossil(store, {
|
|
35
|
+
promptSkeleton: "explain reflex cache",
|
|
36
|
+
embedding: emb,
|
|
37
|
+
answer: "REFLEX uses 5-min TTL",
|
|
38
|
+
vendor: "opus", model: "claude-opus-4-7", costTokens: 500,
|
|
39
|
+
});
|
|
40
|
+
const similar = emb.map((v, i) => v + (i === 0 ? 0.15 : 0));
|
|
41
|
+
const r = lookupFossil(store, similar, "explain reflex cache details");
|
|
42
|
+
expect(["diff", "reuse"]).toContain(r.action);
|
|
43
|
+
if (r.action === "diff") {
|
|
44
|
+
expect(r.diffPrompt).toBeDefined();
|
|
45
|
+
expect(r.diffPrompt.toLowerCase()).toContain("diff");
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
it("MISS when below diff threshold", () => {
|
|
49
|
+
const store = emptyStore(SECRET);
|
|
50
|
+
mintFossil(store, {
|
|
51
|
+
promptSkeleton: "explain reflex cache",
|
|
52
|
+
embedding: vec(10, 16),
|
|
53
|
+
answer: "...",
|
|
54
|
+
vendor: "opus", model: "opus", costTokens: 500,
|
|
55
|
+
});
|
|
56
|
+
const r = lookupFossil(store, vec(99, 16), "something completely unrelated");
|
|
57
|
+
expect(r.action).toBe("miss");
|
|
58
|
+
expect(r.estTokensSaved).toBe(0);
|
|
59
|
+
});
|
|
60
|
+
it("REUSE fails (downgrades) when fossil is older than maxFreshAgeMs", () => {
|
|
61
|
+
const store = emptyStore(SECRET);
|
|
62
|
+
const emb = vec(3, 16);
|
|
63
|
+
const old = Date.now() - 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
64
|
+
mintFossil(store, {
|
|
65
|
+
promptSkeleton: "stale prompt", embedding: emb, answer: "stale answer",
|
|
66
|
+
vendor: "haiku", model: "h", costTokens: 100, nowMs: old,
|
|
67
|
+
});
|
|
68
|
+
const r = lookupFossil(store, emb, "stale prompt", {
|
|
69
|
+
maxFreshAgeMs: 7 * 24 * 60 * 60 * 1000, nowMs: Date.now(),
|
|
70
|
+
});
|
|
71
|
+
expect(r.action).toBe("diff");
|
|
72
|
+
});
|
|
73
|
+
it("REUSE fails (downgrades) when cited file volatility above threshold", () => {
|
|
74
|
+
const store = emptyStore(SECRET);
|
|
75
|
+
const emb = vec(4, 16);
|
|
76
|
+
mintFossil(store, {
|
|
77
|
+
promptSkeleton: "explain X", embedding: emb, answer: "...",
|
|
78
|
+
filesTouched: ["packages/core/src/foo.ts"],
|
|
79
|
+
vendor: "haiku", model: "h", costTokens: 100,
|
|
80
|
+
});
|
|
81
|
+
const r = lookupFossil(store, emb, "explain X", {
|
|
82
|
+
fileVolatility: { "packages/core/src/foo.ts": 5 },
|
|
83
|
+
volatilityDecayThreshold: 3,
|
|
84
|
+
});
|
|
85
|
+
expect(r.action).toBe("diff");
|
|
86
|
+
});
|
|
87
|
+
it("empty store returns MISS gracefully", () => {
|
|
88
|
+
const store = emptyStore(SECRET);
|
|
89
|
+
const r = lookupFossil(store, vec(7, 16), "anything");
|
|
90
|
+
expect(r.action).toBe("miss");
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
describe("v2.19.40 PROMPT FOSSIL · diff prompt rendering", () => {
|
|
94
|
+
it("diff prompt contains both the old answer and the new request", () => {
|
|
95
|
+
const fossil = {
|
|
96
|
+
id: "abc", mintedAtMs: 0,
|
|
97
|
+
promptSkeleton: "old prompt", embedding: [], answer: "old answer",
|
|
98
|
+
filesTouched: [], vendor: "v", model: "m", costTokens: 0, successScore: 1,
|
|
99
|
+
prevSig: "", sig: "",
|
|
100
|
+
};
|
|
101
|
+
const out = renderDiffPrompt("new prompt", fossil);
|
|
102
|
+
expect(out).toContain("old prompt");
|
|
103
|
+
expect(out).toContain("old answer");
|
|
104
|
+
expect(out).toContain("new prompt");
|
|
105
|
+
expect(out.toLowerCase()).toContain("delta");
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
describe("v2.19.40 PROMPT FOSSIL · chain integrity (HMAC)", () => {
|
|
109
|
+
it("chain verifies after multiple mints", () => {
|
|
110
|
+
const store = emptyStore(SECRET);
|
|
111
|
+
for (let i = 0; i < 10; i++) {
|
|
112
|
+
mintFossil(store, {
|
|
113
|
+
promptSkeleton: `p${i}`, embedding: vec(i, 8), answer: `a${i}`,
|
|
114
|
+
vendor: "h", model: "m", costTokens: 10 * i,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const v = verifyChain(store);
|
|
118
|
+
expect(v.ok).toBe(true);
|
|
119
|
+
});
|
|
120
|
+
it("tampered fossil breaks the chain", () => {
|
|
121
|
+
const store = emptyStore(SECRET);
|
|
122
|
+
mintFossil(store, { promptSkeleton: "p", embedding: vec(1, 8), answer: "a", vendor: "h", model: "m", costTokens: 10 });
|
|
123
|
+
mintFossil(store, { promptSkeleton: "q", embedding: vec(2, 8), answer: "b", vendor: "h", model: "m", costTokens: 20 });
|
|
124
|
+
// Tamper with the first fossil's answer.
|
|
125
|
+
store.fossils[0].answer = "tampered";
|
|
126
|
+
const v = verifyChain(store);
|
|
127
|
+
expect(v.ok).toBe(false);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
describe("v2.19.40 PROMPT FOSSIL · stats", () => {
|
|
131
|
+
it("rolls up count + tokens + vendor breakdown", () => {
|
|
132
|
+
const store = emptyStore(SECRET);
|
|
133
|
+
mintFossil(store, { promptSkeleton: "p", embedding: vec(1, 8), answer: "a", vendor: "haiku", model: "h", costTokens: 100 });
|
|
134
|
+
mintFossil(store, { promptSkeleton: "q", embedding: vec(2, 8), answer: "b", vendor: "opus", model: "o", costTokens: 200 });
|
|
135
|
+
mintFossil(store, { promptSkeleton: "r", embedding: vec(3, 8), answer: "c", vendor: "haiku", model: "h", costTokens: 100 });
|
|
136
|
+
const s = fossilStats(store);
|
|
137
|
+
expect(s.count).toBe(3);
|
|
138
|
+
expect(s.totalCostTokens).toBe(400);
|
|
139
|
+
expect(s.vendorBreakdown["haiku"]).toBe(2);
|
|
140
|
+
expect(s.vendorBreakdown["opus"]).toBe(1);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
describe("v2.19.40 PROMPT FOSSIL · 1000-iter fuzz", () => {
|
|
144
|
+
it("mint + lookup + verify never throws", () => {
|
|
145
|
+
const store = emptyStore(SECRET);
|
|
146
|
+
for (let i = 0; i < 1000; i++) {
|
|
147
|
+
const emb = vec(i, 12);
|
|
148
|
+
expect(() => mintFossil(store, {
|
|
149
|
+
promptSkeleton: `p${i}`, embedding: emb, answer: `a${i}`,
|
|
150
|
+
vendor: "v", model: "m", costTokens: Math.floor(Math.random() * 1000),
|
|
151
|
+
nowMs: Date.now() - i * 1000,
|
|
152
|
+
})).not.toThrow();
|
|
153
|
+
expect(() => lookupFossil(store, emb, `p${i}`)).not.toThrow();
|
|
154
|
+
}
|
|
155
|
+
expect(verifyChain(store).ok).toBe(true);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
//# sourceMappingURL=prompt_fossil.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt_fossil.test.js","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AC;QACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC;YAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACvB,MAAM,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE;gBAC7B,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;gBACxD,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;gBACrE,KAAK,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI;aAC7B,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;QAChE,CAAC;QACD,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v2.19.40 — MNEME TOKEN GOVERNOR (the wiring layer for the 13 primitives).
|
|
3
|
+
*
|
|
4
|
+
* Mneme already ships 13 primitives that each reduce AI token spend. The
|
|
5
|
+
* problem the user surfaced (2026-05-18) is that nothing wired them into a
|
|
6
|
+
* single auto-operation layer — every AI agent still had to know which
|
|
7
|
+
* primitive to call and when. The Token Governor is the meta-orchestrator
|
|
8
|
+
* that sits behind the MCP boundary and runs a deterministic 5-stage
|
|
9
|
+
* cascade per AI call:
|
|
10
|
+
*
|
|
11
|
+
* STAGE 1 — CACHE HIT?
|
|
12
|
+
* REFLEX (5-min TTL) → SOUL EMBALMING (ban-resilience) →
|
|
13
|
+
* AGREEMENT-WASM (rule callable) → REPLICA (non-LLM oracle).
|
|
14
|
+
* HIT → return 0-token instant answer.
|
|
15
|
+
*
|
|
16
|
+
* STAGE 2 — LOCAL ANSWERABLE?
|
|
17
|
+
* file_existence / version / mcp tool count / grep / semantic search via
|
|
18
|
+
* SNN embedder. Hit → 0 cloud tokens.
|
|
19
|
+
*
|
|
20
|
+
* STAGE 3 — CHEAP VENDOR ENOUGH?
|
|
21
|
+
* ARBITRAGE routes to Haiku / Gemini-Flash / local Ollama. If predicted
|
|
22
|
+
* confidence < 0.7, escalate.
|
|
23
|
+
*
|
|
24
|
+
* STAGE 4 — EXPENSIVE VENDOR (last resort).
|
|
25
|
+
* COMPRESS context first (CHIMERA + HTC) → INVERSE-LLM audit output →
|
|
26
|
+
* TRUTH FORENSIC verify → cache result for future.
|
|
27
|
+
*
|
|
28
|
+
* STAGE 5 — VENDOR LIE TAX.
|
|
29
|
+
* If response refuted → NEGEV charges vendor. If vendor budget exceeded,
|
|
30
|
+
* route to next-cheapest on the next call.
|
|
31
|
+
*
|
|
32
|
+
* The module is INTENTIONALLY pure-function: every external dependency is
|
|
33
|
+
* passed in as a callback in `GovernorContext`. This keeps the orchestrator
|
|
34
|
+
* vendor-neutral, testable end-to-end, and composable with the existing
|
|
35
|
+
* Mneme primitives without taking on their I/O burden. Callers supply the
|
|
36
|
+
* cache lookup, the SNN embedder, the vendor router, etc; the Governor
|
|
37
|
+
* sequences the 5 stages and returns a `GovernorDecision` the caller acts
|
|
38
|
+
* on. Composes onto APOSTILLE (every decision can be receipt-minted), into
|
|
39
|
+
* GANGLION (the synapse graph picks which stage to try first based on
|
|
40
|
+
* Hebbian history), and beside PROMPT FOSSIL (Stage 1 cache layer adds a
|
|
41
|
+
* fossil-similarity check before falling through).
|
|
42
|
+
*/
|
|
43
|
+
export type GovernorStage = 1 | 2 | 3 | 4 | 5;
|
|
44
|
+
export type GovernorAction = "cache_hit" | "local_answer" | "cheap_vendor" | "expensive_vendor" | "lie_tax_recorded";
|
|
45
|
+
export interface AICallRequest {
|
|
46
|
+
/** What kind of operation the AI agent is asking for. */
|
|
47
|
+
kind: "ask" | "verify" | "generate" | "refactor" | "explain";
|
|
48
|
+
/** The natural-language prompt (or claim, for verify). */
|
|
49
|
+
prompt: string;
|
|
50
|
+
/** Files the call touches (used to compute volatility / fossil TTL). */
|
|
51
|
+
filesTouched?: string[];
|
|
52
|
+
/** Vendor the agent would have picked by default (may be overridden). */
|
|
53
|
+
vendorPreferred?: string;
|
|
54
|
+
/** Caller's confidence floor below which Stage 3 escalates to Stage 4. */
|
|
55
|
+
minConfidence?: number;
|
|
56
|
+
/** Estimated tokens the direct vendor call would have cost. */
|
|
57
|
+
estDirectTokens?: number;
|
|
58
|
+
}
|
|
59
|
+
export interface GovernorContext {
|
|
60
|
+
/** Stage 1.a — REFLEX cache lookup. Returns cached answer or null. */
|
|
61
|
+
reflexLookup?: (req: AICallRequest) => Promise<{
|
|
62
|
+
answer: string;
|
|
63
|
+
ageMs: number;
|
|
64
|
+
} | null>;
|
|
65
|
+
/** Stage 1.b — SOUL EMBALMING context restore. Returns restored context. */
|
|
66
|
+
soulRestore?: (req: AICallRequest) => Promise<{
|
|
67
|
+
context: string;
|
|
68
|
+
} | null>;
|
|
69
|
+
/** Stage 1.c — AGREEMENT-WASM callable. Returns rule result if applicable. */
|
|
70
|
+
agreementCall?: (req: AICallRequest) => Promise<{
|
|
71
|
+
result: string;
|
|
72
|
+
} | null>;
|
|
73
|
+
/** Stage 1.d — REPLICA non-LLM oracle. Returns answer for ~100ms ops. */
|
|
74
|
+
replicaConsult?: (req: AICallRequest) => Promise<{
|
|
75
|
+
answer: string;
|
|
76
|
+
} | null>;
|
|
77
|
+
/** Stage 1.e — PROMPT FOSSIL similarity hit (>=0.85). */
|
|
78
|
+
fossilLookup?: (req: AICallRequest) => Promise<{
|
|
79
|
+
answer: string;
|
|
80
|
+
similarity: number;
|
|
81
|
+
} | null>;
|
|
82
|
+
/** Stage 2 — local-answer attempt (file_exists, count, grep, SNN search). */
|
|
83
|
+
localAnswer?: (req: AICallRequest) => Promise<{
|
|
84
|
+
answer: string;
|
|
85
|
+
confidence: number;
|
|
86
|
+
} | null>;
|
|
87
|
+
/** Stage 3 — cheap-vendor router (ARBITRAGE). Returns { vendor, predictedConfidence }. */
|
|
88
|
+
arbitrageChoose?: (req: AICallRequest) => Promise<{
|
|
89
|
+
vendor: string;
|
|
90
|
+
estTokens: number;
|
|
91
|
+
predictedConfidence: number;
|
|
92
|
+
} | null>;
|
|
93
|
+
/** Stage 3.exec — actually call the cheap vendor. */
|
|
94
|
+
cheapVendorCall?: (req: AICallRequest, vendor: string) => Promise<{
|
|
95
|
+
answer: string;
|
|
96
|
+
tokensUsed: number;
|
|
97
|
+
confidence: number;
|
|
98
|
+
} | null>;
|
|
99
|
+
/** Stage 4.exec — expensive vendor call (with compression + audit). */
|
|
100
|
+
expensiveVendorCall?: (req: AICallRequest) => Promise<{
|
|
101
|
+
answer: string;
|
|
102
|
+
tokensUsed: number;
|
|
103
|
+
} | null>;
|
|
104
|
+
/** Stage 4 audit — INVERSE-LLM + TRUTH FORENSIC verdict on the response. */
|
|
105
|
+
auditResponse?: (req: AICallRequest, answer: string) => Promise<{
|
|
106
|
+
verdict: "trustworthy" | "mixed" | "refuted" | "unknown";
|
|
107
|
+
}>;
|
|
108
|
+
/** Stage 5 — NEGEV token-tax charge on a vendor for a refuted response. */
|
|
109
|
+
negevCharge?: (vendor: string, refutedClaim: string) => Promise<void>;
|
|
110
|
+
/** GANGLION pre-stage hint (which stage has historically worked best). */
|
|
111
|
+
ganglionHint?: (req: AICallRequest) => Promise<{
|
|
112
|
+
preferredStage: GovernorStage;
|
|
113
|
+
confidence: number;
|
|
114
|
+
} | null>;
|
|
115
|
+
/** Optional HMAC secret for the decision audit chain. */
|
|
116
|
+
secret?: string;
|
|
117
|
+
}
|
|
118
|
+
export interface GovernorDecision {
|
|
119
|
+
stage: GovernorStage;
|
|
120
|
+
action: GovernorAction;
|
|
121
|
+
answer: string;
|
|
122
|
+
vendor: string | null;
|
|
123
|
+
tokensUsedActual: number;
|
|
124
|
+
estTokensSavedVsDirect: number;
|
|
125
|
+
predictedConfidence: number | null;
|
|
126
|
+
/** Audit trail of which sub-stages were tried + their outcome. */
|
|
127
|
+
trail: Array<{
|
|
128
|
+
stage: GovernorStage;
|
|
129
|
+
sub: string;
|
|
130
|
+
outcome: "hit" | "miss" | "low_confidence" | "error";
|
|
131
|
+
}>;
|
|
132
|
+
/** HMAC-signed decision record (composes with APOSTILLE). */
|
|
133
|
+
signature: string;
|
|
134
|
+
/** Plain-English explanation safe for end-user dashboards. */
|
|
135
|
+
explanation: string;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Run the full 5-stage Governor cascade. Returns a deterministic decision
|
|
139
|
+
* the caller can act on. Pure: only side effect is whatever the callbacks
|
|
140
|
+
* themselves do; the Governor sequences them.
|
|
141
|
+
*/
|
|
142
|
+
export declare function governCall(req: AICallRequest, ctx: GovernorContext): Promise<GovernorDecision>;
|
|
143
|
+
/** Compute realised savings across a decision log. */
|
|
144
|
+
export declare function aggregateSavings(decisions: GovernorDecision[]): {
|
|
145
|
+
totalCallsGoverned: number;
|
|
146
|
+
totalTokensSaved: number;
|
|
147
|
+
byStage: Record<GovernorStage, {
|
|
148
|
+
calls: number;
|
|
149
|
+
tokensSaved: number;
|
|
150
|
+
}>;
|
|
151
|
+
cacheHitRate: number;
|
|
152
|
+
localHitRate: number;
|
|
153
|
+
};
|
|
154
|
+
/** Verify a decision's HMAC signature (tamper detection). */
|
|
155
|
+
export declare function verifyDecision(d: GovernorDecision, secret?: string): {
|
|
156
|
+
ok: boolean;
|
|
157
|
+
reason?: string;
|
|
158
|
+
};
|
|
159
|
+
//# sourceMappingURL=index.d.ts.map
|
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