forked from stephenschoettler/hermes-lcm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
1615 lines (1476 loc) · 67.3 KB
/
Copy pathcommand.py
File metadata and controls
1615 lines (1476 loc) · 67.3 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
"""Slash-style /lcm command helpers for Hermes."""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import os
import sqlite3
from typing import Any
from .db_bootstrap import (
external_content_fts_needs_repair,
inspect_lcm_schema_health,
repair_external_content_fts,
)
from .ingest_protection import externalized_payload_stats, scan_sqlite_payload_risks, sensitive_pattern_status
from .dag import build_nodes_fts_spec
from .presets import (
explicit_operator_overrides,
get_preset,
invalid_operator_overrides,
preset_env_diff,
shipped_presets,
suggest_preset_for_engine,
unsupported_runtime_fields_text,
)
from .session_patterns import build_session_match_keys, matches_session_pattern
from .store import build_message_fts_spec
def _state_db_path_for_engine(engine) -> Path:
hermes_home = getattr(engine, "_hermes_home", "") or ""
if hermes_home:
resolved = Path(hermes_home).expanduser().resolve() / "state.db"
# Check containment within allowed base only when restriction is active
env_base = os.environ.get("LCM_HERMES_BASE_DIR")
if env_base:
allowed_base = Path(env_base).expanduser().resolve()
try:
resolved.relative_to(allowed_base)
except ValueError:
raise ValueError(
f"hermes_home {hermes_home} resolves to {resolved} which is not within allowed base {allowed_base}"
)
return resolved
db_path = Path(getattr(engine._store, "db_path", Path.home() / ".hermes" / "lcm.db"))
return db_path.parent / "state.db"
def _has_lifecycle_fragmentation(stats: dict[str, Any]) -> bool:
direct_mismatch_keys = (
"lifecycle_current_missing_in_lcm_any",
"lifecycle_last_finalized_missing_in_lcm_any",
"lifecycle_current_missing_in_state",
"lifecycle_last_finalized_missing_in_state",
"lcm_message_sessions_missing_in_state",
"lcm_node_sessions_missing_in_state",
)
lifecycle_rows = int(stats.get("lifecycle_rows", 0) or 0)
missing_lifecycle_reference_keys = (
"message_sessions_without_lifecycle_reference",
"node_sessions_without_lifecycle_reference",
)
return (
any(int(stats.get(key, 0) or 0) > 0 for key in direct_mismatch_keys)
or (
lifecycle_rows > 0
and any(int(stats.get(key, 0) or 0) > 0 for key in missing_lifecycle_reference_keys)
)
or (bool(stats.get("state_db_checked")) and bool(stats.get("state_db_error")))
)
def _fmt_bool(value: Any) -> str:
return "yes" if bool(value) else "no"
def _fmt_size(num_bytes: int) -> str:
if num_bytes < 1024:
return f"{num_bytes} B"
units = ["B", "KB", "MB", "GB", "TB"]
value = float(num_bytes)
unit = 0
while value >= 1024 and unit < len(units) - 1:
value /= 1024
unit += 1
precision = 0 if value >= 100 else 1 if value >= 10 else 2
return f"{value:.{precision}f} {units[unit]}"
def _help_text(error: str | None = None) -> str:
lines = []
if error:
lines.append(error)
lines.append("")
lines.extend([
"LCM command help",
"- /lcm or /lcm status: show current LCM runtime/session status",
"- /lcm doctor: run read-only LCM health checks",
"- /lcm doctor clean: best-effort scan of obvious junk/noise session candidates without deleting anything",
"- /lcm doctor clean apply: backup-first cleanup for safe pattern-matched candidates only",
"- /lcm doctor repair: read-only scan for SQLite/FTS index repair needs",
"- /lcm doctor repair apply: backup-first repair/rebuild of message and summary FTS indexes",
"- /lcm doctor source: read-only scan for legacy blank-source rows",
"- /lcm doctor source apply: backup-first normalization of legacy blank-source rows to unknown",
"- /lcm doctor retention: read-only retention analysis for stored session footprint and age",
"- /lcm backup: create a timestamped SQLite backup before any future cleanup workflow",
"- /lcm rotate: preview a tail-preserving in-place compact of the active session (read-only)",
"- /lcm rotate apply: backup-first rotate that advances the lifecycle frontier past pre-tail raw messages",
"- /lcm preset show [name]: inspect shipped preset metadata and benchmark provenance",
"- /lcm preset suggest: preview the best shipped preset for the current engine state",
"- /lcm preset apply <name> --dry-run: preview env-var changes without mutating live config",
"- /lcm help: show this help",
])
return "\n".join(lines)
def _status_text(engine) -> str:
status = engine.get_status()
db_path = Path(engine._store.db_path)
db_exists = db_path.exists()
db_size = db_path.stat().st_size if db_exists else 0
session_bound = bool(engine.current_session_id)
source_stats = status.get("source_lineage") or {}
runtime_identity = status.get("runtime_identity") or {}
source_stats = {
"messages_total": int(source_stats.get("messages_total", 0) or 0),
"attributed_messages": int(source_stats.get("attributed_messages", 0) or 0),
"normalized_unknown_messages": int(source_stats.get("normalized_unknown_messages", 0) or 0),
"legacy_blank_source_messages": int(source_stats.get("legacy_blank_source_messages", 0) or 0),
"effective_unknown_messages": int(source_stats.get("effective_unknown_messages", 0) or 0),
**({"error": source_stats.get("error")} if source_stats.get("error") else {}),
}
protection = status.get("ingest_protection") or sensitive_pattern_status(engine._config)
lines = [
"LCM status",
f"engine: {status.get('engine', engine.name)}",
f"plugin_name: {runtime_identity.get('plugin_name', '(unknown)')}",
f"plugin_version: {runtime_identity.get('plugin_version', '(unknown)')}",
f"plugin_path: {runtime_identity.get('plugin_path', '(unknown)')}",
f"module_path: {runtime_identity.get('module_path', '(unknown)')}",
f"plugin_git_commit: {runtime_identity.get('plugin_git_commit') or '(unavailable)'}",
f"plugin_git_branch: {runtime_identity.get('plugin_git_branch') or '(unavailable)'}",
f"plugin_git_dirty: {runtime_identity.get('plugin_git_dirty') if runtime_identity.get('plugin_git_dirty') is not None else '(unavailable)'}",
f"hermes_home: {runtime_identity.get('hermes_home', '') or '(unset)'}",
f"session_id: {engine.current_session_id or '(unbound)'}",
f"session_platform: {engine.current_session_platform or ('(unbound)' if not session_bound else '(unknown)')}",
f"database_path: {db_path}",
f"database_path_source: {runtime_identity.get('database_path_source', '(unknown)')}",
f"database_exists: {_fmt_bool(db_exists)}",
f"database_size: {_fmt_size(db_size) if db_exists else 'missing'}",
f"compression_count: {engine.compression_count}",
f"last_compression_status: {status.get('last_compression_status', 'idle')}",
f"last_compression_noop_reason: {status.get('last_compression_noop_reason', '') or '(none)'}",
f"threshold_tokens: {engine.threshold_tokens if session_bound else '(uninitialized)'}",
f"cache_metrics_available: {_fmt_bool(status.get('cache_metrics_available'))}",
f"last_input_tokens: {status.get('last_input_tokens', 0)}",
f"last_output_tokens: {status.get('last_output_tokens', 0)}",
f"last_cache_read_tokens: {status.get('last_cache_read_tokens', 0)}",
f"last_cache_write_tokens: {status.get('last_cache_write_tokens', 0)}",
f"last_reasoning_tokens: {status.get('last_reasoning_tokens', 0)}",
f"cache_read_ratio: {float(status.get('cache_read_ratio', 0.0) or 0.0) * 100:.1f}%",
f"sensitive_patterns_enabled: {_fmt_bool(protection.get('enabled'))}",
f"sensitive_patterns: {', '.join(protection.get('patterns') or []) or '(none)'}",
f"sensitive_patterns_source: {protection.get('source', 'default')}",
# Filter classification for current_session_id (the foreground view).
# When a side channel is in flight, get_status() reports the bound
# session's flags; we read the engine properties instead so this row
# stays consistent with the session_id row above.
f"session_ignored: {_fmt_bool(engine.current_session_ignored)}",
f"session_stateless: {_fmt_bool(engine.current_session_stateless)}",
f"side_channel_active: {_fmt_bool(engine.side_channel_active)}",
f"conversation_id: {runtime_identity.get('conversation_id', '') or '(unbound)'}",
f"lifecycle_current_session_id: {runtime_identity.get('lifecycle_current_session_id', '') or '(none)'}",
f"lifecycle_last_finalized_session_id: {runtime_identity.get('lifecycle_last_finalized_session_id', '') or '(none)'}",
f"source_messages_total: {source_stats['messages_total']}",
f"source_attributed_messages: {source_stats['attributed_messages']}",
f"source_unknown_messages: {source_stats['normalized_unknown_messages']}",
f"source_legacy_blank_messages: {source_stats['legacy_blank_source_messages']}",
f"source_effective_unknown_messages: {source_stats['effective_unknown_messages']}",
]
last_rotate_at = status.get("last_rotate_at")
if last_rotate_at:
lines.append(
f"last_rotate_at: "
f"{datetime.fromtimestamp(float(last_rotate_at), tz=timezone.utc).isoformat(timespec='seconds')}"
)
rotate_backup_size = int(status.get("rotate_backup_size", 0) or 0)
if rotate_backup_size:
lines.append(f"rotate_backup_size: {_fmt_size(rotate_backup_size)}")
else:
lines.append("last_rotate_at: (never)")
if status.get("rotate_backup_path"):
lines.append(f"rotate_backup_path: {status['rotate_backup_path']}")
if session_bound:
lines.extend([
f"store_messages: {status.get('store_messages', 0)}",
f"dag_nodes: {status.get('dag_nodes', 0)}",
])
else:
lines.append(
"note: no active Hermes session has initialized LCM in this process yet — after a fresh restart, send one normal message first if you want live per-session runtime details"
)
if "ignore_session_patterns_source" in status:
lines.append(
f"ignore_session_patterns_source: {status.get('ignore_session_patterns_source')}"
)
if "stateless_session_patterns_source" in status:
lines.append(
f"stateless_session_patterns_source: {status.get('stateless_session_patterns_source')}"
)
if source_stats.get("error"):
lines.append(f"source_lineage_error: {source_stats['error']}")
return "\n".join(lines)
def _scan_clean_candidates(engine) -> dict[str, Any]:
conn = engine._store._conn
try:
rows = conn.execute(
"""
WITH session_ids AS (
SELECT session_id FROM messages
UNION
SELECT session_id FROM summary_nodes
),
message_stats AS (
SELECT session_id,
COUNT(*) AS message_count,
COALESCE(SUM(token_estimate), 0) AS token_total
FROM messages
GROUP BY session_id
),
node_stats AS (
SELECT session_id, COUNT(*) AS node_count
FROM summary_nodes
GROUP BY session_id
)
SELECT s.session_id,
COALESCE(m.message_count, 0) AS message_count,
COALESCE(m.token_total, 0) AS token_total,
COALESCE(n.node_count, 0) AS node_count
FROM session_ids s
LEFT JOIN message_stats m ON m.session_id = s.session_id
LEFT JOIN node_stats n ON n.session_id = s.session_id
ORDER BY s.session_id
"""
).fetchall()
except Exception as exc: # pragma: no cover - defensive
return {
"error": str(exc),
"candidates": [],
"ignored_count": 0,
"stateless_count": 0,
"protected_count": 0,
}
candidates = []
ignored_count = 0
stateless_count = 0
protected_count = 0
for session_id, message_count, token_total, node_count in rows:
keys = build_session_match_keys(session_id)
matched_classes = []
if matches_session_pattern(keys, engine._compiled_ignore_session_patterns):
matched_classes.append("ignored-pattern")
ignored_count += 1
elif matches_session_pattern(keys, engine._compiled_stateless_session_patterns):
matched_classes.append("stateless-pattern")
stateless_count += 1
if not matched_classes:
continue
# Protect the actively-bound session from cleanup, not the foreground
# view. While a cron tick has rebound the engine, _session_id points
# at the cron session and the engine is actively writing through it
# via lifecycle hooks; deleting that data mid-flight would corrupt
# the cleanup pass. current_session_id (foreground) is the wrong
# field here.
if session_id == getattr(engine, "_session_id", ""):
protected_count += 1
continue
candidates.append(
{
"session_id": session_id,
"classes": matched_classes,
"message_count": int(message_count),
"node_count": int(node_count),
"token_total": int(token_total),
}
)
return {
"error": None,
"candidates": candidates,
"ignored_count": ignored_count,
"stateless_count": stateless_count,
"protected_count": protected_count,
}
def _scan_retention_candidates(engine) -> dict[str, Any]:
conn = engine._store._conn
now = datetime.now().timestamp()
# SQL is scoped to the foreground session so /lcm doctor retention
# reports the operator's real conversation rather than whatever side
# channel (cron tick, debug probe) currently owns engine._session_id.
# The "protected" flag below still keys off engine._session_id (the
# actively-bound row) because that is the row receiving live writes
# from the concurrent run.
session_id = engine.current_session_id
if not session_id:
return {
"error": None,
"sessions": [],
"sessions_analyzed": 0,
"stale_sessions_30d": 0,
"stale_sessions_90d": 0,
"retained_tokens_30d": 0,
"retained_tokens_90d": 0,
"protected_count": 0,
}
try:
rows = conn.execute(
"""
WITH session_ids AS (
SELECT session_id FROM messages
UNION
SELECT session_id FROM summary_nodes
),
message_stats AS (
SELECT session_id,
COUNT(*) AS message_count,
COALESCE(SUM(token_estimate), 0) AS token_total,
MIN(timestamp) AS first_message_at,
MAX(timestamp) AS last_message_at
FROM messages
GROUP BY session_id
),
node_stats AS (
SELECT session_id,
COUNT(*) AS node_count,
COALESCE(SUM(token_count), 0) AS node_token_total,
MIN(COALESCE(earliest_at, created_at)) AS first_node_at,
MAX(COALESCE(latest_at, created_at)) AS last_node_at
FROM summary_nodes
GROUP BY session_id
)
SELECT s.session_id,
COALESCE(m.message_count, 0) AS message_count,
COALESCE(m.token_total, 0) AS token_total,
COALESCE(n.node_count, 0) AS node_count,
COALESCE(n.node_token_total, 0) AS node_token_total,
m.first_message_at,
m.last_message_at,
n.first_node_at,
n.last_node_at
FROM session_ids s
LEFT JOIN message_stats m ON m.session_id = s.session_id
LEFT JOIN node_stats n ON n.session_id = s.session_id
WHERE s.session_id = ?
ORDER BY s.session_id
""",
(session_id,),
).fetchall()
except Exception as exc: # pragma: no cover - defensive
return {
"error": str(exc),
"sessions": [],
"sessions_analyzed": 0,
"stale_sessions_30d": 0,
"stale_sessions_90d": 0,
"retained_tokens_30d": 0,
"retained_tokens_90d": 0,
"protected_count": 0,
}
sessions = []
protected_count = 0
stale_sessions_30d = 0
stale_sessions_90d = 0
retained_tokens_30d = 0
retained_tokens_90d = 0
for row in rows:
(
session_id,
message_count,
token_total,
node_count,
node_token_total,
first_message_at,
last_message_at,
first_node_at,
last_node_at,
) = row
timestamps = [
ts for ts in (first_message_at, last_message_at, first_node_at, last_node_at)
if ts is not None
]
if not timestamps:
continue
first_activity_at = min(float(ts) for ts in (first_message_at, first_node_at) if ts is not None)
last_activity_at = max(float(ts) for ts in (last_message_at, last_node_at) if ts is not None)
age_days = max(0.0, (now - last_activity_at) / 86400.0)
# Bound (not foreground): protect the live session from retention
# bookkeeping while the engine may still be writing to it.
protected = session_id == getattr(engine, "_session_id", "")
total_footprint_tokens = int(token_total) + int(node_token_total)
if protected:
protected_count += 1
if age_days >= 30.0:
stale_sessions_30d += 1
retained_tokens_30d += total_footprint_tokens
if age_days >= 90.0:
stale_sessions_90d += 1
retained_tokens_90d += total_footprint_tokens
sessions.append(
{
"session_id": session_id,
"protected": protected,
"message_count": int(message_count),
"node_count": int(node_count),
"token_total": total_footprint_tokens,
"raw_token_total": int(token_total),
"summary_token_total": int(node_token_total),
"first_activity_at": float(first_activity_at),
"last_activity_at": float(last_activity_at),
"age_days": age_days,
}
)
sessions.sort(
key=lambda item: (
1 if item["protected"] else 0,
0 if item["age_days"] >= 30.0 else 1,
-item["token_total"],
-item["node_count"],
-item["message_count"],
item["last_activity_at"],
item["session_id"],
)
)
return {
"error": None,
"sessions": sessions,
"sessions_analyzed": len(sessions),
"stale_sessions_30d": stale_sessions_30d,
"stale_sessions_90d": stale_sessions_90d,
"retained_tokens_30d": retained_tokens_30d,
"retained_tokens_90d": retained_tokens_90d,
"protected_count": protected_count,
}
def _flush_engine_connections(engine) -> None:
"""Commit pending writes on every SQLite connection the engine owns.
Shared by ``_backup_database`` (timestamped backup) and
``_rotate_backup_database`` (rolling backup) so the connection-flush
contract stays in one place.
"""
engine._store._conn.commit()
engine._dag._conn.commit()
lifecycle_conn = getattr(getattr(engine, "_lifecycle", None), "_conn", None)
if lifecycle_conn is not None:
lifecycle_conn.commit()
def _backup_database(engine) -> dict[str, Any]:
db_path = Path(engine._store.db_path)
if not db_path.exists():
return {
"ok": False,
"db_path": db_path,
"error": "database file does not exist",
}
backup_dir = engine.backup_dir()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = backup_dir / f"{db_path.stem}-{timestamp}.sqlite3"
try:
backup_dir.mkdir(parents=True, exist_ok=True)
_flush_engine_connections(engine)
dest = sqlite3.connect(str(backup_path))
try:
engine._store._conn.backup(dest)
finally:
dest.close()
except (OSError, sqlite3.Error) as exc:
return {
"ok": False,
"db_path": db_path,
"error": str(exc),
}
backup_size = backup_path.stat().st_size if backup_path.exists() else 0
return {
"ok": True,
"db_path": db_path,
"backup_path": backup_path,
"backup_size": backup_size,
}
def _rotate_backup_database(engine) -> dict[str, Any]:
"""Write a rolling rotate-latest SQLite snapshot of the LCM store.
Atomic via tmp-then-rename so the slot is never half-written. Unlike
``_backup_database`` which produces timestamped files, this overwrites a
single rolling slot so disk usage stays bounded across repeated rotates.
"""
db_path = Path(engine._store.db_path)
if not db_path.exists():
return {
"ok": False,
"db_path": db_path,
"error": "database file does not exist",
}
backup_path = engine.rotate_backup_path()
backup_dir = backup_path.parent
tmp_path = backup_path.with_name(backup_path.name + ".tmp")
try:
backup_dir.mkdir(parents=True, exist_ok=True)
_flush_engine_connections(engine)
if tmp_path.exists():
tmp_path.unlink()
dest = sqlite3.connect(str(tmp_path))
try:
engine._store._conn.backup(dest)
finally:
dest.close()
# Atomic replace so the rolling slot is never half-written.
tmp_path.replace(backup_path)
except (OSError, sqlite3.Error) as exc:
# Best-effort cleanup of the tmp file if something failed midway.
try:
if tmp_path.exists():
tmp_path.unlink()
except OSError:
pass
return {
"ok": False,
"db_path": db_path,
"backup_path": backup_path,
"error": str(exc),
}
backup_size = backup_path.stat().st_size if backup_path.exists() else 0
return {
"ok": True,
"db_path": db_path,
"backup_path": backup_path,
"backup_size": backup_size,
}
def _rotate_text(engine) -> str:
preview = engine.rotate_active_session(apply=False)
if not preview.get("ok"):
reason = preview.get("reason", "unknown")
lines = [
"LCM rotate",
"status: refused",
f"reason: {reason}",
]
session_id = preview.get("session_id")
if session_id:
lines.append(f"session_id: {session_id}")
lines.append("note: read-only preview — no changes were made")
return "\n".join(lines)
backup_path = engine.rotate_backup_path()
lines = [
"LCM rotate",
f"status: {'noop' if preview.get('noop') else 'preview'}",
f"session_id: {preview['session_id']}",
f"conversation_id: {preview['conversation_id']}",
f"total_message_count: {preview['total_message_count']}",
f"fresh_tail_count: {preview['fresh_tail_count']}",
f"pre_tail_message_count: {preview.get('pre_tail_message_count', 0)}",
f"current_frontier_store_id: {preview['current_frontier_store_id']}",
f"new_frontier_store_id: {preview['new_frontier_store_id']}",
f"rotate_backup_path: {backup_path}",
]
if preview.get("noop"):
lines.append(f"reason: {preview.get('reason', 'no_change')}")
lines.append("note: read-only preview — rotate apply would be a no-op for this session")
else:
lines.append("note: read-only preview — use `/lcm rotate apply` to advance the frontier (backup-first)")
lines.append("note: pre-tail raw messages remain in the store and recoverable via lcm_load_session")
return "\n".join(lines)
def _rotate_apply_text(engine) -> str:
# Pre-flight refusal AND noop check before touching disk. This avoids
# both writing a backup for a session that would refuse and overwriting
# the previous known-good rolling backup when the apply would be a no-op
# (e.g., idempotent rerun on an already-rotated session).
pre = engine.rotate_active_session(apply=False)
if not pre.get("ok"):
reason = pre.get("reason", "unknown")
lines = [
"LCM rotate apply",
"status: refused",
f"reason: {reason}",
]
session_id = pre.get("session_id")
if session_id:
lines.append(f"session_id: {session_id}")
lines.append("note: rotate apply refused; no backup was created and no lifecycle state was changed")
return "\n".join(lines)
if pre.get("noop"):
# Surface the same shape as a successful apply but with status:noop so
# operators get the standard fields without a fresh backup write
# destroying the previous known-good snapshot.
lines = [
"LCM rotate apply",
"status: noop",
f"session_id: {pre['session_id']}",
f"conversation_id: {pre['conversation_id']}",
f"total_message_count: {pre['total_message_count']}",
f"fresh_tail_count: {pre['fresh_tail_count']}",
f"pre_tail_message_count: {pre.get('pre_tail_message_count', 0)}",
f"previous_frontier_store_id: {pre['current_frontier_store_id']}",
f"new_frontier_store_id: {pre['new_frontier_store_id']}",
f"reason: {pre.get('reason', 'no_change')}",
"note: rotate is a no-op; rolling backup was not written so the previous rotate-latest snapshot is preserved",
]
return "\n".join(lines)
backup = _rotate_backup_database(engine)
if not backup["ok"]:
return "\n".join([
"LCM rotate apply",
"status: error",
f"database_path: {backup['db_path']}",
f"error: backup failed: {backup['error']}",
"note: rotate apply aborted before any lifecycle mutation",
])
result = engine.rotate_active_session(apply=True)
if not result.get("ok"):
return "\n".join([
"LCM rotate apply",
"status: refused",
f"reason: {result.get('reason', 'unknown')}",
f"rotate_backup_path: {backup['backup_path']}",
f"rotate_backup_size: {_fmt_size(int(backup['backup_size']))}",
"note: backup was created before rotate refused; lifecycle state unchanged",
])
is_noop = bool(result.get("noop"))
lines = [
"LCM rotate apply",
f"status: {'noop' if is_noop else 'ok'}",
f"session_id: {result['session_id']}",
f"conversation_id: {result['conversation_id']}",
f"rotate_backup_path: {backup['backup_path']}",
f"rotate_backup_size: {_fmt_size(int(backup['backup_size']))}",
f"total_message_count: {result['total_message_count']}",
f"fresh_tail_count: {result['fresh_tail_count']}",
f"pre_tail_message_count: {result.get('pre_tail_message_count', 0)}",
f"previous_frontier_store_id: {result['current_frontier_store_id']}",
f"new_frontier_store_id: {result.get('applied_frontier_store_id', result['new_frontier_store_id'])}",
]
if is_noop:
lines.append(f"reason: {result.get('reason', 'no_change')}")
lines.append("note: lifecycle state already at or ahead of the target frontier")
else:
lines.append("note: pre-tail raw messages remain in the store and recoverable via lcm_load_session")
lines.append("note: rolling backup overwrites the previous rotate-latest slot")
return "\n".join(lines)
def _scan_fts_repair(engine) -> dict[str, Any]:
checks: dict[str, dict[str, Any]] = {}
specs = {
"messages_fts": build_message_fts_spec(),
"nodes_fts": build_nodes_fts_spec(),
}
conn = engine._store._conn
for label, spec in specs.items():
try:
needs_repair = external_content_fts_needs_repair(conn, spec)
content_count = int(conn.execute(
f"SELECT COUNT(*) FROM {spec.content_table}"
).fetchone()[0])
try:
fts_count = int(conn.execute(f"SELECT COUNT(*) FROM {spec.table_name}").fetchone()[0])
except sqlite3.Error:
fts_count = None
checks[label] = {
"ok": not needs_repair,
"needs_repair": needs_repair,
"content_rows": content_count,
"fts_rows": fts_count,
"error": None,
}
except Exception as exc: # pragma: no cover - defensive
checks[label] = {
"ok": False,
"needs_repair": True,
"content_rows": None,
"fts_rows": None,
"error": str(exc),
}
return {
"checks": checks,
"needs_repair": any(item["needs_repair"] for item in checks.values()),
}
def _doctor_repair_text(engine) -> str:
scan = _scan_fts_repair(engine)
lines = [
"LCM doctor repair",
f"status: {'repair-needed' if scan['needs_repair'] else 'ok'}",
]
for label, item in scan["checks"].items():
state = "repair-needed" if item["needs_repair"] else "ok"
lines.append(f"{label}: {state}")
if item["error"]:
lines.append(f"{label}_error: {item['error']}")
else:
lines.append(f"{label}_content_rows: {item['content_rows']}")
lines.append(f"{label}_fts_rows: {item['fts_rows']}")
lines.append("note: read-only scan only — no FTS tables were repaired")
if scan["needs_repair"]:
lines.append("note: use `/lcm doctor repair apply` to create a backup and repair FTS indexes")
return "\n".join(lines)
def _doctor_repair_apply_text(engine) -> str:
backup = _backup_database(engine)
if not backup["ok"]:
return "\n".join([
"LCM doctor repair apply",
"status: error",
f"database_path: {backup['db_path']}",
f"error: backup failed: {backup['error']}",
"note: repair apply aborted before any FTS tables were repaired",
])
conn = engine._store._conn
try:
messages_result = repair_external_content_fts(conn, build_message_fts_spec())
nodes_result = repair_external_content_fts(conn, build_nodes_fts_spec())
except sqlite3.Error as exc:
return "\n".join([
"LCM doctor repair apply",
"status: error",
f"database_path: {backup['db_path']}",
f"backup_path: {backup['backup_path']}",
f"backup_size: {_fmt_size(int(backup['backup_size']))}",
f"error: FTS repair failed: {exc}",
"note: backup was created before repair apply",
])
return "\n".join([
"LCM doctor repair apply",
"status: ok",
f"database_path: {backup['db_path']}",
f"backup_path: {backup['backup_path']}",
f"backup_size: {_fmt_size(int(backup['backup_size']))}",
f"messages_fts_rebuilt: {_fmt_bool(messages_result['rebuilt'])}",
f"messages_fts_triggers_recreated: {_fmt_bool(messages_result['triggers_recreated'])}",
f"messages_fts_degraded: {_fmt_bool(messages_result['degraded'])}",
f"nodes_fts_rebuilt: {_fmt_bool(nodes_result['rebuilt'])}",
f"nodes_fts_triggers_recreated: {_fmt_bool(nodes_result['triggers_recreated'])}",
f"nodes_fts_degraded: {_fmt_bool(nodes_result['degraded'])}",
"note: backup created before repair apply",
])
def _doctor_source_text(engine) -> str:
try:
plan = engine._store.get_source_normalization_plan()
except Exception as exc: # pragma: no cover - defensive
return "\n".join([
"LCM doctor source",
"status: error",
f"error: source-lineage scan failed: {exc}",
"note: read-only scan only — no source rows were updated",
])
stats = plan["stats_before"]
would_update = int(plan["would_update_messages"])
lines = [
"LCM doctor source",
f"status: {'normalization-needed' if would_update else 'ok'}",
f"messages_total: {stats['messages_total']}",
f"attributed_messages: {stats['attributed_messages']}",
f"unknown_messages: {stats['normalized_unknown_messages']}",
f"legacy_blank_messages: {stats['legacy_blank_source_messages']}",
f"effective_unknown_messages: {stats['effective_unknown_messages']}",
f"target_source: {plan['target_source']}",
f"would_update_messages: {would_update}",
f"affected_sessions: {plan['affected_sessions']}",
"note: read-only scan only — no source rows were updated",
]
if would_update:
lines.append(
"note: use `/lcm doctor source apply` to create a backup and normalize legacy blank-source rows"
)
else:
lines.append("note: no legacy blank-source rows need normalization")
return "\n".join(lines)
def _doctor_source_apply_text(engine) -> str:
try:
plan = engine._store.get_source_normalization_plan()
except Exception as exc: # pragma: no cover - defensive
return "\n".join([
"LCM doctor source apply",
"status: error",
f"error: source-lineage scan failed: {exc}",
"note: source normalization apply aborted before any rows were updated",
])
if int(plan["would_update_messages"]) == 0:
stats = plan["stats_before"]
return "\n".join([
"LCM doctor source apply",
"status: ok",
f"target_source: {plan['target_source']}",
"updated_messages: 0",
f"legacy_blank_before: {stats['legacy_blank_source_messages']}",
f"legacy_blank_after: {stats['legacy_blank_source_messages']}",
"note: no legacy blank-source rows needed normalization",
])
backup = _backup_database(engine)
if not backup["ok"]:
return "\n".join([
"LCM doctor source apply",
"status: error",
f"database_path: {backup['db_path']}",
f"error: backup failed: {backup['error']}",
"note: source normalization apply aborted before any rows were updated",
])
try:
result = engine._store.normalize_legacy_blank_sources()
except sqlite3.Error as exc:
return "\n".join([
"LCM doctor source apply",
"status: error",
f"database_path: {backup['db_path']}",
f"backup_path: {backup['backup_path']}",
f"backup_size: {_fmt_size(int(backup['backup_size']))}",
f"error: source normalization failed: {exc}",
"note: backup was created before source normalization apply",
])
before = result["stats_before"]
after = result["stats_after"]
return "\n".join([
"LCM doctor source apply",
"status: ok",
f"database_path: {backup['db_path']}",
f"backup_path: {backup['backup_path']}",
f"backup_size: {_fmt_size(int(backup['backup_size']))}",
f"target_source: {result['target_source']}",
f"updated_messages: {result['updated_messages']}",
f"legacy_blank_before: {before['legacy_blank_source_messages']}",
f"legacy_blank_after: {after['legacy_blank_source_messages']}",
f"unknown_before: {before['normalized_unknown_messages']}",
f"unknown_after: {after['normalized_unknown_messages']}",
"note: backup created before source normalization apply",
])
def _doctor_text(engine) -> str:
db_path = Path(engine._store.db_path)
runtime_identity = engine.get_runtime_identity()
store_conn = engine._store._conn
dag_conn = engine._dag._conn
issues: list[str] = []
schema_health = inspect_lcm_schema_health(store_conn, database_path=str(db_path))
schema_missing_raw = schema_health.get("missing_tables")
schema_missing_tables = [str(name) for name in schema_missing_raw] if isinstance(schema_missing_raw, list) else []
schema_existing_raw = schema_health.get("existing_tables")
schema_existing_tables = [str(name) for name in schema_existing_raw] if isinstance(schema_existing_raw, list) else []
schema_core_status = "error" if schema_health.get("error") else "missing" if schema_missing_tables else "ok"
if schema_missing_tables or schema_health.get("error"):
issues.append("schema_core_tables")
def _safe_count(conn, query: str, issue_key: str) -> int | str:
try:
return int(conn.execute(query).fetchone()[0])
except Exception as exc: # pragma: no cover - defensive
issues.append(issue_key)
return f"error: {exc}"
try:
integrity_row = store_conn.execute("PRAGMA integrity_check").fetchone()
integrity = str(integrity_row[0]) if integrity_row else "unknown"
except Exception as exc: # pragma: no cover - defensive
integrity = f"error: {exc}"
issues.append("sqlite_integrity")
try:
store_fts_count = int(store_conn.execute("SELECT COUNT(*) FROM messages_fts").fetchone()[0])
store_fts = "ok"
except Exception as exc: # pragma: no cover - defensive
store_fts_count = f"error: {exc}"
store_fts = f"error: {exc}"
issues.append("messages_fts")
try:
node_fts_count = int(dag_conn.execute("SELECT COUNT(*) FROM nodes_fts").fetchone()[0])
node_fts = "ok"
except Exception as exc: # pragma: no cover - defensive
node_fts_count = f"error: {exc}"
node_fts = f"error: {exc}"
issues.append("nodes_fts")
total_messages = _safe_count(store_conn, "SELECT COUNT(*) FROM messages", "messages_total")
total_message_sessions = _safe_count(
store_conn,
"SELECT COUNT(DISTINCT session_id) FROM messages",
"message_sessions_total",
)
total_nodes = _safe_count(dag_conn, "SELECT COUNT(*) FROM summary_nodes", "summary_nodes_total")
total_node_sessions = _safe_count(
dag_conn,
"SELECT COUNT(DISTINCT session_id) FROM summary_nodes",
"summary_node_sessions_total",
)
db_exists = db_path.exists()
db_size = db_path.stat().st_size if db_exists else 0
wal_path = Path(str(db_path) + "-wal")
wal_size = wal_path.stat().st_size if wal_path.exists() else 0
try:
journal_row = store_conn.execute("PRAGMA journal_mode").fetchone()
journal_mode = str(journal_row[0]) if journal_row else "unknown"
except Exception as exc: # pragma: no cover - defensive
journal_mode = f"error: {exc}"
issues.append("sqlite_journal_mode")
try:
quick_row = store_conn.execute("PRAGMA quick_check").fetchone()
quick_check = str(quick_row[0]) if quick_row else "unknown"
except Exception as exc: # pragma: no cover - defensive
quick_check = f"error: {exc}"
issues.append("sqlite_quick_check")
try:
payload_risks = scan_sqlite_payload_risks(store_conn)
externalized_stats = externalized_payload_stats(engine._config, hermes_home=engine._hermes_home)
except Exception: # pragma: no cover - defensive
payload_risks = {
"largest_content_rows": [],
"largest_tool_calls_rows": [],
"suspicious_data_uri_content_rows": [],
"suspicious_data_uri_tool_calls_rows": [],
"suspicious_base64_like_rows": [],
"quarantined_assistant_rows": [],
"suspicious_repetitive_assistant_rows": [],
}
externalized_stats = {
"externalized_payload_count": 0,
"externalized_payload_bytes": 0,
"externalized_payload_chars": 0,
"externalized_payload_dir": "",
"latest_externalized_payload_path": "",
"latest_externalized_payload_mtime": 0,
}
issues.append("payload_storage")
clean_scan = _scan_clean_candidates(engine)
debt_rows = []
lifecycle_conn = getattr(getattr(engine, "_lifecycle", None), "_conn", None)
if lifecycle_conn is not None:
try:
debt_rows = lifecycle_conn.execute(
"""
SELECT conversation_id, debt_kind, debt_size_estimate
FROM lcm_lifecycle_state
WHERE debt_kind IS NOT NULL AND debt_size_estimate > 0
ORDER BY updated_at DESC
"""
).fetchall()
except Exception as exc: # pragma: no cover - defensive
issues.append("lifecycle_state")
debt_rows = [(f"error: {exc}", "error", 0)]