Skip to main content

rigspark_runtime/
workspace.rs

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