alpiecode 10.8.3__tar.gz → 10.8.6__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 (69) hide show
  1. {alpiecode-10.8.3 → alpiecode-10.8.6}/PKG-INFO +2 -1
  2. {alpiecode-10.8.3 → alpiecode-10.8.6}/pyproject.toml +2 -1
  3. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/PKG-INFO +2 -1
  4. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/requires.txt +1 -0
  5. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/agent.py +63 -7
  7. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/blueprints.py +5 -2
  8. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/cli.py +5 -0
  9. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/compaction.py +1 -1
  10. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/discovery.py +7 -4
  11. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/guardrails.py +15 -5
  12. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/memory.py +5 -5
  13. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/orchestrator.py +6 -6
  14. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/prompt.py +12 -0
  15. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/tools.py +24 -1
  16. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_deloop_and_sessions.py +71 -0
  17. {alpiecode-10.8.3 → alpiecode-10.8.6}/README.md +0 -0
  18. {alpiecode-10.8.3 → alpiecode-10.8.6}/setup.cfg +0 -0
  19. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode/__init__.py +0 -0
  20. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/SOURCES.txt +0 -0
  21. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  22. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/entry_points.txt +0 -0
  23. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/alpiecode.egg-info/top_level.txt +0 -0
  24. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/assessment.py +0 -0
  25. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/backends/__init__.py +0 -0
  26. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/backends/base.py +0 -0
  27. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/backends/local_backend.py +0 -0
  28. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/backends/openai_backend.py +0 -0
  29. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/cache.py +0 -0
  30. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/client.py +0 -0
  31. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/config.py +0 -0
  32. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/context.py +0 -0
  33. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/diff_preview.py +0 -0
  34. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/doctor.py +0 -0
  35. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/dream_rsi.py +0 -0
  36. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/executor.py +0 -0
  37. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/git_ops.py +0 -0
  38. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/github.py +0 -0
  39. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/guardian.py +0 -0
  40. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/ipython_ext.py +0 -0
  41. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/local_model.py +0 -0
  42. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/media.py +0 -0
  43. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/metrics.py +0 -0
  44. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/paths.py +0 -0
  45. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/progress.py +0 -0
  46. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/project_template.py +0 -0
  47. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/rephraser.py +0 -0
  48. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/server.py +0 -0
  49. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/session.py +0 -0
  50. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/slash.py +0 -0
  51. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/subagent.py +0 -0
  52. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/system1.py +0 -0
  53. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/updater.py +0 -0
  54. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/verifier.py +0 -0
  55. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/vscode_installer.py +0 -0
  56. {alpiecode-10.8.3 → alpiecode-10.8.6}/src/codeagent/walkthrough.py +0 -0
  57. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_adaptive_resilience.py +0 -0
  58. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_cli_ui.py +0 -0
  59. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_context_and_trajectory.py +0 -0
  60. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_dream_rsi.py +0 -0
  61. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_local_model_download.py +0 -0
  62. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_non_thinking_and_local_stream.py +0 -0
  63. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_project_templates.py +0 -0
  64. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_slash_and_diff.py +0 -0
  65. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_subagents.py +0 -0
  66. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_task_assessment.py +0 -0
  67. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_verifier.py +0 -0
  68. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_walkthrough.py +0 -0
  69. {alpiecode-10.8.3 → alpiecode-10.8.6}/test/test_web_resilience_and_guardrails.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.8.3
3
+ Version: 10.8.6
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -9,6 +9,7 @@ Requires-Dist: click>=8.0
9
9
  Requires-Dist: httpx[http2]>=0.24.0
10
10
  Requires-Dist: beautifulsoup4>=4.12.0
11
11
  Requires-Dist: yt-dlp>=2024.0.0
12
+ Requires-Dist: prompt-toolkit>=3.0.0
12
13
  Provides-Extra: server
13
14
  Requires-Dist: fastapi>=0.100.0; extra == "server"
14
15
  Requires-Dist: uvicorn>=0.20.0; extra == "server"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "alpiecode"
7
- version = "10.8.3"
7
+ version = "10.8.6"
8
8
  description = "AlpieCode"
9
9
  requires-python = ">=3.9"
