-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract-knowledge.py
More file actions
executable file
·2248 lines (2009 loc) · 83.8 KB
/
extract-knowledge.py
File metadata and controls
executable file
·2248 lines (2009 loc) · 83.8 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
extract-knowledge.py — Extract structured knowledge from session checkpoints
Parses checkpoint sections to identify and categorize:
- Patterns: Reusable coding/architecture best practices
- Mistakes: Errors made and lessons learned
- Decisions: Technical choices and their rationale
- Tools: Tool configurations and usage notes
Usage:
python extract-knowledge.py # Extract from all checkpoints
python extract-knowledge.py --stats # Show extraction statistics
python extract-knowledge.py --list # List all extracted entries
python extract-knowledge.py --category mistakes # Show specific category
Cross-platform: Windows, macOS, Linux. Pure Python stdlib.
"""
import hashlib
import json
import os
import re
import sqlite3
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path
# Fix Windows console encoding for Unicode output
if os.name == "nt":
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
SESSION_STATE = Path.home() / ".copilot" / "session-state"
DB_PATH = Path(os.environ.get("SK_DB_PATH", str(SESSION_STATE / "knowledge.db"))).expanduser()
def _emit_knowledge_event_fail_open(event_type: str, data: dict) -> None:
try:
events_script = Path(__file__).with_name("events.py")
if not events_script.is_file():
return
subprocess.call(
[
sys.executable,
str(events_script),
"append",
event_type,
"--data",
json.dumps(data, ensure_ascii=False),
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
except Exception:
return
def _stable_sha256(*parts) -> str:
payload = "\0".join("" if p is None else str(p) for p in parts)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _knowledge_stable_id(session_id: str, category: str, title: str, topic_key: str) -> str:
return _stable_sha256("knowledge", session_id, category, title or "", topic_key or "")
def _knowledge_relation_stable_id(source_stable_id: str, target_stable_id: str, relation_type: str) -> str:
return _stable_sha256(
"knowledge_relation",
source_stable_id or "",
target_stable_id or "",
relation_type or "",
)
def _utc_now() -> str:
return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
def _default_local_replica_id() -> str:
host = os.environ.get("HOSTNAME") or os.environ.get("COMPUTERNAME") or ""
user = os.environ.get("USER") or os.environ.get("USERNAME") or ""
return f"replica-{_stable_sha256('local-replica', host, user, str(Path.home()))[:16]}"
def _get_local_replica_id(db: sqlite3.Connection) -> str:
try:
row = db.execute("SELECT value FROM sync_state WHERE key='local_replica_id'").fetchone()
current = str(row[0]) if row and row[0] else ""
if current and current != "local":
return current
replica_id = _default_local_replica_id()
db.execute(
"""
INSERT INTO sync_state (key, value)
VALUES ('local_replica_id', ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = datetime('now')
""",
(replica_id,),
)
db.execute(
"""
INSERT INTO sync_metadata (key, value)
VALUES ('local_replica_id', ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = datetime('now')
""",
(replica_id,),
)
return replica_id
except Exception:
return ""
def _enqueue_sync_op_fail_open(
db: sqlite3.Connection,
table_name: str,
row_stable_id: str,
row_payload: dict,
op_type: str = "upsert",
):
try:
tools_dir = str(Path(__file__).resolve().parent)
if tools_dir not in sys.path:
sys.path.insert(0, tools_dir)
from sync_enqueue import enqueue_sync_op_fail_open
enqueue_sync_op_fail_open(db, table_name, row_stable_id, row_payload, op_type)
except Exception:
return
def _seed_sync_table_policies(db: sqlite3.Connection):
rows = [
("sessions", "canonical", "id"),
("documents", "canonical", "stable_id"),
("sections", "canonical", "stable_id"),
("knowledge_entries", "canonical", "stable_id"),
("knowledge_relations", "canonical", "stable_id"),
("entity_relations", "canonical", "stable_id"),
("search_feedback", "canonical", "stable_id"),
("recall_events", "upload_only", ""),
("entry_recall_stats", "upload_only", ""),
("entry_recall_day_log", "upload_only", ""),
("entry_recall_query_log", "upload_only", ""),
("knowledge_fts", "local_only", ""),
("ke_fts", "local_only", ""),
("sessions_fts", "local_only", ""),
("event_offsets", "local_only", ""),
("embeddings", "local_only", ""),
("embedding_meta", "local_only", ""),
("tfidf_model", "local_only", ""),
("entry_concept_tags", "local_only", ""),
]
policy_sql = db.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='sync_table_policies'"
).fetchone()
needs_rebuild = policy_sql and "upload_only" not in (policy_sql[0] or "")
if needs_rebuild:
db.executescript("""
CREATE TABLE sync_table_policies_new (
table_name TEXT PRIMARY KEY,
sync_scope TEXT NOT NULL CHECK(sync_scope IN ('canonical', 'local_only', 'upload_only')),
stable_id_column TEXT DEFAULT ''
);
INSERT INTO sync_table_policies_new (table_name, sync_scope, stable_id_column)
SELECT table_name, sync_scope, COALESCE(stable_id_column, '')
FROM sync_table_policies;
DROP TABLE sync_table_policies;
ALTER TABLE sync_table_policies_new RENAME TO sync_table_policies;
""")
db.executescript("""
CREATE TABLE IF NOT EXISTS sync_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sync_state (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sync_txns (
txn_id TEXT PRIMARY KEY,
replica_id TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('pending', 'committed', 'failed')),
created_at TEXT NOT NULL,
committed_at TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS sync_ops (
id INTEGER PRIMARY KEY AUTOINCREMENT,
txn_id TEXT NOT NULL,
table_name TEXT NOT NULL,
op_type TEXT NOT NULL CHECK(op_type IN ('insert', 'update', 'delete', 'upsert')),
row_stable_id TEXT NOT NULL,
row_payload TEXT NOT NULL,
op_index INTEGER NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(txn_id, op_index)
);
CREATE INDEX IF NOT EXISTS idx_sync_ops_txn ON sync_ops(txn_id);
CREATE INDEX IF NOT EXISTS idx_sync_ops_table_row ON sync_ops(table_name, row_stable_id);
CREATE TABLE IF NOT EXISTS sync_cursors (
replica_id TEXT PRIMARY KEY,
last_txn_id TEXT DEFAULT '',
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sync_failures (
id INTEGER PRIMARY KEY AUTOINCREMENT,
txn_id TEXT DEFAULT '',
table_name TEXT DEFAULT '',
row_stable_id TEXT DEFAULT '',
error_code TEXT DEFAULT '',
error_message TEXT DEFAULT '',
failed_at TEXT NOT NULL,
retry_count INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_sync_failures_txn ON sync_failures(txn_id);
CREATE TABLE IF NOT EXISTS sync_table_policies (
table_name TEXT PRIMARY KEY,
sync_scope TEXT NOT NULL CHECK(sync_scope IN ('canonical', 'local_only', 'upload_only')),
stable_id_column TEXT DEFAULT ''
);
""")
db.executemany(
"""
INSERT INTO sync_table_policies (table_name, sync_scope, stable_id_column)
VALUES (?, ?, ?)
ON CONFLICT(table_name) DO UPDATE SET
sync_scope = excluded.sync_scope,
stable_id_column = excluded.stable_id_column
""",
rows,
)
db.execute("""
INSERT OR IGNORE INTO sync_metadata (key, value)
VALUES ('local_replica_id', 'local')
""")
db.execute("""
INSERT OR IGNORE INTO sync_state (key, value)
VALUES ('local_replica_id', 'local')
""")
def _backfill_stable_ids(db: sqlite3.Connection):
for row in db.execute("""
SELECT id, session_id, category, title, COALESCE(topic_key, ''), COALESCE(stable_id, '')
FROM knowledge_entries
""").fetchall():
ke_id, session_id, category, title, topic_key, existing = row
stable = _knowledge_stable_id(session_id, category, title, topic_key)
if existing != stable:
db.execute("UPDATE knowledge_entries SET stable_id = ? WHERE id = ?", (stable, ke_id))
_enqueue_sync_op_fail_open(
db,
"knowledge_entries",
stable,
{
"session_id": session_id,
"category": category,
"title": title,
"topic_key": topic_key,
"stable_id": stable,
},
)
for row in db.execute("""
SELECT id, subject, predicate, object, COALESCE(stable_id, '')
FROM entity_relations
""").fetchall():
er_id, subject, predicate, obj, existing = row
stable = _stable_sha256("entity_relation", subject or "", predicate or "", obj or "")
if existing != stable:
db.execute("UPDATE entity_relations SET stable_id = ? WHERE id = ?", (stable, er_id))
_enqueue_sync_op_fail_open(
db,
"entity_relations",
stable,
{
"subject": subject,
"predicate": predicate,
"object": obj,
"stable_id": stable,
},
)
for row in db.execute("""
SELECT kr.id,
kr.source_id,
kr.target_id,
kr.relation_type,
COALESCE(kr.source_stable_id, ''),
COALESCE(kr.target_stable_id, ''),
COALESCE(kr.stable_id, ''),
COALESCE(src.stable_id, ''),
COALESCE(tgt.stable_id, '')
FROM knowledge_relations kr
LEFT JOIN knowledge_entries src ON kr.source_id = src.id
LEFT JOIN knowledge_entries tgt ON kr.target_id = tgt.id
""").fetchall():
rel_id, _, _, relation_type, src_existing, tgt_existing, existing, src_stable, tgt_stable = row
if not src_stable or not tgt_stable:
continue
stable = _knowledge_relation_stable_id(src_stable, tgt_stable, relation_type)
if src_existing != src_stable or tgt_existing != tgt_stable or existing != stable:
db.execute(
"""
UPDATE knowledge_relations
SET source_stable_id = ?, target_stable_id = ?, stable_id = ?
WHERE id = ?
""",
(src_stable, tgt_stable, stable, rel_id),
)
def _dedupe_stable_rows(db: sqlite3.Connection, table: str):
if table not in {"knowledge_entries", "knowledge_relations", "entity_relations"}:
return
db.execute(
"""
DELETE FROM {table}
WHERE id IN (
SELECT dupe.id
FROM {table} dupe
JOIN (
SELECT stable_id, MIN(id) AS keep_id
FROM {table}
WHERE COALESCE(stable_id, '') != ''
GROUP BY stable_id
HAVING COUNT(*) > 1
) grouped ON grouped.stable_id = dupe.stable_id
WHERE dupe.id != grouped.keep_id
)
""".replace("{table}", table)
)
def _enforce_stable_id_uniqueness(db: sqlite3.Connection):
has_table = lambda t: (
db.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
(t,),
).fetchone()
is not None
)
for table, index_name in [
("knowledge_entries", "uq_knowledge_entries_stable_id"),
("knowledge_relations", "uq_knowledge_relations_stable_id"),
("entity_relations", "uq_entity_relations_stable_id"),
]:
if has_table(table):
_dedupe_stable_rows(db, table)
db.execute(f"CREATE UNIQUE INDEX IF NOT EXISTS {index_name} ON {table}(stable_id)")
# ── WBS-013: Secret / injection scanner ──────────────────────────────────────
# Mirror of learn.py._INJECTION_PATTERNS (kept in sync with WBS-019 expansions).
# Applied before every DB insert in extract_from_sections() — fail-open (skip entry).
class _ContextAwareHexMatcher:
"""Matches long lowercase-hex strings only when NOT in a git/checksum context.
Prevents false-positive blocking of 40-char git commit SHAs and 64-char
SHA-256 checksums while still catching bare secret hex tokens that appear
without any identifying reference keyword nearby.
Duck-types the compiled regex interface: implements .search(text) returning
a match object (or None) so it can be used transparently in pattern lists.
"""
_HEX_RE = re.compile(r"(?<![A-Za-z0-9])([0-9a-f]{40,})(?![A-Za-z0-9])")
_SAFE_CTX_RE = re.compile(r"(?i)\b(?:commit|sha\d*|hash|checksum|digest|fingerprint)\b")
def search(self, text: str):
"""Return the first match for a secret-context hex run; None if all safe."""
for m in self._HEX_RE.finditer(text):
pre = text[max(0, m.start() - 100) : m.start()]
if self._SAFE_CTX_RE.search(pre):
continue
return m
return None
_EXTRACT_INJECTION_PATTERNS = [
(
re.compile(r"(?i)\bignore\s+(all\s+)?previous\s+instructions?\b"),
"prompt injection: 'ignore previous instructions'",
),
(re.compile(r"(?i)\byou\s+are\s+now\b"), "role hijacking: 'you are now'"),
(re.compile(r"(?i)\bsystem\s*:\s*"), "role injection: 'system:' prefix"),
(re.compile(r"(?i)\b(assistant|user|human)\s*:\s*"), "role injection: fake role prefix"),
(re.compile(r"(?i)\bforget\s+(everything|all|your)\b"), "memory manipulation: 'forget everything'"),
(re.compile(r"(?i)\bdo\s+not\s+follow\b"), "instruction override: 'do not follow'"),
(
re.compile(r"(?i)\b(api[_-]?key|secret[_-]?key|password|token)\s*[:=]\s*\S+"),
"credential leak: API key/password/token",
),
(re.compile(r"(?i)ssh-rsa\s+AAAA"), "credential leak: SSH public key"),
(re.compile(r"(?i)-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----"), "credential leak: private key"),
(re.compile(r"(?i)\beval\s*\("), "code injection: eval()"),
(re.compile(r"(?i)\bexec\s*\("), "code injection: exec()"),
(re.compile(r"[\u200b\u200c\u200d\u2060\ufeff]"), "invisible Unicode characters (zero-width)"),
(re.compile(r"(?i)\bACT\s+AS\b"), "role hijacking: 'act as'"),
(re.compile(r"(?i)\bpretend\s+(you\s+are|to\s+be)\b"), "role hijacking: 'pretend to be'"),
(re.compile(r"(?i)\b(curl|wget|nc|ncat)\s+.*\|\s*(ba)?sh\b"), "remote code execution pattern"),
(
re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),
"credential leak: JWT token",
),
(
re.compile(r"(?i)\bAuthorization\s*:\s*Bearer\s+\S{16,}"),
"credential leak: Authorization Bearer token",
),
(
re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
"credential leak: AWS access key ID",
),
(
re.compile(r"(?i)\b(aws[_-]?secret[_-]?access[_-]?key|aws[_-]?secret)\s*[:=]\s*[A-Za-z0-9/+]{30,}"),
"credential leak: AWS secret access key",
),
# WBS-019: generic long hex token (context-aware — skips git commit SHAs and checksums)
(
_ContextAwareHexMatcher(),
"credential leak: long hex secret/token",
),
]
def _scan_extract_chunk(title: str, content: str) -> str:
"""Scan title + content for injection/credential patterns.
Returns the first matching description, or empty string if clean.
Used by extract_from_sections() to skip unsafe chunks before DB insert.
Fail-open: any exception returns empty string (scan miss is preferable to
blocking extraction entirely).
"""
try:
text = f"{title}\n{content}"
for pattern, description in _EXTRACT_INJECTION_PATTERNS:
if pattern.search(text):
return description
except Exception:
pass
return ""
# ── Extraction patterns — regex + heuristics for each category ────────────────
MISTAKE_INDICATORS = [
r"(?:mistake|error|bug|wrong|incorrect|broken|fail|crash|fix(?:ed)?)\b",
r"(?:should\s+(?:have|not)|shouldn't|don't|avoid|never|careful)",
r"(?:root\s+cause|caused\s+by|problem\s+was|issue\s+was)",
r"(?:lỗi|sai|sửa|tránh|không\s+nên|nguyên\s+nhân)",
]
PATTERN_INDICATORS = [
r"(?:always|must|should|convention|pattern|best\s+practice|rule)\b",
r"(?:use\s+\w+\s+instead\s+of|prefer|recommend)",
r"(?:standard|template|reusable|common\s+(?:pattern|style|approach))",
r"(?:luôn|nên|quy\s+tắc|mẫu|chuẩn)",
r"(?:good\s+practice|consistent(?:ly)?|enforce|ensure\s+(?:that|you))\b",
r"\b(?:tip|guideline|approach|technique|strategy)\b",
r"\b(?:make\s+sure|remember\s+to|keep\s+in\s+mind|note\s+that)\b",
]
DECISION_INDICATORS = [
r"(?:chose|decided|selected|picked|went\s+with|opted)\b",
r"(?:because|reason|rationale|trade-off|tradeoff)",
r"(?:option\s+[A-C]|alternative|compared|versus|vs\.?)\b",
r"(?:chọn|quyết\s+định|lý\s+do|so\s+sánh)",
]
TOOL_INDICATORS = [
r"(?:install|configure|setup|version|upgrade|dependency)\b",
r"(?:gradle|maven|docker|redis|postgres|spring\s+boot)\b",
r"(?:JDK|SDK|IDE|VSCode|extension)\b",
r"(?:cài|cấu\s+hình|phiên\s+bản|nâng\s+cấp)",
]
FEATURE_INDICATORS = [
r"\b(?:implement(?:ed|ing)?|add(?:ed|ing)?|create(?:d|ing)?|build|built|develop(?:ed|ing)?)\b",
r"(?:new\s+(?:feature|endpoint|handler|screen|component|API))\b",
r"\b(?:feature|functionality|capability|user\s+story)\b",
r"(?:thêm|tạo|xây\s+dựng|tính\s+năng|chức\s+năng)\b",
]
REFACTOR_INDICATORS = [
r"\b(?:refactor|restructur|simplif|clean\s*up|extract|reorganiz)",
r"\b(?:rename[ds]?|move[ds]?|split|merge[ds]?|consolidat|dedup)",
r"\b(?:improv(?:e[ds]?|ing)|optimiz|reduc)",
r"(?:tái\s+cấu\s+trúc|đơn\s+giản\s+hóa|tối\s+ưu)",
]
DISCOVERY_INDICATORS = [
r"\b(?:discover|found|learn|realiz|notic|observ)",
r"\b(?:turns\s+out|apparently|actually|interesting)\b",
r"\b(?:TIL|insight|understanding|revelation)\b",
r"(?:phát\s+hiện|nhận\s+ra|hiểu|thấy\s+rằng)",
]
# Error type classification patterns for auto-detection
ERROR_TYPE_PATTERNS = {
"syntax": [
r"(?:syntax\s*error|parse\s*error|unexpected\s*token|unterminated)",
r"(?:indentation|missing\s*(?:bracket|paren|semicolon|colon|comma))",
r"(?:SyntaxError|ParseError|invalid\s*syntax)",
],
"runtime": [
r"(?:runtime\s*error|exception|traceback|stack\s*trace)",
r"(?:TypeError|ValueError|AttributeError|KeyError|IndexError|NameError)",
r"(?:NullPointerException|segfault|segmentation\s*fault|SIGSEGV)",
r"(?:crash(?:ed|es|ing)?|abort|panic|unhandled)",
],
"logic": [
r"(?:logic\s*error|wrong\s*(?:result|output|behavior|value))",
r"(?:incorrect|unexpected\s*(?:result|output|behavior))",
r"(?:off-by-one|race\s*condition|deadlock|infinite\s*loop)",
],
"timeout": [
r"(?:timeout|timed?\s*out|hang(?:s|ing|ed)?|stuck|frozen)",
r"(?:too\s*(?:slow|long)|deadline\s*exceeded|connection\s*timeout)",
],
"permission": [
r"(?:permission\s*denied|access\s*denied|unauthorized|forbidden)",
r"(?:EACCES|EPERM|403|401|authentication\s*fail)",
],
"build": [
r"(?:build\s*(?:fail|error)|compilation\s*(?:fail|error))",
r"(?:linker\s*error|import\s*error|module\s*not\s*found)",
r"(?:cannot\s*find\s*module|unresolved\s*(?:import|reference))",
],
"deploy": [
r"(?:deploy(?:ment)?\s*(?:fail|error)|rollback|service\s*(?:down|unavailable))",
r"(?:health\s*check\s*fail|container\s*(?:crash|restart))",
],
"config": [
r"(?:config(?:uration)?\s*(?:error|missing|invalid))",
r"(?:env(?:ironment)?\s*(?:variable|missing)|\.env|settings?\s*(?:wrong|missing))",
],
}
# Root cause extraction patterns
ROOT_CAUSE_EXTRACTORS = [
r"(?:root\s*cause|caused\s*by|because|reason(?:\s*was)?|due\s*to|problem\s*was|issue\s*was)[:\s]+(.{10,200})",
r"(?:nguyên\s*nhân|do|vì|bởi\s*vì)[:\s]+(.{10,200})",
r"(?:the\s*(?:real|actual|underlying)\s*(?:issue|problem|cause)\s*(?:is|was))[:\s]+(.{10,200})",
r"(?:fixed\s*by|resolved\s*by|solution\s*was)[:\s]+(.{10,200})",
]
# Severity keywords for auto-detection
SEVERITY_KEYWORDS = {
"critical": [r"critical", r"fatal", r"data\s*loss", r"security\s*(?:vuln|breach)", r"production\s*(?:down|crash)"],
"high": [r"crash", r"hang", r"block(?:ed|ing)", r"regression", r"broken\s*(?:build|deploy|test)"],
"low": [r"cosmetic", r"typo", r"formatting", r"style", r"minor", r"warning\b"],
}
def classify_error_type(text: str) -> str:
"""Auto-classify error type from content. Returns empty string if no match."""
text_lower = text.lower()
best_type = ""
best_score = 0
for etype, patterns in ERROR_TYPE_PATTERNS.items():
score = 0
for p in patterns:
score += len(re.findall(p, text_lower, re.IGNORECASE))
if score > best_score:
best_score = score
best_type = etype
return best_type if best_score >= 1 else ""
def extract_root_cause(text: str) -> str:
"""Extract root cause description from content. Returns empty string if none found."""
for p in ROOT_CAUSE_EXTRACTORS:
m = re.search(p, text, re.IGNORECASE)
if m:
cause = m.group(1).strip().rstrip(".")
if len(cause) > 10:
return cause[:200]
return ""
def detect_severity(text: str) -> str:
"""Auto-detect severity from content keywords. Returns 'medium' as default."""
text_lower = text.lower()
for sev in ("critical", "high", "low"):
for p in SEVERITY_KEYWORDS[sev]:
if re.search(p, text_lower, re.IGNORECASE):
return sev
return "medium"
# Stopwords for concept tag extraction (pure stdlib, no ML imports)
_CONCEPT_STOPWORDS = frozenset(
{
"the",
"a",
"an",
"and",
"or",
"but",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"by",
"from",
"is",
"are",
"was",
"were",
"be",
"been",
"have",
"has",
"had",
"do",
"does",
"did",
"will",
"would",
"could",
"should",
"may",
"might",
"can",
"it",
"this",
"that",
"these",
"those",
"i",
"we",
"you",
"he",
"she",
"they",
"not",
"no",
"so",
"if",
"then",
"when",
"where",
"what",
"which",
"who",
"how",
"all",
"any",
"each",
"more",
"most",
"also",
"just",
"up",
"out",
"as",
"into",
"than",
"their",
"its",
"our",
"my",
"your",
"his",
"her",
"them",
"us",
"me",
"after",
"before",
"during",
"while",
"since",
"until",
"too",
"very",
"about",
"above",
"below",
"between",
"through",
"use",
"used",
"using",
"run",
"running",
"make",
"new",
"only",
"now",
"time",
"way",
"need",
"needs",
"see",
"get",
"set",
"add",
"put",
"let",
"say",
"one",
"two",
"per",
"via",
"etc",
"yet",
"got",
}
)
def extract_concept_tags(text: str, top_k: int = 5) -> list:
"""Extract top_k concept tags from text using pure-stdlib term frequency.
Distinct from extract_tags() (which parses explicit user-supplied tags from
checkpoint text). This function performs automatic keyword extraction from
free-form entry title + content using stopword-filtered term frequency.
Args:
text: Combined title and content text to analyze.
top_k: Maximum number of concept tags to return.
Returns:
List of up to top_k lowercase concept tag strings, sorted by frequency desc.
"""
if not text:
return []
# Tokenize: sequences of letters/digits/hyphens/underscores, min 3 chars
tokens = re.findall(r"[a-zA-Z][a-zA-Z0-9_-]{2,}", text.lower())
freq: dict = {}
for tok in tokens:
if tok not in _CONCEPT_STOPWORDS:
freq[tok] = freq.get(tok, 0) + 1
# Sort by frequency descending, then alphabetically for stability
ranked = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
return [tag for tag, _ in ranked[:top_k]]
def ensure_tables(db: sqlite3.Connection):
"""Create knowledge_entries table if not exists."""
db.executescript("""
CREATE TABLE IF NOT EXISTS knowledge_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
document_id INTEGER,
category TEXT NOT NULL,
title TEXT NOT NULL,
stable_id TEXT,
content TEXT NOT NULL,
tags TEXT DEFAULT '',
confidence REAL DEFAULT 1.0,
occurrence_count INTEGER DEFAULT 1,
first_seen TEXT,
last_seen TEXT,
source TEXT DEFAULT 'copilot',
topic_key TEXT,
revision_count INTEGER DEFAULT 1,
content_hash TEXT,
wing TEXT DEFAULT '',
room TEXT DEFAULT '',
facts TEXT DEFAULT '[]',
est_tokens INTEGER DEFAULT 0,
task_id TEXT DEFAULT '',
affected_files TEXT DEFAULT '[]',
source_section TEXT DEFAULT '',
source_file TEXT DEFAULT '',
start_line INTEGER DEFAULT 0,
end_line INTEGER DEFAULT 0,
code_language TEXT DEFAULT '',
code_snippet TEXT DEFAULT '',
UNIQUE(category, title, session_id)
);
CREATE INDEX IF NOT EXISTS idx_ke_category ON knowledge_entries(category);
CREATE INDEX IF NOT EXISTS idx_ke_session ON knowledge_entries(session_id);
CREATE INDEX IF NOT EXISTS idx_ke_source ON knowledge_entries(source);
CREATE INDEX IF NOT EXISTS idx_ke_topic ON knowledge_entries(topic_key);
CREATE INDEX IF NOT EXISTS idx_ke_hash ON knowledge_entries(content_hash);
CREATE INDEX IF NOT EXISTS idx_ke_task ON knowledge_entries(task_id);
CREATE INDEX IF NOT EXISTS idx_ke_stable_id ON knowledge_entries(stable_id);
CREATE TABLE IF NOT EXISTS knowledge_relations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_id INTEGER REFERENCES knowledge_entries(id),
target_id INTEGER REFERENCES knowledge_entries(id),
source_stable_id TEXT DEFAULT '',
target_stable_id TEXT DEFAULT '',
relation_type TEXT NOT NULL,
stable_id TEXT,
confidence REAL DEFAULT 0.8,
created_at TEXT,
UNIQUE(source_id, target_id, relation_type)
);
CREATE INDEX IF NOT EXISTS idx_kr_source ON knowledge_relations(source_id);
CREATE INDEX IF NOT EXISTS idx_kr_target ON knowledge_relations(target_id);
CREATE INDEX IF NOT EXISTS idx_kr_source_stable ON knowledge_relations(source_stable_id);
CREATE INDEX IF NOT EXISTS idx_kr_target_stable ON knowledge_relations(target_stable_id);
CREATE INDEX IF NOT EXISTS idx_kr_stable_id ON knowledge_relations(stable_id);
CREATE TABLE IF NOT EXISTS entity_relations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subject TEXT NOT NULL,
predicate TEXT NOT NULL,
object TEXT NOT NULL,
stable_id TEXT,
noted_at TEXT DEFAULT (datetime('now')),
session_id TEXT DEFAULT '',
UNIQUE(subject, predicate, object)
);
CREATE INDEX IF NOT EXISTS idx_er_subject ON entity_relations(subject);
CREATE INDEX IF NOT EXISTS idx_er_object ON entity_relations(object);
CREATE INDEX IF NOT EXISTS idx_er_stable_id ON entity_relations(stable_id);
CREATE TABLE IF NOT EXISTS wakeup_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at TEXT DEFAULT (datetime('now'))
);
""")
# Migrate existing databases: add new columns if missing
_ALLOWED_COLUMNS = {
"stable_id",
"source",
"topic_key",
"revision_count",
"content_hash",
"wing",
"room",
"facts",
"est_tokens",
"task_id",
"affected_files",
"source_section",
"source_file",
"start_line",
"end_line",
"code_language",
"code_snippet",
}
for col, col_def in [
("stable_id", "TEXT"),
("source", "TEXT DEFAULT 'copilot'"),
("topic_key", "TEXT"),
("revision_count", "INTEGER DEFAULT 1"),
("content_hash", "TEXT"),
("wing", "TEXT DEFAULT ''"),
("room", "TEXT DEFAULT ''"),
("facts", "TEXT DEFAULT '[]'"),
("est_tokens", "INTEGER DEFAULT 0"),
("task_id", "TEXT DEFAULT ''"),
("affected_files", "TEXT DEFAULT '[]'"),
("source_section", "TEXT DEFAULT ''"),
("source_file", "TEXT DEFAULT ''"),
("start_line", "INTEGER DEFAULT 0"),
("end_line", "INTEGER DEFAULT 0"),
("code_language", "TEXT DEFAULT ''"),
("code_snippet", "TEXT DEFAULT ''"),
]:
assert col in _ALLOWED_COLUMNS, f"Unexpected column: {col}"
try:
db.execute(f"ALTER TABLE knowledge_entries ADD COLUMN {col} {col_def}")
except sqlite3.OperationalError:
pass # Column already exists
db.execute("CREATE INDEX IF NOT EXISTS idx_ke_task ON knowledge_entries(task_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_ke_stable_id ON knowledge_entries(stable_id)")
for col, col_def in [
("source_stable_id", "TEXT DEFAULT ''"),
("target_stable_id", "TEXT DEFAULT ''"),
("stable_id", "TEXT"),
]:
try:
db.execute(f"ALTER TABLE knowledge_relations ADD COLUMN {col} {col_def}")
except sqlite3.OperationalError:
pass
db.execute("CREATE INDEX IF NOT EXISTS idx_kr_source_stable ON knowledge_relations(source_stable_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_kr_target_stable ON knowledge_relations(target_stable_id)")
db.execute("CREATE INDEX IF NOT EXISTS idx_kr_stable_id ON knowledge_relations(stable_id)")
try:
db.execute("ALTER TABLE entity_relations ADD COLUMN stable_id TEXT")
except sqlite3.OperationalError:
pass
db.execute("CREATE INDEX IF NOT EXISTS idx_er_stable_id ON entity_relations(stable_id)")
# Create FTS table if needed (standalone, no content= sync issues)
db.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS ke_fts USING fts5(
title, content, tags, category, wing, room, facts,
tokenize='unicode61 remove_diacritics 2'
)
""")
_seed_sync_table_policies(db)
_backfill_stable_ids(db)
_enforce_stable_id_uniqueness(db)
def classify_paragraph(text: str) -> list[tuple[str, float]]:
"""Classify a paragraph into knowledge categories with confidence.
Category-aware thresholds and confidence floors:
- pattern: threshold=1 (easier to extract), floor=0.5
- decision: threshold=2, floor=0.5
- mistake/tool/feature/refactor/discovery: threshold=2, floor=0.4
"""
# Skip noise: interview Q&A, pure tables, pure code
if _is_noise(text):
return []
text_lower = text.lower()
results = []
# (threshold, confidence_floor) per category
_CATEGORY_CONFIG = {
"pattern": (1, 0.5),
"decision": (2, 0.5),
"mistake": (2, 0.4),
"tool": (2, 0.4),
"feature": (2, 0.4),
"refactor": (2, 0.4),
"discovery": (2, 0.4),
}
for category, indicators in [
("mistake", MISTAKE_INDICATORS),
("pattern", PATTERN_INDICATORS),
("decision", DECISION_INDICATORS),
("tool", TOOL_INDICATORS),
("feature", FEATURE_INDICATORS),
("refactor", REFACTOR_INDICATORS),
("discovery", DISCOVERY_INDICATORS),
]:
threshold, conf_floor = _CATEGORY_CONFIG.get(category, (2, 0.4))
score = 0
for pattern in indicators:
matches = len(re.findall(pattern, text_lower, re.IGNORECASE))
score += matches
if score >= threshold:
confidence = max(conf_floor, min(1.0, score / 5.0))
results.append((category, confidence))
return results
# Noise detection patterns
_NOISE_PATTERNS = [
r"(?:phỏng\s*vấn|interview|câu\s*hỏi|bộ\s*câu)",
r"(?:đáp\s*án|mong\s*đợi|tiêu\s*chí|ghi\s*điểm)",
r"(?:bảng\s*đánh\s*giá|evaluation\s*rubric)",
r"(?:trọng\s*số|scoring|rubric|interviewer)",
]
# Strong noise — single match is enough to discard
_STRONG_NOISE_PATTERNS = [
r"đáp\s*án\s*(mong\s*đợi|chi\s*tiết)",
r"bảng\s*(đánh\s*giá|ghi\s*điểm)",
r"câu\s*hỏi\s*phỏng\s*vấn",
r"interview\s*question",
r"nội\s*dung\s*cần\s*đề\s*cập",
]
# User-quote patterns — checkpoint summaries quoting the user, not real mistakes
# KEEP: "User pointed out", "User noticed", "User called out", "User criticized",
# "User demanded" — these are real bug reports / legitimate feedback
_USER_QUOTE_PATTERNS = [
r"^(?:\d+\.\s*)?user\s+(?:said|asked|reported|requested|mentioned|noted)\b",
r"^(?:\d+\.\s*)?user\s+(?:wants?|confirmed|approved|rejected)\b",
r"^(?:\d+\.\s*)?user\s+(?:clarified|provided|applied|selected|chose)\b",
r'^(?:\d+\.\s*)?user\s+said\s*[:"]',
r'^(?:\d+\.\s*)?user\s+reported\s*[:"]',
]