forgexa-cli 1.108.0__tar.gz → 1.108.2__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.108.0 → forgexa_cli-1.108.2}/PKG-INFO +1 -1
  2. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/agent_core.py +81 -7
  4. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/daemon.py +91 -34
  5. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/PKG-INFO +1 -1
  6. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/pyproject.toml +1 -1
  7. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_auth_and_runtime_commands.py +471 -0
  8. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/README.md +0 -0
  9. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/_build_config.py +0 -0
  10. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/_local_bind.py +0 -0
  11. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/autoupgrade.py +0 -0
  12. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/aws_evidence.py +0 -0
  13. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/aws_logs_evidence.py +0 -0
  14. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/code_review_rules.py +0 -0
  15. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/component_runtime.py +0 -0
  16. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/main.py +0 -0
  17. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/observability_contract.py +0 -0
  18. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/observability_evidence.py +0 -0
  19. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/ocr_adapter.py +0 -0
  20. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/py.typed +0 -0
  21. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/runtime_evidence.py +0 -0
  22. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/workspace_storage.py +0 -0
  23. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli/zcode_protocol.py +0 -0
  24. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/SOURCES.txt +0 -0
  25. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  26. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/entry_points.txt +0 -0
  27. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/requires.txt +0 -0
  28. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/forgexa_cli.egg-info/top_level.txt +0 -0
  29. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/setup.cfg +0 -0
  30. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_autoupgrade.py +0 -0
  31. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_check_command.py +0 -0
  32. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_delivery_review_packaged.py +0 -0
  33. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_expiry_warnings_and_revoke.py +0 -0
  34. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_local_bind_commands.py +0 -0
  35. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_publish_script.py +0 -0
  36. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_runtime_credentials.py +0 -0
  37. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_session_credentials.py +0 -0
  38. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_silent_install.py +0 -0
  39. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/tests/test_upgrade_observability.py +0 -0
  40. {forgexa_cli-1.108.0 → forgexa_cli-1.108.2}/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.108.0
3
+ Version: 1.108.2
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.108.0"
2
+ __version__ = "1.108.2"
@@ -5208,6 +5208,7 @@ def deepseek_harness_profile_lock_path(workspace_path: str | Path) -> Path:
5208
5208
 
5209
5209
  def deepseek_harness_overlay(
5210
5210
  *, cwd: Path, credentials_path: Path, provider: str, model: str, read_only: bool = False,
5211
+ project_review: bool = False,
5211
5212
  ) -> list[dict]:
5212
5213
  if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}", model):
5213
5214
  raise ValueError("Invalid DeepSeek Harness model ID")
@@ -5251,6 +5252,18 @@ def deepseek_harness_overlay(
5251
5252
  "reasoningEffort": "high", "maxTokens": 32768,
5252
5253
  }},
5253
5254
  ])
5255
+ if project_review:
5256
+ review_disabled = {
5257
+ "plan-mode", "skill-filesystem", "tool-bash", "tool-fs", "tool-fs-search",
5258
+ "tool-goal", "tool-jobs", "tool-plugin-manager", "tool-pwsh", "tool-ralph",
5259
+ "tool-skill", "tool-subagent", "tool-subagent-control", "tool-subagent-fork",
5260
+ "tool-subagent-list-agents", "tool-todo", "tool-web", "tool-workflow",
5261
+ }
5262
+ for row in rows:
5263
+ if row["id"] in review_disabled:
5264
+ row["disabled"] = True
5265
+ existing = {row["id"] for row in rows}
5266
+ rows.extend({"id": name, "disabled": True} for name in sorted(review_disabled - existing))
5254
5267
  return rows
5255
5268
 
5256
5269
 
