From 6d922307223d12f436b229d4c4b29b8835b93b6c Mon Sep 17 00:00:00 2001
From: soryu <soryu@soryu.co>
Date: Thu, 30 Apr 2026 23:26:10 +0100
Subject: fix(doc-mode): root-walk goal serializer + roundtrip-confirmed draft
 drop, plus richer context menus (#114)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

## The data-loss bug

User reported "even after clicking Save now I have lost my doc". Two causes:

1. **GoalChangePlugin only read children[1]** — it captured edits to the
   single goal paragraph but silently dropped any typing that landed in
   the trailing paragraph below the StepsBlock (or in extra paragraphs the
   user had inserted). pendingGoalRef stayed at the persisted value, Save
   now fired empty/stale content, the doc was overwritten.

2. **fireSave dropped localStorage immediately on save success.** If the
   save persisted the wrong/empty content, the draft (which had the real
   content) was already gone — no recovery path.

## Fixes

### Capture all body content
New `serializeGoalFromRoot` walks the entire root, skips only the H1 title
and the StepsBlock decorator, and emits multi-paragraph markdown joined by
blank lines. `GoalChangePlugin` and `fireSave` both call it now. Seed code
splits an existing multi-paragraph goal back into ParagraphNodes on load.

### Read directly from the editor at save time
`fireSave` now reads pendingGoalRef AND consults the live editor state via
`editor.getEditorState().read()`. If anything went wrong with OnChangePlugin
(which is rare, but possible — and was eating typing for many users), the
save still picks up the actual document body.

### Defensive pre-save flush
Before talking to the backend, `fireSave` writes the value to localStorage.
If the network fails, the page closes mid-flight, or anything else goes
sideways, the draft survives.

### Roundtrip-confirmed draft cleanup
We no longer drop the localStorage draft inside `fireSave`. Instead a new
effect watches `directive.goal` and clears the draft only when:
  lastSavedValueRef === directive.goal === pendingGoalRef.current
i.e. only when the polled state confirms our save persisted AND the user
hasn't typed anything new in the meantime.

## Question notifications respect document mode

`SupervisorQuestionNotification` and `PhaseConfirmationToast` now route to
`/directives/<id>?task=<taskId>` (the doc-mode surface) when the user has
documentMode on AND the question carries a directiveId. Falls back to the
old `/exec/:taskId` route for non-doc-mode users.

## Richer directive folder context menu

In addition to start/pause/archive/delete/go-to-PR/new-draft we now expose:
  - Advance DAG
  - Plan orders
  - Clean up
  - Create / Update PR
All optional callbacks; the legacy tabular UI is unaffected.

## Richer task row context menu

In addition to interrupt/complete/fail/skip we now expose:
  - Send message — browser prompt → sendTaskMessage (same wire as the
    inline comment box)
  - Open in task page — navigates to /exec/:taskId for the full task UI
    (worktree diff viewer, checkpoint controls, etc.)

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---
 .../components/directives/DirectiveContextMenu.tsx | 91 ++++++++++++++++++----
 1 file changed, 77 insertions(+), 14 deletions(-)

(limited to 'makima/frontend/src/components/directives/DirectiveContextMenu.tsx')

diff --git a/makima/frontend/src/components/directives/DirectiveContextMenu.tsx b/makima/frontend/src/components/directives/DirectiveContextMenu.tsx
index 3f24ce1..eda7e7f 100644
--- a/makima/frontend/src/components/directives/DirectiveContextMenu.tsx
+++ b/makima/frontend/src/components/directives/DirectiveContextMenu.tsx
@@ -17,6 +17,14 @@ interface DirectiveContextMenuProps {
    * tabular UI doesn't have to wire it up.
    */
   onNewDraft?: () => void;
+  /** Trigger a fresh PR creation from the current contract state. */
+  onCreatePR?: () => void;
+  /** Manually advance the DAG (find newly-ready steps). */
+  onAdvance?: () => void;
+  /** Run the cleanup task to prune merged/stale steps. */
+  onCleanup?: () => void;
+  /** Pick up linked orders (queue them as new steps). */
+  onPickUpOrders?: () => void;
 }
 
 export function DirectiveContextMenu({
@@ -30,6 +38,10 @@ export function DirectiveContextMenu({
   onDelete,
   onGoToPR,
   onNewDraft,
+  onCreatePR,
+  onAdvance,
+  onCleanup,
+  onPickUpOrders,
 }: DirectiveContextMenuProps) {
   const menuRef = useRef<HTMLDivElement>(null);
 
@@ -153,21 +165,72 @@ export function DirectiveContextMenu({
         </button>
       )}
 
-      {/* Go to PR link */}
+      {/* Orchestration actions — Advance / Pick up orders / Cleanup. */}
+      {(onAdvance || onPickUpOrders || onCleanup) && (
+        <div className={dividerClass} />
+      )}
+      {onAdvance && (
+        <button
+          className={menuItemClass}
+          onClick={() => {
+            onAdvance();
+            onClose();
+          }}
+        >
+          <span className="text-[#75aafc]">»</span>
+          Advance DAG
+        </button>
+      )}
+      {onPickUpOrders && (
+        <button
+          className={menuItemClass}
+          onClick={() => {
+            onPickUpOrders();
+            onClose();
+          }}
+        >
+          <span className="text-[#c084fc]">◆</span>
+          Plan orders
+        </button>
+      )}
+      {onCleanup && (
+        <button
+          className={menuItemClass}
+          onClick={() => {
+            onCleanup();
+            onClose();
+          }}
+        >
+          <span className="text-[#75aafc]">⎚</span>
+          Clean up
+        </button>
+      )}
+
+      {/* PR actions — Create / Update / Go to PR. */}
+      {(onCreatePR || showGoToPR) && <div className={dividerClass} />}
+      {onCreatePR && (
+        <button
+          className={menuItemClass}
+          onClick={() => {
+            onCreatePR();
+            onClose();
+          }}
+        >
+          <span className="text-emerald-300">↗</span>
+          {directive.prUrl ? "Update PR" : "Create PR"}
+        </button>
+      )}
       {showGoToPR && (
-        <>
-          <div className={dividerClass} />
-          <button
-            className={menuItemClass}
-            onClick={() => {
-              onGoToPR();
-              onClose();
-            }}
-          >
-            <span className="text-[#75aafc]">↗</span>
-            Go to PR
-          </button>
-        </>
+        <button
+          className={menuItemClass}
+          onClick={() => {
+            onGoToPR();
+            onClose();
+          }}
+        >
+          <span className="text-[#75aafc]">↗</span>
+          Go to PR
+        </button>
       )}
 
       <div className={dividerClass} />
-- 
cgit v1.2.3

