1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::{
4 collections::{BTreeMap, HashSet},
5 fs,
6 path::{Path, PathBuf},
7 time::Duration,
8};
9#[derive(Debug, thiserror::Error)]
10#[error("workspace: {0}")]
11pub struct WorkspaceError(pub String);
12impl From<std::io::Error> for WorkspaceError {
13 fn from(error: std::io::Error) -> Self {
14 Self(error.to_string())
15 }
16}
17impl From<serde_json::Error> for WorkspaceError {
18 fn from(error: serde_json::Error) -> Self {
19 Self(error.to_string())
20 }
21}
22impl From<crate::memory::MemoryError> for WorkspaceError {
23 fn from(error: crate::memory::MemoryError) -> Self {
24 Self(error.to_string())
25 }
26}
27pub fn relative_path(raw: &str) -> Result<String, WorkspaceError> {
28 if raw.is_empty() || raw == "." {
29 return Ok(String::new());
30 }
31 if raw.len() > 1024
32 || raw.split('/').count() > 40
33 || raw.starts_with('/')
34 || raw.contains(['\\', '\0', ':'])
35 || raw.split('/').any(|part| {
36 part.is_empty()
37 || part == "."
38 || part == ".."
39 || part.ends_with('.')
40 || part.trim() != part
41 })
42 {
43 return Err(WorkspaceError("invalid relative path".into()));
44 }
45 Ok(raw.into())
46}
47pub fn denied(raw: &str) -> bool {
48 let lower = raw.to_lowercase();
49 let segments: Vec<_> = lower.split('/').collect();
50 let name = segments.last().copied().unwrap_or("");
51 segments.iter().any(|part| {
52 [
53 ".git", ".ssh", ".aws", ".gnupg", ".kube", ".docker", ".config",
54 ]
55 .contains(part)
56 }) || [
57 ".env",
58 ".npmrc",
59 ".pypirc",
60 ".netrc",
61 ".git-credentials",
62 ".dockercfg",
63 "credentials",
64 ]
65 .contains(&name)
66 || [".env.", "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"]
67 .iter()
68 .any(|prefix| name.starts_with(prefix))
69 || [".pem", ".key", ".p12", ".pfx", ".asc"]
70 .iter()
71 .any(|suffix| name.ends_with(suffix))
72}
73fn ignored(name: &str) -> bool {
74 [
75 "node_modules",
76 ".git",
77 "dist",
78 "build",
79 "out",
80 "coverage",
81 ".next",
82 ".nuxt",
83 ".cache",
84 ".venv",
85 "venv",
86 "__pycache__",
87 ".staging",
88 ".turbo",
89 ]
90 .contains(&name)
91}
92fn binary(path: &str) -> bool {
93 let extension = Path::new(path)
94 .extension()
95 .and_then(|value| value.to_str())
96 .unwrap_or("")
97 .to_lowercase();
98 [
99 "png", "jpg", "jpeg", "gif", "webp", "ico", "bmp", "pdf", "zip", "gz", "tar", "tgz", "bz2",
100 "7z", "rar", "exe", "dll", "so", "dylib", "bin", "o", "a", "class", "jar", "wasm", "woff",
101 "woff2", "ttf", "otf", "eot", "mp3", "mp4", "mov", "avi", "mkv", "wav", "flac", "sqlite",
102 "db",
103 ]
104 .contains(&extension.as_str())
105}
106fn hash(content: &str) -> String {
107 format!("{:x}", Sha256::digest(content.as_bytes()))
108}
109struct Root {
110 path: PathBuf,
111 identity: same_file::Handle,
112 directory: crate::secure_fs::Directory,
113}
114#[derive(Debug, Clone, Serialize)]
115pub struct WorkspaceRoot {
116 pub id: String,
117 pub name: String,
118}
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(rename_all = "camelCase", deny_unknown_fields)]
121pub struct LineRange {
122 pub start_line: usize,
123 pub end_line: usize,
124}
125#[derive(Debug, Clone, Serialize)]
126pub struct FileSnapshot {
127 pub path: String,
128 pub content: String,
129 pub hash: String,
130 pub size: usize,
131 pub truncated: bool,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub range: Option<LineRange>,
134}
135#[derive(Debug, Clone, Serialize)]
136pub struct TreeEntry {
137 pub name: String,
138 pub path: String,
139 #[serde(rename = "type")]
140 pub kind: String,
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub size: Option<u64>,
143}
144#[derive(Debug, Serialize)]
145#[serde(rename_all = "camelCase")]
146pub struct SearchPage {
147 pub results: Vec<SearchResult>,
148 pub next_cursor: Option<String>,
149 pub scan_truncated: bool,
150}
151#[derive(Debug, Serialize)]
152pub struct SearchResult {
153 pub name: String,
154 pub path: String,
155 pub size: u64,
156}
157pub struct WorkspaceService {
158 roots: BTreeMap<String, Root>,
159}
160impl Default for WorkspaceService {
161 fn default() -> Self {
162 Self::new()
163 }
164}
165impl WorkspaceService {
166 pub fn new() -> Self {
167 Self {
168 roots: BTreeMap::new(),
169 }
170 }
171 pub fn register(&mut self, path: &Path) -> Result<WorkspaceRoot, WorkspaceError> {
172 if self.roots.len() >= 8 {
173 return Err(WorkspaceError("root limit reached".into()));
174 }
175 let path = path.canonicalize()?;
176 if !path.is_dir() {
177 return Err(WorkspaceError("root is not a directory".into()));
178 }
179 let id = uuid::Uuid::new_v4().to_string();
180 let name = path
181 .file_name()
182 .unwrap_or(path.as_os_str())
183 .to_string_lossy()
184 .into_owned();
185 let identity = same_file::Handle::from_path(&path)?;
186 let directory = crate::secure_fs::Directory::open(&path)?;
187 self.roots.insert(
188 id.clone(),
189 Root {
190 path,
191 identity,
192 directory,
193 },
194 );
195 Ok(WorkspaceRoot { id, name })
196 }
197 pub fn revoke(&mut self, id: &str) {
198 self.roots.remove(id);
199 }
200 fn root(&self, id: &str) -> Result<&Root, WorkspaceError> {
201 let root = self
202 .roots
203 .get(id)
204 .ok_or_else(|| WorkspaceError("unknown or revoked root".into()))?;
205 if fs::symlink_metadata(&root.path)?.file_type().is_symlink()
206 || same_file::Handle::from_path(&root.path)? != root.identity
207 {
208 return Err(WorkspaceError("workspace root changed".into()));
209 }
210 Ok(root)
211 }
212 fn resolve(
213 &self,
214 id: &str,
215 path: &str,
216 allow_missing: bool,
217 ) -> Result<PathBuf, WorkspaceError> {
218 let relative = relative_path(path)?;
219 if denied(&relative) {
220 return Err(WorkspaceError("path is not accessible".into()));
221 }
222 let root = self.root(id)?;
223 let mut current = root.path.clone();
224 let parts: Vec<_> = relative
225 .split('/')
226 .filter(|part| !part.is_empty())
227 .collect();
228 for (index, part) in parts.iter().enumerate() {
229 current.push(part);
230 match fs::symlink_metadata(¤t) {
231 Ok(metadata) => {
232 if metadata.file_type().is_symlink()
233 || index + 1 < parts.len() && !metadata.is_dir()
234 {
235 return Err(WorkspaceError("symlink or non-directory ancestor".into()));
236 }
237 }
238 Err(error)
239 if allow_missing
240 && index + 1 == parts.len()
241 && error.kind() == std::io::ErrorKind::NotFound => {}
242 Err(error) => return Err(error.into()),
243 }
244 }
245 if !current.starts_with(&root.path) {
246 return Err(WorkspaceError("path escaped root".into()));
247 }
248 Ok(current)
249 }
250 fn text(&self, id: &str, path: &str, maximum: u64) -> Result<String, WorkspaceError> {
251 self.resolve(id, path, false)?;
252 let bytes = self
253 .root(id)?
254 .directory
255 .read(Path::new(path), maximum, false)?;
256 if bytes.len() as u64 > maximum || bytes.contains(&0) {
257 return Err(WorkspaceError("binary or oversized file".into()));
258 }
259 String::from_utf8(bytes).map_err(|_| WorkspaceError("file is not UTF-8".into()))
260 }
261 fn replace_text(
262 &self,
263 id: &str,
264 path: &str,
265 text: &str,
266 create: bool,
267 ) -> Result<(), WorkspaceError> {
268 self.resolve(id, path, create)?;
269 self.root(id)?
270 .directory
271 .write(Path::new(path), text.as_bytes(), create, !create)?;
272 Ok(())
273 }
274 fn remove_text(&self, id: &str, path: &str) -> Result<(), WorkspaceError> {
275 self.resolve(id, path, false)?;
276 self.root(id)?.directory.remove(Path::new(path))?;
277 Ok(())
278 }
279 pub fn read(
280 &self,
281 id: &str,
282 path: &str,
283 mut range: Option<LineRange>,
284 ) -> Result<FileSnapshot, WorkspaceError> {
285 let relative = relative_path(path)?;
286 if relative.is_empty() || binary(&relative) {
287 return Err(WorkspaceError("text file required".into()));
288 }
289 let full = self.text(id, &relative, 256 * 1024)?;
290 let content = if let Some(range) = &mut range {
291 if range.start_line == 0 || range.end_line < range.start_line {
292 return Err(WorkspaceError("invalid line range".into()));
293 }
294 range.end_line = range.end_line.min(full.split('\n').count());
295 full.split('\n')
296 .skip(range.start_line - 1)
297 .take(range.end_line.saturating_sub(range.start_line) + 1)
298 .collect::<Vec<_>>()
299 .join("\n")
300 } else {
301 full
302 };
303 let size = content.len();
304 let hash = hash(&content);
305 Ok(FileSnapshot {
306 path: relative,
307 content,
308 hash,
309 size,
310 truncated: false,
311 range,
312 })
313 }
314 pub fn create_root(&mut self, path: &Path) -> Result<WorkspaceRoot, WorkspaceError> {
315 crate::memory::owned_directory(path)?;
316 self.register(path)
317 }
318 pub fn git_context(&self, id: &str, mode: &str) -> Result<serde_json::Value, WorkspaceError> {
319 self.git_context_with(id, mode, &crate::workspace_git::NativeGitRunner)
320 }
321 pub fn git_context_with(
322 &self,
323 id: &str,
324 mode: &str,
325 runner: &dyn crate::workspace_git::GitRunner,
326 ) -> Result<serde_json::Value, WorkspaceError> {
327 if !["status", "diff"].contains(&mode) {
328 return Err(WorkspaceError("invalid git context mode".into()));
329 }
330 let root = &self.root(id)?.path;
331 let label = format!("git {mode}");
332 let output = match runner.output(root, mode) {
333 Ok(output) => output,
334 Err(_) => {
335 return Ok(
336 serde_json::json!({"kind":"git","mode":mode,"label":label,"available":false,"content":"","hash":"","size":0,"truncated":false,"reason":"git-failed"}),
337 );
338 }
339 };
340 self.root(id)?;
341 let success = output.success;
342 let bytes = output.bytes;
343 let raw = String::from_utf8_lossy(&bytes);
344 let truncated = raw.chars().count() > 102400;
345 let content = raw.chars().take(102400).collect::<String>();
346 let available = success && !content.trim().is_empty();
347 Ok(
348 serde_json::json!({"kind":"git","mode":mode,"label":label,"available":available,"content":if available{content.as_str()}else{""},"hash":if available{hash(&content)}else{String::new()},"size":if available{content.len()}else{0},"truncated":truncated,"reason":if !success{Some("git-failed")}else if !available{Some("no-changes")}else{None}}),
349 )
350 }
351 pub fn tree(&self, id: &str, path: &str) -> Result<Vec<TreeEntry>, WorkspaceError> {
352 let relative = relative_path(path)?;
353 self.resolve(id, &relative, false)?;
354 let root = self.root(id)?;
355 let directory = if relative.is_empty() {
356 root.directory.dir()?.try_clone()?
357 } else {
358 root.directory.subdir(Path::new(&relative))?
359 };
360 let mut entries = Vec::new();
361 for (count, entry) in directory.entries()?.enumerate() {
362 if count >= 2000 {
363 break;
364 }
365 let entry = entry?;
366 let kind = entry.file_type()?;
367 let name = entry.file_name().to_string_lossy().into_owned();
368 let path = if relative.is_empty() {
369 name.clone()
370 } else {
371 format!("{relative}/{name}")
372 };
373 if kind.is_symlink() || denied(&path) || kind.is_dir() && ignored(&name) {
374 continue;
375 }
376 if kind.is_dir() || kind.is_file() {
377 entries.push(TreeEntry {
378 name,
379 path,
380 kind: if kind.is_dir() { "dir" } else { "file" }.into(),
381 size: if kind.is_file() {
382 Some(entry.metadata()?.len())
383 } else {
384 None
385 },
386 });
387 }
388 }
389 entries.sort_by(|left, right| left.kind.cmp(&right.kind).then(left.name.cmp(&right.name)));
390 Ok(entries)
391 }
392 pub fn search(
393 &self,
394 id: &str,
395 query: &str,
396 limit: usize,
397 cursor: Option<&str>,
398 ) -> Result<SearchPage, WorkspaceError> {
399 self.root(id)?;
400 let limit = limit.clamp(1, 100);
401 let offset = cursor
402 .unwrap_or("0")
403 .parse::<usize>()
404 .map_err(|_| WorkspaceError("invalid cursor".into()))?;
405 let needle = crate::sessions::cap(&query.trim().to_lowercase(), 256);
406 let mut pending = vec![String::new()];
407 let mut matches = Vec::new();
408 let mut scanned = 0;
409 let mut truncated = false;
410 while let Some(path) = pending.pop() {
411 for entry in self.tree(id, &path)? {
412 scanned += 1;
413 if scanned >= 20000 || matches.len() >= 500 {
414 truncated = true;
415 break;
416 }
417 if entry.kind == "dir" {
418 pending.push(entry.path);
419 } else if !binary(&entry.path) && entry.path.to_lowercase().contains(&needle) {
420 matches.push(entry);
421 }
422 }
423 if truncated {
424 break;
425 }
426 }
427 matches.sort_by(|left, right| left.path.cmp(&right.path));
428 let next_cursor = (offset.saturating_add(limit) < matches.len())
429 .then(|| offset.saturating_add(limit).to_string());
430 Ok(SearchPage {
431 results: matches
432 .into_iter()
433 .skip(offset)
434 .take(limit)
435 .map(|entry| SearchResult {
436 name: entry.name,
437 path: entry.path,
438 size: entry.size.unwrap_or(0),
439 })
440 .collect(),
441 next_cursor,
442 scan_truncated: truncated,
443 })
444 }
445}
446#[derive(Debug, Clone, Deserialize, Serialize)]
447#[serde(deny_unknown_fields)]
448pub struct Hunk {
449 pub start: usize,
450 pub end: usize,
451 pub lines: Vec<String>,
452}
453#[derive(Debug, Clone, Deserialize, Serialize)]
454#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)]
455pub enum EditOperation {
456 Create {
457 path: String,
458 text: String,
459 },
460 Update {
461 path: String,
462 #[serde(rename = "baseHash")]
463 base_hash: String,
464 hunks: Vec<Hunk>,
465 },
466 Delete {
467 path: String,
468 #[serde(rename = "baseHash")]
469 base_hash: String,
470 },
471}
472#[derive(Debug, Clone, Deserialize, Serialize)]
473#[serde(rename_all = "camelCase", deny_unknown_fields)]
474pub struct EditProposal {
475 pub workspace_id: String,
476 pub operations: Vec<EditOperation>,
477}
478#[derive(Debug, Serialize, Deserialize)]
479#[serde(rename_all = "camelCase", deny_unknown_fields)]
480struct PlannedFile {
481 path: String,
482 op: String,
483 before_hash: String,
484 result_hash: String,
485 original: Option<String>,
486 new_text: Option<String>,
487}
488#[derive(Debug, Serialize)]
489#[serde(rename_all = "camelCase")]
490pub struct EditReview {
491 pub proposal_id: String,
492 #[serde(skip)]
493 workspace_id: String,
494 #[serde(skip)]
495 files: Vec<PlannedFile>,
496 #[serde(rename = "files")]
497 pub reviewed_files: Vec<ReviewFile>,
498 pub warnings: Vec<String>,
499}
500#[derive(Debug, Serialize)]
501#[serde(rename_all = "camelCase")]
502pub struct ReviewFile {
503 pub path: String,
504 pub op: String,
505 #[serde(skip_serializing_if = "Option::is_none")]
506 pub base_hash: Option<String>,
507 pub result_hash: String,
508 pub added: usize,
509 pub removed: usize,
510 pub hunks: Vec<DiffHunk>,
511 pub warnings: Vec<String>,
512}
513#[derive(Debug, Serialize)]
514pub struct DiffHunk {
515 pub header: String,
516 pub lines: Vec<DiffLine>,
517}
518#[derive(Debug, Serialize)]
519pub struct DiffLine {
520 #[serde(rename = "type")]
521 pub kind: String,
522 pub text: String,
523}
524fn diff_review(file: &PlannedFile, operation: &EditOperation) -> ReviewFile {
525 let line = |kind: &str, text: &str| DiffLine {
526 kind: kind.into(),
527 text: text.into(),
528 };
529 let mut added = 0;
530 let mut removed = 0;
531 let hunks = match operation {
532 EditOperation::Create { text, .. } => {
533 let lines: Vec<_> = text.split('\n').map(|text| line("add", text)).collect();
534 added = lines.len();
535 vec![DiffHunk {
536 header: format!("@@ +1,{added} @@"),
537 lines,
538 }]
539 }
540 EditOperation::Delete { .. } => {
541 let lines: Vec<_> = file
542 .original
543 .as_deref()
544 .unwrap_or("")
545 .split('\n')
546 .map(|text| line("del", text))
547 .collect();
548 removed = lines.len();
549 vec![DiffHunk {
550 header: format!("@@ -1,{removed} @@"),
551 lines,
552 }]
553 }
554 EditOperation::Update { hunks, .. } => {
555 let base: Vec<_> = file.original.as_deref().unwrap_or("").split('\n').collect();
556 let mut ordered = hunks.clone();
557 ordered.sort_by_key(|hunk| hunk.start);
558 ordered
559 .iter()
560 .map(|hunk| {
561 let start = hunk.start - 1;
562 let deleted = hunk.end - start;
563 added += hunk.lines.len();
564 removed += deleted;
565 let mut lines: Vec<_> = base[start.saturating_sub(3)..start]
566 .iter()
567 .map(|text| line("context", text))
568 .collect();
569 lines.extend(base[start..hunk.end].iter().map(|text| line("del", text)));
570 lines.extend(hunk.lines.iter().map(|text| line("add", text)));
571 lines.extend(
572 base[hunk.end..(hunk.end + 3).min(base.len())]
573 .iter()
574 .map(|text| line("context", text)),
575 );
576 DiffHunk {
577 header: format!(
578 "@@ -{},{deleted} +{},{} @@",
579 hunk.start,
580 hunk.start,
581 hunk.lines.len()
582 ),
583 lines,
584 }
585 })
586 .collect()
587 }
588 };
589 ReviewFile {
590 path: file.path.clone(),
591 op: file.op.clone(),
592 base_hash: (file.op != "create").then(|| file.before_hash.clone()),
593 result_hash: file.result_hash.clone(),
594 added,
595 removed,
596 hunks,
597 warnings: if file.op == "update" && added + removed > 2000 {
598 vec!["large change; review carefully".into()]
599 } else {
600 Vec::new()
601 },
602 }
603}
604#[derive(Debug, Serialize, Deserialize)]
605#[serde(rename_all = "camelCase", deny_unknown_fields)]
606struct RecordFile {
607 path: String,
608 op: String,
609 before_hash: String,
610 after_hash: String,
611 #[serde(skip_serializing_if = "Option::is_none")]
612 original: Option<String>,
613}
614#[derive(Debug, Serialize, Deserialize)]
615#[serde(rename_all = "camelCase", deny_unknown_fields)]
616struct ApplyRecord {
617 schema_version: u8,
618 application_id: String,
619 workspace_id: String,
620 created_at: String,
621 #[serde(default, skip_serializing_if = "Option::is_none")]
622 root_identity: Option<String>,
623 files: Vec<RecordFile>,
624}
625#[derive(Debug, Serialize)]
626#[serde(rename_all = "camelCase")]
627pub struct ApplyResult {
628 pub application_id: String,
629 pub files: Vec<String>,
630}
631#[derive(Debug, Serialize)]
632#[serde(rename_all = "camelCase")]
633pub struct RevertResult {
634 pub application_id: String,
635 pub reverted: Vec<String>,
636 pub skipped: Vec<String>,
637}
638impl WorkspaceService {
639 fn root_identity(&self, id: &str) -> Result<String, WorkspaceError> {
640 let root = self.root(id)?;
641 let metadata = fs::metadata(&root.path)?;
642 #[cfg(unix)]
643 let identity = {
644 use std::os::unix::fs::MetadataExt;
645 format!(
646 "{}:{}:{}",
647 root.path.display(),
648 metadata.dev(),
649 metadata.ino()
650 )
651 };
652 #[cfg(not(unix))]
653 let identity = format!("{}:{:?}", root.path.display(), metadata.created()?);
654 Ok(hash(&identity))
655 }
656 pub fn recover(
657 &self,
658 workspace_id: &str,
659 records: &Path,
660 ) -> Result<Vec<RevertResult>, WorkspaceError> {
661 let identity = self.root_identity(workspace_id)?;
662 let guard = self.edit_lock(workspace_id, records)?;
663 let mut results = Vec::new();
664 for (index, entry) in fs::read_dir(records)?.enumerate() {
665 if index >= 10000 {
666 return Err(WorkspaceError("edit journal count exceeds limit".into()));
667 }
668 let entry = entry?;
669 let name = entry.file_name().to_string_lossy().into_owned();
670 let Some(id) = name.strip_suffix(".pending.json") else {
671 continue;
672 };
673 if uuid::Uuid::parse_str(id).is_err() {
674 return Err(WorkspaceError("invalid pending journal name".into()));
675 }
676 let raw = crate::state::secure_read(&entry.path(), 16 * 1024 * 1024, true)
677 .map_err(|error| WorkspaceError(error.to_string()))?;
678 let record: ApplyRecord = serde_json::from_str(&raw)?;
679 if record.root_identity.as_deref() != Some(&identity) {
680 continue;
681 }
682 if record.schema_version != 1
683 || record.application_id != id
684 || record.files.is_empty()
685 || record.files.len() > 20
686 {
687 return Err(WorkspaceError("invalid recovery journal".into()));
688 }
689 for file in &record.files {
690 if !["create", "update"].contains(&file.op.as_str())
691 || file.op == "update"
692 && file.original.as_ref().is_none_or(|text| {
693 text.len() > 512 * 1024 || hash(text) != file.before_hash
694 })
695 {
696 return Err(WorkspaceError("invalid recovery bytes".into()));
697 }
698 }
699 let mut reverted = Vec::new();
700 let mut skipped = Vec::new();
701 for file in record.files.iter().rev() {
702 guard
703 .assert_owned()
704 .map_err(|error| WorkspaceError(error.to_string()))?;
705 let path = self.resolve(workspace_id, &file.path, true)?;
706 if file.op == "create" && !path.try_exists()? {
707 continue;
708 }
709 let current = self.text(workspace_id, &file.path, 512 * 1024);
710 if current
711 .as_ref()
712 .is_ok_and(|text| hash(text) == file.before_hash)
713 {
714 continue;
715 }
716 if !current.is_ok_and(|text| hash(&text) == file.after_hash) {
717 skipped.push(file.path.clone());
718 continue;
719 }
720 if file.op == "create" {
721 self.remove_text(workspace_id, &file.path)?;
722 } else {
723 self.replace_text(
724 workspace_id,
725 &file.path,
726 file.original
727 .as_deref()
728 .ok_or_else(|| WorkspaceError("missing original bytes".into()))?,
729 false,
730 )?;
731 }
732 reverted.push(file.path.clone());
733 }
734 if skipped.is_empty() {
735 fs::rename(entry.path(), records.join(format!("{id}.recovered.json")))?;
736 }
737 results.push(RevertResult {
738 application_id: id.into(),
739 reverted,
740 skipped,
741 });
742 }
743 guard
744 .release()
745 .map_err(|error| WorkspaceError(error.to_string()))?;
746 Ok(results)
747 }
748 pub fn review(&self, proposal: &EditProposal) -> Result<EditReview, WorkspaceError> {
749 self.root(&proposal.workspace_id)?;
750 if proposal.operations.is_empty() || proposal.operations.len() > 20 {
751 return Err(WorkspaceError("invalid edit operation count".into()));
752 }
753 let mut seen = HashSet::new();
754 let mut files = Vec::new();
755 let mut reviewed_files = Vec::new();
756 for operation in &proposal.operations {
757 let path = match operation {
758 EditOperation::Create { path, .. }
759 | EditOperation::Update { path, .. }
760 | EditOperation::Delete { path, .. } => relative_path(path)?,
761 };
762 if path.is_empty()
763 || denied(&path)
764 || binary(&path)
765 || !seen.insert(path.to_lowercase())
766 {
767 return Err(WorkspaceError("unsafe or duplicate edit path".into()));
768 }
769 let (op, original, new_text) = match operation {
770 EditOperation::Create { text, .. } => {
771 let target = self.resolve(&proposal.workspace_id, &path, true)?;
772 if fs::symlink_metadata(target).is_ok() {
773 return Err(WorkspaceError("create target exists".into()));
774 }
775 ("create", None, Some(text.clone()))
776 }
777 EditOperation::Delete { base_hash, .. } => {
778 let snapshot = self.read(&proposal.workspace_id, &path, None)?;
779 if snapshot.hash != *base_hash {
780 return Err(WorkspaceError("stale edit base".into()));
781 }
782 ("delete", Some(snapshot.content), None)
783 }
784 EditOperation::Update {
785 base_hash, hunks, ..
786 } => {
787 let snapshot = self.read(&proposal.workspace_id, &path, None)?;
788 if snapshot.hash != *base_hash {
789 return Err(WorkspaceError("stale edit base".into()));
790 }
791 if hunks.is_empty() || hunks.len() > 100 {
792 return Err(WorkspaceError("invalid hunk count".into()));
793 }
794 let base: Vec<_> = snapshot.content.split('\n').collect();
795 let mut cursor = 0;
796 let mut output = Vec::new();
797 let mut ordered = hunks.clone();
798 ordered.sort_by_key(|hunk| hunk.start);
799 for hunk in ordered {
800 if hunk.start == 0
801 || hunk.start - 1 < cursor
802 || hunk.start > base.len() + 1
803 || hunk.end < hunk.start - 1
804 || hunk.end > base.len()
805 || hunk.lines.len() > 2000
806 || hunk
807 .lines
808 .iter()
809 .any(|line| line.contains(['\n', '\r', '\0']))
810 {
811 return Err(WorkspaceError("overlapping or invalid hunk".into()));
812 }
813 output.extend(
814 base[cursor..hunk.start - 1]
815 .iter()
816 .map(|line| (*line).to_owned()),
817 );
818 output.extend(hunk.lines);
819 cursor = hunk.end;
820 }
821 output.extend(base[cursor..].iter().map(|line| (*line).to_owned()));
822 ("update", Some(snapshot.content), Some(output.join("\n")))
823 }
824 };
825 if new_text
826 .as_ref()
827 .is_some_and(|text| text.len() > 512 * 1024 || text.contains('\0'))
828 {
829 return Err(WorkspaceError("binary or oversized edit content".into()));
830 }
831 let file = PlannedFile {
832 path,
833 op: op.into(),
834 before_hash: original.as_ref().map(|text| hash(text)).unwrap_or_default(),
835 result_hash: new_text.as_ref().map(|text| hash(text)).unwrap_or_default(),
836 original,
837 new_text,
838 };
839 reviewed_files.push(diff_review(&file, operation));
840 files.push(file);
841 }
842 let warnings = if reviewed_files.iter().any(|file| !file.warnings.is_empty()) {
843 vec!["some files reported warnings; review carefully".into()]
844 } else {
845 Vec::new()
846 };
847 Ok(EditReview {
848 proposal_id: uuid::Uuid::new_v4().to_string(),
849 workspace_id: proposal.workspace_id.clone(),
850 files,
851 reviewed_files,
852 warnings,
853 })
854 }
855 fn edit_lock(
856 &self,
857 id: &str,
858 records: &Path,
859 ) -> Result<crate::state::LockGuard, WorkspaceError> {
860 let root = self.root(id)?;
861 crate::memory::owned_directory(records)?;
862 let mut config = crate::state::Config::from_home(records)
863 .map_err(|error| WorkspaceError(error.to_string()))?;
864 config.lock = records.join(format!(
865 "workspace-{}.lock",
866 hash(&root.path.to_string_lossy())
867 ));
868 crate::state::StateStore::new(config)
869 .lock(Duration::from_secs(10))
870 .map_err(|error| WorkspaceError(error.to_string()))
871 }
872 pub fn apply(
873 &self,
874 review: EditReview,
875 records: &Path,
876 timestamp: &str,
877 ) -> Result<ApplyResult, WorkspaceError> {
878 self.apply_with(review, records, timestamp, |_| Ok(()))
879 }
880 pub fn apply_with(
881 &self,
882 review: EditReview,
883 records: &Path,
884 timestamp: &str,
885 before: impl Fn(usize) -> Result<(), WorkspaceError>,
886 ) -> Result<ApplyResult, WorkspaceError> {
887 if review.files.iter().any(|file| file.op == "delete") {
888 return Err(WorkspaceError("delete apply is not enabled".into()));
889 }
890 let guard = self.edit_lock(&review.workspace_id, records)?;
891 for file in &review.files {
892 let path = self.resolve(&review.workspace_id, &file.path, file.op == "create")?;
893 if file.op == "create" {
894 if fs::symlink_metadata(&path).is_ok() {
895 return Err(WorkspaceError("create target appeared".into()));
896 }
897 } else if hash(&self.text(&review.workspace_id, &file.path, 512 * 1024)?)
898 != file.before_hash
899 {
900 return Err(WorkspaceError("stale edit approval".into()));
901 }
902 }
903 let id = uuid::Uuid::new_v4().to_string();
904 let record = ApplyRecord {
905 schema_version: 1,
906 application_id: id.clone(),
907 workspace_id: review.workspace_id.clone(),
908 created_at: timestamp.into(),
909 root_identity: Some(self.root_identity(&review.workspace_id)?),
910 files: review
911 .files
912 .iter()
913 .map(|file| RecordFile {
914 path: file.path.clone(),
915 op: file.op.clone(),
916 before_hash: file.before_hash.clone(),
917 after_hash: file.result_hash.clone(),
918 original: file.original.clone(),
919 })
920 .collect(),
921 };
922 let pending = records.join(format!("{id}.pending.json"));
923 crate::memory::atomic_file(&pending, serde_json::to_vec_pretty(&record)?.as_slice())?;
924 let mut replaced = 0;
925 let result = (|| {
926 for (index, file) in review.files.iter().enumerate() {
927 before(index)?;
928 guard
929 .assert_owned()
930 .map_err(|error| WorkspaceError(error.to_string()))?;
931 let path = self.resolve(&review.workspace_id, &file.path, file.op == "create")?;
932 if file.op == "create" {
933 if fs::symlink_metadata(&path).is_ok() {
934 return Err(WorkspaceError("create target appeared".into()));
935 }
936 } else {
937 if hash(&self.text(&review.workspace_id, &file.path, 512 * 1024)?)
938 != file.before_hash
939 {
940 return Err(WorkspaceError(
941 "edit target changed before publication".into(),
942 ));
943 }
944 }
945 self.replace_text(
946 &review.workspace_id,
947 &file.path,
948 file.new_text
949 .as_deref()
950 .ok_or_else(|| WorkspaceError("missing edit bytes".into()))?,
951 file.op == "create",
952 )?;
953 replaced += 1;
954 }
955 fs::rename(&pending, records.join(format!("{id}.json")))?;
956 Ok::<_, WorkspaceError>(())
957 })();
958 if let Err(error) = result {
959 for file in review.files.iter().take(replaced).rev() {
960 self.resolve(&review.workspace_id, &file.path, false)?;
961 if hash(&self.text(&review.workspace_id, &file.path, 512 * 1024)?)
962 != file.result_hash
963 {
964 return Err(WorkspaceError(
965 "rollback refused changed file; recovery record retained".into(),
966 ));
967 }
968 if let Some(original) = &file.original {
969 self.replace_text(&review.workspace_id, &file.path, original, false)?;
970 } else {
971 self.remove_text(&review.workspace_id, &file.path)?;
972 }
973 }
974 fs::remove_file(pending)?;
975 return Err(error);
976 }
977 guard
978 .release()
979 .map_err(|error| WorkspaceError(error.to_string()))?;
980 Ok(ApplyResult {
981 application_id: id,
982 files: review.files.into_iter().map(|file| file.path).collect(),
983 })
984 }
985 pub fn revert(&self, id: &str, records: &Path) -> Result<RevertResult, WorkspaceError> {
986 if uuid::Uuid::parse_str(id).is_err() {
987 return Err(WorkspaceError("invalid application id".into()));
988 }
989 let raw =
990 crate::state::secure_read(&records.join(format!("{id}.json")), 16 * 1024 * 1024, true)
991 .map_err(|error| WorkspaceError(error.to_string()))?;
992 let record: ApplyRecord = serde_json::from_str(&raw)?;
993 if record.schema_version != 1 || record.application_id != id || record.files.len() > 20 {
994 return Err(WorkspaceError("invalid apply record".into()));
995 }
996 let guard = self.edit_lock(&record.workspace_id, records)?;
997 let mut reverted = Vec::new();
998 let mut skipped = Vec::new();
999 for file in record.files.iter().rev() {
1000 let current = self.text(&record.workspace_id, &file.path, 512 * 1024);
1001 if !current.is_ok_and(|text| hash(&text) == file.after_hash) {
1002 skipped.push(file.path.clone());
1003 continue;
1004 }
1005 self.resolve(&record.workspace_id, &file.path, false)?;
1006 if file.op == "create" {
1007 self.remove_text(&record.workspace_id, &file.path)?;
1008 } else if file.op == "update" {
1009 let original = file
1010 .original
1011 .as_ref()
1012 .ok_or_else(|| WorkspaceError("missing rollback content".into()))?;
1013 if hash(original) != file.before_hash {
1014 return Err(WorkspaceError("rollback content mismatch".into()));
1015 }
1016 self.replace_text(&record.workspace_id, &file.path, original, false)?;
1017 } else {
1018 return Err(WorkspaceError("invalid rollback operation".into()));
1019 }
1020 reverted.push(file.path.clone());
1021 }
1022 guard
1023 .release()
1024 .map_err(|error| WorkspaceError(error.to_string()))?;
1025 Ok(RevertResult {
1026 application_id: id.into(),
1027 reverted,
1028 skipped,
1029 })
1030 }
1031}