ai6_api/safehouse.rs
1//! The safe-house contract, as Guatiao kinds: where a Mission's Agent works.
2//!
3//! A [`SafeHouseProvider`] turns an Operation's source (a Git checkout, a plain
4//! directory, ...) into an isolated working directory for one Mission and hands back a
5//! [`SafeHouseRun`] the caller owns. The runs where the Agent's Run
6//! runs, so a Station loads it; the headquarters never does. Slot order is the ABI:
7//! append, never reorder.
8//!
9//! A provider without history ([`SafeHouseInfo::supports_history`] is `false`) returns
10//! no [`Change`]s; cover checks then report that the work cannot be checked instead of
11//! passing it.
12
13use guatiao::library::{Object, ProviderError};
14use guatiao::{FromValue, Schema, ToValue, Value};
15
16/// What to open. Crosses as a value.
17#[derive(
18 ToValue, FromValue, Schema, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq,
19)]
20#[map(crate = ::guatiao)]
21pub struct SafeHouseSpec {
22 /// The Operation codename.
23 pub operation_id: String,
24 /// What the Mission is called when the safe house opens, its handle: it fills a branch
25 /// template's `{id}` and names the directory.
26 pub mission_id: String,
27 /// The Mission brief, used to name the branch or directory.
28 pub title: String,
29 /// Where the work comes from: a local path today.
30 pub source: String,
31 /// The revision the safe house starts from; a provider without revisions ignores it.
32 pub base: String,
33 /// Branch name template; `{id}`, `{slug}` and `{operation}` are filled in.
34 pub branch: String,
35 /// Whether to cut a separate working directory. `false` works in `source` itself.
36 pub isolate: bool,
37 /// AI6's state directory; isolated safe houses are placed beneath it.
38 pub state_root: String,
39 /// A report from an earlier open: re-attach to that safe house instead of creating one.
40 pub reopen: Option<SafeHouseReport>,
41 /// Work an earlier run saved elsewhere: start the new safe house from its commit, on
42 /// its branch, instead of from `base`. A provider without checkpoints ignores it.
43 pub checkpoint: Option<SafeHouseCheckpoint>,
44 /// Make the working directory a clone of `source` (a repository URL, `user@host:path`,
45 /// or a local repository, bare or not) on its branch `base`, instead of a Mission's working
46 /// directory beneath `state_root`. `branch`, `isolate`, `reopen` and `checkpoint` are then
47 /// ignored; a provider that cannot clone refuses it.
48 pub clone: Option<SafeHouseClone>,
49 /// A throwaway trial clone, whose base may be a commit and which may never publish.
50 pub trial: Option<bool>,
51}
52
53/// Where a cloned safe house goes. Crosses as a value, inside a [`SafeHouseSpec`].
54#[derive(
55 ToValue, FromValue, Schema, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq,
56)]
57#[map(crate = ::guatiao)]
58pub struct SafeHouseClone {
59 /// The working directory: a directory that must not exist yet.
60 pub path: String,
61 /// First make `source` an empty bare repository whose `HEAD` is the spec's `base` when it
62 /// is a local path or `file://` URL that does not exist.
63 pub create_source: bool,
64 /// Keep the repository's git directory here, a directory that must not exist yet, instead
65 /// of `.git` inside `path`: the working directory then holds no `.git` at all, so whoever
66 /// writes there cannot reach the repository's configuration or hooks.
67 pub git_dir: Option<String>,
68 /// Fetch only the last this many commits of `base` (a shallow clone); `None` fetches its
69 /// whole history.
70 pub depth: Option<u32>,
71 /// Give up on the clone, and remove what it made, after this many seconds; `None` keeps
72 /// the provider's own limit.
73 pub timeout_secs: Option<u64>,
74 /// Give up on the clone, and remove what it made, once its working directory and git
75 /// directory hold more than this many bytes; `None` sets no limit.
76 pub max_bytes: Option<u64>,
77}
78
79/// Work in progress saved where another Station can fetch it: a commit pushed to a branch.
80#[derive(
81 ToValue, FromValue, Schema, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq,
82)]
83#[map(crate = ::guatiao)]
84pub struct SafeHouseCheckpoint {
85 /// The Git remote, by name or URL, the commit was pushed to.
86 pub remote: String,
87 /// The branch on the remote that holds the commit.
88 pub branch: String,
89 /// The commit: the safe house's history plus its uncommitted changes.
90 pub commit: String,
91 /// The revision the work started from, when the provider has revisions.
92 pub base: Option<String>,
93}
94
95/// How to save a checkpoint. Crosses as a value.
96#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
97#[map(crate = ::guatiao)]
98pub struct CheckpointSpec {
99 /// The Git remote, by name or URL, to push to.
100 pub remote: String,
101 /// The message of the commit that holds uncommitted changes, already under the
102 /// Operation's cover policy.
103 pub message: String,
104 /// The author and committer name, when the Operation commits under a cover identity.
105 pub author_name: Option<String>,
106 /// The author and committer email, when the Operation commits under a cover identity.
107 pub author_email: Option<String>,
108 /// Commit the work in the working directory itself (`HEAD` moves to the commit) and push
109 /// it to this branch of `remote` as a fast-forward, instead of force-pushing a commit on
110 /// top of `HEAD` to the safe house's own branch. A push the remote refuses is tried once
111 /// more after the work is replayed on the remote branch. The answer's `branch` is where the
112 /// work landed, and its `commit` is empty when there was nothing to save.
113 pub branch: Option<String>,
114 /// With `branch`, where the work goes when the remote branch still refuses it: this
115 /// branch of `remote`, which each such push replaces. Without it the refusal is an error.
116 pub fallback: Option<String>,
117 /// With `branch`, commit exactly these files with exactly this text, and nothing else the
118 /// working directory holds, whoever is writing there meanwhile.
119 pub files: Option<Vec<CheckpointFile>>,
120 /// With `branch` and no `files`: paths, relative to the repository's root, that the save
121 /// leaves out with everything under them, as it leaves out paths with a name starting
122 /// with `.`.
123 pub exclude: Option<Vec<String>>,
124 /// With `branch` and no `files`: refuse the save, committing and pushing nothing, when the
125 /// files it would add or change hold more than this many bytes together.
126 pub max_bytes: Option<u64>,
127}
128
129/// One file a save commits with exactly its text. Crosses as a value, inside a
130/// [`CheckpointSpec`].
131#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
132#[map(crate = ::guatiao)]
133pub struct CheckpointFile {
134 /// The path, `/`-separated and relative to the repository's root; a path naming a parent
135 /// directory or `.git` is refused.
136 pub path: String,
137 /// The file's text; `None` removes it.
138 pub text: Option<String>,
139 /// What the file must hold on the remote branch for the save to go ahead: the hex
140 /// SHA-256 of its text, or empty when it must not exist there. `None` writes it whatever
141 /// it holds.
142 pub base: Option<String>,
143}
144
145/// Where an open safe house is and what it can tell.
146#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
147#[map(crate = ::guatiao)]
148pub struct SafeHouseInfo {
149 /// The working directory.
150 pub path: String,
151 /// The branch assigned to the Mission, when the provider has branches.
152 pub branch: Option<String>,
153 /// The revision the work started from, when the provider has revisions.
154 pub base: Option<String>,
155 /// Whether [`SafeHouseRun::changes`] can answer; `false` means cover is not checkable.
156 pub supports_history: bool,
157 /// Whether `path` is a separate directory made for this Mission.
158 pub isolated: bool,
159}
160
161/// One change made since the base: a commit, for a version-control provider.
162#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
163#[map(crate = ::guatiao)]
164pub struct Change {
165 /// The full change identifier.
166 pub id: String,
167 /// Author in `Name <email>` form.
168 pub author: String,
169 /// Committer in `Name <email>` form.
170 pub committer: String,
171 /// The full message.
172 pub message: String,
173}
174
175/// The changes since the base, newest first.
176#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq, Default)]
177#[map(crate = ::guatiao)]
178pub struct ChangeLog {
179 /// The changes.
180 pub changes: Vec<Change>,
181}
182
183/// The change a safe house holds since its base.
184#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq, Default)]
185#[map(crate = ::guatiao)]
186pub struct SafeHouseDiff {
187 /// The change as a unified diff, then the names of new files nothing tracks yet.
188 pub text: String,
189 /// Whether it was cut to the bytes asked for.
190 pub cut: bool,
191}
192
193/// What a safe house held when the Mission ended, attached to the Mission record.
194#[derive(
195 ToValue, FromValue, Schema, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq,
196)]
197#[map(crate = ::guatiao)]
198pub struct SafeHouseReport {
199 /// The working directory.
200 pub path: String,
201 /// The branch assigned to the Mission, when the provider has branches.
202 pub branch: Option<String>,
203 /// The revision the work started from, when the provider has revisions.
204 pub base: Option<String>,
205 /// Whether the safe house was retained because it holds work.
206 pub kept: bool,
207 /// One-line summaries of the changes since the base, newest first.
208 pub changes: Vec<String>,
209}
210
211/// What of a safe house's work exists nowhere else.
212#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq, Default)]
213#[map(crate = ::guatiao)]
214pub struct SafeHouseExports {
215 /// One-line summaries of the changes made since the base that no remote holds, newest
216 /// first: for a version-control provider, commits on no remote-tracking ref.
217 pub unexported: Vec<String>,
218 /// Whether the working directory holds changes that were never recorded as a change,
219 /// including untracked files.
220 pub dirty: bool,
221 /// Paths, relative to the safe house, that version control ignores: a directory ignored
222 /// whole is one entry. They exist nowhere else; a caller decides which are rebuildable.
223 pub ignored: Vec<String>,
224}
225
226impl SafeHouseExports {
227 /// Whether everything in the safe house also exists elsewhere, counting an ignored path
228 /// as rebuildable only when `rebuildable` says so.
229 pub fn is_exported(&self, rebuildable: impl Fn(&str) -> bool) -> bool {
230 self.unexported.is_empty()
231 && !self.dirty
232 && self.ignored.iter().all(|path| rebuildable(path))
233 }
234}
235
236/// Makes safe houses for Missions.
237#[guatiao::kind(name = "ai6_safehouse")]
238pub trait SafeHouseProvider: Send + Sync {
239 /// Opens the safe house described by `spec` (a [`SafeHouseSpec`] as a value).
240 fn open(&self, spec: &Value) -> Result<Object<dyn SafeHouseRun>, ProviderError>;
241}
242
243/// One Mission's safe house. Every slot takes `&self`.
244#[guatiao::kind(object, name = "ai6_safehouse_run")]
245pub trait SafeHouseRun: Send + Sync {
246 /// Answers a [`SafeHouseInfo`] as a value.
247 fn info(&self) -> Result<Value, ProviderError>;
248 /// Answers a [`ChangeLog`] as a value: the changes since the base, newest first.
249 /// Empty when the provider has no history.
250 fn changes(&self) -> Result<Value, ProviderError>;
251 /// Removes an untouched isolated safe house and retains one that holds work; answers
252 /// a [`SafeHouseReport`] as a value. Idempotent; a safe house in place is left alone.
253 fn finish(&self) -> Result<Value, ProviderError>;
254 /// Saves the work so far where another Station can fetch it, as `spec` (a
255 /// [`CheckpointSpec`] as a value) says, without touching the working directory, and
256 /// answers a [`SafeHouseCheckpoint`] as a value. Unsupported unless the provider has it.
257 fn checkpoint(&self, spec: &Value) -> Result<Value, ProviderError> {
258 let _ = spec;
259 Err(ProviderError::new(
260 guatiao::Status::GUATIAO_ERR_UNSUPPORTED,
261 "this safe-house provider does not save checkpoints",
262 ))
263 }
264 /// Answers a [`SafeHouseDiff`] as a value: the change since the base, at most `bytes` of it.
265 /// Unsupported unless the provider has history.
266 fn diff(&self, bytes: u64) -> Result<Value, ProviderError> {
267 let _ = bytes;
268 Err(ProviderError::new(
269 guatiao::Status::GUATIAO_ERR_UNSUPPORTED,
270 "this safe-house provider cannot show its change",
271 ))
272 }
273 /// Answers a [`SafeHouseExports`] as a value: what of the work exists only here.
274 /// Unsupported unless the provider can tell; a caller then treats all of it as
275 /// unexported.
276 fn exports(&self) -> Result<Value, ProviderError> {
277 Err(ProviderError::new(
278 guatiao::Status::GUATIAO_ERR_UNSUPPORTED,
279 "this safe-house provider cannot tell what of its work exists elsewhere",
280 ))
281 }
282 /// Removes an isolated safe house whatever it holds: its working directory and, for a
283 /// version-control provider, the Mission's branch. A safe house in place is refused.
284 /// Unsupported unless the provider has it.
285 fn discard(&self) -> Result<(), ProviderError> {
286 Err(ProviderError::new(
287 guatiao::Status::GUATIAO_ERR_UNSUPPORTED,
288 "this safe-house provider cannot remove a safe house that holds work",
289 ))
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 // A changed required signature affects every built safe-house provider.
298 #[test]
299 fn floor_hashes_are_pinned() {
300 assert_eq!(SafeHouseProviderVtable::FLOOR_HASH, 4168913036);
301 assert_eq!(SafeHouseRunVtable::FLOOR_HASH, 1018608612);
302 }
303
304 fn spec() -> SafeHouseSpec {
305 SafeHouseSpec {
306 operation_id: "G".to_owned(),
307 mission_id: "mission-1".to_owned(),
308 title: "Inspect".to_owned(),
309 source: "/work/project".to_owned(),
310 base: "HEAD".to_owned(),
311 branch: "{id}-{slug}".to_owned(),
312 isolate: true,
313 state_root: "/state".to_owned(),
314 reopen: Some(SafeHouseReport {
315 path: "/state/safe-houses/G/mission-1".to_owned(),
316 branch: Some("mission-1-inspect".to_owned()),
317 base: Some("abc".to_owned()),
318 kept: true,
319 changes: vec!["abc1234 add work".to_owned()],
320 }),
321 checkpoint: None,
322 trial: None,
323 clone: None,
324 }
325 }
326
327 // A model grows by optional fields only: these keys are what built providers read.
328 #[test]
329 fn models_keep_their_required_keys() {
330 let json = serde_json::to_value(spec()).unwrap();
331 // The ACP crates turn on serde_json's `preserve_order`, so the keys are sorted here.
332 let mut keys = json.as_object().unwrap().keys().collect::<Vec<_>>();
333 keys.sort();
334 assert_eq!(
335 keys,
336 [
337 "base",
338 "branch",
339 "checkpoint",
340 "clone",
341 "isolate",
342 "mission_id",
343 "operation_id",
344 "reopen",
345 "source",
346 "state_root",
347 "title",
348 "trial"
349 ]
350 );
351 }
352
353 #[test]
354 fn a_spec_round_trips_through_a_value() {
355 let spec = spec();
356 let value = spec.to_value().unwrap();
357 assert_eq!(SafeHouseSpec::from_value(&value).unwrap(), spec);
358 }
359}