alpiecode 10.7.4__tar.gz → 10.7.5__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 (63) hide show
  1. {alpiecode-10.7.4 → alpiecode-10.7.5}/PKG-INFO +1 -1
  2. {alpiecode-10.7.4 → alpiecode-10.7.5}/pyproject.toml +1 -1
  3. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/PKG-INFO +1 -1
  4. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/SOURCES.txt +5 -0
  5. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/agent.py +34 -61
  7. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/cache.py +7 -4
  8. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/config.py +45 -29
  9. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/context.py +19 -9
  10. alpiecode-10.7.5/src/codeagent/diff_preview.py +77 -0
  11. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/orchestrator.py +79 -38
  12. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/prompt.py +42 -35
  13. alpiecode-10.7.5/src/codeagent/slash.py +208 -0
  14. alpiecode-10.7.5/src/codeagent/subagent.py +269 -0
  15. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/system1.py +33 -21
  16. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/tools.py +39 -0
  17. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/verifier.py +44 -0
  18. alpiecode-10.7.5/test/test_slash_and_diff.py +78 -0
  19. alpiecode-10.7.5/test/test_subagents.py +93 -0
  20. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_verifier.py +16 -1
  21. {alpiecode-10.7.4 → alpiecode-10.7.5}/README.md +0 -0
  22. {alpiecode-10.7.4 → alpiecode-10.7.5}/setup.cfg +0 -0
  23. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode/__init__.py +0 -0
  24. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  25. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/entry_points.txt +0 -0
  26. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/requires.txt +0 -0
  27. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/alpiecode.egg-info/top_level.txt +0 -0
  28. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/assessment.py +0 -0
  29. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/backends/__init__.py +0 -0
  30. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/backends/base.py +0 -0
  31. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/backends/local_backend.py +0 -0
  32. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/backends/openai_backend.py +0 -0
  33. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/cli.py +0 -0
  34. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/client.py +0 -0
  35. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/compaction.py +0 -0
  36. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/discovery.py +0 -0
  37. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/doctor.py +0 -0
  38. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/dream_rsi.py +0 -0
  39. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/executor.py +0 -0
  40. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/extension/alpiecode.vsix +0 -0
  41. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/git_ops.py +0 -0
  42. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/github.py +0 -0
  43. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/guardian.py +0 -0
  44. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/guardrails.py +0 -0
  45. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/ipython_ext.py +0 -0
  46. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/local_model.py +0 -0
  47. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/media.py +0 -0
  48. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/memory.py +0 -0
  49. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/metrics.py +0 -0
  50. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/paths.py +0 -0
  51. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/progress.py +0 -0
  52. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/rephraser.py +0 -0
  53. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/server.py +0 -0
  54. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/session.py +0 -0
  55. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/updater.py +0 -0
  56. {alpiecode-10.7.4 → alpiecode-10.7.5}/src/codeagent/vscode_installer.py +0 -0
  57. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_adaptive_resilience.py +0 -0
  58. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_cli_ui.py +0 -0
  59. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_context_and_trajectory.py +0 -0
  60. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_dream_rsi.py +0 -0
  61. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_local_model_download.py +0 -0
  62. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_non_thinking_and_local_stream.py +0 -0
  63. {alpiecode-10.7.4 → alpiecode-10.7.5}/test/test_task_assessment.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.7.4
3
+ Version: 10.7.5
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "alpiecode"
7
- version = "10.7.4"
7
+ version = "10.7.5"
8
8
  description = "AlpieCode"
9
9
  requires-python = ">=3.9"
