mindlore 0.7.0 → 0.7.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 (120) hide show
  1. package/README.md +30 -3
  2. package/dist/scripts/bundle-hooks.d.ts +2 -0
  3. package/dist/scripts/bundle-hooks.d.ts.map +1 -0
  4. package/dist/scripts/bundle-hooks.js +70 -0
  5. package/dist/scripts/bundle-hooks.js.map +1 -0
  6. package/dist/scripts/init.js +0 -3
  7. package/dist/scripts/init.js.map +1 -1
  8. package/dist/scripts/lib/all-migrations.d.ts.map +1 -1
  9. package/dist/scripts/lib/all-migrations.js +3 -0
  10. package/dist/scripts/lib/all-migrations.js.map +1 -1
  11. package/dist/scripts/lib/constants.d.ts +7 -2
  12. package/dist/scripts/lib/constants.d.ts.map +1 -1
  13. package/dist/scripts/lib/constants.js +17 -22
  14. package/dist/scripts/lib/constants.js.map +1 -1
  15. package/dist/scripts/lib/mcp-tools.d.ts.map +1 -1
  16. package/dist/scripts/lib/mcp-tools.js +63 -78
  17. package/dist/scripts/lib/mcp-tools.js.map +1 -1
  18. package/dist/scripts/lib/migrations-v072.d.ts +3 -0
  19. package/dist/scripts/lib/migrations-v072.d.ts.map +1 -0
  20. package/dist/scripts/lib/migrations-v072.js +25 -0
  21. package/dist/scripts/lib/migrations-v072.js.map +1 -0
  22. package/dist/scripts/lib/relation-helpers.d.ts +15 -0
  23. package/dist/scripts/lib/relation-helpers.d.ts.map +1 -0
  24. package/dist/scripts/lib/relation-helpers.js +30 -0
  25. package/dist/scripts/lib/relation-helpers.js.map +1 -0
  26. package/dist/scripts/lib/tool-adapters/get-adapter.d.ts +21 -0
  27. package/dist/scripts/lib/tool-adapters/get-adapter.d.ts.map +1 -0
  28. package/dist/scripts/lib/tool-adapters/get-adapter.js +51 -0
  29. package/dist/scripts/lib/tool-adapters/get-adapter.js.map +1 -0
  30. package/dist/scripts/lib/tool-adapters/relate-adapter.d.ts +34 -0
  31. package/dist/scripts/lib/tool-adapters/relate-adapter.d.ts.map +1 -0
  32. package/dist/scripts/lib/tool-adapters/relate-adapter.js +43 -0
  33. package/dist/scripts/lib/tool-adapters/relate-adapter.js.map +1 -0
  34. package/dist/scripts/lib/tool-adapters/search-adapter.d.ts +5 -0
  35. package/dist/scripts/lib/tool-adapters/search-adapter.d.ts.map +1 -1
  36. package/dist/scripts/lib/tool-adapters/search-adapter.js +37 -0
  37. package/dist/scripts/lib/tool-adapters/search-adapter.js.map +1 -1
  38. package/dist/scripts/mcp-server.js +1 -1
  39. package/dist/scripts/mcp-server.js.map +1 -1
  40. package/dist/tests/dont-repeat-dedup.test.d.ts +2 -0
  41. package/dist/tests/dont-repeat-dedup.test.d.ts.map +1 -0
  42. package/dist/tests/dont-repeat-dedup.test.js +93 -0
  43. package/dist/tests/dont-repeat-dedup.test.js.map +1 -0
  44. package/dist/tests/e2e-kg-pipeline.test.d.ts +2 -0
  45. package/dist/tests/e2e-kg-pipeline.test.d.ts.map +1 -0
  46. package/dist/tests/e2e-kg-pipeline.test.js +59 -0
  47. package/dist/tests/e2e-kg-pipeline.test.js.map +1 -0
  48. package/dist/tests/helpers/db.d.ts.map +1 -1
  49. package/dist/tests/helpers/db.js +2 -1
  50. package/dist/tests/helpers/db.js.map +1 -1
  51. package/dist/tests/hook-smoke.test.js +1 -1
  52. package/dist/tests/hook-smoke.test.js.map +1 -1
  53. package/dist/tests/mcp-get-tool.test.d.ts +2 -0
  54. package/dist/tests/mcp-get-tool.test.d.ts.map +1 -0
  55. package/dist/tests/mcp-get-tool.test.js +93 -0
  56. package/dist/tests/mcp-get-tool.test.js.map +1 -0
  57. package/dist/tests/mcp-relate-tool.test.d.ts +2 -0
  58. package/dist/tests/mcp-relate-tool.test.d.ts.map +1 -0
  59. package/dist/tests/mcp-relate-tool.test.js +85 -0
  60. package/dist/tests/mcp-relate-tool.test.js.map +1 -0
  61. package/dist/tests/mcp-server.test.js +3 -1
  62. package/dist/tests/mcp-server.test.js.map +1 -1
  63. package/dist/tests/mcp-tools.test.js +20 -0
  64. package/dist/tests/mcp-tools.test.js.map +1 -1
  65. package/dist/tests/memory-relate.test.d.ts +2 -0
  66. package/dist/tests/memory-relate.test.d.ts.map +1 -0
  67. package/dist/tests/memory-relate.test.js +70 -0
  68. package/dist/tests/memory-relate.test.js.map +1 -0
  69. package/dist/tests/migrations-v063.test.js +1 -1
  70. package/dist/tests/migrations-v072.test.d.ts +2 -0
  71. package/dist/tests/migrations-v072.test.d.ts.map +1 -0
  72. package/dist/tests/migrations-v072.test.js +74 -0
  73. package/dist/tests/migrations-v072.test.js.map +1 -0
  74. package/dist/tests/plugin-cache-regression.test.d.ts +2 -0
  75. package/dist/tests/plugin-cache-regression.test.d.ts.map +1 -0
  76. package/dist/tests/plugin-cache-regression.test.js +19 -0
  77. package/dist/tests/plugin-cache-regression.test.js.map +1 -0
  78. package/dist/tests/search-hook.test.js +1 -1
  79. package/dist/tests/search-hook.test.js.map +1 -1
  80. package/hooks/cc-memory-bulk-sync.cjs +606 -0
  81. package/hooks/cc-session-sync.cjs +856 -0
  82. package/hooks/hooks.json +149 -0
  83. package/hooks/lib/mindlore-common.cjs +2 -2
  84. package/hooks/lib/secure-io.cjs +17 -0
  85. package/hooks/mindlore-cwd-changed.cjs +19 -34
  86. package/hooks/mindlore-decision-detector.cjs +40 -31
  87. package/hooks/mindlore-dont-repeat.cjs +75 -115
  88. package/hooks/mindlore-fts5-sync.cjs +15 -44
  89. package/hooks/mindlore-index.cjs +100 -101
  90. package/hooks/mindlore-model-router.cjs +20 -32
  91. package/hooks/mindlore-post-compact.cjs +26 -42
  92. package/hooks/mindlore-post-read.cjs +35 -60
  93. package/hooks/mindlore-pre-compact.cjs +55 -73
  94. package/hooks/mindlore-read-guard.cjs +28 -51
  95. package/hooks/mindlore-research-guard.cjs +63 -101
  96. package/hooks/mindlore-search.cjs +1156 -93
  97. package/hooks/mindlore-session-end.cjs +155 -276
  98. package/hooks/mindlore-session-focus.cjs +672 -110
  99. package/hooks/src/lib/constants.cjs +15 -0
  100. package/hooks/src/lib/mindlore-common.cjs +975 -0
  101. package/hooks/src/lib/mindlore-common.d.cts +72 -0
  102. package/hooks/src/lib/secure-io.cjs +17 -0
  103. package/hooks/src/lib/types.d.ts +58 -0
  104. package/hooks/src/mindlore-cwd-changed.cjs +57 -0
  105. package/hooks/src/mindlore-decision-detector.cjs +54 -0
  106. package/hooks/src/mindlore-dont-repeat.cjs +243 -0
  107. package/hooks/src/mindlore-fts5-sync.cjs +98 -0
  108. package/hooks/src/mindlore-index.cjs +230 -0
  109. package/hooks/src/mindlore-model-router.cjs +54 -0
  110. package/hooks/src/mindlore-post-compact.cjs +69 -0
  111. package/hooks/src/mindlore-post-read.cjs +106 -0
  112. package/hooks/src/mindlore-pre-compact.cjs +154 -0
  113. package/hooks/src/mindlore-read-guard.cjs +105 -0
  114. package/hooks/src/mindlore-research-guard.cjs +176 -0
  115. package/hooks/src/mindlore-search.cjs +200 -0
  116. package/hooks/src/mindlore-session-end.cjs +511 -0
  117. package/hooks/src/mindlore-session-focus.cjs +256 -0
  118. package/package.json +8 -3
  119. package/plugin.json +5 -4
  120. package/templates/config.json +1 -1
