@open-cr-agent/vcs-local 0.1.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.
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-local
2
+
3
+ The adapter for local Git changes (working tree, ranges and commits) of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer. 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,2 @@
1
+ export declare function ensureCommits(root: string, shas: readonly string[], refspecs?: readonly string[], remote?: string): Promise<void>;
2
+ //# sourceMappingURL=commits.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { git } from "./git.js";
2
+ const FETCH_TIMEOUT_MS = 5 * 60_000;
3
+ // Pull request commits are often missing from a local clone (shallow CI
4
+ // checkouts, fork heads). Fetch them by SHA first, then through the extra
5
+ // refspecs (for example pull/<n>/head), and name what is still missing.
6
+ export async function ensureCommits(root, shas, refspecs = [], remote = "origin") {
7
+ // Anything but a commit id could be read by git fetch as an option.
8
+ const invalid = shas.filter((sha) => !/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(sha));
9
+ if (invalid.length > 0)
10
+ throw new Error(`Not commit ids: ${invalid.join(", ")}`);
11
+ const missing = async () => {
12
+ const result = [];
13
+ for (const sha of shas) {
14
+ const out = await git(["cat-file", "-t", "--end-of-options", sha], {
15
+ cwd: root,
16
+ okExitCodes: [0, 1, 128],
17
+ });
18
+ if (out.trim() !== "commit")
19
+ result.push(sha);
20
+ }
21
+ return result;
22
+ };
23
+ let absent = await missing();
24
+ for (const attempt of [absent, refspecs]) {
25
+ if (absent.length === 0)
26
+ return;
27
+ if (attempt.length === 0)
28
+ continue;
29
+ // No credential prompt can block a non-interactive run.
30
+ await git(["fetch", "--quiet", "--no-tags", remote, ...attempt], {
31
+ cwd: root,
32
+ okExitCodes: [0, 1, 128],
33
+ timeoutMs: FETCH_TIMEOUT_MS,
34
+ env: { GIT_TERMINAL_PROMPT: "0" },
35
+ });
36
+ absent = await missing();
37
+ }
38
+ if (absent.length > 0) {
39
+ throw new Error(`Commits ${absent.join(", ")} are not in this repository and could not be fetched from ${remote}`);
40
+ }
41
+ }
42
+ //# sourceMappingURL=commits.js.map
package/dist/git.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export interface GitOptions {
2
+ cwd: string;
3
+ input?: string;
4
+ okExitCodes?: readonly number[];
5
+ env?: Readonly<Record<string, string>>;
6
+ truncateAt?: number;
7
+ timeoutMs?: number;
8
+ }
9
+ export declare const GIT_TIMEOUT_MS: number;
10
+ export declare class GitError extends Error {
11
+ readonly args: readonly string[];
12
+ readonly exitCode: number | undefined;
13
+ readonly stderr: string;
14
+ constructor(args: readonly string[], exitCode: number | undefined, stderr: string);
15
+ }
16
+ export declare function git(args: readonly string[], options: GitOptions): Promise<string>;
17
+ export declare function isShallow(root: string): Promise<boolean>;
18
+ export declare const SHALLOW_HINT = "the clone is shallow; fetch the full history (for example actions/checkout with fetch-depth: 0)";
19
+ //# sourceMappingURL=git.d.ts.map
package/dist/git.js ADDED
@@ -0,0 +1,69 @@
1
+ import { execFile } from "node:child_process";
2
+ // Every git call ends: a fetch can wait on the network forever, and a diff
3
+ // of a huge repository should fail rather than hang the review.
4
+ export const GIT_TIMEOUT_MS = 10 * 60_000;
5
+ export class GitError extends Error {
6
+ args;
7
+ exitCode;
8
+ stderr;
9
+ constructor(args, exitCode, stderr) {
10
+ super(`git ${args.join(" ")} failed (exit ${exitCode ?? "unknown"}): ${stderr.trim()}`);
11
+ this.args = args;
12
+ this.exitCode = exitCode;
13
+ this.stderr = stderr;
14
+ }
15
+ }
16
+ const MAX_OUTPUT_BYTES = 512 * 1024 * 1024;
17
+ const CLOSED_PIPE = new Set(["EPIPE", "ENOTCONN", "ECONNRESET"]);
18
+ export function git(args, options) {
19
+ const okExitCodes = options.okExitCodes ?? [0];
20
+ return new Promise((resolve, reject) => {
21
+ const child = execFile("git", args, {
22
+ cwd: options.cwd,
23
+ encoding: "utf8",
24
+ maxBuffer: options.truncateAt ?? MAX_OUTPUT_BYTES,
25
+ timeout: options.timeoutMs ?? GIT_TIMEOUT_MS,
26
+ killSignal: "SIGKILL",
27
+ env: { ...process.env, LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", ...options.env },
28
+ }, (error, stdout, stderr) => {
29
+ if (options.truncateAt !== undefined &&
30
+ error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
31
+ resolve(stdout);
32
+ return;
33
+ }
34
+ if (error?.killed && error.signal === "SIGKILL") {
35
+ const seconds = Math.round((options.timeoutMs ?? GIT_TIMEOUT_MS) / 1000);
36
+ reject(new GitError(args, undefined, `timed out after ${seconds}s`));
37
+ return;
38
+ }
39
+ const exitCode = error ? (typeof error.code === "number" ? error.code : undefined) : 0;
40
+ if (exitCode !== undefined && okExitCodes.includes(exitCode))
41
+ resolve(stdout);
42
+ else
43
+ reject(new GitError(args, exitCode, stderr || String(error?.message ?? "")));
44
+ });
45
+ // git may exit before reading stdin; its exit code already reports the
46
+ // outcome, so a broken pipe on our side carries no information. Which
47
+ // error that is depends on timing and platform (EPIPE, or ENOTCONN on
48
+ // macOS when the pipe closed before the write).
49
+ child.stdin?.on("error", (error) => {
50
+ if (!CLOSED_PIPE.has(error.code ?? ""))
51
+ reject(error);
52
+ });
53
+ if (options.input === undefined)
54
+ child.stdin?.end();
55
+ else
56
+ child.stdin?.end(options.input);
57
+ });
58
+ }
59
+ // CI checkouts are shallow by default; commits beyond the cut-off look
60
+ // unrelated to git, which surfaces as a failed merge-base.
61
+ export async function isShallow(root) {
62
+ const out = await git(["rev-parse", "--is-shallow-repository"], {
63
+ cwd: root,
64
+ okExitCodes: [0, 128],
65
+ });
66
+ return out.trim() === "true";
67
+ }
68
+ export const SHALLOW_HINT = "the clone is shallow; fetch the full history (for example actions/checkout with fetch-depth: 0)";
69
+ //# sourceMappingURL=git.js.map
@@ -0,0 +1,7 @@
1
+ export type ChangedFiles = {
2
+ files: string[];
3
+ } | {
4
+ reason: string;
5
+ };
6
+ export declare function filesChangedSince(root: string, from: string, to: string): Promise<ChangedFiles>;
7
+ //# sourceMappingURL=history.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { GitError, git, isShallow, SHALLOW_HINT } from "./git.js";
2
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
3
+ // The files that differ between two commits, when `to` descends from `from`.
4
+ // After a force-push or rebase `from` is no longer an ancestor, and a commit
5
+ // that was never fetched cannot be compared: both give a reason instead.
6
+ export async function filesChangedSince(root, from, to) {
7
+ if (!SHA.test(from) || !SHA.test(to))
8
+ return { reason: "not a commit id" };
9
+ const short = from.slice(0, 7);
10
+ const type = await git(["cat-file", "-t", "--end-of-options", from], {
11
+ cwd: root,
12
+ okExitCodes: [0, 1, 128],
13
+ });
14
+ if (type.trim() !== "commit")
15
+ return { reason: `commit ${short} is not available` };
16
+ try {
17
+ await git(["merge-base", "--is-ancestor", from, to], { cwd: root });
18
+ }
19
+ catch (error) {
20
+ if (error instanceof GitError && error.exitCode === 1) {
21
+ if (await isShallow(root)) {
22
+ return { reason: `commit ${short} cannot be traced to the new head: ${SHALLOW_HINT}` };
23
+ }
24
+ return {
25
+ reason: `commit ${short} is not an ancestor of the new head (force-push or rebase)`,
26
+ };
27
+ }
28
+ throw error;
29
+ }
30
+ const out = await git([
31
+ "diff",
32
+ "--name-only",
33
+ "-z",
34
+ "--no-renames",
35
+ "--no-ext-diff",
36
+ "--no-textconv",
37
+ "--no-relative",
38
+ from,
39
+ to,
40
+ "--",
41
+ ], { cwd: root });
42
+ return { files: out.split("\0").filter((p) => p !== "") };
43
+ }
44
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,6 @@
1
+ export { ensureCommits } from "./commits.js";
2
+ export { GitError } from "./git.js";
3
+ export * from "./history.js";
4
+ export * from "./local-adapter.js";
5
+ export * from "./plugin.js";
6
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { ensureCommits } from "./commits.js";
2
+ export { GitError } from "./git.js";
3
+ export * from "./history.js";
4
+ export * from "./local-adapter.js";
5
+ export * from "./plugin.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,35 @@
1
+ import { type ChangeRequest, type CodeMatch, type FileDiff, type PriorReview, type VcsAdapter } from "@open-cr-agent/core";
2
+ export type LocalTarget = {
3
+ mode: "workspace";
4
+ } | {
5
+ mode: "range";
6
+ from: string;
7
+ to: string;
8
+ } | {
9
+ mode: "commit";
10
+ commit: string;
11
+ };
12
+ export interface LocalGitOptions {
13
+ cwd: string;
14
+ target: LocalTarget;
15
+ }
16
+ export declare const MAX_READ_BYTES: number;
17
+ export declare class LocalGitAdapter implements VcsAdapter {
18
+ private readonly options;
19
+ readonly name = "local";
20
+ private resolved;
21
+ constructor(options: LocalGitOptions);
22
+ repositoryRoot(): Promise<string>;
23
+ getChangeRequest(): Promise<ChangeRequest>;
24
+ getDiff(): Promise<FileDiff[]>;
25
+ readFile(path: string): Promise<string | undefined>;
26
+ searchCode(literal: string): Promise<CodeMatch[]>;
27
+ remoteUrl(remote: string): Promise<string>;
28
+ getPriorReview(): Promise<PriorReview | undefined>;
29
+ publish(): Promise<{
30
+ warnings: string[];
31
+ }>;
32
+ private target;
33
+ private resolveTarget;
34
+ }
35
+ //# sourceMappingURL=local-adapter.d.ts.map
@@ -0,0 +1,252 @@
1
+ import { cp, lstat, mkdtemp, open, readFile, readlink, realpath, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { parseUnifiedDiff, } from "@open-cr-agent/core";
5
+ import { GitError, git, isShallow, SHALLOW_HINT } from "./git.js";
6
+ const WORKING_TREE = "working-tree";
7
+ const SEARCH_RESULT_LIMIT = 100;
8
+ const SEARCH_OUTPUT_BYTES = 4 * 1024 * 1024;
9
+ // A run keeps every file it reads in memory; files beyond this are read in
10
+ // part (larger ones are diffed as binary and not reviewed anyway).
11
+ export const MAX_READ_BYTES = 2 * 1024 * 1024;
12
+ // Explicit prefixes and flags keep the output parseable whatever the user's
13
+ // diff configuration (noprefix, mnemonicPrefix, external drivers, relative).
14
+ // Files over the threshold diff as binary, so one generated or vendored
15
+ // monster cannot fill memory before selection excludes it.
16
+ const DIFF_ARGS = [
17
+ "-c",
18
+ "core.quotepath=true",
19
+ "-c",
20
+ "core.bigFileThreshold=1m",
21
+ "diff",
22
+ "--no-color",
23
+ "--no-ext-diff",
24
+ "--no-textconv",
25
+ "--no-relative",
26
+ "--find-renames",
27
+ "--src-prefix=a/",
28
+ "--dst-prefix=b/",
29
+ ];
30
+ export class LocalGitAdapter {
31
+ options;
32
+ name = "local";
33
+ resolved;
34
+ constructor(options) {
35
+ this.options = options;
36
+ }
37
+ async repositoryRoot() {
38
+ return (await this.target()).root;
39
+ }
40
+ async getChangeRequest() {
41
+ return (await this.target()).request;
42
+ }
43
+ async getDiff() {
44
+ const { root, base, head } = await this.target();
45
+ if (head !== undefined) {
46
+ return parseUnifiedDiff(await git([...DIFF_ARGS, base, head, "--"], { cwd: root }));
47
+ }
48
+ return parseUnifiedDiff(await workspaceDiff(root, base));
49
+ }
50
+ async readFile(path) {
51
+ const { root, head } = await this.target();
52
+ const inside = relativeInside(root, resolve(root, path));
53
+ if (inside === undefined)
54
+ return undefined;
55
+ if (head === undefined)
56
+ return readWorkingTreeFile(root, inside);
57
+ try {
58
+ return await git(["cat-file", "blob", `${head}:${inside.split(sep).join("/")}`], {
59
+ cwd: root,
60
+ truncateAt: MAX_READ_BYTES,
61
+ });
62
+ }
63
+ catch (error) {
64
+ if (error instanceof GitError && error.exitCode === 128)
65
+ return undefined;
66
+ throw error;
67
+ }
68
+ }
69
+ async searchCode(literal) {
70
+ const { root, head } = await this.target();
71
+ const args = ["grep", "-n", "-z", "-I", "--no-color", "--full-name", "-F", "-m", "20"];
72
+ if (head === undefined)
73
+ args.push("--untracked");
74
+ args.push("-e", literal);
75
+ if (head !== undefined)
76
+ args.push(head);
77
+ const out = await git([...args, "--"], {
78
+ cwd: root,
79
+ okExitCodes: [0, 1],
80
+ truncateAt: SEARCH_OUTPUT_BYTES,
81
+ });
82
+ const prefix = head === undefined ? "" : `${head}:`;
83
+ const lines = out.split("\n");
84
+ // Output cut at the byte cap ends inside a line.
85
+ if (!out.endsWith("\n"))
86
+ lines.pop();
87
+ return lines
88
+ .filter((line) => line !== "")
89
+ .slice(0, SEARCH_RESULT_LIMIT)
90
+ .map((line) => {
91
+ const [path = "", lineNumber = "0", ...text] = line.split("\0");
92
+ return { path: path.slice(prefix.length), line: Number(lineNumber), text: text.join("\0") };
93
+ });
94
+ }
95
+ async remoteUrl(remote) {
96
+ const { root } = await this.target();
97
+ return (await git(["remote", "get-url", "--end-of-options", remote], { cwd: root })).trim();
98
+ }
99
+ async getPriorReview() {
100
+ return undefined;
101
+ }
102
+ async publish() {
103
+ return { warnings: [] };
104
+ }
105
+ target() {
106
+ this.resolved ??= this.resolveTarget();
107
+ return this.resolved;
108
+ }
109
+ async resolveTarget() {
110
+ const root = (await git(["rev-parse", "--show-toplevel"], { cwd: this.options.cwd })).trim();
111
+ const target = this.options.target;
112
+ if (target.mode === "workspace") {
113
+ const base = (await tryVerifyCommit(root, "HEAD")) ?? (await emptyTree(root));
114
+ return {
115
+ root,
116
+ base,
117
+ head: undefined,
118
+ request: request(WORKING_TREE, "Working tree changes", "", base, WORKING_TREE),
119
+ };
120
+ }
121
+ if (target.mode === "range") {
122
+ const from = await verifyCommit(root, target.from);
123
+ const to = await verifyCommit(root, target.to);
124
+ const base = await mergeBase(root, from, to);
125
+ const subjects = await git(["log", "--format=- %s", `${base}..${to}`], { cwd: root });
126
+ const title = `Changes from ${target.from} to ${target.to}`;
127
+ return {
128
+ root,
129
+ base,
130
+ head: to,
131
+ request: request(`${base}..${to}`, title, subjects.trim(), base, to),
132
+ };
133
+ }
134
+ const head = await verifyCommit(root, target.commit);
135
+ const base = (await tryVerifyCommit(root, `${head}^`)) ?? (await emptyTree(root));
136
+ const message = (await git(["log", "-1", "--format=%B", head], { cwd: root })).trim();
137
+ const [title = "", ...body] = message.split("\n");
138
+ return {
139
+ root,
140
+ base,
141
+ head,
142
+ request: request(head, title, body.join("\n").trim(), base, head),
143
+ };
144
+ }
145
+ }
146
+ // Untracked files join the diff through intent-to-add entries in a throwaway
147
+ // copy of the index: one git process for any number of files, and the
148
+ // user's real index is never touched.
149
+ async function workspaceDiff(root, base) {
150
+ const listing = await git(["ls-files", "--others", "--exclude-standard", "-z"], { cwd: root });
151
+ const untracked = listing.split("\0").filter((p) => p !== "");
152
+ if (untracked.length === 0)
153
+ return git([...DIFF_ARGS, base, "--"], { cwd: root });
154
+ const dir = await mkdtemp(join(tmpdir(), "ocra-index-"));
155
+ try {
156
+ const index = join(dir, "index");
157
+ const realIndex = (await git(["rev-parse", "--git-path", "index"], { cwd: root })).trim();
158
+ // The copy keeps the index's timestamp: git compares it with entry
159
+ // timestamps to catch same-second, same-size edits ("racy git"), and a
160
+ // fresh timestamp would make it trust stale stat data and miss them.
161
+ await cp(resolve(root, realIndex), index, { preserveTimestamps: true }).catch((error) => {
162
+ if (error.code !== "ENOENT")
163
+ throw error;
164
+ });
165
+ const env = { GIT_INDEX_FILE: index, GIT_LITERAL_PATHSPECS: "1" };
166
+ await git(["add", "--intent-to-add", "--pathspec-from-file=-", "--pathspec-file-nul"], {
167
+ cwd: root,
168
+ env,
169
+ input: untracked.join("\0"),
170
+ });
171
+ return await git([...DIFF_ARGS, base, "--"], { cwd: root, env });
172
+ }
173
+ finally {
174
+ await rm(dir, { recursive: true, force: true });
175
+ }
176
+ }
177
+ async function mergeBase(root, from, to) {
178
+ try {
179
+ return (await git(["merge-base", from, to], { cwd: root })).trim();
180
+ }
181
+ catch (error) {
182
+ if (error instanceof GitError && (await isShallow(root))) {
183
+ throw new Error(`Cannot find where ${from.slice(0, 7)} and ${to.slice(0, 7)} diverge: ${SHALLOW_HINT}`);
184
+ }
185
+ throw error;
186
+ }
187
+ }
188
+ function relativeInside(root, absolute) {
189
+ const inside = relative(root, absolute);
190
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
191
+ return undefined;
192
+ }
193
+ return inside;
194
+ }
195
+ // Reads what git would store, as range and commit mode do: a symlink reads as
196
+ // its target path and a path through a symlinked directory does not exist.
197
+ // Following links would let a committed `notes.txt -> .env` read a file the
198
+ // core access policy refuses by name.
199
+ async function readWorkingTreeFile(root, inside) {
200
+ try {
201
+ const parent = dirname(inside);
202
+ const realParent = await realpath(resolve(root, parent));
203
+ if (realParent !== resolve(await realpath(root), parent))
204
+ return undefined;
205
+ const path = join(realParent, basename(inside));
206
+ const stat = await lstat(path);
207
+ if (stat.isSymbolicLink())
208
+ return await readlink(path, "utf8");
209
+ if (!stat.isFile())
210
+ return undefined;
211
+ if (stat.size <= MAX_READ_BYTES)
212
+ return await readFile(path, "utf8");
213
+ const handle = await open(path, "r");
214
+ try {
215
+ const buffer = Buffer.alloc(MAX_READ_BYTES);
216
+ const { bytesRead } = await handle.read(buffer, 0, MAX_READ_BYTES, 0);
217
+ return buffer.subarray(0, bytesRead).toString("utf8");
218
+ }
219
+ finally {
220
+ await handle.close();
221
+ }
222
+ }
223
+ catch (error) {
224
+ const code = error.code;
225
+ if (code === "ENOENT" || code === "ENOTDIR")
226
+ return undefined;
227
+ throw error;
228
+ }
229
+ }
230
+ function request(id, title, description, baseSha, headSha) {
231
+ return { id, title, description, baseSha, headSha };
232
+ }
233
+ async function verifyCommit(root, ref) {
234
+ const sha = await tryVerifyCommit(root, ref);
235
+ if (sha === undefined)
236
+ throw new Error(`Unknown commit: ${ref}`);
237
+ return sha;
238
+ }
239
+ // --end-of-options stops a user-supplied ref such as "--output=x" from being
240
+ // read as an option.
241
+ async function tryVerifyCommit(root, ref) {
242
+ const out = await git(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], {
243
+ cwd: root,
244
+ okExitCodes: [0, 1, 128],
245
+ });
246
+ const sha = out.trim();
247
+ return sha === "" ? undefined : sha;
248
+ }
249
+ async function emptyTree(root) {
250
+ return (await git(["hash-object", "-t", "tree", "--stdin"], { cwd: root, input: "" })).trim();
251
+ }
252
+ //# sourceMappingURL=local-adapter.js.map
@@ -0,0 +1,4 @@
1
+ import type { OcraPlugin } from "@open-cr-agent/core";
2
+ export declare const localGitPlugin: OcraPlugin;
3
+ export declare function findRepositoryRoot(cwd: string): Promise<string>;
4
+ //# sourceMappingURL=plugin.d.ts.map
package/dist/plugin.js ADDED
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ import { git } from "./git.js";
3
+ import { LocalGitAdapter } from "./local-adapter.js";
4
+ const optionsSchema = z.object({
5
+ cwd: z.string().min(1),
6
+ target: z.discriminatedUnion("mode", [
7
+ z.object({ mode: z.literal("workspace") }),
8
+ z.object({ mode: z.literal("range"), from: z.string().min(1), to: z.string().min(1) }),
9
+ z.object({ mode: z.literal("commit"), commit: z.string().min(1) }),
10
+ ]),
11
+ });
12
+ export const localGitPlugin = {
13
+ name: "vcs-local",
14
+ configure(ctx) {
15
+ ctx.registerVcs("local", (options) => new LocalGitAdapter(optionsSchema.parse(options)));
16
+ },
17
+ };
18
+ export async function findRepositoryRoot(cwd) {
19
+ return (await git(["rev-parse", "--show-toplevel"], { cwd })).trim();
20
+ }
21
+ //# sourceMappingURL=plugin.js.map
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@open-cr-agent/vcs-local",
3
+ "version": "0.1.0",
4
+ "description": "Local git adapter for Open-CR-Agent: working tree, ranges and commits",
5
+ "keywords": [
6
+ "code-review",
7
+ "git"
8
+ ],
9
+ "license": "Apache-2.0",
10
+ "homepage": "https://ocra.majincheng.com",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/jma49/Open-CR-Agent.git",
14
+ "directory": "packages/vcs-local"
15
+ },
16
+ "bugs": "https://github.com/jma49/Open-CR-Agent/issues",
17
+ "engines": {
18
+ "node": ">=22.19"
19
+ },
20
+ "type": "module",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "!dist/**/*.map"
30
+ ],
31
+ "dependencies": {
32
+ "@open-cr-agent/core": "0.1.0",
33
+ "zod": "^4.6.5"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ }
38
+ }