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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-07 20:37)

Ruben Lütke7f55c1b6970b
diff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.py
index 7ff4b2f604..7e8c952870 100644
--- a/jarvis/memory/wiki/extractor.py
+++ b/jarvis/memory/wiki/extractor.py
@@ -21,7 +21,6 @@ background tasks; this module never runs on the voice critical path.
"""
from __future__ import annotations
-import asyncio
import logging
import time
from typing import TYPE_CHECKING, Any
@@ -56,21 +55,6 @@ _KNOWN_KINDS = frozenset(
{"identity", "preference", "person", "project", "decision", "event", "other"}
)
-def _log_trigger_outcome(task: "asyncio.Task[Any]") -> None:
- """Done-callback for the fire-and-forget journal-pressure trigger.
-
- Retrieves the exception (silences the never-retrieved warning) but —
- unlike a bare ``t.exception()`` lambda — actually logs real failures.
- A lost trigger is retried on the next append, so WARNING suffices.
- """
- if task.cancelled():
- return
- exc = task.exception()
- if exc is not None:
- log.warning(
- "ConversationFactExtractor: journal-pressure trigger failed: %s", exc,
- )
-
_SYSTEM_PROMPT = """\
You extract durable personal-memory facts from ONE conversation turn between
@@ -187,13 +171,13 @@ class ConversationFactExtractor:
)
if backlog < self._consolidate_after:
return
- from jarvis.memory.wiki.scheduler import TriggerSource
+ from jarvis.memory.wiki.scheduler import fire_journal_trigger
- task = asyncio.create_task(
- self._scheduler.trigger(TriggerSource.JOURNAL),
+ fire_journal_trigger(
+ self._scheduler,
name="wiki-journal-pressure-trigger",
+ log_context="journal-pressure trigger",
)
- task.add_done_callback(_log_trigger_outcome)
except RuntimeError:
# No running event loop (sync test context) — next append from
# an async context will retry.
diff --git a/jarvis/memory/wiki/integration.py b/jarvis/memory/wiki/integration.py
index 96897f133b..d9bf29a487 100644
--- a/jarvis/memory/wiki/integration.py
+++ b/jarvis/memory/wiki/integration.py
@@ -778,33 +778,6 @@ def _build_curator(
)
-def _fire_journal_trigger(scheduler: Any, *, task_name: str, log_context: str) -> None:
- """Fire one background JOURNAL trigger (fire-and-forget, AP-9).
-
- Shared by every journal-pressure site — the boot-time backlog drain
- (:func:`kick_journal_backlog`) and the age-based flush loop
- (:func:`_journal_age_flush_loop`) — so the actual
- ``scheduler.trigger(...)`` call shape cannot drift between them.
- Callers are responsible for their own preconditions (scheduler present,
- something actually pending) before calling this.
- """
- from jarvis.memory.wiki.scheduler import TriggerSource
-
- task = asyncio.create_task(
- scheduler.trigger(TriggerSource.JOURNAL),
- name=task_name,
- )
-
- def _log_outcome(t: "asyncio.Task[Any]") -> None:
- if t.cancelled():
- return
- exc = t.exception()
- if exc is not None:
- log.warning("wiki_integration: %s failed: %s", log_context, exc)
-
- task.add_done_callback(_log_outcome)
-
-
def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
"""Boot-time backlog drain (Wave-2 C1).
@@ -822,8 +795,12 @@ def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
_record_backlog_health(backlog)
if backlog <= 0:
return
- _fire_journal_trigger(
- scheduler, task_name="wiki-journal-boot-drain", log_context="boot journal drain",
+ from jarvis.memory.wiki.scheduler import fire_journal_trigger
+
+ fire_journal_trigger(
+ scheduler,
+ name="wiki-journal-boot-drain",
+ log_context="boot journal drain",
)
log.info(
"wiki_integration: boot drain triggered for %d pending candidate(s)",
@@ -835,18 +812,36 @@ def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
log.warning("wiki_integration: boot journal drain skipped: %s", exc)
+def _should_age_flush(oldest_ms: int | None, now_ms: int, max_age_min: int) -> bool:
+ """Pure decision for the age-based flush (spec A4).
+
+ ``True`` only when the age flush is enabled (``max_age_min > 0``),
+ something is pending (``oldest_ms is not None``), and the oldest pending
+ candidate is at least ``max_age_min`` minutes old. Extracted from the
+ loop so the age/enable/empty logic is unit-testable without a clock.
+ """
+ if max_age_min <= 0 or oldest_ms is None:
+ return False
+ age_min = (now_ms - oldest_ms) / 60_000
+ return age_min >= max_age_min
+
+
async def _journal_age_flush_loop(journal: Any, scheduler: Any, sched_cfg: Any) -> None:
"""Fire a JOURNAL trigger when the oldest pending candidate exceeds the
configured age (spec A4).
Below-threshold backlogs on a quiet install never cross
``consolidate_after_candidates`` on their own — this loop is the
- backstop that still gets them written. Runs off the voice hot path
- (AP-9) and was started off the boot critical path (AP-26); cancelled in
- :meth:`WikiIntegrationHandle.shutdown` exactly like the hourly
- telemetry loop. Never raises — a check failure is logged and the loop
- keeps polling.
+ backstop that still gets them written, the below-threshold counterpart
+ to the extractor's count-gated trigger (both go through the shared
+ :func:`~jarvis.memory.wiki.scheduler.fire_journal_trigger`). Runs off
+ the voice hot path (AP-9) and was started off the boot critical path
+ (AP-26); cancelled in :meth:`WikiIntegrationHandle.shutdown` exactly
+ like the hourly telemetry loop. Never raises — a check failure is
+ logged and the loop keeps polling.
"""
+ from jarvis.memory.wiki.scheduler import fire_journal_trigger
+
max_age_min = int(getattr(sched_cfg, "flush_pending_max_age_minutes", 10))
if max_age_min <= 0:
log.debug("wiki_integration: age-based journal flush disabled (max_age<=0)")
@@ -855,13 +850,10 @@ async def _journal_age_flush_loop(journal: Any, scheduler: Any, sched_cfg: Any)
await asyncio.sleep(120)
try:
oldest = journal.oldest_pending_ms()
- if oldest is None:
- continue
- age_min = (time.time() * 1000 - oldest) / 60_000
- if age_min >= max_age_min:
- _fire_journal_trigger(
+ if _should_age_flush(oldest, int(time.time() * 1000), max_age_min):
+ fire_journal_trigger(
scheduler,
- task_name="wiki-journal-age-flush-trigger",
+ name="wiki-journal-age-flush-trigger",
log_context="age-based journal flush",
)
except Exception: # noqa: BLE001 — never kill the loop
diff --git a/jarvis/memory/wiki/scheduler.py b/jarvis/memory/wiki/scheduler.py
index a90057cade..05491ca9a3 100644
--- a/jarvis/memory/wiki/scheduler.py
+++ b/jarvis/memory/wiki/scheduler.py
@@ -34,6 +34,7 @@ Example
"""
from __future__ import annotations
+import asyncio
import logging
import time
from dataclasses import dataclass
@@ -60,6 +61,46 @@ class TriggerSource(str, Enum):
JOURNAL = "journal"
+def fire_journal_trigger(
+ scheduler: Any,
+ *,
+ name: str = "wiki-journal-trigger",
+ log_context: str = "journal trigger",
+) -> "asyncio.Task[Any]":
+ """Fire ONE background ``JOURNAL`` trigger (fire-and-forget, AP-9).
+
+ The single shared entry point for EVERY journal-pressure site so the
+ ``scheduler.trigger(TriggerSource.JOURNAL)`` call and its done-callback
+ logging cannot drift apart between them:
+
+ * the per-turn count-threshold trigger
+ (``extractor.ConversationFactExtractor._maybe_trigger_consolidation``),
+ * the boot-time backlog drain (``integration.kick_journal_backlog``), and
+ * the below-threshold age-based flush
+ (``integration._journal_age_flush_loop``).
+
+ Lives here (a runtime-stdlib-only leaf, next to ``TriggerSource``) so
+ ``extractor`` and ``integration`` can both import it without an import
+ cycle. Callers own their own preconditions (scheduler present, backlog
+ over the count threshold / over the age / non-empty) and any
+ ``RuntimeError`` guard for "no running event loop". Returns the created
+ task so a caller may await or track it.
+ """
+ task = asyncio.create_task(scheduler.trigger(TriggerSource.JOURNAL), name=name)
+
+ def _log_outcome(t: "asyncio.Task[Any]") -> None:
+ # A lost trigger is retried on the next append/tick, so WARNING
+ # (not ERROR) is the right severity.
+ if t.cancelled():
+ return
+ exc = t.exception()
+ if exc is not None:
+ log.warning("wiki journal trigger (%s) failed: %s", log_context, exc)
+
+ task.add_done_callback(_log_outcome)
+ return task
+
+
@dataclass(frozen=True, slots=True)
class SchedulerResult:
"""Immutable outcome of a single ``trigger`` call.
diff --git a/tests/unit/memory/wiki/test_journal_age_flush.py b/tests/unit/memory/wiki/test_journal_age_flush.py
index 8019048a87..3574137736 100644
--- a/tests/unit/memory/wiki/test_journal_age_flush.py
+++ b/tests/unit/memory/wiki/test_journal_age_flush.py
@@ -65,3 +65,43 @@ def test_default_consolidation_threshold_is_three() -> None:
cfg = SchedulerConfig()
assert cfg.consolidate_after_candidates == 3
assert cfg.flush_pending_max_age_minutes == 10
+
+
+# ---------------------------------------------------------------------------
+# _should_age_flush: pure age/enable/empty decision behind the flush loop
+# (spec A4). Testing it directly avoids driving the 120s-sleep loop.
+# ---------------------------------------------------------------------------
+
+_NOW_MS = 10_000_000
+
+
+def test_should_age_flush_false_when_nothing_pending() -> None:
+ from jarvis.memory.wiki.integration import _should_age_flush
+
+ assert _should_age_flush(None, _NOW_MS, 10) is False
+
+
+def test_should_age_flush_false_when_disabled() -> None:
+ from jarvis.memory.wiki.integration import _should_age_flush
+
+ # max_age_min <= 0 disables the flush even for an arbitrarily old row.
+ assert _should_age_flush(0, _NOW_MS, 0) is False
+ assert _should_age_flush(0, _NOW_MS, -5) is False
+
+
+def test_should_age_flush_false_below_threshold() -> None:
+ from jarvis.memory.wiki.integration import _should_age_flush
+
+ # 9 minutes old, threshold 10 → not yet.
+ oldest = _NOW_MS - 9 * 60_000
+ assert _should_age_flush(oldest, _NOW_MS, 10) is False
+
+
+def test_should_age_flush_true_at_and_over_threshold() -> None:
+ from jarvis.memory.wiki.integration import _should_age_flush
+
+ # Exactly 10 minutes old → fire (>=), and clearly over → fire.
+ at_threshold = _NOW_MS - 10 * 60_000
+ over_threshold = _NOW_MS - 20 * 60_000
+ assert _should_age_flush(at_threshold, _NOW_MS, 10) is True
+ assert _should_age_flush(over_threshold, _NOW_MS, 10) is True