Files
chungyeong 17ba5d723b feat(my-deepagent): v0.1.0 Step 0~5 — scaffolding through deepagent + OpenRouter
Python rewrite of the agent harness on top of deepagents 0.6.1 + langchain 1.x,
replacing the abandoned TS attempt in packages/. 388 unit/integration tests pass.

Steps
-----
0. Scaffolding — uv workspace, ruff/mypy/pre-commit/alembic, src/tests/docs
   trees with docs/schemas/ seeded from my-deepagent-seed/.
1. Core — config (pydantic-settings with MYDEEPAGENT_ env prefix and TOML
   source), enums (Backend, Capability, RiskLevel, ApprovalDecisionAction,
   ApprovalState, RunState, RunPhaseState, SessionState, ErrorClass),
   errors (MyDeepAgentError + BudgetExhaustedError with PEP-3134 cause +
   context suppression), hash (canonical JSON + sha256).
2. Persona/Workflow/Binding — pydantic v2 schemas with tuple-based deep
   immutability (post-construction hash drift prevented), YAML loaders,
   deterministic auto-select (preferred_backends → version → name → hash),
   override resolution with ineligibility diagnostics, PersonaConsentStore
   with fcntl.flock + tmp+fsync+rename atomic write.
3. Artifact schema registry — Draft202012Validator, multi-root resolution,
   structured ValidationFinding output.
4. Persistence — 18 SQLAlchemy 2.0 async ORM models with FK CASCADE/RESTRICT,
   WAL + busy_timeout + foreign_keys PRAGMA, alembic baseline +
   ux_active_run_repo_base partial unique index, LangGraph SqliteSaver as
   context manager only (lifecycle safety).
5. DeepAgent session — build_agent wires Persona → create_deep_agent with
   LocalShellBackend / FilesystemBackend / StateBackend / CompositeBackend,
   ChatOpenAI(base_url=openrouter) for openrouter: model strings, and 4
   middleware classes (cost / audit-tool / safety-shell / fallback-model).

Critical workarounds
--------------------
- deepagents 0.6.1 rejects FilesystemPermission together with backends that
  implement SandboxBackendProtocol (LocalShellBackend). SafetyShellMiddleware
  enforces destructive-command and secret-path policy at the tool layer
  instead, and build_agent strips the permissions kwarg when the persona's
  deepagents_backend is local_shell.
- FilesystemOperation in deepagents is Literal['read', 'write'] only;
  _map_operations collapses our richer schema (read/write/edit/ls) safely.

Real OpenRouter smoke
---------------------
test_openrouter_deepagents_local_shell_smoke calls DeepSeek via deepagents +
LocalShellBackend + SafetyShellMiddleware end-to-end. PASS, ~$0.000001 cost,
input=9 / output=1 tokens with content "OK".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:40:02 +09:00

122 lines
3.0 KiB
Python

"""Unit tests for src/my_deepagent/hash.py."""
import re
import pytest
from my_deepagent.hash import canonicalize, sha256
# ---------------------------------------------------------------------------
# canonicalize: key ordering
# ---------------------------------------------------------------------------
def test_canonicalize_sorts_keys() -> None:
assert canonicalize({"b": 1, "a": 2}) == '{"a":2,"b":1}'
def test_canonicalize_nested_sorts_keys() -> None:
result = canonicalize({"x": {"b": 2, "a": 1}})
assert result == '{"x":{"a":1,"b":2}}'
def test_canonicalize_empty_dict() -> None:
assert canonicalize({}) == "{}"
def test_canonicalize_empty_list() -> None:
assert canonicalize([]) == "[]"
def test_canonicalize_none() -> None:
assert canonicalize(None) == "null"
def test_canonicalize_integer() -> None:
assert canonicalize(42) == "42"
def test_canonicalize_float() -> None:
# 0.1 has a known floating-point representation
result = canonicalize(0.1)
assert result == "0.1"
def test_canonicalize_no_whitespace() -> None:
result = canonicalize({"a": 1, "b": 2})
assert " " not in result
def test_canonicalize_list_preserves_order() -> None:
# Lists should not be reordered
assert canonicalize([3, 1, 2]) == "[3,1,2]"
def test_canonicalize_string_value() -> None:
assert canonicalize("hello") == '"hello"'
def test_canonicalize_boolean() -> None:
assert canonicalize(True) == "true"
assert canonicalize(False) == "false"
def test_canonicalize_nan_raises() -> None:
import math
with pytest.raises(ValueError):
canonicalize(math.nan)
# ---------------------------------------------------------------------------
# sha256: determinism
# ---------------------------------------------------------------------------
def test_sha256_deterministic() -> None:
value = {"a": 1, "b": [1, 2, 3]}
results = [sha256(value) for _ in range(100)]
assert len(set(results)) == 1
def test_sha256_returns_64_char_hex() -> None:
result = sha256({"a": 1})
assert re.fullmatch(r"[0-9a-f]{64}", result) is not None
def test_sha256_different_inputs_different_hash() -> None:
h1 = sha256({"a": 1})
h2 = sha256({"a": 2})
assert h1 != h2
def test_sha256_key_order_irrelevant() -> None:
# Same content, different insertion order → same hash
h1 = sha256({"a": 1, "b": 2})
h2 = sha256({"b": 2, "a": 1})
assert h1 == h2
def test_sha256_empty_dict() -> None:
result = sha256({})
assert re.fullmatch(r"[0-9a-f]{64}", result) is not None
def test_sha256_none() -> None:
result = sha256(None)
assert re.fullmatch(r"[0-9a-f]{64}", result) is not None
def test_sha256_nested() -> None:
h1 = sha256({"x": {"a": 1, "b": 2}})
h2 = sha256({"x": {"b": 2, "a": 1}})
assert h1 == h2
def test_sha256_known_value() -> None:
# Pre-computed: sha256('{"a":1}') in UTF-8
import hashlib
expected = hashlib.sha256(b'{"a":1}').hexdigest()
assert sha256({"a": 1}) == expected