返回 CodeWhale
turn_artifacts.rs
根目录 / crates / app-server / src / runtime_api / turn_artifacts.rs
1 //! Turn artifact routes (#6653): what a runtime turn produced.
2 //!
3 //! The authority is the runtime store's turn record and its items. Nothing
4 //! is scanned: every reference was recorded where its bytes were written,
5 //! and the workspace delta comes from the engine's own snapshot pair. Reads
6 //! go through the same confined openers as the workspace file and session
7 //! artifact routes; there is no second store.
8
9 use std::path::Path as FsPath;
10
11 use axum::Json;
12 use axum::extract::{Path, Query, State};
13 use serde::{Deserialize, Serialize};
14
15 use super::sessions::{ArtifactAuthority, resolve_session_artifact};
16 use super::workspace::{
17 ConfinedFileBytes, FILE_SERVE_MAX_BYTES, canonical_workspace, encode_window,
18 open_confined_file, parse_read_window, precheck_file_target, read_confined_bytes, read_window,
19 relative_request_path,
20 };
21 use super::{ApiError, RuntimeApiState, map_thread_err};
22 use codewhale_engine::runtime_threads::{
23 FileChangeKind, RuntimeStoreRecordFailure, RuntimeStoreRecordKind, TurnArtifactKind,
24 TurnArtifactRef, TurnItemLifecycleStatus, TurnWorkspaceArtifacts, manager::CallWorkspaceSpan,
25 manager::TurnArtifactsView,
26 };
27
28 pub(super) async fn list_turn_artifacts(
29 State(state): State<RuntimeApiState>,
30 Path((thread_id, turn_id)): Path<(String, String)>,
31 ) -> Result<Json<TurnArtifactsView>, ApiError> {
32 load_view(&state, &thread_id, &turn_id).await.map(Json)
33 }
34
35 async fn load_view(
36 state: &RuntimeApiState,
37 thread_id: &str,
38 turn_id: &str,
39 ) -> Result<TurnArtifactsView, ApiError> {
40 state
41 .runtime_threads
42 .turn_artifacts(thread_id, turn_id)
43 .await
44 .map_err(map_thread_err)?
45 .ok_or_else(|| ApiError::not_found(format!("turn '{turn_id}' not found in this thread")))
46 }
47
48 #[derive(Deserialize)]
49 #[serde(deny_unknown_fields)]
50 pub(super) struct TurnArtifactReadQuery {
51 offset: Option<usize>,
52 limit: Option<usize>,
53 /// Read an intermediate revision one of the turn's items recorded,
54 /// instead of the reference's final one.
55 revision: Option<String>,
56 }
57
58 #[derive(Debug, Serialize)]
59 pub(super) struct TurnArtifactReadResponse {
60 artifact: TurnArtifactRef,
61 /// `workspace` (the live file), `snapshot` (the turn's post-turn
62 /// snapshot), or `session_artifact` (the session artifact directory).
63 source: &'static str,
64 /// Whether the workspace still holds exactly these bytes. `null` for a
65 /// session artifact, or a file reference with no recorded revision.
66 current: Option<bool>,
67 size: u64,
68 /// SHA-256 of the whole content served.
69 revision: String,
70 offset: usize,
71 bytes: usize,
72 truncated: bool,
73 encoding: &'static str,
74 content: String,
75 }
76
77 pub(super) async fn read_turn_artifact(
78 State(state): State<RuntimeApiState>,
79 Path((thread_id, turn_id, artifact_id)): Path<(String, String, String)>,
80 Query(query): Query<TurnArtifactReadQuery>,
81 ) -> Result<Json<TurnArtifactReadResponse>, ApiError> {
82 let (offset, limit) = parse_read_window(query.offset, query.limit)?;
83 let view = load_view(&state, &thread_id, &turn_id).await?;
84 let artifact = select_reference(&view, &artifact_id, query.revision.as_deref())?;
85 let workspace = view.workspace.clone();
86 let thread_workspace = view.thread_workspace.clone();
87 #[cfg(any(test, feature = "test-support"))]
88 let env_ticket = codewhale_engine::test_support::env_scope_ticket();
89 tokio::task::spawn_blocking(move || {
90 #[cfg(any(test, feature = "test-support"))]
91 let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
92 let (source, current, read) = match artifact.kind {
93 TurnArtifactKind::File => {
94 read_file_artifact(&thread_workspace, workspace.as_ref(), &artifact)?
95 }
96 TurnArtifactKind::ToolOutput | TurnArtifactKind::Media => {
97 let session_id = artifact
98 .session_id
99 .as_deref()
100 .ok_or_else(|| ApiError::internal("artifact reference has no session"))?;
101 let root = codewhale_runtime::artifacts::artifact_sessions_root()
102 .ok_or_else(|| ApiError::internal("session artifact root is unavailable"))?;
103 let resolved = resolve_session_artifact(
104 &root,
105 session_id,
106 &artifact.id,
107 ArtifactAuthority::TurnRef {
108 path: &artifact.path,
109 revision: artifact.revision.as_deref(),
110 },
111 )?;
112 ("session_artifact", None, resolved.read)
113 }
114 };
115 let (window, truncated) = read_window(&read.bytes, offset, limit);
116 let (encoding, content) = encode_window(window);
117 Ok(TurnArtifactReadResponse {
118 artifact,
119 source,
120 current,
121 size: read.size,
122 revision: read.revision,
123 offset: offset.min(read.bytes.len()),
124 bytes: window.len(),
125 truncated,
126 encoding,
127 content,
128 })
129 })
130 .await
131 .map_err(|_| ApiError::internal("turn artifact read failed"))?
132 .map(Json)
133 }
134
135 /// The reference to serve: the turn aggregate's, or an item's when the turn
136 /// aggregate no longer lists it (a file written and then deleted still has
137 /// item-level history). `?revision=` selects the item ref that recorded
138 /// exactly that revision.
139 fn select_reference(
140 view: &TurnArtifactsView,
141 artifact_id: &str,
142 revision: Option<&str>,
143 ) -> Result<TurnArtifactRef, ApiError> {
144 let aggregate = view.artifacts.iter().find(|r| r.id == artifact_id);
145 let items = view
146 .item_artifacts
147 .iter()
148 .rev()
149 .filter(|r| r.id == artifact_id);
150 let Some(wanted) = revision.map(|revision| revision.trim().to_ascii_lowercase()) else {
151 return aggregate
152 .or_else(|| {
153 view.item_artifacts
154 .iter()
155 .rev()
156 .find(|r| r.id == artifact_id)
157 })
158 .cloned()
159 .ok_or_else(|| ApiError::not_found("artifact not found in this turn"));
160 };
161 aggregate
162 .into_iter()
163 .chain(items)
164 .find(|r| r.revision.as_deref() == Some(wanted.as_str()))
165 .cloned()
166 .ok_or_else(|| ApiError::not_found("this turn recorded no such revision of the artifact"))
167 }
168
169 /// Serve a file reference: from the workspace when it still holds the
170 /// recorded revision, otherwise from the turn's post-turn snapshot,
171 /// otherwise a conflict naming what the workspace holds now.
172 fn read_file_artifact(
173 thread_workspace: &FsPath,
174 workspace: Option<&TurnWorkspaceArtifacts>,
175 artifact: &TurnArtifactRef,
176 ) -> Result<(&'static str, Option<bool>, ConfinedFileBytes), ApiError> {
177 if artifact.change == Some(FileChangeKind::Deleted) {
178 return Err(ApiError::gone(
179 "this turn deleted the file; restore its prior content with file-revert and the reference's restore_snapshot_id",
180 ));
181 }
182 if artifact
183 .size
184 .is_some_and(|size| size > FILE_SERVE_MAX_BYTES)
185 {
186 return Err(ApiError::payload_too_large(format!(
187 "file is larger than the {FILE_SERVE_MAX_BYTES}-byte serving limit"
188 )));
189 }
190 let relative = relative_request_path(&artifact.path, false)?;
191 let root = canonical_workspace(thread_workspace)?;
192 let live = match precheck_file_target(&root, &relative)? {
193 Some(_) => Some(read_confined_bytes(&open_confined_file(
194 &root, &relative, false,
195 )?)?),
196 None => None,
197 };
198 let Some(wanted) = artifact.revision.as_deref() else {
199 // No recorded revision (an older receipt): all that can be served
200 // is the live file, and whether it is the turn's version is unknown.
201 return live
202 .map(|read| ("workspace", None, read))
203 .ok_or_else(|| ApiError::gone("the file is no longer in the workspace"));
204 };
205 if let Some(read) = live.as_ref()
206 && read.revision == wanted
207 {
208 return Ok(("workspace", Some(true), live.expect("checked above")));
209 }
210 if let Some(post) = workspace.and_then(|w| w.post_turn_snapshot_id.as_deref())
211 && let Some(bytes) = read_snapshot_blob(&root, post, &artifact.path)?
212 {
213 let read = ConfinedFileBytes {
214 size: bytes.len() as u64,
215 revision: super::workspace::content_revision(&bytes),
216 modified: None,
217 bytes,
218 };
219 if read.revision == wanted {
220 return Ok(("snapshot", Some(false), read));
221 }
222 }
223 Err(ApiError::conflict(match live {
224 Some(read) => format!(
225 "this turn's revision is no longer in the workspace or the snapshot store; current revision is {}",
226 read.revision
227 ),
228 None => "this turn's revision is no longer in the workspace or the snapshot store; the file is gone".to_string(),
229 }))
230 }
231
232 fn read_snapshot_blob(
233 workspace: &FsPath,
234 snapshot_id: &str,
235 path: &str,
236 ) -> Result<Option<Vec<u8>>, ApiError> {
237 let Ok(id) = codewhale_snapshot::SnapshotId::parse(snapshot_id) else {
238 return Ok(None);
239 };
240 let Some(repo) = codewhale_snapshot::SnapshotRepo::open_existing(workspace)
241 .map_err(|error| ApiError::internal(format!("snapshot repo unavailable: {error}")))?
242 else {
243 return Ok(None);
244 };
245 match repo.read_blob(&id, path, FILE_SERVE_MAX_BYTES) {
246 Ok(bytes) => Ok(bytes),
247 Err(error) if error.kind() == std::io::ErrorKind::FileTooLarge => {
248 Err(ApiError::payload_too_large(format!(
249 "file is larger than the {FILE_SERVE_MAX_BYTES}-byte serving limit"
250 )))
251 }
252 // A pruned snapshot is not an error: the revision is just gone.
253 Err(error) => {
254 tracing::debug!(%error, "snapshot blob read failed");
255 Ok(None)
256 }
257 }
258 }
259
260 // ---------------------------------------------------------------------------
261 // One tool call's changes
262 // ---------------------------------------------------------------------------
263
264 /// Most files one call's change list holds. The list is cut here, never
265 /// silently; `truncated` says it was.
266 const DEFAULT_CALL_CHANGE_FILES: usize = 200;
267 /// Largest list a caller may ask for.
268 const MAX_CALL_CHANGE_FILES: usize = 1_000;
269 /// Largest patch served for one path. A longer one is cut at a char boundary
270 /// and flagged.
271 const MAX_CALL_CHANGE_PATCH_BYTES: usize = 64 * 1024;
272
273 #[derive(Debug, Deserialize)]
274 #[serde(deny_unknown_fields)]
275 pub(super) struct CallChangesQuery {
276 limit: Option<usize>,
277 }
278
279 /// How one path changed, in the vocabulary the turn artifact contract uses.
280 #[derive(Debug, Clone, Copy, Serialize)]
281 #[serde(rename_all = "snake_case")]
282 enum CallChangeKind {
283 Created,
284 Updated,
285 Deleted,
286 }
287
288 impl CallChangeKind {
289 /// git's own status letter. The diff runs with `--no-renames`, so a move
290 /// reads as a delete plus a create, and a type change (`T`) is an update.
291 fn from_status(status: char) -> Self {
292 match status {
293 'A' => Self::Created,
294 'D' => Self::Deleted,
295 _ => Self::Updated,
296 }
297 }
298 }
299
300 #[derive(Debug, Serialize)]
301 pub(super) struct CallChangeFile {
302 /// Workspace-relative with `/` separators, as git names it.
303 path: String,
304 change: CallChangeKind,
305 /// Lines added and removed; `null` for a binary file.
306 added: Option<u64>,
307 removed: Option<u64>,
308 /// Byte size and SHA-256 hex of the revision the span left, so a client
309 /// can send `expected_hash` to `file-revert`. Both `null` when the path
310 /// was deleted here, or is too large to read.
311 size: Option<u64>,
312 revision: Option<String>,
313 /// The restore point `POST /v1/threads/{id}/file-revert` accepts for this
314 /// path: the call's `tool:` receipt, which this thread owns.
315 restore_snapshot_id: Option<String>,
316 /// The patch between the span's two restore points. `null` when there is
317 /// nothing to render: a binary path, a change with no content delta, or a
318 /// patch git could not write.
319 diff: Option<String>,
320 /// Whether `diff` was cut at the serving bound.
321 diff_truncated: bool,
322 }
323
324 #[derive(Debug, Serialize)]
325 pub(super) struct CallChangesResponse {
326 thread_id: String,
327 turn_id: String,
328 tool_call_id: String,
329 tool_name: Option<String>,
330 /// `captured` when the call's two restore points exist and `files` is
331 /// authoritative; `pending` while its recorded item is active and the
332 /// pair is incomplete; `unavailable` after settlement, with `reason`.
333 state: &'static str,
334 reason: Option<&'static str>,
335 files: Vec<CallChangeFile>,
336 /// Whether `files` was cut at the request's `limit`. How many paths are
337 /// left off is not counted.
338 truncated: bool,
339 }
340
341 /// What one tool call changed, from the workspace restore points the engine
342 /// recorded around it.
343 ///
344 /// The per-call counterpart of the turn's aggregated artifacts: the engine
345 /// brackets every call that may write with a `tool:<call_id>` and a
346 /// `post-tool:<call_id>` receipt, so a file a shell command wrote is
347 /// attributable to that command and not only to the turn that ran it. Both
348 /// trees are read from the side repo; the work tree is never touched, so the
349 /// answer is what the call did rather than what the file holds now.
350 ///
351 /// The span is a time window, not attribution by cause: anything else that
352 /// wrote the same workspace between the two receipts is in it too, exactly as
353 /// the turn delta says. Snapshots exclude what they exclude (`node_modules/`,
354 /// `.gitignore` entries, binary and media extensions), and a path they never
355 /// track cannot appear here. A call the engine judged read-only has no
356 /// receipts at all and answers `call_not_bounded` after settlement. An active
357 /// item without a complete pair answers `pending`; a settled call whose closing
358 /// snapshot was lost answers `post_snapshot_missing`; one whose receipts name
359 /// trees the store no longer holds (pruned, or a store that is gone) answers
360 /// `snapshots_pruned`. All three are `unavailable` rather than an empty list,
361 /// which would read as "this call changed nothing".
362 pub(super) async fn list_call_changes(
363 State(state): State<RuntimeApiState>,
364 Path((thread_id, turn_id, tool_call_id)): Path<(String, String, String)>,
365 Query(query): Query<CallChangesQuery>,
366 ) -> Result<Json<CallChangesResponse>, ApiError> {
367 let limit = query.limit.unwrap_or(DEFAULT_CALL_CHANGE_FILES);
368 if !(1..=MAX_CALL_CHANGE_FILES).contains(&limit) {
369 return Err(ApiError::bad_request(format!(
370 "limit must be between 1 and {MAX_CALL_CHANGE_FILES}"
371 )));
372 }
373 let span = state
374 .runtime_threads
375 .turn_call_span(&thread_id, &turn_id, &tool_call_id)
376 .await
377 .map_err(|error| {
378 if RuntimeStoreRecordFailure::from_error(&error)
379 .is_some_and(|failure| failure.record_kind == RuntimeStoreRecordKind::Item)
380 {
381 ApiError::internal(error.to_string())
382 } else {
383 map_thread_err(error)
384 }
385 })?
386 .ok_or_else(|| {
387 ApiError::not_found(format!(
388 "no call '{tool_call_id}' is recorded on turn '{turn_id}' of this thread"
389 ))
390 })?;
391
392 let (pre, post) = match (
393 span.pre_tool_snapshot_id.clone(),
394 span.post_tool_snapshot_id.clone(),
395 ) {
396 (Some(pre), Some(post)) => (pre, post),
397 (pre, post) => {
398 if matches!(
399 span.item_status,
400 Some(TurnItemLifecycleStatus::Queued | TurnItemLifecycleStatus::InProgress)
401 ) {
402 return Ok(Json(empty_call_changes(&span, "pending", None)));
403 }
404 let reason = match (pre.is_some(), post.is_some()) {
405 (true, false) => "post_snapshot_missing",
406 (false, true) => "pre_snapshot_missing",
407 _ => "call_not_bounded",
408 };
409 return Ok(Json(empty_call_changes(&span, "unavailable", Some(reason))));
410 }
411 };
412
413 let workspace = span.thread_workspace.clone();
414 let restore_snapshot_id = Some(pre.clone());
415 // The side repo lives under the sealed test home; a blocking-pool thread
416 // is a foreign reader until it joins the test's env scope, and would
417 // otherwise resolve the isolated root and report every span pruned.
418 #[cfg(any(test, feature = "test-support"))]
419 let env_ticket = codewhale_engine::test_support::env_scope_ticket();
420 let read = tokio::task::spawn_blocking(move || {
421 #[cfg(any(test, feature = "test-support"))]
422 let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
423 call_span_files(
424 &workspace,
425 &pre,
426 &post,
427 restore_snapshot_id.as_deref(),
428 limit,
429 )
430 })
431 .await
432 .map_err(|_| ApiError::internal("call change read task failed"))??;
433
434 let read = match read {
435 CallSpanOutcome::Captured(read) => read,
436 // The receipt survived; the objects it names did not. Pruning is the
437 // store's own housekeeping, so this is a fact about the span, not an
438 // error a client should report as a failure — the paths the receipt
439 // recorded are still on the turn, and the caller keeps them.
440 CallSpanOutcome::Pruned => {
441 return Ok(Json(empty_call_changes(
442 &span,
443 "unavailable",
444 Some("snapshots_pruned"),
445 )));
446 }
447 };
448
449 Ok(Json(CallChangesResponse {
450 thread_id: span.thread_id,
451 turn_id: span.turn_id,
452 tool_call_id: span.tool_call_id,
453 tool_name: span.tool_name,
454 state: "captured",
455 reason: None,
456 files: read.files,
457 truncated: read.truncated,
458 }))
459 }
460
461 fn empty_call_changes(
462 span: &CallWorkspaceSpan,
463 state: &'static str,
464 reason: Option<&'static str>,
465 ) -> CallChangesResponse {
466 CallChangesResponse {
467 thread_id: span.thread_id.clone(),
468 turn_id: span.turn_id.clone(),
469 tool_call_id: span.tool_call_id.clone(),
470 tool_name: span.tool_name.clone(),
471 state,
472 reason,
473 files: Vec::new(),
474 truncated: false,
475 }
476 }
477
478 struct CallSpanFiles {
479 files: Vec<CallChangeFile>,
480 truncated: bool,
481 }
482
483 /// What reading one call's span produced.
484 enum CallSpanOutcome {
485 Captured(CallSpanFiles),
486 /// A tree the receipts name is no longer in the side repo — or there is
487 /// no side repo left at all. The store keeps only its newest snapshots
488 /// while the turn record that names them is durable, so an old turn's span
489 /// is regularly unrecoverable: a thing to report, not a failure to raise.
490 Pruned,
491 }
492
493 /// Turn one call's two restore points into what it changed: git's own status
494 /// and line counts for the pair, each surviving path's revision read from the
495 /// span's *end*, and the patch between the two trees.
496 fn call_span_files(
497 workspace: &FsPath,
498 pre_tree: &str,
499 post_tree: &str,
500 restore_snapshot_id: Option<&str>,
501 limit: usize,
502 ) -> Result<CallSpanOutcome, ApiError> {
503 let (Ok(pre), Ok(post)) = (
504 codewhale_snapshot::SnapshotId::parse(pre_tree),
505 codewhale_snapshot::SnapshotId::parse(post_tree),
506 ) else {
507 return Err(ApiError::internal(
508 "a recorded restore point is not a valid snapshot id",
509 ));
510 };
511 let Some(repo) = codewhale_snapshot::SnapshotRepo::open_existing(workspace)
512 .map_err(|error| ApiError::internal(format!("snapshot repo unavailable: {error}")))?
513 else {
514 // No store at all. Its receipts cannot be resolved any more than a
515 // pruned tree can, and reading a missing store is "absent" everywhere
516 // else in this module (`read_snapshot_blob`) — so this is the same
517 // answer, not a server failure a client could act on.
518 return Ok(CallSpanOutcome::Pruned);
519 };
520 // Asked before the diff: git's answer to a pruned object is a failure of
521 // the whole command, and a caller has to tell "these were pruned" apart
522 // from "this repo is broken".
523 let has_tree = |id: &codewhale_snapshot::SnapshotId| {
524 repo.has_tree(id)
525 .map_err(|error| ApiError::internal(format!("snapshot tree lookup failed: {error}")))
526 };
527 if !has_tree(&pre)? || !has_tree(&post)? {
528 return Ok(CallSpanOutcome::Pruned);
529 }
530 let (changes, truncated) = repo
531 .path_changes_between(&pre, &post, limit)
532 .map_err(|error| ApiError::internal(format!("snapshot diff failed: {error}")))?;
533 let mut files = Vec::with_capacity(changes.len());
534 for change in changes {
535 // A binary path has no line counts, and git's "Binary files differ"
536 // notice is not a patch a client can render: serve neither.
537 let binary = change.added.is_none() && change.removed.is_none();
538 // The revision is the span's own end, never the work tree: the file
539 // may have moved on since, and the digest a revert is checked against
540 // must be the one this change produced.
541 let (size, revision) = if change.status == 'D' {
542 (None, None)
543 } else {
544 match repo.read_blob(&post, &change.path, FILE_SERVE_MAX_BYTES) {
545 Ok(Some(bytes)) => (
546 Some(bytes.len() as u64),
547 Some(codewhale_runtime::hashing::sha256_hex(&bytes)),
548 ),
549 Ok(None) => (None, None),
550 Err(error) => {
551 tracing::debug!(path = %change.path, %error, "snapshot blob read failed");
552 (None, None)
553 }
554 }
555 };
556 let (diff, diff_truncated) = if binary {
557 (None, false)
558 } else {
559 match repo.patch_between(&pre, &post, &change.path, MAX_CALL_CHANGE_PATCH_BYTES) {
560 Ok((text, cut)) if !text.is_empty() => (Some(text), cut),
561 Ok(_) => (None, false),
562 Err(error) => {
563 tracing::debug!(path = %change.path, %error, "snapshot patch failed");
564 (None, false)
565 }
566 }
567 };
568 files.push(CallChangeFile {
569 path: change.path,
570 change: CallChangeKind::from_status(change.status),
571 added: change.added,
572 removed: change.removed,
573 size,
574 revision,
575 restore_snapshot_id: restore_snapshot_id.map(str::to_owned),
576 diff,
577 diff_truncated,
578 });
579 }
580 Ok(CallSpanOutcome::Captured(CallSpanFiles {
581 files,
582 truncated,
583 }))
584 }
585
585 lines RUST