@open-cr-agent/vcs-local 0.11.0 → 0.13.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/dist/git.d.ts CHANGED
@@ -14,6 +14,14 @@ 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
+ /**
18
+ * A command's output a line at a time, never held whole. Ends early when
19
+ * `onLine` returns false, or at a line longer than `maxLineBytes`, which is
20
+ * not given.
21
+ */
22
+ export declare function gitLines(args: readonly string[], options: Pick<GitOptions, "cwd" | "okExitCodes" | "timeoutMs"> & {
23
+ maxLineBytes: number;
24
+ }, onLine: (line: string) => boolean): Promise<"ended" | "stopped" | "line_too_long">;
17
25
  export declare function childEnvironment(extra?: Readonly<Record<string, string>>): Record<string, string>;
18
26
  export declare function gitEnvironment(env: Readonly<Record<string, string | undefined>>): Record<string, string>;
19
27
  export declare function credentialEnvironment(env: Readonly<Record<string, string | undefined>>): Record<string, string>;
package/dist/git.js CHANGED
@@ -1,4 +1,4 @@
1
- import { execFile } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { OcraError } from "@open-cr-agent/core";
3
3
  import { errnoCode } from "@open-cr-agent/core/internal";
4
4
  // Every git call ends: a fetch can wait on the network forever, and a diff
@@ -59,6 +59,71 @@ export function git(args, options) {
59
59
  child.stdin?.end(options.input);
60
60
  });
61
61
  }
