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
// SPDX-License-Identifier: Apache-2.0
//! The carrier half of `read` / `grep` / `glob` / `ls`: their stdout is
//! collected and delivered as ONE tool result through the shared CLI tool
//! run. Moved out of `read_cmd.rs` unchanged (file-size split).
use crate::cli::common::{CliToolRun, Printable};
use crate::cli::context_execution::CommandOutput;
/// Stdout of one local primitive, collected instead of printed.
///
/// `read`, `grep`, `glob` and `ls` are the carriers the host hooks rewrite
/// native reads to. Their primitives used to `println!` while they rendered;
/// they now write the same lines here, and the finished text goes through the
/// shared CLI tool run ([`deliver_carrier`]) as ONE tool result: release,
/// lineage record of exactly the printed bytes, then the one observed write
/// (`print_released`). The bytes on stdout are the ones the line-by-line
/// prints produced before (#498).
#[derive(Default)]
pub(super) struct Stdout {
pub(super) text: String,
hinted: bool,
}
impl Stdout {
/// What `println!("{text}")` wrote: the text and one newline.
pub(super) fn line(&mut self, text: impl std::fmt::Display) {
use std::fmt::Write as _;
let _ = writeln!(self.text, "{text}");
}
/// What `print_savings` wrote: the footer line, when there is one.
pub(super) fn savings(&mut self, original: usize, sent: usize) {
let footer = lean_ctx::core::protocol::format_savings(original, sent);
if !footer.is_empty() {
self.line(footer);
}
}
/// The output carries hint text that does not come from the sources (a
/// usage hint appended to the rendering): it is printed as before, and
/// is never recorded as a delivery of the sources.
pub(super) fn hint(&mut self) {
self.hinted = true;
}
/// The collected text as one tool result, without the final newline the
/// closing `print_released` adds back. `None`: nothing was written to
/// stdout.
pub(super) fn into_printable(self, failed: bool) -> Option<Printable> {
let text = self.text.strip_suffix('\n')?.to_string();
Some(Printable {
text,
source_only: !self.hinted,
failed,
})
}
}
/// Run one local primitive as a tool-result carrier and print what it wrote.
///
/// `tool` and `arguments` are those of the MCP tool the command stands for;
/// whether the output is recorded follows from that tool's own declaration
/// (`ctx_read`, `ctx_search` with a regex) — a `listing` (`glob`, `ls`) is
/// released like the rest and records nothing. The exit status and everything
/// the primitive wrote to stderr are untouched.
pub(super) fn deliver_carrier(
tool: &str,
project_root: &str,
arguments: Option<&serde_json::Map<String, serde_json::Value>>,
listing: bool,
primitive: impl FnOnce(&mut Stdout) -> CommandOutput,
) -> CommandOutput {
let run = CliToolRun::new(tool, project_root, arguments).admitted_reader_output();
let run = if listing { run.human_facing() } else { run };
let (output, printed) = run.run(|| {
let mut out = Stdout::default();
let output = primitive(&mut out);
let printable = out.into_printable(output.exit_code != 0);
(output, printable)
});
if let Some(text) = printed {
// The one observed writer: the text and the final newline (G08).
crate::cli::common::print_released(&text);
}
output
}
/// A result the daemon returned for `tool`, released through the same run as
/// a local result before the caller prints it with `print_released`.
///
/// The daemon released and recorded the result in its own pipeline; the text
/// printed here also passes this process's release point (policy, masking)
/// and, where protection is active, its receipt. This process captured none
/// of the result's sources, so the text is never recorded here as a delivery
/// of them. `None`: the release produced nothing to print.
#[cfg(unix)]
pub(super) fn released_daemon_result(
tool: &str,
project_root: &str,
arguments: Option<&serde_json::Map<String, serde_json::Value>>,
listing: bool,
text: String,
failed: bool,
) -> Option<String> {
let run = CliToolRun::new(tool, project_root, arguments).admitted_reader_output();
let run = if listing { run.human_facing() } else { run };
let ((), printed) = run.run(|| {
let printable = Printable {
text,
source_only: false,
failed,
};
((), Some(printable))
});
printed
}
/// The arguments of the MCP tool call a CLI carrier stands for, as a map.
pub(super) fn tool_arguments(
value: serde_json::Value,
) -> serde_json::Map<String, serde_json::Value> {
match value {
serde_json::Value::Object(map) => map,
_ => serde_json::Map::new(),
}
}
#[cfg(all(test, unix))]
mod tests {
use crate::cli::common::carrier_tests_support::{AWS_KEY, governed, lineage, project};
/// The daemon routes of `read`, `grep`, `glob` and `ls` printed the
/// daemon's text with `println!`, outside the shared run. It now passes
/// the release point here too, and is never recorded as a delivery.
#[test]
fn a_daemon_result_is_released_and_registers_nothing() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
governed();
let (_project, root) = project();
let arguments =
super::tool_arguments(serde_json::json!({ "path": "a.rs", "mode": "full" }));
let text = "a.rs 1L\npub fn a() {}".to_string();
let printed = super::released_daemon_result(
"ctx_read",
&root,
Some(&arguments),
false,
text.clone(),
false,
);
assert_eq!(
printed.as_deref(),
Some(text.as_str()),
"admitted text keeps its bytes"
);
assert_eq!(lineage(&root, &text), None);
for listing in [false, true] {
let leaked = super::released_daemon_result(
"ctx_read",
&root,
Some(&arguments),
listing,
format!("a.rs 1L\nkey = {AWS_KEY}"),
false,
)
.unwrap_or_default();
assert!(!leaked.contains(AWS_KEY), "{leaked}");
}
}
}