10
10
  dependencies = [
@@ -14,6 +14,7 @@ dependencies = [
14
14
  "httpx[http2]>=0.24.0",
15
15
  "beautifulsoup4>=4.12.0",
16
16
  "yt-dlp>=2024.0.0",
17
+ "prompt-toolkit>=3.0.0",
17
18
  ]
18
19
 
19
20
  [project.optional-dependencies]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.8.3
3
+ Version: 10.8.6
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -9,6 +9,7 @@ Requires-Dist: click>=8.0
9
9
  Requires-Dist: httpx[http2]>=0.24.0
10
10
  Requires-Dist: beautifulsoup4>=4.12.0
11
11
  Requires-Dist: yt-dlp>=2024.0.0
12
+ Requires-Dist: prompt-toolkit>=3.0.0
12
13
  Provides-Extra: server
13
14
  Requires-Dist: fastapi>=0.100.0; extra == "server"
14
15
  Requires-Dist: uvicorn>=0.20.0; extra == "server"
@@ -4,6 +4,7 @@ click>=8.0
4
4
  httpx[http2]>=0.24.0
5
5
  beautifulsoup4>=4.12.0
6
6
  yt-dlp>=2024.0.0
7
+ prompt-toolkit>=3.0.0
7
8
 
8
9
  [ffmpeg]
9
10
  imageio-ffmpeg>=0.4.0
@@ -17,7 +17,7 @@ Supports:
17
17
  from pathlib import Path
18
18
  from typing import Optional, Any, Dict
19
19
 
20
- __version__ = "10.8.3"
20
+ __version__ = "10.8.6"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -79,7 +79,11 @@ def _format_bash_summary(args: dict) -> str:
79
79
 
80
80
 
81
81
  def _format_file_summary(args: dict, name: str) -> str:
82
- path = args.get("path", "")
82
+ path = args.get("path") or args.get("file") or ""
83
+ if name == "edit_file":
84
+ old_lines = len(str(args.get("old_str", "")).splitlines())
85
+ new_lines = len(str(args.get("new_str", "")).splitlines())
86
+ return f"{path} (-{old_lines}/+{new_lines} lines)"
83
87
  extra = f" ({len(str(args['content']).splitlines())} lines)" if name == "write_file" and "content" in args else ""
84
88
  return f"{path}{extra}"
85
89
 
@@ -592,8 +596,34 @@ def run_agent(
592
596
 
593
597
  elif event.type == "tool_result":
594
598
  status_spinner.pause()
595
- if verbose and debug:
596
- _print_tool_result(event.data["content"])
599
+ res_content = str(event.data.get("content", ""))
600
+ if "@@" in res_content and ("--- a/" in res_content or "+++ b/" in res_content):
601
+ from .diff_preview import format_colored_diff
602
+ diff_idx = res_content.find("--- a/")
603
+ if diff_idx != -1:
604
+ header_line = res_content[:diff_idx].strip()
605
+ if header_line and verbose:
606
+ if HAS_RICH:
607
+ console.print(Text(f" └ {header_line}", style="dim green"))
608
+ else:
609
+ print(f" └ {header_line}")
610
+ diff_text = res_content[diff_idx:]
611
+ else:
612
+ diff_text = res_content
613
+ d_lines = diff_text.splitlines()
614
+ if len(d_lines) > 25:
615
+ diff_snippet = "\n".join(d_lines[:22]) + f"\n ... ({len(d_lines)-22} diff lines omitted)"
616
+ else:
617
+ diff_snippet = diff_text
618
+ formatted = format_colored_diff(diff_snippet, has_rich=HAS_RICH)
619
+ if verbose:
620
+ if HAS_RICH:
621
+ console.print(formatted)
622
+ else:
623
+ print(formatted)
624
+ has_printed_anything = True
625
+ elif verbose and debug:
626
+ _print_tool_result(res_content)
597
627
  _checkpoint(workdir, f"checkpoint: turn {event.data['turn']}")
598
628
  status_spinner.resume("Evaluating result & planning next step...", style="bold cyan")
599
629
 
@@ -793,6 +823,35 @@ def run_agent(
793
823
  return AgentRunResult(msgs, success=task_success, outcome=task_outcome)
794
824
 
795
825
 
826
+ def _get_chat_input(prompt_text: str = "You ❯") -> str:
827
+ """Read interactive user input with full arrow-key line editing, cursor movement, and history."""
828
+ try:
829
+ from prompt_toolkit import PromptSession
830
+ from prompt_toolkit.history import FileHistory
831
+ from prompt_toolkit.formatted_text import HTML
832
+ from .paths import get_alpiecode_dir, ensure_dir
833
+
834
+ hist_dir = ensure_dir(get_alpiecode_dir())
835
+ hist_file = hist_dir / "chat_history"
836
+ session = getattr(_get_chat_input, "_pt_session", None)
837
+ if session is None:
838
+ session = PromptSession(history=FileHistory(str(hist_file)))
839
+ _get_chat_input._pt_session = session
840
+
841
+ return session.prompt(HTML(f"\n<ansigreen><b>{prompt_text}</b></ansigreen> ")).strip()
842
+ except Exception:
843
+ pass
844
+
845
+ try:
846
+ import readline
847
+ except ImportError:
848
+ pass
849
+
850
+ if HAS_RICH and console:
851
+ return console.input(f"\n[bold green]{prompt_text}[/bold green] ").strip()
852
+ return input(f"\n{prompt_text} ").strip()
853
+
854
+
796
855
  def run_chat(
797
856
  workdir: Path,
798
857
  cfg: Config,
@@ -856,10 +915,7 @@ def run_chat(
856
915
 
857
916
  while True:
858
917
  try:
859
- if HAS_RICH:
860
- user_input = console.input("\n[bold green]You ❯[/bold green] ").strip()
861
- else:
862
- user_input = input("\nYou ❯ ").strip()
918
+ user_input = _get_chat_input("You ❯")
863
919
  except (EOFError, KeyboardInterrupt):
864
920
  session_mgr.save_session(session)
865
921
  if HAS_RICH:
@@ -64,18 +64,21 @@ def get_web_app_blueprint(task: str) -> DomainBlueprint:
64
64
  entry_point="index.html",
65
65
  execution_runner="python3 -m http.server 8000 (view at http://localhost:8000)",
66
66
  architecture_rules=[
67
+ "Architecture: 100% Pure Vanilla Web Stack (HTML5 + CSS3 + Vanilla JavaScript IIFE). Fast, zero dependencies, zero build step, instant load.",
67
68
  "Write `index.html` FIRST with rich static-first markup: Pre-render headers, hero, navigation, card containers, and modal structure in HTML. NEVER leave an empty body or empty `<div id='app'>`.",
68
69
  "Include an on-screen Error Boundary in `index.html` via `window.addEventListener('error', ...)` to display any JavaScript exceptions visually instead of a blank white screen.",
69
70
  "Write `styles.css` SECOND: Modern responsive styling (CSS Grid/Flexbox, clean typography, badge counters, glassmorphism, card hover lift).",
70
- "Write `app.js` THIRD: Universal vanilla JavaScript in an IIFE `(function() { 'use strict'; ... })();`. Every ID queried (`document.getElementById`) MUST match an `id` present in `index.html`.",
71
+ "Write `app.js` THIRD: Universal vanilla JavaScript in an IIFE `(function() { 'use strict'; ... })();`. Keep `app.js` concise and modular (< 350 lines). Include 6 to 8 rich mock items, not dozens.",
71
72
  "Use `download_asset` or curated Unsplash CDN URLs / inline SVGs for all imagery to ensure 100% working images without 404 broken icons.",
72
73
  "Write EXACTLY ONE complete file per turn in order (Turn 1: index.html, Turn 2: styles.css, Turn 3: app.js).",
73
74
  "Verify all files exist and validate JavaScript with `node --check app.js` before completing.",
74
75
  ],
75
76
  prohibitions=[
77
+ "NEVER load React, ReactDOM, Babel Standalone (`@babel/standalone`), Vue, or Angular via `<script>` CDN in `index.html`. Browser web applications MUST run natively in standard browsers without in-browser compilation.",
78
+ "NEVER write React JSX syntax (`<Component />` or HTML tags inside JS) in `.js` or `.jsx` files. Node cannot run JSX, and browsers without build tools cannot parse JSX. Use `document.createElement`, template literals, or `innerHTML`.",
79
+ "NEVER write oversized JavaScript files (> 350 lines) with gigantic mock datasets. Keep mock data focused and clean (6-8 items).",
76
80
  "NEVER generate an empty `<div id='app'></div>` without pre-rendered static HTML fallback markup (prevents blank white screens).",
77
81
  "NEVER use ES module `import`/`export` in browser scripts without a bundler -- use self-executing functions so it works on both `file://` and `http://localhost`.",
78
- "NEVER write standalone `.jsx` files without a build tool like Vite -- Node cannot execute raw JSX.",
79
82
  "NEVER write utility files like `utils/formatPrice.js` before `index.html` exists.",
80
83
  "NEVER start blocking daemon servers with `&` or real `sleep` in terminal commands.",
81
84
  ],
@@ -88,6 +88,11 @@ def _normalize_args():
88
88
 
89
89
 
90
90
  def main():
91
+ try:
92
+ import readline # Enable full command-line editing (left/right arrow navigation, history)
93
+ except ImportError:
94
+ pass
95
+
91
96
  _normalize_args()
92
97
 
93
98
  common = argparse.ArgumentParser(add_help=False)
@@ -66,7 +66,7 @@ def _summarize_tool_result(tool_name: str, content: str) -> str:
66
66
  first_line = content.strip().splitlines()[0][:90]
67
67
  return f"[Historical tool result (addressed in subsequent turns): {first_line}]"
68
68
 
69
- if tool_name == "write_file" or "wrote " in c_lower or "successfully wrote" in c_lower:
69
+ if tool_name in ("write_file", "edit_file") or "wrote " in c_lower or "successfully wrote" in c_lower or "edit applied" in c_lower:
70
70
  first_line = content.strip().splitlines()[0][:90]
71
71
  return f"[Completed: {first_line}]"
72
72
 
@@ -724,16 +724,19 @@ def build_task_context(task: str, workdir: Path) -> TaskContext:
724
724
  session_data = read_project_session(workdir)
725
725
  has_session = session_data is not None
726
726
 
727
- if complexity in ("high", "extreme") or len(repo.get("frameworks", [])) > 1:
727
+ from .blueprints import resolve_domain_blueprint, BlueprintType
728
+ blueprint = resolve_domain_blueprint(task, repo, intent)
729
+
730
+ if blueprint and blueprint.blueprint_type in (BlueprintType.WEB_APP, BlueprintType.GAME, BlueprintType.CLI_SCRIPT):
731
+ # Keep web applications, games, and CLI tools clean and focused (no 15-file markdown clutter)
732
+ project_profile = "basic"
733
+ elif complexity in ("high", "extreme") or len(repo.get("frameworks", [])) > 1:
728
734
  project_profile = "advanced"
729
735
  elif complexity == "low" and repo.get("file_count", 0) <= 2:
730
736
  project_profile = "basic"
731
737
  else:
732
738
  project_profile = "standard"
733
739
 
734
- from .blueprints import resolve_domain_blueprint
735
- blueprint = resolve_domain_blueprint(task, repo, intent)
736
-
737
740
  return TaskContext(
738
741
  symbol_index=symbol_index,
739
742
  # Assessment & Strategy
@@ -100,11 +100,13 @@ def validate_javascript_syntax(file_path: str, content: str) -> Tuple[bool, Opti
100
100
  err = res_esm.stderr.strip() or "Syntax error in ES module"
101
101
  return False, f"JavaScript SyntaxError in '{file_path}': {err}"
102
102
 
103
- # 3. If file contains JSX syntax, fall back to bracket validation
104
- if "<" in content and ">" in content:
105
- is_balanced, balance_err = check_bracket_balance(content)
106
- if is_balanced:
107
- return True, None
103
+ # 3. If file contains JSX syntax in a .js file, provide an actionable directive
104
+ if "Unexpected token '<'" in err_output or "Unexpected token <" in err_output:
105
+ return False, (
106
+ f"JavaScript SyntaxError in '{file_path}': Raw JSX/HTML syntax ('<tag>') detected. "
107
+ "Node.js and browsers cannot execute raw JSX in .js files without a build step. "
108
+ "Use standard JavaScript DOM APIs (document.createElement, innerHTML, or template literals) instead of JSX."
109
+ )
108
110
 
109
111
  err = res.stderr.strip() or "Syntax error in JavaScript code"
110
112
  return False, f"JavaScript SyntaxError in '{file_path}': {err}"
@@ -148,6 +150,14 @@ def validate_code_syntax(file_path: str, content: str) -> Tuple[bool, Optional[s
148
150
  if not content or not content.strip():
149
151
  return True, None
150
152
 
153
+ # Guard against accidental persistence of compaction summary markers
154
+ stripped = content.strip()
155
+ if stripped.startswith("[Content saved to ") or "[Content saved to " in stripped[:120]:
156
+ return False, (
157
+ f"Pre-commit error for '{file_path}': File content contains a compacted history placeholder marker ('{stripped[:60]}...'). "
158
+ "You must write the complete, actual code implementation, not the historical summary marker."
159
+ )
160
+
151
161
  ext = Path(file_path).suffix.lower()
152
162
  validator = SYNTAX_VALIDATORS.get(ext)
153
163
  if validator:
@@ -15,7 +15,7 @@ import json
15
15
  import hashlib
16
16
  import time
17
17
  from pathlib import Path
18
- from typing import List, Optional
18
+ from typing import List, Optional, Union
19
19
 
20
20
  from .paths import ensure_dir, get_alpiecode_dir
21
21
 
@@ -27,17 +27,17 @@ def get_memory_dir() -> Path:
27
27
  MEMORY_DIR = get_alpiecode_dir() / "memories"
28
28
 
29
29
 
30
- def _project_key(workdir: Path) -> str:
30
+ def _project_key(workdir: Union[Path, str]) -> str:
31
31
  """Generate a stable key for a project directory."""
32
- return hashlib.md5(str(workdir.resolve()).encode()).hexdigest()[:12]
32
+ return hashlib.md5(str(Path(workdir).resolve()).encode()).hexdigest()[:12]
33
33
 
34
34
 
35
- def _memory_path(workdir: Path) -> Path:
35
+ def _memory_path(workdir: Union[Path, str]) -> Path:
36
36
  """Get the memory file path for a project."""
37
37
  return get_memory_dir() / f"{_project_key(workdir)}.json"
38
38
 
39
39
 
40
- def load_memories(workdir: Path) -> List[dict]:
40
+ def load_memories(workdir: Union[Path, str]) -> List[dict]:
41
41
  """
42
42
  Load memories for a specific project directory.
43
43
 
@@ -284,10 +284,10 @@ class AgentOrchestrator:
284
284
  if is_offline:
285
285
  session.context.max_tokens = getattr(cfg, "n_ctx", 8192)
286
286
  else:
287
- b_window = getattr(task_backend, "context_window", 32768)
288
- if not isinstance(b_window, int):
289
- b_window = 32768
290
- session.context.max_tokens = min(b_window, max(effective_max_tokens, 8192))
287
+ b_window = getattr(task_backend, "context_window", 262144)
288
+ if not isinstance(b_window, int) or b_window <= 0:
289
+ b_window = 262144
290
+ session.context.max_tokens = b_window
291
291
  # ?? Dream-RSI Trajectory Recorder ??
292
292
  trajectory_store = TrajectoryStore()
293
293
  trajectory_record = TrajectoryRecord(
@@ -344,9 +344,9 @@ class AgentOrchestrator:
344
344
  f"[ARCHITECTURE DIRECTIVE: {bp.name.upper()}]\n"
345
345
  f"- Required Deliverables: {', '.join(bp.target_files)}\n"
346
346
  f"- Primary Entry Point: {bp.entry_point}\n"
347
- f"- Step 1 (Turn 1): Create '{bp.target_files[0]}' with complete static structure. NEVER generate React/JSX files, empty shells, or unneeded tooling.\n"
347
+ f"- Step 1 (Turn 1): Create '{bp.target_files[0]}' with complete static structure. Pure Vanilla HTML5/CSS3. NEVER load React, Babel Standalone, Vue, or JSX tooling.\n"
348
348
  f"- Step 2: Implement styling and components sequentially.\n"
349
- f"- Step 3: Implement client JavaScript (Universal IIFE, no unbundled ES modules).\n\n"
349
+ f"- Step 3: Implement client JavaScript (Universal Vanilla JS IIFE, NO JSX, NO unbundled ES modules, keep under 300 lines).\n\n"
350
350
  )
351
351
  effective_task = bp_directive + effective_task
352
352
 
@@ -177,8 +177,14 @@ When creating or modifying multi-file projects (e.g. websites, full-stack apps,
177
177
  - Turn 3: Write the logic or component (e.g. `app.js`).
178
178
  - Focus on ONE complete file per turn: this prevents output truncation, guarantees 100% valid syntax, and ensures production-ready code.
179
179
 
180
+ ## Language Selection Policy — CRITICAL
181
+ - Web Development (websites, web applications, stores, dashboards, UI): ALWAYS use standard HTML5, modern CSS3, and Vanilla JavaScript (`index.html`, `styles.css`, `app.js`).
182
+ - All Other Tasks (scripts, CLI tools, APIs, backends, AI/ML, data processing, algorithms, autonomous agents): Default to **Python** (clean, modern Python 3.10+).
183
+ - Use other languages (Rust, Go, C, C++, Java, etc.) ONLY if the user explicitly mentioned that specific language in their prompt (e.g. "in rust", "using golang", "in c++").
184
+
180
185
  ## Tool Rules
181
186
  - Use write_file for NEW files, edit_file for EXISTING files
187
+ - NEVER use write_file to overwrite an existing file from line 0 — use edit_file to modify targeted lines!
182
188
  - Always read_file before edit_file — never edit blind
183
189
  - bash for running code, compiling, testing
184
190
  - Do NOT use bash just to list files or explore — start coding instead
@@ -269,8 +275,14 @@ For multi-file projects, build in dependency order, emitting ONE complete file p
269
275
  - For all projects: Build/compile or verify syntax after each file to catch errors early
270
276
  - Integration build + test after all files written
271
277
 
278
+ ## Language Selection Policy — CRITICAL
279
+ - Web Development (websites, web applications, stores, dashboards, UI): ALWAYS use standard HTML5, modern CSS3, and Vanilla JavaScript (`index.html`, `styles.css`, `app.js`).
280
+ - All Other Tasks (scripts, CLI tools, APIs, backends, AI/ML, data processing, algorithms, autonomous agents): Default to **Python** (clean, modern Python 3.10+).
281
+ - Use other languages (Rust, Go, C, C++, Java, etc.) ONLY if the user explicitly mentioned that specific language in their prompt (e.g. "in rust", "using golang", "in c++").
282
+
272
283
  ## Tool Rules
273
284
  - Use write_file for NEW files, edit_file for EXISTING files
285
+ - NEVER use write_file to overwrite an existing file from line 0 — use edit_file to modify targeted lines!
274
286
  - Always read_file before edit_file
275
287
  - Use list_files to understand project structure when modifying existing code
276
288
  - Use file_search to find specific code patterns
@@ -640,10 +640,20 @@ def _write_file(workdir: Path, path: str, content: str) -> str:
640
640
 
641
641
  p = _resolve_safe_path(workdir, path)
642
642
  p.parent.mkdir(parents=True, exist_ok=True)
643
+ file_existed = p.exists() and p.is_file()
644
+ old_content = p.read_text(encoding="utf-8", errors="replace") if file_existed else ""
645
+
643
646
  p.write_text(content, encoding="utf-8")
644
647
  _RECENTLY_WRITTEN_FILES.add(Path(path).name.lower())
645
648
  get_file_cache().invalidate(p)
646
649
  get_test_cache().invalidate(workdir)
650
+
651
+ if file_existed and old_content and old_content != content:
652
+ from .diff_preview import generate_unified_diff
653
+ diff_text = generate_unified_diff(old_content, content, filepath=path, context_lines=2)
654
+ if diff_text.strip():
655
+ return f"wrote {len(content)} bytes to {path}\n{diff_text.strip()}"
656
+
647
657
  return f"wrote {len(content)} bytes to {path}"
648
658
 
649
659
 
@@ -700,6 +710,14 @@ def _edit_file(workdir: Path, path: str, old_str: str, new_str: str) -> str:
700
710
  return f"error: Edit would result in a syntax error in '{path}':\n{err}\nPlease revise the replacement."
701
711
 
702
712
  p.write_text(new_text, encoding="utf-8")
713
+ _RECENTLY_WRITTEN_FILES.add(Path(path).name.lower())
714
+ get_file_cache().invalidate(p)
715
+ get_test_cache().invalidate(workdir)
716
+
717
+ from .diff_preview import generate_unified_diff
718
+ diff_text = generate_unified_diff(text, new_text, filepath=path, context_lines=2)
719
+ if diff_text.strip():
720
+ return f"edit applied to {path}\n{diff_text.strip()}"
703
721
  return "edit applied"
704
722
 
705
723
 
@@ -937,6 +955,11 @@ def _fetch_url(url: str) -> str:
937
955
 
938
956
  def _request_user_input(question: str) -> str:
939
957
  """Ask the user a question and return their response."""
958
+ try:
959
+ import readline # Enable arrow key navigation in terminal
960
+ except ImportError:
961
+ pass
962
+
940
963
  try:
941
964
  from rich.console import Console
942
965
  from rich.panel import Panel
@@ -948,7 +971,7 @@ def _request_user_input(question: str) -> str:
948
971
  border_style="yellow",
949
972
  ))
950
973
  response = console.input("[bold green]Your answer ❯[/bold green] ").strip()
951
- except ImportError:
974
+ except Exception:
952
975
  print(f"\n❓ Agent needs your input: {question}")
953
976
  response = input("Your answer ❯ ").strip()
954
977
 
@@ -148,3 +148,74 @@ def test_verifier_batch_missing_dom_ids(tmp_path):
148
148
  assert res.error_type == "dom_id_mismatch"
149
149
  assert "'#cart-container'" in res.message
150
150
  assert "'#close-cart-btn'" in res.message
151
+
152
+
153
+ def test_raw_jsx_in_js_file_rejected_with_directive():
154
+ """Verify raw JSX in a .js file produces an actionable pre-commit directive."""
155
+ from codeagent.guardrails import validate_code_syntax
156
+ raw_jsx = """
157
+ function renderApp() {
158
+ return <ShopContext.Provider value={value}>{children}</ShopContext.Provider>;
159
+ }
160
+ """
161
+ passed, err = validate_code_syntax("app.js", raw_jsx)
162
+ assert not passed
163
+ assert "Raw JSX/HTML syntax ('<tag>') detected" in err
164
+ assert "Use standard JavaScript DOM APIs" in err
165
+
166
+
167
+ def test_compacted_placeholder_rejected_by_guardrail():
168
+ """Verify that accidental writes of compaction placeholder markers are caught before hitting disk."""
169
+ from codeagent.guardrails import validate_code_syntax
170
+ compacted_stub = "[Content saved to app.js (487 lines, 15890 bytes)]"
171
+ passed, err = validate_code_syntax("app.js", compacted_stub)
172
+ assert not passed
173
+ assert "compacted history placeholder marker" in err
174
+
175
+
176
+ def test_web_app_blueprint_rules_enforce_vanilla_stack():
177
+ """Verify that get_web_app_blueprint explicitly forbids React/Babel CDN and raw JSX."""
178
+ from codeagent.blueprints import get_web_app_blueprint
179
+ bp = get_web_app_blueprint("create a grocery ecommerce website")
180
+ prohib_text = " ".join(bp.prohibitions)
181
+ assert "React" in prohib_text
182
+ assert "Babel Standalone" in prohib_text
183
+ assert "JSX" in prohib_text
184
+ assert bp.target_files == ["index.html", "styles.css", "app.js"]
185
+
186
+
187
+ def test_edit_file_produces_git_diff(tmp_path):
188
+ """Verify that edit_file returns a unified git-style diff."""
189
+ from codeagent.tools import _edit_file
190
+ target = tmp_path / "app.js"
191
+ target.write_text("const a = 1;\nconst b = 2;\nconsole.log(a + b);\n")
192
+
193
+ res = _edit_file(tmp_path, "app.js", "const b = 2;", "const b = 20;")
194
+ assert "edit applied to app.js" in res
195
+ assert "--- a/app.js" in res
196
+ assert "+++ b/app.js" in res
197
+ assert "-const b = 2;" in res
198
+ assert "+const b = 20;" in res
199
+
200
+
201
+ def test_write_file_on_existing_file_produces_git_diff(tmp_path):
202
+ """Verify that write_file modifying an existing file returns a unified git diff."""
203
+ from codeagent.tools import _write_file
204
+ target = tmp_path / "main.py"
205
+ target.write_text("def hello():\n return 'world'\n")
206
+
207
+ res = _write_file(tmp_path, "main.py", "def hello():\n return 'universe'\n")
208
+ assert "wrote" in res
209
+ assert "main.py" in res
210
+ assert "--- a/main.py" in res
211
+ assert "- return 'world'" in res
212
+ assert "+ return 'universe'" in res
213
+
214
+
215
+ def test_clean_folder_structure_for_web_app_blueprint(tmp_path):
216
+ """Verify that web app tasks resolve to clean basic scaffolding without 15-file clutter."""
217
+ from codeagent.discovery import build_task_context
218
+ ctx = build_task_context("create a fruit store website", tmp_path)
219
+ assert ctx.project_profile == "basic"
220
+ assert ctx.blueprint is not None
221
+ assert ctx.blueprint.name == "Browser-First Web Application"
File without changes
File without changes