workspace-mgr 0.8.6

Fixed-policy repository workspace manager for coding agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::config::{Config, require_supported_cli_at};
use crate::error::{Error, IoContext, Result};
use crate::git::GitRepo;
use crate::lock::RepositoryLock;
use crate::manifest::{
    ResolvedTask, TaskKind, build_task_path, parse_task_identity, validate_additional_scopes,
    validate_task_slug,
};
use crate::path::{reject_symlink_traversal, resolved_under};
use crate::policy::TASK_MANIFEST_NAME;
use crate::relocation::{RelocationNotice, RelocationPlan};
use crate::storage_metadata;
use crate::transaction::validate_remote_task_identity;

#[derive(Debug, Clone)]
pub struct TaskRenameOptions {
    pub start: PathBuf,
    pub manifest: Option<PathBuf>,
    pub new_slug: String,
    pub dry_run: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct TaskRenameReport {
    pub status: String,
    pub operation: String,
    pub kind: TaskKind,
    pub task_id: String,
    pub old_slug: String,
    pub new_slug: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_path: Option<String>,
    pub old_manifest: String,
    pub new_manifest: String,
    pub branch: String,
    pub local_branch_oid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_branch_oid: Option<String>,
    pub local_actions: Vec<TaskRenameAction>,
    pub remote_writes: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub notices: Vec<RelocationNotice>,
    pub review: TaskRenameReview,
}

#[derive(Debug, Clone, Serialize)]
pub struct TaskRenameAction {
    pub action: &'static str,
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct TaskRenameReview {
    pub head_branch_unchanged: bool,
    pub pull_request: &'static str,
    pub agent_action: &'static str,
}

pub fn rename(options: &TaskRenameOptions) -> Result<TaskRenameReport> {
    validate_task_slug(&options.new_slug)?;
    let task_repo = match &options.manifest {
        Some(path) => GitRepo::discover_for_manifest(path)?,
        None => GitRepo::discover(&options.start)?,
    };
    let _repository_lock = RepositoryLock::acquire(&task_repo)?;
    let config = Config::load_compatible(&task_repo)?;
    let manifest_path = match &options.manifest {
        Some(path) => path.clone(),
        None => ResolvedTask::discover(&task_repo, &options.start)?,
    };
    let task = ResolvedTask::load(&task_repo, &config, &manifest_path)?;
    crate::cloud_usage::remind(&task_repo, &task);
    if task.slug == options.new_slug {
        return Err(Error::message(format!(
            "task already uses slug {:?}",
            options.new_slug
        )));
    }
    task_repo.validate_branch(&task.branch)?;
    task_repo.validate_remote_name(&task.remote)?;
    validate_checkout(&task_repo, &task, "task rename")?;

    let identity = parse_task_identity(task.kind, &task.task_id)?;
    let new_task_path =
        (task.kind == TaskKind::Deliverable).then(|| build_task_path(&identity, &options.new_slug));
    validate_additional_scopes(new_task_path.as_deref(), task.additional_scopes.clone())?;
    let local_branch_oid = task_repo
        .optional_oid(&format!("refs/heads/{}", task.branch))?
        .ok_or_else(|| Error::message("task local branch does not exist"))?;
    let remote_base_oid = task_repo.fetch_branch(&task.remote, &task.base_branch)?;
    // The shared branch may already require a newer workspace-mgr than the
    // local checkout declares.
    require_supported_cli_at(
        &task_repo,
        &remote_base_oid,
        &format!("{}/{}", task.remote, task.base_branch),
    )?;
    let remote_branch_oid = inspect_remote_task(&task_repo, &task, &remote_base_oid)?;
    validate_paths(
        &task_repo,
        &task,
        new_task_path.as_deref(),
        &remote_base_oid,
        remote_branch_oid.as_deref(),
    )?;
    let relocation = match (&task.task_path, &new_task_path) {
        (Some(old), Some(new)) => {
            crate::nested_git::validate_move(&task_repo, old, new)?;
            Some(RelocationPlan::opaque(
                &resolved_under(&task_repo.root, old),
                &resolved_under(&task_repo.root, new),
            )?)
        }
        _ => None,
    };

    // The rewritten manifest keeps every other field, including a recorded
    // cloud-usage approval, and uses the lowest schema that represents it.
    let mut new_manifest = task.manifest();
    new_manifest.slug = options.new_slug.clone();
    new_manifest.path = new_task_path.clone();
    let rendered = new_manifest.render()?;
    let new_manifest_path = match &new_task_path {
        Some(path) => resolved_under(&task_repo.root, &format!("{path}/{TASK_MANIFEST_NAME}")),
        None => task.manifest_path.clone(),
    };
    let local_actions = match (&task.task_path, &new_task_path) {
        (Some(old), Some(new)) => vec![
            TaskRenameAction {
                action: "move-directory",
                from: old.clone(),
                to: new.clone(),
            },
            TaskRenameAction {
                action: "rewrite-manifest",
                from: task.manifest_path.display().to_string(),
                to: new_manifest_path.display().to_string(),
            },
        ],
        (None, None) => vec![TaskRenameAction {
            action: "rewrite-private-manifest",
            from: task.manifest_path.display().to_string(),
            to: new_manifest_path.display().to_string(),
        }],
        _ => unreachable!(),
    };

    if !options.dry_run {
        apply_rename(
            &task_repo,
            &config,
            &task,
            new_task_path.as_deref(),
            &rendered,
            relocation.as_ref(),
        )?;
    }

    Ok(TaskRenameReport {
        status: if options.dry_run {
            "dry_run"
        } else {
            "renamed"
        }
        .to_owned(),
        operation: "task-rename".to_owned(),
        kind: task.kind,
        task_id: task.task_id,
        old_slug: task.slug,
        new_slug: options.new_slug.clone(),
        old_path: task.task_path,
        new_path: new_task_path,
        old_manifest: task.manifest_path.display().to_string(),
        new_manifest: new_manifest_path.display().to_string(),
        branch: task.branch,
        local_branch_oid,
        remote_branch_oid,
        local_actions,
        remote_writes: false,
        notices: if !options.dry_run && relocation.is_some() {
            vec![RelocationNotice::renamed_directory()]
        } else {
            Vec::new()
        },
        review: TaskRenameReview {
            head_branch_unchanged: true,
            pull_request: "reuse-existing-draft",
            agent_action: "update the existing pull request title and description after the renamed task is published",
        },
    })
}

/// Every writable task uses the shared checkout on the base branch.
/// `operation` names the command in refusals.
pub(crate) fn validate_checkout(
    repo: &GitRepo,
    task: &ResolvedTask,
    operation: &str,
) -> Result<()> {
    let current = repo.current_branch()?;
    if current.as_deref() != Some(&task.base_branch) {
        return Err(Error::message(format!(
            "{:?} {operation} must run from the shared checkout on {:?}; current branch is {:?}",
            task.kind,
            task.base_branch,
            current.as_deref().unwrap_or("detached HEAD")
        )));
    }
    repo.ensure_branch_not_checked_out(&task.branch)?;
    Ok(())
}

fn inspect_remote_task(
    repo: &GitRepo,
    task: &ResolvedTask,
    remote_base_oid: &str,
) -> Result<Option<String>> {
    let Some(observed) = repo.remote_branch_oid(&task.remote, &task.branch)? else {
        return Ok(None);
    };
    let fetched = repo.fetch_branch(&task.remote, &task.branch)?;
    if fetched != observed {
        return Err(Error::message(
            "task branch changed while rename state was being inspected; retry",
        ));
    }
    validate_remote_task_identity(repo, task, &fetched)?;
    // A newer release may have published the task branch with a declaration
    // this one does not meet.
    require_supported_cli_at(repo, &fetched, &format!("{}/{}", task.remote, task.branch))?;
    let merged = repo.run_unchecked(["merge-base", "--is-ancestor", &fetched, remote_base_oid])?;
    match merged.code {
        0 => Err(Error::message(
            "task branch is already contained in the remote shared branch; merged tasks cannot be renamed",
        )),
        1 => Ok(Some(fetched)),
        _ => Err(Error::message(
            "failed to determine whether the task branch was merged",
        )),
    }
}

fn validate_paths(
    repo: &GitRepo,
    task: &ResolvedTask,
    new_task_path: Option<&str>,
    remote_base_oid: &str,
    remote_branch_oid: Option<&str>,
) -> Result<()> {
    let (Some(old_path), Some(new_path)) = (task.task_path.as_deref(), new_task_path) else {
        return Ok(());
    };
    reject_symlink_traversal(&repo.root, old_path, "task rename source")?;
    reject_symlink_traversal(&repo.root, new_path, "task rename destination")?;
    let old = resolved_under(&repo.root, old_path);
    let metadata = fs::symlink_metadata(&old).at(&old)?;
    if !metadata.is_dir() || metadata.file_type().is_symlink() {
        return Err(Error::message(format!(
            "task rename source must be an ordinary directory: {old_path}"
        )));
    }
    let new = resolved_under(&repo.root, new_path);
    if path_exists(&new)? {
        return Err(Error::message(format!(
            "task rename destination already exists: {new_path}"
        )));
    }
    let staged = repo.run_unchecked(["diff", "--cached", "--quiet", "--", old_path, new_path])?;
    match staged.code {
        0 => {}
        1 => {
            return Err(Error::message(
                "task rename refuses staged changes in the source or destination; unstage them first",
            ));
        }
        _ => return Err(Error::message("failed to inspect staged task changes")),
    }
    if tree_path_exists(repo, remote_base_oid, old_path)? {
        return Err(Error::message(
            "task directory already exists in the remote shared branch; merged tasks cannot be renamed",
        ));
    }
    let destination_is_published = tree_path_exists(repo, remote_base_oid, new_path)?
        || match remote_branch_oid {
            Some(oid) => tree_path_exists(repo, oid, new_path)?,
            None => false,
        };
    if destination_is_published {
        return Err(Error::message(format!(
            "task rename destination already exists in published Git history: {new_path}"
        )));
    }
    Ok(())
}

fn apply_rename(
    repo: &GitRepo,
    config: &Config,
    task: &ResolvedTask,
    new_task_path: Option<&str>,
    rendered: &str,
    relocation: Option<&RelocationPlan>,
) -> Result<()> {
    match (task.task_path.as_deref(), new_task_path) {
        (Some(old_path), Some(new_path)) => {
            let old = resolved_under(&repo.root, old_path);
            let new = resolved_under(&repo.root, new_path);
            let original = fs::read_to_string(&task.manifest_path).at(&task.manifest_path)?;
            let pointer_snapshots = moved_pointer_snapshots(repo, old_path, new_path)?;
            fs::rename(&old, &new).at(&old)?;
            let new_manifest = new.join(TASK_MANIFEST_NAME);
            let mut changed_pointers = Vec::new();
            let mut manifest_rewritten = false;
            let result = (|| {
                if let Some(relocation) = relocation {
                    relocation.apply()?;
                }
                for (index, snapshot) in pointer_snapshots.iter().enumerate() {
                    if storage_metadata::reset_moved_pointer_cloud_metadata(
                        repo,
                        &snapshot.new_path,
                    )? {
                        changed_pointers.push(index);
                    }
                }
                atomic_write(&new_manifest, rendered)?;
                manifest_rewritten = true;
                ResolvedTask::load(repo, config, &new_manifest).map(|_| ())
            })();
            if let Err(error) = result {
                let rollback = rollback_deliverable(
                    &new,
                    &old,
                    manifest_rewritten.then_some((&new_manifest, original.as_str())),
                    &pointer_snapshots,
                    &changed_pointers,
                    relocation,
                );
                return Err(rollback_error(error, rollback));
            }
            Ok(())
        }
        (None, None) => {
            let original = fs::read_to_string(&task.manifest_path).at(&task.manifest_path)?;
            atomic_write(&task.manifest_path, rendered)?;
            if let Err(error) = ResolvedTask::load(repo, config, &task.manifest_path) {
                return Err(rollback_error(
                    error,
                    atomic_write(&task.manifest_path, &original),
                ));
            }
            Ok(())
        }
        _ => unreachable!(),
    }
}

#[derive(Debug)]
struct MovedPointerSnapshot {
    new_path: String,
    new_absolute: PathBuf,
    contents: String,
}

fn moved_pointer_snapshots(
    repo: &GitRepo,
    old_task_path: &str,
    new_task_path: &str,
) -> Result<Vec<MovedPointerSnapshot>> {
    storage_metadata::discover(repo, &[old_task_path.to_owned()])?
        .into_iter()
        .map(|old_pointer| {
            let relative = old_pointer
                .strip_prefix(&format!("{old_task_path}/"))
                .ok_or_else(|| Error::message("managed-storage metadata escaped the task"))?;
            let new_path = format!("{new_task_path}/{relative}");
            let contents =
                fs::read_to_string(resolved_under(&repo.root, &old_pointer)).at(&old_pointer)?;
            let new_absolute = resolved_under(&repo.root, &new_path);
            Ok(MovedPointerSnapshot {
                new_path,
                new_absolute,
                contents,
            })
        })
        .collect()
}

fn rollback_deliverable(
    new_directory: &Path,
    old_directory: &Path,
    manifest: Option<(&Path, &str)>,
    pointer_snapshots: &[MovedPointerSnapshot],
    changed_pointers: &[usize],
    relocation: Option<&RelocationPlan>,
) -> Result<()> {
    let mut rollback = Ok(());
    for index in changed_pointers {
        let snapshot = &pointer_snapshots[*index];
        rollback = combine_rollbacks(
            rollback,
            atomic_write(&snapshot.new_absolute, &snapshot.contents),
        );
    }
    if let Some((path, contents)) = manifest {
        rollback = combine_rollbacks(rollback, atomic_write(path, contents));
    }
    if let Some(relocation) = relocation
        && let Err(error) = relocation.restore()
    {
        return combine_rollbacks(rollback, Err(error));
    }
    combine_rollbacks(
        rollback,
        fs::rename(new_directory, old_directory).at(new_directory),
    )
}

fn tree_path_exists(repo: &GitRepo, oid: &str, path: &str) -> Result<bool> {
    let checked = repo.run_unchecked(["cat-file", "-e", &format!("{oid}:{path}")])?;
    match checked.code {
        0 => Ok(true),
        1 | 128 => Ok(false),
        _ => Err(Error::message(format!(
            "failed to inspect published task path {path:?}"
        ))),
    }
}

fn path_exists(path: &Path) -> Result<bool> {
    match fs::symlink_metadata(path) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(source) => Err(Error::Io {
            path: path.to_path_buf(),
            source,
        }),
    }
}

pub(crate) fn atomic_write(path: &Path, contents: &str) -> Result<()> {
    let parent = path
        .parent()
        .ok_or_else(|| Error::message("task manifest has no parent"))?;
    let mut temporary = tempfile::NamedTempFile::new_in(parent).at(parent)?;
    temporary.write_all(contents.as_bytes()).at(path)?;
    if let Ok(metadata) = fs::metadata(path) {
        temporary
            .as_file()
            .set_permissions(metadata.permissions())
            .at(path)?;
    }
    temporary.flush().at(path)?;
    temporary.persist(path).map_err(|error| Error::Io {
        path: path.to_path_buf(),
        source: error.error,
    })?;
    Ok(())
}

fn rollback_error(error: Error, rollback: Result<()>) -> Error {
    match rollback {
        Ok(()) => error,
        Err(rollback) => Error::message(format!(
            "task rename failed: {error}; rollback also failed: {rollback}"
        )),
    }
}

fn combine_rollbacks(first: Result<()>, second: Result<()>) -> Result<()> {
    match (first, second) {
        (Ok(()), Ok(())) => Ok(()),
        (Err(first), Ok(())) => Err(first),
        (Ok(()), Err(second)) => Err(second),
        (Err(first), Err(second)) => Err(Error::message(format!(
            "manifest rollback failed: {first}; directory rollback failed: {second}"
        ))),
    }
}