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