forked from Ikalus1988/MisakaNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
711 lines (651 loc) · 33.6 KB
/
Copy pathindex.html
File metadata and controls
711 lines (651 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Search 249 indexed failure-recovery lessons from real AI agent debugging sessions. DCO, GitHub token, pip timeout, database locked, and more.">
<link rel="canonical" href="https://misakanet.org/search/">
<meta property="og:title" content="Search Failure Lessons — MisakaNet">
<meta property="og:description" content="Search 249 indexed failure-recovery lessons from real AI agent debugging sessions.">
<meta property="og:url" content="https://misakanet.org/search/">
<title>Search Verified Failure Lessons — MisakaNet</title>
<style>
:root {
--font-ui: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", "Helvetica Neue", Arial, sans-serif;
--font-mono: "JetBrains Mono", "Fira Code", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
--text-main: rgba(255,255,255,0.88);
--text-soft: rgba(255,255,255,0.72);
--text-muted: rgba(255,255,255,0.64);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: var(--font-ui); background: radial-gradient(circle at 50% -20%, rgba(88,166,255,0.09), transparent 38%), #0a0f1d; color: var(--text-main); min-height: 100vh; }
.container { max-width: 720px; margin: 0 auto; padding: 40px 20px; }
.topbar { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 4px; }
h1 { font-family: var(--font-ui); font-size: 24px; font-weight: 700; margin-bottom: 4px; }
.subtitle { color: var(--text-soft); font-size: 15px; line-height: 1.55; margin-bottom: 24px; }
.lang-switch { display: flex; gap: 6px; flex-shrink: 0; margin-top: 2px; }
.lang-switch button { background: transparent; color: var(--text-muted); border: 1px solid rgba(255,255,255,0.12); border-radius: 7px; padding: 4px 10px; cursor: pointer; font-size: 12px; font-family: var(--font-ui); }
.lang-switch button.active { color: #58a6ff; border-color: rgba(88,166,255,0.42); background: rgba(88,166,255,0.08); }
.home-link { display: inline-block; color: var(--text-muted); font-size: 13px; text-decoration: none; margin-bottom: 8px; transition: color 0.15s; }
.home-link:hover { color: #58a6ff; }
.search-box { position: relative; margin-bottom: 16px; background: rgba(255,255,255,0.035); border: 1px solid rgba(88,166,255,0.24); border-radius: 14px; box-shadow: 0 0 0 1px rgba(88,166,255,0.04); transition: border-color 0.2s, box-shadow 0.2s; }
.search-box:focus-within { border-color: rgba(88,166,255,0.62); background: rgba(88,166,255,0.06); box-shadow: 0 0 18px rgba(88,166,255,0.12); }
.search-box input { width: 100%; padding: 15px 16px; background: transparent; border: 0; color: var(--text-main); font-size: 15px; font-family: var(--font-ui); outline: none; }
.search-box input::placeholder { color: rgba(255,255,255,0.56); }
.stats { font-size: 13px; color: var(--text-muted); margin-bottom: 20px; }
.results-header { font-size: 13px; color: var(--text-soft); margin-bottom: 12px; }
.result { padding: 16px; background: rgba(255,255,255,0.025); border: 1px solid rgba(88,166,255,0.12); border-radius: 10px; margin-bottom: 10px; cursor: pointer; transition: border-color 0.15s, box-shadow 0.15s; box-shadow: 0 8px 28px rgba(0,0,0,0.22); }
.result:hover { border-color: rgba(88,166,255,0.35); }
.result-title { font-family: var(--font-ui); font-size: 16px; line-height: 1.35; font-weight: 700; color: var(--text-main); margin-bottom: 4px; }
.result-meta { display: flex; gap: 8px; align-items: center; margin-bottom: 6px; flex-wrap: wrap; }
.badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; font-weight: 600; font-family: var(--font-ui); }
.badge-domain { background: rgba(88,166,255,0.1); color: #58a6ff; }
.badge-status { background: rgba(35,134,54,0.15); color: #3fb950; }
.badge-fatal { background: rgba(239,68,68,0.12); color: #f87171; }
.badge-runtime { background: rgba(251,146,60,0.12); color: #fb923c; }
.badge-setup { background: rgba(56,189,248,0.12); color: #38bdf8; }
.badge-high { background: rgba(35,134,54,0.15); color: #3fb950; }
.badge-medium { background: rgba(251,146,60,0.12); color: #fb923c; }
.badge-low { background: rgba(139,148,158,0.12); color: #8b949e; }
.badge-evidence { background: rgba(163,113,247,0.14); color: #a371f7; cursor: help; }
.section-label { font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 8px; }
.fold-toggle { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; font-size: 13px; color: var(--text-muted); background: transparent; border: 1px solid rgba(255,255,255,0.08); border-radius: 6px; padding: 6px 12px; margin: 8px 0; transition: color 0.15s, border-color 0.15s; }
.fold-toggle:hover { color: #58a6ff; border-color: rgba(88,166,255,0.3); }
.fold-toggle .arrow { transition: transform 0.2s; }
.fold-toggle.open .arrow { transform: rotate(90deg); }
.match-explain { font-size: 11px; color: var(--text-muted); margin-top: 4px; line-height: 1.5; }
.result-id { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.02em; color: var(--text-muted); }
.result-summary { font-family: var(--font-ui); font-size: 13px; color: var(--text-soft); font-weight: 400; line-height: 1.65; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.result-tags { font-size: 11px; color: var(--text-muted); margin-top: 6px; }
.result-actions { display: flex; gap: 12px; align-items: center; margin-top: 10px; }
.btn-primary { font-family: var(--font-ui); font-size: 12px; font-weight: 600; color: #0d1117; background: #58a6ff; border: none; border-radius: 6px; padding: 6px 14px; cursor: pointer; text-decoration: none; display: inline-block; }
.btn-primary:hover { opacity: 0.9; }
.btn-secondary { font-family: var(--font-ui); font-size: 12px; color: var(--text-soft); background: transparent; border: 1px solid #30363d; border-radius: 6px; padding: 6px 14px; cursor: pointer; text-decoration: none; display: inline-block; }
.btn-secondary:hover { border-color: #58a6ff; color: #58a6ff; }
.feedback-bar { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
.feedback-btn { font-family: var(--font-ui); font-size: 11px; color: var(--text-muted); background: transparent; border: 1px solid rgba(255,255,255,0.08); border-radius: 5px; padding: 3px 8px; cursor: pointer; transition: color 0.15s, border-color 0.15s, background 0.15s; }
.feedback-btn:hover { color: #58a6ff; border-color: rgba(88,166,255,0.3); }
.feedback-btn.selected { color: #3fb950; border-color: rgba(35,134,54,0.4); background: rgba(35,134,54,0.08); pointer-events: none; }
.feedback-summary { display: flex; gap: 12px; align-items: center; justify-content: center; padding: 12px; margin-top: 16px; border-top: 1px solid #21262d; font-size: 12px; color: var(--text-muted); }
.feedback-summary a { color: #58a6ff; text-decoration: none; }
.feedback-summary a:hover { text-decoration: underline; }
.lesson-preview { margin-top: 12px; padding: 12px; border: 1px solid rgba(88,166,255,0.16); border-radius: 8px; background: #0b1020; cursor: default; }
.lesson-preview h2 { font-family: var(--font-ui); font-size: 15px; font-weight: 700; color: var(--text-main); margin: 18px 0 8px; }
.lesson-preview h3 { font-family: var(--font-ui); font-size: 13px; font-weight: 600; color: var(--text-main); margin: 14px 0 6px; }
.lesson-preview pre { background: #0b0f14; border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 12px; overflow-x: auto; white-space: pre-wrap; word-break: break-word; font-family: var(--font-mono); font-size: 12px; line-height: 1.65; color: #c9d1d9; }
.lesson-preview code { font-family: var(--font-mono); }
.lesson-preview p code { background: rgba(255,255,255,0.08); padding: 2px 5px; border-radius: 4px; }
.lesson-preview p { margin: 6px 0; line-height: 1.65; }
.preview-status { font-size: 12px; color: var(--text-soft); }
.fallback { padding: 24px; text-align: center; color: var(--text-soft); }
.fallback a { color: #58a6ff; text-decoration: none; }
.fallback a:hover { text-decoration: underline; }
.loading { text-align: center; color: var(--text-muted); padding: 40px; }
.footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #21262d; }
.footer a { color: #58a6ff; text-decoration: none; font-size: 13px; margin: 0 8px; }
</style>
</head>
<body>
<div class="container">
<div class="topbar">
<div>
<a href="/" class="home-link" data-i18n="goHome">← Go to homepage</a>
<h1 data-i18n="heading">Search Verified Failure Lessons</h1>
<p class="subtitle" data-i18n="subtitle">Reviewed fixes from real agent debugging sessions. Not random chat logs.</p>
</div>
<div class="lang-switch" aria-label="Language">
<button type="button" data-lang="zh">中</button>
<button type="button" data-lang="en">EN</button>
</div>
</div>
<div class="search-box">
<input type="text" id="q" data-i18n-placeholder="placeholder" placeholder="Search lessons... (e.g., pip timeout, database locked, profinet)" autofocus>
</div>
<div class="stats" id="stats"></div>
<div id="results" class="loading">Loading lessons...</div>
<div id="feedback-summary" class="feedback-summary" hidden></div>
<div style="text-align:center; margin-top:24px; font-size:12px; color:var(--text-muted);">
Did a lesson help you? <a href="https://github.com/Ikalus1988/MisakaNet/issues/new?template=lesson-feedback.yml" style="color:#58a6ff;">Share feedback</a> (5 lines, anonymous OK)
</div>
</div>
<script>
const I18N = {
en: {
pageTitle: 'Search Verified Failure Lessons — MisakaNet',
heading: 'Search Verified Failure Lessons',
subtitle: 'Reviewed fixes from real agent debugging sessions. Not random chat logs.',
placeholder: 'Search lessons... (e.g., pip timeout, database locked, profinet)',
loading: 'Loading lessons...',
stats: '{count} searchable lessons · {total} total · zero-dep · GitHub-audited',
resultsHeader: 'Found {count} lessons for "{q}"',
resultsStats: '{count} searchable lessons · {total} total · static JSON · GitHub-audited',
noMatchPrefix: 'No exact match for',
noMatchSuffix: 'Try a broader term.',
installSkill: 'Install agent skill',
submitLesson: 'Submit a lesson',
readLesson: 'Read lesson',
collapse: 'Collapse',
openGitHub: 'Open on GitHub',
loadingPreview: 'Loading lesson preview...',
clipped: '... (open on GitHub for full lesson)',
noPreview: 'No preview body found. Open on GitHub for the full lesson.',
previewUnavailable: 'Preview unavailable. Use "Open on GitHub" for the full lesson.',
loadFailed: 'Failed to load lessons.',
goHome: 'Go to homepage',
feedbackIrrelevant: 'Irrelevant',
feedbackTooBasic: 'Too basic',
feedbackHelpful: 'Helpful',
feedbackRecorded: '{count} feedback recorded',
feedbackCopy: 'Copy feedback',
feedbackSubmit: 'Open GitHub issue',
badgeFatal: 'Fatal Pitfall',
badgeRuntime: 'Runtime Failure',
badgeSetup: 'Setup Fix',
badgeVerified: 'Verified',
githubAudited: 'GitHub-audited'
},
zh: {
pageTitle: '搜索已验证失败教训 — MisakaNet',
heading: '搜索已验证失败教训',
subtitle: '来自真实 AI Agent 调试会话的已审核修复,不是随机聊天记录。',
placeholder: '搜索 DCO、GitHub token、pip timeout、database locked...',
loading: '正在加载 lessons...',
stats: '{count} 条可搜索 lessons · {total} 条总计 · 零依赖 · GitHub 审核',
resultsHeader: '为”{q}”找到 {count} 条 lesson',
resultsStats: '{count} 条可搜索 lessons · {total} 条总计 · 静态 JSON · GitHub 审核',
noMatchPrefix: '没有精确匹配',
noMatchSuffix: '可以试试更宽泛的关键词。',
installSkill: '安装 agent skill',
submitLesson: '提交 lesson',
readLesson: '阅读 lesson',
collapse: '收起',
openGitHub: '在 GitHub 打开',
loadingPreview: '正在加载 lesson 预览...',
clipped: '...(完整 lesson 请在 GitHub 打开)',
noPreview: '没有可预览正文。请在 GitHub 打开完整 lesson。',
previewUnavailable: '预览不可用。请使用“在 GitHub 打开”查看完整 lesson。',
loadFailed: 'Lessons 加载失败。',
goHome: '回到首页',
feedbackIrrelevant: '无关',
feedbackTooBasic: '太基础',
feedbackHelpful: '有帮助',
feedbackRecorded: '已记录 {count} 条反馈',
feedbackCopy: '复制反馈',
feedbackSubmit: '提交到 GitHub',
badgeFatal: '致命踩坑',
badgeRuntime: '运行失败',
badgeSetup: '配置修复',
badgeVerified: '已验证',
githubAudited: 'GitHub 审核'
}
};
const LESSONS_URL = "../data/lessons.json";
const RAW_BASE = "https://raw.githubusercontent.com/Ikalus1988/MisakaNet/main/";
let _lessons = null;
let _lastResults = [];
const _previewCache = new Map();
let LANG = localStorage.getItem('misakanet-lang') || localStorage.getItem('misaka_lang') || (navigator.language.startsWith('zh') ? 'zh' : 'en');
function t(key, vars = {}) {
let value = (I18N[LANG] && I18N[LANG][key]) || I18N.en[key] || key;
Object.keys(vars).forEach(name => {
value = value.split('{' + name + '}').join(String(vars[name]));
});
return value;
}
function updateStats() {
if (!_lessons) return;
const searchable = _lessons.filter(isSearchable).length;
const total = _lessons.length;
document.getElementById('stats').textContent = t('stats', { count: searchable, total });
}
function setLang(lang) {
LANG = lang === 'zh' ? 'zh' : 'en';
localStorage.setItem('misakanet-lang', LANG);
document.documentElement.lang = LANG === 'zh' ? 'zh-CN' : 'en';
document.title = t('pageTitle');
document.querySelectorAll('[data-i18n]').forEach(el => {
el.textContent = t(el.dataset.i18n);
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
el.placeholder = t(el.dataset.i18nPlaceholder);
});
document.querySelectorAll('[data-lang]').forEach(btn => {
btn.classList.toggle('active', btn.dataset.lang === LANG);
});
if (!_lessons) {
document.getElementById('results').textContent = t('loading');
return;
}
updateStats();
const q = document.getElementById('q').value.trim();
if (q) render(_lastResults, q);
}
function escapeHTML(value) {
return String(value || '').replace(/[&<>"']/g, ch => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[ch]));
}
function getLessonUrl(lesson) {
const raw = lesson && (lesson.url || lesson.path || '');
if (!raw) return 'https://github.com/Ikalus1988/MisakaNet/tree/main/lessons';
if (/^https?:\/\//i.test(raw)) return raw;
return 'https://github.com/Ikalus1988/MisakaNet/blob/main/' + encodeURI(String(raw).replace(/^\/+/, ''));
}
function getLessonPath(lesson) {
const raw = lesson && (lesson.url || lesson.path || '');
if (!raw) return '';
if (!/^https?:\/\//i.test(raw)) return String(raw).replace(/^\/+/, '');
try {
const url = new URL(raw);
let match = url.pathname.match(/\/Ikalus1988\/MisakaNet\/(?:blob|raw)\/main\/(.+)$/);
if (!match) match = url.pathname.match(/\/Ikalus1988\/MisakaNet\/main\/(.+)$/);
return match ? decodeURIComponent(match[1]) : '';
} catch (e) {
return '';
}
}
function getRawLessonUrl(lesson) {
const path = getLessonPath(lesson);
return path ? RAW_BASE + encodeURI(path) : getLessonUrl(lesson);
}
function stripFrontmatter(markdown) {
return String(markdown || '')
.replace(/^\uFEFF?---\s*\r?\n[\s\S]*?\r?\n---\s*\r?\n?/, '')
.trim();
}
function isSearchable(l) {
const text = ((l.title||'') + ' ' + (l.summary||'')).toLowerCase();
const junk = ['context compaction','earlier turns','poc record','mojibake','bot reply'];
return !junk.some(k => text.includes(k)) && (l.title||'').trim();
}
function search(q) {
if (!q || !_lessons) return [];
const tokens = q.toLowerCase().split(/\s+/).filter(Boolean);
return _lessons.filter(isSearchable).map(l => {
const title = (l.title||'').toLowerCase();
const domain = (l.domain||'').toLowerCase();
const summary = (l.summary||'').toLowerCase();
const tags = (l.tags||[]).join(' ').toLowerCase();
const full = title + ' ' + domain + ' ' + summary + ' ' + tags;
let score = tokens.filter(t => full.includes(t)).length / tokens.length;
if (tokens.some(t => title.includes(t))) score += 0.3;
if (tokens.some(t => tags.includes(t))) score += 0.15;
if (tokens.some(t => domain.includes(t))) score += 0.1;
return { ...l, score };
}).filter(l => l.score > 0).sort((a,b) => b.score - a.score).slice(0, 20);
}
function updateUrl(q, lessonId) {
const url = new URL(location);
if (q) url.searchParams.set('q', q);
else url.searchParams.delete('q');
if (lessonId) url.searchParams.set('lesson', lessonId);
else url.searchParams.delete('lesson');
history.replaceState(null, '', url);
}
function getTakeaway(r) {
// First complete sentence from summary, fallback to title
const s = r.summary || '';
const match = s.match(/^[^.!?。!?]+[.!?。!?]/);
const takeaway = match ? match[0].trim() : s.slice(0, 120);
return takeaway || r.title || '';
}
function inferBadge(r) {
const text = ((r.title||'') + ' ' + (r.summary||'') + ' ' + (r.tags||[]).join(' ')).toLowerCase();
if (/delete|drop|clear|overwrite|corrupt|destroy|清空|覆盖|丢数据/.test(text)) return { key: 'badgeFatal', cls: 'badge-fatal' };
if (/timeout|locked|rate.limit|429|403|oom|crash|崩溃|超时|锁定/.test(text)) return { key: 'badgeRuntime', cls: 'badge-runtime' };
if (/setup|config|install|deploy|初始化|配置|安装/.test(text)) return { key: 'badgeSetup', cls: 'badge-setup' };
return { key: 'badgeVerified', cls: 'badge-status' };
}
// ── Evidence levels (#786) — see docs/trust-semantics.md ──
const EVIDENCE_LABELS = {
E0: 'E0 — contributor self-reported',
E1: 'E1 — maintainer reviewed',
E2: 'E2 — local smoke reproduced',
E3: 'E3 — CI / sandbox verified recovery',
E4: 'E4 — reused by another contributor or agent',
};
// Missing or unknown values read as E0: evidence is never assumed.
function evidenceInfo(level) {
const key = String(level || '').trim().toUpperCase();
const normalized = EVIDENCE_LABELS[key] ? key : 'E0';
return { level: normalized, label: EVIDENCE_LABELS[normalized] };
}
// ── Client-side confidence / result_type classification ──
const ACTIONABLE_RE = /fix|solution|workaround|step\s*\d|verify|verification|error.code|exit.code|```|pip install|git |curl |chmod|mkdir|export /i;
const COMMON_RE = /github.com.*443|connectivity|checklist|basic|intro|overview|getting.started|quick.start|faq|troubleshooting.general|network.*basics|git.*basics|config.*general/i;
const ERROR_CODE_RE = /GH\d{3,4}|E\d{3,5}|INTP-\d+|KL-\d+|exit\s+(?:code|status)\s+\d+|HTTP\s+\d{3}/i;
function classifyResult(r, score) {
const title = (r.title || '').toLowerCase();
const summary = (r.summary || '').toLowerCase();
const tags = (r.tags || []).join(' ').toLowerCase();
const content = title + ' ' + summary + ' ' + tags;
const hasErrorCode = ERROR_CODE_RE.test(r.title + ' ' + (r.summary || '').slice(0, 300));
const hasActionable = ACTIONABLE_RE.test(r.summary || '');
const hasVerification = /## verification|## verify/i.test(r.summary || '');
const isCommon = COMMON_RE.test(title + ' ' + summary.slice(0, 300));
const highScore = score >= 0.6;
const lowScore = score < 0.35;
// Confidence
let confidence = 'medium';
if ((hasErrorCode && score > 0.4) || (hasVerification && hasActionable && highScore)) {
confidence = 'high';
} else if ((isCommon && lowScore) || (score < 0.25 && !hasActionable)) {
confidence = 'low';
}
// Result type
let resultType = 'related';
if (confidence === 'low') resultType = 'common';
else if (confidence === 'high' || (confidence === 'medium' && hasActionable)) resultType = 'actionable';
return { confidence, resultType };
}
// ── Feedback system (localStorage MVP) ──
const FEEDBACK_KEY = 'misakanet-search-feedback';
function getFeedbackStore() {
try { return JSON.parse(localStorage.getItem(FEEDBACK_KEY) || '[]'); } catch { return []; }
}
function saveFeedback(entry) {
const store = getFeedbackStore();
store.push(entry);
localStorage.setItem(FEEDBACK_KEY, JSON.stringify(store));
updateFeedbackSummary();
}
function getFeedbackForLesson(lessonId, query) {
return getFeedbackStore().find(f => f.lesson_id === lessonId && f.query === query);
}
const FEEDBACK_API = window.location.origin + '/api/feedback';
const SEARCH_SIGNAL_API = window.location.origin + '/api/search-signal';
// Unsolved failure map (#788). Only searches that found nothing useful are
// reported; the backend derives a task-family label and drops the query, so no
// raw query text is ever stored. Fire-and-forget, deduped per query per session.
const _signalledQueries = new Set();
function reportUnsolvedSearch(q, results) {
if (!q) return;
const topScore = results.length ? (results[0].score || 0) : 0;
if (results.length && topScore >= 0.35) return; // solved — nothing to report
const key = q.toLowerCase().trim();
if (_signalledQueries.has(key)) return;
_signalledQueries.add(key);
fetch(SEARCH_SIGNAL_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: q, result_count: results.length, top_score: topScore }),
}).catch(() => {}); // silent fail — insights are best-effort
}
function submitFeedback(lessonId, query, feedback) {
const existing = getFeedbackForLesson(lessonId, query);
if (existing) return;
const entry = {
query,
lesson_id: lessonId,
feedback,
ts: new Date().toISOString(),
};
saveFeedback(entry);
restoreFeedbackState(lessonId, query);
// POST to backend (fire-and-forget, localStorage is primary)
fetch(FEEDBACK_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(entry),
}).catch(() => {}); // silent fail, localStorage is fallback
}
function restoreFeedbackState(lessonId, query) {
const bar = document.querySelector('[data-feedback-id="' + lessonId + '"]');
if (!bar) return;
const existing = getFeedbackForLesson(lessonId, query);
if (!existing) return;
bar.querySelectorAll('.feedback-btn').forEach(btn => {
if (btn.dataset.type === existing.feedback) btn.classList.add('selected');
else btn.style.display = 'none';
});
}
function updateFeedbackSummary() {
const el = document.getElementById('feedback-summary');
if (!el) return;
const count = getFeedbackStore().length;
if (count === 0) { el.hidden = true; return; }
el.hidden = false;
el.innerHTML = t('feedbackRecorded', { count }) +
' · <a href="#" onclick="copyFeedback();return false">' + t('feedbackCopy') + '</a>' +
' · <a href="#" onclick="openFeedbackIssue();return false">' + t('feedbackSubmit') + '</a>';
}
// Event delegation for feedback buttons (no inline onclick)
document.getElementById('results').addEventListener('click', function(e) {
const btn = e.target.closest('.feedback-btn');
if (!btn) return;
const bar = btn.closest('.feedback-bar');
if (!bar) return;
const card = btn.closest('.result');
const lessonId = bar.dataset.feedbackId;
const query = document.getElementById('q').value.trim();
if (!lessonId || !query) return;
submitFeedback(lessonId, query, btn.dataset.type);
});
function restoreAllFeedbackStates() {
const query = document.getElementById('q').value.trim();
if (!query) return;
document.querySelectorAll('.feedback-bar').forEach(bar => {
restoreFeedbackState(bar.dataset.feedbackId, query);
});
}
function copyFeedback() {
const data = JSON.stringify(getFeedbackStore(), null, 2);
navigator.clipboard.writeText(data).then(() => alert('Feedback copied to clipboard.'));
}
function openFeedbackIssue() {
const store = getFeedbackStore();
const body = '## Search Feedback\n\n```json\n' + JSON.stringify(store, null, 2) + '\n```\n\n_Submitted via misakanet.org/search/_';
const url = 'https://github.com/Ikalus1988/MisakaNet/issues/new?title=' +
encodeURIComponent('[Search] Feedback report') +
'&body=' + encodeURIComponent(body) +
'&labels=feedback';
window.open(url, '_blank');
}
function render(results, q) {
const el = document.getElementById('results');
_lastResults = results;
reportUnsolvedSearch(q, results);
if (!results.length) {
el.innerHTML = '<div class="fallback">' +
'<div style="margin-bottom:8px;">' + t('noMatchPrefix') + ' "' + escapeHTML(q) + '". ' + t('noMatchSuffix') + '</div>' +
'<div style="font-size:13px;margin-bottom:12px;max-width:480px;margin-left:auto;margin-right:auto;">' +
'Try using fewer keywords, checking spelling, or browsing by <a href="/topics/" style="color:#58a6ff;">topic</a>. ' +
'Popular queries: <code style="font-size:11px;">pip timeout</code>, <code style="font-size:11px;">database locked</code>, <code style="font-size:11px;">DCO sign-off</code>, <code style="font-size:11px;">git rebase</code>.' +
'</div>' +
'<div style="font-size:12px;"><a href="/skill.md">' + t('installSkill') + '</a> · <a href="https://github.com/Ikalus1988/MisakaNet">' + t('submitLesson') + '</a> · <a href="https://github.com/Ikalus1988/MisakaNet/issues/new?template=lesson-request.yml">Request a lesson</a></div></div>';
return;
}
const searchable = _lessons ? _lessons.filter(isSearchable).length : 0;
const total = _lessons ? _lessons.length : 0;
// Classify and group results
const classified = results.map((r, index) => {
const { confidence, resultType } = classifyResult(r, r.score || 0);
return { ...r, _index: index, _confidence: confidence, _resultType: resultType };
});
const topFixes = classified.filter(r => r._resultType === 'actionable');
const commonRefs = classified.filter(r => r._resultType === 'common');
const relatedRefs = classified.filter(r => r._resultType === 'related');
function renderCard(r) {
const takeaway = escapeHTML(getTakeaway(r));
const title = escapeHTML(r.title);
const summary = escapeHTML((r.summary||'').slice(0,200));
const domain = escapeHTML(r.domain||'general');
const tags = (r.tags||[]).slice(0,4).map(escapeHTML).join(', ');
const url = getLessonUrl(r);
const id = escapeHTML(r.id || '');
const badge = inferBadge(r);
const confBadge = r._confidence === 'high' ? 'badge-high' : r._confidence === 'low' ? 'badge-low' : 'badge-medium';
const ev = evidenceInfo(r.evidence_level);
const showTitle = takeaway !== title;
return '<div class="result" tabindex="0" data-index="' + r._index + '" data-id="' + id + '">' +
'<div class="result-meta">' +
'<span class="badge ' + badge.cls + '">' + t(badge.key) + '</span>' +
'<span class="badge badge-domain">' + domain + '</span>' +
'<span class="badge ' + confBadge + '">' + r._confidence + '</span>' +
'<span class="badge badge-evidence" title="' + escapeHTML(ev.label) + '">' + ev.level + '</span>' +
'</div>' +
'<div class="result-title">' + takeaway + '</div>' +
(showTitle ? '<div class="result-id">' + id + '</div>' : '') +
'<div class="result-summary">' + summary + '</div>' +
(tags ? '<div class="result-tags">' + tags + '</div>' : '') +
'<div class="result-actions">' +
'<button class="btn-primary" type="button" data-action="preview">' + t('readLesson') + '</button>' +
'<a class="btn-secondary" href="' + escapeHTML(url) + '" target="_blank" rel="noopener">' + t('openGitHub') + '</a>' +
'</div>' +
'<div class="feedback-bar" data-feedback-id="' + id + '">' +
'<button class="feedback-btn" data-type="irrelevant">' + t('feedbackIrrelevant') + '</button>' +
'<button class="feedback-btn" data-type="too_basic">' + t('feedbackTooBasic') + '</button>' +
'<button class="feedback-btn" data-type="helpful">' + t('feedbackHelpful') + '</button>' +
'</div>' +
'<div class="lesson-preview" hidden></div>' +
'</div>';
}
let html = '<div class="results-header">' + t('resultsHeader', { count: results.length, q: escapeHTML(q) }) + '</div>';
html += '<div class="stats">' + t('resultsStats', { count: searchable, total }) + '</div>';
// Top fixes
if (topFixes.length) {
html += '<div class="section-label">Top fixes</div>';
html += topFixes.map(renderCard).join('');
}
// Related (if no top fixes, show related as primary)
if (!topFixes.length && relatedRefs.length) {
html += '<div class="section-label">Results</div>';
html += relatedRefs.map(renderCard).join('');
} else if (relatedRefs.length) {
html += '<div class="section-label">Related</div>';
html += relatedRefs.map(renderCard).join('');
}
// Common references (folded)
if (commonRefs.length) {
html += '<button class="fold-toggle" type="button" onclick="this.classList.toggle(\'open\');this.nextElementSibling.hidden=!this.nextElementSibling.hidden">' +
'<span class="arrow">▸</span> Common references (' + commonRefs.length + ')' +
'</button>';
html += '<div hidden>' + commonRefs.map(renderCard).join('') + '</div>';
}
el.innerHTML = html;
restoreAllFeedbackStates();
}
function renderMarkdown(text) {
// Minimal markdown renderer: h2, h3, code blocks, inline code, paragraphs
let html = escapeHTML(text);
// Code blocks: ```...```
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>');
// Inline code: `...`
html = html.replace(/`([^`\n]+)`/g, '<code>$1</code>');
// H2: ## ...
html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
// H3: ### ...
html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
// Paragraphs: double newline
html = html.replace(/\n\n/g, '</p><p>');
// Single newline within paragraphs
html = html.replace(/\n/g, '<br>');
return '<p>' + html + '</p>';
}
async function togglePreview(index) {
const lesson = _lastResults[index];
const card = document.querySelector('.result[data-index="' + index + '"]');
const panel = card && card.querySelector('.lesson-preview');
if (!lesson || !panel) return;
// Auto-collapse: close any other open preview first
const openPanels = document.querySelectorAll('.lesson-preview:not([hidden])');
openPanels.forEach(p => {
if (p !== panel) {
p.hidden = true;
const otherBtn = p.closest('.result').querySelector('[data-action="preview"]');
if (otherBtn) otherBtn.textContent = t('readLesson');
}
});
if (panel.dataset.loaded === 'true') {
panel.hidden = !panel.hidden;
const btn = card.querySelector('[data-action="preview"]');
if (btn) btn.textContent = panel.hidden ? t('readLesson') : t('collapse');
updateUrl(document.getElementById('q').value.trim(), panel.hidden ? null : (lesson.id || ''));
return;
}
panel.hidden = false;
panel.innerHTML = '<div class="preview-status">' + t('loadingPreview') + '</div>';
const btn = card.querySelector('[data-action="preview"]');
if (btn) btn.textContent = t('collapse');
try {
// Use pre-generated preview from lessons.json (no remote fetch)
const body = lesson.preview || '';
const clipped = body.length > 2400 ? body.slice(0, 2400) + '\n\n' + t('clipped') : body;
panel.dataset.loaded = 'true';
panel.innerHTML = renderMarkdown(clipped || t('noPreview'));
updateUrl(document.getElementById('q').value.trim(), lesson.id || '');
} catch (e) {
panel.innerHTML = '<div class="preview-status">' + t('previewUnavailable') + '</div>';
}
}
function runSearch(q) {
const results = search(q);
render(results, q);
updateUrl(q);
return results;
}
async function init() {
try {
const r = await fetch(LESSONS_URL);
if (!r.ok) throw new Error(r.status);
_lessons = await r.json();
updateStats();
document.getElementById('results').innerHTML = '';
const params = new URLSearchParams(location.search);
const q = params.get('q');
const lessonId = params.get('lesson');
if (q) {
document.getElementById('q').value = q;
const results = search(q);
render(results, q);
// Auto-expand matching lesson
if (lessonId && results.length) {
const idx = results.findIndex(r => r.id === lessonId);
if (idx >= 0) setTimeout(() => togglePreview(idx), 300);
}
}
} catch(e) {
document.getElementById('results').innerHTML = '<div class="fallback">' + t('loadFailed') + ' <a href="/">' + t('goHome') + '</a></div>';
}
}
document.querySelectorAll('[data-lang]').forEach(btn => {
btn.addEventListener('click', () => setLang(btn.dataset.lang));
});
document.getElementById('q').addEventListener('input', function() {
const q = this.value.trim();
if (!q) { _lastResults = []; document.getElementById('results').innerHTML = ''; updateUrl(''); return; }
runSearch(q);
});
document.getElementById('q').addEventListener('keydown', function(event) {
if (event.key !== 'Enter') return;
const q = this.value.trim();
if (!q) return;
event.preventDefault();
const results = runSearch(q);
if (results.length) togglePreview(0);
});
document.getElementById('results').addEventListener('click', function(event) {
if (event.target.closest('a')) return;
if (event.target.closest('.lesson-preview')) return;
const card = event.target.closest('.result');
if (!card) return;
togglePreview(Number(card.dataset.index));
});
document.getElementById('results').addEventListener('keydown', function(event) {
if (event.target.closest('a,button')) return;
if (event.key !== 'Enter' && event.key !== ' ') return;
const card = event.target.closest('.result');
if (!card) return;
event.preventDefault();
togglePreview(Number(card.dataset.index));
});
setLang(LANG);
init();
updateFeedbackSummary();
</script>
</body>
</html>