Skip to content

Open-source skills for designing and reviewing software with AI agents

feat(cursor): add experimental local Agent support (#164)

n3wth5220a0b18743
diff --git a/.cursor-plugin/agents/codebase_details.md b/.cursor-plugin/agents/codebase_details.md
new file mode 100644
index 0000000..98af66b
--- /dev/null
+++ b/.cursor-plugin/agents/codebase_details.md
@@ -0,0 +1,18 @@
+---
+name: egm-codebase-details
+description: Codebase details reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/codebase_details.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/comprehension.md b/.cursor-plugin/agents/comprehension.md
new file mode 100644
index 0000000..5990990
--- /dev/null
+++ b/.cursor-plugin/agents/comprehension.md
@@ -0,0 +1,18 @@
+---
+name: egm-comprehension
+description: Independent comprehension reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/comprehension.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/design_critic.md b/.cursor-plugin/agents/design_critic.md
new file mode 100644
index 0000000..7b14a2d
--- /dev/null
+++ b/.cursor-plugin/agents/design_critic.md
@@ -0,0 +1,18 @@
+---
+name: egm-design
+description: Design critique reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/design_critic.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/implementation_readiness.md b/.cursor-plugin/agents/implementation_readiness.md
new file mode 100644
index 0000000..50e2ecb
--- /dev/null
+++ b/.cursor-plugin/agents/implementation_readiness.md
@@ -0,0 +1,18 @@
+---
+name: egm-implementation-readiness
+description: Implementation readiness reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/implementation_readiness.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/structural.md b/.cursor-plugin/agents/structural.md
new file mode 100644
index 0000000..d9e276c
--- /dev/null
+++ b/.cursor-plugin/agents/structural.md
@@ -0,0 +1,18 @@
+---
+name: egm-structural
+description: Document structure reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/structural.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/style.md b/.cursor-plugin/agents/style.md
new file mode 100644
index 0000000..27ef8b7
--- /dev/null
+++ b/.cursor-plugin/agents/style.md
@@ -0,0 +1,18 @@
+---
+name: egm-style
+description: Technical style reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/style.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/agents/zoom_out.md b/.cursor-plugin/agents/zoom_out.md
new file mode 100644
index 0000000..87c31c9
--- /dev/null
+++ b/.cursor-plugin/agents/zoom_out.md
@@ -0,0 +1,18 @@
+---
+name: egm-zoom-out
+description: Simplicity and scope reviewer.
+model: inherit
+readonly: true
+permissionMode: readonly
+is_background: false
+---
+
+Require an absolute EGM_ROOT in the task. Read EGM_ROOT/agents/zoom_out.md
+first and follow that canonical persona. EGM_ROOT is a task value, not an
+environment variable. Resolve resources/ against that root.
+Read the absolute target and every supplied standard before returning findings.
+Use only the task and explicitly supplied Goldfish context.
+Do not edit files, run shell commands, access MCP services, or delegate.
+Return findings to the parent; the parent writes reports.
+If required paths or reads are unavailable, return an incomplete review,
+not a passing verdict.
diff --git a/.cursor-plugin/assets/icon.svg b/.cursor-plugin/assets/icon.svg
new file mode 100644
index 0000000..f5d50f6
--- /dev/null
+++ b/.cursor-plugin/assets/icon.svg
@@ -0,0 +1,12 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="1.5 1.5 21 21" width="64" height="64">
+ <!-- Copyright 2026 Google LLC. SPDX-License-Identifier: Apache-2.0 -->
+ <!-- Existing site favicon geometry, with fixed colors for plugin renderers. -->
+ <g fill="#1b6ef3" stroke="#1b6ef3" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <path stroke="none" d="M10.30,6.80 A5.20,5.20 0 0 0 10.30,17.20 A1.20,1.20 0 0 0 11.50,16.00 L11.50,8.00 A1.20,1.20 0 0 0 10.30,6.80Z"/>
+ <path fill="none" d="M7.20,12.00 C6.80,14.60 3.40,14.70 3.20,12.60 C3.10,11.20 3.30,10.20 3.60,9.40"/>
+ </g>
+ <g fill="#e86e00" stroke="#e86e00" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
+ <path stroke="none" d="M13.70,6.80 A5.20,5.20 0 0 1 13.70,17.20 A1.20,1.20 0 0 1 12.50,16.00 L12.50,8.00 A1.20,1.20 0 0 1 13.70,6.80Z"/>
+ <path fill="none" d="M16.80,12.00 L18.00,12.00 C18.80,12.00 19.40,10.60 20.90,9.40 M18.00,12.00 C18.80,12.00 19.40,13.40 20.90,14.60"/>
+ </g>
+</svg>
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
new file mode 100644
index 0000000..1e2120a
--- /dev/null
+++ b/.cursor-plugin/plugin.json
@@ -0,0 +1,13 @@
+{
+ "name": "egm",
+ "version": "0.1.0",
+ "description": "Draft specs, review designs, and check implementation drift.",
+ "author": {"name": "Google"},
+ "homepage": "https://egm.dev",
+ "repository": "https://github.com/google/elephant-goldfish-model",
+ "license": "Apache-2.0",
+ "logo": ".cursor-plugin/assets/icon.svg",
+ "skills": "./skills/",
+ "agents": "./.cursor-plugin/agents/",
+ "rules": "./.cursor-plugin/rules/"
+}
diff --git a/.cursor-plugin/rules/egm.mdc b/.cursor-plugin/rules/egm.mdc
new file mode 100644
index 0000000..7605af7
--- /dev/null
+++ b/.cursor-plugin/rules/egm.mdc
@@ -0,0 +1,35 @@
+---
+description: Cursor runtime routing for EGM workflows only.
+alwaysApply: true
+---
+
+Apply these instructions only to an EGM workflow.
+Before execution, identify the absolute path of the selected EGM SKILL.md.
+For EGM_ROOT/skills/<directory>/SKILL.md, ascend three directories to EGM_ROOT.
+Confirm that EGM_ROOT/.cursor-plugin/plugin.json,
+EGM_ROOT/agents/, EGM_ROOT/resources/, and EGM_ROOT/docs/cursor.md exist.
+If the skill path is unavailable, ask for the installed package's absolute path.
+Read EGM_ROOT/docs/cursor.md before following the canonical skill.
+Do not infer a cache location or use another installed EGM version.
+
+Resolve agents/, resources/, and docs/ against EGM_ROOT. Resolve references/
+against the invoked skill directory. Pass absolute file paths to each child.
+This path mapping does not depend on variable substitution in Markdown.
+
+Keep drafting, synthesis, remediation, and report writes in the parent.
+Use direct Task dispatch to the registered EGM reviewer types.
+Start a new task for every independent reviewer. Never resume a reviewer.
+Supply EGM_ROOT, the target and scope, persona and standard paths, and only
+the explicit Goldfish context. Do not include parent history or deliberation.
+Do not pass earlier findings except where the canonical workflow requires them.
+Do not dispatch the canonical synthesizer or bootstrap orchestrator as a
+generic child. Their native adapters are not included in this experiment.
+
+Wait for every reviewer completion before advancing the stage.
+Write each completed stage report before dispatching the next stage.
+For Step 8, pass the absolute path of the existing zoom_out_report.md to the
+reviewer. If the report is missing, stop the review.
+Keep the canonical stage order and human approval gates.
+If a reviewer cannot start, read required files, or finish, stop the stage.
+Report the incomplete review. Do not simulate a reviewer in the parent.
+Missing host evidence leaves isolation unverified, even if findings exist.
diff --git a/.github/workflows/cursor-native.yml b/.github/workflows/cursor-native.yml
new file mode 100644
index 0000000..6b64551
--- /dev/null
+++ b/.github/workflows/cursor-native.yml
@@ -0,0 +1,49 @@
+# Copyright 2026 Google LLC
+# SPDX-License-Identifier: Apache-2.0
+
+# Native loader discovery only. This job does not authenticate or call a model.
+name: Cursor native discovery
+
+on:
+ pull_request:
+ paths:
+ - '.cursor-plugin/**'
+ - 'skills/**'
+ - 'agents/**'
+ - 'resources/**'
+ - 'docs/**'
+ - 'LICENSE'
+ - 'plugin.json'
+ - 'pyproject.toml'
+ - 'tests/conftest.py'
+ - 'tests/unit/test_cursor.py'
+ - 'tests/unit/test_harnesses.py'
+ - '.github/workflows/cursor-native.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ discovery:
+ runs-on: ubuntu-24.04-arm
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+ - run: python -m pip install pytest==8.3.5 pyyaml==6.0.2
+ - name: Download pinned Cursor CLI
+ run: |
+ curl --fail --location --retry 3 --output "$RUNNER_TEMP/cursor.tar.gz" \
+ https://downloads.cursor.com/lab/2026.10.01-e373342/linux/arm64/agent-cli-package.tar.gz
+ echo '785c5f6bf2a60eb1121e27ed8c14f5ee07ed1b5b6692324f2d9a997238245eb5 '"$RUNNER_TEMP/cursor.tar.gz" | sha256sum --check
+ mkdir "$RUNNER_TEMP/cursor"
+ tar -xzf "$RUNNER_TEMP/cursor.tar.gz" --strip-components=1 -C "$RUNNER_TEMP/cursor"
+ - name: Verify native loader
+ env:
+ EGM_CURSOR_BUNDLE: '${{ runner.temp }}/cursor/index.js'
+ run: python -m pytest tests/unit/test_cursor.py
diff --git a/docs/cursor.md b/docs/cursor.md
new file mode 100644
index 0000000..2c4cc8a
--- /dev/null
+++ b/docs/cursor.md
@@ -0,0 +1,214 @@
+<!--
+Copyright 2026 Google LLC.
+SPDX-License-Identifier: Apache-2.0
+-->
+
+# Cursor integration (experimental)
+
+This adapter targets Cursor local Agent. Installation, workflow, and isolation
+remain unverified. Do not add Cursor to the supported-host table yet.
+See the [design](designs/additional-harnesses.md) and [issue #145](https://github.com/google/elephant-goldfish-model/issues/145).
+
+## Interface and version
+
+The selected CLI reference is `2026.10.01-e373342`, inspected on 2026-10-24.
+Its help lists `--plugin-dir`, `--model`, `--workspace`, and `--output-format`.
+Help, version, and the native offline loader probe ran. No model or reviewer ran.
+This is an inspected version, not a verified minimum version.
+
+The first version command stopped at a locked macOS keychain.
+The launcher's per-command `AGENT_CLI_CREDENTIAL_STORE=file` setting allowed
+help and version inspection. No account configuration changed.
+
+The native manifest is `.cursor-plugin/plugin.json`. It selects shared
+`skills/`, Cursor adapters in `.cursor-plugin/agents/`, and the Cursor rule in
+`.cursor-plugin/rules/`. The explicit agent path excludes raw shared personas.
+Each reviewer declares `readonly: true`, `permissionMode: readonly`,
+`model: inherit`, and `is_background: false`.
+The selected CLI's plugin loader reads `permissionMode`, not `readonly`.
+The documented `readonly` field remains for the local Agent interface.
+The native loader probe confirms all seven reviewers register as read-only.
+This does not prove runtime enforcement or foreground behavior.
+Select a model explicitly for a future live run and
+record its actual identifier from the task records.
+
+Sources: [plugin reference](https://cursor.com/docs/reference/plugins),
+[subagent configuration and context](https://cursor.com/docs/subagents), and
+[local plugin installation](https://cursor.com/docs/plugins#test-plugins-locally).
+These sources describe host capabilities, not EGM verification results.
+
+## Install a candidate
+
+Use a clean Cursor profile with no other EGM installation.
+Local imports must be permitted by the host policy.
+Do not disable an organization policy or overwrite an existing package.
+
+1. Check out the candidate commit in a clean EGM checkout.
+2. Run these commands from that checkout:
+
+ ```sh
+ git diff --exit-code HEAD
+ egm_candidate="$HOME/.cursor/plugins/local/egm"
+ mkdir -p "$(dirname "$egm_candidate")"
+ mkdir "$egm_candidate" && {
+ cp -R .cursor-plugin skills agents resources docs LICENSE "$egm_candidate/" &&
+ git rev-parse HEAD > "$egm_candidate/.egm-source-sha"
+ }
+ ```
+
+3. Stop if a command fails. Inspect any partial copy before retrying.
+4. Reload Cursor and inspect the plugin in Customize.
+5. Confirm seven skills, seven EGM reviewers, and the EGM runtime rule.
+6. Record the absolute package path and installed file checksums.
+
+The copy retains all shared runtime directories and their relative layout.
+It excludes the portable root manifest to select the Cursor format explicitly.
+It contains no symlink to an external checkout.
+The shared source files remain unchanged.
+
+The inspected CLI also accepts a temporary candidate through
+`agent --plugin-dir /absolute/path/to/cursor-package`.
+That command starts an agent and can incur model usage. Run it only after
+explicit authorization for live tests. Do not use force or automatic MCP approval.
+
+## Invoke the workflow
+
+Before the first skill, provide the installed root to the local Agent:
+
+```text
+EGM_ROOT: /absolute/path/to/cursor-package
+Read /absolute/path/to/cursor-package/docs/cursor.md.
+Run /egm-brainstorm for the requested feature.
+```
+
+Select the installed EGM skill from Cursor's slash menu.
+If a skill is not exposed, read its absolute `skills/<directory>/SKILL.md`
+and follow it in the parent context. Do not invent a slash-command namespace.
+Use the same process for `egm-draft`, `egm-review`, and workflow subskills.
+The adapter rule must be active before execution.
+
+Resolve `agents/`, `resources/`, and `docs/` against the selected package root.
+Resolve a skill's `references/` against that skill's directory.
+Do not assume Markdown expands `${CURSOR_PLUGIN_ROOT}` or `${CLAUDE_PLUGIN_ROOT}`.
+Host-specific instructions for Claude and Codex do not select the Cursor runtime.
+
+Keep the synthesizer's orchestration in the parent and dispatch reviewers directly.
+Read `agents/synthesizer.md` for its canonical synthesis instructions when needed.
+Do not create an unrestricted synthesizer child. Bootstrap child delegation is
+outside this experimental adapter; stop if the requested operation requires it.
+
+For each review, start a new native Task of the registered persona type.
+Pass the absolute package root, persona, target, scope, and required standards.
+Pass only explicit Goldfish context, without parent deliberation or history.
+Include previous reports only when the canonical stage explicitly requires them.
+Collect each completion before the next stage. Never reuse a reviewer context.
+Write each completed stage report before dispatching the next stage.
+For Step 8, pass the absolute path of the existing `zoom_out_report.md` to the
+reviewer. Stop if that report is missing.
+If dispatch, required reads, or completion fails, report an incomplete stage and stop.
+Do not replace native reviewers with an in-thread simulation.
+
+The parent writes artifacts to the user's working directory.
+Honor `EGM artifact directory: <path>` in the user's prompt or instruction file.
+Resolve a relative override against the working directory and create it if needed.
+Never write reports into the installed plugin. Preserve canonical approval pauses.
+
+## Verification gates
+
+Offline checks run with `pytest tests/unit/test_cursor.py` or `pytest tests/unit`.
+They check metadata, native configuration, and a relocated package with spaces
+and Unicode in its path. The optional native check skips without a local bundle.
+
+Run the native loader probe against the inspected arm64 CLI bundle on macOS or Linux:
+
+```sh
+EGM_CURSOR_BUNDLE="$HOME/.local/share/cursor-agent/versions/2026.10.01-e373342/index.js" \
+ pytest tests/unit/test_cursor.py
+```
+
+The probe pins Cursor CLI `2026.10.01-e373342` by platform and bundle SHA-256:
+
+- macOS arm64: `f6bd8dece34b56431ee74f1ac827e032d054381085e7da7088e85abdd1008330`.
+- Linux arm64: `90ec23826cd3089232b0b243b8954ac72fab0454dd86d7d71ddae29d39c75cd2`.
+
+The Linux bundle comes from Cursor's [versioned package](https://downloads.cursor.com/lab/2026.10.01-e373342/linux/arm64/agent-cli-package.tar.gz).
+Its downloaded archive SHA-256 was `785c5f6bf2a60eb1121e27ed8c14f5ee07ed1b5b6692324f2d9a997238245eb5`.
+These hashes identify the inspected files. They are not vendor signatures.
+It invokes the installed plugin loader without the CLI entry point.
+It blocks network connections and subprocess launches within the probe.
+It does not patch the installed CLI or start a model session.
+The private loader export is version-specific. Re-audit it before changing the pin.
+
+The probe discovers seven skills, seven read-only reviewer registrations, and
+one active rule in the relocated package. Initially, `readonly: true` alone
+registered default permissions. The added `permissionMode` field corrects that result.
+These are native parsing results, not interactive installation or runtime evidence.
+This historical note does not identify the tested EGM commit or installed package
+checksum. Repeat discovery against the pinned candidate before relying on it for
+that candidate.
+
+Before a live run, obtain explicit approval for model usage.
+Use a clean workspace and profile without unrelated MCP services or memory.
+Record the candidate SHA, package checksums, host version, surface, model, and date.
+Keep these results separate:
+
+| Gate | Required evidence | Current result |
+| --- | --- | --- |
+| Installation | Interactive discovery and actual reads of installed personas, standards, and guides | Unverified; offline native discovery passed |
+| Workflow | Brainstorm, draft, review, artifacts, and an actual human approval pause | Unverified |
+| Isolation | Fresh child records, required reads, read-only denial, and every reviewer completion | Unverified |
+
+For isolation, place a random marker only in the parent conversation.
+Inspect the child input and tool records as well as its answer.
+Probe write denial against a disposable fixture and verify its bytes remain unchanged.
+The native read-only mode restricts writes; it is not a filesystem boundary.
+The prompt also forbids shell and MCP use, but these are not proven tool allowlists.
+Assess injected rules, repository instructions, memory, MCP access, and shared files
+separately. A fresh task does not remove those possible sources of information.
+
+Record native reviewer starts and completions, not only the parent's summary.
+Missing records leave the corresponding gate unverified.
+For CLI `2026.10.01-e373342`, `tests/integration/cursor_child_reads.py` checks
+one child's SQLite store for matching `ReadFile` calls and successful results:
+
+```sh
+python tests/integration/cursor_child_reads.py /absolute/path/to/child/store.db \
+ --required /absolute/path/to/persona.md
+```
+
+Select the store using the child ID from its matched parent Task completion.
+After the child stops, use SQLite's backup API to create a closed snapshot.
+The command rejects a snapshot with a WAL file or a changing main file.
+The command exits nonzero if a required path lacks a matched nonempty success.
+The store and output may contain private paths. Keep them private.
+The command checks reads only. It does not validate dispatch, approvals, stage
+order, isolation, or artifacts. The store schema is private and version-specific.
+It counts opaque binary blobs but cannot interpret their contents.
+No complete Cursor workflow trace parser is supplied. Before accepting one, test
+missing starts, missing completions, malformed records, and Unicode line
+separators. Split JSONL on literal LF only.
+Existing Claude and Codex trace tests do not validate Cursor evidence.
+
+## Grok Bot assessment
+
+Grok Bot remains a separate, unverified surface. No Grok Bot adapter is included.
+Its [work guide](https://cursor.com/docs/grok-bot/work) describes retained memory
+and a shared computer. These can expose previous findings to another reviewer.
+Local Cursor results cannot establish Grok Bot compatibility.
+
+| Requirement | Assessment |
+| --- | --- |
+| Full package import and resource reads | Not tested |
+| Fresh reviewer context | Not tested; retained memory requires a separate probe |
+| Read-only enforcement | Not tested |
+| Native starts and completions | Not tested |
+| Human approval pauses | Not tested |
+| Prior findings in memory and shared files | Not tested; inspect both independently |
+
+Propose any Grok Bot implementation separately after these checks.
+
+## Remove the candidate
+
+Disable the local EGM plugin in Cursor.
+Remove only the candidate folder that you created, then reload Cursor.
+Retain workspace artifacts and verification evidence.
diff --git a/tests/integration/cursor_child_reads.py b/tests/integration/cursor_child_reads.py
new file mode 100644
index 0000000..73fcc33
--- /dev/null
+++ b/tests/integration/cursor_child_reads.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+# Copyright 2026 Google LLC.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Correlate native Cursor ReadFile calls and successes in one child store."""
+
+import argparse
+import hashlib
+import json
+import sqlite3
+from pathlib import Path
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('database', type=Path)
+ parser.add_argument('--required', action='append', required=True)
+ args = parser.parse_args()
+ database = args.database.resolve(strict=True)
+ wal = Path(str(database) + '-wal')
+ if wal.exists():
+ raise ValueError('Provide a closed SQLite backup without a WAL file')
+ before_hash = hashlib.sha256(database.read_bytes()).hexdigest()
+ connection = sqlite3.connect(f'{database.as_uri()}?mode=ro', uri=True)
+ calls: dict[str, str] = {}
+ results: dict[str, dict] = {}
+ failures: set[str] = set()
+ opaque_blobs = 0
+ for (data,) in connection.execute('SELECT data FROM blobs'):
+ try:
+ message = json.loads(data)
+ except (ValueError, TypeError, UnicodeDecodeError) as error:
+ prefixes = ('{', '[') if isinstance(data, str) else (b'{', b'[')
+ if isinstance(data, (str, bytes)) and data.lstrip().startswith(prefixes):
+ raise ValueError('Malformed JSON-looking blob') from error
+ opaque_blobs += 1
+ continue
+ if not isinstance(message, dict):
+ raise ValueError('Unexpected JSON blob structure')
+ if message.get('role') not in ('assistant', 'tool'):
+ continue
+ if not isinstance(message.get('content'), list):
+ raise ValueError('Malformed assistant or tool content')
+ for entry in message.get('content', []):
+ if not isinstance(entry, dict):
+ raise ValueError('Malformed content entry')
+ call_id = entry.get('toolCallId')
+ if entry.get('toolName') != 'ReadFile':
+ continue
+ if not isinstance(call_id, str) or not call_id:
+ raise ValueError('ReadFile entry lacks a call ID')
+ expected_type = 'tool-call' if message['role'] == 'assistant' else 'tool-result'
+ if entry.get('type') != expected_type:
+ raise ValueError(f'Unexpected ReadFile entry type {call_id}')
+ if message.get('role') == 'assistant' and entry.get('type') == 'tool-call':
+ arguments = entry.get('args')
+ path = arguments.get('path') if isinstance(arguments, dict) else None
+ if not isinstance(path, str) or not path:
+ raise ValueError('ReadFile call lacks a path')
+ if call_id in calls and calls[call_id] != path:
+ raise ValueError(f'Conflicting call {call_id}')
+ calls[call_id] = path
+ if message.get('role') == 'tool' and entry.get('type') == 'tool-result':
+ high_level = (message.get('providerOptions', {}).get('cursor', {})
+ .get('highLevelToolCallResult', {}))
+ is_error = high_level.get('isError')
+ if is_error is True:
+ failures.add(call_id)
+ elif is_error is False:
+ success = high_level.get('output', {}).get('success')
+ if not isinstance(success, dict):
+ raise ValueError(f'Malformed result {call_id}')
+ if call_id in results and results[call_id] != success:
+ raise ValueError(f'Conflicting result {call_id}')
+ results[call_id] = success
+ else:
+ raise ValueError(f'Malformed result status {call_id}')
+ connection.close()
+ if wal.exists() or hashlib.sha256(database.read_bytes()).hexdigest() != before_hash:
+ raise ValueError('SQLite store changed while being read')
+ reads = []
+ if failures & results.keys():
+ raise ValueError('A read has conflicting success and error outcomes')
+ for call_id, path in calls.items():
+ result = results.get(call_id)
+ if not result or result.get('path') != path:
+ continue
+ content = result.get('content')
+ if not isinstance(content, str) or not content.strip():
+ continue
+ reads.append({'call_id': call_id, 'path': path, 'bytes': len(content.encode()),
+ 'sha256': hashlib.sha256(content.encode()).hexdigest()})
+ missing = sorted(set(args.required) - {read['path'] for read in reads})
+ print(json.dumps({'database_main_sha256': before_hash, 'opaque_blobs': opaque_blobs,
+ 'reads': reads, 'missing': missing}, indent=2))
+ return bool(missing)
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/tests/unit/test_cursor.py b/tests/unit/test_cursor.py
new file mode 100644
index 0000000..e21913c
--- /dev/null
+++ b/tests/unit/test_cursor.py
@@ -0,0 +1,175 @@
+# Copyright 2026 Google LLC.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Offline Cursor package contracts, not native workflow or isolation proof."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shutil
+import subprocess
+
+import pytest
+
+from .test_harnesses import REVIEWERS, frontmatter
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def installed(tmp_path: Path) -> Path:
+ """Reproduce the documented copy, without another host's manifest."""
+ package = tmp_path / "Cursor candidate café" / "egm"
+ package.mkdir(parents=True)
+ for name in (".cursor-plugin", "skills", "agents", "resources", "docs"):
+ shutil.copytree(ROOT / name, package / name)
+ shutil.copy2(ROOT / "LICENSE", package / "LICENSE")
+ return package
+
+
+def test_manifest_selects_native_adapters(installed: Path) -> None:
+ manifest = json.loads(
+ (installed / ".cursor-plugin/plugin.json").read_text(encoding="utf-8")
+ )
+ canonical = json.loads((ROOT / "plugin.json").read_text(encoding="utf-8"))
+ for field in ("name", "version", "homepage",
+ "repository", "license"):
+ assert manifest[field] == canonical[field]
+ assert manifest["author"] == {"name": "Google"}
+ assert manifest["description"] == "Draft specs, review designs, and check implementation drift."
+ assert manifest["skills"] == "./skills/"
+ assert manifest["agents"] == "./.cursor-plugin/agents/"
+ assert manifest["rules"] == "./.cursor-plugin/rules/"
+ assert set(manifest) == {
+ "name", "version", "description", "author", "homepage", "repository",
+ "license", "skills", "agents", "rules", "logo",
+ }
+ assert not (installed / "plugin.json").exists()
+ assert (installed / manifest["logo"]).is_file()
+ for component in ("skills", "agents", "rules"):
+ assert (installed / manifest[component]).is_dir()
+ adapters = installed / manifest["agents"]
+ assert {p.stem for p in adapters.glob("*.md")} == set(REVIEWERS)
+
+
[email protected]("name", sorted(REVIEWERS))
+def test_reviewers_use_canonical_personas(installed: Path, name: str) -> None:
+ adapter = installed / ".cursor-plugin/agents" / f"{name}.md"
+ config = frontmatter(adapter)
+ persona = installed / "agents" / f"{name}.md"
+ assert config["name"] == frontmatter(persona)["name"]
+ assert config["readonly"] is True
+ assert config["permissionMode"] == "readonly"
+ assert config["is_background"] is False
+ assert config["model"] == "inherit"
+ assert set(config) == {
+ "name", "description", "model", "readonly", "permissionMode", "is_background",
+ }
+ text = adapter.read_text(encoding="utf-8")
+ paths = re.findall(r"EGM_ROOT/([\w/.-]+\.md)", text)
+ assert paths == [f"agents/{name}.md"]
+ assert all((installed / path).is_file() for path in paths)
+ assert "incomplete review" in text
+ assert len(text.splitlines()) < 25 # Routing only, no copied persona rules.
+ assert persona.read_bytes() == (ROOT / "agents" / persona.name).read_bytes()
+
+
+def test_relocated_package_keeps_all_canonical_resources(installed: Path) -> None:
+ for folder in ("skills", "agents", "resources", "docs"):
+ for source in (ROOT / folder).rglob("*"):
+ if source.is_file():
+ destination = installed / source.relative_to(ROOT)
+ assert not destination.is_symlink()
+ assert destination.read_bytes() == source.read_bytes()
+ for prompt in [*installed.glob("skills/*/SKILL.md"),
+ *installed.glob("agents/*.md")]:
+ if prompt.name == "SKILL.md":
+ assert prompt.parents[2] == installed
+ text = prompt.read_text(encoding="utf-8")
+ for target in re.findall(
+ r"`((?:agents|resources|references)/[^`\s]+\.md)`", text
+ ):
+ if any(char in target for char in "{}[]<>"):
+ continue
+ base = prompt.parent if target.startswith("references/") else installed
+ assert (base / target).is_file(), f"{prompt}: missing {target}"
+ for target in re.findall(r"\[[^\]]+\]\(([^)]+)\)", text):
+ if target.startswith("../../"):
+ assert (prompt.parent / target.split("#")[0]).is_file()
+
+
+def test_host_rule_and_guide_keep_failure_and_artifact_contracts() -> None:
+ rule = ROOT / ".cursor-plugin/rules/egm.mdc"
+ assert frontmatter(rule)["alwaysApply"] is True
+ text = " ".join(rule.read_text(encoding="utf-8").split())
+ for contract in (
+ "EGM_ROOT/docs/cursor.md", "absolute file paths", "Never resume",
+ "human approval gates", "stop the stage", "Do not simulate",
+ ):
+ assert contract in text
+ guide = " ".join((ROOT / "docs/cursor.md").read_text(encoding="utf-8").split())
+ assert "EGM artifact directory: <path>" in guide
+ assert "Grok Bot remains a separate, unverified surface" in guide
+ assert "No complete Cursor workflow trace parser is supplied" in guide
+
+
+def test_installed_cursor_native_loader(installed: Path) -> None:
+ """Opt-in probe of the actual pinned loader, with no CLI main or model call."""
+ bundle_path = os.environ.get("EGM_CURSOR_BUNDLE")
+ if not bundle_path:
+ pytest.skip("Set EGM_CURSOR_BUNDLE for the pinned native offline probe")
+ bundle = Path(bundle_path).resolve()
+ pins = {
+ ("Darwin", "arm64"): "f6bd8dece34b56431ee74f1ac827e032d054381085e7da7088e85abdd1008330",
+ ("Linux", "aarch64"): "90ec23826cd3089232b0b243b8954ac72fab0454dd86d7d71ddae29d39c75cd2",
+ }
+ expected = pins.get((platform.system(), platform.machine()))
+ assert expected, "The native loader probe has not been audited on this platform"
+ assert hashlib.sha256(bundle.read_bytes()).hexdigest() == expected, (
+ "Re-audit the private loader interface before changing this version pin"
+ )
+ script = r'''
+const fs = require('node:fs')
+const Module = require('node:module')
+const [filename, packageRoot] = process.argv.slice(1)
+const entry = 'var __webpack_exports__=__webpack_require__("./src/main.tsx")'
+const source = fs.readFileSync(filename, 'utf8')
+if (!source.includes(entry)) throw new Error('Unrecognized bundle entry')
+const deny = () => { throw new Error('Network/process use forbidden in offline probe') }
+require('node:net').Socket.prototype.connect = deny
+globalThis.fetch = deny
+for (const key of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {
+ require('node:child_process')[key] = deny
+}
+const loaded = new Module(filename, module)
+loaded.filename = filename
+loaded.paths = Module._nodeModulePaths(require('node:path').dirname(filename))
+loaded._compile(source.replace(entry,
+ 'module.exports=__webpack_require__("../cursor-plugins/dist/index.js")'), filename)
+loaded.exports.Y__(packageRoot, 'egm').then(plugin => {
+ console.log(JSON.stringify({
+ skills: plugin.skills.map(skill => skill.name),
+ agents: plugin.agents.map(({ name, model, permissionMode }) => ({ name, model, permissionMode })),
+ rules: plugin.rules.map(({ alwaysApply }) => ({ alwaysApply }))
+ }))
+}).catch(error => { console.error(error.message); process.exitCode = 1 })
+'''
+ result = subprocess.run(
+ [str(bundle.parent / "node"), "-e", script, str(bundle), str(installed)],
+ capture_output=True, text=True, check=True, timeout=30,
+ )
+ native = json.loads(result.stdout)
+ assert set(native["skills"]) == {
+ frontmatter(path)["name"] for path in (ROOT / "skills").glob("*/SKILL.md")
+ }
+ expected_agents = {
+ frontmatter(ROOT / "agents" / f"{name}.md")["name"] for name in REVIEWERS
+ }
+ assert {agent["name"] for agent in native["agents"]} == expected_agents
+ assert len(native["agents"]) == len(expected_agents)
+ assert all(agent["permissionMode"] == "readonly" for agent in native["agents"])
+ assert all(agent["model"] == "inherit" for agent in native["agents"])
+ assert native["rules"] == [{"alwaysApply": True}]
diff --git a/tests/unit/test_cursor_child_reads.py b/tests/unit/test_cursor_child_reads.py
new file mode 100644
index 0000000..1b3dff1
--- /dev/null
+++ b/tests/unit/test_cursor_child_reads.py
@@ -0,0 +1,143 @@
+# Copyright 2026 Google LLC.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Fail closed when native Cursor child read evidence is incomplete."""
+
+import json
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+
+import pytest
+
+
+SCRIPT = Path(__file__).resolve().parents[1] / 'integration/cursor_child_reads.py'
+
+
+def probe(tmp_path: Path, messages: list[dict], required: str) -> subprocess.CompletedProcess:
+ database = tmp_path / 'child.db'
+ with sqlite3.connect(database) as connection:
+ connection.execute('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB)')
+ connection.executemany(
+ 'INSERT INTO blobs VALUES (?, ?)',
+ [(str(index), json.dumps(message).encode()) for index, message in enumerate(messages)],
+ )
+ return subprocess.run(
+ [sys.executable, str(SCRIPT), str(database), '--required', required],
+ text=True, capture_output=True, check=False,
+ )
+
+
+def call(path: str, call_id: str = 'call-1') -> dict:
+ return {'role': 'assistant', 'content': [
+ {'type': 'tool-call', 'toolName': 'ReadFile', 'toolCallId': call_id,
+ 'args': {'path': path}},
+ ]}
+
+
+def result(path: str, call_id: str = 'call-1', error: bool = False,
+ content: str = 'fixture content') -> dict:
+ return {
+ 'role': 'tool',
+ 'content': [{'type': 'tool-result', 'toolName': 'ReadFile', 'toolCallId': call_id}],
+ 'providerOptions': {'cursor': {'highLevelToolCallResult': {
+ 'isError': error, 'output': {'success': {'path': path, 'content': content}},
+ }}},
+ }
+
+
+def test_correlated_success_is_required(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ run = probe(tmp_path, [call(path), result(path)], path)
+ assert run.returncode == 0
+ record = json.loads(run.stdout)
+ assert record['missing'] == []
+ assert record['reads'][0]['path'] == path
+ assert record['reads'][0]['bytes'] == len('fixture content')
+
+
+def test_request_without_success_fails(tmp_path: Path) -> None:
+ run = probe(tmp_path, [call('/fixture/persona.md')], '/fixture/persona.md')
+ assert run.returncode != 0
+ assert json.loads(run.stdout)['missing'] == ['/fixture/persona.md']
+
+
+def test_wrong_call_cannot_satisfy_request(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ run = probe(tmp_path, [call(path), result(path, call_id='other')], path)
+ assert run.returncode != 0
+
+
[email protected](('returned_path', 'error'), [
+ ('/fixture/persona.md', True),
+ ('/fixture/other.md', False),
+])
+def test_error_or_wrong_path_cannot_satisfy_request(
+ tmp_path: Path, returned_path: str, error: bool,
+) -> None:
+ path = '/fixture/persona.md'
+ run = probe(tmp_path, [call(path), result(returned_path, error=error)], path)
+ assert run.returncode != 0
+
+
+def test_empty_success_cannot_satisfy_request(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ run = probe(tmp_path, [call(path), result(path, content=' ')], path)
+ assert run.returncode != 0
+
+
+def test_malformed_read_call_cannot_be_ignored(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ malformed = {'role': 'assistant', 'content': [
+ {'type': 'tool-call', 'toolName': 'ReadFile', 'args': {'path': path}},
+ ]}
+ run = probe(tmp_path, [call(path), result(path), malformed], path)
+ assert run.returncode != 0
+
+
+def test_unexpected_read_entry_type_cannot_be_ignored(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ malformed = {'role': 'assistant', 'content': [
+ {'type': 'unexpected', 'toolName': 'ReadFile', 'toolCallId': 'call-2'},
+ ]}
+ run = probe(tmp_path, [call(path), result(path), malformed], path)
+ assert run.returncode != 0
+
+
+def test_live_wal_is_rejected(tmp_path: Path) -> None:
+ database = tmp_path / 'child.db'
+ with sqlite3.connect(database) as connection:
+ connection.execute('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB)')
+ Path(str(database) + '-wal').write_bytes(b'not-a-backup')
+ run = subprocess.run(
+ [sys.executable, str(SCRIPT), str(database), '--required', '/fixture/persona.md'],
+ text=True, capture_output=True, check=False,
+ )
+ assert run.returncode != 0
+ assert 'without a WAL file' in run.stderr
+
+
+def test_conflicting_error_after_success_fails(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ run = probe(tmp_path, [call(path), result(path), result(path, error=True)], path)
+ assert run.returncode != 0
+ assert 'conflicting success and error' in run.stderr
+
+
+def test_malformed_json_array_fails(tmp_path: Path) -> None:
+ path = '/fixture/persona.md'
+ database = tmp_path / 'child.db'
+ with sqlite3.connect(database) as connection:
+ connection.execute('CREATE TABLE blobs (id TEXT PRIMARY KEY, data BLOB)')
+ connection.executemany('INSERT INTO blobs VALUES (?, ?)', [
+ ('1', json.dumps(call(path)).encode()),
+ ('2', json.dumps(result(path)).encode()),
+ ('3', b'[oops'),
+ ])
+ run = subprocess.run(
+ [sys.executable, str(SCRIPT), str(database), '--required', path],
+ text=True, capture_output=True, check=False,
+ )
+ assert run.returncode != 0
+ assert 'Malformed JSON-looking blob' in run.stderr