Testing¶
Tests live in tests/ and use the stdlib unittest framework, with no external runner, no network, and no API key. Mock tests patch provider responses so the agent loop, engine, CLI, and server are exercised without a real model.
Running tests¶
Run all tests:
python -m unittest discover tests
The canonical setup installs the package (pip install -e .), which is also what CI does. CI runs the suite on Python 3.11, 3.12, 3.13, and 3.14 with fail-fast: false. On a source checkout without installing, use PYTHONPATH=$PWD/src (absolute, because the detached-fleet daemon changes directory, so a relative src would not resolve). PluginManager then falls back to the repo-root plugins/ directory for the bundled plugins.
Run a single file:
python -m unittest tests.test_tool_calling
Run tests before committing changes to verify core logic isn't broken.
Static checks¶
The runtime stays stdlib only. Linting, type checking, and coverage are development tooling, installed through the dev extra and never imported by the package:
pip install -e ".[dev]"
ruff check src plugins tests
mypy src/polyglav/config.py src/polyglav/tool_log.py src/polyglav/tools/policy.py \
src/polyglav/sessions/private.py src/polyglav/sessions/manager.py
coverage run --source=src/polyglav -m unittest discover tests && coverage report
CI runs all four. The ruff selection is deliberately narrow (E9, F63, F7, F82), so it fails on syntax errors and undefined or unused names rather than on style. The type check runs over a fixed allowlist of clean modules and widens as modules are cleaned, with src/polyglav/engine.py as the target. Coverage is reported without a threshold until the baseline is known.
Test coverage¶
| File | Covers |
|---|---|
test_agent_loop.py |
Agent-loop behavior: single round trip, thinking persistence, graceful error bail, empty/truncated-stream multi-attempt retry, recovery hint after failed tool-call rounds, truncation error messages (configured cap vs provider default), auto-continue on truncation (stitch + cap + continue instruction), reasoning-only turn not flagged empty, empty-done retried, KeyboardInterrupt cancels the turn (mid-stream and after a tool call) with partial output persisted, unknown-tool results list available tools |
test_auto_compact.py |
Automatic compaction: absolute and relative compact_at, model-entry and config context windows, ambiguous 1.0, disabled limit, headroom projection, turn history, trigger after a tool round, failed summary not retried, intra-turn round boundary, automatic record telemetry |
test_ask.py |
ask tool (core): schema/registration (category ask, permission ask, key_arg question, tool_permission.ask default allow), user answer / empty-cancelled / context+options rendering, no-channel error (headless), direction routing (always the user, with caller/auto accepted as user for one version), the clarity guard (a short question with no context or options is rejected), ask options rendering (numbered block, > prompt, number/letter/free-text selection), permission-request routing (prompts the root, a read-mode catalog ask offers a mode switch), sub-engine _ask_ui inheritance, full-loop ask -> answer tool part -> continue |
test_bundled_plugins.py |
Bundled plugin discovery, tool registration, search/mcp_server/report service, bundled update/uninstall blocking, default-config plugin set, provider registration via the hook |
test_cli.py |
polyglav run: JSON/text output, exit codes, one-shot overrides applied but never persisted, _engine_from_args approval wiring (explicit --model auto-approves, --approve-model grants, default does not). polyglav plugins: list/install/uninstall, enable/disable plugins-list toggle + unknown name, main dispatch. Model, eval, export, and import CLI coverage lives in each plugin suite, including polyglav models context |
test_commands.py |
Slash-command registration and /help output (aliases, subcommands, tools listed under the tools section, mode-filtered listings), /modes list, --verbose descriptions, and <name> instruction, /connect provider flow (interactive picker list/number/URL/bad number/stored-custom reconnect, named connect preset defaults + probe args, hidden stored-key keep/re-enter, unknown-name error, URL known-host + plugin default-URL match + custom name derivation + [name] override + bare hostname, probe-before-commit decline/accept, config model untouched), /model show/switch-touch (provider/model ref unfold and immediate explicit approval), /context and /status token reporting, /session token context, /thinking scopes, /config listing (compact, key detail, --verbose) and scope flags (--global/--local, -a/-r scope), /models configured listing and list probe (key marker sourced from providers.json, provider filter, error/empty, configured-model note), /provider warn |
test_completion.py |
Readline tab completion: commands, session names, plugin names, tool names |
test_config.py |
Config scopes: local-only saves, --global writes, apply() in-memory overrides (never written), unset fallback/origin, global>local merge, empty-local-does-not-shadow-global, polyglav config CLI (get/set/unset/reload, JSON values, show-origin) Verbosity defaults and migration are covered in test_verbosity.py |
test_cost.py |
Cost model: rate normalization, input/output/cache token parts, cached-price calculation, and provider/model > provider > default rate precedence |
test_call.py |
call tool: role allow default (no prompt) / ask confirm grant-decline / unknown-role deny, verbosity.output display, streamed sub-run suppression of the duplicate echo, direct call tool single print, empty-content log-summary fallback, sub-agent session persistence + resolver actions |
test_catalog.py |
catalog tool: registration + default allow, read/write action gating, list/show/save/remove/reload, sequential and hierarchical teams, callable role validation, skill file write, permission-key validation (valid keys pass, write/exec/search normalize to edit/bash/web, an unknown key is rejected with the valid list, true/false actions normalize to allow/deny, an invalid action is rejected, show flags unknown keys and invalid actions), validate action (role permission keys, team stage roles against the catalog, skill content), description lists the permission keys and team shapes |
test_delegation_permissions.py |
Permission ceiling + grants: clamp_action/resolve_permissions/resolve_grant_ceiling (including boolean action coercion), ToolPolicy one-shot/always grants + consume + category/tool matching, boolean action values (false denies, true allows), no-escalation (a role carve cannot widen above the caller's grant_permission), supervisor grants a category it cannot use itself, one-shot grants do not propagate to children, ask(kind='permission') routing (auto/user/deny, ceiling denial, the caller grants once only, the user grants once/always), ask(kind='direction') routing (a sub-agent defaults to the caller, ask_policy.direction user/caller), a category ask reaches every tool in the category while a tool ask stays scoped, granted tool appears then is consumed from the schema, audit entries |
test_engine.py |
Engine.chat turn result, thinking/content separation, load-or-create sessions, auto ses_<ts>_<id> naming (stable across turns), read-mode schema filtering, instruction injection, per-turn mode, glyph param suffix gating, ✗ error-line rendering (never hidden), soft-result note-line rendering at verbosity.tools, check_connection/list_models probe resolution and overrides without state mutation, _reinit_provider provider-registry API key resolution (no config fallback, registry custom base_url fallback when config empty), model-ref unfold + approval gate (unfolded provider/base_url/model, headless deny, approve_models grant, chat short-circuit, subrole-model unfold + gate, team-run pre-check deny) |
test_engine_observer.py |
Engine observer hooks: request start/end with context blocks, ctx tokens, timestamps, and agent fields, tool end with full output and result tokens, compaction events, deny_tools=['*'] schema filtering and refusal, context_snapshot, and sub-engine observer inheritance with role attribution |
polyglav-core-eval/tests/test_eval.py |
Eval harness: fixture model + loading, declarative verifier (exact/must_include/avoid/max_calls/min_calls/args), metric computation (accuracy, redundant, errors, tokens), fixture discovery + precedence (plugin/global/local), cwd isolation and restore, suite aggregation |
polyglav-core-fleet/tests/test_fleet.py |
Fleet supervisor: port allocation (preferred/bind-probe fallback/in-use skip/exhaustion), /health probe ok + failure, manifest/state round-trip + corrupt tolerance, spawn > health > crash > restart > down via sys.executable -c mock servers, max_restarts give-up, unhealthy-threshold restart, disabled gate, log files, env seams (POLYGLAV_FLEET_PORT), polyglav fleet CLI (init/add/remove/status/restart/config incl. role inline + unknown-role error), detached-daemon end-to-end (up --detach, status, down) |
test_history.py |
/history command: default last-10 / n / all listings by absolute turn index, header with total turns and role, line fields (status, duration, tool count, prompt), command-only turns, prompt first-line clip, --thoughts excerpt vs --thoughts all, session:<name> target resolution without changing the current session, unknown target and usage errors, empty-session cases |
test_http.py |
SSE streaming: data parsing, done marker, multi-byte split across chunks, HTTP errors, POST-preserving redirects (loopback server) |
test_jobs.py |
Job model + registry (round-trip incl. require_approval/task_file/approve_model/created_at, runnable + ready-to-run gates, corrupt file tolerance), cron parser (steps/ranges/lists/dom/dow/the restrictive day rule, leap day), next_run/compute_next_run/parse_dt, scheduler run/tick under a mocked engine (verified/failed, retries with backoff, per-attempt history, unknown role, one-shot at, approval gates, per-run require_approval park/re-arm, run memory write + injection, per-run session naming + collision dedupe + --session stability, run content capture), _build_engine role-skill injection (present/missing), task file template/linkage/missing-file failure, status/list/show rendering (incl. the last run: summary line), polyglav jobs CLI (add/approve/list, --file, edit, status output, stop, auto-approval, bad cron, duplicates, run exit codes + content printing), report-back dispatch (verified/failed/build-failure events, payload fields, injected service, no-service no-op, service-exception tolerance) |
test_memory.py |
Shared memory module: path under .polyglav/memory/<scope>/, read/write round-trip, missing-empty, legacy job/team fallback reads, memory_enabled global + per-scope, cap_memory truncation. Engine role memory: injection into the sub-agent system prompt, scope-disabled skip, write after run_subagent, disabled skip, Engine.memorize + /memorize command, team memory on the shared path |
test_metrics.py |
Metric runs: task model and execution settings (mode, temperature, system_prompt), permission preflight, discovery, evidence matching, content hashing, probe scoring, single and multi conditions, tool/edit/context records, per-round timestamps, per-agent round attribution and main/sub round counts, compaction events, cost aggregation, table output, and the list command |
test_models.py |
ModelRegistry (approved-model history in global models.json): path under GLOBAL_DIR, put/find by (provider, model), dedupe + last_used, distinct models keep separate entries, touch, remove, grouped, reload, corrupt-file tolerance, old per-model-key shape dropped without migration, GLOBAL_DIR default |
test_modes.py |
Mode resolution and policy merging: read/write, unknown fallback, instruction composition, access classification (read_tools, unknown-is-write, read cap), submitted-line color (teal read, orange write) |
test_delegate.py |
delegate tool: read-class registration, role-less sibling run + sub_* session, delegate_depth guard, and call rejecting a sibling target |
test_ollama_provider.py |
Streaming provider: fragmented tool-call reassembly, thinking events (reasoning_content and reasoning keys), payload construction. Lives in the polyglav-core-ollama plugin suite (see the bundled-plugin suites note below) |
test_plugins.py |
Plugin manager: manifest compat ranges, discovery precedence, registration hooks (tools/providers/commands/services/roles/teams/skills + hook-failure status), _bundled_dir fallback (source layout + forced import failure), install/update/uninstall, polyglav plugins test (+ load_plugin_test_suite) |
test_print.py |
/print command: whole-turn reprint with the full metadata block (empty fields as -, including a command turn), part-only <n>.<m>, out-of-range part, unknown turn, fixed print cap vs --full, session:<name> targets without changing the current session, unknown target and usage/invalid-spec errors |
test_provider_session.py |
Provider session binding: BaseProvider/OpenAICompatibleProvider store session_id (default empty), an owned provider is rebound to the run's session, a shared provider keeps its binding, a provider without session_id is skipped, and _current_session_id handles a missing session |
test_providers.py |
Core provider substrate: OpenAICompatibleProvider defaults/headers/endpoints, POST-preserving redirects, check_connection probe (success/empty/model note/HTTP/network), list_models silent-on-error, base reasoning payload, tool_call_delta progress, reasoning and content in one delta, host-pattern detect_provider (known hosts, longest-pattern precedence, empty/unknown fallback), core PROVIDERS registry (generic fallback only) and merged_providers (bundled providers included). Vendor provider defaults/endpoints/reasoning/headers live in the per-plugin suites (polyglav-core-ollama, -openai, -groq, -anthropic, -opencode) |
test_providers_registry.py |
ProviderRegistry (global providers.json): path under GLOBAL_DIR, put/find/dedupe per provider, empty key keeps existing, base_url stored only when given, key/base_url lookup, touch, 0600 when keyed, reload, corrupt-file tolerance, remove, GLOBAL_DIR default. resolve_model_ref: known/unknown provider, bare model, no-default provider, empty parts, plugin providers |
test_repl_output.py |
Golden REPL vocabulary: header, mode-colored live prompt, colored submitted-line reprint, wrapped input clearing, wide-character width, thinking, tool summary and hidden body, flat stage lines, ask block and indented context, warning and error colors |
test_repl_input.py |
REPL input: multi-line """/''' block detection, framing strip (pure, lead-in, indentation and trailing spaces preserved), blank lines kept inside a block, EOF exit during an open block, slash commands single-line, output log written only when enabled and rotated per session, plain text by default (no ANSI) with output_log_ansi keeping the colors, banner precedes startup hooks, mode-colored live prompt and NO_COLOR fallback, submitted-line reprint in the mode and command colors |
polyglav-core-bookkeeping/tests/test_plan_todo.py |
Plan and todo bookkeeping: plan_write creates plan_<ts>_<session_id>.md under plan.dir, attaches the path to the session, validates the required sections, appends revisions and honors replace, injects the bounded plan block, propagates the plan to sub-engines, round-trips the session plan field, and /plan and /plans show, attach, detach, and list plans. The todo tool adds, starts, completes, blocks, removes, lists, and shows items, updates .polyglav/todos/<session>.json, injects the current-work block, prints a note, and /todo and /todos show and edit lists |
test_verbosity.py |
Verbosity resolution, presets, scoped overrides, invalid fallbacks, old-key migration, and rendering for thinking and output scopes (off/assistant/agent/all), status, tools, and footer |
test_call_target.py |
Unified call target: role, sequential team, hierarchical team, old role param, unknown target denial, schema target/kind without sibling, and callable/call permission resolution per target |
test_composite_sessions.py |
Composite sessions: SessionManager.tree, /sessions list roots only, /history --tree, /print --tree, and --tree JSON export |
test_run_resume.py |
Run resume and context control: fresh sub_ sessions by default, resume by run id / session name / session id reuses the session and reactivates the run, unknown target raises, context='new' ignores resume, context='compact' summarizes first, team resume seeds the first stage, call/team tools forward resume/context, team field round-trip without warm_sessions/session_key |
test_runs.py |
RunRegistry: sequential ids, parent/children tree and creation-order call log, finish status set-once, duration and usage storage, rollup, task recording, unknown-run tolerance. Engine runs: root run registration, sub-engine shares the registry and links the parent, run_subagent finishes the child run, load_or_create_session updates the run session and session id |
polyglav-core-quality/tests/test_tools.py |
Optional lint/format wrappers: configured commands, failure output, missing cwd, metadata, aliases |
polyglav-core-storage-sqlite/tests/test_store.py |
SQLite session store: round-trip, delete, materialize |
polyglav-core-serve/tests/test_server.py |
polyglav serve HTTP API: /chat, /cancel, /sessions, /health, /version |
test_session_id.py |
Session id: session_id_hash determinism/length/base36, coded_session_name/session_id_from_name parsing (ses_/job_/sub_, explicit names ignored), Session.session_id stamping and round-trip, missing id loads empty, auto ses_<ts>_<id> naming and uniqueness, explicit names have no id, SessionManager.find_by_session_id hit/normalize/miss, RunRegistry.start(session_id=) + find_by_session_id, engine run/session id mirroring, load_or_create_session sync, id stable across turns, saved-session lookup |
test_session_import.py |
JSON session import: session_from_document from an export document and from a raw session dict, optional-field tolerance, non-document rejection, SessionManager.import_document name retention, explicit name, collision to a fresh ses_ name, explicit-collision error, force overwrite, no current-session switch |
test_session_io.py |
Session IO error log: a corrupt session file logs a read line with the name, a missing file and a legacy-format skip log nothing, a failed save logs a save line, and errors.log is not listed as a session |
test_session_log.py |
Session model: turn/part storage and the explicit turn/part API, turn index/status/metadata, per-turn usage/context_tokens/finish_reason telemetry, append-only serialization, tool-part summary and ref persistence and sidecar deletion, tool-part call_id/duration, errors/permissions round-trip, session_id field round-trip, write_summary file, files without the current format do not load (and stay listed), compaction boundary and provider reconstruction (with the standalone summary file), agent-loop turn persistence (thinking, tool parts, analysis, stop reason, call id) |
test_session_metadata.py |
Derived session metadata: title (first user prompt collapsed, clipped to 60, empty for a command-only session), outcome (ok, error when any turn failed), idle_at (last ended turn, updated_at fallback), and that none of the three are stored in to_dict |
test_session_render.py |
Session Markdown export: header metadata (created, updated, id, role, mode, version, turns, outcome, empty-as--), turn/part renderer (user, assistant, thinking, tool call arguments + result + analysis, command + compaction, system), error section, /sessions export dispatch (Markdown and --json, file/stdout targets). Also the terminal turn_summary (line fields, tool count, prompt clip, command turn, dim thinking excerpt vs full all) and render_turn (metadata block incl. empty-as--, all part types, tool duration and tokens, tool error + analysis, compaction, part selection, cap vs --full), plus turn token totals |
test_skills.py |
SkillRegistry: local/global dir scans, plugin/global/local merge and precedence, origins, put/remove round-trip, reload (disk re-read + plugin-manager re-apply), skills_section, /skills command (list/show/new override/remove, plugin remove rejected) |
test_tool_log.py |
Session tool log: append and line-range refs, summaries, engine refs, tool_output_log off, auto-save summary, /print resolution, and sidecar deletion |
test_subagent.py |
In-process sub-engine: provider/plugin/worktree inheritance, caller-mode inheritance, role prompt/tool_permission application, role-skill system-prompt injection (present/missing/empty/no-skills), model override, NullUI when hidden and SubRunUI output scopes, unknown role, full run_subagent flow + persisted sub_* session with parent_id, ask-gated tool cancellation, parent sub_sessions linkage |
test_team_run.py |
Engine.run_team: brief builder (task + prior results + handoff + memory + task hint, prior-result truncation), sequential stage execution with per-stage sub_* sessions + parent linkage + exact brief persistence, hierarchical manager-only execution with member roster, stage mode inheritance, stop-on-failure, unknown-stage-role stop, zero stages, rolling team-memory write (summarized + prior-seeded + fallback), /teams run command output (stages + final result, unknown team, usage) |
test_team_loop.py |
Team review loop: _review_passed (VERDICT: prefix and a full VERDICT: PASS marker, case-insensitive, custom marker), _team_loop_plan (name/index resolution, invalid from/until), pass on first iteration, changes-then-pass iteration with the prior review in the producer brief, a full verdict marker stopping on the first pass, cap reached without pass, pre/post-loop stages run once, stage error stops the loop, loop round-trip |
test_teams.py |
TeamRegistry: bundled/plugin/global/local merge and precedence, origins, type default and hierarchical round-trip (manager, members), stage round-trip (dict + short-string forms), put/remove, reload (disk re-read + plugin-manager re-apply), /teams command (list/show/new override/remove, list <tag> filter, bundled remove rejected) |
test_tool_calling.py |
Tool-calling flow: single and multiple calls, unknown tools, query refinement |
test_tool_policy.py |
ToolPolicy: allow/ask/deny, worktree escalation, deny/allowlist precedence, per-invocation resolver (refines non-deny base, skipped without args, cannot override deny list), read-mode cap (listed key allowed, unlisted/unknown denied, deny beats grant) |
test_tool_registry.py |
Tool registration metadata, schema, refine flags, note-result predicates, _config pass-through, activity params strings with oversized and multiline arguments omitted, fs tool glyphs (* List / * Grep), permission_fn storage + resolver_for, write_actions storage + write_action_keys |
test_turns.py |
Turn model (src/polyglav/sessions/turns.py): turn/part shape and builders for the six part types, finish_turn/finish_tool, tool co-location, provider reconstruction (a turn's text plus consecutive tool parts grouped into one assistant tool_calls message followed by its tool results, thinking attached to the answer or tool round, reasoning-only turns, command parts dropped, system passthrough, deterministic tool-call ids, JSON-serialized arguments), and compaction/provider_messages (summary plus turn-index boundary) |
test_roles.py |
RoleRegistry: bundled/plugin/global/local merge and precedence, origins (bundled/plugin/local/global origin), tags roundtrip + merge, put/remove/reload (disk re-read + plugin-manager re-apply), /roles command (list/show/new override/remove, list <tag> filter, bundled remove rejected) |
test_role_files.py |
Markdown role instructions: frontmatter parsing (present/absent), file body as system_prompt, JSON system_prompt wins over the file, frontmatter fills missing fields, JSON wins frontmatter, explicit instructions reference, path traversal ignored, put writes a short index + Markdown, a second save does not leak the prompt into the index, editing the Markdown after two saves takes effect on reload, remove deletes the Markdown |
test_ui.py |
UI sinks: glyph activity lines, bright-blue call and delegate lines, tool summary/hidden body with oversized params omitted, status oneliner fallback, headless verbose rendering, ✗ tool-error lines, word-streaming buffering (boundary flush, tail flush, off-mode immediate writes, markdown across boundaries, flush before status/confirm), thinking spinner and ✓ Thought, flat ↳ Call/✓ Worked status, single-key confirm with Enter default and a silent decline, hidden confirm input, secret masked input, core-rendered VERDICT: hiding with model stream preserved, ask numbered block and > prompt, number/letter/free-text selection, origin prefix, ask prompt layout (question on its own line, context before options), and verbosity levels, live status metrics, tool round tokens, and scoped output |
tests/helpers.py provides make_chat(config_data), a ChatLoop with a mocked provider, used by most tests to drive the engine without a model.
Plugin test suites¶
Each bundled plugin ships its unit tests in its own directory (plugins/<name>/tests/), covering the plugin's tools and helpers without touching the core. The core suite discovers them through tests/test_plugin_suites.py (registered via load_tests), so python -m unittest discover tests runs everything. A single plugin's suite runs standalone with python plugins/<name>/tests/<file>.py, and headless via polyglav plugins test <name> (or polyglav plugins test for every plugin with a suite).
Live testing¶
Manual live tests against a real provider API are done ad-hoc, not automated. Use a local model (Ollama) or a disposable API key, and verify a turn end-to-end: streaming output, a tool call round trip, and session persistence.
The overnight autonomous run is verified live with a real model: polyglav jobs add <name> --role manager --interval 86400 --file .polyglav/jobs/<name>.md, run it (polyglav jobs run <name> or the daemon), and confirm the run completes and, with report.webhook set, the report arrives. See jobs.md.