diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml new file mode 100644 index 0000000..7e4d9c3 --- /dev/null +++ b/.github/workflows/regression.yml @@ -0,0 +1,24 @@ +name: Stacked PR Regression +on: + pull_request: + workflow_dispatch: +permissions: + contents: read +jobs: + regression: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python: ['3.11', '3.12'] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Install this stage and available extras + run: python -m pip install -e ".[mcp,legacy]" "pytest>=9.0.3,<10" + - run: python -m pytest tests -q -m "not live" + - run: python -m compileall -q miniagent + - run: python scripts/source_stats.py diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 0000000..7407cd7 --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## [Unreleased] + +- [修复] CLI 不再重复注入当前用户消息,日志不再输出 API Key 前缀。 +- [改进] 默认 CLI 工具限制为 Coding Tools;原有基础工具保持显式可用。 +- [文档] 记录六阶段迁移、权限边界和可复现源码统计。 diff --git a/docs/lean-harness.md b/docs/lean-harness.md new file mode 100644 index 0000000..823c4b2 --- /dev/null +++ b/docs/lean-harness.md @@ -0,0 +1,34 @@ +# Lean Harness implementation + +Six stacked PRs: baseline and targeted fixes; async runtime and policy; +any-llm; durable sessions; Skills and official MCP; CLI and release checks. +Each PR targets its predecessor. Merge in order; revert in reverse order. + +## Contracts + +The runtime is async; use `await app.arun()` in an existing event loop. +`app.run()` is a script convenience. One task per Harness/Session at a time. +Plugins change only while idle. Startup dependency sorting, rollback and +reverse cleanup are supported; automatic dependency recovery is deferred. +Tools pass through one validation/authorization entry point. + +Python plugins and MCP servers are trusted software. Workspace checks cover +managed file tools, not arbitrary shell execution. Shell/MCP require explicit +authorization; this is not a sandbox. Noninteractive approval defaults to deny. +Provider keys are isolated. Tool arguments and key prefixes must not be logged. + +Sessions preserve original events and do not replay uncertain side effects. +Compaction changes only the model view. Dynamic plugins, Subagent and long-term +Memory are deferred. Source line counts are observations, not release gates. + +## Validation + +Run `python -m pytest tests -q` and `python scripts/source_stats.py`. +Real-provider smoke tests are opt-in and must report provider/model/SDK version; +mock tests do not establish live compatibility. No provider credential is +required for deterministic regression tests. + +Windows baseline: 189 passed, 2 failures caused by Unix-only `sleep` in timeout +tests. Those tests now invoke the running Python interpreter on every platform. +Original commit `4d61483d039e802f6d34fb6b42d6e2a99b1b6a1c`: 20 files, +4,009 physical lines, 3,288 nonempty lines. diff --git a/miniagent/agent.py b/miniagent/agent.py index 8948cce..ae18e48 100644 --- a/miniagent/agent.py +++ b/miniagent/agent.py @@ -442,7 +442,6 @@ def _call_llm(self, messages: List[Dict[str, str]]) -> str: if not self.api_key: raise ValueError("API key is not set. Please check your environment variables.") - logger.debug(f"Calling LLM with API key: {self.api_key[:6]}...") logger.debug(f"Base URL: {self.base_url or 'default OpenAI'}") logger.debug(f"Model: {self.model}") @@ -649,7 +648,7 @@ def _safe_execute_tool(self, tool_call, tool_callback, status_callback, limit): if status_callback: status_callback(f"Executing tool: {tool_call['name']}...") - logger.info(f"Executing tool: {tool_call['name']} with args: {tool_call['arguments']}") + logger.info(f"Executing tool: {tool_call['name']}") result = self._execute_tool(tool_call, tool_callback=tool_callback) return smart_truncate(str(result), limit), False diff --git a/miniagent/cli.py b/miniagent/cli.py index 4f84555..5fb17ac 100644 --- a/miniagent/cli.py +++ b/miniagent/cli.py @@ -199,7 +199,7 @@ def _confirm_dangerous(cmd: str) -> bool: # Load some default tools if configured, else fall back to all currently registered. agent.tools = [] - tools = cfg.default_tools or agent.get_available_tools() + tools = cfg.default_tools or ["read", "write", "edit", "grep", "glob", "bash"] for tool_name in tools: agent.load_builtin_tool(tool_name) @@ -292,10 +292,9 @@ def main(argv: Optional[List[str]] = None) -> int: console.print(f" [cyan]{t['name']:<18}[/cyan] {desc}") continue + query = _format_history(history) + user_text history.append({"role": "user", "content": user_text}) memory.push("user", user_text) - - query = _format_history(history) + user_text # Prepare streaming callback _stream_chunks: List[str] = [] diff --git a/miniagent/tools/__init__.py b/miniagent/tools/__init__.py index ff56ee5..4c2d6ce 100644 --- a/miniagent/tools/__init__.py +++ b/miniagent/tools/__init__.py @@ -82,7 +82,7 @@ def execute_tool(name: str, **kwargs) -> Any: Returns: Result of the tool execution """ - logger.info(f"Executing tool: {name} with arguments: {kwargs}") + logger.info(f"Executing tool: {name}") tool = get_tool(name) if not tool: diff --git a/scripts/source_stats.py b/scripts/source_stats.py new file mode 100644 index 0000000..73d5175 --- /dev/null +++ b/scripts/source_stats.py @@ -0,0 +1,15 @@ +"""Reproducible physical/nonempty source counts (no trailing phantom line).""" +import json +import subprocess +from pathlib import Path + +root = Path(__file__).resolve().parents[1] +files = sorted((root / "miniagent").rglob("*.py")) +counts = {str(p.relative_to(root)): p.read_text(encoding="utf-8").splitlines() for p in files} +print(json.dumps({ + "commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip(), + "files": len(files), + "physical": sum(len(lines) for lines in counts.values()), + "nonempty": sum(bool(line.strip()) for lines in counts.values() for line in lines), + "per_file": {name: len(lines) for name, lines in counts.items()}, +}, indent=2)) diff --git a/tests/test_cli_baseline.py b/tests/test_cli_baseline.py new file mode 100644 index 0000000..cd71c5f --- /dev/null +++ b/tests/test_cli_baseline.py @@ -0,0 +1,22 @@ +from unittest.mock import Mock + +from miniagent import cli + + +def test_current_user_is_not_duplicated(monkeypatch): + agent, memory = Mock(), Mock() + agent.model, agent.tools = "test", [] + agent.run_with_tools.return_value = "done" + monkeypatch.setattr(cli, "_build_agent", lambda args: (agent, memory)) + entries = iter(["unique current request", "/q"]) + monkeypatch.setattr(cli.Prompt, "ask", lambda *a, **k: next(entries)) + monkeypatch.setenv("MINIAGENT_STREAM", "0") + assert cli.main([]) == 0 + query = agent.run_with_tools.call_args.args[0] + assert query.count("unique current request") == 1 + + +def test_key_prefix_is_not_logged(): + import inspect + from miniagent.agent import MiniAgent + assert "api_key[:" not in inspect.getsource(MiniAgent._call_llm) diff --git a/tests/test_code_tools.py b/tests/test_code_tools.py index ccef381..4f995f0 100644 --- a/tests/test_code_tools.py +++ b/tests/test_code_tools.py @@ -1,6 +1,7 @@ """Tests for code_tools (read/write/edit/grep/glob/bash).""" import os +import sys import pytest from miniagent.tools.code_tools import read, write, edit, grep, glob, bash from miniagent.utils.text_utils import smart_truncate @@ -86,14 +87,14 @@ def test_failing_command(self, tmp_workspace): assert result["exit_code"] != 0 def test_timeout(self, tmp_workspace): - result = bash("sleep 10", timeout=1) + result = bash(f'"{sys.executable}" -c "import time; time.sleep(10)"', timeout=1) assert result["exit_code"] == 1 assert "timed out" in result["stderr"].lower() def test_bash_timeout_from_env(self, tmp_workspace, monkeypatch): """bash() with timeout=0 should read BASH_TIMEOUT env var.""" monkeypatch.setenv("BASH_TIMEOUT", "1") - result = bash("sleep 10", timeout=0) + result = bash(f'"{sys.executable}" -c "import time; time.sleep(10)"', timeout=0) assert result["exit_code"] == 1 assert "timed out" in result["stderr"].lower()