@mrclrchtr/supi-review 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +41 -20
  2. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  3. package/package.json +2 -2
  4. package/src/git-choices.ts +42 -0
  5. package/src/git-command.ts +172 -2
  6. package/src/git.ts +126 -291
  7. package/src/history/collect.ts +15 -6
  8. package/src/review-input.ts +36 -0
  9. package/src/review-limits.ts +12 -0
  10. package/src/review-path.ts +18 -12
  11. package/src/review-result.ts +26 -5
  12. package/src/review.ts +201 -76
  13. package/src/session/review-artifact-store.ts +97 -0
  14. package/src/session/review-plan-store.ts +93 -12
  15. package/src/target/change-metadata.ts +125 -0
  16. package/src/target/diff.ts +43 -0
  17. package/src/target/file-manifest.ts +40 -0
  18. package/src/target/packet.ts +17 -6
  19. package/src/target/resolve.ts +209 -0
  20. package/src/tool/agent-review-schemas.ts +21 -9
  21. package/src/tool/agent-review-tools.ts +66 -17
  22. package/src/tool/child-failure-diagnostics.ts +35 -0
  23. package/src/tool/child-lifecycle-trace.ts +27 -11
  24. package/src/tool/child-session-runner.ts +28 -11
  25. package/src/tool/child-usage.ts +73 -0
  26. package/src/tool/diagnostic-sanitizer.ts +35 -0
  27. package/src/tool/output-page.ts +26 -0
  28. package/src/tool/planner-runner.ts +28 -10
  29. package/src/tool/review-output-tool.ts +93 -0
  30. package/src/tool/review-runner.ts +9 -7
  31. package/src/tool/review-tools.ts +90 -12
  32. package/src/tool/review-workflow.ts +163 -83
  33. package/src/tool/schemas.ts +24 -5
  34. package/src/tool/session-lifecycle.ts +44 -54
  35. package/src/tool/usage-format.ts +15 -0
  36. package/src/tui/common.ts +58 -1
  37. package/src/tui/prepare.ts +57 -31
  38. package/src/tui/run.ts +13 -3
  39. package/src/types.ts +62 -19
package/src/git.ts CHANGED
@@ -3,244 +3,23 @@ import {
3
3
  runGit as git,
4
4
  runGitAllowExit as gitAllowExit,
5
5
  literalPathspec,
6
- withHeadIndex,
6
+ withReviewIndex,
7
7
  } from "./git-command.ts";
8
8
  import {
9
9
  filterExistingReviewPaths,
10
10
  readWorkingTreeFile,
11
11
  resolveReviewPath,
12
12
  } from "./review-path.ts";