10
10
  dependencies = [
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.7.4
3
+ Version: 10.7.5
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -16,6 +16,7 @@ src/codeagent/client.py
16
16
  src/codeagent/compaction.py
17
17
  src/codeagent/config.py
18
18
  src/codeagent/context.py
19
+ src/codeagent/diff_preview.py
19
20
  src/codeagent/discovery.py
20
21
  src/codeagent/doctor.py
21
22
  src/codeagent/dream_rsi.py
@@ -36,6 +37,8 @@ src/codeagent/prompt.py
36
37
  src/codeagent/rephraser.py
37
38
  src/codeagent/server.py
38
39
  src/codeagent/session.py
40
+ src/codeagent/slash.py
41
+ src/codeagent/subagent.py
39
42
  src/codeagent/system1.py
40
43
  src/codeagent/tools.py
41
44
  src/codeagent/updater.py
@@ -52,5 +55,7 @@ test/test_context_and_trajectory.py
52
55
  test/test_dream_rsi.py
53
56
  test/test_local_model_download.py
54
57
  test/test_non_thinking_and_local_stream.py
58
+ test/test_slash_and_diff.py
59
+ test/test_subagents.py
55
60
  test/test_task_assessment.py
56
61
  test/test_verifier.py
@@ -17,7 +17,7 @@ Supports:
17
17
  from pathlib import Path
18
18
  from typing import Optional, Any, Dict
19
19
 
20
- __version__ = "10.7.4"
20
+ __version__ = "10.7.5"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -73,28 +73,38 @@ def _print_reasoning(reasoning: str):
73
73
  console.print(f"💭 {clean}")
74
74
 
75
75
 
76
+ def _format_bash_summary(args: dict) -> str:
77
+ cmd = args.get("command", "").strip()
78
+ return f"$ {cmd[:80]}..." if len(cmd) > 80 else f"$ {cmd}"
79
+
80
+
81
+ def _format_file_summary(args: dict, name: str) -> str:
82
+ path = args.get("path", "")
83
+ extra = f" ({len(str(args['content']).splitlines())} lines)" if name == "write_file" and "content" in args else ""
84
+ return f"{path}{extra}"
85
+
86
+
87
+ TOOL_SUMMARY_FORMATTERS = {
88
+ "bash": _format_bash_summary,
89
+ "write_file": lambda a: _format_file_summary(a, "write_file"),
90
+ "edit_file": lambda a: _format_file_summary(a, "edit_file"),
91
+ "read_file": lambda a: _format_file_summary(a, "read_file"),
92
+ "list_files": lambda a: a.get("path", "."),
93
+ "search": lambda a: f"'{a.get('query', '')}'",
94
+ "web_search": lambda a: f"'{a.get('query', '')}'",
95
+ "fetch_web_page": lambda a: a.get("url", ""),
96
+ "invoke_subagent": lambda a: f"🤖 {a.get('subagent', 'agent')}: '{a.get('prompt', '')[:50]}'",
97
+ }
98
+
99
+
76
100
  def _format_tool_summary(name: str, args: dict) -> str:
77
101
  if not isinstance(args, dict):
78
102
  return ""
79
- if name == "bash":
80
- cmd = args.get("command", "").strip()
81
- return f"$ {cmd[:80]}..." if len(cmd) > 80 else f"$ {cmd}"
82
- elif name in ("write_file", "edit_file", "read_file"):
83
- path = args.get("path", "")
84
- extra = ""
85
- if name == "write_file" and "content" in args:
86
- lines = len(str(args["content"]).splitlines())
87
- extra = f" ({lines} lines)"
88
- return f"{path}{extra}"
89
- elif name == "list_files":
90
- return args.get("path", ".")
91
- elif name in ("search", "web_search"):
92
- return f"'{args.get('query', '')}'"
93
- elif name == "fetch_web_page":
94
- return args.get("url", "")
95
- else:
96
- parts = [f"{k}={repr(v)[:30]}" for k, v in args.items() if k != "content"]
97
- return " ".join(parts)
103
+ formatter = TOOL_SUMMARY_FORMATTERS.get(name)
104
+ if formatter:
105
+ return formatter(args)
106
+ parts = [f"{k}={repr(v)[:30]}" for k, v in args.items() if k != "content"]
107
+ return " ".join(parts)
98
108
 
99
109
 
100
110
  def _print_tool_call(turn: int, name: str, args: dict):
@@ -772,50 +782,13 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
772
782
 
773
783
  if not user_input:
774
784
  continue
775
- if user_input.lower() in ("exit", "quit", "q"):
785
+ # In-chat slash commands (/help, /status, /diff, /undo, /doctor, /research, /review, /test, /clear, /subagents)
786
+ from .slash import handle_slash_command
787
+ slash_res = handle_slash_command(user_input, session, orchestrator, cfg, console, has_rich=HAS_RICH)
788
+ if slash_res is False:
776
789
  console.print("Goodbye! 👋")
777
790
  break
778
-
779
- # In-chat slash commands
780
- if user_input.lower() in ("/clear", "/reset"):
781
- session = session_mgr.create_session(
782
- workdir,
783
- max_tokens=backend.context_window if hasattr(backend, 'context_window') and backend.context_window else (cfg.n_ctx if cfg.base_url == 'offline' else 262_144)
784
- )
785
- if HAS_RICH:
786
- console.print("[bold green]✨ Conversation context reset.[/bold green]")
787
- else:
788
- print("✨ Conversation context reset.")
789
- continue
790
-
791
- if user_input.lower() in ("/info", "/status"):
792
- mode_str = "OFFLINE (Local GGUF)" if is_offline else "ONLINE (Cloud API)"
793
- ctx_tokens = backend.context_window if hasattr(backend, 'context_window') and backend.context_window else cfg.n_ctx
794
- user_turns = len([m for m in session.context.messages if m.get("role") == "user"])
795
- info_msg = (
796
- f"[bold]AlpieCode Session Info[/bold]\n"
797
- f" • Mode: {mode_str}\n"
798
- f" • Working Dir: {workdir}\n"
799
- f" • Context Window: {ctx_tokens} tokens\n"
800
- f" • Session Turns: {user_turns}"
801
- )
802
- if HAS_RICH:
803
- console.print(Panel(info_msg, border_style="cyan", title="ℹ️ Status"))
804
- else:
805
- print(info_msg)
806
- continue
807
-
808
- if user_input.lower() in ("/help", "/?"):
809
- help_msg = (
810
- "Available commands:\n"
811
- " • /clear, /reset - Reset conversation memory\n"
812
- " • /info, /status - View current model and session diagnostics\n"
813
- " • exit, quit, q - Exit interactive chat"
814
- )
815
- if HAS_RICH:
816
- console.print(Panel(help_msg, border_style="dim", title="Help"))
817
- else:
818
- print(help_msg)
791
+ elif slash_res is True:
819
792
  continue
820
793
 
821
794
  has_streamed_chat = False
@@ -289,10 +289,13 @@ class TestResultCache:
289
289
  def _get_workspace_fingerprint(self, workdir: Path) -> str:
290
290
  try:
291
291
  mtimes = []
292
- for ext in ("*.py", "*.js", "*.ts", "*.json"):
293
- for p in workdir.glob(ext):
294
- if p.is_file() and not p.name.startswith("."):
295
- mtimes.append(f"{p.name}:{p.stat().st_mtime_ns}")
292
+ valid_exts = {".py", ".js", ".ts", ".json"}
293
+ with os.scandir(workdir) as it:
294
+ for entry in it:
295
+ if entry.is_file() and not entry.name.startswith("."):
296
+ dot_idx = entry.name.rfind(".")
297
+ if dot_idx != -1 and entry.name[dot_idx:] in valid_exts:
298
+ mtimes.append(f"{entry.name}:{entry.stat().st_mtime_ns}")
296
299
  return hashlib.md5("".join(sorted(mtimes)).encode()).hexdigest()[:12]
297
300
  except Exception:
298
301
  return "0"
@@ -12,7 +12,8 @@ import os
12
12
  import socket
13
13
  from dataclasses import dataclass, asdict, fields
14
14
  from pathlib import Path
15
- from typing import Optional
15
+ import time
16
+ from typing import Optional, Dict, Tuple
16
17
 
17
18
  from .paths import ensure_dir, get_alpiecode_dir, is_android, is_ios, load_dotenv_if_present
18
19
 
@@ -88,42 +89,57 @@ KNOWN_PRESETS = {
88
89
  }
89
90
 
90
91
 
92
+ _SERVER_REACHABLE_CACHE: Dict[Tuple[str, float], Tuple[float, bool]] = {}
93
+
94
+
91
95
  def is_server_reachable(base_url: Optional[str], timeout: float = 0.5) -> bool:
92
- """Fast network ping check to see if server endpoint is online with DNS fallback."""
96
+ """Fast network ping check to see if server endpoint is online with DNS fallback (5s TTL cache)."""
93
97
  if not base_url:
94
98
  return False
95
- try:
96
- from urllib.parse import urlparse
97
- parsed = urlparse(base_url)
98
- host = parsed.hostname
99
- port = parsed.port or (443 if parsed.scheme == "https" else 80)
100
- if not host:
101
- return False
99
+ now = time.time()
100
+ cache_key = (base_url, timeout)
101
+ if cache_key in _SERVER_REACHABLE_CACHE:
102
+ cached_time, cached_res = _SERVER_REACHABLE_CACHE[cache_key]
103
+ if now - cached_time < 5.0:
104
+ return cached_res
105
+
106
+ def _check() -> bool:
102
107
  try:
103
- with socket.create_connection((host, port), timeout=timeout):
104
- return True
105
- except (socket.gaierror, OSError):
106
- # Resilient IP fallback for AWS EC2 / test.169pi.ai on mobile/iOS where DNS might fail ([Errno 8])
107
- if host and "ec2-18-222-121-38" in host:
108
- try:
109
- with socket.create_connection(("18.222.121.38", port), timeout=timeout):
110
- return True
111
- except Exception:
112
- pass
113
- elif host == "test.169pi.ai":
114
- try:
115
- with socket.create_connection(("20.245.200.125", port), timeout=timeout):
116
- return True
117
- except Exception:
118
- pass
108
+ from urllib.parse import urlparse
109
+ parsed = urlparse(base_url)
110
+ host = parsed.hostname
111
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
112
+ if not host:
113
+ return False
114
+ try:
115
+ with socket.create_connection((host, port), timeout=timeout):
116
+ return True
117
+ except (socket.gaierror, OSError):
118
+ # Resilient IP fallback for AWS EC2 / test.169pi.ai on mobile/iOS where DNS might fail ([Errno 8])
119
+ if host and "ec2-18-222-121-38" in host:
120
+ try:
121
+ with socket.create_connection(("18.222.121.38", port), timeout=timeout):
122
+ return True
123
+ except Exception:
124
+ pass
125
+ elif host == "test.169pi.ai":
126
+ try:
127
+ with socket.create_connection(("20.245.200.125", port), timeout=timeout):
128
+ return True
129
+ except Exception:
130
+ pass
131
+ return False
132
+ except Exception:
119
133
  return False
120
- except Exception:
121
- return False
134
+
135
+ res = _check()
136
+ _SERVER_REACHABLE_CACHE[cache_key] = (now, res)
137
+ return res
122
138
 
123
139
 
124
140
  def is_internet_available(timeout: float = 1.0) -> bool:
125
- """Quick check if general internet is available (tries DNS and HTTPS IP)."""
126
- for host, port in [("8.8.8.8", 53), ("1.1.1.1", 53), ("20.245.200.125", 443)]:
141
+ """Quick check if general internet is available (tries DNS and active cloud endpoint)."""
142
+ for host, port in [("8.8.8.8", 53), ("1.1.1.1", 53), ("18.222.121.38", 8000)]:
127
143
  try:
128
144
  with socket.create_connection((host, port), timeout=timeout):
129
145
  return True
@@ -58,6 +58,7 @@ class ContextManager:
58
58
  self._messages: List[dict] = []
59
59
  self._raw_messages: List[dict] = []
60
60
  self._metadata: List[Dict[str, Any]] = []
61
+ self._tool_id_to_name: Dict[str, str] = {}
61
62
  self._turn_counter: int = 0
62
63
  self._cached_summary: Optional[str] = None
63
64
  self._cached_summary_len: int = 0
@@ -100,19 +101,22 @@ class ContextManager:
100
101
  tokens = self._estimate_single_message_tokens(msg)
101
102
  content_str = str(msg.get("content") or "")
102
103
 
103
- # Infer tool name if not provided
104
+ # Infer tool name if not provided (O(1) lookup with backward scan fallback)
104
105
  resolved_tool_name = tool_name
105
106
  if role == "tool" and not resolved_tool_name:
106
107
  t_id = msg.get("tool_call_id", "")
107
- for prev in reversed(self._messages):
108
- if prev.get("role") == "assistant" and prev.get("tool_calls"):
109
- for tc in prev["tool_calls"]:
110
- tc_dict = tc if isinstance(tc, dict) else {}
111
- if tc_dict.get("id") == t_id:
112
- resolved_tool_name = tc_dict.get("function", {}).get("name")
108
+ if t_id and t_id in self._tool_id_to_name:
109
+ resolved_tool_name = self._tool_id_to_name[t_id]
110
+ else:
111
+ for prev in reversed(self._messages):
112
+ if prev.get("role") == "assistant" and prev.get("tool_calls"):
113
+ for tc in prev["tool_calls"]:
114
+ tc_dict = tc if isinstance(tc, dict) else {}
115
+ if tc_dict.get("id") == t_id:
116
+ resolved_tool_name = tc_dict.get("function", {}).get("name")
117
+ break
118
+ if resolved_tool_name:
113
119
  break
114
- if resolved_tool_name:
115
- break
116
120
 
117
121
  # Infer importance
118
122
  resolved_importance = importance
@@ -183,6 +187,12 @@ class ContextManager:
183
187
  """Append an assistant response with tool calls and record metadata."""
184
188
  if response.tool_calls or response.content:
185
189
  self.invalidate_cache()
190
+ if response.tool_calls:
191
+ for tc in response.tool_calls:
192
+ tc_id = getattr(tc, "id", None) or (tc.get("id") if isinstance(tc, dict) else None)
193
+ tc_name = getattr(tc, "name", None) or (tc.get("function", {}).get("name") if isinstance(tc, dict) else None)
194
+ if tc_id and tc_name:
195
+ self._tool_id_to_name[tc_id] = tc_name
186
196
  msg = _serialize_assistant_message(response)
187
197
  self._messages.append(dict(msg))
188
198
  self._raw_messages.append(copy.deepcopy(msg))
@@ -0,0 +1,77 @@
1
+ """
2
+ Interactive Diff Previewer and Formatter for AlpieCode.
3
+
4
+ Provides Git-style unified diff generation with Rich syntax highlighting:
5
+ - Green for additions (+)
6
+ - Red for deletions (-)
7
+ - Cyan for chunk headers (@@ ... @@)
8
+ """
9
+
10
+ import difflib
11
+ from pathlib import Path
12
+ from typing import Optional, Tuple
13
+
14
+
15
+ def generate_unified_diff(
16
+ original: str,
17
+ modified: str,
18
+ filepath: str = "file",
19
+ context_lines: int = 3,
20
+ ) -> str:
21
+ """Generate a standard unified diff string between original and modified text."""
22
+ orig_lines = original.splitlines(keepends=True)
23
+ mod_lines = modified.splitlines(keepends=True)
24
+
25
+ diff = difflib.unified_diff(
26
+ orig_lines,
27
+ mod_lines,
28
+ fromfile=f"a/{filepath}",
29
+ tofile=f"b/{filepath}",
30
+ n=context_lines,
31
+ )
32
+ return "".join(diff)
33
+
34
+
35
+ def format_colored_diff(diff_text: str, has_rich: bool = True) -> str:
36
+ """Format unified diff text with terminal color codes or Rich markup."""
37
+ if not diff_text or not diff_text.strip():
38
+ return "[dim]No changes detected.[/dim]" if has_rich else "No changes detected."
39
+
40
+ formatted_lines = []
41
+ for line in diff_text.splitlines():
42
+ if line.startswith("+++") or line.startswith("---"):
43
+ formatted_lines.append(f"[bold white]{line}[/bold white]" if has_rich else line)
44
+ elif line.startswith("@@"):
45
+ formatted_lines.append(f"[bold cyan]{line}[/bold cyan]" if has_rich else line)
46
+ elif line.startswith("+"):
47
+ formatted_lines.append(f"[green]{line}[/green]" if has_rich else line)
48
+ elif line.startswith("-"):
49
+ formatted_lines.append(f"[red]{line}[/red]" if has_rich else line)
50
+ else:
51
+ formatted_lines.append(f"[dim]{line}[/dim]" if has_rich else line)
52
+
53
+ return "\n".join(formatted_lines)
54
+
55
+
56
+ def get_git_diff_summary(workdir: Path) -> Tuple[str, int, int]:
57
+ """Inspect git diff of working directory and compute additions and deletions count."""
58
+ import subprocess
59
+ try:
60
+ res = subprocess.run(
61
+ ["git", "diff", "HEAD"],
62
+ cwd=str(workdir),
63
+ capture_output=True,
64
+ text=True,
65
+ timeout=5,
66
+ )
67
+ diff_text = res.stdout if res.returncode == 0 else ""
68
+ additions = 0
69
+ deletions = 0
70
+ for line in diff_text.splitlines():
71
+ if line.startswith("+") and not line.startswith("+++"):
72
+ additions += 1
73
+ elif line.startswith("-") and not line.startswith("---"):
74
+ deletions += 1
75
+ return diff_text, additions, deletions
76
+ except Exception:
77
+ return "", 0, 0
@@ -400,11 +400,13 @@ class AgentOrchestrator:
400
400
  "consecutive_stalls": progress_monitor.consecutive_stalls,
401
401
  "interventions": progress_monitor.stall_interventions,
402
402
  })
