forgexa-cli 1.107.5__tar.gz → 1.108.1__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 (40) hide show
  1. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/PKG-INFO +1 -1
  2. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/agent_core.py +93 -0
  4. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/daemon.py +110 -109
  5. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/PKG-INFO +1 -1
  6. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/pyproject.toml +1 -1
  7. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_auth_and_runtime_commands.py +471 -0
  8. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/README.md +0 -0
  9. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/_build_config.py +0 -0
  10. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/_local_bind.py +0 -0
  11. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/autoupgrade.py +0 -0
  12. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/aws_evidence.py +0 -0
  13. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/aws_logs_evidence.py +0 -0
  14. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/code_review_rules.py +0 -0
  15. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/component_runtime.py +0 -0
  16. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/main.py +0 -0
  17. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/observability_contract.py +0 -0
  18. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/observability_evidence.py +0 -0
  19. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/ocr_adapter.py +0 -0
  20. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/py.typed +0 -0
  21. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/runtime_evidence.py +0 -0
  22. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/workspace_storage.py +0 -0
  23. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli/zcode_protocol.py +0 -0
  24. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/SOURCES.txt +0 -0
  25. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  26. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/entry_points.txt +0 -0
  27. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/requires.txt +0 -0
  28. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/forgexa_cli.egg-info/top_level.txt +0 -0
  29. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/setup.cfg +0 -0
  30. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_autoupgrade.py +0 -0
  31. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_check_command.py +0 -0
  32. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_delivery_review_packaged.py +0 -0
  33. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_expiry_warnings_and_revoke.py +0 -0
  34. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_local_bind_commands.py +0 -0
  35. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_publish_script.py +0 -0
  36. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_runtime_credentials.py +0 -0
  37. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_session_credentials.py +0 -0
  38. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_silent_install.py +0 -0
  39. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_upgrade_observability.py +0 -0
  40. {forgexa_cli-1.107.5 → forgexa_cli-1.108.1}/tests/test_workspace_storage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.107.5
3
+ Version: 1.108.1
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.107.5"
2
+ __version__ = "1.108.1"
@@ -3939,6 +3939,99 @@ def delivery_review_linux_command(
3939
3939
  return [*wrapped, "--chdir", str(workspace), "--", *command]
3940
3940
 
3941
3941
 
3942
+ def delivery_review_sandbox_command(
3943
+ command: list[str], workspace: Path, home: Path, *, writable: bool,
3944
+ network: bool = True, read_paths: list[Path] | None = None,
3945
+ allow_claude_tmp: bool = False, deny_paths: list[Path] | None = None,
3946
+ restrict_global_reads: bool = False,
3947
+ ) -> list[str]:
3948
+ sandbox = delivery_review_sandbox_exec()
3949
+ if not sandbox:
3950
+ raise RuntimeError("delivery_review_sandbox_unavailable")
3951
+ user_home_path = Path.home().resolve()
3952
+ workspace_path = workspace.resolve()
3953
+ home_path = home.resolve()
3954
+ if (workspace_path == user_home_path or workspace_path in user_home_path.parents
3955
+ or home_path == user_home_path or home_path in user_home_path.parents
3956
+ or workspace_path == home_path or workspace_path in home_path.parents or home_path in workspace_path.parents):
3957
+ raise RuntimeError("delivery_review_sandbox_scope_invalid")
3958
+ claude_tmp = Path("/tmp").resolve() / f"claude-{os.getuid()}"
3959
+ allowed = [
3960
+ f"(subpath {json.dumps(str(home_path))})",
3961
+ '(literal "/dev/null")',
3962
+ ]
3963
+ if allow_claude_tmp:
3964
+ if workspace_path == claude_tmp or claude_tmp in workspace_path.parents:
3965
+ raise RuntimeError("delivery_review_sandbox_scope_invalid")
3966
+ allowed.append(f"(subpath {json.dumps(str(claude_tmp))})")
3967
+ if writable:
3968
+ allowed.append(f"(subpath {json.dumps(str(workspace_path))})")
3969
+ profile = "(version 1)(allow default)(deny file-write*)(allow file-write* " + " ".join(allowed) + ")"
3970
+ user_home = str(user_home_path)
3971
+ executable = shutil.which(command[0]) or command[0]
3972
+ executable_path = Path(executable).absolute()
3973
+ read_roots = {str(executable_path.parent), str(executable_path.resolve().parent)}
3974
+ read_roots.update(str(path.resolve()) for path in (read_paths or []))
3975
+ virtualenv = executable_path.parent.parent
3976
+ if (virtualenv / "pyvenv.cfg").is_file():
3977
+ read_roots.add(str(virtualenv))
3978
+ if sys.platform == "linux":
3979
+ node_executable = shutil.which("node")
3980
+ if node_executable:
3981
+ read_roots.add(str(Path(node_executable).resolve().parent))
3982
+ for parent in executable_path.resolve().parents:
3983
+ if parent == user_home_path or parent in user_home_path.parents:
3984
+ break
3985
+ if (parent / "package.json").is_file():
3986
+ read_roots.add(str(parent))
3987
+ break
3988
+ if any(Path(root) == user_home_path or Path(root) in user_home_path.parents for root in read_roots):
3989
+ raise RuntimeError("delivery_review_sandbox_scope_invalid")
3990
+ if sys.platform == "linux":
3991
+ return delivery_review_linux_command(
3992
+ command, cwd=workspace_path, home=home_path, writable=writable, network=network,
3993
+ read_paths=[Path(root) for root in read_roots], deny_paths=deny_paths,
3994
+ )
3995
+ executable_rules = " ".join(f"(subpath {json.dumps(root)})" for root in sorted(read_roots))
3996
+ metadata_paths = {
3997
+ str(parent) for root in [*read_roots, str(workspace.resolve()), str(home.resolve())]
3998
+ for parent in Path(root).parents
3999
+ }
4000
+ metadata_rules = " ".join(f"(literal {json.dumps(path)})" for path in sorted(metadata_paths))
4001
+ if restrict_global_reads:
4002
+ system_read_roots = (
4003
+ "/System/Library", "/usr/lib", "/usr/libexec", "/usr/share/icu", "/usr/share/zoneinfo",
4004
+ "/Library/Apple", "/private/etc/ssl", "/dev",
4005
+ )
4006
+ readable = [
4007
+ *(f"(subpath {json.dumps(root)})" for root in system_read_roots),
4008
+ *(f"(subpath {json.dumps(root)})" for root in sorted(read_roots)),
4009
+ f"(subpath {json.dumps(str(workspace_path))})",
4010
+ f"(subpath {json.dumps(str(home_path))})",
4011
+ *(f"(literal {json.dumps(path)})" for path in sorted(metadata_paths)),
4012
+ ]
4013
+ profile += "(deny file-read-data (require-all " + " ".join(
4014
+ f"(require-not {rule})" for rule in readable
4015
+ ) + "))"
4016
+ profile += (
4017
+ f"(deny file-read* (subpath {json.dumps(user_home)}))"
4018
+ f"(allow file-read-metadata {metadata_rules})"
4019
+ f"(allow file-read-data {metadata_rules})"
4020
+ f"(allow file-read* (subpath {json.dumps(str(workspace.resolve()))}) "
4021
+ f"(subpath {json.dumps(str(home.resolve()))}) {executable_rules})"
4022
+ )
4023
+ profile += "(deny file-read-data " + " ".join(
4024
+ f"(regex #{json.dumps(pattern)})" for pattern in DELIVERY_REVIEW_SENSITIVE_PATTERNS
4025
+ ) + ")"
4026
+ if deny_paths:
4027
+ profile += "(deny file-read* " + " ".join(
4028
+ f"(literal {json.dumps(str(path.resolve()))})" for path in deny_paths
4029
+ ) + ")"
4030
+ if not network:
4031
+ profile += "(deny network*)"
4032
+ return [sandbox, "-p", profile, *command]
4033
+
4034
+
3942
4035
  _OPENCODE_WORKER_DENIED_TOOLS = (
3943
4036
  "task", "subagent", "delegate_task", "call_omo_agent",
3944
4037
  "background_output", "background_cancel",
@@ -1428,7 +1428,7 @@ except (ImportError, ModuleNotFoundError):
1428
1428
  # DAEMON_VERSION is the protocol/logic version of the daemon code.
1429
1429
  # Kept in sync with pyproject.toml version via bump-version.sh.
1430
1430
  # CLIENT_TYPE identifies which packaging/distribution this daemon runs in.
1431
- DAEMON_VERSION = "1.107.5"
1431
+ DAEMON_VERSION = "1.108.1"
1432
1432
 
1433
1433
 
1434
1434
  def _detect_client_type() -> str:
@@ -3685,6 +3685,13 @@ class WorkspaceManager:
3685
3685
  )
3686
3686
  return any(marker in err for marker in retry_markers)
3687
3687
 
3688
+ @staticmethod
3689
+ def _is_unresolved_git_delta_error(exc: Exception | str) -> bool:
3690
+ return bool(re.search(
3691
+ r"\b(?:pack has \d+ unresolved deltas?|unresolved deltas left after unpacking)\b",
3692
+ str(exc), re.IGNORECASE,
3693
+ ))
3694
+
3688
3695
  @staticmethod
3689
3696
  def _is_unreadable_git_object_error(exc: Exception | str) -> bool:
3690
3697
  detail = str(exc).lower()
@@ -4166,6 +4173,8 @@ class WorkspaceManager:
4166
4173
  cwd=ws_path, project_key=project_key,
4167
4174
  )
