Linux maintainer tooling and workflows
 help / color / mirror / Atom feed
From: Dmitry Torokhov <dmitry.torokhov@gmail.com>
To: "Kernel.org Tools" <tools@kernel.org>
Cc: Konstantin Ryabitsev <konstantin@linuxfoundation.org>
Subject: [PATCH kgl 3/4] Add initial_labels, intra-pull dedup cache, and Gmail scope upgrades
Date: Fri, 04 Dec 2026 22:56:18 -0800	[thread overview]
Message-ID: <20261204-delivery-rules-v1-3-80af76016200@gmail.com> (raw)
In-Reply-To: <20261204-delivery-rules-v1-0-80af76016200@gmail.com>

Cross-posted messages imported multiple times across feeds and
deliveries reapply all configured labels on every import. For stateful
targets like Gmail and JMAP, this resurrects read or archived messages
by reapplying triage labels such as INBOX or UNREAD, while duplicate
uploads also waste network bandwidth and API quota.

Support initial labels in target import interfaces, applying them only
when a message is newly imported into the account instead of on
duplicate arrivals. Introduce an in-memory per-pull deduplication cache
for Gmail and JMAP targets that collapses duplicate uploads within a
single pull run, updating missing labels on existing messages instead of
re-uploading the entire message body (omitting UNREAD when modifying
pre-existing Gmail messages). Gmail targets without modify scope still
skip identical-label duplicates in the same pull, falling back to import
when a duplicate adds new labels.

Upgrade Gmail OAuth scopes to request modify permissions when labels
need to be updated on existing messages, handling scope verification
lazily during authentication and connection.

Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
---
 src/korgalore/__init__.py       |   4 +
 src/korgalore/cli.py            |  24 +++-
 src/korgalore/dummy_target.py   |   2 +
 src/korgalore/gmail_target.py   | 305 +++++++++++++++++++++++++++++++++++++---
 src/korgalore/google_creds.py   | 134 ++++++++++++++----
 src/korgalore/imap_target.py    |   2 +
 src/korgalore/jmap_target.py    | 177 ++++++++++++++++++++++-
 src/korgalore/maildir_target.py |   2 +
 src/korgalore/pipe_target.py    |   2 +
 tests/test_cli_misc.py          |  95 ++++++++++++-
 tests/test_gmail_target.py      | 304 ++++++++++++++++++++++++++++++++++++++-
 tests/test_google_creds.py      | 217 +++++++++++++++++++++++++++-
 tests/test_jmap_target.py       | 158 +++++++++++++++++++++
 tests/test_pull.py              |  30 ++++
 14 files changed, 1397 insertions(+), 59 deletions(-)

diff --git a/src/korgalore/__init__.py b/src/korgalore/__init__.py
index 5af2b0b..6805615 100644
--- a/src/korgalore/__init__.py
+++ b/src/korgalore/__init__.py
@@ -130,6 +130,10 @@ class AuthenticationError(KorgaloreError):
         self.target_type = target_type
 
 
+class InsufficientScopesError(AuthenticationError):
+    """Raised when target credentials lack required OAuth scopes."""
+
+
 def _init_git_user_agent() -> None:
     """Check git is available and set GIT_HTTP_USER_AGENT environment variable.
 
diff --git a/src/korgalore/cli.py b/src/korgalore/cli.py
index 1e4e3f2..1b048b5 100644
--- a/src/korgalore/cli.py
+++ b/src/korgalore/cli.py
@@ -339,20 +339,37 @@ def get_gmail_target(
     identifier: str,
     details: Mapping[str, Any],
     interactive: bool = True,
+    requires_modify: bool = False,
 ) -> GmailTarget:
-    """Create a Gmail target service instance."""
+    """Create a Gmail target service instance.
+
+    Args:
+        identifier: Target name from ``korgalore.toml``.
+        details: Target configuration mapping.
+        interactive: Whether interactive OAuth browser flows are permitted.
+        requires_modify: Whether ``gmail.modify`` scope is required for
+                         looking up and relabeling existing messages.
+
+    Returns:
+        Configured ``GmailTarget`` instance.
+
+    Raises:
+        click.Abort: If target configuration is invalid.
+    """
     try:
         creds = make_gmail_credentials(
             identifier=identifier,
             details=details,
             interactive=interactive,
             config_dir=get_xdg_config_dir(),
+            requires_modify=requires_modify,
         )
         gt = GmailTarget(
             identifier=identifier,
             creds=creds,
             message_date=details.get('message_date', DEFAULT_MESSAGE_DATE),
             never_mark_spam=details.get('never_mark_spam', False),
+            requires_modify=requires_modify,
         )
     except ConfigurationError as fe:
         logger.critical('Error: %s', str(fe))
@@ -729,7 +746,10 @@ def deliver_commit(
 
         if logger.isEnabledFor(logging.DEBUG):
             subject = msg_get_subject(msg) or '(no subject)'
-            logger.debug(' -> %s', subject)
+            if labels:
+                logger.debug(' -> %s (labels: %s)', subject, ', '.join(labels))
+            else:
+                logger.debug(' -> %s', subject)
         target.import_message(
             raw_message,
             labels=labels,
diff --git a/src/korgalore/dummy_target.py b/src/korgalore/dummy_target.py
index ca77e33..16b903a 100644
--- a/src/korgalore/dummy_target.py
+++ b/src/korgalore/dummy_target.py
@@ -35,6 +35,7 @@ class DummyTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Discard the message.
 
@@ -44,6 +45,7 @@ class DummyTarget:
             feed_name: Ignored.
             delivery_name: Ignored.
             subfolder: Ignored (no folder concept).
+            initial_labels: Ignored.
 
         Returns:
             None
diff --git a/src/korgalore/gmail_target.py b/src/korgalore/gmail_target.py
index 5a08f40..24d68fb 100644
--- a/src/korgalore/gmail_target.py
+++ b/src/korgalore/gmail_target.py
@@ -1,15 +1,20 @@
 import base64
 import logging
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
 from pathlib import Path
-from typing import Any
+from typing import Any, NoReturn
 
 from google.auth.credentials import Credentials as BaseCredentials
 from google.auth.transport.requests import Request
 from googleapiclient.discovery import Resource, build  # type: ignore[import-untyped]
 from googleapiclient.errors import HttpError  # type: ignore[import-untyped]
 
-from korgalore import AuthenticationError, ConfigurationError, RemoteError
+from korgalore import (
+    AuthenticationError,
+    ConfigurationError,
+    InsufficientScopesError,
+    RemoteError,
+)
 from korgalore.google_creds import CommandCredentials, OAuthFileCredentials, parse_token_command
 from korgalore.message import DEFAULT_MESSAGE_DATE, RawMessage, check_message_date, is_plausible_date
 
@@ -23,6 +28,52 @@ SCOPES = [
     'https://www.googleapis.com/auth/gmail.insert',
 ]
 
+# Required when initial_labels or delivery rules are configured so we can look
+# up existing messages across the mailbox and add literal labels without re-inserting.
+MODIFY_SCOPES = [
+    'https://www.googleapis.com/auth/gmail.labels',
+    'https://www.googleapis.com/auth/gmail.modify',
+]
+
+
+def has_gmail_scopes(granted_scopes: Any, required_scopes: Sequence[str]) -> bool:
+    """Check if granted Gmail OAuth scopes satisfy the required scopes.
+
+    Args:
+        granted_scopes: Scope collection recorded on credentials, or a
+            non-collection value when scope metadata is unavailable.
+        required_scopes: Gmail OAuth scope URIs required by the target.
+
+    Returns:
+        True if all required scopes (or broader Gmail scope equivalents) are
+        covered, or if scope metadata is unavailable.
+    """
+    # Treat missing or non-collection scope metadata (such as tokens without
+    # explicit scope claims) as provisionally valid; API calls still enforce
+    # permissions via HTTP 403.
+    if not isinstance(granted_scopes, (list, tuple, set, frozenset)):
+        return True
+    granted = {s.rstrip('/') for s in granted_scopes if isinstance(s, str) and s}
+    if 'https://mail.google.com' in granted:
+        return True
+    modify_scope = 'https://www.googleapis.com/auth/gmail.modify'
+    insert_scope = 'https://www.googleapis.com/auth/gmail.insert'
+    labels_scope = 'https://www.googleapis.com/auth/gmail.labels'
+    readonly_scope = 'https://www.googleapis.com/auth/gmail.readonly'
+    metadata_scope = 'https://www.googleapis.com/auth/gmail.metadata'
+    for req in required_scopes:
+        norm_req = req.rstrip('/')
+        if norm_req in granted:
+            continue
+        # gmail.modify is a strict superset of gmail.insert, and modify/readonly/
+        # metadata all cover label reads needed for gmail.labels translation.
+        if norm_req == insert_scope and modify_scope in granted:
+            continue
+        if norm_req == labels_scope and granted & {modify_scope, readonly_scope, metadata_scope}:
+            continue
+        return False
+    return True
+
 
 class GmailTarget:
     """Target class for delivering email messages to Gmail via the API."""
@@ -35,6 +86,7 @@ class GmailTarget:
         creds: BaseCredentials,
         message_date: str = DEFAULT_MESSAGE_DATE,
         never_mark_spam: object = False,
+        requires_modify: bool = False,
     ) -> None:
         """Initialize a GmailTarget instance.
 
@@ -48,6 +100,9 @@ class GmailTarget:
             never_mark_spam: True to stop Gmail from filing imported messages
                 under Spam. Typed as object because it comes straight from
                 the config file and is checked here.
+            requires_modify: Whether initial-arrival rules or ``initial_labels``
+                require ``gmail.modify`` scope to search and relabel
+                existing messages.
 
         Raises:
             ConfigurationError: If an option has the wrong value.
@@ -60,8 +115,11 @@ class GmailTarget:
         if not isinstance(never_mark_spam, bool):
             raise ConfigurationError(f"Gmail target '{identifier}': 'never_mark_spam' must be a boolean.")
         self.never_mark_spam = never_mark_spam
+        self.requires_modify = requires_modify
         self.service: Resource | None = None
         self._label_map: dict[str, str] | None = None
+        # Per-pull session cache: clean_msgid -> (remote_id, applied_ids, created_in_pull)
+        self._imported_msgids: dict[str, tuple[str, set[str], bool]] = {}
 
     @property
     def needs_auth(self) -> bool:
