From af36f2b853a885a1c4be8b6c248c408b72e43723 Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:17:53 +0900 Subject: [PATCH] Remove historical design docs and shorten project guides --- Docs/architecture.md | 118 +---- Docs/deferred-codex-update-design.md | 199 --------- Docs/mcp.md | 103 ++--- Docs/releases.md | 164 ++----- ...w-history-persistence-design-2026-08-29.md | 403 ------------------ README.md | 87 ++-- .../CodexReview/Store/CodexReviewStore.swift | 11 +- .../ReviewMonitorWindowController.swift | 6 - scripts/review-history-e2e/README.md | 61 +-- 9 files changed, 143 insertions(+), 1009 deletions(-) delete mode 100644 Docs/deferred-codex-update-design.md delete mode 100644 Docs/review-history-persistence-design-2026-08-29.md diff --git a/Docs/architecture.md b/Docs/architecture.md index dbee6bea..458ac573 100644 --- a/Docs/architecture.md +++ b/Docs/architecture.md @@ -1,8 +1,8 @@ # Architecture -ReviewMonitor's UI and MCP server share one `CodexReviewStore`. The store owns -review state and commands; its backend sends requests to `codex app-server`. -`CodexReviewHost` connects these components when the app starts. +ReviewMonitor's UI and MCP server share one `CodexReviewStore`. It owns review +state and commands. At launch, `CodexReviewHost` connects the store to the MCP +listener, the SQLite history database, and the backend that runs `codex app-server`. ## Targets @@ -11,108 +11,36 @@ review state and commands; its backend sends requests to `codex app-server`. | `CodexReview` | Review API, observable store, authentication, settings, and history contracts | | `CodexReviewAppServer` | JSON-RPC requests, notifications, and process transport for `codex app-server` | | `CodexReviewPersistence` | SQLite history storage, migrations, and retention | -| `CodexReviewMCPServer` | MCP tool conversion and the Streamable HTTP endpoint | +| `CodexReviewMCPServer` | MCP tools and the Streamable HTTP endpoint | | `CodexReviewHost` | Live backend, filesystem locations, and dependency assembly | | `CodexReviewTesting` | Fake backend and transport, gates, and manual clock | | `ReviewUI` | Monitor views and controllers | | `TextTransitions` | Animated text rendering | -ReviewMonitor is the app entry point. The package exports `CodexReview`, -`CodexReviewHost`, `ReviewUI`, and `TextTransitions` as libraries; the other -production targets support those libraries internally. - -ReviewUI controllers start observation tracking on demand. Applications can -optionally warm up the runtime during asynchronous setup: - -```swift -try await CodexReviewStore.prepareObservationTracking() -``` - -Controllers can be created without calling this method, or while preparation is -in progress. Synchronous observation startup may block while resolving or joining -runtime work. `CodexReviewStore.start()` prepares tracking asynchronously before -starting the runtime and reports preparation failures through the store's failed -state. Preparation is shared across concurrent calls and reused for the lifetime -of the process. ReviewMonitor and its previews construct their UI directly. +The package exports `CodexReview`, `CodexReviewHost`, `ReviewUI`, and +`TextTransitions` as libraries. ## Review flow -Both UI actions and MCP tools call the store. `CodexReviewStoreBackend` supplies -runtime operations, with live, preview, and test implementations. Each uses the -same store to manage product state. - -The live backend uses one shared connection to a long-lived `codex app-server` -process. The gateway initializes the connection once with `initialize` and -`initialized`, then sends typed requests: - -- Mutating requests on the same thread run in order. Requests on different - threads can run concurrently. -- A review uses a normal `turn/start` on its review thread. The adapter includes - the target, working directory, and server-reported `$review-agent` skill - provisioned during initialization. -- The gateway subscribes to notifications before `turn/start` so it can receive - terminal events sent alongside the response. -- `turn/interrupt` can proceed while `turn/start` is pending. Cancellation uses - control and cleanup requests; it keeps the transport open. - -Fake and live tests use the same transport protocol. - -## MCP sessions - -The app hosts `http://localhost:9417/mcp`. An `initialize` request creates an -`MCP-Session-Id`; subsequent requests carry that header. The server returns JSON -or SSE according to client negotiation, and `DELETE` closes the session. +The store records each accepted review before dispatching it to the backend. +The live backend shares a long-lived app-server connection across reviews. +Each review gets a thread. The adapter subscribes to notifications before +sending `turn/start` with the `$review-agent` skill so it can receive a terminal +event even if it arrives with the response. Reviews on different threads can +run concurrently. -Jobs belong to the session that started them. The MCP adapter converts tool -arguments into store commands and converts their results into MCP responses. -The app-server gateway handles Codex's JSON-RPC separately. See the -[MCP reference](mcp.md) for tool and response fields. - -## History and UI - -The store loads and saves history through `CodexReviewPersistence`, which owns -the SQLite database. `CodexReviewHost` supplies its filesystem location. History -stores review metadata, final results, and findings; live transcripts stay in -memory. Restored reviews appear in the UI but are unavailable to new MCP -sessions. - -`ReviewUI` observes the store and forwards user actions to it. UI tests cover -layout, selection, rendering, accessibility text, and action forwarding. -`CodexReviewTests` and `CodexReviewAppServerTests` cover review, authentication, -settings, and protocol behavior. +History keeps review metadata, final results, and findings in SQLite. Live +transcripts stay in memory. After relaunch, the UI restores past reviews. +Each MCP session can access only the jobs it started. ## Codex updates -`CodexReviewStore.updateCodex(when:install:)` pauses new review execution while -keeping accepted jobs and MCP sessions. It waits for current reviews or cancels -them according to the requested timing, finishes cleanup, stops the old runtime, -runs the installation closure, and starts the replacement runtime. Queued jobs -resume once that runtime is ready. Concurrent update calls wait for the same -operation, using the first call's installation closure. - -Recovery checks whether the owned process has closed. A previously recorded -close error alone does not prevent recovery if the process is now closed. - -The app's `ReviewMonitorCodexUpdater` owns update checks and their results. -Settings and the sidebar share that instance. Automatic checks run at launch -and at eight-hour intervals measured from launch. Manual checks join a check -already in progress and keep that schedule. A check due during installation -runs once after the update. - -On application termination, the app stops checking, shuts down the store, and -waits for startup work before replying to AppKit. Store shutdown cancels an -update still waiting for reviews or waits for an installation already in -progress. Codex updates restart the runtime within the running app. - -### Simulate an update - -To inspect UI responsiveness, set `REVIEW_MONITOR_SIMULATE_CODEX_UPDATE=1` in the -Xcode scheme's **Run → Arguments → Environment Variables** and launch the app. -Use the live runtime with `REVIEW_MONITOR_MOCK_JOBS` and -`REVIEW_MONITOR_REVIEW_MODE` disabled. +`ReviewMonitorCodexUpdater` checks for CLI updates. The store keeps the MCP +listener open and queues new reviews while an update is pending. It drains or +cancels active reviews according to the user's choice, waits for cleanup, +and stops the old app-server before running the installer. Queued reviews +resume in acceptance order once the replacement runtime is ready. -After a one-second simulated check, the normal **Update** button appears. The -installation step waits ten seconds through the same subprocess runner as a -real update. The existing Codex runtime stops and restarts normally, while the -Codex and Homebrew packages stay unchanged. Settings then shows **Up to Date**. -Relaunch the app to repeat the simulation. +To exercise this flow in Xcode, set `REVIEW_MONITOR_SIMULATE_CODEX_UPDATE=1` +with `REVIEW_MONITOR_MOCK_JOBS` and `REVIEW_MONITOR_REVIEW_MODE` disabled. The +app simulates installation and restarts the live runtime. diff --git a/Docs/deferred-codex-update-design.md b/Docs/deferred-codex-update-design.md deleted file mode 100644 index fb44c923..00000000 --- a/Docs/deferred-codex-update-design.md +++ /dev/null @@ -1,199 +0,0 @@ -# レビューを待たせて Codex を更新する - -2026-09-26 に承認した設計。基準 commit は -`b19308aa72492797cb4fd7abfbbb28735b4d7cd0`、実装の分割は -[親 Issue #382](https://github.com/lynnswap/CodexReviewKit/issues/382) に記録する。 -ここでいう変更前の動作は、この commit 時点のもの。 -現在の構成は [architecture.md](architecture.md#codex-updates) を参照。 - -「後でアップデート」を選ぶと、実行中のレビューを最後まで続け、以後の要求を -`CodexReviewStore` のキューに入れる。レビューが終わったら Codex を更新し、 -app-server を再起動してキューのレビューを開始する。Monitor と MCP セッションは -その間も維持する。 - -## 一度の呼び出しで受付から結果を待つ - -クライアントは従来どおり `review_start` を一度呼ぶ。Store は要求を検証し、 -ジョブ ID とセッションの所有権を割り当て、履歴を保存する。更新予約中は -`Queued` と表示し、app-server のスレッドや turn の作成を待たせる。 - -MCP 呼び出しは、キュー待ち、更新、レビュー実行を通して同じジョブの結果を待つ。 -クライアントに要求を再送させない。状態確認とキャンセルは更新中も使える。 - -```mermaid -sequenceDiagram - participant L as MCP クライアント - participant S as CodexReviewStore - participant C as app-server - participant U as Codex 更新処理 - Note over S: 「後でアップデート」を選択 - L->>S: review_start(B) - Note over S: B をキューで保持し、MCP 呼び出しを待機 - C-->>S: 実行中レビュー A の完了 - Note over S,C: A の結果保存と後片付けを完了し、旧プロセスを終了 - S->>U: codex update を一度実行 - U-->>S: 更新結果 - S->>C: 現在の CLI から app-server を起動・初期化 - S->>C: B を開始 - C-->>S: B の最終結果 - S-->>L: review_start(B) の結果 -``` - -予約後の新規要求はすべてキューに入るため、要求が続いても更新を始められる。 -予約前に起動処理へ進んだレビューは完了を待つ。履歴保存中の要求は、保存後に -更新状態を確認して実行か待機を決める。 - -更新後は Store の受付順でレビューを開始する。履歴の保存完了順は使わない。 -開始後は通常どおり並行実行し、先のレビューが終わるまで次を止めることはしない。 - -### MCP の待機上限は540秒 - -`review_start` と `review_await` の上限は、キュー待ちを含めて540秒とする。 -完了しなければ既存形式のジョブ ID と `queued` / `running` を返し、クライアントは -`review_await` で同じジョブを待てる。時間切れや接続切断でキューへ再投入しない。 -HTTP heartbeat は接続維持に使い、LLM 向けのメッセージを増やさない。 - -540秒を超える場合は追加の待機呼び出しが必要になる。これをなくすには、固定の -タイムアウトを持つクライアント側の契約も変更する必要がある。 - -## 受付と実行開始を分ける - -| 変更前の動作 | この設計での変更 | -| --- | --- | -| `beginReview` は保存後すぐに worker を作り、`running` にする | 受付・保存と worker 開始を分け、更新予約中は待たせる | -| `hasRunningJobs` はすべての未完了ジョブと待機処理を含む | 更新は app-server を使用中のレビューと後片付けだけを待つ | -| `admitRuntimeReplacement` は受付を閉じ、保存中の開始要求をキャンセルする | 更新では受付・参照・キャンセルを維持し、実行開始を保留する | -| app-server 終了時に未完了レビューをまとめてキャンセルする | 更新では実行前のキューを保持する。アプリ終了とサインアウトの契約は保つ | -| `store.shutdown()`、更新、Monitor 全体の再起動を行う | Kit が app-server だけを入れ替え、MCP セッションを維持する | -| 起動時と確認後20時間ごとに確認し、設定画面には確認操作がない | 起動時と起動から8時間ごとに確認し、設定画面からも同じ checker を使う | - -関連する実装: - -- [レビューの受付と worker 開始](../Sources/CodexReview/Store/CodexReviewStoreReviews.swift) -- [Store の runtime 差し替えと未完了判定](../Sources/CodexReview/Store/CodexReviewStore.swift) -- [レビュー処理の登録と終了](../Sources/CodexReview/Store/ReviewStoreLifecycle.swift) -- [更新処理](../Tools/ReviewMonitor/CodexReviewMonitor/ReviewMonitorCodexUpdater.swift) -- [停止確認](../Tools/ReviewMonitor/CodexReviewMonitor/CodexReviewMonitorApp.swift) - -## Store がキューと更新操作を持つ - -既存の package と target を使い、レビューと runtime の状態を Store に集約する。 - -| 処理・状態 | 担当 | -| --- | --- | -| 更新予約、レビュー完了待ち、キュー、再開 | `CodexReviewStore` | -| 受付・実行開始・終端の保存 | 履歴 coordinator と `CodexReviewPersistence` | -| app-server の終了・生成・初期化、設定の引き継ぎ | Store の runtime 差し替え処理と `CodexReviewHost` | -| CLI の解決とプロセス I/O | Host / AppServer 層 | -| 更新可否の確認、`codex update` の実行 | 既存の更新処理を Store へ渡す | -| 自動・手動確認とその結果 | `ReviewMonitorCodexUpdater`。設定画面とサイドバーで共有する | -| MCP 呼び出しと完了待機 | MCP adapter と Store | -| 更新待ち・進行・失敗の表示と操作 | アプリと `ReviewUI` | - -キューは受付済みのジョブを参照し、対象・cwd・モデルを受付時の要求から保持する。 -アプリに再投入用の一覧や UI 専用ジョブを作らない。更新の段階も Store の一つの -操作で管理し、Updater に複製しない。 - -### アプリから呼ぶ API - -設計時の利用例: - -```swift -try await store.updateCodex(when: .afterCurrentReviews) { - try await installer.install(plan) -} -``` - -`updateCodex` は ApplicationHostSupport SPI とし、タイミングは -`afterCurrentReviews` と `immediately` を用意する。呼び出し側は一度呼んで -結果を待ち、キューの停止・再開を個別に操作しない。汎用のメンテナンス API は -追加しない。 - -`installer.install(plan)` は `codex update` の完了を返す。テストではこれと -backend transport を差し替え、Store のキューと runtime の処理を本番と同じ -経路で確認する。 - -## 終了を確認してから更新する - -更新操作は実行中レビューの結果保存と backend の後片付けを待つ。 -既存の cleanup timeout を使い、待機ジョブまで含む「全未完了ジョブがゼロ」を -開始条件にしない。 - -旧 app-server の終了を確認した後で `codex update` を実行する。取得と -インストールを分離できないため、レビューと並行してダウンロードを先行させない。 -専用のダウンロード状態や二重のキャッシュも設けない。 - -更新後は CLI を再探索し、認証・設定を読み直して runtime を起動する。 -起動に成功したらキューを worker 開始処理へ渡す。ボタンを再度押した場合や -MCP の待機上限に達した場合も、同じ更新操作とジョブを維持する。 - -### 失敗時も待機ジョブを保持する - -| 状況 | 動作 | -| --- | --- | -| 更新失敗後に現在の CLI で起動できる | エラーを表示してキューを再開する。旧版へ戻ったとは扱わない | -| 旧 app-server の終了を確認できない | インストールを始めず、状態と残ったプロセスを報告してキューを保持する | -| 更新後の起動・認証・設定復元に失敗する | MCP とキューを維持し、既存の再試行で復旧後に再開する | -| 待機ジョブをキャンセルする、または所有セッションを明示終了する | app-server へ送る前にキャンセルし、履歴と待機呼び出しへ結果を返す | -| アプリを明示終了する | 終了処理に参加する。実行中の更新コマンドは結果が確定するまで待つ | - -アカウント切替・サインアウト・手動再起動は更新と直列化する。既存の確認と -キャンセルを保ち、待機要求を別アカウントへ移さない。状態参照は更新完了を -待たずに使える。 - -## 待機中も履歴とキャンセルの対象にする - -受付時刻と実行開始時刻を分け、`queued` の間は実行時間を計測しない。 -受付履歴の保存に失敗したら要求を失敗として返し、メモリだけに受理済みジョブを -残さない。既存の履歴保存にキューと実行開始を加え、新しい保存ファイルは作らない。 -古い履歴は従来どおり実行済みとして読めるようにする。 - -アプリを継続稼働させている間の更新を対象とする。クラッシュや終了後は既存の -復元処理で中断した履歴を表示し、以前の MCP セッションのジョブを自動実行しない。 - -## 画面と更新確認 - -レビュー中は「後でアップデート」と「レビューを停止してアップデート」を提示する。 -前者は更新を予約する操作とし、予約後はサイドバーに更新待ち、新規ジョブに -`Queued` を表示する。実行中レビューがなければそのまま更新に進む。 -更新開始後は進行中の表示へ変え、完了後に通常表示へ戻す。 - -既存のウィンドウ、ログ、アカウント表示を保ち、待機・更新中・失敗・再開を -`#Preview` と UI テストで確認する。 - -自動確認は起動直後と、起動から8時間、16時間、24時間の時点で行う。 -確認にかかった時間や手動確認で周期をずらさない。スリープなどで時刻を過ぎたら -復帰後に一度確認し、過ぎた回数分を連続実行しない。 - -自動・手動確認はアプリ全体で一つの処理を共有し、重なれば進行中の確認を待つ。 -インストール中に予定時刻が来たら更新後に一度確認する。設定画面を閉じても -周期を維持し、開くたびに監視タスクを作らない。CLI の起動時チェック設定で -Monitor の確認を停止しない。 - -設定画面の手動ボタンは確認だけを行う。インストール、レビュー停止、キュー予約は -始めない。「確認中」「更新あり」「最新」「確認できない」「確認失敗」を区別し、 -最終確認時刻とエラーを示す。CLI 選択の失敗や未対応のインストール方法を「最新」と -表示しない。結果はサイドバーの Update 表示にも反映する。 - -## 実装と検証の順序 - -1. Kit の受付と実行開始を分ける。キュー、履歴、キャンセル、MCP の完了待機を - 実装し、通常時の並行実行を保つ。 -2. MCP を維持する更新操作を実装する。レビュー完了待ち、runtime 終了、 - 更新、新 runtime の起動、キュー再開を Store が管理する。 -3. 更新 UI と確認周期を接続する。Monitor 再起動用ヘルパーと失敗起動引数を - 削除し、Preview と利用文書を更新する。 - -親 Issue で順序と完了条件を管理し、各単位を一つの Ready PR にする。 -ローカル codex-review、リモートレビュー、CI を通してから main へ統合する。 - -回帰テストは既存の fake backend、transport、時計、gate を使う。 -予約と受付の競合、履歴保存中の要求、複数セッション、待機ジョブのキャンセル、 -更新・終了・再起動の失敗を対象にする。固定時間の経過だけで同期しない。 - -最終確認では同じ MCP セッションで A を実行中に更新を予約し、B と C を受け付ける。 -A の結果を返した後、更新が一度だけ実行され、同じセッション・ジョブ ID で -B と C が完了することを確認する。540秒以内なら再送や追加の待機呼び出しは不要とする。 - -手動時計で起動直後・8時間・16時間の確認を検証する。途中の手動確認が周期を -変えないこと、重複実行しないこと、設定画面とサイドバーの結果が一致することも確かめる。 diff --git a/Docs/mcp.md b/Docs/mcp.md index 081806b6..deab7339 100644 --- a/Docs/mcp.md +++ b/Docs/mcp.md @@ -1,96 +1,71 @@ # MCP reference -ReviewMonitor hosts a Streamable HTTP MCP server at -`http://localhost:9417/mcp`. It shares one long-lived `codex app-server` process -across sessions. Reviews can run concurrently within a session and across -sessions, but each session can access only its own jobs. +ReviewMonitor hosts a Streamable HTTP MCP server at `http://localhost:9417/mcp`. +Send the `MCP-Session-Id` returned by `initialize` with subsequent requests. +Each session can run several reviews and access only its own jobs. Send +`DELETE` to close the session. ## Tools -| Tool | Use | -| --- | --- | -| `review_start` | Start a review and wait for its result | -| `review_await` | Continue waiting for a queued or running review | -| `review_read` | Read a job snapshot and a page of logs | -| `review_list` | List jobs in the current session | -| `review_cancel` | Cancel a job in the current session | - ### `review_start` -Pass `cwd` and a `target`. The target takes one of these forms: +Pass `cwd` and one of these `target` objects. - `{"type":"uncommittedChanges"}` - `{"type":"baseBranch","branch":"main"}` - `{"type":"commit","sha":"abc1234","title":"Optional title"}` - `{"type":"custom","instructions":"Free-form review instructions"}` -The call waits up to 540 seconds, including time spent queued during a Codex -update. If the returned status is still `queued` or `running`, call -`review_await` with the returned `jobId`. - -The response contains `jobId`, `run`, `lifecycle`, and `output`, described -[below](#response-fields). ReviewMonitor starts with its settings model and -reports `thread/start.model` when the server supplies it. Otherwise, it keeps -the requested model. - -The store waits for the terminal history commit before returning the result. -Backend cleanup continues separately. A later cleanup failure appears in -`review_read` with `logFilter: "all"`. +The call waits up to 540 seconds, including time spent in the queue during a +Codex update. If `lifecycle.status` is still `queued` or `running`, pass the +returned `jobId` to `review_await`. ### `review_await` -Pass `jobId` or `jobID` for a job in the current session. Each call waits up to -540 seconds and returns the same fields as `review_start`. Call it again if the -job is still queued or running. - -Use `review_read` for logs; start and await responses contain neither `logs` -nor `rawLogText`. +Pass `jobId` or `jobID` to wait up to another 540 seconds. Repeat until the job +ends. Both tools return the same [response fields](#response-fields). Use +`review_read` for logs. ### `review_read` -Pass `jobId` or `jobID` to read a job independently of start or await. +Pass `jobId` or `jobID` to read a snapshot and one page of logs. | Optional argument | Meaning | | --- | --- | -| `logOffset` | Zero-based offset; omitting it selects the latest page | -| `logLimit` | Page size, default `100`, maximum `500` | -| `logFilter` | `default` excludes command output and developer entries; `all` includes both | +| `logOffset` | Zero-based offset (defaults to the latest page) | +| `logLimit` | Page size (default `100`, maximum `500`) | +| `logFilter` | `all` includes command output and developer entries omitted by `default` | The response adds `logs`, `logsPage`, and `rawLogText` to the common fields. -Before paging, the server folds grouped replacements and deltas into their -current values. Developer entries have `audience: "developer"`; product entries -omit `audience`. +Developer entries have `audience: "developer"`. Product entries omit `audience`. `logsPage` contains `total`, `offset`, `limit`, `returned`, `hasMoreBefore`, `hasMoreAfter`, `previousOffset`, and `nextOffset`. Use the offsets to fetch -adjacent pages. `rawLogText` contains raw diagnostic text, not a full transcript; -use `logs` for ordered log entries. +adjacent pages. Use `logs` for ordered entries and `rawLogText` for diagnostic +text. Backend cleanup can finish after a review returns. Use `logFilter: "all"` +to see cleanup failures. ### `review_list` -Lists jobs in the current session. +List jobs in the current session. | Optional argument | Meaning | | --- | --- | | `cwd` | Filter by working directory | | `statuses` | Filter by lifecycle status | -| `limit` | Number of jobs, default `20`, maximum `100` | +| `limit` | Number of jobs (default `20`, maximum `100`) | Each entry in `items` contains `jobId`, `cwd`, `targetSummary`, `run`, `lifecycle`, and `output`. ### `review_cancel` -Pass `jobId` to cancel one job, or use `cwd` and `statuses` to select jobs in the -current session. A working directory can match more than one job. - -The response includes cancellation source and message when available. -Cancellations from the app use `source: "userInterface"`. +Pass `jobId` to cancel one job. You can also select a job by `cwd` and +`statuses`. If several jobs match, use the ID of the one you want to cancel. ## Response fields -Start, await, read, and cancel responses share these fields. List entries use -the same `run`, `lifecycle`, and `output` objects. +Start, await, read, and cancel responses include `jobId` and these objects. | Object | Fields | | --- | --- | @@ -104,16 +79,15 @@ the same `run`, `lifecycle`, and `output` objects. ### Lifecycle responses `status` is `queued`, `running`, `succeeded`, `failed`, or `cancelled`. -`terminal` is `null` while the job is queued or running. Once it ends, the -terminal object records its outcome: +`terminal` is `null` while the job is queued or running. | Outcome | Terminal object | Status | | --- | --- | --- | | Completed | `{"kind":"completed"}` | `succeeded` | | Failed | `{"kind":"failed","message":}` | `failed` | -| Interrupted | `{"kind":"interrupted","cause":}` | `cancelled` for requested interruption; otherwise `failed` | +| Interrupted | `{"kind":"interrupted","cause":}` | `cancelled` for requested interruptions, otherwise `failed` | -An interruption cause contains `kind`, `source`, and `message`: +For an interrupted review, inspect `cause.kind`. | `kind` | `source` | `message` | | --- | --- | --- | @@ -128,24 +102,5 @@ it ended. ## Help resources -Use `resources/list` and `resources/read` to read help from the server: - -- `codex-review://help/overview` -- `codex-review://help/tools/review_start` -- `codex-review://help/tools/review_await` -- `codex-review://help/targets/uncommittedChanges` -- `codex-review://help/targets/baseBranch` -- `codex-review://help/targets/commit` -- `codex-review://help/targets/custom` - -`resources/templates/list` also provides templates for tool and target help. - -## Runtime files - -ReviewMonitor keeps its Codex runtime files in `~/.codex_review`: - -| File | Contents | -| --- | --- | -| `config.toml` | Backend settings | -| `review_mcp_endpoint.json` | Current HTTP/SSE endpoint | -| `review_mcp_runtime_state.json` | Server and runtime ownership state | +Read `codex-review://help/overview` for a tool summary. Use `resources/list` +to discover tool and target examples, then `resources/read` to open one. diff --git a/Docs/releases.md b/Docs/releases.md index 1de5b3e3..55142ddc 100644 --- a/Docs/releases.md +++ b/Docs/releases.md @@ -1,12 +1,12 @@ # Release and build guide -For installation and MCP setup, see the [README](../README.md#quick-start). -Run the commands in this guide from the repository root. +Run these commands from the repository root. ## Publish a release -Complete the [signing setup](#one-time-signing-setup), then approve the version, -notes, and source commit. Save the approved notes in a UTF-8 file and run: +Complete the [signing setup](#one-time-signing-setup) and approve the version, +release notes, and current `main` commit. Pass the saved UTF-8 notes to the +release script. ```bash python3 scripts/prepare_release.py start \ @@ -15,69 +15,46 @@ python3 scripts/prepare_release.py start \ --notes-file /path/to/release-notes.md ``` -Add `--prerelease` for a prerelease. The command creates the approved version tag -and a draft targeting the current remote `main` commit, starts CI, and returns. -The tag is immediately available. A matching tag and draft are reused on retry; -conflicting tags are never moved. If workflow dispatch is uncertain, check -Actions before retrying; the tag and draft remain available. +Add `--prerelease` for a prerelease. The command tags the current remote +`main` commit, creates a draft, and starts CI. If dispatch is uncertain, check +Actions before retrying. The command can reuse a matching tag and draft. -CI checks and builds the app, then waits for approval of the `release-signing` -Environment in GitHub. After approval, it signs with Developer ID, notarizes, -verifies and uploads the assets, and publishes the same draft. The draft's title -and notes are preserved. Publication continues without a local process watching -the run. +Once checks pass, approve the `release-signing` deployment in GitHub. The +workflow signs the app and DMG, submits the DMG for notarization, verifies +the assets, and publishes the draft. ### Use an existing draft -Save the version, title, notes, and prerelease setting in GitHub, with `main` as -the target. Open -[Publish Release](https://github.com/lynnswap/CodexReviewKit/actions/workflows/release.yml), -choose **Run workflow** on `main`, and enter the draft's tag. -[Creating or editing a draft does not trigger Actions](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#release), -so dispatch the workflow once. An API-created draft can instead target the full -workflow commit SHA; the workflow rejects a different commit. +Save the draft in GitHub with its version, title, notes, prerelease setting, +and `main` as the target. In the +[Publish Release workflow](https://github.com/lynnswap/CodexReviewKit/actions/workflows/release.yml), +choose **Run workflow** on `main` and enter the draft's tag. An API-created +draft may also target the workflow's full commit SHA. ### Assets and retries -The workflow pins the draft to its full source SHA and creates its tag before -building, including when started from a draft created in GitHub. Checks pass -before signing, which runs separately with native Apple tools and a temporary -keychain. The signing job does not run the app. The publication job verifies -these three assets: +Keep the tag, source commit, and prerelease setting fixed during a run. You +can edit the draft's title and notes. The tag's numeric part sets the marketing +version (`v1.2.3-beta.1` becomes `1.2.3`). The run number sets the build version. -- The DMG -- `release-info.json` -- `SHA256SUMS` - -Only those assets may be attached when the draft is published. Remove unintended -attachments before retrying. Publication requires the tag to still match the -tested commit. - -A failure before publication leaves the tag in place and the draft unpublished. Rerun failed jobs to -reuse completed build and signing artifacts. An uploaded asset with matching -bytes is kept; different bytes under the same name stop publication. If -publication succeeded but confirmation failed, rerunning the publication job -checks the existing assets and tag without changing the release. - -Rerunning the whole workflow can produce different artifacts. Inspect existing -draft assets before removing them and retrying. While a run is active, keep its -tag, source commit, and prerelease setting fixed. You can edit the title and -notes. Apple may continue notarization after a workflow timeout; use the -submission ID in the diagnostics to identify it. - -The tag's numeric part sets the marketing version: `v1.2.3-beta.1` becomes -`1.2.3`. Filenames and metadata retain the full tag. The workflow run number is -the build version, and a retry of the same run keeps that number. +- If a job fails, rerun the failed jobs to reuse the tested artifacts. A full + rebuild can produce different bytes. After a notarization timeout, use the + submission ID in the diagnostics to check its status. +- The draft may contain only the DMG, `release-info.json`, and `SHA256SUMS`. + Publication keeps matching assets and stops on conflicting ones. Inspect + unexpected attachments before removing them and retrying. +- If publication succeeded but confirmation failed, rerun the publication job + to verify the published assets and tag. ## One-time signing setup In **Settings → Environments → release-signing**, allow only `main` and require a reviewer. Leave **Prevent self-review** off if the maintainer starting the run -will also approve signing. CI publishes after approval and successful checks. +will also approve signing. | Environment secret | Value | | --- | --- | -| `DEVELOPER_ID_P12_BASE64` | Base64-encoded, password-protected `.p12` with the intended Developer ID Application certificate and private key | +| `DEVELOPER_ID_P12_BASE64` | Base64-encoded, password-protected `.p12` containing one Developer ID Application certificate and its private key | | `DEVELOPER_ID_P12_PASSWORD` | Export password for the `.p12` | | `NOTARY_API_PRIVATE_KEY` | Full contents of the App Store Connect Team API key's `.p8` file | @@ -87,15 +64,13 @@ will also approve signing. CI publishes after approval and successful checks. | `NOTARY_API_KEY_ID` | App Store Connect API key ID | | `NOTARY_API_ISSUER_ID` | Team API key issuer UUID | -Export one valid **Developer ID Application** identity, including its private -key, to the password-protected `.p12`, and keep a secure backup. An -`Apple Development` certificate cannot sign this distribution. For -notarization, create a dedicated **Team API key** with the **Developer** role. -That role also permits operations beyond notarization and this app. See -[Apple's Developer ID guide](https://developer.apple.com/help/account/certificates/create-developer-id-certificates/) -and [API key management](https://developer.apple.com/help/app-store-connect/get-started/app-store-connect-api/). +Use a dedicated Team API key with the **Developer** role for notarization. +This role also grants access beyond notarization. See Apple's guides to +[Developer ID certificates](https://developer.apple.com/help/account/certificates/create-developer-id-certificates/) +and [API keys](https://developer.apple.com/help/app-store-connect/get-started/app-store-connect-api/). -With GitHub CLI authenticated, upload secrets from local files: +Upload the secrets from local files with GitHub CLI. The password command +prompts for the export password. ```bash base64 < /secure/path/DeveloperID.p12 | gh secret set DEVELOPER_ID_P12_BASE64 \ @@ -106,32 +81,16 @@ gh secret set NOTARY_API_PRIVATE_KEY \ --repo lynnswap/CodexReviewKit --env release-signing < /secure/path/AuthKey.p8 ``` -The password command prompts for its value. Add the three variables in the -Environment's Variables section. The signing step checks the imported -certificate's team and type, then removes the temporary keychain and decoded -key files when it finishes. Keep credentials out of the repository and build -artifacts; update or revoke them through Apple and GitHub. - ## Release build validation -Open -[Release Build](https://github.com/lynnswap/CodexReviewKit/actions/workflows/release-build.yml), -choose **Run workflow** on `main`, and enter a label such as -`v0.0.0-validation`. The build also runs on pushes to `main`. - -The workflow uses the runner's default Xcode, packages the selected commit -without Finder or Apple credentials, and verifies the mounted app. Download the -DMG, `build-info.json`, and `SHA256SUMS` from its artifact, retained for seven -days. The metadata records the commit, version label, Xcode version, and run. -The label's numeric part sets the marketing version; the run number sets the -build version. +The [Release Build workflow](https://github.com/lynnswap/CodexReviewKit/actions/workflows/release-build.yml) +runs on pushes to `main`. To start it manually, choose **Run workflow** on +`main` and enter a label such as `v0.0.0-validation`. The artifact contains +an unsigned validation DMG with an ad-hoc-signed app, `build-info.json`, and +`SHA256SUMS` for seven days. For installation, download the notarized DMG from +the [latest release](https://github.com/lynnswap/CodexReviewKit/releases/latest). -Validation artifacts use an ad-hoc app signature. The DMG has no Developer ID -signature or notarization, and the workflow creates no tag or GitHub Release. -Use a signed public release for installation. - -For the same packaging locally, prepare Python 3.10 or newer and the pinned -DMG tools: +To validate the same packaging locally, use Python 3.10 or newer. ```bash python3 -m venv .build/release-tools @@ -143,48 +102,17 @@ scripts/package-release.sh --version v0.0.0-validation ``` Local validation uses build number `1`. Pass `--build-number` to the build -script for another positive integer. +script to select another positive integer. ## Local builds -For a local app build, use an Apple silicon Mac with Xcode 26.4 or newer and -Python 3.10 or newer: - -```bash -python3 scripts/build_review_monitor.py -``` - -The script creates `dist/CodexReviewMonitor_yymmdd_hhmm.dmg`, named with the local -build-start time. It applies an ad-hoc hardened-runtime signature and verifies -the DMG contents. Caches stay in `.build`; the first run prepares the pinned -DMG tools in `.build/release-tools` and may download locked package dependencies. - -ReviewMonitor can stay open during the build. When reviews finish, quit the -app, open the DMG, drag the app to Applications, choose **Replace**, and relaunch. -You can replace the app without deleting it first. The script leaves installed -apps alone. Builds started in the same minute replace the same DMG only after -the new image passes validation; older filenames are kept. - -The ad-hoc signature is for local use. To select an approved local identity, -pass it explicitly: +The [local build command](../README.md#build-from-source) requires an Apple +silicon Mac with Xcode 26.4 or newer and Python 3.10 or newer. It uses ad-hoc +signing by default. To select a local identity, pass `--signing-identity`. ```bash python3 scripts/build_review_monitor.py \ --signing-identity 'Apple Development: Developer Name (TEAMID)' ``` -The script uses that identity or fails; it never falls back to another one. -Local signing does not notarize the app or make it suitable for redistribution. -Device-management policy can still prohibit it. The script leaves Gatekeeper -and quarantine metadata in place. The app requires macOS 26 or newer. - -## Repository protection - -The `main` ruleset requires a PR, resolved review threads, and passing GitHub -Actions checks against the current base branch. It blocks deletion and force -pushes. A solo maintainer can merge a reviewed PR without another human approval. -CI also runs for documentation changes so required checks can finish on every PR. - -Only `main` can use `release-signing`. Build validation uses neither that -Environment nor Apple secrets. Signing checks that its input artifact ID and -file digest belong to the build in the same workflow run. +Use the release workflow for a notarized DMG. diff --git a/Docs/review-history-persistence-design-2026-08-29.md b/Docs/review-history-persistence-design-2026-08-29.md deleted file mode 100644 index d1241548..00000000 --- a/Docs/review-history-persistence-design-2026-08-29.md +++ /dev/null @@ -1,403 +0,0 @@ -# Review history persistence design - -Design and validation record begun on 2026-08-29. The measurements and delivery -status below belong to that implementation, not the current checkout. See -[architecture.md](architecture.md) for the current target structure. - -| Item | Recorded value | -| --- | --- | -| Status | Re-gated after adversarial review; implementation in progress | -| Integration branch | `codex/persist-review-history` | -| Baseline | `22b1e975015b0bf24b45dad669a91c8b52fd8d2c` | -| Target base | `main` | -| Database framework | SQLiteData 1.11.2 | -| Package baseline | Swift tools 6.3 / Swift language mode 6 | -| Local validation | Xcode 27.0 / Swift 6.4 | -| CI compatibility | Latest stable Xcode 26 runner selected by `.github/workflows/ci.yml` | - -## What history preserves - -ReviewMonitor restores review history after relaunch. Each row keeps its ID, -workspace, manual order, typed target, effective model, lifecycle, final review, -and structured findings. The detail view derives a compact display from those -fields. Transcripts stay in memory. - -Manual review order applies across the app. A repository section can combine a -primary checkout with linked worktrees, while each review keeps its original -`cwd`. Existing databases migrate by sorting workspaces first, then the previous -workspace-local review order, preserving the visible order. - -Acceptance requires: - -1. A completed, failed, or cancelled review returns as one sidebar row after a - clean restart, with its target, model, known duration, terminal cause, result, - and findings. -2. A queued or running row left by the previous process becomes - `.interrupted(.previousProcessExit)`. It has no invented end time and cannot - appear live or cancellable. -3. History stays readable while the MCP runtime starts, stops, or fails. A new - MCP session cannot list, read, await, or cancel previous-process records. -4. Database open, migration, decode, and write failures are visible at the store - and block new review admission. The database is retained. -5. An isolated app E2E run completes a real review, terminates, relaunches, and - verifies the restored sidebar, detail, and findings. - -The four library products and their public source surface stay compatible, as -do the five MCP tool names, schemas, response fields, and session access rules. -Account, settings, and runtime persistence stay unchanged. At the baseline, -there was no shipped history database requiring migration. The original task -also authorized local commits, push, and a Ready PR. - -History excludes transcripts, raw JSON-RPC, reasoning, command output, tool -results, diagnostics, streaming deltas, credentials, account secrets, finding -`rawText`, and rendered projections. This work does not add event replay, -cross-process review resumption, source archives, working-tree snapshots, -diffs, or CloudKit synchronization. Thread and turn IDs cannot authorize or -resume a review after relaunch. - -## Problems at the baseline - -| Finding | Problem | Design response | -| --- | --- | --- | -| F1 | Store seeds contain accounts and settings, but no durable review membership | Load records through a history port and SQLite adapter | -| F2 | `CodexReviewJob` mixes results with logs, message assembly, rendering, revisions, and mutation hints | Persist semantic records instead of encoding the job | -| F3 | Admission passes the typed target to the worker but retains only `targetSummary` | Store the validated target without parsing its display text | -| F4 | The 256 KiB cap excludes some log kinds and metadata | Keep the final-result bound; omit a generic log table | -| F5 | Detail reads `job.logEntries`, while findings read `core.output.reviewResult` | Derive compact final, error, or cancellation entries from history | -| F6 | Sidebar runtime-unavailable state hides existing jobs | Keep history visible and show runtime health in the status accessory | -| F7 | MCP sessions and app history have different lifetimes | Restore rows with a non-live session identity and keep MCP filters | -| F8 | `PreparedRecoveryEnvironment.withHistoryDatabaseURL` also depends on replacement-home, login, and account staging | Give history its own Application Support location and remove the unused helper | - -Recorded source measurements: - -| Target | `public` | `package` | `open` | -| --- | ---: | ---: | ---: | -| `CodexReview` | 225 | 872 | 8 | -| `CodexReviewHost` | 45 | 99 | 10 | -| `ReviewUI` | 9 | 2 | 2 | - -There were no `#if canImport` or `#if os` source gates. The largest relevant files -were `LiveCodexReviewStoreBackend.swift` (3,701 lines), -`CodexReviewStoreReviews.swift` (2,685), -`ReviewMonitorSidebarViewController.swift` (2,672), -`CodexReviewStore.swift` (1,709), and `CodexReviewJob.swift` (1,004). - -## Owners and dependencies - -`CodexReviewPersistence` is an internal target in the same package. It owns -SQLiteData schema, migrations, queries, transactions, retention, and close. -`CodexReview` defines the records and persistence interface, and -`CodexReviewHost` supplies the production location and adapter. This keeps -SQLiteData out of the store and UI without adding a product or versioned package. - -Putting storage in `CodexReviewHost` would add schema and query work to the -3,701-line runtime adapter. Putting it in `CodexReview` would couple review -behavior to concrete database I/O and make preview and test selection less clear. - -```text -ReviewUI ───────────────────────────────▶ CodexReview -CodexReviewMCPServer ───────────────────▶ CodexReview -CodexReviewPersistence ─▶ CodexReview + SQLiteData -CodexReviewHost ─────────┬──────────────▶ CodexReview - └──────────────▶ CodexReviewPersistence -ReviewMonitor.app ─────────────────────▶ CodexReviewHost + ReviewUI -``` - -| Owner | Responsibility | -| --- | --- | -| `CodexReview` | Live review behavior, app-wide manual order, and history contract | -| `CodexReviewPersistence` | Save and restore review records in SQLite | -| `CodexReviewHost` | Owner-only database location and live adapter | -| `ReviewUI` | Render store state, group repository sections, and pass workspace scope for deletion and reordering | -| `CodexReviewMCPServer` | Restrict commands to the current session | - -Update this design before changing an owner, schema, lifecycle, failure -behavior, or MCP access policy. - -### Lifetime and write order - -At composition, the host prepares the owner-only Application Support directory -and injects a database with its exact URL. The first store load opens and -migrates the database, finalizes abandoned rows, and restores history before -accepting reviews. Admission saves a start header before dispatching backend -work. Finalization saves the terminal result, findings, and retention changes -in one transaction. - -Application shutdown drains workers, synchronizes terminal snapshots and order, -then closes the database before replying to termination. Runtime `stop()`, -restart, and account switching leave history open. - -The store coordinates three kinds of work: - -- `HistoryStartReceipt` captures target, model, job and workspace order, session, - and admission before the write. Session and runtime close can see pending - receipts. After saving, the store rechecks the receipt; a stale request gets a - durable terminal result without backend dispatch. -- `HistoryTerminalReceipt` holds the first terminal snapshot and one commit per - live job. Worker completion, cancellation responses, runtime detach, waiters, - and shutdown all wait for that commit. -- `ReviewHistoryMutationCoordinator` runs each database mutation and its - MainActor state change in the same order. Reorder, retention, and deletion - therefore update the store in database commit order. - -The store retains those tasks and receipts until shutdown has waited for them. -Database writes alone cannot establish this ordering if their results are -applied independently on the MainActor. - -## Persistence interface - -New declarations use `package` access unless an existing public API requires -otherwise. SQLiteData and GRDB types stay in `CodexReviewPersistence`. - -```swift -package protocol ReviewHistoryPersistence: Sendable { - func load(retentionPolicy: ReviewHistoryRetentionPolicy) - async throws -> [RestoredReviewRecord] - func recordStarted(_ record: StartedReviewRecord) async throws - func recordTerminal( - _ record: TerminalReviewRecord, - retentionPolicy: ReviewHistoryRetentionPolicy - ) async throws - -> ReviewHistoryMutationResult - func saveOrdering(_ ordering: ReviewHistoryOrdering) async throws - func deleteTerminalReview(id: String) async throws - -> ReviewHistoryMutationResult - func deleteAllTerminalReviews() async throws - -> ReviewHistoryMutationResult - func close() async throws -} - -package enum ReviewHistoryAvailability: Sendable, Equatable { - case loading - case available - case failed(String) - case closed -} - -@MainActor -extension CodexReviewStore { - package func deleteReviewHistory(id: String) async - package func deleteAllReviewHistory() async - package func reorderJob( - id: String, - inWorkspaces cwds: Set, - before nextJobID: String? - ) async -> Bool - public func shutdown() async -} -``` - -Immutable Sendable values cross this interface: - -| Record | Contents | -| --- | --- | -| `StartedReviewRecord` | ID, cwd, workspace and job order, typed target, captured model, non-optional start time | -| `TerminalReviewRecord` | ID, model, typed terminal, optional end time, summary, and completed-only final result and parsed findings | -| `RestoredReviewRecord` | A compatible start and terminal pair; active rows cannot form this value | - -The live adapter lazily creates and owns `any DatabaseWriter` and its close -state. Production opens a `DatabasePool` at the supplied URL on first load; -tests can inject a `DatabaseQueue` or `DatabasePool`. It does not use -`prepareDependencies`, `@Dependency(\.defaultDatabase)`, or SQLiteData -`defaultDatabase(...)`. `CodexReviewStore` remains `@MainActor`. - -Consumers keep their existing construction: - -```swift -let store = CodexReviewStore.makeLiveStore(...) -ReviewMonitorWindowController(store: store, ...) -``` - -The host assembles storage behind `makeLiveStore`. App termination calls the -additive `store.shutdown()` instead of runtime-only `stop()`. - -## Schema - -SQLiteData `@Table` records describe storage rather than the observable job. - -`review_workspaces` stores `cwd` as its primary key and a `sortOrder`. - -`review_records` stores: - -- Stable review ID and workspace `cwd` foreign key -- Unique app-wide `sortOrder` -- Typed target and payload, captured/effective model -- Lifecycle and typed terminal, cancellation, and interruption fields -- `startedAt`, nullable `endedAt`, summary, and final review -- Parsed-result state, source, and parser version -- `terminalCommittedAt` and creation/update timestamps - -`review_findings` stores a stable finding ID, review foreign key with -`ON DELETE CASCADE`, ordinal, priority, title, body, path, and start/end line. -The pair `(reviewID, ordinal)` is unique. - -Tables are `STRICT`, with foreign keys, explicit indices, and versioned, -append-only migrations. Production keeps history during schema changes. -Active rows have no terminal payload. Terminal rows have a compatible typed -terminal; success requires non-empty final review text within the 256 KiB -limit. Findings and parser metadata commit with the terminal result. - -The port excludes session, thread, and turn IDs, exit code, raw logs, and -rendered values. Restored rows derive title, elapsed time, final flag, and -compact logs from stored fields. A terminal write changes only terminal and -result fields of an active row, preserving cwd, target, and order. - -Reordering updates the whole supplied repository section in one store mutation, -preserving each review's `cwd`. Views filter the app-wide order without -regrouping by workspace or storing another UI order. New reviews reserve unique -app-wide positions. Load, start insertion, and order saving reject duplicate -positions, including collisions with rows omitted from a partial update. - -### Retention - -Keep at most 50 terminal reviews per workspace and 500 globally. Prune the -oldest by `(terminalCommittedAt, id)` at startup and after terminal commit. -Protect the completing review in its transaction so the API can read its result, -and keep all active rows. Return pruned IDs to update store membership, then -remove workspaces with no reviews. Version 1 has no time-based expiry. - -## Failures - -| Failure | Result | -| --- | --- | -| Open, migration, load, or decode | Set history to `.failed`, retain the database, continue runtime/auth/settings startup, and reject new reviews with an I/O error | -| Start-header write | Publish no live row and dispatch no backend review | -| Session, runtime, or app closes during a start write | Commit one requested interruption and dispatch no backend work | -| Terminal write | Keep the in-memory outcome, set history to `.failed`, return the completed review's actual result, and reject new starts until a successful app launch | -| Delete or reorder | Keep durable membership/order, set history to `.failed`, and report failure | -| Close | Publish/log the error and wait for the close attempt before termination completes | - -On startup, queued and running rows become -`.interrupted(.previousProcessExit)` with unknown `endedAt`. The UI shows -neither a running timer nor an invented duration. Once application shutdown -enters `.closing`, start and restart cannot acquire a runtime; repeated shutdown -calls wait for the same completion. - -## Boundaries to keep - -Storage, target codecs, and terminal mappings can vary behind the history -interface. Live, preview, and test persistence are selected at composition. -A new target needs a codec/schema migration; a new terminal cause needs a typed -mapping and round-trip test. Runtime availability changes presentation without -changing history membership. - -Remove `PreparedRecoveryEnvironment.withHistoryDatabaseURL` and its isolated -test so the production history location has one owner. Keep the Store and MCP -public behavior, using restored semantic records in the existing UI model. - -Use the history port separately from `CodexReviewStoreBackend`; transport and -storage can vary independently. Keep SQLiteData `@FetchAll` out of leaf views. -`writeDiagnosticsIfNeeded` remains optional test output: it catches write -errors and includes raw/rendered values, so it cannot serve as persistence. -Retain database tasks and explicitly await close rather than relying on deinit. -A corrupt database reports failure without a fallback path or recreation. - -## Validation - -### Adapter - -Test fresh migration and constraints, every target and terminal round trip, -findings transactions and cascade deletion, abandoned-row conversion, retention, -and returned pruned IDs. Invalid or incompatible rows must fail without erasing -data, and operations after close must fail. Cover both temporary-file and -in-memory databases. - -### Store - -Verify that history loads once before admission and start headers save before -dispatch. After a suspended write, recheck the session, work admission, model, -and order. A failed start must publish no row and dispatch no backend work. - -Waiters, cancellation responses, runtime detach, and worker finalization must -wait for terminal persistence. A failed write must expose the error and block -later starts while preserving the completed review's outcome. Restored rows -must remain inaccessible to new MCP sessions. - -Test overlapping reorder, delete, and retention operations for matching database -and store membership/order. Deletion must also update workspace membership and -the selection source. Shutdown must drain workers, synchronize terminal rows -and order, wait for receipts, and close once, rejecting restart and runtime -acquisition during shutdown. - -### UI and app - -Verify history visibility during runtime startup, stop, and failure. Restored -success, failure, and cancellation details must be non-empty. Unknown end times -must have no running timer, and history errors must appear in status. Terminal -context menus delete; active context menus cancel. - -Reordering must accept every insertion gap in a repository section, including -between checkout and worktree rows. Keep each review's cwd and hidden filtered -rows, and restore the same order after reload. Verify production uses its history -path, previews/tests use injected stores, and app termination awaits shutdown. - -### Isolated app E2E - -Rebuild the app and launch it with a dedicated MCP port, diagnostics file, and -temporary database. The composition root owns these explicit inputs: -`REVIEW_MONITOR_TEST_PORT`, `REVIEW_MONITOR_TEST_CODEX_COMMAND`, -`REVIEW_MONITOR_TEST_DIAGNOSTICS_PATH`, and `REVIEW_MONITOR_TEST_HISTORY_PATH`. -Leave `HOME` and production history unchanged. - -Complete a real review through Streamable HTTP, terminate with -`NSRunningApplication.terminate()`, and wait for shutdown. Relaunch the same -binary with the same history path. Check diagnostics and visible UI for one -terminal row with target, model, status, final detail, and findings, without -command or reasoning transcripts. Verify a new MCP session cannot list or read -it. Capture the restored sidebar and detail for the PR. The executable procedure -is in the [E2E README](../scripts/review-history-e2e/README.md). - -```bash -swift test --build-system swiftbuild --no-parallel -xcodebuild test -project Tools/ReviewMonitor/CodexReviewMonitor.xcodeproj \ - -scheme CodexReviewMonitor \ - -destination 'platform=macOS,arch=arm64' \ - CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO -scripts/check-compatibility.sh -git diff --check -``` - -Then run branch-wide local Codex review against `main` until it has no findings. - -## Original delivery record - -| Slice | Planned budget | Recorded completion | -| --- | --- | --- | -| A: schema and adapter | 6 hours; at most 10 production and 4 test files | Dependency, internal target, schema, migrations, codec, retention, close owner, and focused tests complete | -| B: store | 8 hours; at most 12 production and 5 test files | Port and injected disabled/test adapters; load, start/terminal writes, order, delete, shutdown, and Store/MCP tests complete | -| C: app and UI | 5 hours; at most 8 production and 4 test files | Production path/database, history visibility/health/deletion, and UI/app tests complete | -| D: delivery | — | Repository checks, clean local review, commits, and clean worktree complete; push and Ready PR still unchecked | - -Completion measurements were intended to cover the product/target graph, -public/package/open declarations, largest files and store properties, remaining -platform gates, location and close ownership, deleted alternate routes, and -exact validation results. The recorded results were: - -- `swift package dump-package` kept persistence internal, depending on - `CodexReview` and SQLiteData. Host assembled it; UI had no storage dependency. -- Added ApplicationHostSupport SPI covered one-shot `shutdown()`, isolated-store - factories, and history test keys. API baseline and checksum included these - additions; the public live-store factory stayed unchanged. -- History store code had 760 lines; adapter, codec, and schema had 444, 479, and - 290. The store added availability, port, mutation receipts, durable-ID sets, - result leases, and shutdown state, without another UI model or log cache. -- The production location was - `Application Support/CodexReviewMonitor/RecoveryV1/review-history.sqlite`, - retained through Application Support/application/recovery capabilities. - Termination cancelled and waited for launch, store work, history receipts, - database close, and directory close in that order. Runtime restart kept it open. -- The unused helper was removed, with no alternate database route, generic log - table, transcript column, or SQLite import in UI. -- Package tests, the locked app test run (18 tests), compatibility checks, - schema/codec/retention tests, and actual-app semantic/UI E2E passed. E2E used - Codex 0.149.1 and restored the same terminal job and `AccessGate.swift:3-3` - finding after restart. It checked MCP isolation and captured accessibility - text and a screenshot. Local branch review reported zero findings. -- The standard app test command was blocked before compilation by local Xcode - macro trust. CI, release, and E2E used the committed workspace lock, - disabled automatic resolution, and `-skipMacroValidation`; app tests passed - through that path. -- Runtime shutdown closed MCP admission, drained finite JSON-RPC responses - through HTTP response-end acknowledgement, then disconnected sessions and - closed the event-loop group. E2E required curl status 0 and a complete - JSON-RPC/SSE response; restored history could not substitute for that response. diff --git a/README.md b/README.md index 46d49eaa..23395d0e 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,36 @@ # CodexReviewKit -CodexReviewMonitor is a macOS app for running Codex reviews. Start reviews from -Codex or Claude Code through MCP, then read the output and findings in the app. -It requires macOS 26 or newer and the Codex CLI installed on your Mac. +CodexReviewMonitor runs Codex reviews on your Mac. Start a review from Codex or +Claude Code through MCP and read its findings in the app. You'll need macOS 26 +or newer and the Codex CLI. ## Quick start 1. Download the signed and notarized DMG from the [latest release](https://github.com/lynnswap/CodexReviewKit/releases/latest). -2. Open `CodexReviewMonitor_.dmg`, drag `CodexReviewMonitor.app` to - Applications, and launch it. -3. Sign in from the app with **Sign in with ChatGPT**, or choose - **Sign in another way** to use an API key. -4. Register the app's MCP endpoint with your client. + Open the DMG, drag `CodexReviewMonitor.app` to Applications, and launch it. +2. Sign in with ChatGPT, or choose **Sign in another way** to use an API key. + ReviewMonitor uses `~/.codex_review` as its default Codex home. +3. Register ReviewMonitor with your client. - Codex CLI: + **Codex CLI** ```bash codex mcp add codex_review --url http://localhost:9417/mcp ``` - Claude Code: + **Claude Code** ```bash claude mcp add --transport http codex_review http://localhost:9417/mcp ``` -5. Ask your client to review a repository. It uses `review_start` to start a job - and `review_await` if the review needs more time. `review_list`, `review_read`, - and `review_cancel` let you inspect or cancel jobs. - -Keep the app running while you use the tools. It hosts -`http://localhost:9417/mcp` and runs `codex app-server` for the reviews. -ReviewMonitor uses `~/.codex_review` as its Codex home. +4. Keep ReviewMonitor running and ask your client to review a repository. ### Allow time for long reviews -Add these timeout settings to the calling Codex client's configuration after -registering the endpoint. `codex mcp add` does not expose timeout flags. +For long reviews, set the timeouts in the calling Codex client's configuration +after registering the endpoint. ```toml [mcp_servers.codex_review] @@ -46,55 +39,31 @@ startup_timeout_sec = 1200.0 tool_timeout_sec = 1200.0 ``` -This is the client's configuration, separate from ReviewMonitor's -`~/.codex_review` home. See the [MCP reference](Docs/mcp.md) for tool arguments, -results, and session behavior. - ## Update Codex -ReviewMonitor checks for Codex updates at launch and every eight hours. You can -also check in **Settings → Updates → Check for Updates**, which shows the last -check time. A manual check only checks availability; it keeps the automatic -schedule and leaves installation to you. -Settings distinguishes unsupported installations and failed checks from -**Up to Date**. - -Choose **Update** in the sidebar when a new version is available. If reviews are -running, choose **Update After Reviews** to finish them first, or -**Stop Reviews and Update** to cancel them and update now. New review requests -wait in ReviewMonitor's queue and resume after Codex restarts. The app and MCP -sessions stay open, and you do not need to resubmit requests. - -Automatic installation supports the stable Homebrew Codex cask and standalone -installations selected through their stable launcher. Other installations show -manual update guidance when an update is available. Checks and installation use -the selected CLI's installation home, including custom standalone homes; -reviews use `~/.codex_review`. - -If installation fails but Codex restarts, queued reviews resume and Settings -shows the error. If Codex cannot restart, the queue stays available and **Retry** -attempts recovery without reinstalling. Quitting the app cancels queued reviews -and waits for any installation already in progress. +ReviewMonitor checks for updates at launch and every eight hours. To check +manually, open **Settings → Updates → Check for Updates**. + +Choose **Update** in the sidebar. If reviews are running, choose **Update After +Reviews** to finish them first or **Stop Reviews and Update** to cancel them. +New requests stay queued and resume when Codex restarts. If it fails to +restart, choose **Retry** to resume without reinstalling. + +Automatic installation supports the stable Homebrew cask and standalone +installations selected through their stable launcher. For other installations, +follow the manual update instructions in the app. ## Build from source -On an Apple silicon Mac with Xcode 26.4 or newer and Python 3.10 or newer, run -this command from the repository root: +Run this command from the repository root to create a local DMG in `dist/`. +[Build requirements](Docs/releases.md#local-builds) ```bash python3 scripts/build_review_monitor.py ``` -It creates `dist/CodexReviewMonitor_yymmdd_hhmm.dmg` with an ad-hoc signature for -local use. You can keep ReviewMonitor running during the build. Once reviews -finish, quit the app, open the DMG, and drag the new app to Applications. Choose -**Replace**, then launch it. - -See [local build details](Docs/releases.md#local-builds) for signing identities, -build caches, and packaging behavior. - ## Documentation -- [Architecture](Docs/architecture.md): targets, review flow, and runtime updates. -- [MCP reference](Docs/mcp.md): tool arguments, results, and runtime files. -- [Release guide](Docs/releases.md): signing, validation, and publication. +- [Architecture](Docs/architecture.md) +- [MCP reference](Docs/mcp.md) +- [Release and build guide](Docs/releases.md) diff --git a/Sources/CodexReview/Store/CodexReviewStore.swift b/Sources/CodexReview/Store/CodexReviewStore.swift index cdaf3121..9d867824 100644 --- a/Sources/CodexReview/Store/CodexReviewStore.swift +++ b/Sources/CodexReview/Store/CodexReviewStore.swift @@ -242,16 +242,7 @@ public final class CodexReviewStore { } } - /// Optionally warms up continuous observation for the current application process. - /// - /// ReviewUI controllers can be created before this method is called or completes. - /// Synchronous observation startup resolves the runtime on demand and may block - /// the caller. Use this method during asynchronous setup to warm up that work. - /// Concurrent calls share preparation, and successful calls reuse the runtime. - /// ``start(forceRestartIfNeeded:)`` also prepares observation before starting - /// the store's automatic rate limit refresh. - /// - /// - Throws: The error encountered while preparing the Observation runtime. + /// Call during asynchronous setup to avoid blocking on the first synchronous observation. public static func prepareObservationTracking() async throws { try await PortableObservationTracking.prepare() } diff --git a/Sources/ReviewUI/ReviewMonitorWindowController.swift b/Sources/ReviewUI/ReviewMonitorWindowController.swift index 7b3ae189..07cebb41 100644 --- a/Sources/ReviewUI/ReviewMonitorWindowController.swift +++ b/Sources/ReviewUI/ReviewMonitorWindowController.swift @@ -41,9 +41,6 @@ public final class ReviewMonitorWindowController: NSWindowController { } /// Creates a monitor window for the store. - /// - /// Observation tracking starts on demand. You can optionally call - /// `CodexReviewStore.prepareObservationTracking()` during asynchronous setup. public convenience init(store: CodexReviewStore) { self.init( store: store, @@ -53,9 +50,6 @@ public final class ReviewMonitorWindowController: NSWindowController { } /// Creates a monitor window with a settings action. - /// - /// Observation tracking starts on demand. You can optionally call - /// `CodexReviewStore.prepareObservationTracking()` during asynchronous setup. @_spi(PreviewSupport) public convenience init( store: CodexReviewStore, diff --git a/scripts/review-history-e2e/README.md b/scripts/review-history-e2e/README.md index 4de4605a..2e4d2fdd 100644 --- a/scripts/review-history-e2e/README.md +++ b/scripts/review-history-e2e/README.md @@ -1,60 +1,31 @@ # Test review history across an app restart -`run.sh` builds ReviewMonitor, runs a real Codex review, quits that app instance, -and relaunches it with the same SQLite database. It checks that the store restores -the result and that a new MCP session cannot access the restored job. A full -acceptance run also includes the UI inspection below. - -## Before running - -Authenticate `/opt/homebrew/bin/codex` in ReviewMonitor's Codex home, normally -`~/.codex_review`. The script uses that login and creates a temporary Git fixture -with an unsafe uncommitted change to produce a finding. - -The app's composition root must support these isolated test inputs: - -- `REVIEW_MONITOR_TEST_PORT` -- `REVIEW_MONITOR_TEST_CODEX_COMMAND` -- `REVIEW_MONITOR_TEST_DIAGNOSTICS_PATH` -- `REVIEW_MONITOR_TEST_HISTORY_PATH` - -The script fails if those inputs are unavailable. It uses a dedicated -DerivedData directory, port, and history path. It leaves `HOME`, port `9417`, -and the production history database unchanged. - -## Run the automated checks - -From the repository root: +Authenticate `/opt/homebrew/bin/codex` in ReviewMonitor's Codex home (normally +`~/.codex_review`), then run this command from the repository root. ```bash scripts/review-history-e2e/run.sh ``` -Each run keeps an artifact directory with build and app logs, MCP requests and -responses, store diagnostics, SQLite schema and rows, and `e2e-summary.json`. - -On failure, the script prints that directory and terminates the exact app PID -it started. It first requests a graceful quit. If the process stays alive, it -checks the executable path again before sending a signal. +The script builds ReviewMonitor, runs a review in a temporary repository, and +relaunches the app with the same test database. It checks that the result is +restored and that a new MCP session cannot access it. The artifact directory +contains the logs, database output, and `e2e-summary.json`. ## Inspect the restored UI -Run with the second app instance left open: +To check the sidebar and detail view as part of the run, keep the restored app +open. ```bash scripts/review-history-e2e/run.sh --keep-restored-app-running ``` -The output and `e2e-summary.json` identify the app PID, rebuilt binary, -diagnostics, database, fixture, and job. Use that process's accessibility tree to -select the restored row. Check its target, terminal state, duration, final -review, and `AccessGate.swift` finding in the sidebar and detail view. - -Save `ui-restored.png` in the artifact directory and record the inspected -accessibility state beside it. Set `uiEvidenceStatus` from `pending` only after -both the screenshot and accessibility checks pass; store diagnostics alone do -not verify rendering. - -Finish with the exact termination command printed by the script. The script -waits for that app process to exit, keeping it in the isolated environment -throughout the inspection. +1. Use the printed PID to select the restored row through the app's accessibility + tree. Check the target, terminal state, duration, final review, and + `AccessGate.swift` finding. +2. Save `ui-restored.png` and the accessibility output in the artifact directory. + In `e2e-summary.json`, set `uiScreenshot` and `uiAccessibility` to their + absolute paths and `uiEvidenceStatus` to `verified`. +3. Run the printed termination command. The script waits for that app to exit + and checks both evidence files.