Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

refactor(awareness): remove the activity recorder and its recall tools

rubenluetke10-beepe45269bde5fd
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.md
index 11441109e9..a7edfe211e 100644
--- a/docs/LLM-CONTEXT.md
+++ b/docs/LLM-CONTEXT.md
@@ -386,7 +386,7 @@ Verified against the actual file tree (not just CLAUDE.md claims):
| 5 Vision/Action/Admin/Async/Control + Tiered Routing | live | `jarvis/{vision,admin,tasks,control,telemetry}/`, `ROUTER_TOOLS` frozenset, ADR-0001..0011 |
| 6 Self-Healing Worker-Critic | live | `jarvis/missions/{manager,kontrollierer,critic,workers,isolation,worker_runtime,voice,safety}/`. 458 mission tests. Wired via `bootstrap_missions` |
| 7 Self-Mod (foundation + writer + tools) | live | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). `spawn-skill-author` is **NOT** reachable from the brain — see §25; the brain-reachable authoring path is the `create-skill` router tool (2026-08-18) over the same `SkillCreatorService` as `POST /api/skills/creator/*` and `jarvis skills create` |
-| Awareness A0–A5 | live | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, watchers, probes). A1 + A3 router tools registered |
+| Awareness A0–A5 | removed 2026-09-30 | Package and both router tools deleted (token cost, no longer wanted). ADR-0011 amendment "Awareness tools retired" |
| Wiki B0/B1/B2/B3/B5/B7/B8/B9 | live | `jarvis/memory/wiki/` (curator, atomic_writer, page, integration, scheduler, session_rollup, voice_bridge, telemetry, vault_index, watcher, search). 3 router tools |
| Wiki B4 (legacy Curator) | soft-disabled | `factory.py:736-757` gates on `cfg.memory.legacy_curator.enabled` (default `false` since 2026-05-17). `data/workspace/` snapshot stays on disk for 35 reader sites |
| Wiki B6 | not started | — |
@@ -519,7 +519,7 @@ npm run build # tsc -b && vite build --outDir ../dist --emptyOutDir
npm run test # vitest
```
-Line length 100. Target `py311`. One per-file `E501` exception (`jarvis/awareness/prompts.py` — long few-shot strings).
+Line length 100. Target `py311`.
---
@@ -541,7 +541,7 @@ Line length 100. Target `py311`. One per-file `E501` exception (`jarvis/awarenes
**Smoke / probe (manual):**
- `smoke_brain_e2e.py`, `smoke_frontier.py`, `smoke_phase6_p{1,2,2_jobkill,3,3_real}.py`, `smoke-test-ack.ps1`.
- `voice_e2e_probe.py`, `voice_compare.py`, `tts_brain_endtoend.py`, `tts_output_sanity.py`, `warm_keep_bench.py`.
-- `awareness_smoke_a{1,2}.py`, `vision_smoke.py`.
+- `vision_smoke.py`.
- `diag_audio_devices.py`, `diag_mic_{live,mute,wasapi}.py`, `verify_orb_{appears,mute_toggle,drag}.py`, `snap_orb.py` — audio/orb debugging.
**Migration / one-time:**
@@ -660,7 +660,6 @@ Self-mod writeup: [`docs/self_mod.md`](docs/self_mod.md) — 8 mutable settings
| `jarvis/missions/workers/{base,claude_direct_worker,codex_worker,gemini_worker,subjarvis_worker,supervisor}.py` | Worker variants — `WorkerProtocol` structural contract. |
| `jarvis/missions/isolation/{worktree,job_object,env}.py` | Git-worktree manager + Windows Job Object kill-on-close. |
| `jarvis/harness/screenshot_only_loop.py` | Screenshot-only POAV loop — the sole `computer_use` engine (vision picks pixel targets; cross-platform `mss` + `pyautogui`). |
-| `jarvis/awareness/manager.py` | `AwarenessManager` — state holder; **never on voice critical path** (AP-9). |
| `jarvis/memory/wiki/integration.py` | `bootstrap_wiki_integration` — wires SessionRollupWorker (B7) + WikiCurator (B1). |
| `jarvis/sessions/constants.py` | `HANGUP_REASONS` single source of truth — canonical 5-layer enum example. |
| `jarvis/speech/pipeline.py` | Voice pipeline — wake→VAD→STT→Brain→TTS, scrub_for_voice at lines 647 and 1330. |
diff --git a/docs/adr/0009-awareness-architecture.md b/docs/adr/0009-awareness-architecture.md
index 5c0233454b..5a71cf5b48 100644
--- a/docs/adr/0009-awareness-architecture.md
+++ b/docs/adr/0009-awareness-architecture.md
@@ -1,6 +1,7 @@
# ADR-0009 — Awareness-Layer Architecture
-**Status:** Accepted (2026-04-25)
+**Status:** Superseded (2026-09-30) — the awareness layer was removed; its background summaries cost model tokens for a recall feature the product no longer wants. Kept as the historical record.
+**Accepted:** 2026-04-25
**Phase:** A0 — Foundations (the following phases A1-A5 reference this ADR)
## Context
diff --git a/docs/adr/0010-window-focus-watcher-msgwait.md b/docs/adr/0010-window-focus-watcher-msgwait.md
index c5cae39696..ac9e91a7dc 100644
--- a/docs/adr/0010-window-focus-watcher-msgwait.md
+++ b/docs/adr/0010-window-focus-watcher-msgwait.md
@@ -1,6 +1,7 @@
# ADR-0010 — WindowFocusWatcher: MsgWaitForMultipleObjects instead of PumpMessages
-**Status:** Accepted (2026-04-25)
+**Status:** Superseded (2026-09-30) — the window-focus watcher left with the awareness layer (ADR-0009).
+**Accepted:** 2026-04-25
**Phase:** A1 — L1 Live Frame
**Related:** ADR-0009 (Awareness-layer architecture)
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.md
index 0f621537d4..90075d16f2 100644
--- a/docs/adr/0011-router-pure-dispatcher.md
+++ b/docs/adr/0011-router-pure-dispatcher.md
@@ -1409,3 +1409,22 @@ ASGI transport as `app-command`.
`tests/unit/brain/test_routing.py` (exact router set) and
`tests/unit/app_actions/` (catalog exclusions, policy tiers, blocked calls,
parameter mapping).
+
+## Amendment 2026-09-30 — Awareness tools retired
+
+`awareness-snapshot` and `awareness-recall` leave `ROUTER_TOOLS` together with
+the awareness layer that fed them (ADR-0009, ADR-0012). The layer watched the
+foreground window, summarised each stretch of work with a model call, and
+put a live snapshot into every turn's context. That cost tokens on every
+turn and in the background for a recall feature the product no longer wants.
+
+The evidence gate keeps its `activity` domain. No tool serves it now, so a
+question like "what did I have open today?" gets the gate's honest refusal
+("I don't keep a history of your activity") instead of an invented timeline.
+Mission workers lose the `awareness-recall` grant (ADR-0030).
+
+### Regression guards
+
+- `tests/unit/brain/test_routing.py` (exact router set)
+- `tests/unit/brain/test_evidence_gate.py`, `tests/unit/brain/test_evidence_gate_wiring.py` (honest refusal for the `activity` domain)
+- `tests/missions/test_worker_capability_parity.py` (the worker grant)
diff --git a/docs/adr/0012-awareness-recall-router-tier.md b/docs/adr/0012-awareness-recall-router-tier.md
index 8e6fc965e0..c909f8f8d7 100644
--- a/docs/adr/0012-awareness-recall-router-tier.md
+++ b/docs/adr/0012-awareness-recall-router-tier.md
@@ -1,6 +1,6 @@
# ADR-0012 — `awareness-recall` lives in the router tier, not a worker tier
-**Status:** Accepted · **Date:** 2026-05-11 · **Phase:** Awareness A3
+**Status:** Superseded — the tool was removed with the awareness layer on 2026-09-30 (see the ADR-0011 amendment "Awareness tools retired") · **Date:** 2026-05-11 · **Phase:** Awareness A3
## Context
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md
index dddb4446ae..957a3e36a0 100644
--- a/docs/architecture-overview.md
+++ b/docs/architecture-overview.md
@@ -45,7 +45,7 @@ subprocess flicker, audio host-API) are catalogued there.
| **5 — Vision/Action/Admin/Async/Control + Tiered Routing** | ✅ | `jarvis/{vision,admin,tasks,control,telemetry}/`. Computer-Use enabled. Tiered routing via `ROUTER_TOOLS` frozenset. ADR-0001..0011. |
| **6 — Self-Healing Worker-Critic** | ✅ | `jarvis/missions/` (event store, manager, recovery, state machine, budget, cleanup, workers, critic, kontrollierer, safety, voice, isolation). ADR-0009, `docs/phase6-*.md`. Wired into REST + voice path via `bootstrap_missions`. **Live progress (2026-06-15):** both the Codex worker and `ClaudeDirectWorker` stream stdout line-by-line; the orchestrator drain loop emits throttled `WorkerProgress` (`jarvis/missions/events.py`) → WS → `ReasoningPanel`. **Re-run (2026-06-15):** `POST /api/missions/{id}/rerun` re-dispatches a terminal mission's stored prompt as a NEW mission linked via `parent_mission_id` ("Continue" cancelled / "Restart" failed) — the source card is untouched audit; **no state-machine or idempotency change** (deliberate, avoids AP-14). |
| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 skill authoring by voice/chat is the `create-skill` router tool** (2026-08-18; `pyproject.toml` → `jarvis.plugins.tool.create_skill:CreateSkillTool`, router-tier, `monitor`; one bounded brain call through `SkillCreatorService`, the same service behind `POST /api/skills/creator/*` and `jarvis skills create`). The older `spawn-skill-author` class is NOT wired (see `docs/LLM-CONTEXT.md` §25). Generated skills land as `state="draft"` and are never auto-activated (AP-15). |
-| **Awareness A0–A5** | ✅ | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, recall_store, watchers, probes). Router-tier tools `awareness-snapshot` (A1) + `awareness-recall` (A3). ADR-0009/0010/0012. Hard rule: **never on the voice critical path**. |
+| **Awareness A0–A5** | removed 2026-09-30 | The window watcher, episode summaries and the `awareness-snapshot` / `awareness-recall` tools were deleted: they spent tokens every turn for a recall feature the product no longer wants. ADR-0009/0010/0012 are superseded; see the ADR-0011 amendment "Awareness tools retired". |
| **Wiki B0/B1/B2/B3/B5/B7/B8/B9** | ✅ | `jarvis/memory/wiki/` (curator, atomic_writer, page_repository, integration, session_rollup, voice_bridge, telemetry, scheduler). Three router-tier tools: `wiki-recall`, `wiki-page-read`, `wiki-ingest`. ADR-0013/0014/0015. B2 = `docs/obsidian-setup.md` + B9-Wizard. B3 = `WikiView.tsx` + 6-endpoint `wiki_routes.py` + `wiki_ws.py` live-reload. **B4 soft-disabled** 2026-05-17 via `[memory.legacy_curator] enabled = false` — legacy Curator package + `data/workspace/` snapshot stay on disk; Hart-Cut (vault migration + reader refactor + package delete) remains open. **B6 not started**. |
| **Realtime → Jarvis-Agents bridge** | ✅ canonical path live | **Hybrid tool mode (ADR-0035, 2026-08-19, default):** the live model calls every router tool itself through `RealtimeToolBridge` (catalog minus the computer-use vehicles, compact declarations under `[voice].realtime_tool_declaration_budget_tokens`) and keeps ONE provider-neutral `jarvis_action` for computer use, screen looks and any capability it has no function for; the Tool Model runs only those delegated turns. `delegate` (one function, every action through the router Brain) and `direct` stay as explicit modes. `BrainManager` delegates heavy work through `spawn-worker`; `jarvis/missions/` owns worker selection, isolation, retries, Critic review, and Kontrollierer sign-off. MCP and marketplace tools are granted by capability, not exposed as worker harness names. |
| **Ack-Brain (pre-thinking)** | ✅ | `jarvis/brain/ack_brain/` — sub-second butler ACK before the deep brain replies. Gemini Flash Lite primary. UI preamble bubble. Suppress-if-fast gate at 2000ms (`[ack_brain].suppress_if_brain_faster_than_ms`). ADR-0014 (flash-brain). |
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 5dd26a33b6..cea606f930 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -553,8 +553,6 @@ experiences today.
| P-29 | Low | Subscription voice | The dedicated ChatGPT-subscription voice login is an interactive browser flow, so a headless Linux host — and a graphical Linux desktop that ships no terminal emulator able to host the login for its full lifetime — can never CONNECT the profile there (an existing login still reports ready and calls work through the browser voice bridge) | `jarvis/codex_app_server.py::_login_required_state`, `_linux_login_terminal_missing`, `start_codex_subscription_login`, `jarvis/codex_auth.py::_LINUX_LOGIN_TERMINALS` | Both cases report the same `lifecycle_unavailable` truth on every surface (card, activation, voice-mode, Test), each with its own actionable reason — "run Jarvis on a desktop" or "install one of these terminals" — and never an enabled Connect button that can only produce an error toast |
| P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word |
| P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front. Two further silent failures are Windows-only in their FIX: a chord the target does not bind as "paste" (an xterm.js terminal in a Tauri/Electron app swallows Ctrl+V as `^V`), and a target that reads the clipboard late (an async WebView bridge on a busy machine) after the 120 ms restore timer had already put the previous clipboard back | `jarvis/dictation/insert.py::describe_target`, `_insert_windows_verified`, `jarvis/platform/clipboard_offer.py`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three blocks degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. **Windows** additionally offers the text with delayed rendering and watches who reads it: on a host without a clipboard watcher (no Remote Desktop client, clipboard history off — the default) a paste is proven by the target's read, silence cascades Ctrl+V → Ctrl+Shift+V → Shift+Insert → typing (line breaks as Shift+Enter), and the route is remembered per executable; on a host with a watcher the offer is blind, ONE chord goes out (never a guessed second paste) and the previous clipboard is restored after a 2 s grace only if the dictated text is still on it. **macOS / Linux X11**: plain chord + 120 ms timer restore, unchanged — no delayed-rendering equivalent exists there (NSPasteboard promises and X11 selections notify the owner too, but are a follow-up). macOS Secure Input detection is implemented but has not been verified on real hardware from this machine |
-| P-02 | Low | Awareness | Idle detection has no Wayland backend (Windows GetLastInputInfo, macOS Quartz, Linux X11 `xprintidle` all exist since 2026-07-16); Wayland exposes no global idle time without portal support | `jarvis/awareness/watchers/idle.py` | Wayland: one honest log line, watcher does not start |
-| P-03 | Low | Awareness | Window-focus watcher has no Wayland backend (Windows event hook, macOS NSWorkspace, Linux X11 polling all exist since 2026-07-16); Wayland hides the foreground window by design | `jarvis/awareness/watchers/window.py` | Wayland: one honest log line, watcher does not start |
| P-04 | Medium | CU typing | Linux desktop Unicode text input needs the system `xdotool` binary (pip cannot install it); the pyautogui fallback used on Linux drops non-ASCII chars (umlauts, CJK, emoji) without it | `jarvis/cu/actuate/posix.py::type_text`, `jarvis/plugins/tool/type_text.py` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without, the drop is now reported HONESTLY (2026-07-23): an all-non-ASCII text fails with an actionable "install xdotool" error, and a mixed text types its ASCII portion and warns that the rest was dropped — no more silent success |
| P-05 | Low | Wiki | Wiki search hard-fails (RuntimeError with actionable apt/pysqlite3 remediation) on distros whose system SQLite lacks FTS5 | `jarvis/memory/wiki/fts_index.py:279` | `python:3.11-slim` and macOS ship FTS5 — only exotic/old distros affected; message is honest. Decision 2026-07-16: kept as honest hard error — a pysqlite3 shim would rewire seven wiki modules for an exotic audience |
| P-07 | Low | Audio | No macOS/Linux host-API preference exists (the Windows-name-driven tables are intentionally inert off Windows — documented in-code since 2026-07-16), and headset-name heuristics are Windows-centric | `jarvis/audio/player.py`, `jarvis/audio/capture.py` | Device auto-pick falls back to OS default order — works, less clever than on Windows |
diff --git a/jarvis/awareness/__init__.py b/jarvis/awareness/__init__.py
deleted file mode 100644
index 3fd2af9c67..0000000000
--- a/jarvis/awareness/__init__.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""Awareness Layer (Phase A0+) — continuous context for the main Jarvis.
-
-Four-layer architecture (Plan §1):
- L1 Live Frame — RAM, seconds (Phase A1)
- L2 Story — RAM ring buffer + SQLite (Phase A2)
- L3 Session — FTS5 search over episodes (Phase A3)
- L4 Long-Term — Curator -> MEMORY.md (existing)
-
-A0 scope: data models + privacy filter + config schema. No watchers,
-no captures, no bus subscriptions — those come in A1.
-"""
-from __future__ import annotations
-
-from jarvis.awareness.config import (
- AwarenessConfig,
- AwarenessPrivacyConfig,
- AwarenessProbesConfig,
- AwarenessQuotasConfig,
- AwarenessWatchersConfig,
-)
-from jarvis.awareness.context import Context, resolve_context
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.privacy import PrivacyFilter
-from jarvis.awareness.probes import FileSystemProbe, GitProbe, Probe
-from jarvis.awareness.quotas import StorageQuota
-from jarvis.awareness.state import AwarenessState, FrameSnapshot
-from jarvis.awareness.working_set import WorkingSet
-
-__all__ = [
- "AwarenessConfig",
- "AwarenessManager",
- "AwarenessPrivacyConfig",
- "AwarenessProbesConfig",
- "AwarenessQuotasConfig",
- "AwarenessState",
- "AwarenessWatchersConfig",
- "Context",
- "FileSystemProbe",
- "FrameSnapshot",
- "GitProbe",
- "PrivacyFilter",
- "Probe",
- "StorageQuota",
- "WorkingSet",
- "resolve_context",
-]
diff --git a/jarvis/awareness/config.py b/jarvis/awareness/config.py
deleted file mode 100644
index 7264980515..0000000000
--- a/jarvis/awareness/config.py
+++ /dev/null
@@ -1,156 +0,0 @@
-"""AwarenessConfig — Pydantic models for the [awareness] TOML block.
-
-Attached by the root loader (``jarvis.core.config.load_config``) via
-``JarvisConfig.awareness``. All fields have defaults so that a
-``jarvis.toml`` without an ``[awareness]`` block can be read cleanly as
-``AwarenessConfig()`` (backward-compat AC §4).
-
-Defaults are taken 1:1 from JARVIS_AWARENESS_PLAN §4 — when changing
-them, also update the ``[awareness]`` block in ``jarvis.toml``.
-"""
-from __future__ import annotations
-
-from pydantic import BaseModel, ConfigDict, Field
-
-# Default patterns from Plan §4. Lifted into module constants so that tests
-# can compare them without a Pydantic round-trip (test_config.py).
-_DEFAULT_BLOCKED_PROCESSES: list[str] = [
- "1password*", "keepass*", "bitwarden*", "lastpass*",
-]
-
-_DEFAULT_BLOCKED_TITLE_PATTERNS: list[str] = [
- "*Banking*", "*PayPal*", "*Stripe*Dashboard*",
- "*Sparkasse*", "*Postbank*", "*Online-Banking*",
- "*Passwort*", "*Password*Manager*",
- "*Inkognito*", "*Private Browsing*",
-]
-
-_DEFAULT_ALLOWED_PROCESSES: list[str] = [
- "code.exe", "cursor.exe", "windsurf.exe",
- "WindowsTerminal.exe", "pwsh.exe", "cmd.exe",
-]
-
-
-class AwarenessPrivacyConfig(BaseModel):
- """System-layer privacy filter patterns."""
- model_config = ConfigDict(extra="allow")
-
- blocked_processes: list[str] = Field(
- default_factory=lambda: list(_DEFAULT_BLOCKED_PROCESSES),
- )
- blocked_title_patterns: list[str] = Field(
- default_factory=lambda: list(_DEFAULT_BLOCKED_TITLE_PATTERNS),
- )
- allowed_processes: list[str] = Field(
- default_factory=lambda: list(_DEFAULT_ALLOWED_PROCESSES),
- )
- default_when_unknown: str = "block_for_browsers_allow_for_others"
-
-
-class AwarenessWatchersConfig(BaseModel):
- """Watcher settings — consumed by ``AwarenessManager`` from phase A1 onward."""
- model_config = ConfigDict(extra="allow")
-
- enable_window: bool = True
- enable_idle: bool = True
- idle_threshold_minutes: int = 5
-
-
-class AwarenessQuotasConfig(BaseModel):
- """Mirror of ``StorageQuota`` defaults; consumed by ``StoryTracker`` from A2 onward."""
- model_config = ConfigDict(extra="allow")
-
- max_bytes: int = 50 * 1024 * 1024 # 50 MiB
- max_episodes: int = 1000
-
-
-class AwarenessVerdichterConfig(BaseModel):
- """Verdichter brain settings (Plan §6, ``[awareness.verdichter]``).
-
- Controls the episode-summary brain call. ``enabled = false`` turns off
- the Verdichter entirely (StoryTracker then persists episodes with
- ``summary=""``) — hot-disable analogous to the top-level switch.
-
- Defaults (Plan §6 D-A4):
- provider = "claude-api"
- model = "claude-haiku-4-5-20251001"
- max_input_tokens = 8000 # bound on input per episode
- max_output_tokens = 2000 # bound on output per episode
- timeout_s = 5.0 # asyncio.wait_for timeout
- """
- model_config = ConfigDict(extra="allow")
-
- enabled: bool = True
- provider: str = "claude-api"
- model: str = "claude-haiku-4-5-20251001"
- max_input_tokens: int = 8_000
- max_output_tokens: int = 2_000
- timeout_s: float = 5.0
-
-
-class AwarenessProbesConfig(BaseModel):
- """Deep probes settings (Plan §9, ``[awareness.probes]``).
-
- A5-Lite: only GitProbe + FileSystemProbe (MCP/LSP deferred to Phase 6).
- All probes share a combined 200 ms total budget — if exceeded,
- probe_all() is aborted and unset fields remain None.
-
- enabled = false → no probes registered; FrameSnapshot keeps
- git_branch=None / open_file_hint=None.
- """
- model_config = ConfigDict(extra="allow")
-
- enabled: bool = True
- enable_git: bool = True
- enable_filesystem: bool = True
- total_budget_ms: int = 200 # hard cap for probe_all (asyncio.gather)
- fs_max_watched_roots: int = 10 # cap for FileSystemProbe.watch
-
-
-class AwarenessStoryConfig(BaseModel):
- """StoryTracker settings (Plan §6, ``[awareness.story]``).
-
- Controls buffering and trigger logic for L2 episode flushes. ``enabled = false``
- keeps watchers running (L1) but persists no episodes — useful for privacy mode
- or debugging without LLM cost.
-
- Defaults (Plan §6 StoryTracker trigger logic):
- buffer_max = 200 # max frames + events in builder
- episode_min_duration_s = 60 # < 60 s = spam, skip flush
- episode_max_duration_min = 30 # > 30 min = hard cap, force flush
- hard_timer_min = 5 # flush at least every 5 min even without activity
- """
- model_config = ConfigDict(extra="allow")
-
- enabled: bool = True
- buffer_max: int = 200
- episode_min_duration_s: int = 60
- episode_max_duration_min: int = 30
- hard_timer_min: int = 5
-
-
-class AwarenessConfig(BaseModel):
- """Root of the ``[awareness]`` block.
-
- ``enabled = false`` hot-disables the entire subsystem — the factory
- will not build an ``AwarenessManager`` at all and tools will not be
- registered (Plan §15 rollback plan).
- """
- model_config = ConfigDict(extra="allow")
-
- enabled: bool = True
- privacy: AwarenessPrivacyConfig = Field(default_factory=AwarenessPrivacyConfig)
- watchers: AwarenessWatchersConfig = Field(default_factory=AwarenessWatchersConfig)
- quotas: AwarenessQuotasConfig = Field(default_factory=AwarenessQuotasConfig)
- verdichter: AwarenessVerdichterConfig = Field(default_factory=AwarenessVerdichterConfig)
- story: AwarenessStoryConfig = Field(default_factory=AwarenessStoryConfig)
- probes: AwarenessProbesConfig = Field(default_factory=AwarenessProbesConfig)
-
- @classmethod
- def default(cls) -> AwarenessConfig:
- """Convenience factory for tests and direct initialization in A1+.
-
- Equivalent to ``cls()``, but as a named constructor is clearer
- at the call site.
- """
- return cls()
diff --git a/jarvis/awareness/context.py b/jarvis/awareness/context.py
deleted file mode 100644
index 494f8cab27..0000000000
--- a/jarvis/awareness/context.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""Context — data model and resolver for the Phase A4 Working Set.
-
-A ``Context`` represents a "slot" in the RAM LRU cache of the
-``WorkingSet``: project root + task label + last episode ID + timestamp.
-Multiple parallel contexts (e.g. VS Code + Slack + browser) are tracked
-independently; when a known context is reactivated the snapshot returns
-its last episode instead of a generic "most-recent" episode.
-
-Resolver heuristic (Plan §8):
- 1. Process in IDE_SET (code.exe, cursor.exe, windsurf.exe)
- → ``project_root`` via ``psutil.Process.cwd()``
- 2. Browser process → parse hostname from window title
- 3. Terminal process → shell cwd via psutil
- 4. Fallback → ``process_name`` as ``project_root``
-
-``task_label`` = first 5 words of the window title (plan definition).
-
-Hard negatives (from spec):
-- NO ``psutil`` import at module top-level (CI/Linux flaky) — lazy import
- inside the resolver, with ``try/except`` around every ``psutil`` operation.
-- NO persistence — the WorkingSet is RAM-only (the DB holds everything).
-"""
-from __future__ import annotations
-
-import logging
-import re
-import time
-from dataclasses import dataclass, field
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from jarvis.awareness.state import FrameSnapshot
-
-logger = logging.getLogger(__name__)
-
-
-# ---- Heuristic tables -------------------------------------------------------
-
-# IDEs/editors with a well-defined project root via cwd().
-IDE_SET: frozenset[str] = frozenset({
- "code.exe", "cursor.exe", "windsurf.exe",
- "rider64.exe", "pycharm64.exe", "idea64.exe",
- "devenv.exe", # Visual Studio
- "Code.exe", # case variation on Windows
-})
-
-# Browser processes — we parse the hostname from the window title.
-BROWSER_SET: frozenset[str] = frozenset({
- "chrome.exe", "msedge.exe", "firefox.exe",
- "brave.exe", "opera.exe", "vivaldi.exe", "arc.exe",
-})
-
-# Terminal shells — cwd gives the working directory.
-TERMINAL_SET: frozenset[str] = frozenset({
- "WindowsTerminal.exe", "wezterm-gui.exe", "alacritty.exe",
- "ConEmu64.exe", "cmd.exe", "pwsh.exe", "powershell.exe",
- "bash.exe", "zsh.exe",
-})
-
-# Browser window titles typically look like:
-# "Google Search - Mozilla Firefox"
-# "GitHub - PR #123 — Brave"
-# "https://example.com — Chromium"
-# We search for a URL/domain in the title (best-effort).
-_URL_RE = re.compile(r"https?://([^/\s]+)")
-_DOMAIN_RE = re.compile(r"\b([a-z0-9-]+(?:\.[a-z0-9-]+)+)\b", re.IGNORECASE)
-_BROWSER_SUFFIX_RE = re.compile(
- r"\s*[-—–|]\s*(Mozilla\s+Firefox|Google\s+Chrome|Microsoft\s+Edge|"
- r"Chromium|Brave|Opera|Vivaldi|Arc)\s*$",
- re.IGNORECASE,
-)
-
-
-@dataclass(frozen=True, slots=True)
-class Context:
- """A "slot" in the Working Set.
-
- Fields:
- project_root Derived from cwd / hostname / process_name. Also
- serves as the identity key for LRU lookup (uniqueness).
- task_label Human-readable label (max ~5 words from the window title).
- last_episode_id FK to ``awareness_episodes.id``. None until the first
- episode in this context has been persisted.
- last_seen_ns time.time_ns() of the last activity — used by the LRU
- for eviction.
- process_name Originating process (debug + heuristic).
- """
- project_root: str
- task_label: str
- last_episode_id: int | None = None
- last_seen_ns: int = field(default_factory=lambda: time.time_ns())
- process_name: str = ""
-
-
-def resolve_context(frame: FrameSnapshot) -> Context:
- """Heuristic mapping of ``FrameSnapshot`` to ``Context``.
-
- Heuristic order (Plan §8):
- 1. IDE → ``project_root`` via ``psutil.Process.cwd()``
- 2. Browser → hostname from window title
- 3. Terminal → shell cwd via psutil
- 4. Fallback → ``process_name`` as ``project_root``
-
- Every ``psutil`` operation is wrapped in ``try/except`` with fallback to
- ``process_name``. Lazy import (CI/Linux may lack psutil or
- ``psutil.cwd()`` may hang on UAC / disconnected drives).
- """
- process = frame.active_process_name
- title = frame.active_window_title
- pid = frame.active_pid
-
- project_root: str | None = None
-
- if process in IDE_SET:
- project_root = _safe_cwd(pid)
- elif process in BROWSER_SET:
- project_root = _hostname_from_title(title)
- elif process in TERMINAL_SET:
- project_root = _safe_cwd(pid)
-
- # Fallback to process_name — ALWAYS a valid identity key, even
- # when all three heuristics fail.
- if not project_root:
- project_root = process or "unknown"
-
- task_label = _short_label(title)
-
- return Context(
- project_root=project_root,
- task_label=task_label,
- process_name=process,
- )
-
-
-# ---- Helpers ---------------------------------------------------------------
-
-
-def _safe_cwd(pid: int) -> str | None:
- """Look up ``psutil.Process(pid).cwd()`` with fail-silent semantics.
-
- Lazy import: psutil is optional on Linux/CI. On any failure
- (Permission, NoSuchProcess, AccessDenied, OSError, ImportError):
- returns None — the caller falls back to process_name.
- """
- if pid <= 0:
- return None
- try:
- import psutil # noqa: PLC0415
-
- return psutil.Process(pid).cwd()
- except Exception: # noqa: BLE001
- return None
-
-
-def _hostname_from_title(title: str) -> str | None:
- """Best-effort hostname parser from a browser window title.
-
- Expected format examples:
- "GitHub - awesome-repo - Mozilla Firefox" → None (no URL/domain)
- "https://example.com - Chrome" → "example.com"
- "Stack Overflow - Brave" → None
- """
- if not title:
- return None
- # Strip the browser suffix so we don't match "firefox" as a domain.
- cleaned = _BROWSER_SUFFIX_RE.sub("", title)
- # Try an explicit URL match first.
- m = _URL_RE.search(cleaned)
- if m:
- return m.group(1)
- # Otherwise: explicit domain (with dot) in the title.
- m = _DOMAIN_RE.search(cleaned)
- if m:
- return m.group(1)
- return None
-
-
-def _short_label(title: str, *, max_words: int = 5) -> str:
- """First ``max_words`` words of the title as a compact label.
-
- Plan §8: "task_label = first 5 words of the window title minus..."
- Whitespace is stripped and the result is capped at max_words.
- """
- if not title:
- return ""
- words = title.split()
- if len(words) <= max_words:
- return " ".join(words)
- return " ".join(words[:max_words])
diff --git a/jarvis/awareness/episode.py b/jarvis/awareness/episode.py
deleted file mode 100644
index ce998b7836..0000000000
--- a/jarvis/awareness/episode.py
+++ /dev/null
@@ -1,250 +0,0 @@
-"""Episode data classes for the L2 Story Tracker.
-
-``Episode`` is the immutable persist form (frozen+slots) that the
-``StoryTracker`` writes to SQLite after a Verdichter call. Immutability
-allows the flight recorder to replay episodes deterministically.
-
-``EpisodeBuilder`` is the mutable counterpart: it accumulates frames and
-events while a window is open. On a trigger (app switch, idle, hard timer)
-the tracker calls ``build()`` and receives a frozen ``Episode``.
-"""
-from __future__ import annotations
-
-import time
-from dataclasses import dataclass, field
-from typing import Any
-
-from jarvis.awareness.state import FrameSnapshot
-
-
-@dataclass(frozen=True, slots=True)
-class Episode:
- """Immutable, persist-ready episode data class.
-
- Fields correspond 1:1 to the ``awareness_episodes`` table from
- ``schema.sql`` (Slice A). ``tokens_in/out`` are 0 when the Verdichter
- was not invoked (empty episode or timeout).
- """
- started_at_ns: int
- ended_at_ns: int
- trigger_kind: str
- summary: str
- frame_count: int
- primary_app: str
- tokens_in: int = 0
- tokens_out: int = 0
-
-
-@dataclass
-class _EventEntry:
- """Internal format for accumulated events.
-
- Exposed in ``EpisodeBuilder.events`` as a dict representation
- ``{kind, salience, payload, ts_ns}``.
- """
- kind: str
- salience: int
- payload: dict[str, Any]
- ts_ns: int
-
-
-@dataclass
-class _FrameEntry:
- """Internal format for accumulated frames (frame + score)."""
- frame: FrameSnapshot
- salience: int
-
-
-@dataclass
-class EpisodeBuilder:
- """Mutable builder. Accumulates frames and events while an episode is open.
-
- Lifecycle:
-
- 1. ``__init__(started_at_ns)`` — mark the episode start.
- 2. Repeatedly call ``add_frame(frame, salience)`` and/or
- ``add_event(kind, salience, payload)``.
- 3. ``build(ended_at_ns=..., summary=..., …)`` → frozen ``Episode``.
- The builder persists after build() but can be reset
- (caller responsibility, not enforced here).
-
- The ``frames`` / ``events`` properties return **copies** so that
- the Verdichter cannot accidentally mutate the builder state.
- """
- started_at_ns: int
- _frames: list[_FrameEntry] = field(default_factory=list, init=False, repr=False)
- _events: list[_EventEntry] = field(default_factory=list, init=False, repr=False)
-
- def add_frame(self, frame: FrameSnapshot, salience: int) -> None:
- """Append a frame and its salience score to the buffer."""
- self._frames.append(_FrameEntry(frame=frame, salience=salience))
-
- def add_event(
- self, event_kind: str, salience: int, payload: dict[str, Any],
- ) -> None:
- """Buffer an event with salience, payload, and the current timestamp."""
- self._events.append(
- _EventEntry(
- kind=event_kind,
- salience=salience,
- payload=dict(payload), # defensive copy
- ts_ns=time.time_ns(),
- ),
- )
-
- def detach_frames(self) -> list[FrameSnapshot]:
- """Atomic snapshot and reset of the internal frame buffer.
-
- Codex-BLOCKER B2-Fix (2026-05-11): the former ``frames`` property
- returned a copy but left the internal buffer in place. Combined with
- the B1-Fix (Verdichter call outside the lock), this created a race
- window — a concurrent ``add_frame`` call between snapshot creation
- and ``self._builder = None`` in StoryTracker could place a frame in
- a builder that was about to be discarded.
-
- Double-buffer pattern: we replace the internal list with a fresh
- empty list BEFORE returning. The caller (StoryTracker) holds the
- external ``_lock`` during the call, so the list the caller receives
- is fully decoupled from the builder, and any ``add_frame`` arriving
- after the lock is released lands in the fresh bucket (or, if the
- tracker sets ``self._builder = None``, in a new builder).
-
- IMPORTANT: This method is NOT thread-safe in isolation — atomicity
- comes from the external lock held by StoryTracker.
- """
- out = [entry.frame for entry in self._frames]
- self._frames = []
- return out
-
- def detach_events(self) -> list[dict[str, Any]]:
- """Atomic snapshot and reset of the internal event buffer.
-
- Same B2 guarantee as ``detach_frames`` — list swap before return,
- caller holds the external lock.
- """
- out = [
- {
- "kind": entry.kind,
- "salience": entry.salience,
- "payload": dict(entry.payload),
- "ts_ns": entry.ts_ns,
- }
- for entry in self._events
- ]
- self._events = []
- return out
-
- def build(
- self,
- *,
- ended_at_ns: int,
- summary: str,
- tokens_in: int = 0,
- tokens_out: int = 0,
- ) -> Episode:
- """Snapshot → frozen ``Episode``.
-
- ``trigger_kind`` is set by the caller (StoryTracker) — the builder
- does not know it. The default is empty; the tracker patches the field
- during the persist call alongside ``trigger_kind`` via ``replace()``.
- A sentinel is sufficient here — the actual trigger is added by the
- caller in the ``record_episode`` insert (Spec Slice A).
- """
- return Episode(
- started_at_ns=self.started_at_ns,
- ended_at_ns=ended_at_ns,
- trigger_kind="", # set by the caller (StoryTracker)
- summary=summary,
- frame_count=len(self._frames),
- primary_app=self.primary_app,
- tokens_in=tokens_in,
- tokens_out=tokens_out,
- )
-
- @property
- def frames(self) -> list[FrameSnapshot]:
- """Read-only copy of accumulated frames (in insertion order)."""
- return [entry.frame for entry in self._frames]
-
- @property
- def events(self) -> list[dict[str, Any]]:
- """Read-only copy of accumulated events.
-
- Format: ``{"kind": str, "salience": int, "payload": dict, "ts_ns": int}``.
- """
- return [
- {
- "kind": entry.kind,
- "salience": entry.salience,
- "payload": dict(entry.payload),
- "ts_ns": entry.ts_ns,
- }
- for entry in self._events
- ]
-
- @property
- def frame_count(self) -> int:
- """Number of accumulated frames."""
- return len(self._frames)
-
- @property
- def duration_ns(self) -> int:
- """Elapsed time since ``started_at_ns`` (live, not frozen)."""
- return time.time_ns() - self.started_at_ns
-
- @property
- def primary_app(self) -> str:
- """Process with the longest cumulative dwell time.
-
- Calculation: for each frame, the difference to the NEXT frame counts
- as dwell time. The last frame contributes 0 ns (we do not know how
- long it will remain active — the builder is live).
-
- Empty buffer: empty string. Exactly one frame: its
- ``active_process_name`` (even if dwell time is 0 —
- better than an empty string).
-
- Tie (multiple apps with equal time): the first one wins
- (insertion order via dict).
- """
- # Delegates to primary_app_from_snapshot — the same algorithm can be
- # called directly by StoryTracker on detach_frames() results without
- # needing to know the builder's internal format.
- return primary_app_from_snapshot(
- [entry.frame for entry in self._frames],
- )
-
- def is_empty(self) -> bool:
- """True if neither frames nor events have been accumulated."""
- return not self._frames and not self._events
-
-
-def primary_app_from_snapshot(frames: list[FrameSnapshot]) -> str:
- """Standalone primary-app heuristic on a detached FrameSnapshot list.
-
- Identical semantics to ``EpisodeBuilder.primary_app`` — called by
- StoryTracker after ``builder.detach_frames()`` (at that point the builder
- is empty and the property would return "").
- """
- if not frames:
- return ""
- if len(frames) == 1:
- return frames[0].active_process_name
-
- dwell_by_app: dict[str, int] = {}
- for i in range(len(frames) - 1):
- dwell = frames[i + 1].timestamp_ns - frames[i].timestamp_ns
- if dwell < 0: # defensive: out-of-order frames
- dwell = 0
- dwell_by_app[frames[i].active_process_name] = (
- dwell_by_app.get(frames[i].active_process_name, 0) + dwell
- )
-
- # Last frame: 0 ns contribution, but register it as a key so that
- # single-app episodes with only one process and dwell == 0 are handled.
- last_app = frames[-1].active_process_name
- dwell_by_app.setdefault(last_app, 0)
-
- # max() with tie-break via insertion order: dicts are insertion-ordered
- # from Python 3.7; max() returns the first element on equal values.
- return max(dwell_by_app, key=lambda app: dwell_by_app[app])
diff --git a/jarvis/awareness/manager.py b/jarvis/awareness/manager.py
deleted file mode 100644
index ea87b3f4f5..0000000000
--- a/jarvis/awareness/manager.py
+++ /dev/null
@@ -1,371 +0,0 @@
-"""AwarenessManager — lifecycle holder and live-state access point.
-
-Phase A1: extended with ``async start()`` / ``async stop()`` that start
-and stop the watchers (``WindowFocusWatcher`` + ``IdleDetector``).
-Backward-compat with A0: without the ``bus`` parameter the manager is a
-pure state holder (start/stop are no-ops).
-
-Dependency injection: the manager is built in ``jarvis.brain.factory``
-and injected into ``AwarenessSnapshotTool`` and watchers. No singleton —
-Plan §5 hard-negative explicitly forbids it.
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import os
-from typing import TYPE_CHECKING, Any
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.context import resolve_context
-from jarvis.awareness.state import AwarenessState
-from jarvis.awareness.working_set import WorkingSet
-
-if TYPE_CHECKING:
- from jarvis.awareness.probes.base import Probe
- from jarvis.awareness.probes.filesystem import FileSystemProbe
- from jarvis.awareness.story import StoryTracker
- from jarvis.awareness.verdichter import Verdichter
- from jarvis.awareness.watchers.base import AwarenessWatcher
- from jarvis.core.bus import EventBus
- from jarvis.core.events import EpisodeRecorded, FrameUpdated
-
-logger = logging.getLogger(__name__)
-
-_STOP_TIMEOUT_S: float = 2.0 # Plan §5 + §10 hard-negative
-_PROBE_BUDGET_S_DEFAULT: float = 0.2 # Plan §9 hard cap for probe_all
-
-
-class AwarenessManager:
- """Holder of live state, watcher lifecycle, and (A2) StoryTracker.
-
- A0 use without ``bus``: state reads only (``manager.state``). Watchers
- are NOT started — suitable for tests and pure read-only scenarios.
-
- A1 use with ``bus``: ``await manager.start()`` builds watchers (according
- to config.watchers.enable_*) and starts them. ``await manager.stop()``
- cleans up in <2 s.
-
- A2 use: ``factory.py`` sets ``_verdichter`` and ``_story_tracker`` as
- post-init attributes after construction. The manager then automatically
- starts/stops StoryTracker in start()/stop() — if not set, this is a
- no-op (backward-compat).
- """
-
- def __init__(
- self,
- config: AwarenessConfig,
- *,
- bus: EventBus | None = None,
- ) -> None:
- self._config = config
- self._bus = bus
- self._state = AwarenessState()
- self._watchers: list[AwarenessWatcher] = []
- self._started: bool = False
- # A2 post-init attributes (set by factory). Initialized to None here
- # so that getattr reads in tests and lifecycle code do not raise
- # AttributeError.
- self._verdichter: Verdichter | None = None
- self._story_tracker: StoryTracker | None = None
- # A5 post-init attributes. Probes list is filled by the factory
- # (or stays empty if config.probes.enabled=False — probe_all is then
- # a no-op and returns an empty dict).
- self._probes: list[Probe] = []
- # Special subsystem: FileSystemProbe requires start/stop and is
- # therefore referenced separately.
- self._fs_probe: FileSystemProbe | None = None
- # A4 Working Set: per-manager LRU of active contexts. RAM-only,
- # no persistence (the DB holds everything). Plan §8 hard negative:
- # no singletons — one per manager instance.
- self._working_set: WorkingSet = WorkingSet()
- # State property for snapshot_for_prompt — kept in sync with
- # _working_set (single writer in manager).
- self._state.working_set = self._working_set
-
- # ---- Properties ---------------------------------------------------------
-
- @property
- def state(self) -> AwarenessState:
- """Current live state. Synchronous read for the awareness-snapshot tool."""
- return self._state
-
- @property
- def config(self) -> AwarenessConfig:
- return self._config
-
- @property
- def working_set(self) -> WorkingSet:
- """A4 Working Set — multi-context LRU. Read-only access for tools."""
- return self._working_set
-
- # ---- Lifecycle ----------------------------------------------------------
-
- async def start(self) -> None:
- """Start watchers according to config. Idempotent.
-
- If ``config.enabled is False`` OR ``bus is None`` → no-op.
- """
- if self._started:
- return
- if not self._config.enabled or self._bus is None:
- self._started = True
- return
-
- # Lazy import to avoid a module-level cycle (manager → watchers →
- # state → manager would theoretically be possible).
- from jarvis.awareness.privacy import PrivacyFilter
-
- privacy = PrivacyFilter(self._config)
-
- if self._config.watchers.enable_window:
- from jarvis.awareness.watchers.window import WindowFocusWatcher
-
- self._watchers.append(WindowFocusWatcher(
- manager=self, privacy=privacy, bus=self._bus,
- ))
-
- if self._config.watchers.enable_idle:
- from jarvis.awareness.watchers.idle import IdleDetector
-
- threshold_s = self._config.watchers.idle_threshold_minutes * 60
- self._watchers.append(IdleDetector(
- manager=self, bus=self._bus, threshold_s=threshold_s,
- ))
-
- # Start watchers in parallel — if one hangs it does not block the others.
- results = await asyncio.gather(
- *(w.start() for w in self._watchers),
- return_exceptions=True,
- )
- for w, res in zip(self._watchers, results, strict=True):
- if isinstance(res, Exception):
- logger.warning("Watcher %s start failed: %s", type(w).__name__, res)
-
- # Phase A5: FileSystemProbe requires its own start (watchdog thread).
- # GitProbe is stateless and needs no start call.
- if self._fs_probe is not None:
- try:
- await self._fs_probe.start()
- except Exception: # noqa: BLE001
- logger.exception("FileSystemProbe.start() failed — continuing without FS-probe")
-
- # Phase A2: start StoryTracker (if set by factory). Only AFTER
- # watchers — the tracker subscribes to FrameUpdated events that come
- # from WindowFocusWatcher; no point if the watcher is not running yet.
- if self._story_tracker is not None:
- try:
- await self._story_tracker.start()
- except Exception: # noqa: BLE001
- logger.exception("StoryTracker.start() failed — continuing without L2")
-
- # Phase A4 Working Set: subscribe to FrameUpdated (context promote)
- # and EpisodeRecorded (bind episode ID to slot). We let StoryTracker
- # subscribe first so its episode persist runs before our set_episode()
- # (order is not strictly required — both are idempotent — but this
- # matches the intended mental model).
- from jarvis.core.events import ( # noqa: PLC0415
- EpisodeRecorded as _EpisodeRecorded,
- )
- from jarvis.core.events import (
- FrameUpdated as _FrameUpdated,
- )
-
- self._bus.subscribe(_FrameUpdated, self._on_frame_updated_for_working_set)
- self._bus.subscribe(_EpisodeRecorded, self._on_episode_recorded_for_working_set)
-
- self._started = True
-
- async def stop(self) -> None:
- """Stop StoryTracker (final flush) and all watchers. <2 s total timeout."""
- if not self._started:
- return
- watchers = list(self._watchers)
- self._watchers = []
- self._started = False
-
- # Phase A2: stop StoryTracker first — it receives a final
- # flush(trigger="stop") and cancels the hard timer. Watchers are
- # stopped afterward; otherwise in-flight FrameUpdated events could
- # trigger a builder reset after the tracker has already stopped.
- story = self._story_tracker
- self._story_tracker = None
- if story is not None:
- try:
- await asyncio.wait_for(story.stop(), timeout=_STOP_TIMEOUT_S)
- except TimeoutError:
- logger.warning(
- "StoryTracker.stop: timeout %.1fs", _STOP_TIMEOUT_S,
- )
- except Exception: # noqa: BLE001
- logger.exception("StoryTracker.stop raised")
-
- # Phase A5: stop FileSystemProbe (join the observer thread).
- fs_probe = self._fs_probe
- self._fs_probe = None
- if fs_probe is not None:
- try:
- await asyncio.wait_for(fs_probe.stop(), timeout=_STOP_TIMEOUT_S)
- except TimeoutError:
- logger.warning("FileSystemProbe.stop: timeout %.1fs", _STOP_TIMEOUT_S)
- except Exception: # noqa: BLE001
- logger.exception("FileSystemProbe.stop raised")
-
- if not watchers:
- return
-
- try:
- await asyncio.wait_for(
- asyncio.gather(
- *(w.stop() for w in watchers),
- return_exceptions=True,
- ),
- timeout=_STOP_TIMEOUT_S,
- )
- except TimeoutError:
- logger.warning(
- "AwarenessManager.stop: timeout %.1fs during watcher shutdown",
- _STOP_TIMEOUT_S,
- )
-
- # ---- Probes (A5) -------------------------------------------------------
-
- async def probe_all(
- self, *, pid: int, process_name: str = "",
- ) -> dict[str, Any]:
- """Run all registered probes in parallel with a total budget cap.
-
- Returns a merged dict of all probe outputs (e.g. ``git_branch``,
- ``open_file_hint``). On timeout: empty dict. On probe exception
- (return_exceptions via gather): the probe field is absent from output.
-
- cwd is resolved here from pid via psutil — probes receive the
- resolved cwd and do not need to look it up themselves.
-
- Hard negative §9: errors NEVER propagate. Total budget enforced
- via asyncio.wait_for(timeout=config.probes.total_budget_ms / 1000).
- """
- if not self._probes:
- return {}
- budget_s = self._config.probes.total_budget_ms / 1000.0
- # Codex-BLOCKER-1-Fix (2026-04-26): cwd resolve MUST fall within the
- # total budget. psutil.cwd() can hang on Windows (UAC, disconnected
- # network drives). Cap cwd resolve at 25 % of the budget or 50 ms
- # max — on timeout: cwd=None, probes still run with reduced budget.
- cwd_budget_s = min(budget_s * 0.25, 0.05)
- try:
- cwd = await asyncio.wait_for(
- asyncio.to_thread(self._resolve_cwd, pid),
- timeout=cwd_budget_s,
- )
- except TimeoutError:
- cwd = None
- tasks = [
- p.probe(cwd=cwd, process_name=process_name) for p in self._probes
- ]
- # Remaining budget = total minus cwd time. Use 75 % pessimistically
- # so that even after a cwd timeout enough budget remains for probes.
- probes_budget_s = budget_s * 0.75
- try:
- results = await asyncio.wait_for(
- asyncio.gather(*tasks, return_exceptions=True),
- timeout=probes_budget_s,
- )
- except TimeoutError:
- logger.debug(
- "probe_all: probes-budget %.0fms exceeded — returning empty",
- probes_budget_s * 1000,
- )
- return {}
- out: dict[str, Any] = {}
- for r in results:
- if isinstance(r, dict):
- out.update(r)
- return out
-
- # ---- Working Set Bus-Handler (A4) --------------------------------------
-
- async def _on_frame_updated_for_working_set(
- self, ev: FrameUpdated,
- ) -> None:
- """Promote or insert the context for the current frame into the WorkingSet.
-
- The frame is read from ``state.current_frame`` (single-writer invariant
- from A1) — the bus event is only the trigger. Privacy-blocked frames
- are skipped (same hard-negatives as StoryTracker).
-
- On an app switch a ``ContextSwitched`` event is published so that
- UI and the flight recorder can observe the promotion.
- """
- if not ev.is_capture_allowed:
- return
- frame = self._state.current_frame
- if frame is None or not frame.is_capture_allowed:
- return
-
- old_root = self._working_set.current.project_root if self._working_set.current else None
- # resolve_context calls psutil.Process(pid).cwd() for IDE/terminal
- # frames; that can block the event loop on UAC prompts, disconnected
- # drives, or simply slow process introspection. Offload to a worker
- # thread (same pattern as the A5 probes path at line 261).
- ctx = await asyncio.to_thread(resolve_context, frame)
- evicted = self._working_set.observe(ctx)
- new_root = ctx.project_root
-
- if self._bus is not None and old_root is not None and old_root != new_root:
- from jarvis.core.events import ContextSwitched # noqa: PLC0415
-
- try:
- await self._bus.publish(ContextSwitched(
- from_context=old_root,
- to_context=new_root,
- ))
- except Exception: # noqa: BLE001
- logger.debug("ContextSwitched publish failed", exc_info=True)
-
- if evicted is not None:
- logger.debug(
- "WorkingSet evicted oldest context: project_root=%s last_seen_ns=%d",
- evicted.project_root, evicted.last_seen_ns,
- )
-
- async def _on_episode_recorded_for_working_set(
- self, ev: EpisodeRecorded,
- ) -> None:
- """Link the persisted episode ID to the current context slot.
-
- Hard negative §8: episodes remain in the DB even if the context
- pointer is evicted. We ONLY call ``set_episode`` — no DB mutation.
- If the slot has since been evicted (multi-context stress),
- set_episode silently swallows it (returns False).
- """
- current = self._working_set.current
- if current is None:
- return
- # Set the episode on the current top-of-LRU — that is the slot that
- # was active when the episode was flushed.
- # Heuristic accepted (Plan §8 — explicitly desired).
- self._working_set.set_episode(current.project_root, ev.episode_id)
-
- @staticmethod
- def _resolve_cwd(pid: int) -> str | None:
- """Fetch cwd via psutil. Returns None on any failure. Lazy import.
-
- Non-Windows: psutil works there too, but FrameSnapshots only arrive
- on Windows (WindowFocusWatcher is a no-op elsewhere). Defensive
- without an explicit platform check.
- """
- if pid <= 0:
- return None
- if os.name != "nt":
- # Non-Windows: psutil cwd works, but A5 is Win32-centric.
- # Probes themselves are platform-agnostic (GitProbe uses a real
- # subprocess), but for the awareness-watcher path non-nt is a
- # test environment — return None rather than risk a hang.
- return None
- try:
- import psutil # noqa: PLC0415
-
- return psutil.Process(pid).cwd()
- except Exception: # noqa: BLE001
- return None
diff --git a/jarvis/awareness/privacy.py b/jarvis/awareness/privacy.py
deleted file mode 100644
index 53075bc4b3..0000000000
--- a/jarvis/awareness/privacy.py
+++ /dev/null
@@ -1,133 +0,0 @@
-"""PrivacyFilter — Window-title- and process-based capture gating.
-
-Three pattern sources (Plan §4 D-A1):
- 1. SYSTEM (``jarvis.toml [awareness.privacy]``) — not user-editable
- 2. USER (``preferences.toml [awareness.privacy]``) — additive via
- ``user_patterns_fn`` callback
- 3. RUNTIME default (``block_for_browsers_allow_for_others``) — when
- no pattern source matches
-
-Evaluation order in ``is_allowed``: BLOCK overrides ALLOW. Mirrors the
-``_collect_patterns`` + ``fnmatch`` logic from
-``jarvis.safety.risk_tier.RiskTierEvaluator``.
-
-Reasons are machine-readable strings: ``matched_blocked_process:<pat>``,
-``matched_blocked_title:<pat>``, ``matched_allowed_process:<pat>``,
-``default_block_for_browser``, ``default_allow_for_unknown`` — they are
-written to the ``AwarenessCaptureBlocked`` event and are grep-able in tests.
-"""
-from __future__ import annotations
-
-import fnmatch
-import logging
-from collections.abc import Callable
-
-from jarvis.awareness.config import AwarenessConfig
-
-logger = logging.getLogger(__name__)
-
-# Browser process names for the hybrid default. Lowercase for the
-# case-insensitive comparison in is_allowed.
-_BROWSER_NAMES: frozenset[str] = frozenset({
- "firefox.exe", "chrome.exe", "msedge.exe", "edge.exe",
- "opera.exe", "brave.exe", "arc.exe", "vivaldi.exe",
- "librewolf.exe", "iexplore.exe", "safari.exe",
-})
-
-# Callback signature for user_patterns_fn:
-# returns (extra_blocked_processes, extra_blocked_title_patterns, extra_allowed_processes)
-UserPatternsFn = Callable[[], "tuple[list[str], list[str], list[str]]"]
-
-
-class PrivacyFilter:
- """Gatekeeper for awareness captures.
-
- Consulted in A1 before every FrameSnapshot insert. Frames with
- ``is_allowed=False`` are logged via the ``AwarenessCaptureBlocked`` event
- and are NOT emitted as ``FrameUpdated``.
- """
-
- def __init__(
- self,
- config: AwarenessConfig,
- *,
- user_patterns_fn: UserPatternsFn | None = None,
- ) -> None:
- self._privacy = config.privacy
- self._user_patterns_fn = user_patterns_fn
-
- def _collect_patterns(self, kind: str) -> list[str]:
- """Merges SYSTEM patterns with USER patterns.
-
- USER is strictly additive — cannot remove SYSTEM defaults.
- Mirrors ``RiskTierEvaluator._collect_patterns``.
- """
- if kind == "blocked_processes":
- patterns = list(self._privacy.blocked_processes)
- elif kind == "blocked_titles":
- patterns = list(self._privacy.blocked_title_patterns)
- elif kind == "allowed_processes":
- patterns = list(self._privacy.allowed_processes)
- else:
- return []
-
- if self._user_patterns_fn is None:
- return patterns
-
- try:
- extra_procs, extra_titles, extra_allowed = self._user_patterns_fn()
- except Exception: # noqa: BLE001
- # A broken user-provider must not hang the privacy gate.
- # Pattern from risk_tier.RiskTierEvaluator._collect_patterns.
- logger.warning(
- "user_patterns_fn raised — using SYSTEM-defaults only",
- exc_info=True,
- )
- return patterns
-
- if kind == "blocked_processes":
- patterns.extend(extra_procs)
- elif kind == "blocked_titles":
- patterns.extend(extra_titles)
- elif kind == "allowed_processes":
- patterns.extend(extra_allowed)
- return patterns
-
- @staticmethod
- def _matches(value: str, pattern: str) -> bool:
- """Case-insensitive fnmatch — as in ``risk_tier.py:105``."""
- return fnmatch.fnmatchcase(value, pattern) or fnmatch.fnmatchcase(
- value.lower(), pattern.lower(),
- )
-
- def is_allowed(self, *, window_title: str, process_name: str) -> tuple[bool, str]:
- """Verdict for a frame. Returns (allowed, reason).
-
- ``reason`` is written to the ``AwarenessCaptureBlocked`` event (on BLOCK)
- or is used only for debug logging (on ALLOW). Evaluation order:
- Blocked Processes → Blocked Titles → Allowed Processes → Default Hybrid.
- """
- # 1. Blocked Processes — hardest block (password managers, banking apps)
- for pattern in self._collect_patterns("blocked_processes"):
- if self._matches(process_name, pattern):
- return False, f"matched_blocked_process:{pattern}"
-
- # 2. Blocked Titles — title heuristic (banking, password, incognito)
- for pattern in self._collect_patterns("blocked_titles"):
- if self._matches(window_title, pattern):
- return False, f"matched_blocked_title:{pattern}"
-
- # 3. Allowed Processes — coding apps explicitly permitted
- for pattern in self._collect_patterns("allowed_processes"):
- if self._matches(process_name, pattern):
- return True, f"matched_allowed_process:{pattern}"
-
- # 4. Default hybrid (D-A1: block_for_browsers_allow_for_others).
- # Browsers have high PII risk (URLs/tabs), unknown apps generally
- # low risk (productivity tools). Additional default strategies
- # can be added here if made configurable.
- if self._privacy.default_when_unknown == "block_for_browsers_allow_for_others":
- if process_name.lower() in _BROWSER_NAMES:
- return False, "default_block_for_browser"
- return True, "default_allow_for_unknown"
- return True, "default_allow_for_unknown"
diff --git a/jarvis/awareness/probes/__init__.py b/jarvis/awareness/probes/__init__.py
deleted file mode 100644
index 56978fe3bd..0000000000
--- a/jarvis/awareness/probes/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""jarvis.awareness.probes — Deep-probes layer (Phase A5).
-
-Probes run before PrivacyFilter and enrich the FrameSnapshot with
-additional metadata (git_branch, open_file_hint). Every probe is
-defensive — errors NEVER propagate into the FrameUpdate path (Hard
-Negative §9). Manager.probe_all calls all probes in parallel with a
-200 ms total budget.
-
-A5-Lite implements only the two simple probes:
-- ``GitProbe`` — branch via .git/HEAD or asyncio git rev-parse
-- ``FileSystemProbe`` — watchdog FS watcher emitting FileSaved bus events
-
-MCP/LSP are deferred to Phase 6 (user default + Plan §9 sanctions
-"Optional, can be deferred").
-"""
-from __future__ import annotations
-
-from jarvis.awareness.probes.base import Probe
-from jarvis.awareness.probes.filesystem import FileSystemProbe
-from jarvis.awareness.probes.git import GitProbe
-
-__all__ = ["FileSystemProbe", "GitProbe", "Probe"]
diff --git a/jarvis/awareness/probes/base.py b/jarvis/awareness/probes/base.py
deleted file mode 100644
index 818b5a8c7b..0000000000
--- a/jarvis/awareness/probes/base.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""Probe protocol for the awareness deep-probes layer (Phase A5).
-
-Every probe implements ``async def probe(*, cwd, process_name) -> dict``.
-Return values are probe-specific (e.g. ``{"git_branch": str | None}``,
-``{"open_file_hint": str | None}``). ``Manager.probe_all`` merges the
-dicts from all probes.
-
-Hard Negative §9: probe errors MUST NOT propagate — every probe MUST
-catch exceptions internally and return a dict (with None fields).
-"""
-from __future__ import annotations
-
-from typing import Any, Protocol, runtime_checkable
-
-
-@runtime_checkable
-class Probe(Protocol):
- """Probe for the FrameSnapshot build path.
-
- name: stable identifier for logging/telemetry.
- probe(): called by AwarenessManager.probe_all() in parallel with all
- other probes via asyncio.gather. 200 ms total budget.
- """
-
- name: str
-
- async def probe(
- self, *, cwd: str | None, process_name: str = "",
- ) -> dict[str, Any]:
- """Returns probe-specific metadata as a dict.
-
- ``cwd`` may be None (process has none or permission was denied).
- ``process_name`` is informational (e.g. for probes that are only
- relevant for certain apps).
-
- MUST return a dict (with None fields) on every failure;
- never raise an exception — otherwise the watcher drain loop crashes.
- """
- ...
diff --git a/jarvis/awareness/probes/filesystem.py b/jarvis/awareness/probes/filesystem.py
deleted file mode 100644
index dd89caeb6d..0000000000
--- a/jarvis/awareness/probes/filesystem.py
+++ /dev/null
@@ -1,316 +0,0 @@
-"""FileSystemProbe — watchdog-based FS watcher for active project roots.
-
-Lifecycle:
-1. ``__init__(*, bus)`` — Observer instance + internal state init.
-2. ``await start()`` — starts the watchdog observer thread.
-3. ``watch(repo_root)`` — adds a watch for a project root (up to MAX_ROOTS).
-4. ``unwatch(repo_root)`` — removes a watch.
-5. ``await stop()`` — Observer.stop() + join (timeout 1 s).
-
-Hard Negatives §9:
-- NEVER recurse over C:\\ — ALWAYS scoped to the project root
- (Watch.recursive=True is fine for a project tree, but ONLY for the
- project root, NOT for the system root)
-- Bus publish from the watchdog thread MUST NOT be done directly —
- use loop.call_soon_threadsafe instead
-- Probe errors MUST NOT propagate — handler swallows and logs
-
-Debounce:
-- Editors (VS Code) often emit multiple events per save (atomic save:
- temp file + rename, or multi-write). We debounce per path with a
- 200 ms window: within 200 ms only the LAST event counts.
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import threading
-import time
-from pathlib import Path
-from typing import TYPE_CHECKING, Any
-
-if TYPE_CHECKING:
- from jarvis.core.bus import EventBus
-
-logger = logging.getLogger(__name__)
-
-_DEBOUNCE_S: float = 0.2
-_MAX_WATCHED_ROOTS_DEFAULT: int = 10 # Safety cap against unbounded growth
-# Backward-compat alias for existing test imports
-_MAX_WATCHED_ROOTS: int = _MAX_WATCHED_ROOTS_DEFAULT
-_STOP_TIMEOUT_S: float = 1.0
-_PATHS_BLACKLIST_PREFIXES: tuple[str, ...] = (
- ".git", "__pycache__", "node_modules", ".venv", "venv",
- ".tox", ".pytest_cache", ".mypy_cache", ".ruff_cache",
- "dist", "build", ".idea", ".vscode",
-)
-# Codex-MAJOR-4-Fix (2026-04-26): hard roots that must NEVER be watched.
-# On Windows: drive roots, %WINDIR%, %PROGRAMFILES%, home folder.
-# Block-pattern instead of allow-pattern because A5-Lite does not know which
-# project roots the user has — the safer default is "forbid what is clearly dangerous".
-_FORBIDDEN_ROOT_PATTERNS: tuple[str, ...] = (
- "c:\\windows", "c:\\program files", "c:\\program files (x86)",
- "c:\\programdata", "c:\\users\\public",
- "/", "/usr", "/etc", "/var", "/sys", "/proc",
-)
-
-
-def _is_forbidden_root(root: str) -> bool:
- """True if root is a forbidden system/home folder.
-
- Blocks: drive root (e.g. C:\\), $env:WINDIR, $env:PROGRAMFILES,
- $env:USERPROFILE directly (subfolders allowed), Linux system roots.
- """
- try:
- p = Path(root).resolve()
- except (OSError, ValueError):
- return True # invalid root → block
- p_str = str(p).lower().rstrip("\\/")
- # Forbid drive root (e.g. "C:" or "C:\\")
- if len(p_str) <= 3 and (p_str.endswith(":") or p_str.endswith(":\\")):
- return True
- # Home folder DIRECTLY (subfolders allowed, because project roots may live there)
- try:
- home = str(Path.home().resolve()).lower().rstrip("\\/")
- if p_str == home:
- return True
- except (OSError, RuntimeError):
- pass
- # System folder patterns
- for forbidden in _FORBIDDEN_ROOT_PATTERNS:
- if p_str == forbidden.rstrip("\\/") or p_str.startswith(forbidden + "\\"):
- return True
- return False
-
-
-class FileSystemProbe:
- """Watchdog-Wrapper. Probe-Methode liefert open_file_hint."""
-
- name: str = "filesystem"
-
- def __init__(
- self,
- *,
- bus: EventBus,
- max_watched_roots: int = _MAX_WATCHED_ROOTS_DEFAULT,
- ) -> None:
- self._bus = bus
- self._loop: asyncio.AbstractEventLoop | None = None
- # Lazy import so that the module remains importable without watchdog
- # (CI without watchdog is possible).
- self._observer: Any = None
- self._watches: dict[str, Any] = {} # repo_root -> watch handle
- self._lock = threading.Lock()
- # Debounce + last-modified tracking
- self._last_emit: dict[str, float] = {}
- self._latest_in_root: dict[str, str] = {} # repo_root -> last seen path
- self._started: bool = False
- # Codex-Claude-MAJOR-M1-Fix (2026-04-26): max-roots from config DI instead of
- # hardcoded module constant. Default stays 10, but jarvis.toml can override
- # via [awareness.probes].fs_max_watched_roots.
- self._max_watched_roots: int = max_watched_roots
- # Code-reviewer-MAJOR-M2-Fix (2026-04-26): asyncio.create_task without
- # a reference hold risks garbage collection mid-flight (silent
- # event loss). We keep a set + add_done_callback for cleanup.
- self._pending_publish_tasks: set[asyncio.Task[Any]] = set()
-
- # ---- Lifecycle ---------------------------------------------------------
-
- async def start(self) -> None:
- """Starts the watchdog observer thread. Idempotent. No-op if watchdog is missing."""
- if self._started:
- return
- try:
- from watchdog.observers import Observer # noqa: PLC0415
- except ImportError:
- logger.warning("watchdog not installed — FileSystemProbe is a no-op")
- self._started = True
- return
- self._loop = asyncio.get_running_loop()
- self._observer = Observer()
- self._observer.start()
- self._started = True
-
- async def stop(self) -> None:
- """Observer.stop() + join. Idempotent."""
- if not self._started:
- return
- self._started = False
- observer = self._observer
- self._observer = None
- if observer is None:
- with self._lock:
- self._watches.clear()
- self._last_emit.clear()
- self._latest_in_root.clear()
- return
- try:
- observer.stop()
- await asyncio.to_thread(observer.join, _STOP_TIMEOUT_S)
- except Exception: # noqa: BLE001
- logger.debug("FileSystemProbe stop failed", exc_info=True)
- with self._lock:
- self._watches.clear()
- self._last_emit.clear()
- self._latest_in_root.clear()
-
- # ---- Watch-Management --------------------------------------------------
-
- def watch(self, repo_root: str) -> bool:
- """Adds a watch. Returns True if newly registered.
-
- If the _max_watched_roots cap is reached: returns False + warning, no crash.
- On watchdog error: returns False + warning.
- Codex-MAJOR-4-Fix: blocks drive roots, $WINDIR, $PROGRAMFILES,
- and the home folder directly.
- """
- if not self._started or self._observer is None:
- return False
- repo_root = str(Path(repo_root).resolve()) if repo_root else ""
- if not repo_root:
- return False
- # Codex-MAJOR-4-Fix (2026-04-26): reject hard-blocked roots.
- # Otherwise a bug in the context resolver could recursively watch
- # C:\ or the home folder — privacy + resource risk.
- if _is_forbidden_root(repo_root):
- logger.warning(
- "FileSystemProbe.watch: forbidden root %s blocked (system/home dir)",
- repo_root,
- )
- return False
- with self._lock:
- if repo_root in self._watches:
- return False
- if len(self._watches) >= self._max_watched_roots:
- logger.warning(
- "FileSystemProbe: cap %d reached, dropping watch %s",
- self._max_watched_roots, repo_root,
- )
- return False
- try:
- handler = _SaveHandler(probe=self, repo_root=repo_root)
- watch = self._observer.schedule(handler, repo_root, recursive=True)
- except (OSError, FileNotFoundError) as exc:
- logger.warning("FileSystemProbe.watch(%s) failed: %s", repo_root, exc)
- return False
- with self._lock:
- self._watches[repo_root] = watch
- return True
-
- def unwatch(self, repo_root: str) -> None:
- repo_root = str(Path(repo_root).resolve()) if repo_root else ""
- with self._lock:
- watch = self._watches.pop(repo_root, None)
- self._last_emit = {k: v for k, v in self._last_emit.items()
- if not k.startswith(repo_root)}
- self._latest_in_root.pop(repo_root, None)
- if watch is not None and self._observer is not None:
- try:
- self._observer.unschedule(watch)
- except (KeyError, ValueError):
- pass
-
- # ---- Probe-Interface (synchroner state-read) ---------------------------
-
- async def probe(
- self, *, cwd: str | None, process_name: str = "",
- ) -> dict[str, Any]:
- """Returns {open_file_hint: str | None}.
-
- ``open_file_hint`` is the most recently modified file path within the
- project root of cwd. None if no save was seen or cwd is not watched.
- """
- if cwd is None:
- return {"open_file_hint": None}
- try:
- # Path.resolve is a filesystem metadata lookup (fast, microseconds).
- # ASYNC240 disabled: probe() runs within the 200 ms budget, which is fine.
- cwd_resolved = str(Path(cwd).resolve()) # noqa: ASYNC240
- except (OSError, ValueError):
- return {"open_file_hint": None}
- with self._lock:
- # Match against any watched root that is parent of cwd
- for root in self._watches:
- if cwd_resolved == root or cwd_resolved.startswith(root + "\\") \
- or cwd_resolved.startswith(root + "/"):
- return {"open_file_hint": self._latest_in_root.get(root)}
- return {"open_file_hint": None}
-
- # ---- Internal: Event-Handler-Bridge ------------------------------------
-
- def _on_save_event(self, *, path: str, repo_root: str) -> None:
- """Called from the watchdog thread — bridges onto the asyncio loop.
-
- Debounce: 200 ms window per path. Redundant events within the window
- are dropped. If the path is inside a blacklisted subdirectory
- (.git, __pycache__), the event is skipped.
- """
- # Blacklist filter
- rel = path[len(repo_root):].lstrip("/\\") if path.startswith(repo_root) else path
- first_segment = rel.split("/")[0].split("\\")[0]
- if first_segment in _PATHS_BLACKLIST_PREFIXES:
- return
-
- # Debounce
- now = time.monotonic()
- with self._lock:
- last = self._last_emit.get(path, 0.0)
- if now - last < _DEBOUNCE_S:
- return
- self._last_emit[path] = now
- self._latest_in_root[repo_root] = path
-
- # Bus publish via loop.call_soon_threadsafe (NEVER directly in the watchdog thread)
- loop = self._loop
- if loop is None or loop.is_closed():
- return
- try:
- loop.call_soon_threadsafe(
- self._publish_save_event, path, repo_root,
- )
- except RuntimeError:
- pass
-
- def _publish_save_event(self, path: str, repo_root: str) -> None:
- """Executed on the asyncio loop. Schedules bus.publish.
-
- Code-reviewer-MAJOR-M2-Fix (2026-04-26): hold the task reference in
- ``_pending_publish_tasks`` + add_done_callback for cleanup.
- Otherwise GC can collect the task mid-flight and bus.publish is
- never awaited (silent event loss).
- """
- from jarvis.core.events import FileSaved # noqa: PLC0415
- try:
- task = asyncio.create_task(self._bus.publish(
- FileSaved(path=path, repo_root=repo_root),
- ))
- self._pending_publish_tasks.add(task)
- task.add_done_callback(self._pending_publish_tasks.discard)
- except RuntimeError:
- pass
-
-
-class _SaveHandler:
- """watchdog FileSystemEventHandler-compatible (duck-typed).
-
- We avoid direct inheritance from FileSystemEventHandler so that
- the top-level module import of watchdog remains optional.
- """
-
- def __init__(self, *, probe: FileSystemProbe, repo_root: str) -> None:
- self._probe = probe
- self._repo_root = repo_root
-
- def dispatch(self, event: Any) -> None:
- # watchdog calls dispatch for all events
- if event.is_directory:
- return
- if event.event_type not in ("modified", "created", "moved"):
- return
- path = getattr(event, "dest_path", None) or getattr(event, "src_path", "")
- if not path:
- return
- try:
- self._probe._on_save_event(path=path, repo_root=self._repo_root) # noqa: SLF001
- except Exception: # noqa: BLE001
- logger.debug("FileSystemProbe save-event-handler crashed", exc_info=True)
diff --git a/jarvis/awareness/probes/git.py b/jarvis/awareness/probes/git.py
deleted file mode 100644
index 3ed27a3edd..0000000000
--- a/jarvis/awareness/probes/git.py
+++ /dev/null
@@ -1,182 +0,0 @@
-"""GitProbe — branch detection via .git/HEAD or asyncio git subprocess.
-
-Strategy (in order):
-1. Direct file read of .git/HEAD in cwd (fast, no subprocess) — PRIMARY
-2. asyncio subprocess fallback ``git rev-parse --abbrev-ref HEAD`` — if (1) fails
-3. None — if both fail or there is no repo
-
-Hard Negatives §9:
-- NO sync ``subprocess.run`` — everything uses ``asyncio.create_subprocess_exec``
-- 200 ms hard timeout per call (``asyncio.wait_for``)
-- Errors MUST NOT propagate — ``try/except`` returns ``None``
-- Probe is defensive: any unknown error -> ``None`` instead of crash
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-from pathlib import Path
-from typing import Any
-
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
-
-logger = logging.getLogger(__name__)
-
-_HEAD_FILE_TIMEOUT_S = 0.05 # 50 ms for .git/HEAD read
-_SUBPROCESS_TIMEOUT_S = 0.15 # 150 ms for git subprocess
-_TOTAL_BUDGET_S = 0.20 # 200 ms hard cap (Plan §9 AC)
-
-
-class GitProbe:
- """Probe for the git branch of the active process cwd."""
-
- name: str = "git"
-
- async def probe(self, *, cwd: str | None, process_name: str = "") -> dict[str, Any]:
- """Returns ``{git_branch: str | None}``. No crash on any failure."""
- if cwd is None:
- return {"git_branch": None}
-
- # Strategy 1: .git/HEAD direct-read (fast, no subprocess)
- try:
- branch = await asyncio.wait_for(
- asyncio.to_thread(self._read_head_file, cwd),
- timeout=_HEAD_FILE_TIMEOUT_S,
- )
- if branch is not None:
- return {"git_branch": branch}
- except (TimeoutError, asyncio.CancelledError):
- return {"git_branch": None}
- except Exception: # noqa: BLE001
- # File read failed unexpectedly — fall through to subprocess
- logger.debug("GitProbe head-file read failed", exc_info=True)
-
- # Strategy 2: asyncio subprocess fallback
- try:
- return {"git_branch": await asyncio.wait_for(
- self._git_subprocess(cwd),
- timeout=_SUBPROCESS_TIMEOUT_S,
- )}
- except (TimeoutError, asyncio.CancelledError):
- return {"git_branch": None}
- except Exception: # noqa: BLE001
- logger.debug("GitProbe subprocess failed", exc_info=True)
- return {"git_branch": None}
-
- @staticmethod
- def _read_head_file(cwd: str) -> str | None:
- """Reads ``.git/HEAD`` directly. Returns the branch name or SHA prefix for detached HEAD.
-
- Handles 3 cases:
- - ``.git/HEAD`` is a regular file (standard repo)
- - ``.git`` is a FILE containing ``"gitdir: ../<actual-path>"`` (worktree repo)
- - ``.git`` does not exist (not a repo)
-
- Returns ``None`` on any unknown failure.
- """
- try:
- git_dir_or_file = Path(cwd) / ".git"
- if not git_dir_or_file.exists():
- return None
-
- # Worktree repo: .git is a file containing "gitdir: ..."
- if git_dir_or_file.is_file():
- content = git_dir_or_file.read_text(encoding="utf-8").strip()
- if content.startswith("gitdir:"):
- raw = content[len("gitdir:"):].strip()
- raw_path = Path(raw)
- # Codex-MINOR-m5-Fix (2026-04-26): resolve relative gitdir
- # against cwd instead of os.getcwd() — modern git usually
- # writes absolute paths, but `git worktree add --relative`
- # or submodules write a relative path.
- actual_git_dir = (
- raw_path if raw_path.is_absolute()
- else (Path(cwd) / raw_path).resolve()
- )
- head_path = actual_git_dir / "HEAD"
- else:
- return None
- else:
- head_path = git_dir_or_file / "HEAD"
-
- if not head_path.exists():
- return None
-
- head_content = head_path.read_text(encoding="utf-8").strip()
- if head_content.startswith("ref: refs/heads/"):
- return head_content[len("ref: refs/heads/"):]
- # detached HEAD: SHA -> return first 8 chars
- if len(head_content) >= 8:
- return head_content[:8]
- return None
- except (OSError, UnicodeDecodeError):
- return None
-
- async def _git_subprocess(self, cwd: str) -> str | None:
- """asyncio subprocess for ``git rev-parse --abbrev-ref HEAD``.
-
- Returns the branch name or ``None``. Any failure (FileNotFoundError for
- a missing git binary, non-zero exit, decode error) returns ``None``.
-
- Codex-BLOCKER-2-Fix (2026-04-26): on every failure path, proper
- subprocess cleanup with ``terminate -> wait_for(wait, 0.05) -> kill ->
- wait`` in finally — otherwise zombie risk on cancel. CancelledError
- is cleaned up and re-raised so that manager shutdown propagates
- correctly (instead of being silently swallowed as "no branch").
- """
- try:
- proc = await asyncio.create_subprocess_exec(
- "git", "rev-parse", "--abbrev-ref", "HEAD",
- cwd=cwd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- except (FileNotFoundError, OSError, NotImplementedError):
- return None
- try:
- try:
- stdout, _stderr = await proc.communicate()
- except asyncio.CancelledError:
- # Cleanup + re-raise so that shutdown propagates correctly
- await self._cleanup_proc(proc)
- raise
- except OSError:
- await self._cleanup_proc(proc)
- return None
- if proc.returncode != 0:
- return None
- try:
- branch = stdout.decode().strip()
- return branch or None
- except UnicodeDecodeError:
- return None
- finally:
- # Defensive: if the process is still alive after communicate
- # (e.g. due to a race), do explicit cleanup. Idempotent.
- if proc.returncode is None:
- await self._cleanup_proc(proc)
-
- @staticmethod
- async def _cleanup_proc(proc: asyncio.subprocess.Process) -> None:
- """Guarantees a dead subprocess: terminate -> wait 50 ms -> kill -> wait.
-
- No raise — all cleanup errors are swallowed (probe defense).
- """
- try:
- proc.terminate()
- except (OSError, ProcessLookupError):
- pass
- try:
- await asyncio.wait_for(proc.wait(), timeout=0.05)
- return
- except (TimeoutError, OSError):
- pass
- try:
- proc.kill()
- except (OSError, ProcessLookupError):
- pass
- try:
- await asyncio.wait_for(proc.wait(), timeout=0.05)
- except (TimeoutError, OSError):
- pass
diff --git a/jarvis/awareness/prompts.py b/jarvis/awareness/prompts.py
deleted file mode 100644
index cbc76feea8..0000000000
--- a/jarvis/awareness/prompts.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""Verdichter prompts. Plan §6 default variant.
-
-NOTE: Lead replaces VERDICHTER_SYSTEM_PROMPT with tournament-winner after
-a 3-variant comparison against the code-reviewer subagent. Only the
-default variant 1:1 from the plan is stored here.
-"""
-from __future__ import annotations
-
-import datetime as _dt
-from typing import Any
-
-# Few-shot with contrastive negative example chosen (Tournament 2026-04-26).
-# Rationale: Haiku 4.5 obeys declarative verb blacklists (V2) less reliably than
-# an identical input with a correct vs. hallucinated output + explanation in the
-# prompt itself. Primary hallucination risk is content inference from tab titles
-# ("debuggt TypeError" from a Stack Overflow tab) — Plan §6 hard negative.
-# Third example covers degenerate frames (empty titles, settings dialogs).
-# On pattern drift: extend tests in test_verdichter, do NOT soften this prompt.
-# V4 iteration (stuck-pattern + PII-whitelist) is a follow-up.
-VERDICHTER_SYSTEM_PROMPT = """Du bist ein Story-Verdichter für einen persönlichen AI-Assistenten.
-
-Du bekommst Window-Frames + Events. Schreibe EINEN deutschen Absatz (max 120 Worte) der NUR Beobachtungen enthält — KEINE Inhaltsvermutungen.
-
-Beispiel ✅ KORREKT:
-Input: 4 Frames Code.exe mit "main.py", 2 Frames Chrome.exe mit "Stack Overflow", zurück zu Code.exe.
-Output: "Der Nutzer war 18min in Code.exe mit main.py aktiv, wechselte für ca. 3min zu Chrome.exe (Stack-Overflow-Tab) und kehrte zurück zu Code.exe. Aktueller Fokus: main.py."
-
-Beispiel ❌ HALLUZINATION (NICHT machen):
-Input: gleich wie oben.
-Output: "Der Nutzer debuggt main.py, hatte einen Fehler, googelte auf Stack Overflow nach einer Lösung und arbeitet jetzt weiter."
-Begründung: "debuggt", "hatte einen Fehler", "suchte nach Lösung" sind Vermutungen — du siehst nur Window-Titles, nicht den Code-Editor-Inhalt.
-
-Beispiel ✅ KORREKT (degenerierter Input):
-Input: 3 Frames mit window_title="" und process_name="Explorer.exe".
-Output: "Wenig Aktivität — 3 Frames in Explorer.exe ohne erkennbaren Window-Title. Kein klarer Fokus."
-
-Regeln:
-- EIN Absatz, kein Markdown, keine Aufzählung.
-- Nenne Datei-/Project-Namen NUR wenn im window_title sichtbar.
-- Markiere Wiederholungs-Pattern als "Wechsel zwischen X und Y" (NICHT "ist verwirrt").
-- Bei kryptischen/leeren Titles: "unbekannter Inhalt" oder "kein Window-Title".
-""" # i18n-allow: VERDICHTER_SYSTEM_PROMPT is the runtime LLM prompt that dictates the German-language board/awareness "story" output shown to the user — translating it would change the produced output language
-
-
-_HEADER = "# Frames + Events der letzten Minuten:" # i18n-allow: header of the German-language Verdichter LLM input block (VERDICHTER_SYSTEM_PROMPT expects German)
-_TRUNC_MARKER = "[...]"
-
-
-def _format_ts_ns(ts_ns: int | None) -> str:
- """Converts a nanosecond timestamp to HH:MM:SS.
-
- On ``None`` or an invalid value: ``"??:??:??"`` — we do not want the
- Verdichter to crash when a frame arrives without a timestamp.
- """
- if not ts_ns:
- return "??:??:??"
- try:
- seconds = float(ts_ns) / 1_000_000_000.0
- return _dt.datetime.fromtimestamp(seconds).strftime("%H:%M:%S")
- except (OverflowError, OSError, ValueError):
- return "??:??:??"
-
-
-def _frame_ts(frame: dict[str, Any]) -> int | None:
- """Retrieves the timestamp from various frame schemas.
-
- A1-FrameSnapshot uses ``timestamp_ns``, as do persisted frames in
- ``awareness_frames``. Tests/recall reads may also supply ``ts_ns`` —
- both are accepted.
- """
- return frame.get("timestamp_ns") or frame.get("ts_ns")
-
-
-def _frame_process(frame: dict[str, Any]) -> str:
- """Process name from frame; accepts multiple aliases."""
- return (
- frame.get("process_name")
- or frame.get("active_process")
- or frame.get("process")
- or "?"
- )
-
-
-def _frame_title(frame: dict[str, Any]) -> str:
- """Window title from frame; accepts multiple aliases."""
- return (
- frame.get("window_title")
- or frame.get("active_window_title")
- or frame.get("title")
- or ""
- )
-
-
-def _event_ts(event: dict[str, Any]) -> int | None:
- """Timestamp from event dict."""
- return event.get("ts_ns") or event.get("timestamp_ns")
-
-
-def _event_kind(event: dict[str, Any]) -> str:
- return event.get("kind") or event.get("event_kind") or "?"
-
-
-def _event_details(event: dict[str, Any]) -> str:
- """Renders event payload compactly (single line)."""
- payload = event.get("payload") or event.get("details") or {}
- if not payload:
- return ""
- if isinstance(payload, str):
- return payload
- if isinstance(payload, dict):
- # compact: key=value pairs, no newlines
- parts = []
- for k, v in payload.items():
- v_str = str(v).replace("\n", " ").strip()
- if len(v_str) > 60:
- v_str = v_str[:57] + "..."
- parts.append(f"{k}={v_str}")
- return ", ".join(parts)
- return str(payload)[:120]
-
-
-def build_verdichter_prompt(
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- max_chars: int = 3200, # ~800 tokens * 4 chars/token rough
-) -> str:
- """Renders a frame+event list as a compact Markdown block.
-
- Format::
-
- # Frames + Events der letzten Minuten:
- - [HH:MM:SS] <process>: <window_title>
- - [HH:MM:SS] EVENT <kind>: <details>
- ...
- Dominante App: <primary_app>
-
- Truncated with a ``[...]`` prefix when > ``max_chars`` (chronological
- cut from front — the NEWEST entries are preserved).
-
- Expects ``frames`` as ``list[dict]`` with keys: ``timestamp_ns``,
- ``process_name``, ``window_title`` (or ``active_*`` variants —
- handled). ``events`` as ``list[dict]`` with keys: ``ts_ns``,
- ``kind``, ``payload`` (optional).
- """
- # Annotated list: (ts_ns, line) — sort by ts_ns asc
- lines: list[tuple[int, str]] = []
- for frame in frames:
- ts = _frame_ts(frame) or 0
- proc = _frame_process(frame)
- title = _frame_title(frame)
- line = f"- [{_format_ts_ns(ts)}] {proc}: {title}".rstrip()
- lines.append((int(ts), line))
- for event in events:
- ts = _event_ts(event) or 0
- kind = _event_kind(event)
- details = _event_details(event)
- suffix = f": {details}" if details else ""
- line = f"- [{_format_ts_ns(ts)}] EVENT {kind}{suffix}"
- lines.append((int(ts), line))
-
- lines.sort(key=lambda x: x[0])
- body_lines = [line for _, line in lines]
-
- footer = f"Dominante App: {primary_app}" # i18n-allow: label of the German-language Verdichter LLM input block (VERDICHTER_SYSTEM_PROMPT expects German)
-
- # Build full block, then truncate from front (keep newest tail)
- body = "\n".join(body_lines)
- block = f"{_HEADER}\n{body}\n\n{footer}" if body else f"{_HEADER}\n(keine Daten)\n\n{footer}" # i18n-allow: same German-language Verdichter input block
-
- if len(block) <= max_chars:
- return block
-
- # Truncate from front: drop oldest lines until block fits.
- # Reserve space for header + truncation marker + footer.
- fixed_overhead = len(_HEADER) + 1 + len(_TRUNC_MARKER) + 2 + len(footer) + 1
- budget = max(max_chars - fixed_overhead, 0)
- # Walk from end (newest) backwards, accumulating lines until budget hit.
- kept_reversed: list[str] = []
- used = 0
- for line in reversed(body_lines):
- line_len = len(line) + 1 # +1 for newline
- if used + line_len > budget:
- break
- kept_reversed.append(line)
- used += line_len
- kept = list(reversed(kept_reversed))
- truncated_body = "\n".join(kept) if kept else ""
- parts = [_HEADER, _TRUNC_MARKER]
- if truncated_body:
- parts.append(truncated_body)
- parts.extend(["", footer])
- return "\n".join(parts)
diff --git a/jarvis/awareness/quotas.py b/jarvis/awareness/quotas.py
deleted file mode 100644
index f53687142b..0000000000
--- a/jarvis/awareness/quotas.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Storage quotas for awareness persistence (Phase A2+).
-
-In A0 only the data class exists. In A2 the ``StoryTracker`` calls
-``would_exceed()`` before every episode insert — on a cap violation the
-retention policy kicks in (prune the oldest episode or block the insert).
-Bytes are weighted ahead of count because disk pressure (full disk) has
-higher consequences than index bloat.
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True, slots=True)
-class StorageQuota:
- """Bytes and episode cap as a config snapshot.
-
- Frozen because it is built from config at init time and is not
- mutated at runtime (hot-reload creates a new instance).
- """
- max_bytes: int = 50 * 1024 * 1024 # 50 MiB Default
- max_episodes: int = 1000
-
- def would_exceed(
- self,
- *,
- current_bytes: int,
- current_episode_count: int,
- ) -> tuple[bool, str]:
- """Returns (exceeded, reason).
-
- Reason is empty when below cap; otherwise ``"max_bytes_reached"``
- or ``"max_episodes_reached"``. The bytes cap takes priority —
- disk pressure > index pressure.
- """
- if current_bytes >= self.max_bytes:
- return True, "max_bytes_reached"
- if current_episode_count >= self.max_episodes:
- return True, "max_episodes_reached"
- return False, ""
diff --git a/jarvis/awareness/salience.py b/jarvis/awareness/salience.py
deleted file mode 100644
index efd060f421..0000000000
--- a/jarvis/awareness/salience.py
+++ /dev/null
@@ -1,132 +0,0 @@
-"""Rule-based salience scorer for L2 story tracking.
-
-Assigns a score 0-100 to frames (``FrameSnapshot``) and bus events.
-Frames with score < ``SALIENCE_THRESHOLD`` are discarded by the
-``StoryTracker`` before they enter the Verdichter input — token budget
-protection.
-
-The scorer is intentionally **rule-based, not an LLM**: deterministic,
-no additional brain round-trip on the voice critical path.
-
-Plan reference: §6 "Salience Scorer (verbindlich, rule-based)".
-"""
-from __future__ import annotations
-
-from typing import Any
-
-from jarvis.awareness.state import FrameSnapshot
-
-# Frames below this score are NOT included in episode condensation.
-SALIENCE_THRESHOLD: int = 30
-
-# Lower-case for case-insensitive matching against ``process_name.lower()``.
-# Tray helpers / shell UI are noise — the user is not "working" here.
-BORING_PROCESSES: frozenset[str] = frozenset({
- "explorer.exe",
- "shellexperiencehost.exe",
- "searchhost.exe",
- "startmenuexperiencehost.exe",
- "textinputhost.exe",
- "ctfmon.exe",
- "dwm.exe",
-})
-
-# Threshold for "long dwell in the same frame" (>2min ⇒ +10).
-_LONG_DWELL_NS: int = 120_000_000_000
-
-# Default score when no prev frame exists (first frame of the session).
-# Neutral mid-score so the first real workspace frame does not immediately
-# fall below SALIENCE_THRESHOLD — the BORING penalty still applies.
-_BASE_SCORE_NO_PREV: int = 50
-
-
-class SalienceScorer:
- """Rule-based score 0-100 for frames and events.
-
- No LLM, no I/O — pure function. Called exactly once per frame by the
- ``StoryTracker``.
- """
-
- def score_frame(
- self, frame: FrameSnapshot, *, prev: FrameSnapshot | None,
- ) -> int:
- """Score 0-100 for a single frame.
-
- Components (additive, then clamped to [0, 100]):
-
- - +20 if ``process_name`` changed relative to ``prev`` (app switch)
- - +30 if ``window_title`` changed but process stayed the same
- (file/tab switch within the same app)
- - +20 if ``git_branch`` (non-None in both frames) differs
- - +10 if dwell time ``frame.timestamp_ns - prev.timestamp_ns``
- > 2 min (user worked on the same frame for a long time)
- - -50 if ``process_name.lower()`` is in ``BORING_PROCESSES``
-
- With ``prev=None`` (first frame): base score 50 + BORING penalty.
- Never raises NULL/Exception — the caller relies on that guarantee.
- """
- process_name = frame.active_process_name
- boring_penalty = -50 if process_name.lower() in BORING_PROCESSES else 0
-
- if prev is None:
- return self._clamp(_BASE_SCORE_NO_PREV + boring_penalty)
-
- score = 0
-
- # App switch: strongest signal for an episode trigger.
- process_changed = process_name != prev.active_process_name
- if process_changed:
- score += 20
-
- # Title switch within the same app (only when NO process switch,
- # otherwise we would double-count — an app switch implies a title change).
- elif frame.active_window_title != prev.active_window_title:
- score += 30
-
- # Git branch change (only when both are set — None does not compare).
- if (
- frame.git_branch is not None
- and prev.git_branch is not None
- and frame.git_branch != prev.git_branch
- ):
- score += 20
-
- # Long dwell time (>2 min) → user worked focused on the same frame.
- if (frame.timestamp_ns - prev.timestamp_ns) > _LONG_DWELL_NS:
- score += 10
-
- score += boring_penalty
- return self._clamp(score)
-
- def score_event(
- self, event_kind: str, payload: dict[str, Any] | None = None,
- ) -> int:
- """Score 0-100 for bus events (FileSaved, BrainTurnCompleted, …).
-
- Mapping (default 0 for unknown ``event_kind``):
-
- - ``"FileSaved"`` → 40
- - ``"TerminalExit"`` → 60 if ``payload["exit_code"] != 0`` (error!),
- otherwise 20 (clean exit is less interesting)
- - ``"BrainTurnCompleted"`` → 50 (response from main Jarvis = story marker)
- - ``"IdleExited"`` → 20 (attention returns)
- """
- if event_kind == "FileSaved":
- return 40
- if event_kind == "TerminalExit":
- exit_code = (payload or {}).get("exit_code", 0)
- return 60 if exit_code != 0 else 20
- if event_kind == "BrainTurnCompleted":
- return 50
- if event_kind == "IdleExited":
- return 20
- return 0
-
- @staticmethod
- def _clamp(score: int) -> int:
- """Clamp score to [0, 100] — hard negative §6."""
- if score < 0:
- return 0
- if score > 100:
- return 100
- return score
diff --git a/jarvis/awareness/state.py b/jarvis/awareness/state.py
deleted file mode 100644
index edec7a357d..0000000000
--- a/jarvis/awareness/state.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""Data models for the L1 live-frame layer.
-
-``FrameSnapshot`` is immutable (frozen+slots), created by the
-``WindowFocusWatcher`` in phase A1 and written into
-``AwarenessState.current_frame`` in the drain loop. Immutability lets
-the flight recorder deterministically replay every frame.
-
-``AwarenessState`` is mutable (classic dataclass without ``frozen``)
-because the ``AwarenessManager`` holds it as live state and tools such
-as ``awareness-snapshot`` read from it synchronously — without a
-brain/IO round-trip.
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from jarvis.awareness.working_set import WorkingSet
-
-
-# Frames older than this are no longer presented as the *current* foreground
-# window — instead the snapshot marks them as a stale "last observed" reading.
-# Aligned with the 5-minute idle threshold (AwarenessWatchersConfig
-# .idle_threshold_minutes / IdleDetector default 300 s): once a window has not
-# changed for that long, asserting it is "currently active" is no longer
-# honest. Root cause of the 2026-06-17 "BridgeSpace und WhatsApp" overclaim was
-# an ~82-min-old current_frame rendered verbatim as the live state.
-_FRAME_MAX_AGE_S: float = 300.0
-
-
-@dataclass(frozen=True, slots=True)
-class FrameSnapshot:
- """A single L1 frame.
-
- Mandatory fields are set by the ``WindowFocusWatcher`` (A1).
- Optional fields are populated only by phase-A5 probes
- (GitProbe, IDE-LSP/MCP). ``idle_since_ns`` carries the timestamp
- of the last input when the ``IdleDetector`` actively reports "idle".
- """
- timestamp_ns: int
- active_window_title: str
- active_process_name: str
- active_pid: int
- is_capture_allowed: bool
- git_branch: str | None = None
- open_file_hint: str | None = None
- idle_since_ns: int | None = None
-
-
-@dataclass
-class AwarenessState:
- """Mutable live state. Held by the ``AwarenessManager``."""
- current_frame: FrameSnapshot | None = None
- last_episode_summary: str = "" # populated in A2 (StoryTracker)
- last_episode_id: int | None = None # populated in A2
- # A4: WorkingSet reference, set by AwarenessManager. ``None`` in
- # A0/A1 use without manager wiring. ``snapshot_for_prompt`` renders
- # the working set when it has > 1 slot (otherwise the "last episode"
- # line is sufficient).
- working_set: WorkingSet | None = field(default=None)
- is_idle: bool = False
-
- def snapshot_for_prompt(
- self, max_chars: int = 600, max_age_s: float = _FRAME_MAX_AGE_S,
- ) -> str:
- """Compact plain-text snapshot for system-prompt injection.
-
- A1: renders ``current_frame`` (title, process, PID) plus optional
- idle status. A2 appends ``last_episode_summary``. A4 appends
- the working set when more than 1 context is active (multiple
- drawers → user needs the comparison). Never raw JSON.
-
- Freshness guard (2026-06-17): the foreground frame is only presented
- as the *current* window when it is younger than ``max_age_s``.
- An older frame is rendered as a clearly-flagged "last observed"
- reading instead of being narrated as live — otherwise the brain
- reports a stale window state as "currently active" (the root cause
- of the "BridgeSpace und WhatsApp" overclaim). A one-line scope note
- is always appended so the brain never presents this focus history as
- a complete list of every open window/tab.
-
- When ``current_frame is None``: returns an empty string. Truncated
- to ``max_chars`` with a ``…`` suffix.
- """
- if self.current_frame is None:
- return ""
-
- import time as _time # local — no module-level import needed
-
- cur = self.current_frame
- age_s = max(0, (_time.time_ns() - cur.timestamp_ns) // 1_000_000_000)
- descriptor = (
- f"{cur.active_window_title} "
- f"({cur.active_process_name}, pid={cur.active_pid})"
- )
-
- parts: list[str]
- if age_s <= max_age_s:
- parts = [f"Currently focused window: {descriptor}"]
- else:
- age_min = age_s // 60
- parts = [
- f"Last observed foreground window ~{age_min} min ago "
- f"(possibly stale — no live screen view right now): {descriptor}"
- ]
-
- # Scope honesty: awareness only tracks the focused window + recently
- # used apps, never an enumeration of all open windows. Stating this
- # stops the brain from claiming "only X and Y are open on your PC".
- parts.append(
- "(Focused-window history only — NOT a complete list of "
- "open windows/tabs.)"
- )
-
- if self.is_idle and cur.idle_since_ns is not None:
- idle_seconds = max(0, (_time.time_ns() - cur.idle_since_ns) // 1_000_000_000)
- idle_minutes = idle_seconds // 60
- parts.append(f"[Idle seit {idle_minutes}min]")
-
- # A4: multi-context render when > 1 slot is active. With only 1 slot,
- # the working-set render is redundant next to the "last episode" line.
- if self.working_set is not None:
- ws_text = self.working_set.render_for_prompt()
- if ws_text:
- parts.append(ws_text)
-
- if self.last_episode_summary: # populated from A2 onwards
- parts.append(f"Letzte Episode: {self.last_episode_summary}")
-
- text = "\n".join(parts)
- if len(text) > max_chars:
- text = text[: max_chars - 1] + "…"
- return text
diff --git a/jarvis/awareness/story.py b/jarvis/awareness/story.py
deleted file mode 100644
index 744bfb9e9a..0000000000
--- a/jarvis/awareness/story.py
+++ /dev/null
@@ -1,491 +0,0 @@
-"""StoryTracker — bus subscriber for L2 episode condensation.
-
-Lifecycle:
-
-1. Instantiated by ``AwarenessManager.start()`` (when
- ``config.story.enabled and config.verdichter.enabled``).
-2. Subscribes to ``FrameUpdated``, ``IdleEntered``, ``ResponseGenerated``.
-3. Discards privacy-filter-blocked frames without processing them
- (plan §6 hard negative — NO PII frame in Verdichter input).
-4. For each salient frame (``SalienceScorer.score_frame >= 30``):
- append to ``EpisodeBuilder``.
-5. On trigger (app switch / idle / hard timer / stop): snapshot the
- builder (atomic, under lock), call the Verdichter (LOCK-FREE),
- persist the episode, update ``state.last_episode_summary``, publish
- ``EpisodeRecorded`` event.
-
-Hard negatives (all from plan §6):
-- NO spawn_worker — the Verdichter has its own brain instance.
-- Synchronous DB inserts forbidden — everything via ``await recall.record_episode``.
-- Privacy-filter-blocked frames NEVER in Verdichter input.
-- Episodes < 60 s = spam, skip flush (except trigger ``"stop"``).
-- Builder cap: max ``buffer_max`` frames; overflow forces a flush.
-
-Concurrency (Codex-BLOCKER B1+B2 fix, 2026-05-11):
-
-Previously each bus handler held ``_lock`` across the ~5 s Verdichter call,
-blocking every subsequent ``on_frame_updated`` / ``on_idle_entered`` /
-``on_response_generated`` during the async brain RPC (B1). Additionally
-a frame could be lost between the snapshot and ``self._builder = None`` (B2).
-
-New pattern: snapshot (sync, under lock) and dispatch (async, lock-free)
-are separated:
-
-- ``_extract_snapshot_locked``: SYNC. Caller MUST hold ``_lock``. Validates
- the builder against the spam guard, extracts a double-buffer snapshot via
- ``EpisodeBuilder.detach_frames``/``detach_events`` (B2), sets
- ``self._builder = None``, and returns a frozen ``_FlushSnapshot``
- dataclass. No ``await``, no yield point.
-- ``_run_flush``: ASYNC. Caller MUST have released ``_lock``. Calls the
- Verdichter, persists in ``RecallStore``, updates ``manager.state``, and
- publishes ``EpisodeRecorded``.
-
-Every bus handler follows the same pattern:
-
- pending: list[_FlushSnapshot] = []
- async with self._lock:
- snap = self._extract_snapshot_locked(trigger_kind="...")
- if snap is not None:
- pending.append(snap)
- for snap in pending:
- await self._run_flush(snap)
-
-``_on_frame_updated`` may extract up to two snapshots in a single lock
-acquisition (app-switch flush + buffer/max-duration overflow after the new
-``add_frame``); both are dispatched in order outside the lock.
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import time
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
-
-from jarvis.awareness.episode import (
- Episode,
- EpisodeBuilder,
- primary_app_from_snapshot,
-)
-from jarvis.awareness.salience import SALIENCE_THRESHOLD, SalienceScorer
-from jarvis.core.events import (
- EpisodeRecorded,
- FrameUpdated,
- IdleEntered,
- ResponseGenerated,
-)
-
-if TYPE_CHECKING:
- from jarvis.awareness.config import AwarenessStoryConfig
- from jarvis.awareness.manager import AwarenessManager
- from jarvis.awareness.state import FrameSnapshot
- from jarvis.awareness.verdichter import Verdichter
- from jarvis.core.bus import EventBus
- from jarvis.memory.recall import RecallStore
-
-logger = logging.getLogger(__name__)
-
-_TIMER_STOP_TIMEOUT_S: float = 1.5
-
-_FORCED_TRIGGERS: frozenset[str] = frozenset({
- "stop", "buffer_overflow", "max_duration",
-})
-
-
-@dataclass(frozen=True, slots=True)
-class _FlushSnapshot:
- """Immutable snapshot of an ``EpisodeBuilder``, ready for lock-free
- persistence.
-
- Fully decoupled from the builder — the builder can be reused or
- discarded after the snapshot without touching it. This is the B2
- guarantee (atomic double-buffer).
- """
- trigger_kind: str
- started_at_ns: int
- frames: list[dict[str, Any]]
- events: list[dict[str, Any]]
- primary_app: str
- frame_count: int
-
-
-class StoryTracker:
- """Bus subscriber. Accumulates salient frames and events, flushes on trigger."""
-
- def __init__(
- self,
- *,
- manager: AwarenessManager,
- bus: EventBus,
- recall: RecallStore,
- verdichter: Verdichter,
- config: AwarenessStoryConfig,
- scorer: SalienceScorer | None = None,
- ) -> None:
- self._manager = manager
- self._bus = bus
- self._recall = recall
- self._verdichter = verdichter
- self._config = config
- self._scorer = scorer or SalienceScorer()
-
- self._builder: EpisodeBuilder | None = None
- self._prev_frame: FrameSnapshot | None = None
- self._lock = asyncio.Lock()
- self._timer_task: asyncio.Task[None] | None = None
- self._started: bool = False
-
- # ---- Lifecycle ----------------------------------------------------------
-
- async def start(self) -> None:
- """Subscribes to the bus and starts the hard-timer task. Idempotent."""
- if self._started:
- return
- self._bus.subscribe(FrameUpdated, self._on_frame_updated)
- self._bus.subscribe(IdleEntered, self._on_idle_entered)
- self._bus.subscribe(ResponseGenerated, self._on_response_generated)
- loop = asyncio.get_running_loop()
- self._timer_task = loop.create_task(
- self._hard_timer_loop(), name="story-tracker-timer",
- )
- self._started = True
-
- async def stop(self) -> None:
- """Final flush + cancel timer. Best-effort.
-
- B1 fix: snapshot under lock, dispatch lock-free — so the final
- flush does not block a parallel bus handler either (edge case
- during shutdown races).
- """
- if not self._started:
- return
- self._started = False
-
- task = self._timer_task
- self._timer_task = None
- if task is not None:
- task.cancel()
- try:
- await asyncio.wait_for(task, timeout=_TIMER_STOP_TIMEOUT_S)
- except (TimeoutError, asyncio.CancelledError):
- pass
- except Exception: # noqa: BLE001
- logger.debug(
- "StoryTracker timer task ended with exception",
- exc_info=True,
- )
-
- snap: _FlushSnapshot | None
- async with self._lock:
- snap = self._extract_snapshot_locked(trigger_kind="stop")
- if snap is not None:
- await self._run_flush(snap)
-
- # ---- Bus-Handlers -------------------------------------------------------
-
- async def _on_frame_updated(self, ev: FrameUpdated) -> None:
- """Per frame: privacy check, trigger check (app switch), salience
- filter, buffering, buffer-overflow check.
-
- Order is CRITICAL:
- 1. The app-switch trigger MUST be checked before the salience filter,
- because the score of an app-switch frame is often below
- SALIENCE_THRESHOLD (app switch +20 < 30) — yet the OLD builder
- with highly salient code frames must still flush.
- 2. Salience filter afterwards: frame without another signal is dropped.
- 3. add_frame only for high-salience frames.
- 4. Buffer-overflow check after add_frame.
-
- B1 concurrency: all snapshots are extracted UNDER the lock; the
- actual ``_run_flush`` calls run AFTER the lock is released. This
- way the ~5 s Verdichter call does not block a single frame update.
- """
- # Hard negative §6: privacy-filter-blocked frames NEVER in Verdichter input.
- if not ev.is_capture_allowed:
- return
-
- # Read the current FrameSnapshot from AwarenessState — the
- # WindowFocusWatcher.drain_loop just wrote it there
- # (single-writer invariant from A1).
- frame = self._manager.state.current_frame
- if frame is None:
- return
-
- # M2 defense (code-reviewer 2026-04-26): theoretically a blocked frame
- # could be written to state.current_frame between
- # FrameUpdated(allowed=True) and our state read (race window <1 ms).
- # Re-checking is_capture_allowed protects against leaking a blocked
- # title into the Verdichter input. Cheap one-liner — no performance hit.
- if not frame.is_capture_allowed:
- return
-
- pending: list[_FlushSnapshot] = []
- async with self._lock:
- # Step 1: app-switch trigger FIRST. Snapshots the OLD builder
- # under lock — the Verdichter call runs later, lock-free.
- is_app_switch = (
- self._prev_frame is not None
- and self._builder is not None
- and frame.active_process_name != self._prev_frame.active_process_name
- )
- if is_app_switch:
- snap = self._extract_snapshot_locked(
- trigger_kind="window_switch",
- )
- if snap is not None:
- pending.append(snap)
-
- # Step 2: salience filter for the NEW frame.
- score = self._scorer.score_frame(frame, prev=self._prev_frame)
- if score < SALIENCE_THRESHOLD:
- self._prev_frame = frame
- else:
- # Step 3: open builder if needed (possibly empty after flush).
- if self._builder is None:
- self._builder = EpisodeBuilder(
- started_at_ns=frame.timestamp_ns,
- )
-
- self._builder.add_frame(frame, score)
- self._prev_frame = frame
-
- # Step 4a: buffer overflow after add_frame. Snapshot; the
- # current frame is part of the overflowing episode.
- if self._builder.frame_count > self._config.buffer_max:
- snap = self._extract_snapshot_locked(
- trigger_kind="buffer_overflow",
- )
- if snap is not None:
- pending.append(snap)
- else:
- # Step 4b (m4 fix): hard cap on episode duration.
- # Plan §6 EPISODE_MAX_DURATION_MIN=30 — otherwise a
- # "still active" episode grows without bound.
- max_dur_ns = (
- self._config.episode_max_duration_min
- * 60 * 1_000_000_000
- )
- if self._builder.duration_ns > max_dur_ns:
- snap = self._extract_snapshot_locked(
- trigger_kind="max_duration",
- )
- if snap is not None:
- pending.append(snap)
-
- # Lock released — Verdichter + persist run lock-free.
- for snap in pending:
- await self._run_flush(snap)
-
- async def _on_idle_entered(self, ev: IdleEntered) -> None:
- """Idle = user is gone = episode boundary. Flush immediately (lock-free)."""
- snap: _FlushSnapshot | None
- async with self._lock:
- snap = self._extract_snapshot_locked(trigger_kind="idle_entered")
- if snap is not None:
- await self._run_flush(snap)
-
- async def _on_response_generated(self, ev: ResponseGenerated) -> None:
- """Brain turn complete = high-salience event in the running episode."""
- async with self._lock:
- if self._builder is None:
- return
- score = self._scorer.score_event("BrainTurnCompleted")
- self._builder.add_event(
- "BrainTurnCompleted",
- score,
- payload={"text_len": len(ev.text), "language": ev.language},
- )
-
- # ---- Snapshot + Dispatch ------------------------------------------------
-
- def _extract_snapshot_locked(
- self, *, trigger_kind: str,
- ) -> _FlushSnapshot | None:
- """Atomic snapshot + builder reset. SYNC.
-
- Caller MUST hold ``self._lock``. Returns None when there is nothing
- to flush (no builder, empty builder, or spam-skip on min-duration).
-
- Spam skip: triggers outside ``_FORCED_TRIGGERS`` are dropped when
- the builder duration is below ``episode_min_duration_s`` — the
- builder is discarded (``self._builder = None``) so the next frame
- opens a fresh episode.
-
- Atomic snapshot: ``EpisodeBuilder.detach_frames`` /
- ``detach_events`` swap the internal lists with fresh buckets
- (double-buffer, B2 fix). The returned snapshot is therefore fully
- decoupled from the builder — no concurrent ``add_frame`` can touch it.
- """
- builder = self._builder
- if builder is None or builder.is_empty():
- return None
-
- duration_s = builder.duration_ns // 1_000_000_000
- forced = trigger_kind in _FORCED_TRIGGERS
- if not forced and duration_s < self._config.episode_min_duration_s:
- # Too short = spam — drop builder, next frame opens fresh.
- logger.debug(
- "StoryTracker skip flush: duration=%ds < min=%ds (trigger=%s)",
- duration_s, self._config.episode_min_duration_s, trigger_kind,
- )
- self._builder = None
- return None
-
- # Atomic extract: detach_* empty the builder buffers atomically (B2).
- # primary_app is computed on the detached list — after detach the
- # builder is empty and ``builder.primary_app`` would return "".
- started_at_ns = builder.started_at_ns
- raw_frames = builder.detach_frames()
- events_dict = builder.detach_events()
- primary_app = primary_app_from_snapshot(raw_frames)
-
- frames_dict: list[dict[str, Any]] = [
- {
- "timestamp_ns": f.timestamp_ns,
- "process_name": f.active_process_name,
- "window_title": f.active_window_title,
- }
- for f in raw_frames
- ]
-
- snap = _FlushSnapshot(
- trigger_kind=trigger_kind,
- started_at_ns=started_at_ns,
- frames=frames_dict,
- events=events_dict,
- primary_app=primary_app,
- frame_count=len(raw_frames),
- )
- # Reset BEFORE returning — the next bus handler acquiring the lock
- # can cleanly open a fresh EpisodeBuilder. detach_* already emptied
- # the buffer; this reference reset makes the state ``no episode in
- # flight`` explicit.
- self._builder = None
- return snap
-
- async def _run_flush(self, snap: _FlushSnapshot) -> None:
- """Verdichter -> RecallStore -> state update -> EpisodeRecorded.
-
- LOCK-FREE: this method MUST be called WITHOUT ``self._lock``;
- otherwise the ~5 s Verdichter call blocks all parallel bus handlers
- (Codex-BLOCKER B1).
- """
- # Defense-in-depth: Verdichter.call() already wraps its brain call
- # in its own asyncio.wait_for(timeout=cfg.timeout_s) — but a future
- # refactor or alternative Verdichter implementation might drop that
- # guard. The caller-side wait_for guarantees this code path can
- # never hang indefinitely no matter what changes inside Verdichter.
- # Buffer (+ 2.0s) so the inner timeout fires first under normal
- # operation and yields the clean error_reason="timeout" usage dict;
- # the outer wait_for only ever trips when the inner one is missing
- # or broken.
- _inner_timeout_s: float = float(
- getattr(getattr(self._verdichter, "_config", None), "timeout_s", 5.0)
- )
- try:
- summary, usage = await asyncio.wait_for(
- self._verdichter.call(
- frames=snap.frames,
- events=snap.events,
- primary_app=snap.primary_app,
- ),
- timeout=_inner_timeout_s + 2.0,
- )
- except Exception: # noqa: BLE001
- # Defensive: any verdichter failure (crash, outer-timeout trip,
- # cancellation) → persist an empty episode rather than lose it.
- logger.exception(
- "Verdichter call raised — persisting empty episode",
- )
- summary = ""
- usage = {
- "tokens_in": 0, "tokens_out": 0, "duration_ms": 0,
- "error_reason": "verdichter_exception",
- }
-
- ended_at_ns = time.time_ns()
- episode = Episode(
- started_at_ns=snap.started_at_ns,
- ended_at_ns=ended_at_ns,
- trigger_kind=snap.trigger_kind,
- summary=summary,
- frame_count=snap.frame_count,
- primary_app=snap.primary_app,
- tokens_in=int(usage.get("tokens_in", 0)),
- tokens_out=int(usage.get("tokens_out", 0)),
- )
-
- try:
- episode_id = await self._recall.record_episode(
- started_at_ns=episode.started_at_ns,
- ended_at_ns=episode.ended_at_ns,
- trigger_kind=snap.trigger_kind,
- summary=summary,
- frame_count=episode.frame_count,
- primary_app=snap.primary_app,
- tokens_in=episode.tokens_in,
- tokens_out=episode.tokens_out,
- )
- except Exception: # noqa: BLE001
- logger.exception("recall.record_episode failed — episode lost")
- return
-
- # Update state (snapshot_for_prompt will now reflect last_episode_summary).
- # Single-writer pattern from A2 — no lock needed; the tracker is the
- # sole mutator of both fields.
- self._manager.state.last_episode_summary = summary
- self._manager.state.last_episode_id = episode_id
-
- # Publish event — UI/flight-recorder listen for it.
- duration_ms = max(
- 0, (ended_at_ns - episode.started_at_ns) // 1_000_000,
- )
- await self._bus.publish(EpisodeRecorded(
- episode_id=episode_id,
- summary_preview=summary[:80],
- primary_app=snap.primary_app,
- frame_count=episode.frame_count,
- duration_ms=int(duration_ms),
- ))
-
- logger.info(
- "Episode persisted: id=%d trigger=%s primary_app=%s frames=%d "
- "duration_s=%d tokens_in=%d tokens_out=%d",
- episode_id, snap.trigger_kind, snap.primary_app,
- episode.frame_count, duration_ms // 1000,
- episode.tokens_in, episode.tokens_out,
- )
-
- async def _maybe_flush(self, *, trigger_kind: str) -> None:
- """Convenience helper: lock acquire + snapshot + release + dispatch.
-
- Used by tests and the internal hard-timer loop. Production bus
- handlers use ``_extract_snapshot_locked`` directly to batch the
- snapshot with other state mutations in a single lock acquisition.
-
- IMPORTANT: this method acquires ``self._lock`` itself — callers
- must NOT hold the lock, or a deadlock will occur on the non-reentrant
- asyncio.Lock.
- """
- snap: _FlushSnapshot | None
- async with self._lock:
- snap = self._extract_snapshot_locked(trigger_kind=trigger_kind)
- if snap is not None:
- await self._run_flush(snap)
-
- # ---- Hard-Timer ---------------------------------------------------------
-
- async def _hard_timer_loop(self) -> None:
- """Every ``hard_timer_min`` minutes: call ``_maybe_flush`` with trigger='hard_timer'."""
- interval_s = self._config.hard_timer_min * 60
- try:
- while self._started:
- try:
- await asyncio.sleep(interval_s)
- except asyncio.CancelledError:
- break
- await self._maybe_flush(trigger_kind="hard_timer")
- except asyncio.CancelledError:
- pass
- except Exception: # noqa: BLE001
- logger.exception("StoryTracker hard-timer loop crashed")
diff --git a/jarvis/awareness/verdichter.py b/jarvis/awareness/verdichter.py
deleted file mode 100644
index 434276c7a6..0000000000
--- a/jarvis/awareness/verdichter.py
+++ /dev/null
@@ -1,187 +0,0 @@
-"""Verdichter — direct Brain call (no Heavy-Worker spawn).
-
-Plan §6 Hard Negative: NEVER via ``spawn_worker`` (Wave-4 rebrand —
-previously ``spawn_sub_jarvis``). Verdichter obtains its Brain instance
-directly from the ``BrainProviderRegistry`` (instantiated in
-``factory.py``) and calls ``brain.complete(req)``.
-Own timeout (5s default), own token caps.
-
-Contract::
-
- summary, usage = await verdichter.call(
- frames=[{"timestamp_ns": ..., "process_name": ..., "window_title": ...}, ...],
- events=[{"ts_ns": ..., "kind": ..., "payload": {...}}, ...],
- primary_app="Code.exe",
- )
-
-On empty input / timeout / brain error: ``summary == ""`` and
-``usage["error_reason"]`` is set — the caller then persists the episode
-with an empty summary instead of crashing.
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import time
-from typing import TYPE_CHECKING, Any
-
-from jarvis.awareness.config import AwarenessVerdichterConfig
-from jarvis.awareness.prompts import VERDICHTER_SYSTEM_PROMPT, build_verdichter_prompt
-from jarvis.brain.streaming import aggregate
-from jarvis.core.protocols import BrainMessage, BrainRequest
-from jarvis.costs.ledger import usage_context
-
-if TYPE_CHECKING:
- from jarvis.core.protocols import Brain
-
-logger = logging.getLogger(__name__)
-
-
-def _tagged_complete(brain, request): # type: ignore[no-untyped-def]
- """The digest's model calls are ledgered as awareness work."""
- with usage_context("awareness"):
- return brain.complete(request)
-
-# Plan §6 Hard Negative: max 30 frames+events per call.
-# On overflow: keep the NEWEST ones (chronological tail).
-MAX_FRAMES_PLUS_EVENTS = 30
-
-
-def _ts(item: dict[str, Any]) -> int:
- """Extract timestamp from a frame or event — both schemas accepted."""
- return int(item.get("timestamp_ns") or item.get("ts_ns") or 0)
-
-
-class Verdichter:
- """Direct Brain call (no Jarvis-Agent spawn).
-
- Stateless — no bus subscription, no internal counters. One instance
- is constructed in ``factory.py`` and passed to the ``StoryTracker``.
- """
-
- def __init__(
- self,
- *,
- brain: Brain,
- config: AwarenessVerdichterConfig,
- ) -> None:
- self._brain = brain
- self._config = config
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- """Synthesise an episode summary from frames and events.
-
- Returns:
- ``(summary_text, usage_dict)``. ``usage_dict`` contains::
-
- {
- "tokens_in": int,
- "tokens_out": int,
- "duration_ms": int,
- "error_reason": str | None,
- }
-
- Failure modes:
- - Empty input → ``("", {..., "error_reason": "empty_input"})``
- - Timeout (asyncio.TimeoutError) → ``("", {..., "error_reason": "timeout"})``
- - Brain exception → ``("", {..., "error_reason": str(exc)[:200]})``
- """
- # Empty-input gate (hard-cap required by Plan §6 AC).
- if not frames and not events:
- return "", {
- "tokens_in": 0,
- "tokens_out": 0,
- "duration_ms": 0,
- "error_reason": "empty_input",
- }
-
- # Hard cap: max 30 frames+events. Keep the NEWEST ones (tail).
- # Sort by timestamp ascending, then take the last N.
- frames, events = self._cap_to_max(frames, events)
-
- prompt = build_verdichter_prompt(
- frames=frames,
- events=events,
- primary_app=primary_app,
- max_chars=self._config.max_input_tokens * 4,
- )
- request = BrainRequest(
- messages=(BrainMessage(role="user", content=prompt),),
- system=VERDICHTER_SYSTEM_PROMPT,
- max_tokens=self._config.max_output_tokens,
- temperature=0.5, # less creative, more factual
- stream=True,
- )
-
- start_ns = time.time_ns()
- try:
- agg = await asyncio.wait_for(
- aggregate(_tagged_complete(self._brain, request)),
- timeout=self._config.timeout_s,
- )
- except TimeoutError:
- duration_ms = (time.time_ns() - start_ns) // 1_000_000
- logger.warning(
- "Verdichter timeout after %dms (config.timeout_s=%.1f)",
- duration_ms, self._config.timeout_s,
- )
- return "", {
- "tokens_in": 0,
- "tokens_out": 0,
- "duration_ms": int(duration_ms),
- "error_reason": "timeout",
- }
- except Exception as exc: # noqa: BLE001
- duration_ms = (time.time_ns() - start_ns) // 1_000_000
- logger.warning("Verdichter brain-call failed: %s", exc)
- return "", {
- "tokens_in": 0,
- "tokens_out": 0,
- "duration_ms": int(duration_ms),
- "error_reason": str(exc)[:200],
- }
-
- duration_ms = (time.time_ns() - start_ns) // 1_000_000
- return agg.text, {
- "tokens_in": int(agg.usage.get("input_tokens", 0)),
- "tokens_out": int(agg.usage.get("output_tokens", 0)),
- "duration_ms": int(duration_ms),
- "error_reason": None,
- }
-
- @staticmethod
- def _cap_to_max(
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- """If ``len(frames)+len(events) > 30``: keep the newest 30.
-
- Strategy: merge all items with a type marker, sort by timestamp
- ascending, take the last ``MAX_FRAMES_PLUS_EVENTS``, then split
- back into frames and events.
- """
- total = len(frames) + len(events)
- if total <= MAX_FRAMES_PLUS_EVENTS:
- return frames, events
-
- annotated: list[tuple[int, str, dict[str, Any]]] = []
- for f in frames:
- annotated.append((_ts(f), "frame", f))
- for e in events:
- annotated.append((_ts(e), "event", e))
- annotated.sort(key=lambda x: x[0])
- tail = annotated[-MAX_FRAMES_PLUS_EVENTS:]
-
- kept_frames = [item for _, kind, item in tail if kind == "frame"]
- kept_events = [item for _, kind, item in tail if kind == "event"]
- logger.debug(
- "Verdichter capped %d -> %d (frames=%d, events=%d)",
- total, len(tail), len(kept_frames), len(kept_events),
- )
- return kept_frames, kept_events
diff --git a/jarvis/awareness/watchers/__init__.py b/jarvis/awareness/watchers/__init__.py
deleted file mode 100644
index 17519127c7..0000000000
--- a/jarvis/awareness/watchers/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-"""Awareness watchers (Phase A1) — maintain the L1 live frame.
-
-Watchers are the background actors that keep ``AwarenessState`` up to
-date: ``WindowFocusWatcher`` (Win32 hook on foreground changes),
-``IdleDetector`` (GetLastInputInfo polling). Started by
-``AwarenessManager`` during bootstrap, stopped on shutdown.
-
-Re-exports will be added in Wave 4 once all watchers exist.
-"""
-from __future__ import annotations
diff --git a/jarvis/awareness/watchers/base.py b/jarvis/awareness/watchers/base.py
deleted file mode 100644
index 398eeb59de..0000000000
--- a/jarvis/awareness/watchers/base.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""AwarenessWatcher protocol — lifecycle contract for all watchers.
-
-Structural (``typing.Protocol``) rather than inheritance — consistent with
-the plugin-system pattern in ``jarvis/core/protocols.py``. Watcher
-implementations do NOT need Jarvis as a dependency; they satisfy the
-protocol via method signatures.
-"""
-from __future__ import annotations
-
-from typing import Protocol, runtime_checkable
-
-
-@runtime_checkable
-class AwarenessWatcher(Protocol):
- """Lifecycle contract for background watchers.
-
- Both methods are idempotent: calling ``start()`` twice is a no-op,
- calling ``stop()`` twice is a no-op. ``stop()`` may block for at most
- 2 s — otherwise there is a risk of memory/handle leaks.
- """
- async def start(self) -> None:
- """Start background activity. Returns once running."""
- ...
-
- async def stop(self) -> None:
- """Stop cleanly within 2 s. Guarantees no hook/thread leak."""
- ...
diff --git a/jarvis/awareness/watchers/idle.py b/jarvis/awareness/watchers/idle.py
deleted file mode 100644
index be2ddf8a3f..0000000000
--- a/jarvis/awareness/watchers/idle.py
+++ /dev/null
@@ -1,324 +0,0 @@
-"""IdleDetector — polls the OS idle-time counter on a 1 s tick.
-
-Plan §5 explicitly permits polling for idle detection (as opposed to the
-foreground window, which uses hooks). Rationale: a single idle-seconds
-read is an O(1) call with no hook lifecycle. Mouse/KB WinEventHooks (or
-their macOS/Linux equivalents) would be a privacy risk (capturing all
-input) and have a UAC-proximity aspect.
-
-Idle transition: Active → Idle when ``idle_seconds >= threshold_s``,
-Idle → Active on the first input afterwards. Both transitions emit an
-event and sync ``manager.state.is_idle`` plus
-``current_frame.idle_since_ns`` (via ``dataclasses.replace`` because
-FrameSnapshot is frozen).
-
-Per-OS idle-seconds backend, resolved ONCE in ``start()`` (never
-re-probed per tick):
- * Windows — ``GetLastInputInfo`` via ctypes. Always available.
- * macOS — Quartz ``CGEventSourceSecondsSinceLastEventType``, lazily
- imported (optional ``pyobjc-framework-Quartz`` extra).
- * Linux — the ``xprintidle`` binary (X11 XScreenSaver extension), only
- when a real X11 display is present; unavailable on Wayland (no
- global idle-time query by OS design) and on headless hosts.
-
-No backend available: ``start()`` logs ONE clear line and returns
-WITHOUT starting the tick loop — mirrors ``WindowFocusWatcher``'s
-honest degradation, instead of the previous behavior of spinning
-forever and reporting "never idle" off Windows.
-
-A backend that starts failing at runtime (binary uninstalled, native
-call breaking) disables itself after ``_MAX_CONSECUTIVE_FAILURES``
-consecutive failures instead of spamming the log or polling a dead
-probe forever.
-
-Lazy imports (AP-26): ``ctypes``, ``Quartz`` and the ``xprintidle``
-subprocess call are all imported/spawned only inside their respective
-backend methods, never at module scope.
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import shutil
-import subprocess
-import time
-from dataclasses import replace
-from typing import TYPE_CHECKING
-
-from jarvis.core.events import IdleEntered, IdleExited
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
-from jarvis.platform import detect_platform
-from jarvis.platform.probes import display_present, is_wayland
-
-if TYPE_CHECKING:
- from jarvis.awareness.manager import AwarenessManager
- from jarvis.core.bus import EventBus
-
-logger = logging.getLogger(__name__)
-
-_TICK_SECONDS: float = 1.0
-_STOP_TIMEOUT_S: float = 1.0
-_MAX_CONSECUTIVE_FAILURES: int = 5 # runtime probe failures before self-disabling
-
-
-class IdleDetector:
- """Polls the OS idle-time counter. Emits idle transitions."""
-
- def __init__(
- self,
- *,
- manager: AwarenessManager,
- bus: EventBus,
- threshold_s: int = 300, # Plan D-A6: 5 min default
- ) -> None:
- self._manager = manager
- self._bus = bus
- self._threshold_s = threshold_s
- self._task: asyncio.Task[None] | None = None
- self._stopped: bool = False
- self._is_idle: bool = False
- self._became_idle_at_ns: int = 0
- # Resolved once in start() — one of "win32"/"macos"/"linux", or
- # None if start() never ran / no backend is usable on this host.
- self._backend: str | None = None
- self._consecutive_failures: int = 0
-
- # ---- Lifecycle -----------------------------------------------------------
-
- async def start(self) -> None:
- """Resolve the idle-seconds backend once, then start the 1 s tick
- loop. Idempotent.
-
- No usable backend (headless Linux, Wayland, missing xprintidle,
- missing pyobjc-Quartz): logs one clear line and returns without
- starting the loop.
- """
- if self._task is not None:
- return
- backend, reason = self._resolve_backend()
- if backend is None:
- logger.info("idle detection unavailable on this platform: %s", reason)
- return
- self._backend = backend
- self._consecutive_failures = 0
- self._stopped = False
- loop = asyncio.get_running_loop()
- self._task = loop.create_task(self._run(), name="awareness-idle")
-
- async def stop(self) -> None:
- """Cancel the task, wait <1 s. Idempotent."""
- self._stopped = True
- task = self._task
- self._task = None
- if task is None:
- return
- task.cancel()
- try:
- await asyncio.wait_for(task, timeout=_STOP_TIMEOUT_S)
- except (TimeoutError, asyncio.CancelledError):
- pass
- except Exception: # noqa: BLE001
- logger.debug("IdleDetector task ended with exception", exc_info=True)
-
- # ---- Backend resolution ---------------------------------------------------
-
- @staticmethod
- def _resolve_backend() -> tuple[str | None, str]:
- """Pick the idle-seconds backend for this OS, once.
-
- Returns ``(backend, reason)``. ``backend`` is one of
- ``"win32"``/``"macos"``/``"linux"``, or ``None`` when nothing usable
- was found; ``reason`` is a short human-readable explanation, only
- meaningful when ``backend`` is ``None``.
- """
- plat = detect_platform()
- if plat == "win32":
- return "win32", ""
- if plat == "darwin":
- try:
- import Quartz # type: ignore[import-not-found] # noqa: PLC0415
-
- _ = Quartz.CGEventSourceSecondsSinceLastEventType
- except Exception: # noqa: BLE001
- return None, "pyobjc-framework-Quartz is not installed"
- return "macos", ""
- if plat == "linux":
- if is_wayland():
- return None, (
- "Wayland has no global idle-time query (X11-only via xprintidle)"
- )
- if not display_present():
- return None, "no graphical display detected (headless session)"
- if shutil.which("xprintidle") is None:
- return None, "xprintidle is not installed (e.g. `apt install xprintidle`)"
- return "linux", ""
- return None, f"unsupported platform ({plat})"
-
- # ---- Tick-Loop -----------------------------------------------------------
-
- async def _run(self) -> None:
- """Loop until ``_stopped`` or cancelled. Each tick: ``_tick_once`` + sleep."""
- while not self._stopped:
- try:
- await self._tick_once()
- except asyncio.CancelledError:
- break
- except Exception: # noqa: BLE001
- # Defensive: a single failed tick must not tear down the
- # loop. Log the error once and keep ticking.
- logger.debug("IdleDetector tick failed", exc_info=True)
- try:
- await asyncio.sleep(_TICK_SECONDS)
- except asyncio.CancelledError:
- break
-
- async def _tick_once(self) -> None:
- """One tick iteration: measure idle time, check transition, publish event.
-
- Independently testable — tests call ``_tick_once()`` directly,
- without the ``_run()`` loop and therefore without waiting 1 s.
-
- A backend that raises is counted as a failure rather than crashing
- the loop; after ``_MAX_CONSECUTIVE_FAILURES`` in a row it disables
- idle detection for the rest of the session (one log line) instead
- of repeatedly polling a dead probe.
- """
- try:
- idle_seconds = await asyncio.to_thread(self._get_idle_seconds)
- except Exception: # noqa: BLE001
- self._consecutive_failures += 1
- logger.debug(
- "idle-seconds probe failed (backend=%s)", self._backend, exc_info=True,
- )
- if self._consecutive_failures >= _MAX_CONSECUTIVE_FAILURES:
- logger.info(
- "idle detection: %d consecutive probe failures on backend "
- "'%s' — disabling idle detection for this session",
- self._consecutive_failures, self._backend,
- )
- self._stopped = True
- return
- self._consecutive_failures = 0
-
- now_ns = time.time_ns()
- should_be_idle = idle_seconds >= self._threshold_s
-
- if should_be_idle and not self._is_idle:
- # Active → Idle
- self._is_idle = True
- self._became_idle_at_ns = now_ns - int(idle_seconds * 1e9)
- self._manager.state.is_idle = True
- cur = self._manager.state.current_frame
- if cur is not None:
- # FrameSnapshot is frozen — create a new one with replace().
- self._manager.state.current_frame = replace(
- cur, idle_since_ns=self._became_idle_at_ns,
- )
- await self._bus.publish(IdleEntered(idle_since_ns=self._became_idle_at_ns))
-
- elif not should_be_idle and self._is_idle:
- # Idle → Active
- was_idle_for_ms = max(0, int((now_ns - self._became_idle_at_ns) / 1_000_000))
- self._is_idle = False
- self._became_idle_at_ns = 0
- self._manager.state.is_idle = False
- cur = self._manager.state.current_frame
- if cur is not None and cur.idle_since_ns is not None:
- self._manager.state.current_frame = replace(cur, idle_since_ns=None)
- await self._bus.publish(IdleExited(was_idle_for_ms=was_idle_for_ms))
-
- # ---- Idle-seconds dispatch -------------------------------------------------
-
- def _get_idle_seconds(self) -> float:
- """Idle seconds via the backend resolved once in ``start()``.
-
- Dispatches on ``self._backend`` (set by ``start()`` /
- ``_resolve_backend``). Each backend method is best-effort in its
- own right for expected conditions; unexpected failures propagate
- to ``_tick_once``'s failure counter instead of being swallowed
- here, so a persistently broken backend actually disables itself.
- """
- if self._backend == "win32":
- return self._get_idle_seconds_win32()
- if self._backend == "macos":
- return self._get_idle_seconds_macos()
- if self._backend == "linux":
- return self._get_idle_seconds_linux()
- return 0.0
-
- # ---- Win32 ---------------------------------------------------------------
-
- @staticmethod
- def _get_idle_seconds_win32() -> float:
- """``GetLastInputInfo`` + ``GetTickCount`` → idle seconds.
-
- Lazy-imports ``ctypes`` so the module can be imported on Linux/Mac
- without a Win32 stack.
-
- ``GetTickCount`` returns ms-since-boot and wraps after ~49.7 days
- — the wrap is handled by 64-bit extension when
- ``current_tick < info.dwTime``.
- """
- import ctypes # noqa: PLC0415
- from ctypes import wintypes # noqa: PLC0415
-
- class LASTINPUTINFO(ctypes.Structure):
- _fields_ = [
- ("cbSize", wintypes.UINT),
- ("dwTime", wintypes.DWORD),
- ]
-
- info = LASTINPUTINFO()
- info.cbSize = ctypes.sizeof(LASTINPUTINFO)
- ok = ctypes.windll.user32.GetLastInputInfo(ctypes.byref(info))
- if not ok:
- return 0.0
- current_tick = ctypes.windll.kernel32.GetTickCount()
- if current_tick < info.dwTime:
- current_tick += 0x100000000
- idle_ms = current_tick - info.dwTime
- return idle_ms / 1000.0
-
- # ---- macOS -----------------------------------------------------------------
-
- @staticmethod
- def _get_idle_seconds_macos() -> float:
- """``CGEventSourceSecondsSinceLastEventType`` — combined session
- state, any input event type. Lazy ``Quartz`` import (optional
- ``pyobjc-framework-Quartz`` extra).
-
- Raises if Quartz is unavailable or the native call fails — the
- caller (``_tick_once``) counts this as a probe failure rather than
- silently reporting "never idle".
- """
- import Quartz # type: ignore[import-not-found] # noqa: PLC0415
-
- return float(Quartz.CGEventSourceSecondsSinceLastEventType(
- Quartz.kCGEventSourceStateCombinedSessionState,
- Quartz.kCGAnyInputEventType,
- ))
-
- # ---- Linux -----------------------------------------------------------------
-
- @staticmethod
- def _get_idle_seconds_linux() -> float:
- """``xprintidle`` prints idle milliseconds on stdout (X11
- XScreenSaver extension). Uses the shared ``NO_WINDOW_CREATIONFLAGS``
- convention (a no-op off Windows).
-
- Raises on a missing binary, non-zero exit, or timeout — the caller
- counts it as a probe failure rather than silently reporting "never
- idle".
- """
- result = subprocess.run(
- ["xprintidle"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=2.0,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if result.returncode != 0:
- raise RuntimeError(f"xprintidle exited with code {result.returncode}")
- return int((result.stdout or "").strip()) / 1000.0
diff --git a/jarvis/awareness/watchers/window.py b/jarvis/awareness/watchers/window.py
deleted file mode 100644
index e1d5958ab0..0000000000
--- a/jarvis/awareness/watchers/window.py
+++ /dev/null
@@ -1,977 +0,0 @@
-"""WindowFocusWatcher — Win32 ``SetWinEventHook`` on ``EVENT_SYSTEM_FOREGROUND``.
-
-Architecture (binding):
-
- 1. Dedicated pump thread runs ``MsgWaitForMultipleObjects(stop_event,
- QS_ALLINPUT)``. Wakeup on event OR new Win32 message. Subagent
- recommendation Q1 — replaces ``pythoncom.PumpMessages`` because it
- can be shut down deterministically via ``win32event.SetEvent``.
- 2. Hook callback (Win32 thread) does ONLY
- ``loop.call_soon_threadsafe(_safe_enqueue, payload)``. NO logging,
- NO await, NO PrivacyFilter, NO bus.publish (Plan §5+§10
- Hard-Negative HN4).
- 3. Drain loop (asyncio) pulls ``(timestamp_ns, hwnd)`` from the queue,
- calls ``_resolve_window_meta`` (in ``asyncio.to_thread``) +
- ``PrivacyFilter`` + ``bus.publish`` of ``FrameUpdated`` or
- ``AwarenessCaptureBlocked``.
-
-Platform guard: ``detect_platform() != "win32"`` routes ``start()`` to the
-POSIX polling fallback below instead of the Win32 hook path. Lazy imports
-of ``ctypes``, ``win32event`` and ``psutil`` INSIDE the methods (Plan §5
-Hard-Negative HN3).
-
-POSIX polling fallback (macOS/Linux): no OS-level foreground-change hook
-is used there, so ``WindowFocusWatcher`` instead polls
-``jarvis.platform.window_state.foreground_window()`` on a
-``_POSIX_POLL_INTERVAL_S`` cadence and calls the SAME ``_emit_frame`` tail
-the Win32 drain loop uses, so both platforms publish identical
-``FrameUpdated`` / ``AwarenessCaptureBlocked`` events. macOS always has a
-display (no TCC/Accessibility grant is needed just to read the frontmost
-application — ``window_state.foreground_window()`` already degrades to
-``None`` without the optional Screen-Recording grant or without pyobjc).
-An empty probe only disables the fallback while NO probe has ever
-succeeded — that is a backend which cannot work here; afterwards it means
-"nothing is focused right now", which on X11 is an everyday state (see
-``_poll_loop``). A window that merely has no readable TITLE is a healthy
-probe too and never counts against it. Headless Linux and Wayland sessions
-are gated up front (mirrors ``IdleDetector``): one honest log line, no
-polling task, no crash.
-
-Lifecycle order in ``stop()`` (subagent Q4, 6 phases):
- P1: cancel drain task (asyncio side first, so no ``bus.publish``
- fires after we unregister the hook).
- P2: ``win32event.SetEvent(stop_event)`` — wakes ``MsgWaitForMultipleObjects``.
- P3: ``pump_thread.join(timeout=1.5)``.
- P4: defensive ``UnhookWinEvent`` in case the pump thread crashed; the
- primary cleanup path is in the pump thread's finally block.
- P5: ``CloseHandle(stop_event)``.
- P6: remaining queue items are DRAINED and the per-run change-detection
- state is reset (loss acceptable — Plan §5 does not require
- no-event-loss on shutdown — but carrying either into a later
- ``start()`` is not: the queue and the "last seen window" markers live
- on the instance, so a restart would replay pre-stop frames and then
- swallow the first genuine one as "unchanged").
-"""
-from __future__ import annotations
-
-import asyncio
-import logging
-import os
-import shutil
-import subprocess
-import threading
-import time
-from typing import TYPE_CHECKING
-
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.core.events import AwarenessCaptureBlocked, FrameUpdated
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
-from jarvis.core.win32_dpi import ensure_dpi_awareness
-from jarvis.platform import detect_platform, window_state
-from jarvis.platform.probes import display_present, is_wayland
-
-if TYPE_CHECKING:
- from jarvis.awareness.manager import AwarenessManager
- from jarvis.awareness.privacy import PrivacyFilter
- from jarvis.core.bus import EventBus
- from jarvis.platform.window_state import WindowInfo
-
-logger = logging.getLogger(__name__)
-
-# Win32 constants — defined as module-level constants so the module can
-# be imported on Linux. Values are platform-stable (Win32 API contract).
-_EVENT_SYSTEM_FOREGROUND: int = 0x0003
-_WINEVENT_OUTOFCONTEXT: int = 0x0000
-_WINEVENT_SKIPOWNPROCESS: int = 0x0002
-
-_QUEUE_MAX: int = 64 # Burst-Buffer (Alt+Tab-Marathon)
-_DRAIN_GET_TIMEOUT_S: float = 0.25 # Drain-Wakeup um stop-Flag zu pruefen
-_PUMP_JOIN_TIMEOUT_S: float = 1.5 # Stop-Phase 3
-_DRAIN_CANCEL_TIMEOUT_S: float = 0.5 # Stop-Phase 1
-_HWND_DEDUPE_NS: int = 50_000_000 # 50ms — schluckt Win32-Doppel-Events
-_PUMP_READY_TIMEOUT_S: float = 2.0 # start() wait-bis-Hook-gesetzt
-
-# POSIX polling fallback (macOS/Linux) — no OS-level focus-change hook is
-# used there, so we poll at a modest cadence instead. 2 s balances staying
-# off the voice hot path against noticing an app switch reasonably fast.
-_POSIX_POLL_INTERVAL_S: float = 2.0
-_POSIX_POLL_MAX_FAILURES: int = 5 # empty probes BEFORE the first success
-_POSIX_POLL_STOP_TIMEOUT_S: float = 1.5
-# Last-resort pid lookup for an X11 window (see ``_linux_window_pid``). Kept
-# generous on purpose: a slow answer is still a correct one, while a timeout
-# yields an empty process name, and the privacy rules that key on the process
-# (rather than the title) then have nothing to match against.
-_POSIX_PID_PROBE_TIMEOUT_S: float = 5.0
-
-
-def _linux_window_pid(window_id: int) -> int:
- """Owning pid of an X11 window id via ``xdotool``, or ``0``. Never raises.
-
- A LAST RESORT: ``window_state.foreground_window`` already reads the pid off
- the very window it took the title from, so this only runs for a client that
- advertises no ``_NET_WM_PID`` at all — which is also the property xdotool
- reads, so the honest expectation is that it returns 0 as well. It stays as
- the single documented seam for that lookup instead of being inlined, and it
- no longer routes the routine "this window has no pid property" case through
- a broad exception handler that logged it as a resolution failure with a
- traceback, drowning the real ones.
-
- Runs on a worker thread (called via ``asyncio.to_thread``), so it must be
- bounded: every ``subprocess`` failure mode — a missing binary, a dead X
- connection, a hung server — degrades to ``0``.
- """
- executable = shutil.which("xdotool")
- if executable is None:
- return 0
- try:
- proc = subprocess.run(
- [executable, "getwindowpid", str(window_id)],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=_POSIX_PID_PROBE_TIMEOUT_S,
- check=False,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- except (OSError, subprocess.SubprocessError):
- logger.debug(
- "xdotool getwindowpid failed for window %s", window_id, exc_info=True,
- )
- return 0
- if proc.returncode != 0:
- logger.debug("xdotool reports no pid for X11 window %s", window_id)
- return 0
- raw = (proc.stdout or "").strip()
- try:
- pid = int(raw)
- except ValueError:
- logger.debug(
- "xdotool returned a non-numeric pid %r for X11 window %s", raw, window_id,
- )
- return 0
- return pid if pid > 0 else 0
-
-
-class WindowFocusWatcher:
- """Responds to foreground window changes via a Win32 hook."""
-
- def __init__(
- self,
- *,
- manager: AwarenessManager,
- privacy: PrivacyFilter,
- bus: EventBus,
- ) -> None:
- self._manager = manager
- self._privacy = privacy
- self._bus = bus
-
- # Async-Side
- self._loop: asyncio.AbstractEventLoop | None = None
- self._queue: asyncio.Queue[tuple[int, int]] = asyncio.Queue(maxsize=_QUEUE_MAX)
- self._drain_task: asyncio.Task[None] | None = None
- self._drain_stop: asyncio.Event = asyncio.Event()
-
- # Sync-Side (Win32)
- self._pump_thread: threading.Thread | None = None
- self._hook_handle: int | None = None
- # Guards the read-and-clear of _hook_handle: the pump thread and stop()
- # both release the hook, from different threads. See _take_hook_handle.
- self._hook_lock: threading.Lock = threading.Lock()
- self._stop_event_handle: int | None = None
- # The WINEVENTPROC instance MUST be kept alive — otherwise it is
- # GC'd, the C pointer dangles, and Win32 calls invalid memory.
- self._wineventproc_ref: object | None = None
-
- # POSIX polling side (macOS/Linux fallback — no hook available)
- self._poll_task: asyncio.Task[None] | None = None
- self._poll_stop: asyncio.Event = asyncio.Event()
- self._poll_last_handle: int | None = None
- self._poll_last_title: str = ""
-
- # State
- self._started: bool = False
- self._stopping: bool = False
- # Drops split by source thread to eliminate the +=1 race
- # (CPython GIL switch between read/modify/write).
- self._drops_pump: int = 0 # written in the Win32 _proc callback
- self._drops_async: int = 0 # written in the asyncio _safe_enqueue
- self._last_hwnd: int = 0
- self._last_emit_ns: int = 0
-
- @property
- def _drops(self) -> int:
- """Sum of both drop counters (compat for smoke tests + unit tests)."""
- return self._drops_pump + self._drops_async
-
- # ---- Lifecycle ----------------------------------------------------------
-
- async def start(self) -> None:
- """Start the Win32 pump thread and drain task, or the POSIX polling
- fallback on macOS/Linux. Idempotent.
-
- Headless Linux / Wayland: logs one honest line and starts no task
- (mirrors ``IdleDetector``).
- """
- if self._started:
- return
- if detect_platform() != "win32":
- self._start_posix_polling()
- self._started = True
- return
-
- ensure_dpi_awareness()
- self._loop = asyncio.get_running_loop()
- self._drain_stop.clear()
- self._stop_event_handle = self._create_stop_event()
-
- ready = threading.Event()
- thread = threading.Thread(
- target=self._pump_loop,
- name="awareness-window-pump",
- args=(ready,),
- daemon=True,
- )
- thread.start()
- if not ready.wait(timeout=_PUMP_READY_TIMEOUT_S):
- logger.warning(
- "WindowFocusWatcher: pump-thread did not signal ready in %.1fs",
- _PUMP_READY_TIMEOUT_S,
- )
-
- self._pump_thread = thread
- self._drain_task = self._loop.create_task(
- self._drain_loop(), name="awareness-window-drain",
- )
- self._started = True
-
- async def stop(self) -> None:
- """Clean shutdown <2 s. Idempotent. 6-phase sequence on Windows;
- a 2-phase cancel-and-join on the POSIX polling fallback."""
- if self._stopping:
- return
- if not self._started:
- return
- self._stopping = True
-
- if detect_platform() != "win32":
- try:
- await self._stop_posix_polling()
- self._reset_frame_state()
- finally:
- self._started = False
- self._stopping = False
- return
-
- try:
- # P1: Drain-Task cancellen (asyncio-side)
- self._drain_stop.set()
- drain_task = self._drain_task
- self._drain_task = None
- if drain_task is not None:
- drain_task.cancel()
- try:
- await asyncio.wait_for(drain_task, timeout=_DRAIN_CANCEL_TIMEOUT_S)
- except (TimeoutError, asyncio.CancelledError):
- pass
- except Exception: # noqa: BLE001
- logger.debug("drain task ended with exception", exc_info=True)
-
- # P2: SetEvent (Win32) — wakes MsgWaitForMultipleObjects immediately
- if self._stop_event_handle is not None:
- try:
- import win32event # noqa: PLC0415
-
- win32event.SetEvent(self._stop_event_handle)
- except Exception: # noqa: BLE001, S110
- # Defensive Win32 cleanup — do not escalate errors,
- # otherwise the next phase step in stop() would hang.
- pass
-
- # P3: Pump-Thread join
- pump = self._pump_thread
- self._pump_thread = None
- if pump is not None and pump.is_alive():
- pump.join(timeout=_PUMP_JOIN_TIMEOUT_S)
- if pump.is_alive():
- logger.warning(
- "WindowFocusWatcher pump-thread did not exit in %.1fs",
- _PUMP_JOIN_TIMEOUT_S,
- )
-
- # P4: Defensive UnhookWinEvent (primary path is in pump-loop finally)
- hook_handle = self._take_hook_handle()
- if hook_handle is not None:
- try:
- import ctypes # noqa: PLC0415
-
- # Own WinDLL instance + argtypes — otherwise ctypes
- # silently truncates the 64-bit handle to c_int (32-bit).
- u32 = ctypes.WinDLL("user32", use_last_error=True)
- u32.UnhookWinEvent.argtypes = [ctypes.c_void_p]
- u32.UnhookWinEvent.restype = ctypes.c_int
- u32.UnhookWinEvent(hook_handle)
- except Exception: # noqa: BLE001, S110
- # Defensive Win32 cleanup — do not escalate errors,
- # otherwise the next phase step in stop() would hang.
- pass
-
- # P5: CloseHandle stop_event
- if self._stop_event_handle is not None:
- try:
- import win32api # noqa: PLC0415
-
- win32api.CloseHandle(self._stop_event_handle)
- except Exception: # noqa: BLE001, S110
- # Defensive Win32 cleanup — do not escalate errors,
- # otherwise the next phase step in stop() would hang.
- pass
- self._stop_event_handle = None
-
- # P6: discard leftover queue items. They must NOT survive into a
- # later start(): the queue lives on the instance, so a restart
- # (awareness toggled off and on again) used to drain events
- # captured before the stop and publish them as fresh frames with
- # their old timestamps.
- if self._drops > 0:
- logger.info(
- "WindowFocusWatcher: %d frames dropped (pump=%d, async=%d)",
- self._drops, self._drops_pump, self._drops_async,
- )
- self._reset_frame_state()
- finally:
- self._started = False
- self._stopping = False
-
- def _take_hook_handle(self) -> int | None:
- """Atomically claim the hook handle so exactly ONE caller unhooks it.
-
- Both ``stop()``'s defensive P4 and the pump thread's ``finally`` release
- the hook, and P3's join is explicitly allowed to TIME OUT — so a pump
- thread that is merely slow can be inside its cleanup while ``stop()``
- reads the very same handle. Calling ``UnhookWinEvent`` twice on one
- handle has a use-after-free shape: the second call either no-ops or,
- once Win32 has recycled that handle value for a hook installed
- elsewhere in the process, tears down SOMEONE ELSE's hook. Read-and-clear
- under a lock makes the loser of that race see ``None`` and do nothing.
- """
- with self._hook_lock:
- handle, self._hook_handle = self._hook_handle, None
- return handle
-
- def _reset_frame_state(self) -> None:
- """Drop queued frames and per-run change-detection state.
-
- Both survive on the instance across a stop/start cycle, and both are
- wrong on the next run: the queued payloads describe windows from the
- previous session, and the stale "last seen" markers make the FIRST
- probe after a restart compare equal to what was focused before the
- stop — so the POSIX poller emitted nothing at all until the user
- happened to switch windows, leaving ``state.current_frame`` frozen.
- """
- while True:
- try:
- self._queue.get_nowait()
- except asyncio.QueueEmpty:
- # Not a failure: an empty queue is exactly the drained state
- # this loop exists to reach.
- break
- self._last_hwnd = 0
- self._last_emit_ns = 0
- self._poll_last_handle = None
- self._poll_last_title = ""
-
- # ---- Win32-Pump-Thread --------------------------------------------------
-
- @staticmethod
- def _create_stop_event() -> int:
- """Create a manual-reset event handle. Lazy-imports win32event."""
- import win32event # noqa: PLC0415
-
- # CreateEvent(SecurityAttrs=None, ManualReset=True, InitialState=False, Name=None)
- return win32event.CreateEvent(None, True, False, None)
-
- def _pump_loop(self, ready: threading.Event) -> None:
- """Win32 message pump using ``MsgWaitForMultipleObjects``.
-
- Lifecycle:
- 1. SetWinEventHook for EVENT_SYSTEM_FOREGROUND.
- 2. ``ready.set()`` → start() may return.
- 3. Wait loop until stop_event is signalled.
- 4. PeekMessage drain on each wakeup.
- 5. ``UnhookWinEvent`` in finally — on the same thread that set
- it (best practice, even though OUTOFCONTEXT hooks technically
- allow it from any thread).
- """
- import ctypes # noqa: PLC0415
- from ctypes import wintypes # noqa: PLC0415
-
- import win32event # noqa: PLC0415
-
- # WinEventProc signature per Win32 documentation.
- WINEVENTPROC = ctypes.WINFUNCTYPE(
- None,
- ctypes.c_void_p, # HWINEVENTHOOK
- wintypes.DWORD, # event
- wintypes.HWND, # hwnd
- wintypes.LONG, # idObject
- wintypes.LONG, # idChild
- wintypes.DWORD, # idEventThread
- wintypes.DWORD, # dwmsEventTime
- )
-
- def _proc(hook, event, hwnd, idObject, idChild, idThread, dwmsEventTime):
- # Hard-Negative HN4: NO logging, NO await, NO PrivacyFilter
- # in this callback. Enqueue only.
- # We filter on the actual window (idObject==OBJID_WINDOW (0)).
- if idObject != 0 or idChild != 0:
- return
- if not hwnd:
- return
- payload = (time.time_ns(), int(hwnd))
- loop = self._loop
- if loop is None or loop.is_closed():
- return
- try:
- loop.call_soon_threadsafe(self._safe_enqueue, payload)
- except RuntimeError:
- # Loop closed mid-call — drop. Race-Fenster <1ms.
- self._drops_pump += 1
-
- proc_ref = WINEVENTPROC(_proc)
- # MUST be kept alive — otherwise GC'd and Win32 calls invalid memory.
- self._wineventproc_ref = proc_ref
-
- # WinDLL("user32", use_last_error=True) instead of ctypes.windll.user32:
- # (a) own instance so our argtypes settings do not affect other modules
- # (vision/screenshot.py etc.),
- # (b) use_last_error=True is required for ctypes.get_last_error() below
- # — otherwise the call always returns 0 instead of the real Win32 error.
- user32 = ctypes.WinDLL("user32", use_last_error=True)
- user32.SetWinEventHook.restype = ctypes.c_void_p
- user32.SetWinEventHook.argtypes = [
- wintypes.DWORD, # eventMin
- wintypes.DWORD, # eventMax
- ctypes.c_void_p, # hmodWinEventProc (HMODULE — pointer-sized)
- WINEVENTPROC, # pfnWinEventProc — explicit Callback-Type
- wintypes.DWORD, # idProcess
- wintypes.DWORD, # idThread
- wintypes.DWORD, # dwFlags
- ]
- user32.UnhookWinEvent.argtypes = [ctypes.c_void_p]
- user32.UnhookWinEvent.restype = ctypes.c_int
- hook = user32.SetWinEventHook(
- _EVENT_SYSTEM_FOREGROUND,
- _EVENT_SYSTEM_FOREGROUND,
- None,
- proc_ref,
- 0, # all processes
- 0, # all threads
- _WINEVENT_OUTOFCONTEXT | _WINEVENT_SKIPOWNPROCESS,
- )
- if not hook:
- err = ctypes.get_last_error()
- logger.error("SetWinEventHook failed (last_error=%d) — Watcher disabled", err)
- ready.set()
- return
-
- self._hook_handle = int(hook)
- ready.set()
-
- # MsgWaitForMultipleObjects-Loop
- QS_ALLINPUT = 0x04FF
- WAIT_OBJECT_0 = 0x00000000
- MSG_PENDING = WAIT_OBJECT_0 + 1
- INFINITE = 0xFFFFFFFF
- PM_REMOVE = 0x0001
-
- msg = wintypes.MSG()
- try:
- while True:
- rc = win32event.MsgWaitForMultipleObjects(
- [self._stop_event_handle], False, INFINITE, QS_ALLINPUT,
- )
- # Only WAIT_OBJECT_0 + 1 means "messages are pending". Anything
- # else is either the stop event (WAIT_OBJECT_0) or a wait that
- # failed — WAIT_FAILED (0xFFFFFFFF) or WAIT_ABANDONED_0 on a
- # closed/invalid stop handle. Falling through to PeekMessage on
- # a failed wait spun this thread at 100 % CPU forever, because
- # nothing in the loop can clear the failure and the wait returns
- # immediately every time. Treat any non-message result as
- # terminal and leave (same doctrine as AP-20 for socket loops):
- # stop() still joins us, and the finally block unhooks.
- if rc != MSG_PENDING:
- if rc != WAIT_OBJECT_0:
- logger.error(
- "WindowFocusWatcher: MsgWaitForMultipleObjects "
- "returned 0x%08X (last_error=%d) — pump stopped, "
- "focus tracking is off until the next start()",
- int(rc) & 0xFFFFFFFF,
- ctypes.get_last_error(),
- )
- break
- while user32.PeekMessageW(ctypes.byref(msg), 0, 0, 0, PM_REMOVE):
- user32.TranslateMessage(ctypes.byref(msg))
- user32.DispatchMessageW(ctypes.byref(msg))
- except Exception: # noqa: BLE001
- logger.exception("WindowFocusWatcher pump-loop crashed")
- finally:
- # Unregister hook — on the SAME thread that registered it. Claimed
- # atomically so a stop() whose join timed out cannot unhook the same
- # handle a second time (see _take_hook_handle).
- handle = self._take_hook_handle()
- if handle is not None:
- try:
- user32.UnhookWinEvent(handle)
- except Exception: # noqa: BLE001, S110
- # Defensive Win32 cleanup — do not escalate errors,
- # otherwise the next phase step in stop() would hang.
- pass
- self._wineventproc_ref = None
-
- # ---- Async-Side ---------------------------------------------------------
-
- def _safe_enqueue(self, payload: tuple[int, int]) -> None:
- """Runs in the asyncio loop. Drop-on-full without raising an exception."""
- try:
- self._queue.put_nowait(payload)
- except asyncio.QueueFull:
- self._drops_async += 1
-
- async def _drain_loop(self) -> None:
- """Consume the queue, calling ``_drain_once`` per item until stopped."""
- while not self._drain_stop.is_set():
- try:
- await self._drain_once()
- except asyncio.CancelledError:
- break
- except Exception: # noqa: BLE001
- logger.debug("drain iteration failed", exc_info=True)
-
- async def _drain_once(self) -> None:
- """One drain iteration: 1 item from queue (or timeout) → bus.
-
- Independently testable: tests call ``_drain_once()`` directly after
- ``_safe_enqueue()`` without starting ``_drain_loop``.
- """
- try:
- payload = await asyncio.wait_for(
- self._queue.get(), timeout=_DRAIN_GET_TIMEOUT_S,
- )
- except TimeoutError:
- return
-
- ts_ns, hwnd = payload
-
- # Dedupe: Win32 sometimes emits 2-3 EVENT_SYSTEM_FOREGROUND events
- # within <50 ms during Alt+Tab. We filter here instead of in the
- # callback (HN4).
- #
- # The lower bound matters: these timestamps come from time.time_ns(),
- # a WALL clock that can step BACKWARDS (an NTP correction, the user
- # fixing the clock, a VM resuming from suspend). A negative delta is
- # also "< 50 ms", so a single backward step used to swallow every
- # further event for the window that happened to be focused across it —
- # focus tracking silently froze on that app until the clock caught up.
- # A backward jump is not a duplicate, so it must not dedupe.
- since_last_ns = ts_ns - self._last_emit_ns
- if hwnd == self._last_hwnd and 0 <= since_last_ns < _HWND_DEDUPE_NS:
- return
-
- # Retrieve window title + PID + process name from hwnd — ctypes
- # calls + psutil are blocking, so run in to_thread.
- try:
- window_title, pid, process_name = await asyncio.to_thread(
- self._resolve_window_meta, hwnd,
- )
- except Exception: # noqa: BLE001
- logger.debug("Window-meta lookup failed for hwnd=%d", hwnd, exc_info=True)
- return
-
- if not window_title.strip() and not process_name.strip():
- # Nothing at all could be read about this window. _resolve_window_meta
- # answers ("", 0, "") both for a genuine probe failure and for a
- # window whose owner exited mid-lookup, and that is NOT a frame:
- # publishing it handed PrivacyFilter two empty strings, which match
- # no block pattern and therefore fall through to
- # "default_allow_for_unknown" — so an unidentifiable window was
- # waved through AND overwrote state.current_frame, blanking the
- # foreground context the brain reads until the next app switch.
- # The POSIX poller in this same class already refuses exactly this
- # ("the privacy filter must never be handed an empty title to wave
- # through"); the Win32 path never got the same guard.
- logger.debug(
- "Win32 window meta unresolvable for hwnd=%d — probe discarded, "
- "frame not published", hwnd,
- )
- return
-
- await self._emit_frame(
- ts_ns=ts_ns, handle=hwnd, window_title=window_title,
- pid=pid, process_name=process_name,
- )
-
- async def _emit_frame(
- self, *, ts_ns: int, handle: int, window_title: str, pid: int, process_name: str,
- ) -> None:
- """Privacy-filter + probe + publish one resolved frame.
-
- Shared tail of both frame sources — the Win32 drain loop (hwnd
- events dequeued from the WinEventHook callback) and the POSIX
- polling fallback (macOS/Linux, see below) — so every platform
- builds and publishes the identical ``FrameUpdated`` /
- ``AwarenessCaptureBlocked`` event through one code path. Callers
- are responsible for their own change-detection/dedupe before
- calling this (the Win32 path dedupes by hwnd+timestamp in
- ``_drain_once``; the POSIX path dedupes by handle+title in
- ``_poll_once``).
- """
- # PrivacyFilter — on the asyncio thread, not a native callback.
- allowed, reason = self._privacy.is_allowed(
- window_title=window_title,
- process_name=process_name,
- )
-
- # Phase A5: probes only for allowed frames (privacy + cost guard).
- # probe_all has a 200 ms hard cap and does not propagate errors.
- probe_data: dict[str, object] = {}
- if allowed and pid > 0:
- try:
- probe_data = await self._manager.probe_all(
- pid=pid, process_name=process_name,
- )
- except Exception: # noqa: BLE001
- logger.debug("probe_all failed for pid=%d", pid, exc_info=True)
- probe_data = {}
-
- # Build FrameSnapshot and set AwarenessState.current_frame.
- # Single-writer pattern: only this method writes current_frame
- # (the Win32 drain loop and the POSIX poll loop never run at the
- # same time — start() branches to exactly one of them). Readers
- # are synchronous in the same loop, no race.
- cur_frame = self._manager.state.current_frame
- idle_since_ns = cur_frame.idle_since_ns if cur_frame is not None else None
- snap = FrameSnapshot(
- timestamp_ns=ts_ns,
- active_window_title=window_title,
- active_process_name=process_name,
- active_pid=pid,
- is_capture_allowed=allowed,
- git_branch=probe_data.get("git_branch"), # type: ignore[arg-type]
- open_file_hint=probe_data.get("open_file_hint"), # type: ignore[arg-type]
- idle_since_ns=idle_since_ns,
- )
- self._manager.state.current_frame = snap
- self._last_hwnd = handle
- self._last_emit_ns = ts_ns
-
- # Publish bus event. allowed → FrameUpdated, blocked →
- # AwarenessCaptureBlocked (NOT both).
- if allowed:
- await self._bus.publish(FrameUpdated(
- window_title=window_title,
- process_name=process_name,
- pid=pid,
- is_capture_allowed=True,
- ))
- else:
- await self._bus.publish(AwarenessCaptureBlocked(
- window_title=window_title,
- process_name=process_name,
- reason=reason,
- ))
-
- @staticmethod
- def _resolve_window_meta(hwnd: int) -> tuple[str, int, str]:
- """``GetWindowTextW`` + ``GetWindowThreadProcessId`` + psutil.name().
-
- Returns ``(window_title, pid, process_name)``. On any error:
- ``("", 0, "")``. Lazy imports.
- """
- if os.name != "nt":
- return ("", 0, "")
- import ctypes # noqa: PLC0415
- from ctypes import wintypes # noqa: PLC0415
-
- try:
- # Own WinDLL instance + explicit argtypes, exactly like the
- # UnhookWinEvent call in stop(): with the shared ``ctypes.windll``
- # and no signatures, the HWND is marshalled as a 32-bit c_int, so a
- # handle above 0x7FFFFFFF raises ArgumentError (frame silently
- # dropped) instead of resolving — and binding signatures on the
- # PROCESS-WIDE windll would leak into vision/screenshot.py and
- # window_state.py, which configure the same functions themselves.
- user32 = ctypes.WinDLL("user32", use_last_error=True)
- user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
- user32.GetWindowTextLengthW.restype = ctypes.c_int
- user32.GetWindowTextW.argtypes = [
- wintypes.HWND, wintypes.LPWSTR, ctypes.c_int,
- ]
- user32.GetWindowTextW.restype = ctypes.c_int
- user32.GetWindowThreadProcessId.argtypes = [
- wintypes.HWND, ctypes.POINTER(wintypes.DWORD),
- ]
- user32.GetWindowThreadProcessId.restype = wintypes.DWORD
-
- handle = wintypes.HWND(hwnd)
- length = max(0, int(user32.GetWindowTextLengthW(handle)))
- buf = ctypes.create_unicode_buffer(length + 1)
- user32.GetWindowTextW(handle, buf, length + 1)
- title = buf.value or ""
-
- pid = wintypes.DWORD()
- user32.GetWindowThreadProcessId(handle, ctypes.byref(pid))
- pid_int = int(pid.value)
-
- try:
- import psutil # noqa: PLC0415
-
- proc_name = psutil.Process(pid_int).name()
- except Exception: # noqa: BLE001
- proc_name = ""
-
- return (title, pid_int, proc_name)
- except Exception: # noqa: BLE001
- return ("", 0, "")
-
- # ---- POSIX polling fallback (macOS/Linux) --------------------------------
-
- def _start_posix_polling(self) -> None:
- """Start the polling fallback, or degrade honestly.
-
- macOS always has a display (``probes.display_present()`` is
- unconditional there) and needs no permission just to read the
- frontmost application, so it always starts polling; a session
- that genuinely cannot be read (no pyobjc, or later a revoked
- grant) is discovered per-tick by ``_poll_once`` and disables the
- loop via the consecutive-failure counter instead of being gated
- here. Linux needs a real X11 session — headless hosts and Wayland
- compositors (no global foreground-window query by OS design, the
- same reason ``probes.has_hotkey``/``has_cursor`` refuse there) are
- rejected up front instead of polling a backend that can never work.
- """
- plat = detect_platform()
- if plat not in ("darwin", "linux"):
- logger.info(
- "window-focus tracking unavailable on this platform (%s)", plat,
- )
- return
- if plat == "linux" and (is_wayland() or not display_present()):
- logger.info(
- "window-focus tracking unavailable on this platform: "
- "no usable X11 display (headless session or Wayland)",
- )
- return
-
- self._poll_stop.clear()
- loop = asyncio.get_running_loop()
- self._poll_task = loop.create_task(
- self._poll_loop(), name="awareness-window-poll",
- )
-
- async def _stop_posix_polling(self) -> None:
- """Cancel the polling task, wait <1.5 s. Idempotent."""
- self._poll_stop.set()
- task = self._poll_task
- self._poll_task = None
- if task is None:
- return
- task.cancel()
- try:
- await asyncio.wait_for(task, timeout=_POSIX_POLL_STOP_TIMEOUT_S)
- except (TimeoutError, asyncio.CancelledError):
- pass
- except Exception: # noqa: BLE001
- logger.debug("POSIX poll task ended with exception", exc_info=True)
-
- async def _poll_loop(self) -> None:
- """Call ``_poll_once`` every ``_POSIX_POLL_INTERVAL_S`` until stopped.
-
- The failure counter is a STARTUP GATE, not a running health check: it
- only disables the loop while no probe has EVER returned a usable window,
- which is the signature of a backend that cannot work here (no pyobjc, no
- xdotool, a ``DISPLAY`` pointing at an X server that is not actually
- reachable). Once one window has been read, an empty probe is treated as a
- healthy "nothing is focused right now" observation and the loop keeps
- going.
-
- That distinction is the whole point. ``xdotool getactivewindow`` exits
- non-zero — and the probe therefore reports nothing — whenever no client
- window holds the X11 input focus: the user is on the desktop or the
- wallpaper, a window just closed, a lock/screensaver is up, or a
- pointer-focus WM briefly parked focus on the root window. All of those
- are ordinary, transient states. Counting them meant 10 s on the desktop
- permanently killed focus tracking for the rest of the session and blamed
- a missing xdotool in the log. This is the same conflation of "the backend
- is broken" with "there is momentarily nothing to report" that
- ``_poll_once`` already had to unlearn for title-less X11 windows.
-
- Waits on ``_poll_stop`` rather than a plain sleep so ``stop()`` wakes the
- loop immediately instead of waiting out the interval.
- """
- consecutive_failures = 0
- ever_succeeded = False
- while not self._poll_stop.is_set():
- try:
- ok = await self._poll_once()
- except asyncio.CancelledError:
- break
- except Exception: # noqa: BLE001
- # Mirrors the Win32 drain loop: one bad iteration must not end
- # focus tracking for the session. Without this the task died
- # with an unretrieved exception and no log line at all — the
- # feature was simply off, silently.
- logger.debug("POSIX poll iteration failed", exc_info=True)
- ok = False
-
- if ok:
- ever_succeeded = True
- consecutive_failures = 0
- elif not ever_succeeded:
- consecutive_failures += 1
- if consecutive_failures >= _POSIX_POLL_MAX_FAILURES:
- logger.info(
- "window-focus polling never produced usable window info "
- "(%d attempts) — stopping: no backend that can read the "
- "foreground window here (missing pyobjc/xdotool, or the "
- "advertised display cannot be queried)",
- consecutive_failures,
- )
- return
-
- try:
- await asyncio.wait_for(
- self._poll_stop.wait(), timeout=_POSIX_POLL_INTERVAL_S,
- )
- except TimeoutError:
- pass
- except asyncio.CancelledError:
- break
-
- async def _poll_once(self) -> bool:
- """One polling iteration: probe the foreground window, emit a frame
- via :meth:`_emit_frame` if focus actually changed.
-
- Returns ``True`` when the probe itself worked (whether or not focus
- changed — an unchanged focus is still a healthy probe), ``False``
- only when the backend answered with nothing at all (feeds the
- consecutive-failure counter in :meth:`_poll_loop`).
- Independently testable — tests call this directly instead of
- waiting out the real polling interval.
- """
- try:
- win = await asyncio.to_thread(self._posix_foreground_window)
- except Exception: # noqa: BLE001
- logger.debug("POSIX foreground-window probe failed", exc_info=True)
- return False
-
- if win is None:
- return False
-
- if not (win.title or "").strip():
- # A window WITHOUT a readable title is not a broken backend — X11
- # windows legitimately carry no name, and xdotool's getwindowname
- # can fail for one window while getactivewindow keeps working.
- # Counting it as a failure meant five such polls (10 s) permanently
- # disabled focus tracking for the whole session, with no way back
- # short of a restart. Report the probe as healthy, but publish
- # nothing: a frame with no title is unidentifiable, and the privacy
- # filter must never be handed an empty title to wave through.
- logger.debug(
- "POSIX foreground window has no readable title (handle=%s) — "
- "probe healthy, frame not published",
- win.handle,
- )
- return True
-
- changed = (win.handle, win.title) != (self._poll_last_handle, self._poll_last_title)
- if not changed:
- return True
-
- try:
- pid, process_name = await asyncio.to_thread(
- self._resolve_posix_focus_meta, win,
- )
- await self._emit_frame(
- ts_ns=time.time_ns(),
- handle=win.handle or 0,
- window_title=win.title,
- pid=pid,
- process_name=process_name,
- )
- except Exception: # noqa: BLE001
- logger.debug("POSIX frame emit failed", exc_info=True)
- return True
- # Commit the change-detection markers only AFTER the frame published.
- # Claiming the window as "already reported" before the emit turned any
- # transient failure in the tail (a raising privacy rule, a bus handler,
- # a deep probe) into a permanent one: the next tick saw an unchanged
- # focus and stayed quiet, so ``state.current_frame`` kept describing the
- # PREVIOUS window until the user happened to switch again. Retrying one
- # interval later costs nothing and is the same reasoning behind
- # ``_reset_frame_state``.
- self._poll_last_handle = win.handle
- self._poll_last_title = win.title
- return True
-
- @staticmethod
- def _posix_foreground_window() -> WindowInfo | None:
- """Thin seam over ``window_state.foreground_window`` — tests patch
- this directly to simulate macOS/Linux without a real display."""
- return window_state.foreground_window()
-
- @staticmethod
- def _resolve_posix_focus_meta(win: WindowInfo) -> tuple[int, str]:
- """Best-effort ``(pid, process_name)`` for a foreground ``WindowInfo``.
-
- The pid the PROBE already resolved wins. ``window_state.foreground_window``
- fills ``WindowInfo.pid`` on all three platforms from the very same
- window it took the title from, so using it keeps title and process
- identity from the same instant. Re-querying "who is frontmost NOW"
- instead — as this did unconditionally — pairs app A's title with app
- B's process whenever focus moves between the probe and this call
- (a 2 s poll makes that window wide open), and the PrivacyFilter then
- judges a title against the wrong process name in both directions:
- a blocked app waved through, or an allowed one blocked.
-
- Only when the probe carries no pid does this fall back to a live
- query — macOS: ``NSWorkspace``'s frontmost application (needs neither
- the Screen-Recording nor the Accessibility grant); Linux:
- :func:`_linux_window_pid` resolves the owning pid from the X11 window id.
- ``psutil`` resolves the process name from the pid on both. Never raises —
- a missing pyobjc/xdotool or a transient lookup error degrades to
- ``(0, "")``; the frame still publishes and title-based privacy filtering
- still applies.
-
- A non-positive result is normalised to ``0`` rather than passed on. A
- negative pid would travel into ``FrameSnapshot.active_pid`` and every
- consumer's ``pid > 0`` guard as a value that looks resolved but names no
- process.
- """
- pid = int(win.pid or 0)
- if pid <= 0:
- plat = detect_platform()
- if plat == "darwin":
- try:
- from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415
-
- app = NSWorkspace.sharedWorkspace().frontmostApplication()
- if app is not None:
- pid = int(app.processIdentifier())
- except Exception: # noqa: BLE001 — no pyobjc / transient AppKit error
- logger.debug("macOS frontmost pid lookup failed", exc_info=True)
- pid = 0
- elif plat == "linux" and win.handle:
- pid = _linux_window_pid(int(win.handle))
- if pid <= 0:
- return 0, ""
-
- process_name = ""
- try:
- import psutil # noqa: PLC0415
-
- process_name = psutil.Process(pid).name()
- except Exception: # noqa: BLE001
- process_name = ""
- return pid, process_name
diff --git a/jarvis/awareness/working_set.py b/jarvis/awareness/working_set.py
deleted file mode 100644
index a5166cb269..0000000000
--- a/jarvis/awareness/working_set.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""WorkingSet — Multi-Context LRU for Phase A4.
-
-Phase A4 problem (Plan §8): currently Jarvis only knows the last episode.
-When the user switches between 3 contexts (VS Code → Slack → VS Code), on
-the next wake-word they would get the Slack thread — incorrect. The Working
-Set holds up to 5 ``Context`` slots in RAM (LRU). On re-activation of a
-known context, ``snapshot_for_prompt`` returns the episode for that context —
-not "the last whatever-episode".
-
-Hard negatives (from the spec):
-- ``WorkingSet`` is NOT persisted — RAM-only. SQLite holds all episodes.
-- No singletons — one instance per ``AwarenessManager`` (DI).
-- Eviction does NOT delete episodes — only the RAM pointer; episodes remain in DB.
-- Cap = 5 slots (Plan §8).
-"""
-from __future__ import annotations
-
-import logging
-import time
-from collections import OrderedDict
-
-from jarvis.awareness.context import Context
-
-logger = logging.getLogger(__name__)
-
-
-# Plan §8: max 5 LRU slots.
-DEFAULT_MAX_SLOTS: int = 5
-
-
-class WorkingSet:
- """LRU cache of ``Context`` slots.
-
- Identity key is ``Context.project_root`` (strings — hostname/cwd/
- process_name). The ordering inside the internal ``OrderedDict`` is
- recency order: last entry = most recent context, first entry =
- oldest (= eviction candidate).
-
- API:
- ``observe(context)`` Mark a context as active, promotes it to top.
- ``set_episode(root, id)`` Link a persisted episode ID to the
- corresponding context slot.
- ``get(root)`` LRU-fresh lookup, returns Context or None.
- ``contexts()`` Iterable in MRU order (most recent first).
- ``size`` Number of slots currently occupied.
- """
-
- def __init__(self, *, max_slots: int = DEFAULT_MAX_SLOTS) -> None:
- if max_slots <= 0:
- raise ValueError(f"max_slots must be > 0, got {max_slots}")
- self._max_slots = max_slots
- # OrderedDict: insertion-order is recency. move_to_end()=promote.
- self._slots: OrderedDict[str, Context] = OrderedDict()
-
- # ---- Mutation -----------------------------------------------------------
-
- def observe(self, context: Context) -> Context | None:
- """Mark a context as just-active (LRU promote).
-
- - If ``project_root`` is already present: the context is re-promoted
- (moved to the end of the OrderedDict). Fields are merged: the new
- ``task_label``/``last_seen_ns`` overwrites the old one; the old
- ``last_episode_id`` is preserved unless the new
- ``context.last_episode_id`` is not None.
- - If ``project_root`` is not yet present: a new slot is created.
- If the LRU is full: ``popitem(last=False)`` evicts the oldest
- (== first entry).
-
- Returns: the evicted Context if an eviction occurred; otherwise None.
- (Used by the AwarenessManager to optionally emit ``ContextSwitched``
- events.)
- """
- evicted: Context | None = None
- existing = self._slots.get(context.project_root)
- if existing is not None:
- # Merge: adopt new fields; keep last_episode_id only if the new
- # value is not None (otherwise retain the old one).
- merged = Context(
- project_root=context.project_root,
- task_label=context.task_label or existing.task_label,
- last_episode_id=(
- context.last_episode_id
- if context.last_episode_id is not None
- else existing.last_episode_id
- ),
- # Always take the new value here: this is an observe() call,
- # so the caller is asserting "this slot was just touched". A
- # bare ``or`` would short-circuit on the integer 0 — uncommon
- # but semantically wrong; ``time.time_ns()`` of a Unix-epoch
- # boot would otherwise be discarded in favour of the older
- # mtime, the exact opposite of LRU's promote-on-observe rule.
- last_seen_ns=context.last_seen_ns,
- process_name=context.process_name or existing.process_name,
- )
- self._slots[context.project_root] = merged
- self._slots.move_to_end(context.project_root)
- return None
-
- # New slot — check whether the LRU is full.
- if len(self._slots) >= self._max_slots:
- # popitem(last=False) removes the OLDEST (FIFO-insertion order).
- _, evicted = self._slots.popitem(last=False)
- self._slots[context.project_root] = context
- return evicted
-
- def set_episode(self, project_root: str, episode_id: int) -> bool:
- """Links a just-persisted episode to its context slot.
-
- Called by the AwarenessManager on ``EpisodeRecorded`` — the episode
- belongs to the CURRENT frame context, whose project_root was already
- registered via ``observe``.
-
- Returns True if the slot was updated, False if the slot was evicted
- in the meantime (e.g. during rapid multi-context switches within a
- Verdichter call).
- """
- existing = self._slots.get(project_root)
- if existing is None:
- return False
- updated = Context(
- project_root=existing.project_root,
- task_label=existing.task_label,
- last_episode_id=episode_id,
- last_seen_ns=existing.last_seen_ns,
- process_name=existing.process_name,
- )
- self._slots[project_root] = updated
- # An episode update does NOT promote — recency comes from observe().
- return True
-
- # ---- Read ---------------------------------------------------------------
-
- def get(self, project_root: str) -> Context | None:
- """Lookup without promote — read-only, non-mutating."""
- return self._slots.get(project_root)
-
- def contexts(self) -> list[Context]:
- """Snapshot of all contexts in MRU order (most recent first).
-
- Returns a new list — the caller may mutate it without affecting the
- WorkingSet.
- """
- # OrderedDict iterates in insertion order (FIFO); we want MRU-first,
- # so reverse.
- return list(reversed(self._slots.values()))
-
- @property
- def size(self) -> int:
- return len(self._slots)
-
- @property
- def max_slots(self) -> int:
- return self._max_slots
-
- @property
- def current(self) -> Context | None:
- """The most recent context (MRU-first), or None if the set is empty."""
- if not self._slots:
- return None
- # next() over reversed gives MRU.
- return next(reversed(self._slots.values()))
-
- # ---- Render -------------------------------------------------------------
-
- def render_for_prompt(self, *, max_chars: int = 400) -> str:
- """Compact plain-text render for system-prompt injection.
-
- Returns a multi-line block (or empty string when 0 or 1 slot — with
- only one context the working set adds nothing,
- ``AwarenessState.snapshot_for_prompt`` already renders the single
- episode).
-
- Format:
- Active contexts:
- - <project_root>: <task_label> [Episode #<id>]
- - <project_root>: <task_label> [Episode #<id>]
- ...
- """
- if len(self._slots) <= 1:
- return ""
-
- lines = ["Active contexts:"]
- for ctx in self.contexts():
- ep_part = (
- f" [Episode #{ctx.last_episode_id}]"
- if ctx.last_episode_id is not None
- else ""
- )
- label = ctx.task_label or ctx.project_root
- lines.append(f"- {ctx.project_root}: {label}{ep_part}")
-
- text = "\n".join(lines)
- if len(text) > max_chars:
- text = text[: max_chars - 1] + "…"
- return text
-
- # ---- Test-Helper --------------------------------------------------------
-
- def __len__(self) -> int:
- return len(self._slots)
-
- def __contains__(self, project_root: object) -> bool:
- return project_root in self._slots
-
-
-def now_ns() -> int:
- """Wrapper for time.time_ns() — for test patching."""
- return time.time_ns()
diff --git a/jarvis/board/categories.py b/jarvis/board/categories.py
index 41c72233bb..a8f7d0bf23 100644
--- a/jarvis/board/categories.py
+++ b/jarvis/board/categories.py
@@ -35,7 +35,7 @@ _FALLBACK = "system"
# Substring rules, evaluated in this order — FIRST hit wins. Order matters:
# "knowledge" is placed before "community" so that the "recall" substring in
-# ``awareness-recall`` / ``wiki-recall`` is not mis-caught by the "call" needle
+# ``wiki-recall`` is not mis-caught by the "call" needle
# of the community bucket.
_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
(
diff --git a/jarvis/brain/ack_generator.py b/jarvis/brain/ack_generator.py
index c6d9f3f8ad..4cf60c0d51 100644
--- a/jarvis/brain/ack_generator.py
+++ b/jarvis/brain/ack_generator.py
@@ -20,7 +20,7 @@ Design constraints:
user knows the right intent was understood — generic "okay, one moment"
variants only as fallback for tools whose args are too noisy to echo
(raw shell commands, long harness tasks).
-* **Skip-list.** Passive state reads (awareness-snapshot, screen-snapshot,
+* **Skip-list.** Passive state reads (screen-snapshot,
wiki lookups) and low-latency individual UI events (click, hotkey,
type-text) return ``None`` because a chat-style ack would chatter or feel
uncanny.
@@ -117,7 +117,6 @@ def is_voice_control_utterance(utterance: str | None) -> bool:
# sequence (type-text streams characters; click is single-pixel).
ACK_SKIP_TOOLS: frozenset[str] = frozenset({
# passive observations
- "awareness_snapshot",
"screen_snapshot",
"whoami",
# fast passive memory reads (2026-07-06: wiki-recall answered in 72 ms —
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.py
index 73f0efb9d5..40aad58036 100644
--- a/jarvis/brain/dispatcher.py
+++ b/jarvis/brain/dispatcher.py
@@ -141,7 +141,7 @@ class BrainDispatcher:
"""
tid = trace_id or uuid4()
messages: list[BrainMessage] = list(history or [])
- # Wave 2 (omni-latency): per-turn dynamic context (date/awareness/wiki)
+ # Wave 2 (omni-latency): per-turn dynamic context (date/wiki)
# rides on the user message, NOT the cached system prompt, so the
# provider prompt cache stays warm. It is never stored in history
# (the manager appends the clean user_text there).
diff --git a/jarvis/brain/evidence_gate.py b/jarvis/brain/evidence_gate.py
index 9f9038d4e2..6b5739354a 100644
--- a/jarvis/brain/evidence_gate.py
+++ b/jarvis/brain/evidence_gate.py
@@ -203,7 +203,7 @@ _REFUSAL_DE: dict[str, str] = {
"repos": "Ich habe aktuell keinen Zugriff auf deine Repositories.", # i18n-allow
"deployments": "Ich habe aktuell keinen Zugriff auf deine Deployments.", # i18n-allow
"cloud": "Ich habe aktuell keinen Zugriff auf deine Cloud-Abrechnung.", # i18n-allow
- "activity": "Ich kann gerade nicht auf deinen Aktivitätsverlauf zugreifen.", # i18n-allow
+ "activity": "Ich zeichne keinen Aktivitätsverlauf auf.", # i18n-allow
}
_REFUSAL_DE_FALLBACK = "Dafuer habe ich aktuell keinen Datenzugriff." # i18n-allow
@@ -214,7 +214,7 @@ _REFUSAL_EN: dict[str, str] = {
"repos": "I have no access to your repositories right now.",
"deployments": "I have no access to your deployments right now.",
"cloud": "I have no access to your cloud billing right now.",
- "activity": "I can't access your activity history right now.",
+ "activity": "I don't keep a history of your activity.",
}
_REFUSAL_EN_FALLBACK = "I have no data access for that right now."
@@ -228,7 +228,7 @@ _REFUSAL_ES: dict[str, str] = {
"repos": "Ahora mismo no tengo acceso a tus repositorios.", # i18n-allow
"deployments": "Ahora mismo no tengo acceso a tus despliegues.", # i18n-allow
"cloud": "Ahora mismo no tengo acceso a tu facturación en la nube.", # i18n-allow
- "activity": "Ahora mismo no puedo acceder a tu historial de actividad.", # i18n-allow
+ "activity": "No guardo un historial de tu actividad.", # i18n-allow
}
_REFUSAL_ES_FALLBACK = "Ahora mismo no tengo acceso a esos datos." # i18n-allow
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index f41cbce0c3..3e69368970 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -20,10 +20,6 @@ from typing import Any, Literal
log = logging.getLogger(__name__)
-# Deadline for one awareness summary on a subscription CLI: a CLI turn spends
-# seconds on process start before the model even answers.
-_VERDICHTER_SUBSCRIPTION_TIMEOUT_S = 60.0
-
BrainCallback = Callable[[str], Awaitable[str]]
# Router-tier: pure-dispatcher set (grown via documented ADR-0011 amendments;
@@ -56,7 +52,7 @@ BrainCallback = Callable[[str], Awaitable[str]]
# Rationale: Hauptjarvis is a pure dispatcher. Direct actions outside this
# list (open_app, type_text, remember, whoami …) are delegated to a background
# worker — the router delegates them via ``spawn_worker``. Read-only lookups
-# (search-web, wiki-recall, awareness-recall) and safe-gated direct actions
+# (search-web, wiki-recall) and safe-gated direct actions
# (computer-use, cli-tools, plugin-tools) are router-tier by design — see the
# ADR-0011 amendments (2026-05-24 CLI, 2026-05-29 Computer-Use, 2026-06-01
# plugins, 2026-06-10 inline web search).
@@ -109,15 +105,6 @@ ROUTER_TOOLS = frozenset({
# (AP-5/AP-14). See ADR-0011 amendment "Every app action".
"find-app-action",
"run-app-action",
- # Phase A1: synchronous state read on the AwarenessManager (Plan §5).
- # NO brain call, NO IO — property read only.
- "awareness-snapshot",
- # Phase A3 (Plan §7): BM25 full-text search across the recent episode
- # log. The plan originally placed this in a Sub-Jarvis tier; Welle 4
- # deleted that tier, so it lives here. Still read-only, still safe to
- # call without confirmation. See ADR on awareness routing for the
- # placement rationale.
- "awareness-recall",
# Agent society (2026-09-02): the voice front door of the user's named
# agents. ``delegate-to-agent`` appends ONE ASSIGN envelope to the
# society board and acknowledges inside the voice budget; the society
@@ -397,8 +384,6 @@ def _load_tools_for_tier(
people: Any,
config: Any,
mission_manager: Any = None,
- awareness_manager: Any = None,
- recall_store: Any = None,
contacts: Any = None,
) -> dict[str, Any]:
"""Load all tools for the given tier and instantiate them.
@@ -409,7 +394,7 @@ def _load_tools_for_tier(
the heavy worker runs as an external subprocess via the Mission-Manager.
Encapsulates entry-point discovery + special cases (dispatch-to-harness,
- spawn-worker, whoami, awareness-snapshot).
+ spawn-worker, whoami).
Args:
tier: currently only ``"router"``.
@@ -552,18 +537,6 @@ def _load_tools_for_tier(
)
elif ep.name == "whoami":
inst = cls(profile=user_profile, people=people)
- elif ep.name == "awareness-snapshot":
- if awareness_manager is None:
- log.debug("awareness-snapshot skipped: no AwarenessManager")
- continue
- inst = cls(manager=awareness_manager)
- elif ep.name == "awareness-recall":
- # Phase A3: the tool itself stays loaded even when the store
- # is None — its execute() returns a clean "unavailable" error
- # in that case rather than disappearing from the schema mid
- # session. That keeps the tool surface stable for the router
- # brain across awareness on/off toggles.
- inst = cls(recall_store=recall_store)
elif ep.name == "wiki-recall":
# Phase B5: build VaultSearch with the configured vault root.
# The search instance is created once per brain build and
@@ -612,7 +585,7 @@ def _load_tools_for_tier(
# emit ProfileUpdated on `bus` for live UI sync. Loads even when
# user_profile is None — execute() returns a clean error then, so
# the tool surface stays stable across sessions (mirrors
- # awareness-recall / wiki-ingest).
+ # wiki-ingest).
inst = cls(profile_resolver=lambda: user_profile, bus=bus)
elif ep.name in ("contact-lookup", "contact-upsert", "call-contact"):
# Chunk B (jarvis-contacts): all three consume Contract 1
@@ -621,7 +594,7 @@ def _load_tools_for_tier(
# until Chunk A merges (or if the store fails to build) — the
# tools then return a clean "contacts unavailable" error rather
# than disappearing from the schema mid-session (stable tool
- # surface, mirrors awareness-recall / wiki-ingest). call-contact
+ # surface, mirrors wiki-ingest). call-contact
# additionally lazy-loads Contract 2 (place_call) + the telephony
# config at execute time, degrading to a clear English no-op when
# the [telephony] extra / Chunk C is absent.
@@ -975,177 +948,6 @@ def _phase2_full_brain(
# but the harness is unregistered — that block is inert (Welle-4 removal).
warn_if_phantom_worker_harness(config, harness_manager)
- # Phase A1: build the AwarenessManager (DI for the awareness-snapshot tool).
- # Do NOT start it here — start()/stop() is the responsibility of the app layer
- # (DesktopApp._start_speech_and_orb or similar). Without start() the tool
- # returns an empty snapshot ("") — that is acceptable for Plan-AC; the tool
- # schema entry in the router is the actual A1 deliverable.
- awareness_manager: Any | None = None
- if config.awareness.enabled:
- from jarvis.awareness.manager import AwarenessManager
-
- awareness_manager = AwarenessManager(config.awareness, bus=bus)
-
- # Phase A2: build the Verdichter brain (Haiku) as a separate brain
- # instance and attach it to the AwarenessManager. Hard Negative §6:
- # the Verdichter is a DIRECT brain call, NOT spawn_worker. Therefore
- # its own instance via BrainProviderRegistry, NOT the router brain.
- v_cfg = config.awareness.verdichter
- if v_cfg.enabled:
- try:
- from jarvis.awareness.verdichter import Verdichter
- from jarvis.brain.provider_registry import BrainProviderRegistry
-
- # BUG-LIVE-04 (2026-05-14) — honour the user-mandate "no
- # Anthropic account". `AwarenessVerdichterConfig` still
- # defaults to provider="claude-api" / model="claude-haiku"
- # for legacy compatibility, but the user's
- # `[brain.primary]` is the real source of truth: every
- # other brain-call path (Critic, ack-brain, sub-jarvis
- # chain) routes through it. The verdichter is the last
- # Anthropic-hardcoded hold-out — when primary is
- # non-Claude, redirect this call too so live logs stop
- # screaming `Your credit balance is too low to access
- # the Anthropic API` every 30 seconds.
- v_provider = v_cfg.provider
- v_model = v_cfg.model
- # Redirect off the legacy claude-api default in TWO cases:
- # (a) the user picked a different `[brain.primary]` (the
- # original BUG-LIVE-04 redirect), OR
- # (b) primary is STILL the claude-api default but the host has
- # NO usable Anthropic credential — then cross to the first
- # reachable keyed family (open-source AP-22). Without (b)
- # the awareness loop repeat-401's every ~30 s on a machine
- # whose only key is elsewhere. This is a read-only
- # background build, off the voice hot path (AP-9). Reuses
- # the resolver's key-aware family probe, not a hardcoded
- # provider list.
- if v_provider == "claude-api":
- from jarvis.brain.resolver import (
- _provider_reachable,
- _reachable_keyed_families,
- )
-
- redirect_target: str | None = None
- if config.brain.primary != "claude-api":
- redirect_target = config.brain.primary
- elif not _provider_reachable(config, "claude-api"):
- families = _reachable_keyed_families(
- config, exclude=frozenset({"claude-api"}),
- )
- if families:
- redirect_target = families[0][0]
- if redirect_target and redirect_target != "claude-api":
- v_provider = redirect_target
- primary_cfg = config.brain.providers.get(v_provider)
- # Verdichter is short, factual, latency-sensitive — pick
- # a lightweight model: the provider's configured `model`,
- # then its `deep_model`, then the family's light tier
- # default (never leave a claude model id on a non-claude
- # provider).
- chosen_model = None
- if primary_cfg is not None:
- chosen_model = (
- getattr(primary_cfg, "model", None)
- or getattr(primary_cfg, "deep_model", None)
- )
- if not chosen_model:
- from jarvis.brain.manager import get_tier_default_model
-
- chosen_model = get_tier_default_model(
- "router", v_provider,
- ) or get_tier_default_model("deep", v_provider)
- if chosen_model:
- v_model = str(chosen_model)
- log.info(
- "Verdichter provider redirected: claude-api -> %s "
- "(brain.primary mandate / no usable Anthropic "
- "credential, BUG-LIVE-04 + AP-22)",
- v_provider,
- )
-
- v_registry = BrainProviderRegistry()
- from jarvis.brain.resolver import SubscriptionFirstBrain
-
- # Episode summaries are background work: a connected
- # subscription writes them, the keyed brain above only when
- # none is signed in. A CLI turn takes seconds, so the call
- # deadline is widened to the subscription budget.
- v_brain = SubscriptionFirstBrain(
- config,
- v_registry.instantiate(v_provider, model=v_model),
- cli_timeout_s=_VERDICHTER_SUBSCRIPTION_TIMEOUT_S,
- )
- if v_cfg.timeout_s < _VERDICHTER_SUBSCRIPTION_TIMEOUT_S:
- v_cfg = v_cfg.model_copy(
- update={"timeout_s": _VERDICHTER_SUBSCRIPTION_TIMEOUT_S}
- )
- awareness_manager._verdichter = Verdichter( # noqa: SLF001
- brain=v_brain, config=v_cfg,
- )
- log.info(
- "Verdichter aktiv (provider=%s model=%s timeout=%.1fs)",
- v_provider, v_model, v_cfg.timeout_s,
- )
- except Exception as exc: # noqa: BLE001
- log.warning("Verdichter could not be initialized: %s", exc)
- awareness_manager._verdichter = None # noqa: SLF001
-
- # Phase A2: build the StoryTracker and attach it to the manager. Lifecycle
- # (start/stop) is handled by the manager in start() — analogous to Watchers.
- # Prerequisites: Verdichter + Recall + story.enabled.
- s_cfg = config.awareness.story
- v_inst = getattr(awareness_manager, "_verdichter", None)
- if s_cfg.enabled and v_inst is not None and recall is not None:
- try:
- from jarvis.awareness.story import StoryTracker
-
- awareness_manager._story_tracker = StoryTracker( # noqa: SLF001
- manager=awareness_manager,
- bus=bus,
- recall=recall,
- verdichter=v_inst,
- config=s_cfg,
- )
- log.info(
- "StoryTracker konfiguriert (buffer_max=%d, min_dur=%ds, "
- "hard_timer=%dmin)",
- s_cfg.buffer_max, s_cfg.episode_min_duration_s,
- s_cfg.hard_timer_min,
- )
- except Exception as exc: # noqa: BLE001
- log.warning("StoryTracker could not be initialized: %s", exc)
- awareness_manager._story_tracker = None # noqa: SLF001
-
- # Phase A5-Lite: probes (GitProbe + FileSystemProbe). Called by the
- # watcher drain loop via manager.probe_all() in parallel within a
- # 200 ms total budget. FileSystemProbe requires start/stop —
- # AwarenessManager wires that in start()/stop().
- p_cfg = config.awareness.probes
- if p_cfg.enabled:
- try:
- from jarvis.awareness.probes import FileSystemProbe, GitProbe
-
- probes_list: list = []
- if p_cfg.enable_git:
- probes_list.append(GitProbe())
- if p_cfg.enable_filesystem:
- fs_probe = FileSystemProbe(
- bus=bus,
- max_watched_roots=p_cfg.fs_max_watched_roots,
- )
- probes_list.append(fs_probe)
- awareness_manager._fs_probe = fs_probe # noqa: SLF001
- awareness_manager._probes = probes_list # noqa: SLF001
- log.info(
- "Awareness-Probes konfiguriert: %s (budget=%dms)",
- [type(p).__name__ for p in probes_list], p_cfg.total_budget_ms,
- )
- except Exception as exc: # noqa: BLE001
- log.warning("Probes could not be initialized: %s", exc)
- awareness_manager._probes = [] # noqa: SLF001
- awareness_manager._fs_probe = None # noqa: SLF001
-
# Build tools — Wave 4: no sub-tier any more; the Jarvis-Agent worker runs
# as an external subprocess via MissionManager. If a MissionManager is
# already present in ``app.state`` (server bootstrap), we pass it to
@@ -1169,8 +971,6 @@ def _phase2_full_brain(
people=people,
config=config,
mission_manager=mission_manager_ref,
- awareness_manager=awareness_manager,
- recall_store=recall,
contacts=contact_store,
)
local_action_tools = _load_local_action_tools(
@@ -1197,7 +997,6 @@ def _phase2_full_brain(
user_profile=user_profile,
soul=soul,
people=people,
- awareness_manager=awareness_manager,
contacts=contact_store,
)
@@ -1581,14 +1380,6 @@ def _phase2_full_brain(
from jarvis.brain.wiki_context import WikiContextInjector
manager._wiki_injector = WikiContextInjector(search=None)
- # B5 follow-up (2026-05-13): expose awareness_manager so the desktop-app
- # startup hook can call awareness_manager.start(). Without this, the
- # StoryTracker never subscribes to ResponseGenerated and no episode is
- # ever written, which prevents SessionRollupWorker from triggering the
- # WikiCurator at idle.
- if awareness_manager is not None:
- manager._awareness_manager = awareness_manager # noqa: SLF001
-
return manager
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index de9f69b1c1..9a0c2691f3 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -128,7 +128,6 @@ from .turn_planner import is_contextual_follow_up, plan_turn
from .voice_command_gate import match_voice_command
if TYPE_CHECKING:
- from jarvis.awareness.manager import AwarenessManager
from jarvis.brain.evidence_gate import EvidenceVerdict
from jarvis.brain.wiki_context import WikiContextInjector
from jarvis.control.cost import CostMeter as CostMeterLike
@@ -2746,7 +2745,6 @@ class BrainManager:
people: PersonStore | None = None,
curator: Curator | None = None,
cost_meter: "CostMeterLike | None" = None, # noqa: UP037
- awareness_manager: "AwarenessManager | None" = None, # noqa: UP037
wiki_injector: "WikiContextInjector | None" = None, # noqa: UP037
contacts: Any = None,
readback_composer: "ReadbackComposer | None" = None, # noqa: UP037
@@ -2795,10 +2793,6 @@ class BrainManager:
# call, with the EXISTING canned line as the instant fallback. None on the
# bare/CLI managers and in tests => unchanged canned behavior (risk-free).
self._readback_composer = readback_composer
- # Phase A1: optional AwarenessManager. When set, _build_system_prompt()
- # injects a compact live snapshot (window/idle) as a fallback in case
- # the LLM does NOT call the awareness-snapshot tool. Plan §5 "Files to Modify".
- self._awareness_manager = awareness_manager
# Phase 5 / ADR-0006: optional budget hook. Fed with aggregated usage
# post-call; pre-call blocks when in cooldown or when the task/daily
# budget is exceeded. When None, the feature is completely inactive —
@@ -2980,7 +2974,6 @@ class BrainManager:
user_profile: UserProfile | None = None,
soul: Soul | None = None,
people: PersonStore | None = None,
- awareness_manager: "AwarenessManager | None" = None, # noqa: UP037
contacts: Any = None,
) -> BrainManager:
"""Builds a BrainManager from the tier-specific config.
@@ -3167,7 +3160,6 @@ class BrainManager:
user_profile=user_profile,
soul=soul,
people=people,
- awareness_manager=awareness_manager,
contacts=contacts,
)
manager._configured_fallbacks = configured_fallbacks
@@ -3785,7 +3777,7 @@ class BrainManager:
stacks for a voice turn (name, soul, persona, the assistant file, the
user's profile, people, contacts, the identity card, core memory, the
skills section, the tool-routing rules), the wiki context this turn's
- text pulls in, and the per-turn context (date, awareness). Read-only:
+ text pulls in, and the per-turn context (date). Read-only:
nothing is stored on the manager, so a voice turn running alongside
sees no trace of it.
"""
@@ -4371,31 +4363,12 @@ class BrainManager:
cm = cm[:20_000] + "…"
parts.append(cm)
- # Phase A1: awareness snapshot as fallback when the LLM does not
- # actively call the awareness-snapshot tool. Defensive try/except
- # because a state read must never crash the system-prompt build.
- # Wave 2 (omni-latency): in cache-optimized mode this moves to the
- # per-turn user message (_build_turn_context) so the cached system
- # prefix stays byte-stable across turns. Legacy mode keeps it here.
- if self._awareness_manager is not None and not self._cache_optimized():
- try:
- snap = self._awareness_manager.state.snapshot_for_prompt(max_chars=4_000)
- if snap:
- parts.append(
- "CURRENT CONTEXT (background, for orientation only, do "
- "NOT read aloud or enumerate unless the user asks "
- f"directly):\n{snap}"
- )
- except Exception: # noqa: BLE001
- pass
-
# Skills-Brain-Integration (Track B): surface the installed, active
# user skills so the router-tier brain can actually choose ``run_skill``
# for them. Without this block the ``run-skill`` tool is registered but
# the brain never learns which skills exist, so it is never selected.
- # Static content (changes only on install/promote), so unlike the
- # per-turn awareness snapshot above it stays in the cached system
- # prefix — mirrors the capability block below. Defensive try/except:
+ # Static content (changes only on install/promote), so it stays in the
+ # cached system prefix — mirrors the capability block below. Defensive try/except:
# a renderer fault must never crash the system-prompt build. The lazy
# import is intentional so a monkeypatched renderer resolves correctly.
try:
@@ -4642,7 +4615,7 @@ class BrainManager:
def _build_turn_context(self) -> str:
"""Per-turn dynamic context for the user message (cache-optimized mode).
- Date/time + awareness snapshot + wiki context. Empty in legacy mode
+ Date/time + wiki context. Empty in legacy mode
(there these live in the system prompt instead). Riding on the user
message keeps the cached system prefix byte-stable across turns, which
is what actually lets the Gemini/Anthropic prompt cache hit.
@@ -4672,17 +4645,6 @@ class BrainManager:
private = _TURN_OVERRIDE.get()
if private is not None and private.tool_context.get("tool_origin") == "society":
return "\n\n".join(parts)
- if self._awareness_manager is not None:
- try:
- snap = self._awareness_manager.state.snapshot_for_prompt(max_chars=4_000)
- if snap:
- parts.append(
- "CURRENT CONTEXT (background, for orientation only, do "
- "NOT read aloud or enumerate unless the user asks "
- f"directly):\n{snap}"
- )
- except Exception: # noqa: BLE001
- pass
if self._wiki_context_suffix:
parts.append(self._wiki_context_suffix)
agentic_block = self._agentic_focus_block()
@@ -4694,8 +4656,7 @@ class BrainManager:
"""Workspace-awareness block while the Agentic IDE's focus mode is on.
Pure in-memory read (the session's cached project profile + each
- terminal's ring buffer), so it stays off the latency budget the way
- awareness does (AP-9). Any failure degrades to no block — a coding-mode
+ terminal's ring buffer), so it stays off the latency budget (AP-9). Any failure degrades to no block — a coding-mode
convenience must never be able to break a voice turn.
"""
try:
@@ -5418,16 +5379,6 @@ class BrainManager:
domain_map = dict(
connected_domain_tool_map(cli_reg) if cli_reg is not None else {}
)
- # The "activity" (screen / window-history) domain is served by the
- # always-on internal awareness-recall tool, not a connected CLI, so
- # wire it into the domain→tool map here. Without a mandated tool the
- # fast brain confabulates "der lokale Verlaufsspeicher ist nicht
- # verfügbar" without ever calling awareness-recall (live 2026-06-18,
- # proven from the log). Guarded on the tool actually being
- # registered so a deployment without awareness degrades to the
- # gate's honest refusal, never a mandate for a missing tool.
- if "awareness-recall" in (getattr(self, "_tools", None) or {}):
- domain_map.setdefault("activity", "awareness-recall")
def _hint(domain: str, lang: str) -> str:
if cli_reg is None:
@@ -5463,48 +5414,6 @@ class BrainManager:
log.debug("evidence gate degraded to PASS", exc_info=True)
return EvidenceVerdict(kind="pass")
- async def _prefetch_activity_block(
- self, tool_name: str, user_text: str, *, trace_id: Any = None,
- ) -> str:
- """Deterministically run the safe, read-only awareness-recall tool.
-
- The evidence gate's ``activity`` domain mandates ``awareness-recall``,
- but the fast brain does not reliably call a soft-mandated tool (live
- 2026-06-18). Rather than depend on the model, the manager runs the tool
- itself and injects the rendered timeline as answer-context. Goes through
- the ``ToolExecutor`` (never a direct ``Tool.execute`` — AP-3) so the
- risk-tier/audit path is honoured. Returns the rendered output, or ``""``
- when the tool is missing / errors / yields nothing (the caller then
- keeps the soft mandate so the honest fallback fires, never a
- confabulation).
- """
- tool = (self._tools or {}).get(tool_name)
- if tool is None or self._tool_executor is None:
- log.warning(
- "activity pre-fetch skipped: tool=%r present=%s executor=%s",
- tool_name, tool is not None, self._tool_executor is not None,
- )
- return ""
- try:
- res = await self._tool_executor.execute(
- tool,
- {"query": user_text, "since_minutes": 1440},
- user_utterance=user_text,
- trace_id=trace_id,
- )
- except Exception: # noqa: BLE001 — pre-fetch is best-effort, never fatal
- log.warning("activity pre-fetch raised", exc_info=True)
- return ""
- ok = bool(getattr(res, "success", False))
- out = str(getattr(res, "output", "") or "").strip()
- log.info(
- "activity pre-fetch result: success=%s out_len=%d err=%r",
- ok, len(out), getattr(res, "error", None),
- )
- if ok:
- return out
- return ""
-
def _is_smalltalk(self, user_text: str) -> bool:
"""Pure smalltalk allowlist check — independent of spawn-verb logic.
@@ -11578,37 +11487,11 @@ class BrainManager:
"Evidence gate: domain=%s requires tool %s this turn",
verdict.domain, verdict.tool_name,
)
- injected = False
- if verdict.domain == "activity":
- # The fast brain will NOT reliably honor a soft tool directive
- # (live 2026-06-18: awareness-recall was mandated yet never
- # called — executed=[] in the log — and the model confabulated
- # "der lokale Verlaufsspeicher ist nicht verfügbar"). The tool
- # is internal, read-only and safe, so run it deterministically
- # HERE (via the ToolExecutor) and inject its result as concrete
- # answer-context. The brain then answers from real data with no
- # dependency on its tool-calling discretion; the honest-fallback
- # guard is intentionally left disarmed because the data is
- # already in hand.
- block = await self._prefetch_activity_block(
- verdict.tool_name, user_text, trace_id=turn_trace_id,
- )
- if block:
- self._evidence_directive = (
- "The user is asking what they had open / were doing on "
- "their computer. Their ACTUAL recent on-device activity "
- "is below — answer the question from THIS data, "
- "naturally and concisely. The awareness store IS "
- "available; never claim it is unavailable.\n\n" + block
- )
- self._evidence_required_tool = ""
- injected = True
- if not injected:
- self._evidence_directive = verdict.directive
- self._evidence_required_tool = verdict.tool_name
- # Persist the domain so the honest "couldn't reach X" fallback can
- # NAME the capability (B3) instead of the generic "the tool".
- self._evidence_required_domain = verdict.domain
+ self._evidence_directive = verdict.directive
+ self._evidence_required_tool = verdict.tool_name
+ # Persist the domain so the honest "couldn't reach X" fallback can
+ # NAME the capability (B3) instead of the generic "the tool".
+ self._evidence_required_domain = verdict.domain
# Say-do honesty guard for WRITES. The read evidence gate above never
# fires on a "save this" turn (it is not a lookup), so a confirmed offer
@@ -11882,7 +11765,7 @@ class BrainManager:
self._wiki_context_suffix = ""
# Wave 2 (omni-latency): assemble the per-turn dynamic context (date +
- # awareness + wiki) once. In cache-optimized mode it rides on the user
+ # wiki) once. In cache-optimized mode it rides on the user
# message (keeping the cached system prompt stable); empty in legacy
# mode. Reused for every provider in the fallback chain below.
turn_context = self._build_turn_context()
@@ -13275,16 +13158,11 @@ class BrainManager:
harness_manager = HarnessManager(bus=self._bus)
- # ROOT CAUSE of the "local history store is unavailable"
- # voice bug (live 2026-06-18): this rebuild — triggered by EVERY
- # CLI/MCP connect at boot ("Tool-Registry refreshed: 29 -> 107") —
- # used to drop the four shared DI references the boot path passes, so
- # the rebuilt awareness-recall got recall_store=None (and
- # awareness-snapshot/contact/spawn_worker lost their managers too).
- # awareness-recall then returned "awareness recall store unavailable"
- # FOREVER after the first CLI connected, and the brain faithfully
- # relayed that — it was a genuine outage, never a confabulation. The
- # boot DI MUST be mirrored here so a refresh preserves it.
+ # This rebuild runs on EVERY CLI/MCP connect at boot ("Tool-Registry
+ # refreshed: 29 -> 107"). It must mirror the shared DI references
+ # the boot path passes, or the rebuilt tools lose their managers
+ # (live 2026-06-18: contact/spawn_worker went dark after the first
+ # CLI connected).
new_tools = _load_tools_for_tier(
tier,
bus=self._bus,
@@ -13294,8 +13172,6 @@ class BrainManager:
people=self._people,
config=self._config,
mission_manager=_resolve_mission_manager(),
- awareness_manager=self._awareness_manager,
- recall_store=self._recall,
contacts=self._contacts,
)
new_local_action_tools = _load_local_action_tools(
@@ -13601,7 +13477,7 @@ class BrainManager:
return await run_selected(
selection=selected, prompt=prompt, tool_names=tuple(tools), trace_id=trace_id
)
- # The per-turn context (date/time, awareness, wiki) rides on the user
+ # The per-turn context (date/time, wiki) rides on the user
# message in cache-optimized mode; without it a scheduled turn did not
# know what day it was (BUG-212 — the morning brief prompts say "the
# date is in your context" and it was not). Legacy mode carries it in
diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.py
index d3c43f84a8..141ffdee1e 100644
--- a/jarvis/brain/resolver.py
+++ b/jarvis/brain/resolver.py
@@ -571,48 +571,6 @@ def resolve_subscription_brain(
# Internal — Chain-Building
# ----------------------------------------------------------------------
-class SubscriptionFirstBrain:
- """Background brain: a connected subscription first, the keyed brain otherwise.
-
- For background callers built at boot (awareness summaries). The login probe
- spawns CLIs, so it runs lazily on the first call, off the event loop, and
- is re-checked after :attr:`RECHECK_S` so a later sign-in or sign-out is
- honoured. A key is spent only while no subscription is connected, which
- keeps a single-key install working (AP-22) without billing the voice key
- for work nobody waits on (live 2026-09-29).
- """
-
- RECHECK_S = 600.0
-
- def __init__(
- self, config: JarvisConfig, fallback: Brain, *, cli_timeout_s: float | None = None
- ) -> None:
- self._config = config
- self._fallback = fallback
- self._cli_timeout_s = cli_timeout_s
- self._chosen: Any = None
- self._checked_at = float("-inf")
- self.name = getattr(fallback, "name", "")
-
- async def _pick(self) -> Any:
- import asyncio
- import time
-
- now = time.monotonic()
- if self._chosen is None or now - self._checked_at >= self.RECHECK_S:
- subscription = await asyncio.to_thread(
- resolve_subscription_brain, self._config, cli_timeout_s=self._cli_timeout_s
- )
- self._chosen = subscription if subscription is not None else self._fallback
- self._checked_at = now
- return self._chosen
-
- async def complete(self, req: Any) -> Any:
- brain = await self._pick()
- async for delta in brain.complete(req):
- yield delta
-
-
def _resolve_chain(config: JarvisConfig) -> list[tuple[str, str | None]]:
"""Builds the ordered (provider, model) list for the fallback chain.
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
index 6047b88aba..7483ec420d 100644
--- a/jarvis/brain/turn_planner.py
+++ b/jarvis/brain/turn_planner.py
@@ -992,7 +992,7 @@ def plan_turn(
# Recall of the user's own past is STRONG evidence, deliberately outside
# the suppressors: "wann war ich zuletzt beim Zahnarzt?" reads as
# first-person smalltalk to every weak heuristic, yet only the
- # orchestrator (Wiki memory / awareness episodes) can answer
+ # orchestrator (Wiki memory) can answer
# it. # i18n-allow: quoted German recall utterance
if _RECALL_RE is not None and _RECALL_RE.search(normalized):
reasons.add(TurnReason.PRIVATE_DATA)
diff --git a/jarvis/core/capabilities_seed.py b/jarvis/core/capabilities_seed.py
index cf8e35e89b..1dc6df0558 100644
--- a/jarvis/core/capabilities_seed.py
+++ b/jarvis/core/capabilities_seed.py
@@ -64,11 +64,6 @@ _WIKI_OBJECTS: tuple[str, ...] = (
"fact", "fakt", # i18n-allow
)
-_AWARENESS_OBJECTS: tuple[str, ...] = (
- "awareness", "status", "zustand", "zustaende", "state", "context",
- "kontext", "erinnerung", "memory", "verlauf", "history", "episode", # i18n-allow
-)
-
# ---------------------------------------------------------------------------
# Seed table
@@ -144,24 +139,6 @@ _SEED_CAPABILITIES: list[Capability] = [
risk_tier="ask",
requires_evidence=True,
),
- Capability(
- id="tool.awareness-snapshot",
- source="router_tool",
- verbs=_READ_VERBS,
- objects=_AWARENESS_OBJECTS,
- description="Read a snapshot of the current awareness/context state (read-only).",
- risk_tier="safe",
- requires_evidence=False,
- ),
- Capability(
- id="tool.awareness-recall",
- source="router_tool",
- verbs=_READ_VERBS,
- objects=_AWARENESS_OBJECTS,
- description="Full-text search over the recent awareness episode log (read-only).",
- risk_tier="safe",
- requires_evidence=False,
- ),
Capability(
id="tool.run-skill",
source="router_tool",
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index e586df2618..84e3597e41 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -31,10 +31,6 @@ from typing import TYPE_CHECKING, Any, Literal, get_args, get_origin
import yaml
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
-# Sub-config from the awareness sub-package. A top-level import is fine because
-# jarvis.awareness.config only knows Pydantic and never calls back into core.* —
-# no circular-import risk.
-from jarvis.awareness.config import AwarenessConfig
from jarvis.live.config import LiveConfig
# wake_constants is pure stdlib (no jarvis imports) — safe to import from this
@@ -1492,17 +1488,14 @@ class EvidenceDomainsConfig(BaseModel):
"guthaben",
"billing",
],
- # Local screen / window-activity history. Served by the always-on
- # internal `awareness-recall` tool (wired into the domain→tool map in
- # BrainManager._run_evidence_gate, NOT a connected CLI), so a question
- # like "was hatte ich heute offen / was habe ich gemacht / which
- # windows were open" deterministically FORCES an awareness-recall call
- # instead of letting the (esp. fast-tier) model confabulate "der lokale
- # Verlaufsspeicher ist nicht verfügbar" without ever calling the tool
- # (live 2026-06-18, proven from the log: no tool execution line, yet the
- # refusal was spoken). Keywords are PHRASE-specific to opened
- # windows/apps/today's on-device activity — never a bare "offen"/"open"
- # token, so "ist die Frage noch offen" can't hijack the domain.
+ # Local screen / window-activity history. Jarvis keeps no such
+ # history (the awareness recorder was removed 2026-09-30), so no
+ # tool serves this domain: a question like "was hatte ich heute
+ # offen / which windows were open" gets the gate's honest "I have
+ # no access to your activity history" instead of a confabulated
+ # timeline. Keywords are PHRASE-specific to opened windows/apps/
+ # today's on-device activity — never a bare "offen"/"open" token,
+ # so "ist die Frage noch offen" can't hijack the domain.
"activity": [
"offen hatte",
"offen gehabt",
@@ -1638,20 +1631,18 @@ class BrainConfig(BaseModel):
class WikiCuratorConfig(BaseModel):
"""Curator LLM settings for the long-term wiki memory (Phase B1).
- The curator turns one new source (a BrainTurnCompleted summary, an
- EpisodeRecorded entry, a MissionCompleted hand-off) into a small set
+ The curator turns one new source (a BrainTurnCompleted summary or a
+ MissionCompleted hand-off) into a small set
of structured wiki page updates. The LLM is intentionally provider-
agnostic: ``provider=""`` falls back to ``brain.primary`` and
``model=""`` falls back to the resolved provider's ``model`` field
- under ``brain.providers``. Pattern mirrors
- ``AwarenessVerdichterConfig`` (Plan §6).
+ under ``brain.providers``.
"""
model_config = ConfigDict(extra="allow")
provider: str = "" # "" = fall back to brain.primary
model: str = "" # "" = provider default model
- max_input_tokens: int = 64_000
# Headroom for a complete proposal; the streaming truncation guard
# rejects any residual length-capped generation. The Stage-2 judge
# returns FULL page bodies per add/update, so a batched response
@@ -2841,7 +2832,7 @@ class PerformanceConfig(BaseModel):
# keep it whenever in doubt. Cuts the per-turn image tax on cheap turns.
conditional_vision: bool = True
# Wave 2 (omni-latency): cache-optimized prompt layout. Static prefix in the
- # system prompt, per-turn dynamic context (awareness/wiki/date) moved into the
+ # system prompt, per-turn dynamic context (wiki/date) moved into the
# user message so the provider prompt cache actually hits.
cache_optimized_prompt: bool = True
@@ -4415,9 +4406,6 @@ class JarvisConfig(BaseModel):
performance: PerformanceConfig = Field(default_factory=PerformanceConfig)
# Wave 0 (omni-latency) — hot-path latency span instrumentation toggle.
latency: LatencyConfig = Field(default_factory=LatencyConfig)
- # Phase A0+: awareness layer (continuous context). Entire subsystem
- # hot-disabled via [awareness].enabled = false (plan §15).
- awareness: AwarenessConfig = Field(default_factory=AwarenessConfig)
# Phase B5 — wiki write-wiring: SessionRollupWorker + WikiCurator bootstrap (Agent A).
wiki_integration: WikiIntegrationConfig = Field(default_factory=WikiIntegrationConfig)
# Phase B5 — CuratorScheduler (Agent D). Top-level field — Wave-2 cleanup task
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 65556c3b21..3c31bcabad 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -2080,93 +2080,20 @@ class BioFeedbackRecorded(Event):
# ----------------------------------------------------------------------
-# Awareness Layer (Phase A0+)
+# Idle boundary
# ----------------------------------------------------------------------
-@dataclass(frozen=True, slots=True)
-class FrameUpdated(Event):
- """A new L1 frame was captured and written to the AwarenessState.
-
- Emitted by the ``WindowFocusWatcher`` (Phase A1). The PrivacyFilter verdict
- is already applied — when ``is_capture_allowed=False`` the frame was still
- registered (window title + process), but deeper capture (pixels, UIA tree)
- is blocked in later phases.
- """
- window_title: str = ""
- process_name: str = ""
- pid: int = 0
- is_capture_allowed: bool = True
-
-
-@dataclass(frozen=True, slots=True)
-class EpisodeRecorded(Event):
- """An L2 episode was condensed and persisted to SQLite.
-
- Defined in A0 only; populated by the ``StoryTracker`` in A2.
- ``summary_preview`` is capped at ~80 characters for the UI pulse;
- the full ``summary`` text lives in ``awareness_episodes.summary``.
- """
- episode_id: int = 0
- summary_preview: str = ""
- primary_app: str = ""
- frame_count: int = 0
- duration_ms: int = 0
-
-
-@dataclass(frozen=True, slots=True)
-class ContextSwitched(Event):
- """Working-set change: a different project/task context was detected.
-
- Defined in A0 only; populated by ``WorkingSet`` in A4. Fields contain
- ``Context.task_label`` values (e.g. ``"pipeline.py - jarvis"``).
- """
- from_context: str = ""
- to_context: str = ""
-
-
@dataclass(frozen=True, slots=True)
class IdleEntered(Event):
- """The user has had no mouse/keyboard input for ``idle_threshold_minutes``.
+ """The user has had no mouse/keyboard input for a while.
- On receiving this event the ``StoryTracker`` (A2) flushes the running
- episode so it is not lost — idle == episode boundary.
+ The wiki's ``SessionRollupWorker`` flushes a session on it. No built-in
+ watcher publishes it since the awareness recorder was removed
+ (2026-09-30); the explicit flush paths still work without it.
"""
idle_since_ns: int = 0
-@dataclass(frozen=True, slots=True)
-class IdleExited(Event):
- """User input detected again after an idle phase."""
- was_idle_for_ms: int = 0
-
-
-@dataclass(frozen=True, slots=True)
-class AwarenessCaptureBlocked(Event):
- """The PrivacyFilter marked a frame as not capturable.
-
- ``reason`` is a pattern or default verdict (e.g.
- ``matched_blocked_title:*Banking*`` or ``default_block_for_browser``).
- The frame is NOT emitted as ``FrameUpdated`` — anyone who needs both events
- must use ``subscribe_all()`` (the flight-recorder pattern).
- """
- window_title: str = ""
- process_name: str = ""
- reason: str = ""
-
-
-@dataclass(frozen=True, slots=True)
-class FileSaved(Event):
- """Phase A5: the FileSystemWatcher detected a file save in an active project root.
-
- Emitted by the ``FileSystemProbe`` (watchdog). The ``StoryTracker`` subscribes
- optionally and adds it as a high-salience event to the running builder
- (``SalienceScorer.score_event('FileSaved') = 40``).
- """
- path: str = ""
- process_name: str = "" # active process at the time, optional
- repo_root: str = "" # project root that was watched
-
-
# ----------------------------------------------------------------------
# Wiki Live-Reload (Phase B3 — Desktop Wiki View, Agent D)
# ----------------------------------------------------------------------
diff --git a/jarvis/core/self_mod/schema_introspect.py b/jarvis/core/self_mod/schema_introspect.py
index 0e39bbec69..1bcbd20e41 100644
--- a/jarvis/core/self_mod/schema_introspect.py
+++ b/jarvis/core/self_mod/schema_introspect.py
@@ -158,8 +158,7 @@ def resolve_model_for_path(path: str) -> type[BaseModel]:
"""Navigate ``JarvisConfig`` along ``path`` to the model owning the leaf.
More robust than ``getattr(jarvis.core.config, name)``: it follows the real
- schema, so a section model defined in a submodule (e.g.
- ``AwarenessPrivacyConfig``) and never re-exported into ``config`` still
+ schema, so a section model defined in a submodule and never re-exported into ``config`` still
resolves. This is the canonical anti-drift check for an introspected spec.
"""
from jarvis.core.config import JarvisConfig
diff --git a/jarvis/costs/ledger.py b/jarvis/costs/ledger.py
index 0b3b580df9..74930a0f52 100644
--- a/jarvis/costs/ledger.py
+++ b/jarvis/costs/ledger.py
@@ -3,8 +3,8 @@
The Costs section used to learn about spend from the surfaces that happened
to record it — a voice turn's ``BrainTurnCompleted``, a chat's
``turn_finished``, a mission's draft. Twenty-odd callers of the brain
-protocol never told anyone: dictation polish, the wiki curator, awareness
-digests, the mission critic, computer-use planning, skill authoring, board
+protocol never told anyone: dictation polish, the wiki curator, the mission
+critic, computer-use planning, skill authoring, board
profiles. Their OpenRouter and Gemini bills were real and invisible
(maintainer, 2026-08-25: "I have spent money on OpenRouter, I know it").
diff --git a/jarvis/costs/model.py b/jarvis/costs/model.py
index b2426a66ea..b16fd79744 100644
--- a/jarvis/costs/model.py
+++ b/jarvis/costs/model.py
@@ -42,7 +42,7 @@ SURFACE_JARVIS_VOICE = "jarvis-voice"
#: Coding agents driven by a vendor CLI, indexed from their session logs.
SURFACE_AGENTIC_IDE = "agentic-ide"
#: Every model call no surface above claims: dictation polish, the wiki
-#: curator, awareness digests, the mission critic, computer-use planning,
+#: curator, the mission critic, computer-use planning,
#: skill authoring … — read from the usage ledger (:mod:`jarvis.costs.ledger`).
SURFACE_BACKGROUND = "background"
diff --git a/jarvis/missions/kontrollierer/worker_prompt.py b/jarvis/missions/kontrollierer/worker_prompt.py
index e49054f9c1..e1f94500bf 100644
--- a/jarvis/missions/kontrollierer/worker_prompt.py
+++ b/jarvis/missions/kontrollierer/worker_prompt.py
@@ -81,8 +81,7 @@ SUPERVISOR_BOUNDARY_DIRECTIVE: Final[str] = (
"credentials; and never change live configuration. For knowledge and "
"research work, use only the supervisor-granted Jarvis tools that appear "
"in your tool list: the wiki tools (wiki-list, wiki-recall, "
- "wiki-page-read, wiki-ingest), the semantic knowledge base "
- "session memory (awareness-recall), web search "
+ "wiki-page-read, wiki-ingest), web search "
"(search_web), and contact lookup (contact-lookup). A tool absent from "
"your tool list is not available for this mission - do not call it. A "
"denied or failed supervisor tool call is a normal, recoverable event: "
diff --git a/jarvis/missions/workers/capabilities.py b/jarvis/missions/workers/capabilities.py
index 0a5c792b1a..93fdad93dc 100644
--- a/jarvis/missions/workers/capabilities.py
+++ b/jarvis/missions/workers/capabilities.py
@@ -206,35 +206,17 @@ _UNCONDITIONAL_EXTRA_KNOWLEDGE_TOOLS: tuple[str, ...] = (
)
-def _awareness_recall_available() -> bool:
- """Session memory follows the awareness master switch — fail closed.
-
- Granting ``awareness-recall`` while ``[awareness].enabled = false`` would
- hand the worker a phantom tool whose every call errors (the honesty
- failure ``search_status`` was written to avoid).
- """
- try:
- from jarvis.core.config import load_config # noqa: PLC0415 — lazy, boot-safe
-
- return bool(load_config().awareness.enabled)
- except Exception: # noqa: BLE001 - config drift must not break missions
- return False
-
-
def restricted_worker_knowledge_tools() -> tuple[str, ...]:
"""Read-only knowledge surface granted to Jarvis-Agents (ADR-0030).
- Dynamic, gate-driven: the wiki triple is unconditional; session memory
- (``awareness-recall``) follows the awareness master switch; ``search_web``
- and ``contact-lookup`` mirror the voice brain's read-only reach.
+ The wiki triple plus ``search_web`` and ``contact-lookup``, mirroring the
+ voice brain's read-only reach.
Execution always stays in the supervisor via the ADR-0025 broker — a
worker never holds
the tool object — and every gate fails closed so a disabled subsystem
never yields a phantom tool.
"""
tools: list[str] = list(RESTRICTED_WORKER_KNOWLEDGE_TOOLS)
- if _awareness_recall_available():
- tools.append("awareness-recall")
tools.extend(_UNCONDITIONAL_EXTRA_KNOWLEDGE_TOOLS)
return tuple(tools)
diff --git a/jarvis/plugins/tool/awareness_recall.py b/jarvis/plugins/tool/awareness_recall.py
deleted file mode 100644
index 4d3d55fc3c..0000000000
--- a/jarvis/plugins/tool/awareness_recall.py
+++ /dev/null
@@ -1,230 +0,0 @@
-"""``awareness-recall`` tool — BM25 full-text search across recent episodes.
-
-Plan §7 (Awareness Phase A3, L3 Session Search). Originally specified as a
-``SUB_TOOL`` for "Sub-Jarvis"; after Welle 4 deleted the sub tier entirely
-this tool lives in ``ROUTER_TOOLS``. The router brain calls it directly
-when the user asks about earlier work ("vorhin", "heute morgen", "an
-welcher Datei war ich"), and may bake the result into an
-``spawn_worker`` ``context_hints`` field if it then decides to delegate
-heavy work to a Jarvis-Agent worker.
-
-The tool is read-only (``risk_tier="safe"``): a single FTS5 ``MATCH``
-query against the ``awareness_episodes_fts`` virtual table, no brain
-call, no network, no mutation. Output is a compact markdown block that
-the router brain can consume directly inside its system prompt — same
-contract as ``awareness-snapshot`` so the brain does not need to learn a
-new shape.
-"""
-from __future__ import annotations
-
-import logging
-import time
-from dataclasses import dataclass
-from typing import Any
-
-log = logging.getLogger(__name__)
-
-# We import RecallStore only for type hints to keep the plugin importable
-# in environments where the recall store happens to be unavailable
-# (configured off, schema migration in progress, etc.). The actual
-# instance is injected via the constructor.
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from jarvis.memory.recall import RecallStore
-
-
-@dataclass
-class ToolResult:
- """Mirror of ``awareness_snapshot.ToolResult`` for a uniform shape.
-
- If the canonical Tool-Result protocol in ``jarvis.core.protocols`` is
- extended later, this dataclass must stay structurally compatible.
- """
-
- success: bool
- output: str
- error: str | None = None
-
-
-_MINUTES_IN_NS: int = 60 * 1_000_000_000
-
-
-def _format_episode(row: dict[str, Any]) -> str:
- """Render a single episode row as a one-line markdown snippet.
-
- Format: ``- [HH:MM, primary_app] summary-first-120-chars…``
-
- ``started_at_ns`` is interpreted as a nanosecond Unix timestamp; the
- local-time HH:MM is shown so a router brain can humanise it without
- re-parsing the value. The summary is truncated to 120 characters and
- suffixed with an ellipsis when it had to be cut — the goal is to fit
- several snippets into a system-prompt without blowing the budget.
- """
- started_ns = int(row.get("started_at_ns", 0))
- started_s = started_ns / 1_000_000_000 if started_ns > 0 else 0
- hhmm = time.strftime("%H:%M", time.localtime(started_s)) if started_s else "??:??"
- app = row.get("primary_app", "unknown") or "unknown"
- summary = (row.get("summary") or "").strip()
- if len(summary) > 120:
- summary = summary[:120].rstrip() + "…"
- return f"- [{hhmm}, {app}] {summary}"
-
-
-class AwarenessRecallTool:
- """Router-tier full-text search over the last N hours of episodes."""
-
- name: str = "awareness-recall"
- description: str = (
- "Searches the awareness episode log for the last N hours by full-text. "
- "Call this when the user asks about earlier work — phrases like "
- "'vorhin', 'heute morgen', 'der Befehl von eben', 'an welcher Datei "
- "war ich'. Returns up to 5 ranked snippets with timestamp and the "
- "primary app of each episode. Read-only, no brain call."
- )
- risk_tier: str = "safe"
- schema: dict[str, Any] = {
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "One to four FTS5 keywords. Avoid full sentences.",
- },
- "k": {
- "type": "integer",
- "default": 5,
- "minimum": 1,
- "maximum": 10,
- "description": "Maximum number of ranked snippets to return.",
- },
- "since_minutes": {
- "type": "integer",
- "default": 1440,
- "minimum": 1,
- "maximum": 10080,
- "description": (
- "Search horizon in minutes. Default 1440 (24h), maximum "
- "10080 (7 days). Older episodes are filtered out."
- ),
- },
- },
- "required": ["query"],
- }
-
- def __init__(self, recall_store: RecallStore | None) -> None:
- self._recall = recall_store
-
- async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
- """Execute the search. Args are validated at call time, not in schema.
-
- Defensive behaviour:
- - ``recall_store`` is None → ``success=False`` with a clear error,
- no exception. This happens when awareness is configured off or
- the bootstrap is still in flight; the router brain should treat
- it as "tool unavailable" rather than a hard failure.
- - empty query → ``success=True`` with a placeholder line so the
- brain still sees structured output, not a crash.
- - keyword miss but episodes exist in the window → ``success=True``
- with the most recent activity timeline (recency fallback), so a
- recency question ("what did I have open today") is answered from
- real data instead of a bare "nothing found" that a brain can
- mis-narrate as the store being down (2026-06-18 confabulation).
- - genuinely empty window → ``success=True`` with a sentence that
- explicitly affirms the store is reachable, so the honest "empty"
- cannot be escalated into a false "unavailable"/"error" claim.
- """
- if self._recall is None:
- return ToolResult(
- success=False,
- output="",
- error="awareness recall store unavailable",
- )
-
- query = str(args.get("query", "")).strip()
- k = int(args.get("k", 5))
- since_minutes = int(args.get("since_minutes", 1440))
-
- # Clamp to schema bounds defensively — JSON-schema validation may
- # not have run upstream when called from a test harness.
- k = max(1, min(k, 10))
- since_minutes = max(1, min(since_minutes, 10080))
-
- since_ns = time.time_ns() - since_minutes * _MINUTES_IN_NS
-
- hours = since_minutes / 60
-
- # Query the store. A genuine DB failure must surface HONESTLY (so the
- # brain can say "search is down") and be logged — it must never be
- # invisible. Previously this path had no logging at all, so when the
- # live deep/fast brain claimed "der lokale Verlaufsspeicher ist nicht
- # verfügbar" there was no way to tell whether the store had actually
- # failed or the brain had confabulated an outage over a healthy result
- # (2026-06-18). The log line below records the real branch + output so
- # that question is answerable from the log alone.
- try:
- rows = await self._recall.search_episodes(
- query=query,
- limit=k,
- since_ns=since_ns,
- )
- recent = rows or await self._recall.recent_episodes(
- limit=k, since_ns=since_ns,
- )
- except Exception as exc: # noqa: BLE001 — surface, never confabulate
- log.warning(
- "awareness-recall query failed for %r (since=%dmin): %s",
- query, since_minutes, exc, exc_info=True,
- )
- return ToolResult(
- success=False,
- output="",
- error=f"awareness recall query failed: {exc}",
- )
-
- if rows:
- lines = [_format_episode(r) for r in rows]
- out = (
- f"Found {len(rows)} episode(s) matching '{query}' in the last "
- f"{hours:.1f}h:\n" + "\n".join(lines)
- )
- log.info("awareness-recall %r: keyword hit, %d row(s)", query, len(rows))
- return ToolResult(success=True, output=out)
-
- # No keyword match. A question like "what did I have open today?" is a
- # *recency* query, not a keyword query, and episode summaries are often
- # sparse (empty when the Verdichter could not characterise a window).
- # Hand the brain the user's actual recent activity timeline — it
- # directly answers a recency question. Lead with the DATA, positively:
- # an earlier version led with "No episode summary matched '<query>' …"
- # and the live deep/fast brain latched onto that negative opener and
- # reported the (healthy, fully-populated) store as "nicht verfügbar"
- # (2026-06-18). The keyword caveat is now a trailing parenthetical so a
- # skimming model reads "recent activity from the store" first, never a
- # leading negation.
- if recent:
- lines = [_format_episode(r) for r in recent]
- out = (
- f"Recent activity from the awareness store (last {hours:.1f}h, "
- f"newest first) — this IS your window/app history:\n"
- + "\n".join(lines)
- + f"\n(No episode summary text contained '{query}'; the list "
- f"above is the recency timeline.)"
- )
- log.info(
- "awareness-recall %r: recency fallback, %d row(s)",
- query, len(recent),
- )
- return ToolResult(success=True, output=out)
-
- # Genuinely nothing logged in the window. State explicitly that the
- # store *is* reachable and was searched, so this honest "empty" cannot
- # be escalated into a false "unavailable"/"error" claim downstream.
- log.info("awareness-recall %r: empty window (store reachable)", query)
- return ToolResult(
- success=True,
- output=(
- f"The awareness store was searched successfully and is "
- f"reachable, but it has no activity recorded in the last "
- f"{hours:.1f}h."
- ),
- )
diff --git a/jarvis/plugins/tool/awareness_snapshot.py b/jarvis/plugins/tool/awareness_snapshot.py
deleted file mode 100644
index 4bd56fc1db..0000000000
--- a/jarvis/plugins/tool/awareness_snapshot.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""``awareness-snapshot`` tool — synchronous state read for the router.
-
-Binding per Plan §5: this tool is router-tier-only (NOT in SUB_TOOLS). It
-makes NO brain call and NO IO — just a synchronous read on
-``AwarenessState.snapshot_for_prompt()``.
-
-When the main Jarvis uses it: for utterances like "what am I doing right
-now?" or "which file am I in?" — the answer is already in the awareness
-state and doesn't need an LLM roundtrip or a Jarvis-Agent spawn.
-"""
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Any
-
-from jarvis.awareness.manager import AwarenessManager
-
-
-@dataclass
-class ToolResult:
- """Minimal wrapper for tool output. The full contract lives in
- jarvis.core.protocols; here just what we actually send back.
-
- If the real tool-result protocol is extended, this class must stay
- structurally compatible (or be replaced directly by the protocol).
- """
- success: bool
- output: str
- error: str | None = None
-
-
-class AwarenessSnapshotTool:
- """Synchronous state read on ``manager.state.snapshot_for_prompt()``."""
-
- name: str = "awareness-snapshot"
- description: str = (
- "Returns the current awareness state (active window, idle status, "
- "last episode summary if any). USE this BEFORE asking the user for "
- "context — the answer is often already in here."
- )
- risk_tier: str = "safe"
- schema: dict[str, Any] = {
- "type": "object",
- "properties": {},
- "required": [],
- }
-
- def __init__(self, manager: AwarenessManager) -> None:
- self._manager = manager
-
- async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
- """Synchronous state read — NO brain call, NO IO.
-
- ``args`` and ``ctx`` are ignored (schema has no required fields).
- """
- snap = self._manager.state.snapshot_for_prompt()
- return ToolResult(success=True, output=snap)
diff --git a/jarvis/skills/schema.py b/jarvis/skills/schema.py
index 33d2e47f25..230369d901 100644
--- a/jarvis/skills/schema.py
+++ b/jarvis/skills/schema.py
@@ -347,9 +347,8 @@ class SkillDirectTriggered(Event):
Complementary to SkillStarted: SkillDirectTriggered marks the
*activation decision* (brain bypassed), SkillStarted marks the
- actual run start in the SkillRunner. Forward-compatible with the
- awareness layer (A0-A5) via ``trigger_type`` as the activation-path
- discriminator.
+ actual run start in the SkillRunner. ``trigger_type`` is the
+ activation-path discriminator.
"""
skill_name: str = ""
trigger_type: str = "" # "voice_direct" | "hotkey" | "cron"
diff --git a/jarvis/society/capabilities.py b/jarvis/society/capabilities.py
index 12073ff9b2..e6c0070af2 100644
--- a/jarvis/society/capabilities.py
+++ b/jarvis/society/capabilities.py
@@ -97,8 +97,6 @@ _CORE_TOOLS: Final[frozenset[str]] = frozenset(
"wiki-ingest",
"wiki-list",
"wiki-page-read",
- "awareness-recall",
- "awareness-snapshot",
"run-skill",
"inspect-pointer",
"open-app",
diff --git a/jarvis/speech/warmup_prefetch.py b/jarvis/speech/warmup_prefetch.py
index 018a044e25..f351d29a7d 100644
--- a/jarvis/speech/warmup_prefetch.py
+++ b/jarvis/speech/warmup_prefetch.py
@@ -10,8 +10,8 @@ Profiling on a real desktop showed the dominant cost is the
~2.9 s, NOT the model parse (~0.1 s).
Worse, since the serve-first fast-boot bootstrap (the server now answers in
-~200 ms and every subsystem — brain build, wiki FTS index, conductor, workflows,
-awareness — boots concurrently as ``create_task``), that import no longer runs
+~200 ms and every subsystem — brain build, wiki FTS index, conductor, workflows —
+boots concurrently as ``create_task``), that import no longer runs
alone: it serializes on the global Python import lock against all those other
heavy imports and starves to 7-24 s (measured ``wake-start=14187``). That is the
"VOICE STARTING… forever" the user sees.
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 00bb2c235b..781a078c93 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -2083,18 +2083,6 @@ class DesktopApp:
getattr(built, "active_provider", "unknown"),
)
_wire_ready_brain(built)
-
- awareness_manager = getattr(built, "_awareness_manager", None)
- if awareness_manager is not None:
- from loguru import logger as _aw_logger
-
- try:
- await awareness_manager.start()
- _aw_logger.info(
- "AwarenessManager started — StoryTracker is now listening on bus."
- )
- except Exception as exc: # noqa: BLE001
- _aw_logger.opt(exception=exc).warning("AwarenessManager.start() failed.")
except Exception as exc: # noqa: BLE001
from loguru import logger
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index c79fe42ee4..d33d01eb09 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -269,7 +269,7 @@ _DEFAULT_ADMIN_PORT = 47821
def _fast_admin_port() -> int:
"""Read ``[ui].admin_api_port`` from jarvis.toml with a raw tomllib read (a
few ms) so the fast-boot bootstrap can bind the REAL port without paying the
- ~240 ms full ``load_config`` (which drags pydantic + the brain/awareness
+ ~240 ms full ``load_config`` (which drags pydantic + the brain
imports) on the time-to-serving path. Falls back to the packaged default.
The configured value is the *base*: a non-default instance (``--instance
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index ad1bb4f3f7..f52c137e1c 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -817,7 +817,7 @@ class WebServer:
evaluator = AchievementEvaluator(db_path=db_path, bus=self.bus)
bio_store = BioStore(db_path=db_path)
- # Optional data-source paths (awareness, missions, self-mod).
+ # Optional data-source paths (missions, self-mod).
# If the file/DB doesn't exist, the block just silently drops out
# of the prompt — no error. Paths come from ``user_data_dir()``,
# not relative strings, so an app restart in a different CWD
diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.py
index c9756e3c8e..adf0448291 100644
--- a/jarvis/ui/web/telephony_routes.py
+++ b/jarvis/ui/web/telephony_routes.py
@@ -986,8 +986,7 @@ def _build_session(
# creates-and-drops a coroutine without ever running it. Fire-and-forget via
# asyncio.create_task instead, keeping a strong reference here so the event
# loop can't garbage-collect the task mid-flight (each self-discards on
-# completion) — the same pattern used for FileSaved publishes in
-# jarvis/awareness/probes/filesystem.py.
+# completion).
_PENDING_PUBLISH_TASKS: set[asyncio.Task[Any]] = set()
diff --git a/pyproject.toml b/pyproject.toml
index caffd76776..aefe828125 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -757,10 +757,6 @@ app-command = "jarvis.plugins.tool.app_command:AppCommandTool"
# under the person's per-action policy. See ADR-0011 amendment "Every app action".
find-app-action = "jarvis.plugins.tool.app_action:FindAppActionTool"
run-app-action = "jarvis.plugins.tool.app_action:RunAppActionTool"
-# Phase A1 — Awareness layer L1 (synchronous state read for the router).
-awareness-snapshot = "jarvis.plugins.tool.awareness_snapshot:AwarenessSnapshotTool"
-# Phase A3 — Awareness-Layer L3 (BM25 search across recent episodes).
-awareness-recall = "jarvis.plugins.tool.awareness_recall:AwarenessRecallTool"
# Agent society voice tools (2026-09-02): ONE typed ASSIGN to a named agent
# with an immediate spoken ack, and a read-only status answer. Router-tier
# only (ADR-0011 amendment); never in a worker set (AP-5/AP-14).
@@ -903,9 +899,6 @@ select = ["E", "F", "I", "UP", "B", "ASYNC", "S", "A"]
ignore = ["S101", "S603", "S607"]
[tool.ruff.lint.per-file-ignores]
-# The Verdichter system prompt intentionally contains long few-shot examples
-# (Tournament 2026-04-26 pick) — string content, must NOT be reformatted.
-"jarvis/awareness/prompts.py" = ["E501"]
# Telephony tests parse our OWN generated TwiML (trusted input, not untrusted
# network data) and use the literal word "secret" / fake fixture tokens that
# bandit flags as hardcoded passwords. Both are false positives in a test
diff --git a/scripts/awareness_smoke_a1.py b/scripts/awareness_smoke_a1.py
deleted file mode 100644
index 08586e7b63..0000000000
--- a/scripts/awareness_smoke_a1.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""Live smoke test for Phase A1 — Awareness L1 live frame.
-
-Initializes ``AwarenessManager`` + watchers (WindowFocusWatcher +
-IdleDetector), runs for N seconds (default 30s), logs every
-``FrameUpdated`` and ``IdleEntered/Exited`` event to stdout.
-
-Cleaner shutdown via Ctrl+C: ``signal.signal(SIGINT, ...)`` sets an
-asyncio.Event that wakes the main coroutine; afterwards
-``await manager.stop()`` with a 2s timeout (see Plan §5 hard negative).
-
-Manual: switch the foreground window 5x (Alt+Tab or click on
-another app); the window titles/processes appear in the output.
-
-Usage:
- python scripts/awareness_smoke_a1.py [--seconds 30]
-"""
-from __future__ import annotations
-
-import argparse
-import asyncio
-import logging
-import signal
-import subprocess
-import sys
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.core.bus import EventBus
-from jarvis.core.events import (
- AwarenessCaptureBlocked,
- FrameUpdated,
- IdleEntered,
- IdleExited,
-)
-
-
-async def _auto_trigger_window_switches(log: logging.Logger, count: int = 5) -> None:
- """Opens/closes notepad.exe N times — reproducibly triggers
- EVENT_SYSTEM_FOREGROUND. Used for a CI-suitable self-test without
- user interaction.
- """
- for i in range(count):
- await asyncio.sleep(1.0)
- log.info("AUTO-TRIGGER #%d spawning notepad.exe", i + 1)
- try:
- proc = subprocess.Popen(["notepad.exe"]) # noqa: ASYNC220
- except OSError as exc:
- log.warning("AUTO-TRIGGER #%d failed to spawn: %s", i + 1, exc)
- continue
- await asyncio.sleep(1.5)
- try:
- proc.terminate()
- proc.wait(timeout=2.0)
- except subprocess.TimeoutExpired:
- proc.kill()
- except OSError:
- pass
-
-
-async def run_smoke(seconds: int, auto_trigger: bool, debug: bool) -> int:
- logging.basicConfig(
- level=logging.DEBUG if debug else logging.INFO,
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
- stream=sys.stdout,
- )
- log = logging.getLogger("smoke-a1")
- if debug:
- logging.getLogger("jarvis.awareness").setLevel(logging.DEBUG)
-
- bus = EventBus()
- config = AwarenessConfig.default()
- manager = AwarenessManager(config, bus=bus)
-
- counter = {"frame": 0, "idle_in": 0, "idle_out": 0, "blocked": 0}
-
- async def on_frame(ev: FrameUpdated) -> None:
- counter["frame"] += 1
- log.info(
- "FRAME #%d title=%r process=%r pid=%d capture_allowed=%s",
- counter["frame"], ev.window_title, ev.process_name,
- ev.pid, ev.is_capture_allowed,
- )
-
- async def on_idle_in(ev: IdleEntered) -> None:
- counter["idle_in"] += 1
- log.info("IDLE-IN idle_since_ns=%d", ev.idle_since_ns)
-
- async def on_idle_out(ev: IdleExited) -> None:
- counter["idle_out"] += 1
- log.info("IDLE-OUT was_idle_for_ms=%d", ev.was_idle_for_ms)
-
- async def on_blocked(ev: AwarenessCaptureBlocked) -> None:
- counter["blocked"] += 1
- log.info(
- "BLOCKED title=%r process=%r reason=%s",
- ev.window_title, ev.process_name, ev.reason,
- )
-
- bus.subscribe(FrameUpdated, on_frame)
- bus.subscribe(IdleEntered, on_idle_in)
- bus.subscribe(IdleExited, on_idle_out)
- bus.subscribe(AwarenessCaptureBlocked, on_blocked)
-
- log.info(
- "Starte AwarenessManager — enable_window=%s enable_idle=%s "
- "idle_threshold=%dmin",
- config.watchers.enable_window, config.watchers.enable_idle,
- config.watchers.idle_threshold_minutes,
- )
- await manager.start()
- log.info(
- "OK — watchers active (count=%d). %ds run time. "
- "Please switch the foreground window 5x (Alt+Tab or click). "
- "Ctrl+C stops immediately.",
- len(manager._watchers), seconds,
- )
-
- trigger_task: asyncio.Task[None] | None = None
- if auto_trigger:
- log.info("AUTO-TRIGGER aktiv — starte notepad-spawn-loop")
- trigger_task = asyncio.create_task(
- _auto_trigger_window_switches(log, count=5),
- name="auto-trigger",
- )
-
- stop_event = asyncio.Event()
- loop = asyncio.get_running_loop()
-
- def _on_signal(_signum: int, _frame: object) -> None:
- log.info("Stop-Signal empfangen — fahre runter")
- loop.call_soon_threadsafe(stop_event.set)
-
- signal.signal(signal.SIGINT, _on_signal)
- if hasattr(signal, "SIGBREAK"):
- signal.signal(signal.SIGBREAK, _on_signal)
-
- try:
- await asyncio.wait_for(stop_event.wait(), timeout=float(seconds))
- log.info("Shutdown via Signal")
- except TimeoutError:
- log.info("Zeit abgelaufen (%ds) — stoppe Watchers", seconds)
-
- if trigger_task is not None and not trigger_task.done():
- trigger_task.cancel()
- try:
- await trigger_task
- except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
- # Smoke cleanup — no logging needed, the script is ending anyway.
- pass
-
- # Collect watcher stats BEFORE stop() — the list is empty afterwards.
- watcher_stats = [
- (type(w).__name__, getattr(w, "_drops", None), getattr(w, "_last_hwnd", None))
- for w in (getattr(manager, "_watchers", []) or [])
- ]
- await manager.stop()
- for name, drops, last_hwnd in watcher_stats:
- log.info("WATCHER-STAT %s drops=%s last_hwnd=%s", name, drops, last_hwnd)
-
- log.info(
- "DONE — Frames=%d Idle-In=%d Idle-Out=%d Blocked=%d",
- counter["frame"], counter["idle_in"],
- counter["idle_out"], counter["blocked"],
- )
- return 0
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description="Awareness A1 live smoke")
- parser.add_argument(
- "--seconds", type=int, default=30,
- help="Lauf-Dauer in Sekunden (Default 30)",
- )
- parser.add_argument(
- "--auto-trigger", action="store_true",
- help="Auto-Spawn 5x notepad.exe — triggert Hooks ohne User-Action",
- )
- parser.add_argument(
- "--debug", action="store_true",
- help="DEBUG-level logging for jarvis.awareness.*",
- )
- args = parser.parse_args()
-
- if sys.platform != "win32":
- print(
- "[SKIP] awareness_smoke_a1.py ist Win32-only "
- "(SetWinEventHook fehlt auf diesem OS)",
- file=sys.stderr,
- )
- return 0
-
- return asyncio.run(run_smoke(args.seconds, args.auto_trigger, args.debug))
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/scripts/awareness_smoke_a2.py b/scripts/awareness_smoke_a2.py
deleted file mode 100644
index 9eaea503a1..0000000000
--- a/scripts/awareness_smoke_a2.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""Live smoke test for Phase A2 — L2 Story Tracker (bus replay).
-
-The Plan §6 smoke test is really "work manually for 30min" — unrealistic
-for a smoke test. Instead, this script replays a realistic
-bus sequence (FrameUpdated + IdleEntered) against a fully wired
-StoryTracker with a real Verdichter (Haiku brain call, if an API key is present)
-or a FakeVerdichter (no key found).
-
-What the script verifies:
-- StoryTracker accumulates salient frames in the builder
-- app switch + min-duration triggers a Verdichter call
-- episode lands in tmp SQLite + the FTS index is populated
-- state.last_episode_summary is set
-- EpisodeRecorded event is published
-
-Usage::
-
- python scripts/awareness_smoke_a2.py
- python scripts/awareness_smoke_a2.py --use-real-haiku # brain call instead of fake
-"""
-from __future__ import annotations
-
-import argparse
-import asyncio
-import logging
-import os
-import sys
-import tempfile
-import time
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-from jarvis.awareness.config import AwarenessConfig, AwarenessStoryConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.awareness.story import StoryTracker
-from jarvis.core.bus import EventBus
-from jarvis.core.events import EpisodeRecorded, FrameUpdated, IdleEntered
-from jarvis.memory.recall import RecallStore
-
-
-@dataclass
-class FakeVerdichter:
- summary: str = ( # i18n-allow: simulated Verdichter output — the real Verdichter's summary is German by design (VERDICHTER_SYSTEM_PROMPT)
- "Der Nutzer war 8min in Code.exe mit pipeline.py aktiv, " # i18n-allow: simulated Verdichter output, German by design
- "wechselte kurz zu Chrome.exe (GitHub-PR-Tab) und kehrte zurueck. " # i18n-allow: simulated Verdichter output, German by design
- "Aktueller Fokus: pipeline.py."
- )
- calls: list[dict[str, Any]] = field(default_factory=list)
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- self.calls.append({
- "n_frames": len(frames),
- "n_events": len(events),
- "primary_app": primary_app,
- })
- return self.summary, {
- "tokens_in": 380, "tokens_out": 95,
- "duration_ms": 420, "error_reason": None,
- }
-
-
-def _make_frame(
- *, title: str, process: str, ts_ns: int, capture_allowed: bool = True,
-) -> FrameSnapshot:
- return FrameSnapshot(
- timestamp_ns=ts_ns,
- active_window_title=title,
- active_process_name=process,
- active_pid=1000,
- is_capture_allowed=capture_allowed,
- )
-
-
-async def run_smoke(use_real_haiku: bool) -> int:
- logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
- stream=sys.stdout,
- )
- log = logging.getLogger("smoke-a2")
-
- # Tmp DB
- tmpdir = Path(tempfile.mkdtemp(prefix="jarvis-a2-smoke-"))
- db_path = tmpdir / "jarvis.db"
- log.info("Tmp DB: %s", db_path)
-
- bus = EventBus()
- recall = RecallStore(db_path)
- await recall.open()
-
- manager = AwarenessManager(AwarenessConfig.default())
-
- # Verdichter: Real-Haiku oder Fake
- if use_real_haiku:
- try:
- from jarvis.awareness.verdichter import Verdichter
- from jarvis.brain.provider_registry import BrainProviderRegistry
-
- v_cfg = manager.config.verdichter
- log.info(
- "Real-Haiku-Modus: provider=%s model=%s",
- v_cfg.provider, v_cfg.model,
- )
- registry = BrainProviderRegistry()
- brain = registry.instantiate(v_cfg.provider, model=v_cfg.model)
- verdichter: Any = Verdichter(brain=brain, config=v_cfg)
- except Exception as exc: # noqa: BLE001
- log.warning("Real-Haiku-Init failed (%s) — fallback to FakeVerdichter", exc)
- verdichter = FakeVerdichter()
- else:
- verdichter = FakeVerdichter()
- log.info("FakeVerdichter aktiv (deterministische Summary)")
-
- cfg = AwarenessStoryConfig(episode_min_duration_s=1)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall,
- verdichter=verdichter, config=cfg,
- )
-
- # Bus subscriber for stats
- received: list[EpisodeRecorded] = []
-
- async def collect(ev: EpisodeRecorded) -> None:
- received.append(ev)
- bus.subscribe(EpisodeRecorded, collect)
-
- await tracker.start()
-
- log.info("=== Replay: 6 frames over ~2.5s, then IdleEntered ===")
- base_ts = time.time_ns() - 2_500_000_000
-
- sequence: list[tuple[str, str, bool]] = [
- ("pipeline.py - Visual Studio Code", "Code.exe", True),
- ("manager.py - Visual Studio Code", "Code.exe", True),
- ("Banking - Sparkasse - Chrome", "chrome.exe", False), # blocked
- ("pipeline.py - Visual Studio Code", "Code.exe", True),
- ("factory.py - Visual Studio Code", "Code.exe", True),
- ("pipeline.py - Visual Studio Code", "Code.exe", True),
- ]
-
- for i, (title, process, allowed) in enumerate(sequence):
- f = _make_frame(
- title=title, process=process,
- ts_ns=base_ts + i * 400_000_000,
- capture_allowed=allowed,
- )
- manager.state.current_frame = f
- ev = FrameUpdated(
- window_title=title, process_name=process,
- pid=1000, is_capture_allowed=allowed,
- )
- log.info(
- "FRAME #%d process=%s title=%r allowed=%s",
- i + 1, process, title, allowed,
- )
- await tracker._on_frame_updated(ev)
- await asyncio.sleep(0.05)
-
- # Idle = Episode-Boundary
- log.info("=== IdleEntered → flush ===")
- await asyncio.sleep(1.2) # > min_duration
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- await asyncio.sleep(0.1) # bus dispatch settle
-
- # Verifikationen
- log.info("=== Verifikationen ===")
- log.info("Verdichter calls: %d", len(verdichter.calls))
- if verdichter.calls:
- c = verdichter.calls[0]
- log.info(
- " → Frames=%d Events=%d primary_app=%s",
- c.get("n_frames", c.get("frames_n", 0)),
- c.get("n_events", c.get("events_n", 0)),
- c["primary_app"],
- )
-
- episodes = await recall.recent_episodes(limit=10)
- log.info("Persisted episodes: %d", len(episodes))
- for ep in episodes:
- preview = ep["summary"][:80] + ("..." if len(ep["summary"]) > 80 else "")
- log.info(
- " → id=%d trigger=%s primary_app=%s frames=%d tokens=%d/%d summary=%r",
- ep["id"], ep["trigger_kind"], ep["primary_app"],
- ep["frame_count"], ep["tokens_in"], ep["tokens_out"], preview,
- )
-
- fts_results = await recall.search_episodes(query="pipeline", limit=5)
- log.info("FTS-Search 'pipeline': %d hit(s)", len(fts_results))
-
- log.info("State after flush:")
- log.info(" → last_episode_summary: %r", manager.state.last_episode_summary)
- log.info(" → last_episode_id: %s", manager.state.last_episode_id)
-
- log.info("EpisodeRecorded events received: %d", len(received))
-
- snap = manager.state.snapshot_for_prompt(max_chars=600)
- log.info("snapshot_for_prompt() (%d chars):", len(snap))
- for line in snap.splitlines():
- log.info(" | %s", line)
-
- await tracker.stop()
- await recall.close()
- log.info("=== DONE ===")
- return 0
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description="Awareness A2 bus-replay smoke")
- parser.add_argument(
- "--use-real-haiku", action="store_true",
- help="Echter Brain-Call statt FakeVerdichter (braucht API-Key)",
- )
- args = parser.parse_args()
- if os.environ.get("PYTHONIOENCODING", "").lower() != "utf-8":
- os.environ["PYTHONIOENCODING"] = "utf-8"
- return asyncio.run(run_smoke(args.use_real_haiku))
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txt
index 8091fb6107..fbb8bb901f 100644
--- a/scripts/ci/german-allowlist.txt
+++ b/scripts/ci/german-allowlist.txt
@@ -250,7 +250,6 @@ jarvis/ui/web/frontend/src/components/runs/__tests__/toolTable.test.tsx
# German fixtures are the content under test for the bilingual confirm flow,
# evidence-gate domains, the turn-language resolver, the continuation buffer
# and the Spanish path (same rationale as the voice turn-taking block) ---
-tests/unit/awareness/test_awareness_recall_tool.py
tests/unit/brain/test_evidence_gate.py
tests/unit/brain/test_evidence_gate_wiring.py
tests/unit/brain/test_refresh_tools_di.py
@@ -272,10 +271,6 @@ jarvis/voice/tool_confirmation.py
jarvis/safety/explicit_intent.py
tests/unit/safety/test_explicit_intent.py
-# --- awareness-recall tool: forensic comments quote the German runtime phrase
-# ("der lokale Verlaufsspeicher ist nicht verfügbar") the DI fix addresses ---
-jarvis/plugins/tool/awareness_recall.py
-
# --- manager.py + config.py: forensic comments quote the same German runtime
# phrase, and config.py carries the evidence-domain voice-intent keyword
# vocabulary ("was hatte ich auf", "geoeffnete fenster") — German matching
@@ -348,8 +343,6 @@ jarvis/harness/screenshot_only_loop_stable.py
# --- German drain (2026-07-01): product-surface files where an inline i18n-allow
# marker is impossible (multiline prompt strings / JSON / YAML front-matter /
# verbatim forensic code-blocks). Each is one of the four allowed buckets. ---
-# German runtime summarizer system prompt (bucket 1, multiline string)
-jarvis/awareness/prompts.py
# German runtime self-observation system prompt (bucket 1, multiline string)
jarvis/board/prompts.py
# German user-utterance examples in the wiki-extraction prompt (bucket 3, multiline string)
diff --git a/scripts/ci/silent-handlers-baseline.json b/scripts/ci/silent-handlers-baseline.json
index 1559303704..1488afe1e6 100644
--- a/scripts/ci/silent-handlers-baseline.json
+++ b/scripts/ci/silent-handlers-baseline.json
@@ -47,14 +47,6 @@
"jarvis/audio/player.py": 6,
"jarvis/audio/vad.py": 4,
"jarvis/autostart/windows.py": 1,
- "jarvis/awareness/context.py": 1,
- "jarvis/awareness/manager.py": 2,
- "jarvis/awareness/probes/filesystem.py": 5,
- "jarvis/awareness/probes/git.py": 10,
- "jarvis/awareness/prompts.py": 1,
- "jarvis/awareness/story.py": 3,
- "jarvis/awareness/watchers/idle.py": 4,
- "jarvis/awareness/watchers/window.py": 11,
"jarvis/board/achievements.py": 1,
"jarvis/board/aggregator.py": 7,
"jarvis/board/evaluator.py": 3,
diff --git a/tests/board/test_categories.py b/tests/board/test_categories.py
index a399aa33a9..31d3cb716b 100644
--- a/tests/board/test_categories.py
+++ b/tests/board/test_categories.py
@@ -53,9 +53,7 @@ def test_six_stable_keys_in_order() -> None:
("read_visible_ui_state", "browser"),
("click_element", "browser"),
# Knowledge / memory — MUST win over "community" for the "recall"
- # substring (awareness-recall contains "call").
- ("awareness-recall", "knowledge"),
- ("awareness-snapshot", "knowledge"),
+ # substring (wiki-recall contains "call").
("wiki-recall", "knowledge"),
("wiki-ingest", "knowledge"),
("remember", "knowledge"),
diff --git a/tests/integration/awareness/test_a1_e2e.py b/tests/integration/awareness/test_a1_e2e.py
deleted file mode 100644
index fe3c46429c..0000000000
--- a/tests/integration/awareness/test_a1_e2e.py
+++ /dev/null
@@ -1,149 +0,0 @@
-"""Integration tests for Phase A1 — E2E with real Win32.
-
-Skips on Linux/Mac (Plan §5 AC). Spawns notepad.exe as a known
-foreground trigger and measures SetWinEventHook latency + UnhookWinEvent
-cleanup + the 2s shutdown budget.
-
-NOT collected by the standard test suite when running on non-Windows —
-pytestmark skips the whole module. On the worktree path
-``C:\\Users\\Administrator\\Desktop\\jarvis-a0`` (Win32) the tests run
-for real; on Linux CI: skipped.
-"""
-from __future__ import annotations
-
-import asyncio
-import os
-import subprocess
-import time
-
-import pytest
-
-pytestmark = pytest.mark.skipif(
- os.name != "nt",
- reason="Win32-only — hook lifecycle test needs a real pump thread",
-)
-
-# Imports must NOT crash on Linux — lazy imports in the watchers make sure of
-# that (see HN3). If they do: a module-top import of win32event or similar
-# was accidentally introduced → fix immediately.
-from jarvis.awareness.config import AwarenessConfig # noqa: E402
-from jarvis.awareness.manager import AwarenessManager # noqa: E402
-from jarvis.awareness.privacy import PrivacyFilter # noqa: E402
-from jarvis.awareness.watchers.idle import IdleDetector # noqa: E402
-from jarvis.awareness.watchers.window import WindowFocusWatcher # noqa: E402
-from jarvis.core.bus import EventBus # noqa: E402
-from jarvis.core.events import FrameUpdated, IdleEntered # noqa: E402
-
-
-def _async_collect(target: list):
- """Test helper: returns an async handler that appends events to the list."""
- async def _handler(ev):
- target.append(ev)
- return _handler
-
-
-async def test_window_focus_watcher_real_win32_hook() -> None:
- """Real SetWinEventHook: spawn notepad -> receive FrameUpdated.
-
- Needs an interactive desktop on which a freshly started notepad.exe takes
- the foreground. A hosted CI runner guarantees neither (no user in front
- of the session, and the image decides whether a classic ``notepad.exe``
- exists at all), so there the event may never fire and the test fails for
- the environment, not for the watcher. The hook lifecycle itself stays covered in CI by the
- double-lifecycle and stop-budget tests below.
- """
- cfg = AwarenessConfig.default()
- bus = EventBus()
- manager = AwarenessManager(cfg)
- privacy = PrivacyFilter(cfg)
-
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.start()
-
- proc = None
- try:
- proc = subprocess.Popen(["notepad.exe"])
- # Poll for the event (max 3s — hook latency should be <100ms)
- for _ in range(60):
- if any(ev.process_name.lower() == "notepad.exe" for ev in received):
- break
- await asyncio.sleep(0.05)
-
- assert any(ev.process_name.lower() == "notepad.exe" for ev in received), (
- f"No FrameUpdated for notepad.exe. "
- f"Received: {[(ev.process_name, ev.window_title) for ev in received]}"
- )
- finally:
- if proc is not None:
- proc.terminate()
- try:
- proc.wait(timeout=2)
- except subprocess.TimeoutExpired:
- proc.kill()
- await watcher.stop()
-
-
-async def test_window_focus_watcher_double_lifecycle() -> None:
- """start -> stop -> start -> stop without a crash (UnhookWinEvent works)."""
- cfg = AwarenessConfig.default()
- bus = EventBus()
- manager = AwarenessManager(cfg)
- privacy = PrivacyFilter(cfg)
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
-
- await watcher.start()
- await watcher.stop()
- await watcher.start()
- await watcher.stop()
-
-
-async def test_window_focus_watcher_stop_under_2s() -> None:
- """Plan §5 AC: stop() returns within 2 s."""
- cfg = AwarenessConfig.default()
- bus = EventBus()
- manager = AwarenessManager(cfg)
- privacy = PrivacyFilter(cfg)
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.start()
-
- t0 = time.perf_counter()
- await watcher.stop()
- elapsed = time.perf_counter() - t0
- assert elapsed < 2.0, f"stop() took {elapsed:.2f}s, exceeds 2s budget"
-
-
-async def test_idle_detector_real_threshold_2s() -> None:
- """IdleDetector with threshold_s=2 — waits 3.5s with no mouse/KB sim.
-
- Assumption: test runs in a non-interactive session (CI/headless).
- In an interactive session with mouse movement the test can fail
- — that counts as environmental noise, not an A1 regression.
- """
- cfg = AwarenessConfig.default()
- bus = EventBus()
- manager = AwarenessManager(cfg)
-
- received: list[IdleEntered] = []
- bus.subscribe(IdleEntered, _async_collect(received))
-
- detector = IdleDetector(manager=manager, bus=bus, threshold_s=2)
- await detector.start()
- try:
- await asyncio.sleep(3.5)
- assert manager.state.is_idle is True or len(received) > 0, (
- "Expected: IdleEntered after 3.5s of inactivity. "
- "If this fails: likely an interactive session with mouse movement."
- )
- finally:
- await detector.stop()
diff --git a/tests/integration/awareness/test_a2_e2e.py b/tests/integration/awareness/test_a2_e2e.py
deleted file mode 100644
index df57452713..0000000000
--- a/tests/integration/awareness/test_a2_e2e.py
+++ /dev/null
@@ -1,329 +0,0 @@
-"""Phase A2 — End-to-end integration test.
-
-Real components wired up (EventBus + RecallStore with a tmpdir DB +
-StoryTracker + FakeVerdichter). Simulates a real bus sequence:
-
- FrameUpdated x N -> IdleEntered
-
-and checks the full path:
-
- - the condenser is called exactly once with the high-salience frames
- - the episode lands in awareness_episodes (SQLite)
- - the FTS index awareness_episodes_fts is populated (searchable)
- - state.last_episode_summary + last_episode_id were set
- - the EpisodeRecorded event was published
- - frames blocked by PrivacyFilter are NOT in the condenser input
-
-Plan §6 AC §6:
- - "Episode is created after a window switch to a different app (test with bus replay)" ✅
- - "Episode lands in SQLite, FTS index is populated" ✅
- - "state.last_episode_summary is updated after every flush" ✅
- - "Frames blocked by PrivacyFilter are NOT in the condenser input" ✅
-
-Convention: fakes instead of mocks (CLAUDE.md). FakeVerdichter is deterministic.
-"""
-from __future__ import annotations
-
-import time
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-import pytest
-
-from jarvis.awareness.config import AwarenessConfig, AwarenessStoryConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.awareness.story import StoryTracker
-from jarvis.core.bus import EventBus
-from jarvis.core.events import (
- EpisodeRecorded,
- FrameUpdated,
- IdleEntered,
-)
-from jarvis.memory.recall import RecallStore
-
-# ---- Fakes -----------------------------------------------------------------
-
-
-@dataclass
-class FakeVerdichter:
- """Deterministic condenser — no real brain call in the e2e test."""
- summary: str = "E2E Test: User war in Code.exe mit pipeline.py aktiv."
- tokens_in: int = 250
- tokens_out: int = 80
- calls: list[dict[str, Any]] = field(default_factory=list)
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- self.calls.append({
- "frames": list(frames),
- "events": list(events),
- "primary_app": primary_app,
- })
- return self.summary, {
- "tokens_in": self.tokens_in,
- "tokens_out": self.tokens_out,
- "duration_ms": 150,
- "error_reason": None,
- }
-
-
-# ---- Fixtures --------------------------------------------------------------
-
-
-async def recall_store(tmp_path: Path) -> RecallStore:
- db_path = tmp_path / "jarvis_a2_e2e.db"
- store = RecallStore(db_path)
- await store.open()
- yield store
- await store.close()
-
-
-# ---- Helpers ---------------------------------------------------------------
-
-
-def _make_frame(
- *,
- title: str,
- process: str = "Code.exe",
- pid: int = 1000,
- ts_ns: int | None = None,
- capture_allowed: bool = True,
-) -> FrameSnapshot:
- return FrameSnapshot(
- timestamp_ns=ts_ns if ts_ns is not None else time.time_ns(),
- active_window_title=title,
- active_process_name=process,
- active_pid=pid,
- is_capture_allowed=capture_allowed,
- )
-
-
-def _frame_event(frame: FrameSnapshot) -> FrameUpdated:
- return FrameUpdated(
- window_title=frame.active_window_title,
- process_name=frame.active_process_name,
- pid=frame.active_pid,
- is_capture_allowed=frame.is_capture_allowed,
- )
-
-
-# ---- Tests -----------------------------------------------------------------
-
-
-async def test_e2e_idle_flush_persists_episode_with_fts(
- recall_store: RecallStore,
-) -> None:
- """Bus replay: 3 high-salience frames -> IdleEntered -> episode in SQLite + FTS."""
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- verdichter = FakeVerdichter(
- summary="User arbeitete an pipeline.py in Code.exe (~12min).",
- )
- cfg = AwarenessStoryConfig(episode_min_duration_s=1)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall_store,
- verdichter=verdichter, config=cfg,
- )
- received: list[EpisodeRecorded] = []
-
- async def collect(ev: EpisodeRecorded) -> None:
- received.append(ev)
- bus.subscribe(EpisodeRecorded, collect)
-
- # 3 salient frames (different titles, same process → +30 each)
- base_ts = time.time_ns() - 2_000_000_000 # 2s in the past
- for i, title in enumerate(["pipeline.py", "manager.py", "factory.py"]):
- f = _make_frame(title=title, ts_ns=base_ts + i * 500_000_000)
- manager.state.current_frame = f
- await tracker._on_frame_updated(_frame_event(f))
-
- # IdleEntered → flush
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
-
- # Condenser was called 1x
- assert len(verdichter.calls) == 1
- call = verdichter.calls[0]
- assert len(call["frames"]) == 3
- assert call["primary_app"] == "Code.exe"
-
- # Episode in SQLite
- episodes = await recall_store.recent_episodes(limit=10)
- assert len(episodes) == 1
- ep = episodes[0]
- assert ep["summary"] == "User arbeitete an pipeline.py in Code.exe (~12min)."
- assert ep["primary_app"] == "Code.exe"
- assert ep["frame_count"] == 3
- assert ep["trigger_kind"] == "idle_entered"
- assert ep["tokens_in"] == 250
- assert ep["tokens_out"] == 80
-
- # FTS index is populated: search returns the episode
- fts_results = await recall_store.search_episodes(query="pipeline", limit=10)
- assert len(fts_results) == 1
- assert fts_results[0]["summary"] == ep["summary"]
-
- # State updated
- assert manager.state.last_episode_summary == ep["summary"]
- assert manager.state.last_episode_id == ep["id"]
-
- # EpisodeRecorded event published
- import asyncio as _aio
- await _aio.sleep(0.05)
- assert len(received) == 1
- assert received[0].episode_id == ep["id"]
- assert received[0].summary_preview == ep["summary"][:80]
-
-
-async def test_e2e_privacy_blocked_frames_not_in_verdichter_input(
- recall_store: RecallStore,
-) -> None:
- """Hard negative §6: capture_allowed=False frames NEVER in the condenser input."""
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- verdichter = FakeVerdichter()
- cfg = AwarenessStoryConfig(episode_min_duration_s=1)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall_store,
- verdichter=verdichter, config=cfg,
- )
-
- base_ts = time.time_ns() - 2_000_000_000
- # Mix: 2 allowed, 1 blocked, 2 allowed
- sequence = [
- ("file_a.py", True),
- ("Banking - Sparkasse", False), # PrivacyFilter blocked
- ("file_b.py", True),
- ("Password Vault", False), # blocked
- ("file_c.py", True),
- ]
- for i, (title, allowed) in enumerate(sequence):
- f = _make_frame(
- title=title, ts_ns=base_ts + i * 500_000_000,
- capture_allowed=allowed,
- )
- manager.state.current_frame = f
- await tracker._on_frame_updated(_frame_event(f))
-
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
-
- # Condenser call contains NO blocked titles
- assert len(verdichter.calls) == 1
- call = verdichter.calls[0]
- titles_seen = [f["window_title"] for f in call["frames"]]
- assert "Banking - Sparkasse" not in titles_seen
- assert "Password Vault" not in titles_seen
- # Allowed titles are present (3 of them)
- assert len(titles_seen) == 3
- for t in ("file_a.py", "file_b.py", "file_c.py"):
- assert t in titles_seen
-
-
-async def test_e2e_app_switch_creates_episode_after_min_duration(
- recall_store: RecallStore,
-) -> None:
- """Plan §6 AC: episode is created after a window switch to a different app."""
- import asyncio as _aio
-
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- verdichter = FakeVerdichter(summary="Code-Phase abgeschlossen.")
- cfg = AwarenessStoryConfig(episode_min_duration_s=1)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall_store,
- verdichter=verdichter, config=cfg,
- )
-
- # Frame in Code.exe
- f1 = _make_frame(title="main.py", process="Code.exe")
- manager.state.current_frame = f1
- await tracker._on_frame_updated(_frame_event(f1))
-
- # > min_duration warten
- await _aio.sleep(1.1)
-
- # App-Switch: Code → Chrome
- f2 = _make_frame(
- title="GitHub - PR #42", process="chrome.exe", pid=2000,
- )
- manager.state.current_frame = f2
- await tracker._on_frame_updated(_frame_event(f2))
-
- # Episode persistiert mit trigger="window_switch"
- episodes = await recall_store.recent_episodes(limit=10)
- assert len(episodes) == 1
- assert episodes[0]["trigger_kind"] == "window_switch"
- assert episodes[0]["primary_app"] == "Code.exe"
-
-
-async def test_e2e_short_episode_not_persisted(
- recall_store: RecallStore,
-) -> None:
- """Plan §6 AC: episode NOT created on a same-app switch without the 60s minimum duration."""
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- verdichter = FakeVerdichter()
- # min_duration=999s — alle App-Switches sind "zu kurz"
- cfg = AwarenessStoryConfig(episode_min_duration_s=999)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall_store,
- verdichter=verdichter, config=cfg,
- )
-
- base_ts = time.time_ns()
- f1 = _make_frame(title="main.py", process="Code.exe", ts_ns=base_ts)
- manager.state.current_frame = f1
- await tracker._on_frame_updated(_frame_event(f1))
-
- f2 = _make_frame(
- title="GitHub", process="chrome.exe", pid=2,
- ts_ns=base_ts + 500_000_000, # 0.5s spaeter
- )
- manager.state.current_frame = f2
- await tracker._on_frame_updated(_frame_event(f2))
-
- # Condenser NOT called, recall empty
- assert verdichter.calls == []
- episodes = await recall_store.recent_episodes(limit=10)
- assert len(episodes) == 0
-
-
-async def test_e2e_state_snapshot_includes_episode_summary(
- recall_store: RecallStore,
-) -> None:
- """Plan §6 AC: state.snapshot_for_prompt() contains the summary after a flush."""
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- summary = "Du arbeitest seit 23min an pipeline.py in Code.exe."
- verdichter = FakeVerdichter(summary=summary)
- cfg = AwarenessStoryConfig(episode_min_duration_s=1)
- tracker = StoryTracker(
- manager=manager, bus=bus, recall=recall_store,
- verdichter=verdichter, config=cfg,
- )
-
- f = _make_frame(title="pipeline.py")
- manager.state.current_frame = f
- await tracker._on_frame_updated(_frame_event(f))
- import asyncio as _aio
- await _aio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
-
- snap = manager.state.snapshot_for_prompt(max_chars=600)
- # current_frame is None (the watcher wasn't started); but
- # last_episode_summary is set → should be rendered.
- # If current_frame is None: snapshot_for_prompt returns "" — that's
- # the A1 implementation. Let's make sure it either
- # renders OR set current_frame.
- # Set current_frame again so the snapshot renders:
- manager.state.current_frame = f
- snap = manager.state.snapshot_for_prompt(max_chars=600)
- assert summary in snap
- assert "pipeline.py" in snap
diff --git a/tests/integration/awareness/test_a3_e2e.py b/tests/integration/awareness/test_a3_e2e.py
deleted file mode 100644
index 18c38a4a83..0000000000
--- a/tests/integration/awareness/test_a3_e2e.py
+++ /dev/null
@@ -1,131 +0,0 @@
-"""End-to-end test for Awareness Phase A3.
-
-Goes through the full happy path without mocks: open a real SQLite-backed
-``RecallStore``, persist three real episodes through ``record_episode``
-(which fires the FTS5 trigger automatically), instantiate the real
-``AwarenessRecallTool``, call ``execute`` with a real time-bounded query,
-and assert on the rendered markdown output.
-
-The point is to catch wiring drift — schema/trigger out of sync, sanitizer
-swallowing valid queries, time arithmetic flipped sign, etc. — that unit
-tests with mocked stores would miss.
-"""
-from __future__ import annotations
-
-import time
-from pathlib import Path
-
-import pytest
-import pytest_asyncio
-
-from jarvis.memory import RecallStore
-from jarvis.plugins.tool.awareness_recall import AwarenessRecallTool
-
-
-@pytest_asyncio.fixture
-async def store(tmp_path: Path):
- s = RecallStore(tmp_path / "awareness.db")
- await s.open()
- yield s
- await s.close()
-
-
-async def test_end_to_end_search_finds_recent_writes_filtering_old_ones(
- store: RecallStore,
-) -> None:
- """Three real episodes — one old, two recent — must filter and rank correctly."""
- now_ns = time.time_ns()
- minute_ns = 60 * 1_000_000_000
-
- # 3 hours ago: should be filtered out by since_minutes=60.
- await store.record_episode(
- started_at_ns=now_ns - 180 * minute_ns,
- ended_at_ns=now_ns - 179 * minute_ns,
- trigger_kind="window_switch",
- summary="pipeline refactor that should NOT appear in 60min window",
- frame_count=4,
- primary_app="code.exe",
- )
- # 20 minutes ago: must appear, lower BM25 rank than the very recent one.
- await store.record_episode(
- started_at_ns=now_ns - 20 * minute_ns,
- ended_at_ns=now_ns - 19 * minute_ns,
- trigger_kind="window_switch",
- summary="pipeline configure event bus subscribers",
- frame_count=6,
- primary_app="code.exe",
- )
- # 2 minutes ago: must appear.
- await store.record_episode(
- started_at_ns=now_ns - 2 * minute_ns,
- ended_at_ns=now_ns - 1 * minute_ns,
- trigger_kind="idle_entered",
- summary="pipeline tests finally green",
- frame_count=2,
- primary_app="code.exe",
- )
-
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute(
- {"query": "pipeline", "k": 5, "since_minutes": 60},
- ctx=None,
- )
-
- assert result.success is True
- out = result.output
- assert "pipeline configure event bus" in out
- assert "pipeline tests finally green" in out
- assert "should NOT appear" not in out
- # Markdown shape: header line then bullet snippets.
- bullets = [ln for ln in out.splitlines() if ln.startswith("- ")]
- assert len(bullets) == 2
- # Each bullet must carry the primary-app marker.
- assert all("code.exe" in line for line in bullets)
-
-
-async def test_end_to_end_no_keyword_match_falls_back_to_recency(store: RecallStore) -> None:
- """Keyword miss with an in-window episode → recency fallback, not a bare empty.
-
- The store holds an episode the keyword does not match. A recency question
- ("what did I have open?") must still get the real activity, clearly
- labelled as a reachable-store recency fallback — never a bare "nothing"
- that a brain can mis-narrate as a store outage (2026-06-18 confabulation).
- """
- now_ns = time.time_ns()
- minute_ns = 60 * 1_000_000_000
- await store.record_episode(
- started_at_ns=now_ns - 10 * minute_ns,
- ended_at_ns=now_ns - 9 * minute_ns,
- trigger_kind="window_switch",
- summary="reading documentation about caching strategies",
- frame_count=1,
- primary_app="msedge.exe",
- )
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute(
- {"query": "completely-unrelated-term", "since_minutes": 60},
- ctx=None,
- )
- assert result.success is True
- # The in-window episode is surfaced as recent activity, not dropped.
- assert "msedge.exe" in result.output
- # ...and the output LEADS positively with the data (never a leading
- # negation a skimming model reads as "unavailable").
- first_line = result.output.splitlines()[0].lower()
- assert not first_line.startswith("no ")
- assert "activity" in first_line or "history" in first_line
-
-
-async def test_end_to_end_empty_window_affirms_store_reachable(store: RecallStore) -> None:
- """No episodes at all in the window → honest "no episodes", store reachable."""
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute(
- {"query": "completely-unrelated-term", "since_minutes": 60},
- ctx=None,
- )
- assert result.success is True
- assert "no activity" in result.output.lower()
- assert "reachable" in result.output.lower()
diff --git a/tests/integration/awareness/test_a5_e2e.py b/tests/integration/awareness/test_a5_e2e.py
deleted file mode 100644
index 74eb6e0047..0000000000
--- a/tests/integration/awareness/test_a5_e2e.py
+++ /dev/null
@@ -1,125 +0,0 @@
-"""Phase A5-Lite — End-to-end integration test.
-
-Verifies that ``AwarenessManager.probe_all`` parallelizes correctly,
-honors the total budget, catches probe exceptions, and returns a
-merged dict.
-
-Plan §9 AC:
-- GitProbe returns the branch when cwd = git repo, else None ✓
-- FileSystemWatcher emits a FileSaved event ✓ (test_filesystem_probe)
-- All probes have an individual timeout (200ms total budget) ✓
-- Probe errors do NOT crash; unset fields become None ✓
-"""
-from __future__ import annotations
-
-import asyncio
-import subprocess
-from pathlib import Path
-from typing import Any
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.probes import FileSystemProbe, GitProbe
-from jarvis.core.bus import EventBus
-
-# ---- Fakes -----------------------------------------------------------------
-
-
-class _SlowProbe:
- """Probe that needs >budget — tests timeout handling."""
- name = "slow"
- async def probe(self, *, cwd: str | None, process_name: str = "") -> dict[str, Any]:
- await asyncio.sleep(0.5) # > 200ms budget
- return {"slow_field": "should_not_be_in_output"}
-
-
-class _RaisingProbe:
- """Probe that raises — tests return_exceptions=True."""
- name = "raising"
- async def probe(self, *, cwd: str | None, process_name: str = "") -> dict[str, Any]:
- raise RuntimeError("simulated probe failure")
-
-
-class _StaticProbe:
- """Probe with deterministic output."""
- name = "static"
- def __init__(self, output: dict[str, Any]) -> None:
- self._output = output
- async def probe(self, *, cwd: str | None, process_name: str = "") -> dict[str, Any]:
- return dict(self._output)
-
-
-# ---- Tests -----------------------------------------------------------------
-
-
-async def test_probe_all_empty_probes_returns_empty_dict() -> None:
- """Default manager has no probes → probe_all returns {}."""
- m = AwarenessManager(AwarenessConfig.default())
- result = await m.probe_all(pid=1234, process_name="Code.exe")
- assert result == {}
-
-
-async def test_probe_all_merges_multiple_probe_outputs() -> None:
- """2 StaticProbes → merged dict."""
- m = AwarenessManager(AwarenessConfig.default())
- m._probes = [
- _StaticProbe({"git_branch": "main"}),
- _StaticProbe({"open_file_hint": "C:/x/y.py"}),
- ]
- result = await m.probe_all(pid=0, process_name="Code.exe")
- assert result == {"git_branch": "main", "open_file_hint": "C:/x/y.py"}
-
-
-async def test_probe_all_timeout_returns_empty_dict() -> None:
- """Probe needs >budget → wait_for triggers TimeoutError → {}."""
- cfg = AwarenessConfig.default()
- cfg.probes.total_budget_ms = 50 # 50ms budget
- m = AwarenessManager(cfg)
- m._probes = [_SlowProbe()]
- result = await m.probe_all(pid=0, process_name="x")
- assert result == {}
-
-
-async def test_probe_all_swallows_probe_exceptions() -> None:
- """Probe raises an exception → return_exceptions=True → field missing from output, no crash."""
- m = AwarenessManager(AwarenessConfig.default())
- m._probes = [
- _RaisingProbe(),
- _StaticProbe({"git_branch": "main"}),
- ]
- result = await m.probe_all(pid=0, process_name="x")
- # raising-probe contributed nothing, static-probe did
- assert result == {"git_branch": "main"}
-
-
-async def test_probe_all_with_real_git_probe_in_repo(tmp_path: Path) -> None:
- """Real GitProbe against a tmp git-init → returns the branch.
-
- Bypasses the ``probe_all`` path because psutil's cwd-resolve doesn't
- work for a fake pid — we instantiate GitProbe directly and call
- ``probe()`` with tmp_path as cwd.
- """
- subprocess.run( # noqa: ASYNC221 — sync subprocess only in test setup
- ["git", "init", "--initial-branch=main", str(tmp_path)],
- check=True, capture_output=True,
- )
- git = GitProbe()
- result = await git.probe(cwd=str(tmp_path), process_name="x")
- assert result == {"git_branch": "main"}
-
-
-async def test_filesystem_probe_lifecycle_via_manager() -> None:
- """FileSystemProbe can start/stop via the manager without crashing."""
- bus = EventBus()
- m = AwarenessManager(AwarenessConfig.default(), bus=bus)
- fs = FileSystemProbe(bus=bus)
- m._fs_probe = fs
- m._probes = [fs]
- await m.start()
- try:
- # Manager.start() already called fs.start() (per manager.py:start())
- result = await m.probe_all(pid=0, process_name="x")
- # cwd=None → fs returns {open_file_hint: None}
- assert result == {"open_file_hint": None}
- finally:
- await m.stop()
diff --git a/tests/integration/test_ack_flow.py b/tests/integration/test_ack_flow.py
index 27f8a2f52f..c8ed99cf4c 100644
--- a/tests/integration/test_ack_flow.py
+++ b/tests/integration/test_ack_flow.py
@@ -8,7 +8,7 @@ These tests cover the spec's §8 "Test Strategy" integration scenarios:
2. Voice-control bypass ("sei still") — no Flash-Brain call.
3. Provider error → no AnnouncementRequested → main response still emits.
4. Audio order: ack publish timestamp strictly before main-response timestamp.
-5. ACK_SKIP_TOOLS scenario: passive read tool (awareness_snapshot) does not
+5. ACK_SKIP_TOOLS scenario: passive read tool (screen_snapshot) does not
emit a router-side ack.
6. Concurrent launch: both tasks scheduled in the same event-loop tick.
diff --git a/tests/integration/test_capability_coupling_e2e.py b/tests/integration/test_capability_coupling_e2e.py
index 3dddad46da..d61bf67a84 100644
--- a/tests/integration/test_capability_coupling_e2e.py
+++ b/tests/integration/test_capability_coupling_e2e.py
@@ -181,7 +181,7 @@ def test_search_web_unregistered_hits_unsupported() -> None:
fall into UNSUPPORTED — guarding the historical search_web prompt drift
where the system prompt advertised a tool that did not exist."""
# Use a fresh registry without web-search (seeded default has 'such' on
- # awareness/wiki recall but those resolve, so we use an isolated registry).
+ # wiki recall but those resolve, so we use an isolated registry).
fresh = CapabilityRegistry()
# No capabilities registered → action_intent True, resolve None
assert fresh.has_action_intent("such im web nach python 3.13")
diff --git a/tests/integration/test_cli_integration.py b/tests/integration/test_cli_integration.py
index afa745de9c..a5476602fe 100644
--- a/tests/integration/test_cli_integration.py
+++ b/tests/integration/test_cli_integration.py
@@ -147,8 +147,6 @@ async def test_load_tools_for_tier_includes_cli_tool(tmp_path: Path) -> None:
people=None,
config=JarvisConfig(),
mission_manager=None,
- awareness_manager=None,
- recall_store=None,
)
assert "cli_demo" in tools, f"cli_demo not loaded; got {sorted(tools)}"
diff --git a/tests/integration/test_factory_wiring.py b/tests/integration/test_factory_wiring.py
index 63346ca4d9..627e73191a 100644
--- a/tests/integration/test_factory_wiring.py
+++ b/tests/integration/test_factory_wiring.py
@@ -71,74 +71,3 @@ def test_echo_mode_escape_works() -> None:
assert result.startswith("Echo:")
finally:
os.environ.pop("JARVIS_BRAIN", None)
-
-
-def test_verdichter_provider_follows_brain_primary_when_non_claude(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """BUG-LIVE-04 regression — when `[brain.primary]` is not Claude
- but the Verdichter config still carries its legacy `provider =
- "claude-api"` default, the factory must redirect the verdichter
- brain instantiation to the user's primary provider. Otherwise the
- live log fills with `Your credit balance is too low to access the
- Anthropic API` for an account the user does not own."""
- from jarvis.brain import factory as factory_module
- from jarvis.brain.provider_registry import BrainProviderRegistry
- from jarvis.core import config as config_module
-
- cfg = config_module.load_config()
- # Stage the precondition: brain.primary points at a non-Claude
- # provider (mirror what BUG-017 left in `jarvis.toml` — Grok).
- monkeypatch.setattr(cfg.brain, "primary", "grok", raising=False)
- # Ensure a `grok` ProviderConfig with a sane `model` exists so the
- # redirect can pick a real model id.
- providers = dict(cfg.brain.providers)
- if "grok" not in providers:
- from jarvis.core.config import BrainProviderConfig
-
- providers["grok"] = BrainProviderConfig(
- api="grok",
- model="grok-4.3",
- deep_model="grok-4.3",
- )
- monkeypatch.setattr(cfg.brain, "providers", providers, raising=False)
- monkeypatch.setattr(cfg.awareness.verdichter, "provider", "claude-api", raising=False)
- monkeypatch.setattr(cfg.awareness.verdichter, "model", "claude-haiku-4-5-20251001", raising=False)
- monkeypatch.setattr(cfg.awareness.verdichter, "enabled", True, raising=False)
- monkeypatch.setattr(cfg.awareness, "enabled", True, raising=False)
-
- monkeypatch.setattr(config_module, "load_config", lambda: cfg)
-
- captured: list[tuple[str, str]] = []
-
- real_instantiate = BrainProviderRegistry.instantiate
-
- def fake_instantiate(self, provider: str, *, model: str | None = None, **kw):
- captured.append((provider, model or ""))
- # Return whatever the real registry would have given us for the
- # primary so the rest of the factory build doesn't have to mock
- # an entire Brain.
- if provider == "claude-api":
- raise AssertionError(
- f"factory must NOT call claude-api when brain.primary={cfg.brain.primary!r}"
- )
- return real_instantiate(self, provider, model=model, **kw)
-
- monkeypatch.setattr(BrainProviderRegistry, "instantiate", fake_instantiate)
-
- os.environ.pop("JARVIS_BRAIN", None)
- try:
- factory_module.build_default_brain(tier="router")
- except Exception:
- # Factory may still fail downstream (missing credentials etc.) —
- # we only care about the provider-redirect, which fires before
- # any real call.
- pass
-
- verdichter_calls = [
- (p, m) for (p, m) in captured if p == "grok" and "grok" in m.lower()
- ]
- assert verdichter_calls, (
- f"Expected at least one Verdichter instantiation redirected to grok; "
- f"captured={captured}"
- )
diff --git a/tests/integration/test_skill_listing_in_prompt.py b/tests/integration/test_skill_listing_in_prompt.py
index ca7eb38163..659b9b2025 100644
--- a/tests/integration/test_skill_listing_in_prompt.py
+++ b/tests/integration/test_skill_listing_in_prompt.py
@@ -9,9 +9,6 @@ These tests:
1. Verify the section appears with real skills loaded from disk.
2. Verify the section is absent when the context is unset (Headless-Mock-Mode).
3. Verify a renderer crash does not break the prompt build (defense-in-depth).
-
-Pattern reference: ``tests/unit/awareness/test_system_prompt_injection.py``
-mirrors this same structure for the Awareness snapshot.
"""
from __future__ import annotations
@@ -76,7 +73,7 @@ def _reset_skill_context() -> Iterator[None]:
def _make_brain_manager() -> BrainManager:
- """BrainManager with no awareness/memory — minimal harness for prompt tests."""
+ """BrainManager with no memory — minimal harness for prompt tests."""
return BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})
diff --git a/tests/missions/kontrollierer/test_worker_prompt.py b/tests/missions/kontrollierer/test_worker_prompt.py
index 3ff5c423ed..579d0fa788 100644
--- a/tests/missions/kontrollierer/test_worker_prompt.py
+++ b/tests/missions/kontrollierer/test_worker_prompt.py
@@ -109,7 +109,7 @@ def test_supervisor_boundary_names_the_knowledge_surface() -> None:
"""The directive is the one prompt chokepoint — a granted tool the model
was never told about is dead weight (ADR-0030)."""
text = SUPERVISOR_BOUNDARY_DIRECTIVE.lower()
- for name in ("awareness-recall", "search_web", "contact-lookup"):
+ for name in ("search_web", "contact-lookup"):
assert name in text
# Honesty clause: gated-off tools are simply absent from the tool list,
# and the model must not guess-call them (a blind call dirties the
diff --git a/tests/missions/test_worker_capability_parity.py b/tests/missions/test_worker_capability_parity.py
index 4a740d100b..10a80acd8c 100644
--- a/tests/missions/test_worker_capability_parity.py
+++ b/tests/missions/test_worker_capability_parity.py
@@ -103,12 +103,9 @@ def test_config_command_is_rejected_from_worker_inventory() -> None:
WorkerCapabilityInventory.build(app_commands=("brain-switch",))
-def test_worker_knowledge_surface_baseline(monkeypatch: pytest.MonkeyPatch) -> None:
- """All gates off → the wiki triple plus the always-on research pair
- (ADR-0030). Control surfaces and the excluded tools stay out."""
- from jarvis.missions.workers import capabilities
-
- monkeypatch.setattr(capabilities, "_awareness_recall_available", lambda: False)
+def test_worker_knowledge_surface_baseline() -> None:
+ """The wiki triple plus the always-on research pair (ADR-0030).
+ Control surfaces and the excluded tools stay out."""
tools = set(restricted_worker_knowledge_tools())
assert tools == {
@@ -120,28 +117,14 @@ def test_worker_knowledge_surface_baseline(monkeypatch: pytest.MonkeyPatch) -> N
}
assert "computer_use" not in tools
assert "run_shell" not in tools
- # Deliberate ADR-0030 exclusions: live-desktop read, unattended write.
- assert "awareness-snapshot" not in tools
+ # Deliberate ADR-0030 exclusion: unattended write.
assert "contact-upsert" not in tools
assert not any(name.startswith("cli_") for name in tools)
-def test_awareness_gate_adds_session_memory(monkeypatch: pytest.MonkeyPatch) -> None:
- from jarvis.missions.workers import capabilities
-
- monkeypatch.setattr(capabilities, "_awareness_recall_available", lambda: True)
-
- assert "awareness-recall" in restricted_worker_knowledge_tools()
-
-
-def test_every_granted_knowledge_tool_passes_the_broker_denylist(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jarvis.missions.workers import capabilities
+def test_every_granted_knowledge_tool_passes_the_broker_denylist() -> None:
from jarvis.missions.workers.worker_tool_broker import worker_tool_name_allowed
- monkeypatch.setattr(capabilities, "_awareness_recall_available", lambda: True)
-
for name in restricted_worker_knowledge_tools():
assert worker_tool_name_allowed(name), name
@@ -150,9 +133,7 @@ def test_mission_inventory_combines_wiki_reads_with_relevant_connectors(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from jarvis.missions import init as missions_init
- from jarvis.missions.workers import capabilities
- monkeypatch.setattr(capabilities, "_awareness_recall_available", lambda: False)
monkeypatch.setattr(
missions_init,
"_assemble_worker_mcp_servers",
diff --git a/tests/unit/awareness/__init__.py b/tests/unit/awareness/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/unit/awareness/test_awareness_recall_tool.py b/tests/unit/awareness/test_awareness_recall_tool.py
deleted file mode 100644
index c06f0ebf77..0000000000
--- a/tests/unit/awareness/test_awareness_recall_tool.py
+++ /dev/null
@@ -1,325 +0,0 @@
-"""Tests for ``jarvis.plugins.tool.awareness_recall.AwarenessRecallTool``.
-
-Plan §7 (Phase A3): a read-only BM25 search across recent episodes,
-called by the router brain when the user references earlier work. The
-plan originally placed this in a sub-jarvis tier; Welle 4 removed that
-tier, so the tool lives in ``ROUTER_TOOLS``.
-
-Tests cover:
-- Plan-mandated tool shape (name, risk_tier, schema, description hints).
-- Hit / miss behaviour with seeded episodes.
-- ``since_minutes`` filter correctness via a small clock-skew fixture.
-- ``k`` cap honoured.
-- Defensive path: ``recall_store=None`` yields ``success=False`` instead
- of throwing.
-- Latency budget (loose).
-- Routing-tier placement: in ``ROUTER_TOOLS``, not in any worker set.
-"""
-from __future__ import annotations
-
-import time
-from pathlib import Path
-
-import pytest
-import pytest_asyncio
-
-from jarvis.memory import RecallStore
-from jarvis.plugins.tool.awareness_recall import AwarenessRecallTool
-
-
-# ---------------------------------------------------------------------------
-# Fixtures
-# ---------------------------------------------------------------------------
-
-@pytest_asyncio.fixture
-async def store(tmp_path: Path):
- s = RecallStore(tmp_path / "awareness.db")
- await s.open()
- yield s
- await s.close()
-
-
-async def _seed(store: RecallStore, *, summary: str, app: str, minutes_ago: int) -> int:
- """Insert one episode whose ``started_at_ns`` lies ``minutes_ago`` in the past."""
- now_ns = time.time_ns()
- delta_ns = minutes_ago * 60 * 1_000_000_000
- return await store.record_episode(
- started_at_ns=now_ns - delta_ns,
- ended_at_ns=now_ns - delta_ns + 1_000_000_000,
- trigger_kind="window_switch",
- summary=summary,
- frame_count=3,
- primary_app=app,
- )
-
-
-# ---------------------------------------------------------------------------
-# Plan-mandated tool shape
-# ---------------------------------------------------------------------------
-
-def test_name_is_awareness_recall() -> None:
- tool = AwarenessRecallTool(recall_store=None)
- assert tool.name == "awareness-recall"
-
-
-def test_risk_tier_is_safe() -> None:
- tool = AwarenessRecallTool(recall_store=None)
- assert tool.risk_tier == "safe"
-
-
-def test_schema_requires_query_only() -> None:
- tool = AwarenessRecallTool(recall_store=None)
- assert tool.schema["required"] == ["query"]
- assert "k" in tool.schema["properties"]
- assert "since_minutes" in tool.schema["properties"]
-
-
-def test_schema_clamps_documented() -> None:
- """k and since_minutes must declare their bounds."""
- tool = AwarenessRecallTool(recall_store=None)
- props = tool.schema["properties"]
- assert props["k"]["minimum"] == 1
- assert props["k"]["maximum"] == 10
- assert props["since_minutes"]["minimum"] == 1
- assert props["since_minutes"]["maximum"] == 10080 # 7 days
-
-
-def test_description_mentions_user_phrasing() -> None:
- """The description must hint at the user phrases the brain should map to it."""
- tool = AwarenessRecallTool(recall_store=None)
- descr = tool.description.lower()
- assert "vorhin" in descr or "earlier" in descr
-
-
-# ---------------------------------------------------------------------------
-# Defensive path
-# ---------------------------------------------------------------------------
-
-async def test_recall_store_none_returns_unavailable_without_throwing() -> None:
- tool = AwarenessRecallTool(recall_store=None)
- result = await tool.execute({"query": "pipeline"}, ctx=None)
- assert result.success is False
- assert result.error is not None
- assert "unavailable" in result.error.lower()
-
-
-# ---------------------------------------------------------------------------
-# Hit / miss
-# ---------------------------------------------------------------------------
-
-async def test_no_episodes_returns_friendly_empty(store: RecallStore) -> None:
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "pipeline"}, ctx=None)
- assert result.success is True
- # Empty window: honest AND explicitly reachable, so it cannot be
- # mis-narrated as an outage (2026-06-18 confabulation).
- assert "reachable" in result.output.lower()
- assert "no activity" in result.output.lower()
-
-
-async def test_match_returns_markdown_with_app_name(store: RecallStore) -> None:
- await _seed(store, summary="pipeline refactor on event bus", app="code.exe", minutes_ago=5)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "pipeline"}, ctx=None)
- assert result.success is True
- assert "code.exe" in result.output
- assert "pipeline" in result.output.lower()
- assert result.output.lstrip().startswith("Found")
-
-
-async def test_match_includes_local_hhmm(store: RecallStore) -> None:
- await _seed(store, summary="working on awareness recall", app="code.exe", minutes_ago=1)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "awareness"}, ctx=None)
- assert result.success is True
- # Look for HH:MM-shaped substring in the output.
- import re
- assert re.search(r"\b\d{2}:\d{2}\b", result.output) is not None
-
-
-# ---------------------------------------------------------------------------
-# Recency fallback (honesty: a reachable-but-no-keyword-match store must not
-# surface a bare empty result that a brain can mis-narrate as an outage)
-# ---------------------------------------------------------------------------
-
-async def test_no_keyword_match_falls_back_to_recent_timeline(store: RecallStore) -> None:
- """Keyword miss + episodes in window → return the recent activity timeline.
-
- Regression for the 2026-06-18 "der Awareness-Speicher meldet einen Fehler
- und ist nicht erreichbar" confabulation: the store was reachable and held
- 375 episodes, but the user's recency question ("what did I have open
- today") produced keywords that did not match the sparse episode summaries.
- The tool returned a bare "No episodes matched", and the deep brain
- escalated that *empty* result into a false *unavailable* claim. The fix
- makes the tool hand the brain the real activity timeline (which directly
- answers a recency question) instead of an empty result.
- """
- # Episodes exist in the window but none contain the keyword 'kubernetes'.
- await _seed(store, summary="", app="ShareX.exe", minutes_ago=20)
- await _seed(
- store, summary="Der Nutzer war in der Anwendung python",
- app="python.exe", minutes_ago=40,
- )
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "kubernetes"}, ctx=None)
- assert result.success is True
- # The brain must receive the user's real activity, not a bare "nothing".
- assert "python.exe" in result.output
- assert "ShareX.exe" in result.output
- # The output must LEAD positively with the data — never a leading
- # negation ("No episode summary matched …") that a skimming model reads
- # as "unavailable" (the regression that kept the bug alive after the
- # first fix attempt). The keyword caveat is a trailing note only.
- first_line = result.output.splitlines()[0].lower()
- assert not first_line.startswith("no ")
- assert "found" not in first_line
- assert "activity" in first_line or "history" in first_line
-
-
-async def test_recency_fallback_honours_since_window(store: RecallStore) -> None:
- """The recency fallback must not leak episodes older than the window."""
- await _seed(store, summary="", app="old.exe", minutes_ago=180)
- await _seed(store, summary="", app="fresh.exe", minutes_ago=10)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute(
- {"query": "nomatchkeyword", "since_minutes": 60}, ctx=None,
- )
- assert result.success is True
- assert "fresh.exe" in result.output
- assert "old.exe" not in result.output
-
-
-async def test_truly_empty_window_affirms_store_reachable(store: RecallStore) -> None:
- """No episodes at all → empty message must affirm the store IS reachable.
-
- A bare "nothing found" is what the deep brain mis-read as an outage, so
- the genuinely-empty path states explicitly that the store works.
- """
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "anything"}, ctx=None)
- assert result.success is True
- assert "no activity" in result.output.lower()
- assert "reachable" in result.output.lower()
-
-
-async def test_db_failure_surfaces_honestly_not_silently() -> None:
- """A genuine store/DB error → success=False with an honest error.
-
- It must NOT be swallowed into a success result the brain could narrate
- however it likes — a real outage has to be distinguishable from "empty".
- """
- class _BoomStore:
- async def search_episodes(self, **_kw):
- raise RuntimeError("database is locked")
-
- async def recent_episodes(self, **_kw):
- raise RuntimeError("database is locked")
-
- tool = AwarenessRecallTool(recall_store=_BoomStore())
- result = await tool.execute({"query": "pipeline"}, ctx=None)
- assert result.success is False
- assert result.error is not None
- assert "failed" in result.error.lower()
-
-
-# ---------------------------------------------------------------------------
-# since_minutes filter
-# ---------------------------------------------------------------------------
-
-async def test_since_minutes_drops_old_matches(store: RecallStore) -> None:
- await _seed(store, summary="pipeline ancient", app="code.exe", minutes_ago=180)
- await _seed(store, summary="pipeline recent", app="code.exe", minutes_ago=10)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute(
- {"query": "pipeline", "since_minutes": 60},
- ctx=None,
- )
- assert result.success is True
- assert "pipeline recent" in result.output
- assert "pipeline ancient" not in result.output
-
-
-async def test_default_since_minutes_is_24h(store: RecallStore) -> None:
- """An episode 6h old must be visible without explicit since_minutes."""
- await _seed(store, summary="pipeline somewhere mid-day", app="code.exe", minutes_ago=360)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "pipeline"}, ctx=None)
- assert result.success is True
- assert "pipeline somewhere mid-day" in result.output
-
-
-# ---------------------------------------------------------------------------
-# k cap
-# ---------------------------------------------------------------------------
-
-async def test_k_cap_truncates_results(store: RecallStore) -> None:
- for i in range(5):
- await _seed(store, summary=f"pipeline iteration {i}", app="code.exe", minutes_ago=i + 1)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "pipeline", "k": 2}, ctx=None)
- # The output has one header line plus one line per snippet.
- bullet_lines = [ln for ln in result.output.splitlines() if ln.startswith("- ")]
- assert len(bullet_lines) == 2
-
-
-async def test_k_above_max_is_clamped(store: RecallStore) -> None:
- for i in range(12):
- await _seed(store, summary=f"pipeline iter {i}", app="code.exe", minutes_ago=i + 1)
- tool = AwarenessRecallTool(recall_store=store)
- result = await tool.execute({"query": "pipeline", "k": 9999}, ctx=None)
- bullet_lines = [ln for ln in result.output.splitlines() if ln.startswith("- ")]
- assert len(bullet_lines) <= 10
-
-
-# ---------------------------------------------------------------------------
-# Latency (loose budget, CI-tolerant)
-# ---------------------------------------------------------------------------
-
-async def test_latency_under_loose_budget(store: RecallStore) -> None:
- """100 episodes, search p95 well under 300ms even with disk + asyncio overhead."""
- for i in range(100):
- await _seed(
- store,
- summary=f"pipeline iteration {i} working on something",
- app="code.exe",
- minutes_ago=(i % 1000) + 1,
- )
- tool = AwarenessRecallTool(recall_store=store)
- durations_ms: list[float] = []
- for _ in range(20):
- t0 = time.perf_counter()
- await tool.execute({"query": "pipeline"}, ctx=None)
- durations_ms.append((time.perf_counter() - t0) * 1000)
- durations_ms.sort()
- p95 = durations_ms[int(len(durations_ms) * 0.95)]
- assert p95 < 300.0, f"p95 latency {p95:.2f}ms exceeds 300ms budget"
-
-
-# ---------------------------------------------------------------------------
-# Routing-tier placement
-# ---------------------------------------------------------------------------
-
-def test_in_router_tools() -> None:
- from jarvis.brain import factory
- assert "awareness-recall" in factory.ROUTER_TOOLS
-
-
-def test_not_in_legacy_sub_tools() -> None:
- """Welle 4 removed the sub tier; the legacy frozenset must not exist or
- must not contain awareness-recall if it lingers as a compat shim."""
- from jarvis.brain import factory
- sub_tools = getattr(factory, "SUB_TOOLS", frozenset())
- assert "awareness-recall" not in sub_tools
diff --git a/tests/unit/awareness/test_awareness_snapshot_tool.py b/tests/unit/awareness/test_awareness_snapshot_tool.py
deleted file mode 100644
index b295e1b07d..0000000000
--- a/tests/unit/awareness/test_awareness_snapshot_tool.py
+++ /dev/null
@@ -1,104 +0,0 @@
-"""Tests for jarvis.plugins.tool.awareness_snapshot.AwarenessSnapshotTool.
-
-Binding from plan §5: the tool is SYNCHRONOUS, NO brain call, NO IO.
-Plus two hard negatives:
- 1. Tool MUST be in ROUTER_TOOLS.
- 2. Tool MUST NOT be in SUB_TOOLS (Sub-Jarvis is stateless).
-"""
-from __future__ import annotations
-
-import time
-
-import pytest
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.plugins.tool.awareness_snapshot import AwarenessSnapshotTool
-
-
-def _make_manager_with_frame() -> AwarenessManager:
- manager = AwarenessManager(AwarenessConfig.default())
- manager.state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns(),
- active_window_title="pipeline.py - Visual Studio Code",
- active_process_name="code.exe",
- active_pid=1234,
- is_capture_allowed=True,
- )
- return manager
-
-
-# --- Plan-§5 verbindliche Properties ----------------------------------------
-
-def test_name_is_awareness_snapshot() -> None:
- tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))
- assert tool.name == "awareness-snapshot"
-
-
-def test_risk_tier_is_safe() -> None:
- tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))
- assert tool.risk_tier == "safe"
-
-
-def test_schema_is_empty() -> None:
- """Plan §5: the tool takes no args."""
- tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))
- assert tool.schema == {"type": "object", "properties": {}, "required": []}
-
-
-def test_description_mentions_state_first_use() -> None:
- """Plan §5 description: 'USE this BEFORE asking the user for context'."""
- tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))
- assert "BEFORE" in tool.description
-
-
-# --- Verhalten --------------------------------------------------------------
-
-async def test_returns_synchronously_without_brain_call() -> None:
- """Tool returns immediately — output contains window_title."""
- tool = AwarenessSnapshotTool(manager=_make_manager_with_frame())
- result = await tool.execute({}, ctx=None)
- assert result.success is True
- assert "code.exe" in result.output or "Visual Studio Code" in result.output
-
-
-async def test_returns_empty_string_when_no_frame() -> None:
- """Without current_frame: snapshot_for_prompt returns '' — tool reports success=True."""
- tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))
- result = await tool.execute({}, ctx=None)
- assert result.success is True
- assert result.output == ""
-
-
-async def test_1000_calls_under_50ms_p95() -> None:
- """Plan §5 AC: 1000 calls in <50ms p95."""
- tool = AwarenessSnapshotTool(manager=_make_manager_with_frame())
- durations_ms: list[float] = []
- for _ in range(1000):
- t0 = time.perf_counter()
- await tool.execute({}, ctx=None)
- durations_ms.append((time.perf_counter() - t0) * 1000)
-
- durations_ms.sort()
- p95 = durations_ms[int(len(durations_ms) * 0.95)]
- assert p95 < 50.0, f"p95 latency {p95:.2f}ms exceeds 50ms budget"
-
-
-# --- Hard-Negatives (Plan §5 verbindlich) -----------------------------------
-
-def test_NOT_in_SUB_TOOLS() -> None:
- """Plan §5 hard negative: Sub-Jarvis is stateless — no awareness-snapshot."""
- from jarvis.brain import factory
- sub_tools = getattr(factory, "SUB_TOOLS", frozenset())
- assert "awareness-snapshot" not in sub_tools
-
-
-def test_in_ROUTER_TOOLS() -> None:
- """Plan §5: awareness-snapshot is router-tier only."""
- from jarvis.brain import factory
- router_tools = getattr(factory, "ROUTER_TOOLS", frozenset())
- assert "awareness-snapshot" in router_tools
diff --git a/tests/unit/awareness/test_config.py b/tests/unit/awareness/test_config.py
deleted file mode 100644
index 0da2e1bf50..0000000000
--- a/tests/unit/awareness/test_config.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Tests for jarvis.awareness.config.AwarenessConfig.
-
-A0 scope:
-- The Pydantic model loads with defaults (default() helper).
-- The default blacklist matches the plan §4 wording.
-- Backward compat: jarvis.toml without an [awareness] block loads cleanly.
-- Custom TOML overrides the defaults.
-"""
-from __future__ import annotations
-
-import textwrap
-import tomllib
-
-from jarvis.awareness.config import AwarenessConfig
-
-
-def test_default_loads_clean() -> None:
- """AwarenessConfig.default() with no arguments, no errors."""
- cfg = AwarenessConfig.default()
- assert cfg.enabled is True
- assert cfg.privacy is not None
- assert cfg.watchers is not None
- assert cfg.quotas is not None
-
-
-def test_default_blacklist_matches_plan_section_4() -> None:
- """The default blacklist contains exactly the §4 patterns."""
- cfg = AwarenessConfig.default()
- blocked_procs = cfg.privacy.blocked_processes
- assert "1password*" in blocked_procs
- assert "keepass*" in blocked_procs
- assert "bitwarden*" in blocked_procs
- assert "lastpass*" in blocked_procs
-
- blocked_titles = cfg.privacy.blocked_title_patterns
- for pattern in (
- "*Banking*", "*PayPal*", "*Stripe*Dashboard*",
- "*Sparkasse*", "*Postbank*", "*Online-Banking*",
- "*Passwort*", "*Password*Manager*",
- "*Inkognito*", "*Private Browsing*",
- ):
- assert pattern in blocked_titles, f"plan pattern missing: {pattern}"
-
-
-def test_default_allowed_processes_matches_plan() -> None:
- """The default allowlist contains coding apps from §4."""
- cfg = AwarenessConfig.default()
- for proc in ("code.exe", "cursor.exe", "windsurf.exe",
- "WindowsTerminal.exe", "pwsh.exe", "cmd.exe"):
- assert proc in cfg.privacy.allowed_processes
-
-
-def test_default_when_unknown_is_hybrid() -> None:
- """D-A1 default: hybrid strategy."""
- cfg = AwarenessConfig.default()
- assert cfg.privacy.default_when_unknown == "block_for_browsers_allow_for_others"
-
-
-def test_watchers_defaults_for_a1_forward_compat() -> None:
- """Watchers defaults are defined here, used in A1."""
- cfg = AwarenessConfig.default()
- assert cfg.watchers.enable_window is True
- assert cfg.watchers.enable_idle is True
- assert cfg.watchers.idle_threshold_minutes == 5
-
-
-def test_quotas_defaults() -> None:
- """Quotas defaults: 50 MiB / 1000 episodes."""
- cfg = AwarenessConfig.default()
- assert cfg.quotas.max_bytes == 50 * 1024 * 1024
- assert cfg.quotas.max_episodes == 1000
-
-
-def test_loads_from_toml_overrides_defaults() -> None:
- """Custom TOML overrides defaults field by field."""
- raw = textwrap.dedent("""
- enabled = false
-
- [privacy]
- blocked_processes = ["customapp*"]
- blocked_title_patterns = ["*MyBank*"]
- allowed_processes = ["myeditor.exe"]
- default_when_unknown = "block_for_browsers_allow_for_others"
-
- [watchers]
- enable_window = false
- enable_idle = true
- idle_threshold_minutes = 10
-
- [quotas]
- max_bytes = 1024
- max_episodes = 5
- """).strip()
- data = tomllib.loads(raw)
- cfg = AwarenessConfig(**data)
- assert cfg.enabled is False
- assert cfg.privacy.blocked_processes == ["customapp*"]
- assert cfg.watchers.enable_window is False
- assert cfg.watchers.idle_threshold_minutes == 10
- assert cfg.quotas.max_bytes == 1024
-
-
-def test_partial_toml_keeps_defaults_for_missing_keys() -> None:
- """Backward compat: only some fields set → the rest stays default."""
- data = tomllib.loads('enabled = false\n')
- cfg = AwarenessConfig(**data)
- assert cfg.enabled is False
- # Privacy defaults were NOT changed
- assert "1password*" in cfg.privacy.blocked_processes
diff --git a/tests/unit/awareness/test_context_resolution.py b/tests/unit/awareness/test_context_resolution.py
deleted file mode 100644
index b11e89a664..0000000000
--- a/tests/unit/awareness/test_context_resolution.py
+++ /dev/null
@@ -1,243 +0,0 @@
-"""Unit tests for phase A4 ``resolve_context`` (jarvis/awareness/context.py).
-
-Spec: JARVIS_AWARENESS_PLAN.md §8 heuristic order.
-
-Tests:
-- IDE_SET (code.exe / cursor.exe / windsurf.exe) → cwd via psutil.
-- Browser (chrome.exe / msedge.exe) → hostname from the window title.
-- Terminal (WindowsTerminal.exe / pwsh.exe) → cwd via psutil.
-- Fallback for an unknown process → process_name.
-- task_label = first 5 words of the title.
-- Lazy import of psutil + fail-silent on psutil failures.
-"""
-from __future__ import annotations
-
-from unittest.mock import patch
-
-from jarvis.awareness.context import (
- BROWSER_SET,
- IDE_SET,
- TERMINAL_SET,
- Context,
- _hostname_from_title,
- _short_label,
- resolve_context,
-)
-from jarvis.awareness.state import FrameSnapshot
-
-
-def _frame(
- *, title: str = "main.py", process: str = "code.exe", pid: int = 1234,
-) -> FrameSnapshot:
- return FrameSnapshot(
- timestamp_ns=1_000_000_000,
- active_window_title=title,
- active_process_name=process,
- active_pid=pid,
- is_capture_allowed=True,
- )
-
-
-# ---- Heuristic tables -------------------------------------------------------
-
-
-def test_ide_set_contains_known_editors() -> None:
- assert "code.exe" in IDE_SET
- assert "cursor.exe" in IDE_SET
- assert "windsurf.exe" in IDE_SET
-
-
-def test_browser_set_contains_known_browsers() -> None:
- assert "chrome.exe" in BROWSER_SET
- assert "firefox.exe" in BROWSER_SET
- assert "msedge.exe" in BROWSER_SET
-
-
-def test_terminal_set_contains_known_shells() -> None:
- assert "WindowsTerminal.exe" in TERMINAL_SET
- assert "pwsh.exe" in TERMINAL_SET
- assert "cmd.exe" in TERMINAL_SET
-
-
-# ---- IDE pathway -----------------------------------------------------------
-
-
-def test_ide_resolves_cwd_via_psutil() -> None:
- """code.exe → cwd via psutil.Process.cwd()."""
- with patch("jarvis.awareness.context._safe_cwd", return_value="C:\\repo\\jarvis"):
- ctx = resolve_context(_frame(process="code.exe", title="main.py - VS Code"))
- assert isinstance(ctx, Context)
- assert ctx.project_root == "C:\\repo\\jarvis"
- assert ctx.process_name == "code.exe"
-
-
-def test_ide_falls_back_to_process_name_when_cwd_fails() -> None:
- """psutil failure → fallback to process_name."""
- with patch("jarvis.awareness.context._safe_cwd", return_value=None):
- ctx = resolve_context(_frame(process="code.exe"))
- assert ctx.project_root == "code.exe"
-
-
-# ---- Browser pathway -------------------------------------------------------
-
-
-def test_browser_resolves_url_to_hostname() -> None:
- ctx = resolve_context(_frame(
- process="chrome.exe",
- title="https://github.com/anthropic/claude — Google Chrome",
- ))
- assert ctx.project_root == "github.com"
-
-
-def test_browser_resolves_domain_in_title() -> None:
- ctx = resolve_context(_frame(
- process="firefox.exe",
- title="GitHub - example.com - Mozilla Firefox",
- ))
- assert ctx.project_root == "example.com"
-
-
-def test_browser_falls_back_when_no_url_in_title() -> None:
- """Title without a domain → fallback to process_name."""
- ctx = resolve_context(_frame(
- process="chrome.exe",
- title="Stack Overflow - Google Chrome",
- ))
- assert ctx.project_root == "chrome.exe"
-
-
-# ---- Terminal pathway ------------------------------------------------------
-
-
-def test_terminal_resolves_cwd_via_psutil() -> None:
- with patch("jarvis.awareness.context._safe_cwd", return_value="C:\\workspace"):
- ctx = resolve_context(_frame(
- process="pwsh.exe",
- title="Windows PowerShell",
- ))
- assert ctx.project_root == "C:\\workspace"
-
-
-def test_terminal_falls_back_when_cwd_fails() -> None:
- with patch("jarvis.awareness.context._safe_cwd", return_value=None):
- ctx = resolve_context(_frame(process="WindowsTerminal.exe"))
- assert ctx.project_root == "WindowsTerminal.exe"
-
-
-# ---- Fallback pathway ------------------------------------------------------
-
-
-def test_unknown_process_falls_back_to_process_name() -> None:
- """Unknown process: process_name is the fallback identity key."""
- ctx = resolve_context(_frame(
- process="random_app.exe",
- title="Random App Window",
- ))
- assert ctx.project_root == "random_app.exe"
-
-
-def test_empty_process_name_uses_unknown_sentinel() -> None:
- ctx = resolve_context(_frame(process="", title="Some Window"))
- assert ctx.project_root == "unknown"
-
-
-# ---- task_label -----------------------------------------------------------
-
-
-def test_task_label_truncated_to_five_words() -> None:
- """Plan §8: first 5 words of the window title."""
- ctx = resolve_context(_frame(
- process="random_app.exe",
- title="word1 word2 word3 word4 word5 word6 word7",
- ))
- assert ctx.task_label == "word1 word2 word3 word4 word5"
-
-
-def test_task_label_short_title_kept_as_is() -> None:
- ctx = resolve_context(_frame(
- process="random_app.exe",
- title="short title",
- ))
- assert ctx.task_label == "short title"
-
-
-def test_short_label_helper_max_words_param() -> None:
- assert _short_label("a b c d e f", max_words=3) == "a b c"
- assert _short_label("", max_words=5) == ""
- assert _short_label("only-one") == "only-one"
-
-
-# ---- Hostname parser unit-tests ------------------------------------------
-
-
-def test_hostname_from_title_extracts_https_url() -> None:
- assert _hostname_from_title("https://example.com/foo") == "example.com"
-
-
-def test_hostname_from_title_extracts_domain() -> None:
- assert _hostname_from_title("Some title with example.com - Brave") == "example.com"
-
-
-def test_hostname_from_title_strips_browser_suffix() -> None:
- """A browser suffix must not be interpreted as a domain."""
- assert _hostname_from_title("Login - Mozilla Firefox") is None
-
-
-def test_hostname_from_title_returns_none_for_no_domain() -> None:
- assert _hostname_from_title("Just plain text") is None
- assert _hostname_from_title("") is None
-
-
-# ---- psutil Lazy-Import & Fail-Silent -------------------------------------
-
-
-def test_safe_cwd_returns_none_on_invalid_pid() -> None:
- """pid <= 0 → None without a psutil call."""
- from jarvis.awareness.context import _safe_cwd
-
- assert _safe_cwd(0) is None
- assert _safe_cwd(-1) is None
-
-
-def test_safe_cwd_returns_none_on_psutil_exception() -> None:
- """psutil.Process raises (NoSuchProcess, AccessDenied, OSError, ...)
- → fallback to None without a crash.
- """
- from jarvis.awareness.context import _safe_cwd
-
- # Patch the psutil module lazy import via sys.modules. If psutil is
- # not installed, the except also swallows ImportError.
- with patch("jarvis.awareness.context._safe_cwd", wraps=_safe_cwd):
- # Direct call — _safe_cwd has its own try/except; we simulate
- # via patched psutil module raising an exception.
- try:
- import psutil # noqa: PLC0415
-
- with patch.object(psutil, "Process") as mock_proc:
- mock_proc.side_effect = RuntimeError("nope")
- assert _safe_cwd(99999) is None
- except ImportError:
- # psutil not installed → _safe_cwd returns None via except ImportError
- assert _safe_cwd(99999) is None
-
-
-# ---- Integration: A→B→A Werkzeug-Roundtrip -------------------------------
-
-
-def test_a_then_b_then_a_yields_distinct_then_resumed_contexts() -> None:
- """Plan §8 acceptance: switching A→B→A returns A's episode snippet,
- not B's. Here only the resolver side: A and B get distinct
- project_roots, A re-resolved gives back the same A.
- """
- with patch("jarvis.awareness.context._safe_cwd",
- side_effect=["C:\\a", "C:\\b", "C:\\a"]):
- a_first = resolve_context(_frame(process="code.exe", title="a.py"))
- b = resolve_context(_frame(process="code.exe", title="b.py"))
- a_again = resolve_context(_frame(process="code.exe", title="a.py - again"))
-
- assert a_first.project_root == "C:\\a"
- assert b.project_root == "C:\\b"
- assert a_again.project_root == "C:\\a"
- # task_label from the second A is different → the resolver stays deterministic
- # against a title change.
- assert a_again.task_label == "a.py - again"
diff --git a/tests/unit/awareness/test_episode.py b/tests/unit/awareness/test_episode.py
deleted file mode 100644
index 1b139bcc66..0000000000
--- a/tests/unit/awareness/test_episode.py
+++ /dev/null
@@ -1,268 +0,0 @@
-"""Tests for jarvis.awareness.episode — Episode + EpisodeBuilder.
-
-Spec: plan §6 + TASKS.md "Slice B".
-"""
-from __future__ import annotations
-
-import dataclasses
-import time
-
-import pytest
-
-from jarvis.awareness.episode import Episode, EpisodeBuilder
-from jarvis.awareness.state import FrameSnapshot
-
-
-def _make_frame(
- *,
- process: str = "code.exe",
- title: str = "main.py",
- pid: int = 1000,
- timestamp_ns: int = 1_000_000_000,
-) -> FrameSnapshot:
- """Convenient constructor — sensible defaults."""
- return FrameSnapshot(
- timestamp_ns=timestamp_ns,
- active_window_title=title,
- active_process_name=process,
- active_pid=pid,
- is_capture_allowed=True,
- )
-
-
-# --- Episode (frozen) -------------------------------------------------------
-
-def test_episode_is_frozen() -> None:
- """Episode is frozen — no re-assignment possible."""
- ep = Episode(
- started_at_ns=1,
- ended_at_ns=2,
- trigger_kind="window_switch",
- summary="hello",
- frame_count=3,
- primary_app="code.exe",
- )
- with pytest.raises(dataclasses.FrozenInstanceError):
- ep.summary = "x" # type: ignore[misc]
-
-
-def test_episode_has_slots() -> None:
- """slots=True ⇒ no __dict__."""
- ep = Episode(
- started_at_ns=1,
- ended_at_ns=2,
- trigger_kind="idle",
- summary="x",
- frame_count=0,
- primary_app="",
- )
- with pytest.raises(AttributeError):
- ep.__dict__ # noqa: B018
-
-
-def test_episode_token_defaults_zero() -> None:
- """tokens_in / tokens_out default to 0 (empty episode or timeout)."""
- ep = Episode(
- started_at_ns=1,
- ended_at_ns=2,
- trigger_kind="x",
- summary="",
- frame_count=0,
- primary_app="",
- )
- assert ep.tokens_in == 0
- assert ep.tokens_out == 0
-
-
-# --- EpisodeBuilder lifecycle ----------------------------------------------
-
-def test_builder_starts_empty() -> None:
- """A fresh builder has no frames/events."""
- builder = EpisodeBuilder(started_at_ns=1)
-
- assert builder.frame_count == 0
- assert builder.frames == []
- assert builder.events == []
- assert builder.is_empty() is True
-
-
-def test_add_frame_increments_count() -> None:
- """add_frame() bumps frame_count and is visible in the frames property."""
- builder = EpisodeBuilder(started_at_ns=1)
- frame = _make_frame()
-
- builder.add_frame(frame, salience=42)
-
- assert builder.frame_count == 1
- assert builder.frames == [frame]
- assert builder.is_empty() is False
-
-
-def test_add_event_makes_builder_non_empty() -> None:
- """An event alone is enough ⇒ is_empty=False."""
- builder = EpisodeBuilder(started_at_ns=1)
-
- builder.add_event("FileSaved", salience=40, payload={"path": "foo.py"})
-
- assert builder.frame_count == 0
- assert builder.is_empty() is False
- events = builder.events
- assert len(events) == 1
- assert events[0]["kind"] == "FileSaved"
- assert events[0]["salience"] == 40
- assert events[0]["payload"] == {"path": "foo.py"}
- assert "ts_ns" in events[0]
-
-
-def test_events_returns_independent_copy() -> None:
- """builder.events returns a copy — mutation must not affect the
- builder."""
- builder = EpisodeBuilder(started_at_ns=1)
- builder.add_event("FileSaved", salience=40, payload={"path": "x.py"})
-
- snap1 = builder.events
- snap1.clear() # mutate top-level list
- snap1_again = builder.events
- assert len(snap1_again) == 1 # builder unaffected
-
- # Is the payload dict also a copy? (defensive)
- snap2 = builder.events
- snap2[0]["payload"]["new_key"] = "leaked"
- snap3 = builder.events
- assert "new_key" not in snap3[0]["payload"]
-
-
-def test_frames_returns_independent_copy() -> None:
- """builder.frames returns a copy of the list."""
- builder = EpisodeBuilder(started_at_ns=1)
- builder.add_frame(_make_frame(), salience=50)
-
- snap = builder.frames
- snap.clear()
- assert builder.frame_count == 1 # builder unaffected
-
-
-# --- primary_app -----------------------------------------------------------
-
-def test_primary_app_empty_builder() -> None:
- """Empty builder ⇒ empty string."""
- builder = EpisodeBuilder(started_at_ns=1)
- assert builder.primary_app == ""
-
-
-def test_primary_app_single_frame() -> None:
- """With only 1 frame: its process_name (dwell is 0)."""
- builder = EpisodeBuilder(started_at_ns=1)
- builder.add_frame(_make_frame(process="notepad.exe"), salience=50)
-
- assert builder.primary_app == "notepad.exe"
-
-
-def test_primary_app_most_dwelltime() -> None:
- """3 frames: Notepad 5s → Code 30s → Notepad 10s ⇒ 'code.exe' wins
- (largest cumulative dwell time)."""
- builder = EpisodeBuilder(started_at_ns=0)
-
- # t=0: Notepad starts
- builder.add_frame(
- _make_frame(process="notepad.exe", timestamp_ns=0), salience=30,
- )
- # t=5s: Code starts ⇒ Notepad dwell = 5s
- builder.add_frame(
- _make_frame(process="code.exe", timestamp_ns=5_000_000_000), salience=50,
- )
- # t=35s: Notepad starts again ⇒ Code dwell = 30s
- builder.add_frame(
- _make_frame(process="notepad.exe", timestamp_ns=35_000_000_000), salience=50,
- )
- # t=45s: last frame (contributes 0) ⇒ Notepad dwell +10s additionally
- # WAIT: per spec, dwell is computed between consecutive frames,
- # the last one contributes 0. So Notepad totals 5+10=15s,
- # Code 30s ⇒ Code wins.
- builder.add_frame(
- _make_frame(process="notepad.exe", timestamp_ns=45_000_000_000), salience=30,
- )
-
- assert builder.primary_app == "code.exe"
-
-
-def test_primary_app_tie_first_wins() -> None:
- """On a tie, the first-inserted process wins
- (insertion order)."""
- builder = EpisodeBuilder(started_at_ns=0)
-
- # Notepad: 10s, Code: 10s ⇒ tie ⇒ Notepad (inserted first) wins.
- builder.add_frame(
- _make_frame(process="notepad.exe", timestamp_ns=0), salience=30,
- )
- builder.add_frame(
- _make_frame(process="code.exe", timestamp_ns=10_000_000_000), salience=30,
- )
- builder.add_frame(
- _make_frame(process="other.exe", timestamp_ns=20_000_000_000), salience=30,
- )
-
- assert builder.primary_app == "notepad.exe"
-
-
-# --- build() ----------------------------------------------------------------
-
-def test_build_returns_immutable_episode() -> None:
- """build() returns a frozen Episode — mutation crashes."""
- builder = EpisodeBuilder(started_at_ns=1_000)
- builder.add_frame(_make_frame(), salience=50)
-
- episode = builder.build(ended_at_ns=2_000, summary="test")
-
- with pytest.raises(dataclasses.FrozenInstanceError):
- episode.summary = "x" # type: ignore[misc]
-
-
-def test_build_preserves_all_fields() -> None:
- """All 8 fields land correctly in the Episode."""
- builder = EpisodeBuilder(started_at_ns=100)
- builder.add_frame(
- _make_frame(process="code.exe", timestamp_ns=100), salience=50,
- )
- builder.add_frame(
- _make_frame(process="code.exe", timestamp_ns=200), salience=40,
- )
-
- episode = builder.build(
- ended_at_ns=999,
- summary="You worked in code.exe.",
- tokens_in=123,
- tokens_out=45,
- )
-
- assert episode.started_at_ns == 100
- assert episode.ended_at_ns == 999
- assert episode.summary == "You worked in code.exe."
- assert episode.frame_count == 2
- assert episode.primary_app == "code.exe"
- assert episode.tokens_in == 123
- assert episode.tokens_out == 45
- # trigger_kind is set by the caller (StoryTracker) — the builder doesn't
- # know it and returns the sentinel default empty string here.
- assert episode.trigger_kind == ""
-
-
-def test_build_token_defaults_zero() -> None:
- """build() without tokens_* ⇒ 0 in the Episode (empty/timeout path)."""
- builder = EpisodeBuilder(started_at_ns=1)
- episode = builder.build(ended_at_ns=2, summary="")
- assert episode.tokens_in == 0
- assert episode.tokens_out == 0
-
-
-# --- duration_ns ------------------------------------------------------------
-
-def test_duration_ns_is_plausible() -> None:
- """duration_ns = time.time_ns() - started_at_ns — positive and plausible."""
- started = time.time_ns() - 5_000_000_000 # 5s in the past
- builder = EpisodeBuilder(started_at_ns=started)
-
- duration = builder.duration_ns
-
- # >= 5s, but < 10s (test runs fast).
- assert 5_000_000_000 <= duration < 10_000_000_000
diff --git a/tests/unit/awareness/test_episode_persistence.py b/tests/unit/awareness/test_episode_persistence.py
deleted file mode 100644
index d2b06981c4..0000000000
--- a/tests/unit/awareness/test_episode_persistence.py
+++ /dev/null
@@ -1,370 +0,0 @@
-"""Unit tests for the awareness L2 persistence (phase A2 slice A, plan §6).
-
-Covers schema.sql idempotency, FTS5 trigger sync, round-trip consistency, and
-the ORDER/LIMIT behavior of `record_frame`, `record_episode`, `recent_episodes`
-and `search_episodes`.
-
-Plus: B2 atomic-buffer regression (Codex BLOCKER B2 fix, 2026-05-11).
-Verifies end-to-end via the StoryTracker with a real ``RecallStore``,
-that a frame pushed WHILE a flush is in progress lands in the NEXT
-episode, not the current one, and is never lost.
-"""
-from __future__ import annotations
-
-import asyncio
-import time
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-import pytest_asyncio
-
-from jarvis.awareness.config import AwarenessConfig, AwarenessStoryConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.awareness.story import StoryTracker
-from jarvis.core.bus import EventBus
-from jarvis.core.events import FrameUpdated, IdleEntered
-from jarvis.memory import RecallStore
-
-
-@pytest_asyncio.fixture
-async def tmp_db_path(tmp_path: Path) -> Path:
- """Per-test isolated DB path — avoids cross-test bleed."""
- return tmp_path / "awareness.db"
-
-
-@pytest_asyncio.fixture
-async def recall_store(tmp_db_path: Path):
- """RecallStore async context manager as a fixture (open + close)."""
- store = RecallStore(tmp_db_path)
- await store.open()
- yield store
- await store.close()
-
-
-async def test_schema_idempotent(tmp_db_path: Path) -> None:
- """Calling `open()` twice in a row must not crash — the IF NOT EXISTS guarantee.
-
- Simulates an app restart: the DB already exists with all tables, a
- repeated `executescript(schema.sql)` must not disturb the existing
- data and definitions.
- """
- store_a = RecallStore(tmp_db_path)
- await store_a.open()
- await store_a.record_episode(
- started_at_ns=1_000_000_000,
- ended_at_ns=2_000_000_000,
- trigger_kind="window_switch",
- summary="initial",
- frame_count=1,
- primary_app="vscode.exe",
- )
- await store_a.close()
-
- # Second open() — no exception, data is preserved.
- store_b = RecallStore(tmp_db_path)
- await store_b.open()
- rows = await store_b.recent_episodes(limit=10)
- assert len(rows) == 1
- assert rows[0]["summary"] == "initial"
- await store_b.close()
-
-
-async def test_record_episode_returns_id(recall_store: RecallStore) -> None:
- """`record_episode` returns a positive integer rowid."""
- episode_id = await recall_store.record_episode(
- started_at_ns=1_000_000_000,
- ended_at_ns=1_500_000_000,
- trigger_kind="window_switch",
- summary="You are working on pipeline.py in VS Code.",
- frame_count=12,
- primary_app="Code.exe",
- )
- assert isinstance(episode_id, int)
- assert episode_id > 0
-
-
-async def test_recent_episodes_descending(recall_store: RecallStore) -> None:
- """`recent_episodes(limit=2)` returns the 2 newest in DESC order."""
- base_ns = 1_000_000_000_000
- # Three episodes with ascending start time
- for i in range(3):
- await recall_store.record_episode(
- started_at_ns=base_ns + i * 1_000_000_000,
- ended_at_ns=base_ns + i * 1_000_000_000 + 500_000_000,
- trigger_kind="window_switch",
- summary=f"episode-{i}",
- frame_count=5,
- primary_app="Code.exe",
- )
-
- rows = await recall_store.recent_episodes(limit=2)
- assert len(rows) == 2
- # Newest first → index 2, then 1
- assert rows[0]["summary"] == "episode-2"
- assert rows[1]["summary"] == "episode-1"
- assert rows[0]["started_at_ns"] > rows[1]["started_at_ns"]
-
-
-async def test_recent_episodes_since_ns_filter(recall_store: RecallStore) -> None:
- """`since_ns=mid` filters on a >= comparison → only 2 of 3 episodes."""
- base_ns = 1_000_000_000_000
- timestamps = [base_ns, base_ns + 1_000_000_000, base_ns + 2_000_000_000]
- for i, ts in enumerate(timestamps):
- await recall_store.record_episode(
- started_at_ns=ts,
- ended_at_ns=ts + 100_000_000,
- trigger_kind="timer",
- summary=f"ep-{i}",
- frame_count=1,
- primary_app="x.exe",
- )
-
- # since=middle timestamp → ep-1 and ep-2 (>= mid)
- rows = await recall_store.recent_episodes(limit=10, since_ns=timestamps[1])
- assert len(rows) == 2
- summaries = {r["summary"] for r in rows}
- assert summaries == {"ep-1", "ep-2"}
-
-
-async def test_search_episodes_fts_match(recall_store: RecallStore) -> None:
- """FTS5 MATCH over the summary hits only the matching episode."""
- await recall_store.record_episode(
- started_at_ns=1_000_000_000,
- ended_at_ns=1_500_000_000,
- trigger_kind="window_switch",
- summary="Python coding session in VS Code with tests",
- frame_count=20,
- primary_app="Code.exe",
- )
- await recall_store.record_episode(
- started_at_ns=2_000_000_000,
- ended_at_ns=2_500_000_000,
- trigger_kind="idle_entered",
- summary="Cooking dinner break, browser on a recipe page",
- frame_count=8,
- primary_app="firefox.exe",
- )
-
- rows = await recall_store.search_episodes(query="Python", limit=10)
- assert len(rows) == 1
- assert "Python" in rows[0]["summary"]
- assert rows[0]["primary_app"] == "Code.exe"
-
-
-async def test_record_frame_persists(recall_store: RecallStore) -> None:
- """`record_frame` writes the row and the data can be read back directly."""
- frame_id = await recall_store.record_frame(
- window_title="pipeline.py - Visual Studio Code",
- process_name="Code.exe",
- timestamp_ns=1_234_567_890_000,
- salience_score=75,
- metadata={"git_branch": "awareness/phase-a2", "lines": 250},
- )
- assert isinstance(frame_id, int)
- assert frame_id > 0
-
- conn = recall_store._require_conn()
- cur = await conn.execute(
- "SELECT * FROM awareness_frames WHERE id = ?",
- (frame_id,),
- )
- row = await cur.fetchone()
- await cur.close()
- assert row is not None
- assert row["window_title"] == "pipeline.py - Visual Studio Code"
- assert row["process_name"] == "Code.exe"
- assert row["timestamp_ns"] == 1_234_567_890_000
- assert row["salience_score"] == 75
- # metadata_json is JSON-encoded
- import json
- meta = json.loads(row["metadata_json"])
- assert meta == {"git_branch": "awareness/phase-a2", "lines": 250}
-
-
-# ----------------------------------------------------------------------------
-# B2 atomic-buffer regression (Codex BLOCKER, 2026-05-11)
-# ----------------------------------------------------------------------------
-#
-# Before (bug): EpisodeBuilder accumulated frames in a shared
-# list; with a concurrent flush + a new FrameUpdated, a frame could be lost
-# between the snapshot and the buffer reset.
-# After (fix): EpisodeBuilder.detach_frames/detach_events atomically swap the
-# internal lists for fresh buckets; StoryTracker._extract_snapshot_locked
-# uses these, then sets _builder=None. A concurrent on_frame_updated only
-# gets the lock after the snapshot — and sees builder=None, which leads to
-# a fresh builder for the next frame.
-#
-# Test setup: StoryTracker + a real RecallStore + a slow verdichter that
-# blocks for 300ms. Frame 1 before the flush, frame 2 WHILE the verdichter
-# sleeps. AC: episode 1 contains frame 1, frame 2 lives in the new builder;
-# after stop(), episode 2 is persisted with frame 2. No frame disappears.
-
-
-@dataclass
-class _SlowB2Verdichter:
- """Verdichter fake for the B2 test — sleeps for ``sleep_s`` during
- ``call`` and returns a unique summary so the persisted episodes can be
- unambiguously matched in the test assertions.
- """
- sleep_s: float = 0.3
- calls: list[dict[str, Any]] = field(default_factory=list)
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- self.calls.append({
- "frames_n": len(frames),
- "primary_app": primary_app,
- "titles": [f.get("window_title") for f in frames],
- })
- await asyncio.sleep(self.sleep_s)
- summary = f"summary-{len(self.calls)}"
- return summary, {"tokens_in": 1, "tokens_out": 1, "duration_ms": 0}
-
-
-def _make_frame_for_b2(
- *,
- title: str,
- process: str = "Code.exe",
- ts_ns: int | None = None,
-) -> FrameSnapshot:
- """Helper — minimal FrameSnapshot for the B2 test."""
- return FrameSnapshot(
- timestamp_ns=ts_ns if ts_ns is not None else time.time_ns(),
- active_window_title=title,
- active_process_name=process,
- active_pid=1000,
- is_capture_allowed=True,
- )
-
-
-async def test_frame_during_flush_lands_in_next_episode_buffer(
- tmp_db_path: Path,
-) -> None:
- """B2 AC: a frame enqueued WHILE the flush is running lands in the
- NEXT episode buffer — not lost, not in the current snapshot.
-
- End-to-end with a real ``RecallStore``. Verifies the full
- persistence chain:
- 1. Frame F1 (``frame-1.py``) opens the builder.
- 2. ``IdleEntered`` triggers a flush; the verdichter sleeps 300ms.
- 3. WHILE the verdichter sleeps, F2 (``frame-2.py``) is pushed.
- 4. Expected:
- - The verdichter call sees ONLY F1 (1 frame).
- - The live builder at the end of the push contains F2.
- - After verdichter completion: episode 1 in the DB with summary ``summary-1``.
- - After ``stop()``: episode 2 in the DB with summary ``summary-2``.
- - No frame is in both episodes, none disappears.
- """
- store = RecallStore(tmp_db_path)
- await store.open()
- try:
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- verdichter = _SlowB2Verdichter(sleep_s=0.3)
- tracker = StoryTracker(
- manager=manager,
- bus=bus,
- recall=store,
- verdichter=verdichter, # type: ignore[arg-type]
- config=AwarenessStoryConfig(episode_min_duration_s=1),
- )
- await tracker.start()
-
- try:
- # F1 before the flush — opens the builder.
- f1 = _make_frame_for_b2(title="frame-1.py", ts_ns=time.time_ns())
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1) # cross min_duration
-
- # Idle triggers a flush in its own task — the verdichter sleeps 300ms.
- flush_task = asyncio.create_task(tracker._on_idle_entered(
- IdleEntered(idle_since_ns=time.time_ns()),
- ))
- # Wait until verdichter has actually entered its sleep.
- for _ in range(100):
- await asyncio.sleep(0)
- if verdichter.calls:
- break
- assert verdichter.calls, (
- "Pre-condition: verdichter must be mid-flight"
- )
-
- # F2 WHILE the verdichter sleeps. B2 fix: must go into the NEW
- # builder, NOT into the already snapshotted buffer, and must
- # not be lost.
- f2 = _make_frame_for_b2(title="frame-2.py", ts_ns=time.time_ns())
- manager.state.current_frame = f2
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f2.active_window_title,
- process_name=f2.active_process_name,
- pid=f2.active_pid, is_capture_allowed=True,
- ))
-
- # The verdichter saw only F1.
- assert verdichter.calls[0]["frames_n"] == 1
- assert verdichter.calls[0]["titles"] == ["frame-1.py"]
-
- # F2 lives in the new builder.
- assert tracker._builder is not None
- live_titles = [
- f.active_window_title for f in tracker._builder.frames
- ]
- assert "frame-2.py" in live_titles, (
- f"B2-Regression: frame-2.py disappeared. Live builder "
- f"has {live_titles!r}"
- )
-
- # Wait out the verdichter sleep, episode 1 is persisted.
- await asyncio.wait_for(flush_task, timeout=2.0)
- finally:
- # Force-flush the remaining builder via the stop() trigger.
- await tracker.stop()
-
- # Two episodes persisted: episode 1 (idle, F1), episode 2 (stop, F2).
- rows = await store.recent_episodes(limit=10)
- assert len(rows) == 2, (
- f"B2 AC: expected 2 persisted episodes, found "
- f"{len(rows)} — did frame F2 get lost?"
- )
- # recent_episodes is DESC by started_at_ns → [F2 episode, F1 episode]
- assert rows[0]["summary"] == "summary-2"
- assert rows[0]["trigger_kind"] == "stop"
- assert rows[0]["frame_count"] == 1
- assert rows[1]["summary"] == "summary-1"
- assert rows[1]["trigger_kind"] == "idle_entered"
- assert rows[1]["frame_count"] == 1
- finally:
- await store.close()
-
-
-async def test_record_episode_round_trip(recall_store: RecallStore) -> None:
- """All 8 fields of `record_episode` land 1:1 in `recent_episodes`."""
- payload = {
- "started_at_ns": 5_000_000_000,
- "ended_at_ns": 5_900_000_000,
- "trigger_kind": "brain_turn",
- "summary": "Round-trip test with all fields.",
- "frame_count": 17,
- "primary_app": "wezterm-gui.exe",
- "tokens_in": 642,
- "tokens_out": 158,
- }
- await recall_store.record_episode(**payload)
-
- rows = await recall_store.recent_episodes(limit=1)
- assert len(rows) == 1
- row = rows[0]
- for key, expected in payload.items():
- assert row[key] == expected, f"field {key} not preserved: {row[key]!r} != {expected!r}"
diff --git a/tests/unit/awareness/test_filesystem_probe.py b/tests/unit/awareness/test_filesystem_probe.py
deleted file mode 100644
index 44f8e9860c..0000000000
--- a/tests/unit/awareness/test_filesystem_probe.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Phase A5 slice B — FileSystemProbe tests.
-
-With a real watchdog against tmp_path (fakes instead of mocks). Real FS events
-with a short sleep window for watchdog latency.
-"""
-from __future__ import annotations
-
-import asyncio
-import time
-from pathlib import Path
-
-from jarvis.awareness.probes.filesystem import (
- _MAX_WATCHED_ROOTS,
- FileSystemProbe,
-)
-from jarvis.core.bus import EventBus
-from jarvis.core.events import FileSaved
-
-# --- Helper ---
-
-async def _wait_for_event(
- events: list[FileSaved],
- n: int = 1,
- timeout: float = 2.0, # noqa: ASYNC109 - intentional per-test polling window
-) -> None:
- """Polls until events.length >= n or timeout.
-
- ASYNC109: the timeout parameter is intentional here — the test helper needs
- a configurable polling window per test case, not asyncio.timeout cancellation.
- """
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- if len(events) >= n:
- return
- await asyncio.sleep(0.05)
-
-
-# --- Tests ---
-
-async def test_probe_with_none_cwd_returns_none() -> None:
- bus = EventBus()
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- result = await p.probe(cwd=None)
- assert result == {"open_file_hint": None}
- finally:
- await p.stop()
-
-
-async def test_probe_with_unwatched_cwd_returns_none(tmp_path: Path) -> None:
- bus = EventBus()
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- result = await p.probe(cwd=str(tmp_path))
- assert result == {"open_file_hint": None}
- finally:
- await p.stop()
-
-
-async def test_watch_then_save_emits_filesaved_event(tmp_path: Path) -> None:
- bus = EventBus()
- received: list[FileSaved] = []
-
- async def collect(ev: FileSaved) -> None:
- received.append(ev)
- bus.subscribe(FileSaved, collect)
-
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- ok = p.watch(str(tmp_path))
- assert ok is True
- # File write triggers an event
- await asyncio.sleep(0.1) # watchdog init window
- (tmp_path / "test.py").write_text("print('hello')")
- await _wait_for_event(received, n=1, timeout=3.0)
- assert len(received) >= 1
- assert any("test.py" in ev.path for ev in received)
- finally:
- await p.stop()
-
-
-async def test_debounce_collapses_rapid_saves(tmp_path: Path) -> None:
- bus = EventBus()
- received: list[FileSaved] = []
-
- async def collect(ev: FileSaved) -> None:
- received.append(ev)
- bus.subscribe(FileSaved, collect)
-
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- p.watch(str(tmp_path))
- await asyncio.sleep(0.1)
- f = tmp_path / "rapid.py"
- # 5 rapid writes within 100ms — debounce (200ms) should drop all but 1
- for _ in range(5):
- f.write_text("x")
- await asyncio.sleep(0.01)
- await asyncio.sleep(0.5) # wait for the debounce window to elapse
- # Expectation: max 2 events (1 for the first save + possibly 1 after the debounce window)
- rapid_events = [e for e in received if "rapid.py" in e.path]
- assert len(rapid_events) <= 2
- finally:
- await p.stop()
-
-
-async def test_blacklist_skips_git_directory(tmp_path: Path) -> None:
- bus = EventBus()
- received: list[FileSaved] = []
-
- async def collect(ev: FileSaved) -> None:
- received.append(ev)
- bus.subscribe(FileSaved, collect)
-
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- p.watch(str(tmp_path))
- await asyncio.sleep(0.1)
- (tmp_path / ".git").mkdir(exist_ok=True)
- (tmp_path / ".git" / "ignored.txt").write_text("x")
- (tmp_path / "real_file.py").write_text("real")
- await _wait_for_event(received, n=1, timeout=2.0)
- # Only real_file.py, NOT ignored.txt
- paths = [e.path for e in received]
- assert any("real_file.py" in p for p in paths)
- assert not any(".git" in p and "ignored.txt" in p for p in paths)
- finally:
- await p.stop()
-
-
-async def test_unwatch_stops_events(tmp_path: Path) -> None:
- bus = EventBus()
- received: list[FileSaved] = []
-
- async def collect(ev: FileSaved) -> None:
- received.append(ev)
- bus.subscribe(FileSaved, collect)
-
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- p.watch(str(tmp_path))
- await asyncio.sleep(0.1)
- p.unwatch(str(tmp_path))
- await asyncio.sleep(0.1)
- (tmp_path / "should_not_emit.py").write_text("x")
- await asyncio.sleep(0.5)
- # No events for should_not_emit.py
- paths = [e.path for e in received]
- assert not any("should_not_emit.py" in p for p in paths)
- finally:
- await p.stop()
-
-
-async def test_max_watched_roots_cap(tmp_path: Path) -> None:
- bus = EventBus()
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- # Create MAX+1 directories and try to watch all of them
- for i in range(_MAX_WATCHED_ROOTS):
- d = tmp_path / f"root_{i}"
- d.mkdir()
- assert p.watch(str(d)) is True
- # Cap+1 must return False
- d_extra = tmp_path / "root_extra"
- d_extra.mkdir()
- assert p.watch(str(d_extra)) is False
- finally:
- await p.stop()
-
-
-async def test_probe_returns_latest_save_in_root(tmp_path: Path) -> None:
- bus = EventBus()
- p = FileSystemProbe(bus=bus)
- await p.start()
- try:
- p.watch(str(tmp_path))
- await asyncio.sleep(0.1)
- (tmp_path / "first.py").write_text("a")
- await asyncio.sleep(0.3)
- (tmp_path / "second.py").write_text("b")
- await asyncio.sleep(0.3)
- result = await p.probe(cwd=str(tmp_path))
- assert result["open_file_hint"] is not None
- assert "second.py" in result["open_file_hint"]
- finally:
- await p.stop()
-
-
-async def test_stop_idempotent(tmp_path: Path) -> None:
- bus = EventBus()
- p = FileSystemProbe(bus=bus)
- await p.start()
- await p.stop()
- await p.stop() # second call must not raise
diff --git a/tests/unit/awareness/test_git_probe.py b/tests/unit/awareness/test_git_probe.py
deleted file mode 100644
index 8ad17d9396..0000000000
--- a/tests/unit/awareness/test_git_probe.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""Phase A5 slice A — GitProbe tests.
-
-Convention: fakes instead of mocks (CLAUDE.md). A real ``git init`` in the
-tmp path for realistic tests; subprocess failure modes run through the
-real git binary, not unittest.mock.
-
-The subprocess setup helpers (``_git``, ``_commit``) are sync and are
-deliberately called from the async tests — this is test fixture setup,
-not runtime IO. Hence ``# noqa: ASYNC221``.
-"""
-from __future__ import annotations
-
-import subprocess
-import time
-from pathlib import Path
-
-import pytest
-
-from jarvis.awareness.probes.git import GitProbe
-
-# --- Sync subprocess helpers (test setup, not runtime code) ---
-
-
-def _git(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes]:
- """Run ``git -C <repo> <args>`` synchronously for test setup."""
- return subprocess.run( # noqa: ASYNC221 (sync test setup, not async runtime)
- ["git", "-C", str(repo), *args],
- check=True,
- capture_output=True,
- )
-
-
-def _commit_init(repo: Path, filename: str = "init.txt") -> None:
- """First commit for a freshly initialized repo (so branches exist)."""
- (repo / filename).write_text("init")
- _git(repo, "add", ".")
- _git(
- repo,
- "-c", "user.name=t",
- "commit", "-m", "init",
- )
-
-
-# --- Fixture: real git init in the tmp path ---
-
-
-def git_repo(tmp_path: Path) -> Path:
- """Creates a real git repo via subprocess (sync, tmp setup)."""
- subprocess.run( # noqa: ASYNC221
- ["git", "init", "--initial-branch=main", str(tmp_path)],
- check=True,
- capture_output=True,
- )
- return tmp_path
-
-
-# --- Tests ---
-
-
-async def test_probe_with_none_cwd_returns_none() -> None:
- p = GitProbe()
- result = await p.probe(cwd=None)
- assert result == {"git_branch": None}
-
-
-async def test_probe_non_git_dir_returns_none(tmp_path: Path) -> None:
- p = GitProbe()
- result = await p.probe(cwd=str(tmp_path))
- assert result == {"git_branch": None}
-
-
-async def test_probe_real_git_repo_returns_branch(git_repo: Path) -> None:
- p = GitProbe()
- result = await p.probe(cwd=str(git_repo))
- assert result["git_branch"] == "main"
-
-
-async def test_probe_branch_after_checkout(git_repo: Path) -> None:
- """Switch branch and verify that the change is visible."""
- _commit_init(git_repo, "test.txt")
- _git(git_repo, "checkout", "-b", "feature/x")
- p = GitProbe()
- result = await p.probe(cwd=str(git_repo))
- assert result["git_branch"] == "feature/x"
-
-
-async def test_probe_detached_head_returns_sha_prefix(git_repo: Path) -> None:
- """Detached HEAD: returns an 8-char SHA prefix instead of None."""
- _commit_init(git_repo, "x.txt")
- sha_result = subprocess.run( # noqa: ASYNC221
- ["git", "-C", str(git_repo), "rev-parse", "HEAD"],
- check=True,
- capture_output=True,
- text=True,
- )
- sha = sha_result.stdout.strip()
- _git(git_repo, "checkout", sha)
- p = GitProbe()
- result = await p.probe(cwd=str(git_repo))
- # Expectation: 8-char prefix, not None
- assert result["git_branch"] is not None
- assert len(result["git_branch"]) == 8
- assert sha.startswith(result["git_branch"])
-
-
-async def test_probe_worktree_repo_resolves_gitdir(
- git_repo: Path, tmp_path: Path
-) -> None:
- """Worktree: ``.git`` is a file with ``gitdir: ...`` content."""
- _commit_init(git_repo, "a.txt")
- wt_path = tmp_path / "worktree"
- _git(git_repo, "worktree", "add", str(wt_path), "-b", "wt-branch")
-
- p = GitProbe()
- result = await p.probe(cwd=str(wt_path))
- assert result["git_branch"] == "wt-branch"
-
-
-async def test_probe_invalid_cwd_returns_none() -> None:
- """Nonexistent path -> None, no crash."""
- p = GitProbe()
- result = await p.probe(cwd="C:/Nonexistent/Path/Definitely/Not/Here_xyzz")
- assert result == {"git_branch": None}
-
-
-async def test_probe_handles_corrupted_head_file(git_repo: Path) -> None:
- """``.git/HEAD`` with garbage -> None or a valid string, no crash."""
- head_file = git_repo / ".git" / "HEAD"
- head_file.write_text("\x00\x01\x02 not a valid HEAD")
- p = GitProbe()
- result = await p.probe(cwd=str(git_repo))
- # Should either return success via subprocess OR None — either is fine,
- # the main thing is no crash
- assert isinstance(result, dict)
- assert "git_branch" in result
-
-
-async def test_probe_completes_under_total_budget(git_repo: Path) -> None:
- """Plan §9 AC: 200ms hard timeout per probe call."""
- p = GitProbe()
- start = time.monotonic()
- await p.probe(cwd=str(git_repo))
- elapsed = time.monotonic() - start
- assert elapsed < 0.5, (
- f"Probe took {elapsed * 1000:.1f}ms — should be well under 200ms"
- )
diff --git a/tests/unit/awareness/test_idle_detector.py b/tests/unit/awareness/test_idle_detector.py
deleted file mode 100644
index 83b0024428..0000000000
--- a/tests/unit/awareness/test_idle_detector.py
+++ /dev/null
@@ -1,329 +0,0 @@
-"""Tests for jarvis.awareness.watchers.idle.IdleDetector.
-
-Strategy: mock ``_get_idle_seconds`` plus a direct call to
-``_tick_once()``. This lets tests run <100ms without a real 5min wait and
-without Win32 — pytest works on any platform.
-
-Architecture assumptions that the wave-2 implementation is bound to:
-- ``_tick_once()`` is an isolable method (1 tick = 1 GetLastInputInfo
- + transition check + event publish). ``_run()`` calls it in a loop
- with ``asyncio.sleep(1)`` between ticks.
-- ``_get_idle_seconds()`` is a staticmethod — patchable via
- ``patch.object(IdleDetector, "_get_idle_seconds", ...)``.
-"""
-from __future__ import annotations
-
-import sys
-import time
-from unittest.mock import patch
-
-import pytest
-
-import jarvis.awareness.watchers.idle as idle_mod
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.awareness.watchers.idle import IdleDetector
-from jarvis.core.bus import EventBus
-from jarvis.core.events import IdleEntered, IdleExited
-
-
-def _make_manager() -> AwarenessManager:
- return AwarenessManager(AwarenessConfig.default())
-
-
-def _async_collect(target: list):
- """Test helper: returns an async handler that appends events to the list."""
- async def _handler(ev):
- target.append(ev)
- return _handler
-
-
-async def test_active_to_idle_transition_emits_event() -> None:
- """When _get_idle_seconds >= threshold: IdleEntered + state.is_idle=True."""
- bus = EventBus()
- received: list[IdleEntered] = []
- bus.subscribe(IdleEntered, _async_collect(received))
-
- manager = _make_manager()
- detector = IdleDetector(manager=manager, bus=bus, threshold_s=5)
-
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 6.0)):
- await detector._tick_once()
-
- assert manager.state.is_idle is True
- assert len(received) == 1
- assert received[0].idle_since_ns > 0
-
-
-async def test_idle_to_active_transition_emits_exited() -> None:
- """As soon as _get_idle_seconds < threshold and it was idle before: IdleExited."""
- bus = EventBus()
- exited: list[IdleExited] = []
- bus.subscribe(IdleExited, _async_collect(exited))
-
- manager = _make_manager()
- detector = IdleDetector(manager=manager, bus=bus, threshold_s=5)
-
- # First make it idle
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 6.0)):
- await detector._tick_once()
- assert manager.state.is_idle is True
-
- # Then active again
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 1.0)):
- await detector._tick_once()
-
- assert manager.state.is_idle is False
- assert len(exited) == 1
- assert exited[0].was_idle_for_ms >= 0
-
-
-async def test_idle_since_ns_propagates_into_current_frame() -> None:
- """If current_frame exists: idle_since_ns is set via dataclasses.replace."""
- bus = EventBus()
- manager = _make_manager()
- manager.state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns(),
- active_window_title="VS Code",
- active_process_name="code.exe",
- active_pid=1234,
- is_capture_allowed=True,
- )
-
- detector = IdleDetector(manager=manager, bus=bus, threshold_s=5)
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 7.0)):
- await detector._tick_once()
-
- cur = manager.state.current_frame
- assert cur is not None
- assert cur.idle_since_ns is not None
- # Original fields remain — replace, not overwrite
- assert cur.active_window_title == "VS Code"
- assert cur.active_process_name == "code.exe"
-
-
-async def test_no_event_when_below_threshold() -> None:
- """Multiple ticks below threshold → no events."""
- bus = EventBus()
- received: list[IdleEntered] = []
- bus.subscribe(IdleEntered, _async_collect(received))
-
- detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=5)
-
- fake_seq = iter([4.9, 4.8, 4.5, 0.0])
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: next(fake_seq))):
- for _ in range(4):
- await detector._tick_once()
-
- assert len(received) == 0
-
-
-async def test_no_double_idle_event_within_same_idle_phase() -> None:
- """Stays idle over multiple ticks → exactly 1 IdleEntered."""
- bus = EventBus()
- received: list[IdleEntered] = []
- bus.subscribe(IdleEntered, _async_collect(received))
-
- detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=5)
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 10.0)):
- await detector._tick_once()
- await detector._tick_once()
- await detector._tick_once()
-
- assert len(received) == 1
-
-
-async def test_start_idempotent() -> None:
- """A double start() is a no-op."""
- bus = EventBus()
- detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=300)
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):
- await detector.start()
- await detector.start()
- await detector.stop()
-
-
-async def test_stop_idempotent_and_fast() -> None:
- """stop() completes in <1s. A double stop() is a no-op."""
- bus = EventBus()
- detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=300)
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):
- await detector.start()
- t0 = time.perf_counter()
- await detector.stop()
- await detector.stop()
- elapsed = time.perf_counter() - t0
- assert elapsed < 1.5
-
-
-# ---- Backend resolution (macOS/Linux) ----------------------------------------
-# Platform behavior is simulated by monkeypatching the resolvers idle.py
-# imports (detect_platform / display_present / is_wayland) so these tests run
-# deterministically on any host, including this Windows dev machine.
-
-
-def test_resolve_backend_windows() -> None:
- with patch.object(idle_mod, "detect_platform", lambda: "win32"):
- backend, reason = IdleDetector._resolve_backend()
- assert backend == "win32"
- assert reason == ""
-
-
-def test_resolve_backend_macos_without_quartz(monkeypatch) -> None:
- """No pyobjc-Quartz importable → backend=None with a clear reason.
-
- Forced via ``sys.modules["Quartz"] = None`` (the standard "known
- unimportable" sentinel) so this is deterministic regardless of whether
- the host actually has pyobjc installed.
- """
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "darwin")
- monkeypatch.setitem(sys.modules, "Quartz", None)
- backend, reason = IdleDetector._resolve_backend()
- assert backend is None
- assert "Quartz" in reason
-
-
-def test_resolve_backend_linux_wayland(monkeypatch) -> None:
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(idle_mod, "is_wayland", lambda: True)
- backend, reason = IdleDetector._resolve_backend()
- assert backend is None
- assert "Wayland" in reason
-
-
-def test_resolve_backend_linux_headless(monkeypatch) -> None:
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(idle_mod, "display_present", lambda: False)
- backend, reason = IdleDetector._resolve_backend()
- assert backend is None
- assert "headless" in reason
-
-
-def test_resolve_backend_linux_missing_xprintidle(monkeypatch) -> None:
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(idle_mod, "display_present", lambda: True)
- monkeypatch.setattr(idle_mod.shutil, "which", lambda name: None)
- backend, reason = IdleDetector._resolve_backend()
- assert backend is None
- assert "xprintidle" in reason
-
-
-def test_resolve_backend_linux_available(monkeypatch) -> None:
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(idle_mod, "display_present", lambda: True)
- monkeypatch.setattr(idle_mod.shutil, "which", lambda name: "/usr/bin/xprintidle")
- backend, reason = IdleDetector._resolve_backend()
- assert backend == "linux"
- assert reason == ""
-
-
-async def test_start_degrades_honestly_when_no_backend(monkeypatch, caplog) -> None:
- """No usable backend: start() logs one line and never creates the task
- (mirrors WindowFocusWatcher's honest degradation), instead of spinning
- the 1 s loop forever reporting "never idle"."""
- monkeypatch.setattr(idle_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(idle_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(idle_mod, "display_present", lambda: False)
-
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- with caplog.at_level("INFO"):
- await detector.start()
-
- assert detector._task is None
- assert any("idle detection unavailable" in r.message for r in caplog.records)
- await detector.stop() # no crash on stop-without-start
-
-
-async def test_tick_disables_after_max_consecutive_failures() -> None:
- """A backend that always raises stops the loop after N failures, not
- before, and never crashes the tick."""
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- detector._backend = "linux"
-
- def _raise() -> float:
- raise RuntimeError("xprintidle vanished")
-
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(_raise)):
- for _ in range(idle_mod._MAX_CONSECUTIVE_FAILURES - 1):
- await detector._tick_once()
- assert detector._stopped is False
- await detector._tick_once()
-
- assert detector._stopped is True
- assert detector._consecutive_failures == idle_mod._MAX_CONSECUTIVE_FAILURES
-
-
-async def test_tick_resets_failure_counter_on_success() -> None:
- """A single successful tick after failures resets the counter to zero."""
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- detector._backend = "linux"
- detector._consecutive_failures = idle_mod._MAX_CONSECUTIVE_FAILURES - 1
-
- with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):
- await detector._tick_once()
-
- assert detector._consecutive_failures == 0
- assert detector._stopped is False
-
-
-def test_get_idle_seconds_macos_backend(monkeypatch) -> None:
- """The macOS backend calls CGEventSourceSecondsSinceLastEventType and
- converts the result to a float."""
- import types
-
- fake_quartz = types.SimpleNamespace(
- CGEventSourceSecondsSinceLastEventType=lambda state, event_type: 12.5,
- kCGEventSourceStateCombinedSessionState=object(),
- kCGAnyInputEventType=object(),
- )
- monkeypatch.setitem(sys.modules, "Quartz", fake_quartz)
-
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- detector._backend = "macos"
- assert detector._get_idle_seconds() == 12.5
-
-
-def test_get_idle_seconds_linux_backend(monkeypatch) -> None:
- """The Linux backend parses xprintidle's stdout (milliseconds) to seconds."""
- class _FakeCompleted:
- returncode = 0
- stdout = "4200\n"
-
- monkeypatch.setattr(
- idle_mod.subprocess, "run", lambda *a, **kw: _FakeCompleted(),
- )
-
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- detector._backend = "linux"
- assert detector._get_idle_seconds() == 4.2
-
-
-def test_get_idle_seconds_linux_backend_raises_on_nonzero_exit(monkeypatch) -> None:
- """A non-zero xprintidle exit raises — the tick-level failure counter
- is what disables the backend, not a silent 0.0 here."""
- class _FakeCompleted:
- returncode = 1
- stdout = ""
-
- monkeypatch.setattr(
- idle_mod.subprocess, "run", lambda *a, **kw: _FakeCompleted(),
- )
-
- detector = IdleDetector(manager=_make_manager(), bus=EventBus(), threshold_s=300)
- detector._backend = "linux"
- with pytest.raises(RuntimeError):
- detector._get_idle_seconds()
diff --git a/tests/unit/awareness/test_manager.py b/tests/unit/awareness/test_manager.py
deleted file mode 100644
index 23ada1819b..0000000000
--- a/tests/unit/awareness/test_manager.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""Tests for jarvis.awareness.manager.AwarenessManager (extended in A1)."""
-from __future__ import annotations
-
-import time
-
-import pytest
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.core.bus import EventBus
-
-
-async def test_a0_backward_compat_no_bus_no_crash() -> None:
- """A0 stub use: a manager without a bus works for pure read use cases."""
- cfg = AwarenessConfig.default()
- manager = AwarenessManager(cfg)
- assert manager.state is not None
- assert manager.config is cfg
-
-
-async def test_start_with_disabled_config_skips_watchers() -> None:
- """enabled=False → start() is a no-op."""
- cfg = AwarenessConfig(enabled=False)
- bus = EventBus()
- manager = AwarenessManager(cfg, bus=bus)
-
- await manager.start()
- await manager.stop()
-
-
-async def test_start_idempotent() -> None:
- """A double start() = no-op."""
- cfg = AwarenessConfig(enabled=False)
- manager = AwarenessManager(cfg, bus=EventBus())
- await manager.start()
- await manager.start()
- await manager.stop()
-
-
-async def test_stop_idempotent() -> None:
- """A double stop() = no-op."""
- cfg = AwarenessConfig(enabled=False)
- manager = AwarenessManager(cfg, bus=EventBus())
- await manager.start()
- await manager.stop()
- await manager.stop()
-
-
-async def test_stop_completes_within_2s() -> None:
- """Plan §5 + §10 hard negative: stop() <2s."""
- cfg = AwarenessConfig(enabled=False)
- manager = AwarenessManager(cfg, bus=EventBus())
- await manager.start()
-
- t0 = time.perf_counter()
- await manager.stop()
- elapsed = time.perf_counter() - t0
- assert elapsed < 2.0
-
-
-async def test_state_property_returns_same_instance() -> None:
- """manager.state is a stable instance (no new object per read)."""
- manager = AwarenessManager(AwarenessConfig.default())
- s1 = manager.state
- s2 = manager.state
- assert s1 is s2
diff --git a/tests/unit/awareness/test_privacy.py b/tests/unit/awareness/test_privacy.py
deleted file mode 100644
index 13b4d97397..0000000000
--- a/tests/unit/awareness/test_privacy.py
+++ /dev/null
@@ -1,184 +0,0 @@
-"""Tests for jarvis.awareness.privacy.PrivacyFilter.
-
-Plan §4 smoke expectations + hybrid default behavior + user-patterns additivity.
-
-PrivacyFilter mirrors jarvis.safety.risk_tier: SYSTEM patterns are hard,
-USER can only block additively (never remove system defaults). Order:
-BLOCK > ALLOW > default hybrid (block-for-browsers).
-"""
-from __future__ import annotations
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.privacy import PrivacyFilter
-
-
-def _filter() -> PrivacyFilter:
- return PrivacyFilter(AwarenessConfig.default())
-
-
-# --- Plan §4 smoke test (binding) ------------------------------------------
-
-def test_blocks_banking_title() -> None:
- """Plan smoke 1: Sparkasse-Online-Banking → BLOCKED, reason matches."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="Sparkasse Online-Banking - Mozilla Firefox", # i18n-allow
- process_name="firefox.exe",
- )
- assert allowed is False
- assert reason.startswith("matched_blocked_title:")
- # A banking pattern must match — either *Banking* or *Sparkasse* or *Online-Banking*
- assert any(p in reason for p in ("*Banking*", "*Sparkasse*", "*Online-Banking*")) # i18n-allow
-
-
-def test_allows_vscode() -> None:
- """Plan smoke 2: VS Code → ALLOWED, reason matches."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="pipeline.py - jarvis - Visual Studio Code",
- process_name="code.exe",
- )
- assert allowed is True
- assert reason == "matched_allowed_process:code.exe"
-
-
-# --- Hybrid default (D-A1) --------------------------------------------------
-
-def test_browser_without_explicit_block_still_blocked_via_hybrid() -> None:
- """D-A1: a browser without a title match → BLOCKED (default block_for_browsers)."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="Wikipedia — The Free Encyclopedia",
- process_name="firefox.exe",
- )
- assert allowed is False
- assert reason == "default_block_for_browser"
-
-
-def test_unknown_non_browser_allowed_via_hybrid() -> None:
- """D-A1: Notepad or similar → ALLOWED (default allow_for_others)."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="Untitled - Notepad",
- process_name="notepad.exe",
- )
- assert allowed is True
- assert reason == "default_allow_for_unknown"
-
-
-def test_chrome_blocked_by_hybrid() -> None:
- """Chrome counts as a browser → the hybrid default blocks it."""
- pf = _filter()
- allowed, _ = pf.is_allowed(
- window_title="GitHub - Mozilla Firefox",
- process_name="chrome.exe",
- )
- assert allowed is False
-
-
-# --- BLOCK trumps ALLOW + order ---------------------------------------------
-
-def test_blocked_process_trumps_allowed_process() -> None:
- """1password title in code.exe → BLOCK wins (the process blacklist applies)."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="My Vault - 1Password",
- process_name="1password.exe",
- )
- assert allowed is False
- assert reason.startswith("matched_blocked_process:1password*")
-
-
-def test_blocked_title_trumps_allowed_process() -> None:
- """Banking title in code.exe (e.g. a PDF view) → the title blacklist wins."""
- pf = _filter()
- allowed, reason = pf.is_allowed(
- window_title="Sparkasse Statement.pdf - Code", # i18n-allow
- process_name="code.exe",
- )
- assert allowed is False
- assert reason.startswith("matched_blocked_title:")
-
-
-# --- User patterns are additive ----------------------------------------------
-
-def test_user_patterns_can_add_blocks() -> None:
- """The user can add their own blocked_processes — additive to the system."""
- cfg = AwarenessConfig.default()
-
- def user_patterns() -> tuple[list[str], list[str], list[str]]:
- # (blocked_processes, blocked_title_patterns, allowed_processes)
- return (["secretapp.exe"], [], [])
-
- pf = PrivacyFilter(cfg, user_patterns_fn=user_patterns)
- allowed, reason = pf.is_allowed(
- window_title="My Secret Tool",
- process_name="secretapp.exe",
- )
- assert allowed is False
- assert reason.startswith("matched_blocked_process:secretapp.exe")
-
-
-def test_user_patterns_cannot_remove_system_blocks() -> None:
- """User patterns are ADDITIVE — an empty user list leaves the system
- defaults active. 1password stays blocked even if the user adds nothing."""
- cfg = AwarenessConfig.default()
-
- def user_patterns() -> tuple[list[str], list[str], list[str]]:
- return ([], [], []) # user deletes nothing; can't anyway
-
- pf = PrivacyFilter(cfg, user_patterns_fn=user_patterns)
- allowed, _ = pf.is_allowed(
- window_title="My Vault",
- process_name="1password.exe",
- )
- assert allowed is False # system default 1password* still applies
-
-
-def test_user_patterns_callback_errors_are_swallowed() -> None:
- """If user_patterns_fn raises: treat it like an empty list, don't crash.
- Mirrors jarvis.safety.risk_tier._collect_patterns try/except."""
- cfg = AwarenessConfig.default()
-
- def broken() -> tuple[list[str], list[str], list[str]]:
- raise RuntimeError("user-toml-broken")
-
- pf = PrivacyFilter(cfg, user_patterns_fn=broken)
- # Doesn't crash; system defaults apply normally
- allowed, _ = pf.is_allowed(
- window_title="Untitled - Notepad",
- process_name="notepad.exe",
- )
- assert allowed is True
-
-
-# --- reason string format (plan §4 smoke spec) ------------------------------
-
-def test_reason_format_for_blocked_title() -> None:
- """reason format: matched_blocked_title:<pattern>."""
- pf = _filter()
- _, reason = pf.is_allowed(
- window_title="PayPal Login",
- process_name="firefox.exe",
- )
- assert reason == "matched_blocked_title:*PayPal*"
-
-
-def test_reason_format_for_allowed_process() -> None:
- """reason format: matched_allowed_process:<pattern>."""
- pf = _filter()
- _, reason = pf.is_allowed(
- window_title="Untitled-1 - Visual Studio Code",
- process_name="code.exe",
- )
- assert reason == "matched_allowed_process:code.exe"
-
-
-def test_case_insensitive_matching() -> None:
- """Patterns match case-insensitively (like risk_tier.py:105)."""
- pf = _filter()
- allowed, _ = pf.is_allowed(
- window_title="Meine SPARKASSE Online-Banking Sitzung", # i18n-allow
- process_name="firefox.exe",
- )
- assert allowed is False
diff --git a/tests/unit/awareness/test_quotas.py b/tests/unit/awareness/test_quotas.py
deleted file mode 100644
index 82ebcc6950..0000000000
--- a/tests/unit/awareness/test_quotas.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""Tests for jarvis.awareness.quotas.StorageQuota.
-
-A0 scope: a pure dataclass with a would_exceed verdict. A2 uses it
-during episode persistence as a pre-insert check.
-"""
-from __future__ import annotations
-
-from jarvis.awareness.quotas import StorageQuota
-
-
-def test_default_thresholds() -> None:
- """Defaults: 50 MiB bytes, 1000 episodes."""
- q = StorageQuota()
- assert q.max_bytes == 50 * 1024 * 1024
- assert q.max_episodes == 1000
-
-
-def test_would_exceed_below_caps() -> None:
- """Both values under the cap → (False, '')."""
- q = StorageQuota()
- exceeded, reason = q.would_exceed(current_bytes=1024, current_episode_count=10)
- assert exceeded is False
- assert reason == ""
-
-
-def test_would_exceed_at_byte_cap() -> None:
- """current_bytes reaches max_bytes → blocks."""
- q = StorageQuota(max_bytes=1000, max_episodes=100)
- exceeded, reason = q.would_exceed(current_bytes=1000, current_episode_count=0)
- assert exceeded is True
- assert reason == "max_bytes_reached"
-
-
-def test_would_exceed_at_episode_cap() -> None:
- """current_episode_count reaches max_episodes → blocks."""
- q = StorageQuota(max_bytes=10**9, max_episodes=5)
- exceeded, reason = q.would_exceed(current_bytes=0, current_episode_count=5)
- assert exceeded is True
- assert reason == "max_episodes_reached"
-
-
-def test_would_exceed_byte_takes_priority_when_both_full() -> None:
- """When both caps are full: the bytes reason wins (disk risk > count risk)."""
- q = StorageQuota(max_bytes=100, max_episodes=10)
- exceeded, reason = q.would_exceed(current_bytes=100, current_episode_count=10)
- assert exceeded is True
- assert reason == "max_bytes_reached"
-
-
-def test_would_exceed_above_caps_still_blocks() -> None:
- """Values above the cap too (race condition) → blocks."""
- q = StorageQuota(max_bytes=100, max_episodes=10)
- exceeded, reason = q.would_exceed(current_bytes=200, current_episode_count=20)
- assert exceeded is True
- assert reason == "max_bytes_reached"
-
-
-def test_storagequota_is_frozen() -> None:
- """Quotas are config snapshots — frozen prevents mutation."""
- import dataclasses
-
- import pytest
-
- q = StorageQuota()
- with pytest.raises(dataclasses.FrozenInstanceError):
- q.max_bytes = 0 # type: ignore[misc]
diff --git a/tests/unit/awareness/test_salience.py b/tests/unit/awareness/test_salience.py
deleted file mode 100644
index 92c01ad0b5..0000000000
--- a/tests/unit/awareness/test_salience.py
+++ /dev/null
@@ -1,257 +0,0 @@
-"""Tests for jarvis.awareness.salience — SalienceScorer.
-
-Pure function tests, no bus / no I/O. Spec: plan §6
-"Salience Scorer (binding, rule-based)".
-"""
-from __future__ import annotations
-
-from jarvis.awareness.salience import (
- BORING_PROCESSES,
- SALIENCE_THRESHOLD,
- SalienceScorer,
-)
-from jarvis.awareness.state import FrameSnapshot
-
-
-def _make_frame(
- *,
- process: str = "code.exe",
- title: str = "main.py - VS Code",
- pid: int = 1000,
- timestamp_ns: int = 1_000_000_000,
- git_branch: str | None = None,
-) -> FrameSnapshot:
- """Convenient constructor — all fields with sensible defaults."""
- return FrameSnapshot(
- timestamp_ns=timestamp_ns,
- active_window_title=title,
- active_process_name=process,
- active_pid=pid,
- is_capture_allowed=True,
- git_branch=git_branch,
- )
-
-
-# --- score_frame: prev=None --------------------------------------------------
-
-def test_score_frame_no_prev_returns_neutral() -> None:
- """First frame with no prev → deterministically a mid-score default."""
- scorer = SalienceScorer()
- frame = _make_frame()
-
- score = scorer.score_frame(frame, prev=None)
-
- # Default base = 50, no BORING, no bonus → 50.
- assert score == 50
-
-
-def test_score_frame_no_prev_boring_still_penalised() -> None:
- """Even without prev, the BORING penalty still applies."""
- scorer = SalienceScorer()
- frame = _make_frame(process="explorer.exe")
-
- score = scorer.score_frame(frame, prev=None)
-
- # 50 (base) - 50 (BORING) = 0.
- assert score == 0
-
-
-# --- score_frame: deltas ------------------------------------------------------
-
-def test_score_frame_process_switch_adds_20() -> None:
- """Process switch ⇒ +20 (app switch)."""
- scorer = SalienceScorer()
- prev = _make_frame(process="notepad.exe", title="A.txt")
- frame = _make_frame(process="code.exe", title="B.py", timestamp_ns=2_000_000_000)
-
- score = scorer.score_frame(frame, prev=prev)
-
- # Process changed = +20. Title differs, but that's only counted
- # when the process stays the same — otherwise it's double-counted.
- assert score == 20
-
-
-def test_score_frame_title_switch_same_process_adds_30() -> None:
- """Title switch with the same process ⇒ +30 (file/tab switch)."""
- scorer = SalienceScorer()
- prev = _make_frame(process="code.exe", title="main.py - VS Code")
- frame = _make_frame(
- process="code.exe", title="utils.py - VS Code", timestamp_ns=2_000_000_000,
- )
-
- score = scorer.score_frame(frame, prev=prev)
-
- assert score == 30
-
-
-def test_score_frame_git_branch_change_adds_20() -> None:
- """Git branch switch ⇒ +20 (both non-None required)."""
- scorer = SalienceScorer()
- prev = _make_frame(git_branch="main")
- frame = _make_frame(
- git_branch="feature/x", timestamp_ns=2_000_000_000,
- )
-
- score = scorer.score_frame(frame, prev=prev)
-
- # Process+title same ⇒ no bonuses there, just branch +20.
- assert score == 20
-
-
-def test_score_frame_git_branch_one_none_no_bonus() -> None:
- """git_branch set in only one frame ⇒ no bonus."""
- scorer = SalienceScorer()
- prev = _make_frame(git_branch=None)
- frame = _make_frame(git_branch="main", timestamp_ns=2_000_000_000)
-
- score = scorer.score_frame(frame, prev=prev)
-
- assert score == 0
-
-
-def test_score_frame_long_dwell_adds_10() -> None:
- """Frame >2min after prev ⇒ +10 (dwell time)."""
- scorer = SalienceScorer()
- prev = _make_frame(timestamp_ns=0)
- frame = _make_frame(timestamp_ns=121_000_000_000) # >2min
-
- score = scorer.score_frame(frame, prev=prev)
-
- # Process+title same ⇒ only the dwell bonus.
- assert score == 10
-
-
-def test_score_frame_short_dwell_no_bonus() -> None:
- """Frame <=2min after prev ⇒ no dwell bonus."""
- scorer = SalienceScorer()
- prev = _make_frame(timestamp_ns=0)
- frame = _make_frame(timestamp_ns=120_000_000_000) # exactly 2min
-
- score = scorer.score_frame(frame, prev=prev)
-
- assert score == 0
-
-
-# --- score_frame: BORING penalty ---------------------------------------------
-
-def test_score_frame_boring_process_subtracts_50() -> None:
- """Explorer.exe ⇒ -50 penalty (pulls the score down)."""
- scorer = SalienceScorer()
- prev = _make_frame(process="code.exe")
- # Process switch ⇒ +20, then -50 ⇒ -30 ⇒ clamped to 0.
- frame = _make_frame(process="explorer.exe", timestamp_ns=2_000_000_000)
-
- score = scorer.score_frame(frame, prev=prev)
-
- assert score == 0
-
-
-def test_score_frame_case_insensitive_boring() -> None:
- """BORING_PROCESSES match case-insensitively."""
- scorer = SalienceScorer()
- prev = _make_frame(process="code.exe")
-
- # Both variants must produce the same score.
- frame_lower = _make_frame(process="explorer.exe", timestamp_ns=2_000_000_000)
- frame_upper = _make_frame(process="Explorer.exe", timestamp_ns=2_000_000_000)
- frame_mixed = _make_frame(process="ExPlOrEr.ExE", timestamp_ns=2_000_000_000)
-
- s_lower = scorer.score_frame(frame_lower, prev=prev)
- s_upper = scorer.score_frame(frame_upper, prev=prev)
- s_mixed = scorer.score_frame(frame_mixed, prev=prev)
-
- assert s_lower == s_upper == s_mixed == 0
-
-
-def test_score_frame_clamped_to_0_100() -> None:
- """Extreme combos respect the [0, 100] clamp."""
- scorer = SalienceScorer()
- # All bonuses: process+20, branch+20, dwell+10 = +50 (realistic max).
- # We can't force score > 100 via score_frame — so this test is
- # primarily for the lower bound (BORING + no bonuses).
- prev = _make_frame(process="code.exe", git_branch="main")
- frame = _make_frame(
- process="explorer.exe", # +20 process, -50 BORING
- title="other",
- git_branch="main", # same, no bonus
- timestamp_ns=2_000_000_000, # short dwell
- )
-
- score = scorer.score_frame(frame, prev=prev)
-
- # Score must lie in [0, 100], here concretely 0 (clamped from -30).
- assert 0 <= score <= 100
- assert score == 0
-
-
-def test_score_frame_max_combo_not_above_100() -> None:
- """Even the max bonus stack stays <= 100."""
- scorer = SalienceScorer()
- prev = _make_frame(
- process="notepad.exe", title="A.txt", git_branch="main", timestamp_ns=0,
- )
- # Process switch (+20), branch (+20), dwell >2min (+10), no BORING.
- # Title switch doesn't count because the process already switched.
- frame = _make_frame(
- process="code.exe",
- title="main.py",
- git_branch="feature/x",
- timestamp_ns=200_000_000_000,
- )
-
- score = scorer.score_frame(frame, prev=prev)
-
- assert score == 50 # 20 + 20 + 10
- assert 0 <= score <= 100
-
-
-# --- score_event ---------------------------------------------------------------
-
-def test_score_event_known_kinds() -> None:
- """FileSaved=40, BrainTurnCompleted=50, IdleExited=20."""
- scorer = SalienceScorer()
-
- assert scorer.score_event("FileSaved") == 40
- assert scorer.score_event("BrainTurnCompleted") == 50
- assert scorer.score_event("IdleExited") == 20
-
-
-def test_score_event_terminal_exit_with_payload() -> None:
- """TerminalExit: exit_code=0 ⇒ 20, otherwise ⇒ 60."""
- scorer = SalienceScorer()
-
- assert scorer.score_event("TerminalExit", {"exit_code": 0}) == 20
- assert scorer.score_event("TerminalExit", {"exit_code": 1}) == 60
- assert scorer.score_event("TerminalExit", {"exit_code": 127}) == 60
-
-
-def test_score_event_terminal_exit_default_zero_exit_code() -> None:
- """TerminalExit without a payload ⇒ default exit_code=0 ⇒ 20."""
- scorer = SalienceScorer()
-
- assert scorer.score_event("TerminalExit") == 20
- assert scorer.score_event("TerminalExit", None) == 20
- assert scorer.score_event("TerminalExit", {}) == 20
-
-
-def test_score_event_unknown_default_zero() -> None:
- """Unknown event_kind ⇒ 0."""
- scorer = SalienceScorer()
-
- assert scorer.score_event("WhateverElse") == 0
- assert scorer.score_event("") == 0
- assert scorer.score_event("RandomEventName", {"foo": "bar"}) == 0
-
-
-# --- Module-level constants ---------------------------------------------------
-
-def test_threshold_constant_value() -> None:
- """SALIENCE_THRESHOLD is 30 (plan §6)."""
- assert SALIENCE_THRESHOLD == 30
-
-
-def test_boring_processes_lowercase() -> None:
- """All BORING_PROCESSES entries are lowercase
- (the caller compares with .lower() — otherwise a silent no-match)."""
- for entry in BORING_PROCESSES:
- assert entry == entry.lower(), f"BORING entry not lowercase: {entry!r}"
diff --git a/tests/unit/awareness/test_state.py b/tests/unit/awareness/test_state.py
deleted file mode 100644
index 8175749197..0000000000
--- a/tests/unit/awareness/test_state.py
+++ /dev/null
@@ -1,171 +0,0 @@
-"""Tests for jarvis.awareness.state — FrameSnapshot + AwarenessState.
-
-A0 scope: data classes + default behavior. snapshot_for_prompt() is an
-A0 placeholder (empty string); real rendering logic arrives in A1.
-"""
-from __future__ import annotations
-
-import dataclasses
-import time
-
-import pytest
-
-from jarvis.awareness.state import AwarenessState, FrameSnapshot
-
-# --- FrameSnapshot ---------------------------------------------------------
-
-def test_framesnapshot_is_frozen() -> None:
- """frozen=True verhindert Re-Assignment."""
- snap = FrameSnapshot(
- timestamp_ns=1,
- active_window_title="x",
- active_process_name="y",
- active_pid=1,
- is_capture_allowed=True,
- )
- with pytest.raises(dataclasses.FrozenInstanceError):
- snap.active_pid = 2 # type: ignore[misc]
-
-
-def test_framesnapshot_has_slots() -> None:
- """slots=True → no __dict__, only the declared fields."""
- snap = FrameSnapshot(
- timestamp_ns=1,
- active_window_title="x",
- active_process_name="y",
- active_pid=1,
- is_capture_allowed=True,
- )
- with pytest.raises(AttributeError):
- snap.__dict__ # noqa: B018
-
-
-def test_framesnapshot_optional_fields_default_none() -> None:
- """git_branch / open_file_hint / idle_since_ns are always None in A0."""
- snap = FrameSnapshot(
- timestamp_ns=1,
- active_window_title="x",
- active_process_name="y",
- active_pid=1,
- is_capture_allowed=True,
- )
- assert snap.git_branch is None
- assert snap.open_file_hint is None
- assert snap.idle_since_ns is None
-
-
-# --- AwarenessState --------------------------------------------------------
-
-def test_awarenessstate_default_init() -> None:
- """AwarenessState() with no args is valid and has sensible defaults.
-
- A4 refactor: ``working_set`` is no longer a ``list`` but an
- optional ``WorkingSet | None``. Default = None — set by the
- AwarenessManager constructor.
- """
- state = AwarenessState()
- assert state.current_frame is None
- assert state.last_episode_summary == ""
- assert state.last_episode_id is None
- assert state.is_idle is False
- assert state.working_set is None
-
-
-def test_awarenessstate_is_mutable() -> None:
- """AwarenessState is NOT frozen — watchers write into it."""
- state = AwarenessState()
- state.is_idle = True
- state.last_episode_summary = "hello"
- assert state.is_idle is True
- assert state.last_episode_summary == "hello"
-
-
-def test_awarenessstate_working_set_is_per_instance() -> None:
- """A4: ``working_set`` is a WorkingSet reference from the manager (not a
- shared default). We verify that two AwarenessState instances are
- independent of each other when each gets its own WorkingSet.
- """
- from jarvis.awareness.working_set import WorkingSet
-
- a = AwarenessState()
- b = AwarenessState()
- a.working_set = WorkingSet()
- b.working_set = WorkingSet()
- # Mutating a.working_set must not affect b.
- from jarvis.awareness.context import Context
- a.working_set.observe(Context(project_root="x", task_label=""))
- assert a.working_set.size == 1
- assert b.working_set.size == 0
-
-
-def test_snapshot_for_prompt_a0_placeholder() -> None:
- """A0: snapshot_for_prompt returns an empty string. A1 replaces this."""
- state = AwarenessState()
- assert state.snapshot_for_prompt() == ""
- assert state.snapshot_for_prompt(max_chars=100) == ""
-
-
-# --- Freshness guard (anti-stale-context, 2026-06-17) ----------------------
-# Root cause of the "BridgeSpace und WhatsApp" overclaim: a current_frame that
-# had not updated for ~82 min was rendered verbatim as the present state. The
-# snapshot must never present an old frame as the live foreground.
-
-
-def test_snapshot_fresh_frame_rendered_as_current() -> None:
- """A frame observed just now is presented as the CURRENTLY focused window."""
- state = AwarenessState()
- state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns(),
- active_window_title="pipeline.py - Visual Studio Code",
- active_process_name="Code.exe",
- active_pid=4242,
- is_capture_allowed=True,
- )
- snap = state.snapshot_for_prompt()
- assert "Currently focused window" in snap
- assert "pipeline.py - Visual Studio Code" in snap
- assert "Code.exe" in snap
- # A fresh frame must NOT carry the stale marker.
- assert "stale" not in snap.lower()
- assert "Last observed" not in snap
-
-
-def test_snapshot_old_frame_is_marked_stale_not_current() -> None:
- """A frame from ~90 min ago must be flagged as stale, never as 'current'.
-
- Regression guard for the 19:38 turn where an 82-min-old frame
- ('WhatsApp'/'BridgeSpace') was narrated as 'aktuell ... aktiv'.
- """
- ninety_min_ns = int(90 * 60 * 1_000_000_000)
- state = AwarenessState()
- state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns() - ninety_min_ns,
- active_window_title="WhatsApp",
- active_process_name="WhatsApp.exe",
- active_pid=777,
- is_capture_allowed=True,
- )
- snap = state.snapshot_for_prompt()
- # The window title is still surfaced (honest: this is the LAST thing seen)...
- assert "WhatsApp" in snap
- # ...but it must be explicitly marked stale and NOT presented as current.
- assert "Last observed" in snap
- assert "stale" in snap.lower()
- assert "Currently focused window" not in snap
-
-
-def test_snapshot_includes_open_window_scope_disclaimer() -> None:
- """The block must state it is focused-window history, not a full window list.
-
- Stops the brain from overclaiming 'only X and Y are open on your PC'.
- """
- state = AwarenessState()
- state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns(),
- active_window_title="Editor",
- active_process_name="Code.exe",
- active_pid=1,
- is_capture_allowed=True,
- )
- snap = state.snapshot_for_prompt()
- assert "not a complete list" in snap.lower()
diff --git a/tests/unit/awareness/test_story_tracker.py b/tests/unit/awareness/test_story_tracker.py
deleted file mode 100644
index 07a5c7e8aa..0000000000
--- a/tests/unit/awareness/test_story_tracker.py
+++ /dev/null
@@ -1,825 +0,0 @@
-"""Phase A2 — StoryTracker (jarvis/awareness/story.py).
-
-Tests the trigger logic (salience filter, app switch, idle, hard timer,
-buffer overflow), the end-to-end path (Verdichter -> Recall -> state
-update -> bus event), and all §6 hard negatives (PrivacyFilter block,
-min-duration skip, Verdichter exception handling).
-
-Convention: fakes instead of mocks (CLAUDE.md). FakeRecall + FakeVerdichter
-implement exactly the methods the tracker calls.
-"""
-from __future__ import annotations
-
-import asyncio
-import time
-from dataclasses import dataclass, field
-from typing import Any
-
-from jarvis.awareness.config import AwarenessConfig, AwarenessStoryConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.awareness.story import StoryTracker
-from jarvis.core.bus import EventBus
-from jarvis.core.events import (
- EpisodeRecorded,
- FrameUpdated,
- IdleEntered,
- ResponseGenerated,
-)
-
-# ---- Fakes -----------------------------------------------------------------
-
-
-@dataclass
-class FakeRecall:
- """Fake for RecallStore — collects record_episode calls."""
- episodes: list[dict[str, Any]] = field(default_factory=list)
- next_id: int = 1
- raise_on_record: bool = False
-
- async def record_episode(self, **kwargs: Any) -> int:
- if self.raise_on_record:
- raise RuntimeError("simulated recall failure")
- ep_id = self.next_id
- self.next_id += 1
- self.episodes.append({"id": ep_id, **kwargs})
- return ep_id
-
-
-@dataclass
-class FakeVerdichter:
- """Fake for Verdichter — returns a deterministic summary + usage."""
- summary: str = "Fake summary"
- tokens_in: int = 100
- tokens_out: int = 50
- duration_ms: int = 200
- raise_exc: Exception | None = None
- calls: list[dict[str, Any]] = field(default_factory=list)
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- self.calls.append({
- "frames_n": len(frames),
- "events_n": len(events),
- "primary_app": primary_app,
- })
- if self.raise_exc is not None:
- raise self.raise_exc
- return self.summary, {
- "tokens_in": self.tokens_in,
- "tokens_out": self.tokens_out,
- "duration_ms": self.duration_ms,
- "error_reason": None,
- }
-
-
-# ---- Helpers ---------------------------------------------------------------
-
-
-def _make_frame(
- *,
- title: str = "main.py - Visual Studio Code",
- process: str = "Code.exe",
- pid: int = 1000,
- ts_ns: int | None = None,
- capture_allowed: bool = True,
-) -> FrameSnapshot:
- return FrameSnapshot(
- timestamp_ns=ts_ns if ts_ns is not None else time.time_ns(),
- active_window_title=title,
- active_process_name=process,
- active_pid=pid,
- is_capture_allowed=capture_allowed,
- )
-
-
-def _make_tracker(
- *,
- story_cfg: AwarenessStoryConfig | None = None,
- fake_recall: FakeRecall | None = None,
- fake_verdichter: FakeVerdichter | None = None,
-) -> tuple[StoryTracker, AwarenessManager, EventBus, FakeRecall, FakeVerdichter]:
- bus = EventBus()
- manager = AwarenessManager(AwarenessConfig.default())
- recall = fake_recall or FakeRecall()
- verdichter = fake_verdichter or FakeVerdichter()
- cfg = story_cfg or AwarenessStoryConfig()
- tracker = StoryTracker(
- manager=manager,
- bus=bus,
- recall=recall,
- verdichter=verdichter,
- config=cfg,
- )
- return tracker, manager, bus, recall, verdichter
-
-
-# ---- Tests: Lifecycle ------------------------------------------------------
-
-
-async def test_init_does_not_crash() -> None:
- tracker, *_ = _make_tracker()
- assert tracker._started is False
-
-
-async def test_start_subscribes_to_bus() -> None:
- tracker, _, bus, _, _ = _make_tracker()
- await tracker.start()
- try:
- # Bus should now have subscribers for the 3 event types.
- # We test this indirectly: publish an event and check whether the
- # handler was called (via _on_response_generated → builder.add_event)
- # First open the builder via a frame:
- frame = _make_frame()
- tracker._manager.state.current_frame = frame
- await bus.publish(FrameUpdated(
- window_title=frame.active_window_title,
- process_name=frame.active_process_name,
- pid=frame.active_pid,
- is_capture_allowed=True,
- ))
- await asyncio.sleep(0.01) # bus dispatch async
- await bus.publish(ResponseGenerated(text="hello", language="de"))
- await asyncio.sleep(0.01)
- assert tracker._builder is not None
- assert any(
- e["kind"] == "BrainTurnCompleted" for e in tracker._builder.events
- )
- finally:
- await tracker.stop()
-
-
-async def test_start_idempotent() -> None:
- tracker, *_ = _make_tracker()
- await tracker.start()
- await tracker.start() # second call must not raise
- await tracker.stop()
-
-
-async def test_stop_idempotent() -> None:
- tracker, *_ = _make_tracker()
- await tracker.start()
- await tracker.stop()
- await tracker.stop() # second call must not raise
-
-
-# ---- Tests: Frame-Filter ---------------------------------------------------
-
-
-async def test_privacy_blocked_frame_not_buffered() -> None:
- """Hard negative §6: PrivacyFilter-blocked frames NEVER enter Verdichter input."""
- tracker, manager, _, _, _ = _make_tracker()
- manager.state.current_frame = _make_frame(capture_allowed=False)
- ev = FrameUpdated(
- window_title="Banking", process_name="chrome.exe",
- pid=1, is_capture_allowed=False,
- )
- await tracker._on_frame_updated(ev)
- assert tracker._builder is None
- assert tracker._prev_frame is None
-
-
-async def test_low_salience_frame_dropped() -> None:
- """Frames with score < SALIENCE_THRESHOLD do NOT end up in the builder."""
- tracker, manager, _, _, _ = _make_tracker()
- # Boring process (Explorer.exe) → -50 penalty → below threshold.
- boring = _make_frame(process="Explorer.exe", title="File-Explorer")
- manager.state.current_frame = boring
- ev = FrameUpdated(
- window_title=boring.active_window_title,
- process_name=boring.active_process_name,
- pid=boring.active_pid,
- is_capture_allowed=True,
- )
- await tracker._on_frame_updated(ev)
- # _prev_frame is still updated (for the next comparison)
- assert tracker._prev_frame is not None
- # BUT no builder is opened
- assert tracker._builder is None
-
-
-async def test_high_salience_frame_buffered() -> None:
- """High-salience frame opens the builder and ends up in it."""
- tracker, manager, _, _, _ = _make_tracker()
- frame = _make_frame()
- manager.state.current_frame = frame
- ev = FrameUpdated(
- window_title=frame.active_window_title,
- process_name=frame.active_process_name,
- pid=frame.active_pid,
- is_capture_allowed=True,
- )
- await tracker._on_frame_updated(ev)
- assert tracker._builder is not None
- assert tracker._builder.frame_count == 1
-
-
-# ---- Tests: Trigger-Logik --------------------------------------------------
-
-
-async def test_app_switch_after_min_duration_triggers_flush() -> None:
- """Process switch + duration >= 60s → flush via Verdichter."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- )
- # Frame 1: Code.exe
- f1 = _make_frame(process="Code.exe", title="main.py", ts_ns=time.time_ns())
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- # Wait > min_duration (1s in test config)
- await asyncio.sleep(1.1)
- # Frame 2: Chrome.exe (App-Switch)
- f2 = _make_frame(process="Chrome.exe", title="Stack Overflow")
- manager.state.current_frame = f2
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f2.active_window_title,
- process_name=f2.active_process_name,
- pid=f2.active_pid, is_capture_allowed=True,
- ))
- # Verdichter MUST have been called
- assert len(verdichter.calls) == 1
- # Episode persisted
- assert len(recall.episodes) == 1
- assert recall.episodes[0]["trigger_kind"] == "window_switch"
-
-
-async def test_short_episode_skipped_on_app_switch() -> None:
- """App switch + duration < min → no flush, builder reset."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=60),
- )
- f1 = _make_frame(process="Code.exe")
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- # NO sleep — duration ~0s
- f2 = _make_frame(process="Chrome.exe", title="other")
- manager.state.current_frame = f2
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f2.active_window_title,
- process_name=f2.active_process_name,
- pid=f2.active_pid, is_capture_allowed=True,
- ))
- # Verdichter NOT called, recall NOT populated
- assert verdichter.calls == []
- assert recall.episodes == []
- # Builder was reset though (not None, since a new frame was inserted)
- # — we test: builder.frame_count is 0 or builder is None
- assert tracker._builder is None or tracker._builder.frame_count == 0
-
-
-async def test_idle_entered_flushes_long_episode() -> None:
- """IdleEntered after >= min_duration → flush."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- )
- f1 = _make_frame()
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- assert len(verdichter.calls) == 1
- assert recall.episodes[0]["trigger_kind"] == "idle_entered"
-
-
-async def test_idle_entered_skips_short_episode() -> None:
- """IdleEntered on a too-short episode → reset, no flush."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=60),
- )
- f1 = _make_frame()
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- assert verdichter.calls == []
- assert recall.episodes == []
-
-
-async def test_buffer_overflow_forces_flush() -> None:
- """frames > buffer_max → forced flush regardless of duration."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(buffer_max=3, episode_min_duration_s=999),
- )
- # Push 5 distinct frames (different titles → high salience)
- base_ts = time.time_ns()
- for i in range(5):
- # Same process_name (Code.exe), different titles → +30 each (no
- # process-switch trigger; but buffer_max overflow trigger)
- f = _make_frame(
- title=f"file_{i}.py", process="Code.exe",
- ts_ns=base_ts + i * 1_000_000_000,
- )
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- # Buffer overflow from frame 4 onward → flush with trigger="buffer_overflow"
- assert len(verdichter.calls) >= 1
- assert any(
- ep["trigger_kind"] == "buffer_overflow" for ep in recall.episodes
- )
-
-
-# ---- Tests: ResponseGenerated ---------------------------------------------
-
-
-async def test_response_generated_adds_event_to_builder() -> None:
- """ResponseGenerated → builder.add_event with kind='BrainTurnCompleted'."""
- tracker, manager, _, _, _ = _make_tracker()
- # First a frame, so the builder exists
- f = _make_frame()
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- # Now ResponseGenerated
- await tracker._on_response_generated(
- ResponseGenerated(text="Reply from the brain", language="de"),
- )
- assert tracker._builder is not None
- events = tracker._builder.events
- assert len(events) == 1
- assert events[0]["kind"] == "BrainTurnCompleted"
- assert events[0]["payload"]["text_len"] == len("Reply from the brain")
-
-
-async def test_response_generated_without_builder_is_noop() -> None:
- """ResponseGenerated without an open builder → no-op (no crash)."""
- tracker, *_ = _make_tracker()
- # Builder ist None
- await tracker._on_response_generated(
- ResponseGenerated(text="hi", language="en"),
- )
- assert tracker._builder is None
-
-
-# ---- Tests: Persist + State + Event ---------------------------------------
-
-
-async def test_flush_updates_state_last_episode_summary() -> None:
- """After flush: manager.state.last_episode_summary + last_episode_id."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=FakeVerdichter(summary="Test summary X"),
- )
- f1 = _make_frame()
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- assert manager.state.last_episode_summary == "Test summary X"
- assert manager.state.last_episode_id == recall.episodes[0]["id"]
-
-
-async def test_flush_publishes_episode_recorded_event() -> None:
- """After flush: bus.publish(EpisodeRecorded(...))."""
- tracker, manager, bus, _, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=FakeVerdichter(summary="Hello world"),
- )
- received: list[EpisodeRecorded] = []
-
- async def collect(ev: EpisodeRecorded) -> None:
- received.append(ev)
-
- bus.subscribe(EpisodeRecorded, collect)
-
- f = _make_frame()
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- await asyncio.sleep(0.05) # bus dispatch
- assert len(received) == 1
- assert received[0].summary_preview == "Hello world"
- assert received[0].frame_count == 1
-
-
-# ---- Tests: Failure-Modes -------------------------------------------------
-
-
-async def test_verdichter_exception_handled_gracefully() -> None:
- """Verdichter raises → empty summary, episode persisted anyway."""
- tracker, manager, _, recall, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=FakeVerdichter(raise_exc=RuntimeError("brain dead")),
- )
- f = _make_frame()
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- # Episode was persisted WITH empty summary
- assert len(recall.episodes) == 1
- assert recall.episodes[0]["summary"] == ""
- assert recall.episodes[0]["tokens_in"] == 0
-
-
-async def test_recall_exception_drops_episode_no_crash() -> None:
- """recall.record_episode raises → episode lost, no crash, no state update."""
- tracker, manager, _, recall, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_recall=FakeRecall(raise_on_record=True),
- )
- f = _make_frame()
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
- await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))
- # State NOT updated because persist failed
- assert manager.state.last_episode_summary == ""
- assert recall.episodes == []
-
-
-async def test_stop_force_flushes_remaining_builder() -> None:
- """stop() flushes regardless of duration (trigger='stop' forces a flush)."""
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=999),
- )
- await tracker.start()
- f = _make_frame()
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- # NO sleep — duration ~0s. But stop() forces a flush.
- await tracker.stop()
- assert len(verdichter.calls) == 1
- assert recall.episodes[0]["trigger_kind"] == "stop"
-
-
-async def test_stale_state_blocked_frame_does_not_leak(
-) -> None:
- """M2 fix: a blocked frame in state.current_frame must NEVER end up in
- the builder, even if the event arrived marked allowed (race window).
- """
- tracker, manager, _, _, _ = _make_tracker()
- # Setup: state has a blocked frame, but the event says allowed=True
- blocked_frame = _make_frame(
- title="Banking", process="chrome.exe",
- capture_allowed=False,
- )
- manager.state.current_frame = blocked_frame
- ev = FrameUpdated(
- window_title="something_else", process_name="Code.exe",
- pid=1, is_capture_allowed=True, # Event says allowed
- )
- await tracker._on_frame_updated(ev)
- # M2-Defense: re-check stops the leak
- assert tracker._builder is None
-
-
-async def test_hard_timer_path_persists_episode_with_correct_trigger() -> None:
- """AC-3 trigger path: _maybe_flush(trigger_kind='hard_timer') persists
- the episode with trigger_kind='hard_timer'. We simulate the timer tick
- directly instead of waiting 5 real-time minutes.
- """
- tracker, manager, _, recall, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- )
- base_ns = time.time_ns() - 2_000_000_000 # 2s in the past
- f = _make_frame(ts_ns=base_ns)
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- # B1 refactor: _maybe_flush acquires its own lock — the caller must
- # NOT hold the lock anymore (otherwise deadlock on asyncio.Lock).
- await tracker._maybe_flush(trigger_kind="hard_timer")
- assert recall.episodes[0]["trigger_kind"] == "hard_timer"
-
-
-async def test_hard_timer_loop_lifecycle_starts_and_cancels_cleanly() -> None:
- """AC-3 lifecycle: _hard_timer_loop runs as a background task and cancels
- cleanly on stop() — no hanging task, no resource leak.
- """
- tracker, *_ = _make_tracker()
- assert tracker._timer_task is None
- await tracker.start()
- assert tracker._timer_task is not None
- assert not tracker._timer_task.done()
- await tracker.stop()
- assert tracker._timer_task is None # after stop the task is cleaned up
-
-
-async def test_max_duration_triggers_flush() -> None:
- """m4 fix: episode > episode_max_duration_min → forced flush.
-
- Single-frame setup: ts_ns is 2min in the past, so Builder.duration_ns
- already exceeds max_duration_min*60s on the very first add_frame. This
- gives us exactly 1 Verdichter call (deterministic).
- """
- tracker, manager, _, recall, verdichter = _make_tracker(
- story_cfg=AwarenessStoryConfig(
- episode_min_duration_s=999, # min = high, otherwise flush via min
- episode_max_duration_min=1, # max = 1min for the test
- buffer_max=999, # buffer wide enough
- ),
- )
- base_ns = time.time_ns() - (2 * 60 * 1_000_000_000) # 2min in the past
- f = _make_frame(title="long_session.py", ts_ns=base_ns)
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- # max_duration trigger fires right after add_frame —
- # Builder.duration_ns ≈ 2min > 1min hard cap.
- assert len(verdichter.calls) == 1
- assert recall.episodes[0]["trigger_kind"] == "max_duration"
-
-
-# ---- Tests: Concurrency (Codex-BLOCKER B1 + B2 Fix, 2026-05-11) ------------
-
-
-@dataclass
-class SlowVerdichter:
- """Fake Verdichter whose call blocks for ``sleep_s``.
-
- Used to reproduce the B1 lock-holding pattern — without the B1 fix
- the lock would be held for 5s and parallel _on_frame_updated calls
- would execute serially.
- """
- sleep_s: float = 0.5
- summary: str = "slow summary"
- calls_started: int = 0
- calls_completed: int = 0
-
- async def call(
- self,
- *,
- frames: list[dict[str, Any]],
- events: list[dict[str, Any]],
- primary_app: str,
- ) -> tuple[str, dict[str, Any]]:
- self.calls_started += 1
- await asyncio.sleep(self.sleep_s)
- self.calls_completed += 1
- return self.summary, {
- "tokens_in": 10, "tokens_out": 5,
- "duration_ms": int(self.sleep_s * 1000),
- }
-
-
-async def test_b1_lock_free_during_verdichter_call() -> None:
- """B1 regression (AC-strict): mock Verdichter blocks for 5s, 50 parallel
- frame pushes — test throughput < 100ms total (not 5s serial).
-
- Plan AC (JARVIS_AWARENESS_PLAN §6 follow-up AC, Codex blocker B1):
- - Verdichter sleep = 5.0s (hard AC value from the spike prompt).
- - 50 parallel pushes must complete in <0.1s (100ms). Without the
- B1 fix, push #1 alone would wait the full 5s on the lock; all 50
- serially would take ~5s * 50 = 250s.
- - With the B1 fix the lock is released BEFORE the 5s sleep — the 50
- pushes complete in <100ms.
- """
- slow = SlowVerdichter(sleep_s=5.0)
- tracker, manager, _, _, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=slow, # type: ignore[arg-type]
- )
-
- f1 = _make_frame(process="Code.exe", title="orig.py")
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
-
- # Idle → triggers slow flush in background.
- flush_task = asyncio.create_task(
- tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns())),
- )
- # Yield until the flush task has actually entered verdichter.call. We
- # poll calls_started rather than blindly spinning asyncio.sleep(0) so
- # this is not flaky on slow CI.
- for _ in range(100):
- await asyncio.sleep(0)
- if slow.calls_started >= 1:
- break
- assert slow.calls_started == 1, (
- "Pre-condition: verdichter must have entered its sleep"
- )
-
- # Hammer 50 frame updates while verdichter is blocked.
- start = time.monotonic()
- for i in range(50):
- f = _make_frame(process="Code.exe", title=f"hammer_{i}.py")
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- elapsed = time.monotonic() - start
-
- # AC-strict: 50 pushes in <100ms while verdichter still sleeps. Without
- # the B1 fix, push #1 alone would wait 5s on the lock — all 50 together
- # would have taken 250s+.
- assert elapsed < 0.1, (
- f"B1-Regression: {elapsed:.3f}s for 50 frame updates while verdichter "
- f"blocks 5s (AC: <0.1s — Lock is held over verdichter.call)"
- )
-
- # Flush task must still complete cleanly (verdichter sleep = 5s + slack).
- await asyncio.wait_for(flush_task, timeout=6.5)
- assert slow.calls_completed == 1
-
-
-async def test_b1_idle_handler_does_not_block_frame_handler() -> None:
- """B1: idle-flush + frame-update interleaved → frame-update returns immediately.
-
- Direct stress test: the idle handler keeps internal run_flush busy via
- SlowVerdichter; a parallel frame update must not wait.
- """
- slow = SlowVerdichter(sleep_s=0.4)
- tracker, manager, _, _, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=slow, # type: ignore[arg-type]
- )
- f1 = _make_frame(process="Code.exe", title="initial.py")
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
-
- idle_task = asyncio.create_task(
- tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns())),
- )
- # Let idle_task grab+release lock and start verdichter.
- await asyncio.sleep(0)
- await asyncio.sleep(0)
-
- f2 = _make_frame(process="Code.exe", title="parallel.py", ts_ns=time.time_ns())
- manager.state.current_frame = f2
- start = time.monotonic()
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f2.active_window_title,
- process_name=f2.active_process_name,
- pid=f2.active_pid, is_capture_allowed=True,
- ))
- elapsed = time.monotonic() - start
-
- # Frame handler MUST not have waited for the 0.4s verdichter — Lock
- # was released before run_flush (B1).
- assert elapsed < 0.1, (
- f"B1-Regression: frame handler took {elapsed:.3f}s while idle-flush "
- f"was holding lock (must be <0.1s)"
- )
- await asyncio.wait_for(idle_task, timeout=2.0)
-
-
-async def test_b2_no_frame_loss_during_concurrent_flush() -> None:
- """B2 regression: a frame pushed while a flush is in progress MUST end up
- in some episode (old or next) — never "lost".
-
- Setup: frame 1 opens the builder, idle triggers a flush (Verdichter
- blocks for 300ms). While the flush is in progress, a second frame is
- pushed. We expect:
- - Episode 1 contains frame 1 (frame_count == 1).
- - Frame 2 starts episode 2 (a new builder, since _builder=None after
- the atomic detach in the B1 snapshot).
- - The final flush via stop() persists episode 2 with frame 2.
- """
- slow = SlowVerdichter(sleep_s=0.3, summary="ep1")
- tracker, manager, _, recall, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- fake_verdichter=slow, # type: ignore[arg-type]
- )
- await tracker.start()
-
- try:
- f1 = _make_frame(process="Code.exe", title="ep1.py")
- manager.state.current_frame = f1
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f1.active_window_title,
- process_name=f1.active_process_name,
- pid=f1.active_pid, is_capture_allowed=True,
- ))
- await asyncio.sleep(1.1)
-
- # Trigger flush in background (verdichter blocks 300ms).
- flush_task = asyncio.create_task(
- tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns())),
- )
- # Let the flush task acquire+release the lock and reach verdichter.call.
- await asyncio.sleep(0)
- await asyncio.sleep(0.05)
-
- # Push frame 2 while verdichter is still mid-flight. WITHOUT B2-fix
- # this could land in the dying-builder buffer (lost when
- # _builder=None is set without atomic detach) or in a fresh builder
- # that gets immediately overwritten. With B2-fix the snapshot+reset
- # is atomic, so frame 2 goes into a brand-new empty builder.
- f2 = _make_frame(
- process="Code.exe",
- title="ep2.py",
- ts_ns=time.time_ns(),
- )
- manager.state.current_frame = f2
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f2.active_window_title,
- process_name=f2.active_process_name,
- pid=f2.active_pid, is_capture_allowed=True,
- ))
-
- # Wait for the in-flight flush to complete.
- await asyncio.wait_for(flush_task, timeout=2.0)
-
- # Episode 1 persisted with exactly frame_count == 1 (only f1).
- assert len(recall.episodes) == 1
- assert recall.episodes[0]["summary"] == "ep1"
- assert recall.episodes[0]["frame_count"] == 1
-
- # Frame 2 must be in the live builder (not lost).
- assert tracker._builder is not None
- live_titles = [f.active_window_title for f in tracker._builder.frames]
- assert "ep2.py" in live_titles, (
- f"B2-Regression: frame ep2.py disappeared. Live builder has "
- f"{live_titles!r}"
- )
- finally:
- # Force-flush ep2 via stop() to verify persistence.
- await tracker.stop()
-
- # Episode 2 from stop()-trigger persisted with frame 2.
- assert len(recall.episodes) == 2
- assert recall.episodes[1]["trigger_kind"] == "stop"
- assert recall.episodes[1]["frame_count"] == 1
-
-
-async def test_b2_extract_snapshot_locked_resets_builder() -> None:
- """B2: after _extract_snapshot_locked, the builder is None and all
- frames/events are in the snapshot — no double bookkeeping.
- """
- tracker, manager, _, _, _ = _make_tracker(
- story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),
- )
- f = _make_frame(title="x.py", ts_ns=time.time_ns() - 2_000_000_000)
- manager.state.current_frame = f
- await tracker._on_frame_updated(FrameUpdated(
- window_title=f.active_window_title,
- process_name=f.active_process_name,
- pid=f.active_pid, is_capture_allowed=True,
- ))
- assert tracker._builder is not None
- assert tracker._builder.frame_count == 1
-
- async with tracker._lock:
- snap = tracker._extract_snapshot_locked(trigger_kind="window_switch")
-
- assert snap is not None
- assert tracker._builder is None # B2: builder reset atomar
- assert len(snap.frames) == 1
- assert snap.frames[0]["window_title"] == "x.py"
- assert snap.primary_app == f.active_process_name
diff --git a/tests/unit/awareness/test_system_prompt_injection.py b/tests/unit/awareness/test_system_prompt_injection.py
deleted file mode 100644
index 4f7d20f3bf..0000000000
--- a/tests/unit/awareness/test_system_prompt_injection.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Phase A1 — system-prompt injection of the awareness snapshot.
-
-Plan §5 'Files to Modify' requires that ``BrainManager._build_system_prompt``
-injects a compact live snapshot from ``AwarenessManager.state`` — as a
-fallback for the case where the LLM does NOT call the
-``awareness-snapshot`` tool.
-
-AC-5 (plan verifier): the main Jarvis (router) gets the tool in its schema
-and also has the state passively in the prompt; Sub-Jarvis gets NO
-``awareness_manager`` (stateless).
-"""
-from __future__ import annotations
-
-import time
-
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.state import FrameSnapshot
-from jarvis.brain.manager import BrainManager
-from jarvis.core.bus import EventBus
-from jarvis.core.config import JarvisConfig
-
-
-def _make_brain(awareness_manager: AwarenessManager | None) -> BrainManager:
- # These tests assert the snapshot lands in the cached SYSTEM prompt. The
- # default `cache_optimized_prompt=True` deliberately moves the snapshot into
- # the per-turn user message instead (Wave-2 omni-latency), so pin the legacy
- # in-system-prompt path here to test exactly that contract.
- config = JarvisConfig()
- config.performance.cache_optimized_prompt = False
- return BrainManager(
- config=config,
- bus=EventBus(),
- tools={},
- awareness_manager=awareness_manager,
- )
-
-
-def test_no_awareness_manager_no_snapshot_in_prompt() -> None:
- """Backward compat: without ``awareness_manager``, NOTHING may be injected."""
- brain = _make_brain(awareness_manager=None)
- prompt = brain._build_system_prompt()
- assert "CURRENT CONTEXT" not in prompt
-
-
-def test_awareness_manager_with_empty_state_no_snapshot() -> None:
- """``state.snapshot_for_prompt()`` returns '' when ``current_frame is None``.
-
- In that case the injection block must NOT emit an empty
- ``CURRENT CONTEXT:`` marker — the prompt should stay clean.
- """
- mgr = AwarenessManager(AwarenessConfig.default())
- assert mgr.state.current_frame is None
- brain = _make_brain(awareness_manager=mgr)
- prompt = brain._build_system_prompt()
- assert "CURRENT CONTEXT" not in prompt
-
-
-def test_awareness_manager_with_frame_injects_snapshot() -> None:
- """A set ``current_frame`` must land in the prompt as ``CURRENT CONTEXT``."""
- mgr = AwarenessManager(AwarenessConfig.default())
- mgr.state.current_frame = FrameSnapshot(
- timestamp_ns=time.time_ns(),
- active_window_title="Editor — main.py",
- active_process_name="Code.exe",
- active_pid=12345,
- is_capture_allowed=True,
- )
-
- brain = _make_brain(awareness_manager=mgr)
- prompt = brain._build_system_prompt()
-
- assert "CURRENT CONTEXT" in prompt
- assert "Editor — main.py" in prompt
- assert "Code.exe" in prompt
- assert "pid=12345" in prompt
-
-
-def test_snapshot_failure_does_not_break_prompt_build() -> None:
- """Defensive try/except: a broken ``snapshot_for_prompt`` must not
- topple the system-prompt build."""
- mgr = AwarenessManager(AwarenessConfig.default())
-
- class _BadState:
- def snapshot_for_prompt(self, max_chars: int = 600) -> str: # noqa: ARG002
- raise RuntimeError("simulated state failure")
-
- mgr._state = _BadState() # type: ignore[assignment]
-
- brain = _make_brain(awareness_manager=mgr)
- # Must not raise
- prompt = brain._build_system_prompt()
- assert isinstance(prompt, str)
- assert len(prompt) > 0
- assert "CURRENT CONTEXT" not in prompt
diff --git a/tests/unit/awareness/test_verdichter.py b/tests/unit/awareness/test_verdichter.py
deleted file mode 100644
index b45c327035..0000000000
--- a/tests/unit/awareness/test_verdichter.py
+++ /dev/null
@@ -1,447 +0,0 @@
-"""Tests for jarvis.awareness.verdichter.Verdichter.
-
-Plan §6 AC:
-- Verdichter call with FakeBrain returns a deterministic summary
-- Timeout (5s) yields an empty summary + error_reason="timeout", does not crash
-- Token cap: for len(frames+events) > 30, the 30 newest are kept
-- Empty input (frames=[], events=[]) -> skip with error_reason="empty_input"
-- Verdichter NEVER goes through the spawn_worker mechanism (direct BrainProviderRegistry)
-"""
-from __future__ import annotations
-
-import asyncio
-import inspect
-import re
-from collections.abc import AsyncIterator
-from pathlib import Path
-
-import pytest
-
-from jarvis.awareness.config import AwarenessVerdichterConfig
-from jarvis.awareness.prompts import (
- VERDICHTER_SYSTEM_PROMPT,
- build_verdichter_prompt,
-)
-from jarvis.awareness.verdichter import MAX_FRAMES_PLUS_EVENTS, Verdichter
-from jarvis.core.protocols import BrainDelta, BrainRequest
-from tests.fixtures.brain.fake_brain import FakeBrain
-
-# ----------------------------------------------------------------------
-# Test-Helpers
-# ----------------------------------------------------------------------
-
-def _frame(ts_ns: int, process: str = "Code.exe", title: str = "main.py") -> dict:
- """Builds a frame-dict im A1-Schema (timestamp_ns)."""
- return {
- "timestamp_ns": ts_ns,
- "process_name": process,
- "window_title": title,
- }
-
-
-def _event(ts_ns: int, kind: str = "FileSaved", payload: dict | None = None) -> dict:
- """Builds an event-dict (ts_ns)."""
- out = {"ts_ns": ts_ns, "kind": kind}
- if payload is not None:
- out["payload"] = payload
- return out
-
-
-def _default_config(**overrides) -> AwarenessVerdichterConfig:
- """AwarenessVerdichterConfig with a short timeout for tests."""
- base = {
- "enabled": True,
- "provider": "claude-api",
- "model": "claude-haiku-4-5-20251001",
- "max_input_tokens": 800,
- "max_output_tokens": 200,
- "timeout_s": 1.0, # short, for fast tests
- }
- base.update(overrides)
- return AwarenessVerdichterConfig(**base)
-
-
-# ----------------------------------------------------------------------
-# Test 1: deterministischer Summary-Return
-# ----------------------------------------------------------------------
-
-async def test_call_with_fake_brain_returns_summary() -> None:
- """FakeBrain.text -> call() returnt (text, usage mit error_reason=None)."""
- brain = FakeBrain(text_response="Du arbeitest seit 12min an pipeline.py in VS Code.")
- cfg = _default_config()
- verdichter = Verdichter(brain=brain, config=cfg)
-
- frames = [_frame(1_700_000_000_000_000_000, "Code.exe", "pipeline.py")]
- events = [_event(1_700_000_001_000_000_000, "FileSaved")]
-
- summary, usage = await verdichter.call(
- frames=frames, events=events, primary_app="Code.exe",
- )
-
- assert summary == "Du arbeitest seit 12min an pipeline.py in VS Code."
- assert usage["error_reason"] is None
- assert usage["tokens_in"] == 0 # FakeBrain does not emit usage
- assert usage["tokens_out"] == 0
- assert usage["duration_ms"] >= 0
- # FakeBrain was called ONCE (no Sub-Jarvis spawn loop)
- assert len(brain.calls) == 1
- # Verify that the system prompt from prompts.py was passed through
- assert brain.calls[0].system == VERDICHTER_SYSTEM_PROMPT
-
-
-# ----------------------------------------------------------------------
-# Test 2: Empty Input
-# ----------------------------------------------------------------------
-
-async def test_call_with_empty_input_returns_empty_input_reason() -> None:
- """frames=[] + events=[] -> ('', error_reason='empty_input'), no brain call."""
- brain = FakeBrain(text_response="should not be called")
- cfg = _default_config()
- verdichter = Verdichter(brain=brain, config=cfg)
-
- summary, usage = await verdichter.call(
- frames=[], events=[], primary_app="Code.exe",
- )
-
- assert summary == ""
- assert usage["error_reason"] == "empty_input"
- assert usage["tokens_in"] == 0
- assert usage["tokens_out"] == 0
- assert usage["duration_ms"] == 0
- # NO brain call on empty input
- assert len(brain.calls) == 0
-
-
-# ----------------------------------------------------------------------
-# Test 3: Timeout
-# ----------------------------------------------------------------------
-
-class _SlowBrain:
- """Brain that deliberately sleeps longer than the timeout."""
-
- name: str = "slow-brain"
- context_window: int = 8192
- supports_tools: bool = False
- supports_vision: bool = False
-
- def __init__(self, sleep_s: float = 5.0) -> None:
- self._sleep_s = sleep_s
- self.calls: list = []
-
- async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- self.calls.append(req)
- await asyncio.sleep(self._sleep_s)
- yield BrainDelta(content="never", finish_reason="stop")
-
- def estimate_cost(self, req: BrainRequest) -> float:
- return 0.0
-
-
-async def test_call_with_timeout_returns_timeout_reason() -> None:
- """Brain schlaeft 5s, Timeout=0.1s -> ('', error_reason='timeout')."""
- brain = _SlowBrain(sleep_s=5.0)
- cfg = _default_config(timeout_s=0.1)
- verdichter = Verdichter(brain=brain, config=cfg)
-
- frames = [_frame(1_700_000_000_000_000_000)]
-
- summary, usage = await verdichter.call(
- frames=frames, events=[], primary_app="Code.exe",
- )
-
- assert summary == ""
- assert usage["error_reason"] == "timeout"
- assert usage["tokens_in"] == 0
- assert usage["tokens_out"] == 0
- # Timeout ungefaehr 100ms (Toleranz +/-)
- assert usage["duration_ms"] >= 90, f"duration_ms={usage['duration_ms']} too short"
- assert usage["duration_ms"] < 1500, f"duration_ms={usage['duration_ms']} too long"
-
-
-# ----------------------------------------------------------------------
-# Test 4: Token-Cap (max 30 Frames+Events, neueste gewinnen)
-# ----------------------------------------------------------------------
-
-class _SpyBrain:
- """Brain that stores the passed-in prompt for inspection."""
-
- name: str = "spy-brain"
- context_window: int = 8192
- supports_tools: bool = False
- supports_vision: bool = False
-
- def __init__(self) -> None:
- self.last_prompt: str = ""
- self.calls: list = []
-
- async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- self.calls.append(req)
- # Store the last message (user prompt)
- for msg in req.messages:
- if msg.role == "user" and isinstance(msg.content, str):
- self.last_prompt = msg.content
- yield BrainDelta(content="ok", finish_reason="stop")
-
- def estimate_cost(self, req: BrainRequest) -> float:
- return 0.0
-
-
-async def test_call_caps_to_30_frames_plus_events() -> None:
- """50 Frames + 0 Events -> nur 30 Frames im finalen Prompt.
-
- Strategy: NEWEST 30 (chronological tail). The oldest 20 frames are
- dropped — we verify this by looking for the "old" and "new" markers
- in the prompt.
- """
- brain = _SpyBrain()
- cfg = _default_config(max_input_tokens=10_000) # large enough, no truncation
- verdichter = Verdichter(brain=brain, config=cfg)
-
- base_ts = 1_700_000_000_000_000_000
- # 50 Frames mit aufsteigender Zeit, jedes mit Marker im Title.
- frames = [
- _frame(base_ts + i * 1_000_000_000, "Code.exe", f"file_{i:02d}.py")
- for i in range(50)
- ]
-
- summary, usage = await verdichter.call(
- frames=frames, events=[], primary_app="Code.exe",
- )
-
- assert summary == "ok"
- # Cap: max 30 Frames+Events. 50 Frames -> 30 neueste.
- assert MAX_FRAMES_PLUS_EVENTS == 30
- # Check: the old frames file_00..file_19 are missing, file_20..file_49 are present.
- prompt = brain.last_prompt
- assert "file_49.py" in prompt, "Newest frame must be in the prompt"
- assert "file_20.py" in prompt, "First non-trimmed frame must be present"
- assert "file_19.py" not in prompt, "file_19 should have been dropped (too old)"
- assert "file_00.py" not in prompt, "file_00 should have been dropped (oldest)"
- # Genau 30 Frame-Zeilen
- frame_lines = re.findall(r"^- \[\d\d:\d\d:\d\d\] Code\.exe: file_\d\d\.py$",
- prompt, flags=re.MULTILINE)
- assert len(frame_lines) == 30, f"Erwartet 30 Frame-Zeilen, gefunden {len(frame_lines)}"
-
-
-# ----------------------------------------------------------------------
-# Test 5: Brain-Error
-# ----------------------------------------------------------------------
-
-async def test_call_brain_error_returns_error_reason() -> None:
- """FakeBrain mit fail_on_call=0 -> ('', error_reason=str(exc))."""
- brain = FakeBrain(text_response="never", fail_on_call=0)
- cfg = _default_config()
- verdichter = Verdichter(brain=brain, config=cfg)
-
- frames = [_frame(1_700_000_000_000_000_000)]
-
- summary, usage = await verdichter.call(
- frames=frames, events=[], primary_app="Code.exe",
- )
-
- assert summary == ""
- assert usage["error_reason"] is not None
- # FakeBrain wirft "FakeBrain-scripted failure"
- assert "FakeBrain-scripted failure" in usage["error_reason"]
- assert usage["tokens_in"] == 0
- assert usage["tokens_out"] == 0
-
-
-# ----------------------------------------------------------------------
-# Test 6: Prompt-Format (Header + Footer)
-# ----------------------------------------------------------------------
-
-def test_build_verdichter_prompt_format() -> None:
- """Direct-Call: Header + Frame + Event + Dominante App."""
- base_ts = 1_700_000_000_000_000_000
- frames = [_frame(base_ts, "Code.exe", "main.py")]
- events = [_event(base_ts + 1_000_000_000, "FileSaved", {"path": "main.py"})]
-
- prompt = build_verdichter_prompt(
- frames=frames, events=events, primary_app="Code.exe",
- )
-
- assert "# Frames + Events der letzten Minuten:" in prompt
- assert "Dominante App: Code.exe" in prompt
- assert "Code.exe: main.py" in prompt
- assert "EVENT FileSaved" in prompt
- assert "path=main.py" in prompt
-
-
-# ----------------------------------------------------------------------
-# Test 7: Truncation-Marker
-# ----------------------------------------------------------------------
-
-def test_build_verdichter_prompt_truncation() -> None:
- """Sehr viele Frames + max_chars klein -> [...] Marker erscheint."""
- base_ts = 1_700_000_000_000_000_000
- # 100 Frames mit langen Titles
- frames = [
- _frame(base_ts + i * 1_000_000_000, "Code.exe", "x" * 200)
- for i in range(100)
- ]
-
- prompt = build_verdichter_prompt(
- frames=frames, events=[], primary_app="Code.exe",
- max_chars=500, # too small for everything
- )
-
- assert "[...]" in prompt, f"Truncation-Marker fehlt im Prompt:\n{prompt!r}"
- assert "Dominante App: Code.exe" in prompt # Footer bleibt
- assert "# Frames + Events der letzten Minuten:" in prompt # Header bleibt
- assert len(prompt) <= 500 + 50, "Truncation hat max_chars zu weit ueberschritten"
-
-
-# ----------------------------------------------------------------------
-# Test 8: spawn_worker NIEMALS — Source-Code-Audit + Behavior-Spy
-# ----------------------------------------------------------------------
-
-def _strip_string_literals_and_comments(src: str) -> str:
- """Strips Python docstrings/string literals and comments out of src.
-
- Tokenize-based. Used in the NEVER-spawn test so that hard-negative
- mentions in docstrings (e.g. "NEVER spawn_worker") don't false-positive
- trigger. We only want actual code references (imports, function
- calls, identifiers).
- """
- import io
- import token as _token_mod
- import tokenize
-
- buf = io.StringIO(src)
- out: list[str] = []
- for tok in tokenize.generate_tokens(buf.readline):
- if tok.type in (_token_mod.STRING, _token_mod.COMMENT):
- continue
- if tok.type == _token_mod.NL or tok.type == _token_mod.NEWLINE:
- out.append("\n")
- continue
- if tok.string:
- out.append(tok.string + " ")
- return "".join(out)
-
-
-def test_verdichter_NEVER_calls_spawn_worker() -> None:
- """Hard negative §6: Verdichter must NOT run via spawn_worker.
-
- Welle-4 migration: the tool used to be called ``spawn_sub_jarvis``. The
- regression guards stay active for both names, to prevent a spawn
- dependency from ever being reintroduced.
-
- Check 1 (code, not docstrings): the source code of Verdichter +
- prompts.py contains NO code reference to spawn_worker /
- spawn_sub_jarvis / SubJarvisManager / jarvis.sub_jarvis. Docstring
- mentions are allowed — we strip strings + comments via tokenize
- before matching.
- Check 2: Verdichter.__init__ accepts ``brain`` + ``config``
- directly — no hidden manager wiring.
- """
- # Check 1: source of the module (code-only, no docstrings)
- import jarvis.awareness.verdichter as v_mod
- src_code = _strip_string_literals_and_comments(inspect.getsource(v_mod))
- assert "spawn_worker" not in src_code, (
- "Verdichter CODE must not reference spawn_worker "
- "(docstring mentions would be OK)"
- )
- assert "SubJarvisManager" not in src_code, (
- "Verdichter CODE must not import/instantiate SubJarvisManager"
- )
- assert "jarvis.sub_jarvis" not in src_code, (
- "Verdichter CODE must not import jarvis.sub_jarvis"
- )
-
- # Check 2: prompts.py is also clean (code-only)
- import jarvis.awareness.prompts as p_mod
- p_code = _strip_string_literals_and_comments(inspect.getsource(p_mod))
- assert "spawn_worker" not in p_code
- assert "jarvis.sub_jarvis" not in p_code
- assert "SubJarvisManager" not in p_code
-
- # Check 3: the Verdichter class hangs directly off the Brain protocol,
- # not off a manager. inspect.signature(__init__) must have "brain".
- sig = inspect.signature(Verdichter.__init__)
- assert "brain" in sig.parameters, "Verdichter.__init__ must accept brain="
- assert "config" in sig.parameters, "Verdichter.__init__ must accept config="
- assert "manager" not in sig.parameters, (
- "Verdichter.__init__ must NOT have a manager= (otherwise Sub-Jarvis wiring)"
- )
-
- # Check 4: source file exists and lives in the awareness module
- src_file = Path(inspect.getfile(v_mod))
- assert src_file.exists()
- assert src_file.parent.name == "awareness", (
- f"verdichter.py must live in jarvis/awareness/, is in {src_file.parent}"
- )
-
-
-async def test_verdichter_brain_call_uses_brain_complete_directly() -> None:
- """Behavior check: Verdichter.call() calls brain.complete() ONCE.
-
- A Sub-Jarvis spawn would trigger multiple brain calls + a tool-use loop.
- A single brain.complete() call is the proof that this is a direct
- brain call (hard negative §6).
- """
- brain = FakeBrain(text_response="ok")
- cfg = _default_config()
- verdichter = Verdichter(brain=brain, config=cfg)
-
- frames = [_frame(1_700_000_000_000_000_000)]
-
- summary, usage = await verdichter.call(
- frames=frames, events=[], primary_app="Code.exe",
- )
-
- # EXACTLY ONE brain call (no tool-use loop, no spawn loop)
- assert len(brain.calls) == 1, (
- f"Verdichter must make only 1 brain call, found {len(brain.calls)}. "
- "More calls = tool-use loop = probably a Sub-Jarvis spawn."
- )
- # Request has NO tools (a Sub-Jarvis spawn would be a tool)
- assert brain.calls[0].tools == (), (
- "Verdichter BrainRequest must NOT have tools (otherwise tool-use loop)"
- )
- assert summary == "ok"
-
-
-async def test_verdichter_latency_p95_under_2s() -> None:
- """Plan §6 AC: Verdichter call p95 < 2s.
-
- 100 calls with FakeBrain (deterministic response, no network).
- Verifies that the Verdichter implementation itself (prompt build,
- stream aggregate, asyncio overhead) does not introduce a path latency
- > 2s.
-
- Real latency regression against the Anthropic API is out of scope
- (needs an API key, is network-dependent). This test guards against
- Verdichter implementation regressions (e.g. an unbounded loop in the
- prompt builder, blocking I/O that stalls the asyncio loop).
- """
- import time as _time
-
- brain = FakeBrain(text_response="OK")
- cfg = _default_config()
- verdichter = Verdichter(brain=brain, config=cfg)
-
- frames = [_frame(_time.time_ns() - i * 100_000_000) for i in range(5)]
-
- durations_ms: list[float] = []
- for _ in range(100):
- start_ns = _time.time_ns()
- await verdichter.call(
- frames=frames, events=[], primary_app="Code.exe",
- )
- durations_ms.append((_time.time_ns() - start_ns) / 1_000_000.0)
-
- durations_ms.sort()
- p95_idx = int(len(durations_ms) * 0.95)
- p95_ms = durations_ms[p95_idx]
- assert p95_ms < 2000.0, (
- f"Verdichter p95 = {p95_ms:.1f}ms > 2000ms (AC Plan §6). "
- f"durations_ms head/tail = {durations_ms[:3]} / {durations_ms[-3:]}"
- )
diff --git a/tests/unit/awareness/test_window_watcher.py b/tests/unit/awareness/test_window_watcher.py
deleted file mode 100644
index dc3d3fb44f..0000000000
--- a/tests/unit/awareness/test_window_watcher.py
+++ /dev/null
@@ -1,815 +0,0 @@
-"""Tests for jarvis.awareness.watchers.window.WindowFocusWatcher.
-
-Strategy: fake pump (no real Win32 hook) plus an injected
-``_resolve_window_meta`` plus a direct call to ``_drain_once()``. This lets
-tests run on any platform; the real hook lifecycle is in the integration
-test ``test_a1_e2e.py``.
-
-Architecture assumptions the Wave 3 implementation dictates:
-- ``_drain_once()`` is isolatable (one iteration of the drain loop).
-- ``_safe_enqueue((ts_ns, hwnd))`` pushes items onto the queue (asyncio-thread-safe).
-- ``_resolve_window_meta(hwnd)`` is a staticmethod — patchable.
-- ``_loop`` is a property set in tests before _safe_enqueue.
-"""
-from __future__ import annotations
-
-import asyncio
-import os
-import time
-from types import SimpleNamespace
-from unittest.mock import patch
-
-import pytest
-
-import jarvis.awareness.watchers.window as window_mod
-from jarvis.awareness.config import AwarenessConfig
-from jarvis.awareness.manager import AwarenessManager
-from jarvis.awareness.privacy import PrivacyFilter
-from jarvis.awareness.watchers.window import WindowFocusWatcher
-from jarvis.core.bus import EventBus
-from jarvis.core.events import AwarenessCaptureBlocked, FrameUpdated
-from jarvis.platform.window_state import WindowInfo
-
-
-def _make_components() -> tuple[EventBus, AwarenessManager, PrivacyFilter]:
- cfg = AwarenessConfig.default()
- bus = EventBus()
- manager = AwarenessManager(cfg)
- privacy = PrivacyFilter(cfg)
- return bus, manager, privacy
-
-
-def _async_collect(target: list):
- """Test helper: returns an async handler that appends events to the list."""
- async def _handler(ev):
- target.append(ev)
- return _handler
-
-
-async def test_drain_routes_allowed_to_frame_updated() -> None:
- """Frame mit allowed Privacy → FrameUpdated published."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("pipeline.py - Visual Studio Code", 1234, "code.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 999))
- await watcher._drain_once()
-
- assert len(received) == 1
- assert received[0].process_name == "code.exe"
- assert received[0].is_capture_allowed is True
-
-
-async def test_drain_routes_blocked_to_capture_blocked() -> None:
- """Frame with a banking title → AwarenessCaptureBlocked, NO FrameUpdated."""
- bus, manager, privacy = _make_components()
- blocked: list[AwarenessCaptureBlocked] = []
- updated: list[FrameUpdated] = []
- bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))
- bus.subscribe(FrameUpdated, _async_collect(updated))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("Sparkasse Online-Banking", 5678, "firefox.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 999))
- await watcher._drain_once()
-
- assert len(blocked) == 1
- assert len(updated) == 0
- assert "matched_blocked_title" in blocked[0].reason
-
-
-async def test_dedupe_50ms_window() -> None:
- """Duplicate hwnd <50ms apart gets dropped — Win32 sometimes emits 2-3."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("My Doc - Notepad", 1, "notepad.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- ts = time.time_ns()
- watcher._safe_enqueue((ts, 100))
- await watcher._drain_once()
- watcher._safe_enqueue((ts + 10_000_000, 100)) # 10ms spaeter
- await watcher._drain_once()
-
- assert len(received) == 1
-
-
-async def test_dedupe_does_not_drop_different_hwnd() -> None:
- """Different hwnds within <50ms are NOT deduplicated."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: (f"hwnd-{hwnd}", hwnd, "notepad.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- ts = time.time_ns()
- watcher._safe_enqueue((ts, 100))
- await watcher._drain_once()
- watcher._safe_enqueue((ts + 10_000_000, 200)) # anderer hwnd
- await watcher._drain_once()
-
- assert len(received) == 2
-
-
-async def test_queue_full_increments_drops_no_crash() -> None:
- """When the queue is full: drop counter +1, no crash, no exception."""
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- watcher._loop = asyncio.get_running_loop()
-
- # Queue ueberlaufen lassen (maxsize=64)
- for i in range(80):
- watcher._safe_enqueue((time.time_ns() + i, i))
-
- assert watcher._drops > 0
-
-
-async def test_publish_updates_state_current_frame() -> None:
- """After drain: manager.state.current_frame is set."""
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("Test - Notepad", 999, "notepad.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 100))
- await watcher._drain_once()
-
- assert manager.state.current_frame is not None
- assert manager.state.current_frame.active_window_title == "Test - Notepad"
- assert manager.state.current_frame.active_process_name == "notepad.exe"
-
-
-async def test_start_idempotent_on_linux() -> None:
- """On Linux: start() is a no-op, no Win32 crash, a duplicate call is ok."""
- if os.name == "nt":
- pytest.skip("Linux-only — Win32-start startet echten Pump-Thread")
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.start()
- await watcher.start() # no crash
- await watcher.stop()
-
-
-async def test_stop_idempotent_no_start() -> None:
- """stop() ohne start() ist no-op."""
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.stop() # no crash, no hang
- await watcher.stop()
-
-
-async def test_unresolvable_window_is_not_published_as_a_frame() -> None:
- """``_resolve_window_meta`` answers ("", 0, "") for a probe that failed.
-
- Publishing that handed PrivacyFilter two empty strings, which match no
- block pattern and fall through to ``default_allow_for_unknown`` — so an
- unidentifiable window was waved through AND overwrote
- ``state.current_frame``, blanking the foreground context the brain reads.
- The POSIX poller already refused exactly this; Win32 never did.
- """
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- blocked: list[AwarenessCaptureBlocked] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
- bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("", 0, "")),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 100))
- await watcher._drain_once()
-
- assert received == []
- assert blocked == []
- assert manager.state.current_frame is None
-
-
-async def test_a_title_less_window_still_publishes_when_the_process_is_known() -> None:
- """Only a TOTALLY unreadable probe is discarded: a window with no caption
- but a known owner still says which app is focused, and the process-based
- privacy rules can act on it."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("", 4321, "notepad.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 100))
- await watcher._drain_once()
-
- assert len(received) == 1
- assert received[0].process_name == "notepad.exe"
-
-
-async def test_a_backward_clock_step_does_not_dedupe_away_later_frames() -> None:
- """The dedupe delta comes from the WALL clock, which can step backwards
- (NTP correction, a resumed VM). A negative delta is also "< 50 ms", so one
- backward step used to swallow every further event for the focused window
- and freeze focus tracking on that app until the clock caught up."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta",
- staticmethod(lambda hwnd: ("My Doc - Notepad", 1, "notepad.exe")),
- ):
- watcher._loop = asyncio.get_running_loop()
- ts = time.time_ns()
- watcher._safe_enqueue((ts, 100))
- await watcher._drain_once()
- # The clock jumps a minute back; the same window is focused again.
- watcher._safe_enqueue((ts - 60_000_000_000, 100))
- await watcher._drain_once()
-
- assert len(received) == 2
-
-
-async def test_resolve_meta_failure_skips_frame_no_crash() -> None:
- """If _resolve_window_meta raises: the frame is dropped, no crash."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- def _raises(hwnd: int) -> tuple[str, int, str]:
- raise RuntimeError("simulated failure")
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_resolve_window_meta", staticmethod(_raises),
- ):
- watcher._loop = asyncio.get_running_loop()
- watcher._safe_enqueue((time.time_ns(), 100))
- await watcher._drain_once()
-
- assert len(received) == 0
-
-
-# ---- POSIX polling fallback (macOS/Linux) -----------------------------------
-# Platform behavior is simulated by monkeypatching the resolvers window.py
-# imports (detect_platform / display_present / is_wayland) so these tests run
-# deterministically on any host, including this Windows dev machine.
-
-
-async def test_posix_start_degrades_honestly_on_headless_linux(monkeypatch) -> None:
- """start() on a headless Linux host logs one line and starts no poll task."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod, "display_present", lambda: False)
- monkeypatch.setattr(window_mod, "is_wayland", lambda: False)
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.start()
-
- assert watcher._poll_task is None
- await watcher.stop() # idempotent no-op, no crash, no hang
-
-
-async def test_posix_start_degrades_honestly_on_wayland(monkeypatch) -> None:
- """start() on a Wayland session logs one line and starts no poll task."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod, "display_present", lambda: True)
- monkeypatch.setattr(window_mod, "is_wayland", lambda: True)
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.start()
-
- assert watcher._poll_task is None
- await watcher.stop()
-
-
-async def test_posix_start_polls_on_macos(monkeypatch) -> None:
- """macOS always has a display — start() always starts the poll task."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),
- ):
- await watcher.start()
- assert watcher._poll_task is not None
- await watcher.stop()
-
- assert watcher._poll_task is None
-
-
-async def test_posix_poll_once_emits_on_focus_change() -> None:
- """A changed foreground window publishes exactly one FrameUpdated."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Terminal", handle=42)),
- ), patch.object(
- WindowFocusWatcher, "_resolve_posix_focus_meta",
- staticmethod(lambda win: (123, "Terminal.app")),
- ):
- ok_first = await watcher._poll_once()
- ok_second = await watcher._poll_once() # unchanged focus — no re-emit
-
- assert ok_first is True
- assert ok_second is True
- assert len(received) == 1
- assert received[0].process_name == "Terminal.app"
- assert received[0].pid == 123
- assert manager.state.current_frame is not None
- assert manager.state.current_frame.active_window_title == "Terminal"
-
-
-async def test_posix_poll_once_detects_a_second_focus_change() -> None:
- """Two distinct focus changes publish two distinct events."""
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- windows = iter([
- WindowInfo(title="Terminal", handle=1),
- WindowInfo(title="Browser", handle=2),
- ])
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: next(windows)),
- ), patch.object(
- WindowFocusWatcher, "_resolve_posix_focus_meta",
- staticmethod(lambda win: (1, "some.app")),
- ):
- await watcher._poll_once()
- await watcher._poll_once()
-
- assert len(received) == 2
- assert received[0].window_title == "Terminal"
- assert received[1].window_title == "Browser"
-
-
-async def test_posix_poll_once_routes_blocked_title_to_capture_blocked() -> None:
- """A privacy-blocked title publishes AwarenessCaptureBlocked, not FrameUpdated."""
- bus, manager, privacy = _make_components()
- blocked: list[AwarenessCaptureBlocked] = []
- updated: list[FrameUpdated] = []
- bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))
- bus.subscribe(FrameUpdated, _async_collect(updated))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Sparkasse Online-Banking", handle=9)),
- ), patch.object(
- WindowFocusWatcher, "_resolve_posix_focus_meta",
- staticmethod(lambda win: (55, "firefox")),
- ):
- await watcher._poll_once()
-
- assert len(blocked) == 1
- assert len(updated) == 0
-
-
-async def test_posix_poll_once_returns_false_on_no_window() -> None:
- """No usable window info → _poll_once reports a failure, no crash."""
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),
- ):
- ok = await watcher._poll_once()
- assert ok is False
-
-
-async def test_posix_poll_once_returns_false_on_probe_exception() -> None:
- """A raising probe is a failure too, not a crash."""
- def _raises() -> WindowInfo | None:
- raise RuntimeError("simulated Quartz failure")
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window", staticmethod(_raises),
- ):
- ok = await watcher._poll_once()
- assert ok is False
-
-
-async def test_posix_poll_loop_stops_after_max_consecutive_failures(monkeypatch) -> None:
- """The poll loop self-disables after consecutive empty probes instead of
- spinning forever."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod, "display_present", lambda: True)
- monkeypatch.setattr(window_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window", staticmethod(lambda: None),
- ):
- await watcher.start()
- assert watcher._poll_task is not None
- await asyncio.wait_for(watcher._poll_task, timeout=5.0)
-
- # The loop returned on its own (self-disabled) rather than being cancelled.
- assert watcher._poll_task.done()
- assert not watcher._poll_task.cancelled()
- await watcher.stop() # idempotent cleanup, no crash
-
-
-async def test_posix_poll_loop_keeps_going_after_a_success(monkeypatch) -> None:
- """An empty probe after a working one is "nothing is focused", not a failure.
-
- ``xdotool getactivewindow`` exits non-zero whenever no client window holds
- the X11 input focus — the user is on the desktop, a window just closed, a
- lock screen is up. Those are everyday states, and counting them meant 10 s
- on the wallpaper permanently killed focus tracking for the whole session
- while the log blamed a missing xdotool.
- """
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod, "display_present", lambda: True)
- monkeypatch.setattr(window_mod, "is_wayland", lambda: False)
- monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)
-
- # One usable window, then far more empty probes than the startup gate allows.
- target = window_mod._POSIX_POLL_MAX_FAILURES * 3
- reached = asyncio.Event()
- loop = asyncio.get_running_loop()
- state = {"calls": 0}
-
- def _probe() -> WindowInfo | None:
- # Runs on a worker thread (asyncio.to_thread) — signal back thread-safely.
- state["calls"] += 1
- if state["calls"] > target:
- loop.call_soon_threadsafe(reached.set)
- return WindowInfo(title="Terminal", handle=1, pid=5) if state["calls"] == 1 else None
-
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window", staticmethod(_probe),
- ):
- await watcher.start()
- task = watcher._poll_task
- assert task is not None
- await asyncio.wait_for(reached.wait(), timeout=5.0)
- assert not task.done(), "the loop self-disabled on a healthy empty probe"
- await watcher.stop()
-
-
-async def test_posix_poll_loop_survives_a_raising_iteration(monkeypatch) -> None:
- """A single bad iteration must not end focus tracking silently.
-
- Only ``CancelledError`` was caught, so anything else killed the task with an
- unretrieved exception and no log line — the feature was simply off.
- """
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
- monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)
-
- real_poll_once = WindowFocusWatcher._poll_once
- state = {"calls": 0}
-
- async def _flaky_poll_once(self) -> bool:
- state["calls"] += 1
- if state["calls"] == 1:
- raise RuntimeError("simulated iteration failure")
- return await real_poll_once(self)
-
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- published = asyncio.Event()
-
- async def _collect(ev) -> None:
- received.append(ev)
- published.set()
-
- bus.subscribe(FrameUpdated, _collect)
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_poll_once", _flaky_poll_once,
- ), patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Terminal", handle=1, pid=5)),
- ):
- await watcher.start()
- task = watcher._poll_task
- assert task is not None
- # The loop only reaches a publish if it survived the raising iteration.
- await asyncio.wait_for(published.wait(), timeout=5.0)
- assert not task.done()
- await watcher.stop()
-
- assert [ev.window_title for ev in received] == ["Terminal"]
-
-
-async def test_posix_poll_once_retries_a_window_whose_emit_failed() -> None:
- """A failed publish must not mark the window as already reported.
-
- Committing the change-detection markers before the emit turned a transient
- tail failure into a permanent one: the next tick saw an unchanged focus and
- stayed quiet, so ``state.current_frame`` kept describing the PREVIOUS window
- until the user happened to switch again.
- """
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- attempts = {"n": 0}
-
- def _meta(win: WindowInfo) -> tuple[int, str]:
- attempts["n"] += 1
- if attempts["n"] == 1:
- raise RuntimeError("transient psutil failure")
- return 123, "gnome-terminal-server"
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Terminal", handle=42)),
- ), patch.object(
- WindowFocusWatcher, "_resolve_posix_focus_meta", staticmethod(_meta),
- ):
- assert await watcher._poll_once() is True # probe healthy, emit failed
- assert received == []
- assert await watcher._poll_once() is True # same window, retried
-
- assert len(received) == 1
- assert received[0].window_title == "Terminal"
- assert manager.state.current_frame is not None
- assert manager.state.current_frame.active_pid == 123
-
-
-# ---- Linux X11 pid resolution -----------------------------------------------
-
-
-def test_linux_window_pid_returns_zero_without_xdotool(monkeypatch) -> None:
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
- assert window_mod._linux_window_pid(7) == 0
-
-
-def test_linux_window_pid_reads_the_reported_pid(monkeypatch) -> None:
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
- monkeypatch.setattr(
- window_mod.subprocess, "run",
- lambda *_a, **_kw: SimpleNamespace(returncode=0, stdout="4242\n", stderr=""),
- )
- assert window_mod._linux_window_pid(7) == 4242
-
-
-def test_linux_window_pid_uses_the_resolved_executable(monkeypatch) -> None:
- """Spawn the binary ``which`` found, not a bare name re-resolved via PATH."""
- seen: list[list[str]] = []
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/opt/bin/xdotool")
-
- def _run(argv, **_kw):
- seen.append(argv)
- return SimpleNamespace(returncode=0, stdout="9\n", stderr="")
-
- monkeypatch.setattr(window_mod.subprocess, "run", _run)
- assert window_mod._linux_window_pid(7) == 9
- assert seen == [["/opt/bin/xdotool", "getwindowpid", "7"]]
-
-
-def test_linux_window_pid_degrades_on_a_window_without_the_pid_property(
- monkeypatch,
-) -> None:
- """xdotool exits non-zero for a client that publishes no ``_NET_WM_PID``.
-
- Routine, not an error — it must not surface as a resolution failure with a
- traceback that buries the real ones.
- """
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
- monkeypatch.setattr(
- window_mod.subprocess, "run",
- lambda *_a, **_kw: SimpleNamespace(
- returncode=1, stdout="", stderr="xdotool: window has no pid property",
- ),
- )
- assert window_mod._linux_window_pid(7) == 0
-
-
-def test_linux_window_pid_degrades_on_unusable_output(monkeypatch) -> None:
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
- for stdout in ("", "not-a-pid", "-3"):
- monkeypatch.setattr(
- window_mod.subprocess, "run",
- lambda *_a, _out=stdout, **_kw: SimpleNamespace(
- returncode=0, stdout=_out, stderr="",
- ),
- )
- assert window_mod._linux_window_pid(7) == 0
-
-
-def test_linux_window_pid_degrades_when_the_probe_times_out(monkeypatch) -> None:
- """A hung X connection must not propagate out of a poll-loop worker thread."""
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
-
- def _timeout(*_a, **_kw):
- raise window_mod.subprocess.TimeoutExpired(cmd="xdotool", timeout=5.0)
-
- monkeypatch.setattr(window_mod.subprocess, "run", _timeout)
- assert window_mod._linux_window_pid(7) == 0
-
-
-def test_posix_focus_meta_never_reports_a_negative_pid(monkeypatch) -> None:
- """A negative pid looks resolved but names no process."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
- monkeypatch.setattr(
- window_mod.subprocess, "run",
- lambda *_a, **_kw: SimpleNamespace(returncode=0, stdout="-1", stderr=""),
- )
- assert WindowFocusWatcher._resolve_posix_focus_meta(
- WindowInfo(title="x", handle=5),
- ) == (0, "")
-
-
-async def test_posix_stop_without_start_is_noop() -> None:
- """stop() without a prior start() is a no-op on the POSIX path too."""
- bus, manager, privacy = _make_components()
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- await watcher.stop()
- await watcher.stop()
-
-
-async def test_posix_poll_once_treats_a_titleless_window_as_a_healthy_probe() -> None:
- """A window with no readable title is not a dead backend.
-
- X11 windows legitimately carry no name, and xdotool's getwindowname can
- fail for one window while getactivewindow keeps working. Counting that as
- a failure meant five such polls (10 s) permanently disabled focus tracking
- for the rest of the session. Nothing is published either — an empty title
- is unidentifiable and must never be handed to the privacy filter.
- """
- bus, manager, privacy = _make_components()
- updated: list[FrameUpdated] = []
- blocked: list[AwarenessCaptureBlocked] = []
- bus.subscribe(FrameUpdated, _async_collect(updated))
- bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title=" ", handle=7)),
- ):
- assert await watcher._poll_once() is True
- assert await watcher._poll_once() is True
-
- assert updated == []
- assert blocked == []
-
-
-async def test_stop_discards_queued_frames_and_stale_focus_state(monkeypatch) -> None:
- """A restart must not replay pre-stop frames, and must not swallow the
- first genuine frame after it as "unchanged".
-
- Queue and change-detection markers live on the instance, so both used to
- survive a stop/start cycle (awareness toggled off and on in Settings):
- stale payloads were published as fresh frames, and the poller then saw the
- unchanged foreground window as "already reported" and emitted nothing —
- leaving ``state.current_frame`` frozen until the user switched windows.
- """
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Terminal", handle=42)),
- ), patch.object(
- WindowFocusWatcher, "_resolve_posix_focus_meta",
- staticmethod(lambda win: (123, "Terminal.app")),
- ):
- watcher._started = True
- await watcher._poll_once()
- watcher._safe_enqueue((time.time_ns(), 4242)) # frame captured pre-stop
-
- await watcher.stop()
- assert watcher._queue.empty()
- assert watcher._poll_last_handle is None
- assert watcher._poll_last_title == ""
- assert watcher._last_hwnd == 0
-
- watcher._started = True
- await watcher._poll_once() # same window, fresh run → must re-emit
-
- assert len(received) == 2
-
-
-async def test_posix_focus_meta_uses_the_pid_the_probe_already_resolved(
- monkeypatch,
-) -> None:
- """Title and process identity must come from the SAME instant.
-
- ``window_state.foreground_window`` fills ``WindowInfo.pid`` from the very
- window it read the title off. Asking "who is frontmost NOW" a second time
- instead paired app A's title with app B's process whenever focus moved in
- between — a 2 s poll leaves that gap wide open — and the PrivacyFilter then
- judged a title against the wrong process name in both directions.
- """
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
-
- def _must_not_run():
- raise AssertionError("re-queried the frontmost app instead of using win.pid")
-
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: _must_not_run())
-
- pid, _name = WindowFocusWatcher._resolve_posix_focus_meta(
- WindowInfo(title="Notes", handle=7, pid=4242),
- )
-
- assert pid == 4242
-
-
-async def test_posix_focus_meta_degrades_to_zero_without_a_probe_pid(
- monkeypatch,
-) -> None:
- """No pid from the probe and no usable backend → (0, ""), never a raise."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
-
- assert WindowFocusWatcher._resolve_posix_focus_meta(
- WindowInfo(title="untitled", handle=9),
- ) == (0, "")
-
-
-async def test_posix_poll_emits_the_probe_pid_end_to_end(monkeypatch) -> None:
- """The published frame carries the probe's own pid, not a re-query."""
- monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
- monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
-
- bus, manager, privacy = _make_components()
- received: list[FrameUpdated] = []
- bus.subscribe(FrameUpdated, _async_collect(received))
-
- watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
- with patch.object(
- WindowFocusWatcher, "_posix_foreground_window",
- staticmethod(lambda: WindowInfo(title="Terminal", handle=3, pid=777)),
- ):
- assert await watcher._poll_once() is True
-
- assert len(received) == 1
- assert received[0].pid == 777
diff --git a/tests/unit/awareness/test_working_set.py b/tests/unit/awareness/test_working_set.py
deleted file mode 100644
index 81c895a577..0000000000
--- a/tests/unit/awareness/test_working_set.py
+++ /dev/null
@@ -1,253 +0,0 @@
-"""Unit tests for Phase A4 ``WorkingSet`` (jarvis/awareness/working_set.py).
-
-Spec: JARVIS_AWARENESS_PLAN.md §8.
-
-Tests:
-- LRU eviction at full capacity (>5 slots).
-- Re-promotion on re-activation (A → B → A).
-- ``set_episode`` linkage with the active slot.
-- Eviction deletes NO episodes (only the RAM pointer).
-- Render format for the system prompt (multi-context vs. single-context).
-
-Convention: fakes instead of mocks, pure unit tests without async/IO.
-"""
-from __future__ import annotations
-
-from jarvis.awareness.context import Context
-from jarvis.awareness.working_set import DEFAULT_MAX_SLOTS, WorkingSet
-
-
-def _ctx(
- root: str,
- *,
- label: str = "task",
- episode_id: int | None = None,
- last_seen_ns: int = 0,
- process: str = "",
-) -> Context:
- return Context(
- project_root=root,
- task_label=label,
- last_episode_id=episode_id,
- last_seen_ns=last_seen_ns,
- process_name=process,
- )
-
-
-# ---- Basic Lifecycle -------------------------------------------------------
-
-
-def test_working_set_starts_empty() -> None:
- ws = WorkingSet()
- assert ws.size == 0
- assert ws.current is None
- assert ws.contexts() == []
-
-
-def test_default_max_slots_is_five() -> None:
- """Plan §8: Working Set max 5 LRU-Slots."""
- assert DEFAULT_MAX_SLOTS == 5
- assert WorkingSet().max_slots == 5
-
-
-def test_max_slots_validation() -> None:
- import pytest
-
- with pytest.raises(ValueError):
- WorkingSet(max_slots=0)
- with pytest.raises(ValueError):
- WorkingSet(max_slots=-1)
-
-
-# ---- Observe + LRU --------------------------------------------------------
-
-
-def test_observe_inserts_new_context() -> None:
- ws = WorkingSet()
- ctx = _ctx("repo-a", label="main.py")
- evicted = ws.observe(ctx)
- assert evicted is None
- assert ws.size == 1
- assert "repo-a" in ws
- assert ws.get("repo-a") == ctx
-
-
-def test_observe_promotes_existing_context() -> None:
- """Re-Promotion: bekannter project_root wandert ans Ende der LRU."""
- ws = WorkingSet(max_slots=3)
- a = _ctx("a", label="a-task")
- b = _ctx("b", label="b-task")
- c = _ctx("c", label="c-task")
- ws.observe(a)
- ws.observe(b)
- ws.observe(c)
- # c ist juengster, a ist aeltester.
- assert [ctx.project_root for ctx in ws.contexts()] == ["c", "b", "a"]
-
- # Re-Activation von a → a wandert ans MRU-Ende.
- ws.observe(_ctx("a", label="a-task-v2"))
- assert [ctx.project_root for ctx in ws.contexts()] == ["a", "c", "b"]
-
-
-def test_observe_evicts_oldest_when_full() -> None:
- """Plan §8 Eviction: > max_slots → aeltester fliegt raus."""
- ws = WorkingSet(max_slots=3)
- ws.observe(_ctx("a"))
- ws.observe(_ctx("b"))
- ws.observe(_ctx("c"))
- # Vierter Context → evictet "a".
- evicted = ws.observe(_ctx("d"))
- assert evicted is not None
- assert evicted.project_root == "a"
- assert ws.size == 3
- assert "a" not in ws
- assert "d" in ws
-
-
-def test_observe_seven_contexts_with_max_five_evicts_oldest_two() -> None:
- """7 context switches with max=5: the oldest slot flies out, 5 remain.
-
- Acceptance criterion: "Test with 7 context switches: the oldest
- context entry flies out of the working set, all 7 episodes in the
- DB unchanged."
- """
- ws = WorkingSet(max_slots=5)
- inserted = ["c1", "c2", "c3", "c4", "c5", "c6", "c7"]
- evicted_roots: list[str] = []
- for r in inserted:
- evicted = ws.observe(_ctx(r))
- if evicted is not None:
- evicted_roots.append(evicted.project_root)
- # c1 is evicted by c6, c2 by c7.
- assert evicted_roots == ["c1", "c2"]
- assert ws.size == 5
- assert [ctx.project_root for ctx in ws.contexts()] == ["c7", "c6", "c5", "c4", "c3"]
-
-
-def test_promote_a_then_b_then_a() -> None:
- """A→B→A: A landet wieder oben in MRU, snapshot zeigt A als current."""
- ws = WorkingSet(max_slots=5)
- a = _ctx("a", label="a-work")
- b = _ctx("b", label="b-work")
- ws.observe(a)
- ws.observe(b)
- assert ws.current.project_root == "b"
-
- ws.observe(_ctx("a", label="a-work-resumed"))
- assert ws.current.project_root == "a"
- # task_label from the last observe overwrites
- assert ws.current.task_label == "a-work-resumed"
-
-
-# ---- set_episode ----------------------------------------------------------
-
-
-def test_set_episode_updates_existing_slot() -> None:
- ws = WorkingSet()
- ws.observe(_ctx("a"))
- ws.set_episode("a", 42)
- assert ws.get("a").last_episode_id == 42
-
-
-def test_set_episode_returns_false_for_unknown_root() -> None:
- """If the slot has been evicted, set_episode swallows it silently."""
- ws = WorkingSet(max_slots=2)
- ws.observe(_ctx("a"))
- ws.observe(_ctx("b"))
- ws.observe(_ctx("c")) # evicts "a"
- assert ws.set_episode("a", 99) is False
- # b and c are unchanged
- assert ws.get("b").last_episode_id is None
-
-
-def test_set_episode_does_not_promote() -> None:
- """set_episode only updates the episode ID, NOT the LRU order."""
- ws = WorkingSet(max_slots=3)
- ws.observe(_ctx("a"))
- ws.observe(_ctx("b"))
- ws.observe(_ctx("c"))
- # c is current, a is the oldest.
- ws.set_episode("a", 11)
- # Order unchanged: c stays MRU, a stays LRU.
- assert [ctx.project_root for ctx in ws.contexts()] == ["c", "b", "a"]
-
-
-def test_observe_preserves_existing_episode_when_new_is_none() -> None:
- """Re-Activation ohne neue Episode-ID: alte ID bleibt erhalten."""
- ws = WorkingSet()
- ws.observe(_ctx("a", episode_id=7))
- ws.observe(_ctx("a", episode_id=None))
- assert ws.get("a").last_episode_id == 7
-
-
-def test_observe_overwrites_episode_when_new_is_set() -> None:
- """When a new context sets a new episode ID, it overwrites the old one."""
- ws = WorkingSet()
- ws.observe(_ctx("a", episode_id=7))
- ws.observe(_ctx("a", episode_id=12))
- assert ws.get("a").last_episode_id == 12
-
-
-# ---- Render ---------------------------------------------------------------
-
-
-def test_render_for_prompt_empty_returns_empty_string() -> None:
- assert WorkingSet().render_for_prompt() == ""
-
-
-def test_render_for_prompt_single_slot_returns_empty_string() -> None:
- """Single-Context = redundant zur "letzte Episode"-Zeile, no render."""
- ws = WorkingSet()
- ws.observe(_ctx("a", label="solo"))
- assert ws.render_for_prompt() == ""
-
-
-def test_render_for_prompt_multi_slot_includes_all_contexts() -> None:
- ws = WorkingSet(max_slots=5)
- ws.observe(_ctx("repo-jarvis", label="awareness/working_set.py"))
- ws.observe(_ctx("slack.com", label="DMs Sarah"))
- ws.set_episode("repo-jarvis", 42)
- ws.set_episode("slack.com", 43)
-
- text = ws.render_for_prompt()
-
- assert "Active contexts" in text
- assert "repo-jarvis" in text
- assert "slack.com" in text
- # Episode IDs are displayed too
- assert "Episode #42" in text
- assert "Episode #43" in text
-
-
-def test_render_for_prompt_truncates_to_max_chars() -> None:
- ws = WorkingSet(max_slots=5)
- for i in range(5):
- ws.observe(_ctx(
- f"very-long-project-root-{i}-" + "x" * 50,
- label=f"task-with-a-rather-long-label-{i}",
- ))
- text = ws.render_for_prompt(max_chars=80)
- assert len(text) <= 80
- assert text.endswith("…")
-
-
-# ---- Eviction Hard-Negative: Episodes Survive ------------------------------
-
-
-def test_eviction_does_not_affect_episode_id_field() -> None:
- """Plan §8 hard negative: eviction = only the RAM pointer goes away, the
- episode stays in the DB. Here: on eviction only the WorkingSet slot
- goes away, the last_episode_id value is still visible on the evicted
- object (verifies that we do not wipe data).
- """
- ws = WorkingSet(max_slots=2)
- ws.observe(_ctx("a"))
- ws.set_episode("a", 100)
- ws.observe(_ctx("b"))
- evicted = ws.observe(_ctx("c")) # evicts "a"
- assert evicted is not None
- assert evicted.project_root == "a"
- # The episode ID of the evicted slot is still there — a caller could
- # react to it (e.g. audit). We ONLY verify that no delete calls
- # happen — the test itself has no DB.
- assert evicted.last_episode_id == 100
diff --git a/tests/unit/brain/test_ack_generator.py b/tests/unit/brain/test_ack_generator.py
index 56e7fa9371..7ecc157043 100644
--- a/tests/unit/brain/test_ack_generator.py
+++ b/tests/unit/brain/test_ack_generator.py
@@ -124,9 +124,8 @@ class TestSkipList:
assert generate_ack(tool_name, {}, picker=_fresh()) is None
def test_hyphenated_skip_tool_also_returns_none(self) -> None:
- # Awareness-snapshot is registered with hyphens in ROUTER_TOOLS;
- # normalization must catch both spellings.
- assert generate_ack("awareness-snapshot", {}, picker=_fresh()) is None
+ # Router tools are registered with hyphens; normalization must catch
+ # both spellings.
assert generate_ack("screen-snapshot", {}, picker=_fresh()) is None
def test_fast_wiki_reads_are_skipped(self) -> None:
diff --git a/tests/unit/brain/test_active_model_awareness.py b/tests/unit/brain/test_active_model_awareness.py
index 04c9776ef6..244285adea 100644
--- a/tests/unit/brain/test_active_model_awareness.py
+++ b/tests/unit/brain/test_active_model_awareness.py
@@ -28,7 +28,6 @@ def _manager(*, wake_phrase: str = "Hey Jarvis") -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_agent_instructions_in_manager.py b/tests/unit/brain/test_agent_instructions_in_manager.py
index 8b51a806b1..271e278a30 100644
--- a/tests/unit/brain/test_agent_instructions_in_manager.py
+++ b/tests/unit/brain/test_agent_instructions_in_manager.py
@@ -23,7 +23,6 @@ def _manager() -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_custom_system_prompt_in_manager.py b/tests/unit/brain/test_custom_system_prompt_in_manager.py
index e30d3ae499..9b2adecee9 100644
--- a/tests/unit/brain/test_custom_system_prompt_in_manager.py
+++ b/tests/unit/brain/test_custom_system_prompt_in_manager.py
@@ -22,7 +22,6 @@ def _manager() -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_evidence_gate.py b/tests/unit/brain/test_evidence_gate.py
index 28d8d71e8e..366c63b068 100644
--- a/tests/unit/brain/test_evidence_gate.py
+++ b/tests/unit/brain/test_evidence_gate.py
@@ -103,16 +103,15 @@ def test_general_cost_question_does_not_force_gcloud():
assert v.kind == "pass"
-# --- activity / window-history domain (2026-06-18 confabulation fix) ----------
+# --- activity / window-history domain -----------------------------------------
-def test_activity_question_forces_awareness_recall():
- """'Was hatte ich heute offen?' must FORCE awareness-recall.
+def test_activity_question_is_refused_honestly():
+ """'Was hatte ich heute offen?' gets an honest refusal.
- Live 2026-06-18: the fast brain answered "der lokale Verlaufsspeicher ist
- nicht verfügbar" WITHOUT ever calling awareness-recall (proven from the log:
- no tool execution line). Mandating the always-on internal tool removes the
- model's discretion to confabulate an outage.
+ Jarvis keeps no activity history (the awareness recorder was removed
+ 2026-09-30), so no tool serves the domain. The gate must answer
+ honestly instead of letting the model invent a timeline.
"""
from jarvis.core.config import EvidenceDomainsConfig
@@ -128,12 +127,11 @@ def test_activity_question_forces_awareness_recall():
enabled=True,
domains=domains,
capability_registry=CapabilityRegistry(),
- domain_tool_map={"activity": "awareness-recall"},
+ domain_tool_map={},
refusal_hint_fn=None,
)
- assert v.kind == "require_tool", utterance
- assert v.tool_name == "awareness-recall", utterance
- assert "NEVER invent" in v.directive
+ assert v.kind == "honest_refusal", utterance
+ assert v.domain == "activity", utterance
def test_activity_hard_negative_bare_offen_does_not_trigger():
@@ -146,7 +144,7 @@ def test_activity_hard_negative_bare_offen_does_not_trigger():
enabled=True,
domains=domains,
capability_registry=CapabilityRegistry(),
- domain_tool_map={"activity": "awareness-recall"},
+ domain_tool_map={},
refusal_hint_fn=None,
)
assert v.kind == "pass"
diff --git a/tests/unit/brain/test_evidence_gate_wiring.py b/tests/unit/brain/test_evidence_gate_wiring.py
index 9b372ed7b9..bf99347fd1 100644
--- a/tests/unit/brain/test_evidence_gate_wiring.py
+++ b/tests/unit/brain/test_evidence_gate_wiring.py
@@ -96,43 +96,15 @@ def test_run_evidence_gate_disabled_passes():
assert m._run_evidence_gate("Was steht heute noch an?").kind == "pass"
-def test_run_evidence_gate_maps_activity_to_awareness_recall(monkeypatch):
- """Window/activity-history questions force the always-on awareness-recall.
-
- The fast brain otherwise confabulates "der lokale Verlaufsspeicher ist nicht
- verfügbar" without ever calling the tool (live 2026-06-18). awareness-recall
- is an internal router tool, not a connected CLI, so the manager must inject
- the domain→tool mapping itself.
- """
- import jarvis.clis.shared as shared
- import jarvis.core.capabilities as cap_mod
- from jarvis.core.config import EvidenceDomainsConfig
-
- m = _bare_manager()
- m._tools = {"awareness-recall": object()}
- m._config = SimpleNamespace(
- brain=SimpleNamespace(
- evidence_domains=SimpleNamespace(
- enabled=True, domains=EvidenceDomainsConfig().domains,
- )
- )
- )
- monkeypatch.setattr(shared, "get_active_registry", lambda: None)
- monkeypatch.setattr(cap_mod, "get_registry", lambda: cap_mod.CapabilityRegistry())
- verdict = m._run_evidence_gate("Was hatte ich heute offen?")
- assert verdict.kind == "require_tool"
- assert verdict.tool_name == "awareness-recall"
-
-
-def test_run_evidence_gate_activity_refuses_when_tool_absent(monkeypatch):
- """If awareness-recall is not registered, the activity domain degrades to an
- honest refusal — never a confabulated outage."""
+def test_run_evidence_gate_activity_refuses_honestly(monkeypatch):
+ """Jarvis keeps no activity history, so a window/activity question gets an
+ honest refusal — never a confabulated timeline."""
import jarvis.clis.shared as shared
import jarvis.core.capabilities as cap_mod
from jarvis.core.config import EvidenceDomainsConfig
m = _bare_manager()
- m._tools = {"screenshot": object()} # no awareness-recall
+ m._tools = {"screenshot": object()}
m._config = SimpleNamespace(
brain=SimpleNamespace(
evidence_domains=SimpleNamespace(
@@ -146,59 +118,6 @@ def test_run_evidence_gate_activity_refuses_when_tool_absent(monkeypatch):
assert verdict.kind == "honest_refusal"
-class _FakeResult:
- def __init__(self, success, output):
- self.success = success
- self.output = output
-
-
-class _FakeExecutor:
- def __init__(self, result):
- self._result = result
- self.calls = []
-
- async def execute(self, tool, args, **kw):
- self.calls.append((tool, args, kw))
- return self._result
-
-
-async def test_prefetch_activity_block_returns_tool_output():
- """The deterministic pre-fetch returns the awareness-recall output so the
- brain answers from real data instead of confabulating an outage (the fast
- brain never calls the soft-mandated tool itself — live 2026-06-18)."""
- m = _bare_manager()
- tool = object()
- m._tools = {"awareness-recall": tool}
- execr = _FakeExecutor(_FakeResult(True, "Recent activity: - [20:49, Terminal.exe]"))
- m._tool_executor = execr
- block = await m._prefetch_activity_block(
- "awareness-recall", "Was hatte ich heute offen?",
- )
- assert "Recent activity" in block
- # It went through the ToolExecutor (never a direct Tool.execute — AP-3).
- assert execr.calls and execr.calls[0][0] is tool
-
-
-async def test_prefetch_activity_block_empty_on_failure_keeps_fallback():
- m = _bare_manager()
- m._tools = {"awareness-recall": object()}
- m._tool_executor = _FakeExecutor(_FakeResult(False, ""))
- assert await m._prefetch_activity_block("awareness-recall", "x") == ""
-
-
-async def test_prefetch_activity_block_no_tool_or_executor():
- m = _bare_manager()
- m._tools = {}
- m._tool_executor = _FakeExecutor(_FakeResult(True, "x"))
- assert await m._prefetch_activity_block("awareness-recall", "x") == ""
- m._tools = {"awareness-recall": object()}
- m._tool_executor = None
- assert await m._prefetch_activity_block("awareness-recall", "x") == ""
-
-
@pytest.mark.parametrize(
("pin", "expected_fragment"),
[
diff --git a/tests/unit/brain/test_identity_card_in_manager.py b/tests/unit/brain/test_identity_card_in_manager.py
index 9e11332d35..15d8df0f2d 100644
--- a/tests/unit/brain/test_identity_card_in_manager.py
+++ b/tests/unit/brain/test_identity_card_in_manager.py
@@ -53,7 +53,6 @@ def _manager(tmp_path: Path, *, cache_optimized: bool, profile: str | None) -> B
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = ""
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_prompt_cache_layout.py b/tests/unit/brain/test_prompt_cache_layout.py
index 903466fc02..b6a8ff7590 100644
--- a/tests/unit/brain/test_prompt_cache_layout.py
+++ b/tests/unit/brain/test_prompt_cache_layout.py
@@ -1,42 +1,26 @@
"""Tests for the cache-optimized prompt layout (Wave 2 — omni-latency).
The provider prompt cache (Gemini CachedContent / Anthropic cache_control) is
-keyed on the system prompt. Today awareness + wiki are baked into it and change
-every turn, so the cache never hits (measured baseline: ~9-12 s TTFT despite
-caching being ON). Wave 2 moves the per-turn dynamic context (date / awareness /
-wiki) onto the user message so the system prompt stays byte-stable and the
-cache actually warms up.
+keyed on the system prompt. Per-turn dynamic context (date / wiki) used to be
+baked into it and changed every turn, so the cache never hit (measured
+baseline: ~9-12 s TTFT despite caching being ON). Wave 2 moves that context
+onto the user message so the system prompt stays byte-stable and the cache
+actually warms up.
"""
from __future__ import annotations
from jarvis.brain.manager import BrainManager
from jarvis.core.config import load_config
-_AWARE_A = "Active window: Code.exe — main.py"
-_AWARE_B = "Active window: chrome.exe — youtube.com"
_WIKI = "WIKI_CONTEXT_MARKER: The fictional test user prefers synthwave."
-class _FakeAwarenessState:
- def __init__(self, snap: str) -> None:
- self.snap = snap
-
- def snapshot_for_prompt(self, max_chars: int = 600) -> str:
- return self.snap
-
-
-class _FakeAwareness:
- def __init__(self, snap: str) -> None:
- self.state = _FakeAwarenessState(snap)
-
-
-def _manager(*, cache_optimized: bool, snap: str) -> BrainManager:
+def _manager(*, cache_optimized: bool) -> BrainManager:
m = BrainManager.__new__(BrainManager) # bypass heavy __init__
m._soul = None
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = _FakeAwareness(snap)
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = _WIKI
m._reply_language = "auto"
@@ -47,40 +31,36 @@ def _manager(*, cache_optimized: bool, snap: str) -> BrainManager:
def test_cache_optimized_excludes_dynamic_from_system_prompt() -> None:
- m = _manager(cache_optimized=True, snap=_AWARE_A)
+ m = _manager(cache_optimized=True)
sp = m._build_system_prompt()
- assert _AWARE_A not in sp
assert _WIKI not in sp
# static content is still present
assert "ROUTER DISCIPLINE BLOCK" in sp
-def test_system_prompt_byte_stable_across_awareness_changes() -> None:
- # The caching guarantee: different awareness state -> identical system prompt.
- m = _manager(cache_optimized=True, snap=_AWARE_A)
+def test_system_prompt_byte_stable_across_wiki_changes() -> None:
+ # The caching guarantee: different per-turn context -> identical system prompt.
+ m = _manager(cache_optimized=True)
first = m._build_system_prompt()
- m._awareness_manager = _FakeAwareness(_AWARE_B)
m._wiki_context_suffix = "WIKI_CONTEXT_MARKER: something else entirely."
second = m._build_system_prompt()
assert first == second
def test_legacy_mode_keeps_dynamic_in_system_prompt() -> None:
- m = _manager(cache_optimized=False, snap=_AWARE_A)
+ m = _manager(cache_optimized=False)
sp = m._build_system_prompt()
- assert _AWARE_A in sp
assert _WIKI in sp
-def test_turn_context_carries_date_awareness_and_wiki() -> None:
- m = _manager(cache_optimized=True, snap=_AWARE_A)
+def test_turn_context_carries_date_and_wiki() -> None:
+ m = _manager(cache_optimized=True)
ctx = m._build_turn_context()
- assert _AWARE_A in ctx
assert _WIKI in ctx
# a date/time stamp is injected (fixes the missing BUG-005 date injection)
assert "20" in ctx # year prefix, e.g. 2026
def test_turn_context_empty_in_legacy_mode() -> None:
- m = _manager(cache_optimized=False, snap=_AWARE_A)
+ m = _manager(cache_optimized=False)
assert m._build_turn_context() == ""
diff --git a/tests/unit/brain/test_refresh_tools_di.py b/tests/unit/brain/test_refresh_tools_di.py
index 00df7bddbe..081ce5e57e 100644
--- a/tests/unit/brain/test_refresh_tools_di.py
+++ b/tests/unit/brain/test_refresh_tools_di.py
@@ -1,12 +1,10 @@
"""``BrainManager.refresh_tools`` must preserve the boot-time DI.
-Regression for the live 2026-06-18 voice bug ("der lokale Verlaufsspeicher ist
-nicht verfügbar"): every CLI/MCP connect at boot triggers a tool refresh. The
-refresh rebuilt the tool set via ``_load_tools_for_tier`` but dropped the shared
-DI references the boot path passes, so the rebuilt ``awareness-recall`` got
-``recall_store=None`` and returned "awareness recall store unavailable" forever
-after the first CLI connected — a genuine outage the brain faithfully relayed,
-never a confabulation. The fix mirrors the boot DI on refresh.
+Regression for the live 2026-06-18 voice bug: every CLI/MCP connect at boot
+triggers a tool refresh. The refresh rebuilt the tool set via
+``_load_tools_for_tier`` but dropped the shared DI references the boot path
+passes, so the rebuilt tools lost their managers after the first CLI
+connected. The fix mirrors the boot DI on refresh.
"""
from types import SimpleNamespace
@@ -23,13 +21,11 @@ def _bare_for_refresh(**di):
m._config = SimpleNamespace(safety=SimpleNamespace())
m._user_profile = None
m._people = None
- m._recall = di.get("recall")
- m._awareness_manager = di.get("awareness")
m._contacts = di.get("contacts")
return m
-def test_refresh_tools_preserves_recall_store_and_managers(monkeypatch):
+def test_refresh_tools_preserves_managers(monkeypatch):
import jarvis.brain.factory as factory
import jarvis.harness.manager as harness_mod
@@ -38,43 +34,19 @@ def test_refresh_tools_preserves_recall_store_and_managers(monkeypatch):
def _fake_load_tools_for_tier(tier, **kwargs):
captured.update(kwargs)
captured["tier"] = tier
- return {"awareness-recall": object()}
+ return {"contact-lookup": object()}
monkeypatch.setattr(factory, "_load_tools_for_tier", _fake_load_tools_for_tier)
monkeypatch.setattr(factory, "_load_local_action_tools", lambda **kw: {})
monkeypatch.setattr(factory, "_resolve_mission_manager", lambda: "MM")
monkeypatch.setattr(harness_mod, "HarnessManager", lambda **kw: object())
- recall, awareness, contacts = object(), object(), object()
- m = _bare_for_refresh(recall=recall, awareness=awareness, contacts=contacts)
+ contacts = object()
+ m = _bare_for_refresh(contacts=contacts)
m.refresh_tools()
# The boot-time DI must survive the refresh — this is the whole bug.
- assert captured.get("recall_store") is recall
- assert captured.get("awareness_manager") is awareness
assert captured.get("contacts") is contacts
assert captured.get("mission_manager") == "MM"
- assert "awareness-recall" in m._tools
-
-
-def test_refresh_tools_recall_store_never_silently_none(monkeypatch):
- """Even after a refresh, awareness-recall must NOT be handed a None store
- when the manager holds a real one (the exact silent-None regression)."""
- import jarvis.brain.factory as factory
- import jarvis.harness.manager as harness_mod
-
- captured: dict = {}
- monkeypatch.setattr(
- factory, "_load_tools_for_tier",
- lambda tier, **kw: (captured.update(kw), {"x": object()})[1],
- )
- monkeypatch.setattr(factory, "_load_local_action_tools", lambda **kw: {})
- monkeypatch.setattr(factory, "_resolve_mission_manager", lambda: None)
- monkeypatch.setattr(harness_mod, "HarnessManager", lambda **kw: object())
-
- recall = object()
- m = _bare_for_refresh(recall=recall)
- m.refresh_tools()
- assert captured["recall_store"] is recall
- assert captured["recall_store"] is not None
+ assert "contact-lookup" in m._tools
diff --git a/tests/unit/brain/test_reply_language.py b/tests/unit/brain/test_reply_language.py
index a8f51f106a..db2f9c9276 100644
--- a/tests/unit/brain/test_reply_language.py
+++ b/tests/unit/brain/test_reply_language.py
@@ -25,7 +25,6 @@ def _manager(reply_language: str) -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = reply_language
diff --git a/tests/unit/brain/test_reply_language_hot_reload.py b/tests/unit/brain/test_reply_language_hot_reload.py
index c0bad540bf..b649739f27 100644
--- a/tests/unit/brain/test_reply_language_hot_reload.py
+++ b/tests/unit/brain/test_reply_language_hot_reload.py
@@ -27,7 +27,6 @@ def _manager_with_bus(bus: EventBus, reply_language: str) -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = reply_language
diff --git a/tests/unit/brain/test_resolve_subscription_brain.py b/tests/unit/brain/test_resolve_subscription_brain.py
index 3f405a387b..7002c77894 100644
--- a/tests/unit/brain/test_resolve_subscription_brain.py
+++ b/tests/unit/brain/test_resolve_subscription_brain.py
@@ -203,34 +203,3 @@ def test_every_subscription_card_can_answer_the_connection_probe() -> None:
getattr(brain_cls, "subscription_connected", None)
), f"{spec.id} has no subscription_connected probe"
-
-class _TextBrain:
- def __init__(self, text: str) -> None:
- self.text = text
-
- async def complete(self, _req: Any): # noqa: ANN201
- yield self.text
-
-
-async def _collect(brain: Any) -> list[str]:
- return [delta async for delta in brain.complete(object())]
-
-
-def test_background_brain_prefers_a_connected_subscription(monkeypatch) -> None:
- import asyncio
-
- monkeypatch.setattr(
- resolver, "resolve_subscription_brain", lambda cfg, **_kw: _TextBrain("subscription")
- )
- brain = resolver.SubscriptionFirstBrain(_cfg(), _TextBrain("paid-key"))
-
- assert asyncio.run(_collect(brain)) == ["subscription"]
-
-
-def test_background_brain_uses_the_key_without_a_subscription(monkeypatch) -> None:
- import asyncio
-
- monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg, **_kw: None)
- brain = resolver.SubscriptionFirstBrain(_cfg(), _TextBrain("paid-key"))
-
- assert asyncio.run(_collect(brain)) == ["paid-key"]
diff --git a/tests/unit/brain/test_router_tool_entrypoint_parity.py b/tests/unit/brain/test_router_tool_entrypoint_parity.py
index 93e8dde4c4..2954a6c07d 100644
--- a/tests/unit/brain/test_router_tool_entrypoint_parity.py
+++ b/tests/unit/brain/test_router_tool_entrypoint_parity.py
@@ -78,7 +78,7 @@ KNOWN_UNREACHABLE: frozenset[str] = frozenset({
"dispatch-to-admin",
"dispatch-with-review",
"multi-spawn",
- # Superseded by the wiki + awareness tools.
+ # Superseded by the wiki tools.
"remember",
"whoami",
# Dev-loop helpers, plausibly worker-only by design.
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 656e04e9e1..7c4e41a646 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -1861,9 +1861,6 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
# Enum-constrained + schema-validated; dangerous -> risk "ask".
# Never a spawn (AP-5/AP-14). ADR-0011 amendment "app-command tool".
"app-command",
- "awareness-snapshot",
- # Awareness Phase A3 (BM25 search over recent episode log).
- "awareness-recall",
# Skills-Brain-Integration (also in SUB_TOOLS — structural D9 protection)
"run-skill",
# Skill authoring by voice/chat (2026-08-18): the brain writes a NEW
diff --git a/tests/unit/brain/test_self_control_standing.py b/tests/unit/brain/test_self_control_standing.py
index 5002965751..b03e4ee9aa 100644
--- a/tests/unit/brain/test_self_control_standing.py
+++ b/tests/unit/brain/test_self_control_standing.py
@@ -22,7 +22,6 @@ def _manager() -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = ""
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_system_prompt_name.py b/tests/unit/brain/test_system_prompt_name.py
index e83e254384..f5f5fe9349 100644
--- a/tests/unit/brain/test_system_prompt_name.py
+++ b/tests/unit/brain/test_system_prompt_name.py
@@ -23,7 +23,6 @@ def _manager_with_name(*, wake_phrase: str = "Hey Jarvis") -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_turn_override.py b/tests/unit/brain/test_turn_override.py
index d9f1d472a3..ffb050bf3f 100644
--- a/tests/unit/brain/test_turn_override.py
+++ b/tests/unit/brain/test_turn_override.py
@@ -367,7 +367,6 @@ def _prompt_manager() -> BrainManager:
m._user_profile = None
m._people = None
m._core_memory = None
- m._awareness_manager = None
m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
m._wiki_context_suffix = ""
m._reply_language = "auto"
diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.py
index 408bd2471e..cb035595a7 100644
--- a/tests/unit/brain/test_turn_planner.py
+++ b/tests/unit/brain/test_turn_planner.py
@@ -772,7 +772,7 @@ def test_no_open_workspace_changes_nothing() -> None:
)
def test_recall_of_the_users_past_delegates_as_private_data(utterance: str) -> None:
"""Explicit recall of the user's own past is strong evidence: only the
- orchestrator (Wiki memory / awareness episodes) can answer it."""
+ orchestrator (Wiki memory) can answer it."""
plan = plan_turn(utterance)
assert plan.path is TurnPath.ORCHESTRATOR
assert TurnReason.PRIVATE_DATA in plan.reasons
diff --git a/tests/unit/core/test_capabilities.py b/tests/unit/core/test_capabilities.py
index 7a9ba6e96c..eedce32897 100644
--- a/tests/unit/core/test_capabilities.py
+++ b/tests/unit/core/test_capabilities.py
@@ -326,8 +326,6 @@ class TestSeedRegistry:
# LLM-visible router tool — phantom-vehicle routing fix; the dead
# 'openclaw' capability id was still being advertised).
"tool.spawn-worker",
- "tool.awareness-snapshot",
- "tool.awareness-recall",
"tool.run-skill",
"tool.wiki-recall",
"tool.wiki-page-read",
@@ -419,8 +417,6 @@ class TestSeedRegistry:
def test_requires_evidence_false_for_read_only(self) -> None:
"""Read-only tools must have requires_evidence=False."""
read_only_ids = {
- "tool.awareness-snapshot",
- "tool.awareness-recall",
"tool.wiki-recall",
"tool.wiki-page-read",
}
diff --git a/tests/unit/core/test_evidence_domains_config.py b/tests/unit/core/test_evidence_domains_config.py
index 68a06ea22a..f5e4d380ec 100644
--- a/tests/unit/core/test_evidence_domains_config.py
+++ b/tests/unit/core/test_evidence_domains_config.py
@@ -14,8 +14,8 @@ def test_defaults_ship_seven_domains_enabled():
def test_defaults_include_activity_window_history_domain():
- # "Was hatte ich heute offen?" must force awareness-recall instead of a
- # confabulated "lokaler Verlaufsspeicher nicht verfügbar" (live 2026-06-18).
+ # "Was hatte ich heute offen?" gets an honest refusal (Jarvis keeps no
+ # activity history) instead of a confabulated timeline.
# Keywords are phrase-specific to opened windows / on-device activity.
cfg = EvidenceDomainsConfig()
kws = cfg.domains["activity"]
diff --git a/tests/unit/self_mod/test_registry.py b/tests/unit/self_mod/test_registry.py
index e1a684a1b6..0a4e603be9 100644
--- a/tests/unit/self_mod/test_registry.py
+++ b/tests/unit/self_mod/test_registry.py
@@ -304,8 +304,8 @@ class TestAllowlistFieldParity:
@pytest.mark.parametrize("spec", SelfModRegistry.list_all(), ids=lambda s: s.path)
def test_model_and_field_exist(self, spec: MutableSpec) -> None:
# Resolve the owning model by navigating JarvisConfig along the path,
- # not getattr(config, name): a submodule section model (e.g.
- # AwarenessPrivacyConfig) is never re-exported into config, but it is
+ # not getattr(config, name): a submodule section model is never
+ # re-exported into config, but it is
# still the real owner. This is the stronger anti-drift check.
model = resolve_model_for_path(spec.path)
assert issubclass(model, BaseModel)
diff --git a/tests/unit/self_mod/test_schema_introspect.py b/tests/unit/self_mod/test_schema_introspect.py
index 3fafd3e6c2..7b59a8aba1 100644
--- a/tests/unit/self_mod/test_schema_introspect.py
+++ b/tests/unit/self_mod/test_schema_introspect.py
@@ -83,7 +83,7 @@ class TestSpecShape:
# model that actually owns it in the schema — the TestAllowlistFieldParity
# contract, applied to the whole introspected set via schema navigation
# (more robust than getattr(config, name): covers submodule section
- # models like AwarenessPrivacyConfig that config never re-exports).
+ # models that config never re-exports).
for spec in introspect_mutable_specs():
model = resolve_model_for_path(spec.path)
assert issubclass(model, BaseModel)
diff --git a/tests/unit/ui/web/test_boot_critical_path_stays_light.py b/tests/unit/ui/web/test_boot_critical_path_stays_light.py
index 59e67cdd61..9bf1ef48c4 100644
--- a/tests/unit/ui/web/test_boot_critical_path_stays_light.py
+++ b/tests/unit/ui/web/test_boot_critical_path_stays_light.py
@@ -3,7 +3,7 @@
The desktop/headless serve-first boot only stays fast because the
``FastBootstrap`` can bind the port and serve the UI shell BEFORE the heavy
imports (``fastapi``, the ``jarvis.brain`` graph, ``jarvis.core.config`` with
-its brain/awareness pulls) are paid. If a future change makes
+its brain pulls) are paid. If a future change makes
``jarvis.ui.web.fast_bootstrap`` transitively import any of those, the bind
moves back behind the heavy work and the boot silently regresses — the exact
"it keeps getting slower as I add features" rot this guards against.
@@ -20,7 +20,7 @@ import sys
# Modules that must NOT be pulled in merely by importing the bootstrap. Each is a
# multi-hundred-ms import that the serve-first boot deliberately defers.
-_FORBIDDEN = ("fastapi", "jarvis.brain", "jarvis.core.config", "jarvis.awareness")
+_FORBIDDEN = ("fastapi", "jarvis.brain", "jarvis.core.config")
def test_fast_bootstrap_import_stays_light() -> None: