mindlore 0.5.0 → 0.5.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.
Files changed (149) hide show
  1. package/README.md +15 -2
  2. package/dist/scripts/fetch-raw.d.ts +2 -0
  3. package/dist/scripts/fetch-raw.d.ts.map +1 -0
  4. package/dist/scripts/fetch-raw.js +124 -0
  5. package/dist/scripts/fetch-raw.js.map +1 -0
  6. package/dist/scripts/init.js +45 -3
  7. package/dist/scripts/init.js.map +1 -1
  8. package/dist/scripts/lib/constants.d.ts +13 -0
  9. package/dist/scripts/lib/constants.d.ts.map +1 -1
  10. package/dist/scripts/lib/constants.js +24 -4
  11. package/dist/scripts/lib/constants.js.map +1 -1
  12. package/dist/scripts/lib/db-helpers.d.ts +12 -2
  13. package/dist/scripts/lib/db-helpers.d.ts.map +1 -1
  14. package/dist/scripts/lib/db-helpers.js +36 -0
  15. package/dist/scripts/lib/db-helpers.js.map +1 -1
  16. package/dist/scripts/lib/hybrid-search.d.ts +0 -2
  17. package/dist/scripts/lib/hybrid-search.d.ts.map +1 -1
  18. package/dist/scripts/lib/hybrid-search.js +7 -1
  19. package/dist/scripts/lib/hybrid-search.js.map +1 -1
  20. package/dist/scripts/lib/migrations-v051.d.ts +3 -0
  21. package/dist/scripts/lib/migrations-v051.d.ts.map +1 -0
  22. package/dist/scripts/lib/migrations-v051.js +24 -0
  23. package/dist/scripts/lib/migrations-v051.js.map +1 -0
  24. package/dist/scripts/lib/migrations-v052.d.ts +3 -0
  25. package/dist/scripts/lib/migrations-v052.d.ts.map +1 -0
  26. package/dist/scripts/lib/migrations-v052.js +23 -0
  27. package/dist/scripts/lib/migrations-v052.js.map +1 -0
  28. package/dist/scripts/lib/migrations.d.ts +1 -0
  29. package/dist/scripts/lib/migrations.d.ts.map +1 -1
  30. package/dist/scripts/lib/migrations.js +3 -1
  31. package/dist/scripts/lib/migrations.js.map +1 -1
  32. package/dist/scripts/lib/privacy-filter.d.ts +3 -0
  33. package/dist/scripts/lib/privacy-filter.d.ts.map +1 -0
  34. package/dist/scripts/lib/privacy-filter.js +28 -0
  35. package/dist/scripts/lib/privacy-filter.js.map +1 -0
  36. package/dist/scripts/lib/similarity.d.ts +12 -0
  37. package/dist/scripts/lib/similarity.d.ts.map +1 -0
  38. package/dist/scripts/lib/similarity.js +64 -0
  39. package/dist/scripts/lib/similarity.js.map +1 -0
  40. package/dist/scripts/lib/skeleton.d.ts +2 -0
  41. package/dist/scripts/lib/skeleton.d.ts.map +1 -0
  42. package/dist/scripts/lib/skeleton.js +99 -0
  43. package/dist/scripts/lib/skeleton.js.map +1 -0
  44. package/dist/scripts/lib/skill-memory.d.ts +13 -0
  45. package/dist/scripts/lib/skill-memory.d.ts.map +1 -0
  46. package/dist/scripts/lib/skill-memory.js +94 -0
  47. package/dist/scripts/lib/skill-memory.js.map +1 -0
  48. package/dist/scripts/mindlore-fts5-index.js +18 -3
  49. package/dist/scripts/mindlore-fts5-index.js.map +1 -1
  50. package/dist/scripts/mindlore-health-check.d.ts +1 -1
  51. package/dist/scripts/mindlore-health-check.d.ts.map +1 -1
  52. package/dist/scripts/mindlore-health-check.js +117 -96
  53. package/dist/scripts/mindlore-health-check.js.map +1 -1
  54. package/dist/scripts/quality-populate.js +8 -4
  55. package/dist/scripts/quality-populate.js.map +1 -1
  56. package/dist/tests/catch-up.test.d.ts +2 -0
  57. package/dist/tests/catch-up.test.d.ts.map +1 -0
  58. package/dist/tests/catch-up.test.js +88 -0
  59. package/dist/tests/catch-up.test.js.map +1 -0
  60. package/dist/tests/cc-memory-sync.test.d.ts +2 -0
  61. package/dist/tests/cc-memory-sync.test.d.ts.map +1 -0
  62. package/dist/tests/cc-memory-sync.test.js +121 -0
  63. package/dist/tests/cc-memory-sync.test.js.map +1 -0
  64. package/dist/tests/episode-file.test.d.ts +2 -0
  65. package/dist/tests/episode-file.test.d.ts.map +1 -0
  66. package/dist/tests/episode-file.test.js +82 -0
  67. package/dist/tests/episode-file.test.js.map +1 -0
  68. package/dist/tests/fetch-raw.test.d.ts +2 -0
  69. package/dist/tests/fetch-raw.test.d.ts.map +1 -0
  70. package/dist/tests/fetch-raw.test.js +43 -0
  71. package/dist/tests/fetch-raw.test.js.map +1 -0
  72. package/dist/tests/helpers/db.d.ts +1 -0
  73. package/dist/tests/helpers/db.d.ts.map +1 -1
  74. package/dist/tests/helpers/db.js +10 -0
  75. package/dist/tests/helpers/db.js.map +1 -1
  76. package/dist/tests/hook-logging.test.d.ts +2 -0
  77. package/dist/tests/hook-logging.test.d.ts.map +1 -0
  78. package/dist/tests/hook-logging.test.js +108 -0
  79. package/dist/tests/hook-logging.test.js.map +1 -0
  80. package/dist/tests/index-cli-embed.test.d.ts +7 -0
  81. package/dist/tests/index-cli-embed.test.d.ts.map +1 -0
  82. package/dist/tests/index-cli-embed.test.js +128 -0
  83. package/dist/tests/index-cli-embed.test.js.map +1 -0
  84. package/dist/tests/privacy-filter.test.d.ts +2 -0
  85. package/dist/tests/privacy-filter.test.d.ts.map +1 -0
  86. package/dist/tests/privacy-filter.test.js +56 -0
  87. package/dist/tests/privacy-filter.test.js.map +1 -0
  88. package/dist/tests/resolve-hook-common.test.d.ts +2 -0
  89. package/dist/tests/resolve-hook-common.test.d.ts.map +1 -0
  90. package/dist/tests/resolve-hook-common.test.js +30 -0
  91. package/dist/tests/resolve-hook-common.test.js.map +1 -0
  92. package/dist/tests/schema-version.test.js +28 -0
  93. package/dist/tests/schema-version.test.js.map +1 -1
  94. package/dist/tests/search-cli-hybrid.test.d.ts +6 -0
  95. package/dist/tests/search-cli-hybrid.test.d.ts.map +1 -0
  96. package/dist/tests/search-cli-hybrid.test.js +103 -0
  97. package/dist/tests/search-cli-hybrid.test.js.map +1 -0
  98. package/dist/tests/search-hook.test.js +33 -0
  99. package/dist/tests/search-hook.test.js.map +1 -1
  100. package/dist/tests/search-offload.test.d.ts +2 -0
  101. package/dist/tests/search-offload.test.d.ts.map +1 -0
  102. package/dist/tests/search-offload.test.js +34 -0
  103. package/dist/tests/search-offload.test.js.map +1 -0
  104. package/dist/tests/similarity.test.d.ts +2 -0
  105. package/dist/tests/similarity.test.d.ts.map +1 -0
  106. package/dist/tests/similarity.test.js +61 -0
  107. package/dist/tests/similarity.test.js.map +1 -0
  108. package/dist/tests/skeleton.test.d.ts +2 -0
  109. package/dist/tests/skeleton.test.d.ts.map +1 -0
  110. package/dist/tests/skeleton.test.js +116 -0
  111. package/dist/tests/skeleton.test.js.map +1 -0
  112. package/dist/tests/skill-memory-api.test.d.ts +2 -0
  113. package/dist/tests/skill-memory-api.test.d.ts.map +1 -0
  114. package/dist/tests/skill-memory-api.test.js +62 -0
  115. package/dist/tests/skill-memory-api.test.js.map +1 -0
  116. package/dist/tests/skill-memory.test.d.ts +2 -0
  117. package/dist/tests/skill-memory.test.d.ts.map +1 -0
  118. package/dist/tests/skill-memory.test.js +67 -0
  119. package/dist/tests/skill-memory.test.js.map +1 -0
  120. package/dist/tests/token-budget.test.d.ts +2 -0
  121. package/dist/tests/token-budget.test.d.ts.map +1 -0
  122. package/dist/tests/token-budget.test.js +32 -0
  123. package/dist/tests/token-budget.test.js.map +1 -0
  124. package/dist/tests/wiki-lint.test.d.ts +2 -0
  125. package/dist/tests/wiki-lint.test.d.ts.map +1 -0
  126. package/dist/tests/wiki-lint.test.js +47 -0
  127. package/dist/tests/wiki-lint.test.js.map +1 -0
  128. package/hooks/lib/mindlore-common.cjs +109 -2
  129. package/hooks/mindlore-cwd-changed.cjs +2 -2
  130. package/hooks/mindlore-decision-detector.cjs +2 -2
  131. package/hooks/mindlore-dont-repeat.cjs +2 -2
  132. package/hooks/mindlore-fts5-sync.cjs +2 -2
  133. package/hooks/mindlore-index.cjs +141 -3
  134. package/hooks/mindlore-model-router.cjs +2 -2
  135. package/hooks/mindlore-post-compact.cjs +2 -2
  136. package/hooks/mindlore-post-read.cjs +2 -2
  137. package/hooks/mindlore-pre-compact.cjs +2 -2
  138. package/hooks/mindlore-read-guard.cjs +15 -3
  139. package/hooks/mindlore-research-guard.cjs +2 -2
  140. package/hooks/mindlore-search.cjs +69 -41
  141. package/hooks/mindlore-session-end.cjs +129 -39
  142. package/hooks/mindlore-session-focus.cjs +24 -3
  143. package/package.json +6 -5
  144. package/plugin.json +29 -2
  145. package/skills/mindlore-diary/SKILL.md +76 -0
  146. package/skills/mindlore-ingest/SKILL.md +48 -50
  147. package/skills/mindlore-log/SKILL.md +3 -143
  148. package/skills/mindlore-reflect/SKILL.md +104 -0
  149. package/templates/config.json +6 -1
