-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
1795 lines (1688 loc) · 56 KB
/
Copy pathmain.rs
File metadata and controls
1795 lines (1688 loc) · 56 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
use clap::{Parser, Subcommand};
use serde_json::json;
use std::ffi::OsString;
use std::fs;
use std::path::PathBuf;
use tree_ring_memory_core::plan_maintenance;
use tree_ring_memory_core::sensitivity::SensitivityGuard;
use tree_ring_memory_core::{
audit_memories, collect_dox_memories, collect_revolve_memories, consolidate_memories,
decode_jsonl, normalize_import_events, AuditReport, ConsolidationPeriod, ConsolidationReport,
ConsolidationRequest, DoxSyncReport, DoxSyncRequest, MaintenanceReport, MaintenanceRequest,
RevolveSyncReport, RevolveSyncRequest,
};
use tree_ring_memory_core::{MemoryEvent, MemoryLink};
use tree_ring_memory_sqlite::{MemoryRetriever, SQLiteMemoryStore};
mod agent_awareness;
mod integrations;
mod ring_mark;
mod tui;
mod welcome;
#[derive(Debug, Parser)]
#[command(
name = "tree-ring",
version,
about = "Local tree-ring memory for AI agents."
)]
struct Cli {
#[arg(
long,
default_value = ".tree-ring",
global = true,
help = "memory store root"
)]
root: PathBuf,
#[arg(
long,
global = true,
help = "emit machine-readable JSON where supported"
)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
#[command(about = "initialize a local memory store")]
Init,
#[command(about = "store a memory")]
Remember {
summary: String,
#[arg(long)]
event_type: String,
#[arg(long, default_value = "cambium")]
ring: String,
#[arg(long, default_value = "global")]
scope: String,
#[arg(long)]
project: Option<String>,
#[arg(long = "tag")]
tags: Vec<String>,
},
#[command(about = "record an evidence-backed improvement-loop outcome")]
Evidence {
summary: String,
#[arg(
long,
default_value = "observed",
help = "observed, promoted, rejected, or deferred"
)]
outcome: String,
#[arg(
long,
help = "file path, run id, checkpoint id, PR, issue, or eval ref"
)]
evidence_ref: String,
#[arg(long, help = "optional project scope")]
project: Option<String>,
#[arg(long, help = "optional extra context")]
details: Option<String>,
#[arg(long, help = "optional numeric evaluation score")]
score: Option<f64>,
#[arg(long = "tag")]
tags: Vec<String>,
},
#[command(about = "recall memories")]
Recall {
query: String,
#[arg(long)]
project: Option<String>,
#[arg(long, default_value_t = 8)]
limit: usize,
#[arg(long)]
include_sensitive: bool,
},
#[command(about = "delete or redact a memory")]
Forget {
memory_id: String,
#[arg(long, default_value = "delete")]
mode: ForgetMode,
#[arg(long)]
reason: String,
},
#[command(about = "export memories as portable JSONL")]
Export {
#[arg(long, help = "write JSONL export to a file instead of stdout")]
output: Option<PathBuf>,
#[arg(long, help = "include sensitive memories in the export")]
include_sensitive: bool,
#[arg(long, help = "include superseded memories in the export")]
include_superseded: bool,
},
#[command(about = "import memories from portable JSONL")]
Import {
path: PathBuf,
#[arg(long, help = "validate the import without writing memories")]
dry_run: bool,
#[arg(long, help = "replace existing memories with matching ids")]
replace_existing: bool,
},
#[command(about = "audit memory quality, privacy, and integrity")]
Audit {
#[arg(
long,
default_value = "all",
help = "all, stale, sensitive, low_confidence, supersession, or contradictions"
)]
audit_type: String,
},
#[command(about = "consolidate memories into deterministic ring summaries")]
Consolidate {
#[arg(
long,
default_value = "daily",
help = "daily, weekly, monthly, yearly, or manual"
)]
period_type: String,
#[arg(
long,
help = "stable period key; derived from current UTC time when omitted"
)]
period_key: Option<String>,
#[arg(long, help = "optional project filter")]
project: Option<String>,
#[arg(long, help = "plan consolidation without writing summaries or records")]
dry_run: bool,
#[arg(
long,
help = "create a new consolidation and supersede prior summaries"
)]
force: bool,
},
#[command(about = "plan or apply Rust-owned memory maintenance")]
Maintain {
#[arg(long, help = "optional project filter")]
project: Option<String>,
#[arg(long, help = "include superseded memories in maintenance planning")]
include_superseded: bool,
#[arg(long, help = "delete expired temporary memories")]
apply_expired: bool,
#[arg(long, help = "redact memories with secret-like content")]
apply_secret_redactions: bool,
#[arg(long, help = "rebuild the SQLite FTS index")]
repair_fts: bool,
},
#[command(about = "open the Rust-native Tree Ring Memory terminal console")]
Tui {
#[arg(long, help = "optional JSONL event stream to light rings in real time")]
event_stream: Option<PathBuf>,
#[arg(
long,
default_value_t = 250,
help = "animation and refresh cadence in milliseconds"
)]
tick_ms: u64,
},
#[command(about = "show first-run onboarding and next commands")]
Welcome {
#[arg(long, help = "initialize the configured memory root during onboarding")]
init: bool,
#[arg(long, help = "print a stable onboarding screen without animation")]
no_animation: bool,
},
#[command(about = "summarize DOX-style AGENTS.md guidance into memory")]
Dox {
#[command(subcommand)]
command: DoxCommand,
},
#[command(about = "import Revolve-style evidence records into memory")]
Revolve {
#[command(subcommand)]
command: RevolveCommand,
},
#[command(about = "discover local agent-framework integration markers")]
Integrations {
#[command(subcommand)]
command: IntegrationCommand,
},
}
#[derive(Debug, Subcommand)]
enum DoxCommand {
#[command(about = "scan AGENTS.md files and store concise source-linked memories")]
Sync {
#[arg(
long,
default_value = ".",
help = "project root or AGENTS.md file to scan"
)]
source_root: PathBuf,
#[arg(long, help = "optional project scope for imported memories")]
project: Option<String>,
#[arg(long, help = "preview generated memories without writing them")]
dry_run: bool,
},
}
#[derive(Debug, Subcommand)]
enum RevolveCommand {
#[command(about = "scan Revolve records and store evidence-linked memories")]
Sync {
#[arg(
long,
default_value = "revolve",
help = "Revolve root or evidence file to scan"
)]
source_root: PathBuf,
#[arg(long, help = "optional project scope for imported memories")]
project: Option<String>,
#[arg(long, help = "preview generated memories without writing them")]
dry_run: bool,
},
}
#[derive(Debug, Subcommand)]
enum IntegrationCommand {
#[command(about = "scan a project root for known agent-framework markers")]
Scan {
#[arg(long, default_value = ".", help = "project root to scan")]
source_root: PathBuf,
},
}
#[derive(Debug, Clone, clap::ValueEnum)]
enum ForgetMode {
Delete,
Redact,
}
fn main() -> std::process::ExitCode {
let args = std::env::args_os().collect::<Vec<_>>();
if let Some((root, json_output)) = global_welcome_request(&args) {
return exit_from_result(welcome::run(&root, false, false, json_output));
}
exit_from_result(run(Cli::parse_from(args)))
}
fn exit_from_result(result: Result<(), String>) -> std::process::ExitCode {
match result {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(error) => {
eprintln!("{error}");
std::process::ExitCode::from(2)
}
}
}
fn global_welcome_request(args: &[OsString]) -> Option<(PathBuf, bool)> {
let mut index = 1usize;
let mut root = PathBuf::from(".tree-ring");
let mut json_output = false;
while index < args.len() {
let arg = args[index].to_str()?;
match arg {
"--json" => {
json_output = true;
index += 1;
}
"--root" => {
let value = args.get(index + 1)?;
root = PathBuf::from(value);
index += 2;
}
"-h" | "--help" | "-V" | "--version" => return None,
value if value.starts_with("--root=") => {
root = PathBuf::from(value.trim_start_matches("--root="));
index += 1;
}
value if value.starts_with('-') => return None,
_command => return None,
}
}
Some((root, json_output))
}
fn run(cli: Cli) -> Result<(), String> {
let db_path = cli.root.join("memory.sqlite");
if let Command::Welcome { init, no_animation } = &cli.command {
return welcome::run(&cli.root, *init, *no_animation, cli.json);
}
if let Command::Integrations {
command: IntegrationCommand::Scan { source_root },
} = &cli.command
{
let report = integrations::scan_integrations(source_root);
print_integration_report(&report, cli.json)?;
return Ok(());
}
if let Command::Tui {
event_stream,
tick_ms,
} = cli.command
{
if cli.json {
return Err("--json is not supported with the interactive TUI".to_string());
}
return tui::run(cli.root, event_stream, tick_ms);
}
if let Command::Import {
path,
dry_run: true,
replace_existing: _,
} = cli.command
{
let input = fs::read_to_string(&path).map_err(|err| err.to_string())?;
let decoded = decode_jsonl(&input).map_err(|err| err.to_string())?;
let events = normalize_import_events(decoded.events).map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
json!({
"ok": true,
"path": path,
"valid_count": events.len(),
"inserted_count": 0,
"replaced_count": 0,
"skipped_duplicate_count": 0,
"dry_run": true,
})
);
} else {
println!(
"Tree Ring Memory import complete: valid={} inserted=0 replaced=0 skipped_duplicates=0 dry_run=true",
events.len()
);
}
return Ok(());
}
if let Command::Audit { audit_type } = &cli.command {
let report = if db_path.exists() {
SQLiteMemoryStore::open_read_only(&db_path)
.and_then(|store| store.audit(audit_type))
.map_err(|err| err.to_string())?
} else {
audit_memories(&[], audit_type).map_err(|err| err.to_string())?
};
print_audit_report(&report, cli.json)?;
return Ok(());
}
if let Command::Consolidate {
period_type,
period_key,
project,
dry_run: true,
force,
} = &cli.command
{
let request = consolidation_request(
period_type,
period_key.clone(),
project.clone(),
true,
*force,
)?;
let report = if db_path.exists() {
let store =
SQLiteMemoryStore::open_read_only(&db_path).map_err(|err| err.to_string())?;
let events = store.list_all(false).map_err(|err| err.to_string())?;
consolidate_memories(&events, &request).map_err(|err| err.to_string())?
} else {
consolidate_memories(&[], &request).map_err(|err| err.to_string())?
};
print_consolidation_report(&report, cli.json)?;
return Ok(());
}
if let Command::Maintain {
project,
include_superseded,
apply_expired,
apply_secret_redactions,
repair_fts,
} = &cli.command
{
let request = maintenance_request(
project.clone(),
*include_superseded,
*apply_expired,
*apply_secret_redactions,
*repair_fts,
);
if request.dry_run {
let report = if db_path.exists() {
let mut store =
SQLiteMemoryStore::open_read_only(&db_path).map_err(|err| err.to_string())?;
store.maintain(&request).map_err(|err| err.to_string())?
} else {
plan_maintenance(&[], &request)
};
print_maintenance_report(&report, cli.json)?;
return Ok(());
}
}
if let Command::Dox {
command:
DoxCommand::Sync {
source_root,
project,
dry_run: true,
},
} = &cli.command
{
let report = collect_dox_memories(&dox_request(source_root.clone(), project.clone()))
.map_err(|err| err.to_string())?;
print_dox_report(&report, cli.json, true)?;
return Ok(());
}
if let Command::Revolve {
command:
RevolveCommand::Sync {
source_root,
project,
dry_run: true,
},
} = &cli.command
{
let report =
collect_revolve_memories(&revolve_request(source_root.clone(), project.clone()))
.map_err(|err| err.to_string())?;
print_revolve_report(&report, cli.json, true)?;
return Ok(());
}
let mut store = SQLiteMemoryStore::open(&db_path).map_err(|err| err.to_string())?;
match cli.command {
Command::Init => {
let awareness = agent_awareness::ensure_agent_awareness(&cli.root)
.map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
json!({
"ok": true,
"root": cli.root,
"sqlite_path": db_path,
"message": "Tree Ring Memory initialized",
"agent_awareness": awareness,
})
);
} else {
println!("Tree Ring Memory initialized at {}", cli.root.display());
println!("No cloud sync; secret-like memory is blocked by default.");
print_agent_awareness_summary(&awareness);
}
}
Command::Remember {
summary,
event_type,
ring,
scope,
project,
tags,
} => {
let guard = SensitivityGuard::default();
let values = [&summary, &event_type, &ring, &scope]
.into_iter()
.chain(project.iter())
.chain(tags.iter())
.map(String::as_str);
let detected_sensitivity = guard
.detect_text_sensitivity(values)
.map_err(|err| err.to_string())?;
let mut event = MemoryEvent::new(summary, event_type).map_err(|err| err.to_string())?;
event.ring = ring;
event.scope = scope;
event.project = project;
event.tags = tags;
if detected_sensitivity != "normal" {
event.sensitivity = detected_sensitivity;
}
event.validate().map_err(|err| err.to_string())?;
store.put(&event).map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
serde_json::to_string(&event).map_err(|err| err.to_string())?
);
} else {
println!("{}", event.id);
}
}
Command::Evidence {
summary,
outcome,
evidence_ref,
project,
details,
score,
tags,
} => {
let event = evidence_event(
summary,
outcome,
evidence_ref,
project,
details,
score,
tags,
)?;
store.put(&event).map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
serde_json::to_string(&event).map_err(|err| err.to_string())?
);
} else {
println!(
"{} [{}] {} evidence={}",
event.id, event.ring, event.summary, event.source.ref_
);
}
}
Command::Recall {
query,
project,
limit,
include_sensitive,
} => {
let results = MemoryRetriever::new(&store)
.recall(
&query,
project.as_deref(),
None,
None,
None,
None,
include_sensitive,
false,
limit,
false,
)
.map_err(|err| err.to_string())?;
if cli.json {
let payload: Vec<_> = results
.into_iter()
.map(|result| {
json!({
"memory": result.memory,
"score": result.score,
"ranking": result.ranking,
})
})
.collect();
println!(
"{}",
serde_json::to_string(&payload).map_err(|err| err.to_string())?
);
} else {
for result in results {
println!(
"{} [{}] {} score={:.3}",
result.memory.id, result.memory.ring, result.memory.summary, result.score
);
}
}
}
Command::Forget {
memory_id,
mode,
reason,
} => {
if reason.trim().is_empty() {
return Err("forget reason is required".to_string());
}
match mode {
ForgetMode::Delete => store.delete(&memory_id).map_err(|err| err.to_string())?,
ForgetMode::Redact => store.redact(&memory_id).map_err(|err| err.to_string())?,
}
if cli.json {
println!("{}", json!({"ok": true, "memory_id": memory_id}));
} else {
println!("Tree Ring Memory forget complete: {memory_id}");
}
}
Command::Export {
output,
include_sensitive,
include_superseded,
} => {
let (jsonl, report) = store
.export_jsonl(include_sensitive, include_superseded)
.map_err(|err| err.to_string())?;
if let Some(output) = output {
if let Some(parent) = output.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent).map_err(|err| err.to_string())?;
}
}
fs::write(&output, jsonl).map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
json!({
"ok": true,
"path": output,
"memory_count": report.memory_count,
"sensitive_included": report.sensitive_included,
"superseded_included": report.superseded_included,
})
);
} else {
println!(
"Tree Ring Memory export complete: {} memories -> {}",
report.memory_count,
output.display()
);
}
} else {
print!("{jsonl}");
}
}
Command::Import {
path,
dry_run,
replace_existing,
} => {
let input = fs::read_to_string(&path).map_err(|err| err.to_string())?;
let report = store
.import_jsonl(&input, dry_run, replace_existing)
.map_err(|err| err.to_string())?;
if cli.json {
println!(
"{}",
json!({
"ok": true,
"path": path,
"valid_count": report.valid_count,
"inserted_count": report.inserted_count,
"replaced_count": report.replaced_count,
"skipped_duplicate_count": report.skipped_duplicate_count,
"dry_run": report.dry_run,
})
);
} else {
println!(
"Tree Ring Memory import complete: valid={} inserted={} replaced={} skipped_duplicates={} dry_run={}",
report.valid_count,
report.inserted_count,
report.replaced_count,
report.skipped_duplicate_count,
report.dry_run
);
}
}
Command::Audit { .. } => unreachable!("audit returns before opening the writable store"),
Command::Consolidate {
period_type,
period_key,
project,
dry_run,
force,
} => {
let request = consolidation_request(&period_type, period_key, project, dry_run, force)?;
let report = store.consolidate(&request).map_err(|err| err.to_string())?;
print_consolidation_report(&report, cli.json)?;
}
Command::Maintain {
project,
include_superseded,
apply_expired,
apply_secret_redactions,
repair_fts,
} => {
let request = maintenance_request(
project,
include_superseded,
apply_expired,
apply_secret_redactions,
repair_fts,
);
let report = store.maintain(&request).map_err(|err| err.to_string())?;
print_maintenance_report(&report, cli.json)?;
}
Command::Tui { .. } => unreachable!("tui returns before opening the scriptable store"),
Command::Welcome { .. } => {
unreachable!("welcome returns before opening the scriptable store")
}
Command::Integrations { .. } => {
unreachable!("integrations scan returns before opening the scriptable store")
}
Command::Dox {
command:
DoxCommand::Sync {
source_root,
project,
dry_run,
},
} => {
let report = collect_dox_memories(&dox_request(source_root, project))
.map_err(|err| err.to_string())?;
if !dry_run {
store
.put_many(&report.events)
.map_err(|err| err.to_string())?;
}
print_dox_report(&report, cli.json, dry_run)?;
}
Command::Revolve {
command:
RevolveCommand::Sync {
source_root,
project,
dry_run,
},
} => {
let report = collect_revolve_memories(&revolve_request(source_root, project))
.map_err(|err| err.to_string())?;
if !dry_run {
store
.put_many(&report.events)
.map_err(|err| err.to_string())?;
}
print_revolve_report(&report, cli.json, dry_run)?;
}
}
Ok(())
}
fn dox_request(source_root: PathBuf, project: Option<String>) -> DoxSyncRequest {
let mut request = DoxSyncRequest::new(source_root);
request.project = project;
request
}
fn revolve_request(source_root: PathBuf, project: Option<String>) -> RevolveSyncRequest {
let mut request = RevolveSyncRequest::new(source_root);
request.project = project;
request
}
fn maintenance_request(
project: Option<String>,
include_superseded: bool,
apply_expired: bool,
apply_secret_redactions: bool,
repair_fts: bool,
) -> MaintenanceRequest {
MaintenanceRequest {
dry_run: !(apply_expired || apply_secret_redactions || repair_fts),
apply_expired,
apply_secret_redactions,
repair_fts,
include_superseded,
project,
}
}
fn consolidation_request(
period_type: &str,
period_key: Option<String>,
project: Option<String>,
dry_run: bool,
force: bool,
) -> Result<ConsolidationRequest, String> {
Ok(ConsolidationRequest {
period_type: ConsolidationPeriod::parse(period_type).map_err(|err| err.to_string())?,
period_key,
project,
dry_run,
force,
})
}
fn evidence_event(
summary: String,
outcome: String,
evidence_ref: String,
project: Option<String>,
details: Option<String>,
score: Option<f64>,
tags: Vec<String>,
) -> Result<MemoryEvent, String> {
if summary.trim().is_empty() {
return Err("evidence summary is required".to_string());
}
if evidence_ref.trim().is_empty() {
return Err("evidence-ref is required".to_string());
}
if let Some(score) = score {
if !(0.0..=1.0).contains(&score) {
return Err("evidence score must be between 0 and 1".to_string());
}
}
let normalized_outcome = outcome.trim().to_ascii_lowercase();
let (ring, event_type, salience, confidence, retention) = match normalized_outcome.as_str() {
"promoted" | "promotion" => (
"heartwood",
"evaluation_promotion",
0.86,
score.unwrap_or(0.84).max(0.75),
"durable",
),
"rejected" | "rejection" => (
"scar",
"evaluation_rejection",
0.90,
score.unwrap_or(0.78),
"durable",
),
"deferred" | "seed" | "hypothesis" => (
"seed",
"evaluation_hypothesis",
0.68,
score.unwrap_or(0.60),
"normal",
),
"observed" | "observation" | "result" => (
"outer",
"evaluation_result",
0.72,
score.unwrap_or(0.70),
"normal",
),
_ => {
return Err(
"evidence outcome must be observed, promoted, rejected, or deferred".to_string(),
)
}
};
let guard = SensitivityGuard::default();
let values = [&summary, &outcome, &evidence_ref]
.into_iter()
.chain(project.iter())
.chain(details.iter())
.chain(tags.iter())
.map(String::as_str);
let detected_sensitivity = guard
.detect_text_sensitivity(values)
.map_err(|err| err.to_string())?;
let mut event = MemoryEvent::new(summary.trim(), event_type).map_err(|err| err.to_string())?;
event.ring = ring.to_string();
event.scope = "eval".to_string();
event.project = project;
event.details = evidence_details(&normalized_outcome, score, details);
event.source.source_type = "evidence".to_string();
event.source.ref_ = evidence_ref.trim().to_string();
event.tags = evidence_tags(normalized_outcome.as_str(), tags);
event.salience = salience;
event.confidence = confidence.clamp(0.0, 1.0);
event.retention = retention.to_string();
event.links.push(MemoryLink {
link_type: "evidence".to_string(),
target: event.source.ref_.clone(),
});
if detected_sensitivity != "normal" {
event.sensitivity = detected_sensitivity;
}
event.validate().map_err(|err| err.to_string())?;
Ok(event)
}
fn evidence_details(outcome: &str, score: Option<f64>, details: Option<String>) -> String {
let mut lines = vec![format!("Outcome: {outcome}")];
if let Some(score) = score {
lines.push(format!("Score: {score:.3}"));
}
if let Some(details) = details {
let trimmed = details.trim();
if !trimmed.is_empty() {
lines.push(trimmed.to_string());
}
}
lines.join("\n")
}
fn evidence_tags(outcome: &str, mut tags: Vec<String>) -> Vec<String> {
tags.push("evidence".to_string());
tags.push("improvement-loop".to_string());
tags.push(format!("outcome:{outcome}"));
tags.sort();
tags.dedup();
tags
}
fn print_audit_report(report: &AuditReport, json_output: bool) -> Result<(), String> {
if json_output {
println!(
"{}",
serde_json::to_string(report).map_err(|err| err.to_string())?
);
} else {
println!(
"Tree Ring Memory audit: type={} memories={} findings={}",
report.audit_type, report.memory_count, report.finding_count
);
for finding in &report.findings {
let memory_id = finding.memory_id.as_deref().unwrap_or("-");
let related = finding.related_memory_id.as_deref().unwrap_or("-");
println!(
"{} [{}] memory={} related={} {} -> {}",
finding.audit_type,
finding.severity,
memory_id,
related,
finding.finding,
finding.recommended_action
);
}
}
Ok(())
}
fn print_consolidation_report(
report: &ConsolidationReport,
json_output: bool,
) -> Result<(), String> {
if json_output {
println!(
"{}",
serde_json::to_string(report).map_err(|err| err.to_string())?
);
} else {
println!(
"Tree Ring Memory consolidation: type={} key={} candidates={} outputs={} status={}",
report.period_type,
report.period_key,
report.candidate_count,
report.output_memory_ids.len(),
report.status
);
if !report.notes.is_empty() {
println!("{}", report.notes);
}
}
Ok(())
}
fn print_maintenance_report(report: &MaintenanceReport, json_output: bool) -> Result<(), String> {
if json_output {
println!(
"{}",
serde_json::to_string(report).map_err(|err| err.to_string())?
);
} else {
println!(
"Tree Ring Memory maintenance: memories={} planned={} applied={} dry_run={} status={}",
report.memory_count,
report.planned_action_count,
report.applied_action_count,
report.dry_run,
report.status
);
println!(
"FTS: memories={} index={} missing={} orphan={} repaired={}",
report.fts.memory_rows,
report.fts.fts_rows,
report.fts.missing_fts_rows,
report.fts.orphan_fts_rows,
report.fts.repaired
);
for action in &report.actions {
println!(
"{} [{}] memory={} applied={} {}",
action.action_type,
action.severity,
action.memory_id,
action.applied,
action.reason
);
}
if report.dry_run {
println!(
"Report-only: use --apply-expired, --apply-secret-redactions, or --repair-fts to apply eligible maintenance."
);
}
}