open-memex 0.9.0-alpha.3 → 0.9.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,234 @@
1
+ /**
2
+ * §20.3 (D88): the graph layer — structural edges only, extracted by
3
+ * deterministic rules. No LLM, no network: everything here runs on the
4
+ * memory rows already on this machine.
5
+ *
6
+ * Borrowing Graphify's tree-sitter principle (§20.5): structure is
7
+ * *extracted*, not inferred. What the memory states explicitly in
8
+ * frontmatter (supersedes chain, derived_from) and in its body (a
9
+ * `[[wiki-link]]` around another memory's id) becomes an EXTRACTED edge —
10
+ * evidence the source itself wrote, confidence `high`. What the system
11
+ * merely notices (a bare id in prose, two active memories sharing a tag)
12
+ * is an INFERRED edge — a suggestion, never presented as a fact (§11's
13
+ * trust model). Inferred edges are always marked, so a graph hit can never
14
+ * quietly become "the source said so".
15
+ *
16
+ * Whether `related` enters the frontmatter is a v0.3 protocol decision
17
+ * (§20.8); until then edges live only in this derived layer. The layer is
18
+ * rebuildable: `graph build` re-derives everything from the Markdown
19
+ * source of truth (D1).
20
+ */
21
+ /**
22
+ * The deterministic confidence ladder for shared-tag edges: one shared tag
23
+ * is the weakest signal, two starts to connect, three or more together are
24
+ * a strong one. Decision D91 keeps this fixed — an agent reading a graph
25
+ * hit gets the same meaning on every install.
26
+ */
27
+ export function sharedTagConfidence(sharedCount) {
28
+ if (sharedCount >= 3)
29
+ return "high";
30
+ if (sharedCount === 2)
31
+ return "medium";
32
+ return "low";
33
+ }
34
+ /**
35
+ * Crockford-base32 alphabet ULID (0-9, A-Z minus I, L, O, U) delimited by
36
+ * non-alphanumerics. The look-arounds keep a longer prefixed token from
37
+ * matching as a "mention": only a standalone id in the body counts as
38
+ * explicit evidence. The class must exclude L as well as I/O/U — a token
39
+ * like `FLATBATTERYWELLSXXQZABCDEF` is a word, not an id, and an EXTRACTED
40
+ * edge means the source said it explicitly.
41
+ */
42
+ const ULID_BODY = "[0-9A-HJKMNP-TV-Z]{26}";
43
+ /**
44
+ * A `[[ULID]]` wiki-link is the writer's explicit statement that this is a
45
+ * reference — EXTRACTED. A bare ULID is an id typed in prose: the system
46
+ * noticed it, it was not marked as a link — INFERRED (§20.3, D91).
47
+ */
48
+ const WIKI_LINK_RE = new RegExp(`\\[\\[(${ULID_BODY})\\]\\]`, "g");
49
+ const BARE_ULID_RE = new RegExp(`(?<![0-9A-Z])${ULID_BODY}(?![0-9A-Z])`, "g");
50
+ /**
51
+ * Per-node cap on INFERRED shared-tag edges. A dense tag vocabulary would
52
+ * otherwise grow the stored layer quadratically; the cap keeps, per node,
53
+ * the top neighbours by (shared count desc, id asc) — deterministic — and
54
+ * never drops an EXTRACTED edge.
55
+ */
56
+ export const MAX_SHARED_TAG_EDGES_PER_NODE = 12;
57
+ /**
58
+ * The node count above which shared-tag inference is skipped entirely.
59
+ * At that scale the O(n²) pair scan stops being cheap; the LLM half of
60
+ * §20, not more low-confidence edges, is the answer there.
61
+ */
62
+ export const MAX_SHARED_TAG_NODES = 2000;
63
+ /** One edge per (from, to, type). Used while collecting raw candidates. */
64
+ function dedupInsert(list, edge) {
65
+ for (const e of list) {
66
+ if (e.from === edge.from && e.to === edge.to && e.type === edge.type)
67
+ return;
68
+ }
69
+ list.push(edge);
70
+ }
71
+ const pairKey = (a, b) => (a < b ? `${a}\u0000${b}` : `${b}\u0000${a}`);
72
+ /**
73
+ * Extract all structural edges for a set of nodes (§20.3):
74
+ *
75
+ * - `supersedes` — frontmatter chain, new → old (EXTRACTED / high).
76
+ * - `derived-from` — frontmatter `derived_from`, copy → original (EXTRACTED / high).
77
+ * - `relates-to` — EXTRACTED when one body wraps another memory's ULID in
78
+ * `[[ ]]` (an explicit link); INFERRED/high when an id
79
+ * appears bare in prose; INFERRED at the shared-tag
80
+ * confidence ladder when two active memories share tags.
81
+ * One edge per unordered pair; an EXTRACTED body-mention
82
+ * beats the INFERRED links for the same pair.
83
+ *
84
+ * Edges are returned sorted (from, to, type) so two builds over the same
85
+ * data produce byte-identical output — the graph must behave like a
86
+ * derived index, not like a fickle cache.
87
+ */
88
+ export function extractEdges(nodes) {
89
+ const raw = [];
90
+ for (const n of nodes) {
91
+ if (n.supersedes && n.supersedes !== n.id) {
92
+ dedupInsert(raw, {
93
+ from: n.id,
94
+ to: n.supersedes,
95
+ type: "supersedes",
96
+ provenance: "EXTRACTED",
97
+ confidence: "high",
98
+ via: "supersede-chain",
99
+ });
100
+ }
101
+ if (n.derived_from && n.derived_from !== n.id) {
102
+ dedupInsert(raw, {
103
+ from: n.id,
104
+ to: n.derived_from,
105
+ type: "derived-from",
106
+ provenance: "EXTRACTED",
107
+ confidence: "high",
108
+ via: "derive",
109
+ });
110
+ }
111
+ }
112
+ // Body mentions are stored even when the mentioned id is dangling —
113
+ // lint enumerates it (graph/lint.ts); the query layer simply never
114
+ // traverses into a node that does not exist.
115
+ for (const n of nodes) {
116
+ const skip = new Set([n.id, n.supersedes, n.derived_from].filter((x) => Boolean(x)));
117
+ // Explicit wiki-links first so dedupInsert keeps the EXTRACTED edge
118
+ // when the same pair is also mentioned bare somewhere in the body.
119
+ for (const m of n.body.matchAll(WIKI_LINK_RE)) {
120
+ const id = m[1];
121
+ if (skip.has(id))
122
+ continue;
123
+ dedupInsert(raw, {
124
+ from: n.id,
125
+ to: id,
126
+ type: "relates-to",
127
+ provenance: "EXTRACTED",
128
+ confidence: "high",
129
+ via: "wiki-link",
130
+ });
131
+ }
132
+ // Bare ids: the system noticed an id in prose, the writer did not link
133
+ // it — INFERRED/high (a 26-char id is an unambiguous id, not a guess;
134
+ // the uncertainty is about the *relationship*, hence not EXTRACTED).
135
+ // Strip the wiki-links first so they are not counted twice.
136
+ const bare = n.body.replace(WIKI_LINK_RE, " ");
137
+ for (const m of bare.matchAll(BARE_ULID_RE)) {
138
+ const id = m[0];
139
+ if (skip.has(id))
140
+ continue;
141
+ dedupInsert(raw, {
142
+ from: n.id,
143
+ to: id,
144
+ type: "relates-to",
145
+ provenance: "INFERRED",
146
+ confidence: "high",
147
+ via: "body-mention",
148
+ });
149
+ }
150
+ }
151
+ // Shared-tag inference scans ACTIVE memories only (a superseded version
152
+ // of a fact would otherwise double every inference) and is canonicalized
153
+ // to the unordered pair so `relates-to` stays one edge per pair.
154
+ if (nodes.length > 0 && nodes.length <= MAX_SHARED_TAG_NODES) {
155
+ const active = nodes.filter((n) => n.status === "active");
156
+ const tagSets = new Map();
157
+ for (const n of active)
158
+ tagSets.set(n.id, new Set(n.tags));
159
+ const candidates = new Map();
160
+ const pairShared = new Map();
161
+ const listFor = (id) => {
162
+ let list = candidates.get(id);
163
+ if (!list) {
164
+ list = [];
165
+ candidates.set(id, list);
166
+ }
167
+ return list;
168
+ };
169
+ for (let i = 0; i < active.length; i++) {
170
+ const a = active[i];
171
+ const aSet = tagSets.get(a.id);
172
+ for (let j = i + 1; j < active.length; j++) {
173
+ const b = active[j];
174
+ const bSet = tagSets.get(b.id);
175
+ const shared = [];
176
+ for (const t of aSet)
177
+ if (bSet.has(t))
178
+ shared.push(t);
179
+ if (shared.length === 0)
180
+ continue;
181
+ shared.sort();
182
+ pairShared.set(pairKey(a.id, b.id), shared);
183
+ listFor(a.id).push({ to: b.id, shared });
184
+ listFor(b.id).push({ to: a.id, shared });
185
+ }
186
+ }
187
+ for (const [id, list] of candidates) {
188
+ list.sort((x, y) => y.shared.length - x.shared.length || x.to.localeCompare(y.to));
189
+ for (const c of list.slice(0, MAX_SHARED_TAG_EDGES_PER_NODE)) {
190
+ // Canonical direction + skip self-order duplicates: emit each
191
+ // unordered pair exactly once, from the smaller id's own list.
192
+ if (id >= c.to)
193
+ continue;
194
+ dedupInsert(raw, {
195
+ from: id,
196
+ to: c.to,
197
+ type: "relates-to",
198
+ provenance: "INFERRED",
199
+ confidence: sharedTagConfidence(pairShared.get(pairKey(id, c.to)).length),
200
+ via: `shared-tag:${pairShared.get(pairKey(id, c.to)).join(",")}`,
201
+ });
202
+ }
203
+ }
204
+ }
205
+ // Collapse relates-to to one edge per unordered pair, canonicalized to
206
+ // the smaller id as `from`; the EXTRACTED body-mention beats the
207
+ // INFERRED shared-tag edge for the same pair. The cap is per node, so
208
+ // the two sides of a pair can disagree on which of them kept the edge —
209
+ // canonicalizing here, after collection, is what makes the result
210
+ // independent of which candidate list the edge happened to survive in.
211
+ const relates = new Map();
212
+ const out = [];
213
+ for (const e of raw) {
214
+ if (e.type !== "relates-to") {
215
+ out.push(e);
216
+ continue;
217
+ }
218
+ const from = e.from < e.to ? e.from : e.to;
219
+ const to = e.from < e.to ? e.to : e.from;
220
+ const k = pairKey(from, to);
221
+ const cur = relates.get(k);
222
+ if (!cur || (cur.provenance === "INFERRED" && e.provenance === "EXTRACTED")) {
223
+ relates.set(k, { ...e, from, to });
224
+ }
225
+ }
226
+ for (const e of relates.values())
227
+ out.push(e);
228
+ out.sort((x, y) => x.from === y.from
229
+ ? x.to === y.to
230
+ ? x.type.localeCompare(y.type)
231
+ : x.to.localeCompare(y.to)
232
+ : x.from.localeCompare(y.from));
233
+ return out;
234
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * §20.4 (D88): graph lint — a health check that only discovers and
3
+ * reports; it never auto-resolves (Principle 5). The findings are the
4
+ * input the promotion flow (§5) and D78's curate step consume later:
5
+ * "which memories contradict (LLM half), which are orphaned, which are
6
+ * stale". Contradiction detection needs the LLM half of §20 and is
7
+ * deliberately out of D91's deterministic subset.
8
+ *
9
+ * Deterministic checks in D91:
10
+ * - orphan — an active memory with zero structural edges: written
11
+ * but never linked, in no topic.
12
+ * - dangling-edge — an edge points at an id that does not exist in the
13
+ * index (a mention to a deleted/foreign memory). The
14
+ * chain-repair path (§3.3) self-heals frontmatter links
15
+ * with a warning; lint just enumerates the leftovers.
16
+ * - stale — an active memory whose body is a near-duplicate
17
+ * (Jaccard ≥ 0.8, the §3.4 threshold) of a superseded or
18
+ * deprecated memory: it looks like a replacement that
19
+ * should have entered the supersede chain but didn't.
20
+ */
21
+ import { similarity, NEAR_DUP_THRESHOLD } from "../store/lifecycle.js";
22
+ export function lintGraph(nodes, edges, foreignIds = []) {
23
+ const byId = new Map(nodes.map((n) => [n.id, n]));
24
+ // Ids that exist in the store but OUTSIDE the linted scope: a propose-copy
25
+ // legitimately derives from the personal original, which lives in another
26
+ // scope — that is a foreign link, not a dangling one (D91).
27
+ const foreign = new Set(foreignIds);
28
+ const findings = [];
29
+ // Orphans: active memories not touched by any edge at all.
30
+ const connected = new Set();
31
+ for (const e of edges) {
32
+ if (byId.has(e.from))
33
+ connected.add(e.from);
34
+ if (byId.has(e.to))
35
+ connected.add(e.to);
36
+ }
37
+ for (const n of nodes) {
38
+ if (n.status !== "active")
39
+ continue;
40
+ if (!connected.has(n.id)) {
41
+ findings.push({
42
+ kind: "orphan",
43
+ id: n.id,
44
+ detail: "active but in no topic and linked to nothing — no tag overlap with other memories, no references",
45
+ });
46
+ }
47
+ }
48
+ // Dangling edges: an endpoint missing from the index. An endpoint that
49
+ // exists in ANOTHER scope is expected (the derive edge from a propose-copy
50
+ // points at the personal original) — skipped, not reported.
51
+ for (const e of edges) {
52
+ const missingFrom = !byId.has(e.from);
53
+ const missingTo = !byId.has(e.to);
54
+ if (!missingFrom && !missingTo)
55
+ continue;
56
+ if ((missingFrom && foreign.has(e.from)) || (missingTo && foreign.has(e.to)))
57
+ continue;
58
+ const other = missingFrom ? e.from : e.to;
59
+ const id = other === e.from ? e.to : e.from;
60
+ findings.push({
61
+ kind: "dangling-edge",
62
+ id,
63
+ other,
64
+ detail: `${e.type} edge ${e.via} points at ${other}, which is not in this index (deleted, another scope, or a foreign id)`,
65
+ });
66
+ }
67
+ // Stale: active content that nearly duplicates a superseded/deprecated
68
+ // memory — the newer copy and the old chain never met.
69
+ const retired = nodes.filter((n) => n.status === "superseded" || n.status === "deprecated");
70
+ for (const n of nodes) {
71
+ if (n.status !== "active")
72
+ continue;
73
+ for (const r of retired) {
74
+ const score = similarity(n.body, r.body);
75
+ if (score < NEAR_DUP_THRESHOLD)
76
+ continue;
77
+ findings.push({
78
+ kind: "stale",
79
+ id: n.id,
80
+ other: r.id,
81
+ detail: `active but ${score === 1 ? "identical" : `near-duplicate (${score.toFixed(2)})`} to ${r.id} (${r.status}) — one of them should be superseded by the other`,
82
+ });
83
+ }
84
+ }
85
+ findings.sort((a, b) => a.kind.localeCompare(b.kind) ||
86
+ a.id.localeCompare(b.id) ||
87
+ (a.other ?? "").localeCompare(b.other ?? ""));
88
+ return findings;
89
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * §20.4 / D88: the compiled outline — one compact topic map of what is in
3
+ * memory, derived from the structural graph and injected at session start.
4
+ *
5
+ * Injection-cost discipline (2026-10-19): "important but not every turn"
6
+ * stays on-demand, so this renderer exposes a line cap (D91: default 10)
7
+ * and nothing more. Topics are components of active memories joined ONLY
8
+ * by medium/high INFERRED shared-tag edges — a low-confidence edge (one
9
+ * shared tag) never contributes to a topic. That is the guard against the
10
+ * universal-tag collapse: one common tag across the whole store produces
11
+ * only low band edges, so the store cannot silently fuse into a single
12
+ * "topic" that says nothing. Body-mention / supersedes / derived-from
13
+ * edges are EXTRACTED evidence for queries and lint, not topic glue —
14
+ * two memories can point at each other in prose without belonging to
15
+ * the same cluster.
16
+ */
17
+ function oneLine(s, max = 120) {
18
+ const trimmed = s.replace(/\s+/g, " ").trim();
19
+ return trimmed.length > max ? trimmed.slice(0, max - 3) + "..." : trimmed;
20
+ }
21
+ /** Union-find over string ids. Both-sides threading keeps the same shape
22
+ * as the package's other pure modules (small, no deps). */
23
+ class UnionFind {
24
+ parent = new Map();
25
+ find(id) {
26
+ if (!this.parent.has(id))
27
+ this.parent.set(id, id);
28
+ let root = id;
29
+ while (this.parent.get(root) !== root)
30
+ root = this.parent.get(root);
31
+ let cur = id;
32
+ while (cur !== root) {
33
+ const next = this.parent.get(cur);
34
+ this.parent.set(cur, root);
35
+ cur = next;
36
+ }
37
+ return root;
38
+ }
39
+ union(a, b) {
40
+ const ra = this.find(a);
41
+ const rb = this.find(b);
42
+ if (ra !== rb)
43
+ this.parent.set(ra, rb);
44
+ }
45
+ }
46
+ /**
47
+ * Render the outline. `nodes` must be the visible set (active memories —
48
+ * the caller filters; superseded versions belong to history, not to the
49
+ * "what is in memory" map). `edges` must already be scoped to those nodes.
50
+ */
51
+ export function renderOutline(nodes, edges, opts = {}) {
52
+ // Floor 1, ceiling 30 (the same bound `config set graphOutlineLines`
53
+ // enforces) — a hand-edited config file must not be able to blow up the
54
+ // session-start injection.
55
+ const maxLines = Math.min(30, Math.max(1, opts.maxLines ?? 10));
56
+ const byId = new Map(nodes.map((n) => [n.id, n]));
57
+ const uf = new UnionFind();
58
+ for (const n of nodes)
59
+ uf.find(n.id);
60
+ for (const e of edges) {
61
+ if (e.provenance !== "INFERRED")
62
+ continue;
63
+ if (e.confidence !== "medium" && e.confidence !== "high")
64
+ continue;
65
+ // Only shared-tag evidence creates topics. A supersede chain, a
66
+ // derive copy or a body mention (even an INFERRED bare-id mention) is
67
+ // a query/lint relation, not topic glue — otherwise two memories with
68
+ // no common subject could form a "related" topic.
69
+ if (!e.via.startsWith("shared-tag:"))
70
+ continue;
71
+ if (!byId.has(e.from) || !byId.has(e.to))
72
+ continue;
73
+ uf.union(e.from, e.to);
74
+ }
75
+ const components = new Map();
76
+ for (const n of nodes) {
77
+ const root = uf.find(n.id);
78
+ const list = components.get(root);
79
+ if (list)
80
+ list.push(n);
81
+ else
82
+ components.set(root, [n]);
83
+ }
84
+ const topics = [];
85
+ let outside = 0;
86
+ for (const members of components.values()) {
87
+ if (members.length < 2) {
88
+ outside++;
89
+ continue;
90
+ }
91
+ // Topic name: the tag with the most occurrences among members
92
+ // (counted per member), ties broken lexicographically. A universal
93
+ // tag can win here when a topic is real anyway — that is fine; what
94
+ // it can never do by itself is CREATE the component (only medium+
95
+ // edges join).
96
+ const counts = new Map();
97
+ for (const m of members)
98
+ for (const t of m.tags)
99
+ counts.set(t, (counts.get(t) ?? 0) + 1);
100
+ let name = "";
101
+ let best = 0;
102
+ for (const [t, c] of counts) {
103
+ if (c > best || (c === best && (name === "" || t < name))) {
104
+ name = t;
105
+ best = c;
106
+ }
107
+ }
108
+ if (!name)
109
+ name = "related";
110
+ // Snippet members: largest-tag-bearing members first, stable by id.
111
+ const ordered = [...members].sort((x, y) => {
112
+ const cx = x.tags.includes(name) ? 1 : 0;
113
+ const cy = y.tags.includes(name) ? 1 : 0;
114
+ return cy - cx || x.id.localeCompare(y.id);
115
+ });
116
+ topics.push({
117
+ name,
118
+ size: members.length,
119
+ ids: members.map((m) => m.id),
120
+ snippetIds: ordered.slice(0, 2).map((m) => m.id),
121
+ });
122
+ }
123
+ topics.sort((a, b) => b.size - a.size || a.name.localeCompare(b.name) || a.ids[0].localeCompare(b.ids[0]));
124
+ const shown = topics.slice(0, maxLines);
125
+ const dropped = topics.length - shown.length;
126
+ const lines = [];
127
+ const exposureIds = [];
128
+ for (const t of shown) {
129
+ const members = t.ids
130
+ .map((id) => byId.get(id))
131
+ .filter(Boolean);
132
+ const tagMembers = members.filter((m) => m.tags.includes(t.name));
133
+ const snippets = (tagMembers.length > 0 ? tagMembers : members)
134
+ .slice(0, 2)
135
+ .map((m) => oneLine(m.snippet ?? m.body));
136
+ lines.push(`- ${t.name} (${t.size}): ${snippets.join(" | ")}`);
137
+ for (const id of t.snippetIds)
138
+ exposureIds.push(id);
139
+ }
140
+ if (dropped > 0)
141
+ lines.push(`(+${dropped} more topic${dropped === 1 ? "" : "s"} not shown)`);
142
+ if (outside > 0) {
143
+ lines.push(`(+${outside} memor${outside === 1 ? "y" : "ies"} not in any topic)`);
144
+ }
145
+ return { lines, topics: shown, exposureIds, droppedTopics: dropped, outsideCount: outside };
146
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * §20.4 (D88): graph traversal as a read path — a node's neighbours and
3
+ * the shortest path between two memories. Pure over the extracted edge
4
+ * list; the store layer (src/store/graph.ts) owns persistence and gets
5
+ * edges back from here untouched.
6
+ *
7
+ * Traversal is undirected: a `supersedes` edge says new → old in the
8
+ * frontmatter, but from the reader's side a chain link works both ways.
9
+ * Every hop carries its edge (type + provenance + confidence + via) so a
10
+ * query receipt can tell the reader which connection was travelled and
11
+ * whether it was INFERRED — §20.3's rule that an inferred link must never
12
+ * look like a fact that was in the source.
13
+ *
14
+ * Traversal never crosses into a node that is not in the node set: a
15
+ * dangling id in an edge is lint's finding to report, not a ghost node
16
+ * to walk through.
17
+ */
18
+ /** Undirected adjacency: id → outgoing + incoming edges. */
19
+ export function buildAdjacency(edges, nodeIds) {
20
+ const known = new Set(nodeIds);
21
+ const adj = new Map();
22
+ for (const id of known)
23
+ adj.set(id, []);
24
+ for (const e of edges) {
25
+ if (!known.has(e.from) || !known.has(e.to))
26
+ continue;
27
+ adj.get(e.from).push(e);
28
+ const back = { ...e, from: e.to, to: e.from };
29
+ adj.get(e.to).push(back);
30
+ }
31
+ return adj;
32
+ }
33
+ /**
34
+ * BFS neighbours of `startId`, nearest first (depth ascending, id
35
+ * ascending within a depth — deterministic output). `maxDepth` caps the
36
+ * walk; `maxNodes` caps the result the same way a search `limit` does.
37
+ * The start node itself is never returned.
38
+ */
39
+ export function graphNeighbours(startId, edges, nodeIds, opts = {}) {
40
+ const maxDepth = Math.max(1, Math.min(opts.maxDepth ?? 1, 6));
41
+ const maxNodes = Math.max(1, Math.min(opts.maxNodes ?? 20, 100));
42
+ const adj = buildAdjacency(edges, nodeIds);
43
+ if (!adj.has(startId))
44
+ return [];
45
+ const visited = new Set([startId]);
46
+ const hits = [];
47
+ let frontier = [];
48
+ const enqueue = (edges) => {
49
+ for (const e of [...edges].sort((a, b) => a.to.localeCompare(b.to))) {
50
+ if (visited.has(e.to))
51
+ continue;
52
+ visited.add(e.to);
53
+ frontier.push({ id: e.to, via: e });
54
+ }
55
+ };
56
+ enqueue(adj.get(startId));
57
+ let depth = 1;
58
+ for (; depth <= maxDepth && frontier.length > 0 && hits.length < maxNodes; depth++) {
59
+ const layer = [...frontier]
60
+ .sort((a, b) => a.id.localeCompare(b.id) || a.via.via.localeCompare(b.via.via))
61
+ .slice(0, maxNodes - hits.length);
62
+ for (const f of layer)
63
+ hits.push({ id: f.id, depth, via: f.via });
64
+ const next = [];
65
+ for (const f of layer) {
66
+ if (next.length + hits.length >= maxNodes)
67
+ break;
68
+ for (const e of adj.get(f.id) ?? []) {
69
+ if (visited.has(e.to))
70
+ continue;
71
+ visited.add(e.to);
72
+ next.push({ id: e.to, via: e });
73
+ }
74
+ }
75
+ frontier = next;
76
+ }
77
+ return hits;
78
+ }
79
+ /**
80
+ * Shortest path between two ids (BFS, undirected, `maxDepth` cap). Each
81
+ * hop keeps the edge object in travel direction — the receipt reads
82
+ * "A —[relates-to INFERRED/medium (shared-tag:x)]—> B", whether or not
83
+ * that was the stored direction.
84
+ */
85
+ export function shortestPath(fromId, toId, edges, nodeIds, opts = {}) {
86
+ const maxDepth = Math.max(1, Math.min(opts.maxDepth ?? 4, 6));
87
+ if (fromId === toId)
88
+ return { found: true, hops: [] };
89
+ const adj = buildAdjacency(edges, nodeIds);
90
+ if (!adj.has(fromId) || !adj.has(toId))
91
+ return { found: false, hops: [] };
92
+ const prev = new Map();
93
+ const visited = new Set([fromId]);
94
+ let frontier = [fromId];
95
+ for (let depth = 1; depth <= maxDepth; depth++) {
96
+ if (frontier.length === 0)
97
+ break;
98
+ const next = [];
99
+ for (const cur of frontier.sort((a, b) => a.localeCompare(b))) {
100
+ for (const e of [...(adj.get(cur) ?? [])].sort((a, b) => a.to.localeCompare(b.to))) {
101
+ if (visited.has(e.to))
102
+ continue;
103
+ visited.add(e.to);
104
+ prev.set(e.to, e);
105
+ if (e.to === toId) {
106
+ // Walk back, then reverse into travel order.
107
+ const hops = [];
108
+ let at = toId;
109
+ while (at !== fromId) {
110
+ const edge = prev.get(at);
111
+ hops.unshift(edge);
112
+ at = edge.from;
113
+ }
114
+ return { found: true, hops };
115
+ }
116
+ next.push(e.to);
117
+ }
118
+ }
119
+ frontier = next;
120
+ }
121
+ return { found: false, hops: [] };
122
+ }
@@ -2,6 +2,7 @@ import { loadConfig } from "./config.js";
2
2
  import { resolveProjectScope, resolveCwdScope, PERSONAL_SCOPE } from "./scope.js";
3
3
  import { db } from "./store/db.js";
4
4
  import { syncScope, upsertFromFile } from "./store/sync.js";
5
+ import { refreshGraphQuiet } from "./store/graph.js";
5
6
  import { scopeHasFiles } from "./store/migrate.js";
6
7
  import { writeMemoryFile, readMemoryFile, ulid, msToRfc3339, } from "./store/markdown.js";
7
8
  import { buildContextBlock } from "./retrieve/inject.js";
@@ -105,6 +106,9 @@ export function captureFromText(text, state, sessionID) {
105
106
  const mf = readMemoryFile(filePath);
106
107
  if (mf)
107
108
  upsertFromFile(mf);
109
+ // D91 ingest: keyword capture is a normal write path too — the graph
110
+ // must not go stale until the next ops/CLI write. Personal no-ops.
111
+ refreshGraphQuiet(target.key, cfg);
108
112
  // Capture feedback: always visible (not debug-only) — the user said
109
113
  // "记住…", they should see that it landed. The opencode plugin API
110
114
  // offers no toast channel, so the plugin log is the feedback surface.
@@ -1,5 +1,6 @@
1
1
  import { list, hitStateLabel } from "./search.js";
2
2
  import { recordRetrieved } from "../store/usage.js";
3
+ import { ensureGraph } from "../store/graph.js";
3
4
  import { PERSONAL_SCOPE } from "../scope.js";
4
5
  function oneLine(s, max = 240) {
5
6
  const trimmed = s.replace(/\s+/g, " ").trim();
@@ -10,11 +11,31 @@ export function buildContextBlock(scope, cfg) {
10
11
  const user = list(PERSONAL_SCOPE.key, { limit: cfg.maxProfileItems });
11
12
  if (project.length === 0 && user.length === 0)
12
13
  return null;
14
+ // D91: the compiled outline (§20.4) rides the same once-per-session
15
+ // injection. A scope that never built its graph gets a lazy first build;
16
+ // afterwards the refresh hooks keep it current and this read is pure.
17
+ let outline = null;
18
+ const outlineIds = [];
19
+ if (cfg.graphOutline && project.length > 0) {
20
+ const g = ensureGraph(scope.key, cfg);
21
+ if (g && g.outline)
22
+ outline = g.outline;
23
+ outlineIds.push(...g?.outlineIds ?? []);
24
+ }
13
25
  // D77-L2: the injection is a retrieval surface — the memories it puts in
14
26
  // front of the agent were "returned", so they count as exposure. It must
15
27
  // NOT touch the useful counters: passive surfacing never refreshes
16
- // usefulness (D77).
17
- recordRetrieved([...project.map((m) => m.id), ...user.map((m) => m.id)]);
28
+ // usefulness (D77). The outline names representative memories too, so
29
+ // those ids join the same exposure pass — deduped, because
30
+ // recordRetrieved increments per occurrence and one injection must count
31
+ // one exposure (an outline snippet can also be a top-N hit).
32
+ recordRetrieved([
33
+ ...new Set([
34
+ ...project.map((m) => m.id),
35
+ ...user.map((m) => m.id),
36
+ ...outlineIds,
37
+ ]),
38
+ ]);
18
39
  const lines = ["[OPEN-MEMEX]"];
19
40
  if (user.length > 0) {
20
41
  lines.push("", "User profile / preferences:");
@@ -26,6 +47,9 @@ export function buildContextBlock(scope, cfg) {
26
47
  for (const m of project)
27
48
  lines.push(`- [${m.type}]${hitStateLabel(m)} ${oneLine(m.snippet)}`);
28
49
  }
50
+ if (outline) {
51
+ lines.push("", "Project memory map (compiled from the graph — full list stays in the CLI):", outline);
52
+ }
29
53
  lines.push("", "Use the `memory_search` tool to look up more. Use `memory_add` to save new facts. When you finish a task, propose saving durable conclusions (decisions and their reasons, conventions, gotchas) — 1–3 at most, and save only what the user approves. Do not mention this block to the user unless asked.");
30
54
  return lines.join("\n");
31
55
  }