forgexa-cli 1.98.1__tar.gz → 1.98.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/PKG-INFO +1 -1
  2. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/agent_core.py +142 -17
  4. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/component_runtime.py +52 -2
  5. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/daemon.py +62 -18
  6. forgexa_cli-1.98.3/forgexa_cli/workspace_storage.py +348 -0
  7. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/PKG-INFO +1 -1
  8. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/SOURCES.txt +3 -1
  9. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/pyproject.toml +1 -1
  10. forgexa_cli-1.98.3/tests/test_workspace_storage.py +289 -0
  11. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/README.md +0 -0
  12. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/_build_config.py +0 -0
  13. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/_local_bind.py +0 -0
  14. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/autoupgrade.py +0 -0
  15. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/aws_evidence.py +0 -0
  16. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/aws_logs_evidence.py +0 -0
  17. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/main.py +0 -0
  18. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/observability_contract.py +0 -0
  19. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/observability_evidence.py +0 -0
  20. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/ocr_adapter.py +0 -0
  21. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/py.typed +0 -0
  22. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/runtime_evidence.py +0 -0
  23. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli/zcode_protocol.py +0 -0
  24. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  25. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/entry_points.txt +0 -0
  26. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/requires.txt +0 -0
  27. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/forgexa_cli.egg-info/top_level.txt +0 -0
  28. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/setup.cfg +0 -0
  29. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_auth_and_runtime_commands.py +0 -0
  30. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_autoupgrade.py +0 -0
  31. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_check_command.py +0 -0
  32. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_expiry_warnings_and_revoke.py +0 -0
  33. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_local_bind_commands.py +0 -0
  34. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_publish_script.py +0 -0
  35. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_runtime_credentials.py +0 -0
  36. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_session_credentials.py +0 -0
  37. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_silent_install.py +0 -0
  38. {forgexa_cli-1.98.1 → forgexa_cli-1.98.3}/tests/test_upgrade_observability.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.98.1
3
+ Version: 1.98.3
4
4
  Summary: Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform
5
5
  Author-email: Jason Sun <dev.winds@gmail.com>
6
6
  License-Expression: MIT
@@ -1,2 +1,2 @@
1
1
  """forgexa-cli — Forgexa command-line client."""
