-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_entrypoints.py
More file actions
2519 lines (2263 loc) · 95 KB
/
Copy pathbridge_entrypoints.py
File metadata and controls
2519 lines (2263 loc) · 95 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
"""Bridge-compatible entry points for BrainClaw Python backend.
The TypeScript bridge calls Python functions as:
from openclaw_memory.<module> import <function>
result = <function>(**json.loads(sys.argv[1]))
All functions here are:
- Synchronous (bridge uses subprocess, not asyncio)
- Self-contained (build own DB clients from env vars)
- Gracefully degrading (return error dict, not crash)
"""
import os
import asyncio
import json
import math
from typing import List, Dict, Any, Optional
import hashlib
import logging
import uuid
import datetime
import urllib.request
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Namespace UUID for deterministic agent UUIDs (must match migrate_memory_md.py)
# ---------------------------------------------------------------------------
BRAINCLAW_NS = uuid.UUID("b4a1bc1a-0000-4000-a000-b4a1bc1ab000")
def _postgres_url() -> Optional[str]:
return os.getenv("POSTGRES_URL") or os.getenv("POSTGRESQL_URL") or os.getenv("DATABASE_URL")
def _parse_postgres_url(url: str) -> dict:
"""Parse PostgreSQL URL into connection parameters.
Args:
url: PostgreSQL connection URL (postgresql://user:pass@host:port/db)
Returns:
Dictionary with host, port, database, user, password
"""
from urllib.parse import urlparse
parsed = urlparse(url)
return {
"host": parsed.hostname or "localhost",
"port": parsed.port or 5432,
"database": parsed.path.lstrip("/"),
"user": parsed.username or "openclaw",
"password": parsed.password or "",
}
def _run_async(coro):
"""Run an async coroutine synchronously."""
try:
loop = asyncio.get_event_loop()
if loop.is_closed():
raise RuntimeError("closed")
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)
def _stringify_uuid(value):
return str(value) if value is not None else None
def _row_to_dict(row) -> dict:
if row is None:
return {}
if isinstance(row, dict):
return dict(row)
if hasattr(row, "items"):
return dict(row.items())
if hasattr(row, "keys"):
return {key: row[key] for key in row.keys()}
return dict(row)
def _coerce_json_container(value, *, default):
if value is None:
return default.copy() if isinstance(default, (dict, list)) else default
parsed = value
if isinstance(value, str):
text = value.strip()
if not text:
return default.copy() if isinstance(default, (dict, list)) else default
try:
parsed = json.loads(text)
except json.JSONDecodeError:
return default.copy() if isinstance(default, (dict, list)) else default
if isinstance(default, dict):
return dict(parsed) if isinstance(parsed, dict) else {}
if isinstance(default, list):
return list(parsed) if isinstance(parsed, list) else []
return parsed
def _format_memory_record(row: dict) -> dict:
"""Normalize a Postgres row into the bridge memory record shape."""
row = _row_to_dict(row)
metadata = _coerce_json_container(row.get("metadata"), default={})
metadata.setdefault("memory_class", row.get("memory_class"))
metadata.setdefault("memory_type", row.get("memory_type"))
metadata.setdefault("status", row.get("status"))
metadata.setdefault("visibility_scope", row.get("visibility_scope"))
metadata.setdefault("confidence", row.get("confidence"))
metadata.setdefault("agent_id", _stringify_uuid(row.get("agent_id")))
metadata.setdefault("tenant_id", _stringify_uuid(row.get("tenant_id")))
provenance = {
"source_message_id": _stringify_uuid(row.get("source_message_id")),
"source_session_id": _stringify_uuid(row.get("source_session_id")),
"source_tool_call_id": _stringify_uuid(row.get("source_tool_call_id")),
"extracted_by": row.get("extracted_by"),
"extractor_name": row.get("extractor_name"),
"extractor_version": row.get("extractor_version"),
"extraction_timestamp": row.get("extraction_timestamp").isoformat()
if row.get("extraction_timestamp")
else None,
"extraction_confidence": row.get("extraction_confidence"),
"extraction_metadata": _coerce_json_container(row.get("extraction_metadata"), default={}),
"superseded_by": _stringify_uuid(row.get("superseded_by")),
"supersession_reason": row.get("supersession_reason"),
}
return {
"id": _stringify_uuid(row.get("id")),
"content": row.get("content", ""),
"metadata": metadata,
"provenance": provenance,
"created_at": row.get("created_at").isoformat() if row.get("created_at") else None,
"updated_at": row.get("updated_at").isoformat() if row.get("updated_at") else None,
}
def _coerce_identity_uuid(value: Optional[object]) -> Optional[uuid.UUID]:
if value is None:
return None
if isinstance(value, uuid.UUID):
return value
text = str(value).strip()
if not text:
return None
try:
return uuid.UUID(text)
except ValueError:
return uuid.uuid5(BRAINCLAW_NS, text)
def _safe_uuid(value: Optional[object]) -> Optional[uuid.UUID]:
if value is None:
return None
if isinstance(value, uuid.UUID):
return value
try:
return uuid.UUID(str(value))
except (ValueError, TypeError):
return None
def _db_uuid_text(value: Optional[object]) -> Optional[str]:
parsed = _safe_uuid(value)
return str(parsed) if parsed else None
def _memory_md_snapshot_metadata(*, backup_path: str, content: str) -> dict:
return {
"backup_kind": "memory_md_snapshot",
"backup_path": backup_path,
"backup_sync_mode": "bidirectional",
"hidden_from_dashboard": True,
"file_hash": hashlib.sha256(content.encode("utf-8")).hexdigest(),
}
def _supersede_current_memory_row(cur, *, original_id: str, new_content: str, update_reason: str) -> dict:
cur.execute(
"""
UPDATE memory_items
SET is_current = FALSE,
supersession_reason = %s,
updated_at = NOW()
WHERE id = %s
""",
(update_reason, original_id),
)
cur.execute(
"""
INSERT INTO memory_items (
tenant_id, agent_id, memory_class, memory_type, status,
content, source_message_id, source_session_id,
source_tool_call_id, extracted_by, extraction_method,
extraction_timestamp, extractor_name, extractor_version,
extraction_confidence, extraction_metadata, confidence,
user_confirmed, user_confirmed_at, user_confirmed_by,
valid_from, valid_to, is_current, superseded_by,
supersession_reason, visibility_scope, access_control,
retention_policy, retention_until, weaviate_id,
neo4j_id, weaviate_synced, neo4j_synced,
weaviate_synced_at, neo4j_synced_at, sync_version,
metadata
)
SELECT
tenant_id, agent_id, memory_class, memory_type, status,
%s, source_message_id, source_session_id,
source_tool_call_id, extracted_by, extraction_method,
NOW(), COALESCE(extractor_name, extracted_by, 'brainclaw-control-ui'),
COALESCE(extractor_version, '1.5.0-intel-perfection'),
extraction_confidence, COALESCE(extraction_metadata, '{}'::jsonb),
confidence, user_confirmed,
user_confirmed_at, user_confirmed_by, NOW(), NULL,
TRUE, %s, %s, visibility_scope,
COALESCE(access_control, '{}'::jsonb), retention_policy,
retention_until, NULL, NULL, FALSE, FALSE, NULL, NULL,
COALESCE(sync_version, 1) + 1, COALESCE(metadata, '{}'::jsonb)
FROM memory_items
WHERE id = %s
RETURNING id, tenant_id, agent_id, memory_class, memory_type, status,
content, metadata, source_message_id, source_session_id,
source_tool_call_id, extracted_by, extraction_method,
extraction_timestamp, extractor_name, extractor_version,
extraction_confidence, extraction_metadata, confidence,
visibility_scope, superseded_by, supersession_reason,
created_at, updated_at
""",
(new_content, original_id, update_reason, original_id),
)
next_row = dict(cur.fetchone() or {})
if not next_row:
return {}
cur.execute(
"""
UPDATE memory_items
SET superseded_by = %s,
updated_at = NOW()
WHERE id = %s
""",
(str(next_row["id"]), original_id),
)
return next_row
def _upsert_memory_md_snapshot_record(
cur,
*,
agent_db_id: str,
tenant_db_id: str | None,
content: str,
backup_path: str,
update_reason: str,
json_wrapper,
) -> dict | None:
snapshot_metadata = _memory_md_snapshot_metadata(backup_path=backup_path, content=content)
cur.execute(
"""
SELECT id, tenant_id, agent_id, memory_class, memory_type, status,
content, metadata, source_message_id, source_session_id,
source_tool_call_id, extracted_by, extraction_method,
extraction_timestamp, extractor_name, extractor_version,
extraction_confidence, extraction_metadata, confidence,
visibility_scope, superseded_by, supersession_reason,
created_at, updated_at
FROM memory_items
WHERE agent_id::text = %s
AND is_current = TRUE
AND COALESCE(metadata->>'backup_kind', '') = 'memory_md_snapshot'
ORDER BY COALESCE(updated_at, created_at) DESC
LIMIT 1
""",
(agent_db_id,),
)
current_row = dict(cur.fetchone() or {})
if current_row and str(current_row.get("content") or "").strip() == content.strip():
return current_row
if current_row:
next_row = _supersede_current_memory_row(
cur,
original_id=str(current_row["id"]),
new_content=content,
update_reason=update_reason,
)
if next_row:
cur.execute(
"""
UPDATE memory_items
SET metadata = %s,
updated_at = NOW()
WHERE id = %s
""",
(json_wrapper(snapshot_metadata), str(next_row["id"])),
)
next_row["metadata"] = snapshot_metadata
return next_row
return None
now = datetime.datetime.utcnow()
cur.execute(
"""
INSERT INTO memory_items (
id, tenant_id, agent_id, memory_class, memory_type, status,
content, extracted_by, extraction_method, extraction_timestamp,
extractor_name, extractor_version, extraction_confidence,
extraction_metadata, confidence, user_confirmed, valid_from,
is_current, visibility_scope, access_control, retention_policy,
metadata, created_at, updated_at
) VALUES (
%s, %s, %s, %s, %s, %s,
%s, %s, %s, %s,
%s, %s, %s,
%s, %s, %s, %s,
%s, %s, %s, %s,
%s, %s, %s
)
RETURNING id, tenant_id, agent_id, memory_class, memory_type, status,
content, metadata, source_message_id, source_session_id,
source_tool_call_id, extracted_by, extraction_method,
extraction_timestamp, extractor_name, extractor_version,
extraction_confidence, extraction_metadata, confidence,
visibility_scope, superseded_by, supersession_reason,
created_at, updated_at
""",
(
str(uuid.uuid4()),
tenant_db_id,
agent_db_id,
"summary",
"memory_md_backup",
"active",
content,
"brainclaw",
"memory_md_backup_sync",
now,
"brainclaw",
"1.5.0-intel-perfection",
1.0,
json_wrapper({"backup_kind": "memory_md_snapshot"}),
1.0,
True,
now,
True,
"agent",
json_wrapper({}),
"default",
json_wrapper(snapshot_metadata),
now,
now,
),
)
inserted = dict(cur.fetchone() or {})
if inserted:
inserted["metadata"] = snapshot_metadata
return inserted or None
def _parse_alternatives(content: str) -> list[str]:
import re
match = re.search(r"alternatives?\s+considered\s*:\s*(.+?)(?:\.\s|$)", content, re.IGNORECASE)
if not match:
return []
candidates = re.split(r",|;|\n| or ", match.group(1))
return [candidate.strip(" .") for candidate in candidates if candidate.strip(" .")]
def _extract_workflow_steps(content: str) -> list[dict]:
import re
numbered = re.findall(r"(?:^|\s)(\d+)\.\s*(.*?)(?=(?:\s+\d+\.\s)|$)", content, re.DOTALL)
if numbered:
return [
{"step": int(number), "description": description.strip()}
for number, description in numbered
if description.strip()
]
steps = []
for index, raw_line in enumerate(content.splitlines(), start=1):
line = raw_line.strip()
if not line:
continue
if line.startswith(("- ", "* ")):
steps.append({"step": len(steps) + 1, "description": line[2:].strip()})
elif line.lower().startswith("step "):
cleaned = re.sub(r"^step\s+\d+\s*[:.-]?\s*", "", line, flags=re.IGNORECASE)
if cleaned:
steps.append({"step": len(steps) + 1, "description": cleaned})
return steps
def infer_memory_semantics(
content: str,
event_type: str = "message",
role: str = "",
metadata: Optional[dict] = None,
) -> dict:
metadata = dict(metadata or {})
content = (content or "").strip()
content_lower = content.lower()
explicit_class = str(metadata.get("memory_class") or "").strip().lower()
explicit_type = str(metadata.get("memory_type") or "").strip().lower()
decision_phrases = (
"we decided",
"decided to",
"let's go with",
"agreed on",
"agreed to",
"the decision was",
"we will use",
"we'll use",
"chose to",
"selected",
)
procedure_markers = (
"procedure:",
"runbook:",
"playbook:",
"steps:",
"workflow:",
"how to",
)
success_markers = ("worked", "successful", "successfully", "resolved", "fixed")
memory_class = "semantic"
memory_type = explicit_type or "fact"
confidence = float(metadata.get("confidence") or 0.78)
structured_metadata: dict = {}
if explicit_class and explicit_class not in {"general", "unknown"}:
memory_class = explicit_class
if not explicit_type:
memory_type = {
"decision": "technical",
"procedural": "procedure",
"identity": "preference",
"relational": "project",
"episodic": event_type or "event",
"summary": "session",
}.get(memory_class, "fact")
elif any(phrase in content_lower for phrase in decision_phrases):
memory_class = "decision"
memory_type = explicit_type or "technical"
elif any(marker in content_lower for marker in procedure_markers) or _extract_workflow_steps(content):
memory_class = "procedural"
memory_type = explicit_type or "procedure"
elif event_type == "tool_call":
memory_class = "episodic"
memory_type = explicit_type or "tool_run"
elif role == "system":
memory_class = "identity"
memory_type = explicit_type or "guardrail"
if memory_class == "decision":
import re
rationale_match = re.search(r"because\s+(.+?)(?:\.\s|$)", content, re.IGNORECASE)
structured_metadata.update(
{
"decision_summary": content.splitlines()[0].strip(),
"rationale": rationale_match.group(1).strip() if rationale_match else "",
"alternatives": _parse_alternatives(content),
"decision_status": str(metadata.get("decision_status") or "accepted"),
"supporting_evidence": metadata.get("supporting_evidence") or [],
}
)
confidence = max(confidence, 0.9)
if memory_class == "procedural":
workflow_steps = _extract_workflow_steps(content)
success = bool(metadata.get("success")) or any(marker in content_lower for marker in success_markers)
failure = bool(metadata.get("failure")) or "failed" in content_lower
structured_metadata.update(
{
"workflow_steps": workflow_steps,
"success_count": 1 if success else 0,
"failure_count": 1 if failure and not success else 0,
"last_successful_execution": datetime.datetime.utcnow().isoformat() if success else None,
}
)
confidence = max(confidence, 0.88 if success else 0.74)
if memory_class == "identity":
confidence = max(confidence, 0.82)
return {
"memory_class": memory_class,
"memory_type": memory_type,
"status": structured_metadata.get("decision_status", "active"),
"confidence": min(confidence, 1.0),
"metadata": structured_metadata,
}
def detect_pairwise_contradictions(memories: list[dict]) -> list[dict]:
from openclaw_memory.memory.write_policy import WritePolicy
import re
policy = WritePolicy()
contradictions = []
ignore_tokens = {
"brainclaw",
"openclaw",
"running",
"memory",
"system",
"plugin",
"using",
"current",
"active",
}
for left_index in range(len(memories)):
left = memories[left_index]
left_content = (left.get("content") or "").strip()
if not left_content:
continue
left_tokens = {
token
for token in re.findall(r"[a-z0-9]+", left_content.lower())
if len(token) > 3 and token not in ignore_tokens
}
for right_index in range(left_index + 1, len(memories)):
right = memories[right_index]
right_content = (right.get("content") or "").strip()
if not right_content:
continue
right_tokens = {
token
for token in re.findall(r"[a-z0-9]+", right_content.lower())
if len(token) > 3 and token not in ignore_tokens
}
if not (left_tokens & right_tokens):
continue
reason = policy.detect_contradiction(left_content, [right_content]) or policy.detect_contradiction(
right_content,
[left_content],
)
if not reason:
continue
contradictions.append(
{
"memory_ids": [str(left.get("id")), str(right.get("id"))],
"reason": reason,
"contents": [left_content, right_content],
}
)
return contradictions
def summarize_audit_health(
audit_rows: int,
memory_event_rows: int,
retrieval_rows: int,
provenance_gap_count: int,
) -> dict:
status = "HEALTHY" if provenance_gap_count == 0 else "DEGRADED"
return {
"status": status,
"tables": {
"audit_log": audit_rows,
"memory_events": memory_event_rows,
"retrieval_logs": retrieval_rows,
},
"provenance_gap_count": provenance_gap_count,
}
def _json_safe(value):
if isinstance(value, datetime.datetime):
return value.isoformat()
if isinstance(value, datetime.date):
return value.isoformat()
if isinstance(value, dict):
return {key: _json_safe(item) for key, item in value.items()}
if isinstance(value, list):
return [_json_safe(item) for item in value]
return value
def _safe_repository_state_snapshot(repository):
checkpoint_state = None
integration_state = None
backfill_required_state = {"pending": 0, "failed": 0, "completed": 0}
rebuild_status: dict = {}
errors: list[str] = []
try:
checkpoint_state = repository.get_checkpoint()
except Exception as exc: # pragma: no cover - defensive in live runtime
errors.append(str(exc))
try:
integration_state = repository.get_integration_state()
except Exception as exc: # pragma: no cover - defensive in live runtime
errors.append(str(exc))
try:
backfill_required_state = repository.summarize_backfill_state()
except Exception as exc: # pragma: no cover - defensive in live runtime
errors.append(str(exc))
try:
rebuild_status = repository.get_rebuild_status()
except Exception as exc: # pragma: no cover - defensive in live runtime
errors.append(str(exc))
repository_error = "; ".join(errors) if errors else None
return (
_json_safe(checkpoint_state),
_json_safe(integration_state),
_json_safe(backfill_required_state),
_json_safe(rebuild_status),
repository_error,
)
def lcm_status(runtime: Optional[dict] = None, plugin_config: Optional[dict] = None, **kwargs) -> dict:
from openclaw_memory.integration.lossless_adapter import (
LosslessClawAdapter,
OpenClawRuntimeSnapshot,
)
from openclaw_memory.integration.lossless_sync import build_postgres_repository_from_env
adapter = LosslessClawAdapter(
runtime=OpenClawRuntimeSnapshot.from_dict(runtime),
db_path=(plugin_config or {}).get("losslessClawDbPath") or (plugin_config or {}).get("dbPath"),
plugin_config=plugin_config or {},
)
report = adapter.detect().to_dict()
repository = build_postgres_repository_from_env()
checkpoint_state = None
integration_state = None
backfill_required_state = {"pending": 0, "failed": 0, "completed": 0}
rebuild_status = {}
repository_error = None
if repository is not None:
try:
repository.upsert_integration_state(report)
except Exception as exc: # pragma: no cover - defensive in live runtime
repository_error = str(exc)
repository = None
if repository is not None:
(
checkpoint_state,
integration_state,
backfill_required_state,
rebuild_status,
snapshot_error,
) = _safe_repository_state_snapshot(repository)
repository_error = snapshot_error
response = {
**report,
"integration_state": integration_state,
"checkpoint_state": checkpoint_state,
"degraded_state_details": {
"reason_code": (integration_state or {}).get("reason_code") or report.get("reason_code"),
"last_degraded_reason_code": (integration_state or {}).get("last_degraded_reason_code"),
"last_degraded_transition_at": (integration_state or {}).get("last_degraded_transition_at"),
"last_successful_supported_profile": (integration_state or {}).get("last_successful_supported_profile")
or report.get("supported_profile"),
},
"replay_status": {
"status": (checkpoint_state or {}).get("status"),
"retry_count": (checkpoint_state or {}).get("retry_count"),
"replay_marker": (checkpoint_state or {}).get("replay_marker"),
},
"backfill_required_state": backfill_required_state,
"rebuild_status": rebuild_status,
}
if repository_error:
response["repository_error"] = repository_error
return response
def lcm_expand(summary_id: str = "", **kwargs) -> dict:
"""Expand a summary into its constituent chunks/messages."""
if not summary_id:
return {"error": "summary_id is required"}
conn = None
try:
import sqlite3
import os
db_path = _get_plugin_config().get("losslessClawDbPath", "/home/node/.openclaw/lossless-claw/lcm.db")
if not os.path.exists(db_path):
return {"error": f"LCM database not found at {db_path}"}
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
# Get the summary content first
cur.execute("SELECT content, metadata FROM summaries WHERE id = ?", (summary_id,))
summary = cur.fetchone()
if not summary:
return {"error": f"Summary {summary_id} not found"}
# Get the chunks associated with this summary
cur.execute("""
SELECT c.id, c.content, c.metadata, c.created_at
FROM chunks c
JOIN summary_chunks sc ON c.id = sc.chunk_id
WHERE sc.summary_id = ?
ORDER BY c.created_at ASC
""", (summary_id,))
chunks = [dict(row) for row in cur.fetchall()]
return {
"summary_id": summary_id,
"content": summary["content"],
"chunks": chunks,
"count": len(chunks)
}
except Exception as e:
logger.error("lcm_expand failed: %s", e)
return {"error": str(e)}
finally:
if conn:
conn.close()
def lcm_describe(summary_id: str = "", **kwargs) -> dict:
"""Get detailed metadata and provenance for a summary."""
if not summary_id:
return {"error": "summary_id is required"}
conn = None
try:
import sqlite3
import os
db_path = _get_plugin_config().get("losslessClawDbPath", "/home/node/.openclaw/lossless-claw/lcm.db")
if not os.path.exists(db_path):
return {"error": f"LCM database not found at {db_path}"}
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM summaries WHERE id = ?", (summary_id,))
summary = cur.fetchone()
if not summary:
return {"error": f"Summary {summary_id} not found"}
return dict(summary)
except Exception as e:
logger.error("lcm_describe failed: %s", e)
return {"error": str(e)}
finally:
if conn:
conn.close()
def lcm_sync(
runtime: Optional[dict] = None,
plugin_config: Optional[dict] = None,
mode: str = "incremental",
**kwargs,
) -> dict:
from openclaw_memory.integration.lossless_adapter import (
LosslessClawAdapter,
OpenClawRuntimeSnapshot,
)
from openclaw_memory.integration.lossless_sync import (
LosslessClawSyncEngine,
build_postgres_repository_from_env,
)
adapter = LosslessClawAdapter(
runtime=OpenClawRuntimeSnapshot.from_dict(runtime),
db_path=(plugin_config or {}).get("losslessClawDbPath") or (plugin_config or {}).get("dbPath"),
plugin_config=plugin_config or {},
)
status = adapter.detect().to_dict()
repository = build_postgres_repository_from_env()
if repository is None:
if status["compatibility_state"] != "installed_compatible":
return {
"status": "skipped",
"mode": mode,
"compatibility_state": status["compatibility_state"],
"reason_code": status.get("reason_code"),
"checkpoint_state": None,
"replay_status": {"status": None, "retry_count": None, "replay_marker": None},
"backfill_required_state": {"pending": 0, "failed": 0, "completed": 0},
"degraded_state_details": {
"reason_code": status.get("reason_code"),
"last_degraded_reason_code": None,
"last_degraded_transition_at": None,
"last_successful_supported_profile": status.get("supported_profile"),
},
"rebuild_status": {},
}
return {
"status": "failed",
"mode": mode,
"compatibility_state": status["compatibility_state"],
"reason_code": status.get("reason_code"),
"error": "Canonical PostgreSQL repository unavailable",
"checkpoint_state": None,
"replay_status": {"status": None, "retry_count": None, "replay_marker": None},
"backfill_required_state": {"pending": 0, "failed": 0, "completed": 0},
"degraded_state_details": {
"reason_code": status.get("reason_code"),
"last_degraded_reason_code": None,
"last_degraded_transition_at": None,
"last_successful_supported_profile": status.get("supported_profile"),
},
"rebuild_status": {},
}
checkpoint_state = None
integration_state = None
backfill_required_state = {"pending": 0, "failed": 0, "completed": 0}
rebuild_status = {}
repository_error = None
try:
engine = LosslessClawSyncEngine(adapter=adapter, repository=repository)
result = engine.sync(mode=mode)
except Exception as exc:
result = {
"status": "failed",
"mode": mode,
"compatibility_state": status["compatibility_state"],
"reason_code": status.get("reason_code"),
"error": "Canonical sync failure",
}
repository_error = str(exc)
(
checkpoint_state,
integration_state,
backfill_required_state,
rebuild_status,
snapshot_error,
) = _safe_repository_state_snapshot(repository)
if snapshot_error:
repository_error = "; ".join(
[part for part in [repository_error, snapshot_error] if part]
)
response = {
**result,
"integration_state": integration_state,
"checkpoint_state": checkpoint_state,
"degraded_state_details": {
"reason_code": (integration_state or {}).get("reason_code") or result.get("reason_code"),
"last_degraded_reason_code": (integration_state or {}).get("last_degraded_reason_code"),
"last_degraded_transition_at": (integration_state or {}).get("last_degraded_transition_at"),
"last_successful_supported_profile": (integration_state or {}).get("last_successful_supported_profile")
or status.get("supported_profile"),
},
"replay_status": {
"status": (checkpoint_state or {}).get("status"),
"retry_count": (checkpoint_state or {}).get("retry_count"),
"replay_marker": (checkpoint_state or {}).get("replay_marker"),
},
"backfill_required_state": backfill_required_state,
"rebuild_status": rebuild_status,
}
if repository_error:
response["repository_error"] = repository_error
return response
def lcm_rebuild(target: str = "", **kwargs) -> dict:
from openclaw_memory.integration.lossless_sync import (
LosslessClawSyncEngine,
build_postgres_repository_from_env,
)
repository = build_postgres_repository_from_env()
if repository is None:
return {
"status": "failed",
"target": str(target or "").strip().lower(),
"error": "Canonical PostgreSQL repository unavailable",
"rebuild_checkpoint": None,
"backfill_required_state": {"pending": 0, "failed": 0, "completed": 0},
}
repository_error = None
try:
engine = LosslessClawSyncEngine(adapter=None, repository=repository)
result = engine.rebuild(target)
except Exception as exc:
result = {
"status": "failed",
"target": str(target or "").strip().lower(),
"error": "Canonical rebuild failure",
}
repository_error = str(exc)
(
_checkpoint_state,
_integration_state,
backfill_required_state,
rebuild_status,
snapshot_error,
) = _safe_repository_state_snapshot(repository)
if snapshot_error:
repository_error = "; ".join(
[part for part in [repository_error, snapshot_error] if part]
)
normalized_target = str(target or "").strip().lower()
response = {
**result,
"rebuild_checkpoint": rebuild_status.get(normalized_target),
"backfill_required_state": backfill_required_state,
}
if repository_error:
response["repository_error"] = repository_error
return response
def _detect_control_ui_status() -> str:
configured_url = os.getenv("BRAINCLAW_CONTROL_UI_URL")
urls = [configured_url] if configured_url else []
urls.extend(
[
"http://127.0.0.1:3000/__openclaw__/control/",
"http://127.0.0.1:18789/__openclaw__/control/",
]
)
for url in urls:
try:
with urllib.request.urlopen(url, timeout=2) as response:
return "healthy" if response.status == 200 else f"http_{response.status}"
except Exception:
continue
return "unknown"
def sync_operational_memory_files(
runtime: Optional[dict] = None,
plugin_config: Optional[dict] = None,
sync_date: Optional[str] = None,
**kwargs,
) -> dict:
from openclaw_memory.graph.health import get_health_stats
from openclaw_memory.integration.lossless_adapter import (
LosslessClawAdapter,
OpenClawRuntimeSnapshot,
)
from openclaw_memory.integration.operational_memory_sync import (
DEFAULT_PRIMARY_AGENT_ID,
sync_operational_memory_files as sync_files,
)
plugin_config = plugin_config or {}
runtime_snapshot = OpenClawRuntimeSnapshot.from_dict(runtime)
adapter = LosslessClawAdapter(
runtime=runtime_snapshot,
db_path=plugin_config.get("losslessClawDbPath") or plugin_config.get("dbPath"),
plugin_config=plugin_config,
)
status = adapter.detect().to_dict()
graph_health = get_health_stats()
tool_names = [
tool_name
for tool_name, available in (status.get("tool_availability") or {}).items()
if available
]
snapshot = {
"openclaw_version": runtime_snapshot.openclaw_version or status.get("openclaw_version"),
"memory_slot": runtime_snapshot.memory_slot,
"context_engine_slot": runtime_snapshot.context_engine_slot,
"plugin_version": status.get("plugin_version") or runtime_snapshot.plugin_version,
"compatibility_state": status.get("compatibility_state", "unknown"),
"supported_profile": status.get("supported_profile"),
"tool_names": tool_names,
"node_count": graph_health.get("node_count"),
"edge_count": graph_health.get("edge_count"),
"control_ui_status": _detect_control_ui_status(),
}
state_dir = Path(os.getenv("OPENCLAW_STATE_DIR", "/home/node/.openclaw"))
config_path = Path(os.getenv("OPENCLAW_CONFIG_PATH", state_dir / "openclaw.json"))
result = sync_files(