Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Agent Note: Editor Viewport Sketch Layer, Reading Card, and Scene Edit Hold Gate

Status: implemented

## Problem

Authors often need to point at empty areas of a 2D level—where no object or tile exists yet—and describe what an agent should build there ("3 spikes", "platform, back and forth", "locked until the lever"). Relying solely on text prompts forces manual coordinate lookup, while letting an agent immediately mutate the scene risks misinterpreting rough intent. At the same time, annotations must never leak into `*.scene.yaml` or pollute scene undo history, must remain accurate across viewport zoom and pan levels, and must not crowd the compact 2D `editor-toolbar`.

## Decision

The editor adds a session-only 2D viewport sketch layer (`packages/game/editor/sketch.go`, `sketch_png.go`, `sketch_ui.go`) paired with `editormcp` tools (`packages/game/editor/editormcp/sketch.go`) and a confirmation hold gate on mutating scene tools:

- **Strict scene-coordinate session state**: Sketch marks (`Pen` polyline, `Arrow` start → end, `Box` rect, `Text` point + label) live exclusively on `Editor.sketch` and per-tab `sceneTab.sketch`, never on `sceneformat.SceneDoc` or `Editor.History`. Pointer drags convert canvas points immediately via `Editor.CanvasToWorld` and re-project during rendering via `Editor.WorldToCanvas`, keeping geometry invariant across zoom and pan changes. Sketch undo uses an isolated mark snapshot stack (`undoStack`) so undoing a mark never alters scene history or marks a scene dirty.
- **Dedicated `ScopeSketch` keyboard scope**: Entering sketch mode (`D` in `ScopeViewport2D`, or `View > Sketch`) activates `ScopeSketch` (priority `5` while sketching in 2D), enabling single-key tool shortcuts (`P` Pen, `A` Arrow, `B` Box, `T` Text, `I` Add mark at cursor, `H` Hide/Show marks, `⌘Z` Undo last mark) without colliding with `ScopeViewport` / `ScopeTile` bindings or adding extra buttons to `editor-toolbar`. `Esc` exits sketch drawing mode while retaining marks until sent, cleared, or kept.
- **Structured payload + rendered PNG**: `Editor.SendSketch` emits a `SketchAgentRequest` carrying `"Sketch · N marks"`, structured marks in scene coordinates, and a software-rasterized PNG (`RenderSketchViewportPNG` via `packages/game/mcp.RenderPNG` plus a 5×7 bitmap text pass for numbered badges and labels).
- **MCP reading card and hold gate**: Sending a sketch transitions the hold state to `SketchHoldPending` (and `SketchHoldReading` once the agent calls `sketch_reading`). While `Editor.SketchHoldActive()` is true, `scene_edit` and other mutating scene MCP tools (`tile_paint`, `tile_autotile`, `tile_erase`, `object_paste_yaml`, `object_duplicate`, `object_group`, `object_move_under`, `object_set_field`) refuse cleanly with a structured `*EditError` and leave the scene and history untouched. `ApproveSketchReading` (**Go ahead**) or `ReplyToSketchReading` releases the hold and captures a pre-edit scene snapshot; `CorrectSketchMark` (**Correct a mark**) reopens sketch mode with that exact mark selected while keeping the hold active.
- **Review overlay and Keep / Revert symmetry**: Approved `scene_edit` calls record changes into `sketchReviewState` (opening the review card with a **Sketch overlay** toggle that renders the sketch as a faint dotted reference over added/changed outlines). Both `KeepSketchReview` and `KeepTileReview` clear the sketch layer; both `RevertSketchReview` and `RevertAllTileReview` restore the scene while preserving the sketch marks so the author can send them again.

### Related notes

- Builds on [Editor MCP Server](../../implemented/architecture/2026-11-25-editor-mcp-server.md) for tool registration, `EditError` refusals, and in-memory MCP testing.
- Complements [Editor Viewport Overlays](../../implemented/feature/2026-11-26-editor-viewport-overlays.md) and [Editor MCP Tile Review](../../implemented/feature/2026-11-26-editor-mcp-tile-review.md) by sharing the Spec dark/light token palette and Keep/Revert lifecycle.
- Uses the scope-aware shortcut registry from [Editor Settings and Shortcuts](../../implemented/feature/2026-11-26-editor-settings-shortcuts.md).

## Alternatives considered

