alpiecode 10.8.2__tar.gz → 10.8.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 (70) hide show
  1. {alpiecode-10.8.2 → alpiecode-10.8.5}/PKG-INFO +1 -1
  2. {alpiecode-10.8.2 → alpiecode-10.8.5}/pyproject.toml +1 -1
  3. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/PKG-INFO +1 -1
  4. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/SOURCES.txt +1 -0
  5. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/agent.py +131 -24
  7. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/blueprints.py +5 -2
  8. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/cli.py +32 -3
  9. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/compaction.py +1 -1
  10. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/discovery.py +7 -4
  11. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/executor.py +10 -7
  12. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/guardrails.py +15 -5
  13. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/memory.py +5 -5
  14. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/orchestrator.py +64 -8
  15. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/prompt.py +12 -0
  16. alpiecode-10.8.5/src/codeagent/session.py +302 -0
  17. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/slash.py +41 -0
  18. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/system1.py +72 -10
  19. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/tools.py +27 -0
  20. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/verifier.py +21 -7
  21. alpiecode-10.8.5/test/test_deloop_and_sessions.py +221 -0
  22. alpiecode-10.8.2/src/codeagent/session.py +0 -77
  23. {alpiecode-10.8.2 → alpiecode-10.8.5}/README.md +0 -0
  24. {alpiecode-10.8.2 → alpiecode-10.8.5}/setup.cfg +0 -0
  25. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode/__init__.py +0 -0
  26. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  27. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/entry_points.txt +0 -0
  28. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/requires.txt +0 -0
  29. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/alpiecode.egg-info/top_level.txt +0 -0
  30. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/assessment.py +0 -0
  31. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/backends/__init__.py +0 -0
  32. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/backends/base.py +0 -0
  33. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/backends/local_backend.py +0 -0
  34. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/backends/openai_backend.py +0 -0
  35. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/cache.py +0 -0
  36. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/client.py +0 -0
  37. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/config.py +0 -0
  38. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/context.py +0 -0
  39. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/diff_preview.py +0 -0
  40. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/doctor.py +0 -0
  41. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/dream_rsi.py +0 -0
  42. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/git_ops.py +0 -0
  43. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/github.py +0 -0
  44. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/guardian.py +0 -0
  45. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/ipython_ext.py +0 -0
  46. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/local_model.py +0 -0
  47. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/media.py +0 -0
  48. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/metrics.py +0 -0
  49. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/paths.py +0 -0
  50. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/progress.py +0 -0
  51. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/project_template.py +0 -0
  52. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/rephraser.py +0 -0
  53. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/server.py +0 -0
  54. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/subagent.py +0 -0
  55. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/updater.py +0 -0
  56. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/vscode_installer.py +0 -0
  57. {alpiecode-10.8.2 → alpiecode-10.8.5}/src/codeagent/walkthrough.py +0 -0
  58. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_adaptive_resilience.py +0 -0
  59. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_cli_ui.py +0 -0
  60. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_context_and_trajectory.py +0 -0
  61. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_dream_rsi.py +0 -0
  62. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_local_model_download.py +0 -0
  63. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_non_thinking_and_local_stream.py +0 -0
  64. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_project_templates.py +0 -0
  65. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_slash_and_diff.py +0 -0
  66. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_subagents.py +0 -0
  67. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_task_assessment.py +0 -0
  68. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_verifier.py +0 -0
  69. {alpiecode-10.8.2 → alpiecode-10.8.5}/test/test_walkthrough.py +0 -0
  70. {alpiecode-10.8.2 → alpiecode-10.8.5}/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.2
3
+ Version: 10.8.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.8.2"
7
+ version = "10.8.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.8.2
3
+ Version: 10.8.5
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -54,6 +54,7 @@ src/codeagent/backends/openai_backend.py
54
54
  test/test_adaptive_resilience.py
55
55
  test/test_cli_ui.py
56
56
  test/test_context_and_trajectory.py
57
+ test/test_deloop_and_sessions.py
57
58
  test/test_dream_rsi.py
58
59
  test/test_local_model_download.py
59
60
  test/test_non_thinking_and_local_stream.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.8.2"
20
+ __version__ = "10.8.5"
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
 