@@ -75,6 +133,45 @@ class GmailTarget:
         """Return True if target credentials support interactive reauthentication."""
         return isinstance(self.creds, OAuthFileCredentials)
 
+    def _handle_http_error(self, error: HttpError) -> NoReturn:
+        """Translate a Gmail API HttpError into a korgalore domain exception.
+
+        Args:
+            error: Google API HTTP error raised during a Gmail request.
+
+        Raises:
+            AuthenticationError: On HTTP 401 when credentials support interactive
+                                 re-authentication.
+            InsufficientScopesError: On HTTP 403 caused by missing OAuth scopes.
+            RemoteError: For all other Gmail API errors or non-reauthenticable 401s.
+        """
+        status = getattr(error.resp, 'status', None)
+        content = error.content.decode('utf-8', errors='replace') if hasattr(error, 'content') else str(error)
+        if status == 401:
+            if self.can_reauthenticate:
+                raise AuthenticationError(
+                    f"Gmail authentication expired or invalid for target '{self.identifier}': {error}",
+                    target_id=self.identifier,
+                    target_type='gmail',
+                ) from error
+            raise RemoteError(f"Gmail authentication failed for target '{self.identifier}': {error}") from error
+        if status == 403:
+            if 'ACCESS_TOKEN_SCOPE_INSUFFICIENT' in content or 'insufficientPermissions' in content:
+                hint = 'https://www.googleapis.com/auth/gmail.modify' if self.requires_modify else 'required'
+                if self.can_reauthenticate:
+                    action = f"Run 'kgl auth {self.identifier}' to re-authenticate."
+                else:
+                    action = (
+                        f"Update 'token_command' for target '{self.identifier}' to issue a token with {hint} scope."
+                    )
+                raise InsufficientScopesError(
+                    f"Gmail target '{self.identifier}' lacks {hint} OAuth scope. {action}",
+                    target_id=self.identifier,
+                    target_type='gmail',
+                ) from error
+            raise RemoteError(f'An error occurred: {error}') from error
+        raise RemoteError(f'An error occurred: {error}') from error
+
     def connect(self) -> None:
         """Establish connection to the Gmail API service.
 
@@ -84,6 +181,8 @@ class GmailTarget:
             ConfigurationError: If credentials file is missing or token_command
                                 cannot be executed.
             AuthenticationError: If OAuth token refresh or authentication fails.
+            InsufficientScopesError: If the loaded or refreshed token lacks
+                                     required OAuth scopes.
             RemoteError: If token_command fails, times out, or returns an
                          invalid token.
         """
@@ -94,13 +193,26 @@ class GmailTarget:
             self.creds.refresh(Request())  # type: ignore[no-untyped-call]
 
         logger.debug('Connecting to Gmail service for %s', self.identifier)
-        self.service = build('gmail', 'v1', credentials=self.creds, cache_discovery=False)
-        try:
-            self._label_map = {label['name']: label['id'] for label in self.list_labels()}
-        except Exception:
-            self.service = None
-            self._label_map = None
-            raise
+        for attempt in range(2):
+            self.service = build('gmail', 'v1', credentials=self.creds, cache_discovery=False)
+            try:
+                self._label_map = {label['name']: label['id'] for label in self.list_labels()}
+                if self.requires_modify:
+                    # Probe messages.list so tokens lacking metadata/modify claims fail upfront.
+                    self._find_existing_message('korgalore-scope-probe')
+                return
+            except InsufficientScopesError:
+                self.service = None
+                self._label_map = None
+                if attempt == 0 and isinstance(self.creds, OAuthFileCredentials) and self.creds.interactive:
+                    logger.info("Target '%s' lacks required scopes; re-authenticating...", self.identifier)
+                    self.reauthenticate()
+                    continue
+                raise
+            except Exception:
+                self.service = None
+                self._label_map = None
+                raise
 
     def _api(self) -> Any:
         """Return the connected Gmail API service, connecting first if needed.
@@ -124,7 +236,7 @@ class GmailTarget:
             return labels
 
         except HttpError as error:
-            raise RemoteError(f'An error occurred: {error}') from error
+            self._handle_http_error(error)
 
     def translate_labels(self, labels: list[str]) -> list[str]:
         """Translate label names to Gmail label IDs.
@@ -150,6 +262,45 @@ class GmailTarget:
             translated.append(label_id)
         return translated
 