- **Storing sketch marks as temporary objects or metadata inside `SceneDoc`**: Would automatically inherit scene rendering and undo history, but violates the core invariant that every author-created YAML file stays clean and reviewable and risks saving transient marks into git diffs. Rejected in favor of session-only `sketchState` synced per `sceneTab`.
- **Adding a Sketch button directly to `editor-toolbar`**: Matches the top bar in `Sketch.dc.html`, but the current 2D `editor-toolbar` already wraps at 1200 px and has layout tests verifying toolbar compactness. Rejected in favor of keyboard shortcut `D`, `View > Sketch`, Command Palette, Scene Tree `SKETCH LAYER`, and the floating top-center sketch toolbar.
- **Blocking `scene_edit` in `Editor` mutators themselves**: Would prevent manual editor edits while a sketch is pending, even when the user wants to tweak something by hand before confirming. Rejected in favor of enforcing the hold gate specifically on mutating `editormcp` handlers via `Editor.SketchHoldActive()`.

## Consequences

- **Benefits**:
- Authors can annotate empty regions with four tools and numbered badges at any zoom level without ever dirtying `.scene.yaml` or scene undo history.
- Agents receive both exact scene coordinates and a visual PNG with numbered badges, and must restate their interpretation via `sketch_reading` before mutating the scene.
- Review lets authors visually compare added/changed objects against their original sketch and either clear marks on Keep or keep marks ready to re-send on Revert.
- **Costs**:
- Adding `sketch_read` and `sketch_reading` increases the built-in `editormcp` tool surface (requiring updates to tool-list conformance tests and docs).
- `packages/game/editor` now contains a lightweight 5×7 bitmap text rasterizer (`sketch_png.go`) parallel to `editormcp/viewport_text.go` so `Editor.RenderSketchViewportPNG` works without introducing a package cycle between `editor` and `editormcp`.
3 changes: 3 additions & 0 deletions changelog.d/editor-viewport-sketch-agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/editor`, `game/editor/editormcp`: add a session-only viewport sketch layer (Pen, Arrow, Box, Text in scene coordinates with numbered badges, labels, rendered PNG export, keyboard shortcuts in `ScopeSketch`), `sketch_read` / `sketch_reading` MCP tools with a confirmation hold gate on `scene_edit` until Go ahead or Correct a mark, and a review Sketch overlay toggle where Keep clears marks and Revert keeps them (#1025).
10 changes: 10 additions & 0 deletions docs/en/editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -1522,3 +1522,13 @@ The right rail (`RightRailView`) switches between **Agent** (`AgentPanelView` /
- **Folded earlier requests, History link, and Jump to latest**: earlier reviewed requests fold to one line each (`N EARLIER REQUESTS`) and expand on click to show the full prompt, changed fields, steps, and **Open this step in History** (`OpenHistoryStep`), which opens the unified History timeline highlighted on that step. Expanding an earlier request surfaces a floating **Jump to latest** pill (`JumpToLatestAgentRequest`).
- **Empty-thread view (`AgentAlwaysReadItems`, `AgentBriefSuggestions`)**: an empty thread lists what the agent reads with every request (`<scene> · whole scene`, `brief.yaml`, `AGENTS.md`, `Viewport image`) and up to three starter prompts read safely from the project's `brief.yaml` (`FROM YOUR BRIEF`).
- **Inspector footer attribution (`LastAgentChangeForObject`, `OpenAgentRequest`)**: when a selected object was changed by a non-reverted agent request (via `SendAgentRequestWith`, `RecordAgentStep`, or `editormcp`'s `scene_edit`), the Inspector footer displays `Changed in “<request>” · <age>` and clicking it opens that thread and expands that request.

## Viewport sketch layer for the agent (#1025)

Draw session-only numbered annotations directly over the 2D viewport to point at empty places in a level before asking the agent to build them (`docs/design/editor/Sketch.dc.html`, styled exclusively with `docs/design/editor/Spec.dc.html` tokens):

- **Four sketch tools in scene coordinates**: press `D` (`CmdSketchToggle`, or `View > Sketch`) to toggle Sketch mode without adding extra buttons to the compact 2D `editor-toolbar`. Switch between **Pen** (`P`, freehand polyline), **Arrow** (`A`, start → end), **Box** (`B`, rect), and **Text** (`T`, point + label) in `ScopeSketch`, or place a mark at the cursor with `I` (`CmdSketchAddMarkAtCursor`). Every mark gets a sequential numbered badge (`1`, `2`, `3`, …) and an optional label (such as `"3 spikes"`, `"platform, back and forth"`, `"locked until the lever"`). All geometry is converted through `CanvasToWorld` and stored strictly in scene coordinates so marks scale and pan accurately across zoom levels and are **never** written into `SceneDoc`, `*.scene.yaml`, or scene undo `History`.
- **Sketch bar, Scene Tree row, and status bar**: the floating sketch bar displays the four tools, **Undo last mark** (`⌘Z` in `ScopeSketch`), **Hide / Show marks** (`H`), `"N marks not saved"`, **Clear**, and **Done**. Pressing `Esc` finishes sketch mode while keeping drawn marks until sent, cleared, or kept. The Scene Tree displays a compact `SKETCH LAYER` row (`N marks · not saved`), and the status bar shows live scene coordinates and the active sketch tool.
- **Sending a sketch to the agent (`SendSketch` / `Editor.OnSendSketch`)**: the composer attaches a `"Sketch · N marks"` context chip (clicking toggles a `"Sent with this request"` scene-coordinate preview). Sending delivers `SketchAgentRequest` with structured marks (`number`, `kind`, geometry in scene coordinates, `label`) and a rendered PNG of the viewport with numbered marks overlaid (`RenderSketchViewportPNG`).
- **Agent reading card & `scene_edit` confirmation hold**: sending a sketch arms a hold gate (`SketchHoldActive() == true`) that causes `scene_edit` and other mutating scene MCP tools to refuse edits until the person confirms. The agent reads marks via `sketch_read` and posts its restatement (`"I read your sketch as: …"` with numbered items and assumptions) via `sketch_reading` (`PostSketchReading`). Clicking **Go ahead** (`ApproveSketchReading`, `⌘↵`) releases the hold; clicking **Correct a mark** (`CorrectSketchMark`, `⇧M`, or clicking any numbered item) reopens sketch mode with that exact mark selected while keeping the hold active; replying in words (`ReplyToSketchReading`) works too.
- **Review overlay & Keep / Revert**: after approval, agent edits open a review card (`SketchReviewOpen`) with a **Sketch overlay** toggle (`O`, `ToggleSketchReviewOverlay`, also available in `TileReview`) that lays the faint dotted sketch over the result. **Keep** (`KeepSketchReview` / `KeepTileReview`) keeps the edits and clears the sketch layer; **Revert** (`RevertSketchReview` / `RevertAllTileReview`) undoes the edits while keeping the sketch marks intact to send again.
2 changes: 2 additions & 0 deletions docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,8 @@ claude mcp add game-editor -- nsgo game mcp
| `datatable_review_propose` | edit | `files` (required), `prompt`, `checks` (optional) | Validates one or more version-1 YAML data table files against `datatable.ParseDocument` (and any registered Go row type) and opens the row-by-row Data Table review screen with old → new, `Δ%`, per-record Revert/Restore, and optional named agent check figures without modifying disk until Keep. |
| `datatable_review_checks` | edit | `checks` (required) | Attaches or refreshes named agent check figures (`label`, `value`, `before`, `basis`) on the active Data Table review and clears `checksOutOfDate` after the person reverts, edits, or reorders records. |
| `datatable_review_status` | read | `file` (optional) | Reports the active Data Table review's files, kept/reverted/user-edited counts, active record states, attached check figures, and whether `checksOutOfDate` is true. |
| `sketch_read` | read | `includeImage`, `scale` | Reads the active or sent viewport sketch marks (Pen, Arrow, Box, Text) with sequential badge numbers, exact scene coordinates, labels, prompt, hold state, and an optional rendered PNG of the viewport with numbered marks overlaid. |
| `sketch_reading` | edit | `summary`, `items`, `assumptions` | Posts the agent's restatement card (`"I read your sketch as: …"`) and assumptions for a sent viewport sketch; while a sent sketch awaits confirmation, `scene_edit` and other mutating scene tools hold cleanly until the person chooses **Go ahead**, **Correct a mark**, or replies in words. |

Every tool registered on the editor's MCP server can be turned on or off per computer in **Settings › Tools** (`Editor.SetMCPToolEnabled`): disabling a tool removes it from the server's advertised tool list (`tools/list_changed`) and returns a readable refusal if called. Outbound content categories in **Settings › Usage and privacy** (**WHAT MAY LEAVE THIS COMPUTER**: Scene and data files, Viewport images, Go source code, Art and audio files) are enforced for every connected agent across all tools (including symlink-resolved file paths) and all resources (`editor://scene`, `editor://selection`, `editor://agent/turn`, `editor://brief`, `editor://rules`, `editor://context`), refusing calls with the reason whenever the requested content kind is switched off. Additional MCP servers configured in **Settings › Tools** (starting with `nsgo-game` for the running game via `go tool nsgo mcp`) are synced into `.mcp.json` and `.codex/config.toml` via `editormcp.InstallWithServers`.

