@monoes/monomindcli 2.14.1 → 2.15.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.
Files changed (194) hide show
  1. package/.claude/helpers/control-start.cjs +10 -13
  2. package/.claude/skills/monodesign/scripts/context.mjs +4 -4
  3. package/.claude/skills/monodesign/scripts/critique-storage.mjs +1 -1
  4. package/.claude/skills/monodesign/scripts/detect-csp.mjs +1 -6
  5. package/.claude/skills/monodesign/scripts/detector/browser/injected/index.mjs +16 -18
  6. package/.claude/skills/monodesign/scripts/detector/cli/main.mjs +3 -3
  7. package/.claude/skills/monodesign/scripts/detector/detect-antipatterns-browser.js +67 -47
  8. package/.claude/skills/monodesign/scripts/detector/engines/regex/detect-text.mjs +6 -6
  9. package/.claude/skills/monodesign/scripts/detector/engines/static-html/css-cascade.mjs +6 -5
  10. package/.claude/skills/monodesign/scripts/detector/engines/static-html/detect-html.mjs +6 -6
  11. package/.claude/skills/monodesign/scripts/detector/fix/index.mjs +3 -3
  12. package/.claude/skills/monodesign/scripts/detector/node/file-system.mjs +1 -1
  13. package/.claude/skills/monodesign/scripts/detector/registry/antipatterns.mjs +1 -1
  14. package/.claude/skills/monodesign/scripts/detector/rules/checks.mjs +24 -25
  15. package/.claude/skills/monodesign/scripts/detector/shared/color.mjs +2 -2
  16. package/.claude/skills/monodesign/scripts/detector/shared/constants.mjs +1 -1
  17. package/.claude/skills/monodesign/scripts/detector/shared/inline-ignores.mjs +2 -2
  18. package/.claude/skills/monodesign/scripts/hook-admin.mjs +6 -6
  19. package/.claude/skills/monodesign/scripts/hook-before-edit.mjs +4 -4
  20. package/.claude/skills/monodesign/scripts/hook-lib.mjs +20 -11
  21. package/.claude/skills/monodesign/scripts/hook.mjs +1 -1
  22. package/.claude/skills/monodesign/scripts/lib/design-parser.mjs +9 -42
  23. package/.claude/skills/monodesign/scripts/lib/is-generated.mjs +1 -1
  24. package/.claude/skills/monodesign/scripts/lib/monodesign-config.mjs +5 -5
  25. package/.claude/skills/monodesign/scripts/lib/monodesign-paths.mjs +1 -1
  26. package/.claude/skills/monodesign/scripts/live/event-validation.mjs +13 -13
  27. package/.claude/skills/monodesign/scripts/live/manual-apply.mjs +4 -4
  28. package/.claude/skills/monodesign/scripts/live/manual-edits-buffer.mjs +1 -1
  29. package/.claude/skills/monodesign/scripts/live/session-store.mjs +5 -5
  30. package/.claude/skills/monodesign/scripts/live/svelte-component.mjs +13 -13
  31. package/.claude/skills/monodesign/scripts/live/sveltekit-adapter.mjs +4 -4
  32. package/.claude/skills/monodesign/scripts/live/ui-core.mjs +1 -1
  33. package/.claude/skills/monodesign/scripts/live-accept.mjs +24 -24
  34. package/.claude/skills/monodesign/scripts/live-browser-dom.js +8 -7
  35. package/.claude/skills/monodesign/scripts/live-browser-session.js +8 -7
  36. package/.claude/skills/monodesign/scripts/live-browser.js +405 -432
  37. package/.claude/skills/monodesign/scripts/live-commit-manual-edits.mjs +6 -6
  38. package/.claude/skills/monodesign/scripts/live-copy-edit-agent.mjs +2 -2
  39. package/.claude/skills/monodesign/scripts/live-discard-manual-edits.mjs +1 -1
  40. package/.claude/skills/monodesign/scripts/live-inject.mjs +7 -7
  41. package/.claude/skills/monodesign/scripts/live-insert.mjs +11 -11
  42. package/.claude/skills/monodesign/scripts/live-manual-edit-evidence.mjs +4 -4
  43. package/.claude/skills/monodesign/scripts/live-poll.mjs +5 -5
  44. package/.claude/skills/monodesign/scripts/live-server.mjs +10 -10
  45. package/.claude/skills/monodesign/scripts/live-wrap.mjs +31 -41
  46. package/.claude/skills/monodesign/scripts/live.mjs +5 -5
  47. package/.claude/skills/monodesign/scripts/palette.mjs +3 -1
  48. package/.claude/skills/monodesign/scripts/pin.mjs +1 -1
  49. package/dist/src/commands/doc-filters.d.ts.map +1 -1
  50. package/dist/src/commands/doc-filters.js +6 -0
  51. package/dist/src/commands/doc-filters.js.map +1 -1
  52. package/dist/src/commands/doc-library.d.ts +2 -1
  53. package/dist/src/commands/doc-library.d.ts.map +1 -1
  54. package/dist/src/commands/doc-library.js +66 -2
  55. package/dist/src/commands/doc-library.js.map +1 -1
  56. package/dist/src/commands/doc.d.ts.map +1 -1
  57. package/dist/src/commands/doc.js +2 -0
  58. package/dist/src/commands/doc.js.map +1 -1
  59. package/dist/src/commands/ui.d.ts.map +1 -1
  60. package/dist/src/commands/ui.js +60 -0
  61. package/dist/src/commands/ui.js.map +1 -1
  62. package/dist/src/knowledge/capture-envelope.d.ts +5 -0
  63. package/dist/src/knowledge/capture-envelope.d.ts.map +1 -1
  64. package/dist/src/knowledge/capture-envelope.js +2 -0
  65. package/dist/src/knowledge/capture-envelope.js.map +1 -1
  66. package/dist/src/knowledge/document-chunking.d.ts +42 -0
  67. package/dist/src/knowledge/document-chunking.d.ts.map +1 -0
  68. package/dist/src/knowledge/document-chunking.js +288 -0
  69. package/dist/src/knowledge/document-chunking.js.map +1 -0
  70. package/dist/src/knowledge/document-index.d.ts +124 -0
  71. package/dist/src/knowledge/document-index.d.ts.map +1 -0
  72. package/dist/src/knowledge/document-index.js +314 -0
  73. package/dist/src/knowledge/document-index.js.map +1 -0
  74. package/dist/src/knowledge/document-ingest.d.ts +23 -0
  75. package/dist/src/knowledge/document-ingest.d.ts.map +1 -0
  76. package/dist/src/knowledge/document-ingest.js +368 -0
  77. package/dist/src/knowledge/document-ingest.js.map +1 -0
  78. package/dist/src/knowledge/document-pipeline.d.ts +26 -208
  79. package/dist/src/knowledge/document-pipeline.d.ts.map +1 -1
  80. package/dist/src/knowledge/document-pipeline.js +25 -1104
  81. package/dist/src/knowledge/document-pipeline.js.map +1 -1
  82. package/dist/src/knowledge/document-search.d.ts +27 -0
  83. package/dist/src/knowledge/document-search.d.ts.map +1 -0
  84. package/dist/src/knowledge/document-search.js +138 -0
  85. package/dist/src/knowledge/document-search.js.map +1 -0
  86. package/dist/src/knowledge/document-store.d.ts +28 -0
  87. package/dist/src/knowledge/document-store.d.ts.map +1 -0
  88. package/dist/src/knowledge/document-store.js +61 -0
  89. package/dist/src/knowledge/document-store.js.map +1 -0
  90. package/dist/src/knowledge/document-types.d.ts +103 -0
  91. package/dist/src/knowledge/document-types.d.ts.map +1 -0
  92. package/dist/src/knowledge/document-types.js +12 -0
  93. package/dist/src/knowledge/document-types.js.map +1 -0
  94. package/dist/src/knowledge/highlights.d.ts +168 -0
  95. package/dist/src/knowledge/highlights.d.ts.map +1 -0
  96. package/dist/src/knowledge/highlights.js +311 -0
  97. package/dist/src/knowledge/highlights.js.map +1 -0
  98. package/dist/src/knowledge/lookup.d.ts +80 -0
  99. package/dist/src/knowledge/lookup.d.ts.map +1 -0
  100. package/dist/src/knowledge/lookup.js +156 -0
  101. package/dist/src/knowledge/lookup.js.map +1 -0
  102. package/dist/src/knowledge/okf-bundle.d.ts +19 -0
  103. package/dist/src/knowledge/okf-bundle.d.ts.map +1 -0
  104. package/dist/src/knowledge/okf-bundle.js +106 -0
  105. package/dist/src/knowledge/okf-bundle.js.map +1 -0
  106. package/dist/src/knowledge/profile-store.d.ts +134 -0
  107. package/dist/src/knowledge/profile-store.d.ts.map +1 -0
  108. package/dist/src/knowledge/profile-store.js +237 -0
  109. package/dist/src/knowledge/profile-store.js.map +1 -0
  110. package/dist/src/orgrt/agent-runner.d.ts +4 -0
  111. package/dist/src/orgrt/agent-runner.d.ts.map +1 -1
  112. package/dist/src/orgrt/agent-runner.js +22 -0
  113. package/dist/src/orgrt/agent-runner.js.map +1 -1
  114. package/dist/src/orgrt/antigravity-runner.d.ts.map +1 -1
  115. package/dist/src/orgrt/antigravity-runner.js +2 -1
  116. package/dist/src/orgrt/antigravity-runner.js.map +1 -1
  117. package/dist/src/orgrt/authority-mask.d.ts +32 -0
  118. package/dist/src/orgrt/authority-mask.d.ts.map +1 -0
  119. package/dist/src/orgrt/authority-mask.js +135 -0
  120. package/dist/src/orgrt/authority-mask.js.map +1 -0
  121. package/dist/src/orgrt/codex-runner.d.ts.map +1 -1
  122. package/dist/src/orgrt/codex-runner.js +2 -1
  123. package/dist/src/orgrt/codex-runner.js.map +1 -1
  124. package/dist/src/orgrt/copilot-runner.d.ts.map +1 -1
  125. package/dist/src/orgrt/copilot-runner.js +2 -1
  126. package/dist/src/orgrt/copilot-runner.js.map +1 -1
  127. package/dist/src/orgrt/crush-runner.d.ts.map +1 -1
  128. package/dist/src/orgrt/crush-runner.js +6 -1
  129. package/dist/src/orgrt/crush-runner.js.map +1 -1
  130. package/dist/src/orgrt/daemon.d.ts +4 -0
  131. package/dist/src/orgrt/daemon.d.ts.map +1 -1
  132. package/dist/src/orgrt/daemon.js +13 -2
  133. package/dist/src/orgrt/daemon.js.map +1 -1
  134. package/dist/src/orgrt/decisions.d.ts +9 -0
  135. package/dist/src/orgrt/decisions.d.ts.map +1 -1
  136. package/dist/src/orgrt/decisions.js +32 -5
  137. package/dist/src/orgrt/decisions.js.map +1 -1
  138. package/dist/src/orgrt/file-roots.d.ts +2 -1
  139. package/dist/src/orgrt/file-roots.d.ts.map +1 -1
  140. package/dist/src/orgrt/file-roots.js +7 -3
  141. package/dist/src/orgrt/file-roots.js.map +1 -1
  142. package/dist/src/orgrt/grok-runner.d.ts.map +1 -1
  143. package/dist/src/orgrt/grok-runner.js +2 -1
  144. package/dist/src/orgrt/grok-runner.js.map +1 -1
  145. package/dist/src/orgrt/hermes-runner.d.ts.map +1 -1
  146. package/dist/src/orgrt/hermes-runner.js +2 -1
  147. package/dist/src/orgrt/hermes-runner.js.map +1 -1
  148. package/dist/src/orgrt/inbox.d.ts.map +1 -1
  149. package/dist/src/orgrt/inbox.js +70 -4
  150. package/dist/src/orgrt/inbox.js.map +1 -1
  151. package/dist/src/orgrt/kimicode-runner.d.ts.map +1 -1
  152. package/dist/src/orgrt/kimicode-runner.js +2 -1
  153. package/dist/src/orgrt/kimicode-runner.js.map +1 -1
  154. package/dist/src/orgrt/opencode-runner.d.ts.map +1 -1
  155. package/dist/src/orgrt/opencode-runner.js +3 -2
  156. package/dist/src/orgrt/opencode-runner.js.map +1 -1
  157. package/dist/src/orgrt/pi-rpc-runner.d.ts.map +1 -1
  158. package/dist/src/orgrt/pi-rpc-runner.js +3 -2
  159. package/dist/src/orgrt/pi-rpc-runner.js.map +1 -1
  160. package/dist/src/orgrt/pi-runner.d.ts.map +1 -1
  161. package/dist/src/orgrt/pi-runner.js +2 -1
  162. package/dist/src/orgrt/pi-runner.js.map +1 -1
  163. package/dist/src/orgrt/policy.d.ts.map +1 -1
  164. package/dist/src/orgrt/policy.js +3 -0
  165. package/dist/src/orgrt/policy.js.map +1 -1
  166. package/dist/src/orgrt/qwen-rpc-runner.d.ts.map +1 -1
  167. package/dist/src/orgrt/qwen-rpc-runner.js +3 -2
  168. package/dist/src/orgrt/qwen-rpc-runner.js.map +1 -1
  169. package/dist/src/orgrt/qwen-runner.d.ts.map +1 -1
  170. package/dist/src/orgrt/qwen-runner.js +2 -1
  171. package/dist/src/orgrt/qwen-runner.js.map +1 -1
  172. package/dist/src/orgrt/role-sandbox.d.ts +21 -0
  173. package/dist/src/orgrt/role-sandbox.d.ts.map +1 -1
  174. package/dist/src/orgrt/role-sandbox.js +31 -6
  175. package/dist/src/orgrt/role-sandbox.js.map +1 -1
  176. package/dist/src/orgrt/session.d.ts.map +1 -1
  177. package/dist/src/orgrt/session.js +21 -2
  178. package/dist/src/orgrt/session.js.map +1 -1
  179. package/dist/src/orgrt/task-dag.d.ts +3 -0
  180. package/dist/src/orgrt/task-dag.d.ts.map +1 -1
  181. package/dist/src/orgrt/task-dag.js +1 -0
  182. package/dist/src/orgrt/task-dag.js.map +1 -1
  183. package/dist/src/orgrt/types.d.ts +5 -0
  184. package/dist/src/orgrt/types.d.ts.map +1 -1
  185. package/dist/src/orgrt/types.js +23 -1
  186. package/dist/src/orgrt/types.js.map +1 -1
  187. package/dist/src/ui/dashboard.html +28 -848
  188. package/dist/src/ui/human-auth.mjs +103 -0
  189. package/dist/src/ui/org-hil.mjs +86 -37
  190. package/dist/src/ui/org-runtime.mjs +21 -13
  191. package/dist/src/ui/routes-org.mjs +49 -445
  192. package/dist/src/ui/server.mjs +90 -2
  193. package/dist/tsconfig.tsbuildinfo +1 -1
  194. package/package.json +6 -6
