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
//! 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.
//! (#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::base_url`]/[`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 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;
/// 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 the turn's writes are still
/// attempted (fail-open — they carry their own warnings).
/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`.
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.
/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`.
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_base_url_or_unreachable`'s fail-open contract (mirrored
/// here, not reused directly, since `base_url` is already resolved by the
/// caller of [`TurnMemorySink::new`]).
/// 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`.
async
/// Derive the palace id for a project directory (#2345).
///
/// Why: mirrors `trusty_common::catchup`'s own (private-to-that-module)
/// `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."
/// What: probes `git config --get remote.origin.url` from `project_dir`,
/// then calls `trusty_common::derive_palace_id` (explicit override env ->
/// git owner/repo slug -> parent/dir slug), falling back to the directory's
/// basename (or `"unknown-project"`) when all three yield `None`.
/// Test: `memory_sink::tests::derive_palace_id_for_project_falls_back_to_dirname`.