返回 CodeWhale
workspace.rs
根目录 / crates / app-server / src / runtime_api / workspace.rs
1 use std::io::Read as _;
2 use std::path::{Component, Path as FsPath, PathBuf};
3
4 use axum::Json;
5 use axum::extract::{Query, State};
6 use axum::http::StatusCode;
7 use base64::Engine as _;
8 use serde::{Deserialize, Serialize};
9 use sha2::{Digest, Sha256};
10
11 use codewhale_dependencies::Git;
12 use codewhale_util::git_metadata::{GitHead, GitReadError, is_git_metadata_name, read_head};
13
14 use super::{ApiError, RuntimeApiState, map_thread_err};
15
16 #[derive(Deserialize)]
17 #[serde(deny_unknown_fields)]
18 pub(super) struct ThreadScopeQuery {
19 pub(super) thread_id: Option<String>,
20 }
21
22 pub(super) async fn scoped_workspace(
23 state: &RuntimeApiState,
24 thread_id: Option<&str>,
25 ) -> Result<PathBuf, ApiError> {
26 let Some(thread_id) = thread_id else {
27 return Ok(state.workspace.clone());
28 };
29 thread_workspace(state, thread_id)
30 .await
31 .map(|(_, workspace)| workspace)
32 }
33
34 pub(super) async fn thread_workspace(
35 state: &RuntimeApiState,
36 thread_id: &str,
37 ) -> Result<(codewhale_engine::runtime_threads::ThreadRecord, PathBuf), ApiError> {
38 thread_workspace_directory(state, thread_id)
39 .await
40 .map(|(thread, workspace, _)| (thread, workspace))
41 }
42
43 async fn thread_workspace_directory(
44 state: &RuntimeApiState,
45 thread_id: &str,
46 ) -> Result<
47 (
48 codewhale_engine::runtime_threads::ThreadRecord,
49 PathBuf,
50 std::fs::File,
51 ),
52 ApiError,
53 > {
54 if thread_id.trim().is_empty() {
55 return Err(ApiError::bad_request("thread_id must not be empty"));
56 }
57 let thread = state
58 .runtime_threads
59 .get_thread(thread_id)
60 .await
61 .map_err(map_thread_err)?;
62 let recorded = thread.workspace.clone();
63 if !recorded.is_absolute() {
64 return Err(
65 ApiError::conflict("thread workspace is not an absolute path")
66 .with_code("thread_workspace_unavailable"),
67 );
68 }
69 let (workspace, directory) = tokio::task::spawn_blocking(move || {
70 codewhale_util::workspace_dir::open_workspace_directory(&recorded).map_err(|_| {
71 ApiError::conflict("thread workspace is unavailable or changed")
72 .with_code("thread_workspace_unavailable")
73 })
74 })
75 .await
76 .map_err(|_| ApiError::internal("thread workspace resolution failed"))??;
77 Ok((thread, workspace, directory))
78 }
79
80 #[derive(Deserialize)]
81 #[serde(deny_unknown_fields)]
82 pub(super) struct WorkspaceFileSearchQuery {
83 #[serde(default)]
84 query: String,
85 limit: Option<usize>,
86 thread_id: Option<String>,
87 }
88
89 #[derive(Debug, Serialize)]
90 pub(super) struct WorkspaceFileSearchResponse {
91 paths: Vec<String>,
92 }
93
94 /// Read-only suggestions: never use the process cwd or a caller-selected root.
95 pub(super) async fn workspace_file_search(
96 State(state): State<RuntimeApiState>,
97 Query(query): Query<WorkspaceFileSearchQuery>,
98 ) -> Result<Json<WorkspaceFileSearchResponse>, ApiError> {
99 if query.query.len() > 256 {
100 return Err(ApiError::bad_request(
101 "query must be at most 256 UTF-8 bytes",
102 ));
103 }
104 let limit = query.limit.unwrap_or(20);
105 if !(1..=100).contains(&limit) {
106 return Err(ApiError::bad_request("limit must be between 1 and 100"));
107 }
108 let workspace = scoped_workspace(&state, query.thread_id.as_deref()).await?;
109 if query.query.trim().is_empty() {
110 return Ok(Json(WorkspaceFileSearchResponse { paths: Vec::new() }));
111 }
112 let paths = tokio::task::spawn_blocking(move || -> Result<_, ApiError> {
113 let root = if query.thread_id.is_some() {
114 workspace
115 } else {
116 workspace
117 .canonicalize()
118 .map_err(|_| ApiError::internal("workspace is unavailable"))?
119 };
120 Ok(collect_workspace_file_suggestions(
121 &root,
122 &query.query,
123 limit,
124 ))
125 })
126 .await
127 .map_err(|_| ApiError::internal("workspace file search failed"))??;
128 Ok(Json(WorkspaceFileSearchResponse { paths }))
129 }
130
131 fn collect_workspace_file_suggestions(root: &FsPath, query: &str, limit: usize) -> Vec<String> {
132 use codewhale_runtime::working_set::{Workspace, rank_completion_candidates};
133
134 let workspace = Workspace::with_cwd(root.to_owned(), None);
135 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
136 // Reuse the composer's bounded discovery and ignore policy, without its
137 // divergent-cwd pass or symlink-directory traversal. No persistent index.
138 let candidates = workspace
139 .completion_discovery_candidates(20_000, &|| std::time::Instant::now() >= deadline);
140 rank_completion_candidates(&candidates, query, candidates.len())
141 .into_iter()
142 .filter(|candidate| {
143 let path = FsPath::new(candidate);
144 path.components()
145 .all(|component| matches!(component, std::path::Component::Normal(_)))
146 && root
147 .join(path)
148 .canonicalize()
149 .is_ok_and(|resolved| resolved.starts_with(root) && resolved.is_file())
150 })
151 .take(limit)
152 .collect()
153 }
154
155 #[derive(Debug, Serialize)]
156 pub(super) struct WorkspaceStatusResponse {
157 pub(super) workspace: PathBuf,
158 pub(super) git_repo: bool,
159 pub(super) branch: Option<String>,
160 pub(super) head: Option<String>,
161 pub(super) dirty: bool,
162 /// True when `git status` could not be read, so `dirty` and the
163 /// staged/unstaged/untracked counts are unknown rather than zero.
164 pub(super) status_unavailable: bool,
165 pub(super) staged: usize,
166 pub(super) unstaged: usize,
167 pub(super) untracked: usize,
168 pub(super) ahead: Option<u32>,
169 pub(super) behind: Option<u32>,
170 /// Whether the user has trusted this workspace in user-owned config.
171 pub(super) workspace_trusted: bool,
172 }
173
174 #[derive(Debug, Default)]
175 pub(super) struct WorkspaceGitMetadata {
176 pub(super) branch: Option<String>,
177 pub(super) head: Option<String>,
178 pub(super) dirty: bool,
179 }
180
181 /// Status is several blocking `git` spawns, so it runs off the async workers
182 /// (#6149) like every other git read on this surface. It keeps normal
183 /// untracked settings rather than the full review diff flags, but it never
184 /// runs a repository-configured helper: fsmonitor, hooks and clean/process
185 /// filters are off, as on every read-only review path (see `run_status`).
186 pub(super) async fn workspace_status(
187 State(state): State<RuntimeApiState>,
188 ) -> Result<Json<WorkspaceStatusResponse>, ApiError> {
189 let workspace = state.workspace.clone();
190 tokio::task::spawn_blocking(move || collect_workspace_status(&workspace))
191 .await
192 .map(Json)
193 .map_err(|_| ApiError::internal("workspace status failed"))
194 }
195
196 #[derive(Debug, Deserialize)]
197 #[serde(deny_unknown_fields)]
198 pub(super) struct WorkspaceTrustRequest {
199 trusted: bool,
200 }
201
202 #[derive(Debug, Serialize)]
203 pub(super) struct WorkspaceTrustResponse {
204 workspace: PathBuf,
205 /// The verdict as it stands *after* the write, read back through the same
206 /// gate ([`codewhale_runtime::config::is_workspace_trusted`]) the engine consults.
207 /// Echoing the request would report an intention; this reports the fact a
208 /// client would see on its next read, so a write that landed somewhere the
209 /// read path does not look is a `false` here rather than a lie.
210 workspace_trusted: bool,
211 /// The user-global config document the decision was written to, so a
212 /// client can name the file without ever reading or editing it.
213 config_path: PathBuf,
214 message: String,
215 }
216
217 /// Record — or revoke — this workspace's trust in the user-global config.
218 ///
219 /// This route is the only writer a GUI has. A client never edits `config.toml`
220 /// itself: that decision lives with the engine, which owns the same file the
221 /// read path ([`codewhale_runtime::config::is_workspace_trusted`]) consults. The write goes
222 /// through [`codewhale_runtime::config::set_workspace_trust`] — the very function behind the
223 /// TUI's `/trust on --save` — so both front ends and the gate agree on one
224 /// document, and neither can drift into a second source of truth.
225 ///
226 /// The workspace is the server's own (`state.workspace`), never a
227 /// caller-supplied path: a client may trust the project it is attached to and
228 /// nothing else.
229 pub(super) async fn update_workspace_trust(
230 State(state): State<RuntimeApiState>,
231 Json(request): Json<WorkspaceTrustRequest>,
232 ) -> Result<Json<WorkspaceTrustResponse>, ApiError> {
233 let workspace = state.workspace.clone();
234 let trusted = request.trusted;
235 let target = workspace.clone();
236 let (config_path, recorded) = tokio::task::spawn_blocking(move || {
237 let config_path = codewhale_runtime::config::set_workspace_trust(&target, trusted)?;
238 // Read back through the engine's own gate rather than trusting the
239 // write: the two are only ever allowed to agree.
240 Ok::<_, anyhow::Error>((
241 config_path,
242 codewhale_runtime::config::is_workspace_trusted(&target),
243 ))
244 })
245 .await
246 .map_err(|_| ApiError::internal("workspace trust update failed"))?
247 .map_err(|error| ApiError::internal(format!("Failed to update workspace trust: {error}")))?;
248 Ok(Json(WorkspaceTrustResponse {
249 workspace,
250 workspace_trusted: recorded,
251 config_path,
252 message: if recorded {
253 "Workspace trust saved in user config. Project skills and commands use it on subsequent turns; project hooks also require separate approval. Restart the engine to rebuild project MCP connections. Thread Full Access and existing project instructions are unchanged."
254 } else {
255 // Worded as the state, not as the action: this arm is reached both by
256 // a revoke and by a grant the gate did not accept, and "revoked"
257 // would be the wrong sentence for the second.
258 "Workspace trust is not recorded in user config. Project skills, commands, hooks and MCP loading use this decision; existing project instructions and MCP connections are not removed. Thread Full Access is unchanged."
259 }
260 .to_string(),
261 }))
262 }
263
264 pub(super) fn collect_workspace_status(workspace: &FsPath) -> WorkspaceStatusResponse {
265 let mut status = WorkspaceStatusResponse {
266 workspace: workspace.to_path_buf(),
267 git_repo: false,
268 branch: None,
269 head: None,
270 dirty: false,
271 status_unavailable: false,
272 staged: 0,
273 unstaged: 0,
274 untracked: 0,
275 ahead: None,
276 behind: None,
277 // Computed before the early returns below: whether the workspace is a
278 // git repository has nothing to do with whether the user trusted it,
279 // and a non-repo project still has skills and hooks to skip.
280 workspace_trusted: codewhale_runtime::config::is_workspace_trusted(workspace),
281 };
282
283 let Some(head) = read_workspace_head(workspace) else {
284 return status;
285 };
286
287 status.git_repo = true;
288 let (branch, short_head) = branch_and_head(&head);
289 status.branch = branch;
290 status.head = short_head;
291
292 let porcelain = run_status(workspace);
293 status.status_unavailable = porcelain.is_none();
294 status.dirty = porcelain
295 .as_deref()
296 .is_some_and(|porcelain| !porcelain.trim().is_empty());
297 if let Some(porcelain) = porcelain {
298 for line in porcelain.lines() {
299 if line.starts_with("??") {
300 status.untracked += 1;
301 continue;
302 }
303 let chars: Vec<char> = line.chars().collect();
304 if chars.len() >= 2 {
305 if chars[0] != ' ' {
306 status.staged += 1;
307 }
308 if chars[1] != ' ' {
309 status.unstaged += 1;
310 }
311 }
312 }
313 }
314
315 if let Some(counts) = run_git(
316 Git::review_base(workspace),
317 &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
318 ) {
319 let mut parts = counts.split_whitespace();
320 if let (Some(behind), Some(ahead)) = (parts.next(), parts.next()) {
321 status.behind = behind.parse::<u32>().ok();
322 status.ahead = ahead.parse::<u32>().ok();
323 }
324 }
325
326 status
327 }
328
329 pub(super) fn collect_workspace_git_metadata(workspace: &FsPath) -> WorkspaceGitMetadata {
330 match read_workspace_head(workspace) {
331 Some(head) => workspace_git_metadata(workspace, &head),
332 None => WorkspaceGitMetadata::default(),
333 }
334 }
335
336 fn branch_and_head(head: &GitHead) -> (Option<String>, Option<String>) {
337 match head.id {
338 Some(_) => (
339 head.branch.clone().or_else(|| {
340 head.short_id()
341 .map(|short_id| format!("detached@{short_id}"))
342 }),
343 head.short_id().map(str::to_string),
344 ),
345 None => (None, None),
346 }
347 }
348
349 fn workspace_git_metadata(workspace: &FsPath, head: &GitHead) -> WorkspaceGitMetadata {
350 let (branch, head) = branch_and_head(head);
351 let porcelain = run_status(workspace);
352 WorkspaceGitMetadata {
353 branch,
354 head,
355 dirty: porcelain
356 .as_deref()
357 .is_some_and(|porcelain| !porcelain.trim().is_empty()),
358 }
359 }
360
361 fn read_workspace_head(workspace: &FsPath) -> Option<GitHead> {
362 let cancel = std::sync::atomic::AtomicBool::new(false);
363 match read_head(workspace, &cancel) {
364 Ok(head) => Some(head),
365 Err(GitReadError::NotRepository) => None,
366 Err(error) => {
367 tracing::warn!(%error, "workspace git head read failed");
368 None
369 }
370 }
371 }
372
373 /// `git status` through [`Git::status_command`]: besides fsmonitor and hooks
374 /// it neutralizes every clean/process filter driver the repository itself
375 /// configures (never the user's global or system ones, such as Git LFS),
376 /// and submodules are compared without a child status inside them. `None`
377 /// means git could not be read, never a clean tree.
378 fn run_status(workspace: &FsPath) -> Option<String> {
379 run_git(Git::status_command(workspace), &["--porcelain=v1"])
380 }
381
382 fn run_git(command: anyhow::Result<std::process::Command>, args: &[&str]) -> Option<String> {
383 let output = command.ok()?.args(args).output().ok()?;
384 if !output.status.success() {
385 return None;
386 }
387 String::from_utf8(output.stdout).ok()
388 }
389
390 // ---------------------------------------------------------------------------
391 // Workspace files (#6163): a bounded directory listing, bounded reads that
392 // carry a content revision, and revision-checked writes. The server's
393 // configured workspace is the only root and every path is workspace-relative
394 // with `/` separators. Symlinks are never followed, `.git` is never served,
395 // and there is no second file store: bytes go straight to the workspace
396 // through the same confined opener Fleet artifacts use.
397 // ---------------------------------------------------------------------------
398
399 const FILE_LIST_LIMIT_DEFAULT: usize = 200;
400 const FILE_LIST_LIMIT_MAX: usize = 2_000;
401 pub(super) const FILE_READ_LIMIT_DEFAULT: usize = 256 * 1024;
402 pub(super) const FILE_READ_LIMIT_MAX: usize = 4 * 1024 * 1024;
403 /// Files above this size are not served at all: the revision is a digest of
404 /// the whole file, and a Files browser should not page through larger blobs.
405 pub(super) const FILE_SERVE_MAX_BYTES: u64 = 16 * 1024 * 1024;
406 pub(super) const FILE_WRITE_MAX_BYTES: usize = 4 * 1024 * 1024;
407 /// Request-body ceiling for the write route: the content cap plus headroom for
408 /// base64 expansion and the JSON envelope, so an oversized `content` reaches
409 /// the handler and gets a 413 with a message instead of a dropped connection.
410 pub(super) const FILE_WRITE_BODY_LIMIT_BYTES: usize = FILE_WRITE_MAX_BYTES * 4 / 3 + 64 * 1024;
411 const FILE_PATH_MAX_BYTES: usize = 4_096;
412
413 #[derive(Deserialize)]
414 #[serde(deny_unknown_fields)]
415 pub(super) struct WorkspaceFilesListQuery {
416 #[serde(default)]
417 path: String,
418 limit: Option<usize>,
419 thread_id: Option<String>,
420 }
421
422 #[derive(Debug, Serialize)]
423 pub(super) struct WorkspaceFileEntry {
424 name: String,
425 path: String,
426 /// `file`, `directory`, `symlink` (listed by name, never followed) or `other`.
427 kind: &'static str,
428 #[serde(skip_serializing_if = "Option::is_none")]
429 size: Option<u64>,
430 #[serde(skip_serializing_if = "Option::is_none")]
431 modified: Option<String>,
432 }
433
434 #[derive(Debug, Serialize)]
435 pub(super) struct WorkspaceFilesListResponse {
436 path: String,
437 entries: Vec<WorkspaceFileEntry>,
438 truncated: bool,
439 }
440
441 #[derive(Deserialize)]
442 #[serde(deny_unknown_fields)]
443 pub(super) struct WorkspaceFileReadQuery {
444 path: String,
445 offset: Option<usize>,
446 limit: Option<usize>,
447 thread_id: Option<String>,
448 }
449
450 #[derive(Debug, Serialize)]
451 pub(super) struct WorkspaceFileReadResponse {
452 path: String,
453 size: u64,
454 /// SHA-256 of the whole file, not of the returned window.
455 revision: String,
456 #[serde(skip_serializing_if = "Option::is_none")]
457 modified: Option<String>,
458 offset: usize,
459 bytes: usize,
460 truncated: bool,
461 encoding: &'static str,
462 content: String,
463 }
464
465 #[derive(Deserialize)]
466 #[serde(deny_unknown_fields)]
467 pub(super) struct WorkspaceFileWriteRequest {
468 path: String,
469 content: String,
470 /// `utf-8` (default) or `base64`.
471 #[serde(default)]
472 encoding: Option<String>,
473 /// Required to overwrite an existing file; must be absent for a new one.
474 #[serde(default)]
475 expected_revision: Option<String>,
476 }
477
478 #[derive(Debug, Serialize)]
479 pub(super) struct WorkspaceFileWriteResponse {
480 path: String,
481 size: u64,
482 revision: String,
483 created: bool,
484 written_at: String,
485 }
486
487 /// Bytes of one confined file plus the facts a client needs to reason about
488 /// them: total size, the whole-file revision and the modification time.
489 pub(super) struct ConfinedFileBytes {
490 pub(super) size: u64,
491 pub(super) revision: String,
492 pub(super) modified: Option<String>,
493 pub(super) bytes: Vec<u8>,
494 }
495
496 pub(super) fn parse_read_window(
497 offset: Option<usize>,
498 limit: Option<usize>,
499 ) -> Result<(usize, usize), ApiError> {
500 let limit = limit.unwrap_or(FILE_READ_LIMIT_DEFAULT);
501 if !(1..=FILE_READ_LIMIT_MAX).contains(&limit) {
502 return Err(ApiError::bad_request(format!(
503 "limit must be between 1 and {FILE_READ_LIMIT_MAX} bytes"
504 )));
505 }
506 Ok((offset.unwrap_or(0), limit))
507 }
508
509 /// Byte window `[offset, offset + limit)` clamped to the content.
510 pub(super) fn read_window(bytes: &[u8], offset: usize, limit: usize) -> (&[u8], bool) {
511 let start = offset.min(bytes.len());
512 let end = start.saturating_add(limit).min(bytes.len());
513 (&bytes[start..end], end < bytes.len())
514 }
515
516 /// Text windows come back as UTF-8; anything with a NUL byte, invalid UTF-8,
517 /// or a window that splits a multi-byte character comes back as base64.
518 pub(super) fn encode_window(window: &[u8]) -> (&'static str, String) {
519 if !window.contains(&0)
520 && let Ok(text) = std::str::from_utf8(window)
521 {
522 return ("utf-8", text.to_string());
523 }
524 (
525 "base64",
526 base64::engine::general_purpose::STANDARD.encode(window),
527 )
528 }
529
530 pub(super) fn content_revision(bytes: &[u8]) -> String {
531 Sha256::digest(bytes)
532 .iter()
533 .map(|byte| format!("{byte:02x}"))
534 .collect()
535 }
536
537 fn rfc3339(time: std::time::SystemTime) -> String {
538 chrono::DateTime::<chrono::Utc>::from(time).to_rfc3339()
539 }
540
541 pub(super) fn map_fs_error(error: std::io::Error, what: &str) -> ApiError {
542 use std::io::ErrorKind;
543 match error.kind() {
544 ErrorKind::NotFound => ApiError::not_found(format!("{what} not found")),
545 ErrorKind::PermissionDenied => ApiError::forbidden(format!("{what} is not readable")),
546 ErrorKind::InvalidInput | ErrorKind::InvalidData => ApiError::forbidden(format!(
547 "{what} must be a regular, non-linked path inside the workspace"
548 )),
549 ErrorKind::Unsupported => {
550 ApiError::not_implemented("confined file access is unavailable on this platform")
551 }
552 _ => ApiError::internal(format!("{what} access failed: {error}")),
553 }
554 }
555
556 /// A workspace-relative request path. Empty and `.` mean the root, which only
557 /// listing accepts. Absolute paths, `..`, backslashes and `.git` are refused.
558 pub(super) fn relative_request_path(raw: &str, allow_root: bool) -> Result<PathBuf, ApiError> {
559 let trimmed = raw.trim();
560 if trimmed.len() > FILE_PATH_MAX_BYTES {
561 return Err(ApiError::bad_request(format!(
562 "path must be at most {FILE_PATH_MAX_BYTES} UTF-8 bytes"
563 )));
564 }
565 if trimmed.contains('\\') {
566 return Err(ApiError::bad_request("path must use / separators"));
567 }
568 if trimmed.starts_with('/') || FsPath::new(trimmed).is_absolute() {
569 return Err(ApiError::bad_request("path must be workspace-relative"));
570 }
571 let trimmed = trimmed.trim_end_matches('/');
572 if trimmed.is_empty() || trimmed == "." {
573 return if allow_root {
574 Ok(PathBuf::new())
575 } else {
576 Err(ApiError::bad_request("path is required"))
577 };
578 }
579 let path = PathBuf::from(trimmed);
580 if !codewhale_util::files::path_is_confined(&path) {
581 return Err(ApiError::bad_request(
582 "path must be workspace-relative without . or .. components",
583 ));
584 }
585 if path
586 .components()
587 .any(|component| matches!(component, Component::Normal(name) if is_git_metadata_name(name)))
588 {
589 return Err(ApiError::forbidden("the .git directory is not served"));
590 }
591 Ok(path)
592 }
593
594 pub(super) fn canonical_workspace(workspace: &FsPath) -> Result<PathBuf, ApiError> {
595 workspace
596 .canonicalize()
597 .map_err(|_| ApiError::internal("workspace is unavailable"))
598 }
599
600 fn relative_display(path: &FsPath) -> String {
601 path.components()
602 .filter_map(|component| match component {
603 Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
604 _ => None,
605 })
606 .collect::<Vec<_>>()
607 .join("/")
608 }
609
610 /// Walk `relative` from the root one component at a time, refusing any link
611 /// or reparse point on the way, and confirm the result is a directory that
612 /// still resolves inside the root.
613 fn confined_directory(root: &FsPath, relative: &FsPath) -> Result<PathBuf, ApiError> {
614 let mut directory = root.to_path_buf();
615 for component in relative.components() {
616 directory.push(component);
617 let metadata = std::fs::symlink_metadata(&directory)
618 .map_err(|error| map_fs_error(error, "directory"))?;
619 if metadata.file_type().is_symlink()
620 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
621 {
622 return Err(ApiError::forbidden("symlinks are not followed"));
623 }
624 if !metadata.is_dir() {
625 return Err(ApiError::bad_request("path is not a directory"));
626 }
627 }
628 let resolved = directory
629 .canonicalize()
630 .map_err(|error| map_fs_error(error, "directory"))?;
631 if !resolved.starts_with(root) {
632 return Err(ApiError::forbidden("path resolves outside the workspace"));
633 }
634 Ok(directory)
635 }
636
637 pub(super) async fn workspace_files_list(
638 State(state): State<RuntimeApiState>,
639 Query(query): Query<WorkspaceFilesListQuery>,
640 ) -> Result<Json<WorkspaceFilesListResponse>, ApiError> {
641 let relative = relative_request_path(&query.path, true)?;
642 let limit = query.limit.unwrap_or(FILE_LIST_LIMIT_DEFAULT);
643 if !(1..=FILE_LIST_LIMIT_MAX).contains(&limit) {
644 return Err(ApiError::bad_request(format!(
645 "limit must be between 1 and {FILE_LIST_LIMIT_MAX}"
646 )));
647 }
648 let workspace = scoped_workspace(&state, query.thread_id.as_deref()).await?;
649 tokio::task::spawn_blocking(move || list_workspace_directory(&workspace, &relative, limit))
650 .await
651 .map_err(|_| ApiError::internal("workspace listing failed"))?
652 .map(Json)
653 }
654
655 fn list_workspace_directory(
656 workspace: &FsPath,
657 relative: &FsPath,
658 limit: usize,
659 ) -> Result<WorkspaceFilesListResponse, ApiError> {
660 let root = canonical_workspace(workspace)?;
661 let directory = confined_directory(&root, relative)?;
662 let mut entries = Vec::new();
663 let read_dir =
664 std::fs::read_dir(&directory).map_err(|error| map_fs_error(error, "directory"))?;
665 for entry in read_dir {
666 let entry = entry.map_err(|error| map_fs_error(error, "directory"))?;
667 let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
668 continue;
669 };
670 if is_git_metadata_name(std::ffi::OsStr::new(&name)) {
671 continue;
672 }
673 let Ok(file_type) = entry.file_type() else {
674 continue;
675 };
676 let metadata = entry.metadata().ok();
677 let is_link = file_type.is_symlink()
678 || metadata
679 .as_ref()
680 .is_some_and(codewhale_util::path_identity::metadata_is_link_or_reparse);
681 let kind = if is_link {
682 "symlink"
683 } else if file_type.is_dir() {
684 "directory"
685 } else if file_type.is_file() {
686 "file"
687 } else {
688 "other"
689 };
690 let file_metadata = (kind == "file").then_some(metadata).flatten();
691 entries.push(WorkspaceFileEntry {
692 path: relative_display(&relative.join(&name)),
693 name,
694 kind,
695 size: file_metadata.as_ref().map(std::fs::Metadata::len),
696 modified: file_metadata
697 .as_ref()
698 .and_then(|metadata| metadata.modified().ok())
699 .map(rfc3339),
700 });
701 }
702 entries.sort_by(|left, right| {
703 (left.kind != "directory")
704 .cmp(&(right.kind != "directory"))
705 .then_with(|| left.name.to_lowercase().cmp(&right.name.to_lowercase()))
706 .then_with(|| left.name.cmp(&right.name))
707 });
708 let truncated = entries.len() > limit;
709 entries.truncate(limit);
710 Ok(WorkspaceFilesListResponse {
711 path: relative_display(relative),
712 entries,
713 truncated,
714 })
715 }
716
717 pub(super) fn open_confined_file(
718 root: &FsPath,
719 relative: &FsPath,
720 create: bool,
721 ) -> Result<codewhale_util::files::WorkspaceFile, ApiError> {
722 codewhale_util::files::WorkspaceFile::open(root, relative, create)
723 .map_err(|error| map_fs_error(error, "file"))
724 }
725
726 /// [`open_confined_file`] for the application's own state root, which a user
727 /// may have relocated behind a link (on Windows, a junction to another
728 /// volume). The root is resolved once and every component below it is still
729 /// refused when linked, so a reader follows its writer and a caller-supplied
730 /// workspace root keeps the stricter [`open_confined_file`].
731 pub(super) fn open_confined_file_resolved(
732 root: &FsPath,
733 relative: &FsPath,
734 create: bool,
735 ) -> Result<codewhale_util::files::WorkspaceFile, ApiError> {
736 codewhale_util::files::WorkspaceFile::open_resolved_root(root, relative, create)
737 .map_err(|error| map_fs_error(error, "file"))
738 }
739
740 /// Read one confined file completely (bounded by `FILE_SERVE_MAX_BYTES`) so
741 /// the revision always describes the whole file.
742 pub(super) fn read_confined_bytes(
743 file: &codewhale_util::files::WorkspaceFile,
744 ) -> Result<ConfinedFileBytes, ApiError> {
745 let mut handle = file
746 .open_file()
747 .map_err(|error| map_fs_error(error, "file"))?;
748 let metadata = handle
749 .metadata()
750 .map_err(|error| map_fs_error(error, "file"))?;
751 if metadata.len() > FILE_SERVE_MAX_BYTES {
752 return Err(ApiError::payload_too_large(format!(
753 "file is larger than the {FILE_SERVE_MAX_BYTES}-byte serving limit"
754 )));
755 }
756 let mut bytes = Vec::with_capacity(metadata.len() as usize);
757 handle
758 .by_ref()
759 .take(FILE_SERVE_MAX_BYTES + 1)
760 .read_to_end(&mut bytes)
761 .map_err(|error| map_fs_error(error, "file"))?;
762 if bytes.len() as u64 > FILE_SERVE_MAX_BYTES {
763 return Err(ApiError::payload_too_large(format!(
764 "file grew past the {FILE_SERVE_MAX_BYTES}-byte serving limit while it was read"
765 )));
766 }
767 Ok(ConfinedFileBytes {
768 size: bytes.len() as u64,
769 revision: content_revision(&bytes),
770 modified: metadata.modified().ok().map(rfc3339),
771 bytes,
772 })
773 }
774
775 /// Refuse links and non-files before the confined opener runs, so a client
776 /// sees a precise status instead of a generic confinement error.
777 pub(super) fn precheck_file_target(
778 root: &FsPath,
779 relative: &FsPath,
780 ) -> Result<Option<std::fs::Metadata>, ApiError> {
781 if let Some(parent) = relative
782 .parent()
783 .filter(|parent| !parent.as_os_str().is_empty())
784 {
785 // Every directory on the way must be a real directory; a link would
786 // otherwise surface as a confinement error from the opener.
787 confined_directory(root, parent).or_else(|error| {
788 if error.status == StatusCode::NOT_FOUND {
789 Ok(PathBuf::new())
790 } else {
791 Err(error)
792 }
793 })?;
794 }
795 match std::fs::symlink_metadata(root.join(relative)) {
796 Ok(metadata) => {
797 if metadata.file_type().is_symlink()
798 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
799 {
800 return Err(ApiError::forbidden("symlinks are not followed"));
801 }
802 if metadata.is_dir() {
803 return Err(ApiError::bad_request("path is a directory"));
804 }
805 Ok(Some(metadata))
806 }
807 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
808 Err(error) => Err(map_fs_error(error, "file")),
809 }
810 }
811
812 pub(super) async fn workspace_file_read(
813 State(state): State<RuntimeApiState>,
814 Query(query): Query<WorkspaceFileReadQuery>,
815 ) -> Result<Json<WorkspaceFileReadResponse>, ApiError> {
816 let relative = relative_request_path(&query.path, false)?;
817 let (offset, limit) = parse_read_window(query.offset, query.limit)?;
818 let workspace = scoped_workspace(&state, query.thread_id.as_deref()).await?;
819 tokio::task::spawn_blocking(move || {
820 let root = canonical_workspace(&workspace)?;
821 if precheck_file_target(&root, &relative)?.is_none() {
822 return Err(ApiError::not_found("file not found"));
823 }
824 let file = open_confined_file(&root, &relative, false)?;
825 let read = read_confined_bytes(&file)?;
826 let (window, truncated) = read_window(&read.bytes, offset, limit);
827 let (encoding, content) = encode_window(window);
828 Ok(WorkspaceFileReadResponse {
829 path: relative_display(&relative),
830 size: read.size,
831 revision: read.revision,
832 modified: read.modified,
833 offset: offset.min(read.bytes.len()),
834 bytes: window.len(),
835 truncated,
836 encoding,
837 content,
838 })
839 })
840 .await
841 .map_err(|_| ApiError::internal("workspace file read failed"))?
842 .map(Json)
843 }
844
845 pub(super) async fn workspace_file_write(
846 State(state): State<RuntimeApiState>,
847 Query(scope): Query<ThreadScopeQuery>,
848 Json(request): Json<WorkspaceFileWriteRequest>,
849 ) -> Result<(StatusCode, Json<WorkspaceFileWriteResponse>), ApiError> {
850 let relative = relative_request_path(&request.path, false)?;
851 let bytes = match request.encoding.as_deref().unwrap_or("utf-8") {
852 "utf-8" => request.content.into_bytes(),
853 "base64" => base64::engine::general_purpose::STANDARD
854 .decode(request.content.as_bytes())
855 .map_err(|_| ApiError::bad_request("content is not valid base64"))?,
856 _ => return Err(ApiError::bad_request("encoding must be utf-8 or base64")),
857 };
858 if bytes.len() > FILE_WRITE_MAX_BYTES {
859 return Err(ApiError::payload_too_large(format!(
860 "content must be at most {FILE_WRITE_MAX_BYTES} bytes"
861 )));
862 }
863 let expected_revision = request
864 .expected_revision
865 .map(|revision| revision.trim().to_ascii_lowercase())
866 .filter(|revision| !revision.is_empty());
867 let (workspace, directory) = if let Some(thread_id) = scope.thread_id.as_deref() {
868 let (_, workspace, directory) = thread_workspace_directory(&state, thread_id).await?;
869 (workspace, std::sync::Arc::new(directory))
870 } else {
871 let scope = &state.workspace_scope;
872 (scope.canonical.clone(), scope.directory.clone())
873 };
874 tokio::task::spawn_blocking(move || {
875 write_workspace_file(
876 &workspace,
877 &directory,
878 &relative,
879 &bytes,
880 expected_revision.as_deref(),
881 )
882 })
883 .await
884 .map_err(|_| ApiError::internal("workspace file write failed"))?
885 }
886
887 fn write_workspace_file(
888 workspace: &FsPath,
889 directory: &std::fs::File,
890 relative: &FsPath,
891 bytes: &[u8],
892 expected_revision: Option<&str>,
893 ) -> Result<(StatusCode, Json<WorkspaceFileWriteResponse>), ApiError> {
894 static WRITES: std::sync::Mutex<()> = std::sync::Mutex::new(());
895 let _write_guard = WRITES
896 .lock()
897 .map_err(|_| ApiError::internal("workspace file write lock is unavailable"))?;
898 let root = canonical_workspace(workspace)?;
899 let created = precheck_file_target(&root, relative)?.is_none();
900 match (created, expected_revision) {
901 (true, Some(_)) => {
902 return Err(ApiError::conflict(
903 "expected_revision was given but the file does not exist",
904 ));
905 }
906 (false, None) => {
907 return Err(ApiError::conflict(
908 "expected_revision is required to overwrite an existing file; read it first",
909 ));
910 }
911 _ => {}
912 }
913 // Parents are created only for a new file, and only through the confined
914 // opener, which refuses links at every component. This is the user's own
915 // file, not a private store: keep its mode on edit, follow the umask on
916 // creation.
917 let file =
918 codewhale_util::files::WorkspaceFile::open_shared_in(&root, directory, relative, created)
919 .map_err(|error| map_fs_error(error, "file"))?;
920 if let Some(expected) = expected_revision {
921 let current = read_confined_bytes(&file)?;
922 if current.revision != expected {
923 return Err(ApiError::conflict(format!(
924 "file changed since it was read; current revision is {}",
925 current.revision
926 )));
927 }
928 }
929 publish_workspace_file(&file, bytes, created)?;
930 Ok((
931 if created {
932 StatusCode::CREATED
933 } else {
934 StatusCode::OK
935 },
936 Json(WorkspaceFileWriteResponse {
937 path: relative_display(relative),
938 size: bytes.len() as u64,
939 revision: content_revision(bytes),
940 created,
941 written_at: chrono::Utc::now().to_rfc3339(),
942 }),
943 ))
944 }
945
946 pub(super) fn publish_workspace_file(
947 file: &codewhale_util::files::WorkspaceFile,
948 bytes: &[u8],
949 created: bool,
950 ) -> Result<(), ApiError> {
951 // Absence was observed before opening the confined parent. Another
952 // creator can publish meanwhile; never replace that creator's file.
953 let publication = if created {
954 file.publish(bytes)
955 } else {
956 file.replace(bytes)
957 };
958 publication.map_err(|error| {
959 if created && error.kind() == std::io::ErrorKind::AlreadyExists {
960 ApiError::conflict("file was created by another writer; read it before overwriting")
961 } else {
962 map_fs_error(error, "file")
963 }
964 })
965 }
966
967 // ── Effective instruction sources (#6168) ────────────────────────────────
968
969 #[derive(Debug, Serialize)]
970 pub(super) struct WorkspaceInstructionSource {
971 /// `project` | `rule` | `global` | `fragment` | `configured` |
972 /// `constitution` | `ignored`.
973 kind: &'static str,
974 /// `loaded` | `shadowed` | `skipped` | `missing`.
975 status: &'static str,
976 scope_dir: PathBuf,
977 path: PathBuf,
978 /// Workspace-relative spelling when the path sits under the workspace.
979 relative_path: Option<String>,
980 exists: bool,
981 bytes: Option<u64>,
982 warning: Option<String>,
983 }
984
985 #[derive(Debug, Serialize)]
986 pub(super) struct WorkspaceInstructionsResponse {
987 workspace: PathBuf,
988 sources: Vec<WorkspaceInstructionSource>,
989 /// Foreign instruction formats the operator opted into.
990 foreign_imports: Vec<String>,
991 /// True when no file-based instructions exist anywhere and the
992 /// prompt carries the ephemeral generated context instead.
993 generated_fallback: bool,
994 /// Resolved per-scope ceilings in estimated tokens (#6526): the global
995 /// scope, the project scope (instructions + rules), the static-prefix
996 /// guard, and the usable window they are percentages of.
997 global_budget_tokens: usize,
998 project_budget_tokens: usize,
999 static_guard_tokens: Option<usize>,
1000 usable_window_tokens: Option<usize>,
1001 /// Warnings from the real load pass — includes assembly-level notices
1002 /// (unimported foreign formats, ignored WHALE.md, constitution parse)
1003 /// alongside what per-source `warning` fields already carry.
1004 warnings: Vec<String>,
1005 }
1006
1007 fn instruction_source_kind_name(
1008 kind: codewhale_engine::project_context::InstructionSourceKind,
1009 ) -> &'static str {
1010 use codewhale_engine::project_context::InstructionSourceKind as Kind;
1011 match kind {
1012 Kind::Project => "project",
1013 Kind::Rule => "rule",
1014 Kind::Global => "global",
1015 Kind::Fragment => "fragment",
1016 Kind::Configured => "configured",
1017 Kind::Constitution => "constitution",
1018 Kind::Ignored => "ignored",
1019 }
1020 }
1021
1022 fn instruction_source_status_name(
1023 status: codewhale_engine::project_context::InstructionSourceStatus,
1024 ) -> &'static str {
1025 use codewhale_engine::project_context::InstructionSourceStatus as Status;
1026 match status {
1027 Status::Loaded => "loaded",
1028 Status::Shadowed => "shadowed",
1029 Status::Skipped => "skipped",
1030 Status::Missing => "missing",
1031 }
1032 }
1033
1034 /// Read-only listing of the effective instruction sources for this
1035 /// workspace (#6168): repository-root → workspace chain candidates, rules
1036 /// files, the global fallback layer, opted-in foreign fragments, configured
1037 /// `instructions = [...]` files, and the constitution — each with the status
1038 /// the prompt loaders give it. Edits go through the workspace file routes.
1039 pub(super) async fn workspace_instructions(
1040 State(state): State<RuntimeApiState>,
1041 ) -> Result<Json<WorkspaceInstructionsResponse>, ApiError> {
1042 let workspace = state.workspace.clone();
1043 let config = state.config.read().clone();
1044 let configured = config.instructions_paths();
1045 let settings = codewhale_engine::project_context::InstructionSettings::from_config(&config);
1046 let foreign_imports = settings
1047 .imports
1048 .keys()
1049 .into_iter()
1050 .map(str::to_string)
1051 .collect();
1052 let budgets = codewhale_engine::project_context::InstructionBudgets::resolve(
1053 Some(&settings.budget),
1054 None,
1055 None,
1056 )
1057 .map_err(ApiError::internal)?;
1058
1059 let (sources, generated_fallback, warnings, workspace_root) =
1060 tokio::task::spawn_blocking(move || {
1061 let sources =
1062 codewhale_engine::project_context::project_instruction_sources_with_settings(
1063 &workspace,
1064 &settings,
1065 &configured,
1066 );
1067 // The real load pass supplies assembly-level warnings and tells us
1068 // whether the ephemeral generated context is what the prompt
1069 // carries. Cached — this is the same call the engine makes.
1070 let ctx = codewhale_engine::project_context::load_project_context_with_settings(
1071 &workspace, &settings,
1072 );
1073 let generated_fallback = ctx.instructions.is_some() && ctx.source_path.is_none();
1074 // `project_instruction_sources` canonicalizes the workspace (the
1075 // `/var` → `/private/var` class of alias), so relative paths must
1076 // be computed against the canonical spelling or every strip fails.
1077 // It rides this closure rather than the async body because
1078 // `canonicalize` is a blocking syscall, and one on a Tokio worker
1079 // is one too many (#6149).
1080 let workspace_root =
1081 std::fs::canonicalize(&workspace).unwrap_or_else(|_| workspace.clone());
1082 (sources, generated_fallback, ctx.warnings, workspace_root)
1083 })
1084 .await
1085 .map_err(|_| ApiError::internal("instruction source listing failed"))?;
1086 Ok(Json(WorkspaceInstructionsResponse {
1087 workspace: workspace_root.clone(),
1088 sources: sources
1089 .into_iter()
1090 .map(|source| WorkspaceInstructionSource {
1091 kind: instruction_source_kind_name(source.kind),
1092 status: instruction_source_status_name(source.status),
1093 // Forward slashes on every platform. `display()` emits the
1094 // native separator, which would make a wire field describing a
1095 // repo-relative path differ between a Windows and a Unix host
1096 // and force every client to branch on the server's OS. The
1097 // absolute `path` below stays native, because that one is only
1098 // meaningful on the machine that produced it.
1099 relative_path: source
1100 .path
1101 .strip_prefix(&workspace_root)
1102 .ok()
1103 .map(|relative| {
1104 relative
1105 .components()
1106 .map(|part| part.as_os_str().to_string_lossy())
1107 .collect::<Vec<_>>()
1108 .join("/")
1109 }),
1110 scope_dir: source.scope_dir,
1111 path: source.path,
1112 exists: source.exists,
1113 bytes: source.bytes,
1114 warning: source.warning,
1115 })
1116 .collect(),
1117 foreign_imports,
1118 generated_fallback,
1119 global_budget_tokens: budgets.global_tokens,
1120 project_budget_tokens: budgets.project_tokens,
1121 static_guard_tokens: budgets.static_guard_tokens,
1122 usable_window_tokens: budgets.usable_window_tokens,
1123 warnings,
1124 }))
1125 }
1126
1127 #[cfg(test)]
1128 mod tests {
1129 use super::*;
1130 #[cfg(unix)]
1131 use codewhale_dependencies::ExternalTool as _;
1132
1133 #[cfg(unix)]
1134 #[test]
1135 fn workspace_status_does_not_run_the_repository_fsmonitor() -> anyhow::Result<()> {
1136 let tmp = tempfile::tempdir()?;
1137 let repo = tmp.path().join("repo");
1138 std::fs::create_dir_all(&repo)?;
1139 let git = |args: &[&str]| Git::status(args, &repo).is_ok_and(|status| status.success());
1140 if !git(&["init", "-q"]) {
1141 return Ok(());
1142 }
1143 std::fs::write(repo.join("file.txt"), "hello\n")?;
1144 assert!(git(&["add", "file.txt"]));
1145 assert!(git(&[
1146 "-c",
1147 "user.name=t",
1148 "-c",
1149 "user.email=t@example.invalid",
1150 "commit",
1151 "-qm",
1152 "init",
1153 ]));
1154 std::fs::write(repo.join("file.txt"), "hello\nworld\n")?;
1155 let marker = tmp.path().join("ran");
1156 let hook = tmp.path().join("fsmonitor.sh");
1157 std::fs::write(
1158 &hook,
1159 format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()),
1160 )?;
1161 codewhale_config::private_directory::tighten_mode(&hook, 0o755)?;
1162 assert!(git(&["config", "core.fsmonitor", &hook.to_string_lossy()]));
1163
1164 let status = collect_workspace_status(&repo);
1165 assert!(status.git_repo);
1166 assert_eq!(status.unstaged, 1);
1167 assert!(!marker.exists(), "the repository's fsmonitor hook ran");
1168 Ok(())
1169 }
1170
1171 #[test]
1172 fn git_metadata_directory_is_refused_in_any_letter_case() {
1173 for raw in [
1174 ".git",
1175 ".git/config",
1176 ".GIT/config",
1177 ".Git/hooks/pre-commit",
1178 "sub/.gIt/HEAD",
1179 ] {
1180 let error = relative_request_path(raw, false).expect_err(raw);
1181 assert_eq!(error.status, StatusCode::FORBIDDEN, "{raw}");
1182 }
1183 for raw in [".github/workflows/ci.yml", "a.git/b", ".gitignore", "git"] {
1184 assert!(relative_request_path(raw, false).is_ok(), "{raw}");
1185 }
1186 }
1187
1188 #[test]
1189 fn listing_hides_git_metadata_directory_in_any_letter_case() -> anyhow::Result<()> {
1190 let tmp = tempfile::tempdir()?;
1191 std::fs::create_dir_all(tmp.path().join(".Git"))?;
1192 std::fs::write(tmp.path().join("kept.txt"), "kept")?;
1193 let listing = list_workspace_directory(tmp.path(), FsPath::new(""), 100)
1194 .map_err(|error| anyhow::anyhow!(error.message))?;
1195 let names: Vec<&str> = listing
1196 .entries
1197 .iter()
1198 .map(|entry| entry.name.as_str())
1199 .collect();
1200 assert_eq!(names, ["kept.txt"]);
1201 Ok(())
1202 }
1203
1204 #[test]
1205 fn workspace_file_search_reuses_discovery_ignores() -> anyhow::Result<()> {
1206 let tmp = tempfile::tempdir()?;
1207 let root = tmp.path();
1208 std::fs::create_dir_all(root.join(".git"))?;
1209 std::fs::create_dir_all(root.join(".agents"))?;
1210 std::fs::create_dir_all(root.join("target"))?;
1211 std::fs::write(root.join(".gitignore"), ".agents/\ntarget/\nlocal.rs\n")?;
1212 std::fs::write(root.join(".ignore"), "blocked.rs\n")?;
1213 std::fs::write(root.join(".deepseekignore"), "private.rs\n")?;
1214 for name in [
1215 "local.rs",
1216 "blocked.rs",
1217 "private.rs",
1218 ".agents/guide.rs",
1219 "target/build.rs",
1220 ] {
1221 std::fs::write(root.join(name), "not returned")?;
1222 }
1223 let paths = collect_workspace_file_suggestions(&root.canonicalize()?, ".rs", 100);
1224 assert_eq!(paths, [".agents/guide.rs", "local.rs"]);
1225 Ok(())
1226 }
1227
1228 #[cfg(unix)]
1229 #[test]
1230 fn workspace_file_search_contains_symlinks_and_excludes_other_workspaces() -> anyhow::Result<()>
1231 {
1232 use std::os::unix::fs::symlink;
1233
1234 let tmp = tempfile::tempdir()?;
1235 let root = tmp.path().join("workspace");
1236 let other = tmp.path().join("workspace-other");
1237 std::fs::create_dir_all(&root)?;
1238 std::fs::create_dir_all(&other)?;
1239 std::fs::write(root.join("inside.rs"), "inside")?;
1240 std::fs::write(other.join("outside.rs"), "outside")?;
1241 symlink(root.join("inside.rs"), root.join("alias.rs"))?;
1242 symlink(other.join("outside.rs"), root.join("escape.rs"))?;
1243 symlink(&other, root.join("external-directory"))?;
1244 symlink(&other, root.join(".agents"))?;
1245 symlink(other.join("missing.rs"), root.join("broken.rs"))?;
1246 symlink(&root, root.join("loop"))?;
1247 let paths = collect_workspace_file_suggestions(&root.canonicalize()?, ".rs", 100);
1248 assert_eq!(paths, ["alias.rs", "inside.rs"]);
1249 Ok(())
1250 }
1251 }
1252
1252 lines RUST