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): pull adapters for all fourteen curated integrations
Ruben Lütke18f59df54267
diff --git a/jarvis/ultrawiki/adapters/__init__.py b/jarvis/ultrawiki/adapters/__init__.pyindex b7c43db0e3..317e4aa619 100644--- a/jarvis/ultrawiki/adapters/__init__.py+++ b/jarvis/ultrawiki/adapters/__init__.py@@ -28,6 +28,43 @@ __all__ = ["register_builtin_adapters", "registered_adapter_ids"]#: Guard so a repeated call is a no-op rather than a re-registration storm._REGISTERED = False+#: Every adapter shipped with Jarvis: (integration id, module, factory attr).+#: One row per catalog entry with a reader — the parity test asserts this+#: table covers every roster id whose reader exists, so a new adapter that+#: forgets its row here fails CI instead of silently staying "pending".+_BUILTIN_ADAPTERS: tuple[tuple[str, str, str], ...] = (+ ("plugin:github", "jarvis.ultrawiki.adapters.github", "github_pull_adapter"),+ ("plugin:slack", "jarvis.ultrawiki.adapters.slack", "slack_pull_adapter"),+ ("plugin:gmail", "jarvis.ultrawiki.adapters.google_mail", "gmail_pull_adapter"),+ (+ "plugin:google_calendar",+ "jarvis.ultrawiki.adapters.google_calendar",+ "google_calendar_pull_adapter",+ ),+ (+ "plugin:google_drive",+ "jarvis.ultrawiki.adapters.google_drive",+ "google_drive_pull_adapter",+ ),+ ("plugin:notion", "jarvis.ultrawiki.adapters.notion", "notion_pull_adapter"),+ ("plugin:asana", "jarvis.ultrawiki.adapters.asana", "asana_pull_adapter"),+ ("plugin:linear", "jarvis.ultrawiki.adapters.linear", "linear_pull_adapter"),+ ("plugin:todoist", "jarvis.ultrawiki.adapters.todoist", "todoist_pull_adapter"),+ ("plugin:clickup", "jarvis.ultrawiki.adapters.clickup", "clickup_pull_adapter"),+ ("plugin:dropbox", "jarvis.ultrawiki.adapters.dropbox", "dropbox_pull_adapter"),+ (+ "plugin:airtable",+ "jarvis.ultrawiki.adapters.airtable",+ "airtable_pull_adapter",+ ),+ ("plugin:discord", "jarvis.ultrawiki.adapters.discord", "discord_pull_adapter"),+ (+ "plugin:telegram",+ "jarvis.ultrawiki.adapters.telegram",+ "telegram_pull_adapter",+ ),+)+def register_builtin_adapters() -> list[str]:"""Register every adapter shipped with Jarvis. Idempotent, never raises.@@ -37,22 +74,31 @@ def register_builtin_adapters() -> list[str]:reason for the whole bridge to lose its readers."""global _REGISTERED+ import importlib # noqa: PLC0415 — lazy+from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415 — lazyif _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)+ for integration_id, module_path, factory_name in _BUILTIN_ADAPTERS:+ try:+ module = importlib.import_module(module_path)+ factory = getattr(module, factory_name)+ declared = getattr(module, "INTEGRATION_ID", integration_id)+ if declared != integration_id:+ raise RuntimeError(+ f"module declares {declared!r}, table says {integration_id!r}"+ )+ plugin_bridge.register_pull_adapter(integration_id, factory)+ registered.append(integration_id)+ except Exception as exc: # noqa: BLE001 — one bad adapter must not sink the rest+ log.warning(+ "UltraWiki: pull adapter %s could not register: %s",+ integration_id,+ exc,+ )_REGISTERED = Trueif registered:diff --git a/jarvis/ultrawiki/adapters/_google.py b/jarvis/ultrawiki/adapters/_google.pynew file mode 100644index 0000000000..e4fbdc4783--- /dev/null+++ b/jarvis/ultrawiki/adapters/_google.py@@ -0,0 +1,301 @@+"""Shared plumbing for the Google-family pull adapters (Gmail, Calendar, Drive).++The three Google integrations are separate marketplace plugins with separate+token entries (they share one OAuth *client*, never one grant), so each+adapter resolves its OWN plugin id — but everything else about talking to a+Google API is identical: bearer-token requests, JSON envelopes, 429/quota+behaviour with a ``Retry-After`` header, and the same honest error sentences+when a connection is missing, expired, or rejected. That sameness lives here+exactly once.++Nothing in this module is an adapter: it never yields items, never touches+the store, and never decides what is worth importing. It is the transport+floor the three adapters stand on, with an injectable ``httpx`` transport so+every test drives it offline.+"""++from __future__ import annotations++import asyncio+import base64+import binascii+import html as html_module+import logging+import re+from datetime import UTC, datetime, timedelta+from typing import Any++import httpx++log = logging.getLogger(__name__)++__all__ = [+ "BODY_CAP",+ "TIMEOUT",+ "TRUNCATION_MARKER",+ "GoogleAdapterError",+ "cap_body",+ "cursor_cutoff",+ "decode_base64url",+ "google_get",+ "google_get_json",+ "google_token",+ "iso_utc_from_ms",+ "ms_to_ns",+ "strip_html",+ "to_ns",+]++#: Generous on read: exporting a large document is not instant, but a sync+#: must not hang forever on one item either.+TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)++#: A single item's body never exceeds this many characters (memory-shaped+#: scope: a knowledge base wants the text, not a bulk archive).+BODY_CAP = 1_000_000++#: Appended when a body was cut at :data:`BODY_CAP` — the record must say it+#: is incomplete rather than imply the text ends where the cap fell.+TRUNCATION_MARKER = "\n\n[truncated: this item exceeded the 1 MB import cap]"++#: Bounded retries for rate-limited requests: respect ``Retry-After`` when+#: present, back off briefly when not, and give up honestly after this many+#: attempts — a sync must never spin on a throttled API.+_MAX_ATTEMPTS = 3+_MAX_RETRY_WAIT = 30.0+++class GoogleAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def google_token(plugin_id: str, product: str) -> str:+ """The marketplace token for one Google plugin, or an honest refusal.++ ``plugin_id`` is the marketplace id (``gmail`` / ``google_calendar`` /+ ``google_drive``); ``product`` is the display name the error sentences+ carry. The token itself never appears in any message.+ """+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load(plugin_id)+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise GoogleAdapterError(+ f"The {product} connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise GoogleAdapterError(+ f"{product} is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise GoogleAdapterError(+ f"The {product} connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _rate_limited(response: httpx.Response) -> bool:+ """True when the answer means "slow down", regardless of the status code.++ Google APIs signal throttling as plain 429 AND as 403 with a+ rate/quota reason in the body; both deserve the same bounded retry.+ """+ if response.status_code == 429:+ return True+ if response.status_code == 403:+ text = response.text.lower()+ return "ratelimit" in text or "rate limit" in text or "quota" in text+ return False+++def _retry_wait(response: httpx.Response, attempt: int) -> float:+ header = response.headers.get("retry-after", "")+ try:+ wait = float(header)+ except ValueError:+ wait = float(2**attempt)+ return min(max(wait, 0.0), _MAX_RETRY_WAIT)+++async def google_get(+ client: httpx.AsyncClient,+ url: str,+ token: str,+ product: str,+ *,+ params: dict[str, Any] | None = None,+ headers: dict[str, str] | None = None,+ tolerate: tuple[int, ...] = (),+) -> httpx.Response:+ """One GET with bounded rate-limit retries; every failure becomes a sentence.++ ``tolerate`` lists status codes the CALLER wants to handle (e.g. a 404 on+ a probe, a 403 on one file's export) — those come back as the response.+ Credential failures (401) and exhausted rate budgets always raise: they+ concern the whole sync, never a single item.+ """+ request_headers = {"Authorization": f"Bearer {token}"}+ if headers:+ request_headers.update(headers)++ response: httpx.Response | None = None+ for attempt in range(_MAX_ATTEMPTS):+ try:+ response = await client.get(url, headers=request_headers, params=params)+ except httpx.HTTPError as exc:+ raise GoogleAdapterError(+ f"{product} was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if not _rate_limited(response):+ break+ if attempt + 1 >= _MAX_ATTEMPTS:+ break+ await asyncio.sleep(_retry_wait(response, attempt))+ if response is None: # pragma: no cover - loop always runs at least once+ raise GoogleAdapterError(f"{product} could not be reached.")++ if _rate_limited(response):+ raise GoogleAdapterError(+ f"{product}'s rate limit is exhausted. The next sync continues "+ "where this one stopped."+ )+ if response.status_code in tolerate:+ return response+ if response.status_code == 401:+ raise GoogleAdapterError(+ f"{product} rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 403:+ raise GoogleAdapterError(+ f"{product} denied access (HTTP 403). The connection may lack the "+ "required scope — reconnect it in the Plugins store."+ )+ if response.status_code >= 400:+ raise GoogleAdapterError(+ f"{product} answered HTTP {response.status_code} for this request."+ )+ return response+++async def google_get_json(+ client: httpx.AsyncClient,+ url: str,+ token: str,+ product: str,+ *,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """A JSON GET; a non-object answer degrades to an empty dict."""+ response = await google_get(client, url, token, product, params=params)+ try:+ payload = response.json()+ except ValueError as exc:+ raise GoogleAdapterError(+ f"{product} answered with something that is not JSON."+ ) from exc+ return payload if isinstance(payload, dict) else {}+++# ---------------------------------------------------------------------------+# Time — the cursor convention shared with the reference adapter+# ---------------------------------------------------------------------------+++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 ms_to_ns(ms: Any) -> int:+ """Epoch milliseconds (Gmail's ``internalDate``) → nanoseconds; 0 on junk."""+ try:+ value = int(ms)+ except (TypeError, ValueError):+ return 0+ return value * 1_000_000 if value > 0 else 0+++def iso_utc_from_ms(ms: Any) -> str:+ """Epoch milliseconds → ``YYYY-MM-DDTHH:MM:SSZ``; empty string on junk."""+ try:+ value = int(ms)+ except (TypeError, ValueError):+ return ""+ if value <= 0:+ return ""+ return datetime.fromtimestamp(value / 1000, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def cursor_cutoff(checkpoint: str | None) -> datetime | None:+ """The stored numeric cursor as an aware UTC moment, one day earlier.++ The cursor is nanoseconds since the epoch (the sync runner's convention,+ advanced from ``metadata["mtime_ns"]``). A day is subtracted before+ querying so a boundary can never skip an item; re-yielded items upsert as+ ``unchanged``. A non-numeric checkpoint — the bridge passes the last+ item's external id during a backfill — is NOT a cursor and returns+ ``None``; the adapters resume positionally from it instead.+ """+ if not checkpoint:+ return None+ try:+ seconds = int(checkpoint) / 1_000_000_000+ except (TypeError, ValueError):+ return None+ if seconds <= 0:+ return None+ return datetime.fromtimestamp(seconds, tz=UTC) - timedelta(days=1)+++# ---------------------------------------------------------------------------+# Text — capping, HTML stripping, base64url+# ---------------------------------------------------------------------------+++def cap_body(text: str) -> tuple[str, bool]:+ """``(body, truncated)`` — the text cut at :data:`BODY_CAP` and marked."""+ if len(text) <= BODY_CAP:+ return text, False+ return text[:BODY_CAP] + TRUNCATION_MARKER, True+++_SCRIPT_STYLE_RE = re.compile(r"<(script|style)\b.*?</\1\s*>", re.IGNORECASE | re.DOTALL)+_BREAK_RE = re.compile(r"<\s*(br|/p|/div|/li|/tr|/h[1-6]|/blockquote)\s*/?\s*>", re.IGNORECASE)+_TAG_RE = re.compile(r"<[^>]+>")+_SPACE_RE = re.compile(r"[ \t]+")+_BLANK_RE = re.compile(r"\n{3,}")+++def strip_html(markup: str) -> str:+ """HTML → readable plain text. Regex only, never an LLM call (AP-11 spirit)."""+ text = _SCRIPT_STYLE_RE.sub(" ", markup)+ text = _BREAK_RE.sub("\n", text)+ text = _TAG_RE.sub(" ", text)+ # Unescape entities, then fold non-breaking spaces into ordinary ones:+ # \xa0 survives `` `` and reads as junk in a plain-text memory.+ text = html_module.unescape(text).replace("\xa0", " ")+ lines = [_SPACE_RE.sub(" ", line).strip() for line in text.splitlines()]+ return _BLANK_RE.sub("\n\n", "\n".join(lines)).strip()+++def decode_base64url(data: str) -> str:+ """Gmail's base64url body data → text; empty string on junk, never a crash."""+ if not data:+ return ""+ padded = data + "=" * (-len(data) % 4)+ try:+ raw = base64.urlsafe_b64decode(padded.encode("ascii"))+ except (ValueError, binascii.Error):+ return ""+ return raw.decode("utf-8", errors="replace")diff --git a/jarvis/ultrawiki/adapters/airtable.py b/jarvis/ultrawiki/adapters/airtable.pynew file mode 100644index 0000000000..72814b52c9--- /dev/null+++ b/jarvis/ultrawiki/adapters/airtable.py@@ -0,0 +1,451 @@+"""Airtable pull adapter — every record in every base the token can read.++Airtable is structured data, and a record's memory value lives in its field+values: this adapter walks ``meta/bases`` → tables → records and yields one+``RawItem`` per record, its fields flattened to ``Field: value`` lines in the+table's own schema order. Attachments are listed by name and URL and NEVER+downloaded — binaries do not belong in a knowledge base, but knowing a record+carries "photo.jpg" absolutely does.++Scope, stated plainly:++* **Everything the token allows is walked** — every base ``meta/bases``+ returns (offset-paged), every table of each base, every record of each+ table (offset-paged, 100 per request). A single base the token can list but+ not read (a missing scope on just that base, HTTP 403) is skipped with a+ log line so the rest still imports; a rejected token aborts honestly.+* **Freshness is a full rescan.** Airtable's list API has NO global+ modified-since filter, so there is nothing a cursor could ask the server+ for. The honest freshness path is re-running the walk and letting the+ idempotent upserts sort new/changed/unchanged — cheap in writes, one+ request per 100 records in reads. ``metadata["mtime_ns"]`` is still+ carried (from a ``lastModifiedTime`` field when the table has one, else+ ``createdTime``) so the runner's cursor advances, and a NUMERIC checkpoint+ is deliberately read as "full rescan" rather than mis-filtering.+* **Record comments are not imported** — the records API does not return+ them, and fetching them would cost one request per record.++The walk is deterministic: tables are visited in the string order of their+``<base>:<table>:`` prefix and records sorted by record id, which makes the+stream strictly increasing in ``external_id`` (``<base>:<table>:<record>``) —+exactly what lets the bridge's backfill checkpoint resume strictly after the+last persisted id. Tables whose every record sorts before the checkpoint are+skipped without a single records request.++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 asyncio+import json+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",+ "AirtableAdapterError",+ "airtable_pull_adapter",+ "item_from_record",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:airtable"++_API = "https://api.airtable.com"++#: Airtable's maximum records page size.+_PAGE_SIZE = 100+#: Hard bounds so a misbehaving server can never loop a walk forever. 5 000+#: record pages is half a million records in ONE table — beyond any plan.+_MAX_RECORD_PAGES = 5000+_MAX_BASE_PAGES = 100++_TIMEOUT = httpx.Timeout(connect=5.0, read=25.0, write=10.0, pool=5.0)++#: A flattened record is normally tiny; the cap only guards a pathological+#: long-text field.+_MAX_BODY_BYTES = 1024 * 1024+_TRUNCATION_MARKER = "\n\n[truncated at 1 MiB — open the link for the full record]"++#: Bounded 429 handling. Airtable documents a 30-second penalty window, so+#: that is the default wait when no Retry-After header says otherwise.+_MAX_RETRIES = 3+_MAX_RETRY_WAIT = 30.0+++class AirtableAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token.++ ``status`` carries the HTTP status when one applies, so the walk can skip+ a single denied base without abandoning everything the token CAN read.+ """++ def __init__(self, message: str, *, status: int | None = None) -> None:+ super().__init__(message)+ self.status = status+++def _token() -> str:+ """The marketplace Airtable token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("airtable")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise AirtableAdapterError(+ "The Airtable connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise AirtableAdapterError(+ "Airtable is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise AirtableAdapterError(+ "The Airtable connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _retry_wait(response: httpx.Response) -> float:+ """How long a 429 asks us to wait — honored, but never beyond the bound."""+ raw = response.headers.get("retry-after", "")+ try:+ wait = float(raw)+ except ValueError:+ wait = _MAX_RETRY_WAIT # Airtable's documented penalty window+ return min(max(wait, 0.0), _MAX_RETRY_WAIT)+++async def _get(+ client: httpx.AsyncClient,+ url: str,+ token: str,+ params: dict[str, Any] | None = None,+) -> httpx.Response:+ """One GET with bounded 429 retries and user-actionable failure mapping."""+ response: httpx.Response | None = None+ for attempt in range(_MAX_RETRIES + 1):+ try:+ response = await client.get(+ url, headers={"Authorization": f"Bearer {token}"}, params=params+ )+ except httpx.HTTPError as exc:+ raise AirtableAdapterError(+ f"Airtable was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429 and attempt < _MAX_RETRIES:+ await asyncio.sleep(_retry_wait(response))+ continue+ break+ assert response is not None # the loop always assigns or raises+ if response.status_code == 401:+ raise AirtableAdapterError(+ "Airtable rejected the connection. Reconnect it in the Plugins store.",+ status=401,+ )+ if response.status_code == 403:+ raise AirtableAdapterError(+ "Airtable denied access to this data — the connection is missing a "+ "permission scope. Reconnect it in the Plugins store.",+ status=403,+ )+ if response.status_code == 429:+ raise AirtableAdapterError(+ "Airtable's rate limit is exhausted. The next sync continues where "+ "this one stopped.",+ status=429,+ )+ if response.status_code >= 400:+ raise AirtableAdapterError(+ f"Airtable answered HTTP {response.status_code} for this request.",+ status=response.status_code,+ )+ return response+++async def _list_bases(client: httpx.AsyncClient, token: str) -> list[dict[str, Any]]:+ """Every base the token can see, via offset paging."""+ bases: list[dict[str, Any]] = []+ offset: str | None = None+ for _page in range(_MAX_BASE_PAGES):+ params: dict[str, Any] = {"offset": offset} if offset else {}+ response = await _get(client, f"{_API}/v0/meta/bases", token, params=params)+ payload = response.json() or {}+ rows = payload.get("bases")+ bases.extend(row for row in (rows or []) if isinstance(row, dict))+ offset = str(payload.get("offset") or "") or None+ if not offset:+ break+ else: # pragma: no cover — needs 100 real pages+ log.warning("airtable adapter: stopped listing bases after %d pages", _MAX_BASE_PAGES)+ return bases+++async def _list_tables(+ client: httpx.AsyncClient, token: str, base_id: str+) -> list[dict[str, Any]]:+ """Every table of one base (the endpoint returns them all at once)."""+ response = await _get(client, f"{_API}/v0/meta/bases/{base_id}/tables", token)+ rows = (response.json() or {}).get("tables")+ return [row for row in (rows or []) if isinstance(row, dict)]+++async def _list_records(+ client: httpx.AsyncClient, token: str, base_id: str, table_id: str+) -> list[dict[str, Any]]:+ """Every record of one table, via offset paging."""+ records: list[dict[str, Any]] = []+ offset: str | None = None+ for _page in range(_MAX_RECORD_PAGES):+ params: dict[str, Any] = {"pageSize": _PAGE_SIZE}+ if offset:+ params["offset"] = offset+ response = await _get(client, f"{_API}/v0/{base_id}/{table_id}", token, params=params)+ payload = response.json() or {}+ rows = payload.get("records")+ records.extend(row for row in (rows or []) if isinstance(row, dict))+ offset = str(payload.get("offset") or "") or None+ if not offset:+ break+ else: # pragma: no cover — needs half a million real records+ log.warning(+ "airtable adapter: stopped listing records of %s/%s after %d pages",+ base_id,+ table_id,+ _MAX_RECORD_PAGES,+ )+ return records+++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 _resume_checkpoint(checkpoint: str | None) -> str | None:+ """The backfill resume id, or ``None`` for a full walk.++ A backfill checkpoint is the last persisted ``external_id`` — here always+ ``<base>:<table>:<record>``, so it contains colons. A NUMERIC checkpoint+ is the runner's mtime cursor; Airtable has no server-side modified filter+ to hand it to, so it deliberately reads as "full rescan" (idempotent+ upserts make that correct, the module docstring makes it honest).+ """+ if not checkpoint:+ return None+ text = str(checkpoint).strip()+ if ":" not in text:+ return None+ return text+++def _render_value(value: Any) -> str:+ """One field value as display text; attachments become ``name (url)``."""+ if value is None:+ return ""+ if isinstance(value, bool):+ return "yes" if value else "no"+ if isinstance(value, int | float | str):+ return str(value).strip()+ if isinstance(value, dict):+ # Attachments carry a filename; listed, never downloaded.+ if value.get("filename") or value.get("url"):+ name = str(value.get("filename") or "attachment")+ url = str(value.get("url") or "")+ return f"{name} ({url})" if url else name+ # Collaborators and similar objects: prefer a human-readable field.+ for key in ("name", "email", "label", "text", "id"):+ if value.get(key):+ return str(value[key])+ return json.dumps(value, ensure_ascii=False)+ if isinstance(value, list):+ parts = [_render_value(entry) for entry in value]+ return ", ".join(part for part in parts if part)+ return str(value)+++def _schema_fields(table: dict[str, Any]) -> list[dict[str, Any]]:+ rows = table.get("fields")+ return [row for row in (rows or []) if isinstance(row, dict)]+++def _modified_value(table: dict[str, Any], fields: dict[str, Any]) -> str:+ """The record's last-modified time, when the table tracks one."""+ for field in _schema_fields(table):+ if str(field.get("type") or "") == "lastModifiedTime":+ value = fields.get(str(field.get("name") or ""))+ if isinstance(value, str) and value:+ return value+ return ""+++def _title_for(table: dict[str, Any], fields: dict[str, Any], record_id: str) -> str:+ """The primary field's value — the name Airtable itself shows the record as."""+ primary_id = str(table.get("primaryFieldId") or "")+ for field in _schema_fields(table):+ if str(field.get("id") or "") == primary_id:+ rendered = _render_value(fields.get(str(field.get("name") or "")))+ if rendered:+ return rendered+ break+ table_name = str(table.get("name") or "table")+ return f"{table_name} record {record_id}"+++def item_from_record(+ base: dict[str, Any], table: dict[str, Any], record: dict[str, Any]+) -> RawItem | None:+ """One record as a ``RawItem``; ``None`` when it is unusable.++ The body flattens the fields in the table's own schema order (extra keys+ the schema does not know follow, sorted), because that order is the one+ the user arranged and reads the record in.+ """+ base_id = str(base.get("id") or "")+ table_id = str(table.get("id") or "")+ record_id = str(record.get("id") or "")+ if not base_id or not table_id or not record_id:+ return None+ fields = record.get("fields")+ if not isinstance(fields, dict):+ fields = {}++ created = str(record.get("createdTime") or "")+ modified = _modified_value(table, fields)+ timestamp = modified or created++ base_name = str(base.get("name") or base_id)+ table_name = str(table.get("name") or table_id)+ schema_order = [+ str(field.get("name") or "")+ for field in _schema_fields(table)+ if field.get("name")+ ]+ ordered = [name for name in schema_order if name in fields]+ ordered += sorted(name for name in fields if name not in schema_order)+ lines = []+ for name in ordered:+ rendered = _render_value(fields.get(name))+ if rendered:+ lines.append(f"{name}: {rendered}")++ body = f"{base_name} · {table_name} · record"+ if lines:+ body += "\n\n" + "\n".join(lines)+ if len(body.encode("utf-8")) > _MAX_BODY_BYTES:+ body = body.encode("utf-8")[:_MAX_BODY_BYTES].decode("utf-8", errors="replace")+ body += _TRUNCATION_MARKER++ return RawItem(+ external_id=f"{base_id}:{table_id}:{record_id}",+ title=_title_for(table, fields, record_id),+ body=body,+ permalink=f"https://airtable.com/{base_id}/{table_id}/{record_id}",+ timestamp_utc=timestamp,+ # The table is the natural conversation: its records belong together.+ thread_key=f"{base_id}:{table_id}",+ metadata={+ "mtime_ns": _to_ns(timestamp),+ "base": base_id,+ "base_name": base_name,+ "table": table_id,+ "table_name": table_name,+ "created_time": created,+ "modified_time": modified,+ },+ )+++async def airtable_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every record of every base the connected Airtable token can read.++ ``checkpoint`` is the bridge's backfill resume id (see+ :func:`_resume_checkpoint`). ``transport`` is a test seam; production+ leaves it ``None``.+ """+ token = _token()+ resume_after = _resume_checkpoint(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ walk: list[tuple[str, dict[str, Any], dict[str, Any]]] = []+ for base in await _list_bases(client, token):+ base_id = str(base.get("id") or "")+ if not base_id:+ continue+ try:+ tables = await _list_tables(client, token, base_id)+ except AirtableAdapterError as exc:+ if exc.status in (403, 404):+ log.info("airtable adapter: skipping base %s (%s)", base_id, exc)+ continue+ raise+ for table in tables:+ table_id = str(table.get("id") or "")+ if table_id:+ walk.append((f"{base_id}:{table_id}:", base, table))+ # Sorted by the external_id PREFIX: with records sorted by id below,+ # the whole stream is strictly increasing in external_id — the only+ # order under which "resume strictly after the checkpoint" is correct.+ walk.sort(key=lambda row: row[0])++ for prefix, base, table in walk:+ if resume_after and not resume_after.startswith(prefix) and prefix < resume_after:+ # Every record of this table sorts at or before the+ # checkpoint — skip it without a single records request.+ continue+ base_id = str(base.get("id") or "")+ table_id = str(table.get("id") or "")+ try:+ records = await _list_records(client, token, base_id, table_id)+ except AirtableAdapterError as exc:+ if exc.status in (403, 404):+ log.info(+ "airtable adapter: skipping table %s/%s (%s)",+ base_id,+ table_id,+ exc,+ )+ continue+ raise+ records.sort(key=lambda row: str(row.get("id") or ""))+ for record in records:+ item = item_from_record(base, table, record)+ if item is None:+ continue+ if resume_after and item.external_id <= resume_after:+ continue+ yielded += 1+ yield item++ log.info(+ "Airtable adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "resumed backfill" if resume_after else "full rescan",+ )diff --git a/jarvis/ultrawiki/adapters/asana.py b/jarvis/ultrawiki/adapters/asana.pynew file mode 100644index 0000000000..468940a4f1--- /dev/null+++ b/jarvis/ultrawiki/adapters/asana.py@@ -0,0 +1,403 @@+"""Asana pull adapter — every task the connected account can list.++Scope, honestly stated. The adapter walks every workspace the marketplace+token reaches, every project in those workspaces (archived projects included —+the listing simply omits the ``archived`` filter), and every task in those+projects, completed ones included. On top of the project walk it lists the+tasks assigned to the connected user per workspace, so personal tasks that+live in no walked project still arrive. Comment stories are fetched per task+and folded into the body chronologically; system activity ("moved to section+X") is excluded because it is bookkeeping, not memory.++What the token structurally cannot yield: subtasks that are neither placed in+a project nor assigned to the user (reaching them needs one extra request per+task, doubling the budget for a corner case), and tasks that sit in no project+and are assigned to someone else (only Asana's paid search API can enumerate+those). Everything else the API can list, this adapter imports.++Cursor convention (the reference adapter's): a numeric checkpoint is the sync+runner's nanosecond cursor and narrows every task listing with+``modified_since`` (minus a five-minute overlap so a boundary is safe;+re-yielded items upsert as ``unchanged``). A ``task:<gid>`` checkpoint is the+bridge's backfill resume marker: tasks stream oldest-to-newest in a+deterministic order, so the walk resumes strictly after that id. Any other+checkpoint is read as "no cursor" and yields the full set. Every item carries+``metadata["mtime_ns"]`` so the runner can advance its cursor.++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 asyncio+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",+ "AsanaAdapterError",+ "asana_pull_adapter",+ "item_from_task",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:asana"++_API = "https://app.asana.com/api/1.0"++_PAGE_SIZE = 100+#: Safety valve per collection walk; at 100 rows a page this is 20 000 rows.+_MAX_PAGES = 200++#: Generous on read: a cold walk 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)++#: Bounded 429 handling: honor Retry-After up to a cap, then give up honestly.+_MAX_ATTEMPTS = 3+_RETRY_WAIT_CAP = 30.0+_DEFAULT_RETRY_WAIT = 2.0++#: Re-ask five minutes before the cursor so a boundary can never skip an item.+_SINCE_OVERLAP_SECONDS = 300++#: Memory-shaped bodies: cap one item at ~1 MB and say so, never silently.+_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_NOTE = "\n\n[truncated — the full text lives at the link above]"++_TASK_FIELDS = (+ "name,notes,completed,completed_at,created_at,modified_at,"+ "due_on,due_at,assignee.name,created_by.name,permalink_url"+)+_STORY_FIELDS = "created_at,created_by.name,resource_subtype,text"+++class AsanaAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Asana token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("asana")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise AsanaAdapterError(+ "The Asana connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise AsanaAdapterError(+ "Asana is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise AsanaAdapterError(+ "The Asana 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/json",+ }+++def _retry_wait(response: httpx.Response | None) -> float:+ if response is None:+ return 0.0+ header = str(response.headers.get("Retry-After") or "").strip()+ try:+ wait = float(header)+ except ValueError:+ wait = _DEFAULT_RETRY_WAIT+ return min(max(wait, 0.0), _RETRY_WAIT_CAP)+++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."""+ response: httpx.Response | None = None+ for attempt in range(_MAX_ATTEMPTS):+ if attempt:+ await asyncio.sleep(_retry_wait(response))+ try:+ response = await client.get(url, headers=_headers(token), params=params)+ except httpx.HTTPError as exc:+ raise AsanaAdapterError(+ f"Asana was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code != 429:+ break+ if response is None: # pragma: no cover - loop always runs at least once+ raise AsanaAdapterError("Asana answered nothing for this request.")+ if response.status_code == 401:+ raise AsanaAdapterError(+ "Asana rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 429:+ raise AsanaAdapterError(+ "Asana's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise AsanaAdapterError(+ f"Asana answered HTTP {response.status_code} for this request."+ )+ return response+++async def _paged(+ client: httpx.AsyncClient, url: str, token: str, params: dict[str, Any]+) -> list[dict[str, Any]]:+ """Every row behind one Asana collection URL, following offset pages."""+ rows: list[dict[str, Any]] = []+ offset = ""+ for page in range(_MAX_PAGES):+ page_params: dict[str, Any] = {**params, "limit": _PAGE_SIZE}+ if offset:+ page_params["offset"] = offset+ response = await _get(client, url, token, params=page_params)+ payload = response.json() or {}+ data = payload.get("data")+ if isinstance(data, list):+ rows.extend(row for row in data if isinstance(row, dict))+ next_page = payload.get("next_page")+ offset = str(next_page.get("offset") or "") if isinstance(next_page, dict) else ""+ if not offset:+ return rows+ if page == _MAX_PAGES - 1:+ log.info(+ "Asana adapter: stopping a walk at %d pages; the next sync "+ "resumes from the cursor",+ _MAX_PAGES,+ )+ return rows+++def _since_iso(checkpoint: str | None) -> str:+ """The stored numeric cursor as an ISO instant for ``modified_since``."""+ if not checkpoint:+ return ""+ try:+ ns = int(checkpoint)+ except (TypeError, ValueError):+ return ""+ if ns <= 0:+ return ""+ seconds = ns / 1_000_000_000 - _SINCE_OVERLAP_SECONDS+ if seconds <= 0:+ return ""+ return datetime.fromtimestamp(seconds, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _resume_marker(checkpoint: str | None) -> str:+ """The checkpoint as a backfill resume id (``task:<gid>``), or empty."""+ if checkpoint and checkpoint.startswith("task:"):+ return checkpoint+ return ""+++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 _cap(text: str) -> str:+ if len(text) <= _MAX_BODY_CHARS:+ return text+ return text[:_MAX_BODY_CHARS] + _TRUNCATION_NOTE+++def _comment_lines(stories: list[dict[str, Any]]) -> list[str]:+ """Comment stories as chronological body lines; system activity excluded."""+ comments: list[tuple[str, str]] = []+ for story in stories:+ if not isinstance(story, dict):+ continue+ if str(story.get("resource_subtype") or "") != "comment_added":+ continue+ text = str(story.get("text") or "").strip()+ if not text:+ continue+ author = str((story.get("created_by") or {}).get("name") or "")+ created = str(story.get("created_at") or "")+ prefix = " · ".join(part for part in (created, author) if part)+ comments.append((created, f"[{prefix}] {text}" if prefix else text))+ comments.sort(key=lambda pair: pair[0])+ return [line for _created, line in comments]+++def item_from_task(+ task: dict[str, Any],+ *,+ thread_key: str,+ context: str,+ comments: list[str],+) -> RawItem | None:+ """One Asana task as a ``RawItem``; ``None`` when it is unusable.++ The body is composed rather than copied raw: a bare notes field loses+ which project the task lives in and whether it was ever finished, and both+ are exactly what a later question turns on.+ """+ gid = str(task.get("gid") or "")+ permalink = str(task.get("permalink_url") or "").strip()+ if not gid or not permalink:+ return None++ title = str(task.get("name") or "").strip() or f"task {gid}"+ state = "completed" if task.get("completed") else "open"+ assignee = str((task.get("assignee") or {}).get("name") or "")+ author = str((task.get("created_by") or {}).get("name") or "")+ due = str(task.get("due_at") or task.get("due_on") or "")+ created = str(task.get("created_at") or "")+ modified = str(task.get("modified_at") or "")++ header_parts = [part for part in (context, "task", state) if part]+ if assignee:+ header_parts.append(f"assigned to {assignee}")+ if due:+ header_parts.append(f"due {due}")+ if author:+ header_parts.append(f"created by {author}")+ header = " · ".join(header_parts)++ body_text = str(task.get("notes") or "").strip()+ if comments:+ body_text += ("\n\n" if body_text else "") + "Comments:\n" + "\n".join(comments)++ return RawItem(+ external_id=f"task:{gid}",+ title=title,+ body=_cap(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 modification time rides in metadata for the cursor.+ timestamp_utc=created or modified,+ thread_key=thread_key,+ author_raw=author,+ metadata={+ "mtime_ns": _to_ns(modified or created),+ "state": state,+ "assignee": assignee,+ "due": due,+ "comments": len(comments),+ "updated_at": modified,+ },+ )+++async def asana_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every task the connected Asana account can list.++ ``checkpoint`` doubles as the incremental cursor (see the module+ docstring). ``transport`` is a test seam; production leaves it ``None``.+ """+ token = _token()+ since = _since_iso(checkpoint)+ resume_after = _resume_marker(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ # (created_at, gid, task, thread_key, context) — sorted below, so the+ # stream is deterministic and a backfill resume can pick up mid-walk.+ stubs: list[tuple[str, str, dict[str, Any], str, str]] = []+ seen: set[str] = set()++ def note(task: dict[str, Any], thread_key: str, context: str) -> None:+ gid = str(task.get("gid") or "")+ if not gid or gid in seen:+ return+ seen.add(gid)+ stubs.append(+ (str(task.get("created_at") or ""), gid, task, thread_key, context)+ )++ workspaces = await _paged(client, f"{_API}/workspaces", token, {})+ for workspace in sorted(workspaces, key=lambda ws: str(ws.get("gid") or "")):+ ws_gid = str(workspace.get("gid") or "")+ ws_name = str(workspace.get("name") or "")+ if not ws_gid:+ continue+ projects = await _paged(+ client,+ f"{_API}/workspaces/{ws_gid}/projects",+ token,+ {"opt_fields": "name"},+ )+ for project in sorted(projects, key=lambda p: str(p.get("gid") or "")):+ p_gid = str(project.get("gid") or "")+ p_name = str(project.get("name") or "")+ if not p_gid:+ continue+ params: dict[str, Any] = {"project": p_gid, "opt_fields": _TASK_FIELDS}+ if since:+ params["modified_since"] = since+ for task in await _paged(client, f"{_API}/tasks", token, params):+ note(task, p_gid, p_name)+ # Personal tasks living in no walked project still belong to the+ # memory; the assignee listing is the one other door the API opens.+ params = {"assignee": "me", "workspace": ws_gid, "opt_fields": _TASK_FIELDS}+ if since:+ params["modified_since"] = since+ for task in await _paged(client, f"{_API}/tasks", token, params):+ note(task, ws_gid, ws_name)++ stubs.sort(key=lambda stub: (stub[0], stub[1]))+ start = 0+ if resume_after:+ for index, stub in enumerate(stubs):+ if f"task:{stub[1]}" == resume_after:+ start = index + 1+ break++ for _created, gid, task, thread_key, context in stubs[start:]:+ stories = await _paged(+ client,+ f"{_API}/tasks/{gid}/stories",+ token,+ {"opt_fields": _STORY_FIELDS},+ )+ item = item_from_task(+ task,+ thread_key=thread_key,+ context=context,+ comments=_comment_lines(stories),+ )+ if item is not None:+ yielded += 1+ yield item++ log.info(+ "Asana adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if since else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/clickup.py b/jarvis/ultrawiki/adapters/clickup.pynew file mode 100644index 0000000000..26a7eb3540--- /dev/null+++ b/jarvis/ultrawiki/adapters/clickup.py@@ -0,0 +1,425 @@+"""ClickUp pull adapter — every task the connected token can list.++Scope, honestly stated. The adapter walks every workspace ("team") the+marketplace token reaches through ClickUp's filtered team-task walk, with+``include_closed`` and ``subtasks`` set — so open, closed and subtask rows all+arrive in one paginated stream, no per-list hierarchy crawl. Comments are+fetched per task and folded into the body chronologically, following ClickUp's+own comment pagination to the end (bounded at 1 000 per task, with an explicit+marker when the bound stops early).++What the token structurally cannot yield: tasks living in ARCHIVED lists —+the team-task walk does not return them, and ClickUp offers no team-wide door+to archived containers. Docs, whiteboards and chat are not tasks and are not+imported; file attachments are never downloaded — only comment text survives,+which is what a memory is for. ClickUp's budget is ~100 requests a minute and+comments cost one request per task, so a very large first backfill may hit the+wall mid-walk; the bounded Retry-After handling below stops honestly and the+next sync resumes from the checkpoint.++Cursor convention (the reference adapter's): a numeric checkpoint is the sync+runner's nanosecond cursor and narrows every task listing with+``date_updated_gt`` in epoch milliseconds (minus a five-minute overlap so a+boundary is safe; re-yielded items upsert as ``unchanged``). A ``task:<id>``+checkpoint is the bridge's backfill resume marker: tasks stream+oldest-to-newest in a deterministic order, so the walk resumes strictly after+that id. Any other checkpoint is read as "no cursor" and yields the full set.+Every item carries ``metadata["mtime_ns"]`` so the runner can advance its+cursor.++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 asyncio+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",+ "ClickUpAdapterError",+ "clickup_pull_adapter",+ "item_from_task",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:clickup"++_API = "https://api.clickup.com/api/v2"++#: The team-task walk pages at 100 rows; a short page ends the walk.+_PAGE_SIZE = 100+#: Safety valve per workspace walk; at 100 rows a page this is 20 000 rows.+_MAX_PAGES = 200++#: ClickUp returns the 25 most recent comments per request; older pages follow+#: via ``start``/``start_id``. 40 pages bounds one task at 1 000 comments.+_COMMENT_PAGE = 25+_MAX_COMMENT_PAGES = 40++#: Generous on read: a cold walk 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)++#: Bounded 429 handling: honor Retry-After up to a cap, then give up honestly.+_MAX_ATTEMPTS = 3+_RETRY_WAIT_CAP = 30.0+_DEFAULT_RETRY_WAIT = 2.0++#: Re-ask five minutes before the cursor so a boundary can never skip an item.+_SINCE_OVERLAP_SECONDS = 300++#: Memory-shaped bodies: cap one item at ~1 MB and say so, never silently.+_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_NOTE = "\n\n[truncated — the full text lives at the link above]"++_MORE_COMMENTS_NOTE = "[more comments on ClickUp — open the link to read them]"+++class ClickUpAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace ClickUp token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("clickup")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise ClickUpAdapterError(+ "The ClickUp connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise ClickUpAdapterError(+ "ClickUp is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise ClickUpAdapterError(+ "The ClickUp connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ # ClickUp expects the BARE token in Authorization — no "Bearer" prefix;+ # its OAuth and personal tokens share this convention.+ return {+ "Authorization": token,+ "Accept": "application/json",+ }+++def _retry_wait(response: httpx.Response | None) -> float:+ if response is None:+ return 0.0+ header = str(response.headers.get("Retry-After") or "").strip()+ try:+ wait = float(header)+ except ValueError:+ wait = _DEFAULT_RETRY_WAIT+ return min(max(wait, 0.0), _RETRY_WAIT_CAP)+++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."""+ response: httpx.Response | None = None+ for attempt in range(_MAX_ATTEMPTS):+ if attempt:+ await asyncio.sleep(_retry_wait(response))+ try:+ response = await client.get(url, headers=_headers(token), params=params)+ except httpx.HTTPError as exc:+ raise ClickUpAdapterError(+ f"ClickUp was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code != 429:+ break+ if response is None: # pragma: no cover - loop always runs at least once+ raise ClickUpAdapterError("ClickUp answered nothing for this request.")+ if response.status_code == 401:+ raise ClickUpAdapterError(+ "ClickUp rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 429:+ raise ClickUpAdapterError(+ "ClickUp's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise ClickUpAdapterError(+ f"ClickUp answered HTTP {response.status_code} for this request."+ )+ return response+++def _since_ms(checkpoint: str | None) -> int:+ """The stored numeric cursor as epoch milliseconds for ``date_updated_gt``."""+ if not checkpoint:+ return 0+ try:+ ns = int(checkpoint)+ except (TypeError, ValueError):+ return 0+ if ns <= 0:+ return 0+ ms = ns // 1_000_000 - _SINCE_OVERLAP_SECONDS * 1000+ return ms if ms > 0 else 0+++def _resume_marker(checkpoint: str | None) -> str:+ """The checkpoint as a backfill resume id (``task:<id>``), or empty."""+ if checkpoint and checkpoint.startswith("task:"):+ return checkpoint+ return ""+++def _ms_to_iso(ms: Any) -> str:+ """Epoch milliseconds → ISO-8601 UTC; empty when unparseable."""+ try:+ value = int(ms)+ except (TypeError, ValueError):+ return ""+ if value <= 0:+ return ""+ return datetime.fromtimestamp(value / 1000, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _ms_to_ns(ms: Any) -> int:+ """Epoch milliseconds → nanoseconds since the epoch; 0 when unparseable."""+ try:+ value = int(ms)+ except (TypeError, ValueError):+ return 0+ return value * 1_000_000 if value > 0 else 0+++def _cap(text: str) -> str:+ if len(text) <= _MAX_BODY_CHARS:+ return text+ return text[:_MAX_BODY_CHARS] + _TRUNCATION_NOTE+++async def _comment_lines(+ client: httpx.AsyncClient, token: str, task_id: str+) -> tuple[list[str], bool]:+ """One task's comments as chronological body lines + whether some remain.++ ClickUp serves comments newest-first, 25 a page; the walk follows the+ ``start``/``start_id`` pagination to the end and only stops early at the+ per-task bound, which the caller then declares in the body.+ """+ rows: list[dict[str, Any]] = []+ params: dict[str, Any] | None = None+ more = False+ for page in range(_MAX_COMMENT_PAGES):+ response = await _get(client, f"{_API}/task/{task_id}/comment", token, params=params)+ payload = response.json() or {}+ page_rows = payload.get("comments")+ if not isinstance(page_rows, list) or not page_rows:+ break+ rows.extend(row for row in page_rows if isinstance(row, dict))+ if len(page_rows) < _COMMENT_PAGE:+ break+ oldest = page_rows[-1]+ params = {+ "start": str(oldest.get("date") or ""),+ "start_id": str(oldest.get("id") or ""),+ }+ if page == _MAX_COMMENT_PAGES - 1:+ more = True+ log.info(+ "ClickUp adapter: stopping the comment walk for task %s at %d "+ "pages; the rest stays behind the permalink",+ task_id,+ _MAX_COMMENT_PAGES,+ )+ lines: list[tuple[int, str]] = []+ for row in rows:+ text = str(row.get("comment_text") or "").strip()+ if not text:+ continue+ author = str((row.get("user") or {}).get("username") or "")+ stamp = _ms_to_iso(row.get("date"))+ prefix = " · ".join(part for part in (stamp, author) if part)+ lines.append((_ms_to_ns(row.get("date")), f"[{prefix}] {text}" if prefix else text))+ lines.sort(key=lambda pair: pair[0])+ return [line for _stamp, line in lines], more+++def item_from_task(+ task: dict[str, Any],+ *,+ comments: list[str],+ more_comments: bool = False,+) -> RawItem | None:+ """One ClickUp task as a ``RawItem``; ``None`` when it is unusable.++ The body is composed rather than copied raw: a bare description loses+ which list the task lives in and whether it was ever finished, and both+ are exactly what a later question turns on.+ """+ task_id = str(task.get("id") or "")+ permalink = str(task.get("url") or "").strip()+ if not task_id or not permalink:+ return None++ title = str(task.get("name") or "").strip() or f"task {task_id}"+ status = str((task.get("status") or {}).get("status") or "")+ archived = bool(task.get("archived"))+ assignees = [+ str(row.get("username") or "")+ for row in task.get("assignees") or []+ if isinstance(row, dict) and row.get("username")+ ]+ author = str((task.get("creator") or {}).get("username") or "")+ due = _ms_to_iso(task.get("due_date"))+ created = _ms_to_iso(task.get("date_created"))+ updated = _ms_to_iso(task.get("date_updated"))+ task_list = task.get("list") or {}+ list_id = str(task_list.get("id") or "")+ folder = task.get("folder") or {}+ # ClickUp models folderless lists as a "hidden" folder; naming it would+ # put the API's plumbing word into the record.+ folder_name = "" if folder.get("hidden") else str(folder.get("name") or "")+ context = " / ".join(part for part in (folder_name, str(task_list.get("name") or "")) if part)++ header_parts = [part for part in (context, "task", status) if part]+ if archived:+ header_parts.append("archived")+ if assignees:+ header_parts.append("assigned to " + ", ".join(assignees))+ if due:+ header_parts.append(f"due {due}")+ if author:+ header_parts.append(f"created by {author}")+ header = " · ".join(header_parts)++ body_text = str(task.get("description") or task.get("text_content") or "").strip()+ if comments:+ body_text += ("\n\n" if body_text else "") + "Comments:\n" + "\n".join(comments)+ if more_comments:+ body_text += ("\n\n" if body_text else "") + _MORE_COMMENTS_NOTE++ return RawItem(+ external_id=f"task:{task_id}",+ title=title,+ body=_cap(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 modification time rides in metadata for the cursor.+ timestamp_utc=created or updated,+ thread_key=list_id,+ author_raw=author,+ metadata={+ "mtime_ns": _ms_to_ns(task.get("date_updated") or task.get("date_created")),+ "state": status,+ "archived": archived,+ "assignees": assignees,+ "due": due,+ "comments": len(comments),+ "updated_at": updated,+ },+ )+++async def clickup_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every task the connected ClickUp token can list.++ ``checkpoint`` doubles as the incremental cursor (see the module+ docstring). ``transport`` is a test seam; production leaves it ``None``.+ """+ token = _token()+ since_ms = _since_ms(checkpoint)+ resume_after = _resume_marker(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ response = await _get(client, f"{_API}/team", token)+ teams = (response.json() or {}).get("teams")+ rows: list[dict[str, Any]] = []+ for team in sorted(+ teams if isinstance(teams, list) else [],+ key=lambda row: str((row or {}).get("id") or ""),+ ):+ team_id = str((team or {}).get("id") or "") if isinstance(team, dict) else ""+ if not team_id:+ continue+ for page in range(_MAX_PAGES):+ params: dict[str, Any] = {+ "page": page,+ "order_by": "created",+ "reverse": "false",+ "subtasks": "true",+ "include_closed": "true",+ }+ if since_ms:+ params["date_updated_gt"] = since_ms+ response = await _get(client, f"{_API}/team/{team_id}/task", token, params=params)+ payload = response.json() or {}+ page_rows = payload.get("tasks")+ if not isinstance(page_rows, list) or not page_rows:+ break+ rows.extend(row for row in page_rows if isinstance(row, dict))+ if len(page_rows) < _PAGE_SIZE:+ break+ if page == _MAX_PAGES - 1:+ log.info(+ "ClickUp adapter: stopping a walk at %d pages; the "+ "next sync resumes from the cursor",+ _MAX_PAGES,+ )++ # Deterministic oldest-to-newest order, so the bridge's backfill+ # checkpoint (last flushed external_id) resumes strictly after it.+ seen: set[str] = set()+ ordered: list[dict[str, Any]] = []+ for row in sorted(+ rows,+ key=lambda r: (_ms_to_ns(r.get("date_created")), str(r.get("id") or "")),+ ):+ row_id = str(row.get("id") or "")+ if not row_id or row_id in seen:+ continue+ seen.add(row_id)+ ordered.append(row)++ start = 0+ if resume_after:+ for index, row in enumerate(ordered):+ if f"task:{row.get('id')}" == resume_after:+ start = index + 1+ break++ for row in ordered[start:]:+ comments, more = await _comment_lines(client, token, str(row.get("id") or ""))+ item = item_from_task(row, comments=comments, more_comments=more)+ if item is not None:+ yielded += 1+ yield item++ log.info(+ "ClickUp adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if since_ms else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/discord.py b/jarvis/ultrawiki/adapters/discord.pynew file mode 100644index 0000000000..5808edbb68--- /dev/null+++ b/jarvis/ultrawiki/adapters/discord.py@@ -0,0 +1,551 @@+"""Discord pull adapter — every conversation the connected bot can read.++Scope, stated honestly: a Discord BOT token reaches exactly the servers the+bot was invited to, and inside them exactly the text and announcement+channels it can view and whose history it may read. Nothing else exists for+it: direct messages are structurally unreachable (the API exposes no DM list+to a bot), and channels without the View Channel / Read Message History+permissions are skipped quietly rather than failing the whole sync. Thread+and forum posts are not walked yet — a tracked gap, not a silent one.+Attachments are recorded by filename only; binaries are never downloaded.++Within that boundary the adapter takes EVERYTHING: each readable channel's+full message history, paginated backwards with ``before=<id>`` until the+beginning, then emitted oldest-to-newest as one :class:`RawItem` per+channel-day — a day of one channel is the natural memory unit of a chat, and+per-message rows would drown the store. Bodies are capped near 1 MB with an+explicit truncation marker.++Determinism and resume: emission order is servers ascending by id, channels+ascending by id, days ascending — so the bridge's backfill checkpoint (the+last emitted ``external_id``) lets a resumed run skip strictly past what was+already imported. A numeric checkpoint is read as the sync runner's+``mtime_ns`` cursor (the convention the file walkers and the GitHub adapter+share): it is floored to the start of its UTC day, converted to a snowflake,+and passed as ``after=`` — re-asking from the day boundary is what keeps+day chunks complete, and re-yielded chunks upsert as ``unchanged``.++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 asyncio+import logging+from collections.abc import AsyncIterator+from datetime import UTC, datetime, timedelta+from typing import Any++import httpx++from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "DiscordAdapterError",+ "discord_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:discord"++_API = "https://discord.com/api/v10"++#: Milliseconds of the Discord epoch (2015-01-01T00:00:00Z) — snowflake ids+#: encode their creation time relative to this, which is what lets a time+#: cursor become an ``after=<id>`` parameter without any extra request.+_DISCORD_EPOCH_MS = 1_420_070_400_000++#: API maxima: 100 messages per history page, 200 guilds per listing page.+_PAGE_LIMIT = 100+_GUILD_PAGE_LIMIT = 200++#: Channel types that hold readable prose: 0 = GUILD_TEXT, 5 = ANNOUNCEMENT.+_TEXT_CHANNEL_TYPES = frozenset({0, 5})++#: One item's body stays under roughly 1 MB; beyond it the chunk is cut with+#: an explicit marker rather than silently dropped or shipped oversized.+_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_MARKER = "\n\n[truncated near 1 MB — the rest of this day stays on Discord]"++#: Bounded politeness for 429s: retry a few times with the server's own+#: Retry-After, each wait capped, then surface an honest error. The backfill+#: checkpoint makes stopping free; hanging on an unbounded sleep is not.+_RETRY_MAX = 3+_RETRY_WAIT_CAP_S = 15.0++#: Generous on read: a full first backfill is not instant, but no single+#: request may hang a sync forever.+_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)+++class DiscordAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Discord bot token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("discord")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise DiscordAdapterError(+ "The Discord connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise DiscordAdapterError(+ "Discord is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise DiscordAdapterError(+ "The Discord connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bot {token}"}+++def _retry_after_seconds(response: httpx.Response) -> float:+ """The server's requested wait, bounded to a sane ceiling."""+ value: float | None = None+ header = response.headers.get("retry-after", "")+ if header:+ try:+ value = float(header)+ except ValueError:+ value = None+ if value is None:+ try:+ value = float((response.json() or {}).get("retry_after"))+ except Exception: # noqa: BLE001 — a non-JSON 429 body means "use the default"+ value = None+ if value is None:+ value = 1.0+ return min(max(value, 0.0), _RETRY_WAIT_CAP_S)+++async def _get(+ client: httpx.AsyncClient,+ url: str,+ token: str,+ params: dict[str, Any] | None = None,+ *,+ skip_forbidden: bool = False,+) -> httpx.Response | None:+ """One GET with bounded 429 retries and user-actionable failures.++ ``skip_forbidden=True`` turns a 403 into ``None`` — the caller treats it+ as "this channel is not for the bot" instead of failing the sync.+ """+ response: httpx.Response | None = None+ for attempt in range(_RETRY_MAX + 1):+ try:+ response = await client.get(url, headers=_headers(token), params=params)+ except httpx.HTTPError as exc:+ raise DiscordAdapterError(+ f"Discord was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429 and attempt < _RETRY_MAX:+ await asyncio.sleep(_retry_after_seconds(response))+ continue+ break+ assert response is not None # the loop always runs at least once+ if response.status_code == 401:+ raise DiscordAdapterError(+ "Discord rejected the bot token. Reconnect it in the Plugins store."+ )+ if response.status_code == 403 and skip_forbidden:+ return None+ if response.status_code == 429:+ raise DiscordAdapterError(+ "Discord's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise DiscordAdapterError(+ f"Discord answered HTTP {response.status_code} for this request."+ )+ return response+++# -- snowflake / time helpers -------------------------------------------------+++def _snowflake_int(raw: str) -> int:+ try:+ return int(raw)+ except (TypeError, ValueError):+ return 0+++def _ns_to_snowflake(ns: int) -> str:+ """A synthetic message id for a moment in time — ``after=`` understands it."""+ ms = ns // 1_000_000+ if ms <= _DISCORD_EPOCH_MS:+ return "0"+ return str((ms - _DISCORD_EPOCH_MS) << 22)+++def _day_start_snowflake(ns: int) -> str:+ """The snowflake at 00:00 UTC of the cursor's day.++ Re-asking from the day boundary (not the cursor itself) is what keeps a+ day chunk COMPLETE: an incremental run that started mid-day would+ otherwise upsert a partial day over the full one already stored.+ """+ moment = datetime.fromtimestamp(ns / 1_000_000_000, tz=UTC)+ midnight = datetime(moment.year, moment.month, moment.day, tzinfo=UTC)+ return _ns_to_snowflake(int(midnight.timestamp() * 1_000_000_000))+++def _next_day_snowflake(day: str) -> str | None:+ """The snowflake at 00:00 UTC of the day AFTER ``day``; ``None`` if unparseable."""+ try:+ start = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=UTC)+ except ValueError:+ return None+ boundary = start + timedelta(days=1)+ return _ns_to_snowflake(int(boundary.timestamp() * 1_000_000_000))+++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 _iso_z(iso: str) -> str:+ """Discord's offset timestamp normalized to a clean ``...Z`` form."""+ ns = _to_ns(iso)+ if ns <= 0:+ return iso+ return datetime.fromtimestamp(ns / 1_000_000_000, tz=UTC).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )+++def _day_of(iso: str) -> str:+ ns = _to_ns(iso)+ if ns <= 0:+ return ""+ return datetime.fromtimestamp(ns / 1_000_000_000, tz=UTC).strftime("%Y-%m-%d")+++def _hhmm(iso: str) -> str:+ ns = _to_ns(iso)+ if ns <= 0:+ return ""+ return datetime.fromtimestamp(ns / 1_000_000_000, tz=UTC).strftime("%H:%M")+++# -- checkpoint ---------------------------------------------------------------+++def _parse_checkpoint(+ checkpoint: str | None,+) -> tuple[int | None, tuple[int, int, str] | None]:+ """``(cursor_ns, resume_key)`` — at most one of the two is set.++ A numeric checkpoint is the runner's ``mtime_ns`` cursor (incremental).+ ``discord:<guild>:<channel>:<day>`` is one of our own external_ids — the+ bridge hands back the last emitted one when resuming a backfill mid-walk.+ Anything else degrades to a full backfill; upserts make re-reads free.+ """+ if not checkpoint:+ return None, None+ try:+ ns = int(checkpoint)+ except ValueError:+ ns = 0+ if ns > 0:+ return ns, None+ parts = checkpoint.split(":")+ if (+ len(parts) == 4+ and parts[0] == "discord"+ and parts[1].isdigit()+ and parts[2].isdigit()+ ):+ return None, (int(parts[1]), int(parts[2]), parts[3])+ return None, None+++# -- API walks ----------------------------------------------------------------+++async def _guilds(client: httpx.AsyncClient, token: str) -> list[dict[str, Any]]:+ """Every server the bot is in, ascending by id (deterministic order)."""+ collected: list[dict[str, Any]] = []+ after = ""+ while True:+ params: dict[str, Any] = {"limit": _GUILD_PAGE_LIMIT}+ if after:+ params["after"] = after+ response = await _get(client, f"{_API}/users/@me/guilds", token, params)+ assert response is not None+ rows = response.json() or []+ if not isinstance(rows, list) or not rows:+ break+ valid = [row for row in rows if isinstance(row, dict) and row.get("id")]+ collected.extend(valid)+ if len(rows) < _GUILD_PAGE_LIMIT or not valid:+ break+ after = str(max(_snowflake_int(str(row["id"])) for row in valid))+ collected.sort(key=lambda row: _snowflake_int(str(row.get("id"))))+ return collected+++async def _text_channels(+ client: httpx.AsyncClient, token: str, guild_id: str+) -> list[dict[str, Any]]:+ """The guild's readable text/announcement channels, ascending by id."""+ response = await _get(+ client, f"{_API}/guilds/{guild_id}/channels", token, skip_forbidden=True+ )+ if response is None:+ log.debug("Discord adapter: no channel-list access for guild %s", guild_id)+ return []+ rows = response.json() or []+ if not isinstance(rows, list):+ return []+ channels = [+ row+ for row in rows+ if isinstance(row, dict)+ and row.get("id")+ and row.get("type") in _TEXT_CHANNEL_TYPES+ ]+ channels.sort(key=lambda row: _snowflake_int(str(row.get("id"))))+ return channels+++async def _channel_messages(+ client: httpx.AsyncClient,+ token: str,+ channel_id: str,+ *,+ after: str | None = None,+) -> list[dict[str, Any]] | None:+ """All reachable messages of one channel, ascending by id.++ ``None`` means the bot may not read this channel at all (403 on the first+ page); a permission loss mid-walk keeps what was already collected. With+ ``after`` set the walk moves forward from that id; otherwise the full+ history is paginated backwards with ``before`` and sorted ascending at+ the end. Each page is sorted locally too — order is OUR contract, not an+ assumption about the API's response ordering.+ """+ url = f"{_API}/channels/{channel_id}/messages"+ collected: list[dict[str, Any]] = []+ first_page = True+ cursor = after+ while True:+ params: dict[str, Any] = {"limit": _PAGE_LIMIT}+ if after is not None:+ params["after"] = cursor+ elif cursor:+ params["before"] = cursor+ response = await _get(client, url, token, params, skip_forbidden=True)+ if response is None:+ return None if first_page else collected+ first_page = False+ rows = response.json() or []+ if not isinstance(rows, list) or not rows:+ break+ batch = [row for row in rows if isinstance(row, dict) and row.get("id")]+ batch.sort(key=lambda row: _snowflake_int(str(row["id"])))+ collected.extend(batch)+ if len(rows) < _PAGE_LIMIT or not batch:+ break+ cursor = str(batch[-1]["id"]) if after is not None else str(batch[0]["id"])+ collected.sort(key=lambda row: _snowflake_int(str(row["id"])))+ return collected+++# -- RawItem mapping ----------------------------------------------------------+++def _author_of(message: dict[str, Any]) -> str:+ author = message.get("author") or {}+ if not isinstance(author, dict):+ return "unknown"+ return str(author.get("global_name") or author.get("username") or "unknown")+++def _message_text(message: dict[str, Any]) -> str:+ """The message's prose, plus honest placeholders for what is NOT pulled."""+ parts: list[str] = []+ content = str(message.get("content") or "").strip()+ if content:+ parts.append(content)+ for embed in message.get("embeds") or []:+ if not isinstance(embed, dict):+ continue+ for key in ("title", "description"):+ value = str(embed.get(key) or "").strip()+ if value:+ parts.append(value)+ for attachment in message.get("attachments") or []:+ if not isinstance(attachment, dict):+ continue+ name = str(attachment.get("filename") or "").strip()+ if name:+ # By name only — binaries never enter the knowledge base.+ parts.append(f"[attachment: {name}]")+ return " ".join(parts)+++def _chunk_item(+ guild: dict[str, Any],+ channel: dict[str, Any],+ day: str,+ messages: list[dict[str, Any]],+) -> RawItem | None:+ """One channel-day as a ``RawItem``; ``None`` when the day holds no prose."""+ guild_id = str(guild.get("id") or "")+ channel_id = str(channel.get("id") or "")+ guild_name = str(guild.get("name") or "").strip() or f"server {guild_id}"+ channel_name = str(channel.get("name") or "").strip() or f"channel {channel_id}"++ lines: list[str] = []+ used: list[dict[str, Any]] = []+ total = 0+ truncated = False+ for message in messages:+ text = _message_text(message)+ if not text:+ continue+ stamp = _hhmm(str(message.get("timestamp") or ""))+ prefix = f"[{stamp}] " if stamp else ""+ line = f"{prefix}{_author_of(message)}: {text}"+ if total + len(line) > _MAX_BODY_CHARS:+ truncated = True+ break+ lines.append(line)+ used.append(message)+ total += len(line) + 1+ if not used:+ return None++ first, last = used[0], used[-1]+ header = f"{guild_name} · #{channel_name} · {day} · {len(used)} message(s)"+ body = f"{header}\n\n" + "\n".join(lines)+ if truncated:+ body += _TRUNCATION_MARKER+ return RawItem(+ external_id=f"discord:{guild_id}:{channel_id}:{day}",+ title=f"#{channel_name} — {day}",+ body=body,+ permalink=(+ f"https://discord.com/channels/{guild_id}/{channel_id}/{first.get('id')}"+ ),+ timestamp_utc=_iso_z(str(first.get("timestamp") or "")),+ thread_key=f"{guild_id}/{channel_id}",+ author_raw="",+ metadata={+ # Ids stay strings: snowflakes overflow JSON-consumer precision.+ "mtime_ns": _to_ns(str(last.get("timestamp") or "")),+ "guild_id": guild_id,+ "channel_id": channel_id,+ "guild_name": guild_name,+ "channel_name": channel_name,+ "day": day,+ "message_count": len(used),+ "last_message_id": str(last.get("id") or ""),+ "truncated": truncated,+ },+ )+++def _day_items(+ guild: dict[str, Any],+ channel: dict[str, Any],+ messages: list[dict[str, Any]],+) -> list[RawItem]:+ groups: dict[str, list[dict[str, Any]]] = {}+ for message in messages:+ day = _day_of(str(message.get("timestamp") or ""))+ if day:+ groups.setdefault(day, []).append(message)+ items = []+ for day in sorted(groups):+ item = _chunk_item(guild, channel, day, groups[day])+ if item is not None:+ items.append(item)+ return items+++# -- the adapter --------------------------------------------------------------+++async def discord_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every readable channel's history as channel-day chunks.++ ``checkpoint`` is either the runner's numeric ``mtime_ns`` cursor+ (incremental: only messages from that day forward) or the last emitted+ ``external_id`` (backfill resume: continue strictly after it). ``transport``+ is a test seam; production leaves it ``None``.+ """+ token = _token()+ cursor_ns, resume = _parse_checkpoint(checkpoint)+ after_all = _day_start_snowflake(cursor_ns) if cursor_ns else None+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ for guild in await _guilds(client, token):+ guild_id = str(guild.get("id") or "")+ guild_int = _snowflake_int(guild_id)+ if resume and guild_int < resume[0]:+ continue+ for channel in await _text_channels(client, token, guild_id):+ channel_id = str(channel.get("id") or "")+ channel_int = _snowflake_int(channel_id)+ after = after_all+ if resume and guild_int == resume[0]:+ if channel_int < resume[1]:+ continue+ if channel_int == resume[1]:+ # The checkpoint names a finished day of THIS channel:+ # continue strictly after it, never re-walk history.+ after = _next_day_snowflake(resume[2]) or after+ messages = await _channel_messages(+ client, token, channel_id, after=after+ )+ if messages is None:+ log.debug(+ "Discord adapter: skipping unreadable channel %s in guild %s",+ channel_id,+ guild_id,+ )+ continue+ for item in _day_items(guild, channel, messages):+ yielded += 1+ yield item++ log.info(+ "Discord adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if cursor_ns else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/dropbox.py b/jarvis/ultrawiki/adapters/dropbox.pynew file mode 100644index 0000000000..5ec5d7a3bb--- /dev/null+++ b/jarvis/ultrawiki/adapters/dropbox.py@@ -0,0 +1,437 @@+"""Dropbox pull adapter — the text files in the connected Dropbox.++Of everything a Dropbox holds, this pulls the part that belongs in a *memory*:+the text-like files — notes, documents, exports, configs — matched by the same+extension-allowlist philosophy the local-folder connector uses (a curated+default set, overridable per source via ``config["extensions"]``). Binaries+are skipped honestly, by extension, before a single byte is downloaded: this+adapter ships no OCR and no PDF/Office extraction, and pretending a JPEG is a+memory would only pollute search. Dropbox Paper docs and other entries the API+marks non-downloadable are excluded by the listing itself.++Scope, stated plainly:++* **Everything the token can list is walked** — ``files/list_folder`` with+ ``recursive=true`` plus ``list_folder/continue`` cursor paging, so team+ folders and deep trees are all reached. Only the extension allowlist and the+ size caps narrow what is *imported*.+* **Size caps:** files whose listed size exceeds 2 MiB are skipped with a log+ line (the local-folder connector's limit); a downloaded body is cut at 1 MiB+ with a visible truncation marker. A knowledge base wants the text, not a+ bulk mirror.+* **Incremental is client-side.** Dropbox's ``list_folder`` has no+ modified-since filter, and its own delta cursor (``list_folder/continue``+ across runs) is an opaque string that cannot ride the sync runner's NUMERIC+ cursor convention — so that cursor is used for in-run paging only. Instead+ every item carries ``metadata["mtime_ns"]`` (``server_modified``), the key+ the runner already advances; a numeric checkpoint filters files by that time+ BEFORE downloading, which is where the cost lives. The re-listing itself is+ cheap, and unchanged items upsert as ``unchanged``.++The walk is deterministic: entries are sorted by ``path_lower`` — which IS the+``external_id`` — so the bridge's backfill checkpoint (the last persisted id)+resumes strictly after it instead of restarting.++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. A+token the REST API rejects (for instance one scoped away from it) surfaces as+the honest reconnect error on the source card.+"""++from __future__ import annotations++import asyncio+import json+import logging+from collections.abc import AsyncIterator+from datetime import UTC, datetime+from pathlib import PurePosixPath+from typing import Any+from urllib.parse import quote++import httpx++from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "TEXT_EXTENSIONS",+ "DropboxAdapterError",+ "dropbox_pull_adapter",+ "item_from_entry",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:dropbox"++_API = "https://api.dropboxapi.com"+_CONTENT = "https://content.dropboxapi.com"++#: Dropbox's maximum page size for ``files/list_folder``.+_PAGE_LIMIT = 2000+#: Hard bound on ``list_folder/continue`` hops — 5 000 × 2 000 entries is far+#: beyond any personal account; the bound only exists so a misbehaving server+#: can never loop this walk forever.+_MAX_LIST_PAGES = 5000++#: Generous on read: downloads stream real file bodies, not JSON envelopes.+_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)++#: Listed size above this → the file is skipped before download (the+#: local-folder connector's limit, same philosophy).+_MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024+#: A downloaded body is cut here, with a visible marker.+_MAX_BODY_BYTES = 1024 * 1024+_TRUNCATION_MARKER = "\n\n[truncated at 1 MiB — open the link for the full file]"++#: Bounded 429 handling: worst case a few short waits, never an unbounded stall.+_MAX_RETRIES = 3+_MAX_RETRY_WAIT = 30.0++#: The extension allowlist that decides "text-like". Same philosophy as the+#: local-folder connector's DEFAULT_EXTENSIONS, widened to the document-shaped+#: formats a Dropbox typically holds. Override per source with+#: ``config["extensions"]``.+TEXT_EXTENSIONS: tuple[str, ...] = (+ ".md",+ ".markdown",+ ".txt",+ ".text",+ ".rst",+ ".org",+ ".csv",+ ".tsv",+ ".json",+ ".yaml",+ ".yml",+ ".toml",+ ".ini",+ ".cfg",+ ".log",+ ".tex",+ ".html",+ ".htm",+ ".xml",+)+++class DropboxAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Dropbox token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("dropbox")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise DropboxAdapterError(+ "The Dropbox connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise DropboxAdapterError(+ "Dropbox is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise DropboxAdapterError(+ "The Dropbox connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _retry_wait(response: httpx.Response, attempt: int) -> float:+ """How long a 429 asks us to wait — honored, but never beyond the bound."""+ raw = response.headers.get("retry-after", "")+ try:+ wait = float(raw)+ except ValueError:+ wait = float(2**attempt)+ return min(max(wait, 0.0), _MAX_RETRY_WAIT)+++async def _request(+ client: httpx.AsyncClient,+ url: str,+ token: str,+ *,+ json_body: dict[str, Any] | None = None,+ api_arg: dict[str, Any] | None = None,+) -> httpx.Response:+ """One POST with bounded 429 retries; network failures become sentences.++ ``json_body`` is the RPC-endpoint shape (JSON body); ``api_arg`` is the+ content-endpoint shape (``Dropbox-API-Arg`` header, empty body). The two+ are never combined.+ """+ headers = {"Authorization": f"Bearer {token}"}+ if api_arg is not None:+ headers["Dropbox-API-Arg"] = json.dumps(api_arg)+ for attempt in range(_MAX_RETRIES + 1):+ try:+ if json_body is not None:+ response = await client.post(url, headers=headers, json=json_body)+ else:+ response = await client.post(url, headers=headers)+ except httpx.HTTPError as exc:+ raise DropboxAdapterError(+ f"Dropbox was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429 and attempt < _MAX_RETRIES:+ await asyncio.sleep(_retry_wait(response, attempt))+ continue+ return response+ raise DropboxAdapterError( # pragma: no cover — the loop always returns+ "Dropbox kept rate-limiting this sync."+ )+++def _raise_for_status(response: httpx.Response) -> None:+ """Map a failed response to a sentence a user can act on."""+ if response.status_code == 401:+ raise DropboxAdapterError(+ "Dropbox rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 429:+ raise DropboxAdapterError(+ "Dropbox's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise DropboxAdapterError(+ f"Dropbox answered HTTP {response.status_code} for this request."+ )+++async def _api_post(+ client: httpx.AsyncClient, url: str, token: str, json_body: dict[str, Any]+) -> httpx.Response:+ response = await _request(client, url, token, json_body=json_body)+ _raise_for_status(response)+ return response+++def _extensions(ctx: ConnectorContext) -> tuple[str, ...]:+ """The allowlist for this source — config override or the curated default.++ Same normalization the local-folder connector applies: entries may omit+ the leading dot, empties are dropped, an empty override falls back.+ """+ raw = ctx.config.get("extensions")+ if not raw:+ return TEXT_EXTENSIONS+ normalized: list[str] = []+ for entry in raw:+ text = str(entry).strip().lower()+ if not text:+ continue+ normalized.append(text if text.startswith(".") else f".{text}")+ return tuple(normalized) or TEXT_EXTENSIONS+++async def _list_text_files(+ client: httpx.AsyncClient, token: str, extensions: tuple[str, ...]+) -> list[dict[str, Any]]:+ """Every text-like file entry the token can list, via cursor paging."""+ entries: list[dict[str, Any]] = []+ response = await _api_post(+ client,+ f"{_API}/2/files/list_folder",+ token,+ {+ "path": "",+ "recursive": True,+ "include_deleted": False,+ "include_non_downloadable_files": False,+ "limit": _PAGE_LIMIT,+ },+ )+ for _page in range(_MAX_LIST_PAGES):+ payload = response.json() or {}+ rows = payload.get("entries")+ for entry in rows if isinstance(rows, list) else []:+ if not isinstance(entry, dict) or entry.get(".tag") != "file":+ continue+ path_lower = str(entry.get("path_lower") or "")+ if not path_lower:+ continue+ if PurePosixPath(path_lower).suffix not in extensions:+ continue+ if entry.get("is_downloadable") is False:+ # Paper docs and friends: files/download cannot fetch them.+ log.debug("dropbox adapter: %s is not downloadable; skipping", path_lower)+ continue+ entries.append(entry)+ if not payload.get("has_more"):+ break+ response = await _api_post(+ client,+ f"{_API}/2/files/list_folder/continue",+ token,+ {"cursor": str(payload.get("cursor") or "")},+ )+ else: # pragma: no cover — needs 5 000 real pages+ log.warning(+ "dropbox adapter: stopped listing after %d pages; the next sync "+ "resumes from the checkpoint",+ _MAX_LIST_PAGES,+ )+ return entries+++async def _download_text(+ client: httpx.AsyncClient, token: str, path_lower: str+) -> str | None:+ """One file body as capped text; ``None`` skips the file, auth aborts.++ A single vanished or unreadable file (deleted between list and download,+ a 409 path error) must not sink the other thousand — but a rejected token+ or an exhausted rate budget is not a per-file condition and raises.+ """+ response = await _request(+ client, f"{_CONTENT}/2/files/download", token, api_arg={"path": path_lower}+ )+ if response.status_code in (401, 429):+ _raise_for_status(response)+ if response.status_code >= 400:+ log.info(+ "dropbox adapter: skipping %s (download answered HTTP %d)",+ path_lower,+ response.status_code,+ )+ return None+ raw = response.content+ text = raw[:_MAX_BODY_BYTES].decode("utf-8", errors="replace")+ if len(raw) > _MAX_BODY_BYTES:+ text += _TRUNCATION_MARKER+ return text+++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 _split_checkpoint(checkpoint: str | None) -> tuple[str | None, int]:+ """Read the checkpoint as (resume-after path, mtime-ns cursor).++ The bridge hands over ONE string that means two different things: during a+ backfill it is the last persisted ``external_id`` — here always a+ ``path_lower``, so it starts with ``/`` — and once the bridge runs+ incrementally it is the runner's numeric ``mtime_ns`` cursor. Anything+ else (or nothing) reads as a full walk, which idempotent upserts make safe.+ """+ if not checkpoint:+ return None, 0+ text = str(checkpoint).strip()+ if text.startswith("/"):+ return text, 0+ try:+ return None, max(int(text), 0)+ except ValueError:+ return None, 0+++def _preview_url(path_display: str) -> str:+ """The Dropbox web preview link for one file path."""+ parts = [part for part in path_display.split("/") if part]+ if not parts:+ return "https://www.dropbox.com/home"+ folder = "/".join(quote(part) for part in parts[:-1])+ base = f"https://www.dropbox.com/home/{folder}" if folder else "https://www.dropbox.com/home"+ return f"{base}?preview={quote(parts[-1])}"+++def item_from_entry(entry: dict[str, Any], body: str) -> RawItem | None:+ """One listed file plus its downloaded body as a ``RawItem``."""+ path_lower = str(entry.get("path_lower") or "")+ if not path_lower:+ return None+ path_display = str(entry.get("path_display") or path_lower)+ modified = str(entry.get("server_modified") or entry.get("client_modified") or "")+ name = PurePosixPath(path_display)+ parent = path_lower.rsplit("/", 1)[0] or "/"+ return RawItem(+ external_id=path_lower,+ title=name.stem or name.name,+ body=body,+ permalink=_preview_url(path_display),+ timestamp_utc=modified,+ # The folder is the natural conversation: files that live together+ # tend to belong together.+ thread_key=parent,+ metadata={+ "mtime_ns": _to_ns(modified),+ "size_bytes": int(entry.get("size") or 0),+ "path_display": path_display,+ "rev": str(entry.get("rev") or ""),+ },+ )+++async def dropbox_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every text-like file the connected Dropbox token can reach.++ ``checkpoint`` doubles as resume point and incremental cursor (see+ :func:`_split_checkpoint`). ``transport`` is a test seam; production+ leaves it ``None``.+ """+ token = _token()+ resume_after, min_mtime_ns = _split_checkpoint(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ entries = await _list_text_files(client, token, _extensions(ctx))+ # Sorted by external_id: the ONLY order under which "resume strictly+ # after the checkpointed id" is correct (the local-folder precedent).+ entries.sort(key=lambda row: str(row.get("path_lower") or ""))+ for entry in entries:+ path_lower = str(entry.get("path_lower") or "")+ if resume_after and path_lower <= resume_after:+ continue+ if min_mtime_ns:+ modified = str(+ entry.get("server_modified") or entry.get("client_modified") or ""+ )+ if _to_ns(modified) <= min_mtime_ns:+ continue # unchanged since the cursor — never downloaded+ size = int(entry.get("size") or 0)+ if size > _MAX_DOWNLOAD_BYTES:+ log.info(+ "dropbox adapter: skipping %s (%d bytes exceeds the %d-byte limit)",+ path_lower,+ size,+ _MAX_DOWNLOAD_BYTES,+ )+ continue+ body = await _download_text(client, token, path_lower)+ if body is None:+ continue+ item = item_from_entry(entry, body)+ if item is not None:+ yielded += 1+ yield item++ log.info(+ "Dropbox adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if min_mtime_ns else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/google_calendar.py b/jarvis/ultrawiki/adapters/google_calendar.pynew file mode 100644index 0000000000..c1782f73af--- /dev/null+++ b/jarvis/ultrawiki/adapters/google_calendar.py@@ -0,0 +1,287 @@+"""Google Calendar pull adapter — every event on every calendar of the account.++Of everything Calendar is, this pulls what belongs in a *memory*: each event's+own text — what it was called, when it happened, where, who organised it, who+was invited, and what the description said. The walk covers EVERY calendar the+account subscribes to (``calendarList``), in a deterministic order (sorted by+calendar id), and each calendar's events oldest to newest+(``singleEvents=true`` + ``orderBy=startTime``), so an interrupted backfill+resumes at the calendar it stopped in.++Scope honesty — what the token allows vs. what is imported:++- **Recurring events are imported as their expanded instances**, which is the+ only form the API can order by start time. Expansion needs a time ceiling:+ the walk covers everything from 1970 up to TWO YEARS ahead of the sync.+ Instances of a never-ending series beyond that horizon are structurally out+ of reach for a bounded import; the horizon rolls forward with every sync,+ so they arrive as time does.+- **Cancelled events are skipped** — a tombstone carries no text to remember.+- **Attachments and conference links are not imported**; the event's+ ``htmlLink`` permalink leads to them.+- **Incremental rides the ``updated`` cursor** via ``metadata["mtime_ns"]``+ (the key the sync runner already advances): a numeric checkpoint becomes+ ``updatedMin`` one day earlier, so a boundary can never skip an event.+ The API's native incremental channel is ``syncToken``, which is finer but+ is an opaque per-calendar token the bridge's single numeric cursor cannot+ hold — the documented fallback is exactly this ``updatedMin`` narrowing,+ and a full backfill remains cheap because event pages carry complete+ event data (no per-item fetch).++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, timedelta+from typing import Any+from urllib.parse import quote++import httpx++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "GoogleAdapterError",+ "google_calendar_pull_adapter",+ "item_from_event",+]++#: Re-exported so callers can catch the family's error type from this module.+GoogleAdapterError = g.GoogleAdapterError++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:google_calendar"++_PLUGIN_ID = "google_calendar"+_PRODUCT = "Google Calendar"+_API = "https://www.googleapis.com/calendar/v3"++#: Everything since the epoch — "far past" without inventing a start of time.+_TIME_MIN = "1970-01-01T00:00:00Z"++#: Expansion ceiling for recurring events (see the module docstring).+_LOOKAHEAD_DAYS = 730++#: The API's own page maxima.+_CALENDAR_PAGE_SIZE = 250+_EVENT_PAGE_SIZE = 2500++#: A large meeting can carry hundreds of attendees; the record names this+#: many and counts the rest — a memory needs "who", not a mailing list dump.+_ATTENDEE_DISPLAY_CAP = 25+++def _when(edge: Any) -> str:+ """An event boundary as ISO-8601 UTC-compatible text; empty when absent.++ Timed events carry ``dateTime`` (with offset — kept as-is, the contract+ allows offsets); all-day events carry only ``date`` and are normalised to+ midnight UTC so the timestamp stays machine-comparable.+ """+ if not isinstance(edge, dict):+ return ""+ stamp = str(edge.get("dateTime") or "").strip()+ if stamp:+ return stamp+ day = str(edge.get("date") or "").strip()+ return f"{day}T00:00:00Z" if day else ""+++def _attendee_line(event: dict[str, Any]) -> str:+ attendees = [row for row in event.get("attendees") or [] if isinstance(row, dict)]+ if not attendees:+ return ""+ names = [+ str(row.get("displayName") or row.get("email") or "").strip()+ for row in attendees+ ]+ names = [name for name in names if name]+ if not names:+ return ""+ shown = names[:_ATTENDEE_DISPLAY_CAP]+ rest = len(names) - len(shown)+ line = f"Attendees ({len(names)}): {', '.join(shown)}"+ if rest > 0:+ line += f" (+{rest} more)"+ return line+++def item_from_event(+ calendar_id: str, calendar_label: str, event: dict[str, Any]+) -> RawItem | None:+ """One event as a ``RawItem``; ``None`` when it is cancelled or unusable.++ The body is composed rather than copied raw: a bare description loses+ which calendar the event lived on, when it ran, and who was there — and+ those are exactly what a later question ("when did I meet Ada?") turns on.+ """+ if str(event.get("status") or "") == "cancelled":+ return None+ event_id = str(event.get("id") or "").strip()+ permalink = str(event.get("htmlLink") or "").strip()+ if not event_id or not permalink:+ return None++ start = _when(event.get("start"))+ end = _when(event.get("end"))+ title = str(event.get("summary") or "").strip() or "(untitled event)"+ organizer = event.get("organizer") or {}+ organizer_name = str(+ organizer.get("displayName") or organizer.get("email") or ""+ ).strip()+ location = str(event.get("location") or "").strip()+ description = str(event.get("description") or "").strip()+ if "<" in description and ">" in description:+ # Calendar descriptions may carry HTML; the memory wants readable text.+ description = g.strip_html(description)+ recurring_id = str(event.get("recurringEventId") or "").strip()+ updated = str(event.get("updated") or "")++ header = f"{calendar_label} · event · {start}" if calendar_label else f"event · {start}"+ if end:+ header += f" until {end}"+ lines = [header]+ if location:+ lines.append(f"Location: {location}")+ if organizer_name:+ lines.append(f"Organizer: {organizer_name}")+ attendee_line = _attendee_line(event)+ if attendee_line:+ lines.append(attendee_line)+ if description:+ lines.append("")+ lines.append(description)+ body, truncated = g.cap_body("\n".join(lines).strip())++ return RawItem(+ # Calendar-scoped: the same invitation appears on several calendars+ # with the SAME event id, and each copy must upsert as its own row.+ external_id=f"{calendar_id}:{event_id}",+ title=title,+ body=body,+ permalink=permalink,+ # WHEN IT HAPPENED — the event's own start, not its last edit. The+ # edit time rides in metadata to drive the cursor.+ timestamp_utc=start,+ # Instances of one recurring series thread together.+ thread_key=f"{calendar_id}:{recurring_id or event_id}",+ author_raw=organizer_name,+ metadata={+ "mtime_ns": g.to_ns(updated),+ "calendar_id": calendar_id,+ "calendar_label": calendar_label,+ "status": str(event.get("status") or ""),+ "recurring_event_id": recurring_id,+ "attendees": len(event.get("attendees") or []),+ "truncated": truncated,+ },+ )+++async def _calendars(client: httpx.AsyncClient, token: str) -> list[tuple[str, str]]:+ """Every subscribed calendar as ``(id, label)``, sorted by id.++ Sorted so the cross-calendar walk order is deterministic — the resume+ convention leans on it — and does not reshuffle when the API reorders+ its listing.+ """+ rows: list[tuple[str, str]] = []+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {"maxResults": _CALENDAR_PAGE_SIZE}+ if page_token:+ params["pageToken"] = page_token+ payload = await g.google_get_json(+ client, f"{_API}/users/me/calendarList", token, _PRODUCT, params=params+ )+ for row in payload.get("items") or []:+ if not isinstance(row, dict):+ continue+ calendar_id = str(row.get("id") or "").strip()+ if not calendar_id:+ continue+ label = str(row.get("summaryOverride") or row.get("summary") or "").strip()+ rows.append((calendar_id, label or calendar_id))+ page_token = str(payload.get("nextPageToken") or "") or None+ if not page_token:+ break+ rows.sort(key=lambda pair: pair[0])+ return rows+++async def google_calendar_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every event on every calendar, calendar by calendar, oldest first.++ ``checkpoint`` doubles as the resume/cursor convention: a numeric value is+ the incremental cursor (nanoseconds → ``updatedMin``); anything else is+ the last imported external id (``<calendar id>:<event id>``) from an+ interrupted backfill — calendars sorted BEFORE that calendar are complete+ and are skipped, the checkpoint's own calendar is re-walked from its start+ (event pages carry full data, so re-listing one calendar is cheap and the+ already-imported rows upsert as ``unchanged``). ``transport`` is a test+ seam; production leaves it ``None``.+ """+ token = g.google_token(_PLUGIN_ID, _PRODUCT)+ cutoff = g.cursor_cutoff(checkpoint)+ resume_calendar = ""+ if checkpoint and cutoff is None and ":" in checkpoint:+ resume_calendar = checkpoint.rsplit(":", 1)[0]+ time_max = (datetime.now(UTC) + timedelta(days=_LOOKAHEAD_DAYS)).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )+ yielded = 0++ async with httpx.AsyncClient(timeout=g.TIMEOUT, transport=transport) as client:+ for calendar_id, calendar_label in await _calendars(client, token):+ if resume_calendar and calendar_id < resume_calendar:+ continue # completed before the interruption+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {+ "singleEvents": "true",+ "orderBy": "startTime",+ "timeMin": _TIME_MIN,+ "timeMax": time_max,+ "maxResults": _EVENT_PAGE_SIZE,+ }+ if cutoff:+ params["updatedMin"] = cutoff.strftime("%Y-%m-%dT%H:%M:%SZ")+ if page_token:+ params["pageToken"] = page_token+ payload = await g.google_get_json(+ client,+ f"{_API}/calendars/{quote(calendar_id, safe='')}/events",+ token,+ _PRODUCT,+ params=params,+ )+ for row in payload.get("items") or []:+ if not isinstance(row, dict):+ continue+ item = item_from_event(calendar_id, calendar_label, row)+ if item is not None:+ yielded += 1+ yield item+ page_token = str(payload.get("nextPageToken") or "") or None+ if not page_token:+ break++ log.info(+ "Google Calendar adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if cutoff else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/google_drive.py b/jarvis/ultrawiki/adapters/google_drive.pynew file mode 100644index 0000000000..11c1522d1c--- /dev/null+++ b/jarvis/ultrawiki/adapters/google_drive.py@@ -0,0 +1,324 @@+"""Google Drive pull adapter — the readable text of every non-trashed file.++Of everything Drive holds, this pulls what belongs in a *memory*: the TEXT.+Google-native documents are exported to plain text (Docs → ``text/plain``,+Sheets → ``text/csv``, Slides → ``text/plain``); text-shaped regular files+(``text/*``, JSON, XML, YAML, …) are downloaded directly. The walk lists the+complete non-trashed corpus ordered by ``modifiedTime`` ascending, so an+interrupted backfill resumes strictly after the last imported file id without+re-downloading anything before it.++Scope honesty — what the token allows vs. what is imported:++- **Binaries are skipped, deliberately and visibly.** Images, videos,+ archives, PDFs and Office binaries have no text the Drive API can hand+ over as such (Drive exports only Google-native types), and a knowledge+ base must never swallow blobs. Skipped files are counted in one log line;+ they yield NO item.+- **Folders and shortcuts are skipped** — structure, not content; a+ shortcut's target imports as itself.+- **Bodies are capped at ~1 MB** with a visible truncation marker. Direct+ downloads are bounded at the source with an HTTP ``Range`` header, so an+ oversized file never crosses the wire whole; Google-native exports are+ additionally subject to Google's own ~10 MB export ceiling — a document+ whose export fails yields its metadata with an honest note instead of+ failing the sync.+- **Shared drives are not enumerated.** The walk covers the user corpus (My+ Drive plus items shared with the user that surface in ``files.list``);+ separate shared-drive corpora need a per-drive walk a later change can add.+- **Incremental rides the ``modifiedTime`` cursor** via+ ``metadata["mtime_ns"]`` (the key the sync runner already advances): a+ numeric checkpoint narrows the listing with ``modifiedTime > <cutoff>``+ one day earlier, so a boundary can never skip a file.++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 typing import Any++import httpx++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "GoogleAdapterError",+ "google_drive_pull_adapter",+ "item_from_file",+]++#: Re-exported so callers can catch the family's error type from this module.+GoogleAdapterError = g.GoogleAdapterError++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:google_drive"++_PLUGIN_ID = "google_drive"+_PRODUCT = "Google Drive"+_API = "https://www.googleapis.com/drive/v3"++_PAGE_SIZE = 1000+_FIELDS = (+ "nextPageToken,files(id,name,mimeType,size,createdTime,modifiedTime,"+ "webViewLink,description,owners(displayName,emailAddress))"+)++#: Google-native types and the text shape they export to.+_GOOGLE_EXPORTS: dict[str, str] = {+ "application/vnd.google-apps.document": "text/plain",+ "application/vnd.google-apps.spreadsheet": "text/csv",+ "application/vnd.google-apps.presentation": "text/plain",+}++#: Non-``text/*`` MIME types that are still text on the inside.+_TEXT_MIMES: frozenset[str] = frozenset(+ {+ "application/json",+ "application/xml",+ "application/javascript",+ "application/x-yaml",+ "application/yaml",+ "application/toml",+ "application/x-sh",+ "application/csv",+ }+)+++def _content_plan(mime: str) -> tuple[str, str] | None:+ """How to obtain a file's text: ``("export", target)``, ``("download", "")``,+ or ``None`` when the file has no text form and is skipped honestly."""+ if mime in _GOOGLE_EXPORTS:+ return ("export", _GOOGLE_EXPORTS[mime])+ if mime.startswith("application/vnd.google-apps."):+ return None # folder, shortcut, form, drawing, … — no text export+ if mime.startswith("text/") or mime in _TEXT_MIMES:+ return ("download", "")+ return None+++def item_from_file(+ file: dict[str, Any], content: str, content_truncated: bool+) -> RawItem | None:+ """One listed file plus its fetched text as a ``RawItem``.++ The body is composed rather than copied raw: bare file content loses its+ own name, kind and owner — the handles a later question reaches for.+ """+ file_id = str(file.get("id") or "").strip()+ if not file_id:+ return None+ name = str(file.get("name") or "").strip() or "(unnamed file)"+ mime = str(file.get("mimeType") or "")+ created = str(file.get("createdTime") or "")+ modified = str(file.get("modifiedTime") or "")+ owners = [row for row in file.get("owners") or [] if isinstance(row, dict)]+ owner = ""+ if owners:+ owner = str(owners[0].get("displayName") or owners[0].get("emailAddress") or "")+ permalink = (+ str(file.get("webViewLink") or "").strip()+ or f"https://drive.google.com/file/d/{file_id}/view"+ )+ description = str(file.get("description") or "").strip()++ header = f"Google Drive · {name} · {mime}"+ if owner:+ header += f" · owned by {owner}"+ lines = [header]+ if description:+ lines.append(description)+ if content:+ lines.append("")+ lines.append(content)+ body, capped = g.cap_body("\n".join(lines).strip())+ truncated = capped or content_truncated+ if content_truncated and not capped:+ body += g.TRUNCATION_MARKER++ try:+ size = int(file.get("size") or 0)+ except (TypeError, ValueError):+ size = 0++ return RawItem(+ external_id=file_id,+ title=name,+ body=body,+ permalink=permalink,+ # WHEN IT CAME TO BE — the memory is about the document, not its last+ # touch. The modification time rides in metadata to drive the cursor.+ timestamp_utc=created or modified,+ author_raw=owner,+ metadata={+ "mtime_ns": g.to_ns(modified or created),+ "mime_type": mime,+ "size": size,+ "truncated": truncated,+ },+ )+++async def _all_files(+ client: httpx.AsyncClient, token: str, query: str+) -> list[dict[str, Any]]:+ """The complete non-trashed listing, oldest-modified first.++ Metadata only — no content crosses the wire here, so even a large Drive+ costs a handful of cheap requests before the first download, and the+ resume point can be located before anything expensive happens.+ """+ rows: list[dict[str, Any]] = []+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {+ "q": query,+ "orderBy": "modifiedTime",+ "pageSize": _PAGE_SIZE,+ "fields": _FIELDS,+ }+ if page_token:+ params["pageToken"] = page_token+ payload = await g.google_get_json(+ client, f"{_API}/files", token, _PRODUCT, params=params+ )+ for row in payload.get("files") or []:+ if isinstance(row, dict) and row.get("id"):+ rows.append(row)+ page_token = str(payload.get("nextPageToken") or "") or None+ if not page_token:+ break+ return rows+++async def _file_text(+ client: httpx.AsyncClient, token: str, file: dict[str, Any]+) -> tuple[str, bool] | None:+ """``(text, truncated)`` for one file, or ``None`` when it has no text form.++ A per-file fetch failure (export ceiling, permission quirk on one item)+ degrades to an honest note — one stubborn file must never sink the whole+ walk. Credential failures and exhausted rate budgets still raise, because+ they concern the sync, not the file.+ """+ plan = _content_plan(str(file.get("mimeType") or ""))+ if plan is None:+ return None+ mode, target = plan+ file_id = str(file.get("id") or "")++ if mode == "export":+ response = await g.google_get(+ client,+ f"{_API}/files/{file_id}/export",+ token,+ _PRODUCT,+ params={"mimeType": target},+ tolerate=(403, 404),+ )+ if response.status_code >= 400:+ return (+ f"[content could not be exported (HTTP {response.status_code}) — "+ "open the link to view it]",+ False,+ )+ return response.text, False++ # Direct download, bounded at the source: the Range header caps what+ # crosses the wire, so an oversized file costs one capped request.+ response = await g.google_get(+ client,+ f"{_API}/files/{file_id}",+ token,+ _PRODUCT,+ params={"alt": "media"},+ headers={"Range": f"bytes=0-{g.BODY_CAP - 1}"},+ tolerate=(403, 404, 416),+ )+ if response.status_code == 416: # empty file: the range has nothing to cover+ return "", False+ if response.status_code >= 400:+ return (+ f"[content could not be downloaded (HTTP {response.status_code}) — "+ "open the link to view it]",+ False,+ )+ try:+ declared = int(file.get("size") or 0)+ except (TypeError, ValueError):+ declared = 0+ truncated = response.status_code == 206 and declared > g.BODY_CAP+ return response.text, truncated+++async def google_drive_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield the readable text of every non-trashed file, oldest-modified first.++ ``checkpoint`` doubles as the resume/cursor convention: a numeric value is+ the incremental cursor (nanoseconds → ``modifiedTime >`` query); anything+ else is the last imported file id from an interrupted backfill, and the+ walk resumes strictly after it — files before the resume point are never+ content-fetched again. A checkpoint id that no longer exists (the file was+ trashed) degrades to a full walk rather than silently skipping everything.+ ``transport`` is a test seam; production leaves it ``None``.+ """+ token = g.google_token(_PLUGIN_ID, _PRODUCT)+ cutoff = g.cursor_cutoff(checkpoint)+ query = "trashed = false"+ if cutoff:+ query += f" and modifiedTime > '{cutoff.strftime('%Y-%m-%dT%H:%M:%SZ')}'"+ resume_after = checkpoint if (checkpoint and cutoff is None) else None+ yielded = 0+ skipped = 0++ async with httpx.AsyncClient(timeout=g.TIMEOUT, transport=transport) as client:+ files = await _all_files(client, token, query)+ if resume_after:+ index = next(+ (i for i, row in enumerate(files) if str(row.get("id")) == resume_after),+ None,+ )+ if index is None:+ log.info(+ "Google Drive adapter: checkpoint file %s no longer exists; "+ "walking the full listing instead",+ resume_after,+ )+ else:+ files = files[index + 1 :]+ for file in files:+ fetched = await _file_text(client, token, file)+ if fetched is None:+ skipped += 1+ continue+ content, content_truncated = fetched+ item = item_from_file(file, content, content_truncated)+ if item is not None:+ yielded += 1+ yield item++ if skipped:+ log.info(+ "Google Drive adapter: skipped %d file(s) with no text form "+ "(binaries are never imported)",+ skipped,+ )+ log.info(+ "Google Drive adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if cutoff else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/google_mail.py b/jarvis/ultrawiki/adapters/google_mail.pynew file mode 100644index 0000000000..22b87c0107--- /dev/null+++ b/jarvis/ultrawiki/adapters/google_mail.py@@ -0,0 +1,253 @@+"""Gmail pull adapter — every message the connected mailbox holds.++Of everything Gmail is, this pulls what belongs in a *memory*: the text of+every message — who wrote, to whom, when, and what was said. The walk is the+full mailbox (``users.messages.list`` paged to the end), oldest to newest, so+an interrupted backfill resumes strictly after the last imported message id.++Scope honesty — what the token allows vs. what is imported:++- **Message text only.** The plain-text part is preferred; an HTML-only+ message is stripped to readable text; a message with neither decodable part+ falls back to the API's snippet. Attachments are binaries and are NEVER+ downloaded — each item states how many it left behind, so the record never+ implies the body is the whole message.+- **Spam and trash are excluded** (the API's default listing). A memory keeps+ what the user kept.+- **Bodies are capped at ~1 MB** with a visible truncation marker.+- **Incremental rides the ``internalDate`` cursor** via+ ``metadata["mtime_ns"]`` — the key the sync runner already advances. Gmail's+ history API (``historyId``) is finer-grained but its log expires after days+ and the bridge persists exactly one numeric cursor, so the receive time is+ the honest durable choice; each message's ``historyId`` is stashed in+ metadata for a future history-based mode. A numeric checkpoint narrows the+ listing with ``after:<epoch seconds>`` (one day earlier, so a boundary can+ never skip a message; re-yielded items upsert as ``unchanged``).++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 typing import Any++import httpx++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.types import ConnectorContext, RawItem++log = logging.getLogger(__name__)++__all__ = [+ "INTEGRATION_ID",+ "GoogleAdapterError",+ "gmail_pull_adapter",+ "item_from_message",+]++#: Re-exported so callers can catch the family's error type from this module.+GoogleAdapterError = g.GoogleAdapterError++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:gmail"++_PLUGIN_ID = "gmail"+_PRODUCT = "Gmail"+_API = "https://gmail.googleapis.com/gmail/v1/users/me"++#: The listing is ids only, so the largest page the API allows is the cheap+#: way to enumerate a big mailbox.+_LIST_PAGE_SIZE = 500++#: Defensive bound on MIME-part recursion; real messages nest a handful deep.+_MAX_PART_DEPTH = 20+++def _header(headers: list[Any], name: str) -> str:+ wanted = name.lower()+ for row in headers:+ if isinstance(row, dict) and str(row.get("name") or "").lower() == wanted:+ return str(row.get("value") or "").strip()+ return ""+++def _collect_text(+ part: Any, plain: list[str], html_parts: list[str], depth: int = 0+) -> None:+ """Walk the MIME tree collecting decodable text; attachments stay behind."""+ if depth > _MAX_PART_DEPTH or not isinstance(part, dict):+ return+ filename = str(part.get("filename") or "")+ mime = str(part.get("mimeType") or "").lower()+ data = str((part.get("body") or {}).get("data") or "")+ if not filename and data:+ if mime.startswith("text/plain"):+ plain.append(g.decode_base64url(data))+ elif mime.startswith("text/html"):+ html_parts.append(g.decode_base64url(data))+ for sub in part.get("parts") or []:+ _collect_text(sub, plain, html_parts, depth + 1)+++def _attachment_count(part: Any, depth: int = 0) -> int:+ if depth > _MAX_PART_DEPTH or not isinstance(part, dict):+ return 0+ count = 1 if str(part.get("filename") or "") else 0+ for sub in part.get("parts") or []:+ count += _attachment_count(sub, depth + 1)+ return count+++def _body_text(payload: dict[str, Any], snippet: str) -> str:+ plain: list[str] = []+ html_parts: list[str] = []+ _collect_text(payload, plain, html_parts)+ if any(text.strip() for text in plain):+ return "\n".join(text for text in plain if text.strip()).strip()+ if any(text.strip() for text in html_parts):+ return g.strip_html("\n".join(html_parts))+ return snippet.strip()+++def item_from_message(message: dict[str, Any]) -> RawItem | None:+ """One fetched message as a ``RawItem``; ``None`` when it is unusable.++ The body is composed rather than copied raw: a bare body loses who wrote+ it and to whom, and both are exactly what a later question ("what did Ada+ write about X?") turns on.+ """+ message_id = str(message.get("id") or "").strip()+ if not message_id:+ return None+ payload = message.get("payload") or {}+ headers = payload.get("headers") or []+ subject = _header(headers, "Subject")+ sender = _header(headers, "From")+ recipient = _header(headers, "To")+ thread_id = str(message.get("threadId") or "")+ internal_ms = message.get("internalDate")++ descriptor: list[str] = []+ if sender:+ descriptor.append(f"from {sender}")+ if recipient:+ descriptor.append(f"to {recipient}")+ header_line = "email" + (f" {' · '.join(descriptor)}" if descriptor else "")+ body_text = _body_text(payload, str(message.get("snippet") or ""))+ attachments = _attachment_count(payload)+ if attachments:+ # Binaries are never imported (memory-shaped scope); the record must+ # say what it does not contain instead of implying completeness.+ body_text += (+ f"\n\n[{attachments} attachment(s) not imported — "+ "open the link to download them]"+ )+ body, truncated = g.cap_body(f"{header_line}\n\n{body_text}".strip())++ return RawItem(+ external_id=message_id,+ title=subject or "(no subject)",+ body=body,+ permalink=f"https://mail.google.com/mail/u/0/#all/{message_id}",+ # WHEN IT ARRIVED — the memory is about the event. internalDate also+ # drives the cursor via metadata, so both stay consistent.+ timestamp_utc=g.iso_utc_from_ms(internal_ms),+ thread_key=thread_id or message_id,+ author_raw=sender,+ metadata={+ "mtime_ns": g.ms_to_ns(internal_ms),+ "thread_id": thread_id,+ "label_ids": [str(label) for label in message.get("labelIds") or []],+ "history_id": str(message.get("historyId") or ""),+ "attachments": attachments,+ "truncated": truncated,+ },+ )+++async def _all_message_ids(+ client: httpx.AsyncClient, token: str, query: str+) -> list[str]:+ """Every message id the token can list, oldest first.++ The API lists newest-first; reversing the complete listing gives the+ deterministic oldest-to-newest walk the checkpoint convention needs. The+ listing is ids only, so even a very large mailbox costs a few hundred+ cheap requests before any message body is fetched.+ """+ ids: list[str] = []+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {"maxResults": _LIST_PAGE_SIZE}+ if query:+ params["q"] = query+ if page_token:+ params["pageToken"] = page_token+ payload = await g.google_get_json(+ client, f"{_API}/messages", token, _PRODUCT, params=params+ )+ for row in payload.get("messages") or []:+ if isinstance(row, dict) and row.get("id"):+ ids.append(str(row["id"]))+ page_token = str(payload.get("nextPageToken") or "") or None+ if not page_token:+ break+ ids.reverse()+ return ids+++async def gmail_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every message in the connected mailbox, oldest to newest.++ ``checkpoint`` doubles as the resume/cursor convention: a numeric value is+ the incremental cursor (nanoseconds → ``after:`` query); anything else is+ the last imported message id from an interrupted backfill, and the walk+ resumes strictly after it. A checkpoint id that no longer exists (the+ message was deleted) degrades to a full walk — unchanged items upsert+ cheaply, and silently skipping the whole mailbox would be the real bug.+ ``transport`` is a test seam; production leaves it ``None``.+ """+ token = g.google_token(_PLUGIN_ID, _PRODUCT)+ cutoff = g.cursor_cutoff(checkpoint)+ query = f"after:{int(cutoff.timestamp())}" if cutoff else ""+ resume_after = checkpoint if (checkpoint and cutoff is None) else None+ yielded = 0++ async with httpx.AsyncClient(timeout=g.TIMEOUT, transport=transport) as client:+ ids = await _all_message_ids(client, token, query)+ if resume_after:+ try:+ ids = ids[ids.index(resume_after) + 1 :]+ except ValueError:+ log.info(+ "Gmail adapter: checkpoint message %s no longer exists; "+ "walking the full mailbox instead",+ resume_after,+ )+ for message_id in ids:+ payload = await g.google_get_json(+ client,+ f"{_API}/messages/{message_id}",+ token,+ _PRODUCT,+ params={"format": "full"},+ )+ item = item_from_message(payload)+ if item is not None:+ yielded += 1+ yield item++ log.info(+ "Gmail adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if cutoff else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/linear.py b/jarvis/ultrawiki/adapters/linear.pynew file mode 100644index 0000000000..fdb50b0ea9--- /dev/null+++ b/jarvis/ultrawiki/adapters/linear.py@@ -0,0 +1,416 @@+"""Linear pull adapter — every issue the connected account can query.++Scope, honestly stated. One paginated GraphQL query walks the workspace's+issues with ``includeArchived: true``, so open, completed, canceled AND+archived issues all arrive — Linear's API puts no per-team fences around a+token, so this really is everything the account can see. Each issue carries+its first 50 comments inline in the same query (no per-issue request); an+issue with more than 50 comments gets an explicit marker line instead of a+silent cut, because the record must say what it does not contain.++Structural limits: Linear documents, project updates and attachments are not+issues and are not imported — this reader is about the task stream, and the+issue body plus its comments is where the decisions live. Comment threads+beyond the first 50 per issue stay behind the permalink, as marked.++Cursor convention (the reference adapter's): a numeric checkpoint is the sync+runner's nanosecond cursor and becomes an ``updatedAt >= <instant>`` filter+(minus a five-minute overlap so a boundary is safe; re-yielded items upsert+as ``unchanged``). An ``issue:<id>`` checkpoint is the bridge's backfill+resume marker: issues stream oldest-to-newest in a deterministic order, so+the walk resumes strictly after that id. Any other checkpoint is read as "no+cursor" and yields the full set. Every item carries ``metadata["mtime_ns"]``+so the runner can advance its cursor.++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 asyncio+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",+ "LinearAdapterError",+ "item_from_issue",+ "linear_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:linear"++_API = "https://api.linear.app/graphql"++#: Modest page size: each issue carries a nested comment page, and Linear+#: prices queries by complexity, not by row count.+_PAGE_SIZE = 50+_MAX_PAGES = 200+_COMMENT_PAGE = 50++_TIMEOUT = httpx.Timeout(connect=5.0, read=25.0, write=10.0, pool=5.0)++_MAX_ATTEMPTS = 3+_RETRY_WAIT_CAP = 30.0+_DEFAULT_RETRY_WAIT = 2.0++_SINCE_OVERLAP_SECONDS = 300++_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_NOTE = "\n\n[truncated — the full text lives at the link above]"++_MORE_COMMENTS_NOTE = "[more comments on Linear — open the link to read them]"++_ISSUES_QUERY = f"""+query UltraWikiIssues($first: Int!, $after: String, $filter: IssueFilter) {{+ issues(first: $first, after: $after, filter: $filter, includeArchived: true) {{+ nodes {{+ id+ identifier+ title+ description+ url+ createdAt+ updatedAt+ archivedAt+ dueDate+ state {{ name }}+ assignee {{ name }}+ creator {{ name }}+ team {{ id key name }}+ project {{ name }}+ comments(first: {_COMMENT_PAGE}) {{+ nodes {{+ body+ createdAt+ user {{ name }}+ }}+ pageInfo {{ hasNextPage }}+ }}+ }}+ pageInfo {{ hasNextPage endCursor }}+ }}+}}+"""+++class LinearAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Linear token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("linear")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise LinearAdapterError(+ "The Linear connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise LinearAdapterError(+ "Linear is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise LinearAdapterError(+ "The Linear connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ }+++def _retry_wait(response: httpx.Response | None) -> float:+ if response is None:+ return 0.0+ header = str(response.headers.get("Retry-After") or "").strip()+ try:+ wait = float(header)+ except ValueError:+ wait = _DEFAULT_RETRY_WAIT+ return min(max(wait, 0.0), _RETRY_WAIT_CAP)+++async def _query(+ client: httpx.AsyncClient, token: str, variables: dict[str, Any]+) -> dict[str, Any]:+ """One GraphQL round trip, every failure mapped to an actionable sentence."""+ response: httpx.Response | None = None+ for attempt in range(_MAX_ATTEMPTS):+ if attempt:+ await asyncio.sleep(_retry_wait(response))+ try:+ response = await client.post(+ _API,+ headers=_headers(token),+ json={"query": _ISSUES_QUERY, "variables": variables},+ )+ except httpx.HTTPError as exc:+ raise LinearAdapterError(+ f"Linear was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code != 429:+ break+ if response is None: # pragma: no cover - loop always runs at least once+ raise LinearAdapterError("Linear answered nothing for this request.")+ if response.status_code == 401:+ raise LinearAdapterError(+ "Linear rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 429:+ raise LinearAdapterError(+ "Linear's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code >= 400:+ raise LinearAdapterError(+ f"Linear answered HTTP {response.status_code} for this request."+ )+ payload = response.json() or {}+ errors = payload.get("errors")+ if isinstance(errors, list) and errors:+ codes = {+ str(((error or {}).get("extensions") or {}).get("code") or "")+ for error in errors+ if isinstance(error, dict)+ }+ if "AUTHENTICATION_ERROR" in codes:+ raise LinearAdapterError(+ "Linear rejected the connection. Reconnect it in the Plugins store."+ )+ if "RATELIMITED" in codes:+ raise LinearAdapterError(+ "Linear's rate limit is exhausted. The next sync continues "+ "where this one stopped."+ )+ first = next(+ (+ str(error.get("message") or "")+ for error in errors+ if isinstance(error, dict) and error.get("message")+ ),+ "unspecified error",+ )+ raise LinearAdapterError(f"Linear reported an error for this request: {first}")+ data = payload.get("data")+ return data if isinstance(data, dict) else {}+++def _since_iso(checkpoint: str | None) -> str:+ """The stored numeric cursor as an ISO instant for the updatedAt filter."""+ if not checkpoint:+ return ""+ try:+ ns = int(checkpoint)+ except (TypeError, ValueError):+ return ""+ if ns <= 0:+ return ""+ seconds = ns / 1_000_000_000 - _SINCE_OVERLAP_SECONDS+ if seconds <= 0:+ return ""+ return datetime.fromtimestamp(seconds, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _resume_marker(checkpoint: str | None) -> str:+ """The checkpoint as a backfill resume id (``issue:<id>``), or empty."""+ if checkpoint and checkpoint.startswith("issue:"):+ return checkpoint+ return ""+++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 _cap(text: str) -> str:+ if len(text) <= _MAX_BODY_CHARS:+ return text+ return text[:_MAX_BODY_CHARS] + _TRUNCATION_NOTE+++def _comment_lines(comments: Any) -> tuple[list[str], bool]:+ """Chronological comment lines + whether more exist beyond the page."""+ nodes = (comments or {}).get("nodes") if isinstance(comments, dict) else None+ page_info = (comments or {}).get("pageInfo") if isinstance(comments, dict) else None+ more = bool(isinstance(page_info, dict) and page_info.get("hasNextPage"))+ rows: list[tuple[str, str]] = []+ for node in nodes or []:+ if not isinstance(node, dict):+ continue+ body = str(node.get("body") or "").strip()+ if not body:+ continue+ author = str((node.get("user") or {}).get("name") or "")+ created = str(node.get("createdAt") or "")+ prefix = " · ".join(part for part in (created, author) if part)+ rows.append((created, f"[{prefix}] {body}" if prefix else body))+ rows.sort(key=lambda pair: pair[0])+ return [line for _created, line in rows], more+++def item_from_issue(issue: dict[str, Any]) -> RawItem | None:+ """One Linear issue as a ``RawItem``; ``None`` when it is unusable."""+ issue_id = str(issue.get("id") or "")+ permalink = str(issue.get("url") or "").strip()+ if not issue_id or not permalink:+ return None++ identifier = str(issue.get("identifier") or "") or issue_id+ title = str(issue.get("title") or "").strip() or f"issue {identifier}"+ state = str((issue.get("state") or {}).get("name") or "")+ archived = bool(issue.get("archivedAt"))+ assignee = str((issue.get("assignee") or {}).get("name") or "")+ author = str((issue.get("creator") or {}).get("name") or "")+ due = str(issue.get("dueDate") or "")+ created = str(issue.get("createdAt") or "")+ updated = str(issue.get("updatedAt") or "")+ team = issue.get("team") or {}+ team_id = str(team.get("id") or "")+ team_name = str(team.get("name") or team.get("key") or "")+ project = str((issue.get("project") or {}).get("name") or "")++ header_parts = [part for part in (team_name, f"issue {identifier}", state) if part]+ if archived:+ header_parts.append("archived")+ if project:+ header_parts.append(f"project {project}")+ if assignee:+ header_parts.append(f"assigned to {assignee}")+ if due:+ header_parts.append(f"due {due}")+ if author:+ header_parts.append(f"created by {author}")+ header = " · ".join(header_parts)++ comments, more = _comment_lines(issue.get("comments"))+ body_text = str(issue.get("description") or "").strip()+ if comments:+ body_text += ("\n\n" if body_text else "") + "Comments:\n" + "\n".join(comments)+ if more:+ body_text += ("\n\n" if body_text else "") + _MORE_COMMENTS_NOTE++ return RawItem(+ external_id=f"issue:{issue_id}",+ title=title,+ body=_cap(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=team_id,+ author_raw=author,+ metadata={+ "mtime_ns": _to_ns(updated or created),+ "identifier": identifier,+ "state": state,+ "archived": archived,+ "assignee": assignee,+ "due": due,+ "comments": len(comments),+ "updated_at": updated,+ },+ )+++async def linear_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every issue the connected Linear account can query.++ ``checkpoint`` doubles as the incremental cursor (see the module+ docstring). ``transport`` is a test seam; production leaves it ``None``.+ """+ token = _token()+ since = _since_iso(checkpoint)+ resume_after = _resume_marker(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ nodes: list[dict[str, Any]] = []+ after: str | None = None+ for page in range(_MAX_PAGES):+ variables: dict[str, Any] = {"first": _PAGE_SIZE, "after": after}+ if since:+ variables["filter"] = {"updatedAt": {"gte": since}}+ data = await _query(client, token, variables)+ connection = data.get("issues") or {}+ rows = connection.get("nodes")+ if isinstance(rows, list):+ nodes.extend(row for row in rows if isinstance(row, dict))+ page_info = connection.get("pageInfo") or {}+ if not page_info.get("hasNextPage"):+ break+ after = str(page_info.get("endCursor") or "") or None+ if after is None:+ break+ if page == _MAX_PAGES - 1:+ log.info(+ "Linear adapter: stopping at %d pages; the next sync "+ "resumes from the cursor",+ _MAX_PAGES,+ )++ # Deterministic oldest-to-newest order, so the bridge's backfill+ # checkpoint (last flushed external_id) resumes strictly after it.+ seen: set[str] = set()+ ordered: list[dict[str, Any]] = []+ for node in sorted(+ nodes,+ key=lambda n: (str(n.get("createdAt") or ""), str(n.get("id") or "")),+ ):+ node_id = str(node.get("id") or "")+ if not node_id or node_id in seen:+ continue+ seen.add(node_id)+ ordered.append(node)++ start = 0+ if resume_after:+ for index, node in enumerate(ordered):+ if f"issue:{node.get('id')}" == resume_after:+ start = index + 1+ break++ for node in ordered[start:]:+ item = item_from_issue(node)+ if item is not None:+ yielded += 1+ yield item++ log.info(+ "Linear adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if since else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/notion.py b/jarvis/ultrawiki/adapters/notion.pynew file mode 100644index 0000000000..0a71a6dcd1--- /dev/null+++ b/jarvis/ultrawiki/adapters/notion.py@@ -0,0 +1,686 @@+"""Notion pull adapter — every page and database the integration can reach.++Of everything Notion holds, this pulls what belongs in a *memory*: the words.+It walks the Search API (ascending by ``last_edited_time``, cursor paging)+across everything shared with the integration, renders each standalone page's+block tree to plain text lines (``blocks.children``, recursive, bounded depth,+cycle-guarded), and reads every database's rows through+``databases/<id>/query`` with the row properties flattened to ``Name: value``+lines.++Item shape: ONE item per page (title plus rendered block content) and ONE item+per database row (title plus flattened properties). ``external_id`` is the+Notion page/row id, so a re-sync upserts the same rows instead of duplicating+them; the permalink is Notion's own ``url`` field.++HONEST SCOPE — what a token structurally cannot yield:++* An internal integration sees ONLY the pages and databases a user has+ explicitly shared with it (children included). Nothing else appears in+ Search, so "everything" here means everything SHARED — a workspace where the+ integration was never invited into the top-level pages imports nothing, and+ the fix is sharing those pages, not reconnecting.+* Database rows import their PROPERTIES, not their page body — fetching each+ row's block tree would cost one extra request per row and burn the rate+ budget (3 requests/second) on large databases. A row whose knowledge lives+ in its body appears with title and properties only.+* Comments are not imported (a separate API needing its own capability, one+ request per block). Files and images are imported as ``[file: ...]``-style+ markers, never as binary content — text is the memory, blobs are not.+* Nesting beyond 8 block levels is not descended into; a marker line says so+ in the rendered page.++Rate limits: Notion answers HTTP 429 with ``Retry-After``; every request+honours it with bounded waits (at most four attempts, at most 30 s each)+before failing honestly.++The incremental cursor rides on ``metadata["mtime_ns"]`` — the key the sync+runner already advances — carrying each item's ``last_edited_time``. A numeric+checkpoint narrows the import to items edited on or after the day before the+cursor's day (Search itself has no time filter, so the listing is still+walked, but the expensive per-page block fetches are skipped for untouched+pages; database queries filter server-side). Touched pages are re-yielded in+full and upsert on their content hash. 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 asyncio+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",+ "NotionAdapterError",+ "notion_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves (catalog id ``notion``).+INTEGRATION_ID = "plugin:notion"++_API = "https://api.notion.com/v1"++#: Pinned API version: the last version where ``databases/<id>/query`` is the+#: one stable row-reading path (later versions split databases into data+#: sources). Upgrading is a deliberate change, never an accident.+_NOTION_VERSION = "2022-06-28"++#: Notion's maximum page size for search, query and block listings.+_PAGE_SIZE = 100+_MAX_SEARCH_PAGES = 200 # 20 000 shared pages/databases per walk+_MAX_QUERY_PAGES = 200 # 20 000 rows per database+_MAX_BLOCK_PAGES = 50 # 5 000 blocks per nesting level++#: Recursive block rendering stops here; a marker line keeps the record honest.+_MAX_DEPTH = 8++#: Bounded 429 handling: honour Retry-After, but never wait unboundedly.+_MAX_ATTEMPTS = 4+_MAX_RETRY_WAIT = 30.0++#: Cap any single item body; a marker says the record is incomplete.+_MAX_BODY_BYTES = 1_000_000+_TRUNCATION_MARKER = "\n\n[truncated — this item exceeded the 1 MB import cap]"+_DEPTH_MARKER = "[deeper content not imported — nesting exceeds the depth cap]"++_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)+++class NotionAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Notion token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("notion")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise NotionAdapterError(+ "The Notion connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise NotionAdapterError(+ "Notion is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise NotionAdapterError(+ "The Notion connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}", "Notion-Version": _NOTION_VERSION}+++async def _request(+ client: httpx.AsyncClient,+ method: str,+ path: str,+ token: str,+ *,+ json_body: dict[str, Any] | None = None,+ params: dict[str, Any] | None = None,+) -> httpx.Response:+ """One API call with bounded 429 retries and honest failure mapping.++ Returns the response — including 4xx responses, which each caller handles+ per its own degradation rule. Only transport failures, dead credentials+ (401) and exhausted rate budgets raise.+ """+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ response = await client.request(+ method, f"{_API}{path}", headers=_headers(token), json=json_body, params=params+ )+ except httpx.HTTPError as exc:+ raise NotionAdapterError(+ f"Notion was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429:+ if attempt == _MAX_ATTEMPTS:+ break+ try:+ delay = float(response.headers.get("retry-after") or "")+ except ValueError:+ delay = 1.0+ await asyncio.sleep(min(max(delay, 0.0), _MAX_RETRY_WAIT))+ continue+ if response.status_code == 401:+ raise NotionAdapterError(+ "Notion rejected the connection. Reconnect it in the Plugins store."+ )+ return response+ raise NotionAdapterError(+ "Notion's rate limit persisted after several bounded waits. "+ "The next sync continues where this one stopped."+ )+++async def _validate(client: httpx.AsyncClient, token: str) -> None:+ """Confirm the token works before walking anything (401 raises inside)."""+ response = await _request(client, "GET", "/users/me", token)+ if response.status_code >= 400:+ raise NotionAdapterError(+ f"Notion could not confirm the connection (HTTP {response.status_code})."+ )+++def _to_ns(iso: str) -> int:+ """ISO-8601 → nanoseconds since the epoch; 0 when unparseable."""+ if not iso:+ return 0+ try:+ moment = datetime.fromisoformat(str(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 _cursor_to_since(checkpoint: str | None) -> str:+ """The stored numeric cursor as an ISO date for ``on_or_after``. Empty when unset.++ The cursor is nanoseconds since the epoch (the sync runner's convention).+ A day is subtracted before filtering: re-asking from the previous day is+ what guarantees nothing is skipped at a boundary, and re-yielded items+ upsert as ``unchanged``. A non-numeric checkpoint — the bridge passes the+ last item's id during a backfill — is read as "no cursor".+ """+ 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)+ return datetime.fromordinal(moment.toordinal() - 1).strftime("%Y-%m-%d")+++def _plain(rich: Any) -> str:+ """A Notion rich-text array as plain prose; empty for anything else."""+ if not isinstance(rich, list):+ return ""+ return "".join(+ str(part.get("plain_text") or "") for part in rich if isinstance(part, dict)+ ).strip()+++def _title_of(properties: Any) -> str:+ """The value of the one ``title``-typed property; empty when absent."""+ if not isinstance(properties, dict):+ return ""+ for prop in properties.values():+ if isinstance(prop, dict) and prop.get("type") == "title":+ return _plain(prop.get("title"))+ return ""+++def _permalink_of(obj: dict[str, Any]) -> str:+ """Notion's own ``url``, or the canonical constructed form as fallback."""+ url = str(obj.get("url") or "").strip()+ if url:+ return url+ object_id = str(obj.get("id") or "").replace("-", "")+ return f"https://www.notion.so/{object_id}" if object_id else ""+++def _parent_id(obj: dict[str, Any]) -> str:+ """The direct parent's id (page, database or block); empty for workspace."""+ parent = obj.get("parent")+ if not isinstance(parent, dict):+ return ""+ parent_type = str(parent.get("type") or "")+ return str(parent.get(parent_type) or "") if parent_type != "workspace" else ""+++def _cap_body(body: str) -> str:+ encoded = body.encode("utf-8")+ if len(encoded) <= _MAX_BODY_BYTES:+ return body+ kept = encoded[:_MAX_BODY_BYTES].decode("utf-8", errors="ignore").rstrip()+ return kept + _TRUNCATION_MARKER+++# ---------------------------------------------------------------------------+# Block rendering — a page's block tree as plain text lines+# ---------------------------------------------------------------------------+++def _block_line(block: dict[str, Any], number: int) -> str:+ """One block as one plain-text line (or fenced lines for code).++ ``number`` is the running index inside a contiguous numbered-list run.+ Media blocks become markers — the name or caption is memory, the bytes+ are not (and never will be pulled).+ """+ btype = str(block.get("type") or "")+ payload = block.get(btype) if isinstance(block.get(btype), dict) else {}+ text = _plain(payload.get("rich_text"))+ if btype == "paragraph":+ return text+ if btype == "heading_1":+ return f"# {text}" if text else ""+ if btype == "heading_2":+ return f"## {text}" if text else ""+ if btype == "heading_3":+ return f"### {text}" if text else ""+ if btype == "bulleted_list_item":+ return f"- {text}" if text else ""+ if btype == "numbered_list_item":+ return f"{number}. {text}" if text else ""+ if btype == "to_do":+ mark = "x" if payload.get("checked") else " "+ return f"[{mark}] {text}" if text else ""+ if btype == "quote":+ return f"> {text}" if text else ""+ if btype == "code":+ language = str(payload.get("language") or "").strip()+ return f"```{language}\n{text}\n```" if text else ""+ if btype == "callout":+ return f"[callout] {text}" if text else ""+ if btype == "toggle":+ return text+ if btype == "child_page":+ title = str(payload.get("title") or "").strip()+ return f"[subpage: {title}]" if title else "[subpage]"+ if btype == "child_database":+ title = str(payload.get("title") or "").strip()+ return f"[database: {title}]" if title else "[database]"+ if btype == "table_row":+ cells = payload.get("cells")+ if isinstance(cells, list):+ return " | ".join(_plain(cell) for cell in cells)+ return ""+ if btype == "equation":+ return str(payload.get("expression") or "").strip()+ if btype == "divider":+ return "---"+ if btype in ("bookmark", "embed", "link_preview"):+ url = str(payload.get("url") or "").strip()+ caption = _plain(payload.get("caption"))+ if caption and url:+ return f"{caption} ({url})"+ return url or caption+ if btype in ("image", "file", "pdf", "video", "audio"):+ label = _plain(payload.get("caption")) or str(payload.get("name") or "").strip()+ if not label:+ external = payload.get("external")+ label = str(external.get("url") or "") if isinstance(external, dict) else ""+ return f"[{btype}: {label}]" if label else f"[{btype}]"+ # Unknown or structural types (synced_block, column_list, ...): keep any+ # words they carry; their children are still descended into.+ return text+++async def _block_children(+ client: httpx.AsyncClient, token: str, block_id: str+) -> list[dict[str, Any]]:+ """One level of a block's children, fully paged. Empty on a refusal."""+ blocks: list[dict[str, Any]] = []+ cursor = ""+ for _page in range(_MAX_BLOCK_PAGES):+ params: dict[str, Any] = {"page_size": _PAGE_SIZE}+ if cursor:+ params["start_cursor"] = cursor+ response = await _request(+ client, "GET", f"/blocks/{block_id}/children", token, params=params+ )+ if response.status_code >= 400:+ log.debug(+ "Notion adapter: block children unavailable for %s (HTTP %d)",+ block_id,+ response.status_code,+ )+ break+ payload: dict[str, Any] = response.json() or {}+ blocks.extend(b for b in payload.get("results") or [] if isinstance(b, dict))+ if not payload.get("has_more"):+ break+ cursor = str(payload.get("next_cursor") or "")+ if not cursor:+ break+ else:+ log.warning(+ "Notion adapter: block %s exceeded the children page cap; "+ "imported what was read",+ block_id,+ )+ return blocks+++async def _render_children(+ client: httpx.AsyncClient,+ token: str,+ block_id: str,+ depth: int,+ visited: set[str],+ lines: list[str],+) -> None:+ """Render one block's children into ``lines``, bounded and cycle-guarded."""+ if block_id in visited:+ return # a synced/self-referencing block must not loop the import+ visited.add(block_id)+ if depth >= _MAX_DEPTH:+ lines.append(" " * depth + _DEPTH_MARKER)+ return+ number = 0+ for block in await _block_children(client, token, block_id):+ btype = str(block.get("type") or "")+ number = number + 1 if btype == "numbered_list_item" else 0+ line = _block_line(block, number)+ if line:+ indent = " " * depth+ lines.append("\n".join(indent + part for part in line.split("\n")))+ # Sub-pages and inline databases are their own search results (when+ # shared); descending into them here would import them twice.+ if block.get("has_children") and btype not in ("child_page", "child_database"):+ child_id = str(block.get("id") or "")+ if child_id:+ await _render_children(client, token, child_id, depth + 1, visited, lines)+++# ---------------------------------------------------------------------------+# Property flattening — a database row's properties as ``Name: value`` lines+# ---------------------------------------------------------------------------+++def _flatten_property(prop: Any) -> str:+ """One property value as a short plain string; empty when it has none."""+ if not isinstance(prop, dict):+ return ""+ ptype = str(prop.get("type") or "")+ value = prop.get(ptype)+ if ptype in ("title", "rich_text"):+ return _plain(value)+ if ptype in ("number",):+ return "" if value is None else str(value)+ if ptype in ("select", "status"):+ return str((value or {}).get("name") or "") if isinstance(value, dict) else ""+ if ptype == "multi_select":+ if not isinstance(value, list):+ return ""+ return ", ".join(+ str(entry.get("name") or "") for entry in value if isinstance(entry, dict)+ )+ if ptype == "date":+ if not isinstance(value, dict):+ return ""+ start = str(value.get("start") or "")+ end = str(value.get("end") or "")+ return f"{start} → {end}" if start and end else start+ if ptype == "people":+ if not isinstance(value, list):+ return ""+ return ", ".join(+ str(person.get("name") or person.get("id") or "")+ for person in value+ if isinstance(person, dict)+ )+ if ptype == "files":+ if not isinstance(value, list):+ return ""+ return ", ".join(+ f"[file: {entry.get('name') or 'attachment'}]"+ for entry in value+ if isinstance(entry, dict)+ )+ if ptype in ("checkbox", "boolean"):+ return "yes" if value else "no"+ if ptype in ("url", "email", "phone_number", "string", "created_time", "last_edited_time"):+ return str(value or "")+ if ptype in ("formula", "rollup"):+ # Both wrap an inner ``{"type": X, X: value}`` shape — recurse once.+ if isinstance(value, dict) and str(value.get("type") or "") == "array":+ entries = value.get("array")+ if not isinstance(entries, list):+ return ""+ return ", ".join(+ flat for entry in entries if (flat := _flatten_property(entry))+ )+ return _flatten_property(value)+ if ptype in ("created_by", "last_edited_by"):+ return str((value or {}).get("name") or "") if isinstance(value, dict) else ""+ if ptype == "relation":+ count = len(value) if isinstance(value, list) else 0+ return f"[{count} linked page(s)]" if count else ""+ if ptype == "unique_id":+ if not isinstance(value, dict):+ return ""+ prefix = str(value.get("prefix") or "")+ num = value.get("number")+ if num is None:+ return ""+ return f"{prefix}-{num}" if prefix else str(num)+ return ""+++# ---------------------------------------------------------------------------+# Item mapping+# ---------------------------------------------------------------------------+++def _row_item(row: dict[str, Any], database_title: str, database_id: str) -> RawItem | None:+ """One database row as one item — title plus flattened properties."""+ row_id = str(row.get("id") or "")+ permalink = _permalink_of(row)+ if not row_id or not permalink:+ return None+ properties = row.get("properties") if isinstance(row.get("properties"), dict) else {}+ title = _title_of(properties) or "Untitled"+ lines = [+ f"{name}: {flat}"+ for name in sorted(properties)+ if isinstance(properties.get(name), dict)+ and properties[name].get("type") != "title"+ and (flat := _flatten_property(properties[name]))+ ]+ header = f"{database_title} · database row" if database_title else "Notion database row"+ edited = str(row.get("last_edited_time") or row.get("created_time") or "")+ return RawItem(+ external_id=row_id,+ title=title,+ body=_cap_body("\n".join([header, "", title, *lines]).strip()),+ permalink=permalink,+ timestamp_utc=edited,+ thread_key=database_id or _parent_id(row) or row_id,+ metadata={+ "mtime_ns": _to_ns(edited),+ "kind": "database_row",+ "database_id": database_id or _parent_id(row),+ "database_title": database_title,+ "created_time": str(row.get("created_time") or ""),+ },+ )+++def _page_item(page: dict[str, Any], lines: list[str]) -> RawItem | None:+ """One standalone page as one item — title plus its rendered block tree."""+ page_id = str(page.get("id") or "")+ permalink = _permalink_of(page)+ if not page_id or not permalink:+ return None+ title = _title_of(page.get("properties")) or "Untitled"+ edited = str(page.get("last_edited_time") or page.get("created_time") or "")+ parent = _parent_id(page)+ return RawItem(+ external_id=page_id,+ title=title,+ body=_cap_body("\n".join([f"Notion page · {title}", "", *lines]).strip()),+ permalink=permalink,+ timestamp_utc=edited,+ thread_key=parent or page_id,+ metadata={+ "mtime_ns": _to_ns(edited),+ "kind": "page",+ "parent_id": parent,+ "created_time": str(page.get("created_time") or ""),+ },+ )+++# ---------------------------------------------------------------------------+# Walks+# ---------------------------------------------------------------------------+++async def _search(client: httpx.AsyncClient, token: str) -> AsyncIterator[dict[str, Any]]:+ """Every page and database shared with the integration, oldest-edited first."""+ cursor = ""+ for _page in range(_MAX_SEARCH_PAGES):+ body: dict[str, Any] = {+ "page_size": _PAGE_SIZE,+ "sort": {"direction": "ascending", "timestamp": "last_edited_time"},+ }+ if cursor:+ body["start_cursor"] = cursor+ response = await _request(client, "POST", "/search", token, json_body=body)+ if response.status_code >= 400:+ raise NotionAdapterError(+ f"Notion answered HTTP {response.status_code} while listing "+ "the shared content."+ )+ payload: dict[str, Any] = response.json() or {}+ for result in payload.get("results") or []:+ if isinstance(result, dict):+ yield result+ if not payload.get("has_more"):+ return+ cursor = str(payload.get("next_cursor") or "")+ if not cursor:+ return+ log.warning(+ "Notion adapter: the search walk exceeded the page cap; imported what was found"+ )+++async def _database_rows(+ client: httpx.AsyncClient, token: str, database_id: str, since: str+) -> list[dict[str, Any]] | None:+ """Every row of one database, oldest-edited first. ``None`` = honestly skipped."""+ rows: list[dict[str, Any]] = []+ cursor = ""+ for _page in range(_MAX_QUERY_PAGES):+ body: dict[str, Any] = {+ "page_size": _PAGE_SIZE,+ "sorts": [{"timestamp": "last_edited_time", "direction": "ascending"}],+ }+ if since:+ body["filter"] = {+ "timestamp": "last_edited_time",+ "last_edited_time": {"on_or_after": since},+ }+ if cursor:+ body["start_cursor"] = cursor+ response = await _request(+ client, "POST", f"/databases/{database_id}/query", token, json_body=body+ )+ if response.status_code >= 400:+ # A linked or restricted database refuses its query; rows the token+ # CAN see still arrive as search results and import there.+ log.info(+ "Notion adapter: skipping database %s (HTTP %d); rows shared "+ "with the integration still import via search",+ database_id,+ response.status_code,+ )+ return None+ payload: dict[str, Any] = response.json() or {}+ rows.extend(r for r in payload.get("results") or [] if isinstance(r, dict))+ if not payload.get("has_more"):+ break+ cursor = str(payload.get("next_cursor") or "")+ if not cursor:+ break+ else:+ log.warning(+ "Notion adapter: database %s exceeded the query page cap; "+ "imported what was read",+ database_id,+ )+ return rows+++async def notion_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every page and database row the connected Notion token can read.++ ``checkpoint`` doubles as the incremental cursor: numeric means "only what+ changed since", anything else means a full backfill. ``transport`` is a+ test seam; production leaves it ``None``.+ """+ token = _token()+ since = _cursor_to_since(checkpoint)+ since_ns = _to_ns(f"{since}T00:00:00Z") if since else 0+ yielded = 0+ seen: set[str] = set()++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ await _validate(client, token)+ async for result in _search(client, token):+ kind = str(result.get("object") or "")+ if kind == "database":+ database_id = str(result.get("id") or "")+ if not database_id:+ continue+ rows = await _database_rows(client, token, database_id, since)+ if rows is None:+ continue+ database_title = _plain(result.get("title"))+ for row in rows:+ item = _row_item(row, database_title, database_id)+ if item is not None and item.external_id not in seen:+ seen.add(item.external_id)+ yielded += 1+ yield item+ elif kind == "page":+ page_id = str(result.get("id") or "")+ if not page_id or page_id in seen:+ continue+ edited_ns = _to_ns(str(result.get("last_edited_time") or ""))+ if since_ns and edited_ns and edited_ns < since_ns:+ continue # untouched since the cursor; skip the block fetches+ parent = result.get("parent") if isinstance(result.get("parent"), dict) else {}+ if str(parent.get("type") or "") == "database_id":+ # A row whose database query already ran is in ``seen``;+ # this path catches rows whose database is not queryable.+ item = _row_item(result, "", str(parent.get("database_id") or ""))+ else:+ lines: list[str] = []+ await _render_children(client, token, page_id, 0, set(), lines)+ item = _page_item(result, lines)+ if item is not None and item.external_id not in seen:+ seen.add(item.external_id)+ yielded += 1+ yield item++ log.info(+ "Notion adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if since else "backfill",+ )diff --git a/jarvis/ultrawiki/adapters/slack.py b/jarvis/ultrawiki/adapters/slack.pynew file mode 100644index 0000000000..7d6e8344c0--- /dev/null+++ b/jarvis/ultrawiki/adapters/slack.py@@ -0,0 +1,670 @@+"""Slack pull adapter — every conversation the connected token can see.++Of everything Slack holds, this pulls what belongs in a *memory*: the words.+It walks ``conversations.list`` across all four conversation types (public+channels, private channels, group DMs, DMs), reads each conversation's FULL+history oldest-to-newest (``conversations.history``, cursor paging), and+expands every thread through ``conversations.replies`` — a thread is+remembered as one coherent exchange, not a scatter of orphaned lines.++Item shape: ONE item per thread (parent plus replies as chronological+``author: text`` lines) and ONE item per calendar day of non-threaded+messages in a conversation. That keeps ids stable across re-runs — a re-sync+upserts the same rows instead of duplicating them — and keeps single Slack+messages from becoming thousands of one-line memory entries.++HONEST SCOPE — what a token structurally cannot yield:++* Visibility is the TOKEN's, not the workspace's. A user token sees what that+ user sees; a bot token sees only conversations the app was invited into.+ Public channels the token is not a member of appear in the listing but+ answer ``not_in_channel`` on history — those are skipped with a log line,+ never faked.+* A conversation *type* the token has no scope for (``missing_scope``)+ degrades per type: the other types still import fully. The same applies to+ ``users.list`` — without it, raw user ids appear instead of display names.+* Files and images are imported as ``[file: <name>]`` markers, never as+ binary content — text is the memory, blobs are not.+* On an incremental (cursor) run, a NEW reply to a thread that started before+ the cursor is only caught when the reply was "also sent to the channel"; a+ plain reply to an old thread surfaces on the next FULL backfill. (The+ bridge currently re-runs full backfills, so nothing is missed today.)++Permalinks are CONSTRUCTED from the workspace URL (``auth.test``) in the+canonical ``/archives/<channel>/p<ts>`` shape that ``chat.getPermalink``+returns — calling that API per item would cost one extra request per+imported item and burn the rate budget for zero new information.++Rate limits: Slack answers HTTP 429 with ``Retry-After``; every request+honours it with bounded waits (at most four attempts, at most 30 s each)+before failing honestly.++The incremental cursor rides on ``metadata["mtime_ns"]`` — the key the sync+runner already advances — carrying each item's newest message time. A numeric+checkpoint narrows history to the day before the cursor's day (a whole-day+rewind keeps day-chunk ids complete rather than half-rebuilt at a boundary);+a non-numeric checkpoint — the bridge passes the last item's id during a+backfill — is read as "no cursor" and re-yields the full set, which upserts+as ``unchanged``.++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 asyncio+import logging+import re+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",+ "SlackAdapterError",+ "slack_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves (catalog id ``slack``).+INTEGRATION_ID = "plugin:slack"++_API = "https://slack.com/api"++#: Fixed walk order across conversation types — determinism, not preference.+_CONVERSATION_TYPES = ("public_channel", "private_channel", "mpim", "im")++#: Slack's recommended page size for the conversations/users families.+_PAGE_LIMIT = 200+_MAX_LIST_PAGES = 50 # 10 000 conversations or users per listing walk+_MAX_HISTORY_PAGES = 2000 # 400 000 messages per conversation+_MAX_THREAD_PAGES = 200 # 40 000 replies per thread++#: Bounded 429 handling: honour Retry-After, but never wait unboundedly.+_MAX_ATTEMPTS = 4+_MAX_RETRY_WAIT = 30.0++#: Cap any single item body; a marker says the record is incomplete.+_MAX_BODY_BYTES = 1_000_000+_TRUNCATION_MARKER = "\n\n[truncated — this item exceeded the 1 MB import cap]"++_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)++#: ``ok: false`` errors that mean the CREDENTIAL is dead, not the request.+_AUTH_ERRORS = frozenset(+ {"invalid_auth", "not_authed", "account_inactive", "token_revoked", "token_expired"}+)++#: Join/leave/archive housekeeping is not memory; topic and purpose changes+#: carry real text and are kept.+_NOISE_SUBTYPES = frozenset(+ {+ "channel_join",+ "channel_leave",+ "group_join",+ "group_leave",+ "channel_archive",+ "channel_unarchive",+ "bot_add",+ "bot_remove",+ }+)++_MENTION_RE = re.compile(r"<@([A-Z0-9]+)(?:\|[^>]*)?>")+_CHANNEL_REF_RE = re.compile(r"<#[A-Z0-9]+\|([^>]+)>")+_LINK_RE = re.compile(r"<(https?://[^>|]+)(?:\|([^>]*))?>")+++class SlackAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Slack token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("slack")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise SlackAdapterError(+ "The Slack connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise SlackAdapterError(+ "Slack is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise SlackAdapterError(+ "The Slack connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++async def _call(+ client: httpx.AsyncClient,+ method: str,+ token: str,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """One Web API call with bounded 429 retries and honest failure mapping.++ Returns the parsed payload — including ``ok: false`` payloads, which each+ caller handles per its own degradation rule. Only transport failures, HTTP+ errors, exhausted rate budgets, and dead-credential errors raise.+ """+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ response = await client.get(+ f"{_API}/{method}", headers=_headers(token), params=params+ )+ except httpx.HTTPError as exc:+ raise SlackAdapterError(+ f"Slack was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429:+ if attempt == _MAX_ATTEMPTS:+ break+ try:+ delay = float(response.headers.get("retry-after") or "")+ except ValueError:+ delay = 1.0+ await asyncio.sleep(min(max(delay, 0.0), _MAX_RETRY_WAIT))+ continue+ if response.status_code >= 400:+ raise SlackAdapterError(+ f"Slack answered HTTP {response.status_code} for {method}."+ )+ payload: dict[str, Any] = response.json() or {}+ if not payload.get("ok") and str(payload.get("error") or "") in _AUTH_ERRORS:+ raise SlackAdapterError(+ "Slack rejected the connection. Reconnect it in the Plugins store."+ )+ return payload+ raise SlackAdapterError(+ "Slack's rate limit persisted after several bounded waits. "+ "The next sync continues where this one stopped."+ )+++def _next_cursor(payload: dict[str, Any]) -> str:+ metadata = payload.get("response_metadata") or {}+ return str(metadata.get("next_cursor") or "").strip() if isinstance(metadata, dict) else ""+++async def _team_url(client: httpx.AsyncClient, token: str) -> str:+ """The workspace's base URL (permalink prefix); also validates the token."""+ payload = await _call(client, "auth.test", token)+ if not payload.get("ok"):+ raise SlackAdapterError(+ "Slack could not confirm the connection "+ f"({payload.get('error') or 'unknown error'})."+ )+ # slack.com/archives/... redirects a signed-in user to the right+ # workspace, so a missing url degrades to a still-working link.+ return str(payload.get("url") or "").strip() or "https://slack.com/"+++async def _display_names(client: httpx.AsyncClient, token: str) -> dict[str, str]:+ """User id → display name, cached for the whole run. Empty on missing scope."""+ names: dict[str, str] = {}+ cursor = ""+ for _page in range(_MAX_LIST_PAGES):+ params: dict[str, Any] = {"limit": _PAGE_LIMIT}+ if cursor:+ params["cursor"] = cursor+ payload = await _call(client, "users.list", token, params)+ if not payload.get("ok"):+ log.info(+ "Slack adapter: user names are unavailable (%s); raw user ids "+ "will appear instead",+ payload.get("error") or "unknown error",+ )+ return names+ for member in payload.get("members") or []:+ if not isinstance(member, dict):+ continue+ user_id = str(member.get("id") or "")+ profile = member.get("profile") if isinstance(member.get("profile"), dict) else {}+ name = str(+ profile.get("display_name")+ or profile.get("real_name")+ or member.get("real_name")+ or member.get("name")+ or ""+ ).strip()+ if user_id and name:+ names[user_id] = name+ cursor = _next_cursor(payload)+ if not cursor:+ break+ return names+++async def _conversations(client: httpx.AsyncClient, token: str) -> list[dict[str, Any]]:+ """Every conversation the token can list, in a deterministic order.++ Each type is requested separately so a scope the token lacks removes ONE+ type, never the whole import. Archived conversations are included — the+ words in them are still the user's history.+ """+ found: dict[str, dict[str, Any]] = {}+ for conv_type in _CONVERSATION_TYPES:+ cursor = ""+ for _page in range(_MAX_LIST_PAGES):+ params: dict[str, Any] = {"types": conv_type, "limit": _PAGE_LIMIT}+ if cursor:+ params["cursor"] = cursor+ payload = await _call(client, "conversations.list", token, params)+ if not payload.get("ok"):+ error = str(payload.get("error") or "unknown error")+ if error == "missing_scope":+ log.info(+ "Slack adapter: the token has no scope to list %s "+ "conversations; the other types still import",+ conv_type,+ )+ else:+ log.warning(+ "Slack adapter: listing %s conversations failed (%s)",+ conv_type,+ error,+ )+ break+ for channel in payload.get("channels") or []:+ if isinstance(channel, dict) and channel.get("id"):+ found[str(channel["id"])] = channel+ cursor = _next_cursor(payload)+ if not cursor:+ break+ else:+ log.warning(+ "Slack adapter: %s listing exceeded the page cap; importing "+ "what was found",+ conv_type,+ )+ rows = list(found.values())+ rows.sort(key=lambda c: (float(c.get("created") or 0), str(c.get("id") or "")))+ return rows+++def _ts_sort_key(message: dict[str, Any]) -> float:+ try:+ return float(str(message.get("ts") or "0"))+ except ValueError:+ return 0.0+++async def _history(+ client: httpx.AsyncClient, token: str, channel_id: str, oldest: str+) -> list[dict[str, Any]] | None:+ """A conversation's full history, ascending. ``None`` = honestly skipped."""+ messages: list[dict[str, Any]] = []+ cursor = ""+ for _page in range(_MAX_HISTORY_PAGES):+ params: dict[str, Any] = {"channel": channel_id, "limit": _PAGE_LIMIT}+ if oldest:+ params["oldest"] = oldest+ if cursor:+ params["cursor"] = cursor+ payload = await _call(client, "conversations.history", token, params)+ if not payload.get("ok"):+ # not_in_channel and missing_scope are structural facts about the+ # token, not errors of ours: skip this conversation and say so.+ log.info(+ "Slack adapter: skipping conversation %s (%s)",+ channel_id,+ payload.get("error") or "unknown error",+ )+ return None+ messages.extend(m for m in payload.get("messages") or [] if isinstance(m, dict))+ cursor = _next_cursor(payload)+ if not cursor:+ break+ else:+ log.warning(+ "Slack adapter: conversation %s exceeded the history page cap; "+ "imported what was read",+ channel_id,+ )+ messages.sort(key=_ts_sort_key)+ return messages+++async def _thread_messages(+ client: httpx.AsyncClient, token: str, channel_id: str, thread_ts: str+) -> list[dict[str, Any]]:+ """One thread — parent plus every reply — ascending and de-duplicated."""+ messages: list[dict[str, Any]] = []+ cursor = ""+ for _page in range(_MAX_THREAD_PAGES):+ params: dict[str, Any] = {+ "channel": channel_id,+ "ts": thread_ts,+ "limit": _PAGE_LIMIT,+ }+ if cursor:+ params["cursor"] = cursor+ payload = await _call(client, "conversations.replies", token, params)+ if not payload.get("ok"):+ log.debug(+ "Slack adapter: replies unavailable for %s/%s (%s)",+ channel_id,+ thread_ts,+ payload.get("error") or "unknown error",+ )+ break+ messages.extend(m for m in payload.get("messages") or [] if isinstance(m, dict))+ cursor = _next_cursor(payload)+ if not cursor:+ break+ else:+ log.warning(+ "Slack adapter: thread %s/%s exceeded the reply page cap; "+ "imported what was read",+ channel_id,+ thread_ts,+ )+ unique = {str(m.get("ts") or ""): m for m in messages if m.get("ts")}+ return sorted(unique.values(), key=_ts_sort_key)+++def _to_ns(ts: str) -> int:+ """A Slack ``ts`` ("seconds.fraction") → nanoseconds; 0 when unparseable.++ Split-and-pad instead of ``float`` math: at epoch scale a float64 loses+ the sub-second digits that make two messages ordered.+ """+ text = str(ts or "").strip()+ if not text:+ return 0+ seconds, _, fraction = text.partition(".")+ try:+ whole = int(seconds)+ except ValueError:+ return 0+ try:+ frac_ns = int((fraction + "000000000")[:9]) if fraction else 0+ except ValueError:+ frac_ns = 0+ return whole * 1_000_000_000 + frac_ns+++def _ts_to_iso(ts: str) -> str:+ ns = _to_ns(ts)+ if ns <= 0:+ return ""+ moment = datetime.fromtimestamp(ns // 1_000_000_000, tz=UTC)+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _day_of(ts: str) -> str:+ ns = _to_ns(ts)+ if ns <= 0:+ return ""+ return datetime.fromtimestamp(ns // 1_000_000_000, tz=UTC).strftime("%Y-%m-%d")+++def _cursor_to_oldest(checkpoint: str | None) -> str:+ """The stored numeric cursor as a Slack ``oldest`` value. Empty when unset.++ The cursor is nanoseconds since the epoch (the sync runner's convention).+ History is re-asked from the START OF THE PREVIOUS UTC DAY: day-chunk+ items carry a per-day id, so a mid-day cut would rebuild a HALF day under+ the full day's id and silently shrink it. Re-yielded items upsert as+ ``unchanged``. A non-numeric checkpoint — the bridge passes the last+ item's id during a backfill — is read as "no cursor".+ """+ 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_start = datetime.fromordinal(moment.toordinal() - 1).replace(tzinfo=UTC)+ return f"{int(day_start.timestamp())}.000000"+++def _permalink(team_url: str, channel_id: str, ts: str) -> str:+ """The canonical archive deep link ``chat.getPermalink`` would return."""+ return f"{team_url.rstrip('/')}/archives/{channel_id}/p{str(ts).replace('.', '')}"+++def _clean_text(text: str, names: dict[str, str]) -> str:+ """Slack markup → readable prose: mentions named, links unwrapped."""+ if not text:+ return ""+ cleaned = _MENTION_RE.sub(lambda m: "@" + names.get(m.group(1), m.group(1)), text)+ cleaned = _CHANNEL_REF_RE.sub(lambda m: "#" + m.group(1), cleaned)+ cleaned = _LINK_RE.sub(lambda m: m.group(2) or m.group(1), cleaned)+ return (+ cleaned.replace("<", "<").replace(">", ">").replace("&", "&").strip()+ )+++def _author_of(message: dict[str, Any], names: dict[str, str]) -> str:+ user = str(message.get("user") or "")+ if user:+ return names.get(user, user)+ profile = message.get("bot_profile") if isinstance(message.get("bot_profile"), dict) else {}+ return str(message.get("username") or profile.get("name") or "app")+++def _line(message: dict[str, Any], names: dict[str, str]) -> str:+ """One ``author: text`` line; empty when the message carries no words.++ Files become ``[file: <name>]`` markers — the name is memory, the bytes+ are not (and never will be pulled).+ """+ parts: list[str] = []+ text = _clean_text(str(message.get("text") or ""), names)+ if text:+ parts.append(text)+ for file_info in message.get("files") or []:+ if isinstance(file_info, dict):+ name = str(file_info.get("title") or file_info.get("name") or "attachment")+ parts.append(f"[file: {name}]")+ if not parts:+ return ""+ return f"{_author_of(message, names)}: {' '.join(parts)}"+++def _cap_body(body: str) -> str:+ encoded = body.encode("utf-8")+ if len(encoded) <= _MAX_BODY_BYTES:+ return body+ kept = encoded[:_MAX_BODY_BYTES].decode("utf-8", errors="ignore").rstrip()+ return kept + _TRUNCATION_MARKER+++def _channel_label(channel: dict[str, Any], names: dict[str, str]) -> str:+ if channel.get("is_im"):+ user = str(channel.get("user") or "")+ return f"DM with @{names.get(user, user or 'unknown')}"+ name = str(channel.get("name") or channel.get("id") or "conversation")+ if channel.get("is_mpim"):+ return f"group DM {name}"+ return f"#{name}"+++def _max_mtime_ns(messages: list[dict[str, Any]]) -> int:+ return max((_to_ns(str(m.get("ts") or "")) for m in messages), default=0)+++def _thread_item(+ channel_id: str,+ label: str,+ messages: list[dict[str, Any]],+ names: dict[str, str],+ team_url: str,+) -> RawItem | None:+ """One thread as one item — parent and replies in spoken order."""+ lines = [line for message in messages if (line := _line(message, names))]+ parent_ts = str(messages[0].get("ts") or "") if messages else ""+ if not lines or not parent_ts:+ return None+ parent_text = _clean_text(str(messages[0].get("text") or ""), names)+ title = f"Thread in {label}"+ if parent_text:+ title += f": {parent_text[:80]}"+ header = f"{label} · thread · {len(lines)} message(s)"+ return RawItem(+ external_id=f"{channel_id}:{parent_ts}",+ title=title,+ body=_cap_body("\n".join([header, "", *lines])),+ permalink=_permalink(team_url, channel_id, parent_ts),+ timestamp_utc=_ts_to_iso(parent_ts),+ thread_key=channel_id,+ author_raw=_author_of(messages[0], names),+ metadata={+ "mtime_ns": _max_mtime_ns(messages),+ "channel": channel_id,+ "channel_label": label,+ "kind": "thread",+ "thread_ts": parent_ts,+ "message_count": len(lines),+ },+ )+++def _day_item(+ channel_id: str,+ label: str,+ day: str,+ messages: list[dict[str, Any]],+ names: dict[str, str],+ team_url: str,+) -> RawItem | None:+ """One calendar day of a conversation's non-threaded messages as one item."""+ lines = [line for message in messages if (line := _line(message, names))]+ first_ts = str(messages[0].get("ts") or "") if messages else ""+ if not lines or not first_ts:+ return None+ header = f"{label} · {day} · {len(lines)} message(s)"+ return RawItem(+ external_id=f"{channel_id}:{day}",+ title=f"{label} on {day}",+ body=_cap_body("\n".join([header, "", *lines])),+ permalink=_permalink(team_url, channel_id, first_ts),+ timestamp_utc=_ts_to_iso(first_ts),+ thread_key=channel_id,+ metadata={+ "mtime_ns": _max_mtime_ns(messages),+ "channel": channel_id,+ "channel_label": label,+ "kind": "day",+ "day": day,+ "message_count": len(lines),+ },+ )+++async def _conversation_items(+ client: httpx.AsyncClient,+ token: str,+ channel: dict[str, Any],+ names: dict[str, str],+ team_url: str,+ oldest: str,+) -> list[RawItem] | None:+ """Every item one conversation contributes, ascending. ``None`` = skipped."""+ channel_id = str(channel.get("id") or "")+ if not channel_id:+ return []+ history = await _history(client, token, channel_id, oldest)+ if history is None:+ return None+ label = _channel_label(channel, names)++ # Threads are pulled out of the day flow: a parent with replies becomes a+ # thread item, and a broadcast reply ("also sent to channel") marks its+ # thread for expansion instead of duplicating one line into a day chunk.+ thread_parents: dict[str, dict[str, Any] | None] = {}+ by_day: dict[str, list[dict[str, Any]]] = {}+ for message in history:+ ts = str(message.get("ts") or "")+ if not ts or str(message.get("subtype") or "") in _NOISE_SUBTYPES:+ continue+ thread_ts = str(message.get("thread_ts") or "")+ if thread_ts and thread_ts != ts:+ thread_parents.setdefault(thread_ts, None)+ continue+ if int(message.get("reply_count") or 0) > 0:+ thread_parents[ts] = message+ continue+ day = _day_of(ts)+ if day:+ by_day.setdefault(day, []).append(message)++ items: list[RawItem] = []+ for thread_ts in sorted(thread_parents, key=float):+ messages = await _thread_messages(client, token, channel_id, thread_ts)+ if not messages:+ parent = thread_parents[thread_ts]+ messages = [parent] if parent else []+ item = _thread_item(channel_id, label, messages, names, team_url)+ if item is not None:+ items.append(item)+ for day in sorted(by_day):+ day_item = _day_item(channel_id, label, day, by_day[day], names, team_url)+ if day_item is not None:+ items.append(day_item)+ items.sort(key=lambda item: (item.timestamp_utc, item.external_id))+ return items+++async def slack_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every conversation the connected Slack token can read.++ ``checkpoint`` doubles as the incremental cursor: numeric means "only+ what changed since", anything else means a full backfill. ``transport``+ is a test seam; production leaves it ``None``.+ """+ token = _token()+ oldest = _cursor_to_oldest(checkpoint)+ yielded = 0+ skipped = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ team_url = await _team_url(client, token)+ names = await _display_names(client, token)+ conversations = await _conversations(client, token)+ for channel in conversations:+ items = await _conversation_items(+ client, token, channel, names, team_url, oldest+ )+ if items is None:+ skipped += 1+ continue+ for item in items:+ yielded += 1+ yield item++ log.info(+ "Slack adapter: yielded %d item(s) from %d conversation(s) for %s (%s%s)",+ yielded,+ len(conversations) - skipped,+ ctx.source_id,+ "incremental" if oldest else "backfill",+ f"; {skipped} unreadable conversation(s) skipped" if skipped else "",+ )diff --git a/jarvis/ultrawiki/adapters/telegram.py b/jarvis/ultrawiki/adapters/telegram.pynew file mode 100644index 0000000000..5ffe6ff03a--- /dev/null+++ b/jarvis/ultrawiki/adapters/telegram.py@@ -0,0 +1,401 @@+"""Telegram pull adapter — forward capture only, because the Bot API allows+nothing else.++THE STRUCTURAL LIMIT, UP FRONT: a Telegram BOT cannot read the past. The Bot+API has no history endpoint — ``getUpdates`` holds only the updates delivered+since the bot last confirmed them and Telegram keeps them for roughly 24+hours; anything said before the bot joined a chat, and anything older than+that window, is permanently out of reach for a bot token. "Everything the+token allows" therefore honestly means FORWARD CAPTURE: from the moment this+source syncs, every message the bot receives is imported and nothing that+arrives is lost between runs — it is not, and can never be, a backfill of old+conversations. (A full-history Telegram import would need a user-account MTProto+session, which is a different credential and a different consent conversation.)++Three more honest boundaries of that capture:++* Reading updates CONSUMES them: advancing the ``getUpdates`` offset confirms+ earlier pages server-side. That also means only ONE reader can exist — when+ the Telegram chat channel (or a webhook) is polling this bot, Telegram+ answers 409 and the sync surfaces that plainly instead of silently reading+ nothing. On installs where the chat channel is active, that channel eats+ the update stream first.+* In group chats, BotFather's default "privacy mode" delivers only commands+ and replies to the bot; capturing the full group conversation requires the+ user to disable it for their bot.+* Media is recorded as a text placeholder plus any caption; binaries are+ never downloaded.++Determinism and cursors: updates arrive ascending by ``update_id`` and are+emitted in that order, one :class:`RawItem` per message (an edit re-yields+the same ``external_id`` and upserts as changed). The cursor rides on+``metadata["max_rowid"]`` = the update id — the numeric key the sync runner+already advances (the jarvis-conversations connector uses the same one) — so+a numeric checkpoint becomes ``offset = cursor + 1``. A non-numeric backfill+checkpoint is not a position in a replayable stream (the stream is gone) and+degrades to "whatever Telegram still holds unconfirmed", which is exactly+the un-imported remainder. Bodies are capped near 1 MB with a truncation+marker, far above Telegram's own 4096-character message ceiling.++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. The token is part of every Bot-API URL, so error paths repeat only an+exception's TYPE, never its text, and never a URL.+"""++from __future__ import annotations++import asyncio+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",+ "TelegramAdapterError",+ "telegram_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:telegram"++_API = "https://api.telegram.org"++#: ``getUpdates`` returns at most 100 updates per call.+_PAGE_LIMIT = 100++#: Uniform adapter contract; Telegram's own 4096-char message cap sits far+#: below it, so this is a guard rail, not an expected path.+_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_MARKER = "\n\n[truncated near 1 MB — the rest stays on Telegram]"++#: Bounded politeness for 429s (see the Discord adapter for the rationale).+_RETRY_MAX = 3+_RETRY_WAIT_CAP_S = 15.0++_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)++#: The update kinds that carry a message payload. ``allowed_updates`` is+#: deliberately NOT sent: it changes the bot's subscription persistently and+#: would strip the Telegram chat channel of the update kinds IT needs.+_MESSAGE_KEYS: tuple[tuple[str, bool], ...] = (+ ("message", False),+ ("edited_message", True),+ ("channel_post", False),+ ("edited_channel_post", True),+)+++class TelegramAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Telegram bot token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("telegram")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise TelegramAdapterError(+ "The Telegram connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise TelegramAdapterError(+ "Telegram is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise TelegramAdapterError(+ "The Telegram connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _retry_after_seconds(response: httpx.Response) -> float:+ """The server's requested wait, bounded to a sane ceiling."""+ value: float | None = None+ header = response.headers.get("retry-after", "")+ if header:+ try:+ value = float(header)+ except ValueError:+ value = None+ if value is None:+ try:+ payload = response.json() or {}+ value = float((payload.get("parameters") or {}).get("retry_after"))+ except Exception: # noqa: BLE001 — a non-JSON 429 body means "use the default"+ value = None+ if value is None:+ value = 1.0+ return min(max(value, 0.0), _RETRY_WAIT_CAP_S)+++async def _call(+ client: httpx.AsyncClient,+ token: str,+ method: str,+ params: dict[str, Any] | None = None,+) -> Any:+ """One Bot-API call, every failure mapped to a sentence a user can act on.++ The token lives in the URL, so no branch below may repeat a URL or an+ exception's text — only types and Telegram's own ``description`` field+ (which never contains the token).+ """+ url = f"{_API}/bot{token}/{method}"+ response: httpx.Response | None = None+ for attempt in range(_RETRY_MAX + 1):+ try:+ response = await client.get(url, params=params)+ except httpx.HTTPError as exc:+ raise TelegramAdapterError(+ f"Telegram was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code == 429 and attempt < _RETRY_MAX:+ await asyncio.sleep(_retry_after_seconds(response))+ continue+ break+ assert response is not None # the loop always runs at least once+ if response.status_code in (401, 403):+ raise TelegramAdapterError(+ "Telegram rejected the bot token. Reconnect it in the Plugins store."+ )+ if response.status_code == 409:+ raise TelegramAdapterError(+ "Another consumer is reading this bot's updates (the Telegram chat "+ "channel or a webhook). Telegram allows only one reader at a time — "+ "the import can only run while that consumer is idle."+ )+ if response.status_code == 429:+ raise TelegramAdapterError(+ "Telegram's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ try:+ payload = response.json() or {}+ except Exception: # noqa: BLE001 — a non-JSON answer is an API failure+ payload = {}+ if response.status_code >= 400 or not payload.get("ok"):+ description = str(payload.get("description") or "").strip()+ raise TelegramAdapterError(+ f"Telegram answered: {description or f'HTTP {response.status_code}'}"+ )+ return payload.get("result")+++def _checkpoint_to_offset(checkpoint: str | None) -> int | None:+ """A numeric checkpoint (the runner's ``max_rowid`` cursor) as the next+ ``getUpdates`` offset. Anything else — including a backfill resume+ ``external_id`` — means "no offset": Telegram then serves every update it+ still holds unconfirmed, which IS the un-imported remainder.+ """+ if not checkpoint:+ return None+ try:+ cursor = int(checkpoint)+ except ValueError:+ return None+ if cursor <= 0:+ return None+ return cursor + 1+++def _iso_from_unix(seconds: int) -> str:+ return datetime.fromtimestamp(seconds, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _chat_label(chat: dict[str, Any]) -> str:+ title = str(chat.get("title") or "").strip()+ if title:+ return title+ name = " ".join(+ part+ for part in (+ str(chat.get("first_name") or "").strip(),+ str(chat.get("last_name") or "").strip(),+ )+ if part+ )+ if name:+ return name+ username = str(chat.get("username") or "").strip()+ if username:+ return f"@{username}"+ return f"chat {chat.get('id')}"+++def _author_of(message: dict[str, Any], chat: dict[str, Any]) -> str:+ sender = message.get("from")+ if isinstance(sender, dict):+ name = " ".join(+ part+ for part in (+ str(sender.get("first_name") or "").strip(),+ str(sender.get("last_name") or "").strip(),+ )+ if part+ )+ if name:+ return name+ username = str(sender.get("username") or "").strip()+ if username:+ return f"@{username}"+ signature = str(message.get("author_signature") or "").strip()+ if signature:+ return signature+ return _chat_label(chat) # channel posts carry no sender+++def _permalink_for(chat: dict[str, Any], message_id: int) -> str:+ """The deepest link Telegram offers for this chat kind.++ Public chats get a real ``t.me`` URL; private supergroups/channels get+ the members-only ``t.me/c/`` form; private and small-group chats have no+ web URL at all, so the ``tg://`` app link is the honest deepest link —+ it resolves inside a logged-in Telegram app, nowhere else.+ """+ username = str(chat.get("username") or "").strip()+ if username:+ return f"https://t.me/{username}/{message_id}"+ chat_id = str(chat.get("id") or "")+ if chat_id.startswith("-100"):+ return f"https://t.me/c/{chat_id[4:]}/{message_id}"+ if str(chat.get("type") or "") == "private":+ return f"tg://openmessage?user_id={chat_id}&message_id={message_id}"+ return f"tg://openmessage?chat_id={chat_id.lstrip('-')}&message_id={message_id}"+++def _message_text(message: dict[str, Any]) -> str:+ """The message's prose plus honest placeholders for undownloaded media."""+ parts: list[str] = []+ text = str(message.get("text") or message.get("caption") or "").strip()+ if text:+ parts.append(text)+ if message.get("photo"):+ parts.append("[photo]")+ document = message.get("document")+ if isinstance(document, dict):+ name = str(document.get("file_name") or "").strip()+ parts.append(f"[file: {name}]" if name else "[file]")+ for kind in ("voice", "video", "audio", "video_note"):+ if message.get(kind):+ parts.append(f"[{kind.replace('_', ' ')}]")+ return " ".join(parts)+++def _item_from_message(+ message: dict[str, Any], *, update_id: int, edited: bool+) -> RawItem | None:+ """One update's message as a ``RawItem``; ``None`` when it holds no text."""+ chat = message.get("chat")+ message_id = message.get("message_id")+ date = int(message.get("date") or 0)+ if not isinstance(chat, dict) or message_id is None or date <= 0:+ return None+ text = _message_text(message)+ if not text:+ return None # stickers, joins, service messages — nothing to remember++ chat_id = str(chat.get("id") or "")+ label = _chat_label(chat)+ author = _author_of(message, chat)+ header = f"{label} · {author}" + (" · edited" if edited else "")+ body = f"{header}\n\n{text}"+ if len(body) > _MAX_BODY_CHARS:+ body = body[:_MAX_BODY_CHARS] + _TRUNCATION_MARKER++ return RawItem(+ external_id=f"msg:{chat_id}:{message_id}",+ title=f"{author} in {label}",+ body=body,+ permalink=_permalink_for(chat, int(message_id)),+ # WHEN IT WAS SAID — an edit updates the body, not the moment.+ timestamp_utc=_iso_from_unix(date),+ thread_key=f"chat:{chat_id}",+ author_raw=author,+ metadata={+ # The runner advances the cursor on this key (max update id).+ "max_rowid": update_id,+ "chat_id": chat_id,+ "chat_type": str(chat.get("type") or ""),+ "chat_title": label,+ "message_id": int(message_id),+ "edited": edited,+ },+ )+++def _item_from_update(update: dict[str, Any]) -> RawItem | None:+ try:+ update_id = int(update.get("update_id") or 0)+ except (TypeError, ValueError):+ return None+ if update_id <= 0:+ return None+ for key, edited in _MESSAGE_KEYS:+ message = update.get(key)+ if isinstance(message, dict):+ return _item_from_message(message, update_id=update_id, edited=edited)+ return None # callback queries, member events, ... — not memory material+++async def telegram_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every message update the bot currently holds, oldest first.++ ``checkpoint`` numeric = the runner's update-id cursor (continue after+ it); anything else = read whatever Telegram still holds unconfirmed.+ ``transport`` is a test seam; production leaves it ``None``.+ """+ token = _token()+ offset = _checkpoint_to_offset(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ # Fail fast and honestly on a dead token, before touching the queue.+ await _call(client, token, "getMe")+ while True:+ params: dict[str, Any] = {"limit": _PAGE_LIMIT, "timeout": 0}+ if offset is not None:+ params["offset"] = offset+ updates = await _call(client, token, "getUpdates", params)+ if not isinstance(updates, list) or not updates:+ break+ highest = 0+ for update in updates:+ if not isinstance(update, dict):+ continue+ try:+ highest = max(highest, int(update.get("update_id") or 0))+ except (TypeError, ValueError):+ pass+ item = _item_from_update(update)+ if item is not None:+ yielded += 1+ yield item+ if highest <= 0:+ break+ offset = highest + 1+ if len(updates) < _PAGE_LIMIT:+ break # the queue is drained++ log.info(+ "Telegram adapter: yielded %d item(s) for %s (forward capture%s)",+ yielded,+ ctx.source_id,+ ", resumed from cursor" if offset is not None and checkpoint else "",+ )diff --git a/jarvis/ultrawiki/adapters/todoist.py b/jarvis/ultrawiki/adapters/todoist.pynew file mode 100644index 0000000000..b3245e36ac--- /dev/null+++ b/jarvis/ultrawiki/adapters/todoist.py@@ -0,0 +1,434 @@+"""Todoist pull adapter — the full task snapshot plus completed history.++Scope, honestly stated. One Sync-API request returns EVERY active task the+account holds, with its project names, comments ("notes") and collaborator+names in the same payload — no per-task requests at all. A second, paginated+walk over ``completed/get_all`` adds the completed history, as far back as+the user's Todoist plan retains it (free plans keep less history than Pro;+the adapter imports whatever the endpoint yields and cannot reach past that).+Deleted tasks are skipped, not tombstoned — the bridge does not reconcile+deletes for this source. File attachments on comments are never downloaded;+only their text survives, which is what a memory is for.++Structural limits, stated plainly: the Sync API gives active tasks NO+modification timestamp, so a numeric cursor cannot narrow the read — every+run is a full snapshot, which costs one request plus the completed walk and+upserts unchanged items as ``unchanged``. ``metadata["mtime_ns"]`` is+therefore the best honest signal (the newest of creation, completion and+latest comment), not a true modified time. The API also provides no web URL+per task; the permalink is the canonical ``app.todoist.com`` task address.++Cursor convention: a ``task:<id>`` checkpoint is the bridge's backfill resume+marker — items stream oldest-to-newest deterministically, so the walk resumes+strictly after that id. A numeric checkpoint (the runner's nanosecond cursor)+is accepted but, per the limit above, still yields the full snapshot. Any+other non-empty checkpoint is treated as a Todoist ``sync_token`` and asked+as an incremental delta; a token the server rejects falls back to a full+snapshot rather than failing the sync.++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 asyncio+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",+ "TodoistAdapterError",+ "item_from_task",+ "todoist_pull_adapter",+]++#: The plugin-bridge candidate id this adapter serves.+INTEGRATION_ID = "plugin:todoist"++_API = "https://api.todoist.com/sync/v9"++_RESOURCE_TYPES = '["projects","items","notes","collaborators"]'++#: completed/get_all pages at up to 200 rows; 200 pages bounds the walk at+#: 40 000 completed tasks per sync — the next sync continues from the cursor.+_COMPLETED_PAGE = 200+_MAX_COMPLETED_PAGES = 200++_TIMEOUT = httpx.Timeout(connect=5.0, read=25.0, write=10.0, pool=5.0)++_MAX_ATTEMPTS = 3+_RETRY_WAIT_CAP = 30.0+_DEFAULT_RETRY_WAIT = 2.0++_MAX_BODY_CHARS = 1_000_000+_TRUNCATION_NOTE = "\n\n[truncated — the full text lives at the link above]"+++class TodoistAdapterError(RuntimeError):+ """A pull step failed. The message is safe to show and never holds the token."""+++def _token() -> str:+ """The marketplace Todoist token, or an honest refusal."""+ from jarvis.marketplace.token_store import TokenStore # noqa: PLC0415 — lazy++ try:+ tokens = TokenStore().load("todoist")+ except Exception as exc: # noqa: BLE001 — a locked keyring is not a crash+ raise TodoistAdapterError(+ "The Todoist connection could not be read from this machine's "+ "credential store."+ ) from exc+ if tokens is None:+ raise TodoistAdapterError(+ "Todoist is not connected. Connect it in the Plugins store first."+ )+ if tokens.needs_reauth or not tokens.access:+ raise TodoistAdapterError(+ "The Todoist connection expired. Reconnect it in the Plugins store."+ )+ return str(tokens.access)+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def _retry_wait(response: httpx.Response | None) -> float:+ if response is None:+ return 0.0+ header = str(response.headers.get("Retry-After") or "").strip()+ try:+ wait = float(header)+ except ValueError:+ wait = _DEFAULT_RETRY_WAIT+ return min(max(wait, 0.0), _RETRY_WAIT_CAP)+++async def _request(+ client: httpx.AsyncClient,+ method: str,+ url: str,+ token: str,+ *,+ params: dict[str, Any] | None = None,+ data: dict[str, Any] | None = None,+ tolerate_400: bool = False,+) -> httpx.Response | None:+ """One round trip, every failure mapped to an actionable sentence.++ ``tolerate_400`` returns ``None`` on HTTP 400 instead of raising — the+ seam for a stale ``sync_token`` the caller wants to retry as a full read.+ """+ response: httpx.Response | None = None+ for attempt in range(_MAX_ATTEMPTS):+ if attempt:+ await asyncio.sleep(_retry_wait(response))+ try:+ response = await client.request(+ method, url, headers=_headers(token), params=params, data=data+ )+ except httpx.HTTPError as exc:+ raise TodoistAdapterError(+ f"Todoist was unreachable ({type(exc).__name__}). Check this "+ "machine's internet connection."+ ) from exc+ if response.status_code != 429:+ break+ if response is None: # pragma: no cover - loop always runs at least once+ raise TodoistAdapterError("Todoist answered nothing for this request.")+ if response.status_code in (401, 403):+ raise TodoistAdapterError(+ "Todoist rejected the connection. Reconnect it in the Plugins store."+ )+ if response.status_code == 429:+ raise TodoistAdapterError(+ "Todoist's rate limit is exhausted. The next sync continues where "+ "this one stopped."+ )+ if response.status_code == 400 and tolerate_400:+ return None+ if response.status_code >= 400:+ raise TodoistAdapterError(+ f"Todoist answered HTTP {response.status_code} for this request."+ )+ return response+++def _resume_marker(checkpoint: str | None) -> str:+ """The checkpoint as a backfill resume id (``task:<id>``), or empty."""+ if checkpoint and checkpoint.startswith("task:"):+ return checkpoint+ return ""+++def _sync_token_of(checkpoint: str | None) -> str:+ """A checkpoint that is neither numeric nor a resume id is a sync token."""+ if not checkpoint or checkpoint.startswith("task:"):+ return ""+ try:+ int(checkpoint)+ except (TypeError, ValueError):+ return checkpoint+ return ""+++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 _cap(text: str) -> str:+ if len(text) <= _MAX_BODY_CHARS:+ return text+ return text[:_MAX_BODY_CHARS] + _TRUNCATION_NOTE+++def _comment_lines(notes: list[dict[str, Any]]) -> tuple[list[str], str]:+ """One task's notes as chronological body lines, plus the newest post time.++ Attachment files are never downloaded; only the note's text survives.+ """+ rows: list[tuple[str, str]] = []+ for note in notes:+ if not isinstance(note, dict) or note.get("is_deleted"):+ continue+ text = str(note.get("content") or "").strip()+ if not text:+ continue+ posted = str(note.get("posted_at") or "")+ rows.append((posted, f"[{posted}] {text}" if posted else text))+ rows.sort(key=lambda pair: pair[0])+ latest = rows[-1][0] if rows else ""+ return [line for _posted, line in rows], latest+++def item_from_task(+ task: dict[str, Any],+ *,+ project_name: str,+ project_id: str,+ assignee: str,+ comments: list[str],+ last_comment_at: str = "",+) -> RawItem | None:+ """One Todoist task as a ``RawItem``; ``None`` when it is unusable."""+ task_id = str(task.get("id") or "")+ title = str(task.get("content") or "").strip()+ if not task_id or not title:+ return None++ state = "completed" if task.get("checked") else "open"+ due = str((task.get("due") or {}).get("date") or "") if task.get("due") else ""+ created = str(task.get("added_at") or "")+ completed_at = str(task.get("completed_at") or "")++ header_parts = [part for part in (project_name, "task", state) if part]+ if assignee:+ header_parts.append(f"assigned to {assignee}")+ if due:+ header_parts.append(f"due {due}")+ header = " · ".join(header_parts)++ body_text = str(task.get("description") or "").strip()+ if comments:+ body_text += ("\n\n" if body_text else "") + "Comments:\n" + "\n".join(comments)++ # The newest signal the API exposes — creation, completion or the latest+ # comment. NOT a true modified time; the Sync API does not provide one.+ mtime_ns = max(_to_ns(created), _to_ns(completed_at), _to_ns(last_comment_at))++ return RawItem(+ external_id=f"task:{task_id}",+ title=title,+ body=_cap(f"{header}\n\n{body_text}".strip()),+ # The Sync API carries no web URL; this is the canonical task address.+ permalink=f"https://app.todoist.com/app/task/{task_id}",+ timestamp_utc=created or completed_at,+ thread_key=project_id,+ author_raw=assignee,+ metadata={+ "mtime_ns": mtime_ns,+ "state": state,+ "project": project_id,+ "due": due,+ "comments": len(comments),+ "completed_at": completed_at,+ },+ )+++async def _sync_payload(+ client: httpx.AsyncClient, token: str, sync_token: str+) -> dict[str, Any] | None:+ """One Sync-API read; ``None`` when the server rejected a stale token."""+ response = await _request(+ client,+ "POST",+ f"{_API}/sync",+ token,+ data={"sync_token": sync_token, "resource_types": _RESOURCE_TYPES},+ # "*" is Todoist's "give me everything" sentinel and sync_token is its+ # PAGINATION cursor — neither is a credential; the names merely collide+ # with the hardcoded-secret heuristic.+ tolerate_400=sync_token != "*", # noqa: S105+ )+ if response is None:+ return None+ payload = response.json() or {}+ return payload if isinstance(payload, dict) else {}+++async def _completed_rows(+ client: httpx.AsyncClient, token: str+) -> list[dict[str, Any]]:+ """Every completed task the plan's history retains, oldest data included."""+ rows: list[dict[str, Any]] = []+ for page in range(_MAX_COMPLETED_PAGES):+ response = await _request(+ client,+ "GET",+ f"{_API}/completed/get_all",+ token,+ params={+ "limit": _COMPLETED_PAGE,+ "offset": page * _COMPLETED_PAGE,+ "annotate_items": "true",+ "annotate_notes": "true",+ },+ )+ payload = (response.json() or {}) if response is not None else {}+ page_rows = payload.get("items")+ if not isinstance(page_rows, list) or not page_rows:+ break+ rows.extend(row for row in page_rows if isinstance(row, dict))+ if len(page_rows) < _COMPLETED_PAGE:+ break+ if page == _MAX_COMPLETED_PAGES - 1:+ log.info(+ "Todoist adapter: stopping the completed walk at %d pages; "+ "the next sync resumes from the cursor",+ _MAX_COMPLETED_PAGES,+ )+ return rows+++async def todoist_pull_adapter(+ ctx: ConnectorContext,+ checkpoint: str | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+) -> AsyncIterator[RawItem]:+ """Yield every task the connected Todoist account can list.++ ``checkpoint`` handling is described in the module docstring.+ ``transport`` is a test seam; production leaves it ``None``.+ """+ token = _token()+ resume_after = _resume_marker(checkpoint)+ sync_token = _sync_token_of(checkpoint)+ yielded = 0++ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:+ incremental = bool(sync_token)+ payload = await _sync_payload(client, token, sync_token or "*")+ if payload is None:+ # A stale sync token must degrade to a full read, never fail.+ incremental = False+ payload = await _sync_payload(client, token, "*") or {}++ projects = {+ str(row.get("id") or ""): str(row.get("name") or "")+ for row in payload.get("projects") or []+ if isinstance(row, dict)+ }+ people = {+ str(row.get("id") or ""): str(row.get("full_name") or "")+ for row in payload.get("collaborators") or []+ if isinstance(row, dict)+ }+ notes_by_task: dict[str, list[dict[str, Any]]] = {}+ for note in payload.get("notes") or []:+ if isinstance(note, dict):+ notes_by_task.setdefault(str(note.get("item_id") or ""), []).append(note)++ items: list[RawItem] = []+ seen: set[str] = set()++ def note_task(task: dict[str, Any], extra_notes: list[dict[str, Any]]) -> None:+ task_id = str(task.get("id") or "")+ external_id = f"task:{task_id}"+ if not task_id or external_id in seen:+ return+ project_id = str(task.get("project_id") or "")+ assignee = people.get(str(task.get("responsible_uid") or ""), "")+ comments, last_comment_at = _comment_lines(+ notes_by_task.get(task_id, []) + extra_notes+ )+ item = item_from_task(+ task,+ project_name=projects.get(project_id, ""),+ project_id=project_id,+ assignee=assignee,+ comments=comments,+ last_comment_at=last_comment_at,+ )+ if item is not None:+ seen.add(external_id)+ items.append(item)++ for task in payload.get("items") or []:+ if not isinstance(task, dict) or task.get("is_deleted"):+ continue+ note_task(task, [])++ # An incremental delta already carries completed transitions as items+ # with ``checked``; only a full snapshot needs the history walk.+ if not incremental:+ for row in await _completed_rows(client, token):+ annotated = row.get("item_object")+ task = dict(annotated) if isinstance(annotated, dict) else {+ "id": str(row.get("task_id") or ""),+ "content": str(row.get("content") or ""),+ "project_id": str(row.get("project_id") or ""),+ }+ task.setdefault("checked", True)+ task.setdefault("completed_at", str(row.get("completed_at") or ""))+ extra = [n for n in row.get("notes") or [] if isinstance(n, dict)]+ note_task(task, extra)++ items.sort(key=lambda item: (item.timestamp_utc, item.external_id))+ start = 0+ if resume_after:+ for index, item in enumerate(items):+ if item.external_id == resume_after:+ start = index + 1+ break++ for item in items[start:]:+ yielded += 1+ yield item++ log.info(+ "Todoist adapter: yielded %d item(s) for %s (%s)",+ yielded,+ ctx.source_id,+ "incremental" if incremental else "backfill",+ )diff --git a/tests/unit/ultrawiki/adapters/__init__.py b/tests/unit/ultrawiki/adapters/__init__.pynew file mode 100644index 0000000000..02cdeeca09--- /dev/null+++ b/tests/unit/ultrawiki/adapters/__init__.py@@ -0,0 +1 @@+"""Tests for the UltraWiki pull adapters (one file per integration)."""diff --git a/tests/unit/ultrawiki/adapters/test_airtable.py b/tests/unit/ultrawiki/adapters/test_airtable.pynew file mode 100644index 0000000000..82c90172ba--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_airtable.py@@ -0,0 +1,425 @@+"""The Airtable pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: a stable+composite id (``<base>:<table>:<record>`` — a re-run must upsert, not+duplicate), a real deep link on every record, fields flattened in the table's+own schema order, attachments listed by name and URL but never downloaded,+a deterministic external-id order so the backfill checkpoint resumes strictly+after the last persisted id, honest full-rescan freshness (Airtable has no+global modified-since filter), and failure messages a user can act on that+never carry the token.+"""++from __future__ import annotations++from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import airtable as at+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Airtable plugin, without touching the host's keyring."""++ class _Tokens:+ access = "pat-airtable-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-airtable",+ config={"integration_id": "plugin:airtable"},+ secret_get=lambda _name: None,+ )+++def _base(base_id: str = "appBASE01", name: str = "Product") -> dict[str, Any]:+ return {"id": base_id, "name": name, "permissionLevel": "read"}+++def _table(+ table_id: str = "tblT01",+ name: str = "Ideas",+ fields: list[dict[str, Any]] | None = None,+) -> dict[str, Any]:+ if fields is None:+ fields = [+ {"id": "fldName", "name": "Name", "type": "singleLineText"},+ {"id": "fldNotes", "name": "Notes", "type": "multilineText"},+ ]+ return {+ "id": table_id,+ "name": name,+ "primaryFieldId": fields[0]["id"] if fields else "",+ "fields": fields,+ }+++def _record(+ record_id: str = "rec01",+ fields: dict[str, Any] | None = None,+ created: str = "2026-03-01T10:00:00Z",+) -> dict[str, Any]:+ return {+ "id": record_id,+ "createdTime": created,+ "fields": fields if fields is not None else {"Name": "Wake-word fix"},+ }+++def _transport(+ bases: list[dict[str, Any]],+ tables: dict[str, Any],+ records: dict[str, Any],+ *,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """Serve the three Airtable endpoints from plain dicts.++ ``tables`` maps a base id to its table list (or an int HTTP status to+ answer with); ``records`` maps ``"<base>/<table>"`` to a record list (or a+ status). Offset paging gets its own handlers in the tests that pin it.+ """++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/v0/meta/bases":+ return httpx.Response(200, json={"bases": bases})+ parts = path.strip("/").split("/")+ if len(parts) == 5 and parts[:3] == ["v0", "meta", "bases"] and parts[4] == "tables":+ payload = tables.get(parts[3])+ if isinstance(payload, int):+ return httpx.Response(payload, json={})+ return httpx.Response(200, json={"tables": payload or []})+ if len(parts) == 3 and parts[0] == "v0":+ payload = records.get(f"{parts[1]}/{parts[2]}")+ if isinstance(payload, int):+ return httpx.Response(payload, json={})+ return httpx.Response(200, json={"records": payload or []})+ return httpx.Response(404, json={})++ return httpx.MockTransport(handler)+++async def _collect(checkpoint: str | None = None, **kwargs: Any) -> list:+ return [+ item+ async for item in at.airtable_pull_adapter(_ctx(), checkpoint, **kwargs)+ ]+++async def test_a_record_becomes_a_linkable_dated_item():+ transport = _transport(+ [_base()],+ {"appBASE01": [_table()]},+ {"appBASE01/tblT01": [_record(fields={"Name": "Wake-word fix", "Notes": "Ship it"})]},+ )+ items = await _collect(transport=transport)+ 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 == "appBASE01:tblT01:rec01"+ # Evidence has to lead back to where it lives — the record's deep link.+ assert item.permalink == "https://airtable.com/appBASE01/tblT01/rec01"+ assert item.timestamp_utc == "2026-03-01T10:00:00Z"+ assert item.title == "Wake-word fix"+ assert item.thread_key == "appBASE01:tblT01"+ assert "Product · Ideas · record" in item.body+ assert "Name: Wake-word fix" in item.body+ assert "Notes: Ship it" in item.body+ assert item.metadata["mtime_ns"] == at._to_ns("2026-03-01T10:00:00Z")+++async def test_fields_follow_the_tables_own_schema_order():+ """The schema order is the one the user arranged and reads the record in;+ keys the schema does not know follow, sorted."""+ fields = [+ {"id": "fldA", "name": "Alpha", "type": "singleLineText"},+ {"id": "fldB", "name": "Beta", "type": "singleLineText"},+ ]+ record = _record(fields={"Zulu": "last", "Beta": "two", "Alpha": "one", "Mike": "extra"})+ transport = _transport(+ [_base()],+ {"appBASE01": [_table(fields=fields)]},+ {"appBASE01/tblT01": [record]},+ )+ items = await _collect(transport=transport)+ lines = items[0].body.splitlines()+ assert lines[2:] == ["Alpha: one", "Beta: two", "Mike: extra", "Zulu: last"]+++async def test_attachments_are_listed_by_name_and_url_never_downloaded():+ seen: list[httpx.Request] = []+ fields = [+ {"id": "fldName", "name": "Name", "type": "singleLineText"},+ {"id": "fldFiles", "name": "Files", "type": "multipleAttachments"},+ ]+ record = _record(+ fields={+ "Name": "Spec",+ "Files": [+ {"filename": "photo.jpg", "url": "https://dl.airtable.com/photo.jpg", "size": 9}+ ],+ }+ )+ transport = _transport(+ [_base()],+ {"appBASE01": [_table(fields=fields)]},+ {"appBASE01/tblT01": [record]},+ seen=seen,+ )+ items = await _collect(transport=transport)+ assert "Files: photo.jpg (https://dl.airtable.com/photo.jpg)" in items[0].body+ # Listed, never fetched: every request stayed on the Airtable API host.+ assert all(request.url.host == "api.airtable.com" for request in seen)+++async def test_a_tracked_modified_time_wins_over_created_time():+ fields = [+ {"id": "fldName", "name": "Name", "type": "singleLineText"},+ {"id": "fldMod", "name": "Last touched", "type": "lastModifiedTime"},+ ]+ record = _record(fields={"Name": "x", "Last touched": "2026-03-05T09:00:00Z"})+ transport = _transport(+ [_base()],+ {"appBASE01": [_table(fields=fields)]},+ {"appBASE01/tblT01": [record]},+ )+ items = await _collect(transport=transport)+ assert items[0].timestamp_utc == "2026-03-05T09:00:00Z"+ assert items[0].metadata["modified_time"] == "2026-03-05T09:00:00Z"+ assert items[0].metadata["created_time"] == "2026-03-01T10:00:00Z"+ assert items[0].metadata["mtime_ns"] == at._to_ns("2026-03-05T09:00:00Z")+++async def test_values_render_human_readably():+ fields = [+ {"id": "fldName", "name": "Name", "type": "singleLineText"},+ {"id": "fldDone", "name": "Done", "type": "checkbox"},+ {"id": "fldOwner", "name": "Owner", "type": "singleCollaborator"},+ {"id": "fldTags", "name": "Tags", "type": "multipleSelects"},+ ]+ record = _record(+ fields={+ "Name": "x",+ "Done": True,+ "Owner": {"id": "usr1", "email": "[email protected]", "name": "Ana"},+ "Tags": ["a", "b"],+ }+ )+ transport = _transport(+ [_base()],+ {"appBASE01": [_table(fields=fields)]},+ {"appBASE01/tblT01": [record]},+ )+ items = await _collect(transport=transport)+ assert "Done: yes" in items[0].body+ assert "Owner: Ana" in items[0].body+ assert "Tags: a, b" in items[0].body+++async def test_a_record_with_an_empty_primary_field_still_gets_a_title():+ transport = _transport(+ [_base()],+ {"appBASE01": [_table()]},+ {"appBASE01/tblT01": [_record(fields={})]},+ )+ items = await _collect(transport=transport)+ assert items[0].title == "Ideas record rec01"+ assert items[0].body == "Product · Ideas · record"+++async def test_offset_paging_walks_every_base_and_record_page():+ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == "/v0/meta/bases":+ if request.url.params.get("offset") == "b2":+ return httpx.Response(200, json={"bases": [_base("appB", "Second")]})+ return httpx.Response(+ 200, json={"bases": [_base("appA", "First")], "offset": "b2"}+ )+ if path.endswith("/tables"):+ return httpx.Response(200, json={"tables": [_table()]})+ if request.url.params.get("offset") == "r2":+ return httpx.Response(200, json={"records": [_record("rec02")]})+ assert request.url.params.get("pageSize") == "100"+ return httpx.Response(200, json={"records": [_record("rec01")], "offset": "r2"})++ items = await _collect(transport=httpx.MockTransport(handler))+ assert [item.external_id for item in items] == [+ "appA:tblT01:rec01",+ "appA:tblT01:rec02",+ "appB:tblT01:rec01",+ "appB:tblT01:rec02",+ ]+++async def test_the_walk_is_sorted_by_external_id():+ """Registry order is whatever the API returns; the yield order must be the+ one order the checkpoint can resume from."""+ transport = _transport(+ [_base("appB"), _base("appA")],+ {"appB": [_table("tblZ")], "appA": [_table("tblM"), _table("tblA")]},+ {+ "appB/tblZ": [_record("rec1")],+ "appA/tblM": [_record("rec2"), _record("rec1")],+ "appA/tblA": [_record("rec9")],+ },+ )+ items = await _collect(transport=transport)+ ids = [item.external_id for item in items]+ assert ids == sorted(ids)+ assert ids[0] == "appA:tblA:rec9"+ assert len(ids) == 4+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ seen: list[httpx.Request] = []+ transport = _transport(+ [_base("appA")],+ {"appA": [_table("tbl0"), _table("tbl1"), _table("tbl2")]},+ {+ "appA/tbl0": [_record("rec1")],+ "appA/tbl1": [_record("rec1"), _record("rec2"), _record("rec3")],+ "appA/tbl2": [_record("rec1")],+ },+ seen=seen,+ )+ items = await _collect(checkpoint="appA:tbl1:rec2", transport=transport)+ assert [item.external_id for item in items] == ["appA:tbl1:rec3", "appA:tbl2:rec1"]+ # A table whose every record sorts before the checkpoint is skipped+ # without a single records request.+ assert "/v0/appA/tbl0" not in [request.url.path for request in seen]+++async def test_a_numeric_cursor_is_honestly_a_full_rescan():+ """Airtable's list API has no global modified-since filter, so a numeric+ cursor cannot narrow the walk server-side; mis-filtering would silently+ lose records. It deliberately reads as a full rescan — the idempotent+ upserts make that correct."""+ transport = _transport(+ [_base()],+ {"appBASE01": [_table()]},+ {"appBASE01/tblT01": [_record()]},+ )+ cursor = str(at._to_ns("2026-03-04T12:00:00Z"))+ items = await _collect(checkpoint=cursor, transport=transport)+ assert [item.external_id for item in items] == ["appBASE01:tblT01:rec01"]+++async def test_a_denied_base_is_skipped_not_fatal():+ """A missing scope on ONE base must not abandon everything the token CAN+ read."""+ transport = _transport(+ [_base("appA"), _base("appB")],+ {"appA": 403, "appB": [_table()]},+ {"appB/tblT01": [_record()]},+ )+ items = await _collect(transport=transport)+ assert [item.external_id for item in items] == ["appB:tblT01:rec01"]+++async def test_a_denied_table_is_skipped_not_fatal():+ transport = _transport(+ [_base("appA")],+ {"appA": [_table("tblA"), _table("tblB")]},+ {"appA/tblA": 403, "appA/tblB": [_record()]},+ )+ items = await _collect(transport=transport)+ assert [item.external_id for item in items] == ["appA:tblB:rec01"]+++async def test_a_rate_limited_request_waits_and_retries_bounded():+ attempts = {"count": 0}++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path == "/v0/meta/bases":+ attempts["count"] += 1+ if attempts["count"] == 1:+ return httpx.Response(429, headers={"Retry-After": "0"})+ return httpx.Response(200, json={"bases": [_base()]})+ if request.url.path.endswith("/tables"):+ return httpx.Response(200, json={"tables": [_table()]})+ return httpx.Response(200, json={"records": [_record()]})++ items = await _collect(transport=httpx.MockTransport(handler))+ assert attempts["count"] == 2+ assert len(items) == 1+++async def test_a_pathological_long_text_field_is_truncated_with_a_marker():+ huge = "x" * (at._MAX_BODY_BYTES + 100_000)+ transport = _transport(+ [_base()],+ {"appBASE01": [_table()]},+ {"appBASE01/tblT01": [_record(fields={"Name": "big", "Notes": huge})]},+ )+ items = await _collect(transport=transport)+ assert len(items) == 1+ body = items[0].body+ assert body.endswith(at._TRUNCATION_MARKER)+ marker_bytes = len(at._TRUNCATION_MARKER.encode("utf-8"))+ assert len(body.encode("utf-8")) <= at._MAX_BODY_BYTES + marker_bytes+++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, json={"error": {"type": "AUTHENTICATION_REQUIRED"}})++ with pytest.raises(at.AirtableAdapterError) as excinfo:+ await _collect(transport=httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "pat-airtable-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(at.AirtableAdapterError, match="not connected"):+ await _collect(transport=_transport([], {}, {}))+++async def test_an_expired_connection_is_named_as_such(monkeypatch):+ class _Tokens:+ access = "pat-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(at.AirtableAdapterError, match="expired"):+ await _collect(transport=_transport([], {}, {}))+++def test_the_integration_id_matches_the_curated_catalog():+ """The adapter must register under the id the picker actually routes."""+ from jarvis.ultrawiki import connector_catalog++ spec = connector_catalog.bridge_entry_for(at.INTEGRATION_ID)+ assert spec is not None+ assert spec.id == "airtable"diff --git a/tests/unit/ultrawiki/adapters/test_asana.py b/tests/unit/ultrawiki/adapters/test_asana.pynew file mode 100644index 0000000000..10e86c2831--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_asana.py@@ -0,0 +1,338 @@+"""The Asana pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-task ids (a re-run must upsert, not duplicate), a real deep link on every+item, deterministic oldest-to-newest streaming so the backfill checkpoint can+resume strictly after an id, comment stories folded chronologically, bounded+429 handling, 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 asana as asn+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Asana plugin, without touching the host's keyring."""++ class _Tokens:+ access = "asana-test-token"+ 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-asana",+ config={"integration_id": "plugin:asana"},+ secret_get=lambda _name: None,+ )+++def _task(gid: str = "t1", **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "gid": gid,+ "name": "Ship the wake-word fix",+ "notes": "The wake word misses every third call.",+ "completed": False,+ "created_at": "2026-03-01T10:00:00.000Z",+ "modified_at": "2026-03-04T12:00:00.000Z",+ "due_on": "2026-04-01",+ "assignee": {"name": "Alice"},+ "created_by": {"name": "Bob"},+ "permalink_url": f"https://app.asana.com/0/p1/{gid}",+ }+ base.update(overrides)+ return base+++def _story(iso: str, text: str, author: str = "Alice", subtype: str = "comment_added"):+ return {+ "created_at": iso,+ "created_by": {"name": author},+ "resource_subtype": subtype,+ "text": text,+ }+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _transport(+ *,+ workspaces: list[dict[str, Any]] | None = None,+ projects: dict[str, list[dict[str, Any]]] | None = None,+ project_tasks: dict[str, list[dict[str, Any]]] | None = None,+ my_tasks: dict[str, list[dict[str, Any]]] | None = None,+ stories: dict[str, list[dict[str, Any]]] | None = None,+ rate_limit_first: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Asana account: dispatches by REST path."""+ remaining_429 = {"n": rate_limit_first}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ path = request.url.path+ params = request.url.params+ if path == "/api/1.0/workspaces":+ return _json({"data": workspaces or [{"gid": "ws1", "name": "Acme"}]})+ if path.startswith("/api/1.0/workspaces/") and path.endswith("/projects"):+ ws_gid = path.split("/")[-2]+ return _json({"data": (projects or {"ws1": [{"gid": "p1", "name": "Widgets"}]}).get(+ ws_gid, []+ )})+ if path == "/api/1.0/tasks" and params.get("project"):+ return _json({"data": (project_tasks or {}).get(params["project"], [])})+ if path == "/api/1.0/tasks":+ return _json({"data": (my_tasks or {}).get(params.get("workspace") or "", [])})+ if path.startswith("/api/1.0/tasks/") and path.endswith("/stories"):+ gid = path.split("/")[-2]+ return _json({"data": (stories or {}).get(gid, [])})+ return httpx.Response(404, content=b"{}")++ return httpx.MockTransport(handler)+++async def _collect(+ transport: httpx.MockTransport, checkpoint: str | None = None+) -> list:+ return [+ item+ async for item in asn.asana_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_a_task_becomes_a_linkable_dated_item():+ items = await _collect(+ _transport(+ project_tasks={"p1": [_task()]},+ stories={+ "t1": [+ _story("2026-03-02T09:00:00.000Z", "On it"),+ _story("2026-03-01T11:00:00.000Z", "Can you take this?", author="Bob"),+ _story(+ "2026-03-01T10:30:00.000Z",+ "moved to section Doing",+ subtype="section_changed",+ ),+ ]+ },+ )+ )+ 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 == "task:t1"+ # Evidence has to lead back to where it lives — mandatory from item one.+ assert item.permalink == "https://app.asana.com/0/p1/t1"+ # WHEN IT HAPPENED, not when it was last touched.+ assert item.timestamp_utc == "2026-03-01T10:00:00.000Z"+ assert item.title == "Ship the wake-word fix"+ assert item.author_raw == "Bob"+ assert item.thread_key == "p1"+ # The composed header keeps the context a bare notes field would lose.+ header = "Widgets · task · open · assigned to Alice · due 2026-04-01 · created by Bob"+ assert header in item.body+ assert "The wake word misses every third call." in item.body+ # Comments fold in chronologically; system activity is bookkeeping, not memory.+ body = item.body+ assert body.index("Can you take this?") < body.index("On it")+ assert "moved to section" not in body+ # The cursor rides on the key the sync runner advances.+ assert item.metadata["mtime_ns"] == asn._to_ns("2026-03-04T12:00:00.000Z")+ assert item.metadata["comments"] == 2+++async def test_completed_and_personal_tasks_arrive_too():+ done = _task("t2", name="Old chore", completed=True, permalink_url="https://app.asana.com/0/x/t2")+ personal = _task("t3", name="Just mine", permalink_url="https://app.asana.com/0/x/t3")+ items = await _collect(+ _transport(project_tasks={"p1": [done]}, my_tasks={"ws1": [personal]})+ )+ by_id = {item.external_id: item for item in items}+ assert by_id["task:t2"].metadata["state"] == "completed"+ # A task living in no walked project still arrives, keyed to its workspace.+ assert by_id["task:t3"].thread_key == "ws1"+ assert "Acme" in by_id["task:t3"].body+++async def test_a_task_seen_in_two_listings_arrives_once():+ task = _task()+ items = await _collect(+ _transport(project_tasks={"p1": [task]}, my_tasks={"ws1": [task]})+ )+ assert [item.external_id for item in items] == ["task:t1"]+ # The project walk noted it first, so the project stays its thread.+ assert items[0].thread_key == "p1"+++async def test_items_stream_oldest_to_newest_deterministically():+ newer = _task("t9", created_at="2026-03-05T10:00:00.000Z")+ older = _task("t2", created_at="2026-02-01T10:00:00.000Z")+ items = await _collect(_transport(project_tasks={"p1": [newer, older]}))+ assert [item.external_id for item in items] == ["task:t2", "task:t9"]+++async def test_a_numeric_checkpoint_narrows_every_task_listing():+ seen: list[httpx.Request] = []+ await _collect(+ _transport(seen=seen),+ checkpoint=str(asn._to_ns("2026-03-04T12:00:00Z")),+ )+ task_calls = [r for r in seen if r.url.path == "/api/1.0/tasks"]+ assert task_calls # both the project walk and the assignee listing ran+ for call in task_calls:+ # Five minutes before the cursor: the overlap is what makes a+ # boundary safe; re-yielded items upsert as unchanged.+ assert call.url.params.get("modified_since") == "2026-03-04T11:55:00Z"+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ first = _task("t1", created_at="2026-03-01T10:00:00.000Z")+ second = _task("t2", created_at="2026-03-02T10:00:00.000Z")+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(project_tasks={"p1": [first, second]}, seen=seen),+ checkpoint="task:t1",+ )+ assert [item.external_id for item in items] == ["task:t2"]+ # The skipped task's comment stories are never fetched — resume must not+ # re-spend the budget on rows the store already holds.+ story_calls = [r for r in seen if r.url.path.endswith("/stories")]+ assert [r.url.path for r in story_calls] == ["/api/1.0/tasks/t2/stories"]+++async def test_an_unknown_checkpoint_shape_is_read_as_no_cursor():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(project_tasks={"p1": [_task()]}, seen=seen),+ checkpoint="issue:4242",+ )+ assert len(items) == 1+ task_calls = [r for r in seen if r.url.path == "/api/1.0/tasks"]+ assert all(call.url.params.get("modified_since") is None for call in task_calls)+++async def test_offset_pages_are_walked_to_the_end():+ def handler(request: httpx.Request) -> httpx.Response:+ path = request.url.path+ if path == "/api/1.0/workspaces":+ return _json({"data": [{"gid": "ws1", "name": "Acme"}]})+ if path.endswith("/projects"):+ return _json({"data": [{"gid": "p1", "name": "Widgets"}]})+ if path == "/api/1.0/tasks" and request.url.params.get("project"):+ if request.url.params.get("offset"):+ return _json({"data": [_task("t2")]})+ return _json({"data": [_task("t1")], "next_page": {"offset": "cursor-2"}})+ if path == "/api/1.0/tasks":+ return _json({"data": []})+ if path.endswith("/stories"):+ return _json({"data": []})+ return httpx.Response(404, content=b"{}")++ items = await _collect(httpx.MockTransport(handler))+ assert sorted(item.external_id for item in items) == ["task:t1", "task:t2"]+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(project_tasks={"p1": [_task()]}, rate_limit_first=1, seen=seen)+ )+ assert len(items) == 1+ # The 429, then the honoured retry of the same first request.+ assert seen[0].url.path == seen[1].url.path == "/api/1.0/workspaces"+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(asn.AsanaAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == asn._MAX_ATTEMPTS # bounded, never an endless retry loop+++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'{"errors":[{"message":"Not Authorized"}]}')++ with pytest.raises(asn.AsanaAdapterError) as excinfo:+ await _collect(httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "asana-test-token" 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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(asn.AsanaAdapterError, match="not connected"):+ await _collect(_transport(seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_an_oversized_item_is_capped_with_a_marker():+ huge = _task(notes="x" * 1_100_000)+ items = await _collect(_transport(project_tasks={"p1": [huge]}))+ body = items[0].body+ assert body.endswith("[truncated — the full text lives at the link above]")+ assert len(body) < 1_100_000+++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(project_tasks={"p1": [_task(permalink_url=""), _task("t5")]})+ )+ assert [item.external_id for item in items] == ["task:t5"]+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(asn.INTEGRATION_ID)+ assert spec is not None and spec.id == "asana"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(asn.INTEGRATION_ID, asn.asana_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:asana") is True+ finally:+ plugin_bridge.unregister_pull_adapter(asn.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_clickup.py b/tests/unit/ultrawiki/adapters/test_clickup.pynew file mode 100644index 0000000000..a99f9e1938--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_clickup.py@@ -0,0 +1,367 @@+"""The ClickUp pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-task ids (a re-run must upsert, not duplicate), a real deep link on every+item, closed tasks and subtasks explicitly asked for, comments walked through+ClickUp's own pagination and folded chronologically, deterministic+oldest-to-newest streaming for the backfill checkpoint, bounded 429 handling,+and failure messages a user can act on that never carry the token.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import clickup as cu+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected ClickUp plugin, without touching the host's keyring."""++ class _Tokens:+ access = "clickup-test-token"+ 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-clickup",+ config={"integration_id": "plugin:clickup"},+ secret_get=lambda _name: None,+ )+++def _ms(iso: str) -> str:+ moment = datetime.fromisoformat(iso).replace(tzinfo=UTC)+ return str(int(moment.timestamp() * 1000))+++def _task(task_id: str = "abc1", **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "id": task_id,+ "name": "Ship the wake-word fix",+ "description": "The wake word misses every third call.",+ "status": {"status": "in progress"},+ "archived": False,+ "date_created": _ms("2026-03-01T10:00:00"),+ "date_updated": _ms("2026-03-04T12:00:00"),+ "due_date": _ms("2026-04-01T00:00:00"),+ "creator": {"username": "Bob"},+ "assignees": [{"username": "Alice"}],+ "list": {"id": "L1", "name": "Widgets"},+ "folder": {"id": "F1", "name": "Engineering", "hidden": False},+ "url": f"https://app.clickup.com/t/{task_id}",+ }+ base.update(overrides)+ return base+++def _comment(iso: str, text: str, author: str = "Alice", comment_id: str = "") -> dict[str, Any]:+ return {+ "id": comment_id or f"c-{iso}",+ "comment_text": text,+ "user": {"username": author},+ "date": _ms(iso),+ }+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _transport(+ *,+ teams: list[dict[str, Any]] | None = None,+ task_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ comment_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ rate_limit_first: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake ClickUp account: teams, the team-task walk, per-task comments."""+ remaining_429 = {"n": rate_limit_first}+ comment_calls: dict[str, int] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ path = request.url.path+ params = request.url.params+ if path == "/api/v2/team":+ return _json({"teams": teams or [{"id": "9001", "name": "Acme"}]})+ if path.startswith("/api/v2/team/") and path.endswith("/task"):+ team_id = path.split("/")[-2]+ pages = (task_pages or {}).get(team_id, [[]])+ page = int(params.get("page") or 0)+ return _json({"tasks": pages[page] if page < len(pages) else []})+ if path.startswith("/api/v2/task/") and path.endswith("/comment"):+ task_id = path.split("/")[-2]+ pages = (comment_pages or {}).get(task_id, [[]])+ index = comment_calls.get(task_id, 0)+ comment_calls[task_id] = index + 1+ return _json({"comments": pages[index] if index < len(pages) else []})+ return httpx.Response(404, content=b"{}")++ return httpx.MockTransport(handler)+++async def _collect(+ transport: httpx.MockTransport, checkpoint: str | None = None+) -> list:+ return [+ item+ async for item in cu.clickup_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_a_task_becomes_a_linkable_dated_item():+ comments = [+ [+ _comment("2026-03-02T09:00:00", "On it"),+ _comment("2026-03-01T11:00:00", "Can you take this?", author="Bob"),+ ]+ ]+ items = await _collect(+ _transport(task_pages={"9001": [[_task()]]}, comment_pages={"abc1": comments})+ )+ 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 == "task:abc1"+ # Evidence has to lead back to where it lives — mandatory from item one.+ assert item.permalink == "https://app.clickup.com/t/abc1"+ # 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 == "Bob"+ assert item.thread_key == "L1"+ # The composed header keeps the context a bare description would lose.+ assert "Engineering / Widgets · task · in progress" in item.body+ assert "assigned to Alice" in item.body+ assert "due 2026-04-01T00:00:00Z" in item.body+ assert "created by Bob" in item.body+ assert "The wake word misses every third call." in item.body+ # Comments fold in chronologically, oldest first.+ assert item.body.index("Can you take this?") < item.body.index("On it")+ # The cursor rides on the key the sync runner advances.+ assert item.metadata["mtime_ns"] == cu._ms_to_ns(_ms("2026-03-04T12:00:00"))+ assert item.metadata["comments"] == 2+++async def test_closed_and_subtask_rows_are_explicitly_asked_for():+ seen: list[httpx.Request] = []+ closed = _task(archived=True, status={"status": "complete"})+ items = await _collect(_transport(task_pages={"9001": [[closed]]}, seen=seen))+ assert items[0].metadata["state"] == "complete"+ assert items[0].metadata["archived"] is True+ assert "archived" in items[0].body+ walk = next(r for r in seen if r.url.path == "/api/v2/team/9001/task")+ # Without these flags ClickUp silently omits closed tasks and subtasks.+ assert walk.url.params.get("include_closed") == "true"+ assert walk.url.params.get("subtasks") == "true"+++async def test_a_hidden_folder_never_names_the_plumbing():+ """ClickUp models folderless lists as a "hidden" folder; its API name+ must not leak into the record."""+ folderless = _task(folder={"id": "F0", "name": "hidden", "hidden": True})+ items = await _collect(_transport(task_pages={"9001": [[folderless]]}))+ assert "hidden /" not in items[0].body+ assert "Widgets · task" in items[0].body+++async def test_a_numeric_checkpoint_narrows_the_walk_by_update_time():+ seen: list[httpx.Request] = []+ moment = datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC)+ await _collect(+ _transport(seen=seen),+ checkpoint=str(int(moment.timestamp() * 1_000_000_000)),+ )+ walk = next(r for r in seen if r.url.path == "/api/v2/team/9001/task")+ # Five minutes before the cursor, in the epoch milliseconds the API+ # speaks: the overlap is what makes a boundary safe.+ expected = int(moment.timestamp() * 1000) - 300_000+ assert walk.url.params.get("date_updated_gt") == str(expected)+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ first = _task("aaa", date_created=_ms("2026-03-01T10:00:00"))+ second = _task("bbb", date_created=_ms("2026-03-02T10:00:00"))+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(task_pages={"9001": [[first, second]]}, seen=seen),+ checkpoint="task:aaa",+ )+ assert [item.external_id for item in items] == ["task:bbb"]+ # The skipped task's comments are never fetched — resume must not+ # re-spend the budget on rows the store already holds.+ comment_calls = [r for r in seen if r.url.path.endswith("/comment")]+ assert [r.url.path for r in comment_calls] == ["/api/v2/task/bbb/comment"]+++async def test_an_unknown_checkpoint_shape_is_read_as_no_cursor():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(task_pages={"9001": [[_task()]]}, seen=seen),+ checkpoint="issue:4242",+ )+ assert len(items) == 1+ walk = next(r for r in seen if r.url.path == "/api/v2/team/9001/task")+ assert walk.url.params.get("date_updated_gt") is None+++async def test_task_pages_are_walked_to_the_end():+ pages = [+ [_task(f"t{i:03d}", date_created=_ms("2026-03-01T10:00:00")) for i in range(100)],+ [_task("t999", date_created=_ms("2026-03-02T10:00:00"))],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(_transport(task_pages={"9001": pages}, seen=seen))+ assert len(items) == 101+ walk = [r for r in seen if r.url.path == "/api/v2/team/9001/task"]+ assert len(walk) == 2 # stopped after the short second page+++async def test_every_workspace_the_token_reaches_is_walked():+ teams = [{"id": "9002", "name": "Beta"}, {"id": "9001", "name": "Acme"}]+ items = await _collect(+ _transport(+ teams=teams,+ task_pages={+ "9001": [[_task("aaa", date_created=_ms("2026-03-01T10:00:00"))]],+ "9002": [[_task("bbb", date_created=_ms("2026-02-01T10:00:00"))]],+ },+ )+ )+ # Both workspaces contribute, merged into ONE oldest-to-newest stream.+ assert [item.external_id for item in items] == ["task:bbb", "task:aaa"]+++async def test_comment_pages_are_walked_through_the_pagination():+ page_one = [+ _comment("2026-03-02T10:00:00", f"comment {i}", comment_id=f"c{i}")+ for i in range(cu._COMMENT_PAGE)+ ]+ page_two = [_comment("2026-03-01T09:00:00", "the very first comment", comment_id="c-old")]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ task_pages={"9001": [[_task()]]},+ comment_pages={"abc1": [page_one, page_two]},+ seen=seen,+ )+ )+ body = items[0].body+ # The older page arrived AND sorts before the newer one.+ assert body.index("the very first comment") < body.index("comment 0")+ assert items[0].metadata["comments"] == cu._COMMENT_PAGE + 1+ comment_calls = [r for r in seen if r.url.path.endswith("/comment")]+ assert len(comment_calls) == 2+ # The second ask carries ClickUp's start/start_id pagination pair.+ assert comment_calls[1].url.params.get("start_id") == page_one[-1]["id"]+++async def test_the_bare_token_convention_is_kept():+ """ClickUp rejects "Bearer "-prefixed personal tokens; the header carries+ the token bare, exactly as its docs demand."""+ seen: list[httpx.Request] = []+ await _collect(_transport(seen=seen))+ assert seen[0].headers["Authorization"] == "clickup-test-token"+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(task_pages={"9001": [[_task()]]}, rate_limit_first=1, seen=seen)+ )+ assert len(items) == 1+ assert seen[0].url.path == seen[1].url.path == "/api/v2/team"+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(cu.ClickUpAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == cu._MAX_ATTEMPTS # bounded, never an endless retry loop+++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'{"err":"Token invalid","ECODE":"OAUTH_025"}')++ with pytest.raises(cu.ClickUpAdapterError) as excinfo:+ await _collect(httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "clickup-test-token" 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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(cu.ClickUpAdapterError, match="not connected"):+ await _collect(_transport(seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_an_oversized_item_is_capped_with_a_marker():+ huge = _task(description="x" * 1_100_000)+ items = await _collect(_transport(task_pages={"9001": [[huge]]}))+ body = items[0].body+ assert body.endswith("[truncated — the full text lives at the link above]")+ assert len(body) < 1_100_000+++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(task_pages={"9001": [[_task(url=""), _task("keep")]]})+ )+ assert [item.external_id for item in items] == ["task:keep"]+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(cu.INTEGRATION_ID)+ assert spec is not None and spec.id == "clickup"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(cu.INTEGRATION_ID, cu.clickup_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:clickup") is True+ finally:+ plugin_bridge.unregister_pull_adapter(cu.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_discord.py b/tests/unit/ultrawiki/adapters/test_discord.pynew file mode 100644index 0000000000..da7d4d0766--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_discord.py@@ -0,0 +1,322 @@+"""The Discord pull adapter, driven fully offline through MockTransport.++What these tests pin: full history through pagination, day-chunk emission in+deterministic oldest-to-newest order, the checkpoint conventions (resume+strictly after an external_id; a numeric cursor becomes ``after=``), quiet+skipping of channels the bot may not read, bounded 429 handling, and failure+messages a user can act on that never carry the bot token.++The mock reproduces Discord's real pagination semantics — ``before``/``after``+windows over snowflake-ordered messages, newest first in every response — so+the adapter's ordering guarantees are earned, not assumed.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import discord as dc+from jarvis.ultrawiki.types import ConnectorContext++_GUILD = {"id": "111", "name": "Acme HQ"}+_CHANNEL = {"id": "222", "name": "general", "type": 0}++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Discord plugin, without touching the host's keyring."""++ class _Tokens:+ access = "discord_bot_secret_value"+ 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-discord",+ config={"integration_id": "plugin:discord"},+ secret_get=lambda _name: None,+ )+++def _snowflake(iso: str, sequence: int = 0) -> str:+ """A realistic message id: creation time is encoded, as on real Discord.++ The adapter converts time cursors into snowflakes and the mock filters by+ id — both only line up when ids and timestamps agree, exactly as live.+ """+ moment = datetime.fromisoformat(iso.replace("Z", "+00:00"))+ ms = int(moment.timestamp() * 1000)+ return str(((ms - 1_420_070_400_000) << 22) + sequence)+++def _message(iso: str, text: str, *, author: str = "ruth", sequence: int = 0) -> dict:+ return {+ "id": _snowflake(iso, sequence),+ "content": text,+ "timestamp": iso.replace("Z", "+00:00"),+ "author": {"username": author},+ "attachments": [],+ "embeds": [],+ }+++def _transport(+ channels: dict[str, list[dict[str, Any]]],+ *,+ guilds: list[dict[str, Any]] | None = None,+ guild_channels: list[dict[str, Any]] | None = None,+ forbidden: set[str] = frozenset(),+ seen: list[httpx.Request] | None = None,+ ratelimit_first: int = 0,+) -> httpx.MockTransport:+ """A faithful little Discord: snowflake windows, newest-first pages."""+ remaining_429 = {"n": ratelimit_first}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/api/v10/users/@me/guilds":+ if request.url.params.get("after"):+ return httpx.Response(200, json=[])+ return httpx.Response(200, json=guilds if guilds is not None else [_GUILD])+ if path.startswith("/api/v10/guilds/") and path.endswith("/channels"):+ rows = guild_channels if guild_channels is not None else [_CHANNEL]+ return httpx.Response(200, json=rows)+ if path.startswith("/api/v10/channels/") and path.endswith("/messages"):+ channel_id = path.split("/")[4]+ if channel_id in forbidden:+ return httpx.Response(403, json={"message": "Missing Access", "code": 50001})+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"}, json={"retry_after": 0})+ messages = sorted(+ channels.get(channel_id, []), key=lambda m: int(m["id"])+ )+ params = request.url.params+ limit = int(params.get("limit", "50"))+ if "after" in params:+ window = [m for m in messages if int(m["id"]) > int(params["after"])]+ window = window[:limit]+ elif "before" in params:+ window = [m for m in messages if int(m["id"]) < int(params["before"])]+ window = window[-limit:]+ else:+ window = messages[-limit:]+ return httpx.Response(200, json=list(reversed(window))) # newest first+ return httpx.Response(404, json={"message": "Not Found"})++ return httpx.MockTransport(handler)+++async def _collect(checkpoint: str | None = None, **kwargs: Any) -> list:+ return [+ item+ async for item in dc.discord_pull_adapter(_ctx(), checkpoint, **kwargs)+ ]+++async def test_a_channel_becomes_day_chunks_oldest_to_newest():+ transport = _transport(+ {+ "222": [+ _message("2026-03-02T09:00:00Z", "second day", sequence=1),+ _message("2026-03-01T10:00:00Z", "first day, first", sequence=1),+ _message("2026-03-01T11:30:00Z", "first day, second", sequence=2),+ ]+ }+ )+ items = await _collect(transport=transport)+ assert [i.external_id for i in items] == [+ "discord:111:222:2026-03-01",+ "discord:111:222:2026-03-02",+ ]+ first = items[0]+ # Evidence deep-links to the first message of the chunk.+ assert first.permalink == (+ f"https://discord.com/channels/111/222/{_snowflake('2026-03-01T10:00:00Z', 1)}"+ )+ assert first.timestamp_utc == "2026-03-01T10:00:00Z"+ assert first.thread_key == "111/222"+ assert "Acme HQ · #general · 2026-03-01 · 2 message(s)" in first.body+ assert "[10:00] ruth: first day, first" in first.body+ assert "[11:30] ruth: first day, second" in first.body+ assert first.metadata["message_count"] == 2+++async def test_full_history_is_walked_through_every_page():+ day = "2026-03-01"+ messages = [+ _message(f"{day}T10:00:00Z", f"msg {i}", sequence=i) for i in range(250)+ ]+ seen: list[httpx.Request] = []+ items = await _collect(transport=_transport({"222": messages}, seen=seen))+ assert len(items) == 1+ assert items[0].metadata["message_count"] == 250+ assert "msg 0" in items[0].body+ assert "msg 249" in items[0].body+ history_calls = [r for r in seen if r.url.path.endswith("/messages")]+ assert len(history_calls) == 3 # 100 + 100 + 50+++async def test_the_cursor_rides_on_the_key_the_sync_runner_advances():+ items = await _collect(+ transport=_transport({"222": [_message("2026-03-01T10:00:00Z", "hi", sequence=1)]})+ )+ assert items[0].metadata["mtime_ns"] == dc._to_ns("2026-03-01T10:00:00Z")+ assert items[0].metadata["mtime_ns"] > 0+++async def test_a_numeric_checkpoint_walks_forward_from_that_day():+ """The runner's ns cursor becomes ``after=<snowflake at the day start>`` —+ re-asking from the boundary keeps day chunks complete."""+ messages = [+ _message("2026-03-01T10:00:00Z", "old", sequence=1),+ _message("2026-03-03T09:00:00Z", "new", sequence=1),+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ checkpoint=str(dc._to_ns("2026-03-03T12:00:00Z")),+ transport=_transport({"222": messages}, seen=seen),+ )+ history = next(r for r in seen if r.url.path.endswith("/messages"))+ assert "after" in history.url.params+ assert [i.external_id for i in items] == ["discord:111:222:2026-03-03"]+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ """The bridge hands back the last emitted external_id mid-walk; the same+ channel continues after that day and earlier channels are skipped."""+ older = {"id": "200", "name": "announcements", "type": 5}+ channels = [older, _CHANNEL]+ data = {+ "200": [_message("2026-02-01T08:00:00Z", "already imported", sequence=1)],+ "222": [+ _message("2026-03-01T10:00:00Z", "already imported too", sequence=1),+ _message("2026-03-02T10:00:00Z", "still missing", sequence=1),+ ],+ }+ items = await _collect(+ checkpoint="discord:111:222:2026-03-01",+ transport=_transport(data, guild_channels=channels),+ )+ assert [i.external_id for i in items] == ["discord:111:222:2026-03-02"]+++async def test_unreadable_channels_are_skipped_not_fatal():+ channels = [+ {"id": "221", "name": "private-ops", "type": 0},+ _CHANNEL,+ ]+ data = {"222": [_message("2026-03-01T10:00:00Z", "visible", sequence=1)]}+ items = await _collect(+ transport=_transport(data, guild_channels=channels, forbidden={"221"})+ )+ assert [i.external_id for i in items] == ["discord:111:222:2026-03-01"]+++async def test_voice_and_category_channels_are_not_walked():+ channels = [+ {"id": "300", "name": "Voice Lounge", "type": 2},+ {"id": "301", "name": "a-category", "type": 4},+ _CHANNEL,+ ]+ seen: list[httpx.Request] = []+ await _collect(+ transport=_transport(+ {"222": [_message("2026-03-01T10:00:00Z", "hi", sequence=1)]},+ guild_channels=channels,+ seen=seen,+ )+ )+ walked = {r.url.path.split("/")[4] for r in seen if r.url.path.endswith("/messages")}+ assert walked == {"222"}+++async def test_attachments_are_named_never_downloaded():+ message = _message("2026-03-01T10:00:00Z", "", sequence=1)+ message["attachments"] = [+ {"filename": "report.pdf", "url": "https://cdn.discordapp.com/report.pdf"}+ ]+ seen: list[httpx.Request] = []+ items = await _collect(transport=_transport({"222": [message]}, seen=seen))+ assert "[attachment: report.pdf]" in items[0].body+ assert all("cdn.discordapp.com" not in str(r.url) for r in seen)+++async def test_an_oversized_day_is_truncated_with_a_marker(monkeypatch):+ monkeypatch.setattr(dc, "_MAX_BODY_CHARS", 80)+ messages = [+ _message("2026-03-01T10:00:00Z", "x" * 60, sequence=i) for i in range(1, 4)+ ]+ items = await _collect(transport=_transport({"222": messages}))+ assert len(items) == 1+ assert items[0].body.endswith(dc._TRUNCATION_MARKER)+ assert items[0].metadata["truncated"] is True+++async def test_a_429_is_retried_within_bounds_and_then_succeeds():+ seen: list[httpx.Request] = []+ items = await _collect(+ transport=_transport(+ {"222": [_message("2026-03-01T10:00:00Z", "hi", sequence=1)]},+ seen=seen,+ ratelimit_first=1,+ )+ )+ assert len(items) == 1+ history_calls = [r for r in seen if r.url.path.endswith("/messages")]+ assert len(history_calls) == 2 # the 429 plus the successful retry+++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, json={"message": "401: Unauthorized"})++ with pytest.raises(dc.DiscordAdapterError) as excinfo:+ await _collect(transport=httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "discord_bot_secret_value" 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(dc.DiscordAdapterError, match="not connected"):+ await _collect(transport=_transport({}))+++def test_the_integration_id_matches_the_curated_roster():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ # The id must resolve to the roster's Discord card, or the reader serves+ # a name nothing offers.+ spec = connector_catalog.bridge_entry_for(dc.INTEGRATION_ID)+ assert spec is not None+ assert spec.id == "discord"++ plugin_bridge.register_pull_adapter(dc.INTEGRATION_ID, dc.discord_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:discord") is True+ finally:+ plugin_bridge.unregister_pull_adapter(dc.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_dropbox.py b/tests/unit/ultrawiki/adapters/test_dropbox.pynew file mode 100644index 0000000000..00d62e5b35--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_dropbox.py@@ -0,0 +1,308 @@+"""The Dropbox pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: a stable id+(``path_lower`` — a re-run must upsert, not duplicate), a real web preview+link on every item, honest skipping of binaries BEFORE any byte is+downloaded, deterministic path order so the backfill checkpoint resumes+strictly after the last persisted id, 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 dropbox as dbx+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Dropbox plugin, without touching the host's keyring."""++ class _Tokens:+ access = "sl.dbx-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(**config: Any) -> ConnectorContext:+ return ConnectorContext(+ source_id="src-dropbox",+ config={"integration_id": "plugin:dropbox", **config},+ secret_get=lambda _name: None,+ )+++def _file(+ path_display: str,+ *,+ size: int = 64,+ modified: str = "2026-03-01T10:00:00Z",+ tag: str = "file",+ downloadable: bool = True,+) -> dict[str, Any]:+ entry: dict[str, Any] = {+ ".tag": tag,+ "name": path_display.rsplit("/", 1)[-1],+ "path_lower": path_display.lower(),+ "path_display": path_display,+ "id": f"id:{path_display}",+ "server_modified": modified,+ "client_modified": modified,+ "size": size,+ "rev": "0123456789abcdef",+ }+ if not downloadable:+ entry["is_downloadable"] = False+ return entry+++def _transport(+ pages: list[list[dict[str, Any]]],+ contents: dict[str, str],+ *,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/2/files/download":+ arg = json.loads(request.headers["Dropbox-API-Arg"])+ body = contents.get(arg["path"])+ if body is None:+ # The file vanished between list and download.+ return httpx.Response(409, json={"error_summary": "path/not_found/.."})+ return httpx.Response(200, content=body.encode())+ if path == "/2/files/list_folder":+ index = 0+ elif path == "/2/files/list_folder/continue":+ index = int(json.loads(request.content)["cursor"].split("-")[1])+ else:+ return httpx.Response(404, json={})+ return httpx.Response(+ 200,+ json={+ "entries": pages[index],+ "cursor": f"cursor-{index + 1}",+ "has_more": index + 1 < len(pages),+ },+ )++ return httpx.MockTransport(handler)+++def _downloaded_paths(seen: list[httpx.Request]) -> list[str]:+ return [+ json.loads(request.headers["Dropbox-API-Arg"])["path"]+ for request in seen+ if request.url.path == "/2/files/download"+ ]+++async def _collect(+ checkpoint: str | None = None, *, ctx: ConnectorContext | None = None, **kwargs: Any+) -> list:+ return [+ item+ async for item in dbx.dropbox_pull_adapter(ctx or _ctx(), checkpoint, **kwargs)+ ]+++async def test_a_text_file_becomes_a_linkable_dated_item():+ entry = _file("/Notes/Weekly Plan.md")+ transport = _transport([[entry]], {"/notes/weekly plan.md": "Plan the wake-word fix."})+ items = await _collect(transport=transport)+ 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 == "/notes/weekly plan.md"+ # Evidence has to lead back to where it lives — the web preview link.+ assert item.permalink == "https://www.dropbox.com/home/Notes?preview=Weekly%20Plan.md"+ assert item.timestamp_utc == "2026-03-01T10:00:00Z"+ assert item.title == "Weekly Plan"+ assert item.thread_key == "/notes"+ assert item.body == "Plan the wake-word fix."+ assert item.metadata["mtime_ns"] == dbx._to_ns("2026-03-01T10:00:00Z")+ assert item.metadata["rev"] == "0123456789abcdef"+++async def test_binaries_are_never_downloaded():+ """The skip happens by extension BEFORE any byte moves — a photo library+ must not cost one request per photo just to be rejected."""+ seen: list[httpx.Request] = []+ pages = [[_file("/photo.jpg"), _file("/report.pdf"), _file("/notes.md")]]+ items = await _collect(+ transport=_transport(pages, {"/notes.md": "text"}, seen=seen)+ )+ assert [item.external_id for item in items] == ["/notes.md"]+ assert _downloaded_paths(seen) == ["/notes.md"]+++async def test_folders_deleted_and_non_downloadable_entries_are_ignored():+ seen: list[httpx.Request] = []+ pages = [+ [+ _file("/docs", tag="folder"),+ _file("/gone.md", tag="deleted"),+ _file("/paper.md", downloadable=False),+ ]+ ]+ items = await _collect(transport=_transport(pages, {}, seen=seen))+ assert items == []+ assert _downloaded_paths(seen) == []+++async def test_the_extension_allowlist_is_configurable_per_source():+ """Same philosophy as the local-folder connector: a curated default the+ source config may override."""+ pages = [[_file("/build.log"), _file("/notes.md")]]+ items = await _collect(+ ctx=_ctx(extensions=["log"]),+ transport=_transport(pages, {"/build.log": "log text"}),+ )+ assert [item.external_id for item in items] == ["/build.log"]+++async def test_cursor_paging_walks_every_page_in_path_order():+ """list_folder/continue is followed to the end, and the yield order is+ sorted by external_id — the only order the checkpoint can resume from."""+ seen: list[httpx.Request] = []+ pages = [[_file("/b.md")], [_file("/a.md")]]+ items = await _collect(+ transport=_transport(pages, {"/a.md": "A", "/b.md": "B"}, seen=seen)+ )+ assert [item.external_id for item in items] == ["/a.md", "/b.md"]+ assert len([r for r in seen if r.url.path == "/2/files/list_folder/continue"]) == 1+++async def test_a_path_checkpoint_resumes_strictly_after_it():+ seen: list[httpx.Request] = []+ pages = [[_file("/a.md"), _file("/b.md"), _file("/c.md")]]+ contents = {"/a.md": "A", "/b.md": "B", "/c.md": "C"}+ items = await _collect(+ checkpoint="/b.md", transport=_transport(pages, contents, seen=seen)+ )+ assert [item.external_id for item in items] == ["/c.md"]+ # Skipped files are skipped before download, not after.+ assert _downloaded_paths(seen) == ["/c.md"]+++async def test_a_numeric_cursor_skips_unchanged_files_before_download():+ seen: list[httpx.Request] = []+ pages = [+ [+ _file("/old.md", modified="2026-03-01T10:00:00Z"),+ _file("/new.md", modified="2026-03-03T10:00:00Z"),+ ]+ ]+ contents = {"/old.md": "old", "/new.md": "new"}+ cursor = str(dbx._to_ns("2026-03-02T00:00:00Z"))+ items = await _collect(+ checkpoint=cursor, transport=_transport(pages, contents, seen=seen)+ )+ assert [item.external_id for item in items] == ["/new.md"]+ assert _downloaded_paths(seen) == ["/new.md"]+++async def test_oversized_files_are_skipped_and_long_bodies_truncated():+ seen: list[httpx.Request] = []+ pages = [+ [+ _file("/huge.md", size=3 * 1024 * 1024),+ _file("/long.md", size=dbx._MAX_BODY_BYTES + 200_000),+ ]+ ]+ contents = {"/long.md": "x" * (dbx._MAX_BODY_BYTES + 100_000)}+ items = await _collect(transport=_transport(pages, contents, seen=seen))+ assert [item.external_id for item in items] == ["/long.md"]+ # The oversized file never cost a download.+ assert _downloaded_paths(seen) == ["/long.md"]+ body = items[0].body+ assert body.endswith(dbx._TRUNCATION_MARKER)+ assert len(body) == dbx._MAX_BODY_BYTES + len(dbx._TRUNCATION_MARKER)+++async def test_a_vanished_file_is_skipped_not_fatal():+ """One 409 between list and download must not sink the other files."""+ pages = [[_file("/gone.md"), _file("/here.md")]]+ items = await _collect(transport=_transport(pages, {"/here.md": "still here"}))+ assert [item.external_id for item in items] == ["/here.md"]+++async def test_a_rate_limited_request_waits_and_retries_bounded():+ attempts = {"count": 0}++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path == "/2/files/download":+ return httpx.Response(200, content=b"text")+ attempts["count"] += 1+ if attempts["count"] == 1:+ return httpx.Response(429, headers={"Retry-After": "0"})+ return httpx.Response(+ 200, json={"entries": [_file("/a.md")], "cursor": "c", "has_more": False}+ )++ items = await _collect(transport=httpx.MockTransport(handler))+ assert [item.external_id for item in items] == ["/a.md"]+ assert attempts["count"] == 2+++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, json={"error_summary": "invalid_access_token/.."})++ with pytest.raises(dbx.DropboxAdapterError) as excinfo:+ await _collect(transport=httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "sl.dbx-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(dbx.DropboxAdapterError, match="not connected"):+ await _collect(transport=_transport([[]], {}))+++async def test_an_expired_connection_is_named_as_such(monkeypatch):+ class _Tokens:+ access = "sl.dbx-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(dbx.DropboxAdapterError, match="expired"):+ await _collect(transport=_transport([[]], {}))+++def test_the_integration_id_matches_the_curated_catalog():+ """The adapter must register under the id the picker actually routes."""+ from jarvis.ultrawiki import connector_catalog++ spec = connector_catalog.bridge_entry_for(dbx.INTEGRATION_ID)+ assert spec is not None+ assert spec.id == "dropbox"diff --git a/tests/unit/ultrawiki/adapters/test_google_calendar.py b/tests/unit/ultrawiki/adapters/test_google_calendar.pynew file mode 100644index 0000000000..c311bfa603--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_google_calendar.py@@ -0,0 +1,352 @@+"""The Google Calendar pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: a+deterministic calendar-by-calendar walk (sorted, so the resume convention+holds), calendar-scoped external ids with the real ``htmlLink`` deep link,+all-day events normalised to machine-comparable timestamps, recurring+instances threaded by their series, cancelled tombstones skipped, and the+``updatedMin`` narrowing that stands in for the syncToken the bridge's single+numeric cursor cannot hold.+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any+from urllib.parse import unquote++import httpx+import pytest++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.adapters import google_calendar as gc+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Google Calendar plugin, without touching the host's keyring."""++ class _Tokens:+ access = "ya29.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-gcal",+ config={"integration_id": "plugin:google_calendar"},+ secret_get=lambda _name: None,+ )+++def _calendar(calendar_id: str, summary: str = "") -> dict[str, Any]:+ return {"id": calendar_id, "summary": summary or calendar_id}+++def _event(+ event_id: str,+ start_iso: str,+ *,+ summary: str = "Standup",+ description: str = "",+ attendees: list[dict[str, Any]] | None = None,+ recurring: str = "",+ status: str = "confirmed",+ updated: str = "2026-03-05T08:00:00Z",+ all_day: bool = False,+ location: str = "",+) -> dict[str, Any]:+ event: dict[str, Any] = {+ "id": event_id,+ "status": status,+ "htmlLink": f"https://calendar.google.com/calendar/event?eid={event_id}",+ "summary": summary,+ "updated": updated,+ "organizer": {"displayName": "Ada", "email": "[email protected]"},+ "start": {"date": start_iso} if all_day else {"dateTime": start_iso},+ }+ if description:+ event["description"] = description+ if attendees is not None:+ event["attendees"] = attendees+ if recurring:+ event["recurringEventId"] = recurring+ if location:+ event["location"] = location+ return event+++def _transport(+ *,+ calendars: list[dict[str, Any]],+ events: dict[str, list[list[dict[str, Any]]]],+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Calendar API: a calendar list plus paged per-calendar events."""++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = unquote(request.url.path)+ if path == "/calendar/v3/users/me/calendarList":+ return httpx.Response(200, json={"items": calendars})+ if path.startswith("/calendar/v3/calendars/") and path.endswith("/events"):+ calendar_id = path[len("/calendar/v3/calendars/") : -len("/events")]+ pages = events.get(calendar_id, [[]])+ index = int(request.url.params.get("pageToken") or 0)+ page = pages[index] if index < len(pages) else []+ payload: dict[str, Any] = {"items": page}+ if index + 1 < len(pages):+ payload["nextPageToken"] = str(index + 1)+ return httpx.Response(200, json=payload)+ return httpx.Response(404)++ return httpx.MockTransport(handler)+++async def _collect(transport: httpx.MockTransport, checkpoint: str | None = None) -> list:+ return [+ item+ async for item in gc.google_calendar_pull_adapter(+ _ctx(), checkpoint, transport=transport+ )+ ]+++async def test_every_calendar_contributes_in_deterministic_sorted_order():+ items = await _collect(+ _transport(+ # The API answers in ITS order; the walk must not depend on it.+ calendars=[_calendar("b@x", "Team"), _calendar("a@x", "Personal")],+ events={+ "a@x": [[_event("e1", "2026-03-01T09:00:00Z")]],+ "b@x": [[_event("e2", "2026-03-02T09:00:00Z")]],+ },+ )+ )+ # Calendar-scoped ids: the same invitation on two calendars must upsert as+ # two rows, and the sorted calendar order is what the resume leans on.+ assert [item.external_id for item in items] == ["a@x:e1", "b@x:e2"]+ first = items[0]+ assert first.permalink == "https://calendar.google.com/calendar/event?eid=e1"+ assert first.title == "Standup"+ assert first.timestamp_utc == "2026-03-01T09:00:00Z"+ assert first.author_raw == "Ada"+ assert "Personal · event · 2026-03-01T09:00:00Z" in first.body+ # The cursor rides on the key the sync runner advances.+ assert first.metadata["mtime_ns"] == g.to_ns("2026-03-05T08:00:00Z")+++async def test_an_all_day_event_gets_a_machine_comparable_midnight_timestamp():+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={"a@x": [[_event("e1", "2026-03-01", all_day=True)]]},+ )+ )+ assert items[0].timestamp_utc == "2026-03-01T00:00:00Z"+++async def test_cancelled_events_are_skipped():+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={+ "a@x": [+ [+ _event("e1", "2026-03-01T09:00:00Z", status="cancelled"),+ _event("e2", "2026-03-02T09:00:00Z"),+ ]+ ]+ },+ )+ )+ # A tombstone carries no text to remember.+ assert [item.external_id for item in items] == ["a@x:e2"]+++async def test_recurring_instances_thread_together_as_one_series():+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={+ "a@x": [+ [+ _event("s1_20260301", "2026-03-01T09:00:00Z", recurring="s1"),+ _event("s1_20260308", "2026-03-08T09:00:00Z", recurring="s1"),+ ]+ ]+ },+ )+ )+ assert [item.thread_key for item in items] == ["a@x:s1", "a@x:s1"]+ assert items[0].external_id != items[1].external_id+++async def test_a_large_attendee_list_is_summarised_not_dumped():+ attendees = [{"email": f"person{i:02d}@example.test"} for i in range(30)]+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={"a@x": [[_event("e1", "2026-03-01T09:00:00Z", attendees=attendees)]]},+ )+ )+ body = items[0].body+ assert "Attendees (30):" in body+ assert "(+5 more)" in body # 25 shown, the rest counted — not a mailing list dump+ assert "[email protected]" not in body+++async def test_an_html_description_is_stripped_to_readable_text():+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={+ "a@x": [+ [+ _event(+ "e1",+ "2026-03-01T09:00:00Z",+ description="<p>Agenda items</p><p>Budget</p>",+ )+ ]+ ]+ },+ )+ )+ body = items[0].body+ assert "Agenda items" in body+ assert "Budget" in body+ assert "<p>" not in body+++async def test_event_pages_are_walked_to_the_end():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x")],+ events={+ "a@x": [+ [_event("e1", "2026-03-01T09:00:00Z")],+ [_event("e2", "2026-03-02T09:00:00Z")],+ ]+ },+ seen=seen,+ )+ )+ assert [item.external_id for item in items] == ["a@x:e1", "a@x:e2"]+ event_calls = [r for r in seen if r.url.path.endswith("/events")]+ assert len(event_calls) == 2+++async def test_the_walk_asks_for_expanded_instances_in_start_order():+ seen: list[httpx.Request] = []+ await _collect(+ _transport(calendars=[_calendar("a@x")], events={"a@x": [[]]}, seen=seen)+ )+ call = next(r for r in seen if r.url.path.endswith("/events"))+ params = call.url.params+ assert params.get("singleEvents") == "true"+ assert params.get("orderBy") == "startTime"+ assert params.get("timeMin") == "1970-01-01T00:00:00Z"+ assert params.get("timeMax") # the recurring-expansion ceiling is bounded+++async def test_a_numeric_checkpoint_becomes_updated_min_a_day_earlier():+ ns = g.to_ns("2026-03-04T12:00:00Z")+ seen: list[httpx.Request] = []+ await _collect(+ _transport(calendars=[_calendar("a@x")], events={"a@x": [[]]}, seen=seen),+ checkpoint=str(ns),+ )+ call = next(r for r in seen if r.url.path.endswith("/events"))+ # One day earlier, so a boundary can never skip an event; the rewound+ # overlap upserts as unchanged. This is the documented syncToken fallback.+ assert call.url.params.get("updatedMin") == "2026-03-03T12:00:00Z"+++async def test_a_backfill_checkpoint_skips_completed_calendars():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ calendars=[_calendar("a@x"), _calendar("b@x")],+ events={+ "a@x": [[_event("e1", "2026-03-01T09:00:00Z")]],+ "b@x": [[_event("e2", "2026-03-02T09:00:00Z")]],+ },+ seen=seen,+ ),+ checkpoint="b@x:e2",+ )+ # Calendars sorted before the checkpoint's calendar are complete; the+ # checkpoint's own calendar is re-walked (cheap — pages carry full data).+ walked = {+ unquote(r.url.path)[len("/calendar/v3/calendars/") : -len("/events")]+ for r in seen+ if r.url.path.endswith("/events")+ }+ assert walked == {"b@x"}+ assert [item.external_id for item in items] == ["b@x:e2"]+++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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(gc.GoogleAdapterError, match="not connected"):+ await _collect(_transport(calendars=[], events={}, seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_an_oversized_description_is_capped_and_marked():+ huge = _event("e1", "2026-03-01T09:00:00Z", description="x" * (g.BODY_CAP + 10))+ items = await _collect(+ _transport(calendars=[_calendar("a@x")], events={"a@x": [[huge]]})+ )+ assert items[0].body.endswith(g.TRUNCATION_MARKER)+ assert items[0].metadata["truncated"] is True+++async def test_the_lookahead_ceiling_rolls_forward_with_the_sync():+ seen: list[httpx.Request] = []+ await _collect(+ _transport(calendars=[_calendar("a@x")], events={"a@x": [[]]}, seen=seen)+ )+ call = next(r for r in seen if r.url.path.endswith("/events"))+ ceiling = datetime.fromisoformat(+ call.url.params.get("timeMax").replace("Z", "+00:00")+ )+ days_ahead = (ceiling - datetime.now(UTC)).days+ # Two years ahead of THIS sync — instances beyond it arrive as time does.+ assert 725 <= days_ahead <= 731+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(gc.INTEGRATION_ID)+ assert spec is not None and spec.id == "google_calendar"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(+ gc.INTEGRATION_ID, gc.google_calendar_pull_adapter+ )+ try:+ assert plugin_bridge.has_pull_adapter("plugin:google_calendar") is True+ finally:+ plugin_bridge.unregister_pull_adapter(gc.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_google_drive.py b/tests/unit/ultrawiki/adapters/test_google_drive.pynew file mode 100644index 0000000000..15f75aa024--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_google_drive.py@@ -0,0 +1,336 @@+"""The Google Drive pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: Google-native+documents exported to text, text-shaped files downloaded with a source-side+byte bound, binaries skipped honestly instead of swallowed, a deterministic+oldest-modified-first walk so the checkpoint convention holds, per-file+degradation instead of all-or-nothing failure, and refusals that never carry+the token.+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.adapters import google_drive as gd+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Google Drive plugin, without touching the host's keyring."""++ class _Tokens:+ access = "ya29.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-gdrive",+ config={"integration_id": "plugin:google_drive"},+ secret_get=lambda _name: None,+ )+++_DOC = "application/vnd.google-apps.document"+_SHEET = "application/vnd.google-apps.spreadsheet"+_FOLDER = "application/vnd.google-apps.folder"+++def _file(+ file_id: str,+ name: str,+ mime: str,+ *,+ size: int = 0,+ created: str = "2026-01-01T10:00:00Z",+ modified: str = "2026-02-01T10:00:00Z",+ description: str = "",+) -> dict[str, Any]:+ row: dict[str, Any] = {+ "id": file_id,+ "name": name,+ "mimeType": mime,+ "createdTime": created,+ "modifiedTime": modified,+ "webViewLink": f"https://drive.google.com/x/{file_id}/view",+ "owners": [{"displayName": "Ada", "emailAddress": "[email protected]"}],+ }+ if size:+ row["size"] = str(size)+ if description:+ row["description"] = description+ return row+++def _transport(+ *,+ listing: list[list[dict[str, Any]]],+ exports: dict[str, str] | None = None,+ contents: dict[str, str] | None = None,+ export_status: dict[str, int] | None = None,+ download_status: dict[str, int] | None = None,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Drive API: a paged listing plus per-file export/download."""++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/drive/v3/files":+ index = int(request.url.params.get("pageToken") or 0)+ page = listing[index] if index < len(listing) else []+ payload: dict[str, Any] = {"files": page}+ if index + 1 < len(listing):+ payload["nextPageToken"] = str(index + 1)+ return httpx.Response(200, json=payload)+ if path.endswith("/export"):+ file_id = path.split("/files/")[1].rsplit("/", 1)[0]+ status = (export_status or {}).get(file_id, 200)+ if status != 200:+ return httpx.Response(status)+ return httpx.Response(200, text=(exports or {}).get(file_id, ""))+ if path.startswith("/drive/v3/files/"):+ file_id = path.rsplit("/", 1)[1]+ status = (download_status or {}).get(file_id, 200)+ if status not in (200, 206):+ return httpx.Response(status)+ return httpx.Response(status, text=(contents or {}).get(file_id, ""))+ return httpx.Response(404)++ return httpx.MockTransport(handler)+++async def _collect(transport: httpx.MockTransport, checkpoint: str | None = None) -> list:+ return [+ item+ async for item in gd.google_drive_pull_adapter(+ _ctx(), checkpoint, transport=transport+ )+ ]+++async def test_a_google_doc_is_exported_to_plain_text():+ doc = _file("f1", "Design notes", _DOC)+ items = await _collect(+ _transport(listing=[[doc]], exports={"f1": "The exported document text."})+ )+ assert len(items) == 1+ item = items[0]+ assert item.external_id == "f1"+ assert item.title == "Design notes"+ assert item.permalink == "https://drive.google.com/x/f1/view"+ assert item.timestamp_utc == "2026-01-01T10:00:00Z"+ assert item.author_raw == "Ada"+ assert "The exported document text." in item.body+ assert f"Google Drive · Design notes · {_DOC}" in item.body+ # The cursor rides on the key the sync runner advances.+ assert item.metadata["mtime_ns"] == g.to_ns("2026-02-01T10:00:00Z")+++async def test_a_spreadsheet_exports_as_csv_and_a_text_file_downloads_bounded():+ sheet = _file("f1", "Budget", _SHEET)+ notes = _file("f2", "notes.md", "text/markdown", size=100)+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ listing=[[sheet, notes]],+ exports={"f1": "a,b\n1,2"},+ contents={"f2": "# Notes"},+ seen=seen,+ )+ )+ assert [item.external_id for item in items] == ["f1", "f2"]+ export_call = next(r for r in seen if r.url.path.endswith("/export"))+ assert export_call.url.params.get("mimeType") == "text/csv"+ download_call = next(+ r for r in seen if r.url.params.get("alt") == "media"+ )+ # Bounded at the source: an oversized file never crosses the wire whole.+ assert download_call.headers.get("Range") == f"bytes=0-{g.BODY_CAP - 1}"+++async def test_binaries_folders_and_shortcuts_are_skipped_honestly():+ listing = [+ [+ _file("f1", "photo.png", "image/png"),+ _file("f2", "archive.zip", "application/zip"),+ _file("f3", "Projects", _FOLDER),+ _file("f4", "scan.pdf", "application/pdf"),+ _file("f5", "notes.txt", "text/plain"),+ ]+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(listing=listing, contents={"f5": "readable"}, seen=seen)+ )+ # Only the text file becomes an item; nothing binary was even requested.+ assert [item.external_id for item in items] == ["f5"]+ fetched = {+ r.url.path.rsplit("/", 1)[1] for r in seen if r.url.params.get("alt") == "media"+ }+ assert fetched == {"f5"}+++async def test_listing_pages_are_walked_to_the_end():+ pages = [+ [_file("f1", "one.txt", "text/plain")],+ [_file("f2", "two.txt", "text/plain")],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(listing=pages, contents={"f1": "one", "f2": "two"}, seen=seen)+ )+ assert [item.external_id for item in items] == ["f1", "f2"]+ list_calls = [r for r in seen if r.url.path == "/drive/v3/files"]+ assert len(list_calls) == 2+++async def test_the_listing_is_non_trashed_and_ordered_by_modified_time():+ seen: list[httpx.Request] = []+ await _collect(_transport(listing=[[]], seen=seen))+ call = next(r for r in seen if r.url.path == "/drive/v3/files")+ assert call.url.params.get("q") == "trashed = false"+ assert call.url.params.get("orderBy") == "modifiedTime"+++async def test_a_numeric_checkpoint_narrows_the_query_by_a_day():+ ns = g.to_ns("2026-03-04T12:00:00Z")+ seen: list[httpx.Request] = []+ await _collect(_transport(listing=[[]], seen=seen), checkpoint=str(ns))+ call = next(r for r in seen if r.url.path == "/drive/v3/files")+ # One day earlier, so a boundary can never skip a file; the rewound+ # overlap upserts as unchanged.+ assert call.url.params.get("q") == (+ "trashed = false and modifiedTime > '2026-03-03T12:00:00Z'"+ )+++async def test_a_backfill_checkpoint_resumes_strictly_after_the_file_id():+ listing = [+ [+ _file("f1", "one.txt", "text/plain", modified="2026-02-01T10:00:00Z"),+ _file("f2", "two.txt", "text/plain", modified="2026-02-02T10:00:00Z"),+ _file("f3", "three.txt", "text/plain", modified="2026-02-03T10:00:00Z"),+ ]+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(listing=listing, contents={"f3": "three"}, seen=seen),+ checkpoint="f2",+ )+ assert [item.external_id for item in items] == ["f3"]+ fetched = {+ r.url.path.rsplit("/", 1)[1] for r in seen if r.url.params.get("alt") == "media"+ }+ # Files before the resume point are never content-fetched again.+ assert fetched == {"f3"}+++async def test_a_vanished_checkpoint_id_degrades_to_a_full_walk():+ listing = [+ [+ _file("f1", "one.txt", "text/plain"),+ _file("f2", "two.txt", "text/plain"),+ ]+ ]+ items = await _collect(+ _transport(listing=listing, contents={"f1": "one", "f2": "two"}),+ checkpoint="trashed-file-id",+ )+ # Silently skipping the whole Drive would be the real bug.+ assert [item.external_id for item in items] == ["f1", "f2"]+++async def test_a_failed_export_degrades_to_metadata_with_an_honest_note():+ doc = _file("f1", "Locked doc", _DOC)+ ok = _file("f2", "notes.txt", "text/plain")+ items = await _collect(+ _transport(+ listing=[[doc, ok]],+ export_status={"f1": 403},+ contents={"f2": "still imported"},+ )+ )+ # One stubborn file must never sink the whole walk.+ assert [item.external_id for item in items] == ["f1", "f2"]+ assert "[content could not be exported (HTTP 403)" in items[0].body+ assert "still imported" in items[1].body+++async def test_an_oversized_download_is_marked_truncated():+ big = _file("f1", "huge.txt", "text/plain", size=g.BODY_CAP + 5)+ items = await _collect(+ _transport(+ listing=[[big]],+ contents={"f1": "the first megabyte"},+ download_status={"f1": 206},+ )+ )+ assert items[0].body.endswith(g.TRUNCATION_MARKER)+ assert items[0].metadata["truncated"] is True+++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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(gd.GoogleAdapterError, match="not connected"):+ await _collect(_transport(listing=[[]], seen=seen))+ assert seen == [] # refused before a single request left the machine+++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, json={"error": {"message": "Invalid Credentials"}})++ with pytest.raises(gd.GoogleAdapterError) as excinfo:+ await _collect(httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "ya29.test" not in message+++def test_the_timestamp_is_iso_utc():+ # Guard the contract shape once: parseable, UTC-anchored.+ doc = _file("f1", "Design notes", _DOC)+ item = gd.item_from_file(doc, "text", False)+ assert item is not None+ parsed = datetime.fromisoformat(item.timestamp_utc.replace("Z", "+00:00"))+ assert parsed.tzinfo is not None+ assert parsed.astimezone(UTC).year == 2026+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(gd.INTEGRATION_ID)+ assert spec is not None and spec.id == "google_drive"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(gd.INTEGRATION_ID, gd.google_drive_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:google_drive") is True+ finally:+ plugin_bridge.unregister_pull_adapter(gd.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_google_mail.py b/tests/unit/ultrawiki/adapters/test_google_mail.pynew file mode 100644index 0000000000..7441344e41--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_google_mail.py@@ -0,0 +1,306 @@+"""The Gmail pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: a stable+external id per message with a real deep link, a deterministic oldest-to-newest+walk so the checkpoint convention holds, text/plain preferred over stripped+HTML with the snippet as the honest floor, attachments counted but never+downloaded, and failure messages a user can act on that never carry the token.+"""++from __future__ import annotations++import base64+from datetime import UTC, datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import _google as g+from jarvis.ultrawiki.adapters import google_mail as gm+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Gmail plugin, without touching the host's keyring."""++ class _Tokens:+ access = "ya29.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-gmail",+ config={"integration_id": "plugin:gmail"},+ secret_get=lambda _name: None,+ )+++def _b64(text: str) -> str:+ """Gmail-shaped base64url: unpadded."""+ return base64.urlsafe_b64encode(text.encode()).decode().rstrip("=")+++def _ms(iso: str) -> int:+ return int(datetime.fromisoformat(iso).replace(tzinfo=UTC).timestamp() * 1000)+++def _message(+ message_id: str,+ iso: str,+ *,+ subject: str = "Quarterly plan",+ sender: str = "Ada <[email protected]>",+ to: str = "[email protected]",+ plain: str | None = "plain body",+ html: str | None = None,+ attachments: int = 0,+ snippet: str = "",+ thread: str = "",+) -> dict[str, Any]:+ parts: list[dict[str, Any]] = []+ if plain is not None:+ parts.append(+ {"mimeType": "text/plain", "filename": "", "body": {"data": _b64(plain)}}+ )+ if html is not None:+ parts.append(+ {"mimeType": "text/html", "filename": "", "body": {"data": _b64(html)}}+ )+ for i in range(attachments):+ parts.append(+ {+ "mimeType": "application/pdf",+ "filename": f"report-{i}.pdf",+ "body": {"attachmentId": f"att-{i}", "size": 12345},+ }+ )+ return {+ "id": message_id,+ "threadId": thread or f"t-{message_id}",+ "internalDate": str(_ms(iso)),+ "snippet": snippet,+ "historyId": "4711",+ "labelIds": ["INBOX"],+ "payload": {+ "mimeType": "multipart/mixed",+ "filename": "",+ "headers": [+ {"name": "Subject", "value": subject},+ {"name": "From", "value": sender},+ {"name": "To", "value": to},+ ],+ "parts": parts,+ },+ }+++def _transport(+ *,+ listing: list[list[dict[str, Any]]],+ messages: dict[str, dict[str, Any]],+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Gmail: a paged newest-first id listing plus per-id full fetches."""++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/gmail/v1/users/me/messages":+ index = int(request.url.params.get("pageToken") or 0)+ page = listing[index] if index < len(listing) else []+ payload: dict[str, Any] = {+ "messages": [{"id": row["id"], "threadId": row["threadId"]} for row in page]+ }+ if index + 1 < len(listing):+ payload["nextPageToken"] = str(index + 1)+ return httpx.Response(200, json=payload)+ if path.startswith("/gmail/v1/users/me/messages/"):+ body = messages.get(path.rsplit("/", 1)[1])+ if body is None:+ return httpx.Response(404)+ return httpx.Response(200, json=body)+ return httpx.Response(404)++ return httpx.MockTransport(handler)+++async def _collect(transport: httpx.MockTransport, checkpoint: str | None = None) -> list:+ return [+ item+ async for item in gm.gmail_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_messages_arrive_oldest_first_with_stable_ids_and_deep_links():+ older = _message("m1", "2026-03-01T10:00:00")+ newer = _message("m2", "2026-03-02T10:00:00")+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(listing=[[newer, older]], messages={"m1": older, "m2": newer}, seen=seen)+ )+ # The API lists newest first; the walk must still be oldest to newest so+ # the checkpoint convention (resume strictly after) holds.+ assert [item.external_id for item in items] == ["m1", "m2"]+ first = items[0]+ assert first.permalink == "https://mail.google.com/mail/u/0/#all/m1"+ assert first.title == "Quarterly plan"+ assert first.timestamp_utc == "2026-03-01T10:00:00Z"+ assert first.thread_key == "t-m1"+ assert first.author_raw == "Ada <[email protected]>"+ assert "from Ada <[email protected]>" in first.body+ assert "to [email protected]" in first.body+ # The cursor rides on the key the sync runner advances.+ assert first.metadata["mtime_ns"] == _ms("2026-03-01T10:00:00") * 1_000_000+ # Bodies come from ONE format=full fetch per message.+ fetch = next(r for r in seen if r.url.path.endswith("/messages/m1"))+ assert fetch.url.params.get("format") == "full"+++async def test_the_plain_text_part_is_preferred_over_html():+ message = _message(+ "m1", "2026-03-01T10:00:00", plain="the plain truth", html="<p>the html copy</p>"+ )+ items = await _collect(_transport(listing=[[message]], messages={"m1": message}))+ assert "the plain truth" in items[0].body+ assert "html copy" not in items[0].body+++async def test_an_html_only_message_is_stripped_to_readable_text():+ message = _message(+ "m1",+ "2026-03-01T10:00:00",+ plain=None,+ html="<html><body><p>First line</p><p>Second <b>line</b></p></body></html>",+ )+ items = await _collect(_transport(listing=[[message]], messages={"m1": message}))+ body = items[0].body+ assert "First line" in body+ assert "Second line" in body+ # No markup survives; the "<" in the header is the sender's address.+ assert "<p>" not in body+ assert "<b>" not in body+++async def test_a_message_with_no_decodable_part_falls_back_to_the_snippet():+ message = _message(+ "m1", "2026-03-01T10:00:00", plain=None, snippet="the short preview"+ )+ items = await _collect(_transport(listing=[[message]], messages={"m1": message}))+ assert "the short preview" in items[0].body+++async def test_attachments_are_counted_never_downloaded():+ message = _message("m1", "2026-03-01T10:00:00", attachments=2)+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(listing=[[message]], messages={"m1": message}, seen=seen)+ )+ body = items[0].body+ assert "[2 attachment(s) not imported" in body+ assert items[0].metadata["attachments"] == 2+ # No request beyond the listing and the message fetch: binaries never move.+ assert all("attachment" not in request.url.path for request in seen)+++async def test_listing_pages_are_walked_to_the_end():+ first = _message("m1", "2026-03-01T10:00:00")+ second = _message("m2", "2026-03-02T10:00:00")+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ listing=[[second], [first]],+ messages={"m1": first, "m2": second},+ seen=seen,+ )+ )+ assert [item.external_id for item in items] == ["m1", "m2"]+ list_calls = [r for r in seen if r.url.path == "/gmail/v1/users/me/messages"]+ assert len(list_calls) == 2+++async def test_a_numeric_checkpoint_narrows_the_listing_by_a_day():+ ns = g.to_ns("2026-03-04T12:00:00Z")+ seen: list[httpx.Request] = []+ await _collect(_transport(listing=[[]], messages={}, seen=seen), checkpoint=str(ns))+ call = next(r for r in seen if r.url.path == "/gmail/v1/users/me/messages")+ # One day earlier, so a boundary can never skip a message; the rewound+ # overlap upserts as unchanged.+ expected = int(datetime(2026, 3, 3, 12, 0, 0, tzinfo=UTC).timestamp())+ assert call.url.params.get("q") == f"after:{expected}"+++async def test_a_backfill_checkpoint_resumes_strictly_after_the_message_id():+ rows = [_message(f"m{i}", f"2026-03-0{i}T10:00:00") for i in (1, 2, 3)]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ listing=[[rows[2], rows[1], rows[0]]],+ messages={row["id"]: row for row in rows},+ seen=seen,+ ),+ checkpoint="m2",+ )+ assert [item.external_id for item in items] == ["m3"]+ fetched = {r.url.path.rsplit("/", 1)[1] for r in seen if "/messages/" in r.url.path}+ # Already-imported messages are never body-fetched again.+ assert fetched == {"m3"}+++async def test_a_vanished_checkpoint_id_degrades_to_a_full_walk():+ rows = [_message(f"m{i}", f"2026-03-0{i}T10:00:00") for i in (1, 2)]+ items = await _collect(+ _transport(+ listing=[[rows[1], rows[0]]], messages={row["id"]: row for row in rows}+ ),+ checkpoint="deleted-id",+ )+ # Silently skipping the whole mailbox would be the real bug.+ assert [item.external_id for item in items] == ["m1", "m2"]+++async def test_an_oversized_body_is_capped_and_marked():+ message = _message("m1", "2026-03-01T10:00:00", plain="x" * (g.BODY_CAP + 10))+ items = await _collect(_transport(listing=[[message]], messages={"m1": message}))+ assert items[0].body.endswith(g.TRUNCATION_MARKER)+ assert items[0].metadata["truncated"] is True+++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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(gm.GoogleAdapterError, match="not connected"):+ await _collect(_transport(listing=[[]], messages={}, seen=seen))+ assert seen == [] # refused before a single request left the machine+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(gm.INTEGRATION_ID)+ assert spec is not None and spec.id == "gmail"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(gm.INTEGRATION_ID, gm.gmail_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:gmail") is True+ finally:+ plugin_bridge.unregister_pull_adapter(gm.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_google_shared.py b/tests/unit/ultrawiki/adapters/test_google_shared.pynew file mode 100644index 0000000000..a1ec079dcf--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_google_shared.py@@ -0,0 +1,199 @@+"""The shared Google plumbing, driven fully offline through MockTransport.++These tests pin the family-wide guarantees every Google adapter leans on:+bounded rate-limit retries that honour ``Retry-After``, credential failures+that become actionable sentences and never echo the token, and the text+helpers (body cap, HTML stripping, base64url) that keep imports memory-shaped.+"""++from __future__ import annotations++import httpx+import pytest++from jarvis.ultrawiki.adapters import _google as g++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Google plugin, without touching the host's keyring."""++ class _Tokens:+ access = "ya29.test"+ needs_reauth = False++ class _Store:+ def load(self, _plugin_id):+ return _Tokens()++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+++# ---------------------------------------------------------------------------+# Rate limits — bounded waits, honest surrender+# ---------------------------------------------------------------------------+++async def test_a_throttled_request_waits_and_then_succeeds():+ calls: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ calls.append(request)+ if len(calls) == 1:+ return httpx.Response(429, headers={"Retry-After": "0"})+ return httpx.Response(200, json={"ok": True})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ payload = await g.google_get_json(+ client, "https://example.test/x", "tok", "Gmail"+ )+ assert payload == {"ok": True}+ assert len(calls) == 2+++async def test_a_persistently_throttled_request_gives_up_honestly():+ calls: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ calls.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(g.GoogleAdapterError, match="rate limit"):+ await g.google_get(client, "https://example.test/x", "tok", "Gmail")+ # Bounded: the retry budget is spent, never a spin.+ assert len(calls) == 3+++async def test_a_quota_shaped_403_counts_as_throttling_not_as_a_scope_problem():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 403,+ json={"error": {"errors": [{"reason": "rateLimitExceeded"}]}},+ headers={"Retry-After": "0"},+ )++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(g.GoogleAdapterError, match="rate limit"):+ await g.google_get(client, "https://example.test/x", "tok", "Drive")+++# ---------------------------------------------------------------------------+# Credential failures — actionable, token never echoed+# ---------------------------------------------------------------------------+++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, json={"error": {"message": "Invalid Credentials"}})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(g.GoogleAdapterError) as excinfo:+ await g.google_get(client, "https://example.test/x", "ya29.secret", "Gmail")+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "ya29.secret" not in message+++async def test_a_tolerated_status_comes_back_to_the_caller():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(404)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ response = await g.google_get(+ client, "https://example.test/x", "tok", "Drive", tolerate=(404,)+ )+ assert response.status_code == 404+++def test_an_unconnected_plugin_refuses_with_the_store_as_the_fix(monkeypatch):+ class _Store:+ def load(self, _plugin_id):+ return None++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+ with pytest.raises(g.GoogleAdapterError, match="not connected"):+ g.google_token("gmail", "Gmail")+++def test_an_expired_connection_is_named_as_such(monkeypatch):+ class _Tokens:+ access = "ya29.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(g.GoogleAdapterError, match="expired"):+ g.google_token("google_drive", "Google Drive")+++def test_a_broken_credential_store_is_a_sentence_not_a_stack_trace(monkeypatch):+ class _Store:+ def load(self, _plugin_id):+ raise OSError("keyring backend unavailable")++ monkeypatch.setattr(+ "jarvis.marketplace.token_store.TokenStore", lambda *a, **k: _Store()+ )+ with pytest.raises(g.GoogleAdapterError, match="credential store"):+ g.google_token("google_calendar", "Google Calendar")+++# ---------------------------------------------------------------------------+# Text helpers — the memory-shaped scope+# ---------------------------------------------------------------------------+++def test_an_oversized_body_is_capped_and_marked():+ body, truncated = g.cap_body("x" * (g.BODY_CAP + 10))+ assert truncated is True+ assert body.endswith(g.TRUNCATION_MARKER)+ assert len(body) == g.BODY_CAP + len(g.TRUNCATION_MARKER)+++def test_a_small_body_passes_untouched():+ body, truncated = g.cap_body("hello")+ assert (body, truncated) == ("hello", False)+++def test_html_is_stripped_to_readable_text_without_scripts():+ markup = (+ "<html><head><style>p{color:red}</style></head><body>"+ "<script>alert('x')</script><p>First line</p><p>Second <b>line</b></p>"+ "</body></html>"+ )+ text = g.strip_html(markup)+ assert "First line" in text+ assert "Second line" in text+ assert "alert" not in text+ assert "color" not in text+ assert "<" not in text+++def test_base64url_junk_degrades_to_empty_never_a_crash():+ assert g.decode_base64url("!!not base64!!") == ""+ assert g.decode_base64url("") == ""+ # Unpadded base64url (Gmail's shape) round-trips.+ assert g.decode_base64url("aGVsbG8") == "hello"+++def test_a_numeric_cursor_becomes_a_day_earlier_cutoff():+ ns = g.to_ns("2026-03-04T12:00:00Z")+ cutoff = g.cursor_cutoff(str(ns))+ assert cutoff is not None+ assert cutoff.strftime("%Y-%m-%dT%H:%M:%SZ") == "2026-03-03T12:00:00Z"+++def test_a_backfill_external_id_checkpoint_is_not_a_cursor():+ assert g.cursor_cutoff("18c0f00aa1") is None+ assert g.cursor_cutoff(None) is None+ assert g.cursor_cutoff("") is Nonediff --git a/tests/unit/ultrawiki/adapters/test_linear.py b/tests/unit/ultrawiki/adapters/test_linear.pynew file mode 100644index 0000000000..fba26c867b--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_linear.py@@ -0,0 +1,318 @@+"""The Linear pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-issue ids (a re-run must upsert, not duplicate), a real deep link on every+item, archived and completed issues included, inline comments folded+chronologically with an honest marker when more exist, deterministic+oldest-to-newest streaming for the backfill checkpoint, bounded 429 handling,+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 linear as lin+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Linear plugin, without touching the host's keyring."""++ class _Tokens:+ access = "lin_api_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-linear",+ config={"integration_id": "plugin:linear"},+ secret_get=lambda _name: None,+ )+++def _comment(iso: str, body: str, author: str = "Alice") -> dict[str, Any]:+ return {"body": body, "createdAt": iso, "user": {"name": author}}+++def _issue(issue_id: str = "abc-1", **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "id": issue_id,+ "identifier": "ENG-7",+ "title": "Ship the wake-word fix",+ "description": "The wake word misses every third call.",+ "url": "https://linear.app/acme/issue/ENG-7/ship-the-wake-word-fix",+ "createdAt": "2026-03-01T10:00:00.000Z",+ "updatedAt": "2026-03-04T12:00:00.000Z",+ "archivedAt": None,+ "dueDate": "2026-04-01",+ "state": {"name": "In Progress"},+ "assignee": {"name": "Alice"},+ "creator": {"name": "Bob"},+ "team": {"id": "team-1", "key": "ENG", "name": "Engineering"},+ "project": {"name": "Voice"},+ "comments": {"nodes": [], "pageInfo": {"hasNextPage": False}},+ }+ base.update(overrides)+ return base+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _transport(+ pages: list[list[dict[str, Any]]],+ *,+ rate_limit_first: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Linear workspace: one GraphQL endpoint, cursor-paged."""+ remaining_429 = {"n": rate_limit_first}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ variables = json.loads(request.content.decode())["variables"]+ after = variables.get("after")+ index = int(after) if after else 0+ nodes = pages[index] if index < len(pages) else []+ has_next = index + 1 < len(pages)+ return _json(+ {+ "data": {+ "issues": {+ "nodes": nodes,+ "pageInfo": {"hasNextPage": has_next, "endCursor": str(index + 1)},+ }+ }+ }+ )++ return httpx.MockTransport(handler)+++async def _collect(+ transport: httpx.MockTransport, checkpoint: str | None = None+) -> list:+ return [+ item+ async for item in lin.linear_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_an_issue_becomes_a_linkable_dated_item():+ issue = _issue(+ comments={+ "nodes": [+ _comment("2026-03-02T09:00:00.000Z", "On it"),+ _comment("2026-03-01T11:00:00.000Z", "Can you take this?", author="Bob"),+ ],+ "pageInfo": {"hasNextPage": False},+ }+ )+ items = await _collect(_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:abc-1"+ # Evidence has to lead back to where it lives — mandatory from item one.+ assert item.permalink == "https://linear.app/acme/issue/ENG-7/ship-the-wake-word-fix"+ # WHEN IT HAPPENED, not when it was last touched.+ assert item.timestamp_utc == "2026-03-01T10:00:00.000Z"+ assert item.title == "Ship the wake-word fix"+ assert item.author_raw == "Bob"+ assert item.thread_key == "team-1"+ # The composed header keeps the context a bare description would lose.+ assert "Engineering · issue ENG-7 · In Progress" in item.body+ assert "project Voice" in item.body+ assert "assigned to Alice" in item.body+ assert "due 2026-04-01" in item.body+ assert "The wake word misses every third call." in item.body+ # Comments fold in chronologically, oldest first.+ assert item.body.index("Can you take this?") < item.body.index("On it")+ # The cursor rides on the key the sync runner advances.+ assert item.metadata["mtime_ns"] == lin._to_ns("2026-03-04T12:00:00.000Z")+ assert item.metadata["comments"] == 2+++async def test_archived_issues_are_asked_for_and_labelled():+ seen: list[httpx.Request] = []+ archived = _issue(archivedAt="2026-03-10T08:00:00.000Z", state={"name": "Done"})+ items = await _collect(_transport([[archived]], seen=seen))+ assert items[0].metadata["archived"] is True+ assert "archived" in items[0].body+ # The query itself must ask for archived rows, or they silently vanish.+ query = json.loads(seen[0].content.decode())["query"]+ assert "includeArchived: true" in query+++async def test_comments_beyond_the_inline_page_are_declared():+ issue = _issue(+ comments={+ "nodes": [_comment("2026-03-01T11:00:00.000Z", "first of many")],+ "pageInfo": {"hasNextPage": True},+ }+ )+ items = await _collect(_transport([[issue]]))+ assert "[more comments on Linear — open the link to read them]" in items[0].body+++async def test_a_numeric_checkpoint_becomes_an_updated_at_filter():+ seen: list[httpx.Request] = []+ await _collect(+ _transport([[]], seen=seen),+ checkpoint=str(lin._to_ns("2026-03-04T12:00:00Z")),+ )+ variables = json.loads(seen[0].content.decode())["variables"]+ # Five minutes before the cursor: the overlap is what makes a boundary+ # safe; re-yielded items upsert as unchanged.+ assert variables["filter"] == {"updatedAt": {"gte": "2026-03-04T11:55:00Z"}}+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ first = _issue("aaa", createdAt="2026-03-01T10:00:00.000Z")+ second = _issue("bbb", createdAt="2026-03-02T10:00:00.000Z")+ items = await _collect(_transport([[first, second]]), checkpoint="issue:aaa")+ assert [item.external_id for item in items] == ["issue:bbb"]+++async def test_an_unknown_checkpoint_shape_is_read_as_no_cursor():+ seen: list[httpx.Request] = []+ items = await _collect(_transport([[_issue()]], seen=seen), checkpoint="task:42")+ assert len(items) == 1+ variables = json.loads(seen[0].content.decode())["variables"]+ assert "filter" not in variables+++async def test_cursor_pages_are_walked_to_the_end():+ pages = [+ [_issue("aaa", createdAt="2026-03-01T10:00:00.000Z")],+ [_issue("bbb", createdAt="2026-03-02T10:00:00.000Z")],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(_transport(pages, seen=seen))+ assert len(items) == 2+ assert len(seen) == 2 # one request per page, then pageInfo said stop+++async def test_items_stream_oldest_to_newest_deterministically():+ newest_first = [+ _issue("zzz", createdAt="2026-03-05T10:00:00.000Z"),+ _issue("aaa", createdAt="2026-02-01T10:00:00.000Z"),+ ]+ items = await _collect(_transport([newest_first]))+ assert [item.external_id for item in items] == ["issue:aaa", "issue:zzz"]+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(_transport([[_issue()]], rate_limit_first=1, seen=seen))+ assert len(items) == 1+ assert len(seen) == 2 # the 429, then the honoured retry+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(lin.LinearAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == lin._MAX_ATTEMPTS # bounded, never an endless retry loop+++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'{"error":"Unauthorized"}')++ with pytest.raises(lin.LinearAdapterError) as excinfo:+ await _collect(httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "lin_api_test" not in message+++async def test_a_graphql_auth_error_is_mapped_like_a_401():+ """Linear can answer HTTP 200 with an in-band authentication error."""++ def handler(request: httpx.Request) -> httpx.Response:+ return _json(+ {+ "errors": [+ {+ "message": "Authentication required",+ "extensions": {"code": "AUTHENTICATION_ERROR"},+ }+ ]+ }+ )++ with pytest.raises(lin.LinearAdapterError, match="Reconnect"):+ await _collect(httpx.MockTransport(handler))+++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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(lin.LinearAdapterError, match="not connected"):+ await _collect(_transport([[]], seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_an_oversized_item_is_capped_with_a_marker():+ huge = _issue(description="x" * 1_100_000)+ items = await _collect(_transport([[huge]]))+ body = items[0].body+ assert body.endswith("[truncated — the full text lives at the link above]")+ assert len(body) < 1_100_000+++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([[_issue(url=""), _issue("keep")]]))+ assert [item.external_id for item in items] == ["issue:keep"]+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(lin.INTEGRATION_ID)+ assert spec is not None and spec.id == "linear"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(lin.INTEGRATION_ID, lin.linear_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:linear") is True+ finally:+ plugin_bridge.unregister_pull_adapter(lin.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_notion.py b/tests/unit/ultrawiki/adapters/test_notion.pynew file mode 100644index 0000000000..e9d8d90780--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_notion.py@@ -0,0 +1,444 @@+"""The Notion pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-page and per-row ids (a re-run must upsert, not duplicate), Notion's own+deep link on every item, faithful plain-text rendering of the block tree with+bounded depth and a cycle guard, per-database degradation instead of+all-or-nothing failure, bounded 429 handling, and failure messages a user can+act on that never carry the token.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import notion as no+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Notion plugin, without touching the host's keyring."""++ class _Tokens:+ access = "ntn-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-notion",+ config={"integration_id": "plugin:notion"},+ secret_get=lambda _name: None,+ )+++def _rt(text: str) -> list[dict[str, Any]]:+ return [{"type": "text", "plain_text": text}]+++def _page_obj(+ pid: str,+ title: str = "Untitled",+ edited: str = "2026-03-01T10:00:00.000Z",+ created: str = "2026-02-01T09:00:00.000Z",+ parent: dict[str, Any] | None = None,+ props: dict[str, Any] | None = None,+) -> dict[str, Any]:+ properties: dict[str, Any] = {"Name": {"id": "title", "type": "title", "title": _rt(title)}}+ properties.update(props or {})+ return {+ "object": "page",+ "id": pid,+ "created_time": created,+ "last_edited_time": edited,+ "parent": parent or {"type": "workspace", "workspace": True},+ "url": f"https://www.notion.so/{pid}",+ "properties": properties,+ }+++def _db_obj(+ did: str, title: str = "Tasks", edited: str = "2026-03-01T08:00:00.000Z"+) -> dict[str, Any]:+ return {+ "object": "database",+ "id": did,+ "created_time": "2026-01-01T00:00:00.000Z",+ "last_edited_time": edited,+ "title": _rt(title),+ "url": f"https://www.notion.so/{did}",+ }+++def _block(+ bid: str, btype: str, text: str = "", has_children: bool = False, **payload: Any+) -> dict[str, Any]:+ content: dict[str, Any] = {"rich_text": _rt(text) if text else []}+ content.update(payload)+ return {+ "object": "block",+ "id": bid,+ "type": btype,+ "has_children": has_children,+ btype: content,+ }+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _paged(pages: list[list[dict[str, Any]]], index: int) -> httpx.Response:+ page = pages[index] if index < len(pages) else []+ more = index + 1 < len(pages)+ return _json(+ {+ "object": "list",+ "results": page,+ "has_more": more,+ "next_cursor": str(index + 1) if more else None,+ }+ )+++def _transport(+ *,+ search: list[list[dict[str, Any]]] | None = None,+ queries: dict[str, list[list[dict[str, Any]]]] | None = None,+ blocks: dict[str, list[list[dict[str, Any]]]] | None = None,+ query_errors: dict[str, int] | None = None,+ me_status: int = 200,+ rate_limit_first: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake shared Notion workspace: dispatches by API path."""+ remaining_429 = {"n": rate_limit_first}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ path = request.url.path+ if path == "/v1/users/me":+ if me_status != 200:+ return httpx.Response(me_status)+ return _json({"object": "user", "type": "bot", "name": "Test Bot"})+ if path == "/v1/search":+ body = json.loads(request.content or b"{}")+ return _paged(search or [[]], int(body.get("start_cursor") or 0))+ if path.startswith("/v1/databases/") and path.endswith("/query"):+ did = path.split("/")[3]+ if did in (query_errors or {}):+ return httpx.Response((query_errors or {})[did])+ body = json.loads(request.content or b"{}")+ return _paged((queries or {}).get(did, [[]]), int(body.get("start_cursor") or 0))+ if path.startswith("/v1/blocks/") and path.endswith("/children"):+ bid = path.split("/")[3]+ index = int(request.url.params.get("start_cursor") or 0)+ return _paged((blocks or {}).get(bid, [[]]), index)+ return httpx.Response(404)++ return httpx.MockTransport(handler)+++async def _collect(transport: httpx.MockTransport, checkpoint: str | None = None) -> list:+ return [+ item+ async for item in no.notion_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_a_page_becomes_one_item_with_rendered_blocks():+ page = _page_obj("page-1", "Launch plan", edited="2026-03-01T10:00:00.000Z")+ root = [+ _block("b1", "heading_1", "Plan"),+ _block("b2", "paragraph", "We ship on Friday."),+ _block("b3", "bulleted_list_item", "pack the build"),+ _block("b4", "numbered_list_item", "first step"),+ _block("b5", "numbered_list_item", "second step"),+ _block("b6", "to_do", "write docs", checked=True),+ _block("b7", "to_do", "record demo", checked=False),+ _block("b8", "quote", "measure twice"),+ _block("b9", "code", "print('hi')", language="python"),+ _block("b10", "callout", "watch the deadline"),+ _block("b11", "toggle", "details", has_children=True),+ ]+ toggle_children = [_block("b12", "paragraph", "hidden note")]+ items = await _collect(+ _transport(search=[[page]], blocks={"page-1": [root], "b11": [toggle_children]})+ )+ 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 == "page-1"+ assert item.title == "Launch plan"+ assert item.permalink == "https://www.notion.so/page-1"+ assert item.timestamp_utc == "2026-03-01T10:00:00.000Z"+ body = item.body+ assert "# Plan" in body+ assert "We ship on Friday." in body+ assert "- pack the build" in body+ assert "1. first step" in body and "2. second step" in body+ assert "[x] write docs" in body and "[ ] record demo" in body+ assert "> measure twice" in body+ assert "```python\nprint('hi')\n```" in body+ assert "[callout] watch the deadline" in body+ # The toggle's hidden children are rendered, indented one level deeper.+ assert "\n hidden note" in body+ assert item.metadata["kind"] == "page"+ assert item.metadata["mtime_ns"] == no._to_ns("2026-03-01T10:00:00.000Z")+++async def test_database_rows_flatten_their_properties():+ db = _db_obj("db-1", "Projects")+ row = _page_obj(+ "row-1",+ "Apollo",+ edited="2026-03-02T12:00:00.000Z",+ parent={"type": "database_id", "database_id": "db-1"},+ props={+ "Status": {"type": "status", "status": {"name": "Done"}},+ "Priority": {"type": "select", "select": {"name": "High"}},+ "Tags": {"type": "multi_select", "multi_select": [{"name": "a"}, {"name": "b"}]},+ "Due": {"type": "date", "date": {"start": "2026-03-05"}},+ "Shipped": {"type": "checkbox", "checkbox": True},+ "Estimate": {"type": "number", "number": 3},+ },+ )+ items = await _collect(_transport(search=[[db]], queries={"db-1": [[row]]}))+ assert len(items) == 1+ item = items[0]+ assert item.external_id == "row-1"+ assert item.title == "Apollo"+ assert item.thread_key == "db-1"+ assert item.timestamp_utc == "2026-03-02T12:00:00.000Z"+ body = item.body+ assert "Projects · database row" in body+ assert "Status: Done" in body+ assert "Priority: High" in body+ assert "Tags: a, b" in body+ assert "Due: 2026-03-05" in body+ assert "Shipped: yes" in body+ assert "Estimate: 3" in body+ assert item.metadata["kind"] == "database_row"+ assert item.metadata["database_title"] == "Projects"+++async def test_a_row_seen_via_search_and_query_is_yielded_once():+ db = _db_obj("db-1", "Projects")+ row = _page_obj(+ "row-1", "Apollo", parent={"type": "database_id", "database_id": "db-1"}+ )+ # Search returns BOTH the database and its row page; the row must not+ # import twice under the same id.+ items = await _collect(_transport(search=[[db, row]], queries={"db-1": [[row]]}))+ assert [item.external_id for item in items] == ["row-1"]+++async def test_an_unqueryable_database_degrades_to_its_search_rows():+ """A linked or restricted database refuses its query; a row page the token+ can see still arrives via search and must import, not vanish."""+ db = _db_obj("db-1", "Projects")+ row = _page_obj(+ "row-1", "Apollo", parent={"type": "database_id", "database_id": "db-1"}+ )+ items = await _collect(_transport(search=[[db, row]], query_errors={"db-1": 404}))+ assert [item.external_id for item in items] == ["row-1"]+ assert items[0].thread_key == "db-1"+ assert items[0].metadata["kind"] == "database_row"+++async def test_nested_blocks_stop_at_the_depth_cap_with_a_marker():+ page = _page_obj("page-1", "Deep")+ blocks: dict[str, list[list[dict[str, Any]]]] = {}+ parent = "page-1"+ for level in range(10):+ bid = f"chain-{level}"+ blocks[parent] = [[_block(bid, "paragraph", f"level{level}", has_children=True)]]+ parent = bid+ blocks[parent] = [[_block("tail", "paragraph", "level10")]]+ items = await _collect(_transport(search=[[page]], blocks=blocks))+ body = items[0].body+ assert "level7" in body+ assert "level8" not in body # beyond the bounded depth+ assert no._DEPTH_MARKER in body+++async def test_a_self_referencing_block_does_not_loop_the_import():+ page = _page_obj("page-1", "Loop")+ loop_block = _block("loop", "toggle", "spin", has_children=True)+ items = await _collect(+ _transport(+ search=[[page]],+ blocks={"page-1": [[loop_block]], "loop": [[loop_block]]},+ )+ )+ assert len(items) == 1 # terminated — the cycle guard broke the recursion+ assert "spin" in items[0].body+++async def test_search_and_block_pages_are_walked_to_the_end():+ pages = [+ [_page_obj("p1", "One", edited="2026-03-01T10:00:00.000Z")],+ [_page_obj("p2", "Two", edited="2026-03-02T10:00:00.000Z")],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ search=pages,+ blocks={+ "p1": [+ [_block("b1", "paragraph", "from page one")],+ [_block("b2", "paragraph", "from block page two")],+ ]+ },+ seen=seen,+ )+ )+ assert [item.external_id for item in items] == ["p1", "p2"]+ assert "from page one" in items[0].body+ assert "from block page two" in items[0].body+ search_calls = [r for r in seen if r.url.path == "/v1/search"]+ assert len(search_calls) == 2+ block_calls = [r for r in seen if r.url.path == "/v1/blocks/b1/children"]+ assert len(block_calls) == 0 # only listed children fetch further pages+ root_calls = [r for r in seen if r.url.path == "/v1/blocks/p1/children"]+ assert len(root_calls) == 2+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ search=[[_page_obj("p1", "One")]],+ rate_limit_first=1,+ seen=seen,+ )+ )+ assert [item.external_id for item in items] == ["p1"]+ me_calls = [r for r in seen if r.url.path == "/v1/users/me"]+ assert len(me_calls) == 2 # the 429, then the honoured retry+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(no.NotionAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == no._MAX_ATTEMPTS # bounded, never an endless retry loop+++async def test_a_revoked_token_says_what_to_do_and_never_echoes_it():+ with pytest.raises(no.NotionAdapterError) as excinfo:+ await _collect(_transport(me_status=401))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "ntn-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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(no.NotionAdapterError, match="not connected"):+ await _collect(_transport(seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_a_numeric_checkpoint_narrows_by_last_edited_time():+ moment = datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC)+ db = _db_obj("db-1", "Projects")+ stale = _page_obj("old-page", "Old", edited="2026-02-01T10:00:00.000Z")+ fresh = _page_obj("new-page", "Fresh", edited="2026-03-04T09:00:00.000Z")+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(search=[[db, stale, fresh]], seen=seen),+ checkpoint=str(int(moment.timestamp() * 1_000_000_000)),+ )+ # The previous UTC day, not the cursor's own day: a whole-day rewind is+ # what guarantees nothing is skipped at a boundary; overlaps upsert.+ query = next(r for r in seen if r.url.path == "/v1/databases/db-1/query")+ body = json.loads(query.content)+ assert body["filter"]["last_edited_time"] == {"on_or_after": "2026-03-03"}+ # The untouched page is skipped WITHOUT spending its block requests...+ assert [item.external_id for item in items] == ["new-page"]+ assert not any(r.url.path == "/v1/blocks/old-page/children" for r in seen)+ # ...while the touched page is re-yielded in full.+ assert any(r.url.path == "/v1/blocks/new-page/children" for r in seen)+++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 cursor, and mis-parsing it would silently skip history."""+ db = _db_obj("db-1", "Projects")+ seen: list[httpx.Request] = []+ await _collect(_transport(search=[[db]], seen=seen), checkpoint="row-1")+ query = next(r for r in seen if r.url.path == "/v1/databases/db-1/query")+ assert "filter" not in json.loads(query.content)+++async def test_an_oversized_item_is_capped_with_a_marker():+ page = _page_obj("page-1", "Huge")+ huge = _block("b1", "paragraph", "x" * 1_100_000)+ items = await _collect(_transport(search=[[page]], blocks={"page-1": [[huge]]}))+ body = items[0].body+ assert body.endswith("[truncated — this item exceeded the 1 MB import cap]")+ assert len(body.encode("utf-8")) < 1_100_000+++async def test_media_blocks_become_markers_never_binaries():+ page = _page_obj("page-1", "Media")+ root = [+ _block("b1", "image", caption=_rt("architecture sketch")),+ _block("b2", "file", name="notes.pdf"),+ _block("b3", "bookmark", url="https://example.com/post"),+ ]+ items = await _collect(_transport(search=[[page]], blocks={"page-1": [root]}))+ body = items[0].body+ assert "[image: architecture sketch]" in body+ assert "[file: notes.pdf]" in body+ assert "https://example.com/post" in body+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(no.INTEGRATION_ID)+ assert spec is not None and spec.id == "notion"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(no.INTEGRATION_ID, no.notion_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:notion") is True+ finally:+ plugin_bridge.unregister_pull_adapter(no.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_slack.py b/tests/unit/ultrawiki/adapters/test_slack.pynew file mode 100644index 0000000000..e9ae98698d--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_slack.py@@ -0,0 +1,400 @@+"""The Slack pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-thread and per-day ids (a re-run must upsert, not duplicate), a real deep+link on every item, chronological ``author: text`` rendering, per-scope+degradation instead of all-or-nothing failure, bounded 429 handling, and+failure messages a user can act on that never carry the token.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import slack as sl+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Slack plugin, without touching the host's keyring."""++ class _Tokens:+ access = "xoxb-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-slack",+ config={"integration_id": "plugin:slack"},+ secret_get=lambda _name: None,+ )+++def _ts(iso: str, micro: str = "000100") -> str:+ moment = datetime.fromisoformat(iso).replace(tzinfo=UTC)+ return f"{int(moment.timestamp())}.{micro}"+++def _msg(iso: str, user: str = "U1", text: str = "hello", **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {"type": "message", "ts": _ts(iso), "user": user, "text": text}+ base.update(overrides)+ return base+++def _channel(cid: str = "C1", name: str = "general", created: int = 100, **overrides: Any):+ base: dict[str, Any] = {"id": cid, "name": name, "created": created}+ base.update(overrides)+ return base+++_USERS = [+ {"id": "U1", "name": "alice", "profile": {"display_name": "Alice"}},+ {"id": "U2", "name": "bob", "profile": {"display_name": "Bob"}},+]+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _transport(+ *,+ channels: dict[str, list[dict[str, Any]]] | None = None,+ history: dict[str, list[list[dict[str, Any]]]] | None = None,+ replies: dict[tuple[str, str], list[dict[str, Any]]] | None = None,+ users: list[dict[str, Any]] | None = None,+ auth: dict[str, Any] | None = None,+ missing_scope_types: frozenset[str] = frozenset(),+ history_errors: dict[str, str] | None = None,+ rate_limit_first_history: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Slack workspace: dispatches by Web API method path."""+ remaining_429 = {"n": rate_limit_first_history}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ params = request.url.params+ if path == "/api/auth.test":+ return _json(auth or {"ok": True, "url": "https://acme.slack.com/"})+ if path == "/api/users.list":+ return _json({"ok": True, "members": users if users is not None else _USERS})+ if path == "/api/conversations.list":+ conv_type = params.get("types") or ""+ if conv_type in missing_scope_types:+ return _json({"ok": False, "error": "missing_scope"})+ return _json({"ok": True, "channels": (channels or {}).get(conv_type, [])})+ if path == "/api/conversations.history":+ channel = params.get("channel") or ""+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ if channel in (history_errors or {}):+ return _json({"ok": False, "error": (history_errors or {})[channel]})+ pages = (history or {}).get(channel, [[]])+ index = int(params.get("cursor") or 0)+ page = pages[index] if index < len(pages) else []+ next_cursor = str(index + 1) if index + 1 < len(pages) else ""+ return _json(+ {+ "ok": True,+ "messages": page,+ "has_more": bool(next_cursor),+ "response_metadata": {"next_cursor": next_cursor},+ }+ )+ if path == "/api/conversations.replies":+ key = (params.get("channel") or "", params.get("ts") or "")+ return _json({"ok": True, "messages": (replies or {}).get(key, [])})+ return _json({"ok": False, "error": "unknown_method"})++ return httpx.MockTransport(handler)+++async def _collect(+ transport: httpx.MockTransport, checkpoint: str | None = None+) -> list:+ return [+ item+ async for item in sl.slack_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_a_thread_becomes_one_chronological_item():+ parent_ts = _ts("2026-03-01T10:00:00")+ parent = _msg(+ "2026-03-01T10:00:00",+ text="Shall we ship?",+ thread_ts=parent_ts,+ reply_count=2,+ )+ thread = [+ parent,+ _msg("2026-03-01T10:05:00", user="U2", text="Yes", thread_ts=parent_ts),+ _msg("2026-03-01T11:00:00", user="U1", text="Done", thread_ts=parent_ts),+ ]+ items = await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": [[parent]]},+ replies={("C1", parent_ts): thread},+ )+ )+ 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 == f"C1:{parent_ts}"+ assert item.thread_key == "C1"+ # The canonical archive deep link, constructed instead of paying one+ # chat.getPermalink request per item.+ assert item.permalink == "https://acme.slack.com/archives/C1/p" + parent_ts.replace(".", "")+ assert item.timestamp_utc == "2026-03-01T10:00:00Z"+ # Parent and replies as chronological "author: text" lines.+ body = item.body+ assert body.index("Alice: Shall we ship?") < body.index("Bob: Yes") < body.index("Alice: Done")+ assert item.author_raw == "Alice"+ assert item.metadata["kind"] == "thread"+ assert item.metadata["mtime_ns"] == sl._to_ns(_ts("2026-03-01T11:00:00"))+++async def test_plain_messages_group_into_one_item_per_day():+ history = [+ _msg("2026-03-01T10:00:00", text="first"),+ _msg("2026-03-01T11:00:00", user="U2", text="second"),+ _msg("2026-03-02T09:00:00", text="third"),+ ]+ items = await _collect(+ _transport(channels={"public_channel": [_channel()]}, history={"C1": [history]})+ )+ # One item per day, oldest first — deterministic order for the checkpoint.+ assert [i.external_id for i in items] == ["C1:2026-03-01", "C1:2026-03-02"]+ first = items[0]+ assert first.body.index("Alice: first") < first.body.index("Bob: second")+ assert first.timestamp_utc == "2026-03-01T10:00:00Z"+ assert first.thread_key == "C1"+ assert first.metadata["kind"] == "day"+ # The cursor rides on the key the sync runner advances.+ assert first.metadata["mtime_ns"] == sl._to_ns(_ts("2026-03-01T11:00:00"))+++async def test_unknown_user_ids_fall_back_to_the_raw_id():+ history = [+ _msg("2026-03-01T10:00:00", text="<@U1> please look"),+ _msg("2026-03-01T11:00:00", user="U9", text="on it"),+ ]+ items = await _collect(+ _transport(channels={"public_channel": [_channel()]}, history={"C1": [history]})+ )+ body = items[0].body+ # Mentions resolve through the cached users.list lookup...+ assert "Alice: @Alice please look" in body+ # ...and an id the roster does not know stays visible as itself.+ assert "U9: on it" in body+++async def test_a_type_the_token_cannot_list_degrades_instead_of_failing():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": [[_msg("2026-03-01T10:00:00")]]},+ missing_scope_types=frozenset({"private_channel", "mpim", "im"}),+ seen=seen,+ )+ )+ assert len(items) == 1 # the readable type still imported fully+ requested = {+ r.url.params.get("types")+ for r in seen+ if r.url.path == "/api/conversations.list"+ }+ # Every type the maintainer wants is at least ASKED for; scopes decide.+ assert requested == {"public_channel", "private_channel", "mpim", "im"}+++async def test_an_unreadable_conversation_is_skipped_not_fatal():+ """A bot token lists public channels it was never invited into; their+ history answers not_in_channel and must not sink the readable ones."""+ items = await _collect(+ _transport(+ channels={"public_channel": [_channel(), _channel("C2", "private-ish", 200)]},+ history={"C1": [[_msg("2026-03-01T10:00:00")]]},+ history_errors={"C2": "not_in_channel"},+ )+ )+ assert [i.metadata["channel"] for i in items] == ["C1"]+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": [[_msg("2026-03-01T10:00:00")]]},+ rate_limit_first_history=1,+ seen=seen,+ )+ )+ assert len(items) == 1+ history_calls = [r for r in seen if r.url.path == "/api/conversations.history"]+ assert len(history_calls) == 2 # the 429, then the honoured retry+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(sl.SlackAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == sl._MAX_ATTEMPTS # bounded, never an endless retry loop+++async def test_a_revoked_token_says_what_to_do_and_never_echoes_it():+ with pytest.raises(sl.SlackAdapterError) as excinfo:+ await _collect(_transport(auth={"ok": False, "error": "token_revoked"}))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "xoxb-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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(sl.SlackAdapterError, match="not connected"):+ await _collect(_transport(seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_a_numeric_checkpoint_narrows_history_by_whole_days():+ moment = datetime(2026, 3, 4, 12, 0, 0, tzinfo=UTC)+ seen: list[httpx.Request] = []+ await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": [[]]},+ seen=seen,+ ),+ checkpoint=str(int(moment.timestamp() * 1_000_000_000)),+ )+ call = next(r for r in seen if r.url.path == "/api/conversations.history")+ # Start of the PREVIOUS UTC day: a mid-day cut would rebuild a half day+ # under the full day's id; the rewound overlap upserts as unchanged.+ expected = f"{int(datetime(2026, 3, 3, tzinfo=UTC).timestamp())}.000000"+ assert call.url.params.get("oldest") == expected+++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 cursor, and mis-parsing it would silently skip history."""+ seen: list[httpx.Request] = []+ await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": [[]]},+ seen=seen,+ ),+ checkpoint="C1:2026-03-01",+ )+ call = next(r for r in seen if r.url.path == "/api/conversations.history")+ assert call.url.params.get("oldest") is None+++async def test_an_oversized_item_is_capped_with_a_marker():+ huge = _msg("2026-03-01T10:00:00", text="x" * 1_100_000)+ items = await _collect(+ _transport(channels={"public_channel": [_channel()]}, history={"C1": [[huge]]})+ )+ body = items[0].body+ assert body.endswith("[truncated — this item exceeded the 1 MB import cap]")+ assert len(body.encode("utf-8")) < 1_100_000+++async def test_join_and_leave_noise_is_not_memory():+ history = [+ _msg("2026-03-01T09:00:00", text="Alice has joined", subtype="channel_join"),+ _msg("2026-03-01T10:00:00", text="the real conversation"),+ _msg("2026-03-02T09:00:00", user="U2", text="Bob left", subtype="channel_leave"),+ ]+ items = await _collect(+ _transport(channels={"public_channel": [_channel()]}, history={"C1": [history]})+ )+ # A day holding only housekeeping produces no item at all.+ assert [i.external_id for i in items] == ["C1:2026-03-01"]+ assert "joined" not in items[0].body+++async def test_history_pages_are_walked_to_the_end():+ pages = [+ [_msg("2026-03-01T10:00:00", text="from page one")],+ [_msg("2026-03-01T11:00:00", user="U2", text="from page two")],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(+ channels={"public_channel": [_channel()]},+ history={"C1": pages},+ seen=seen,+ )+ )+ assert len(items) == 1+ assert "from page one" in items[0].body+ assert "from page two" in items[0].body+ history_calls = [r for r in seen if r.url.path == "/api/conversations.history"]+ assert len(history_calls) == 2+++async def test_a_dm_is_labelled_as_a_conversation_with_its_person():+ items = await _collect(+ _transport(+ channels={"im": [{"id": "D1", "user": "U1", "is_im": True, "created": 5}]},+ history={"D1": [[_msg("2026-03-01T10:00:00", text="just between us")]]},+ )+ )+ assert len(items) == 1+ assert "DM with @Alice" in items[0].body+ assert items[0].thread_key == "D1"+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(sl.INTEGRATION_ID)+ assert spec is not None and spec.id == "slack"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(sl.INTEGRATION_ID, sl.slack_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:slack") is True+ finally:+ plugin_bridge.unregister_pull_adapter(sl.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_telegram.py b/tests/unit/ultrawiki/adapters/test_telegram.pynew file mode 100644index 0000000000..9457c0517a--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_telegram.py@@ -0,0 +1,344 @@+"""The Telegram pull adapter, driven fully offline through MockTransport.++What these tests pin: forward capture of the update queue in ascending+update-id order, drain-through pagination, the runner's numeric cursor+becoming ``offset=cursor+1``, honest degradation of a non-numeric backfill+checkpoint to "whatever Telegram still holds", media as named placeholders+that are never downloaded, bounded 429 handling, the single-reader 409+surfaced plainly, and failure messages that never echo the bot credential+even though the Bot API embeds it in every URL.++The mock reproduces the Bot API's real ``getUpdates`` semantics — offset+filtering over ascending update ids, at most ``limit`` per page — so the+adapter's ordering and drain guarantees are earned, not assumed.+"""++from __future__ import annotations++from typing import Any++import httpx+import pytest++from jarvis.ultrawiki.adapters import telegram as tg+from jarvis.ultrawiki.types import ConnectorContext++_BOT_CREDENTIAL = "7000000001:AAE-telegram-bot-credential-value"++_PRIVATE = {"id": 4242, "type": "private", "first_name": "Ruth"}+_SUPERGROUP = {"id": -100123456789, "type": "supergroup", "title": "Acme HQ"}++#: 2026-02-25T06:13:20Z — pinned as a literal so the ISO mapping is tested,+#: not merely round-tripped through the adapter's own helper.+_DATE = 1_772_000_000+_DATE_ISO = "2026-02-25T06:13:20Z"++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Telegram plugin, without touching the host's keyring."""++ class _Tokens:+ access = _BOT_CREDENTIAL+ 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-telegram",+ config={"integration_id": "plugin:telegram"},+ secret_get=lambda _name: None,+ )+++def _update(+ update_id: int,+ text: str = "",+ *,+ chat: dict[str, Any] | None = None,+ date: int = _DATE,+ key: str = "message",+ message_id: int | None = None,+ sender: dict[str, Any] | None = None,+ extra: dict[str, Any] | None = None,+) -> dict[str, Any]:+ message: dict[str, Any] = {+ "message_id": message_id if message_id is not None else update_id,+ "chat": dict(chat if chat is not None else _PRIVATE),+ "date": date,+ }+ if sender is not None:+ message["from"] = sender+ elif key in ("message", "edited_message"):+ message["from"] = {"first_name": "Ruth", "username": "ruth"}+ if text:+ message["text"] = text+ if extra:+ message.update(extra)+ return {"update_id": update_id, key: message}+++def _transport(+ updates: list[dict[str, Any]],+ *,+ seen: list[httpx.Request] | None = None,+ ratelimit_first: int = 0,+) -> httpx.MockTransport:+ """A faithful little Bot API: offset windows over ascending update ids."""+ remaining_429 = {"n": ratelimit_first}+ ordered = sorted(updates, key=lambda u: int(u["update_id"]))++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ method = request.url.path.rsplit("/", 1)[-1]+ if method == "getMe":+ return httpx.Response(+ 200, json={"ok": True, "result": {"id": 1, "is_bot": True}}+ )+ if method == "getUpdates":+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(+ 429,+ headers={"Retry-After": "0"},+ json={"ok": False, "parameters": {"retry_after": 0}},+ )+ params = request.url.params+ offset = int(params.get("offset", "0") or 0)+ limit = int(params.get("limit", "100"))+ window = [u for u in ordered if int(u["update_id"]) >= offset][:limit]+ return httpx.Response(200, json={"ok": True, "result": window})+ return httpx.Response(404, json={"ok": False, "description": "Not Found"})++ return httpx.MockTransport(handler)+++async def _collect(checkpoint: str | None = None, **kwargs: Any) -> list:+ return [+ item+ async for item in tg.telegram_pull_adapter(_ctx(), checkpoint, **kwargs)+ ]+++async def test_updates_become_items_oldest_to_newest():+ items = await _collect(+ transport=_transport(+ [+ _update(9, "third"),+ _update(7, "first"),+ _update(8, "second"),+ ]+ )+ )+ assert [i.external_id for i in items] == ["msg:4242:7", "msg:4242:8", "msg:4242:9"]+ first = items[0]+ assert first.title == "Ruth in Ruth"+ assert first.body == "Ruth · Ruth\n\nfirst"+ # A private chat has no web URL; the app link is the honest deepest link.+ assert first.permalink == "tg://openmessage?user_id=4242&message_id=7"+ assert first.timestamp_utc == _DATE_ISO+ assert first.thread_key == "chat:4242"+ assert first.author_raw == "Ruth"+++async def test_the_queue_is_drained_through_every_page():+ updates = [_update(i, f"msg {i}") for i in range(1, 151)]+ seen: list[httpx.Request] = []+ items = await _collect(transport=_transport(updates, seen=seen))+ assert len(items) == 150+ assert items[0].external_id == "msg:4242:1"+ assert items[-1].external_id == "msg:4242:150"+ pages = [r for r in seen if r.url.path.endswith("/getUpdates")]+ assert len(pages) == 2 # 100 + 50+ assert pages[1].url.params.get("offset") == "101"+++async def test_the_cursor_rides_on_the_key_the_sync_runner_advances():+ items = await _collect(transport=_transport([_update(41, "hi")]))+ assert items[0].metadata["max_rowid"] == 41+++async def test_a_numeric_checkpoint_continues_strictly_after_it():+ updates = [_update(5, "old"), _update(6, "newer"), _update(7, "newest")]+ seen: list[httpx.Request] = []+ items = await _collect(checkpoint="5", transport=_transport(updates, seen=seen))+ first_page = next(r for r in seen if r.url.path.endswith("/getUpdates"))+ assert first_page.url.params.get("offset") == "6"+ assert [i.external_id for i in items] == ["msg:4242:6", "msg:4242:7"]+++async def test_a_backfill_checkpoint_degrades_to_the_unconfirmed_remainder():+ """A resume external_id is not a position in a replayable stream — the+ stream is gone. The adapter reads whatever Telegram still holds, which IS+ the un-imported remainder; upserts absorb any overlap."""+ seen: list[httpx.Request] = []+ items = await _collect(+ checkpoint="msg:4242:7",+ transport=_transport([_update(12, "still queued")], seen=seen),+ )+ first_page = next(r for r in seen if r.url.path.endswith("/getUpdates"))+ assert "offset" not in first_page.url.params+ assert [i.external_id for i in items] == ["msg:4242:12"]+++async def test_group_and_channel_posts_carry_real_permalinks():+ channel = {+ "id": -1009876543210,+ "type": "channel",+ "title": "Announcements",+ "username": "acme_announce",+ }+ items = await _collect(+ transport=_transport(+ [+ _update(20, "release is out", key="channel_post", chat=channel),+ _update(21, "group talk", chat=_SUPERGROUP),+ ]+ )+ )+ by_id = {i.external_id: i for i in items}+ public = by_id["msg:-1009876543210:20"]+ assert public.permalink == "https://t.me/acme_announce/20"+ assert public.author_raw == "Announcements" # channel posts carry no sender+ private_group = by_id["msg:-100123456789:21"]+ assert private_group.permalink == "https://t.me/c/123456789/21"+ assert "Acme HQ" in private_group.body+++async def test_media_is_named_never_downloaded():+ seen: list[httpx.Request] = []+ items = await _collect(+ transport=_transport(+ [+ _update(+ 30,+ extra={+ "photo": [{"file_id": "p1"}],+ "caption": "the whiteboard",+ },+ ),+ _update(+ 31,+ extra={"document": {"file_id": "d1", "file_name": "report.pdf"}},+ ),+ ],+ seen=seen,+ )+ )+ assert "the whiteboard [photo]" in items[0].body+ assert "[file: report.pdf]" in items[1].body+ # Only Bot-API method calls — never a file download endpoint.+ assert all("/file/" not in r.url.path for r in seen)+++async def test_an_edit_re_yields_the_same_external_id():+ items = await _collect(+ transport=_transport(+ [+ _update(40, "first wording", message_id=7),+ _update(41, "final wording", message_id=7, key="edited_message"),+ ]+ )+ )+ assert [i.external_id for i in items] == ["msg:4242:7", "msg:4242:7"]+ assert items[0].metadata["edited"] is False+ assert items[1].metadata["edited"] is True+ assert "final wording" in items[1].body+++async def test_service_updates_yield_nothing():+ items = await _collect(+ transport=_transport(+ [+ _update(50, extra={"sticker": {"file_id": "s1"}}),+ _update(51, extra={"new_chat_members": [{"id": 2}]}),+ {"update_id": 52, "callback_query": {"id": "cq", "data": "x"}},+ ]+ )+ )+ assert items == []+++async def test_a_429_is_retried_within_bounds_and_then_succeeds():+ seen: list[httpx.Request] = []+ items = await _collect(+ transport=_transport([_update(60, "hi")], seen=seen, ratelimit_first=1)+ )+ assert len(items) == 1+ pages = [r for r in seen if r.url.path.endswith("/getUpdates")]+ assert len(pages) == 2 # the 429 plus the successful retry+++async def test_the_single_reader_conflict_is_surfaced_plainly():+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/getMe"):+ return httpx.Response(+ 200, json={"ok": True, "result": {"id": 1, "is_bot": True}}+ )+ return httpx.Response(+ 409,+ json={+ "ok": False,+ "description": "Conflict: terminated by other getUpdates request",+ },+ )++ with pytest.raises(tg.TelegramAdapterError, match="one reader"):+ await _collect(transport=httpx.MockTransport(handler))+++async def test_a_rejected_credential_says_what_to_do_and_never_echoes_it():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"ok": False, "description": "Unauthorized"})++ with pytest.raises(tg.TelegramAdapterError) as excinfo:+ await _collect(transport=httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert _BOT_CREDENTIAL 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(tg.TelegramAdapterError, match="not connected"):+ await _collect(transport=_transport([]))+++async def test_an_oversized_message_is_truncated_with_a_marker(monkeypatch):+ monkeypatch.setattr(tg, "_MAX_BODY_CHARS", 60)+ items = await _collect(transport=_transport([_update(70, "x" * 500)]))+ assert len(items) == 1+ assert items[0].body.endswith(tg._TRUNCATION_MARKER)+ assert len(items[0].body) == 60 + len(tg._TRUNCATION_MARKER)+++def test_the_integration_id_matches_the_curated_roster():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ # The id must resolve to the roster's Telegram card, or the reader serves+ # a name nothing offers.+ spec = connector_catalog.bridge_entry_for(tg.INTEGRATION_ID)+ assert spec is not None+ assert spec.id == "telegram"++ plugin_bridge.register_pull_adapter(tg.INTEGRATION_ID, tg.telegram_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:telegram") is True+ finally:+ plugin_bridge.unregister_pull_adapter(tg.INTEGRATION_ID)diff --git a/tests/unit/ultrawiki/adapters/test_todoist.py b/tests/unit/ultrawiki/adapters/test_todoist.pynew file mode 100644index 0000000000..57b8082578--- /dev/null+++ b/tests/unit/ultrawiki/adapters/test_todoist.py@@ -0,0 +1,365 @@+"""The Todoist pull adapter, driven fully offline through MockTransport.++What makes this reader trustworthy rather than merely functional: stable+per-task ids (a re-run must upsert, not duplicate), a canonical deep link on+every item, the completed history folded in next to the active snapshot,+comments rendered chronologically, sync-token incrementals that degrade to a+full read when the token goes stale, bounded 429 handling, and failure+messages a user can act on that never carry the token.+"""++from __future__ import annotations++import json+from typing import Any+from urllib.parse import parse_qs++import httpx+import pytest++from jarvis.ultrawiki.adapters import todoist as td+from jarvis.ultrawiki.types import ConnectorContext++[email protected](autouse=True)+def marketplace_token(monkeypatch):+ """A connected Todoist plugin, without touching the host's keyring."""++ class _Tokens:+ access = "todoist-test-token"+ 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-todoist",+ config={"integration_id": "plugin:todoist"},+ secret_get=lambda _name: None,+ )+++def _task(task_id: str = "t1", **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "id": task_id,+ "content": "Ship the wake-word fix",+ "description": "The wake word misses every third call.",+ "project_id": "p1",+ "added_at": "2026-03-01T10:00:00.000000Z",+ "checked": False,+ "is_deleted": False,+ "due": {"date": "2026-04-01"},+ "responsible_uid": "u2",+ }+ base.update(overrides)+ return base+++def _note(item_id: str, posted_at: str, content: str, **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "id": f"n-{item_id}-{posted_at}",+ "item_id": item_id,+ "posted_at": posted_at,+ "content": content,+ "is_deleted": False,+ }+ base.update(overrides)+ return base+++_PROJECTS = [{"id": "p1", "name": "Widgets"}]+_PEOPLE = [{"id": "u2", "full_name": "Alice"}]+++def _payload(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "projects": _PROJECTS,+ "collaborators": _PEOPLE,+ "items": [],+ "notes": [],+ "sync_token": "fresh-token",+ }+ base.update(overrides)+ return base+++def _json(payload: dict[str, Any]) -> httpx.Response:+ return httpx.Response(+ 200,+ content=json.dumps(payload).encode(),+ headers={"content-type": "application/json"},+ )+++def _sync_token_of(request: httpx.Request) -> str:+ form = parse_qs(request.content.decode())+ return form.get("sync_token", [""])[0]+++def _transport(+ *,+ full: dict[str, Any] | None = None,+ delta: dict[str, Any] | None = None,+ completed_pages: list[list[dict[str, Any]]] | None = None,+ stale_tokens: bool = False,+ rate_limit_first: int = 0,+ seen: list[httpx.Request] | None = None,+) -> httpx.MockTransport:+ """A fake Todoist account: the sync endpoint plus the completed archive."""+ remaining_429 = {"n": rate_limit_first}++ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ if remaining_429["n"] > 0:+ remaining_429["n"] -= 1+ return httpx.Response(429, headers={"Retry-After": "0"})+ path = request.url.path+ if path == "/sync/v9/sync":+ cursor = _sync_token_of(request)+ if cursor == "*":+ return _json(full or _payload())+ if stale_tokens:+ return httpx.Response(400, content=b'{"error":"invalid sync_token"}')+ return _json(delta or _payload())+ if path == "/sync/v9/completed/get_all":+ pages = completed_pages or [[]]+ offset = int(request.url.params.get("offset") or 0)+ index = offset // td._COMPLETED_PAGE+ rows = pages[index] if index < len(pages) else []+ return _json({"items": rows})+ return httpx.Response(404, content=b"{}")++ return httpx.MockTransport(handler)+++async def _collect(+ transport: httpx.MockTransport, checkpoint: str | None = None+) -> list:+ return [+ item+ async for item in td.todoist_pull_adapter(_ctx(), checkpoint, transport=transport)+ ]+++async def test_a_task_becomes_a_linkable_dated_item():+ notes = [+ _note("t1", "2026-03-02T09:00:00.000000Z", "On it"),+ _note("t1", "2026-03-01T11:00:00.000000Z", "Can you take this?"),+ _note("t1", "2026-03-03T09:00:00.000000Z", "gone", is_deleted=True),+ ]+ items = await _collect(_transport(full=_payload(items=[_task()], notes=notes)))+ 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 == "task:t1"+ # The Sync API carries no web URL; this is the canonical task address.+ assert item.permalink == "https://app.todoist.com/app/task/t1"+ # WHEN IT HAPPENED, not when it was last touched.+ assert item.timestamp_utc == "2026-03-01T10:00:00.000000Z"+ assert item.title == "Ship the wake-word fix"+ assert item.thread_key == "p1"+ assert item.author_raw == "Alice"+ # The composed header keeps the context a bare description would lose.+ assert "Widgets · task · open · assigned to Alice · due 2026-04-01" in item.body+ assert "The wake word misses every third call." in item.body+ # Comments fold in chronologically; a deleted note is not memory.+ assert item.body.index("Can you take this?") < item.body.index("On it")+ assert "gone" not in item.body+ # No true modified time exists; the newest honest signal drives the cursor.+ assert item.metadata["mtime_ns"] == td._to_ns("2026-03-02T09:00:00.000000Z")+ assert item.metadata["comments"] == 2+++async def test_the_completed_history_arrives_next_to_the_snapshot():+ completed_row = {+ "task_id": "t9",+ "content": "Old chore",+ "project_id": "p1",+ "completed_at": "2026-02-01T08:00:00.000000Z",+ "item_object": _task(+ "t9",+ content="Old chore",+ added_at="2026-01-01T10:00:00.000000Z",+ checked=True,+ due=None,+ responsible_uid=None,+ ),+ "notes": [_note("t9", "2026-01-02T10:00:00.000000Z", "done and dusted")],+ }+ items = await _collect(+ _transport(full=_payload(items=[_task()]), completed_pages=[[completed_row]])+ )+ by_id = {item.external_id: item for item in items}+ assert set(by_id) == {"task:t1", "task:t9"}+ done = by_id["task:t9"]+ assert done.metadata["state"] == "completed"+ assert done.metadata["completed_at"] == "2026-02-01T08:00:00.000000Z"+ assert "done and dusted" in done.body+++async def test_deleted_tasks_are_skipped_not_imported():+ items = await _collect(+ _transport(full=_payload(items=[_task(is_deleted=True), _task("t2")]))+ )+ assert [item.external_id for item in items] == ["task:t2"]+++async def test_a_sync_token_checkpoint_asks_for_the_delta_only():+ seen: list[httpx.Request] = []+ delta = _payload(items=[_task("t7", checked=True)])+ items = await _collect(+ _transport(delta=delta, seen=seen), checkpoint="opaque-sync-token"+ )+ assert [item.external_id for item in items] == ["task:t7"]+ assert items[0].metadata["state"] == "completed"+ sync_calls = [r for r in seen if r.url.path == "/sync/v9/sync"]+ assert [_sync_token_of(r) for r in sync_calls] == ["opaque-sync-token"]+ # A delta already carries completed transitions; the archive walk would+ # only re-spend the budget.+ assert not any(r.url.path.endswith("/completed/get_all") for r in seen)+++async def test_a_stale_sync_token_degrades_to_a_full_read():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(full=_payload(items=[_task()]), stale_tokens=True, seen=seen),+ checkpoint="stale-sync-token",+ )+ assert [item.external_id for item in items] == ["task:t1"]+ sync_calls = [r for r in seen if r.url.path == "/sync/v9/sync"]+ # The rejected token, then the honest fresh start.+ assert [_sync_token_of(r) for r in sync_calls] == ["stale-sync-token", "*"]+++async def test_a_numeric_checkpoint_still_yields_the_full_snapshot():+ """The Sync API gives active tasks no modified time, so a nanosecond+ cursor cannot narrow the read — pretending it could would skip changes."""+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(full=_payload(items=[_task()]), seen=seen),+ checkpoint=str(td._to_ns("2026-03-04T12:00:00Z")),+ )+ assert len(items) == 1+ sync_calls = [r for r in seen if r.url.path == "/sync/v9/sync"]+ assert [_sync_token_of(r) for r in sync_calls] == ["*"]+++async def test_a_backfill_checkpoint_resumes_strictly_after_it():+ first = _task("t1", added_at="2026-03-01T10:00:00.000000Z")+ second = _task("t2", added_at="2026-03-02T10:00:00.000000Z")+ items = await _collect(+ _transport(full=_payload(items=[first, second])), checkpoint="task:t1"+ )+ assert [item.external_id for item in items] == ["task:t2"]+++async def test_items_stream_oldest_to_newest_deterministically():+ newer = _task("t9", added_at="2026-03-05T10:00:00.000000Z")+ older = _task("t2", added_at="2026-02-01T10:00:00.000000Z")+ items = await _collect(_transport(full=_payload(items=[newer, older])))+ assert [item.external_id for item in items] == ["task:t2", "task:t9"]+++async def test_completed_pages_are_walked_to_the_end():+ def _row(task_id: str) -> dict[str, Any]:+ return {+ "task_id": task_id,+ "content": f"chore {task_id}",+ "project_id": "p1",+ "completed_at": "2026-02-01T08:00:00.000000Z",+ "item_object": _task(task_id, content=f"chore {task_id}", checked=True, due=None),+ }++ pages = [+ [_row(f"c{i}") for i in range(td._COMPLETED_PAGE)],+ [_row("last")],+ ]+ seen: list[httpx.Request] = []+ items = await _collect(_transport(completed_pages=pages, seen=seen))+ assert len(items) == td._COMPLETED_PAGE + 1+ walk = [r for r in seen if r.url.path.endswith("/completed/get_all")]+ assert len(walk) == 2 # stopped after the short second page+++async def test_rate_limited_requests_wait_and_retry():+ seen: list[httpx.Request] = []+ items = await _collect(+ _transport(full=_payload(items=[_task()]), rate_limit_first=1, seen=seen)+ )+ assert len(items) == 1+ assert seen[0].url.path == seen[1].url.path == "/sync/v9/sync"+++async def test_a_persistent_rate_limit_raises_an_honest_bounded_error():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(429, headers={"Retry-After": "0"})++ with pytest.raises(td.TodoistAdapterError, match="rate limit"):+ await _collect(httpx.MockTransport(handler))+ assert len(seen) == td._MAX_ATTEMPTS # bounded, never an endless retry loop+++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'{"error":"Unauthorized"}')++ with pytest.raises(td.TodoistAdapterError) as excinfo:+ await _collect(httpx.MockTransport(handler))+ message = str(excinfo.value)+ assert "Reconnect" in message+ assert "todoist-test-token" 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()+ )+ seen: list[httpx.Request] = []+ with pytest.raises(td.TodoistAdapterError, match="not connected"):+ await _collect(_transport(seen=seen))+ assert seen == [] # refused before a single request left the machine+++async def test_an_oversized_item_is_capped_with_a_marker():+ huge = _task(description="x" * 1_100_000)+ items = await _collect(_transport(full=_payload(items=[huge])))+ body = items[0].body+ assert body.endswith("[truncated — the full text lives at the link above]")+ assert len(body) < 1_100_000+++async def test_a_task_without_a_title_is_skipped_not_faked():+ items = await _collect(+ _transport(full=_payload(items=[_task(content=""), _task("t5")]))+ )+ assert [item.external_id for item in items] == ["task:t5"]+++def test_the_integration_id_matches_the_catalog_and_the_bridge():+ from jarvis.ultrawiki import connector_catalog+ from jarvis.ultrawiki.connectors import plugin_bridge++ spec = connector_catalog.bridge_entry_for(td.INTEGRATION_ID)+ assert spec is not None and spec.id == "todoist"+ # The id must match what list_candidates reports, or the reader is+ # registered under a name nothing looks up.+ plugin_bridge.register_pull_adapter(td.INTEGRATION_ID, td.todoist_pull_adapter)+ try:+ assert plugin_bridge.has_pull_adapter("plugin:todoist") is True+ finally:+ plugin_bridge.unregister_pull_adapter(td.INTEGRATION_ID)