@orion-agents/orion-code 0.3.28 → 0.3.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -22,9 +22,91 @@ which is **not** a pass.
22
22
 
23
23
  ## [Unreleased]
24
24
 
25
- ## [0.3.28] — UNRELEASED
25
+ ## [0.3.30] — UNRELEASED
26
+
27
+ > **Status: candidate.** Open. Qualification & documentation slice (PR4
28
+ > automatable portion of the v0.3.27 review loop, plan:
29
+ > `docs/plan/v0.3.30-plan.md`): the public README (English and 简体中文) no
30
+ > longer claims that Files/Git/Review are read-only or that the project
31
+ > navigator creates no other runtimes — Files offers CAS-guarded text editing
32
+ > (512 KiB cap), Git offers staging, hunk/line feedback, local commits and
33
+ > history reading, Review starts the shared bounded review runner, and the
34
+ > Host runs a bounded Session actor pool (3 running / 4 resident by default);
35
+ > remote or destructive Git operations remain unexposed by design. A new
36
+ > `docs/architecture/code-review-loop.md` documents the shared loop end to
37
+ > end (selectors, tighten-only budgets, receipt digests, staleness, state
38
+ > banners, Web single-flight, host-restart history boundary). The v0.3.29
39
+ > entry is corrected to `published` (tag `v0.3.29`, npm `latest`). The
40
+ > human-labeled paid quality benchmark and real Host + Chrome full-chain E2E
41
+ > remain honestly `not_run` (no model credentials in the automation
42
+ > environment). Not merged, tagged or published.
26
43
 
27
- > **Status: candidate.** Open. The typed `/review` runtime & CLI slice
44
+ ### Changed
45
+
46
+ - README.md / README.zh-CN.md: aligned the Web workbench capability summary
47
+ with the current implementation (Files CAS editing, Git staging/commit/
48
+ history, Review shared runner, bounded Session actor pool) and kept the
49
+ explicit "remote/destructive Git operations not exposed" boundary.
50
+ - docs: added `docs/architecture/code-review-loop.md` (shared review loop
51
+ usage & semantics) and indexed it in `docs/readme.md`.
52
+ - CHANGELOG: corrected the 0.3.29 delivery status from `candidate` to
53
+ `published` (tagged `v0.3.29`, npm registry `latest`).
54
+
55
+ ## [0.3.29] — 2026-10-22
56
+
57
+ > **Status: published.** Released as `@orion-agents/orion-code@0.3.29` from
58
+ > tag `v0.3.29` (merge commit `86c20aa`, PR #285, 2026-10-22); npm registry
59
+ > `latest` confirmed 0.3.29 via direct registry query. The Web shared review
60
+ > loop (plan: `docs/plan/v0.3.29-plan.md`, PR3 core of the v0.3.27 review loop):
61
+ > the Host now starts the same bounded single-pass review runner the CLI uses
62
+ > (`runCodeReview`, v0.3.28) against the active Workspace. `POST /review/run`
63
+ > performs fast admission (one in-flight run per Host, typed
64
+ > `review_run_in_progress` 409 and `review_no_model` 422) and the model
65
+ > completion continues in the background; `GET /review/runs` and
66
+ > `GET /review/runs/:runId` read a bounded in-memory history where every
67
+ > receipt passes digest re-verification and is flagged `stale` when the
68
+ > repository revision changed after admission. The Review panel lists the runs
69
+ > with honest state banners (running / cancelled / failed / partial / stale
70
+ > never render as a green pass), groups findings P0→P3 with file:line anchors
71
+ > into the existing diff view, counts contract-invalid model output instead of
72
+ > hiding it, and can send each finding back to the Composer as a typed draft
73
+ > the user still confirms. The fileKey→path mapping is captured through an
74
+ > additive `onSnapshotCaptured` runner hook; the frozen receipt contract is
75
+ > unchanged.
76
+
77
+ ### Added
78
+
79
+ - `src/web/code-review-run-service.ts` — the Host-side review run service:
80
+ single-flight admission, background execution of the shared runner, bounded
81
+ receipt history (20 runs, oldest finished evicted first), digest
82
+ re-verification on read, repository-revision staleness flags, cancellation,
83
+ and the `parseWebReviewSelectorV1` request validation.
84
+ - `src/web/workbench-controller.ts` — `reviewRunStart` / `reviewRunList` /
85
+ `reviewRunGet` / `reviewRunCancel`, with the review model adapter derived
86
+ from the control-plane Runtime's `llm` (typed 422 when the Host has no
87
+ configured model).
88
+ - `src/web/server.ts` — `POST /review/run` and
89
+ `POST /review/runs/:runId/cancel` behind `assertMutation` +
90
+ `executeMutation`, plus read-only `GET /review/runs[/:runId]` with context
91
+ guards.
92
+ - `web/src/components/review/ReviewRunsSection.tsx` and
93
+ `review-runs-view.ts` — the Review panel results section: run button,
94
+ polling while a run is in flight, priority-grouped findings, honest banners,
95
+ diff anchoring and typed Composer drafts.
96
+ - Tests: `tests/web-code-review-run-service.test.ts` (10 unit tests),
97
+ `tests/web-review-run-endpoint.test.ts` (4 real-host tests on a temp Git
98
+ repository, including the 403 nonce guard and the 422 no-model path),
99
+ `tests/web-review-runs-view.test.tsx` (13 pure + SSR view tests).
100
+
101
+ ### Not run
102
+
103
+ - Real Host + Chrome full-chain E2E and the human-labeled quality benchmark
104
+ (PR4) — the local automation sandbox has no model credentials; recorded
105
+ honestly as `not_run`, not silently skipped.
106
+
107
+ ## [0.3.28] — 2026-10-22
108
+
109
+ > **Status: published.** The typed `/review` runtime & CLI slice
28
110
  > (plan: `docs/plan/v0.3.28-plan.md`, PR2 core of the v0.3.27 review loop):
