@open-cr-agent/vcs-platform 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,202 @@
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.
202
+
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @open-cr-agent/vcs-platform
2
+
3
+ What the code review platform adapters of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer, share: the summary comment and the review state it carries, the text of inline comments, and the rules for who may override, dismiss or answer ocra. Most users want [`@open-cr-agent/cli`](https://www.npmjs.com/package/@open-cr-agent/cli), which provides the `ocra` command and installs this package; see the [manual](https://ocra.majincheng.com). All `@open-cr-agent` packages are released together at one version. Apache-2.0.
@@ -0,0 +1,6 @@
1
+ export * from "./platform.js";
2
+ export * from "./render.js";
3
+ export * from "./retry.js";
4
+ export * from "./review.js";
5
+ export * from "./state.js";
6
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./platform.js";
2
+ export * from "./render.js";
3
+ export * from "./retry.js";
4
+ export * from "./review.js";
5
+ export * from "./state.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ import type { Finding, ReviewReport } from "@open-cr-agent/core";
2
+ import type { PlatformText } from "./render.js";
3
+ export interface ReviewPlatform {
4
+ readonly text: PlatformText;
5
+ bot(): Promise<Bot>;
6
+ changeRequest(): Promise<PlatformChangeRequest>;
7
+ comments(): Promise<PlatformComment[]>;
8
+ editor(comment: PlatformComment): Promise<string | undefined>;
9
+ canWrite(login: string): Promise<boolean>;
10
+ threads(): Promise<PlatformThread[]>;
11
+ publishFindings(report: ReviewReport, fresh: readonly InlineFinding[]): Promise<PublishedFindings>;
12
+ writeSummary(existing: PlatformComment | undefined, body: string): Promise<void>;
13
+ resolveThread(id: string): Promise<void>;
14
+ }
15
+ export interface Bot {
16
+ login: string;
17
+ is(login: string): boolean;
18
+ }
19
+ export interface PlatformChangeRequest {
20
+ id: string;
21
+ title: string;
22
+ description: string;
23
+ baseSha: string;
24
+ headSha: string;
25
+ author?: string;
26
+ }
27
+ export interface PlatformComment {
28
+ id: string;
29
+ author?: string;
30
+ body: string;
31
+ }
32
+ export interface PlatformThread {
33
+ id: string;
34
+ resolved: boolean;
35
+ resolvedBy?: string;
36
+ comments: {
37
+ author: string;
38
+ body: string;
39
+ editor?: string;
40
+ }[];
41
+ }
42
+ export interface InlineFinding {
43
+ finding: Finding & {
44
+ lineRange: NonNullable<Finding["lineRange"]>;
45
+ };
46
+ body: string;
47
+ }
48
+ export interface PublishedFindings {
49
+ posted: string[];
50
+ warnings: string[];
51
+ finish?: () => Promise<string[]>;
52
+ }
53
+ //# sourceMappingURL=platform.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=platform.js.map
@@ -0,0 +1,19 @@
1
+ import { type Finding, type ReviewReport } from "@open-cr-agent/core";
2
+ import { type ReviewState } from "./state.js";
3
+ export interface PlatformText {
4
+ changeRequest: string;
5
+ authority: string;
6
+ }
7
+ export declare function safeMarkdown(text: string): string;
8
+ export declare function codeSpan(text: string): string;
9
+ export declare const FINDING_MARKER: RegExp;
10
+ export declare function inlineBody(f: Finding): string;
11
+ export interface SummaryInput {
12
+ report: ReviewReport;
13
+ commented: ReadonlySet<string>;
14
+ state: ReviewState;
15
+ text: PlatformText;
16
+ unattributed?: number;
17
+ }
18
+ export declare function renderSummary({ report, commented, state, text, unattributed, }: SummaryInput): string;
19
+ //# sourceMappingURL=render.d.ts.map
package/dist/render.js ADDED
@@ -0,0 +1,201 @@
1
+ import { coverageGaps, } from "@open-cr-agent/core";
2
+ import { SUMMARY_MARKER, writeState } from "./state.js";
3
+ // GitHub rejects comments over 65,536 characters; GitLab takes 1,000,000,
4
+ // but a summary that long is no use to anyone.
5
+ const MAX_SUMMARY_CHARS = 65_000;
6
+ const ICON = { critical: "🔴", warning: "🟠", suggestion: "🔵" };
7
+ const VERIFICATION = {
8
+ confirmed: "verified",
9
+ uncertain: "unverified (verifier unsure)",
10
+ unchecked: "not verified",
11
+ };
12
+ // A run that reviewed nothing has no verdict to announce, and one that missed
13
+ // files or could not verify a critical finding says so next to its verdict.
14
+ function headline(report) {
15
+ const { notReviewed, nothingReviewed } = coverageGaps(report);
16
+ if (nothingReviewed)
17
+ return "⏸️ Not reviewed";
18
+ const incomplete = notReviewed > 0 || report.unverifiedCriticals > 0;
19
+ const overridden = report.verdict === "significant_concerns" && report.changeRequest.override
20
+ ? " · overridden"
21
+ : "";
22
+ return `${VERDICT[report.verdict]}${overridden}${incomplete ? " · incomplete" : ""}`;
23
+ }
24
+ // Who overrode a blocking verdict, or how someone entitled to can.
25
+ function overrideNote(report, text) {
26
+ if (report.verdict !== "significant_concerns")
27
+ return [];
28
+ const override = report.changeRequest.override;
29
+ if (override) {
30
+ return [
31
+ "",
32
+ `**Overridden** by @\u200b${safeMarkdown(override.by)} for ${codeSpan(report.changeRequest.headSha.slice(0, 7))}: ${safeMarkdown(override.reason)}`,
33
+ ];
34
+ }
35
+ return [
36
+ "",
37
+ `Someone with ${text.authority} other than the author can let this commit pass by commenting \`/ocra override ${report.changeRequest.headSha} <reason>\`.`,
38
+ ];
39
+ }
40
+ function spendLimitNote(report) {
41
+ const limit = report.spendLimit;
42
+ if (!limit)
43
+ return "";
44
+ return ` of a $${limit.usd} limit${limit.reached ? ", reached" : ""}`;
45
+ }
46
+ function verification(f) {
47
+ return VERIFICATION[f.verification ?? "unchecked"];
48
+ }
49
+ const VERDICT = {
50
+ approved: "✅ Approved",
51
+ approved_with_comments: "💬 Approved with comments",
52
+ minor_issues: "⚠️ Minor issues",
53
+ significant_concerns: "🛑 Significant concerns",
54
+ };
55
+ // Model text is untrusted: it may not close our markup, mention people,
56
+ // pull in images, spell one of ocra's commands (`/ocra …`, which would count
57
+ // if ocra posted as a person with write access), start a line with a slash
58
+ // (GitLab runs a line such as `/merge` or `/approve` in a comment as a quick
59
+ // action, with the rights of the token that posted it), or become a link at
60
+ // all. A pull request can plant an address for a reviewer to repeat (the
61
+ // adversarial probe saw one), and a bot comment lends it credibility.
62
+ // Character references get a zero-width space after their `&` and stay as
63
+ // typed, since both platforms look for mentions after decoding them
64
+ // (`&#64;all`); unlike `&amp;`, it keeps `&lt;` quoted in code readable.
65
+ // Every `@` gets one too, which no mention survives (GitLab usernames may
66
+ // start with `_` or `.`), nor an email address. Inline links lose their `](`,
67
+ // and every `]:` is escaped, so no link reference definition (`[1]: https://…`)
68
+ // can form, at line start or inside a blockquote or list item, and no
69
+ // reference-style link (`[x][1]`, `[x][]`, `[1]`) has anything to resolve to.
70
+ // Addresses of every scheme get a zero-width space after the colon (GitLab
71
+ // links `smb://` and `vscode://` too), and `www.` one before its dot, so they
72
+ // read the same and stay text.
73
+ const CHARACTER_REFERENCE = /&(?=#\d{1,7};|#[xX][\da-fA-F]{1,6};|[A-Za-z][A-Za-z\d]{1,31};)/g;
74
+ export function safeMarkdown(text) {
75
+ return text
76
+ .replace(CHARACTER_REFERENCE, "&\u200b")
77
+ .replaceAll("<!--", "&lt;!--")
78
+ .replace(/<\/?[a-zA-Z][^>]*>/g, (tag) => tag.replaceAll("<", "&lt;"))
79
+ .replaceAll("@", "@\u200b")
80
+ .replace(/!\[/g, "!\u200b[")
81
+ .replace(/\/(?=ocra)/gi, "/\u200b")
82
+ .replace(/^([ \t]*)\//gm, "$1\u200b/")
83
+ .replace(/:(?=\/\/)/g, ":\u200b")
84
+ .replace(/\bwww(?=\.)/gi, "www\u200b")
85
+ .replaceAll("](", "]\\(")
86
+ .replaceAll("]:", "]\\:");
87
+ }
88
+ // File paths come from the diff, so the author controls them: a backtick or
89
+ // newline must not end the code span and let markup through, and angle
90
+ // brackets must not form ocra's HTML-comment markers in the raw body.
91
+ export function codeSpan(text) {
92
+ const safe = text
93
+ .replaceAll("`", "\u02cb")
94
+ .replace(/[\r\n]+/g, " ")
95
+ .replaceAll("<", "\u2039")
96
+ .replaceAll(">", "\u203a");
97
+ return `\`${safe}\``;
98
+ }
99
+ function location(f) {
100
+ if (!f.lineRange)
101
+ return codeSpan(f.file);
102
+ const { start, end } = f.lineRange;
103
+ return codeSpan(`${f.file}:${start === end ? start : `${start}-${end}`}`);
104
+ }
105
+ export const FINDING_MARKER = /<!-- ocra:finding ([0-9a-f]{16}) -->/;
106
+ export function inlineBody(f) {
107
+ const parts = [
108
+ `<!-- ocra:finding ${f.fingerprint} -->`,
109
+ `${ICON[f.severity]} **${safeMarkdown(f.title)}** · ${f.severity} · ${verification(f)} · ${f.reviewer}${f.lowConfidence ? " · low confidence" : ""}`,
110
+ "",
111
+ safeMarkdown(f.body),
112
+ ];
113
+ if (f.suggestion)
114
+ parts.push("", `**Suggestion:** ${safeMarkdown(f.suggestion)}`);
115
+ return parts.join("\n");
116
+ }
117
+ export function renderSummary({ report, commented, state, text, unattributed = 0, }) {
118
+ const counts = ["critical", "warning", "suggestion"]
119
+ .map((s) => `${report.findings.filter((f) => f.severity === s).length} ${s}`)
120
+ .join(", ");
121
+ const lines = [
122
+ SUMMARY_MARKER,
123
+ `## ocra review · ${headline(report)}`,
124
+ "",
125
+ safeMarkdown(report.summary),
126
+ ...overrideNote(report, text),
127
+ "",
128
+ `**${report.findings.length} finding(s)** (${counts}) · risk tier \`${report.tier}\``,
129
+ ];
130
+ if (report.scope?.mode === "incremental") {
131
+ lines.push("", `Reviewed only what changed since ${codeSpan(report.scope.since.slice(0, 7))}.`);
132
+ }
133
+ else if (report.scope) {
134
+ lines.push("", `Reviewed every file again: ${safeMarkdown(report.scope.reason)}.`);
135
+ }
136
+ // Only true while no confirmed critical blocks, and low-confidence
137
+ // findings do not count at all.
138
+ const unverified = report.verdict === "significant_concerns"
139
+ ? 0
140
+ : report.findings.filter((f) => f.severity === "critical" && f.verification !== "confirmed" && !f.lowConfidence).length;
141
+ if (unverified > 0) {
142
+ lines.push("", `${unverified} critical finding(s) are not verified, so they cap the verdict at minor issues.`);
143
+ }
144
+ if (report.unverifiedCriticals > 0) {
145
+ lines.push("", `**Incomplete:** verification failed or ran out of budget for ${report.unverifiedCriticals} critical finding(s); check them yourself.`);
146
+ }
147
+ const { notReviewed } = coverageGaps(report);
148
+ if (notReviewed > 0) {
149
+ const limit = report.spendLimit?.reached
150
+ ? `; the spend limit of $${report.spendLimit.usd} was reached`
151
+ : "";
152
+ lines.push("", `**Incomplete:** ${notReviewed} selected file(s) were not reviewed${limit}. They are listed under Coverage and cost, and the next review of this ${text.changeRequest} includes them.`);
153
+ }
154
+ if (unattributed > 0) {
155
+ lines.push("", `${unattributed} resolved thread(s) of ocra's did not dismiss their finding: nothing says who resolved them, as when a push resolves outdated threads. To dismiss a finding, answer its thread with \`/ocra dismiss\` or "won't fix".`);
156
+ }
157
+ const inSummary = report.findings.filter((f) => !commented.has(f.fingerprint));
158
+ if (inSummary.length > 0) {
159
+ lines.push("", "### Findings outside the diff");
160
+ for (const f of inSummary) {
161
+ lines.push(`- ${ICON[f.severity]} ${location(f)} **${safeMarkdown(f.title)}** _(${verification(f)}${f.lowConfidence ? ", low confidence" : ""})_: ${safeMarkdown(f.body).replaceAll("\n", " ")}`);
162
+ }
163
+ }
164
+ if (report.remembered.length > 0) {
165
+ lines.push("", `${report.remembered.length} finding(s) matched \`.ocra/memory.json\` and are not repeated.`);
166
+ }
167
+ const rereview = report.rereview;
168
+ if (rereview && rereview.fixed.length > 0) {
169
+ lines.push("", "### Fixed since the last review");
170
+ for (const f of rereview.fixed)
171
+ lines.push(`- ~~${safeMarkdown(f.title)}~~ ${codeSpan(f.file)}`);
172
+ }
173
+ if (rereview && rereview.notReproduced.length > 0) {
174
+ lines.push("", "### Not reported this time, code unchanged", "", "Still open and counted in the verdict until the code changes or a reviewer dismisses them.", "");
175
+ for (const f of rereview.notReproduced)
176
+ lines.push(`- ${ICON[f.severity]} ${safeMarkdown(f.title)} ${codeSpan(f.file)} _(${verification(f)})_`);
177
+ }
178
+ if (rereview && rereview.unchanged.length > 0) {
179
+ lines.push("", "### Still open in unchanged files", "", "Reported earlier in files not changed since; they count in the verdict.", "");
180
+ for (const f of rereview.unchanged)
181
+ lines.push(`- ${ICON[f.severity]} ${safeMarkdown(f.title)} ${codeSpan(f.file)} _(${verification(f)})_`);
182
+ }
183
+ if (rereview && rereview.dismissed.length > 0) {
184
+ lines.push("", "### Dismissed by reviewers");
185
+ for (const f of rereview.dismissed)
186
+ lines.push(`- ${safeMarkdown(f.title)} ${codeSpan(f.file)}`);
187
+ }
188
+ if (rereview && rereview.notRechecked.length > 0) {
189
+ lines.push("", "### Not re-checked this time", "", "Their files were not reviewed in this run; they stay open and count in the verdict.", "");
190
+ for (const f of rereview.notRechecked)
191
+ lines.push(`- ${ICON[f.severity]} ${safeMarkdown(f.title)} ${codeSpan(f.file)} _(${verification(f)})_`);
192
+ }
193
+ const failed = report.coverage.filter((c) => c.status === "failed" || c.status === "unreviewed");
194
+ const { costUsd, inputTokens, outputTokens } = report.usage;
195
+ lines.push("", "_The verdict is advice from language models that read the change itself, and can be swayed by text in it. Do not use it as a security gate._", "", "<details><summary>Coverage and cost</summary>", "", `${report.coverage.filter((c) => c.status === "reviewed").length} reviewed · ${report.coverage.filter((c) => c.status === "unchanged").length} unchanged since the last review · ${failed.length} not reviewed · ${report.coverage.filter((c) => c.status === "excluded").length} excluded · ${inputTokens} in / ${outputTokens} out tokens · $${costUsd.toFixed(4)}${spendLimitNote(report)}`, ...failed.map((c) => `- not reviewed: ${codeSpan(c.path)}`), "", "</details>");
196
+ const markdown = lines.join("\n");
197
+ const footer = `\n\n${writeState(state)}`;
198
+ const room = MAX_SUMMARY_CHARS - footer.length;
199
+ return ((markdown.length > room ? `${markdown.slice(0, room - 40)}\n\n…(truncated)` : markdown) + footer);
200
+ }
201
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1,11 @@
1
+ export declare const MAX_ATTEMPTS = 3;
2
+ export interface RetryDecision {
3
+ retry: boolean;
4
+ waitMs: number;
5
+ }
6
+ export declare function retryDecision(method: string, idempotent: boolean, outcome: {
7
+ status: number;
8
+ headers: Headers;
9
+ body: string;
10
+ } | "network_error", attempt: number, now?: number): RetryDecision;
11
+ //# sourceMappingURL=retry.d.ts.map
package/dist/retry.js ADDED
@@ -0,0 +1,40 @@
1
+ // Platforms answer bursts with a rate limit (429 on both; GitHub also a 403
2
+ // "secondary rate limit") and have short 5xx outages. One such answer during
3
+ // publish used to throw away a paid review, so requests are retried a
4
+ // bounded number of times.
5
+ export const MAX_ATTEMPTS = 3;
6
+ const MAX_WAIT_MS = 60_000;
7
+ // A request the platform refused without acting on it (rate limits) can
8
+ // always be repeated. A 5xx or a lost connection may have happened after the
9
+ // platform acted, so only requests that are safe to repeat retry then: POST
10
+ // would post the same comment or review twice.
11
+ export function retryDecision(method, idempotent, outcome, attempt, now = Date.now()) {
12
+ const stop = { retry: false, waitMs: 0 };
13
+ if (attempt >= MAX_ATTEMPTS)
14
+ return stop;
15
+ const backoff = 1_000 * 2 ** (attempt - 1);
16
+ const safe = idempotent || method === "GET";
17
+ if (outcome === "network_error")
18
+ return safe ? { retry: true, waitMs: backoff } : stop;
19
+ const { status, headers, body } = outcome;
20
+ const rateLimited = status === 429 ||
21
+ (status === 403 &&
22
+ (headers.get("x-ratelimit-remaining") === "0" || /secondary rate limit/i.test(body)));
23
+ if (rateLimited)
24
+ return { retry: true, waitMs: rateLimitWait(headers, now) ?? backoff };
25
+ if (safe && status >= 500)
26
+ return { retry: true, waitMs: backoff };
27
+ return stop;
28
+ }
29
+ function rateLimitWait(headers, now) {
30
+ const after = Number(headers.get("retry-after"));
31
+ if (Number.isFinite(after) && after > 0)
32
+ return Math.min(after * 1_000, MAX_WAIT_MS);
33
+ // GitHub's header, then GitLab's; both carry epoch seconds.
34
+ const reset = Number(headers.get("x-ratelimit-reset") ?? headers.get("ratelimit-reset"));
35
+ if (Number.isFinite(reset) && reset > 0) {
36
+ return Math.min(Math.max(reset * 1_000 - now, 0), MAX_WAIT_MS);
37
+ }
38
+ return undefined;
39
+ }
40
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1,50 @@
1
+ import { type ChangeRequest, type CodeMatch, type FileDiff, type PriorReview, type ReviewReport, type VcsAdapter } from "@open-cr-agent/core";
2
+ import type { ReviewPlatform } from "./platform.js";
3
+ export type CodeSource = Pick<VcsAdapter, "getDiff" | "readFile" | "searchCode">;
4
+ export interface History {
5
+ filesChangedSince(from: string, to: string): Promise<{
6
+ files: string[];
7
+ } | {
8
+ reason: string;
9
+ }>;
10
+ }
11
+ export interface PlatformReviewOptions {
12
+ name: string;
13
+ platform: ReviewPlatform;
14
+ code: CodeSource;
15
+ history?: History;
16
+ }
17
+ export declare function declinesFinding(reply: string): boolean;
18
+ export declare class PlatformReview implements VcsAdapter {
19
+ private readonly options;
20
+ readonly name: string;
21
+ private readonly platform;
22
+ private readonly memo;
23
+ private readonly writers;
24
+ constructor(options: PlatformReviewOptions);
25
+ getChangeRequest(): Promise<ChangeRequest>;
26
+ private override;
27
+ private unedited;
28
+ private canWrite;
29
+ getDiff(): Promise<FileDiff[]>;
30
+ readFile(path: string): Promise<string | undefined>;
31
+ searchCode(literal: string): Promise<CodeMatch[]>;
32
+ getPriorReview(): Promise<PriorReview | undefined>;
33
+ private priorState;
34
+ private changesSince;
35
+ private repliesByPeople;
36
+ publish(report: ReviewReport): Promise<{
37
+ warnings: string[];
38
+ }>;
39
+ private ownThreads;
40
+ private unattributedResolutions;
41
+ private resolveFixedThreads;
42
+ private lastEditor;
43
+ private summaryComment;
44
+ private bot;
45
+ private changeRequest;
46
+ private comments;
47
+ private threads;
48
+ private once;
49
+ }
50
+ //# sourceMappingURL=review.d.ts.map
package/dist/review.js ADDED
@@ -0,0 +1,368 @@
1
+ import { errorMessage, } from "@open-cr-agent/core";
2
+ import { FINDING_MARKER, inlineBody, renderSummary } from "./render.js";
3
+ import { lostProgress, readState, SUMMARY_MARKER } from "./state.js";
4
+ const OVERRIDE = /^\/ocra override ([0-9a-fA-F]{40}(?:[0-9a-fA-F]{24})?)\s+(\S.*)$/m;
5
+ const MAX_OVERRIDE_REASON = 300;
6
+ const MAX_REPLIES = 3;
7
+ const MAX_REPLY_CHARS = 1_000;
8
+ const DECLINE = /^(won['’]?t fix|wontfix|will not fix|by design|false positive|not a bug|working as intended|intended behaviou?r)(?=$|[\s.,;:!—–-])/i;
9
+ const COMMAND = /^\/ocra dismiss\b/im;
10
+ // A dismissal takes a clear decline: an explicit `/ocra dismiss`, or a reply
11
+ // that opens with a decline and does not ask. Words anywhere else in a reply
12
+ // ("this is not intended", "is this by design?", "acknowledged, will fix")
13
+ // do not dismiss, since a dismissed finding leaves the verdict. Disagreement
14
+ // ("I disagree") keeps the finding reported.
15
+ export function declinesFinding(reply) {
16
+ if (COMMAND.test(reply))
17
+ return true;
18
+ const opening = reply
19
+ .trim()
20
+ .split(/(?<=[.!?])\s|\n/)[0]
21
+ ?.trim() ?? "";
22
+ return DECLINE.test(opening) && !opening.endsWith("?");
23
+ }
24
+ // The review conversation on a code review platform, the same on every one:
25
+ // which earlier state and which comments count, who may override or dismiss,
26
+ // and what gets posted. The platform only maps its API (ReviewPlatform).
27
+ export class PlatformReview {
28
+ options;
29
+ name;
30
+ platform;
31
+ memo = new Map();
32
+ writers = new Map();
33
+ constructor(options) {
34
+ this.options = options;
35
+ this.name = options.name;
36
+ this.platform = options.platform;
37
+ }
38
+ async getChangeRequest() {
39
+ const cr = await this.changeRequest();
40
+ const override = await this.override(cr);
41
+ return {
42
+ id: cr.id,
43
+ title: cr.title,
44
+ description: cr.description,
45
+ baseSha: cr.baseSha,
46
+ headSha: cr.headSha,
47
+ ...(override ? { override } : {}),
48
+ };
49
+ }
50
+ // "Break glass": `/ocra override <commit> <reason>` from someone with
51
+ // write access other than the author lets a blocking verdict pass for that
52
+ // commit only, so a later push with new problems needs a new decision. The
53
+ // author can never overrule the review of their own change. Comments are
54
+ // best effort: without them there is simply no override.
55
+ async override(cr) {
56
+ const comments = await this.comments().catch(() => []);
57
+ const bot = await this.bot();
58
+ let found;
59
+ for (const c of comments) {
60
+ const login = c.author;
61
+ const match = OVERRIDE.exec(c.body);
62
+ if (!match || !login || login === cr.author || bot.is(login))
63
+ continue;
64
+ // ocra's own summary is never a command, whichever account posted it.
65
+ if (c.body.includes(SUMMARY_MARKER))
66
+ continue;
67
+ const [, commit = "", reason = ""] = match;
68
+ // The full commit id: a short prefix can be matched by a new commit.
69
+ if (commit.toLowerCase() !== cr.headSha)
70
+ continue;
71
+ if (!(await this.unedited(c, login)) || !(await this.canWrite(login)))
72
+ continue;
73
+ found = { by: login, reason: reason.trim().slice(0, MAX_OVERRIDE_REASON) };
74
+ }
75
+ return found;
76
+ }
77
+ // Anyone with write access can edit anyone's comment, and the platform
78
+ // keeps showing the original author: a command counts only when nobody
79
+ // else edited it. Unknown means no.
80
+ async unedited(comment, login) {
81
+ try {
82
+ const editor = await this.platform.editor(comment);
83
+ return editor === undefined || editor === login;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ // Write access from the platform, memoized per login; a failed lookup
90
+ // means no.
91
+ canWrite(login) {
92
+ let known = this.writers.get(login);
93
+ if (!known) {
94
+ known = this.platform.canWrite(login).catch(() => false);
95
+ this.writers.set(login, known);
96
+ }
97
+ return known;
98
+ }
99
+ getDiff() {
100
+ return this.options.code.getDiff();
101
+ }
102
+ readFile(path) {
103
+ return this.options.code.readFile(path);
104
+ }
105
+ searchCode(literal) {
106
+ return this.options.code.searchCode(literal);
107
+ }
108
+ async getPriorReview() {
109
+ const prior = await this.priorState();
110
+ if ("untrusted" in prior)
111
+ return { findings: [], fullReviewReason: prior.untrusted };
112
+ const { state } = prior;
113
+ if (!state)
114
+ return undefined;
115
+ const { dismissed, replies } = await this.repliesByPeople(state.findings);
116
+ return {
117
+ findings: state.findings.map((f) => dismissed.has(f.fingerprint) ? { ...f, dismissed: true } : f),
118
+ ...(await this.changesSince(state)),
119
+ ...(state.tier ? { tier: state.tier } : {}),
120
+ ...(Object.keys(replies).length > 0 ? { replies } : {}),
121
+ };
122
+ }
123
+ // Anyone with write access can edit the summary comment, including a
124
+ // change request's author. Every part of the state is then suspect: a head
125
+ // skips their next changes, a `commented` flag hides a finding from both
126
+ // the inline comments and the summary. So the state counts only when ocra
127
+ // was the last to edit the comment; otherwise the run starts over.
128
+ priorState() {
129
+ return this.once("prior", async () => {
130
+ const comment = await this.summaryComment();
131
+ const state = comment ? readState(comment.body) : undefined;
132
+ if (!comment || !state)
133
+ return {};
134
+ const editor = await this.lastEditor(comment);
135
+ if (editor === undefined) {
136
+ return { untrusted: "could not check who last edited the previous review's summary" };
137
+ }
138
+ if (!(await this.bot()).is(editor)) {
139
+ return { untrusted: "the previous review's summary was edited by someone else" };
140
+ }
141
+ return { state };
142
+ });
143
+ }
144
+ async changesSince(state) {
145
+ const { history } = this.options;
146
+ if (!state.head)
147
+ return { fullReviewReason: "the previous review did not record its commit" };
148
+ if (!history)
149
+ return { fullReviewReason: "no repository history to compare with" };
150
+ const head = (await this.changeRequest()).headSha;
151
+ const changed = await history.filesChangedSince(state.head, head);
152
+ if ("reason" in changed)
153
+ return { fullReviewReason: changed.reason };
154
+ return {
155
+ changedSince: {
156
+ head: state.head,
157
+ files: [...new Set([...changed.files, ...(state.pending ?? [])])],
158
+ },
159
+ };
160
+ }
161
+ // A thread of ocra's that a reviewer resolved, or answered with a clear
162
+ // "won't fix", dismisses its finding. A reviewer is someone with write
163
+ // access other than the change request's author, in a comment nobody else
164
+ // edited: otherwise the author could resolve or argue a finding away. Any
165
+ // other reply from a reviewer dismisses nothing, but the judge weighs it
166
+ // when the finding comes back (and cannot drop a confirmed critical for
167
+ // it). Replies are collected for every thread of ocra's, not only tracked
168
+ // findings, so a finding a reply argued away does not return without it.
169
+ // Thread data is best effort: without it nothing is dismissed or replied.
170
+ async repliesByPeople(findings) {
171
+ const commented = new Set(findings.filter((f) => f.commented).map((f) => f.fingerprint));
172
+ const author = (await this.changeRequest()).author;
173
+ const bot = await this.bot();
174
+ const reviewer = async (login) => login !== undefined && login !== author && !bot.is(login) && (await this.canWrite(login));
175
+ const threads = await this.threads().catch(() => []);
176
+ const dismissed = new Set();
177
+ const replies = {};
178
+ for (const thread of threads) {
179
+ const fingerprint = findingOf(thread, bot);
180
+ if (!fingerprint)
181
+ continue;
182
+ const said = [];
183
+ let declined = false;
184
+ for (const r of thread.comments.slice(1)) {
185
+ const own = r.editor === undefined || r.editor === r.author;
186
+ if (!own || !(await reviewer(r.author)))
187
+ continue;
188
+ if (declinesFinding(r.body))
189
+ declined = true;
190
+ else if (r.body.trim() !== "")
191
+ said.push(r.body.trim().slice(0, MAX_REPLY_CHARS));
192
+ }
193
+ if (commented.has(fingerprint)) {
194
+ const resolved = thread.resolved && (await reviewer(thread.resolvedBy));
195
+ if (resolved || declined) {
196
+ dismissed.add(fingerprint);
197
+ continue;
198
+ }
199
+ }
200
+ if (said.length > 0)
201
+ replies[fingerprint] = said.slice(-MAX_REPLIES);
202
+ }
203
+ return { dismissed, replies };
204
+ }
205
+ async publish(report) {
206
+ const previous = await this.summaryComment();
207
+ const prior = await this.priorState();
208
+ const trusted = "state" in prior ? prior.state : undefined;
209
+ const before = trusted?.findings ?? [];
210
+ const alreadyCommented = new Set([
211
+ ...before.filter((f) => f.commented).map((f) => f.fingerprint),
212
+ ...(trusted?.posted ?? []),
213
+ ...(await this.ownThreads()),
214
+ ]);
215
+ const fresh = report.findings.flatMap((f) => {
216
+ if (alreadyCommented.has(f.fingerprint) || !f.lineRange || !f.anchor.inDiff)
217
+ return [];
218
+ return [{ finding: { ...f, lineRange: f.lineRange }, body: inlineBody(f) }];
219
+ });
220
+ const published = await this.platform.publishFindings(report, fresh);
221
+ const commented = new Set([...alreadyCommented, ...published.posted]);
222
+ const current = new Set(report.findings.map((f) => f.fingerprint));
223
+ const rereview = report.rereview;
224
+ const quiet = [
225
+ ...(rereview?.notReproduced ?? []),
226
+ ...(rereview?.notRechecked ?? []),
227
+ ...(rereview?.unchanged ?? []),
228
+ ...(rereview?.dismissed ?? []),
229
+ ];
230
+ // Low-confidence findings (--ultra) are shown, not counted; stored as
231
+ // ordinary findings they would count on the next push.
232
+ const state = [
233
+ ...report.findings
234
+ .filter((f) => !f.lowConfidence)
235
+ .map((f) => ({
236
+ fingerprint: f.fingerprint,
237
+ title: f.title,
238
+ file: f.file,
239
+ severity: f.severity,
240
+ commented: commented.has(f.fingerprint),
241
+ ...(f.quote ? { quote: f.quote } : {}),
242
+ ...(f.verification ? { verification: f.verification } : {}),
243
+ })),
244
+ ...quiet.filter((f) => !current.has(f.fingerprint)),
245
+ ];
246
+ const pending = report.coverage
247
+ .filter((c) => c.status === "failed" || c.status === "unreviewed")
248
+ .map((c) => c.path);
249
+ const tracked = new Set(state.map((f) => f.fingerprint));
250
+ const untracked = [...commented].filter((fp) => !tracked.has(fp));
251
+ const unattributed = await this.unattributedResolutions(current);
252
+ const body = renderSummary({
253
+ report,
254
+ commented,
255
+ state: {
256
+ findings: state,
257
+ head: report.changeRequest.headSha,
258
+ pending,
259
+ tier: report.tier,
260
+ ...(untracked.length > 0 ? { posted: untracked } : {}),
261
+ },
262
+ text: this.platform.text,
263
+ unattributed,
264
+ });
265
+ await this.platform.writeSummary(previous, body);
266
+ const lost = lostProgress(body, pending.length);
267
+ return {
268
+ warnings: [
269
+ ...(lost ? [lost] : []),
270
+ ...published.warnings,
271
+ ...((await published.finish?.()) ?? []),
272
+ ...(await this.resolveFixedThreads(report)),
273
+ ],
274
+ };
275
+ }
276
+ // Findings ocra already commented on inline, from its own threads, so a
277
+ // run that stopped between posting them and writing the summary, or a
278
+ // summary whose state no longer counts, does not post them twice.
279
+ async ownThreads() {
280
+ const bot = await this.bot();
281
+ const threads = await this.threads().catch(() => []);
282
+ return threads.flatMap((thread) => findingOf(thread, bot) ?? []);
283
+ }
284
+ // Findings still reported whose thread was resolved without saying by
285
+ // whom: that resolution dismissed nothing, and the summary says why.
286
+ async unattributedResolutions(current) {
287
+ const bot = await this.bot();
288
+ const threads = await this.threads().catch(() => []);
289
+ return threads.filter((thread) => {
290
+ const fingerprint = findingOf(thread, bot);
291
+ return (thread.resolved &&
292
+ thread.resolvedBy === undefined &&
293
+ fingerprint !== undefined &&
294
+ current.has(fingerprint));
295
+ }).length;
296
+ }
297
+ // Resolving threads is a courtesy: the summary already lists what was
298
+ // fixed, so a failure here is a warning, not a failed publish.
299
+ async resolveFixedThreads(report) {
300
+ const fixed = new Set((report.rereview?.fixed ?? []).filter((f) => f.commented).map((f) => f.fingerprint));
301
+ if (fixed.size === 0)
302
+ return [];
303
+ try {
304
+ const bot = await this.bot();
305
+ for (const thread of await this.threads()) {
306
+ const fingerprint = findingOf(thread, bot);
307
+ if (thread.resolved || !fingerprint || !fixed.has(fingerprint))
308
+ continue;
309
+ await this.platform.resolveThread(thread.id);
310
+ }
311
+ return [];
312
+ }
313
+ catch (error) {
314
+ return [`could not resolve the threads of fixed findings: ${errorMessage(error)}`];
315
+ }
316
+ }
317
+ // The account that last edited the comment (ocra itself when nobody did),
318
+ // or undefined when that cannot be told.
319
+ async lastEditor(comment) {
320
+ try {
321
+ return (await this.platform.editor(comment)) ?? (await this.bot()).login;
322
+ }
323
+ catch {
324
+ return undefined;
325
+ }
326
+ }
327
+ // The last summary ocra posted: by the account's exact login, never by a
328
+ // look-alike, since a comment counted as ocra's is trusted when unedited.
329
+ summaryComment() {
330
+ return this.once("summary", async () => {
331
+ const bot = await this.bot();
332
+ return (await this.comments()).findLast((c) => c.author === bot.login && c.body.includes(SUMMARY_MARKER));
333
+ });
334
+ }
335
+ bot() {
336
+ return this.once("bot", () => this.platform.bot());
337
+ }
338
+ changeRequest() {
339
+ return this.once("changeRequest", () => this.platform.changeRequest());
340
+ }
341
+ comments() {
342
+ return this.once("comments", () => this.platform.comments());
343
+ }
344
+ threads() {
345
+ return this.once("threads", () => this.platform.threads());
346
+ }
347
+ // Platform data is read once per run: a second read could see a comment
348
+ // posted in between and disagree with the first.
349
+ once(key, load) {
350
+ let value = this.memo.get(key);
351
+ if (!value) {
352
+ value = load();
353
+ this.memo.set(key, value);
354
+ }
355
+ return value;
356
+ }
357
+ }
358
+ // The finding a thread of ocra's is about: its first comment is ocra's, with
359
+ // a marker, and nobody else edited it. An edited marker could point a
360
+ // reviewer's resolution or reply at another finding, or hide one.
361
+ function findingOf(thread, bot) {
362
+ const first = thread.comments[0];
363
+ const fingerprint = first && FINDING_MARKER.exec(first.body)?.[1];
364
+ if (!first || !fingerprint || !bot.is(first.author))
365
+ return undefined;
366
+ return first.editor === undefined || bot.is(first.editor) ? fingerprint : undefined;
367
+ }
368
+ //# sourceMappingURL=review.js.map
@@ -0,0 +1,15 @@
1
+ import type { PriorFinding } from "@open-cr-agent/core";
2
+ import { type RiskTier } from "@open-cr-agent/core";
3
+ export declare const SUMMARY_MARKER = "<!-- ocra:review -->";
4
+ export declare const MAX_WRITTEN_STATE_CHARS = 30000;
5
+ export interface ReviewState {
6
+ findings: PriorFinding[];
7
+ head?: string;
8
+ pending?: string[];
9
+ posted?: string[];
10
+ tier?: RiskTier;
11
+ }
12
+ export declare function readState(body: string): ReviewState | undefined;
13
+ export declare function writeState(state: ReviewState): string;
14
+ export declare function lostProgress(body: string, pending: number): string | undefined;
15
+ //# sourceMappingURL=state.d.ts.map
package/dist/state.js ADDED
@@ -0,0 +1,120 @@
1
+ import { RISK_TIERS, severitySchema, verificationSchema } from "@open-cr-agent/core";
2
+ import { z } from "zod";
3
+ export const SUMMARY_MARKER = "<!-- ocra:review -->";
4
+ // Only a state block that ends the comment counts: author-controlled text
5
+ // (file paths, titles) is printed above it and must not be able to plant one.
6
+ const STATE_PATTERN = /<!-- ocra:state v1 ([A-Za-z0-9+/=]+) -->\s*$/;
7
+ const MAX_STATE_FINDINGS = 500;
8
+ const MAX_STATE_CHARS = 60_000;
9
+ // Written states stay well under what is read, so the summary text keeps room
10
+ // in GitHub's 65,536-character comment limit.
11
+ export const MAX_WRITTEN_STATE_CHARS = 30_000;
12
+ const MAX_PENDING_FILES = 1_000;
13
+ const MAX_POSTED = 1_000;
14
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
15
+ const stateSchema = z.object({
16
+ findings: z
17
+ .array(z.object({
18
+ fingerprint: z.string().regex(/^[0-9a-f]{16}$/),
19
+ title: z.string().max(300),
20
+ file: z.string().max(1_000),
21
+ severity: severitySchema,
22
+ commented: z.boolean(),
23
+ quote: z
24
+ .object({
25
+ lines: z.number().int().positive().max(1_000),
26
+ hash: z.string().regex(/^[0-9a-f]{16}$/),
27
+ })
28
+ .optional(),
29
+ verification: verificationSchema.optional(),
30
+ }))
31
+ .max(MAX_STATE_FINDINGS),
32
+ head: z.string().regex(SHA).optional(),
33
+ pending: z.array(z.string().max(1_000)).max(MAX_PENDING_FILES).optional(),
34
+ posted: z
35
+ .array(z.string().regex(/^[0-9a-f]{16}$/))
36
+ .max(MAX_POSTED)
37
+ .optional(),
38
+ tier: z.enum(RISK_TIERS).optional(),
39
+ });
40
+ // The state lives in a comment anyone with write access can edit, so it is
41
+ // validated and bounded, and the adapter ignores it when someone other than
42
+ // ocra edited the comment. Dismissals are never stored: they are recomputed
43
+ // from review threads on every run.
44
+ export function readState(body) {
45
+ const encoded = STATE_PATTERN.exec(body)?.[1];
46
+ if (!encoded || encoded.length > MAX_STATE_CHARS)
47
+ return undefined;
48
+ try {
49
+ const parsed = stateSchema.safeParse(JSON.parse(Buffer.from(encoded, "base64").toString("utf8")));
50
+ if (!parsed.success)
51
+ return undefined;
52
+ const { head, pending, posted, tier } = parsed.data;
53
+ return {
54
+ findings: parsed.data.findings.map(({ quote, verification, ...finding }) => ({
55
+ ...finding,
56
+ ...(quote ? { quote } : {}),
57
+ ...(verification ? { verification } : {}),
58
+ })),
59
+ ...(head ? { head } : {}),
60
+ ...(pending ? { pending } : {}),
61
+ ...(posted?.length ? { posted } : {}),
62
+ ...(tier ? { tier } : {}),
63
+ };
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ export function writeState(state) {
70
+ const kept = state.findings.slice(0, MAX_STATE_FINDINGS).map((f) => ({
71
+ fingerprint: f.fingerprint,
72
+ title: f.title.slice(0, 300),
73
+ file: f.file.slice(0, 1_000),
74
+ severity: f.severity,
75
+ commented: f.commented,
76
+ ...(f.quote ? { quote: f.quote } : {}),
77
+ ...(f.verification ? { verification: f.verification } : {}),
78
+ }));
79
+ // Without the full list of unfinished files the next run could skip one of
80
+ // them, so a list that does not fit drops the head and forces a full review.
81
+ const pending = state.pending ?? [];
82
+ const scope = state.head && pending.length <= MAX_PENDING_FILES
83
+ ? {
84
+ head: state.head,
85
+ ...(pending.length > 0 ? { pending: pending.map((p) => p.slice(0, 1_000)) } : {}),
86
+ }
87
+ : {};
88
+ // Too large a state first loses its scope (a full review next time), then
89
+ // findings from the end of the list (this run's come first, most severe
90
+ // first); a dropped finding's inline comment may be posted again.
91
+ const extras = {
92
+ ...(state.posted?.length ? { posted: state.posted.slice(-MAX_POSTED) } : {}),
93
+ ...(state.tier ? { tier: state.tier } : {}),
94
+ };
95
+ let encoded = encode(kept, { ...scope, ...extras });
96
+ if (encoded.length > MAX_WRITTEN_STATE_CHARS)
97
+ encoded = encode(kept, extras);
98
+ if (encoded.length > MAX_WRITTEN_STATE_CHARS)
99
+ encoded = encode(kept, {});
100
+ let count = kept.length;
101
+ while (encoded.length > MAX_WRITTEN_STATE_CHARS && count > 0) {
102
+ count = Math.floor(count * 0.8);
103
+ encoded = encode(kept.slice(0, count), {});
104
+ }
105
+ return `<!-- ocra:state v1 ${encoded} -->`;
106
+ }
107
+ // A state too large for the comment loses its head and unfinished files
108
+ // (writeState), so the next review starts over instead of continuing; the
109
+ // warning for that, or undefined when the state in `body` kept its head.
110
+ export function lostProgress(body, pending) {
111
+ const kept = readState(body);
112
+ if (!kept || kept.head !== undefined)
113
+ return undefined;
114
+ const files = pending > 0 ? ` with its ${pending} unfinished file(s)` : "";
115
+ return `the review state did not fit in the summary comment${files}: the next review of this pull request reviews every file again`;
116
+ }
117
+ function encode(findings, scope) {
118
+ return Buffer.from(JSON.stringify({ findings, ...scope }), "utf8").toString("base64");
119
+ }
120
+ //# sourceMappingURL=state.js.map
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@open-cr-agent/vcs-platform",
3
+ "version": "0.1.2",
4
+ "description": "What Open-CR-Agent's code review platform adapters share: the review summary, its state, and who may command ocra",
5
+ "keywords": [
6
+ "code-review",
7
+ "pull-request",
8
+ "merge-request"
9
+ ],
10
+ "license": "Apache-2.0",
11
+ "homepage": "https://ocra.majincheng.com",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jma49/Open-CR-Agent.git",
15
+ "directory": "packages/vcs-platform"
16
+ },
17
+ "bugs": "https://github.com/jma49/Open-CR-Agent/issues",
18
+ "engines": {
19
+ "node": ">=22.19"
20
+ },
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "!dist/**/*.map"
31
+ ],
32
+ "dependencies": {
33
+ "@open-cr-agent/core": "0.1.2",
34
+ "zod": "^4.6.5"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }