dsh-cortex-memory 0.4.11 → 0.4.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +112 -0
- package/LICENSE +1 -1
- package/README.md +62 -36
- package/bench/README.md +29 -0
- package/bench/ab-engine.mjs +60 -0
- package/bench/ann-bench.mjs +78 -0
- package/bench/hnsw-bench.mjs +79 -0
- package/bench/locomo.js +89 -0
- package/bench/longmemeval.js +83 -0
- package/bench/metrics.js +67 -0
- package/bench/migration-bench.mjs +69 -0
- package/bench/results/semantic-cn.json +24 -0
- package/bench/run.js +77 -0
- package/bench/semantic-cn.js +116 -0
- package/bench/synthetic.js +99 -0
- package/bench/vector-ab.mjs +76 -0
- package/docs/compatibility.md +39 -0
- package/docs/install-windows.md +144 -0
- package/docs/models.md +183 -0
- package/docs/multimodal.md +112 -0
- package/docs/permissions.md +53 -0
- package/docs/privacy.md +50 -0
- package/docs/scopes.md +142 -0
- package/examples/README.md +72 -0
- package/examples/setup-cortex-bge.ps1 +66 -0
- package/examples/uninstall-cortex.ps1 +91 -0
- package/index.js +23 -0
- package/package.json +11 -5
- package/src/core/config.js +27 -0
- package/src/engines/extract.js +10 -10
- package/src/engines/retrieve.js +30 -5
- package/src/guardian/guardian.js +2 -15
- package/src/guardian/invariants.js +9 -5
- package/src/host/runtime.js +10 -14
- package/src/self/evolution.js +32 -5
- package/src/self/policies.js +21 -2
- package/src/service/cortex.js +3 -2
- package/src/store/database.js +9 -1
- package/src/store/schema.sql +2 -1
- package/src/vector/hnsw.js +5 -5
- package/test/integration/_helpers.js +128 -0
- package/test/integration/acceptance.test.js +803 -0
- package/test/integration/ann-load.test.js +61 -0
- package/test/integration/api-contract.test.js +1476 -0
- package/test/integration/backup-privacy.test.js +214 -0
- package/test/integration/consolidate.test.js +75 -0
- package/test/integration/edge-cases.test.js +1088 -0
- package/test/integration/exchange.test.js +326 -0
- package/test/integration/life-loop.test.js +188 -0
- package/test/integration/load.test.js +751 -0
- package/test/integration/markdown-sync.test.js +35 -0
- package/test/integration/policy-query-api.test.js +306 -0
- package/test/integration/resilience-writes.test.js +241 -0
- package/test/integration/tools-contract.test.js +1324 -0
- package/test/unit/ann-edge.test.js +102 -0
- package/test/unit/ann.test.js +77 -0
- package/test/unit/api-client.test.js +576 -0
- package/test/unit/api-validate.test.js +19 -0
- package/test/unit/api.test.js +555 -0
- package/test/unit/appraisal.test.js +48 -0
- package/test/unit/attachments.test.js +33 -0
- package/test/unit/autonomy.test.js +53 -0
- package/test/unit/batch.test.js +46 -0
- package/test/unit/bench.test.js +40 -0
- package/test/unit/benchmark-synthetic.test.js +52 -0
- package/test/unit/client-contract.test.js +29 -0
- package/test/unit/compression.test.js +76 -0
- package/test/unit/core.test.js +77 -0
- package/test/unit/develop.test.js +130 -0
- package/test/unit/development.test.js +68 -0
- package/test/unit/digest.test.js +26 -0
- package/test/unit/dsr.test.js +111 -0
- package/test/unit/edges-candidates.test.js +113 -0
- package/test/unit/emotion.test.js +61 -0
- package/test/unit/encode.test.js +98 -0
- package/test/unit/evolution.test.js +130 -0
- package/test/unit/external-ann-search.test.js +50 -0
- package/test/unit/external-ann.test.js +29 -0
- package/test/unit/facts-belief.test.js +32 -0
- package/test/unit/facts.test.js +107 -0
- package/test/unit/feature-overrides.test.js +42 -0
- package/test/unit/fts-migration.test.js +42 -0
- package/test/unit/graph.test.js +79 -0
- package/test/unit/growth-reflect.test.js +123 -0
- package/test/unit/guard-runtime.test.js +40 -0
- package/test/unit/guardian.test.js +91 -0
- package/test/unit/health-privacy.test.js +102 -0
- package/test/unit/hnsw.test.js +35 -0
- package/test/unit/host-runtime.test.js +142 -0
- package/test/unit/host.test.js +58 -0
- package/test/unit/identity.test.js +98 -0
- package/test/unit/induct-evaluate.test.js +41 -0
- package/test/unit/ingest-extracted.test.js +35 -0
- package/test/unit/initiative.test.js +90 -0
- package/test/unit/jobs.test.js +93 -0
- package/test/unit/json-snapshot.test.js +57 -0
- package/test/unit/life-consolidate.test.js +34 -0
- package/test/unit/life.test.js +149 -0
- package/test/unit/llm-facts-integration.test.js +27 -0
- package/test/unit/llm-facts.test.js +16 -0
- package/test/unit/llm.test.js +45 -0
- package/test/unit/locomo.test.js +45 -0
- package/test/unit/longmemeval.test.js +56 -0
- package/test/unit/markdown-import.test.js +44 -0
- package/test/unit/markdown.test.js +34 -0
- package/test/unit/memory-edit.test.js +112 -0
- package/test/unit/metrics.test.js +26 -0
- package/test/unit/migration.test.js +38 -0
- package/test/unit/model-config.test.js +52 -0
- package/test/unit/narrative.test.js +62 -0
- package/test/unit/playbook-consolidate.test.js +24 -0
- package/test/unit/privacy-scope.test.js +39 -0
- package/test/unit/profile.test.js +20 -0
- package/test/unit/prompt.test.js +42 -0
- package/test/unit/providers.test.js +42 -0
- package/test/unit/qa.test.js +100 -0
- package/test/unit/query.test.js +53 -0
- package/test/unit/retention.test.js +31 -0
- package/test/unit/retrieval-ranking.test.js +31 -0
- package/test/unit/retrieve.test.js +117 -0
- package/test/unit/rotation.test.js +25 -0
- package/test/unit/scanner.test.js +50 -0
- package/test/unit/scenario.test.js +78 -0
- package/test/unit/scheduler.test.js +136 -0
- package/test/unit/self-state.test.js +94 -0
- package/test/unit/service.test.js +72 -0
- package/test/unit/shiori-import.test.js +77 -0
- package/test/unit/skills.test.js +104 -0
- package/test/unit/store.test.js +111 -0
- package/test/unit/temporal-graph.test.js +44 -0
- package/test/unit/tiers.test.js +39 -0
- package/test/unit/tokenizer-fts.test.js +35 -0
- package/test/unit/tools.test.js +122 -0
- package/test/unit/upgrade-0412.test.js +104 -0
- package/test/unit/upgrade-0413.test.js +84 -0
- package/test/unit/upgrade-0414.test.js +101 -0
- package/test/unit/vector-ann.test.js +53 -0
- package/test/unit/vector-async.test.js +69 -0
- package/test/unit/vector.test.js +68 -0
- package/test/unit/working.test.js +80 -0
package/src/self/evolution.js
CHANGED
|
@@ -34,6 +34,28 @@ export function createEvolutionEngine({
|
|
|
34
34
|
let dayKey = '';
|
|
35
35
|
let dayCount = 0;
|
|
36
36
|
|
|
37
|
+
// Rehydrate canaries after a process restart. Without this, an active
|
|
38
|
+
// policy that was still inside its observation window would never roll back.
|
|
39
|
+
for (const policy of policies.listCanaries?.() ?? []) {
|
|
40
|
+
const canary = policy.canary;
|
|
41
|
+
if (!canary || typeof canary !== 'object') continue;
|
|
42
|
+
canaries.set(policy.id, {
|
|
43
|
+
kind: policy.kind,
|
|
44
|
+
previousId: canary.previousId ?? null,
|
|
45
|
+
ticks: Number(canary.ticks) || 0,
|
|
46
|
+
activatedAt: Number(canary.activatedAt) || Date.now(),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function localDay(value) {
|
|
51
|
+
const date = new Date(value);
|
|
52
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function persistCanary(id, canary) {
|
|
56
|
+
try { policies.setCanary?.(id, canary); } catch { /* persistence must not break evolution */ }
|
|
57
|
+
}
|
|
58
|
+
|
|
37
59
|
function propose({ kind, config, rationale = '', metrics = null, scopeId = 'global' } = {}) {
|
|
38
60
|
const policy = policies.create({ kind, config, rationale, metrics });
|
|
39
61
|
audit?.record?.({
|
|
@@ -136,7 +158,7 @@ export function createEvolutionEngine({
|
|
|
136
158
|
if (guardConfig.autoActivate !== true) {
|
|
137
159
|
return { ...optimized, activated: [], deferred: 'auto-activate-off', guard: { ...guardConfig } };
|
|
138
160
|
}
|
|
139
|
-
const today =
|
|
161
|
+
const today = localDay(Date.now());
|
|
140
162
|
if (today !== dayKey) { dayKey = today; dayCount = 0; }
|
|
141
163
|
const activated = [];
|
|
142
164
|
const errors = [];
|
|
@@ -153,7 +175,7 @@ export function createEvolutionEngine({
|
|
|
153
175
|
? evaluateQuality({ scopeId, phase: 'after', baseline })
|
|
154
176
|
: null;
|
|
155
177
|
if (quality && quality.ok === false) {
|
|
156
|
-
const target = previous?.id ? policies.rollback(policy.kind, previous.id) : policies.
|
|
178
|
+
const target = previous?.id ? policies.rollback(policy.kind, previous.id) : policies.retire(policy.id);
|
|
157
179
|
audit?.record?.({
|
|
158
180
|
actor: 'self:autoEvolve',
|
|
159
181
|
action: 'policy.autoevolve.quality-rollback',
|
|
@@ -164,12 +186,14 @@ export function createEvolutionEngine({
|
|
|
164
186
|
errors.push({ id: proposal.id, error: 'quality-guard', quality });
|
|
165
187
|
continue;
|
|
166
188
|
}
|
|
167
|
-
|
|
189
|
+
const canary = {
|
|
168
190
|
kind: policy.kind,
|
|
169
191
|
previousId: previous?.id ?? null,
|
|
170
192
|
ticks: 0,
|
|
171
193
|
activatedAt: Date.now(),
|
|
172
|
-
}
|
|
194
|
+
};
|
|
195
|
+
canaries.set(policy.id, canary);
|
|
196
|
+
persistCanary(policy.id, canary);
|
|
173
197
|
lastActivatedAt = Date.now();
|
|
174
198
|
dayCount += 1;
|
|
175
199
|
activated.push(policy);
|
|
@@ -189,7 +213,7 @@ export function createEvolutionEngine({
|
|
|
189
213
|
if (failed) {
|
|
190
214
|
for (const [id, canary] of [...canaries.entries()]) {
|
|
191
215
|
try {
|
|
192
|
-
const target = canary.previousId ? policies.rollback(canary.kind, canary.previousId) : policies.
|
|
216
|
+
const target = canary.previousId ? policies.rollback(canary.kind, canary.previousId) : policies.retire(id);
|
|
193
217
|
audit?.record?.({
|
|
194
218
|
actor: 'self:autoRollback',
|
|
195
219
|
action: 'policy.autoevolve.rollback',
|
|
@@ -199,6 +223,7 @@ export function createEvolutionEngine({
|
|
|
199
223
|
});
|
|
200
224
|
rolledBack.push({ id, kind: canary.kind, to: target?.id ?? null });
|
|
201
225
|
canaries.delete(id);
|
|
226
|
+
persistCanary(id, null);
|
|
202
227
|
} catch (error) {
|
|
203
228
|
rolledBack.push({ id, kind: canary.kind, error: error instanceof Error ? error.message : String(error) });
|
|
204
229
|
}
|
|
@@ -209,6 +234,7 @@ export function createEvolutionEngine({
|
|
|
209
234
|
canary.ticks += 1;
|
|
210
235
|
if (canary.ticks >= guardConfig.canaryTicks) {
|
|
211
236
|
canaries.delete(id);
|
|
237
|
+
persistCanary(id, null);
|
|
212
238
|
audit?.record?.({
|
|
213
239
|
actor: 'self:canary',
|
|
214
240
|
action: 'policy.autoevolve.promote',
|
|
@@ -218,6 +244,7 @@ export function createEvolutionEngine({
|
|
|
218
244
|
});
|
|
219
245
|
} else {
|
|
220
246
|
canaries.set(id, canary);
|
|
247
|
+
persistCanary(id, canary);
|
|
221
248
|
}
|
|
222
249
|
}
|
|
223
250
|
return { rolledBack, pending: canaries.size };
|
package/src/self/policies.js
CHANGED
|
@@ -13,6 +13,7 @@ function rowToPolicy(row) {
|
|
|
13
13
|
status: row.status,
|
|
14
14
|
createdAt: row.created_at,
|
|
15
15
|
activatedAt: row.activated_at,
|
|
16
|
+
canary: row.canary_json ? JSON.parse(row.canary_json) : null,
|
|
16
17
|
};
|
|
17
18
|
}
|
|
18
19
|
|
|
@@ -72,10 +73,28 @@ export function createPolicyRepository(db) {
|
|
|
72
73
|
function deactivate(kind) {
|
|
73
74
|
const current = active(kind);
|
|
74
75
|
if (!current) return null;
|
|
75
|
-
db.prepare("UPDATE policies SET status = 'candidate', activated_at = NULL WHERE id = ?").run(current.id);
|
|
76
|
+
db.prepare("UPDATE policies SET status = 'candidate', activated_at = NULL, canary_json = NULL WHERE id = ?").run(current.id);
|
|
76
77
|
return get(current.id);
|
|
77
78
|
}
|
|
78
79
|
|
|
80
|
+
function retire(id) {
|
|
81
|
+
const target = get(id);
|
|
82
|
+
if (!target) return null;
|
|
83
|
+
db.prepare("UPDATE policies SET status = 'superseded', activated_at = NULL, canary_json = NULL WHERE id = ?").run(id);
|
|
84
|
+
return get(id);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function setCanary(id, canary) {
|
|
88
|
+
const policy = get(id);
|
|
89
|
+
if (!policy) throw new Error(`policy not found: ${id}`);
|
|
90
|
+
db.prepare('UPDATE policies SET canary_json = ? WHERE id = ?').run(canary == null ? null : stableStringify(canary), id);
|
|
91
|
+
return get(id);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function listCanaries() {
|
|
95
|
+
return db.prepare("SELECT * FROM policies WHERE status = 'active' AND canary_json IS NOT NULL ORDER BY activated_at DESC").all().map(rowToPolicy);
|
|
96
|
+
}
|
|
97
|
+
|
|
79
98
|
function updateMetrics(id, metrics) {
|
|
80
99
|
const policy = get(id);
|
|
81
100
|
if (!policy) throw new Error(`policy not found: ${id}`);
|
|
@@ -83,5 +102,5 @@ export function createPolicyRepository(db) {
|
|
|
83
102
|
return get(id);
|
|
84
103
|
}
|
|
85
104
|
|
|
86
|
-
return { get, list, active, create, activate, rollback, deactivate, updateMetrics };
|
|
105
|
+
return { get, list, active, create, activate, rollback, deactivate, retire, setCanary, listCanaries, updateMetrics };
|
|
87
106
|
}
|
package/src/service/cortex.js
CHANGED
|
@@ -339,6 +339,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
339
339
|
traceId: result.trace?.id ?? null,
|
|
340
340
|
eventId: result.event?.id ?? null,
|
|
341
341
|
recordedAt: result.trace?.recordedAt ?? null,
|
|
342
|
+
persona: config.persona,
|
|
342
343
|
});
|
|
343
344
|
if (config.features?.autoGraphCandidates === true || config.features?.graphCandidateAutoFacts === true) {
|
|
344
345
|
const queued = [];
|
|
@@ -1455,12 +1456,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1455
1456
|
},
|
|
1456
1457
|
flushLlmFacts,
|
|
1457
1458
|
recallTiered: ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
|
|
1458
|
-
const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
|
|
1459
|
+
const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
|
|
1459
1460
|
const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
|
|
1460
1461
|
return { query, result, selection, text: renderTiers(selection) };
|
|
1461
1462
|
},
|
|
1462
1463
|
recallTieredAsync: async ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
|
|
1463
|
-
const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
|
|
1464
|
+
const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
|
|
1464
1465
|
const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
|
|
1465
1466
|
return { query, result, selection, text: renderTiers(selection) };
|
|
1466
1467
|
},
|
package/src/store/database.js
CHANGED
|
@@ -9,7 +9,7 @@ import { ftsText } from '../memory/tokenizer.js';
|
|
|
9
9
|
|
|
10
10
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
11
11
|
const SCHEMA_FILE = path.join(HERE, 'schema.sql');
|
|
12
|
-
export const SCHEMA_VERSION =
|
|
12
|
+
export const SCHEMA_VERSION = 7;
|
|
13
13
|
export const FTS_INDEX_VERSION = 2;
|
|
14
14
|
|
|
15
15
|
function ensureTraceColumns(db) {
|
|
@@ -28,6 +28,13 @@ function ensureSummonColumns(db) {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
function ensurePolicyColumns(db) {
|
|
32
|
+
const columns = db.prepare('PRAGMA table_info(policies)').all();
|
|
33
|
+
if (!columns.some((column) => column.name === 'canary_json')) {
|
|
34
|
+
db.exec('ALTER TABLE policies ADD COLUMN canary_json TEXT');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
31
38
|
function ensureFactsColumns(db) {
|
|
32
39
|
const columns = db.prepare('PRAGMA table_info(facts)').all();
|
|
33
40
|
if (!columns.some((column) => column.name === 'superseded_at')) {
|
|
@@ -86,6 +93,7 @@ export function migrate(db, { version = SCHEMA_VERSION } = {}) {
|
|
|
86
93
|
ensureTraceColumns(db);
|
|
87
94
|
ensureFactsColumns(db);
|
|
88
95
|
ensureSummonColumns(db);
|
|
96
|
+
ensurePolicyColumns(db);
|
|
89
97
|
const row = db.prepare('SELECT value FROM meta WHERE key = ?').get('schema_version');
|
|
90
98
|
if (!row) {
|
|
91
99
|
db.prepare('INSERT INTO meta(key, value, updated_at) VALUES (?, ?, ?)').run('schema_version', String(version), nowIso());
|
package/src/store/schema.sql
CHANGED
|
@@ -259,7 +259,8 @@ CREATE TABLE IF NOT EXISTS policies (
|
|
|
259
259
|
metrics_json TEXT,
|
|
260
260
|
status TEXT NOT NULL DEFAULT 'candidate',
|
|
261
261
|
created_at TEXT NOT NULL,
|
|
262
|
-
activated_at TEXT
|
|
262
|
+
activated_at TEXT,
|
|
263
|
+
canary_json TEXT
|
|
263
264
|
);
|
|
264
265
|
|
|
265
266
|
CREATE TABLE IF NOT EXISTS audit (
|
package/src/vector/hnsw.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Small dependency-free HNSW index for Cortex.
|
|
3
3
|
*
|
|
4
|
-
* This is
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* This is the default ANN engine in `src/vector/index.js` (`annEngine: 'hnsw'`);
|
|
5
|
+
* the older single-layer NSW implementation remains selectable as `'nsw'`.
|
|
6
|
+
* The implementation uses simple sorted frontiers (not a binary heap) because
|
|
7
|
+
* it is easier to audit; run `bench/hnsw-bench.mjs` before changing parameters
|
|
8
|
+
* for a large corpus.
|
|
9
9
|
*/
|
|
10
10
|
function mulberry32(seed) {
|
|
11
11
|
let state = seed >>> 0;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for the integration suite.
|
|
3
|
+
*
|
|
4
|
+
* The tests are deliberately black-box: every helper here only creates real
|
|
5
|
+
* cortex instances in throwaway directories, drives real repository/engine
|
|
6
|
+
* code, and cleans up afterwards. Nothing mocks the module under test.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { Readable } from 'node:stream';
|
|
12
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
13
|
+
import { API_BASE } from '../../src/api/routes.js';
|
|
14
|
+
|
|
15
|
+
export const DAY_MS = 86_400_000;
|
|
16
|
+
/** Fixed reference instant: 2026-11-11T10:00:00+08:00. */
|
|
17
|
+
export const BASE_MS = Date.parse('2026-11-11T10:00:00+08:00');
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Create a cortex backed by a fresh temporary directory.
|
|
21
|
+
* Returns the directory (for cleanup) and the service.
|
|
22
|
+
*/
|
|
23
|
+
export function makeCortex(config = {}) {
|
|
24
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-integration-'));
|
|
25
|
+
const dataRoot = config.dataRoot ?? path.join(dir, 'data');
|
|
26
|
+
const dbFile = config.dbFile ?? path.join(dataRoot, 'cortex.sqlite');
|
|
27
|
+
const cortex = createCortex({ config: { ...config, dataRoot, dbFile } });
|
|
28
|
+
return { dir, cortex };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Close every cortex first, then delete every temporary directory. Safe to
|
|
33
|
+
* call from a finally block even when the test failed halfway through setup.
|
|
34
|
+
*/
|
|
35
|
+
export function cleanup(...contexts) {
|
|
36
|
+
for (const context of contexts) {
|
|
37
|
+
try {
|
|
38
|
+
context?.cortex?.close();
|
|
39
|
+
} catch {
|
|
40
|
+
/* closing is best-effort, cleanup must not mask the real assertion */
|
|
41
|
+
}
|
|
42
|
+
if (context?.dir) rmSync(context.dir, { recursive: true, force: true });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Request stream shaped the way the API handler expects node:http objects. */
|
|
47
|
+
export function apiRequest({
|
|
48
|
+
method = 'GET',
|
|
49
|
+
route = '/ping',
|
|
50
|
+
body = null,
|
|
51
|
+
headers = {},
|
|
52
|
+
remoteAddress = '127.0.0.1',
|
|
53
|
+
host = '127.0.0.1:7430',
|
|
54
|
+
origin = 'http://127.0.0.1:7430',
|
|
55
|
+
site = 'same-origin',
|
|
56
|
+
url = null,
|
|
57
|
+
} = {}) {
|
|
58
|
+
const stream = Readable.from(body === null ? [] : [Buffer.from(JSON.stringify(body), 'utf8')]);
|
|
59
|
+
stream.method = method;
|
|
60
|
+
stream.url = url ?? `${API_BASE}${route}`;
|
|
61
|
+
const merged = {
|
|
62
|
+
host,
|
|
63
|
+
origin,
|
|
64
|
+
'sec-fetch-site': site,
|
|
65
|
+
...(body === null ? {} : { 'content-type': 'application/json' }),
|
|
66
|
+
...headers,
|
|
67
|
+
};
|
|
68
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
69
|
+
if (value === undefined) delete merged[key];
|
|
70
|
+
}
|
|
71
|
+
stream.headers = merged;
|
|
72
|
+
stream.socket = { remoteAddress };
|
|
73
|
+
return stream;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Minimal ServerResponse recorder: enough for the route handler. */
|
|
77
|
+
export function apiResponse() {
|
|
78
|
+
return {
|
|
79
|
+
statusCode: 0,
|
|
80
|
+
headers: null,
|
|
81
|
+
body: '',
|
|
82
|
+
writeHead(code, headers) {
|
|
83
|
+
this.statusCode = code;
|
|
84
|
+
this.headers = headers ?? null;
|
|
85
|
+
},
|
|
86
|
+
end(chunk) {
|
|
87
|
+
if (chunk != null) this.body += String(chunk);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function invokeApi(handler, options = {}) {
|
|
93
|
+
const response = apiResponse();
|
|
94
|
+
await handler(apiRequest(options), response);
|
|
95
|
+
return { status: response.statusCode, headers: response.headers, json: JSON.parse(response.body || '{}') };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Split an exported MEMORY.md mirror into its per-memory frontmatter blocks.
|
|
100
|
+
*
|
|
101
|
+
* The exporter writes one multi-entry document; the importer expects one
|
|
102
|
+
* memory per file. This helper converts the mirror into the vault shape the
|
|
103
|
+
* importer documents, using the same textual boundaries the exporter emits.
|
|
104
|
+
*/
|
|
105
|
+
export function splitMirrorEntries(markdown) {
|
|
106
|
+
const entries = [];
|
|
107
|
+
const pattern = /^---\n([\s\S]*?)\n---\n\n([\s\S]*?)(?=\n---\n|$)/gm;
|
|
108
|
+
for (const match of String(markdown ?? '').matchAll(pattern)) {
|
|
109
|
+
entries.push({ frontmatter: match[1], body: match[2].trim() });
|
|
110
|
+
}
|
|
111
|
+
return entries;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Write one frontmatter memory file into a vault directory. */
|
|
115
|
+
export function writeVaultEntry(dir, name, { frontmatter, body }) {
|
|
116
|
+
mkdirSync(dir, { recursive: true });
|
|
117
|
+
const file = path.join(dir, name);
|
|
118
|
+
writeFileSync(file, `---\n${frontmatter}\n---\n\n${body}\n`, 'utf8');
|
|
119
|
+
return file;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Write a raw file, mainly for hand-authored vault fixtures. */
|
|
123
|
+
export function writeRaw(dir, name, content) {
|
|
124
|
+
mkdirSync(dir, { recursive: true });
|
|
125
|
+
const file = path.join(dir, name);
|
|
126
|
+
writeFileSync(file, content, 'utf8');
|
|
127
|
+
return file;
|
|
128
|
+
}
|