@mneme-ai/core 2.106.0 → 2.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"archaeology.test.js","sourceRoot":"","sources":["../../src/archaeology/archaeology.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEnI,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAExB,QAAQ,CAAC,oDAAoD,EAAE,GAAG,EAAE;IAClE,EAAE,CAAC,mDAAmD,EAAE,GAAG,EAAE;QAC3D,MAAM,CAAC,GAAG,WAAW,CAAC,uDAAuD,EAAE,OAAO,CAAC,CAAC;QACxF,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxD,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAG,2BAA2B;IACxF,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,2DAA2D,EAAE,GAAG,EAAE;QACnE,MAAM,CAAC,GAAG,WAAW,CAAC,iEAAiE,EAAE,OAAO,CAAC,CAAC;QAClG,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3C,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CA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AAC,EAAE,CAAC,CAAC;QAC3C,MAAM,CAAC,YAAY,CAAC,CAAC,EAAE,IAAa,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC5D,MAAM,CAAC,gBAAgB,CAAC,IAAa,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * v2.107.0 — DATA ARCHAEOLOGY (Signed Provenance Ingest).
3
+ *
4
+ * The honest, world-class-engineering core of the "data archaeology" idea —
5
+ * WITHOUT the dark-web / aggressive-scraper / socket-sniffing theatre.
6
+ * Mneme's edge is NOT "access more data" (anyone can `curl`). It is: **every
7
+ * fact that enters your local brain carries a signed, verifiable PROVENANCE**
8
+ * — proof of WHERE it came from, WHEN it was fetched, and that it has not
9
+ * been tampered. Raw PUBLIC content is *distilled* into dense fact-shaped
10
+ * statements, each content-addressed + Ed25519-signed, then handed to the
11
+ * Cognitive Cortex (which dedups + quarantines contradictions). Knowledge
12
+ * alchemy done right: accountable, not hoarded.
13
+ *
14
+ * The fetching is the CALLER's job (an agent's WebFetch, or a local file) —
15
+ * this layer never crawls. It provides the *discipline* (a robots.txt +
16
+ * rate-limit policy you clear BEFORE fetching, so ingest stays legitimate)
17
+ * and the *cryptographic accountability* (signed provenance).
18
+ *
19
+ * Pure + total (108-error rule): deterministic, no network, never throws.
20
+ */
21
+ import { type NotaryReceipt } from "../notary/receipt.js";
22
+ export interface RobotsRules {
23
+ allow: string[];
24
+ disallow: string[];
25
+ crawlDelaySec: number | null;
26
+ }
27
+ /** Parse robots.txt for a user-agent (falls back to the `*` block). Total. */
28
+ export declare function parseRobots(robotsTxt: string, userAgent?: string): RobotsRules;
29
+ /** robots.txt longest-match: the most specific rule wins; ties → Allow. Total. */
30
+ export declare function isPathAllowed(rules: RobotsRules, path: string): boolean;
31
+ export interface RateState {
32
+ tokens: number;
33
+ lastMs: number;
34
+ }
35
+ export interface RateVerdict {
36
+ allowed: boolean;
37
+ state: RateState;
38
+ waitMs: number;
39
+ }
40
+ /** Pure token-bucket rate limiter (deterministic; the clock is an arg). Total. */
41
+ export declare function rateAcquire(state: RateState | null, capacity: number, refillPerSec: number, nowMs: number): RateVerdict;
42
+ /** Pull fact-shaped statements from raw text: sentences carrying a concrete
43
+ * signal (a number, a Proper-Noun pair, a code token, or a fact keyword).
44
+ * Deduped, capped, deterministic. Total. */
45
+ export declare function distill(content: string, maxFacts?: number): string[];
46
+ export interface SourceRef {
47
+ url: string;
48
+ content: string;
49
+ fetchedAt: number;
50
+ }
51
+ export interface ProvenanceFact {
52
+ statement: string;
53
+ /** cortex key (statement-hash) for dedup + contradiction-gating. */
54
+ key: string;
55
+ sourceUrl: string;
56
+ contentHash: string;
57
+ fetchedAt: number;
58
+ receipt: NotaryReceipt;
59
+ }
60
+ export interface IngestResult {
61
+ facts: ProvenanceFact[];
62
+ contentHash: string;
63
+ distilled: number;
64
+ }
65
+ /** Distill a fetched source into signed provenance-facts (ready for the
66
+ * cortex). Total. `at` = issue timestamp (deterministic). */
67
+ export declare function ingestSource(repoRoot: string, src: SourceRef, at: number, maxFacts?: number): IngestResult;
68
+ export interface ProvenanceVerdict {
69
+ valid: boolean;
70
+ bound: boolean;
71
+ sourceUrl: string | null;
72
+ reason: string;
73
+ }
74
+ /** Verify a fact's provenance OFFLINE: signature valid AND the receipt binds
75
+ * this exact statement + source + content hash. Catches a forged source. Total. */
76
+ export declare function verifyProvenance(fact: ProvenanceFact): ProvenanceVerdict;
77
+ export interface ArchaeologyGauntlet {
78
+ robotsRespected: boolean;
79
+ rateLimits: boolean;
80
+ distills: boolean;
81
+ signedProvenance: boolean;
82
+ forgeryCaught: boolean;
83
+ stable: boolean;
84
+ score: number;
85
+ }
86
+ /** Prove the archaeology engine. Total + deterministic. */
87
+ export declare function archaeologyGauntlet(repoRoot: string, at: number):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B,oEAAoE;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,aAAa,CAAC;CACxB;AAED,MAAM,WAAW,YAAY;IAAG,KAAK,EAAE,cAAc,EAAE,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE;AAEjG;8DAC8D;AAC9D,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,SAAK,GAAG,YAAY,CAmBtG;AAED,MAAM,WAAW,iBAAiB;IAAG,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE;AAE/G;oFACoF;AACpF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,cAAc,GAAG,iBAAiB,CAYxE;AAED,MAAM,WAAW,mBAAmB;IAClC,eAAe,EAAE,OAAO,CAAC;IACzB,UAAU,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,2DAA2D;AAC3D,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,mBAAmB,CAiBrF"}
@@ -0,0 +1,216 @@
1
+ /**
2
+ * v2.107.0 — DATA ARCHAEOLOGY (Signed Provenance Ingest).
3
+ *
4
+ * The honest, world-class-engineering core of the "data archaeology" idea —
5
+ * WITHOUT the dark-web / aggressive-scraper / socket-sniffing theatre.
6
+ * Mneme's edge is NOT "access more data" (anyone can `curl`). It is: **every
7
+ * fact that enters your local brain carries a signed, verifiable PROVENANCE**
8
+ * — proof of WHERE it came from, WHEN it was fetched, and that it has not
9
+ * been tampered. Raw PUBLIC content is *distilled* into dense fact-shaped
10
+ * statements, each content-addressed + Ed25519-signed, then handed to the
11
+ * Cognitive Cortex (which dedups + quarantines contradictions). Knowledge
12
+ * alchemy done right: accountable, not hoarded.
13
+ *
14
+ * The fetching is the CALLER's job (an agent's WebFetch, or a local file) —
15
+ * this layer never crawls. It provides the *discipline* (a robots.txt +
16
+ * rate-limit policy you clear BEFORE fetching, so ingest stays legitimate)
17
+ * and the *cryptographic accountability* (signed provenance).
18
+ *
19
+ * Pure + total (108-error rule): deterministic, no network, never throws.
20
+ */
21
+ import { createHash } from "node:crypto";
22
+ import { issueReceipt, verifyReceipt } from "../notary/receipt.js";
23
+ function sha256(s) { return createHash("sha256").update(typeof s === "string" ? s : "", "utf8").digest("hex"); }
24
+ /** Parse robots.txt for a user-agent (falls back to the `*` block). Total. */
25
+ export function parseRobots(robotsTxt, userAgent = "*") {
26
+ const out = { allow: [], disallow: [], crawlDelaySec: null };
27
+ try {
28
+ const lines = (typeof robotsTxt === "string" ? robotsTxt : "").split(/\r?\n/);
29
+ const uaLower = userAgent.toLowerCase();
30
+ let active = false;
31
+ let starRules = null;
32
+ let cur = out;
33
+ for (const raw of lines) {
34
+ const line = raw.replace(/#.*$/, "").trim();
35
+ if (!line)
36
+ continue;
37
+ const m = line.match(/^([a-zA-Z-]+)\s*:\s*(.*)$/);
38
+ if (!m)
39
+ continue;
40
+ const field = m[1].toLowerCase();
41
+ const val = m[2].trim();
42
+ if (field === "user-agent") {
43
+ const ua = val.toLowerCase();
44
+ active = ua === uaLower;
45
+ if (active)
46
+ cur = out;
47
+ else if (ua === "*") {
48
+ starRules = starRules ?? { allow: [], disallow: [], crawlDelaySec: null };
49
+ cur = starRules;
50
+ }
51
+ else
52
+ cur = { allow: [], disallow: [], crawlDelaySec: null };
53
+ }
54
+ else if (field === "disallow" && val)
55
+ cur.disallow.push(val);
56
+ else if (field === "allow" && val)
57
+ cur.allow.push(val);
58
+ else if (field === "crawl-delay") {
59
+ const n = parseFloat(val);
60
+ if (Number.isFinite(n))
61
+ cur.crawlDelaySec = n;
62
+ }
63
+ }
64
+ if (out.allow.length === 0 && out.disallow.length === 0 && out.crawlDelaySec === null && starRules)
65
+ return starRules;
66
+ if (out.crawlDelaySec === null && starRules?.crawlDelaySec != null)
67
+ out.crawlDelaySec = starRules.crawlDelaySec;
68
+ return out;
69
+ }
70
+ catch {
71
+ return out;
72
+ }
73
+ }
74
+ /** robots.txt longest-match: the most specific rule wins; ties → Allow. Total. */
75
+ export function isPathAllowed(rules, path) {
76
+ try {
77
+ const p = typeof path === "string" ? path : "/";
78
+ const r = rules && Array.isArray(rules.disallow) ? rules : { allow: [], disallow: [], crawlDelaySec: null };
79
+ let best = null;
80
+ for (const d of r.disallow)
81
+ if (d && p.startsWith(d))
82
+ if (!best || d.length > best.len)
83
+ best = { len: d.length, allow: false };
84
+ for (const a of (r.allow ?? []))
85
+ if (a && p.startsWith(a))
86
+ if (!best || a.length >= best.len)
87
+ best = { len: a.length, allow: true };
88
+ return best ? best.allow : true;
89
+ }
90
+ catch {
91
+ return true;
92
+ }
93
+ }
94
+ /** Pure token-bucket rate limiter (deterministic; the clock is an arg). Total. */
95
+ export function rateAcquire(state, capacity, refillPerSec, nowMs) {
96
+ const cap = capacity > 0 ? capacity : 1;
97
+ const rate = refillPerSec > 0 ? refillPerSec : 1;
98
+ const now = Number.isFinite(nowMs) ? nowMs : 0;
99
+ const s = state && Number.isFinite(state.tokens) ? state : { tokens: cap, lastMs: now };
100
+ const elapsed = Math.max(0, now - s.lastMs) / 1000;
101
+ const tokens = Math.min(cap, s.tokens + elapsed * rate);
102
+ if (tokens >= 1)
103
+ return { allowed: true, state: { tokens: tokens - 1, lastMs: now }, waitMs: 0 };
104
+ return { allowed: false, state: { tokens, lastMs: now }, waitMs: Math.ceil(((1 - tokens) / rate) * 1000) };
105
+ }
106
+ // ── DISTILL — raw content → dense, fact-shaped statements (deterministic) ──
107
+ /** Pull fact-shaped statements from raw text: sentences carrying a concrete
108
+ * signal (a number, a Proper-Noun pair, a code token, or a fact keyword).
109
+ * Deduped, capped, deterministic. Total. */
110
+ export function distill(content, maxFacts = 50) {
111
+ try {
112
+ const text = typeof content === "string" ? content : "";
113
+ const chunks = text.split(/(?<=[.!?])\s+|\n+/).map((s) => s.replace(/\s+/g, " ").trim());
114
+ const seen = new Set();
115
+ const out = [];
116
+ for (const s of chunks) {
117
+ if (s.length < 12 || s.length > 400)
118
+ continue;
119
+ const signal = /\d/.test(s) || /[A-Z][a-z]+ [A-Z][a-z]+/.test(s) || /[\w-]+[:=(){}/][\w-]/.test(s) || /\b(is|are|was|were|has|have|equals|returns|requires|supports|released|version|rate|ratio|percent)\b/i.test(s);
120
+ if (!signal)
121
+ continue;
122
+ const norm = s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
123
+ if (seen.has(norm))
124
+ continue;
125
+ seen.add(norm);
126
+ out.push(s);
127
+ if (out.length >= Math.max(1, maxFacts))
128
+ break;
129
+ }
130
+ return out;
131
+ }
132
+ catch {
133
+ return [];
134
+ }
135
+ }
136
+ /** Distill a fetched source into signed provenance-facts (ready for the
137
+ * cortex). Total. `at` = issue timestamp (deterministic). */
138
+ export function ingestSource(repoRoot, src, at, maxFacts = 50) {
139
+ try {
140
+ const url = typeof src?.url === "string" ? src.url.slice(0, 2000) : "";
141
+ const content = typeof src?.content === "string" ? src.content : "";
142
+ const fetchedAt = Number.isFinite(src?.fetchedAt) ? src.fetchedAt : at;
143
+ const contentHash = sha256(content);
144
+ const facts = distill(content, maxFacts).map((statement) => {
145
+ const statementHash = sha256(statement);
146
+ const receipt = issueReceipt(repoRoot, {
147
+ kind: "memory-capsule",
148
+ subject: `archaeology:${contentHash.slice(0, 16)}`,
149
+ payload: { statementHash, statement, sourceUrl: url, contentHash, fetchedAt },
150
+ includePayload: true,
151
+ issuedAt: at,
152
+ });
153
+ return { statement, key: "ingest." + statementHash.slice(0, 24), sourceUrl: url, contentHash, fetchedAt, receipt };
154
+ });
155
+ return { facts, contentHash, distilled: facts.length };
156
+ }
157
+ catch {
158
+ return { facts: [], contentHash: "", distilled: 0 };
159
+ }
160
+ }
161
+ /** Verify a fact's provenance OFFLINE: signature valid AND the receipt binds
162
+ * this exact statement + source + content hash. Catches a forged source. Total. */
163
+ export function verifyProvenance(fact) {
164
+ try {
165
+ if (!fact || !fact.receipt)
166
+ return { valid: false, bound: false, sourceUrl: null, reason: "no fact/receipt" };
167
+ const v = verifyReceipt(fact.receipt);
168
+ if (!v.valid)
169
+ return { valid: false, bound: false, sourceUrl: null, reason: v.reason ?? "bad signature" };
170
+ const p = fact.receipt.payload;
171
+ const bound = !!p
172
+ && p.statementHash === sha256(fact.statement)
173
+ && p.statement === fact.statement && p.sourceUrl === fact.sourceUrl
174
+ && p.contentHash === fact.contentHash && p.fetchedAt === fact.fetchedAt;
175
+ return { valid: true, bound, sourceUrl: bound ? fact.sourceUrl : null, reason: bound ? "provenance verified: statement signed from this source" : "signature valid but fact does not match receipt (forged source/statement)" };
176
+ }
177
+ catch (e) {
178
+ return { valid: false, bound: false, sourceUrl: null, reason: `threw: ${e.message}` };
179
+ }
180
+ }
181
+ /** Prove the archaeology engine. Total + deterministic. */
182
+ export function archaeologyGauntlet(repoRoot, at) {
183
+ try {
184
+ const rules = parseRobots("User-agent: *\nDisallow: /private\nAllow: /private/ok\nCrawl-delay: 2", "mneme");
185
+ const robotsRespected = isPathAllowed(rules, "/public/x") === true && isPathAllowed(rules, "/private/secret") === false && isPathAllowed(rules, "/private/ok/page") === true;
186
+ const r1 = rateAcquire(null, 2, 1, 1000);
187
+ const r2 = rateAcquire(r1.state, 2, 1, 1000);
188
+ const r3 = rateAcquire(r2.state, 2, 1, 1000);
189
+ const rateLimits = r1.allowed && r2.allowed && !r3.allowed && r3.waitMs > 0;
190
+ const content = "The render error rate is 3.2 percent. Mneme Cortex signs every fact. Random filler word here. Version 2.107 ships ingest.";
191
+ const ing = ingestSource(repoRoot, { url: "https://example.org/stats", content, fetchedAt: at }, at);
192
+ const distills = ing.distilled >= 2;
193
+ const signedProvenance = ing.facts.length > 0 && verifyProvenance(ing.facts[0]).bound;
194
+ const forged = JSON.parse(JSON.stringify(ing.facts[0]));
195
+ forged.sourceUrl = "https://evil.example";
196
+ const forgeryCaught = verifyProvenance(forged).bound === false;
197
+ let stable = true;
198
+ try {
199
+ parseRobots(null);
200
+ isPathAllowed(null, null);
201
+ distill(null);
202
+ ingestSource(repoRoot, null, at);
203
+ verifyProvenance(null);
204
+ rateAcquire(null, 0, 0, NaN);
205
+ }
206
+ catch {
207
+ stable = false;
208
+ }
209
+ const perfect = robotsRespected && rateLimits && distills && signedProvenance && forgeryCaught && stable;
210
+ return { robotsRespected, rateLimits, distills, signedProvenance, forgeryCaught, stable, score: perfect ? 100 : 0 };
211
+ }
212
+ catch {
213
+ return { robotsRespected: false, rateLimits: false, distills: false, signedProvenance: false, forgeryCaught: false, stable: false, score: 0 };
214
+ }
215
+ }
216
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/archaeology/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,aAAa,EAAsB,MAAM,sBAAsB,CAAC;AAEvF,SAAS,MAAM,CAAC,CAAS,IAAY,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAMhI,8EAA8E;AAC9E,MAAM,UAAU,WAAW,CAAC,SA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gB,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;IAAC,CAAC;AAC5J,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=entropy.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entropy.test.d.ts","sourceRoot":"","sources":["../../src/entropy/entropy.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,73 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mixEntropy, healthCheck, generateSecret, verifySecretAttestation, entropyGauntlet } from "./index.js";
4
+ const R = process.cwd();
5
+ const A = { id: "a", data: "0123456789abcdef".repeat(8), encoding: "hex" };
6
+ const B = { id: "b", data: "fedcba9876543210".repeat(8), encoding: "hex" };
7
+ describe("v2.108 MNEME ENTROPY — audited multi-source entropy & secrets", () => {
8
+ it("mix is deterministic given the same sources, diverges on different sources", () => {
9
+ expect(mixEntropy([A, B], 32).toString("hex")).toBe(mixEntropy([A, B], 32).toString("hex"));
10
+ expect(mixEntropy([A, B], 32).toString("hex")).not.toBe(mixEntropy([A, { id: "b", data: "00".repeat(64), encoding: "hex" }], 32).toString("hex"));
11
+ });
12
+ it("DEFENSE IN DEPTH — a stuck (all-zero) source can't weaken the mix", () => {
13
+ const stuck = { id: "stuck", data: Buffer.alloc(64, 0) };
14
+ const out = mixEntropy([stuck, A, B], 256);
15
+ expect(healthCheck(out).passed).toBe(true); // still strong because A,B carry entropy
16
+ // and removing the stuck source changes nothing it contributed (it had none) — output differs only by the source set
17
+ expect(out.length).toBe(256);
18
+ });
19
+ it("health check FLAGS a stuck source + PASSES real OS randomness", () => {
20
+ expect(healthCheck(Buffer.alloc(512, 0)).passed).toBe(false); // all zeros
21
+ expect(healthCheck(Buffer.alloc(512, 0xff)).passed).toBe(false); // all ones
22
+ expect(healthCheck(randomBytes(512)).passed).toBe(true); // CSPRNG
23
+ });
24
+ it("min-entropy estimate is high for random, 0 for a constant (conservative estimator)", () => {
25
+ expect(healthCheck(randomBytes(4096)).minEntropyBitsPerByte).toBeGreaterThan(5); // estimator under-counts but stays high
26
+ expect(healthCheck(Buffer.alloc(256, 7)).minEntropyBitsPerByte).toBe(0);
27
+ });
28
+ it("generateSecret signs a provenance attestation that binds the secret — without containing it", () => {
29
+ const sec = generateSecret(R, [A, B, { id: "os", data: randomBytes(32) }], 32, 1700000000000);
30
+ expect(sec.secretHex).toHaveLength(64);
31
+ expect(sec.sourceIds).toEqual(["a", "b", "os"]);
32
+ // the attestation payload must NOT contain the secret, only its hash
33
+ expect(JSON.stringify(sec.attestation)).not.toContain(sec.secretHex);
34
+ expect(verifySecretAttestation(sec.attestation, sec.secretHex).bound).toBe(true);
35
+ expect(verifySecretAttestation(sec.attestation, "ab".repeat(32)).bound).toBe(false); // wrong secret caught
36
+ });
37
+ it("entropy gauntlet scores 100", () => {
38
+ const g = entropyGauntlet(R, 1700000000000);
39
+ expect(g.mixDeterministic).toBe(true);
40
+ expect(g.mixDiverges).toBe(true);
41
+ expect(g.defenseInDepth).toBe(true);
42
+ expect(g.healthDetectsStuck).toBe(true);
43
+ expect(g.attestationBinds).toBe(true);
44
+ expect(g.score).toBe(100);
45
+ });
46
+ it("REFUSES no-entropy input (v2.108 review): empty sources → usableEntropy false, no valid secret", () => {
47
+ const r = generateSecret(R, [], 32, 1700000000000);
48
+ expect(r.usableEntropy).toBe(false);
49
+ expect(r.secretHex).toBe("");
50
+ expect(r.outputHealth.passed).toBe(false);
51
+ // and its (refused) attestation must not bind anything
52
+ expect(verifySecretAttestation(r.attestation, "ab".repeat(32)).bound).toBe(false);
53
+ });
54
+ it("adaptive monobit tolerance REJECTS a biased small sample (v2.108 review)", () => {
55
+ const biased = Buffer.concat([Buffer.alloc(48, 0x00), Buffer.alloc(16, 0xff)]); // 64 bytes, monobit 0.25
56
+ expect(healthCheck(biased).passed).toBe(false);
57
+ // real randomness of the same size still passes
58
+ expect(healthCheck(randomBytes(64)).passed).toBe(true);
59
+ });
60
+ it("verify rejects an undefined / empty secret explicitly (v2.108 review)", () => {
61
+ const sec = generateSecret(R, [A, B], 32, 1700000000000);
62
+ expect(verifySecretAttestation(sec.attestation, undefined).bound).toBe(false);
63
+ expect(verifySecretAttestation(sec.attestation, "").bound).toBe(false);
64
+ });
65
+ it("STABILITY — total on garbage", () => {
66
+ expect(() => mixEntropy(null)).not.toThrow();
67
+ expect(mixEntropy(null).length).toBeGreaterThanOrEqual(0);
68
+ expect(healthCheck(null).passed).toBe(false);
69
+ expect(() => generateSecret(R, null, 0, 0)).not.toThrow();
70
+ expect(verifySecretAttestation(null, null).bound).toBe(false);
71
+ });
72
+ });
73
+ //# sourceMappingURL=entropy.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entropy.test.js","sourceRoot":"","sources":["../../src/entropy/entropy.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,cAAc,EAAE,uBAAuB,EAAE,eAAe,EAAsB,MAAM,YAAY,CAAC;AAEnI,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AACxB,MAAM,CAAC,GAAkB,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAC1F,MAAM,CAAC,GAAkB,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAE1F,QAAQ,CAAC,+DAA+D,EAAE,GAAG,EAAE;IAC7E,EAAE,CAAC,4EAA4E,EAAE,GAAG,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AI,CAAC,KAAK,CAAC,CAAC;IACzE,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,8BAA8B,EAAE,GAAG,EAAE;QACtC,MAAM,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,IAAa,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;QACtD,MAAM,CAAC,UAAU,CAAC,IAAa,CAAC,CAAC,MAAM,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC;QACnE,MAAM,CAAC,WAAW,CAAC,IAAa,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACtD,MAAM,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,CAAC,EAAE,IAAa,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;QACnE,MAAM,CAAC,uBAAuB,CAAC,IAAa,EAAE,IAAa,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAClF,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * v2.108.0 — MNEME ENTROPY (Audited Multi-Source Entropy & Secrets).
3
+ *
4
+ * The honest, world-class-crypto-engineering core of the "True Entropy
5
+ * Security" idea — WITHOUT the ocean-wave / quantum-vacuum mysticism.
6
+ *
7
+ * What it really does (and what it does NOT claim):
8
+ * - It MIXES every entropy source you actually have — the OS CSPRNG, timing
9
+ * jitter, any physical/external sample you feed it (a public randomness
10
+ * beacon, a sensor reading) — through a standard cryptographic extractor
11
+ * (HKDF / HMAC-SHA-512). This is DEFENSE IN DEPTH: the output is strong if
12
+ * *any one* source has entropy, so a single backdoored/degraded source
13
+ * can't weaken your key.
14
+ * - It HEALTH-CHECKS sources (NIST-style monobit / runs / byte-uniformity)
15
+ * and estimates min-entropy, so a stuck source is FLAGGED, not trusted.
16
+ * - It SIGNS a provenance attestation (which sources, their health, the
17
+ * min-entropy estimate, the secret's hash) so you can PROVE how a secret
18
+ * was derived — WITHOUT revealing the secret (only its hash is signed).
19
+ *
20
+ * It does NOT claim to be "unhackable by quantum computers" — `crypto`'s
21
+ * CSPRNG is already secure; the value here is resilience + AUDITABILITY +
22
+ * fail-safe health checks, the things real key-management gets wrong.
23
+ *
24
+ * Pure + total (108-error rule): deterministic given its inputs, never throws.
25
+ */
26
+ import { type NotaryReceipt } from "../notary/receipt.js";
27
+ export interface EntropySource {
28
+ id: string;
29
+ /** raw entropy bytes (hex/base64/utf8 string or a Buffer). */
30
+ data: string | Buffer;
31
+ /** optional encoding of a string `data` (default utf8; "hex"/"base64"). */
32
+ encoding?: "hex" | "base64" | "utf8";
33
+ }
34
+ /**
35
+ * HKDF-style extractor over ALL sources (RFC-5869 shape). Each source is
36
+ * domain-separated by its id so a duplicate buffer can't cancel itself out.
37
+ * Extract = HMAC(salt, IKM); Expand = HMAC-chain to `outBytes`. Defense in
38
+ * depth: the result is uniform if any single source carries entropy. Total.
39
+ */
40
+ export declare function mixEntropy(sources: EntropySource[], outBytes?: number): Buffer;
41
+ export interface HealthReport {
42
+ /** fraction of 1-bits (ideal 0.5). */
43
+ monobit: number;
44
+ /** number of runs of consecutive equal bits. */
45
+ runs: number;
46
+ /** byte-frequency chi-square (lower ≈ more uniform; ideal ~255). */
47
+ chiSquare: number;
48
+ /** estimated min-entropy in bits/byte (0..8). */
49
+ minEntropyBitsPerByte: number;
50
+ /** true iff the sample passes the basic randomness checks. */
51
+ passed: boolean;
52
+ }
53
+ /**
54
+ * NIST-style health check (monobit + runs + byte-uniformity) + a min-entropy
55
+ * ESTIMATE (from the most-frequent byte). Detects a stuck/degraded source.
56
+ * For very short samples the thresholds are loosened. Total. */
57
+ export declare function healthCheck(bytes: Buffer | string): HealthReport;
58
+ export interface SecretResult {
59
+ /** the generated secret, hex-encoded. */
60
+ secretHex: string;
61
+ /** false when NO source carried any bytes — the "secret" would be a fixed
62
+ * function of the empty input, so it is refused (empty + health failed). */
63
+ usableEntropy: boolean;
64
+ sourceIds: string[];
65
+ /** per-source health (a stuck source is flagged but still mixed in). */
66
+ sourceHealth: Array<{
67
+ id: string;
68
+ passed: boolean;
69
+ minEntropyBitsPerByte: number;
70
+ }>;
71
+ /** health of the FINAL mixed output. */
72
+ outputHealth: HealthReport;
73
+ /** signed provenance: proves the derivation WITHOUT revealing the secret. */
74
+ attestation: NotaryReceipt;
75
+ }
76
+ /**
77
+ * Generate a secret of `outBytes` from the given sources, with a SIGNED
78
+ * provenance attestation over (sourceIds, health, sha256(secret)). Total.
79
+ * `at` is the issue timestamp (deterministic). The OS CSPRNG source should be
80
+ * supplied by the caller (CLI/MCP) so this core stays pure.
81
+ */
82
+ export declare function generateSecret(repoRoot: string, sources: EntropySource[], outBytes: number, at: number): SecretResult;
83
+ export interface SecretVerify {
84
+ valid: boolean;
85
+ bound: boolean;
86
+ reason: string;
87
+ }
88
+ /** Verify a secret's provenance OFFLINE: the attestation signature is valid
89
+ * AND sha256(secret) matches the signed outputHash — proving this exact
90
+ * secret was derived from the attested sources, without the attestation ever
91
+ * containing the secret. Total. */
92
+ export declare function verifySecretAttestation(attestation: NotaryReceipt, secretHex: string): SecretVerify;
93
+ export interface EntropyGauntlet {
94
+ mixDeterministic: boolean;
95
+ mixDiverges: boolean;
96
+ defenseInDepth: boolean;
97
+ healthDetectsStuck: boolean;
98
+ attestationBinds: boolean;
99
+ stable: boolean;
100
+ score: number;
101
+ }
102
+ /** Prove the entropy engine. Total + deterministic. */
103
+ export declare function entropyGauntlet(repoRoot: string, at: number): EntropyGauntlet;
104
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/entropy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAA+B,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEvF,MAAM,WAAW,aAA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