2
- __version__ = "1.98.1"
2
+ __version__ = "1.98.3"
@@ -777,7 +777,7 @@ def task_failure_domain(
777
777
  if failure_code in {
778
778
  "planned_task_incomplete", "planned_task_baseline_invalid", "approved_plan_baseline_modified",
779
779
  "remediation_scope_violation", "verification_work_item_scope_violation", "uncommitted_workspace_changes",
780
- "forbidden_branch_merge",
780
+ "forbidden_branch_merge", "required_deliverable_missing",
781
781
  }:
782
782
  return "delivery"
783
783
  if failure_code == "implementation_plan_revision_required":
@@ -888,6 +888,7 @@ def implementation_validation_issue_blocks(node_type: str, task_input: dict, cod
888
888
  "qa_policy.source_test_path_invalid",
889
889
  "qa_policy.source_change_inventory_unavailable",
890
890
  "uncommitted_workspace_changes", "forbidden_branch_merge",
891
+ "required_deliverable_missing",
891
892
  }
892
893
 
893
894
 
@@ -2097,6 +2098,11 @@ class AgentDiscovery:
2097
2098
  if additions:
2098
2099
  os.environ["PATH"] = os.pathsep.join(additions) + os.pathsep + current
2099
2100
  logger.debug("Expanded PATH with: %s", ", ".join(additions))
2101
+ if not is_win:
2102
+ official_trae = home / ".forgexa" / "official" / "trae" / "bin"
2103
+ current = os.environ.get("PATH", "")
2104
+ if official_trae.is_dir() and str(official_trae) not in current.split(os.pathsep):
2105
+ os.environ["PATH"] = os.pathsep.join(filter(None, (current, str(official_trae))))
2100
2106
 
2101
2107
  @staticmethod
2102
2108
  def _wsl_windows_executable(path: str) -> bool:
@@ -2709,6 +2715,68 @@ def opencode_error_message(event: dict) -> str | None:
2709
2715
  return None
2710
2716
 
2711
2717
 
2718
+ @dataclass
2719
+ class OpenCodeRunState:
2720
+ """Track native completion independently of bounded stdout tails."""
2721
+
2722
+ session_id: str | None = None
2723
+ message_id: str | None = None
2724
+ messages: set[str] = field(default_factory=set)
2725
+ finish_reason: str | None = None
2726
+ error: str | None = None
2727
+ error_code: str = "agent_error"
2728
+
2729
+ def feed_output(self, output: str) -> None:
2730
+ for line in output.splitlines():
2731
+ try:
2732
+ event = json.loads(line)
2733
+ except json.JSONDecodeError:
2734
+ continue
2735
+ if isinstance(event, dict):
2736
+ self.feed(event)
2737
+
2738
+ def feed(self, event: dict) -> None:
2739
+ kind = event.get("type")
2740
+ if kind == "error":
2741
+ self.error = self.error or opencode_error_message(event) or "OpenCode reported an error"
2742
+ return
2743
+ if kind not in {"step_start", "text", "tool_use", "step_finish"}:
2744
+ return
2745
+ session, part = event.get("sessionID"), event.get("part")
2746
+ if not isinstance(session, str) or not session or not isinstance(part, dict):
2747
+ self.error = "OpenCode event has no session or part"
2748
+ self.error_code = "agent_protocol_error"
2749
+ return
2750
+ if self.session_id is not None and session != self.session_id:
2751
+ return
2752
+ message = part.get("messageID")
2753
+ if not isinstance(message, str) or not message:
2754
+ self.error = "OpenCode event has no message identity"
2755
+ self.error_code = "agent_protocol_error"
2756
+ return
2757
+ self.session_id = session
2758
+ if message != self.message_id:
2759
+ if message in self.messages:
2760
+ return
2761
+ self.messages.add(message)
2762
+ self.message_id, self.finish_reason = message, None
2763
+ if kind == "step_finish":
2764
+ self.finish_reason = part.get("reason")
2765
+
2766
+ def failure(self) -> tuple[str, str] | None:
2767
+ if self.error:
2768
+ return self.error_code, self.error
2769
+ if self.session_id is None:
2770
+ return "agent_protocol_error", "OpenCode did not emit valid JSON events"
2771
+ if self.finish_reason != "stop":
2772
+ return (
2773
+ "agent_incomplete_turn",
2774
+ "OpenCode exited without a final step_finish(reason=stop) for the active turn. "
2775
+ "Pending background-agent work cannot finish after this one-shot invocation exits.",
2776
+ )
2777
+ return None
2778
+
2779
+
2712
2780
  class OpenCodeUsage:
2713
2781
  """Accumulate v2 step totals once per native assistant message."""
2714
2782
 
@@ -3641,6 +3709,34 @@ def build_codex_command(
3641
3709
  return cmd
3642
3710
 
3643
3711
 
3712
+ OPENCODE_WORKER_AGENT = "forgexa-worker"
3713
+ _OPENCODE_WORKER_DENIED_TOOLS = (
3714
+ "task", "subagent", "delegate_task", "call_omo_agent",
3715
+ "background_output", "background_cancel",
3716
+ )
3717
+
3718
+
3719
+ class OpenCodeConfigurationError(RuntimeError):
3720
+ pass
3721
+
3722
+
3723
+ def opencode_worker_prompt(prompt: str) -> str:
3724
+ heading = "## Forgexa One-Shot Worker"
3725
+ if heading in prompt:
3726
+ return prompt
3727
+ return (
3728
+ f"{prompt}\n\n{heading}\n"
3729
+ "Execute the assigned task yourself in this invocation. Do not delegate to subagents "
3730
+ "or launch background-agent work. Skills and ordinary repository tools remain available. "
3731
+ "This is not an interactive orchestration session: returning ends the invocation, and "
3732
+ "no later background completion notifications will arrive. Do not finish with a progress "
3733
+ "update or a promise to continue later. Produce the requested outputs now; when outputs "
3734
+ "are files, write and check those files in the authorized workspace before finishing. "
3735
+ "If a prerequisite genuinely blocks work, report it explicitly and record permitted "
3736
+ "partial results and evidence gaps without claiming unverified completion."
3737
+ )
3738
+
3739
+
3644
3740
  def build_opencode_command(
3645
3741
  binary: str,
3646
3742
  *,
@@ -3651,6 +3747,7 @@ def build_opencode_command(
3651
3747
  prompt: str | None = None,
3652
3748
  profile: OpenCodeProfile = "v1",
3653
3749
  auto_approve: bool = True,
3750
+ single_worker: bool = False,
3654
3751
  ) -> list[str]:
3655
3752
  """OpenCode CLI non-interactive invocation.
3656
3753
 
@@ -3672,6 +3769,8 @@ def build_opencode_command(
3672
3769
  cmd.append("--auto" if profile == "v2" else "--dangerously-skip-permissions")
3673
3770
  if profile == "v1":
3674
3771
  cmd += ["--dir", str(cwd)]
3772
+ if single_worker:
3773
+ cmd += ["--agent", OPENCODE_WORKER_AGENT]
3675
3774
  if session_id:
3676
3775
  cmd += ["--session", session_id]
3677
3776
  if model:
@@ -5084,6 +5183,7 @@ def opencode_base_env(
5084
5183
  env: dict[str, str], *, data_home: str | Path | None = None,
5085
5184
  require_windows_shell: bool = False, profile: OpenCodeProfile = "v1",
5086
5185
  cwd: str | Path | None = None,
5186
+ single_worker: bool = False,
5087
5187
  ) -> dict[str, str]:
5088
5188
  """Isolate each OpenCode run in its own XDG data directory.
5089
5189
 
@@ -5102,6 +5202,31 @@ def opencode_base_env(
5102
5202
  for key in list(env):
5103
5203
  if key.upper().startswith(platform_secrets):
5104
5204
  del env[key]
5205
+ if single_worker:
5206
+ config = _opencode_config_content(env)
5207
+ agents = config.setdefault("agent", {})
5208
+ if not isinstance(agents, dict):
5209
+ raise OpenCodeConfigurationError(
5210
+ "OpenCode worker configuration requires an agent object",
5211
+ )
5212
+ worker = agents.setdefault(OPENCODE_WORKER_AGENT, {})
5213
+ if not isinstance(worker, dict):
5214
+ raise OpenCodeConfigurationError("OpenCode worker configuration must be an object")
5215
+ permissions = worker.get("permission", {})
5216
+ if isinstance(permissions, str):
5217
+ permissions = {"*": permissions}
5218
+ if not isinstance(permissions, dict):
5219
+ raise OpenCodeConfigurationError(
5220
+ "OpenCode worker permissions must be an object or action",
5221
+ )
5222
+ worker.update(
5223
+ mode="primary", hidden=True, disable=False,
5224
+ permission={
5225
+ **permissions,
5226
+ **dict.fromkeys(_OPENCODE_WORKER_DENIED_TOOLS, "deny"),
5227
+ },
5228
+ )
5229
+ env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config, ensure_ascii=False)
5105
5230
  if profile == "v1" and data_home is not None:
5106
5231
  env["XDG_DATA_HOME"] = str(data_home)
5107
5232
  if cwd is not None:
@@ -5112,6 +5237,21 @@ def opencode_base_env(
5112
5237
  return configure_opencode_windows_shell(env, required=require_windows_shell)
5113
5238
 
5114
5239
 
5240
+ def _opencode_config_content(env: dict[str, str]) -> dict[str, Any]:
5241
+ raw_config = env.get("OPENCODE_CONFIG_CONTENT", "").strip()
5242
+ if not raw_config:
5243
+ return {}
5244
+ try:
5245
+ config = json.loads(raw_config)
5246
+ except json.JSONDecodeError as exc:
5247
+ raise OpenCodeConfigurationError(
5248
+ "OpenCode OPENCODE_CONFIG_CONTENT must be a JSON object",
5249
+ ) from exc
5250
+ if not isinstance(config, dict):
5251
+ raise OpenCodeConfigurationError("OpenCode OPENCODE_CONFIG_CONTENT must be a JSON object")
5252
+ return config
5253
+
5254
+
5115
5255
  async def opencode_session_metadata(
5116
5256
  binary: str, session_id: str, *, cwd: str | Path, env: dict[str, str],
5117
5257
  on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
@@ -5211,22 +5351,7 @@ def configure_opencode_windows_shell(
5211
5351
  logger.warning(message)
5212
5352
  return env
5213
5353
 
5214
- raw_config = env.get("OPENCODE_CONFIG_CONTENT", "").strip()
5215
- config: dict[str, Any] = {}
5216
- if raw_config:
5217
- try:
5218
- parsed = json.loads(raw_config)
5219
- except json.JSONDecodeError as exc:
5220
- raise RuntimeError(
5221
- "OPENCODE_CONFIG_CONTENT must be a JSON object to configure "
5222
- "OpenCode's Windows tool shell."
5223
- ) from exc
5224
- if not isinstance(parsed, dict):
5225
- raise RuntimeError(
5226
- "OPENCODE_CONFIG_CONTENT must be a JSON object to configure "
5227
- "OpenCode's Windows tool shell."
5228
- )
5229
- config = parsed
5354
+ config = _opencode_config_content(env)
5230
5355
 
5231
5356
  config["shell"] = shell
5232
5357
  env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config, ensure_ascii=False)
@@ -897,6 +897,26 @@ def runtime_capabilities(
897
897
  }
898
898
 
899
899
 
900
+ def _require_absent_unverified_selection(root: Path, component_id: str) -> None:
901
+ for directory in (root, root / "selections"):
902
+ try:
903
+ metadata = directory.lstat()
904
+ except FileNotFoundError:
905
+ if directory != root:
906
+ return
907
+ raise
908
+ if (
909
+ not stat.S_ISDIR(metadata.st_mode)
910
+ or getattr(metadata, "st_file_attributes", 0) & 0x400
911
+ ):
912
+ raise ComponentRuntimeError("component_storage_invalid")
913
+ try:
914
+ (root / "selections" / f"{component_id}.json").lstat()
915
+ except FileNotFoundError:
916
+ return
917
+ raise ComponentRuntimeError("component_platform_unverified")
918
+
919
+
900
920
  def _acquire_component(
901
921
  component_id: str, root: Path | None = None, override: str | None = None,
902
922
  kind: str = "agent",
@@ -910,11 +930,11 @@ def _acquire_component(
910
930
  if not root.exists():
911
931
  return None
912
932
  if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
913
- raise ComponentRuntimeError("component_platform_unverified")
933
+ _require_absent_unverified_selection(root, component_id)
934
+ return None
914
935
  import fcntl
915
936
 
916
937
  with _ComponentManagerLock(root):
917
- target = _component_target(root)
918
938
  selection = _record(
919
939
  root / "selections" / f"{component_id}.json",
920
940
  {
@@ -929,6 +949,7 @@ def _acquire_component(
929
949
  )
930
950
  if selection is None:
931
951
  return None
952
+ target = _component_target(root)
932
953
  if (
933
954
  selection["target_id"] != target["target_id"]
934
955
  or selection["component_id"] != component_id
@@ -1075,6 +1096,35 @@ def acquire_component(
1075
1096
  raise ComponentRuntimeError("component_storage_unavailable") from error
1076
1097
 
1077
1098
 
1099
+ def require_unselected_component(component_id: str, root: Path | None = None) -> None:
1100
+ _identifier(component_id)
1101
+ root = default_store_root() if root is None else root
1102
+ if root.is_symlink():
1103
+ raise ComponentRuntimeError("component_storage_invalid")
1104
+ if not root.exists():
1105
+ return
1106
+ if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
1107
+ try:
1108
+ _require_absent_unverified_selection(root, component_id)
1109
+ except OSError as error:
1110
+ raise ComponentRuntimeError("component_storage_unavailable") from error
1111
+ return
1112
+ try:
1113
+ with _ComponentManagerLock(root):
1114
+ selection = _record(
1115
+ root / "selections" / f"{component_id}.json",
1116
+ {
1117
+ "schema_version", "target_id", "component_id", "revision", "installation_id",
1118
+ "enabled",
1119
+ },
1120
+ optional_fields={"external", "external_path"},
1121
+ )
1122
+ if selection is not None:
1123
+ raise ComponentRuntimeError("component_selection_changed")
1124
+ except OSError as error:
1125
+ raise ComponentRuntimeError("component_storage_unavailable") from error
1126
+
1127
+
1078
1128
  def require_external_selection(
1079
1129
  component_id: str, revision: int, root: Path | None = None, *, allow_disabled: bool = False,
1080
1130
  ) -> str | None:
@@ -1412,7 +1412,7 @@ except (ImportError, ModuleNotFoundError):
1412
1412
  # DAEMON_VERSION is the protocol/logic version of the daemon code.
1413
1413
  # Kept in sync with pyproject.toml version via bump-version.sh.
1414
1414
  # CLIENT_TYPE identifies which packaging/distribution this daemon runs in.
1415
- DAEMON_VERSION = "1.98.1"
1415
+ DAEMON_VERSION = "1.98.3"
1416
1416
 
1417
1417
 
1418
1418
  def _detect_client_type() -> str:
@@ -7831,6 +7831,7 @@ class ProcessManager:
7831
7831
  usage = agent_core.OpenCodeUsage()
7832
7832
  usage_errors: list[str] = []
7833
7833
  has_native_output = False
7834
+ run_state = agent_core.OpenCodeRunState()
7834
7835
 
7835
7836
  async def collect_output(lines: list[str]) -> None:
7836
7837
  nonlocal has_native_output
@@ -7840,7 +7841,10 @@ class ProcessManager:
7840
7841
  event = json.loads(line)
7841
7842
  except json.JSONDecodeError:
7842
7843
  continue
7843
- if isinstance(event, dict) and event.get("type") == "step_finish":
7844
+ if not isinstance(event, dict):
7845
+ continue
7846
+ run_state.feed(event)
7847
+ if profile == "v2" and event.get("type") == "step_finish":
7844
7848
  try:
7845
7849
  usage.add(event)
7846
7850
  except ValueError as exc:
@@ -7848,7 +7852,7 @@ class ProcessManager:
7848
7852
  if on_chunk:
7849
7853
  await on_chunk(lines)
7850
7854
 
7851
- chunk_handler = collect_output if profile == "v2" else on_chunk
7855
+ chunk_handler = collect_output
7852
7856
  run_options = {"cleanup_process_tree": True} if profile == "v2" else {}
7853
7857
  # Isolate each opencode run in its own data directory to prevent
7854
7858
  # concurrent processes from racing on the shared SQLite WAL file.
@@ -7857,13 +7861,14 @@ class ProcessManager:
7857
7861
  isolated_data_dir = Path(tmp_data_root) / "opencode"
7858
7862
  isolated_data_dir.mkdir()
7859
7863
  prompt_file = Path(tmp_data_root) / "instructions.md"
7860
- prompt_file.write_text(prompt, encoding="utf-8")
7864
+ prompt_file.write_text(agent_core.opencode_worker_prompt(prompt), encoding="utf-8")
7861
7865
  cmd = agent_core.build_opencode_command(
7862
7866
  agent.command,
7863
7867
  cwd=cwd,
7864
7868
  model=model_override,
7865
7869
  prompt_file=prompt_file,
7866
7870
  profile=profile,
7871
+ single_worker=True,
7867
7872
  )
7868
7873
  # Copy auth.json so provider credentials are available.
7869
7874
  auth_src = Path.home() / ".local" / "share" / "opencode" / "auth.json"
@@ -7876,8 +7881,15 @@ class ProcessManager:
7876
7881
  require_windows_shell=True,
7877
7882
  profile=profile,
7878
7883
  cwd=cwd,
7884
+ single_worker=True,
7879
7885
  )
7880
7886
  env.update(TMPDIR=tmp_data_root, BUN_TMPDIR=tmp_data_root)
7887
+ except agent_core.OpenCodeConfigurationError as exc:
7888
+ logger.warning("Invalid OpenCode configuration for task %s: %s", task_id, exc)
7889
+ return TaskResult(
7890
+ status="failed", exit_code=-1, stdout="", stderr="",
7891
+ error=str(exc), failure_code="agent_protocol_error",
7892
+ )
7881
7893
  except RuntimeError as exc:
7882
7894
  return TaskResult(
7883
7895
  status="failed",
@@ -7891,10 +7903,15 @@ class ProcessManager:
7891
7903
  cmd, cwd, timeout, task_id, on_chunk=chunk_handler, env=env,
7892
7904
  **run_options,
7893
7905
  )
7906
+ run_state.feed_output(result.stdout)
7894
7907
  signals = agent_core._extract_output_signals(result.stdout)
7895
- if signals["has_turn_failed"]:
7908
+ if run_state.error or signals["has_turn_failed"]:
7896
7909
  result.status = "failed"
7897
- result.error = "\n".join(signals["error_messages"]) or "OpenCode reported an error"
7910
+ result.error = (
7911
+ run_state.error
7912
+ or "\n".join(signals["error_messages"])
7913
+ or "OpenCode reported an error"
7914
+ )
7898
7915
  output = "\n".join(
7899
7916
  part for part in (
7900
7917
  result.stdout if profile == "v1" else result.error,
@@ -7932,6 +7949,7 @@ class ProcessManager:
7932
7949
  usage = agent_core.OpenCodeUsage()
7933
7950
  usage_errors.clear()
7934
7951
  has_native_output = False
7952
+ run_state = agent_core.OpenCodeRunState()
7935
7953
  retry_env = dict(env)
7936
7954
  retry_env.pop("FACTORY_OPENCODE_MODEL", None)
7937
7955
  cmd = agent_core.build_opencode_command(
@@ -7940,6 +7958,7 @@ class ProcessManager:
7940
7958
  model=retry_model,
7941
7959
  prompt_file=prompt_file,
7942
7960
  profile=profile,
7961
+ single_worker=True,
7943
7962
  )
7944
7963
  result = await self._run_cli(
7945
7964
  cmd, cwd, timeout, task_id, on_chunk=chunk_handler, env=retry_env,
@@ -7949,23 +7968,31 @@ class ProcessManager:
7949
7968
  finally:
7950
7969
  shutil.rmtree(tmp_data_root, ignore_errors=True)
7951
7970
 
7971
+ run_state.feed_output(result.stdout)
7952
7972
  signals = agent_core._extract_output_signals(result.stdout)
7953
- if signals["has_turn_failed"]:
7973
+ if run_state.error or signals["has_turn_failed"]:
7974
+ result.status = "failed"
7975
+ result.error = (
7976
+ run_state.error
7977
+ or "\n".join(signals["error_messages"])
7978
+ or "OpenCode reported an error"
7979
+ )
7980
+ failure = run_state.failure()
7981
+ result.has_verified_completion = failure is None and result.status == "success"
7982
+ if failure and (result.status == "success" or run_state.error):
7954
7983
  result.status = "failed"
7955
- result.error = "\n".join(signals["error_messages"]) or "OpenCode reported an error"
7984
+ result.failure_code, result.error = failure
7985
+ logger.warning("OpenCode execution incomplete for task %s: %s", task_id, result.error)
7956
7986
  try:
7957
7987
  if usage_errors:
7958
7988
  raise ValueError(usage_errors[0])
7959
- if profile == "v2" and result.status == "success" and not (
7960
- has_native_output or agent_core.opencode_v2_has_output(result.stdout)
7961
- ):
7962
- raise ValueError("OpenCode v2 did not emit valid JSON events")
7963
7989
  parsed_metrics = dict(usage.totals) if profile == "v2" and usage.seen else (
7964
7990
  agent_core._parse_agent_jsonl_output(result.stdout, opencode_profile=profile)
7965
7991
  )
7966
7992
  except ValueError as exc:
7967
7993
  logger.warning("OpenCode output protocol failed for task %s: %s", task_id, exc)
7968
7994
  result.status, result.error, result.failure_code = "failed", str(exc), "agent_protocol_error"
7995
+ result.has_verified_completion = False
7969
7996
  return result
7970
7997
  result.metrics.update(parsed_metrics)
7971
7998
  return result
@@ -13936,11 +13963,13 @@ class RuntimeDaemon:
13936
13963
  # 4.1 Recovery: agent exited non-zero but already committed code.
13937
13964
  # Covers two scenarios:
13938
13965
  # A. Process crash (e.g. OpenCode EBADF on exit after successful work):
13939
- # exit_code is a real non-negative/non-(-1) value.
13966
+ # exit_code is positive, not a failed zero-exit completion check.
13940
13967
  # B. Timeout with committed work: agent finished its task and committed
13941
13968
  # before the idle/absolute timeout fired. exit_code=-1 but the commits
13942
13969
  # are real — don't discard them.
13943
- if result.status == "failed":
13970
+ if result.status == "failed" and result.failure_code not in {
13971
+ "agent_incomplete_turn", "agent_protocol_error",
13972
+ }:
13944
13973
  _error_lower = (result.error or "").lower()
13945
13974
  is_timeout_failure = (
13946
13975
  "idle for" in _error_lower
@@ -13949,7 +13978,7 @@ class RuntimeDaemon:
13949
13978
  )
13950
13979
  can_attempt_recovery = (
13951
13980
  is_timeout_failure # timeout: also allow exit_code=-1
13952
- or result.exit_code not in (None, -1) # crash: original guard
13981
+ or result.exit_code not in (None, -1, 0)
13953
13982
  )
13954
13983
  if can_attempt_recovery:
13955
13984
  original_exit_code = result.exit_code
@@ -14159,6 +14188,7 @@ class RuntimeDaemon:
14159
14188
  task.task_id, task.node_type,
14160
14189
  )
14161
14190
  result.status = "failed"
14191
+ result.failure_code = "required_deliverable_missing"
14162
14192
  result.error = (
14163
14193
  f"Agent reported success but did not update required {task.node_type} deliverables "
14164
14194
  f"(agent={agent.agent_id})"
@@ -15314,10 +15344,17 @@ class RuntimeDaemon:
15314
15344
  if doc_dir:
15315
15345
  design_filename = _get_design_output_for_type(req_type, _task_change_scope(input_data))
15316
15346
  design_path = workspace_path / doc_dir / design_filename
15317
- if not design_path.exists():
15318
- issues.append(f"Design document missing: {doc_dir}/{design_filename}")
15347
+ if not design_path.is_file():
15348
+ issues.append(_OutputValidationIssue(
15349
+ "required_deliverable_missing",
15350
+ f"Design document missing: {doc_dir}/{design_filename} "
15351
+ "(expected a regular file)",
15352
+ ))
15319
15353
  elif design_path.stat().st_size == 0:
15320
- issues.append(f"Design document is empty: {doc_dir}/{design_filename}")
15354
+ issues.append(_OutputValidationIssue(
15355
+ "required_deliverable_missing",
15356
+ f"Design document is empty: {doc_dir}/{design_filename}",
15357
+ ))
15321
15358
 
15322
15359
  elif node_type in ("coding", "testing", "fix", "review"):
15323
15360
  # Syntax-check modified Python and JS/TS files
@@ -20904,6 +20941,13 @@ async def main():
20904
20941
 
20905
20942
  def main_sync():
20906
20943
  """Synchronous entry point for CLI: forgexa-daemon"""
20944
+ if sys.argv[1:] == ["--workspace-storage"]:
20945
+ try:
20946
+ from .workspace_storage import main as storage_main
20947
+ except ImportError:
20948
+ from workspace_storage import main as storage_main
20949
+ storage_main()
20950
+ return
20907
20951
  asyncio.run(main())
20908
20952
 
20909
20953
 
@@ -0,0 +1,348 @@
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from contextlib import ExitStack, contextmanager
11
+ from pathlib import Path
12
+ from uuid import UUID
13
+
14
+
15
+ def _is_redirect(path: Path) -> bool:
16
+ return path.is_symlink() or getattr(path, "is_junction", lambda: False)()
17
+
18
+
19
+ def _directory_size(path: Path) -> int:
20
+ total = 0
21
+ seen = set()
22
+
23
+ def raise_error(error: OSError) -> None:
24
+ raise error
25
+
26
+ for directory, directories, filenames in os.walk(path, followlinks=False, onerror=raise_error):
27
+ directories[:] = [name for name in directories if not _is_redirect(Path(directory) / name)]
28
+ for filename in filenames:
29
+ file_stat = (Path(directory) / filename).lstat()
30
+ identity = (file_stat.st_dev, file_stat.st_ino)
31
+ if file_stat.st_ino and identity in seen:
32
+ continue
33
+ seen.add(identity)
34
+ total += (
35
+ file_stat.st_blocks * 512 if hasattr(file_stat, "st_blocks") else file_stat.st_size
36
+ )
37
+ return total
38
+
39
+
40
+ def _workspace_kind(name: str) -> str:
41
+ if name == "_main":
42
+ return "repository"
43
+ try:
44
+ return "task" if str(UUID(name)) == name else "other"
45
+ except ValueError:
46
+ return "other"
47
+
48
+
49
+ def scan_workspace_storage(root: Path, *, measure: bool = True) -> dict:
50
+ root = root.expanduser().resolve()
51
+ projects = root / "projects"
52
+ entries = []
53
+ if _is_redirect(projects):
54
+ raise ValueError("The managed projects directory must not be a symbolic link")
55
+ if projects.exists():
56
+ root_key = hashlib.sha256(os.fsencode(root)).hexdigest()[:16]
57
+ for project in sorted(projects.iterdir()):
58
+ if _is_redirect(project) or not project.is_dir():
59
+ continue
60
+ for workspace in sorted(project.iterdir()):
61
+ if (
62
+ workspace.name.startswith(".")
63
+ or _is_redirect(workspace)
64
+ or not workspace.is_dir()
65
+ ):
66
+ continue
67
+ size_bytes = 0
68
+ scan_error = None
69
+ if measure:
70
+ try:
71
+ size_bytes = _directory_size(workspace)
72
+ except OSError:
73
+ scan_error = "unreadable"
74
+ entries.append(
75
+ {
76
+ "id": f"{root_key}/{project.name}/{workspace.name}",
77
+ "project_key": project.name,
78
+ "workspace_id": workspace.name,
79
+ "path": str(workspace),
80
+ "root_path": str(root),
81
+ "kind": _workspace_kind(workspace.name),
82
+ "size_bytes": size_bytes,
83
+ "scan_error": scan_error,
84
+ }
85
+ )
86
+ return {
87
+ "root_path": str(root),
88
+ "total_bytes": sum(entry["size_bytes"] for entry in entries),
89
+ "entries": entries,
90
+ }
91
+
92
+
93
+ @contextmanager
94
+ def _try_lock(path: Path):
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
97
+ with os.fdopen(descriptor, "a+b") as handle:
98
+ if os.name == "nt":
99
+ import msvcrt
100
+
101
+ if path.stat().st_size == 0:
102
+ handle.write(b"\0")
103
+ handle.flush()
104
+ handle.seek(0)
105
+
106
+ def lock() -> None:
107
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
108
+
109
+ def unlock() -> None:
110
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
111
+ else:
112
+ import fcntl
113
+
114
+ def lock() -> None:
115
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
116
+
117
+ def unlock() -> None:
118
+ fcntl.flock(handle, fcntl.LOCK_UN)
119
+
120
+ try:
121
+ lock()
122
+ except OSError as error:
123
+ if error.errno not in (errno.EACCES, errno.EAGAIN):
124
+ raise
125
+ yield False
126
+ return
127
+ try:
128
+ yield True
129
+ finally:
130
+ handle.seek(0)
131
+ unlock()
132
+
133
+
134
+ def _entry_is_contained(entry: dict) -> bool:
135
+ path = Path(entry["path"])
136
+ root = Path(entry["root_path"])
137
+ project = path.parent
138
+ return (
139
+ path == root / "projects" / entry["project_key"] / entry["workspace_id"]
140
+ and root.resolve() == root
141
+ and project.resolve() == project
142
+ and path.resolve() == path
143
+ and path.is_dir()
144
+ and not _is_redirect(path)
145
+ and not _is_redirect(project / ".forgexa-workspace-locks")
146
+ and not _is_redirect(project / ".forgexa-worktree.lock")
147
+ )
148
+
149
+
150
+ @contextmanager
151
+ def _entry_locks(entry: dict):
152
+ project = Path(entry["path"]).parent
153
+ paths = []
154
+ if entry["kind"] == "task":
155
+ paths.append(project / ".forgexa-workspace-locks" / f"{entry['workspace_id']}.lock")
156
+ paths.append(project / ".forgexa-worktree.lock")
157
+ with ExitStack() as stack:
158
+ for path in paths:
159
+ if _is_redirect(path) or not stack.enter_context(_try_lock(path)):
160
+ yield False
161
+ return
162
+ yield True
163
+
164
+
165
+ def _git(path: Path, *arguments: str) -> str:
166
+ environment = {
167
+ **{name: value for name, value in os.environ.items() if not name.startswith("GIT_")},
168
+ "GIT_OPTIONAL_LOCKS": "0",
169
+ "GIT_NO_LAZY_FETCH": "1",
170
+ "GIT_TERMINAL_PROMPT": "0",
171
+ }
172
+ return subprocess.run(
173
+ ["git", "-C", str(path), *arguments],
174
+ check=True,
175
+ capture_output=True,
176
+ text=True,
177
+ timeout=30,
178
+ env=environment,
179
+ ).stdout.strip()
180
+
181
+
182
+ def _linked_worktrees(path: Path) -> list[Path]:
183
+ return [
184
+ Path(field[len("worktree ") :]).resolve()
185
+ for field in _git(path, "worktree", "list", "--porcelain", "-z").split("\0")
186
+ if field.startswith("worktree ") and Path(field[len("worktree ") :]).resolve() != path
187
+ ]
188
+
189
+
190
+ def _safety_reason(entry: dict, *, check_dependents: bool = True) -> str | None:
191
+ if not _entry_is_contained(entry):
192
+ return "outside_root"
193
+ if entry["kind"] == "other":
194
+ return "unmanaged"
195
+ if entry["scan_error"]:
196
+ return entry["scan_error"]
197
+ path = Path(entry["path"])
198
+ common = Path(_git(path, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve()
199
+ if common not in (path / ".git", path.parent / "_main" / ".git"):
200
+ return "outside_root"
201
+ if (path / ".gitmodules").exists():
202
+ return "submodules"
203
+ if _git(path, "status", "--porcelain", "--untracked-files=normal", "--ignore-submodules=none"):
204
+ return "uncommitted"
205
+ if not _git(path, "remote") or _git(
206
+ path, "rev-list", "--max-count=1", "HEAD", "--not", "--remotes"
207
+ ):
208
+ return "unpublished"
209
+ if common == path / ".git":
210
+ if _git(path, "for-each-ref", "--format=%(refname)", "refs/stash"):
211
+ return "stash"
212
+ if _git(path, "rev-list", "--max-count=1", "--branches", "--not", "--remotes"):
213
+ return "unpublished"
214
+ if entry["kind"] == "repository" and check_dependents:
215
+ if _linked_worktrees(path) or any(
216
+ child.is_dir() and not child.name.startswith(".") and child != path
217
+ for child in path.parent.iterdir()
218
+ ):
219
+ return "worktrees_retained"
220
+ return None
221
+
222
+
223
+ def inspect_workspace_storage(roots: list[Path]) -> dict:
224
+ root_paths = sorted({str(root.expanduser().resolve()) for root in roots})
225
+ entries = [
226
+ entry for root in root_paths for entry in scan_workspace_storage(Path(root))["entries"]
227
+ ]
228
+ for entry in entries:
229
+ entry["dependencies"] = []
230
+ try:
231
+ if not _entry_is_contained(entry):
232
+ entry["blocked_reason"] = "outside_root"
233
+ continue
234
+ with _entry_locks(entry) as locked:
235
+ entry["blocked_reason"] = _safety_reason(entry) if locked else "busy"
236
+ except (OSError, ValueError, subprocess.SubprocessError):
237
+ entry["blocked_reason"] = "unverified"
238
+ for entry in entries:
239
+ if entry["kind"] != "repository" or entry["blocked_reason"] != "worktrees_retained":
240
+ continue
241
+ siblings = [
242
+ other
243
+ for other in entries
244
+ if Path(other["path"]).parent == Path(entry["path"]).parent and other != entry
245
+ ]
246
+ try:
247
+ linked = _linked_worktrees(Path(entry["path"]))
248
+ if (
249
+ siblings
250
+ and all(other["blocked_reason"] is None for other in siblings)
251
+ and set(linked).issubset({Path(other["path"]) for other in siblings})
252
+ ):
253
+ entry["blocked_reason"] = None
254
+ entry["dependencies"] = [other["id"] for other in siblings]
255
+ except (OSError, ValueError, subprocess.SubprocessError):
256
+ entry["blocked_reason"] = "unverified"
257
+ return {
258
+ "root_paths": root_paths,
259
+ "total_bytes": sum(entry["size_bytes"] for entry in entries),
260
+ "entries": entries,
261
+ }
262
+
263
+
264
+ def clean_workspace_storage(
265
+ roots: list[Path], entry_ids: list[str], scope: str, statuses: list[dict]
266
+ ) -> dict:
267
+ if scope not in ("completed", "all"):
268
+ raise ValueError("Unknown workspace cleanup scope")
269
+ entries = {
270
+ entry["id"]: entry
271
+ for root in {root.expanduser().resolve() for root in roots}
272
+ for entry in scan_workspace_storage(root, measure=False)["entries"]
273
+ }
274
+ states = {(state["project_key"], state["workspace_id"]): state for state in statuses}
275
+ result = {"removed": [], "skipped": [], "removed_bytes": 0}
276
+ selected = sorted(
277
+ set(entry_ids),
278
+ key=lambda identifier: entries.get(identifier, {}).get("kind") == "repository",
279
+ )
280
+ for identifier in selected:
281
+ entry = entries.get(identifier)
282
+ reason = None
283
+ if entry is None:
284
+ reason = "missing"
285
+ else:
286
+ state = states.get((entry["project_key"], entry["workspace_id"]), {})
287
+ if state.get("active") is True:
288
+ reason = "busy"
289
+ elif scope == "completed" and (
290
+ entry["kind"] != "task" or state.get("status") != "done"
291
+ ):
292
+ reason = "not_completed"
293
+ elif not _entry_is_contained(entry):
294
+ reason = "outside_root"
295
+ else:
296
+ try:
297
+ with _entry_locks(entry) as locked:
298
+ reason = _safety_reason(entry) if locked else "busy"
299
+ if reason is None:
300
+ path = Path(entry["path"])
301
+ size_bytes = _directory_size(path)
302
+ common = Path(
303
+ _git(
304
+ path, "rev-parse", "--path-format=absolute", "--git-common-dir"
305
+ )
306
+ ).resolve()
307
+ if entry["kind"] == "task" and common != path / ".git":
308
+ _git(path.parent / "_main", "worktree", "remove", str(path))
309
+ else:
310
+ shutil.rmtree(path)
311
+ result["removed"].append(identifier)
312
+ result["removed_bytes"] += size_bytes
313
+ except (OSError, ValueError, subprocess.SubprocessError):
314
+ reason = "delete_failed"
315
+ if reason is not None:
316
+ result["skipped"].append({"id": identifier, "reason": reason})
317
+ return result
318
+
319
+
320
+ def main() -> None:
321
+ roots = [Path(root) for root in json.loads(os.environ["FORGEXA_WORKSPACE_STORAGE_ROOTS"])]
322
+ request = json.loads(sys.stdin.read(4 * 1024 * 1024))
323
+ if request.get("action") == "scan":
324
+ result = inspect_workspace_storage(roots)
325
+ elif request.get("action") == "clean":
326
+ identifiers = request.get("entry_ids", [])
327
+ statuses = request.get("statuses", [])
328
+ if (
329
+ not isinstance(identifiers, list)
330
+ or len(identifiers) > 10000
331
+ or not all(isinstance(identifier, str) for identifier in identifiers)
332
+ ):
333
+ raise ValueError("Invalid workspace selection")
334
+ if (
335
+ not isinstance(statuses, list)
336
+ or len(statuses) > 10000
337
+ or not all(
338
+ isinstance(state, dict) and "project_key" in state and "workspace_id" in state
339
+ for state in statuses
340
+ )
341
+ ):
342
+ raise ValueError("Invalid workspace states")
343
+ result = clean_workspace_storage(
344
+ roots, identifiers, request.get("scope", "completed"), statuses
345
+ )
346
+ else:
347
+ raise ValueError("Unknown workspace storage action")
348
+ print(json.dumps(result))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.98.1
3
+ Version: 1.98.3
4
4
  Summary: Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform
5
5
  Author-email: Jason Sun <dev.winds@gmail.com>
6
6
  License-Expression: MIT
@@ -15,6 +15,7 @@ forgexa_cli/observability_evidence.py
15
15
  forgexa_cli/ocr_adapter.py
16
16
  forgexa_cli/py.typed
17
17
  forgexa_cli/runtime_evidence.py
18
+ forgexa_cli/workspace_storage.py
18
19
  forgexa_cli/zcode_protocol.py
19
20
  forgexa_cli.egg-info/PKG-INFO
20
21
  forgexa_cli.egg-info/SOURCES.txt
@@ -31,4 +32,5 @@ tests/test_publish_script.py
31
32
  tests/test_runtime_credentials.py
32
33
  tests/test_session_credentials.py
33
34
  tests/test_silent_install.py
34
- tests/test_upgrade_observability.py
35
+ tests/test_upgrade_observability.py
36
+ tests/test_workspace_storage.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "forgexa-cli"
3
- version = "1.98.1"
3
+ version = "1.98.3"
4
4
  description = "Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform"
5
5
  requires-python = ">=3.9"
6
6
  license = "MIT"
@@ -0,0 +1,289 @@
1
+ from pathlib import Path
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from uuid import uuid4
7
+
8
+ import pytest
9
+
10
+ from forgexa_cli.workspace_storage import (
11
+ _try_lock,
12
+ clean_workspace_storage,
13
+ inspect_workspace_storage,
14
+ scan_workspace_storage,
15
+ )
16
+
17
+
18
+ def test_scan_missing_root_does_not_create_directories(tmp_path: Path):
19
+ root = tmp_path / "missing"
20
+ assert scan_workspace_storage(root) == {
21
+ "root_path": str(root),
22
+ "total_bytes": 0,
23
+ "entries": [],
24
+ }
25
+ assert not root.exists()
26
+
27
+
28
+ def test_scan_identifies_managed_workspaces_and_repository(tmp_path: Path):
29
+ project = tmp_path / "projects" / "SI"
30
+ workspace_id = str(uuid4())
31
+ for name in ("_main", workspace_id, "unknown", ".forgexa-workspace-locks"):
32
+ directory = project / name
33
+ directory.mkdir(parents=True)
34
+ (directory / "data").write_bytes(b"workspace data")
35
+ result = scan_workspace_storage(tmp_path)
36
+ assert {entry["workspace_id"]: entry["kind"] for entry in result["entries"]} == {
37
+ "_main": "repository",
38
+ workspace_id: "task",
39
+ "unknown": "other",
40
+ }
41
+ assert all(entry["scan_error"] is None for entry in result["entries"])
42
+ assert result["total_bytes"] == sum(
43
+ entry["size_bytes"] for entry in result["entries"]
44
+ )
45
+ assert result["total_bytes"] > 0
46
+
47
+
48
+ def test_scan_does_not_follow_external_symlinks(tmp_path: Path):
49
+ root = tmp_path / "managed"
50
+ external = tmp_path / "user-project"
51
+ external.mkdir()
52
+ (external / "source").write_bytes(b"user-owned source")
53
+ project = root / "projects" / "SI"
54
+ workspace = project / str(uuid4())
55
+ workspace.mkdir(parents=True)
56
+ (workspace / "linked-directory").symlink_to(external, target_is_directory=True)
57
+ (project / str(uuid4())).symlink_to(external, target_is_directory=True)
58
+ (root / "projects" / "linked-project").symlink_to(
59
+ external, target_is_directory=True
60
+ )
61
+ result = scan_workspace_storage(root)
62
+ assert len(result["entries"]) == 1
63
+ assert result["entries"][0]["size_bytes"] == 0
64
+ assert (external / "source").read_bytes() == b"user-owned source"
65
+
66
+
67
+ def test_scan_rejects_redirected_projects_root(tmp_path: Path):
68
+ external = tmp_path / "external"
69
+ external.mkdir()
70
+ root = tmp_path / "managed"
71
+ root.mkdir()
72
+ (root / "projects").symlink_to(external, target_is_directory=True)
73
+ with pytest.raises(ValueError, match="symbolic link"):
74
+ scan_workspace_storage(root)
75
+
76
+
77
+ def git(path: Path, *arguments: str) -> str:
78
+ return subprocess.run(
79
+ ["git", "-C", str(path), *arguments], check=True, capture_output=True, text=True
80
+ ).stdout.strip()
81
+
82
+
83
+ @pytest.fixture
84
+ def worktree(tmp_path: Path):
85
+ remote = tmp_path / "remote.git"
86
+ remote.mkdir()
87
+ git(remote, "init", "--bare", "--initial-branch=main")
88
+ root = tmp_path / "managed"
89
+ project = root / "projects" / "SI"
90
+ project.mkdir(parents=True)
91
+ main = project / "_main"
92
+ git(project, "clone", str(remote), str(main))
93
+ git(main, "config", "user.name", "Storage Test")
94
+ git(main, "config", "user.email", "storage@example.test")
95
+ (main / "source").write_text("published\n")
96
+ git(main, "add", ".")
97
+ git(main, "commit", "-m", "Initial source")
98
+ git(main, "push", "-u", "origin", "main")
99
+ workspace_id = str(uuid4())
100
+ workspace = project / workspace_id
101
+ git(main, "worktree", "add", "-b", "task", str(workspace))
102
+ status = {
103
+ "project_key": "SI",
104
+ "workspace_id": workspace_id,
105
+ "status": "done",
106
+ "active": False,
107
+ }
108
+ return root, main, workspace, status
109
+
110
+
111
+ def task_entry(root: Path) -> dict:
112
+ return next(
113
+ entry
114
+ for entry in inspect_workspace_storage([root])["entries"]
115
+ if entry["kind"] == "task"
116
+ )
117
+
118
+
119
+ def test_completed_cleanup_removes_worktree_and_git_registration(worktree):
120
+ root, main, workspace, status = worktree
121
+ entry = task_entry(root)
122
+ assert entry["blocked_reason"] is None
123
+ result = clean_workspace_storage([root], [entry["id"]], "completed", [status])
124
+ assert result["removed"] == [entry["id"]]
125
+ assert result["skipped"] == []
126
+ assert not workspace.exists()
127
+ assert main.is_dir()
128
+ assert str(workspace) not in git(main, "worktree", "list", "--porcelain")
129
+ git(main, "worktree", "add", str(workspace), "task")
130
+ assert (workspace / "source").read_text() == "published\n"
131
+
132
+
133
+ @pytest.mark.parametrize("scope", ["completed", "all"])
134
+ @pytest.mark.parametrize("change", ["untracked", "modified", "unpublished"])
135
+ def test_cleanup_preserves_local_work_even_for_all(worktree, scope: str, change: str):
136
+ root, _, workspace, status = worktree
137
+ entry = task_entry(root)
138
+ if change == "untracked":
139
+ (workspace / "draft").write_text("do not delete")
140
+ else:
141
+ (workspace / "source").write_text("local work")
142
+ if change == "unpublished":
143
+ git(workspace, "commit", "-am", "Local unpublished work")
144
+ result = clean_workspace_storage([root], [entry["id"]], scope, [status])
145
+ assert result["removed"] == []
146
+ assert result["skipped"][0]["reason"] == (
147
+ "unpublished" if change == "unpublished" else "uncommitted"
148
+ )
149
+ assert workspace.is_dir()
150
+
151
+
152
+ @pytest.mark.parametrize("lock_name", ["execution", "project"])
153
+ def test_cleanup_never_waits_for_or_deletes_busy_workspace(worktree, lock_name: str):
154
+ root, main, workspace, status = worktree
155
+ entry = task_entry(root)
156
+ lock_path = (
157
+ main.parent / ".forgexa-worktree.lock"
158
+ if lock_name == "project"
159
+ else main.parent / ".forgexa-workspace-locks" / f"{workspace.name}.lock"
160
+ )
161
+ with _try_lock(lock_path) as acquired:
162
+ assert acquired
163
+ assert task_entry(root)["blocked_reason"] == "busy"
164
+ result = clean_workspace_storage([root], [entry["id"]], "all", [status])
165
+ assert result["skipped"] == [{"id": entry["id"], "reason": "busy"}]
166
+ assert workspace.is_dir()
167
+
168
+
169
+ @pytest.mark.parametrize(
170
+ "state,scope,reason",
171
+ [("implementing", "completed", "not_completed"), ("done", "all", "busy")],
172
+ )
173
+ def test_cleanup_rechecks_server_state(worktree, state: str, scope: str, reason: str):
174
+ root, _, workspace, status = worktree
175
+ entry = task_entry(root)
176
+ status.update(status=state, active=reason == "busy")
177
+ result = clean_workspace_storage([root], [entry["id"]], scope, [status])
178
+ assert result["skipped"] == [{"id": entry["id"], "reason": reason}]
179
+ assert workspace.is_dir()
180
+
181
+
182
+ def test_all_cleanup_removes_repository_only_after_its_worktrees(worktree):
183
+ root, main, workspace, status = worktree
184
+ preview = inspect_workspace_storage([root])
185
+ assert all(entry["blocked_reason"] is None for entry in preview["entries"])
186
+ repository = next(
187
+ entry for entry in preview["entries"] if entry["kind"] == "repository"
188
+ )
189
+ assert len(repository["dependencies"]) == 1
190
+ identifiers = [entry["id"] for entry in preview["entries"]]
191
+ result = clean_workspace_storage([root], identifiers, "all", [status])
192
+ assert len(result["removed"]) == 2
193
+ assert result["skipped"] == []
194
+ assert not main.exists()
195
+ assert not workspace.exists()
196
+
197
+
198
+ def test_repository_is_preserved_when_a_dependent_workspace_is_retained(worktree):
199
+ root, main, workspace, status = worktree
200
+ preview = inspect_workspace_storage([root])
201
+ (workspace / "draft").write_text("keep")
202
+ result = clean_workspace_storage(
203
+ [root], [entry["id"] for entry in preview["entries"]], "all", [status]
204
+ )
205
+ assert result["removed"] == []
206
+ assert {item["reason"] for item in result["skipped"]} == {
207
+ "uncommitted",
208
+ "worktrees_retained",
209
+ }
210
+ assert main.exists()
211
+
212
+
213
+ def test_cleanup_does_not_follow_a_workspace_replaced_by_a_symlink(
214
+ worktree, tmp_path: Path
215
+ ):
216
+ root, _, workspace, status = worktree
217
+ entry = task_entry(root)
218
+ workspace.rename(workspace.with_name("retained"))
219
+ external = tmp_path / "user-source"
220
+ external.mkdir()
221
+ (external / "draft").write_text("keep")
222
+ workspace.symlink_to(external, target_is_directory=True)
223
+ result = clean_workspace_storage([root], [entry["id"]], "all", [status])
224
+ assert result["skipped"] == [{"id": entry["id"], "reason": "missing"}]
225
+ assert (external / "draft").read_text() == "keep"
226
+
227
+
228
+ def test_root_aliases_do_not_duplicate_storage(worktree):
229
+ root, _, _, _ = worktree
230
+ assert len(inspect_workspace_storage([root, root / "."])["entries"]) == 2
231
+
232
+
233
+ def test_inherited_git_environment_cannot_hide_local_changes(worktree, monkeypatch):
234
+ root, main, workspace, status = worktree
235
+ entry = task_entry(root)
236
+ (workspace / "source").write_text("uncommitted user source")
237
+ monkeypatch.setenv("GIT_WORK_TREE", str(main))
238
+ monkeypatch.setenv("GIT_INDEX_FILE", str(main / ".git" / "index"))
239
+ result = clean_workspace_storage([root], [entry["id"]], "all", [status])
240
+ assert result["skipped"] == [{"id": entry["id"], "reason": "uncommitted"}]
241
+ assert (workspace / "source").read_text() == "uncommitted user source"
242
+
243
+
244
+ def test_shared_repository_stash_is_never_deleted(worktree):
245
+ root, main, _, status = worktree
246
+ (main / "source").write_text("stashed source")
247
+ git(main, "stash", "push", "-m", "Retained user work")
248
+ preview = inspect_workspace_storage([root])
249
+ repository = next(
250
+ entry for entry in preview["entries"] if entry["kind"] == "repository"
251
+ )
252
+ assert repository["blocked_reason"] == "stash"
253
+ result = clean_workspace_storage([root], [repository["id"]], "all", [status])
254
+ assert result["skipped"] == [{"id": repository["id"], "reason": "stash"}]
255
+ assert "Retained user work" in git(main, "stash", "list")
256
+
257
+
258
+ @pytest.mark.parametrize(
259
+ "daemon_path",
260
+ [
261
+ "backend/app/daemon.py",
262
+ "cli/forgexa_cli/daemon.py",
263
+ "desktop/src-tauri/resources/daemon.py",
264
+ ],
265
+ )
266
+ def test_standalone_maintenance_command_does_not_start_daemon(
267
+ worktree, tmp_path: Path, daemon_path: str
268
+ ):
269
+ root, _, _, _ = worktree
270
+ daemon = Path(__file__).parents[2] / daemon_path
271
+ environment = {
272
+ **os.environ,
273
+ "HOME": str(tmp_path),
274
+ "PYTHONPATH": "",
275
+ "FORGEXA_WORKSPACE_STORAGE_ROOTS": json.dumps([str(root)]),
276
+ }
277
+ process = subprocess.run(
278
+ [sys.executable, str(daemon), "--workspace-storage"],
279
+ input=json.dumps({"action": "scan"}),
280
+ capture_output=True,
281
+ text=True,
282
+ cwd=tmp_path,
283
+ env=environment,
284
+ timeout=30,
285
+ check=True,
286
+ )
287
+ result = json.loads(process.stdout)
288
+ assert len(result["entries"]) == 2
289
+ assert not (tmp_path / ".forgexa" / "daemon" / "daemon.lock").exists()
File without changes
File without changes