Autonomous research system for measurable, computer-executable research.
Python
fix(lifecycle): preserve run lifecycle integrity across start/stop/resume (#198)
Glen-SP49b53086b173
diff --git a/docs/guides/operators.md b/docs/guides/operators.mdindex fca870d..14f1d66 100644--- a/docs/guides/operators.md+++ b/docs/guides/operators.md@@ -251,6 +251,26 @@ Use `praxist-control` with the request "resume the latest run" for this preparatskill understands interrupted PI and Gems boundaries and avoids destructiveguessing.+### Supported Resume Boundaries++Praxist supports automated resumption for several lifecycle boundaries:++- **Clean generation boundary**: Resuming after any generation whose boundary marker, frontier promotions, and synthesis agenda were committed. The run advances directly to the next generation.+- **Interrupted generation boundary**: When a cohort finished and generated valid results, but the boundary marker or agenda creation crashed or was interrupted. Praxist detects the pending boundary, executes the boundary completion (or recovers a pending Gems reset), and then advances.+- **Interrupted in-flight cohort**: When a cohort execution crashed before completing valid results. Praxist removes transient runtime sentinels and reruns the incomplete cohort from the last committed boundary.+- **Relocated task directory**: An unchanged task project may be moved to a different path as long as its manifest checksum and descriptor remain identical.+- **Extended generation limit**: An operator may resume a run that reached its initial generation limit by providing an increased `--generations` limit.++### Unsupported Resume Boundaries and Protected States++To preserve experimental integrity and prevent accidental data corruption, certain irregular states are rejected with actionable operator feedback:++- **Pre-existing run artifacts in non-resume startup**: Starting a run into a directory containing Praxist artifacts without `--resume` or `--resume-from` is rejected, guiding the operator to continue the run with `--resume-from` or choose a fresh directory.+- **Non-empty directory without Praxist artifacts**: Non-resume startup into an existing non-empty directory containing unrelated files is rejected, instructing the operator to select a fresh directory.+- **Missing or damaged startup artifacts**: If `run.json` or `startup_config.json` is missing, unreadable, or malformed JSON, Praxist halts with a specific error noting that manual inspection is required to repair or restore the artifacts.+- **Canonical identity drift**: Resuming with a different agent runtime, model, model provider, or modified task files is blocked to guarantee scientific provenance.+- **Active or remote execution**: Resuming a run whose process is verified live on the local machine or hosted on another machine is rejected.+## Agent-Assisted OperationCodex or Claude Code is the recommended interface when an action requires path selection,diff --git a/praxist/cli/registry.py b/praxist/cli/registry.pyindex 325efd4..7e27bbb 100644--- a/praxist/cli/registry.py+++ b/praxist/cli/registry.py@@ -400,7 +400,7 @@ def process_start_token(pid: int) -> str:)if completed.returncode == 0 and completed.stdout:started = " ".join(completed.stdout.split())- if started:+ if started and started != "-":return f"ps:{started}"except (OSError, ValueError, TypeError, subprocess.TimeoutExpired):return ""diff --git a/praxist/cli/resume.py b/praxist/cli/resume.pyindex 5194e85..d775836 100644--- a/praxist/cli/resume.py+++ b/praxist/cli/resume.py@@ -590,9 +590,15 @@ def _read_json_object(path: Path) -> dict[str, object]:try:payload = json.loads(path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError) as exc:- raise ResumeError(f"could not read resume artifact {path}: {exc}") from exc+ raise ResumeError(+ f"could not read resume artifact {path}: {exc}. "+ "Manual inspection is required to verify or repair run artifacts before resuming."+ ) from excif not isinstance(payload, dict):- raise ResumeError(f"resume artifact must be a JSON object: {path}")+ raise ResumeError(+ f"resume artifact must be a JSON object: {path}. "+ "Manual inspection is required to verify or repair run artifacts before resuming."+ )return payloaddiff --git a/praxist/cli/start.py b/praxist/cli/start.pyindex 5186c77..918cdd2 100644--- a/praxist/cli/start.py+++ b/praxist/cli/start.py@@ -436,11 +436,42 @@ def launch_run(raise StartError("--resume requires --run-dir or --resume-from.")resolved_run_dir = resume_from_path or _resolve_run_dir(run_dir, resolved_task_path, now)resume_enabled = bool(resume or resume_from_path is not None)- if not resume_enabled and resolved_run_dir.exists() and any(resolved_run_dir.iterdir()):- raise StartError(- f"fresh run directory is not empty: {resolved_run_dir}. "- "Choose another --run-dir or use --resume-from."- )+ if not resume_enabled and resolved_run_dir.exists():+ blocking_paths = [+ path for path in resolved_run_dir.iterdir() if not _is_ignorable_precreated_path(path)+ ]+ if blocking_paths:+ has_artifacts = any(+ (resolved_run_dir / rel).exists()+ for rel in (+ "run.json",+ "startup_config.json",+ "trajectory.jsonl",+ "budget_ledger.jsonl",+ "artifact_index.jsonl",+ "run_summary.json",+ "plugin_resolution.json",+ "effective_task_spec.yaml",+ "model_profiles.json",+ "cache_policy.json",+ "task_project_manifest.json",+ "credentials_redacted.json",+ "findings",+ "frontier",+ "agendas",+ "memory",+ "gems",+ "gen_0",+ )+ ) or any(child.name.startswith("gen_") for child in resolved_run_dir.iterdir())+ if has_artifacts:+ raise StartError(+ f"fresh run directory is not empty: {resolved_run_dir}. "+ "Choose another --run-dir or use --resume-from."+ )+ raise StartError(+ f"fresh run directory is not empty: {resolved_run_dir}. Choose another --run-dir."+ )run_id = resolved_run_dir.namestartup_baseline = _startup_artifact_signatures(resolved_run_dir)log_file = resolved_run_dir / "logs" / "launcher.nohup.log"@@ -1414,3 +1445,21 @@ def operator_text(value: object) -> str:else:output.append(char)return "".join(output)+++def _is_ignorable_precreated_path(path: Path) -> bool:+ if path.is_file():+ return path.name in {".DS_Store", ".gitkeep"}+ if path.is_dir():+ if path.name == "logs":+ return all(child.name in {".gitkeep", "launcher.nohup.log"} for child in path.iterdir())+ if path.name in {+ "findings",+ "frontier",+ "agendas",+ "memory",+ "gems",+ } or path.name.startswith("gen_"):+ return False+ return not any(path.iterdir())+ return Falsediff --git a/praxist/cli/status.py b/praxist/cli/status.pyindex 4787234..b6cd702 100644--- a/praxist/cli/status.py+++ b/praxist/cli/status.py@@ -76,6 +76,7 @@ STATE_FAILED = "failed"STATE_INCONSISTENT = "status_inconsistent"_RUN_DIR_HINT_RE = re.compile(r"--run-dir(?:[=\s]+)(\S+)")+_PS_ETIME_RE = re.compile(r"^(?:-|\d{1,2}:\d{2}(?::\d{2})?|\d+-\d{1,2}:\d{2}:\d{2})$")_LAST_PS_ERROR = ""@@ -814,20 +815,30 @@ def _read_ps_table(*, timeout_seconds: float = 10.0) -> dict[int, tuple[int, strrows: dict[int, tuple[int, str, str]] = {}lines = result.stdout.splitlines()for line in lines[1:]:- parts = line.strip().split(None, 3)- if len(parts) < 4:+ parts = line.strip().split(None, 2)+ if len(parts) < 3:continuetry:pid = int(parts[0])ppid = int(parts[1])except ValueError:continue- etime = parts[2]- command = parts[3]+ etime, command = _split_ps_etime_command(parts[2])+ if not command:+ continuerows[pid] = (ppid, etime, command)return rows+def _split_ps_etime_command(remainder: str) -> tuple[str, str]:+ fields = remainder.strip().split(None, 1)+ if not fields:+ return "-", ""+ if _PS_ETIME_RE.match(fields[0]):+ return fields[0], fields[1] if len(fields) > 1 else ""+ return "-", remainder.strip()++def _self_ancestor_pids(rows: dict[int, tuple[int, str, str]]) -> set[int]:"""Return PIDs that should never appear in the output (this process tree)."""try:diff --git a/praxist/plugins/workflow_stages/research_loop/backend/resume_state.py b/praxist/plugins/workflow_stages/research_loop/backend/resume_state.pyindex 84a2940..7b30158 100644--- a/praxist/plugins/workflow_stages/research_loop/backend/resume_state.py+++ b/praxist/plugins/workflow_stages/research_loop/backend/resume_state.py@@ -541,7 +541,8 @@ def ensure_resumable_run_dir(run_dir: Path) -> None:missing = [rel for rel in ("run.json", "startup_config.json") if not (run_dir / rel).exists()]if missing:raise ValueError(- f"resume run_dir is missing Praxist startup artifacts: {run_dir} ({', '.join(missing)})"+ f"resume run_dir is missing Praxist startup artifacts: {run_dir} ({', '.join(missing)}). "+ "Manual inspection is required to verify or repair run artifacts before resuming.")@@ -549,9 +550,15 @@ def _read_json_object_for_resume(path: Path) -> dict[str, Any]:try:value = json.loads(path.read_text(encoding="utf-8"))except json.JSONDecodeError as exc:- raise ValueError(f"resume artifact is not valid JSON: {path}") from exc+ raise ValueError(+ f"resume artifact is not valid JSON: {path}. "+ "Manual inspection is required to verify or repair run artifacts before resuming."+ ) from excif not isinstance(value, dict):- raise ValueError(f"resume artifact must be a JSON object: {path}")+ raise ValueError(+ f"resume artifact must be a JSON object: {path}. "+ "Manual inspection is required to verify or repair run artifacts before resuming."+ )return valuediff --git a/praxist/plugins/workflow_stages/research_loop/backend/run_lifecycle.py b/praxist/plugins/workflow_stages/research_loop/backend/run_lifecycle.pyindex f93f9ae..92935e5 100644--- a/praxist/plugins/workflow_stages/research_loop/backend/run_lifecycle.py+++ b/praxist/plugins/workflow_stages/research_loop/backend/run_lifecycle.py@@ -184,7 +184,7 @@ def _resolve_stop_signal_path(run_dir: Path, raw_path: str) -> Path | None:resolved_candidate.relative_to(resolved_run_root)except ValueError:return None- if _has_symlink_component(run_root, candidate):+ if _has_symlink_component(resolved_run_root, resolved_candidate):return Nonereturn candidatediff --git a/praxist/plugins/workflow_stages/research_loop/startup.py b/praxist/plugins/workflow_stages/research_loop/startup.pyindex de9e921..4356a76 100644--- a/praxist/plugins/workflow_stages/research_loop/startup.py+++ b/praxist/plugins/workflow_stages/research_loop/startup.py@@ -1206,31 +1206,46 @@ def _touch_required_jsonl(run_dir: Path) -> None:path.touch(exist_ok=True)+PRAXIST_RUN_ARTIFACT_REL_PATHS = (+ "run.json",+ "startup_config.json",+ "trajectory.jsonl",+ "budget_ledger.jsonl",+ "artifact_index.jsonl",+ "run_summary.json",+ "plugin_resolution.json",+ "effective_task_spec.yaml",+ "model_profiles.json",+ "cache_policy.json",+ "task_project_manifest.json",+ "credentials_redacted.json",+ "findings",+ "frontier",+ "agendas",+ "memory",+ "gems",+ "gen_0",+)++def _ensure_fresh_run_dir(run_dir: Path, *, resume: bool = False) -> None:if resume:ensure_resumable_run_dir(run_dir)returnif not run_dir.exists():return- for rel in (- "run.json",- "trajectory.jsonl",- "budget_ledger.jsonl",- "artifact_index.jsonl",- "run_summary.json",- "plugin_resolution.json",- "startup_config.json",- ):- if (run_dir / rel).exists():- raise ValueError(- f"run_dir already contains Praxist run artifacts: {run_dir}. "- "Resume mode is not implemented; choose a fresh run directory."- )+ has_artifacts = any((run_dir / rel).exists() for rel in PRAXIST_RUN_ARTIFACT_REL_PATHS) or any(+ child.name.startswith("gen_") for child in run_dir.iterdir()+ )+ if has_artifacts:+ raise ValueError(+ f"run_dir already contains Praxist run artifacts: {run_dir}. "+ "Use --resume or --resume-from to continue this run, or choose a fresh run directory."+ )blocking_paths = [path for path in run_dir.iterdir() if not _is_ignorable_precreated_path(path)]if blocking_paths:raise ValueError(- f"run_dir already exists and is not empty: {run_dir}. "- "Resume mode is not implemented; choose a fresh run directory."+ f"run_dir already exists and is not empty: {run_dir}. Choose a fresh run directory.")@@ -1240,6 +1255,14 @@ def _is_ignorable_precreated_path(path: Path) -> bool:if path.is_dir():if path.name == "logs":return all(child.name in {".gitkeep", "launcher.nohup.log"} for child in path.iterdir())+ if path.name in {+ "findings",+ "frontier",+ "agendas",+ "memory",+ "gems",+ } or path.name.startswith("gen_"):+ return Falsereturn not any(path.iterdir())return Falsediff --git a/tests/unit/test_cli_registry.py b/tests/unit/test_cli_registry.pyindex 113dd40..eede99e 100644--- a/tests/unit/test_cli_registry.py+++ b/tests/unit/test_cli_registry.py@@ -309,6 +309,26 @@ class RegistryBasicsTest(unittest.TestCase):env={"LANG": "C", "LC_ALL": "C"},)+ def test_process_start_token_handles_daemonized_dash(self) -> None:+ from praxist.cli import registry++ with (+ patch.object(Path, "read_text", side_effect=OSError("proc unavailable")),+ patch("praxist.cli.registry.shutil.which", return_value="/bin/ps"),+ patch(+ "praxist.cli.registry.subprocess.run",+ return_value=registry.subprocess.CompletedProcess(+ args=[],+ returncode=0,+ stdout="-\n",+ ),+ ),+ ):+ self.assertEqual(+ registry.process_start_token(4242),+ "",+ )+def test_process_start_token_handles_proc_no_ps_and_ps_timeout(self) -> None:from praxist.cli import registrydiff --git a/tests/unit/test_cli_resume.py b/tests/unit/test_cli_resume.pyindex 9125915..b0690a8 100644--- a/tests/unit/test_cli_resume.py+++ b/tests/unit/test_cli_resume.py@@ -890,6 +890,7 @@ class ResumeRunTest(unittest.TestCase):with self.assertRaises(resume.ResumeError) as cm:resume.resolve_resume_target(str(run_dir))self.assertIn("JSON object", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))def test_missing_resume_artifacts_are_rejected(self) -> None:from praxist.cli import resume@@ -900,6 +901,29 @@ class ResumeRunTest(unittest.TestCase):resume.resolve_resume_target(str(missing_run_dir))self.assertIn("does not exist", str(cm.exception))+ def test_existing_directory_missing_startup_artifacts_requires_manual_inspection(self) -> None:+ from praxist.cli import resume++ empty_run_dir = Path(self.workspace.name) / "empty_existing_run"+ empty_run_dir.mkdir()++ with self.assertRaises(resume.ResumeError) as cm:+ resume.resolve_resume_target(str(empty_run_dir))+ self.assertIn("missing Praxist startup artifacts", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))++ def test_resume_malformed_json_artifact_requires_manual_inspection(self) -> None:+ from praxist.cli import resume++ task = _make_task_dir(Path(self.workspace.name), name="corrupt_json_task")+ run_dir = _make_run_dir(Path(self.workspace.name), task_path=task)+ (run_dir / "startup_config.json").write_text("{not-valid-json", encoding="utf-8")++ with self.assertRaises(resume.ResumeError) as cm:+ resume.resolve_resume_target(str(run_dir))+ self.assertIn("could not read resume artifact", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))+def test_run_directory_with_multiple_registry_owners_is_rejected(self) -> None:from praxist.cli import registry, resumediff --git a/tests/unit/test_cli_start.py b/tests/unit/test_cli_start.pyindex ad9c44f..a21d66b 100644--- a/tests/unit/test_cli_start.py+++ b/tests/unit/test_cli_start.py@@ -662,6 +662,106 @@ class LaunchRunTest(unittest.TestCase):)self.assertIn("--resume-from and --run-dir", str(cm.exception))+ def test_fresh_run_dir_rejects_preexisting_run_artifacts_with_resume_guidance(self) -> None:+ from praxist.cli import start++ task = _make_task_dir(Path(self.workspace.name), name="existing_artifacts_task")+ run_dir = Path(self.workspace.name) / "existing_artifacts_run"+ run_dir.mkdir(parents=True)+ (run_dir / "run.json").write_text("{}", encoding="utf-8")+ with self.assertRaises(start.StartError) as cm:+ start.launch_run(+ task_path=str(task),+ run_dir=str(run_dir),+ model=None,+ model_provider_ref=None,+ frontier_strategy="auto",+ cohort=None,+ generations=None,+ server=False,+ resume=False,+ spawn=MagicMock(return_value=_FakeProc()),+ )+ self.assertIn("fresh run directory is not empty", str(cm.exception))+ self.assertIn("Choose another --run-dir or use --resume-from.", str(cm.exception))++ def test_fresh_run_dir_rejects_empty_artifact_directory_with_resume_guidance(self) -> None:+ from praxist.cli import start++ for artifact_name in ("frontier", "findings", "gen_1"):+ with self.subTest(artifact=artifact_name):+ task = _make_task_dir(Path(self.workspace.name), name=f"empty_{artifact_name}_task")+ run_dir = Path(self.workspace.name) / f"empty_{artifact_name}_run"+ run_dir.mkdir(parents=True)+ (run_dir / artifact_name).mkdir()+ with self.assertRaises(start.StartError) as cm:+ start.launch_run(+ task_path=str(task),+ run_dir=str(run_dir),+ model=None,+ model_provider_ref=None,+ frontier_strategy="auto",+ cohort=None,+ generations=None,+ server=False,+ resume=False,+ spawn=MagicMock(return_value=_FakeProc()),+ )+ self.assertIn("fresh run directory is not empty", str(cm.exception))+ self.assertIn("Choose another --run-dir or use --resume-from.", str(cm.exception))++ def test_fresh_run_dir_rejects_unrelated_nonempty_directory_without_resume_guidance(+ self,+ ) -> None:+ from praxist.cli import start++ task = _make_task_dir(Path(self.workspace.name), name="unrelated_nonempty_task")+ run_dir = Path(self.workspace.name) / "unrelated_nonempty_run"+ run_dir.mkdir(parents=True)+ (run_dir / "user_notes.txt").write_text("notes", encoding="utf-8")+ with self.assertRaises(start.StartError) as cm:+ start.launch_run(+ task_path=str(task),+ run_dir=str(run_dir),+ model=None,+ model_provider_ref=None,+ frontier_strategy="auto",+ cohort=None,+ generations=None,+ server=False,+ resume=False,+ spawn=MagicMock(return_value=_FakeProc()),+ )+ self.assertIn("fresh run directory is not empty", str(cm.exception))+ self.assertIn("Choose another --run-dir.", str(cm.exception))+ self.assertNotIn("--resume-from", str(cm.exception))++ def test_fresh_run_dir_allows_ignorable_precreated_paths(self) -> None:+ from praxist.cli import start++ task = _make_task_dir(Path(self.workspace.name), name="ignorable_paths_task")+ run_dir = Path(self.workspace.name) / "ignorable_paths_run"+ run_dir.mkdir(parents=True)+ (run_dir / ".gitkeep").write_text("", encoding="utf-8")+ (run_dir / ".DS_Store").write_text("", encoding="utf-8")+ logs_dir = run_dir / "logs"+ logs_dir.mkdir()+ (logs_dir / "launcher.nohup.log").write_text("", encoding="utf-8")++ entry = start.launch_run(+ task_path=str(task),+ run_dir=str(run_dir),+ model=None,+ model_provider_ref=None,+ frontier_strategy="auto",+ cohort=None,+ generations=None,+ server=False,+ resume=False,+ spawn=MagicMock(return_value=_FakeProc()),+ )+ self.assertEqual(Path(entry.run_dir), run_dir.resolve())+def test_server_flag_drops_local_arg(self) -> None:from praxist.cli import start@@ -1363,7 +1463,7 @@ class StartCliEndToEndTest(unittest.TestCase):self.assertIn("praxist --monitor --run-id", err)def test_dispatcher_hint_shell_quotes_explicit_run_dir(self) -> None:- run_dir = Path(self.workspace.name).resolve() / "run with spaces;printf unsafe"+ run_dir = (Path(self.workspace.name) / "run with spaces;printf unsafe").resolve()code, out, err = self._run(["start", "--task-path", str(self.task), "--run-dir", str(run_dir)])diff --git a/tests/unit/test_cli_status.py b/tests/unit/test_cli_status.pyindex bb452aa..53432ac 100644--- a/tests/unit/test_cli_status.py+++ b/tests/unit/test_cli_status.py@@ -314,6 +314,45 @@ class StatusMergeTest(unittest.TestCase):self.assertEqual(row.model, "claude-opus-4-7")self.assertEqual(row.state, "running")+ def test_daemonized_registry_row_with_missing_etime_stays_live(self) -> None:+ from praxist.cli import status++ run_id = self._seed_registry(+ command=(+ "python",+ "-m",+ "praxist.run",+ "run",+ "--task-path",+ "/t",+ "--run-dir",+ "/tmp/status_demo",+ ),+ )+ ps_output = (+ " PID PPID ELAPSED COMMAND\n"+ " 8000 0 python -m praxist.run run --task-path /t --run-dir /tmp/status_demo\n"+ )+ with (+ patch("praxist.cli.status.shutil.which", return_value="/bin/ps"),+ patch(+ "praxist.cli.status.subprocess.run",+ return_value=_fake_ps_completed(ps_output),+ ),+ patch.object(os, "getpid", return_value=99998),+ patch.object(os, "getppid", return_value=99999),+ ):+ rows = status.collect_status_rows(include_peer_health=False)++ self.assertEqual(len(rows), 1)+ row = rows[0]+ self.assertEqual(row.run_id, run_id)+ self.assertEqual(row.source, status.SOURCE_REGISTRY)+ self.assertEqual(row.state, "running")+ self.assertEqual(row.ppid, 0)+ self.assertEqual(row.etime, "-")+ self.assertIn("python -m praxist.run", row.command)+def test_live_process_with_stopped_registry_is_inconsistent(self) -> None:from praxist.cli import registry, statusdiff --git a/tests/unit/test_research_loop_resume_contracts.py b/tests/unit/test_research_loop_resume_contracts.pyindex 427b0b1..c7e0ffb 100644--- a/tests/unit/test_research_loop_resume_contracts.py+++ b/tests/unit/test_research_loop_resume_contracts.py@@ -616,11 +616,105 @@ class ResearchLoopResumeContractsTest(unittest.TestCase):(run_dir / "run.json").write_text("{}", encoding="utf-8")(run_dir / "startup_config.json").write_text("{}", encoding="utf-8")- with self.assertRaises(ValueError):+ with self.assertRaises(ValueError) as cm:startup._ensure_fresh_run_dir(run_dir)+ self.assertIn("already contains Praxist run artifacts", str(cm.exception))+ self.assertIn("Use --resume or --resume-from", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))startup._ensure_fresh_run_dir(run_dir, resume=True)+ def test_startup_non_resume_distinguishes_run_artifacts_from_unrelated_files(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ dir_with_unrelated = Path(tmp) / "unrelated"+ dir_with_unrelated.mkdir()+ (dir_with_unrelated / "user_notes.txt").write_text("hello", encoding="utf-8")++ with self.assertRaises(ValueError) as cm:+ startup._ensure_fresh_run_dir(dir_with_unrelated)+ self.assertIn("already exists and is not empty", str(cm.exception))+ self.assertIn("Choose a fresh run directory.", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))+ self.assertNotIn("--resume-from", str(cm.exception))++ def test_startup_non_resume_detects_individual_praxist_artifacts(self) -> None:+ for rel in startup.PRAXIST_RUN_ARTIFACT_REL_PATHS:+ with tempfile.TemporaryDirectory() as tmp:+ run_dir = Path(tmp) / "test_run"+ run_dir.mkdir()+ artifact_path = run_dir / rel+ if rel in {"findings", "frontier", "agendas", "memory", "gems", "gen_0"}:+ artifact_path.mkdir(parents=True)+ else:+ artifact_path.parent.mkdir(parents=True, exist_ok=True)+ artifact_path.write_text("{}", encoding="utf-8")++ with self.assertRaises(ValueError) as cm:+ startup._ensure_fresh_run_dir(run_dir)+ self.assertIn("already contains Praxist run artifacts", str(cm.exception))+ self.assertIn("Use --resume or --resume-from", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))++ with tempfile.TemporaryDirectory() as tmp:+ run_dir = Path(tmp) / "test_run_gen_1"+ run_dir.mkdir()+ (run_dir / "gen_1").mkdir()+ with self.assertRaises(ValueError) as cm:+ startup._ensure_fresh_run_dir(run_dir)+ self.assertIn("already contains Praxist run artifacts", str(cm.exception))+ self.assertIn("Use --resume or --resume-from", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))++ def test_resume_mode_on_missing_or_damaged_artifacts_requires_manual_inspection(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ empty_dir = Path(tmp) / "empty"+ empty_dir.mkdir()+ with self.assertRaises(ValueError) as cm:+ startup._ensure_fresh_run_dir(empty_dir, resume=True)+ self.assertIn("missing Praxist startup artifacts", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))++ with tempfile.TemporaryDirectory() as tmp:+ bad_json_dir = Path(tmp) / "bad_json"+ bad_json_dir.mkdir()+ (bad_json_dir / "run.json").write_text("{not-valid-json", encoding="utf-8")+ (bad_json_dir / "startup_config.json").write_text("{}", encoding="utf-8")+ with self.assertRaises(ValueError) as cm:+ resume_state._read_json_object_for_resume(bad_json_dir / "run.json")+ self.assertIn("not valid JSON", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))++ with tempfile.TemporaryDirectory() as tmp:+ non_obj_dir = Path(tmp) / "non_obj"+ non_obj_dir.mkdir()+ (non_obj_dir / "run.json").write_text("[1, 2, 3]", encoding="utf-8")+ with self.assertRaises(ValueError) as cm:+ resume_state._read_json_object_for_resume(non_obj_dir / "run.json")+ self.assertIn("must be a JSON object", str(cm.exception))+ self.assertIn("Manual inspection is required", str(cm.exception))++ def test_resume_plan_safely_handles_already_completed_all_generations(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ run_dir = Path(tmp) / "completed_run"+ run_dir.mkdir()+ (run_dir / "startup_config.json").write_text(+ json.dumps({"contract_version": 2, "marker_contract_start": 0}), encoding="utf-8"+ )+ # Generation 0 complete+ self._write_generation_results(run_dir, 0)+ write_boundary_marker(run_dir, gen_id=0, promoted_count=1, pi_status="succeeded")++ # Generation 1 complete+ self._write_generation_results(run_dir, 1)+ write_boundary_marker(run_dir, gen_id=1, promoted_count=1, pi_status="succeeded")++ plan = inspect_resume_plan(run_dir, max_generations=2, pi_enabled=True)+ self.assertEqual(plan.completed_generations, 2)+ self.assertEqual(plan.start_generation, 2)+ self.assertIsNone(plan.pending_boundary_generation)+ self.assertFalse(plan.has_pending_boundary)+ self.assertEqual(plan.warnings, ())+def test_startup_resume_identity_accepts_matching_canonical_args(self) -> None:with tempfile.TemporaryDirectory() as tmp:run_dir = Path(tmp) / "run_a"diff --git a/tests/unit/test_run_lifecycle_contracts.py b/tests/unit/test_run_lifecycle_contracts.pyindex f79c07b..2dcd194 100644--- a/tests/unit/test_run_lifecycle_contracts.py+++ b/tests/unit/test_run_lifecycle_contracts.py@@ -212,6 +212,36 @@ class RunLifecycleGateContractsTest(unittest.TestCase):"absolute_run_local",)+ def test_relative_run_dir_accepts_an_absolute_run_local_stop_signal(self) -> None:+ with tempfile.TemporaryDirectory(dir=Path.cwd()) as tmp:+ root = Path(tmp).relative_to(Path.cwd())+ run_dir = root / "run"+ run_dir.mkdir()+ signal = (run_dir / "run_control" / "stop.json").resolve()++ write_external_stop_signal(+ run_dir,+ {"reason": "absolute_run_local"},+ stop_signal_path=str(signal),+ )++ self.assertTrue(signal.is_file())+ decision = evaluate_run_stop_gate(+ task_spec=SimpleNamespace(+ run_lifecycle=SimpleNamespace(+ max_wall_clock_hours=None,+ stop_signal_path=str(signal),+ )+ ),+ run_dir=run_dir,+ run_started_at_seconds=10.0,+ now_seconds=20.0,+ next_generation=1,+ generations_completed=1,+ )+ self.assertTrue(decision.should_stop)+ self.assertEqual(decision.signal_evidence["reason"], "absolute_run_local")+def test_stop_signal_paths_must_be_run_local_plain_paths(self) -> None:with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)diff --git a/tests/unit/test_startup_helper_contracts.py b/tests/unit/test_startup_helper_contracts.pyindex 9c4e0ac..f9aa186 100644--- a/tests/unit/test_startup_helper_contracts.py+++ b/tests/unit/test_startup_helper_contracts.py@@ -529,13 +529,21 @@ class StartupHelperContractsTest(unittest.TestCase):(run_dir / "empty").mkdir()startup._ensure_fresh_run_dir(run_dir)(run_dir / "run.json").write_text("{}", encoding="utf-8")- with self.assertRaises(ValueError):+ with self.assertRaises(ValueError) as cm:startup._ensure_fresh_run_dir(run_dir)+ self.assertIn("already contains Praxist run artifacts", str(cm.exception))+ self.assertIn("Use --resume or --resume-from", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))+blocked = workspace / "blocked_run"(blocked / "nonempty").mkdir(parents=True)(blocked / "nonempty" / "x").write_text("x", encoding="utf-8")- with self.assertRaises(ValueError):+ with self.assertRaises(ValueError) as cm:startup._ensure_fresh_run_dir(blocked)+ self.assertIn("already exists and is not empty", str(cm.exception))+ self.assertIn("Choose a fresh run directory.", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))+ self.assertNotIn("--resume-from", str(cm.exception))descriptor_path = workspace / "task.yaml"descriptor_path.write_text("[1]", encoding="utf-8")diff --git a/tests/workflows/test_research_loop.py b/tests/workflows/test_research_loop.pyindex 57243bb..f6f6a57 100644--- a/tests/workflows/test_research_loop.py+++ b/tests/workflows/test_research_loop.py@@ -251,6 +251,91 @@ class ResearchLoopWorkflowTest(unittest.TestCase):disabled = prepared.resolution_manifest["disabled_optional"]self.assertTrue(any(item.get("stage_id") == "ideation" for item in disabled))+ def test_research_loop_startup_rejects_preexisting_artifacts_with_resume_guidance(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ run_dir = (root / "run_existing").resolve()+ with patch.dict(os.environ, {}, clear=False):+ prepare_research_loop_plugin_run(+ task_project_path=Path.cwd() / "templates" / "tasks" / "toy_math",+ workspace=root,+ run_dir=run_dir,+ runtime_ref="agent_runtime:fake_runtime",+ model_provider_ref="model_provider:fake_provider",+ budget_policy_ref="budget_policy:fake_tiered",+ model="fake-deterministic",+ local_mode=True,+ frontier_strategy="auto",+ credential_profile="fake_multi_key",+ command="initial test",+ )+ with self.assertRaises(ValueError) as cm:+ prepare_research_loop_plugin_run(+ task_project_path=Path.cwd() / "templates" / "tasks" / "toy_math",+ workspace=root,+ run_dir=run_dir,+ runtime_ref="agent_runtime:fake_runtime",+ model_provider_ref="model_provider:fake_provider",+ budget_policy_ref="budget_policy:fake_tiered",+ model="fake-deterministic",+ local_mode=True,+ frontier_strategy="auto",+ credential_profile="fake_multi_key",+ command="second test",+ resume=False,+ )+ self.assertIn("already contains Praxist run artifacts", str(cm.exception))+ self.assertIn("Use --resume or --resume-from", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))++ with patch.dict(os.environ, {}, clear=False):+ resumed = prepare_research_loop_plugin_run(+ task_project_path=Path.cwd() / "templates" / "tasks" / "toy_math",+ workspace=root,+ run_dir=run_dir,+ runtime_ref="agent_runtime:fake_runtime",+ model_provider_ref="model_provider:fake_provider",+ budget_policy_ref="budget_policy:fake_tiered",+ model="fake-deterministic",+ local_mode=True,+ frontier_strategy="auto",+ credential_profile="fake_multi_key",+ command="resumed test",+ resume=True,+ )+ self.assertEqual(resumed.run_dir, run_dir)+ run_json = json.loads((run_dir / "run.json").read_text(encoding="utf-8"))+ self.assertEqual(run_json.get("resume_count"), 1)+ self.assertIn("resumed_at", run_json)++ def test_research_loop_startup_rejects_unrelated_nonempty_directory_without_resume_guidance(+ self,+ ) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ run_dir = (root / "run_unrelated").resolve()+ run_dir.mkdir()+ (run_dir / "random.txt").write_text("hello", encoding="utf-8")+ with self.assertRaises(ValueError) as cm:+ prepare_research_loop_plugin_run(+ task_project_path=Path.cwd() / "templates" / "tasks" / "toy_math",+ workspace=root,+ run_dir=run_dir,+ runtime_ref="agent_runtime:fake_runtime",+ model_provider_ref="model_provider:fake_provider",+ budget_policy_ref="budget_policy:fake_tiered",+ model="fake-deterministic",+ local_mode=True,+ frontier_strategy="auto",+ credential_profile="fake_multi_key",+ command="unrelated test",+ resume=False,+ )+ self.assertIn("already exists and is not empty", str(cm.exception))+ self.assertIn("Choose a fresh run directory.", str(cm.exception))+ self.assertNotIn("Resume mode is not implemented", str(cm.exception))+ self.assertNotIn("--resume-from", str(cm.exception))+if __name__ == "__main__":unittest.main()