403
- # After 3 interventions (= 9+ stalled turns), force wrap-up
403
+ # After 3 interventions (= 9+ stalled turns), enforce active action
404
404
  if progress_monitor.stall_interventions >= 3:
405
405
  session.context.add_user_message(
406
- "[SYSTEM] Multiple stall interventions have not resolved the issue. "
407
- "Finish now with whatever you have. Output DONE: <summary of what was completed>."
406
+ "[SYSTEM DIRECTIVE] Multiple stall interventions have detected repetitive inspection without code modifications. "
407
+ "Do NOT continue reading or grepping files. You must take active corrective action immediately: "
408
+ "use edit_file to fix errors in existing source files, or write_file to produce deliverables, "
409
+ "then compile/run to verify. Do not output DONE until the code compiles cleanly."
408
410
  )
409
411
 
410
412
  # ── Turn-Level Adaptive Reasoning Dynamics ──
@@ -650,7 +652,19 @@ class AgentOrchestrator:
650
652
  elif tc.name == "bash":
651
653
  c = tc_args.get("command", "")
652
654
  if c:
653
- session_executed_commands.append({"command": c, "exit_code": 0})
655
+ c_exit = 0
656
+ for r in results:
657
+ if getattr(r, "tool_call_id", None) == getattr(tc, "id", None) or getattr(r, "name", "") == "bash":
658
+ try:
659
+ r_raw = getattr(r, "content", "") or ""
660
+ clean_r = r_raw.split("\n", 1)[-1] if r_raw.startswith("⚠️") else r_raw
661
+ parsed_r = _json.loads(clean_r)
662
+ if isinstance(parsed_r, dict) and "exit_code" in parsed_r:
663
+ c_exit = int(parsed_r["exit_code"])
664
+ break
665
+ except Exception:
666
+ pass
667
+ session_executed_commands.append({"command": c, "exit_code": c_exit})
654
668
 