29
111
  > `/review` arguments now parse into the frozen `ReviewSelectorV1` (worktree /
30
112
  > `--base` / repeatable `--path`, back-compat single-path filter) and unknown
@@ -38,7 +120,8 @@ which is **not** a pass.
38
120
  > reports "no changes under review" without calling the model, and partial,
39
121
  > failed, cancelled or inconclusive runs never render as a green pass.
40
122
  > Web wiring (PR3) and the qualification benchmark (PR4) remain subsequent
41
- > slices. Not merged, tagged or published.
123
+ > slices. Merged as #284, tagged `v0.3.28` on main (`8a4722b`), published to
124
+ > npm (registry `latest` = 0.3.28).
42
125
 
43
126
  ### Added
44
127
 
@@ -161,7 +244,7 @@ which is **not** a pass.
161
244
  ### Fixed
162
245
 
163
246
  - #269: `GET /git/conflict` no longer fails with `git cat-file: could not get object
164
- info` after editing a conflicted file before staging — the `worktree` version is read
247
+ info` after editing a conflicted file before staging — the `worktree` version is read
165
248
  from the filesystem (contained within the repository root) instead of an object
166
249
  `hash-object` never wrote.
167
250
  - #270: `GET /git/file-history` with a `rev` now walks that revision; previously the
package/README.md CHANGED
@@ -2,15 +2,13 @@
2
2
 
3
3
  Local-first, goal-driven coding agent for the terminal and browser.
4
4
 
