Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-14 18:22)

Ruben Lütkee9f91edbc4fa
diff --git a/docs/marketplace/google-oauth-setup.md b/docs/marketplace/google-oauth-setup.md
index ae623c5821..2c23667a97 100644
--- a/docs/marketplace/google-oauth-setup.md
+++ b/docs/marketplace/google-oauth-setup.md
@@ -83,36 +83,33 @@ client, do that in the same dialog first (above), then reconnect.
### Keeping it connected (the 7-day rule)
-Google issues a refresh token that **expires after 7 days** while your app's
-publishing status is **Testing** and a sensitive/restricted scope is requested.
-To keep a plugin connected permanently you must **publish the app to "In
-production"** (Audience → Publish app). Even an *unverified* production app keeps
-the refresh token alive for the app owner / test users — you just click through a
-one-time "Google hasn't verified this app" notice when connecting:
-
-- For **`drive.file`** (Drive): non-sensitive — publishing needs no verification,
- so Drive is permanent immediately after you publish (or even in testing it is
- unaffected by the 7-day rule because `drive.file` is non-sensitive… still,
- publish to be safe).
-- For **`calendar`** (Calendar, full read/write across all calendars):
- **sensitive but not restricted** — same light path as Gmail send: publishing to
- production needs OAuth verification for *public* use but **no CASA assessment**.
- For your own account just publish to production (unverified is fine) and the
- connection stops expiring; voice commands like "what's on my calendar today" and
- "schedule a meeting tomorrow at 3pm" then work indefinitely. (The narrower
- `calendar.events` scope also works for create/read/delete but **cannot list your
- other calendars**, so events on a secondary calendar would be invisible — use
- the full `calendar` scope.)
-- For **Gmail read** (`gmail.readonly`, restricted): publishing to production
- requires Google's OAuth app **verification + a CASA security assessment**
- (several weeks). Until that completes, Gmail works but reconnects ~weekly.
-- For **Gmail send only** (`gmail.send`, sensitive but not restricted): a far
- lighter path — production needs OAuth verification but **no** CASA assessment.
-
-For just Calendar + Drive + Gmail-send, the quick path is: publish the app to
-production and connect — no verification needed for your own use. The heavy
-verification + CASA path is only required for the restricted Gmail read scope, or
-for distributing the app publicly.
+Google authorizations issued while an external app's publishing status is
+**Testing** expire seven days after consent whenever the request includes any
+scope beyond basic identity (`openid`, email, and profile). That includes
+`drive.file`, `calendar`, and the Gmail scopes. Jarvis cannot extend that
+provider-enforced lifetime.
+
+For durable offline refresh, open **Google Auth Platform → Audience** and choose
+**Publish app** so the project is **In production**. A Google Workspace project
+used only inside its organization can instead use an **Internal** audience. Then
+reconnect each Google plugin once so Google issues a grant under the new audience
+configuration.
+
+- **Drive `drive.file`** is non-sensitive, but it is still outside the basic
+ identity-only exception to Testing's seven-day lifetime.
+- **Calendar `calendar`** and **Gmail `gmail.send`** are sensitive scopes.
+- **Gmail `gmail.readonly`** is restricted. Public distribution can require
+ Google's restricted-scope verification, and systems that transmit or store
+ restricted data through a third-party server can require a security assessment.
+ Personal use by a small number of known users may qualify for Google's
+ verification exception, subject to an unverified-app warning and user cap.
+
+Production status removes the scheduled seven-day Testing expiry; it does not
+make a grant irrevocable. Google can still require authorization again after a
+user revokes access, an account or administrator changes policy, credentials are
+rotated, or another provider security condition invalidates the refresh token.
+Jarvis handles ordinary access-token expiry automatically and only asks for
+reconnection when the refresh grant itself is no longer usable.
---
diff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.json
index fdf8130190..8022923d79 100644
--- a/jarvis/marketplace/seed_catalog.json
+++ b/jarvis/marketplace/seed_catalog.json
@@ -279,7 +279,7 @@
"url": "https://drivemcp.googleapis.com/mcp/v1",
"auth_header_template": "Authorization: Bearer ${plugin_google_drive_access_token}"
},
- "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md. Uses the non-sensitive drive.file scope (no Google verification, stays connected permanently). The Drive MCP server is Google's official endpoint (Developer Preview)."
+ "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md. Uses the non-sensitive drive.file scope. Publish the Google consent app to 'In production' so offline access can refresh normally; a 'Testing' grant expires after 7 days. The Drive MCP server is Google's official endpoint (Developer Preview)."
},
{
"id": "gmail",
@@ -306,7 +306,7 @@
"offline_access": true
},
"native_tool": "gmail",
- "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md (shares the Google client with Drive). In Google 'Testing' status the connection expires every 7 days; publish the app + complete Google's restricted-scope verification to make it permanent."
+ "post_install_hint_md": "Setup: see docs/marketplace/google-oauth-setup.md (shares the Google client with Drive). In Google 'Testing' status the refresh grant expires after 7 days. Publish the consent app to 'In production' and complete restricted-scope verification when Google requires it so Jarvis can refresh offline access automatically. A user, account, or administrator can still revoke the grant."
},
{
"id": "google_calendar",
@@ -332,7 +332,7 @@
"offline_access": true
},
"native_tool": "google_calendar",
- "post_install_hint_md": "Setup: shares the Google OAuth client with Gmail/Drive. Add the full 'calendar' scope to the OAuth consent screen (it reads events across ALL your calendars, not just the primary one) and publish the app to 'In production' so the refresh token (and thus the connection) never expires — a 'Testing' app drops it after 7 days."
+ "post_install_hint_md": "Setup: shares the Google OAuth client with Gmail/Drive. Add the full 'calendar' scope to the OAuth consent screen (it reads events across ALL your calendars, not just the primary one). A 'Testing' refresh grant expires after 7 days; publish the consent app to 'In production' so Jarvis can refresh offline access automatically. A user, account, or administrator can still revoke the grant."
}
]
}
diff --git a/jarvis/marketplace/token_store.py b/jarvis/marketplace/token_store.py
index 6af9a76a82..68d9c85105 100644
--- a/jarvis/marketplace/token_store.py
+++ b/jarvis/marketplace/token_store.py
@@ -103,13 +103,17 @@ class KeyringBackend:
def delete(self, key: str) -> None:
from jarvis.core.config import delete_secret
- # Deliberately does not raise on a failed delete (unlike `set`): both
- # `ChunkedBackend._clear_overflow` and `ChunkedBackend.set`'s
- # rollback/leftover-cleanup call this as best-effort housekeeping and
- # rely on it never raising, so a cleanup failure here can't mask a
- # more important error or turn a successful token save into a
- # reported failure. The return value is intentionally not checked;
- # see jarvis/core/config.py:delete_secret for the honest result.
+ # Explicit disconnect is fail-closed. ``get_secret`` may degrade a
+ # locked platform keyring to an empty file fallback, so a later read is
+ # not proof that the OS credential was removed. ``delete_secret`` is
+ # the authoritative cross-backend verification result.
+ if not delete_secret(key):
+ raise RuntimeError(f"keyring delete could not be verified for {key!r}")
+
+ def delete_best_effort(self, key: str) -> None:
+ """Delete housekeeping data without masking an already-successful save."""
+ from jarvis.core.config import delete_secret
+
delete_secret(key)
@@ -153,6 +157,14 @@ class ChunkedBackend:
self._backend = backend
self._chunk_size = chunk_size
+ def _delete_entry(self, key: str, *, strict: bool) -> None:
+ if not strict:
+ best_effort = getattr(self._backend, "delete_best_effort", None)
+ if callable(best_effort):
+ best_effort(key)
+ return
+ self._backend.delete(key)
+
@staticmethod
def _overflow_key(key: str, index: int) -> str:
return f"{key}__{index}"
@@ -195,26 +207,26 @@ class ChunkedBackend:
def _clear_cleanup_extent_best_effort(self, key: str) -> None:
try:
- self._backend.delete(self._cleanup_extent_key(key))
+ self._delete_entry(self._cleanup_extent_key(key), strict=False)
except Exception: # noqa: BLE001 - save already succeeded
return
def _clear_cleanup_extent_verified(self, key: str) -> None:
extent_key = self._cleanup_extent_key(key)
- self._backend.delete(extent_key)
+ self._delete_entry(extent_key, strict=True)
if self._backend.get(extent_key) is not None:
raise RuntimeError(f"could not delete cleanup extent for {key!r}")
def _clear_overflow(self, key: str, *, start_index: int = 0) -> bool:
"""Best-effort delete contiguous ``<key>__i`` overflow pieces.
- ``KeyringBackend.delete`` deliberately cannot raise when its lower-level
- delete fails because this helper also runs after a successful save. A
- backend can therefore leave a chunk readable after ``delete``. Stop at
- that first retained chunk instead of probing an unbounded sequence of
- generated keys, and report whether every discovered chunk was removed.
- Save-time cleanup may ignore this result. Explicit deletion uses the
- persisted cleanup extent below so gaps cannot hide later chunks.
+ This helper runs after a successful save, so it explicitly selects a
+ backend's best-effort deletion path instead of strict disconnect
+ semantics. A backend may therefore leave a chunk readable after the
+ attempt. Stop at that first retained chunk instead of probing an
+ unbounded sequence of generated keys, and report whether every
+ discovered chunk was removed. Explicit deletion uses the persisted
+ cleanup extent below so gaps cannot hide later chunks.
"""
i = start_index
while True:
@@ -230,7 +242,7 @@ class ChunkedBackend:
except Exception: # noqa: BLE001 - keep save-time cleanup best-effort
return False
try:
- self._backend.delete(chunk_key)
+ self._delete_entry(chunk_key, strict=False)
retained = self._backend.get(chunk_key)
except Exception: # noqa: BLE001 - keep save-time cleanup best-effort
return False
@@ -238,7 +250,14 @@ class ChunkedBackend:
return False
i += 1
- def _clear_indexed_overflow(self, key: str, count: int, *, start_index: int = 0) -> bool:
+ def _clear_indexed_overflow(
+ self,
+ key: str,
+ count: int,
+ *,
+ start_index: int = 0,
+ strict: bool = False,
+ ) -> bool:
"""Attempt and verify every chunk named by a manifest or extent."""
cleared = True
for i in range(start_index, count):
@@ -251,7 +270,7 @@ class ChunkedBackend:
if piece is None:
continue
try:
- self._backend.delete(chunk_key)
+ self._delete_entry(chunk_key, strict=strict)
except Exception: # noqa: BLE001 - finish the bounded cleanup pass
cleared = False
continue
@@ -289,7 +308,7 @@ class ChunkedBackend:
cleared = False
continue
try:
- self._backend.delete(chunk_key)
+ self._delete_entry(chunk_key, strict=True)
retained = self._backend.get(chunk_key)
except Exception: # noqa: BLE001 - finish the bounded cleanup pass
cleared = False
@@ -370,7 +389,7 @@ class ChunkedBackend:
for i in range(written):
old_piece = prior[i]
if old_piece is None:
- self._backend.delete(self._overflow_key(key, i))
+ self._delete_entry(self._overflow_key(key, i), strict=False)
else:
self._backend.set(self._overflow_key(key, i), old_piece)
raise
@@ -388,14 +407,17 @@ class ChunkedBackend:
# delete may already have left gaps, so an active chunked value must use
# its exact persisted count rather than stop at the first missing index.
head = self._backend.get(key)
- cleanup_extent = self._cleanup_extent(key)
+ persisted_cleanup_extent = self._cleanup_extent(key)
+ active_count = 0
if head is not None and head.startswith(_CHUNK_SENTINEL):
active_count = self._manifest_count(key, head)
- cleanup_extent = max(active_count, cleanup_extent)
- if cleanup_extent:
- overflow_cleared = self._clear_indexed_overflow(key, cleanup_extent)
+ if persisted_cleanup_extent:
+ cleanup_extent = max(active_count, persisted_cleanup_extent)
+ overflow_cleared = self._clear_indexed_overflow(key, cleanup_extent, strict=True)
else:
- # Expensive only for an explicit disconnect of a pre-sidecar value.
+ # A pre-sidecar header records only its active prefix; an older
+ # failed shrink may have left sparse chunks beyond that count.
+ # Expensive only for explicit disconnect of this legacy shape.
overflow_cleared = self._clear_sparse_legacy_overflow(key)
if not overflow_cleared:
raise RuntimeError(f"could not delete every overflow chunk for {key!r}")
@@ -403,7 +425,7 @@ class ChunkedBackend:
# chunks beyond a newer header. Remove it only after every named chunk
# is verified absent, then remove the primary value/header.
self._clear_cleanup_extent_verified(key)
- self._backend.delete(key)
+ self._delete_entry(key, strict=True)
class InMemoryBackend:
diff --git a/tests/unit/core/test_keyring_backend_recovery.py b/tests/unit/core/test_keyring_backend_recovery.py
index e9bc5bac30..50acb1323c 100644
--- a/tests/unit/core/test_keyring_backend_recovery.py
+++ b/tests/unit/core/test_keyring_backend_recovery.py
@@ -12,6 +12,7 @@ import keyring.backend
import pytest
import jarvis.core.config as cfg
+from jarvis.marketplace.token_store import Tokens, TokenStore
class _MemoryBackend(keyring.backend.KeyringBackend):
@@ -45,6 +46,22 @@ class _NoDeleteBackend(_MemoryBackend):
return None
+class _LockableBackend(_MemoryBackend):
+ """Platform store that becomes unreadable after a credential was saved."""
+
+ locked = False
+
+ def get_password(self, service: str, username: str) -> str | None:
+ if self.locked:
+ raise RuntimeError("platform credential store is locked")
+ return super().get_password(service, username)
+
+ def delete_password(self, service: str, username: str) -> None:
+ if self.locked:
+ raise RuntimeError("platform credential store is locked")
+ super().delete_password(service, username)
+
+
@pytest.fixture
def _restore_keyring_backend():
original = keyring.get_keyring()
@@ -326,3 +343,37 @@ def test_failed_retained_platform_delete_preserves_newer_file_copy(
assert cfg.delete_secret("google_client_secret") is False
assert cfg._FileCredStore().get(cfg.KEYRING_SERVICE, "google_client_secret") == "new-file-value"
assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-file-value"
+
+
+def test_marketplace_disconnect_fails_closed_when_platform_token_becomes_locked(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+ _restore_keyring_backend,
+) -> None:
+ platform_backend = _LockableBackend()
+ credential_slot = "plugin_gmail_tokens"
+ raw_token = Tokens(access="platform-access" * 20).to_json()
+ chunks = [raw_token[i * len(raw_token) // 6 : (i + 1) * len(raw_token) // 6] for i in range(6)]
+ platform_backend.set_password(cfg.KEYRING_SERVICE, credential_slot, "\x00JCHUNKS\x006")
+ for index, chunk in enumerate(chunks):
+ platform_backend.set_password(cfg.KEYRING_SERVICE, f"{credential_slot}__{index}", chunk)
+ retained_entries = dict(platform_backend.values)
+ assert len(retained_entries) == 7
+ keyring.set_keyring(platform_backend)
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)
+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)
+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)
+ monkeypatch.delenv("PLUGIN_GMAIL_TOKENS", raising=False)
+ platform_backend.locked = True
+
+ with pytest.raises(RuntimeError, match="token deletion could not be verified"):
+ TokenStore().delete("gmail")
+
+ # The read path has degraded to an empty file fallback, but that absence is
+ # not accepted as deletion proof while all seven OS entries are locked.
+ assert cfg.get_secret(credential_slot, env_fallback=None) is None
+ assert platform_backend.values == retained_entries
+ assert cfg._FILE_BACKEND_ACTIVE is True
+ assert cfg._PLATFORM_KEYRING_BACKEND is platform_backend
diff --git a/tests/unit/marketplace/test_token_store.py b/tests/unit/marketplace/test_token_store.py
index 317df9a86c..fcac3364d1 100644
--- a/tests/unit/marketplace/test_token_store.py
+++ b/tests/unit/marketplace/test_token_store.py
@@ -10,6 +10,7 @@ import pytest
from jarvis.marketplace.token_store import (
ChunkedBackend,
InMemoryBackend,
+ KeyringBackend,
Tokens,
TokenStore,
)
@@ -57,12 +58,13 @@ class _SilentDeleteBackend:
class _PartialOverflowDeleteBackend(_SizeLimitedFakeBackend):
- """Silently retains chunk one until the test allows its deletion."""
+ """Silently retains one selected chunk until the test allows deletion."""
- allow_chunk_one_delete = False
+ allow_blocked_chunk_delete = False
+ blocked_chunk_index = 1
def delete(self, key: str) -> None:
- if key.endswith("__1") and not self.allow_chunk_one_delete:
+ if key.endswith(f"__{self.blocked_chunk_index}") and not self.allow_blocked_chunk_delete:
return
super().delete(key)
@@ -123,6 +125,19 @@ def test_chunked_backend_cleanup_stops_after_silent_delete_failure():
assert primitive.overflow_get_calls == 2
+def test_keyring_delete_is_strict_but_housekeeping_remains_best_effort(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ from jarvis.core import config
+
+ monkeypatch.setattr(config, "delete_secret", lambda _key: False)
+ backend = KeyringBackend()
+
+ backend.delete_best_effort("plugin_gmail_tokens__9")
+ with pytest.raises(RuntimeError, match="keyring delete could not be verified"):
+ backend.delete("plugin_gmail_tokens")
+
+
class _FailNthSetBackend:
"""Mimics a keyring backend whose ``set`` raises on a chosen call number
(1-indexed across the object's whole lifetime) — used to simulate a
@@ -260,7 +275,7 @@ def test_store_delete_keeps_manifest_until_every_indexed_chunk_is_removed():
assert backend.store[primary_key] == manifest
assert backend.store[f"{primary_key}__1"]
- backend.allow_chunk_one_delete = True
+ backend.allow_blocked_chunk_delete = True
store.delete("gmail")
assert backend.store == {}
@@ -294,7 +309,7 @@ def test_shrink_persists_cleanup_extent_across_restart_until_delete_succeeds():
assert backend.store[f"{key}__extent"] == extent
assert backend.store[f"{key}__1"]
- backend.allow_chunk_one_delete = True
+ backend.allow_blocked_chunk_delete = True
restarted.delete("gmail")
assert backend.store == {}
@@ -339,7 +354,51 @@ def test_legacy_sparse_delete_retains_primary_and_extent_after_noop():
assert backend.store[f"{key}__1"] == "legacy-fragment-one"
assert backend.store[f"{key}__extent"] == "2"
- backend.allow_chunk_one_delete = True
+ backend.allow_blocked_chunk_delete = True
+ store.delete("gmail")
+
+ assert backend.store == {}
+
+
+def test_legacy_sparse_delete_scans_beyond_valid_smaller_manifest():
+ backend = _SizeLimitedFakeBackend(limit=1000)
+ key = "plugin_gmail_tokens"
+ chunked = ChunkedBackend(backend, chunk_size=20)
+ chunked.set(key, "a" * 30) # valid two-chunk active manifest
+ backend.store[f"{key}__4"] = "legacy-tail-fragment"
+ assert f"{key}__extent" not in backend.store
+
+ TokenStore(chunked).delete("gmail")
+
+ assert backend.store == {}
+
+
+def test_legacy_tail_failure_preserves_manifest_and_retries_exact_extent():
+ backend = _PartialOverflowDeleteBackend(limit=1000)
+ backend.blocked_chunk_index = 4
+ key = "plugin_gmail_tokens"
+ chunked = ChunkedBackend(backend, chunk_size=20)
+ chunked.set(key, "a" * 30) # valid two-chunk active manifest
+ legacy_manifest = backend.store[key]
+ backend.store[f"{key}__4"] = "legacy-tail-fragment"
+ store = TokenStore(chunked)
+
+ with pytest.raises(RuntimeError):
+ store.delete("gmail")
+
+ assert backend.store[key] == legacy_manifest
+ assert f"{key}__0" not in backend.store
+ assert f"{key}__1" not in backend.store
+ assert backend.store[f"{key}__4"] == "legacy-tail-fragment"
+ assert backend.store[f"{key}__extent"] == "5"
+
+ # The durable extent makes subsequent retries exact rather than heuristic.
+ with pytest.raises(RuntimeError):
+ store.delete("gmail")
+ assert backend.store[key] == legacy_manifest
+ assert backend.store[f"{key}__4"] == "legacy-tail-fragment"
+
+ backend.allow_blocked_chunk_delete = True
store.delete("gmail")
assert backend.store == {}