diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-turn-checkpoints.md b/.agents/notes/implemented/feature/2026-11-26-editor-turn-checkpoints.md new file mode 100644 index 000000000..b7d19531a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-turn-checkpoints.md @@ -0,0 +1,29 @@ +# Agent Note: Editor persistent turn checkpoints under `.nsgo/checkpoints/` + +Status: implemented + +## Problem + +The editor's in-memory `History` command stack only tracks linear undo steps for the current session and only covers commands executed inside the open scene tab. When an agent turn edits multiple files across a project (scenes, prefabs, data tables, `game.yaml`, Go code, and binary media), or when an autonomous task or automation runs, restarting the editor drops the undo stack and leaves no built-in way to preview or restore every file a turn touched back to its pre-turn bytes. + +## Decision + +The editor stores a persistent checkpoint for every agent turn, autonomous task, and automation under `.nsgo/checkpoints//` inside the project root, ignored by Git (writing `.nsgo/checkpoints/.gitignore` and `.nsgo/.gitignore` when absent): + +- **On-disk layout**: each checkpoint directory holds a strict versioned YAML manifest (`manifest.yaml`, `version: 1`, `editor.CheckpointVersion`, rejecting unknown fields, duplicate keys, trailing documents, invalid paths, and invalid SHA-256 digests) plus verbatim pre-turn file bytes under `files/`. Binary media is copied verbatim with no conversion, and non-existent files created by a turn are recorded with `existed: false` so restoring removes them. +- **Lazy first-write capture**: before a turn first writes any project file (either via `WriteAgentFile`/`DeleteAgentFile`/`RecordCheckpointFile` or via `History.beforeCommand` intercepting scene/project commands and `editormcp` `ActionEdit` calls), the editor captures that file's pre-turn bytes (verbatim disk bytes when clean, or canonical in-memory YAML if an open document already has unsaved edits). Subsequent writes to the same file in the same turn are no-ops, preserving the original pre-turn state. You-only files (`MatchYouOnlyPath` / `CheckYouOnlyTarget`), `.nsgo/`, `.git/`, symlinks, and files exceeding `32 MiB` are strictly refused. +- **Pre-start checkpoints for tasks and automations**: `TakeCheckpointBeforeTask`, `RunTaskWithCheckpoint`, `launchTaskRunner` in `tasks.go`, `TakeCheckpointBeforeAutomation`, `RunAutomationWithCheckpoint`, `editormcp`'s `game_playtest`, and automation-mode edit calls persist a checkpoint before work begins so partial or crashed runs remain restorable. +- **Size cap**: `Editor.CheckpointMaxBytes` (default `128 MiB`) prunes the oldest completed checkpoints while keeping at least the newest checkpoint and never deleting an active turn. +- **History panel and one-step undoable restore**: `HistoryPanelView` (`⌘Y`, `CmdHistoryPanel`) renders `UnifiedHistoryEntries` combining persisted checkpoints, current-session edits, saved points, and Git milestones by day with `All` / `You` / `Agent` filters, read-only viewport preview (`ActiveScene()` shows the checkpoint's scene snapshot while editing is off; `Esc` exits preview), and `RestoreCheckpoint` executed as a single `fallibleCommand` (`checkpointRestoreCmd`) that verifies byte length and SHA-256 digests, atomically restores all touched files on disk, synchronizes open scene tabs and `game.yaml` without triggering disk-conflict banners, and rolls back every file and open editor state on one `Undo()`. +- **MCP surface**: `editormcp` exposes `checkpoint_list` (`ActionRead`) and `checkpoint_restore` (`ActionEdit`, evaluating per-file `edit`/`code`/`delete` permission rules and You-only boundaries via `targets`) and automatically wraps file-mutating `ActionEdit` calls in panic- and cancel-safe turn checkpoints (preserving partial checkpoints on error/panic and discarding empty turns). + +## Alternatives considered + +- **Storing checkpoints in Git stash or shadow commits**: Git repositories may not be initialized in new projects, and creating Git objects/refs can interfere with hooks, worktrees, or user workflows. Plain files under `.nsgo/checkpoints/` work identically with or without Git and stay strictly ignored. +- **Content-addressed custom binary pack or `encoding/gob` archive**: Violates the repository's plain-text format rule (`AGENTS.md`), prevents human/AI inspection and diffing of manifests, and adds custom binary parsing risk. A versioned YAML manifest alongside verbatim files under `files/` keeps manifests human-readable and media byte-exact. +- **Full-project snapshots per turn**: Copying the entire project on every turn would quickly blow through the disk budget on media-heavy projects. Capturing each file lazily before its first write in a turn keeps checkpoints tiny and proportional to the turn's actual footprint. + +## Consequences + +- **Benefits**: Every agent turn, task, and automation is restorable byte-for-byte across editor restarts, across all file types (YAML, Go, and binary media), and `Restore` integrates cleanly into `Undo`/`Redo` as a single step. Checkpoints are inspectable YAML manifests with JSON Schema validation (`checkpoint.v1.json`) and SHA-256 integrity checks. +- **Costs**: Restoring a checkpoint rewrites touched files on disk immediately (to support non-scene files like prefabs and Go code) and synchronizes open tabs; if disk writes fail mid-restore, `checkpointRestoreCmd` rolls back already-written files. Large media files touched repeatedly in separate turns consume disk space until the size cap drops older checkpoints. diff --git a/apps/website/public/schemas/checkpoint.v1.json b/apps/website/public/schemas/checkpoint.v1.json new file mode 100644 index 000000000..967178831 --- /dev/null +++ b/apps/website/public/schemas/checkpoint.v1.json @@ -0,0 +1,77 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://game.nsgo.dev/schemas/checkpoint.v1.json", + "title": "NSGo game editor checkpoint manifest (version 1)", + "description": "CheckpointManifest is the strict versioned YAML manifest stored at .nsgo/checkpoints//manifest.yaml.", + "type": "object", + "properties": { + "version": { + "description": "Version is the schema version; it must equal CheckpointVersion (1).", + "type": "integer", + "const": 1 + }, + "id": { + "description": "ID is the unique checkpoint directory name (for example \"20261126T144100Z-0001\").", + "type": "string" + }, + "createdAt": { + "description": "CreatedAt is the RFC3339 UTC timestamp when the checkpoint was started.", + "type": "string" + }, + "who": { + "description": "Who identifies who initiated the checkpoint (\"agent\", \"you\", or \"git\").", + "type": "string" + }, + "kind": { + "description": "Kind identifies why the checkpoint was taken (\"turn\", \"task\", or \"automation\").", + "type": "string" + }, + "title": { + "description": "Title is the short human-readable summary shown in the History panel.", + "type": "string" + }, + "detail": { + "description": "Detail is optional secondary context (such as change counts or trigger details).", + "type": "string" + }, + "files": { + "description": "Files lists every project file captured before its first write in this checkpoint, sorted by path.", + "type": "array", + "items": { + "$ref": "#/definitions/CheckpointFile" + } + } + }, + "additionalProperties": false, + "definitions": { + "CheckpointFile": { + "description": "CheckpointFile records one project file captured before its first write in a checkpoint.", + "type": "object", + "properties": { + "path": { + "description": "Path is the slash-separated path from the project root (for example \"scenes/level_01.scene.yaml\").", + "type": "string" + }, + "existed": { + "description": "Existed reports whether the file existed before the turn wrote it; false means restoring deletes the file.", + "type": "boolean" + }, + "size": { + "description": "Size is the saved file size in bytes when Existed is true.", + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000 + }, + "sha256": { + "description": "SHA256 is the lowercase hex SHA-256 digest of the saved bytes when Existed is true.", + "type": "string" + }, + "mode": { + "description": "Mode is the optional 4-digit octal Unix file mode (for example \"0755\") when non-default.", + "type": "string" + } + }, + "additionalProperties": false + } + } +} diff --git a/changelog.d/editor-turn-checkpoints-1018.md b/changelog.d/editor-turn-checkpoints-1018.md new file mode 100644 index 000000000..d1d95d9b4 --- /dev/null +++ b/changelog.d/editor-turn-checkpoints-1018.md @@ -0,0 +1,3 @@ +### Added + +- Editor: persistent per-turn checkpoints stored as strict versioned YAML manifests and verbatim pre-turn files under `.nsgo/checkpoints/` (ignored by git, enforcing You-only boundaries, symlink refusal, and automatic size-cap pruning), pre-start checkpoints for autonomous tasks and automations, unified History panel (`⌘Y`) integration with cross-session checkpoint preview and one-step undoable multi-file restore, plus `checkpoint_list` and permission-checked `checkpoint_restore` MCP tools. diff --git a/docs/en/editor.md b/docs/en/editor.md index ce664b537..2bcf6c1bb 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1401,6 +1401,16 @@ The History panel (`HistoryPanelView`), styled with `docs/design/editor/Spec.dc. - **Non-destructive Restore (`RestoreHistoryEntry`)**: clicking **Restore** rolls the active scene, project, and every extra touched file back to that point as **one new undoable step** in `History`. Later steps remain in the timeline and can still be previewed or restored, and a single `Undo` returns immediately to the latest state. - **Agent read access (`editormcp`)**: the read-only `history_list` tool (`ActionRead`) exposes the same newest-first timeline to connected agents with optional `author` (`all`, `you`, `agent`) and `limit` filters plus unsaved and active preview metadata. +## Persistent per-turn checkpoints (#1018) + +Agent turns, autonomous tasks, and automations persist across editor restarts inside the project's `.nsgo/checkpoints/` directory and appear alongside session edits in the unified History panel (`⌘Y`, `CmdHistoryPanel`): + +- **Lazy first-write capture (`.nsgo/checkpoints/`)**: before an agent turn (`BeginCheckpointTurn` / `RunCheckpointTurn`, or any file-mutating `editormcp` `ActionEdit` tool call) first modifies a project file—scenes, prefabs, data tables, `game.yaml`, Go code, or verbatim binary media—the editor snapshots its pre-turn bytes under `.nsgo/checkpoints//files/` and writes a strict versioned YAML manifest (`manifest.yaml`, `editor.CheckpointVersion = 1`, JSON Schema `https://game.nsgo.dev/schemas/checkpoint.v1.json`). Files created by the turn record `existed: false` so restoring deletes them. `.nsgo/checkpoints/.gitignore` and `.nsgo/.gitignore` are written automatically so checkpoints stay ignored by Git, and `Editor.CheckpointMaxBytes` (default `128 MiB`) prunes the oldest completed checkpoints when total size exceeds the cap. +- **Tasks and automations**: autonomous background tasks (`TakeCheckpointBeforeTask`, `RunTaskWithCheckpoint`, and `SubmitTask` runners) and automations (`TakeCheckpointBeforeAutomation`, `RunAutomationWithCheckpoint`, `game_playtest`, and automation-mode MCP edits) always persist a checkpoint before they start. +- **Security and integrity**: checkpoint capture, writes, and restores strictly exclude `.git/`, `.nsgo/`, and all You-only configuration files (`MatchYouOnlyPath` / `CheckYouOnlyTarget`), refuse symlinks along every path component, cap manifest and file sizes (`2 MiB` / `32 MiB`), and verify both byte length and SHA-256 digests before writing. +- **Unified History preview and one-step undoable restore**: `OpenProject` reloads persisted checkpoints into `HistoryPanelView` (`UnifiedHistoryEntries`). Clicking a checkpoint previews its scene snapshot read-only (`PreviewCheckpoint`), and **Restore** (`RestoreCheckpoint`) atomically restores every touched file on disk, synchronizes open tabs and `game.yaml`, and records one undoable step (`checkpointRestoreCmd`) so `Undo` (`⌘Z`) puts the entire turn back byte-for-byte. +- **Matching MCP tools (`editormcp`)**: `checkpoint_list` (`ActionRead`) lists unified history and persisted checkpoints; `checkpoint_restore` (`ActionEdit`) evaluates permission rules (`edit`, `code`, `delete`) and You-only boundaries against every file recorded in the checkpoint manifest before restoring as one undoable step. + ## You-only trust boundary and proposed deletions (#1015) Settings that govern what an AI agent is allowed to touch — **Permissions** (`permissions.yaml`), **Tools** (`tools.yaml` / `mcp.yaml`), **Models** (`models.yaml`), and **Usage** (`usage.yaml`) — follow the **You-only rule** (`docs/design/editor/Permissions.dc.html`, `Settings.dc.html`): diff --git a/docs/en/formats.md b/docs/en/formats.md index e7439482d..c5da0f6dd 100644 --- a/docs/en/formats.md +++ b/docs/en/formats.md @@ -2131,6 +2131,36 @@ requests: status: done ``` + +### Editor turn checkpoints + +| Files | Version | Read and written by | Fields | +| --- | --- | --- | --- | +| `.nsgo/checkpoints//manifest.yaml` (`editor.CheckpointsDir`, `editor.CheckpointManifestFile`), with saved pre-turn file contents stored verbatim under `.nsgo/checkpoints//files/` and ignored by Git | `version: 1` | `editor.ParseCheckpointManifest`, `editor.EncodeCheckpointManifest`, `Editor.BeginCheckpointTurn`, `Editor.RestoreCheckpoint` | [Editor & Scene Format](editor.md#persistent-per-turn-checkpoints-1018) | + +Each agent turn, autonomous task, or automation records the pre-turn bytes of every project file before its first write (scenes, prefabs, data tables, `game.yaml`, Go code, and binary media alike). `files` is sorted by slash-separated `path` relative to the project root. When `existed` is `true`, `size` and `sha256` describe the raw bytes stored under `files/`, with optional 4-digit octal `mode` when non-default; when `existed` is `false`, restoring deletes the file that the turn created. A size cap (`Editor.CheckpointMaxBytes`, defaulting to 128 MiB) drops the oldest completed checkpoints. + +```yaml +version: 1 +id: 20261126T144100Z-0001 +createdAt: "2026-11-26T14:41:00Z" +who: agent +kind: turn +title: Coin spin, bob and sparkle +detail: 2 files +files: + - path: fx/sparkle.particles.yaml + existed: false + - path: prefabs/coin.prefab.yaml + existed: true + size: 142 + sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + - path: scenes/level_01.scene.yaml + existed: true + size: 512 + sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 +``` + ### Asset build cache diff --git a/docs/zh/editor.md b/docs/zh/editor.md index e5ca3351a..293948677 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1401,6 +1401,16 @@ func main() { - **非破坏性恢复(`RestoreHistoryEntry`)**:点击 **Restore** 会将当前场景、项目以及期间改动的全部额外文件作为**一个新的可撤销步骤**回滚到该时间点;后续历史步骤全部保留且仍可预览或恢复,执行一次 `Undo` 即可立即回到恢复前的最新状态。 - **智能体读取接口(`editormcp`)**:只读工具 `history_list`(`ActionRead`)向已连接的智能体暴露同一份按最新优先排列的历史列表,支持 `author`(`all`、`you`、`agent`)与 `limit` 筛选以及未保存和当前预览状态。 +## 持久化回合检查点(#1018) + +智能体回合、自主后台任务与自动化流程的检查点会持久化在项目的 `.nsgo/checkpoints/` 目录中,重启编辑器后仍可保留,并与当前会话编辑一同显示在统一历史面板(`⌘Y`,`CmdHistoryPanel`)中: + +- **首次写入前快照(`.nsgo/checkpoints/`)**:在智能体回合(`BeginCheckpointTurn` / `RunCheckpointTurn`,或任意会修改文件的 `editormcp` `ActionEdit` 工具调用)首次修改项目文件——包括场景、预制体、数据表、`game.yaml`、Go 代码及按原字节保存的二进制媒体——之前,编辑器会将其修改前的字节原样保存到 `.nsgo/checkpoints//files/`,并写入严格版本化的 YAML 清单(`manifest.yaml`,`editor.CheckpointVersion = 1`,JSON Schema `https://game.nsgo.dev/schemas/checkpoint.v1.json`)。回合新建的文件记为 `existed: false`,恢复时会将其删除。编辑器会自动写入 `.nsgo/checkpoints/.gitignore` 与 `.nsgo/.gitignore` 以保持被 Git 忽略,并在总占用超过 `Editor.CheckpointMaxBytes`(默认 `128 MiB`)时自动清理最旧的已完成检查点。 +- **后台任务与自动化**:自主后台任务(`TakeCheckpointBeforeTask`、`RunTaskWithCheckpoint` 及 `SubmitTask` 启动的执行器)与自动化流程(`TakeCheckpointBeforeAutomation`、`RunAutomationWithCheckpoint`、`game_playtest` 及自动化模式下的 MCP 编辑)在开始前总会先持久化创建一个检查点。 +- **安全与完整性保护**:检查点的记录、写入与恢复严格排除 `.git/`、`.nsgo/` 以及全部仅限用户配置文件(`MatchYouOnlyPath` / `CheckYouOnlyTarget`),拒绝路径上任何层级的符号链接,限制清单与单文件大小上限(`2 MiB` / `32 MiB`),并在恢复写入前同时校验文件字节数与 SHA-256 摘要。 +- **统一历史预览与单步可撤销恢复**:`OpenProject` 会将已持久化的检查点重新载入 `HistoryPanelView`(`UnifiedHistoryEntries`)。点击任意检查点可只读预览该时刻的场景快照(`PreviewCheckpoint`),点击 **恢复(Restore)**(`RestoreCheckpoint`)会原子恢复所有受影响文件、同步打开的标签页与 `game.yaml`,并将其作为单个可撤销步骤(`checkpointRestoreCmd`)记入 `History`,按一次 `Undo`(`⌘Z`)即可逐字节还原整个回合。 +- **配套 MCP 工具(`editormcp`)**:`checkpoint_list`(`ActionRead`)列出统一历史与持久化检查点;`checkpoint_restore`(`ActionEdit`)会先针对检查点清单中记录的每一个文件评估权限规则(`edit`、`code`、`delete`)及仅限用户边界,通过后再作为单个可撤销步骤执行恢复。 + ## 仅限用户信任边界与提议删除(#1015) 控制 AI 智能体行为边界的四项设置——**权限**(`permissions.yaml`)、**工具**(`tools.yaml` / `mcp.yaml`)、**模型**(`models.yaml`)与**用量**(`usage.yaml`)——严格遵循**仅限用户(You only)规则**(对应 `docs/design/editor/Permissions.dc.html`、`Settings.dc.html`): diff --git a/docs/zh/formats.md b/docs/zh/formats.md index 8023a5b94..1dfb26c64 100644 --- a/docs/zh/formats.md +++ b/docs/zh/formats.md @@ -2131,6 +2131,36 @@ requests: status: done ``` + +### 编辑器回合检查点 + +| 文件 | 版本 | 读写函数 | 字段 | +| --- | --- | --- | --- | +| `.nsgo/checkpoints//manifest.yaml`(`editor.CheckpointsDir`、`editor.CheckpointManifestFile`),写入前的原始文件内容按原样保存在 `.nsgo/checkpoints//files/` 下并由 Git 忽略 | `version: 1` | `editor.ParseCheckpointManifest`、`editor.EncodeCheckpointManifest`、`Editor.BeginCheckpointTurn`、`Editor.RestoreCheckpoint` | [编辑器与场景格式](editor.md#持久化回合检查点1018) | + +每个智能体回合、自主任务或自动化在首次写入任何项目文件之前都会记录其原始字节(场景、预制体、数据表、`game.yaml`、Go 代码与二进制媒体一视同仁)。`files` 按相对项目根目录的斜杠路径 `path` 排序。当 `existed` 为 `true` 时,`size` 与 `sha256` 描述保存在 `files/` 下的原始字节,非默认权限通过 4 位八进制 `mode` 记录;当 `existed` 为 `false` 时,恢复操作会删除该回合新建的文件。容量上限(`Editor.CheckpointMaxBytes`,默认 128 MiB)会自动清理最旧的已完成检查点。 + +```yaml +version: 1 +id: 20261126T144100Z-0001 +createdAt: "2026-11-26T14:41:00Z" +who: agent +kind: turn +title: Coin spin, bob and sparkle +detail: 2 files +files: + - path: fx/sparkle.particles.yaml + existed: false + - path: prefabs/coin.prefab.yaml + existed: true + size: 142 + sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + - path: scenes/level_01.scene.yaml + existed: true + size: 512 + sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 +``` + ### 资源构建缓存 diff --git a/packages/game/cmd/gameschema/main.go b/packages/game/cmd/gameschema/main.go index afe87e3d0..f7e287ed5 100644 --- a/packages/game/cmd/gameschema/main.go +++ b/packages/game/cmd/gameschema/main.go @@ -310,6 +310,13 @@ var formats = []format{ pkg: "editor", version: editor.AgentThreadFileVersion, }, + { + url: editor.CheckpointSchemaURL, + title: "NSGo game editor checkpoint manifest (version 1)", + typ: reflect.TypeFor[editor.CheckpointManifest](), + pkg: "editor", + version: editor.CheckpointVersion, + }, } // durationTypes maps duration types to their YAML schema forms: time.Duration accepts a Go duration string or integer nanoseconds; cutscene.Duration accepts only Go duration strings such as "1.5s". diff --git a/packages/game/editor/checkpoints.go b/packages/game/editor/checkpoints.go new file mode 100644 index 000000000..53d77e92d --- /dev/null +++ b/packages/game/editor/checkpoints.go @@ -0,0 +1,2042 @@ +package editor + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + "unicode" + + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "go.yaml.in/yaml/v3" +) + +// CheckpointVersion is the schema version of checkpoint manifest YAML files stored under .nsgo/checkpoints/. +const CheckpointVersion = 1 + +// CheckpointSchemaURL is the published JSON Schema URL for checkpoint manifests. +const CheckpointSchemaURL = "https://game.nsgo.dev/schemas/checkpoint.v1.json" + +// CheckpointsDir is the slash-separated path from a project root where persistent turn checkpoints are stored. +const CheckpointsDir = ".nsgo/checkpoints" + +// CheckpointManifestFile is the manifest filename inside each checkpoint directory under CheckpointsDir. +const CheckpointManifestFile = "manifest.yaml" + +// DefaultCheckpointMaxBytes is the default total disk budget for .nsgo/checkpoints before the oldest checkpoints are pruned (128 MiB). +const DefaultCheckpointMaxBytes int64 = 128 << 20 + +const ( + // maxCheckpointManifestBytes caps manifest.yaml size when loading from disk. + maxCheckpointManifestBytes int64 = 2 << 20 + // maxCheckpointFileBytes caps any single project file captured into or restored from a checkpoint (32 MiB). + maxCheckpointFileBytes int64 = 32 << 20 + // maxCheckpointFilesPerTurn caps how many distinct files one checkpoint manifest may record. + maxCheckpointFilesPerTurn = 500 + // maxCheckpointDirs caps how many checkpoint directories LoadCheckpoints scans per project. + maxCheckpointDirs = 2000 +) + +// CheckpointKind identifies why a persistent checkpoint was created. +type CheckpointKind string + +const ( + // CheckpointKindTurn marks a checkpoint created for an agent turn's edits. + CheckpointKindTurn CheckpointKind = "turn" + // CheckpointKindTask marks a checkpoint taken before an autonomous background task starts. + CheckpointKindTask CheckpointKind = "task" + // CheckpointKindAutomation marks a checkpoint taken before an automation run starts. + CheckpointKindAutomation CheckpointKind = "automation" +) + +// CheckpointManifest is the strict versioned YAML manifest stored at .nsgo/checkpoints//manifest.yaml. +type CheckpointManifest struct { + // Version is the schema version; it must equal CheckpointVersion (1). + Version int `yaml:"version"` + // ID is the unique checkpoint directory name (for example "20261126T144100Z-0001"). + ID string `yaml:"id"` + // CreatedAt is the RFC3339 UTC timestamp when the checkpoint was started. + CreatedAt string `yaml:"createdAt"` + // Who identifies who initiated the checkpoint ("agent", "you", or "git"). + Who HistoryAuthor `yaml:"who"` + // Kind identifies why the checkpoint was taken ("turn", "task", or "automation"). + Kind CheckpointKind `yaml:"kind"` + // Title is the short human-readable summary shown in the History panel. + Title string `yaml:"title"` + // Detail is optional secondary context (such as change counts or trigger details). + Detail string `yaml:"detail,omitempty"` + // Files lists every project file captured before its first write in this checkpoint, sorted by path. + Files []CheckpointFile `yaml:"files,omitempty"` +} + +// CheckpointFile records one project file captured before its first write in a checkpoint. +type CheckpointFile struct { + // Path is the slash-separated path from the project root (for example "scenes/level_01.scene.yaml"). + Path string `yaml:"path"` + // Existed reports whether the file existed before the turn wrote it; false means restoring deletes the file. + Existed bool `yaml:"existed"` + // Size is the saved file size in bytes when Existed is true. + Size int64 `yaml:"size,omitempty"` + // SHA256 is the lowercase hex SHA-256 digest of the saved bytes when Existed is true. + SHA256 string `yaml:"sha256,omitempty"` + // Mode is the optional 4-digit octal Unix file mode (for example "0755") when non-default. + Mode string `yaml:"mode,omitempty"` +} + +// CheckpointSummary pairs a loaded CheckpointManifest with its total on-disk footprint in bytes. +type CheckpointSummary struct { + CheckpointManifest + // TotalBytes is the total size on disk of the checkpoint directory (manifest plus saved files). + TotalBytes int64 +} + +// CheckpointOptions configures a new turn, task, or automation checkpoint. +type CheckpointOptions struct { + // Who defaults to HistoryAuthorAgent when empty. + Who HistoryAuthor + // Kind defaults to CheckpointKindTurn when empty. + Kind CheckpointKind + // Title is shown in the History panel; defaults to a descriptive label when empty. + Title string + // Detail is optional secondary context shown alongside the title. + Detail string + // PreCaptureFiles lists project-relative paths to snapshot immediately before work starts. + PreCaptureFiles []string +} + +// activeCheckpointTurn tracks an in-progress agent turn, task, or automation checkpoint. +type activeCheckpointTurn struct { + manifest CheckpointManifest + dir string + recorded map[string]bool + persisted bool + keepEmpty bool + countedAgent bool + projectDir string +} + +type checkpointState struct { + active *activeCheckpointTurn + list []CheckpointSummary + seq uint64 +} + +// ParseCheckpointManifest strictly decodes and validates a versioned checkpoint manifest YAML document, +// refusing empty documents, duplicate keys, unknown fields, trailing documents, and unsupported versions. +func ParseCheckpointManifest(data []byte) (*CheckpointManifest, error) { + if len(bytes.TrimSpace(data)) == 0 { + return nil, errors.New("editor: checkpoint manifest: empty document (missing version)") + } + if int64(len(data)) > maxCheckpointManifestBytes { + return nil, fmt.Errorf("editor: checkpoint manifest: document exceeds maximum size (%d bytes)", maxCheckpointManifestBytes) + } + var root yaml.Node + if err := yaml.Unmarshal(data, &root); err != nil { + return nil, fmt.Errorf("editor: checkpoint manifest: parse: %w", err) + } + if root.Kind != yaml.DocumentNode || len(root.Content) == 0 || root.Content[0].Kind != yaml.MappingNode { + return nil, errors.New("editor: checkpoint manifest: document must be a YAML mapping with version") + } + if err := checkDuplicateYAMLKeys(root.Content[0]); err != nil { + return nil, fmt.Errorf("editor: checkpoint manifest: %w", err) + } + hasVersion := false + for i := 0; i+1 < len(root.Content[0].Content); i += 2 { + if root.Content[0].Content[i].Value == "version" { + hasVersion = true + break + } + } + if !hasVersion { + return nil, errors.New("editor: checkpoint manifest: missing required field version") + } + + var m CheckpointManifest + dec := yaml.NewDecoder(bytes.NewReader(data)) + dec.KnownFields(true) + if err := dec.Decode(&m); err != nil { + return nil, fmt.Errorf("editor: checkpoint manifest: decode: %w", err) + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + if err == nil { + return nil, errors.New("editor: checkpoint manifest: unexpected trailing YAML document") + } + return nil, fmt.Errorf("editor: checkpoint manifest: decode: %w", err) + } + if err := ValidateCheckpointManifest(&m); err != nil { + return nil, err + } + return &m, nil +} + +// ValidateCheckpointManifest checks that m conforms to version 1 of the checkpoint manifest schema. +func ValidateCheckpointManifest(m *CheckpointManifest) error { + if m == nil { + return errors.New("editor: checkpoint manifest: nil document") + } + if m.Version != CheckpointVersion { + return fmt.Errorf("editor: checkpoint manifest: unsupported version %d (want %d)", m.Version, CheckpointVersion) + } + if err := validateCheckpointID(m.ID); err != nil { + return fmt.Errorf("editor: checkpoint manifest: %w", err) + } + if m.CreatedAt == "" { + return errors.New("editor: checkpoint manifest: createdAt is required") + } + if _, err := time.Parse(time.RFC3339, m.CreatedAt); err != nil { + return fmt.Errorf("editor: checkpoint manifest: createdAt %q must be RFC3339: %w", m.CreatedAt, err) + } + switch m.Who { + case HistoryAuthorAgent, HistoryAuthorYou, HistoryAuthorGit: + default: + return fmt.Errorf("editor: checkpoint manifest: invalid who %q (want agent, you, or git)", m.Who) + } + switch m.Kind { + case CheckpointKindTurn, CheckpointKindTask, CheckpointKindAutomation: + default: + return fmt.Errorf("editor: checkpoint manifest: invalid kind %q (want turn, task, or automation)", m.Kind) + } + if err := validateCheckpointText("title", m.Title, true); err != nil { + return fmt.Errorf("editor: checkpoint manifest: %w", err) + } + if err := validateCheckpointText("detail", m.Detail, false); err != nil { + return fmt.Errorf("editor: checkpoint manifest: %w", err) + } + if len(m.Files) > maxCheckpointFilesPerTurn { + return fmt.Errorf("editor: checkpoint manifest: too many files (%d > %d)", len(m.Files), maxCheckpointFilesPerTurn) + } + seen := make(map[string]bool, len(m.Files)) + for i, f := range m.Files { + clean, err := cleanCheckpointRelPath(f.Path) + if err != nil || clean != f.Path { + if err != nil { + return fmt.Errorf("editor: checkpoint manifest: files[%d]: %w", i, err) + } + return fmt.Errorf("editor: checkpoint manifest: files[%d].path %q must be canonical slash-separated relative path %q", i, f.Path, clean) + } + if seen[f.Path] { + return fmt.Errorf("editor: checkpoint manifest: duplicate file path %q", f.Path) + } + seen[f.Path] = true + if f.Size < 0 { + return fmt.Errorf("editor: checkpoint manifest: files[%d].size %d must not be negative", i, f.Size) + } + if f.Existed { + if f.Size > maxCheckpointFileBytes { + return fmt.Errorf("editor: checkpoint manifest: files[%d].size %d exceeds maximum %d", i, f.Size, maxCheckpointFileBytes) + } + if !validSHA256Hex(f.SHA256) { + return fmt.Errorf("editor: checkpoint manifest: files[%d].sha256 %q must be 64 lowercase hex characters", i, f.SHA256) + } + if f.Mode != "" { + if _, err := parseOctalFileMode(f.Mode); err != nil { + return fmt.Errorf("editor: checkpoint manifest: files[%d].mode: %w", i, err) + } + } + } else { + if f.Size != 0 || f.SHA256 != "" || f.Mode != "" { + return fmt.Errorf("editor: checkpoint manifest: files[%d]: non-existent file must not set size, sha256, or mode", i) + } + } + } + return nil +} + +// EncodeCheckpointManifest validates m and encodes it as deterministic 2-space YAML with files sorted by path. +func EncodeCheckpointManifest(m *CheckpointManifest) ([]byte, error) { + if err := ValidateCheckpointManifest(m); err != nil { + return nil, err + } + cp := *m + if len(m.Files) > 0 { + cp.Files = slices.Clone(m.Files) + slices.SortFunc(cp.Files, func(a, b CheckpointFile) int { + return strings.Compare(a.Path, b.Path) + }) + } + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(&cp); err != nil { + _ = enc.Close() + return nil, fmt.Errorf("editor: checkpoint manifest: encode: %w", err) + } + if err := enc.Close(); err != nil { + return nil, fmt.Errorf("editor: checkpoint manifest: encode: %w", err) + } + return buf.Bytes(), nil +} + +func validateCheckpointID(id string) error { + if id == "" { + return errors.New("id is required") + } + if len(id) > 128 { + return fmt.Errorf("id %q is too long", id) + } + if strings.Contains(id, "..") { + return fmt.Errorf("id %q must not contain '..'", id) + } + for _, r := range id { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { + continue + } + return fmt.Errorf("id %q contains invalid character %q", id, r) + } + return nil +} + +func validateCheckpointText(field, s string, required bool) error { + if s == "" { + if required { + return fmt.Errorf("%s is required", field) + } + return nil + } + if strings.TrimSpace(s) != s || strings.IndexFunc(s, unicode.IsControl) >= 0 { + return fmt.Errorf("%s %q must have no surrounding spaces or control characters", field, s) + } + return nil +} + +func validSHA256Hex(s string) bool { + if len(s) != 64 { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { + return false + } + } + return true +} + +func parseOctalFileMode(s string) (os.FileMode, error) { + if len(s) != 4 || s[0] != '0' { + return 0, fmt.Errorf("invalid octal mode %q (want 4 digits like 0644)", s) + } + v, err := strconv.ParseUint(s, 8, 32) + if err != nil || v > 0o777 { + return 0, fmt.Errorf("invalid octal mode %q", s) + } + return os.FileMode(v), nil +} + +func formatOctalFileMode(mode os.FileMode) string { + perm := mode.Perm() + if perm == 0 || perm == 0o644 { + return "" + } + return fmt.Sprintf("%04o", perm) +} + +// cleanCheckpointRelPath validates that rel names a regular project file inside the project root, +// outside .nsgo/ and .git/, and outside all You-only configuration files (permissions, tools, models, usage). +func cleanCheckpointRelPath(rel string) (string, error) { + if rel == "" { + return "", errors.New("path is empty") + } + if strings.IndexFunc(rel, unicode.IsControl) >= 0 { + return "", fmt.Errorf("path %q contains control characters", rel) + } + if strings.ContainsRune(rel, '\\') { + return "", fmt.Errorf("path %q must use forward slashes", rel) + } + if strings.ContainsRune(rel, ':') { + return "", fmt.Errorf("path %q contains invalid ':'", rel) + } + if path.IsAbs(rel) || filepath.IsAbs(rel) || filepath.VolumeName(rel) != "" { + return "", fmt.Errorf("path %q must be relative to the project root", rel) + } + clean := path.Clean(rel) + if clean == "." || clean == ".." || strings.HasPrefix(clean, "../") || !fs.ValidPath(clean) { + return "", fmt.Errorf("path %q leaves the project root", rel) + } + lower := strings.ToLower(clean) + if lower == ".nsgo" || strings.HasPrefix(lower, ".nsgo/") || lower == ".git" || strings.HasPrefix(lower, ".git/") { + return "", fmt.Errorf("path %q is inside reserved metadata directory", rel) + } + if dom, youOnly := MatchYouOnlyPath(clean); youOnly { + return "", fmt.Errorf("path %q is protected by the You-only rule (%s)", clean, dom.DisplayName()) + } + return clean, nil +} + +func (e *Editor) checkCheckpointYouOnly(cleanRel string) error { + if dom, ok := MatchYouOnlyPath(cleanRel); ok { + return fmt.Errorf("editor: checkpoint: %s is protected by the You-only rule (%s)", cleanRel, dom.DisplayName()) + } + if e != nil { + if dom, ok := e.CheckYouOnlyTarget(cleanRel); ok { + return fmt.Errorf("editor: checkpoint: %s is protected by the You-only rule (%s)", cleanRel, dom.DisplayName()) + } + } + return nil +} + +// resolvePathNoSymlinks resolves cleanRel inside rootDir and refuses ANY symlink along the path +// (including dangling symlinks and internal symlinks pointing to reserved or You-only files). +func resolvePathNoSymlinks(rootDir, rel string) (string, error) { + clean, err := cleanCheckpointRelPath(rel) + if err != nil { + return "", err + } + rootAbs, err := filepath.Abs(rootDir) + if err != nil { + return "", err + } + if realRoot, err := filepath.EvalSymlinks(rootAbs); err == nil { + rootAbs = realRoot + } + parts := strings.Split(clean, "/") + cur := rootAbs + for i, part := range parts { + cur = filepath.Join(cur, part) + info, lerr := os.Lstat(cur) + if lerr != nil { + if errors.Is(lerr, fs.ErrNotExist) { + // Remaining path segments do not exist yet. + break + } + return "", fmt.Errorf("editor: checkpoint: stat %s: %w", clean, lerr) + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("editor: checkpoint: %s traverses or targets a symlink", clean) + } + if i < len(parts)-1 && !info.IsDir() { + return "", fmt.Errorf("editor: checkpoint: %s parent %q is not a directory", clean, part) + } + } + abs := filepath.Join(rootAbs, filepath.FromSlash(clean)) + if !isSubpath(rootAbs, abs) { + return "", fmt.Errorf("editor: checkpoint: %s escapes root", clean) + } + return abs, nil +} + +// readFileBoundedNoSymlink reads a regular non-symlink file capped at maxBytes. +func readFileBoundedNoSymlink(abs string, maxBytes int64) ([]byte, os.FileInfo, error) { + linfo, err := os.Lstat(abs) + if err != nil { + return nil, nil, err + } + if linfo.Mode()&os.ModeSymlink != 0 { + return nil, nil, fmt.Errorf("editor: checkpoint: refusing symlink %s", filepath.Base(abs)) + } + if !linfo.Mode().IsRegular() { + return nil, nil, fmt.Errorf("editor: checkpoint: %s is not a regular file", filepath.Base(abs)) + } + if maxBytes > 0 && linfo.Size() > maxBytes { + return nil, nil, fmt.Errorf("editor: checkpoint: file %s exceeds maximum size (%d bytes)", filepath.Base(abs), maxBytes) + } + f, err := os.Open(abs) + if err != nil { + return nil, nil, err + } + defer func() { _ = f.Close() }() + info, err := f.Stat() + if err != nil { + return nil, nil, err + } + if !info.Mode().IsRegular() { + return nil, nil, fmt.Errorf("editor: checkpoint: %s is not a regular file", filepath.Base(abs)) + } + if maxBytes > 0 && info.Size() > maxBytes { + return nil, nil, fmt.Errorf("editor: checkpoint: file %s exceeds maximum size (%d bytes)", filepath.Base(abs), maxBytes) + } + var data []byte + if maxBytes > 0 { + data, err = io.ReadAll(io.LimitReader(f, maxBytes+1)) + if err != nil { + return nil, nil, err + } + if int64(len(data)) > maxBytes { + return nil, nil, fmt.Errorf("editor: checkpoint: file %s exceeds maximum size (%d bytes)", filepath.Base(abs), maxBytes) + } + } else { + data, err = io.ReadAll(f) + if err != nil { + return nil, nil, err + } + } + return data, info, nil +} + +// checkNotSymlinkDir ensures path p, if it exists, is a real directory and not a symlink. +func checkNotSymlinkDir(p string) error { + info, err := os.Lstat(p) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("editor: checkpoint: refusing symlink directory %s", filepath.Base(p)) + } + if !info.IsDir() { + return fmt.Errorf("editor: checkpoint: %s is not a directory", filepath.Base(p)) + } + return nil +} + +// projectDirPath returns the open project's root directory, or "" without a project. +func (e *Editor) projectDirPath() string { + if e == nil || e.Project == nil || e.ProjectPath == "" { + return "" + } + return filepath.Dir(e.ProjectPath) +} + +// CheckpointsDir returns the OS path to the open project's .nsgo/checkpoints directory, or "" without a project. +func (e *Editor) CheckpointsDir() string { + root := e.projectDirPath() + if root == "" { + return "" + } + return filepath.Join(root, filepath.FromSlash(CheckpointsDir)) +} + +func (e *Editor) effectiveCheckpointMaxBytes() int64 { + if e != nil && e.CheckpointMaxBytes > 0 { + return e.CheckpointMaxBytes + } + return DefaultCheckpointMaxBytes +} + +func ensureCheckpointsGitIgnore(projectDir string) error { + nsgoDir := filepath.Join(projectDir, ".nsgo") + if err := checkNotSymlinkDir(nsgoDir); err != nil { + return err + } + cpDir := filepath.Join(projectDir, filepath.FromSlash(CheckpointsDir)) + if err := checkNotSymlinkDir(cpDir); err != nil { + return err + } + if err := os.MkdirAll(cpDir, 0o755); err != nil { + return err + } + cpIgnore := filepath.Join(cpDir, ".gitignore") + if info, err := os.Lstat(cpIgnore); errors.Is(err, fs.ErrNotExist) { + if err := writeFileAtomic(cpIgnore, []byte("*\n")); err != nil { + return err + } + } else if err == nil && info.Mode()&os.ModeSymlink != 0 { + return errors.New("editor: checkpoint: refusing symlink .nsgo/checkpoints/.gitignore") + } + nsgoIgnore := filepath.Join(nsgoDir, ".gitignore") + if info, err := os.Lstat(nsgoIgnore); errors.Is(err, fs.ErrNotExist) { + if err := writeFileAtomic(nsgoIgnore, []byte("checkpoints/\n")); err != nil { + return err + } + } else if err == nil && info.Mode()&os.ModeSymlink != 0 { + return errors.New("editor: checkpoint: refusing symlink .nsgo/.gitignore") + } + return nil +} + +func (e *Editor) nextCheckpointID(cpRoot string, now time.Time) string { + stamp := now.UTC().Format("20060102T150405Z") + for { + e.checkpoints.seq++ + id := fmt.Sprintf("%s-%04d", stamp, e.checkpoints.seq) + if _, err := os.Lstat(filepath.Join(cpRoot, id)); errors.Is(err, fs.ErrNotExist) { + return id + } + } +} + +// ActiveTurnID returns the checkpoint ID of the currently active agent turn, or "" when no turn is active. +func (e *Editor) ActiveTurnID() string { + if e == nil || e.checkpoints.active == nil { + return "" + } + return e.checkpoints.active.manifest.ID +} + +// ActiveTurnFileCount reports how many files have been recorded into the currently active checkpoint turn. +func (e *Editor) ActiveTurnFileCount() int { + if e == nil || e.checkpoints.active == nil { + return 0 + } + return len(e.checkpoints.active.manifest.Files) +} + +// BeginCheckpointTurn starts an agent turn checkpoint over the open project. Before the turn first writes +// any file (scene, prefab, data, game.yaml, Go code, or binary media), its original bytes are stored +// under .nsgo/checkpoints//. Call EndCheckpointTurn when the turn finishes. +func (e *Editor) BeginCheckpointTurn(title string) (string, error) { + return e.BeginCheckpointTurnWith(CheckpointOptions{ + Who: HistoryAuthorAgent, + Kind: CheckpointKindTurn, + Title: title, + }) +} + +// BeginCheckpointTurnWith starts a persistent checkpoint turn configured by opts. +func (e *Editor) BeginCheckpointTurnWith(opts CheckpointOptions) (string, error) { + if e == nil { + return "", errors.New("editor: nil editor") + } + projectDir := e.projectDirPath() + if projectDir == "" { + return "", ErrNoProject + } + if e.checkpoints.active != nil { + return "", fmt.Errorf("editor: checkpoint turn %q is already active", e.checkpoints.active.manifest.ID) + } + who := opts.Who + if who == "" { + who = HistoryAuthorAgent + } + kind := opts.Kind + if kind == "" { + kind = CheckpointKindTurn + } + title := strings.TrimSpace(opts.Title) + if title == "" { + switch kind { + case CheckpointKindTask: + title = "Background task · checkpoint before start" + case CheckpointKindAutomation: + title = "Automation · checkpoint before start" + default: + title = "Agent turn" + } + } + detail := strings.TrimSpace(opts.Detail) + now := e.HistoryNow().UTC() + cpRoot := filepath.Join(projectDir, filepath.FromSlash(CheckpointsDir)) + id := e.nextCheckpointID(cpRoot, now) + turn := &activeCheckpointTurn{ + manifest: CheckpointManifest{ + Version: CheckpointVersion, + ID: id, + CreatedAt: now.Format(time.RFC3339), + Who: who, + Kind: kind, + Title: title, + Detail: detail, + }, + dir: filepath.Join(cpRoot, id), + recorded: make(map[string]bool), + keepEmpty: kind == CheckpointKindTask || kind == CheckpointKindAutomation, + countedAgent: who == HistoryAuthorAgent, + projectDir: projectDir, + } + e.checkpoints.active = turn + if turn.countedAgent { + e.EnterAgentContext() + } + + if len(opts.PreCaptureFiles) > 0 { + for _, f := range opts.PreCaptureFiles { + if err := e.RecordCheckpointFile(f); err != nil { + e.abortActiveTurn() + return "", err + } + } + } + if turn.keepEmpty && !turn.persisted { + if err := e.persistActiveTurnManifest(); err != nil { + e.abortActiveTurn() + return "", err + } + } + return id, nil +} + +func (e *Editor) abortActiveTurn() { + if e == nil || e.checkpoints.active == nil { + return + } + turn := e.checkpoints.active + e.checkpoints.active = nil + if turn.countedAgent { + e.LeaveAgentContext() + } + if turn.persisted && turn.dir != "" { + _ = os.RemoveAll(turn.dir) + } +} + +// AbortCheckpointTurn cancels the currently active checkpoint turn and removes its incomplete checkpoint directory. +func (e *Editor) AbortCheckpointTurn() { + if e == nil || e.checkpoints.active == nil { + return + } + e.abortActiveTurn() + _, _ = e.LoadCheckpoints() + e.notify() +} + +// FinishCheckpointTurnOnError finalizes the active checkpoint turn after a failure or panic: +// if no files were captured (and the turn is not a pre-start task/automation checkpoint), it discards +// the empty checkpoint; otherwise it persists the checkpoint with detail so partial edits stay restorable. +func (e *Editor) FinishCheckpointTurnOnError(detail string) (*CheckpointSummary, error) { + if e == nil || e.checkpoints.active == nil { + return nil, nil + } + if len(e.checkpoints.active.manifest.Files) == 0 && !e.checkpoints.active.keepEmpty { + e.AbortCheckpointTurn() + return nil, nil + } + if strings.TrimSpace(detail) == "" { + detail = "interrupted" + } + return e.EndCheckpointTurn(detail) +} + +// RecordCheckpointFile snapshots the pre-turn bytes of relPath into the active checkpoint before +// the turn first modifies relPath. Repeated calls for the same path in the same turn are no-ops, +// preserving the original pre-turn bytes. Binary files are stored verbatim. +// Refuses paths outside the project root, symlinks, .nsgo/, .git/, and You-only files. +func (e *Editor) RecordCheckpointFile(relPath string) error { + if e == nil || e.checkpoints.active == nil { + return nil + } + turn := e.checkpoints.active + clean, err := cleanCheckpointRelPath(strings.ReplaceAll(relPath, `\`, "/")) + if err != nil { + return fmt.Errorf("editor: checkpoint: %w", err) + } + if err := e.checkCheckpointYouOnly(clean); err != nil { + return err + } + if turn.recorded[clean] { + return nil + } + if len(turn.manifest.Files) >= maxCheckpointFilesPerTurn { + return fmt.Errorf("editor: checkpoint: reached maximum %d files per turn", maxCheckpointFilesPerTurn) + } + abs, err := resolvePathNoSymlinks(turn.projectDir, clean) + if err != nil { + return err + } + + // Capture the exact pre-turn bytes. If the file is an open dirty scene tab or dirty game.yaml, + // capture the editor's current bytes; otherwise read the raw bytes from disk so comments, + // hand-formatting, and binary media are preserved byte-for-byte. + var ( + data []byte + existed bool + mode os.FileMode = 0o644 + ) + if dirtyBytes, ok := e.dirtyOpenFileBytes(clean); ok { + if int64(len(dirtyBytes)) > maxCheckpointFileBytes { + return fmt.Errorf("editor: checkpoint: %s exceeds maximum file size (%d bytes)", clean, maxCheckpointFileBytes) + } + data = dirtyBytes + existed = true + if info, statErr := os.Lstat(abs); statErr == nil && info.Mode().IsRegular() { + mode = info.Mode().Perm() + } + } else { + raw, info, readErr := readFileBoundedNoSymlink(abs, maxCheckpointFileBytes) + switch { + case readErr == nil: + data = raw + existed = true + mode = info.Mode().Perm() + case errors.Is(readErr, fs.ErrNotExist): + existed = false + default: + return fmt.Errorf("editor: checkpoint: read %s: %w", clean, readErr) + } + } + + if err := ensureCheckpointsGitIgnore(turn.projectDir); err != nil { + return err + } + if err := checkNotSymlinkDir(turn.dir); err != nil { + return err + } + if err := os.MkdirAll(turn.dir, 0o755); err != nil { + return err + } + + entry := CheckpointFile{ + Path: clean, + Existed: existed, + } + if existed { + sum := sha256.Sum256(data) + entry.Size = int64(len(data)) + entry.SHA256 = hex.EncodeToString(sum[:]) + entry.Mode = formatOctalFileMode(mode) + + filesRoot := filepath.Join(turn.dir, "files") + if err := checkNotSymlinkDir(filesRoot); err != nil { + return err + } + if err := os.MkdirAll(filesRoot, 0o755); err != nil { + return err + } + dst, derr := resolvePathNoSymlinks(filesRoot, clean) + if derr != nil { + return derr + } + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return err + } + if err := writeFileAtomic(dst, data); err != nil { + return err + } + } + + turn.manifest.Files = append(turn.manifest.Files, entry) + slices.SortFunc(turn.manifest.Files, func(a, b CheckpointFile) int { + return strings.Compare(a.Path, b.Path) + }) + turn.recorded[clean] = true + return e.persistActiveTurnManifest() +} + +func (e *Editor) persistActiveTurnManifest() error { + turn := e.checkpoints.active + if turn == nil { + return nil + } + if err := ensureCheckpointsGitIgnore(turn.projectDir); err != nil { + return err + } + if err := checkNotSymlinkDir(turn.dir); err != nil { + return err + } + if err := os.MkdirAll(turn.dir, 0o755); err != nil { + return err + } + data, err := EncodeCheckpointManifest(&turn.manifest) + if err != nil { + return err + } + mPath := filepath.Join(turn.dir, CheckpointManifestFile) + if info, lerr := os.Lstat(mPath); lerr == nil && info.Mode()&os.ModeSymlink != 0 { + return errors.New("editor: checkpoint: refusing symlink manifest.yaml") + } + if err := writeFileAtomic(mPath, data); err != nil { + return err + } + turn.persisted = true + return nil +} + +// dirtyOpenFileBytes returns the in-memory bytes for relPath if it corresponds to an open dirty +// editor document (scene tab or game.yaml). Clean documents return false so callers read verbatim disk bytes. +func (e *Editor) dirtyOpenFileBytes(relPath string) ([]byte, bool) { + if e == nil { + return nil, false + } + if relPath == project.FileName && e.ProjectDirty() { + if data, err := project.Encode(e.Project); err == nil { + return data, true + } + } + e.syncActiveTab() + for i, t := range e.tabs { + if t.scenePath == relPath && e.tabDirtyAt(i) && t.doc != nil { + if data, err := sceneformat.Encode(t.doc); err == nil { + return data, true + } + } + } + return nil, false +} + +// WriteAgentFile records relPath's pre-turn bytes into the active checkpoint (if any) before +// writing data atomically to relPath inside the open project. Open scene tabs or game.yaml +// matching relPath are reloaded cleanly to stay synchronized with disk. +// Refuses You-only files, symlinks, paths outside the project root, and edits while playing or previewing history. +func (e *Editor) WriteAgentFile(relPath string, data []byte) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } + if e.StartScreenOpen() || e.MergeConflictOpen() { + return errors.New("editor: file edits are unavailable while a full-window screen is open") + } + projectDir := e.projectDirPath() + if projectDir == "" { + return ErrNoProject + } + if int64(len(data)) > maxCheckpointFileBytes { + return fmt.Errorf("editor: file %q exceeds maximum write size (%d bytes)", relPath, maxCheckpointFileBytes) + } + clean, err := cleanCheckpointRelPath(strings.ReplaceAll(relPath, `\`, "/")) + if err != nil { + return fmt.Errorf("editor: %w", err) + } + if err := e.checkCheckpointYouOnly(clean); err != nil { + return err + } + abs, err := resolvePathNoSymlinks(projectDir, clean) + if err != nil { + return err + } + if e.checkpoints.active != nil { + if err := e.RecordCheckpointFile(clean); err != nil { + return err + } + } + if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { + return err + } + if err := writeFileAtomic(abs, data); err != nil { + return err + } + e.syncOpenDocumentsFromRestoredFile(clean, abs, data, true) + e.filesRev++ + e.assetsRev++ + e.snapshotProjectTree() + e.invalidateProjectIndex() + e.RefreshChangesCount() + e.notify() + return nil +} + +// DeleteAgentFile records relPath's pre-turn bytes into the active checkpoint (if any) before +// removing relPath from the open project. +// Refuses You-only files, symlinks, paths outside the project root, and edits while playing or previewing history. +func (e *Editor) DeleteAgentFile(relPath string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.HistoryPreviewActive() { + return ErrHistoryPreview + } + if e.StartScreenOpen() || e.MergeConflictOpen() { + return errors.New("editor: file deletions are unavailable while a full-window screen is open") + } + projectDir := e.projectDirPath() + if projectDir == "" { + return ErrNoProject + } + clean, err := cleanCheckpointRelPath(strings.ReplaceAll(relPath, `\`, "/")) + if err != nil { + return fmt.Errorf("editor: %w", err) + } + if err := e.checkCheckpointYouOnly(clean); err != nil { + return err + } + abs, err := resolvePathNoSymlinks(projectDir, clean) + if err != nil { + return err + } + if e.checkpoints.active != nil { + if err := e.RecordCheckpointFile(clean); err != nil { + return err + } + } + if err := os.Remove(abs); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + e.syncOpenDocumentsFromRestoredFile(clean, abs, nil, false) + e.filesRev++ + e.assetsRev++ + e.snapshotProjectTree() + e.invalidateProjectIndex() + e.RefreshChangesCount() + e.notify() + return nil +} + +// EndCheckpointTurn finalizes the currently active checkpoint turn, persists its manifest (or cleans up +// an empty regular turn that touched no files), enforces the checkpoint size cap, and refreshes History. +func (e *Editor) EndCheckpointTurn(detail string) (*CheckpointSummary, error) { + if e == nil { + return nil, errors.New("editor: nil editor") + } + turn := e.checkpoints.active + if turn == nil { + return nil, nil + } + if d := strings.TrimSpace(detail); d != "" { + turn.manifest.Detail = d + } + if len(turn.manifest.Files) == 0 && !turn.keepEmpty { + e.abortActiveTurn() + return nil, nil + } + if err := e.persistActiveTurnManifest(); err != nil { + return nil, err + } + finishedID := turn.manifest.ID + e.checkpoints.active = nil + if turn.countedAgent { + e.LeaveAgentContext() + } + + if _, err := e.PruneCheckpoints(); err != nil { + return nil, err + } + list, err := e.LoadCheckpoints() + if err != nil { + return nil, err + } + e.notify() + for i := range list { + if list[i].ID == finishedID { + cp := list[i] + return &cp, nil + } + } + return nil, nil +} + +// RunCheckpointTurn runs fn inside BeginCheckpointTurn / EndCheckpointTurn, recording every file fn touches +// into one persistent checkpoint. If fn returns an error or panics and no files were modified, +// the empty checkpoint is discarded; if files were already modified, the checkpoint is kept so +// the partial turn remains restorable. +func (e *Editor) RunCheckpointTurn(title string, fn func() error) (*CheckpointSummary, error) { + if _, err := e.BeginCheckpointTurn(title); err != nil { + return nil, err + } + completed := false + defer func() { + if !completed { + _, _ = e.FinishCheckpointTurnOnError("interrupted") + } + }() + runErr := fn() + completed = true + if runErr != nil { + summary, _ := e.FinishCheckpointTurnOnError("interrupted") + return summary, runErr + } + return e.EndCheckpointTurn("") +} + +// defaultPreStartCaptureFiles returns the project-relative paths of open scenes and game.yaml +// to snapshot before an autonomous task or automation begins when no explicit file list is given. +func (e *Editor) defaultPreStartCaptureFiles() []string { + if e == nil || e.Project == nil || e.ProjectPath == "" { + return nil + } + var out []string + add := func(p string) { + if p == "" { + return + } + if clean, err := cleanCheckpointRelPath(p); err == nil && e.checkCheckpointYouOnly(clean) == nil && !slices.Contains(out, clean) { + out = append(out, clean) + } + } + e.syncActiveTab() + for _, t := range e.tabs { + add(t.scenePath) + } + add(project.FileName) + slices.Sort(out) + return out +} + +// TakeCheckpointBeforeTask takes a persistent checkpoint under .nsgo/checkpoints/ immediately +// before an autonomous background task starts. When files is empty, the open scene(s) and game.yaml +// are captured. Any active turn must be ended first. +func (e *Editor) TakeCheckpointBeforeTask(title string, files ...string) (*CheckpointSummary, error) { + return e.takePreStartCheckpoint(CheckpointKindTask, title, files...) +} + +// TakeCheckpointBeforeAutomation takes a persistent checkpoint under .nsgo/checkpoints/ immediately +// before an automation runs. When files is empty, the open scene(s) and game.yaml are captured. +func (e *Editor) TakeCheckpointBeforeAutomation(title string, files ...string) (*CheckpointSummary, error) { + return e.takePreStartCheckpoint(CheckpointKindAutomation, title, files...) +} + +func (e *Editor) takePreStartCheckpoint(kind CheckpointKind, title string, files ...string) (*CheckpointSummary, error) { + if len(files) == 0 { + files = e.defaultPreStartCaptureFiles() + } + cleanTitle := formatPreStartCheckpointTitle(kind, title) + if _, err := e.BeginCheckpointTurnWith(CheckpointOptions{ + Who: HistoryAuthorAgent, + Kind: kind, + Title: cleanTitle, + PreCaptureFiles: files, + }); err != nil { + return nil, err + } + return e.EndCheckpointTurn("") +} + +// RunTaskWithCheckpoint takes a pre-start checkpoint before running autonomous task fn, keeps it +// active so every additional file fn touches is captured before its first write, and finalizes it. +func (e *Editor) RunTaskWithCheckpoint(title string, files []string, fn func() error) (*CheckpointSummary, error) { + return e.runPreStartCheckpoint(CheckpointKindTask, title, files, fn) +} + +// RunAutomationWithCheckpoint takes a pre-start checkpoint before running automation fn, keeps it +// active so every additional file fn touches is captured before its first write, and finalizes it. +func (e *Editor) RunAutomationWithCheckpoint(title string, files []string, fn func() error) (*CheckpointSummary, error) { + return e.runPreStartCheckpoint(CheckpointKindAutomation, title, files, fn) +} + +func formatPreStartCheckpointTitle(kind CheckpointKind, title string) string { + cleanTitle := strings.TrimSpace(title) + if cleanTitle == "" { + if kind == CheckpointKindAutomation { + return "Automation · checkpoint before start" + } + return "Task · checkpoint before start" + } + if !strings.Contains(strings.ToLower(cleanTitle), "checkpoint") { + cleanTitle += " · checkpoint before start" + } + return cleanTitle +} + +func (e *Editor) runPreStartCheckpoint(kind CheckpointKind, title string, files []string, fn func() error) (*CheckpointSummary, error) { + if len(files) == 0 { + files = e.defaultPreStartCaptureFiles() + } + if _, err := e.BeginCheckpointTurnWith(CheckpointOptions{ + Who: HistoryAuthorAgent, + Kind: kind, + Title: formatPreStartCheckpointTitle(kind, title), + PreCaptureFiles: files, + }); err != nil { + return nil, err + } + completed := false + defer func() { + if !completed { + _, _ = e.FinishCheckpointTurnOnError("interrupted") + } + }() + runErr := fn() + completed = true + detail := "" + if runErr != nil { + detail = "failed" + } + summary, endErr := e.EndCheckpointTurn(detail) + if runErr != nil { + return summary, runErr + } + return summary, endErr +} + +// LoadCheckpoints scans .nsgo/checkpoints/ in the open project, parses each manifest, sorts newest +// first, and updates the editor's cached checkpoint list. Invalid, symlinked, or non-checkpoint directories are skipped. +func (e *Editor) LoadCheckpoints() ([]CheckpointSummary, error) { + if e == nil { + return nil, nil + } + projectDir := e.projectDirPath() + if projectDir == "" { + e.checkpoints.list = nil + return nil, nil + } + nsgoDir := filepath.Join(projectDir, ".nsgo") + if err := checkNotSymlinkDir(nsgoDir); err != nil { + e.checkpoints.list = nil + return nil, err + } + cpRoot := filepath.Join(projectDir, filepath.FromSlash(CheckpointsDir)) + if err := checkNotSymlinkDir(cpRoot); err != nil { + e.checkpoints.list = nil + return nil, err + } + entries, err := os.ReadDir(cpRoot) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + e.checkpoints.list = nil + return nil, nil + } + return nil, err + } + var out []CheckpointSummary + scanned := 0 + for _, de := range entries { + if scanned >= maxCheckpointDirs { + break + } + if de.Type()&fs.ModeSymlink != 0 || !de.IsDir() || strings.HasPrefix(de.Name(), ".") { + continue + } + if validateCheckpointID(de.Name()) != nil { + continue + } + scanned++ + dir := filepath.Join(cpRoot, de.Name()) + if checkNotSymlinkDir(dir) != nil { + continue + } + mPath := filepath.Join(dir, CheckpointManifestFile) + data, _, readErr := readFileBoundedNoSymlink(mPath, maxCheckpointManifestBytes) + if readErr != nil { + continue + } + m, parseErr := ParseCheckpointManifest(data) + if parseErr != nil || m.ID != de.Name() { + continue + } + total := dirSizeBytes(dir) + out = append(out, CheckpointSummary{ + CheckpointManifest: *m, + TotalBytes: total, + }) + } + sortCheckpointsNewestFirst(out) + e.checkpoints.list = out + return slices.Clone(out), nil +} + +func sortCheckpointsNewestFirst(list []CheckpointSummary) { + slices.SortFunc(list, func(a, b CheckpointSummary) int { + ta, errA := time.Parse(time.RFC3339, a.CreatedAt) + tb, errB := time.Parse(time.RFC3339, b.CreatedAt) + if errA == nil && errB == nil && !ta.Equal(tb) { + if ta.After(tb) { + return -1 + } + return 1 + } + return strings.Compare(b.ID, a.ID) + }) +} + +func dirSizeBytes(dir string) int64 { + var total int64 + _ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.Type()&fs.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + return nil + } + if info, err := d.Info(); err == nil { + total += info.Size() + } + return nil + }) + return total +} + +// Checkpoints returns the open project's persisted checkpoints, newest first. +func (e *Editor) Checkpoints() []CheckpointSummary { + if e == nil || len(e.checkpoints.list) == 0 { + return nil + } + out := make([]CheckpointSummary, len(e.checkpoints.list)) + for i, c := range e.checkpoints.list { + c.Files = slices.Clone(c.Files) + out[i] = c + } + return out +} + +// CheckpointManifest loads and validates the manifest of checkpoint id from .nsgo/checkpoints//manifest.yaml. +func (e *Editor) CheckpointManifest(id string) (*CheckpointManifest, error) { + if e == nil { + return nil, errors.New("editor: nil editor") + } + if err := validateCheckpointID(id); err != nil { + return nil, fmt.Errorf("editor: checkpoint: %w", err) + } + projectDir := e.projectDirPath() + if projectDir == "" { + return nil, ErrNoProject + } + if err := checkNotSymlinkDir(filepath.Join(projectDir, ".nsgo")); err != nil { + return nil, err + } + cpRoot := filepath.Join(projectDir, filepath.FromSlash(CheckpointsDir)) + if err := checkNotSymlinkDir(cpRoot); err != nil { + return nil, err + } + cpDir := filepath.Join(cpRoot, id) + if err := checkNotSymlinkDir(cpDir); err != nil { + return nil, err + } + data, _, err := readFileBoundedNoSymlink(filepath.Join(cpDir, CheckpointManifestFile), maxCheckpointManifestBytes) + if err != nil { + return nil, fmt.Errorf("editor: checkpoint %q: %w", id, err) + } + m, err := ParseCheckpointManifest(data) + if err != nil { + return nil, err + } + if m.ID != id { + return nil, fmt.Errorf("editor: checkpoint %q: manifest id %q does not match directory", id, m.ID) + } + return m, nil +} + +// CheckpointFileBytes returns the saved pre-turn bytes of relPath from checkpoint id, whether it +// existed before the turn, and any error (including size or SHA-256 mismatch). +func (e *Editor) CheckpointFileBytes(id, relPath string) ([]byte, bool, error) { + m, err := e.CheckpointManifest(id) + if err != nil { + return nil, false, err + } + clean, err := cleanCheckpointRelPath(strings.ReplaceAll(relPath, `\`, "/")) + if err != nil { + return nil, false, err + } + for _, f := range m.Files { + if f.Path != clean { + continue + } + if !f.Existed { + return nil, false, nil + } + data, err := readVerifiedCheckpointFile(filepath.Join(e.CheckpointsDir(), id), f) + if err != nil { + return nil, false, err + } + return data, true, nil + } + return nil, false, fmt.Errorf("editor: checkpoint %q does not record %q", id, clean) +} + +func readVerifiedCheckpointFile(cpDir string, f CheckpointFile) ([]byte, error) { + if !f.Existed { + return nil, nil + } + filesRoot := filepath.Join(cpDir, "files") + if err := checkNotSymlinkDir(filesRoot); err != nil { + return nil, err + } + abs, err := resolvePathNoSymlinks(filesRoot, f.Path) + if err != nil { + return nil, err + } + data, _, err := readFileBoundedNoSymlink(abs, maxCheckpointFileBytes) + if err != nil { + return nil, fmt.Errorf("editor: checkpoint: read saved %s: %w", f.Path, err) + } + if int64(len(data)) != f.Size { + return nil, fmt.Errorf("editor: checkpoint: %s size mismatch (got %d, want %d)", f.Path, len(data), f.Size) + } + sum := sha256.Sum256(data) + got := hex.EncodeToString(sum[:]) + if got != f.SHA256 { + return nil, fmt.Errorf("editor: checkpoint: %s checksum mismatch (got %s, want %s)", f.Path, got, f.SHA256) + } + return data, nil +} + +// PruneCheckpoints drops the oldest completed checkpoints under .nsgo/checkpoints/ until total +// storage is within CheckpointMaxBytes (defaulting to DefaultCheckpointMaxBytes), keeping at least +// the newest checkpoint and never deleting an active turn. Returns the number of dropped checkpoints. +func (e *Editor) PruneCheckpoints() (int, error) { + if e == nil { + return 0, nil + } + list, err := e.LoadCheckpoints() + if err != nil { + return 0, err + } + capBytes := e.effectiveCheckpointMaxBytes() + if capBytes <= 0 || len(list) <= 1 { + return 0, nil + } + var total int64 + for _, c := range list { + total += c.TotalBytes + } + if total <= capBytes { + return 0, nil + } + activeID := e.ActiveTurnID() + cpRoot := e.CheckpointsDir() + dropped := 0 + // list is newest first, so iterate from oldest (end) toward newest, leaving at least index 0. + for i := len(list) - 1; i >= 1 && total > capBytes; i-- { + c := list[i] + if c.ID == activeID { + continue + } + if err := os.RemoveAll(filepath.Join(cpRoot, c.ID)); err != nil { + return dropped, err + } + total -= c.TotalBytes + dropped++ + } + if dropped > 0 { + _, _ = e.LoadCheckpoints() + } + return dropped, nil +} + +// fileRestoreState captures a project file's exact on-disk state plus any open-editor in-memory state. +type fileRestoreState struct { + projectDir string + relPath string + absPath string + existed bool + bytes []byte + mode os.FileMode + sceneDoc *sceneformat.SceneDoc + sceneSaved []byte + hadScene bool + projDoc *project.File + projSaved []byte + hadProj bool +} + +// checkpointRestoreCmd restores every file recorded in a checkpoint back to its pre-turn bytes +// as one undoable step; Undo puts back every file (and open editor state) as it was before Restore. +type checkpointRestoreCmd struct { + ed *Editor + label string + summary string + detail string + files []string + cpID string + before []fileRestoreState + after []fileRestoreState + applied bool +} + +func (c *checkpointRestoreCmd) Label() string { return c.label } +func (c *checkpointRestoreCmd) Do() { _ = c.do() } +func (c *checkpointRestoreCmd) Undo() { _ = c.undo() } + +func (c *checkpointRestoreCmd) historyMeta() HistoryMeta { + return HistoryMeta{ + Author: HistoryAuthorYou, + Summary: c.summary, + Detail: c.detail, + Files: slices.Clone(c.files), + } +} + +func (c *checkpointRestoreCmd) do() error { + if err := applyFileRestoreStates(c.ed, c.after, c.before); err != nil { + return err + } + c.applied = true + return nil +} + +func (c *checkpointRestoreCmd) undo() error { + if err := applyFileRestoreStates(c.ed, c.before, c.after); err != nil { + return err + } + c.applied = false + return nil +} + +func applyFileRestoreStates(ed *Editor, target, fallback []fileRestoreState) error { + // Pre-validate every target path against symlinks and You-only boundaries before writing anything. + for _, st := range target { + if err := ed.checkCheckpointYouOnly(st.relPath); err != nil { + return err + } + if _, err := resolvePathNoSymlinks(st.projectDir, st.relPath); err != nil { + return err + } + } + written := 0 + for i, st := range target { + if err := writeOneRestoreState(st); err != nil { + // Roll back previously written files to fallback state. + for j := written - 1; j >= 0; j-- { + _ = writeOneRestoreState(fallback[j]) + } + return err + } + written = i + 1 + } + for _, st := range target { + if st.hadScene { + ed.applyRestoredSceneTabState(st) + } else if st.hadProj { + ed.applyRestoredProjectState(st) + } else { + ed.syncOpenDocumentsFromRestoredFile(st.relPath, st.absPath, st.bytes, st.existed) + } + } + ed.filesRev++ + ed.assetsRev++ + ed.snapshotProjectTree() + ed.invalidateProjectIndex() + ed.rebuildDependentTabs(ed.activeTabID()) + ed.RefreshChangesCount() + ed.CheckProblems() + return nil +} + +func writeOneRestoreState(st fileRestoreState) error { + abs, err := resolvePathNoSymlinks(st.projectDir, st.relPath) + if err != nil { + return fmt.Errorf("editor: restore %s: %w", st.relPath, err) + } + if !st.existed { + if err := os.Remove(abs); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("editor: restore %s: %w", st.relPath, err) + } + return nil + } + if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { + return fmt.Errorf("editor: restore %s: %w", st.relPath, err) + } + if err := writeFileAtomic(abs, st.bytes); err != nil { + return fmt.Errorf("editor: restore %s: %w", st.relPath, err) + } + if st.mode != 0 && st.mode != 0o644 { + _ = os.Chmod(abs, st.mode) + } + return nil +} + +func (e *Editor) applyRestoredSceneTabState(st fileRestoreState) { + if e == nil || st.sceneDoc == nil { + return + } + e.syncActiveTab() + for i, t := range e.tabs { + if t.scenePath != st.relPath && canonicalTabFilePath(t.filePath) != canonicalTabFilePath(st.absPath) { + continue + } + cloned := st.sceneDoc.Clone() + saved := append([]byte(nil), st.sceneSaved...) + var diskSnap diskSnapshot + if st.existed { + diskSnap = makeDiskSnapshot(st.absPath, st.bytes) + } + t.doc = cloned + t.sceneSaved = saved + t.sceneDisk = diskSnap + if i == e.activeTab { + e.Doc = cloned + e.sceneSaved = saved + if st.existed { + e.recordSceneDiskSnapshot(st.absPath, st.bytes) + } else { + e.clearSceneDiskSnapshot() + } + e.pruneSelection() + e.keepValidActiveLayer() + e.s3d.stale = true + e.Rebuild() + e.syncActiveTab() + } else { + if built, err := e.buildSceneDoc(cloned); err == nil { + built.DrawAllTiles = true + t.built = built + t.buildErr = nil + } + } + } +} + +func (e *Editor) applyRestoredProjectState(st fileRestoreState) { + if e == nil || st.projDoc == nil { + return + } + e.Project = st.projDoc.Clone() + e.projectSaved = append([]byte(nil), st.projSaved...) + e.syncAudioMixer() + if st.existed { + e.recordProjectDiskSnapshot(st.absPath, st.bytes) + } else { + e.clearProjectDiskSnapshot() + } +} + +func (e *Editor) syncOpenDocumentsFromRestoredFile(relPath, absPath string, data []byte, existed bool) { + if e == nil { + return + } + if !existed { + if relPath == project.FileName { + e.clearProjectDiskSnapshot() + return + } + e.syncActiveTab() + for i, t := range e.tabs { + if t.scenePath != relPath && canonicalTabFilePath(t.filePath) != canonicalTabFilePath(absPath) { + continue + } + t.sceneDisk = diskSnapshot{} + if i == e.activeTab { + e.clearSceneDiskSnapshot() + } + } + return + } + if relPath == project.FileName && e.Project != nil { + if pf, err := project.Parse(data); err == nil { + if enc, encErr := project.Encode(pf); encErr == nil { + e.Project = pf + e.projectSaved = enc + e.syncAudioMixer() + e.recordProjectDiskSnapshot(absPath, data) + } + } + return + } + e.syncActiveTab() + for i, t := range e.tabs { + if t.scenePath != relPath && canonicalTabFilePath(t.filePath) != canonicalTabFilePath(absPath) { + continue + } + doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{ + File: absPath, + Components: e.components, + PhysicsLayers: e.effectivePhysicsLayers(), + }) + if err != nil { + continue + } + enc, err := sceneformat.Encode(doc) + if err != nil { + continue + } + t.doc = doc + t.sceneSaved = enc + t.sceneDisk = makeDiskSnapshot(absPath, data) + if i == e.activeTab { + e.Doc = doc + e.sceneSaved = enc + e.recordSceneDiskSnapshot(absPath, data) + e.pruneSelection() + e.keepValidActiveLayer() + e.s3d.stale = true + e.Rebuild() + e.syncActiveTab() + } else if built, berr := e.buildSceneDoc(doc); berr == nil { + built.DrawAllTiles = true + t.built = built + t.buildErr = nil + } + } +} + +func (e *Editor) keepValidActiveLayer() { + if e == nil || e.Doc == nil { + return + } + if e.ActiveLayer != "" { + found := false + for _, l := range e.Doc.Layers { + if l.Name == e.ActiveLayer { + found = true + break + } + } + if !found { + if len(e.Doc.Layers) > 0 { + e.ActiveLayer = e.Doc.Layers[0].Name + } else { + e.ActiveLayer = "" + } + } + } +} + +func (e *Editor) effectivePhysicsLayers() *sceneformat.PhysicsLayerTable { + if e != nil && e.Project != nil { + return e.Project.PhysicsLayerTable() + } + return nil +} + +func (e *Editor) buildSceneDoc(doc *sceneformat.SceneDoc) (*sceneformat.BuiltScene, error) { + return sceneformat.Build(doc, e.liveResolver()) +} + +func (e *Editor) captureCurrentRestoreState(projectDir, relPath string) (fileRestoreState, error) { + if err := e.checkCheckpointYouOnly(relPath); err != nil { + return fileRestoreState{}, err + } + abs, err := resolvePathNoSymlinks(projectDir, relPath) + if err != nil { + return fileRestoreState{}, err + } + st := fileRestoreState{ + projectDir: projectDir, + relPath: relPath, + absPath: abs, + mode: 0o644, + } + raw, info, rerr := readFileBoundedNoSymlink(abs, maxCheckpointFileBytes) + switch { + case rerr == nil: + st.existed = true + st.bytes = raw + st.mode = info.Mode().Perm() + case errors.Is(rerr, fs.ErrNotExist): + st.existed = false + default: + return fileRestoreState{}, fmt.Errorf("editor: read %s before restore: %w", relPath, rerr) + } + + if relPath == project.FileName && e.Project != nil { + st.hadProj = true + st.projDoc = e.Project.Clone() + st.projSaved = append([]byte(nil), e.projectSaved...) + } + e.syncActiveTab() + for _, t := range e.tabs { + if t.doc == nil { + continue + } + if t.scenePath == relPath || canonicalTabFilePath(t.filePath) == canonicalTabFilePath(abs) { + st.hadScene = true + st.sceneDoc = t.doc.Clone() + st.sceneSaved = append([]byte(nil), t.sceneSaved...) + break + } + } + return st, nil +} + +// RestoreCheckpoint restores every file recorded in checkpoint id back to its pre-turn bytes +// (removing files that did not exist before the turn) as one undoable step in History. +// Calling Undo reverts every file and open editor tab back to the state right before Restore. +// Refuses You-only files, symlinks, and restores while playing, on full-window screens, or during an active turn. +func (e *Editor) RestoreCheckpoint(id string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.StartScreenOpen() || e.MergeConflictOpen() { + return errors.New("editor: checkpoint restore is unavailable while a full-window screen is open") + } + if e.ActiveTurnID() != "" { + return fmt.Errorf("editor: cannot restore checkpoint while turn %q is active", e.ActiveTurnID()) + } + projectDir := e.projectDirPath() + if projectDir == "" { + return ErrNoProject + } + m, err := e.CheckpointManifest(id) + if err != nil { + return err + } + e.cancelTransientInteraction() + e.ExitHistoryPreview() + + cpDir := filepath.Join(e.CheckpointsDir(), id) + before := make([]fileRestoreState, 0, len(m.Files)) + after := make([]fileRestoreState, 0, len(m.Files)) + touched := make([]string, 0, len(m.Files)) + + for _, f := range m.Files { + if err := e.checkCheckpointYouOnly(f.Path); err != nil { + return err + } + cur, err := e.captureCurrentRestoreState(projectDir, f.Path) + if err != nil { + return err + } + target := fileRestoreState{ + projectDir: projectDir, + relPath: f.Path, + absPath: cur.absPath, + existed: f.Existed, + mode: 0o644, + } + if f.Existed { + raw, err := readVerifiedCheckpointFile(cpDir, f) + if err != nil { + return err + } + target.bytes = raw + if f.Mode != "" { + if parsedMode, merr := parseOctalFileMode(f.Mode); merr == nil { + target.mode = parsedMode + } + } + if cur.hadScene { + if doc, perr := sceneformat.ParseWith(raw, sceneformat.ParseOptions{ + File: cur.absPath, + Components: e.components, + PhysicsLayers: e.effectivePhysicsLayers(), + }); perr == nil { + if enc, eerr := sceneformat.Encode(doc); eerr == nil { + target.hadScene = true + target.sceneDoc = doc + target.sceneSaved = enc + } + } + } + if cur.hadProj { + if pf, perr := project.Parse(raw); perr == nil { + if enc, eerr := project.Encode(pf); eerr == nil { + target.hadProj = true + target.projDoc = pf + target.projSaved = enc + } + } + } + } + before = append(before, cur) + after = append(after, target) + touched = append(touched, f.Path) + } + + ts, _ := time.Parse(time.RFC3339, m.CreatedAt) + ago := e.FormatHistoryRelativeTime(ts) + summary := "Restored to " + ago + detail := m.Title + if detail == "" { + detail = ago + } + + cmd := &checkpointRestoreCmd{ + ed: e, + label: "Restore checkpoint: " + m.Title, + summary: summary, + detail: detail, + files: touched, + cpID: id, + before: before, + after: after, + } + if err := e.History.execute(cmd); err != nil { + return err + } + + wantProject := e.ProjectPath + wantTabID := e.activeTabID() + wantHistory := e.History + wantCursor := e.History.Index() + wantCmd := e.History.topUndoCommand() + + toastMsg := fmt.Sprintf("Restored to %s · %s", ago, detail) + e.Status = toastMsg + e.ShowToast(Toast{ + ID: "history-restore", + Kind: ToastSuccess, + Message: toastMsg, + ActionLabel: e.T("toolbar.undo"), + ActionShortcut: FormatShortcut(e.EffectiveShortcut(CmdUndo), e.defaultShortcutOS()), + OnAction: func() { + e.DismissToast() + if e.Playing() || e.StartScreenOpen() || e.MergeConflictOpen() { + return + } + if e.ProjectPath != wantProject || e.activeTabID() != wantTabID || e.History != wantHistory { + return + } + if e.History == nil || e.History.Index() != wantCursor || e.History.topUndoCommand() != wantCmd { + return + } + e.Undo() + }, + }) + e.notify() + return nil +} + +// PreviewCheckpoint enters read-only History preview mode for persistent checkpoint id without +// mutating Doc or History. When the checkpoint contains the open scene, ActiveScene() renders its +// pre-turn scene snapshot read-only in the viewport. +func (e *Editor) PreviewCheckpoint(id string) error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.playing { + return ErrPlaying + } + if e.StartScreenOpen() || e.MergeConflictOpen() { + return errors.New("editor: history preview is unavailable while a full-window screen is open") + } + m, err := e.CheckpointManifest(id) + if err != nil { + return err + } + + var previewDoc *sceneformat.SceneDoc + var previewScene *sceneformat.BuiltScene + if e.ScenePath != "" { + if raw, existed, rerr := e.CheckpointFileBytes(id, e.ScenePath); rerr == nil && existed { + if doc, perr := sceneformat.ParseWith(raw, sceneformat.ParseOptions{ + File: e.FilePath, + Components: e.components, + PhysicsLayers: e.effectivePhysicsLayers(), + }); perr == nil { + if built, berr := e.buildSceneDoc(doc); berr == nil { + built.DrawAllTiles = true + previewDoc = doc + previewScene = built + } + } + } + } + + entry := checkpointManifestToHistoryEntry(*m) + e.cancelTransientInteraction() + e.cancelAutoSaveTimer() + e.historyPanel.preview = &historyPreviewState{ + checkpointID: id, + entry: entry, + doc: previewDoc, + scene: previewScene, + } + e.s3d.stale = true + e.Status = fmt.Sprintf("Previewing %s · editing is off", e.FormatHistoryRelativeTime(entry.Timestamp)) + e.notify() + return nil +} + +func checkpointManifestToHistoryEntry(m CheckpointManifest) HistoryEntry { + ts, _ := time.Parse(time.RFC3339, m.CreatedAt) + files := make([]string, len(m.Files)) + for i, f := range m.Files { + files[i] = f.Path + } + return HistoryEntry{ + Kind: HistoryEntryCheckpoint, + Author: m.Who, + Summary: m.Title, + Detail: m.Detail, + Files: files, + Timestamp: ts, + CheckpointID: m.ID, + CheckpointKind: m.Kind, + Persistent: true, + } +} + +// UnifiedHistoryEntries returns the merged History panel timeline combining the active scene's +// session entries, persisted project checkpoints from .nsgo/checkpoints/, and Git milestones, +// filtered by filter and sorted newest first. Session sub-commands captured inside a persisted +// checkpoint are folded into that checkpoint row so turns are never duplicated. +func (e *Editor) UnifiedHistoryEntries(filter HistoryFilter) []HistoryEntry { + if e == nil { + return nil + } + if filter == "" { + filter = e.HistoryFilter() + } + + cps := e.Checkpoints() + cpSet := make(map[string]bool, len(cps)) + var out []HistoryEntry + for _, cp := range cps { + cpSet[cp.ID] = true + entry := checkpointManifestToHistoryEntry(cp.CheckpointManifest) + if !historyEntryMatchesFilter(entry, filter) { + continue + } + out = append(out, entry) + } + + for _, entry := range e.FilteredHistoryEntries(filter) { + if entry.CheckpointID != "" && cpSet[entry.CheckpointID] { + continue + } + out = append(out, entry) + } + + if e.History != nil && filter == HistoryFilterAll { + for _, m := range e.History.Milestones() { + detail := m.Branch + if len(m.Files) > 0 { + detail = fmt.Sprintf("%d files · %s", len(m.Files), m.Branch) + } + out = append(out, HistoryEntry{ + Kind: HistoryEntryEdit, + Author: HistoryAuthorGit, + Summary: m.Summary, + Detail: detail, + Files: slices.Clone(m.Files), + Timestamp: m.Timestamp, + }) + } + } + + slices.SortStableFunc(out, func(a, b HistoryEntry) int { + if !a.Timestamp.Equal(b.Timestamp) { + if a.Timestamp.After(b.Timestamp) { + return -1 + } + return 1 + } + if a.Persistent != b.Persistent { + if a.Persistent { + return -1 + } + return 1 + } + if a.CheckpointID != b.CheckpointID { + return strings.Compare(b.CheckpointID, a.CheckpointID) + } + if a.ID != b.ID { + if a.ID > b.ID { + return -1 + } + return 1 + } + return 0 + }) + return out +} + +func historyEntryMatchesFilter(entry HistoryEntry, filter HistoryFilter) bool { + switch filter { + case HistoryFilterYou: + return entry.Kind != HistoryEntrySaved && entry.Author == HistoryAuthorYou + case HistoryFilterAgent: + return entry.Kind != HistoryEntrySaved && entry.Author == HistoryAuthorAgent + default: + return true + } +} + +// beforeHistoryExecute runs right before a History command mutates editor state. +// When an agent turn is active, it snapshots the open scene (or game.yaml for project edits) +// before the first write to that file. +func (e *Editor) beforeHistoryExecute(cmd Command) { + if e == nil || e.checkpoints.active == nil { + return + } + if _, isRestore := cmd.(*checkpointRestoreCmd); isRestore { + return + } + if _, isProj := cmd.(*projectCmd); isProj { + if e.Project != nil && e.ProjectPath != "" { + _ = e.RecordCheckpointFile(project.FileName) + } + return + } + if e.ScenePath != "" { + _ = e.RecordCheckpointFile(e.ScenePath) + } +} + +func (e *Editor) resetCheckpointsForProject() { + if e == nil { + return + } + e.abortActiveTurn() + e.checkpoints.list = nil + if e.Project != nil && e.ProjectPath != "" { + _, _ = e.LoadCheckpoints() + } +} diff --git a/packages/game/editor/checkpoints_test.go b/packages/game/editor/checkpoints_test.go new file mode 100644 index 000000000..85a3a8f62 --- /dev/null +++ b/packages/game/editor/checkpoints_test.go @@ -0,0 +1,689 @@ +package editor_test + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func setupCheckpointProject(t *testing.T) (dir, sceneFile, prefabFile string, sceneOrig, prefabOrig []byte) { + t.Helper() + dir = t.TempDir() + for _, sub := range []string{"scenes", "prefabs", "data", "scripts", "art"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + gameYAML := "version: 1\nname: Dungeon Run\nid: dev.nsgo.dungeon\nappVersion: 0.1.0\nwindow:\n width: 640\n height: 360\nautoload:\n mainScene: level_01\n scenes:\n - name: level_01\n path: scenes/level_01.scene.yaml\n" + if err := os.WriteFile(filepath.Join(dir, project.FileName), []byte(gameYAML), 0o644); err != nil { + t.Fatal(err) + } + sceneOrig = []byte("# Hand-written comment preserved on restore.\nversion: 2\nname: Level 01\nvirtualWidth: 640\nvirtualHeight: 360\nbackgroundColor: \"#141824\"\nlayers:\n - name: actors\n space: world\n order: 0\n objects:\n - id: knight\n name: Knight\n x: 96\n y: 180\n") + sceneFile = filepath.Join(dir, "scenes", "level_01.scene.yaml") + if err := os.WriteFile(sceneFile, sceneOrig, 0o644); err != nil { + t.Fatal(err) + } + prefabOrig = []byte("# Coin prefab v1\nversion: 1\nname: Coin\nspin: false\nbob: 0\n") + prefabFile = filepath.Join(dir, "prefabs", "coin.prefab.yaml") + if err := os.WriteFile(prefabFile, prefabOrig, 0o644); err != nil { + t.Fatal(err) + } + return dir, sceneFile, prefabFile, sceneOrig, prefabOrig +} + +// #1018 acceptance 1: an agent turn edits a scene and a prefab (plus newly created file, game.yaml, +// Go code, and binary media), restores the checkpoint from History, gets every file back byte for byte, +// and one Undo puts the turn back byte for byte. +func TestCheckpointAgentTurnRestoresSceneAndPrefabByteForByteAndUndoes(t *testing.T) { + dir, sceneFile, prefabFile, sceneOrig, prefabOrig := setupCheckpointProject(t) + + goFile := filepath.Join(dir, "scripts", "patrol.go") + goOrig := []byte("package scripts\n\nconst PatrolSpeed = 24\n") + if err := os.WriteFile(goFile, goOrig, 0o644); err != nil { + t.Fatal(err) + } + binFile := filepath.Join(dir, "art", "coin.png") + binOrig := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0xFF} + if err := os.WriteFile(binFile, binOrig, 0o644); err != nil { + t.Fatal(err) + } + gameOrig, err := os.ReadFile(filepath.Join(dir, project.FileName)) + if err != nil { + t.Fatal(err) + } + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + clock := time.Date(2026, 11, 26, 14, 41, 0, 0, time.UTC) + ed.Now = func() time.Time { return clock } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + prefabEdited := []byte("# Coin prefab v2\nversion: 1\nname: Coin\nspin: true\nbob: 4\n") + sparkleNew := []byte("version: 1\nname: sparkle\nrate: 12\n") + goEdited := []byte("package scripts\n\nconst PatrolSpeed = 18\n") + binEdited := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xDE, 0xAD, 0xBE, 0xEF} + + summary, err := ed.RunCheckpointTurn("Coin spin, bob and sparkle", func() error { + // 1. Edit the open scene via editor commands and save to disk. + if err := ed.MoveObject("knight", 220, 140); err != nil { + return err + } + if err := ed.SaveFile(sceneFile); err != nil { + return err + } + // 2. Edit a prefab file twice during the same turn — checkpoint must keep the ORIGINAL bytes! + if err := ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("intermediate\n")); err != nil { + return err + } + if err := ed.WriteAgentFile("prefabs/coin.prefab.yaml", prefabEdited); err != nil { + return err + } + // 3. Create a brand new file (existed: false -> Restore must delete it; Undo must recreate it). + if err := ed.WriteAgentFile("fx/sparkle.particles.yaml", sparkleNew); err != nil { + return err + } + // 4. Edit game.yaml, Go code, and binary media. + if err := ed.EditProject("Rename", func(f *project.File) { f.Name = "Dungeon Run v2" }); err != nil { + return err + } + if err := ed.SaveProject(); err != nil { + return err + } + if err := ed.WriteAgentFile("scripts/patrol.go", goEdited); err != nil { + return err + } + return ed.WriteAgentFile("art/coin.png", binEdited) + }) + if err != nil { + t.Fatalf("RunCheckpointTurn: %v", err) + } + if summary == nil || summary.ID == "" { + t.Fatal("expected non-nil checkpoint summary") + } + + // Verify .gitignore exists under .nsgo/checkpoints/. + gi, err := os.ReadFile(filepath.Join(dir, ".nsgo", "checkpoints", ".gitignore")) + if err != nil || string(gi) != "*\n" { + t.Fatalf(".nsgo/checkpoints/.gitignore = %q, err = %v", string(gi), err) + } + + // Capture post-turn scene & game.yaml bytes for Undo comparison. + sceneAfterTurn, err := os.ReadFile(sceneFile) + if err != nil { + t.Fatal(err) + } + gameAfterTurn, err := os.ReadFile(filepath.Join(dir, project.FileName)) + if err != nil { + t.Fatal(err) + } + if bytes.Equal(sceneAfterTurn, sceneOrig) { + t.Fatal("expected scene to change during agent turn") + } + + // Preview the checkpoint before restoring: ActiveScene shows knight at (96, 180) while ed.Doc stays at (220, 140). + clock = clock.Add(5 * time.Minute) + if err := ed.PreviewCheckpoint(summary.ID); err != nil { + t.Fatalf("PreviewCheckpoint: %v", err) + } + if !ed.HistoryPreviewActive() { + t.Fatal("expected HistoryPreviewActive") + } + if bo := ed.ActiveScene().Object("knight"); bo == nil || bo.Doc.X != 96 || bo.Doc.Y != 180 { + t.Fatalf("preview knight = %+v, want (96, 180)", bo) + } + if docObj, _, _ := ed.FindObject("knight"); docObj == nil || docObj.X != 220 { + t.Fatalf("live Doc knight changed during preview: %+v", docObj) + } + + // Restore the checkpoint from History. + if err := ed.RestorePreviewedHistory(); err != nil { + t.Fatalf("RestorePreviewedHistory: %v", err) + } + if ed.HistoryPreviewActive() { + t.Fatal("preview should end after Restore") + } + + // Verify every file is back byte-for-byte! + assertFileBytes := func(label, p string, want []byte) { + t.Helper() + got, err := os.ReadFile(p) + if err != nil { + t.Fatalf("%s: read %s: %v", label, p, err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s: %s bytes mismatch:\ngot: %q\nwant: %q", label, p, got, want) + } + } + assertFileBytes("after restore", sceneFile, sceneOrig) + assertFileBytes("after restore", prefabFile, prefabOrig) + assertFileBytes("after restore", goFile, goOrig) + assertFileBytes("after restore", binFile, binOrig) + assertFileBytes("after restore", filepath.Join(dir, project.FileName), gameOrig) + if _, err := os.Stat(filepath.Join(dir, "fx", "sparkle.particles.yaml")); !os.IsNotExist(err) { + t.Fatalf("after restore: newly created file should be removed, stat err = %v", err) + } + if docObj, _, _ := ed.FindObject("knight"); docObj == nil || docObj.X != 96 || docObj.Y != 180 { + t.Fatalf("after restore: open scene knight = %+v, want (96, 180)", docObj) + } + if ed.Project.Name != "Dungeon Run" { + t.Fatalf("after restore: ed.Project.Name = %q, want Dungeon Run", ed.Project.Name) + } + + // One Undo puts the entire turn back byte-for-byte! + if !ed.Undo() { + t.Fatal("Undo returned false after RestoreCheckpoint") + } + assertFileBytes("after undo", sceneFile, sceneAfterTurn) + assertFileBytes("after undo", prefabFile, prefabEdited) + assertFileBytes("after undo", goFile, goEdited) + assertFileBytes("after undo", binFile, binEdited) + assertFileBytes("after undo", filepath.Join(dir, project.FileName), gameAfterTurn) + assertFileBytes("after undo", filepath.Join(dir, "fx", "sparkle.particles.yaml"), sparkleNew) + if docObj, _, _ := ed.FindObject("knight"); docObj == nil || docObj.X != 220 || docObj.Y != 140 { + t.Fatalf("after undo: open scene knight = %+v, want (220, 140)", docObj) + } + if ed.Project.Name != "Dungeon Run v2" { + t.Fatalf("after undo: ed.Project.Name = %q, want Dungeon Run v2", ed.Project.Name) + } + + // Redo re-applies the restore cleanly! + if !ed.Redo() { + t.Fatal("Redo returned false") + } + assertFileBytes("after redo", sceneFile, sceneOrig) + assertFileBytes("after redo", prefabFile, prefabOrig) +} + +// #1018 acceptance 2: reopening the project in a fresh Editor lists the exact same checkpoints +// and lets the user restore them across sessions. +func TestCheckpointsPersistAcrossProjectReopen(t *testing.T) { + dir, sceneFile, prefabFile, sceneOrig, prefabOrig := setupCheckpointProject(t) + + ed1, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed1.WaitForProblems) + baseTime := time.Date(2026, 11, 26, 14, 0, 0, 0, time.UTC) + ed1.Now = func() time.Time { return baseTime } + if err := ed1.OpenProject(dir); err != nil { + t.Fatal(err) + } + + cp1, err := ed1.RunCheckpointTurn("First turn", func() error { + return ed1.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: CoinV2\n")) + }) + if err != nil { + t.Fatal(err) + } + baseTime = baseTime.Add(10 * time.Minute) + cp2, err := ed1.RunCheckpointTurn("Second turn", func() error { + if err := ed1.MoveObject("knight", 300, 180); err != nil { + return err + } + return ed1.SaveFile(sceneFile) + }) + if err != nil { + t.Fatal(err) + } + + // Simulate editor restart: brand new Editor instance opening the same project directory. + ed2, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed2.WaitForProblems) + ed2.Now = func() time.Time { return baseTime.Add(5 * time.Minute) } + if err := ed2.OpenProject(dir); err != nil { + t.Fatal(err) + } + + got := ed2.Checkpoints() + if len(got) != 2 { + t.Fatalf("Checkpoints after reopen = %d, want 2", len(got)) + } + if got[0].ID != cp2.ID || got[1].ID != cp1.ID { + t.Fatalf("Checkpoints order = [%s, %s], want [%s, %s]", got[0].ID, got[1].ID, cp2.ID, cp1.ID) + } + + // Restore cp1 across sessions and verify prefab bytes come back verbatim. + if err := ed2.RestoreCheckpoint(cp1.ID); err != nil { + t.Fatalf("RestoreCheckpoint after reopen: %v", err) + } + gotPrefab, err := os.ReadFile(prefabFile) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotPrefab, prefabOrig) { + t.Fatalf("prefab after cross-session restore = %q, want %q", gotPrefab, prefabOrig) + } + // Restore cp2 and verify scene bytes come back verbatim. + if err := ed2.RestoreCheckpoint(cp2.ID); err != nil { + t.Fatalf("RestoreCheckpoint cp2 after reopen: %v", err) + } + gotScene, err := os.ReadFile(sceneFile) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotScene, sceneOrig) { + t.Fatalf("scene after cross-session restore = %q, want %q", gotScene, sceneOrig) + } +} + +// Size cap drops oldest completed checkpoints while preserving newest ones. +func TestCheckpointSizeCapDropsOldest(t *testing.T) { + dir, _, _, _, _ := setupCheckpointProject(t) + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + clock := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC) + ed.Now = func() time.Time { return clock } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + // Write a 2 KiB file so each checkpoint is > 2 KiB. + payload := bytes.Repeat([]byte("A"), 2048) + if err := os.WriteFile(filepath.Join(dir, "data", "blob.txt"), payload, 0o644); err != nil { + t.Fatal(err) + } + // Cap at 5 KiB -> fits 2 checkpoints (~2.3 KiB each), drops oldest when 3rd arrives. + ed.CheckpointMaxBytes = 5200 + + var ids []string + for i := 0; i < 4; i++ { + clock = clock.Add(time.Minute) + next := bytes.Repeat([]byte{byte('B' + i)}, 2048) + cp, err := ed.RunCheckpointTurn("Turn "+string(rune('1'+i)), func() error { + return ed.WriteAgentFile("data/blob.txt", next) + }) + if err != nil { + t.Fatalf("turn %d: %v", i, err) + } + ids = append(ids, cp.ID) + } + + list := ed.Checkpoints() + if len(list) >= 4 { + t.Fatalf("expected oldest checkpoints to be pruned, got %d", len(list)) + } + if list[0].ID != ids[len(ids)-1] { + t.Fatalf("newest checkpoint = %s, want %s", list[0].ID, ids[len(ids)-1]) + } + if _, err := os.Stat(filepath.Join(ed.CheckpointsDir(), ids[0])); !os.IsNotExist(err) { + t.Fatalf("oldest checkpoint %s should have been dropped, stat err = %v", ids[0], err) + } +} + +// Tasks and automations always take a persistent checkpoint before they start. +func TestTasksAndAutomationsTakeCheckpointBeforeStart(t *testing.T) { + dir, _, _, _, prefabOrig := setupCheckpointProject(t) + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + clock := time.Date(2026, 11, 26, 2, 0, 0, 0, time.UTC) + ed.Now = func() time.Time { return clock } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + // Verify the checkpoint exists on disk BEFORE the task body writes anything. + taskSummary, err := ed.RunTaskWithCheckpoint("Nightly 20-run playtest", []string{"prefabs/coin.prefab.yaml"}, func() error { + id := ed.ActiveTurnID() + if id == "" { + t.Fatal("expected active checkpoint ID inside task") + } + mPath := filepath.Join(ed.CheckpointsDir(), id, editor.CheckpointManifestFile) + if _, statErr := os.Stat(mPath); statErr != nil { + t.Fatalf("expected checkpoint manifest on disk before task starts: %v", statErr) + } + return ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: TaskModified\n")) + }) + if err != nil { + t.Fatalf("RunTaskWithCheckpoint: %v", err) + } + if taskSummary.Kind != editor.CheckpointKindTask || !strings.Contains(taskSummary.Title, "checkpoint before start") { + t.Fatalf("task checkpoint = %+v", taskSummary) + } + + clock = clock.Add(time.Minute) + autoSummary, err := ed.TakeCheckpointBeforeAutomation("Auto-tile pass", "scenes/level_01.scene.yaml") + if err != nil { + t.Fatalf("TakeCheckpointBeforeAutomation: %v", err) + } + if autoSummary.Kind != editor.CheckpointKindAutomation { + t.Fatalf("automation checkpoint kind = %q, want automation", autoSummary.Kind) + } + + // Restoring the task checkpoint puts prefab back byte-for-byte. + if err := ed.RestoreCheckpoint(taskSummary.ID); err != nil { + t.Fatalf("RestoreCheckpoint(task): %v", err) + } + got, err := os.ReadFile(filepath.Join(dir, "prefabs", "coin.prefab.yaml")) + if err != nil || !bytes.Equal(got, prefabOrig) { + t.Fatalf("prefab after restoring task checkpoint = %q, err = %v", got, err) + } +} + +// Strict validation tests for CheckpointManifest YAML format. +func TestCheckpointManifestValidationRejectsInvalid(t *testing.T) { + valid := []byte("version: 1\nid: 20261126T144100Z-0001\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: Slimes and coins\nfiles:\n - path: scenes/level_01.scene.yaml\n existed: true\n size: 12\n sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n") + if _, err := editor.ParseCheckpointManifest(valid); err != nil { + t.Fatalf("valid manifest failed: %v", err) + } + cases := []struct { + name string + yaml string + }{ + {"unknown field", "version: 1\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nextra: 1\n"}, + {"bad version", "version: 2\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\n"}, + {"parent path", "version: 1\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nfiles:\n - path: ../escape.yaml\n existed: false\n"}, + {"nsgo metadata path", "version: 1\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nfiles:\n - path: .nsgo/checkpoints/x\n existed: false\n"}, + {"bad sha256", "version: 1\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nfiles:\n - path: a.yaml\n existed: true\n size: 1\n sha256: nothex\n"}, + {"nonexistent with size", "version: 1\nid: a\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nfiles:\n - path: a.yaml\n existed: false\n size: 1\n"}, + } + for _, tc := range cases { + if _, err := editor.ParseCheckpointManifest([]byte(tc.yaml)); err == nil { + t.Errorf("%s: expected ParseCheckpointManifest to fail", tc.name) + } + } +} + +// UI test: History panel opens with ⌘Y, filters All/You/Agent, previews a checkpoint read-only, +// exits preview with Esc, restores via the Restore button, and undoes via the Undo button. +func TestHistoryPanelUIWithCheckpointsAndFilters(t *testing.T) { + dir, sceneFile, prefabFile, sceneOrig, prefabOrig := setupCheckpointProject(t) + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + clock := time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + ed.Now = func() time.Time { return clock } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + // Manual edit by You. + if err := ed.MoveObject("knight", 120, 180); err != nil { + t.Fatal(err) + } + if err := ed.SaveFile(sceneFile); err != nil { + t.Fatal(err) + } + sceneAfterYou, _ := os.ReadFile(sceneFile) + + // Agent turn editing both scene and prefab. + clock = clock.Add(11 * time.Minute) + cp, err := ed.RunCheckpointTurn("Coin spin, bob and sparkle", func() error { + if err := ed.MoveObject("knight", 260, 180); err != nil { + return err + } + if err := ed.SaveFile(sceneFile); err != nil { + return err + } + return ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: CoinSpin\n")) + }) + if err != nil { + t.Fatal(err) + } + clock = clock.Add(10 * time.Minute) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), desktopEnv()) + app.Settle() + + // Open History via toolbar button. + app.Press("id:toolbar-history") + app.Settle() + if !app.Exists("id:history-panel") { + t.Fatal("expected history-panel after clicking toolbar-history") + } + + cpRowID := "id:history-row-cp:" + cp.ID + if !app.Exists(cpRowID) { + t.Fatalf("expected checkpoint row %s in History panel", cpRowID) + } + + // Filter to You -> hides Agent checkpoint. + app.Press("id:history-filter-you") + app.Settle() + if app.Exists(cpRowID) { + t.Fatal("Agent checkpoint should be hidden under You filter") + } + + // Filter to Agent -> shows Agent checkpoint. + app.Press("id:history-filter-agent") + app.Settle() + if !app.Exists(cpRowID) { + t.Fatal("Agent checkpoint should be visible under Agent filter") + } + + // Click checkpoint row -> enters read-only preview banner. + app.Press(cpRowID) + app.Settle() + if !app.Exists("id:history-preview-banner") || !ed.HistoryPreviewActive() { + t.Fatal("expected history-preview-banner after clicking checkpoint row") + } + if bo := ed.ActiveScene().Object("knight"); bo == nil || bo.Doc.X != 120 { + t.Fatalf("preview knight X = %v, want 120", bo) + } + + // Press Back/Esc -> exits preview. + app.Press("id:history-preview-back") + app.Settle() + if ed.HistoryPreviewActive() || app.Exists("id:history-preview-banner") { + t.Fatal("expected preview to end after clicking Back") + } + + // Click checkpoint again and click Restore -> restores both files byte-for-byte & shows restore toast with Undo. + app.Press(cpRowID) + app.Settle() + app.Press("id:history-preview-restore") + app.Settle() + if !app.Exists("id:editor-toast") || !app.Exists("id:editor-toast-action") { + t.Fatal("expected restore toast with Undo action after Restore") + } + gotScene, _ := os.ReadFile(sceneFile) + gotPrefab, _ := os.ReadFile(prefabFile) + if !bytes.Equal(gotScene, sceneAfterYou) || !bytes.Equal(gotPrefab, prefabOrig) { + t.Fatalf("after UI Restore: scene/prefab mismatch") + } + _ = sceneOrig + + // Click Undo button in restore toast -> puts the turn back byte-for-byte. + app.Press("id:editor-toast-action") + app.Settle() + if obj, _, _ := ed.FindObject("knight"); obj == nil || obj.X != 260 { + t.Fatalf("after Undo toast action: knight X = %v, want 260", obj) + } + gotPrefabAfterUndo, _ := os.ReadFile(prefabFile) + if !strings.Contains(string(gotPrefabAfterUndo), "CoinSpin") { + t.Fatalf("after Undo toast action: prefab = %q, want CoinSpin", string(gotPrefabAfterUndo)) + } +} + +// Security: You-only files (permissions.yaml, tools.yaml, models.yaml, usage.yaml, .game/editor.yaml) +// are rejected by manifest parsing, checkpoint recording, agent writes/deletes, and restore. +func TestCheckpointsEnforceYouOnlyBoundary(t *testing.T) { + dir, _, _, _, _ := setupCheckpointProject(t) + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + youOnlyPaths := []string{ + "permissions.yaml", + "sub/permissions.yaml", + "tools.yaml", + "mcp.yaml", + "models.yaml", + "usage.yaml", + "privacy.yaml", + ".nsgo/permissions.yaml", + ".game/editor.yaml", + } + for _, p := range youOnlyPaths { + if err := ed.WriteAgentFile(p, []byte("version: 1\nprofile: autonomous\n")); err == nil { + t.Errorf("WriteAgentFile(%q) succeeded, want You-only error", p) + } + if err := ed.DeleteAgentFile(p); err == nil { + t.Errorf("DeleteAgentFile(%q) succeeded, want You-only error", p) + } + manifest := "version: 1\nid: 20261126T144100Z-0001\ncreatedAt: \"2026-11-26T14:41:00Z\"\nwho: agent\nkind: turn\ntitle: x\nfiles:\n - path: " + p + "\n existed: false\n" + if _, err := editor.ParseCheckpointManifest([]byte(manifest)); err == nil { + t.Errorf("ParseCheckpointManifest(%q) succeeded, want You-only error", p) + } + } + + // Recording inside an active turn must also refuse You-only targets. + if _, err := ed.BeginCheckpointTurn("Try You-only"); err != nil { + t.Fatal(err) + } + defer ed.AbortCheckpointTurn() + if err := ed.RecordCheckpointFile("permissions.yaml"); err == nil { + t.Fatal("RecordCheckpointFile(permissions.yaml) succeeded, want error") + } +} + +// Security: symlinks (external, dangling, and internal pointing to You-only/.git) and tampered +// checkpoint payloads (SHA-256 / size mismatch) are refused across record, write, delete, and restore. +func TestCheckpointsRefuseSymlinksAndTamperedPayloads(t *testing.T) { + dir, _, _, _, _ := setupCheckpointProject(t) + outsideDir := t.TempDir() + outsideFile := filepath.Join(outsideDir, "secret.txt") + if err := os.WriteFile(outsideFile, []byte("secret"), 0o644); err != nil { + t.Fatal(err) + } + permFile := filepath.Join(dir, "permissions.yaml") + if err := os.WriteFile(permFile, []byte("version: 1\nprofile: cautious\n"), 0o644); err != nil { + t.Fatal(err) + } + // Create external symlink, dangling symlink, and internal symlink pointing to permissions.yaml. + extLink := filepath.Join(dir, "data", "ext_link.yaml") + if err := os.Symlink(outsideFile, extLink); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + danglingLink := filepath.Join(dir, "data", "dangling_link.yaml") + if err := os.Symlink(filepath.Join(outsideDir, "missing.txt"), danglingLink); err != nil { + t.Fatal(err) + } + internalLink := filepath.Join(dir, "data", "perm_alias.yaml") + if err := os.Symlink(permFile, internalLink); err != nil { + t.Fatal(err) + } + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + for _, rel := range []string{"data/ext_link.yaml", "data/dangling_link.yaml", "data/perm_alias.yaml"} { + if err := ed.WriteAgentFile(rel, []byte("pwned")); err == nil { + t.Errorf("WriteAgentFile(%q) allowed symlink write", rel) + } + if err := ed.DeleteAgentFile(rel); err == nil { + t.Errorf("DeleteAgentFile(%q) allowed symlink delete", rel) + } + } + if raw, _ := os.ReadFile(permFile); !strings.Contains(string(raw), "cautious") { + t.Fatalf("permissions.yaml was altered via internal symlink: %q", string(raw)) + } + + // Create a real checkpoint, tamper with its stored file bytes, and confirm Restore refuses without mutating disk. + cp, err := ed.RunCheckpointTurn("Tamper test", func() error { + return ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: CoinV2\n")) + }) + if err != nil { + t.Fatal(err) + } + savedBlob := filepath.Join(ed.CheckpointsDir(), cp.ID, "files", "prefabs", "coin.prefab.yaml") + if err := os.WriteFile(savedBlob, []byte("corrupted bytes"), 0o644); err != nil { + t.Fatal(err) + } + if err := ed.RestoreCheckpoint(cp.ID); err == nil { + t.Fatal("RestoreCheckpoint succeeded despite tampered checkpoint payload") + } + gotPrefab, _ := os.ReadFile(filepath.Join(dir, "prefabs", "coin.prefab.yaml")) + if string(gotPrefab) != "version: 1\nname: CoinV2\n" { + t.Fatalf("prefab mutated on failed restore: %q", string(gotPrefab)) + } +} + +// Panic & lifecycle safety: a panic inside RunCheckpointTurn never strands ActiveTurnID, and switching to Demo clears checkpoints cleanly. +func TestCheckpointsPanicAndLifecycleSafety(t *testing.T) { + dir, _, _, _, prefabOrig := setupCheckpointProject(t) + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + + // Panic after modifying a file -> ActiveTurnID cleared, partial checkpoint preserved and restorable. + func() { + defer func() { _ = recover() }() + _, _ = ed.RunCheckpointTurn("Panicking turn", func() error { + if err := ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: Broken\n")); err != nil { + return err + } + panic("boom") + }) + }() + if ed.ActiveTurnID() != "" { + t.Fatalf("ActiveTurnID stranded after panic: %q", ed.ActiveTurnID()) + } + cps := ed.Checkpoints() + if len(cps) != 1 || cps[0].Detail != "interrupted" { + t.Fatalf("expected 1 interrupted checkpoint after panic, got %+v", cps) + } + if err := ed.RestoreCheckpoint(cps[0].ID); err != nil { + t.Fatalf("RestoreCheckpoint after panic: %v", err) + } + if raw, _ := os.ReadFile(filepath.Join(dir, "prefabs", "coin.prefab.yaml")); !bytes.Equal(raw, prefabOrig) { + t.Fatalf("prefab not restored after panic checkpoint") + } + + // Switching to Demo aborts any active turn and clears loaded project checkpoints. + if _, err := ed.BeginCheckpointTurn("Dangling before demo"); err != nil { + t.Fatal(err) + } + ed.OpenDemo() + if ed.ActiveTurnID() != "" { + t.Fatalf("ActiveTurnID not cleared on OpenDemo: %q", ed.ActiveTurnID()) + } + if len(ed.Checkpoints()) != 0 { + t.Fatalf("Checkpoints not cleared on OpenDemo: %+v", ed.Checkpoints()) + } +} diff --git a/packages/game/editor/conformance_test.go b/packages/game/editor/conformance_test.go index e275d082d..d016ca64e 100644 --- a/packages/game/editor/conformance_test.go +++ b/packages/game/editor/conformance_test.go @@ -15,3 +15,12 @@ func TestRecentProjectsFormatConformance(t *testing.T) { Doc: "editor#recent", }) } + +func TestCheckpointManifestFormatConformance(t *testing.T) { + formattest.Run(t, formattest.Format[*editor.CheckpointManifest]{ + Decode: editor.ParseCheckpointManifest, + Encode: editor.EncodeCheckpointManifest, + Files: []string{"testdata/checkpoint_manifest.yaml"}, + Doc: "editor#checkpoint", + }) +} diff --git a/packages/game/editor/editorcmd/checkpoints_screenshot_test.go b/packages/game/editor/editorcmd/checkpoints_screenshot_test.go new file mode 100644 index 000000000..5b6434e80 --- /dev/null +++ b/packages/game/editor/editorcmd/checkpoints_screenshot_test.go @@ -0,0 +1,137 @@ +package editorcmd_test + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestHistoryCheckpointsMacOSScreenshots renders the Project History & Checkpoints panel +// (previewing a checkpoint, restored state, and light theme) on the real native macOS host +// (`env -u GOROOT TMPDIR=/tmp go tool nsgo test -target macos -run TestHistoryCheckpointsMacOSScreenshots ./editor/editorcmd`) +// for visual verification beside docs/design/editor/Checkpoints.dc.html and Spec.dc.html. +func TestHistoryCheckpointsMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + for _, sub := range []string{"scenes", "prefabs", "scripts", "playtests"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + scenePath := filepath.Join(dir, "scenes", "level_01.scene.yaml") + if err := os.WriteFile(scenePath, []byte("version: 2\nname: Level 01\nvirtualWidth: 640\nvirtualHeight: 360\nbackgroundColor: \"#141824\"\nlayers:\n - name: actors\n space: world\n order: 0\n objects:\n - id: knight\n name: Knight\n x: 110\n y: 190\n - id: slime_01\n name: Slime 01\n x: 240\n y: 210\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "prefabs", "coin.prefab.yaml"), []byte("version: 1\nname: Coin\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "scripts", "patrol.go"), []byte("package scripts\n\nconst Speed = 24\n"), 0o644); err != nil { + t.Fatal(err) + } + pf := &project.File{ + Version: project.CurrentVersion, + Name: "Dungeon Run", + ID: "dev.nsgo.dungeonrun", + AppVersion: "0.4.2", + Window: project.Window{Width: 640, Height: 360}, + Autoload: &project.Autoload{ + Scenes: []project.Entry{{Name: "level_01", Path: "scenes/level_01.scene.yaml"}}, + MainScene: "level_01", + }, + } + data, err := project.Encode(pf) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, project.FileName), data, 0o644); err != nil { + t.Fatal(err) + } + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(ed.WaitForProblems) + ed.SetLanguage(editor.LanguageEnglish) + ed.SetAppearance(editor.AppearanceDark) + + // Populate realistic multi-day history entries matching Checkpoints.dc.html. + clock := time.Date(2026, 11, 25, 2, 0, 0, 0, time.UTC) + ed.Now = func() time.Time { return clock } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + if _, err := ed.TakeCheckpointBeforeTask("Nightly 20-run playtest", "playtests/2026-11-24.report.yaml"); err != nil { + t.Fatal(err) + } + + clock = time.Date(2026, 11, 26, 14, 5, 0, 0, time.UTC) + if _, err := ed.RunCheckpointTurn("Slower patrol, documented", func() error { + if err := ed.WriteAgentFile("scripts/patrol.go", []byte("package scripts\n\nconst Speed = 18\n")); err != nil { + return err + } + return ed.WriteAgentFile("AGENTS.md", []byte("# Rules\n")) + }); err != nil { + t.Fatal(err) + } + + clock = time.Date(2026, 11, 26, 14, 20, 0, 0, time.UTC) + if err := ed.MoveObject("knight", 148, 190); err != nil { + t.Fatal(err) + } + if err := ed.SaveFile(scenePath); err != nil { + t.Fatal(err) + } + + clock = time.Date(2026, 11, 26, 14, 31, 0, 0, time.UTC) + cpSlimes, err := ed.RunCheckpointTurn("Slimes and coins · 6 changes", func() error { + if err := ed.MoveObject("slime_01", 280, 210); err != nil { + return err + } + return ed.SaveFile(scenePath) + }) + if err != nil { + t.Fatal(err) + } + + clock = time.Date(2026, 11, 26, 14, 41, 0, 0, time.UTC) + if _, err := ed.RunCheckpointTurn("Coin spin, bob and sparkle", func() error { + if err := ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: Coin\nspin: true\n")); err != nil { + return err + } + return ed.WriteAgentFile("fx/sparkle.particles.yaml", []byte("version: 1\nname: sparkle\n")) + }); err != nil { + t.Fatal(err) + } + + clock = time.Date(2026, 11, 26, 14, 43, 0, 0, time.UTC) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + + app.Post(func() { + ed.SetHistoryPanelOpen(true) + _ = ed.PreviewCheckpoint(cpSlimes.ID) + }) + app.Settle() + app.Screenshot("history-checkpoints-dark-preview") + + app.Post(func() { + _ = ed.RestorePreviewedHistory() + }) + app.Settle() + app.Screenshot("history-checkpoints-dark-restored") + + app.Post(func() { + ed.SetAppearance(editor.AppearanceLight) + _ = ed.PreviewCheckpoint(cpSlimes.ID) + }) + app.Settle() + app.Screenshot("history-checkpoints-light-preview") +} diff --git a/packages/game/editor/editormcp/checkpoints.go b/packages/game/editor/editormcp/checkpoints.go new file mode 100644 index 000000000..974adfedb --- /dev/null +++ b/packages/game/editor/editormcp/checkpoints.go @@ -0,0 +1,264 @@ +package editormcp + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" +) + +const ( + // ToolCheckpointList lists persistent turn checkpoints and session history entries in the open project. + ToolCheckpointList = "checkpoint_list" + // ToolCheckpointRestore restores a persistent checkpoint back to its pre-turn files as one undoable step. + ToolCheckpointRestore = "checkpoint_restore" +) + +const checkpointListSchema = `{ + "type": "object", + "additionalProperties": false, + "properties": { + "filter": {"type": "string", "enum": ["all", "you", "agent"], "description": "Filter entries by actor; all when absent"}, + "limit": {"type": "integer", "minimum": 1, "maximum": 200, "description": "Maximum number of entries to return; 50 when absent"} + } +}` + +const checkpointRestoreSchema = `{ + "type": "object", + "additionalProperties": false, + "required": ["id"], + "properties": { + "id": {"type": "string", "minLength": 1, "description": "The checkpoint ID to restore (from checkpoint_list)"} + } +}` + +// CheckpointListItem is one entry returned by checkpoint_list. +type CheckpointListItem struct { + ID string `json:"id"` + CheckpointID string `json:"checkpointId,omitempty"` + Time string `json:"time,omitempty"` + Who string `json:"who"` + Kind string `json:"kind,omitempty"` + Title string `json:"title"` + Detail string `json:"detail,omitempty"` + Files []string `json:"files,omitempty"` + Persistent bool `json:"persistent"` + Restorable bool `json:"restorable"` +} + +// CheckpointListResult is the structured payload returned by checkpoint_list. +type CheckpointListResult struct { + Filter string `json:"filter"` + Total int `json:"total"` + Entries []CheckpointListItem `json:"entries"` +} + +// CheckpointRestoreResult is the structured payload returned by checkpoint_restore. +type CheckpointRestoreResult struct { + ID string `json:"id"` + Title string `json:"title"` + Files []string `json:"files,omitempty"` + Revision uint64 `json:"revision"` +} + +func checkpointTools() []Tool { + return []Tool{ + { + Name: ToolCheckpointList, + Title: "List history and checkpoints", + Description: "List recent project history and persistent turn checkpoints stored in .nsgo/checkpoints, newest first, optionally filtered by who made them (all, you, or agent).", + InputSchema: []byte(checkpointListSchema), + Action: ActionRead, + Handler: checkpointList, + }, + { + Name: ToolCheckpointRestore, + Title: "Restore a checkpoint", + Description: "Restore every file recorded in a persistent checkpoint back to its pre-turn bytes as one undoable step; Undo puts the turn back.", + InputSchema: []byte(checkpointRestoreSchema), + Action: ActionEdit, + targets: checkpointRestoreTargets, + Handler: checkpointRestore, + }, + } +} + +// checkpointRestoreTargets expands a checkpoint_restore call into one PermissionRequest per file +// recorded in the checkpoint manifest so You-only boundaries and file-scoped edit/code/delete rules +// are evaluated against every file that restoring would modify or remove. +func checkpointRestoreTargets(args json.RawMessage, ed *editor.Editor) []editor.PermissionRequest { + if ed == nil { + return nil + } + var parsed struct { + ID string `json:"id"` + } + if err := json.Unmarshal(args, &parsed); err != nil { + return nil + } + id := strings.TrimPrefix(strings.TrimSpace(parsed.ID), "cp:") + if id == "" { + return nil + } + m, err := ed.CheckpointManifest(id) + if err != nil || len(m.Files) == 0 { + return nil + } + reqs := make([]editor.PermissionRequest, 0, len(m.Files)) + for _, f := range m.Files { + action := editor.PermissionActionEdit + if !f.Existed { + action = editor.PermissionActionDelete + } else if strings.HasSuffix(strings.ToLower(f.Path), ".go") { + action = editor.PermissionActionCode + } + reqs = append(reqs, editor.PermissionRequest{ + Tool: ToolCheckpointRestore, + Action: action, + Target: f.Path, + }) + } + return reqs +} + +func checkpointList(ctx context.Context, c *Call) (*Result, error) { + var args struct { + Filter string `json:"filter"` + Limit int `json:"limit"` + } + if err := c.Decode(&args); err != nil { + return nil, fmt.Errorf("checkpoint_list: %w", err) + } + filter := editor.HistoryFilterAll + switch args.Filter { + case "", "all": + filter = editor.HistoryFilterAll + case "you": + filter = editor.HistoryFilterYou + case "agent": + filter = editor.HistoryFilterAgent + default: + return nil, fmt.Errorf("checkpoint_list: unknown filter %q (want all, you, or agent)", args.Filter) + } + limit := args.Limit + if limit <= 0 { + limit = 50 + } + if limit > 200 { + limit = 200 + } + + var res CheckpointListResult + res.Filter = string(filter) + err := c.Editor(ctx, func(ed *editor.Editor) error { + if ed.Project != nil && ed.ProjectPath != "" { + _, _ = ed.LoadCheckpoints() + } + entries := ed.UnifiedHistoryEntries(filter) + res.Total = len(entries) + if len(entries) > limit { + entries = entries[:limit] + } + res.Entries = make([]CheckpointListItem, 0, len(entries)) + for _, e := range entries { + ts := "" + if !e.Timestamp.IsZero() { + ts = e.Timestamp.UTC().Format(time.RFC3339) + } + id := fmt.Sprintf("history:%d", e.ID) + kind := string(e.Kind) + restorable := e.ID > 0 + if e.Kind == editor.HistoryEntryCheckpoint && e.CheckpointID != "" { + id = "cp:" + e.CheckpointID + kind = string(e.CheckpointKind) + restorable = len(e.Files) > 0 + } + res.Entries = append(res.Entries, CheckpointListItem{ + ID: id, + CheckpointID: e.CheckpointID, + Time: ts, + Who: string(e.Author), + Kind: kind, + Title: e.Summary, + Detail: e.Detail, + Files: e.Files, + Persistent: e.Persistent, + Restorable: restorable, + }) + } + return nil + }) + if err != nil { + return nil, err + } + + var b strings.Builder + if len(res.Entries) == 0 { + b.WriteString("No history entries or checkpoints.\n") + } else { + fmt.Fprintf(&b, "%d history entries (showing %d):\n", res.Total, len(res.Entries)) + for _, item := range res.Entries { + tag := item.Who + if tag == "" { + tag = item.Kind + } + if item.CheckpointID != "" { + tag += " · checkpoint " + item.CheckpointID + } + fmt.Fprintf(&b, "- [%s] %s", tag, item.Title) + if len(item.Files) > 0 { + fmt.Fprintf(&b, " (%s)", strings.Join(item.Files, ", ")) + } + b.WriteByte('\n') + } + } + return &Result{Text: b.String(), Structured: res}, nil +} + +func checkpointRestore(ctx context.Context, c *Call) (*Result, error) { + var args struct { + ID string `json:"id"` + } + if err := c.Decode(&args); err != nil { + return nil, fmt.Errorf("checkpoint_restore: %w", err) + } + id := strings.TrimPrefix(strings.TrimSpace(args.ID), "cp:") + if id == "" { + return nil, fmt.Errorf("checkpoint_restore: id is required") + } + + var res CheckpointRestoreResult + err := c.Editor(ctx, func(ed *editor.Editor) error { + m, err := ed.CheckpointManifest(id) + if err != nil { + return err + } + if err := ed.RestoreCheckpoint(id); err != nil { + return err + } + res.ID = m.ID + res.Title = m.Title + res.Files = make([]string, len(m.Files)) + for i, f := range m.Files { + res.Files[i] = f.Path + } + res.Revision = ed.Revision() + return nil + }) + if err != nil { + return nil, fmt.Errorf("checkpoint_restore: %w", err) + } + + text := fmt.Sprintf("Restored checkpoint %s (%q) across %d file(s) as one undoable step.", res.ID, res.Title, len(res.Files)) + return &Result{Text: text, Structured: res}, nil +} + +func checkpointTitleForTool(t Tool) string { + if t.Title != "" { + return t.Title + } + return t.Name +} diff --git a/packages/game/editor/editormcp/checkpoints_test.go b/packages/game/editor/editormcp/checkpoints_test.go new file mode 100644 index 000000000..f395de011 --- /dev/null +++ b/packages/game/editor/editormcp/checkpoints_test.go @@ -0,0 +1,133 @@ +package editormcp_test + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor/editormcp" +) + +// MCP edits record persistent turn checkpoints visible via checkpoint_list and restorable via checkpoint_restore with Undo. +func TestMCPCheckpointsListAndRestore(t *testing.T) { + f := openFixture(t) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + sceneOrig, err := os.ReadFile(f.scenePath()) + if err != nil { + t.Fatal(err) + } + prefabFile := filepath.Join(f.dir, "prefabs", "coin.prefab.yaml") + if err := os.MkdirAll(filepath.Dir(prefabFile), 0o755); err != nil { + t.Fatal(err) + } + prefabOrig := []byte("version: 1\nname: Coin\n") + if err := os.WriteFile(prefabFile, prefabOrig, 0o644); err != nil { + t.Fatal(err) + } + + // Run an agent turn that calls scene_edit through MCP and edits a prefab. + if _, err := f.ed.BeginCheckpointTurn("Move hero and update coin"); err != nil { + t.Fatal(err) + } + mustOK(t, call(t, cs, editormcp.ToolSceneEdit, map[string]any{ + "edits": []any{ + map[string]any{"op": "move", "id": "hero", "x": 180, "y": 90}, + }, + })) + if err := f.ed.SaveFile(f.scenePath()); err != nil { + t.Fatal(err) + } + if err := f.ed.WriteAgentFile("prefabs/coin.prefab.yaml", []byte("version: 1\nname: CoinGold\n")); err != nil { + t.Fatal(err) + } + cp, err := f.ed.EndCheckpointTurn("2 files") + if err != nil || cp == nil { + t.Fatalf("EndCheckpointTurn: %v, %+v", err, cp) + } + + // checkpoint_list returns the persistent checkpoint. + listRes := call(t, cs, editormcp.ToolCheckpointList, map[string]any{"filter": "agent"}) + listText := mustOK(t, listRes) + var listOut editormcp.CheckpointListResult + structured(t, listRes, &listOut) + if len(listOut.Entries) != 1 || listOut.Entries[0].CheckpointID != cp.ID || !strings.Contains(listText, cp.ID) { + t.Fatalf("checkpoint_list = %+v\n%s", listOut, listText) + } + + // checkpoint_restore restores both scene and prefab byte-for-byte. + restRes := call(t, cs, editormcp.ToolCheckpointRestore, map[string]any{"id": cp.ID}) + mustOK(t, restRes) + var restOut editormcp.CheckpointRestoreResult + structured(t, restRes, &restOut) + if restOut.ID != cp.ID || len(restOut.Files) != 2 { + t.Fatalf("checkpoint_restore = %+v", restOut) + } + gotScene, _ := os.ReadFile(f.scenePath()) + gotPrefab, _ := os.ReadFile(prefabFile) + if !bytes.Equal(gotScene, sceneOrig) || !bytes.Equal(gotPrefab, prefabOrig) { + t.Fatalf("restored files did not match originals byte-for-byte") + } + + // Undo puts the turn back! + if !f.ed.Undo() { + t.Fatal("Undo returned false") + } + if obj, _, _ := f.ed.FindObject("hero"); obj == nil || obj.X != 180 { + t.Fatalf("hero after Undo = %+v, want X=180", obj) + } + gotPrefabAfterUndo, _ := os.ReadFile(prefabFile) + if string(gotPrefabAfterUndo) != "version: 1\nname: CoinGold\n" { + t.Fatalf("prefab after Undo = %q", string(gotPrefabAfterUndo)) + } +} + +// Permission enforcement: checkpoint_restore checks every file in the checkpoint manifest against +// the project's permission rules (delete -> Deny in Balanced, .go -> Ask in Balanced). +func TestMCPCheckpointRestoreEnforcesPermissions(t *testing.T) { + f := openFixture(t) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + // Checkpoint 1 created a new file (existed: false), so restoring deletes it -> Balanced denies delete! + cpNew, err := f.ed.RunCheckpointTurn("Create sparkle", func() error { + return f.ed.WriteAgentFile("fx/sparkle.particles.yaml", []byte("version: 1\nname: sparkle\n")) + }) + if err != nil { + t.Fatal(err) + } + resDel := call(t, cs, editormcp.ToolCheckpointRestore, map[string]any{"id": cpNew.ID}) + if !resDel.IsError { + t.Fatalf("expected Balanced permission Deny for checkpoint_restore deleting newly created file, got ok") + } + if _, err := os.Stat(filepath.Join(f.dir, "fx", "sparkle.particles.yaml")); err != nil { + t.Fatalf("denied checkpoint_restore must not remove file: %v", err) + } + + // Checkpoint 2 edited a Go file -> Balanced requires Ask (pending permission error) for code! + goPath := filepath.Join(f.dir, "scripts", "patrol.go") + if err := os.MkdirAll(filepath.Dir(goPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(goPath, []byte("package scripts\nconst Speed = 10\n"), 0o644); err != nil { + t.Fatal(err) + } + cpGo, err := f.ed.RunCheckpointTurn("Tune patrol speed", func() error { + return f.ed.WriteAgentFile("scripts/patrol.go", []byte("package scripts\nconst Speed = 20\n")) + }) + if err != nil { + t.Fatal(err) + } + resGo := call(t, cs, editormcp.ToolCheckpointRestore, map[string]any{"id": cpGo.ID}) + if !resGo.IsError { + t.Fatalf("expected Balanced permission Ask for checkpoint_restore touching .go file, got ok") + } + if raw, _ := os.ReadFile(goPath); !strings.Contains(string(raw), "Speed = 20") { + t.Fatalf("blocked checkpoint_restore mutated patrol.go: %q", string(raw)) + } +} diff --git a/packages/game/editor/editormcp/example_test.go b/packages/game/editor/editormcp/example_test.go index f681cbe90..abcaf3ecb 100644 --- a/packages/game/editor/editormcp/example_test.go +++ b/packages/game/editor/editormcp/example_test.go @@ -85,6 +85,8 @@ func ExampleServer_AddTool() { // agent_turn_get read // agent_turn_reply edit // brief_edit edit + // checkpoint_list read + // checkpoint_restore edit // cutscene_scrub read // cutscene_write edit // datatable_review_checks edit diff --git a/packages/game/editor/editormcp/history.go b/packages/game/editor/editormcp/history.go index f8a11225d..6133a4ddb 100644 --- a/packages/game/editor/editormcp/history.go +++ b/packages/game/editor/editormcp/history.go @@ -31,6 +31,8 @@ type HistoryEntryView struct { ChangeCount int `json:"changeCount,omitempty"` KeptCount int `json:"keptCount,omitempty"` Undone bool `json:"undone,omitempty"` + CheckpointID string `json:"checkpointId,omitempty"` + Persistent bool `json:"persistent,omitempty"` } // HistoryListResult is the structured payload returned by history_list. @@ -114,6 +116,8 @@ func historyList(ctx context.Context, c *Call) (*Result, error) { ChangeCount: entry.ChangeCount, KeptCount: entry.KeptCount, Undone: entry.Undone, + CheckpointID: entry.CheckpointID, + Persistent: entry.Persistent, }) } return nil diff --git a/packages/game/editor/editormcp/playtest.go b/packages/game/editor/editormcp/playtest.go index b5fdb066e..9c362c064 100644 --- a/packages/game/editor/editormcp/playtest.go +++ b/packages/game/editor/editormcp/playtest.go @@ -308,6 +308,16 @@ func gamePlaytest(ctx context.Context, c *Call) (*Result, error) { Pattern: pattern, } + // Always take a pre-start checkpoint before an autonomous playtest runs. + _ = c.Editor(ctx, func(ed *editor.Editor) error { + if ed.ActiveTurnID() == "" { + _, _ = ed.TakeCheckpointBeforeAutomation("Playtest · "+cleanCfg, cleanOut) + } else { + _ = ed.RecordCheckpointFile(cleanOut) + } + return nil + }) + runner := c.s.runPlaytest if runner == nil { runner = defaultRunPlaytest diff --git a/packages/game/editor/editormcp/proxy_test.go b/packages/game/editor/editormcp/proxy_test.go index d671c5b43..772e24ab9 100644 --- a/packages/game/editor/editormcp/proxy_test.go +++ b/packages/game/editor/editormcp/proxy_test.go @@ -62,7 +62,7 @@ func TestProxyFindsTheEditor(t *testing.T) { } }}, "") - if names := listNames(t, cs); !slices.Equal(names, []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"}) { + if names := listNames(t, cs); !slices.Equal(names, []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"}) { t.Fatalf("tools without an editor: %v", names) } res := call(t, cs, editormcp.ToolSceneRead, nil) diff --git a/packages/game/editor/editormcp/server.go b/packages/game/editor/editormcp/server.go index d46cb8886..5b6d03b8b 100644 --- a/packages/game/editor/editormcp/server.go +++ b/packages/game/editor/editormcp/server.go @@ -887,13 +887,54 @@ func (s *Server) callWithSession(ctx context.Context, t Tool, args json.RawMessa if err = s.checkPrivacyPre(ctx, t, args, onEditor); err != nil { return nil, err } - res, err = t.Handler(ctx, &Call{ + c := &Call{ Args: args, s: s, onEditor: onEditor, session: session, taskID: s.sessionTaskID(session), - }) + } + startedTurn := false + if t.Action == ActionEdit && + t.Name != ToolCheckpointRestore && + t.Name != ToolAgentTurnReply && + t.Name != ToolTasksSubmit && + t.Name != ToolTasksControl && + t.Name != ToolPermissionsDraft && + t.Name != ToolGameDeleteFile { + kind := editor.CheckpointKindTurn + if onEditor { + kind = editor.CheckpointKindAutomation + } + _ = c.Editor(ctx, func(ed *editor.Editor) error { + if ed.Project != nil && ed.ProjectPath != "" && ed.ActiveTurnID() == "" { + if _, berr := ed.BeginCheckpointTurnWith(editor.CheckpointOptions{ + Who: editor.HistoryAuthorAgent, + Kind: kind, + Title: checkpointTitleForTool(t), + }); berr == nil { + startedTurn = true + } + } + return nil + }) + } + finished := false + if startedTurn { + defer func() { + cleanupCtx := context.WithoutCancel(ctx) + _ = c.Editor(cleanupCtx, func(ed *editor.Editor) error { + if !finished || err != nil { + _, _ = ed.FinishCheckpointTurnOnError("interrupted") + } else { + _, _ = ed.EndCheckpointTurn("") + } + return nil + }) + }() + } + res, err = t.Handler(ctx, c) + finished = true if err == nil { if perr := s.checkPrivacyPost(ctx, t, res, onEditor); perr != nil { res, err = nil, perr diff --git a/packages/game/editor/editormcp/server_test.go b/packages/game/editor/editormcp/server_test.go index 647eb4de2..8eb033d41 100644 --- a/packages/game/editor/editormcp/server_test.go +++ b/packages/game/editor/editormcp/server_test.go @@ -39,7 +39,7 @@ func TestServerListsToolsAndResources(t *testing.T) { } } slices.Sort(names) - want := []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"} + want := []string{"agent_turn_get", "agent_turn_reply", "brief_edit", "checkpoint_list", "checkpoint_restore", "cutscene_scrub", "cutscene_write", "datatable_review_checks", "datatable_review_propose", "datatable_review_status", "game_check", "game_playtest", "history_list", "merge_abort", "merge_finish", "merge_resolve", "merge_status", "object_copy_yaml", "object_duplicate", "object_find_usages", "object_group", "object_locate_yaml", "object_move_under", "object_paste_yaml", "object_select_same_prefab", "object_set_field", "object_visibility", "permissions_draft", "play_frozen_context", "play_replay_step", "playtest_define", "playtest_report", "problem_propose_fix", "project_context", "refactor_rename", "refs_find", "release_notes_draft", "release_review_uploads", "review_notes_get", "review_redo", "review_status", "rules_edit", "scene_edit", "scene_read", "selection_get", "sketch_read", "sketch_reading", "states_test", "states_write", "tasks_control", "tasks_list", "tasks_submit", "tile_autotile", "tile_erase", "tile_paint", "tile_query", "tile_review_keep", "tile_review_restore_region", "tile_review_revert_all", "tile_review_revert_region", "tile_review_status", "tileset_edit", "tileset_read", "viewport_image"} if !slices.Equal(names, want) { t.Fatalf("tools = %v, want %v", names, want) } diff --git a/packages/game/editor/editormcp/tools.go b/packages/game/editor/editormcp/tools.go index bb331052f..50bd72528 100644 --- a/packages/game/editor/editormcp/tools.go +++ b/packages/game/editor/editormcp/tools.go @@ -146,7 +146,7 @@ func builtinTools() []Tool { Target: tilesetEditTarget, Handler: tilesetEdit, }, - }, append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(playtestTools(), mergeTools()...), refsTools()...), tileTools()...), inspectorTools()...), objectMenuTools()...), releaseTools()...), problemTools()...), playFrozenTools()...), agentTools()...), taskTools()...), contextTools()...), historyTools()...), youOnlyTools()...), reviewTools()...), dataTableReviewTools()...), sketchTools()...)...) + }, append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(append(playtestTools(), mergeTools()...), refsTools()...), tileTools()...), inspectorTools()...), objectMenuTools()...), releaseTools()...), problemTools()...), playFrozenTools()...), agentTools()...), taskTools()...), contextTools()...), historyTools()...), youOnlyTools()...), reviewTools()...), dataTableReviewTools()...), sketchTools()...), checkpointTools()...)...) } // projectRoot returns the absolute, symlink-free root of ed's project, or "" without one. diff --git a/packages/game/editor/history.go b/packages/game/editor/history.go index fd2252679..7c386aafc 100644 --- a/packages/game/editor/history.go +++ b/packages/game/editor/history.go @@ -68,6 +68,8 @@ const ( HistoryEntryEdit HistoryEntryKind = "edit" // HistoryEntrySaved is a saved-point marker recorded when files are persisted to disk or OnSave. HistoryEntrySaved HistoryEntryKind = "saved" + // HistoryEntryCheckpoint is a persistent per-turn, task, or automation checkpoint stored under .nsgo/checkpoints/. + HistoryEntryCheckpoint HistoryEntryKind = "checkpoint" ) // HistoryFilter filters which entries the History panel or MCP history_list returns. @@ -106,6 +108,12 @@ type HistoryEntry struct { Undone bool // RestoredFromID is non-zero when this step was created by restoring an earlier HistoryEntry. RestoredFromID uint64 + // CheckpointID is non-empty when this entry is backed by or belongs to a persistent checkpoint under .nsgo/checkpoints/. + CheckpointID string + // CheckpointKind identifies why a persistent checkpoint was created ("turn", "task", or "automation"). + CheckpointKind CheckpointKind + // Persistent reports whether this entry is stored in .nsgo/checkpoints/ and survives editor restarts. + Persistent bool } // Clone returns a deep copy of e so callers cannot mutate History's internal slice. @@ -195,6 +203,8 @@ type History struct { onChange func() // beforeExecute optionally rejects mutations (for example while read-only History preview is active). beforeExecute func() error + // beforeCommand optionally runs right before a command mutates state (for example to snapshot touched files into an active checkpoint). + beforeCommand func(Command) // onRecord enriches a newly recorded timeline entry with scene/file snapshots and editor context. onRecord func(cmd Command, rec *historyRecord) // onClear runs when Clear empties the stack. @@ -525,6 +535,9 @@ func (h *History) execute(cmd Command) error { return err } } + if h.beforeCommand != nil { + h.beforeCommand(cmd) + } if f, ok := cmd.(fallibleCommand); ok { if err := f.do(); err != nil { return err diff --git a/packages/game/editor/history_timeline.go b/packages/game/editor/history_timeline.go index 0159156a1..d35dd4d9b 100644 --- a/packages/game/editor/history_timeline.go +++ b/packages/game/editor/history_timeline.go @@ -42,10 +42,11 @@ type AgentTurnOptions struct { } type historyPreviewState struct { - entryID uint64 - entry HistoryEntry - doc *sceneformat.SceneDoc - scene *sceneformat.BuiltScene + entryID uint64 + checkpointID string + entry HistoryEntry + doc *sceneformat.SceneDoc + scene *sceneformat.BuiltScene } type historyPanelState struct { @@ -60,29 +61,29 @@ type historyPanelState struct { } // SetHistoryClock sets the clock used to timestamp History timeline entries across all open tabs. -// Passing nil restores time.Now. +// Passing nil restores Editor.Now or time.Now. func (e *Editor) SetHistoryClock(fn func() time.Time) { if e == nil { return } e.historyPanel.clock = fn if e.History != nil { - e.History.SetClock(fn) + e.History.SetClock(e.HistoryNow) } for _, t := range e.tabs { if t != nil && t.history != nil { - t.history.SetClock(fn) + t.history.SetClock(e.HistoryNow) } } } -// HistoryNow returns the current time according to the editor's configured History clock (or time.Now). +// HistoryNow returns the current time according to the editor's configured History clock, Editor.Now, or time.Now. func (e *Editor) HistoryNow() time.Time { if e != nil && e.historyPanel.clock != nil { return e.historyPanel.clock() } - if e != nil && e.History != nil { - return e.History.now() + if e != nil && e.Now != nil { + return e.Now() } return time.Now() } @@ -124,6 +125,7 @@ func (e *Editor) resetHistoryPanelForProject() { e.historyPanel.pendingMeta = nil e.historyPanel.savingDepth = 0 e.historyPanel.savedFiles = nil + e.resetCheckpointsForProject() } // SetHistoryPanelOpen opens or closes the History timeline panel. @@ -140,6 +142,9 @@ func (e *Editor) SetHistoryPanelOpen(open bool) { } changed := e.historyPanel.open != open e.historyPanel.open = open + if open && e.Project != nil && e.ProjectPath != "" { + _, _ = e.LoadCheckpoints() + } if !open && e.historyPanel.preview != nil { e.historyPanel.preview = nil e.s3d.stale = true @@ -223,6 +228,29 @@ func (e *Editor) HistoryPreviewEntry() (HistoryEntry, bool) { return e.historyPanel.preview.entry.Clone(), true } +// HistoryPreviewCheckpointID returns the checkpoint ID currently being previewed read-only, or "". +func (e *Editor) HistoryPreviewCheckpointID() string { + if e == nil || e.historyPanel.preview == nil { + return "" + } + return e.historyPanel.preview.checkpointID +} + +// RestorePreviewedHistory restores whichever History entry or persistent checkpoint is currently +// being previewed as ONE undoable step. +func (e *Editor) RestorePreviewedHistory() error { + if e == nil { + return errors.New("editor: nil editor") + } + if e.historyPanel.preview == nil { + return errors.New("editor: no history entry is currently previewed") + } + if cpID := e.historyPanel.preview.checkpointID; cpID != "" { + return e.RestoreCheckpoint(cpID) + } + return e.RestoreHistoryEntry(e.historyPanel.preview.entryID) +} + // HistoryPreviewDoc returns the read-only SceneDoc currently being previewed, or nil when not previewing. func (e *Editor) HistoryPreviewDoc() *sceneformat.SceneDoc { if e == nil || e.historyPanel.preview == nil { @@ -868,6 +896,15 @@ func (e *Editor) recordHistoryStep(cmd Command, rec *historyRecord) { rec.entry.Summary = strings.TrimSpace(cmd.Label()) } } + if turn := e.checkpoints.active; turn != nil { + if _, isRestore := cmd.(*checkpointRestoreCmd); !isRestore { + rec.entry.CheckpointID = turn.manifest.ID + rec.entry.CheckpointKind = turn.manifest.Kind + if turn.manifest.Who == HistoryAuthorAgent && rec.entry.Author == HistoryAuthorYou { + rec.entry.Author = HistoryAuthorAgent + } + } + } if len(rec.entry.Files) == 0 { if f := e.historyActiveSceneFile(); f != "" { diff --git a/packages/game/editor/history_ui.go b/packages/game/editor/history_ui.go index 8507fc4ea..47b662f76 100644 --- a/packages/game/editor/history_ui.go +++ b/packages/game/editor/history_ui.go @@ -16,19 +16,20 @@ type historyThemeKey struct { } type historyPreviewBannerKey struct { - id uint64 - ago string - dark bool - lang string + id uint64 + checkpointID string + ago string + dark bool + lang string } func (e *Editor) historyListDigest(dark bool, lang string) string { filter := e.HistoryFilter() - entries := e.FilteredHistoryEntries(filter) + entries := e.UnifiedHistoryEntries(filter) previewEntry, previewing := e.HistoryPreviewEntry() dirty := e.HasUnsavedChanges() var b strings.Builder - fmt.Fprintf(&b, "%t|%s|%s|%t|%d|%d|", dark, lang, filter, dirty, previewEntry.ID, len(entries)) + fmt.Fprintf(&b, "%t|%s|%s|%t|%d|%s|%d|", dark, lang, filter, dirty, previewEntry.ID, previewEntry.CheckpointID, len(entries)) if previewing { b.WriteByte('1') } else { @@ -40,7 +41,7 @@ func (e *Editor) historyListDigest(dark bool, lang string) string { for _, entry := range entries { ago := e.FormatHistoryRelativeTime(entry.Timestamp) day := e.FormatHistoryDayLabel(entry.Timestamp) - fmt.Fprintf(&b, ";%d:%s:%s:%t:%s:%s", entry.ID, entry.Kind, entry.Author, entry.Undone, day, ago) + fmt.Fprintf(&b, ";%d:%s:%s:%s:%t:%s:%s", entry.ID, entry.CheckpointID, entry.Kind, entry.Author, entry.Undone, day, ago) } return b.String() } @@ -77,10 +78,11 @@ func HistoryPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core return historyPreviewBannerKey{dark: tk.dark, lang: tk.lang} } return historyPreviewBannerKey{ - id: entry.ID, - ago: ed.FormatHistoryRelativeTime(entry.Timestamp), - dark: tk.dark, - lang: tk.lang, + id: entry.ID, + checkpointID: entry.CheckpointID, + ago: ed.FormatHistoryRelativeTime(entry.Timestamp), + dark: tk.dark, + lang: tk.lang, } }) listKeyMemo := core.NewMemo(cx, func() string { @@ -237,7 +239,8 @@ func HistoryPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core previewBar := core.Show{ When: func() bool { - return previewMemo.Get().id != 0 + pk := previewMemo.Get() + return pk.id != 0 || pk.checkpointID != "" }, Then: func(cx *core.Scope) core.Node { return core.View{ @@ -307,8 +310,8 @@ func HistoryPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core } }, OnPress: func(core.PressEvent) { - if entry, ok := ed.HistoryPreviewEntry(); ok { - ed.report(ed.RestoreHistoryEntry(entry.ID)) + if ed.HistoryPreviewActive() { + ed.report(ed.RestorePreviewedHistory()) } }, Children: []core.Node{ @@ -397,7 +400,7 @@ func HistoryPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core _ = listKeyMemo.Get() p := pal() filter := ed.HistoryFilter() - entries := ed.FilteredHistoryEntries(filter) + entries := ed.UnifiedHistoryEntries(filter) previewEntry, previewing := ed.HistoryPreviewEntry() dirty := ed.HasUnsavedChanges() @@ -511,9 +514,16 @@ func HistoryPanelView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core }, }) } - isSelected := previewing && previewEntry.ID == entry.ID + var isSelected bool + if previewing { + if entry.Kind == HistoryEntryCheckpoint && entry.CheckpointID != "" { + isSelected = previewEntry.CheckpointID == entry.CheckpointID + } else if entry.ID > 0 { + isSelected = previewEntry.CheckpointID == "" && previewEntry.ID == entry.ID + } + } hasMore := i < len(entries)-1 - listRows = append(listRows, historyEntryRowView(ed, p, entry, isSelected, hasMore)) + listRows = append(listRows, historyEntryRowView(ed, p, entry, i, isSelected, hasMore)) } } @@ -613,13 +623,33 @@ func historyEntryBadgeColors(p SpecPalette, entry HistoryEntry) (label string, d } } -func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected bool, hasMore bool) core.Node { +func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, rowIdx int, selected bool, hasMore bool) core.Node { badgeLabel, dotColor, badgeBg, badgeFg := historyEntryBadgeColors(p, entry) relTime := ed.FormatHistoryRelativeTime(entry.Timestamp) headline := FormatHistoryEntryHeadline(entry) subtitle := FormatHistoryEntrySubtitle(entry, relTime) clockStr := entry.Timestamp.Format("15:04") + isCheckpoint := entry.Kind == HistoryEntryCheckpoint && entry.CheckpointID != "" + var rowTestID, titleTestID, subtitleTestID, filesTestID string + switch { + case isCheckpoint: + rowTestID = "history-row-cp:" + entry.CheckpointID + titleTestID = "history-row-title-cp:" + entry.CheckpointID + subtitleTestID = "history-row-subtitle-cp:" + entry.CheckpointID + filesTestID = "history-row-files-cp:" + entry.CheckpointID + case entry.ID > 0: + rowTestID = fmt.Sprintf("history-row-%d", entry.ID) + titleTestID = fmt.Sprintf("history-row-title-%d", entry.ID) + subtitleTestID = fmt.Sprintf("history-row-subtitle-%d", entry.ID) + filesTestID = fmt.Sprintf("history-row-files-%d", entry.ID) + default: + rowTestID = fmt.Sprintf("history-row-git-%d", rowIdx) + titleTestID = fmt.Sprintf("history-row-title-git-%d", rowIdx) + subtitleTestID = fmt.Sprintf("history-row-subtitle-git-%d", rowIdx) + filesTestID = fmt.Sprintf("history-row-files-git-%d", rowIdx) + } + rowStyle := core.Style{ Direction: core.Row, AlignItems: core.AlignStart, @@ -666,6 +696,29 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected }, }, } + if isCheckpoint { + metaChildren = append(metaChildren, core.View{ + Style: core.Style{ + Height: core.Pt(18), + Padding: core.Symmetric(0, 6), + CornerRadius: 5, + Background: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Text{ + Content: ed.T("history.checkpoint"), + Style: core.Style{ + FontSize: 10, + FontWeight: 500, + Color: p.TextSecondary, + }, + }, + }, + }) + } if entry.Undone { metaChildren = append(metaChildren, core.Text{ Content: ed.T("history.undone"), @@ -686,7 +739,7 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected Children: metaChildren, }, core.Text{ - TestID: fmt.Sprintf("history-row-title-%d", entry.ID), + TestID: titleTestID, Content: headline, Style: core.Style{ FontSize: 12.5, @@ -695,7 +748,7 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected }, }, core.Text{ - TestID: fmt.Sprintf("history-row-subtitle-%d", entry.ID), + TestID: subtitleTestID, Content: subtitle, Style: core.Style{ FontSize: 11.5, @@ -712,7 +765,7 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected filesLine := strings.Join(bases, " · ") if filesLine != "" && filesLine != entry.Detail { bodyChildren = append(bodyChildren, core.Text{ - TestID: fmt.Sprintf("history-row-files-%d", entry.ID), + TestID: filesTestID, Content: filesLine, Style: core.Style{ FontFamily: core.FontMonospace, @@ -723,16 +776,11 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected } } - entryID := entry.ID - return core.View{ - TestID: fmt.Sprintf("history-row-%d", entry.ID), - Role: core.RoleButton, - Label: headline + " · " + subtitle, - Focusable: func() bool { return true }, - Style: rowStyle, - OnPress: func(core.PressEvent) { - ed.report(ed.PreviewHistoryEntry(entryID)) - }, + interactive := isCheckpoint || entry.ID > 0 + row := core.View{ + TestID: rowTestID, + Label: headline + " · " + subtitle, + Style: rowStyle, Children: []core.Node{ historyTimelineRail(p, dotColor, false, hasMore), core.View{ @@ -745,6 +793,22 @@ func historyEntryRowView(ed *Editor, p SpecPalette, entry HistoryEntry, selected }, }, } + if interactive { + row.Role = core.RoleButton + row.Focusable = func() bool { return true } + if isCheckpoint { + cpID := entry.CheckpointID + row.OnPress = func(core.PressEvent) { + ed.report(ed.PreviewCheckpoint(cpID)) + } + } else { + entryID := entry.ID + row.OnPress = func(core.PressEvent) { + ed.report(ed.PreviewHistoryEntry(entryID)) + } + } + } + return row } // viewportHistoryPreviewBannerView renders the floating read-only preview banner at the top of the @@ -772,10 +836,11 @@ func viewportHistoryPreviewBannerView(cx *core.Scope, ed *Editor, rev *core.Sign return historyPreviewBannerKey{dark: dark, lang: lang} } return historyPreviewBannerKey{ - id: entry.ID, - ago: ed.FormatHistoryRelativeTime(entry.Timestamp), - dark: dark, - lang: lang, + id: entry.ID, + checkpointID: entry.CheckpointID, + ago: ed.FormatHistoryRelativeTime(entry.Timestamp), + dark: dark, + lang: lang, } }) pal := func() SpecPalette { @@ -845,8 +910,8 @@ func viewportHistoryPreviewBannerView(cx *core.Scope, ed *Editor, rev *core.Sign } }, OnPress: func(core.PressEvent) { - if entry, ok := ed.HistoryPreviewEntry(); ok { - ed.report(ed.RestoreHistoryEntry(entry.ID)) + if ed.HistoryPreviewActive() { + ed.report(ed.RestorePreviewedHistory()) } }, Children: []core.Node{ diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index 1ba62a54c..101d1892d 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -409,6 +409,7 @@ strings: gizmo.spaceLocal: Local gizmo.translate: Translate history.back: Back + history.checkpoint: Checkpoint history.close: Close History history.empty: No edits yet. Your edits and the agent's turns appear here on one timeline. history.emptyAgent: No agent turns recorded yet. @@ -417,7 +418,7 @@ strings: history.filter.all: All history.filter.you: You history.filterLabel: Show - history.footer: Click a step to preview the scene at that point; Restore rolls back to it as one new step, so nothing is ever lost. + history.footer: Stored in .nsgo/checkpoints, ignored by git. Click a step to preview read-only; Restore rolls back as one undoable step. history.now: Now history.previewing: Previewing %s · editing is off history.restore: Restore diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index f5fee6589..f3d44a5b2 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -409,6 +409,7 @@ strings: gizmo.spaceLocal: 局部 gizmo.translate: 平移 history.back: 返回 + history.checkpoint: 检查点 history.close: 关闭历史面板 history.empty: 暂无编辑记录。你的编辑与智能体的回合会按同一条时间线显示在这里。 history.emptyAgent: 暂无智能体回合记录。 @@ -417,7 +418,7 @@ strings: history.filter.all: 全部 history.filter.you: 你 history.filterLabel: 显示 - history.footer: 点击任意步骤即可只读预览当时的场景;“恢复”会将其作为一个新的可撤销步骤回滚,不会丢失后续历史。 + history.footer: 保存在 .nsgo/checkpoints 中并被 git 忽略。点击任意步骤可只读预览;“恢复”会作为单个可撤销步骤回滚。 history.now: 现在 history.previewing: 正在预览 %s · 编辑已关闭 history.restore: 恢复 diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 4fab0809d..7be464288 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -600,6 +600,8 @@ type Editor struct { OnSendSketch func(SketchAgentRequest) // OnReplySketchReading, when set, is called when the author answers an agent sketch reading card (Go ahead, Correct a mark, or a text reply). OnReplySketchReading func(SketchReadingReply) + // CheckpointMaxBytes caps the total disk size under .nsgo/checkpoints/ before the oldest checkpoints are pruned (defaults to DefaultCheckpointMaxBytes when <= 0). + CheckpointMaxBytes int64 playing bool playPaused bool @@ -953,6 +955,8 @@ type Editor struct { agentReview agentReviewState // review holds the change-by-change agent turn review state, pending overlays, and right-rail Agent card state. review turnReviewState + // checkpoints holds the open project's persistent .nsgo/checkpoints/ state and any active turn. + checkpoints checkpointState } // DefaultSceneDoc returns a valid starter SceneDoc suitable for a new editor session. diff --git a/packages/game/editor/tabs.go b/packages/game/editor/tabs.go index 42d3b96d9..36ff65916 100644 --- a/packages/game/editor/tabs.go +++ b/packages/game/editor/tabs.go @@ -90,13 +90,14 @@ func (e *Editor) nextTabID() uint64 { func (e *Editor) newTabHistory() *History { h := NewHistory() - h.clock = e.historyPanel.clock + h.clock = e.HistoryNow h.beforeExecute = func() error { if e.HistoryPreviewActive() { return ErrHistoryPreview } return nil } + h.beforeCommand = e.beforeHistoryExecute h.onRecord = func(cmd Command, rec *historyRecord) { e.recordHistoryStep(cmd, rec) } diff --git a/packages/game/editor/tasks.go b/packages/game/editor/tasks.go index a95c7a6a1..5c31376b5 100644 --- a/packages/game/editor/tasks.go +++ b/packages/game/editor/tasks.go @@ -1452,6 +1452,13 @@ func (e *Editor) launchTaskRunner(taskID string) { if !ok { return } + if e.Project != nil && e.ProjectPath != "" && e.ActiveTurnID() == "" { + if task.Source == TaskSourceAutomation { + _, _ = e.TakeCheckpointBeforeAutomation(task.Title) + } else { + _, _ = e.TakeCheckpointBeforeTask(task.Title) + } + } runner := e.AgentTaskRunner ctx, cancel := context.WithTimeout(context.Background(), defaultTaskRunnerTimeout) e.tasks.mu.Lock() diff --git a/packages/game/editor/testdata/checkpoint_manifest.yaml b/packages/game/editor/testdata/checkpoint_manifest.yaml new file mode 100644 index 000000000..8901d2032 --- /dev/null +++ b/packages/game/editor/testdata/checkpoint_manifest.yaml @@ -0,0 +1,18 @@ +version: 1 +id: 20261126T144100Z-0001 +createdAt: "2026-11-26T14:41:00Z" +who: agent +kind: turn +title: Coin spin, bob and sparkle +detail: 2 files +files: + - path: fx/sparkle.particles.yaml + existed: false + - path: prefabs/coin.prefab.yaml + existed: true + size: 142 + sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + - path: scenes/level_01.scene.yaml + existed: true + size: 512 + sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 diff --git a/packages/game/formats_test.go b/packages/game/formats_test.go index 71405298d..a616cdd78 100644 --- a/packages/game/formats_test.go +++ b/packages/game/formats_test.go @@ -124,6 +124,7 @@ var formatVersions = map[string]string{ "editor.AgentThreadFileVersion": "editor#agent-thread", "editor.AgentThreadVersion": "editor#thread", "editor.AutomationsVersion": "editor#automations", + "editor.CheckpointVersion": "editor#checkpoint", "editor.PermissionsVersion": "editor#permissions", "editor.RecentProjectsVersion": "editor", "editor.SettingsVersion": "editor",