Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/regression.yml
Original file line number Diff line number Diff line change
@@ -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
7 changes: 7 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Changelog

## [Unreleased]

- [修复] CLI 不再重复注入当前用户消息,日志不再输出 API Key 前缀。
- [改进] 默认 CLI 工具限制为 Coding Tools;原有基础工具保持显式可用。
- [文档] 记录六阶段迁移、权限边界和可复现源码统计。
34 changes: 34 additions & 0 deletions docs/lean-harness.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 1 addition & 2 deletions miniagent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Expand Down Expand Up @@ -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

Expand Down
5 changes: 2 additions & 3 deletions miniagent/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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] = []
Expand Down
2 changes: 1 addition & 1 deletion miniagent/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
15 changes: 15 additions & 0 deletions scripts/source_stats.py
Original file line number Diff line number Diff line change
@@ -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))
22 changes: 22 additions & 0 deletions tests/test_cli_baseline.py
Original file line number Diff line number Diff line change
@@ -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)
5 changes: 3 additions & 2 deletions tests/test_code_tools.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()

Expand Down
Loading