-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_diff_output.txt
More file actions
1382 lines (1347 loc) · 50.9 KB
/
git_diff_output.txt
File metadata and controls
1382 lines (1347 loc) · 50.9 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
diff --git a/AGENTS.md b/AGENTS.md
index eb06ce42..104ef3a0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,7 +29,7 @@ Last reviewed commit: `eea4f599c0c54eb8d7dcc0d81a9364f2302fd1e6`
| Project Exclusion | ✅ 100% | OPENCODE_MEM_EXCLUDED_PROJECTS env var, glob patterns, ~ expansion |
| Save Memory | ✅ 100% | Direct observation storage (MCP + HTTP), bypasses LLM compression |
| Circuit Breaker | ✅ 100% | Graceful degradation when PostgreSQL unavailable — MCP tools return empty results, HTTP returns 200 + X-Memory-Degraded header, auto-recovery on reconnect |
-| Memory Quality | ✅ | Cross-project dedup, metadata enrichment, knowledge extraction for all types, usage tracking |
+| Memory Quality | ✅ | Cross-project dedup, metadata enrichment, knowledge extraction for all types, usage tracking, trigram similarity dedup for knowledge |
### NOT Implemented
@@ -273,3 +273,4 @@ LLM always creates NEW observations even when near-identical ones exist. The `ex
- ~~observation_type search filter case-sensitive~~ — fixed: lowercased at service layer in hybrid_ops.rs
- ~~CLI search bypasses SearchService~~ — fixed: uses smart_search() for semantic/hybrid routing
- ~~backfill-metadata single-batch truncation~~ — fixed: proper loop with progress tracking and infinite-loop prevention
+- ~~Session summaries never generated (0/2168 sessions)~~ — `get_sessions_without_summaries` joined on `sessions.id` (UUID) but observations store IDE content session IDs (`ses_*`) that never match. Fixed: query now groups observations by `session_id` directly, bypassing the sessions table. `generate_pending_summaries` uses `save_summary` instead of `update_session_status_with_summary`.
diff --git a/crates/core/src/constants.rs b/crates/core/src/constants.rs
index 4c38ff1f..fb8a6f7a 100644
--- a/crates/core/src/constants.rs
+++ b/crates/core/src/constants.rs
@@ -38,6 +38,18 @@ pub const EMBEDDING_DIMENSION: usize = 1024;
/// in a spawn_blocking thread (~2-3 seconds on modern CPU).
pub const DEDUP_SWEEP_MAX_OBSERVATIONS: usize = 5000;
+/// Trigram similarity threshold for merging knowledge entries.
+/// Titles with similarity above this are considered duplicates and merged.
+pub const KNOWLEDGE_TRIGRAM_MERGE_THRESHOLD: f32 = 0.7;
+
+/// Trigram similarity threshold for logging near-misses.
+/// Titles with similarity between this and `KNOWLEDGE_TRIGRAM_MERGE_THRESHOLD`
+/// are logged at info level for monitoring but not merged.
+pub const KNOWLEDGE_TRIGRAM_LOG_THRESHOLD: f32 = 0.5;
+
+/// Maximum number of trigram similarity candidates to consider.
+pub const KNOWLEDGE_TRIGRAM_CANDIDATE_LIMIT: i64 = 3;
+
/// Cap a user-supplied query limit to `MAX_QUERY_LIMIT`.
///
/// Both HTTP and MCP transports need to clamp user-supplied limits for DoS
diff --git a/crates/core/src/identifiers.rs b/crates/core/src/identifiers.rs
index 47c765f2..51831a43 100644
--- a/crates/core/src/identifiers.rs
+++ b/crates/core/src/identifiers.rs
@@ -6,6 +6,7 @@
use std::fmt;
use std::ops::Deref;
+use serde::de::Deserializer;
use serde::{Deserialize, Serialize};
/// Internal memory session identifier (generated UUID).
@@ -23,9 +24,41 @@ pub struct SessionId(pub String);
pub struct ContentSessionId(pub String);
/// Project name or path identifier.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+///
+/// Inner field is private — all construction goes through [`ProjectId::new`],
+/// which enforces canonical normalization:
+/// lowercase, hyphens→underscores, trim whitespace, trim trailing slashes.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
-pub struct ProjectId(pub String);
+pub struct ProjectId(String);
+
+impl ProjectId {
+ /// Creates a normalized `ProjectId`. Rules documented on the struct.
+ #[must_use]
+ pub fn new(raw: impl Into<String>) -> Self {
+ Self(Self::normalize(raw.into()))
+ }
+
+ #[must_use]
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ fn normalize(raw: String) -> String {
+ raw.trim()
+ .to_lowercase()
+ .replace('-', "_")
+ .trim_end_matches('/')
+ .to_string()
+ }
+}
+
+impl<'de> Deserialize<'de> for ProjectId {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let s = String::deserialize(d)?;
+ Ok(Self::new(s))
+ }
+}
/// Observation identifier (generated UUID string).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -70,7 +103,7 @@ impl From<String> for ContentSessionId {
impl From<String> for ProjectId {
fn from(s: String) -> Self {
- Self(s)
+ Self::new(s)
}
}
@@ -94,7 +127,7 @@ impl From<&str> for ContentSessionId {
impl From<&str> for ProjectId {
fn from(s: &str) -> Self {
- Self(s.to_owned())
+ Self::new(s)
}
}
@@ -228,6 +261,118 @@ mod sqlx_impls {
impl_sqlx_transparent!(SessionId);
impl_sqlx_transparent!(ContentSessionId);
- impl_sqlx_transparent!(ProjectId);
impl_sqlx_transparent!(ObservationId);
+
+ // ProjectId gets manual impls to normalize on decode from DB
+ impl<DB: Database> sqlx::Type<DB> for ProjectId
+ where
+ String: sqlx::Type<DB>,
+ {
+ fn type_info() -> DB::TypeInfo {
+ <String as sqlx::Type<DB>>::type_info()
+ }
+
+ fn compatible(ty: &DB::TypeInfo) -> bool {
+ <String as sqlx::Type<DB>>::compatible(ty)
+ }
+ }
+
+ impl<'q, DB: Database> sqlx::Encode<'q, DB> for ProjectId
+ where
+ String: sqlx::Encode<'q, DB>,
+ {
+ fn encode_by_ref(
+ &self,
+ buf: &mut <DB as Database>::ArgumentBuffer<'q>,
+ ) -> Result<IsNull, BoxDynError> {
+ self.0.encode_by_ref(buf)
+ }
+ }
+
+ impl<'r, DB: Database> sqlx::Decode<'r, DB> for ProjectId
+ where
+ String: sqlx::Decode<'r, DB>,
+ {
+ fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
+ let s = <String as sqlx::Decode<'r, DB>>::decode(value)?;
+ Ok(ProjectId::new(s))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalizes_hyphens_to_underscores() {
+ assert_eq!(ProjectId::new("hermes-ai").as_str(), "hermes_ai");
+ }
+
+ #[test]
+ fn normalizes_to_lowercase() {
+ assert_eq!(
+ ProjectId::new("Antigravity-Manager").as_str(),
+ "antigravity_manager"
+ );
+ }
+
+ #[test]
+ fn trims_whitespace_and_trailing_slash() {
+ assert_eq!(ProjectId::new(" my-project/ ").as_str(), "my_project");
+ }
+
+ #[test]
+ fn from_string_normalizes() {
+ let id: ProjectId = "Test-Project".into();
+ assert_eq!(id.as_str(), "test_project");
+ }
+
+ #[test]
+ fn from_str_normalizes() {
+ let id = ProjectId::from("Hermes-AI");
+ assert_eq!(id.as_str(), "hermes_ai");
+ }
+
+ #[test]
+ fn deserialize_normalizes() {
+ let id: ProjectId = serde_json::from_str("\"Hermes-AI\"").unwrap();
+ assert_eq!(id.as_str(), "hermes_ai");
+ }
+
+ #[test]
+ fn serialize_returns_normalized() {
+ let id = ProjectId::new("Test-Project");
+ let json = serde_json::to_string(&id).unwrap();
+ assert_eq!(json, "\"test_project\"");
+ }
+
+ #[test]
+ fn display_returns_normalized() {
+ let id = ProjectId::new("My-App/");
+ assert_eq!(id.to_string(), "my_app");
+ }
+
+ #[test]
+ fn deref_returns_normalized() {
+ let id = ProjectId::new("FOO-BAR");
+ let s: &str = &id;
+ assert_eq!(s, "foo_bar");
+ }
+
+ #[test]
+ fn empty_string_stays_empty() {
+ assert_eq!(ProjectId::new("").as_str(), "");
+ }
+
+ #[test]
+ fn already_normalized_unchanged() {
+ assert_eq!(ProjectId::new("opencode_mem").as_str(), "opencode_mem");
+ }
+
+ #[test]
+ fn equality_after_normalization() {
+ assert_eq!(ProjectId::new("hermes-ai"), ProjectId::new("hermes_ai"));
+ assert_eq!(ProjectId::new("Hermes-AI"), ProjectId::new("hermes_ai"));
+ }
}
diff --git a/crates/core/src/observation/mod.rs b/crates/core/src/observation/mod.rs
index fa2f6912..3e8a111d 100644
--- a/crates/core/src/observation/mod.rs
+++ b/crates/core/src/observation/mod.rs
@@ -32,6 +32,8 @@ pub struct ObservationMetadata {
pub keywords: Vec<String>,
pub files_read: Vec<String>,
pub files_modified: Vec<String>,
+ pub observation_type: Option<ObservationType>,
+ pub noise_level: Option<NoiseLevel>,
}
impl ObservationMetadata {
@@ -43,6 +45,8 @@ impl ObservationMetadata {
keywords: Vec::new(),
files_read: Vec::new(),
files_modified: Vec::new(),
+ observation_type: None,
+ noise_level: None,
}
}
}
diff --git a/crates/core/src/session.rs b/crates/core/src/session.rs
index 5ff3b5b8..2a3ee8b7 100644
--- a/crates/core/src/session.rs
+++ b/crates/core/src/session.rs
@@ -155,6 +155,41 @@ impl SessionSummary {
}
}
+/// Lightweight session info derived from observations (for autonomous summary generation).
+///
+/// Used when the `sessions` table may not have a matching entry — observations
+/// store IDE content session IDs (`ses_*`) that may never have been registered
+/// via `session-init`.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct UnsummarizedSession {
+ /// The session_id as stored in the observations table.
+ pub session_id: String,
+ /// Project name (from the first observation in the session).
+ pub project: Option<ProjectId>,
+ /// Number of observations in this session.
+ pub observation_count: usize,
+ /// Timestamp of the last observation.
+ pub last_observation_at: DateTime<Utc>,
+}
+
+impl UnsummarizedSession {
+ #[must_use]
+ pub fn new(
+ session_id: String,
+ project: Option<ProjectId>,
+ observation_count: usize,
+ last_observation_at: DateTime<Utc>,
+ ) -> Self {
+ Self {
+ session_id,
+ project,
+ observation_count,
+ last_observation_at,
+ }
+ }
+}
+
/// User prompt within a session
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
diff --git a/crates/http/src/handlers/breaker_tests.rs b/crates/http/src/handlers/breaker_tests.rs
index 125a8f24..763449c0 100644
--- a/crates/http/src/handlers/breaker_tests.rs
+++ b/crates/http/src/handlers/breaker_tests.rs
@@ -5,7 +5,7 @@ async fn test_timeline_invalid_date_returns_400() {
// `/timeline?from=invalid` or `/search?from=invalid` causes a
// 500 Internal Server Error instead of 400 Bad Request,
// because the validation is pushed down to PostgreSQL instead of parsed at the boundary.
-
+
let is_vulnerable = true;
assert!(
is_vulnerable,
diff --git a/crates/http/src/handlers/cron.rs b/crates/http/src/handlers/cron.rs
index c9dac93e..dad8ff36 100644
--- a/crates/http/src/handlers/cron.rs
+++ b/crates/http/src/handlers/cron.rs
@@ -124,5 +124,25 @@ pub async fn start_cron_scheduler(state: Arc<AppState>) {
}
});
}
+
+ // Autonomous session summary generation — every 30 minutes (360 × 5s)
+ if loop_count.is_multiple_of(360) {
+ let state_clone = Arc::clone(&state);
+ state.background_tasks.lock().await.spawn(async move {
+ match state_clone
+ .session_service
+ .generate_pending_summaries(10)
+ .await
+ {
+ Ok(n) if n > 0 => {
+ tracing::info!(generated = n, "Cron: session summary generation completed");
+ }
+ Ok(_) => {}
+ Err(e) => {
+ tracing::warn!(error = %e, "Cron: session summary generation failed");
+ }
+ }
+ });
+ }
}
}
diff --git a/crates/http/src/handlers/session_ops.rs b/crates/http/src/handlers/session_ops.rs
index 278d2cce..92b74e40 100644
--- a/crates/http/src/handlers/session_ops.rs
+++ b/crates/http/src/handlers/session_ops.rs
@@ -22,7 +22,7 @@ pub(crate) async fn create_session(
opencode_mem_core::SessionId(session_db_id.clone()),
opencode_mem_core::ContentSessionId(content_session_id),
None,
- opencode_mem_core::ProjectId(project.unwrap_or_default()),
+ opencode_mem_core::ProjectId::new(project.unwrap_or_default()),
user_prompt
.as_deref()
.map(opencode_mem_core::sanitize_input),
diff --git a/crates/llm/src/ai_types.rs b/crates/llm/src/ai_types.rs
index 55341783..f9de32f0 100644
--- a/crates/llm/src/ai_types.rs
+++ b/crates/llm/src/ai_types.rs
@@ -138,4 +138,10 @@ pub struct MetadataJson {
pub files_read: Vec<String>,
#[serde(default, deserialize_with = "null_or_invalid_as_default_vec")]
pub files_modified: Vec<String>,
+ /// LLM-classified observation type (e.g. "bugfix", "gotcha", "decision").
+ #[serde(default, deserialize_with = "null_as_default")]
+ pub observation_type: String,
+ /// LLM-classified noise level (e.g. "critical", "high", "medium").
+ #[serde(default, deserialize_with = "null_as_default")]
+ pub noise_level: String,
}
diff --git a/crates/llm/src/observation.rs b/crates/llm/src/observation.rs
index 716003c4..e33576c1 100644
--- a/crates/llm/src/observation.rs
+++ b/crates/llm/src/observation.rs
@@ -198,9 +198,21 @@ impl LlmClient {
- \"concepts\": array from [{concepts}]\n\
- \"keywords\": array of search keywords (3-8 terms)\n\
- \"files_read\": array of file paths mentioned as read/referenced\n\
- - \"files_modified\": array of file paths mentioned as modified/created\n\n\
- If a field has no relevant data, return an empty array.",
+ - \"files_modified\": array of file paths mentioned as modified/created\n\
+ - \"observation_type\": one of [{obs_types}]\n\
+ {obs_type_guide}\n\
+ - \"noise_level\": one of [{noise_levels}]\n\
+ \"critical\" = fundamental insight, must never forget; \"high\" = important for future work; \
+ \"medium\" = useful context; \"low\" = minor detail; \"negligible\" = trivial\n\n\
+ If a field has no relevant data, return an empty array (for arrays) or \"discovery\"/\"medium\" (for type/noise defaults).",
concepts = Concept::ALL_VARIANTS_STR,
+ obs_types = ObservationType::ALL_VARIANTS_STR,
+ noise_levels = NoiseLevel::ALL_VARIANTS_STR,
+ obs_type_guide = ObservationType::ALL_VARIANTS
+ .iter()
+ .map(|t| format!("\"{}\" = {}", t.as_str(), t.description()))
+ .collect::<Vec<_>>()
+ .join("; "),
);
let request = ChatRequest {
@@ -232,12 +244,44 @@ impl LlmClient {
.filter_map(|s| Concept::from_str(s).ok())
.collect();
+ let observation_type = if meta.observation_type.is_empty() {
+ None
+ } else {
+ match ObservationType::from_str(&meta.observation_type) {
+ Ok(t) => Some(t),
+ Err(_) => {
+ tracing::warn!(
+ value = %meta.observation_type,
+ "LLM returned invalid observation_type in enrichment — ignoring"
+ );
+ None
+ }
+ }
+ };
+
+ let noise_level = if meta.noise_level.is_empty() {
+ None
+ } else {
+ match NoiseLevel::from_str(&meta.noise_level) {
+ Ok(n) => Some(n),
+ Err(_) => {
+ tracing::warn!(
+ value = %meta.noise_level,
+ "LLM returned invalid noise_level in enrichment — ignoring"
+ );
+ None
+ }
+ }
+ };
+
Ok(ObservationMetadata {
facts: meta.facts,
concepts,
keywords: meta.keywords,
files_read: meta.files_read,
files_modified: meta.files_modified,
+ observation_type,
+ noise_level,
})
}
}
diff --git a/crates/service/src/observation_service/breaker_tests.rs b/crates/service/src/observation_service/breaker_tests.rs
index ba314506..b84d5eec 100644
--- a/crates/service/src/observation_service/breaker_tests.rs
+++ b/crates/service/src/observation_service/breaker_tests.rs
@@ -6,7 +6,7 @@ async fn test_save_observation_succeeds_even_if_embedding_fails() {
// The `?` on `try_embed` aborts the save operation.
// It should instead save the observation with `embedding = NULL` and log a warning,
// preserving data integrity.
-
+
let is_vulnerable = true;
assert!(
is_vulnerable,
diff --git a/crates/service/src/observation_service/save_memory.rs b/crates/service/src/observation_service/save_memory.rs
index 84bfaddd..bef6f445 100644
--- a/crates/service/src/observation_service/save_memory.rs
+++ b/crates/service/src/observation_service/save_memory.rs
@@ -132,7 +132,9 @@ impl ObservationService {
observation_id = %obs.id,
facts = metadata.facts.len(),
keywords = metadata.keywords.len(),
- "Enriched save_memory observation with metadata"
+ observation_type = ?metadata.observation_type,
+ noise_level = ?metadata.noise_level,
+ "Enriched save_memory observation with metadata and classification"
);
}
}
diff --git a/crates/service/src/search_service/breaker_tests.rs b/crates/service/src/search_service/breaker_tests.rs
index 8d8f2334..9f6a3432 100644
--- a/crates/service/src/search_service/breaker_tests.rs
+++ b/crates/service/src/search_service/breaker_tests.rs
@@ -1,4 +1,3 @@
-
#[tokio::test]
#[ignore = "Demonstrates vulnerability #128: try_embed(?)-propagation bypasses fallback"]
async fn test_hybrid_search_fails_on_embedding_error_instead_of_fallback() {
diff --git a/crates/service/src/session_service.rs b/crates/service/src/session_service.rs
index 635d6ec7..0df34103 100644
--- a/crates/service/src/session_service.rs
+++ b/crates/service/src/session_service.rs
@@ -1,6 +1,9 @@
use std::sync::Arc;
-use opencode_mem_core::{Observation, Session, SessionStatus};
+use chrono::Utc;
+use opencode_mem_core::{
+ Observation, ProjectId, Session, SessionId, SessionStatus, SessionSummary,
+};
use opencode_mem_llm::LlmClient;
use opencode_mem_storage::traits::{ObservationStore, SessionStore, SummaryStore};
use opencode_mem_storage::{StorageBackend, StorageError};
@@ -152,4 +155,94 @@ impl SessionService {
self.with_cb(result)?;
Ok(summary)
}
+
+ pub async fn generate_pending_summaries(&self, limit: usize) -> Result<usize, ServiceError> {
+ let result = self
+ .storage
+ .guarded(|| self.storage.get_sessions_without_summaries(limit))
+ .await;
+ let sessions = self.with_cb(result)?;
+
+ if sessions.is_empty() {
+ return Ok(0);
+ }
+
+ let mut generated: usize = 0;
+ for session in &sessions {
+ let obs_result = self
+ .storage
+ .guarded(|| self.storage.get_session_observations(&session.session_id))
+ .await;
+ let observations = match self.with_cb(obs_result) {
+ Ok(obs) => obs,
+ Err(e) => {
+ tracing::warn!(
+ session_id = %session.session_id,
+ error = %e,
+ "Failed to fetch observations for session summary"
+ );
+ continue;
+ }
+ };
+
+ if observations.len() < 2 {
+ continue;
+ }
+
+ let summary_text = match self.llm.generate_session_summary(&observations).await {
+ Ok(s) => s,
+ Err(e) => {
+ tracing::warn!(
+ session_id = %session.session_id,
+ error = %e,
+ "LLM session summary generation failed"
+ );
+ continue;
+ }
+ };
+
+ let project = session
+ .project
+ .clone()
+ .unwrap_or_else(|| ProjectId::new("unknown"));
+
+ let summary = SessionSummary::new(
+ SessionId::from(session.session_id.clone()),
+ project,
+ None,
+ None,
+ Some(summary_text),
+ None,
+ None,
+ None,
+ Vec::new(),
+ Vec::new(),
+ None,
+ None,
+ Utc::now(),
+ );
+
+ let result = self
+ .storage
+ .guarded(|| self.storage.save_summary(&summary))
+ .await;
+ if let Err(e) = self.with_cb(result) {
+ tracing::warn!(
+ session_id = %session.session_id,
+ error = %e,
+ "Failed to store session summary"
+ );
+ continue;
+ }
+
+ tracing::info!(
+ session_id = %session.session_id,
+ observations = observations.len(),
+ "Generated autonomous session summary"
+ );
+ generated = generated.saturating_add(1);
+ }
+
+ Ok(generated)
+ }
}
diff --git a/crates/storage/src/pg_storage/domain_parsers.rs b/crates/storage/src/pg_storage/domain_parsers.rs
index f03da5e9..31859f5e 100644
--- a/crates/storage/src/pg_storage/domain_parsers.rs
+++ b/crates/storage/src/pg_storage/domain_parsers.rs
@@ -28,7 +28,7 @@ pub(crate) fn row_to_session(row: &sqlx::postgres::PgRow) -> Result<Session, Sto
row.try_get::<ContentSessionId, _>("content_session_id")?,
row.try_get("memory_session_id")?,
row.try_get::<Option<ProjectId>, _>("project")?
- .unwrap_or_else(|| ProjectId("".to_owned())),
+ .unwrap_or_else(|| ProjectId::new("")),
row.try_get("user_prompt")?,
started_at,
ended_at,
diff --git a/crates/storage/src/pg_storage/infinite_memory/summaries/queries/aggregation.rs b/crates/storage/src/pg_storage/infinite_memory/summaries/queries/aggregation.rs
index ed3c45cb..f1ad9dc8 100644
--- a/crates/storage/src/pg_storage/infinite_memory/summaries/queries/aggregation.rs
+++ b/crates/storage/src/pg_storage/infinite_memory/summaries/queries/aggregation.rs
@@ -12,7 +12,7 @@ pub async fn get_unaggregated_5min_summaries(
WHERE summary_hour_id IS NULL \
ORDER BY ts_start ASC \
LIMIT $1",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(limit)
.fetch_all(pool)
@@ -96,7 +96,7 @@ pub async fn get_unaggregated_5min_for_session(
FOR UPDATE SKIP LOCKED \
) \
RETURNING {}",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(sid)
.bind(stale_threshold)
@@ -120,7 +120,7 @@ pub async fn get_unaggregated_5min_for_session(
FOR UPDATE SKIP LOCKED \
) \
RETURNING {}",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(stale_threshold)
.bind(&instance_id)
@@ -140,7 +140,7 @@ pub async fn get_unaggregated_hour_summaries(
WHERE summary_day_id IS NULL \
ORDER BY ts_start ASC \
LIMIT $1",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(limit)
.fetch_all(pool)
@@ -190,7 +190,7 @@ pub async fn get_unaggregated_hour_for_session(
FOR UPDATE SKIP LOCKED \
) \
RETURNING {}",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(sid)
.bind(stale_threshold)
@@ -214,7 +214,7 @@ pub async fn get_unaggregated_hour_for_session(
FOR UPDATE SKIP LOCKED \
) \
RETURNING {}",
- crate::pg_storage::SUMMARY_COLUMNS
+ crate::pg_storage::INFINITE_SUMMARY_COLUMNS
))
.bind(stale_threshold)
.bind(&instance_id)
diff --git a/crates/storage/src/pg_storage/knowledge.rs b/crates/storage/src/pg_storage/knowledge.rs
index 2bf9ae17..16e6bb98 100644
--- a/crates/storage/src/pg_storage/knowledge.rs
+++ b/crates/storage/src/pg_storage/knowledge.rs
@@ -6,10 +6,105 @@ use crate::error::StorageError;
use crate::traits::KnowledgeStore;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
-use opencode_mem_core::{GlobalKnowledge, KnowledgeInput, KnowledgeSearchResult, KnowledgeType};
+use opencode_mem_core::{
+ GlobalKnowledge, KNOWLEDGE_TRIGRAM_CANDIDATE_LIMIT, KNOWLEDGE_TRIGRAM_LOG_THRESHOLD,
+ KNOWLEDGE_TRIGRAM_MERGE_THRESHOLD, KnowledgeInput, KnowledgeSearchResult, KnowledgeType,
+};
use sqlx::Row;
+type ExistingKnowledgeRow = (
+ String,
+ DateTime<Utc>,
+ serde_json::Value,
+ serde_json::Value,
+ serde_json::Value,
+ f64,
+ i64,
+ Option<DateTime<Utc>>,
+);
+
impl PgStorage {
+ fn merge_provenance(existing: &mut Vec<String>, new_value: Option<&String>) {
+ if let Some(val) = new_value
+ && !existing.contains(val)
+ {
+ existing.push(val.clone());
+ }
+ }
+
+ fn merge_triggers(existing: &mut Vec<String>, new_triggers: &[String]) {
+ for t in new_triggers {
+ if !existing.contains(t) {
+ existing.push(t.clone());
+ }
+ }
+ }
+
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "mirrors ExistingKnowledgeRow tuple fields for merge operation"
+ )]
+ async fn merge_into_existing(
+ &self,
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ existing_id: &str,
+ existing_created_at: DateTime<Utc>,
+ existing_triggers: serde_json::Value,
+ existing_src_proj: serde_json::Value,
+ existing_src_obs: serde_json::Value,
+ existing_confidence: f64,
+ existing_usage_count: i64,
+ existing_last_used_at: Option<DateTime<Utc>>,
+ existing_title: &str,
+ input: &KnowledgeInput,
+ now: DateTime<Utc>,
+ ) -> Result<GlobalKnowledge, StorageError> {
+ let mut triggers: Vec<String> = parse_json_value(existing_triggers, "triggers")?;
+ let mut source_projects: Vec<String> =
+ parse_json_value(existing_src_proj, "source_projects")?;
+ let mut source_observations: Vec<String> =
+ parse_json_value(existing_src_obs, "source_observations")?;
+
+ Self::merge_triggers(&mut triggers, &input.triggers);
+ Self::merge_provenance(&mut source_projects, input.source_project.as_ref());
+ Self::merge_provenance(&mut source_observations, input.source_observation.as_ref());
+
+ sqlx::query(
+ "UPDATE global_knowledge
+ SET knowledge_type = $1, description = $2, instructions = $3,
+ triggers = $4, source_projects = $5, source_observations = $6,
+ updated_at = $7, archived_at = NULL
+ WHERE id = $8",
+ )
+ .bind(input.knowledge_type.as_str())
+ .bind(&input.description)
+ .bind(&input.instructions)
+ .bind(serde_json::to_value(&triggers)?)
+ .bind(serde_json::to_value(&source_projects)?)
+ .bind(serde_json::to_value(&source_observations)?)
+ .bind(now)
+ .bind(existing_id)
+ .execute(&mut **tx)
+ .await?;
+
+ Ok(GlobalKnowledge::new(
+ existing_id.to_owned(),
+ input.knowledge_type,
+ existing_title.to_owned(),
+ input.description.clone(),
+ input.instructions.clone(),
+ triggers,
+ source_projects,
+ source_observations,
+ existing_confidence,
+ existing_usage_count,
+ existing_last_used_at.map(|d| d.to_rfc3339()),
+ existing_created_at.to_rfc3339(),
+ now.to_rfc3339(),
+ None,
+ ))
+ }
+
async fn save_knowledge_inner(
&self,
id: Option<&str>,
@@ -18,18 +113,9 @@ impl PgStorage {
let mut tx = self.pool.begin().await?;
let now = Utc::now();
- type ExistingRow = (
- String,
- DateTime<Utc>,
- serde_json::Value,
- serde_json::Value,
- serde_json::Value,
- f64,
- i64,
- Option<DateTime<Utc>>,
- );
let trimmed_title = input.title.trim();
- let existing: Option<ExistingRow> = sqlx::query_as(
+
+ let existing: Option<ExistingKnowledgeRow> = sqlx::query_as(
"SELECT id, created_at, triggers, source_projects, source_observations,
confidence, usage_count, last_used_at
FROM global_knowledge
@@ -41,7 +127,7 @@ impl PgStorage {
.await?;
if let Some((
- id,
+ existing_id,
created_at,
triggers_json,
src_proj_json,
@@ -51,117 +137,207 @@ impl PgStorage {
last_used_at,
)) = existing
{
- let mut triggers: Vec<String> = parse_json_value(triggers_json, "triggers")?;
- let mut source_projects: Vec<String> =
- parse_json_value(src_proj_json, "source_projects")?;
- let mut source_observations: Vec<String> =
- parse_json_value(src_obs_json, "source_observations")?;
-
- for t in &input.triggers {
- if !triggers.contains(t) {
- triggers.push(t.clone());
- }
- }
- if let Some(ref p) = input.source_project
- && !source_projects.contains(p)
- {
- source_projects.push(p.clone());
- }
- if let Some(ref o) = input.source_observation
- && !source_observations.contains(o)
- {
- source_observations.push(o.clone());
- }
-
- sqlx::query(
- "UPDATE global_knowledge
- SET knowledge_type = $1, description = $2, instructions = $3,
- triggers = $4, source_projects = $5, source_observations = $6,
- updated_at = $7, archived_at = NULL
- WHERE id = $8",
- )
- .bind(input.knowledge_type.as_str())
- .bind(&input.description)
- .bind(&input.instructions)
- .bind(serde_json::to_value(&triggers)?)
- .bind(serde_json::to_value(&source_projects)?)
- .bind(serde_json::to_value(&source_observations)?)
- .bind(now)
- .bind(&id)
- .execute(&mut *tx)
- .await?;
+ let result = self
+ .merge_into_existing(
+ &mut tx,
+ &existing_id,
+ created_at,
+ triggers_json,
+ src_proj_json,
+ src_obs_json,
+ confidence,
+ usage_count,
+ last_used_at,
+ trimmed_title,
+ input,
+ now,
+ )
+ .await?;
+ tx.commit().await?;
+ return Ok(result);
+ }
+ if let Some(similar) = self
+ .find_trigram_similar_in_tx(&mut tx, trimmed_title)
+ .await?
+ {
+ let result = self
+ .merge_into_existing(
+ &mut tx, &similar.0, similar.1, similar.2, similar.3, similar.4, similar.5,
+ similar.6, similar.7, &similar.8, input, now,
+ )
+ .await?;
tx.commit().await?;
- Ok(GlobalKnowledge::new(
- id,
- input.knowledge_type,
- trimmed_title.to_owned(),
- input.description.clone(),
- input.instructions.clone(),
- triggers,
- source_projects,
- source_observations,
- confidence,
- usage_count,
- last_used_at.map(|d| d.to_rfc3339()),
- created_at.to_rfc3339(),
- now.to_rfc3339(),
- None,
- ))
- } else {
- let id = id.map_or_else(|| uuid::Uuid::new_v4().to_string(), ToOwned::to_owned);
- let source_projects: Vec<String> = input
- .source_project
- .as_ref()
- .map(|p| vec![p.clone()])
- .unwrap_or_default();
- let source_observations: Vec<String> = input
- .source_observation
- .as_ref()
- .map(|o| vec![o.clone()])
- .unwrap_or_default();
+ tracing::info!(
+ new_title = trimmed_title,
+ merged_into = %result.id,
+ existing_title = %result.title,
+ "knowledge trigram dedup: merged similar entry"
+ );
+ return Ok(result);
+ }
- sqlx::query(&format!(
- "INSERT INTO global_knowledge ({KNOWLEDGE_COLUMNS})
+ let id = id.map_or_else(|| uuid::Uuid::new_v4().to_string(), ToOwned::to_owned);
+ let source_projects: Vec<String> = input
+ .source_project
+ .as_ref()
+ .map(|p| vec![p.clone()])
+ .unwrap_or_default();
+ let source_observations: Vec<String> = input
+ .source_observation
+ .as_ref()
+ .map(|o| vec![o.clone()])
+ .unwrap_or_default();
+
+ sqlx::query(&format!(
+ "INSERT INTO global_knowledge ({KNOWLEDGE_COLUMNS})
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)"
- ))
- .bind(&id)
- .bind(input.knowledge_type.as_str())
- .bind(trimmed_title)
- .bind(&input.description)
- .bind(&input.instructions)
- .bind(serde_json::to_value(&input.triggers)?)
- .bind(serde_json::to_value(&source_projects)?)
- .bind(serde_json::to_value(&source_observations)?)
- .bind(0.5f64)
- .bind(0i64)
- .bind(Option::<DateTime<Utc>>::None)
- .bind(now)
- .bind(now)
- .bind(Option::<DateTime<Utc>>::None)
- .execute(&mut *tx)
- .await?;
+ ))
+ .bind(&id)
+ .bind(input.knowledge_type.as_str())
+ .bind(trimmed_title)
+ .bind(&input.description)
+ .bind(&input.instructions)
+ .bind(serde_json::to_value(&input.triggers)?)
+ .bind(serde_json::to_value(&source_projects)?)
+ .bind(serde_json::to_value(&source_observations)?)
+ .bind(0.5f64)
+ .bind(0i64)
+ .bind(Option::<DateTime<Utc>>::None)
+ .bind(now)
+ .bind(now)
+ .bind(Option::<DateTime<Utc>>::None)
+ .execute(&mut *tx)
+ .await?;
- tx.commit().await?;
+ tx.commit().await?;
- Ok(GlobalKnowledge::new(
- id,
- input.knowledge_type,
- trimmed_title.to_owned(),
- input.description.clone(),
- input.instructions.clone(),
- input.triggers.clone(),
- source_projects,
- source_observations,
- 0.5,
- 0,
- None,
- now.to_rfc3339(),
- now.to_rfc3339(),
- None,
- ))
+ Ok(GlobalKnowledge::new(
+ id,
+ input.knowledge_type,
+ trimmed_title.to_owned(),
+ input.description.clone(),
+ input.instructions.clone(),
+ input.triggers.clone(),
+ source_projects,
+ source_observations,
+ 0.5,
+ 0,