@open-cr-agent/vcs-local 0.7.0 → 0.9.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.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Reads blobs of a revision through one `git cat-file --batch-command`
3
+ * instead of a process per file: an agent and anchoring read hundreds of
4
+ * files a run. Undefined for a path that is not a blob there, like
5
+ * `git cat-file blob` failing; a blob over `maxBytes` is left to the caller,
6
+ * which reads its start alone.
7
+ */
8
+ export declare class BlobReader {
9
+ private readonly root;
10
+ private child;
11
+ private pending;
12
+ private buffer;
13
+ private idle;
14
+ private timeout;
15
+ constructor(root: string);
16
+ read(name: string, maxBytes: number): Promise<{
17
+ text: string;
18
+ } | {
19
+ tooLarge: true;
20
+ } | undefined>;
21
+ private send;
22
+ private process;
23
+ private drain;
24
+ private arm;
25
+ private stop;
26
+ private fail;
27
+ }
@@ -0,0 +1,145 @@
1
+ import { spawn } from "node:child_process";
2
+ import { childEnvironment } from "./git.js";
3
+ // How long a read may take before the reader gives up on its process.
4
+ const READ_TIMEOUT_MS = 60_000;
5
+ // An idle process is ended so a finished review leaves none behind.
6
+ const IDLE_MS = 250;
7
+ /**
8
+ * Reads blobs of a revision through one `git cat-file --batch-command`
9
+ * instead of a process per file: an agent and anchoring read hundreds of
10
+ * files a run. Undefined for a path that is not a blob there, like
11
+ * `git cat-file blob` failing; a blob over `maxBytes` is left to the caller,
12
+ * which reads its start alone.
13
+ */
14
+ export class BlobReader {
15
+ root;
16
+ child;
17
+ pending = [];
18
+ buffer = Buffer.alloc(0);
19
+ idle;
20
+ timeout;
21
+ constructor(root) {
22
+ this.root = root;
23
+ }
24
+ async read(name, maxBytes) {
25
+ const info = await this.send("info", `info ${name}`);
26
+ if (info?.type !== "blob")
27
+ return undefined;
28
+ if (info.size > maxBytes)
29
+ return { tooLarge: true };
30
+ const bytes = await this.send("contents", `contents ${info.oid}`);
31
+ return { text: bytes.toString("utf8") };
32
+ }
33
+ send(kind, command) {
34
+ const child = this.process();
35
+ return new Promise((resolve, reject) => {
36
+ this.pending.push({ kind, resolve, reject });
37
+ this.arm();
38
+ child.stdin.write(`${command}\n`);
39
+ });
40
+ }
41
+ process() {
42
+ if (this.child)
43
+ return this.child;
44
+ const child = spawn("git", ["cat-file", "--batch-command"], {
45
+ cwd: this.root,
46
+ env: childEnvironment(),
47
+ stdio: ["pipe", "pipe", "pipe"],
48
+ });
49
+ child.stdout.on("data", (chunk) => {
50
+ this.buffer = Buffer.concat([this.buffer, chunk]);
51
+ this.drain();
52
+ });
53
+ child.stderr.resume();
54
+ child.on("error", (error) => this.fail(child, error));
55
+ child.on("close", (code) => this.fail(child, new Error(`git cat-file exited with ${code}`)));
56
+ child.stdin.on("error", (error) => this.fail(child, error));
57
+ this.child = child;
58
+ return child;
59
+ }
60
+ drain() {
61
+ for (;;) {
62
+ const next = this.pending[0];
63
+ if (!next)
64
+ break;
65
+ const end = this.buffer.indexOf(0x0a);
66
+ if (end < 0)
67
+ return;
68
+ const header = this.buffer.subarray(0, end).toString("utf8");
69
+ if (next.kind === "info") {
70
+ this.buffer = this.buffer.subarray(end + 1);
71
+ this.pending.shift();
72
+ next.resolve(parseInfo(header));
73
+ continue;
74
+ }
75
+ const info = parseInfo(header);
76
+ if (!info) {
77
+ this.buffer = this.buffer.subarray(end + 1);
78
+ this.pending.shift();
79
+ next.reject(new Error(`git cat-file: ${header}`));
80
+ continue;
81
+ }
82
+ // The contents, then a line feed.
83
+ if (this.buffer.length < end + 1 + info.size + 1)
84
+ return;
85
+ const bytes = Buffer.from(this.buffer.subarray(end + 1, end + 1 + info.size));
86
+ this.buffer = this.buffer.subarray(end + 1 + info.size + 1);
87
+ this.pending.shift();
88
+ next.resolve(bytes);
89
+ }
90
+ this.arm();
91
+ }
92
+ // While a read is waiting, a timeout; once none is, the idle timer.
93
+ arm() {
94
+ clearTimeout(this.idle);
95
+ clearTimeout(this.timeout);
96
+ const child = this.child;
97
+ if (!child)
98
+ return;
99
+ hold(child, this.pending.length > 0);
100
+ if (this.pending.length > 0) {
101
+ this.timeout = setTimeout(() => this.fail(child, new Error("git cat-file timed out")), READ_TIMEOUT_MS).unref();
102
+ }
103
+ else {
104
+ this.idle = setTimeout(() => this.stop(child), IDLE_MS).unref();
105
+ }
106
+ }
107
+ stop(child) {
108
+ if (this.child !== child)
109
+ return;
110
+ this.child = undefined;
111
+ this.buffer = Buffer.alloc(0);
112
+ child.stdin.end();
113
+ }
114
+ fail(child, error) {
115
+ if (this.child !== child)
116
+ return;
117
+ this.child = undefined;
118
+ this.buffer = Buffer.alloc(0);
119
+ clearTimeout(this.idle);
120
+ clearTimeout(this.timeout);
121
+ const pending = this.pending;
122
+ this.pending = [];
123
+ child.kill("SIGKILL");
124
+ for (const p of pending)
125
+ p.reject(error);
126
+ }
127
+ }
128
+ // A review that ends while the reader is idle must not wait for it, and one
129
+ // waiting on a read must not end.
130
+ function hold(child, held) {
131
+ for (const handle of [child, child.stdin, child.stdout, child.stderr]) {
132
+ const h = handle;
133
+ if (held)
134
+ h.ref?.();
135
+ else
136
+ h.unref?.();
137
+ }
138
+ }
139
+ // "<oid> <type> <size>", or "<name> missing" (or ambiguous) for none.
140
+ function parseInfo(header) {
141
+ const match = /^([0-9a-f]{40,64}) (\S+) (\d+)$/.exec(header);
142
+ if (!match)
143
+ return undefined;
144
+ return { oid: match[1], type: match[2], size: Number(match[3]) };
145
+ }
@@ -0,0 +1,9 @@
1
+ interface RemoteBranch {
2
+ name: string;
3
+ sha: string;
4
+ }
5
+ export declare function fetchRemoteBranches(root: string, prefix: string, { max, remote }: {
6
+ max: number;
7
+ remote?: string;
8
+ }): Promise<RemoteBranch[]>;
9
+ export {};
@@ -0,0 +1,59 @@
1
+ import { OcraError } from "@open-cr-agent/core";
2
+ import { credentialEnvironment, git, isShallow } from "./git.js";
3
+ const FETCH_TIMEOUT_MS = 2 * 60_000;
4
+ const BRANCH = /^refs\/heads\/([A-Za-z0-9._/-]+)$/;
5
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
6
+ // The remote's branches whose names start with `prefix`, last name first
7
+ // and at most `max`, with their commits fetched so they can be read. No
8
+ // local ref is written: the commits are reachable only for this run.
9
+ export async function fetchRemoteBranches(root, prefix, { max, remote = "origin" }) {
10
+ if (!/^[A-Za-z0-9._-][A-Za-z0-9._/-]*$/.test(prefix) || prefix.includes("..")) {
11
+ throw new OcraError("INPUT_INVALID", `Not a branch name prefix: ${prefix}`);
12
+ }
13
+ // No credential prompt can block a non-interactive run.
14
+ const env = { ...credentialEnvironment(process.env), GIT_TERMINAL_PROMPT: "0" };
15
+ const listed = await git(["ls-remote", "--heads", remote, `refs/heads/${prefix}*`], {
16
+ cwd: root,
17
+ timeoutMs: FETCH_TIMEOUT_MS,
18
+ env,
19
+ });
20
+ const branches = listed
21
+ .split("\n")
22
+ .map((line) => {
23
+ const [sha = "", ref = ""] = line.split("\t");
24
+ const name = BRANCH.exec(ref)?.[1];
25
+ return name?.startsWith(prefix) && SHA.test(sha) && !name.includes("..")
26
+ ? { name, sha }
27
+ : undefined;
28
+ })
29
+ .filter((b) => b !== undefined)
30
+ .sort((a, b) => (a.name < b.name ? 1 : a.name > b.name ? -1 : 0))
31
+ .slice(0, max);
32
+ const absent = await missing(root, branches);
33
+ if (absent.length > 0) {
34
+ // Fetching full history into a shallow clone would undo its depth.
35
+ const depth = (await isShallow(root)) ? ["--depth=1"] : [];
36
+ // An empty refmap keeps git from updating origin's tracking refs.
37
+ await git([
38
+ "fetch",
39
+ "--quiet",
40
+ "--no-tags",
41
+ "--refmap=",
42
+ ...depth,
43
+ remote,
44
+ ...absent.map((b) => `refs/heads/${b.name}`),
45
+ ], { cwd: root, timeoutMs: FETCH_TIMEOUT_MS, env });
46
+ }
47
+ const unread = new Set(await missing(root, branches));
48
+ return branches.filter((b) => !unread.has(b));
49
+ }
50
+ async function missing(root, branches) {
51
+ if (branches.length === 0)
52
+ return [];
53
+ const out = await git(["cat-file", "--batch-check=%(objecttype)"], {
54
+ cwd: root,
55
+ input: `${branches.map((b) => b.sha).join("\n")}\n`,
56
+ });
57
+ const types = out.split("\n");
58
+ return branches.filter((_, i) => types[i] !== "commit");
59
+ }
package/dist/commits.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { OcraError } from "@open-cr-agent/core";
2
- import { git } from "./git.js";
2
+ import { credentialEnvironment, git } from "./git.js";
3
3
  const FETCH_TIMEOUT_MS = 5 * 60_000;