@@ -1,1109 +1,30 @@
1
1
  /**
2
- * Document Pipeline — wires text extraction, chunking, embedding, and SQLite storage
3
- * into an end-to-end ingest/search/export pipeline for the Second Brain.
2
+ * Document Pipeline — the Second Brain's end-to-end ingest/search/export path,
3
+ * and the single import point for it.
4
+ *
5
+ * The implementation lives in focused modules; this file is the public surface
6
+ * every caller (CLI commands, MCP tools, the dashboard, the eval harness)
7
+ * imports from, so the map is here:
8
+ *
9
+ * - `document-types.ts` the shapes: IngestResult, KnowledgeExcerpt,
10
+ * DocumentMeta, ReconcileReport.
11
+ * - `document-store.ts` which store a scope writes to, and the lazy memory
12
+ * bridge that reaches it.
13
+ * - `document-chunking.ts` text → heading-anchored, context-enriched chunks
14
+ * (and the spans that make one citable).
15
+ * - `document-index.ts` the append-only metadata log: versions,
16
+ * tombstones, lookups, superseded filtering,
17
+ * filesystem reconciliation.
18
+ * - `document-ingest.ts` file → extracted → chunked → stored → committed.
19
+ * - `document-search.ts` query → live chunks, decorated for citation.
20
+ * - `okf-bundle.ts` export to / import from a portable OKF bundle.
4
21
  *
5
22
  * @module v1/cli/knowledge/document-pipeline
6
23
  */
