Snu reference

From arnoudkooi/sn-scriptsync · View interactive version

Snu reference is an AI agent skill from the GitHub repository arnoudkooi/sn-scriptsync. Extended reference appendix: detailed file-structure notes, table metadata caching, agent best-practices, and edge cases not covered by the core. Read this when you need depth the other skills do not cover.

How to use this skill

Skill file

<!-- SN-SCRIPTSYNC:SKILL instructionsSchemaVersion=39 -->

SN ScriptSync — Deep Reference

Appendix and deep-dive reference material.

File Structure

ServiceNow files follow this pattern:

{workspace}/
  {instance}/                    # e.g., "myinstance"
    _settings.json               # Instance configuration
    _requests.log                # Log of completed requests
    agent/                       # Event-driven Agent API
      requests/                  # Place request files here
        req_abc123.json          # Individual request (you create)
      responses/                 # Responses appear here
        res_abc123.json          # Matching response (extension creates)
    {scope}/                     # e.g., "global", "x_myapp"
      {table}/                   # e.g., "sys_script_include"
        _map.json                # Maps sys_id to file names
        structure.json           # Table metadata (cached from ServiceNow)
        {name}.{field}.{ext}     # e.g., "MyUtils.script.js"

_structure.json(Table Metadata Cache)

The structure.json file contains cached table metadata from ServiceNow:

AI agents should:

  1. Check if structure.json exists first - read it instead of calling API
  2. If not exists, call get_table_metadata (which will create it)
  3. Use it to understand mandatory fields and reference requirements

Example structure.json:

{
  "columns": {
    "name": { "label": "Name", "type": "string", "mandatory": true, "max_length": 100 },
    "script": { "label": "Script", "type": "script_plain", "mandatory": false },
    "active": { "label": "Active", "type": "boolean", "default": "true" },
    "sys_scope": { "label": "Application", "type": "reference", "reference": "sys_scope" }
  }
}

Best Practices for AI Agents

🚫 DO NOT Use Cursor's Internal Browser Tools

Never use the built-in Cursor browser tools (mcp_cursor-ide-browser_*) for ServiceNow interactions:

Instead, use the Agent API commands:

🚫 Only Use Documented Slash Commands

Only use slash commands documented in SN Utils:

If unsure about a slash command, don't use it. Stick to the documented ones.

šŸš€ IMPORTANT: Always Check Connection First

Before ANY ServiceNow operations, call check_connection to verify readiness:

{ "id": "init", "command": "check_connection" }

If NOT ready, inform the user:

Save and verify before reporting completion

Follow the core Workflow: explicitly write the authorized changes and inspect the save result. A successful verified: true with matching persisted content needs no separate read-back. Only when the save is not already verified, read back and compare the saved content on the target instance. For VS Code file edits, inspect get_sync_status and call sync_now only if all eligible queued files belong to the task and review permits it. Wait for the intended files to leave the pending/syncing lists before reading them. The standalone host needs a typed record write instead of a file-queue flush.

synced: true means sent, not verified. If a save is held for approval, name the exact approval step; do not report completion or bypass the hold through another write route.

šŸ“ø Screenshot Permission Required

First-time screenshots require user action:

When taking the first screenshot in a session, the user must click the SN Utils extension icon on the target browser tab to grant permission.

AI Agent workflow:

  1. Call take_screenshot command
  2. If response contains permission error, inform the user:

> "Please click the SN Utils extension icon on the ServiceNow tab to grant screenshot permission, then I'll retry."

  1. Wait for user confirmation
  2. Retry the screenshot command

Subsequent screenshots will reuse the same tab and won't require re-approval.

🚫 Avoid Opening Duplicate Tabs

Before opening a new tab, check if a similar tab is already open:

Use activate_tab with reload: true instead of open_in_browser when you want to refresh an existing tab:

// āŒ DON'T open multiple tabs to the same URL
{ "command": "open_in_browser", "params": { "table": "rm_story", "sys_id": "abc123" } }
// (calling again opens ANOTHER tab)

// āœ… DO use activate_tab to refresh existing tab
{ "command": "activate_tab", "params": { 
  "url": "https://*.service-now.com/rm_story.do*sys_id=abc123*", 
  "reload": true,
  "waitForLoad": true 
}}

Guidelines:

⚔ PREFERRED: Use `create_artifact` for Creating New Records

The create_artifact command is the recommended way for AI agents to create artifacts:

āš ļø IMPORTANT: The name field is REQUIRED for ALL tables, even if the table's display field is different (like short_description for stories).

{
  "id": "1",
  "command": "create_artifact",
  "params": {
    "table": "sys_script_include",
    "scope": "global",
    "fields": {
      "name": "MyUtils",
      "script": "var MyUtils = Class.create();\nMyUtils.prototype = { initialize: function() {}, type: 'MyUtils' };"
    }
  }
}

Queue Behavior Note

| Operation | Behavior |

|-----------|----------|

| create_artifact (Agent API) | Writes or stages the request according to permissions/review; verify the created record |

| sync_now (VS Code Agent API) | Sends eligible queued files across the workspace; blocked in review mode; does not verify persistence |

| Local file edit | Monitored and queued by default (syncDelay: 0); auto-sync requires a positive delay |

| Standalone local file edit | Does not flush a VS Code queue; use a typed record write |

āš ļø Multi-File Artifacts (Widgets, UI Pages)

Prefer create_artifact with all intended fields for a new widget, or update_record_batch for changes to several fields of an existing widget. Respect review and inspect the save result. Only if it lacks successful verified: true confirmation covering every changed field, use get_record and compare those fields. For file-based edits, use the queue workflow above and check that the watcher detected all intended files; a fixed sleep or an empty queue is not proof of a save.

šŸ–„ļø Opening and Refreshing Widget Previews

After creating or updating a widget, you can open it in the browser and refresh it automatically:

Open widget preview:

{ "id": "open", "command": "open_in_browser", "params": { "table": "sp_widget", "name": "MyWidget", "scope": "global" } }

This opens: /$sp.do?id=sp-preview&sys_id={sys_id}

Refresh after changes:

{ "id": "refresh", "command": "refresh_preview", "params": { "table": "sp_widget", "name": "MyWidget", "scope": "global" } }

This refreshes all browser tabs showing the widget preview.

Recommended widget development flow:

1. check_connection           → Verify connected
2. create_artifact            → Create widget with all fields
3. open_in_browser            → Open preview in browser
4. (make changes to files)
5. Save through the authorized queue or typed-write route; collect any approval
6. Inspect the save result    → Only use get_record to compare content if the save is not already verified
7. refresh_preview            → Refresh browser and verify the changed behaviour
8. Report the saved/verified result, or the specific remaining blocker

Verifying the rendered widget (component-only screenshot):

To capture just the widget without a per-tab screenshot grant, pair activate_tab with the CDP capture_full_page selector:

{ "id": "act", "command": "activate_tab", "params": { "urlPattern": "sp-preview", "openIfNotFound": true, "waitForLoad": true } }
{ "id": "shot", "command": "capture_full_page", "params": { "selector": ".my-widget" } }

The selector trick returns a clean, component-only image (no full page, no per-tab grant). capture_full_page uses the browser debugger — preflight with get_capabilities (cdp.available).

Step-by-Step Workflow

  1. FIRST: Get table metadata (REQUIRED for any new artifact):

Step 1: Check for cached structure.json first:

```

{instance}/{scope}/{table}/structure.json

```

If this file exists, read it directly - no API call needed!

Step 2: If no cache, call the API:

```

{ "command": "get_table_metadata", "params": { "table": "sys_script_include" } }

```

This will also create/update structure.json for future use.

Step 3: Analyze the metadata for:

This determines if you need to ask questions before creating.

  1. Before creating a new artifact:
  1. Creating new artifacts (two methods):

Method 1: Agent API (PREFERRED)

```json

{ "command": "create_artifact", "params": { "table": "...", "fields": { ... } } }

```

Method 2: File creation (alternative)

āš ļø Common Mistake to Avoid:

```

āŒ WRONG (mixing code files with configuration files):

MyBusinessRule.script.js <- āœ… Code field (create file)

MyBusinessRule.collection.js <- āŒ Config field (DO NOT CREATE)

MyBusinessRule.when.js <- āŒ Config field (DO NOT CREATE)

MyBusinessRule.active.js <- āŒ Config field (DO NOT CREATE)

āœ… CORRECT (only code/content files):

MyBusinessRule.script.js <- āœ… Create this (contains code)

(collection, when, active in payload OR extension prompts)

āœ… CORRECT (UI Page with multiple code fields):

MyUIPage.html <- āœ… Create this (contains markup)

MyUIPage.processing_script.js <- āœ… Create this (contains code)

MyUIPage.client_script.js <- āœ… Create this (contains code)

(name, active, etc. in payload OR extension prompts)

```

  1. Wait for responses:
  1. Remote commands require:
  1. Complex tables with parent records:

Some tables CANNOT be created without a parent record:

| Table | Requires Parent | Parent Table | Notes |

|-------|-----------------|--------------|-------|

| sys_ws_operation | Yes | sys_ws_definition | REST API endpoint needs a REST API service |

| sys_script | Yes | Table reference | Business Rule needs a target table |

| sys_ui_action | Yes | Table reference | UI Action needs a target table |

| sys_script_client | Yes | Table reference | Client Script needs a target table |

| sys_dictionary | Yes | Table reference | Dictionary entry needs a table |

Before creating these artifacts:

  1. Recommended workflow for AI agents:

```

1. User requests: "Create a REST API endpoint"

2. AI calls: get_table_metadata for sys_ws_operation

→ Analyzes response, sees: web_service_definition is mandatory reference

3. AI calls: get_parent_options for sys_ws_definition

→ Gets list of existing REST API services

4a. IF options exist, AI asks:

"Which REST API service should this belong to?

4b. IF NO options exist, AI offers TWO options:

"No REST API services found. Choose an option:

Option 1: Create in ServiceNow (opens pre-filled form)

šŸ‘‰ Click here to create REST API Service

After creating, I can add the endpoint.

Option 2: I'll create both for you

I'll use create_artifact to create the REST API service first,

then create the endpoint with the reference."

5. User provides choice

6. AI calls: check_name_exists to avoid duplicates

7. AI uses create_artifact command:

{

"command": "create_artifact",

"params": {

"table": "sys_ws_operation",

"scope": "global",

"fields": {

"name": "getUsers",

"web_service_definition": "<parent_sys_id>",

"http_method": "GET",

"operation_script": "..."

}

}

}

```

āš ļø IMPORTANT: Guiding users is the AI agent's responsibility!

The sn-scriptsync extension cannot determine context or make decisions.

When no parent records exist, the AI agent MUST:

https://<instance>.service-now.com/<parent_table>_list.do

  1. When no parent record exists - Two options:

Option 1: User creates in ServiceNow (with pre-filled form)

Provide a link with sysparm_query to pre-fill the form:

```

https://<instance>.service-now.com/<table>.do?sys_id=-1&sysparm_query=name=<suggested_name>^active=true^sys_scope=<scope>

```

Example for REST API Service:

```

https://myinstance.service-now.com/sys_ws_definition.do?sys_id=-1&sysparm_query=name=HelloWorld API^active=true^sys_scope=x_myapp

```

Option 2: AI Agent creates the parent record (RECOMMENDED)

Use create_artifact to create the parent first, then the child:

```json

// Step 1: Create parent REST API service

{

"id": "1",

"command": "create_artifact",

"params": {

"table": "sys_ws_definition",

"scope": "global",

"fields": {

"name": "HelloWorld API",

"active": "true"

}

}

}

// Step 2: Wait for response, get sys_id from result

// Response: { "result": { "sys_id": "abc123def456...", "name": "HelloWorld API" } }

// Step 3: Create child with reference to parent sys_id

{

"id": "2",

"command": "create_artifact",

"params": {

"table": "sys_ws_operation",

"scope": "global",

"fields": {

"name": "getUsers",

"web_service_definition": "abc123def456...",

"http_method": "GET",

"operation_script": "(function process(request, response) { ... })(request, response);"

}

}

}

```

āš ļø IMPORTANT: Reference fields require sys_id!

When creating a child record that has a mandatory reference field:

āš ļø Do NOT suggest:

Generic URL pattern with pre-fill:

```

https://<instance>.service-now.com/<table>.do?sys_id=-1&sysparm_query=<field>=<value>^<field2>=<value2>

```

Common parent tables:

| Parent Type | Table | Key Fields to Pre-fill |

|-------------|-------|----------------------|

| REST API Service | sys_ws_definition | name, active, sys_scope |

| Table | sys_db_object | name, label, sys_scope |

| Application | sys_app | name, scope, version |

| Portal | sp_portal | title, url_suffix |

  1. Simple vs Complex artifacts:

Simple (can create directly):

Complex (ask questions first):


šŸ AI Agent Workflow Checklist

At Start of Session

1. ALWAYS confirm instance and scope:

2. For GLOBAL scope work: ALWAYS use a specific update set:

```

STRY0012345 - Implement user validation logic

```

Format: <Story Number> - <Story Short Description>

Workflow for update set management:

1. Query for existing update set (or create new one):
   { "command": "query_records", "params": { 
     "table": "sys_update_set", 
     "query": "nameLIKESTRY0012345^state=in progress", 
     "fields": "sys_id,name,state" 
   }}
   
2. If no update set exists, create one:
   { "command": "create_artifact", "params": { 
     "table": "sys_update_set", 
     "scope": "global", 
     "fields": { 
       "name": "STRY0012345 - Implement user validation logic",
       "state": "in progress"
     } 
   }}
   
3. Switch to the update set:
   { "command": "switch_context", "params": { 
     "switchType": "updateset", 
     "value": "<sys_id from step 1 or 2>" 
   }}
   
4. Now proceed with creating artifacts

3. ALWAYS call check_connection first:

{ "id": "init", "command": "check_connection" }

If ready: false, inform the user and STOP:

Before Completion

Explicitly save and verify the intended changes. Follow the core Workflow and the queue/review boundaries above. Inspect the save result first: a successful verified: true with matching persisted content needs no extra read. Only if that confirmation is absent, compare the stored fields using get_record. A successful send alone is not proof of persistence. Report local-only, awaiting approval and verified remote saves accurately.

Complete Example Flow

1. AI calls: { "command": "check_connection" }
   → If not ready, inform user and stop
   → If ready, proceed

2. AI calls: { "command": "clear_last_error" }
   → Clear any previous errors before starting

3. For GLOBAL scope: Ensure correct update set
   → Query for existing update set or create new one
   → Use story number format if from a story: "STRY0012345 - Description"
   → { "command": "switch_context", "params": { "switchType": "updateset", "value": "..." }}

4. AI creates/modifies artifacts using create_artifact or file changes

5. AI explicitly saves through the supported queue or typed-write route
   → Inspect the queue first; respect review and held user saves

6. AI inspects the save result; reads and compares the changed fields only if not already verified
   → Also check get_sync_status/get_last_error for file-sync failures

7. AI reports results:
   → If error: "āŒ Error: {error message}"
   → If success: "āœ… Done! Created MyUtils (sys_id: abc123)"

Why this matters:

Error Handling

Errors are automatically:

  1. Written to {instance}/_last_error.json for the instance that reported the error only
  2. Used to fail that instance's pending Agent API requests
  3. Available via get_last_error command