@@ -0,0 +1,72 @@
1
+ import type BetterSqlite3 from 'better-sqlite3';
2
+ type Database = BetterSqlite3.Database;
3
+
4
+ export const MINDLORE_DIR: string;
5
+ export const GLOBAL_MINDLORE_DIR: string;
6
+ export const DB_NAME: string;
7
+ export const SKIP_FILES: Set<string>;
8
+ export const SQL_FTS_CREATE: string;
9
+ export const SQL_FTS_INSERT: string;
10
+ export const DEFAULT_MODELS: Record<string, string>;
11
+
12
+ export function globalDir(): string;
13
+ export function findMindloreDir(): string | null;
14
+ export function getActiveMindloreDir(): string | null;
15
+ export function getAllDbs(): string[];
16
+ export function getProjectName(): string;
17
+ export function getLatestDelta(diaryDir: string): string | null;
18
+ export function sha256(content: string): string;
19
+
20
+ export interface FrontmatterResult {
21
+ meta: Record<string, unknown>;
22
+ body: string;
23
+ }
24
+ export function parseFrontmatter(content: string): FrontmatterResult;
25
+
26
+ export interface FtsMetadata {
27
+ slug: string;
28
+ description: string;
29
+ type: string;
30
+ category: string;
31
+ title: string;
32
+ tags: string;
33
+ quality: string | null;
34
+ dateCaptured: string | null;
35
+ }
36
+ export function extractFtsMetadata(
37
+ meta: Record<string, unknown>,
38
+ body: string,
39
+ filePath: string,
40
+ baseDir: string,
41
+ ): FtsMetadata;
42
+
43
+ export function readHookStdin(fields: string[]): string;
44
+
45
+ export interface FtsEntry {
46
+ path: string;
47
+ slug: string;
48
+ description: string;
49
+ type: string;
50
+ category: string;
51
+ title: string;
52
+ content: string;
53
+ tags: string;
54
+ quality: string | null;
55
+ dateCaptured: string | null;
56
+ project: string;
57
+ }
58
+ export function insertFtsRow(db: Database, entry: FtsEntry): void;
59
+
60
+ export function extractHeadings(content: string, max?: number): string[];
61
+ export function requireDatabase(): typeof import('better-sqlite3');
62
+ export function openDatabase(dbPath: string, opts?: { readonly?: boolean }): Database | null;
63
+ export function getAllMdFiles(dir: string, skip?: Set<string>): string[];
64
+
65
+ export interface MindloreConfig {
66
+ version?: string;
67
+ created?: string;
68
+ models?: Record<string, string>;
69
+ [key: string]: unknown;
70
+ }
71
+ export function readConfig(mindloreDir: string): MindloreConfig | null;
72
+ export function detectSchemaVersion(db: unknown): number;
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+
5
+ function safeMkdir(dirPath) {
6
+ fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
7
+ }
8
+
9
+ function safeWriteFile(filePath, data) {
10
+ fs.writeFileSync(filePath, data, { encoding: 'utf8', mode: 0o600 });
11
+ }
12
+
13
+ function safeWriteJson(filePath, obj) {
14
+ safeWriteFile(filePath, JSON.stringify(obj, null, 2) + '\n');
15
+ }
16
+
17
+ module.exports = { safeMkdir, safeWriteFile, safeWriteJson };
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Type declarations for mindlore-common.cjs hook functions.
3
+ * Use with JSDoc @type imports in .cjs hook files.
4
+ */
5
+
6
+ export interface FtsMetadata {
7
+ slug: string;
8
+ description: string;
9
+ type: string;
10
+ category: string;
11
+ title: string;
12
+ tags: string;
13
+ quality: string | null;
14
+ dateCaptured: string | null;
15
+ }
16
+
17
+ export interface FtsEntry {
18
+ path: string;
19
+ slug?: string;
20
+ description?: string;
21
+ type?: string;
22
+ category?: string;
23
+ title?: string;
24
+ content?: string;
25
+ tags?: string;
26
+ quality?: string | null;
27
+ dateCaptured?: string | null;
28
+ project?: string | null;
29
+ }
30
+
31
+ export interface ParsedFrontmatter {
32
+ meta: Record<string, string | string[]>;
33
+ body: string;
34
+ }
35
+
36
+ export interface MindloreCommon {
37
+ MINDLORE_DIR: string;
38
+ GLOBAL_MINDLORE_DIR: string;
39
+ DB_NAME: string;
40
+ SKIP_FILES: Set<string>;
41
+ globalDir(): string;
42
+ findMindloreDir(): string | null;
43
+ getActiveMindloreDir(): string;
44
+ getAllDbs(): string[];
45
+ getLatestDelta(diaryDir: string): string | null;
46
+ sha256(content: string): string;
47
+ parseFrontmatter(content: string): ParsedFrontmatter;
48
+ extractFtsMetadata(meta: Record<string, string>, body: string, filePath: string, baseDir: string): FtsMetadata;
49
+ insertFtsRow(db: import('better-sqlite3').Database, entry: FtsEntry): void;
50
+ readHookStdin(fields: string[]): string;
51
+ extractHeadings(content: string, max: number): string[];
52
+ requireDatabase(): typeof import('better-sqlite3') | null;
53
+ openDatabase(dbPath: string, opts?: { readonly?: boolean }): import('better-sqlite3').Database | null;
54
+ getAllMdFiles(dir: string, skip?: Set<string>): string[];
55
+ SQL_FTS_CREATE: string;
56
+ SQL_FTS_INSERT: string;
57
+ getProjectName(): string;
58
+ }
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * mindlore-cwd-changed — CwdChanged hook
6
+ *
7
+ * Fires when user changes working directory.
8
+ * CwdChanged has NO inject to Claude — stdout is swallowed, stderr shown to user.
9
+ *
10
+ * Side effects:
11
+ * 1. Detect scope (global ~/.mindlore/ or none)
12
+ * 2. Write scope state to .mindlore/diary/_scope.json for session-focus to read
13
+ * 3. Show user-facing message via stderr
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const { findMindloreDir, globalDir, hookLog, withTelemetry } = require('./lib/mindlore-common.cjs');
19
+
20
+ function main() {
21
+ const cwd = process.cwd();
22
+ const activeDir = findMindloreDir();
23
+ const scope = !activeDir ? 'none' : activeDir.startsWith(globalDir()) ? 'global' : 'project';
24
+
25
+ if (activeDir) {
26
+ const diaryDir = path.join(activeDir, 'diary');
27
+ if (!fs.existsSync(diaryDir)) {
28
+ fs.mkdirSync(diaryDir, { recursive: true });
29
+ }
30
+
31
+ // Dirty-check: skip write if scope hasn't changed
32
+ const scopePath = path.join(diaryDir, '_scope.json');
33
+ if (fs.existsSync(scopePath)) {
34
+ try {
35
+ const existing = JSON.parse(fs.readFileSync(scopePath, 'utf8'));
36
+ if (existing.cwd === cwd && existing.scope === scope) return;
37
+ } catch (_err) {
38
+ // corrupt file — overwrite
39
+ }
40
+ }
41
+
42
+ fs.writeFileSync(scopePath, JSON.stringify({
43
+ scope,
44
+ dir: activeDir,
45
+ cwd,
46
+ timestamp: new Date().toISOString(),
47
+ }, null, 2), 'utf8');
48
+ }
49
+
50
+ if (scope === 'none') {
51
+ process.stderr.write(`[Mindlore] Bu projede mindlore kurulu degil. npx mindlore init calistirin.\n`);
52
+ } else {
53
+ process.stderr.write(`[Mindlore scope: ${scope}] ${activeDir}\n`);
54
+ }
55
+ }
56
+
57
+ withTelemetry('mindlore-cwd-changed', main).catch(err => { hookLog('cwd-changed', 'error', err?.message ?? String(err)); });
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * mindlore-decision-detector — UserPromptSubmit hook
6
+ *
7
+ * Detects decision signals in user messages (TR + EN).
8
+ * Outputs a suggestion to record the decision via /mindlore-decide.
9
+ * Does NOT block (exit 0) — advisory only.
10
+ */
11
+
12
+ const { findMindloreDir, readHookStdin, hookLog, withTelemetry } = require('./lib/mindlore-common.cjs');
13
+
14
+ const SIGNALS_TR = [
15
+ 'karar verdik', 'karar verildi', 'kararlastirdik', 'kararlaştırdık',
16
+ 'şunu seçtik', 'sunu sectik', 'bunu yapmayalım', 'bunu yapmayalim',
17
+ 'yerine', 'tercih ettik', 'onaylandi', 'onaylandı', 'kesinleşti', 'kesinlesti',
18
+ 'vazgeçtik', 'vazgectik', 'iptal ettik',
19
+ ];
20
+
21
+ const SIGNALS_EN = [
22
+ 'decided', 'decision made', "let's go with", 'lets go with',
23
+ "we'll use", 'well use', 'approved', 'settled on',
24
+ 'going with', 'chosen', 'finalized', 'rejected',
25
+ ];
26
+
27
+ function detectDecision(text) {
28
+ const lower = text.toLowerCase();
29
+ for (const signal of SIGNALS_TR) {
30
+ if (lower.includes(signal)) return signal;
31
+ }
32
+ for (const signal of SIGNALS_EN) {
33
+ if (lower.includes(signal)) return signal;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ function main() {
39
+ const baseDir = findMindloreDir();
40
+ if (!baseDir) return;
41
+
42
+ const userText = readHookStdin(['prompt', 'content', 'message']);
43
+ if (!userText || userText.length < 10) return;
44
+
45
+ const signal = detectDecision(userText);
46
+ if (signal) {
47
+ process.stdout.write(`[Mindlore: Karar sinyali tespit edildi ("${signal}") — /mindlore-decide record ile kaydetmek ister misin?]\n`);
48
+ }
49
+ }
50
+
51
+ withTelemetry('mindlore-decision-detector', main).catch(err => {
52
+ hookLog('mindlore-decision-detector', 'error', err?.message ?? String(err));
53
+ process.exit(0);
54
+ });
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * mindlore-dont-repeat — PreToolUse hook (matcher: "Write|Edit")
6
+ *
7
+ * Checks code being written against negative rules (DON'T, NEVER, AVOID, YAPMA, etc.)
8
+ * found in LESSONS files and Mindlore learnings/.
9
+ *
10
+ * Sources checked (in order):
11
+ * 1. ~/.claude/lessons/global.md (global rules)
12
+ * 2. ./LESSONS.md (project-level rules, if exists)
13
+ * 3. .mindlore/learnings/*.md (Mindlore learnings, if exists)
14
+ *
15
+ * Advisory only (exit 0) — does not block, injects additionalContext warning.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const os = require('os');
21
+ const { findMindloreDir, getProjectName, hookLog, withTelemetrySync } = require('./lib/mindlore-common.cjs');
22
+
23
+ /**
24
+ * File-persisted pattern cache — survives across process invocations.
25
+ * Cache file: .mindlore/diary/_pattern-cache.json
26
+ * Each entry keyed by source file path, stores mtimeMs + extracted patterns.
27
+ * On hit: stat only, no readFile+parse. On miss: read, parse, update cache.
28
+ */
29
+
30
+ let cacheDirty = false;
31
+
32
+ function readCache(cachePath) {
33
+ if (!cachePath) return {};
34
+ try {
35
+ return JSON.parse(fs.readFileSync(cachePath, 'utf8'));
36
+ } catch (_err) {
37
+ return {};
38
+ }
39
+ }
40
+
41
+ function writeCache(cachePath, cache) {
42
+ if (!cachePath || !cacheDirty) return;
43
+ try {
44
+ fs.writeFileSync(cachePath, JSON.stringify(cache), 'utf8');
45
+ } catch (_err) { /* write failure is non-fatal */ }
46
+ }
47
+
48
+ function loadPatterns(filePath, cache) {
49
+ try {
50
+ const stat = fs.statSync(filePath);
51
+ const mtimeMs = stat.mtimeMs;
52
+ const cached = cache[filePath];
53
+ if (cached && cached.mtimeMs === mtimeMs) return cached.patterns;
54
+
55
+ const patterns = extractNegativePatterns(fs.readFileSync(filePath, 'utf8'));
56
+ cache[filePath] = { mtimeMs, patterns };
57
+ cacheDirty = true;
58
+ return patterns;
59
+ } catch (_err) {
60
+ return [];
61
+ }
62
+ }
63
+
64
+ function extractNegativePatterns(content) {
65
+ const patterns = [];
66
+ const lines = content.split('\n');
67
+
68
+ for (const line of lines) {
69
+ const trimmed = line.trim();
70
+ // Multi-language: TR (YAPMA, KRITIK) + EN (DON'T, NEVER, AVOID, DO NOT)
71
+ const isNegativeRule = /^-\s*(YAPMA|KRITIK|DON'?T|NEVER|AVOID|DO NOT):/i.test(trimmed);
72
+ if (!isNegativeRule) continue;
73
+
74
+ // Extract backtick-quoted code patterns: `pattern`
75
+ const backtickMatches = trimmed.match(/`([^`]+)`/g);
76
+ if (backtickMatches) {
77
+ for (const match of backtickMatches) {
78
+ const pattern = match.slice(1, -1).trim();
79
+ // Skip short/generic patterns — too many false positives
80
+ if (pattern.length < 8) continue;
81
+ if (/^[^a-zA-Z0-9]+$/.test(pattern)) continue;
82
+ // Skip single words (too generic: "node", "bash", "any")
83
+ if (/^\w+$/.test(pattern) && pattern.length < 12) continue;
84
+ // Skip file extensions and paths
85
+ if (/^\.\w{1,5}$/.test(pattern)) continue;
86
+ if (pattern.startsWith('/') || pattern.startsWith('~')) continue;
87
+ if (pattern.includes('.md') || pattern.includes('.json')) continue;
88
+ // Skip common false-positive patterns
89
+ if (/^(node|bash|npm|git|process|require|import|export|const|let|var)$/i.test(pattern)) continue;
90
+
91
+ patterns.push({
92
+ pattern,
93
+ rule: trimmed.substring(0, 120),
94
+ });
95
+ }
96
+ }
97
+
98
+ // Extract "quoted strings" as patterns
99
+ const quoteMatches = trimmed.match(/"([^"]+)"/g);
100
+ if (quoteMatches) {
101
+ for (const match of quoteMatches) {
102
+ const quoted = match.slice(1, -1).trim();
103
+ if (quoted.length < 4) continue;
104
+ patterns.push({
105
+ pattern: quoted,
106
+ rule: trimmed.substring(0, 120),
107
+ });
108
+ }
109
+ }
110
+ }
111
+
112
+ return patterns;
113
+ }
114
+
115
+ let _lessonsEnforcementCached = null;
116
+ function hasLessonsEnforcementHook() {
117
+ if (_lessonsEnforcementCached !== null) return _lessonsEnforcementCached;
118
+ try {
119
+ const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
120
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
121
+ const hooks = settings.hooks || {};
122
+ const preToolUse = hooks.PreToolUse || [];
123
+ _lessonsEnforcementCached = preToolUse.some(entry => {
124
+ const cmds = (entry.hooks || []).map(h => h.command || '').concat(entry.command || '');
125
+ return cmds.some(c => c.includes('lessons-enforcement'));
126
+ });
127
+ } catch (_err) {
128
+ _lessonsEnforcementCached = false;
129
+ }
130
+ return _lessonsEnforcementCached;
131
+ }
132
+
133
+ function checkContent(content, patterns) {
134
+ const matches = [];
135
+ for (const p of patterns) {
136
+ try {
137
+ const escaped = p.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
138
+ const regex = new RegExp(escaped, 'i');
139
+ if (regex.test(content)) {
140
+ matches.push(p);
141
+ }
142
+ } catch { /* skip invalid patterns */ }
143
+ }
144
+ return matches;
145
+ }
146
+
147
+ function main() {
148
+ let input = '';
149
+ const stdinTimeout = setTimeout(() => process.exit(0), 3000);
150
+ process.stdin.setEncoding('utf8');
151
+ process.stdin.on('error', () => process.exit(0));
152
+ process.stdin.on('data', chunk => input += chunk);
153
+ process.stdin.on('end', () => {
154
+ clearTimeout(stdinTimeout);
155
+ try {
156
+ const data = JSON.parse(input || '{}');
157
+ const toolName = data.tool_name || '';
158
+
159
+ if (!['Write', 'Edit'].includes(toolName)) {
160
+ return process.exit(0);
161
+ }
162
+
163
+ const toolInput = data.tool_input || {};
164
+ const filePath = toolInput.file_path || '';
165
+
166
+ // Skip non-code files
167
+ if (!filePath) return process.exit(0);
168
+ const ext = path.extname(filePath).toLowerCase();
169
+ const codeExts = ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.py', '.go', '.rs', '.java', '.c', '.cpp', '.h', '.sh', '.yaml', '.yml'];
170
+ if (!codeExts.includes(ext)) return process.exit(0);
171
+
172
+ // Skip rule files themselves
173
+ const basename = path.basename(filePath);
174
+ if (basename === 'LESSONS.md' || basename === 'global.md' || basename === 'CLAUDE.md') {
175
+ return process.exit(0);
176
+ }
177
+
178
+ // Collect content being written (skip old_string — that's code being removed, not added)
179
+ const allContent = [
180
+ toolInput.content || '',
181
+ toolInput.new_string || '',
182
+ ].join('\n');
183
+
184
+ if (allContent.trim().length < 10) return process.exit(0);
185
+
186
+ // Full dedup: lessons-enforcement hook scans identical sources — skip entirely
187
+ if (hasLessonsEnforcementHook()) return process.exit(0);
188
+
189
+ // Load patterns from all sources (file-persisted mtime cache)
190
+ const mindloreDir = findMindloreDir();
191
+ const cachePath = mindloreDir ? path.join(mindloreDir, 'diary', `_pattern-cache-${getProjectName()}.json`) : null;
192
+ const cache = readCache(cachePath);
193
+ const allPatterns = [];
194
+ const cwd = process.cwd();
195
+
196
+ // 1. Global lessons
197
+ allPatterns.push(...loadPatterns(path.join(os.homedir(), '.claude', 'lessons', 'global.md'), cache));
198
+
199
+ // 2. Project LESSONS.md
200
+ allPatterns.push(...loadPatterns(path.join(cwd, 'LESSONS.md'), cache));
201
+
202
+ // 3. Mindlore learnings/ directory
203
+ if (mindloreDir) {
204
+ const learningsDir = path.join(mindloreDir, 'learnings');
205
+ try {
206
+ const files = fs.readdirSync(learningsDir).filter(f => f.endsWith('.md'));
207
+ for (const file of files) {
208
+ allPatterns.push(...loadPatterns(path.join(learningsDir, file), cache));
209
+ }
210
+ } catch (_err) { /* learnings/ doesn't exist yet */ }
211
+ }
212
+
213
+ writeCache(cachePath, cache);
214
+
215
+ if (allPatterns.length === 0) return process.exit(0);
216
+
217
+ // Check content against patterns
218
+ const matches = checkContent(allContent, allPatterns);
219
+ if (matches.length === 0) return process.exit(0);
220
+
221
+ // Build warning — max 3 matches shown
222
+ const shown = matches.slice(0, 3);
223
+ const warning = shown.map(m =>
224
+ ` - Pattern: \`${m.pattern}\` → ${m.rule}`
225
+ ).join('\n');
226
+ const extra = matches.length > 3 ? `\n ... and ${matches.length - 3} more` : '';
227
+
228
+ const msg = `[Mindlore: ${matches.length} dont-repeat rule violation detected]\n${warning}${extra}`;
229
+
230
+ process.stdout.write(JSON.stringify({
231
+ hookSpecificOutput: {
232
+ hookEventName: 'PreToolUse',
233
+ additionalContext: msg
234
+ }
235
+ }));
236
+ } catch {
237
+ // Silent fail
238
+ }
239
+ process.exit(0);
240
+ });
241
+ }
242
+
243
+ try { withTelemetrySync('mindlore-dont-repeat', main); } catch (err) { hookLog('dont-repeat', 'error', err?.message ?? String(err)); }
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * mindlore-fts5-sync — FileChanged hook (incremental re-index)
6
+ *
7
+ * Handles bulk file changes by checking all .mindlore/ .md files
8
+ * against their content hashes and re-indexing only changed ones.
9
+ *
10
+ * Lightweight complement to mindlore-index.cjs which handles single files.
11
+ * This hook catches cases where multiple files change at once (e.g., git pull).
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { DB_NAME, sha256, openDatabase, getAllMdFiles, parseFrontmatter, extractFtsMetadata, insertFtsRow, readHookStdin, getActiveMindloreDir, getProjectName, resolveProject, hookLog, withTelemetry, SQL_FTS_SESSIONS_INSERT, isSessionCategory, isInsideMindloreDir } = require('./lib/mindlore-common.cjs');
17
+
18
+ function main() {
19
+ const filePath = readHookStdin(['path', 'file_path']);
20
+
21
+ if (!filePath) return;
22
+ const resolved = path.resolve(filePath);
23
+ if (!isInsideMindloreDir(resolved)) return;
24
+
25
+ // Skip if this is a single .md file change — mindlore-index.cjs handles those.
26
+ // This hook is for bulk changes (git pull, manual batch edits).
27
+ if (filePath.endsWith('.md')) return;
28
+
29
+ const baseDir = getActiveMindloreDir();
30
+ if (!fs.existsSync(baseDir)) return;
31
+
32
+ const dbPath = path.join(baseDir, DB_NAME);
33
+ if (!fs.existsSync(dbPath)) return;
34
+
35
+ const db = openDatabase(dbPath);
36
+ if (!db) return;
37
+
38
+ const mdFiles = getAllMdFiles(baseDir);
39
+
40
+ const allHashes = new Map();
41
+ for (const row of db.prepare('SELECT path, content_hash FROM file_hashes').all()) {
42
+ allHashes.set(row.path, row.content_hash);
43
+ }
44
+
45
+ const deleteFts = db.prepare('DELETE FROM mindlore_fts WHERE path = ?');
46
+ const deleteFtsSessions = db.prepare('DELETE FROM mindlore_fts_sessions WHERE path = ?');
47
+ const insertFtsSessions = db.prepare(SQL_FTS_SESSIONS_INSERT);
48
+ const upsertHash = db.prepare(`
49
+ INSERT INTO file_hashes (path, content_hash, last_indexed)
50
+ VALUES (?, ?, ?)
51
+ ON CONFLICT(path) DO UPDATE SET
52
+ content_hash = excluded.content_hash,
53
+ last_indexed = excluded.last_indexed
54
+ `);
55
+
56
+ const now = new Date().toISOString();
57
+
58
+ try {
59
+ const project = getProjectName();
60
+
61
+ const changedFiles = [];
62
+ for (const file of mdFiles) {
63
+ const content = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
64
+ const hash = sha256(content);
65
+
66
+ const existingHash = allHashes.get(file);
67
+ if (existingHash === hash) continue;
68
+
69
+ const { meta, body } = parseFrontmatter(content);
70
+ const { slug, description, type, category, title, tags, quality, dateCaptured, project: ftsProject } = extractFtsMetadata(meta, body, file, baseDir);
71
+ const resolvedProject = resolveProject(ftsProject, file, project);
72
+ changedFiles.push({ file, hash, slug, description, type, category, title, tags, quality, dateCaptured, resolvedProject, body });
73
+ }
74
+
75
+ // No file I/O inside — minimize lock hold time
76
+ const transaction = db.transaction(() => {
77
+ for (const item of changedFiles) {
78
+ deleteFts.run(item.file);
79
+ deleteFtsSessions.run(item.file);
80
+ if (isSessionCategory(item.category)) {
81
+ insertFtsSessions.run(item.file, item.slug, item.description, item.type, item.category, item.title, item.body, item.tags, item.quality ?? null, item.dateCaptured ?? null, item.resolvedProject);
82
+ } else {
83
+ insertFtsRow(db, { path: item.file, slug: item.slug, description: item.description, type: item.type, category: item.category, title: item.title, content: item.body, tags: item.tags, quality: item.quality, dateCaptured: item.dateCaptured, project: item.resolvedProject });
84
+ }
85
+ upsertHash.run(item.file, item.hash, now);
86
+ }
87
+ });
88
+ transaction();
89
+ } finally {
90
+ db.close();
91
+ }
92
+
93
+ }
94
+
95
+ withTelemetry('mindlore-fts5-sync', main).catch(err => {
96
+ hookLog('mindlore-fts5-sync', 'error', err?.message ?? String(err));
97
+ process.exit(0);
98
+ });