# GPDoc Extension - AI Agent Rules

## IMPORTANT: Agent Suggestion Mode

Before editing any GPDoc file, check if the user has enabled "Agent Suggestion Mode" in VS Code settings (`gpdoc.agentSuggestionMode`).

### When Agent Suggestion Mode is ENABLED:
1. **DO NOT make direct edits** to the GPDoc file content
2. **Use suggestion mode** by updating `meta.suggestions` instead of `content.document`
3. **Add comments** to explain your changes in `meta.comments`
4. **Remind the user** in your response: "🔔 Agent Suggestion Mode is ON - Changes are being tracked as suggestions for your review."

### How to Make Suggestions (when enabled):
Instead of directly modifying `content.document`, update the file's metadata:

```json
{
  "meta": {
    "suggestions": {
      "enabled": true,
      "baselineContent": "<original content before changes>",
      "items": {
        "5": {
          "lineNumber": 5,
          "oldContent": "Original line content",
          "newContent": "Suggested new content",
          "changeType": "modified",
          "suggestedAt": "<ISO 8601 timestamp>",
          "applied": false
        },
        "10": {
          "lineNumber": 10,
          "oldContent": "",
          "newContent": "New line to insert",
          "changeType": "inserted",
          "suggestedAt": "<ISO 8601 timestamp>",
          "applied": false
        }
      }
    },
    "comments": {
      "threads": {
        "thread_<unique_id>": {
          "id": "thread_<unique_id>",
          "position": {
            "lineNumber": 5,
            "column": 1,
            "lineContent": "The line of text being commented on"
          },
          "resolved": false,
          "resolvedBy": null,
          "resolvedAt": null,
          "createdAt": "<ISO 8601 timestamp>",
          "updatedAt": "<ISO 8601 timestamp>",
          "comments": [
            {
              "id": "cmt_<unique_id>",
              "text": "I suggest changing this line because...",
              "author": {
                "userId": "ai-agent",
                "name": "AI Agent",
                "email": "",
                "avatar": null
              },
              "createdAt": "<ISO 8601 timestamp>",
              "updatedAt": "<ISO 8601 timestamp>"
            }
          ]
        }
      },
      "metadata": {
        "totalComments": 1,
        "resolvedComments": 0,
        "lastCommentAt": "<ISO 8601 timestamp>"
      }
    }
  }
}
```

### Suggestion Item Fields:
- `lineNumber` - 1-based line number in the document
- `oldContent` - Original text of the line (empty string for insertions)
- `newContent` - Suggested replacement text (empty string for deletions)
- `changeType` - One of: `"inserted"`, `"modified"`, `"deleted"`
- `suggestedAt` - ISO 8601 timestamp when the suggestion was made
- `applied` - Boolean, always `false` when creating new suggestions

### Change Types for Suggestions:
- `"inserted"` - New line being added
- `"modified"` - Existing line being changed
- `"deleted"` - Line being removed (set `newContent` to empty string)

### Comment Thread Structure:
Each comment is stored as a **thread** in `meta.comments.threads`, keyed by thread ID.
- A thread has a `position` (lineNumber, column, lineContent) and an array of `comments`
- Each comment has `text`, `author` (object with `name` and `email`), and timestamps
- Threads can be `resolved` (boolean) for tracking review status
- `meta.comments.metadata` tracks summary counts (`totalComments`, `resolvedComments`, `lastCommentAt`)

### When Agent Suggestion Mode is DISABLED:
Make direct edits to the content as described in the sections below.

---

## GPDoc File Structure

GPDoc files use the `.gpdoc.json` extension and have a specific JSON structure. When editing GPDoc files, AI agents MUST:

1. **Preserve the file structure**: Always maintain all top-level fields:
   - `id` - Unique identifier (DO NOT change)
   - `filetype` - One of: "document", "notebook", "slides", "script", "spreadsheet" (DO NOT change unless converting file type)
   - `filename` - Filename without extension (can be updated)
   - `content` - Type-specific content object (this is what you edit)
   - `created_at` - ISO 8601 timestamp (DO NOT change)
   - `updated_at` - ISO 8601 timestamp (MUST update to current time when editing)
   - `meta` - Metadata object (preserve existing fields, can add new ones)

2. **Update the `updated_at` field**: Always set to `new Date().toISOString()` when making any changes.

3. **Edit content based on filetype**:
   - **Document** (`filetype: "document"`): Edit `content.document` (markdown string)
   - **Notebook** (`filetype: "notebook"`): Edit `content.cells` (array of cell objects)
   - **Slides** (`filetype: "slides"`): Edit `content.slides` (array of markdown strings)
   - **Script** (`filetype: "script"`): Edit `content.script` (code string) and optionally `content.language`
   - **Spreadsheet** (`filetype: "spreadsheet"`): Edit `content.query` (SQL string) and `content.cells` (array)