Common errors and solutions:

| Error | Solution |

|-------|----------|

| "ACL Error" | Change scope in browser to match the artifact's scope |

| "No valid token" | Run /token in ServiceNow browser session |

| "No WebSocket connection" | Open SN Utils helper tab |

| "User Not Authenticated" | Login to ServiceNow in browser |


šŸ”§ Updating Any ServiceNow Record (Advanced)

The sn-scriptsync extension can update any ServiceNow table, not just script artifacts. This is useful for adding work notes to incidents, updating task fields, etc.

āš ļø IMPORTANT: Use In-Memory Approach - Clean Up After

Do NOT leave temporary files in the workspace. Create the files, sync, then delete them immediately.

How It Works

  1. Create a temporary folder structure: {instance}/global/{table}/
  2. Create a _map.json with the record's sys_id
  3. Create a field file: {record_identifier}.{field_name}.txt
  4. Follow the queue workflow to save only the authorized changes, respecting review
  5. Read back and verify the change before deleting temporary files

Example: Adding a Work Note to an Incident

Step 1: Query the incident to get sys_id
{ "command": "query_records", "params": { "table": "incident", "query": "number=INC0010020", "fields": "sys_id,number,short_description" } }

Step 2: Update the record directly (no temp files!)
{ "command": "update_record", "params": { "table": "incident", "sys_id": "<sys_id>", "field": "work_notes", "content": "Your work note message here" } }

Step 3: Verify the journal entry before reporting completion; do not repeat the write if its outcome is uncertain
{ "command": "query_records", "params": { "table": "sys_journal_field", "query": "element_id=<sys_id>^element=work_notes", "fields": "value,sys_created_on", "limit": 1, "orderBy": "ORDERBYDESCsys_created_on" } }

Common Use Cases

| Task | Table | Field |

|------|-------|-------|

| Add incident work note | incident | work_notes |

| Add incident comment | incident | comments |

| Update task description | task | description |

| Update short description | incident | short_description |

| Add change work note | change_request | work_notes |

Field Types

Work Notes Formatting

Work notes support ServiceNow's wiki markup and basic HTML:

// Basic formatting
[code]<b>Bold Header</b>[/code]    → Bold text in a code-style block

// HTML tags work in work notes
<b>Bold</b>                        → Bold text
<i>Italic</i>                      → Italic text
<u>Underline</u>                   → Underlined text

// Lists (plain text works best)
• Item 1                           → Bullet point (use • character)
• Item 2

// Line breaks
Text line 1\nText line 2           → Use \n in JSON strings

Example work note:

{
  "command": "update_record",
  "params": {
    "table": "rm_story",
    "sys_id": "abc123",
    "field": "work_notes",
    "content": "[code]<b>šŸš€ Development Started</b>[/code]\n\nCreated update set: <b>STRY001 - My Feature</b>\n\n<b>Tasks:</b>\n• Create widget\n• Add styling\n• Test functionality"
  }
}

AI Agent Workflow for Record Updates (Direct API) ⚔

Preferred method - zero temporary files:

1. Query record to get sys_id (if not already known)
2. Use update_record command directly
3. Accept successful verified:true with matching persisted content; otherwise read back and compare (query sys_journal_field for journal entries)
4. Report the verified result, or the exact approval/verification blocker

Direct Update Commands

āš ļø IMPORTANT: Transaction Scope Required

For update operations, the extension automatically includes ?sysparm_transaction_scope=<SCOPE_SYS_ID> in the API request. Always ensure you're operating in the correct scope context.

`update_record` - Single field update
{
    "id": "unique-id",
    "command": "update_record",
    "params": {
        "sys_id": "a1b2c3d4e5f67890...",
        "table": "sys_script_include",
        "field": "script",
        "content": "var MyUtils = Class.create();\n...",
        "scope": "global"
    }
}