4168
4175
  except RuntimeError as exc:
4176
+ if self._is_unresolved_git_delta_error(exc):
4177
+ raise
4169
4178
  sync_error = f"fetch branch ref failed: {exc}"
4170
4179
  else:
4171
4180
  try:
@@ -4189,6 +4198,8 @@ class WorkspaceManager:
4189
4198
  )
4190
4199
  sync_success = True
4191
4200
  except RuntimeError as exc:
4201
+ if self._is_unresolved_git_delta_error(exc):
4202
+ raise
4192
4203
  sync_error = f"pull --ff-only failed: {exc}"
4193
4204
 
4194
4205
  if not sync_success:
@@ -5282,7 +5293,9 @@ class WorkspaceManager:
5282
5293
  "fetch", "origin", f"+{branch_name}:{tracking_ref}", cwd=repository,
5283
5294
  timeout=settings.GIT_FETCH_TIMEOUT, project_key=project_key,
5284
5295
  )
5285
- except RuntimeError:
5296
+ except RuntimeError as exc:
5297
+ if self._is_unresolved_git_delta_error(exc):
5298
+ raise
5286
5299
  remaining = (await self._git(
5287
5300
  "ls-remote", "--heads", "origin", branch_ref, cwd=repository,
5288
5301
  timeout=settings.GIT_FETCH_TIMEOUT, project_key=project_key,
@@ -5466,6 +5479,8 @@ class WorkspaceManager:
5466
5479
  project_key=project_key,
5467
5480
  )
5468
5481
  except RuntimeError as exc:
5482
+ if self._is_unresolved_git_delta_error(exc):
5483
+ raise
5469
5484
  if not stale_branch_checkout:
5470
5485
  logger.warning(
5471
5486
  "fetch origin/%s failed for QA workspace %s: %s — reusing current checkout",
@@ -5673,6 +5688,8 @@ class WorkspaceManager:
5673
5688
  await self._git("fetch", "origin", cwd=ws_path,
5674
5689
  timeout=settings.GIT_FETCH_TIMEOUT, project_key=project_key)
5675
5690
  except RuntimeError as _pre_fe:
5691
+ if self._is_unresolved_git_delta_error(_pre_fe):
5692
+ raise
5676
5693
  logger.warning(
5677
5694
  "fetch origin failed for worktree %s: %s "
5678
5695
  "(likely auth/SSH issue — will retry in sync loop)",
@@ -5687,6 +5704,8 @@ class WorkspaceManager:
5687
5704
  cwd=ws_path, timeout=settings.GIT_FETCH_TIMEOUT, project_key=project_key,
5688
5705
  )
5689
5706
  except RuntimeError as _pre_fe2:
5707
+ if self._is_unresolved_git_delta_error(_pre_fe2):
5708
+ raise
5690
5709
  _sync_err_str = str(_pre_fe2)
5691
5710
  _sync_err_lower_pre = _sync_err_str.lower()
5692
5711
  _is_not_found_pre = (
@@ -5865,6 +5884,8 @@ class WorkspaceManager:
5865
5884
  project_key=project_key,
5866
5885
  )
5867
5886
  except RuntimeError as _sf:
5887
+ if self._is_unresolved_git_delta_error(_sf):
5888
+ raise
5868
5889
  logger.warning(
5869
5890
  "Re-fetch %s failed (attempt %d): %s",
5870
5891
  branch_name, _sync_attempt + 1, _sf,
@@ -5898,6 +5919,8 @@ class WorkspaceManager:
5898
5919
  project_key=project_key,
5899
5920
  )
5900
5921
  except RuntimeError as _sf2:
5922
+ if self._is_unresolved_git_delta_error(_sf2):
5923
+ raise
5901
5924
  logger.warning(
5902
5925
  "Re-fetch %s failed (attempt %d): %s",
5903
5926
  branch_name, _sync_attempt + 1, _sf2,
@@ -6033,6 +6056,8 @@ class WorkspaceManager:
6033
6056
  cwd=main_repo, timeout=settings.GIT_FETCH_TIMEOUT, project_key=project_key,
6034
6057
  )
6035
6058
  except RuntimeError as _fetch_err:
6059
+ if self._is_unresolved_git_delta_error(_fetch_err):
6060
+ raise
6036
6061
  err_str = str(_fetch_err)
6037
6062
  # Detect "unrelated histories" / history-rewrite scenarios:
6038
6063
  # If the remote history was rewritten (e.g. BFG large-file removal),
@@ -6075,7 +6100,9 @@ class WorkspaceManager:
6075
6100
  timeout=settings.GIT_FETCH_TIMEOUT,
6076
6101
  project_key=project_key,
6077
6102
  )
6078
- except RuntimeError:
6103
+ except RuntimeError as exc:
6104
+ if self._is_unresolved_git_delta_error(exc):
6105
+ raise
6079
6106
  pass # Branch may not exist on remote yet (first analysis)
6080
6107
 
6081
6108
  # Prune stale worktree references (e.g. directories deleted externally
@@ -6149,6 +6176,8 @@ class WorkspaceManager:
6149
6176
  project_key=project_key,
6150
6177
  )
