From 5100f4744241361d2c68efb6346e68b829a61096 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:53:24 +0900 Subject: [PATCH] feat(editor,editormcp): resolve review conflicts and hand-edit YAML in review --- ...11-26-editor-review-conflicts-yaml-edit.md | 36 + .../editor-review-conflicts-yaml-edit-1032.md | 4 + docs/en/editor.md | 11 +- docs/en/mcp.md | 2 +- docs/zh/editor.md | 11 +- docs/zh/mcp.md | 2 +- .../review_conflicts_screenshot_test.go | 222 ++ packages/game/editor/editormcp/review.go | 76 +- packages/game/editor/editormcp/review_test.go | 243 +++ packages/game/editor/review.go | 481 ++-- packages/game/editor/review_conflicts.go | 1937 +++++++++++++++++ packages/game/editor/review_conflicts_test.go | 558 +++++ packages/game/editor/review_notes.go | 37 + packages/game/editor/review_ui.go | 775 ++++++- packages/game/editor/state.go | 1 + 15 files changed, 4146 insertions(+), 250 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-review-conflicts-yaml-edit.md create mode 100644 changelog.d/editor-review-conflicts-yaml-edit-1032.md create mode 100644 packages/game/editor/editorcmd/review_conflicts_screenshot_test.go create mode 100644 packages/game/editor/review_conflicts.go create mode 100644 packages/game/editor/review_conflicts_test.go diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-review-conflicts-yaml-edit.md b/.agents/notes/implemented/feature/2026-11-26-editor-review-conflicts-yaml-edit.md new file mode 100644 index 000000000..f28dc6780 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-review-conflicts-yaml-edit.md @@ -0,0 +1,36 @@ +# Agent Note: Review turn conflict resolution and in-place YAML hand editing + +Status: implemented + +## Problem + +Inside the full-window change-by-change agent turn Review screen ([editor-review-change-by-change](./2026-11-26-editor-review-change-by-change.md), `docs/design/editor/Review.dc.html`, issue #1032), two workflows must block **Keep** cleanly without losing either the author's or the agent's work: + +1. **Overlapping edits**: the author may edit an object (for example appending a sound entry to `door_1.properties.on_open`) while a pending agent turn edits the same object. Edits to different fields must merge automatically without prompting, whereas overlapping edits to the same field or list must surface both sides (`you` and `agent`), let the author pick **Mine**, **Agent's**, or **Both** (keeping yours first), and block **Keep** until resolved. +2. **In-place YAML hand edits**: the author may edit an added or changed scene object's YAML directly in the Review right pane. Valid edits must update the Review viewport live, tag edited lines `you`, keep/undo as part of the turn, and remain readable by the agent through MCP in round 2; invalid YAML (such as typing `x 444` without a colon) must mark the exact scene line, block **Keep** and **Done**, offer a mechanical one-step fix when the parser names what is missing, and provide **Undo my typing**. + +## Decision + +Layer conflict resolution and in-place YAML editing directly onto the existing `turnReviewState` / `reviewFileState` / `ReviewScreenView` engine in `packages/game/editor/review.go`, `packages/game/editor/review_conflicts.go`, `packages/game/editor/review_ui.go`, and `packages/game/editor/editormcp/review.go`: + +- **Three-way merge on concurrent manual edits (`syncReviewAfterMutate`, `SyncReviewPersonEdits`)**: each scene `reviewFileState` tracks `personDoc` and `personEdited` alongside `beforeDoc` and `afterDoc`. Non-agent mutations through `Editor.afterMutate` update `personDoc` for the matching open scene and run `sceneformat.Merge(beforeDoc, personDoc, afterDoc)`. Disjoint field edits auto-merge into `effectiveReviewSceneDoc` with zero conflicts; overlapping field or list edits populate `ReviewChange.Conflicts` with `you` and `agent` lines. Picking `ReviewConflictBoth` preserves common base items followed by the person's additions first and the agent's additions second. +- **Keep blockers and atomic single-step Undo**: `Editor.ReviewBlockers()` prioritizes active YAML parse errors (`"Fix YAML on line N"`) ahead of unresolved conflicts (`"Choose how merges"`) and custom blockers. `KeepTurnReview()` jumps to the first blocker and returns `*ReviewBlockedError` (wrapping `ErrReviewBlocked`). When `personEdited` is true, `agentTurnKeepCmd` records the encoded `personDoc` as `beforeBytes` so one `Undo` reverts the agent turn, merge choice, and hand edits together while preserving the author's concurrent manual edits; when `personEdited` is false, exact `beforeYAML` bytes are preserved verbatim. +- **Strict, bounded YAML parsing and mechanical one-step fixes (`parseReviewObjectYAML`)**: `SetReviewYAMLDraft` enforces a 256 KiB cap, rejects NUL bytes, checks You-only boundaries (`validateReviewRelPath`), decodes with `yaml.Decoder.KnownFields(true)` (refusing unknown fields), checks duplicate mapping keys, detects plain-scalar continuation folds (`x 444` absorbed into a preceding plain scalar), validates component schemas and full-scene `sceneformat.Validate`, and produces verified `PatchedYAML` one-step fixes (**Add the colon**, **Close the quote**, **Add the closing brace**, **Add the closing bracket**, **Replace tabs with spaces**). +- **Focus-stable YAML editor and Spec Dark/Light UI (`reviewRightView`)**: `review-yaml-input` (`specInputField` with `Multiline: true` and reactive `StyleFunc`) is mounted inside a `core.Dynamic` keyed strictly on `(editing, changeID, yamlEditSessionRev)` rather than `reviewRev`, so typing never remounts `ui.Input`, steals focus, resets caret, or triggers single-letter `ScopeReview` shortcuts (`IsTyping()` guards `bindReviewShortcuts` and `KeyNotEditing`), while `ApplyReviewYAMLFix` and `UndoReviewYAMLTyping` bump `yamlEditSessionRev` to refresh the input cleanly. +- **Round-2 MCP visibility and privacy enforcement (`editormcp/review.go`, `editormcp/privacy.go`)**: `agentTurnKeepCmd.do` retains a deep snapshot of kept changes (`lastChanges`, `lastFiles`) so `Editor.ReviewStatus()` and `review_status` continue reporting conflict choices and `you`-tagged hand-edited fields/lines after Keep for round 2, while capping `HandEditLines`/`HandEditYAML` and enforcing `PrivacySceneAndData` and `PrivacyGoSource`. + +Related notes: [editor-review-change-by-change](./2026-11-26-editor-review-change-by-change.md), [editor-mcp-tile-review](./2026-11-26-editor-mcp-tile-review.md). + +## Alternatives considered + +1. **Maintain a separate single-file `ReviewSession` parallel to `turnReviewState`**: rejected because multi-file review (`#1014`) already landed with hardened path/symlink/You-only checks, multi-tab sync, unified History metadata, and `bindReviewShortcuts` inside `ReviewScreenView`. Layering `#1032` directly onto `turnReviewState` avoids duplicate UI/state and inherits every security boundary automatically. +2. **Mount `ui.Input` inside `reviewRightView`'s `reviewRev`-driven `core.Dynamic`**: rejected because every keystroke calls `SetReviewYAMLDraft` which bumps `uiRev` to update the live viewport and diff lines; mounting `ui.Input` under `reviewRev` would remount the input and lose focus on every keystroke. + +## Consequences + +- **Benefits**: + - Concurrent manual edits auto-merge when disjoint and present clear **Mine / Agent's / Both** choices when overlapping, without dropping either side. + - In-place YAML edits validate strictly, update the Review viewport live, recover cleanly from common syntax typos in one click, and undo with the turn in a single History step. + - Round-2 agents observe both merge choices and `you`-tagged hand edits through `review_status` under the project's privacy switches. +- **Costs**: + - `turnReviewState` retains a cloned snapshot of kept `ReviewChange` summaries (`lastChanges`) until the next turn review starts or the project switches so round-2 MCP queries can read them after Keep. diff --git a/changelog.d/editor-review-conflicts-yaml-edit-1032.md b/changelog.d/editor-review-conflicts-yaml-edit-1032.md new file mode 100644 index 000000000..704b34559 --- /dev/null +++ b/changelog.d/editor-review-conflicts-yaml-edit-1032.md @@ -0,0 +1,4 @@ +### Added + +- `game/editor`: three-way conflict detection and resolution (**Mine / Agent's / Both**, keeping yours first) for concurrent manual edits during an agent turn review (`syncReviewAfterMutate`, `SyncReviewPersonEdits`, `ResolveReviewConflict`), plus in-place YAML editing in the Review right pane (`BeginReviewYAMLEdit`, `SetReviewYAMLDraft`, `FinishReviewYAMLEdit`) with live viewport preview, `you`-tagged lines, strict unknown-field/duplicate-key validation, mechanical one-step parse fixes (`ApplyReviewYAMLFix`), **Undo my typing** (`UndoReviewYAMLTyping`), and single-step `History` Keep/Undo (#1032). +- `game/editor/editormcp`: extend `review_status` to expose conflict merge choices (`mine`, `agent`, `both`), `you`-tagged hand-edited YAML fields and lines (preserved after Keep for round 2), and YAML parse error blockers, while enforcing `PrivacySceneAndData` and `PrivacyGoSource` privacy switches (#1032). diff --git a/docs/en/editor.md b/docs/en/editor.md index a034456dc..5a47d9961 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1469,7 +1469,7 @@ When an agent completes a turn (`Editor.StartTurnReview`), the full-window **Rev - **Right pane (Why + YAML)**: shows the agent's reason (**WHY**) above the line-numbered YAML lines touched by the focused change with `+` / `−` signs. - **Esc / Resume pending state**: pressing `Esc` (`PauseReview`) returns to the editor while leaving the review pending—the main viewport renders pending change overlays (`drawPendingReviewOverlay`) and the right-rail **Agent** tab (`AgentPanelView`) shows `"Review waiting · N changes, F files"` with seen count, blockers, and **Resume review** (`ResumeReview`), which returns to the exact same focused change and seen state. - **Keep, Revert all, and one-step Undo**: **Revert all** asks in a focus-trapped confirmation dialog naming every file that goes back and reminding that `⌘Z` / `Ctrl+Z` brings everything back. Both **Keep** (`KeepTurnReview`) and **Revert all** (`ConfirmReviewRevertAll`) execute as **one `Editor.History` step**, update saved YAML files and the open scene, show a Spec toast with **Undo**, and record `"Kept K · reverted R · one undo step"` in the Agent panel; a single `Editor.Undo()` restores every touched file byte for byte. -- **MCP read access (`editormcp`)**: the read-only `review_status` tool (`ToolReviewStatus`, `ActionRead`) lets connected agents inspect which changes have been seen or reverted, active blockers, and keep/revert outcomes without granting the agent permission to keep or revert the turn (unsent draft notes are never exposed, and `SceneAndData` / `GoSource` privacy rules are enforced). +- **MCP read access (`editormcp`)**: the read-only `review_status` tool (`ToolReviewStatus`, `ActionRead`) lets connected agents inspect which changes have been seen or reverted, overlapping conflict choices (`mine`, `agent`, `both`), hand-edited YAML fields and lines tagged `"you"`, active blockers, and keep/revert outcomes (including after Keep for round 2) without granting the agent permission to keep or revert the turn (unsent draft notes are never exposed, and `SceneAndData` / `GoSource` privacy rules are enforced). ### Review notes and second-round redo (#1031) @@ -1479,6 +1479,15 @@ Instead of reverting everything or hand-editing YAML when one or two changes nee - **Send notes and noted-only redo (`SendReviewNotes`, `ApplyReviewRedo`, `editormcp`)**: clicking **Send N notes** in the header (which becomes the primary accent button while unsent notes exist) dispatches all remaining notes to the agent over MCP (`review_notes_get`), naming each change's `change_id`, `file`, `object`, `field`, `kind`, and `note`. The agent revises only noted changes within the same turn via `review_redo` (un-noted changes and tampered un-noted objects in the same file are refused, You-only/permission/privacy rules are enforced). Redone changes appear unseen again in Round 2+ with `"Redone from your note: …"` in **WHY** and `"Revised in round N. Your note: …"` on the card. - **Round tabs, banner, filters, paused card, and single-step Undo**: once Round 2 exists, the header shows **Round 1 | Round 2** tabs (`SetReviewViewRound`) and a banner below the filter chips (`"Round 2 · the agent redid only the N changes you left notes on. Both rounds keep and undo as one step."`). **Round 1** is read-only (`ErrReviewReadOnlyRound` on edit/revert/note attempts) and shows the agent's first version for comparison; **Keep** (`⌘↵`) always applies the **latest round** as **one `Editor.History` step**, so a single **Undo** (`⌘Z`) restores every touched file to its exact pre-request bytes. The **Notes** chip filters to changes with notes, the paused **Agent** panel card shows unsent note counts (`"N notes not sent"`), and the **Revert all** dialog warns that pending notes will be dropped. +### Review conflicts and in-place YAML hand editing (#1032) + +Inside the change-by-change Review screen, two cases block **Keep** cleanly without losing either the author's or the agent's work: + +- **Three-way conflict resolution (`syncReviewAfterMutate`, `SyncReviewPersonEdits`, `ResolveReviewConflict`)**: manual edits made through editor commands (`MoveObject`, `SetProperty`, `SetComponentField`, and so on) while a review turn is pending automatically three-way merge against the turn baseline and agent snapshot via `sceneformat.Merge`. Edits to **different fields** of the same object merge cleanly without asking; overlapping edits to the **same field or list** (such as appending to `door_1`'s `on_open` list) display both sides inside the change card with line authors (`you`, `agent`) and a **Mine / Agent's / Both** segmented control (`ReviewConflictMine`, `ReviewConflictAgent`, `ReviewConflictBoth`), where **Both** keeps both entries with **yours first**. Until every unresolved conflict is chosen, **Keep** is disabled (`*ReviewBlockedError` wrapping `ErrReviewBlocked`) with `"Choose how merges"`, and pressing **Keep** or the header blocker jumps straight to that change. +- **In-place YAML editing and live viewport preview (`BeginReviewYAMLEdit`, `SetReviewYAMLDraft`, `FinishReviewYAMLEdit`)**: clicking **Edit** on any non-reverted added or changed scene object makes the right-hand YAML pane editable in place without losing text-input focus or firing single-letter Review shortcuts while typing. Drafts are bounded (256 KiB), strictly decoded with `KnownFields(true)`, checked for duplicate keys and `sceneformat.Validate` (and component registry rules), and checked against You-only boundaries. Valid edits update the Review viewport live (`ReviewEffectiveSceneDoc`) and tag hand-edited lines `you`. +- **Parse errors, mechanical one-step fixes, and Undo my typing (`ApplyReviewYAMLFix`, `UndoReviewYAMLTyping`)**: invalid YAML (such as typing `x 444` without a colon) marks the failing scene line, surfaces `"Fix YAML on line N"` in the header blocker and `"Line N isn't valid YAML"` in the alert card, disables **Done** (`ErrReviewYAMLInvalid`) and **Keep**, offers verified one-step fixes when the parser names what is missing (**Add the colon**, **Close the quote**, **Add the closing brace**, **Add the closing bracket**, **Replace tabs with spaces**), and always provides **Undo my typing**. +- **Single undo step and round-2 MCP visibility**: conflict merge choices and valid hand edits land with the turn in **one `Editor.History` step** (`KeepTurnReview`)—one `Undo` reverts the agent turn, merge choice, and hand edit together while preserving any concurrent manual edits made outside the review—and remain readable through `editormcp`'s `review_status` tool (`Editor.ReviewStatus`) tagged `"you"` for round 2. + ## System notifications, Dock badge, and Play-mode dot for agent tasks (#1023) Agent tasks (both background tasks managed via `tasks.go` / #1022 and foreground Agent panel runs) reach the person outside the editor through NSGo's native notification and badge APIs (`core.Scope.ShowNotification`, `core.Scope.RequestNotificationPermission`, `core.Scope.OnNotificationPress`, and `core.Scope.SetBadge`), matching `docs/design/editor/Tasks.dc.html`, `docs/design/editor/AgentStates.dc.html`, and `docs/design/editor/Spec.dc.html` using exclusively Spec design tokens: diff --git a/docs/en/mcp.md b/docs/en/mcp.md index df1005c1e..b21166e53 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -297,7 +297,7 @@ claude mcp add game-editor -- nsgo game mcp | `game_check` | run | none | Runs the Problems panel's check (`assetcheck` with the editor's component registry, and `project.Check`, including open unsaved documents in the editor) and returns its visible problems, each with file, 1-based line, 1-based column (where known), and message. | | `problem_propose_fix` | read | `problem` (required), `explanation` (required), `edit` (required) | Validates a proposed fix for a live problem on a cloned scene, computes the exact `-`/`+` YAML diff, and shows the review card (with Apply fix, Show me, Ignore, and Ask about this problem…) in the editor's Agent panel. Never applies the fix or modifies any file — no MCP tool applies a fix. | | `history_list` | read | `author` (`all`, `you`, `agent`), `limit` (1–500, default 50) (both optional) | Reads the editor's unified History timeline of manual edits, agent turns, external Git reloads, and saved points (newest first), with author, summary, detail, touched files, timestamps, change/kept counts, unsaved status, and active preview ID. | -| `review_status` | read | none | Returns the active or most recent change-by-change agent turn review state: whether it is open or pending, the quoted request, round state, file summaries, every change's seen and reverted flags, active blockers, and the last keep/revert outcome. Unsent draft notes are never exposed, privacy policies are enforced, and keeping or reverting remains the person's decision. | +| `review_status` | read | none | Returns the active or most recent change-by-change agent turn review state: whether it is open or pending, the quoted request, round state, file summaries, every change's seen and reverted flags, overlapping edit conflicts and the person's merge choice (`mine`, `agent`, `both`), in-review YAML hand edits tagged `"you"` with edited fields and lines (preserved after Keep for round 2), active blockers (including YAML parse errors), and the last keep/revert outcome. Unsent draft notes are never exposed, privacy policies (`SceneAndData` and `GoSource`) are enforced, and keeping or reverting remains the person's decision. | | `review_notes_get` | read | none | Reads the active agent turn review's round state, changes, and the change-scoped notes explicitly sent by the author via **Send N notes** or **Revert and redo with this note** (`change_id`, `file`, `object`, `field`, `kind`, `note`, `revert_first`). Unsent draft notes and notes removed before sending are never returned. | | `review_redo` | edit | `changes` (required non-empty array of `{change_id, detail?, x?, y?, component?, fields?, file_content?, old_value?, new_value?, delta?, yaml_lines?}`) | Redoes only changes the author left notes on in the active review, advancing the same turn to Round 2+ while keeping earlier rounds intact and read-only. Un-noted changes (and any un-noted items in a supplied `file_content`) are refused atomically; redone changes become unseen again with `"Redone from your note: …"` as their Why, and **Keep** still applies the latest round as one undo step. | | `game_playtest` | run | `file`, `run`, `count`, `seeds`, `out`, `recordings` (all optional) | Validates `playtest.yaml`, runs the configured headless bot playtests with per-seed `.replay.yaml` recordings, writes the YAML report and returns each metric's value, goal status (`met` or `missed`) and heat-map position data. | diff --git a/docs/zh/editor.md b/docs/zh/editor.md index 682049572..c0d0fe100 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1469,7 +1469,7 @@ func main() { - **右侧面板(Why 与 YAML)**:在顶部显示智能体给出该改动的原因(**WHY**),下方展示带行号与 `+` / `−` 符号的精确 YAML 差异行。 - **按 `Esc` 挂起与恢复审核**:按 `Esc`(`PauseReview`)回到编辑器并保持审核挂起——主视口继续绘制待审核改动叠加层(`drawPendingReviewOverlay`),右侧 **Agent** 标签页(`AgentPanelView`)展示 `"Review waiting · N changes, F files"`、已读计数、阻塞数与 **Resume review** 按钮(`ResumeReview`),点击后精确回到离开时的聚焦改动与已读状态。 - **保留、全部撤回与单步撤销**:**Revert all** 弹出带焦点限制的确认对话框,列出将还原的文件并提示 `⌘Z` / `Ctrl+Z` 可全部恢复。**Keep**(`KeepTurnReview`)与 **Revert all**(`ConfirmReviewRevertAll`)均记录为 `Editor.History` 中的**单个步骤**,更新磁盘 YAML 文件与当前打开场景、弹出带 **Undo** 的规范 Toast,并在 Agent 面板显示 `"Kept K · reverted R · one undo step"`;执行一次 `Editor.Undo()` 即可按字节完整还原全部改动文件。 -- **MCP 只读接口(`editormcp`)**:新增只读工具 `review_status`(`ToolReviewStatus`、`ActionRead`),供智能体读取哪些改动已被查看或撤回、当前阻塞项以及保留/撤回结果,但保持保留与撤回决定权始终属于用户(绝不暴露未发送的草稿批注,并强制执行 `SceneAndData` / `GoSource` 隐私规则)。 +- **MCP 只读接口(`editormcp`)**:只读工具 `review_status`(`ToolReviewStatus`、`ActionRead`)供智能体读取每项改动的已读/撤回状态、冲突合并选择(`mine`、`agent`、`both`)、标注为 `"you"` 的就地手改 YAML 字段与代码行、当前阻塞项以及保留/撤回结果(保留后仍可在第二轮读取),但保留与撤回决定权始终属于开发者(绝不暴露未发送的草稿批注,并强制执行 `SceneAndData` / `GoSource` 隐私规则)。 ### 审核批注与第二轮局部重做(#1031) @@ -1479,6 +1479,15 @@ func main() { - **发送批注与仅重做批注项(`SendReviewNotes`、`ApplyReviewRedo`、`editormcp`)**:点击顶栏的 **Send N notes**(存在未发送批注时切换为主强调色按钮)会通过 MCP(`review_notes_get`)将所有未发送批注连同每项改动的 `change_id`、`file`、`object`、`field`、`kind` 与 `note` 发给智能体。智能体在同一回合内调用 `review_redo` 仅重做带有批注的改动(未加批注的改动以及同一文件中被夹带修改的未批注对象均会被原子拒绝,同时强制执行 You-only、权限规则与隐私边界);重做后的改动在 Round 2+ 中重新标为未读,并在 **WHY** 中显示 `"Redone from your note: …"`、在卡片下方显示 `"Revised in round N. Your note: …"`。 - **轮次标签页、横幅、过滤、挂起卡片与单步撤销**:进入 Round 2 后,顶栏展示 **Round 1 | Round 2** 切换标签(`SetReviewViewRound`),过滤标签下方展示轮次横幅(`"Round 2 · the agent redid only the N changes you left notes on. Both rounds keep and undo as one step."`)。**Round 1** 以只读方式保留智能体最初版本供对照(编辑、撤回或批注操作返回 `ErrReviewReadOnlyRound`);**Keep**(`⌘↵`)始终将**最新一轮**合并为 `Editor.History` 中的**单个步骤**,按一次 **Undo**(`⌘Z`)即可将全部受影响文件按字节还原至请求前状态。**Notes** 标签用于筛选带批注的改动,挂起时的 **Agent** 面板卡片会显示未发送批注数(`"N notes not sent"`),**Revert all** 对话框也会提示将丢弃未发送批注。 +### 审核冲突合并与就地手改 YAML(#1032) + +在逐项审核界面中,以下两种情况会清晰阻止 **Keep** 而不会丢失开发者或智能体任何一方的工作: + +- **三方冲突检测与合并(`syncReviewAfterMutate`、`SyncReviewPersonEdits`、`ResolveReviewConflict`)**:当审核回合挂起期间开发者通过编辑器命令(如 `MoveObject`、`SetProperty`、`SetComponentField` 等)手动编辑场景时,编辑器会自动通过 `sceneformat.Merge` 对基线、开发者修改与智能体提案做三方合并。对同一对象**不同字段**的修改会自动无感合并;对**同一字段或列表**的重叠修改(例如同时向 `door_1` 的 `on_open` 列表追加条目)会在改动卡片内展示双方行并标明作者(`you`、`agent`),提供 **Mine / Agent's / Both** 三选一控件(`ReviewConflictMine`、`ReviewConflictAgent`、`ReviewConflictBoth`),其中 **Both** 会保留双方条目且**你的条目在前**。在所有冲突未作出选择前,**Keep** 处于禁用状态(返回包装 `ErrReviewBlocked` 的 `*ReviewBlockedError`)并在顶栏提示 `"Choose how <对象> merges"`,点击 **Keep** 或顶栏阻塞胶囊会直接跳转到该冲突卡片。 +- **右侧 YAML 面板就地编辑与视口实时更新(`BeginReviewYAMLEdit`、`SetReviewYAMLDraft`、`FinishReviewYAMLEdit`)**:对任意未撤回的新增或修改场景对象点击 **Edit** 即可在右侧面板就地编辑 YAML,输入过程中保持输入框焦点稳定且绝不误触单字母审核快捷键。草稿受大小上限(256 KiB)保护,严格使用 `KnownFields(true)` 解码并拒绝未知字段、重复键与仅限用户文件,同时通过 `sceneformat.Validate` 与组件注册表校验。合法修改会实时刷新审核视口(`ReviewEffectiveSceneDoc`)并将手改行标为 `you`。 +- **YAML 解析错误、一键修复与撤销输入(`ApplyReviewYAMLFix`、`UndoReviewYAMLTyping`)**:输入无效 YAML(例如漏写冒号 `x 444`)会高亮标记出错的场景行,在顶栏显示 `"Fix YAML on line N"`、在告警卡片显示 `"Line N isn't valid YAML"`,禁用 **Done**(返回 `ErrReviewYAMLInvalid`)与 **Keep**,在解析器明确指出缺失项时提供经过校验的一键修复按钮(**Add the colon**、**Close the quote**、**Add the closing brace**、**Add the closing bracket**、**Replace tabs with spaces**),并始终提供 **Undo my typing** 回退本次输入。 +- **单步撤销与第二轮 MCP 可见性**:冲突合并选择与合法手改 YAML 都属于该回合的一部分——点击 **Keep**(`KeepTurnReview`)时合并为 `Editor.History` 中的**单个撤销步骤**,按一次 `Undo` 即可整体撤销智能体改动、合并选择与手改内容(同时保留开发者在审核外的手动编辑),并通过 `editormcp` 的 `review_status` 工具(`Editor.ReviewStatus`)以 `"you"` 标签供智能体在第二轮读取。 + ## 智能体任务的系统通知、Dock 角标与播放模式提示点(#1023) 编辑器通过 NSGo 原生通知与角标 API(`core.Scope.ShowNotification`、`core.Scope.RequestNotificationPermission`、`core.Scope.OnNotificationPress` 与 `core.Scope.SetBadge`)为后台任务(`tasks.go` / #1022)与智能体面板回合提供编辑器外提醒,界面严格遵循 `docs/design/editor/Tasks.dc.html`、`docs/design/editor/AgentStates.dc.html` 与 `docs/design/editor/Spec.dc.html` 令牌规范: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 71f737b67..3b5525c44 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -297,7 +297,7 @@ claude mcp add game-editor -- nsgo game mcp | `game_check` | run | 无 | 运行问题面板的检查(使用编辑器组件注册表的 `assetcheck`,以及 `project.Check`,并包含编辑器中打开且未保存的文档),返回其中的可见问题,每条带文件、从 1 开始的行号、列号(可定位时)和消息。 | | `problem_propose_fix` | read | `problem`(必填)、`explanation`(必填)、`edit`(必填) | 在克隆场景上校验针对实时问题的修复建议,计算精确的 `-`/`+` YAML 差异,并在编辑器的 Agent 面板展示审查卡片(含应用修复、定位查看、忽略与提问)。绝不自动应用修复或修改任何文件——没有任何 MCP 工具会直接应用修复。 | | `history_list` | read | `author`(`all`、`you`、`agent`)、`limit`(1–500,默认 50)(均可选) | 读取编辑器统一的 History 时间线(按最新优先排列),包含手动编辑、智能体回合、外部 Git 重载与保存点的作者、摘要、详情、涉及文件、时间戳、变更/保留计数、未保存状态以及当前预览条目 ID。 | -| `review_status` | read | 无 | 返回当前或最近一次逐项智能体回合审核的状态:是否打开或挂起、用户请求文本、轮次状态、按文件统计摘要、每项改动的已读与撤回标记、当前阻塞项以及最近一次保留/撤回结果。绝不暴露未发送草稿批注,强制执行隐私策略,且保留或撤回始终由开发者决定。 | +| `review_status` | read | 无 | 返回当前或最近一次逐项智能体回合审核的状态:是否打开或挂起、用户请求文本、轮次状态、按文件统计摘要、每项改动的已读与撤回标记、与开发者手动编辑重叠的冲突及合并选择(`mine`、`agent`、`both`)、审核中就地手改并标注为 `"you"` 的 YAML 字段与代码行(保留后仍供第二轮读取)、当前阻塞项(包含 YAML 解析错误)以及最近一次保留/撤回结果。绝不暴露未发送草稿批注,强制遵守 `SceneAndData` 与 `GoSource` 隐私策略,且保留或撤回始终由开发者决定。 | | `review_notes_get` | read | 无 | 读取当前智能体回合审核的轮次状态、改动列表以及作者通过 **Send N notes** 或 **Revert and redo with this note** 显式发送的批注(含 `change_id`、`file`、`object`、`field`、`kind`、`note`、`revert_first`)。未发送草稿与发送前移除的批注绝不返回。 | | `review_redo` | edit | `changes`(必填非空数组,每项含 `change_id` 及可选 `detail`、`x`、`y`、`component`、`fields`、`file_content`、`old_value`、`new_value`、`delta`、`yaml_lines`) | 仅重做当前审核中作者留有批注的改动,在同一回合内推进至 Round 2+ 并以只读方式保留先前轮次。未加批注的改动(以及 `file_content` 中夹带的未批注项)会被原子拒绝;重做项重新标为未读且 Why 更新为 `"Redone from your note: …"`,**Keep** 仍将最新一轮作为单个撤销步骤应用。 | | `game_playtest` | run | `file`、`run`、`count`、`seeds`、`out`、`recordings`(均可选) | 校验 `playtest.yaml`,无头运行配置好的机器人试玩并按种子录制 `.replay.yaml` 回放,写出 YAML 报告并返回每项指标的值、目标状态(`met` 或 `missed`)以及热力图坐标数据。 | diff --git a/packages/game/editor/editorcmd/review_conflicts_screenshot_test.go b/packages/game/editor/editorcmd/review_conflicts_screenshot_test.go new file mode 100644 index 000000000..db99e5f53 --- /dev/null +++ b/packages/game/editor/editorcmd/review_conflicts_screenshot_test.go @@ -0,0 +1,222 @@ +package editorcmd_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const macosReviewBaseScene = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: plank + x: 336 + y: 226 + - id: knight + name: Knight + x: 352 + y: 192 + z: 10 + - id: door_1 + name: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true + - id: crate_04 + x: 504 + y: 270 +` + +const macosReviewAgentScene = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: plank + x: 336 + y: 226 + - id: knight + name: Knight + x: 352 + y: 192 + z: 12 + - id: door_1 + name: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true + - reveal: coin_trail + - id: slime_01 + prefab: prefabs/slime.prefab.yaml + x: 160 + y: 278 + - id: slime_02 + prefab: prefabs/slime.prefab.yaml + x: 232 + y: 278 + - id: slime_03 + prefab: prefabs/slime.prefab.yaml + x: 452 + y: 208 + - id: coin_01 + prefab: prefabs/coin.prefab.yaml + x: 486 + y: 280 + - id: coin_02 + prefab: prefabs/coin.prefab.yaml + x: 512 + y: 270 + - id: coin_03 + prefab: prefabs/coin.prefab.yaml + x: 538 + y: 280 +` + +// TestReviewConflictsAndYAMLEditMacOSScreenshots renders the Review screen on the real native +// macOS host and captures screenshots of: +// 1. Unresolved conflict on door_1 ("Choose how door_1 merges", Mine/Agent's/Both, disabled Keep) +// 2. Resolved conflict ("Merged both, yours first") +// 3. In-place YAML parse error ("Line N isn't valid YAML", "Add the colon", "Undo my typing") +// 4. Fixed YAML hand edit tagged "you" with live viewport update +// 5. Spec Light appearance parity +func TestReviewConflictsAndYAMLEditMacOSScreenshots(t *testing.T) { + dir := t.TempDir() + for rel, content := range map[string]string{ + "game.yaml": `version: 1 +name: review-conflicts +id: dev.nsgo.review-conflicts +appVersion: 1.0.0 +window: + width: 640 + height: 360 +autoload: + mainScene: level_01 + scenes: + - name: level_01 + path: scenes/level_01.scene.yaml +`, + "scenes/level_01.scene.yaml": macosReviewBaseScene, + "prefabs/slime.prefab.yaml": "version: 1\nid: slime\nname: Slime\n", + "prefabs/coin.prefab.yaml": "version: 1\nid: coin\nname: Coin\n", + } { + full := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + ed.WaitForProblems() + ed.SetAppearance(editor.AppearanceDark) + + if err := ed.StartTurnReview(editor.ReviewTurnInput{ + Request: "Put slime patrols on the lower floors of level_01, with a coin trail toward door_1.", + Files: []editor.ReviewFileInput{ + { + Path: "scenes/level_01.scene.yaml", + BeforeYAML: []byte(macosReviewBaseScene), + AfterYAML: []byte(macosReviewAgentScene), + Reasons: map[string]string{ + "slime_01": "Two slimes share the 120 px floor span, half a cycle apart, so there is always a gap to pass.", + "slime_02": "Two slimes share the 120 px floor span, half a cycle apart, so there is always a gap to pass.", + "slime_03": "The plank is the only other floor wide enough for a patrol; this slime guards the coin trail from above.", + "knight": "Slimes are drawn at z 11; without this the Knight disappears behind slime_03 on the plank.", + "door_1": "The trail stays hidden until the door opens, so it reads as a reward rather than a hint.", + "crate_04": "The crate blocked the second coin; nothing else references it.", + }, + }, + }, + }); err != nil { + t.Fatalf("StartTurnReview: %v", err) + } + + // Person edits door_1's on_open list concurrently. + if err := ed.SetProperty("door_1", "on_open", []any{ + map[string]any{"open": true}, + map[string]any{"sound": "sfx/door_creak.ogg"}, + }); err != nil { + t.Fatal(err) + } + if !ed.FocusReviewChange("door_1") { + t.Fatal("FocusReviewChange(door_1) failed") + } + + var doorID, slimeID string + for _, ch := range ed.ReviewStatus().Changes { + switch ch.ObjectID { + case "door_1": + doorID = ch.ID + case "slime_03": + slimeID = ch.ID + } + } + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900)) + + app.Settle() + app.Screenshot("review-conflict-unresolved") + + // Pick Both on door_1. + app.Press("id:review-conflict-both-door_1") + app.Settle() + app.Screenshot("review-conflict-both-resolved") + + // Focus slime_03, start editing YAML, type invalid "x 444" without colon. + app.Press("id:review-card-focus-" + slimeID) + app.Press("id:review-yaml-edit") + app.Settle() + app.Post(func() { + for _, ch := range ed.ReviewStatus().Changes { + if ch.ObjectID == "slime_03" { + broken := strings.Replace(ch.HandEditYAML, "x: 452", "x 444", 1) + _ = ed.SetReviewYAMLDraft("slime_03", broken) + } + } + }) + app.Settle() + app.Screenshot("review-yaml-error") + + // Apply "Add the colon" one-step fix. + app.Press("id:review-yaml-fix") + app.Settle() + app.Screenshot("review-yaml-fixed-you") + + // Capture Spec Light parity with conflict card visible. + app.Press("id:review-yaml-done") + app.Press("id:review-card-focus-" + doorID) + app.Post(func() { + ed.SetAppearance(editor.AppearanceLight) + }) + app.Settle() + app.Screenshot("review-conflict-light") +} diff --git a/packages/game/editor/editormcp/review.go b/packages/game/editor/editormcp/review.go index 1f7daaa2c..5bcbac25c 100644 --- a/packages/game/editor/editormcp/review.go +++ b/packages/game/editor/editormcp/review.go @@ -13,7 +13,7 @@ import ( ) const ( - // ToolReviewStatus reads the active or most recent agent turn review's seen and reverted change state. + // ToolReviewStatus reads the active or most recent agent turn review's seen, reverted, conflict, and hand-edited YAML state. ToolReviewStatus = "review_status" // ToolReviewNotesGet reads the active review's round state, changes, and sent notes waiting for the agent. ToolReviewNotesGet = "review_notes_get" @@ -26,6 +26,8 @@ const ( maxReviewStatusTextChanges = 200 // maxReviewStatusYAMLLines caps YAML diff lines per change in the MCP structured snapshot. maxReviewStatusYAMLLines = 60 + // maxReviewStatusYAMLBytes caps HandEditYAML per change in the MCP structured snapshot. + maxReviewStatusYAMLBytes = 16 << 10 // maxReviewRedoItems caps how many change entries one review_redo call may submit. maxReviewRedoItems = 256 ) @@ -85,7 +87,7 @@ func reviewTools() []Tool { { Name: ToolReviewStatus, Title: "Read agent turn review status", - Description: "Return the current agent turn review state: whether it is open or pending, the request, round state, file summaries, every change's seen and reverted flags, active blockers, and the last keep/revert outcome. Unsent draft notes are never exposed. Read-only: keeping or reverting remains the person's decision.", + Description: "Return the current or most recent agent turn review state: whether it is open or pending, the request, round state, file summaries, every change's seen and reverted flags, overlapping edit conflicts and the person's merge choice (mine, agent, both), in-review YAML hand edits tagged \"you\" with edited fields and lines, active blockers (including YAML parse errors), and the last keep/revert outcome. Unsent draft notes are never exposed, and privacy policies are enforced. Read-only: keeping or reverting remains the person's decision.", InputSchema: []byte(reviewStatusSchema), Action: ActionRead, Handler: reviewStatus, @@ -164,11 +166,14 @@ func reviewStatus(ctx context.Context, c *Call) (*Result, error) { return nil, err } - // Never leak unsent draft notes over MCP; also redact diff lines for files blocked by privacy (e.g. GoSource off). + // Never leak unsent draft notes over MCP; also redact diff/hand-edit lines for files blocked by privacy (e.g. GoSource off). for i := range snap.Changes { snap.Changes[i].Note = "" if checkPathPrivacy(policy, root, snap.Changes[i].File) != nil { snap.Changes[i].YAMLLines = nil + snap.Changes[i].HandEditLines = nil + snap.Changes[i].HandEditYAML = "" + snap.Changes[i].Conflicts = nil for j := range snap.Changes[i].Versions { snap.Changes[i].Versions[j].YAMLLines = nil } @@ -182,6 +187,50 @@ func reviewStatus(ctx context.Context, c *Call) (*Result, error) { snap.Changes[i].Versions[j].YAMLLines = snap.Changes[i].Versions[j].YAMLLines[:maxReviewStatusYAMLLines] } } + if len(snap.Changes[i].HandEditLines) > maxReviewStatusYAMLLines { + snap.Changes[i].HandEditLines = snap.Changes[i].HandEditLines[:maxReviewStatusYAMLLines] + } + if len(snap.Changes[i].HandEditYAML) > maxReviewStatusYAMLBytes { + snap.Changes[i].HandEditYAML = snap.Changes[i].HandEditYAML[:maxReviewStatusYAMLBytes] + } + } + + writeChangeSummary := func(b *strings.Builder, changes []editor.ReviewChange) { + limit := min(len(changes), maxReviewStatusTextChanges) + for _, ch := range changes[:limit] { + seenTag := "unseen" + if ch.Seen { + seenTag = "seen" + } + revTag := "kept" + if ch.Reverted { + revTag = "reverted" + } + fmt.Fprintf(b, "\n- [%s] %s (%s) %s · %s, %s", ch.Kind, ch.Title, ch.File, ch.Detail, seenTag, revTag) + if len(ch.Conflicts) > 0 { + choice := string(ch.ConflictChoice) + if choice == "" { + choice = "unresolved" + } + fmt.Fprintf(b, ", conflict=%s", choice) + } + if ch.HandEdited { + by := ch.HandEditBy + if by == "" { + by = editor.ReviewAuthorYou + } + fmt.Fprintf(b, ", hand-edited by %s", by) + if len(ch.HandEditFields) > 0 { + fmt.Fprintf(b, " [%s]", strings.Join(ch.HandEditFields, ", ")) + } + } + if ch.YAMLError != nil { + fmt.Fprintf(b, ", yaml error on line %d", ch.YAMLError.Line) + } + } + if len(changes) > limit { + fmt.Fprintf(b, "\n... and %d more changes", len(changes)-limit) + } } var b strings.Builder @@ -205,22 +254,11 @@ func reviewStatus(ctx context.Context, c *Call) (*Result, error) { fmt.Fprintf(&b, "\n - %s: %s", bl.ChangeID, bl.Reason) } } - limit := min(len(snap.Changes), maxReviewStatusTextChanges) - for _, ch := range snap.Changes[:limit] { - seenTag := "unseen" - if ch.Seen { - seenTag = "seen" - } - revTag := "kept" - if ch.Reverted { - revTag = "reverted" - } - fmt.Fprintf(&b, "\n- [%s] %s (%s) %s · %s, %s", ch.Kind, ch.Title, ch.File, ch.Detail, seenTag, revTag) - } - if len(snap.Changes) > limit { - fmt.Fprintf(&b, "\n... and %d more changes", len(snap.Changes)-limit) - } - case editor.ReviewOutcomeKept, editor.ReviewOutcomeReverted: + writeChangeSummary(&b, snap.Changes) + case editor.ReviewOutcomeKept: + fmt.Fprintf(&b, "Review %s: %s", snap.Outcome, snap.LastOutcomeMsg) + writeChangeSummary(&b, snap.Changes) + case editor.ReviewOutcomeReverted: fmt.Fprintf(&b, "Review %s: %s", snap.Outcome, snap.LastOutcomeMsg) default: b.WriteString("No agent turn review is active.") diff --git a/packages/game/editor/editormcp/review_test.go b/packages/game/editor/editormcp/review_test.go index 06fef3207..eb09f1992 100644 --- a/packages/game/editor/editormcp/review_test.go +++ b/packages/game/editor/editormcp/review_test.go @@ -1,6 +1,8 @@ package editormcp_test import ( + "os" + "path/filepath" "strings" "testing" @@ -119,3 +121,244 @@ layers: t.Fatalf("paused snap = %+v", snap) } } + +// #1032 Acceptance 2: type invalid YAML in the review pane, check that Keep and Done are refused, +// apply the offered fix, and find the hand edit tagged as the person's ("you") in the turn read through MCP. +func TestReviewStatusExposesHandEditTaggedYouAndConflictChoice(t *testing.T) { + f := openFixture(t) + + baseYAML := `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true +` + agentYAML := `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true + - reveal: coin_trail + - id: slime_03 + prefab: prefabs/slime.prefab.yaml + x: 452 + y: 208 +` + for rel, content := range map[string]string{ + "scenes/level_01.scene.yaml": baseYAML, + "prefabs/slime.prefab.yaml": "version: 1\nid: slime\nname: Slime\n", + } { + full := filepath.Join(f.dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + if err := f.ed.OpenScene("scenes/level_01.scene.yaml"); err != nil { + t.Fatalf("OpenScene: %v", err) + } + + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + if err := f.ed.StartTurnReview(editor.ReviewTurnInput{ + Request: "Add slime_03 and reveal coin_trail on door_1", + Files: []editor.ReviewFileInput{ + { + Path: "scenes/level_01.scene.yaml", + BeforeYAML: []byte(baseYAML), + AfterYAML: []byte(agentYAML), + }, + }, + }); err != nil { + t.Fatalf("StartTurnReview: %v", err) + } + + // Person also edits door_1's on_open list concurrently. + if err := f.ed.SetProperty("door_1", "on_open", []any{ + map[string]any{"open": true}, + map[string]any{"sound": "sfx/door_creak.ogg"}, + }); err != nil { + t.Fatal(err) + } + + // Person starts editing slime_03's YAML and types invalid YAML ("x 444"). + if err := f.ed.BeginReviewYAMLEdit("slime_03"); err != nil { + t.Fatal(err) + } + var slimeYAML string + for _, ch := range f.ed.ReviewStatus().Changes { + if ch.ObjectID == "slime_03" { + slimeYAML = ch.HandEditYAML + } + } + broken := strings.Replace(slimeYAML, "x: 452", "x 444", 1) + if err := f.ed.SetReviewYAMLDraft("slime_03", broken); err == nil { + t.Fatal("expected invalid YAML parse error") + } + + // Keep and Done are refused while invalid. + if err := f.ed.KeepTurnReview(); err == nil { + t.Fatal("expected KeepTurnReview refused while YAML is broken") + } + if err := f.ed.FinishReviewYAMLEdit("slime_03"); err == nil { + t.Fatal("expected FinishReviewYAMLEdit (Done) refused while YAML is broken") + } + + // MCP reports the active YAML error blocker. + res := call(t, cs, editormcp.ToolReviewStatus, map[string]any{}) + mustOK(t, res) + var snap editor.ReviewSnapshot + structured(t, res, &snap) + if len(snap.Blockers) == 0 || snap.Blockers[0].Kind != "yaml_error" { + t.Fatalf("expected yaml_error blocker in MCP review_status, got %+v", snap.Blockers) + } + + // Apply the offered fix ("Add the colon"), finish YAML edit, and resolve door_1 conflict with Both. + if err := f.ed.ApplyReviewYAMLFix("slime_03"); err != nil { + t.Fatalf("ApplyReviewYAMLFix: %v", err) + } + if err := f.ed.FinishReviewYAMLEdit("slime_03"); err != nil { + t.Fatalf("FinishReviewYAMLEdit: %v", err) + } + if err := f.ed.ResolveReviewConflict("door_1", editor.ReviewConflictBoth); err != nil { + t.Fatalf("ResolveReviewConflict: %v", err) + } + + // Read the turn through MCP: slime_03 hand edit is tagged "you", door_1 conflict choice is "both". + res = call(t, cs, editormcp.ToolReviewStatus, map[string]any{}) + out := mustOK(t, res) + snap = editor.ReviewSnapshot{} + structured(t, res, &snap) + if len(snap.Blockers) != 0 { + t.Fatalf("expected no blockers after fix and conflict resolution, got %+v", snap.Blockers) + } + if !strings.Contains(out, "hand-edited by you") { + t.Fatalf("expected MCP text to mention hand-edited by you:\n%s", out) + } + + var gotSlime, gotDoor *editor.ReviewChange + for i := range snap.Changes { + switch snap.Changes[i].ObjectID { + case "slime_03": + gotSlime = &snap.Changes[i] + case "door_1": + gotDoor = &snap.Changes[i] + } + } + if gotSlime == nil || !gotSlime.HandEdited || gotSlime.HandEditBy != editor.ReviewAuthorYou || gotSlime.Author != editor.ReviewAuthorYou { + t.Fatalf("slime_03 MCP report missing 'you' tag: %+v", gotSlime) + } + foundXLine := false + for _, ln := range gotSlime.HandEditLines { + if strings.Contains(ln.Text, "x: 444") && ln.Author == editor.ReviewAuthorYou { + foundXLine = true + } + } + if !foundXLine { + t.Fatalf("expected x: 444 tagged 'you' in HandEditLines: %+v", gotSlime.HandEditLines) + } + if gotDoor == nil || gotDoor.ConflictChoice != editor.ReviewConflictBoth { + t.Fatalf("door_1 MCP report = %+v, want conflictChoice=both", gotDoor) + } + + // After Keep, the agent can still read the kept turn's hand edit and merge choice in round 2. + if err := f.ed.KeepTurnReview(); err != nil { + t.Fatalf("KeepTurnReview: %v", err) + } + res = call(t, cs, editormcp.ToolReviewStatus, map[string]any{}) + out = mustOK(t, res) + snap = editor.ReviewSnapshot{} + structured(t, res, &snap) + if snap.Outcome != editor.ReviewOutcomeKept { + t.Fatalf("outcome = %q, want kept", snap.Outcome) + } + if !strings.Contains(out, "hand-edited by you") || !strings.Contains(out, "conflict=both") { + t.Fatalf("expected kept review_status text to retain hand-edit & conflict choice for round 2:\n%s", out) + } + keptSlime := (*editor.ReviewChange)(nil) + for i := range snap.Changes { + if snap.Changes[i].ObjectID == "slime_03" { + keptSlime = &snap.Changes[i] + } + } + if keptSlime == nil || keptSlime.HandEditBy != editor.ReviewAuthorYou { + t.Fatalf("expected hand edit tagged 'you' to persist in kept turn for round 2: %+v", snap.Changes) + } +} + +func TestReviewStatusRespectsPrivacySwitches(t *testing.T) { + f := openFixture(t) + s := editormcp.New(f.ed, editormcp.Options{}) + t.Cleanup(func() { _ = s.Close() }) + cs := connect(t, s, nil) + + if err := f.ed.StartTurnReview(editor.ReviewTurnInput{ + Request: "Add helper in game.go", + Files: []editor.ReviewFileInput{ + { + Path: "game.go", + BeforeYAML: []byte("package main\n"), + AfterYAML: []byte("package main\nfunc helper() {}\n"), + }, + }, + }); err != nil { + t.Fatalf("StartTurnReview: %v", err) + } + + // Turning off Go source privacy must redact .go diff/hand-edit lines from review_status without leaking source code. + if err := f.ed.SetAgentPrivacy(editor.PrivacyGoSource, false); err != nil { + t.Fatal(err) + } + res := call(t, cs, editormcp.ToolReviewStatus, nil) + mustOK(t, res) + var goSnap editor.ReviewSnapshot + structured(t, res, &goSnap) + for _, ch := range goSnap.Changes { + if ch.File == "game.go" { + if len(ch.YAMLLines) > 0 || len(ch.HandEditLines) > 0 || ch.HandEditYAML != "" || len(ch.Conflicts) > 0 { + t.Fatalf("expected .go lines redacted when PrivacyGoSource is off, got: %+v", ch) + } + for _, v := range ch.Versions { + if len(v.YAMLLines) > 0 { + t.Fatalf("expected .go version lines redacted when PrivacyGoSource is off, got: %+v", v) + } + } + } + } + + // Re-enabling Go source but turning off Scene & Data privacy must refuse review_status. + if err := f.ed.SetAgentPrivacy(editor.PrivacyGoSource, true); err != nil { + t.Fatal(err) + } + if err := f.ed.SetAgentPrivacy(editor.PrivacySceneAndData, false); err != nil { + t.Fatal(err) + } + res = call(t, cs, editormcp.ToolReviewStatus, nil) + if !res.IsError { + t.Fatalf("expected review_status refused when PrivacySceneAndData is off, got OK: %+v", res) + } +} diff --git a/packages/game/editor/review.go b/packages/game/editor/review.go index 9ee3643b5..ad77caab7 100644 --- a/packages/game/editor/review.go +++ b/packages/game/editor/review.go @@ -32,6 +32,8 @@ const ( maxReviewRounds = 20 // maxReviewRedoYAMLLines bounds custom YAML diff lines provided on one review_redo item. maxReviewRedoYAMLLines = 2000 + // maxReviewYAMLEditBytes bounds an in-place YAML edit draft in the Review right pane (256 KiB). + maxReviewYAMLEditBytes = 256 << 10 ) var ( @@ -57,8 +59,21 @@ var ( ErrReviewMaxRounds = errors.New("editor: review reached maximum number of rounds") // ErrReviewInvalidRound is returned when selecting an out-of-range review round. ErrReviewInvalidRound = errors.New("editor: invalid review round") + // ErrReviewYAMLInvalid is returned by FinishReviewYAMLEdit when the hand-edited YAML does not parse or validate. + ErrReviewYAMLInvalid = errors.New("editor: review YAML is invalid") ) +// ReviewBlockedError describes why KeepTurnReview refused to land the turn. +type ReviewBlockedError struct { + Blocker ReviewBlocker +} + +func (e *ReviewBlockedError) Error() string { + return "editor: review has an unresolved blocker: " + e.Blocker.Reason +} + +func (e *ReviewBlockedError) Unwrap() error { return ErrReviewBlocked } + // ReviewFileKind classifies the kind of file touched by an agent turn. type ReviewFileKind string @@ -112,11 +127,12 @@ const ( // ReviewYAMLLine is one line in the right-hand YAML/code diff view. type ReviewYAMLLine struct { - Line int `json:"line"` - Sign string `json:"sign,omitempty"` // "", "+", "-" - Text string `json:"text"` - Tag string `json:"tag,omitempty"` - Error bool `json:"error,omitempty"` + Line int `json:"line"` + Sign string `json:"sign,omitempty"` // "", "+", "-" + Text string `json:"text"` + Tag string `json:"tag,omitempty"` + Author ReviewLineAuthor `json:"author,omitempty"` + Error bool `json:"error,omitempty"` } // ReviewDataCellDiff describes a changed cell in a data table row. @@ -150,7 +166,10 @@ type ReviewDataTablePreview struct { // ReviewBlocker describes an active blocker preventing Keep until resolved. type ReviewBlocker struct { + Kind string `json:"kind,omitempty"` // "yaml_error", "conflict", or "custom" ChangeID string `json:"changeId"` + ObjectID string `json:"objectId,omitempty"` + Line int `json:"line,omitempty"` Reason string `json:"reason"` } @@ -175,42 +194,62 @@ type ReviewChangeVersion struct { // ReviewChange is one reviewable change inside an agent turn. type ReviewChange struct { - ID string `json:"id"` - File string `json:"file"` - FileKind ReviewFileKind `json:"fileKind"` - Kind ReviewChangeKind `json:"kind"` - Title string `json:"title"` - Detail string `json:"detail"` - Why string `json:"why"` - ObjectID string `json:"objectId,omitempty"` - Layer string `json:"layer,omitempty"` - ParentID string `json:"parentId,omitempty"` - Field string `json:"field,omitempty"` - OldValue string `json:"oldValue,omitempty"` - NewValue string `json:"newValue,omitempty"` - DeltaPct string `json:"deltaPct,omitempty"` - PrefabImpact string `json:"prefabImpact,omitempty"` - RowID string `json:"rowId,omitempty"` - Line int `json:"line,omitempty"` - YAMLLines []ReviewYAMLLine `json:"yamlLines,omitempty"` - Seen bool `json:"seen"` - Reverted bool `json:"reverted"` - Note string `json:"note,omitempty"` - SentNote string `json:"sentNote,omitempty"` - RedoneInRound int `json:"redoneInRound,omitempty"` - RedoneNote string `json:"redoneNote,omitempty"` - Versions []ReviewChangeVersion `json:"versions,omitempty"` - Blocker string `json:"blocker,omitempty"` - GoRequiresConfirm bool `json:"goRequiresConfirm,omitempty"` - GoConfirmed bool `json:"goConfirmed,omitempty"` - beforeObj *sceneformat.ObjectDoc `json:"-"` - afterObj *sceneformat.ObjectDoc `json:"-"` - beforeLayer string `json:"-"` - afterLayer string `json:"-"` - beforeParentID string `json:"-"` - beforeYAMLNode *yaml.Node `json:"-"` - afterYAMLNode *yaml.Node `json:"-"` - cellDiffs []ReviewDataCellDiff `json:"-"` + ID string `json:"id"` + File string `json:"file"` + FileKind ReviewFileKind `json:"fileKind"` + Kind ReviewChangeKind `json:"kind"` + Title string `json:"title"` + Detail string `json:"detail"` + Why string `json:"why"` + ObjectID string `json:"objectId,omitempty"` + Layer string `json:"layer,omitempty"` + ParentID string `json:"parentId,omitempty"` + Field string `json:"field,omitempty"` + OldValue string `json:"oldValue,omitempty"` + NewValue string `json:"newValue,omitempty"` + DeltaPct string `json:"deltaPct,omitempty"` + PrefabImpact string `json:"prefabImpact,omitempty"` + RowID string `json:"rowId,omitempty"` + Line int `json:"line,omitempty"` + YAMLLines []ReviewYAMLLine `json:"yamlLines,omitempty"` + Seen bool `json:"seen"` + Reverted bool `json:"reverted"` + Note string `json:"note,omitempty"` + SentNote string `json:"sentNote,omitempty"` + RedoneInRound int `json:"redoneInRound,omitempty"` + RedoneNote string `json:"redoneNote,omitempty"` + Versions []ReviewChangeVersion `json:"versions,omitempty"` + Blocker string `json:"blocker,omitempty"` + GoRequiresConfirm bool `json:"goRequiresConfirm,omitempty"` + GoConfirmed bool `json:"goConfirmed,omitempty"` + Author ReviewLineAuthor `json:"author,omitempty"` + Conflicts []ReviewConflict `json:"conflicts,omitempty"` + ConflictChoice ReviewConflictChoice `json:"conflictChoice,omitempty"` + AutoMergedFields []string `json:"autoMergedFields,omitempty"` + EditingYAML bool `json:"editingYaml,omitempty"` + HandEdited bool `json:"handEdited,omitempty"` + HandEditBy ReviewLineAuthor `json:"handEditBy,omitempty"` + HandEditFields []string `json:"handEditFields,omitempty"` + HandEditLines []ReviewYAMLLine `json:"handEditLines,omitempty"` + HandEditYAML string `json:"handEditYaml,omitempty"` + YAMLError *ReviewYAMLError `json:"yamlError,omitempty"` + beforeObj *sceneformat.ObjectDoc `json:"-"` + afterObj *sceneformat.ObjectDoc `json:"-"` + personObj *sceneformat.ObjectDoc `json:"-"` + beforeLayer string `json:"-"` + afterLayer string `json:"-"` + beforeParentID string `json:"-"` + beforeYAMLNode *yaml.Node `json:"-"` + afterYAMLNode *yaml.Node `json:"-"` + cellDiffs []ReviewDataCellDiff `json:"-"` + handEditPreYAML string `json:"-"` + handEditObj *sceneformat.ObjectDoc `json:"-"` + handEditBaseObj *sceneformat.ObjectDoc `json:"-"` + handEditLineNums []int `json:"-"` + hadHandEditBeforeSession bool `json:"-"` + preSessionHandObj *sceneformat.ObjectDoc `json:"-"` + preSessionHandFields []string `json:"-"` + preSessionHandLineNums []int `json:"-"` } // ReviewFileSummary summarizes one file group in the review. @@ -278,6 +317,8 @@ type ReviewFileInput struct { BeforeYAML []byte // AfterYAML is the exact file content after the agent turn (empty/nil when deleted). AfterYAML []byte + // PersonYAML optionally supplies concurrent manual edits made by the person to this file. + PersonYAML []byte // ExistedBefore explicitly records whether the file existed on disk before the turn. // When nil, it defaults to len(BeforeYAML) > 0. ExistedBefore *bool @@ -351,6 +392,8 @@ type reviewFileState struct { afterYAML []byte beforeDoc *sceneformat.SceneDoc afterDoc *sceneformat.SceneDoc + personDoc *sceneformat.SceneDoc + personEdited bool beforeBuilt *sceneformat.BuiltScene currentBuilt *sceneformat.BuiltScene builtDirty bool @@ -364,38 +407,42 @@ type reviewFileState struct { } type turnReviewState struct { - open bool - outcome ReviewOutcome - request string - defaultWhy string - round int - viewRound int - composingID string - noteDraft string - pendingBatch *ReviewNoteBatch - roundRedone map[int]int - files []*reviewFileState - filesByPath map[string]*reviewFileState - changes []*ReviewChange - changesByID map[string]*ReviewChange - focusedID string - focusedRowKey string - filter ReviewFilter - search string - collapsedFiles map[string]bool - collapsedKinds map[string]bool - peekBefore bool - revertConfirm bool - legend ReviewOverlayVisibility - activeRegion string - lastKept int - lastReverted int - lastTotal int - lastFileCount int - lastRounds int - lastRequest string - lastOutcomeMsg string - uiRev uint64 + open bool + outcome ReviewOutcome + request string + defaultWhy string + round int + viewRound int + composingID string + noteDraft string + pendingBatch *ReviewNoteBatch + roundRedone map[int]int + files []*reviewFileState + filesByPath map[string]*reviewFileState + changes []*ReviewChange + changesByID map[string]*ReviewChange + focusedID string + focusedRowKey string + filter ReviewFilter + search string + collapsedFiles map[string]bool + collapsedKinds map[string]bool + peekBefore bool + revertConfirm bool + legend ReviewOverlayVisibility + activeRegion string + lastKept int + lastReverted int + lastTotal int + lastFileCount int + lastRounds int + lastRequest string + lastOutcomeMsg string + lastChanges []ReviewChange + lastFiles []ReviewFileSummary + applyingCmd bool + yamlEditSessionRev uint64 + uiRev uint64 } func (e *Editor) bumpReviewUIRev() { @@ -551,7 +598,7 @@ func (e *Editor) StartTurnReview(input ReviewTurnInput) error { if err != nil { return err } - if len(fi.BeforeYAML) > maxReviewFileBytes || len(fi.AfterYAML) > maxReviewFileBytes { + if len(fi.BeforeYAML) > maxReviewFileBytes || len(fi.AfterYAML) > maxReviewFileBytes || len(fi.PersonYAML) > maxReviewFileBytes { return fmt.Errorf("editor: review file %q exceeds %d byte limit", cleanPath, maxReviewFileBytes) } if seenPaths[cleanPath] { @@ -581,6 +628,11 @@ func (e *Editor) StartTurnReview(input ReviewTurnInput) error { if err != nil { return fmt.Errorf("editor: diff review file %s: %w", cleanPath, err) } + if fs.kind == ReviewFileScene { + if err := e.initReviewScenePersonDoc(fs, fi); err != nil { + return fmt.Errorf("editor: parse review person scene %s: %w", cleanPath, err) + } + } if len(fileChanges) == 0 { continue } @@ -610,6 +662,7 @@ func (e *Editor) StartTurnReview(input ReviewTurnInput) error { e.ExitHistoryPreview() e.review = st + e.syncAllReviewConflicts() e.cancelAutoSaveTimer() if input.StartPending { e.showAgentTabForReview() @@ -1767,13 +1820,24 @@ func (e *Editor) effectiveReviewSceneDocForRound(fs *reviewFileState, round int) if fs == nil { return nil } + latest := e.reviewLatestRound() + isLatest := latest <= 0 || round >= latest rs := fs.roundState(round) afterDoc := fs.afterDoc if rs != nil && rs.afterDoc != nil { afterDoc = rs.afterDoc } + if fs.personEdited && isLatest { + if merged := e.effectiveReviewSceneDocWithConflicts(fs); merged != nil { + return merged + } + } if fs.beforeDoc == nil { - return cloneSceneDoc(afterDoc) + doc := cloneSceneDoc(afterDoc) + if isLatest { + e.applyReviewHandEditsToDoc(fs, doc) + } + return doc } doc := cloneSceneDoc(fs.beforeDoc) @@ -1894,6 +1958,9 @@ func (e *Editor) effectiveReviewSceneDocForRound(fs *reviewFileState, round int) doc.Layers[li].Objects = append(doc.Layers[li].Objects, m.obj) } + if isLatest { + e.applyReviewHandEditsToDoc(fs, doc) + } return doc } @@ -1947,23 +2014,31 @@ func (e *Editor) effectiveReviewFileBytesForRound(fs *reviewFileState, round int if fs == nil { return nil, false, nil } - if e.allFileChangesReverted(fs.path) { + if e.allFileChangesReverted(fs.path) && !fs.personEdited { return append([]byte(nil), fs.beforeYAML...), fs.existedBefore, nil } + latest := e.reviewLatestRound() + isLatest := latest <= 0 || round >= latest rs := fs.roundState(round) afterYAML := fs.afterYAML if rs != nil { afterYAML = rs.afterYAML } - // If no changes in this file are reverted, preserve exact AfterYAML for the requested round! + // If no changes in this file are reverted, hand-edited, or merged with person edits, preserve exact AfterYAML for the requested round! anyReverted := false + anyHandEdited := false for _, ch := range e.review.changes { - if ch.File == fs.path && ch.Reverted { + if ch.File != fs.path { + continue + } + if ch.Reverted { anyReverted = true - break + } + if ch.HandEdited { + anyHandEdited = true } } - if !anyReverted { + if !anyReverted && (!isLatest || (!anyHandEdited && !fs.personEdited)) { return append([]byte(nil), afterYAML...), len(afterYAML) > 0, nil } @@ -2446,7 +2521,12 @@ func (e *Editor) reviewOverlaysForFile(filePath string) []ReviewSceneOverlay { p0 := bo.World.TransformPoint(math2d.Vec2{X: rx, Y: ry}) x, y, w, h = p0.X, p0.Y, rw, rh } else { - obj := ver.afterObj + var obj *sceneformat.ObjectDoc + if !e.ReviewViewingReadOnlyRound() && ch.handEditObj != nil { + obj = ch.handEditObj + } else { + obj = ver.afterObj + } if obj == nil { obj = ch.beforeObj } @@ -2711,21 +2791,29 @@ func (e *Editor) SetReviewSearch(q string) { e.notify() } -// FocusReviewChange focuses changeID, expands its file/kind groups if collapsed, marks it seen, and frames it. +// FocusReviewChange focuses changeID (full change ID or object ID), expands its file/kind groups if collapsed, +// marks it seen, and frames it. func (e *Editor) FocusReviewChange(changeID string) bool { if e == nil || e.review.outcome != ReviewOutcomePending { return false } - ch := e.review.changesByID[changeID] + ch := e.findReviewChange(changeID) if ch == nil { return false } + // Close any valid inline YAML edit on another change when moving away; keep broken edits flagged. + for _, other := range e.review.changes { + if other.ID != ch.ID && other.EditingYAML && other.YAMLError == nil { + other.EditingYAML = false + } + } e.review.focusedID = ch.ID e.review.focusedRowKey = reviewCardRowKey(ch.ID) ch.Seen = true e.review.collapsedFiles[ch.File] = false e.review.collapsedKinds[ch.File+":"+string(ch.Kind)] = false e.review.peekBefore = false + e.review.yamlEditSessionRev++ e.frameFocusedReviewChange() e.bumpReviewUIRev() e.notify() @@ -2919,13 +3007,19 @@ func (e *Editor) ToggleReviewChangeReverted(changeID string) bool { if e == nil || e.review.outcome != ReviewOutcomePending || e.ReviewViewingReadOnlyRound() { return false } - ch := e.review.changesByID[changeID] + ch := e.findReviewChange(changeID) if ch == nil || ch.GoRequiresConfirm { return false } ch.Reverted = !ch.Reverted + if ch.Reverted { + ch.EditingYAML = false + ch.YAMLError = nil + e.review.yamlEditSessionRev++ + } if fs := e.review.filesByPath[ch.File]; fs != nil { fs.markAllRoundsDirty() + e.refreshReviewChangeYAMLLines(fs, ch) } e.refreshPrefabImpacts() e.bumpReviewUIRev() @@ -2959,8 +3053,15 @@ func (e *Editor) ToggleReviewFileReverted(filePath string) bool { for _, ch := range e.review.changes { if ch.File == filePath && !ch.GoRequiresConfirm { ch.Reverted = target + if target { + ch.EditingYAML = false + ch.YAMLError = nil + } } } + if target { + e.review.yamlEditSessionRev++ + } fs.markAllRoundsDirty() e.refreshPrefabImpacts() e.bumpReviewUIRev() @@ -2994,8 +3095,15 @@ func (e *Editor) ToggleReviewKindReverted(filePath string, kind ReviewChangeKind for _, ch := range e.review.changes { if ch.File == filePath && ch.Kind == kind && !ch.GoRequiresConfirm { ch.Reverted = target + if target { + ch.EditingYAML = false + ch.YAMLError = nil + } } } + if target { + e.review.yamlEditSessionRev++ + } fs.markAllRoundsDirty() e.refreshPrefabImpacts() e.bumpReviewUIRev() @@ -3071,18 +3179,52 @@ func (e *Editor) SetReviewChangeBlocker(changeID, reason string) { e.notify() } -// ReviewBlockers returns all active blockers on non-reverted changes. +// ReviewBlockers returns all active blockers on non-reverted changes in priority order: +// active YAML parse errors first ("Fix YAML on line N"), then unresolved merge conflicts +// ("Choose how merges"), then any custom blockers. func (e *Editor) ReviewBlockers() []ReviewBlocker { if e == nil || e.review.outcome != ReviewOutcomePending { return nil } var out []ReviewBlocker + for _, ch := range e.review.changes { + if ch.Reverted { + continue + } + if ch.YAMLError != nil { + out = append(out, ReviewBlocker{ + Kind: "yaml_error", + ChangeID: ch.ID, + ObjectID: ch.ObjectID, + Line: ch.YAMLError.Line, + Reason: fmt.Sprintf("Fix YAML on line %d", ch.YAMLError.Line), + }) + } + } + for _, ch := range e.review.changes { + if ch.Reverted { + continue + } + if ch.HasUnresolvedConflict() { + out = append(out, ReviewBlocker{ + Kind: "conflict", + ChangeID: ch.ID, + ObjectID: ch.ObjectID, + Reason: fmt.Sprintf("Choose how %s merges", ch.Title), + }) + } + } for _, ch := range e.review.changes { if ch.Reverted { continue } if ch.Blocker != "" { - out = append(out, ReviewBlocker{ChangeID: ch.ID, Reason: ch.Blocker}) + out = append(out, ReviewBlocker{ + Kind: "custom", + ChangeID: ch.ID, + ObjectID: ch.ObjectID, + Reason: ch.Blocker, + }) } } return out @@ -3098,6 +3240,11 @@ func (e *Editor) JumpToReviewBlocker() string { e.review.filter = ReviewFilterAll } e.review.search = "" + if blockers[0].Kind == "yaml_error" { + if ch := e.review.changesByID[blockers[0].ChangeID]; ch != nil { + ch.EditingYAML = true + } + } e.FocusReviewChange(blockers[0].ChangeID) return blockers[0].ChangeID } @@ -3181,16 +3328,22 @@ func (e *Editor) reviewAbsPath(relPath string) string { } func (e *Editor) openSceneProjectRelPath() string { - if e == nil || e.FilePath == "" { + if e == nil { return "" } - if e.ProjectPath != "" { - root := filepath.Dir(e.ProjectPath) - if rel, err := filepath.Rel(root, e.FilePath); err == nil && !strings.HasPrefix(rel, "..") { - return filepath.ToSlash(rel) + if e.FilePath != "" { + if e.ProjectPath != "" { + root := filepath.Dir(e.ProjectPath) + if rel, err := filepath.Rel(root, e.FilePath); err == nil && !strings.HasPrefix(rel, "..") { + return filepath.ToSlash(rel) + } } + return filepath.ToSlash(e.FilePath) + } + if e.ScenePath != "" { + return path.Clean(strings.ReplaceAll(e.ScenePath, `\`, "/")) } - return filepath.ToSlash(e.FilePath) + return "" } func reviewDefaultTargetOS() core.OS { @@ -3288,39 +3441,76 @@ func writeReviewFileAtomic(absPath string, data []byte) error { // KeepTurnReview applies all non-reverted changes across every touched file as ONE History undo step, // saves them cleanly, shows a Toast with Undo, and updates the Agent panel summary. -// When any blocker is active, KeepTurnReview jumps to the first blocker and returns ErrReviewBlocked. +// When any blocker is active, KeepTurnReview jumps to the first blocker and returns *ReviewBlockedError +// (which wraps ErrReviewBlocked). func (e *Editor) KeepTurnReview() error { if e == nil || e.review.outcome != ReviewOutcomePending { return ErrNoReview } if blockers := e.ReviewBlockers(); len(blockers) > 0 { e.JumpToReviewBlocker() - return fmt.Errorf("%w: %s", ErrReviewBlocked, blockers[0].Reason) + return &ReviewBlockedError{Blocker: blockers[0]} } + diskBacked := e.ProjectPath != "" || e.FilePath != "" writes := make([]reviewFileWrite, 0, len(e.review.files)) for _, fs := range e.review.files { if fs.kind == ReviewFileGo { continue } - abs, err := e.resolveSafeReviewWritePath(fs.path) - if err != nil { - return err + var abs string + if diskBacked { + var err error + abs, err = e.resolveSafeReviewWritePath(fs.path) + if err != nil { + return err + } + } else { + if _, err := e.validateReviewRelPath(fs.path); err != nil { + return err + } + } + if fs.kind == ReviewFileScene { + effDoc := e.effectiveReviewSceneDoc(fs) + if err := sceneformat.Validate(effDoc); err != nil { + return fmt.Errorf("editor: validate review scene %s: %w", fs.path, err) + } } afterBytes, existsAfter, err := e.effectiveReviewFileBytes(fs) if err != nil { return fmt.Errorf("editor: encode review file %s: %w", fs.path, err) } + beforeBytes := append([]byte(nil), fs.beforeYAML...) + if fs.kind == ReviewFileScene && fs.personEdited && fs.personDoc != nil { + if enc, eerr := sceneformat.Encode(fs.personDoc); eerr == nil { + beforeBytes = enc + } + } writes = append(writes, reviewFileWrite{ relPath: fs.path, absPath: abs, existedBefore: fs.existedBefore, - beforeBytes: append([]byte(nil), fs.beforeYAML...), + beforeBytes: beforeBytes, existedAfter: existsAfter, afterBytes: afterBytes, }) } + // Commit any active valid inline YAML edits before capturing the kept snapshot. + for _, ch := range e.review.changes { + if ch.EditingYAML && ch.YAMLError == nil { + ch.EditingYAML = false + } + } + + keptSnap := e.ReviewStatus() + latestRound := e.reviewLatestRound() + if e.ReviewViewingReadOnlyRound() { + keptSnap.Changes = make([]ReviewChange, len(e.review.changes)) + for i, ch := range e.review.changes { + keptSnap.Changes[i] = cloneReviewChangeForSnapshot(ch, latestRound, false) + } + } e.ExitHistoryPreview() kept, reverted := e.reviewKeptAndRevertedCounts() savedState := e.review @@ -3330,16 +3520,18 @@ func (e *Editor) KeepTurnReview() error { } cmd := &agentTurnKeepCmd{ - ed: e, - label: label, - writes: writes, - kept: kept, - reverted: reverted, - total: len(savedState.changes), - fileCount: len(savedState.files), - rounds: max(savedState.round, 1), - request: savedState.request, - priorState: savedState, + ed: e, + label: label, + writes: writes, + kept: kept, + reverted: reverted, + total: len(savedState.changes), + fileCount: len(savedState.files), + rounds: max(savedState.round, 1), + request: savedState.request, + keptChanges: keptSnap.Changes, + keptFiles: keptSnap.Files, + priorState: savedState, } if err := e.History.execute(cmd); err != nil { return err @@ -3471,7 +3663,9 @@ func (e *Editor) syncOpenSceneAfterReviewWrites(writes []reviewFileWrite, forwar e.sceneSaved = canon } e.syncActiveTab() - e.recordSceneDiskSnapshot(w.absPath, data) + if w.absPath != "" { + e.recordSceneDiskSnapshot(w.absPath, data) + } e.cancelAutoSaveTimer() e.recordSaveSucceededFor(e.activeTabID(), false) continue @@ -3507,16 +3701,18 @@ func (e *Editor) syncOpenSceneAfterReviewWrites(writes []reviewFileWrite, forwar } type agentTurnKeepCmd struct { - ed *Editor - label string - writes []reviewFileWrite - kept int - reverted int - total int - fileCount int - rounds int - request string - priorState turnReviewState + ed *Editor + label string + writes []reviewFileWrite + kept int + reverted int + total int + fileCount int + rounds int + request string + keptChanges []ReviewChange + keptFiles []ReviewFileSummary + priorState turnReviewState } func (c *agentTurnKeepCmd) Label() string { return c.label } @@ -3553,7 +3749,10 @@ func (c *agentTurnKeepCmd) historyMeta() HistoryMeta { } func (c *agentTurnKeepCmd) do() error { - if err := c.ed.applyReviewFileWrites(c.writes, true); err != nil { + c.ed.review.applyingCmd = true + err := c.ed.applyReviewFileWrites(c.writes, true) + c.ed.review.applyingCmd = false + if err != nil { return err } msg := formatKeptSummary(c.kept, c.reverted, c.rounds) @@ -3568,6 +3767,8 @@ func (c *agentTurnKeepCmd) do() error { lastRounds: max(c.rounds, 1), lastRequest: c.request, lastOutcomeMsg: msg, + lastChanges: cloneReviewChangesSlice(c.keptChanges), + lastFiles: slices.Clone(c.keptFiles), legend: c.priorState.legend, uiRev: c.ed.review.uiRev + 1, } @@ -3589,12 +3790,17 @@ func (c *agentTurnKeepCmd) do() error { } func (c *agentTurnKeepCmd) undo() error { - if err := c.ed.applyReviewFileWrites(c.writes, false); err != nil { + c.ed.review.applyingCmd = true + err := c.ed.applyReviewFileWrites(c.writes, false) + c.ed.review.applyingCmd = false + if err != nil { return err } c.ed.review.outcome = ReviewOutcomeNone c.ed.review.open = false c.ed.review.lastOutcomeMsg = "" + c.ed.review.lastChanges = nil + c.ed.review.lastFiles = nil c.ed.bumpReviewUIRev() c.ed.Status = "Undid kept review" c.ed.notify() @@ -3639,7 +3845,10 @@ func (c *agentTurnRevertAllCmd) historyMeta() HistoryMeta { } func (c *agentTurnRevertAllCmd) do() error { - if err := c.ed.applyReviewFileWrites(c.writes, true); err != nil { + c.ed.review.applyingCmd = true + err := c.ed.applyReviewFileWrites(c.writes, true) + c.ed.review.applyingCmd = false + if err != nil { return err } msg := fmt.Sprintf("Reverted all %d · files are as they were before this request", c.total) @@ -3675,7 +3884,10 @@ func (c *agentTurnRevertAllCmd) do() error { } func (c *agentTurnRevertAllCmd) undo() error { - if err := c.ed.applyReviewFileWrites(c.writes, false); err != nil { + c.ed.review.applyingCmd = true + err := c.ed.applyReviewFileWrites(c.writes, false) + c.ed.review.applyingCmd = false + if err != nil { return err } restored := c.priorState @@ -3751,6 +3963,17 @@ func (e *Editor) ReviewStatus() ReviewSnapshot { if snap.Request == "" { snap.Request = st.lastRequest } + if st.outcome == ReviewOutcomeKept && len(st.lastChanges) > 0 { + snap.Changes = cloneReviewChangesSlice(st.lastChanges) + snap.Files = slices.Clone(st.lastFiles) + seen := 0 + for _, ch := range snap.Changes { + if ch.Seen { + seen++ + } + } + snap.SeenCount = seen + } return snap } @@ -3775,17 +3998,7 @@ func (e *Editor) ReviewStatus() ReviewSnapshot { if ch.Seen { seen++ } - cp := *ch - ver := ch.VersionFor(viewRound) - cp.Detail = ver.Detail - cp.Why = ver.Why - cp.OldValue = ver.OldValue - cp.NewValue = ver.NewValue - cp.DeltaPct = ver.DeltaPct - cp.Line = ver.Line - cp.YAMLLines = slices.Clone(ver.YAMLLines) - cp.Versions = cloneReviewChangeVersions(ch.Versions) - snap.Changes[i] = cp + snap.Changes[i] = cloneReviewChangeForSnapshot(ch, viewRound, snap.ViewingReadOnlyRound) } snap.SeenCount = seen diff --git a/packages/game/editor/review_conflicts.go b/packages/game/editor/review_conflicts.go new file mode 100644 index 000000000..b6fb1d709 --- /dev/null +++ b/packages/game/editor/review_conflicts.go @@ -0,0 +1,1937 @@ +package editor + +import ( + "bytes" + "errors" + "fmt" + "io" + "math" + "reflect" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/nsgo-dev/game/packages/game/sceneformat" + "go.yaml.in/yaml/v3" +) + +// ReviewConflictChoice selects how an overlapping edit between the person and the agent merges. +type ReviewConflictChoice string + +const ( + // ReviewConflictUnresolved indicates the person has not yet chosen Mine, Agent's, or Both. + ReviewConflictUnresolved ReviewConflictChoice = "" + // ReviewConflictMine keeps the person's edit for the conflicting field or list. + ReviewConflictMine ReviewConflictChoice = "mine" + // ReviewConflictAgent keeps the agent's edit for the conflicting field or list. + ReviewConflictAgent ReviewConflictChoice = "agent" + // ReviewConflictBoth keeps both sides' entries for a conflicting list (or map), yours first. + ReviewConflictBoth ReviewConflictChoice = "both" +) + +// ReviewLineAuthor tags who wrote a line in the review YAML pane or conflict card. +type ReviewLineAuthor string + +const ( + ReviewAuthorNone ReviewLineAuthor = "" + ReviewAuthorAgent ReviewLineAuthor = "agent" + ReviewAuthorYou ReviewLineAuthor = "you" +) + +// ReviewConflictLine is one side's preview line inside a conflict card ("you" or "agent"). +type ReviewConflictLine struct { + Author ReviewLineAuthor `json:"author"` + Sign string `json:"sign"` + Text string `json:"text"` +} + +// ReviewConflict describes one overlapping field or list edit on a reviewed object. +type ReviewConflict struct { + Field string `json:"field"` + IsList bool `json:"isList,omitempty"` + Base any `json:"base,omitempty"` + Mine any `json:"mine,omitempty"` + Agent any `json:"agent,omitempty"` + MineLines []ReviewConflictLine `json:"mineLines,omitempty"` + AgentLines []ReviewConflictLine `json:"agentLines,omitempty"` +} + +// ReviewYAMLFix is a mechanical one-step fix offered when a YAML parse error names what is missing. +type ReviewYAMLFix struct { + Label string `json:"label"` + Description string `json:"description,omitempty"` + PatchedYAML string `json:"patchedYaml"` +} + +// ReviewYAMLError describes a syntax or validation error while hand-editing YAML in a review. +type ReviewYAMLError struct { + Line int `json:"line"` + LocalLine int `json:"localLine"` + Title string `json:"title"` + Message string `json:"message"` + Fix *ReviewYAMLFix `json:"fix,omitempty"` + RawParseErr string `json:"rawParseErr,omitempty"` +} + +// CanEditYAML reports whether this change can be hand-edited in place in the review's right YAML pane. +func (c *ReviewChange) CanEditYAML() bool { + if c == nil || c.Reverted || c.FileKind != ReviewFileScene { + return false + } + return c.Kind == ReviewChangeAdded || c.Kind == ReviewChangeChanged +} + +// HasUnresolvedConflict reports whether this non-reverted change has overlapping edits awaiting a choice. +func (c *ReviewChange) HasUnresolvedConflict() bool { + if c == nil || c.Reverted || len(c.Conflicts) == 0 { + return false + } + return c.ConflictChoice == ReviewConflictUnresolved +} + +// findReviewChange resolves a change either by its exact ReviewChange.ID or (when unique / unambiguous) +// by its ObjectID, preferring the currently focused file when multiple files share an object ID. +func (e *Editor) findReviewChange(idOrObj string) *ReviewChange { + if e == nil || idOrObj == "" { + return nil + } + if ch := e.review.changesByID[idOrObj]; ch != nil { + return ch + } + focusedFile := "" + if cur := e.review.changesByID[e.review.focusedID]; cur != nil { + focusedFile = cur.File + } + var firstMatch *ReviewChange + for _, ch := range e.review.changes { + if ch.ObjectID != idOrObj { + continue + } + if focusedFile != "" && ch.File == focusedFile { + return ch + } + if firstMatch == nil { + firstMatch = ch + } + } + return firstMatch +} + +func (e *Editor) initReviewScenePersonDoc(fs *reviewFileState, fi ReviewFileInput) error { + if fs == nil || fs.kind != ReviewFileScene { + return nil + } + opts := sceneformat.ParseOptions{Components: e.components} + if len(fi.PersonYAML) > 0 { + pdoc, err := sceneformat.ParseWith(fi.PersonYAML, opts) + if err != nil { + return err + } + fs.personDoc = pdoc + fs.personEdited = !reviewSceneDocsEqual(fs.beforeDoc, pdoc) + return nil + } + openRel := e.openSceneProjectRelPath() + if openRel != "" && fs.path == openRel && e.Doc != nil { + fs.personDoc = e.Doc.Clone() + fs.personEdited = !reviewSceneDocsEqual(fs.beforeDoc, fs.personDoc) + return nil + } + fs.personDoc = cloneSceneDoc(fs.beforeDoc) + fs.personEdited = false + return nil +} + +func reviewSceneDocsEqual(a, b *sceneformat.SceneDoc) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + ba, ea := sceneformat.Encode(a) + bb, eb := sceneformat.Encode(b) + return ea == nil && eb == nil && bytes.Equal(ba, bb) +} + +func (e *Editor) syncAllReviewConflicts() { + if e == nil || e.review.outcome != ReviewOutcomePending { + return + } + for _, fs := range e.review.files { + if fs.kind == ReviewFileScene { + e.syncReviewConflictsForFile(fs) + } + } +} + +// syncReviewAfterMutate keeps a pending turn review synchronized whenever the person edits +// the open scene through normal editor commands (MoveObject, SetProperty, SetComponentField, etc.). +func (e *Editor) syncReviewAfterMutate() { + if e == nil || e.review.applyingCmd || e.agentActorDepth.Load() > 0 || !e.HasPendingReview() || e.Doc == nil { + return + } + openRel := e.openSceneProjectRelPath() + if openRel == "" { + return + } + fs := e.review.filesByPath[openRel] + if fs == nil || fs.kind != ReviewFileScene { + return + } + fs.personDoc = e.Doc.Clone() + fs.personEdited = !reviewSceneDocsEqual(fs.beforeDoc, fs.personDoc) + e.syncReviewConflictsForFile(fs) + fs.markAllRoundsDirty() + e.bumpReviewUIRev() +} + +// SyncReviewPersonEdits explicitly synchronizes the pending review turn against the editor's open scene Doc +// (useful after direct in-memory edits or external disk reloads). +func (e *Editor) SyncReviewPersonEdits() { + if e == nil || !e.HasPendingReview() || e.Doc == nil { + return + } + openRel := e.openSceneProjectRelPath() + if openRel == "" { + return + } + fs := e.review.filesByPath[openRel] + if fs == nil || fs.kind != ReviewFileScene { + return + } + fs.personDoc = e.Doc.Clone() + fs.personEdited = !reviewSceneDocsEqual(fs.beforeDoc, fs.personDoc) + e.syncReviewConflictsForFile(fs) + fs.markAllRoundsDirty() + e.bumpReviewUIRev() + e.notify() +} + +// syncReviewConflictsForFile recomputes 3-way merge conflicts and auto-merged fields +// between fs.beforeDoc, fs.personDoc, and fs.afterDoc for every change in fs. +func (e *Editor) syncReviewConflictsForFile(fs *reviewFileState) { + if e == nil || fs == nil || fs.kind != ReviewFileScene || fs.beforeDoc == nil || fs.afterDoc == nil { + return + } + if !fs.personEdited || fs.personDoc == nil { + for _, ch := range e.review.changes { + if ch.File != fs.path { + continue + } + hadConflicts := len(ch.Conflicts) > 0 + ch.personObj = nil + ch.Conflicts = nil + ch.ConflictChoice = ReviewConflictUnresolved + ch.AutoMergedFields = nil + if hadConflicts { + e.refreshReviewChangeYAMLLines(fs, ch) + } + } + return + } + + res, err := sceneformat.Merge(fs.beforeDoc, fs.personDoc, fs.afterDoc) + if err != nil { + return + } + + personIdx := indexObjects(fs.personDoc) + conflictsByObj := make(map[string][]sceneformat.MergeConflict) + for _, c := range res.Conflicts { + if c.Scope == "object" && c.Object != "" { + conflictsByObj[c.Object] = append(conflictsByObj[c.Object], c) + } + } + + for _, ch := range e.review.changes { + if ch.File != fs.path { + continue + } + if pInfo, ok := personIdx[ch.ObjectID]; ok { + ch.personObj = mergeCloneObjectDocPtr(pInfo.obj) + } else { + ch.personObj = nil + } + + rawConflicts := conflictsByObj[ch.ObjectID] + prevSig := reviewConflictSignature(ch.Conflicts) + ch.Conflicts = nil + for _, rc := range rawConflicts { + ch.Conflicts = append(ch.Conflicts, buildReviewConflict(rc)) + } + if len(ch.Conflicts) == 0 { + ch.ConflictChoice = ReviewConflictUnresolved + } else if reviewConflictSignature(ch.Conflicts) != prevSig { + ch.ConflictChoice = ReviewConflictUnresolved + } + + // Record any fields where person and agent edited different fields and merged cleanly. + ch.AutoMergedFields = nil + if len(ch.Conflicts) == 0 && ch.beforeObj != nil && ch.personObj != nil && ch.afterObj != nil { + personDiff := diffObjectFieldPaths(ch.beforeObj, ch.personObj) + agentDiff := diffObjectFieldPaths(ch.beforeObj, ch.afterObj) + if len(personDiff) > 0 && len(agentDiff) > 0 { + var merged []string + for _, f := range personDiff { + if !slices.Contains(agentDiff, f) { + merged = append(merged, f) + } + } + slices.Sort(merged) + ch.AutoMergedFields = merged + } + } + e.refreshReviewChangeYAMLLines(fs, ch) + } +} + +// ResolveReviewConflict sets how a conflicting change merges (Mine, Agent's, Both, or Unresolved). +func (e *Editor) ResolveReviewConflict(changeID string, choice ReviewConflictChoice) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + switch choice { + case ReviewConflictUnresolved, ReviewConflictMine, ReviewConflictAgent, ReviewConflictBoth: + default: + return fmt.Errorf("editor: invalid review conflict choice %q", choice) + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + if _, err := e.validateReviewRelPath(ch.File); err != nil { + return err + } + if len(ch.Conflicts) == 0 { + return fmt.Errorf("editor: review change %q has no conflict to resolve", ch.ObjectID) + } + ch.ConflictChoice = choice + ch.Seen = true + if fs := e.review.filesByPath[ch.File]; fs != nil { + fs.markAllRoundsDirty() + e.refreshReviewChangeYAMLLines(fs, ch) + } + e.bumpReviewUIRev() + e.notify() + return nil +} + +// BeginReviewYAMLEdit switches the review's right YAML pane into in-place editing for an added or changed scene object. +func (e *Editor) BeginReviewYAMLEdit(changeID string) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + if _, err := e.validateReviewRelPath(ch.File); err != nil { + return err + } + if !ch.CanEditYAML() { + return fmt.Errorf("editor: cannot edit YAML for %s (%s)", ch.Title, ch.Kind) + } + if ch.EditingYAML { + return nil + } + fs := e.review.filesByPath[ch.File] + effObj := e.effectiveReviewObjectForChange(fs, ch) + if effObj == nil { + return fmt.Errorf("editor: object %q has no YAML to edit", ch.ObjectID) + } + if ch.handEditBaseObj == nil { + ch.handEditBaseObj = mergeCloneObjectDocPtr(effObj) + } + currentYAML := encodeReviewObjectYAML(effObj) + if ch.HandEdited && strings.TrimSpace(ch.HandEditYAML) != "" && ch.YAMLError == nil { + currentYAML = ch.HandEditYAML + } + ch.handEditPreYAML = currentYAML + ch.HandEditYAML = currentYAML + ch.hadHandEditBeforeSession = ch.HandEdited + ch.preSessionHandObj = mergeCloneObjectDocPtr(ch.handEditObj) + ch.preSessionHandFields = slices.Clone(ch.HandEditFields) + ch.preSessionHandLineNums = slices.Clone(ch.handEditLineNums) + ch.YAMLError = nil + ch.EditingYAML = true + ch.Seen = true + e.review.focusedID = ch.ID + e.review.focusedRowKey = reviewCardRowKey(ch.ID) + e.review.yamlEditSessionRev++ + e.refreshReviewChangeYAMLLines(fs, ch) + e.bumpReviewUIRev() + e.notify() + return nil +} + +// SetReviewYAMLDraft updates the in-place YAML text for changeID, parses and validates it live +// (refusing unknown fields and duplicate keys), updates the Review viewport immediately when valid, +// or records a line-specific error with a one-step fix when the parser reports what is missing. +func (e *Editor) SetReviewYAMLDraft(changeID, raw string) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + if _, err := e.validateReviewRelPath(ch.File); err != nil { + return err + } + if !ch.CanEditYAML() { + return fmt.Errorf("editor: cannot edit YAML for %s", ch.Title) + } + if !ch.EditingYAML { + if err := e.BeginReviewYAMLEdit(ch.ID); err != nil { + return err + } + } + fs := e.review.filesByPath[ch.File] + startLine := ch.Line + if startLine <= 0 { + startLine = 1 + } + + if len(raw) > maxReviewYAMLEditBytes { + ch.YAMLError = &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: fmt.Sprintf("YAML edit exceeds %d KiB limit. Keep stays off until the file parses.", maxReviewYAMLEditBytes/1024), + } + e.refreshReviewChangeYAMLLines(fs, ch) + e.bumpReviewUIRev() + e.notify() + return errors.New(ch.YAMLError.Message) + } + if strings.ContainsRune(raw, 0) { + ch.YAMLError = &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: "YAML cannot contain NUL bytes. Keep stays off until the file parses.", + } + e.refreshReviewChangeYAMLLines(fs, ch) + e.bumpReviewUIRev() + e.notify() + return errors.New(ch.YAMLError.Message) + } + + ch.HandEditYAML = raw + var baseDoc *sceneformat.SceneDoc + if fs != nil { + baseDoc = fs.beforeDoc + } + + parsedObj, yamlErr := parseReviewObjectYAML(raw, startLine, ch.ObjectID, ch.handEditBaseObj, e.components, baseDoc) + if yamlErr != nil { + ch.YAMLError = yamlErr + e.refreshReviewChangeYAMLLines(fs, ch) + e.bumpReviewUIRev() + e.notify() + return errors.New(yamlErr.Message) + } + + // Dry-run into the full effective scene to guarantee sceneformat.Validate passes with this edit. + prevObj := ch.handEditObj + prevEdited := ch.HandEdited + ch.handEditObj = parsedObj + ch.HandEdited = true + ch.YAMLError = nil + var derr error + if fs != nil { + doc := e.effectiveReviewSceneDoc(fs) + derr = sceneformat.Validate(doc) + } + if derr != nil { + ch.handEditObj = prevObj + ch.HandEdited = prevEdited + ch.YAMLError = &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: derr.Error() + ". Keep stays off until the file parses.", + } + e.refreshReviewChangeYAMLLines(fs, ch) + e.bumpReviewUIRev() + e.notify() + return derr + } + + // Compute which fields and 1-based scene lines were edited by "you". + baseObj := ch.handEditBaseObj + if baseObj == nil { + baseObj = ch.afterObj + } + ch.HandEditFields = diffObjectFieldPaths(baseObj, parsedObj) + ch.handEditLineNums = computeHandEditedLines(baseObj, parsedObj, startLine) + ch.HandEdited = len(ch.HandEditFields) > 0 || len(ch.handEditLineNums) > 0 + if !ch.HandEdited { + ch.handEditObj = nil + } + if ch.Kind == ReviewChangeAdded { + ch.Detail = formatAddedObjectDetail(parsedObj) + } else if ch.Kind == ReviewChangeChanged && ch.beforeObj != nil { + ch.Detail = formatChangedObjectDetail(ch.beforeObj, parsedObj, ch.beforeLayer, ch.afterLayer) + } + + if fs != nil { + fs.markAllRoundsDirty() + e.refreshReviewChangeYAMLLines(fs, ch) + } + e.bumpReviewUIRev() + e.notify() + return nil +} + +// ApplyReviewYAMLFix applies the offered one-step fix (such as "Add the colon") to the failing YAML draft. +func (e *Editor) ApplyReviewYAMLFix(changeID string) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + if _, err := e.validateReviewRelPath(ch.File); err != nil { + return err + } + if ch.YAMLError == nil || ch.YAMLError.Fix == nil { + return errors.New("editor: no one-step YAML fix is available") + } + patched := ch.YAMLError.Fix.PatchedYAML + e.review.yamlEditSessionRev++ + return e.SetReviewYAMLDraft(ch.ID, patched) +} + +// UndoReviewYAMLTyping discards the in-progress YAML typing and restores the pre-edit snapshot. +func (e *Editor) UndoReviewYAMLTyping(changeID string) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + ch.HandEditYAML = ch.handEditPreYAML + ch.YAMLError = nil + ch.EditingYAML = false + ch.HandEdited = ch.hadHandEditBeforeSession + ch.handEditObj = mergeCloneObjectDocPtr(ch.preSessionHandObj) + ch.HandEditFields = slices.Clone(ch.preSessionHandFields) + ch.handEditLineNums = slices.Clone(ch.preSessionHandLineNums) + fs := e.review.filesByPath[ch.File] + if obj := e.effectiveReviewObjectForChange(fs, ch); obj != nil { + if ch.Kind == ReviewChangeAdded { + ch.Detail = formatAddedObjectDetail(obj) + } else if ch.Kind == ReviewChangeChanged && ch.beforeObj != nil { + ch.Detail = formatChangedObjectDetail(ch.beforeObj, obj, ch.beforeLayer, ch.afterLayer) + } + } + if fs != nil { + fs.markAllRoundsDirty() + e.refreshReviewChangeYAMLLines(fs, ch) + } + e.review.yamlEditSessionRev++ + e.bumpReviewUIRev() + e.notify() + return nil +} + +// FinishReviewYAMLEdit exits in-place YAML editing (Done). Refused with ErrReviewYAMLInvalid while the YAML does not parse. +func (e *Editor) FinishReviewYAMLEdit(changeID string) error { + if e == nil || e.review.outcome != ReviewOutcomePending { + return ErrNoReview + } + if e.ReviewViewingReadOnlyRound() { + return ErrReviewReadOnlyRound + } + ch := e.findReviewChange(changeID) + if ch == nil { + return fmt.Errorf("editor: unknown review change %q", changeID) + } + if ch.YAMLError != nil { + return fmt.Errorf("%w: %s", ErrReviewYAMLInvalid, ch.YAMLError.Title) + } + ch.EditingYAML = false + e.review.yamlEditSessionRev++ + if fs := e.review.filesByPath[ch.File]; fs != nil { + e.refreshReviewChangeYAMLLines(fs, ch) + } + e.bumpReviewUIRev() + e.notify() + return nil +} + +// ReviewEffectiveSceneDoc returns a cloned copy of the live merged SceneDoc for filePath in the active review +// (applying non-reverted agent changes, auto-merged person edits, resolved conflicts, and valid hand edits). +func (e *Editor) ReviewEffectiveSceneDoc(filePath string) *sceneformat.SceneDoc { + if e == nil || e.review.outcome != ReviewOutcomePending { + return nil + } + fs := e.review.filesByPath[filePath] + if fs == nil || fs.kind != ReviewFileScene { + return nil + } + return cloneSceneDoc(e.effectiveReviewSceneDoc(fs)) +} + +func (e *Editor) effectiveReviewSceneDocWithConflicts(fs *reviewFileState) *sceneformat.SceneDoc { + if fs == nil || fs.beforeDoc == nil || fs.afterDoc == nil { + return nil + } + personDoc := fs.personDoc + if personDoc == nil { + personDoc = fs.beforeDoc + } + mergeRes, err := sceneformat.Merge(fs.beforeDoc, personDoc, fs.afterDoc) + if err != nil { + return nil + } + doc := mergeRes.Doc.Clone() + + for _, ch := range e.review.changes { + if ch.File != fs.path { + continue + } + if ch.Reverted { + // Restore person's object (or base object if person did not touch it), or remove if added. + _, _ = removeObjectFromDoc(doc, ch.ObjectID) + if ch.personObj != nil { + insertObjectInDoc(doc, mergeCloneObjectDocPtr(ch.personObj), ch.beforeLayer, ch.beforeParentID) + } else if ch.beforeObj != nil { + insertObjectInDoc(doc, mergeCloneObjectDocPtr(ch.beforeObj), ch.beforeLayer, ch.beforeParentID) + } + continue + } + + // Apply conflict choices first (before any hand edit on top). + if len(ch.Conflicts) > 0 { + obj, _, _ := findObjectInDoc(doc, ch.ObjectID) + if obj != nil { + for _, c := range ch.Conflicts { + switch ch.ConflictChoice { + case ReviewConflictMine: + applyObjectFieldValue(obj, c.Field, cloneAnyValue(c.Mine)) + case ReviewConflictAgent: + applyObjectFieldValue(obj, c.Field, cloneAnyValue(c.Agent)) + case ReviewConflictBoth: + merged := mergeConflictValueBoth(c.Base, c.Mine, c.Agent) + applyObjectFieldValue(obj, c.Field, merged) + default: + // Unresolved preview preserves person's side until chosen. + applyObjectFieldValue(obj, c.Field, cloneAnyValue(c.Mine)) + } + } + } + } + + // Apply valid hand-edited YAML on top of the change. + if ch.HandEdited && ch.handEditObj != nil { + existing, _, _ := findObjectInDoc(doc, ch.ObjectID) + if existing != nil { + replacement := mergeCloneObjectDocPtr(ch.handEditObj) + if len(replacement.Children) == 0 && len(existing.Children) > 0 { + replacement.Children = cloneObjectSlice(existing.Children) + } + *existing = *replacement + } else { + insertObjectInDoc(doc, mergeCloneObjectDocPtr(ch.handEditObj), ch.afterLayer, ch.ParentID) + } + } + } + return doc +} + +func (e *Editor) applyReviewHandEditsToDoc(fs *reviewFileState, doc *sceneformat.SceneDoc) { + if fs == nil || doc == nil { + return + } + for _, ch := range e.review.changes { + if ch.File != fs.path || ch.Reverted || !ch.HandEdited || ch.handEditObj == nil { + continue + } + existing, _, _ := findObjectInDoc(doc, ch.ObjectID) + if existing != nil { + replacement := mergeCloneObjectDocPtr(ch.handEditObj) + if len(replacement.Children) == 0 && len(existing.Children) > 0 { + replacement.Children = cloneObjectSlice(existing.Children) + } + *existing = *replacement + } else { + insertObjectInDoc(doc, mergeCloneObjectDocPtr(ch.handEditObj), ch.afterLayer, ch.ParentID) + } + } +} + +func (e *Editor) effectiveReviewObjectForChange(fs *reviewFileState, ch *ReviewChange) *sceneformat.ObjectDoc { + if ch == nil { + return nil + } + if fs != nil && fs.kind == ReviewFileScene { + if doc := e.effectiveReviewSceneDoc(fs); doc != nil { + if obj, _, _ := findObjectInDoc(doc, ch.ObjectID); obj != nil { + return mergeCloneObjectDocPtr(obj) + } + } + } + if ch.HandEdited && ch.handEditObj != nil { + return mergeCloneObjectDocPtr(ch.handEditObj) + } + if ch.afterObj != nil { + return mergeCloneObjectDocPtr(ch.afterObj) + } + return mergeCloneObjectDocPtr(ch.beforeObj) +} + +func (e *Editor) refreshReviewChangeYAMLLines(fs *reviewFileState, ch *ReviewChange) { + if ch == nil || ch.FileKind != ReviewFileScene { + return + } + start := ch.Line + if start <= 0 { + start = 1 + } + + // If currently editing and broken, render the raw draft lines with the error line marked. + if ch.EditingYAML && ch.YAMLError != nil { + rawLines := strings.Split(strings.TrimSuffix(ch.HandEditYAML, "\n"), "\n") + out := make([]ReviewYAMLLine, 0, len(rawLines)) + for i, text := range rawLines { + lineNum := start + i + isErr := lineNum == ch.YAMLError.Line || (i+1) == ch.YAMLError.LocalLine + sign := "+" + if ch.Kind == ReviewChangeChanged { + sign = "" + } + tag := "" + if isErr { + tag = fmt.Sprintf("line %d", lineNum) + } + out = append(out, ReviewYAMLLine{ + Line: lineNum, + Sign: sign, + Text: text, + Tag: tag, + Error: isErr, + }) + } + ch.YAMLLines = out + return + } + + // Special conflict rendering showing both "you" and "agent" lines when unresolved or Both. + if len(ch.Conflicts) > 0 && !ch.HandEdited { + ch.YAMLLines = buildConflictYAMLLines(ch, start) + return + } + + // If hand-edited, render lines with edited lines tagged "you". + if ch.HandEdited && ch.handEditObj != nil { + editedSet := make(map[int]bool, len(ch.handEditLineNums)) + for _, ln := range ch.handEditLineNums { + editedSet[ln] = true + } + switch ch.Kind { + case ReviewChangeAdded: + raw := encodeReviewObjectYAML(ch.handEditObj) + lines := strings.Split(strings.TrimSuffix(raw, "\n"), "\n") + out := make([]ReviewYAMLLine, 0, len(lines)) + for i, l := range lines { + ln := start + i + author := ReviewAuthorNone + tag := "" + if editedSet[ln] { + author = ReviewAuthorYou + tag = string(ReviewAuthorYou) + } + out = append(out, ReviewYAMLLine{Line: ln, Sign: "+", Text: l, Tag: tag, Author: author}) + } + ch.YAMLLines = out + return + case ReviewChangeChanged: + baseRaw := encodeReviewObjectYAML(ch.beforeObj) + effRaw := encodeReviewObjectYAML(ch.handEditObj) + baseLines := strings.Split(strings.TrimSuffix(baseRaw, "\n"), "\n") + effLines := strings.Split(strings.TrimSuffix(effRaw, "\n"), "\n") + ch.YAMLLines = diffReviewHandEditYAMLLines(baseLines, effLines, start, true, editedSet) + return + } + } + + // Restore standard diff lines when neither conflict nor hand-edit is active. + if fs != nil { + switch ch.Kind { + case ReviewChangeAdded: + if ch.afterObj != nil { + _, ch.YAMLLines = buildAddedObjectYAMLDiff(fs.afterYAML, ch.afterObj) + } + case ReviewChangeChanged: + if ch.beforeObj != nil && ch.afterObj != nil { + _, ch.YAMLLines = buildChangedObjectYAMLDiff(fs.beforeYAML, fs.afterYAML, ch.beforeObj, ch.afterObj) + } + case ReviewChangeRemoved: + if ch.beforeObj != nil { + _, ch.YAMLLines = buildRemovedObjectYAMLDiff(fs.beforeYAML, ch.beforeObj) + } + } + } +} + +func buildConflictYAMLLines(ch *ReviewChange, start int) []ReviewYAMLLine { + var out []ReviewYAMLLine + ln := start + out = append(out, ReviewYAMLLine{Line: ln, Text: " - id: " + ch.ObjectID}) + ln++ + for _, c := range ch.Conflicts { + shortField := c.Field + if idx := strings.LastIndex(shortField, "."); idx >= 0 { + shortField = shortField[idx+1:] + } + showMine := ch.ConflictChoice == ReviewConflictUnresolved || ch.ConflictChoice == ReviewConflictMine || ch.ConflictChoice == ReviewConflictBoth + showAgent := ch.ConflictChoice == ReviewConflictUnresolved || ch.ConflictChoice == ReviewConflictAgent || ch.ConflictChoice == ReviewConflictBoth + if c.IsList { + out = append(out, ReviewYAMLLine{Line: ln, Text: " " + shortField + ":"}) + ln++ + if baseSlice, ok := toAnySlice(c.Base); ok { + for _, item := range baseSlice { + out = append(out, ReviewYAMLLine{Line: ln, Text: " - " + formatConflictListItem(item)}) + ln++ + } + } + if showMine { + for _, ml := range c.MineLines { + out = append(out, ReviewYAMLLine{ + Line: ln, + Sign: "+", + Text: " - " + ml.Text, + Tag: string(ReviewAuthorYou), + Author: ReviewAuthorYou, + }) + ln++ + } + } + if showAgent { + for _, al := range c.AgentLines { + out = append(out, ReviewYAMLLine{ + Line: ln, + Sign: "+", + Text: " - " + al.Text, + Tag: string(ReviewAuthorAgent), + Author: ReviewAuthorAgent, + }) + ln++ + } + } + } else { + if c.Base != nil { + out = append(out, ReviewYAMLLine{Line: ln, Sign: "-", Text: " " + formatConflictScalar(c.Field, c.Base)}) + ln++ + } + if showMine { + for _, ml := range c.MineLines { + out = append(out, ReviewYAMLLine{ + Line: ln, + Sign: "+", + Text: " " + ml.Text, + Tag: string(ReviewAuthorYou), + Author: ReviewAuthorYou, + }) + ln++ + } + } + if showAgent { + for _, al := range c.AgentLines { + out = append(out, ReviewYAMLLine{ + Line: ln, + Sign: "+", + Text: " " + al.Text, + Tag: string(ReviewAuthorAgent), + Author: ReviewAuthorAgent, + }) + ln++ + } + } + } + } + return out +} + +func diffReviewHandEditYAMLLines(baseLines, effLines []string, start int, handEdited bool, editedSet map[int]bool) []ReviewYAMLLine { + baseSet := make(map[string]int, len(baseLines)) + for _, l := range baseLines { + baseSet[l]++ + } + effSet := make(map[string]int, len(effLines)) + for _, l := range effLines { + effSet[l]++ + } + var out []ReviewYAMLLine + emittedDel := make(map[int]bool) + for i, l := range effLines { + ln := start + i + if baseSet[l] > 0 { + baseSet[l]-- + out = append(out, ReviewYAMLLine{Line: ln, Text: l}) + continue + } + keyPrefix := yamlLineKeyPrefix(l) + if keyPrefix != "" { + for bi, bl := range baseLines { + if emittedDel[bi] || effSet[bl] > 0 { + continue + } + if yamlLineKeyPrefix(bl) == keyPrefix { + emittedDel[bi] = true + out = append(out, ReviewYAMLLine{Line: ln, Sign: "-", Text: bl}) + break + } + } + } + author := ReviewAuthorNone + tag := "" + if handEdited && editedSet[ln] { + author = ReviewAuthorYou + tag = string(ReviewAuthorYou) + } + out = append(out, ReviewYAMLLine{Line: ln, Sign: "+", Text: l, Tag: tag, Author: author}) + } + for bi, bl := range baseLines { + if emittedDel[bi] || effSet[bl] > 0 { + continue + } + out = append(out, ReviewYAMLLine{Line: start + len(effLines), Sign: "-", Text: bl}) + } + return out +} + +func yamlLineKeyPrefix(line string) string { + idx := strings.IndexByte(line, ':') + if idx <= 0 { + return "" + } + return line[:idx] +} + +// cloneReviewChangeForSnapshot produces a deep, immutable snapshot copy of ch for ReviewStatus and MCP. +func cloneReviewChangeForSnapshot(ch *ReviewChange, viewRound int, readOnly bool) ReviewChange { + cp := *ch + cp.Versions = cloneReviewChangeVersions(ch.Versions) + if readOnly && viewRound > 0 { + ver := ch.VersionFor(viewRound) + cp.Detail = ver.Detail + cp.Why = ver.Why + cp.OldValue = ver.OldValue + cp.NewValue = ver.NewValue + cp.DeltaPct = ver.DeltaPct + cp.Line = ver.Line + cp.YAMLLines = slices.Clone(ver.YAMLLines) + cp.EditingYAML = false + cp.YAMLError = nil + } else { + cp.YAMLLines = slices.Clone(ch.YAMLLines) + } + cp.AutoMergedFields = slices.Clone(ch.AutoMergedFields) + cp.HandEditFields = slices.Clone(ch.HandEditFields) + + author := ReviewAuthorAgent + var handBy ReviewLineAuthor + if ch.HandEdited { + author = ReviewAuthorYou + handBy = ReviewAuthorYou + } else if len(ch.Conflicts) > 0 && ch.ConflictChoice == ReviewConflictMine { + author = ReviewAuthorYou + } + cp.Author = author + cp.HandEditBy = handBy + + var handLines []ReviewYAMLLine + for _, ln := range cp.YAMLLines { + if ln.Author == ReviewAuthorYou || ln.Tag == string(ReviewAuthorYou) { + handLines = append(handLines, ln) + } + } + cp.HandEditLines = handLines + + if !readOnly && (ch.HandEdited || ch.EditingYAML) { + if ch.handEditObj != nil && ch.YAMLError == nil { + cp.HandEditYAML = encodeReviewObjectYAML(ch.handEditObj) + } else { + cp.HandEditYAML = ch.HandEditYAML + } + } else { + cp.HandEditYAML = "" + } + + if len(ch.Conflicts) > 0 { + cp.Conflicts = make([]ReviewConflict, len(ch.Conflicts)) + for ci, c := range ch.Conflicts { + cc := c + cc.Base = cloneAnyValue(c.Base) + cc.Mine = cloneAnyValue(c.Mine) + cc.Agent = cloneAnyValue(c.Agent) + cc.MineLines = slices.Clone(c.MineLines) + cc.AgentLines = slices.Clone(c.AgentLines) + cp.Conflicts[ci] = cc + } + } + if !readOnly && ch.YAMLError != nil { + errCp := *ch.YAMLError + if ch.YAMLError.Fix != nil { + fixCp := *ch.YAMLError.Fix + errCp.Fix = &fixCp + } + cp.YAMLError = &errCp + } + return cp +} + +func cloneReviewChangesSlice(in []ReviewChange) []ReviewChange { + if len(in) == 0 { + return nil + } + out := make([]ReviewChange, len(in)) + for i := range in { + cp := in[i] + cp.YAMLLines = slices.Clone(in[i].YAMLLines) + cp.Versions = cloneReviewChangeVersions(in[i].Versions) + cp.AutoMergedFields = slices.Clone(in[i].AutoMergedFields) + cp.HandEditFields = slices.Clone(in[i].HandEditFields) + cp.HandEditLines = slices.Clone(in[i].HandEditLines) + if len(in[i].Conflicts) > 0 { + cp.Conflicts = make([]ReviewConflict, len(in[i].Conflicts)) + for ci, c := range in[i].Conflicts { + cc := c + cc.Base = cloneAnyValue(c.Base) + cc.Mine = cloneAnyValue(c.Mine) + cc.Agent = cloneAnyValue(c.Agent) + cc.MineLines = slices.Clone(c.MineLines) + cc.AgentLines = slices.Clone(c.AgentLines) + cp.Conflicts[ci] = cc + } + } + if in[i].YAMLError != nil { + errCp := *in[i].YAMLError + if in[i].YAMLError.Fix != nil { + fixCp := *in[i].YAMLError.Fix + errCp.Fix = &fixCp + } + cp.YAMLError = &errCp + } + out[i] = cp + } + return out +} + +// --- Conflict metadata formatting --- + +func reviewConflictSignature(cs []ReviewConflict) string { + if len(cs) == 0 { + return "" + } + var b strings.Builder + for _, c := range cs { + mineB, _ := yaml.Marshal(c.Mine) + agentB, _ := yaml.Marshal(c.Agent) + fmt.Fprintf(&b, "%s|%s|%s;", c.Field, bytes.TrimSpace(mineB), bytes.TrimSpace(agentB)) + } + return b.String() +} + +func buildReviewConflict(rc sceneformat.MergeConflict) ReviewConflict { + c := ReviewConflict{ + Field: rc.Field, + Base: cloneAnyValue(rc.Base), + Mine: cloneAnyValue(rc.Ours), + Agent: cloneAnyValue(rc.Theirs), + } + mineSlice, mineIsList := toAnySlice(rc.Ours) + agentSlice, agentIsList := toAnySlice(rc.Theirs) + baseSlice, _ := toAnySlice(rc.Base) + if mineIsList && agentIsList { + c.IsList = true + for _, item := range sliceAdditions(baseSlice, mineSlice) { + c.MineLines = append(c.MineLines, ReviewConflictLine{ + Author: ReviewAuthorYou, + Sign: "+", + Text: formatConflictListItem(item), + }) + } + for _, item := range sliceAdditions(baseSlice, agentSlice) { + c.AgentLines = append(c.AgentLines, ReviewConflictLine{ + Author: ReviewAuthorAgent, + Sign: "+", + Text: formatConflictListItem(item), + }) + } + if len(c.MineLines) == 0 { + c.MineLines = []ReviewConflictLine{{Author: ReviewAuthorYou, Sign: "+", Text: formatConflictScalar(rc.Field, rc.Ours)}} + } + if len(c.AgentLines) == 0 { + c.AgentLines = []ReviewConflictLine{{Author: ReviewAuthorAgent, Sign: "+", Text: formatConflictScalar(rc.Field, rc.Theirs)}} + } + return c + } + + c.MineLines = []ReviewConflictLine{{ + Author: ReviewAuthorYou, + Sign: "+", + Text: formatConflictScalar(rc.Field, rc.Ours), + }} + c.AgentLines = []ReviewConflictLine{{ + Author: ReviewAuthorAgent, + Sign: "+", + Text: formatConflictScalar(rc.Field, rc.Theirs), + }} + return c +} + +func formatConflictListItem(item any) string { + if m, ok := item.(map[string]any); ok && len(m) == 1 { + for k, v := range m { + return fmt.Sprintf("%s: %s", k, formatSimpleYAMLVal(v)) + } + } + return formatSimpleYAMLVal(item) +} + +func formatConflictScalar(field string, v any) string { + short := field + if idx := strings.LastIndex(field, "."); idx >= 0 { + short = field[idx+1:] + } + if v == nil { + return short + ": (removed)" + } + return fmt.Sprintf("%s: %s", short, formatSimpleYAMLVal(v)) +} + +func formatSimpleYAMLVal(v any) string { + if v == nil { + return "null" + } + switch x := v.(type) { + case string: + return x + case bool: + return strconv.FormatBool(x) + case int: + return strconv.Itoa(x) + case int64: + return strconv.FormatInt(x, 10) + case float32: + return strconv.FormatFloat(float64(x), 'f', -1, 32) + case float64: + return strconv.FormatFloat(x, 'f', -1, 64) + default: + raw, err := yaml.Marshal(v) + if err != nil { + return fmt.Sprint(v) + } + return strings.TrimSpace(string(raw)) + } +} + +// encodeReviewObjectYAML encodes obj as clean 2-space indented object YAML without repeating children. +func encodeReviewObjectYAML(obj *sceneformat.ObjectDoc) string { + if obj == nil { + return "" + } + cp := mergeCloneObjectDocPtr(obj) + cp.Children = nil + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + _ = enc.Encode(cp) + _ = enc.Close() + lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") + for i, l := range lines { + if i == 0 { + lines[i] = " - " + l + } else { + lines[i] = " " + l + } + } + return strings.Join(lines, "\n") +} + +// computeHandEditedLines returns the 1-based scene line numbers of lines in newObj's YAML +// that differ from baseObj's YAML. +func computeHandEditedLines(baseObj, newObj *sceneformat.ObjectDoc, startLine int) []int { + if newObj == nil { + return nil + } + baseLines := strings.Split(strings.TrimSuffix(encodeReviewObjectYAML(baseObj), "\n"), "\n") + newLines := strings.Split(strings.TrimSuffix(encodeReviewObjectYAML(newObj), "\n"), "\n") + baseCount := make(map[string]int, len(baseLines)) + for _, l := range baseLines { + baseCount[l]++ + } + var out []int + for i, l := range newLines { + if baseCount[l] > 0 { + baseCount[l]-- + continue + } + out = append(out, startLine+i) + } + return out +} + +// --- Strict YAML parsing & mechanical one-step fix detection --- + +var ( + reReviewYAMLLineErr = regexp.MustCompile(`line (\d+):`) + reReviewMissingColon = regexp.MustCompile(`^(\s*(?:-\s+)?)([A-Za-z_][A-Za-z0-9_.-]*)(\s+)([^:#\s].*)$`) + reReviewLeadingTabErr = regexp.MustCompile(`^\t+`) +) + +func parseReviewObjectYAML(raw string, startLine int, expectedID string, baseObj *sceneformat.ObjectDoc, reg *sceneformat.ComponentRegistry, baseDoc *sceneformat.SceneDoc) (*sceneformat.ObjectDoc, *ReviewYAMLError) { + if strings.TrimSpace(raw) == "" { + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: "Object YAML cannot be empty. Keep stays off until the file parses.", + } + } + + rawLines := strings.Split(strings.TrimSuffix(raw, "\n"), "\n") + + // Check for leading tabs first (yaml/v3 rejects tabs for indentation). + for i, l := range rawLines { + if reReviewLeadingTabErr.MatchString(l) { + sceneLine := startLine + i + patched := slices.Clone(rawLines) + for j := range patched { + for strings.HasPrefix(patched[j], "\t") { + patched[j] = " " + strings.TrimPrefix(patched[j], "\t") + } + } + return nil, &ReviewYAMLError{ + Line: sceneLine, + LocalLine: i + 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: "YAML indentation uses spaces, not tabs. Keep stays off until the file parses.", + Fix: &ReviewYAMLFix{ + Label: "Replace tabs with spaces", + Description: "Replace leading tabs with two spaces each.", + PatchedYAML: strings.Join(patched, "\n"), + }, + } + } + } + + var root yaml.Node + if err := yaml.Unmarshal([]byte(raw), &root); err != nil { + return nil, diagnoseReviewYAMLParseError(raw, rawLines, startLine, err) + } + if root.Kind == 0 || len(root.Content) == 0 { + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: "Expected a YAML mapping for the object. Keep stays off until the file parses.", + } + } + docNode := root.Content[0] + if docNode.Kind == yaml.SequenceNode { + if len(docNode.Content) != 1 { + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: "Expected a single object entry. Keep stays off until the file parses.", + } + } + docNode = docNode.Content[0] + } + if docNode.Kind != yaml.MappingNode { + if fixErr := detectReviewMissingColonInLines(rawLines, startLine, 0); fixErr != nil { + return nil, fixErr + } + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: "Expected key: value fields for the object. Keep stays off until the file parses.", + } + } + + // Refuse duplicate mapping keys deterministically. + if dupErr := checkDuplicateYAMLMappingKeys(docNode, startLine); dupErr != nil { + return nil, dupErr + } + + // Guard against YAML folding a colon-less line (`x 444`) into the preceding plain string scalar! + if fixErr := detectReviewFoldedMissingColon(&root, rawLines, startLine); fixErr != nil { + return nil, fixErr + } + + // Re-encode the mapping node and decode strictly with KnownFields(true) so unknown fields are refused. + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(docNode); err != nil { + return nil, diagnoseReviewYAMLParseError(raw, rawLines, startLine, err) + } + _ = enc.Close() + + dec := yaml.NewDecoder(bytes.NewReader(buf.Bytes())) + dec.KnownFields(true) + var obj sceneformat.ObjectDoc + if err := dec.Decode(&obj); err != nil && !errors.Is(err, io.EOF) { + localLine := extractReviewYAMLErrorLine(err.Error(), len(rawLines)) + sceneLine := startLine + localLine - 1 + if fixErr := detectReviewMissingColonInLines(rawLines, startLine, localLine-1); fixErr != nil { + return nil, fixErr + } + return nil, &ReviewYAMLError{ + Line: sceneLine, + LocalLine: localLine, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: cleanReviewYAMLErrorText(err.Error()) + ". Keep stays off until the file parses.", + RawParseErr: err.Error(), + } + } + + if obj.ID == "" { + obj.ID = expectedID + } + if obj.ID != expectedID { + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: fmt.Sprintf("Object id %q must stay %q. Keep stays off until the file parses.", obj.ID, expectedID), + } + } + + // Validate component fields if a component registry is available. + if reg != nil && len(obj.Components) > 0 { + testScene := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Layers: []sceneformat.LayerDoc{{Name: "check", Objects: []sceneformat.ObjectDoc{obj}}}, + } + if baseDoc != nil && baseDoc.Version > 0 { + testScene.Version = baseDoc.Version + } + if encoded, err := sceneformat.Encode(testScene); err == nil { + if _, perr := sceneformat.ParseWith(encoded, sceneformat.ParseOptions{Components: reg}); perr != nil { + return nil, &ReviewYAMLError{ + Line: startLine, + LocalLine: 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", startLine), + Message: perr.Error() + ". Keep stays off until the file parses.", + } + } + } + } + + // Preserve existing children if not explicitly edited. + if len(obj.Children) == 0 && baseObj != nil && len(baseObj.Children) > 0 { + obj.Children = cloneObjectSlice(baseObj.Children) + } + return &obj, nil +} + +func checkDuplicateYAMLMappingKeys(n *yaml.Node, startLine int) *ReviewYAMLError { + if n == nil { + return nil + } + if n.Kind == yaml.MappingNode { + seen := make(map[string]bool, len(n.Content)/2) + for i := 0; i+1 < len(n.Content); i += 2 { + k := n.Content[i] + v := n.Content[i+1] + if k.Kind == yaml.ScalarNode { + if seen[k.Value] { + localLine := max(k.Line, 1) + sceneLine := startLine + localLine - 1 + return &ReviewYAMLError{ + Line: sceneLine, + LocalLine: localLine, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: fmt.Sprintf("Duplicate key %q on line %d. Keep stays off until the file parses.", k.Value, sceneLine), + } + } + seen[k.Value] = true + } + if err := checkDuplicateYAMLMappingKeys(v, startLine); err != nil { + return err + } + } + return nil + } + for _, child := range n.Content { + if err := checkDuplicateYAMLMappingKeys(child, startLine); err != nil { + return err + } + } + return nil +} + +func diagnoseReviewYAMLParseError(raw string, rawLines []string, startLine int, err error) *ReviewYAMLError { + errStr := err.Error() + localLine := extractReviewYAMLErrorLine(errStr, len(rawLines)) + hintIdx := localLine - 1 + + // 1. Check for missing colon on the reported line or the preceding line. + if strings.Contains(errStr, "could not find expected ':'") || strings.Contains(errStr, "mapping values are not allowed") { + if fixErr := detectReviewMissingColonInLines(rawLines, startLine, hintIdx); fixErr != nil { + fixErr.RawParseErr = errStr + return fixErr + } + } + + // 2. Check for unclosed quote. + if strings.Contains(errStr, "found unexpected end of stream") || strings.Contains(errStr, "quoted scalar") { + for _, idx := range reviewCandidateLineIndices(len(rawLines), hintIdx) { + line := rawLines[idx] + for _, quote := range []byte{'"', '\''} { + if strings.Count(line, string(quote))%2 == 1 { + patched := slices.Clone(rawLines) + patched[idx] = line + string(quote) + sceneLine := startLine + idx + return &ReviewYAMLError{ + Line: sceneLine, + LocalLine: idx + 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: fmt.Sprintf("Unclosed %c quote; close the string on line %d. Keep stays off until the file parses.", quote, sceneLine), + RawParseErr: errStr, + Fix: &ReviewYAMLFix{ + Label: "Close the quote", + Description: fmt.Sprintf("Add the closing %c quote on line %d.", quote, sceneLine), + PatchedYAML: strings.Join(patched, "\n"), + }, + } + } + } + } + } + + // 3. Check for unclosed inline brace or bracket. + for _, pair := range [][3]string{ + {"{", "}", "Add the closing brace"}, + {"[", "]", "Add the closing bracket"}, + } { + openCh, closeCh, label := pair[0], pair[1], pair[2] + if strings.Count(raw, openCh) > strings.Count(raw, closeCh) { + for _, idx := range reviewCandidateLineIndices(len(rawLines), hintIdx) { + if strings.Count(rawLines[idx], openCh) > strings.Count(rawLines[idx], closeCh) { + patched := slices.Clone(rawLines) + patched[idx] = rawLines[idx] + " " + closeCh + sceneLine := startLine + idx + return &ReviewYAMLError{ + Line: sceneLine, + LocalLine: idx + 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: fmt.Sprintf("Missing %s on line %d. Keep stays off until the file parses.", closeCh, sceneLine), + RawParseErr: errStr, + Fix: &ReviewYAMLFix{ + Label: label, + Description: fmt.Sprintf("Append %s to line %d.", closeCh, sceneLine), + PatchedYAML: strings.Join(patched, "\n"), + }, + } + } + } + } + } + + // Fallback: check for missing colon anywhere near the error line. + if fixErr := detectReviewMissingColonInLines(rawLines, startLine, hintIdx); fixErr != nil { + fixErr.RawParseErr = errStr + return fixErr + } + + sceneLine := startLine + localLine - 1 + return &ReviewYAMLError{ + Line: sceneLine, + LocalLine: localLine, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: cleanReviewYAMLErrorText(errStr) + ". Keep stays off until the file parses.", + RawParseErr: errStr, + } +} + +func detectReviewFoldedMissingColon(root *yaml.Node, rawLines []string, startLine int) *ReviewYAMLError { + var found *ReviewYAMLError + var walk func(n *yaml.Node) + walk = func(n *yaml.Node) { + if n == nil || found != nil { + return + } + if n.Kind == yaml.ScalarNode && n.Style == 0 && n.Line > 0 && n.Line < len(rawLines) { + nextIdx := n.Line // 0-based index of line (n.Line + 1) + if nextIdx < len(rawLines) { + if m := reReviewMissingColon.FindStringSubmatch(rawLines[nextIdx]); m != nil && !strings.Contains(rawLines[nextIdx], ":") { + key := m[2] + if strings.Contains(n.Value, key) { + patched := slices.Clone(rawLines) + patched[nextIdx] = m[1] + m[2] + ":" + m[3] + m[4] + sceneLine := startLine + nextIdx + found = &ReviewYAMLError{ + Line: sceneLine, + LocalLine: nextIdx + 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: fmt.Sprintf("Expected key: value; add a colon after %s. Keep stays off until the file parses.", key), + Fix: &ReviewYAMLFix{ + Label: "Add the colon", + Description: fmt.Sprintf("Add a colon after %s.", key), + PatchedYAML: strings.Join(patched, "\n"), + }, + } + return + } + } + } + } + for _, child := range n.Content { + walk(child) + } + } + walk(root) + return found +} + +func detectReviewMissingColonInLines(rawLines []string, startLine int, hintIdx int) *ReviewYAMLError { + for _, idx := range reviewCandidateLineIndices(len(rawLines), hintIdx) { + line := rawLines[idx] + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + if strings.Contains(line, ":") { + continue + } + m := reReviewMissingColon.FindStringSubmatch(line) + if m == nil { + continue + } + key := m[2] + patched := slices.Clone(rawLines) + patched[idx] = m[1] + m[2] + ":" + m[3] + m[4] + sceneLine := startLine + idx + return &ReviewYAMLError{ + Line: sceneLine, + LocalLine: idx + 1, + Title: fmt.Sprintf("Line %d isn't valid YAML", sceneLine), + Message: fmt.Sprintf("Expected key: value; add a colon after %s. Keep stays off until the file parses.", key), + Fix: &ReviewYAMLFix{ + Label: "Add the colon", + Description: fmt.Sprintf("Add a colon after %s.", key), + PatchedYAML: strings.Join(patched, "\n"), + }, + } + } + return nil +} + +func reviewCandidateLineIndices(n, hint int) []int { + if n <= 0 { + return nil + } + if hint < 0 { + hint = 0 + } + if hint >= n { + hint = n - 1 + } + seen := make(map[int]bool, n) + var out []int + add := func(i int) { + if i >= 0 && i < n && !seen[i] { + seen[i] = true + out = append(out, i) + } + } + add(hint - 1) + add(hint) + add(hint + 1) + for i := 0; i < n; i++ { + add(i) + } + return out +} + +func extractReviewYAMLErrorLine(msg string, maxLine int) int { + if m := reReviewYAMLLineErr.FindStringSubmatch(msg); len(m) == 2 { + if n, err := strconv.Atoi(m[1]); err == nil && n >= 1 { + if maxLine > 0 && n > maxLine { + return maxLine + } + return n + } + } + return 1 +} + +func cleanReviewYAMLErrorText(msg string) string { + s := strings.TrimSpace(msg) + s = strings.TrimPrefix(s, "yaml: ") + if idx := strings.Index(s, "\n"); idx >= 0 { + s = strings.TrimSpace(s[:idx]) + } + if s == "" { + return "Invalid YAML" + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// --- Field-level value merging & diff helpers --- + +func toAnySlice(v any) ([]any, bool) { + if v == nil { + return nil, false + } + if s, ok := v.([]any); ok { + return s, true + } + rv := reflect.ValueOf(v) + if rv.Kind() == reflect.Slice { + out := make([]any, rv.Len()) + for i := 0; i < rv.Len(); i++ { + out[i] = rv.Index(i).Interface() + } + return out, true + } + return nil, false +} + +// sliceAdditions returns items in side that are not accounted for by base, preserving side's order. +func sliceAdditions(base, side []any) []any { + used := make([]bool, len(base)) + var added []any + for _, item := range side { + matched := false + for j, bItem := range base { + if !used[j] && yamlDeepEqual(bItem, item) { + used[j] = true + matched = true + break + } + } + if !matched { + added = append(added, cloneAnyValue(item)) + } + } + return added +} + +// mergeConflictValueBoth merges a conflicting list or map keeping both entries, yours first. +func mergeConflictValueBoth(base, mine, agent any) any { + mineSlice, mineIsList := toAnySlice(mine) + agentSlice, agentIsList := toAnySlice(agent) + if mineIsList && agentIsList { + baseSlice, _ := toAnySlice(base) + mineAdded := sliceAdditions(baseSlice, mineSlice) + agentAdded := sliceAdditions(baseSlice, agentSlice) + var merged []any + for _, bItem := range baseSlice { + if sliceContainsDeep(mineSlice, bItem) && sliceContainsDeep(agentSlice, bItem) { + merged = append(merged, cloneAnyValue(bItem)) + } + } + for _, item := range mineAdded { + merged = append(merged, cloneAnyValue(item)) + } + for _, item := range agentAdded { + if !sliceContainsDeep(mineAdded, item) { + merged = append(merged, cloneAnyValue(item)) + } + } + return merged + } + if mineMap, okM := mine.(map[string]any); okM { + if agentMap, okA := agent.(map[string]any); okA { + out := make(map[string]any, len(mineMap)+len(agentMap)) + for k, v := range agentMap { + out[k] = cloneAnyValue(v) + } + for k, v := range mineMap { + out[k] = cloneAnyValue(v) + } + return out + } + } + return cloneAnyValue(mine) +} + +func sliceContainsDeep(s []any, target any) bool { + for _, item := range s { + if yamlDeepEqual(item, target) { + return true + } + } + return false +} + +func yamlDeepEqual(a, b any) bool { + if reflect.DeepEqual(a, b) { + return true + } + ba, ea := yaml.Marshal(a) + bb, eb := yaml.Marshal(b) + return ea == nil && eb == nil && bytes.Equal(ba, bb) +} + +func cloneAnyValue(v any) any { + if v == nil { + return nil + } + switch x := v.(type) { + case map[string]any: + out := make(map[string]any, len(x)) + for k, val := range x { + out[k] = cloneAnyValue(val) + } + return out + case []any: + out := make([]any, len(x)) + for i, val := range x { + out[i] = cloneAnyValue(val) + } + return out + default: + return v + } +} + +func applyObjectFieldValue(obj *sceneformat.ObjectDoc, field string, val any) { + if obj == nil || field == "" { + return + } + if strings.HasPrefix(field, "properties.") { + rest := strings.Split(strings.TrimPrefix(field, "properties."), ".") + if obj.Properties == nil { + obj.Properties = make(map[string]any) + } + setNestedMapValue(obj.Properties, rest, val) + if len(obj.Properties) == 0 { + obj.Properties = nil + } + return + } + if strings.HasPrefix(field, "components.") { + rest := strings.Split(strings.TrimPrefix(field, "components."), ".") + if obj.Components == nil { + obj.Components = make(map[string]any) + } + setNestedMapValue(obj.Components, rest, val) + if len(obj.Components) == 0 { + obj.Components = nil + } + return + } + + switch field { + case "name": + if s, ok := val.(string); ok { + obj.Name = s + } + case "prefab": + if s, ok := val.(string); ok { + obj.Prefab = s + } + case "x": + if f, ok := reviewAsFloat32(val); ok { + obj.X = f + } + case "y": + if f, ok := reviewAsFloat32(val); ok { + obj.Y = f + } + case "posZ": + if f, ok := reviewAsFloat32(val); ok { + obj.PosZ = f + } + case "z": + if n, ok := reviewAsInt(val); ok { + obj.Z = n + } + case "rotation": + if f, ok := reviewAsFloat32(val); ok { + obj.Rotation = f + } + case "scaleX": + if val == nil { + obj.ScaleX = nil + } else if f, ok := reviewAsFloat32(val); ok { + obj.ScaleX = &f + } + case "scaleY": + if val == nil { + obj.ScaleY = nil + } else if f, ok := reviewAsFloat32(val); ok { + obj.ScaleY = &f + } + case "alpha": + if val == nil { + obj.Alpha = nil + } else if f, ok := reviewAsFloat32(val); ok { + obj.Alpha = &f + } + case "flipX": + if b, ok := val.(bool); ok { + obj.FlipX = b + } + case "flipY": + if b, ok := val.(bool); ok { + obj.FlipY = b + } + case "material": + if s, ok := val.(string); ok { + obj.Material = s + } + case "mesh": + if s, ok := val.(string); ok { + obj.Mesh = s + } + case "model": + if s, ok := val.(string); ok { + obj.Model = s + } + } +} + +func setNestedMapValue(m map[string]any, parts []string, val any) { + if len(parts) == 0 { + return + } + if len(parts) == 1 { + if val == nil { + delete(m, parts[0]) + } else { + m[parts[0]] = cloneAnyValue(val) + } + return + } + sub, ok := m[parts[0]].(map[string]any) + if !ok { + if val == nil { + return + } + sub = make(map[string]any) + m[parts[0]] = sub + } + setNestedMapValue(sub, parts[1:], val) + if len(sub) == 0 { + delete(m, parts[0]) + } +} + +func reviewAsFloat32(v any) (float32, bool) { + switch x := v.(type) { + case float32: + return x, !math.IsNaN(float64(x)) && !math.IsInf(float64(x), 0) + case float64: + return float32(x), !math.IsNaN(x) && !math.IsInf(x, 0) + case int: + return float32(x), true + case int64: + return float32(x), true + case uint64: + return float32(x), true + default: + return 0, false + } +} + +func reviewAsInt(v any) (int, bool) { + switch x := v.(type) { + case int: + return x, true + case int64: + return int(x), true + case float64: + return int(x), true + case float32: + return int(x), true + default: + return 0, false + } +} + +// diffObjectFieldPaths returns the sorted dot-separated field paths where a and b differ. +func diffObjectFieldPaths(a, b *sceneformat.ObjectDoc) []string { + if a == nil && b == nil { + return nil + } + ma := objectToGenericMap(a) + mb := objectToGenericMap(b) + var out []string + diffGenericMaps("", ma, mb, &out) + slices.Sort(out) + return out +} + +func objectToGenericMap(o *sceneformat.ObjectDoc) map[string]any { + if o == nil { + return nil + } + cp := mergeCloneObjectDocPtr(o) + cp.Children = nil + raw, err := yaml.Marshal(cp) + if err != nil { + return nil + } + var m map[string]any + _ = yaml.Unmarshal(raw, &m) + return m +} + +func diffGenericMaps(prefix string, a, b map[string]any, out *[]string) { + keys := make([]string, 0, len(a)+len(b)) + seen := make(map[string]bool, len(a)+len(b)) + for k := range a { + seen[k] = true + keys = append(keys, k) + } + for k := range b { + if !seen[k] { + seen[k] = true + keys = append(keys, k) + } + } + slices.Sort(keys) + for _, k := range keys { + p := k + if prefix != "" { + p = prefix + "." + k + } + va, hasA := a[k] + vb, hasB := b[k] + if !hasA || !hasB { + *out = append(*out, p) + continue + } + if yamlDeepEqual(va, vb) { + continue + } + ma, okA := va.(map[string]any) + mb, okB := vb.(map[string]any) + if okA && okB { + diffGenericMaps(p, ma, mb, out) + continue + } + *out = append(*out, p) + } +} diff --git a/packages/game/editor/review_conflicts_test.go b/packages/game/editor/review_conflicts_test.go new file mode 100644 index 000000000..57c7e1453 --- /dev/null +++ b/packages/game/editor/review_conflicts_test.go @@ -0,0 +1,558 @@ +package editor_test + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const reviewConflictBaseScene = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: knight + name: Knight + x: 352 + y: 192 + z: 10 + - id: door_1 + name: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true + - id: crate_04 + x: 504 + y: 270 +` + +const reviewConflictAgentScene = `version: 3 +name: level_01 +virtualWidth: 640 +virtualHeight: 360 +layers: + - name: actors + space: world + order: 0 + objects: + - id: knight + name: Knight + x: 352 + y: 192 + z: 12 + - id: door_1 + name: door_1 + x: 574 + y: 248 + properties: + on_open: + - open: true + - reveal: coin_trail + - id: slime_03 + prefab: prefabs/slime.prefab.yaml + x: 452 + y: 208 +` + +func writeReviewConflictFile(t *testing.T, p, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatalf("mkdir %s: %v", p, err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", p, err) + } +} + +func newReviewConflictFixture(t *testing.T) (*editor.Editor, string) { + t.Helper() + dir := t.TempDir() + writeReviewConflictFile(t, filepath.Join(dir, "game.yaml"), `version: 1 +name: conflict-demo +id: dev.nsgo.conflict-demo +appVersion: 1.0.0 +window: + width: 640 + height: 360 +autoload: + mainScene: level_01 + scenes: + - name: level_01 + path: scenes/level_01.scene.yaml +`) + writeReviewConflictFile(t, filepath.Join(dir, "scenes", "level_01.scene.yaml"), reviewConflictBaseScene) + writeReviewConflictFile(t, filepath.Join(dir, "prefabs", "slime.prefab.yaml"), "version: 1\nid: slime\nname: Slime\n") + + ed, err := editor.New(nil, nil) + if err != nil { + t.Fatalf("editor.New: %v", err) + } + if err := ed.OpenProject(dir); err != nil { + t.Fatalf("OpenProject: %v", err) + } + ed.WaitForProblems() + return ed, dir +} + +func startReviewConflictTurn(t *testing.T, ed *editor.Editor) { + t.Helper() + if err := ed.StartTurnReview(editor.ReviewTurnInput{ + Request: "Put slime patrols on the lower floors with a coin trail toward door_1.", + Files: []editor.ReviewFileInput{ + { + Path: "scenes/level_01.scene.yaml", + BeforeYAML: []byte(reviewConflictBaseScene), + AfterYAML: []byte(reviewConflictAgentScene), + Reasons: map[string]string{ + "door_1": "The trail stays hidden until the door opens.", + "slime_03": "Guards the coin trail from the upper plank.", + "knight": "Slimes draw at z 11; keep Knight above them.", + "crate_04": "Blocked the coin trail.", + }, + }, + }, + }); err != nil { + t.Fatalf("StartTurnReview: %v", err) + } +} + +func findSnapChange(snap editor.ReviewSnapshot, objID string) *editor.ReviewChange { + for i := range snap.Changes { + if snap.Changes[i].ObjectID == objID { + return &snap.Changes[i] + } + } + return nil +} + +// #1032 Acceptance 1: edit door_1 by hand while a turn changes the same list, check that Keep is refused +// with the blocker, pick Both, keep, and find both entries in the saved YAML, yours first, and verify +// one Undo restores everything. +func TestReviewConflictDoorListMergeBothYoursFirst(t *testing.T) { + ed, dir := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + + // Person edits door_1's on_open list by hand while the turn is pending. + if err := ed.SetProperty("door_1", "on_open", []any{ + map[string]any{"open": true}, + map[string]any{"sound": "sfx/door_creak.ogg"}, + }); err != nil { + t.Fatalf("SetProperty door_1 on_open: %v", err) + } + + snap := ed.ReviewStatus() + doorChange := findSnapChange(snap, "door_1") + if doorChange == nil { + t.Fatal("missing review change for door_1") + } + if len(doorChange.Conflicts) != 1 { + t.Fatalf("door_1 conflicts = %d, want 1", len(doorChange.Conflicts)) + } + c := doorChange.Conflicts[0] + if !c.IsList || c.Field != "properties.on_open" { + t.Fatalf("unexpected conflict metadata: %+v", c) + } + if len(c.MineLines) == 0 || c.MineLines[0].Author != editor.ReviewAuthorYou || !strings.Contains(c.MineLines[0].Text, "sfx/door_creak.ogg") { + t.Fatalf("MineLines = %+v, want you + sfx/door_creak.ogg", c.MineLines) + } + if len(c.AgentLines) == 0 || c.AgentLines[0].Author != editor.ReviewAuthorAgent || !strings.Contains(c.AgentLines[0].Text, "coin_trail") { + t.Fatalf("AgentLines = %+v, want agent + coin_trail", c.AgentLines) + } + + // Focus a different change so we verify Keep jumps directly to door_1. + if !ed.FocusReviewChange("slime_03") { + t.Fatal("FocusReviewChange(slime_03) failed") + } + + // Keep MUST be refused with "Choose how door_1 merges" and jump focus to door_1. + err := ed.KeepTurnReview() + if err == nil { + t.Fatal("KeepTurnReview succeeded despite unresolved conflict on door_1") + } + var blocked *editor.ReviewBlockedError + if !errors.As(err, &blocked) || !errors.Is(err, editor.ErrReviewBlocked) { + t.Fatalf("KeepTurnReview error = %T (%v), want *ReviewBlockedError wrapping ErrReviewBlocked", err, err) + } + if blocked.Blocker.Reason != "Choose how door_1 merges" { + t.Fatalf("blocker reason = %q, want %q", blocked.Blocker.Reason, "Choose how door_1 merges") + } + if got := ed.ReviewStatus().FocusedID; got != doorChange.ID { + t.Fatalf("focused change after blocked Keep = %q, want %q", got, doorChange.ID) + } + + // Pick Both -> blocker clears. + if err := ed.ResolveReviewConflict("door_1", editor.ReviewConflictBoth); err != nil { + t.Fatalf("ResolveReviewConflict Both: %v", err) + } + if blockers := ed.ReviewBlockers(); len(blockers) != 0 { + t.Fatalf("expected blockers cleared after choosing Both, got %+v", blockers) + } + + // Verify YAML lines tag both sides accurately ("you" first, then "agent"). + doorChange = findSnapChange(ed.ReviewStatus(), "door_1") + youIdx, agentIdx := -1, -1 + for i, ln := range doorChange.YAMLLines { + if strings.Contains(ln.Text, "sfx/door_creak.ogg") && ln.Author == editor.ReviewAuthorYou { + youIdx = i + } + if strings.Contains(ln.Text, "coin_trail") && ln.Author == editor.ReviewAuthorAgent { + agentIdx = i + } + } + if youIdx < 0 || agentIdx < 0 || youIdx >= agentIdx { + t.Fatalf("expected you line before agent line in YAML pane, got youIdx=%d agentIdx=%d lines=%+v", youIdx, agentIdx, doorChange.YAMLLines) + } + + // Keep the review -> saved YAML on disk has both entries, yours first. + if err := ed.KeepTurnReview(); err != nil { + t.Fatalf("KeepTurnReview after Both: %v", err) + } + savedBytes, err := os.ReadFile(filepath.Join(dir, "scenes", "level_01.scene.yaml")) + if err != nil { + t.Fatalf("read saved scene: %v", err) + } + savedStr := string(savedBytes) + posYours := strings.Index(savedStr, "sfx/door_creak.ogg") + posAgent := strings.Index(savedStr, "coin_trail") + if posYours < 0 || posAgent < 0 { + t.Fatalf("saved YAML missing merged entries:\n%s", savedStr) + } + if posYours >= posAgent { + t.Fatalf("expected yours (%d) before agent's (%d) in saved YAML:\n%s", posYours, posAgent, savedStr) + } + if obj, _, _ := ed.FindObject("slime_03"); obj == nil { + t.Fatal("expected slime_03 present after Keep") + } + + // One Undo reverts the kept turn (agent additions + merge result) in a single step, + // preserving the person's own manual edit. + if !ed.Undo() { + t.Fatal("expected Undo to revert kept review turn") + } + if obj, _, _ := ed.FindObject("slime_03"); obj != nil { + t.Fatal("expected slime_03 removed after one Undo") + } + afterUndoBytes, err := os.ReadFile(filepath.Join(dir, "scenes", "level_01.scene.yaml")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(afterUndoBytes), "coin_trail") { + t.Fatalf("expected agent's coin_trail undone in one step:\n%s", string(afterUndoBytes)) + } + if !strings.Contains(string(afterUndoBytes), "sfx/door_creak.ogg") { + t.Fatalf("expected person's manual door_creak edit preserved after undoing turn:\n%s", string(afterUndoBytes)) + } +} + +func TestReviewConflictMineAndAgentChoices(t *testing.T) { + for _, tc := range []struct { + name string + choice editor.ReviewConflictChoice + wantHas string + wantLacks string + }{ + {"mine", editor.ReviewConflictMine, "sfx/door_creak.ogg", "coin_trail"}, + {"agent", editor.ReviewConflictAgent, "coin_trail", "sfx/door_creak.ogg"}, + } { + t.Run(tc.name, func(t *testing.T) { + ed, dir := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + if err := ed.SetProperty("door_1", "on_open", []any{ + map[string]any{"open": true}, + map[string]any{"sound": "sfx/door_creak.ogg"}, + }); err != nil { + t.Fatal(err) + } + if err := ed.ResolveReviewConflict("door_1", tc.choice); err != nil { + t.Fatal(err) + } + if err := ed.KeepTurnReview(); err != nil { + t.Fatal(err) + } + saved, err := os.ReadFile(filepath.Join(dir, "scenes", "level_01.scene.yaml")) + if err != nil { + t.Fatal(err) + } + s := string(saved) + if !strings.Contains(s, tc.wantHas) { + t.Fatalf("expected %q in saved YAML:\n%s", tc.wantHas, s) + } + if strings.Contains(s, tc.wantLacks) { + t.Fatalf("did not expect %q in saved YAML:\n%s", tc.wantLacks, s) + } + }) + } +} + +func TestReviewDifferentFieldsAutoMergeWithoutConflict(t *testing.T) { + ed, dir := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + + // Agent edited door_1.properties.on_open; person moves door_1's x coordinate (a different field). + if err := ed.MoveObject("door_1", 590, 248); err != nil { + t.Fatal(err) + } + + doorChange := findSnapChange(ed.ReviewStatus(), "door_1") + if len(doorChange.Conflicts) != 0 { + t.Fatalf("expected 0 conflicts when editing different fields, got %+v", doorChange.Conflicts) + } + if len(ed.ReviewBlockers()) != 0 { + t.Fatalf("expected no Keep blocker, got %+v", ed.ReviewBlockers()) + } + if err := ed.KeepTurnReview(); err != nil { + t.Fatalf("KeepTurnReview failed: %v", err) + } + door, _, _ := ed.FindObject("door_1") + if door == nil || door.X != 590 { + t.Fatalf("door_1.X = %v, want 590", door) + } + saved, err := os.ReadFile(filepath.Join(dir, "scenes", "level_01.scene.yaml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(saved), "coin_trail") { + t.Fatalf("expected agent's on_open edit preserved alongside person's move:\n%s", string(saved)) + } +} + +func TestReviewHandEditYAMLParseErrorFixAndUndo(t *testing.T) { + ed, dir := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + + if err := ed.BeginReviewYAMLEdit("slime_03"); err != nil { + t.Fatalf("BeginReviewYAMLEdit: %v", err) + } + slime := findSnapChange(ed.ReviewStatus(), "slime_03") + if slime == nil || !slime.EditingYAML { + t.Fatal("expected slime_03 in EditingYAML mode") + } + + // Type invalid YAML: replace "x: 452" with "x 444" (missing colon). + brokenYAML := strings.Replace(slime.HandEditYAML, "x: 452", "x 444", 1) + if brokenYAML == slime.HandEditYAML { + t.Fatalf("fixture did not contain x: 452:\n%s", slime.HandEditYAML) + } + if err := ed.SetReviewYAMLDraft("slime_03", brokenYAML); err == nil { + t.Fatal("expected SetReviewYAMLDraft to fail on missing colon") + } + + slime = findSnapChange(ed.ReviewStatus(), "slime_03") + if slime.YAMLError == nil { + t.Fatal("expected YAMLError set on slime_03") + } + if !strings.Contains(slime.YAMLError.Title, "isn't valid YAML") { + t.Fatalf("unexpected error title: %q", slime.YAMLError.Title) + } + if slime.YAMLError.Fix == nil || slime.YAMLError.Fix.Label != "Add the colon" { + t.Fatalf("expected one-step fix 'Add the colon', got %+v", slime.YAMLError.Fix) + } + + // Header blocker names the failing line. + blockers := ed.ReviewBlockers() + if len(blockers) != 1 || blockers[0].Kind != "yaml_error" || blockers[0].Line != slime.YAMLError.Line { + t.Fatalf("unexpected blockers: %+v", blockers) + } + if !strings.HasPrefix(blockers[0].Reason, "Fix YAML on line ") { + t.Fatalf("blocker reason = %q, want prefix 'Fix YAML on line '", blockers[0].Reason) + } + + // Done and Keep are both refused while YAML is invalid. + if err := ed.FinishReviewYAMLEdit("slime_03"); !errors.Is(err, editor.ErrReviewYAMLInvalid) { + t.Fatalf("FinishReviewYAMLEdit err = %v, want ErrReviewYAMLInvalid", err) + } + if err := ed.KeepTurnReview(); !errors.Is(err, editor.ErrReviewBlocked) { + t.Fatalf("KeepTurnReview err = %v, want ErrReviewBlocked", err) + } + + // Apply the offered one-step fix. + if err := ed.ApplyReviewYAMLFix("slime_03"); err != nil { + t.Fatalf("ApplyReviewYAMLFix: %v", err) + } + slime = findSnapChange(ed.ReviewStatus(), "slime_03") + if slime.YAMLError != nil { + t.Fatalf("expected YAMLError cleared after fix, got %+v", slime.YAMLError) + } + if len(ed.ReviewBlockers()) != 0 { + t.Fatalf("expected blockers cleared after fix, got %+v", ed.ReviewBlockers()) + } + + // Live effective scene doc updates immediately as soon as YAML parses. + effDoc := ed.ReviewEffectiveSceneDoc("scenes/level_01.scene.yaml") + if effDoc == nil { + t.Fatal("ReviewEffectiveSceneDoc returned nil") + } + var effSlime *sceneformat.ObjectDoc + for i := range effDoc.Layers[0].Objects { + if effDoc.Layers[0].Objects[i].ID == "slime_03" { + effSlime = &effDoc.Layers[0].Objects[i] + } + } + if effSlime == nil || effSlime.X != 444 { + t.Fatalf("live viewport slime_03 = %+v, want X=444", effSlime) + } + + // Edited line is tagged "you". + foundYou := false + for _, ln := range slime.YAMLLines { + if strings.Contains(ln.Text, "x: 444") && ln.Author == editor.ReviewAuthorYou { + foundYou = true + break + } + } + if !foundYou { + t.Fatalf("expected x: 444 line tagged 'you' in YAMLLines: %+v", slime.YAMLLines) + } + + // Done succeeds now, Keep lands x: 444 on disk, and one Undo reverts the whole turn. + if err := ed.FinishReviewYAMLEdit("slime_03"); err != nil { + t.Fatalf("FinishReviewYAMLEdit after fix: %v", err) + } + if err := ed.KeepTurnReview(); err != nil { + t.Fatalf("KeepTurnReview after fix: %v", err) + } + keptSlime, _, _ := ed.FindObject("slime_03") + if keptSlime == nil || keptSlime.X != 444 { + t.Fatalf("kept slime_03 = %+v, want X=444", keptSlime) + } + savedBytes, err := os.ReadFile(filepath.Join(dir, "scenes", "level_01.scene.yaml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(savedBytes), "x: 444") { + t.Fatalf("saved scene YAML missing x: 444:\n%s", string(savedBytes)) + } + if !ed.Undo() { + t.Fatal("expected single Undo to revert turn including hand edit") + } + if obj, _, _ := ed.FindObject("slime_03"); obj != nil { + t.Fatal("expected slime_03 removed after single Undo") + } +} + +func TestReviewYAMLValidationRefusesUnknownFieldsDuplicateKeysOversizedAndYouOnly(t *testing.T) { + ed, _ := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + + if err := ed.BeginReviewYAMLEdit("slime_03"); err != nil { + t.Fatal(err) + } + baseYAML := findSnapChange(ed.ReviewStatus(), "slime_03").HandEditYAML + + // Unknown field must be refused. + if err := ed.SetReviewYAMLDraft("slime_03", baseYAML+"\n unknownBogusField: 123"); err == nil { + t.Fatal("expected unknown field to be refused") + } + // Duplicate key must be refused. + if err := ed.SetReviewYAMLDraft("slime_03", baseYAML+"\n x: 100"); err == nil { + t.Fatal("expected duplicate key to be refused") + } + // Oversized YAML draft (>256 KiB) must be refused. + if err := ed.SetReviewYAMLDraft("slime_03", baseYAML+"\n name: "+strings.Repeat("a", 300<<10)); err == nil { + t.Fatal("expected oversized YAML draft to be refused") + } + // NUL byte must be refused. + if err := ed.SetReviewYAMLDraft("slime_03", baseYAML+"\x00"); err == nil { + t.Fatal("expected NUL byte in YAML draft to be refused") + } + // Undo my typing restores clean state. + if err := ed.UndoReviewYAMLTyping("slime_03"); err != nil { + t.Fatalf("UndoReviewYAMLTyping: %v", err) + } + slime := findSnapChange(ed.ReviewStatus(), "slime_03") + if slime.YAMLError != nil || slime.EditingYAML || slime.HandEdited { + t.Fatalf("expected clean state after Undo my typing: err=%v editing=%v handEdited=%v", slime.YAMLError, slime.EditingYAML, slime.HandEdited) + } + if len(ed.ReviewBlockers()) != 0 { + t.Fatalf("expected blockers cleared after Undo my typing, got %+v", ed.ReviewBlockers()) + } +} + +func TestReviewUIConflictAndYAMLEditInteractionAndFocusStability(t *testing.T) { + ed, _ := newReviewConflictFixture(t) + startReviewConflictTurn(t, ed) + + if err := ed.SetProperty("door_1", "on_open", []any{ + map[string]any{"open": true}, + map[string]any{"sound": "sfx/door_creak.ogg"}, + }); err != nil { + t.Fatal(err) + } + + macEnv := nsgotest.Environment(core.Environment{OS: core.OSMacOS, Idiom: core.IdiomDesktop, Dark: true, Locale: "en-US"}) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), macEnv) + + // Blocker pill jumps to door_1; pressing Both resolves the conflict. + app.Press("id:review-blocker-pill") + doorChange := findSnapChange(ed.ReviewStatus(), "door_1") + if ed.ReviewStatus().FocusedID != doorChange.ID { + t.Fatalf("expected blocker press to focus door_1 (%s), got %s", doorChange.ID, ed.ReviewStatus().FocusedID) + } + app.Press("id:review-conflict-both-door_1") + if len(ed.ReviewBlockers()) != 0 { + t.Fatalf("expected blockers cleared after pressing Both, got %+v", ed.ReviewBlockers()) + } + + // Focus slime_03, click Edit, verify YAML input mounts stably and does not let single-letter Review shortcuts fire while typing. + slimeChange := findSnapChange(ed.ReviewStatus(), "slime_03") + app.Press("id:review-card-focus-" + slimeChange.ID) + app.Press("id:review-yaml-edit") + app.Settle() + if !app.Exists("id:review-yaml-input") { + t.Fatal("expected review-yaml-input mounted after pressing Edit") + } + origSlimeYAML := findSnapChange(ed.ReviewStatus(), "slime_03").HandEditYAML + app.Press("id:review-yaml-input") + app.Settle() + app.Key("x") + app.Key("j") + app.Key("k") + app.Key("b") + app.Settle() + if cur := findSnapChange(ed.ReviewStatus(), "slime_03"); cur == nil || cur.Reverted { + t.Fatalf("typing 'x' in review-yaml-input must not revert slime_03: %+v", cur) + } + if ed.ReviewStatus().FocusedID != slimeChange.ID { + t.Fatalf("typing 'j'/'k' in review-yaml-input must not move focus away from slime_03") + } + if ed.ReviewPeekingBefore() { + t.Fatal("typing 'b' in review-yaml-input must not activate peek-before") + } + + // Inject broken YAML ("x 444" missing colon), press Fix, press Done, press Keep. + app.Post(func() { + _ = ed.SetReviewYAMLDraft("slime_03", strings.Replace(origSlimeYAML, "x: 452", "x 444", 1)) + }) + app.Settle() + if !app.Exists("id:review-yaml-error") { + t.Fatal("expected review-yaml-error alert card mounted") + } + app.Press("id:review-yaml-fix") + app.Settle() + app.Press("id:review-yaml-done") + app.Settle() + app.Press("id:review-keep") + app.Settle() + + if ed.ReviewOpen() || ed.HasPendingReview() { + t.Fatal("expected review closed and kept") + } + if obj, _, _ := ed.FindObject("slime_03"); obj == nil || obj.X != 444 { + t.Fatalf("slime_03 after UI Keep = %+v, want X=444", obj) + } +} diff --git a/packages/game/editor/review_notes.go b/packages/game/editor/review_notes.go index df5dedae7..87a9adda4 100644 --- a/packages/game/editor/review_notes.go +++ b/packages/game/editor/review_notes.go @@ -303,7 +303,22 @@ func (e *Editor) SetReviewViewRound(round int) error { } for _, ch := range e.review.changes { ch.syncFromVersion(ch.VersionFor(round)) + if round == latest { + if ch.HandEdited && ch.handEditObj != nil { + if ch.Kind == ReviewChangeAdded { + ch.Detail = formatAddedObjectDetail(ch.handEditObj) + } else if ch.Kind == ReviewChangeChanged && ch.beforeObj != nil { + ch.Detail = formatChangedObjectDetail(ch.beforeObj, ch.handEditObj, ch.beforeLayer, ch.afterLayer) + } + } + if ch.HandEdited || ch.EditingYAML || len(ch.Conflicts) > 0 || ch.YAMLError != nil { + if fs := e.review.filesByPath[ch.File]; fs != nil { + e.refreshReviewChangeYAMLLines(fs, ch) + } + } + } } + e.review.yamlEditSessionRev++ e.frameFocusedReviewChange() e.bumpReviewUIRev() e.notify() @@ -1148,6 +1163,14 @@ func (e *Editor) ApplyReviewRedo(redos []ReviewRedoChange) error { ch.Versions = append(ch.Versions, nextVer) ch.syncFromVersion(nextVer) + ch.EditingYAML = false + ch.YAMLError = nil + ch.HandEdited = false + ch.handEditObj = nil + ch.handEditBaseObj = nil + ch.HandEditFields = nil + ch.handEditLineNums = nil + ch.HandEditYAML = "" ch.Seen = false ch.Reverted = false ch.RedoneInRound = nextRound @@ -1170,6 +1193,7 @@ func (e *Editor) ApplyReviewRedo(redos []ReviewRedoChange) error { e.review.round = nextRound e.review.viewRound = nextRound + e.review.yamlEditSessionRev++ if e.review.roundRedone == nil { e.review.roundRedone = make(map[int]int) } @@ -1177,6 +1201,19 @@ func (e *Editor) ApplyReviewRedo(redos []ReviewRedoChange) error { e.review.composingID = "" e.review.noteDraft = "" + e.syncAllReviewConflicts() + for _, ch := range e.review.changes { + if ch.HandEdited && ch.handEditObj != nil { + if ch.Kind == ReviewChangeAdded { + ch.Detail = formatAddedObjectDetail(ch.handEditObj) + } else if ch.Kind == ReviewChangeChanged && ch.beforeObj != nil { + ch.Detail = formatChangedObjectDetail(ch.beforeObj, ch.handEditObj, ch.beforeLayer, ch.afterLayer) + } + if fs := e.review.filesByPath[ch.File]; fs != nil { + e.refreshReviewChangeYAMLLines(fs, ch) + } + } + } e.refreshPrefabImpacts() e.frameFocusedReviewChange() e.Status = e.ReviewRoundBannerText() diff --git a/packages/game/editor/review_ui.go b/packages/game/editor/review_ui.go index f219c9b9f..3662b2d0a 100644 --- a/packages/game/editor/review_ui.go +++ b/packages/game/editor/review_ui.go @@ -46,6 +46,7 @@ func ReviewScreenView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core rightRef := &core.Ref{} revertBtnRef := &core.Ref{} filterInputRef := &core.Ref{} + yamlInputRef := &core.Ref{} regionRefs := map[string]*core.Ref{ reviewRegionHeader: headerRef, @@ -124,7 +125,7 @@ func ReviewScreenView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core return } if ed.IsTyping() { - if filterInputRef.HoldsFocus() { + if filterInputRef.HoldsFocus() || yamlInputRef.HoldsFocus() { headerRef.Focus() } return @@ -268,7 +269,7 @@ func ReviewScreenView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core Children: []core.Node{ reviewSidebarView(cx, ed, reviewRev, activeRegion, listRef, filterInputRef), reviewCenterView(cx, ed, reviewRev, activeRegion, centerRef), - reviewRightView(cx, ed, reviewRev, activeRegion, rightRef), + reviewRightView(cx, ed, reviewRev, activeRegion, rightRef, yamlInputRef), }, }, revertModal, @@ -482,7 +483,12 @@ func reviewHeaderView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], headerChildren = append(headerChildren, core.View{Style: core.Style{FlexGrow: 1}}) if blocked { - reason := snap.Blockers[0].Reason + blocker := snap.Blockers[0] + reason := blocker.Reason + blockerRole := p.Warning + if blocker.Kind == "yaml_error" { + blockerRole = p.Removed + } headerChildren = append(headerChildren, core.View{ TestID: "review-blocker-pill", Role: core.RoleButton, @@ -495,9 +501,9 @@ func reviewHeaderView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], Padding: core.Symmetric(0, 10), Gap: 8, CornerRadius: 6, - Background: p.Warning.Fill, + Background: blockerRole.Fill, BorderWidth: 1, - BorderColor: p.Warning.Edge, + BorderColor: blockerRole.Edge, FlexShrink: 0, FocusVisible: p.FocusRing(2), }, @@ -507,11 +513,11 @@ func reviewHeaderView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], Children: []core.Node{ core.Icon{ SVG: lucide.TriangleAlert(), - Style: core.Style{Width: core.Pt(14), Height: core.Pt(14), Color: p.Warning.Fg}, + Style: core.Style{Width: core.Pt(14), Height: core.Pt(14), Color: blockerRole.Fg}, }, core.Text{ Content: reason, - Style: core.Style{FontSize: 12, FontWeight: 500, Color: p.Warning.Fg}, + Style: core.Style{FontSize: 12, FontWeight: 500, Color: blockerRole.Fg}, }, }, }) @@ -1780,6 +1786,50 @@ func reviewCardView(cx *core.Scope, ed *Editor, p SpecPalette, snap ReviewSnapsh }) } + if !readOnly && len(ch.Conflicts) > 0 && !ch.Reverted { + cardChildren = append(cardChildren, reviewConflictCardView(ed, ch, p)) + } + + if !readOnly && ch.YAMLError != nil && !ch.Reverted { + cardChildren = append(cardChildren, core.View{ + TestID: "review-card-yaml-error-" + ch.ObjectID, + Style: core.Style{ + Margin: core.Edges{Left: 42, Right: 8, Bottom: 8}, + Padding: core.Symmetric(6, 10), + CornerRadius: 8, + Background: p.Removed.Fill, + BorderWidth: 1, + BorderColor: p.Removed.Edge, + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: []core.Node{ + core.Icon{SVG: lucide.TriangleAlert(), Style: core.Style{Width: core.Pt(12), Height: core.Pt(12), Color: p.Removed.Fg}}, + core.Text{Content: ch.YAMLError.Title, Style: core.Style{FontSize: 11.5, FontWeight: 500, Color: p.Removed.Fg}}, + }, + }) + } else if !readOnly && ch.HandEdited && !ch.Reverted { + cardChildren = append(cardChildren, core.View{ + TestID: "review-card-hand-edited-" + ch.ObjectID, + Style: core.Style{ + Margin: core.Edges{Left: 42, Right: 8, Bottom: 8}, + Padding: core.Symmetric(4, 8), + CornerRadius: 6, + Background: p.Bg, + BorderWidth: 1, + BorderColor: p.LineRaised, + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + }, + Children: []core.Node{ + core.Icon{SVG: lucide.Pencil(), Style: core.Style{Width: core.Pt(11), Height: core.Pt(11), Color: p.TextMuted}}, + core.Text{Content: "Edited in review · tagged you", Style: core.Style{FontSize: 11, Color: p.TextMuted}}, + }, + }) + } + if ch.Blocker != "" && !ch.Reverted { cardChildren = append(cardChildren, core.View{ Style: core.Style{ @@ -1814,6 +1864,170 @@ func reviewCardView(cx *core.Scope, ed *Editor, p SpecPalette, snap ReviewSnapsh } } +func reviewConflictCardView(ed *Editor, ch *ReviewChange, p SpecPalette) core.Node { + resolved := ch.ConflictChoice != ReviewConflictUnresolved + changeID := ch.ID + objID := ch.ObjectID + if objID == "" { + objID = ch.Title + } + + boxBg := p.Warning.Fill + boxBorder := p.Warning.Edge + headFg := p.Warning.Fg + headIcon := lucide.TriangleAlert() + headIconColor := p.Warning.Fg + headTitle := fmt.Sprintf("You also edited %s", ch.Title) + segBorder := p.Warning.Edge + + if resolved { + boxBg = p.Bg + boxBorder = p.LineRaised + headFg = p.TextPrimary + headIcon = lucide.Check() + headIconColor = p.Added.Fg + segBorder = p.LineRaised + switch ch.ConflictChoice { + case ReviewConflictBoth: + headTitle = "Merged both, yours first" + case ReviewConflictMine: + headTitle = "Merged: your edit only" + case ReviewConflictAgent: + headTitle = "Merged: the agent’s edit only" + } + } + + var diffLines []core.Node + for _, c := range ch.Conflicts { + for _, ml := range c.MineLines { + diffLines = append(diffLines, reviewConflictLineRow(string(ml.Author), ml.Sign+" "+ml.Text, p)) + } + for _, al := range c.AgentLines { + diffLines = append(diffLines, reviewConflictLineRow(string(al.Author), al.Sign+" "+al.Text, p)) + } + } + + segBtn := func(testID, label string, choice ReviewConflictChoice) core.Node { + selected := ch.ConflictChoice == choice + bg := core.Transparent + fg := p.TextMuted + if selected { + bg = p.LineRaised + fg = p.TextPrimary + } + return core.View{ + TestID: testID, + Role: core.RoleButton, + Label: fmt.Sprintf("%s for %s", label, ch.Title), + Focusable: func() bool { return true }, + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + Height: core.Pt(26), + Padding: core.Symmetric(0, 8), + CornerRadius: 6, + Background: bg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.ResolveReviewConflict(changeID, choice)) + }, + Children: []core.Node{ + core.Text{ + Content: label, + Style: core.Style{ + FontSize: 12, + FontWeight: 500, + Color: fg, + }, + }, + }, + } + } + + return core.View{ + TestID: "review-conflict-card-" + objID, + Role: core.RoleGroup, + Label: "Conflict on " + ch.Title, + Style: core.Style{ + Margin: core.Edges{Right: 8, Bottom: 8, Left: 42}, + Padding: core.All(12), + CornerRadius: 8, + Background: boxBg, + BorderWidth: 1, + BorderColor: boxBorder, + Gap: 8, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.Icon{ + SVG: headIcon, + Style: core.Style{Width: core.Pt(14), Height: core.Pt(14), Color: headIconColor, FlexShrink: 0}, + }, + core.Text{ + TestID: "review-conflict-title-" + objID, + Content: headTitle, + Style: core.Style{FontSize: 12.5, FontWeight: 500, Color: headFg}, + }, + }, + }, + core.View{ + Style: core.Style{Gap: 3}, + Children: diffLines, + }, + core.View{ + Style: core.Style{ + Direction: core.Row, + Gap: 2, + Padding: core.All(2), + CornerRadius: 8, + Background: p.Bg, + BorderWidth: 1, + BorderColor: segBorder, + }, + Children: []core.Node{ + segBtn("review-conflict-mine-"+objID, "Mine", ReviewConflictMine), + segBtn("review-conflict-agent-"+objID, "Agent's", ReviewConflictAgent), + segBtn("review-conflict-both-"+objID, "Both", ReviewConflictBoth), + }, + }, + }, + } +} + +func reviewConflictLineRow(author, text string, p SpecPalette) core.Node { + return core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter}, + Children: []core.Node{ + core.Text{ + Content: author, + Style: core.Style{ + Width: core.Pt(48), + FlexShrink: 0, + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextFaint, + }, + }, + core.Text{ + Content: text, + Style: core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinWidth: core.Pt(0), + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextSecondary, + }, + }, + }, + } +} + func reviewKindSpecRole(p SpecPalette, kind ReviewChangeKind) SpecRole { switch kind { case ReviewChangeAdded: @@ -2738,26 +2952,170 @@ func reviewGenericFileCenterView(p SpecPalette, ch *ReviewChange) core.Node { } } -// --- Right pane: Why + YAML lines touched --- +// --- Right pane: Why + YAML lines touched + in-place YAML editing --- -func reviewRightView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], activeRegion *core.Signal[string], rightRef *core.Ref) core.Node { - return core.Dynamic(func(cx *core.Scope) core.Node { +func reviewRightView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], activeRegion *core.Signal[string], rightRef, yamlInputRef *core.Ref) core.Node { + // Key the YAML input strictly on (editing, changeID, yamlEditSessionRev) — NEVER on reviewRev — + // so typing in the multiline YAML editor never remounts ui.Input, steals focus, or resets caret! + yamlEditKey := core.NewMemo(cx, func() string { + _ = reviewRev.Get() + if ed.ReviewViewingReadOnlyRound() { + return "" + } + ch := ed.review.changesByID[ed.review.focusedID] + if ch == nil || !ch.EditingYAML { + return "" + } + return fmt.Sprintf("%s:%d", ch.ID, ed.review.yamlEditSessionRev) + }) + + headerNode := core.Dynamic(func(cx *core.Scope) core.Node { _ = reviewRev.Get() p := ed.SpecPalette(cx) ch := ed.review.changesByID[ed.review.focusedID] + readOnly := ed.ReviewViewingReadOnlyRound() title := "YAML" - whyText := "" - var ylines []ReviewYAMLLine - reverted := false + var headerActions []core.Node if ch != nil { title = ch.Title + " · YAML" if ch.FileKind == ReviewFileGo { title = ch.Title + " · diff" } - whyText = ch.Why - ylines = ch.YAMLLines + changeID := ch.ID + editing := !readOnly && ch.EditingYAML + canEdit := !readOnly && !editing && ch.CanEditYAML() + yamlBroken := ch.YAMLError != nil + + if canEdit { + headerActions = append(headerActions, core.View{ + TestID: "review-yaml-edit", + Role: core.RoleButton, + Label: "Edit YAML for " + ch.Title, + Focusable: func() bool { return true }, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Height: core.Pt(28), + Padding: core.Symmetric(0, 10), + Gap: 6, + CornerRadius: 6, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.BeginReviewYAMLEdit(changeID)) + }, + Children: []core.Node{ + core.Icon{ + SVG: lucide.Pencil(), + Style: core.Style{Width: core.Pt(13), Height: core.Pt(13), Color: p.TextSecondary}, + }, + core.Text{ + Content: "Edit", + Style: core.Style{FontSize: 12.5, Color: p.TextSecondary}, + }, + }, + }) + } + if editing { + doneStyle := core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 12), + CornerRadius: 6, + Background: p.Accent.Fg, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + } + if yamlBroken { + doneStyle.Opacity = core.Alpha(0.45) + } + headerActions = append(headerActions, + core.Text{ + TestID: "review-yaml-editing-label", + Content: "Editing", + Style: core.Style{FontSize: 11.5, Color: p.TextFaint, FlexShrink: 0}, + }, + core.View{ + TestID: "review-yaml-done", + Role: core.RoleButton, + Label: "Done editing YAML", + Focusable: func() bool { return true }, + Style: doneStyle, + OnPress: func(core.PressEvent) { + if err := ed.FinishReviewYAMLEdit(changeID); err != nil && !errors.Is(err, ErrReviewYAMLInvalid) { + ed.report(err) + } + }, + Children: []core.Node{ + core.Text{ + Content: "Done", + Style: core.Style{FontSize: 12.5, FontWeight: 600, Color: p.Accent.OnFill}, + }, + }, + }, + ) + } + } + + return core.View{ + Style: core.Style{ + Height: core.Pt(44), + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 8, + Padding: core.Edges{Left: 14, Right: 10}, + Borders: core.Edges{Bottom: 1}, + BorderColor: p.Line, + FlexShrink: 0, + }, + Children: append([]core.Node{ + core.Text{ + TestID: "review-right-title", + Content: title, + MaxLines: 1, + Style: core.Style{ + FontSize: 12.5, + FontWeight: 600, + Color: p.TextPrimary, + FlexGrow: 1, + MinWidth: core.Pt(0), + Overflow: core.Hidden, + }, + }, + }, headerActions...), + } + }) + + diffBodyNode := core.Dynamic(func(cx *core.Scope) core.Node { + _ = reviewRev.Get() + p := ed.SpecPalette(cx) + ch := ed.review.changesByID[ed.review.focusedID] + readOnly := ed.ReviewViewingReadOnlyRound() + viewRound := ed.ReviewViewRound() + + whyText := "" + var ylines []ReviewYAMLLine + reverted := false + editing := false + yamlBroken := false + if ch != nil { reverted = ch.Reverted + if readOnly { + ver := ch.VersionFor(viewRound) + whyText = ver.Why + ylines = ver.YAMLLines + } else { + whyText = ch.Why + ylines = ch.YAMLLines + editing = ch.EditingYAML + yamlBroken = ch.YAMLError != nil + } } var bodyKids []core.Node @@ -2814,69 +3172,268 @@ func reviewRightView(cx *core.Scope, ed *Editor, reviewRev *core.Memo[uint64], a }) } + scrollStyle := core.Style{ + FlexGrow: 1, + FlexBasis: core.Pt(0), + MinHeight: core.Pt(0), + Padding: core.Symmetric(10, 0), + } + if editing { + scrollStyle.Background = p.Inset + scrollStyle.Borders = core.Edges{Bottom: 1} + if yamlBroken { + scrollStyle.BorderColor = p.Removed.Edge + } else { + scrollStyle.BorderColor = p.Accent.Edge + } + } + bodyKids = append(bodyKids, ui.ScrollView{ - TestID: "review-yaml-scroll", + TestID: "review-yaml-scroll", + Style: scrollStyle, + Children: []core.Node{reviewYAMLDiffLinesView(p, ylines)}, + }) + + return core.View{ Style: core.Style{ FlexGrow: 1, FlexBasis: core.Pt(0), MinHeight: core.Pt(0), - Padding: core.Symmetric(10, 0), }, - Children: []core.Node{reviewYAMLDiffLinesView(p, ylines)}, - }) + Children: bodyKids, + } + }) - base := core.Style{ - Width: core.Pt(392), - FlexShrink: 0, - Background: p.Panel, - Borders: core.Edges{Left: 1}, - BorderColor: p.Line, - MinHeight: core.Pt(0), + yamlEditorNode := core.Dynamic(func(cx *core.Scope) core.Node { + key := yamlEditKey.Get() + if key == "" { + return core.View{Style: core.Style{Height: core.Pt(0), FlexShrink: 0}} } + ch := ed.review.changesByID[ed.review.focusedID] + if ch == nil || !ch.EditingYAML { + return core.View{Style: core.Style{Height: core.Pt(0), FlexShrink: 0}} + } + changeID := ch.ID + title := ch.Title + draftSig := core.NewSignal(cx, ch.HandEditYAML) + return core.View{ - Ref: rightRef, - TestID: "review-right-pane", - Role: core.RoleRegion, - Label: "Why and YAML diff", - Focusable: func() bool { return true }, - OnFocusIn: func() { - if activeRegion.GetUntracked() != "" && activeRegion.GetUntracked() != reviewRegionRight { - activeRegion.Set("") + TestID: "review-yaml-editor-box", + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Padding: core.All(12), + Background: p.Inset, + Borders: core.Edges{Top: 1}, + BorderColor: p.Line, + Gap: 6, + FlexShrink: 0, } }, - StyleFunc: func() core.Style { - return reviewRegionStyle(p, activeRegion, reviewRegionRight, base) + Children: []core.Node{ + core.Text{ + Content: "EDIT YAML IN PLACE", + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + FontSize: 11, + FontWeight: 600, + LetterSpacing: 0.6, + Color: p.TextFaint, + } + }, + }, + specInputField(cx, ed, ui.Input{ + Ref: yamlInputRef, + TestID: "review-yaml-input", + Label: "Edit YAML for " + title, + Multiline: true, + Value: draftSig.Get, + OnChange: func(v string) { + draftSig.Set(v) + _ = ed.SetReviewYAMLDraft(changeID, v) + }, + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + return core.Style{ + Width: core.Pct(100), + Height: core.Pt(160), + Background: p.Bg, + BorderWidth: 1, + BorderColor: p.LineRaised, + CornerRadius: 6, + Padding: core.All(8), + FontSize: 11.5, + FontFamily: core.FontMonospace, + Color: p.TextPrimary, + FocusVisible: p.FocusRing(-2), + } + }, + }), }, - Children: append([]core.Node{ - core.View{ + } + }) + + yamlFooterNode := core.Dynamic(func(cx *core.Scope) core.Node { + _ = reviewRev.Get() + p := ed.SpecPalette(cx) + if ed.ReviewViewingReadOnlyRound() { + return core.View{Style: core.Style{Height: core.Pt(0), FlexShrink: 0}} + } + ch := ed.review.changesByID[ed.review.focusedID] + if ch == nil { + return core.View{Style: core.Style{Height: core.Pt(0), FlexShrink: 0}} + } + changeID := ch.ID + if ch.YAMLError != nil { + errObj := ch.YAMLError + var errActions []core.Node + if errObj.Fix != nil { + errActions = append(errActions, core.View{ + TestID: "review-yaml-fix", + Role: core.RoleButton, + Label: errObj.Fix.Label, + Focusable: func() bool { return true }, Style: core.Style{ - Height: core.Pt(44), - Direction: core.Row, - AlignItems: core.AlignCenter, - Padding: core.Symmetric(0, 14), - Borders: core.Edges{Bottom: 1}, - BorderColor: p.Line, - FlexShrink: 0, + Height: core.Pt(28), + Padding: core.Symmetric(0, 12), + CornerRadius: 8, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.ApplyReviewYAMLFix(changeID)) }, Children: []core.Node{ core.Text{ - TestID: "review-right-title", - Content: title, - MaxLines: 1, - Style: core.Style{ - FontSize: 12.5, - FontWeight: 600, - Color: p.TextPrimary, - FlexGrow: 1, - MinWidth: core.Pt(0), - Overflow: core.Hidden, + Content: errObj.Fix.Label, + Style: core.Style{FontSize: 12.5, Color: p.TextSecondary}, + }, + }, + }) + } + errActions = append(errActions, core.View{ + TestID: "review-yaml-undo", + Role: core.RoleButton, + Label: "Undo my typing", + Focusable: func() bool { return true }, + Style: core.Style{ + Height: core.Pt(28), + Padding: core.Symmetric(0, 8), + CornerRadius: 8, + AlignItems: core.AlignCenter, + JustifyContent: core.JustifyCenter, + FocusVisible: p.FocusRing(2), + }, + OnPress: func(core.PressEvent) { + ed.report(ed.UndoReviewYAMLTyping(changeID)) + }, + Children: []core.Node{ + core.Text{ + Content: "Undo my typing", + Style: core.Style{FontSize: 12.5, Color: p.TextMuted}, + }, + }, + }) + + return core.View{ + TestID: "review-yaml-error", + Role: core.RoleAlert, + Style: core.Style{ + Margin: core.Edges{Top: 10, Right: 14, Bottom: 14, Left: 14}, + Padding: core.All(12), + CornerRadius: 12, + Background: p.Removed.Fill, + BorderWidth: 1, + BorderColor: p.Removed.Edge, + Gap: 8, + FlexShrink: 0, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 8}, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Width: core.Pt(6), + Height: core.Pt(6), + CornerRadius: 3, + Background: p.Removed.Fg, + FlexShrink: 0, + }, + }, + core.Text{ + TestID: "review-yaml-error-title", + Content: errObj.Title, + Style: core.Style{FontSize: 12.5, FontWeight: 500, Color: p.Removed.Fg}, }, }, }, + core.Text{ + TestID: "review-yaml-error-message", + Content: errObj.Message, + Style: core.Style{FontSize: 12.5, Color: p.TextSecondary}, + }, + core.View{ + Style: core.Style{Direction: core.Row, Gap: 8}, + Children: errActions, + }, + }, + } + } + if ch.EditingYAML { + return core.View{ + Style: core.Style{ + Margin: core.Edges{Top: 8, Right: 14, Bottom: 12, Left: 14}, + FlexShrink: 0, + }, + Children: []core.Node{ + core.Text{ + TestID: "review-yaml-valid-hint", + Content: "Your edit joins this review; the agent sees it in round 2.", + Style: core.Style{FontSize: 12, Color: p.TextFaint}, + }, }, - }, bodyKids...), + } } + return core.View{Style: core.Style{Height: core.Pt(0), FlexShrink: 0}} }) + + return core.View{ + Ref: rightRef, + TestID: "review-right-pane", + Role: core.RoleRegion, + Label: "Why and YAML diff", + Focusable: func() bool { return true }, + OnFocusIn: func() { + if activeRegion.GetUntracked() != "" && activeRegion.GetUntracked() != reviewRegionRight { + activeRegion.Set("") + } + }, + StyleFunc: func() core.Style { + p := ed.SpecPalette(cx) + base := core.Style{ + Width: core.Pt(392), + FlexShrink: 0, + Background: p.Panel, + Borders: core.Edges{Left: 1}, + BorderColor: p.Line, + MinHeight: core.Pt(0), + Overflow: core.Hidden, + } + return reviewRegionStyle(p, activeRegion, reviewRegionRight, base) + }, + Children: []core.Node{ + headerNode, + diffBodyNode, + yamlEditorNode, + yamlFooterNode, + }, + } } func reviewYAMLDiffLinesView(p SpecPalette, lines []ReviewYAMLLine) core.Node { @@ -2900,6 +3457,7 @@ func reviewYAMLDiffLinesView(p SpecPalette, lines []ReviewYAMLLine) core.Node { if l.Error { bg = p.Removed.Fill fg = p.TextPrimary + signColor = p.Removed.Fg } lineNum := "" if l.Line > 0 { @@ -2909,47 +3467,78 @@ func reviewYAMLDiffLinesView(p SpecPalette, lines []ReviewYAMLLine) core.Node { if sign == "-" { sign = "−" } - nodes = append(nodes, core.View{ - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Padding: core.Symmetric(2, 12), - Gap: 6, - Background: bg, - }, - Children: []core.Node{ - core.Text{ - Content: lineNum, - Style: core.Style{ - Width: core.Pt(30), - FontFamily: core.FontMonospace, - FontSize: 11, - Color: p.TextFaint, - FlexShrink: 0, - }, + tagText := l.Tag + if tagText == "" && l.Author != ReviewAuthorNone { + tagText = string(l.Author) + } + tagColor := p.TextFaint + if l.Error { + if tagText == "" && l.Line > 0 { + tagText = fmt.Sprintf("line %d", l.Line) + } + tagColor = p.Removed.Fg + } + + rowChildren := []core.Node{ + core.Text{ + Content: lineNum, + Style: core.Style{ + Width: core.Pt(30), + FontFamily: core.FontMonospace, + FontSize: 11, + Color: p.TextFaint, + FlexShrink: 0, }, - core.Text{ - Content: sign, - Style: core.Style{ - Width: core.Pt(12), - FontFamily: core.FontMonospace, - FontSize: 11.5, - FontWeight: 600, - Color: signColor, - FlexShrink: 0, - }, + }, + core.Text{ + Content: sign, + Style: core.Style{ + Width: core.Pt(12), + FontFamily: core.FontMonospace, + FontSize: 11.5, + FontWeight: 600, + Color: signColor, + FlexShrink: 0, }, - core.Text{ - Content: l.Text, - Style: core.Style{ - FontFamily: core.FontMonospace, - FontSize: 11.5, - Color: fg, - FlexGrow: 1, - MinWidth: core.Pt(0), - }, + }, + core.Text{ + Content: l.Text, + Style: core.Style{ + FontFamily: core.FontMonospace, + FontSize: 11.5, + Color: fg, + FlexGrow: 1, + MinWidth: core.Pt(0), }, }, + } + if tagText != "" { + rowChildren = append(rowChildren, core.Text{ + TestID: fmt.Sprintf("review-yaml-tag-%d", l.Line), + Content: tagText, + Style: core.Style{ + FontSize: 11, + Color: tagColor, + FlexShrink: 0, + Padding: core.Edges{Left: 6}, + }, + }) + } + + rowStyle := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Padding: core.Symmetric(2, 12), + Gap: 6, + Background: bg, + } + if l.Error { + rowStyle.Borders = core.Edges{Bottom: 1.5} + rowStyle.BorderColor = p.Removed.Edge + } + nodes = append(nodes, core.View{ + Style: rowStyle, + Children: rowChildren, }) } return core.View{TestID: "review-yaml-lines", Children: nodes} diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index c707183be..fb07575fe 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -1146,6 +1146,7 @@ func (e *Editor) afterMutate() { e.syncHUDAfterMutate() e.syncTileReviewAfterMutate() e.syncAgentTurnAfterMutate() + e.syncReviewAfterMutate() e.Rebuild() // Ensure SelectedID and selectedIDs still point to existing local, instanced, or inherited objects. e.pruneSelection()