@@ -14,7 +14,7 @@
14
14
 
15
15
  const fs = require('fs');
16
16
  const path = require('path');
17
- const { findMindloreDir, readHookStdin, getProjectName } = require('./lib/mindlore-common.cjs');
17
+ const { findMindloreDir, readHookStdin, getProjectName, hookLog, extractSkeleton } = require('./lib/mindlore-common.cjs');
18
18
 
19
19
  function main() {
20
20
  const baseDir = findMindloreDir();
@@ -81,13 +81,25 @@ function main() {
81
81
  // Warn on 2nd read (exit 0 = allow but warn)
82
82
  if (count > 1) {
83
83
  const totalWaste = tokens > 0 ? ` Toplam tekrar: ~${tokens * (count - 1)} token.` : '';
84
+ let skeletonSection = '';
85
+ try {
86
+ const ext = path.extname(filePath).slice(1);
87
+ const fileContent = fs.readFileSync(filePath, 'utf8');
88
+ if (fileContent.length < 500_000) {
89
+ const skeleton = extractSkeleton(fileContent, ext);
90
+ if (skeleton !== fileContent) {
91
+ const truncated = skeleton.length > 2000 ? skeleton.slice(0, 2000) + '\n...[truncated]' : skeleton;
92
+ skeletonSection = '\n\n' + truncated;
93
+ }
94
+ }
95
+ } catch (_e) { /* unreadable/binary — skip */ }
84
96
  process.stdout.write(JSON.stringify({
85
97
  hookSpecificOutput: {
86
98
  hookEventName: 'PreToolUse',
87
- additionalContext: `[Mindlore: ${basename}${tokenInfo} bu session'da ${count}. kez okunuyor.${totalWaste} Bir sonraki okuma engellenecek — Edit gerekiyorsa simdi yap.]`
99
+ additionalContext: `[Mindlore: ${basename}${tokenInfo} bu session'da ${count}. kez okunuyor.${totalWaste} Bir sonraki okuma engellenecek — Edit gerekiyorsa simdi yap.]${skeletonSection}`
88
100
  }
89
101
  }));
90
102
  }
91
103
  }
92
104
 
93
- main();
105
+ try { main(); } catch (err) { hookLog('read-guard', 'error', err?.message ?? String(err)); }
@@ -14,7 +14,7 @@
14
14
 
15
15
  const fs = require('fs');
16
16
  const path = require('path');
17
- const { getAllDbs, requireDatabase, extractKeywords, sanitizeKeyword } = require('./lib/mindlore-common.cjs');
17
+ const { getAllDbs, requireDatabase, extractKeywords, sanitizeKeyword, hookLog } = require('./lib/mindlore-common.cjs');
18
18
 
19
19
  // Keywords that signal a research/web-search intent in agent prompts
20
20
  // Note: entries with dots/stars are regex patterns, rest are literals
@@ -141,4 +141,4 @@ function main() {
141
141
  process.stdout.write(JSON.stringify(output));
142
142
  }
143
143
 
144
- main();
144
+ try { main(); } catch (err) { hookLog('research-guard', 'error', err?.message ?? String(err)); }
@@ -10,11 +10,10 @@
10
10
 
11
11
  const fs = require('fs');
12
12
  const path = require('path');
13
- const { getAllDbs, requireDatabase, extractHeadings, readHookStdin, extractKeywords, readConfig, loadSqliteVecCjs, hasVecTableCjs } = require('./lib/mindlore-common.cjs');
13
+ const { getAllDbs, requireDatabase, extractHeadings, readHookStdin, extractKeywords, sanitizeKeyword, readConfig, loadSqliteVecCjs, hasVecTableCjs, hookLog } = require('./lib/mindlore-common.cjs');
14
14
 
15
15
  const MAX_RESULTS = 3;
16
16
  const MIN_QUERY_WORDS = 3;
17
- const MIN_KEYWORD_HITS = 2;
18
17
 
19
18
  // Try to load hybrid search module (built TS)
20
19
  let hybridSearchMod;
@@ -81,35 +80,30 @@ function searchDb(dbPath, keywords, Database) {
81
80
  }
82
81
  }
