@jayyuen66/dsh-ocr-review 0.1.6 → 0.1.8

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/README.md CHANGED
@@ -1,200 +1,240 @@
1
- # @jayyuen66/dsh-ocr-review
2
-
3
- English · [中文](README.zh-CN.md)
4
-
5
- ## What it does
6
-
7
- - Wraps the external `ocr` (open-code-review) CLI into 5 model tools plus 1 web settings card for dsh; the host validates tool arguments not at all, so every shape and type gate lives in this package.
8
- - The host half (`host.ts`) declares 6 `.volatile()` settings fields — the namespace is implicit: the host projects the form from the profile entry id `ocr-review` and the plugin calls no `settings.register`.
9
- - It also registers 5 tools, one systemPrompt routing section (`ocr-review-routing`, order 1555) and 5 methods on the official Typert Remote namespace `ocrReview`.
10
- - The client half (`src/client-entry.ts` → `client.js`) is the settings card, taking provider/model from the `llm-pi-ai` namespace of the settings service, plus three read-only contributions about the external CLI: a badge and a section on the plugin's detail page and the guidance shown right after the bundle is enabled.
11
- - It writes provider/model into the external ocr CLI's own `~/.opencodereview/config.json` — as an `api_key_cmd` command, never as a plaintext key.
12
- - Review results come back as a structured summary whose fields split into two notions: what OCR found (`status`, `aggregation`, `topComments`, `warnings`) and whether the run actually covered the selected files (`coverage`, `budgetExceeded`, `toolCalls`). Under `--audience agent` the CLI drops its progress lines to `io.Discard`, so the second notion is only reachable through those fields.
13
-
14
- ## Prerequisites (external CLI)
15
-
16
- - This package imports no OCR library, it only spawns processes: `ocr review` / `ocr scan` / `ocr delegate preview` / `ocr delegate rule` / `ocr session` / `ocr llm test`.
17
- - Commands are built against the contract verified line-by-line on the **1.13.0** source (header comments of `lib/cli.ts` and `lib/parse.ts`). That version is declared once, in `ocrCliVersion` in package.json, and mirrored by `EXPECTED_OCR_CLI_VERSION` in `lib/cli.ts`; `test/publish-manifest.test.ts` asserts the two are the same string and `test/readme-parity.test.ts` asserts this paragraph says it too, so "the README tells you to install A while the code verifies against B" cannot be self-consistent on both sides.
18
- - Multi-value `--exclude`/`--path` are merged into one comma-separated flag, and `--format` only accepts json/text/sarif.
19
- - **You install the CLI yourself.** This package deliberately ships no `optionalDependencies`: pulling `@alibaba-group/open-code-review` in as a dependency changed the user's global toolchain as a side effect of installing a plugin, and — worse — its absolute path resolved *ahead of* whatever the user had on PATH, so upgrading the CLI in the terminal never reached the plugin and the version on the card never matched the one they were running.
20
- - Command resolution order, therefore: the first `ocr` executable found on `PATH` (its absolute path becomes the command word), then a copy somebody placed in this package's own dependency tree as a fallback, and only if neither exists the bare `ocr` (which is what the tools refuse to spawn, see below). The card, the tool preflight and the actual command word all read this one judgement, so "which copy is used" cannot be told three different ways. On Windows the bundled fallback is skipped outright (`bin/ocr.js` is a shebang script that pwsh/cmd cannot execute) and the command word stays the bare `ocr`, because an absolute path with backslashes is not reliably quotable in `cmd`.
21
- - Install it with either command; the npm one carries the verified version, the brew one cannot:
22
-
23
- ```sh
24
- brew install open-code-review # formula tracks the newest release
25
- npm i -g @alibaba-group/open-code-review@1.13.0 # pinned to the verified version
26
- ```
27
-
28
- `homebrew/core` carries a single stable formula with no versioned variant (`open-code-review@x.y` does not exist), so brew cannot pin: what you get is whatever is newest. When that differs from the version above, the tools say so (see "External CLI status and version"). `ocrInstallHint` lets a deployment lead with one of the two when nothing is installed yet; a CLI that is already installed is always described by its own source.
29
- - With neither path available the tools refuse before spawning and give the install commands above with the version filled in; if a candidate existed when the verdict was taken but the child still cannot exec it, the shell answers 127 and the tool reports "ocr command not found" pointing at the card's External CLI row.
30
- - Platforms: macOS and Linux are the targets. Process reaping (the reaper guard around `ocr_review` / `ocr_scan`) depends on a POSIX toolchain - bash traps and job control plus the process-group semantics of `ps` / `pgrep` / `kill` - and the `HOME=` assignment prefix behind a custom `ocrConfigPath` is POSIX-only too. None of that exists on Windows: the package runs the bare command there (guarded by `process.platform`), skips the bundled launcher (a bare `ocr` on PATH is required), and writes the `api_key_cmd` with double-quote escaping because ocr runs credential commands through `cmd.exe` on Windows. The cost is that a hard host exit can leave an orphaned OCR process on Windows.
31
- - The provider list and the key status come from the official host channels `ctx.settings.describe()` (the `value.providers` of the `llm-pi-ai` entry) and `ctx.credentials`.
32
- - When either is missing the card shows the degradation reason while tools and settings keep working.
33
- - The host must be `>= 0.2.1-rc.2`. That floor sits in `engines.dsh`, which is documentation only — no loader or installer reads it. What actually gates installation is the exact spelling of the four peer pins: the host compares every peer range against its own runtime version (prereleases participate) and refuses with `incompatible-version` when one does not match. On a machine still running dsh 0.2.1-rc.2, upgrade dsh first, or record an exemption for this package in the profile's `compatibility.json` (`dsh plugin --profile <profile> allow-version <name@version> --dsh-version <runtime version> --accept-risk`). This bundle imports no symbol from the `@deepseek-ai/dsh` package itself (every service face comes from the `@deepseek-ai/dsh-*` sub-packages), so it is not declared as a dependency of any kind.
34
-
35
- ## External CLI status and version
36
-
37
- One judgement, `resolveOcrAvailability` in `lib/cli.ts`, answers "is there an `ocr` here, which copy, and how was it installed": the first executable found on `PATH` (with `PATHEXT` extensions on Windows), otherwise a copy inside this package's own dependency tree. "How it was installed" is read off the file the symlink in `bin` actually points at (`realpathSync`): anything under a `node_modules` is an npm-style global install, anything under `Cellar`/`Homebrew` is a formula, and neither of those is reported as unrecognised rather than guessed — the brew-vs-npm order matters because a formula-installed Node puts its own global npm packages under the same `homebrew` prefix. It is pure filesystem — `statSync(...).isFile()`, never a spawn — and it answers **candidate**, not **runnable**: a file that exists but cannot execute (no executable bit, or the bundled entry present while its platform binary is missing) passes the probe and is reported by the real spawn instead, which is why the "command not found" wording is kept as a separate fallback.
38
-
39
- | Surface | What it does with that answer |
40
- | ------- | ----------------------------- |
41
- | The five tools | The probe runs before anything spawns. With no candidate on either path the model gets "neither path found, install it like this" — with the verified version inside the command — instead of an exit-127 reverse-derivation. Re-read per call, never cached per process: installing the CLI takes effect on the next call without restarting dsh |
42
- | Settings card | A status line **outside** the provider panel (whether this machine has `ocr` and whether the host can list providers are two different facts, and a machine missing the CLI must still see the reason): which copy, which install method, which version this plugin was verified against, which version was last measured, plus the install commands when nothing is there. One `Detect version` button |
43
- | Detail page | A badge beside the title and a section under the page's own content, both rendering null for a subject that is not this package and while the read has not come back. The badge switches to "version differs" once a measurement disagrees with the verified version |
44
- | After enabling | The activation guidance slot says the install recipe, version and all, only when the answer is `none` — the outermost position a third-party bundle may render in |
45
-
46
- - The plugin **list** card's tag row is not plugin-extensible: those tags are the host's own verdicts on the entry (`running` / `off` / `problem`). The two places above are as far out as a bundle can reach, and they are client-half surfaces, so a disabled plugin cannot warn that its CLI is missing — disabling it removes the thing that would have said so.
47
- - All three client surfaces read the same `ocrBinary` field of the `providers` method, and none of them computes availability, the install channel or the install command locally: three separate judgements is how a status display drifts, and a command written out in two places is how the card ends up teaching a version the plugin does not verify against.ot verify against.
48
- - **Version is not free**: reading it spawns `ocr version`. It runs when you press `Detect version`, and once at apply when `startupVerify` is on (the same switch that governs the apply-time `ocr llm test`, because both are "may the plugin start a process at load"). A page render never spawns: the `providers` reply only reports the version measured so far, or `null` when nothing has been measured yet — the card says "verified against 1.13.0" and stays quiet about your machine until a measurement exists.
49
- - **A version disagreement is shown and said**: the receipt line names both numbers (measured vs verified), the badge flips, and `ocr_review` / `ocr_scan` append a note to the summary's `hint` so the model is told this result did not come from the verified version. It is never presented as a hard failure — a newer CLI usually works — and this package runs no install or upgrade itself: the command it shows depends on which install method that copy came from (`brew upgrade open-code-review` for a formula, `npm i -g @alibaba-group/open-code-review@<verified>` for a global package), with the brew caveat spelled out because a formula cannot pin.
50
- - The receipt shows the CLI's own output underneath the version line, with terminal control sequences stripped (upstream's launcher hard-codes the colour codes around its "new version available" nudge, and that nudge is printed by the JS wrapper, so `--color never` cannot reach it) — the line you are meant to select and copy is `npm i -g …`, and copying it must not drag escape bytes into your terminal. One completed round trip re-reads the payload, so the status line and the version you just got describe the same moment (install the CLI while the page is open and the row no longer contradicts the receipt). This package deliberately provides no update action and no clipboard API (a non-secure context would fail silently, which looks like the button doing nothing).
51
- - **Upstream self-update**: the `ocr` npm wrapper runs `scripts/update.js` on its own during invocations (18-minute cooldown, pid lock), and that script executes `npm i -g @alibaba-group/open-code-review@<latest>`. The `ocrNoAutoUpdate` deployment switch sets `OCR_NO_UPDATE=1` on every command this package spawns, so a review never changes global packages under you; it defaults to off, i.e. upstream behaviour. The version probe always sets it, switch or not — probing is a read and must not install anything. The launcher prints its "new version available" nudge to stderr *before* checking that variable, so the nudge still arrives in the receipt text.
52
-
53
- ## Installation
1
+ <p align="center">
2
+ <img src="https://cdn.jsdelivr.net/gh/JayYuen666/dsh-ocr-review@main/icon.svg" width="96" height="96" alt="dsh-ocr-review logo" />
3
+ </p>
4
+
5
+ <h1 align="center">dsh-ocr-review</h1>
6
+
7
+ <p align="center"><em>The external `ocr` (open-code-review) CLI as seven dsh model tools and one settings card — you install the CLI, the plugin only discovers, verifies and drives it.</em></p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@jayyuen66/dsh-ocr-review"><img src="https://img.shields.io/npm/v/@jayyuen66/dsh-ocr-review?style=flat-square&logo=npm&logoColor=white" alt="npm version" /></a>
11
+ <a href="https://www.npmjs.com/package/@jayyuen66/dsh-ocr-review"><img src="https://img.shields.io/npm/dm/@jayyuen66/dsh-ocr-review?style=flat-square" alt="npm downloads" /></a>
12
+ <a href="https://github.com/JayYuen666/dsh-ocr-review/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/JayYuen666/dsh-ocr-review/ci.yml?branch=main&style=flat-square&label=ci" alt="ci" /></a>
13
+ <img src="https://img.shields.io/badge/license-MIT-4c1?style=flat-square" alt="MIT" />
14
+ <img src="https://img.shields.io/badge/node-%3E%3D22.12-4c1?style=flat-square&logo=nodedotjs&logoColor=white" alt="node" />
15
+ <img src="https://img.shields.io/badge/dsh-%5E0.2.1--rc.3-658EFF?style=flat-square" alt="dsh" />
16
+ <a href="https://github.com/deepseek-ai/deepseek-harness"><img src="https://img.shields.io/badge/powered_by_dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white" alt="powered by dsh" /></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <img src="https://skillicons.dev/icons?i=typescript,nodejs,react,vitest,githubactions" alt="tech stack" />
21
+ </p>
22
+
23
+ <p align="center">
24
+ <a href="https://github.com/JayYuen666"><img src="https://img.shields.io/badge/GitHub-JayYuen666-181717?style=flat-square&logo=github&logoColor=white" alt="GitHub" /></a>
25
+ <a href="mailto:cqwkkj@gmail.com"><img src="https://img.shields.io/badge/Email-cqwkkj@gmail.com-EA4335?style=flat-square&logo=gmail&logoColor=white" alt="Email" /></a>
26
+ <a href="https://twitter.com/JayYuen666"><img src="https://img.shields.io/badge/Twitter-X%2FJayYuen666-000000?style=flat-square&logo=x&logoColor=white" alt="Twitter/X" /></a>
27
+ <a href="./README.zh-CN.md"><img src="https://img.shields.io/badge/lang-简体中文-658EFF?style=flat-square" alt="简体中文" /></a>
28
+ </p>
29
+
30
+ **A code-review bridge for [dsh](https://github.com/deepseek-ai/deepseek-harness): seven model tools (`ocr_review`, `ocr_scan`, delegate preview & rule, `ocr_session`, `ocr_rules_check`, `ocr_llm`) plus a settings card that applies the host's provider/model selection to the external CLI's own config — as a runtime command, never a plaintext key.**
31
+
32
+ ## <img src="https://api.iconify.design/lucide/file-text.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Contents
33
+
34
+ - [What it does](#what-it-does)
35
+ - [Install](#install)
36
+ - [The external CLI](#the-external-cli)
37
+ - [Verify it is live](#verify-it-is-live)
38
+ - [What it does not provide](#what-it-does-not-provide)
39
+ - [Enabling it in dsh](#enabling-it-in-dsh)
40
+ - [Tools exposed to the model](#tools-exposed-to-the-model)
41
+ - [Settings](#settings)
42
+ - [Public interface](#public-interface)
43
+ - [Credentials and the OCR config file](#credentials-and-the-ocr-config-file)
44
+ - [Background runs as host jobs](#background-runs-as-host-jobs)
45
+ - [Data and privacy](#data-and-privacy)
46
+ - [Known boundaries](#known-boundaries)
47
+ - [FAQ](#faq)
48
+ - [Development](#development)
49
+ - [License](#license)
50
+
51
+ ## <img src="https://api.iconify.design/lucide/shield.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> What it does
52
+
53
+ - **One settings card also carries the admin surfaces**: a validated MCP servers JSON editor (saving touches only `mcp_servers`) and a ChatGPT section that reports `ocr auth` status and switches OCR's provider/model. Both are human-managed; neither is a model tool (a stdio MCP server runs commands, and OAuth sign-in needs a browser plus a local callback).
54
+ - **Wraps the external `ocr` (open-code-review) CLI into seven model tools.** The host validates tool arguments not at all, so every shape, type and enum gate lives in this package: user-controlled strings are single-quote escaped, enums are whitelist-clamped, and wrong-typed values error instead of silently narrowing or widening a review.
55
+ - **One settings card** (the web client half) picks provider/model from the host's own `llm-pi-ai` settings entry and key status from the host credentials service. When either service is absent the card shows the degradation reason; tools and settings keep working.
56
+ - **Applying a selection writes the CLI's own `~/.opencodereview/config.json`** — as an `api_key_cmd` command that reads the host credential ref at OCR runtime. A plaintext key is never written anywhere.
57
+ - **Results are a structured summary with two distinct notions**: what OCR found (`status`, `aggregation`, `topComments`, `warnings`) and whether the run actually covered the selected files (`coverage`, `budgetExceeded`, `toolCalls`). The CLI is invoked with `--audience agent`, which suppresses its progress output — the second notion is only reachable through those fields.
58
+ - **CLI availability is one judgement** (`resolveOcrAvailability` in `lib/cli.ts`): pure filesystem, never a spawn, re-read per call. The card status row, the detail-page badge and the activation guidance all render that one answer, so "which copy is in use" cannot be told three ways.
59
+ - **Background runs (`wait: false`) are official host jobs**: `job_list` / `job_output` / `job_kill` can observe and stop a review that outlives the tool call.
60
+
61
+ ## <img src="https://api.iconify.design/lucide/package.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Install
54
62
 
55
63
  ```sh
56
64
  dsh plugin --profile web add @jayyuen66/dsh-ocr-review
57
65
  ```
58
66
 
59
- - **Upgrading an installed copy is remove-then-add.** While the profile runs HMR (the shipped profiles do), `add` on a package the profile already depends on refuses *before* pnpm runs - `application: 'failed'` with `error.code: 'already-installed'`, no profile file touched - and so does the Web page's install box. Run `dsh plugin --profile web remove @jayyuen66/dsh-ocr-review` first, then `add` the target version; the removal stops the old bundle's plugins and drops its module mappings, so the new version starts without a restart. Without HMR the same `add` runs pnpm and reports `restart-required`.
60
- - The packages are on the public npm registry, so installation needs no credentials.
61
- - The published files are only `host.js`, `client.js`, `cordis.patch.yml`, `scripts` and `THIRD_PARTY_NOTICES.md` (third-party licenses of the bundled runtime dependencies; `prepack` rebuilds both bundles), source repository: see `repository.url` in package.json.
62
- - No `@deepseek-ai/*` goes in `dependencies`, and that is not a style preference. Consumers of this package are dsh plugins installed into a profile (`nodeLinker: hoisted`, `autoInstallPeers: false`), so any host package listed under `dependencies` is written into that profile as a **real directory**, coexisting with the copy the host process already loaded. `@deepseek-ai/dsh-tools` keys its `TOOL_RUNTIME_SCHEDULER` with a plain `Symbol` (not `Symbol.for`), so symbol identity is per module instance: the host's `dsh-agent-loop` reads a `ToolRuntime` mounted from the duplicate using its own copy's symbol, gets `undefined`, and **every native tool call throws** `Cannot read properties of undefined (reading 'prepare')` — the whole profile loses its tools. This package's build, typecheck and tests all stay green right up to that point, so `test/publish-manifest.test.ts` pins the invariant in the manifest instead.
63
- - The four host packages this bundle imports as **values** are required (non-optional) `peerDependencies`: `@deepseek-ai/schemastery` (the host's fork of schemastery — only it implements `.volatile()` resolution), `@deepseek-ai/dsh-credentials`, `@deepseek-ai/dsh-home-paths` and `@deepseek-ai/dsh-atomic-write`. The host provides them at runtime, and a profile installs no peers, so no duplicate appears. `build-host.mjs` externalizes `dependencies`, `peerDependencies` *and* `optionalDependencies`, so `host.js` keeps the bare specifiers unchanged.
64
- - Those four are repeated in `devDependencies` — that is what lets this repository's own typecheck, build and tests resolve them. Every other `@deepseek-ai/*` is type-only (erased at build, no specifier left in `host.js`) and stays in `devDependencies` alone.
65
- - What is left in `dependencies` is genuinely this package's own runtime code: `@jayyuen66/dsh-plugin-shared` and `js-yaml` (the last one used only by `scripts/get-cred.mjs`).
67
+ Remove with `dsh plugin --profile web remove @jayyuen66/dsh-ocr-review`. The package is on the public npm registry, so installation needs no credentials.
68
+
69
+ - **Upgrading an installed copy is remove-then-add.** On a profile running HMR (the shipped ones do), `add` on a package the profile already depends on refuses before pnpm runs (`already-installed`) — run `remove` first, then `add` the target version; the new one starts without a restart. Without HMR the same `add` runs pnpm and reports `restart-required`.
70
+ - **Requires Node.js `>= 22.12` and host `dsh` on the `0.2.1-rc.3` line.** The host reads `engines.dsh` (`^0.2.1-rc.3`) and decides on it alone; prereleases participate in the comparison. An incompatible host needs the explicit risk grant `dsh plugin --profile <p> allow-version @jayyuen66/dsh-ocr-review@<version> --dsh-version <exact> --accept-risk`.
71
+ - **No `@deepseek-ai/*` under `dependencies`, by contract** (`test/publish-manifest.test.ts` enforces it). Consumer profiles install with `nodeLinker: hoisted` and `autoInstallPeers: false`, so a host package there is materialized as a real directory next to the copy the running host already loaded. `@deepseek-ai/dsh-tools` keys its scheduler with a plain `Symbol` (not `Symbol.for`), so symbol identity is per instance and **every native tool call in that profile throws** — while this package's build, typecheck and coverage gates stay green right up to that moment.
72
+ - **The five host packages `host.js` imports as values are required peers**: `@deepseek-ai/schemastery` (the host fork — only it resolves `.volatile()` fields), `@deepseek-ai/dsh-credentials`, `@deepseek-ai/dsh-home-paths`, `@deepseek-ai/dsh-atomic-write` and `@deepseek-ai/dsh-typert-protocol` (the Remote service base). Each is repeated in `devDependencies` at the same pin so this repository's own typecheck resolves them; the build externalizes all manifest tables, keeping bare specifiers in the artifact.
73
+ - **What ships**: `host.js`, `client.js`, `cordis.patch.yml`, `scripts/`, `icon.svg`, `CHANGELOG.md` and `THIRD_PARTY_NOTICES.md`. `prepack` rebuilds the bundles, so nothing stale is published.
74
+
75
+ ### <img src="https://api.iconify.design/lucide/arrow-down-to-line.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Shared version floor
66
76
 
67
- ## Installing and upgrading the external CLI
77
+ If your profile pins `@jayyuen66/dsh-plugin-shared` with a pnpm `overrides` entry, that pin must be at least the version this package declares. A lower pin installs a copy without the names imported at runtime, and the host then reports `N entries did not activate` together with `does not provide an export named ...` at boot — the package installs fine and never loads, and no per-repository CI run can see it.
68
78
 
69
- This package spawns `ocr`; it does not install it. Pick whichever fits your machine:
79
+ ## <img src="https://api.iconify.design/lucide/terminal.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> The external CLI
80
+
81
+ This package spawns `ocr`; it never installs or upgrades it. The command contract is verified against **1.13.3** (`EXPECTED_OCR_CLI_VERSION` in `lib/cli.ts`, declared once as `ocrCliVersion` in package.json — tests pin the manifest, the code constant and both READMEs to the same string).
70
82
 
71
83
  ```sh
72
84
  brew install open-code-review # the formula tracks the newest release
73
- npm i -g @alibaba-group/open-code-review@1.13.0 # pinned to the version this plugin verifies against
85
+ npm i -g @alibaba-group/open-code-review@1.13.3 # pinned to the version this plugin verifies against
74
86
  ```
75
87
 
76
- - **brew cannot pin a version.** `homebrew/core` carries one stable formula for `open-code-review` and no versioned variant (`open-code-review@1.12` does not exist), so `brew install` / `brew upgrade` always yields whatever is newest upstream. If the plugin's verified version is what you need, install it with npm; the card says the same thing wherever it shows a brew command.
77
- - **The plugin never runs either command.** The version probe sets `OCR_NO_UPDATE=1` so that reading state cannot trigger upstream's own global install, and `ocrNoAutoUpdate` extends that to every command (see above).
78
- - **Upgrading an existing install** is described by that install's own source: `brew upgrade open-code-review` for a formula, `npm i -g @alibaba-group/open-code-review@<version>` for a global package. Where the path says neither (`~/bin/ocr` copied by hand, `npx`, a prefix we do not recognise), the deployment's `ocrInstallHint` decides which of the two to lead with.
79
- - **Upgrading from a release that shipped the CLI** (`optionalDependencies`, every release up to and including 0.1.5-rc): nothing needs doing, because PATH now wins over the bundled copy, so the stale one stops shadowing your own. If you want it gone from the profile's tree, remove it there (`pnpm remove @alibaba-group/open-code-review` under `<dsh data dir>/profiles/<profile>/`, or reinstall the profile); the `allowBuilds: {'@alibaba-group/open-code-review': true}` entry that release needed in that profile's `pnpm-workspace.yaml` can be deleted too.
80
- - **`ERR_PNPM_IGNORED_BUILDS` no longer comes from this package.** Earlier releases tripped it because upstream's wrapper carries a `postinstall` (`scripts/install.js`) and pnpm 10+ will not run a dependency's build script unless allowlisted. With no dependency to run, that error can only be coming from some other package; the host's own approval flow (the web plugin page, or `install_bundle`'s `approvedBuilds`) still covers those cases, and the host validates only the pending package names — you have to approve explicitly either way.
88
+ - **brew cannot pin.** `homebrew/core` carries one stable formula and no versioned variant, so `brew install` / `brew upgrade` always yields whatever is newest upstream. The npm command is the only one that can carry the verified version.
89
+ - **PATH wins, and the refusal is honest.** Command resolution takes the first `ocr` on `PATH`, then a copy inside this package's own dependency tree (skipped on Windows — a shebang script pwsh/cmd cannot execute); with neither, the tools refuse before spawning and hand the model the install commands above with the version filled in. "How it was installed" is read off the real target of the `bin` symlink: npm-style under `node_modules`, a formula under `Cellar` / `Homebrew`, otherwise reported as unrecognised rather than guessed.
90
+ - **Version is measured, not assumed.** Reading it spawns `ocr version` (15 s wall clock, always with `OCR_NO_UPDATE=1`) — on the card's Detect button, and once at apply when `startupVerify` is on. Rendering a page never spawns: the card shows the last measurement, or nothing measured yet. A disagreement names both numbers, flips the badge and appends a note to the review summary's `hint`; it is never a hard failure, and this package runs no installer.
91
+ - **Upstream self-update is real.** The npm wrapper runs `npm i -g @alibaba-group/open-code-review@<latest>` during invocations on its own. The version probe always suppresses that; `ocrNoAutoUpdate` extends the suppression to every command this package spawns (see Settings).
92
+ - **Upgrading from a release that bundled the CLI** (`optionalDependencies`, up to and including 0.1.5-rc): nothing to do — PATH now wins, so the stale copy stops shadowing yours. To clean the profile's tree, remove the package there and delete the `allowBuilds` entry that release needed in the profile's `pnpm-workspace.yaml`.
93
+ - **Platforms.** macOS and Linux are the targets: the process reaper and the `HOME=` injection behind a custom `ocrConfigPath` are POSIX-only. Windows runs the bare command without reaping (a hard host exit can leave an orphaned OCR process) and requires a global `ocr` on PATH.
81
94
 
82
- ## Enabling it in dsh
95
+ ## <img src="https://api.iconify.design/lucide/circle-check.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Verify it is live
83
96
 
84
- - The in-package `cordis.patch.yml` declares `- id: ocr-review` / `name: "@jayyuen66/dsh-ocr-review"` and is pointed at by `dsh.bundle.patch` in `package.json`.
85
- - `dsh plugin --profile web add/remove` registers and removes it, then restart dsh.
86
- - The card needs a web profile (`dsh.client.platform: web`, `immediately: true`).
87
- - The five `ocrReview` methods are registered on the apply fiber (`installOcrRemote`, unconditional): they need no optional host service, so a TUI host that never brings up a web layer still has them, and tools and settings stay available either way.
88
- - The gateway exposes them only to clients of this profile; authentication and the source checks are its own, so this package has no CSRF token, no body cap and no route disposer of its own.
89
- - Deployment defaults can go on the profile's `config:` line (cordis validates and fills defaults through the exported `Config` schema); precedence: runtime settings value > line config > built-in default.
97
+ 1. **Mounted**: `dsh --profile web --dump-config` ends with this package's layer (`# == @jayyuen666/dsh-ocr-review`).
98
+ - That command is the only accepted "it is in the layer stack" signal, and it is **not read-only** — it rewrites the profile's root assembly file. Read layer lines from stdout **and** check stderr separately: an unmatched patch target appears only on stderr, so the exit code alone proves nothing. Accept both `# == <layer>` and `# == <layer>, patched by <path>`.
99
+ 2. **The card renders**: the settings page shows the card, and its External CLI row names which copy is in use, how it was installed, and which version this plugin verifies against.
100
+ 3. **Detect version works**: pressing it runs one `ocr version` and fills the measured version into the row — or names the failure arm (command missing, non-zero exit, timeout, nothing parseable).
101
+ 4. **Tools answer honestly without the CLI**: on a machine with no `ocr`, `ocr_review` refuses before spawning and returns the install commands with the verified version — not an exit-127 to reverse-derive.
90
102
 
91
- ## Tools exposed to the model
103
+ ## <img src="https://api.iconify.design/lucide/circle-slash.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> What it does not provide
92
104
 
93
- | Tool | Arguments and constraints |
94
- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
95
- | `ocr_review` | repo (absolute path, default = current session workspace), scope workspace/commit/branch (branch needs both from+to and is mutually exclusive with commit), effort, background, exclude (at most 50 entries), provider/model/resume (resume only with commit/branch — workspace reviews cannot be resumed), wait |
96
- | Numeric group (arguments of `ocr_review`) | concurrency/timeoutMinutes/maxTools/maxTokens/maxTokensBudget (mapped to `--concurrency` `--timeout` `--max-tools` `--max-tokens` `--max-tokens-budget`; non-integers or values below the floor are rejected; note that `--max-tools` values 1-49 are raised to 50 by OCR — its help text says min 50) |
97
- | `ocr_scan` | repo, path (at most 100 entries), exclude (50), batch none/by-language/by-directory, provider/model (native shared flags of scan_cmd, matching review), the same numeric group, wait; no git diff required |
98
- | `ocr_delegate_preview` / `ocr_delegate_rule` | The former: repo, scope/commit/from/to, exclude 50, background. The latter: repo, paths required, 1–200 entries, positional arguments after `--`, each escaped. Zero LLM cost on the OCR side, they return only the file list and the rule groups |
99
- | `ocr_session` | repo, action list/show/comments (whitelist, anything else errors), id, limit (clamped to 1–100, default 10); show/comments without an id falls back to list |
100
- | Background and reaper | `wait: false` (background start, no host deadline, no time limit by default, no `--output`, poll results with `ocr_session`) and the host reaper guard apply only to these two minute-scale commands, review and scan - that subprocess is also an official job (see the job-surface section below); that change left the tool's JSON untouched (a later output-contract rework switched it to the direct canonical object, see below) |
105
+ - **It does not install or upgrade the CLI.** The brew/npm commands are shown, never run; there is no update action and no clipboard API (a non-secure context would fail silently, looking like a dead button).
106
+ - **No HTTP route of its own.** The data plane is one official Typert Remote namespace (`ocrReview`) through the host `/api` gateway; authentication, Host / DNS-rebinding / Origin checks and body limits are the gateway's. This package holds no CSRF token, no body cap and no route disposer.
107
+ - **No CLI subcommand.** `dsh ocr …` does not exist.
108
+ - **It reads no file outside** the CLI's config path, the temp files it creates itself, and the host settings / credentials services it is handed.
109
+ - What it *does* consume: the host `settings` and `credentials` services (provider list, key status), `shell` (every `ocr` subprocess), `jobs` (background runs) and `systemPrompt` (one routing section). A missing settings or credentials service degrades the card only — the tools keep working.
101
110
 
102
- ## Settings
111
+ ## <img src="https://api.iconify.design/lucide/plug.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Enabling it in dsh
103
112
 
104
- | Field | Values, defaults and use |
105
- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
- | `effort` | low/medium/high, built-in default medium; used when `ocr_review` is called without an explicit effort |
107
- | `language` | 中文/English, default 中文; written as the top-level `language` key of the OCR config when a selection is applied |
108
- | `autoVerify` | default true; when true, a successful `/select` also runs `ocr llm test --color never` (capped at 90 seconds) |
109
- | `maxComments` | default 12, the number of comments kept in the summary; 0 = no truncation, non-integers and negatives fall back to 12 |
110
- | `timeoutMinutes` | default 0 = request the host cap (the host clamps to min(request, shell.maxTimeoutMs)), >0 is a number of minutes |
111
- | `ocrConfigPath` | where the external ocr CLI config lives; left empty it derives `os.homedir()/.opencodereview/config.json`, `~` and `~/` prefixes are accepted, relative paths error out. **A custom value must follow the `<X>/.opencodereview/config.json` layout**: OCR has no file-level path override (it only ever looks at `<HOME>/.opencodereview/config.json`, `config_cmd.go:92-99`), so the plugin makes it effective by injecting `HOME=<X>` into the ocr subprocess (config and sessions are redirected together, and `api_key_cmd` carries the host-resolved data directory as get-cred's explicit first-tier locator); any path outside that layout is rejected outright at the setting layer rather than silently mismatching (the HOME injection is a POSIX assignment prefix; Windows has no such channel, so custom paths only take effect on macOS/Linux) |
113
+ - `dsh.bundle.patch` in `package.json` points at `cordis.patch.yml`, whose single registration line is `- id: ocr-review` with `name` set to the bare package name — the bare name is what makes the host scan the client half.
114
+ - The card needs a web profile (`dsh.client.platform: web`, `immediately: true`). The five `ocrReview` methods are installed unconditionally on the apply fiber, so a host whose web layer never comes up (a TUI) still has the tools and settings.
115
+ - The gateway exposes the methods only to clients of this profile; this package adds nothing in front of it.
116
+ - Deployment defaults go on the registration line's `config:` (cordis validates through the exported `Config` schema); precedence: settings-card runtime value > line config > built-in default.
112
117
 
113
- Three deployment-level tuning keys are deliberately **not** on the settings card — they are plain (non-volatile) fields of the exported `Config`, settable only on the profile's `config:` line and taking effect on restart:
118
+ ## <img src="https://api.iconify.design/lucide/hammer.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Tools exposed to the model
114
119
 
115
- | Key | Default | Use |
116
- | -------------------- | --------- | ------------------------------------------------------------------------------------------------------------ |
117
- | `llmTestTimeoutMs` | `90000` | Wall clock for `ocr llm test` (shared by autoVerify and the card's "test connection"); raise it on slow machines |
118
- | `ocrBackgroundMaxMs` | `0` | Backstop window for background reviews (`jobs.wait` to the deadline, then `kill`); 0 = none, so a run ends only when the host exits, the session stops, the plugin unloads or the job is killed |
119
- | `stdoutMaxBytes` | `400000` | Executor stdout buffer cap, shared by foreground and background runs |
120
+ | Tool | Arguments and constraints |
121
+ | --- | --- |
122
+ | `ocr_review` | repo (absolute path, default = the session workspace), scope workspace/commit/branch (branch needs both from+to and is mutually exclusive with commit), effort, background, exclude, provider/model/resume — resume only with commit/branch; a workspace run cannot be resumed. preview (file-selection only), noFilter, maxGitProcs, rule/backgroundFile (repo-root files only), wait |
123
+ | Numeric group (review and scan) | concurrency / timeoutMinutes / maxTools / maxTokens / maxTokensBudget, mapped to `--concurrency` `--timeout` `--max-tools` `--max-tokens` `--max-tokens-budget`. Values pass through faithfully; min floors are 1 for concurrency and 0 for the rest, and non-integers or below-floor values error instead of clamping |
124
+ | `ocr_scan` | repo, path, exclude, batch none/by-language/by-directory, provider/model (the CLI's native shared flags), the same numeric group, preview, noPlan/noDedup/noSummary, resume, maxGitProcs, rule (repo-root file), wait. Whole-repo scanning, no git diff required |
125
+ | `ocr_delegate_preview` / `ocr_delegate_rule` | preview: repo, scope/commit/from/to, exclude, background, backgroundFile/rule/maxGitProcs. rule: repo plus paths — required, up to 200 entries, positional after `--`, each escaped — plus rule. Zero LLM cost on the OCR side: they return the file list and the rule groups |
126
+ | `ocr_session` | repo, action list/show/comments/compare/export, id, before/after (compare), severity/category (comments filter), limit — default 10; an explicit value must be an integer in 1–100 and out-of-range errors rather than clamping. compare returns the four buckets; export returns an HTML path |
127
+ | `ocr_rules_check` | repo, path (required), rule (repo-root file): print the winning rule layer, glob and body; no LLM call |
128
+ | `ocr_llm` | action providers/models: read-only LLM catalogue queries; no review and no connectivity test |
129
+ | List caps | exclude and path take up to 2000 entries each; exceeding the cap rejects the call. Entries are never silently dropped — "reviewed fewer files than the list" must not be reportable as success |
120
130
 
121
- A fourth non-volatile field is a deployment decision rather than a tuning value, for the same reason (it changes what a run may do to the machine, so it does not belong on a card a user can flip mid-review):
131
+ `wait: false` starts a background run with no host deadline (poll `ocr_session`; the subprocess is also an official job, see [Background runs as host jobs](#background-runs-as-host-jobs)), and the reaper guard takes the OCR process tree down when dsh exits in any way. Cancelling the tool call stops the corresponding background process.
122
132
 
123
- | Key | Default | Use |
124
- | ------------------ | ------- | ------------------------------------------------------------------------------------------------------ |
125
- | `ocrNoAutoUpdate` | `false` | When true, every `ocr` command this package spawns carries `OCR_NO_UPDATE=1`, which stops upstream's wrapper from running `npm i -g @alibaba-group/open-code-review@<latest>` in the middle of a review. `false` keeps upstream behaviour (18-minute cooldown, pid lock). The version probe sets the variable regardless of this switch |
133
+ ## <img src="https://api.iconify.design/lucide/sliders-horizontal.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Settings
126
134
 
127
- The fifth is about which install command a user is *shown*, which the same reasoning keeps off the card (a deployment that standardises on brew or on npm should not have each machine discover it separately):
135
+ The namespace is the entry id `ocr-review`; the card fields are the `.volatile()` ones.
128
136
 
129
- | Key | Default | Use |
130
- | --------------- | -------- | ------------------------------------------------------------------------------------------------------ |
131
- | `ocrInstallHint` | `both` | When nothing is installed, which command the tools, the card and the activation guidance lead with: `both` (show both), `brew`, `npm`. It is a fallback, not an override: once a candidate exists its own install source decides the wording, because telling a formula user to run `npm i -g` would leave a second copy behind while PATH still resolves to the old one. The npm command always carries the verified version; the brew one never can |
137
+ | Field | Values, default, use |
138
+ | --- | --- |
139
+ | `effort` | auto/low/medium/high, default auto; `auto` omits `--effort` so OCR's own configured effort wins. Used when `ocr_review` is called without an explicit effort |
140
+ | `language` | 中文/English, default 中文; written as the top-level `language` key of the CLI config when a selection is applied |
141
+ | `autoVerify` | default true; a successful select also runs `ocr llm test` (capped by `llmTestTimeoutMs`) |
142
+ | `maxComments` | default 12, the number of comments kept in the summary; 0 = no truncation, non-integers and negatives fall back to 12 |
143
+ | `timeoutMinutes` | default 0 = request the host cap (the host clamps to min(request, shell.maxTimeoutMs)); above 0 is a number of minutes |
144
+ | `ocrConfigPath` | Where the CLI config lives; empty derives `<home>/.opencodereview/config.json`, `~` and `~/` prefixes accepted, relative paths error. A custom value must follow the `<X>/.opencodereview/config.json` layout — the CLI has no file-level path override, so the plugin injects `HOME=<X>` into the subprocess (config and sessions redirect together); anything else is rejected at the setting layer. POSIX-only: Windows has no such channel |
132
145
 
133
- ## Credentials and config files
146
+ The deployment keys below are deliberately **not** on the card — they are plain (non-volatile) fields of the exported `Config`, settable only on the profile's `config:` line and taking effect on restart:
134
147
 
135
- | Aspect | Fact |
136
- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
137
- | Credential form in the config | What lands in the config is a command, not a secret: `api_key_cmd` = `node '<path of scripts/get-cred.mjs in this package>' '<REF>' '<dsh data dir>'` (POSIX, single-quote escaped) or `node "<path>" "<REF>" "<dsh data dir>"` (Windows, double-quote escaped - ocr runs credential commands through `cmd.exe` there); the third part is the host's current `resolveDshHome()` result, so get-cred's fallback layers stay correct when HOME is redirected or the dsh home is set outside the env, and the REF name must match `^[A-Z0-9_]+$` or the command is refused |
138
- | Precedence mirroring | get-cred reads its three layers in the **same order** as the official credentials-local: `refs.<REF>` in `$DSH_HOME/.credentials.yaml` first, then the inherited process environment, then `$DSH_HOME/.env`. Getting the order wrong fails silently: the host treats the managed file as the effective credential, so a script that answers with the environment copy first makes OCR authenticate against a different key than the one the card reports while both sides show success. dsh 0.2.1-rc.2 moved the environment layer below the managed file, and this package's script plus `test/get-cred.test.ts` moved with it |
139
- | Reachability gate | `select` and `migrate` refuse a key whose credential source OCR cannot reach at runtime: dsh strips variables named `KEY`/`PASSWORD`/`SECRET`/`TOKEN` or prefixed `DSH_` from spawned shells (`scrubbedParentEnv`), and get-cred deliberately does not read the reviewed repository's `.env`. Keys that only live in the dsh process environment or the workspace `.env` therefore resolve on the host side yet fail at OCR runtime - previously a silent "select succeeded → OCR 401". Sources `file` (`$DSH_HOME/.credentials.yaml`) and `user-env` (`$DSH_HOME/.env`) pass; `env` passes only when the ref name matches none of the scrubbed patterns; `project-env` never passes. The refusal happens before any write, with the fix named in the error text (store the key in the managed credentials file or `$DSH_HOME/.env`) |
140
- | How writes happen | Atomic replacements via the official `@deepseek-ai/dsh-atomic-write`: a random-suffixed `.<hex>.tmp` sibling created with `wx`, then rename, with the new inode carrying 0600 (parent directories 0700). The `.bak` backup is copied by this package **before** the rename and chmod-ed to 0600 (the official helper has no backup semantics). The whole read→decide→write span is serialized by the official `withFileLock`, so a short-lived `config.json.lock` appears in that directory during a write and is removed in `finally`; a lock left by a crashed holder is taken over via a pid liveness probe. **Known inconsistency**: contention beyond the official default 2s wait makes the write throw `atomic-write: timed out waiting for the writer lock at …`, and the endpoint answers 400 with that English text verbatim — it comes from the official package and bypasses `lib/messages.ts`, unlike every other user-visible error here. Before this swap the read-modify-write shared one event-loop tick, so this failure mode did not exist; mapping it would need an injectable wait budget plus a timeout test, so this package documents it instead of silently widening the surface. An existing config that is invalid JSON or whose top level is not an object aborts the write instead of "treating it as empty and overwriting" |
141
- | `migrate()` | Replaces the plaintext `api_key` of custom provider entries with `api_key_cmd` and deletes the plaintext; entries whose key source is unreachable at OCR runtime (same gate as `select`) or whose `apiKeyEnv` is not found in settings are left untouched and listed in `skippedUnknown`; nothing is written when nothing was migrated |
142
- | `scripts/get-cred.mjs` | Spawned by the external ocr CLI itself and the only place in this package still reading host credential files. The data directory is resolved as explicit third argument > `$DSH_HOME` > `~/.dsh`, and the lookup order is the one named under **Precedence mirroring** above (managed document > inherited environment > `.env`) - note the inherited layer is usually empty for credential refs, because dsh scrubs `KEY`/`PASSWORD`/`SECRET`/`TOKEN`- and `DSH_*`-named variables out of spawned shells. The project `.env` of the reviewed repository is deliberately not read; when all three layers miss it exits non-zero and names every location it checked |
148
+ | Key | Default | Use |
149
+ | --- | --- | --- |
150
+ | `llmTestTimeoutMs` | `90000` | Wall clock for `ocr llm test`, shared by autoVerify and the card's test connection; raise it on slow machines |
151
+ | `startupVerify` | `true` | Run the endpoint self-check (and one version measurement) at apply. The same switch governs both, because the criterion is "may a load spawn processes"; turn it off if loads must stay process-free |
152
+ | `ocrBackgroundMaxMs` | `0` | Backstop window for background reviews (registry wait to the deadline, then kill); 0 = no window — a run ends only when the host exits, the session stops, the plugin unloads or the job is killed |
153
+ | `stdoutMaxBytes` | `400000` | Shell executor stdout cap, shared by foreground and background runs (review results go through the `--output` temp file precisely to step outside it) |
154
+ | `ocrNoAutoUpdate` | `false` | true puts `OCR_NO_UPDATE=1` on every command this package spawns, stopping upstream's mid-review `npm i -g` of a newer release; false keeps upstream behaviour. The version probe sets the variable regardless |
155
+ | `ocrInstallHint` | `both` | Which install command to lead with when nothing is installed: `both` / `brew` / `npm`. A fallback, not an override — an existing copy is always described by its own source, because telling a formula user to run `npm i -g` leaves a second copy behind while PATH still resolves the old one. The npm command always carries the verified version; the brew one never can |
143
156
 
144
- ## Public methods
157
+ ## <img src="https://api.iconify.design/lucide/network.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Public interface
145
158
 
146
- The card's contract surface is one official Typert Remote namespace, `ocrReview` (`OCR_REMOTE_NAMESPACE` in `lib/remote-shape.ts`), whose five methods are marked programmatically (`markRemote` in `host.ts`). There are no `/_dsh/*` routes any more: authentication, the Host / DNS-rebinding / Origin checks and the request-size limit are the host `/api` gateway's job, so this package holds no CSRF token, no body cap, no 405 arm and no route disposer.
159
+ One official Typert Remote namespace, `ocrReview` (`OCR_REMOTE_NAMESPACE` in `lib/remote-shape.ts`), its nine methods marked programmatically in `host.ts`. The service registers at construction and is withdrawn with its fiber, so a hot reload cannot leave a stale namespace behind.
147
160
 
148
161
  | Method | Input | Success payload |
149
162
  | --- | --- | --- |
150
- | `providers()` | — | `{providers (each with a hasKey boolean), current, getCredReady, source, endpointVerify, ocrBinary}`, never containing a key. `ocrBinary` is the filesystem-only availability verdict plus the version context the card renders: `{source: "path" \| "bundled" \| "none", path?, channel?: "brew" \| "npm" \| "unknown", expectedVersion, measuredVersion: string \| null, installHint}` — `measuredVersion` is whatever the last `ocr version` produced (apply-time self-check or a pressed Detect), `null` when nothing has run yet, and reading this method never spawns. `installHint` is that install sentence, localized and composed host-side so the card cannot drift from the version the plugin verifies against. `endpointVerify` is the apply-time `ocr llm test` result or null when it has not run |
151
- | `select(request)` | `{provider, model}`, both must hit the list returned by `describe()` | `{ok, applied, llmTest}` (`llmTest` is null when `autoVerify` is off) |
163
+ | `providers()` | — | `{providers (each with a hasKey boolean), current, getCredReady, source, endpointVerify, ocrBinary}` — never a key. `ocrBinary` carries the filesystem-only availability verdict plus the version context (`source`, `channel`, `expectedVersion`, `measuredVersion: string \| null`, `installHint`); reading this method never spawns |
164
+ | `select(request)` | `{provider, model}`, both must hit the list `describe()` returns | `{ok, applied, llmTest}` (`llmTest` is null when `autoVerify` is off) |
152
165
  | `migrate()` | — | `{ok, migrated, skippedUnknown}` |
153
- | `test()` | — | `{ok, output}` (`ok` here is the **test verdict**, not whether the call ran; output is redacted first, then cut to 8000 characters) |
154
- | `probe()` | — | `{ok, version, expectedVersion, consistent, output, reason, changeText}` — spawns `ocr version` with a 15s wall clock and `OCR_NO_UPDATE=1`, reads the version out of its output and writes it into this apply's slot so the next `providers` read and the next `ocr_review`/`ocr_scan` receipt describe the same measurement. `version` is null unless the command succeeded and printed a parseable version; `consistent` is a **three-state** (`true` / `false` / `null` — null means no version was read, where claiming a mismatch would be claiming something with no evidence); `reason` names the failure arm (`command not found`, non-zero exit, timeout, or exit 0 with nothing parseable, which is what an unreleased build looks like); `changeText` carries the install/upgrade sentence only when there is a command to give — a measured version that differs, or no candidate at all — and is empty on a timeout with the CLI still in place; `output` is redacted and cut the same way as `test`, with terminal control sequences stripped, so an upstream upgrade notice stays copyable |
155
- | Refusals | — | the write methods answer `{ok:false, error, status}`, where `status` is a **retained semantic code, not an HTTP status**: the gateway frames the reply, the client renders `error`, and the number is what lets the tests pin which rule fired (400 for an empty or off-list selection, 500 for a write that failed or a credential script that is missing) |
156
-
157
- The service registers at construction (that is cordis' `Service` contract, via `ctx.reflect.provide`) and is withdrawn with the fiber it was made on, which is why `installOcrRemote` returns nothing useful and why a hot reload cannot leave a stale namespace behind — the disposer bookkeeping the old routes needed is gone with them. The client half (`src/remote.ts`) holds the five descriptors, `$mount`s them once and then reads the derived key `remote.ocrReview`; with no `remote` service in the client context there is no reader at all and the card falls back to its `remoteUnavailable` line. There is deliberately **no client-side wall clock** on these calls — the timeout belongs to the gateway, and a second one in the card is how a slow write gets reported as lost while it actually landed.
158
-
159
- ## The background job surface (official `ctx.jobs`)
160
-
161
- The external `ocr` subprocess started by `wait: false` is also registered as an **unowned** job in the host's `ctx.jobs` (`kind: "ocr-review"`, id `ocr-review-<16 hex>`, handed out by the registry from a truncated randomUUID rather than a counter; being unowned also means the official `job/registered` / `job/settled` session lifecycle records are not written, since those need an owner). What changed is who can see and stop it, not what the model receives:
162
-
163
- | Aspect | Fact |
164
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
- | Model observation surface | Three more tools: the official `job_list` shows the review, `job_output` reads its stdout/stderr (the registry pulls from `proc.observed` on its own cadence - non-consuming, so it never steals bytes from the `readOutput()` cursor), and `job_kill` stops it. Results still come from the `ocr_session` record; the payload content is unchanged since the job-surface swap, and a later output-contract rework returns the canonical object directly (no more stringify-ing the receipt into a `{ text }` wrapper) |
166
- | Broken executor reader | When the executor's reader throws, the official pump only writes one line to the host log and afterwards reads that channel as empty (measured) ⇒ this package writes **one** "this section is incomplete" note into the ring, exactly once, and stops knocking on the broken reader |
167
- | Controller lifetime | Attached only for the instant of `start`: the registry refuses `start` when no controller serves the owner, and on the web surface the host's own `tool-jobs` row is disabled at the host plane (each preset realm mounts its own), so an unowned job needs a controller of our own. We attach it and detach it immediately (measured: detaching restores the refusal, and read/kill/settlement never need it again) - a resident token would pry that gate open for a composition that deliberately has no job tools |
168
- | Three reap paths | The optional backstop window, a plugin unload, and a session dispose all call `jobs.kill(id, undefined, reason)` instead of killing the process around it, so the record moves to `stopping` and the reason lands in `detail` (measured: bypassing it left the row stuck at `running` forever). They may overlap - killing a `stopping` job still returns `requested` and `proc.kill()` is idempotent. Reasons are model-facing, so they come from the bilingual catalog |
169
- | Nothing there may throw | An error raised inside a host event handler is rethrown by Node via `process.nextTick` ⇒ uncaught ⇒ **the whole host process exits** (reproduced locally: `Error: unknown job ...` followed by `EXIT=1`). The official package does not cover for producers either - `killJob` calls `job.cancel()` bare (dsh-jobs-local's `killJob`, and only the teardown arm wraps each call in try/catch), and a reloaded registry throws for an unfamiliar id (the `expect` throw in the same file). So two layers each catch once: `cancel` swallows the "process is already gone" family through `killProc`, `stop` catches the registry arm and falls back to killing our own process. One test per layer - deleting either layer turns it red |
170
- | The optional backstop | We still give the external CLI no host `timeoutMs` (a long review would be cut off), but "no end at all" gained a victim with this adoption - the 10-slot unowned bucket is **shared host-wide** (measured: `running` and `stopping` both count, overflow refuses new `start`s), so one hung CLI parks a slot forever. The backstop uses the registry's own `wait(id, ms)` + `kill`, not a host timer and not a bare `setTimeout` |
171
- | Unowned exposure | Unowned means visible to every session - any caller can `list`/`read`/`kill` it. Known and accepted for this wave (owned jobs would need the `dsh-agent` registry, measured unavailable); rolling the adoption back is the only way to close it |
172
- | Settled-record window | The registry never recycles settled records on its own, and it outlives this plugin - so before each registration this package prunes the oldest settled `ocr-review` records down to 9 and only then starts, so the roster never holds more than 10 (each ring is capped at 256 KiB). At unload both jobs are done: live ones are killed through the registry, settled ones are removed - disabling this plugin means there is no "next apply" left to prune the window. Live and stopping records are never pruned: the registry answers overflow by **refusing `start`** (measured: the unowned bucket holds 10), not by killing somebody's review |
173
- | No registry, no background | When the host has not loaded `dsh-jobs-local`, `wait: false` throws an error naming the missing piece instead of starting a subprocess nobody can observe. Foreground runs (`wait: true`) are unaffected |
174
-
175
- ## Data and privacy
166
+ | `test()` | — | `{ok, output}` — `ok` is the **test verdict**, not whether the call ran; output is redacted first, then cut to 8000 characters |
167
+ | `probe()` | — | `{ok, version, expectedVersion, consistent, output, reason, changeText}` — one `ocr version` under a 15 s wall clock, with `OCR_NO_UPDATE=1`. `consistent` is three-state (`null` = nothing was measured, where claiming a mismatch would be claiming without evidence); `reason` names the failure arm; `changeText` carries the install/upgrade sentence only when there is a command to give |
168
+ | `mcp()` | — | `{ok, json}` — only the `mcp_servers` object as pretty JSON, never providers or keys |
169
+ | `saveMcp(request)` | `{json}` — raw JSON text, at most 64 KiB; stdio/remote entries are validated field by field | `{ok, count}` — writes only `mcp_servers`; other config is preserved |
170
+ | `auth()` | — | `{ok, output, loginCommand}` — read-only `ocr auth status --provider chatgpt`; sign-in itself stays a terminal action because it needs a browser and a local callback |
171
+ | `chatGpt(request)` | `{model}` | `{ok, model}` — sets `provider: "chatgpt"` and `providers.chatgpt.model`, writes no key |
172
+
173
+ Refusals answer `{ok: false, error, status}` where `status` is a **retained semantic code, not an HTTP status** (400 for an empty or off-list selection, 500 for a failed write or a missing credential script) — the number lets the tests pin which rule fired, and the client renders `error` only. There is deliberately no client-side wall clock on these calls: the timeout belongs to the gateway, and a second one in the card is how a slow write gets reported lost while it actually landed.
174
+
175
+ ## <img src="https://api.iconify.design/lucide/key-round.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Credentials and the OCR config file
176
+
177
+ | Aspect | Fact |
178
+ | --- | --- |
179
+ | What lands in the config | A command, not a secret: `api_key_cmd` = `node '<path of scripts/get-cred.mjs in this package>' '<REF>' '<dsh data dir>'` — single-quote escaped on POSIX, double-quote escaped on Windows (the CLI runs credential commands through `cmd.exe` there). The data directory is the host's current resolved home, so get-cred's fallback layers stay correct when `HOME` is redirected; the REF name must satisfy the official ref-name rule or the command is refused |
180
+ | Layer order | get-cred reads the same three layers in the same order as the official credentials-local: `refs.<REF>` in the managed credentials file first, then the inherited process environment, then `$DSH_HOME/.env`. The host treats the managed file as the effective credential, so a wrong order fails silently — OCR authenticates against a different key than the card reports while both sides show success |
181
+ | Reachability gate | select and migrate refuse a key the CLI cannot read at runtime: dsh strips `KEY`/`PASSWORD`/`SECRET`/`TOKEN`-named and `DSH_`-prefixed variables from spawned shells, and the reviewed repository's `.env` is deliberately not read. Keys living only in the dsh process environment or the workspace `.env` resolve on the host side yet fail at OCR runtime — previously a silent "select succeeded, OCR 401". The refusal happens before any write and names the fix |
182
+ | Writes | Atomic replacement through the official atomic-write helper: a random-suffixed temp sibling, then rename, with 0600 on the new inode; the `.bak` backup is copied by this package before the rename. The whole read→decide→write span runs under the official file lock — a short-lived `config.json.lock` appears and is removed in `finally`. An existing config that is invalid JSON or not an object aborts the write instead of being treated as empty |
183
+ | `migrate()` | Replaces the plaintext `api_key` of custom provider entries with `api_key_cmd` and deletes the plaintext; entries whose key source is unreachable at CLI runtime (same gate as select) or whose `apiKeyEnv` is missing from settings are left untouched and listed in `skippedUnknown`; nothing is written when nothing migrated |
184
+ | `scripts/get-cred.mjs` | Spawned by the CLI itself; the only place in this package that still reads host credential files. When all three layers miss it exits non-zero and names every location it checked |
185
+
186
+ ## <img src="https://api.iconify.design/lucide/hourglass.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Background runs as host jobs
187
+
188
+ | Aspect | Fact |
189
+ | --- | --- |
190
+ | What the model gains | `job_list` shows the review, `job_output` reads its stdout/stderr (non-consuming — it never steals bytes from the session reader), `job_kill` stops it. Results still come from the `ocr_session` record |
191
+ | No registry, no background | A host without the jobs service makes `wait: false` throw an error naming the missing piece instead of starting a subprocess nobody can observe; foreground runs are unaffected |
192
+ | The shared bucket | The unowned job slots are shared host-wide and overflow refuses new starts, so one hung CLI parks a slot forever. That is what the optional `ocrBackgroundMaxMs` backstop is for — it uses the registry's own wait + kill, not a host timer |
193
+ | Cleanup | Settled records of this kind are pruned down to a fixed window before each start; live and stopping records are never pruned (the registry answers overflow by refusing, not by killing somebody's review). At unload, live jobs are killed through the registry and settled ones removed |
194
+ | Exposure | Unowned means any caller can list / read / kill it. Known and accepted for this adoption; closing it would mean rolling the job registration back |
195
+ | Nothing may throw | An error raised inside a host event handler takes the whole host process down, and the official package does not cover producers either — the cancel chain catches at two layers, each pinned by its own test |
196
+
197
+ ## <img src="https://api.iconify.design/lucide/lock.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Data and privacy
198
+
199
+ | Aspect | Fact |
200
+ | --- | --- |
201
+ | Process boundary | The reviewed repository's paths and diff content go into the `ocr` child process, and the CLI sends them to the LLM endpoint configured in its own config.json — that egress is the review feature itself and does not pass through the dsh host. Plaintext keys never appear in tool results or Remote payloads; a value resolved by the host is used only to confirm "it resolves right now" and is discarded on the spot |
202
+ | Redaction | All raw CLI stdout/stderr leaving this package (failure details, llm test, parse-failure echoes, session passthrough) goes through `redactKeyMaterial()`: bearer and assignment forms strictly, the standalone-key form only with random-string features, so file paths handed to the model are not erased with it |
203
+ | On disk | Two places only: the CLI's `config.json` (plus its temp sibling, the `.bak` backup and the short-lived lock) and `ocr-review-*` / `ocr-scan-*` temp files, deleted right after reading. Pre-migration plaintext may persist in that `.bak` (mode 0600) — delete the backup yourself to be rid of it. Outside these two, the only writer is the CLI's own npm wrapper unless `ocrNoAutoUpdate` is on |
204
+
205
+ ## <img src="https://api.iconify.design/lucide/triangle-alert.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Known boundaries
206
+
207
+ - **Windows gets no reaper and no custom config path.** Both rest on a POSIX toolchain (bash traps, process-group semantics, the `HOME=` assignment prefix); on Windows the package runs the bare command un-reaped, and a hard host exit can leave an orphaned OCR process.
208
+ - **A version mismatch is never a hard failure.** A newer CLI usually works; both numbers are shown, the badge flips, and the summary's `hint` says so. This package never runs an installer.
209
+ - **Version reads cost a spawn** and never happen on render; the card shows the last measurement or nothing — a page render cannot install, update or probe anything.
210
+ - **The atomic-write lock timeout surfaces in English.** Contention past the official wait budget throws the official package's own timeout text — the one user-visible error here that bypasses the bilingual message table.
211
+ - **`partial` is a terminal success state.** Some files failed but coverage stands and the comments are valid; it is neither upgraded to success nor folded into failure.
212
+ - **Unowned background jobs are visible to every session** (see Background runs) — accepted with the adoption, and the only way to close it is to roll the registration back.
213
+
214
+ ## <img src="https://api.iconify.design/lucide/circle-help.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> FAQ
215
+
216
+ | Question / symptom | Answer |
217
+ | --- | --- |
218
+ | Exit 0 was taken as a successful review | Exit 0 is not success: any `status` outside success / complete / partial / completed_with_warnings / completed_with_errors / skipped reports as failure. `partial` means some files failed while coverage and the comments stand. A parse failure echoes the first 500 redacted UTF-16 code units of the raw output |
219
+ | Did the summary cover everything? | Two notions, neither replaces the other. `droppedCount` / `invalidCommentCount` say whether **this summary** listed every comment (raise `maxComments` or set 0 and re-check). Whether **the run** covered the selected files is `coverage` (`selected` is the denominator, `failedItems` names the files with their reasons) plus `budgetExceeded` and `toolCalls` |
220
+ | `add` was refused with `already-installed` | HMR profiles refuse `add` on an already-installed package before pnpm runs — `remove` first, then `add` the target version (see Install) |
221
+ | What happens to background processes when dsh exits? | The reaper guard takes the review/scan process tree down with TERM→1s→KILL on any host exit (including kill -9 followed by adoption); cancelling the tool call stops the corresponding background process |
222
+ | Where might a plaintext key still sit? | Nowhere this package writes. A pre-migration config's plaintext may survive in the `.bak` produced by the first write after you migrate (mode 0600); delete that backup to be rid of it |
223
+
224
+ ## <img src="https://api.iconify.design/lucide/wrench.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> Development
176
225
 
177
- | Aspect | Fact |
178
- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
179
- | Process boundary | The reviewed repository's paths and diff content go into the `ocr` child process, and OCR sends them to the LLM endpoint it has in its own config.json; that egress is the review feature itself and does not pass through the dsh host. Plaintext keys never appear in tool results or in the `ocrReview` payloads, and the value the host gets from `resolve()` is used only to confirm "it resolves right now" and is discarded on the spot |
180
- | Redaction of raw output | Raw OCR stdout/stderr (failure details, llm test, parse-failure echoes, session passthrough) all go through `redactKeyMaterial()` before leaving the host: bearer and assignment forms are redacted strictly, while the standalone-key form additionally demands random-string features so that file paths handed to the model are not erased as well |
181
- | Places written | This package writes to only two places: the external ocr CLI's `config.json` (plus its random-suffixed `.tmp`, the `.bak` backup, and the short-lived `config.json.lock` held only for the duration of one read-modify-write) and `ocr-review-*`/`ocr-scan-*` in the system temp directory (removed right after reading). Plaintext that predates a migration may still sit in the `.bak` produced by that same write (mode 0600); removing it for good means deleting that backup yourself. Writes outside those two places can still happen **inside the CLI's own wrapper**: unless `ocrNoAutoUpdate` is on, an `ocr` invocation may trigger upstream's global `npm i -g` of a newer release. This package never runs an installer itself, and the version probe always suppresses that path |
182
-
183
- ## FAQ
184
-
185
- | Symptom | Verdict |
186
- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
187
- | Exit 0 taken for a successful review | Exit 0 is not a successful review: any `status` outside success/complete/**partial**/completed_with_warnings/completed_with_errors/skipped is reported as failure (`{"error": …}` is of that kind; partial is one of the manifest terminal states — some files failed but coverage remains, and the comments still stand), and a parse failure echoes the first 500 redacted UTF-16 code units of the raw output (an emoji takes 2) |
188
- | Whether the summary covered everything | Two different notions, neither replaces the other: `droppedCount` and `invalidCommentCount` only say whether *this summary* listed every comment OCR produced (raise `maxComments`, or set 0, and re-check). Whether *the run* covered everything is in `coverage` (`selected` is the denominator, `completed`/`reused`/`failed`/`waived` partition it, `failedItems` names the files with their classification and reason) plus `budgetExceeded` (the token budget stopped it early — `status` still only says `partial`); `toolCalls` reports how many of the model's tool calls failed. stdout has its own 400000-byte cap, which is why review results always go through the `--output` temp file |
189
- | Background processes when dsh exits | When dsh exits in any way (including kill -9 followed by launchd adoption), the OCR process tree of review/scan is taken down by the reaper guard inside the command with TERM→1s→KILL; cancelling the tool call terminates the corresponding background process too |
190
-
191
- ## Development
226
+ ```sh
227
+ pnpm install
228
+ pnpm run check # typecheck (both sides) → lint → client build → host build → tests with coverage → format
229
+ ```
192
230
 
193
- - `npm run check` is the single gate to run before publishing: typecheck (both tsconfigs) + `oxlint` + rebuild both bundles + `npm test` (vitest with coverage) + `oxfmt --check`.
194
- - `npm test` runs with `--coverage` under a **100% global threshold** (lines/statements/branches/functions) — any line or branch not pinned by a test turns the suite red by design.
195
- - `npm run build` / `npm run build:client` produce the published `host.js` / `client.js`. After editing `host.ts`, `lib/*` or `src/*` they must be rebuilt (`test/build-host.test.ts` pins bundle freshness against the sources, so a stale bundle fails the suite). Never hand-edit the bundles.
231
+ - Coverage thresholds are **100%** across four metrics over the surface `vitest.config.ts` opts into (`coverageInclude`: `host.ts` + `lib/**`); two areas are deliberately outside it: the client half (`src/**`) is exercised through the bundle and the settings-card tests, and `scripts/get-cred.mjs` is driven by process-level tests spawning a child (v8 coverage cannot see a child process) — its behavioral gate lives in `test/get-cred.test.ts`.
232
+ - Adding this package's **local directory** to a profile (`pnpm add <path>`) needs pnpm ≥ 12.3.0: earlier pnpm 12 releases resolve an unaliased local path as a registry package name (upstream #14437, fixed in 12.3.0). Installing from the registry is unaffected.
233
+ - Bundle freshness is pinned by `test/build-host.test.ts`: a stale `host.js` / `client.js` fails the suite. Never hand-edit the bundles; `prepack` rebuilds them.
196
234
  - The plugin source is TypeScript loaded directly by the host's cordis loader (Node ≥ 22.18 type stripping); the bundles exist for the published npm surface.
197
235
 
198
- ## License
236
+ ## <img src="https://api.iconify.design/lucide/scale.svg?color=%23658EFF&height=22" height="22" width="22" align="absmiddle" alt="" /> License
237
+
238
+ MIT. Source at [github.com/JayYuen666/dsh-ocr-review](https://github.com/JayYuen666/dsh-ocr-review). Issues go to that repository's tracker.
199
239
 
200
- MIT — see [LICENSE](LICENSE).
240
+ Runtime dependencies carry their own licenses; [`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md) records that artifact boundary and how to re-check it.