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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(wiki): one-shot profile re-curation CLI (dry-run default)
Personal Jarvis Maintainer7eef17b97591
diff --git a/jarvis/memory/wiki/cli.py b/jarvis/memory/wiki/cli.pyindex 9effd935a8..c03fd2bd79 100644--- a/jarvis/memory/wiki/cli.py+++ b/jarvis/memory/wiki/cli.py@@ -27,6 +27,7 @@ from __future__ import annotationsimport argparseimport asyncioimport logging+import osimport sysfrom pathlib import Path@@ -166,6 +167,54 @@ def _run_cleanup(vault_root: Path, *, apply: bool) -> int:return 0+async def _run_recurate_profile(vault_root: Path, *, apply: bool) -> int:+ """Async body of the ``recurate-profile`` subcommand (ADR-0029 cleanup).++ Re-judges the ONE user profile page under the asymmetric curation bar:+ keep supported personal facts, move topic detail to topic pages, drop+ world-knowledge trivia. Dry-run by default; ``--apply`` snapshots the+ whole vault first and writes all-or-nothing.+ """+ from jarvis.core.config import load_config++ from .recurate import recurate_profile++ # os.path instead of Path.is_dir: no blocking pathlib call in async code+ # (ASYNC240) for the one line this subcommand adds.+ if not os.path.isdir(vault_root):+ print(f"ERROR: vault not found: {vault_root}", file=sys.stderr)+ return 1++ curator = _build_curator(vault_root)+ await curator._vault.scan(vault_root) # noqa: SLF001 — CLI wiring+ report = await recurate_profile(+ vault_root=vault_root,+ config=load_config(),+ curator=curator,+ apply=apply,+ backup_dir=DEFAULT_BACKUP_DIR,+ )++ mode = "APPLIED" if report.applied else "DRY-RUN (pass --apply to write)"+ print(f"PROFILE RE-CURATION {mode} profile: {report.profile_rel}")+ if report.error:+ print(f"ERROR: {report.error}", file=sys.stderr)+ return 1+ if report.backup_path:+ print(f" backup: {report.backup_path}")+ if not report.proposals:+ print(" (judge proposed no changes — profile is already clean)")+ return 0+ print(f" proposals: {len(report.proposals)}")+ for update in report.proposals:+ print(f" {update.operation:8s} {update.target_path}")+ if update.reason:+ print(f" reason: {update.reason}")+ if not report.applied:+ print(" (dry-run — nothing written)")+ return 0++async def _run_ingest(source_path: Path,vault_root: Path,@@ -312,6 +361,30 @@ def main(argv: list[str] | None = None) -> int:help="Enable DEBUG-level logging.",)+ p_recurate = subparsers.add_parser(+ "recurate-profile",+ help="One-shot ADR-0029 cleanup: re-judge the user profile page — "+ "keep personal facts, move topic detail to topic pages, drop "+ "world-knowledge trivia. Dry-run by default.",+ )+ p_recurate.add_argument(+ "--vault",+ type=Path,+ default=DEFAULT_VAULT,+ help=f"Vault root (default: {DEFAULT_VAULT}).",+ )+ p_recurate.add_argument(+ "--apply",+ action="store_true",+ help="Snapshot the vault and write the proposals (all-or-nothing). "+ "Omit for a dry-run report.",+ )+ p_recurate.add_argument(+ "--debug",+ action="store_true",+ help="Enable DEBUG-level logging.",+ )+args = parser.parse_args(argv)logging.basicConfig(@@ -325,6 +398,11 @@ def main(argv: list[str] | None = None) -> int:if args.command == "cleanup":return _run_cleanup(args.vault.resolve(), apply=bool(args.apply))+ if args.command == "recurate-profile":+ return asyncio.run(+ _run_recurate_profile(args.vault.resolve(), apply=bool(args.apply))+ )+if args.command == "ingest":return asyncio.run(_run_ingest(diff --git a/jarvis/memory/wiki/recurate.py b/jarvis/memory/wiki/recurate.pynew file mode 100644index 0000000000..30eaee52f0--- /dev/null+++ b/jarvis/memory/wiki/recurate.py@@ -0,0 +1,264 @@+"""One-shot re-curation of the user profile page (spec 2026-07-20 §3).++Vaults populated before the evidence-tiered redesign (ADR-0029) concentrate+their accumulated slop on the user profile: world-knowledge trivia bullets,+topic detail that belongs on linked topic pages, and unsupported one-off+claims. This module re-judges exactly that ONE page with the asymmetric+curation bar and proposes the cleaned state:++* keep every supported personal fact (identity, people, possessions,+ health, habits, projects) — cleanup must never cost real memory;+* move topic detail onto the topic's own page (creating it when missing,+ cross-linked both ways);+* drop bullets that are world-knowledge trivia or unsupported one-off+ mentions.++Safety posture: **dry-run by default** (proposals are printed, nothing is+written), a full tar.gz vault snapshot before any apply, and every write+goes through ``WikiCurator.apply_external_updates`` with+``all_or_nothing=True`` (backup → secret guard → validate → rollback →+FTS). Manual invocation only (``jarvis.memory.wiki.cli recurate-profile``)+— never scheduled, never on the voice path (AP-9).+"""+from __future__ import annotations++import logging+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from jarvis.brain.streaming import aggregate, is_length_truncated+from jarvis.core.protocols import BrainMessage, BrainRequest++from .cleanup import _full_snapshot+from .curator_llm import _extract_json_array+from .journal import normalise_subjects+from .prompt import resolve_user_entity_slug+from .protocols import PageUpdate++log = logging.getLogger(__name__)++_TARGET_DIRS = ("entities", "concepts", "projects")++_RECURATE_SYSTEM = """\+You re-curate the ONE user profile page of a personal knowledge wiki (an+Obsidian vault). You receive the current profile body and the list of pages+that already exist. Propose the cleaned state of the vault as JSON updates.++Curation bar (binding, asymmetric):+- KEEP every supported personal fact: identity, close people, possessions,+ health, habits and recurring activities, values, active projects,+ decisions. Losing a real personal fact is the worst possible outcome of+ this cleanup — when unsure whether a bullet is real memory, keep it.+- MOVE topic detail to the topic's own page: when a profile bullet carries+ detail about a named durable topic (a vehicle, a sport, a person, a tool),+ keep at most a one-line [[wikilink]] bullet on the profile and put the+ detail on the topic page ("update" it, or "create" it when missing,+ cross-linked with the profile in both directions).+- DROP bullets that are world-knowledge trivia with no personal anchor,+ duplicated lines, template scaffolding, or transient status chatter.+ Bullets ending with the marker *(inferred)* may be kept as-is; never+ invent new *(inferred)* lines.++Output contract:+Return ONLY a JSON array of update objects, no prose, no code fences:+ [{"target": "<dir>/<slug>.md", "operation": "update" | "create",+ "new_body": "<full page markdown with frontmatter>",+ "reason": "<short why>"}]+- Include the profile page itself as one "update" (its cleaned full body,+ section structure intact). If the profile needs no change, return [].+- "create" only for pages that do not exist yet; "update" only for pages+ that do. Directories allowed: entities/, concepts/, projects/.+- Preserve the ## Sources section content of every page you touch.+- Never write credentials or secrets. Never touch sessions/ or _archive/.+"""+++@dataclass(slots=True)+class RecurateReport:+ """Outcome of one re-curation run (dry or applied)."""++ profile_rel: str = ""+ proposals: list[PageUpdate] = field(default_factory=list)+ reasons: list[str] = field(default_factory=list)+ applied: bool = False+ backup_path: Path | None = None+ error: str = ""+++def _existing_pages(vault_root: Path) -> list[str]:+ pages: list[str] = []+ for directory in _TARGET_DIRS:+ base = vault_root / directory+ if not base.is_dir():+ continue+ pages.extend(+ f"{directory}/{page.name}" for page in sorted(base.glob("*.md"))+ )+ return pages+++def _validate_items(+ items: list[Any], *, profile_rel: str, vault_root: Path,+) -> str | None:+ """Deterministic shape check before anything reaches the write pipeline."""+ if not items:+ return None+ for item in items:+ if not isinstance(item, dict):+ return "response contains a non-object item"+ target = str(item.get("target") or "").strip().replace("\\", "/")+ operation = str(item.get("operation") or "").strip()+ body = item.get("new_body")+ parts = target.split("/")+ if (+ len(parts) != 2+ or parts[0] not in _TARGET_DIRS+ or not parts[1].endswith(".md")+ or normalise_subjects((parts[1][:-3],)) != (parts[1][:-3],)+ ):+ return f"unsafe target: {target!r}"+ if operation not in ("update", "create"):+ return f"unsupported operation: {operation!r}"+ if not isinstance(body, str) or not body.strip():+ return f"missing new_body for {target}"+ exists = (vault_root / target).is_file()+ if operation == "create" and exists:+ return f"create targets an existing page: {target}"+ if operation == "update" and not exists:+ return f"update targets a missing page: {target}"+ return None+++async def recurate_profile(+ *,+ vault_root: Path,+ config: Any,+ curator: Any,+ registry: Any | None = None,+ apply: bool = False,+ backup_dir: Path | None = None,+) -> RecurateReport:+ """Re-judge the user profile page; dry-run unless ``apply`` is True."""+ report = RecurateReport()+ wiki_cfg = config.memory.wiki+ user_slug = resolve_user_entity_slug(+ getattr(wiki_cfg.session_rollup, "user_entity_slug", "")+ )+ profile_rel = f"entities/{user_slug}.md"+ report.profile_rel = profile_rel+ profile_path = vault_root / profile_rel+ if not profile_path.is_file():+ report.error = f"profile page not found: {profile_rel}"+ return report+ profile_body = profile_path.read_text(encoding="utf-8")++ pages = "\n".join(f"- {page}" for page in _existing_pages(vault_root))+ user_prompt = (+ f"User profile page (binding target): {profile_rel}\n"+ "----- CURRENT PROFILE BODY -----\n"+ f"{profile_body.rstrip()}\n"+ "----- END PROFILE BODY -----\n\n"+ "Existing pages:\n"+ f"{pages or '- (none)'}\n\n"+ "Return the JSON array now."+ )+ request = BrainRequest(+ messages=(BrainMessage(role="user", content=user_prompt),),+ system=_RECURATE_SYSTEM,+ max_tokens=int(wiki_cfg.curator.max_output_tokens),+ temperature=0.2,+ stream=True,+ )++ from jarvis.memory.wiki.provider_chain import (+ build_wiki_provider_chain,+ complete_with_fallback,+ credential_ready_wiki_providers,+ )++ # An injected registry (tests) skips the credential filter — the same+ # convention as WikiCuratorLLM/Consolidator: production uses a fresh+ # registry and only keeps key-ready provider families in the chain.+ credential_filter = registry is None+ if registry is None:+ from jarvis.brain.provider_registry import BrainProviderRegistry++ registry = BrainProviderRegistry()+ available = set(registry.available())+ chain = build_wiki_provider_chain(+ primary=(wiki_cfg.curator.provider.strip() or config.brain.primary),+ model_override=wiki_cfg.curator.model,+ available=available,+ credential_ready=(+ credential_ready_wiki_providers(available=available, config=config)+ if credential_filter+ else available+ ),+ )++ def _validate_response(agg: Any) -> str | None:+ if is_length_truncated(agg.finish_reason, agg.text):+ return "truncated structured output"+ try:+ parsed = _extract_json_array(agg.text)+ except ValueError as exc:+ return f"malformed JSON array: {exc}"+ return _validate_items(+ parsed, profile_rel=profile_rel, vault_root=vault_root,+ )++ result = await complete_with_fallback(+ registry=registry,+ chain=chain,+ request=request,+ timeout_s=float(wiki_cfg.curator.timeout_s),+ label="RecurateProfile",+ aggregate=aggregate,+ validate=_validate_response,+ )+ if result is None:+ report.error = "no provider produced a valid re-curation proposal"+ return report+ agg_response, _provider = result+ items = _extract_json_array(agg_response.text)++ for item in items:+ report.proposals.append(+ PageUpdate(+ target_path=Path(str(item["target"]).strip().replace("\\", "/")),+ operation=str(item["operation"]).strip(),+ new_body=str(item["new_body"]),+ reason=str(item.get("reason") or ""),+ )+ )+ report.reasons.append(str(item.get("reason") or ""))++ if not apply or not report.proposals:+ return report++ snapshot_dir = backup_dir or (vault_root.parent / "wiki-backups")+ report.backup_path = _full_snapshot(vault_root, snapshot_dir)+ write_result = await curator.apply_external_updates(+ report.proposals,+ source_label=f"recurate-profile:{time.strftime('%Y-%m-%d')}",+ verb="merge",+ all_or_nothing=True,+ )+ rejected = [+ *getattr(write_result, "failed_validation", ()),+ *getattr(write_result, "blocked_pii", ()),+ *getattr(write_result, "skipped_due_to_recent_edit", ()),+ ]+ if rejected or not getattr(write_result, "applied", ()):+ report.error = (+ f"{len(rejected)} write(s) rejected; vault left unchanged "+ "(all-or-nothing)"+ )+ return report+ report.applied = True+ return report+++__all__ = ["RecurateReport", "recurate_profile"]diff --git a/tests/unit/memory/wiki/test_recurate.py b/tests/unit/memory/wiki/test_recurate.pynew file mode 100644index 0000000000..5e2ff119ae--- /dev/null+++ b/tests/unit/memory/wiki/test_recurate.py@@ -0,0 +1,255 @@+"""Tests for the one-shot profile re-curation pass (ADR-0029 cleanup).++A scripted FakeBrain plays the re-curation judge; the curator, writer,+and vault are real-on-tmpfs. Pins: dry-run proposes and writes NOTHING;+apply snapshots the vault first and writes all-or-nothing through+``WikiCurator.apply_external_updates``; unsafe judge output falls to the+next provider family.+"""+from __future__ import annotations++import json+import os+import time+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import pytest+import pytest_asyncio++from jarvis.core.config import (+ BrainConfig,+ BrainProviderConfig,+ JarvisConfig,+ MemoryConfig,+ SessionRollupConfig,+ WikiMemoryConfig,+)+from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.memory.wiki.atomic_writer import AtomicWriter+from jarvis.memory.wiki.curator import WikiCurator+from jarvis.memory.wiki.curator_llm import WikiCuratorLLM+from jarvis.memory.wiki.log_writer import LogWriter+from jarvis.memory.wiki.page import MarkdownPageRepository+from jarvis.memory.wiki.recurate import recurate_profile+from jarvis.memory.wiki.vault_index import VaultIndex++PROFILE_BODY = (+ "---\n"+ "type: entity\n"+ "entity_kind: person\n"+ "slug: ruben\n"+ "aliases: [Ruben]\n"+ "created: 2026-06-01\n"+ "updated: 2026-06-01\n"+ "---\n"+ "\n"+ "# Ruben\n"+ "\n"+ "## Summary\n"+ "\n"+ "The user.\n"+ "\n"+ "## Facts\n"+ "\n"+ "- Enjoys great coffee.\n"+ "- The Eiffel Tower is 330 metres tall.\n"+ "\n"+ "## Relationships\n"+ "\n"+ "## Sources\n"+ "\n"+ "- conversation\n"+)++CLEANED_PROFILE = PROFILE_BODY.replace(+ "- The Eiffel Tower is 330 metres tall.\n", ""+)+++class FakeBrain:+ name = "fake-brain"+ context_window = 100_000+ supports_tools = False+ supports_vision = False++ def __init__(self, response_text: str) -> None:+ self.response_text = response_text+ self.received_requests: list[BrainRequest] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.received_requests.append(req)+ yield BrainDelta(content=self.response_text)+ yield BrainDelta(finish_reason="stop")++ def estimate_cost(self, req: BrainRequest) -> float: # pragma: no cover+ return 0.0+++class FakeRegistry:+ def __init__(self, brain: Any) -> None:+ self._brain = brain++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ return self._brain++ def available(self) -> set[str]:+ return {"gemini"}+++class ScriptedProviderRegistry:+ def __init__(self, responses: dict[str, str]) -> None:+ self._responses = responses+ self.tried: list[str] = []++ def instantiate(self, name: str, **_kwargs: Any) -> Any:+ self.tried.append(name)+ return FakeBrain(self._responses[name])++ def available(self) -> set[str]:+ return set(self._responses)+++def _config() -> JarvisConfig:+ return JarvisConfig(+ brain=BrainConfig(+ primary="gemini",+ providers={"gemini": BrainProviderConfig(model="gemini-3.1-pro-preview")},+ ),+ memory=MemoryConfig(+ wiki=WikiMemoryConfig(+ session_rollup=SessionRollupConfig(user_entity_slug="ruben"),+ )+ ),+ )+++@pytest_asyncio.fixture+async def stack(tmp_path: Path):+ vault_root = tmp_path / "vault"+ for sub in ("entities", "concepts", "projects", "sessions", "_archive"):+ (vault_root / sub).mkdir(parents=True)+ (vault_root / "schema.md").write_text("# stub schema\n", encoding="utf-8")+ (vault_root / "log.md").write_text("# Wiki Log\n", encoding="utf-8")+ profile = vault_root / "entities" / "ruben.md"+ profile.write_text(PROFILE_BODY, encoding="utf-8")+ # Age past the writer's 30s concurrent-edit lock so an immediate apply+ # is not skipped as a recent manual edit.+ aged = time.time() - 120.0+ os.utime(profile, (aged, aged))++ repo = MarkdownPageRepository()+ vault = VaultIndex(repo=repo)+ await vault.scan(vault_root)+ curator = WikiCurator(+ repo=repo,+ vault=vault,+ writer=AtomicWriter(vault_root=vault_root, backup_dir=tmp_path / "backups"),+ llm=WikiCuratorLLM.__new__(WikiCuratorLLM),+ log_writer=LogWriter(log_path=vault_root / "log.md"),+ vault_root=vault_root,+ )+ return vault_root, curator+++def _cleanup_json() -> str:+ return json.dumps(+ [+ {+ "target": "entities/ruben.md",+ "operation": "update",+ "new_body": CLEANED_PROFILE,+ "reason": "drop world-knowledge trivia",+ }+ ]+ )+++async def test_dry_run_proposes_but_writes_nothing(stack) -> None:+ vault_root, curator = stack+ report = await recurate_profile(+ vault_root=vault_root,+ config=_config(),+ curator=curator,+ registry=FakeRegistry(FakeBrain(_cleanup_json())),+ apply=False,+ )++ assert report.error == ""+ assert report.applied is False+ assert report.backup_path is None+ assert [str(u.target_path) for u in report.proposals] == ["entities/ruben.md"]+ # Dry-run must leave the vault byte-identical.+ on_disk = (vault_root / "entities" / "ruben.md").read_text(encoding="utf-8")+ assert on_disk == PROFILE_BODY+++async def test_apply_snapshots_then_writes_cleaned_profile(+ stack, tmp_path: Path,+) -> None:+ vault_root, curator = stack+ report = await recurate_profile(+ vault_root=vault_root,+ config=_config(),+ curator=curator,+ registry=FakeRegistry(FakeBrain(_cleanup_json())),+ apply=True,+ backup_dir=tmp_path / "recurate-backups",+ )++ assert report.error == ""+ assert report.applied is True+ assert report.backup_path is not None and report.backup_path.is_file()+ on_disk = (vault_root / "entities" / "ruben.md").read_text(encoding="utf-8")+ assert "The Eiffel Tower" not in on_disk+ assert "- Enjoys great coffee." in on_disk+++async def test_unsafe_target_falls_through_to_next_provider(stack) -> None:+ vault_root, curator = stack+ registry = ScriptedProviderRegistry(+ {+ "gemini": json.dumps(+ [+ {+ "target": "../outside.md",+ "operation": "update",+ "new_body": "x",+ }+ ]+ ),+ "openrouter": _cleanup_json(),+ }+ )+ report = await recurate_profile(+ vault_root=vault_root,+ config=_config(),+ curator=curator,+ registry=registry,+ apply=False,+ )++ assert report.error == ""+ assert registry.tried == ["gemini", "openrouter"]+ assert len(report.proposals) == 1+++async def test_missing_profile_reports_error(stack) -> None:+ vault_root, curator = stack+ (vault_root / "entities" / "ruben.md").unlink()++ report = await recurate_profile(+ vault_root=vault_root,+ config=_config(),+ curator=curator,+ registry=FakeRegistry(FakeBrain("[]")),+ apply=False,+ )++ assert report.error == "profile page not found: entities/ruben.md"+ assert report.proposals == []