-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearn.py
More file actions
executable file
·4357 lines (3936 loc) · 161 KB
/
learn.py
File metadata and controls
executable file
·4357 lines (3936 loc) · 161 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
"""
learn.py — Record new knowledge from AI agent sessions
Allows AI agents (Copilot, Claude, Cursor) to write learnings back to the
shared knowledge base during or after work.
Usage:
python learn.py --mistake "Title" "Description of what went wrong and fix"
python learn.py --pattern "Title" "Description of what works well"
python learn.py --decision "Title" "Architecture decision and rationale"
python learn.py --tool "Title" "Tool/config that was useful"
python learn.py --feature "Title" "New feature implementation details"
python learn.py --refactor "Title" "Code improvement description"
python learn.py --discovery "Title" "Codebase finding or insight"
python learn.py --mistake "Title" "Description" --tags "docker,compose"
python learn.py --mistake "Title" "Description" --session abc123
python learn.py --mistake "Title" "Description" --confidence 0.8
python learn.py --mistake "Title" "Description" --wing backend --room dynamodb
python learn.py --mistake "Title" "Description" --priority P0
python learn.py --pattern "Title" "Description" --priority P1 --fact "batch limit is 25" --fact "GSI eventual"
python learn.py --mistake "Title" "Description" --task "memory-surface" --file "briefing.py" --file "learn.py"
python learn.py --pattern "Title" "Description" --code-location "path/to/file.py:50-75"
python learn.py --relate "copyToGroup" "reads_from" "patient-dynamic-form.json"
python learn.py --relate "addPatient Lambda" "writes_to" "dataTable"
python learn.py --from-file notes.md # Bulk import from markdown
python learn.py --from-checkpoint path/to/checkpoint.md # Batch ingest by ## heading
python learn.py --from-checkpoint path/to/file.md --dry-run # Preview without inserting
python learn.py --from-pr 576 # Batch ingest from PR body
python learn.py --from-pr https://github.com/org/repo/pull/576 # PR URL also works
python learn.py --from-file notes.md --as-category discovery # Insert whole file as one entry
python learn.py --flush-inbox # Replay entries queued while DB was locked
python learn.py --list # List recent entries
python learn.py --stats # Show knowledge stats
Lifecycle management:
python learn.py --mark-resolved <id> # Mark mistake #N as resolved
python learn.py --mark-resolved <id> --fix-steps "Step 1..." # Record fix steps
python learn.py --mark-resolved <id> --prevention-hook "Hook" # Record prevention note
python learn.py --list-unresolved # List unresolved mistakes
python learn.py --list-unresolved --category pattern --limit 10
python learn.py --retag # Re-run wing/room detection
python learn.py --retag --category mistake --dry-run # Preview changes
python learn.py --retag --entry-id 42 # Retag single entry
python learn.py --retag --wing backend # Retag all backend entries
Auto-update cerebrum snapshot (opt-in):
python learn.py --pattern "Title" "Desc" --update-cerebrum
python learn.py --mistake "Title" "Desc" --update-cerebrum --cerebrum-output CEREBRUM.md
python learn.py --decision "Title" "Desc" --update-cerebrum --cerebrum-sections mistakes,decisions
"""
import hashlib
import json
import os
import re
import sqlite3
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
if os.name == "nt":
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
TOOLS_DIR = Path(__file__).parent
SESSION_STATE = Path.home() / ".copilot" / "session-state"
DB_PATH = Path(os.environ.get("SK_DB_PATH", str(SESSION_STATE / "knowledge.db"))).expanduser()
LEARN_INBOX = Path(os.environ.get("SK_LEARN_INBOX", str(SESSION_STATE / "learn-inbox"))).expanduser()
DEFAULT_DB_BUSY_TIMEOUT_MS = 30_000
DEFAULT_LEARN_QUEUE_BUSY_TIMEOUT_MS = 250
_DISPATCHED_MARKER_PATH = Path.home() / ".copilot" / "markers" / "dispatched-subagent-active"
_MARKER_ENTRY_TTL = 4 * 3600 # 4 hours
# Predefined relation types (predicate → inverse). "related_to" is its own inverse.
RELATION_TYPES: dict[str, str] = {
"causes": "caused_by",
"fixes": "fixed_by",
"requires": "required_by",
"SUPERSEDES": "superseded_by",
"related_to": "related_to",
"navigates_to": "navigated_from",
"uses": "used_by",
"implements": "implemented_by",
"documents": "documented_by",
"tests": "tested_by",
}
def _llm_suggest_tags(title: str, content: str) -> list[str]:
"""Call LLM API to suggest tags. Returns list of lowercase tag strings."""
api_key = os.environ.get("SK_LLM_API_KEY") or os.environ.get("OPENAI_API_KEY") or ""
if not api_key:
print(
"Error: LLM API key not set. Set SK_LLM_API_KEY or OPENAI_API_KEY.",
file=sys.stderr,
)
sys.exit(1)
model = os.environ.get("SK_LLM_MODEL", "gpt-4o-mini")
prompt = (
f"Given this knowledge entry title and content, suggest 3-5 relevant tags "
f"as a JSON array of lowercase strings. Title: {title}. "
f"Content: {content[:500]}. Respond with only a JSON array."
)
payload = json.dumps(
{
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 100,
}
).encode("utf-8")
req = urllib.request.Request(
"https://api.openai.com/v1/chat/completions",
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
},
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read())
raw = data["choices"][0]["message"]["content"].strip()
m = re.search(r"\[.*?\]", raw, re.DOTALL)
if not m:
return []
tags = json.loads(m.group(0))
return [str(t).lower().strip() for t in tags if isinstance(t, str)]
def _should_use_writer_broker() -> bool:
"""Return True when the writer-broker should be auto-enabled.
Auto-enables when:
- SK_WRITER_BROKER is not explicitly "0" (override-off takes priority)
- The dispatched-subagent-active marker exists
- The marker has at least one fresh active entry (within 4h TTL)
Explicit overrides:
SK_WRITER_BROKER=0 → always False (disabled)
SK_WRITER_BROKER=1 → always True (enabled, existing behaviour)
Fail-open: any read/parse error returns False so learn.py never crashes.
"""
env_val = os.environ.get("SK_WRITER_BROKER", "")
if env_val == "0":
return False
if env_val in ("1", "true"):
return True
# Auto-detect via dispatched-subagent marker
try:
if not _DISPATCHED_MARKER_PATH.is_file():
return False
data = json.loads(_DISPATCHED_MARKER_PATH.read_text(encoding="utf-8"))
if not isinstance(data, dict):
return False
raw_active = data.get("active_tentacles")
if not isinstance(raw_active, list) or not raw_active:
return False
now = time.time()
for entry in raw_active:
if isinstance(entry, dict):
ts = entry.get("ts")
try:
if ts is not None and (now - float(ts)) < _MARKER_ENTRY_TTL:
return True
except (TypeError, ValueError):
pass
elif isinstance(entry, str):
# Old string-list format has no per-entry timestamp; treat as active
return True
return False
except Exception:
return False
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 _queue_learn_payload(payload: dict) -> Path:
"""Persist a learn write for later replay when SQLite is temporarily locked."""
LEARN_INBOX.mkdir(parents=True, exist_ok=True)
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True)
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
name = f"{time.strftime('%Y%m%dT%H%M%S')}-{time.time_ns()}-{digest}.json"
final_path = LEARN_INBOX / name
tmp_path = LEARN_INBOX / f".{name}.tmp"
tmp_path.write_bytes(raw.encode("utf-8") + b"\n")
os.replace(tmp_path, final_path)
return final_path
def _build_learn_payload(
argv: list[str],
entry_kwargs: dict,
*,
update_cerebrum: bool = False,
cerebrum_output: str = "CEREBRUM.md",
cerebrum_sections: str | None = None,
) -> dict:
return {
"schema_version": 1,
"queued_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
"reason": "database_locked",
"argv": list(argv),
"entry": entry_kwargs,
"cerebrum": {
"update": update_cerebrum,
"output": cerebrum_output,
"sections": cerebrum_sections,
},
}
def _replay_queued_payload(payload: dict) -> tuple[int, int]:
entry = dict(payload.get("entry") or {})
entry_id = _write_learn_entry(entry)
if entry_id >= 0 and entry.get("category") == "pattern":
_emit_knowledge_event_fail_open(
"pattern_learned",
{
"entry_id": entry_id,
"title": entry.get("title", ""),
"task_id": entry.get("task_id", ""),
"wing": entry.get("wing", ""),
"room": entry.get("room", ""),
"priority": entry.get("priority") or "P2",
"confidence": entry.get("confidence"),
},
)
cerebrum_rc = 0
cerebrum = payload.get("cerebrum") or {}
if entry_id >= 0 and cerebrum.get("update"):
cerebrum_rc = _auto_update_cerebrum(
cerebrum.get("output") or "CEREBRUM.md",
cerebrum.get("sections"),
json_mode=True,
)
return entry_id, cerebrum_rc
def _broadcast_new_entry(entry_id: int, category: str, title: str, session_id: str) -> None:
"""Append lightweight notification to broadcast log for parallel agents."""
import json
import time
markers_dir = Path.home() / ".copilot" / "markers"
markers_dir.mkdir(parents=True, exist_ok=True)
broadcast_path = markers_dir / "knowledge-broadcast.jsonl"
record = {
"ts": time.time(),
"entry_id": entry_id,
"category": category,
"title": title[:100],
"session_id": session_id or "",
}
try:
with broadcast_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")
except OSError:
pass # fail-open
def _write_learn_entry(
entry_kwargs: dict,
*,
max_attempts: int = 5,
base_delay: float = 0.5,
db_busy_timeout_ms: int | None = None,
) -> int:
"""Write an entry through the standard retry path, preserving CLI call shape."""
entry = dict(entry_kwargs)
category = entry.pop("category")
title = entry.pop("title")
content = entry.pop("content")
return with_retry(
add_entry,
category,
title,
content,
max_attempts=max_attempts,
base_delay=base_delay,
db_busy_timeout_ms=db_busy_timeout_ms,
**entry,
)
_INBOX_FILENAME_HASH_RE = re.compile(r"-([0-9a-f]{16})\.json$")
def _inbox_filename_hash(path: Path) -> str | None:
"""Return the 16-hex hash component embedded in a queue filename, or None."""
m = _INBOX_FILENAME_HASH_RE.search(path.name)
return m.group(1) if m else None
def _validate_inbox_file(path: Path) -> tuple[bool, str | None, dict | None]:
"""Return (ok, reason, payload).
Security gate for issue #573: every queued JSON file must:
1. Have a filename of the form `<ts>-<ns>-<16hex>.json` where `<16hex>`
is the first 16 hex chars of sha256(file_bytes.rstrip(b"\\n")).
Both the Python and Rust producers strip exactly one trailing newline,
so this single check covers both writers without coupling to either's
JSON serialization choices.
2. Parse as JSON with a dict body containing schema_version==1 and a
dict `entry` carrying string category/title/content.
The hash check rejects tampered/poisoned files (e.g. a file dropped into
the inbox with a hand-crafted payload that does not match its filename).
On validation failure the file is treated by the caller as `.rejected`.
"""
try:
raw_bytes = path.read_bytes()
except OSError as exc:
return False, f"read_error:{exc}", None
expected_hash = _inbox_filename_hash(path)
if expected_hash is None:
return False, "filename_format_invalid", None
# Producers append exactly one trailing newline; strip CRLF (Windows
# legacy) and bare LF so files survive any cross-platform transport.
if raw_bytes.endswith(b"\r\n"):
stripped = raw_bytes[:-2]
elif raw_bytes.endswith(b"\n"):
stripped = raw_bytes[:-1]
else:
stripped = raw_bytes
actual_hash = hashlib.sha256(stripped).hexdigest()[:16]
if actual_hash != expected_hash:
return False, f"hash_mismatch:{actual_hash}!={expected_hash}", None
try:
payload = json.loads(stripped.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
return False, f"json_decode_error:{exc}", None
if not isinstance(payload, dict):
return False, "payload_not_object", None
if payload.get("schema_version") != 1:
return False, f"schema_version!=1 got={payload.get('schema_version')!r}", None
entry = payload.get("entry")
if not isinstance(entry, dict):
return False, "entry_not_object", None
for required in ("category", "title", "content"):
if not isinstance(entry.get(required), str) or not entry.get(required):
return False, f"missing_field:{required}", None
return True, None, payload
def flush_learn_inbox(
limit: int = 100,
min_age_s: float | None = None,
per_entry_timeout_s: float | None = None,
wall_budget_s: float | None = None,
) -> dict:
"""Replay queued learn writes in FIFO order by mtime.
Args:
limit: maximum number of files to process this call.
min_age_s: when set, only process files whose mtime is at least this
many seconds in the past. Used by auto-flush retry-stale-only mode
(`SK_AUTOFLUSH_MAX_AGE_S`); unset = process all ages.
per_entry_timeout_s: soft per-entry budget. Replay itself is not
cancellable (SQLite call), but elapsed >= budget causes the loop
to stop scheduling new entries.
wall_budget_s: soft total budget across all entries.
Returns dict with status, processed, remaining, failed, rejected counts.
Backwards-compatible — additional `rejected` key is new (defaults to 0).
"""
if not LEARN_INBOX.exists():
return {
"status": "ok",
"processed": 0,
"remaining": 0,
"failed": 0,
"rejected": 0,
"cerebrum_failed": 0,
}
# FIFO by mtime (DoD #573). Falls back to name if mtime is unavailable.
def _sort_key(p: Path) -> tuple[float, str]:
try:
return (p.stat().st_mtime, p.name)
except OSError:
return (0.0, p.name)
files = sorted(LEARN_INBOX.glob("*.json"), key=_sort_key)
now = time.time()
if min_age_s is not None and min_age_s > 0:
files = [p for p in files if (now - _sort_key(p)[0]) >= min_age_s]
processed = 0
failed = 0
rejected = 0
cerebrum_failed = 0
busy = False
started = time.monotonic()
for path in files[: max(0, limit)]:
if wall_budget_s is not None and (time.monotonic() - started) >= wall_budget_s:
break
ok, reason, payload = _validate_inbox_file(path)
if not ok:
try:
path.rename(path.with_suffix(path.suffix + ".rejected"))
except OSError:
pass
rejected += 1
continue
entry_started = time.monotonic()
try:
_, cerebrum_rc = _replay_queued_payload(payload)
path.unlink()
processed += 1
if cerebrum_rc != 0:
cerebrum_failed += 1
except sqlite3.OperationalError as exc:
if _is_busy_error(exc):
busy = True
break
failed += 1
try:
path.rename(path.with_suffix(path.suffix + ".failed"))
except OSError:
pass
except Exception:
failed += 1
try:
path.rename(path.with_suffix(path.suffix + ".failed"))
except OSError:
pass
if per_entry_timeout_s is not None and (time.monotonic() - entry_started) >= per_entry_timeout_s:
# Soft budget exceeded for this entry: stop scheduling new work.
break
remaining = len(list(LEARN_INBOX.glob("*.json"))) if LEARN_INBOX.exists() else 0
return {
"status": "busy" if busy else "ok",
"processed": processed,
"remaining": remaining,
"failed": failed,
"rejected": rejected,
"cerebrum_failed": cerebrum_failed,
}
# Wing auto-detection rules: tag patterns → wing
_WING_RULES = [
(
{
"lambda",
"dynamodb",
"sqs",
"cdk",
"api",
"cognito",
"s3",
"eventbridge",
"cloudwatch",
"sns",
"websocket",
"nefoap",
"database",
"sql",
"sqlite",
"postgres",
"mysql",
"mongo",
"redis",
"rest",
"graphql",
"http",
"webhook",
"grpc",
"microservice",
"endpoint",
"server",
},
"backend",
),
(
{
"expo",
"react",
"react-native",
"screen",
"component",
"css",
"ui",
"navigation",
"hook",
"vue",
"angular",
"svelte",
"tailwind",
"nextjs",
"nuxt",
},
"frontend",
),
(
{"jest", "playwright", "e2e", "test", "testing", "coverage", "pytest", "vitest", "unittest", "mock", "fixture"},
"testing",
),
(
{
"vpc",
"cloudwatch",
"cdk",
"cloudformation",
"infrastructure",
"deploy",
"pipeline",
"kubernetes",
"helm",
"terraform",
"ansible",
"k8s",
},
"infrastructure",
),
(
{
"git",
"ci",
"cd",
"docker",
"devops",
"proxy",
"tls",
"npm",
"yarn",
"package-manager",
"github-actions",
"gitlab-ci",
"makefile",
"build",
},
"devops",
),
(
{
"typescript",
"javascript",
"eslint",
"prettier",
"i18n",
"mermaid",
"openapi",
"python",
"rust",
"golang",
"java",
"kotlin",
"swift",
},
"shared",
),
({"knowledge", "memory", "briefing", "learn", "recall", "extract", "session", "sk", "session-knowledge"}, "memory"),
]
# Room auto-detection rules: tag/title patterns → room
_ROOM_RULES = [
({"patient", "patient-search", "傷病者"}, "patient"),
({"hospital", "病院"}, "hospital"),
({"copytogroup", "copy-to-group", "傷病者追加"}, "copyToGroup"),
({"websocket", "ws"}, "websocket"),
({"dynamodb", "dao", "repository"}, "dynamodb"),
({"auth", "cognito", "login"}, "auth"),
({"s3", "media", "upload", "presigned"}, "s3-media"),
({"sqs", "queue", "consumer"}, "sqs"),
({"notification", "通知"}, "notification"),
({"audit", "audit-log"}, "audit-log"),
({"nefoap", "指令"}, "nefoap"),
({"lambda", "handler"}, "lambda"),
({"playwright", "e2e"}, "e2e"),
({"excel", "spreadsheet", "tsv", "csv"}, "data-export"),
({"cdk", "cloudformation", "stack"}, "cdk"),
({"sqlite", "postgres", "mysql", "mongo", "redis", "database", "sql"}, "database"),
({"rest", "graphql", "api", "endpoint", "http", "webhook"}, "api"),
({"kubernetes", "helm", "k8s", "pod", "deployment"}, "kubernetes"),
({"knowledge", "memory", "briefing", "learn", "recall"}, "memory"),
({"session", "session-knowledge", "sk"}, "session"),
({"docker", "dockerfile", "container", "compose"}, "docker"),
({"github-actions", "gitlab-ci", "pipeline", "ci", "cd"}, "ci-cd"),
({"typescript", "javascript", "eslint", "prettier"}, "js-ts"),
({"python", "pip", "venv", "conda"}, "python"),
({"rust", "cargo", "tokio", "wasm"}, "rust"),
]
def _detect_recurrence(db: sqlite3.Connection, entry_id: int, category: str) -> bool:
"""Return True if this entry was already served in the current session (recurrence)."""
if category != "mistake":
return False
try:
rows = db.execute(
"SELECT selected_entry_ids FROM recall_events "
"WHERE created_at > unixepoch('now', '-8 hours') "
"ORDER BY created_at DESC LIMIT 20"
).fetchall()
for row in rows:
if row[0]:
try:
ids = json.loads(row[0])
if entry_id in ids or str(entry_id) in ids:
return True
except (json.JSONDecodeError, TypeError):
pass
except Exception:
pass
return False
def _handle_recurrence(db: sqlite3.Connection, entry_id: int) -> None:
"""Escalate entry to P0 and tag as recurring if recurrence_count >= 2."""
db.execute(
"UPDATE knowledge_entries SET recurrence_count = recurrence_count + 1 WHERE id = ?",
(entry_id,),
)
row = db.execute(
"SELECT recurrence_count, tags, priority FROM knowledge_entries WHERE id = ?",
(entry_id,),
).fetchone()
if not row:
return
count, tags, priority = row
if count >= 2:
new_tags = tags or ""
if "recurring" not in new_tags:
new_tags = (new_tags + ",recurring").strip(",")
db.execute(
"UPDATE knowledge_entries SET priority = 'P0', tags = ? WHERE id = ?",
(new_tags, entry_id),
)
print(f"⚠️ Recurrence detected (count={count})! Entry #{entry_id} escalated to P0 with tag 'recurring'.")
db.commit()
def _detect_wing(tags: str, title: str, content: str) -> str:
"""Auto-detect wing from tags/title/content."""
tag_set = {t.strip().lower() for t in tags.split(",") if t.strip()}
text_lower = f"{title} {content[:200]}".lower()
for patterns, wing in _WING_RULES:
if tag_set & patterns:
return wing
if any(p in text_lower for p in patterns):
return wing
return ""
def _detect_room(tags: str, title: str, content: str) -> str:
"""Auto-detect room from tags/title/content."""
tag_set = {t.strip().lower() for t in tags.split(",") if t.strip()}
text_lower = f"{title} {content[:300]}".lower()
for patterns, room in _ROOM_RULES:
if tag_set & patterns:
return room
if any(p in text_lower for p in patterns):
return room
return ""
# 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",
}
)
# Injection scanning patterns (inspired by Hermes Agent memory security)
# Block prompt injection, role hijacking, credential exfiltration, invisible Unicode
# WBS-019: expanded with JWT, bearer, and AWS-like secret patterns
import re
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 _INJECTION_PATTERNS.
"""
_HEX_RE = re.compile(r"(?<![A-Za-z0-9])([0-9a-f]{40,})(?![A-Za-z0-9])")
# Keywords that indicate the hex string is a commit SHA or checksum reference,
# not a raw secret. Checked in the 100-char window *before* the hex run.
_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 # preceded by commit/hash/checksum keyword — likely legitimate
return m # no safe context — treat as potential credential
return None
_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"),
# Issue #691: GitHub personal/oauth/user/server/refresh access tokens
(
re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"),
"credential leak: GitHub access token",
),
# WBS-019: JWT tokens (3-part base64url separated by dots, header starts with eyJ)
(
re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),
"credential leak: JWT token",
),
# WBS-019: Authorization header with bearer token
(
re.compile(r"(?i)\bAuthorization\s*:\s*Bearer\s+\S{16,}"),
"credential leak: Authorization Bearer token",
),
# WBS-019: AWS-style secret keys (AKIA... access key or 40-char base62 secret)
(
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)
# See _ContextAwareHexMatcher below for the false-positive mitigation logic.
(
_ContextAwareHexMatcher(),
"credential leak: long hex secret/token",
),
]
_CODE_LANGUAGE_MAP = {
".py": "python",
".js": "javascript",
".jsx": "jsx",
".ts": "typescript",
".tsx": "tsx",
".go": "go",
".rs": "rust",
".java": "java",
".kt": "kotlin",
".swift": "swift",
".sh": "bash",
".md": "markdown",
}
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 extract_concept_tags(text: str, top_k: int = 5) -> list:
"""Extract top_k concept tags from text using pure-stdlib term frequency.
Distinct from existing tag parsing that reads explicit user-supplied tags.
This performs automatic keyword extraction from free-form text using
stopword-filtered term frequency, with no numpy/sklearn/ML imports.
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 []
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
ranked = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
return [tag for tag, _ in ranked[:top_k]]
def _auto_tag_entry(db: sqlite3.Connection, entry_id: int, title: str, content: str) -> None:
"""Insert auto-generated concept tags for an entry, replacing any stale auto tags.
Safe to call for both insert and update paths:
- On update: deletes existing source='auto' rows first, then inserts fresh tags.
- On insert: simply inserts fresh tags (no prior rows exist).
- Gracefully no-ops if the entry_concept_tags table does not exist yet.
"""
try:
has_table = db.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='entry_concept_tags'"
).fetchone()
if not has_table:
return
tags = extract_concept_tags(f"{title} {content}", top_k=5)
if not tags:
return
now = time.strftime("%Y-%m-%dT%H:%M:%S")
# Atomic delete-then-insert via SAVEPOINT so a failed insert cannot
# commit the deletion and silently erase existing tags.
db.execute("SAVEPOINT _auto_tag")
try:
db.execute(
"DELETE FROM entry_concept_tags WHERE entry_id = ? AND source = 'auto'",
(entry_id,),
)
db.executemany(
"""
INSERT INTO entry_concept_tags (entry_id, tag, source, tagged_at)
VALUES (?, ?, 'auto', ?)
ON CONFLICT(entry_id, tag) DO UPDATE SET tagged_at = excluded.tagged_at
""",
[(entry_id, tag, now) for tag in tags],
)
db.execute("RELEASE _auto_tag")
except Exception:
db.execute("ROLLBACK TO _auto_tag")
db.execute("RELEASE _auto_tag")
except Exception:
pass # Never break add_entry convergence for tagging failures
def _knowledge_stable_id(session_id: str, category: str, title: str, topic_key: str = "") -> str:
return _stable_sha256("knowledge", session_id or "", category or "", title or "", topic_key or "")
def _default_local_replica_id() -> str:
host = os.environ.get("HOSTNAME") or os.environ.get("COMPUTERNAME") or ""