13
- import type {
14
- DiffStats,
15
- ReviewSnapshot,
16
- ReviewSnapshotSummary,
17
- ReviewTargetSpec,
18
- } from "./types.ts";
19
-
20
- const FULL_COMMIT_ID_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
21
- const DIFF_FLAGS = ["--no-ext-diff", "--no-textconv", "--binary"] as const;
22
-
23
- function parseNullList(text: string): string[] {
24
- return text
25
- .split("\0")
26
- .filter(Boolean)
27
- .sort((left, right) => left.localeCompare(right));
28
- }
29
-
30
- /** Count patch additions and deletions without interpreting binary payloads. */
31
- export function parseDiffStats(text: string, fileCount?: number): DiffStats {
32
- let additions = 0;
33
- let deletions = 0;
34
- let files = 0;
35
- for (const line of text.split("\n")) {
36
- if (line.startsWith("diff --git ")) files++;
37
- else if (line.startsWith("+") && !line.startsWith("+++")) additions++;
38
- else if (line.startsWith("-") && !line.startsWith("---")) deletions++;
39
- }
40
- return { files: fileCount ?? files, additions, deletions };
41
- }
42
-
43
- /** Validate the agent-facing full Git object-id syntax before invoking Git. */
44
- export function isFullCommitId(value: string): boolean {
45
- return FULL_COMMIT_ID_RE.test(value);
46
- }
47
-
48
- async function resolveCommit(cwd: string, value: string): Promise<string | undefined> {
49
- if (!isFullCommitId(value)) return undefined;
50
- const type = (await gitAllowExit(cwd, ["cat-file", "-t", value], [128])).trim();
51
- if (type !== "commit") return undefined;
52
- const canonical = (await git(cwd, ["rev-parse", "--verify", value])).trim().toLowerCase();
53
- return canonical === value.toLowerCase() ? canonical : undefined;
54
- }
55
-
56
- async function headCommit(cwd: string): Promise<string | undefined> {
57
- const value = (
58
- await gitAllowExit(
59
- cwd,
60
- [
61
- "rev-parse",
62
- "--verify",
63
- // biome-ignore lint/security/noSecrets: Git revision syntax, not a secret
64
- "HEAD^{commit}",
65
- ],
66
- [1, 128],
67
- )
68
- ).trim();
69
- return value || undefined;
70
- }
71
-
72
- async function commitParent(cwd: string, commit: string): Promise<string | undefined> {
73
- const body = await git(cwd, ["cat-file", "-p", commit]);
74
- const parent = body.match(/^parent ([0-9a-f]+)$/m)?.[1];
75
- if (!parent) return undefined;
76
- const type = (await gitAllowExit(cwd, ["cat-file", "-t", parent], [128])).trim();
77
- if (type !== "commit") {
78
- throw new Error(`First parent ${parent} for ${commit} is unavailable.`);
79
- }
80
- return parent;
81
- }
82
-
83
- function joinDiffs(parts: string[]): string {
84
- return parts
85
- .filter(Boolean)
86
- .map((part) => (part.endsWith("\n") ? part : `${part}\n`))
87
- .join("");
88
- }
89
-
90
- async function diffUntrackedFile(cwd: string, path: string): Promise<string> {
91
- const safe = resolveReviewPath(cwd, path);
92
- return gitAllowExit(
93
- cwd,
94
- literalPathspec(["diff", ...DIFF_FLAGS, "--no-index", "--", "/dev/null", safe.path]),
95
- [1],
96
- );
97
- }
98
-
99
- async function workingTreeSnapshot(cwd: string): Promise<ReviewSnapshot | undefined> {
100
- const head = await headCommit(cwd);
101
- if (!head) return undefined;
102
- return withHeadIndex(cwd, head, async (indexFile) => {
103
- const [trackedDiff, tracked, untrackedText] = await Promise.all([
104
- git(cwd, ["diff", ...DIFF_FLAGS, "HEAD"], indexFile),
105
- git(cwd, ["diff", "--name-only", "-z", "HEAD"], indexFile),
106
- git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"], indexFile),
107
- ]);
108
- const untracked = parseNullList(untrackedText);
109
- const changedFiles = Array.from(new Set([...parseNullList(tracked), ...untracked])).sort();
110
- if (changedFiles.length === 0) return undefined;
111
- const diffText = joinDiffs([
112
- trackedDiff,
113
- ...(await Promise.all(untracked.map((path) => diffUntrackedFile(cwd, path)))),
114
- ]);
115
- return {
116
- requestedTarget: { kind: "working-tree" },
117
- target: { kind: "working-tree", headCommit: head },
118
- title: "Working tree changes",
119
- changedFiles,
120
- diffText,
121
- stats: parseDiffStats(diffText, changedFiles.length),
122
- };
123
- });
124
- }
125
-
126
- async function comparisonSnapshot(
127
- cwd: string,
128
- requested: Extract<ReviewTargetSpec, { kind: "comparison" }>,
129
- ): Promise<ReviewSnapshot | undefined> {
130
- const [base, head] = await Promise.all([
131
- resolveCommit(cwd, requested.baseCommit),
132
- headCommit(cwd),
133
- ]);
134
- if (!base || !head) return undefined;
135
- const mergeBase = (await gitAllowExit(cwd, ["merge-base", base, head], [1])).trim();
136
- if (!mergeBase) return undefined;
137
- const [diffText, names] = await Promise.all([
138
- git(cwd, ["diff", ...DIFF_FLAGS, mergeBase, head]),
139
- git(cwd, ["diff", "--name-only", "-z", mergeBase, head]),
140
- ]);
141
- const changedFiles = parseNullList(names);
142
- if (changedFiles.length === 0) return undefined;
143
- return {
144
- requestedTarget: requested,
145
- target: {
146
- kind: "comparison",
147
- requestedBaseCommit: base,
148
- mergeBaseCommit: mergeBase,
149
- headCommit: head,
150
- },
151
- title: `Changes ${mergeBase.slice(0, 7)}..${head.slice(0, 7)}`,
152
- changedFiles,
153
- diffText,
154
- stats: parseDiffStats(diffText, changedFiles.length),
155
- };
156
- }
157
-
158
- async function commitSnapshot(
159
- cwd: string,
160
- requested: Extract<ReviewTargetSpec, { kind: "commit" }>,
161
- ): Promise<ReviewSnapshot | undefined> {
162
- const commit = await resolveCommit(cwd, requested.commit);
163
- if (!commit) return undefined;
164
- const parent = await commitParent(cwd, commit);
165
- const [diffText, names] = await Promise.all([
166
- parent
167
- ? git(cwd, ["diff", ...DIFF_FLAGS, parent, commit])
168
- : git(cwd, ["show", ...DIFF_FLAGS, "--format=", "--root", commit]),
169
- parent
170
- ? git(cwd, ["diff", "--name-only", "-z", parent, commit])
171
- : git(cwd, ["diff-tree", "--root", "--no-commit-id", "--name-only", "-r", "-z", commit]),
172
- ]);
173
- const changedFiles = parseNullList(names);
174
- if (changedFiles.length === 0) return undefined;
175
- return {
176
- requestedTarget: requested,
177
- target: { kind: "commit", commit, ...(parent ? { parentCommit: parent } : {}) },
178
- title: `Commit ${commit.slice(0, 7)}`,
179
- changedFiles,
180
- diffText,
181
- stats: parseDiffStats(diffText, changedFiles.length),
182
- };
183
- }
184
-
185
- export interface CommitChoice {
186
- commit: string;
187
- label: string;
188
- }
189
-
190
- /** List local branches with resolved commit ids for the interactive adapter. */
191
- export async function listLocalBranches(cwd: string): Promise<CommitChoice[]> {
192
- const output = await git(cwd, [
193
- "for-each-ref",
194
- // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
195
- "--format=%(objectname)%00%(refname:short)",
196
- "refs/heads",
197
- ]);
198
- return output
199
- .trim()
200
- .split("\n")
201
- .flatMap((line) => {
202
- const [commit, label] = line.split("\0");
203
- return commit && label ? [{ commit, label }] : [];
204
- });
205
- }
206
-
207
- /** List recent commits with resolved ids for the interactive adapter. */
208
- export async function listRecentCommits(cwd: string, limit = 30): Promise<CommitChoice[]> {
209
- const output = await git(cwd, [
210
- "log",
211
- `--max-count=${limit}`,
212
- // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
213
- "--format=%H%x00%s",
214
- ]);
215
- return output
216
- .trim()
217
- .split("\n")
218
- .flatMap((line) => {
219
- const [commit, subject] = line.split("\0");
220
- return commit && subject ? [{ commit, label: `${commit.slice(0, 7)} ${subject}` }] : [];
221
- });
222
- }
223
-
224
- /** Pin target identities and capture the target's changed files, patch, and stats. */
225
- export function resolveReviewSnapshot(
226
- cwd: string,
227
- target: ReviewTargetSpec,
228
- ): Promise<ReviewSnapshot | undefined> {
229
- switch (target.kind) {
230
- case "working-tree":
231
- return workingTreeSnapshot(cwd);
232
- case "comparison":
233
- return comparisonSnapshot(cwd, target);
234
- case "commit":
235
- return commitSnapshot(cwd, target);
236
- }
237
- }
13
+ import {
14
+ assertFullDiffCharacters,
15
+ DIFF_FLAGS,
16
+ diffUntrackedFile,
17
+ joinDiffParts,
18
+ parseNullList,
19
+ } from "./target/diff.ts";
20
+ import type { ResolvedReviewTarget, ReviewSnapshot } from "./types.ts";
238
21
 