4
4
  // Pull request commits are often missing from a local clone (shallow CI
5
5
  // checkouts, fork heads). Fetch them by SHA first, then through the extra
@@ -32,7 +32,7 @@ export async function ensureCommits(root, shas, refspecs = [], remote = "origin"
32
32
  cwd: root,
33
33
  okExitCodes: [0, 1, 128],
34
34
  timeoutMs: FETCH_TIMEOUT_MS,
35
- env: { GIT_TERMINAL_PROMPT: "0" },
35
+ env: { ...credentialEnvironment(process.env), GIT_TERMINAL_PROMPT: "0" },
36
36
  });
37
37
  absent = await missing();
38
38
  }
@@ -0,0 +1,9 @@
1
+ export declare const MAX_FIX_FILES = 5;
2
+ export declare function isFixSubject(subject: string): boolean;
3
+ export declare function isMinedPath(path: string): boolean;
4
+ export interface FixCommit {
5
+ sha: string;
6
+ subject: string;
7
+ }
8
+ export declare function fixCommits(root: string, ref: string): Promise<FixCommit[]>;
9
+ export declare function fixedFiles(root: string, sha: string): Promise<string[]>;
package/dist/fixes.js ADDED
@@ -0,0 +1,52 @@
1
+ import { git } from "./git.js";
2
+ // Fix commits in a repository's history, read the same way by the learning
3
+ // miner (ocra learn) and the golden-case miner (ocra-eval). Every call reads
4
+ // objects only: nothing is checked out and nothing from the repository runs.
5
+ // A fix touching more source files than this is usually a refactor that
6
+ // happens to say "fix"; it says little about one defect.
7
+ export const MAX_FIX_FILES = 5;
8
+ // History older than this many first-parent commits is not mined.
9
+ const MAX_COMMITS = 5_000;
10
+ const SHA = /^[0-9a-f]{40}$/;
11
+ // Conventional Commits' fix and revert, plus the plain wording of
12
+ // repositories that do not use them.
13
+ const FIX_SUBJECT = /^(fix|revert)(\([^)]*\))?!?:|^revert\b|\b(fix(es|ed)?|bug)\b/i;
14
+ export function isFixSubject(subject) {
15
+ return FIX_SUBJECT.test(subject);
16
+ }
17
+ // Source files only: a defect in docs, tests, snapshots, lockfiles or
18
+ // generated data is not what the reviewers are asked to find.
19
+ const NOT_SOURCE = /\.(md|mdx|rst|txt|json|jsonc|lock|snap|ya?ml|toml|svg|png|jpe?g|gif|csv)$|(^|\/)(CHANGELOG|LICENSE)[^/]*$|\.(test|spec|e2e)\.|(^|\/)(__snapshots__|__tests__|tests?|fixtures?|\.changeset)\//i;
20
+ export function isMinedPath(path) {
21
+ return !NOT_SOURCE.test(path);
22
+ }
23
+ // Newest first, on the first-parent line of `ref`.
24
+ export async function fixCommits(root, ref) {
25
+ const log = await git([
26
+ "log",
27
+ "--first-parent",
28
+ "--no-merges",
29
+ `--max-count=${MAX_COMMITS}`,
30
+ "--format=%H%x00%s%x00",
31
+ "--end-of-options",
32
+ ref,
33
+ ], { cwd: root });
34
+ const fields = log.split("\0");
35
+ const fixes = [];
36
+ for (let i = 0; i + 1 < fields.length; i += 2) {
37
+ const sha = fields[i]?.trim() ?? "";
38
+ const subject = fields[i + 1] ?? "";
39
+ if (SHA.test(sha) && isFixSubject(subject))
40
+ fixes.push({ sha, subject });
41
+ }
42
+ return fixes;
43
+ }
44
+ // The source files a fix changed, as it named them.
45
+ export async function fixedFiles(root, sha) {
46
+ if (!SHA.test(sha))
47
+ return [];
48
+ const names = await git(["diff", "--name-only", "-z", "--no-renames", `${sha}^`, sha], {
49
+ cwd: root,
50
+ });
51
+ return names.split("\0").filter((f) => f !== "" && isMinedPath(f));
52
+ }
package/dist/git.d.ts CHANGED
@@ -14,5 +14,12 @@ export declare class GitError extends OcraError {
14
14
  constructor(args: readonly string[], exitCode: number | undefined, stderr: string);
15
15
  }
