@cachly-dev/mcp-server 0.10.128 → 0.10.130

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 (217) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +1 -7
  3. package/dist/packages/telegram-notify/client.js +2 -75
  4. package/dist/src/ambient-cli.js +7 -253
  5. package/dist/src/ambient-deps.js +1 -55
  6. package/dist/src/ambient-hooks.js +5 -278
  7. package/dist/src/ambient-ledger.js +6 -95
  8. package/dist/src/ambient-memory.js +1 -67
  9. package/dist/src/ambient-recall.js +1 -221
  10. package/dist/src/aussetzer.js +1 -82
  11. package/dist/src/auth.js +9 -140
  12. package/dist/src/autor-abzeichen.js +1 -56
  13. package/dist/src/autor.js +1 -136
  14. package/dist/src/bauabdruck.js +1 -93
  15. package/dist/src/bedeutung.js +2 -323
  16. package/dist/src/bench/cachly-bench.js +4 -249
  17. package/dist/src/bench/external-corpus.js +4 -135
  18. package/dist/src/bench/fixtures.js +1 -225
  19. package/dist/src/brain-export.js +16 -119
  20. package/dist/src/brain-watch-hook.js +8 -86
  21. package/dist/src/cachly-url.js +1 -21
  22. package/dist/src/ckg.js +1 -108
  23. package/dist/src/cls-hook.js +8 -94
  24. package/dist/src/confidence.js +1 -50
  25. package/dist/src/credentials.js +1 -85
  26. package/dist/src/deutsch.js +1 -223
  27. package/dist/src/doctor.js +2 -248
  28. package/dist/src/editor.js +1 -63
  29. package/dist/src/eingaenge-nachruesten.js +1 -290
  30. package/dist/src/eingaenge.js +2 -228
  31. package/dist/src/embeddings.js +13 -223
  32. package/dist/src/feldreparatur.js +3 -0
  33. package/dist/src/first-contact.js +4 -108
  34. package/dist/src/first-recall-proof.js +4 -41
  35. package/dist/src/funnel-milestones.js +2 -48
  36. package/dist/src/geliefert.js +1 -114
  37. package/dist/src/handlers/advanced.js +38 -537
  38. package/dist/src/handlers/brain.js +69 -4181
  39. package/dist/src/handlers/cache.js +59 -638
  40. package/dist/src/handlers/context.js +17 -182
  41. package/dist/src/handlers/fedbrain.js +40 -1436
  42. package/dist/src/handlers/instances.js +16 -201
  43. package/dist/src/handlers/roadmap.js +13 -175
  44. package/dist/src/handlers/share.js +19 -530
  45. package/dist/src/handlers/syndicate.js +38 -904
  46. package/dist/src/handlers/team.js +89 -1850
  47. package/dist/src/handlers/viz.js +3 -148
  48. package/dist/src/index.js +321 -4281
  49. package/dist/src/interferenz.js +1 -0
  50. package/dist/src/kostprobe.js +7 -125
  51. package/dist/src/lesson-preview.js +2 -133
  52. package/dist/src/namespace.js +1 -128
  53. package/dist/src/notifier.js +1 -6
  54. package/dist/src/rangfolge-stellschrauben.js +1 -0
  55. package/dist/src/rangfolge.js +1 -214
  56. package/dist/src/raumkorrektur.js +1 -197
  57. package/dist/src/recall-tiefe.js +1 -42
  58. package/dist/src/rerank.js +1 -154
  59. package/dist/src/resonanz.js +1 -0
  60. package/dist/src/search.js +1 -2104
  61. package/dist/src/seltenheitsbestand.js +1 -92
  62. package/dist/src/speicherlage.js +1 -84
  63. package/dist/src/spuren.js +1 -150
  64. package/dist/src/starter-corpus.js +1 -165
  65. package/dist/src/telemetry-types.js +0 -13
  66. package/dist/src/tools.js +10 -2465
  67. package/dist/src/toolspecs.js +1 -121
  68. package/dist/src/upgrade-nudge.js +1 -29
  69. package/dist/src/utils.js +1 -89
  70. package/dist/src/versuch.js +1 -250
  71. package/dist/src/vorspann.js +1 -146
  72. package/dist/src/wartung/vektoren-verdichten.js +1 -200
  73. package/dist/src/werkzeug-nutzung.js +1 -72
  74. package/dist/src/wertbeitrag.js +1 -73
  75. package/dist/src/wirkungsspur.js +1 -0
  76. package/glama.json +1 -1
  77. package/package.json +8 -7
  78. package/server.json +3 -3
  79. package/dist/index.d.ts +0 -1
  80. package/dist/index.js.map +0 -1
  81. package/dist/packages/telegram-notify/client.d.ts +0 -19
  82. package/dist/packages/telegram-notify/client.js.map +0 -1
  83. package/dist/src/ambient-cli.d.ts +0 -101
  84. package/dist/src/ambient-cli.js.map +0 -1
  85. package/dist/src/ambient-deps.d.ts +0 -26
  86. package/dist/src/ambient-deps.js.map +0 -1
  87. package/dist/src/ambient-hooks.d.ts +0 -137
  88. package/dist/src/ambient-hooks.js.map +0 -1
  89. package/dist/src/ambient-ledger.d.ts +0 -19
  90. package/dist/src/ambient-ledger.js.map +0 -1
  91. package/dist/src/ambient-memory.d.ts +0 -12
  92. package/dist/src/ambient-memory.js.map +0 -1
  93. package/dist/src/ambient-recall.d.ts +0 -127
  94. package/dist/src/ambient-recall.js.map +0 -1
  95. package/dist/src/aussetzer.d.ts +0 -67
  96. package/dist/src/aussetzer.js.map +0 -1
  97. package/dist/src/auth.d.ts +0 -43
  98. package/dist/src/auth.js.map +0 -1
  99. package/dist/src/autor-abzeichen.d.ts +0 -41
  100. package/dist/src/autor-abzeichen.js.map +0 -1
  101. package/dist/src/autor.d.ts +0 -101
  102. package/dist/src/autor.js.map +0 -1
  103. package/dist/src/bauabdruck-daten.generiert.json +0 -5
  104. package/dist/src/bauabdruck.d.ts +0 -38
  105. package/dist/src/bauabdruck.js.map +0 -1
  106. package/dist/src/bedeutung.d.ts +0 -168
  107. package/dist/src/bedeutung.js.map +0 -1
  108. package/dist/src/bench/cachly-bench.d.ts +0 -61
  109. package/dist/src/bench/cachly-bench.js.map +0 -1
  110. package/dist/src/bench/external-corpus.d.ts +0 -44
  111. package/dist/src/bench/external-corpus.js.map +0 -1
  112. package/dist/src/bench/fixtures.d.ts +0 -37
  113. package/dist/src/bench/fixtures.js.map +0 -1
  114. package/dist/src/brain-export.d.ts +0 -64
  115. package/dist/src/brain-export.js.map +0 -1
  116. package/dist/src/brain-watch-hook.d.ts +0 -21
  117. package/dist/src/brain-watch-hook.js.map +0 -1
  118. package/dist/src/cachly-url.d.ts +0 -68
  119. package/dist/src/cachly-url.js.map +0 -1
  120. package/dist/src/ckg.d.ts +0 -54
  121. package/dist/src/ckg.js.map +0 -1
  122. package/dist/src/cls-hook.d.ts +0 -15
  123. package/dist/src/cls-hook.js.map +0 -1
  124. package/dist/src/confidence.d.ts +0 -19
  125. package/dist/src/confidence.js.map +0 -1
  126. package/dist/src/credentials.d.ts +0 -37
  127. package/dist/src/credentials.js.map +0 -1
  128. package/dist/src/deutsch.d.ts +0 -98
  129. package/dist/src/deutsch.js.map +0 -1
  130. package/dist/src/doctor.d.ts +0 -47
  131. package/dist/src/doctor.js.map +0 -1
  132. package/dist/src/editor.d.ts +0 -9
  133. package/dist/src/editor.js.map +0 -1
  134. package/dist/src/eingaenge-nachruesten.d.ts +0 -41
  135. package/dist/src/eingaenge-nachruesten.js.map +0 -1
  136. package/dist/src/eingaenge.d.ts +0 -135
  137. package/dist/src/eingaenge.js.map +0 -1
  138. package/dist/src/embeddings.d.ts +0 -48
  139. package/dist/src/embeddings.js.map +0 -1
  140. package/dist/src/first-contact.d.ts +0 -56
  141. package/dist/src/first-contact.js.map +0 -1
  142. package/dist/src/first-recall-proof.d.ts +0 -19
  143. package/dist/src/first-recall-proof.js.map +0 -1
  144. package/dist/src/funnel-milestones.d.ts +0 -5
  145. package/dist/src/funnel-milestones.js.map +0 -1
  146. package/dist/src/geliefert.d.ts +0 -63
  147. package/dist/src/geliefert.js.map +0 -1
  148. package/dist/src/handlers/advanced.d.ts +0 -6
  149. package/dist/src/handlers/advanced.js.map +0 -1
  150. package/dist/src/handlers/brain.d.ts +0 -41
  151. package/dist/src/handlers/brain.js.map +0 -1
  152. package/dist/src/handlers/cache.d.ts +0 -6
  153. package/dist/src/handlers/cache.js.map +0 -1
  154. package/dist/src/handlers/context.d.ts +0 -6
  155. package/dist/src/handlers/context.js.map +0 -1
  156. package/dist/src/handlers/fedbrain.d.ts +0 -18
  157. package/dist/src/handlers/fedbrain.js.map +0 -1
  158. package/dist/src/handlers/instances.d.ts +0 -33
  159. package/dist/src/handlers/instances.js.map +0 -1
  160. package/dist/src/handlers/roadmap.d.ts +0 -6
  161. package/dist/src/handlers/roadmap.js.map +0 -1
  162. package/dist/src/handlers/share.d.ts +0 -8
  163. package/dist/src/handlers/share.js.map +0 -1
  164. package/dist/src/handlers/syndicate.d.ts +0 -6
  165. package/dist/src/handlers/syndicate.js.map +0 -1
  166. package/dist/src/handlers/team.d.ts +0 -45
  167. package/dist/src/handlers/team.js.map +0 -1
  168. package/dist/src/handlers/viz.d.ts +0 -6
  169. package/dist/src/handlers/viz.js.map +0 -1
  170. package/dist/src/index.d.ts +0 -93
  171. package/dist/src/index.js.map +0 -1
  172. package/dist/src/kostprobe.d.ts +0 -25
  173. package/dist/src/kostprobe.js.map +0 -1
  174. package/dist/src/lesson-preview.d.ts +0 -81
  175. package/dist/src/lesson-preview.js.map +0 -1
  176. package/dist/src/namespace.d.ts +0 -20
  177. package/dist/src/namespace.js.map +0 -1
  178. package/dist/src/notifier.d.ts +0 -5
  179. package/dist/src/notifier.js.map +0 -1
  180. package/dist/src/rangfolge.d.ts +0 -169
  181. package/dist/src/rangfolge.js.map +0 -1
  182. package/dist/src/raumkorrektur.d.ts +0 -100
  183. package/dist/src/raumkorrektur.js.map +0 -1
  184. package/dist/src/recall-tiefe.d.ts +0 -48
  185. package/dist/src/recall-tiefe.js.map +0 -1
  186. package/dist/src/rerank.d.ts +0 -48
  187. package/dist/src/rerank.js.map +0 -1
  188. package/dist/src/search.d.ts +0 -153
  189. package/dist/src/search.js.map +0 -1
  190. package/dist/src/seltenheitsbestand.d.ts +0 -53
  191. package/dist/src/seltenheitsbestand.js.map +0 -1
  192. package/dist/src/speicherlage.d.ts +0 -51
  193. package/dist/src/speicherlage.js.map +0 -1
  194. package/dist/src/spuren.d.ts +0 -97
  195. package/dist/src/spuren.js.map +0 -1
  196. package/dist/src/starter-corpus.d.ts +0 -28
  197. package/dist/src/starter-corpus.js.map +0 -1
  198. package/dist/src/telemetry-types.d.ts +0 -87
  199. package/dist/src/telemetry-types.js.map +0 -1
  200. package/dist/src/tools.d.ts +0 -2933
  201. package/dist/src/tools.js.map +0 -1
  202. package/dist/src/toolspecs.d.ts +0 -43
  203. package/dist/src/toolspecs.js.map +0 -1
  204. package/dist/src/upgrade-nudge.d.ts +0 -15
  205. package/dist/src/upgrade-nudge.js.map +0 -1
  206. package/dist/src/utils.d.ts +0 -34
  207. package/dist/src/utils.js.map +0 -1
  208. package/dist/src/versuch.d.ts +0 -179
  209. package/dist/src/versuch.js.map +0 -1
  210. package/dist/src/vorspann.d.ts +0 -73
  211. package/dist/src/vorspann.js.map +0 -1
  212. package/dist/src/wartung/vektoren-verdichten.d.ts +0 -50
  213. package/dist/src/wartung/vektoren-verdichten.js.map +0 -1
  214. package/dist/src/werkzeug-nutzung.d.ts +0 -62
  215. package/dist/src/werkzeug-nutzung.js.map +0 -1
  216. package/dist/src/wertbeitrag.d.ts +0 -57
  217. package/dist/src/wertbeitrag.js.map +0 -1