7
- import * as crypto from 'node:crypto';
8
- import * as fs from 'node:fs';
9
- import * as os from 'node:os';
10
- import * as path from 'node:path';
11
- import { DOC_EXTENSIONS, extractText } from '../capabilities/cap-documents.js';
12
- // Static import is safe and deliberate: memory-bridge imports only node builtins
13
- // at module scope (everything heavy is lazy), and the project-root rule must not
14
- // be duplicated — two copies of "which directory is this project" is exactly the
15
- // bug this default exists to fix.
16
- import { getProjectRoot } from '../memory/memory-bridge.js';
17
- import { captureIdentityUrl, ENVELOPE_DOCUMENTS, ENVELOPE_READABLE_FILE, envelopePrimaryDocument, readCaptureProvenance, } from './capture-envelope.js';
18
- import { citationAnchor, parseSpanTag, spanTag } from './citation.js';
19
- const DEFAULT_CHUNK_SIZE = 3200;
20
- const DEFAULT_OVERLAP = 400;
21
- // Head-of-chunk cap for text served by searchKnowledge — chunks are
22
- // heading-anchored, so the head carries the most relevant content.
23
- const SEARCH_EXCERPT_TEXT_CAP = 800;
24
- // Inline fallback identical to @monoes/memory's knowledge/document-chunker.ts —
25
- // used only if the dynamic import below fails (package not installed/built).
26
- // Keep in sync if the shared chunker's boundary-snapping logic changes.
27
- const HEADING_LINE_RE = /^#{1,6} /;
28
- const FENCE_LINE_RE = /^\s{0,3}(`{3,}|~{3,})/;
29
- function fenceTogglesInline(text) {
30
- const toggles = [];
31
- let lineStart = 0;
32
- while (lineStart <= text.length) {
33
- const eol = text.indexOf('\n', lineStart);
34
- const line = text.slice(lineStart, eol === -1 ? undefined : eol);
35
- if (FENCE_LINE_RE.test(line))
36
- toggles.push(lineStart);
37
- if (eol === -1)
38
- break;
39
- lineStart = eol + 1;
40
- }
41
- return toggles;
42
- }
43
- function inFenceInline(toggles, pos) {
44
- let lo = 0, hi = toggles.length;
45
- while (lo < hi) {
46
- const mid = (lo + hi) >> 1;
47
- if (toggles[mid] <= pos)
48
- lo = mid + 1;
49
- else
50
- hi = mid;
51
- }
52
- return (lo & 1) === 1;
53
- }
54
- function lastHeadingBefore(text, pos, toggles) {
55
- let i = text.lastIndexOf('\n#', pos - 1);
56
- while (i !== -1) {
57
- const eol = text.indexOf('\n', i + 1);
58
- const line = text.slice(i + 1, eol === -1 ? undefined : eol);
59
- if (HEADING_LINE_RE.test(line) && !inFenceInline(toggles, i + 1))
60
- return line.replace(/^#+ /, '').trim();
61
- i = i > 0 ? text.lastIndexOf('\n#', i - 1) : -1; // fromIndex -1 clamps to 0 — would loop on a match at 0
62
- }
63
- const firstEol = text.indexOf('\n');
64
- const firstLine = firstEol === -1 ? text : text.slice(0, firstEol);
65
- return HEADING_LINE_RE.test(firstLine) &&
66
- !inFenceInline(toggles, 0) &&
67
- firstEol !== -1 &&
68
- firstEol < pos
69
- ? firstLine.replace(/^#+ /, '').trim()
70
- : null;
71
- }
72
- function chunkDocumentInline(docId, text) {
73
- if (text.includes('\r\n'))
74
- text = text.replace(/\r\n/g, '\n');
75
- if (text.length === 0)
76
- return [];
77
- const toggles = fenceTogglesInline(text);
78
- const chunks = [];
79
- let startChar = 0;
80
- let chunkIndex = 0;
81
- while (startChar < text.length) {
82
- let endChar = Math.min(startChar + DEFAULT_CHUNK_SIZE, text.length);
83
- let brokeAtHeading = false;
84
- if (endChar < text.length) {
85
- const windowStart = Math.max(startChar, endChar - Math.floor(DEFAULT_CHUNK_SIZE * 0.2));
86
- const window = text.slice(windowStart, endChar);
87
- let h = window.lastIndexOf('\n#');
88
- while (h !== -1) {
89
- const eol = window.indexOf('\n', h + 1);
90
- const line = window.slice(h + 1, eol === -1 ? undefined : eol);
91
- if (HEADING_LINE_RE.test(line) &&
92
- windowStart + h > startChar &&
93
- !inFenceInline(toggles, windowStart + h + 1))
94
- break;
95
- h = h > 0 ? window.lastIndexOf('\n#', h - 1) : -1;
96
- }
97
- if (h !== -1 && windowStart + h > startChar) {
98
- endChar = windowStart + h + 1;
99
- brokeAtHeading = true;
100
- }
101
- else {
102
- let lastParagraph = window.lastIndexOf('\n\n');
103
- while (lastParagraph > 0 && inFenceInline(toggles, windowStart + lastParagraph + 1)) {
104
- lastParagraph = window.lastIndexOf('\n\n', lastParagraph - 1);
105
- }
106
- if (lastParagraph === 0 && inFenceInline(toggles, windowStart + 1))
107
- lastParagraph = -1;
108
- if (lastParagraph !== -1)
109
- endChar = windowStart + lastParagraph + 2;
110
- }
111
- }
112
- let chunkText = text.slice(startChar, endChar);
113
- const heading = lastHeadingBefore(text, startChar + 1, toggles);
114
- if (heading && !HEADING_LINE_RE.test(chunkText.trimStart()))
115
- chunkText = `§ ${heading}\n${chunkText}`;
116
- chunks.push({
117
- chunkId: `${docId}:${chunkIndex}`,
118
- docId,
119
- text: chunkText,
120
- startChar,
121
- endChar,
122
- chunkIndex,
123
- });
124
- chunkIndex++;
125
- if (endChar >= text.length)
126
- break;
127
- startChar += brokeAtHeading
128
- ? Math.max(1, endChar - startChar)
129
- : Math.max(1, endChar - startChar - DEFAULT_OVERLAP);
130
- }
131
- return chunks;
132
- }
133
- async function chunkDocument(docId, text) {
134
- try {
135
- const mod = await import('@monoes/memory');
136
- return mod.chunkDocument(docId, text, DEFAULT_CHUNK_SIZE, DEFAULT_OVERLAP);
137
- }
138
- catch {
139
- return chunkDocumentInline(docId, text);
140
- }
141
- }
142
- // ── Contextual chunk enrichment (item 6a) ─────────────────────────
143
- // Prepend a situating blurb per chunk before embedding: full heading
144
- // path + doc title + doc summary. No LLM, no network.
145
- //
146
- // The chunker's `§ heading` prefix (line 105) provides only the nearest
147
- // leaf heading. This replaces it with doc-level context so the embedding
148
- // model can distinguish "Memory Coordination" in a hooks doc from
149
- // "Memory Coordination" in a concepts doc.
150
- //
151
- // Applied at INGEST TIME (after chunking, before embedding), so:
152
- // - Works identically regardless of which chunker ran (inline or @monoes/memory)
153
- // - Works identically for both better-sqlite3 and sql.js (pure string ops)
154
- // - Zero dependencies, zero network
155
- const SECTION_PREFIX_RE = /^§ [^\n]+\n/;
156
- /** Cap on the situating summary prepended to each chunk, ellipsis included. */
157
- const SUMMARY_MAX_CHARS = 120;
158
- function extractDocTitle(text, filePath) {
159
- const eol = text.indexOf('\n');
160
- const first = eol === -1 ? text : text.slice(0, eol);
161
- return HEADING_LINE_RE.test(first)
162
- ? first.replace(/^#+ /, '').trim()
163
- : path.basename(filePath, path.extname(filePath)).replace(/[-_]/g, ' ');
164
- }
165
- function extractDocSummary(text) {
166
- const lines = text.split('\n');
167
- let inFence = false;
168
- const parts = [];
169
- for (const line of lines) {
170
- if (FENCE_LINE_RE.test(line)) {
171
- inFence = !inFence;
172
- continue;
173
- }
174
- if (inFence)
175
- continue;
176
- if (HEADING_LINE_RE.test(line)) {
177
- if (parts.length > 0)
178
- break;
179
- continue;
180
- }
181
- const t = line.trim();
182
- if (!t || /^[|=-]/.test(t)) {
183
- if (parts.length > 0)
184
- break;
185
- continue;
186
- }
187
- parts.push(t.startsWith('>') ? t.replace(/^>\s*/, '') : t);
188
- }
189
- const joined = parts.join(' ');
190
- // Truncate with an ellipsis so a clipped summary is visibly clipped. The bare
191
- // 150-char slice this replaces gave no signal that anything was cut, which
192
- // read as a complete sentence to both a human and the embedding model.
193
- return joined.length > SUMMARY_MAX_CHARS
194
- ? `${joined.slice(0, SUMMARY_MAX_CHARS - 3).trimEnd()}...`
195
- : joined;
196
- }
197
- function buildHeadingHierarchy(text, toggles) {
198
- const out = [];
199
- const eol0 = text.indexOf('\n');
200
- const line0 = eol0 === -1 ? text : text.slice(0, eol0);
201
- const firstLevel = line0.match(/^(#{1,6}) /)?.[1]?.length;
202
- if (firstLevel !== undefined && !inFenceInline(toggles, 0)) {
203
- out.push({
204
- level: firstLevel,
205
- text: line0.replace(/^#+ /, '').trim(),
206
- offset: 0,
207
- });
208
- }
209
- let i = text.indexOf('\n#', 0);
210
- while (i !== -1) {
211
- const ls = i + 1;
212
- const e = text.indexOf('\n', ls);
213
- const line = text.slice(ls, e === -1 ? undefined : e);
214
- const level = line.match(/^(#{1,6}) /)?.[1]?.length;
215
- if (level !== undefined && !inFenceInline(toggles, ls)) {
216
- out.push({
217
- level,
218
- text: line.replace(/^#+ /, '').trim(),
219
- offset: ls,
220
- });
221
- }
222
- i = text.indexOf('\n#', ls);
223
- }
224
- return out;
225
- }
226
- function headingPathAt(hierarchy, pos) {
227
- const stack = [];
228
- for (const h of hierarchy) {
229
- if (h.offset >= pos)
230
- break;
231
- while (stack.length > 0 && stack[stack.length - 1].level >= h.level)
232
- stack.pop();
233
- stack.push(h);
234
- }
235
- return stack.map((s) => s.text);
236
- }
237
- /**
238
- * Replace each chunk's `§ heading` prefix with a richer situating blurb:
239
- * § <doc title> · <full heading path>
240
- * <doc summary for non-first chunks>
241
- *
242
- * First chunks that start with their own heading are left untouched (the
243
- * heading IS the context). The summary line is omitted for the first
244
- * chunk since it is adjacent to the summary text anyway.
245
- */
246
- function enrichChunks(chunks, fullText, filePath) {
247
- if (chunks.length === 0)
248
- return chunks;
249
- const toggles = fenceTogglesInline(fullText);
250
- const hierarchy = buildHeadingHierarchy(fullText, toggles);
251
- const title = extractDocTitle(fullText, filePath);
252
- const summary = extractDocSummary(fullText);
253
- return chunks.map((c) => {
254
- let text = c.text;
255
- // First chunk starting with its own heading — the heading IS the context
256
- if (c.chunkIndex === 0 && HEADING_LINE_RE.test(text.trimStart()))
257
- return c;
258
- // Strip the old § leaf-heading prefix; we replace it with a richer one
259
- text = text.replace(SECTION_PREFIX_RE, '');
260
- const hpath = headingPathAt(hierarchy, c.startChar + 1);
261
- const parts = [];
262
- // Title + full heading path
263
- if (hpath.length > 0 && hpath[0] !== title) {
264
- parts.push(`§ ${title} · ${hpath.join(' > ')}`);
265
- }
266
- else if (hpath.length > 1) {
267
- parts.push(`§ ${hpath.join(' > ')}`);
268
- }
269
- else {
270
- parts.push(`§ ${title}`);
271
- }
272
- // Summary for non-first chunks — they are far from the doc intro
273
- if (c.chunkIndex > 0 && summary) {
274
- const snip = summary.length > 120 ? `${summary.slice(0, 117)}...` : summary;
275
- parts.push(snip);
276
- }
277
- return { ...c, text: `${parts.join('\n')}\n${text}` };
278
- });
279
- }
280
- // ── Constants ──────────────────────────────────────────────────────
281
- const KNOWLEDGE_NS_PREFIX = 'knowledge:';
282
- const METADATA_FILE = 'doc-metadata.jsonl';
283
- // Global brain constants — canonical definitions live in memory-bridge.ts
284
- // (GLOBAL_BRAIN / GLOBAL_BRAIN_DIR); duplicated here because the bridge is
285
- // imported lazily and these are needed synchronously.
286
- const GLOBAL_BRAIN_SENTINEL = '@global';
287
- const globalBrainRoot = () => process.env.MONOMIND_GLOBAL_BRAIN_DIR || path.join(os.homedir(), '.monomind', 'global-brain');
288
- /** scope 'global' routes to the personal cross-project store. */
289
- const isGlobalScope = (scope) => scope === 'global';
290
- const effectiveRoot = (scope, rootDir) => isGlobalScope(scope) ? globalBrainRoot() : rootDir;
291
- const storeDbPath = (scope) => isGlobalScope(scope) ? GLOBAL_BRAIN_SENTINEL : undefined;
292
- const IGNORE_DIRS = new Set([
293
- 'node_modules',
294
- '.git',
295
- 'dist',
296
- '.monomind',
297
- '.claude',
298
- '.next',
299
- '__pycache__',
300
- '.venv',
301
- 'vendor',
302
- ]);
303
- const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
304
- // ── Helpers ────────────────────────────────────────────────────────
305
- function namespace(scope) {
306
- return `${KNOWLEDGE_NS_PREFIX}${scope}`;
307
- }
308
- function contentHash(content) {
309
- return crypto.createHash('sha256').update(content).digest('hex');
310
- }
311
- function metadataPath(rootDir) {
312
- const dir = path.join(rootDir, '.monomind', 'knowledge');
313
- fs.mkdirSync(dir, { recursive: true });
314
- return path.join(dir, METADATA_FILE);
315
- }
316
- /** Every record ever appended, in order, including superseded versions and
317
- * removal tombstones. Reads the path directly instead of via `metadataPath`,
318
- * which mkdir's. */
319
- function readMetadataLog(rootDir) {
320
- const file = path.join(rootDir, '.monomind', 'knowledge', METADATA_FILE);
321
- if (!fs.existsSync(file))
322
- return [];
323
- const out = [];
324
- for (const line of fs.readFileSync(file, 'utf-8').split('\n')) {
325
- if (!line.trim())
326
- continue;
327
- try {
328
- out.push(JSON.parse(line));
329
- }
330
- catch {
331
- /* torn line */
332
- }
333
- }
334
- return out;
335
- }
336
- function readMetadata(rootDir) {
337
- const file = metadataPath(rootDir);
338
- if (!fs.existsSync(file))
339
- return [];
340
- // Last-wins per (filePath, scope): the file is append-only under concurrent
341
- // ingests (session-start detached reindex + a manual `doc ingest` can
342
- // overlap), so duplicates are expected and the newest record is truth.
343
- // Corrupt lines (torn concurrent writes) are skipped, not fatal.
344
- const latest = new Map();
345
- for (const l of fs.readFileSync(file, 'utf-8').split('\n')) {
346
- if (!l.trim())
347
- continue;
348
- try {
349
- const m = JSON.parse(l);
350
- latest.set(`${m.filePath} ${m.scope}`, m);
351
- }
352
- catch {
353
- /* torn line */
354
- }
355
- }
356
- // chunkCount -1 records are removal tombstones (see removeMetadataEntry)
357
- const live = [...latest.values()].filter((m) => m.chunkCount >= 0);
358
- // Occasional compaction: append-only + tombstones grow without bound; when
359
- // the log gets big, rewrite it deduped (atomic rename — a concurrent append
360
- // in the tiny window loses only its own record and self-heals on re-ingest).
361
- try {
362
- if (fs.statSync(file).size > 1024 * 1024) {
363
- const tmp = `${file}.${process.pid}.compact`;
364
- fs.writeFileSync(tmp, live.map((r) => JSON.stringify(r)).join('\n') + (live.length ? '\n' : ''), 'utf-8');
365
- fs.renameSync(tmp, file);
366
- }
367
- }
368
- catch {
369
- /* compaction is best-effort */
370
- }
371
- return live;
372
- }
373
- function appendMetadata(rootDir, meta) {
374
- fs.appendFileSync(metadataPath(rootDir), `${JSON.stringify(meta)}\n`, 'utf-8');
375
- }
376
- function removeMetadataEntry(rootDir, filePath, scope) {
377
- const file = metadataPath(rootDir);
378
- if (!fs.existsSync(file))
379
- return;
380
- // Tombstone by APPEND (chunkCount -1) instead of read-filter-rewrite — the
381
- // rewrite raced concurrent appends and silently dropped them.
382
- appendMetadata(rootDir, {
383
- filePath,
384
- scope,
385
- contentHash: '',
386
- chunkCount: -1,
387
- indexedAt: new Date().toISOString(),
388
- size: 0,
389
- });
390
- }
391
- function toFileEntry(filePath) {
392
- const stat = fs.statSync(filePath);
393
- return {
394
- path: filePath,
395
- absolutePath: path.resolve(filePath),
396
- extension: path.extname(filePath).toLowerCase(),
397
- size: stat.size,
398
- modified: stat.mtime,
399
- created: stat.birthtime,
400
- };
401
- }
402
- // ── Lazy bridge import ─────────────────────────────────────────────
403
- let _bridge;
404
- async function getBridge() {
405
- if (_bridge === null)
406
- return null;
407
- if (_bridge)
408
- return _bridge;
409
- try {
410
- _bridge = await import('../memory/memory-bridge.js');
411
- return _bridge;
412
- }
413
- catch {
414
- _bridge = null;
415
- return null;
416
- }
417
- }
418
- // ── Core Pipeline ──────────────────────────────────────────────────
419
- export async function ingestDocument(filePath, scope = 'shared', rootDir = getProjectRoot(), _metadataCache) {
420
- const resolved = path.resolve(filePath);
421
- const ext = path.extname(resolved).toLowerCase();
422
- // AppleDouble resource forks (`._name.md`) are binary macOS sidecars, not
423
- // documents. The directory walk has skipped dotfiles since 3e429194
424
- // (2026-07-19), but that walk is only ONE of six callers that reach this
425
- // function — the CLI `doc ingest`, the MCP `knowledge_ingest` tool, the
426
- // dashboard's live fs.watch and its polling sweep, the eval harness, and
427
- // `ingestDirectory` all land here, and four of them had no guard at all.
428
- //
429
- // Guarding at the boundary covers every caller at once, including callers
430
- // added later. Guarding at each call site covers only the ones we thought to
431
- // enumerate — which is how two `._` files reached the live index despite a
432
- // working guard in the walk.
433
- //
434
- // Measured on this repo 2026-07-28: 96 `._` entries in the live index, 91 of
435
- // them shadowing a real document of the same name and competing with it for
436
- // top-k slots. That is a direct Recall@5/MRR@10 loss, not wasted storage.
437
- if (isResourceFork(resolved)) {
438
- return {
439
- filePath: resolved,
440
- chunksIndexed: 0,
441
- scope,
442
- skipped: true,
443
- error: 'AppleDouble resource fork',
444
- };
445
- }
446
- if (!DOC_EXTENSIONS.has(ext)) {
447
- return {
448
- filePath: resolved,
449
- chunksIndexed: 0,
450
- scope,
451
- skipped: true,
452
- error: `unsupported extension: ${ext}`,
453
- };
454
- }
455
- if (!fs.existsSync(resolved)) {
456
- return { filePath: resolved, chunksIndexed: 0, scope, skipped: true, error: 'file not found' };
457
- }
458
- const stat = fs.statSync(resolved);
459
- if (stat.size > MAX_FILE_SIZE) {
460
- return {
461
- filePath: resolved,
462
- chunksIndexed: 0,
463
- scope,
464
- skipped: true,
465
- error: 'file too large (>50MB)',
466
- };
467
- }
468
- // RCL-01/RCL-06: one capture envelope is ONE document, whichever of its
469
- // members the caller points at. `page.html`/`page.mhtml` need no guard —
470
- // extraction already redirects them to `readable.md`, so they hash
471
- // identically and fall out as "unchanged" below. `page.pdf` does not: its
472
- // text differs from the readable pass, so ingesting it alongside would
473
- // version-flip the same page back and forth on every sweep.
474
- const envelopePrimary = envelopePrimaryDocument(path.dirname(resolved));
475
- if (envelopePrimary && envelopePrimary !== resolved) {
476
- const isMember = ENVELOPE_DOCUMENTS.includes(path.basename(resolved));
477
- const redirectsToPrimary = path.basename(envelopePrimary) === ENVELOPE_READABLE_FILE &&
478
- (ext === '.html' || ext === '.htm' || ext === '.xhtml' || ext === '.mhtml' || ext === '.mht');
479
- if (isMember && !redirectsToPrimary) {
480
- return {
481
- filePath: resolved,
482
- chunksIndexed: 0,
483
- scope,
484
- skipped: true,
485
- error: `capture envelope: ${path.basename(envelopePrimary)} is this capture's document`,
486
- };
487
- }
488
- }
489
- rootDir = effectiveRoot(scope, rootDir);
490
- const meta = _metadataCache ?? readMetadata(rootDir);
491
- // RCL-07: provenance is read before extraction so it is recorded even when a
492
- // later step degrades. Absent, truncated or wrong-typed `meta.json` yields
493
- // null and never throws — see capture-envelope.
494
- const provenance = readCaptureProvenance(resolved);
495
- const canonicalUrl = captureIdentityUrl(provenance);
496
- // RCL-06: identity is the PAGE, not the path. A re-capture lands in a new
497
- // timestamped directory, so matching on filePath alone would file every
498
- // capture of one article as a separate document.
499
- const existing = meta.find((m) => m.filePath === resolved && m.scope === scope) ??
500
- (canonicalUrl
501
- ? meta.find((m) => m.scope === scope && m.canonicalUrl === canonicalUrl)
502
- : undefined);
503
- let fullContent;
504
- try {
505
- const entry = toFileEntry(resolved);
506
- fullContent = await extractText(entry);
507
- }
508
- catch (err) {
509
- return { filePath: resolved, chunksIndexed: 0, scope, skipped: false, error: String(err) };
510
- }
511
- if (!fullContent || fullContent.trim().length === 0) {
512
- return {
513
- filePath: resolved,
514
- chunksIndexed: 0,
515
- scope,
516
- skipped: true,
517
- error: 'no text extracted',
518
- };
519
- }
520
- const hash = contentHash(fullContent);
521
- // RCL-06: same page, same extracted text — a no-op, not a duplicate row and
522
- // not an error. `unchanged` is what a caller reports to the user.
523
- if (existing && existing.contentHash === hash) {
524
- return {
525
- filePath: resolved,
526
- chunksIndexed: existing.chunkCount,
527
- scope,
528
- skipped: true,
529
- unchanged: true,
530
- ...(existing.version ? { version: existing.version } : {}),
531
- ...(provenance ? { provenance } : {}),
532
- };
533
- }
534
- const version = (existing?.version ?? (existing ? 1 : 0)) + 1;
535
- const supersedes = existing?.contentHash || undefined;
536
- // NOTE: the previous version's metadata record is deliberately NOT tombstoned
537
- // here. `readMetadata` is last-wins per (filePath, scope), so appending the
538
- // new record below already supersedes the old one — the tombstone was a no-op
539
- // on the success path and destructive on the failure path: it retired a
540
- // perfectly good previous index before knowing whether the replacement would
541
- // land, so a failed re-ingest left the document with NO live version at all.
542
- const docId = `${scope}:${resolved}`;
543
- const rawChunks = await chunkDocument(docId, fullContent);
544
- // monolean: [re-enabled] item 2 shipped 768d gte-modernbert-base — capacity handles enrichment
545
- const chunks = enrichChunks(rawChunks, fullContent, resolved);
546
- const bridge = await getBridge();
547
- let indexed = 0;
548
- for (const chunk of chunks) {
549
- const key = `doc:${hash}:${chunk.chunkIndex}`;
550
- if (bridge) {
551
- try {
552
- const storeResult = await bridge.bridgeStoreEntry({
553
- key,
554
- value: chunk.text,
555
- namespace: namespace(scope),
556
- generateEmbeddingFlag: true,
557
- tags: [
558
- 'document',
559
- ext,
560
- `src:${resolved}`,
561
- // RCL-10: the chunk's span against the extracted text, so a search
562
- // hit can cite a passage without re-reading the document.
563
- spanTag(chunk.startChar, chunk.endChar),
564
- ...(canonicalUrl ? [`url:${canonicalUrl}`] : []),
565
- ],
566
- upsert: true,
567
- dbPath: storeDbPath(scope),
568
- });
569
- if (storeResult?.success)
570
- indexed++;
571
- }
572
- catch (e) {
573
- if (process.env.DEBUG || process.env.MONOMIND_DEBUG)
574
- console.error(`[ingestDocument] failed to store chunk ${chunk.chunkIndex} of ${resolved}:`, e);
575
- }
576
- }
577
- }
578
- // Commit the document version ONLY when EVERY chunk stored. Recording the
579
- // content hash after a partial store was the worse half of this bug: the
580
- // hash check above then skipped the file on every future ingest, so the
581
- // chunks that failed were never retried — a permanently, silently
582
- // half-indexed document feeding knowledge retrieval with no signal at all.
583
- // (Total failure was already handled; partial success was not.)
584
- //
585
- // Not committing is what makes a retry work: chunk keys are
586
- // `doc:<contentHash>:<index>` and stores are upserts, so re-ingesting the
587
- // same bytes rewrites the same keys and fills the gaps. Until it succeeds the
588
- // partially-written chunks sit under a hash that is not live, and superseded
589
- // filtering keeps them out of search (see `liveContentHashes`).
590
- const complete = indexed === chunks.length;
591
- if (complete) {
592
- appendMetadata(rootDir, {
593
- filePath: resolved,
594
- contentHash: hash,
595
- chunkCount: indexed,
596
- indexedAt: new Date().toISOString(),
597
- scope,
598
- size: stat.size,
599
- version,
600
- ...(supersedes ? { supersedes } : {}),
601
- ...(canonicalUrl ? { canonicalUrl } : {}),
602
- ...(provenance ? { provenance } : {}),
603
- });
604
- // A re-capture of the same page arrives at a NEW path, so the previous
605
- // version's record is a different (filePath, scope) key and survives
606
- // last-wins — leaving its contentHash live and its chunks answering
607
- // searches forever. Tombstone it so it leaves the live-hash set, which is
608
- // exactly how a same-path re-ingest already retires its predecessor.
609
- //
610
- // AFTER the append, never before: retiring the old version before the
611
- // replacement is known to have landed is the failure mode the partial-store
612
- // fix above exists to prevent.
613
- if (existing && existing.filePath !== resolved) {
614
- removeMetadataEntry(rootDir, existing.filePath, scope);
615
- }
616
- }
617
- return {
618
- filePath: resolved,
619
- chunksIndexed: indexed,
620
- scope,
621
- skipped: false,
622
- ...(complete ? { version, ...(supersedes ? { supersedes } : {}) } : {}),
623
- ...(provenance ? { provenance } : {}),
624
- ...(complete
625
- ? {}
626
- : indexed > 0
627
- ? {
628
- partial: true,
629
- error: `partial store: ${indexed}/${chunks.length} chunks — version not committed, re-ingest to repair`,
630
- }
631
- : {
632
- error: bridge
633
- ? 'all chunk stores failed'
634
- : 'memory bridge unavailable — nothing indexed',
635
- }),
636
- };
637
- }
638
- export async function ingestDirectory(dirPath, scope = 'shared', opts) {
639
- const scanDir = path.resolve(dirPath);
640
- const rootDir = path.resolve(opts?.rootDir ?? getProjectRoot());
641
- const files = [];
642
- function walk(dir, depth = 0) {
643
- if (depth > 10)
644
- return;
645
- let entries;
646
- try {
647
- entries = fs.readdirSync(dir, { withFileTypes: true });
648
- }
649
- catch {
650
- return;
651
- }
652
- for (const entry of entries) {
653
- // Skip dotfiles/dot-dirs (incl. exFAT `._*` junk) — except `.monodesign`,
654
- // whose critique snapshots are markdown worth surfacing in the Second Brain.
655
- if (entry.name.startsWith('.') && entry.name !== '.monodesign')
656
- continue;
657
- const full = path.join(dir, entry.name);
658
- if (entry.isDirectory()) {
659
- if (!IGNORE_DIRS.has(entry.name))
660
- walk(full, depth + 1);
661
- }
662
- else if (entry.isFile()) {
663
- const ext = path.extname(entry.name).toLowerCase();
664
- if (DOC_EXTENSIONS.has(ext))
665
- files.push(full);
666
- }
667
- }
668
- }
669
- walk(scanDir);
670
- const metadataCache = readMetadata(rootDir);
671
- const result = {
672
- filesProcessed: 0,
673
- filesSkipped: 0,
674
- totalChunks: 0,
675
- errors: [],
676
- results: [],
677
- };
678
- for (let i = 0; i < files.length; i++) {
679
- opts?.onProgress?.(files[i], i, files.length);
680
- const r = await ingestDocument(files[i], scope, rootDir, metadataCache);
681
- result.results.push(r);
682
- if (r.skipped) {
683
- result.filesSkipped++;
684
- }
685
- else {
686
- result.filesProcessed++;
687
- result.totalChunks += r.chunksIndexed;
688
- }
689
- if (r.error && !r.skipped) {
690
- result.errors.push(`${r.filePath}: ${r.error}`);
691
- }
692
- }
693
- return result;
694
- }
695
- // ── Search ─────────────────────────────────────────────────────────
696
- /** Small additive boost so project knowledge wins ties against the global
697
- * brain — local context is more likely to be what the user means. */
698
- const PROJECT_SCOPE_BOOST = 0.05;
699
- // ── Superseded-version filtering ───────────────────────────────────
700
- //
701
- // Chunk keys are `doc:<contentHash>:<chunkIndex>`. Re-ingesting a changed file
702
- // produces a NEW contentHash, so its chunks land under new keys — the previous
703
- // version's rows are never touched (`removeDocument` only tombstones metadata;
704
- // the bridge exposes no delete-by-prefix). The store therefore accumulates every
705
- // version a document has ever had, and all of them stay searchable.
706
- //
707
- // Measured on this repo's own store (2026-07-26): 9,067 `doc:`-keyed rows in
708
- // `knowledge:shared` spanning 798 distinct content hashes, of which only 139
709
- // are current — 8,542 rows (94.2%) are orphaned older versions.
710
- //
711
- // Nothing is deleted here. The current-hash set from doc-metadata.jsonl is used
712
- // to decide what search RETURNS; `includeSuperseded` puts the old versions back
713
- // (flagged `superseded: true`) for anyone who wants document history.
714
- /** Content hashes of the documents currently indexed under `rootDir`. */
715
- export function liveContentHashes(rootDir) {
716
- const live = new Set();
717
- for (const m of readMetadata(rootDir))
718
- if (m.contentHash)
719
- live.add(m.contentHash);
720
- return live;
721
- }
722
- /** True when a metadata log exists under `rootDir`.
723
- *
724
- * An empty live-hash set has two very different causes: the log is missing (we
725
- * cannot judge what is current) or the log exists and every document has been
726
- * removed (nothing is current). Collapsing them made `doc remove` of the LAST
727
- * document a no-op — the tombstoned chunks came straight back in search.
728
- *
729
- * Reads the path directly instead of via `metadataPath`, which mkdir's. */
730
- export function hasKnowledgeMetadata(rootDir) {
731
- return fs.existsSync(path.join(rootDir, '.monomind', 'knowledge', METADATA_FILE));
732
- }
733
- /**
734
- * True when `key` is a document chunk whose version is no longer current.
735
- * Non-`doc:` keys are never superseded. When no metadata is available nothing
736
- * is filtered, because "no metadata" must not read as "everything is stale".
737
- *
738
- * `metadataPresent` defaults to the old `live.size > 0` heuristic so existing
739
- * two-argument callers keep their exact behaviour; pass `hasKnowledgeMetadata`
740
- * to also filter correctly once the last document has been removed.
741
- */
742
- export function isSupersededKey(key, live, metadataPresent = live.size > 0) {
743
- if (!key?.startsWith('doc:'))
744
- return false;
745
- if (!metadataPresent)
746
- return false;
747
- return !live.has(key.split(':')[1] ?? '');
748
- }
749
- /** How many rows to ask the backend for per requested result when superseded
750
- * filtering is active — most rows in a long-lived store are old versions, so
751
- * a 1:1 fetch would return an almost-empty page. */
752
- const SUPERSEDED_OVERFETCH = 20;
753
- const SUPERSEDED_OVERFETCH_CAP = 300;
754
- export function supersededOverfetchLimit(limit, live) {
755
- if (live.size === 0)
756
- return limit;
757
- return Math.min(Math.max(limit * SUPERSEDED_OVERFETCH, limit), SUPERSEDED_OVERFETCH_CAP);
758
- }
759
- export async function searchKnowledge(query, opts) {
760
- const bridge = await getBridge();
761
- if (!bridge)
762
- return [];
763
- const scope = opts?.scope ?? 'shared';
764
- const limit = opts?.limit ?? 10;
765
- const minScore = opts?.minScore ?? 0.3;
766
- const store = opts?.store ?? 'all';
767
- const targets = [];
768
- if (store !== 'global') {
769
- targets.push({
770
- ns: namespace(scope),
771
- root: opts?.rootDir ?? getProjectRoot(),
772
- label: scope,
773
- boost: PROJECT_SCOPE_BOOST,
774
- });
775
- }
776
- if (store !== 'project') {
777
- targets.push({
778
- ns: namespace('global'),
779
- dbPath: GLOBAL_BRAIN_SENTINEL,
780
- root: globalBrainRoot(),
781
- label: 'global',
782
- boost: 0,
783
- });
784
- }
785
- const includeSuperseded = opts?.includeSuperseded === true;
786
- const perTarget = await Promise.all(targets.map(async (t) => {
787
- const meta = readMetadata(t.root);
788
- const hasMeta = hasKnowledgeMetadata(t.root);
789
- const live = new Set();
790
- for (const m of meta)
791
- if (m.contentHash)
792
- live.add(m.contentHash);
793
- // Old versions dominate a long-lived store, so a 1:1 fetch would come back
794
- // nearly empty once they are filtered out. Over-fetch, then trim.
795
- const fetchLimit = includeSuperseded ? limit : supersededOverfetchLimit(limit, live);
796
- const result = await bridge
797
- .bridgeSearchEntries({
798
- query,
799
- namespace: t.ns,
800
- limit: fetchLimit,
801
- threshold: minScore,
802
- dbPath: t.dbPath,
803
- skipRerank: opts?.skipRerank,
804
- includeSuperseded,
805
- rootDir: t.root,
806
- })
807
- .catch(() => null);
808
- if (!result?.success || !result.results.length)
809
- return [];
810
- const hashToFile = new Map();
811
- const hashToProvenance = new Map();
812
- for (const m of meta) {
813
- hashToFile.set(m.contentHash, m.filePath);
814
- if (m.provenance)
815
- hashToProvenance.set(m.contentHash, m.provenance);
816
- }
817
- const kept = includeSuperseded
818
- ? result.results
819
- : result.results.filter((r) => !isSupersededKey(String(r.key ?? ''), live, hasMeta));
820
- return kept.slice(0, limit).map((r) => {
821
- const parts = r.key.startsWith('doc:') ? r.key.split(':') : [];
822
- const hash = parts[1] ?? '';
823
- const idx = parseInt(parts[2] ?? '0', 10);
824
- // The src: tag stored at ingest is the chunk's OWN provenance — the
825
- // hash→file map can misattribute when two documents share identical
826
- // content, and goes empty when a re-ingested file's hash changed.
827
- const srcTag = (r.tags ?? []).find((tag) => tag.startsWith('src:'));
828
- const superseded = includeSuperseded && isSupersededKey(String(r.key ?? ''), live, hasMeta);
829
- // RCL-10: offsets ride on the chunk's own `span:` tag, so citing a hit
830
- // costs nothing here. Chunks stored before span tags simply have none,
831
- // and `doc cite --chunk` recomputes them from the document.
832
- const span = parseSpanTag(r.tags);
833
- return {
834
- id: r.id,
835
- filePath: srcTag ? srcTag.slice(4) : (hashToFile.get(hash) ?? ''),
836
- // Serve the head of the chunk only — chunks are heading-anchored, so the
837
- // head carries the most relevant text, and full chunks (up to ~3.2K
838
- // chars) bloat every search response.
839
- text: typeof r.content === 'string' && r.content.length > SEARCH_EXCERPT_TEXT_CAP
840
- ? r.content.slice(0, SEARCH_EXCERPT_TEXT_CAP)
841
- : r.content,
842
- similarity: r.score + t.boost,
843
- chunkIndex: Number.isNaN(idx) ? 0 : idx,
844
- scope: t.label,
845
- ...(superseded ? { superseded: true } : {}),
846
- // RCL-07: only LIVE versions carry provenance here — a superseded
847
- // chunk's record is no longer in the live metadata. Its `url:` tag
848
- // still identifies the page it came from.
849
- ...(hashToProvenance.has(hash) ? { provenance: hashToProvenance.get(hash) } : {}),
850
- ...(span
851
- ? {
852
- startChar: span.startChar,
853
- endChar: span.endChar,
854
- anchor: citationAnchor(hash, span.startChar, span.endChar),
855
- }
856
- : {}),
857
- };
858
- });
859
- }));
860
- return perTarget
861
- .flat()
862
- .sort((a, b) => b.similarity - a.similarity)
863
- .slice(0, limit);
864
- }
865
- // ── List / Remove ──────────────────────────────────────────────────
866
- export function listDocuments(rootDir = getProjectRoot(), scope) {
867
- const all = readMetadata(rootDir);
868
- return scope ? all.filter((m) => m.scope === scope) : all;
869
- }
870
- /**
871
- * Every recorded version of one document, oldest first (RCL-06).
872
- *
873
- * `target` is either an indexed file path or a capture's `canonicalUrl`. Read
874
- * from the append-only log rather than the last-wins view, which is how a
875
- * superseded version stays addressable after its record has been replaced or
876
- * tombstoned.
877
- *
878
- * Best-effort by design: `readMetadata` compacts the log once it passes 1MB
879
- * and keeps only live records, so history older than a compaction is gone.
880
- * The `supersedes` pointer on each record is the durable part.
881
- */
882
- export function listDocumentVersions(rootDir = getProjectRoot(), target, scope) {
883
- const resolved = target ? path.resolve(target) : undefined;
884
- return readMetadataLog(rootDir)
885
- .filter((m) => m.chunkCount >= 0)
886
- .filter((m) => !scope || m.scope === scope)
887
- .filter((m) => !target || m.filePath === resolved || m.filePath === target || m.canonicalUrl === target)
888
- .sort((a, b) => (a.version ?? 0) - (b.version ?? 0) || a.indexedAt.localeCompare(b.indexedAt));
889
- }
890
- // ── Citation / lookup helpers (RCL-10) ─────────────────────────────
891
- /** The store root for a scope: the global brain for `global`, else the project. */
892
- export function getKnowledgeRoot(scope = 'shared', rootDir = getProjectRoot()) {
893
- return effectiveRoot(scope, rootDir);
894
- }
895
- /** Chunk spans for a text, using the SAME chunker the ingest used — this is
896
- * what makes a chunk index resolvable back to a character range without
897
- * storing the text twice. */
898
- export async function chunkSpans(text) {
899
- const chunks = await chunkDocument('cite', text);
900
- return chunks.map((c) => ({
901
- chunkIndex: c.chunkIndex,
902
- startChar: c.startChar,
903
- endChar: c.endChar,
904
- }));
905
- }
906
- /**
907
- * The indexed record for whatever a caller wrote down: a file path, a
908
- * capture's `canonicalUrl` (fragment ignored), or the `<scope>:<path>` docId.
909
- *
910
- * Live records win. A superseded version is only reached through the
911
- * append-only log, and only when nothing live matches — otherwise citing a
912
- * re-captured page would resolve against the version it replaced.
913
- */
914
- export function findDocumentRecord(rootDir = getProjectRoot(), target = '', scope) {
915
- const raw = target.trim();
916
- if (!raw)
917
- return undefined;
918
- // `<scope>:<path>` — but not `https://…`, whose colon is a URL scheme.
919
- const scoped = /^([a-z][a-z0-9_-]*):(?!\/\/)(.+)$/i.exec(raw);
920
- const candidates = scoped ? [raw, scoped[2]] : [raw];
921
- const hash = raw.indexOf('#');
922
- if (hash > 0)
923
- candidates.push(raw.slice(0, hash));
924
- const resolvedPaths = new Set(candidates.map((c) => path.resolve(c)));
925
- const wanted = new Set(candidates);
926
- const scopeFilter = scope ?? (scoped ? scoped[1] : undefined);
927
- const matches = (m) => {
928
- if (scopeFilter && m.scope !== scopeFilter && !wanted.has(m.filePath))
929
- return false;
930
- if (wanted.has(m.filePath) || resolvedPaths.has(path.resolve(m.filePath)))
931
- return true;
932
- return !!m.canonicalUrl && wanted.has(m.canonicalUrl);
933
- };
934
- const live = readMetadata(rootDir).filter(matches);
935
- if (live.length) {
936
- return live.sort((a, b) => (b.version ?? 0) - (a.version ?? 0))[0];
937
- }
938
- const historical = readMetadataLog(rootDir)
939
- .filter((m) => m.chunkCount >= 0)
940
- .filter(matches);
941
- return historical.sort((a, b) => (b.version ?? 0) - (a.version ?? 0))[0];
942
- }
943
- export async function removeDocument(filePath, scope = 'shared', rootDir = getProjectRoot()) {
944
- removeMetadataEntry(rootDir, path.resolve(filePath), scope);
945
- // SQLite cleanup: bridge doesn't expose delete-by-key, so metadata removal is sufficient.
946
- // Orphaned SQLite entries get swept on next full re-index or TTL expiry.
947
- }
948
- // ── Filesystem reconciliation (item 4b-i) ──────────────────────────
949
- /**
950
- * True for macOS AppleDouble sidecars (`._name`).
951
- *
952
- * Matches on the BASENAME PREFIX only. A legitimate document may contain `._`
953
- * elsewhere in its name (`v1._2-release.md`), or live under a dot-directory
954
- * that is deliberately indexed (`.monodesign/` critique snapshots), and
955
- * neither may be rejected.
956
- */
957
- export function isResourceFork(filePath) {
958
- return path.basename(filePath).startsWith('._');
959
- }
960
- /**
961
- * Reconcile the document index against the filesystem: find index entries whose
962
- * source file no longer exists and, only when explicitly asked, tombstone them.
963
- *
964
- * WHY — `removeDocument` only ever tombstoned metadata, and nothing has ever
965
- * compared the index against the disk, so a deleted file stayed searchable
966
- * forever. Measured 2026-07-28: 109 of 257 live entries (42.4%) had no file
967
- * behind them, including `docs/concepts/memory.md`. The Second Brain was
968
- * answering questions from documents the user had deleted.
969
- *
970
- * WHY IT IS THIS CAUTIOUS — "drop the index entry when the file is missing" is
971
- * a rule with a known catastrophic reading. A missing file is also an unmounted
972
- * volume, a checked-out branch, a partial clone, or a permissions failure. Two
973
- * guards were tried against real data and REJECTED; they are recorded here so
974
- * they are not re-proposed:
975
- *
976
- * - "abort if >50% of entries are missing" — the real, legitimate missing
977
- * fraction was 42.4%, so the threshold never fires in the one case we have.
978
- * Any threshold that would have blocked this reconcile is fitted to nothing.
979
- * - "only reconcile when the parent directory still exists" — 26 of the 109
980
- * missing files had no parent directory, because `docs/concepts`,
981
- * `docs/adrs` and `docs/commands` were legitimately deleted wholesale. A
982
- * deleted directory and an unmounted volume are indistinguishable there.
983
- *
984
- * What does discriminate is the ROOT. An intact, readable root carrying a
985
- * metadata log means the tree is genuinely present, so a missing file is
986
- * genuinely gone. A missing root means nothing beneath it is knowable and
987
- * nothing may be removed — hence throw rather than reconcile.
988
- *
989
- * Removal tombstones metadata; it does not delete store rows. Chunks stay on
990
- * disk and fall out of search through the existing superseded filter, which
991
- * keeps this consistent with the mark-don't-destroy rule and leaves the whole
992
- * operation reversible from the archive.
993
- */
994
- export async function reconcileIndex(rootDir = getProjectRoot(), opts) {
995
- const apply = opts?.apply === true;
996
- // Root guard — the unmounted-volume case. Every file below a missing root
997
- // looks deleted, so this must abort rather than reconcile.
998
- if (!rootDir || !fs.existsSync(rootDir)) {
999
- throw new Error(`reconcileIndex: project root does not exist: ${rootDir} — refusing to reconcile ` +
1000
- `(an unmounted volume makes every indexed file look deleted)`);
1001
- }
1002
- if (!hasKnowledgeMetadata(rootDir)) {
1003
- throw new Error(`reconcileIndex: no knowledge metadata log under ${rootDir} — refusing to reconcile ` +
1004
- `("no metadata" must not read as "everything is stale")`);
1005
- }
1006
- const records = readMetadata(rootDir).filter((m) => !opts?.scope || m.scope === opts.scope);
1007
- const missing = records.filter((m) => !fs.existsSync(m.filePath));
1008
- if (!apply || missing.length === 0) {
1009
- return { missing, scanned: records.length, applied: apply, removed: 0 };
1010
- }
1011
- // Archive BEFORE removing, inside the operation so no caller can bypass it
1012
- // by forgetting — the same precondition rule the delete path uses.
1013
- const dir = path.join(rootDir, '.monomind', 'knowledge', 'archive');
1014
- fs.mkdirSync(dir, { recursive: true });
1015
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
1016
- const archivePath = path.join(dir, `reconcile-${stamp}.jsonl`);
1017
- fs.writeFileSync(archivePath, `${missing.map((m) => JSON.stringify(m)).join('\n')}\n`, 'utf-8');
1018
- let removed = 0;
1019
- for (const m of missing) {
1020
- removeMetadataEntry(rootDir, m.filePath, m.scope);
1021
- removed++;
1022
- }
1023
- return { missing, scanned: records.length, applied: true, removed, archivePath };
1024
- }
1025
- // ── OKF Export ─────────────────────────────────────────────────────
1026
- export async function exportToOKF(outputDir, rootDir = getProjectRoot(), scope = 'shared') {
1027
- const docs = listDocuments(rootDir, scope);
1028
- fs.mkdirSync(outputDir, { recursive: true });
1029
- let exported = 0;
1030
- const indexEntries = [];
1031
- for (const doc of docs) {
1032
- // Read original content
1033
- let content = '';
1034
- try {
1035
- if (fs.existsSync(doc.filePath)) {
1036
- const entry = toFileEntry(doc.filePath);
1037
- content = await extractText(entry);
1038
- }
1039
- }
1040
- catch {
1041
- continue;
1042
- }
1043
- if (!content)
1044
- continue;
1045
- const title = path.basename(doc.filePath, path.extname(doc.filePath));
1046
- const ext = path.extname(doc.filePath).toLowerCase();
1047
- const relativePath = path.relative(rootDir, doc.filePath);
1048
- const slug = title.replace(/[^a-zA-Z0-9._-]+/g, '-').toLowerCase();
1049
- const outFile = path.join(outputDir, `${slug}.md`);
1050
- const yamlEscape = (s) => /[:"'[\]{}#&*!|>%@`]/.test(s) ? `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"` : s;
1051
- const frontmatter = [
1052
- '---',
1053
- `type: Document`,
1054
- `title: ${yamlEscape(title)}`,
1055
- `description: ${yamlEscape(`Extracted from ${path.basename(doc.filePath)}`)}`,
1056
- `resource: ${yamlEscape(relativePath)}`,
1057
- `tags: ["document", ${yamlEscape(ext.slice(1))}]`,
1058
- `timestamp: ${yamlEscape(doc.indexedAt)}`,
1059
- `contentHash: ${yamlEscape(doc.contentHash)}`,
1060
- `chunkCount: ${doc.chunkCount}`,
1061
- '---',
1062
- '',
1063
- ].join('\n');
1064
- fs.writeFileSync(outFile, frontmatter + content, 'utf-8');
1065
- indexEntries.push(`* [${title}](${slug}.md) - ${path.basename(doc.filePath)} (${doc.chunkCount} chunks)`);
1066
- exported++;
1067
- }
1068
- // Write index.md
1069
- const indexContent = [
1070
- `# Knowledge Bundle`,
1071
- '',
1072
- `Exported from monomind on ${new Date().toISOString().slice(0, 10)}`,
1073
- '',
1074
- ...indexEntries,
1075
- '',
1076
- ].join('\n');
1077
- fs.writeFileSync(path.join(outputDir, 'index.md'), indexContent, 'utf-8');
1078
- return { exported, outputDir };
1079
- }
1080
- // ── OKF Import ─────────────────────────────────────────────────────
1081
- export async function importFromOKF(bundleDir, scope = 'shared', rootDir = getProjectRoot()) {
1082
- const resolved = path.resolve(bundleDir);
1083
- const files = fs
1084
- .readdirSync(resolved)
1085
- .filter((f) => f.endsWith('.md') && f !== 'index.md' && f !== 'log.md')
1086
- .map((f) => path.join(resolved, f));
1087
- const result = {
1088
- filesProcessed: 0,
1089
- filesSkipped: 0,
1090
- totalChunks: 0,
1091
- errors: [],
1092
- results: [],
1093
- };
1094
- for (const file of files) {
1095
- const r = await ingestDocument(file, scope, rootDir);
1096
- result.results.push(r);
1097
- if (r.skipped) {
1098
- result.filesSkipped++;
1099
- }
1100
- else {
1101
- result.filesProcessed++;
1102
- result.totalChunks += r.chunksIndexed;
1103
- }
1104
- if (r.error && !r.skipped)
1105
- result.errors.push(`${r.filePath}: ${r.error}`);
1106
- }
1107
- return result;
1108
- }
24
+ export { chunkSpans } from './document-chunking.js';
25
+ export { findDocumentRecord, hasKnowledgeMetadata, isResourceFork, isSupersededKey, listDocuments, listDocumentVersions, liveContentHashes, reconcileIndex, removeDocument, supersededOverfetchLimit, } from './document-index.js';
26
+ export { ingestDirectory, ingestDocument } from './document-ingest.js';
27
+ export { searchKnowledge } from './document-search.js';
28
+ export { getKnowledgeRoot } from './document-store.js';
29
+ export { exportToOKF, importFromOKF } from './okf-bundle.js';
1109
30
  //# sourceMappingURL=document-pipeline.js.map