Enterprise agent platform for building, deploying, and operating AI teammates.
feat(connectors): add the Google Drive write check and its sweep (#3752)
Q1hangL523699b39047
diff --git a/docs/operations/connector-smoke-v2.md b/docs/operations/connector-smoke-v2.mdindex 2183c2736..176394dc5 100644--- a/docs/operations/connector-smoke-v2.md+++ b/docs/operations/connector-smoke-v2.md@@ -115,10 +115,10 @@ ConnectorChecks(Validation enforces these:- **Steps.** Every step of a write check (`create`, `verify`, `cleanup`, `cleanup_guard`) and of a sweep (`find`, `delete`) needs at least one assertion. A tenant pin's read, a cleanup guard and the sweep are not checked tools: they do not count as a check of their tool.-- **Tenant pin.** The pin's step reads the connection's tenant id at `path`; `expected` is the registry's id (a fixture key). Every tenant pin of a connector, its sweep's included, names the same fixture key. A path, here and in an assertion, is a tuple.-- **Write area.** `create`, and the sweep's `find`, take at least one write-area fixture key, `<app_id>.write_...`: `jira.write_project_key` above, or `google-drive.write_folder_id`. It names the isolated container the tenant registry (xorbitsai/xagent-saas#2533) sets aside for the connector's write checks. Its namespace is the connector's, which can differ from the pin's (`google.tenant_id`).+- **Tenant pin.** The pin's step reads, at `path`, a value only this tenant's account has: the vendor's tenant id where the connector's tools return it, as Jira's site listing does, or the id of the tenant's own write-area container, which the seed keeps unshared so no other account's read finds it (Drive's `google-drive.write_folder_id`, as #3567 decides). `expected` is that value in the registry (a fixture key). Every tenant pin of a connector, its sweep's included, names the same fixture key. A path, here and in an assertion, is a tuple.+- **Write area.** `create`, and the sweep's `find`, take at least one write-area fixture key, `<app_id>.write_...`: `jira.write_project_key` above, or `google-drive.write_folder_id`. It names the isolated container the tenant registry (xorbitsai/xagent-saas#2533) sets aside for the connector's write checks. Its namespace is the connector's; the pin's key can be a tenant-level key in another namespace (`google.tenant_id`) or, as in Drive's check, the write-area container in the connector's.- **Run-scoped name.** `create` names its object with a `RunScopedName`, which the engine fills in as `xagent-smoke-<run_id>-<suffix>`. No two write checks of a connector use the same suffix, so in one run a name matches one check's object.-- **Cleanup.** `cleanup`'s arguments name the run's object: by the `RunScopedName` that `create` gave it, or by a `CreatedRef` (the value at a path of the create step's payload, typically the id the vendor gave the new object). They take no fixture key but the tenant pin's and write-area keys, so no seeded object outside the write area is the target. A cleanup with neither reference, with another run-scoped name or with another fixture key is refused.+- **Cleanup.** `cleanup`'s arguments name the run's object: by the `RunScopedName` that `create` gave it, or by a `CreatedRef` (the value at a path of the create step's payload, typically the id the vendor gave the new object). They take no fixture key but the tenant pin's and write-area keys, so no seeded object outside the write area is the target. A pin may name the write-area container itself, as Drive's does, so that allowance adds no key outside it. A cleanup with neither reference, with another run-scoped name or with another fixture key is refused.- **Cleanup guard.** A cleanup that deletes by a `CreatedRef` needs a `cleanup_guard`, and no other cleanup has one. The guard's arguments carry the same reference and no run-scoped name, and its `Equals` asserts the `RunScopedName` that `create` gave the object. Its fixture keys are limited as cleanup's are.- **Read steps.** Read checks, `verify`, every tenant pin's step, the cleanup guard and the sweep's `find` only read: none may call a tool that any of the connector's write checks creates or cleans up with.- **Approval verdict.** `expected_verdicts` gives, for exactly the `create` and `cleanup` tools, the verdict the deployment's write policy gives a restricted actor (`allow`, `require_approval`, `deny`): for Toby, `deny` when the tool is withheld from a non-installer member. A change to Toby's write classification can therefore turn a check declared here red until its declaration follows; that is intended.@@ -127,7 +127,7 @@ Validation enforces these:At run time (see [Running write checks](#running-write-checks)):-- The pin runs before any write, and a tenant id that differs from the registry's refuses the write.+- The pin runs before any write, and a value that differs from the registry's refuses the write.- The probe path bypasses both the approval gate and the per-user tool overrides, so the engine compares each declared verdict with the identity's write policy before any call.- Cleanup runs even when verify fails, which is why the guard belongs to cleanup and not to verify. The guard's `Equals` compares the whole run-scoped name.- The sweeper (see [The sweeper](#the-sweeper)) lists only the write area, so an object created outside it would never be swept. It matches each item's name against `xagent-smoke-` and reads the object's age from it.@@ -135,13 +135,15 @@ At run time (see [Running write checks](#running-write-checks)):Review each write flow against these, which validation cannot check:- Cleanup and sweep use the connector's own tools, so a connector whose server cannot delete what its write check creates declares no write check until its Tier 1 issue settles how to clean up. Today that includes the HubSpot MCP server, which has no delete tool (#3572), the in-repo GitHub server (#3568), Slack's messages (#3743, split from its Tier 1 issue #3571), Gmail's drafts (#3567) and Teams' messages (#3569).-- The sweep's `find` lists the same container `create` writes into. Jira's search takes only JQL, so its sweep reads a query fixture rather than the project key `create` takes.+- The sweep's `find` lists the same container `create` writes into. Jira's search takes only JQL, and Drive's takes the whole query, so their sweeps read a query fixture rather than the project key or the folder id `create` takes.- Each step's target comes from its reference or a write-area fixture, never from a literal, or from the pin's key, next to one: validation sees that a reference is present, not which argument the tool treats as its target.- The cleanup guard finds the object by its `CreatedRef` alone, not by a query fixture or a literal that sits next to it. Only then does it catch a wrongly declared path before anything is deleted.+- A write check reads the object it created back, not where that object sits: `verify` and the guard read it back by the id it created and assert its run-scoped name; the Drive check's `verify` asserts the file's content too, and no step reads the object's parents. Whether the object landed in the write area therefore rests on `create` passing the container: Drive's create sends it as `parent_id`, which reaches Composio's create tool as `parents` on a Composio grant, and no passing run shows the tool honoured it. Confirm that once by hand before writes are switched on, on the connection the runs use: call `google_drive_create_file` with `mime_type="text/plain"`, `parent_id` set to the write folder's id (`google-drive.write_folder_id`, the seed's `xagent-smoke-write` in the account's My Drive root), and a name that does not start with `xagent-smoke-`; check in Drive that the file is in that folder and not in the root, then delete it with `google_drive_delete_file`. A passing run cannot stand in for that: the check deletes the file it creates, so nothing is left to look at, and a run whose writes are off reports the check `skip`/`writes_disabled` without calling it. A file a create put in My Drive's root instead, such as one a failed cleanup or a lost create answer left, is one the sweep never lists.- Cleanup and the sweep's `delete` never target the write-area container itself, which is a seeded object too.- The sweep's `ItemRef` is the id of the item whose `name` the sweeper matched, not a parent's or a sibling's.- Every read step only reads. Validation refuses the connector's own create and cleanup tools there, not every tool that writes.- A pin over a list, such as Jira's sites, asserts that the list has exactly one item.+- A pin on the write-area container, rather than on a vendor tenant id, proves that the connection is the test account itself and that the container the create targets is that account's: the seed keeps the container unshared, so another account's search finds no folder of that name in its own My Drive root, and the id it does find has to be the registry's. The pin does not show where the file lands: that still rests on `create` passing the container through `parents`, which no step reads.- A cleanup that deletes by run-scoped name matches the whole name, never part of it: one suffix can begin another (`issue`, `issue-2`), and the engine passes the name to the tool as it is.- Gmail creates drafts and never sends.- Jira sets no assignee and no watcher.@@ -175,7 +177,7 @@ A path is a tuple of object keys and list indexes into the payload; `()` is the### Fixture keys-A fixture key is `<namespace>.<name>`, at most 80 characters: the namespace is kebab-case, by convention the app id of the connector or tenant family that owns the value, and the name is one or more dot-separated snake_case parts (`google-docs.document_id`, `jira.seed.project_key`). The identity adapter resolves keys from server-side configuration, per environment and identity (`fixtures.FixtureResolver`). An unresolved key reports the check as `skip` with `fixture_missing` and the key as the row's `reason`. Errors and results name the key, never its value. The document, Google, GitHub, Jira and Microsoft 365 connectors' read checks use these keys; the probe route does not take fixtures yet (#3284).+A fixture key is `<namespace>.<name>`, at most 80 characters: the namespace is kebab-case, by convention the app id of the connector or tenant family that owns the value, and the name is one or more dot-separated snake_case parts (`google-docs.document_id`, `jira.seed.project_key`). The identity adapter resolves keys from server-side configuration, per environment and identity (`fixtures.FixtureResolver`). An unresolved key reports a read check as `skip` with `fixture_missing` and the key as the row's `reason`; a write check or a sweep is refused as `fail` with `tenant_mismatch` and the key, and only after the write policy has answered for its tools (see [Running write checks](#running-write-checks)). Errors and results name the key, never its value. The document, Google, GitHub, Jira and Microsoft 365 connectors' read checks use these keys; the probe route does not take fixtures yet (#3284).### Today's L3 probes@@ -203,7 +205,9 @@ The six document connectors (`google-docs`, `google-sheets`, `google-slides`, `p`gmail`, `google-analytics`, `google-calendar`, `google-docs`, `google-drive`, `google-sheets` and `google-slides` have adopted V2 against the Google test tenant (#3567). Every read check but the probe-derived `l3_probe` is bound to a fixture key the tenant registry records for the seed layout: `gmail.seed_label_id` (the label's one seeded message), `google-drive.seed_folder_id` (the closed seed folder, found by a Drive search), `google-docs.document_id` (read directly, and again through Drive's text export), `google-sheets.spreadsheet_id` (the spreadsheet's one tab, and the seeded `item`/`quantity` block through `google_sheets_read_range`), `google-slides.presentation_id` (the deck's title and its one slide), and `google-analytics.property_id`. The checks assert the seed's own values where the seed pins one, such as the document's text `xagent smoke seed document`, the spreadsheet's `alpha`/`1` row and the deck's one slide, so a change to that seed is a change to the checks that read it. Assertions the seed does not pin are shape guards: a spreadsheet tab's `row_count` and `column_count` are Google's default grid, and an Analytics report's `rows` is an array. `google_analytics_run_report` returns no property field of GA's own: `query.property_id` is its normalization of the argument it was given, so no assertion reads it, and `google-analytics.property_id` must be a bare-digit string (`563334905`), the form the tenant registry records. `google-analytics` also runs its probe-derived `l3_probe`, which takes no fixture. `google-calendar` keeps only that check, because every Calendar tool addresses `primary`, while the seed's calendar is a secondary one, so no seeded event is reachable.-Every other Google tool is exempt: the reads outside the 80% cut; the writes, whose checks are decided with the write flows (#3567); the writes that create an object no tool of their server deletes (`google_docs_create_document`, `google_sheets_create_spreadsheet`, `google_slides_create_presentation`, `google_slides_import_pptx`, `gmail_send_messages`); and the in-place Docs edits (`google_docs_append_text`, `google_docs_replace_text`, `google_docs_batch_update`), which stay pending: a write check creates, verifies and deletes its own object and has no step for an edit, and the tenant registry sets aside no write-area document to edit. `google_slides_get_slide_thumbnail` is exempt because the tenant registry records no slide-id fixture: the deck the seed creates holds Google's default slide, but no fixture names it, and `gmail_manage_labels` is exempt because it is the only tool that reads a label and the only one that creates or deletes one, so a label write check's verify or cleanup guard would call its own create and cleanup tool (`#3653`); no separate label-reading tool is added.+Every other Google tool is exempt: the reads outside the 80% cut; the writes without a check, whose checks are decided with the write flows (#3567); the writes that create an object no tool of their server deletes (`google_docs_create_document`, `google_sheets_create_spreadsheet`, `google_slides_create_presentation`, `google_slides_import_pptx`, `gmail_send_messages`); and the in-place Docs edits (`google_docs_append_text`, `google_docs_replace_text`, `google_docs_batch_update`), which stay pending: a write check creates, verifies and deletes its own object and has no step for an edit, and the tenant registry sets aside no write-area document to edit. `google_slides_get_slide_thumbnail` is exempt because the tenant registry records no slide-id fixture: the deck the seed creates holds Google's default slide, but no fixture names it, and `gmail_manage_labels` is exempt because it is the only tool that reads a label and the only one that creates or deletes one, so a label write check's verify or cleanup guard would call its own create and cleanup tool (`#3653`); no separate label-reading tool is added.++`google-drive` adds the first Google write check (#3567). `google-drive.file_round_trip` creates `xagent-smoke-<run_id>-drive-file` in the tenant registry's write folder (`google-drive.write_folder_id`), reads it back with `google_drive_get_file_content` to confirm its run-scoped name and its content, and deletes it; the same read guards the cleanup, by name alone. Before any write, the tenant pin reads that write folder: Drive has no tool that returns the Workspace customer id, so #3567 pins the write check and its sweep to their own write-area container, which the seed keeps unshared so a connection to any other account cannot read it. The pin searches for it with the seed's own uniqueness rule — its name `xagent-smoke-write`, its folder type, `'root' in parents` and `trashed = false` — and requires the id it finds to be `google-drive.write_folder_id`, so a folder with that name elsewhere, such as in a shared drive, is not the write folder. Both verdicts are `allow`, because Toby withholds a write tool from a member only for a connector whose writes it classifies, and only Jira's are classified today; classifying Google's writes turns this check red until its declaration follows. Its sweep lists the write folder with `google-drive.write_sweep_query` and deletes leftovers by id. Running it needs `XAGENT_CONNECTOR_SMOKE_WRITE_APPS=google-drive`; an environment where the QA member's `google-drive` connection is enumerated (production-au today); the write side of xorbitsai/xagent-saas#2534: `write_policy_verdict`, without which the check is refused before its first call, and the sweep entry, without which the sweep is not scheduled; and a QA member whose Google connection can see the write folder: the seed makes its objects with the seed project's own OAuth client, not the connector's, and does not share them, so a `drive.file` grant, which sees only the objects the app created or the account picked with it, cannot reach them — sharing the folder in Drive does not add it to that grant, so a legacy `drive.file` connection has to be reconnected — while a full-Drive or Composio-backed connection can. On a Composio grant `google_drive_create_file` stages the content through Composio's Files API, has Composio's `GOOGLEDRIVE_CREATE_FILE` create the file from the staged object, and reads the new file back through the proxy: when that read answers, its checksum and size are compared with the staged content, and a read-back that fails for another reason leaves Composio's answer, the new file's id, as the result. Every step of the check keeps its tool name, and the reads and the delete are proxied Drive API calls.`onedrive`, `teams`, `word`, `excel` and `powerpoint` have adopted V2 against the Microsoft 365 test account (#3569), with read checks only. Every check but Teams' L3 row and four shape guards is bound to a fixture key the tenant registry records for the seed layout: the closed OneDrive folder `xagent-smoke-seed` (`onedrive.seed_folder_path`) holds exactly four files, the text note `xagent-smoke-seed-note-q7k2.txt` (`onedrive.seed_file_path`, here `xagent-smoke-seed/xagent-smoke-seed-note-q7k2.txt`, and `onedrive.seed_file_id`) and the Word, Excel and PowerPoint seed files (`word.file_path`, `excel.file_path`, `powerpoint.file_path`); the read team (`teams.seed_team_id`) has one channel (`teams.seed_channel_id`), which lists the seeded message (`teams.seed_message_id`) first. The Teams ids are strings, as Graph returns them: a message id is a string of digits, and `teams.seed_message_id` must be recorded as that string (`1731400000000`), not as a number, since `Equals` compares as JSON does. Graph orders a channel's messages by the last activity of each reply chain, most recently active first, and includes system messages, so the seeded message must stay the channel's most recently active thread. The checks assert the seed's own values: the folder's four items; the note, the only item a search for `q7k2` finds (the marker is in its name and in no other seeded file's name or content; the search spans the whole drive, so a future write check must not name or fill its objects with `q7k2`; whether Graph's search tokenizes `q7k2` out of the file name is confirmed on the seed's first run), read by id under its seeded name, and read by path to its exact text; the document's two paragraphs, `xagent smoke seed document` and `second seeded paragraph`; the workbook's one worksheet `seed`, its `item`/`quantity`, `alpha`/`1`, `beta`/`2` block (numbers as numbers) and its values-only used range `seed!A1:B3` (formatting outside the block does not widen it); the deck's one slide, whose one text box reads `xagent smoke seed presentation` and which has no speaker notes; the team's one channel and the id and text of the message it lists first. `onedrive_get_profile`, `auth_status`, `list_teams` and `list_chats` (`teams.list_chats`) take no fixture and are shape guards; the team list is only checked for at least one team, since the account also belongs to other teams, and the chat list passes when it is empty, since the seed cannot hold a chat. `teams` also keeps its probe-derived `teams.l3_probe` row, which calls `get_current_user` and takes no fixture: under the rule of #3568, an L3 row kept beside a connector's checks does not take one of its five read slots (#3569). OneDrive's checks replace its probe-derived `onedrive.l3_probe` row, which called `onedrive_get_profile`; the document connectors keep their `read_fixture` ids.@@ -274,7 +278,7 @@ Once its connector's session has passed, a write check is refused, without calliOtherwise it runs, each call under `check_timeout`:-1. **Pin.** The pin's step is called. A call that fails is `tenant_mismatch`/`pin_failed`, and a tenant id that is not the registry's is `tenant_mismatch`/`mismatch`.+1. **Pin.** The pin's step is called. A call that fails is `tenant_mismatch`/`pin_failed`, and a value that is not the registry's is `tenant_mismatch`/`mismatch`.2. **Create.** If the call raises, times out or returns an error, nothing is cleaned up: whatever it may have made is the sweeper's. If only an assertion fails, the object may exist, so cleanup still runs.3. **Verify** runs when create passed. Every `CreatedRef` reads create's payload; a step whose id is not there, or is not a non-empty string or a finite number, makes create `assertion_failed`/`create:created_ref_missing`, and a cleanup that would delete by that id is left to the sweeper.4. **Cleanup guard and cleanup** run whenever create returned something to clean up, including after a failed verify. The guard reads the object by its `CreatedRef` and must confirm its run-scoped name; if not, nothing is deleted and the row is `cleanup_failed`/`ownership` (`cleanup_failed`/`guard:<detail>` when the guard's call fails). A failed cleanup is `cleanup_failed`/`cleanup:<detail>`. Both calls run under their own call timeouts rather than the run's deadline, and finish even when the run is cancelled, which is re-raised afterwards.diff --git a/src/xagent/web/connector_checks/assertions.py b/src/xagent/web/connector_checks/assertions.pyindex 4a1386c44..8abdbd61b 100644--- a/src/xagent/web/connector_checks/assertions.py+++ b/src/xagent/web/connector_checks/assertions.py@@ -125,8 +125,8 @@ def resolve_expected(def value_at(raw: Any, payload: PayloadSource, path: PayloadPath) -> Any:"""The value at ``path`` in ``raw``'s ``payload``, or ``MISSING``.- A write check reads its tenant id and a created object's id this way. A- result that is not a mapping, is flagged ``is_error`` or has no such+ A write check reads its tenant pin's value and a created object's id this+ way. A result that is not a mapping, is flagged ``is_error`` or has no suchpayload holds no value."""if not isinstance(raw, Mapping) or raw.get("is_error"):diff --git a/src/xagent/web/connector_checks/declarations.py b/src/xagent/web/connector_checks/declarations.pyindex 083e6f862..21b020d5f 100644--- a/src/xagent/web/connector_checks/declarations.py+++ b/src/xagent/web/connector_checks/declarations.py@@ -255,8 +255,10 @@ class ToolStep:@dataclass(frozen=True)class TenantPin:- """Before any write, ``step`` reads the connection's tenant id at- ``path``; it must equal the registry's id, ``expected``."""+ """Before any write, ``step`` reads, at ``path``, a value only this+ tenant's account has: its tenant id where a tool of the connector returns+ one, or the id of the tenant's own write-area container, which the seed+ keeps unshared. It must equal the registry's value, ``expected``."""step: ToolSteppath: PayloadPathdiff --git a/src/xagent/web/connector_checks/registry.py b/src/xagent/web/connector_checks/registry.pyindex d846833ba..853ce9ecc 100644--- a/src/xagent/web/connector_checks/registry.py+++ b/src/xagent/web/connector_checks/registry.py@@ -638,6 +638,112 @@ def _teams_checks() -> ConnectorChecks:)+def _google_drive_write_checks() -> tuple[WriteCheck, Sweep]:+ """Google Drive's write check and sweep (#3567), sharing one tenant pin.++ Drive has no tool that returns the Workspace customer id, so #3567 pins+ the write check and the sweep to their own write-area container instead:+ the one folder the seed names ``xagent-smoke-write`` in the account's My+ Drive root and keeps unshared, which a connection to any other account+ therefore cannot read. The same read shows that the connection is the test+ account and that the container the create targets is that account's;+ whether the file lands there rests on the create's parent, which no step+ reads. The query is the seed's own uniqueness rule, so a folder with that+ name outside the root, such as one in a shared drive, does not make the pin+ fail. The check creates a text file in that folder, reads it back to+ confirm its run-scoped name and its content, and deletes it; the cleanup+ guard makes the same read but asserts the name alone, so content that did+ not land as sent does not keep the file from being deleted. The sweep lists+ the folder with the registry's query fixture, since Drive's search takes+ the whole query, and deletes leftovers by id.+ """+ pin = TenantPin(+ ToolStep(+ "google_drive_search",+ {+ "query": (+ "name = 'xagent-smoke-write' and "+ "mimeType = 'application/vnd.google-apps.folder' and "+ "'root' in parents and "+ "trashed = false"+ ),+ "max_results": 10,+ },+ assertions=(Length(("files",), 1, 1),),+ ),+ path=("files", 0, "id"),+ expected=FixtureRef("google-drive.write_folder_id"),+ )+ name = RunScopedName("drive-file")+ created = CreatedRef(("file", "id"))+ probe = "xagent smoke write probe"+ # The guard asserts the name alone, so a file whose content did not land+ # as sent is still deleted.+ guard = ToolStep(+ "google_drive_get_file_content",+ {"file_id": created},+ assertions=(StatusSuccess(), Equals(("file", "name"), name)),+ )+ write = WriteCheck(+ "google-drive.file_round_trip",+ create=ToolStep(+ "google_drive_create_file",+ {+ "name": name,+ "content": probe,+ "mime_type": "text/plain",+ "parent_id": FixtureRef("google-drive.write_folder_id"),+ },+ assertions=(StatusSuccess(), HasKeys(("file",), ("id",))),+ ),+ verify=ToolStep(+ "google_drive_get_file_content",+ {"file_id": created},+ assertions=(+ StatusSuccess(),+ Equals(("file", "name"), name),+ Equals(("content",), probe),+ ),+ ),+ cleanup=ToolStep(+ "google_drive_delete_file",+ {"file_id": created},+ assertions=(StatusSuccess(),),+ ),+ cleanup_guard=guard,+ tenant_pin=pin,+ # Toby withholds a write tool from a member who did not install the+ # connector, and classifies only Jira's writes today, so neither Drive+ # tool is withheld. Classifying Drive's writes turns this red.+ expected_verdicts={+ "google_drive_create_file": "allow",+ "google_drive_delete_file": "allow",+ },+ )+ sweep = Sweep(+ tenant_pin=pin,+ find=ToolStep(+ "google_drive_search",+ {+ "query": FixtureRef("google-drive.write_sweep_query"),+ "max_results": 100,+ },+ assertions=(StatusSuccess(), HasKeys((), ("files",))),+ ),+ items=("files",),+ name=("name",),+ delete=ToolStep(+ "google_drive_delete_file",+ {"file_id": ItemRef(("id",))},+ assertions=(StatusSuccess(),),+ ),+ )+ return write, sweep+++_GOOGLE_DRIVE_WRITE, _GOOGLE_DRIVE_SWEEP = _google_drive_write_checks()++# Connectors that have adopted V2, by catalog app id. Each tool of an in-repo# connector has a check or an exemption (#3565, tests/web/connector_checks/# test_tool_coverage.py); a remote one declares the checks it has.@@ -1019,9 +1125,7 @@ CONNECTOR_CHECKS: Mapping[str, ConnectorChecks] = {issue=_GOOGLE_TIER_1,reads=("google_drive_download_file", "google_drive_list_permissions"),writes=(- "google_drive_create_file","google_drive_create_folder",- "google_drive_delete_file","google_drive_move_file","google_drive_remove_permission","google_drive_rename_file",@@ -1031,6 +1135,8 @@ CONNECTOR_CHECKS: Mapping[str, ConnectorChecks] = {"google_drive_upload_file",),),+ writes=(_GOOGLE_DRIVE_WRITE,),+ sweep=_GOOGLE_DRIVE_SWEEP,),"google-sheets": ConnectorChecks("google-sheets",diff --git a/src/xagent/web/connector_checks/writes.py b/src/xagent/web/connector_checks/writes.pyindex 11499c730..71c6971cc 100644--- a/src/xagent/web/connector_checks/writes.py+++ b/src/xagent/web/connector_checks/writes.py@@ -344,9 +344,11 @@ async def pin_tenant(timeout: float,where: str,) -> str | None:- """Read the connection's tenant id at ``path`` with ``step``: the- ``tenant_mismatch`` reason (``pin_failed``, ``mismatch``), or None when- it is ``expected``. The sweeper pins its tenant the same way."""+ """Read with ``step``, at ``path``, the value only this tenant's account+ has: its tenant id, or the id of the tenant's own write-area container.+ Return the ``tenant_mismatch`` reason (``pin_failed``, ``mismatch``), or+ None when the value is ``expected``. The sweeper pins its tenant the same+ way."""pinned = await call_step(tool, step, timeout)raise_if_cancelled()if step_fault(pinned, step, where, _PIN) is not None:diff --git a/tests/web/connector_checks/test_google_drive_checks.py b/tests/web/connector_checks/test_google_drive_checks.pynew file mode 100644index 000000000..f361d3645--- /dev/null+++ b/tests/web/connector_checks/test_google_drive_checks.py@@ -0,0 +1,799 @@+"""Google Drive's write check (#3567), run end to end.++The declaration in ``registry.py`` runs through the real engine and sweeper,+and every step calls the real tool function in+``web/tools/mcp/google_drive.py``. Only Drive's API is replaced, by an+in-memory drive laid out like the test tenant's seed: a closed seed folder+holding the seed document, and the write folder the write check creates in.+The Composio tests replace Composio's two calls as well, so the create runs+through ``google_drive_composio.create_file`` as it does on a production+grant: stage the content, run ``GOOGLEDRIVE_CREATE_FILE``, read the new file+back through the proxy.+"""++from __future__ import annotations++import hashlib+import re+from collections.abc import Callable+from datetime import datetime, timedelta, timezone+from typing import Any++import pytest++from xagent.web.connector_checks.engine import run_checks+from xagent.web.connector_checks.results import RunResult+from xagent.web.connector_checks.sweeper import run_sweep+from xagent.web.tools.mcp import (+ composio_proxy,+ composio_tools,+ google_drive,+ google_drive_composio,+)++from .fakes import FakePolicyAdapter, FakeTool, listed, rows, targets, tool_for++SEED_FOLDER = "folder-seed"+SEED_DOC = "doc-seed"+WRITE_FOLDER = "folder-write"+FOLDER_MIME = "application/vnd.google-apps.folder"+DOC_MIME = "application/vnd.google-apps.document"+SEED_DOC_TEXT = "xagent smoke seed document\nSecond line: seeded content\n"+FIXTURES = {+ "google-drive.seed_folder_id": SEED_FOLDER,+ "google-drive.write_folder_id": WRITE_FOLDER,+ "google-drive.write_sweep_query": (+ f"'{WRITE_FOLDER}' in parents and trashed = false"+ ),+ "google-docs.document_id": SEED_DOC,+}+# Toby classifies only Jira's writes, so it withholds neither Drive tool from a+# member who did not install the connector.+VERDICTS = {"google_drive_create_file": "allow", "google_drive_delete_file": "allow"}+NAMED = re.compile(r"xagent-smoke-[0-9]{12}-[0-9a-f]{6}-drive-file")+# The tenant pin's search: the write folder, by the seed's own name rule.+PIN_QUERY = (+ "name = 'xagent-smoke-write' and "+ f"mimeType = '{FOLDER_MIME}' and "+ "'root' in parents and "+ "trashed = false"+)+_NAME_QUERY = re.compile(+ r"name = '(?P<name>[^']*)' and mimeType = '(?P<mime_type>[^']*)'"+ r"(?: and '(?P<root>root)' in parents)? and trashed = false"+)+_PARENT_QUERY = re.compile(r"'(?P<parent>[^']*)' in parents and trashed = false")+# The lookup a create whose answer was lost makes: by name and parent.+_SAME_NAME_QUERY = re.compile(+ r"name = '(?P<name>[^']*)' and trashed = false and '(?P<parent>[^']*)' in parents"+)+++def _in_parent(item: dict[str, Any], parent: str | None) -> bool:+ """Whether a name query's parent clause holds: anywhere when it has none,+ the root for the fake's top-level items, or one of the item's parents."""+ if parent is None:+ return True+ if parent == "root":+ return not item["parents"]+ return parent in item["parents"]+++class Drive:+ """An in-memory Drive answering the requests google_drive.py sends."""++ def __init__(self) -> None:+ self.revoked = False+ self.items: dict[str, dict[str, Any]] = {}+ self.contents: dict[str, bytes] = {}+ self.requests: list[tuple[str, str]] = []+ self.created: list[dict[str, Any]] = []+ self.add(SEED_FOLDER, "xagent-smoke-seed", FOLDER_MIME)+ self.add(+ SEED_DOC,+ "xagent-smoke-seed-doc",+ DOC_MIME,+ parent=SEED_FOLDER,+ content=SEED_DOC_TEXT.encode("utf-8"),+ )+ self.add(WRITE_FOLDER, "xagent-smoke-write", FOLDER_MIME)++ def add(+ self,+ file_id: str,+ name: str,+ mime_type: str,+ *,+ parent: str | None = None,+ content: bytes = b"",+ ) -> str:+ self.items[file_id] = {+ "id": file_id,+ "name": name,+ "mimeType": mime_type,+ "modifiedTime": "2026-11-01T00:00:00.000Z",+ "parents": [parent] if parent else [],+ }+ self.contents[file_id] = content+ return file_id++ def files(self) -> _Files:+ return _Files(self)++ def refused(self) -> None:+ if self.revoked:+ raise RuntimeError("401 Client Error: Unauthorized")++ def search(self, query: str, page_size: int) -> dict[str, Any]:+ self.refused()+ self.requests.append(("list", query))+ by_name = _NAME_QUERY.fullmatch(query)+ if by_name:+ found = [+ item+ for item in self.items.values()+ if item["name"] == by_name["name"]+ and item["mimeType"] == by_name["mime_type"]+ and _in_parent(item, by_name["root"])+ ]+ else:+ same_name = _SAME_NAME_QUERY.fullmatch(query)+ if same_name is not None:+ found = [+ {+ "id": item["id"],+ "name": item["name"],+ "createdTime": item["modifiedTime"],+ }+ for item in self.items.values()+ if item["name"] == same_name["name"]+ and same_name["parent"] in item["parents"]+ ]+ else:+ by_parent = _PARENT_QUERY.fullmatch(query)+ assert by_parent, query+ found = [+ item+ for item in self.items.values()+ if by_parent["parent"] in item["parents"]+ ]+ return {"files": found[:page_size]}++ def create(self, body: dict[str, Any], media: Any) -> dict[str, Any]:+ self.refused()+ (parent,) = body.get("parents") or [None]+ content = media.getbytes(0, 1 << 20)+ file_id = self.add(+ f"file-{len(self.items) + 1}",+ body["name"],+ body["mimeType"],+ parent=parent,+ content=content,+ )+ self.created.append(+ {+ "id": file_id,+ "name": body["name"],+ "parent": parent,+ "mime_type": body["mimeType"],+ "content": content,+ }+ )+ self.requests.append(("create", file_id))+ return {+ "id": file_id,+ "name": body["name"],+ "mimeType": body["mimeType"],+ "webViewLink": f"https://drive.example/{file_id}",+ }++ def get(self, file_id: str) -> dict[str, Any]:+ self.refused()+ self.requests.append(("get", file_id))+ if file_id not in self.items:+ raise RuntimeError("404 Client Error: Not Found")+ item = self.items[file_id]+ if item["mimeType"] == FOLDER_MIME:+ return item+ # What Drive reports for a stored file, and what a Composio create's+ # read-back and a proxied download are checked against.+ data = self.contents[file_id]+ return {+ **item,+ "size": str(len(data)),+ "md5Checksum": hashlib.md5(data, usedforsecurity=False).hexdigest(),+ }++ def media(self, file_id: str) -> str:+ """The id a media request would read, which the downloader indexes+ ``contents`` by."""+ self.refused()+ self.requests.append(("media", file_id))+ if file_id not in self.items:+ raise RuntimeError("404 Client Error: Not Found")+ return file_id++ def delete(self, file_id: str) -> None:+ self.refused()+ self.requests.append(("delete", file_id))+ if file_id not in self.items:+ raise RuntimeError("404 Client Error: Not Found")+ del self.items[file_id]+++class _Request:+ """An unexecuted Drive request: the call runs on ``execute``."""++ def __init__(self, run: Callable[[], Any]) -> None:+ self._run = run++ def execute(self) -> Any:+ return self._run()+++class _Files:+ def __init__(self, drive: Drive) -> None:+ self._drive = drive++ def list(self, **kwargs: Any) -> _Request:+ return _Request(lambda: self._drive.search(kwargs["q"], kwargs["pageSize"]))++ def create(self, **kwargs: Any) -> _Request:+ return _Request(+ lambda: self._drive.create(kwargs["body"], kwargs["media_body"])+ )++ def get(self, **kwargs: Any) -> _Request:+ return _Request(lambda: self._drive.get(kwargs["fileId"]))++ def get_media(self, **kwargs: Any) -> str:+ return self._drive.media(kwargs["fileId"])++ def export_media(self, **kwargs: Any) -> str:+ return self._drive.media(kwargs["fileId"])++ def delete(self, **kwargs: Any) -> _Request:+ return _Request(lambda: self._drive.delete(kwargs["fileId"]))+++# Every tool the server registers, so the session lists what production does.+_TOOLS = (+ "google_drive_search",+ "google_drive_get_file_content",+ "google_drive_download_file",+ "google_drive_upload_file",+ "google_drive_update_file_content",+ "google_drive_create_file",+ "google_drive_create_folder",+ "google_drive_rename_file",+ "google_drive_move_file",+ "google_drive_delete_file",+ "google_drive_list_permissions",+ "google_drive_share_file",+ "google_drive_update_permission",+ "google_drive_remove_permission",+)+++def drive(monkeypatch: pytest.MonkeyPatch) -> Drive:+ drive = Drive()+ monkeypatch.setattr(google_drive, "get_drive_service", lambda: drive)+ monkeypatch.setattr(+ google_drive, "_download_media", lambda file_id: drive.contents[file_id]+ )+ return drive+++class Composio:+ """Composio's two calls a Drive create makes, on the fake drive.++ ``stage_file`` keeps the bytes under a made-up key, and ``execute_tool``+ has ``GOOGLEDRIVE_CREATE_FILE`` create the file in Drive the way the+ tool does: named as the arguments say, in the folder its ``parents``+ names. ``fail_status`` loses the answer after the tool ran (a 5xx), the+ case where the file exists but the call reports it as unconfirmed.+ """++ def __init__(self, drive: Drive, *, fail_status: int | None = None) -> None:+ self.drive = drive+ self.fail_status = fail_status+ self.staged: dict[str, tuple[bytes, str]] = {}+ self.executed: list[tuple[str, dict[str, Any]]] = []++ def stage_file(+ self,+ *,+ toolkit_slug: str,+ tool_slug: str,+ filename: str,+ mimetype: str,+ md5: str,+ data: Any,+ length: int,+ on_dedup: Callable[[], None] | None = None,+ ) -> dict[str, str]:+ key = f"s3key-{len(self.staged) + 1}"+ body = bytes(data)+ assert hashlib.md5(body, usedforsecurity=False).hexdigest() == md5+ assert len(body) == length+ self.staged[key] = (body, mimetype)+ return {"name": filename, "mimetype": mimetype, "s3key": key}++ def execute_tool(+ self, tool_slug: str, arguments: dict[str, Any], *, toolkit: str+ ) -> composio_tools.ToolResult:+ self.executed.append((tool_slug, dict(arguments)))+ body, _ = self.staged[arguments["file_to_upload"]["s3key"]]+ (parent,) = arguments.get("parents") or [None]+ file_id = self.drive.add(+ f"file-{len(self.drive.items) + 1}",+ arguments["name"],+ arguments["mimeType"],+ parent=parent,+ content=body,+ )+ self.drive.created.append(+ {"id": file_id, "name": arguments["name"], "parent": parent}+ )+ if self.fail_status is not None:+ raise composio_tools.ComposioToolError(+ "bad gateway", status=self.fail_status+ )+ return composio_tools.ToolResult(+ successful=True, data={"id": file_id}, error=None+ )+++def composio(drive: Drive, monkeypatch: pytest.MonkeyPatch) -> Composio:+ """A Composio-backed grant: Drive's calls stay on the fake drive, and the+ create stages and runs Composio's tool instead of Drive's files.create."""+ monkeypatch.setenv(composio_proxy.COMPOSIO_CONNECTED_ACCOUNT_ID_ENV, "ca_test")+ composio = Composio(drive)+ monkeypatch.setattr(composio_tools, "stage_file", composio.stage_file)+ monkeypatch.setattr(composio_tools, "execute_tool", composio.execute_tool)+ return composio+++def writes_on(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("XAGENT_CONNECTOR_SMOKE_WRITE_APPS", "google-drive")+++def _tools() -> dict[str, FakeTool]:+ return {name: tool_for(google_drive, name) for name in _TOOLS}+++def _adapter(+ fixtures: dict[str, Any] = FIXTURES, tools: dict[str, FakeTool] | None = None+) -> FakePolicyAdapter:+ tools = tools if tools is not None else _tools()+ return FakePolicyAdapter(+ targets("google-drive"),+ {"google-drive": listed(*tools.values())},+ verdicts=VERDICTS,+ fixtures=fixtures,+ )+++async def _run(+ adapter: FakePolicyAdapter, checks: list[str] | None = None+) -> RunResult:+ return await run_checks(+ adapter, checks=checks, check_timeout=5.0, total_timeout=60.0+ )+++def _check_rows(result: RunResult) -> dict[str, tuple[Any, ...]]:+ # The session row carries no check id.+ return {+ row[1] or "session": row[2:] for row in rows(result) if row[0] == "google-drive"+ }+++_CHECKS = (+ "google-drive.search_seed_folder",+ "google-drive.read_seed_file",+ "google-drive.file_round_trip",+)+++# A run against the seeded drive++[email protected]("writes_on")+async def test_every_check_passes_on_the_seeded_drive_and_leaves_nothing(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)+ tools = _tools()++ result = await _run(_adapter(tools=tools))++ assert _check_rows(result) == {+ "session": ("pass", None, None),+ **{check: ("pass", None, None) for check in _CHECKS},+ }+ assert result.complete+ # The write check created one run-scoped file in the write folder, read it+ # back, and deleted it again.+ assert len(drive.created) == 1+ assert len([kind for kind, _ in drive.requests if kind == "delete"]) == 1+ assert drive.items == seeded++[email protected]("writes_on")+async def test_the_write_check_names_its_file_for_its_run(drive: Drive) -> None:+ await _run(_adapter())++ (created,) = drive.created+ assert created["parent"] == WRITE_FOLDER+ assert created["mime_type"] == "text/plain"+ assert created["content"] == b"xagent smoke write probe"+ assert NAMED.fullmatch(created["name"])+++async def test_with_writes_off_the_reads_still_run(drive: Drive) -> None:+ result = await _run(_adapter())++ checks = _check_rows(result)+ assert checks.pop("google-drive.file_round_trip") == (+ "skip",+ "writes_disabled",+ None,+ )+ assert set(checks.values()) == {("pass", None, None)}+ assert not [kind for kind, _ in drive.requests if kind in ("create", "delete")]++[email protected]("writes_on")+async def test_a_revoked_grant_fails_every_check_and_writes_nothing(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)+ drive.revoked = True++ result = await _run(_adapter())++ checks = _check_rows(result)+ assert checks.pop("session") == ("pass", None, None)+ assert set(checks) == set(_CHECKS)+ assert {outcome for outcome, _, _ in checks.values()} == {"fail"}+ assert drive.items == seeded++[email protected]("writes_on")+async def test_a_pin_that_reads_another_write_folder_refuses_the_write(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)++ result = await _run(+ _adapter({**FIXTURES, "google-drive.write_folder_id": "folder-2"})+ )++ checks = _check_rows(result)+ # The read checks keep to the seed, so they still pass; the pin reads the+ # write folder and requires the registry's id, so it refuses the write.+ assert checks["google-drive.search_seed_folder"] == ("pass", None, None)+ assert checks["google-drive.file_round_trip"] == (+ "fail",+ "tenant_mismatch",+ "mismatch",+ )+ assert not drive.created+ assert drive.items == seeded++[email protected]("writes_on")+async def test_a_same_named_folder_outside_the_root_does_not_fail_the_pin(+ drive: Drive,+) -> None:+ # The seed's own uniqueness rule counts folders in My Drive's root only,+ # so the pin's search does too: a folder with the write folder's name+ # deeper in the tree is not a second write folder.+ drive.add("folder-nested", "xagent-smoke-write", FOLDER_MIME, parent=SEED_FOLDER)++ result = await _run(_adapter(), checks=["google-drive.file_round_trip"])++ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "pass",+ None,+ None,+ )+ assert len(drive.created) == 1++[email protected]("writes_on")+async def test_a_write_folder_the_connection_cannot_read_refuses_the_write(+ drive: Drive,+) -> None:+ # A native `drive.file` grant, or a connection to another account, cannot+ # see the write folder the seed made: the pin's search finds no such+ # folder and nothing is written.+ seeded = dict(drive.items)+ del drive.items[WRITE_FOLDER]+ del seeded[WRITE_FOLDER]++ result = await _run(_adapter(), checks=["google-drive.file_round_trip"])++ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "tenant_mismatch",+ "pin_failed",+ )+ # The pin's search ran, with the registry's own query: an unrecognised+ # query becomes an error envelope the tool swallows into the same+ # `pin_failed`, so the test pins the query too.+ assert ("list", PIN_QUERY) in drive.requests+ assert not drive.created+ assert drive.items == seeded+++# A Composio-backed grant, the connection production actually serves++[email protected]("writes_on", "composio")+async def test_a_composio_grant_creates_reads_and_deletes_the_file(+ drive: Drive, composio: Composio+) -> None:+ seeded = dict(drive.items)++ result = await _run(_adapter())++ assert _check_rows(result) == {+ "session": ("pass", None, None),+ **{check: ("pass", None, None) for check in _CHECKS},+ }+ # The pin read the write folder before the create, and the create ran+ # Composio's tool with the file staged in that folder.+ assert ("list", PIN_QUERY) in drive.requests+ ((slug, arguments),) = composio.executed+ assert slug == google_drive_composio.GOOGLEDRIVE_CREATE_FILE+ assert arguments["parents"] == [WRITE_FOLDER]+ assert arguments["mimeType"] == "text/plain"+ assert arguments["file_to_upload"]["mimetype"] == "text/plain"+ assert NAMED.fullmatch(arguments["name"])+ # One file was created and deleted, through the same Drive API calls.+ assert len(drive.created) == 1+ assert len([kind for kind, _ in drive.requests if kind == "delete"]) == 1+ assert drive.items == seeded++[email protected]("writes_on", "composio")+async def test_a_composio_create_whose_answer_is_lost_leaves_the_file_to_the_sweep(+ drive: Drive, composio: Composio+) -> None:+ seeded = dict(drive.items)+ composio.fail_status = 502++ result = await _run(_adapter())++ # The tool ran, so the file exists; with no id in the answer the create+ # fails its status assertion and nothing is deleted.+ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "assertion_failed",+ "create:status_success",+ )+ (created,) = set(drive.items) - set(seeded)+ assert drive.items[created]["parents"] == [WRITE_FOLDER]+ assert not [kind for kind, _ in drive.requests if kind == "delete"]++ # The next sweep finds it in the write folder and deletes it by id.+ later = datetime.now(timezone.utc) + timedelta(hours=3)+ swept = await run_sweep(+ _adapter(), call_timeout=5.0, total_timeout=60.0, now=lambda: later+ )+ (row,) = swept.to_document()["rows"]+ assert (row["outcome"], row["found"], row["deleted"]) == ("pass", 1, 1)+ assert drive.items == seeded++[email protected]("writes_on", "composio")+async def test_a_composio_grant_that_cannot_read_the_write_folder_writes_nothing(+ drive: Drive, composio: Composio+) -> None:+ # The grant reaches Drive (the reads answer) but not the seed's write+ # folder: a search for it finds nothing, so the pin fails and no create+ # runs.+ del drive.items[WRITE_FOLDER]+ seeded = dict(drive.items)++ result = await _run(_adapter(), checks=["google-drive.file_round_trip"])++ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "tenant_mismatch",+ "pin_failed",+ )+ # The pin's search ran, with the registry's own query: an unrecognised+ # query becomes an error envelope the tool swallows into the same+ # `pin_failed`.+ assert ("list", PIN_QUERY) in drive.requests+ assert not composio.executed+ assert not drive.created+ assert drive.items == seeded++[email protected]("writes_on")+async def test_a_file_that_lost_its_run_scoped_name_is_not_deleted(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)+ original = drive.create++ def rename(body: dict[str, Any], media: Any) -> dict[str, Any]:+ file = original(body, media)+ drive.items[file["id"]]["name"] = "another name"+ return file++ drive.create = rename # type: ignore[method-assign]++ result = await _run(_adapter())++ # The read-back no longer finds the run-scoped name, so the guard stops+ # the cleanup and the file stays for the sweeper.+ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "cleanup_failed",+ "ownership",+ )+ assert not [kind for kind, _ in drive.requests if kind == "delete"]+ assert set(drive.items) == set(seeded) | {drive.created[0]["id"]}++[email protected]("writes_on")+async def test_a_file_whose_content_did_not_land_as_sent_fails_verify_and_is_deleted(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)+ original = drive.create++ def store_other(body: dict[str, Any], media: Any) -> dict[str, Any]:+ file = original(body, media)+ drive.contents[file["id"]] = b"not the probe text"+ return file++ drive.create = store_other # type: ignore[method-assign]++ result = await _run(_adapter())++ # `verify` reads the content back and finds another, which fails the+ # check; the guard asserts the name alone, so the file is still deleted.+ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "assertion_failed",+ "verify:equals",+ )+ assert len([kind for kind, _ in drive.requests if kind == "delete"]) == 1+ assert drive.items == seeded++[email protected]("writes_on")+async def test_a_create_that_returns_an_error_is_not_cleaned_up(+ drive: Drive,+) -> None:+ seeded = dict(drive.items)++ def refuse(body: dict[str, Any], media: Any) -> dict[str, Any]:+ raise RuntimeError("403 Client Error: Forbidden")++ drive.create = refuse # type: ignore[method-assign]++ result = await _run(_adapter())++ # The tool turns the Drive error into its own error envelope, so the create+ # fails its status assertion; with no created id, nothing is deleted.+ assert _check_rows(result)["google-drive.file_round_trip"] == (+ "fail",+ "assertion_failed",+ "create:status_success",+ )+ assert not [kind for kind, _ in drive.requests if kind == "delete"]+ assert drive.items == seeded+++# Drifted seed objects+++async def test_a_seed_document_whose_text_is_gone_fails_its_read(+ drive: Drive,+) -> None:+ drive.contents[SEED_DOC] = b"another document"++ result = await _run(_adapter())++ outcome, failure_class, reason = _check_rows(result)["google-drive.read_seed_file"]+ assert (outcome, failure_class) == ("fail", "assertion_failed")+ assert reason == "contains"+++async def test_a_seed_document_that_drifted_fails_its_read(drive: Drive) -> None:+ drive.items[SEED_DOC]["name"] = "another-doc"++ result = await _run(_adapter())++ outcome, failure_class, reason = _check_rows(result)["google-drive.read_seed_file"]+ assert (outcome, failure_class) == ("fail", "assertion_failed")+ assert reason == "equals"+++async def test_a_seed_folder_that_is_gone_fails_its_read(drive: Drive) -> None:+ del drive.items[SEED_FOLDER]++ result = await _run(_adapter())++ outcome, failure_class, reason = _check_rows(result)[+ "google-drive.search_seed_folder"+ ]+ assert (outcome, failure_class) == ("fail", "assertion_failed")+ assert reason == "length"+++# The sweep++[email protected]("writes_on")+async def test_the_sweep_deletes_only_old_leftovers_in_the_write_folder(+ drive: Drive,+) -> None:+ now = datetime(2026, 11, 11, 12, 0, tzinfo=timezone.utc)++ def run_name(age: timedelta) -> str:+ return f"xagent-smoke-{(now - age).strftime('%Y%m%d%H%M')}-a1b2c3-drive-file"++ seeded = dict(drive.items)+ stale = run_name(timedelta(hours=3))+ old = drive.add("file-old", stale, "text/plain", parent=WRITE_FOLDER)+ young = drive.add(+ "file-young", run_name(timedelta(minutes=30)), "text/plain", parent=WRITE_FOLDER+ )+ # The same old run-scoped name outside the write folder: the sweep lists+ # the write folder alone, so it stays.+ elsewhere = drive.add("file-elsewhere", stale, "text/plain", parent=SEED_FOLDER)+ tools = _tools()++ result = await run_sweep(+ _adapter(tools=tools), call_timeout=5.0, total_timeout=60.0, now=lambda: now+ )++ assert tools["google_drive_delete_file"].calls == [{"file_id": old}]+ (row,) = result.to_document()["rows"]+ assert (row["connector"], row["outcome"]) == ("google-drive", "pass")+ assert old not in drive.items+ assert young in drive.items+ assert elsewhere in drive.items+ assert set(drive.items) == set(seeded) | {young, elsewhere}+ assert ("list", FIXTURES["google-drive.write_sweep_query"]) in drive.requests++[email protected]("writes_on")+async def test_a_sweep_whose_pin_cannot_read_the_write_folder_sweeps_nothing(+ drive: Drive,+) -> None:+ # The pin runs before the sweep's find, so a write folder the connection+ # cannot read ends the sweep there: the old leftover in it is neither+ # listed nor deleted.+ drive.add(+ "file-stale",+ "xagent-smoke-202601010000-a1b2c3-drive-file",+ "text/plain",+ parent=WRITE_FOLDER,+ )+ del drive.items[WRITE_FOLDER]+ seeded = dict(drive.items)++ result = await run_sweep(_adapter(), call_timeout=5.0, total_timeout=60.0)++ (row,) = result.to_document()["rows"]+ assert (row["outcome"], row["failure_class"], row["reason"]) == (+ "fail",+ "tenant_mismatch",+ "pin_failed",+ )+ assert (row["found"], row["deleted"]) == (0, 0)+ assert ("list", FIXTURES["google-drive.write_sweep_query"]) not in drive.requests+ assert not [kind for kind, _ in drive.requests if kind == "delete"]+ assert drive.items == seededdiff --git a/tests/web/connector_checks/test_registry.py b/tests/web/connector_checks/test_registry.pyindex 0ac4fcb32..1538e146e 100644--- a/tests/web/connector_checks/test_registry.py+++ b/tests/web/connector_checks/test_registry.py@@ -21,17 +21,24 @@ from xagent.web.connector_checks.declarations import (Assertion,ConnectorChecks,Contains,+ CreatedRef,DeclarationError,EachHasKeys,Equals,FixtureRef,HasKeys,IsType,+ ItemRef,L3Envelope,Length,ReadCheck,+ RunScopedName,StatusSuccess,+ Sweep,+ TenantPin,+ ToolStep,UnprobeableCheck,+ WriteCheck,validate_connector_checks,)from xagent.web.connector_checks.fixtures import FixtureValue, resolve_fixtures@@ -1388,7 +1395,7 @@ _GOOGLE_APP_MODULES = {"google-slides": google_slides,}-# The fixture keys the Google read checks use, pinned here so that adding or+# The fixture keys the Google checks use, pinned here so that adding or# dropping one shows in the diff. The tenant registry# (xorbitsai/xagent-saas#2627) records each of them for the Google seed layout._GOOGLE_FIXTURE_KEYS_USED = frozenset(@@ -1397,6 +1404,8 @@ _GOOGLE_FIXTURE_KEYS_USED = frozenset("google-analytics.property_id","google-docs.document_id","google-drive.seed_folder_id",+ "google-drive.write_folder_id",+ "google-drive.write_sweep_query","google-sheets.spreadsheet_id","google-slides.presentation_id",}@@ -1417,6 +1426,10 @@ class _Fixtures:"google-analytics.property_id": "563334905","google-docs.document_id": "doc-1","google-drive.seed_folder_id": "folder-1",+ "google-drive.write_folder_id": "folder-write",+ "google-drive.write_sweep_query": (+ "'folder-write' in parents and trashed = false"+ ),"google-sheets.spreadsheet_id": "sheet-1","google-slides.presentation_id": "deck-1",}@@ -1428,13 +1441,37 @@ class _Fixtures:_FIXTURES = _Fixtures()-def _fixture_keys(check: ReadCheck) -> Iterator[FixtureRef]:- yield from _fixture_refs(check.arguments)- for assertion in check.assertions:+def _fixture_keys(step: ReadCheck | ToolStep) -> Iterator[FixtureRef]:+ yield from _fixture_refs(step.arguments)+ for assertion in step.assertions:if isinstance(assertion, Equals):yield from _fixture_refs(assertion.value)+def _google_fixture_keys() -> Iterator[FixtureRef]:+ """Every fixture key a Google declaration names: a read check's, a write+ check's (its pin's expected included), and its sweep's."""+ for app_id in _GOOGLE_APP_MODULES:+ checks = CONNECTOR_CHECKS[app_id]+ for read in checks.reads:+ if isinstance(read, ReadCheck):+ yield from _fixture_keys(read)+ for write in checks.writes:+ yield from _fixture_refs(write.tenant_pin.expected)+ for step in (+ write.create,+ write.verify,+ write.cleanup,+ write.cleanup_guard,+ ):+ if step is not None:+ yield from _fixture_keys(step)+ if checks.sweep is not None:+ yield from _fixture_refs(checks.sweep.tenant_pin.expected)+ yield from _fixture_keys(checks.sweep.find)+ yield from _fixture_keys(checks.sweep.delete)++@pytest.mark.parametrize(("check_id", "expected"), sorted(_GOOGLE_READS.items()))def test_a_google_read_check_is_declared_exactly(check_id: str, expected: tuple[str, dict[str, Any], tuple[Assertion, ...]]@@ -1495,14 +1532,8 @@ def test_a_google_document_probe_still_needs_a_fixture(app_id: str) -> None:)-def test_the_google_read_checks_use_exactly_these_fixture_keys() -> None:- keys = {- ref.key- for app_id in _GOOGLE_APP_MODULES- for check in CONNECTOR_CHECKS[app_id].reads- if isinstance(check, ReadCheck)- for ref in _fixture_keys(check)- }+def test_the_google_checks_use_exactly_these_fixture_keys() -> None:+ keys = {ref.key for ref in _google_fixture_keys()}assert keys == _GOOGLE_FIXTURE_KEYS_USED@@ -1532,15 +1563,111 @@ def test_a_google_fixture_is_bound_to_a_parameter_of_its_tool(app_id: str) -> Noassert required <= set(check.arguments), (check.tool, required)+def test_google_drive_declares_its_write_check() -> None:+ """The pin, the create, the read-back that also guards the cleanup, and+ the verdicts, pinned so that changing a step shows in the diff."""+ pin = TenantPin(+ ToolStep(+ "google_drive_search",+ {+ "query": (+ "name = 'xagent-smoke-write' and "+ "mimeType = 'application/vnd.google-apps.folder' and "+ "'root' in parents and "+ "trashed = false"+ ),+ "max_results": 10,+ },+ assertions=(Length(("files",), 1, 1),),+ ),+ path=("files", 0, "id"),+ # Drive has no tool that returns the tenant's customer id, so the pin+ # reads the write-area container (#3567): the folder the seed keeps+ # unshared, found by the seed's own rule - its name, its type and the+ # root as its parent - and required to be the registry's id.+ expected=FixtureRef("google-drive.write_folder_id"),+ )+ name = RunScopedName("drive-file")+ created = CreatedRef(("file", "id"))+ probe = "xagent smoke write probe"+ # The guard asserts the name alone, so content that did not land as sent+ # still lets the cleanup delete the file.+ guard = ToolStep(+ "google_drive_get_file_content",+ {"file_id": created},+ assertions=(StatusSuccess(), Equals(("file", "name"), name)),+ )++ assert CONNECTOR_CHECKS["google-drive"].writes == (+ WriteCheck(+ "google-drive.file_round_trip",+ create=ToolStep(+ "google_drive_create_file",+ {+ "name": name,+ "content": probe,+ "mime_type": "text/plain",+ "parent_id": FixtureRef("google-drive.write_folder_id"),+ },+ assertions=(StatusSuccess(), HasKeys(("file",), ("id",))),+ ),+ verify=ToolStep(+ "google_drive_get_file_content",+ {"file_id": created},+ assertions=(+ StatusSuccess(),+ Equals(("file", "name"), name),+ Equals(("content",), probe),+ ),+ ),+ cleanup=ToolStep(+ "google_drive_delete_file",+ {"file_id": created},+ assertions=(StatusSuccess(),),+ ),+ cleanup_guard=guard,+ tenant_pin=pin,+ # Toby classifies only Jira's writes, so it withholds neither+ # Drive tool from a member.+ expected_verdicts={+ "google_drive_create_file": "allow",+ "google_drive_delete_file": "allow",+ },+ ),+ )+++def test_google_drive_declares_its_sweep() -> None:+ checks = CONNECTOR_CHECKS["google-drive"]++ assert checks.sweep == Sweep(+ tenant_pin=checks.writes[0].tenant_pin,+ find=ToolStep(+ "google_drive_search",+ {+ "query": FixtureRef("google-drive.write_sweep_query"),+ "max_results": 100,+ },+ assertions=(StatusSuccess(), HasKeys((), ("files",))),+ ),+ items=("files",),+ name=("name",),+ delete=ToolStep(+ "google_drive_delete_file",+ {"file_id": ItemRef(("id",))},+ assertions=(StatusSuccess(),),+ ),+ )++def test_a_cleanable_write_keeps_a_pending_exemption() -> None:- """The writes whose own cleanup tool can delete what they create wait for- round two (#3567); none carries the permanent no-cleanup reason."""+ """The writes whose own cleanup tool can delete what they create still+ wait for a later check (#3567); none carries the permanent no-cleanup+ reason."""cleanable = ("google_calendar_create_events","google_calendar_delete_events",- "google_drive_create_file","google_drive_create_folder",- "google_drive_delete_file","google_sheets_add_sheet","google_sheets_delete_sheet","google_slides_add_slide",diff --git a/tests/web/services/test_standby_startup.py b/tests/web/services/test_standby_startup.pyindex 1c168078a..51d36ef70 100644--- a/tests/web/services/test_standby_startup.py+++ b/tests/web/services/test_standby_startup.py@@ -243,6 +243,12 @@ async def test_standby_preloads_channel_modules_but_only_activation_starts_them()# Undo the stub modules _patch_startup installed; the finder serves fresh ones.for name in _CHANNEL_MODULES:+ package_name, _, attribute = name.rpartition(".")+ package = importlib.import_module(package_name)+ # The fake import rebinds the name on the parent package as well;+ # restoring sys.modules alone would leave that binding behind.+ previous = getattr(package, attribute, None)+ monkeypatch.setattr(package, attribute, previous, raising=False)monkeypatch.setitem(sys.modules, name, None)del sys.modules[name]for task_name in ("telegram_task", "feishu_task", "slack_task"):