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.

fix(wiki): surface captured facts in desktop graph

Ruben Lütkeee654d50510f
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index b1a43d5032..a11b59aaf9 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -6156,6 +6156,7 @@ class BrainManager:
user_text: str,
*,
trace_id: UUID | None = None,
+ use_history: bool = True,
) -> str | None:
"""Deterministic explicit wiki-write path (spec A1-A3).
@@ -6170,7 +6171,10 @@ class BrainManager:
if self._tool_executor is None:
return None
- match = match_wiki_intent(user_text)
+ match = match_wiki_intent(
+ user_text,
+ prior_text=self._previous_user_turn_text(use_history=use_history),
+ )
if match is None:
return None
tool = self._tools.get("wiki-ingest")
@@ -7408,7 +7412,9 @@ class BrainManager:
# never reinterpret the command as booking or dispatching that noun.
# Deterministic, model-independent, and confirm-after-write.
wiki_reply = await self._run_wiki_ingest_fast_path(
- user_text, trace_id=turn_trace_id,
+ user_text,
+ trace_id=turn_trace_id,
+ use_history=use_history,
)
if wiki_reply is not None:
await self._record_response_side_effects(
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index c860887aad..72e39e6d7a 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1332,11 +1332,12 @@ class FileSaved(Event):
class WikiPageChanged(Event):
"""A markdown file inside the wiki vault changed on disk.
- Emitted by :class:`jarvis.memory.wiki.watcher.WikiWatcher` after a
- debounced filesystem event in one of the watched sub-folders
- (``entities/``, ``concepts/``, ``projects/``, ``sessions/``). The
- desktop wiki view's WebSocket endpoint forwards this event to the
- frontend so React Query caches can be invalidated immediately.
+ Emitted directly by :class:`jarvis.memory.wiki.curator.WikiCurator`
+ after an app-owned atomic write, or by
+ :class:`jarvis.memory.wiki.watcher.WikiWatcher` after a debounced
+ external filesystem event. The desktop wiki view's WebSocket endpoint
+ forwards this event to the frontend so React Query caches can be
+ invalidated immediately.
``path`` is the vault-relative POSIX path (e.g. ``"entities/harald.md"``)
so the frontend can use the string as-is regardless of the host
diff --git a/jarvis/memory/wiki/consolidator.py b/jarvis/memory/wiki/consolidator.py
index 95f9fc86f6..8ab0072c54 100644
--- a/jarvis/memory/wiki/consolidator.py
+++ b/jarvis/memory/wiki/consolidator.py
@@ -53,6 +53,7 @@ from jarvis.memory.wiki.prompt import (
)
from jarvis.memory.wiki.protocols import PageUpdate
from jarvis.memory.wiki.telemetry import telemetry
+from jarvis.memory.wiki.wikilink import extract_wikilinks
if TYPE_CHECKING:
from jarvis.core.config import JarvisConfig
@@ -67,6 +68,14 @@ log = logging.getLogger(__name__)
# and never _archive (frozen).
_TARGET_DIRS = ("entities", "concepts", "projects")
+_GRAPH_TARGET_DIR_BY_KIND = {
+ "person": "entities",
+ "asset": "entities",
+ "place": "entities",
+ "organization": "entities",
+ "project": "projects",
+}
+
# Numeric claims are a small but damaging hallucination class: a page about an
# RTX 5070 Ti was once embellished with unsupported "24 GB VRAM" prose. Keep
# the matcher deliberately lexical and deterministic so Stage 2 can reject the
@@ -94,8 +103,11 @@ _EXPLICIT_PERSISTENCE_CLAUSE_RE = re.compile(
r"(?:(?:this|it)\s+)?that\b|"
r"\b(?:merk(?:e)?\s+dir|notier(?:e)?|speicher(?:e)?|"
r"halt(?:e)?\s+fest)\s*[,;:]?\s*dass\b|"
- r"\b(?:fueg(?:e)?|füg(?:e)?)\b.{0,40}?\bhinzu\s*[,;:]?\s*dass\b|" # i18n-allow: German persistence-clause input vocabulary
- r"\bhinzuf(?:ue|ü)gen\s*[,;:]?\s*dass\b|" # i18n-allow: German persistence-clause input vocabulary
+ r"\beintrag(?:en|e|st|t)\b.{0,40}?\bdass\b|"
+ r"\b(?:fueg(?:e)?|füg(?:e)?)\b.{0,40}?" # i18n-allow: German input vocabulary
+ r"\bhinzu\s*[,;:]?\s*dass\b|" # i18n-allow: German input vocabulary
+ r"\bhinzuf(?:ue|ü)gen\s*" # i18n-allow: German input vocabulary
+ r"[,;:]?\s*dass\b|" # i18n-allow: German input vocabulary
r"\b(?:recuerda|anota|guarda|registra|añade|anade|agrega)\s*"
r"[,;:]?\s*que\b"
r")",
@@ -523,7 +535,18 @@ class Consolidator:
# superseded one, and a profile update may create the missing
# topic page in the same batch, for the same candidate.
is_secondary = cid in judged_ids
- if is_secondary and decision not in ("invalidate", "add"):
+ required_place_update = (
+ is_secondary
+ and decision == "update"
+ and self._is_required_place_secondary_update(
+ by_id[cid], item.get("target")
+ )
+ )
+ if (
+ is_secondary
+ and decision not in ("invalidate", "add")
+ and not required_place_update
+ ):
continue
judged_ids.add(cid)
@@ -554,14 +577,26 @@ class Consolidator:
reason=str(item.get("reason", ""))[:200],
)
if is_secondary:
- companion_by_candidate.setdefault(cid, []).append(update)
- secondary_adds.append(target)
+ if required_place_update:
+ # The two existing sides of a residence edge are one
+ # candidate-level transaction: either both links land
+ # or neither page changes.
+ updates_by_candidate.setdefault(cid, []).append(update)
+ else:
+ companion_by_candidate.setdefault(cid, []).append(update)
+ secondary_adds.append(target)
+ if (
+ target == self._required_graph_target(by_id[cid])
+ or target
+ in self._required_place_write_targets(by_id[cid])
+ ):
+ required_targets.setdefault(cid, set()).add(target)
else:
updates_by_candidate.setdefault(cid, []).append(update)
write_plan[cid] = (decision, target)
- # The candidate's journal verdict tracks ONLY its primary
- # (and invalidation) writes — a companion page failure
- # must not reject or stall the primary fact.
+ # The journal always tracks the primary. A graph-mandatory
+ # companion is added above as a required target; optional
+ # companion pages retain their best-effort semantics.
required_targets.setdefault(cid, set()).add(target)
else: # invalidate
superseded_by = str(item.get("superseded_by", "") or "").strip()
@@ -585,9 +620,9 @@ class Consolidator:
for cid in sorted(write_cids, key=row_order.__getitem__):
# Companion topic pages land FIRST, in their own non-atomic call:
# the primary body's [[link]] to them then resolves from disk,
- # and a failing companion can never hold the durable primary
- # fact hostage — it just logs, and the demoted link heals via
- # promotion once a later batch creates the page.
+ # and a failing companion can never roll back the durable primary
+ # fact. A graph-mandatory companion keeps the journal row pending
+ # for retry; an optional companion remains best-effort.
companions = companion_by_candidate.get(cid)
if companions:
companion_result = await self._curator.apply_external_updates(
@@ -610,8 +645,8 @@ class Consolidator:
if failed_companions:
log.warning(
"Consolidator: companion topic page(s) %s for "
- "candidate %d did not land — the primary decision "
- "proceeds without them",
+ "candidate %d did not land; the primary write remains "
+ "durable and mandatory graph work stays pending",
", ".join(failed_companions),
cid,
)
@@ -751,6 +786,94 @@ class Consolidator:
return None
return rel
+ def _graph_target(self, row: JournalRow) -> str | None:
+ """Return the canonical or existing topic page for ``row``."""
+ directory = _GRAPH_TARGET_DIR_BY_KIND.get(str(row.kind or ""))
+ if directory is None:
+ return None
+ user_slug = resolve_user_entity_slug(
+ getattr(
+ self._root_cfg.memory.wiki.session_rollup,
+ "user_entity_slug",
+ "",
+ )
+ )
+ topic_slug = next(
+ (
+ subject
+ for subject in row.subjects
+ if subject not in {user_slug, "user"}
+ ),
+ "",
+ )
+ if not topic_slug:
+ return None
+ for candidate_dir in _TARGET_DIRS:
+ candidate = self._vault_root / candidate_dir / f"{topic_slug}.md"
+ if candidate.is_file():
+ return f"{candidate_dir}/{topic_slug}.md"
+ return f"{directory}/{topic_slug}.md"
+
+ def _required_graph_target(self, row: JournalRow) -> str | None:
+ """Return the missing page required to make ``row`` graph-visible."""
+ target = self._graph_target(row)
+ if target is None or (self._vault_root / target).is_file():
+ return None
+ return target
+
+ def _required_place_write_targets(self, row: JournalRow) -> set[str]:
+ """Return user/place pages that must change to establish both links."""
+ if row.kind != "place":
+ return set()
+ graph_target = self._graph_target(row)
+ if graph_target is None:
+ return set()
+ user_slug = resolve_user_entity_slug(
+ getattr(
+ self._root_cfg.memory.wiki.session_rollup,
+ "user_entity_slug",
+ "",
+ )
+ )
+ profile_target = f"entities/{user_slug}.md"
+ topic_slug = Path(graph_target).stem
+ required: set[str] = set()
+ for target, linked_slug in (
+ (graph_target, user_slug),
+ (profile_target, topic_slug),
+ ):
+ path = self._vault_root / target
+ try:
+ body = path.read_text(encoding="utf-8")
+ except OSError:
+ required.add(target)
+ continue
+ if not self._body_links_to_slug(body, linked_slug):
+ required.add(target)
+ return required
+
+ def _is_required_place_secondary_update(
+ self,
+ row: JournalRow,
+ raw_target: Any,
+ ) -> bool:
+ """Allow only the missing half of a residence-link update pair."""
+ target = self._safe_target(raw_target)
+ return (
+ target is not None
+ and target in self._required_place_write_targets(row)
+ and (self._vault_root / target).is_file()
+ )
+
+ @staticmethod
+ def _body_links_to_slug(body: str, slug: str) -> bool:
+ """Return whether ``body`` contains a wikilink to ``slug``."""
+ for raw_link in extract_wikilinks(body):
+ target = raw_link.split("|", 1)[0].strip().removesuffix(".md")
+ if target.rsplit("/", 1)[-1] == slug:
+ return True
+ return False
+
def _validate_decisions(
self,
parsed: list[Any],
@@ -763,8 +886,9 @@ class Consolidator:
A transport-successful JSON array is not necessarily a usable answer.
Reject the whole response (and let the provider chain try another
family) unless every candidate has exactly one valid primary decision.
- Secondary actions are limited to distinct invalidations and companion
- "add" pages (the graph-visibility rule) for the same candidate.
+ Secondary actions are limited to distinct invalidations, companion
+ "add" pages, and the exact second existing-page update required to
+ establish a bidirectional residence link.
"""
expected = {row.id for row in rows}
by_id = {row.id: row for row in rows}
@@ -786,10 +910,17 @@ class Consolidator:
if secondary:
# Secondary actions: extra invalidations for a contradiction,
# or a companion "add" that creates a missing topic page in
- # the same batch (graph-visibility rule in the prompt).
- if primary_decisions[cid] == "noop" or decision not in (
- "invalidate",
- "add",
+ # the same batch. A narrowly-scoped second update is permitted
+ # only when an existing residence page/profile lacks its edge.
+ required_place_update = (
+ decision == "update"
+ and self._is_required_place_secondary_update(
+ by_id[cid], item.get("target")
+ )
+ )
+ if primary_decisions[cid] == "noop" or (
+ decision not in ("invalidate", "add")
+ and not required_place_update
):
return "candidate has more than one primary decision"
else:
@@ -828,7 +959,14 @@ class Consolidator:
target_path = self._vault_root / target
if decision in ("add", "update"):
- if secondary and decision != "add":
+ required_place_update = (
+ secondary
+ and decision == "update"
+ and self._is_required_place_secondary_update(
+ by_id[cid], target
+ )
+ )
+ if secondary and decision != "add" and not required_place_update:
return "secondary decision must be an add or an invalidation"
body = item.get("new_body")
if not isinstance(body, str) or not body.strip():
@@ -860,6 +998,87 @@ class Consolidator:
if primary_seen != expected:
return "decision array does not cover every candidate"
+
+ for cid, row in by_id.items():
+ graph_target = self._graph_target(row)
+ if graph_target is None:
+ continue
+ graph_path = self._vault_root / graph_target
+ graph_item = next(
+ (
+ item
+ for item in parsed
+ if item.get("candidate_id") == cid
+ and item.get("decision") in ("add", "update")
+ and self._safe_target(item.get("target")) == graph_target
+ ),
+ None,
+ )
+ if not graph_path.is_file():
+ if graph_item is None or graph_item.get("decision") != "add":
+ return (
+ "graph-visible fact is missing its required companion page: "
+ f"{graph_target}"
+ )
+
+ # Non-place topics retain the missing-page invariant. Residence
+ # additionally requires a durable edge in both directions even
+ # when both pages already existed before this candidate.
+ if row.kind != "place":
+ continue
+ user_slug = resolve_user_entity_slug(
+ getattr(
+ self._root_cfg.memory.wiki.session_rollup,
+ "user_entity_slug",
+ "",
+ )
+ )
+ if graph_item is not None:
+ graph_body = str(graph_item.get("new_body", "") or "")
+ else:
+ try:
+ graph_body = graph_path.read_text(encoding="utf-8")
+ except OSError:
+ graph_body = ""
+ if not self._body_links_to_slug(graph_body, user_slug):
+ return "place companion page does not link to the user profile"
+
+ profile_target = f"entities/{user_slug}.md"
+ profile_path = self._vault_root / profile_target
+ profile_item = next(
+ (
+ item
+ for item in parsed
+ if item.get("candidate_id") == cid
+ and item.get("decision") in ("add", "update")
+ and self._safe_target(item.get("target")) == profile_target
+ ),
+ None,
+ )
+ if profile_item is not None:
+ profile_body = str(profile_item.get("new_body", "") or "")
+ else:
+ try:
+ profile_body = profile_path.read_text(encoding="utf-8")
+ except OSError:
+ profile_body = ""
+ topic_slug = Path(graph_target).stem
+ if not self._body_links_to_slug(profile_body, topic_slug):
+ return "user profile does not link to the place companion page"
+
+ required_place_targets = self._required_place_write_targets(row)
+ proposed_targets = {
+ self._safe_target(item.get("target"))
+ for item in parsed
+ if item.get("candidate_id") == cid
+ and item.get("decision") in ("add", "update")
+ }
+ missing_updates = required_place_targets - proposed_targets
+ if missing_updates:
+ return (
+ "residence link repair is missing required page update(s): "
+ + ", ".join(sorted(missing_updates))
+ )
return None
@staticmethod
diff --git a/jarvis/memory/wiki/curator.py b/jarvis/memory/wiki/curator.py
index 1ab2db8802..e3d148d170 100644
--- a/jarvis/memory/wiki/curator.py
+++ b/jarvis/memory/wiki/curator.py
@@ -30,8 +30,11 @@ context.
from __future__ import annotations
import logging
+from collections.abc import Awaitable, Callable
from pathlib import Path
+from jarvis.core.events import WikiPageChanged
+
from .log_writer import LogWriter
from .protocols import (
AtomicWriter,
@@ -119,6 +122,11 @@ class WikiCurator:
and to synthesise a ``WriteResult`` when the LLM returns an
empty proposal (the writer was never called, so no backup
was taken).
+ event_publisher:
+ Optional application event publisher. After an app-owned write
+ lands, the curator emits :class:`WikiPageChanged` so an open Wiki
+ view can invalidate its tree and graph without depending on an OS
+ filesystem watcher noticing the curator's atomic rename.
"""
def __init__(
@@ -130,6 +138,7 @@ class WikiCurator:
llm: CuratorLLM,
log_writer: LogWriter,
vault_root: Path,
+ event_publisher: Callable[[WikiPageChanged], Awaitable[None]] | None = None,
) -> None:
self._repo = repo
self._vault = vault
@@ -137,6 +146,7 @@ class WikiCurator:
self._llm = llm
self._log = log_writer
self._vault_root = Path(vault_root).resolve()
+ self._event_publisher = event_publisher
async def ingest(
self,
@@ -249,12 +259,61 @@ class WikiCurator:
type(exc).__name__,
)
+ await self._publish_page_changes(updates, result.applied)
+
return result
# ------------------------------------------------------------------
# Internals
# ------------------------------------------------------------------
+ async def _publish_page_changes(
+ self,
+ updates: list[PageUpdate],
+ applied: list[Path],
+ ) -> None:
+ """Best-effort live invalidation for app-owned vault writes."""
+ if self._event_publisher is None:
+ return
+
+ operations = {
+ update.target_path.resolve(): update.operation for update in updates
+ }
+ kinds = {
+ "create": "created",
+ "update": "modified",
+ "rename": "created",
+ "archive": "deleted",
+ }
+ for path in applied:
+ resolved = path.resolve()
+ try:
+ relative = resolved.relative_to(self._vault_root)
+ except ValueError:
+ log.warning(
+ "WikiCurator: cannot publish out-of-vault applied path %s",
+ resolved,
+ )
+ continue
+
+ event = WikiPageChanged(
+ slug=relative.stem,
+ path=relative.as_posix(),
+ kind=kinds.get(operations.get(resolved, "update"), "modified"),
+ )
+ try:
+ await self._event_publisher(event)
+ except Exception as exc: # noqa: BLE001
+ # The page and audit log have already landed. Live UI
+ # invalidation is auxiliary and must never turn that success
+ # into a retry that could duplicate durable information.
+ log.warning(
+ "WikiCurator: page write succeeded but live event publish "
+ "failed for %s: %s",
+ relative.as_posix(),
+ type(exc).__name__,
+ )
+
def _anchor_to_vault(self, upd: PageUpdate) -> PageUpdate:
"""Resolve a vault-relative ``target_path`` against the vault root.
diff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.py
index c0e4dd9635..813a5b2f83 100644
--- a/jarvis/memory/wiki/curator_llm.py
+++ b/jarvis/memory/wiki/curator_llm.py
@@ -15,9 +15,9 @@ parse error, schema mismatch, timeout, brain exception — produces an
empty ``list[PageUpdate]`` and a logged warning. The orchestrator is
required to keep running across LLM faults; raising is not an option.
-The salience filter (smalltalk → ``[]``) lives in the prompt, not here.
-We trust the LLM to follow the contract; we only validate its JSON
-shape and translate it into ``PageUpdate`` objects.
+The salience filter (smalltalk → ``[]``) lives in the prompt. Structural
+JSON checks and a narrow deterministic graph invariant protect explicit
+residence writes before translating them into ``PageUpdate`` objects.
Reference pattern: ``jarvis/awareness/verdichter.py`` (same brain-via-
config, timeout-via-wait_for, error-tolerant shape).
@@ -38,10 +38,13 @@ from jarvis.memory.wiki.prompt import (
build_system_prompt,
build_user_prompt,
compute_vault_summary,
+ resolve_user_entity_slug,
select_top_slugs,
)
from jarvis.memory.wiki.protocols import PageUpdate
+from jarvis.memory.wiki.residence import detect_residence_slug
from jarvis.memory.wiki.telemetry import telemetry
+from jarvis.memory.wiki.wikilink import extract_wikilinks
if TYPE_CHECKING:
from jarvis.core.config import JarvisConfig, WikiCuratorConfig
@@ -298,6 +301,99 @@ def _parse_updates(raw_text: str) -> list[PageUpdate]:
return updates
+def _body_links_to_slug(body: str, slug: str) -> bool:
+ """Return whether a Markdown body links to ``slug`` in any Wiki form."""
+ for raw_link in extract_wikilinks(body):
+ target = raw_link.split("|", 1)[0].strip().removesuffix(".md")
+ if target.rsplit("/", 1)[-1] == slug:
+ return True
+ return False
+
+
+def _existing_entity_body(vault: Any, slug: str) -> str | None:
+ """Return an existing entity body from a real or minimal vault index."""
+ page = None
+ try:
+ page = vault.find_by_slug(slug)
+ except Exception: # noqa: BLE001 - minimal vault fakes may omit lookup
+ page = None
+ if page is None:
+ try:
+ page = next(
+ (
+ candidate
+ for candidate in (vault.pages_by_type("entity") or [])
+ if getattr(candidate, "slug", "") == slug
+ ),
+ None,
+ )
+ except Exception: # noqa: BLE001 - semantic validation stays fail-closed
+ page = None
+ if page is None or getattr(page, "page_type", "entity") != "entity":
+ return None
+ path = getattr(page, "path", None)
+ if path is not None:
+ parts = Path(path).parts
+ if len(parts) < 2 or parts[-2:] != ("entities", f"{slug}.md"):
+ return None
+ body = getattr(page, "body", None)
+ return body if isinstance(body, str) else None
+
+
+def _effective_entity_body(
+ updates: list[PageUpdate],
+ *,
+ target: str,
+ slug: str,
+ vault: Any,
+) -> str | None:
+ """Return the proposed body for ``target``, or its current vault body."""
+ for update in reversed(updates):
+ if update.target_path.as_posix() != target:
+ continue
+ if update.operation == "archive":
+ return None
+ return update.new_body
+ return _existing_entity_body(vault, slug)
+
+
+def _semantic_graph_error(
+ source_content: str,
+ updates: list[PageUpdate],
+ *,
+ user_slug: str,
+ vault: Any,
+) -> str | None:
+ """Reject a grounded residence unless both linked graph pages exist."""
+ place_slug = detect_residence_slug(source_content)
+ if place_slug is None:
+ return None
+
+ place_target = f"entities/{place_slug}.md"
+ profile_target = f"entities/{user_slug}.md"
+ place_body = _effective_entity_body(
+ updates,
+ target=place_target,
+ slug=place_slug,
+ vault=vault,
+ )
+ if place_body is None:
+ return f"grounded residence is missing its graph page: {place_target}"
+ profile_body = _effective_entity_body(
+ updates,
+ target=profile_target,
+ slug=user_slug,
+ vault=vault,
+ )
+ if profile_body is None:
+ return f"grounded residence is missing its user profile: {profile_target}"
+ if not _body_links_to_slug(place_body, user_slug):
+ return "residence graph page does not link to the user profile"
+ if not _body_links_to_slug(profile_body, place_slug):
+ return "user profile does not link to the residence graph page"
+ return None
+
+
class WikiCuratorLLM:
"""Default ``CuratorLLM`` implementation.
@@ -394,14 +490,17 @@ class WikiCuratorLLM:
candidate_slugs = self._collect_candidate_slugs(vault, vault_summary)
top_slugs = select_top_slugs(source_content, candidate_slugs)
- system_prompt = build_system_prompt(
- schema_md,
- vault_summary,
- user_entity_slug=getattr(
+ user_slug = resolve_user_entity_slug(
+ getattr(
self._config.memory.wiki.session_rollup,
"user_entity_slug",
"",
- ),
+ )
+ )
+ system_prompt = build_system_prompt(
+ schema_md,
+ vault_summary,
+ user_entity_slug=user_slug,
)
user_prompt = build_user_prompt(source_label, source_content, top_slugs)
@@ -447,11 +546,20 @@ class WikiCuratorLLM:
rejection_reasons.append(reason)
return reason
try:
- _parse_updates(agg.text)
+ updates = _parse_updates(agg.text)
except (ValueError, json.JSONDecodeError) as exc:
reason = f"malformed update JSON: {exc}"
rejection_reasons.append(reason)
return reason
+ reason = _semantic_graph_error(
+ source_content,
+ updates,
+ user_slug=user_slug,
+ vault=vault,
+ )
+ if reason is not None:
+ rejection_reasons.append(reason)
+ return reason
return None
result = await complete_with_fallback(
diff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.py
index 148e7b2df2..dd2574c420 100644
--- a/jarvis/memory/wiki/extractor.py
+++ b/jarvis/memory/wiki/extractor.py
@@ -41,6 +41,7 @@ from jarvis.memory.wiki.curator_llm import (
)
from jarvis.memory.wiki.grounding import is_unsupported_user_interest_claim
from jarvis.memory.wiki.journal import CandidateFact, normalise_subjects
+from jarvis.memory.wiki.residence import detect_residence_slug
from jarvis.memory.wiki.secret_guard import contains_secret
from jarvis.memory.wiki.telemetry import telemetry
@@ -100,6 +101,8 @@ _KNOWN_KINDS = frozenset(
}
)
+_GRAPH_SUBJECT_KINDS = frozenset({"place"})
+
_SYSTEM_PROMPT = """\
You extract durable personal-memory facts from one FOCUS USER TURN. Earlier
@@ -136,6 +139,10 @@ Rules:
- Every element must use the exact focus turn id as evidence_turn_id.
- "subjects" names who/what the fact is about (e.g. ["person-name"],
["personal-jarvis"]). The caller supplies the speaker's exact user slug.
+ For a first-person fact about a named place, person, organization, project,
+ asset, or vehicle, include BOTH the exact user slug and the named topic slug.
+ Example: "I live in San Francisco" uses kind "place" and subjects
+ ["<user-slug>", "san-francisco"].
- Never include credentials, API keys, passwords, or tokens in a fact.
- No prose outside the JSON array.
"""
@@ -169,6 +176,10 @@ Rules:
the disclosed fact and never invent a reason for the question.
- Resolve pronouns and follow-up clarifications across turns. Prefer one
complete fact over several fragments.
+- For a first-person fact about a named place, person, organization, project,
+ asset, or vehicle, include BOTH the exact user slug and the named topic slug.
+ A residence in San Francisco uses kind "place" and subject
+ "san-francisco" alongside the exact user slug.
- Return [] for greetings, questions, commands without durable content,
transient bodily/status chatter, weather talk, and immediate-task details.
- Never include credentials, API keys, passwords, or tokens.
@@ -823,6 +834,15 @@ class ConversationFactExtractor:
reason = f"malformed JSON array: {exc}"
rejection_reasons.append(reason)
return reason
+ if not self._has_complete_residence_candidates(
+ parsed,
+ allowed_evidence=allowed_evidence,
+ fallback_evidence=fallback_evidence,
+ evidence_text_by_id=evidence_text_by_id,
+ ):
+ reason = "candidate array lacks a complete residence graph subject"
+ rejection_reasons.append(reason)
+ return reason
if parsed and not self._has_usable_fact_item(
parsed,
allowed_evidence=allowed_evidence,
@@ -949,8 +969,18 @@ class ConversationFactExtractor:
provider chain can ask a different family instead of recording a false
terminal ``empty`` result.
"""
+ if not self._has_complete_residence_candidates(
+ parsed,
+ allowed_evidence=allowed_evidence,
+ fallback_evidence=fallback_evidence,
+ evidence_text_by_id=evidence_text_by_id,
+ ):
+ telemetry.inc("wiki_candidates_blocked_incomplete_subjects")
+ return False
+
secret_count = 0
unsupported_interest_count = 0
+ incomplete_subject_count = 0
usable = False
for item in parsed[:max_facts]:
if not isinstance(item, dict):
@@ -972,6 +1002,15 @@ class ConversationFactExtractor:
if isinstance(raw_subjects, list)
else ()
)
+ kind = item.get("kind")
+ if not isinstance(kind, str) or kind not in _KNOWN_KINDS:
+ kind = "other"
+ if not self._graph_subjects_complete(
+ kind=kind,
+ subjects=subjects,
+ ):
+ incomplete_subject_count += 1
+ continue
if is_unsupported_user_interest_claim(
fact=fact,
subjects=subjects,
@@ -988,6 +1027,11 @@ class ConversationFactExtractor:
"wiki_candidates_blocked_unsupported_interest",
unsupported_interest_count,
)
+ if incomplete_subject_count:
+ telemetry.inc(
+ "wiki_candidates_blocked_incomplete_subjects",
+ incomplete_subject_count,
+ )
return usable
def _coerce_facts(
@@ -999,6 +1043,15 @@ class ConversationFactExtractor:
evidence_text_by_id: dict[str, str],
max_facts: int,
) -> list[CandidateFact]:
+ if not self._has_complete_residence_candidates(
+ parsed,
+ allowed_evidence=allowed_evidence,
+ fallback_evidence=fallback_evidence,
+ evidence_text_by_id=evidence_text_by_id,
+ ):
+ telemetry.inc("wiki_candidates_blocked_incomplete_subjects")
+ return []
+
facts: list[CandidateFact] = []
for item in parsed[:max_facts]:
if not isinstance(item, dict):
@@ -1032,6 +1085,16 @@ class ConversationFactExtractor:
evidence_text_by_id.get(evidence, ""),
max_chars=_MAX_EVIDENCE_EXCERPT_CHARS,
).strip()
+ if not self._graph_subjects_complete(
+ kind=kind,
+ subjects=subjects,
+ ):
+ telemetry.inc("wiki_candidates_blocked_incomplete_subjects")
+ log.info(
+ "ConversationFactExtractor: dropped graph fact without "
+ "complete user and topic subjects"
+ )
+ continue
if is_unsupported_user_interest_claim(
fact=fact,
subjects=subjects,
@@ -1054,6 +1117,64 @@ class ConversationFactExtractor:
)
return facts
+ def _graph_subjects_complete(
+ self,
+ *,
+ kind: str,
+ subjects: tuple[str, ...],
+ ) -> bool:
+ """Require a named topic beyond a lone user slug for graph facts."""
+ if kind not in _GRAPH_SUBJECT_KINDS:
+ return True
+ return self._user_entity_slug in subjects and any(
+ subject != self._user_entity_slug for subject in subjects
+ )
+
+ def _has_complete_residence_candidates(
+ self,
+ parsed: list[Any],
+ *,
+ allowed_evidence: set[str],
+ fallback_evidence: str,
+ evidence_text_by_id: dict[str, str],
+ ) -> bool:
+ """Require one correctly typed user/place candidate per residence turn."""
+ requirements = {
+ evidence: place_slug
+ for evidence, excerpt in evidence_text_by_id.items()
+ if evidence in allowed_evidence
+ and (
+ place_slug := detect_residence_slug(
+ excerpt.split("\nPrior user context", 1)[0]
+ )
+ )
+ }
+ for evidence, place_slug in requirements.items():
+ complete = False
+ for item in parsed:
+ if not isinstance(item, dict) or item.get("kind") != "place":
+ continue
+ raw_evidence = item.get("evidence_turn_id")
+ item_evidence = (
+ raw_evidence.strip()
+ if isinstance(raw_evidence, str) and raw_evidence.strip()
+ else fallback_evidence
+ )
+ if item_evidence != evidence:
+ continue
+ raw_subjects = item.get("subjects")
+ subjects = (
+ normalise_subjects(raw_subjects)
+ if isinstance(raw_subjects, list)
+ else ()
+ )
+ if self._user_entity_slug in subjects and place_slug in subjects:
+ complete = True
+ break
+ if not complete:
+ return False
+ return True
+
def _ensure_brain(self) -> Any:
"""Lazily instantiate the cheap brain; ``None`` when unavailable."""
if self._brain is not None:
diff --git a/jarvis/memory/wiki/integration.py b/jarvis/memory/wiki/integration.py
index 3a0162ba17..93312a23e1 100644
--- a/jarvis/memory/wiki/integration.py
+++ b/jarvis/memory/wiki/integration.py
@@ -42,7 +42,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from jarvis.core.events import IdleEntered
+from jarvis.core.events import IdleEntered, WikiPageChanged
if TYPE_CHECKING:
from jarvis.core.bus import EventBus
@@ -318,6 +318,7 @@ async def bootstrap_wiki_integration(
vault_root=vault_path,
brain_caller=brain_caller,
root_config=root_cfg,
+ event_publisher=bus.publish,
)
# Publish the live curator so the ``wiki-ingest`` tool can find it.
@@ -375,12 +376,14 @@ async def bootstrap_wiki_integration(
# idempotent skeleton pass; failures never break boot.
try:
from jarvis.memory.wiki.profile import ensure_profile_skeleton
+ from jarvis.memory.wiki.prompt import resolve_user_entity_slug
- user_slug = str(getattr(rollup_cfg, "user_entity_slug", "") or "")
- if user_slug:
- await ensure_profile_skeleton(
- vault_root=vault_path, slug=user_slug, curator=curator,
- )
+ user_slug = resolve_user_entity_slug(
+ getattr(rollup_cfg, "user_entity_slug", "")
+ )
+ await ensure_profile_skeleton(
+ vault_root=vault_path, slug=user_slug, curator=curator,
+ )
except Exception as exc: # noqa: BLE001
log.warning("wiki_integration: profile skeleton pass failed: %s", exc)
@@ -823,6 +826,7 @@ def _build_curator(
vault_root: Path,
brain_caller: Callable[[str, str], Awaitable[str]] | None,
root_config: Any | None = None,
+ event_publisher: Callable[[WikiPageChanged], Awaitable[None]] | None = None,
) -> Any:
"""Construct a :class:`~jarvis.memory.wiki.curator.WikiCurator` instance.
@@ -871,6 +875,7 @@ def _build_curator(
llm=llm,
log_writer=log_writer,
vault_root=vault_root,
+ event_publisher=event_publisher,
)
diff --git a/jarvis/memory/wiki/intent.py b/jarvis/memory/wiki/intent.py
index 2fa94a5687..eb47f4b352 100644
--- a/jarvis/memory/wiki/intent.py
+++ b/jarvis/memory/wiki/intent.py
@@ -7,7 +7,9 @@ model-independently.
Pure regex -- no LLM and no IO (AP-9/AP-11). The de/en/es tokens are speech
recognition input vocabulary (closed-list category 3). Precision remains the
-priority: every match requires both a write verb and an explicit wiki target.
+priority: every match requires both a write verb and either an explicit wiki
+target in the current turn or a locative reference to the immediately prior
+Wiki/Obsidian turn.
"""
from __future__ import annotations
@@ -24,7 +26,8 @@ _TRANSLITERATION = str.maketrans({
_WRITE_VERB_RE = re.compile(
r"\b(?:"
r"schreib\w*|notier\w*|speicher\w*|merk(?:e|st|t)?\s+(?:es\s+)?dir|"
- r"eintrag\w*|trag\w*|vermerk\w*|hinzufueg\w*|fueg\w*|" # i18n-allow
+ r"eintrag(?:en|e|st|t|end\w*)|eingetrag\w*|trag\w*|" # i18n-allow
+ r"vermerk\w*|hinzufueg\w*|fueg\w*|" # i18n-allow
r"write|save|note(?:\s+down)?|add|store|put|record|enter|update|"
r"escrib\w*|guard\w*|anot\w*|apunt\w*|agreg\w*|anad\w*|"
r"registr\w*|actualiz\w*|pon"
@@ -49,6 +52,27 @@ _WIKI_TARGET_RE = re.compile(
re.IGNORECASE,
)
+# A bounded prior turn may establish the destination for a locative follow-up
+# such as "put an entry there". Require a possessive personal-vault reference;
+# a general discussion about how wikis work must never authorise a durable
+# write. # i18n-allow: multilingual speech-input vocabulary
+_PERSONAL_WIKI_CONTEXT_RE = re.compile(
+ r"(?:"
+ r"\b(?:mein\w*|dein\w*|unser\w*|euer\w*|ihr\w*|my|your|our|"
+ r"mi|mis|tu|tus|nuestro\w*)\b.{0,64}"
+ r"\b(?:wiki(?:[\s-]?system)?|obsidian|vault)\b|"
+ r"\b(?:wiki(?:[\s-]?system)?|obsidian|vault)\b.{0,64}"
+ r"\b(?:mein\w*|dein\w*|unser\w*|euer\w*|ihr\w*|my|your|our|"
+ r"mi|mis|tu|tus|nuestro\w*)\b"
+ r")",
+ re.IGNORECASE,
+)
+_CONTEXTUAL_TARGET_RE = re.compile(
+ r"\b(?:da|dort|darein|da\s+rein|darin|hinein|there|in\s+it|into\s+it|"
+ r"ahi|alli|en\s+eso)\b",
+ re.IGNORECASE,
+)
+
# Polite question grammar may still express a command.
# The tokens are speech-input vocabulary. # i18n-allow
_POLITE_PREFIX_RE = re.compile(
@@ -91,7 +115,8 @@ _ANAPHORA = frozenset({
_FILLER_WORDS = frozenset({
"bitte", "mal", "doch", "kurz", "please", "por", "favor", "que",
- "dass", "ein", "hinzu", # i18n-allow: input vocabulary
+ "dass", "ein", "eine", "einen", "einem", "einer", "eintrag", "hinzu", # i18n-allow
+ "entry", "an", # i18n-allow: input vocabulary
})
_LEADING_FILLER_RE = re.compile(
@@ -174,8 +199,17 @@ def _match_target_before_verb(
return None
-def match_wiki_intent(user_text: str) -> WikiIntentMatch | None:
- """Return a match for an explicit wiki-write command, otherwise ``None``."""
+def match_wiki_intent(
+ user_text: str,
+ *,
+ prior_text: str | None = None,
+) -> WikiIntentMatch | None:
+ """Return a match for an explicit or bounded contextual Wiki write.
+
+ ``prior_text`` must be the immediately preceding user turn. It is used only
+ to resolve a locative destination in the current command; content is never
+ copied from it by this matcher.
+ """
norm = _normalize(user_text)
if not norm or len(norm) > 600:
return None
@@ -206,4 +240,18 @@ def match_wiki_intent(user_text: str) -> WikiIntentMatch | None:
if matched is not None:
_verb, content = matched
return WikiIntentMatch(content=content, matched=norm)
+
+ prior_norm = _normalize(prior_text or "")
+ if (
+ prior_norm
+ and len(prior_norm) <= 1_200
+ and _PERSONAL_WIKI_CONTEXT_RE.search(prior_norm)
+ ):
+ for target in _CONTEXTUAL_TARGET_RE.finditer(body):
+ matched = _match_verb_before_target(body, target)
+ if matched is None:
+ matched = _match_target_before_verb(body, target)
+ if matched is not None:
+ _verb, content = matched
+ return WikiIntentMatch(content=content, matched=norm)
return None
diff --git a/jarvis/memory/wiki/prompt.py b/jarvis/memory/wiki/prompt.py
index 07eeaf99a9..c63b2b4b3c 100644
--- a/jarvis/memory/wiki/prompt.py
+++ b/jarvis/memory/wiki/prompt.py
@@ -104,6 +104,12 @@ Rules:
with no commentary.
- Never break a `[[wikilink]]`. If a link would resolve nowhere, also
emit the missing target as a `create` update in the same array.
+- A named durable place, person, organization, project, owned asset, or
+ vehicle must be visually browsable as its own page; a bullet on the user
+ profile alone is not sufficient. Create the missing topic page in the same
+ array and link both pages. In particular, a disclosed residence creates or
+ updates `entities/<place-slug>.md` and links it bidirectionally with the
+ runtime-supplied user entity page.
- Every `new_body` must conform to `schema.md` (frontmatter keys, body
sections, page-type rules).
- Never touch `_archive/` or `attachments/`. Never write secrets.
@@ -471,8 +477,10 @@ Return ONLY a JSON array. Emit exactly one PRIMARY object per candidate. A
primary "add", "update" or "invalidate" may be followed by SECONDARY objects
with the same candidate_id: "invalidate" objects when a contradiction must
retire existing pages, and/or "add" objects that create a missing companion
-topic page in the same batch (see graph visibility below). No other
-duplicate candidate_id is allowed:
+topic page in the same batch (see graph visibility below). One narrowly scoped
+secondary "update" is also allowed when BOTH the existing user profile and an
+existing residence place page need their missing bidirectional link repaired.
+No other duplicate candidate_id is allowed:
{"candidate_id": <int>, "decision": "add" | "update" | "noop" | "invalidate",
"target": "<dir>/<slug>.md", "new_body": "<full page markdown>",
"superseded_by": "<slug>", "reason": "<short why>"}
@@ -519,6 +527,15 @@ batch and cross-link it with the profile in both directions. Do not create
topic pages for one-off mentions, smalltalk themes, or unsupported guesses
— the evidence rules above still apply.
+A grounded residence is always graph-visible: use kind `place`, require the
+candidate subjects to contain both the exact user slug and the named place
+slug, create `entities/<place-slug>.md` when missing, and cross-link the place
+and user profile in both directions. A profile-only residence decision is an
+invalid response, not a successful consolidation. If both pages already exist
+but either direction is missing, emit the two complete-page `update` objects
+under the same candidate_id; this residence-link repair is the ONLY permitted
+secondary update.
+
Page-type templates (frontmatter keys are mandatory):
- entities/<slug>.md: type: entity, entity_kind (person|tool|repository|
service|device|asset|vehicle|place|organization), slug, aliases, created,
diff --git a/jarvis/memory/wiki/residence.py b/jarvis/memory/wiki/residence.py
new file mode 100644
index 0000000000..86a919068d
--- /dev/null
+++ b/jarvis/memory/wiki/residence.py
@@ -0,0 +1,80 @@
+"""Deterministic residence detection shared by both Wiki review stages.
+
+The detector recognizes only an explicitly asserted current residence in the
+supported runtime languages. It supplies a schema-safe place slug so provider
+responses can be checked semantically instead of relying on prompt compliance.
+"""
+from __future__ import annotations
+
+import re
+
+from jarvis.memory.wiki.session_links import slugify
+
+_RESIDENCE_PLACE = r"(?P<place>[\w'.-]+(?:\s+[\w'.-]+){0,5}?)"
+_RESIDENCE_END = (
+ r"(?=\s*(?:[,;.!?]|$|\b(?:and|but|that|"
+ r"und|aber|dass|" # i18n-allow: German residence input vocabulary
+ r"y|pero|que)\b))"
+)
+_RESIDENCE_PATTERNS = (
+ re.compile(
+ r"\b(?:i|the\s+user|user|speaker)\s+"
+ r"(?:(?:now|currently)\s+)?"
+ r"(?:live|lives|reside|resides|am\s+based)\s+"
+ r"(?:now\s+)?(?:in|at)\s+"
+ + _RESIDENCE_PLACE
+ + _RESIDENCE_END,
+ re.IGNORECASE,
+ ),
+ re.compile(
+ r"\b(?:ich|der\s+benutzer|" # i18n-allow: German input vocabulary
+ r"die\s+nutzerin)\s+" # i18n-allow: German residence input vocabulary
+ r"(?:(?:jetzt|aktuell)\s+)?" # i18n-allow: German residence input vocabulary
+ r"(?:wohne|wohnt|lebe|lebt)\s+" # i18n-allow: German residence input vocabulary
+ r"(?:(?:jetzt|aktuell)\s+)?in\s+" # i18n-allow: German residence input vocabulary
+ + _RESIDENCE_PLACE
+ + _RESIDENCE_END,
+ re.IGNORECASE,
+ ),
+ re.compile(
+ r"\bich\s+(?:(?:jetzt|aktuell)\s+)?in\s+" # i18n-allow: German residence input vocabulary
+ + _RESIDENCE_PLACE
+ + r"\s+(?:wohne|lebe)\b", # i18n-allow: German residence input vocabulary
+ re.IGNORECASE,
+ ),
+ re.compile(
+ r"\b(?:yo\s+)?(?:vivo|resido)\s+(?:ahora\s+)?en\s+"
+ + _RESIDENCE_PLACE
+ + _RESIDENCE_END,
+ re.IGNORECASE,
+ ),
+)
+_RESIDENCE_TRAILING_WORDS = frozenset(
+ {
+ "now",
+ "currently",
+ "jetzt", # i18n-allow: German residence input vocabulary
+ "aktuell", # i18n-allow: German residence input vocabulary
+ "nun", # i18n-allow: German residence input vocabulary
+ "ahora",
+ }
+)
+
+
+def detect_residence_slug(source_content: str) -> str | None:
+ """Return the named place slug from an asserted current residence."""
+ source = " ".join(str(source_content or "").split())
+ for pattern in _RESIDENCE_PATTERNS:
+ match = pattern.search(source)
+ if match is None:
+ continue
+ words = match.group("place").strip(" '.-").split()
+ while words and words[-1].casefold() in _RESIDENCE_TRAILING_WORDS:
+ words.pop()
+ place_slug = slugify(" ".join(words))
+ if place_slug:
+ return place_slug
+ return None
+
+
+__all__ = ["detect_residence_slug"]
diff --git a/jarvis/memory/wiki/scheduler.py b/jarvis/memory/wiki/scheduler.py
index e0a8906bdd..1a1d794b50 100644
--- a/jarvis/memory/wiki/scheduler.py
+++ b/jarvis/memory/wiki/scheduler.py
@@ -286,12 +286,20 @@ class CuratorScheduler:
"""
active = self._journal_fire_task
if active is not None and not active.done():
- drain = self._journal_drain_task
- if drain is not None and not drain.done():
- self._journal_dirty = True
+ # Mark every request that arrives before the shared fire task is
+ # completely done. The inner drain normally consumes this flag,
+ # while ``_run_scheduled_journal_trigger`` closes the tiny tail
+ # window after the drain's final check but before the outer task
+ # returns. Without that hand-off, a candidate appended as soon as
+ # the previous page appeared on disk could remain pending until a
+ # later turn happened to trigger another drain.
+ self._journal_dirty = True
return active
- active = asyncio.create_task(self.trigger(TriggerSource.JOURNAL), name=name)
+ active = asyncio.create_task(
+ self._run_scheduled_journal_trigger(),
+ name=name,
+ )
self._journal_fire_task = active
def _clear(done: asyncio.Task[SchedulerResult]) -> None:
@@ -301,6 +309,14 @@ class CuratorScheduler:
active.add_done_callback(_clear)
return active
+ async def _run_scheduled_journal_trigger(self) -> SchedulerResult:
+ """Run one shared fire task until every late request is observed."""
+ result = await self.trigger(TriggerSource.JOURNAL)
+ while self._journal_dirty:
+ self._journal_dirty = False
+ result = await self.trigger(TriggerSource.JOURNAL)
+ return result
+
async def shutdown(self, *, timeout_s: float = 5.0) -> None:
"""Drain or cancel journal work before the shared journal is closed."""
tasks = {
diff --git a/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts b/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
index 813b9840e5..c75bfdce8c 100644
--- a/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
+++ b/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
@@ -1,51 +1,58 @@
-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
-import { renderHook, act } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createElement, ReactNode } from "react";
import { useWikiLive } from "@/hooks/useWikiLive";
-/** Minimal mock for WebSocket with onopen/onmessage/onclose/onerror plumbing. */
+/** Minimal event-listener WebSocket mock compatible with the shared client. */
class MockWebSocket {
static OPEN = 1;
static CLOSED = 3;
- readyState = MockWebSocket.OPEN;
static instances: MockWebSocket[] = [];
- onopen: ((ev: unknown) => void) | null = null;
- onmessage: ((ev: { data: string }) => void) | null = null;
- onclose: ((ev: unknown) => void) | null = null;
- onerror: ((ev: unknown) => void) | null = null;
+ readyState = MockWebSocket.OPEN;
+ readonly url: string;
+ private listeners: Record<string, Array<(event: any) => void>> = {};
+
+ constructor(url: string) {
+ this.url = url;
+ MockWebSocket.instances.push(this);
+ queueMicrotask(() => this.fire("open", {}));
+ }
+
+ addEventListener(type: string, listener: (event: any) => void) {
+ (this.listeners[type] ??= []).push(listener);
+ }
+
+ send = vi.fn();
- url: string;
close = vi.fn(() => {
+ if (this.readyState === MockWebSocket.CLOSED) return;
this.readyState = MockWebSocket.CLOSED;
- if (this.onclose) this.onclose({});
+ this.fire("close", { code: 1000 });
});
- constructor(url: string) {
- this.url = url;
- MockWebSocket.instances.push(this);
- // Fire open on the next tick so the consumer's effect has run.
- queueMicrotask(() => {
- if (this.onopen) this.onopen({});
- });
+ fire(type: string, event: any) {
+ if (type === "close") this.readyState = MockWebSocket.CLOSED;
+ for (const listener of this.listeners[type] ?? []) listener(event);
}
deliver(payload: unknown) {
const data = typeof payload === "string" ? payload : JSON.stringify(payload);
- if (this.onmessage) this.onmessage({ data });
+ this.fire("message", { data });
}
}
function wrapper({ children }: { children: ReactNode }) {
- const qc = new QueryClient({
+ const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
- return createElement(QueryClientProvider, { client: qc }, children);
+ return createElement(QueryClientProvider, { client: queryClient }, children);
}
describe("useWikiLive", () => {
- const OriginalWS = globalThis.WebSocket;
+ const originalWebSocket = globalThis.WebSocket;
+ const originalFetch = globalThis.fetch;
beforeEach(() => {
MockWebSocket.instances = [];
@@ -57,15 +64,19 @@ describe("useWikiLive", () => {
});
afterEach(() => {
- (globalThis as any).WebSocket = OriginalWS;
+ vi.useRealTimers();
+ (globalThis as any).WebSocket = originalWebSocket;
+ (globalThis as any).fetch = originalFetch;
});
- it("opens a WebSocket on mount and sets connected=true after open", async () => {
+ it("opens the live socket and reports the connected state", async () => {
const { result } = renderHook(() => useWikiLive(), { wrapper });
- expect(MockWebSocket.instances.length).toBe(1);
- expect(MockWebSocket.instances[0].url).toContain("/api/wiki/live");
- // Wait a microtask so the queued open fires.
+ expect(MockWebSocket.instances).toHaveLength(1);
+ expect(MockWebSocket.instances[0].url).toBe(
+ "ws://localhost:5173/api/wiki/live",
+ );
+
await act(async () => {
await Promise.resolve();
});
@@ -73,18 +84,19 @@ describe("useWikiLive", () => {
});
it("refreshes every wiki projection when the socket opens", async () => {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- const spy = vi.spyOn(qc, "invalidateQueries");
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
const customWrapper = ({ children }: { children: ReactNode }) =>
- createElement(QueryClientProvider, { client: qc }, children);
+ createElement(QueryClientProvider, { client: queryClient }, children);
renderHook(() => useWikiLive(), { wrapper: customWrapper });
await act(async () => {
await Promise.resolve();
});
- const keys = spy.mock.calls.map((call) => call[0]?.queryKey);
- expect(keys).toEqual([
+ expect(invalidate.mock.calls.map((call) => call[0]?.queryKey)).toEqual([
["wiki", "tree"],
["wiki", "graph"],
["wiki", "health"],
@@ -95,31 +107,32 @@ describe("useWikiLive", () => {
});
it("refreshes every wiki projection on page_changed", async () => {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- const spy = vi.spyOn(qc, "invalidateQueries");
-
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
const customWrapper = ({ children }: { children: ReactNode }) =>
- createElement(QueryClientProvider, { client: qc }, children);
+ createElement(QueryClientProvider, { client: queryClient }, children);
- const { result } = renderHook(() => useWikiLive(), { wrapper: customWrapper });
+ const { result } = renderHook(() => useWikiLive(), {
+ wrapper: customWrapper,
+ });
await act(async () => {
await Promise.resolve();
});
- expect(result.current.connected).toBe(true);
- spy.mockClear();
+ invalidate.mockClear();
await act(async () => {
MockWebSocket.instances[0].deliver({
type: "page_changed",
- slug: "harald",
- path: "entities/harald.md",
+ slug: "nova",
+ path: "entities/nova.md",
kind: "modified",
});
await Promise.resolve();
});
- const keys = spy.mock.calls.map((call) => call[0]?.queryKey);
- expect(keys).toEqual([
+ expect(invalidate.mock.calls.map((call) => call[0]?.queryKey)).toEqual([
["wiki", "tree"],
["wiki", "graph"],
["wiki", "health"],
@@ -130,43 +143,76 @@ describe("useWikiLive", () => {
expect(result.current.lastEventAt).not.toBeNull();
});
- it("closes the WebSocket on unmount and stops further work", async () => {
+ it("retries a 4401 WebKit rejection with a one-time ticket", async () => {
+ vi.useFakeTimers();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ ticket: "wiki-ticket", expires_in: 60 }),
+ });
+ (globalThis as any).fetch = fetchMock;
+
+ const { result, unmount } = renderHook(() => useWikiLive(), { wrapper });
+ const firstSocket = MockWebSocket.instances[0];
+
+ await act(async () => {
+ firstSocket.fire("close", { code: 4401 });
+ await vi.advanceTimersByTimeAsync(500);
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/ui/ws-ticket",
+ expect.objectContaining({
+ method: "POST",
+ cache: "no-store",
+ credentials: "same-origin",
+ }),
+ );
+ expect(MockWebSocket.instances).toHaveLength(2);
+ expect(MockWebSocket.instances[1].url).toBe(
+ "ws://localhost:5173/api/wiki/live?ticket=wiki-ticket",
+ );
+ expect(result.current.connected).toBe(true);
+
+ unmount();
+ });
+
+ it("closes the socket on unmount without reconnecting", async () => {
+ vi.useFakeTimers();
const { unmount } = renderHook(() => useWikiLive(), { wrapper });
await act(async () => {
- await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(0);
});
- const ws = MockWebSocket.instances[0];
- expect(ws.close).not.toHaveBeenCalled();
+ const socket = MockWebSocket.instances[0];
unmount();
- expect(ws.close).toHaveBeenCalled();
- // After unmount, no further reconnect happens even if we wait.
- const before = MockWebSocket.instances.length;
+ expect(socket.close).toHaveBeenCalledOnce();
+
await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 50));
+ await vi.advanceTimersByTimeAsync(60_000);
});
- expect(MockWebSocket.instances.length).toBe(before);
+ expect(MockWebSocket.instances).toHaveLength(1);
});
- it("ignores malformed messages", async () => {
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- const spy = vi.spyOn(qc, "invalidateQueries");
-
+ it("ignores malformed and unrelated messages", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
const customWrapper = ({ children }: { children: ReactNode }) =>
- createElement(QueryClientProvider, { client: qc }, children);
+ createElement(QueryClientProvider, { client: queryClient }, children);
+
renderHook(() => useWikiLive(), { wrapper: customWrapper });
await act(async () => {
await Promise.resolve();
});
- spy.mockClear();
+ invalidate.mockClear();
await act(async () => {
MockWebSocket.instances[0].deliver("not json at all");
MockWebSocket.instances[0].deliver({ type: "something_else" });
await Promise.resolve();
});
- // The spy must NOT have been called — malformed and unrelated
- // messages are silently dropped.
- expect(spy).not.toHaveBeenCalled();
+
+ expect(invalidate).not.toHaveBeenCalled();
});
});
diff --git a/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts b/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
index cae62ebb88..c2cd420586 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
@@ -1,25 +1,25 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { WSClient } from "@/lib/ws";
/**
* Live-reload hook for the desktop wiki view.
*
- * Mounts a WebSocket connection to `/api/wiki/live` and invalidates the
- * all React Query caches that project vault state every time the server
- * connects or pushes a `page_changed` message.
+ * Mounts a WebSocket connection to `/api/wiki/live` and invalidates all
+ * React Query caches that project vault state every time the server connects
+ * or pushes a `page_changed` message.
*
- * Mount this hook **once** at the WikiView level (not deeper). Switching
- * away from the wiki tab unmounts the hook and closes the socket — that
- * is the desired behaviour: no background polling when the user is on
- * another tab.
+ * Mount this hook once at the WikiView level. Switching away from the wiki
+ * tab unmounts the hook and closes the socket, so no background connection
+ * remains while the user is on another tab.
*
- * Reconnects use exponential backoff starting at 1 s and capped at
- * 30 s so a flapping server cannot DOS itself.
+ * The shared transport handles reconnect backoff and the one-time-ticket
+ * authentication fallback required by Safari and WKWebView.
*/
export interface UseWikiLiveResult {
- /** True while the WS is OPEN. False during connect, reconnect, or after unmount. */
+ /** True while the WebSocket is open. */
connected: boolean;
- /** Wall-clock ms of the last forwarded `page_changed` event, or null. */
+ /** Wall-clock milliseconds of the last forwarded event, or null. */
lastEventAt: number | null;
}
@@ -32,36 +32,31 @@ interface PageChangedMessage {
function isPageChanged(value: unknown): value is PageChangedMessage {
if (typeof value !== "object" || value === null) return false;
- const v = value as Record<string, unknown>;
+ const message = value as Record<string, unknown>;
return (
- v.type === "page_changed" &&
- typeof v.slug === "string" &&
- typeof v.path === "string" &&
- (v.kind === "created" || v.kind === "modified" || v.kind === "deleted")
+ message.type === "page_changed" &&
+ typeof message.slug === "string" &&
+ typeof message.path === "string" &&
+ (message.kind === "created" ||
+ message.kind === "modified" ||
+ message.kind === "deleted")
);
}
function buildWsUrl(): string {
- // Always derive from the current host so dev (Vite proxy) and prod
- // (pywebview/launcher on 47821) both work without config.
- const proto = window.location.protocol === "https:" ? "wss" : "ws";
- return `${proto}://${window.location.host}/api/wiki/live`;
+ // Derive the URL from the current host so the Vite proxy and packaged
+ // desktop launcher work without separate configuration.
+ const protocol = window.location.protocol === "https:" ? "wss" : "ws";
+ return `${protocol}://${window.location.host}/api/wiki/live`;
}
export function useWikiLive(): UseWikiLiveResult {
- const qc = useQueryClient();
+ const queryClient = useQueryClient();
const [connected, setConnected] = useState(false);
const [lastEventAt, setLastEventAt] = useState<number | null>(null);
- // Refs so the effect deps stay stable (we only re-run on qc change).
- const wsRef = useRef<WebSocket | null>(null);
- const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const reconnectAttemptsRef = useRef(0);
- const mountedRef = useRef(true);
-
useEffect(() => {
- mountedRef.current = true;
- const url = buildWsUrl();
+ let active = true;
const invalidateWikiProjection = () => {
// Prefix invalidation is intentional for pages, searches, and backlinks.
@@ -75,99 +70,36 @@ export function useWikiLive(): UseWikiLiveResult {
["wiki", "page"],
["wiki", "backlinks"],
]) {
- void qc.invalidateQueries({ queryKey });
+ void queryClient.invalidateQueries({ queryKey });
}
};
- const scheduleReconnect = () => {
- if (!mountedRef.current) return;
- // Exponential backoff capped at 30 s, with a small floor at 250 ms
- // so the first immediate retry on a flap is still snappy.
- const attempt = reconnectAttemptsRef.current;
- const delayMs = Math.min(30_000, Math.max(250, 1000 * Math.pow(2, attempt)));
- reconnectAttemptsRef.current = attempt + 1;
- reconnectTimerRef.current = setTimeout(() => {
- reconnectTimerRef.current = null;
- connect();
- }, delayMs);
- };
-
- const connect = () => {
- if (!mountedRef.current) return;
- let ws: WebSocket;
- try {
- ws = new WebSocket(url);
- } catch {
- // Constructor itself may throw on a malformed URL (jsdom edge
- // cases). Treat as a close.
- scheduleReconnect();
- return;
- }
- wsRef.current = ws;
-
- ws.onopen = () => {
- if (!mountedRef.current) return;
- reconnectAttemptsRef.current = 0;
+ const client = new WSClient({
+ url: buildWsUrl(),
+ onOpen: () => {
+ if (!active) return;
setConnected(true);
// Recover any events missed while the socket was disconnected.
invalidateWikiProjection();
- };
-
- ws.onmessage = (ev: MessageEvent) => {
- if (!mountedRef.current) return;
- let parsed: unknown;
- try {
- parsed = JSON.parse(typeof ev.data === "string" ? ev.data : "");
- } catch {
- return;
- }
- if (!isPageChanged(parsed)) return;
- // Refresh every projection, including relationship targets whose
- // backlinks changed even though their own page did not.
+ },
+ onMessage: (message) => {
+ if (!active || !isPageChanged(message)) return;
invalidateWikiProjection();
setLastEventAt(Date.now());
- };
-
- ws.onclose = () => {
- if (!mountedRef.current) return;
+ },
+ onClose: () => {
+ if (!active) return;
setConnected(false);
- wsRef.current = null;
- scheduleReconnect();
- };
-
- ws.onerror = () => {
- // Some browsers fire error then close; some only fire error.
- // Force a close so the onclose path runs.
- try {
- ws.close();
- } catch {
- /* noop */
- }
- };
- };
+ },
+ });
- connect();
+ client.connect();
return () => {
- mountedRef.current = false;
- if (reconnectTimerRef.current !== null) {
- clearTimeout(reconnectTimerRef.current);
- reconnectTimerRef.current = null;
- }
- const ws = wsRef.current;
- if (ws !== null) {
- // Detach onclose first so the cleanup doesn't trigger a reconnect.
- ws.onclose = null;
- ws.onerror = null;
- try {
- ws.close();
- } catch {
- /* noop */
- }
- wsRef.current = null;
- }
+ active = false;
+ client.close();
};
- }, [qc]);
+ }, [queryClient]);
return { connected, lastEventAt };
}
diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.py
index fae1b708b8..280f0973a3 100644
--- a/jarvis/ui/web/wiki_routes.py
+++ b/jarvis/ui/web/wiki_routes.py
@@ -18,10 +18,10 @@ logical errors. HTTP 404 stays reserved for unknown routes; HTTP 500 only
fires on unhandled exceptions. The write endpoint uses non-2xx responses when
nothing was stored so CLI and agent callers cannot mistake a no-op for success.
-The module reuses ``PageRepository`` (B1, ``jarvis/memory/wiki/page.py``),
-``VaultIndex`` (B1, ``jarvis/memory/wiki/vault_index.py``) and
-``VaultSearch`` (B5, ``jarvis/memory/wiki/search.py``), and the guarded Wiki
-ingest service. It never writes Wiki files directly.
+The module reuses the tolerant Markdown parser (B1,
+``jarvis/memory/wiki/page.py``), ``VaultSearch`` (B5,
+``jarvis/memory/wiki/search.py``), and the guarded Wiki ingest service. It
+never writes Wiki files directly.
The vault root is read from ``app.state.config.wiki_integration.vault_root``.
Tests can override the path by setting that attribute directly before the
@@ -32,7 +32,9 @@ from __future__ import annotations
import asyncio
import logging
+import os
import time
+from dataclasses import dataclass
from datetime import UTC
from pathlib import Path
from typing import Any
@@ -50,11 +52,10 @@ from jarvis.memory.wiki.integration import (
get_running_capture_runtime,
get_running_curator,
)
-from jarvis.memory.wiki.page import MarkdownPageRepository
+from jarvis.memory.wiki.page import parse_markdown
from jarvis.memory.wiki.protocols import WikiPage
from jarvis.memory.wiki.search import VaultSearch
from jarvis.memory.wiki.telemetry import telemetry as _telemetry
-from jarvis.memory.wiki.vault_index import VaultIndex
from jarvis.memory.wiki.vault_root import resolve_vault_root
from jarvis.memory.wiki.wikilink import (
_canonicalise as _canonicalise_link, # type: ignore[attr-defined]
@@ -64,7 +65,7 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/wiki", tags=["wiki"])
-# Directories that VaultIndex / page tree walks. Order matters for stable UI.
+# Canonical directories remain first in the tree for response compatibility.
_PAGE_DIRS: tuple[tuple[str, str], ...] = (
("entities", "entity"),
("concepts", "concept"),
@@ -72,6 +73,13 @@ _PAGE_DIRS: tuple[tuple[str, str], ...] = (
("sessions", "session"),
)
+# Frozen history and binary-only storage are not live Wiki pages. Hidden
+# directories (for example .obsidian and .trash) are pruned separately.
+_EXCLUDED_PAGE_DIRS: frozenset[str] = frozenset(
+ {"_archive", "attachments", "90-attachments"}
+)
+_ROOT_FOLDER_NAME = "root"
+
# Snippet window (chars) for backlink context extraction around the wikilink.
_BACKLINK_SNIPPET_RADIUS = 80
_BACKLINK_SNIPPET_MAX = 200
@@ -160,86 +168,142 @@ def _human_title_from_slug(slug: str) -> str:
# ----------------------------------------------------------------------
-# Walking helpers (off-loop)
+# Visible-vault projection (off-loop)
# ----------------------------------------------------------------------
-def _walk_tree_sync(vault_root: Path) -> tuple[list[dict[str, Any]], int, float | None]:
- """Walk the four page directories. Returns (folders, total_pages, log_mtime)."""
- folders: list[dict[str, Any]] = []
- total_pages = 0
- for dirname, kind in _PAGE_DIRS:
- folder = vault_root / dirname
- files: list[dict[str, Any]] = []
- if folder.is_dir():
- for md_path in sorted(folder.glob("*.md")):
- if md_path.name.startswith("."):
- continue
- try:
- stat = md_path.stat()
- except OSError as exc:
- log.warning("wiki_route_walk_failed: %s — %s", md_path, exc)
- continue
- title = _title_from_disk(md_path)
- files.append(
- {
- "slug": md_path.stem,
- "title": title,
- "mtime": stat.st_mtime,
- "size": stat.st_size,
- }
- )
- total_pages += len(files)
- folders.append(
- {
- "name": dirname,
- "kind": kind,
- "count": len(files),
- "files": files,
- }
+@dataclass(frozen=True, slots=True)
+class _VisiblePage:
+ """One live Markdown page plus filesystem metadata for route responses."""
+
+ page: WikiPage
+ relative_path: Path
+ mtime: float
+ size: int
+
+
+def _visible_path_sort_key(relative_path: Path) -> tuple[int, str]:
+ """Keep canonical page directories first, then root and custom folders."""
+ parts = relative_path.parts
+ top = parts[0] if len(parts) > 1 else ""
+ standard_order = {name: index for index, (name, _) in enumerate(_PAGE_DIRS)}
+ if top in standard_order:
+ rank = standard_order[top]
+ elif not top:
+ rank = len(_PAGE_DIRS)
+ else:
+ rank = len(_PAGE_DIRS) + 1
+ return rank, relative_path.as_posix().casefold()
+
+
+def _scan_visible_pages_sync(vault_root: Path) -> list[_VisiblePage]:
+ """Parse every user-visible Markdown page below ``vault_root``.
+
+ Hidden trees, frozen archive history, and attachment stores are pruned
+ before files are opened. Symlinked files that resolve outside the vault
+ are also ignored so a crafted vault cannot expose unrelated host files.
+ """
+ root = vault_root.resolve()
+ paths: list[tuple[Path, Path]] = []
+ for current, dirnames, filenames in os.walk(root, followlinks=False):
+ dirnames[:] = sorted(
+ (
+ name
+ for name in dirnames
+ if not name.startswith(".")
+ and name.casefold() not in _EXCLUDED_PAGE_DIRS
+ ),
+ key=str.casefold,
)
+ current_path = Path(current)
+ for filename in sorted(filenames, key=str.casefold):
+ if filename.startswith(".") or Path(filename).suffix.casefold() != ".md":
+ continue
+ path = current_path / filename
+ try:
+ resolved = path.resolve()
+ resolved.relative_to(root)
+ relative = path.relative_to(root)
+ except (OSError, ValueError):
+ continue
+ paths.append((path, relative))
- log_mtime: float | None = None
- log_path = vault_root / "log.md"
- if log_path.is_file():
+ paths.sort(key=lambda item: _visible_path_sort_key(item[1]))
+ visible: list[_VisiblePage] = []
+ for path, relative in paths:
try:
- log_mtime = log_path.stat().st_mtime
- except OSError:
- log_mtime = None
- return folders, total_pages, log_mtime
+ raw = path.read_text(encoding="utf-8", errors="replace")
+ stat = path.stat()
+ except OSError as exc:
+ log.warning("wiki_route_walk_failed: %s - %s", path, exc)
+ continue
+ visible.append(
+ _VisiblePage(
+ page=parse_markdown(raw, path),
+ relative_path=relative,
+ mtime=stat.st_mtime,
+ size=stat.st_size,
+ )
+ )
+ return visible
-def _title_from_disk(md_path: Path) -> str:
- """Cheap H1 extraction without a full parse. Falls back to humanised stem."""
- try:
- # Read only the first ~2 KB; an H1 always sits at the top.
- head = md_path.read_text(encoding="utf-8", errors="replace")[:2048]
- except OSError:
- return _human_title_from_slug(md_path.stem)
- in_frontmatter = False
- for raw_line in head.splitlines():
- line = raw_line.rstrip()
- if line == "---":
- in_frontmatter = not in_frontmatter
- continue
- if in_frontmatter:
- continue
- stripped = line.lstrip()
- if stripped.startswith("# "):
- return stripped[2:].strip()
- return _human_title_from_slug(md_path.stem)
+async def _scan_visible_pages(vault_root: Path) -> list[_VisiblePage]:
+ """Build a fresh, non-blocking projection of the active Obsidian vault."""
+ return await asyncio.to_thread(_scan_visible_pages_sync, vault_root)
-async def _build_index(vault_root: Path) -> VaultIndex:
- """Build a freshly scanned ``VaultIndex`` over ``vault_root``.
+def _folder_name(relative_path: Path) -> str:
+ parent = relative_path.parent
+ return _ROOT_FOLDER_NAME if parent == Path(".") else parent.as_posix()
- Reading is delegated to ``asyncio.to_thread`` inside the repository, so
- this coroutine can run on the event loop without blocking.
- """
- repo = MarkdownPageRepository()
- index = VaultIndex(repo=repo)
- await index.scan(vault_root)
- return index
+
+def _folder_kind(name: str, pages: list[_VisiblePage]) -> str:
+ standard_kinds = dict(_PAGE_DIRS)
+ if name in standard_kinds:
+ return standard_kinds[name]
+ kinds = {item.page.page_type for item in pages if item.page.page_type}
+ return next(iter(kinds)) if len(kinds) == 1 else "meta"
+
+
+def _tree_from_visible_pages(
+ visible: list[_VisiblePage],
+) -> tuple[list[dict[str, Any]], float | None]:
+ """Return compatible flat folder buckets plus the root log timestamp."""
+ grouped: dict[str, list[_VisiblePage]] = {name: [] for name, _ in _PAGE_DIRS}
+ log_mtime: float | None = None
+ for item in visible:
+ name = _folder_name(item.relative_path)
+ grouped.setdefault(name, []).append(item)
+ if item.relative_path.as_posix() == "log.md":
+ log_mtime = item.mtime
+
+ standard_names = [name for name, _ in _PAGE_DIRS]
+ extra_names = sorted(
+ (name for name in grouped if name not in standard_names),
+ key=lambda name: (name != _ROOT_FOLDER_NAME, name.casefold()),
+ )
+ folders: list[dict[str, Any]] = []
+ for name in [*standard_names, *extra_names]:
+ pages = grouped[name]
+ files = [
+ {
+ "slug": item.page.slug,
+ "title": item.page.frontmatter.get("title") or _title_of(item.page),
+ "mtime": item.mtime,
+ "size": item.size,
+ }
+ for item in pages
+ ]
+ folders.append(
+ {
+ "name": name,
+ "kind": _folder_kind(name, pages),
+ "count": len(files),
+ "files": files,
+ }
+ )
+ return folders, log_mtime
# ----------------------------------------------------------------------
@@ -274,23 +338,13 @@ async def get_tree(request: Request) -> dict[str, Any]:
}
try:
- folders, total_pages, log_mtime = await asyncio.to_thread(
- _walk_tree_sync, vault_root
- )
+ visible = await _scan_visible_pages(vault_root)
+ folders, log_mtime = _tree_from_visible_pages(visible)
except Exception as exc: # noqa: BLE001
log.warning("wiki_route_failed route=/tree error=%s", exc)
return {"ok": False, "error": "tree walk failed"}
- total_links = 0
- try:
- index = await _build_index(vault_root)
- for _, kind in _PAGE_DIRS:
- for page in index.pages_by_type(kind):
- total_links += len(getattr(page, "wikilinks", ()))
- except Exception as exc: # noqa: BLE001
- log.warning("wiki_route_failed route=/tree (link count) error=%s", exc)
- # Don't fail the whole response if only the link count is degraded.
- total_links = 0
+ total_links = sum(len(item.page.wikilinks) for item in visible)
last_curator_run = _format_mtime(log_mtime)
@@ -299,7 +353,7 @@ async def get_tree(request: Request) -> dict[str, Any]:
"vault_root": vault_str,
"folders": folders,
"stats": {
- "total_pages": total_pages,
+ "total_pages": len(visible),
"total_links": total_links,
"last_curator_run": last_curator_run,
},
@@ -352,7 +406,7 @@ async def get_page(slug: str, request: Request) -> dict[str, Any]:
"frontmatter": dict(page.frontmatter),
"frontmatter_valid": bool(page.is_schema_valid),
"body_md": body_md,
- "wikilinks": [_canonicalise_link(link).rsplit("/", 1)[-1] for link in page.wikilinks],
+ "wikilinks": [_link_slug(link) for link in page.wikilinks],
"stats": {
"words": words,
"bytes": size_bytes,
@@ -373,14 +427,12 @@ async def get_graph(request: Request) -> dict[str, Any]:
return {"ok": True, "nodes": [], "edges": [], "broken": []}
try:
- index = await _build_index(vault_root)
+ visible = await _scan_visible_pages(vault_root)
except Exception as exc: # noqa: BLE001
log.warning("wiki_route_failed route=/graph error=%s", exc)
return {"ok": False, "error": "graph build failed"}
- pages: list[WikiPage] = []
- for _, kind in _PAGE_DIRS:
- pages.extend(index.pages_by_type(kind))
+ pages = [item.page for item in visible]
nodes: list[dict[str, Any]] = []
known_slugs: set[str] = set()
@@ -402,7 +454,7 @@ async def get_graph(request: Request) -> dict[str, Any]:
for page in pages:
body = page.body
for raw_link in page.wikilinks:
- target_slug = _canonicalise_link(raw_link).rsplit("/", 1)[-1]
+ target_slug = _link_slug(raw_link)
if not target_slug:
continue
context = _link_context(body, raw_link, target_slug)
@@ -439,12 +491,16 @@ async def get_backlinks(slug: str, request: Request) -> dict[str, Any]:
return {"ok": True, "slug": slug, "backlinks": []}
try:
- index = await _build_index(vault_root)
+ visible = await _scan_visible_pages(vault_root)
except Exception as exc: # noqa: BLE001
log.warning("wiki_route_failed route=/backlinks/%s error=%s", slug, exc)
return {"ok": False, "error": "backlinks lookup failed"}
- sources: list[WikiPage] = index.backlinks_to(slug)
+ sources = [
+ item.page
+ for item in visible
+ if any(_link_slug(link) == slug for link in item.page.wikilinks)
+ ]
out: list[dict[str, Any]] = []
for src in sources:
snippet = _link_context(src.body, slug, slug)
@@ -714,31 +770,10 @@ def _is_safe_slug(slug: str) -> bool:
async def _find_page(vault_root: Path, slug: str) -> WikiPage | None:
- """Locate a page by slug across the four page directories.
-
- Falls back from the ``VaultIndex`` (which skips schema-invalid pages)
- to a direct file probe so the UI can still render malformed pages with
- a warning banner.
- """
- index = await _build_index(vault_root)
- page = index.find_by_slug(slug)
- if page is not None:
- return page
-
- # Fallback: parse a schema-invalid page directly so the UI can show it.
- repo = MarkdownPageRepository()
- for dirname, _ in _PAGE_DIRS:
- candidate = vault_root / dirname / f"{slug}.md"
- if candidate.is_file():
- try:
- return await repo.load(candidate)
- except Exception as exc: # noqa: BLE001
- log.warning(
- "wiki_route_failed route=/page/%s parse error=%s",
- slug,
- exc,
- )
- return None
+ """Locate a visible page by slug using the stable projection order."""
+ for item in await _scan_visible_pages(vault_root):
+ if item.page.slug == slug:
+ return item.page
return None
@@ -751,6 +786,12 @@ def _relative_to_vault(path: Path, vault_root: Path) -> str:
return rel.as_posix()
+def _link_slug(link: str) -> str:
+ """Reduce a path-qualified Obsidian link to its page slug."""
+ target = _canonicalise_link(link).replace("\\", "/").rsplit("/", 1)[-1]
+ return target[:-3] if target.casefold().endswith(".md") else target
+
+
def _link_context(body: str, link_target: str, fallback_slug: str) -> str:
"""Return a short context snippet around the first occurrence of a link.
diff --git a/tests/integration/memory/wiki/test_curator_ingest_e2e.py b/tests/integration/memory/wiki/test_curator_ingest_e2e.py
index d1727a08d4..98bfd17f22 100644
--- a/tests/integration/memory/wiki/test_curator_ingest_e2e.py
+++ b/tests/integration/memory/wiki/test_curator_ingest_e2e.py
@@ -24,6 +24,7 @@ from unittest.mock import patch
import pytest
import pytest_asyncio
+from jarvis.core.events import WikiPageChanged
from jarvis.memory.wiki.atomic_writer import AtomicWriter
from jarvis.memory.wiki.curator import WikiCurator
from jarvis.memory.wiki.curator_llm import WikiCuratorLLM
@@ -58,6 +59,10 @@ async def real_stack(tmp_path: Path):
llm = WikiCuratorLLM.__new__(WikiCuratorLLM)
# We bypass __init__ so we don't try to instantiate a real brain;
# the patched method below is the only entry point we exercise.
+ events: list[WikiPageChanged] = []
+
+ async def publish_event(event: WikiPageChanged) -> None:
+ events.append(event)
curator = WikiCurator(
repo=repo,
@@ -66,8 +71,9 @@ async def real_stack(tmp_path: Path):
llm=llm,
log_writer=log_writer,
vault_root=vault_root,
+ event_publisher=publish_event,
)
- return curator, vault_root, backup_dir
+ return curator, vault_root, backup_dir, events
def _entity_body(slug: str, summary_line: str) -> str:
@@ -104,7 +110,7 @@ def _entity_body(slug: str, summary_line: str) -> str:
@pytest.mark.asyncio
async def test_ingest_creates_pages_writes_log_and_backup(real_stack):
"""One ingest call → two entity pages + one log entry + one backup."""
- curator, vault_root, backup_dir = real_stack
+ curator, vault_root, backup_dir, events = real_stack
fake_updates = [
PageUpdate(
@@ -149,11 +155,16 @@ async def test_ingest_creates_pages_writes_log_and_backup(real_stack):
backups = list(backup_dir.glob("wiki-*.tar.gz"))
assert len(backups) == 1
+ assert [(event.slug, event.path, event.kind) for event in events] == [
+ ("ruben", "entities/ruben.md", "created"),
+ ("wiki-project", "entities/wiki-project.md", "created"),
+ ]
+
@pytest.mark.asyncio
async def test_ingest_with_no_proposed_updates_writes_nothing(real_stack):
"""LLM returns ``[]`` → no writes, no backup, no log entry."""
- curator, vault_root, backup_dir = real_stack
+ curator, vault_root, backup_dir, events = real_stack
with patch.object(curator._llm, "propose_updates", return_value=[]):
result = await curator.ingest(
@@ -174,3 +185,4 @@ async def test_ingest_with_no_proposed_updates_writes_nothing(real_stack):
# No backup taken.
assert list(backup_dir.glob("*.tar.gz")) == []
+ assert events == []
diff --git a/tests/unit/brain/test_wiki_fast_path.py b/tests/unit/brain/test_wiki_fast_path.py
index 888a959954..13e359cd8d 100644
--- a/tests/unit/brain/test_wiki_fast_path.py
+++ b/tests/unit/brain/test_wiki_fast_path.py
@@ -372,6 +372,36 @@ async def test_non_wiki_turn_returns_none(manager_factory):
assert not tool.calls
+async def test_reported_obsidian_follow_up_ingests_inline_facts(manager_factory):
+ """An immediate Obsidian context resolves "there" without saving the
+ preceding listing question as content."""
+ tool = FakeWikiIngestTool(ToolResult(success=True, output="stored"))
+ mgr, _executor, _bus = manager_factory(tools={"wiki-ingest": tool})
+ mgr._history.append( # noqa: SLF001 - bounded production-history seam
+ BrainMessage(
+ role="user",
+ content="Was steht in meiner Obsidian-Wiki drin?", # i18n-allow
+ )
+ )
+ mgr._history.append( # noqa: SLF001 - mirror the preceding assistant reply
+ BrainMessage(role="assistant", content="Dein Vault hat zwölf Seiten."), # i18n-allow
+ )
+
+ reply = await mgr._run_wiki_ingest_fast_path(
+ "Kannst du bitte einen Eintrag da eintragen, dass ich ziemlich " # i18n-allow
+ "genervt bin und dass ich in San Francisco " # i18n-allow
+ "wohne?" # i18n-allow: production transcript under test
+ )
+
+ assert reply is not None
+ await asyncio.sleep(0.05)
+ assert len(tool.calls) == 1
+ saved = tool.calls[0]["text"].lower()
+ assert "genervt" in saved
+ assert "san francisco" in saved
+ assert "was steht" not in saved
+
+
async def test_live_polite_travel_fact_reaches_wiki_before_local_action(
manager_factory,
monkeypatch,
diff --git a/tests/unit/memory/wiki/test_consolidator.py b/tests/unit/memory/wiki/test_consolidator.py
index cdc7ba0914..00c5cc0ca4 100644
--- a/tests/unit/memory/wiki/test_consolidator.py
+++ b/tests/unit/memory/wiki/test_consolidator.py
@@ -380,6 +380,252 @@ def _espresso_project_body() -> str:
)
+def _san_francisco_place_body() -> str:
+ today = dt.date.today().isoformat()
+ return (
+ "---\n"
+ "type: entity\n"
+ "entity_kind: place\n"
+ "slug: san-francisco\n"
+ "aliases: [San Francisco]\n"
+ f"created: {today}\n"
+ f"updated: {today}\n"
+ "---\n\n"
+ "# San Francisco\n\n"
+ "## Summary\n\n"
+ "The user's current city of residence.\n\n"
+ "## Facts\n\n"
+ "- The user lives in San Francisco.\n\n"
+ "## Relationships\n\n"
+ "- Home of [[entities/ruben]].\n\n"
+ "## Sources\n\n"
+ "- conversation\n"
+ )
+
+
+async def test_residence_profile_only_judge_falls_back_to_linked_place_page(
+ stack,
+) -> None:
+ """A residence is not complete until its own linked graph node lands."""
+ vault_root, _curator, journal = stack
+ _write_aged(vault_root / "entities" / "ruben.md", RUBEN_FULL_BODY)
+ journal.append(
+ [
+ CandidateFact(
+ fact="The user lives in San Francisco.",
+ kind="place",
+ subjects=("ruben", "san-francisco"),
+ )
+ ],
+ source_label="realtime:residence",
+ turn_hash="residence-graph",
+ )
+ cid = journal.pending()[0].id
+ updated_profile = RUBEN_FULL_BODY.replace(
+ "- Enjoys great coffee.\n",
+ "- Enjoys great coffee.\n- Lives in San Francisco.\n",
+ ).replace(
+ "## Relationships\n\n",
+ "## Relationships\n\n- Lives in [[entities/san-francisco]].\n\n",
+ )
+ profile_only = _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ "reason": "profile note",
+ }
+ ]
+ )
+ linked = _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ "reason": "profile note",
+ },
+ {
+ "candidate_id": cid,
+ "decision": "add",
+ "target": "entities/san-francisco.md",
+ "new_body": _san_francisco_place_body(),
+ "reason": "graph-visible residence",
+ },
+ ]
+ )
+ registry = ScriptedProviderRegistry(
+ {"gemini": profile_only, "openrouter": linked}
+ )
+
+ label = await _consolidator(
+ stack,
+ FakeBrain([]),
+ config=_config(user_entity_slug="ruben"),
+ registry=registry,
+ ).run_once()
+
+ assert label == "journal-batch:1"
+ assert registry.tried == ["gemini", "openrouter"]
+ profile = (vault_root / "entities" / "ruben.md").read_text(encoding="utf-8")
+ place = (vault_root / "entities" / "san-francisco.md").read_text(
+ encoding="utf-8"
+ )
+ assert "[[entities/san-francisco]]" in profile
+ assert "[[entities/ruben]]" in place
+ assert journal.pending() == []
+
+
+async def test_residence_repairs_two_existing_isolated_pages_atomically(stack) -> None:
+ """The narrow secondary-update exception connects both existing pages."""
+ vault_root, _curator, journal = stack
+ _write_aged(vault_root / "entities" / "ruben.md", RUBEN_FULL_BODY)
+ isolated_place = _san_francisco_place_body().replace(
+ "- Home of [[entities/ruben]].\n",
+ "",
+ )
+ _write_aged(
+ vault_root / "entities" / "san-francisco.md",
+ isolated_place,
+ )
+ journal.append(
+ [
+ CandidateFact(
+ fact="The user lives in San Francisco.",
+ kind="place",
+ subjects=("ruben", "san-francisco"),
+ )
+ ],
+ source_label="realtime:existing-residence",
+ turn_hash="existing-residence",
+ )
+ cid = journal.pending()[0].id
+ updated_profile = RUBEN_FULL_BODY.replace(
+ "- Enjoys great coffee.\n",
+ "- Enjoys great coffee.\n- Lives in San Francisco.\n",
+ ).replace(
+ "## Relationships\n\n",
+ "## Relationships\n\n- Lives in [[entities/san-francisco]].\n\n",
+ )
+ updated_place = isolated_place.replace(
+ "## Relationships\n\n",
+ "## Relationships\n\n- Home of [[entities/ruben]].\n\n",
+ )
+ profile_only = _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ }
+ ]
+ )
+ linked = _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ },
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/san-francisco.md",
+ "new_body": updated_place,
+ },
+ ]
+ )
+ registry = ScriptedProviderRegistry(
+ {"gemini": profile_only, "openrouter": linked}
+ )
+
+ label = await _consolidator(
+ stack,
+ FakeBrain([]),
+ config=_config(user_entity_slug="ruben"),
+ registry=registry,
+ ).run_once()
+
+ assert label == "journal-batch:1"
+ assert registry.tried == ["gemini", "openrouter"]
+ assert "[[entities/san-francisco]]" in (
+ vault_root / "entities" / "ruben.md"
+ ).read_text(encoding="utf-8")
+ assert "[[entities/ruben]]" in (
+ vault_root / "entities" / "san-francisco.md"
+ ).read_text(encoding="utf-8")
+ assert journal.pending() == []
+
+
+async def test_residence_with_existing_bidirectional_links_needs_one_update(
+ stack,
+) -> None:
+ vault_root, _curator, journal = stack
+ connected_profile = RUBEN_FULL_BODY.replace(
+ "## Relationships\n\n",
+ "## Relationships\n\n- Lives in [[entities/san-francisco]].\n\n",
+ )
+ _write_aged(vault_root / "entities" / "ruben.md", connected_profile)
+ connected_place = _san_francisco_place_body()
+ _write_aged(
+ vault_root / "entities" / "san-francisco.md",
+ connected_place,
+ )
+ journal.append(
+ [
+ CandidateFact(
+ fact="The user feels settled in San Francisco.",
+ kind="place",
+ subjects=("ruben", "san-francisco"),
+ )
+ ],
+ source_label="realtime:connected-residence",
+ turn_hash="connected-residence",
+ )
+ cid = journal.pending()[0].id
+ updated_profile = connected_profile.replace(
+ "- Enjoys great coffee.\n",
+ "- Enjoys great coffee.\n- Feels settled in San Francisco.\n",
+ )
+ brain = FakeBrain(
+ [
+ _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ }
+ ]
+ )
+ ]
+ )
+
+ label = await _consolidator(
+ stack,
+ brain,
+ config=_config(user_entity_slug="ruben"),
+ ).run_once()
+
+ assert label == "journal-batch:1"
+ assert "Feels settled in San Francisco" in (
+ vault_root / "entities" / "ruben.md"
+ ).read_text(encoding="utf-8")
+ assert (
+ vault_root / "entities" / "san-francisco.md"
+ ).read_text(encoding="utf-8") == connected_place
+ assert journal.pending() == []
+
+
@pytest.mark.asyncio
async def test_companion_add_creates_topic_page_beside_profile_update(stack) -> None:
"""Graph-visibility rule: a profile update may CREATE the missing topic
@@ -488,12 +734,75 @@ async def test_failing_companion_add_never_blocks_the_primary_fact(stack) -> Non
assert journal.pending() == [] # consolidated despite the refused companion
+async def test_failing_required_place_companion_keeps_candidate_pending(stack) -> None:
+ vault_root, _curator, journal = stack
+ _write_aged(vault_root / "entities" / "ruben.md", RUBEN_FULL_BODY)
+ journal.append(
+ [
+ CandidateFact(
+ fact="The user lives in San Francisco.",
+ kind="place",
+ subjects=("ruben", "san-francisco"),
+ )
+ ],
+ source_label="realtime:residence-retry",
+ turn_hash="residence-retry",
+ )
+ cid = journal.pending()[0].id
+ updated_profile = RUBEN_FULL_BODY.replace(
+ "- Enjoys great coffee.\n",
+ "- Enjoys great coffee.\n- Lives in San Francisco.\n",
+ ).replace(
+ "## Relationships\n\n",
+ "## Relationships\n\n- Lives in [[entities/san-francisco]].\n\n",
+ )
+ poisoned_place = _san_francisco_place_body().replace(
+ "The user's current city of residence.",
+ "Stored with sk-proj-" + "A" * 24 + ".",
+ )
+ brain = FakeBrain(
+ [
+ _judge_json(
+ [
+ {
+ "candidate_id": cid,
+ "decision": "update",
+ "target": "entities/ruben.md",
+ "new_body": updated_profile,
+ },
+ {
+ "candidate_id": cid,
+ "decision": "add",
+ "target": "entities/san-francisco.md",
+ "new_body": poisoned_place,
+ },
+ ]
+ )
+ ]
+ )
+
+ label = await _consolidator(
+ stack,
+ brain,
+ config=_config(user_entity_slug="ruben"),
+ ).run_once()
+
+ assert label == "journal-transient:1"
+ assert not (vault_root / "entities" / "san-francisco.md").exists()
+ assert "Lives in San Francisco" in (
+ vault_root / "entities" / "ruben.md"
+ ).read_text(encoding="utf-8")
+ assert len(journal.pending()) == 1
+
+
@pytest.mark.asyncio
async def test_secondary_update_is_still_rejected(stack) -> None:
"""Only "add" and "invalidate" may ride as secondary actions — a
secondary "update" of another existing page stays invalid."""
vault_root, _curator, journal = stack
_write_aged(vault_root / "entities" / "ruben.md", RUBEN_FULL_BODY)
+ _write_aged(vault_root / "entities" / "lena.md", LENA_BODY)
journal.append(
[CandidateFact(
fact="The user is pursuing a high-end espresso machine.",
@@ -524,7 +833,9 @@ async def test_secondary_update_is_still_rejected(stack) -> None:
label = await consolidator.run_once()
assert label == "judge-unavailable" # rejected response, chain exhausted
- assert not (vault_root / "entities" / "lena.md").exists()
+ assert (
+ vault_root / "entities" / "lena.md"
+ ).read_text(encoding="utf-8") == LENA_BODY
assert journal.pending() != [] # candidate stays visible for the next pass
diff --git a/tests/unit/memory/wiki/test_curator_llm.py b/tests/unit/memory/wiki/test_curator_llm.py
index dedc9a6a42..21fadf16bd 100644
--- a/tests/unit/memory/wiki/test_curator_llm.py
+++ b/tests/unit/memory/wiki/test_curator_llm.py
@@ -115,6 +115,21 @@ class FakeRegistry:
return self._brain
+class ScriptedRegistry:
+ """Return a distinct structured response for each provider family."""
+
+ def __init__(self, responses: dict[str, str]) -> None:
+ self._responses = responses
+ self.tried: list[str] = []
+
+ def available(self) -> set[str]:
+ return set(self._responses)
+
+ def instantiate(self, name: str, **_kwargs: Any) -> FakeBrain:
+ self.tried.append(name)
+ return FakeBrain(self._responses[name])
+
+
class FakeVault:
"""Minimal ``VaultIndex`` stub with one entry per page type."""
@@ -360,6 +375,77 @@ async def test_direct_ingest_real_schema_binds_portable_runtime_user_slug() -> N
assert "ruben" not in system.casefold()
+async def test_direct_residence_falls_back_until_graph_is_bidirectional(
+ tmp_path: Path,
+) -> None:
+ """A profile-only residence response cannot complete explicit ingest."""
+ profile_without_link = (
+ "---\ntype: entity\nentity_kind: person\nslug: owner-profile\n---\n\n"
+ "# Owner Profile\n\n## Facts\n\n- Lives in San Francisco.\n"
+ )
+ profile_with_link = profile_without_link.replace(
+ "- Lives in San Francisco.",
+ "- Lives in [[entities/san-francisco|San Francisco]].",
+ )
+ place_with_link = (
+ "---\ntype: entity\nentity_kind: place\nslug: san-francisco\n---\n\n"
+ "# San Francisco\n\n## Relationships\n\n"
+ "- Residence of [[entities/owner-profile|Owner Profile]].\n"
+ )
+ profile_only = json.dumps(
+ [
+ {
+ "target": "entities/owner-profile.md",
+ "operation": "update",
+ "new_body": profile_without_link,
+ "reason": "record residence on profile",
+ }
+ ]
+ )
+ graph_complete = json.dumps(
+ [
+ {
+ "target": "entities/owner-profile.md",
+ "operation": "update",
+ "new_body": profile_with_link,
+ "reason": "link residence from profile",
+ },
+ {
+ "target": "entities/san-francisco.md",
+ "operation": "create",
+ "new_body": place_with_link,
+ "reason": "create visible residence page",
+ },
+ ]
+ )
+ registry = ScriptedRegistry(
+ {"gemini": profile_only, "openrouter": graph_complete}
+ )
+ llm = WikiCuratorLLM(
+ config=_make_config(primary="gemini", user_entity_slug="owner-profile"),
+ schema_path=_write_schema(tmp_path),
+ registry=registry,
+ )
+
+ updates = await llm.propose_updates(
+ (
+ "ich ziemlich genervt bin und dass ich in " # i18n-allow: reported transcript fixture
+ "San Francisco wohne" # i18n-allow: reported residence transcript fixture
+ ),
+ "tool:wiki-ingest",
+ repo=FakeRepo(),
+ vault=FakeVault(),
+ )
+
+ assert registry.tried == ["gemini", "openrouter"]
+ assert llm.provider_name == "openrouter"
+ assert {update.target_path.as_posix() for update in updates} == {
+ "entities/owner-profile.md",
+ "entities/san-francisco.md",
+ }
+
+
@pytest.mark.asyncio
async def test_propose_updates_uses_primary_when_provider_empty(tmp_path: Path) -> None:
"""Empty ``provider`` falls back to ``brain.primary``."""
diff --git a/tests/unit/memory/wiki/test_extractor.py b/tests/unit/memory/wiki/test_extractor.py
index d9650824af..30fd383230 100644
--- a/tests/unit/memory/wiki/test_extractor.py
+++ b/tests/unit/memory/wiki/test_extractor.py
@@ -159,6 +159,61 @@ async def test_happy_path_appends_parsed_facts(journal: CandidateJournal) -> Non
assert kwargs.get("model") == "gemini-3-flash-preview"
+ ("incomplete_kind", "incomplete_subjects"),
+ [
+ ("place", ["user"]),
+ ("place", ["san-francisco"]),
+ ("other", ["user", "san-francisco"]),
+ ],
+)
+async def test_residence_requires_named_place_subject_and_falls_back(
+ journal: CandidateJournal,
+ incomplete_kind: str,
+ incomplete_subjects: list[str],
+) -> None:
+ incomplete = json.dumps(
+ [
+ {
+ "fact": "The user lives in San Francisco.",
+ "kind": incomplete_kind,
+ "subjects": incomplete_subjects,
+ "evidence_turn_id": "residence-turn",
+ }
+ ]
+ )
+ complete = json.dumps(
+ [
+ {
+ "fact": "The user lives in San Francisco.",
+ "kind": "place",
+ "subjects": ["user", "san-francisco"],
+ "evidence_turn_id": "residence-turn",
+ }
+ ]
+ )
+ registry = ScriptedRegistry(
+ {"gemini": incomplete, "openrouter": complete}
+ )
+ extractor = ConversationFactExtractor(
+ config=_config(), journal=journal, registry=registry,
+ )
+
+ count = await extractor.extract_and_journal(
+ "Ich wohne in San Francisco.", # i18n-allow: production residence fixture
+ "Noted.",
+ source_label="realtime:residence",
+ turn_hash="residence-turn",
+ )
+
+ assert count == 1
+ assert registry.tried == ["gemini", "openrouter"]
+ row = journal.pending()[0]
+ assert row.kind == "place"
+ assert row.subjects == ("user", "san-francisco")
+
+
@pytest.mark.asyncio
async def test_short_input_skips_brain_entirely(journal: CandidateJournal) -> None:
brain = FakeBrain(_ok_facts_json())
diff --git a/tests/unit/memory/wiki/test_scheduler_journal_trigger.py b/tests/unit/memory/wiki/test_scheduler_journal_trigger.py
index bd10469893..748cc0d531 100644
--- a/tests/unit/memory/wiki/test_scheduler_journal_trigger.py
+++ b/tests/unit/memory/wiki/test_scheduler_journal_trigger.py
@@ -236,6 +236,35 @@ async def test_fire_and_forget_requests_share_one_task(tmp_path: Path) -> None:
await first
+async def test_fire_task_rechecks_request_after_drain_final_check(
+ tmp_path: Path,
+) -> None:
+ """A request in the drain's return tail must start one follow-up pass."""
+ drain_checked = asyncio.Event()
+ release_tail = asyncio.Event()
+ consolidator = FakeConsolidator()
+ scheduler = _scheduler(tmp_path, consolidator=consolidator)
+ original_drain = scheduler._drain_journal
+
+ async def _pause_after_final_check():
+ result = await original_drain()
+ drain_checked.set()
+ await release_tail.wait()
+ return result
+
+ scheduler._drain_journal = _pause_after_final_check
+ first = fire_journal_trigger(scheduler)
+ await drain_checked.wait()
+
+ second = fire_journal_trigger(scheduler)
+ assert second is first
+ release_tail.set()
+ await first
+
+ assert consolidator.runs == 2
+
+
@pytest.mark.asyncio
async def test_journal_trigger_without_consolidator_skips(tmp_path: Path) -> None:
scheduler = _scheduler(tmp_path, consolidator=None)
diff --git a/tests/unit/memory/wiki/test_wiki_intent.py b/tests/unit/memory/wiki/test_wiki_intent.py
index 3a3ec52fea..f881a9c19f 100644
--- a/tests/unit/memory/wiki/test_wiki_intent.py
+++ b/tests/unit/memory/wiki/test_wiki_intent.py
@@ -96,6 +96,53 @@ def test_latest_transcript_reference_is_anaphoric(text: str) -> None:
assert match.content is None
+def test_reported_obsidian_follow_up_resolves_locative_wiki_target() -> None:
+ prior = "Was steht in meiner Obsidian-Wiki drin?" # i18n-allow
+ match = match_wiki_intent(
+ (
+ "Kannst du bitte einen Eintrag da eintragen, dass ich ziemlich " # i18n-allow
+ "genervt bin und dass ich in San Francisco " # i18n-allow
+ "wohne?" # i18n-allow: production transcript under test
+ ),
+ prior_text=prior,
+ )
+
+ assert match is not None
+ assert match.content is not None
+ assert "genervt" in match.content
+ assert "san francisco" in match.content
+
+
+def test_entry_noun_before_explicit_wiki_target_is_control_syntax() -> None:
+ match = match_wiki_intent(
+ "Kannst du bitte einen Eintrag in mein Wiki eintragen, dass ich " # i18n-allow
+ "in San Francisco wohne?" # i18n-allow: production syntax under test
+ )
+
+ assert match is not None
+ assert match.content is not None
+ assert match.content.startswith("ich in san francisco")
+
+
+def test_locative_write_requires_immediate_wiki_context() -> None:
+ text = "Kannst du bitte einen Eintrag da eintragen, dass ich morgen frei habe?" # i18n-allow
+
+ assert match_wiki_intent(text) is None
+ assert match_wiki_intent(
+ text,
+ prior_text="Was steht morgen in meinem Kalender?", # i18n-allow
+ ) is None
+
+
+def test_general_wiki_discussion_does_not_authorize_contextual_write() -> None:
+ text = "Kannst du bitte einen Eintrag da eintragen, dass ich morgen frei habe?" # i18n-allow
+
+ assert match_wiki_intent(
+ text,
+ prior_text="Wie funktioniert ein Wiki?", # i18n-allow
+ ) is None
+
+
@pytest.mark.parametrize("text", [
"Was steht im Wiki über Joy?", # recall, not write # i18n-allow
"Wie funktioniert ein Wiki?", # general question # i18n-allow
diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.py
index 65bedd8e31..ca19cacf53 100644
--- a/tests/unit/ui/web/test_wiki_routes.py
+++ b/tests/unit/ui/web/test_wiki_routes.py
@@ -124,6 +124,53 @@ def empty_vault(tmp_path: Path) -> Path:
return vault
+def starter_obsidian_vault(tmp_path: Path) -> Path:
+ """Twelve-page starter vault without any curator page directories."""
+ vault = tmp_path / "vault"
+ pages = {
+ "README.md": "# Vault README\n\nStart at [[Home]].\n",
+ "schema.md": "# Wiki Schema\n\nEditing contract.\n",
+ "log.md": "# Change Log\n\nNo changes yet.\n",
+ "memory.md": "# Memory\n\nLong-term notes.\n",
+ "00-index/Home.md": (
+ "# Home\n\nSee [[Personal Knowledge Management]] and [[README]].\n"
+ ),
+ "10-notes/Evergreen Notes.md": "# Evergreen Notes\n\nDurable ideas.\n",
+ "10-notes/Graph View Visualisation.md": (
+ "# Graph View Visualisation\n\nConnected notes.\n"
+ ),
+ "10-notes/Markdown as Foundation.md": (
+ "# Markdown as Foundation\n\nPlain text lasts.\n"
+ ),
+ "10-notes/Personal Knowledge Management.md": (
+ "# Personal Knowledge Management\n\nA connected knowledge practice.\n"
+ ),
+ "10-notes/Zettelkasten Method.md": (
+ "# Zettelkasten Method\n\nAtomic linked notes.\n"
+ ),
+ "99-templates/Daily Note.md": "# Daily Note\n\nTemplate body.\n",
+ "99-templates/Note Template.md": "# Note Template\n\nTemplate body.\n",
+ }
+ for relative, body in pages.items():
+ path = vault / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(body, encoding="utf-8")
+
+ # These Markdown-shaped decoys are not live pages.
+ for relative in (
+ ".obsidian/internal.md",
+ ".trash/deleted.md",
+ "_archive/retired.md",
+ "attachments/extracted-text.md",
+ "90-attachments/extracted-text.md",
+ ):
+ path = vault / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("# Not visible\n", encoding="utf-8")
+ return vault
+
+
class _FakeCurator:
def __init__(self, result: object) -> None:
self.result = result
@@ -206,6 +253,35 @@ def test_tree_with_missing_vault_returns_empty_ok_response(tmp_path: Path) -> No
assert all(folder["files"] == [] for folder in body["folders"])
+def test_tree_projects_all_visible_starter_vault_pages(
+ starter_obsidian_vault: Path,
+) -> None:
+ app = _make_app(starter_obsidian_vault)
+ with TestClient(app) as client:
+ response = client.get("/api/wiki/tree")
+
+ body = response.json()
+ assert body["ok"] is True
+ assert body["stats"]["total_pages"] == 12
+ assert body["stats"]["total_links"] == 3
+
+ folders = body["folders"]
+ assert [folder["name"] for folder in folders[:4]] == [
+ "entities",
+ "concepts",
+ "projects",
+ "sessions",
+ ]
+ folders_by_name = {folder["name"]: folder for folder in folders}
+ assert folders_by_name["root"]["count"] == 4
+ assert folders_by_name["00-index"]["count"] == 1
+ assert folders_by_name["10-notes"]["count"] == 5
+ assert folders_by_name["99-templates"]["count"] == 2
+ assert set(folders_by_name).isdisjoint(
+ {".obsidian", ".trash", "_archive", "attachments", "90-attachments"}
+ )
+
+
# ----------------------------------------------------------------------
# /page/{slug}
# ----------------------------------------------------------------------
@@ -315,6 +391,36 @@ def test_graph_with_broken_wikilink_lists_it_in_broken_bucket(tmp_path: Path) ->
assert body["broken"][0]["target"] == "ghost-page"
+def test_starter_vault_pages_are_readable_and_connected_in_graph(
+ starter_obsidian_vault: Path,
+) -> None:
+ app = _make_app(starter_obsidian_vault)
+ with TestClient(app) as client:
+ graph = client.get("/api/wiki/graph").json()
+ root_page = client.get("/api/wiki/page/README").json()
+ note_page = client.get(
+ "/api/wiki/page/Personal%20Knowledge%20Management"
+ ).json()
+ backlinks = client.get(
+ "/api/wiki/backlinks/Personal%20Knowledge%20Management"
+ ).json()
+
+ assert graph["ok"] is True
+ assert len(graph["nodes"]) == 12
+ node_ids = {node["id"] for node in graph["nodes"]}
+ assert {"README", "Home", "Personal Knowledge Management"} <= node_ids
+ edge_pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
+ assert ("Home", "Personal Knowledge Management") in edge_pairs
+ assert ("Home", "README") in edge_pairs
+
+ assert root_page["ok"] is True
+ assert root_page["path"] == "README.md"
+ assert root_page["frontmatter_valid"] is False
+ assert note_page["ok"] is True
+ assert note_page["path"] == "10-notes/Personal Knowledge Management.md"
+ assert {item["slug"] for item in backlinks["backlinks"]} == {"Home"}
+
+
# ----------------------------------------------------------------------
# /backlinks/{slug}
# ----------------------------------------------------------------------