Expand Down
10 changes: 10 additions & 0 deletions docs/zh/editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -1522,3 +1522,13 @@ func main() {
- **折叠较早请求、跳转历史记录与跳到最新**:已审查的较早请求折叠为单行(`N 条较早请求`),点击展开显示完整提示词、变更明细、步骤列表以及**在历史记录中打开此步骤**(`OpenHistoryStep`)链接,点击后在统一历史时间线中高亮该步骤;展开较早请求时底部浮现**跳到最新**按钮(`JumpToLatestAgentRequest`)。
- **空白线程视图(`AgentAlwaysReadItems`、`AgentBriefSuggestions`)**:空白线程会列出智能体每次请求必读的上下文(`<场景> · 整个场景`、`brief.yaml`、`AGENTS.md`、`视口图像`),并安全读取项目 `brief.yaml` 中的建议提示(`来自项目简报`)。
- **检查器页脚来源链接(`LastAgentChangeForObject`、`OpenAgentRequest`)**:当选中对象曾被未还原的智能体请求修改(无论是通过 `SendAgentRequestWith`、`RecordAgentStep` 还是 `editormcp` 的 `scene_edit`),检查器页脚会显示“修改自“<请求标题>” · <时间>”,点击即可打开对应线程并定位/展开该请求。

## 面向智能体的视口草图层(#1025)

在 2D 视口上直接绘制会话级编号草图,指向关卡中尚不存在对象的区域再交给智能体构建(对应 `docs/design/editor/Sketch.dc.html`,严格使用 `docs/design/editor/Spec.dc.html` 令牌):

- **场景坐标下的四种草图工具**:按 `D`(`CmdSketchToggle` 或 `视图 > 草图`)开启/关闭草图模式,不向紧凑的 2D `editor-toolbar` 额外增加按钮。在 `ScopeSketch` 作用域下可切换 **画笔(Pen,`P`,自由折线)**、**箭头(Arrow,`A`,起点 → 终点)**、**方框(Box,`B`,矩形区域)** 与 **文本(Text,`T`,锚点 + 标签)**,也可按 `I`(`CmdSketchAddMarkAtCursor`)在光标处用键盘放置标记。每个标记自动分配连续编号徽章(`1`、`2`、`3`…)和可选标签(例如 `"3 spikes"`、`"platform, back and forth"`、`"locked until the lever"`)。所有几何坐标均通过 `CanvasToWorld` 严格保存在场景坐标中,跨缩放与平移保持精准,且**绝不**写入 `SceneDoc`、`*.scene.yaml` 或场景撤销 `History`。
- **悬浮草图栏、场景树行与状态栏**:顶部悬浮草图栏提供四种工具、**撤销上一个标记**(`ScopeSketch` 下的 `⌘Z`)、**隐藏 / 显示标记**(`H`)、`"N marks not saved"` 计数、**Clear** 与 **Done**。按 `Esc` 结束草图绘制模式并保留已绘标记,直到发送、清空或审查保留。场景树底部展示紧凑的 `SKETCH LAYER` 行(`N marks · not saved`),状态栏实时显示场景坐标与当前草图工具。
- **将草图发送给智能体(`SendSketch` / `Editor.OnSendSketch`)**:输入框附带 `"Sketch · N marks"` 上下文芯片(点击可展开 `"Sent with this request"` 场景坐标预览)。发送时通过 `SketchAgentRequest` 传递结构化标记(编号、类型、场景坐标几何、标签)以及叠加了编号标记的视口渲染 PNG(`RenderSketchViewportPNG`)。
- **智能体解读卡片与 `scene_edit` 确认闸门**:发送草图后立即启用确认闸门(`SketchHoldActive() == true`),在用户确认前 `scene_edit` 等变更场景的 MCP 工具会被拒绝。智能体通过 `sketch_read` 读取草图,并通过 `sketch_reading`(`PostSketchReading`)提交复述卡片(`"I read your sketch as: …"` 与待确认假设)。点击 **Go ahead**(`ApproveSketchReading`、`⌘↵`)放行修改;点击 **Correct a mark**(`CorrectSketchMark`、`⇧M` 或点击任意编号条目)会重新进入草图模式并精确选中该标记,同时保持确认闸门生效;直接输入文字回复(`ReplyToSketchReading`)同样有效。
- **审查叠加层与保留 / 撤销行为**:确认后智能体的场景修改会打开审查卡片(`SketchReviewOpen`),内置 **Sketch overlay** 开关(`O`、`ToggleSketchReviewOverlay`,瓦片审查 `TileReview` 中同样支持)将草图以半透明点线叠加在结果之上。**Keep**(`KeepSketchReview` / `KeepTileReview`)保留修改并清空草图层;**Revert**(`RevertSketchReview` / `RevertAllTileReview`)撤销修改但保留草图标记以便再次发送。
Loading
Loading