Skip to main content

speccoder_runtime/
in_place.rs

1//! In-place runs: `speccoder run --in-place` works on
2//! `speccoder/<feature>` in the person's own checkout instead of a separate
3//! worktree — the way to run features whose spec git ignores (a worktree
4//! holds only commits).
5//!
6//! What the worktree gave, replaced:
7//! - a clean checkout before the run, and the person's branch never touched:
8//!   the run switches to `speccoder/<feature>` and back;
9//! - an intent the run cannot read differently later: every intent, judge
10//!   and context file — git-ignored ones included — is hashed when the run
11//!   starts (the manifest) and re-checked before every task and every tick;
12//!   only the engine's own one-byte tick and convergence append change it;
13//! - a checkout nobody else changes: HEAD, the branch and a clean tree are
14//!   re-checked before every task and tick (the checkout guard).
15//!
16//! Evidence is committed before the tick: a gitignored `tasks.md` is never in
17//! a commit, so its tick is local, and the commit says so (`Tick: local`).
18
19use std::collections::BTreeMap;
20use std::path::{Path, PathBuf};
21
22use serde::{Deserialize, Serialize};
23use speccoder_core::{CommandData, CommandResult, CommandStatus, InPlaceReport, RefusedPath};
24
25use crate::git::Git;
26use crate::integrity::{JudgeSnapshot, sha256_hex};
27use crate::tools::policy::Policy;
28use crate::worktree;
29
30/// The session record in a project's state directory.
31pub const FILE: &str = "in-place.json";
32
33/// Runtime state under the intent that is not intent.
34fn runtime_state(path: &str) -> bool {
35    path.contains("/workflows/runs/") || path.split('/').any(|c| c == "__pycache__")
36}
37
38/// Why an in-place run refuses or stops.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct InPlaceError {
41    /// `DIRTY-CHECKOUT`, `INTENT-CHANGED`, ….
42    pub code: &'static str,
43    /// What happened.
44    pub message: String,
45    /// The paths involved, with why.
46    pub paths: Vec<(String, String)>,
47    /// What to run: the first is `fix:`, the rest `or:`.
48    pub fix: Vec<String>,
49}
50
51impl InPlaceError {
52    fn new(code: &'static str, message: impl Into<String>) -> Self {
53        Self {
54            code,
55            message: message.into(),
56            paths: Vec::new(),
57            fix: Vec::new(),
58        }
59    }
60
61    fn fix(mut self, lines: &[&str]) -> Self {
62        self.fix = lines.iter().map(|l| (*l).to_owned()).collect();
63        self
64    }
65
66    /// A stop during the run (exit 23) rather than a refusal before it (14).
67    #[must_use]
68    pub fn is_stop(&self) -> bool {
69        matches!(
70            self.code,
71            "INTENT-CHANGED"
72                | "JUDGE-CHANGED"
73                | "CHECKOUT-CHANGED"
74                | "GIT-CHANGED"
75                | "RETURN-BLOCKED"
76        )
77    }
78
79    /// One line naming the code, for a run report's reason and a saved
80    /// attempt: `stopped[INTENT-CHANGED]: … (specs/x/spec.md: changed)`.
81    #[must_use]
82    pub fn line(&self) -> String {
83        let word = if self.is_stop() { "stopped" } else { "error" };
84        let mut line = format!("{word}[{}]: {}", self.code, self.message);
85        for (p, why) in &self.paths {
86            line.push_str(&format!("; {p} ({why})"));
87        }
88        line
89    }
90
91    /// The command's result, its code and fixes on the envelope.
92    #[must_use]
93    pub fn result(&self, command: &str) -> CommandResult {
94        let status = match self.code {
95            "IN-PLACE-PARALLEL" => CommandStatus::UsageError,
96            _ if self.is_stop() => CommandStatus::NeedsHuman,
97            _ => CommandStatus::GitPrecondition,
98        };
99        CommandResult::new(command, status, &self.message)
100            .with_code(self.code)
101            .with_fix(self.fix.clone())
102            .with_data(CommandData::InPlace(Box::new(InPlaceReport {
103                paths: self
104                    .paths
105                    .iter()
106                    .map(|(path, reason)| RefusedPath {
107                        path: path.clone(),
108                        reason: reason.clone(),
109                    })
110                    .collect(),
111            })))
112    }
113}
114
115/// The branch the person was on.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum Original {
119    /// A branch name.
120    Branch(String),
121    /// A detached commit.
122    Detached(String),
123}
124
125impl Original {
126    fn target(&self) -> &str {
127        match self {
128            Self::Branch(b) | Self::Detached(b) => b,
129        }
130    }
131
132    /// As a person reads it.
133    #[must_use]
134    pub fn describe(&self) -> String {
135        match self {
136            Self::Branch(b) => b.clone(),
137            Self::Detached(c) => format!("detached {}", c.chars().take(10).collect::<String>()),
138        }
139    }
140}
141
142/// An in-place run in progress: written before the checkout is switched,
143/// removed after it is switched back.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct Session {
146    /// The feature.
147    pub feature: String,
148    /// `speccoder/<feature>`.
149    pub branch: String,
150    /// Where the person was.
151    pub original: Original,
152    /// The checkout (the repository's root).
153    pub checkout: PathBuf,
154    /// The project root inside it.
155    pub project: PathBuf,
156    /// The branch's tip as speccoder last left it.
157    pub tip: String,
158    /// Intent, judge and context files by hash, as the run expects them.
159    pub manifest: BTreeMap<String, String>,
160    /// The running process.
161    pub pid: u32,
162    /// Seconds since the epoch.
163    pub started_at: u64,
164    /// What starting this run did on its own (a resume, work set aside, a
165    /// tick restored): told with the outcome, never recorded.
166    #[serde(skip)]
167    pub notes: Vec<String>,
168    /// What git ignored when the session began (directories end in `/`):
169    /// hidden from the model's file tools, as a worktree would not hold it.
170    #[serde(default)]
171    pub hidden: Vec<String>,
172    /// The repository's configuration, hooks, `info/` and refs (other than
173    /// the session's branch) by hash: nothing a run does may change them.
174    #[serde(default)]
175    pub git: String,
176}
177
178/// The manifest of `project`: every intent, judge and context file, ignored
179/// ones included, minus runtime state.
180#[must_use]
181pub fn manifest(project: &Path, policy: &Policy) -> BTreeMap<String, String> {
182    JudgeSnapshot::take(project, policy)
183        .entries()
184        .iter()
185        .filter(|(p, _)| !runtime_state(p))
186        .map(|(p, h)| (p.clone(), h.clone()))
187        .collect()
188}
189
190/// The paths that differ between two manifests, with how.
191#[must_use]
192pub fn diff(
193    expected: &BTreeMap<String, String>,
194    now: &BTreeMap<String, String>,
195) -> Vec<(String, String)> {
196    let mut out = Vec::new();
197    for (p, h) in expected {
198        match now.get(p) {
199            None => out.push((p.clone(), "deleted".to_owned())),
200            Some(n) if n != h => out.push((p.clone(), "modified".to_owned())),
201            _ => {}
202        }
203    }
204    for p in now.keys().filter(|p| !expected.contains_key(*p)) {
205        out.push((p.clone(), "added".to_owned()));
206    }
207    out
208}
209
210/// Whether `after` is `before` with exactly one byte changed, from a space
211/// to `x`/`X` (the engine's tick).
212#[must_use]
213pub fn is_tick(before: &[u8], after: &[u8]) -> bool {
214    let changed: Vec<(u8, u8)> = before
215        .iter()
216        .zip(after)
217        .filter(|(a, b)| a != b)
218        .map(|(a, b)| (*a, *b))
219        .collect();
220    before.len() == after.len() && matches!(changed.as_slice(), [(b' ', b'x' | b'X')])
221}
222
223/// SHA-256 over the intent files except the task lists (files named
224/// `tasks_file`, whose task lines the commits pin one by one with
225/// `Task-Line:`): what the verdict commits name (`Intent-Digest:`), so a
226/// later reader can tell the spec, plan or constitution changed — not a
227/// tick or a convergence round.
228#[must_use]
229pub fn intent_digest(project: &Path, policy: &Policy, tasks_file: &str) -> String {
230    let mut parts = Vec::new();
231    for (path, hash) in manifest(project, policy) {
232        if policy.write_protected(&path) != Some(crate::tools::paths::Class::Intent) {
233            continue;
234        }
235        if path.rsplit('/').next() == Some(tasks_file) {
236            continue;
237        }
238        parts.push(format!("{path} {hash}"));
239    }
240    sha256_hex(parts.join("\n").as_bytes())
241}
242
243pub(crate) use crate::integrity::untick;
244
245fn now() -> u64 {
246    std::time::SystemTime::now()
247        .duration_since(std::time::UNIX_EPOCH)
248        .map_or(0, |d| d.as_secs())
249}
250
251impl Session {
252    /// The record's path in a project's state directory.
253    #[must_use]
254    pub fn path(plane_dir: &Path) -> PathBuf {
255        plane_dir.join(FILE)
256    }
257
258    /// The record, if a session exists.
259    #[must_use]
260    pub fn load(plane_dir: &Path) -> Option<Self> {
261        let text = std::fs::read_to_string(Self::path(plane_dir)).ok()?;
262        serde_json::from_str(&text).ok()
263    }
264
265    /// Writes the record (temporary file, then rename).
266    pub fn save(&self, plane_dir: &Path) -> Result<(), String> {
267        std::fs::create_dir_all(plane_dir).map_err(|e| e.to_string())?;
268        let tmp = plane_dir.join(format!("{FILE}.tmp"));
269        let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
270        std::fs::write(&tmp, text).map_err(|e| e.to_string())?;
271        std::fs::rename(&tmp, Self::path(plane_dir)).map_err(|e| e.to_string())
272    }
273
274    /// Whether the process that owns it is running.
275    #[must_use]
276    pub fn is_live(&self) -> bool {
277        self.pid != std::process::id() && crate::progress::alive(self.pid)
278    }
279
280    /// Checks the preconditions, records the session, and switches the
281    /// checkout to `speccoder/<feature>`.
282    pub fn begin(
283        project: &Path,
284        plane_dir: &Path,
285        feature: &str,
286        policy: &Policy,
287    ) -> Result<Self, InPlaceError> {
288        let root_of = Git::at(project).toplevel().ok().flatten().ok_or_else(|| {
289            InPlaceError::new("UNBORN-HEAD", "the project is not inside a git repository")
290                .fix(&["git init && git add -A && git commit -m init"])
291        })?;
292        let checkout = std::fs::canonicalize(&root_of).unwrap_or(root_of);
293        let project = std::fs::canonicalize(project).unwrap_or_else(|_| project.to_path_buf());
294        let git = Git::at(&checkout);
295        if let Some(s) = Self::load(plane_dir).filter(Self::is_live) {
296            return Err(InPlaceError::new(
297                "IN-PLACE-ACTIVE",
298                format!(
299                    "an in-place run of {} is running (pid {})",
300                    s.feature, s.pid
301                ),
302            ));
303        }
304        if git.head().ok().flatten().is_none() {
305            return Err(
306                InPlaceError::new("UNBORN-HEAD", "the repository has no commits yet")
307                    .fix(&["git add -A && git commit -m init"]),
308            );
309        }
310        // A run of this feature that died on its branch, at the commit it
311        // recorded: with the intent unchanged it is taken over — an attempt
312        // the journal can resume resumes; with the intent changed, what it
313        // left is saved and the task starts fresh.
314        let mut notes = Vec::new();
315        if let Some(mut prior) = Self::load(plane_dir).filter(|p| {
316            p.feature == feature
317                && git
318                    .line(&["symbolic-ref", "-q", "HEAD"])
319                    .unwrap_or_default()
320                    == format!("refs/heads/{}", p.branch)
321                && git.line(&["rev-parse", "HEAD"]).unwrap_or_default() == p.tip
322        }) {
323            let dirty = worktree::require_clean(&checkout).is_err();
324            if diff(&prior.manifest, &manifest(&project, policy)).is_empty() {
325                if !dirty || resumable(plane_dir, feature, &prior.tip) {
326                    prior.pid = std::process::id();
327                    prior.started_at = now();
328                    prior
329                        .save(plane_dir)
330                        .map_err(|e| InPlaceError::new("IN-PLACE-ACTIVE", e))?;
331                    prior.notes.push(format!(
332                        "took over the interrupted in-place run (returns to {})",
333                        prior.original.describe()
334                    ));
335                    return Ok(prior);
336                }
337            } else if dirty
338                && let Some(r) = prior.set_aside(
339                    plane_dir,
340                    "left by an interrupted in-place run; the spec changed since, so it starts fresh",
341                )? {
342                    notes.push(format!(
343                        "the spec changed since the run was interrupted: what it left is saved as {r} and the task starts fresh"
344                    ));
345                }
346        }
347        if let Err(r) = worktree::require_clean(&checkout) {
348            let mut e = InPlaceError::new(
349                "DIRTY-CHECKOUT",
350                "the checkout has uncommitted changes; an in-place run needs a clean one",
351            )
352            .fix(&["git stash -u", "git commit"]);
353            if let Some((p, _)) = r.paths.iter().find(|(p, _)| {
354                policy.write_protected(p) == Some(crate::tools::paths::Class::Intent)
355            }) {
356                e.fix.push(format!("echo {p} >> .git/info/exclude"));
357            }
358            e.paths = r.paths;
359            return Err(e);
360        }
361        let config =
362            crate::verify::find_config(&project).map(|d| d.join(crate::verify::config::FILE));
363        let tracked = config.as_ref().is_some_and(|c| {
364            git.succeeds(&["ls-files", "--error-unmatch", "--", &c.to_string_lossy()])
365                .unwrap_or(false)
366        });
367        if !tracked {
368            return Err(InPlaceError::new(
369                "CONFIG-NOT-TRACKED",
370                "speccoder.toml is not committed; the checks that judge a run are reviewed like code",
371            )
372            .fix(&["git add speccoder.toml && git commit -m \"speccoder config\""]));
373        }
374        let branch = format!("speccoder/{feature}");
375        let listing = git
376            .run(&["worktree", "list", "--porcelain"])
377            .map(|b| String::from_utf8_lossy(&b).into_owned())
378            .unwrap_or_default();
379        let mut current_wt = String::new();
380        for line in listing.lines() {
381            if let Some(p) = line.strip_prefix("worktree ") {
382                current_wt = p.to_owned();
383            } else if line == format!("branch refs/heads/{branch}")
384                && Path::new(&current_wt) != checkout
385            {
386                return Err(InPlaceError::new(
387                    "BRANCH-IN-WORKTREE",
388                    format!("{branch} is checked out in the worktree {current_wt}"),
389                )
390                .fix(&[&format!("git worktree remove {current_wt}")]));
391            }
392        }
393        let head_ref = git
394            .line(&["symbolic-ref", "-q", "HEAD"])
395            .unwrap_or_default();
396        // A run that died leaves its record: on its branch, the branch to
397        // go back to is the recorded one, not the one checked out now.
398        let prior = Self::load(plane_dir);
399        if let Some(p) = prior.as_ref().filter(|p| p.feature != feature) {
400            return Err(InPlaceError::new(
401                "IN-PLACE-SESSION",
402                format!(
403                    "an interrupted in-place run of {} holds this checkout",
404                    p.feature
405                ),
406            )
407            .fix(&["speccoder run --in-place --return"]));
408        }
409        let original = match (prior, head_ref.strip_prefix("refs/heads/")) {
410            (Some(p), Some(b)) if b == branch => p.original,
411            (_, Some(b)) => Original::Branch(b.to_owned()),
412            (_, None) => Original::Detached(git.line(&["rev-parse", "HEAD"]).unwrap_or_default()),
413        };
414        let mut session = Self {
415            feature: feature.to_owned(),
416            branch: branch.clone(),
417            original: original.clone(),
418            checkout: checkout.clone(),
419            project: project.clone(),
420            tip: String::new(),
421            manifest: BTreeMap::new(),
422            pid: std::process::id(),
423            started_at: now(),
424            notes,
425            hidden: Vec::new(),
426            git: String::new(),
427        };
428        // Written before switching: a crash after the switch still knows
429        // where to go back to.
430        session
431            .save(plane_dir)
432            .map_err(|e| InPlaceError::new("IN-PLACE-ACTIVE", e))?;
433        if original != Original::Branch(branch.clone()) {
434            let exists = git
435                .succeeds(&[
436                    "rev-parse",
437                    "--verify",
438                    "-q",
439                    &format!("refs/heads/{branch}"),
440                ])
441                .unwrap_or(false);
442            let switched = if exists {
443                git.run(&["switch", "-q", &branch])
444            } else {
445                git.run(&["switch", "-q", "-c", &branch, "HEAD"])
446            };
447            if let Err(e) = switched {
448                let _ = std::fs::remove_file(Self::path(plane_dir));
449                return Err(InPlaceError::new(
450                    "DIRTY-CHECKOUT",
451                    format!("cannot switch to {branch}: {}", e.0),
452                ));
453            }
454            // The person's committed spec changes reach the branch.
455            if exists
456                && let Original::Branch(b) = &original
457                && !git
458                    .succeeds(&["merge-base", "--is-ancestor", b, "HEAD"])
459                    .unwrap_or(true)
460            {
461                let mut merge = crate::attempts::IDENTITY.to_vec();
462                merge.extend(["merge", "-q", "--no-edit", b.as_str()]);
463                if git.run(&merge).is_err() {
464                    let _ = git.run(&["merge", "--abort"]);
465                    let _ = git.run(&["switch", "-q", original.target()]);
466                    let _ = std::fs::remove_file(Self::path(plane_dir));
467                    return Err(InPlaceError::new(
468                        "MERGE-CONFLICT",
469                        format!("{b} does not merge cleanly into {branch}"),
470                    )
471                    .fix(&[&format!(
472                        "git switch {branch} && git merge {b}   # resolve, commit, then run again"
473                    )]));
474                }
475            }
476        }
477        session.tip = git.line(&["rev-parse", "HEAD"]).unwrap_or_default();
478        session.manifest = manifest(&project, policy);
479        session.git = git_fingerprint(&checkout, &branch);
480        session.hidden = git
481            .run(&[
482                "ls-files",
483                "-z",
484                "--others",
485                "--ignored",
486                "--exclude-standard",
487                "--directory",
488            ])
489            .map(|b| {
490                String::from_utf8_lossy(&b)
491                    .split('\0')
492                    .filter(|p| !p.is_empty())
493                    .map(str::to_owned)
494                    .collect()
495            })
496            .unwrap_or_default();
497        session
498            .save(plane_dir)
499            .map_err(|e| InPlaceError::new("IN-PLACE-ACTIVE", e))?;
500        Ok(session)
501    }
502
503    /// Saves what a dead run left in the checkout under an attempt ref,
504    /// restores the branch tip, and forgets the attempts that cannot resume
505    /// any more. `None` when there was nothing to save.
506    fn set_aside(&self, plane_dir: &Path, reason: &str) -> Result<Option<String>, InPlaceError> {
507        let _ = std::fs::remove_dir_all(plane_dir.join("resume").join(&self.feature));
508        // A call that waited for a person waits on nothing now.
509        let _ = crate::approvals::withdraw_waiting(&self.project, plane_dir, &self.feature, reason);
510        if worktree::require_clean(&self.checkout).is_ok() {
511            return Ok(None);
512        }
513        let tmp = plane_dir.join("tmp");
514        let record = crate::attempts::Record {
515            run: None,
516            outcome: "interrupted",
517            reason,
518            pending: None,
519            usage: None,
520        };
521        let saved = crate::attempts::save(&self.checkout, &tmp, &self.feature, "in-place", &record)
522            .map_err(|e| InPlaceError::new("RETURN-BLOCKED", e.0))?;
523        let git = Git::at(&self.checkout);
524        let head_tree =
525            worktree::Checkpoint(git.line(&["rev-parse", "HEAD^{tree}"]).unwrap_or_default());
526        worktree::restore(&self.checkout, &tmp, &head_tree)
527            .map_err(|e| InPlaceError::new("RETURN-BLOCKED", e.0))?;
528        Ok(Some(saved.reference))
529    }
530
531    /// The checkout guard and the manifest, before every task: HEAD where
532    /// speccoder left it, nothing changed, the protected files as recorded.
533    pub fn check(&self, policy: &Policy) -> Result<(), InPlaceError> {
534        self.check_with(policy, true)
535    }
536
537    /// [`Session::check`] before a tick: the attempt's own writes are in the
538    /// checkout then, so only HEAD and the protected files are compared.
539    pub fn check_before_tick(&self, policy: &Policy) -> Result<(), InPlaceError> {
540        self.check_with(policy, false)
541    }
542
543    fn check_with(&self, policy: &Policy, clean: bool) -> Result<(), InPlaceError> {
544        // Where the sandbox cannot keep `.git` read-only, a change is caught
545        // here — before speccoder runs git there again for a tick.
546        if !self.git.is_empty() && git_fingerprint(&self.checkout, &self.branch) != self.git {
547            return Err(InPlaceError::new(
548                "GIT-CHANGED",
549                "the repository's configuration, hooks or branches changed during the run; speccoder does not run git against them",
550            )
551            .fix(&[
552                "git -C . config --list --local   # review, restore what changed",
553                "speccoder run --in-place --return",
554            ]));
555        }
556        let git = Git::at(&self.checkout);
557        let head_ref = git
558            .line(&["symbolic-ref", "-q", "HEAD"])
559            .unwrap_or_default();
560        let head = git.line(&["rev-parse", "HEAD"]).unwrap_or_default();
561        let fix = [
562            format!("git stash -u && git switch {}", self.original.target()),
563            "speccoder run --in-place --return".to_owned(),
564        ];
565        if head_ref != format!("refs/heads/{}", self.branch) || head != self.tip {
566            let mut e = InPlaceError::new(
567                "CHECKOUT-CHANGED",
568                format!(
569                    "the checkout moved during the run (HEAD is {}, speccoder left {} at {}); nothing was switched",
570                    if head_ref.is_empty() {
571                        head.clone()
572                    } else {
573                        head_ref.clone()
574                    },
575                    self.branch,
576                    self.tip.chars().take(10).collect::<String>()
577                ),
578            );
579            e.fix = fix.to_vec();
580            return Err(e);
581        }
582        if let Some(r) = clean
583            .then(|| worktree::require_clean(&self.checkout).err())
584            .flatten()
585        {
586            let mut e = InPlaceError::new(
587                "CHECKOUT-CHANGED",
588                "the checkout changed during the run; nothing was saved, restored or switched",
589            );
590            e.paths = r.paths;
591            e.fix = fix.to_vec();
592            return Err(e);
593        }
594        let now = manifest(&self.project, policy);
595        let changed = diff(&self.manifest, &now);
596        if !changed.is_empty() {
597            let intent = changed.iter().any(|(p, _)| {
598                policy.write_protected(p) == Some(crate::tools::paths::Class::Intent)
599            });
600            let mut e = InPlaceError::new(
601                if intent {
602                    "INTENT-CHANGED"
603                } else {
604                    "JUDGE-CHANGED"
605                },
606                if intent {
607                    "the spec changed under the running judge; the run stops before judging against it"
608                } else {
609                    "a judge input changed under the running judge"
610                },
611            );
612            e.paths = changed;
613            e.fix = vec![
614                "review the change, then run again: the next run judges against the spec as it is"
615                    .to_owned(),
616            ];
617            return Err(e);
618        }
619        Ok(())
620    }
621
622    /// After a speccoder commit: the new tip.
623    pub fn advance(&mut self, plane_dir: &Path) {
624        self.tip = Git::at(&self.checkout)
625            .line(&["rev-parse", "HEAD"])
626            .unwrap_or_default();
627        let _ = self.save(plane_dir);
628    }
629
630    /// After the engine's tick or append of `file` (absolute): the manifest
631    /// takes its new hash — only when the change is exactly that (`accept`
632    /// says what the bytes before and after may be).
633    pub fn accept(
634        &mut self,
635        plane_dir: &Path,
636        file: &Path,
637        before: &[u8],
638        accept: impl Fn(&[u8], &[u8]) -> bool,
639    ) -> Result<(), InPlaceError> {
640        let after = std::fs::read(file).unwrap_or_default();
641        let rel = file
642            .strip_prefix(&self.project)
643            .map(|r| r.to_string_lossy().replace('\\', "/"))
644            .unwrap_or_default();
645        if !accept(before, &after) {
646            return Err(InPlaceError::new(
647                "INTENT-CHANGED",
648                format!("{rel} changed beyond the engine's own write"),
649            ));
650        }
651        self.manifest.insert(rel, sha256_hex(&after));
652        let _ = self.save(plane_dir);
653        Ok(())
654    }
655
656    /// Switches the checkout back to where the person was, when it is as
657    /// speccoder left it; removes the record after.
658    pub fn finish(&self, plane_dir: &Path) -> Result<(), InPlaceError> {
659        let git = Git::at(&self.checkout);
660        let head = git.line(&["rev-parse", "HEAD"]).unwrap_or_default();
661        let on_branch = git
662            .line(&["symbolic-ref", "-q", "HEAD"])
663            .unwrap_or_default()
664            == format!("refs/heads/{}", self.branch);
665        if !on_branch || head != self.tip || worktree::require_clean(&self.checkout).is_err() {
666            return Err(InPlaceError::new(
667                "RETURN-BLOCKED",
668                format!(
669                    "the checkout is not as speccoder left it, so it stays on {}",
670                    self.branch
671                ),
672            )
673            .fix(&[
674                &format!("git stash -u && git switch {}", self.original.target()),
675                "speccoder run --in-place --return",
676            ]));
677        }
678        if self.original != Original::Branch(self.branch.clone()) {
679            let back = match &self.original {
680                Original::Branch(b) => git.run(&["switch", "-q", b]),
681                Original::Detached(c) => git.run(&["switch", "-q", "--detach", c]),
682            };
683            if let Err(e) = back {
684                return Err(InPlaceError::new("RETURN-BLOCKED", e.0)
685                    .fix(&[&format!("git switch {}", self.original.target())]));
686            }
687        }
688        let _ = std::fs::remove_file(Self::path(plane_dir));
689        Ok(())
690    }
691}
692
693impl Session {
694    /// A run killed between its verdict commit and the local tick: each
695    /// open task whose newest commit names its line exactly (`Task-Line`) is
696    /// ticked now, the manifest accepting it. Returns what was ticked.
697    pub fn reconcile(
698        &mut self,
699        plane_dir: &Path,
700        tasks_file: &Path,
701        tasks: &speccoder_core::snapshot::ParsedTasks,
702        tick: impl Fn(&Path, &str, &str) -> Result<(), String>,
703    ) -> Vec<String> {
704        let log = Git::at(&self.checkout)
705            .run(&[
706                "log",
707                "--format=%(trailers:key=Spec-Task,valueonly)\u{1f}%(trailers:key=Task-Line,valueonly)\u{1e}",
708                &self.branch,
709            ])
710            .map(|b| String::from_utf8_lossy(&b).into_owned())
711            .unwrap_or_default();
712        let mut newest: BTreeMap<String, String> = BTreeMap::new();
713        for record in log.split('\u{1e}') {
714            let Some((task, line)) = record.trim().split_once('\u{1f}') else {
715                continue;
716            };
717            if let Some(id) = task.trim().strip_prefix(&format!("{}/", self.feature)) {
718                newest
719                    .entry(id.to_owned())
720                    .or_insert_with(|| line.trim().to_owned());
721            }
722        }
723        let mut ticked = Vec::new();
724        for t in tasks.tasks.iter().filter(|t| !t.done) {
725            if newest
726                .get(&t.id)
727                .is_none_or(|l| l.is_empty() || *l != t.line_hash)
728            {
729                continue;
730            }
731            let before = std::fs::read(tasks_file).unwrap_or_default();
732            if tick(tasks_file, &t.id, &t.line_hash).is_ok()
733                && self.accept(plane_dir, tasks_file, &before, is_tick).is_ok()
734            {
735                ticked.push(t.id.clone());
736            }
737        }
738        if !ticked.is_empty() {
739            self.notes.push(format!(
740                "ticked {} from {} verdict commit(s): the run was interrupted before the tick",
741                ticked.join(", "),
742                ticked.len()
743            ));
744        }
745        ticked
746    }
747}
748
749/// What committing a task in place did.
750#[derive(Debug, Default)]
751pub struct Committed {
752    /// The verdict commit.
753    pub commit: Option<String>,
754    /// Whether the task is ticked.
755    pub ticked: bool,
756    /// What went wrong, for the report's integrity list.
757    pub problems: Vec<String>,
758}
759
760impl Session {
761    /// Commits a passed (or attested) task and ticks it. The evidence comes
762    /// first: a `tasks_file` git ignores is never in a commit, so the commit
763    /// names the tick as local (`Tick: local`), and the tick follows it. A
764    /// tracked one is ticked and committed together, as in a worktree.
765    /// Every commit says it was made in place, against which intent
766    /// (`intent_digest`) and which task line (`line_hash`, before the tick).
767    pub fn commit_and_tick(
768        &mut self,
769        plane_dir: &Path,
770        tasks_file: &Path,
771        line_hash: &str,
772        message: &str,
773        intent_digest: &str,
774        tick: impl Fn() -> Result<(), String>,
775    ) -> Committed {
776        let mut out = Committed::default();
777        let rel = tasks_file
778            .strip_prefix(&self.checkout)
779            .map(|r| r.to_string_lossy().replace('\\', "/"))
780            .unwrap_or_default();
781        let tracked = Git::at(&self.checkout)
782            .succeeds(&["ls-files", "--error-unmatch", "--", &rel])
783            .unwrap_or(false);
784        let mut trailers = format!(
785            "Mode: in-place\nIntent-Digest: sha256:{intent_digest}\nTask-Line: {line_hash}\n"
786        );
787        if !tracked {
788            trailers.push_str(&format!("Tick: local {rel}\n"));
789        }
790        let message = format!("{}\n{trailers}", message.trim_end());
791        let before = std::fs::read(tasks_file).unwrap_or_default();
792        let tick_now = |out: &mut Committed| match tick() {
793            Ok(()) => out.ticked = true,
794            Err(e) => out.problems.push(format!("tick refused: {e}")),
795        };
796        if tracked {
797            tick_now(&mut out);
798        }
799        if out.ticked || !tracked {
800            match crate::pipeline::commit::commit_attempt_as(&self.checkout, &message, !tracked) {
801                Ok(id) => out.commit = Some(id),
802                Err(e) => out.problems.push(format!("commit failed: {e}")),
803            }
804        }
805        if !tracked && out.commit.is_some() {
806            tick_now(&mut out);
807        }
808        if out.ticked
809            && let Err(e) = self.accept(plane_dir, tasks_file, &before, is_tick)
810        {
811            out.problems.push(e.message);
812        }
813        self.advance(plane_dir);
814        out
815    }
816}
817
818impl Session {
819    /// Commits a convergence round in place: the append to `tasks_file`
820    /// (old bytes an exact prefix of the new) is accepted into the manifest,
821    /// and the commit says it was made in place, against which intent; a
822    /// git-ignored task list is not in it, so the commit may be empty.
823    pub fn commit_round(
824        &mut self,
825        plane_dir: &Path,
826        tasks_file: &Path,
827        before: &[u8],
828        message: &str,
829        intent_digest: &str,
830    ) -> Result<String, String> {
831        self.accept(plane_dir, tasks_file, before, |b, a| a.starts_with(b))
832            .map_err(|e| e.message)?;
833        let rel = tasks_file
834            .strip_prefix(&self.checkout)
835            .map(|r| r.to_string_lossy().replace('\\', "/"))
836            .unwrap_or_default();
837        let tracked = Git::at(&self.checkout)
838            .succeeds(&["ls-files", "--error-unmatch", "--", &rel])
839            .unwrap_or(false);
840        let mut trailers = format!("Mode: in-place\nIntent-Digest: sha256:{intent_digest}\n");
841        if !tracked {
842            trailers.push_str(&format!("Tasks: local {rel}\n"));
843        }
844        let message = format!("{}\n{trailers}", message.trim_end());
845        let id = crate::pipeline::commit::commit_attempt_as(&self.checkout, &message, !tracked)?;
846        self.advance(plane_dir);
847        Ok(id)
848    }
849
850    /// The model's view of this checkout: the policy denies git that moves
851    /// it and hides what git ignored; the sandbox keeps `.git` read-only
852    /// and the ignored secrets unreadable.
853    #[must_use]
854    pub fn confine(
855        &self,
856        policy: Policy,
857        runner: crate::sandbox::Runner,
858    ) -> (Policy, crate::sandbox::Runner, Option<String>) {
859        let secrets: Vec<PathBuf> = self
860            .hidden
861            .iter()
862            .map(|h| h.trim_end_matches('/'))
863            .filter(|h| policy.protected().is_secret(h))
864            .map(|h| self.checkout.join(h))
865            .collect();
866        let (runner, notice) = runner.carve(&[self.checkout.join(".git")], &secrets);
867        (
868            policy.in_place().with_hidden(self.hidden.clone()),
869            runner,
870            notice,
871        )
872    }
873}
874
875/// A hash over what in `.git` could make git run code or move a branch the
876/// person owns: `config`, `hooks/`, `info/`, and every branch and tag except
877/// `branch` (speccoder's own).
878fn git_fingerprint(checkout: &Path, branch: &str) -> String {
879    let git = Git::at(checkout);
880    let Some(dir) = git
881        .line(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
882        .ok()
883        .map(PathBuf::from)
884    else {
885        return String::new();
886    };
887    let mut parts = Vec::new();
888    let mut files = vec![dir.join("config")];
889    for sub in ["hooks", "info"] {
890        files.extend(
891            ignore::WalkBuilder::new(dir.join(sub))
892                .standard_filters(false)
893                .build()
894                .flatten()
895                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
896                .map(ignore::DirEntry::into_path),
897        );
898    }
899    files.sort();
900    for f in files {
901        let hash = std::fs::read(&f).map_or_else(|_| "-".to_owned(), |b| sha256_hex(&b));
902        parts.push(format!("{} {hash}", f.display()));
903    }
904    let own = format!("refs/heads/{branch} ");
905    let refs = git
906        .run(&[
907            "for-each-ref",
908            "--format=%(refname) %(objectname)",
909            "refs/heads",
910            "refs/tags",
911        ])
912        .map(|b| String::from_utf8_lossy(&b).into_owned())
913        .unwrap_or_default();
914    parts.extend(
915        refs.lines()
916            .filter(|l| !l.starts_with(&own))
917            .map(str::to_owned),
918    );
919    sha256_hex(parts.join("\n").as_bytes())
920}
921
922/// Whether the journal holds an attempt of `feature` that started at `head`.
923fn resumable(plane_dir: &Path, feature: &str, head: &str) -> bool {
924    std::fs::read_dir(plane_dir.join("resume").join(feature))
925        .into_iter()
926        .flatten()
927        .flatten()
928        .filter_map(|e| crate::resume::load(&e.path()))
929        .any(|m| m.head == head)
930}
931
932/// `run --in-place --return`: saves what an interrupted run left, switches
933/// back to the person's branch, removes the record. No model call.
934pub fn return_checkout(plane_dir: &Path) -> Result<String, InPlaceError> {
935    let Some(session) = Session::load(plane_dir) else {
936        return Err(InPlaceError::new(
937            "IN-PLACE-SESSION",
938            "there is no in-place run to return from",
939        ));
940    };
941    if session.is_live() {
942        return Err(InPlaceError::new(
943            "IN-PLACE-ACTIVE",
944            format!("the in-place run (pid {}) is still running", session.pid),
945        ));
946    }
947    let git = Git::at(&session.checkout);
948    let saved = session.set_aside(
949        plane_dir,
950        "left by an interrupted in-place run; saved by --return",
951    )?;
952    let fresh = Session {
953        tip: git.line(&["rev-parse", "HEAD"]).unwrap_or_default(),
954        ..session.clone()
955    };
956    fresh.finish(plane_dir)?;
957    Ok(match saved {
958        Some(r) => format!(
959            "back on {}; what the interrupted run left is saved as {r}",
960            session.original.describe()
961        ),
962        None => format!("back on {}", session.original.describe()),
963    })
964}
965
966/// The project's in-place session, if one is open or was left by a run
967/// that died: what `status` and the TUI show.
968#[must_use]
969pub fn session_at(path: &Path, state: &Path) -> Option<Session> {
970    let root = crate::format::open(path, None).map_or_else(
971        |_| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
972        |o| PathBuf::from(&o.snapshot.root),
973    );
974    Session::load(&worktree::project_state_dir(state, &root))
975}
976
977impl Session {
978    /// `in-place · speccoder/<f> in <checkout> (returns to <original>)`.
979    #[must_use]
980    pub fn mode_line(&self) -> String {
981        format!(
982            "in-place · {} in {} (returns to {})",
983            self.branch,
984            self.checkout.display(),
985            self.original.describe()
986        )
987    }
988}
989
990/// A worktree-mode run of a feature that an in-place session holds: the
991/// branch is checked out in the person's checkout, so it is refused.
992#[must_use]
993pub fn session_elsewhere(path: &Path, feature: Option<&str>, state: &Path) -> Option<InPlaceError> {
994    let opened = crate::format::open(path, feature).ok()?;
995    let plane_dir = worktree::project_state_dir(state, Path::new(&opened.snapshot.root));
996    let session = Session::load(&plane_dir)?;
997    let wanted = opened
998        .snapshot
999        .feature
1000        .as_ref()
1001        .map(|f| f.feature.name.as_str());
1002    if wanted.is_some_and(|w| w != session.feature) {
1003        return None;
1004    }
1005    Some(
1006        InPlaceError::new(
1007            "IN-PLACE-SESSION",
1008            format!(
1009                "{} is being run in place in {} (on {})",
1010                session.feature,
1011                session.checkout.display(),
1012                session.branch
1013            ),
1014        )
1015        .fix(&[
1016            "speccoder run --in-place",
1017            "speccoder run --in-place --return",
1018        ]),
1019    )
1020}
1021
1022/// `run --in-place --return` for the project at `path`, with the state in `state`.
1023#[must_use]
1024pub fn return_in_place(path: &Path, state: &Path) -> CommandResult {
1025    let root = crate::format::open(path, None).map_or_else(
1026        |_| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
1027        |o| PathBuf::from(&o.snapshot.root),
1028    );
1029    let plane_dir = worktree::project_state_dir(state, &root);
1030    match return_checkout(&plane_dir) {
1031        Ok(message) => CommandResult::new("run", speccoder_core::CommandStatus::Ok, &message),
1032        Err(e) => e.result("run"),
1033    }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039
1040    #[test]
1041    fn only_the_engines_tick_is_a_tick() {
1042        let before = b"- [ ] T001 a\n- [ ] T002 b\n";
1043        let mut after = before.to_vec();
1044        after[3] = b'x';
1045        assert!(is_tick(before, &after));
1046        let mut two = after.clone();
1047        two[16] = b'X';
1048        assert!(!is_tick(before, &two), "two ticks are not one");
1049        let mut other = before.to_vec();
1050        other[8] = b'Z';
1051        assert!(!is_tick(before, &other), "any other byte is not a tick");
1052        assert!(!is_tick(before, b"- [ ] T001 a\n"));
1053    }
1054
1055    #[test]
1056    fn the_intent_digest_ignores_ticks_only() {
1057        assert_eq!(
1058            untick(b"- [x] T1\n- [X] T2\n- [ ] T3"),
1059            b"- [ ] T1\n- [ ] T2\n- [ ] T3"
1060        );
1061        assert_eq!(untick(b"a [xy] b"), b"a [xy] b");
1062    }
1063
1064    /// SC-006: re-checking a 2,000-file, 20 MB protected set takes at
1065    /// most a second (`cargo test --release -- --ignored`).
1066    #[test]
1067    #[ignore = "a timing check: run in release"]
1068    fn a_large_protected_set_is_rechecked_within_a_second() {
1069        let dir = tempfile::tempdir().unwrap();
1070        let chunk = "x".repeat(10 * 1024);
1071        for f in 0..40 {
1072            let feature = dir.path().join(format!("specs/{f:03}-f"));
1073            std::fs::create_dir_all(&feature).unwrap();
1074            for i in 0..50 {
1075                std::fs::write(feature.join(format!("checklist-{i}.md")), &chunk).unwrap();
1076            }
1077        }
1078        let policy = Policy::new(&[], &[]);
1079        let first = manifest(dir.path(), &policy);
1080        assert!(first.len() >= 2000, "{} files", first.len());
1081        let start = std::time::Instant::now();
1082        let again = manifest(dir.path(), &policy);
1083        let took = start.elapsed();
1084        assert!(diff(&first, &again).is_empty());
1085        assert!(took <= std::time::Duration::from_secs(1), "took {took:?}");
1086    }
1087
1088    #[test]
1089    fn manifests_diff_by_path() {
1090        let a: BTreeMap<String, String> = [("s.md", "1"), ("t.md", "2")]
1091            .iter()
1092            .map(|(p, h)| ((*p).to_owned(), (*h).to_owned()))
1093            .collect();
1094        let mut b = a.clone();
1095        b.insert("t.md".to_owned(), "3".to_owned());
1096        b.remove("s.md");
1097        b.insert("n.md".to_owned(), "4".to_owned());
1098        let d = diff(&a, &b);
1099        assert_eq!(
1100            d,
1101            [
1102                ("s.md".to_owned(), "deleted".to_owned()),
1103                ("t.md".to_owned(), "modified".to_owned()),
1104                ("n.md".to_owned(), "added".to_owned())
1105            ]
1106        );
1107        assert!(
1108            runtime_state(".specify/workflows/runs/x.json") && runtime_state("a/__pycache__/b.pyc")
1109        );
1110    }
1111}