1use 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
30pub const FILE: &str = "in-place.json";
32
33fn runtime_state(path: &str) -> bool {
35 path.contains("/workflows/runs/") || path.split('/').any(|c| c == "__pycache__")
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct InPlaceError {
41 pub code: &'static str,
43 pub message: String,
45 pub paths: Vec<(String, String)>,
47 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 #[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum Original {
119 Branch(String),
121 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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct Session {
146 pub feature: String,
148 pub branch: String,
150 pub original: Original,
152 pub checkout: PathBuf,
154 pub project: PathBuf,
156 pub tip: String,
158 pub manifest: BTreeMap<String, String>,
160 pub pid: u32,
162 pub started_at: u64,
164 #[serde(skip)]
167 pub notes: Vec<String>,
168 #[serde(default)]
171 pub hidden: Vec<String>,
172 #[serde(default)]
175 pub git: String,
176}
177
178#[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#[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#[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#[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 #[must_use]
254 pub fn path(plane_dir: &Path) -> PathBuf {
255 plane_dir.join(FILE)
256 }
257
258 #[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 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 #[must_use]
276 pub fn is_live(&self) -> bool {
277 self.pid != std::process::id() && crate::progress::alive(self.pid)
278 }
279
280 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 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(¤t_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 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 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 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 fn set_aside(&self, plane_dir: &Path, reason: &str) -> Result<Option<String>, InPlaceError> {
507 crate::approvals::withdraw_waiting(&self.project, plane_dir, &self.feature, reason)
511 .map_err(|e| {
512 InPlaceError::new(
513 "RETURN-BLOCKED",
514 format!("the calls waiting for a person could not be withdrawn: {e}"),
515 )
516 })?;
517 let _ = std::fs::remove_dir_all(plane_dir.join("resume").join(&self.feature));
518 if worktree::require_clean(&self.checkout).is_ok() {
519 return Ok(None);
520 }
521 let tmp = plane_dir.join("tmp");
522 let record = crate::attempts::Record {
523 run: None,
524 outcome: "interrupted",
525 reason,
526 pending: None,
527 usage: None,
528 };
529 let saved = crate::attempts::save(&self.checkout, &tmp, &self.feature, "in-place", &record)
530 .map_err(|e| InPlaceError::new("RETURN-BLOCKED", e.0))?;
531 let git = Git::at(&self.checkout);
532 let head_tree =
533 worktree::Checkpoint(git.line(&["rev-parse", "HEAD^{tree}"]).unwrap_or_default());
534 worktree::restore(&self.checkout, &tmp, &head_tree)
535 .map_err(|e| InPlaceError::new("RETURN-BLOCKED", e.0))?;
536 Ok(Some(saved.reference))
537 }
538
539 pub fn check(&self, policy: &Policy) -> Result<(), InPlaceError> {
542 self.check_with(policy, true)
543 }
544
545 pub fn check_before_tick(&self, policy: &Policy) -> Result<(), InPlaceError> {
548 self.check_with(policy, false)
549 }
550
551 fn check_with(&self, policy: &Policy, clean: bool) -> Result<(), InPlaceError> {
552 if !self.git.is_empty() && git_fingerprint(&self.checkout, &self.branch) != self.git {
555 return Err(InPlaceError::new(
556 "GIT-CHANGED",
557 "the repository's configuration, hooks or branches changed during the run; speccoder does not run git against them",
558 )
559 .fix(&[
560 "git -C . config --list --local # review, restore what changed",
561 "speccoder run --in-place --return",
562 ]));
563 }
564 let git = Git::at(&self.checkout);
565 let head_ref = git
566 .line(&["symbolic-ref", "-q", "HEAD"])
567 .unwrap_or_default();
568 let head = git.line(&["rev-parse", "HEAD"]).unwrap_or_default();
569 let fix = [
570 format!("git stash -u && git switch {}", self.original.target()),
571 "speccoder run --in-place --return".to_owned(),
572 ];
573 if head_ref != format!("refs/heads/{}", self.branch) || head != self.tip {
574 let mut e = InPlaceError::new(
575 "CHECKOUT-CHANGED",
576 format!(
577 "the checkout moved during the run (HEAD is {}, speccoder left {} at {}); nothing was switched",
578 if head_ref.is_empty() {
579 head.clone()
580 } else {
581 head_ref.clone()
582 },
583 self.branch,
584 self.tip.chars().take(10).collect::<String>()
585 ),
586 );
587 e.fix = fix.to_vec();
588 return Err(e);
589 }
590 if let Some(r) = clean
591 .then(|| worktree::require_clean(&self.checkout).err())
592 .flatten()
593 {
594 let mut e = InPlaceError::new(
595 "CHECKOUT-CHANGED",
596 "the checkout changed during the run; nothing was saved, restored or switched",
597 );
598 e.paths = r.paths;
599 e.fix = fix.to_vec();
600 return Err(e);
601 }
602 let now = manifest(&self.project, policy);
603 let changed = diff(&self.manifest, &now);
604 if !changed.is_empty() {
605 let intent = changed.iter().any(|(p, _)| {
606 policy.write_protected(p) == Some(crate::tools::paths::Class::Intent)
607 });
608 let mut e = InPlaceError::new(
609 if intent {
610 "INTENT-CHANGED"
611 } else {
612 "JUDGE-CHANGED"
613 },
614 if intent {
615 "the spec changed under the running judge; the run stops before judging against it"
616 } else {
617 "a judge input changed under the running judge"
618 },
619 );
620 e.paths = changed;
621 e.fix = vec![
622 "review the change, then run again: the next run judges against the spec as it is"
623 .to_owned(),
624 ];
625 return Err(e);
626 }
627 Ok(())
628 }
629
630 pub fn advance(&mut self, plane_dir: &Path) {
632 self.tip = Git::at(&self.checkout)
633 .line(&["rev-parse", "HEAD"])
634 .unwrap_or_default();
635 let _ = self.save(plane_dir);
636 }
637
638 pub fn accept(
642 &mut self,
643 plane_dir: &Path,
644 file: &Path,
645 before: &[u8],
646 accept: impl Fn(&[u8], &[u8]) -> bool,
647 ) -> Result<(), InPlaceError> {
648 let after = std::fs::read(file).unwrap_or_default();
649 let rel = file
650 .strip_prefix(&self.project)
651 .map(|r| r.to_string_lossy().replace('\\', "/"))
652 .unwrap_or_default();
653 if !accept(before, &after) {
654 return Err(InPlaceError::new(
655 "INTENT-CHANGED",
656 format!("{rel} changed beyond the engine's own write"),
657 ));
658 }
659 self.manifest.insert(rel, sha256_hex(&after));
660 let _ = self.save(plane_dir);
661 Ok(())
662 }
663
664 pub fn finish(&self, plane_dir: &Path) -> Result<(), InPlaceError> {
667 let git = Git::at(&self.checkout);
668 let head = git.line(&["rev-parse", "HEAD"]).unwrap_or_default();
669 let on_branch = git
670 .line(&["symbolic-ref", "-q", "HEAD"])
671 .unwrap_or_default()
672 == format!("refs/heads/{}", self.branch);
673 if !on_branch || head != self.tip || worktree::require_clean(&self.checkout).is_err() {
674 return Err(InPlaceError::new(
675 "RETURN-BLOCKED",
676 format!(
677 "the checkout is not as speccoder left it, so it stays on {}",
678 self.branch
679 ),
680 )
681 .fix(&[
682 &format!("git stash -u && git switch {}", self.original.target()),
683 "speccoder run --in-place --return",
684 ]));
685 }
686 if self.original != Original::Branch(self.branch.clone()) {
687 let back = match &self.original {
688 Original::Branch(b) => git.run(&["switch", "-q", b]),
689 Original::Detached(c) => git.run(&["switch", "-q", "--detach", c]),
690 };
691 if let Err(e) = back {
692 return Err(InPlaceError::new("RETURN-BLOCKED", e.0)
693 .fix(&[&format!("git switch {}", self.original.target())]));
694 }
695 }
696 let _ = std::fs::remove_file(Self::path(plane_dir));
697 Ok(())
698 }
699}
700
701impl Session {
702 pub fn reconcile(
706 &mut self,
707 plane_dir: &Path,
708 tasks_file: &Path,
709 tasks: &speccoder_core::snapshot::ParsedTasks,
710 tick: impl Fn(&Path, &str, &str) -> Result<(), String>,
711 ) -> Vec<String> {
712 let log = Git::at(&self.checkout)
713 .run(&[
714 "log",
715 "--format=%(trailers:key=Spec-Task,valueonly)\u{1f}%(trailers:key=Task-Line,valueonly)\u{1e}",
716 &self.branch,
717 ])
718 .map(|b| String::from_utf8_lossy(&b).into_owned())
719 .unwrap_or_default();
720 let mut newest: BTreeMap<String, String> = BTreeMap::new();
721 for record in log.split('\u{1e}') {
722 let Some((task, line)) = record.trim().split_once('\u{1f}') else {
723 continue;
724 };
725 if let Some(id) = task.trim().strip_prefix(&format!("{}/", self.feature)) {
726 newest
727 .entry(id.to_owned())
728 .or_insert_with(|| line.trim().to_owned());
729 }
730 }
731 let mut ticked = Vec::new();
732 for t in tasks.tasks.iter().filter(|t| !t.done) {
733 if newest
734 .get(&t.id)
735 .is_none_or(|l| l.is_empty() || *l != t.line_hash)
736 {
737 continue;
738 }
739 let before = std::fs::read(tasks_file).unwrap_or_default();
740 if tick(tasks_file, &t.id, &t.line_hash).is_ok()
741 && self.accept(plane_dir, tasks_file, &before, is_tick).is_ok()
742 {
743 ticked.push(t.id.clone());
744 }
745 }
746 if !ticked.is_empty() {
747 self.notes.push(format!(
748 "ticked {} from {} verdict commit(s): the run was interrupted before the tick",
749 ticked.join(", "),
750 ticked.len()
751 ));
752 }
753 ticked
754 }
755}
756
757#[derive(Debug, Default)]
759pub struct Committed {
760 pub commit: Option<String>,
762 pub ticked: bool,
764 pub problems: Vec<String>,
766}
767
768impl Session {
769 pub fn commit_and_tick(
776 &mut self,
777 plane_dir: &Path,
778 tasks_file: &Path,
779 line_hash: &str,
780 message: &str,
781 intent_digest: &str,
782 tick: impl Fn() -> Result<(), String>,
783 ) -> Committed {
784 let mut out = Committed::default();
785 let rel = tasks_file
786 .strip_prefix(&self.checkout)
787 .map(|r| r.to_string_lossy().replace('\\', "/"))
788 .unwrap_or_default();
789 let tracked = Git::at(&self.checkout)
790 .succeeds(&["ls-files", "--error-unmatch", "--", &rel])
791 .unwrap_or(false);
792 let mut trailers = format!(
793 "Mode: in-place\nIntent-Digest: sha256:{intent_digest}\nTask-Line: {line_hash}\n"
794 );
795 if !tracked {
796 trailers.push_str(&format!("Tick: local {rel}\n"));
797 }
798 let message = format!("{}\n{trailers}", message.trim_end());
799 let before = std::fs::read(tasks_file).unwrap_or_default();
800 let tick_now = |out: &mut Committed| match tick() {
801 Ok(()) => out.ticked = true,
802 Err(e) => out.problems.push(format!("tick refused: {e}")),
803 };
804 if tracked {
805 tick_now(&mut out);
806 }
807 if out.ticked || !tracked {
808 match crate::pipeline::commit::commit_attempt_as(&self.checkout, &message, !tracked) {
809 Ok(id) => out.commit = Some(id),
810 Err(e) => out.problems.push(format!("commit failed: {e}")),
811 }
812 }
813 if !tracked && out.commit.is_some() {
814 tick_now(&mut out);
815 }
816 if out.ticked
817 && let Err(e) = self.accept(plane_dir, tasks_file, &before, is_tick)
818 {
819 out.problems.push(e.message);
820 }
821 self.advance(plane_dir);
822 out
823 }
824}
825
826impl Session {
827 pub fn commit_round(
832 &mut self,
833 plane_dir: &Path,
834 tasks_file: &Path,
835 before: &[u8],
836 message: &str,
837 intent_digest: &str,
838 ) -> Result<String, String> {
839 self.accept(plane_dir, tasks_file, before, |b, a| a.starts_with(b))
840 .map_err(|e| e.message)?;
841 let rel = tasks_file
842 .strip_prefix(&self.checkout)
843 .map(|r| r.to_string_lossy().replace('\\', "/"))
844 .unwrap_or_default();
845 let tracked = Git::at(&self.checkout)
846 .succeeds(&["ls-files", "--error-unmatch", "--", &rel])
847 .unwrap_or(false);
848 let mut trailers = format!("Mode: in-place\nIntent-Digest: sha256:{intent_digest}\n");
849 if !tracked {
850 trailers.push_str(&format!("Tasks: local {rel}\n"));
851 }
852 let message = format!("{}\n{trailers}", message.trim_end());
853 let id = crate::pipeline::commit::commit_attempt_as(&self.checkout, &message, !tracked)?;
854 self.advance(plane_dir);
855 Ok(id)
856 }
857
858 #[must_use]
862 pub fn confine(
863 &self,
864 policy: Policy,
865 runner: crate::sandbox::Runner,
866 ) -> (Policy, crate::sandbox::Runner, Option<String>) {
867 let secrets: Vec<PathBuf> = self
868 .hidden
869 .iter()
870 .map(|h| h.trim_end_matches('/'))
871 .filter(|h| policy.protected().is_secret(h))
872 .map(|h| self.checkout.join(h))
873 .collect();
874 let (runner, notice) = runner.carve(&[self.checkout.join(".git")], &secrets);
875 (
876 policy.in_place().with_hidden(self.hidden.clone()),
877 runner,
878 notice,
879 )
880 }
881}
882
883fn git_fingerprint(checkout: &Path, branch: &str) -> String {
887 let git = Git::at(checkout);
888 let Some(dir) = git
889 .line(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
890 .ok()
891 .map(PathBuf::from)
892 else {
893 return String::new();
894 };
895 let mut parts = Vec::new();
896 let mut files = vec![dir.join("config")];
897 for sub in ["hooks", "info"] {
898 files.extend(
899 ignore::WalkBuilder::new(dir.join(sub))
900 .standard_filters(false)
901 .build()
902 .flatten()
903 .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
904 .map(ignore::DirEntry::into_path),
905 );
906 }
907 files.sort();
908 for f in files {
909 let hash = std::fs::read(&f).map_or_else(|_| "-".to_owned(), |b| sha256_hex(&b));
910 parts.push(format!("{} {hash}", f.display()));
911 }
912 let own = format!("refs/heads/{branch} ");
913 let refs = git
914 .run(&[
915 "for-each-ref",
916 "--format=%(refname) %(objectname)",
917 "refs/heads",
918 "refs/tags",
919 ])
920 .map(|b| String::from_utf8_lossy(&b).into_owned())
921 .unwrap_or_default();
922 parts.extend(
923 refs.lines()
924 .filter(|l| !l.starts_with(&own))
925 .map(str::to_owned),
926 );
927 sha256_hex(parts.join("\n").as_bytes())
928}
929
930fn resumable(plane_dir: &Path, feature: &str, head: &str) -> bool {
932 std::fs::read_dir(plane_dir.join("resume").join(feature))
933 .into_iter()
934 .flatten()
935 .flatten()
936 .filter_map(|e| crate::resume::load(&e.path()))
937 .any(|m| m.head == head)
938}
939
940pub fn return_checkout(plane_dir: &Path) -> Result<String, InPlaceError> {
943 let Some(session) = Session::load(plane_dir) else {
944 return Err(InPlaceError::new(
945 "IN-PLACE-SESSION",
946 "there is no in-place run to return from",
947 ));
948 };
949 if session.is_live() {
950 return Err(InPlaceError::new(
951 "IN-PLACE-ACTIVE",
952 format!("the in-place run (pid {}) is still running", session.pid),
953 ));
954 }
955 let git = Git::at(&session.checkout);
956 let saved = session.set_aside(
957 plane_dir,
958 "left by an interrupted in-place run; saved by --return",
959 )?;
960 let fresh = Session {
961 tip: git.line(&["rev-parse", "HEAD"]).unwrap_or_default(),
962 ..session.clone()
963 };
964 fresh.finish(plane_dir)?;
965 Ok(match saved {
966 Some(r) => format!(
967 "back on {}; what the interrupted run left is saved as {r}",
968 session.original.describe()
969 ),
970 None => format!("back on {}", session.original.describe()),
971 })
972}
973
974#[must_use]
977pub fn session_at(path: &Path, state: &Path) -> Option<Session> {
978 let root = crate::format::open(path, None).map_or_else(
979 |_| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
980 |o| PathBuf::from(&o.snapshot.root),
981 );
982 Session::load(&worktree::project_state_dir(state, &root))
983}
984
985impl Session {
986 #[must_use]
988 pub fn mode_line(&self) -> String {
989 format!(
990 "in-place · {} in {} (returns to {})",
991 self.branch,
992 self.checkout.display(),
993 self.original.describe()
994 )
995 }
996}
997
998#[must_use]
1001pub fn session_elsewhere(path: &Path, feature: Option<&str>, state: &Path) -> Option<InPlaceError> {
1002 let opened = crate::format::open(path, feature).ok()?;
1003 let plane_dir = worktree::project_state_dir(state, Path::new(&opened.snapshot.root));
1004 let session = Session::load(&plane_dir)?;
1005 let wanted = opened
1006 .snapshot
1007 .feature
1008 .as_ref()
1009 .map(|f| f.feature.name.as_str());
1010 if wanted.is_some_and(|w| w != session.feature) {
1011 return None;
1012 }
1013 Some(
1014 InPlaceError::new(
1015 "IN-PLACE-SESSION",
1016 format!(
1017 "{} is being run in place in {} (on {})",
1018 session.feature,
1019 session.checkout.display(),
1020 session.branch
1021 ),
1022 )
1023 .fix(&[
1024 "speccoder run --in-place",
1025 "speccoder run --in-place --return",
1026 ]),
1027 )
1028}
1029
1030#[must_use]
1032pub fn return_in_place(path: &Path, state: &Path) -> CommandResult {
1033 let root = crate::format::open(path, None).map_or_else(
1034 |_| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),
1035 |o| PathBuf::from(&o.snapshot.root),
1036 );
1037 let plane_dir = worktree::project_state_dir(state, &root);
1038 match return_checkout(&plane_dir) {
1039 Ok(message) => CommandResult::new("run", speccoder_core::CommandStatus::Ok, &message),
1040 Err(e) => e.result("run"),
1041 }
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046 use super::*;
1047
1048 #[test]
1049 fn only_the_engines_tick_is_a_tick() {
1050 let before = b"- [ ] T001 a\n- [ ] T002 b\n";
1051 let mut after = before.to_vec();
1052 after[3] = b'x';
1053 assert!(is_tick(before, &after));
1054 let mut two = after.clone();
1055 two[16] = b'X';
1056 assert!(!is_tick(before, &two), "two ticks are not one");
1057 let mut other = before.to_vec();
1058 other[8] = b'Z';
1059 assert!(!is_tick(before, &other), "any other byte is not a tick");
1060 assert!(!is_tick(before, b"- [ ] T001 a\n"));
1061 }
1062
1063 #[test]
1064 fn the_intent_digest_ignores_ticks_only() {
1065 assert_eq!(
1066 untick(b"- [x] T1\n- [X] T2\n- [ ] T3"),
1067 b"- [ ] T1\n- [ ] T2\n- [ ] T3"
1068 );
1069 assert_eq!(untick(b"a [xy] b"), b"a [xy] b");
1070 }
1071
1072 #[test]
1075 #[ignore = "a timing check: run in release"]
1076 fn a_large_protected_set_is_rechecked_within_a_second() {
1077 let dir = tempfile::tempdir().unwrap();
1078 let chunk = "x".repeat(10 * 1024);
1079 for f in 0..40 {
1080 let feature = dir.path().join(format!("specs/{f:03}-f"));
1081 std::fs::create_dir_all(&feature).unwrap();
1082 for i in 0..50 {
1083 std::fs::write(feature.join(format!("checklist-{i}.md")), &chunk).unwrap();
1084 }
1085 }
1086 let policy = Policy::new(&[], &[]);
1087 let first = manifest(dir.path(), &policy);
1088 assert!(first.len() >= 2000, "{} files", first.len());
1089 let start = std::time::Instant::now();
1090 let again = manifest(dir.path(), &policy);
1091 let took = start.elapsed();
1092 assert!(diff(&first, &again).is_empty());
1093 assert!(took <= std::time::Duration::from_secs(1), "took {took:?}");
1094 }
1095
1096 #[test]
1097 fn manifests_diff_by_path() {
1098 let a: BTreeMap<String, String> = [("s.md", "1"), ("t.md", "2")]
1099 .iter()
1100 .map(|(p, h)| ((*p).to_owned(), (*h).to_owned()))
1101 .collect();
1102 let mut b = a.clone();
1103 b.insert("t.md".to_owned(), "3".to_owned());
1104 b.remove("s.md");
1105 b.insert("n.md".to_owned(), "4".to_owned());
1106 let d = diff(&a, &b);
1107 assert_eq!(
1108 d,
1109 [
1110 ("s.md".to_owned(), "deleted".to_owned()),
1111 ("t.md".to_owned(), "modified".to_owned()),
1112 ("n.md".to_owned(), "added".to_owned())
1113 ]
1114 );
1115 assert!(
1116 runtime_state(".specify/workflows/runs/x.json") && runtime_state("a/__pycache__/b.pyc")
1117 );
1118 }
1119}