@@ -304,6 +308,8 @@ def run_agent(
304
308
  server_url: str = None,
305
309
  complexity: str = None,
306
310
  debug: bool = False,
311
+ resume_id: Optional[str] = None,
312
+ continue_session: bool = False,
307
313
  ) -> AgentRunResult:
308
314
  """Run non-interactive agent task with Rich presentation."""
309
315
  workdir = workdir.resolve()
@@ -337,7 +343,26 @@ def run_agent(
337
343
  backend = resolve_backend(cfg)
338
344
  orchestrator = AgentOrchestrator(backend)
339
345
  session_mgr = SessionManager()
340
- session = session_mgr.create_session(workdir, 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))
346
+ max_ctx = backend.context_window if hasattr(backend, 'context_window') and backend.context_window else (cfg.n_ctx if cfg.base_url == 'offline' else 262_144)
347
+
348
+ session = None
349
+ if continue_session:
350
+ sid = session_mgr.get_latest_session_id(workdir)
351
+ if sid:
352
+ session = session_mgr.load_session(sid, workdir, max_tokens=max_ctx)
353
+ if session and verbose:
354
+ console.print(f"🔄 [cyan]Continuing session[/cyan] [bold]{session.id}[/bold] ({len(session.context.messages)} prior messages)")
355
+ elif resume_id:
356
+ session = session_mgr.load_session(resume_id, workdir, max_tokens=max_ctx)
357
+ if session and verbose:
358
+ console.print(f"🔄 [cyan]Resumed session[/cyan] [bold]{session.id}[/bold] ({len(session.context.messages)} prior messages)")
359
+
360
+ if not session:
361
+ session = session_mgr.create_session(workdir, max_tokens=max_ctx, task_description=task)
362
+
363
+ from .session import setup_sigint_handler
364
+ setup_sigint_handler(session, session_mgr)
365
+
341
366
  event_stream = orchestrator.run_task(
342
367
  session=session,
343
368
  task=task,
@@ -544,10 +569,16 @@ def run_agent(
544
569
  sys.stdout.write("\n")
545
570
  sys.stdout.flush()
546
571
  has_streamed_tokens = False
547
- _print_tool_call(event.data["turn"], event.data["name"], event.data["arguments"])
548
- has_printed_anything = True
572
+
549
573
  tc_name = event.data.get("name", "")
550
574
  args = event.data.get("arguments", {})
575
+ is_deliverable_action = tc_name in ("write_file", "edit_file", "apply_patch", "download_asset")
576
+
577
+ # Professional presentation: Print deliverables / edits or in debug mode
578
+ if is_deliverable_action or debug:
579
+ _print_tool_call(event.data["turn"], event.data["name"], event.data["arguments"])
580
+ has_printed_anything = True
581
+
551
582
  if tc_name == "bash":
552
583
  cmd = args.get("command", "").strip()
553
584
  status_spinner.resume(f"Executing bash: {cmd[:60]}...", style="bold yellow")
@@ -557,13 +588,42 @@ def run_agent(
557
588
  elif tc_name in ("write_file", "edit_file"):
558
589
  p = args.get("path", "")
559
590
  status_spinner.resume(f"Saving {p}...", style="bold cyan")
591
+ elif tc_name == "download_asset":
592
+ k = args.get("category") or args.get("query") or ""
593
+ status_spinner.resume(f"Downloading asset '{k}'...", style="bold cyan")
560
594
  else:
561
595
  status_spinner.resume(f"Executing {tc_name}...", style="bold cyan")
562
596
 
563
597
  elif event.type == "tool_result":
564
598
  status_spinner.pause()
565
- if verbose:
566
- _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)
567
627
  _checkpoint(workdir, f"checkpoint: turn {event.data['turn']}")
568
628
  status_spinner.resume("Evaluating result & planning next step...", style="bold cyan")
569
629
 
@@ -619,23 +679,26 @@ def run_agent(
619
679
  style="dim"
620
680
  )
621
681
 
622
- elif event.type == "system1_intervention" and verbose:
623
- status_spinner.pause()
682
+ elif event.type == "system1_intervention":
624
683
  data = event.data
625
684
  action = data.get("action", "")
626
685
  err_type = data.get("error_type", "")
627
686
  directive = data.get("directive", "")
628
- if HAS_RICH:
629
- console.print(Panel(
630
- f"[bold yellow]⚡ System 1 (Jev) Intervention[/bold yellow] (Turn {data.get('turn')})\n"
631
- f"• Action: [cyan]{action}[/cyan] | Error Type: [red]{err_type}[/red]\n"
632
- f"• Directive: {directive}",
633
- border_style="yellow",
634
- padding=(0, 1)
635
- ))
687
+ if debug and verbose:
688
+ status_spinner.pause()
689
+ if HAS_RICH:
690
+ console.print(Panel(
691
+ f"[bold yellow]⚡ System 1 (Jev) Intervention[/bold yellow] (Turn {data.get('turn')})\n"
692
+ f"• Action: [cyan]{action}[/cyan] | Error Type: [red]{err_type}[/red]\n"
693
+ f"• Directive: {directive}",
694
+ border_style="yellow",
695
+ padding=(0, 1)
696
+ ))
697
+ else:
698
+ print(f"\n⚡ [System 1 Intervention] {action}: {directive}")
699
+ status_spinner.resume()
636
700
  else:
637
- print(f"\n⚡ [System 1 Intervention] {action}: {directive}")
638
- status_spinner.resume()
701
+ status_spinner.update(f"⚡ Jev ({err_type}): {directive[:60]}...", style="bold yellow")
639
702
 
640
703
  elif event.type == "metrics" and verbose:
641
704
  status_spinner.stop()
@@ -750,12 +813,24 @@ def run_agent(
750
813
  print(f"\n⚠️ Safety ceiling ({event.data['max_turns']}) reached.")
751
814
  finally:
752
815
  status_spinner.stop()
816
+ if "session_mgr" in locals() and "session" in locals() and session:
817
+ try:
818
+ session_mgr.save_session(session)
819
+ except Exception:
820
+ pass
753
821
 
754
822
  msgs = session.context.messages if "session" in locals() else []
755
823
  return AgentRunResult(msgs, success=task_success, outcome=task_outcome)
756
824
 
757
825
 
758
- def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = False) -> None:
826
+ def run_chat(
827
+ workdir: Path,
828
+ cfg: Config,
829
+ verbose: bool = True,
830
+ debug: bool = False,
831
+ resume_id: Optional[str] = None,
832
+ continue_session: bool = False,
833
+ ) -> None:
759
834
  """Run interactive chat session with Rich presentation."""
760
835
  workdir = workdir.resolve()
761
836
  _ensure_git(workdir)
@@ -763,7 +838,25 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
763
838
  backend = resolve_backend(cfg)
764
839
  orchestrator = AgentOrchestrator(backend)
765
840
  session_mgr = SessionManager()
766
- session = session_mgr.create_session(workdir, 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))
841
+ max_ctx = backend.context_window if hasattr(backend, 'context_window') and backend.context_window else (cfg.n_ctx if cfg.base_url == 'offline' else 262_144)
842
+
843
+ session = None
844
+ if continue_session:
845
+ sid = session_mgr.get_latest_session_id(workdir)
846
+ if sid:
847
+ session = session_mgr.load_session(sid, workdir, max_tokens=max_ctx)
848
+ if session and HAS_RICH:
849
+ console.print(f"🔄 Continuing session [bold cyan]{session.id}[/bold cyan] ({len(session.context.messages)} prior messages)")
850
+ elif resume_id:
851
+ session = session_mgr.load_session(resume_id, workdir, max_tokens=max_ctx)
852
+ if session and HAS_RICH:
853
+ console.print(f"🔄 Resumed session [bold cyan]{session.id}[/bold cyan] ({len(session.context.messages)} prior messages)")
854
+
855
+ if not session:
856
+ session = session_mgr.create_session(workdir, max_tokens=max_ctx, task_description="Interactive chat")
857
+
858
+ from .session import setup_sigint_handler
859
+ setup_sigint_handler(session, session_mgr)
767
860
 
768
861
  is_offline = (
769
862
  getattr(backend, "is_offline", False) is True
@@ -779,7 +872,7 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
779
872
  mode_line = f"🌐 Mode: [bold green]ONLINE[/bold green]\n🤖 Model: [bold cyan]{cur_model}[/bold cyan]" if not is_offline else f"🧠 Mode: [bold yellow]OFFLINE[/bold yellow]\n🤖 Model: [bold cyan]{cur_model} (Local GGUF)[/bold cyan]"
780
873
  console.print(
781
874
  Panel(
782
- f"[bold cyan]AlpieCode[/bold cyan] interactive mode\n"
875
+ f"[bold cyan]AlpieCode[/bold cyan] interactive mode (Session: [bold]{session.id}[/bold])\n"
783
876
  f"📂 Working in: [cyan]{workdir}[/cyan]\n"
784
877
  f"{mode_line}\n\n"
785
878
  "Type your request, or [bold red]exit[/bold red] / [bold red]quit[/bold red] to stop.",
@@ -788,7 +881,7 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
788
881
  )
789
882
  )
790
883
  else:
791
- console.print("\n💬 Chat Mode — type your request, or 'exit' to stop.")
884
+ console.print(f"\n💬 Chat Mode (Session: {session.id}) — type your request, or 'exit' to stop.")
792
885
  console.print(f"📂 Working in: {workdir}")
793
886
 
794
887
  while True:
@@ -798,7 +891,13 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
798
891
  else:
799
892
  user_input = input("\nYou ❯ ").strip()
800
893
  except (EOFError, KeyboardInterrupt):
801
- console.print("\nGoodbye! 👋")
894
+ session_mgr.save_session(session)
895
+ if HAS_RICH:
896
+ console.print(f"\nSession saved (id: [bold cyan]{session.id}[/bold cyan]). Resume with: [bold]alpiecode --continue[/bold]")
897
+ console.print("Goodbye! 👋")
898
+ else:
899
+ print(f"\nSession saved (id: {session.id}). Resume with: alpiecode --continue")
900
+ print("Goodbye! 👋")
802
901
  break
803
902
 
804
903
  if not user_input:
@@ -807,9 +906,16 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
807
906
  from .slash import handle_slash_command
808
907
  slash_res = handle_slash_command(user_input, session, orchestrator, cfg, console, has_rich=HAS_RICH)
809
908
  if slash_res is False:
810
- console.print("Goodbye! 👋")
909
+ session_mgr.save_session(session)
910
+ if HAS_RICH:
911
+ console.print(f"Session saved (id: [bold cyan]{session.id}[/bold cyan]). Resume with: [bold]alpiecode --continue[/bold]")
912
+ console.print("Goodbye! 👋")
913
+ else:
914
+ print(f"Session saved (id: {session.id}). Resume with: alpiecode --continue")
915
+ print("Goodbye! 👋")
811
916
  break
812
917
  elif slash_res is True:
918
+ session_mgr.save_session(session)
813
919
  continue
814
920
 
815
921
  has_streamed_chat = False
@@ -913,3 +1019,4 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
913
1019
  break
914
1020
  finally:
915
1021
  chat_status.stop()
1022
+ session_mgr.save_session(session)
@@ -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
  ],
@@ -109,6 +109,9 @@ def main():
109
109
  common.add_argument("--debug", action="store_true", help="Show autonomous discovery and debug diagnostics")
110
110
  common.add_argument("--offline", "--local", dest="offline", action="store_true", help="Run using local offline GGUF model on GPU without internet")
111
111
  common.add_argument("--ctx-size", type=int, default=None, help="Context size in tokens (default: 8192 offline, 262144 online)")
112
+ common.add_argument("--resume", dest="resume_id", default=None, help="Resume an existing session by ID or transcript path")
113
+ common.add_argument("--continue", dest="continue_session", action="store_true", help="Continue the most recent session in this project")
114
+ common.add_argument("--sessions", action="store_true", help="List saved conversation sessions")
112
115
 
113
116
  from . import __version__
114
117
  parser = argparse.ArgumentParser(
@@ -166,10 +169,28 @@ def main():
166
169
 
167
170
  args = parser.parse_args()
168
171
 
169
- if not args.command:
170
- parser.print_help()
172
+ if getattr(args, "sessions", False):
173
+ import time
174
+ from .session import SessionManager
175
+ sm = SessionManager()
176
+ saved = sm.list_saved_sessions(Path(args.workdir))
177
+ if not saved:
178
+ print("ℹ️ No saved sessions found.")
179
+ else:
180
+ print("\n📋 Saved AlpieCode Sessions:")
181
+ for s in saved[:10]:
182
+ sid = s.get("id")
183
+ updated = time.ctime(s.get("updated_at", 0))
184
+ msgs = s.get("message_count", 0)
185
+ task_desc = (s.get("task_description") or "Interactive chat")[:50]
186
+ print(f" • {sid} ({updated}) [{msgs} msgs] {task_desc}")
187
+ print("\nResume a session with: alpiecode --resume <session_id> or alpiecode --continue\n")
171
188
  return
172
189
 
190
+ if not args.command:
191
+ # Bare invocation (e.g. typing `alpiecode`): default directly to interactive conversation mode (like `agy` or `claude`)
192
+ args.command = "chat"
193
+
173
194
  if args.command == "version":
174
195
  print(f"alpiecode {__version__}")
175
196
  return
@@ -319,6 +340,8 @@ def main():
319
340
  url=getattr(args, "url", None),
320
341
  github_repo=getattr(args, "github", None),
321
342
  debug=getattr(args, "debug", False),
343
+ resume_id=getattr(args, "resume_id", None),
344
+ continue_session=getattr(args, "continue_session", False),
322
345
  )
323
346
  if not result:
324
347
  sys.exit(1)
@@ -328,7 +351,13 @@ def main():
328
351
  cfg.max_turns = args.max_turns
329
352
  _show_banner()
330
353
  from .agent import run_chat
331
- run_chat(Path(args.workdir), cfg, verbose=not args.quiet, debug=getattr(args, 'debug', False))
354
+ run_chat(
355
+ Path(args.workdir), cfg,
356
+ verbose=not args.quiet,
357
+ debug=getattr(args, 'debug', False),
358
+ resume_id=getattr(args, "resume_id", None),
359
+ continue_session=getattr(args, "continue_session", False),
360
+ )
332
361
 
333
362
  elif args.command == "plan":
334
363
  plan_task = (
@@ -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
@@ -439,15 +439,18 @@ class ToolExecutor:
439
439
  # Repetitive verification sequence guard
440
440
  if tc.name == "bash":
441
441
  cmd_str = safe_args.get("command", "").strip()
442
- if cmd_str and cmd_str in self.successful_bash_commands:
443
- res_str += (
444
- "\n\n⚠️ REPETITIVE VERIFICATION NOTICE: This exact command has already run and passed with exit code 0, "
445
- "and no files have been modified since. Re-running identical tests is unnecessary. "
446
- "All checks have already passed! Finalize the task now with: DONE: <summary>."
442
+ norm_cmd = re.sub(r"\s*\|\s*(?:head|tail|grep|sed|less|cat)\b.*", "", cmd_str)
443
+ norm_cmd = re.sub(r"\s*2>&1\s*", " ", norm_cmd).strip()
444
+ if norm_cmd and norm_cmd in self.successful_bash_commands:
445
+ res_str = (
446
+ "{\"stdout\": \"Check already verified with exit code 0. Deliverables ready.\", \"stderr\": \"\", \"exit_code\": 0}"
447
+ "\n\n🛑 CIRCUIT BREAKER TRIGGERED: This verification check has already passed with exit code 0, "
448
+ "and no files have been modified since. Stop running redundant inspection commands. "
449
+ "Finalize the task now with: DONE: <summary>."
447
450
  )
448
451
  elif '"exit_code": 0' in res_str:
449
- if cmd_str:
450
- self.successful_bash_commands.add(cmd_str)
452
+ if norm_cmd:
453
+ self.successful_bash_commands.add(norm_cmd)
451
454
 
452
455
  # Smart error hint injection for failed bash commands
453
456
  if tc.name == "bash" and '"exit_code"' in res_str:
@@ -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(
@@ -337,6 +337,19 @@ class AgentOrchestrator:
337
337
  if pre_read_ctx:
338
338
  effective_task = rephrased_task + "\n\n" + pre_read_ctx
339
339
 
340
+ # Prepend explicit positional blueprint directive so Turn 1 adheres to the target architecture
341
+ bp = getattr(task_context, "blueprint", None)
342
+ if bp:
343
+ bp_directive = (
344
+ f"[ARCHITECTURE DIRECTIVE: {bp.name.upper()}]\n"
345
+ f"- Required Deliverables: {', '.join(bp.target_files)}\n"
346
+ f"- Primary Entry Point: {bp.entry_point}\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
+ f"- Step 2: Implement styling and components sequentially.\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
+ )
351
+ effective_task = bp_directive + effective_task
352
+
340
353
  user_content = self.prompt_builder.build_user_content(
341
354
  task=effective_task,
342
355
  image_path=image_path,
@@ -488,12 +501,24 @@ class AgentOrchestrator:
488
501
 
489
502
  yield AgentEvent("turn_start", {"turn": turn, "thinking": turn_enable_thinking})
490
503
 
491
- # In offline mode, guide the model with current workspace progress
492
- if is_offline and session_touched_files:
504
+ # Guide the model with workspace progress and DOM element contract
505
+ if session_touched_files:
493
506
  file_list = ", ".join(sorted(list(session_touched_files)))
494
507
  state_hint = f"[Workspace State: Files created so far: {file_list}. Do NOT re-create these files. Proceed with remaining files or tests.]"
508
+
509
+ # If index.html exists but JavaScript hasn't been written yet, inject the exact declared DOM ID contract
510
+ html_p = session.workdir / "index.html"
511
+ if html_p.exists() and not any(f.endswith(".js") for f in session_touched_files):
512
+ try:
513
+ html_txt = html_p.read_text(encoding="utf-8", errors="replace")
514
+ d_ids = sorted(list(set(re.findall(r'id=["\']([a-zA-Z0-9_\-]+)["\']', html_txt))))
515
+ if d_ids:
516
+ state_hint += f"\n[DOM Schema Contract: 'index.html' defines declared element IDs: {', '.join(d_ids[:25])}. In client scripts, query ONLY these declared IDs.]"
517
+ except Exception:
518
+ pass
519
+
495
520
  last_msgs = session.context.messages
496
- if last_msgs and not any(state_hint in str(m.get("content", "")) for m in last_msgs[-2:]):
521
+ if last_msgs and not any("[Workspace State:" in str(m.get("content", "")) for m in last_msgs[-2:]):
497
522
  session.context.add_user_message(state_hint)
498
523
 
499
524
  try:
@@ -812,7 +837,7 @@ class AgentOrchestrator:
812
837
 
813
838
  if not v_res.passed:
814
839
  session._auto_verify_attempts = verify_attempts + 1
815
- if session._auto_verify_attempts < 2:
840
+ if session._auto_verify_attempts < 3:
816
841
  replan_prompt = format_replan_directive(v_res, is_offline=is_offline)
817
842
  session.context.add_user_message(replan_prompt)
818
843
 
@@ -921,6 +946,37 @@ class AgentOrchestrator:
921
946
  "confidence": decision.confidence,
922
947
  })
923
948
 
949
+ # ── Hard Circuit Breaker: Auto-verify and fast-forward to finish if inspection loop detected ──
950
+ if decision.action == ActionCategory.SKIP_LLM_FINISH:
951
+ from .verifier import IntelligentVerificationEngine
952
+ v_engine = IntelligentVerificationEngine(session.workdir)
953
+ v_res = v_engine.run_full_verification(
954
+ task=task,
955
+ session_touched_files=session_touched_files,
956
+ task_context=task_context,
957
+ run_bash_fn=session.executor.dispatch.get("bash", lambda a: ""),
958
+ is_offline=is_offline,
959
+ successful_commands=getattr(session.executor, "successful_bash_commands", None),
960
+ )
961
+ if v_res.passed:
962
+ task_metrics.finish()
963
+ yield AgentEvent("metrics", task_metrics.summary())
964
+ _ensure_trajectory_saved("success")
965
+ extract_and_save_memories(session.workdir, getattr(session.context, 'all_messages', session.context.messages))
966
+ _sync_project_memory_and_traces(
967
+ session.workdir, task, "Task deliverables completed and verified.", session_touched_files, session_executed_commands, task_metrics, turn
968
+ )
969
+ if any(f.endswith(".html") for f in session_touched_files) or (session.workdir / "index.html").exists():
970
+ yield AgentEvent("web_preview", {
971
+ "html_path": str((session.workdir / "index.html").resolve()),
972
+ "port": 8000,
973
+ })
974
+ yield AgentEvent("done", {
975
+ "summary": f"All deliverables verified successfully: {', '.join(sorted(list(session_touched_files))) if session_touched_files else 'complete'}.",
976
+ "success": True,
977
+ })
978
+ return
979
+
924
980
  # Track touched files and commands for walkthrough
925
981
  for tc in tool_calls:
926
982
  tc_args = tc.arguments if isinstance(tc.arguments, dict) else {}