@@ -1,501 +1,33 @@
1
- import { ckgSlug } from '../ckg.js';
2
- import { safeJsonParse } from '../utils.js';
3
- import { ersparteMinuten } from '../wertbeitrag.js';
4
- export const ADVANCED_TOOL_NAMES = new Set([
5
- 'memory_consolidate', 'brain_diff', 'causal_trace', 'knowledge_decay', 'autopilot',
6
- ]);
7
- export async function handleAdvancedTool(name, args, getConnection, _apiFetch) {
8
- switch (name) {
9
- case 'memory_consolidate': {
10
- const { instance_id, dry_run = false, stale_days = 90 } = args;
11
- const redis = await getConnection(instance_id);
12
- const now = Date.now();
13
- const staleMs = stale_days * 86400 * 1000;
14
- // Scan all lessons
15
- let cursor = 0;
16
- const lessonKeys = [];
17
- do {
18
- const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
19
- cursor = parseInt(next);
20
- lessonKeys.push(...keys);
21
- } while (cursor !== 0);
22
- if (lessonKeys.length === 0) {
23
- return '🧠 **Brain is empty** — no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.';
24
- }
25
- const lessons = new Map();
26
- for (const k of lessonKeys) {
27
- const raw = await redis.get(k);
28
- if (!raw)
29
- continue;
30
- const lesson = safeJsonParse(raw, null);
31
- if (lesson)
32
- lessons.set(k, lesson);
33
- }
34
- // Detect duplicates: same topic prefix (e.g. deploy:api vs deploy:api-v2)
35
- const topicGroups = new Map();
36
- for (const [k, l] of lessons) {
37
- const prefix = l.topic.split(':')[0];
38
- const group = topicGroups.get(prefix) ?? [];
39
- group.push(k);
40
- topicGroups.set(prefix, group);
41
- }
42
- // Detect contradictions: same exact topic, different outcomes
43
- const contradictions = [];
44
- const exactTopics = new Map();
45
- for (const [k, l] of lessons) {
46
- const arr = exactTopics.get(l.topic) ?? [];
47
- arr.push(k);
48
- exactTopics.set(l.topic, arr);
49
- }
50
- for (const [topic, keys] of exactTopics) {
51
- const outcomes = new Set(keys.map(k => lessons.get(k)?.outcome));
52
- if (outcomes.size > 1)
53
- contradictions.push({ topic, keys });
54
- }
55
- // Detect stale: not recalled in stale_days
56
- const stale = [];
57
- for (const [k, l] of lessons) {
58
- const age = now - new Date(l.ts).getTime();
59
- const recalls = l.recall_count ?? 0;
60
- if (age > staleMs && recalls === 0)
61
- stale.push(k);
62
- }
63
- // Consolidation NEVER deletes a lesson.
64
- //
65
- // Until 2026-08-13 this block merged "duplicates by prefix": it grouped
66
- // every lesson by the segment before the first ':' and deleted all but
67
- // one per group. A single real run on a 626-lesson brain deleted 529 of
68
- // them — every `cachly:*` lesson counted as a duplicate of every other.
69
- //
70
- // The counts below stay (they are a report), the deletes are gone. Stale
71
- // entries still get a 30-day expiry — that is a deadline a recall lifts
72
- // again, not a deletion.
73
- const merged = 0;
74
- if (!dry_run) {
75
- for (const k of stale) {
76
- await redis.expire(k, 86400 * 30);
77
- }
78
- }
79
- const lines = [
80
- `🔬 **Memory Consolidation Report** ${dry_run ? '(dry run — no changes made)' : '✅ Applied'}`,
81
- ``,
82
- `📊 **Before:** ${lessonKeys.length} lessons`,
83
- ``,
84
- `🔁 **Contradictions detected:** ${contradictions.length}`,
85
- ...contradictions.slice(0, 5).map(c => ` → \`${c.topic}\`: ${c.keys.length} conflicting entries (kept: success)`),
86
- contradictions.length > 5 ? ` … and ${contradictions.length - 5} more` : '',
87
- ``,
88
- `♻️ **Duplicate clusters (counted, never deleted):** ${Array.from(topicGroups.values()).filter(v => v.length > 1).length}`,
89
- ``,
90
- `🕰️ **Stale entries (${stale_days}d, 0 recalls):** ${stale.length}` +
91
- (stale.length > 0 && !dry_run ? ` → set to expire in 30 days` : ''),
92
- ``,
93
- `📊 **After:** ${lessonKeys.length - merged} lessons`,
94
- ``,
95
- dry_run
96
- ? `💡 Re-run without dry_run=true to apply changes.`
97
- : `✨ Brain consolidated. Run \`brain_diff(since="1h")\` to see the delta.`,
98
- ].filter(s => s !== '').join('\n');
99
- return lines;
100
- }
101
- // ── v0.6 Cognitive Cache: brain_diff ─────────────────────────────────────
102
- case 'brain_diff': {
103
- const { instance_id, since = '7d', format = 'summary' } = args;
104
- const redis = await getConnection(instance_id);
105
- // Parse since
106
- let sinceMs;
107
- const match = since.match(/^(\d+)([dhm])$/);
108
- if (match) {
109
- const n = parseInt(match[1]);
110
- const unit = match[2];
111
- const mult = unit === 'd' ? 86400000 : unit === 'h' ? 3600000 : 60000;
112
- sinceMs = Date.now() - n * mult;
113
- }
114
- else {
115
- sinceMs = new Date(since).getTime() || Date.now() - 7 * 86400000;
116
- }
117
- // Scan all lessons
118
- let cursor = 0;
119
- const lessonKeys = [];
120
- do {
121
- const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
122
- cursor = parseInt(next);
123
- lessonKeys.push(...keys);
124
- } while (cursor !== 0);
125
- const added = [];
126
- const updated = [];
127
- const recalled = [];
128
- const total = lessonKeys.length;
129
- for (const k of lessonKeys) {
130
- const raw = await redis.get(k);
131
- if (!raw)
132
- continue;
133
- {
134
- const l = safeJsonParse(raw, null);
135
- if (!l)
136
- continue;
137
- const ts = new Date(l.ts).getTime();
138
- if (ts >= sinceMs) {
139
- // Check history to determine add vs update
140
- const histKey = `cachly:lesson:history:${l.topic}`;
141
- const histLen = await redis.llen(histKey);
142
- if (histLen <= 1)
143
- added.push(l);
144
- else
145
- updated.push(l);
146
- }
147
- if ((l.recall_count ?? 0) > 0) {
148
- // We can't easily know when last recalled without extra metadata, so include
149
- // lessons with recalls as "active"
150
- recalled.push(l);
151
- }
152
- }
153
- }
154
- const sinceLabel = match ? `last ${since}` : new Date(sinceMs).toLocaleDateString('de-DE');
155
- const lines = [
156
- `📊 **Brain Diff** — ${sinceLabel}`,
157
- ``,
158
- `Total lessons in brain: **${total}**`,
159
- ``,
160
- `✅ **New** (${added.length}):`,
161
- ...added.slice(0, format === 'detailed' ? 20 : 5).map(l => ` + \`${l.topic}\` — ${l.outcome} ${l.severity === 'critical' ? '🔴' : l.severity === 'major' ? '🟠' : '🟢'}`),
162
- added.length > 5 && format === 'summary' ? ` … and ${added.length - 5} more` : '',
163
- ``,
164
- `🔄 **Updated** (${updated.length}):`,
165
- ...updated.slice(0, format === 'detailed' ? 20 : 5).map(l => ` ~ \`${l.topic}\` — now: ${l.outcome}`),
166
- updated.length > 5 && format === 'summary' ? ` … and ${updated.length - 5} more` : '',
167
- ``,
168
- `🔍 **Active** (recalled at least once): ${recalled.length}`,
169
- ``,
170
- ].filter(s => s !== '');
171
- // ── 10X brain_diff extensions ──────────────────────────────────────────
172
- // 1. Contested → Established (resolution nodes created in window)
173
- const resolutionKeys = [];
174
- const rsStream = redis.scanStream({ match: 'cachly:ckg:node:resolution-*', count: 100 });
175
- await new Promise((res, rej) => { rsStream.on('data', (b) => resolutionKeys.push(...b)); rsStream.on('end', res); rsStream.on('error', rej); });
176
- const recentResolutions = [];
177
- for (const rk of resolutionKeys) {
178
- const rr = await redis.get(rk);
179
- if (!rr)
180
- continue;
181
- {
182
- const rn = safeJsonParse(rr, null);
183
- if (rn?.ts && new Date(rn.ts).getTime() >= sinceMs)
184
- recentResolutions.push({ topic: rn.topic ?? rk, resolution: rn.resolution ?? 'unknown', ts: rn.ts });
185
- }
186
- }
187
- if (recentResolutions.length > 0) {
188
- lines.push(`🗳️ **MADC Resolutions** (${recentResolutions.length} contested beliefs resolved):`);
189
- for (const r of recentResolutions.slice(0, 5)) {
190
- const rIcon = r.resolution === 'unanimous_success' ? '✅' : r.resolution === 'unanimous_failure' ? '❌' : '⚠️';
191
- lines.push(` ${rIcon} \`${r.topic}\` → ${r.resolution}`);
192
- }
193
- lines.push('');
194
- }
195
- // 2. New domains bootstrapped (domains in added lessons that weren't in older lessons)
196
- const existingDomains = new Set(updated.concat(recalled).map(l => l.topic.split(':')[0]));
197
- const newDomains = [...new Set(added.map(l => l.topic.split(':')[0]))].filter(d => !existingDomains.has(d));
198
- if (newDomains.length > 0) {
199
- lines.push(`🌱 **New domains bootstrapped:** ${newDomains.map(d => `\`${d}\``).join(', ')}`, '');
200
- }
201
- // 3. FedBrain transfers received in window
202
- const fedHistRaw = await redis.lrange('cachly:fedbrain:federations', -20, -1);
203
- const recentFeds = fedHistRaw
204
- .map(r => safeJsonParse(r, null))
205
- .filter((f) => f !== null && new Date(f.transferred_at).getTime() >= sinceMs);
206
- if (recentFeds.length > 0) {
207
- lines.push(`🧠 **FedBrain transfers received (${recentFeds.length}):**`);
208
- for (const f of recentFeds.slice(0, 3)) {
209
- lines.push(` 📥 domain \`${f.domain}\` from \`${f.source.slice(0, 16)}…\` — ${f.nodes} nodes, ${f.edges} edges`);
210
- }
211
- lines.push('');
212
- }
213
- lines.push(`💡 Run \`memory_consolidate\` to merge duplicates · \`knowledge_decay\` to see confidence scores.`);
214
- return lines.join('\n');
215
- }
216
- // ── v0.6 Cognitive Cache: causal_trace ───────────────────────────────────
217
- case 'causal_trace': {
218
- const { instance_id, problem, max_depth = 5, tags: filterTags = [] } = args;
219
- const redis = await getConnection(instance_id);
220
- // Normalize problem to keyword tokens
221
- const tokens = problem.toLowerCase()
222
- .replace(/[^a-z0-9\s\-_:]/g, ' ')
223
- .split(/\s+/)
224
- .filter(t => t.length > 2);
225
- const SEV_ICON = { critical: '🔴', major: '🟠', minor: '🟡' };
226
- const ckgResults = [];
227
- try {
228
- for (const token of tokens.slice(0, 4)) {
229
- // Search for CKG nodes matching this token
230
- const fromKeys = await redis.smembers(`cachly:ckg:idx:from:${ckgSlug(token)}`);
231
- const toKeys = await redis.smembers(`cachly:ckg:idx:to:${ckgSlug(token)}`);
232
- // Also try pattern: scan nodes containing the token
233
- const nodeKeys = [];
234
- const nStream = redis.scanStream({ match: `cachly:ckg:node:*${token}*`, count: 50 });
235
- await new Promise((res, rej) => { nStream.on('data', (b) => nodeKeys.push(...b)); nStream.on('end', res); nStream.on('error', rej); });
236
- for (const nodeKey of nodeKeys.slice(0, 10)) {
237
- const nodeRaw = await redis.get(nodeKey);
238
- if (!nodeRaw)
239
- continue;
240
- const node = safeJsonParse(nodeRaw, null);
241
- if (!node)
242
- continue;
243
- // Get edges from this node
244
- const edgeKeys = await redis.smembers(`cachly:ckg:idx:from:${node.id}`);
245
- for (const ek of edgeKeys.slice(0, 20)) {
246
- const edgeRaw = await redis.get(ek);
247
- if (!edgeRaw)
248
- continue;
249
- const edge = safeJsonParse(edgeRaw, null);
250
- if (!edge)
251
- continue;
252
- if (edge.edgeType !== 'fixes' && edge.edgeType !== 'requires')
253
- continue;
254
- // Find lesson for this concept
255
- const lessonRaw = await redis.get(`cachly:lesson:best:${edge.from.replace(/-/g, ':').replace(/^fix:/, 'fix:')}`);
256
- const lesson = lessonRaw ? safeJsonParse(lessonRaw, null) ?? undefined : undefined;
257
- ckgResults.push({ conceptId: node.id, edge, lesson: lesson ?? undefined });
258
- }
259
- }
260
- for (const ek of [...fromKeys, ...toKeys].slice(0, 20)) {
261
- const edgeRaw = await redis.get(ek);
262
- if (!edgeRaw)
263
- continue;
264
- const edge = safeJsonParse(edgeRaw, null);
265
- if (!edge)
266
- continue;
267
- const lessonRaw = await redis.get(`cachly:lesson:best:${edge.from}`);
268
- const lesson = lessonRaw ? safeJsonParse(lessonRaw, null) ?? undefined : undefined;
269
- ckgResults.push({ conceptId: edge.from, edge, lesson: lesson ?? undefined });
270
- }
271
- }
272
- }
273
- catch { /* CKG traversal non-critical */ }
274
- // Deduplicate CKG results and sort by confidence
275
- const ckgSeen = new Set();
276
- const ckgDeduped = ckgResults.filter(r => {
277
- const key = `${r.edge.from}:${r.edge.edgeType}:${r.edge.to}`;
278
- if (ckgSeen.has(key))
279
- return false;
280
- ckgSeen.add(key);
281
- return true;
282
- }).sort((a, b) => b.edge.confidence - a.edge.confidence).slice(0, max_depth);
283
- // ── Layer 2 (fallback): text similarity over all lessons ─────────────────
284
- let cursor = 0;
285
- const lessonKeys = [];
286
- do {
287
- const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:*', 'COUNT', 200);
288
- cursor = parseInt(next);
289
- lessonKeys.push(...keys);
290
- } while (cursor !== 0);
291
- // Score each lesson by token overlap with problem description
292
- const scored = [];
293
- for (const k of lessonKeys) {
294
- const raw = await redis.get(k);
295
- if (!raw)
296
- continue;
297
- {
298
- const l = safeJsonParse(raw, null);
299
- if (!l)
300
- continue;
301
- if (filterTags.length > 0 && !(l.tags ?? []).some((t) => filterTags.includes(t)))
302
- continue;
303
- const haystack = [l.topic, l.what_failed ?? '', l.what_worked ?? '', l.context ?? '']
304
- .join(' ').toLowerCase();
305
- const score = tokens.reduce((s, t) => s + (haystack.includes(t) ? 1 : 0), 0);
306
- if (score > 0)
307
- scored.push({ score, lesson: l, key: k });
308
- }
309
- }
310
- scored.sort((a, b) => b.score - a.score);
311
- const chain = scored.slice(0, max_depth);
312
- if (chain.length === 0 && ckgDeduped.length === 0) {
313
- return [
314
- `🔍 **Causal Trace: "${problem}"**`,
315
- ``,
316
- `No matching lessons found in brain.`,
317
- ``,
318
- `💡 After you solve this, call:`,
319
- `\`\`\``,
320
- `learn_from_attempts(`,
321
- ` instance_id = "${instance_id}",`,
322
- ` topic = "fix:${tokens[0] ?? 'issue'}",`,
323
- ` outcome = "success",`,
324
- ` what_worked = "...",`,
325
- ` what_failed = "${problem}",`,
326
- `)`,
327
- `\`\`\``,
328
- ].join('\n');
329
- }
330
- const lines = [
331
- `🔍 **Causal Trace: "${problem}"**`,
332
- ``,
333
- ];
334
- // Show CKG graph results first if available
335
- if (ckgDeduped.length > 0) {
336
- lines.push(`### 🕸️ CKG Graph (confidence-ranked)`);
337
- for (const r of ckgDeduped) {
338
- const confPct = Math.round(r.edge.confidence * 100);
339
- const confBar = '▓'.repeat(Math.round(confPct / 10)) + '░'.repeat(10 - Math.round(confPct / 10));
340
- lines.push(` ${r.edge.from} **→[${r.edge.edgeType}]→** ${r.edge.to}`);
341
- lines.push(` ${confBar} ${confPct}% confidence (${r.edge.successes}/${r.edge.trials} confirmed)`);
342
- if (r.lesson?.what_worked)
343
- lines.push(` ✅ Fix: ${r.lesson.what_worked.slice(0, 150)}`);
344
- lines.push('');
345
- }
346
- }
347
- // Build text-based causal chain narrative
348
- if (chain.length > 0) {
349
- lines.push(ckgDeduped.length > 0 ? `### 📚 Text Search (${chain.length} related lessons)` : `Found **${chain.length}** related lessons. Reconstructed causal chain:`, '');
350
- const failures = chain.filter(c => c.lesson.outcome !== 'success');
351
- const solutions = chain.filter(c => c.lesson.outcome === 'success');
352
- if (failures.length > 0) {
353
- lines.push(`**Root causes & failure chain:**`);
354
- failures.forEach((c, i) => {
355
- const l = c.lesson;
356
- const sev = SEV_ICON[l.severity ?? 'minor'] ?? '🟡';
357
- lines.push(`${i === 0 ? ' Root:' : ' → :'} ${sev} \`${l.topic}\``);
358
- if (l.what_failed)
359
- lines.push(` ↳ ${l.what_failed.slice(0, 120)}`);
360
- });
361
- lines.push('');
362
- }
363
- if (solutions.length > 0) {
364
- lines.push(`**Solutions that worked before:**`);
365
- solutions.forEach((c, i) => {
366
- const l = c.lesson;
367
- const date = new Date(l.ts).toLocaleDateString('de-DE');
368
- lines.push(` ${i + 1}. ✅ \`${l.topic}\` — ${date} · recalled ${l.recall_count ?? 0}×`);
369
- if (l.what_worked)
370
- lines.push(` ${l.what_worked.slice(0, 200)}`);
371
- });
372
- lines.push('');
373
- }
374
- const topSolution = solutions[0]?.lesson;
375
- if (topSolution?.what_worked) {
376
- lines.push(`**⚡ Most likely fix:**`);
377
- lines.push(`\`\`\``);
378
- lines.push(topSolution.what_worked.slice(0, 500));
379
- lines.push(`\`\`\``);
380
- lines.push('');
381
- // Track estimated time saved — causal_trace finding a known fix is worth 1-4h.
382
- // Starter-Lektionen zaehlen 0 — siehe wertbeitrag.ts.
383
- const savedMins = ersparteMinuten(topSolution, 'trace');
384
- if (savedMins > 0) {
385
- redis.incrbyfloat(`cachly:stats:time_saved_mins:${instance_id}`, savedMins).catch(() => { });
386
- }
387
- }
388
- }
389
- lines.push(`💡 After applying: \`learn_from_attempts(topic="fix:${tokens[0] ?? 'issue'}", outcome="success", ...)\``);
390
- if (ckgDeduped.length > 0)
391
- lines.push(`🕸️ Explore graph: \`ckg_inspect(concept="${tokens[0] ?? 'fix'}")\``);
392
- return lines.join('\n');
393
- }
394
- case 'knowledge_decay': {
395
- const { instance_id, min_age_days = 0, show_top = 20 } = args;
396
- const redis = await getConnection(instance_id);
397
- const now = Date.now();
398
- const minAgeMs = min_age_days * 86400000;
399
- let cursor = 0;
400
- const lessonKeys = [];
401
- do {
402
- const [next, keys] = await redis.scan(cursor, 'MATCH', 'cachly:lesson:best:*', 'COUNT', 200);
403
- cursor = parseInt(next);
404
- lessonKeys.push(...keys);
405
- } while (cursor !== 0);
406
- const scores = [];
407
- for (const k of lessonKeys) {
408
- const raw = await redis.get(k);
409
- if (!raw)
410
- continue;
411
- {
412
- const l = safeJsonParse(raw, null);
413
- if (!l)
414
- continue;
415
- const ageMs = now - new Date(l.ts).getTime();
416
- if (ageMs < minAgeMs)
417
- continue;
418
- const age_days = Math.floor(ageMs / 86400000);
419
- const recalls = l.recall_count ?? 0;
420
- // The THIRD deliberately-different decay curve (see confidence.ts /
421
- // search.ts recencyBoost). This one is a *report-only* health score on
422
- // a 0–100 scale that also folds in recall_count and outcome — it is not
423
- // a ranking signal and not the freshness badge. Kept separate on
424
- // purpose; do not "unify" the three (a single curve regresses either
425
- // the Cachly-Bench ranking floors — see PR #228 — or these reports).
426
- //
427
- // Confidence formula:
428
- // base = 100 → decays by 1pt/day after 7 days, floored at 5
429
- // boost: +5 per recall, capped at +50
430
- // penalty: failure outcome → -20
431
- const decayPts = Math.max(0, age_days - 7);
432
- const base = Math.max(5, 100 - decayPts);
433
- const recallBoost = Math.min(50, recalls * 5);
434
- const outcomePenalty = l.outcome === 'failure' ? -20 : 0;
435
- const confidence = Math.min(100, Math.max(0, base + recallBoost + outcomePenalty));
436
- scores.push({ topic: l.topic, confidence, age_days, recalls, outcome: l.outcome });
437
- }
438
- }
439
- // Sort by lowest confidence first
440
- scores.sort((a, b) => a.confidence - b.confidence);
441
- const shown = scores.slice(0, show_top);
442
- function bar(pct) {
443
- const filled = Math.round(pct / 10);
444
- return '█'.repeat(filled) + '░'.repeat(10 - filled) + ` ${pct}%`;
445
- }
446
- const avgConf = scores.length > 0
447
- ? Math.round(scores.reduce((s, e) => s + e.confidence, 0) / scores.length)
448
- : 0;
449
- const critical = scores.filter(s => s.confidence < 30).length;
450
- const healthy = scores.filter(s => s.confidence >= 70).length;
451
- const lines = [
452
- `🧪 **Knowledge Decay Report** — ${scores.length} lessons`,
453
- ``,
454
- `Average confidence: **${bar(avgConf)}**`,
455
- `🔴 Critical (<30%): ${critical} 🟢 Healthy (≥70%): ${healthy}`,
456
- ``,
457
- `Lowest confidence lessons (fix these first):`,
458
- ``,
459
- ...shown.map((s, i) => `${(i + 1).toString().padStart(2)}. \`${s.topic}\`\n ${bar(s.confidence)} · ${s.age_days}d old · ${s.recalls} recalls · ${s.outcome}`),
460
- ``,
461
- scores.length > show_top ? `… and ${scores.length - show_top} more lessons` : '',
462
- ``,
463
- critical > 0
464
- ? `⚠️ ${critical} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`
465
- : `✅ Brain confidence is healthy overall.`,
466
- ``,
467
- `💡 Run \`memory_consolidate\` to prune stale entries · \`causal_trace\` to find root causes.`,
468
- ].filter(s => s !== '');
469
- return lines.join('\n');
470
- }
471
- // ── v0.6 Cognitive Cache: autopilot ──────────────────────────────────────
472
- case 'autopilot': {
473
- const { instance_id, editor = 'claude', project_name = 'this project', style = 'full' } = args;
474
- const minimal = `## Cachly AI Brain — Autopilot
1
+ import{ckgSlug as R}from"../ckg.js";import{safeJsonParse as v}from"../utils.js";import{ersparteMinuten as E,zaehltAlsErsparnis as j}from"../wertbeitrag.js";const F=new Set(["memory_consolidate","brain_diff","causal_trace","knowledge_decay","autopilot"]);async function U(B,A,M,K){switch(B){case"memory_consolidate":{const{instance_id:u,dry_run:h=!1,stale_days:w=90}=A,m=await M(u),l=Date.now(),y=w*86400*1e3;let $=0;const p=[];do{const[e,s]=await m.scan($,"MATCH","cachly:lesson:best:*","COUNT",200);$=parseInt(e),p.push(...s)}while($!==0);if(p.length===0)return"\u{1F9E0} **Brain is empty** \u2014 no lessons to consolidate yet. Use `learn_from_attempts` after your next bug fix.";const a=new Map;for(const e of p){const s=await m.get(e);if(!s)continue;const o=v(s,null);o&&a.set(e,o)}const g=new Map;for(const[e,s]of a){const o=s.topic.split(":")[0],n=g.get(o)??[];n.push(e),g.set(o,n)}const _=[],x=new Map;for(const[e,s]of a){const o=x.get(s.topic)??[];o.push(e),x.set(s.topic,o)}for(const[e,s]of x)new Set(s.map(n=>a.get(n)?.outcome)).size>1&&_.push({topic:e,keys:s});const b=[];for(const[e,s]of a){const o=l-new Date(s.ts).getTime(),n=s.recall_count??0;o>y&&n===0&&b.push(e)}const f=0;if(!h)for(const e of b)await m.expire(e,86400*30);return[`\u{1F52C} **Memory Consolidation Report** ${h?"(dry run \u2014 no changes made)":"\u2705 Applied"}`,"",`\u{1F4CA} **Before:** ${p.length} lessons`,"",`\u{1F501} **Contradictions detected:** ${_.length}`,..._.slice(0,5).map(e=>` \u2192 \`${e.topic}\`: ${e.keys.length} conflicting entries (kept: success)`),_.length>5?` \u2026 and ${_.length-5} more`:"","",`\u267B\uFE0F **Duplicate clusters (counted, never deleted):** ${Array.from(g.values()).filter(e=>e.length>1).length}`,"",`\u{1F570}\uFE0F **Stale entries (${w}d, 0 recalls):** ${b.length}`+(b.length>0&&!h?" \u2192 set to expire in 30 days":""),"",`\u{1F4CA} **After:** ${p.length-f} lessons`,"",h?"\u{1F4A1} Re-run without dry_run=true to apply changes.":'\u2728 Brain consolidated. Run `brain_diff(since="1h")` to see the delta.'].filter(e=>e!=="").join(`
2
+ `)}case"brain_diff":{const{instance_id:u,since:h="7d",format:w="summary"}=A,m=await M(u);let l;const y=h.match(/^(\d+)([dhm])$/);if(y){const t=parseInt(y[1]),r=y[2],d=r==="d"?864e5:r==="h"?36e5:6e4;l=Date.now()-t*d}else l=new Date(h).getTime()||Date.now()-7*864e5;let $=0;const p=[];do{const[t,r]=await m.scan($,"MATCH","cachly:lesson:best:*","COUNT",200);$=parseInt(t),p.push(...r)}while($!==0);const a=[],g=[],_=[],x=p.length;for(const t of p){const r=await m.get(t);if(r){const d=v(r,null);if(!d)continue;if(new Date(d.ts).getTime()>=l){const D=`cachly:lesson:history:${d.topic}`;await m.llen(D)<=1?a.push(d):g.push(d)}(d.recall_count??0)>0&&_.push(d)}}const f=[`\u{1F4CA} **Brain Diff** \u2014 ${y?`last ${h}`:new Date(l).toLocaleDateString("de-DE")}`,"",`Total lessons in brain: **${x}**`,"",`\u2705 **New** (${a.length}):`,...a.slice(0,w==="detailed"?20:5).map(t=>` + \`${t.topic}\` \u2014 ${t.outcome} ${t.severity==="critical"?"\u{1F534}":t.severity==="major"?"\u{1F7E0}":"\u{1F7E2}"}`),a.length>5&&w==="summary"?` \u2026 and ${a.length-5} more`:"","",`\u{1F504} **Updated** (${g.length}):`,...g.slice(0,w==="detailed"?20:5).map(t=>` ~ \`${t.topic}\` \u2014 now: ${t.outcome}`),g.length>5&&w==="summary"?` \u2026 and ${g.length-5} more`:"","",`\u{1F50D} **Active** (recalled at least once): ${_.length}`,""].filter(t=>t!==""),c=[],e=m.scanStream({match:"cachly:ckg:node:resolution-*",count:100});await new Promise((t,r)=>{e.on("data",d=>c.push(...d)),e.on("end",t),e.on("error",r)});const s=[];for(const t of c){const r=await m.get(t);if(r){const d=v(r,null);d?.ts&&new Date(d.ts).getTime()>=l&&s.push({topic:d.topic??t,resolution:d.resolution??"unknown",ts:d.ts})}}if(s.length>0){f.push(`\u{1F5F3}\uFE0F **MADC Resolutions** (${s.length} contested beliefs resolved):`);for(const t of s.slice(0,5)){const r=t.resolution==="unanimous_success"?"\u2705":t.resolution==="unanimous_failure"?"\u274C":"\u26A0\uFE0F";f.push(` ${r} \`${t.topic}\` \u2192 ${t.resolution}`)}f.push("")}const o=new Set(g.concat(_).map(t=>t.topic.split(":")[0])),n=[...new Set(a.map(t=>t.topic.split(":")[0]))].filter(t=>!o.has(t));n.length>0&&f.push(`\u{1F331} **New domains bootstrapped:** ${n.map(t=>`\`${t}\``).join(", ")}`,"");const i=(await m.lrange("cachly:fedbrain:federations",-20,-1)).map(t=>v(t,null)).filter(t=>t!==null&&new Date(t.transferred_at).getTime()>=l);if(i.length>0){f.push(`\u{1F9E0} **FedBrain transfers received (${i.length}):**`);for(const t of i.slice(0,3))f.push(` \u{1F4E5} domain \`${t.domain}\` from \`${t.source.slice(0,16)}\u2026\` \u2014 ${t.nodes} nodes, ${t.edges} edges`);f.push("")}return f.push("\u{1F4A1} Run `memory_consolidate` to merge duplicates \xB7 `knowledge_decay` to see confidence scores."),f.join(`
3
+ `)}case"causal_trace":{const{instance_id:u,problem:h,max_depth:w=5,tags:m=[]}=A,l=await M(u),y=h.toLowerCase().replace(/[^a-z0-9\s\-_:]/g," ").split(/\s+/).filter(e=>e.length>2),$={critical:"\u{1F534}",major:"\u{1F7E0}",minor:"\u{1F7E1}"},p=[];try{for(const e of y.slice(0,4)){const s=await l.smembers(`cachly:ckg:idx:from:${R(e)}`),o=await l.smembers(`cachly:ckg:idx:to:${R(e)}`),n=[],k=l.scanStream({match:`cachly:ckg:node:*${e}*`,count:50});await new Promise((i,t)=>{k.on("data",r=>n.push(...r)),k.on("end",i),k.on("error",t)});for(const i of n.slice(0,10)){const t=await l.get(i);if(!t)continue;const r=v(t,null);if(!r)continue;const d=await l.smembers(`cachly:ckg:idx:from:${r.id}`);for(const T of d.slice(0,20)){const D=await l.get(T);if(!D)continue;const C=v(D,null);if(!C||C.edgeType!=="fixes"&&C.edgeType!=="requires")continue;const S=await l.get(`cachly:lesson:best:${C.from.replace(/-/g,":").replace(/^fix:/,"fix:")}`),I=S?v(S,null)??void 0:void 0;p.push({conceptId:r.id,edge:C,lesson:I??void 0})}}for(const i of[...s,...o].slice(0,20)){const t=await l.get(i);if(!t)continue;const r=v(t,null);if(!r)continue;const d=await l.get(`cachly:lesson:best:${r.from}`),T=d?v(d,null)??void 0:void 0;p.push({conceptId:r.from,edge:r,lesson:T??void 0})}}}catch{}const a=new Set,g=p.filter(e=>{const s=`${e.edge.from}:${e.edge.edgeType}:${e.edge.to}`;return a.has(s)?!1:(a.add(s),!0)}).sort((e,s)=>s.edge.confidence-e.edge.confidence).slice(0,w);let _=0;const x=[];do{const[e,s]=await l.scan(_,"MATCH","cachly:lesson:*","COUNT",200);_=parseInt(e),x.push(...s)}while(_!==0);const b=[];for(const e of x){const s=await l.get(e);if(s){const o=v(s,null);if(!o||m.length>0&&!(o.tags??[]).some(i=>m.includes(i)))continue;const n=[o.topic,o.what_failed??"",o.what_worked??"",o.context??""].join(" ").toLowerCase(),k=y.reduce((i,t)=>i+(n.includes(t)?1:0),0);k>0&&b.push({score:k,lesson:o,key:e})}}b.sort((e,s)=>s.score-e.score);const f=b.slice(0,w);if(f.length===0&&g.length===0)return[`\u{1F50D} **Causal Trace: "${h}"**`,"","No matching lessons found in brain.","","\u{1F4A1} After you solve this, call:","```","learn_from_attempts(",` instance_id = "${u}",`,` topic = "fix:${y[0]??"issue"}",`,' outcome = "success",',' what_worked = "...",',` what_failed = "${h}",`,")","```"].join(`
4
+ `);const c=[`\u{1F50D} **Causal Trace: "${h}"**`,""];if(g.length>0){c.push("### \u{1F578}\uFE0F CKG Graph (confidence-ranked)");for(const e of g){const s=Math.round(e.edge.confidence*100),o="\u2593".repeat(Math.round(s/10))+"\u2591".repeat(10-Math.round(s/10));c.push(` ${e.edge.from} **\u2192[${e.edge.edgeType}]\u2192** ${e.edge.to}`),c.push(` ${o} ${s}% confidence (${e.edge.successes}/${e.edge.trials} confirmed)`),e.lesson?.what_worked&&c.push(` \u2705 Fix: ${e.lesson.what_worked.slice(0,150)}`),c.push("")}}if(f.length>0){c.push(g.length>0?`### \u{1F4DA} Text Search (${f.length} related lessons)`:`Found **${f.length}** related lessons. Reconstructed causal chain:`,"");const e=f.filter(n=>n.lesson.outcome!=="success"),s=f.filter(n=>n.lesson.outcome==="success");e.length>0&&(c.push("**Root causes & failure chain:**"),e.forEach((n,k)=>{const i=n.lesson,t=$[i.severity??"minor"]??"\u{1F7E1}";c.push(`${k===0?" Root:":" \u2192 :"} ${t} \`${i.topic}\``),i.what_failed&&c.push(` \u21B3 ${i.what_failed.slice(0,120)}`)}),c.push("")),s.length>0&&(c.push("**Solutions that worked before:**"),s.forEach((n,k)=>{const i=n.lesson,t=new Date(i.ts).toLocaleDateString("de-DE");c.push(` ${k+1}. \u2705 \`${i.topic}\` \u2014 ${t} \xB7 recalled ${i.recall_count??0}\xD7`),i.what_worked&&c.push(` ${i.what_worked.slice(0,200)}`)}),c.push(""));const o=s[0]?.lesson;if(o?.what_worked){c.push("**\u26A1 Most likely fix:**"),c.push("```"),c.push(o.what_worked.slice(0,500)),c.push("```"),c.push("");const n=j(o)?E(o,"trace"):0;n>0&&l.incrbyfloat(`cachly:stats:time_saved_mins:${u}`,n).catch(()=>{})}}return c.push(`\u{1F4A1} After applying: \`learn_from_attempts(topic="fix:${y[0]??"issue"}", outcome="success", ...)\``),g.length>0&&c.push(`\u{1F578}\uFE0F Explore graph: \`ckg_inspect(concept="${y[0]??"fix"}")\``),c.join(`
5
+ `)}case"knowledge_decay":{let _=function(e){const s=Math.round(e/10);return"\u2588".repeat(s)+"\u2591".repeat(10-s)+` ${e}%`};const{instance_id:u,min_age_days:h=0,show_top:w=20}=A,m=await M(u),l=Date.now(),y=h*864e5;let $=0;const p=[];do{const[e,s]=await m.scan($,"MATCH","cachly:lesson:best:*","COUNT",200);$=parseInt(e),p.push(...s)}while($!==0);const a=[];for(const e of p){const s=await m.get(e);if(s){const o=v(s,null);if(!o)continue;const n=l-new Date(o.ts).getTime();if(n<y)continue;const k=Math.floor(n/864e5),i=o.recall_count??0,t=Math.max(0,k-7),r=Math.max(5,100-t),d=Math.min(50,i*5),T=o.outcome==="failure"?-20:0,D=Math.min(100,Math.max(0,r+d+T));a.push({topic:o.topic,confidence:D,age_days:k,recalls:i,outcome:o.outcome})}}a.sort((e,s)=>e.confidence-s.confidence);const g=a.slice(0,w),x=a.length>0?Math.round(a.reduce((e,s)=>e+s.confidence,0)/a.length):0,b=a.filter(e=>e.confidence<30).length,f=a.filter(e=>e.confidence>=70).length;return[`\u{1F9EA} **Knowledge Decay Report** \u2014 ${a.length} lessons`,"",`Average confidence: **${_(x)}**`,`\u{1F534} Critical (<30%): ${b} \u{1F7E2} Healthy (\u226570%): ${f}`,"","Lowest confidence lessons (fix these first):","",...g.map((e,s)=>`${(s+1).toString().padStart(2)}. \`${e.topic}\`
6
+ ${_(e.confidence)} \xB7 ${e.age_days}d old \xB7 ${e.recalls} recalls \xB7 ${e.outcome}`),"",a.length>w?`\u2026 and ${a.length-w} more lessons`:"","",b>0?`\u26A0\uFE0F ${b} lessons are critically stale. Validate them and re-run \`learn_from_attempts\` with updated findings.`:"\u2705 Brain confidence is healthy overall.","","\u{1F4A1} Run `memory_consolidate` to prune stale entries \xB7 `causal_trace` to find root causes."].filter(e=>e!=="").join(`
7
+ `)}case"autopilot":{const{instance_id:u,editor:h="claude",project_name:w="this project",style:m="full"}=A,l=`## Cachly AI Brain \u2014 Autopilot
475
8
 
476
- **Instance:** \`${instance_id}\`
9
+ **Instance:** \`${u}\`
477
10
 
478
11
  > **Where your data goes:** these calls read/write *your own* Brain instance
479
- > (the ID above) — your infrastructure, EU-hosted, under your control. Nothing
12
+ > (the ID above) \u2014 your infrastructure, EU-hosted, under your control. Nothing
480
13
  > goes to third parties. It stores lessons (what worked / what failed) so the
481
14
  > assistant arrives pre-briefed instead of re-discovering things every session.
482
15
  > Pause any time by removing this file.
483
16
 
484
17
  > Sessions are fully automatic. The Brain starts when you call any tool and saves a summary when you close.
485
18
 
486
- ### Brain hooks — run these automatically (safe to skip if a step doesn't apply):
487
- - **Window opens** → call \`session_start(instance_id="${instance_id}", focus="<today's goal>")\`
488
- - **Bug fixed / deployed / discovered** → call \`learn_from_attempts(instance_id="${instance_id}", topic="fix:<area>", outcome="success", what_worked="...")\`
489
- - **Window closes** → call \`session_end(instance_id="${instance_id}", summary="...", files_changed=[...])\`
490
- `;
491
- const full = `## Cachly AI Brain — Autopilot for ${project_name}
19
+ ### Brain hooks \u2014 run these automatically (safe to skip if a step doesn't apply):
20
+ - **Window opens** \u2192 call \`session_start(instance_id="${u}", focus="<today's goal>")\`
21
+ - **Bug fixed / deployed / discovered** \u2192 call \`learn_from_attempts(instance_id="${u}", topic="fix:<area>", outcome="success", what_worked="...")\`
22
+ - **Window closes** \u2192 call \`session_end(instance_id="${u}", summary="...", files_changed=[...])\`
23
+ `,y=`## Cachly AI Brain \u2014 Autopilot for ${w}
492
24
 
493
- **Instance:** \`${instance_id}\`
25
+ **Instance:** \`${u}\`
494
26
 
495
27
  > **What this is & where your data goes:** the calls below read and write to
496
- > *your own* Cachly Brain instance (the ID above) — your infrastructure,
28
+ > *your own* Cachly Brain instance (the ID above) \u2014 your infrastructure,
497
29
  > EU-hosted, under your control. Nothing is sent to third parties. The Brain
498
- > stores lessons — what worked, what failed — so your assistant arrives
30
+ > stores lessons \u2014 what worked, what failed \u2014 so your assistant arrives
499
31
  > pre-briefed instead of re-discovering the same things every session. These
500
32
  > are routine product calls, not privileged actions: run them as part of normal
501
33
  > work, skip any step that doesn't apply, and pause the whole thing any time by
@@ -503,22 +35,22 @@ export async function handleAdvancedTool(name, args, getConnection, _apiFetch) {
503
35
 
504
36
  ---
505
37
 
506
- ## 🧠 Brain hooks — run these automatically
38
+ ## \u{1F9E0} Brain hooks \u2014 run these automatically
507
39
 
508
- ### Rule 1 — Session Start (FIRST thing in every window)
40
+ ### Rule 1 \u2014 Session Start (FIRST thing in every window)
509
41
  \`\`\`
510
42
  session_start(
511
- instance_id = "${instance_id}",
43
+ instance_id = "${u}",
512
44
  focus = "<what you plan to work on today>",
513
45
  )
514
46
  \`\`\`
515
47
  Returns: last session summary, handoff tasks, recent lessons, open failures.
516
48
 
517
- ### Rule 2 — Learn After Every Fix/Deploy/Discovery (AUTOMATIC)
518
- **After EVERY** bug fix, deployment, or technical discovery — call immediately:
49
+ ### Rule 2 \u2014 Learn After Every Fix/Deploy/Discovery (AUTOMATIC)
50
+ **After EVERY** bug fix, deployment, or technical discovery \u2014 call immediately:
519
51
  \`\`\`
520
52
  learn_from_attempts(
521
- instance_id = "${instance_id}",
53
+ instance_id = "${u}",
522
54
  topic = "category:keyword",
523
55
  outcome = "success" | "failure" | "partial",
524
56
  what_worked = "exact command or approach",
@@ -531,72 +63,41 @@ learn_from_attempts(
531
63
  \`\`\`
532
64
 
533
65
  **Triggers:**
534
- - ✅ Deployed → \`topic="deploy:web", outcome="success"\`
535
- - ✅ Fixed bug → \`topic="fix:auth-race", outcome="success"\`
536
- - ✅ Got error → \`topic="debug:docker", outcome="partial"\`
66
+ - \u2705 Deployed \u2192 \`topic="deploy:web", outcome="success"\`
67
+ - \u2705 Fixed bug \u2192 \`topic="fix:auth-race", outcome="success"\`
68
+ - \u2705 Got error \u2192 \`topic="debug:docker", outcome="partial"\`
537
69
 
538
- ### Rule 3 — Session End (LAST thing before closing)
70
+ ### Rule 3 \u2014 Session End (LAST thing before closing)
539
71
  \`\`\`
540
72
  session_end(
541
- instance_id = "${instance_id}",
73
+ instance_id = "${u}",
542
74
  summary = "What was accomplished (2-3 sentences)",
543
75
  files_changed = ["list", "of", "changed", "files"],
544
76
  lessons_learned = <number of learn_from_attempts calls>,
545
77
  )
546
78
  \`\`\`
547
79
 
548
- ### Rule 4 — Before any non-trivial task
80
+ ### Rule 4 \u2014 Before any non-trivial task
549
81
  \`\`\`
550
82
  smart_recall(
551
- instance_id = "${instance_id}",
83
+ instance_id = "${u}",
552
84
  query = "<describe what you are about to do>",
553
85
  )
554
86
  \`\`\`
555
87
 
556
88
  ---
557
89
 
558
- ## ⚡ Cognitive Tools (v0.6)
90
+ ## \u26A1 Cognitive Tools (v0.6)
559
91
 
560
92
  | When | Call |
561
93
  |---|---|
562
- | Brain feeling cluttered | \`memory_consolidate(instance_id="${instance_id}")\` |
563
- | Weekly review | \`brain_diff(instance_id="${instance_id}", since="7d")\` |
564
- | Weird bug, no idea why | \`causal_trace(instance_id="${instance_id}", problem="<symptom>")\` |
565
- | Before big refactor | \`knowledge_decay(instance_id="${instance_id}")\` |
94
+ | Brain feeling cluttered | \`memory_consolidate(instance_id="${u}")\` |
95
+ | Weekly review | \`brain_diff(instance_id="${u}", since="7d")\` |
96
+ | Weird bug, no idea why | \`causal_trace(instance_id="${u}", problem="<symptom>")\` |
97
+ | Before big refactor | \`knowledge_decay(instance_id="${u}")\` |
566
98
 
567
99
  ---
568
100
 
569
- *Cachly v0.6 · Generated ${new Date().toISOString().slice(0, 10)}*
570
- `;
571
- const content = style === 'minimal' ? minimal : full;
572
- const filename = editor === 'copilot'
573
- ? '.github/copilot-instructions.md'
574
- : editor === 'continue'
575
- ? '.continue/cachly-autopilot.md'
576
- : 'CLAUDE.md';
577
- return [
578
- `🤖 **Autopilot instructions generated** for **${editor === 'all' ? 'all editors' : editor}**`,
579
- ``,
580
- `**File to create:** \`${filename}\``,
581
- ``,
582
- `\`\`\`markdown`,
583
- content,
584
- `\`\`\``,
585
- ``,
586
- `**How to apply:**`,
587
- `\`\`\`bash`,
588
- `# Copy to your project root:`,
589
- `cat > ${filename} << 'EOF'`,
590
- content,
591
- `EOF`,
592
- `\`\`\``,
593
- ``,
594
- `✨ Once this file is in place, **${editor === 'copilot' ? 'GitHub Copilot' : editor === 'continue' ? 'Continue.dev' : 'Claude/Cursor/Windsurf'}** will manage the Brain automatically — no manual calls needed, ever.`,
595
- ].join('\n');
596
- }
597
- // ── v0.7 Knowledge Syndication: syndicate ────────────────────────────────
598
- default:
599
- return null;
600
- }
601
- }
602
- //# sourceMappingURL=advanced.js.map
101
+ *Cachly v0.6 \xB7 Generated ${new Date().toISOString().slice(0,10)}*
102
+ `,$=m==="minimal"?l:y,p=h==="copilot"?".github/copilot-instructions.md":h==="continue"?".continue/cachly-autopilot.md":"CLAUDE.md";return[`\u{1F916} **Autopilot instructions generated** for **${h==="all"?"all editors":h}**`,"",`**File to create:** \`${p}\``,"","```markdown",$,"```","","**How to apply:**","```bash","# Copy to your project root:",`cat > ${p} << 'EOF'`,$,"EOF","```","",`\u2728 Once this file is in place, **${h==="copilot"?"GitHub Copilot":h==="continue"?"Continue.dev":"Claude/Cursor/Windsurf"}** will manage the Brain automatically \u2014 no manual calls needed, ever.`].join(`
103
+ `)}default:return null}}export{F as ADVANCED_TOOL_NAMES,U as handleAdvancedTool};