## Editing Examples

### Editing a Document

When editing a GPDoc document, update `content.document` with the markdown content:

```json
{
  "id": "1234567890-abc123",
  "filetype": "document",
  "filename": "My Document",
  "content": {
    "document": "# Updated Title\n\nUpdated content here..."
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-15T12:00:00.000Z",
  "meta": {
    "location": "/"
  }
}
```

### Editing a Notebook

When editing a GPDoc notebook, update `content.cells` array:

```json
{
  "id": "1234567890-abc123",
  "filetype": "notebook",
  "filename": "My Notebook",
  "content": {
    "cells": [
      {
        "cell_type": "markdown",
        "source": "# Updated Notebook",
        "metadata": {}
      },
      {
        "cell_type": "code",
        "source": "console.log('Updated code');",
        "language": "javascript",
        "metadata": {}
      }
    ]
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-15T12:00:00.000Z",
  "meta": {
    "location": "/"
  }
}
```

### Editing a Script

When editing a GPDoc script, update `content.script`:

```json
{
  "id": "1234567890-abc123",
  "filetype": "script",
  "filename": "My Script",
  "content": {
    "script": "// Updated script code\nconsole.log('Hello');",
    "language": "typescript"
  },
  "created_at": "2024-01-01T00:00:00.000Z",
  "updated_at": "2024-01-15T12:00:00.000Z",
  "meta": {
    "location": "/"
  }
}
```

## Critical Rules

1. **NEVER delete required fields**: `id`, `filetype`, `filename`, `content`, `created_at`, `updated_at`, `meta` are all required.

2. **ALWAYS update `updated_at`**: Set to current ISO 8601 timestamp when making any changes.

3. **Preserve `id` and `created_at`**: These should never change.

4. **Maintain JSON structure**: Ensure valid JSON with proper formatting (2-space indentation recommended).

5. **Content structure varies by filetype**: 
   - Documents: `content.document` (string)
   - Notebooks: `content.cells` (array)
   - Slides: `content.slides` (array of strings)
   - Scripts: `content.script` (string) + `content.language` (string)
   - Spreadsheets: `content.query` (string) + `content.cells` (array)

6. **When adding new content**: 
   - For documents: Replace or append to `content.document` markdown string
   - For notebooks: Add new objects to `content.cells` array
   - For slides: Add new strings to `content.slides` array
   - For scripts: Replace `content.script` string
   - For spreadsheets: Update `content.query` SQL string

## Common Mistakes to Avoid

❌ **DON'T**: Edit just the `content` field directly without the nested structure
```json
// WRONG
{
  "content": "# New content"
}
```

✅ **DO**: Edit the type-specific content field
```json
// CORRECT for documents
{
  "content": {
    "document": "# New content"
  }
}
```

❌ **DON'T**: Forget to update `updated_at`
```json
// WRONG - updated_at not changed
{
  "updated_at": "2024-01-01T00:00:00.000Z"  // Old timestamp
}
```

✅ **DO**: Always update `updated_at`
```json
// CORRECT
{
  "updated_at": "2024-01-15T12:00:00.000Z"  // Current timestamp
}
```

❌ **DON'T**: Delete or modify `id` or `created_at`
```json
// WRONG
{
  "id": "new-id",  // Changed ID
  "created_at": "2024-01-15T00:00:00.000Z"  // Changed creation date
}
```

✅ **DO**: Preserve `id` and `created_at`
```json
// CORRECT
{
  "id": "1234567890-abc123",  // Original ID preserved
  "created_at": "2024-01-01T00:00:00.000Z"  // Original date preserved
}
```

## File Type Reference

### Document (`filetype: "document"`)
- Content location: `content.document`
- Format: Markdown string
- Example: `"# Title\n\nBody text"`

### Notebook (`filetype: "notebook"`)
- Content location: `content.cells`
- Format: Array of cell objects
- Cell structure: `{ cell_type: "markdown"|"code", source: string, language?: string, metadata: {} }`

### Slides (`filetype: "slides"`)
- Content location: `content.slides`
- Format: Array of markdown strings (one per slide)
- Example: `["# Slide 1", "# Slide 2"]`

### Script (`filetype: "script"`)
- Content location: `content.script`
- Format: Code string (TypeScript/JavaScript)
- Also includes: `content.language` (e.g., "typescript", "javascript")

### Spreadsheet (`filetype: "spreadsheet"`)
- Content location: `content.query`
- Format: SQL query string
- Also includes: `content.cells` (array, typically empty for SQL-based spreadsheets)