239
- /** Remove the potentially large patch while retaining pinned target metadata. */
240
- export function summarizeReviewSnapshot(snapshot: ReviewSnapshot): ReviewSnapshotSummary {
241
- const { diffText: _, ...summary } = snapshot;
242
- return summary;
243
- }
22
+ export { resolveReviewSnapshot, summarizeReviewSnapshot } from "./target/resolve.ts";
244
23
 
245
24
  async function showBlob(
246
25
  cwd: string,
@@ -256,8 +35,25 @@ async function showBlob(
256
35
  }
257
36
  }
258
37
 
259
- async function isWorkingTreePathAllowed(cwd: string, head: string, path: string): Promise<boolean> {
260
- return withHeadIndex(cwd, head, async (indexFile) => {
38
+ function withWorkingTreeIndex<T>(
39
+ cwd: string,
40
+ target: Extract<ResolvedReviewTarget, { kind: "working-tree" }>,
41
+ operation: (indexFile: string) => Promise<T>,
42
+ ): Promise<T> {
43
+ return withReviewIndex(
44
+ cwd,
45
+ target.headCommit,
46
+ target.mergeBaseCommit ?? target.headCommit,
47
+ operation,
48
+ );
49
+ }
50
+
51
+ async function isWorkingTreePathAllowed(
52
+ cwd: string,
53
+ target: Extract<ResolvedReviewTarget, { kind: "working-tree" }>,
54
+ path: string,
55
+ ): Promise<boolean> {
56
+ return withWorkingTreeIndex(cwd, target, async (indexFile) => {
261
57
  const output = await git(
262
58
  cwd,
263
59
  literalPathspec(["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", path]),
@@ -269,120 +65,159 @@ async function isWorkingTreePathAllowed(cwd: string, head: string, path: string)
269
65
 
270
66
  /** Read one before/after file from the target rather than an unrelated live checkout. */
271
67
  export async function readReviewFile(
272
- cwd: string,
68
+ _cwd: string,
273
69
  snapshot: ReviewSnapshot,
274
70
  path: string,
275
71
  side: "before" | "after" = "after",
276
72
  ): Promise<string | undefined> {
277
- const safe = resolveReviewPath(cwd, path);
73
+ const root = snapshot.repositoryRoot;
74
+ const safe = resolveReviewPath(root, path);
278
75
  const target = snapshot.target;
279
76
  if (target.kind === "working-tree") {
280
- if (side === "before") return showBlob(cwd, target.headCommit, safe.path);
281
- if (!(await isWorkingTreePathAllowed(cwd, target.headCommit, safe.path))) {
77
+ if (side === "before") {
78
+ return showBlob(root, target.mergeBaseCommit ?? target.headCommit, safe.path);
79
+ }
80
+ if (!(await isWorkingTreePathAllowed(root, target, safe.path))) {
282
81
  throw new Error(`${safe.path} is not part of the selected working-tree target.`);
283
82
  }
284
- return readWorkingTreeFile(cwd, safe.path);
83
+ return readWorkingTreeFile(root, safe.path);
285
84
  }
286
85
  if (target.kind === "comparison") {
287
- return showBlob(cwd, side === "before" ? target.mergeBaseCommit : target.headCommit, safe.path);
86
+ return showBlob(
87
+ root,
88
+ side === "before" ? target.mergeBaseCommit : target.headCommit,
89
+ safe.path,
90
+ );
288
91
  }
289
- return showBlob(cwd, side === "before" ? target.parentCommit : target.commit, safe.path);
92
+ return showBlob(root, side === "before" ? target.parentCommit : target.commit, safe.path);
93
+ }
94
+
95
+ async function readWorkingTreeDiff(
96
+ root: string,
97
+ target: Extract<ResolvedReviewTarget, { kind: "working-tree" }>,
98
+ path?: string,
99
+ ): Promise<string> {
100
+ return withWorkingTreeIndex(root, target, async (indexFile) => {
101
+ const baseline = target.mergeBaseCommit ?? target.headCommit;
102
+ const pathArgs = path ? ["--", path] : [];
103
+ const [tracked, untrackedText] = await Promise.all([
104
+ git(root, literalPathspec(["diff", ...DIFF_FLAGS, baseline, ...pathArgs]), indexFile),
105
+ git(
106
+ root,
107
+ literalPathspec(["ls-files", "--others", "--exclude-standard", "-z", ...pathArgs]),
108
+ indexFile,
109
+ ),
110
+ ]);
111
+ const parts = [tracked];
112
+ let totalCharacters = tracked.length;
113
+ for (const untrackedPath of parseNullList(untrackedText)) {
114
+ const patch = await diffUntrackedFile(root, untrackedPath);
115
+ totalCharacters += patch.length;
116
+ assertFullDiffCharacters(totalCharacters);
117
+ parts.push(patch);
118
+ }
119
+ return joinDiffParts(parts);
120
+ });
290
121
  }
291
122
 
292
- /** Read one changed file's patch from the selected target. */
123
+ /** Read the full target patch, or one changed path's patch when `path` is supplied. */
293
124
  export async function readReviewDiff(
294
- cwd: string,
125
+ _cwd: string,
295
126
  snapshot: ReviewSnapshot,
296
- path: string,
127
+ path?: string,
297
128
  ): Promise<string> {
298
- const safe = resolveReviewPath(cwd, path);
299
- if (!snapshot.changedFiles.includes(safe.path)) {
129
+ const root = snapshot.repositoryRoot;
130
+ const safe = path ? resolveReviewPath(root, path) : undefined;
131
+ if (safe && !snapshot.changes.some((change) => change.path === safe.path)) {
300
132
  throw new Error(`${safe.path} is not changed by this target.`);
301
133
  }
302
134
  const target = snapshot.target;
303
135
  if (target.kind === "working-tree") {
304
- return withHeadIndex(cwd, target.headCommit, async (indexFile) => {
305
- const tracked = await git(
306
- cwd,
307
- literalPathspec(["diff", ...DIFF_FLAGS, "HEAD", "--", safe.path]),
308
- indexFile,
309
- );
310
- return tracked || diffUntrackedFile(cwd, safe.path);
311
- });
136
+ return readWorkingTreeDiff(root, target, safe?.path);
312
137
  }
138
+ const pathArgs = safe ? ["--", safe.path] : [];
313
139
  if (target.kind === "comparison") {
314
140
  return git(
315
- cwd,
141
+ root,
316
142
  literalPathspec([
317
143
  "diff",
318
144
  ...DIFF_FLAGS,
319
145
  target.mergeBaseCommit,
320
146
  target.headCommit,
321
- "--",
322
- safe.path,
147
+ ...pathArgs,
323
148
  ]),
324
149
  );
325
150
  }
326
151
  return target.parentCommit
327
152
  ? git(
328
- cwd,
329
- literalPathspec([
330
- "diff",
331
- ...DIFF_FLAGS,
332
- target.parentCommit,
333
- target.commit,
334
- "--",
335
- safe.path,
336
- ]),
153
+ root,
154
+ literalPathspec(["diff", ...DIFF_FLAGS, target.parentCommit, target.commit, ...pathArgs]),
337
155
  )
338
156
  : git(
339
- cwd,
340
- literalPathspec([
341
- "show",
342
- ...DIFF_FLAGS,
343
- "--format=",
344
- "--root",
345
- target.commit,
346
- "--",
347
- safe.path,
348
- ]),
157
+ root,
158
+ literalPathspec(["show", ...DIFF_FLAGS, "--format=", "--root", target.commit, ...pathArgs]),
349
159
  );
350
160
  }
351
161
 
352
162
  /** List files present on the target's after side, excluding ignored untracked files. */
353
- export async function listReviewFiles(cwd: string, snapshot: ReviewSnapshot): Promise<string[]> {
163
+ export async function listReviewFiles(_cwd: string, snapshot: ReviewSnapshot): Promise<string[]> {
164
+ const root = snapshot.repositoryRoot;
354
165
  const target = snapshot.target;
355
166
  if (target.kind !== "working-tree") {
356
167
  const commit = target.kind === "comparison" ? target.headCommit : target.commit;
357
- return parseNullList(await git(cwd, ["ls-tree", "-r", "--name-only", "-z", commit]));
168
+ return parseNullList(await git(root, ["ls-tree", "-r", "--name-only", "-z", commit]));
358
169
  }
359
- return withHeadIndex(cwd, target.headCommit, async (indexFile) => {
170
+ return withWorkingTreeIndex(root, target, async (indexFile) => {
360
171
  const candidates = parseNullList(
361
- await git(cwd, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], indexFile),
172
+ await git(root, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], indexFile),
362
173
  );
363
- return filterExistingReviewPaths(cwd, candidates);
174
+ return filterExistingReviewPaths(root, candidates);
364
175
  });
365
176
  }
366
177
 
367
- /** Search literal text on the target's after side with Git's repository-aware search. */
178
+ /** Target side, Git search mode, and optional repository-relative scope. */
179
+ export interface ReviewSearchOptions {
180
+ path?: string;
181
+ side?: "before" | "after";
182
+ mode?: "literal" | "regex";
183
+ }
184
+
185
+ function resolveSearchCommit(
186
+ target: ResolvedReviewTarget,
187
+ side: "before" | "after",
188
+ ): string | undefined {
189
+ if (target.kind === "working-tree") return target.mergeBaseCommit ?? target.headCommit;
190
+ if (target.kind === "comparison") {
191
+ return side === "before" ? target.mergeBaseCommit : target.headCommit;
192
+ }
193
+ return side === "before" ? target.parentCommit : target.commit;
194
+ }
195
+
196
+ /** Search literal or extended-regex text on either selected target side. */
368
197
  export async function searchReviewFiles(
369
- cwd: string,
198
+ _cwd: string,
370
199
  snapshot: ReviewSnapshot,
371
200
  query: string,
372
- path?: string,
201
+ options: ReviewSearchOptions = {},
373
202
  ): Promise<string> {
374
- const pathArgs = path ? ["--", resolveReviewPath(cwd, path).path] : [];
203
+ const root = snapshot.repositoryRoot;
204
+ const pathArgs = options.path ? ["--", resolveReviewPath(root, options.path).path] : [];
375
205
  const target = snapshot.target;
376
- const args = literalPathspec(["grep", "-n", "-F", "--untracked", "-e", query, ...pathArgs]);
377
- if (target.kind === "working-tree") {
378
- return withHeadIndex(cwd, target.headCommit, (indexFile) =>
379
- gitAllowExit(cwd, args, [1], indexFile),
206
+ const side = options.side ?? "after";
207
+ const modeFlag = options.mode === "regex" ? "-E" : "-F";
208
+
209
+ if (target.kind === "working-tree" && side === "after") {
210
+ const args = literalPathspec(["grep", "-n", modeFlag, "--untracked", "-e", query, ...pathArgs]);
211
+ return withWorkingTreeIndex(root, target, (indexFile) =>
212
+ gitAllowExit(root, args, [1], indexFile),
380
213
  );
381
214
  }
382
- const commit = target.kind === "comparison" ? target.headCommit : target.commit;
215
+
216
+ const commit = resolveSearchCommit(target, side);
217
+ if (!commit) return "";
383
218
  return gitAllowExit(
384
- cwd,
385
- literalPathspec(["grep", "-n", "-F", "-e", query, commit, ...pathArgs]),
219
+ root,
220
+ literalPathspec(["grep", "-n", modeFlag, "-e", query, commit, ...pathArgs]),
386
221
  [1],
387
222
  );
388
223
  }
@@ -2,6 +2,7 @@ import type { SessionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { extractVisibleText } from "../tool/runner-helpers.ts";
3
3
 
4
4
  const MAX_PLANNER_CONTEXT_CHARS = 8_000;
5
+ const MAX_SUMMARY_WITH_VISIBLE_CHARS = 3_000;
5
6
  type Message = SessionContext["messages"][number];
6
7
 
7
8
  interface PlannerRow {
@@ -31,7 +32,14 @@ function takeRecentRows(rows: string[], maxChars: number): string {
31
32
  const separator = recent.length > 0 ? 1 : 0;
32
33
  const remaining = maxChars - size - separator;
33
34
  if (row.length > remaining) {
34
- if (recent.length === 0 && remaining > 0) recent.unshift(row.slice(0, remaining));
35
+ if (recent.length === 0 && remaining > 0) {
36
+ const marker = "\n[… truncated]";
37
+ recent.unshift(
38
+ remaining > marker.length
39
+ ? `${row.slice(0, remaining - marker.length)}${marker}`
40
+ : row.slice(0, remaining),
41
+ );
42
+ }
35
43
  break;
36
44
  }
37
45
  recent.unshift(row);
@@ -46,12 +54,13 @@ export function collectPlannerContext(messages: Message[]): string {
46
54
  const row = toPlannerRow(message);
47
55
  return row ? [row] : [];
48
56
  });
49
- const summaries = rows
50
- .filter((row) => row.kind === "summary")
51
- .map((row) => row.text)
52
- .join("\n")
53
- .slice(0, MAX_PLANNER_CONTEXT_CHARS);
54
57
  const visible = rows.filter((row) => row.kind === "visible").map((row) => row.text);
58
+ const summaryBudget =
59
+ visible.length > 0 ? MAX_SUMMARY_WITH_VISIBLE_CHARS : MAX_PLANNER_CONTEXT_CHARS;
60
+ const summaries = takeRecentRows(
61
+ rows.filter((row) => row.kind === "summary").map((row) => row.text),
62
+ summaryBudget,
63
+ );
55
64
  const separator = summaries && visible.length > 0 ? 1 : 0;
56
65
  const recent = takeRecentRows(visible, MAX_PLANNER_CONTEXT_CHARS - summaries.length - separator);
57
66
  return [summaries, recent].filter(Boolean).join("\n");
@@ -0,0 +1,36 @@
1
+ import { REVIEW_LIMITS } from "./review-limits.ts";
2
+ import type { ReviewInput } from "./types.ts";
3
+
4
+ /** Canonicalize and semantically validate review input for every adapter. */
5
+ export function normalizeReviewInput(review: ReviewInput): ReviewInput {
6
+ const sharedContext = review.sharedContext?.trim();
7
+ const tasks = review.tasks.map((task) => ({
8
+ id: task.id.trim(),
9
+ instructions: task.instructions.trim(),
10
+ }));
11
+ if (tasks.length < 1 || tasks.length > 4) {
12
+ throw new Error("Provide between one and four review tasks.");
13
+ }
14
+ if (tasks.some((task) => !task.id || !task.instructions)) {
15
+ throw new Error("Review task ids and instructions must not be blank.");
16
+ }
17
+ if (tasks.some((task) => task.id.length > REVIEW_LIMITS.taskIdCharacters)) {
18
+ throw new Error(
19
+ `Review task ids must not exceed ${REVIEW_LIMITS.taskIdCharacters} characters.`,
20
+ );
21
+ }
22
+ if (tasks.some((task) => task.instructions.length > REVIEW_LIMITS.taskInstructionCharacters)) {
23
+ throw new Error(
24
+ `Review task instructions must not exceed ${REVIEW_LIMITS.taskInstructionCharacters.toLocaleString("en-US")} characters.`,
25
+ );
26
+ }
27
+ if (sharedContext && sharedContext.length > REVIEW_LIMITS.sharedContextCharacters) {
28
+ throw new Error(
29
+ `Shared review context must not exceed ${REVIEW_LIMITS.sharedContextCharacters.toLocaleString("en-US")} characters.`,
30
+ );
31
+ }
32
+ if (new Set(tasks.map((task) => task.id)).size !== tasks.length) {
33
+ throw new Error("Review task ids must be unique.");
34
+ }
35
+ return { ...(sharedContext ? { sharedContext } : {}), tasks };
36
+ }
@@ -0,0 +1,12 @@
1
+ /** Centralized provider and runtime bounds for persisted review input/output. */
2
+ export const REVIEW_LIMITS = {
3
+ taskIdCharacters: 64,
4
+ sharedContextCharacters: 16_000,
5
+ taskInstructionCharacters: 16_000,
6
+ summaryCharacters: 8_000,
7
+ findingsPerTask: 20,
8
+ findingTitleCharacters: 200,
9
+ findingDescriptionCharacters: 8_000,
10
+ locationPathCharacters: 4_096,
11
+ searchQueryCharacters: 4_096,
12
+ } as const;
@@ -1,6 +1,9 @@
1
1
  import { lstat, readFile, readlink, realpath } from "node:fs/promises";
2
2
  import { dirname, posix, relative, resolve, sep, win32 } from "node:path";
3
3
 
4
+ /** Maximum working-tree file size materialized by one review read. */
5
+ export const MAX_REVIEW_FILE_BYTES = 16 * 1024 * 1024;
6
+
4
7
  /** Verified repository-relative review path that cannot lexically escape the worktree. */
5
8
  export interface SafeReviewPath {
6
9
  absolute: string;
@@ -59,6 +62,11 @@ export async function readWorkingTreeFile(cwd: string, path: string): Promise<st
59
62
  assertInsideRepository(repository, parent, path);
60
63
  if (stat.isSymbolicLink()) return await readlink(safe.absolute);
61
64
  if (!stat.isFile()) return undefined;
65
+ if (stat.size > MAX_REVIEW_FILE_BYTES) {
66
+ throw new Error(
67
+ `${safe.path} exceeds the ${MAX_REVIEW_FILE_BYTES}-byte working-tree review read limit.`,
68
+ );
69
+ }
62
70
  const resolvedFile = await realpath(safe.absolute);
63
71
  assertInsideRepository(repository, resolvedFile, path);
64
72
  return await readFile(safe.absolute, "utf8");
@@ -70,16 +78,14 @@ export async function readWorkingTreeFile(cwd: string, path: string): Promise<st
70
78
 
71
79
  /** Remove deleted paths from a Git-produced repository-relative path list. */
72
80
  export async function filterExistingReviewPaths(cwd: string, paths: string[]): Promise<string[]> {
73
- const existing = await Promise.all(
74
- paths.map(async (path) => {
75
- try {
76
- await lstat(resolveReviewPath(cwd, path).absolute);
77
- return path;
78
- } catch (error) {
79
- if (isMissingPath(error)) return undefined;
80
- throw error;
81
- }
82
- }),
83
- );
84
- return existing.filter((path): path is string => path !== undefined);
81
+ const existing: string[] = [];
82
+ for (const path of paths) {
83
+ try {
84
+ await lstat(resolveReviewPath(cwd, path).absolute);
85
+ existing.push(path);
86
+ } catch (error) {
87
+ if (!isMissingPath(error)) throw error;
88
+ }
89
+ }
90
+ return existing;
85
91
  }