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