655
669
  # ── Guard: Never report success when no tool ran on an action-oriented task ──
656
670
  task_requires_actions = task_context.intent in ("create", "modify", "debug") or getattr(task_context.assessment, "verification_required", False)
@@ -727,7 +741,7 @@ class AgentOrchestrator:
727
741
  auto_verify_passed = getattr(session, "_auto_verify_passed", False)
728
742
  verify_attempts = getattr(session, "_auto_verify_attempts", 0)
729
743
 
730
- if has_code_files and not auto_verify_passed and verify_attempts < 2:
744
+ if has_code_files and not auto_verify_passed:
731
745
  from .verifier import IntelligentVerificationEngine, format_replan_directive
732
746
  v_engine = IntelligentVerificationEngine(session.workdir)
733
747
 
@@ -747,38 +761,53 @@ class AgentOrchestrator:
747
761
 
748
762
  if not v_res.passed:
749
763
  session._auto_verify_attempts = verify_attempts + 1
750
- replan_prompt = format_replan_directive(v_res, is_offline=is_offline)
751
- session.context.add_user_message(replan_prompt)
752
-
753
- v_type = "syntax" if v_res.tier == "syntax" else ("tests" if "test" in v_res.tier else v_res.tier)
754
- v_event_data = {
755
- "type": v_type,
756
- "tier": v_res.tier,
757
- "error_type": v_res.error_type,
758
- "message": v_res.message,
759
- "failing_file": v_res.failing_file,
760
- }
761
- if v_res.errors:
762
- v_event_data["errors"] = v_res.errors
763
- if v_res.command:
764
- v_event_data["command"] = v_res.command
765
- v_event_data["exit_code"] = v_res.exit_code
766
- yield AgentEvent("verification_failed", v_event_data)
767
-
768
- replan_trigger = "syntax_errors" if v_res.tier == "syntax" else ("test_failure" if "test" in v_res.tier else f"{v_res.tier}_failure")
769
- replan_data = {
770
- "turn": turn,
771
- "strategy": strategy,
772
- "trigger": replan_trigger,
773
- "details": v_res.errors or v_res.message,
774
- }
775
- if v_res.command:
776
- replan_data["command"] = v_res.command
777
- replan_data["exit_code"] = v_res.exit_code
778
- yield AgentEvent("replan", replan_data)
779
-
780
- prior_turn_had_error = True
781
- continue
764
+ if session._auto_verify_attempts < 2:
765
+ replan_prompt = format_replan_directive(v_res, is_offline=is_offline)
766
+ session.context.add_user_message(replan_prompt)
767
+
768
+ v_type = "syntax" if v_res.tier == "syntax" else ("tests" if "test" in v_res.tier else v_res.tier)
769
+ v_event_data = {
770
+ "type": v_type,
771
+ "tier": v_res.tier,
772
+ "error_type": v_res.error_type,
773
+ "message": v_res.message,
774
+ "failing_file": v_res.failing_file,
775
+ }
776
+ if v_res.errors:
777
+ v_event_data["errors"] = v_res.errors
778
+ if v_res.command:
779
+ v_event_data["command"] = v_res.command
780
+ v_event_data["exit_code"] = v_res.exit_code
781
+ yield AgentEvent("verification_failed", v_event_data)
782
+
783
+ replan_trigger = "syntax_errors" if v_res.tier == "syntax" else ("test_failure" if "test" in v_res.tier else f"{v_res.tier}_failure")
784
+ replan_data = {
785
+ "turn": turn,
786
+ "strategy": strategy,
787
+ "trigger": replan_trigger,
788
+ "details": v_res.errors or v_res.message,
789
+ }
790
+ if v_res.command:
791
+ replan_data["command"] = v_res.command
792
+ replan_data["exit_code"] = v_res.exit_code
793
+ yield AgentEvent("replan", replan_data)
794
+
795
+ prior_turn_had_error = True
796
+ continue
797
+ else:
798
+ # Replan attempts exhausted: fail, never report success
799
+ task_metrics.finish()
800
+ yield AgentEvent("metrics", task_metrics.summary())
801
+ _ensure_trajectory_saved("failed")
802
+ yield AgentEvent("failed", {
803
+ "reason": "verification_failed",
804
+ "message": f"Verification failed after replan attempts: {v_res.message}",
805
+ })
806
+ yield AgentEvent("done", {
807
+ "summary": f"Task failed verification: {v_res.message}",
808
+ "success": False,
809
+ })
810
+ return
782
811
 
783
812
  session._auto_verify_passed = True
784
813
 
@@ -857,7 +886,19 @@ class AgentOrchestrator:
857
886
  elif tc.name == "bash":
858
887
  c = tc_args.get("command", "")
859
888
  if c:
860
- session_executed_commands.append({"command": c, "exit_code": 0})
889
+ c_exit = 0
890
+ for r in results:
891
+ if getattr(r, "tool_call_id", None) == getattr(tc, "id", None) or getattr(r, "name", "") == "bash":
892
+ try:
893
+ r_raw = getattr(r, "content", "") or ""
894
+ clean_r = r_raw.split("\n", 1)[-1] if r_raw.startswith("⚠️") else r_raw
895
+ parsed_r = _json.loads(clean_r)
896
+ if isinstance(parsed_r, dict) and "exit_code" in parsed_r:
897
+ c_exit = int(parsed_r["exit_code"])
898
+ break
899
+ except Exception:
900
+ pass
901
+ session_executed_commands.append({"command": c, "exit_code": c_exit})
861
902
 
862
903
  # ── Record progress for stall detection ──
863
904
  tc_dicts = [{"name": tc.name, "arguments": tc.arguments} for tc in tool_calls]