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(ultrawiki): the first real reader — GitHub issues and pull requests
Ruben Lütke7b97745f743d
diff --git a/jarvis/ultrawiki/adapters/__init__.py b/jarvis/ultrawiki/adapters/__init__.pynew file mode 100644index 0000000000..b7c43db0e3--- /dev/null+++ b/jarvis/ultrawiki/adapters/__init__.py@@ -0,0 +1,73 @@+"""Pull adapters — the readers that turn a connected integration into items.++The plugin bridge is a gateway: it knows about consent, scheduling and+checkpoints, but nothing about any particular product's API. An adapter is the+missing half — ``(ctx, checkpoint) -> AsyncIterator[RawItem]`` for exactly one+integration id.++Until this package existed, EVERY connected app reported "pull adapter+pending": seven integrations that a user had genuinely connected, that the+Plugins store honestly called connected, and that could never contribute a+single item. That gap is what made a knowledge base look broken while nothing+was wrong.++Registration is explicit and late (:func:`register_builtin_adapters`), never a+side effect of importing this package — an adapter reaches for credentials and+network clients, and the plugin bridge must stay importable on a machine that+has neither. The runtime calls it once, lazily, off the boot path (AP-26).+"""++from __future__ import annotations++import logging++log = logging.getLogger(__name__)++__all__ = ["register_builtin_adapters", "registered_adapter_ids"]++#: Guard so a repeated call is a no-op rather than a re-registration storm.+_REGISTERED = False+++def register_builtin_adapters() -> list[str]:+ """Register every adapter shipped with Jarvis. Idempotent, never raises.++ A broken or absent adapter must shorten the list, never stop the others+ from registering — one product's API client failing to import is not a+ reason for the whole bridge to lose its readers.+ """+ global _REGISTERED+ from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415 — lazy++ if _REGISTERED:+ return registered_adapter_ids()++ registered: list[str] = []+ try:+ from jarvis.ultrawiki.adapters.github import ( # noqa: PLC0415 — lazy+ INTEGRATION_ID,+ github_pull_adapter,+ )++ plugin_bridge.register_pull_adapter(INTEGRATION_ID, github_pull_adapter)+ registered.append(INTEGRATION_ID)+ except Exception as exc: # noqa: BLE001 — one bad adapter must not sink the rest+ log.warning("UltraWiki: the GitHub pull adapter could not register: %s", exc)++ _REGISTERED = True+ if registered:+ log.info("UltraWiki pull adapters registered: %s", ", ".join(registered))+ return registered+++def registered_adapter_ids() -> list[str]:+ """Integration ids that currently have a reader (sorted, for display)."""+ from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415 — lazy++ return sorted(plugin_bridge._PULL_ADAPTERS) # noqa: SLF001 — documented seam+++def reset_for_tests() -> None:+ """Drop the idempotence guard so a test can re-register deliberately."""+ global _REGISTERED+ _REGISTERED = Falsediff --git a/jarvis/ultrawiki/adapters/github.py b/jarvis/ultrawiki/adapters/github.pynew file mode 100644index 0000000000..2e6ca41c3a--- /dev/null+++ b/jarvis/ultrawiki/adapters/github.py@@ -0,0 +1,319 @@+"""GitHub pull adapter — the issues and pull requests you were part of.++The first real reader behind the plugin bridge. Of everything GitHub holds,+this pulls the part that belongs in a *memory*: the issues and pull requests+the account is **involved in** — authored, assigned, mentioned, or commented+on. Those carry the decisions and the reasoning. A list of repository names+does not, and the file tree is a code search's job, not a memory's.++One search query does all of it (``involves:<login>``), which matters: the+Search API allows 30 requests a minute, an order of magnitude tighter than the+5 000/hour core bucket, and walking every repository's issue list would burn+that budget on a personal account within seconds.++Re-syncs are cheap by construction, so the bridge's current+``IncrementalMode.NONE`` (every run is a full backfill) costs one or two+requests on a personal account, and every unchanged item upserts as+``unchanged`` on its content hash — no duplicates, no wasted processing.++The adapter is nevertheless already cursor-aware: hand it a numeric checkpoint+and the query gains ``updated:>=<date>``. It rides on ``metadata["mtime_ns"]``,+the convention the sync runner already advances (the file connectors use the+same key for mtimes), so switching the bridge to incremental later needs no+change here. A non-numeric checkpoint — the bridge passes the last item's id+during a backfill — is read as "no cursor" and yields the full set.++Credentials come from the marketplace token the user connected in the Plugins+store — this adapter never asks for a second one and never logs the token.+"""++from __future__ import annotations++import logging+from collections.abc import AsyncIterator+from datetime import UTC, datetime+from typing import Any++import httpx++from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "GitHubAdapterError",+ "github_pull_adapter",+ "item_from_issue",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:github"++_API = "https://api.github.com"++#: Search results are capped at 1 000 per query by GitHub, i.e. 10 full pages.+#: Asking beyond that returns 422, so the walk stops there by construction.+_PER_PAGE = 100+_MAX_PAGES = 10++#: Generous on read: a cold search over a large account is not instant, but a+#: settings screen must not hang on it either.+_TIMEOUT = httpx.Timeout(connect=5.0, read=25.0, write=10.0, pool=5.0)++#: Below this the adapter stops early and lets the next sync continue from the+#: cursor, rather than spending the user's last requests and failing mid-page.+_RATELIMIT_FLOOR = 3+++class GitHubAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace GitHub token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("github")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise GitHubAdapterError(+ "The GitHub connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise GitHubAdapterError(+ "GitHub is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise GitHubAdapterError(+ "The GitHub connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {token}",+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ }+++async def _get(+ client: httpx.AsyncClient, url: str, token: str, params: dict[str, Any] | None = None+) -> httpx.Response:+ """One GET, with every failure mapped to a sentence a user can act on."""+ try:+ response = await client.get(url, headers=_headers(token), params=params)+ except httpx.HTTPError as exc:+ raise GitHubAdapterError(+ f"GitHub was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 401:+ raise GitHubAdapterError(+ "GitHub rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 403 and "rate limit" in response.text.lower():+ raise GitHubAdapterError(+ "GitHub's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise GitHubAdapterError(+ f"GitHub answered HTTP {response.status_code} for this request."+ )+ return response+++async def _login(client: httpx.AsyncClient, token: str) -> str:+ """Whose involvement to search for.++ Resolved from the token rather than configured: the account that connected+ the plugin IS the account whose memory this is, and asking the user to+ retype their own handle is a chance to get it wrong.+ """+ response = await _get(client, f"{_API}/user", token)+ login = str((response.json() or {}).get("login") or "").strip()+ if not login:+ raise GitHubAdapterError("GitHub did not report which account is connected.")+ return login+++def _cursor_to_date(checkpoint: str | None) -> str:+ """The stored numeric cursor as a GitHub search date. Empty when unset.++ The cursor is nanoseconds since the epoch (the sync runner's convention).+ A day is subtracted before querying: GitHub's ``updated:>=`` works on whole+ days, so re-asking from the previous day is what guarantees nothing is+ skipped at a boundary. Re-yielded items upsert as ``unchanged``.+ """+ if not checkpoint:+ return ""+ try:+ seconds = int(checkpoint) / 1_000_000_000+ except (TypeError, ValueError):+ return ""+ if seconds <= 0:+ return ""+ moment = datetime.fromtimestamp(seconds, tz=UTC)+ day = moment.toordinal() - 1+ return datetime.fromordinal(day).strftime("%Y-%m-%d")+++def _to_ns(iso: str) -> int:+ """ISO-8601 → nanoseconds since the epoch; 0 when unparseable."""+ if not iso:+ return 0+ try:+ moment = datetime.fromisoformat(iso.replace("Z", "+00:00"))+ except ValueError:+ return 0+ if moment.tzinfo is None:+ moment = moment.replace(tzinfo=UTC)+ return int(moment.timestamp() * 1_000_000_000)+++def _repo_of(issue: dict[str, Any]) -> str:+ """``owner/repo`` from the search result's repository_url."""+ url = str(issue.get("repository_url") or "")+ parts = url.rsplit("/", 2)+ return "/".join(parts[-2:]) if len(parts) >= 3 else ""+++def item_from_issue(issue: dict[str, Any]) -> RawItem | None:+ """One search hit as a ``RawItem``; ``None`` when it is unusable.++ The body is composed rather than copied raw: a bare issue body loses which+ repository it belongs to and whether it was ever resolved, and both are+ exactly what a later question ("what did we decide about X?") turns on.+ """+ permalink = str(issue.get("html_url") or "").strip()+ number = issue.get("number")+ if not permalink or number is None:+ return None++ repo = _repo_of(issue)+ is_pr = bool(issue.get("pull_request"))+ kind = "pull request" if is_pr else "issue"+ state = str(issue.get("state") or "")+ # A merged PR and a closed-unmerged one are opposite outcomes; "closed"+ # alone would record them as the same thing.+ if is_pr and state == "closed":+ merged = (issue.get("pull_request") or {}).get("merged_at")+ state = "merged" if merged else "closed without merging"++ title = str(issue.get("title") or "").strip() or f"{kind} #{number}"+ author = str((issue.get("user") or {}).get("login") or "")+ labels = [+ str(label.get("name") or "")+ for label in (issue.get("labels") or [])+ if isinstance(label, dict) and label.get("name")+ ]+ created = str(issue.get("created_at") or "")+ updated = str(issue.get("updated_at") or "")++ header = f"{repo} · {kind} #{number} · {state}" if repo else f"{kind} #{number}"+ if labels:+ header += f" · {', '.join(labels)}"+ if author:+ header += f" · opened by {author}"+ body_text = str(issue.get("body") or "").strip()+ comments = int(issue.get("comments") or 0)+ if comments:+ # The comment threads are NOT fetched (one request per issue would+ # blow the 30/min search budget on the first sync). Saying how many+ # exist keeps the record honest about what it does not contain.+ body_text += f"\n\n[{comments} comment(s) on GitHub — open the link to read them]"++ return RawItem(+ external_id=f"issue:{issue.get('id')}",+ title=title,+ body=f"{header}\n\n{body_text}".strip(),+ permalink=permalink,+ # WHEN IT HAPPENED, not when it was last touched — the memory is about+ # the event. The update time rides in metadata to drive the cursor.+ timestamp_utc=created or updated,+ thread_key=f"{repo}#{number}" if repo else str(number),+ author_raw=author,+ metadata={+ "mtime_ns": _to_ns(updated or created),+ "repo": repo,+ "kind": "pull_request" if is_pr else "issue",+ "state": state,+ "labels": labels,+ "comments": comments,+ "updated_at": updated,+ },+ )+++async def github_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield the issues and pull requests this account is involved in.++ ``checkpoint`` doubles as the incremental cursor: present means "only what+ changed since", absent means a full backfill. ``transport`` is a test seam;+ production leaves it ``None``.+ """+ token = _token()+ since = _cursor_to_date(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ login = await _login(client, token)+ query = f"involves:{login}"+ if since:+ query += f" updated:>={since}"++ for page in range(1, _MAX_PAGES + 1):+ response = await _get(+ client,+ f"{_API}/search/issues",+ token,+ params={+ "q": query,+ "sort": "updated",+ "order": "asc",+ "per_page": _PER_PAGE,+ "page": page,+ },+ )+ payload = response.json() or {}+ rows = payload.get("items")+ if not isinstance(rows, list) or not rows:+ break++ for row in rows:+ if not isinstance(row, dict):+ continue+ item = item_from_issue(row)+ if item is not None:+ yielded += 1+ yield item++ if len(rows) < _PER_PAGE:+ break+ # Stop one step short of the wall instead of failing mid-page: the+ # cursor is already checkpointed, so the next run resumes cleanly.+ remaining = response.headers.get("x-ratelimit-remaining")+ if remaining is not None and remaining.isdigit():+ if int(remaining) <= _RATELIMIT_FLOOR:+ log.info(+ "GitHub adapter: stopping at page %d — rate budget "+ "nearly spent; the next sync resumes from the cursor",+ page,+ )+ break++ log.info(+ "GitHub adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if since else "backfill",+ )diff --git a/tests/unit/ultrawiki/test_github_adapter.py b/tests/unit/ultrawiki/test_github_adapter.pynew file mode 100644index 0000000000..40b11023bc--- /dev/null+++ b/tests/unit/ultrawiki/test_github_adapter.py@@ -0,0 +1,253 @@+"""The GitHub pull adapter, driven fully offline through MockTransport.++The first real reader behind the plugin bridge, so these tests pin what makes+a reader trustworthy rather than merely functional: a stable id (a re-run must+upsert, not duplicate), a real deep link on every item, the event's own time+rather than its last edit, and failure messages a user can act on that never+carry the token.+"""++from __future__ import annotations++import json+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import github as gh+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected GitHub plugin, without touching the host's keyring."""++ class _Tokens:+ access = "gho_test"+ needs_reauth = False++ class _Store:+ def load(self, _plugin_id):+ return _Tokens()++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+++def _ctx() -> ConnectorContext:+ return ConnectorContext(+ source_id="src-github",+ config={"integration_id": "plugin:github"},+ secret_get=lambda _name: None,+ )+++def _issue(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "id": 4242,+ "number": 7,+ "title": "Ship the wake-word fix",+ "html_url": "https://github.com/acme/widgets/issues/7",+ "repository_url": "https://api.github.com/repos/acme/widgets",+ "state": "open",+ "body": "The wake word misses every third call.",+ "user": {"login": "rubenluetke10-beep"},+ "labels": [{"name": "bug"}],+ "comments": 0,+ "created_at": "2026-03-01T10:00:00Z",+ "updated_at": "2026-03-04T12:00:00Z",+ }+ base.update(overrides)+ return base+++def _transport(+ pages: list[list[dict[str, Any]]],+ *,+ login: str = "rubenluetke10-beep",+ headers: dict[str, str] | None = None,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if request.url.path == "/user":+ return httpx.Response(200, content=json.dumps({"login": login}).encode())+ page = int(request.url.params.get("page", "1"))+ rows = pages[page - 1] if page <= len(pages) else []+ return httpx.Response(+ 200,+ content=json.dumps({"items": rows}).encode(),+ headers=headers or {},+ )++ return httpx.MockTransport(handler)+++async def _collect(checkpoint: str | None = None, **kwargs: Any) -> list:+ return [+ item+ async for item in gh.github_pull_adapter(_ctx(), checkpoint, **kwargs)+ ]+++async def test_an_issue_becomes_a_linkable_dated_item():+ items = await _collect(transport=_transport([[_issue()]]))+ assert len(items) == 1+ item = items[0]+ # Stable per source: a second run must upsert this same row, not add one.+ assert item.external_id == "issue:4242"+ # Evidence has to lead back to where it lives — mandatory from item one.+ assert item.permalink == "https://github.com/acme/widgets/issues/7"+ # WHEN IT HAPPENED, not when it was last touched.+ assert item.timestamp_utc == "2026-03-01T10:00:00Z"+ assert item.title == "Ship the wake-word fix"+ assert item.author_raw == "rubenluetke10-beep"+ assert item.thread_key == "acme/widgets#7"+ # The composed header keeps the context a bare body would lose.+ assert "acme/widgets · issue #7 · open" in item.body+ assert "bug" in item.body+ assert "The wake word misses every third call." in item.body+++async def test_a_merged_pull_request_is_not_recorded_as_merely_closed():+ """"Closed" and "merged" are opposite outcomes; conflating them loses the+ only fact a later question usually turns on."""+ merged = _issue(+ id=99,+ number=12,+ state="closed",+ pull_request={"merged_at": "2026-03-05T09:00:00Z"},+ )+ rejected = _issue(id=100, number=13, state="closed", pull_request={"merged_at": None})+ items = await _collect(transport=_transport([[merged, rejected]]))+ assert items[0].metadata["state"] == "merged"+ assert items[0].metadata["kind"] == "pull_request"+ assert items[1].metadata["state"] == "closed without merging"+++async def test_unfetched_comments_are_declared_rather_than_silently_dropped():+ """One request per issue would blow the 30/min search budget, so the+ threads are not pulled — the record must say so instead of implying the+ body is the whole conversation."""+ items = await _collect(transport=_transport([[_issue(comments=5)]]))+ assert "5 comment(s) on GitHub" in items[0].body+ assert items[0].metadata["comments"] == 5+++async def test_the_cursor_rides_on_the_key_the_sync_runner_advances():+ items = await _collect(transport=_transport([[_issue()]]))+ # 2026-03-04T12:00:00Z in nanoseconds — the runner reads exactly this key.+ assert items[0].metadata["mtime_ns"] == gh._to_ns("2026-03-04T12:00:00Z")+ assert items[0].metadata["mtime_ns"] > 0+++async def test_a_numeric_checkpoint_narrows_the_query_by_date():+ seen: list[httpx.Request] = []+ await _collect(+ checkpoint=str(gh._to_ns("2026-03-04T12:00:00Z")),+ transport=_transport([[]], seen=seen),+ )+ search = next(r for r in seen if r.url.path == "/search/issues")+ query = search.url.params["q"]+ assert "involves:rubenluetke10-beep" in query+ # A day earlier than the cursor: GitHub's updated:>= works on whole days,+ # so re-asking from the previous day is what makes a boundary safe.+ assert "updated:>=2026-03-03" in query+++async def test_a_backfill_checkpoint_is_read_as_no_cursor():+ """The bridge passes the last item's external_id during a backfill.++ That is not a date, and mis-parsing it would silently narrow the query to+ nothing. It must degrade to a full read.+ """+ seen: list[httpx.Request] = []+ await _collect(checkpoint="issue:4242", transport=_transport([[]], seen=seen))+ search = next(r for r in seen if r.url.path == "/search/issues")+ assert "updated:" not in search.url.params["q"]+++async def test_pagination_stops_on_a_short_page():+ pages = [[_issue(id=i, number=i) for i in range(100)], [_issue(id=999, number=999)]]+ seen: list[httpx.Request] = []+ items = await _collect(transport=_transport(pages, seen=seen))+ assert len(items) == 101+ searches = [r for r in seen if r.url.path == "/search/issues"]+ assert len(searches) == 2 # stopped after the short second page+++async def test_a_nearly_spent_rate_budget_stops_early_instead_of_failing():+ """The cursor is already checkpointed, so stopping is free; running into+ the wall mid-page is not."""+ pages = [[_issue(id=i, number=i) for i in range(100)] for _ in range(3)]+ seen: list[httpx.Request] = []+ items = await _collect(+ transport=_transport(pages, headers={"x-ratelimit-remaining": "1"}, seen=seen)+ )+ assert len(items) == 100+ assert len([r for r in seen if r.url.path == "/search/issues"]) == 1+++async def test_a_rejected_token_says_what_to_do_and_never_echoes_it():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, content=b'{"message":"Bad credentials"}')++ with pytest.raises(gh.GitHubAdapterError) as excinfo:+ await _collect(transport=httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "gho_test" not in message+++async def test_an_unconnected_plugin_refuses_before_any_request(monkeypatch):+ class _Store:+ def load(self, _plugin_id):+ return None++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+ with pytest.raises(gh.GitHubAdapterError, match="not connected"):+ await _collect(transport=_transport([[]]))+++async def test_an_expired_connection_is_named_as_such(monkeypatch):+ class _Tokens:+ access = "gho_old"+ needs_reauth = True++ class _Store:+ def load(self, _plugin_id):+ return _Tokens()++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+ with pytest.raises(gh.GitHubAdapterError, match="expired"):+ await _collect(transport=_transport([[]]))+++async def test_a_row_without_a_permalink_is_skipped_not_faked():+ """Every item must deep-link back; a row that cannot is dropped."""+ items = await _collect(+ transport=_transport([[_issue(html_url=""), _issue(id=5, number=8)]])+ )+ assert [i.external_id for i in items] == ["issue:5"]+++def test_the_adapter_registers_under_the_bridge_candidate_id():+ from jarvis.ultrawiki import adapters+ from jarvis.ultrawiki.connectors import plugin_bridge++ adapters.reset_for_tests()+ plugin_bridge.unregister_pull_adapter(gh.INTEGRATION_ID)+ assert plugin_bridge.has_pull_adapter(gh.INTEGRATION_ID) is False++ registered = adapters.register_builtin_adapters()+ assert gh.INTEGRATION_ID in registered+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ assert plugin_bridge.has_pull_adapter("plugin:github") is True