@@ -5323,16 +5336,41 @@ def deepseek_harness_sandbox_command(
5323
5336
 
5324
5337
  @contextmanager
5325
5338
  def deepseek_harness_runtime(
5326
- binary: str, workspace_path: str | Path, *, model: str | None = None,
5327
- session_id: str | None = None, read_only: bool = False, delivery_review: bool = False,
5339
+ binary: str,
5340
+ workspace_path: str | Path,
5341
+ *,
5342
+ model: str | None = None,
5343
+ session_id: str | None = None,
5344
+ read_only: bool = False,
5345
+ delivery_review: bool = False,
5346
+ review_home: Path | None = None,
5347
+ review_source: Path | None = None,
5348
+ review_read_paths: list[Path] | None = None,
5328
5349
  ):
5329
5350
  binary = os.path.abspath(shutil.which(binary) or os.path.expanduser(binary))
5330
5351
  cwd = Path(workspace_path).expanduser().resolve()
5331
- home = deepseek_harness_home(cwd)
5352
+ if review_home is not None and (
5353
+ sys.platform != "darwin"
5354
+ or not read_only
5355
+ or not delivery_review
5356
+ or session_id
5357
+ or review_source is None
5358
+ ):
5359
+ raise RuntimeError(
5360
+ "DeepSeek project review requires an isolated, non-resumable macOS session"
5361
+ )
5362
+ home = (
5363
+ review_home.resolve() if review_home is not None else deepseek_harness_home(cwd)
5364
+ )
5332
5365
  home.mkdir(parents=True, exist_ok=True, mode=0o700)
5333
5366
  if sys.platform != "win32":
5334
5367
  home.chmod(0o700)
5335
- lock = acquire_file_lock(deepseek_harness_profile_lock_path(cwd))
5368
+ lock_path = (
5369
+ home / "profile.lock"
5370
+ if review_home is not None
5371
+ else deepseek_harness_profile_lock_path(cwd)
5372
+ )
5373
+ lock = acquire_file_lock(lock_path)
5336
5374
  if lock is None:
5337
5375
  raise RuntimeError("DeepSeek Harness profile is busy with another local turn")
5338
5376
  try:
@@ -5363,11 +5401,13 @@ def deepseek_harness_runtime(
5363
5401
  source_home = Path(os.environ.get("DSH_HOME", str(Path.home() / ".dsh"))).expanduser().resolve()
5364
5402
  credentials = Path(os.environ.get("FACTORY_DEEPSEEK_HARNESS_CREDENTIALS", str(source_home / ".credentials.yaml"))).expanduser().resolve()
5365
5403
  configuration = deepseek_harness_configuration(binary, credentials, env)
5404
+ if review_home is not None:
5405
+ env.update(HOME=str(home), USERPROFILE=str(home), OPENSSL_CONF=os.devnull)
5366
5406
  selected_model = model or os.environ.get("FACTORY_DEEPSEEK_HARNESS_MODEL", "").strip() or "deepseek-flash"
5367
5407
  overlay = temporary_root / "run.patch.json"
5368
5408
  composition = deepseek_harness_overlay(
5369
5409
  cwd=cwd, credentials_path=credentials, provider=configuration["provider"],
5370
- model=selected_model, read_only=read_only,
5410
+ model=selected_model, read_only=read_only, project_review=review_home is not None,
5371
5411
  )
5372
5412
  identity = hashlib.sha256(json.dumps({"build": deepseek_harness_build_info(binary)["fingerprint"], "overlay": composition}, sort_keys=True).encode()).hexdigest()
5373
5413
  env["FORGEXA_DEEPSEEK_HARNESS_COMPOSITION"] = identity
@@ -5377,6 +5417,36 @@ def deepseek_harness_runtime(
5377
5417
  raise RuntimeError("Native Harness session configuration changed or is not owned by Forgexa; start a new session")
5378
5418
  overlay.write_text(json.dumps(composition), encoding="utf-8")
5379
5419
  command = build_deepseek_harness_command(binary, overlay_path=overlay, session_id=session_id)
5420
+ if review_home is not None:
5421
+ paths = list(review_read_paths or [])
5422
+ if credentials.is_file():
5423
+ paths.append(credentials)
5424
+ source = review_source.resolve()
5425
+ executable = Path(binary)
5426
+ paths_to_check = [
5427
+ *paths,
5428
+ executable.parent.resolve(),
5429
+ executable.resolve().parent,
5430
+ ]
5431
+ if any(
5432
+ path == source or path in source.parents or source in path.parents
5433
+ for path in paths_to_check
5434
+ ):
5435
+ raise RuntimeError(
5436
+ "DeepSeek review runtime overlaps the original repository"
5437
+ )
5438
+ yield (
5439
+ delivery_review_sandbox_command(
5440
+ command,
5441
+ cwd,
5442
+ home,
5443
+ writable=False,
5444
+ read_paths=paths,
5445
+ restrict_global_reads=True,
5446
+ ),
5447
+ env,
5448
+ )
5449
+ return
5380
5450
  read_paths = []
5381
5451
  if delivery_review:
5382
5452
  executable = Path(binary)
@@ -5408,6 +5478,8 @@ async def run_deepseek_harness(
5408
5478
  cancel_requested: Any = None,
5409
5479
  component_lease: Any = None,
5410
5480
  read_only: bool = False, delivery_review: bool = False,
5481
+ review_home: Path | None = None, review_source: Path | None = None,
5482
+ review_read_paths: list[Path] | None = None,
5411
5483
  ) -> dict:
5412
5484
  """Execute and validate a supervised one-shot process with bounded output."""
5413
5485
  process = None
@@ -5421,7 +5493,8 @@ async def run_deepseek_harness(
5421
5493
  stderr_text = ""
5422
5494
  runtime = deepseek_harness_runtime(
5423
5495
  binary, workspace_path, model=model, session_id=session_id,
5424
- read_only=read_only, delivery_review=delivery_review,
5496
+ read_only=read_only, delivery_review=delivery_review, review_home=review_home,
5497
+ review_source=review_source, review_read_paths=review_read_paths,
5425
5498
  )
5426
5499
  entered = False
5427
5500
  try:
@@ -5490,7 +5563,8 @@ async def run_deepseek_harness(
5490
5563
  if state.error:
5491
5564
  _kill_proc(process)
5492
5565
  break
5493
- if event is not None and event.get("type") == "session" and env.get("FORGEXA_DEEPSEEK_HARNESS_COMPOSITION"):
5566
+ if (review_home is None and event is not None and event.get("type") == "session"
5567
+ and env.get("FORGEXA_DEEPSEEK_HARNESS_COMPOSITION")):
5494
5568
  binding = deepseek_harness_home(workspace_path) / "forgexa-session-bindings" / (hashlib.sha256(state.session_id.encode()).hexdigest() + ".json")
5495
5569
  with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=binding.parent, delete=False) as temporary:
5496
5570
  json.dump({"composition": env["FORGEXA_DEEPSEEK_HARNESS_COMPOSITION"]}, temporary)
@@ -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.108.0"
1431
+ DAEMON_VERSION = "1.108.2"
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
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.108.0
3
+ Version: 1.108.2
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.108.0"
3
+ version = "1.108.2"
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