diff --git a/packages/review-editor/App.tsx b/packages/review-editor/App.tsx index 3b43b7a..6dfdbb0 100644 --- a/packages/review-editor/App.tsx +++ b/packages/review-editor/App.tsx @@ -1166,6 +1166,7 @@ const ReviewApp: React.FC = () => { defaultBranch: data.gitContext!.defaultBranch, diffOptions: data.gitContext!.diffOptions, compareTarget: data.gitContext!.compareTarget, + jjEvologs: data.gitContext!.jjEvologs, }; }); } @@ -1193,7 +1194,7 @@ const ReviewApp: React.FC = () => { if (branch === selectedBase) return; const previous = selectedBase; setSelectedBase(branch); - if (activeDiffBase === 'branch' || activeDiffBase === 'merge-base' || activeDiffBase === 'jj-line') { + if (activeDiffBase === 'branch' || activeDiffBase === 'merge-base' || activeDiffBase === 'jj-line' || activeDiffBase === 'jj-evolog') { const ok = await fetchDiffSwitch(diffType, branch); if (!ok) setSelectedBase(previous); } @@ -1207,8 +1208,22 @@ const ReviewApp: React.FC = () => { ? `worktree:${activeWorktreePath}:${baseDiffType}` : baseDiffType; if (fullDiffType === diffType) return; - await fetchDiffSwitch(fullDiffType); - }, [diffType, activeWorktreePath, fetchDiffSwitch]); + // For evolog, default to the second entry (previous state of @) so the + // server doesn't fall back to the jj bookmark/trunk revset. + // When leaving evolog, restore the base to the detected compare target + // so other base-dependent modes (jj-line) don't inherit a commit ID. + const enteringEvolog = + baseDiffType === 'jj-evolog' && gitContext?.jjEvologs && gitContext.jjEvologs.length >= 2; + const leavingEvolog = + !enteringEvolog && activeDiffBase === 'jj-evolog' && gitContext?.defaultBranch; + const baseOverride = enteringEvolog + ? gitContext!.jjEvologs![1].commitId + : leavingEvolog + ? gitContext!.defaultBranch + : undefined; + if (baseOverride) setSelectedBase(baseOverride); + await fetchDiffSwitch(fullDiffType, baseOverride); + }, [diffType, activeWorktreePath, fetchDiffSwitch, gitContext]); // Switch worktree context (or back to main repo). Preserves the current // diff mode across the switch — if the reviewer was looking at "PR Diff" @@ -1307,7 +1322,7 @@ const ReviewApp: React.FC = () => { // the new patch to arrive before refetching — otherwise the viewer can // briefly pair an old patch with the new base's content. reviewBase: - (activeDiffBase === 'branch' || activeDiffBase === 'merge-base' || activeDiffBase === 'jj-line') + (activeDiffBase === 'branch' || activeDiffBase === 'merge-base' || activeDiffBase === 'jj-line' || activeDiffBase === 'jj-evolog') ? committedBase ?? undefined : undefined, activeDiffBase, @@ -2079,6 +2094,8 @@ const ReviewApp: React.FC = () => { detectedBase={prMetadata ? undefined : gitContext?.defaultBranch || gitContext?.compareTarget?.fallback} onSelectBase={prMetadata ? undefined : handleBaseSelect} compareTarget={gitContext?.compareTarget} + jjEvologs={prMetadata ? undefined : gitContext?.jjEvologs} + detectedEvoBase={prMetadata ? undefined : gitContext?.jjEvologs?.[1]?.commitId} stagedFiles={stagedFiles} onCopyRawDiff={handleCopyDiff} canCopyRawDiff={!!diffData?.rawPatch} @@ -2158,6 +2175,7 @@ const ReviewApp: React.FC = () => { {activeDiffBase === 'jj-current' && "No changes in the current jj change."} {activeDiffBase === 'jj-last' && "No changes in the last jj change."} {activeDiffBase === 'jj-line' && `No changes in your line of work vs ${selectedBase || gitContext?.defaultBranch || '@-'}.`} + {activeDiffBase === 'jj-evolog' && `No changes since evolution ${selectedBase ? selectedBase.slice(0, 8) : 'previous'} — the change looks the same as before.`} {activeDiffBase === 'jj-all' && "No files at the current jj change."} {activeDiffBase === 'branch' && `No changes vs ${selectedBase || gitContext?.defaultBranch || 'main'}${activeWorktreePath ? ' in this worktree' : ''}.`} {activeDiffBase === 'merge-base' && `No changes vs ${selectedBase || gitContext?.defaultBranch || 'main'}${activeWorktreePath ? ' in this worktree' : ''}.`} diff --git a/packages/review-editor/components/DiffTypePicker.tsx b/packages/review-editor/components/DiffTypePicker.tsx index 88daadb..c8f7e0e 100644 --- a/packages/review-editor/components/DiffTypePicker.tsx +++ b/packages/review-editor/components/DiffTypePicker.tsx @@ -23,6 +23,7 @@ const OPTION_HINTS: Record = { 'jj-current': "Changes in the current jj change.", 'jj-last': "Changes in the previous jj change.", 'jj-line': "Changes in your line of work from the selected bookmark or revision.", + 'jj-evolog': "What changed between two evolutions of the current change — shows what you amended.", 'jj-all': "Every tracked file in the current jj workspace, shown as additions.", branch: "Straight compare against the base branch (picked below). Can show commits that aren't yours if the base has new commits.", 'merge-base': "Only what you've added on top of the base branch (picked below). Same as GitHub's PR view.", diff --git a/packages/review-editor/components/EvoLogPicker.tsx b/packages/review-editor/components/EvoLogPicker.tsx new file mode 100644 index 0000000..610b92a --- /dev/null +++ b/packages/review-editor/components/EvoLogPicker.tsx @@ -0,0 +1,162 @@ +import React, { useState } from 'react'; +import * as Popover from '@radix-ui/react-popover'; +import type { JjEvoLogEntry } from '@plannotator/shared/types'; + +interface EvoLogPickerProps { + entries: JjEvoLogEntry[]; + /** Currently selected evolog commit ID. */ + selectedCommitId: string; + /** The default commit ID (second evolog entry — previous state). */ + detectedCommitId: string; + onSelect: (commitId: string) => void; + disabled?: boolean; +} + +/** + * Picker for jj evolog entries. + * + * Shows the evolution history of the current change so the user can pick + * which previous state to compare against. The newest entry (index 0) is + * the current `@`; subsequent entries are older states in reverse order. + */ +export const EvoLogPicker: React.FC = ({ + entries, + selectedCommitId, + detectedCommitId, + onSelect, + disabled, +}) => { + const [open, setOpen] = useState(false); + + const selected = entries.find((e) => e.commitId === selectedCommitId) ?? entries[1]; + const isCustom = selectedCommitId !== detectedCommitId; + + const handleSelect = (commitId: string) => { + onSelect(commitId); + setOpen(false); + }; + + const handleReset = () => { + onSelect(detectedCommitId); + setOpen(false); + }; + + return ( + + + + + + +
+

+ Evolution history — pick a previous state to compare against +

+
+
+ {entries.map((entry, idx) => { + const isSelected = entry.commitId === selectedCommitId; + const isDetected = entry.commitId === detectedCommitId; + const isCurrent = idx === 0; + + return ( + + ); + })} +
+ {isCustom && ( +
+ +
+ )} +
+
+
+ ); +}; diff --git a/packages/review-editor/components/FileTree.tsx b/packages/review-editor/components/FileTree.tsx index 9026bf7..6c0aa8f 100644 --- a/packages/review-editor/components/FileTree.tsx +++ b/packages/review-editor/components/FileTree.tsx @@ -1,9 +1,10 @@ import React, { useEffect, useCallback, useState, useMemo } from 'react'; import { CodeAnnotation } from '@plannotator/ui/types'; -import type { AvailableBranches, CompareTargetConfig, DiffOption, WorktreeInfo } from '@plannotator/shared/types'; +import type { AvailableBranches, CompareTargetConfig, DiffOption, JjEvoLogEntry, WorktreeInfo } from '@plannotator/shared/types'; import { buildFileTree, getAncestorPaths, getAllFolderPaths, getVisualFileOrder } from '../utils/buildFileTree'; import { FileTreeNodeItem } from './FileTreeNode'; import { BaseBranchPicker } from './BaseBranchPicker'; +import { EvoLogPicker } from './EvoLogPicker'; import { DiffTypePicker } from './DiffTypePicker'; import { WorktreePicker } from './WorktreePicker'; import { getReviewSearchSideLabel, type ReviewSearchFileGroup, type ReviewSearchMatch } from '../utils/reviewSearch'; @@ -36,6 +37,10 @@ interface FileTreeProps { detectedBase?: string; onSelectBase?: (branch: string) => void; compareTarget?: CompareTargetConfig; + /** Evolution log entries for the current jj change (jj-evolog mode only). */ + jjEvologs?: JjEvoLogEntry[]; + /** Default evolog commit ID to compare against (second evolog entry). */ + detectedEvoBase?: string; stagedFiles?: Set; onCopyRawDiff?: () => void; canCopyRawDiff?: boolean; @@ -85,6 +90,8 @@ export const FileTree: React.FC = ({ detectedBase, onSelectBase, compareTarget, + jjEvologs, + detectedEvoBase, stagedFiles, onCopyRawDiff, canCopyRawDiff = false, @@ -368,8 +375,32 @@ export const FileTree: React.FC = ({ )} - {/* Compare target picker — only relevant for base-dependent diff types */} - {onSelectBase && + {/* Evolog picker — only shown when jj-evolog diff type is active */} + {activeDiffType === 'jj-evolog' && + onSelectBase && + selectedBase && + jjEvologs && + jjEvologs.length >= 2 && + detectedEvoBase && ( +
+ + from evolution + +
+ +
+
+ )} + + {/* Compare target picker — only relevant for base-dependent diff types (not evolog) */} + {activeDiffType !== 'jj-evolog' && + onSelectBase && selectedBase && detectedBase && availableBranches && diff --git a/packages/server/agent-review-message.ts b/packages/server/agent-review-message.ts index d8cb9ce..bfa9c1e 100644 --- a/packages/server/agent-review-message.ts +++ b/packages/server/agent-review-message.ts @@ -127,6 +127,13 @@ export function getLocalDiffInstruction( inspect: `Run \`jj diff --git --from ${shellQuote(baseRevset)} --to @\` to inspect the changes.`, }; } + case "jj-evolog": { + const fromRev = defaultBranch || ""; + return { + target: "what changed between two evolutions of the current JJ change", + inspect: `Run \`jj diff --git --from ${shellQuote(fromRev)} --to @\` to inspect the changes (shows what was amended since the selected prior evolution).`, + }; + } case "jj-all": return { target: "all files in the JJ workspace", diff --git a/packages/shared/jj-core.test.ts b/packages/shared/jj-core.test.ts index 3515bc1..bf25e7a 100644 --- a/packages/shared/jj-core.test.ts +++ b/packages/shared/jj-core.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { getJjDiffArgs, + getJjEvoLogEntries, jjLineBaseRevset, parseJjBookmarkList, parseJjRemoteBookmarkList, @@ -125,6 +126,95 @@ describe("jj compare targets", () => { }); }); +describe("jj evolog", () => { + test("builds evolog diff args with explicit base", () => { + expect(getJjDiffArgs("jj-evolog", "abc123456789")).toEqual({ + args: ["diff", "--git", "--from", "abc123456789", "--to", "@"], + label: "Evolution diff from abc12345", + }); + }); + + test("builds evolog diff args with whitespace flag", () => { + expect(getJjDiffArgs("jj-evolog", "abc123456789", { hideWhitespace: true })?.args) + .toEqual(["diff", "--git", "-w", "--from", "abc123456789", "--to", "@"]); + }); + + test("parses evolog output correctly (commit.* template fields)", async () => { + const runtime: ReviewJjRuntime = { + async runJj() { + return { + stdout: [ + "abc123456789\tAdd login form\t2 minutes ago", + "def456789012\tAdd login form\t10 minutes ago", + "ghi789012345\tAdd login form\t1 hour ago", + "", + ].join("\n"), + stderr: "", + exitCode: 0, + }; + }, + }; + const entries = await getJjEvoLogEntries(runtime); + expect(entries).toHaveLength(3); + expect(entries[0]).toEqual({ commitId: "abc123456789", description: "Add login form", age: "2 minutes ago" }); + expect(entries[1]).toEqual({ commitId: "def456789012", description: "Add login form", age: "10 minutes ago" }); + expect(entries[2]).toEqual({ commitId: "ghi789012345", description: "Add login form", age: "1 hour ago" }); + }); + + test("returns empty array when evolog exits non-zero", async () => { + const runtime: ReviewJjRuntime = { + async runJj() { + return { stdout: "", stderr: "error: no such revision", exitCode: 1 }; + }, + }; + const entries = await getJjEvoLogEntries(runtime); + expect(entries).toHaveLength(0); + }); + + test("defaults to second evolog entry when no base given", async () => { + let callCount = 0; + const calls: string[][] = []; + const runtime: ReviewJjRuntime = { + async runJj(args) { + calls.push(args); + callCount++; + if (args[0] === "evolog") { + return { + stdout: [ + "abc123456789\tFix bug\t1 minute ago", + "def456789012\tFix bug\t5 minutes ago", + "", + ].join("\n"), + stderr: "", + exitCode: 0, + }; + } + return { stdout: "diff --git a/foo.ts b/foo.ts\n", stderr: "", exitCode: 0 }; + }, + }; + const result = await runJjDiff(runtime, "jj-evolog", ""); + expect(result.label).toBe("Evolution diff from def45678"); + // evolog call + diff call + expect(callCount).toBe(2); + const diffCall = calls.find((c) => c[0] === "diff"); + expect(diffCall).toEqual(["diff", "--git", "--from", "def456789012", "--to", "@"]); + }); + + test("returns error when evolog has no previous entry", async () => { + const runtime: ReviewJjRuntime = { + async runJj(args) { + if (args[0] === "evolog") { + return { stdout: "abc123456789\tInitial commit\t1 minute ago\n", stderr: "", exitCode: 0 }; + } + return { stdout: "", stderr: "", exitCode: 0 }; + }, + }; + const result = await runJjDiff(runtime, "jj-evolog", ""); + expect(result.error).toBe("No previous evolution found"); + expect(result.patch).toBe(""); + }); +}); + describe("jj bookmark parsing", () => { test("parses escaped newline separators from jj bookmark templates", () => { expect(parseJjBookmarkList('"dev"\\n"main"\\n')).toEqual(["dev", "main"]); diff --git a/packages/shared/jj-core.ts b/packages/shared/jj-core.ts index 21c6e21..5189d98 100644 --- a/packages/shared/jj-core.ts +++ b/packages/shared/jj-core.ts @@ -5,6 +5,7 @@ import { type GitCommandResult, type GitContext, type GitDiffOptions, + type JjEvoLogEntry, JJ_TRUNK_REVSET, jjLineBaseRevset, validateFilePath, @@ -15,6 +16,7 @@ export { jjCompareTargetRevset, jjLineBaseRevset, parseRemoteBookmark, + type JjEvoLogEntry, } from "./review-core"; export interface ReviewJjRuntime { @@ -41,6 +43,8 @@ export async function getJjContext( const defaultTarget = await selectDefaultJjCompareTarget(runtime, root ?? cwd); const contextCwd = root ?? cwd; + const evologs = await getJjEvoLogEntries(runtime, root ?? cwd); + return { currentBranch: "", defaultBranch: defaultTarget, @@ -48,6 +52,7 @@ export async function getJjContext( { id: "jj-current", label: "Current change" }, { id: "jj-last", label: "Last change" }, { id: "jj-line", label: "Line of work" }, + ...(evologs.length >= 2 ? [{ id: "jj-evolog", label: "Evolution diff" }] : []), { id: "jj-all", label: "All files" }, ], worktrees: [], @@ -68,6 +73,7 @@ export async function getJjContext( repository: contextCwd ? { displayFallback: basename(contextCwd) } : undefined, cwd: contextCwd, vcsType: "jj", + jjEvologs: evologs.length >= 2 ? evologs : undefined, }; } @@ -78,7 +84,18 @@ export async function runJjDiff( cwd?: string, options?: GitDiffOptions, ): Promise { - const compareTarget = defaultBranch.length > 0 ? defaultBranch : JJ_TRUNK_REVSET; + let compareTarget = defaultBranch.length > 0 ? defaultBranch : JJ_TRUNK_REVSET; + + // For evolog diffs, when no explicit base is provided, default to the + // second evolog entry (the previous state of the current change). + if (diffType === "jj-evolog" && defaultBranch.length === 0) { + const evologs = await getJjEvoLogEntries(runtime, cwd); + if (evologs.length < 2) { + return { patch: "", label: "Evolution diff", error: "No previous evolution found" }; + } + compareTarget = evologs[1].commitId; + } + const args = getJjDiffArgs(diffType, compareTarget, options); if (!args) return { patch: "", label: "Unknown diff type" }; @@ -144,6 +161,14 @@ export async function getJjFileContentsForDiff( newContent: await jjFileContent(runtime, "@", filePath, fileCwd), }; } + case "jj-evolog": { + // defaultBranch carries the evolog commit ID of the historical state. + const evologRev = defaultBranch.length > 0 ? defaultBranch : "@-"; + return { + oldContent: await jjFileContent(runtime, evologRev, oldFilePath, fileCwd), + newContent: await jjFileContent(runtime, "@", filePath, fileCwd), + }; + } case "jj-all": return { oldContent: null, @@ -171,6 +196,13 @@ export function getJjDiffArgs( args: ["diff", "--git", ...whitespaceArgs, "--from", jjLineBaseRevset(compareTarget), "--to", "@"], label: `Line of work vs ${compareTarget}`, }; + case "jj-evolog": + // compareTarget is the short commit ID of an older evolog entry. + // Diff from that historical state to the current working copy. + return { + args: ["diff", "--git", ...whitespaceArgs, "--from", compareTarget, "--to", "@"], + label: `Evolution diff from ${compareTarget.slice(0, 8)}`, + }; case "jj-all": return { args: ["diff", "--git", ...whitespaceArgs, "--from", "root()", "--to", "@"], label: "All files" }; default: @@ -333,6 +365,47 @@ function parseSerializedJjString(value: string): string | null { } } +/** + * Returns the evolution log for the current change (`@`), newest-first. + * Each entry represents a previous state of the same change ID. + * Returns an empty array if evolog is unavailable or the change has no history. + */ +export async function getJjEvoLogEntries( + runtime: ReviewJjRuntime, + cwd?: string, +): Promise { + // Template uses CommitEvolutionEntry type: each field is accessed via `commit.*`. + const result = await runtime.runJj( + [ + "evolog", + "--no-graph", + "-r", + "@", + "-T", + 'commit.commit_id().short(12) ++ "\t" ++ commit.description().first_line() ++ "\t" ++ commit.author().timestamp().ago() ++ "\n"', + ], + { cwd }, + ); + + if (result.exitCode !== 0) return []; + + const entries: JjEvoLogEntry[] = []; + for (const rawLine of result.stdout.split("\n")) { + const line = rawLine.trim(); + if (!line) continue; + const tabIdx = line.indexOf("\t"); + if (tabIdx === -1) continue; + const commitId = line.slice(0, tabIdx); + const rest = line.slice(tabIdx + 1); + const tab2 = rest.indexOf("\t"); + const description = tab2 === -1 ? rest : rest.slice(0, tab2); + const age = tab2 === -1 ? undefined : rest.slice(tab2 + 1); + if (commitId) entries.push({ commitId, description, age }); + } + + return entries; +} + async function jjFileContent( runtime: ReviewJjRuntime, rev: string, diff --git a/packages/shared/review-core.ts b/packages/shared/review-core.ts index 2bcc436..e79a703 100644 --- a/packages/shared/review-core.ts +++ b/packages/shared/review-core.ts @@ -18,6 +18,7 @@ export type DiffType = | "jj-last" | "jj-line" | "jj-all" + | "jj-evolog" | "branch" | "merge-base" | "all" @@ -61,6 +62,15 @@ export interface RepositoryContext { displayFallback?: string; } +export interface JjEvoLogEntry { + /** Short commit ID (12 hex chars) */ + commitId: string; + /** First line of the commit message */ + description: string; + /** Human-readable age string, e.g. "2 hours ago" */ + age?: string; +} + export interface GitContext { currentBranch: string; defaultBranch: string; @@ -71,6 +81,8 @@ export interface GitContext { repository?: RepositoryContext; cwd?: string; vcsType?: "git" | "jj" | "p4"; + /** Evolution log entries for the current jj change (jj only). */ + jjEvologs?: JjEvoLogEntry[]; } export interface DiffResult { diff --git a/packages/shared/types.ts b/packages/shared/types.ts index d249ee6..711badb 100644 --- a/packages/shared/types.ts +++ b/packages/shared/types.ts @@ -14,6 +14,7 @@ export type { DiffOption, WorktreeInfo, GitContext, + JjEvoLogEntry, AvailableBranches, CompareTargetConfig, CompareTargetPickerCopy, diff --git a/packages/shared/vcs-core.ts b/packages/shared/vcs-core.ts index 79edab6..0f81324 100644 --- a/packages/shared/vcs-core.ts +++ b/packages/shared/vcs-core.ts @@ -105,7 +105,7 @@ export interface PreparedLocalReviewDiff { } const GIT_DIFF_TYPES = new Set(["uncommitted", "staged", "unstaged", "last-commit", "branch", "merge-base", "all"]); -const JJ_DIFF_TYPES = new Set(["jj-current", "jj-last", "jj-line", "jj-all"]); +const JJ_DIFF_TYPES = new Set(["jj-current", "jj-last", "jj-line", "jj-evolog", "jj-all"]); function selectNearestProvider( candidates: Array<{ provider: VcsProvider; root: string | null; order: number }>, diff --git a/tests/manual/test-jj-review.ts b/tests/manual/test-jj-review.ts index 5d885a3..e353301 100644 --- a/tests/manual/test-jj-review.ts +++ b/tests/manual/test-jj-review.ts @@ -8,11 +8,20 @@ * - one current working-copy change on top * * Usage: - * bun run tests/manual/test-jj-review.ts [--keep] [--setup-only] + * bun run tests/manual/test-jj-review.ts [--keep] [--setup-only] [--with-evolog] + * + * Flags: + * --keep Don't delete the sandbox after the server exits. + * --setup-only Create the sandbox and print the path, but don't start the server. + * --with-evolog Amend the current change a few times before launching, so the + * "Evolution diff" mode appears in the UI with entries to pick from. + * Without this flag a helper script is written to the sandbox that + * you can run yourself at any time: `./create-evolog.sh` * * What to test in the review UI: * 1. The View dropdown lists JJ modes only: * Current change, Last change, Line of work, All files. + * (With --with-evolog or after running create-evolog.sh: also Evolution diff.) * 2. Initial view is Current change, even if a saved Git default exists. * 3. Current change shows only the working-copy commit (@). * 4. Last change shows only the previous committed JJ change (@-). @@ -20,6 +29,10 @@ * 6. All files shows the whole repository from root() to @. * 7. Hide whitespace re-runs JJ diff with -w. * 8. Staging controls are unavailable because JJ has no Git-style staging. + * 9. (Evolog) Evolution diff shows what changed between amendments of @. + * 10. (Evolog) The EvoLogPicker lists 3+ entries with commit IDs and ages. + * 11. (Evolog) Selecting an older entry re-diffs against that snapshot. + * 12. (Evolog) The "current" entry (index 0) is disabled in the picker. */ import { $ } from "bun"; @@ -40,6 +53,7 @@ import { import html from "../../apps/review/dist/index.html" with { type: "text" }; const SETUP_ONLY = process.argv.includes("--setup-only"); +const WITH_EVOLOG = process.argv.includes("--with-evolog"); const KEEP = process.argv.includes("--keep") || SETUP_ONLY; const sandbox = path.join(tmpdir(), `plannotator-jj-test-${Date.now()}`); @@ -680,6 +694,412 @@ async function createJjWorkspace(): Promise { await $`jj status`.cwd(jjRepo).quiet(); } +/** + * Amend the current working-copy change several times to create a realistic + * evolution log. Simulates a typical iteration cycle: first pass, then + * fixing issues you spotted, then responding to review feedback, then a + * final polish. After this, `jj evolog -r @` will show 5 entries. + */ +async function createEvologHistory(): Promise { + // Amendment 1: noticed the audit log service is missing a metadata field + // that other services expect. Quick fix while the change is still fresh. + await write("src/services/audit-log.ts", lines([ + "export interface AuditEvent {", + " type: string;", + " actor: string;", + " resource?: string;", + " createdAt: string;", + "}", + "", + "export function recordAuditEvent(type: string, actor = 'system', resource?: string): AuditEvent {", + " return {", + " type,", + " actor,", + " resource,", + " createdAt: new Date().toISOString(),", + " };", + "}", + ])); + await $`jj describe -m "feat: add config, audit log, and project API improvements"`.cwd(jjRepo).quiet(); + await $`jj status`.cwd(jjRepo).quiet(); + + // Amendment 2: reviewer pointed out the config should validate env vars + // instead of silently accepting garbage values. Also add a debug level + // to the logger since we're adding enableRequestTracing. + await write("src/config.ts", lines([ + "export interface Config {", + " port: number;", + " logLevel: 'debug' | 'info' | 'warn' | 'error';", + " enableRequestTracing: boolean;", + " maxRetries: number;", + "}", + "", + "const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']);", + "", + "export function loadConfig(): Config {", + " const rawLogLevel = process.env.LOG_LEVEL ?? 'info';", + " if (!VALID_LOG_LEVELS.has(rawLogLevel)) {", + " throw new Error(`Invalid LOG_LEVEL: ${rawLogLevel}`);", + " }", + "", + " return {", + " port: Number(process.env.PORT ?? 3000),", + " logLevel: rawLogLevel as Config['logLevel'],", + " enableRequestTracing: process.env.REQUEST_TRACING === '1',", + " maxRetries: Number(process.env.MAX_RETRIES ?? 3),", + " };", + "}", + ])); + await write("src/utils/logger.ts", lines([ + "export type LogLevel = 'debug' | 'info' | 'warn' | 'error';", + "", + "const LEVEL_PRIORITY: Record = {", + " debug: 0,", + " info: 1,", + " warn: 2,", + " error: 3,", + "};", + "", + "export function createLogger(level: string) {", + " const threshold = LEVEL_PRIORITY[level as LogLevel] ?? 1;", + "", + " return {", + " debug(message: string, data?: unknown) {", + " if (threshold <= 0) console.debug(message, data ?? '');", + " },", + " info(message: string, data?: unknown) {", + " if (threshold <= 1) console.log(message, data ?? '');", + " },", + " warn(message: string, data?: unknown) {", + " if (threshold <= 2) console.warn(message, data ?? '');", + " },", + " error(message: string, data?: unknown) {", + " console.error(message, data ?? '');", + " },", + " };", + "}", + ])); + await $`jj describe -m "feat: add config validation, structured logger, audit log, and project API"`.cwd(jjRepo).quiet(); + await $`jj status`.cwd(jjRepo).quiet(); + + // Amendment 3: realized the archive job threshold should be configurable + // via config rather than hardcoded. Wire it through. + await write("src/config.ts", lines([ + "export interface Config {", + " port: number;", + " logLevel: 'debug' | 'info' | 'warn' | 'error';", + " enableRequestTracing: boolean;", + " maxRetries: number;", + " staleProjectDays: number;", + "}", + "", + "const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']);", + "", + "export function loadConfig(): Config {", + " const rawLogLevel = process.env.LOG_LEVEL ?? 'info';", + " if (!VALID_LOG_LEVELS.has(rawLogLevel)) {", + " throw new Error(`Invalid LOG_LEVEL: ${rawLogLevel}`);", + " }", + "", + " return {", + " port: Number(process.env.PORT ?? 3000),", + " logLevel: rawLogLevel as Config['logLevel'],", + " enableRequestTracing: process.env.REQUEST_TRACING === '1',", + " maxRetries: Number(process.env.MAX_RETRIES ?? 3),", + " staleProjectDays: Number(process.env.STALE_PROJECT_DAYS ?? 120),", + " };", + "}", + ])); + await write("src/features/projects/jobs/nightly/archive-stale-projects.ts", lines([ + "import { listProjects, saveProject } from '../../repositories/project-repository';", + "", + "export async function archiveStaleProjects(", + " staleAfterDays: number,", + " now = new Date(),", + "): Promise {", + " const projects = await listProjects();", + " let archived = 0;", + "", + " for (const project of projects) {", + " const ageMs = now.getTime() - new Date(project.updatedAt).getTime();", + " const ageDays = ageMs / (1000 * 60 * 60 * 24);", + " if (project.status === 'paused' && ageDays > staleAfterDays) {", + " await saveProject({ ...project, status: 'archived' });", + " archived += 1;", + " }", + " }", + "", + " return archived;", + "}", + ])); + await $`jj describe -m "feat: config validation, structured logger, configurable archive threshold"`.cwd(jjRepo).quiet(); + await $`jj status`.cwd(jjRepo).quiet(); + + // Amendment 4: final cleanup — fix the invoice repository to use the + // status field properly and tighten the http client types. The kind of + // last-minute polish before marking a change as ready. + await write("src/features/billing/invoices/repositories/invoice-repository.ts", lines([ + "import type { Invoice } from '../domain/invoice';", + "", + "export async function listOpenInvoices(accountId: string): Promise {", + " return [", + " {", + " id: 'inv_001',", + " accountId,", + " totalCents: 24000,", + " status: 'open',", + " dueAt: '2026-05-15T00:00:00.000Z',", + " },", + " ];", + "}", + "", + "export async function listOverdueInvoices(accountId: string, now = new Date()): Promise {", + " const invoices = await listOpenInvoices(accountId);", + " return invoices.filter((inv) => new Date(inv.dueAt).getTime() < now.getTime());", + "}", + ])); + await write("src/shared/http/client.ts", lines([ + "export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';", + "", + "export interface HttpRequestOptions {", + " method?: HttpMethod;", + " headers?: Record;", + " body?: unknown;", + " signal?: AbortSignal;", + "}", + "", + "export async function requestJson(url: string, options: HttpRequestOptions = {}): Promise {", + " const response = await fetch(url, {", + " method: options.method ?? 'GET',", + " headers: {", + " 'content-type': 'application/json',", + " ...options.headers,", + " },", + " body: options.body === undefined ? undefined : JSON.stringify(options.body),", + " signal: options.signal,", + " });", + "", + " if (!response.ok) {", + " throw new Error(`Request failed: ${response.status} ${response.statusText}`);", + " }", + "", + " return response.json() as Promise;", + "}", + ])); + await $`jj describe -m "feat: config validation, structured logger, project archive, invoice & http cleanup"`.cwd(jjRepo).quiet(); + await $`jj status`.cwd(jjRepo).quiet(); +} + +/** + * Write a standalone shell script into the sandbox that creates evolog + * history when run. This lets the user launch the sandbox without evolog, + * verify the base modes work, then run the script and refresh to see the + * Evolution diff mode appear. + */ +async function writeEvologHelperScript(): Promise { + const script = `#!/usr/bin/env bash +set -euo pipefail + +# Creates evolution history for the current JJ change (@) by amending it +# four times, simulating a realistic iteration cycle. After running this, +# refresh the Plannotator review UI — the "Evolution diff" mode will +# appear in the diff type picker with 5 entries to compare between. + +cd "${jjRepo}" + +echo "Amendment 1/4: adding resource field to audit log..." +cat > src/services/audit-log.ts << 'TSEOF' +export interface AuditEvent { + type: string; + actor: string; + resource?: string; + createdAt: string; +} + +export function recordAuditEvent(type: string, actor = 'system', resource?: string): AuditEvent { + return { + type, + actor, + resource, + createdAt: new Date().toISOString(), + }; +} +TSEOF +jj describe -m "feat: add config, audit log, and project API improvements" +jj status > /dev/null + +echo "Amendment 2/4: adding config validation and structured logger..." +cat > src/config.ts << 'TSEOF' +export interface Config { + port: number; + logLevel: 'debug' | 'info' | 'warn' | 'error'; + enableRequestTracing: boolean; + maxRetries: number; +} + +const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']); + +export function loadConfig(): Config { + const rawLogLevel = process.env.LOG_LEVEL ?? 'info'; + if (!VALID_LOG_LEVELS.has(rawLogLevel)) { + throw new Error(\\\`Invalid LOG_LEVEL: \\\${rawLogLevel}\\\`); + } + + return { + port: Number(process.env.PORT ?? 3000), + logLevel: rawLogLevel as Config['logLevel'], + enableRequestTracing: process.env.REQUEST_TRACING === '1', + maxRetries: Number(process.env.MAX_RETRIES ?? 3), + }; +} +TSEOF +cat > src/utils/logger.ts << 'TSEOF' +export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; + +const LEVEL_PRIORITY: Record = { + debug: 0, + info: 1, + warn: 2, + error: 3, +}; + +export function createLogger(level: string) { + const threshold = LEVEL_PRIORITY[level as LogLevel] ?? 1; + + return { + debug(message: string, data?: unknown) { + if (threshold <= 0) console.debug(message, data ?? ''); + }, + info(message: string, data?: unknown) { + if (threshold <= 1) console.log(message, data ?? ''); + }, + warn(message: string, data?: unknown) { + if (threshold <= 2) console.warn(message, data ?? ''); + }, + error(message: string, data?: unknown) { + console.error(message, data ?? ''); + }, + }; +} +TSEOF +jj describe -m "feat: config validation, structured logger, audit log, and project API" +jj status > /dev/null + +echo "Amendment 3/4: making archive threshold configurable..." +cat > src/config.ts << 'TSEOF' +export interface Config { + port: number; + logLevel: 'debug' | 'info' | 'warn' | 'error'; + enableRequestTracing: boolean; + maxRetries: number; + staleProjectDays: number; +} + +const VALID_LOG_LEVELS = new Set(['debug', 'info', 'warn', 'error']); + +export function loadConfig(): Config { + const rawLogLevel = process.env.LOG_LEVEL ?? 'info'; + if (!VALID_LOG_LEVELS.has(rawLogLevel)) { + throw new Error(\\\`Invalid LOG_LEVEL: \\\${rawLogLevel}\\\`); + } + + return { + port: Number(process.env.PORT ?? 3000), + logLevel: rawLogLevel as Config['logLevel'], + enableRequestTracing: process.env.REQUEST_TRACING === '1', + maxRetries: Number(process.env.MAX_RETRIES ?? 3), + staleProjectDays: Number(process.env.STALE_PROJECT_DAYS ?? 120), + }; +} +TSEOF +cat > src/features/projects/jobs/nightly/archive-stale-projects.ts << 'TSEOF' +import { listProjects, saveProject } from '../../repositories/project-repository'; + +export async function archiveStaleProjects( + staleAfterDays: number, + now = new Date(), +): Promise { + const projects = await listProjects(); + let archived = 0; + + for (const project of projects) { + const ageMs = now.getTime() - new Date(project.updatedAt).getTime(); + const ageDays = ageMs / (1000 * 60 * 60 * 24); + if (project.status === 'paused' && ageDays > staleAfterDays) { + await saveProject({ ...project, status: 'archived' }); + archived += 1; + } + } + + return archived; +} +TSEOF +jj describe -m "feat: config validation, structured logger, configurable archive threshold" +jj status > /dev/null + +echo "Amendment 4/4: polish — overdue invoice query and http client cleanup..." +cat > src/features/billing/invoices/repositories/invoice-repository.ts << 'TSEOF' +import type { Invoice } from '../domain/invoice'; + +export async function listOpenInvoices(accountId: string): Promise { + return [ + { + id: 'inv_001', + accountId, + totalCents: 24000, + status: 'open', + dueAt: '2026-05-15T00:00:00.000Z', + }, + ]; +} + +export async function listOverdueInvoices(accountId: string, now = new Date()): Promise { + const invoices = await listOpenInvoices(accountId); + return invoices.filter((inv) => new Date(inv.dueAt).getTime() < now.getTime()); +} +TSEOF +cat > src/shared/http/client.ts << 'TSEOF' +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; + +export interface HttpRequestOptions { + method?: HttpMethod; + headers?: Record; + body?: unknown; + signal?: AbortSignal; +} + +export async function requestJson(url: string, options: HttpRequestOptions = {}): Promise { + const response = await fetch(url, { + method: options.method ?? 'GET', + headers: { + 'content-type': 'application/json', + ...options.headers, + }, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + signal: options.signal, + }); + + if (!response.ok) { + throw new Error(\\\`Request failed: \\\${response.status} \\\${response.statusText}\\\`); + } + + return response.json() as Promise; +} +TSEOF +jj describe -m "feat: config validation, structured logger, project archive, invoice & http cleanup" +jj status > /dev/null + +echo "" +echo "Done! Evolution log now has 5 entries:" +jj evolog --no-graph -r @ -T 'commit.commit_id().short(8) ++ " " ++ commit.description().first_line() ++ " (" ++ commit.author().timestamp().ago() ++ ")\\n"' +echo "" +echo "Refresh the Plannotator review UI to see the Evolution diff mode." +`; + const scriptPath = path.join(sandbox, "create-evolog.sh"); + await Bun.write(scriptPath, script); + await $`chmod +x ${scriptPath}`.quiet(); +} + async function printSandboxSummary(): Promise { const log = await $`jj log --no-graph -T 'change_id.short() ++ " " ++ commit_id.short() ++ " " ++ bookmarks ++ " " ++ remote_bookmarks ++ " " ++ description.first_line() ++ "\n"'`.cwd(jjRepo).quiet(); const status = await $`jj status`.cwd(jjRepo).quiet(); @@ -702,8 +1122,13 @@ async function printSandboxSummary(): Promise { console.error(" jj diff --git --from 'heads(::@ & ::(trunk()))' --to @"); console.error(" jj diff --git --from 'root()' --to @"); console.error(" jj diff --git -w -r @"); + console.error(" jj evolog -r @"); console.error(" jj git push --dry-run --bookmark review/jj-demo"); console.error(""); + console.error("Evolog helper script:"); + console.error(` ${path.join(sandbox, "create-evolog.sh")}`); + console.error(" (Amends @ twice to create evolution history, then refresh the UI)") + console.error(""); } if (!(await $`command -v jj`.quiet().nothrow()).stdout.length) { @@ -717,6 +1142,17 @@ console.error(""); await mkdir(sandbox, { recursive: true }); await createSeedGitRemote(); await createJjWorkspace(); +await writeEvologHelperScript(); + +if (WITH_EVOLOG) { + console.error("Creating evolution history (--with-evolog)..."); + await createEvologHistory(); + const evolog = await $`jj evolog --no-graph -r @ -T 'commit.commit_id().short(8) ++ " " ++ commit.description().first_line() ++ "\n"'`.cwd(jjRepo).quiet(); + console.error("Evolog entries:"); + console.error(evolog.text().trimEnd()); + console.error(""); +} + await printSandboxSummary(); if (SETUP_ONLY) { @@ -737,6 +1173,12 @@ console.error("Expected initial state:"); console.error(" - VCS type: jj"); console.error(" - Initial View: Current change"); console.error(" - Base for Line of work: trunk()"); +if (WITH_EVOLOG) { + console.error(" - Evolution diff: available (5 evolog entries)"); + console.error(" - EvoLogPicker: should show entries with commit IDs + ages"); +} else { + console.error(" - Evolution diff: not shown (run create-evolog.sh and refresh)"); +} console.error(""); const server = await startReviewServer({