Repository navigation
Expand file tree
/
Copy pathcommand.py
More file actions
5079 lines (4750 loc) · 213 KB
/
Copy pathcommand.py
File metadata and controls
5079 lines (4750 loc) · 213 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 dataclasses import dataclass
from datetime import date, datetime, timezone
from enum import Enum
from pathlib import Path
import dataclasses
import json
import math
import os
import re
import sqlite3
import time
from typing import Any
import uuid
from .db_bootstrap import (
check_external_content_fts_integrity,
external_content_fts_needs_repair,
inspect_lcm_schema_health,
join_background_integrity_scans,
load_integrity_failed,
remediate_interim_schema_stamp,
repair_external_content_fts,
)
from .diagnostics import (
_has_lifecycle_fragmentation,
_state_db_path_for_engine,
doctor_guidance_for_checks,
)
from .ingest_protection import (
externalized_payload_stats,
scan_externalized_payload_integrity,
scan_sqlite_payload_risks,
sensitive_pattern_status,
)
from .dag import SummaryDAG, build_nodes_fts_spec
from .presets import (
explicit_operator_overrides,
get_preset,
invalid_operator_overrides,
preset_confidence_reasons,
preset_env_diff,
preset_match_confidence,
shipped_presets,
suggest_preset_for_engine,
unsupported_runtime_fields_text,
)
from .maintenance import backup_database, rotate_backup_database
from .assertion_rebuild import rebuild_assertions
from .assertion_store import AssertionSchemaUnavailableError, AssertionStore
from . import rollup_builder
from .rollup_store import RollupStore
from .session_patterns import build_session_match_keys, matches_session_pattern
from .store import build_message_fts_spec
from .chunking import (
VALID_CONTENT_POLICIES,
chunk_message,
group_by_store_id,
normalize_content_policy,
)
from .embedding_provider import (
EmbeddedDocumentBatch,
EmbeddingProviderError,
FastembedProvider,
ProviderPreDispatchError,
VoyageError,
_VOYAGE_CONTEXT_DOCUMENT_TOKEN_BUDGET,
_VOYAGE_CONTEXT_MAX_CHUNK_TOKENS,
_VOYAGE_CONTEXT_MAX_REQUEST_CHUNKS,
_VOYAGE_CONTEXT_REQUEST_TOKEN_BUDGET,
_VOYAGE_MAX_BATCH_ITEMS,
_is_voyage_context_model,
_plan_contextualized_requests,
default_chunk_model,
fastembed_download_size_note,
resolve_provider,
)
from .tokens import count_tokens
from .vector_store import EmbeddingIdentity, EmbeddingPublishOutcome, VectorStore
_EMBEDDING_BACKFILL_CLAIM_KEY = "lcm_embedding_backfill_claim"
_EMBEDDING_BACKFILL_CLAIM_TTL_S = 10 * 60
_EMBEDDING_BACKFILL_BATCH_SIZE = 32
def _env_float(key: str, default: float) -> float:
raw = os.environ.get(key)
if raw is None:
return default
try:
value = float(raw)
except (TypeError, ValueError):
return default
return value if value >= 0 else default
def _embedding_backfill_lease_ttl_s() -> float:
return _env_float("LCM_EMBEDDING_BACKFILL_LEASE_TTL_S", float(_EMBEDDING_BACKFILL_CLAIM_TTL_S)) or float(
_EMBEDDING_BACKFILL_CLAIM_TTL_S
)
def _embedding_backfill_heartbeat_s() -> float:
# Refresh cadence: renew the lease at most this often during a long run so a
# live owner keeps a lease a second worker would otherwise steal as expired.
return _env_float("LCM_EMBEDDING_BACKFILL_HEARTBEAT_S", 60.0)
def _embedding_backfill_budget_s() -> float:
# Operation-wide wall-clock budget (0 = unlimited). When exceeded the run
# stops between batches and reports partial rather than running unbounded.
return _env_float("LCM_EMBEDDING_BACKFILL_BUDGET_S", 0.0)
def _ensure_inflight_table(conn: sqlite3.Connection) -> None:
expected_columns = (
("embedded_id", "TEXT", 0, None, 1),
("identity_hash", "TEXT", 0, None, 2),
("lease_id", "TEXT", 0, None, 0),
("generation", "INTEGER", 0, None, 0),
("claimed_at", "REAL", 0, None, 0),
("state", "TEXT", 1, "'claimed'", 0),
("request_id", "TEXT", 0, None, 0),
("updated_at", "REAL", 0, None, 0),
("last_error", "TEXT", 0, None, 0),
)
expected_checks = ("statein('claimed','dispatched','uncertain')",)
def normalize_check_expression(expression: str) -> str:
# SQL keywords/identifiers are case-insensitive, but quoted literal
# bytes are not. Preserve literal case and whitespace so e.g.
# 'CLAIMED' or 'claimed ' cannot collide with the canonical CHECK.
normalized: list[str] = []
quote: str | None = None
cursor = 0
while cursor < len(expression):
char = expression[cursor]
if quote is not None:
normalized.append(char)
if quote == "]":
if char == "]":
quote = None
elif char == quote:
if cursor + 1 < len(expression) and expression[cursor + 1] == quote:
cursor += 1
normalized.append(expression[cursor])
else:
quote = None
elif char in {"'", '"', "`"}:
quote = char
normalized.append(char)
elif char == "[":
quote = "]"
normalized.append(char)
elif not char.isspace():
normalized.append(char.lower())
cursor += 1
return "".join(normalized)
def check_expressions(sql: str) -> tuple[str, ...]:
"""Return every normalized CHECK body, including duplicates and order."""
lowered = sql.lower()
expressions: list[str] = []
offset = 0
while True:
match = re.search(r"\bcheck\s*\(", lowered[offset:])
if match is None:
return tuple(expressions)
body_start = offset + match.end()
cursor = body_start
depth = 1
quote: str | None = None
while cursor < len(lowered) and depth:
char = lowered[cursor]
if quote is not None:
if quote == "]":
if char == "]":
quote = None
elif char == quote:
# SQLite escapes quotes by doubling them.
if cursor + 1 < len(lowered) and lowered[cursor + 1] == quote:
cursor += 1
else:
quote = None
elif char in {"'", '"', "`"}:
quote = char
elif char == "[":
quote = "]"
elif char == "(":
depth += 1
elif char == ")":
depth -= 1
cursor += 1
if depth:
return ("<malformed>",)
expressions.append(
normalize_check_expression(sql[body_start:cursor - 1])
)
offset = cursor
def create_table() -> None:
conn.execute(
"""
CREATE TABLE lcm_embedding_backfill_inflight (
embedded_id TEXT,
identity_hash TEXT,
lease_id TEXT,
generation INTEGER,
claimed_at REAL,
state TEXT NOT NULL DEFAULT 'claimed'
CHECK(state IN ('claimed', 'dispatched', 'uncertain')),
request_id TEXT,
updated_at REAL,
last_error TEXT,
PRIMARY KEY(embedded_id, identity_hash)
)
"""
)
def table_info() -> tuple[tuple[object, ...], ...]:
return tuple(
(str(row[1]), str(row[2]).upper(), int(row[3]), row[4], int(row[5]))
for row in conn.execute(
"PRAGMA table_info(lcm_embedding_backfill_inflight)"
).fetchall()
)
started_transaction = not conn.in_transaction
try:
if started_transaction:
conn.execute("BEGIN IMMEDIATE")
# Inspect only after obtaining the DDL write lock. Two first-run
# backfills may arrive together; a pre-lock snapshot lets both observe
# a missing table and makes the loser execute a stale CREATE TABLE.
exists = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' "
"AND name='lcm_embedding_backfill_inflight'"
).fetchone()
if exists is None:
create_table()
else:
actual = table_info()
actual_names = {str(column[0]) for column in actual}
expected_by_name = {column[0]: column for column in expected_columns}
required_legacy = {column[0] for column in expected_columns[:5]}
if not required_legacy <= actual_names or not actual_names <= set(expected_by_name):
raise RuntimeError(
"incompatible lcm_embedding_backfill_inflight columns"
)
# Types and the composite PK are never safe to reinterpret. The
# newer lifecycle columns are additive and can be rebuilt into the
# exact checked/defaulted shape below.
for column in actual:
expected = expected_by_name[str(column[0])]
if str(column[1]) != expected[1] or int(column[4]) != expected[4]:
raise RuntimeError(
"incompatible lcm_embedding_backfill_inflight column "
f"{column[0]}"
)
table_sql = str(exists[0] or "")
exact = (
actual == expected_columns
and check_expressions(table_sql) == expected_checks
)
if not exact:
old_table = "lcm_embedding_backfill_inflight_legacy"
if conn.execute(
"SELECT 1 FROM sqlite_master WHERE name=?", (old_table,)
).fetchone() is not None:
raise RuntimeError(
"cannot repair lcm_embedding_backfill_inflight: "
"legacy staging table already exists"
)
conn.execute(
"ALTER TABLE lcm_embedding_backfill_inflight "
f"RENAME TO {old_table}"
)
create_table()
state_expr = (
"CASE WHEN state IN ('claimed','dispatched','uncertain') "
"THEN state ELSE 'uncertain' END"
if "state" in actual_names
else "'uncertain'"
)
request_expr = "request_id" if "request_id" in actual_names else "NULL"
updated_expr = (
"COALESCE(updated_at, claimed_at)"
if "updated_at" in actual_names
else "claimed_at"
)
error_expr = "last_error" if "last_error" in actual_names else "NULL"
conn.execute(
"INSERT INTO lcm_embedding_backfill_inflight("
"embedded_id, identity_hash, lease_id, generation, claimed_at, "
"state, request_id, updated_at, last_error) "
"SELECT embedded_id, identity_hash, lease_id, generation, claimed_at, "
f"{state_expr}, {request_expr}, {updated_expr}, {error_expr} "
f"FROM {old_table}"
)
conn.execute(f"DROP TABLE {old_table}")
if table_info() != expected_columns:
raise RuntimeError(
"lcm_embedding_backfill_inflight schema verification failed"
)
verified_sql = str(conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' "
"AND name='lcm_embedding_backfill_inflight'"
).fetchone()[0] or "")
if check_expressions(verified_sql) != expected_checks:
raise RuntimeError(
"lcm_embedding_backfill_inflight CHECK constraints are not exact"
)
expected_indexes = {
"idx_lcm_embedding_inflight_identity_state": (
"identity_hash", "state", "embedded_id"
),
"idx_lcm_embedding_inflight_maintenance": (
"identity_hash", "state", "updated_at", "embedded_id"
),
}
def index_shape(name: str) -> tuple[tuple[object, ...], ...]:
return tuple(
(
None if row[2] is None else str(row[2]),
int(row[3]),
str(row[4]).upper(),
int(row[5]),
)
for row in conn.execute(f"PRAGMA index_xinfo({name})").fetchall()
)
for name, columns in expected_indexes.items():
expected_shape = tuple(
(column, 0, "BINARY", 1) for column in columns
) + ((None, 0, "BINARY", 0),)
index = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='index' AND name=?",
(name,),
).fetchone()
needs_create = index is None
if index is not None:
index_flags = next(
(
(int(row[2]), int(row[4]))
for row in conn.execute(
"PRAGMA index_list(lcm_embedding_backfill_inflight)"
).fetchall()
if str(row[1]) == name
),
None,
)
if index_shape(name) != expected_shape or index_flags != (0, 0):
conn.execute(f"DROP INDEX {name}")
needs_create = True
if needs_create:
conn.execute(
f"CREATE INDEX {name} "
f"ON lcm_embedding_backfill_inflight({', '.join(columns)})"
)
if index_shape(name) != expected_shape:
raise RuntimeError(f"in-flight index verification failed: {name}")
if started_transaction:
conn.commit()
except Exception:
if started_transaction:
conn.rollback()
raise
_VOYAGE_MAX_BATCH_TOKENS = 80_000
_VOYAGE_MAX_DOCUMENT_TOKENS = 27_000
_VOYAGE_USD_PER_MILLION_TOKENS = {
"voyage-4-large": 0.12,
"voyage-4": 0.06,
"voyage-4-lite": 0.02,
"voyage-context-3": 0.18,
"voyage-3-lite": 0.02,
"voyage-3.5-lite": 0.02,
"voyage-3": 0.06,
"voyage-3.5": 0.06,
"voyage-3-large": 0.18,
"voyage-code-3": 0.18,
}
_ROLLUPS_OUTPUT_CHAR_LIMIT = 20_000
class _RollupBuildOutcome(str, Enum):
READY = "ready"
DEFERRED = "deferred"
NO_SOURCE = "no-source"
SUPERSEDED = "superseded"
FAILED = "failed"
QUEUED = "queued"
@dataclass(frozen=True)
class _RollupRebuildResult:
period_kind: str
period_start: str
outcome: _RollupBuildOutcome
attempted: bool
detail: str | None = None
def _bounded_rollups_text(text: str) -> str:
"""Apply one final bound to every ``/lcm rollups`` serialization."""
if len(text) <= _ROLLUPS_OUTPUT_CHAR_LIMIT:
return text
marker = (
"\ntruncated: true"
f"\nchar_limit: {_ROLLUPS_OUTPUT_CHAR_LIMIT}"
"\ntruncation_reason: response_char_limit"
)
return text[: _ROLLUPS_OUTPUT_CHAR_LIMIT - len(marker)] + marker
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 clean lifecycle: read-only scan for lifecycle rows with zero messages/nodes",
"- /lcm doctor clean lifecycle apply: backup-first cleanup of empty lifecycle rows 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 repair schema-stamp: read-only scan for an interim-build schema_version stamp ahead of the actual v5 shape",
"- /lcm doctor repair schema-stamp apply: backup-first reset of an interim schema_version stamp back to the supported version",
"- /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 rollups: show temporal-rollup status for the current session",
"- /lcm rollups rebuild <day|week|month|all> [date]: synchronously rebuild a bounded UTC target set",
"- /lcm assertions rebuild [--apply] [--limit N]: preview or run one bounded exact-row assertion batch",
"- /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 embed warmup: download/probe the configured embedding model and register its dimension",
"- /lcm embed backfill [--apply] [--limit N]: preview or populate missing leaf-summary embeddings",
"- /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)
config_sources = status.get("config_sources") or {}
config_source_warnings = status.get("config_source_warnings") or []
ignored_config_yaml_lcm_keys = status.get("ignored_config_yaml_lcm_keys") or []
uninitialized = "(uninitialized)"
unknown = "(unknown)"
model = (engine.model or unknown) if session_bound else uninitialized
provider = (engine.provider or unknown) if session_bound else uninitialized
context_length_source = (
(getattr(engine, "_context_length_source", "") or unknown)
if session_bound
else uninitialized
)
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"model: {model}",
f"provider: {provider}",
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"context_length: {engine.context_length if session_bound else '(uninitialized)'}",
f"raw_context_length: {status.get('raw_context_length', 0) if session_bound else '(uninitialized)'}",
f"effective_context_length_cap: {status.get('effective_context_length_cap') or '(none)'}",
f"effective_context_length_reason: {status.get('effective_context_length_reason') or '(none)'}",
f"context_length_source: {context_length_source}",
f"configured_context_threshold: {status.get('configured_context_threshold', engine._config.context_threshold)}",
f"context_threshold: {status.get('context_threshold', engine._config.context_threshold)}",
f"context_threshold_source: {status.get('context_threshold_source', config_sources.get('context_threshold', 'manual_or_default'))}",
f"context_threshold_autoraised: {status.get('context_threshold_autoraised') 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 config_source_warnings:
lines.append("config_source_warnings: " + "; ".join(config_source_warnings))
if ignored_config_yaml_lcm_keys:
lines.append(
"ignored_config_yaml_lcm_keys: "
+ ", ".join(f"lcm.{key}" for key in ignored_config_yaml_lcm_keys)
)
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]:
try:
rows = engine._store.scan_session_cleanup_stats()
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]:
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 = engine._store.scan_session_retention_stats(session_id)
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 _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"fresh_tail_max_tokens: {preview['fresh_tail_max_tokens']}",
f"effective_fresh_tail_count: {preview['effective_fresh_tail_count']}",
f"effective_fresh_tail_tokens: {preview['effective_fresh_tail_tokens']}",
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"fresh_tail_max_tokens: {pre['fresh_tail_max_tokens']}",
f"effective_fresh_tail_count: {pre['effective_fresh_tail_count']}",
f"effective_fresh_tail_tokens: {pre['effective_fresh_tail_tokens']}",
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"fresh_tail_max_tokens: {result['fresh_tail_max_tokens']}",
f"effective_fresh_tail_count: {result['effective_fresh_tail_count']}",
f"effective_fresh_tail_tokens: {result['effective_fresh_tail_tokens']}",
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.connection
for label, spec in specs.items():
try:
structural_needs_repair = external_content_fts_needs_repair(conn, spec)
integrity_check = check_external_content_fts_integrity(conn, spec)
integrity_status = str(integrity_check.get("status") or "fail")
needs_repair = structural_needs_repair or integrity_status == "fail"
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,
"integrity_status": integrity_status,
"integrity_detail": integrity_check.get("detail"),
"error": None,
}
except Exception as exc: # pragma: no cover - defensive
checks[label] = {
"ok": False,
"needs_repair": True,
"content_rows": None,
"fts_rows": None,
"integrity_status": "error",
"integrity_detail": str(exc),
"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(f"{label}_integrity_status: {item['integrity_status']}")
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",
])
# Join any in-flight background integrity scan first: otherwise a scan still
# mid-flight can error out (or re-check) after the repair commits and re-write
# a fresh fts_integrity_failed marker, reproducing F1's stuck false-positive
# via a race (F3).
join_background_integrity_scans()
conn = engine._store.connection
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']))}",