返回 CodeWhale
turn_artifacts.rs
根目录 / crates / engine / src / runtime_threads / turn_artifacts.rs
1 //! Typed artifact references on runtime turns and items.
2 //!
3 //! A turn's artifacts are what it left behind that a client can open: files
4 //! a tool created or changed in the workspace, tool output that spilled to
5 //! the session artifact directory, and media a tool produced. Each is named
6 //! by a [`TurnArtifactRef`] carrying path, kind, size and revision, so a
7 //! Preview surface can show "what this turn produced" without scanning.
8 //!
9 //! Facts come from where the bytes were written, never from re-reading the
10 //! disk later: file tools and `apply_patch` record `size`/`sha256` in their
11 //! `mutation.files[]` receipt, spills record `artifact_digest`, and media
12 //! publication records `sha256`. This module only parses those receipts and
13 //! confines every path; there is no second artifact store.
14
15 use std::path::{Component, Path, PathBuf};
16
17 use chrono::{DateTime, Utc};
18 use serde::{Deserialize, Serialize};
19 use serde_json::Value;
20
21 /// Hard ceiling on refs parsed from one tool result. A patch touching more
22 /// files than this is still applied; the extra refs are simply not listed.
23 pub const MAX_ITEM_ARTIFACTS: usize = 1_000;
24
25 /// What kind of thing the reference names.
26 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27 #[serde(rename_all = "snake_case")]
28 pub enum TurnArtifactKind {
29 /// A file in the thread workspace; `path` is workspace-relative.
30 File,
31 /// Tool output spilled to the session artifact directory; `path` is
32 /// session-relative (`artifacts/art_<call>.txt`).
33 ToolOutput,
34 /// Media a tool returned, published immutably under the session.
35 Media,
36 }
37
38 /// How a file changed. Only set on `kind = file`.
39 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40 #[serde(rename_all = "snake_case")]
41 pub enum FileChangeKind {
42 Created,
43 Updated,
44 Deleted,
45 Renamed,
46 }
47
48 /// Which receipt produced the reference.
49 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
50 #[serde(rename_all = "snake_case")]
51 pub enum TurnArtifactSource {
52 /// A file tool's `mutation` receipt (write/edit/apply_patch).
53 ToolMutation,
54 /// A large tool result spilled to a session artifact.
55 ToolOutputSpill,
56 /// A tool's media publication.
57 ToolMedia,
58 /// The workspace snapshot delta between the turn's pre-turn and
59 /// post-turn snapshots. This is everything that changed in the workspace
60 /// while the turn ran, which includes writes by shell commands and
61 /// sub-agents but also by anything else writing the same workspace at the
62 /// same time (an editor, another thread, a background job).
63 WorkspaceChangedDuringTurn,
64 }
65
66 /// One thing a turn (or one tool call inside it) produced.
67 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68 pub struct TurnArtifactRef {
69 /// URL-safe id, stable within the turn: `file_<32 hex>` for a file (a
70 /// digest of its path), the spill's `art_<call>` id, or the media
71 /// `art_image_<sha256>` handle.
72 pub id: String,
73 pub kind: TurnArtifactKind,
74 /// `kind = file`: workspace-relative with `/` separators.
75 /// `tool_output`/`media`: session-relative (`artifacts/...`).
76 pub path: String,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub change: Option<FileChangeKind>,
79 /// The old path of a renamed file.
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub previous_path: Option<String>,
82 /// Byte size of the content this reference names. `None` when deleted.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub size: Option<u64>,
85 /// SHA-256 (lowercase hex) of the whole content: the same value the
86 /// workspace file read reports as `revision`. `None` when deleted or too
87 /// large to hash.
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub revision: Option<String>,
90 /// Exact media type, for `kind = media`.
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub content_type: Option<String>,
93 /// Owning artifact session, for `tool_output`/`media`.
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub session_id: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub item_id: Option<String>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub tool_call_id: Option<String>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub tool_name: Option<String>,
102 pub source: TurnArtifactSource,
103 /// A restore point `POST /v1/threads/{id}/file-revert` accepts for this
104 /// file on this thread: the tree id of a `tool` or `pre_turn` snapshot
105 /// recorded on this turn (`TurnRecord::workspace_snapshots`), so the
106 /// thread owns it (#6621). Absent when the turn recorded none.
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub restore_snapshot_id: Option<String>,
109 pub recorded_at: DateTime<Utc>,
110 }
111
112 /// Identity of the tool call a set of refs is parsed for.
113 pub struct ToolArtifactContext<'a> {
114 pub item_id: &'a str,
115 pub tool_call_id: &'a str,
116 pub tool_name: &'a str,
117 /// The thread workspace every file path is confined to: as configured,
118 /// and canonicalized when that differs (tools resolve against the
119 /// configured path, which may traverse a symlink such as macOS `/var`).
120 pub workspace_roots: &'a [PathBuf],
121 /// The `tool` restore point recorded on this turn for this call (its
122 /// tree id), when there is one. Only a receipt the thread owns is
123 /// advertised.
124 pub restore_snapshot_id: Option<&'a str>,
125 pub recorded_at: DateTime<Utc>,
126 }
127
128 /// The stable ref id for a workspace file path.
129 pub fn file_artifact_id(path: &str) -> String {
130 let digest = codewhale_runtime::hashing::sha256_hex(path.as_bytes());
131 format!("file_{}", &digest[..32])
132 }
133
134 pub fn is_sha256_hex(value: &str) -> bool {
135 value.len() == 64
136 && value
137 .bytes()
138 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
139 }
140
141 /// Normalize a tool-supplied path into a workspace-relative display path.
142 ///
143 /// Accepts a relative path or an absolute one inside any of the workspace's
144 /// root spellings. Refuses `..`, empty, non-UTF-8, anything outside, and
145 /// `.git` (never served).
146 pub fn confined_workspace_path(workspace_roots: &[PathBuf], raw: &str) -> Option<String> {
147 let rel = workspace_roots
148 .iter()
149 .find_map(|root| codewhale_snapshot::workspace_relative_path(root, raw))?;
150 relative_display(&rel)
151 }
152
153 fn relative_display(rel: &Path) -> Option<String> {
154 let mut parts = Vec::new();
155 for component in rel.components() {
156 let Component::Normal(name) = component else {
157 return None;
158 };
159 if codewhale_util::git_metadata::is_git_metadata_name(name) {
160 return None;
161 }
162 parts.push(name.to_str()?);
163 }
164 (!parts.is_empty()).then(|| parts.join("/"))
165 }
166
167 /// A session-relative artifact path: relative, `/`-separated, under
168 /// `artifacts/`, with no `.`/`..` components.
169 pub fn confined_session_artifact_path(raw: &str) -> Option<String> {
170 if raw.contains('\\') {
171 return None;
172 }
173 let path = PathBuf::from(raw);
174 if path.is_absolute() {
175 return None;
176 }
177 let display = relative_display(&path)?;
178 display
179 .split('/')
180 .next()
181 .is_some_and(|first| first == codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME)
182 .then_some(display)
183 }
184
185 fn is_safe_artifact_id(id: &str) -> bool {
186 id.starts_with("art_")
187 && id.len() <= 200
188 && id
189 .bytes()
190 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
191 }
192
193 fn change_kind(outcome: &str) -> Option<FileChangeKind> {
194 match outcome {
195 "created" => Some(FileChangeKind::Created),
196 "updated" => Some(FileChangeKind::Updated),
197 "deleted" => Some(FileChangeKind::Deleted),
198 _ => None,
199 }
200 }
201
202 fn written_facts(entry: &Value) -> (Option<u64>, Option<String>) {
203 let size = entry.get("size").and_then(Value::as_u64);
204 let revision = entry
205 .get("sha256")
206 .and_then(Value::as_str)
207 .filter(|digest| is_sha256_hex(digest))
208 .map(str::to_owned);
209 (size, revision)
210 }
211
212 /// Parse the artifact references a tool result's metadata describes.
213 ///
214 /// Three receipts are read: `mutation.files[]`/`mutation.renames[]` (file
215 /// tools), the spill keys `artifact_id`/`artifact_session_id`/
216 /// `artifact_relative_path`/`artifact_byte_size`/`artifact_digest`, and
217 /// `tool_media[]`. Anything that is not confined — an absolute or `..`
218 /// path, a path outside the workspace, an invalid session id — yields no
219 /// reference rather than a reference a client could be misled by.
220 pub fn artifact_refs_from_tool_metadata(
221 metadata: &Value,
222 context: &ToolArtifactContext<'_>,
223 ) -> Vec<TurnArtifactRef> {
224 let mut refs = Vec::new();
225 let base = |id: String, kind, path: String, source| TurnArtifactRef {
226 id,
227 kind,
228 path,
229 change: None,
230 previous_path: None,
231 size: None,
232 revision: None,
233 content_type: None,
234 session_id: None,
235 item_id: Some(context.item_id.to_owned()),
236 tool_call_id: Some(context.tool_call_id.to_owned()),
237 tool_name: Some(context.tool_name.to_owned()),
238 source,
239 restore_snapshot_id: None,
240 recorded_at: context.recorded_at,
241 };
242
243 // The call's own `tool` restore point, from the receipt recorded on this
244 // turn — never from the tool's result metadata, which a tool controls.
245 let restore_snapshot_id = context
246 .restore_snapshot_id
247 .filter(|id| codewhale_snapshot::SnapshotId::is_well_formed(id))
248 .map(str::to_owned);
249
250 if let Some(mutation) = metadata.get("mutation") {
251 for entry in mutation
252 .get("files")
253 .and_then(Value::as_array)
254 .into_iter()
255 .flatten()
256 {
257 let Some(change) = entry
258 .get("outcome")
259 .and_then(Value::as_str)
260 .and_then(change_kind)
261 else {
262 continue;
263 };
264 let Some(path) = entry
265 .get("path")
266 .and_then(Value::as_str)
267 .and_then(|raw| confined_workspace_path(context.workspace_roots, raw))
268 else {
269 continue;
270 };
271 let mut reference = base(
272 file_artifact_id(&path),
273 TurnArtifactKind::File,
274 path,
275 TurnArtifactSource::ToolMutation,
276 );
277 reference.change = Some(change);
278 if change != FileChangeKind::Deleted {
279 (reference.size, reference.revision) = written_facts(entry);
280 }
281 reference.restore_snapshot_id = restore_snapshot_id.clone();
282 refs.push(reference);
283 }
284 for entry in mutation
285 .get("renames")
286 .and_then(Value::as_array)
287 .into_iter()
288 .flatten()
289 {
290 let confine = |key: &str| {
291 entry
292 .get(key)
293 .and_then(Value::as_str)
294 .and_then(|raw| confined_workspace_path(context.workspace_roots, raw))
295 };
296 let (Some(from), Some(to)) = (confine("from"), confine("to")) else {
297 continue;
298 };
299 let mut reference = base(
300 file_artifact_id(&to),
301 TurnArtifactKind::File,
302 to,
303 TurnArtifactSource::ToolMutation,
304 );
305 reference.change = Some(FileChangeKind::Renamed);
306 reference.previous_path = Some(from);
307 (reference.size, reference.revision) = written_facts(entry);
308 reference.restore_snapshot_id = restore_snapshot_id.clone();
309 refs.push(reference);
310 }
311 }
312
313 if let (Some(artifact_id), Some(session_id), Some(path)) = (
314 metadata
315 .get("artifact_id")
316 .and_then(Value::as_str)
317 .filter(|id| is_safe_artifact_id(id)),
318 metadata
319 .get("artifact_session_id")
320 .and_then(Value::as_str)
321 .filter(|id| codewhale_runtime::artifacts::is_valid_session_id(id)),
322 metadata
323 .get("artifact_relative_path")
324 .and_then(Value::as_str)
325 .and_then(confined_session_artifact_path),
326 ) {
327 let mut reference = base(
328 artifact_id.to_owned(),
329 TurnArtifactKind::ToolOutput,
330 path,
331 TurnArtifactSource::ToolOutputSpill,
332 );
333 reference.session_id = Some(session_id.to_owned());
334 reference.size = metadata.get("artifact_byte_size").and_then(Value::as_u64);
335 reference.revision = metadata
336 .get("artifact_digest")
337 .and_then(Value::as_str)
338 .filter(|digest| is_sha256_hex(digest))
339 .map(str::to_owned);
340 refs.push(reference);
341 }
342
343 for media in metadata
344 .get("tool_media")
345 .and_then(Value::as_array)
346 .into_iter()
347 .flatten()
348 {
349 let Some(handle) = media
350 .get("artifact_id")
351 .and_then(Value::as_str)
352 .filter(|id| id.strip_prefix("art_image_").is_some_and(is_sha256_hex))
353 else {
354 continue;
355 };
356 let Some(session_id) = media
357 .get("session_id")
358 .and_then(Value::as_str)
359 .filter(|id| codewhale_runtime::artifacts::is_valid_session_id(id))
360 else {
361 continue;
362 };
363 let mut reference = base(
364 handle.to_owned(),
365 TurnArtifactKind::Media,
366 format!(
367 "{}/{handle}.image",
368 codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME
369 ),
370 TurnArtifactSource::ToolMedia,
371 );
372 reference.session_id = Some(session_id.to_owned());
373 reference.size = media.get("byte_size").and_then(Value::as_u64);
374 reference.revision = media
375 .get("sha256")
376 .and_then(Value::as_str)
377 .filter(|digest| is_sha256_hex(digest))
378 .map(str::to_owned);
379 reference.content_type = media
380 .get("media_type")
381 .and_then(Value::as_str)
382 .map(str::to_owned);
383 refs.push(reference);
384 }
385
386 refs.truncate(MAX_ITEM_ARTIFACTS);
387 refs
388 }
389
390 /// The legacy `artifact_refs: Vec<PathBuf>` projection.
391 ///
392 /// Clients pinned to the older contract read these as workspace-relative
393 /// file paths (the desktop Preview does), so only existing workspace files
394 /// belong here: never a spill or media path, never a deleted file.
395 pub fn legacy_artifact_refs(refs: &[TurnArtifactRef]) -> Vec<PathBuf> {
396 let mut paths: Vec<PathBuf> = Vec::new();
397 for reference in refs {
398 if reference.kind != TurnArtifactKind::File
399 || reference.change == Some(FileChangeKind::Deleted)
400 {
401 continue;
402 }
403 let path = PathBuf::from(&reference.path);
404 if !paths.contains(&path) {
405 paths.push(path);
406 }
407 }
408 paths
409 }
410
411 /// Ceiling on a turn's aggregate. The cut is reported, never silent.
412 pub const MAX_TURN_ARTIFACTS: usize = 1_000;
413
414 /// Where the turn's workspace-level accounting stands.
415 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
416 #[serde(rename_all = "snake_case")]
417 pub enum TurnWorkspaceState {
418 /// The turn ended; the post-turn snapshot or its diff is still running.
419 /// `artifacts` holds the item-derived refs until `turn.artifacts` lands.
420 Pending,
421 /// The pre/post snapshot delta is merged into `artifacts`.
422 Settled,
423 /// No delta will come; `reason` says why. `artifacts` holds what the
424 /// tool receipts recorded.
425 Unavailable,
426 }
427
428 /// Why a turn has no workspace delta.
429 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
430 #[serde(rename_all = "snake_case")]
431 pub enum TurnWorkspaceReason {
432 SnapshotsDisabled,
433 WorkspaceTooLarge,
434 TooManyFiles,
435 UnsafeLocation,
436 SnapshotFailed,
437 /// The turn ran no snapshot pair: a compaction or purge operation, or a
438 /// turn that ended before the engine reported one.
439 NotCaptured,
440 /// The Runtime restarted before the delta settled.
441 RuntimeRestarted,
442 /// The snapshots exist but diffing them failed.
443 DeltaFailed,
444 }
445
446 /// The workspace half of a turn's artifact accounting.
447 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
448 pub struct TurnWorkspaceArtifacts {
449 pub state: TurnWorkspaceState,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub reason: Option<TurnWorkspaceReason>,
452 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub pre_turn_snapshot_id: Option<String>,
454 #[serde(default, skip_serializing_if = "Option::is_none")]
455 pub post_turn_snapshot_id: Option<String>,
456 /// The aggregate was cut at `MAX_TURN_ARTIFACTS` (or the delta at its
457 /// own bound); `omitted` counts what is not listed.
458 #[serde(default)]
459 pub truncated: bool,
460 #[serde(default)]
461 pub omitted: u64,
462 }
463
464 impl TurnWorkspaceArtifacts {
465 pub fn unavailable(reason: TurnWorkspaceReason) -> Self {
466 Self {
467 state: TurnWorkspaceState::Unavailable,
468 reason: Some(reason),
469 pre_turn_snapshot_id: None,
470 post_turn_snapshot_id: None,
471 truncated: false,
472 omitted: 0,
473 }
474 }
475
476 pub fn pending(pre_turn_snapshot_id: String) -> Self {
477 Self {
478 state: TurnWorkspaceState::Pending,
479 reason: None,
480 pre_turn_snapshot_id: Some(pre_turn_snapshot_id),
481 post_turn_snapshot_id: None,
482 truncated: false,
483 omitted: 0,
484 }
485 }
486 }
487
488 /// A settled workspace delta, ready to merge.
489 pub struct WorkspaceDelta {
490 pub refs: Vec<TurnArtifactRef>,
491 /// Item-reported paths that either snapshot contains. An item path in
492 /// neither snapshot is invisible to them (excluded or ignored), so the
493 /// delta's silence about it proves nothing and its item ref is kept.
494 pub tracked_item_paths: std::collections::HashSet<String>,
495 pub truncated: bool,
496 pub omitted: u64,
497 }
498
499 /// Convert a snapshot delta into turn refs. `restore_snapshot_id` is the
500 /// pre-turn restore point recorded on the turn, which file-revert accepts
501 /// for this thread.
502 pub fn delta_refs(
503 delta: &codewhale_snapshot::SnapshotDelta,
504 restore_snapshot_id: Option<&str>,
505 recorded_at: DateTime<Utc>,
506 ) -> Vec<TurnArtifactRef> {
507 use codewhale_snapshot::DeltaChange;
508 delta
509 .entries
510 .iter()
511 .map(|entry| TurnArtifactRef {
512 id: file_artifact_id(&entry.path),
513 kind: TurnArtifactKind::File,
514 path: entry.path.clone(),
515 change: Some(match entry.change {
516 DeltaChange::Created => FileChangeKind::Created,
517 DeltaChange::Updated => FileChangeKind::Updated,
518 DeltaChange::Deleted => FileChangeKind::Deleted,
519 DeltaChange::Renamed => FileChangeKind::Renamed,
520 }),
521 previous_path: entry.previous_path.clone(),
522 size: entry.size,
523 revision: entry.sha256.clone(),
524 content_type: None,
525 session_id: None,
526 item_id: None,
527 tool_call_id: None,
528 tool_name: None,
529 source: TurnArtifactSource::WorkspaceChangedDuringTurn,
530 restore_snapshot_id: restore_snapshot_id.map(str::to_owned),
531 recorded_at,
532 })
533 .collect()
534 }
535
536 /// The merged turn aggregate.
537 pub struct MergedTurnArtifacts {
538 pub artifacts: Vec<TurnArtifactRef>,
539 pub truncated: bool,
540 pub omitted: u64,
541 }
542
543 /// Fold one item file ref into the per-path net change.
544 fn compose_file(
545 files: &mut std::collections::HashMap<String, TurnArtifactRef>,
546 next: &TurnArtifactRef,
547 ) {
548 let mut merged = next.clone();
549 if next.change == Some(FileChangeKind::Renamed) {
550 let source = next
551 .previous_path
552 .as_ref()
553 .and_then(|previous| files.remove(previous));
554 if let Some(source) = source {
555 merged.restore_snapshot_id = source.restore_snapshot_id.or(merged.restore_snapshot_id);
556 match source.change {
557 // A file this turn created and then moved is simply created.
558 Some(FileChangeKind::Created) => {
559 merged.change = Some(FileChangeKind::Created);
560 merged.previous_path = None;
561 }
562 // Renamed twice: the net rename is from the first origin.
563 Some(FileChangeKind::Renamed) => merged.previous_path = source.previous_path,
564 _ => {}
565 }
566 if merged.previous_path.as_deref() == Some(merged.path.as_str()) {
567 merged.change = Some(FileChangeKind::Updated);
568 merged.previous_path = None;
569 }
570 }
571 files.insert(merged.path.clone(), merged);
572 return;
573 }
574 let Some(previous) = files.remove(&next.path) else {
575 files.insert(merged.path.clone(), merged);
576 return;
577 };
578 merged.restore_snapshot_id = previous
579 .restore_snapshot_id
580 .clone()
581 .or(merged.restore_snapshot_id);
582 match (previous.change, next.change) {
583 // Created then deleted within the turn: nothing is left to show.
584 (Some(FileChangeKind::Created), Some(FileChangeKind::Deleted)) => return,
585 (Some(FileChangeKind::Created), _) => merged.change = Some(FileChangeKind::Created),
586 (Some(FileChangeKind::Renamed), Some(FileChangeKind::Deleted)) => {
587 // The file moved and then went away: its origin is what is gone.
588 let origin = previous.previous_path.clone().unwrap_or(previous.path);
589 merged.id = file_artifact_id(&origin);
590 merged.path = origin;
591 merged.previous_path = None;
592 }
593 (Some(FileChangeKind::Renamed), _) => {
594 merged.change = Some(FileChangeKind::Renamed);
595 merged.previous_path = previous.previous_path;
596 }
597 // Deleted then written again: the file existed before and still does.
598 (Some(FileChangeKind::Deleted), Some(FileChangeKind::Created)) => {
599 merged.change = Some(FileChangeKind::Updated);
600 }
601 _ => {}
602 }
603 files.insert(merged.path.clone(), merged);
604 }
605
606 /// The one place a turn's aggregate is computed.
607 ///
608 /// Items are the authority for what each tool call produced. Tool output and
609 /// media refs are always kept. File refs compose by item order (last writer
610 /// wins; created+deleted drops, created+updated stays created, a rename
611 /// folds its origin). When a settled `delta` exists it is authoritative for
612 /// the net workspace change, size and revision of every path the snapshots
613 /// can see; item provenance is copied onto the delta ref for the same path,
614 /// and an item path the delta omits although the snapshots track it netted
615 /// to no change and is dropped. Most recent first; capped.
616 pub fn merge_turn_artifacts<'a>(
617 item_refs: impl IntoIterator<Item = &'a TurnArtifactRef>,
618 delta: Option<&WorkspaceDelta>,
619 ) -> MergedTurnArtifacts {
620 let mut outputs: Vec<TurnArtifactRef> = Vec::new();
621 let mut files = std::collections::HashMap::new();
622 for reference in item_refs {
623 if reference.kind == TurnArtifactKind::File {
624 compose_file(&mut files, reference);
625 } else {
626 outputs.retain(|existing| existing.id != reference.id);
627 outputs.push(reference.clone());
628 }
629 }
630 let (mut truncated, mut omitted) = (false, 0);
631 let mut artifacts = outputs;
632 match delta {
633 Some(delta) => {
634 truncated = delta.truncated;
635 omitted = delta.omitted;
636 for mut reference in delta.refs.iter().cloned() {
637 if let Some(item) = files.remove(&reference.path) {
638 reference.item_id = item.item_id;
639 reference.tool_call_id = item.tool_call_id;
640 reference.tool_name = item.tool_name;
641 reference.source = TurnArtifactSource::ToolMutation;
642 reference.recorded_at = item.recorded_at;
643 reference.restore_snapshot_id =
644 reference.restore_snapshot_id.or(item.restore_snapshot_id);
645 }
646 artifacts.push(reference);
647 }
648 artifacts.extend(
649 files
650 .into_values()
651 .filter(|item| !delta.tracked_item_paths.contains(&item.path)),
652 );
653 }
654 None => artifacts.extend(files.into_values()),
655 }
656 artifacts.sort_by(|left, right| {
657 right
658 .recorded_at
659 .cmp(&left.recorded_at)
660 .then_with(|| left.path.cmp(&right.path))
661 });
662 if artifacts.len() > MAX_TURN_ARTIFACTS {
663 truncated = true;
664 omitted += (artifacts.len() - MAX_TURN_ARTIFACTS) as u64;
665 artifacts.truncate(MAX_TURN_ARTIFACTS);
666 }
667 MergedTurnArtifacts {
668 artifacts,
669 truncated,
670 omitted,
671 }
672 }
673
674 #[cfg(test)]
675 mod tests {
676 use super::*;
677 use serde_json::json;
678
679 const SNAPSHOT: &str = "0123456789abcdef0123456789abcdef01234567";
680
681 fn context<'a>(workspace: &'a [PathBuf], restore: Option<&'a str>) -> ToolArtifactContext<'a> {
682 ToolArtifactContext {
683 item_id: "item_1",
684 tool_call_id: "call_1",
685 tool_name: "apply_patch",
686 workspace_roots: workspace,
687 restore_snapshot_id: restore,
688 recorded_at: Utc::now(),
689 }
690 }
691
692 #[test]
693 fn mutation_receipt_yields_confined_file_refs_with_written_facts() {
694 let workspace = tempfile::tempdir().unwrap();
695 let digest = codewhale_runtime::hashing::sha256_hex(b"new\n");
696 let absolute = workspace.path().join("src/abs.rs");
697 let metadata = json!({
698 "mutation": {
699 "files": [
700 { "path": "src/lib.rs", "outcome": "updated", "size": 4, "sha256": digest },
701 { "path": absolute.to_str().unwrap(), "outcome": "created", "size": 4, "sha256": digest },
702 { "path": "gone.txt", "outcome": "deleted", "size": 9, "sha256": digest },
703 // Forged or unconfined paths never become refs.
704 { "path": "../escape.txt", "outcome": "created" },
705 { "path": "/etc/passwd", "outcome": "updated" },
706 { "path": ".git/config", "outcome": "updated" },
707 { "path": "odd.txt", "outcome": "exploded" },
708 { "path": "bad-digest.txt", "outcome": "created", "size": 1, "sha256": "sha256:nothex" }
709 ],
710 "renames": [{ "from": "old.txt", "to": "new.txt", "size": 4, "sha256": digest }]
711 },
712 });
713 let refs = artifact_refs_from_tool_metadata(
714 &metadata,
715 &context(&[workspace.path().to_path_buf()], Some(SNAPSHOT)),
716 );
717 let paths: Vec<&str> = refs.iter().map(|r| r.path.as_str()).collect();
718 assert_eq!(
719 paths,
720 [
721 "src/lib.rs",
722 "src/abs.rs",
723 "gone.txt",
724 "bad-digest.txt",
725 "new.txt"
726 ]
727 );
728 let lib = &refs[0];
729 assert_eq!(lib.kind, TurnArtifactKind::File);
730 assert_eq!(lib.id, file_artifact_id("src/lib.rs"));
731 assert_eq!(lib.change, Some(FileChangeKind::Updated));
732 assert_eq!(lib.size, Some(4));
733 assert_eq!(lib.revision.as_deref(), Some(digest.as_str()));
734 assert_eq!(lib.source, TurnArtifactSource::ToolMutation);
735 assert_eq!(lib.restore_snapshot_id.as_deref(), Some(SNAPSHOT));
736 assert_eq!(lib.item_id.as_deref(), Some("item_1"));
737 assert_eq!(lib.tool_call_id.as_deref(), Some("call_1"));
738 // Deleted entries carry no size or revision even if a receipt did.
739 assert_eq!(refs[2].change, Some(FileChangeKind::Deleted));
740 assert_eq!((refs[2].size, refs[2].revision.as_deref()), (None, None));
741 // A malformed digest is dropped, not passed through.
742 assert_eq!(refs[3].revision, None);
743 let renamed = &refs[4];
744 assert_eq!(renamed.change, Some(FileChangeKind::Renamed));
745 assert_eq!(renamed.previous_path.as_deref(), Some("old.txt"));
746
747 // The legacy projection holds only live workspace paths.
748 assert_eq!(
749 legacy_artifact_refs(&refs),
750 ["src/lib.rs", "src/abs.rs", "bad-digest.txt", "new.txt"]
751 .map(PathBuf::from)
752 .to_vec()
753 );
754 }
755
756 #[test]
757 fn restore_point_comes_only_from_the_recorded_receipt() {
758 let workspace = tempfile::tempdir().unwrap();
759 // A tool cannot name its own restore point: result metadata that
760 // claims one is ignored (#6621).
761 let metadata = json!({
762 "mutation": { "files": [{ "path": "a.txt", "outcome": "created" }] },
763 "restore_snapshot_id": SNAPSHOT,
764 "restore_snapshot_session_id": "sess-1",
765 });
766 let restore = |recorded| {
767 artifact_refs_from_tool_metadata(
768 &metadata,
769 &context(&[workspace.path().to_path_buf()], recorded),
770 )[0]
771 .restore_snapshot_id
772 .clone()
773 };
774 let recorded = "fedcba9876543210fedcba9876543210fedcba98";
775 assert_eq!(restore(Some(recorded)).as_deref(), Some(recorded));
776 assert_eq!(restore(None), None);
777 assert_eq!(restore(Some("not-a-snapshot")), None);
778 }
779
780 #[test]
781 fn spill_and_media_receipts_yield_session_refs_and_forgeries_yield_none() {
782 let workspace = tempfile::tempdir().unwrap();
783 let digest = codewhale_runtime::hashing::sha256_hex(b"output");
784 let handle = format!("art_image_{digest}");
785 let metadata = json!({
786 "artifact_id": "art_call_1",
787 "artifact_session_id": "sess-abc",
788 "artifact_relative_path": "artifacts/art_call_1.txt",
789 "artifact_byte_size": 6,
790 "artifact_digest": digest,
791 "tool_media": [
792 { "session_id": "sess-abc", "artifact_id": handle, "media_type": "image/png",
793 "byte_size": 10, "sha256": digest },
794 { "session_id": "../x", "artifact_id": handle },
795 { "session_id": "sess-abc", "artifact_id": "art_image_short" }
796 ],
797 });
798 let refs = artifact_refs_from_tool_metadata(
799 &metadata,
800 &context(&[workspace.path().to_path_buf()], None),
801 );
802 assert_eq!(refs.len(), 2, "{refs:?}");
803 let spill = &refs[0];
804 assert_eq!(spill.kind, TurnArtifactKind::ToolOutput);
805 assert_eq!(spill.id, "art_call_1");
806 assert_eq!(spill.path, "artifacts/art_call_1.txt");
807 assert_eq!(spill.session_id.as_deref(), Some("sess-abc"));
808 assert_eq!(spill.size, Some(6));
809 assert_eq!(spill.revision.as_deref(), Some(digest.as_str()));
810 assert_eq!(spill.source, TurnArtifactSource::ToolOutputSpill);
811 let media = &refs[1];
812 assert_eq!(media.kind, TurnArtifactKind::Media);
813 assert_eq!(media.path, format!("artifacts/{handle}.image"));
814 assert_eq!(media.content_type.as_deref(), Some("image/png"));
815 assert!(legacy_artifact_refs(&refs).is_empty());
816
817 for (key, forged) in [
818 ("artifact_relative_path", json!("/abs/artifacts/x.txt")),
819 ("artifact_relative_path", json!("artifacts/../../escape")),
820 ("artifact_relative_path", json!("elsewhere/x.txt")),
821 ("artifact_session_id", json!("../other")),
822 ("artifact_id", json!("not-an-artifact")),
823 ] {
824 let mut value = metadata.clone();
825 value[key] = forged.clone();
826 value.as_object_mut().unwrap().remove("tool_media");
827 assert!(
828 artifact_refs_from_tool_metadata(
829 &value,
830 &context(&[workspace.path().to_path_buf()], None)
831 )
832 .is_empty(),
833 "{key}={forged} must not become a ref"
834 );
835 }
836 }
837
838 fn file_ref(path: &str, change: FileChangeKind, revision: &str, at: i64) -> TurnArtifactRef {
839 TurnArtifactRef {
840 id: file_artifact_id(path),
841 kind: TurnArtifactKind::File,
842 path: path.to_string(),
843 change: Some(change),
844 previous_path: None,
845 size: Some(revision.len() as u64),
846 revision: Some(revision.to_string()),
847 content_type: None,
848 session_id: None,
849 item_id: Some(format!("item_{at}")),
850 tool_call_id: Some(format!("call_{at}")),
851 tool_name: Some("write".to_string()),
852 source: TurnArtifactSource::ToolMutation,
853 restore_snapshot_id: Some(format!("snap_{at}")),
854 recorded_at: DateTime::from_timestamp(at, 0).unwrap(),
855 }
856 }
857
858 fn by_path(merged: &MergedTurnArtifacts) -> Vec<(&str, Option<FileChangeKind>, Option<&str>)> {
859 let mut rows: Vec<_> = merged
860 .artifacts
861 .iter()
862 .map(|r| (r.path.as_str(), r.change, r.revision.as_deref()))
863 .collect();
864 rows.sort_by_key(|row| row.0);
865 rows
866 }
867
868 #[test]
869 fn item_refs_compose_by_order_without_a_delta() {
870 let mut renamed = file_ref("b.txt", FileChangeKind::Renamed, "r_b", 6);
871 renamed.previous_path = Some("a.txt".into());
872 let items = vec![
873 file_ref("new.txt", FileChangeKind::Created, "r1", 1),
874 file_ref("new.txt", FileChangeKind::Updated, "r2", 2),
875 file_ref("tmp.txt", FileChangeKind::Created, "t1", 3),
876 file_ref("tmp.txt", FileChangeKind::Deleted, "t2", 4),
877 file_ref("old.txt", FileChangeKind::Updated, "o1", 5),
878 file_ref("old.txt", FileChangeKind::Deleted, "o2", 5),
879 renamed,
880 ];
881 let merged = merge_turn_artifacts(&items, None);
882 assert_eq!(
883 by_path(&merged),
884 vec![
885 ("b.txt", Some(FileChangeKind::Renamed), Some("r_b")),
886 ("new.txt", Some(FileChangeKind::Created), Some("r2")),
887 ("old.txt", Some(FileChangeKind::Deleted), Some("o2")),
888 ]
889 );
890 let created = merged
891 .artifacts
892 .iter()
893 .find(|r| r.path == "new.txt")
894 .unwrap();
895 // The earliest restore point survives; provenance is the last writer.
896 assert_eq!(created.restore_snapshot_id.as_deref(), Some("snap_1"));
897 assert_eq!(created.item_id.as_deref(), Some("item_2"));
898 // Most recent first.
899 assert_eq!(merged.artifacts[0].path, "b.txt");
900 assert!(!merged.truncated);
901 }
902
903 #[test]
904 fn a_settled_delta_is_authoritative_for_visible_paths() {
905 let items = vec![
906 file_ref("edited.txt", FileChangeKind::Updated, "item_rev", 1),
907 // Written and then restored to its original bytes: net zero.
908 file_ref("reverted.txt", FileChangeKind::Updated, "x", 2),
909 // Under an excluded directory: the snapshots cannot see it.
910 file_ref("dist/app.js", FileChangeKind::Created, "js", 3),
911 ];
912 let mut shell = file_ref("out.md", FileChangeKind::Created, "shell_rev", 9);
913 shell.source = TurnArtifactSource::WorkspaceChangedDuringTurn;
914 shell.item_id = None;
915 shell.tool_call_id = None;
916 shell.tool_name = None;
917 let mut edited = file_ref("edited.txt", FileChangeKind::Updated, "delta_rev", 9);
918 edited.source = TurnArtifactSource::WorkspaceChangedDuringTurn;
919 edited.restore_snapshot_id = Some("pre".into());
920 let delta = WorkspaceDelta {
921 refs: vec![edited, shell],
922 tracked_item_paths: ["edited.txt", "reverted.txt"].map(String::from).into(),
923 truncated: false,
924 omitted: 0,
925 };
926 let merged = merge_turn_artifacts(&items, Some(&delta));
927 assert_eq!(
928 by_path(&merged),
929 vec![
930 ("dist/app.js", Some(FileChangeKind::Created), Some("js")),
931 (
932 "edited.txt",
933 Some(FileChangeKind::Updated),
934 Some("delta_rev")
935 ),
936 ("out.md", Some(FileChangeKind::Created), Some("shell_rev")),
937 ]
938 );
939 let edited = merged
940 .artifacts
941 .iter()
942 .find(|r| r.path == "edited.txt")
943 .unwrap();
944 assert_eq!(edited.source, TurnArtifactSource::ToolMutation);
945 assert_eq!(edited.item_id.as_deref(), Some("item_1"));
946 assert_eq!(edited.restore_snapshot_id.as_deref(), Some("pre"));
947 let shell = merged
948 .artifacts
949 .iter()
950 .find(|r| r.path == "out.md")
951 .unwrap();
952 assert_eq!(shell.source, TurnArtifactSource::WorkspaceChangedDuringTurn);
953 assert_eq!(shell.item_id, None);
954 }
955
956 #[test]
957 fn the_aggregate_is_capped_and_says_so() {
958 let items: Vec<_> = (0..(MAX_TURN_ARTIFACTS as i64 + 5))
959 .map(|n| file_ref(&format!("f{n}.txt"), FileChangeKind::Created, "r", n))
960 .collect();
961 let merged = merge_turn_artifacts(&items, None);
962 assert_eq!(merged.artifacts.len(), MAX_TURN_ARTIFACTS);
963 assert!(merged.truncated);
964 assert_eq!(merged.omitted, 5);
965 // The newest writes are the ones kept.
966 assert_eq!(
967 merged.artifacts[0].path,
968 format!("f{}.txt", MAX_TURN_ARTIFACTS + 4)
969 );
970 }
971 }
972
972 lines RUST