Skip to main content

trusty_code/
catchup.rs

1//! DOC-28 catch-up context injection for the PM prompt (#1762, PR2).
2//!
3//! Why: When a PM agent starts a task, it has no intrinsic knowledge of recent
4//! project activity — paused sessions, new git commits, or recent memory palace
5//! entries.  Injecting a catch-up digest as seed `fallback_guidance` in the PM
6//! system prompt gives it the context to orient quickly, mirroring the behaviour
7//! the trusty-mpm harness provides via `session_launch`.
8//! What: [`pm_catchup_context`] builds a [`CatchupOptions`] for the project and
9//! calls the shared engine in trusty-common, returning `Some(digest)` when
10//! meaningful content was produced or `None` to indicate the assembler should
11//! skip this section entirely.
12//! Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
13//!
14//! [`pm_catchup_context`]: crate::catchup::pm_catchup_context
15//! [`CatchupOptions`]: trusty_common::catchup::CatchupOptions
16
17use std::path::Path;
18
19use tracing::debug;
20use trusty_common::catchup::{CatchupOptions, run_catchup};
21
22/// Build PM-prompt catch-up seed context for the given project directory.
23///
24/// Why: the PM prompt benefits from a one-time digest of what happened in the
25/// project since the last session — paused work, recent commits, recent memory
26/// palace entries — so it can orient immediately without asking the operator.
27/// This is injected as `fallback_guidance` (the last section of the assembled
28/// prompt) and is only wired into the PM agent path; sub-agents receive `None`
29/// because they operate under the PM's direction and do not need the high-level
30/// activity digest.
31///
32/// **Watermark is NOT advanced** (`advance_watermark = false`).  trusty-code is
33/// a read-only consumer of the catch-up state: watermark advancement is owned by
34/// trusty-mpm's `session_launch` hook, which controls the canonical boundary
35/// between sessions.  Advancing from trusty-code would skew that boundary and
36/// cause cross-harness interference where activity is silently dropped from the
37/// next mpm session's digest.
38///
39/// Fail-open: any error or empty/whitespace result returns `None` rather than
40/// propagating, so prompt assembly always succeeds even when the daemon is
41/// offline or the project has no git history.
42///
43/// What: resolves `memory_socket` via
44/// [`crate::session::memory_sink::resolve_recorder_socket`] (env override
45/// `TRUSTY_MEMORY_SOCKET` first, else the derived socket path,
46/// else a fail-fast placeholder — issue #2030; never the live daemon from a
47/// test process — #9139), then delegates to
48/// [`pm_catchup_context_with_socket`].
49/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
50pub async fn pm_catchup_context(project_dir: &Path) -> Option<String> {
51    // #9139: a test process never dials the operator's live daemon.
52    let memory_socket = crate::session::memory_sink::resolve_recorder_socket();
53    pm_catchup_context_with_socket(project_dir, memory_socket).await
54}
55
56/// Same as [`pm_catchup_context`], but with the trusty-memory base URL passed
57/// in explicitly rather than resolved from the process-wide `TRUSTY_MEMORY_SOCKET`
58/// env var (issue #3003).
59///
60/// Why: [`pm_catchup_context`]'s tests need a guaranteed-unreachable dial
61/// target so the fail-open path is exercised deterministically. The previous
62/// approach mutated the process-global `TRUSTY_MEMORY_SOCKET` env var via
63/// `unsafe { std::env::set_var(..) }` with no cleanup and no cross-test lock —
64/// `cargo test`'s default parallelism runs every test in this crate's lib
65/// binary as threads of ONE process, so that leaked env value was observable
66/// by any concurrently-running test whose code path also calls
67/// [`trusty_common::memory_rpc::resolve_memory_socket_or_unreachable`]
68/// (e.g. `run_task::tests::*`, via `execute_run_task` -> `pm_catchup_context`),
69/// producing false-red flakes unrelated to the leaking test itself. Threading
70/// `memory_socket` through as a parameter — the same pattern
71/// [`crate::session::memory_sink::TurnMemorySink::with_capacity`] already uses
72/// for the identical reason — removes the shared mutable global entirely, so
73/// tests need no lock and no cleanup.
74/// What: builds `CatchupOptions` with `memory_socket` and sane limits, calls
75/// `run_catchup` with `advance_watermark = false`, and returns `Some(digest)`
76/// when the result is non-whitespace, else `None`.
77/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`,
78/// `catchup::tests::pm_catchup_context_does_not_panic_on_non_git_dir`.
79async fn pm_catchup_context_with_socket(
80    project_dir: &Path,
81    memory_socket: std::path::PathBuf,
82) -> Option<String> {
83    let opts = CatchupOptions {
84        project_dir: project_dir.to_path_buf(),
85        memory_socket,
86        include_git: true,
87        include_palace: true,
88        git_limit: 50,
89        drawer_limit: 15,
90        full: false,
91    };
92
93    // advance_watermark = false: trusty-code never owns the watermark boundary;
94    // that belongs to trusty-mpm session_launch to avoid cross-harness skew.
95    let digest = run_catchup(&opts, false).await;
96
97    if digest.trim().is_empty() {
98        debug!("pm_catchup_context: empty digest — omitting from PM prompt");
99        None
100    } else {
101        Some(digest)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use std::fs;
109    use std::process::Command;
110    use tempfile::TempDir;
111
112    /// Initialise a minimal git repo with one commit so catch-up has a real git
113    /// context to scan (avoids "not a git repo" errors in the engine).
114    fn init_git_repo(dir: &TempDir) {
115        let p = dir.path();
116        for args in [
117            vec!["init"],
118            vec!["config", "user.email", "test@test.com"],
119            vec!["config", "user.name", "Test"],
120        ] {
121            // Ignore errors: git may not be on PATH in some CI environments;
122            // the test will simply see an empty digest (fail-open).
123            let _ = Command::new("git").arg("-C").arg(p).args(&args).output();
124        }
125        let _ = fs::write(p.join("README.md"), b"test");
126        let _ = Command::new("git")
127            .arg("-C")
128            .arg(p)
129            .args(["add", "."])
130            .output();
131        let _ = Command::new("git")
132            .arg("-C")
133            .arg(p)
134            .args(["commit", "-m", "init"])
135            .output();
136    }
137
138    /// A socket path under a directory that cannot exist, so a dial is refused
139    /// by the kernel immediately rather than hanging or waiting out a budget —
140    /// the same literal `trusty_common::memory_rpc`'s own
141    /// `UNREACHABLE_PLACEHOLDER` and `run_task::tests::isolate_ambient_daemons`
142    /// use.
143    ///
144    /// It held `"http://127.0.0.1:1"` until #6286's review: that string named a
145    /// TCP port for a transport that no longer exists, and
146    /// [`pm_catchup_context_with_socket`] takes a `PathBuf`, so it coerced into
147    /// the CWD-RELATIVE path `http:/127.0.0.1:1`. The dial still failed, but by
148    /// accident of the working directory rather than by the guarantee the doc
149    /// comment claimed.
150    ///
151    /// Why (#3003): passed directly to
152    /// [`pm_catchup_context_with_socket`] instead of mutating the
153    /// process-global `TRUSTY_MEMORY_SOCKET` env var, so this test needs no lock
154    /// and cannot leak state into concurrently-running tests (e.g.
155    /// `run_task::tests::*`, which also resolves a trusty-memory socket via
156    /// `pm_catchup_context` inside `execute_run_task`).
157    const UNREACHABLE_MEMORY_SOCKET: &str = "/nonexistent/trusty-memory/trusty-memory.sock";
158
159    /// Verifies that `pm_catchup_context` does not panic and returns either
160    /// `Some` or `None` consistently when the memory daemon is unreachable.
161    ///
162    /// Why: tests can never assume a live trusty-memory daemon; this test
163    /// points at an unreachable socket so the palace section degrades gracefully.
164    /// What: creates a temp dir with a git repo, calls
165    /// `pm_catchup_context_with_socket` with [`UNREACHABLE_MEMORY_SOCKET`],
166    /// asserts no panic and that the returned value is well-formed.
167    /// Test: this test.
168    #[tokio::test]
169    async fn pm_catchup_context_does_not_panic_on_empty_repo() {
170        let tmp = TempDir::new().unwrap();
171        init_git_repo(&tmp);
172
173        let result =
174            pm_catchup_context_with_socket(tmp.path(), UNREACHABLE_MEMORY_SOCKET.into()).await;
175
176        // Result is either Some(non-empty) or None — never panics.
177        match &result {
178            Some(ctx) => {
179                assert!(
180                    !ctx.trim().is_empty(),
181                    "Some(ctx) must not be empty/whitespace"
182                );
183            }
184            None => {
185                // Acceptable: the engine may return all-whitespace if every
186                // source produces an empty section header only.
187            }
188        }
189
190        // Confirm no state file was written under the temp dir (advance=false
191        // means no ~/.trusty-mpm/<palace-id>/catchup-state.json for this
192        // ephemeral project — state path is keyed by palace_id, not project_dir,
193        // so we cannot predict the exact path; instead, verify the return value
194        // alone which is the observable contract for advance_watermark=false).
195        //
196        // The palace_id for a repo with no remote defaults to the basename of
197        // the tempdir.  We check that neither the path nor any sub-path was
198        // created inside the temp dir itself (the engine writes to ~/.trusty-mpm,
199        // not to the project dir).
200        let state_file_in_project = tmp.path().join(".trusty-mpm");
201        assert!(
202            !state_file_in_project.exists(),
203            "advance_watermark=false must not write state inside the project dir"
204        );
205    }
206
207    /// Verifies that `pm_catchup_context` does not panic when the project dir
208    /// is not a git repository (engine is expected to fail-open on git errors).
209    ///
210    /// Why: operators may invoke `tcode run-task` outside a git repo; the PM
211    /// prompt must still be assembled without aborting.
212    /// What: calls `pm_catchup_context_with_socket` with
213    /// [`UNREACHABLE_MEMORY_SOCKET`] on a plain temp dir (no git init) and
214    /// asserts that the function returns without panicking.
215    /// Test: this test.
216    #[tokio::test]
217    async fn pm_catchup_context_does_not_panic_on_non_git_dir() {
218        let tmp = TempDir::new().unwrap();
219
220        // Must not panic — fall through to None or Some(whitespace-only) path.
221        let _result =
222            pm_catchup_context_with_socket(tmp.path(), UNREACHABLE_MEMORY_SOCKET.into()).await;
223    }
224}