+    def _label_names(self, label_ids: Sequence[str]) -> list[str]:
+        """Map label IDs back to human-readable label names using the loaded label map."""
+        if not label_ids:
+            return []
+        id_to_name = {lid: name for name, lid in self._label_map.items()} if self._label_map else {}
+        return [id_to_name.get(lid, lid) for lid in label_ids]
+
+    def _find_existing_message(self, message_id: str) -> str | None:
+        """Find an existing Gmail message matching an RFC 822 Message-ID.
+
+        Args:
+            message_id: Raw or angle-bracketed Message-ID header value.
+
+        Returns:
+            Gmail message ID if a matching message exists anywhere in the
+            account (including Spam and Trash), or None otherwise.
+
+        Raises:
+            AuthenticationError: If Gmail authentication is invalid.
+            InsufficientScopesError: If the token lacks ``gmail.modify`` scope.
+            RemoteError: If the Gmail search request fails.
+        """
+        clean_msgid = message_id.strip('<>').strip()
+        escaped = clean_msgid.replace('\\', '\\\\').replace('"', '\\"')
+        query = f'rfc822msgid:"{escaped}"'
+        try:
+            # Include Spam and Trash so previously trashed or archived messages
+            # are still found and never re-imported with initial labels.
+            results = (
+                self._api().users().messages().list(userId='me', q=query, maxResults=1, includeSpamTrash=True).execute()
+            )
+            messages = results.get('messages', [])
+            if messages:
+                msg_id = messages[0].get('id')
+                return str(msg_id) if msg_id is not None else None
+            return None
+        except HttpError as error:
+            self._handle_http_error(error)
+
     def import_message(
         self,
         raw_message: bytes,
@@ -157,32 +308,135 @@ class GmailTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Import a raw email message into Gmail.
 
         Args:
             raw_message: The raw email message as bytes.
-            labels: List of label names to apply to the message.
+            labels: List of literal label names to apply to the message.
             feed_name: Optional feed name for trace header.
             delivery_name: Optional delivery name for trace header.
             subfolder: Ignored for Gmail (use labels for folder assignment).
+            initial_labels: Optional label names applied only on initial arrival.
 
         Returns:
-            The Gmail API response object for the imported message.
+            The Gmail API response object for the imported or modified message.
 
         Raises:
+            ConfigurationError: If any requested label does not exist in Gmail.
+            AuthenticationError: If Gmail authentication is invalid.
+            InsufficientScopesError: If the token lacks required OAuth scopes.
             RemoteError: If the Gmail API call fails.
         """
+        literal_ids = list(dict.fromkeys(self.translate_labels(labels))) if labels else []
+        literal_id_set = set(literal_ids)
+        initial_ids = list(dict.fromkeys(self.translate_labels(initial_labels))) if initial_labels else []
+        effective_initial_ids = [lid for lid in initial_ids if lid not in literal_id_set]
+
+        msg = RawMessage(raw_message)
+        clean_msgid = msg.message_id.strip('<>').strip() or None if msg.message_id else None
+
         try:
-            msg = RawMessage(raw_message)
+            # Check intra-pull session dedup cache
+            if clean_msgid and clean_msgid in self._imported_msgids:
+                remote_id, applied_ids, created_in_pull = self._imported_msgids[clean_msgid]
+                if created_in_pull:
+                    # Message was freshly inserted in this pull, so all literal and
+                    # initial labels from later cross-posts still apply (including UNREAD).
+                    target_ids = literal_ids + effective_initial_ids
+                else:
+                    # Pre-existing message: omit UNREAD so already-read mail stays read.
+                    target_ids = [lid for lid in literal_ids if lid != 'UNREAD']
+                missing_ids = [lid for lid in target_ids if lid not in applied_ids]
+                if not missing_ids:
+                    logger.debug('Skipping duplicate Gmail import for %s in same pull', clean_msgid)
+                    return {'id': remote_id, 'skipped': True}
+
+                if self.requires_modify:
+                    missing_names = self._label_names(missing_ids)
+                    logger.debug(
+                        'Adding Gmail labels %s to duplicate message %s (%s)',
+                        missing_names,
+                        clean_msgid,
+                        remote_id,
+                    )
+                    try:
+                        res = (
+                            self._api()
+                            .users()
+                            .messages()
+                            .modify(userId='me', id=remote_id, body={'addLabelIds': missing_ids})
+                            .execute()
+                        )
+                        applied_ids.update(missing_ids)
+                        return res
+                    except HttpError as error:
+                        if getattr(error.resp, 'status', None) == 404:
+                            logger.debug(
+                                'Existing Gmail message %s vanished before modify; falling back to import',
+                                remote_id,
+                            )
+                            self._imported_msgids.pop(clean_msgid, None)
+                        else:
+                            self._handle_http_error(error)
+                # If not requires_modify or modify hit 404, fall through to import
+
+            # Check pre-existing message in Gmail mailbox when initial_labels need protection
+            if effective_initial_ids and clean_msgid and self.requires_modify:
+                existing_id = self._find_existing_message(clean_msgid)
+                if existing_id is not None:
+                    # Avoid re-marking pre-existing (possibly already read) messages as UNREAD.
+                    modify_label_ids = [lid for lid in literal_ids if lid != 'UNREAD']
+                    if not modify_label_ids:
+                        logger.debug('Skipping Gmail import: message %s already exists as %s', clean_msgid, existing_id)
+                        self._imported_msgids[clean_msgid] = (existing_id, set(), False)
+                        return {'id': existing_id, 'skipped': True}
+                    modify_names = self._label_names(modify_label_ids)
+                    logger.debug(
+                        'Adding Gmail labels %s to existing message %s (%s)',
+                        modify_names,
+                        clean_msgid,
+                        existing_id,
+                    )
+                    try:
+                        res = (
+                            self._api()
+                            .users()
+                            .messages()
+                            .modify(
+                                userId='me',
+                                id=existing_id,
+                                body={'addLabelIds': modify_label_ids},
+                            )
+                            .execute()
+                        )
+                        self._imported_msgids[clean_msgid] = (existing_id, set(modify_label_ids), False)
+                        return res
+                    except HttpError as error:
+                        if getattr(error.resp, 'status', None) == 404:
+                            logger.debug(
+                                'Existing Gmail message %s vanished before modify; falling back to import',
+                                existing_id,
+                            )
+                        else:
+                            self._handle_http_error(error)
+
+            # Upload the message
             encoded_message = base64.urlsafe_b64encode(msg.as_bytes(feed_name, delivery_name)).decode()
             message_body: dict[str, Any] = {'raw': encoded_message}
 
-            if labels:
-                label_ids = self.translate_labels(labels)
-                message_body['labelIds'] = label_ids
+            combined_ids = literal_ids + effective_initial_ids
+            if combined_ids:
+                message_body['labelIds'] = combined_ids
+
+            combined_names = self._label_names(combined_ids)
+            logger.debug(
+                'Importing message %s to Gmail with labels: %s',
+                clean_msgid or '(no-msgid)',
+                combined_names,
+            )
 
-            # Upload the message
             result = (
                 self._api()
                 .users()
@@ -195,11 +449,17 @@ class GmailTarget:
                 )
                 .execute()
             )
+            remote_id = result.get('id')
+            if clean_msgid and remote_id:
+                existing_entry = self._imported_msgids.get(clean_msgid)
+                prior_applied = existing_entry[1] if existing_entry else set()
+                prior_created = existing_entry[2] if existing_entry else True
+                self._imported_msgids[clean_msgid] = (str(remote_id), prior_applied | set(combined_ids), prior_created)
 
             return result
 
         except HttpError as error:
-            raise RemoteError(f'An error occurred: {error}') from error
+            self._handle_http_error(error)
 
     def _internal_date_source(self, msg: RawMessage) -> str:
         """Choose how Gmail dates the message.
@@ -238,6 +498,7 @@ class GmailTarget:
         self.creds.reauthenticate()
         self.service = None
         self._label_map = None
+        self._imported_msgids.clear()
 
 
 def make_gmail_credentials(
@@ -245,6 +506,7 @@ def make_gmail_credentials(
     details: Mapping[str, Any],
     config_dir: Path,
     interactive: bool = True,
+    requires_modify: bool = False,
 ) -> BaseCredentials:
     """Create credentials for a Gmail target from configuration.
 
@@ -253,6 +515,8 @@ def make_gmail_credentials(
         details: Target configuration mapping from ``korgalore.toml``.
         config_dir: Configuration directory that holds the default token file.
         interactive: Whether interactive OAuth browser flows are permitted.
+        requires_modify: Whether OAuth file credentials must include
+                         ``gmail.modify`` scope.
 
     Returns:
         Configured credentials instance compatible with ``GmailTarget``.
@@ -290,7 +554,8 @@ def make_gmail_credentials(
         identifier=identifier,
         credentials_file=creds_raw,
         token_file=token_file,
-        scopes=SCOPES,
+        scopes=MODIFY_SCOPES if requires_modify else SCOPES,
         interactive=interactive,
         target_type='gmail',
+        scope_checker=has_gmail_scopes,
     )
diff --git a/src/korgalore/google_creds.py b/src/korgalore/google_creds.py
index eb07c1d..c8cc527 100644
--- a/src/korgalore/google_creds.py
+++ b/src/korgalore/google_creds.py
@@ -3,7 +3,7 @@
 import logging
 import os
 import subprocess
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
 from pathlib import Path
 from typing import Any
 
@@ -14,10 +14,44 @@ from google.auth.transport.requests import Request
 from google.oauth2.credentials import Credentials
 from google_auth_oauthlib.flow import InstalledAppFlow  # type: ignore[import-untyped]
 
-from korgalore import AuthenticationError, ConfigurationError, RemoteError, atomic_write, split_command
+from korgalore import (
+    AuthenticationError,
+    ConfigurationError,
+    InsufficientScopesError,
+    RemoteError,
+    atomic_write,
+    split_command,
+)
 
 logger = logging.getLogger('korgalore')
 
+
+def effective_creds_scopes(creds: Any) -> Any:
+    """Return concrete granted scopes, falling back to configured scopes.
+
+    Args:
+        creds: Google credentials instance loaded from disk or OAuth flow.
+
+    Returns:
+        Granted scope collection if present as a concrete sequence or set,
+        otherwise the credential's configured ``scopes`` attribute or ``None``.
+    """
+    # Prefer granted_scopes only when it is a concrete collection so tokens
+    # without explicit granted_scopes still fall back to .scopes.
+    granted = getattr(creds, 'granted_scopes', None)
+    if isinstance(granted, (list, tuple, set, frozenset)):
+        return granted
+    return getattr(creds, 'scopes', None)
+
+
+def default_scope_checker(granted_scopes: Any, required_scopes: Sequence[str]) -> bool:
+    """Check whether concrete granted scopes cover every required scope."""
+    if not isinstance(granted_scopes, (list, tuple, set, frozenset)):
+        return True
+    granted = {s.rstrip('/') for s in granted_scopes if isinstance(s, str) and s}
+    return all(req.rstrip('/') in granted for req in required_scopes)
+
+
 # InstalledAppFlow.run_local_server() returns either flavour depending on what
 # the client_secrets file describes. Both expose the valid/expired/refresh_token
 # attributes and the to_json() and refresh() methods used below, so the code
@@ -36,6 +70,7 @@ class OAuthFileCredentials(BaseCredentials):
         scopes: Sequence[str],
         interactive: bool = True,
         target_type: str = 'gmail',
+        scope_checker: Callable[[Any, Sequence[str]], bool] | None = None,
     ) -> None:
         """Initialize file-backed OAuth credentials for a Google target.
 
@@ -52,6 +87,8 @@ class OAuthFileCredentials(BaseCredentials):
                          If False, raise ``AuthenticationError`` on
                          ``refresh()`` instead (for GUI/unattended mode).
             target_type: Target type string reported in AuthenticationError.
+            scope_checker: Optional callable validating granted scopes against
+                           required scopes.
 
         Raises:
             ConfigurationError: If credentials file path is empty.
@@ -63,6 +100,7 @@ class OAuthFileCredentials(BaseCredentials):
         self._scopes = list(scopes)
         self._target_type = target_type
         self.needs_auth = False
+        self._scope_checker = scope_checker or default_scope_checker
 
         if not credentials_file:
             raise ConfigurationError(f"No credentials file specified for target '{identifier}'.")
@@ -114,11 +152,30 @@ class OAuthFileCredentials(BaseCredentials):
         if self._creds:
             self._creds.expiry = value
 
+    def _has_required_scopes(self, creds: Any) -> bool:
+        """Return True if credentials satisfy all required scopes."""
+        return self._scope_checker(effective_creds_scopes(creds), self._scopes)
+
     @property
     def valid(self) -> bool:
-        """Whether loaded OAuth2 credentials are present and currently valid."""
+        """Whether loaded OAuth2 credentials are valid and satisfy required scopes."""
+        if self._creds and not self._has_required_scopes(self._creds):
+            return False
         return bool(self._creds and self._creds.valid)
 
+    @property
+    def interactive(self) -> bool:
+        """Whether this credential provider may prompt interactively."""
+        return self._interactive
+
+    def _missing_scopes_error(self) -> InsufficientScopesError:
+        """Build an InsufficientScopesError with remediation instructions."""
+        return InsufficientScopesError(
+            f"OAuth token for '{self.identifier}' lacks required scopes. Run 'kgl auth {self.identifier}'.",
+            target_id=self.identifier,
+            target_type=self._target_type,
+        )
+
     def _save_token(self) -> None:
         """Persist current OAuth credentials to the configured token file."""
         if self._creds is None:
@@ -148,32 +205,49 @@ class OAuthFileCredentials(BaseCredentials):
                                 authentication is needed.
             AuthenticationError: If refresh fails or authentication is needed
                                  in non-interactive mode.
+            InsufficientScopesError: If the loaded or refreshed token lacks
+                                     required OAuth scopes.
         """
         just_loaded = self._load_token_file()
-        if just_loaded and self._creds and self._creds.valid:
-            self.needs_auth = False
-            return
-
-        req = request or Request()
-        # If there are no (valid) credentials available, refresh or let the user log in
-        if self._creds and self._creds.refresh_token:
-            try:
-                self._creds.refresh(req)  # type: ignore[no-untyped-call]
-                self._save_token()
+        if self._creds and not self._has_required_scopes(self._creds):
+            if not self._interactive:
+                self.needs_auth = True
+                raise self._missing_scopes_error()
+            logger.info("OAuth token for '%s' lacks required scopes; re-authenticating...", self.identifier)
+        else:
+            if just_loaded and self._creds and self._creds.valid:
                 self.needs_auth = False
                 return
-            except RefreshError as e:
-                logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
-                self._quarantine_token()
-                self._creds = None
-                if not self._interactive:
-                    self.needs_auth = True
-                    # In non-interactive mode (GUI), fail fast so the UI can prompt re-auth
-                    raise AuthenticationError(
-                        f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
-                        target_id=self.identifier,
-                        target_type=self._target_type,
-                    ) from e
+
+            req = request or Request()
+            # If there are no (valid) credentials available, refresh or let the user log in
+            if self._creds and self._creds.refresh_token:
+                try:
+                    self._creds.refresh(req)  # type: ignore[no-untyped-call]
+                    if not self._has_required_scopes(self._creds):
+                        if not self._interactive:
+                            self.needs_auth = True
+                            raise self._missing_scopes_error()
+                        logger.info(
+                            "OAuth token for '%s' lacks required scopes; re-authenticating...",
+                            self.identifier,
+                        )
+                    else:
+                        self._save_token()
+                        self.needs_auth = False
+                        return
+                except RefreshError as e:
+                    logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
+                    self._quarantine_token()
+                    self._creds = None
+                    if not self._interactive:
+                        self.needs_auth = True
+                        # In non-interactive mode (GUI), fail fast so the UI can prompt re-auth
+                        raise AuthenticationError(
+                            f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
+                            target_id=self.identifier,
+                            target_type=self._target_type,
+                        ) from e
 
         if not self._credentials_file.exists():
             raise ConfigurationError(
@@ -198,6 +272,8 @@ class OAuthFileCredentials(BaseCredentials):
         Raises:
             ConfigurationError: If credentials file is not found.
             AuthenticationError: If the local OAuth authorization flow fails.
+            InsufficientScopesError: If the user completes OAuth consent without
+                                     granting all required scopes.
         """
         if not self._credentials_file.exists():
             raise ConfigurationError(
@@ -206,7 +282,7 @@ class OAuthFileCredentials(BaseCredentials):
         logger.critical('Log in to account for %s', self.identifier)
         try:
             flow = InstalledAppFlow.from_client_secrets_file(str(self._credentials_file), self._scopes)
-            self._creds = flow.run_local_server(port=0)
+            new_creds = flow.run_local_server(port=0)
         except Exception as e:
             self.needs_auth = True
             raise AuthenticationError(
@@ -214,6 +290,12 @@ class OAuthFileCredentials(BaseCredentials):
                 target_id=self.identifier,
                 target_type=self._target_type,
             ) from e
+        # Validate scopes on the fresh credentials before updating self._creds or
+        # saving token.json so partial consent never overwrites a working token.
+        if not self._has_required_scopes(new_creds):
+            self.needs_auth = True
+            raise self._missing_scopes_error()
+        self._creds = new_creds
         self._save_token()
         self.needs_auth = False
 
diff --git a/src/korgalore/imap_target.py b/src/korgalore/imap_target.py
index 73bc280..824495a 100644
--- a/src/korgalore/imap_target.py
+++ b/src/korgalore/imap_target.py
@@ -258,6 +258,7 @@ class ImapTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Import raw email message to IMAP server.
 
@@ -267,6 +268,7 @@ class ImapTarget:
             feed_name: Optional feed name for trace header
             delivery_name: Optional delivery name for trace header
             subfolder: Optional subfolder path relative to target's folder
+            initial_labels: Ignored for IMAP (single folder only)
 
         Returns:
             IMAP response from APPEND command
diff --git a/src/korgalore/jmap_target.py b/src/korgalore/jmap_target.py
index 35dc59e..5d30d65 100644
--- a/src/korgalore/jmap_target.py
+++ b/src/korgalore/jmap_target.py
@@ -76,6 +76,69 @@ class JmapTarget:
         # Mailbox cache
         self._mailbox_map: dict[str, str] | None = None  # name -> id
 
+        # Per-pull session cache: clean_msgid -> (email_id, applied_mailbox_ids, created_in_pull)
+        self._imported_msgids: dict[str, tuple[str, set[str], bool]] = {}
+
+    def _add_mailboxes(self, email_id: str, mailbox_ids: list[str]) -> bool:
+        """Add mailbox IDs to an existing email via JMAP Email/set.
+
+        Args:
+            email_id: Existing JMAP email ID to update.
+            mailbox_ids: Mailbox IDs to attach to the email.
+
+        Returns:
+            True if the update succeeded (or nothing needed updating), or False if
+            the server reported ``notFound`` so the caller can fall back to import.
+
+        Raises:
+            RemoteError: If the HTTP request fails or JMAP returns another error.
+        """
+        if not mailbox_ids or not self.api_url:
+            return True
+        update_patch = {f'mailboxIds/{mb_id}': True for mb_id in mailbox_ids}
+        request_body = {
+            'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
+            'methodCalls': [
+                [
+                    'Email/set',
+                    {
+                        'accountId': self.account_id,
+                        'update': {
+                            email_id: update_patch,
+                        },
+                    },
+                    'call-set',
+                ]
+            ],
+        }
+        try:
+            response = self._get_session().post(
+                self.api_url,
+                json=request_body,
+                headers={'Authorization': f'Bearer {self.token}'},
+                timeout=self.timeout,
+            )
+            response.raise_for_status()
+            result = response.json()
+        except requests.RequestException as e:
+            raise RemoteError(f'Failed to update mailboxes for email {email_id}: {e}') from e
+
+        for method_response in result.get('methodResponses', []):
+            method_name, method_result, _ = method_response
+            if method_name == 'error':
+                raise RemoteError(f'JMAP Email/set failed: {method_result}')
+            if method_name == 'Email/set':
+                not_updated = method_result.get('notUpdated') or {}
+                if email_id in not_updated:
+                    err = not_updated[email_id]
+                    if isinstance(err, dict) and err.get('type') == 'notFound':
+                        logger.debug('Existing JMAP message %s vanished before Email/set update', email_id)
+                        return False
+                    raise RemoteError(f'JMAP Email/set failed: {not_updated}')
+                if not_updated:
+                    raise RemoteError(f'JMAP Email/set failed: {not_updated}')
+        return True
+
     def _get_session(self) -> requests.Session:
         """Get requests session, using provided one or falling back to requests module."""
         if self._reqsession is not None:
@@ -296,6 +359,63 @@ class JmapTarget:
             logger.debug('Failed to check for existing message: %s', e)
             return False
 
+    def _find_existing_message(self, message_id: str) -> str | None:
+        """Find any existing email in the JMAP account matching Message-ID.
+
+        Expects angle-bracketed Message-IDs so RFC 8621 header substring matching
+        is bounded and does not match substrings of unrelated Message-IDs. Unlike
+        ``_check_message_exists``, query errors fail closed by raising
+        ``RemoteError`` instead of returning None and risking duplicate imports
+        with initial labels into INBOX.
+
+        Args:
+            message_id: Angle-bracketed RFC 5322 Message-ID header value.
+
+        Returns:
+            JMAP email ID if found in any mailbox, or None if absent.
+
+        Raises:
+            RemoteError: If the HTTP request fails or JMAP returns an error.
+        """
+        assert self.api_url is not None, 'Must call connect() first'
+        request_body = {
+            'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
+            'methodCalls': [
+                [
+                    'Email/query',
+                    {
+                        'accountId': self.account_id,
+                        'filter': {'header': ['Message-ID', message_id]},
+                        'limit': 1,
+                    },
+                    'call-0',
+                ]
+            ],
+        }
+        try:
+            response = self._get_session().post(
+                self.api_url,
+                json=request_body,
+                headers={'Authorization': f'Bearer {self.token}'},
+                timeout=self.timeout,
+            )
+            response.raise_for_status()
+            result = response.json()
+        except requests.RequestException as e:
+            raise RemoteError(f'Failed to query JMAP message {message_id}: {e}') from e
+
+        for method_response in result.get('methodResponses', []):
+            method_name, method_result, _ = method_response
+            if method_name == 'error':
+                raise RemoteError(f'JMAP Email/query failed: {method_result}')
+            if method_name == 'Email/query':
+                ids = method_result.get('ids', [])
+                if ids:
+                    return str(ids[0])
+                return None
+
+        raise RemoteError(f'Unexpected JMAP Email/query response: {result}')
+
     def import_message(
         self,
         raw_message: bytes,
@@ -303,6 +423,7 @@ class JmapTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Import raw email message to JMAP server.
 
@@ -312,6 +433,7 @@ class JmapTarget:
             feed_name: Optional feed name for trace header
             delivery_name: Optional delivery name for trace header
             subfolder: Ignored for JMAP (use labels for multiple folders)
+            initial_labels: Optional initial folder names applied only on initial arrival
 
         Returns:
             JMAP import result dict
@@ -326,17 +448,52 @@ class JmapTarget:
         else:
             # Default to INBOX if no folders specified
             mailbox_ids_list = self.translate_folders(['inbox'])
-
-        # Step 2: Check if message already exists in target mailbox(es)
+        literal_mb_set = set(mailbox_ids_list)
+
+        effective_initial_mb_ids: list[str] = []
+        if initial_labels:
+            raw_initial_mb_ids = self.translate_folders(initial_labels)
+            effective_initial_mb_ids = [
+                mb_id for mb_id in dict.fromkeys(raw_initial_mb_ids) if mb_id not in literal_mb_set
+            ]
+
+        clean_msgid = msg.message_id.strip('<>').strip() or None if msg.message_id else None
+
+        # Step 2: Check intra-pull cache
+        if clean_msgid and clean_msgid in self._imported_msgids:
+            existing_id, applied_mb_ids, created_in_pull = self._imported_msgids[clean_msgid]
+            target_mb_ids = mailbox_ids_list + (effective_initial_mb_ids if created_in_pull else [])
+            missing_mb_ids = [mb_id for mb_id in target_mb_ids if mb_id not in applied_mb_ids]
+            if not missing_mb_ids:
+                logger.debug('Skipping duplicate JMAP import for %s in same pull', clean_msgid)
+                return {'id': existing_id, 'skipped': True}
+
+            if self._add_mailboxes(existing_id, missing_mb_ids):
+                applied_mb_ids.update(missing_mb_ids)
+                return {'id': existing_id, 'modified': True}
+            logger.debug('Existing JMAP message %s vanished before update; falling back to import', existing_id)
+            self._imported_msgids.pop(clean_msgid, None)
+
+        # Step 3: Check if message already exists in target mailbox(es)
         if msg.message_id and self._check_message_exists(msg.message_id, mailbox_ids_list):
             logger.debug('Skipping import: message %s already in target mailbox', msg.message_id)
             return {'id': '(duplicate)', 'skipped': True}
 
-        # Step 3: Upload blob
+        # Step 3b: Check if message already exists anywhere in the JMAP account
+        if effective_initial_mb_ids and clean_msgid:
+            found_id = self._find_existing_message(f'<{clean_msgid}>')
+            if found_id is not None:
+                if self._add_mailboxes(found_id, mailbox_ids_list):
+                    self._imported_msgids[clean_msgid] = (found_id, set(mailbox_ids_list), False)
+                    return {'id': found_id, 'modified': True}
+                logger.debug('Existing JMAP message %s vanished before update; falling back to import', found_id)
+
+        # Step 4: Upload blob
         blob_id = self._upload_blob(msg.as_bytes(feed_name, delivery_name))
 
+        all_mb_ids = mailbox_ids_list + effective_initial_mb_ids
         # Build mailboxIds dict (id -> true)
-        mailbox_ids = {mb_id: True for mb_id in mailbox_ids_list}
+        mailbox_ids = {mb_id: True for mb_id in all_mb_ids}
 
         email: dict[str, Any] = {
             'blobId': blob_id,
@@ -378,7 +535,10 @@ class JmapTarget:
                     # Check for successful creation first
                     created = method_result.get('created', {})
                     if 'msg1' in created:
-                        logger.debug('Imported message: %s', created['msg1']['id'])
+                        msg_id = str(created['msg1']['id'])
+                        logger.debug('Imported message: %s', msg_id)
+                        if clean_msgid:
+                            self._imported_msgids[clean_msgid] = (msg_id, set(all_mb_ids), True)
                         return created['msg1']
 
                     # If not created, check if there were errors (notCreated will be non-empty)
@@ -388,6 +548,13 @@ class JmapTarget:
                         if 'msg1' in not_created and not_created['msg1'].get('type') == 'alreadyExists':
                             existing_id = not_created['msg1'].get('existingId', '(unknown)')
                             logger.debug('Message already exists with id: %s', existing_id)
+                            if (
+                                existing_id
+                                and existing_id != '(unknown)'
+                                and self._add_mailboxes(existing_id, mailbox_ids_list)
+                                and clean_msgid
+                            ):
+                                self._imported_msgids[clean_msgid] = (existing_id, set(mailbox_ids_list), False)
                             return {'id': existing_id}
                         # Any other error is a real failure
                         raise RemoteError(f'JMAP Email/import failed: {not_created}')
diff --git a/src/korgalore/maildir_target.py b/src/korgalore/maildir_target.py
index 3c12978..56be4ce 100644
--- a/src/korgalore/maildir_target.py
+++ b/src/korgalore/maildir_target.py
@@ -85,6 +85,7 @@ class MaildirTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Import message to maildir.
 
@@ -94,6 +95,7 @@ class MaildirTarget:
             feed_name: Optional feed name for trace header
             delivery_name: Optional delivery name for trace header
             subfolder: Optional subfolder path relative to base maildir
+            initial_labels: Ignored for maildir (single folder per target)
 
         Returns:
             Message key from maildir
diff --git a/src/korgalore/pipe_target.py b/src/korgalore/pipe_target.py
index bb026de..d688d7d 100644
--- a/src/korgalore/pipe_target.py
+++ b/src/korgalore/pipe_target.py
@@ -63,6 +63,7 @@ class PipeTarget:
         feed_name: str | None = None,
         delivery_name: str | None = None,
         subfolder: str | None = None,
+        initial_labels: list[str] | None = None,
     ) -> Any:
         """Pipe message to the configured command.
 
@@ -72,6 +73,7 @@ class PipeTarget:
             feed_name: Optional feed name for trace header
             delivery_name: Optional delivery name for trace header
             subfolder: Ignored for pipe target (no folder concept)
+            initial_labels: Ignored for pipe target
 
         Returns:
             Return code from the command
diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py
index 427e8c6..becc858 100644
--- a/tests/test_cli_misc.py
+++ b/tests/test_cli_misc.py
@@ -16,10 +16,12 @@ from unittest.mock import MagicMock, patch
 import click
 import pytest
 from click.testing import CliRunner
+from googleapiclient.errors import HttpError  # type: ignore[import-untyped]
 
-from korgalore import format_key_for_display
-from korgalore.cli import get_target, progress_file, pull
-from korgalore.gmail_target import GmailTarget, make_gmail_credentials
+from korgalore import InsufficientScopesError, format_key_for_display
+from korgalore.cli import auth, get_target, progress_file, pull
+from korgalore.gmail_target import MODIFY_SCOPES, GmailTarget, make_gmail_credentials
+from korgalore.google_creds import OAuthFileCredentials
 from tests.digest_helpers import make_ctx
 
 
@@ -178,3 +180,90 @@ def test_get_target_non_interactive_when_gui_mode() -> None:
         assert res == 'target-service'
         assert mock_gmail.call_args.kwargs['interactive'] is False
         assert mock_gmail.call_args.kwargs['identifier'] == 'test'
+
+
+def test_auth_connects_target_successfully() -> None:
+    runner = CliRunner()
+    ctx_obj = {
+        'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+        'targets': {},
+    }
+    with patch('korgalore.cli.get_target') as mock_gt:
+        target = MagicMock()
+        mock_gt.return_value = target
+        res = runner.invoke(auth, ['test'], obj=ctx_obj)
+        assert res.exit_code == 0
+        target.connect.assert_called_once()
+
+
+def test_auth_aborts_when_connect_raises_insufficient_scopes() -> None:
+    runner = CliRunner()
+    ctx_obj = {
+        'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+        'targets': {},
+    }
+    with patch('korgalore.cli.get_target') as mock_gt:
+        target = MagicMock()
+        target.connect.side_effect = InsufficientScopesError('need modify', target_id='test', target_type='gmail')
+        mock_gt.return_value = target
+        res = runner.invoke(auth, ['test'], obj=ctx_obj)
+        assert res.exit_code == 1
+        target.connect.assert_called_once()
+
+
+def gmail_http_403_scope_error() -> HttpError:
+    resp = MagicMock()
+    resp.status = 403
+    return HttpError(resp, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}')
+
+
+def test_auth_gmail_scope_probe_403_reauthenticates(tmp_path: Path) -> None:
+    runner = CliRunner()
+    creds_path = tmp_path / 'creds.json'
+    creds_path.write_text('{}')
+    provider = OAuthFileCredentials('test', str(creds_path), str(tmp_path / 'token.json'), scopes=MODIFY_SCOPES)
+    provider._creds = MagicMock(valid=True, scopes=None, granted_scopes=None)
+    gt = GmailTarget('test', creds=provider, requires_modify=True)
+
+    probe_service = MagicMock()
+    probe_service.users().labels().list().execute.return_value = {'labels': []}
+    probe_service.users().messages().list().execute.side_effect = [
+        gmail_http_403_scope_error(),
+        {'messages': []},
+    ]
+    ctx_obj = {
+        'config': {'targets': {'test': {'type': 'gmail', 'credentials': str(creds_path)}}},
+        'targets': {},
+    }
+
+    with (
+        patch('korgalore.cli.get_target', return_value=gt),
+        patch('korgalore.gmail_target.build', return_value=probe_service),
+        patch.object(provider, 'reauthenticate') as mock_reauth,
+    ):
+        mock_reauth.side_effect = lambda: setattr(
+            provider, '_creds', MagicMock(valid=True, scopes=None, granted_scopes=None)
+        )
+        res = runner.invoke(auth, ['test'], obj=ctx_obj)
+        assert res.exit_code == 0
+        mock_reauth.assert_called_once()
+        assert probe_service.users().messages().list().execute.call_count == 2
+
+
+def test_auth_gmail_token_command_scope_probe_403_aborts() -> None:
+    runner = CliRunner()
+    ctx_obj = {
+        'config': {'targets': {'test': {'type': 'gmail', 'token_command': 'get-token'}}},
+        'targets': {},
+    }
+    probe_service = MagicMock()
+    probe_service.users().labels().list().execute.return_value = {'labels': []}
+    probe_service.users().messages().list().execute.side_effect = gmail_http_403_scope_error()
+    gt = GmailTarget('test', creds=MagicMock(valid=True), requires_modify=True)
+
+    with (
+        patch('korgalore.cli.get_target', return_value=gt),
+        patch('korgalore.gmail_target.build', return_value=probe_service),
+    ):
+        res = runner.invoke(auth, ['test'], obj=ctx_obj)
+        assert res.exit_code == 1
diff --git a/tests/test_gmail_target.py b/tests/test_gmail_target.py
index 35c37c2..1e28054 100644
--- a/tests/test_gmail_target.py
+++ b/tests/test_gmail_target.py
@@ -1,6 +1,7 @@
 """Tests for GmailTarget message delivery."""
 
 import base64
+import logging
 from pathlib import Path
 from typing import Any
 from unittest.mock import MagicMock, patch
@@ -9,8 +10,8 @@ import pytest
 from google.auth.credentials import Credentials as BaseCredentials
 from googleapiclient.errors import HttpError  # type: ignore[import-untyped]
 
-from korgalore import AuthenticationError, ConfigurationError, RemoteError
-from korgalore.gmail_target import SCOPES, GmailTarget, make_gmail_credentials
+from korgalore import AuthenticationError, ConfigurationError, InsufficientScopesError, RemoteError
+from korgalore.gmail_target import MODIFY_SCOPES, SCOPES, GmailTarget, has_gmail_scopes, make_gmail_credentials
 from korgalore.google_creds import CommandCredentials, OAuthFileCredentials
 
 
@@ -453,3 +454,302 @@ class TestMakeGmailCredentials:
 
         mock_credentials.from_authorized_user_file.assert_called_once_with(str(default_token))
         assert creds._scopes == SCOPES
+
+    def test_requires_modify_uses_modify_scopes_and_gmail_checker(self, tmp_path: Path) -> None:
+        """requires_modify=True selects MODIFY_SCOPES and Gmail scope equivalence checker."""
+        creds = make_gmail_credentials(
+            'work',
+            {'credentials': str(tmp_path / 'creds.json'), 'token': str(tmp_path / 'token.json')},
+            UNUSED_CONFIG_DIR,
+            requires_modify=True,
+        )
+
+        assert isinstance(creds, OAuthFileCredentials)
+        assert creds._scopes == MODIFY_SCOPES
+        assert creds._scope_checker is has_gmail_scopes
+
+    def test_has_gmail_scopes_hierarchy(self) -> None:
+        """Higher-privilege Gmail scopes satisfy lower-privilege required scopes."""
+        assert has_gmail_scopes(['https://mail.google.com/'], MODIFY_SCOPES)
+        assert has_gmail_scopes(['https://www.googleapis.com/auth/gmail.modify'], SCOPES)
+        assert has_gmail_scopes(
+            ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.insert'],
+            SCOPES,
+        )
+        assert has_gmail_scopes(
+            ['https://www.googleapis.com/auth/gmail.metadata', 'https://www.googleapis.com/auth/gmail.insert'],
+            SCOPES,
+        )
+        assert not has_gmail_scopes(['https://www.googleapis.com/auth/gmail.labels'], SCOPES)
+        assert not has_gmail_scopes(SCOPES, MODIFY_SCOPES)
+
+
+class TestGmailTargetDedupAndScopes:
+    """Tests for intra-pull dedup cache and scope handling."""
+
+    def test_intra_pull_dedup_skips_duplicate(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """Subsequent deliveries of same message in same pull with same labels make 0 RPCs."""
+        target, service = gmail_labels
+        service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+        raw = b'Message-ID: <test@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        res1 = target.import_message(raw, ['INBOX'])
+        assert res1 == {'id': 'msg-1'}
+        assert service.users().messages().import_().execute.call_count == 1
+
+        # Second delivery of same message with same label in same pull
+        res2 = target.import_message(raw, ['INBOX'])
+        assert res2 == {'id': 'msg-1', 'skipped': True}
+        assert service.users().messages().import_().execute.call_count == 1
+        service.users().messages().modify.assert_not_called()
+
+    def test_intra_pull_dedup_adds_missing_labels(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """Subsequent delivery with new label modifies the message."""
+        target, service = gmail_labels
+        target.requires_modify = True
+        service.users().messages().import_.return_value.execute.return_value = {'id': 'msg-1'}
+        service.users().messages().modify.return_value.execute.return_value = {'id': 'msg-1', 'modified': True}
+        raw = b'Message-ID: <test@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        target.import_message(raw, ['INBOX'])
+        res2 = target.import_message(raw, ['INBOX', 'MyLabel'])
+
+        assert res2 == {'id': 'msg-1', 'modified': True}
+        service.users().messages().modify.assert_called_once_with(
+            userId='me', id='msg-1', body={'addLabelIds': ['Label_123']}
+        )
+
+    def test_pre_existing_message_omits_unread_and_skips_initial(
+        self, gmail_labels: tuple[GmailTarget, MagicMock]
+    ) -> None:
+        """Pre-existing message found via list: skips initial_labels and omits UNREAD."""
+        target, service = gmail_labels
+        target.requires_modify = True
+        service.users().messages().list.return_value.execute.return_value = {'messages': [{'id': 'existing-msg'}]}
+        service.users().messages().modify.return_value.execute.return_value = {'id': 'existing-msg'}
+        raw = b'Message-ID: <pre@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        res = target.import_message(raw, ['MyLabel', 'UNREAD'], initial_labels=['INBOX'])
+
+        assert res == {'id': 'existing-msg'}
+        service.users().messages().import_.assert_not_called()
+        # Initial label INBOX was skipped, UNREAD was omitted, only MyLabel was added
+        service.users().messages().modify.assert_called_once_with(
+            userId='me', id='existing-msg', body={'addLabelIds': ['Label_123']}
+        )
+
+    def test_http_403_scope_error_translation(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """HTTP 403 with ACCESS_TOKEN_SCOPE_INSUFFICIENT translates to InsufficientScopesError."""
+        target, service = gmail_labels
+        service.users().messages().import_().execute.side_effect = http_error(
+            403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+        )
+
+        with pytest.raises(InsufficientScopesError):
+            target.import_message(b'Test', ['INBOX'])
+
+    def test_http_401_auth_error_translation(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """HTTP 401 translates to AuthenticationError when can_reauthenticate is True."""
+        target, service = gmail_labels
+        target.creds = MagicMock(spec=OAuthFileCredentials)
+        service.users().messages().import_().execute.side_effect = http_error(401, b'Unauthorized')
+
+        with pytest.raises(AuthenticationError):
+            target.import_message(b'Test', ['INBOX'])
+
+    def test_pre_existing_empty_modify_labels_caches_empty_applied_set(
+        self, gmail_labels: tuple[GmailTarget, MagicMock]
+    ) -> None:
+        """Skipping pre-existing message with no non-UNREAD labels leaves UNREAD uncached."""
+        target, service = gmail_labels
+        target.requires_modify = True
+        service.users().messages().list.return_value.execute.return_value = {'messages': [{'id': 'existing-msg'}]}
+        service.users().messages().modify.return_value.execute.return_value = {'id': 'existing-msg'}
+        raw = b'Message-ID: <pre2@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        res1 = target.import_message(raw, ['UNREAD'], initial_labels=['INBOX'])
+        assert res1 == {'id': 'existing-msg', 'skipped': True}
+        assert target._imported_msgids['pre2@example.com'] == ('existing-msg', set(), False)
+        service.users().messages().modify.assert_not_called()
+
+        res2 = target.import_message(raw, ['MyLabel', 'UNREAD'])
+        assert res2 == {'id': 'existing-msg'}
+        service.users().messages().modify.assert_called_once_with(
+            userId='me', id='existing-msg', body={'addLabelIds': ['Label_123']}
+        )
+
+    def test_intra_pull_non_modify_fallthrough_preserves_prior_applied_labels(
+        self, gmail_labels: tuple[GmailTarget, MagicMock]
+    ) -> None:
+        """Falling through to import_ without modify unions prior applied labels in cache."""
+        target, service = gmail_labels
+        target.requires_modify = False
+        service.users().messages().import_.return_value.execute.return_value = {'id': 'msg-1'}
+        raw = b'Message-ID: <cross@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        target.import_message(raw, ['INBOX', 'MyLabel'])
+        target.import_message(raw, ['UNREAD'])
+        res3 = target.import_message(raw, ['INBOX'])
+
+        assert res3 == {'id': 'msg-1', 'skipped': True}
+        assert service.users().messages().import_.call_count == 2
+        assert target._imported_msgids['cross@example.com'] == ('msg-1', {'INBOX', 'Label_123', 'UNREAD'}, True)
+
+    def test_reauthenticate_clears_dedup_cache(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """GmailTarget.reauthenticate() clears _imported_msgids."""
+        target, service = gmail_labels
+        target.creds = MagicMock(spec=OAuthFileCredentials)
+        service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+        target.import_message(b'Message-ID: <reauth@example.com>\r\n\r\nBody', ['INBOX'])
+        assert target._imported_msgids
+
+        target.reauthenticate()
+        assert target._imported_msgids == {}
+
+    def test_connect_probes_messages_list_only_when_requires_modify(
+        self, gmail_labels: tuple[GmailTarget, MagicMock]
+    ) -> None:
+        """connect() probes messages().list() only when requires_modify is True."""
+        target, service = gmail_labels
+        with patch('korgalore.gmail_target.build', return_value=service):
+            target.service = None
+            target.connect()
+            service.users().labels().list.assert_called_once_with(userId='me')
+            service.users().messages().list.assert_not_called()
+
+            target.service = None
+            target._label_map = None
+            target.requires_modify = True
+            target.connect()
+            service.users().messages().list.assert_called_once()
+
+    def test_http_403_scope_error_action_by_credential_type(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """HTTP 403 insufficient scope message tailors remediation to credential type."""
+        target, service = gmail_labels
+        target.requires_modify = True
+        service.users().messages().list().execute.side_effect = http_error(
+            403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+        )
+
+        with patch('korgalore.gmail_target.build', return_value=service):
+            target.creds = MagicMock(spec=OAuthFileCredentials)
+            target.creds.interactive = False
+            target.service = None
+            with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+                target.connect()
+            assert target.service is None
+
+            target.creds = MagicMock(spec=OAuthFileCredentials)
+            target.creds.interactive = True
+            target.service = None
+            with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+                target.connect()
+            assert target.service is None
+            target.creds.reauthenticate.assert_called_once()
+
+            target.creds = CommandCredentials('test', ['echo', 'tok'])
+            target.service = None
+            with pytest.raises(InsufficientScopesError, match='token_command'):
+                target.connect()
+            assert target.service is None
+
+    def test_connect_scope_probe_403_interactive_reauth_retries_and_succeeds(
+        self, gmail_labels: tuple[GmailTarget, MagicMock]
+    ) -> None:
+        """connect() catches InsufficientScopesError, reauthenticates, and retries once."""
+        target, _ = gmail_labels
+        target.requires_modify = True
+        creds = MagicMock(spec=OAuthFileCredentials)
+        creds.interactive = True
+        creds.valid = True
+        target.creds = creds
+        target.service = None
+
+        service1 = MagicMock()
+        service1.users().labels().list().execute.return_value = {'labels': []}
+        service1.users().messages().list().execute.side_effect = http_error(
+            403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+        )
+
+        service2: Any = MagicMock()
+        service2.users().labels().list().execute.return_value = {'labels': [{'id': 'INBOX', 'name': 'INBOX'}]}
+        service2.users().messages().list().execute.return_value = {'messages': []}
+
+        with patch('korgalore.gmail_target.build', side_effect=[service1, service2]):
+            target.connect()
+
+        creds.reauthenticate.assert_called_once()
+        assert target.service is service2
+        assert target._label_map == {'INBOX': 'INBOX'}
+
+    def test_label_names_mapping(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+        """_label_names maps label IDs back to human-readable names."""
+        target, _ = gmail_labels
+        assert target._label_names(['INBOX', 'Label_123', 'UNKNOWN']) == ['INBOX', 'MyLabel', 'UNKNOWN']
+        assert target._label_names([]) == []
+
+    def test_import_and_modify_debug_logging(
+        self,
+        gmail_labels: tuple[GmailTarget, MagicMock],
+        caplog: pytest.LogCaptureFixture,
+    ) -> None:
+        """import_message logs human-readable label names for imports and modifications."""
+        target, service = gmail_labels
+        target.requires_modify = True
+        service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+        service.users().messages().modify().execute.return_value = {'id': 'msg-1'}
+
+        raw = b'Message-ID: <test-log@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+        with caplog.at_level(logging.DEBUG, logger='korgalore'):
+            # Path 1: Initial import (message not in Gmail yet)
+            service.users().messages().list().execute.return_value = {'messages': []}
+            target.import_message(raw, ['INBOX'], initial_labels=['MyLabel'])
+            assert "Importing message test-log@example.com to Gmail with labels: ['INBOX', 'MyLabel']" in caplog.text
+
+            caplog.clear()
+            # Path 2: Same-pull duplicate with new label
+            target.import_message(raw, ['UNREAD'])
+            assert "Adding Gmail labels ['UNREAD'] to duplicate message test-log@example.com (msg-1)" in caplog.text
+
+            caplog.clear()
+            # Path 3: Pre-existing message
+            service.users().messages().list().execute.return_value = {'messages': [{'id': 'msg-pre'}]}
+            service.users().messages().modify().execute.return_value = {'id': 'msg-pre'}
+            raw_pre = b'Message-ID: <pre-exist@example.com>\r\nSubject: Old\r\n\r\nBody'
+            target.import_message(raw_pre, ['MyLabel'], initial_labels=['INBOX'])
+            assert "Adding Gmail labels ['MyLabel'] to existing message pre-exist@example.com (msg-pre)" in caplog.text
+
+    def test_requires_modify_with_never_mark_spam_and_404_fallback(self) -> None:
+        """import_message forwards internalDateSource/neverMarkSpam on 404 fallback, not on modify."""
+        target, _ = make_target(message_date='import', never_mark_spam=True, requires_modify=True)
+        service = MagicMock()
+        target.service = service
+        target._label_map = {'INBOX': 'INBOX', 'MyLabel': 'Label_123'}
+        messages = service.users.return_value.messages.return_value
+
+        raw_existing = b'Message-ID: <existing@example.com>\r\nSubject: Hi\r\n\r\nBody'
+        messages.list.return_value.execute.return_value = {'messages': [{'id': 'msg-existing'}]}
+        messages.modify.return_value.execute.return_value = {'id': 'msg-existing'}
+
+        res_existing = target.import_message(raw_existing, ['MyLabel'], initial_labels=['INBOX'])
+
+        assert res_existing == {'id': 'msg-existing'}
+        messages.modify.assert_called_once_with(userId='me', id='msg-existing', body={'addLabelIds': ['Label_123']})
+        messages.import_.assert_not_called()
+
+        # Pre-existing message vanishes before modify() -> falls back to import_()
+        raw_vanished = b'Message-ID: <vanished@example.com>\r\nSubject: Gone\r\n\r\nBody'
+        messages.list.return_value.execute.return_value = {'messages': [{'id': 'msg-gone'}]}
+        messages.modify.return_value.execute.side_effect = http_error(404, b'Not Found')
+        messages.import_.return_value.execute.return_value = {'id': 'msg-reimported'}
+
+        res = target.import_message(raw_vanished, ['MyLabel'], initial_labels=['INBOX'])
+
+        assert res == {'id': 'msg-reimported'}
+        messages.modify.assert_called_with(userId='me', id='msg-gone', body={'addLabelIds': ['Label_123']})
+        assert messages.modify.call_count == 2
+        import_kwargs = messages.import_.call_args[1]
+        assert import_kwargs['internalDateSource'] == 'receivedTime'
+        assert import_kwargs['neverMarkSpam'] is True
+        assert import_body(service)['labelIds'] == ['Label_123', 'INBOX']
diff --git a/tests/test_google_creds.py b/tests/test_google_creds.py
index 7907feb..4d3c8ae 100644
--- a/tests/test_google_creds.py
+++ b/tests/test_google_creds.py
@@ -2,16 +2,18 @@
 
 import os
 import subprocess
+from collections.abc import Sequence
 from pathlib import Path
 from unittest.mock import MagicMock, patch
 
 import pytest
 from google.auth.exceptions import RefreshError
 
-from korgalore import AuthenticationError, ConfigurationError, RemoteError
+from korgalore import AuthenticationError, ConfigurationError, InsufficientScopesError, RemoteError
 from korgalore.google_creds import (
     CommandCredentials,
     OAuthFileCredentials,
+    default_scope_checker,
     parse_token_command,
     run_token_command,
 )
@@ -254,6 +256,219 @@ class TestOAuthFileCredentials:
             provider.refresh()
         assert not provider.valid
 
+    def test_stored_token_insufficient_scopes_raises(self, tmp_path: Path) -> None:
+        """Non-interactive OAuthFileCredentials raises InsufficientScopesError when scopes missing."""
+        token = tmp_path / 'token.json'
+        token.write_text('{}')
+        mock_creds = MagicMock()
+        mock_creds.valid = True
+        mock_creds.scopes = ['https://example.invalid/scope.a']
+
+        with patch('korgalore.google_creds.Credentials') as mock_c:
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(tmp_path / 'creds.json'),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=False,
+            )
+            with pytest.raises(InsufficientScopesError):
+                provider.refresh()
+
+    def test_default_scope_checker_and_custom_checker(self, tmp_path: Path) -> None:
+        """Default checker validates normalized subsets and custom checkers override it."""
+        assert default_scope_checker(
+            ['https://example.invalid/scope.a/', 'https://example.invalid/scope.b'], TEST_SCOPES
+        )
+        assert default_scope_checker(None, TEST_SCOPES)
+        assert not default_scope_checker(['https://example.invalid/scope.a'], TEST_SCOPES)
+
+        token = tmp_path / 'token.json'
+        token.write_text('{}')
+        mock_creds = MagicMock()
+        mock_creds.valid = True
+        mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+        called: list[tuple[object, list[str]]] = []
+
+        def custom_checker(granted: object, required: Sequence[str]) -> bool:
+            called.append((granted, list(required)))
+            return True
+
+        with patch('korgalore.google_creds.Credentials') as mock_c:
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(tmp_path / 'creds.json'),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=False,
+                scope_checker=custom_checker,
+            )
+            provider.refresh()
+            assert provider.valid
+
+        assert called == [
+            (['https://example.invalid/scope.a'], TEST_SCOPES),
+            (['https://example.invalid/scope.a'], TEST_SCOPES),
+        ]
+
+    def test_oauth_file_credentials_interactive_property(self, tmp_path: Path) -> None:
+        """interactive property exposes configured interactivity."""
+        p_yes = OAuthFileCredentials(
+            'test', str(tmp_path / 'c.json'), str(tmp_path / 't.json'), scopes=TEST_SCOPES, interactive=True
+        )
+        assert p_yes.interactive is True
+        p_no = OAuthFileCredentials(
+            'test', str(tmp_path / 'c.json'), str(tmp_path / 't.json'), scopes=TEST_SCOPES, interactive=False
+        )
+        assert p_no.interactive is False
+
+    def test_refresh_interactive_lacks_scopes_reauthenticates(self, tmp_path: Path) -> None:
+        """Interactive refresh calls reauthenticate when loaded token lacks scopes."""
+        creds_file = tmp_path / 'creds.json'
+        creds_file.write_text('{}')
+        token = tmp_path / 'token.json'
+        token.write_text('{}')
+        mock_creds = MagicMock()
+        mock_creds.valid = True
+        mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+        with (
+            patch('korgalore.google_creds.Credentials') as mock_c,
+            patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+        ):
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(creds_file),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=True,
+            )
+            provider.refresh()
+            mock_reauth.assert_called_once()
+
+    def test_refresh_non_interactive_lacks_scopes_raises(self, tmp_path: Path) -> None:
+        """Non-interactive refresh raises InsufficientScopesError when loaded token lacks scopes."""
+        creds_file = tmp_path / 'creds.json'
+        creds_file.write_text('{}')
+        token = tmp_path / 'token.json'
+        token.write_text('{}')
+        mock_creds = MagicMock()
+        mock_creds.valid = True
+        mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+        with (
+            patch('korgalore.google_creds.Credentials') as mock_c,
+            patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+        ):
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(creds_file),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=False,
+            )
+            with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+                provider.refresh()
+            mock_reauth.assert_not_called()
+            assert provider.needs_auth
+
+    def test_refresh_partial_granted_scopes_raises_when_non_interactive(self, tmp_path: Path) -> None:
+        """Partial granted_scopes after token refresh raises when non-interactive."""
+        creds_file = tmp_path / 'creds.json'
+        creds_file.write_text('{}')
+        token = tmp_path / 'token.json'
+        token.write_text('{"original": true}')
+        mock_creds = MagicMock()
+        mock_creds.valid = False
+        mock_creds.refresh_token = 'rtok'
+        mock_creds.scopes = TEST_SCOPES
+        mock_creds.granted_scopes = TEST_SCOPES
+
+        def partial_refresh(req: object) -> None:
+            mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+        mock_creds.refresh.side_effect = partial_refresh
+
+        with patch('korgalore.google_creds.Credentials') as mock_c:
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(creds_file),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=False,
+            )
+            with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+                provider.refresh()
+        assert provider.needs_auth
+        assert token.read_text() == '{"original": true}'
+
+    def test_refresh_partial_granted_scopes_reauthenticates_when_interactive(self, tmp_path: Path) -> None:
+        """Partial granted_scopes after token refresh reauthenticates when interactive."""
+        creds_file = tmp_path / 'creds.json'
+        creds_file.write_text('{}')
+        token = tmp_path / 'token.json'
+        token.write_text('{"original": true}')
+        mock_creds = MagicMock()
+        mock_creds.valid = False
+        mock_creds.refresh_token = 'rtok'
+        mock_creds.scopes = TEST_SCOPES
+        mock_creds.granted_scopes = TEST_SCOPES
+
+        def partial_refresh(req: object) -> None:
+            mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+        mock_creds.refresh.side_effect = partial_refresh
+
+        with (
+            patch('korgalore.google_creds.Credentials') as mock_c,
+            patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+        ):
+            mock_c.from_authorized_user_file.return_value = mock_creds
+            provider = OAuthFileCredentials(
+                'test',
+                str(creds_file),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=True,
+            )
+            provider.refresh()
+            mock_reauth.assert_called_once()
+        assert token.read_text() == '{"original": true}'
+
+    def test_reauthenticate_partial_consent_raises_without_saving(self, tmp_path: Path) -> None:
+        """Partial browser consent raises InsufficientScopesError before saving token."""
+        creds_file = tmp_path / 'creds.json'
+        creds_file.write_text('{}')
+        token = tmp_path / 'token.json'
+        token.write_text('{"old": true}')
+
+        partial_creds = MagicMock()
+        partial_creds.granted_scopes = ['https://example.invalid/scope.a']
+        mock_flow = MagicMock()
+        mock_flow.run_local_server.return_value = partial_creds
+
+        with patch(
+            'korgalore.google_creds.InstalledAppFlow.from_client_secrets_file', return_value=mock_flow
+        ) as mock_fc:
+            provider = OAuthFileCredentials(
+                'test',
+                str(creds_file),
+                token,
+                scopes=TEST_SCOPES,
+                interactive=True,
+            )
+            with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+                provider.reauthenticate()
+            mock_fc.assert_called_once_with(str(creds_file), TEST_SCOPES)
+        assert provider.needs_auth
+        assert provider._creds is None
+        assert token.read_text() == '{"old": true}'
+
 
 class TestOAuthFileCredentialsRefresh:
     """Tests for refresh(), which runs long after the constructor.
diff --git a/tests/test_jmap_target.py b/tests/test_jmap_target.py
index 520cf94..3bdfe69 100644
--- a/tests/test_jmap_target.py
+++ b/tests/test_jmap_target.py
@@ -392,9 +392,15 @@ class TestJmapTargetImportMessage:
         mock_post.side_effect = [
             upload_response(),
             import_response({'notCreated': {'msg1': {'type': 'alreadyExists', 'existingId': 'existing-789'}}}),
+            json_response({'methodResponses': []}),
         ]
 
         assert jmap_mailboxes.import_message(b'Test', ['inbox']) == {'id': 'existing-789'}
+        assert mock_post.call_count == 3
+        # Third call should be Email/set adding the mailbox
+        set_call = mock_post.call_args_list[2][1]['json']
+        assert set_call['methodCalls'][0][0] == 'Email/set'
+        assert set_call['methodCalls'][0][1]['update']['existing-789'] == {'mailboxIds/mb-1': True}
 
     @pytest.mark.parametrize(
         ('import_result', 'message'),
@@ -495,3 +501,155 @@ class TestJmapTargetDeduplication:
 
         assert result == {'id': 'new-email-id'}
         assert mock_post.call_count == 2  # upload + import only
+
+
+class TestJmapIntraPullDedup:
+    """Tests for JmapTarget per-pull session cache."""
+
+    def test_intra_pull_dedup_skips_duplicate(self, jmap_mailboxes: JmapTarget, mock_post: MagicMock) -> None:
+        """Second delivery of same Message-ID in same pull with same folder makes 0 HTTP calls."""
+        mock_post.side_effect = [query_response([]), upload_response(), created('email-1')]
+        raw = b'From: a@b.com\r\nMessage-ID: <test@example.com>\r\n\r\nBody'
+
+        res1 = jmap_mailboxes.import_message(raw, ['inbox'])
+        assert res1 == {'id': 'email-1'}
+        assert mock_post.call_count == 3
+
+        # Second delivery of same message with same folder
+        res2 = jmap_mailboxes.import_message(raw, ['inbox'])
+        assert res2 == {'id': 'email-1', 'skipped': True}
+        assert mock_post.call_count == 3  # No additional HTTP calls
+
+    def test_intra_pull_dedup_adds_missing_mailbox(self, jmap_mailboxes: JmapTarget, mock_post: MagicMock) -> None:
+        """Second delivery of same Message-ID in same pull with new folder calls Email/set."""
+        mock_post.side_effect = [
+            query_response([]),
+            upload_response(),
+            created('email-1'),
+            json_response({'methodResponses': []}),
+        ]
+        raw = b'From: a@b.com\r\nMessage-ID: <test@example.com>\r\n\r\nBody'
+
+        jmap_mailboxes.import_message(raw, ['inbox'])
+        res2 = jmap_mailboxes.import_message(raw, ['inbox', 'archive'])
+
+        assert res2 == {'id': 'email-1', 'modified': True}
+        assert mock_post.call_count == 4
+        # Fourth call is Email/set adding mb-3 (archive)
+        set_call = mock_post.call_args_list[3][1]['json']
+        assert set_call['methodCalls'][0][0] == 'Email/set'
+        assert set_call['methodCalls'][0][1]['update']['email-1'] == {'mailboxIds/mb-3': True}
+
+    def test_cross_pull_preexisting_archived_message_skips_initial_labels(
+        self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+    ) -> None:
+        """Archived account-wide message gets only literal folders, skipping initial_labels and upload."""
+        mock_post.side_effect = [
+            query_response([]),  # _check_message_exists in mb-3 (archive): not there
+            query_response(['existing-archived']),  # _find_existing_message account-wide: found
+            json_response({'methodResponses': [['Email/set', {'updated': {'existing-archived': None}}, 'call-set']]}),
+        ]
+        raw = b'From: a@b.com\r\nMessage-ID: <arch@example.com>\r\n\r\nBody'
+
+        res1 = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+        assert res1 == {'id': 'existing-archived', 'modified': True}
+        assert mock_post.call_count == 3
+        query_call = mock_post.call_args_list[1][1]['json']['methodCalls'][0][1]
+        assert query_call['filter'] == {'header': ['Message-ID', '<arch@example.com>']}
+        set_call = mock_post.call_args_list[2][1]['json']['methodCalls'][0][1]
+        assert set_call['update'] == {'existing-archived': {'mailboxIds/mb-3': True}}
+
+        # Same message delivered again in same pull with ['archive'] makes 0 HTTP calls
+        res2 = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+        assert res2 == {'id': 'existing-archived', 'skipped': True}
+        assert mock_post.call_count == 3
+
+    def test_cross_pull_preexisting_not_found_falls_back_to_import(
+        self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+    ) -> None:
+        """If account-wide Email/set returns notFound, import_message falls back to upload+import."""
+        mock_post.side_effect = [
+            query_response([]),
+            query_response(['vanished-id']),
+            json_response(
+                {
+                    'methodResponses': [
+                        ['Email/set', {'notUpdated': {'vanished-id': {'type': 'notFound'}}}, 'call-set'],
+                    ]
+                }
+            ),
+            upload_response('blob-fallback'),
+            created('new-id'),
+        ]
+        raw = b'From: a@b.com\r\nMessage-ID: <vanish@example.com>\r\n\r\nBody'
+
+        res = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+        assert res == {'id': 'new-id'}
+        assert mock_post.call_count == 5
+        import_call = mock_post.call_args_list[4][1]['json']['methodCalls'][0][1]
+        assert import_call['emails']['msg1']['mailboxIds'] == {'mb-3': True, 'mb-1': True}
+
+    def test_intra_pull_add_mailboxes_not_found_falls_back_to_import(
+        self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+    ) -> None:
+        """If cached intra-pull Email/set returns notFound, cache is dropped and upload+import runs."""
+        mock_post.side_effect = [
+            query_response([]),
+            upload_response('blob-1'),
+            created('email-1'),
+            json_response(
+                {'methodResponses': [['Email/set', {'notUpdated': {'email-1': {'type': 'notFound'}}}, 'call-set']]}
+            ),
+            query_response([]),
+            upload_response('blob-2'),
+            created('email-2'),
+        ]
+        raw = b'From: a@b.com\r\nMessage-ID: <gone@example.com>\r\n\r\nBody'
+
+        jmap_mailboxes.import_message(raw, ['inbox'])
+        res2 = jmap_mailboxes.import_message(raw, ['archive'])
+        assert res2 == {'id': 'email-2'}
+        assert jmap_mailboxes._imported_msgids['gone@example.com'][0] == 'email-2'
+
+    @pytest.mark.parametrize(
+        'response_or_exc',
+        [
+            requests.RequestException('boom'),
+            json_response({'methodResponses': [['error', {'type': 'serverFail'}, 'call-set']]}),
+            json_response(
+                {'methodResponses': [['Email/set', {'notUpdated': {'e1': {'type': 'forbidden'}}}, 'call-set']]}
+            ),
+        ],
+        ids=['http-error', 'jmap-error', 'not-updated'],
+    )
+    def test_add_mailboxes_errors_raise_remote_error(
+        self, jmap_mailboxes: JmapTarget, mock_post: MagicMock, response_or_exc: Any
+    ) -> None:
+        """_add_mailboxes raises RemoteError on transport, JMAP error, or non-notFound failures."""
+        if isinstance(response_or_exc, Exception):
+            mock_post.side_effect = response_or_exc
+        else:
+            mock_post.return_value = response_or_exc
+
+        with pytest.raises(RemoteError):
+            jmap_mailboxes._add_mailboxes('e1', ['mb-1'])
+
+    @pytest.mark.parametrize(
+        'response_or_exc',
+        [
+            requests.RequestException('boom'),
+            json_response({'methodResponses': [['error', {'type': 'serverFail'}, 'call-0']]}),
+        ],
+        ids=['http-error', 'jmap-error'],
+    )
+    def test_find_existing_message_errors_raise_remote_error(
+        self, jmap_mailboxes: JmapTarget, mock_post: MagicMock, response_or_exc: Any
+    ) -> None:
+        """_find_existing_message fails closed with RemoteError on HTTP or JMAP error."""
+        if isinstance(response_or_exc, Exception):
+            mock_post.side_effect = response_or_exc
+        else:
+            mock_post.return_value = response_or_exc
+
+        with pytest.raises(RemoteError):
+            jmap_mailboxes._find_existing_message('<msg@example.com>')
diff --git a/tests/test_pull.py b/tests/test_pull.py
index ef11859..910eb1e 100644
--- a/tests/test_pull.py
+++ b/tests/test_pull.py
@@ -8,6 +8,7 @@ exits with status 3 at the end when any feed failed to update. Delivery
 failures don't count.
 """
 
+import logging
 from collections.abc import Iterator
 from datetime import UTC, datetime
 from pathlib import Path
@@ -625,3 +626,32 @@ class TestRetryNoopDoesNotRewindPointer:
 
         assert result == SKIPPED_NOOP_COMMIT
         feed.mark_successful_delivery.assert_called_once_with('test-delivery', 0, 'abc123', was_failing=True)
+
+
+class TestDeliverCommitDebugLogging:
+    """Tests for deliver_commit DEBUG level logging."""
+
+    def test_deliver_commit_logs_labels(self, caplog: pytest.LogCaptureFixture) -> None:
+        """deliver_commit logs subject and labels when DEBUG is enabled."""
+        feed = MagicMock()
+        feed.is_noop_commit.return_value = False
+        feed.get_message_at_commit.return_value = b'Subject: Test Subject\nMessage-ID: <m1@example.com>\n\nBody'
+        target = MagicMock()
+
+        with caplog.at_level(logging.DEBUG, logger='korgalore'):
+            deliver_commit('test-delivery', target, feed, 0, 'abc123', ['inbox', 'review'])
+
+        assert ' -> Test Subject (labels: inbox, review)' in caplog.text
+
+    def test_deliver_commit_logs_without_labels_when_empty(self, caplog: pytest.LogCaptureFixture) -> None:
+        """deliver_commit logs only subject when no labels are specified."""
+        feed = MagicMock()
+        feed.is_noop_commit.return_value = False
+        feed.get_message_at_commit.return_value = b'Subject: Test Subject\nMessage-ID: <m1@example.com>\n\nBody'
+        target = MagicMock()
+
+        with caplog.at_level(logging.DEBUG, logger='korgalore'):
+            deliver_commit('test-delivery', target, feed, 0, 'abc123', [])
+
+        assert ' -> Test Subject' in caplog.text
+        assert 'labels:' not in caplog.text

-- 
2.56.1.987.g2ec0ab4260-goog


  parent reply	other threads:[~2026-12-05  6:56 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-05  6:56 [PATCH kgl 0/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
2026-12-05  6:56 ` [PATCH kgl 1/4] Disable interactive OAuth flows when stdin is not a terminal Dmitry Torokhov
2026-12-05  6:56 ` [PATCH kgl 2/4] Defer Gmail OAuth loading until delivery and isolate target failures Dmitry Torokhov
2026-12-05  6:56 ` Dmitry Torokhov [this message]
2026-12-05  6:56 ` [PATCH kgl 4/4] Add conditional initial-arrival delivery rules Dmitry Torokhov

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261204-delivery-rules-v1-3-80af76016200@gmail.com \
    --to=dmitry.torokhov@gmail.com \
    --cc=konstantin@linuxfoundation.org \
    --cc=tools@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox