Feature Spec: Full Drive Integration Model

Version: 1.0 Date: 2026-02-18 Owner: Yohay Etsion (Product Owner) Status: Approved. Ready for implementation. Product: Legionis V2V Phase: Phase 3, Strategic Commitments Related Docs: PRD V3.0 (USP #1 Cloud Storage Connectivity, USP #6 Full Data Ownership), Execution Plan V3.1 (Week 5), DR-2026-002 (Cloud Storage First) Codebase: C:\dev\legionis (GitHub: yohayetsion/legionis)


1. Problem Statement

Legionis currently exposes only the Legionis workspace folder in its file explorer. Users can see context/, deliverables/, and their workspace subfolders, but nothing else from their Google Drive. This creates a walled garden that contradicts the product's core promise: your files, your cloud, your control.

The result is friction. Users who want an agent to review a strategy doc from last quarter, analyze a spreadsheet from a shared folder, or reference a contract buried three levels deep in their Drive must leave Legionis, find the file in Google Drive's native UI, copy its content, and paste it into the chat. That workflow is the opposite of superpowers. It feels like a downgrade from using Drive natively.

The decision is clear: open the entire Drive to the user inside Legionis, let them drag any file into a conversation, manage files anywhere in their Drive, and restrict agents to writing only in the Legionis workspace. The user is the host. Legionis is the guest. The guest should not rearrange the furniture.


2. Decision

The Model

  • Full Drive browsing. Users navigate their entire Google Drive freely within the Legionis file explorer. My Drive root is the top level. The Legionis workspace folder is visually pinned and highlighted, but it is one folder among many.
  • Drag and drop into chat. Users drag files from the file explorer into the chat input area. The system reads the file content and injects it into the agent's context. Any file in the user's Drive is eligible.
  • Full file management. Users can move, rename, create folders, and delete files anywhere in their Drive from within Legionis. Standard file operations. No restrictions.
  • Agent write boundary. Agents create new deliverables exclusively in the Legionis workspace folders (context/, deliverables/, and subfolders). This is the single hard constraint. Agents can read anything the user shares with them, but they cannot write outside the workspace.
  • Why This Model

    The Drive belongs to the user. Legionis adds intelligence to it. A restricted file browser feels like a downgrade from native Drive. This model makes Drive feel like it gained superpowers: the same familiar space, but now you can pull a file into a conversation and an agent acts on it immediately.

    This directly reinforces two core differentiators:


    3. User Stories

    US-1: Browse Full Drive

    As a Legionis user with a connected Google Drive, I want to see my entire Drive in the file explorer, so that I can find and access any file without leaving Legionis.

    Acceptance Criteria:

    US-2: Drag File into Chat

    As a user working with an agent, I want to drag a file from the explorer into the chat input, so that the agent receives the file's content as context for its response.

    Acceptance Criteria:

    US-3: Manage Files Anywhere

    As a user organizing my Drive, I want to rename, move, create folders, and delete files from within Legionis, so that I do not need to switch to the Google Drive web app for file management.

    Acceptance Criteria:

    US-4: Agent Reads Attached Files

    As a product manager using the @pm agent, I want to attach a competitor's analysis document and ask the agent to review it, so that the agent can produce a competitive assessment based on the actual document.

    Acceptance Criteria:

    US-5: Agent Write Boundary Enforced

    As a user concerned about data integrity, I want agents to only create files in the Legionis workspace folder, so that my personal Drive structure is never modified by an AI without my direct action.

    Acceptance Criteria:

    US-6: Locate Workspace Quickly

    As a user with a large Drive, I want the Legionis workspace folder to be visually prominent and always accessible, so that I can navigate to agent deliverables with one click regardless of where I am in my Drive.

    Acceptance Criteria:

    US-7: Drag from Outside Workspace

    As a user with files scattered across Drive folders, I want to drag a file from any folder (not just the workspace) into chat, so that agents can work with my existing documents regardless of where they are stored.

    Acceptance Criteria:


    4. Functional Requirements

    FR-1: Full Drive Browsing

    IDRequirement
    FR-1.1The file explorer root is the user's My Drive, not the Legionis workspace folder.
    FR-1.2The Legionis workspace folder is pinned at the top of the explorer in a visually distinct "Workspace" section with the Legionis icon.
    FR-1.3Folder navigation is lazy-loaded: contents are fetched on expand, not preloaded.
    FR-1.4The explorer supports pagination for folders with 200+ items (Drive API nextPageToken).
    FR-1.5File and folder entries display: name, icon (by MIME type), and modified date.
    FR-1.6The explorer supports "Shared with me" as a navigable section below My Drive.
    FR-1.7Google Workspace files (Docs, Sheets, Slides) display their native icons and are browsable but not directly editable inline. They can be dragged into chat for reading.

    FR-2: Drag-and-Drop File Attachment

    IDRequirement
    FR-2.1Files in the explorer are draggable. The drag preview shows the file name and icon.
    FR-2.2The chat input area is a valid drop target. On drag-over, it displays a visual indicator (blue border highlight, "Drop file to attach" overlay).
    FR-2.3On drop, the system creates a file attachment chip in the chat input with: file name, MIME type icon, and a remove button (x).
    FR-2.4The file is NOT downloaded on drop. Content is fetched on message send to avoid unnecessary API calls.
    FR-2.5Maximum 5 files per message. Attempting to add a 6th displays: "Maximum 5 files per message."
    FR-2.6Supported file types for content injection: plain text, markdown, JSON, CSV, TSV, Google Docs (exported as text), Google Sheets (exported as CSV).
    FR-2.7Unsupported file types (images, PDFs, binaries) display in the chip but inject a metadata-only reference: "[Attached: {filename}, {mimeType}, {size}. Content not extractable as text.]"
    FR-2.8Per-file content limit: 100KB of extracted text. Files exceeding this are truncated with a notice appended to the content.

    FR-3: File Management Operations

    IDRequirement
    FR-3.1Right-click (or long-press on mobile) on any file or folder in the explorer opens a context menu.
    FR-3.2Context menu options for files: Open (preview), Rename, Move to, Delete, Copy Link.
    FR-3.3Context menu options for folders: Open, Rename, New Folder, Move to, Delete.
    FR-3.4Rename: inline edit with Enter to confirm, Escape to cancel. Calls files.update with new name.
    FR-3.5Move to: opens a folder picker dialog. On confirm, calls files.update with addParents (new parent) and removeParents (old parent).
    FR-3.6Delete: confirmation dialog ("Move {name} to trash?"). On confirm, calls files.update with trashed: true.
    FR-3.7New Folder: creates a new folder inside the selected folder. Inline name input, default "Untitled folder".
    FR-3.8All management operations are available everywhere in Drive, not restricted to the workspace.
    FR-3.9Optimistic UI updates: the explorer reflects the change immediately, rolling back on API failure with an error toast.

    FR-4: Agent Write Boundary

    IDRequirement
    FR-4.1Agent tools writeFile and editFile enforce that the target resolves to a descendant of the workspace folder (workspaces.driveFolderId).
    FR-4.2The boundary check occurs in the tool execution layer, not in the Drive API wrapper. This ensures all agent code paths are covered.
    FR-4.3If an agent attempts a write outside the workspace, the tool returns an error string: "Write denied: agents can only create files in the Legionis workspace. Target path: {path}."
    FR-4.4The agent's system prompt includes an explicit instruction: "You can read any file the user shares with you, but you can only write to the Legionis workspace folder."
    FR-4.5User-initiated file management (FR-3) is NOT subject to this boundary. Users manage their entire Drive freely.

    FR-5: Agent File Reading

    IDRequirement
    FR-5.1A new agent tool readDriveFile accepts a fileId parameter (not a workspace-relative path) and returns the file content.
    FR-5.2readDriveFile works for any file the user's Drive credentials can access, regardless of location.
    FR-5.3When a user sends a message with attached files, the chat route fetches each file's content via readDriveFile and prepends it to the agent's context as a system message block.
    FR-5.5The existing workspace-relative tools (readFile, writeFile, editFile, listDirectory, glob, grep) continue to work unchanged for workspace operations.
    FR-5.6Google Workspace files (Docs, Sheets, Slides) are exported before reading: Docs to plain text, Sheets to CSV, Slides to plain text.


    5. UX Specifications

    5.1 File Explorer: Full Drive with Pinned Workspace

    +-----------------------------------------------+
    
    FILE EXPLORER [x]
    +-----------------------------------------------+
    WORKSPACE
    +-- [L] Legionis Workspace (pinned)
    +-- context/
    +-- deliverables/
    ─────────────────────────────────
    MY DRIVE
    +-- [>] Clients/
    +-- [>] Finance/
    +-- [L] Legionis Workspace
    +-- [>] Marketing/
    +-- [>] Projects/
    +-- [>] Shared Resources/
    strategy-2026.md
    budget-template.xlsx
    SHARED WITH ME
    +-- [>] Partner Docs/
    +-- [>] Board Materials/
    +-----------------------------------------------+

    Notes:

    5.2 Drag-and-Drop into Chat

    +-----------------------------------------------+
    
    CHAT
    [User]: Review this competitor analysis
    [PM]: I'd be happy to review it. Could you
    share the document?
    +-----------------------------------------------+
    Drop file to attach
    ~~~ (blue dashed border) ~~~
    +-----------------------------------------------+

    After drop:

    +-----------------------------------------------+

    [competitor-analysis.md] [x]
    Type your message... [Send]
    +-----------------------------------------------+

    Notes:

    5.3 File Management Context Menu

    +-----------------------------------------------+
    
    MY DRIVE
    +-- [>] Projects/
    +-- Q1-strategy.md
    +-- competitor-dOpen
    Rename
    Move to...
    Delete
    Copy Link
    +-----------------------------------------------+

    Notes:

    5.4 Agent Response with Attached File Reference

    +-----------------------------------------------+
    
    CHAT
    [User]: Review this and give me feedback
    [competitor-analysis.md]
    [PM]: Looking at the competitor analysis
    you shared, I see three things worth
    calling out.
    First, the pricing comparison on page 2
    understates our BYOT advantage...
    I've saved my detailed review to:
    deliverables/competitor-review-2026-02.md
    +-----------------------------------------------+

    Notes:

    5.5 Move To Dialog

    +-----------------------------------------------+
    
    Move "budget-v2.xlsx" to:
    +-----------------------------------------------+
    My Drive
    +-- [>] Clients/
    +-- [v] Finance/
    +-- 2025/
    +-- 2026/ <-- (selected, highlighted)
    +-- [>] Projects/
    [ New Folder ]
    +-----------------------------------------------+
    [ Cancel ] [ Move Here ]
    +-----------------------------------------------+


    6. Technical Requirements

    6.1 API Route Changes

    RouteCurrentChange
    GET /api/drive/filesLists workspace folder contents by pathAdd mode query param: mode=workspace (default, existing behavior) or mode=drive (lists by Drive folder ID). When mode=drive, accept folderId param instead of path. For root, use 'root' in parents.
    GET /api/drive/files/[id]Reads file by Drive file IDNo change needed. Already supports any file ID. Remove the "verify belongs to workspace" comment and the intent behind it.
    GET /api/drive/files/contentReads file by workspace-relative pathNo change needed. Continues to serve workspace-relative reads.
    NEW PUT /api/drive/files/[id]N/ARename a file: accepts { name: string }. Calls files.update.
    NEW PATCH /api/drive/files/[id]/moveN/AMove a file: accepts { newParentId: string, oldParentId: string }. Calls files.update with addParents/removeParents.
    NEW DELETE /api/drive/files/[id]N/ATrash a file: calls files.update with { trashed: true }.
    NEW POST /api/drive/filesN/ACreate a new folder: accepts { name: string, parentId: string, mimeType: "application/vnd.google-apps.folder" }.
    NEW POST /api/drive/files/exportN/AExport Google Workspace file as text: accepts { fileId: string, exportMimeType: string }. Returns plain text content. Used for Docs/Sheets/Slides attachment.

    6.2 Component Changes

    ComponentCurrentChange
    file-tree.tsxShows workspace root only. Fetches from GET /api/drive/files?path=/.Redesign to show two sections: (1) Pinned Workspace section fetching workspace root, (2) Full Drive section fetching GET /api/drive/files?mode=drive&folderId=root. Lazy-load children on folder expand.
    file-item.tsxRenders file/folder with expand/collapse.Add: (a) drag handle via HTML5 Drag and Drop API, setting dataTransfer with fileId, fileName, mimeType. (b) Right-click handler for context menu. (c) Visual distinction for Legionis workspace items (amber accent).
    file-preview.tsxMarkdown preview panel for workspace files.Extend to handle any Drive file. Fetch content via GET /api/drive/files/[id] for non-workspace files. Handle Google Workspace exports.
    NEW context-menu.tsxN/AFloating context menu component. Positioned at right-click coordinates. Options: Open, Rename, Move to, Delete, Copy Link. Triggers corresponding API calls.
    NEW move-dialog.tsxN/AModal dialog with folder tree browser for selecting move destination. "New Folder" button at bottom. Confirm/Cancel actions.
    NEW file-drop-zone.tsxN/AWraps the chat input area. Handles onDragOver, onDragLeave, onDrop events. On drop, extracts fileId from dataTransfer, creates attachment chip. Manages attachment state (array of { fileId, name, mimeType }).
    NEW file-attachment-chip.tsxN/AInline chip component: file icon + name + remove button. Displayed in chat input area above the text field.

    6.3 Agent Runtime Changes

    AreaCurrentChange
    Chat route (src/app/api/chat/route.ts)Accepts { messages, agentId }.Accept additional field attachments: Array<{ fileId: string, name: string, mimeType: string }>. For each attachment, fetch content (via Drive client), build context block, prepend to model messages as a system message.
    Tool: readFileReads by workspace-relative path.No change. Continues to resolve paths within workspace.
    Tool: writeFileWrites by workspace-relative path.Add boundary enforcement. Before calling workspace.writeFile(), verify the resolved target is a descendant of the workspace folder. Reject with error string if not.
    Tool: editFileReads then writes by workspace-relative path.Same boundary enforcement as writeFile. The read portion has no restriction; the write-back must target workspace.
    NEW Tool: readDriveFileN/ANew tool definition. Parameters: fileId: string. Description: "Read a file from the user's Google Drive by its file ID. Use this for files the user has attached to the conversation." Calls Drive API directly (not workspace path resolver). Handles Google Workspace export.
    System promptNo mention of Drive access boundaries.Append to L1 (base) system prompt: "File access: You can read any file the user attaches or shares (using readDriveFile). You can only write files to the Legionis workspace folder (using writeFile and editFile). Never attempt to modify files outside the workspace."
    ToolContextContains workspace, userId, agentId, provider, apiKey, workspaceId.Add driveClient: drive_v3.Drivenull for direct Drive access by readDriveFile. Add workspaceFolderId: stringnull for boundary checks.

    6.4 Drive Workspace Class Changes

    AreaCurrentChange
    DriveWorkspace constructorTakes rootFolderId (workspace folder).No change to the class itself. The workspace abstraction remains scoped to the workspace folder. The new readDriveFile tool bypasses this class and uses the Drive client directly.
    PathResolverResolves paths relative to workspace root.No change. Path resolution for workspace operations stays the same.
    NEW DriveExporterN/AUtility class in src/lib/drive/exporter.ts. Handles Google Workspace file export: exportAsText(drive, fileId, mimeType) => string. Maps: application/vnd.google-apps.document to text/plain, application/vnd.google-apps.spreadsheet to text/csv, application/vnd.google-apps.presentation to text/plain.

    6.5 Database Changes

    No schema changes required. The existing file_references table can optionally cache non-workspace file metadata for performance, but this is not required for the initial implementation. The workspaces.driveFolderId field already stores the workspace boundary reference needed for FR-4.


    7. Security and Privacy

    7.1 Permission Model

    ActorRead ScopeWrite Scope
    User (via explorer)Entire Drive (My Drive + Shared with me)Entire Drive (rename, move, delete, create folder)
    Agent (via tools)Any file the user attaches or references by file IDLegionis workspace folder and its descendants only
    Legionis backendOnly files accessed during active requests. No background scanning or indexing.Only workspace folder (for initialization and agent writes).

    7.2 Data Handling

    7.3 What Agents Cannot Do

    7.4 Boundary Enforcement Implementation

    The agent write boundary is enforced at two layers:

  • Tool layer (primary). The writeFile and editFile tools check that the resolved file ID is a descendant of workspaceFolderId before executing the write. This is a hard gate.
  • System prompt (advisory). The agent's system prompt explicitly instructs it to only write to the workspace. This reduces the frequency of boundary-rejected calls, but is not relied upon for security.
  • Layer 1 is the security boundary. Layer 2 is a UX optimization to avoid wasted API calls.


    8. Success Criteria

    #CriterionMeasurement
    SC-1User can browse their full Drive and navigate to any folder within 3 clicks from explorer root.Manual QA: navigate to a 3-level deep folder.
    SC-2User can drag a text file from any Drive folder into chat and the agent's response references its content.End-to-end test: drag file, send message, verify agent context.
    SC-3User can rename, move, and delete files anywhere in Drive via context menu. Operations reflect in Google Drive's native UI within 5 seconds.Manual QA: perform operation in Legionis, verify in Drive.
    SC-4Agent write to a path outside the workspace is rejected with an error.Automated test: mock agent writeFile call targeting a non-workspace path, assert rejection.
    SC-5Agent can read any attached file regardless of its Drive location.End-to-end test: attach file from "Shared with me," verify agent receives content.
    SC-6Google Docs, Sheets, and Slides are exportable as text when attached to chat.Automated test: attach each Google Workspace type, verify text extraction.
    SC-7File explorer loads the Drive root in under 2 seconds on a typical Drive (fewer than 500 root-level items).Performance benchmark with test account.
    SC-8The Legionis workspace folder is always visible and accessible with one click from the pinned section.Manual QA: verify pinned section is persistent across navigation.


    9. Out of Scope

    The following are explicitly excluded from this feature:

    ItemRationale
    Inline editing of Google Docs/Sheets/SlidesGoogle Workspace files have their own editors. Opening them in a new tab (via Copy Link) is sufficient.
    Real-time Drive sync / file watchingPolling or push notifications for Drive changes are a performance risk. Users refresh the explorer manually.
    Agent-initiated file moves or renamesAgents write deliverables. File organization is the user's domain. If needed later, it would require explicit user approval per operation.
    Shared Drives (Google Workspace enterprise)Shared Drives have different API semantics (supportsAllDrives, driveId). Supported in a future iteration if enterprise demand warrants it.
    Offline access or local cachingLegionis is online-first. No offline Drive browsing.
    Binary file content injectionImages, PDFs, and other binary files cannot be injected as text context. Metadata-only references are included. Multimodal support (image analysis) is a separate feature.
    Drag from desktop to chatOnly in-app drag from the Legionis file explorer is supported. Desktop file drag would require a different upload mechanism.
    Search across DriveFull-text search within the Drive explorer is not part of this spec. The existing glob and grep tools work within the workspace. Drive-wide search is a future enhancement.


    10. Open Questions

    #QuestionOwnerTarget Date
    OQ-1Should the "Shared with me" section be a top-level section in the explorer, or nested under My Drive? Google Drive treats it as a separate view.YohayBefore implementation
    OQ-2For Google Sheets with multiple tabs, should we export all tabs as CSV or only the first? Multiple tabs could produce large payloads.YohayDuring implementation
    OQ-3Should we add a "Pin" action to the context menu so users can pin frequently-used non-workspace folders to the top section alongside the Legionis workspace?YohayPost-MVP enhancement decision
    OQ-4Rate limiting on file management operations: should we throttle rapid renames/moves to avoid hitting Google Drive API quotas (1,000 queries per 100 seconds per user)?EngineeringDuring implementation


    Appendix: File Inventory

    Files to Create

    FilePurpose
    src/components/explorer/context-menu.tsxRight-click context menu for file management
    src/components/explorer/move-dialog.tsxFolder picker dialog for move operations
    src/components/chat/file-drop-zone.tsxDrop target wrapper for chat input
    src/components/chat/file-attachment-chip.tsxInline file attachment display
    src/tools/read-drive-file.tsNew agent tool for reading any Drive file by ID
    src/lib/drive/exporter.tsGoogle Workspace file export utility
    src/app/api/drive/files/[id]/move/route.tsMove file API route
    src/app/api/drive/files/export/route.tsGoogle Workspace export API route

    Files to Modify

    FileChange
    src/components/explorer/file-tree.tsxTwo-section layout (pinned workspace + full Drive), lazy loading by folder ID
    src/components/explorer/file-item.tsxDrag handle, right-click handler, workspace visual distinction
    src/components/explorer/file-preview.tsxSupport non-workspace files via file ID fetch
    src/app/api/drive/files/route.tsAdd mode=drive support, folder ID navigation, pagination
    src/app/api/drive/files/[id]/route.tsAdd PUT (rename) and DELETE (trash) handlers
    src/app/api/chat/route.tsAccept attachments array, fetch content, inject into context
    src/tools/write-file.tsAdd workspace boundary check before write
    src/tools/edit-file.tsAdd workspace boundary check before write-back
    src/tools/index.tsExport readDriveFile
    src/lib/agent/runtime.tsAdd readDriveFile to allTools, pass driveClient and workspaceFolderId in context
    src/lib/drive/resolve-workspace.tsReturn driveClient and workspaceFolderId alongside workspace
    src/lib/workspace/types.tsExtend ToolContext with driveClient and workspaceFolderId