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
14use std::path::Path;
15
16use tracing::debug;
17use trusty_common::catchup::{CatchupOptions, run_catchup};
18
19/// Build PM-prompt catch-up seed context for the given project directory.
20///
21/// Why: the PM prompt benefits from a one-time digest of what happened in the
22/// project since the last session — paused work, recent commits, recent memory
23/// palace entries — so it can orient immediately without asking the operator.
24/// This is injected as `fallback_guidance` (the last section of the assembled
25/// prompt) and is only wired into the PM agent path; sub-agents receive `None`
26/// because they operate under the PM's direction and do not need the high-level
27/// activity digest.
28///
29/// **Watermark is NOT advanced** (`advance_watermark = false`).  trusty-code is
30/// a read-only consumer of the catch-up state: watermark advancement is owned by
31/// trusty-mpm's `session_launch` hook, which controls the canonical boundary
32/// between sessions.  Advancing from trusty-code would skew that boundary and
33/// cause cross-harness interference where activity is silently dropped from the
34/// next mpm session's digest.
35///
36/// Fail-open: any error or empty/whitespace result returns `None` rather than
37/// propagating, so prompt assembly always succeeds even when the daemon is
38/// offline or the project has no git history.
39///
40/// What: resolves `memory_url` via
41/// [`trusty_common::mcp::memory_rpc::resolve_memory_base_url_or_unreachable`] (env override
42/// `TRUSTY_MEMORY_URL` first, else the daemon's discovered bound address,
43/// else a fail-fast placeholder — issue #2030), builds `CatchupOptions` with
44/// sane limits, calls `run_catchup` with `advance_watermark = false`, and
45/// returns `Some(digest)` when the result is non-whitespace, else `None`.
46/// Test: `catchup::tests::pm_catchup_context_does_not_panic_on_empty_repo`.
47pub async fn pm_catchup_context(project_dir: &Path) -> Option<String> {
48    let memory_url = trusty_common::mcp::memory_rpc::resolve_memory_base_url_or_unreachable();
49
50    let opts = CatchupOptions {
51        project_dir: project_dir.to_path_buf(),
52        memory_url,
53        include_git: true,
54        include_palace: true,
55        git_limit: 50,
56        drawer_limit: 15,
57        full: false,
58    };
59
60    // advance_watermark = false: trusty-code never owns the watermark boundary;
61    // that belongs to trusty-mpm session_launch to avoid cross-harness skew.
62    let digest = run_catchup(&opts, false).await;
63
64    if digest.trim().is_empty() {
65        debug!("pm_catchup_context: empty digest — omitting from PM prompt");
66        None
67    } else {
68        Some(digest)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use std::fs;
76    use std::process::Command;
77    use tempfile::TempDir;
78
79    /// Initialise a minimal git repo with one commit so catch-up has a real git
80    /// context to scan (avoids "not a git repo" errors in the engine).
81    fn init_git_repo(dir: &TempDir) {
82        let p = dir.path();
83        for args in [
84            vec!["init"],
85            vec!["config", "user.email", "test@test.com"],
86            vec!["config", "user.name", "Test"],
87        ] {
88            // Ignore errors: git may not be on PATH in some CI environments;
89            // the test will simply see an empty digest (fail-open).
90            let _ = Command::new("git").arg("-C").arg(p).args(&args).output();
91        }
92        let _ = fs::write(p.join("README.md"), b"test");
93        let _ = Command::new("git")
94            .arg("-C")
95            .arg(p)
96            .args(["add", "."])
97            .output();
98        let _ = Command::new("git")
99            .arg("-C")
100            .arg(p)
101            .args(["commit", "-m", "init"])
102            .output();
103    }
104
105    /// Verifies that `pm_catchup_context` does not panic and returns either
106    /// `Some` or `None` consistently when the memory daemon is unreachable.
107    ///
108    /// Why: tests can never assume a live trusty-memory daemon; this test
109    /// points at an unreachable port so the palace section degrades gracefully.
110    /// What: creates a temp dir with a git repo, calls `pm_catchup_context`,
111    /// asserts no panic and that the returned value is well-formed.
112    /// Test: this test.
113    #[tokio::test]
114    async fn pm_catchup_context_does_not_panic_on_empty_repo() {
115        let tmp = TempDir::new().unwrap();
116        init_git_repo(&tmp);
117
118        // Point memory_url at an unreachable port so palace fetch fails-open.
119        // SAFETY: single-threaded test; no concurrent env reads.
120        unsafe {
121            std::env::set_var(
122                trusty_common::mcp::memory_rpc::TRUSTY_MEMORY_URL_ENV,
123                "http://127.0.0.1:19999",
124            )
125        };
126
127        let result = pm_catchup_context(tmp.path()).await;
128
129        // Result is either Some(non-empty) or None — never panics.
130        match &result {
131            Some(ctx) => {
132                assert!(
133                    !ctx.trim().is_empty(),
134                    "Some(ctx) must not be empty/whitespace"
135                );
136            }
137            None => {
138                // Acceptable: the engine may return all-whitespace if every
139                // source produces an empty section header only.
140            }
141        }
142
143        // Confirm no state file was written under the temp dir (advance=false
144        // means no ~/.trusty-mpm/<palace-id>/catchup-state.json for this
145        // ephemeral project — state path is keyed by palace_id, not project_dir,
146        // so we cannot predict the exact path; instead, verify the return value
147        // alone which is the observable contract for advance_watermark=false).
148        //
149        // The palace_id for a repo with no remote defaults to the basename of
150        // the tempdir.  We check that neither the path nor any sub-path was
151        // created inside the temp dir itself (the engine writes to ~/.trusty-mpm,
152        // not to the project dir).
153        let state_file_in_project = tmp.path().join(".trusty-mpm");
154        assert!(
155            !state_file_in_project.exists(),
156            "advance_watermark=false must not write state inside the project dir"
157        );
158    }
159
160    /// Verifies that `pm_catchup_context` does not panic when the project dir
161    /// is not a git repository (engine is expected to fail-open on git errors).
162    ///
163    /// Why: operators may invoke `tcode run-task` outside a git repo; the PM
164    /// prompt must still be assembled without aborting.
165    /// What: calls `pm_catchup_context` on a plain temp dir (no git init) and
166    /// asserts that the function returns without panicking.
167    /// Test: this test.
168    #[tokio::test]
169    async fn pm_catchup_context_does_not_panic_on_non_git_dir() {
170        let tmp = TempDir::new().unwrap();
171
172        // Point memory_url at an unreachable port.
173        // SAFETY: single-threaded test; no concurrent env reads.
174        unsafe {
175            std::env::set_var(
176                trusty_common::mcp::memory_rpc::TRUSTY_MEMORY_URL_ENV,
177                "http://127.0.0.1:19999",
178            )
179        };
180
181        // Must not panic — fall through to None or Some(whitespace-only) path.
182        let _result = pm_catchup_context(tmp.path()).await;
183    }
184}