6151
6178
  except RuntimeError as exc:
6179
+ if self._is_unresolved_git_delta_error(exc):
6180
+ raise
6152
6181
  last_branch_fetch_error = self._summarize_git_error(exc)
6153
6182
 
6154
6183
  # Prepare the same recoverable fresh baseline on runtimes without a
@@ -6430,6 +6459,7 @@ class WorkspaceManager:
6430
6459
  accepts but never sends the git protocol banner) is detected within
6431
6460
  ~90 s rather than waiting forever.
6432
6461
  """
6462
+ requested_timeout = timeout
6433
6463
  if timeout is None:
6434
6464
  # `git worktree add` is a full checkout of the target branch;
6435
6465
  # on large repos (e.g. HP SI) or busy disks it legitimately
@@ -6439,8 +6469,24 @@ class WorkspaceManager:
6439
6469
  if args[:2] == ("worktree", "add")
6440
6470
  else 120
6441
6471
  )
6472
+ git_command = _resolve_git_command()
6473
+ if not git_command:
6474
+ raise RuntimeError(
6475
+ "Git executable not found. Install Git for Windows and ensure "
6476
+ "'C:\\Program Files\\Git\\cmd' is accessible to the Forgexa daemon."
6477
+ )
6442
6478
  env = None
6479
+ key_path: str | None = None
6443
6480
  git_prefix_args: list[str] = []
6481
+
6482
+ def cleanup_ssh_key() -> None:
6483
+ if key_path:
6484
+ for path in (key_path, key_path + ".known_hosts"):
6485
+ try:
6486
+ os.unlink(path)
6487
+ except OSError:
6488
+ pass
6489
+
6444
6490
  # Inject SSH key for commands that touch the remote
6445
6491
  remote_commands = {"clone", "fetch", "pull", "push", "ls-remote"}
6446
6492
  if project_key and args and args[0] in remote_commands:
@@ -6572,12 +6618,6 @@ class WorkspaceManager:
6572
6618
  # reject long paths on platforms where it is already enabled).
6573
6619
  # On Linux/macOS this is a no-op.
6574
6620
  longpath_args = ["-c", "core.longpaths=true"]
6575
- git_command = _resolve_git_command()
6576
- if not git_command:
6577
- raise RuntimeError(
6578
- "Git executable not found. Install Git for Windows and ensure "
6579
- "'C:\\Program Files\\Git\\cmd' is accessible to the Forgexa daemon."
6580
- )
6581
6621
  if env_overrides:
6582
6622
  env = {**(env or os.environ), **env_overrides}
6583
6623
 
@@ -6587,15 +6627,19 @@ class WorkspaceManager:
6587
6627
  # orphaned processes from keeping pipes alive.
6588
6628
  # Windows note: start_new_session creates a new console process group;
6589
6629
  # we use taskkill /T there instead of killpg.
6590
- proc = await _create_subprocess_exec(
6591
- git_command, *longpath_args, *git_prefix_args, *args,
6592
- stdin=asyncio.subprocess.DEVNULL,
6593
- stdout=asyncio.subprocess.PIPE,
6594
- stderr=asyncio.subprocess.PIPE,
6595
- cwd=str(cwd) if cwd else None,
6596
- env=env,
6597
- **_agent_process_group_kwargs(),
6598
- )
6630
+ try:
6631
+ proc = await _create_subprocess_exec(
6632
+ git_command, *longpath_args, *git_prefix_args, *args,
6633
+ stdin=asyncio.subprocess.DEVNULL,
6634
+ stdout=asyncio.subprocess.PIPE,
6635
+ stderr=asyncio.subprocess.PIPE,
6636
+ cwd=str(cwd) if cwd else None,
6637
+ env=env,
6638
+ **_agent_process_group_kwargs(),
6639
+ )
6640
+ except BaseException:
6641
+ cleanup_ssh_key()
6642
+ raise
6599
6643
  communication = asyncio.create_task(proc.communicate())
6600
6644
  try:
6601
6645
  stdout, stderr = await asyncio.wait_for(asyncio.shield(communication), timeout=timeout)
@@ -6619,23 +6663,36 @@ class WorkspaceManager:
6619
6663
  raise RuntimeError(error_message) from None
6620
6664
  finally:
6621
6665
  # Clean up temp SSH key file if created
6622
- if env and "GIT_SSH_COMMAND" in env and project_key and self._ssh_keys.get(project_key) and args[0] in remote_commands:
6623
- import re as _re
6624
- m = _re.search(r'-i\s+"?([^"\s]+)"?', env["GIT_SSH_COMMAND"])
6625
- if m:
6626
- key_file = m.group(1)
6627
- # Resolve forward-slash path back to native for unlink
6628
- try:
6629
- os.unlink(key_file)
6630
- except OSError:
6631
- pass
6632
- # Clean up the known_hosts temp file created alongside the key
6633
- try:
6634
- os.unlink(key_file + ".known_hosts")
6635
- except OSError:
6636
- pass
6666
+ cleanup_ssh_key()
6637
6667
  if proc.returncode != 0:
6638
- raise RuntimeError(f"git {' '.join(args)} failed:\n{stderr.decode()}")
6668
+ error = RuntimeError(f"git {' '.join(args)} failed:\n{stderr.decode(errors='replace')}")
6669
+ if (
6670
+ args and args[0] == "fetch" and "--refetch" not in args
6671
+ and self._is_unresolved_git_delta_error(error)
6672
+ ):
6673
+ logger.warning(
6674
+ "Git fetch at %s has unresolved deltas; retrying with --refetch",
6675
+ cwd,
6676
+ )
6677
+ try:
6678
+ return await self._git(
6679
+ "fetch", "--refetch", "--no-auto-maintenance", *args[1:],
6680
+ cwd=cwd,
6681
+ timeout=(
6682
+ requested_timeout if requested_timeout is not None
6683
+ else settings.GIT_FETCH_TIMEOUT
6684
+ ),
6685
+ project_key=project_key,
6686
+ env_overrides=env_overrides,
6687
+ )
6688
+ except RuntimeError as retry_exc:
6689
+ raise RuntimeError(
6690
+ f"{error}\nGit fetch --refetch retry failed: {retry_exc}\n"
6691
+ "Check git --version (Git 2.36 or newer is required for --refetch) "
6692
+ "and inspect the local repository with git fsck --full. "
6693
+ "Preserve existing worktrees and investigate the remote if the retry still fails."
6694
+ ) from retry_exc
6695
+ raise error
6639
6696
  return stdout.decode()
6640
6697
 
6641
6698
 
@@ -6745,76 +6802,10 @@ def _delivery_review_agent_env(agent_id: str, env: dict[str, str], home: Path) -
6745
6802
  def _delivery_review_sandbox_command(command: list[str], workspace: Path, home: Path, *, writable: bool,
6746
6803
  network: bool = True, read_paths: list[Path] | None = None,
6747
6804
  allow_claude_tmp: bool = False, deny_paths: list[Path] | None = None) -> list[str]:
6748
- sandbox = agent_core.delivery_review_sandbox_exec()
6749
- if not sandbox:
6750
- raise RuntimeError("delivery_review_sandbox_unavailable")
6751
- user_home_path = Path.home().resolve()
6752
- workspace_path = workspace.resolve()
6753
- home_path = home.resolve()
6754
- if (workspace_path == user_home_path or workspace_path in user_home_path.parents
6755
- or home_path == user_home_path or home_path in user_home_path.parents
6756
- or workspace_path == home_path or workspace_path in home_path.parents or home_path in workspace_path.parents):
6757
- raise RuntimeError("delivery_review_sandbox_scope_invalid")
6758
- claude_tmp = Path("/tmp").resolve() / f"claude-{os.getuid()}"
6759
- allowed = [
6760
- f"(subpath {json.dumps(str(home_path))})",
6761
- '(literal "/dev/null")',
6762
- ]
6763
- if allow_claude_tmp:
6764
- if workspace_path == claude_tmp or claude_tmp in workspace_path.parents:
6765
- raise RuntimeError("delivery_review_sandbox_scope_invalid")
6766
- allowed.append(f"(subpath {json.dumps(str(claude_tmp))})")
6767
- if writable:
6768
- allowed.append(f"(subpath {json.dumps(str(workspace_path))})")
6769
- profile = "(version 1)(allow default)(deny file-write*)(allow file-write* " + " ".join(allowed) + ")"
6770
- user_home = str(user_home_path)
6771
- executable = shutil.which(command[0]) or command[0]
6772
- executable_path = Path(executable).absolute()
6773
- read_roots = {str(executable_path.parent), str(executable_path.resolve().parent)}
6774
- read_roots.update(str(path.resolve()) for path in (read_paths or []))
6775
- virtualenv = executable_path.parent.parent
6776
- if (virtualenv / "pyvenv.cfg").is_file():
6777
- read_roots.add(str(virtualenv))
6778
- if sys.platform == "linux":
6779
- node_executable = shutil.which("node")
6780
- if node_executable:
6781
- read_roots.add(str(Path(node_executable).resolve().parent))
6782
- for parent in executable_path.resolve().parents:
6783
- if parent == user_home_path or parent in user_home_path.parents:
6784
- break
6785
- if (parent / "package.json").is_file():
6786
- read_roots.add(str(parent))
6787
- break
6788
- if any(Path(root) == user_home_path or Path(root) in user_home_path.parents for root in read_roots):
6789
- raise RuntimeError("delivery_review_sandbox_scope_invalid")
6790
- if sys.platform == "linux":
6791
- return agent_core.delivery_review_linux_command(
6792
- command, cwd=workspace_path, home=home_path, writable=writable, network=network,
6793
- read_paths=[Path(root) for root in read_roots], deny_paths=deny_paths,
6794
- )
6795
- executable_rules = " ".join(f"(subpath {json.dumps(root)})" for root in sorted(read_roots))
6796
- metadata_paths = {
6797
- str(parent) for root in [*read_roots, str(workspace.resolve()), str(home.resolve())]
6798
- for parent in Path(root).parents
6799
- }
6800
- metadata_rules = " ".join(f"(literal {json.dumps(path)})" for path in sorted(metadata_paths))
6801
- profile += (
6802
- f"(deny file-read* (subpath {json.dumps(user_home)}))"
6803
- f"(allow file-read-metadata {metadata_rules})"
6804
- f"(allow file-read-data {metadata_rules})"
6805
- f"(allow file-read* (subpath {json.dumps(str(workspace.resolve()))}) "
6806
- f"(subpath {json.dumps(str(home.resolve()))}) {executable_rules})"
6805
+ return agent_core.delivery_review_sandbox_command(
6806
+ command, workspace, home, writable=writable, network=network, read_paths=read_paths,
6807
+ allow_claude_tmp=allow_claude_tmp, deny_paths=deny_paths,
6807
6808
  )
6808
- profile += "(deny file-read-data " + " ".join(
6809
- f"(regex #{json.dumps(pattern)})" for pattern in agent_core.DELIVERY_REVIEW_SENSITIVE_PATTERNS
6810
- ) + ")"
6811
- if deny_paths:
6812
- profile += "(deny file-read* " + " ".join(
6813
- f"(literal {json.dumps(str(path.resolve()))})" for path in deny_paths
6814
- ) + ")"
6815
- if not network:
6816
- profile += "(deny network*)"
6817
- return [sandbox, "-p", profile, *command]
6818
6809
 
6819
6810
 
6820
6811
  class ProcessManager:
@@ -15596,8 +15587,13 @@ class RuntimeDaemon:
15596
15587
  review_context_json = json.dumps(review_context, ensure_ascii=False)
15597
15588
  except (TypeError, ValueError):
15598
15589
  return failed("delivery_review_scope_incomplete", "Review context is invalid")
15599
- if len(review_context_json.encode("utf-8")) > _RUNTIME_CRITIC_OUTPUT_MAX_CHARS:
15600
- return failed("delivery_review_scope_incomplete", "Review context exceeds the safe input budget")
15590
+ context_bytes = len(review_context_json.encode("utf-8"))
15591
+ if context_bytes > _DELIVERY_REVIEW_PROMPT_MAX_BYTES:
15592
+ return failed(
15593
+ "delivery_review_scope_incomplete",
15594
+ f"Review context alone exceeds the input budget ({context_bytes} bytes; "
15595
+ f"limit {_DELIVERY_REVIEW_PROMPT_MAX_BYTES} bytes)",
15596
+ )
15601
15597
  prompt_prefix = (
15602
15598
  "Review this requirement's cumulative changes against the supplied requirement. "
15603
15599
  "Read relevant callers when needed. Do not edit files, run commands, commit or push. "
@@ -15654,13 +15650,18 @@ class RuntimeDaemon:
15654
15650
  while True:
15655
15651
  batch_prompts = [assemble_prompt(index, batch_paths, batch_diff, recheck_by_batch[index])
15656
15652
  for index, (batch_paths, batch_diff) in enumerate(batches)]
15657
- oversized = next((index for index, (prompt, _) in enumerate(batch_prompts)
15658
- if snapshot is not None and len(prompt.encode("utf-8")) > _DELIVERY_REVIEW_PROMPT_MAX_BYTES), None)
15653
+ prompt_bytes = [len(prompt.encode("utf-8")) for prompt, _ in batch_prompts]
15654
+ oversized = next((index for index, size in enumerate(prompt_bytes)
15655
+ if size > _DELIVERY_REVIEW_PROMPT_MAX_BYTES), None)
15659
15656
  if oversized is None:
15660
15657
  break
15661
15658
  oversized_paths = batches[oversized][0]
15662
15659
  if len(oversized_paths) < 2 or len(batches) >= 8:
15663
- return failed("delivery_review_scope_incomplete", "A complete review prompt exceeds the input budget")
15660
+ return failed(
15661
+ "delivery_review_scope_incomplete",
15662
+ f"A complete review prompt exceeds the input budget ({prompt_bytes[oversized]} bytes; "
15663
+ f"limit {_DELIVERY_REVIEW_PROMPT_MAX_BYTES} bytes)",
15664
+ )
15664
15665
  file_diffs = []
15665
15666
  try:
15666
15667
  for path in oversized_paths:
@@ -15687,7 +15688,7 @@ class RuntimeDaemon:
15687
15688
  "recheck_issue_ids": [issue["id"] for issue in recheck_by_batch[index]]}
15688
15689
  for index, (batch_paths, _) in enumerate(batches)
15689
15690
  ]
15690
- metadata["prompt_bytes"] = [len(prompt.encode("utf-8")) for prompt, _ in batch_prompts]
15691
+ metadata["prompt_bytes"] = prompt_bytes
15691
15692
 
15692
15693
  summaries, issues, combined_metrics, rechecked = [], [], {}, []
15693
15694
  deadline = time.monotonic() + (task.timeout_seconds or settings.AGENT_TIMEOUT)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.107.5
3
+ Version: 1.108.1
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,6 +1,6 @@
1
1
  [project]
2
2
  name = "forgexa-cli"
3
- version = "1.107.5"
3
+ version = "1.108.1"
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"
@@ -6,6 +6,8 @@ import contextlib
6
6
  import io
7
7
  import json
8
8
  import os
9
+ import shlex
10
+ import subprocess
9
11
  import time
10
12
  from pathlib import Path
11
13
  from types import SimpleNamespace
@@ -416,6 +418,475 @@ def test_httpx_recovery_hints_use_platform_specific_upgrade_commands() -> None:
416
418
  assert linux_hints[0] == "python3 -m pip install --upgrade forgexa-cli"
417
419
 
418
420
 
421
+ @pytest.mark.asyncio
422
+ @pytest.mark.parametrize("error", [
423
+ "fatal: pack has 548 unresolved deltas\nfatal: fetch-pack: invalid index-pack output",
424
+ "fatal: pack has 1 unresolved delta\nfatal: fetch-pack: invalid index-pack output",
425
+ "fatal: unresolved deltas left after unpacking\nfatal: unpack-objects failed",
426
+ ])
427
+ async def test_git_refetches_unresolved_deltas(
428
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error: str,
429
+ ) -> None:
430
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
431
+ manager.set_http_auth("SI", "github", "test-token")
432
+ default_refspec = "+develop:refs/remotes/origin/develop"
433
+ processes = [
434
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(b"", error.encode()))),
435
+ SimpleNamespace(returncode=0, communicate=AsyncMock(return_value=(b"recovered", b""))),
436
+ ]
437
+ spawn = AsyncMock(side_effect=processes)
438
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", spawn)
439
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
440
+
441
+ result = await manager._git(
442
+ "fetch", "origin", default_refspec, cwd=tmp_path,
443
+ timeout=37, project_key="SI", env_overrides={"FORGEXA_TEST": "1"},
444
+ )
445
+
446
+ assert result == "recovered"
447
+ assert spawn.await_count == 2
448
+ first, retry = spawn.await_args_list
449
+ assert first.args[-3:] == ("fetch", "origin", default_refspec)
450
+ assert retry.args[-5:] == (
451
+ "fetch", "--refetch", "--no-auto-maintenance", "origin", default_refspec,
452
+ )
453
+ assert retry.args[1:-5] == first.args[1:-3]
454
+ assert retry.kwargs["cwd"] == first.kwargs["cwd"] == str(tmp_path)
455
+ assert retry.kwargs["env"]["FORGEXA_TEST"] == "1"
456
+ assert retry.kwargs["env"]["GIT_TERMINAL_PROMPT"] == "0"
457
+
458
+
459
+ @pytest.mark.asyncio
460
+ @pytest.mark.parametrize("args,error", [
461
+ (("fetch", "origin", "develop"), "Permission denied (publickey)."),
462
+ (("fetch", "origin", "develop"), "fatal: fetch-pack: invalid index-pack output"),
463
+ (("fetch", "--refetch", "origin", "develop"), "fatal: pack has 1 unresolved delta"),
464
+ (("status",), "fatal: pack has 1 unresolved delta"),
465
+ ])
466
+ async def test_git_does_not_refetch_unrelated_or_already_retried_errors(
467
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, args: tuple[str, ...], error: str,
468
+ ) -> None:
469
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
470
+ process = SimpleNamespace(
471
+ returncode=1, communicate=AsyncMock(return_value=(b"", error.encode())),
472
+ )
473
+ spawn = AsyncMock(return_value=process)
474
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", spawn)
475
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
476
+
477
+ with pytest.raises(RuntimeError, match="failed"):
478
+ await manager._git(*args, cwd=tmp_path)
479
+ assert spawn.await_count == 1
480
+
481
+
482
+ @pytest.mark.asyncio
483
+ async def test_git_refetch_failure_reports_both_errors(
484
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
485
+ ) -> None:
486
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
487
+ processes = [
488
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(
489
+ b"", b"fatal: pack has 548 unresolved deltas",
490
+ ))),
491
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(
492
+ b"", b"Permission denied (publickey).",
493
+ ))),
494
+ ]
495
+ spawn = AsyncMock(side_effect=processes)
496
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", spawn)
497
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
498
+
499
+ with pytest.raises(RuntimeError) as failure:
500
+ await manager._git("fetch", "origin", "develop", cwd=tmp_path)
501
+ assert "548 unresolved deltas" in str(failure.value)
502
+ assert "Permission denied (publickey)." in str(failure.value)
503
+ assert spawn.await_count == 2
504
+
505
+
506
+ @pytest.mark.asyncio
507
+ @pytest.mark.parametrize("requested_timeout,expected_timeout", [(None, 321), (37, 37)])
508
+ async def test_git_refetch_respects_explicit_or_large_repo_timeout(
509
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
510
+ requested_timeout: int | None, expected_timeout: int,
511
+ ) -> None:
512
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
513
+ processes = [
514
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(
515
+ b"", b"fatal: pack has 548 unresolved deltas",
516
+ ))),
517
+ SimpleNamespace(returncode=0, communicate=AsyncMock(return_value=(b"", b""))),
518
+ ]
519
+ monkeypatch.setattr(daemon, "settings", SimpleNamespace(
520
+ GIT_FETCH_TIMEOUT=321, GIT_WORKTREE_TIMEOUT=600, GIT_CLONE_FILTER="",
521
+ ))
522
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", AsyncMock(side_effect=processes))
523
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
524
+ manager._git = AsyncMock(wraps=manager._git)
525
+
526
+ await manager._git("fetch", "origin", "develop", cwd=tmp_path, timeout=requested_timeout)
527
+
528
+ assert manager._git.await_args_list[1].kwargs["timeout"] == expected_timeout
529
+
530
+
531
+ @pytest.mark.asyncio
532
+ async def test_git_refetch_reuses_project_ssh_credentials_and_cleans_keys(
533
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
534
+ ) -> None:
535
+ monkeypatch.setenv("HOME", str(tmp_path / "home with spaces"))
536
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "home with spaces"))
537
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
538
+ manager.set_ssh_key("SI", "test-private-key")
539
+ key_paths = []
540
+
541
+ async def spawn(*args, **kwargs):
542
+ key_path = Path(shlex.split(kwargs["env"]["GIT_SSH_COMMAND"])[2])
543
+ assert key_path.read_text() == "test-private-key\n"
544
+ key_paths.append(key_path)
545
+ if len(key_paths) == 1:
546
+ return SimpleNamespace(
547
+ returncode=1,
548
+ communicate=AsyncMock(return_value=(b"", b"fatal: pack has 548 unresolved deltas")),
549
+ )
550
+ return SimpleNamespace(returncode=0, communicate=AsyncMock(return_value=(b"", b"")))
551
+
552
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", spawn)
553
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
554
+ await manager._git("fetch", "origin", "develop", cwd=tmp_path, project_key="SI")
555
+
556
+ assert len(key_paths) == 2
557
+ assert all(not path.exists() for path in key_paths)
558
+ assert all(not Path(f"{path}.known_hosts").exists() for path in key_paths)
559
+
560
+
561
+ @pytest.mark.asyncio
562
+ async def test_git_spawn_failure_cleans_temporary_ssh_key(
563
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
564
+ ) -> None:
565
+ monkeypatch.setenv("HOME", str(tmp_path / "home with spaces"))
566
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "home with spaces"))
567
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
568
+ manager.set_ssh_key("SI", "test-private-key")
569
+ key_paths = []
570
+
571
+ async def spawn(*args, **kwargs):
572
+ key_path = Path(shlex.split(kwargs["env"]["GIT_SSH_COMMAND"])[2])
573
+ assert key_path.exists()
574
+ key_paths.append(key_path)
575
+ raise OSError("Unable to start git")
576
+
577
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", spawn)
578
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
579
+ with pytest.raises(OSError, match="Unable to start git"):
580
+ await manager._git("fetch", "origin", "develop", cwd=tmp_path, project_key="SI")
581
+
582
+ assert len(key_paths) == 1
583
+ assert not key_paths[0].exists()
584
+ assert not Path(f"{key_paths[0]}.known_hosts").exists()
585
+
586
+
587
+ @pytest.mark.asyncio
588
+ async def test_git_refetch_failure_explains_version_and_diagnosis(
589
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
590
+ ) -> None:
591
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
592
+ processes = [
593
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(
594
+ b"", b"fatal: pack has 548 unresolved deltas",
595
+ ))),
596
+ SimpleNamespace(returncode=1, communicate=AsyncMock(return_value=(
597
+ b"", b"error: unknown option `refetch'",
598
+ ))),
599
+ ]
600
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", AsyncMock(side_effect=processes))
601
+ monkeypatch.setattr(daemon, "_resolve_git_command", lambda: "git")
602
+
603
+ with pytest.raises(RuntimeError) as failure:
604
+ await manager._git("fetch", "origin", "develop", cwd=tmp_path)
605
+
606
+ assert "Git 2.36" in str(failure.value)
607
+ assert "git fsck --full" in str(failure.value)
608
+ assert "548 unresolved deltas" in str(failure.value)
609
+
610
+
611
+ @pytest.mark.asyncio
612
+ @pytest.mark.parametrize("existing_workspace", [False, True])
613
+ async def test_workspace_stops_when_delta_refetch_fails(
614
+ tmp_path: Path, existing_workspace: bool,
615
+ ) -> None:
616
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
617
+ project_dir = tmp_path / "project"
618
+ main_repo = project_dir / "_main"
619
+ main_repo.mkdir(parents=True)
620
+ if existing_workspace:
621
+ (project_dir / "workflow").mkdir()
622
+ manager._is_healthy_worktree = AsyncMock(return_value=True)
623
+ manager._safe_rmtree_main = AsyncMock()
624
+ manager._remove_broken_worktree = AsyncMock()
625
+
626
+ async def fake_git(*args, **kwargs):
627
+ if args[:2] == ("fetch", "origin"):
628
+ raise RuntimeError("fatal: pack has 548 unresolved deltas; refetch failed")
629
+ return ""
630
+
631
+ manager._git = AsyncMock(side_effect=fake_git)
632
+ with pytest.raises(RuntimeError, match="548 unresolved deltas"):
633
+ await manager._create_worktree_impl(
634
+ project_dir, "ssh://git@example.com/repo.git", "develop", "workflow",
635
+ "feature/SI-647", fresh_start=True, project_key="SI",
636
+ )
637
+
638
+ manager._safe_rmtree_main.assert_not_awaited()
639
+ manager._remove_broken_worktree.assert_not_awaited()
640
+ assert not any(call.args[0] in {"reset", "checkout", "update-ref"}
641
+ for call in manager._git.await_args_list)
642
+
643
+
644
+ @pytest.mark.asyncio
645
+ @pytest.mark.parametrize("stale_branch_checkout", [False, True])
646
+ async def test_delta_refetch_failure_stops_qa_workspace_refresh(
647
+ tmp_path: Path, stale_branch_checkout: bool,
648
+ ) -> None:
649
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
650
+ workspace = tmp_path / "qa"
651
+ workspace.mkdir()
652
+ (workspace / "draft.txt").write_text("uncommitted work\n")
653
+ manager._remove_broken_worktree = AsyncMock()
654
+
655
+ async def fake_git(*args, **kwargs):
656
+ if args[0] == "symbolic-ref" and not stale_branch_checkout:
657
+ raise RuntimeError("detached HEAD")
658
+ if args[0] == "fetch":
659
+ raise RuntimeError("fatal: pack has 548 unresolved deltas; refetch failed")
660
+ return ""
661
+
662
+ manager._git = AsyncMock(side_effect=fake_git)
663
+ with pytest.raises(RuntimeError, match="548 unresolved deltas"):
664
+ await manager._refresh_or_invalidate_detached_worktree(
665
+ tmp_path / "_main", workspace, "develop", project_key="SI",
666
+ )
667
+
668
+ manager._remove_broken_worktree.assert_not_awaited()
669
+ assert (workspace / "draft.txt").read_text() == "uncommitted work\n"
670
+ assert not any(call.args[0] == "checkout" for call in manager._git.await_args_list)
671
+
672
+
673
+ @pytest.mark.asyncio
674
+ @pytest.mark.parametrize("failed_operation", ["checkout", "reset"])
675
+ async def test_delta_refetch_failure_stops_existing_workspace_sync(
676
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failed_operation: str,
677
+ ) -> None:
678
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
679
+ project_dir = tmp_path / "project"
680
+ workspace = project_dir / "workflow"
681
+ workspace.mkdir(parents=True)
682
+ (workspace / "draft.txt").write_text("uncommitted work\n")
683
+ manager._is_healthy_worktree = AsyncMock(return_value=True)
684
+ manager._remove_broken_worktree = AsyncMock()
685
+ manager._safe_rmtree_main = AsyncMock()
686
+ monkeypatch.setattr(daemon.asyncio, "sleep", AsyncMock())
687
+ fetch_count = 0
688
+
689
+ async def fake_git(*args, **kwargs):
690
+ nonlocal fetch_count
691
+ if args[0] == "fetch":
692
+ fetch_count += 1
693
+ if fetch_count == 3:
694
+ raise RuntimeError("fatal: pack has 548 unresolved deltas; refetch failed")
695
+ return ""
696
+
697
+ async def fake_index_op(*args, **kwargs):
698
+ if failed_operation == "checkout" or args[0] == "reset":
699
+ raise RuntimeError(f"{failed_operation} failed")
700
+ return ""
701
+
702
+ manager._git = AsyncMock(side_effect=fake_git)
703
+ manager._git_index_op = AsyncMock(side_effect=fake_index_op)
704
+ with pytest.raises(RuntimeError, match="548 unresolved deltas"):
705
+ await manager._create_worktree_impl(
706
+ project_dir, "ssh://git@example.com/repo.git", "develop", "workflow",
707
+ "feature/SI-647", project_key="SI", expect_branch=True,
708
+ )
709
+
710
+ assert fetch_count == 3
711
+ manager._remove_broken_worktree.assert_not_awaited()
712
+ manager._safe_rmtree_main.assert_not_awaited()
713
+ assert (workspace / "draft.txt").read_text() == "uncommitted work\n"
714
+
715
+
716
+ @pytest.mark.asyncio
717
+ async def test_delta_refetch_failure_stops_new_workspace_branch_retry(
718
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
719
+ ) -> None:
720
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
721
+ project_dir = tmp_path / "project"
722
+ (project_dir / "_main").mkdir(parents=True)
723
+ fetch_count = 0
724
+
725
+ async def fake_git(*args, **kwargs):
726
+ nonlocal fetch_count
727
+ if args[0] == "fetch":
728
+ fetch_count += 1
729
+ if fetch_count == 3:
730
+ raise RuntimeError("fatal: pack has 548 unresolved deltas; refetch failed")
731
+ return ""
732
+
733
+ manager._git = AsyncMock(side_effect=fake_git)
734
+ monkeypatch.setattr(daemon.asyncio, "sleep", AsyncMock())
735
+ monkeypatch.setattr(daemon, "_create_subprocess_exec", AsyncMock(return_value=SimpleNamespace(
736
+ returncode=1, communicate=AsyncMock(return_value=(b"", b"")),
737
+ )))
738
+ with pytest.raises(RuntimeError, match="548 unresolved deltas"):
739
+ await manager._create_worktree_impl(
740
+ project_dir, "ssh://git@example.com/repo.git", "develop", "workflow",
741
+ "feature/SI-647", project_key="SI",
742
+ )
743
+
744
+ assert fetch_count == 3
745
+ assert not any(call.args[:2] == ("worktree", "add") for call in manager._git.await_args_list)
746
+
747
+
748
+ @pytest.mark.asyncio
749
+ @pytest.mark.parametrize("failed_operation", ["fetch", "pull"])
750
+ @pytest.mark.parametrize("expect_branch", [False, True])
751
+ async def test_delta_refetch_failure_stops_final_workspace_sync(
752
+ tmp_path: Path, failed_operation: str, expect_branch: bool,
753
+ ) -> None:
754
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
755
+ workspace = tmp_path / "workspace"
756
+ workspace.mkdir()
757
+ (workspace / "draft.txt").write_text("uncommitted work\n")
758
+ manager._create_worktree = AsyncMock(return_value=workspace)
759
+ manager._remove_broken_worktree = AsyncMock()
760
+
761
+ async def fake_git(*args, **kwargs):
762
+ if args[0] == "fetch" and failed_operation == "fetch":
763
+ raise RuntimeError("fatal: pack has 548 unresolved deltas; refetch failed")
764
+ return ""
765
+
766
+ async def fake_index_op(*args, **kwargs):
767
+ if args[0] == "pull" and failed_operation == "pull":
768
+ raise RuntimeError("fatal: pack has 548 unresolved deltas")
769
+ return ""
770
+
771
+ manager._git = AsyncMock(side_effect=fake_git)
772
+ manager._git_index_op = AsyncMock(side_effect=fake_index_op)
773
+ task = daemon.TaskInfo(
774
+ task_id="task", graph_id="workflow", node_type="coding" if expect_branch else "analysis",
775
+ agent_type="copilot", input_prompt="", input_data={"analysis_mode": "refine"},
776
+ timeout_seconds=30, max_retries=0, retry_count=0, project={}, work_item={},
777
+ requirement_key="SI-647",
778
+ )
779
+ with pytest.raises(RuntimeError, match="548 unresolved deltas"):
780
+ await manager.prepare_workspace(
781
+ {
782
+ "project_key": "SI", "repo_url": "ssh://git@example.com/repo.git",
783
+ "default_branch": "develop",
784
+ },
785
+ task,
786
+ )
787
+
788
+ manager._remove_broken_worktree.assert_not_awaited()
789
+ assert not any(call.args[0] == "reset" for call in manager._git_index_op.await_args_list)
790
+ assert (workspace / "draft.txt").read_text() == "uncommitted work\n"
791
+
792
+
793
+ @pytest.mark.asyncio
794
+ @pytest.mark.parametrize("object_damage", ["missing", "corrupt"])
795
+ @pytest.mark.parametrize("unpack_limit", ["1", "100"])
796
+ async def test_workspace_repairs_missing_delta_base_and_preserves_worktrees(
797
+ tmp_path: Path, caplog: pytest.LogCaptureFixture,
798
+ monkeypatch: pytest.MonkeyPatch, object_damage: str, unpack_limit: str,
799
+ ) -> None:
800
+ monkeypatch.setenv("HOME", str(tmp_path))
801
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
802
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
803
+
804
+ def git(cwd: Path, *args: str) -> str:
805
+ return subprocess.run(
806
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True,
807
+ ).stdout.strip()
808
+
809
+ remote = tmp_path / "remote.git"
810
+ remote.mkdir()
811
+ git(remote, "init", "--bare")
812
+ seed = tmp_path / "seed"
813
+ seed.mkdir()
814
+ git(seed, "init", "-b", "develop")
815
+ git(seed, "config", "user.name", "Test")
816
+ git(seed, "config", "user.email", "test@example.test")
817
+ original = "".join(
818
+ f"{index:05d} {index * 2654435761 % 2**32:08x}\n" for index in range(20000)
819
+ )
820
+ (seed / "data.txt").write_text(original)
821
+ git(seed, "add", "data.txt")
822
+ git(seed, "commit", "-m", "initial")
823
+ git(seed, "remote", "add", "origin", remote.as_uri())
824
+ git(seed, "push", "origin", "develop")
825
+
826
+ manager = daemon.WorkspaceManager(str(tmp_path / "daemon-root"))
827
+ project_dir = manager.projects_root / "SI"
828
+ main_repo = project_dir / "_main"
829
+ main_repo.mkdir(parents=True)
830
+ git(main_repo, "init", "-b", "develop")
831
+ git(main_repo, "config", "user.name", "Test")
832
+ git(main_repo, "config", "user.email", "test@example.test")
833
+ git(main_repo, "remote", "add", "origin", remote.as_uri())
834
+ git(main_repo, "fetch", "--depth", "1", "origin", "+develop:refs/remotes/origin/develop")
835
+ git(main_repo, "reset", "--hard", "origin/develop")
836
+
837
+ protected = project_dir / "existing-worktree"
838
+ git(main_repo, "worktree", "add", "-b", "feature/existing", str(protected))
839
+ (protected / "local.txt").write_text("unpublished commit\n")
840
+ git(protected, "add", "local.txt")
841
+ git(protected, "commit", "-m", "local work")
842
+ local_commit = git(protected, "rev-parse", "HEAD")
843
+ (protected / "local.txt").write_text("staged work\n")
844
+ git(protected, "add", "local.txt")
845
+ (protected / "local.txt").write_text("staged work\nunstaged work\n")
846
+ (protected / "draft.txt").write_text("uncommitted work\n")
847
+
848
+ base_blob = git(main_repo, "rev-parse", "develop:data.txt")
849
+ loose_blob = main_repo / ".git" / "objects" / base_blob[:2] / base_blob[2:]
850
+ assert loose_blob.exists()
851
+ if object_damage == "missing":
852
+ loose_blob.unlink()
853
+ else:
854
+ loose_blob.chmod(0o600)
855
+ loose_blob.write_bytes(b"corrupt git object")
856
+ updated = original.replace("10000 ", "changed 10000 ", 1)
857
+ (seed / "data.txt").write_text(updated)
858
+ git(seed, "commit", "-am", "update")
859
+ git(seed, "push", "origin", "develop")
860
+ git(main_repo, "config", "fetch.unpackLimit", unpack_limit)
861
+
862
+ task = daemon.TaskInfo(
863
+ task_id="task", graph_id="new-workflow", node_type="analysis", agent_type="copilot",
864
+ input_prompt="", input_data={"analysis_mode": "fresh"}, timeout_seconds=30,
865
+ max_retries=0, retry_count=0, project={}, work_item={}, requirement_key="NEW",
866
+ )
867
+ project = {"project_key": "SI", "repo_url": remote.as_uri(), "default_branch": "develop"}
868
+ if object_damage == "corrupt":
869
+ with pytest.raises(RuntimeError, match="loose object .* is corrupt"):
870
+ await manager.prepare_workspace(project, task)
871
+ assert loose_blob.read_bytes() == b"corrupt git object"
872
+ assert git(protected, "rev-parse", "HEAD") == local_commit
873
+ assert git(protected, "show", ":local.txt") == "staged work"
874
+ assert (protected / "local.txt").read_text() == "staged work\nunstaged work\n"
875
+ assert (protected / "draft.txt").read_text() == "uncommitted work\n"
876
+ return
877
+
878
+ prepared = await manager.prepare_workspace(project, task)
879
+
880
+ assert "unresolved deltas" in caplog.text
881
+ assert (prepared / "data.txt").read_text() == updated
882
+ assert git(protected, "rev-parse", "HEAD") == local_commit
883
+ assert git(protected, "show", ":local.txt") == "staged work"
884
+ assert (protected / "local.txt").read_text() == "staged work\nunstaged work\n"
885
+ assert (protected / "draft.txt").read_text() == "uncommitted work\n"
886
+ assert git(main_repo, "cat-file", "-t", base_blob) == "blob"
887
+ git(main_repo, "fsck", "--full")
888
+
889
+
419
890
  @pytest.mark.asyncio
420
891
  async def test_workspace_reports_last_expected_branch_fetch_error(
421
892
  tmp_path: Path,
File without changes
File without changes