From fe6b78fa59657449be2e888402e3a0197b5c0621 Mon Sep 17 00:00:00 2001 From: soryu Date: Thu, 30 Apr 2026 17:08:30 +0100 Subject: feat(directives): per-PR revision snapshots + sidebar history (#112) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stage 3 of the doc-mode revamp. Builds the foundation for treating contracts as living specifications by freezing their content into a revision every time a PR is raised. ## directive_revisions table (new migration) (id, directive_id, content, pr_url, pr_branch, pr_state, version, frozen_at) with UNIQUE(directive_id, version) and a partial index on pr_state='open' so the next reconciler iteration can poll only what's still in flight. pr_state is constrained to 'open' | 'merged' | 'closed' to mirror GitHub's PR lifecycle. For Stage 3 we only freeze on PR creation; pr_state poll is deferred to a follow-up. ## Repository helpers - create_directive_revision: idempotent on (directive_id, pr_url) so a re-run of the orchestrator's completion task can't double-snapshot. Auto-assigns version = MAX(existing) + 1 per directive. - list_directive_revisions_for_owner: scoped through the directive join so users can only read their own contract history. - update_directive_revision_pr_state: stub for the upcoming poller. - get_latest_merged_revision: returns the most recent merged revision — this is what Stage 4 will diff against on amendments. ## Snapshot trigger update_directive handler now reads the BEFORE pr_url before the update. If pr_url transitions None → Some, it snapshots the directive's current goal as a revision tied to the new pr_url. Failures log and continue — the directive update itself is unaffected. ## API + OpenAPI GET /api/v1/directives/{id}/revisions returns DirectiveRevisionListResponse (revisions newest-first). Schemas registered in OpenAPI. ## Frontend: revisions/ subfolder + read-only viewer Each contract folder now has a third subfolder ("revisions/") that lazily fetches and lists past revisions when the parent directive folder is open. Empty contracts skip the subfolder entirely so brand-new ones aren't cluttered. Each row shows v.md plus a small pill ('open'/'merged'/ 'closed'). Selecting a revision encodes itself into the existing ?task= param as "revision:", so EditorShell can route between the live task stream (realTaskId), the read-only RevisionViewer (revisionId), or the editor itself (neither). The viewer renders the frozen markdown verbatim with a deep-link to the PR — these are immutable historical records, not edit surfaces. Co-authored-by: Claude Opus 4.7 (1M context) --- makima/frontend/src/lib/api.ts | 34 ++++ makima/frontend/src/routes/document-directives.tsx | 216 ++++++++++++++++++++- 2 files changed, 242 insertions(+), 8 deletions(-) (limited to 'makima/frontend') diff --git a/makima/frontend/src/lib/api.ts b/makima/frontend/src/lib/api.ts index 8896f2c..e3dbc30 100644 --- a/makima/frontend/src/lib/api.ts +++ b/makima/frontend/src/lib/api.ts @@ -3451,6 +3451,40 @@ export interface PickUpOrdersResponse { taskId: string | null; } +/** + * Per-PR snapshot of a directive's goal — frozen at PR creation, lifecycle + * tracked alongside the PR itself. + */ +export interface DirectiveRevision { + id: string; + directiveId: string; + /** Inline-markdown content of the directive goal at the moment the PR was raised. */ + content: string; + prUrl: string; + prBranch: string | null; + /** "open" | "merged" | "closed" — tracks the PR lifecycle. */ + prState: string; + version: number; + frozenAt: string; +} + +export interface DirectiveRevisionListResponse { + revisions: DirectiveRevision[]; + total: number; +} + +export async function listDirectiveRevisions( + directiveId: string, +): Promise { + const res = await authFetch( + `${API_BASE}/api/v1/directives/${directiveId}/revisions`, + ); + if (!res.ok) { + throw new Error(`Failed to list revisions: ${res.statusText}`); + } + return res.json(); +} + export async function createDirectivePR(id: string): Promise { const res = await authFetch(`${API_BASE}/api/v1/directives/${id}/create-pr`, { method: "POST" }); if (!res.ok) throw new Error(`Failed to create PR: ${res.statusText}`); diff --git a/makima/frontend/src/routes/document-directives.tsx b/makima/frontend/src/routes/document-directives.tsx index ada8a3d..87102a2 100644 --- a/makima/frontend/src/routes/document-directives.tsx +++ b/makima/frontend/src/routes/document-directives.tsx @@ -16,11 +16,13 @@ import { failDirectiveStep, skipDirectiveStep, stopTask, + listDirectiveRevisions, } from "../lib/api"; import type { DirectiveStatus, DirectiveSummary, DirectiveWithSteps, + DirectiveRevision, } from "../lib/api"; // Status dot color, matching the existing tabular UI's badge palette so the @@ -365,6 +367,27 @@ function DirectiveFolder({ const orchestratorRunning = !!directive.orchestratorTaskId; // Tasks subfolder open state — independent of the directive folder. const [tasksOpen, setTasksOpen] = useState(true); + // Revisions subfolder — collapsed by default since most contracts have + // no merged history yet. + const [revisionsOpen, setRevisionsOpen] = useState(false); + const [revisions, setRevisions] = useState([]); + // Fetch revisions only when the parent folder is open. Re-fetch whenever + // the directive's pr_url changes so a freshly-raised PR appears. + useEffect(() => { + if (!open) return; + let cancelled = false; + listDirectiveRevisions(directive.id) + .then((res) => { + if (!cancelled) setRevisions(res.revisions); + }) + .catch((err) => { + // eslint-disable-next-line no-console + console.warn("[makima] failed to load revisions", err); + }); + return () => { + cancelled = true; + }; + }, [open, directive.id, directive.prUrl]); return (
@@ -477,12 +500,176 @@ function DirectiveFolder({ )} + + {/* revisions/ subfolder — per-PR frozen snapshots of this contract. + Only rendered when there's at least one revision; otherwise the + folder body would be a confusing empty placeholder. */} + {revisions.length > 0 && ( +
  • + + + {revisionsOpen && ( +
      + {revisions.map((r) => { + const isSelected = + selection?.directiveId === directive.id && + selection?.taskId === `revision:${r.id}`; + return ( +
    • + +
    • + ); + })} +
    + )} +
  • + )} )}
    ); } +/** + * Read-only viewer for a frozen contract revision. We render the markdown as + * plain pre-formatted text — these are immutable historical records, not + * places to edit. A header strip shows the PR state and a deep link. + */ +function RevisionViewer({ + directiveId, + revisionId, +}: { + directiveId: string; + revisionId: string; +}) { + const [revision, setRevision] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + let cancelled = false; + setLoading(true); + setError(null); + listDirectiveRevisions(directiveId) + .then((res) => { + if (cancelled) return; + const found = res.revisions.find((r) => r.id === revisionId) ?? null; + if (!found) setError("Revision not found"); + setRevision(found); + }) + .catch((err) => { + if (cancelled) return; + setError(err instanceof Error ? err.message : String(err)); + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; + }, [directiveId, revisionId]); + + if (loading) { + return ( +
    +

    Loading revision…

    +
    + ); + } + if (error || !revision) { + return ( +
    +

    + {error ?? "Revision not found"} +

    +
    + ); + } + + return ( +
    +
    +
    +
    +

    + v{revision.version} +

    + +
    +

    + Frozen {new Date(revision.frozenAt).toLocaleString()} +

    +

    + + {revision.prUrl} + +

    + + {/* Render the frozen markdown as plain pre-formatted text. We + deliberately do not parse it into rich nodes — the goal is to + show the historical record exactly as it was at PR time. */} +
    +            {revision.content}
    +          
    +
    +
    +
    + ); +} + +/** Tiny pill showing the PR state of a revision (open / merged / closed). */ +function RevisionStateBadge({ prState }: { prState: string }) { + const tone = + prState === "merged" + ? "text-emerald-300 border-emerald-700/60" + : prState === "closed" + ? "text-[#7788aa] border-[#2a3a5a]" + : "text-amber-300 border-amber-600/40"; + return ( + + {prState} + + ); +} + /** * Right-side status indicator. Composes the colored status dot with optional * "live" pulse (orchestrator running) and "glow" attention ring (pending user @@ -760,14 +947,25 @@ function EditorShell({ ); } + // The "task" param can encode either a real task id, or a revision via the + // `revision:` prefix. Split that out so the right pane can switch + // between the live task stream and the read-only revision viewer. + const revisionId = + selectedTaskId && selectedTaskId.startsWith("revision:") + ? selectedTaskId.slice("revision:".length) + : null; + const realTaskId = revisionId ? null : selectedTaskId; + // Resolve the label for the breadcrumb when a task is selected. - const taskLabel = selectedTaskId - ? selectedTaskId === directive.orchestratorTaskId + const taskLabel = realTaskId + ? realTaskId === directive.orchestratorTaskId ? "orchestrator" - : selectedTaskId === directive.completionTaskId + : realTaskId === directive.completionTaskId ? "completion" - : directive.steps.find((s) => s.taskId === selectedTaskId)?.name ?? - selectedTaskId.slice(0, 8) + : directive.steps.find((s) => s.taskId === realTaskId)?.name ?? + realTaskId.slice(0, 8) + : revisionId + ? "revision" : null; return ( @@ -800,10 +998,12 @@ function EditorShell({ - {selectedTaskId ? ( + {revisionId ? ( + + ) : realTaskId ? ( ) : (