62
+ const STDERR_CHARS = 4_000;
63
+ /**
64
+ * A command's output a line at a time, never held whole. Ends early when
65
+ * `onLine` returns false, or at a line longer than `maxLineBytes`, which is
66
+ * not given.
67
+ */
68
+ export function gitLines(args, options, onLine) {
69
+ const okExitCodes = options.okExitCodes ?? [0];
70
+ const timeoutMs = options.timeoutMs ?? GIT_TIMEOUT_MS;
71
+ return new Promise((resolve, reject) => {
72
+ const child = spawn("git", args, {
73
+ cwd: options.cwd,
74
+ env: childEnvironment(),
75
+ stdio: ["ignore", "pipe", "pipe"],
76
+ });
77
+ let cut;
78
+ const stop = (reason) => {
79
+ cut = reason;
80
+ child.kill("SIGKILL");
81
+ };
82
+ const timer = setTimeout(() => stop("timed_out"), timeoutMs);
83
+ let pending = [];
84
+ let pendingBytes = 0;
85
+ child.stdout.on("data", (chunk) => {
86
+ let start = 0;
87
+ while (!cut) {
88
+ const end = chunk.indexOf(0x0a, start);
89
+ if (end < 0)
90
+ break;
91
+ const line = Buffer.concat([...pending, chunk.subarray(start, end)]).toString("utf8");
92
+ pending = [];
93
+ pendingBytes = 0;
94
+ start = end + 1;
95
+ if (!onLine(line))
96
+ stop("stopped");
97
+ }
98
+ if (cut || start === chunk.length)
99
+ return;
100
+ pending.push(chunk.subarray(start));
101
+ pendingBytes += chunk.length - start;
102
+ if (pendingBytes > options.maxLineBytes)
103
+ stop("line_too_long");
104
+ });
105
+ let stderr = "";
106
+ child.stderr.on("data", (chunk) => {
107
+ stderr = (stderr + chunk.toString("utf8")).slice(-STDERR_CHARS);
108
+ });
109
+ child.on("error", (error) => {
110
+ clearTimeout(timer);
111
+ reject(error);
112
+ });
113
+ child.on("close", (exitCode) => {
114
+ clearTimeout(timer);
115
+ if (cut === "timed_out") {
116
+ reject(new GitError(args, undefined, `timed out after ${Math.round(timeoutMs / 1000)}s`));
117
+ }
118
+ else if (cut)
119
+ resolve(cut);
120
+ else if (exitCode !== null && okExitCodes.includes(exitCode))
121
+ resolve("ended");
122
+ else
123
+ reject(new GitError(args, exitCode ?? undefined, stderr));
124
+ });
125
+ });
126
+ }
62
127
  export function childEnvironment(extra = {}) {
63
128
  return { ...gitEnvironment(process.env), LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", ...extra };
64
129
  }
package/dist/search.d.ts CHANGED
@@ -5,14 +5,17 @@ export interface SearchScope {
5
5
  attributes: readonly string[];
6
6
  }
7
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.
8
+ * `git grep` at a revision reads every blob of the tree on every core, so
9
+ * each search costs the same however small and two at once only take turns.
10
+ * One grep runs at a time: searches asked for in the same turn (an agent's
11
+ * tool calls, the callers of a bundle's symbols) or while another runs
12
+ * share the next, and it is stopped once each has all it returns.
11
13
  */
12
14
  export declare class CodeSearch {
13
15
  private queue;
16
+ private draining;
14
17
  private readonly scope;
15
18
  constructor(scope: () => Promise<SearchScope>);
16
19
  search(literal: string): Promise<CodeMatch[]>;
17
- private flush;
20
+ private drain;
18
21
  }
package/dist/search.js CHANGED
@@ -1,15 +1,22 @@
1
- import { git } from "./git.js";
1
+ import { gitLines } from "./git.js";
2
2
  const RESULT_LIMIT = 100;
3
3
  const MATCHES_PER_FILE = 20;
4
- const OUTPUT_BYTES = 4 * 1024 * 1024;
4
+ // What one search may read of git's output: a line of a minified bundle or
5
+ // a fixture can be megabytes.
6
+ const OUTPUT_CHARS = 4 * 1024 * 1024;
7
+ // A line that long in bytes is longer in characters than a search may read.
8
+ const MAX_LINE_BYTES = 3 * OUTPUT_CHARS;
5
9
  const BATCH_SIZE = 32;
6
10
  /**
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.
11
+ * `git grep` at a revision reads every blob of the tree on every core, so
12
+ * each search costs the same however small and two at once only take turns.
13
+ * One grep runs at a time: searches asked for in the same turn (an agent's
14
+ * tool calls, the callers of a bundle's symbols) or while another runs
15
+ * share the next, and it is stopped once each has all it returns.
10
16
  */
11
17
  export class CodeSearch {
12
18
  queue = [];
19
+ draining = false;
13
20
  scope;
14
21
  constructor(scope) {
15
22
  this.scope = scope;
@@ -18,84 +25,112 @@ export class CodeSearch {
18
25
  if (!batchable(literal))
19
26
  return this.scope().then((s) => grepOne(s, literal));
20
27
  return new Promise((resolve) => {
21
- if (this.queue.length === 0)
22
- queueMicrotask(() => this.flush());
28
+ if (this.queue.length === 0 && !this.draining)
29
+ queueMicrotask(() => void this.drain());
23
30
  this.queue.push({ literal, done: resolve });
24
31
  });
25
32
  }
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);
33
+ async drain() {
34
+ this.draining = true;
35
+ while (this.queue.length > 0) {
36
+ const batch = this.queue.splice(0, BATCH_SIZE);
31
37
  const results = this.scope().then((s) => grepMany(s, [...new Set(batch.map((q) => q.literal))]));
32
38
  for (const q of batch)
33
39
  q.done(results.then((r) => r.get(q.literal) ?? []));
40
+ await results.catch(() => undefined);
34
41
  }
42
+ this.draining = false;
35
43
  }
36
44
  }
37
45
  // A literal with a line break is several patterns to git.
38
46
  function batchable(literal) {
39
47
  return literal !== "" && !/[\r\n]/.test(literal);
40
48
  }
49
+ // What a search of one literal returns of the lines git lists for it: at
50
+ // most MATCHES_PER_FILE a file and RESULT_LIMIT in all, within OUTPUT_CHARS
51
+ // of output.
52
+ class Matches {
53
+ kept = [];
54
+ full = false;
55
+ chars = 0;
56
+ path;
57
+ inFile = 0;
58
+ // git lists a file's lines together.
59
+ add(match, lineChars) {
60
+ if (this.full)
61
+ return;
62
+ if (match.path !== this.path) {
63
+ this.path = match.path;
64
+ this.inFile = 0;
65
+ }
66
+ if (this.inFile === MATCHES_PER_FILE)
67
+ return;
68
+ this.inFile += 1;
69
+ this.chars += lineChars + 1;
70
+ if (this.chars > OUTPUT_CHARS) {
71
+ this.full = true;
72
+ return;
73
+ }
74
+ this.kept.push(match);
75
+ if (this.kept.length === RESULT_LIMIT)
76
+ this.full = true;
77
+ }
78
+ }
41
79
  async function grepMany(scope, literals) {
42
80
  if (literals.length === 1) {
43
81
  const [literal = ""] = literals;
44
82
  return new Map([[literal, await grepOne(scope, literal)]]);
45
83
  }
84
+ const found = new Map(literals.map((literal) => [literal, new Matches()]));
46
85
  // One alternation, not one -e per literal: git scans the rest of the file
47
86
  // 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] ?? []]));
87
+ const outcome = await grep(scope, ["-E", "-e", literals.map(ereLiteral).join("|")], (match, lineChars) => {
88
+ let open = false;
89
+ for (const [literal, matches] of found) {
90
+ if (match.text.includes(literal))
91
+ matches.add(match, lineChars);
92
+ open ||= !matches.full;
93
+ }
94
+ return open;
95
+ });
96
+ // Which literals a line that was not read holds is unknown.
97
+ if (outcome === "line_too_long") {
98
+ const each = new Map();
99
+ for (const literal of literals)
100
+ each.set(literal, await grepOne(scope, literal));
101
+ return each;
53
102
  }
54
- const lines = parse(scope, out);
55
- return new Map(literals.map((l) => [l, limited(lines.filter((m) => m.text.includes(l)))]));
103
+ return new Map([...found].map(([literal, matches]) => [literal, matches.kept]));
56
104
  }
57
105
  function ereLiteral(literal) {
58
106
  return literal.replace(/[\\.[\](){}*+?^$|]/g, "\\$&");
59
107
  }
60
108
  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;
109
+ const matches = new Matches();
110
+ await grep(scope, ["-F", "-m", String(MATCHES_PER_FILE), "-e", literal], (match, lineChars) => {
111
+ matches.add(match, lineChars);
112
+ return !matches.full;
113
+ });
114
+ return matches.kept;
82
115
  }
83
- function grep(scope, patterns, cap) {
116
+ // Each matching line to `onMatch`, until it returns false.
117
+ function grep(scope, patterns, onMatch) {
84
118
  const args = [...scope.attributes, "grep", "-n", "-z", "-I", "--no-color", "--full-name"];
85
119
  if (scope.head === undefined)
86
120
  args.push("--untracked");
87
121
  args.push(...patterns);
88
122
  if (scope.head !== undefined)
89
123
  args.push(scope.head);
90
- return git([...args, "--"], { cwd: scope.root, okExitCodes: [0, 1], truncateAt: cap });
91
- }
92
- function parse(scope, out) {
93
124
  const prefix = scope.head === undefined ? "" : `${scope.head}:`;
94
- return out
95
- .split("\n")
96
- .filter((line) => line !== "")
97
- .map((line) => {
125
+ return gitLines([...args, "--"], { cwd: scope.root, okExitCodes: [0, 1], maxLineBytes: MAX_LINE_BYTES }, (line) => {
126
+ if (line === "")
127
+ return true;
98
128
  const [path = "", lineNumber = "0", ...text] = line.split("\0");
99
- return { path: path.slice(prefix.length), line: Number(lineNumber), text: text.join("\0") };
129
+ const match = {
130
+ path: path.slice(prefix.length),
131
+ line: Number(lineNumber),
132
+ text: text.join("\0"),
133
+ };
134
+ return onMatch(match, line.length);
100
135
  });
101
136
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/vcs-local",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Local git adapter for Open-CR-Agent: working tree, ranges and commits",
5
5
  "keywords": [
6
6
  "code-review",
@@ -37,7 +37,7 @@
37
37
  "!dist/**/*.map"
38
38
  ],
39
39
  "dependencies": {
40
- "@open-cr-agent/core": "0.11.0",
40
+ "@open-cr-agent/core": "0.13.0",
41
41
  "zod": "^4.6.6"
42
42
  },
43
43
  "publishConfig": {