dsh-layers-hippocampus 1.7.4 → 1.9.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/src/config.js CHANGED
@@ -163,9 +163,12 @@ export const DEFAULT_CONFIG = Object.freeze({
163
163
  autoMaintainOnBoot: true,
164
164
  enableDream: true,
165
165
  dreamIdleMinutes: 180,
166
- // v1.5.5: offline semantic distillation. The LLM leg is optional — when
167
- // `dream.llm` is not configured the engine silently uses the deterministic local
168
- // merge (and logs MEM_E_DREAM_LLM_FALLBACK), so Dream always completes.
166
+ // v1.5.5: offline semantic distillation. The LLM leg is optional.
167
+ // v1.9.1: the DEFAULT leg is now the Host's own model (`dream.llm.useHost`), so a
168
+ // fresh install distils with the model the user already signed in to and never
169
+ // needs an endpoint or a copied API key. An explicit `dream.llm.{baseUrl,model,
170
+ // apiKey}` remains the override; with neither available the deterministic local
171
+ // merge runs and MEM_E_DREAM_LLM_FALLBACK is logged, so Dream always completes.
169
172
  dream: Object.freeze({
170
173
  useLlm: true,
171
174
  minGroupSize: 3,
@@ -182,7 +185,7 @@ export const DEFAULT_CONFIG = Object.freeze({
182
185
  // v1.5.6 local scheduler: LLM Dream waits for the DeepSeek low-valley window
183
186
  // (Beijing 09–12 / 14–18 are peak) instead of requiring an external price plugin.
184
187
  onlyLowValley: true,
185
- llm: Object.freeze({ baseUrl: null, model: null, apiKey: null }),
188
+ llm: Object.freeze({ useHost: true, maxTokens: 1200, baseUrl: null, model: null, apiKey: null }),
186
189
  }),
187
190
  enableReflection: true,
188
191
  // Edges returned by /api/memory/graph. The offline cache may hold up to
@@ -371,10 +374,19 @@ export const DEFAULT_CONFIG = Object.freeze({
371
374
  // code fence, HTTP status, file path, task statement). `autoTag:false` disables
372
375
  // the heuristic entirely (manual behaviour stays unchanged either way).
373
376
  tagging: Object.freeze({ autoTag: true, maxTags: 2 }),
374
- // v1.5.6 microkernel boundary. Default ON so behaviour is unchanged; turning
375
- // multiSpace off makes the engine a strict single-space core (targetSpaceId must
376
- // be "default"), and crossSpaceTransfer requires multiSpace.
377
- features: Object.freeze({ multiSpace: true, crossSpaceTransfer: true, crossSpaceRecall: false }),
377
+ // v1.5.6 microkernel boundary. Default ON so behaviour is unchanged.
378
+ // v1.9.0: `layers` is the canonical name — the three physical directories the
379
+ // orchestrator fills (session / project / public). `multiSpace` is the older
380
+ // name for the SAME switch and stays accepted as a deprecated alias so a
381
+ // deployed profile keeps booting. Turning it off makes the engine a strict
382
+ // single-directory core (targetSpaceId must be "default"), and
383
+ // crossSpaceTransfer requires it.
384
+ features: Object.freeze({
385
+ layers: true,
386
+ multiSpace: true,
387
+ crossSpaceTransfer: true,
388
+ crossSpaceRecall: false,
389
+ }),
378
390
  // v1.5.6 L2 multi-merge: condense duplicate same-tag episodes into one record,
379
391
  // pinned and ordinary groups strictly separated. Offline (maintain) only.
380
392
  l2Merge: Object.freeze({ enabled: true, minGroupSize: 2, maxGroupsPerRun: 5, maxSummaryChars: 400 }),
@@ -596,34 +608,47 @@ function normaliseRaw(raw) {
596
608
  }
597
609
 
598
610
  /**
599
- * v1.5.6: multi-space is a CAPABILITY, not a config promise. It is active only when
600
- * the Host provides the Orchestrator service AND the profile has not turned
601
- * `features.multiSpace` off; otherwise the engine runs the strict single-space core.
611
+ * v1.9.0: the layered world is a CAPABILITY, not a config promise. It is active only
612
+ * when the Host provides the Orchestrator service AND the profile has not turned
613
+ * `features.layers` off; otherwise the engine runs the strict single-directory core.
614
+ *
615
+ * `features.multiSpace` is the deprecated alias for the same switch; the resolver
616
+ * keeps both keys in sync, so either name reads the same effective value.
602
617
  */
603
- export function multiSpaceActive(config, hasOrchestrator) {
604
- return hasOrchestrator === true && config?.features?.multiSpace !== false;
618
+ export function layersActive(config, hasOrchestrator) {
619
+ return hasOrchestrator === true && config?.features?.layers !== false;
605
620
  }
606
621
 
607
622
  /**
608
- * v1.6.7 (M6): WHY multi-space is on or off, so a caller never has to guess whether
609
- * `features.multiSpace: true` was honoured.
623
+ * v1.6.7 (M6): WHY the layered world is on or off, so a caller never has to guess
624
+ * whether `features.layers: true` was honoured.
610
625
  *
611
- * Before this, the default `features.multiSpace: true` combined with
612
- * `multiSpaceActive()` returning false whenever no adapter was injected meant a user
613
- * who explicitly enabled the feature silently got single-space behaviour with no
614
- * explanation. The flag now reports one of three states instead of a bare boolean.
626
+ * The default is `true`, but the effective answer is false whenever no adapter was
627
+ * injected — a user who explicitly enabled the feature would otherwise silently get
628
+ * single-directory behaviour with no explanation. The flag reports one of three
629
+ * states instead of a bare boolean.
615
630
  *
616
631
  * @param {object} config resolved config
617
632
  * @param {boolean} hasOrchestrator true when an injected `orchestrator` service can
618
- * actually create a space adapter
633
+ * actually create a layer adapter
619
634
  * @returns {'active'|'disabled-by-config'|'orchestrator-missing'}
620
635
  */
621
- export function multiSpaceReason(config, hasOrchestrator) {
622
- if (config?.features?.multiSpace === false) return 'disabled-by-config';
636
+ export function layersReason(config, hasOrchestrator) {
637
+ if (config?.features?.layers === false) return 'disabled-by-config';
623
638
  if (hasOrchestrator !== true) return 'orchestrator-missing';
624
639
  return 'active';
625
640
  }
626
641
 
642
+ /** @deprecated v1.9.0 — use `layersActive`. Kept so older callers keep working. */
643
+ export function multiSpaceActive(config, hasOrchestrator) {
644
+ return layersActive(config, hasOrchestrator);
645
+ }
646
+
647
+ /** @deprecated v1.9.0 — use `layersReason`. Kept so older callers keep working. */
648
+ export function multiSpaceReason(config, hasOrchestrator) {
649
+ return layersReason(config, hasOrchestrator);
650
+ }
651
+
627
652
  /**
628
653
  * Migrate a config object from any older schema to the current one.
629
654
  *
@@ -1348,25 +1373,47 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1348
1373
  if (!isPlainObject(featuresIn)) {
1349
1374
  throw configError(ErrorCodes.CONFIG_INVALID_TYPE, 'config.features must be an object', { key: 'features' });
1350
1375
  }
1351
- const featureMultiSpace = requireBoolean(
1352
- featuresIn.multiSpace === undefined ? defaults.features.multiSpace : featuresIn.multiSpace,
1353
- 'features.multiSpace',
1354
- );
1376
+ // v1.9.0: `layers` is canonical and `multiSpace` is its deprecated alias. When
1377
+ // BOTH are written they must agree — silently preferring one would let a profile
1378
+ // say "off" in one key and "on" in the other, which is exactly the kind of
1379
+ // unexplained capability flip this config layer refuses to allow.
1380
+ const featuresLayersWanted =
1381
+ featuresIn.layers === undefined
1382
+ ? featuresIn.multiSpace === undefined
1383
+ ? defaults.features.layers
1384
+ : featuresIn.multiSpace
1385
+ : featuresIn.layers;
1386
+ const featureLayers = requireBoolean(featuresLayersWanted, 'features.layers');
1387
+ if (
1388
+ featuresIn.layers !== undefined &&
1389
+ featuresIn.multiSpace !== undefined &&
1390
+ featuresIn.layers !== featuresIn.multiSpace
1391
+ ) {
1392
+ throw configError(
1393
+ ErrorCodes.CONFIG_OUT_OF_RANGE,
1394
+ 'config.features.layers and the deprecated config.features.multiSpace disagree; set only features.layers',
1395
+ { key: 'features.layers', layers: featuresIn.layers, multiSpace: featuresIn.multiSpace },
1396
+ );
1397
+ }
1398
+ // Kept as a mirror of `layers` (not an independent switch) so every existing
1399
+ // reader — UI, tests, a deployed profile's own tooling — keeps seeing the value
1400
+ // it already understands.
1401
+ const featureMultiSpace = featureLayers;
1355
1402
  const featureCrossSpaceTransfer = requireBoolean(
1356
1403
  featuresIn.crossSpaceTransfer === undefined
1357
- ? // Turning multi-space off implies no cross-space transfer: require the
1404
+ ? // Turning the layered world off implies no cross-space transfer: require the
1358
1405
  // operator to opt back IN explicitly, never the other way around.
1359
- featureMultiSpace
1406
+ featureLayers
1360
1407
  ? defaults.features.crossSpaceTransfer
1361
1408
  : false
1362
1409
  : featuresIn.crossSpaceTransfer,
1363
1410
  'features.crossSpaceTransfer',
1364
1411
  );
1365
- if (featureCrossSpaceTransfer && !featureMultiSpace) {
1412
+ if (featureCrossSpaceTransfer && !featureLayers) {
1366
1413
  throw configError(
1367
1414
  ErrorCodes.CONFIG_OUT_OF_RANGE,
1368
- 'config.features.crossSpaceTransfer requires features.multiSpace (a single-space core has no target space)',
1369
- { key: 'features.crossSpaceTransfer', multiSpace: false },
1415
+ 'config.features.crossSpaceTransfer requires features.layers (a single-directory core has no target space)',
1416
+ { key: 'features.crossSpaceTransfer', layers: false },
1370
1417
  );
1371
1418
  }
1372
1419
  // v1.5.6: cross-space recall aggregation is OPT-IN (and off by default): it
@@ -1375,14 +1422,15 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1375
1422
  featuresIn.crossSpaceRecall === undefined ? defaults.features.crossSpaceRecall : featuresIn.crossSpaceRecall,
1376
1423
  'features.crossSpaceRecall',
1377
1424
  );
1378
- if (featureCrossSpaceRecall && !featureMultiSpace) {
1425
+ if (featureCrossSpaceRecall && !featureLayers) {
1379
1426
  throw configError(
1380
1427
  ErrorCodes.CONFIG_OUT_OF_RANGE,
1381
- 'config.features.crossSpaceRecall requires features.multiSpace (a single-space core has only one space)',
1382
- { key: 'features.crossSpaceRecall', multiSpace: false },
1428
+ 'config.features.crossSpaceRecall requires features.layers (a single-directory core has only one space)',
1429
+ { key: 'features.crossSpaceRecall', layers: false },
1383
1430
  );
1384
1431
  }
1385
1432
  const featuresConfig = Object.freeze({
1433
+ layers: featureLayers,
1386
1434
  multiSpace: featureMultiSpace,
1387
1435
  crossSpaceTransfer: featureCrossSpaceTransfer,
1388
1436
  crossSpaceRecall: featureCrossSpaceRecall,
@@ -1527,6 +1575,22 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1527
1575
  'dream.onlyLowValley',
1528
1576
  ),
1529
1577
  llm: {
1578
+ // v1.9.1: which TRANSPORT offline Dream uses. `useHost` (default on) calls
1579
+ // the Host's own model, so Dream works with no endpoint and no credential;
1580
+ // the three keys below are the explicit override for a separate endpoint.
1581
+ useHost: requireBoolean(
1582
+ dreamLlmIn.useHost === undefined ? defaults.dream.llm.useHost : dreamLlmIn.useHost,
1583
+ 'dream.llm.useHost',
1584
+ ),
1585
+ // v1.9.2: the OUTPUT budget for one distillation. The engine used to derive
1586
+ // it from `maxSummaryChars` alone (`chars*2+64` = 464 by default), which a
1587
+ // reasoning model spends on reasoning and then runs out of room before the
1588
+ // closing brace — the answer arrives with no `{` and every run fell back.
1589
+ maxTokens: requireInteger(
1590
+ dreamLlmIn.maxTokens === undefined ? defaults.dream.llm.maxTokens : dreamLlmIn.maxTokens,
1591
+ 'dream.llm.maxTokens',
1592
+ { min: 128, max: 16_000 },
1593
+ ),
1530
1594
  baseUrl: optionalString(dreamLlmIn.baseUrl, 'dream.llm.baseUrl'),
1531
1595
  model: optionalString(dreamLlmIn.model, 'dream.llm.model'),
1532
1596
  apiKey: optionalString(dreamLlmIn.apiKey, 'dream.llm.apiKey'),
@@ -0,0 +1,109 @@
1
+ /**
2
+ * A dumb, path-addressed mailbox for the hippocampus.
3
+ *
4
+ * RED LINE — a mailbox only. The hippocampus must NOT dedupe, summarise,
5
+ * distil or archive dropbox content. It appends opaque lines and hands them
6
+ * back verbatim. All interpretation belongs to the orchestrator
7
+ * (`dsh-orchestrator`), which owns the cycle:
8
+ *
9
+ * read_dropbox(dataDir) -> LLM / business logic -> write_event(dataDir, ...)
10
+ * -> clear_dropbox(dataDir)
11
+ *
12
+ * Storage is `<dataDir>/state/dropbox.jsonl`, one JSON object per line.
13
+ * Like `pureApi.js`, this module is addressed by a physical `dataDir` only:
14
+ * no spaces, no projects, no config, no singleton state.
15
+ */
16
+
17
+ import crypto from 'node:crypto';
18
+ import path from 'node:path';
19
+
20
+ import { invalidInput } from '../errors.js';
21
+ import { appendLineDurable, readText, writeFileAtomic } from '../util.js';
22
+
23
+ /** Reject anything that is not an absolute physical directory string. */
24
+ function assertDataDir(dataDir) {
25
+ if (typeof dataDir !== 'string' || !dataDir.trim() || !path.isAbsolute(dataDir)) {
26
+ throw invalidInput('dataDir must be an absolute path string', { dataDir });
27
+ }
28
+ return path.resolve(dataDir);
29
+ }
30
+
31
+ /**
32
+ * Absolute path of the dropbox JSONL file for one `dataDir`.
33
+ *
34
+ * @param {string} dataDir absolute physical directory
35
+ * @returns {string} `<dataDir>/state/dropbox.jsonl`
36
+ */
37
+ export function dropboxPath(dataDir) {
38
+ return path.join(assertDataDir(dataDir), 'state', 'dropbox.jsonl');
39
+ }
40
+
41
+ /** Parse JSONL tolerantly: blank and corrupt lines are skipped, never thrown. */
42
+ function parseItems(text) {
43
+ if (!text) return [];
44
+ const items = [];
45
+ for (const raw of text.split('\n')) {
46
+ const line = raw.trim();
47
+ if (!line) continue;
48
+ try {
49
+ const value = JSON.parse(line);
50
+ if (value && typeof value === 'object' && !Array.isArray(value)) items.push(value);
51
+ } catch {
52
+ /* a handler's half-written line must not break the mailbox */
53
+ }
54
+ }
55
+ return items;
56
+ }
57
+
58
+ /**
59
+ * Append one item to the mailbox, creating `state/` when needed.
60
+ *
61
+ * The item is stored as `{ at, ...payload }`; `at` is the append time and a
62
+ * caller-supplied `payload.at` is overridden. `id` is generated unless the
63
+ * payload already carries a non-empty string one.
64
+ *
65
+ * @param {string} dataDir absolute physical directory
66
+ * @param {object} payload arbitrary JSON object, stored verbatim
67
+ * @returns {{ok: true, id: string, path: string, count: number}} count = items now queued
68
+ */
69
+ export function append_to_dropbox(dataDir, payload = {}) {
70
+ const file = dropboxPath(dataDir);
71
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
72
+ throw invalidInput('payload must be an object');
73
+ }
74
+ const givenId = typeof payload.id === 'string' && payload.id.trim() ? payload.id : null;
75
+ const id = givenId ?? `dr_${crypto.randomBytes(12).toString('hex')}`;
76
+ const item = { at: Date.now(), ...payload, id };
77
+ appendLineDurable(file, `${JSON.stringify(item)}\n`);
78
+ return { ok: true, id, path: file, count: parseItems(readText(file)).length };
79
+ }
80
+
81
+ /**
82
+ * Read every queued item, in append order.
83
+ *
84
+ * A missing file reads as an empty mailbox; corrupt lines are skipped.
85
+ *
86
+ * @param {string} dataDir absolute physical directory
87
+ * @returns {{ok: true, items: object[], path: string}}
88
+ */
89
+ export function read_dropbox(dataDir) {
90
+ const file = dropboxPath(dataDir);
91
+ return { ok: true, items: parseItems(readText(file)), path: file };
92
+ }
93
+
94
+ /**
95
+ * Truncate the mailbox to zero bytes.
96
+ *
97
+ * Items appended after the clear start a fresh mailbox; content that was
98
+ * already consumed is gone by design (the orchestrator clears only after it
99
+ * has handled every item).
100
+ *
101
+ * @param {string} dataDir absolute physical directory
102
+ * @returns {{ok: true, cleared: number, path: string}} cleared = items dropped
103
+ */
104
+ export function clear_dropbox(dataDir) {
105
+ const file = dropboxPath(dataDir);
106
+ const cleared = parseItems(readText(file)).length;
107
+ writeFileAtomic(file, '');
108
+ return { ok: true, cleared, path: file };
109
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Pure, path-addressed storage surface for the hippocampus.
3
+ *
4
+ * This is the "dumb database" layer: every function is addressed by ONE absolute
5
+ * physical directory plus opaque ids. There is deliberately no notion of spaces,
6
+ * projects, sessions routing, configuration singletons or sibling plugins here —
7
+ * two different `dataDir`s are fully isolated by construction.
8
+ *
9
+ * Write path: `write_event()` appends one record to `<dataDir>/log` (the same
10
+ * segmented, generation-addressed log the rest of the package reads), then
11
+ * flushes and closes its own handle. Read path: `recall()` re-scans that one
12
+ * directory and returns a simple ranked slice. It is NOT the semantic ranking
13
+ * engine; it exists so a caller that only knows a path can store and fetch.
14
+ *
15
+ * Records are built with the same identity helpers as the engine
16
+ * (`contentHashOf` / `eventIdFor`), so a record written here remains parseable
17
+ * by `src/log/records.js#parseRecord` and therefore by `LogStore#snapshot`.
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+
23
+ import { invalidInput } from '../errors.js';
24
+ import { LogStore } from '../log/logStore.js';
25
+ import { RECORD_TYPES, buildEpisode } from '../log/records.js';
26
+ import { contentHashOf, eventIdFor, normaliseEventTime } from '../identity.js';
27
+ import { clamp01, readJson, readText, round } from '../util.js';
28
+
29
+ /** Reject anything that is not an absolute physical directory string. */
30
+ function assertDataDir(dataDir) {
31
+ if (typeof dataDir !== 'string' || !dataDir.trim() || !path.isAbsolute(dataDir)) {
32
+ throw invalidInput('dataDir must be an absolute path string', { dataDir });
33
+ }
34
+ return path.resolve(dataDir);
35
+ }
36
+
37
+ function logRoot(dataDir) {
38
+ return path.join(dataDir, 'log');
39
+ }
40
+
41
+ /**
42
+ * Read every record under one directory's append log.
43
+ *
44
+ * The pure layer must stay readable even when a single line is damaged, so a
45
+ * malformed line is skipped instead of aborting the whole scan (unlike the
46
+ * engine's strict `parseRecord`, which owns integrity checking).
47
+ *
48
+ * @param {string} dataDir absolute physical directory
49
+ * @returns {object[]} parsed records in log order
50
+ */
51
+ function readRawRecords(dataDir) {
52
+ const root = logRoot(dataDir);
53
+ const current = readText(path.join(root, 'CURRENT'));
54
+ if (!current || !current.trim()) return [];
55
+ const gen = current.trim();
56
+ if (!/^gen-\d{6}$/.test(gen)) return [];
57
+ const dir = path.join(root, gen);
58
+ const manifest = readJson(path.join(dir, 'manifest.json'), null);
59
+ let segmentNames = null;
60
+ if (manifest && Array.isArray(manifest.segments)) {
61
+ segmentNames = manifest.segments.map((segment) => segment && segment.name).filter(Boolean);
62
+ } else {
63
+ try {
64
+ segmentNames = fs
65
+ .readdirSync(dir)
66
+ .filter((name) => name.endsWith('.jsonl'))
67
+ .sort();
68
+ } catch {
69
+ return [];
70
+ }
71
+ }
72
+ const records = [];
73
+ for (const name of segmentNames) {
74
+ const text = readText(path.join(dir, name));
75
+ if (!text) continue;
76
+ for (const raw of text.split('\n')) {
77
+ const line = raw.trim();
78
+ if (!line) continue;
79
+ try {
80
+ const value = JSON.parse(line);
81
+ if (value && typeof value === 'object') records.push(value);
82
+ } catch {
83
+ /* skip one corrupt line; the rest of the directory stays readable */
84
+ }
85
+ }
86
+ }
87
+ return records;
88
+ }
89
+
90
+ /** Targets cancelled by a later `restore` are NOT deleted; ordering matters. */
91
+ function collectDeleted(records) {
92
+ const deleted = new Set();
93
+ for (const record of records) {
94
+ if (record.type === RECORD_TYPES.FORGET && typeof record.target === 'string') deleted.add(record.target);
95
+ else if (record.type === RECORD_TYPES.RESTORE && typeof record.target === 'string') deleted.delete(record.target);
96
+ }
97
+ return deleted;
98
+ }
99
+
100
+ /**
101
+ * Occurrence indices disambiguate identical content at the same instant. The
102
+ * pure layer has no dedupe index, so it derives the next index from the log.
103
+ */
104
+ function selectOccurrenceIndex(records, contentHash, eventTime) {
105
+ let max = -1;
106
+ for (const record of records) {
107
+ if (record.content_hash !== contentHash || record.event_time !== eventTime) continue;
108
+ if (Number.isInteger(record.occurrence_index) && record.occurrence_index > max) max = record.occurrence_index;
109
+ }
110
+ return max + 1;
111
+ }
112
+
113
+ /** Case-insensitive comparison form for tags; underscores are preserved. */
114
+ function canonicalTag(value) {
115
+ return String(value).trim().toLowerCase().replace(/\s+/g, '-');
116
+ }
117
+
118
+ function textScoreOf(content, text) {
119
+ if (!text) return 0;
120
+ const haystack = content.toLowerCase();
121
+ if (haystack.includes(text)) return 1;
122
+ const needles = text.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
123
+ if (needles.length === 0) return 0;
124
+ const tokens = new Set(haystack.split(/[^\p{L}\p{N}]+/u).filter(Boolean));
125
+ let overlap = 0;
126
+ for (const needle of needles) if (tokens.has(needle)) overlap += 1;
127
+ return overlap / needles.length;
128
+ }
129
+
130
+ function matchOf({ content, tags, salience, text, queryTags }) {
131
+ const textScore = textScoreOf(content, text);
132
+ let tagScore = 0;
133
+ if (queryTags.length > 0) {
134
+ const present = new Set(tags.map(canonicalTag));
135
+ let matched = 0;
136
+ for (const tag of queryTags) if (present.has(tag)) matched += 1;
137
+ tagScore = matched / queryTags.length;
138
+ }
139
+ return { textScore, tagScore, score: round(0.6 * textScore + 0.25 * tagScore + 0.15 * clamp01(salience), 6) };
140
+ }
141
+
142
+ /**
143
+ * Append one event to the append-only log of exactly `dataDir`.
144
+ *
145
+ * @param {string} dataDir absolute physical directory
146
+ * @param {object} payload
147
+ * @param {string} payload.content non-empty memory text
148
+ * @param {Array<string|{tag: string, strength?: number}>} [payload.tags]
149
+ * @param {number} [payload.salience] 0..1, default 0.5
150
+ * @param {string|null} [payload.sessionId] stored at top level and in `meta.sessionId`
151
+ * @param {string} [payload.kind] free-form record kind, default 'note'
152
+ * @param {number|string|null} [payload.eventTime] epoch ms / ISO; default now
153
+ * @param {object|null} [payload.meta] caller metadata
154
+ * @returns {Promise<{ok: true, eventId: string, dataDir: string, eventTime: number}>}
155
+ */
156
+ export async function write_event(dataDir, payload = {}) {
157
+ const dir = assertDataDir(dataDir);
158
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
159
+ throw invalidInput('payload must be an object');
160
+ }
161
+ const content = payload.content;
162
+ if (typeof content !== 'string' || !content.trim()) {
163
+ throw invalidInput('content must be a non-empty string');
164
+ }
165
+ const tags = payload.tags === undefined || payload.tags === null ? [] : payload.tags;
166
+ if (!Array.isArray(tags)) throw invalidInput('tags must be an array');
167
+ const salience = payload.salience === undefined ? 0.5 : Number(payload.salience);
168
+ if (!Number.isFinite(salience) || salience < 0 || salience > 1) {
169
+ throw invalidInput('salience must be within [0,1]', { salience: payload.salience });
170
+ }
171
+ const sessionId = payload.sessionId === undefined || payload.sessionId === null ? null : payload.sessionId;
172
+ if (sessionId !== null && (typeof sessionId !== 'string' || !sessionId.trim())) {
173
+ throw invalidInput('sessionId must be a non-empty string or null', { sessionId });
174
+ }
175
+ const kind = payload.kind === undefined ? 'note' : payload.kind;
176
+ if (typeof kind !== 'string' || !kind.trim()) {
177
+ throw invalidInput('kind must be a non-empty string', { kind });
178
+ }
179
+ const meta = payload.meta === undefined || payload.meta === null ? null : payload.meta;
180
+ if (meta !== null && (typeof meta !== 'object' || Array.isArray(meta))) {
181
+ throw invalidInput('meta must be an object or null');
182
+ }
183
+
184
+ const now = Date.now();
185
+ const hasExplicitTime = payload.eventTime !== undefined && payload.eventTime !== null;
186
+ let eventTime;
187
+ if (hasExplicitTime) {
188
+ eventTime = normaliseEventTime(payload.eventTime);
189
+ if (eventTime === null) {
190
+ throw invalidInput('eventTime must resolve to epoch milliseconds', { eventTime: payload.eventTime });
191
+ }
192
+ } else {
193
+ eventTime = now;
194
+ }
195
+
196
+ // A session id is cheap to read at top level, so it goes in both places: the
197
+ // top-level field for scans and `meta.sessionId` so older readers still see it.
198
+ const storedMeta = { ...(meta ?? {}), ...(sessionId === null ? {} : { sessionId }) };
199
+ const payloadForHash = {
200
+ content,
201
+ tags,
202
+ salience,
203
+ ...(Object.keys(storedMeta).length > 0 ? { meta: storedMeta } : {}),
204
+ };
205
+ const contentHash = contentHashOf(payloadForHash);
206
+
207
+ const existing = readRawRecords(dir);
208
+ const occurrenceIndex = selectOccurrenceIndex(existing, contentHash, eventTime);
209
+ const record = buildEpisode({
210
+ payload: payloadForHash,
211
+ eventTime,
212
+ timeSource: hasExplicitTime ? 'caller' : 'ingest',
213
+ contentHash,
214
+ occurrenceIndex,
215
+ logTime: now,
216
+ });
217
+ record.kind = kind;
218
+ if (sessionId !== null) record.sessionId = sessionId;
219
+
220
+ // One short-lived store per write: the pure layer never shares open handles
221
+ // with the engine, so it cannot leak fds or keep another writer's lock.
222
+ const store = new LogStore({ root: logRoot(dir) });
223
+ try {
224
+ await store.append([record]);
225
+ store.flushSync();
226
+ } finally {
227
+ store.close();
228
+ }
229
+ return { ok: true, eventId: record.event_id, dataDir: dir, eventTime };
230
+ }
231
+
232
+ /**
233
+ * Read a simple ranked slice from exactly one directory.
234
+ *
235
+ * `filter.sessionId` is the load-bearing domain rule: a non-empty string keeps
236
+ * ONLY events written with that exact session id; omitted/null returns every
237
+ * event under `dataDir`. A supplied `query.text` or `query.tags` narrows the
238
+ * result set (each must match at least once) and also contributes to the
239
+ * rank score, together with salience and recency.
240
+ *
241
+ * @param {string} dataDir absolute physical directory
242
+ * @param {{text?: string, tags?: string[], topK?: number}} [query]
243
+ * @param {{sessionId?: string, since?: number, until?: number, kinds?: string[]}} [filter]
244
+ * @returns {{ok: true, dataDir: string, hits: object[], total: number, scanned: number}}
245
+ */
246
+ export function recall(dataDir, query = {}, filter = {}) {
247
+ const dir = assertDataDir(dataDir);
248
+ const q = query && typeof query === 'object' ? query : {};
249
+ const f = filter && typeof filter === 'object' ? filter : {};
250
+
251
+ const text = typeof q.text === 'string' ? q.text.trim().toLowerCase() : '';
252
+ const queryTags = (Array.isArray(q.tags) ? q.tags : []).map(canonicalTag).filter(Boolean);
253
+ const topK = Number.isInteger(q.topK) && q.topK > 0 ? q.topK : 20;
254
+
255
+ const sessionId = typeof f.sessionId === 'string' && f.sessionId.trim() ? f.sessionId : null;
256
+ const since = Number.isFinite(Number(f.since)) ? Number(f.since) : null;
257
+ const until = Number.isFinite(Number(f.until)) ? Number(f.until) : null;
258
+ const kinds =
259
+ Array.isArray(f.kinds) && f.kinds.length > 0
260
+ ? new Set(f.kinds.filter((kind) => typeof kind === 'string'))
261
+ : null;
262
+
263
+ const records = readRawRecords(dir);
264
+ const deleted = collectDeleted(records);
265
+ const matches = [];
266
+ for (const record of records) {
267
+ if (record.type !== RECORD_TYPES.EPISODE) continue;
268
+ if (typeof record.event_id !== 'string' || deleted.has(record.event_id)) continue;
269
+ const recordSession =
270
+ typeof record.sessionId === 'string'
271
+ ? record.sessionId
272
+ : typeof record.meta?.sessionId === 'string'
273
+ ? record.meta.sessionId
274
+ : null;
275
+ if (sessionId !== null && recordSession !== sessionId) continue;
276
+ const eventTime = Number.isFinite(record.event_time) ? record.event_time : 0;
277
+ if (since !== null && eventTime < since) continue;
278
+ if (until !== null && eventTime > until) continue;
279
+ const kind = typeof record.kind === 'string' ? record.kind : 'note';
280
+ if (kinds !== null && !kinds.has(kind)) continue;
281
+ matches.push({ record, eventTime, sessionId: recordSession });
282
+ }
283
+
284
+ const hits = [];
285
+ for (const { record, eventTime, sessionId: recordSession } of matches) {
286
+ const content = typeof record.content === 'string' ? record.content : '';
287
+ const tags = (Array.isArray(record.tags) ? record.tags : [])
288
+ .map((tag) => (typeof tag === 'string' ? tag : tag && tag.tag))
289
+ .filter((tag) => typeof tag === 'string' && tag.length > 0);
290
+ const salience = clamp01(Number(record.salience) || 0);
291
+ const match = matchOf({ content, tags, salience, text, queryTags });
292
+ // A supplied text or tag query is a filter, not just a nudge: a caller that
293
+ // asks for "alpha" wants the alpha events, not the whole mailbox reordered.
294
+ if (text && match.textScore === 0) continue;
295
+ if (queryTags.length > 0 && match.tagScore === 0) continue;
296
+ hits.push({
297
+ eventId: record.event_id,
298
+ content,
299
+ tags,
300
+ sessionId: recordSession,
301
+ eventTime,
302
+ score: match.score,
303
+ });
304
+ }
305
+ hits.sort((a, b) => b.score - a.score || b.eventTime - a.eventTime || (a.eventId < b.eventId ? -1 : 1));
306
+ return { ok: true, dataDir: dir, hits: hits.slice(0, topK), total: hits.length, scanned: records.length };
307
+ }