Response:

{
    "id": "unique-id",
    "command": "update_record",
    "status": "success",
    "result": {
        "success": true,
        "message": "Update sent for sys_script_include/a1b2c3d4e5f67890...",
        "table": "sys_script_include",
        "sys_id": "a1b2c3d4e5f67890...",
        "field": "script"
    }
}
`update_record_batch` - Multiple fields at once

Perfect for widgets (script + css + template) or any record with multiple code fields:

{
    "id": "unique-id",
    "command": "update_record_batch",
    "params": {
        "sys_id": "widget_sys_id...",
        "table": "sp_widget",
        "fields": {
            "script": "// Server script\ndata.message = 'Hello';",
            "client_script": "// Client script\nc.message = c.data.message;",
            "css": ".my-widget { color: blue; }",
            "template": "<div class=\"my-widget\">{{c.message}}</div>"
        }
    }
}

Response:

{
    "id": "unique-id",
    "command": "update_record_batch",
    "status": "success",
    "result": {
        "success": true,
        "message": "Updated 4 field(s) on sp_widget/widget_sys_id...",
        "table": "sp_widget",
        "sys_id": "widget_sys_id...",
        "fields": ["script", "client_script", "css", "template"]
    }
}

Benefits of Direct API

| Aspect | File-based (old) | Direct API (new) |

|--------|------------------|------------------|

| Disk writes | 4+ files | 1 file (_requests.json) |

| Cleanup needed | āœ… Must delete temp folder | āŒ None |

| Speed | Slow | Fast |

| Complexity | High | Low |

| Error-prone | Yes (cleanup failures) | No |

Legacy File-based Workflow (deprecated)

For reference only - prefer Direct API above:

1. Query record to get sys_id
2. Create temp folder: {instance}/global/{table}/
3. Create _map.json with sys_id mapping  
4. Create field file with content
5. Follow the queue/review workflow to save only the intended changes
6. Read back and verify the update
7. Delete only your temporary files after verification
8. Report result to user

āš ļø If using file-based workflow: Always delete the temporary folder after syncing.


šŸŽ“ Lessons Learned / Common Mistakes

Things to ALWAYS Do

  1. Check connection first - Call check_connection before any operations
  2. Use absolute paths for attachments - Copy filePath directly from take_screenshot response
  3. Include name field in create_artifact - Required for ALL tables
  4. Use HTML in acceptance_criteria - rm_story.acceptance_criteria is an HTML field
  5. Clean up request/response files - Delete both files after processing
  6. Use string values for state fields - Pass "-7" not -7
  7. Explicitly save and verify before completion - Follow the core Workflow; a local save or successful send is insufficient

Things to NEVER Do

  1. Don't use Cursor browser tools - Use Agent API commands instead (open_in_browser, take_screenshot, etc.)
  2. Don't use undocumented slash commands - Only use /tn, /bg, /token, etc.
  3. Don't open duplicate tabs - Use activate_tab with reload:true for existing tabs
  4. Don't use relative paths for screenshots - They resolve from instance folder, not workspace
  5. Don't assume state values - Query sys_choice to get valid values for choice fields
  6. Don't use markdown in HTML fields - Check field type in table metadata

Quick Reference: Agent API vs Cursor Browser Tools

| Task | āœ… Use Agent API | āŒ Don't Use |

|------|-----------------|--------------|

| Open ServiceNow page | open_in_browser / navigate | browser_navigate |

| Take screenshot | take_screenshot / navigate_and_screenshot | browser_take_screenshot |

| Click element | click_element (or set_field / run_ui_action) | browser_click |

| Set a form field | set_field | browser_type |

| Read page content | query_records / get_form_state | browser_snapshot |

| Refresh page | activate_tab with reload | browser_navigate |

| Run slash command | run_slash_command | Manual typing |

The Agent API uses the authenticated browser session via SN Utils, while Cursor browser tools open an unauthenticated separate session.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.