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
//! Turn recorder (#2345): durable per-turn dual-write to trusty-memory.
//!
//! Why: epic #2343 (Infinite Sessions) requires every PM prompt/response
//! turn to be durably recorded in trusty-memory, independent of the
//! in-process `Transcript` (#2344), which only lives as long as the daemon
//! process. Without this, a daemon restart or crash loses the entire
//! conversation; #2348's `recall_session` tool also needs a semantic
//! recall surface over session history that a bare `chat_turn_append` record
//! alone would not give it (it stores the exact turn but is not
//! embedded/indexed for recall the way `memory_remember` is).
//! What: [`TurnMemorySink`] owns a bounded `tokio::sync::mpsc` queue and a
//! background drain task. [`TurnMemorySink::enqueue`] is the non-blocking
//! producer side, called from `task::executor::run_and_record` at each turn
//! boundary. The drain task calls BOTH `chat_turn_append` (the exact
//! chronological record) and `memory_remember` (tagged
//! `["session:<id>", "turn"]`, `force: true` — the semantic recall surface
//! for #2348) via the MCP `tools/call` envelope
//! (`crate::memory_envelope::call_tool_wrapped`; #2424 — trusty-memory's
//! direct-dispatch allowlist has no `chat_*` methods, so direct dispatch of
//! `chat_turn_append` fails `-32601` on every write), against a base URL
//! resolved ONCE at construction — never blocking or failing the calling
//! turn: any RPC failure is logged via `tracing::warn!` and dropped.
//! (#2424) Before the FIRST write, the drain task ensures the target palace
//! exists ([`ensure_palace`]) — `memory_remember` does NOT auto-create a
//! palace and fails `-32603 "palace metadata missing"` against a missing
//! one, which is exactly how the #2343 soak lost all 50 turns. The ensure
//! result is cached on success so steady state adds zero extra RPCs.
//! (#4638) That auto-create is gated on [`PalaceCreation`], decided from the
//! session's project root by `SessionRegistry::memory_sink_for`. The palace id
//! is DERIVED from that root, so an ephemeral root (a `tempfile::TempDir`)
//! yields a per-run-unique id and the ensure minted one permanent, unreadable
//! palace per run — 5,667 `t-tmp<random>` orphans in three weeks, 97.8% of
//! every palace on the machine, which made trusty-memory's O(n) full-registry
//! handlers (#4637) unusable. A palace is an expensive object (usearch index,
//! KG redb, drawer table, recall log), not a per-session scratch container:
//! the intended shape is ONE durable palace per PROJECT with each session
//! distinguished INSIDE it by `chat_turn_append`'s `session_id` and
//! `memory_remember`'s `session:<id>` tag, and that shape is what
//! [`PalaceCreation::Forbidden`] restores by making `palace_create`
//! unreachable from an ephemeral root.
//! (#2363) `memory_remember`'s dedup gate (jaro_winkler >0.92,
//! 5-min same-palace window) is documented as hostile to sequential
//! conversational turns, so every turn-recorder write passes `force: true`
//! to bypass it outright, along with the other content-QUALITY gates
//! (blocklist, short-content, noise pattern). Issue #2520 (two-tier
//! `force`): `force: true` no longer bypasses secret/credential detection —
//! this sink deliberately does NOT set the separate `allow_secret_like`
//! opt-in, so a turn whose raw LLM/tool-use content looks secret-shaped is
//! correctly REJECTED rather than persisted; this is a behavior change from
//! when `force` was a blanket bypass and is the intended safe default for an
//! automated writer. A `"status":"skipped"` response is still checked and
//! warned on as a belt-and-braces guard in case a gate skips the write.
//! [`TurnMemorySink::socket`]/[`TurnMemorySink::palace`] expose
//! this sink's already-resolved binding so #2348's `recall_session` tool can
//! target the SAME daemon/palace the turn recorder writes into, without a
//! second, independent resolution.
//! [`derive_palace_id_for_project`] mirrors
//! `trusty_common::catchup`'s (private) palace-derivation convention so a
//! session's turns land in the same palace its PM catch-up digest reads
//! from.
//! Test: `memory_sink::tests::*`.
use Path;
use Arc;
use ;
use ;
use ;
use json;
use mpsc;
use ;
use cratecall_tool_wrapped;
/// Bounded mpsc queue capacity (#2345 scope: "~50").
///
/// Why: bounds memory use when trusty-memory is slow or unreachable for a
/// long stretch; a session realistically produces at most one turn per LLM
/// round trip, so 50 in-flight turns is generous slack before the overflow
/// policy below kicks in.
/// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
pub const QUEUE_CAPACITY: usize = 50;
/// Which half of the dual-write degraded, as the retained per-session status
/// reports it (#2425).
///
/// Why: "the durable history is thinning" is not actionable on its own — an
/// operator needs to know whether the daemon is unreachable, the palace is
/// missing, a content gate rejected the write, or the local queue overflowed,
/// because those have different remedies. This is a CLOSED vocabulary rather
/// than the underlying error string precisely so it can be retained and
/// reported without carrying daemon-controlled text into the operator surface.
/// What: one variant per failure site in [`drain`]/[`write_turn`]/
/// [`TurnMemorySink::enqueue`]. Serialises `snake_case`.
/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`,
/// `registry_tests::memory_degradation_event_is_redacted`.
/// The durability verdict for exactly one queued turn (#2425).
///
/// Why: durability is defined over QUEUED-TURN order, but outcomes do not
/// arrive in that order — a queue-full failure is reported synchronously by
/// [`TurnMemorySink::enqueue`] while accepted turns finish later in the
/// detached drain. `sequence` is what lets the consumer put them back in
/// logical order (see `memory_outcome_reconciler`).
/// What: `sequence` is assigned by `enqueue` from a monotonic per-sink
/// counter, so it is dense and gap-free across both reporting paths.
/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`.
pub
/// Sink-side hook that reports each turn's durability verdict (#2425).
///
/// Why: the sink must stay a leaf — it knows nothing about sessions or the
/// registry — but the retained status has to live on the session. An observer
/// inverts that dependency so `registry_memory_sink` installs the coupling and
/// the sink keeps its existing shape.
/// What: called once per queued turn, on whichever thread produced the verdict
/// (the caller's for a synchronous `enqueue` failure, the drain task's
/// otherwise). Implementations MUST NOT block or panic — see
/// `RegistryMemoryDurabilityObserver` for the fail-open contract.
/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`,
/// `memory_sink::tests::dropping_sink_releases_detached_drain_observer`.
pub
/// The observer a sink built without one gets — the pre-#2425 behaviour.
;
/// Whether a sink is entitled to bring its target palace into EXISTENCE
/// (#4638).
///
/// Why: the recorder's palace id is derived from the session's project root,
/// so an EPHEMERAL root yields an id that is unique per run — and `drain`'s
/// [`ensure_palace`] step then auto-created one permanent, unreadable palace
/// for every such run. That is how 5,667 `t-tmp<random>` orphans accumulated
/// in three weeks (97.8% of every palace on the machine), which in turn made
/// trusty-memory's O(n) full-registry handlers (#4637) unusable. A palace is
/// an expensive object (usearch vector index, KG redb, drawer table, recall
/// log), not a cheap per-session namespace, so the entitlement to mint one is
/// modelled explicitly rather than left implicit in "whoever writes first
/// wins". Making it a two-variant enum rather than a `bool` parameter means no
/// call site can pass the dangerous value by accident.
/// What: [`Self::Allowed`] reproduces the pre-#4638 behavior exactly (probe,
/// then `palace_create` on a miss — #2424); [`Self::Forbidden`] probes and
/// writes into a palace that already exists but never creates one, so a sink
/// carrying it can never increase the palace count.
/// Test: `memory_sink::tests::forbidden_creation_never_creates_a_palace`,
/// `memory_sink::tests::ensure_palace_creates_missing_palace_once`.
/// One user-prompt/assistant-response turn queued for durable dual-write.
/// Async, fire-and-forget durable-write sink for one session's turns (#2345).
///
/// Why: see module docs.
/// What: `enqueue` never blocks the calling turn and never fails visibly —
/// see its docs for the overflow policy. The background drain task owns the
/// only receiver, so it keeps running for exactly as long as this sink (and
/// therefore the channel's sender half) stays alive — the session's
/// `SessionEntry` holds the constructed `Arc<TurnMemorySink>` for the
/// session's lifetime (built once, lazily, on the session's first
/// `task.run` — see `SessionRegistry::memory_sink_for`), so the drain task
/// naturally survives across every run on that session, not just one.
/// Background drain loop: pop turns off the channel and dual-write each one,
/// fail-open (see [`write_turn`]), ensuring the target palace exists before
/// the first write (#2424).
///
/// Why: the ensure lives HERE (drain-task-local state) rather than on the
/// sink struct so it needs no locking — the drain task is the only writer —
/// and so a failed ensure is naturally retried on the next turn (the flag is
/// only set on success), covering a daemon that comes up mid-session.
/// What: on success `palace_ensured` latches true and steady state adds
/// zero extra RPCs per turn; on failure under [`PalaceCreation::Allowed`] the
/// turn's writes are still attempted (fail-open — they carry their own
/// warnings).
///
/// (#4638) Under [`PalaceCreation::Forbidden`] a failed ensure means "this
/// palace does not exist and I am not entitled to create it", so the turn is
/// DROPPED instead of written: the two writes could not have landed anyway
/// (`memory_remember` fails `-32603 "palace metadata missing"` against an
/// absent palace), and skipping them keeps a temp-rooted session down to one
/// probe RPC per turn instead of three. The ensure is deliberately re-probed
/// rather than latched-off, so a Forbidden sink whose palace is created
/// out-of-band mid-session (or whose daemon was merely down for the first
/// probe) starts recording normally — "the daemon is unreachable" and "the
/// palace is absent" are not distinguishable from one failed probe, and only
/// the latter is permanent.
/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`,
/// `memory_sink::tests::forbidden_creation_never_creates_a_palace`,
/// `memory_sink::tests::forbidden_creation_still_writes_to_an_existing_palace`.
async
/// Ensure `palace` exists on the target daemon, creating it if missing
/// (#2424). Returns `true` when the palace is known to exist afterwards.
///
/// Why: `memory_remember` does NOT auto-create its palace — against a
/// missing one it fails `-32603 "palace metadata missing"`, which silently
/// killed the semantic half of every soak write. Probe-then-create (rather
/// than unconditional `palace_create`) because trusty-memory's
/// `handle_palace_create` OVERWRITES `palace.json` for an existing palace
/// (resetting `created_at`/`description`) — an existing project palace
/// shared with the PM catch-up digest must not have its metadata clobbered
/// on every session start.
/// What: `palace_info` via `tools/call`; on error (the daemon's signal for
/// "metadata missing" — or any other failure, in which case the create
/// simply fails too and we stay fail-open), `palace_create` with
/// `force: true` (the spec-001 documented bypass for app-managed palaces
/// whose slug does not match the DAEMON's cwd-derived project slug; a no-op
/// authz gate in default single-tenant mode) via `tools/call`. Never
/// propagates an error — failure is logged and reported as `false` so the
/// caller retries on the next turn.
///
/// (#4638) `creation` gates the CREATE half only — the probe always runs, so a
/// [`PalaceCreation::Forbidden`] sink still discovers and uses a palace that
/// already exists. Returning `false` without attempting a create is what makes
/// the bound structural: `palace_create` is unreachable from an ephemeral
/// project root, not merely unlikely.
/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`,
/// `memory_sink::tests::forbidden_creation_never_creates_a_palace`.
async
/// Dual-write one turn: `chat_turn_append` (the exact chronological record)
/// THEN `memory_remember` (the semantic recall surface, #2348).
///
/// Why: the exact and semantic representations are independent trusty-memory
/// endpoints; a mid-outage failure of one must not block the other, so each
/// call's error is handled separately rather than short-circuiting on the
/// first failure. (#2424) BOTH calls go through the MCP `tools/call`
/// envelope (`call_tool_wrapped`) — trusty-memory's direct-dispatch
/// allowlist (`TOOL_METHODS`) has no `chat_*` entries, so the previous
/// direct-method dispatch of `chat_turn_append` failed `-32601 Method not
/// found` on 100% of writes; `memory_remember` IS direct-dispatchable but
/// uses the same envelope anyway so both halves share one verified shape.
/// (#2363) `memory_remember` passes `force: true` because
/// its dedup gate (jaro_winkler >0.92, same-palace, 5-min window) is
/// documented as hostile to sequential conversational turns — near-duplicate
/// consecutive turns are the NORMAL case here, not noise; `force: true` also
/// bypasses the other content-QUALITY gates (blocklist, short-content, noise
/// pattern). Issue #2520: `force` does NOT bypass secret/credential
/// detection — a turn whose content looks secret-shaped comes back as an
/// `Err` from `call_tool_wrapped` (not a `"skipped"` status) and is logged
/// via the fail-open `Err(e)` arm below, same as any other RPC failure. A
/// `"status": "skipped"` response (from a gate `force` does NOT bypass, e.g.
/// a quality/blocklist gate that some OTHER path still applies) is still
/// checked and warned on so a silently thinned recall surface is at least
/// observable in logs — (#2424) `call_tool_wrapped` returns the PARSED inner
/// tool result, so the skipped detection sees the same shape it did under
/// direct dispatch.
/// What: never propagates an error — every failure is logged via
/// `tracing::warn!` and swallowed, matching
/// `resolve_memory_socket_or_unreachable`'s fail-open contract (mirrored
/// here, not reused directly, since `socket` is already resolved by the
/// caller of [`TurnMemorySink::new`]). (#2425) It RETURNS the turn's verdict
/// rather than propagating anything: `Degraded` with the first failed half's
/// category if either call failed, `Durable` otherwise. The default warnings
/// name that category and DELIBERATELY omit the daemon's own error text and
/// `reason` string, both of which are server-controlled and can quote rejected
/// content back — including the credential preview #2520's secret gate refused
/// to store. The daemon's own logs keep that text; this warning does not.
/// Test: `memory_sink::tests::enqueue_drain_happy_path`,
/// `memory_sink::tests::write_turn_is_fail_open_on_unreachable_daemon`,
/// `memory_sink::tests::write_turn_warns_on_skipped_status`,
/// `memory_sink::tests::partial_dual_write_counts_once_as_failed_turn`,
/// `memory_sink::tests::default_memory_warnings_redact_server_payloads_in_subprocess`.
async
/// Resolve the palace id for a project directory (#2345).
///
/// Why: mirrors `trusty_common::catchup`'s own `derive_palace_id_for`
/// convention exactly, so a session's turns land in the SAME palace
/// `catchup::pm_catchup_context` reads its digest from — the PM's own catch-up
/// section and the turn recorder's writes must agree on "which palace is this
/// project."
///
/// This used to answer `"unknown-project"` on any failure. That literal is
/// SHARED: two projects that both fail resolution get the same id, and
/// `SessionRegistry::memory_sink_for` grants a durable project root
/// [`PalaceCreation::Allowed`], so the recorder auto-created one palace under
/// the placeholder and posted both projects' real prompts and responses into it
/// (#5811). While the only failure was "no identity at all" that was rare;
/// routing through `palace_resolve` added three pin-trust failures to the same
/// branch, so a typo in one committed pin was enough to reach it. The error is
/// returned instead, and the caller declines to record.
/// What: delegates to `trusty_common::palace_resolve::resolve_palace` — env
/// override, then the committed pin, then the git `owner/repo` slug, then the
/// `parent/dir` slug of the main worktree root.
/// Test: `memory_sink::tests::derive_palace_id_for_project_falls_back_to_dirname`,
/// `memory_sink::tests::malformed_pin_is_an_error_not_the_shared_placeholder`.
/// A socket path nothing serves: a dial is refused by the kernel at once.
const UNREACHABLE_MEMORY_SOCKET: &str = "/nonexistent/trusty-memory/trusty-memory.sock";
/// Resolve the trusty-memory socket the turn recorder and the PM catch-up read
/// may dial — never the operator's live daemon from a test process (#9139).
///
/// Why: a test process inherited the operator's environment, so the recorder
/// resolved the LIVE daemon's socket and a managed shell's
/// `TRUSTY_MEMORY_PALACE` named the live palace. The #4638 create bound did not
/// stop it, because that palace already exists: 2,308 fixture `turn` drawers
/// landed in it. Test isolation that depends on every caller's environment
/// fails the first time one caller forgets.
/// What: outside a test process this is
/// `trusty_common::memory_rpc::resolve_memory_socket_or_unreachable`. Under
/// the harness (`trusty_common::test_harness::running_under_test_harness`) it
/// is `harness_memory_socket` over `TRUSTY_MEMORY_SOCKET`; the data-dir
/// derivation is never consulted, so the default socket is unreachable.
/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`,
/// `memory_sink::tests::memory_sink_for_under_the_harness_never_binds_a_live_socket`.
pub
/// The socket a test process may dial, given its `TRUSTY_MEMORY_SOCKET` (#9139).
///
/// Why: a test's mock daemon binds under a `TempDir`; a live daemon binds in
/// the operator's data directory, never under a system temp root.
/// What: an explicit, non-blank path with no `..` component whose parent
/// directory, once canonicalized (symlinks resolved), is still under a system
/// temp root is returned unchanged. Anything else — unset, blank, a non-temp
/// path, a `..` escape, a symlink out of temp, or a parent that cannot be
/// canonicalized — yields [`UNREACHABLE_MEMORY_SOCKET`], so a failed isolation
/// fails closed.
/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`.
pub
/// Whether `socket` still sits under a system temp root after `..` and
/// symlinks are resolved (#9139).
///
/// Why: a lexical `starts_with` check admits `/tmp/../Users/x/live.sock` and a
/// temp-dir symlink that points at the operator's data directory.
/// What: false for any `..` component, or when the parent cannot be
/// canonicalized; otherwise the canonical parent must pass
/// `is_under_system_temp`.
/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`.