Skip to main content

lean_ctx/cli/
common.rs

1pub(crate) fn print_savings(original: usize, sent: usize) {
2    let footer = crate::core::protocol::format_savings(original, sent);
3    if !footer.is_empty() {
4        println!("{footer}");
5    }
6}
7
8/// One tool run on behalf of a CLI command — the ONE place where the CLI does
9/// what the MCP dispatcher does around a tool handler (G01, G03/G04, G05).
10///
11/// Order, fixed here and nowhere else in `cli/`:
12///
13/// 1. the handler runs inside the request scope (so the shared read path
14///    admits its sources) AND inside the source capture (so every source the
15///    admitted readers publish is known);
16/// 2. the finished text passes the release point every MCP tool result
17///    passes (`server::policy_guard::release_result`), then the legacy output
18///    redaction (`redact_model_text`). The result of this step is the text
19///    the command prints — a command must not change it afterwards;
20/// 3. the lineage of exactly that text is recorded
21///    (`core::archive::delivered::record_tool_delivery`), which decides by
22///    its own rules whether anything is recorded: an undeclared tool, an
23///    error, an absent or incomplete capture record nothing. Unknown stays
24///    unknown; nothing is guessed here;
25/// 4. the caller writes the returned text with [`print_released`].
26///
27/// Receipt (G08): where the receipt store is mandatory (protection is
28/// active), steps 1 and 2 run inside one admission capture, and between
29/// steps 2 and 3 the Decision Receipt of the output is built, validated and
30/// stored. It binds exactly the bytes the writer writes — the text and its
31/// final `\n`. An output whose owed receipt cannot be stored is not printed:
32/// the content-free notice `receipt.not_persisted` is returned in its place,
33/// as a refusal. Nothing is added to stdout either way (#498). The principal
34/// is `unknown` unless the process showed a presenter capability.
35///
36/// One policy snapshot (G08): the run takes it once, where it starts (the
37/// first of steps 1 and 2), and its capture carries it — the release point,
38/// the receipt duty and the trace sidecar of the run decide under it.
39///
40/// PREPARED, not handed over: the receipt and its sidecar exist before a
41/// byte is written and prove no write. The hand-over is observed by the ONE
42/// writer, [`print_released`] (stdout) or [`exit_withheld`] (stderr and the
43/// exit status), after `write_all` and `flush` of exactly the prepared bytes
44/// succeeded. The receipt's own handle waits for that write on the thread
45/// that prepared it; a command that prints the returned text any other way
46/// leaves the delivery unconfirmed, which is what the inspector then says.
47/// Variants for output that is not `text + "\n"` on stdout:
48/// [`CliToolRun::deliver_json_exact`] with [`print_released_exact`] (no
49/// final newline), [`CliToolRun::to_stderr`] with [`eprint_released`].
50///
51/// Digested bytes: the returned text, and the same text followed by the one
52/// `\n` that the writer adds. A consumer that takes the CLI's stdout as a
53/// tool result holds one of the two (hosts differ in whether they trim the
54/// final newline); both are the same delivery from the same sources. No other
55/// prefix or wrapper is added by the CLI.
56pub(crate) struct CliToolRun<'a> {
57    tool: &'a str,
58    project_root: &'a str,
59    /// The arguments of the call. The tool's own declaration for them
60    /// (`McpTool::publishes_every_source`) is asked only when there is a
61    /// captured source set to record — the registry is not built for a run
62    /// that can record nothing (no protection, no source, an error).
63    arguments: Option<serde_json::Map<String, serde_json::Value>>,
64    /// `false` for output that is not a tool-result carrier (a human-facing
65    /// table, or the text wrapped into another document such as `--json`):
66    /// steps 1 and 2 still apply, step 3 records nothing.
67    carrier: bool,
68    /// Whether step 2 ends with the legacy output redaction.
69    legacy_redaction: bool,
70    /// The admission capture of the output being prepared; opened only where
71    /// the receipt store is mandatory, taken when the receipt is recorded.
72    admissions: std::sync::Mutex<
73        Option<std::sync::Arc<crate::core::context_admission::capture::AdmissionCapture>>,
74    >,
75    /// The receipt duty of this run and the ONE policy snapshot it was
76    /// decided under, taken where the run starts.
77    duty: std::sync::OnceLock<crate::core::context_admission::receipt_store::Duty>,
78    /// The receipt index the output is listed under when it is not the
79    /// project's own ([`Self::receipt_index`]).
80    receipt_index: Option<&'a str>,
81    /// Where the command hands the output: stdout unless a builder says
82    /// otherwise ([`Self::to_stderr`], [`Self::to_file`],
83    /// [`Self::to_clipboard`]).
84    channel: crate::core::context_admission::receipt_store::trace::Channel,
85    /// The Ed25519 public key a package signature was VERIFIED with, when the
86    /// document names it ([`Self::verified_signer_key`]).
87    verified_signer_key: Option<&'a str>,
88}
89
90/// The stdout text one handler produced, with what the helper has to know
91/// about it to decide on a lineage record.
92pub(crate) struct Printable {
93    /// The text, without the final newline the writer adds.
94    pub text: String,
95    /// `false` when the handler mixed session-derived or hint text into the
96    /// output: such a text is never recorded as a delivery of its sources.
97    pub source_only: bool,
98    /// The tool itself reports a failure (`ShellOutcome::is_error`, a non-zero
99    /// exit status of the primitive): an error is never a delivery.
100    pub failed: bool,
101}
102
103impl Printable {
104    /// A successful tool text that consists of the tool's own output only.
105    pub(crate) fn tool_text(text: String) -> Self {
106        Self {
107            text,
108            source_only: true,
109            failed: false,
110        }
111    }
112}
113
114impl<'a> CliToolRun<'a> {
115    /// A run of the registered tool `tool` with `arguments` for `project_root`.
116    /// Whether the tool declares every source is asked of the tool itself,
117    /// for these arguments; an unknown tool declares nothing.
118    pub(crate) fn new(
119        tool: &'a str,
120        project_root: &'a str,
121        arguments: Option<&serde_json::Map<String, serde_json::Value>>,
122    ) -> Self {
123        Self {
124            tool,
125            project_root,
126            arguments: arguments.cloned(),
127            carrier: true,
128            legacy_redaction: true,
129            admissions: std::sync::Mutex::new(None),
130            duty: std::sync::OnceLock::new(),
131            receipt_index: None,
132            channel: crate::core::context_admission::receipt_store::trace::Channel::Stdout,
133            verified_signer_key: None,
134        }
135    }
136
137    /// The document names the public key the Engine has just verified a
138    /// package signature with (`"signer_public_key"`). The release then runs
139    /// inside [`crate::core::redaction::with_verified_signer_key`]: the
140    /// ORIGINAL document, real key included, passes the policy pack, the
141    /// configured redaction patterns, the gateway and the redactor as always;
142    /// only the built-in generic-secret rule does not take that one member
143    /// for a secret. Nothing is substituted and nothing else is exempt.
144    pub(crate) fn verified_signer_key(mut self, key: Option<&'a str>) -> Self {
145        self.verified_signer_key = key;
146        self
147    }
148
149    /// The command writes this run's output to stderr
150    /// ([`eprint_released`]): the receipt is prepared for `Channel::Stderr`,
151    /// for the text and its final `\n`. Everything else is unchanged.
152    #[expect(
153        clippy::wrong_self_convention,
154        reason = "builder that redirects the run"
155    )]
156    pub(crate) fn to_stderr(mut self) -> Self {
157        self.channel = crate::core::context_admission::receipt_store::trace::Channel::Stderr;
158        self
159    }
160
161    /// The command writes this run's output to a FILE instead of a stream:
162    /// the receipt is prepared for the channel `file`, for exactly the
163    /// returned text (no `\n` appended). The path is not recorded. After the
164    /// file was written successfully the command calls
165    /// [`confirm_written_to_file`] with the bytes it wrote.
166    #[expect(
167        clippy::wrong_self_convention,
168        reason = "builder that redirects the run"
169    )]
170    pub(crate) fn to_file(mut self) -> Self {
171        self.channel = crate::core::context_admission::receipt_store::trace::Channel::File;
172        self
173    }
174
175    /// The command hands this run's output to the system CLIPBOARD: the
176    /// receipt is prepared for the channel `clipboard`, for exactly the
177    /// returned text. After the hand-off succeeded the command calls
178    /// [`confirm_copied_to_clipboard`] with the text it copied.
179    #[expect(
180        clippy::wrong_self_convention,
181        reason = "builder that redirects the run"
182    )]
183    pub(crate) fn to_clipboard(mut self) -> Self {
184        self.channel = crate::core::context_admission::receipt_store::trace::Channel::Clipboard;
185        self
186    }
187
188    /// The channel this run's output is prepared for.
189    fn output_channel(&self) -> crate::core::context_admission::receipt_store::trace::Channel {
190        self.channel
191    }
192
193    /// Whether the writer of this run's channel adds one final `\n` to the
194    /// returned text (the stream writers do; a file or the clipboard takes
195    /// exactly the text).
196    fn writer_adds_newline(&self) -> bool {
197        use crate::core::context_admission::receipt_store::trace::Channel;
198        matches!(self.channel, Channel::Stdout | Channel::Stderr)
199    }
200
201    /// List the output's receipt under `key` instead of the project's recent
202    /// deliveries. For a command that reports ON those deliveries (`lean-ctx
203    /// inspect`): its own output is receipted like any other, but must not
204    /// displace the deliveries it shows. The receipt itself is unchanged.
205    pub(crate) fn receipt_index(mut self, key: &'a str) -> Self {
206        self.receipt_index = Some(key);
207        self
208    }
209
210    /// Run `operation` inside this run's admission capture, so every gateway
211    /// decision about the output reaches its receipt (G08). A capture that
212    /// is already open (the run is part of a receipted call) is kept. The
213    /// capture carries the run's policy snapshot, so everything inside it —
214    /// the release point included — decides under the rules of the run's
215    /// start. Must be called inside the request scope.
216    ///
217    /// The capture is opened in every mode, as the MCP call does: without
218    /// protection a run whose capture describes an admitted object — a
219    /// source it read, the text its release point admitted — owes the same
220    /// plain receipt (`receipt_store::record_delivery`), and a run whose
221    /// capture recorded nothing owes none ([`Self::receipted`]).
222    /// Opening it only under protection left the decision of a short-lived
223    /// `lean-ctx read` unrecorded: `lean-ctx inspect` could not show it.
224    fn captured<T>(&self, operation: impl FnOnce() -> T) -> T {
225        use crate::core::context_admission::capture;
226        if capture::current().is_some() {
227            return operation();
228        }
229        let admissions = self
230            .admissions
231            .lock()
232            .unwrap_or_else(std::sync::PoisonError::into_inner)
233            .get_or_insert_with(|| {
234                capture::AdmissionCapture::for_call(self.duty().snapshot().clone())
235            })
236            .clone();
237        capture::ADMISSIONS.sync_scope(Some(admissions), operation)
238    }
239
240    /// The receipt duty of this run under its ONE policy snapshot. The first
241    /// call takes the snapshot — the start of the run; every later use is
242    /// that same snapshot. Must be called inside the request scope.
243    fn duty(&self) -> &crate::core::context_admission::receipt_store::Duty {
244        self.duty
245            .get_or_init(crate::core::context_admission::receipt_store::Duty::at_entry)
246    }
247
248    /// Whether the receipt store is mandatory for this run: decided once,
249    /// under the run's snapshot, for acquisition, release and receipt.
250    /// Must be called inside the request scope.
251    fn mandatory(&self) -> bool {
252        self.duty().mandatory
253    }
254
255    /// The digest of `text` as it is before the release point, for the trace
256    /// sidecar; computed only where a receipt will be recorded.
257    fn prepared_digest(&self, text: &str) -> Option<lean_ctx_protocol::Sha256Digest> {
258        self.mandatory()
259            .then(|| crate::core::context_admission::receipt_store::output_digest(text.as_bytes()))
260    }
261
262    /// Build, validate and store the receipt of exactly `written` — the
263    /// bytes PREPARED for `channel` — before a byte of it is written, with
264    /// its trace sidecar (transport CLI, digest before the release point,
265    /// intended channel, digest of the prepared bytes) and audit anchor.
266    /// Nothing here says the bytes were written: that is observed by the
267    /// writer ([`print_released`], [`exit_withheld`]). `false`: the receipt
268    /// is owed and missing, so `written` must not be written. Without a
269    /// capture (a run inside a receipted call) there is nothing to record.
270    /// Without protection a run whose capture recorded nothing owes nothing,
271    /// and one that admitted something gets the plain receipt — no sidecar, no anchor
272    /// duty, never a withheld output: a failed write is logged and the text
273    /// is printed. Must be called inside the request scope and outside the
274    /// run's capture.
275    fn receipted(
276        &self,
277        written: &str,
278        is_error: bool,
279        before_release: Option<lean_ctx_protocol::Sha256Digest>,
280        channel: crate::core::context_admission::receipt_store::trace::Channel,
281    ) -> bool {
282        use crate::core::context_admission::{capture::Delivered, receipt_store};
283        let Some(admissions) = self
284            .admissions
285            .lock()
286            .unwrap_or_else(std::sync::PoisonError::into_inner)
287            .take()
288        else {
289            return true;
290        };
291        let Some(duty) = self.duty.get() else {
292            return true;
293        };
294        // The MCP call's rule (`finish_gateway_receipt`): without protection
295        // a run whose capture recorded nothing owes nothing.
296        if admissions.is_empty() && !duty.mandatory {
297            return true;
298        }
299        let delivery = receipt_store::trace::Delivery::cli(self.tool, channel, duty.snapshot())
300            .before_release(before_release);
301        let presenter_ref = crate::core::archive::presented::shown_presenter_reference();
302        let record = receipt_store::record_delivery(
303            &admissions,
304            &receipt_store::ReceiptSubject {
305                tool: self.tool,
306                agent_id: None,
307                presenter_ref: presenter_ref.as_deref(),
308                project_root: self.receipt_index.unwrap_or(self.project_root),
309                delivery: &delivery,
310            },
311            &Delivered {
312                text: written,
313                is_error,
314                tokens: crate::core::tokens::count_tokens(written) as u64,
315            },
316            duty,
317        );
318        tracing::debug!("context gateway receipt: {}", record.summary());
319        let released = !record.withholds(duty.mandatory);
320        // The receipt's own handle waits for this thread's next write of
321        // exactly these bytes to the channel; no other write confirms it.
322        if let Some(prepared) = record.into_prepared() {
323            prepared.await_write();
324        }
325        released
326    }
327
328    /// The printed output is not a tool-result carrier: record no lineage.
329    pub(crate) fn human_facing(mut self) -> Self {
330        self.carrier = false;
331        self
332    }
333
334    /// The command prints text that its own admitted reader produced and has
335    /// never passed the legacy output redactor (`read`, `grep`, `glob`,
336    /// `ls`). Step 2 then ends after the release point: running the legacy
337    /// redactor on top could change bytes of an already admitted read, and
338    /// those bytes are pinned (#498). Everything else is unchanged.
339    pub(crate) fn admitted_reader_output(mut self) -> Self {
340        self.legacy_redaction = false;
341        self
342    }
343
344    /// The whole sequence for a handler that also returns a value of its own
345    /// (an exit status, a recording): steps 1–3 above. `handler` returns its
346    /// value and, when it produced stdout text, that text as a [`Printable`].
347    /// The returned text is what the caller writes with [`print_released`]; `None`
348    /// means nothing is printed, released or recorded.
349    pub(crate) fn run<T>(
350        &self,
351        handler: impl FnOnce() -> (T, Option<Printable>),
352    ) -> (T, Option<String>) {
353        let ((value, printable), capture) = self.acquire(handler);
354        let printed = printable.map(|printable| self.finish_checked(printable, capture, false).0);
355        (value, printed)
356    }
357
358    /// [`Self::run`] that also says whether the release point refused the
359    /// text: `(text, true)` is the content-free notice of a refusal, not the
360    /// handler's output. For a command that also sends the released text to a
361    /// destination of its own (a file, the clipboard) and must write no
362    /// notice there. Steps 2 and 3 are those of [`Self::finish`].
363    pub(crate) fn run_checked<T>(
364        &self,
365        handler: impl FnOnce() -> (T, Option<Printable>),
366    ) -> (T, Option<(String, bool)>) {
367        let ((value, printable), capture) = self.acquire(handler);
368        // A caller that asks whether the text was refused does not print the
369        // notice in place of the output: it ends through [`exit_withheld`],
370        // which writes it to stderr. The refusal is prepared for that.
371        let printed = printable.map(|printable| self.finish_checked(printable, capture, true));
372        (value, printed)
373    }
374
375    /// Step 1 on its own, for a command whose acquisition and publication are
376    /// separate phases (the protected CLI path prepares its output, verifies
377    /// its authority and only then publishes): run `handler` inside the
378    /// request scope and the source capture, and hand back what it acquired.
379    /// The capture goes to [`Self::finish`] unchanged.
380    pub(crate) fn acquire<T>(
381        &self,
382        handler: impl FnOnce() -> T,
383    ) -> (T, Option<crate::core::archive::authority::ArchiveAuthority>) {
384        crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
385            self.captured(|| crate::core::archive::authority::capture_sync(handler))
386        })
387    }
388
389    /// Steps 2 and 3 for a text acquired under [`Self::acquire`]: release,
390    /// redaction, lineage record of the returned text. The caller prints the
391    /// result with [`print_released`] and changes nothing in it.
392    pub(crate) fn finish(
393        &self,
394        printable: Printable,
395        capture: Option<crate::core::archive::authority::ArchiveAuthority>,
396    ) -> String {
397        self.finish_checked(printable, capture, false).0
398    }
399
400    /// The one body of steps 2 and 3, for [`Self::finish`] and
401    /// [`Self::run_checked`]: the text to print, and whether the release
402    /// point refused it.
403    fn finish_checked(
404        &self,
405        printable: Printable,
406        capture: Option<crate::core::archive::authority::ArchiveAuthority>,
407        refusal_on_stderr: bool,
408    ) -> (String, bool) {
409        crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
410            let prepared = self.prepared_digest(&printable.text);
411            let (mut printed, mut refused) = self.captured(|| self.released(printable.text));
412            let mut with_newline = format!("{printed}\n");
413            // G08: the receipt of the bytes prepared for the run's stream is
414            // stored before they are written; without it they are not
415            // written. A refusal of the release point is printed like any
416            // text: its bytes are bound in the trace sidecar (V1 names no
417            // output for it).
418            let failed = printable.failed || refused;
419            // Prepared for the channel the bytes are really written to. A
420            // stream run writes text + `\n` to its stream, a refusal too. A
421            // file or clipboard run hands over exactly the text — but its
422            // REFUSAL never goes to the file or the clipboard: the command
423            // ends through [`exit_withheld`], which writes the notice and
424            // `\n` to stderr. So that refusal is prepared for stderr — and so
425            // is the refusal of any run whose caller ends that way
426            // (`refusal_on_stderr`, [`Self::run_checked`]).
427            let stderr = crate::core::context_admission::receipt_store::trace::Channel::Stderr;
428            let (handed, channel) = if refused && (refusal_on_stderr || !self.writer_adds_newline())
429            {
430                (with_newline.as_str(), stderr)
431            } else if self.writer_adds_newline() {
432                (with_newline.as_str(), self.output_channel())
433            } else {
434                (printed.as_str(), self.output_channel())
435            };
436            if !self.receipted(handed, failed, prepared, channel) {
437                printed = crate::core::context_admission::receipt_store::not_persisted_notice();
438                with_newline = format!("{printed}\n");
439                refused = true;
440            }
441            let is_error = printable.failed || refused;
442            if self.carrier {
443                // Session or hint text mixed into the output is expressed the
444                // way `record_tool_delivery` expects it: the call then does
445                // not declare every source.
446                let declares = printable.source_only
447                    && !is_error
448                    && capture.is_some()
449                    && crate::core::archive::delivered::declares_every_source(
450                        &crate::server::registry::build_registry(),
451                        self.tool,
452                        self.arguments.as_ref(),
453                    );
454                crate::core::archive::delivered::record_tool_delivery(
455                    declares,
456                    is_error,
457                    capture,
458                    &[printed.as_str(), with_newline.as_str()],
459                );
460            }
461            (printed, refused)
462        })
463    }
464
465    /// Step 2 for one text: the release point, then (unless the command
466    /// prints an admitted reader's output) the legacy output redaction.
467    /// Returns the text to print and whether the release point refused it.
468    /// Must be called inside the request scope.
469    fn released(&self, text: String) -> (String, bool) {
470        use rmcp::model::{CallToolResult, ContentBlock};
471        let released = crate::server::policy_guard::release_result(
472            self.tool,
473            CallToolResult::success(vec![ContentBlock::text(text)]),
474        );
475        let refused = released.is_error == Some(true);
476        let released_text = released
477            .content
478            .iter()
479            .filter_map(|block| block.as_text().map(|text| text.text.clone()))
480            .collect::<Vec<_>>()
481            .join("\n");
482        let printed = if self.legacy_redaction {
483            crate::server::policy_guard::redact_model_text(&released_text)
484        } else {
485            released_text
486        };
487        (printed, refused)
488    }
489
490    /// The sequence for a machine-readable document (`--json`): the handler
491    /// runs inside the request scope, and the document it returns is released
492    /// WITHOUT ever breaking it. A document is never recorded as a delivery of
493    /// its sources — it wraps the tool's text into another representation.
494    ///
495    /// - `Ok(document)`: print it. An admitted document keeps its bytes. When
496    ///   a value had to be masked, the masked value stands in its place in a
497    ///   still valid document, and the content-free notice went to stderr —
498    ///   the schema is not extended and nothing is prefixed to stdout.
499    /// - `Err(reason)`: the document is withheld as a whole; `reason` is the
500    ///   content-free notice for stderr. Nothing is printed to stdout.
501    pub(crate) fn deliver_json(&self, handler: impl FnOnce() -> String) -> Result<String, String> {
502        self.deliver_document(handler, true)
503    }
504
505    /// [`Self::deliver_json`] for a command that writes the document WITHOUT
506    /// a final newline ([`print_released_exact`]): the receipt binds exactly
507    /// the document's bytes, nothing appended.
508    pub(crate) fn deliver_json_exact(
509        &self,
510        handler: impl FnOnce() -> String,
511    ) -> Result<String, String> {
512        self.deliver_document(handler, false)
513    }
514
515    /// The one body of [`Self::deliver_json`] and
516    /// [`Self::deliver_json_exact`]. `final_newline`: the writer adds one
517    /// `\n` after the document, so the receipt binds it too.
518    fn deliver_document(
519        &self,
520        handler: impl FnOnce() -> String,
521        final_newline: bool,
522    ) -> Result<String, String> {
523        use crate::core::context_admission::receipt_store::trace::Channel;
524        let (document, _capture) = self.acquire(handler);
525        let prepared =
526            crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
527                self.prepared_digest(&document)
528            });
529        let released = self.release_document(document);
530        // G08: the receipt binds exactly the bytes the writer writes — the
531        // document, and the final `\n` where the writer adds one. A
532        // withheld document prepares nothing for stdout: its reason is
533        // prepared for stderr. That those stderr bytes were written, and the
534        // status the command ends with, is recorded by [`exit_withheld`]
535        // when it has written them — never inferred from this `Err`.
536        let (written, is_error, channel) = match &released {
537            Ok((document, _)) if final_newline => {
538                (format!("{document}\n"), false, self.output_channel())
539            }
540            Ok((document, _)) => (document.clone(), false, self.output_channel()),
541            Err(reason) => (format!("{reason}\n"), true, Channel::Stderr),
542        };
543        let receipted =
544            crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
545                self.receipted(&written, is_error, prepared, channel)
546            });
547        if !receipted {
548            return Err(crate::core::context_admission::receipt_store::not_persisted_notice());
549        }
550        let (document, notice) = released?;
551        if let Some(notice) = notice {
552            eprintln!("{notice}");
553        }
554        Ok(document)
555    }
556
557    /// [`Self::deliver_json`] without the handler run and without stderr: the
558    /// released document and, when something was masked in it, the notice.
559    /// Runs inside the run's admission capture (G08).
560    fn release_document(&self, document: String) -> Result<(String, Option<String>), String> {
561        let release = || {
562            crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
563                self.captured(|| self.release_document_scoped(document))
564            })
565        };
566        match self.verified_signer_key {
567            Some(key) => crate::core::redaction::with_verified_signer_key(key, release),
568            None => release(),
569        }
570    }
571
572    fn release_document_scoped(
573        &self,
574        document: String,
575    ) -> Result<(String, Option<String>), String> {
576        use crate::core::context_admission::carrier::{ReleaseGate, Withheld};
577        crate::tools::admitted_sources::as_agent_acquisition(self.project_root, || {
578            // The whole document through the one release sequence first: an
579            // admitted document passes unchanged and keeps its bytes (#498).
580            let (whole, refused) = self.released(document.clone());
581            if !refused && whole == document {
582                return Ok((document, None));
583            }
584            let unadmitted = || Withheld::new(&["release.unadmitted_content"]).notice();
585            // Something has to be masked. Masking the serialized text could
586            // cut through its syntax, so every string value is released on
587            // its own and the document is serialized again around them.
588            let Ok(mut value) = serde_json::from_str::<serde_json::Value>(&document) else {
589                return Err(if refused { whole } else { unadmitted() });
590            };
591            let gate = ReleaseGate::current();
592            let mut notice = None;
593            self.mask_leaves(&gate, &mut value, 0, &mut notice)?;
594            let serialized = if document.contains('\n') {
595                serde_json::to_string_pretty(&value)
596            } else {
597                serde_json::to_string(&value)
598            };
599            let Ok(masked) = serialized else {
600                return Err(unadmitted());
601            };
602            // The result must itself pass the release sequence unchanged;
603            // what value-wise masking cannot settle (a policy-pack refusal,
604            // a finding in a key) withholds the document as a whole.
605            let (verified, refused) = self.released(masked.clone());
606            if refused {
607                return Err(verified);
608            }
609            if verified != masked {
610                return Err(unadmitted());
611            }
612            let notice =
613                notice.unwrap_or_else(|| "[lean-ctx gateway: content redacted]".to_string());
614            Ok((masked, Some(notice)))
615        })
616    }
617
618    /// Release every string value of `value` in place. A key is never
619    /// rewritten (that would change the schema): a finding in a key, a
620    /// withheld value or a document nested too deep to inspect withholds the
621    /// whole document with a content-free reason.
622    fn mask_leaves(
623        &self,
624        gate: &crate::core::context_admission::carrier::ReleaseGate,
625        value: &mut serde_json::Value,
626        depth: usize,
627        notice: &mut Option<String>,
628    ) -> Result<(), String> {
629        use crate::core::context_admission::carrier::{Release, Withheld};
630        use serde_json::Value;
631        const MAX_DEPTH: usize = 64;
632        if depth > MAX_DEPTH {
633            return Err(Withheld::new(&["coverage.partial"]).notice());
634        }
635        match value {
636            Value::String(text) => {
637                match gate.text(text) {
638                    Release::Unchanged => {}
639                    Release::Redacted {
640                        text: masked,
641                        notice: line,
642                    } => {
643                        *text = masked;
644                        notice.get_or_insert(line);
645                    }
646                    Release::Withheld(withheld) => return Err(withheld.notice()),
647                }
648                if self.legacy_redaction {
649                    *text = crate::server::policy_guard::redact_model_text(text);
650                }
651            }
652            Value::Array(items) => {
653                for item in items {
654                    self.mask_leaves(gate, item, depth + 1, notice)?;
655                }
656            }
657            Value::Object(map) => {
658                for (key, item) in map {
659                    if !matches!(gate.text(key), Release::Unchanged) {
660                        return Err(Withheld::new(&["release.unadmitted_content"]).notice());
661                    }
662                    self.mask_leaves(gate, item, depth + 1, notice)?;
663                }
664            }
665            Value::Null | Value::Bool(_) | Value::Number(_) => {}
666        }
667        Ok(())
668    }
669
670    /// Run `handler` and return the text to print (steps 1–3 above). A
671    /// handler error is passed through; nothing is released or recorded for
672    /// it.
673    pub(crate) fn deliver<E>(
674        &self,
675        handler: impl FnOnce() -> Result<String, E>,
676    ) -> Result<String, E> {
677        let (outcome, printed) = self.run(|| match handler() {
678            Ok(text) => (Ok(()), Some(Printable::tool_text(text))),
679            Err(error) => (Err(error), None),
680        });
681        outcome.map(|()| printed.unwrap_or_default())
682    }
683
684    /// [`Self::deliver`] for a handler that cannot fail.
685    pub(crate) fn deliver_text(&self, handler: impl FnOnce() -> String) -> String {
686        match self.deliver(|| Ok::<String, std::convert::Infallible>(handler())) {
687            Ok(text) => text,
688            Err(never) => match never {},
689        }
690    }
691}
692
693/// The ONE stdout writer for a text a [`CliToolRun`] returned: `text` and
694/// its final `\n`, written and flushed, and — only after both succeeded —
695/// the observation that exactly the bytes a receipt was prepared for were
696/// handed to stdout (G08, `receipt_store::observed`). Text no receipt was
697/// prepared for (no protection) is written the same way and records
698/// nothing. A failed write ends the command with status 1; it records no
699/// hand-over.
700pub(crate) fn print_released(text: &str) {
701    write_stdout_observed(format!("{text}\n").as_bytes());
702}
703
704/// [`print_released`] without the final `\n`: exactly `text` is written. For
705/// output whose receipt was prepared for exactly its bytes
706/// ([`CliToolRun::deliver_json_exact`]).
707pub(crate) fn print_released_exact(text: &str) {
708    write_stdout_observed(text.as_bytes());
709}
710
711fn write_stdout_observed(bytes: &[u8]) {
712    use crate::core::context_admission::receipt_store::{observed, trace::Channel};
713    let written =
714        observed::write_observed(&mut std::io::stdout().lock(), Channel::Stdout, bytes, None);
715    if let Err(error) = written {
716        eprintln!("lean-ctx: output could not be written: {error}");
717        std::process::exit(1);
718    }
719}
720
721/// The ONE stderr writer for a text a [`CliToolRun`] prepared for stderr
722/// ([`CliToolRun::to_stderr`]): `text` and its final `\n`, written and
723/// flushed, then the observation for the receipt this thread prepared for
724/// exactly those bytes. Returns to the caller. `exit_status`: the status the
725/// caller ends the process with right after, when it does; it is recorded
726/// with the observation. A failed write records nothing.
727pub(crate) fn eprint_released(text: &str, exit_status: Option<i32>) {
728    use crate::core::context_admission::receipt_store::{observed, trace::Channel};
729    let line = format!("{text}\n");
730    let _ = observed::write_observed(
731        &mut std::io::stderr().lock(),
732        Channel::Stderr,
733        line.as_bytes(),
734        exit_status,
735    );
736}
737
738/// The command wrote exactly `bytes` to the file it was asked for and the
739/// write SUCCEEDED: record `handed_over` (channel `file`) for the receipt
740/// this thread prepared with [`CliToolRun::to_file`], if these are the
741/// prepared bytes. Call it only after the successful write; other bytes, or
742/// no prepared receipt, record nothing.
743pub(crate) fn confirm_written_to_file(bytes: &[u8]) {
744    use crate::core::context_admission::receipt_store::{observed, trace::Channel};
745    observed::handed_over(Channel::File, bytes, None);
746}
747
748/// The command handed exactly `text` to the system clipboard and the
749/// hand-off SUCCEEDED: record `handed_over` (channel `clipboard`) for the
750/// receipt this thread prepared with [`CliToolRun::to_clipboard`]. Call it
751/// only after that success.
752pub(crate) fn confirm_copied_to_clipboard(text: &str) {
753    use crate::core::context_admission::receipt_store::{observed, trace::Channel};
754    observed::handed_over(Channel::Clipboard, text.as_bytes(), None);
755}
756
757/// End a command whose machine-readable document was withheld as a whole
758/// ([`CliToolRun::deliver_json`]): the content-free reason on stderr, exit 1,
759/// nothing on stdout. The ONE writer of that reason: after the bytes were
760/// written and flushed, the observation binds them and the exit status the
761/// process is ended with on the next line (G08). A failed write records
762/// nothing; the process ends with status 1 either way.
763pub(crate) fn exit_withheld(reason: &str) -> ! {
764    eprint_released(reason, Some(1));
765    std::process::exit(1);
766}
767
768/// Strip savings footers from daemon output when the CLI client has footer suppressed.
769#[cfg(unix)]
770pub(crate) fn filter_daemon_output(text: &str) -> String {
771    if crate::core::protocol::savings_footer_visible() {
772        return text.to_string();
773    }
774    text.lines()
775        .filter(|l| {
776            let t = l.trim();
777            !(t.starts_with('[')
778                && t.contains("tok")
779                && t.ends_with(']')
780                && (t.contains("tok saved") || t.contains("lean-ctx:") || t.contains("vs native")))
781        })
782        .collect::<Vec<_>>()
783        .join("\n")
784}
785
786pub fn load_shell_history_pub() -> Vec<String> {
787    load_shell_history()
788}
789
790pub(crate) fn load_shell_history() -> Vec<String> {
791    let shell = std::env::var("SHELL").unwrap_or_default();
792    let Some(home) = dirs::home_dir() else {
793        return Vec::new();
794    };
795
796    let history_file = if shell.contains("zsh") {
797        home.join(".zsh_history")
798    } else if shell.contains("fish") {
799        home.join(".local/share/fish/fish_history")
800    } else if cfg!(windows) && shell.is_empty() {
801        home.join("AppData")
802            .join("Roaming")
803            .join("Microsoft")
804            .join("Windows")
805            .join("PowerShell")
806            .join("PSReadLine")
807            .join("ConsoleHost_history.txt")
808    } else {
809        home.join(".bash_history")
810    };
811
812    // Shell history files (especially zsh's metafied format) frequently contain
813    // non-UTF-8 bytes; `read_to_string` would reject the whole file. Read raw and
814    // decode lossily so a single bad byte never hides 900 lines of real history.
815    match std::fs::read(&history_file) {
816        Ok(bytes) => admitted_history(&String::from_utf8_lossy(&bytes))
817            .lines()
818            .filter_map(|l| {
819                let trimmed = l.trim();
820                if trimmed.starts_with(':') {
821                    trimmed
822                        .split(';')
823                        .nth(1)
824                        .map(std::string::ToString::to_string)
825                } else {
826                    Some(trimmed.to_string())
827                }
828            })
829            .filter(|l| !l.is_empty())
830            .collect(),
831        Err(_) => Vec::new(),
832    }
833}
834
835/// Shell history is command lines the user typed — tokens, passwords and
836/// connection strings included. Before anything is counted, ranked or printed
837/// from it (`discover`, `session` statistics), the whole text passes
838/// admission as carrier text: a value the gateway masks is masked in every
839/// derived line, and a history the policy withholds contributes no line at
840/// all. Redaction keeps the line structure, so the per-line parsing below is
841/// unaffected for clean history. Nothing is written back.
842fn admitted_history(raw: &str) -> String {
843    crate::core::context_admission::carrier::admit_carrier_text(raw)
844        .map(|admission| admission.text)
845        .unwrap_or_default()
846}
847
848pub(crate) fn daemon_fallback_hint() {
849    use std::sync::Once;
850    static HINT: Once = Once::new();
851    HINT.call_once(|| {
852        if crate::core::protocol::meta_visible() {
853            eprintln!("\x1b[2;33mhint: daemon not running — stats tracked locally (lean-ctx serve -d for full tracking)\x1b[0m");
854        }
855    });
856}
857
858pub(crate) fn format_tokens_cli(tokens: u64) -> String {
859    if tokens >= 1_000_000_000_000 {
860        format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
861    } else if tokens >= 1_000_000_000 {
862        // Heavy users cross 1B; keep growing visibly instead of "1310.0M".
863        format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
864    } else if tokens >= 1_000_000 {
865        format!("{:.1}M", tokens as f64 / 1_000_000.0)
866    } else if tokens >= 1_000 {
867        format!("{:.1}K", tokens as f64 / 1_000.0)
868    } else {
869        format!("{tokens}")
870    }
871}
872
873pub(crate) fn detect_project_root(args: &[String]) -> String {
874    detect_project_root_in(args, std::env::current_dir().ok().as_deref())
875}
876
877/// The project a command that writes project-scoped state acts for; `Err`
878/// instead of `~`, `/` or an agent directory (AP04-G10).
879pub(crate) fn require_project_root() -> Result<String, String> {
880    require_project_root_in(std::env::current_dir().ok().as_deref())
881}
882
883fn require_project_root_in(cwd: Option<&std::path::Path>) -> Result<String, String> {
884    let root = detect_project_root_in(&[], cwd);
885    if crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(&root)) {
886        return Err(format!(
887            "{root} is not a project — run inside a project or set LEAN_CTX_PROJECT_ROOT"
888        ));
889    }
890    Ok(root)
891}
892
893fn detect_project_root_in(args: &[String], cwd: Option<&std::path::Path>) -> String {
894    let mut it = args.iter().peekable();
895    while let Some(a) = it.next() {
896        if let Some(v) = a.strip_prefix("--root=")
897            && !v.trim().is_empty()
898        {
899            return normalize_explicit_root(v);
900        }
901        if let Some(v) = a.strip_prefix("--project-root=")
902            && !v.trim().is_empty()
903        {
904            return normalize_explicit_root(v);
905        }
906        if (a == "--root" || a == "--project-root")
907            && let Some(v) = it.peek()
908            && !v.starts_with("--")
909            && !v.trim().is_empty()
910        {
911            return normalize_explicit_root(v);
912        }
913    }
914    let cwd_root = cwd.map(|cwd| promote_to_git_root(&cwd.to_string_lossy()));
915    if let Ok(root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
916        && !root.trim().is_empty()
917    {
918        return crate::server::roots::reconcile_pinned_root(
919            normalize_explicit_root(&root),
920            cwd_root,
921        );
922    }
923    cwd_root.unwrap_or_else(|| ".".to_string())
924}
925
926fn normalize_explicit_root(path: &str) -> String {
927    let expanded = expand_home(path.trim());
928    crate::core::index_paths::normalize_project_root(&expanded)
929}
930
931fn expand_home(path: &str) -> String {
932    if path == "~" {
933        return dirs::home_dir().map_or_else(
934            || path.to_string(),
935            |home| home.to_string_lossy().to_string(),
936        );
937    }
938    if let Some(rest) = path.strip_prefix("~/") {
939        return dirs::home_dir().map_or_else(
940            || path.to_string(),
941            |home| home.join(rest).to_string_lossy().to_string(),
942        );
943    }
944    path.to_string()
945}
946
947pub(crate) fn promote_to_git_root(path: &str) -> String {
948    let mut p = std::path::Path::new(path);
949    loop {
950        // A dotfiles repository at `~` is not the project of everything below.
951        if p.join(".git").exists() && !crate::core::pathutil::is_broad_or_unsafe_root(p) {
952            return p.to_string_lossy().to_string();
953        }
954        match p.parent() {
955            Some(parent) => p = parent,
956            None => return path.to_string(),
957        }
958    }
959}
960
961/// Shared set-up for the tests of the CLI commands that run through
962/// [`CliToolRun`]. Every test starts with the isolation lines
963/// (`isolated_data_dir`, `TestPolicyOverride`) itself.
964#[cfg(test)]
965pub(crate) mod carrier_tests_support {
966    /// A value the gateway masks in every mode.
967    pub(crate) const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
968
969    /// Governed mode without a pack: protection is active, so the admitted
970    /// readers publish their sources into the capture. Call after
971    /// `isolated_data_dir()`.
972    pub(crate) fn governed() {
973        let dir = crate::core::paths::config_dir_read_only().expect("isolated config dir");
974        std::fs::create_dir_all(&dir).expect("config dir");
975        std::fs::write(
976            dir.join("config.toml"),
977            "[context_gateway]\nmode = \"governed\"\n",
978        )
979        .expect("config");
980    }
981
982    /// A project directory and its canonical root.
983    pub(crate) fn project() -> (tempfile::TempDir, String) {
984        let project = tempfile::tempdir().expect("project dir");
985        let root = std::fs::canonicalize(project.path())
986            .expect("root")
987            .to_string_lossy()
988            .into_owned();
989        (project, root)
990    }
991
992    /// Write `content` to `name` under `root`; returns the absolute path.
993    pub(crate) fn source_file(root: &str, name: &str, content: &str) -> String {
994        let path = std::path::Path::new(root).join(name);
995        std::fs::write(&path, content).expect("fixture");
996        path.to_string_lossy().into_owned()
997    }
998
999    /// What a handler does that derives its output from a project source:
1000    /// one read through the admitted reader, which publishes the source.
1001    pub(crate) fn acquire_source(root: &str, path: &str) {
1002        crate::tools::ctx_read::read_file_for_tool_rooted(path, root, "ctx_read")
1003            .expect("admitted source");
1004    }
1005
1006    /// The lineage on record for exactly `printed`, looked up and judged
1007    /// inside the project scope, as the proxy does. `None`: not registered.
1008    pub(crate) fn lineage(root: &str, printed: &str) -> Option<bool> {
1009        crate::tools::admitted_sources::as_agent_acquisition(root, || {
1010            crate::core::archive::delivered::lineage_of(&crate::core::archive::delivered::digest(
1011                printed,
1012            ))
1013            .map(|lineage| lineage.still_admitted().is_ok())
1014        })
1015    }
1016
1017    /// The daemon route switched off for the lifetime of the guard.
1018    pub(crate) struct NoDaemon;
1019
1020    impl NoDaemon {
1021        pub(crate) fn set() -> Self {
1022            crate::test_env::set_var("__LEAN_CTX_NO_DAEMON", "1");
1023            Self
1024        }
1025    }
1026
1027    impl Drop for NoDaemon {
1028        fn drop(&mut self) {
1029            crate::test_env::remove_var("__LEAN_CTX_NO_DAEMON");
1030        }
1031    }
1032}
1033
1034#[cfg(test)]
1035#[path = "common_tests.rs"]
1036mod tests;