1use super::{
3 attempts::{self, ProbeScope},
4 inspection, invalid, same_source,
5};
6use crate::{
7 Result,
8 context::HostContext,
9 observation::{self, Entry, Kind},
10 state::WriterLock,
11};
12use serde::Serialize;
13use std::path::PathBuf;
14
15#[derive(Clone)]
16pub struct CloseRequest {
17 pub id: String,
18 pub executable: Option<PathBuf>,
20 pub search_dirs: Vec<PathBuf>,
21 pub npm_binding: Option<inspection::NpmBinding>,
23 pub brew_prefix: Option<PathBuf>,
24}
25pub struct ClosePreview {
26 id: String,
27 head: String,
28 original_scope_known: bool,
29 scope: ProbeScope,
30 executable: Entry,
31 npm_cli: Option<Entry>,
32 brew_prefix: Option<Entry>,
33 host_binding: String,
34 preview: inspection::Preview,
35}
36pub struct CloseApproval(ClosePreview);
37#[derive(Serialize)]
38pub struct CloseReview<'a> {
39 pub attempt_id: &'a str,
40 pub original_scope_known: bool,
41 pub query: &'a inspection::Description,
42 pub explanation: &'static str,
43 pub brew_prefix: Option<&'a std::path::Path>,
44 pub fresh_probes: Vec<Vec<String>>,
45}
46impl ClosePreview {
47 pub fn review(&self) -> CloseReview<'_> {
48 CloseReview {
49 attempt_id: &self.id,
50 original_scope_known: self.original_scope_known,
51 query: self.preview.description(),
52 brew_prefix: self.scope.brew_prefix.as_deref(),
53 fresh_probes: if self.scope.brew_prefix.is_some() {
54 vec![vec!["--prefix".into()]]
55 } else {
56 vec![]
57 },
58 explanation: "Checks the current package-manager scope, then closes the record if it is unchanged. It does not retry, repair packages or roll back earlier effects.",
59 }
60 }
61 pub fn approve(self) -> CloseApproval {
62 CloseApproval(self)
63 }
64}
65fn executable(path: &std::path::Path) -> Result<Entry> {
66 let e = observation::inspect(path, false)?;
67 if e.kind != Kind::Regular
68 || e.fingerprint
69 .as_ref()
70 .is_none_or(|f| f.mode & 0o111 == 0 || f.links != 1)
71 {
72 return Err(invalid(
73 "closure needs a regular executable at the explicit canonical path",
74 ));
75 }
76 Ok(e)
77}
78pub fn prepare_close(host: &HostContext, request: CloseRequest) -> Result<ClosePreview> {
80 let a = attempts::get(host, &request.id)?;
81 if !a.unresolved {
82 return Err(invalid("Tools attempt is already resolved"));
83 }
84 let known = a.scope.is_some();
85 let scope = if let Some(s) = a.scope {
86 if s.home != host.home
87 || request
88 .executable
89 .as_ref()
90 .is_some_and(|e| e != &s.executable)
91 || (!request.search_dirs.is_empty() && request.search_dirs != s.search_dirs)
92 || request
93 .brew_prefix
94 .as_ref()
95 .is_some_and(|p| s.brew.as_ref().is_none_or(|b| &b.prefix != p))
96 || request
97 .npm_binding
98 .as_ref()
99 .is_some_and(|b| s.npm.as_ref().is_none_or(|n| &n.binding != b))
100 {
101 return Err(invalid(
102 "closure must use the displayed original provider scope",
103 ));
104 }
105 ProbeScope {
106 executable: s.executable,
107 home: s.home,
108 search_dirs: s.search_dirs,
109 npm_binding: s.npm.map(|n| n.binding),
110 brew_prefix: s.brew.map(|b| b.prefix),
111 }
112 } else {
113 ProbeScope { executable: request.executable.ok_or_else(|| invalid("damaged intent needs an explicit trusted provider executable and search directories"))?,
114 home: host.home.clone(), search_dirs: request.search_dirs, npm_binding: request.npm_binding, brew_prefix: request.brew_prefix }
115 };
116 let preview = scope.preview()?;
117 let npm_cli = scope
118 .npm_binding
119 .as_ref()
120 .map(|b| super::npm::program(&b.npm_cli, false))
121 .transpose()?;
122 let executable = executable(&scope.executable)?;
123 let brew_prefix = scope
124 .brew_prefix
125 .as_ref()
126 .map(|p| {
127 let e = observation::inspect(p, false)?;
128 if e.kind != Kind::Directory {
129 return Err(invalid(
130 "Homebrew closure prefix must be physical and available",
131 ));
132 }
133 Ok(e)
134 })
135 .transpose()?;
136 Ok(ClosePreview {
137 id: request.id,
138 head: a.head,
139 original_scope_known: known,
140 scope,
141 executable,
142 npm_cli,
143 brew_prefix,
144 host_binding: crate::journal::digest(crate::journal::encode(host)?.as_bytes()),
145 preview,
146 })
147}
148fn same_cli(cli: &Option<Entry>, scope: &ProbeScope) -> Result<bool> {
149 Ok(match (cli, &scope.npm_binding) {
150 (Some(e), Some(b)) => same_source(e, &super::npm::program(&b.npm_cli, false)?),
151 (None, None) => true,
152 _ => false,
153 })
154}
155pub fn close(
156 host: &HostContext,
157 lock: &WriterLock,
158 approval: CloseApproval,
159) -> Result<super::Attempt> {
160 lock.check_context(host)?;
161 let old = approval.0;
162 if old.host_binding != crate::journal::digest(crate::journal::encode(host)?.as_bytes())
163 || !same_cli(&old.npm_cli, &old.scope)?
164 || !same_source(&old.executable, &executable(&old.scope.executable)?)
165 {
166 return Err(invalid(
167 "Tools closure scope changed; request a fresh review",
168 ));
169 }
170 let before = attempts::get(host, &old.id)?;
171 if before.head != old.head || !before.unresolved {
172 return Err(invalid(
173 "Tools attempt changed; request a fresh closure review",
174 ));
175 }
176 if !same_cli(&old.npm_cli, &old.scope)?
177 || !same_source(&old.executable, &executable(&old.scope.executable)?)
178 {
179 return Err(invalid(
180 "Tools closure executable changed before inspection",
181 ));
182 }
183 if let Some(prefix) = &old.brew_prefix {
184 let check = || -> Result<()> {
185 if !super::npm::same_directory(prefix, &observation::inspect(&prefix.path, false)?)
186 || !same_source(&old.executable, &executable(&old.scope.executable)?)
187 {
188 return Err(invalid("Homebrew closure scope changed"));
189 }
190 Ok(())
191 };
192 check()?;
193 super::brew::closure_prefix(
194 &old.scope.executable,
195 &old.scope.home,
196 &old.scope.search_dirs,
197 &prefix.path,
198 )?;
199 check()?;
200 }
201 let report = old.preview.approve().inspect();
202 let inspection::Observation::Complete { installations } = report.observation else {
203 return Err(invalid(
204 "fresh closure inspection unavailable; Tools attempt remains unresolved",
205 ));
206 };
207 if !same_cli(&old.npm_cli, &old.scope)?
208 || !same_source(&old.executable, &executable(&old.scope.executable)?)
209 {
210 return Err(invalid(
211 "Tools closure executable changed during inspection",
212 ));
213 }
214 if let Some(prefix) = &old.brew_prefix
215 && !super::npm::same_directory(prefix, &observation::inspect(&prefix.path, false)?)
216 {
217 return Err(invalid("Homebrew closure prefix changed during inspection"));
218 }
219 attempts::close(
220 host,
221 lock,
222 &old.id,
223 &old.head,
224 old.scope,
225 installations.len(),
226 )
227}