dsh-auto-review 0.4.0

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.
Files changed (84) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +201 -0
  3. package/README.es.md +226 -0
  4. package/README.hi.md +226 -0
  5. package/README.md +226 -0
  6. package/README.pt.md +226 -0
  7. package/README.zh.md +226 -0
  8. package/cordis.patch.yml +27 -0
  9. package/lib/client.js +494 -0
  10. package/lib/client.js.map +1 -0
  11. package/lib/events-CFl6CHZi.js +344 -0
  12. package/lib/index.js +5305 -0
  13. package/lib/invariant.js +223 -0
  14. package/lib/types/client/ReviewPanel.d.ts +29 -0
  15. package/lib/types/client/ReviewPanel.d.ts.map +1 -0
  16. package/lib/types/client/ReviewPanel.js +63 -0
  17. package/lib/types/client/ReviewPanel.js.map +1 -0
  18. package/lib/types/client/index.d.ts +31 -0
  19. package/lib/types/client/index.d.ts.map +1 -0
  20. package/lib/types/client/index.js +51 -0
  21. package/lib/types/client/index.js.map +1 -0
  22. package/lib/types/client/locales.d.ts +49 -0
  23. package/lib/types/client/locales.d.ts.map +1 -0
  24. package/lib/types/client/locales.js +82 -0
  25. package/lib/types/client/locales.js.map +1 -0
  26. package/lib/types/client/present.d.ts +25 -0
  27. package/lib/types/client/present.d.ts.map +1 -0
  28. package/lib/types/client/present.js +36 -0
  29. package/lib/types/client/present.js.map +1 -0
  30. package/lib/types/client/styles.d.ts +9 -0
  31. package/lib/types/client/styles.d.ts.map +1 -0
  32. package/lib/types/client/styles.js +130 -0
  33. package/lib/types/client/styles.js.map +1 -0
  34. package/lib/types/config.d.ts +200 -0
  35. package/lib/types/config.d.ts.map +1 -0
  36. package/lib/types/config.js +154 -0
  37. package/lib/types/config.js.map +1 -0
  38. package/lib/types/events.d.ts +347 -0
  39. package/lib/types/events.d.ts.map +1 -0
  40. package/lib/types/events.js +369 -0
  41. package/lib/types/events.js.map +1 -0
  42. package/lib/types/index.d.ts +26 -0
  43. package/lib/types/index.d.ts.map +1 -0
  44. package/lib/types/index.js +26 -0
  45. package/lib/types/index.js.map +1 -0
  46. package/lib/types/invariant.d.ts +28 -0
  47. package/lib/types/invariant.d.ts.map +1 -0
  48. package/lib/types/invariant.js +306 -0
  49. package/lib/types/invariant.js.map +1 -0
  50. package/lib/types/messages.d.ts +38 -0
  51. package/lib/types/messages.d.ts.map +1 -0
  52. package/lib/types/messages.js +65 -0
  53. package/lib/types/messages.js.map +1 -0
  54. package/lib/types/projection-types.d.ts +61 -0
  55. package/lib/types/projection-types.d.ts.map +1 -0
  56. package/lib/types/projection-types.js +8 -0
  57. package/lib/types/projection-types.js.map +1 -0
  58. package/lib/types/projection.d.ts +93 -0
  59. package/lib/types/projection.d.ts.map +1 -0
  60. package/lib/types/projection.js +197 -0
  61. package/lib/types/projection.js.map +1 -0
  62. package/lib/types/review.d.ts +141 -0
  63. package/lib/types/review.d.ts.map +1 -0
  64. package/lib/types/review.js +389 -0
  65. package/lib/types/review.js.map +1 -0
  66. package/lib/types/runtime.d.ts +160 -0
  67. package/lib/types/runtime.d.ts.map +1 -0
  68. package/lib/types/runtime.js +486 -0
  69. package/lib/types/runtime.js.map +1 -0
  70. package/package.json +132 -0
  71. package/src/client/ReviewPanel.tsx +164 -0
  72. package/src/client/index.ts +72 -0
  73. package/src/client/locales.ts +87 -0
  74. package/src/client/present.ts +58 -0
  75. package/src/client/styles.ts +131 -0
  76. package/src/config.ts +346 -0
  77. package/src/events.ts +553 -0
  78. package/src/index.ts +28 -0
  79. package/src/invariant.ts +326 -0
  80. package/src/messages.ts +91 -0
  81. package/src/projection-types.ts +61 -0
  82. package/src/projection.ts +224 -0
  83. package/src/review.ts +428 -0
  84. package/src/runtime.ts +562 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,91 @@
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-auto-review` are documented here. The repo is pre-release; versions follow the DeepSeek Harness `0.1.0-rc.x` target runtime and bump on every behavior change.
4
+
5
+ ## [0.4.0] — 2026-08-15
6
+
7
+ ### Added
8
+
9
+ - **Hard-disable feedback**: a `never`-policy rejection (risk rule or tool-policy table entry) now records a log-only `autoReview/rejection` event (with the matched rule/entry as the reason and the correlated `approvalId`) and injects a `[auto-review-never]` marker text plus the deny guidance into the denied tool result — the model learns the action is hard-disabled instead of retrying it. The invariant companion validates the rejection chain (marker ⟺ event, one decision per `approval/asked`, `decided` agreement); the panel and `/auto-review status` count never rejects.
10
+ - `/auto-review status` reports a tripped circuit breaker (kind, count, action) when one is active in the turn.
11
+ - The web review panel's switch gains explicit on/off buttons (they execute `/auto-review on|off`).
12
+
13
+ ### Changed
14
+
15
+ - **Circuit-breaker defaults are now reachable**: `windowDenies` 10 → 6 and `windowSize` 50 → 10, so the window mode (6 of the last 10 verdicts) can trip under the default `maxReviewsPerTurn: 10` even without a 3-deny run (the old 10-in-50 window could never trip first). Explicit configs are unaffected.
16
+ - The projection unit is now built per mount (`makeAutoReviewProjection(enabledByDefault)`), so the panel's initial switch state follows the resolved `enableByDefault` instead of a hardcoded `true`; `stateVersion` bumped to 2 (also for the new `neverRejects` wire field).
17
+ - tsdown `external`/`noExternal` migrated to the non-deprecated `deps.neverBundle`/`deps.alwaysBundle`.
18
+ - Published on npm; the README install section now lists the npm channel first.
19
+
20
+ ### Fixed
21
+
22
+ - The panel's switch row no longer renders the localized "ON" text as its label (it now reads "State: ON/OFF").
23
+
24
+ ## [0.3.0] — 2026-08-14
25
+
26
+ ### Added
27
+
28
+ - **Web review panel**: a session-header action in the Web GUI showing the session's switch, both per-turn budgets, cumulative statistics, the circuit trip, recent verdicts, and one-shot approve buttons for recent denials (they execute `/auto-review approve [n]`).
29
+ - Host: an `autoReview` **session projection** (`src/projection.ts` + `src/projection-types.ts`) folds the log-only `autoReview/*` events into one wire-JSON value; it registers whenever the host provides the session-projection capability (the web profile does), so non-web mounts keep working unchanged.
30
+ - Browser: a **client module** (`dsh.client` declaration + `./client` export) registered on the `conversation.session.header.actions` seat; it reads only the projection whole value — the raw session event stream never reaches browser plugins.
31
+ - The browser bundle follows the shell's client-bundle handshake (`window.__ModuleLoader__.load`), with platform modules external and everything else inlined.
32
+ - `CHANGELOG.md` is now shipped in the tarball.
33
+
34
+ ## [0.2.0] — 2026-08-14
35
+
36
+ ### Breaking
37
+
38
+ - `fallbackPolicy: allow-readonly` is renamed `allow-once` (the grant is unconditional, never "readonly"); the old spelling is rejected loudly at load. Migration: rename the key.
39
+ - The shipped bundle patch no longer AI-reviews `edit` by default (`bash`/`write` remain); in-place modification now reaches the human chain unless configured explicitly.
40
+
41
+ ### Added
42
+
43
+ - **Risk-level policy** (`riskPolicy`): an `allow` verdict whose risk exceeds `maxAutoAllow` never settles the request — `onHighRisk: delegate` continues the chain, `deny` rejects. Recorded as `escalation: 'risk-policy'` on the verdict.
44
+ - **Rejection circuit breaker** (`circuitBreaker`): trips on `consecutiveDenies` consecutive denials or `windowDenies` within the last `windowSize` verdicts of a turn; later requests `delegate`, `reject` (auditable `[auto-review-circuit]` feedback), or `abort-turn` (warning injected + agent cancelled). Recorded as a log-only `autoReview/circuit` event, once per turn.
45
+ - **One-shot human override**: `/auto-review approve [n]` records a single-use `autoReview/override` for the n-th most recent denial; the next same-tool review within `overrideTtlMs` carries the authorization as reviewer context.
46
+ - **Compact reviewer transcript** (`contextBudget`): the reviewer sees a bounded tail of the session's presented messages and tool results.
47
+ - **Ruling policy text** (`reviewerPolicyText`): Codex-style Markdown policy injected into the reviewer prompt (template at `fixtures/config/policy-template.md`).
48
+ - **Anti-circumvention deny guidance** (`denyGuidance`) appended to every injected deny reason.
49
+ - **Risk-rule fields**: `riskRules[].field` selects `reason` (default) | `toolName` | `arguments` (redacted presented call arguments).
50
+ - `/auto-review status` reports cumulative session statistics (allows/denies/fallbacks, mean duration, recent verdicts).
51
+ - Provider capability precheck (`outputSchema`/`toolFilter`) fails with a clear message instead of a generic start rejection; `reviewerTools: []` fails loud at load.
52
+ - UI language config (`language: 'en' | 'zh'`) for the `/auto-review` command output.
53
+
54
+ ### Fixed
55
+
56
+ - Fallback-policy switch and docs now use the honest `allow-once` naming.
57
+
58
+ ## [0.1.2] — 2026-08-14
59
+
60
+ ### Fixed
61
+
62
+ - **Failure-classification race**: a timeout or user cancellation surfaced as a subagent start/run rejection (e.g. the fork driver's pre-publication abort) is now classified `timeout` / `cancelled` instead of the generic `unavailable`, keeping `autoReview/verdict.outcome` consistent with the service's `approval/decided`.
63
+ - **Invariant gaps closed**: the companion now enforces **one verdict per `approval/asked`** and **verdict/`decided` outcome agreement** (previously claimed in JSDoc but not implemented), and validates the new fallback marker.
64
+ - **Per-turn budget split**: `maxReviewsPerTurn` now counts real AI verdicts only; the new `maxFailuresPerTurn` budgets reviewer failures separately, so a broken reviewer no longer eats the AI-decision budget (and stops being retried after the failure budget is spent).
65
+ - **Request reason hygiene**: the request `reason` is truncated to `reasonMaxChars` before entering the reviewer prompt (it is also labeled as the calling agent's self-report, evidence only).
66
+
67
+ ### Added
68
+
69
+ - **Fail-closed feedback**: a fallback rejection now injects an auditable failure text (`[auto-review-fallback]` marker, reviewId-linked) into the denied tool result, so the agent learns why it was rejected instead of retrying the same escalation blindly.
70
+ - `/auto-review status` reports both per-turn budgets (AI verdicts and reviewer failures).
71
+ - CI workflow (`typecheck`/`test`/`build`/`verify`/`pack`) plus a host-version watch that fails when the exact-pinned `@deepseek-ai/dsh-*` peers lag the npm `latest`.
72
+
73
+ ### Changed
74
+
75
+ - Removed stale demo probe scripts and capture artifacts; the tests badge is now a live GitHub Actions badge.
76
+
77
+ ## [0.1.1]
78
+
79
+ ### Added
80
+
81
+ - `autoReview/state` and `autoReview/verdict` are appended with the envelope's `ignorable: true` marker so any harness build can load the log.
82
+
83
+ ### Changed
84
+
85
+ - Git-install channel hardening: repo-shipped `pnpm-workspace.yaml` declares `allowBuilds: { esbuild: true }` for the isolated prepare environment.
86
+
87
+ ## [0.1.0]
88
+
89
+ ### Added
90
+
91
+ - Initial release: `approval/request` answerer with second-model read-only reviewer subagent, structured verdict schema, fail-closed fallback, anti-recursion, per-tool/risk-rule policy routing, deny-reason feedback, session-log audit (`autoReview/verdict`), invariant companion, and the `/auto-review` session command.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.es.md ADDED
@@ -0,0 +1,226 @@
1
+ <!-- enlaces de idioma -->
2
+ [English](README.md) · [中文](README.zh.md) · [Español](README.es.md) · [Português](README.pt.md) · [हिन्दी](README.hi.md)
3
+
4
+ <div align="center">
5
+
6
+ # 🤖 dsh-auto-review
7
+
8
+ **Aprobación automática por segundo modelo para DeepSeek Harness** — el patrón `approvals_reviewer=auto_review` de Codex / *auto mode* de Claude Code, implementado como un plugin puro de Cordis.
9
+
10
+ Cuando una acción del agente cruza el límite del sandbox, un **subagente revisor de solo lectura** decide allow/deny — con un motivo — para que los humanos no aprueben nada mientras nada inseguro se cuela.
11
+
12
+ [![license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
13
+ [![dsh](https://img.shields.io/badge/dsh-0.1.0--rc.6-4c51bf.svg)](https://www.npmjs.com/package/@deepseek-ai/dsh)
14
+ [![tests](https://img.shields.io/github/actions/workflow/status/PerryLink/dsh-auto-review/ci.yml?label=tests&logo=githubactions)](.github/workflows/ci.yml)
15
+ [![typescript](https://img.shields.io/badge/TypeScript-strict-3178c6.svg)](src)
16
+ [![type](https://img.shields.io/badge/type-cordis%20bundle-8a5cf6.svg)](cordis.patch.yml)
17
+ [![repo](https://img.shields.io/badge/repo-PerryLink%2Fdsh--auto--review-181717.svg)](https://github.com/PerryLink/dsh-auto-review)
18
+
19
+ **Cero operaciones humanas.** La petición va al revisor de IA, el veredicto es allow/deny + motivo + nivel de riesgo, y cada decisión se puede reconstruir desde el registro de sesión: `approval/asked` → `autoReview/verdict` (o `autoReview/rejection` para desactivaciones duras) → `approval/decided`.
20
+
21
+ <img src="docs/demo-auto-review.gif" alt="demo de dsh-auto-review" width="720"/>
22
+
23
+ *Una ejecución real de evidencia (servidor real, clave de API real, dos rondas de modelo reales): el revisor de IA **permite** una escritura con escalado dentro del workspace (riesgo bajo, 5,2 s) y luego **deniega** un borrado recursivo fuera del workspace (riesgo alto, 8,9 s) — el motivo de la denegación se devuelve al modelo, visible en la transcripción.*
24
+
25
+ </div>
26
+
27
+ ## ¿Por qué un segundo modelo en lugar de reglas?
28
+
29
+ Los auto-aprobadores basados en patrones deciden antes del despacho, sin evidencia. `dsh-auto-review` entrega la decisión a un **subagente revisor** que lee el workspace real (con su cara de herramientas de solo lectura), los argumentos de la llamada ya presentados (valores sensibles redactados), el motivo de la petición y tus reglas de riesgo — y devuelve un veredicto estructurado. Un veredicto de denegación devuelve su **motivo al modelo que llama**, para que el agente aprenda el porqué en lugar de reintentar a ciegas.
30
+
31
+ ## ✨ Características
32
+
33
+ | | |
34
+ |---|---|
35
+ | 🔌 **Seam oficial** | Un answerer en el waterfall `approval/request`. Las peticiones que no le pertenecen se delegan con `next()` — el flujo de aprobación humana nunca se corta. |
36
+ | 🧠 **Veredicto de segundo modelo** | Subagente fork de un solo uso con lista blanca de herramientas de solo lectura (`read`/`glob`/`grep`) y esquema de veredicto estructurado `{ decision, reason, riskLevel }`. |
37
+ | 🛡️ **Fail closed** | Un fallo, timeout o esquema inválido del revisor nunca abre la puerta: se aplica `fallbackPolicy`, por defecto `rejected`. |
38
+ | 🧩 **Enrutado por configuración** | Políticas por herramienta (`ai`/`human`/`never`) + reglas de riesgo con regex, todo cambiable desde cordis.yml. |
39
+ | 💬 **Los motivos de denegación llegan al modelo** | El motivo del revisor se inyecta en el resultado de la herramienta denegada (vinculado por callId), para que el agente se adapte. Las denegaciones del fallback fail-closed y las desactivaciones duras de la política `never` también inyectan textos auditables (marcadores `[auto-review]` / `[auto-review-fallback]` / `[auto-review-never]`). |
40
+ | 📜 **Auditoría completa** | Eventos de sesión `autoReview/verdict` + `autoReview/rejection` (identidad del revisor, veredicto, motivo, riesgo, duración) + un companion de invariantes que exige *model-visible ⟺ logged*. |
41
+ | 🔁 **Sin recursión** | Las peticiones del propio revisor se reconocen por identidad y se delegan; `maxDepth` + la lista blanca mantienen al revisor sin delegar. |
42
+ | 🧯 **Disyuntor de rechazos** | 3 denegaciones consecutivas (o 6 dentro de los últimos 10 veredictos) en un turno disparan el disyuntor: las peticiones posteriores delegan, rechazan o abortan el turno — sin bucles de denegación interminables. |
43
+ | 🎚️ **Política por nivel de riesgo** | Un veredicto `allow` cuyo riesgo supera `riskPolicy.maxAutoAllow` nunca resuelve la petición: la delega a un humano o la deniega. |
44
+ | ✋ **Anulación humana de un solo uso** | `/auto-review approve [n]` autoriza UN reintento de una denegación reciente; la siguiente revisión de la misma herramienta lleva esa autorización como contexto del revisor (el revisor sigue decidiendo). |
45
+ | 📜 **Contexto del revisor** | Transcripción compacta opcional (mensajes recientes y resultados de herramientas, acotada) + una política de decisión `reviewerPolicyText` en Markdown estilo Codex. |
46
+ | ⌨️ **Comando de sesión** | `/auto-review on|off|status|approve [n]` con una anulación duradera por sesión que sobrevive a la restauración y estadísticas acumuladas de sesión. |
47
+ | 🖥️ **Panel de revisión web** | Un panel en la cabecera de sesión (GUI web) muestra el interruptor (con botones de encendido/apagado), ambos presupuestos por turno, estadísticas acumuladas, el disparo del disyuntor, veredictos recientes y botones de aprobación de un solo uso — impulsado por la proyección de sesión `autoReview`. |
48
+
49
+ ## Cómo funciona
50
+
51
+ ```text
52
+ waterfall approval/request (cadena de answerers)
53
+ │
54
+ ┌───────────────────────┴──────────────────────┐
55
+ │ answerer dsh-auto-review │
56
+ │ · ¿sesión activada? · ¿política = ai? │ no ── next() ──▶ answerer humano (UI)
57
+ │ · reglas de riesgo → toolsPolicy → defecto │
58
+ └───────────────────────┬──────────────────────┘
59
+ │ sí
60
+ ▼
61
+ ┌───────────────────────────────────┐
62
+ │ subagente revisor (fork, un uso) │
63
+ │ · toolFilter: read/glob/grep │
64
+ │ · outputSchema: {decision, │
65
+ │ reason, riskLevel} │
66
+ │ · timeout + abort de req.signal │
67
+ └───────────────┬───────────────────┘
68
+ │ veredicto / fallo (fallback fail-closed)
69
+ ▼
70
+ allow → allowed-once deny → rejected + motivo inyectado en el
71
+ resultado de la herramienta denegada
72
+ │ never → rejected + feedback [auto-review-never]
73
+ │ (desactivación dura, sin revisor)
74
+ ▼
75
+ auditoría: approval/asked → autoReview/verdict | autoReview/rejection
76
+ → approval/decided (eventos de sesión, log-only, verificados por invariantes)
77
+ ```
78
+
79
+ **Orden de composición.** El contestador se ejecuta en su posición de registro dentro del waterfall: si un contestador humano de la UI está compuesto ANTES de la fila `auto-review`, los humanos responden primero y el revisor solo ve lo que se delega aguas abajo. Verifícalo con `dsh --profile <name> --dump-config` y coloca la fila `auto-review` antes de tus filas de contestadores humanos si quieres que las herramientas con política ai se enruten primero al revisor.
80
+
81
+ ## 🚀 Inicio rápido
82
+
83
+ Cuatro canales de instalación; el plugin es un **bundle** (`"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }`).
84
+
85
+ ```sh
86
+ # 1. npm (artefacto publicado, sin paso de build)
87
+ dsh plugin --profile web add dsh-auto-review
88
+ dsh --profile web # reiniciar
89
+
90
+ # 2. tarball de npm (artefactos compilados, instalación offline)
91
+ pnpm pack # → dsh-auto-review-<version>.tgz
92
+ dsh plugin --profile web add ./dsh-auto-review-<version>.tgz
93
+ dsh --profile web # reiniciar
94
+
95
+ # 3. fuente git (fija el commit; el `prepare` autocontenido lo compila)
96
+ # pnpm ≥ 10 bloquea los builds de ciclo de vida: añade primero la clave
97
+ # allowBuilds impresa al pnpm-workspace.yaml del perfil.
98
+ dsh plugin --profile web add "github:PerryLink/dsh-auto-review#<commit>"
99
+
100
+ # 4. enlace local (desarrollo)
101
+ dsh plugin --profile web add link:/path/to/dsh-auto-review
102
+ ```
103
+
104
+ Verifica:
105
+
106
+ ```sh
107
+ dsh --profile web --dump-config | grep -A4 'id: auto-review'
108
+ ```
109
+
110
+ De serie, el patch enviado somete `bash` y `write` a revisión de IA; el resto de herramientas (incluido `edit` — modificación in situ) se delega a la cadena humana. Añade `edit: ai` explícitamente si aceptas ediciones in situ sin un humano en el bucle.
111
+
112
+ ## ⚙️ Configuración
113
+
114
+ Todos los parámetros son campos `Config` de Schemastery (cambiables desde cordis.yml). Una anulación dirigida por `id` **reemplaza toda la fila de config** — repite toda clave que necesites.
115
+
116
+ | Clave | Defecto | Significado |
117
+ |---|---|---|
118
+ | `enableByDefault` | `true` | Las sesiones arrancan con auto-review activado; `/auto-review on\|off` escribe una anulación duradera con prioridad |
119
+ | `toolsPolicy.default` | `human` | Política para herramientas no listadas (delegar al answerer humano) |
120
+ | `toolsPolicy.overrides` | `{}` | Política por herramienta: `ai` (decide el revisor), `human` (forzar humano), `never` (rechazo determinista) |
121
+ | `riskRules` | `[]` | `{pattern, policy, field?}` emparejado (gana la primera coincidencia) antes de la tabla de herramientas; `field` selecciona `reason` (por defecto), `toolName` o `arguments` (los argumentos de llamada presentados redactados) |
122
+ | `reviewerProvider` | `fork` | Provider de subagente para el revisor (backend fork en proceso) |
123
+ | `reviewerModel` | *(heredar)* | Id del modelo del revisor; sin valor hereda la ruta del agente de sesión |
124
+ | `reviewerTimeoutMs` | `60000` | Plazo del veredicto; al vencer se aplica la política de fallback |
125
+ | `reviewerTools` | `[read, glob, grep]` | Lista blanca de herramientas del hijo revisor (no debe estar vacía) — todo lo demás es invisible allí |
126
+ | `fallbackPolicy` | `rejected` | Ante fallo del revisor: `rejected` (fail closed), `delegate` (continúa la cadena), `allow-once` (concede — ver Seguridad). Renombrado desde `allow-readonly` en 0.2.0; la grafía antigua falla en voz alta |
127
+ | `maxReviewsPerTurn` | `10` | Presupuesto real de veredictos de IA por turno abierto; agotado, se delega a humanos |
128
+ | `maxFailuresPerTurn` | `10` | Presupuesto de fallos del revisor por turno abierto (timeout/no disponible/schema, no cancelaciones); agotado, las peticiones se delegan en lugar de pagar otro timeout completo. Por defecto, `maxReviewsPerTurn` |
129
+ | `reasonMaxChars` | `2000` | Tope para los motivos del revisor, el motivo de la petición y la vista previa de argumentos redactada |
130
+ | `reviewerGuidance` | *(ninguna)* | Guía opcional añadida al prompt del revisor (consultiva, no regla dura) |
131
+ | `reviewerPolicyText` | *(ninguna)* | Política de decisión en Markdown inyectada en el prompt del revisor (estilo Codex; plantilla en `fixtures/config/policy-template.md`) |
132
+ | `denyGuidance` | *(texto anti-elusión)* | Guía añadida a cada motivo de denegación inyectado |
133
+ | `contextBudget` | `{turns: 0, maxChars: 4000}` | Presupuesto de transcripción compacta para el prompt del revisor; `turns: 0` lo desactiva |
134
+ | `riskPolicy` | `{maxAutoAllow: high, onHighRisk: delegate}` | Los veredictos `allow` por encima de `maxAutoAllow` delegan (`delegate`) o deniegan (`deny`) |
135
+ | `circuitBreaker` | `{consecutiveDenies: 3, windowDenies: 6, windowSize: 10, action: delegate}` | Disyuntor de rechazos; se dispara con 3 denegaciones consecutivas o 6 de los últimos 10 veredictos del turno; `action`: `delegate` / `reject` / `abort-turn` |
136
+ | `overrideTtlMs` | `300000` | Cuánto tiempo una anulación `/auto-review approve` sigue siendo utilizable |
137
+ | `language` | `en` | Idioma de la interfaz de la salida del comando `/auto-review` (`en` \| `zh`) |
138
+
139
+ Ejemplo (forma completa comentada: `fixtures/config/config-full.yaml`):
140
+
141
+ ```yaml
142
+ - insert:
143
+ - id: auto-review
144
+ name: dsh-auto-review
145
+ config:
146
+ toolsPolicy:
147
+ overrides: { bash: ai, write: ai }
148
+ riskRules:
149
+ - pattern: '(?i)(rm\s+(-[a-z]+\s+)*/|git\s+push\s+--force)'
150
+ policy: never
151
+ - pattern: 'write'
152
+ policy: never
153
+ field: toolName
154
+ reviewerTimeoutMs: 30000
155
+ fallbackPolicy: delegate
156
+ riskPolicy: { maxAutoAllow: medium, onHighRisk: delegate }
157
+ circuitBreaker: { consecutiveDenies: 3, windowDenies: 6, windowSize: 10, action: delegate }
158
+ ```
159
+
160
+ ## ⌨️ Comando de sesión
161
+
162
+ ```
163
+ /auto-review on|off|status|approve [n]
164
+ ```
165
+
166
+ `on`/`off` añaden la anulación duradera `autoReview/state` (el fold sobrevive a reinicios/restauración — la reproducción ES el estado) e inyectan un aviso de cambio visible para el modelo (registrado como evento `user/message`). `status` muestra el estado efectivo, ambos presupuestos por turno (veredictos de IA y fallos del revisor), un disyuntor disparado cuando hay uno activo en el turno y las estadísticas acumuladas de la sesión (permisos/denegaciones/fallos/desactivaciones duras, duración media, veredictos recientes). `approve [n]` registra una `autoReview/override` de un solo uso para la n-ésima denegación más reciente (1 = la más reciente): la siguiente revisión de la misma herramienta dentro de `overrideTtlMs` lleva la autorización como contexto del revisor — el revisor sigue decidiendo, y la anulación se consume con esa revisión independientemente de su resultado.
167
+
168
+ ## 🖥️ Panel de revisión web
169
+
170
+ En la GUI web (perfil web), el paquete aporta una acción en la cabecera de sesión (**AI Review**) que abre un panel con el estado de auto-revisión de la sesión: el interruptor con botones de encendido/apagado (ejecutan `/auto-review on|off`), ambos presupuestos por turno, estadísticas acumuladas (incluidas las desactivaciones duras), el disparo del disyuntor, los veredictos recientes y botones de **aprobación** de un solo uso para denegaciones recientes (ejecutan `/auto-review approve [n]`).
171
+
172
+ Cómo está cableado:
173
+
174
+ - El host registra una **proyección de sesión** `autoReview` (plegada desde los eventos log-only `autoReview/*`) y la sirve a través del canal de proyección de sesión.
175
+ - La mitad navegador es un **módulo cliente** (auto-descubierto desde la declaración `dsh.client`) registrado en el asiento `conversation.session.header.actions`.
176
+ - No hacen falta filas de patch adicionales: el panel carga siempre que el plugin esté instalado en un perfil cuya compilación web ofrece la capacidad de proyección de sesión (el perfil web lo hace). Sin esa capacidad el panel se declara no disponible; el contestador no se ve afectado.
177
+
178
+ El panel solo lee valores de proyección completos — nunca recibe el flujo crudo de eventos de sesión.
179
+
180
+ ## 🔒 Seguridad
181
+
182
+ - El revisor corre con una **cara de herramientas de solo lectura** (lista blanca `toolFilter`). No puede escribir, editar, ejecutar shell, acceder a la red ni delegar (`maxDepth` = su propia profundidad). Su registro de sesión persiste y es auditable.
183
+ - **Los argumentos sensibles se redactan** (coincidencia por nombre de clave: `token`, `password`, `api_key`, `Authorization`, credenciales, claves privadas …) antes de entrar en el prompt del revisor; el plugin nunca ejecuta los argumentos revisados. La redacción es por clave, no por contenido — no sometas a revisión de IA herramientas cuyos valores no puedas mostrar a un modelo.
184
+ - **Fail closed por defecto.** Toda ruta anómala (provider ausente, brechas de capacidad, arranque rechazado, timeout, stopReason no `completed`, veredicto ausente/malformado, fallo de correlación de auditoría) se resuelve con `fallbackPolicy`, por defecto `rejected` — y la denegación devuelve un motivo auditable al modelo en lugar del texto genérico "user rejected". `allow-once` concede incondicionalmente — solo existe para despliegues desatendidos cuyo administrador acepta ese riesgo.
185
+ - **Las desactivaciones duras se explican solas.** Una herramienta o regla de riesgo `never` rechaza de forma determinista Y registra un evento log-only `autoReview/rejection` con la regla/entrada que coincidió, e inyecta un texto con el marcador `[auto-review-never]` en el resultado de la herramienta denegada — el modelo aprende que la acción está desactivada en lugar de reintentarla (verificado por invariantes: marcador ⟺ evento).
186
+ - **Disyuntor de rechazos.** Una racha de denegaciones en un turno dispara el disyuntor (`consecutiveDenies` / `windowDenies` dentro de `windowSize`), registrado como evento log-only `autoReview/circuit`; las peticiones posteriores siguen su `action` (`delegate` / `reject` / `abort-turn`). `abort-turn` inyecta una advertencia visible para el modelo y cancela al agente.
187
+ - **El contexto del revisor es transcripción ya presentada.** `contextBudget` alimenta al revisor con contenido de sesión ya presentado (mensajes, resultados de herramientas). Con el modelo de revisor por defecto en la misma ruta, ese contenido permanece dentro de un único provider; configura `reviewerModel` con un provider diferente solo si aceptas presentarle esa transcripción.
188
+ - **`never` es unidireccional en esta capa.** Una herramienta o regla de riesgo `never` rechaza antes de que la cadena humana vea la petición — es un candado, no un valor por defecto.
189
+ - **El revisor es un modelo.** Sus veredictos son política consultiva, no un kernel de seguridad. Prefiere reglas `human`/`never` para operaciones irreversibles.
190
+
191
+ ## ⚠️ Limitaciones conocidas
192
+
193
+ - El revisor necesita una ruta LLM operativa (heredada del agente de sesión por defecto); sin ella, cada revisión cae al `fallbackPolicy` — nunca una concesión silenciosa.
194
+ - Los nombres de `reviewerTools` deben existir como herramientas globales del perfil; un nombre desconocido hace fallar al hijo revisor en voz alta en el punto más temprano y cae al fallback.
195
+ - Las reglas de riesgo emparejan el `reason` de la petición, el `toolName` o los `arguments` redactados de la llamada según su `field`; las demás condiciones van en `toolsPolicy.overrides`.
196
+ - La anulación `/auto-review approve` autoriza la siguiente revisión de la misma herramienta, no la llamada histórica exacta; una acción distinta sobre la misma herramienta la consume.
197
+ - Los eventos de veredicto son log-only; el panel de revisión web dedicado lee la proyección plegada `autoReview` (el flujo crudo de eventos nunca llega a los plugins del navegador).
198
+ - `autoReview/state` y `autoReview/verdict` se escriben con el marcador de envoltura `ignorable: true`, de modo que cualquier build del harness carga el registro: los lectores que no conocen los tipos fuera del repositorio simplemente omiten esos eventos en lugar de rechazar la sesión. (Los hosts rc.6 aceptan e ignoran el marcador, conservando exactamente el comportamiento anterior; las sesiones escritas por versiones anteriores a 0.1.1 pueden repararse con `scripts/repair-session-logs.mjs` de `dsh-permission-rules`.)
199
+ - El canal git solo necesita la clave `allowBuilds` que imprime el CLI `dsh` para `dsh-auto-review`. El repo trae su propio `pnpm-workspace.yaml` con `allowBuilds: { esbuild: true }` para que el entorno de prepare aislado no falle por el postinstall de esbuild (validación inofensiva del binario de plataforma); `typescript` + `tsdown` son `dependencies` regulares para que ese entorno siempre tenga las herramientas de build.
200
+ - El companion de invariantes opcional (`dsh-auto-review/invariant`) necesita el servicio `invariants` (composiciones agent-spine como headless/ACP); el perfil web simple no lo proporciona, por eso la fila se publica comentada en el patch del bundle.
201
+
202
+ ## 🏷️ Topics de GitHub
203
+
204
+ Recomendados al publicar: `dsh` · `dsh-plugin` · `deepseek-harness` · `deepseek` · `cordis` · `ai-safety` · `approval` · `sandbox` · `subagent` · `llm`
205
+
206
+ ## 🔗 Trabajo relacionado
207
+
208
+ - [Andy8647/dsh-auto-approval](https://github.com/Andy8647/dsh-auto-approval) — clasificador binario allow/deny en el waterfall `tools/pre-execute` con auditoría en archivo de log. `dsh-auto-review` difiere a propósito: cadena de **answerers** oficial, siempre delega lo que no posee, segundo modelo de solo lectura con veredicto estructurado, motivos de denegación devueltos al modelo, auditoría en el registro de sesión.
209
+ - [ACP automation bridge](https://github.com/deepseek-ai/deepseek-harness/tree/master/packages/acp/acp) — decisiones de máquina de un solo uso para sus propios agentes ACP. `dsh-auto-review` está orientado a sesiones y políticas de herramientas del harness interactivo; nunca infiere concesiones duraderas.
210
+
211
+ ## 🧑‍💻 Desarrollo
212
+
213
+ ```sh
214
+ pnpm install # node ^22.19 || >=24
215
+ pnpm run typecheck # tsc, src + tests
216
+ pnpm test # vitest: 135 tests, 8 suites
217
+ pnpm run build # declaraciones tsc + bundles tsdown (lib/)
218
+ pnpm run verify:self-contained
219
+ pnpm pack # artefacto de publicación
220
+ ```
221
+
222
+ Estructura del repositorio (estructura plugin-template): `src/index.ts` (contrato del plugin) · `src/config.ts` (esquema Schemastery + resolución) · `src/runtime.ts` (answerer, comando, inyección del motivo de denegación) · `src/review.ts` (orquestación del revisor, prompt, redacción) · `src/events.ts` (vocabulario de eventos de sesión + folds) · `src/projection.ts` + `src/projection-types.ts` (la proyección de sesión `autoReview`) · `src/invariant.ts` (companion de invariantes) · `src/client/` (mitad navegador: panel de revisión, locales, estilos) · `test/` · `fixtures/`.
223
+
224
+ ## 📄 Licencia
225
+
226
+ [Apache License 2.0](LICENSE)