83
82
 
83
+ // FTS5-only fallback: OR-joined single query (replaces O(docs×keywords) nested loop)
84
84
  try {
85
- const allPaths = db.prepare('SELECT DISTINCT path FROM mindlore_fts').all();
86
- const matchStmt = db.prepare('SELECT rank FROM mindlore_fts WHERE path = ? AND mindlore_fts MATCH ?');
87
- const metaStmt = db.prepare(
88
- 'SELECT slug, description, category, title, tags FROM mindlore_fts WHERE path = ?'
89
- );
85
+ const sanitized = keywords.map(sanitizeKeyword).filter(Boolean);
86
+ if (sanitized.length === 0) { db.close(); return results; }
90
87
 
91
- for (const row of allPaths) {
92
- let hits = 0;
93
- let totalRank = 0;
94
-
95
- for (const kw of keywords) {
96
- try {
97
- const sanitized = kw.replace(/["*(){}[\]^~:]/g, '');
98
- if (!sanitized) continue;
99
- const r = matchStmt.get(row.path, '"' + sanitized + '"');
100
- if (r) {
101
- hits++;
102
- totalRank += r.rank;
103
- }
104
- } catch (_err) {
105
- // FTS5 query error for this keyword — skip
106
- }
107
- }
108
-
109
- if (hits >= MIN_KEYWORD_HITS) {
110
- const meta = metaStmt.get(row.path) || {};
111
- results.push({ path: row.path, hits, totalRank, baseDir, meta });
112
- }
88
+ const ftsQuery = sanitized.join(' OR ');
89
+ const rows = db.prepare(
90
+ `SELECT path, slug, description, category, title, tags, rank
91
+ FROM mindlore_fts WHERE mindlore_fts MATCH ? ORDER BY rank LIMIT ?`
92
+ ).all(ftsQuery, MAX_RESULTS * 2);
93
+
94
+ for (const r of rows) {
95
+ results.push({
96
+ path: r.path || '',
97
+ slug: r.slug,
98
+ description: r.description || '',
99
+ category: r.category || '',
100
+ title: r.title || '',
101
+ tags: r.tags || '',
102
+ headings: [], // populated later in main() after slicing
103
+ hits: sanitized.length,
104
+ rank: r.rank,
105
+ baseDir,
106
+ });
113
107
  }
114
108
  } catch (_err) {
115
109
  // FTS5 query error — silently skip
@@ -126,7 +120,7 @@ function searchDb(dbPath, keywords, Database) {
126
120
  */
127
121
  function searchEpisodesFts(db, keywords) {
128
122
  try {
129
- const ftsQuery = keywords.map(kw => '"' + kw.replace(/["*(){}[\]^~:]/g, '') + '"').filter(q => q !== '""').join(' OR ');
123
+ const ftsQuery = keywords.map(sanitizeKeyword).filter(Boolean).join(' OR ');
130
124
  const rows = db.prepare(
131
125
  "SELECT title, category, slug, tags FROM mindlore_fts WHERE type = 'episode' AND mindlore_fts MATCH ? LIMIT 2"
132
126
  ).all(ftsQuery);
@@ -160,7 +154,7 @@ function main() {
160
154
  }
161
155
 
162
156
  // Sort: most keyword hits first, then best rank
163
- allScores.sort((a, b) => b.hits - a.hits || a.totalRank - b.totalRank);
157
+ allScores.sort((a, b) => b.hits - a.hits || a.rank - b.rank);
164
158
 
165
159
  // Deduplicate by full path (project version wins — appears first in sort)
166
160
  const seen = new Set();
@@ -176,17 +170,32 @@ function main() {
176
170
  const relevant = unique.slice(0, MAX_RESULTS);
177
171
  if (relevant.length === 0) return;
178
172
 
173
+ // Populate headings only for final results (avoid reading extra files)
174
+ for (const r of relevant) {
175
+ if (r.path && r.headings.length === 0 && fs.existsSync(r.path)) {
176
+ try {
177
+ const content = fs.readFileSync(r.path, 'utf8');
178
+ r.headings = extractHeadings(content, 3);
179
+ } catch (_err) { /* skip */ }
180
+ }
181
+ }
182
+
183
+ // Token budget from config
184
+ const config = readConfig(path.dirname(dbPaths[0]));
185
+ const budget = (config && config.tokenBudget) || {};
186
+ // Defaults match DEFAULT_TOKEN_BUDGET in scripts/lib/constants.ts
187
+ const perResultChars = ((budget.perResult || 500) * 4); // ~4 chars/token
188
+ const totalChars = ((budget.searchResults || 1500) * 4);
189
+
179
190
  // Build rich inject output
180
191
  const output = [];
192
+ let totalUsed = 0;
181
193
  for (const r of relevant) {
194
+ if (totalUsed >= totalChars) break;
182
195
  const meta = r.meta || {};
183
196
  const relativePath = path.relative(r.baseDir, r.path).replace(/\\/g, '/');
184
197
 
185
- let headings = [];
186
- if (fs.existsSync(r.path)) {
187
- const content = fs.readFileSync(r.path, 'utf8');
188
- headings = extractHeadings(content, 5);
189
- }
198
+ const headings = r.headings || [];
190
199
 
191
200
  const category = meta.category || path.dirname(relativePath).split('/')[0];
192
201
  const title = meta.title || meta.slug || path.basename(r.path, '.md');
@@ -194,9 +203,10 @@ function main() {
194
203
 
195
204
  const headingStr = headings.length > 0 ? `\nBasliklar: ${headings.join(', ')}` : '';
196
205
  const tagsStr = meta.tags ? `\nTags: ${meta.tags}` : '';
197
- output.push(
198
- `[Mindlore: ${category}/${title}] ${description}\nDosya: ${relativePath}${tagsStr}${headingStr}`
199
- );
206
+ const entry = `[Mindlore: ${category}/${title}] ${description}\nDosya: ${relativePath}${tagsStr}${headingStr}`;
207
+ const truncated = entry.slice(0, perResultChars);
208
+ totalUsed += truncated.length;
209
+ output.push(truncated);
200
210
  }
201
211
 
202
212
  // v0.4.0: Search episode mirrors in FTS5 (reuses searchDb's DB path, no extra open)
@@ -215,8 +225,26 @@ function main() {
215
225
  }
216
226
 
217
227
  if (output.length > 0) {
218
- process.stdout.write(output.join('\n\n') + '\n');
228
+ let outputStr = output.join('\n\n') + '\n';
229
+
230
+ const OFFLOAD_THRESHOLD = 10240; // 10KB
231
+ if (outputStr.length > OFFLOAD_THRESHOLD) {
232
+ const baseDir = path.dirname(dbPaths[0]);
233
+ const tmpDir = path.join(baseDir, 'tmp');
234
+ fs.mkdirSync(tmpDir, { recursive: true });
235
+ const fileName = `search-${Date.now()}.md`;
236
+ const filePath = path.join(tmpDir, fileName);
237
+ fs.writeFileSync(filePath, outputStr, 'utf8');
238
+
239
+ const summary = outputStr.slice(0, 500).replace(/\n/g, ' ').trim();
240
+ outputStr = `[Mindlore Search: ${outputStr.length} chars offloaded to ${filePath}]\n` +
241
+ `Summary: ${summary}...\n` +
242
+ `[Read full results: ${filePath}]`;
243
+ hookLog('search', 'info', 'offloaded to tmp/ (' + outputStr.length + ' chars)');
244
+ }
245
+
246
+ process.stdout.write(outputStr);
219
247
  }
220
248
  }
221
249
 
222
- main();
250
+ try { main(); } catch (err) { hookLog('search', 'error', err?.message ?? String(err)); }
@@ -13,22 +13,48 @@ const fs = require('fs');
13
13
  const path = require('path');
14
14
  const os = require('os');
15
15
  const { execSync, spawn } = require('child_process');
16
- const { findMindloreDir, globalDir, getProjectName, openDatabase, ensureEpisodesTable, hasEpisodesTable, insertBareEpisode, insertFtsRow } = require('./lib/mindlore-common.cjs');
16
+ const { findMindloreDir, globalDir, getProjectName, openDatabase, ensureEpisodesTable, hasEpisodesTable, insertBareEpisode, insertFtsRow, hookLog, SHARED_EXPORT_DIRS, resolveWin32Bin } = require('./lib/mindlore-common.cjs');
17
+
18
+ const EXPORT_DIRS = SHARED_EXPORT_DIRS;
17
19
 
18
20
  // --worker mode: heavy ops run in detached child process (survives parent exit)
19
21
  if (process.argv.includes('--worker')) {
22
+ hookLog('session-end', 'info', 'worker started, pid=' + process.pid);
20
23
  const dataPath = process.argv[process.argv.indexOf('--worker') + 1];
24
+ let payload;
21
25
  try {
22
26
  const raw = fs.readFileSync(dataPath, 'utf8');
23
- fs.unlinkSync(dataPath); // cleanup temp file before any processing
24
- const { baseDir, project, commits, changedFiles, reads } = JSON.parse(raw);
25
- writeBareEpisode(baseDir, project, commits, changedFiles, reads);
26
- syncObsidian(baseDir);
27
- syncGlobalRepo();
27
+ fs.unlinkSync(dataPath);
28
+ payload = JSON.parse(raw);
28
29
  } catch (_err) {
29
- // Graceful fail worker errors are silent
30
+ hookLog('session-end', 'error', 'payload read failed: ' + (_err?.message ?? _err));
31
+ process.exit(0);
32
+ }
33
+ const { baseDir, project, commits, changedFiles, reads } = payload;
34
+
35
+ async function safeRunAsync(fn, label) {
36
+ try {
37
+ await fn();
38
+ hookLog('session-end', 'info', label + ' OK');
39
+ } catch (e) {
40
+ hookLog('session-end', 'error', label + ' FAIL: ' + e?.message);
41
+ }
30
42
  }
31
- process.exit(0);
43
+
44
+ (async () => {
45
+ // Episode writes share DB — run sequentially first
46
+ await safeRunAsync(() => writeBareEpisode(baseDir, project, commits, changedFiles, reads), 'episode');
47
+ await safeRunAsync(() => writeEpisodeFile(baseDir, project, commits, changedFiles, reads), 'episode-file');
48
+
49
+ // Obsidian + git-sync are independent — run in parallel
50
+ await Promise.allSettled([
51
+ safeRunAsync(() => syncObsidian(baseDir), 'obsidian'),
52
+ safeRunAsync(() => syncGlobalRepo(), 'git-sync'),
53
+ ]);
54
+
55
+ hookLog('session-end', 'info', 'worker done');
56
+ process.exit(0);
57
+ })();
32
58
  }
33
59
 
34
60
  function formatDate(date) {
@@ -47,9 +73,10 @@ function formatDate(date) {
47
73
  function getRecentGitInfo() {
48
74
  try {
49
75
  // --name-only includes file names after each commit entry
50
- const raw = execSync('git log --oneline -5 --name-only 2>/dev/null', {
76
+ const raw = execSync('git log --oneline -5 --name-only', {
51
77
  encoding: 'utf8',
52
78
  timeout: 5000,
79
+ stdio: ['pipe', 'pipe', 'pipe'],
53
80
  }).trim();
54
81
  if (!raw) return { commits: [], changedFiles: [] };
55
82
 
@@ -164,7 +191,11 @@ function main() {
164
191
  const workerData = JSON.stringify({ baseDir, project, commits, changedFiles, reads });
165
192
  const tmpFile = path.join(os.tmpdir(), `mindlore-worker-${Date.now()}.json`);
166
193
  fs.writeFileSync(tmpFile, workerData, 'utf8');
167
- const child = spawn(process.execPath, [__filename, '--worker', tmpFile], {
194
+ // Use system node instead of process.execPath CC's embedded Node
195
+ // may not work as a standalone binary for detached worker processes.
196
+ // Resolve full path to avoid shell:true deprecation warning on Windows.
197
+ const nodeBin = resolveWin32Bin('node');
198
+ const child = spawn(nodeBin, [__filename, '--worker', tmpFile], {
168
199
  detached: true,
169
200
  stdio: 'ignore',
170
201
  cwd: process.cwd(),
@@ -173,6 +204,7 @@ function main() {
173
204
  } catch (_err) {
174
205
  // Fallback: run inline if spawn fails
175
206
  writeBareEpisode(baseDir, project, commits, changedFiles, reads);
207
+ writeEpisodeFile(baseDir, project, commits, changedFiles, reads);
176
208
  syncObsidian(baseDir);
177
209
  syncGlobalRepo();
178
210
  }
@@ -247,11 +279,60 @@ function writeBareEpisode(baseDir, project, commits, changedFiles, reads) {
247
279
 
248
280
  db.close();
249
281
  } catch (err) {
250
- process.stderr.write(`[mindlore] episode write failed: ${err?.message ?? err}\n`);
282
+ hookLog('session-end', 'error', `episode write failed: ${err?.message ?? err}`);
251
283
  }
252
284
  }
253
285
 
254
- const EXPORT_DIRS = ['analyses', 'decisions', 'diary', 'raw', 'sources', 'domains', 'connections', 'insights', 'learnings'];
286
+ /**
287
+ * Write episode as .md file to diary/{project}/ for human-readable browsing.
288
+ * Complements the DB episode — same content, different medium.
289
+ */
290
+ function writeEpisodeFile(baseDir, project, commits, changedFiles, reads) {
291
+ const projDir = path.join(baseDir, 'diary', project || 'unknown');
292
+ if (!fs.existsSync(projDir)) fs.mkdirSync(projDir, { recursive: true });
293
+
294
+ const now = process.env.MINDLORE_EPISODE_TS ? new Date(process.env.MINDLORE_EPISODE_TS) : new Date();
295
+ const ts = formatDate(now);
296
+ const filePath = path.join(projDir, `episode-${ts}.md`);
297
+ if (fs.existsSync(filePath)) return; // idempotent
298
+
299
+ const lines = [
300
+ '---',
301
+ `slug: episode-${ts}`,
302
+ 'type: episode',
303
+ `date: ${now.toISOString().slice(0, 10)}`,
304
+ `project: ${project || 'unknown'}`,
305
+ '---',
306
+ '',
307
+ `# Episode — ${ts}`,
308
+ '',
309
+ ];
310
+
311
+ if (commits.length > 0) {
312
+ lines.push('## Commits');
313
+ for (const c of commits) lines.push(`- ${c}`);
314
+ lines.push('');
315
+ }
316
+
317
+ if (changedFiles.length > 0) {
318
+ lines.push('## Changed Files');
319
+ for (const f of changedFiles) lines.push(`- ${f}`);
320
+ lines.push('');
321
+ }
322
+
323
+ if (reads) {
324
+ lines.push('## Read Stats');
325
+ lines.push(`- ${reads.count} files read, ${reads.repeats} repeated`);
326
+ lines.push('');
327
+ }
328
+
329
+ if (commits.length === 0 && changedFiles.length === 0) {
330
+ lines.push('_Read-only session — no commits or file changes._');
331
+ lines.push('');
332
+ }
333
+
334
+ fs.writeFileSync(filePath, lines.join('\n'), 'utf8');
335
+ }
255
336
 
256
337
  /**
257
338
  * Load obsidian-helpers from compiled dist (single source of truth for wikilink conversion).
@@ -316,27 +397,40 @@ function syncObsidian(baseDir) {
316
397
  if (!fs.existsSync(srcDir)) continue;
317
398
 
318
399
  const destDir = path.join(destBase, dir);
319
- if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
400
+ fs.mkdirSync(destDir, { recursive: true });
320
401
 
321
402
  for (const file of fs.readdirSync(srcDir).filter(f => f.endsWith('.md') && !f.startsWith('_'))) {
322
403
  if (exportMdFile(path.join(srcDir, file), path.join(destDir, file), convertFn)) exported++;
323
404
  }
405
+
406
+ // One-level subdirectories (e.g. diary/mindlore/)
407
+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
408
+ if (!entry.isDirectory() || entry.name.startsWith('_') || entry.name.startsWith('.')) continue;
409
+ const subSrc = path.join(srcDir, entry.name);
410
+ const subDest = path.join(destDir, entry.name);
411
+ fs.mkdirSync(subDest, { recursive: true });
412
+ for (const file of fs.readdirSync(subSrc).filter(f => f.endsWith('.md') && !f.startsWith('_'))) {
413
+ if (exportMdFile(path.join(subSrc, file), path.join(subDest, file), convertFn)) exported++;
414
+ }
415
+ }
324
416
  }
325
417
 
326
418
  for (const rootFile of ['INDEX.md', 'log.md']) {
327
419
  const srcPath = path.join(baseDir, rootFile);
328
420
  if (!fs.existsSync(srcPath)) continue;
329
- if (!fs.existsSync(destBase)) fs.mkdirSync(destBase, { recursive: true });
421
+ fs.mkdirSync(destBase, { recursive: true });
330
422
  if (exportMdFile(srcPath, path.join(destBase, rootFile), convertFn)) exported++;
331
423
  }
332
424
 
425
+ hookLog('session-end', 'info', `obsidian exported=${exported}, dirs=${EXPORT_DIRS.length}, vault=${vaultPath}`);
333
426
  if (exported > 0) {
334
427
  config.obsidian.lastExport = new Date().toISOString();
335
428
  config.obsidian.lastExportCount = exported;
336
429
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
337
430
  }
338
431
  } catch (err) {
339
- process.stderr.write(`[mindlore] obsidian sync failed: ${err?.message ?? err}\n`);
432
+ hookLog('session-end', 'error', `obsidian internal: ${err?.message ?? err}`);
433
+ throw err; // re-throw so safeRun logs FAIL
340
434
  }
341
435
  }
342
436
 
@@ -345,38 +439,34 @@ function syncObsidian(baseDir) {
345
439
  * Only runs for the global scope — project .mindlore/ is in the project's own git.
346
440
  * Push failure is graceful (offline support).
347
441
  */
442
+ function resolveGitBin() {
443
+ return resolveWin32Bin('git');
444
+ }
445
+
348
446
  function syncGlobalRepo() {
349
447
  const gDir = globalDir();
350
448
  const gitDir = path.join(gDir, '.git');
351
449
  if (!fs.existsSync(gitDir)) return;
352
450
 
353
- try {
354
- // Check for changes
355
- const status = execSync('git status --porcelain', {
356
- cwd: gDir,
357
- encoding: 'utf8',
358
- timeout: 5000,
359
- }).trim();
451
+ const git = resolveGitBin();
452
+ const execOpts = (timeout) => ({ cwd: gDir, encoding: 'utf8', timeout, stdio: 'pipe' });
360
453
 
361
- if (!status) return; // nothing to commit
454
+ // Check for changes
455
+ const status = execSync(`"${git}" status --porcelain`, execOpts(5000)).trim();
456
+ if (!status) return; // nothing to commit
362
457
 
363
- execSync('git add *.md mindlore.db config.json diary/ sources/ domains/ analyses/ decisions/ raw/ connections/ insights/ learnings/', { cwd: gDir, timeout: 5000, stdio: 'pipe' });
364
- const now = new Date().toISOString().slice(0, 19);
365
- execSync(`git commit -m "mindlore auto-sync ${now}"`, {
366
- cwd: gDir,
367
- timeout: 10000,
368
- stdio: 'pipe',
369
- });
458
+ execSync(`"${git}" add *.md mindlore.db diary/ sources/ domains/ analyses/ decisions/ raw/ connections/ insights/ learnings/`, execOpts(10000));
459
+ const now = new Date().toISOString().slice(0, 19);
460
+ execSync(`"${git}" commit -m "mindlore auto-sync ${now}"`, execOpts(15000));
370
461
 
371
- // Push — graceful fail if no remote or offline
372
- try {
373
- execSync('git push', { cwd: gDir, timeout: 15000, stdio: 'pipe' });
374
- } catch (_pushErr) {
375
- // Offline or no remote silently continue
376
- }
377
- } catch (_err) {
378
- // Git not available or commit failed — silently continue
462
+ // Push — graceful fail if no remote or offline
463
+ try {
464
+ execSync(`"${git}" push`, execOpts(15000));
465
+ } catch (_pushErr) {
466
+ hookLog('session-end', 'warn', 'git push failed (offline?): ' + (_pushErr?.message ?? '').slice(0, 100));
379
467
  }
380
468
  }
381
469
 
382
- main();
470
+ if (!process.argv.includes('--worker')) {
471
+ main();
472
+ }
@@ -10,7 +10,7 @@
10
10
 
11
11
  const fs = require('fs');
12
12
  const path = require('path');
13
- const { findMindloreDir, readConfig, openDatabase, hasEpisodesTable, queryRecentEpisodes, querySupersededChains, formatSupersededChains, queryMultiSessionEpisodes, formatMultiSessionEpisodes, getAllMdFiles } = require('./lib/mindlore-common.cjs');
13
+ const { findMindloreDir, readConfig, openDatabase, hasEpisodesTable, queryRecentEpisodes, querySupersededChains, formatSupersededChains, queryMultiSessionEpisodes, formatMultiSessionEpisodes, getAllMdFiles, getRecentHookErrors, hookLog } = require('./lib/mindlore-common.cjs');
14
14
 
15
15
  function main() {
16
16
  const baseDir = findMindloreDir();
@@ -117,8 +117,29 @@ function main() {
117
117
  }
118
118
  } catch (_healthErr) { /* skip */ }
119
119
 
120
- if (output.length > 0) {
121
- process.stdout.write(output.join('\n\n') + '\n');
120
+ // Check for recent hook errors — inject warnings into CC context
121
+ try {
122
+ const errors = getRecentHookErrors();
123
+ if (errors.length > 0) {
124
+ const lines = errors.map(e => `- [${e.ts.slice(0, 19)}] **${e.hook}** (${e.level}): ${e.msg}`);
125
+ output.push(`[Mindlore Hook Alerts]\n${lines.join('\n')}`);
126
+ }
127
+ } catch (_hookLogErr) { /* skip */ }
128
+
129
+ hookLog('session-focus', 'info', 'session started');
130
+
131
+ // Token budget for session inject
132
+ // Defaults match DEFAULT_TOKEN_BUDGET in scripts/lib/constants.ts
133
+ const budgetConfig = config?.tokenBudget ?? {};
134
+ const maxInjectChars = (budgetConfig.sessionInject || 2000) * 4;
135
+
136
+ let joined = output.join('\n\n');
137
+ if (joined.length > maxInjectChars) {
138
+ joined = joined.slice(0, maxInjectChars) + '\n[...truncated by token budget]';
139
+ }
140
+
141
+ if (joined.length > 0) {
142
+ process.stdout.write(joined + '\n');
122
143
  }
123
144
  }
124
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mindlore",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "AI-native knowledge system for Claude Code",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -17,7 +17,8 @@
17
17
  "health": "node dist/scripts/mindlore-health-check.js",
18
18
  "index": "node dist/scripts/mindlore-fts5-index.js",
19
19
  "search": "node dist/scripts/mindlore-fts5-search.js",
20
- "quality": "node dist/scripts/quality-populate.js"
20
+ "quality": "node dist/scripts/quality-populate.js",
21
+ "fetch-raw": "node dist/scripts/fetch-raw.js"
21
22
  },
22
23
  "keywords": [
23
24
  "claude-code",
@@ -43,7 +44,7 @@
43
44
  "node": ">=20.0.0"
44
45
  },
45
46
  "dependencies": {
46
- "better-sqlite3": "^11.0.0",
47
+ "better-sqlite3": "^12.9.0",
47
48
  "zod": "^4.3.6"
48
49
  },
49
50
  "devDependencies": {
@@ -53,8 +54,8 @@
53
54
  "@typescript-eslint/eslint-plugin": "^8.58.1",
54
55
  "@typescript-eslint/parser": "^8.58.1",
55
56
  "@xenova/transformers": "^2.17.2",
56
- "eslint": "^9.0.0",
57
- "globals": "^15.0.0",
57
+ "eslint": "^10.2.0",
58
+ "globals": "^17.5.0",
58
59
  "jest": "^29.7.0",
59
60
  "sqlite-vec": "^0.1.9",
60
61
  "ts-jest": "^29.4.9",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mindlore",
3
3
  "description": "AI-native knowledge system for Claude Code. Persistent, searchable, evolving knowledge base with FTS5.",
4
- "version": "0.5.0",
4
+ "version": "0.5.2",
5
5
  "skills": [
6
6
  {
7
7
  "name": "mindlore-ingest",
@@ -21,7 +21,17 @@
21
21
  {
22
22
  "name": "mindlore-log",
23
23
  "path": "skills/mindlore-log/SKILL.md",
24
- "description": "Session logging, pattern extraction, and wiki updates. Modes: diary (LLM session analysis to enriched episodes: decisions, discoveries, frictions, learnings, preferences, events), reflect (scan episodes for recurring patterns, 3-tier confidence assessment, nomination pipeline for rule proposals), status (recent sessions summary with trends), save (structured delta + log.md append + domain wiki update). Episodes-powered since v0.4.0."
24
+ "description": "Session logging and wiki updates. Modes: log (manual diary entry), status (recent sessions summary with trends), save (structured delta + log.md append + domain wiki update). For diary analysis use /mindlore-diary; for pattern extraction use /mindlore-reflect."
25
+ },
26
+ {
27
+ "name": "mindlore-diary",
28
+ "path": "skills/mindlore-diary/SKILL.md",
29
+ "description": "LLM-powered session analysis: decisions, discoveries, frictions, learnings. Promotes episodes to semantic knowledge with 3-tier confidence. Reads/writes skill_memory for continuity."
30
+ },
31
+ {
32
+ "name": "mindlore-reflect",
33
+ "path": "skills/mindlore-reflect/SKILL.md",
34
+ "description": "Pattern extraction from episodes: recurring decisions, frictions, discoveries. 3-tier confidence (Note/Learning/Nomination), nomination pipeline with approval flow, CLAUDE.md update proposals."
25
35
  },
26
36
  {
27
37
  "name": "mindlore-decide",
@@ -39,6 +49,23 @@
39
49
  "description": "Discover unexpected connections between knowledge sources — undirected exploration mode. Cross-references domains, sources, analyses, and episodes to find non-obvious relationships. Identifies: shared entities across sources, pattern convergence between domains, episodic evidence supporting or contradicting domain claims. Default scope: project + global (--scope project|global|all)."
40
50
  }
41
51
  ],
52
+ "agents": [
53
+ {
54
+ "name": "mindlore-assistant",
55
+ "path": "agents/mindlore-assistant.md",
56
+ "description": "Knowledge base Q&A with hybrid search and citations"
57
+ },
58
+ {
59
+ "name": "mindlore-researcher",
60
+ "path": "agents/mindlore-researcher.md",
61
+ "description": "Independent web research with source comparison"
62
+ },
63
+ {
64
+ "name": "mindlore-librarian",
65
+ "path": "agents/mindlore-librarian.md",
66
+ "description": "Periodic maintenance, stale detection, health trends"
67
+ }
68
+ ],
42
69
  "hooks": [
43
70
  {
44
71
  "event": "SessionStart",