16
16
  export declare function git(args: readonly string[], options: GitOptions): Promise<string>;
17
+ export declare function childEnvironment(extra?: Readonly<Record<string, string>>): Record<string, string>;
18
+ export declare function gitEnvironment(env: Readonly<Record<string, string | undefined>>): Record<string, string>;
19
+ export declare function credentialEnvironment(env: Readonly<Record<string, string | undefined>>): Record<string, string>;
20
+ export declare function attributesFrom(root: string, commit: string): Promise<string[]>;
21
+ export declare function supportsAttrSource(version: string): boolean;
22
+ /** Whether git has `cat-file --batch-command`. */
23
+ export declare function hasBatchCommand(root: string): Promise<boolean>;
17
24
  export declare function isShallow(root: string): Promise<boolean>;
18
25
  export declare const SHALLOW_HINT = "the clone is shallow; fetch the full history (for example actions/checkout with fetch-depth: 0)";
package/dist/git.js CHANGED
@@ -27,7 +27,7 @@ export function git(args, options) {
27
27
  maxBuffer: options.truncateAt ?? MAX_OUTPUT_BYTES,
28
28
  timeout: options.timeoutMs ?? GIT_TIMEOUT_MS,
29
29
  killSignal: "SIGKILL",
30
- env: { ...process.env, LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", ...options.env },
30
+ env: childEnvironment(options.env),
31
31
  }, (error, stdout, stderr) => {
32
32
  if (options.truncateAt !== undefined &&
33
33
  error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
@@ -59,6 +59,91 @@ export function git(args, options) {
59
59
  child.stdin?.end(options.input);
60
60
  });
61
61
  }
62
+ export function childEnvironment(extra = {}) {
63
+ return { ...gitEnvironment(process.env), LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", ...extra };
64
+ }
65
+ // git and what it starts (ssh, credential helpers, proxies) see only what
66
+ // they need of ocra's environment, never its model keys or platform tokens.
67
+ // git's own variables pass whole: they are its configuration (GIT_DIR in a
68
+ // hook, GIT_SSH_COMMAND, GIT_CONFIG_*), named by whoever started ocra.
69
+ const PASSED_PREFIXES = ["GIT_", "SSH_"];
70
+ const PASSED = new Set([
71
+ "PATH",
72
+ "HOME",
73
+ "XDG_CONFIG_HOME",
74
+ "TMPDIR",
75
+ "HTTP_PROXY",
76
+ "HTTPS_PROXY",
77
+ "ALL_PROXY",
78
+ "NO_PROXY",
79
+ "SSL_CERT_FILE",
80
+ "SSL_CERT_DIR",
81
+ "CURL_CA_BUNDLE",
82
+ // Windows, where names are case-insensitive (process.env keeps "Path").
83
+ "PATHEXT",
84
+ "SYSTEMROOT",
85
+ "SYSTEMDRIVE",
86
+ "WINDIR",
87
+ "COMSPEC",
88
+ "TEMP",
89
+ "TMP",
90
+ "USERPROFILE",
91
+ "HOMEDRIVE",
92
+ "HOMEPATH",
93
+ "APPDATA",
94
+ "LOCALAPPDATA",
95
+ "PROGRAMDATA",
96
+ "PROGRAMFILES",
97
+ ]);
98
+ export function gitEnvironment(env) {
99
+ return pick(env, (upper) => PASSED.has(upper) || PASSED_PREFIXES.some((p) => upper.startsWith(p)));
100
+ }
101
+ // Only a fetch reaches a remote, so only a fetch gets what credential
102
+ // helpers read from the environment: gh's and glab's tokens and Git
103
+ // Credential Manager's settings.
104
+ const CREDENTIAL_PREFIXES = ["GH_", "GLAB_", "GITLAB_", "GCM_"];
105
+ const CREDENTIAL_NAMES = new Set(["GITHUB_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]);
106
+ export function credentialEnvironment(env) {
107
+ return pick(env, (upper) => CREDENTIAL_NAMES.has(upper) || CREDENTIAL_PREFIXES.some((p) => upper.startsWith(p)));
108
+ }
109
+ function pick(env, passes) {
110
+ const picked = {};
111
+ for (const [name, value] of Object.entries(env)) {
112
+ if (value !== undefined && passes(name.toUpperCase()))
113
+ picked[name] = value;
114
+ }
115
+ return picked;
116
+ }
117
+ // Attributes decide which files diff as binary, and binary files are not
118
+ // reviewed, so the reviewed commits must not set them: they come from the
119
+ // base commit, which the reviewer trusts, rather than from the work tree
120
+ // (where a pull request review has the head checked out). git before 2.41
121
+ // has no --attr-source; there the work tree's apply, and the review warns
122
+ // about text files it excluded as binary.
123
+ const ATTR_SOURCE_SINCE = [2, 41];
124
+ const BATCH_COMMAND_SINCE = [2, 36];
125
+ let version;
126
+ function gitVersion(root) {
127
+ version ??= git(["version"], { cwd: root }).catch(() => "");
128
+ return version;
129
+ }
130
+ export async function attributesFrom(root, commit) {
131
+ return supportsAttrSource(await gitVersion(root)) ? [`--attr-source=${commit}`] : [];
132
+ }
133
+ export function supportsAttrSource(version) {
134
+ return versionAtLeast(version, ATTR_SOURCE_SINCE);
135
+ }
136
+ /** Whether git has `cat-file --batch-command`. */
137
+ export async function hasBatchCommand(root) {
138
+ return versionAtLeast(await gitVersion(root), BATCH_COMMAND_SINCE);
139
+ }
140
+ function versionAtLeast(version, [sinceMajor, sinceMinor]) {
141
+ const match = /(\d+)\.(\d+)/.exec(version);
142
+ if (!match)
143
+ return false;
144
+ const [major, minor] = [Number(match[1]), Number(match[2])];
145
+ return major > sinceMajor || (major === sinceMajor && minor >= sinceMinor);
146
+ }
62
147
  // CI checkouts are shallow by default; commits beyond the cut-off look
63
148
  // unrelated to git, which surfaces as a failed merge-base.
64
149
  export async function isShallow(root) {
@@ -1,4 +1,7 @@
1
+ export { fetchRemoteBranches } from "./branches.js";
1
2
  export { ensureCommits } from "./commits.js";
3
+ export { type FixCommit, fixCommits, fixedFiles, isMinedPath, MAX_FIX_FILES, } from "./fixes.js";
2
4
  export { filesChangedSince } from "./history.js";
3
5
  export { LocalGitAdapter } from "./local-adapter.js";
4
6
  export { findRepositoryRoot } from "./plugin.js";
7
+ export { blobReader, resolveCommit, revisionFiles } from "./tree.js";
package/dist/internal.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // "@open-cr-agent/vcs-local/internal": what the CLI uses beyond the public
2
2
  // entry. Not a contract: any release may change it.
3
+ export { fetchRemoteBranches } from "./branches.js";
3
4
  export { ensureCommits } from "./commits.js";
5
+ export { fixCommits, fixedFiles, isMinedPath, MAX_FIX_FILES, } from "./fixes.js";
4
6
  export { filesChangedSince } from "./history.js";
5
7
  export { LocalGitAdapter } from "./local-adapter.js";
6
8
  export { findRepositoryRoot } from "./plugin.js";
9
+ export { blobReader, resolveCommit, revisionFiles } from "./tree.js";
@@ -13,16 +13,20 @@ export interface LocalGitOptions {
13
13
  cwd: string;
14
14
  target: LocalTarget;
15
15
  }
16
- export declare const MAX_READ_BYTES: number;
17
16
  export declare class LocalGitAdapter implements VcsAdapter {
18
17
  readonly name = "local";
19
18
  private resolved;
19
+ private workingTree;
20
+ private search;
21
+ private blobs;
20
22
  private readonly options;
21
23
  constructor(options: LocalGitOptions);
22
24
  repositoryRoot(): Promise<string>;
23
25
  getChangeRequest(): Promise<ChangeRequest>;
24
26
  getDiff(): Promise<FileDiff[]>;
25
27
  readFile(path: string): Promise<string | undefined>;
28
+ private readBatched;
29
+ listFiles(dir: string): Promise<string[]>;
26
30
  searchCode(literal: string): Promise<CodeMatch[]>;
27
31
  remoteUrl(remote: string): Promise<string>;
28
32
  getPriorReview(): Promise<PriorReview | undefined>;
@@ -1,15 +1,13 @@
1
- import { cp, lstat, mkdtemp, open, readdir, readFile, readlink, realpath, rm, } from "node:fs/promises";
1
+ import { cp, mkdtemp, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  import { OcraError, } from "@open-cr-agent/core";
5
- import { errnoCode, isNotFound, parseUnifiedDiff } from "@open-cr-agent/core/internal";
6
- import { GitError, git, isShallow, SHALLOW_HINT } from "./git.js";
5
+ import { isNotFound, parseUnifiedDiff } from "@open-cr-agent/core/internal";
6
+ import { BlobReader } from "./blob-reader.js";
7
+ import { attributesFrom, GitError, git, hasBatchCommand, isShallow, SHALLOW_HINT } from "./git.js";
8
+ import { CodeSearch } from "./search.js";
9
+ import { MAX_READ_BYTES, WorkingTree } from "./working-tree.js";
7
10
  const WORKING_TREE = "working-tree";
8
- const SEARCH_RESULT_LIMIT = 100;
9
- const SEARCH_OUTPUT_BYTES = 4 * 1024 * 1024;
10
- // A run keeps every file it reads in memory; files beyond this are read in
11
- // part (larger ones are diffed as binary and not reviewed anyway).
12
- export const MAX_READ_BYTES = 2 * 1024 * 1024;
13
11
  // Explicit prefixes and flags keep the output parseable whatever the user's
14
12
  // diff configuration (noprefix, mnemonicPrefix, external drivers, relative).
15
13
  // Files over the threshold diff as binary, so one generated or vendored
@@ -31,6 +29,9 @@ const DIFF_ARGS = [
31
29
  export class LocalGitAdapter {
32
30
  name = "local";
33
31
  resolved;
32
+ workingTree;
33
+ search;
34
+ blobs;
34
35
  options;
35
36
  constructor(options) {
36
37
  this.options = options;
@@ -44,7 +45,8 @@ export class LocalGitAdapter {
44
45
  async getDiff() {
45
46
  const { root, base, head } = await this.target();
46
47
  if (head !== undefined) {
47
- return parseUnifiedDiff(await git([...DIFF_ARGS, base, head, "--"], { cwd: root }));
48
+ const attributes = await attributesFrom(root, base);
49
+ return parseUnifiedDiff(await git([...attributes, ...DIFF_ARGS, base, head, "--"], { cwd: root }));
48
50
  }
49
51
  return parseUnifiedDiff(await workspaceDiff(root, base));
50
52
  }
@@ -53,10 +55,16 @@ export class LocalGitAdapter {
53
55
  const inside = relativeInside(root, resolve(root, path));
54
56
  if (inside === undefined)
55
57
  return undefined;
56
- if (head === undefined)
57
- return readWorkingTreeFile(root, inside);
58
+ if (head === undefined) {
59
+ this.workingTree ??= new WorkingTree(root);
60
+ return this.workingTree.read(inside);
61
+ }
62
+ const name = `${head}:${inside.split(sep).join("/")}`;
63
+ const batched = await this.readBatched(root, name);
64
+ if (batched !== "alone")
65
+ return batched;
58
66
  try {
59
- return await git(["cat-file", "blob", `${head}:${inside.split(sep).join("/")}`], {
67
+ return await git(["cat-file", "blob", name], {
60
68
  cwd: root,
61
69
  truncateAt: MAX_READ_BYTES,
62
70
  });
@@ -67,31 +75,45 @@ export class LocalGitAdapter {
67
75
  throw error;
68
76
  }
69
77
  }
70
- async searchCode(literal) {
78
+ // "alone": read with a process of its own, as a blob over the read limit
79
+ // (its start is read) or a name the batch protocol cannot carry is.
80
+ async readBatched(root, name) {
81
+ if (/[\r\n]/.test(name) || !(await hasBatchCommand(root)))
82
+ return "alone";
83
+ this.blobs ??= new BlobReader(root);
84
+ try {
85
+ const read = await this.blobs.read(name, MAX_READ_BYTES);
86
+ return read === undefined ? undefined : "text" in read ? read.text : "alone";
87
+ }
88
+ catch {
89
+ return "alone";
90
+ }
91
+ }
92
+ // The files directly in a directory of the reviewed revision, as readFile
93
+ // takes their paths; in the workspace, those git tracks or would.
94
+ async listFiles(dir) {
71
95
  const { root, head } = await this.target();
72
- const args = ["grep", "-n", "-z", "-I", "--no-color", "--full-name", "-F", "-m", "20"];
73
- if (head === undefined)
74
- args.push("--untracked");
75
- args.push("-e", literal);
76
- if (head !== undefined)
77
- args.push(head);
78
- const out = await git([...args, "--"], {
79
- cwd: root,
80
- okExitCodes: [0, 1],
81
- truncateAt: SEARCH_OUTPUT_BYTES,
82
- });
83
- const prefix = head === undefined ? "" : `${head}:`;
84
- const lines = out.split("\n");
85
- // Output cut at the byte cap ends inside a line.
86
- if (!out.endsWith("\n"))
87
- lines.pop();
88
- return lines
89
- .filter((line) => line !== "")
90
- .slice(0, SEARCH_RESULT_LIMIT)
91
- .map((line) => {
92
- const [path = "", lineNumber = "0", ...text] = line.split("\0");
93
- return { path: path.slice(prefix.length), line: Number(lineNumber), text: text.join("\0") };
96
+ const inside = relativeInside(root, resolve(root, dir));
97
+ if (inside === undefined)
98
+ return [];
99
+ const prefix = `${inside.split(sep).join("/")}/`;
100
+ const paths = head === undefined
101
+ ? (await git(["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", prefix], {
102
+ cwd: root,
103
+ })).split("\0")
104
+ : (await git(["ls-tree", "-z", head, "--", prefix], { cwd: root }))
105
+ .split("\0")
106
+ .filter((entry) => /^100(644|755) blob /.test(entry))
107
+ .map((entry) => entry.slice(entry.indexOf("\t") + 1));
108
+ const direct = paths.filter((p) => p.startsWith(prefix) && !p.slice(prefix.length).includes("/"));
109
+ return [...new Set(direct)].sort();
110
+ }
111
+ searchCode(literal) {
112
+ this.search ??= new CodeSearch(async () => {
113
+ const { root, base, head } = await this.target();
114
+ return { root, head, attributes: head === undefined ? [] : await attributesFrom(root, base) };
94
115
  });
116
+ return this.search.search(literal);
95
117
  }
96
118
  async remoteUrl(remote) {
97
119
  const { root } = await this.target();
@@ -193,54 +215,6 @@ function relativeInside(root, absolute) {
193
215
  }
194
216
  return inside;
195
217
  }
196
- // Reads what git would store, as range and commit mode do: a symlink reads as
197
- // its target path, a path through a symlinked directory does not exist, and
198
- // neither does another spelling of a file's name. Following links would let a
199
- // committed `notes.txt -> .env` read a file the core access policy refuses by
200
- // name; so would a spelling that a case-insensitive file system folds to it.
201
- async function readWorkingTreeFile(root, inside) {
202
- try {
203
- const parent = dirname(inside);
204
- const realParent = await realpath(resolve(root, parent));
205
- if (realParent !== resolve(await realpath(root), parent))
206
- return undefined;
207
- const name = basename(inside);
208
- if (!(await isListed(realParent, name)))
209
- return undefined;
210
- const path = join(realParent, name);
211
- const stat = await lstat(path);
212
- if (stat.isSymbolicLink())
213
- return await readlink(path, "utf8");
214
- if (!stat.isFile())
215
- return undefined;
216
- if (stat.size <= MAX_READ_BYTES)
217
- return await readFile(path, "utf8");
218
- const handle = await open(path, "r");
219
- try {
220
- const buffer = Buffer.alloc(MAX_READ_BYTES);
221
- const { bytesRead } = await handle.read(buffer, 0, MAX_READ_BYTES, 0);
222
- return buffer.subarray(0, bytesRead).toString("utf8");
223
- }
224
- finally {
225
- await handle.close();
226
- }
227
- }
228
- catch (error) {
229
- const code = errnoCode(error);
230
- if (code === "ENOENT" || code === "ENOTDIR")
231
- return undefined;
232
- throw error;
233
- }
234
- }
235
- // Up to Unicode normalization: git on macOS reports names precomposed,
236
- // whatever their form on disk.
237
- async function isListed(dir, name) {
238
- const entries = await readdir(dir);
239
- if (entries.includes(name))
240
- return true;
241
- const wanted = name.normalize("NFC");
242
- return entries.some((entry) => entry.normalize("NFC") === wanted);
243
- }
244
218
  function request(id, title, description, baseSha, headSha) {
245
219
  return { id, title, description, baseSha, headSha };
246
220
  }
@@ -0,0 +1,18 @@
1
+ import type { CodeMatch } from "@open-cr-agent/core";
2
+ export interface SearchScope {
3
+ root: string;
4
+ head: string | undefined;
5
+ attributes: readonly string[];
6
+ }
7
+ /**
8
+ * `git grep` at a revision reads every blob of the tree, so each search
9
+ * costs the same however small; searches asked for in the same turn (an
10
+ * agent's tool calls, the callers of a bundle's symbols) share one grep.
11
+ */
12
+ export declare class CodeSearch {
13
+ private queue;
14
+ private readonly scope;
15
+ constructor(scope: () => Promise<SearchScope>);
16
+ search(literal: string): Promise<CodeMatch[]>;
17
+ private flush;
18
+ }
package/dist/search.js ADDED
@@ -0,0 +1,101 @@
1
+ import { git } from "./git.js";
2
+ const RESULT_LIMIT = 100;
3
+ const MATCHES_PER_FILE = 20;
4
+ const OUTPUT_BYTES = 4 * 1024 * 1024;
5
+ const BATCH_SIZE = 32;
6
+ /**
7
+ * `git grep` at a revision reads every blob of the tree, so each search
8
+ * costs the same however small; searches asked for in the same turn (an
9
+ * agent's tool calls, the callers of a bundle's symbols) share one grep.
10
+ */
11
+ export class CodeSearch {
12
+ queue = [];
13
+ scope;
14
+ constructor(scope) {
15
+ this.scope = scope;
16
+ }
17
+ search(literal) {
18
+ if (!batchable(literal))
19
+ return this.scope().then((s) => grepOne(s, literal));
20
+ return new Promise((resolve) => {
21
+ if (this.queue.length === 0)
22
+ queueMicrotask(() => this.flush());
23
+ this.queue.push({ literal, done: resolve });
24
+ });
25
+ }
26
+ flush() {
27
+ const queued = this.queue;
28
+ this.queue = [];
29
+ for (let i = 0; i < queued.length; i += BATCH_SIZE) {
30
+ const batch = queued.slice(i, i + BATCH_SIZE);
31
+ const results = this.scope().then((s) => grepMany(s, [...new Set(batch.map((q) => q.literal))]));
32
+ for (const q of batch)
33
+ q.done(results.then((r) => r.get(q.literal) ?? []));
34
+ }
35
+ }
36
+ }
37
+ // A literal with a line break is several patterns to git.
38
+ function batchable(literal) {
39
+ return literal !== "" && !/[\r\n]/.test(literal);
40
+ }
41
+ async function grepMany(scope, literals) {
42
+ if (literals.length === 1) {
43
+ const [literal = ""] = literals;
44
+ return new Map([[literal, await grepOne(scope, literal)]]);
45
+ }
46
+ // One alternation, not one -e per literal: git scans the rest of the file
47
+ // for each -F pattern at every matching line, quadratic in a large file.
48
+ const out = await grep(scope, ["-E", "-e", literals.map(ereLiteral).join("|")], OUTPUT_BYTES);
49
+ // Cut at the cap, one literal's lines may have crowded out another's.
50
+ if (Buffer.byteLength(out) >= OUTPUT_BYTES || (out !== "" && !out.endsWith("\n"))) {
51
+ const each = await Promise.all(literals.map((l) => grepOne(scope, l)));
52
+ return new Map(literals.map((l, i) => [l, each[i] ?? []]));
53
+ }
54
+ const lines = parse(scope, out);
55
+ return new Map(literals.map((l) => [l, limited(lines.filter((m) => m.text.includes(l)))]));
56
+ }
57
+ function ereLiteral(literal) {
58
+ return literal.replace(/[\\.[\](){}*+?^$|]/g, "\\$&");
59
+ }
60
+ async function grepOne(scope, literal) {
61
+ const out = await grep(scope, ["-F", "-m", String(MATCHES_PER_FILE), "-e", literal], OUTPUT_BYTES);
62
+ const lines = out.split("\n");
63
+ // Output cut at the byte cap ends inside a line.
64
+ if (!out.endsWith("\n"))
65
+ lines.pop();
66
+ return parse(scope, lines.join("\n")).slice(0, RESULT_LIMIT);
67
+ }
68
+ // What `-m` does for one literal: at most so many lines per file.
69
+ function limited(matches) {
70
+ const perFile = new Map();
71
+ const kept = [];
72
+ for (const m of matches) {
73
+ const n = perFile.get(m.path) ?? 0;
74
+ if (n >= MATCHES_PER_FILE)
75
+ continue;
76
+ perFile.set(m.path, n + 1);
77
+ kept.push(m);
78
+ if (kept.length === RESULT_LIMIT)
79
+ break;
80
+ }
81
+ return kept;
82
+ }
83
+ function grep(scope, patterns, cap) {
84
+ const args = [...scope.attributes, "grep", "-n", "-z", "-I", "--no-color", "--full-name"];
85
+ if (scope.head === undefined)
86
+ args.push("--untracked");
87
+ args.push(...patterns);
88
+ if (scope.head !== undefined)
89
+ args.push(scope.head);
90
+ return git([...args, "--"], { cwd: scope.root, okExitCodes: [0, 1], truncateAt: cap });
91
+ }
92
+ function parse(scope, out) {
93
+ const prefix = scope.head === undefined ? "" : `${scope.head}:`;
94
+ return out
95
+ .split("\n")
96
+ .filter((line) => line !== "")
97
+ .map((line) => {
98
+ const [path = "", lineNumber = "0", ...text] = line.split("\0");
99
+ return { path: path.slice(prefix.length), line: Number(lineNumber), text: text.join("\0") };
100
+ });
101
+ }
package/dist/tree.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ interface RevisionFile {
2
+ path: string;
3
+ blobId: string;
4
+ size: number;
5
+ }
6
+ export declare function resolveCommit(root: string, rev: string): Promise<string>;
7
+ export declare function revisionFiles(root: string, commit: string): Promise<RevisionFile[]>;
8
+ export declare function blobReader(root: string, maxBytes: number): (blobId: string) => Promise<Uint8Array | undefined>;
9
+ export {};
package/dist/tree.js ADDED
@@ -0,0 +1,36 @@
1
+ import { execFile } from "node:child_process";
2
+ import { git, gitEnvironment } from "./git.js";
3
+ const OBJECT_ID = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
4
+ const BLOB_TIMEOUT_MS = 60_000;
5
+ export async function resolveCommit(root, rev) {
6
+ return (await git(["rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`], { cwd: root })).trim();
7
+ }
8
+ // Every file of a commit, as a code graph lists it: regular and executable
9
+ // files only (a symlink's blob is a path, a submodule has none).
10
+ export async function revisionFiles(root, commit) {
11
+ const out = await git(["ls-tree", "-r", "-l", "-z", "--full-tree", "--end-of-options", commit], {
12
+ cwd: root,
13
+ });
14
+ return out.split("\0").flatMap((record) => {
15
+ const tab = record.indexOf("\t");
16
+ const [mode, type, blobId, size] = record.slice(0, tab).split(/ +/);
17
+ const path = record.slice(tab + 1);
18
+ if (tab < 0 || type !== "blob" || !(mode === "100644" || mode === "100755"))
19
+ return [];
20
+ if (!blobId || !OBJECT_ID.test(blobId))
21
+ return [];
22
+ return [{ path, blobId, size: Number(size) }];
23
+ });
24
+ }
25
+ // A blob's raw bytes, which no filter or textconv driver sees; undefined
26
+ // when it is not there or larger than maxBytes.
27
+ export function blobReader(root, maxBytes) {
28
+ const env = { ...gitEnvironment(process.env), LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0" };
29
+ return (blobId) => new Promise((resolve) => {
30
+ if (!OBJECT_ID.test(blobId)) {
31
+ resolve(undefined);
32
+ return;
33
+ }
34
+ execFile("git", ["cat-file", "blob", "--end-of-options", blobId], { cwd: root, env, encoding: "buffer", maxBuffer: maxBytes, timeout: BLOB_TIMEOUT_MS }, (error, stdout) => resolve(error ? undefined : new Uint8Array(stdout)));
35
+ });
36
+ }
@@ -0,0 +1,11 @@
1
+ export declare const MAX_READ_BYTES: number;
2
+ export declare class WorkingTree {
3
+ private readonly root;
4
+ private realRoot;
5
+ private readonly listings;
6
+ constructor(root: string);
7
+ read(inside: string): Promise<string | undefined>;
8
+ private locate;
9
+ private listed;
10
+ private list;
11
+ }
@@ -0,0 +1,94 @@
1
+ import { lstat, open, readdir, readFile, readlink, realpath } from "node:fs/promises";
2
+ import { join, sep } from "node:path";
3
+ import { errnoCode } from "@open-cr-agent/core/internal";
4
+ // A run keeps every file it reads in memory; files beyond this are read in
5
+ // part (larger ones are diffed as binary and not reviewed anyway).
6
+ export const MAX_READ_BYTES = 2 * 1024 * 1024;
7
+ // Reads what git would store, as range and commit mode do: a symlink reads as
8
+ // its target path, a path through a symlinked directory does not exist, and
9
+ // neither does another spelling of a file's name. Following links would let a
10
+ // committed `notes.txt -> .env` read a file the core access policy refuses by
11
+ // name; so would a spelling that a case-insensitive file system folds to it.
12
+ //
13
+ // Each directory is listed once per run: a review reads many files of the
14
+ // same directories, and listing a large one takes hundreds of milliseconds.
15
+ export class WorkingTree {
16
+ root;
17
+ realRoot;
18
+ listings = new Map();
19
+ constructor(root) {
20
+ this.root = root;
21
+ }
22
+ // `inside` is relative to the root and inside it.
23
+ async read(inside) {
24
+ try {
25
+ this.realRoot ??= realpath(this.root);
26
+ const path = await this.locate(await this.realRoot, inside.split(sep));
27
+ if (path === undefined)
28
+ return undefined;
29
+ return await readListed(path);
30
+ }
31
+ catch (error) {
32
+ const code = errnoCode(error);
33
+ if (code === "ENOENT" || code === "ENOTDIR")
34
+ return undefined;
35
+ throw error;
36
+ }
37
+ }
38
+ // The path under the names the directories list, or undefined when a part
39
+ // is not listed or the parent is reached through a link.
40
+ async locate(realRoot, parts) {
41
+ let dir = realRoot;
42
+ for (const [i, part] of parts.entries()) {
43
+ const entry = await this.listed(dir, part);
44
+ if (entry === undefined)
45
+ return undefined;
46
+ const last = i === parts.length - 1;
47
+ if (!last && !entry.isDirectory())
48
+ return undefined;
49
+ dir = join(dir, entry.name);
50
+ }
51
+ // A directory the listing reports as one can still be a junction or a
52
+ // mount; the parent's real path must be the one walked.
53
+ const parent = join(dir, "..");
54
+ return (await realpath(parent)) === parent ? dir : undefined;
55
+ }
56
+ // Up to Unicode normalization: git on macOS reports names precomposed,
57
+ // whatever their form on disk.
58
+ async listed(dir, name) {
59
+ const entries = await this.list(dir);
60
+ const exact = entries.find((entry) => entry.name === name);
61
+ if (exact)
62
+ return exact;
63
+ const wanted = name.normalize("NFC");
64
+ return entries.find((entry) => entry.name.normalize("NFC") === wanted);
65
+ }
66
+ list(dir) {
67
+ let listing = this.listings.get(dir);
68
+ if (listing === undefined) {
69
+ listing = readdir(dir, { withFileTypes: true });
70
+ // A failure other than absence (too many open files) may pass.
71
+ listing.catch(() => this.listings.delete(dir));
72
+ this.listings.set(dir, listing);
73
+ }
74
+ return listing;
75
+ }
76
+ }
77
+ async function readListed(path) {
78
+ const stat = await lstat(path);
79
+ if (stat.isSymbolicLink())
80
+ return await readlink(path, "utf8");
81
+ if (!stat.isFile())
82
+ return undefined;
83
+ if (stat.size <= MAX_READ_BYTES)
84
+ return await readFile(path, "utf8");
85
+ const handle = await open(path, "r");
86
+ try {
87
+ const buffer = Buffer.alloc(MAX_READ_BYTES);
88
+ const { bytesRead } = await handle.read(buffer, 0, MAX_READ_BYTES, 0);
89
+ return buffer.subarray(0, bytesRead).toString("utf8");
90
+ }
91
+ finally {
92
+ await handle.close();
93
+ }
94
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/vcs-local",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Local git adapter for Open-CR-Agent: working tree, ranges and commits",
5
5
  "keywords": [
6
6
  "code-review",
@@ -37,8 +37,8 @@
37
37
  "!dist/**/*.map"
38
38
  ],
39
39
  "dependencies": {
40
- "@open-cr-agent/core": "0.7.0",
41
- "zod": "^4.6.5"
40
+ "@open-cr-agent/core": "0.9.0",
41
+ "zod": "^4.6.6"
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"