5
- > v0.3.28 candidate — open. The typed `/review` workflow: slash arguments are
6
- > parsed into the frozen review selector (worktree / `--base` / `--path`, with
7
- > usage errors instead of silent chat fallback), the review runs against the
8
- > admission-time frozen Git snapshot through a bounded single-pass model call,
9
- > model findings are validated against the contract and the snapshot manifest,
10
- > and the run renders a digest-verifiable receipt with honest state banners
11
- > (empty scope ≠ review pass; partial / failed / cancelled never green). The
12
- > previous release 0.3.27 is on npm (registry `latest`), tagged `v0.3.27`
13
- > (`0be5b18`, #283) and released on GitHub.
5
+ > v0.3.30 candidate — open. Qualification & documentation slice of the review
6
+ > loop: the README capability summary now matches the implementation (Files
7
+ > CAS-guarded editing, Git staging and local commits, Review shared runner,
8
+ > bounded Session actor pool), and `docs/architecture/code-review-loop.md`
9
+ > documents the shared review loop end to end. The previous release 0.3.29 is
10
+ > on npm (registry `latest`), tagged `v0.3.29` (`86c20aa`, #285) and released
11
+ > on GitHub.
14
12
 
15
13
  [中文说明](README.zh-CN.md) ·
16
14
  [v0.3.24 plan](docs/plan/v0.3.24-plan.md) ·
@@ -173,10 +171,10 @@ user extension boundaries.
173
171
  Node.js 22.12+, 24, and 26 are supported. Use Node 24 LTS for production or Node 26 Current for
174
172
  current development environments. Node 20 is upstream EOL and is no longer a v0.3 runtime.
175
173
 
176
- To install the pinned v0.3.28 package when it is available on npm:
174
+ To install the pinned v0.3.30 package when it is available on npm:
177
175
 
178
176
  ```bash
179
- npm install -g @orion-agents/orion-code@0.3.28
177
+ npm install -g @orion-agents/orion-code@0.3.30
180
178
  orion --version
181
179
  orion doctor
182
180
  ```
@@ -258,11 +256,16 @@ state. Approve starts a separate BUILD logical request, Continue Planning starts
258
256
  request with feedback, and Cancel performs no execution. Each operation binds the exact plan digest
259
257
  and survives refresh or Host restart; stale review actions fail with no side effects.
260
258
 
261
- The project navigator does not create multiple runtimes. Cross-project Session selection is one
262
- atomic, revision-guarded Context transition. The left dock is 240–480px or a 48px rail; the right is
263
- 320–720px. Both use IDE-style mouse drag where applicable and there is no keyboard fine resize.
264
- Narrow layouts use drawers without overwriting desktop widths. Files, Git and Review are read-only;
265
- terminal creation requires an explicit gesture and its ticket/output never enter Workbench SSE.
259
+ The Host runs a bounded pool of Session actors (3 running / 4 resident by default) instead of one
260
+ global runtime; the project navigator never applies one Session's writes to another. Cross-project
261
+ Session selection is one atomic, revision-guarded Context transition. The left dock is 240–480px or
262
+ a 48px rail; the right is 320–720px. Both use IDE-style mouse drag where applicable and there is no
263
+ keyboard fine resize. Narrow layouts use drawers without overwriting desktop widths. Files offers
264
+ CAS-guarded text editing (512 KiB cap); Git offers staging, hunk/line feedback, local commits and
265
+ history reading; Review can start the shared bounded review runner and shows digest-verifiable
266
+ findings. Remote or destructive Git operations (push, reset, discard, amend, force push) are not
267
+ exposed and remain separate capability designs; terminal creation requires an explicit gesture and
268
+ its ticket/output never enter Workbench SSE.
266
269
 
267
270
  #### Background host & lifecycle (v0.3.10)
268
271
 
package/README.zh-CN.md CHANGED
@@ -2,12 +2,11 @@
2
2
 
3
3
  面向终端与浏览器、本地优先的目标驱动 Coding Agent。
4
4
 
5
- > v0.3.28 候选版本:进行中。类型化 `/review` 审查工作流:slash 参数解析为冻结的审查
6
- > selector(worktree / `--base` / `--path`,未知参数返回用法而非静默转入普通聊天);审查
7
- > 基于 admission 时冻结的 Git snapshot,经有界单轮模型补全执行;模型 finding 按契约与
8
- > snapshot manifest 校验;输出 digest 可验证的 receipt 与如实状态横幅(空范围 ≠ 审查通过;
9
- > partial / failed / cancelled 永远不会显示为绿色)。上一版 0.3.27 已发布 npm
10
- > (registry `latest`)、打 tag `v0.3.27`(`0be5b18`,#283)并发布 GitHub Release。
5
+ > v0.3.30 候选版本:进行中。审查回路的资格验证与文档切片:README 能力概述与当前实现
6
+ > 对齐(文件 CAS 冲突检测编辑、Git 暂存与本地提交、审阅共享运行器、有界 Session
7
+ > actor 池),并新增 `docs/architecture/code-review-loop.md` 端到端说明共享审查回路。
8
+ > 上一版 0.3.29 已发布 npm(registry `latest`)、打 tag `v0.3.29`(`86c20aa`,#285)
9
+ > 并发布 GitHub Release。
11
10
 
12
11
  [English](README.md) ·
13
12
  [v0.3.24 方案](docs/plan/v0.3.24-plan.md) ·
@@ -102,10 +101,10 @@ MCP 仍是用户可见的扩展边界。
102
101
  支持 Node.js 22.12+、24 和 26。生产环境建议使用 Node 24 LTS,当前开发环境也支持 Node 26
103
102
  Current。Node 20 已结束上游维护,不再属于 v0.3 Runtime 合同。
104
103
 
105
- v0.3.28 在 npm 可用后,可安装固定版本:
104
+ v0.3.30 在 npm 可用后,可安装固定版本:
106
105
 
107
106
  ```bash
108
- npm install -g @orion-agents/orion-code@0.3.28
107
+ npm install -g @orion-agents/orion-code@0.3.30
109
108
  orion --version
110
109
  orion doctor
111
110
  ```
@@ -184,10 +183,14 @@ Host 时会 abort 并 fail-closed。
184
183
  携带反馈创建独立 PLAN request;取消不产生执行副作用。三种操作均绑定 exact digest,刷新或 Host restart
185
184
  后可恢复,stale review fail-closed。
186
185
 
187
- 多项目导航不会创建多个 Runtime;跨项目 Session 选择是一次带 revision guard 的原子 Context 切换。
188
- 桌面左栏可在 240–480px 调整或折叠为 48px rail,右栏为 320–720px;均采用 IDE 式鼠标拖动且不提供
189
- 键盘精细调宽。窄屏自动使用 drawer,且不覆盖桌面宽度偏好。文件、Git 和审阅保持只读;创建终端需要
190
- 显式 user gesture,短期 ticket 与输出均不进入 Workbench SSE。
186
+ Host 以有界 Session actor 池承载并发(默认 3 个运行 / 4 个常驻),而不是单一全局 Runtime;项目导航
187
+ 不会把一个 Session 的写入应用到另一个 Session。跨项目 Session 选择是一次带 revision guard 的原子
188
+ Context 切换。桌面左栏可在 240–480px 调整或折叠为 48px rail,右栏为 320–720px;均采用 IDE 式鼠标
189
+ 拖动且不提供键盘精细调宽。窄屏自动使用 drawer,且不覆盖桌面宽度偏好。文件区提供带 CAS 冲突检测的
190
+ 文本编辑(上限 512 KiB);Git 区提供暂存、hunk/行反馈、本地提交与历史读取;审阅区可发起共享的有界
191
+ 审查运行并查看 digest 可验证的 findings。push、reset、discard、amend、force push 等远端与破坏性
192
+ Git 操作仍未开放,作为独立能力另行设计;创建终端需要显式 user gesture,短期 ticket 与输出均不进入
193
+ Workbench SSE。
191
194
 
192
195
  #### 后台运行与管理(v0.3.10)
193
196
 
@@ -12,5 +12,5 @@ declare function continueAsSlashChat(name: string, args: string): CommandResult;
12
12
  * Git snapshot, and the receipt is rendered by the shared formatter.
13
13
  */
14
14
  declare function handleReview(ctx: CommandContext, args: string): Promise<CommandResult>;
15
- export { handlePlan, handleDiff, handleCommitPlan, continueAsSlashChat, handleReview, };
15
+ export { handlePlan, handleDiff, handleCommitPlan, continueAsSlashChat, handleReview };
16
16
  //# sourceMappingURL=workflow-command-handlers.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_REVIEW_BUDGETS, type CodeReviewResultV1, type ReviewBudgetsV1, type ReviewSelectorV1 } from './contract';
2
- import { type ReviewGitRunner } from './snapshot';
2
+ import { type CodeReviewSnapshotV1, type ReviewGitRunner } from './snapshot';
3
3
  /** One bounded model completion. CLI wiring adapts `LLMService.chat`. */
4
4
  export interface ReviewModelAdapterV1 {
5
5
  complete(messages: readonly {
@@ -29,6 +29,11 @@ export interface ReviewRunOptionsV1 {
29
29
  readonly abortSignal?: AbortSignal;
30
30
  readonly runGit?: ReviewGitRunner;
31
31
  readonly now?: () => number;
32
+ /** v0.3.29 — additive observation hook fired inside the admission window
33
+ * right after the frozen snapshot is captured. Lets a host keep the
34
+ * fileKey -> path mapping for diff anchoring without changing the frozen
35
+ * receipt contract. */
36
+ readonly onSnapshotCaptured?: (snapshot: CodeReviewSnapshotV1) => void;
32
37
  }
33
38
  export type ReviewRunFailureV1 = {
34
39
  readonly kind: 'budget';
@@ -94,7 +94,9 @@ function buildReviewSystemPrompt(rulesDigest) {
94
94
  function buildSnapshotMaterial(snapshot, diffText, budgets) {
95
95
  const sections = [
96
96
  `Snapshot: ${snapshot.snapshotId} (kind=${snapshot.kind}`,
97
- snapshot.kind === 'base' ? `base=${snapshot.baseOid} head=${snapshot.headOid})` : 'worktree scope)',
97
+ snapshot.kind === 'base'
98
+ ? `base=${snapshot.baseOid} head=${snapshot.headOid})`
99
+ : 'worktree scope)',
98
100
  `Input snapshot digest: ${snapshot.inputSnapshotDigest}`,
99
101
  'Changed files (fileKey -> path):',
100
102
  ...snapshot.files.map(file => {
@@ -145,8 +147,12 @@ function snapshotAuthorizesFile(snapshot, finding) {
145
147
  return false;
146
148
  }
147
149
  const relevant = file.hunks.filter(hunk => finding.side === 'old'
148
- ? hunk.oldLines > 0 && finding.startLine <= hunk.oldStart + hunk.oldLines - 1 && finding.endLine >= hunk.oldStart
149
- : hunk.newLines > 0 && finding.startLine <= hunk.newStart + hunk.newLines - 1 && finding.endLine >= hunk.newStart);
150
+ ? hunk.oldLines > 0 &&
151
+ finding.startLine <= hunk.oldStart + hunk.oldLines - 1 &&
152
+ finding.endLine >= hunk.oldStart
153
+ : hunk.newLines > 0 &&
154
+ finding.startLine <= hunk.newStart + hunk.newLines - 1 &&
155
+ finding.endLine >= hunk.newStart);
150
156
  // A finding whose lines touch no diff hunk is not anchored in the frozen
151
157
  // material; the model must cite the changes under review.
152
158
  return relevant.length > 0;
@@ -175,6 +181,7 @@ async function runCodeReview(options) {
175
181
  runGit,
176
182
  readWorktreeFile: (0, snapshot_1.createContainedWorktreeReader)(options.cwd),
177
183
  });
184
+ options.onSnapshotCaptured?.(snapshot);
178
185
  if (aborted())
179
186
  return { ok: false, failure: { kind: 'cancelled' } };
180
187
  // The exact same frozen diff arguments the snapshot used, against the
@@ -189,7 +196,11 @@ async function runCodeReview(options) {
189
196
  const code = error instanceof snapshot_1.ReviewSnapshotError ? error.code : 'not_a_repository';
190
197
  return {
191
198
  ok: false,
192
- failure: { kind: 'snapshot', code, message: error instanceof Error ? error.message : String(error) },
199
+ failure: {
200
+ kind: 'snapshot',
201
+ code,
202
+ message: error instanceof Error ? error.message : String(error),
203
+ },
193
204
  };
194
205
  }
195
206
  const rulesDigest = await computeReviewRulesDigest(options.cwd);
@@ -233,7 +244,10 @@ async function runCodeReview(options) {
233
244
  startedAt,
234
245
  endedAt,
235
246
  };
236
- return { ok: true, result: Object.freeze({ ...base, receiptDigest: (0, contract_1.computeReceiptDigest)(base) }) };
247
+ return {
248
+ ok: true,
249
+ result: Object.freeze({ ...base, receiptDigest: (0, contract_1.computeReceiptDigest)(base) }),
250
+ };
237
251
  }
238
252
  const material = buildSnapshotMaterial(snapshot, diffText, budgets.budgets);
239
253
  if (material.truncated) {
@@ -28,7 +28,10 @@ function looksLikeRelativePath(value) {
28
28
  * path (back-compat path filter). Anything else is a usage error.
29
29
  */
30
30
  function parseReviewSelector(rawArgs) {
31
- const tokens = rawArgs.trim().split(/\s+/).filter(token => token.length > 0);
31
+ const tokens = rawArgs
32
+ .trim()
33
+ .split(/\s+/)
34
+ .filter(token => token.length > 0);
32
35
  let base = null;
33
36
  const paths = [];
34
37
  for (let index = 0; index < tokens.length; index += 1) {
@@ -0,0 +1,68 @@
1
+ import { type CodeReviewResultV1, type ReviewRunStateV1, type ReviewSelectorV1 } from '../services/code-review/contract';
2
+ import { runCodeReview, type ReviewModelAdapterV1 } from '../services/code-review/runner';
3
+ export interface WebCodeReviewRunRecordV1 {
4
+ readonly runId: string;
5
+ readonly selector: ReviewSelectorV1;
6
+ readonly status: ReviewRunStateV1 | 'running';
7
+ readonly startedAt: number;
8
+ readonly endedAt: number | null;
9
+ /** Repository revision captured at admission; compared against the current
10
+ * value on read to mark a stored receipt stale. */
11
+ readonly repositoryRevisionAtAdmission: string;
12
+ /** fileKey -> path mapping captured with the frozen snapshot, so findings
13
+ * can be anchored to a diff without changing the receipt contract. */
14
+ readonly files: ReadonlyArray<{
15
+ readonly fileKey: string;
16
+ readonly path: string;
17
+ }>;
18
+ /** Present only for finished runs whose receipt passed digest re-verification. */
19
+ readonly result: CodeReviewResultV1 | null;
20
+ readonly failure: {
21
+ readonly kind: string;
22
+ readonly message: string;
23
+ } | null;
24
+ /** Recomputed on read: true when the repository changed since admission. */
25
+ readonly stale: boolean;
26
+ }
27
+ export interface WebCodeReviewRunServiceOptionsV1 {
28
+ /** Returns the review model adapter, or null when the Host has no model. */
29
+ readonly adapterProvider: () => ReviewModelAdapterV1 | null;
30
+ /** Workspace root used for the review snapshot; read at start time. */
31
+ readonly cwdProvider: () => string;
32
+ /** Current repository revision, sampled on every read for staleness. */
33
+ readonly repositoryRevisionProvider: () => Promise<string>;
34
+ /** Injectable runner (tests use fakes); defaults to the shared runner. */
35
+ readonly runReview?: typeof runCodeReview;
36
+ readonly now?: () => number;
37
+ /** Bounded receipt history; oldest finished records are evicted first. */
38
+ readonly maxRuns?: number;
39
+ }
40
+ export declare class WebCodeReviewRunServiceV1 {
41
+ private readonly records;
42
+ private readonly inflight;
43
+ private readonly adapterProvider;
44
+ private readonly cwdProvider;
45
+ private readonly repositoryRevisionProvider;
46
+ private readonly runReview;
47
+ private readonly now;
48
+ private readonly maxRuns;
49
+ constructor(options: WebCodeReviewRunServiceOptionsV1);
50
+ /** Admission is synchronous and fast: validate, record, return. The model
51
+ * completion continues in the background. */
52
+ start(selector: ReviewSelectorV1): Promise<{
53
+ readonly runId: string;
54
+ readonly status: 'running';
55
+ }>;
56
+ /** Cancels a running review; finished or unknown runs are a no-op. */
57
+ cancel(runId: string): void;
58
+ list(): Promise<readonly WebCodeReviewRunRecordV1[]>;
59
+ get(runId: string): Promise<WebCodeReviewRunRecordV1>;
60
+ private execute;
61
+ private evictFinished;
62
+ private present;
63
+ }
64
+ /** v0.3.29 — validates the JSON selector accepted by `POST /review/run`.
65
+ * Mirrors the CLI selector contract: worktree scope, base ref scope, optional
66
+ * path filters. Unknown shapes are typed 400s, never guesses. */
67
+ export declare function parseWebReviewSelectorV1(value: unknown): ReviewSelectorV1;
68
+ //# sourceMappingURL=code-review-run-service.d.ts.map
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebCodeReviewRunServiceV1 = void 0;
4
+ exports.parseWebReviewSelectorV1 = parseWebReviewSelectorV1;
5
+ /**
6
+ * v0.3.29 — Host-side shared code-review run service
7
+ * (docs/plan/v0.3.29-plan.md S1). The Web Host starts the same bounded
8
+ * single-pass review runner the CLI uses (v0.3.28 `runCodeReview`) against the
9
+ * active Workspace, keeps a bounded in-memory receipt history, and re-verifies
10
+ * every receipt digest plus repository revision freshness when results are
11
+ * read. No second review engine: receipts, budgets, validation and honest
12
+ * failure states come from the frozen `src/services/code-review` contract.
13
+ *
14
+ * Delivery model: `start()` validates admission and returns immediately; the
15
+ * model completion runs in the background and clients poll `list()`/`get()`.
16
+ * At most one run is in flight per Host (a second start is a typed 409), and
17
+ * a run may be cancelled to release the slot.
18
+ */
19
+ const crypto_1 = require("crypto");
20
+ const contract_1 = require("../services/code-review/contract");
21
+ const runner_1 = require("../services/code-review/runner");
22
+ const errors_1 = require("./errors");
23
+ class WebCodeReviewRunServiceV1 {
24
+ constructor(options) {
25
+ this.records = new Map();
26
+ this.inflight = new Map();
27
+ this.adapterProvider = options.adapterProvider;
28
+ this.cwdProvider = options.cwdProvider;
29
+ this.repositoryRevisionProvider = options.repositoryRevisionProvider;
30
+ this.runReview = options.runReview ?? runner_1.runCodeReview;
31
+ this.now = options.now ?? Date.now;
32
+ this.maxRuns = Math.max(1, options.maxRuns ?? 20);
33
+ }
34
+ /** Admission is synchronous and fast: validate, record, return. The model
35
+ * completion continues in the background. */
36
+ async start(selector) {
37
+ if (this.inflight.size > 0) {
38
+ throw new errors_1.WebWorkbenchError(409, 'A code review is already running in this Host. Wait for it to finish or cancel it.', 'review_run_in_progress');
39
+ }
40
+ const adapter = this.adapterProvider();
41
+ if (!adapter) {
42
+ throw new errors_1.WebWorkbenchError(422, 'The Host has no configured model. Configure a model first, then retry the review.', 'review_no_model');
43
+ }
44
+ const runId = (0, crypto_1.randomUUID)();
45
+ const repositoryRevisionAtAdmission = await this.repositoryRevisionProvider();
46
+ const startedAt = this.now();
47
+ let capturedFiles = [];
48
+ this.records.set(runId, {
49
+ runId,
50
+ selector,
51
+ status: 'running',
52
+ startedAt,
53
+ endedAt: null,
54
+ repositoryRevisionAtAdmission,
55
+ files: capturedFiles,
56
+ result: null,
57
+ failure: null,
58
+ stale: false,
59
+ });
60
+ const abort = new AbortController();
61
+ this.inflight.set(runId, abort);
62
+ const cwd = this.cwdProvider();
63
+ void this.execute({
64
+ runId,
65
+ selector,
66
+ cwd,
67
+ adapter,
68
+ abort,
69
+ onSnapshot: snapshot => {
70
+ capturedFiles = Object.freeze(snapshot.files.map(file => ({ fileKey: file.fileKey, path: file.path })));
71
+ const record = this.records.get(runId);
72
+ if (record)
73
+ this.records.set(runId, { ...record, files: capturedFiles });
74
+ },
75
+ });
76
+ return Object.freeze({ runId, status: 'running' });
77
+ }
78
+ /** Cancels a running review; finished or unknown runs are a no-op. */
79
+ cancel(runId) {
80
+ this.inflight.get(runId)?.abort();
81
+ }
82
+ async list() {
83
+ const currentRevision = await this.repositoryRevisionProvider();
84
+ return [...this.records.values()]
85
+ .sort((left, right) => right.startedAt - left.startedAt)
86
+ .map(record => this.present(record, currentRevision));
87
+ }
88
+ async get(runId) {
89
+ const record = this.records.get(runId);
90
+ if (!record) {
91
+ throw new errors_1.WebWorkbenchError(404, 'Unknown review run.', 'review_run_not_found');
92
+ }
93
+ const currentRevision = await this.repositoryRevisionProvider();
94
+ return this.present(record, currentRevision);
95
+ }
96
+ async execute(input) {
97
+ const { runId, selector, cwd, adapter, abort, onSnapshot } = input;
98
+ const options = {
99
+ cwd,
100
+ selector,
101
+ adapter,
102
+ identity: {
103
+ workspaceIdentity: cwd,
104
+ // Web control-plane runs are their own session identity; they are not
105
+ // attributed to any chat Session actor.
106
+ sessionId: `web-host:${runId}`,
107
+ threadId: `web-host:${runId}`,
108
+ turnId: runId,
109
+ },
110
+ abortSignal: abort.signal,
111
+ ...(onSnapshot ? { onSnapshotCaptured: onSnapshot } : {}),
112
+ };
113
+ let failure = null;
114
+ let result = null;
115
+ try {
116
+ const outcome = await this.runReview(options);
117
+ if (outcome.ok) {
118
+ result = outcome.result;
119
+ }
120
+ else {
121
+ failure = {
122
+ kind: outcome.failure.kind,
123
+ message: failureMessage(outcome.failure),
124
+ };
125
+ }
126
+ }
127
+ catch (error) {
128
+ failure = {
129
+ kind: 'model_error',
130
+ message: error instanceof Error ? error.message : String(error),
131
+ };
132
+ }
133
+ this.inflight.delete(runId);
134
+ const existing = this.records.get(runId);
135
+ if (!existing)
136
+ return;
137
+ const finished = {
138
+ ...existing,
139
+ status: result ? result.state : failure?.kind === 'cancelled' ? 'cancelled' : 'failed',
140
+ endedAt: this.now(),
141
+ result,
142
+ failure,
143
+ };
144
+ this.records.set(runId, finished);
145
+ this.evictFinished();
146
+ }
147
+ evictFinished() {
148
+ const finished = [...this.records.values()]
149
+ .filter(record => record.status !== 'running')
150
+ .sort((left, right) => (left.endedAt ?? left.startedAt) - (right.endedAt ?? right.startedAt));
151
+ let excess = this.records.size - this.maxRuns;
152
+ for (const record of finished) {
153
+ if (excess <= 0)
154
+ break;
155
+ this.records.delete(record.runId);
156
+ excess -= 1;
157
+ }
158
+ }
159
+ present(record, currentRevision) {
160
+ const stale = record.result !== null && record.repositoryRevisionAtAdmission !== currentRevision;
161
+ if (record.result && !(0, contract_1.verifyReceiptDigest)(record.result)) {
162
+ // A receipt that no longer verifies must never be presented as findings;
163
+ // surface it as a failed run with an honest message instead.
164
+ return {
165
+ ...record,
166
+ status: 'failed',
167
+ stale,
168
+ result: null,
169
+ failure: {
170
+ kind: 'receipt_digest_mismatch',
171
+ message: 'The stored review receipt failed digest re-verification.',
172
+ },
173
+ };
174
+ }
175
+ return { ...record, stale };
176
+ }
177
+ }
178
+ exports.WebCodeReviewRunServiceV1 = WebCodeReviewRunServiceV1;
179
+ function failureMessage(failure) {
180
+ switch (failure.kind) {
181
+ case 'cancelled':
182
+ return 'Review cancelled.';
183
+ case 'budget':
184
+ return `Review budget rejected: ${failure.field ?? 'unknown'}`;
185
+ case 'snapshot':
186
+ return `Review scope error (${failure.code ?? 'unknown'}): ${failure.message ?? ''}`;
187
+ case 'model_error':
188
+ return `Review model call failed: ${failure.message ?? ''}`;
189
+ case 'unparsable_output':
190
+ return `Review output could not be parsed: ${failure.message ?? ''}`;
191
+ default:
192
+ return failure.message ?? 'Review failed.';
193
+ }
194
+ }
195
+ /** v0.3.29 — validates the JSON selector accepted by `POST /review/run`.
196
+ * Mirrors the CLI selector contract: worktree scope, base ref scope, optional
197
+ * path filters. Unknown shapes are typed 400s, never guesses. */
198
+ function parseWebReviewSelectorV1(value) {
199
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
200
+ throw new errors_1.WebWorkbenchError(400, 'Review selector must be an object.', 'review_selector_invalid');
201
+ }
202
+ const record = value;
203
+ const keys = Object.keys(record).sort();
204
+ const allowed = record.kind === 'base' ? ['kind', 'paths', 'ref'] : ['kind', 'paths'];
205
+ if (keys.some(key => !allowed.includes(key))) {
206
+ throw new errors_1.WebWorkbenchError(400, `Review selector accepts only ${allowed.join(', ')}.`, 'review_selector_invalid');
207
+ }
208
+ const paths = parseSelectorPaths(record.paths);
209
+ if (record.kind === 'base') {
210
+ if (typeof record.ref !== 'string' || record.ref.trim() === '') {
211
+ throw new errors_1.WebWorkbenchError(400, 'Review selector base ref must be a non-empty string.', 'review_selector_invalid');
212
+ }
213
+ return Object.freeze({ kind: 'base', ref: record.ref, ...(paths ? { paths } : {}) });
214
+ }
215
+ if (record.kind === 'worktree') {
216
+ return Object.freeze({ kind: 'worktree', ...(paths ? { paths } : {}) });
217
+ }
218
+ throw new errors_1.WebWorkbenchError(400, 'Review selector kind must be "worktree" or "base".', 'review_selector_invalid');
219
+ }
220
+ function parseSelectorPaths(value) {
221
+ if (value === undefined)
222
+ return undefined;
223
+ if (!Array.isArray(value) || value.some(path => typeof path !== 'string' || path.trim() === '')) {
224
+ throw new errors_1.WebWorkbenchError(400, 'Review selector paths must be an array of non-empty strings.', 'review_selector_invalid');
225
+ }
226
+ return Object.freeze([...value]);
227
+ }
228
+ //# sourceMappingURL=code-review-run-service.js.map