@mrclrchtr/supi-review 3.1.0 → 4.0.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 (47) hide show
  1. package/README.md +41 -20
  2. package/node_modules/@mrclrchtr/supi-core/package.json +2 -4
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +0 -4
  4. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +3 -2
  5. package/node_modules/@mrclrchtr/supi-core/src/index.ts +0 -4
  6. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +0 -10
  7. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +19 -15
  8. package/package.json +2 -2
  9. package/src/git-choices.ts +42 -0
  10. package/src/git-command.ts +172 -2
  11. package/src/git.ts +126 -294
  12. package/src/history/collect.ts +15 -6
  13. package/src/review-input.ts +36 -0
  14. package/src/review-limits.ts +12 -0
  15. package/src/review-path.ts +18 -12
  16. package/src/review-result.ts +26 -5
  17. package/src/review.ts +150 -62
  18. package/src/session/review-artifact-store.ts +97 -0
  19. package/src/session/review-plan-store.ts +93 -12
  20. package/src/target/change-metadata.ts +125 -0
  21. package/src/target/diff.ts +43 -0
  22. package/src/target/file-manifest.ts +40 -0
  23. package/src/target/packet.ts +17 -6
  24. package/src/target/resolve.ts +209 -0
  25. package/src/tool/agent-review-schemas.ts +9 -4
  26. package/src/tool/agent-review-tools.ts +46 -14
  27. package/src/tool/child-failure-diagnostics.ts +26 -49
  28. package/src/tool/child-lifecycle-trace.ts +3 -16
  29. package/src/tool/child-session-runner.ts +28 -11
  30. package/src/tool/child-usage.ts +73 -0
  31. package/src/tool/diagnostic-sanitizer.ts +35 -0
  32. package/src/tool/output-page.ts +26 -0
  33. package/src/tool/planner-runner.ts +28 -10
  34. package/src/tool/review-output-tool.ts +93 -0
  35. package/src/tool/review-runner.ts +9 -7
  36. package/src/tool/review-tools.ts +90 -12
  37. package/src/tool/review-workflow.ts +146 -82
  38. package/src/tool/schemas.ts +24 -5
  39. package/src/tool/session-lifecycle.ts +44 -54
  40. package/src/tool/usage-format.ts +15 -0
  41. package/src/tui/common.ts +8 -13
  42. package/src/tui/prepare.ts +57 -31
  43. package/src/tui/run.ts +13 -3
  44. package/src/types.ts +60 -21
  45. package/node_modules/@mrclrchtr/supi-core/src/abort-utils.ts +0 -31
  46. package/node_modules/@mrclrchtr/supi-core/src/substrate-types.ts +0 -11
  47. package/node_modules/@mrclrchtr/supi-core/src/types.ts +0 -2
package/src/git.ts CHANGED
@@ -3,247 +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 DIFF_FLAGS = ["--no-ext-diff", "--no-textconv", "--binary"] as const;
21
-
22
- function parseNullList(text: string): string[] {
23
- return text
24
- .split("\0")
25
- .filter(Boolean)
26
- .sort((left, right) => left.localeCompare(right));
27
- }
28
-
29
- /** Count patch additions and deletions without interpreting binary payloads. */
30
- export function parseDiffStats(text: string, fileCount?: number): DiffStats {
31
- let additions = 0;
32
- let deletions = 0;
33
- let files = 0;
34
- for (const line of text.split("\n")) {
35
- if (line.startsWith("diff --git ")) files++;
36
- else if (line.startsWith("+") && !line.startsWith("+++")) additions++;
37
- else if (line.startsWith("-") && !line.startsWith("---")) deletions++;
38
- }
39
- return { files: fileCount ?? files, additions, deletions };
40
- }
41
-
42
- async function resolveCommit(cwd: string, value: string): Promise<string | undefined> {
43
- const canonical = (await gitAllowExit(cwd, ["rev-parse", "--verify", value], [1, 128])).trim();
44
- if (!canonical) return undefined;
45
- const type = (await gitAllowExit(cwd, ["cat-file", "-t", canonical], [128])).trim();
46
- if (type !== "commit") return undefined;
47
- return canonical.toLowerCase();
48
- }
49
-
50
- async function headCommit(cwd: string): Promise<string | undefined> {
51
- const value = (
52
- await gitAllowExit(
53
- cwd,
54
- [
55
- "rev-parse",
56
- "--verify",
57
- // biome-ignore lint/security/noSecrets: Git revision syntax, not a secret
58
- "HEAD^{commit}",
59
- ],
60
- [1, 128],
61
- )
62
- ).trim();
63
- return value || undefined;
64
- }
65
-
66
- async function commitParent(cwd: string, commit: string): Promise<string | undefined> {
67
- const body = await git(cwd, ["cat-file", "-p", commit]);
68
- const parent = body.match(/^parent ([0-9a-f]+)$/m)?.[1];
69
- if (!parent) return undefined;
70
- const type = (await gitAllowExit(cwd, ["cat-file", "-t", parent], [128])).trim();
71
- if (type !== "commit") {
72
- throw new Error(`First parent ${parent} for ${commit} is unavailable.`);
73
- }
74
- return parent;
75
- }
76
-
77
- function joinDiffs(parts: string[]): string {
78
- return parts
79
- .filter(Boolean)
80
- .map((part) => (part.endsWith("\n") ? part : `${part}\n`))
81
- .join("");
82
- }
83
-
84
- async function diffUntrackedFile(cwd: string, path: string): Promise<string> {
85
- const safe = resolveReviewPath(cwd, path);
86
- return gitAllowExit(
87
- cwd,
88
- literalPathspec(["diff", ...DIFF_FLAGS, "--no-index", "--", "/dev/null", safe.path]),
89
- [1],
90
- );
91
- }
92
-
93
- async function workingTreeSnapshot(cwd: string): Promise<ReviewSnapshot | undefined> {
94
- const head = await headCommit(cwd);
95
- if (!head) return undefined;
96
- return withHeadIndex(cwd, head, async (indexFile) => {
97
- const [trackedDiff, tracked, untrackedText] = await Promise.all([
98
- git(cwd, ["diff", ...DIFF_FLAGS, "HEAD"], indexFile),
99
- git(cwd, ["diff", "--name-only", "-z", "HEAD"], indexFile),
100
- git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"], indexFile),
101
- ]);
102
- const untracked = parseNullList(untrackedText);
103
- const changedFiles = Array.from(new Set([...parseNullList(tracked), ...untracked])).sort();
104
- if (changedFiles.length === 0) return undefined;
105
- const diffText = joinDiffs([
106
- trackedDiff,
107
- ...(await Promise.all(untracked.map((path) => diffUntrackedFile(cwd, path)))),
108
- ]);
109
- return {
110
- requestedTarget: { kind: "working-tree" },
111
- target: { kind: "working-tree", headCommit: head },
112
- title: "Working tree changes",
113
- changedFiles,
114
- diffText,
115
- stats: parseDiffStats(diffText, changedFiles.length),
116
- };
117
- });
118
- }
119
-
120
- async function comparisonSnapshot(
121
- cwd: string,
122
- requested: Extract<ReviewTargetSpec, { kind: "comparison" }>,
123
- ): Promise<ReviewSnapshot | undefined> {
124
- const [base, head] = await Promise.all([
125
- resolveCommit(cwd, requested.baseCommit),
126
- headCommit(cwd),
127
- ]);
128
- if (!base) {
129
- throw new Error(`Commit ${requested.baseCommit.slice(0, 7)} not found in this repository.`);
130
- }
131
- if (!head) {
132
- throw new Error("No HEAD commit found in this repository.");
133
- }
134
- const mergeBase = (await gitAllowExit(cwd, ["merge-base", base, head], [1])).trim();
135
- if (!mergeBase) {
136
- throw new Error(`No common ancestor between ${base.slice(0, 7)} and ${head.slice(0, 7)}.`);
137
- }
138
- const [diffText, names] = await Promise.all([
139
- git(cwd, ["diff", ...DIFF_FLAGS, mergeBase, head]),
140
- git(cwd, ["diff", "--name-only", "-z", mergeBase, head]),
141
- ]);
142
- const changedFiles = parseNullList(names);
143
- if (changedFiles.length === 0) return undefined;
144
- return {
145
- requestedTarget: requested,
146
- target: {
147
- kind: "comparison",
148
- requestedBaseCommit: base,
149
- mergeBaseCommit: mergeBase,
150
- headCommit: head,
151
- },
152
- title: `Changes ${mergeBase.slice(0, 7)}..${head.slice(0, 7)}`,
153
- changedFiles,
154
- diffText,
155
- stats: parseDiffStats(diffText, changedFiles.length),
156
- };
157
- }
158
-
159
- async function commitSnapshot(
160
- cwd: string,
161
- requested: Extract<ReviewTargetSpec, { kind: "commit" }>,
162
- ): Promise<ReviewSnapshot | undefined> {
163
- const commit = await resolveCommit(cwd, requested.commit);
164
- if (!commit) {
165
- throw new Error(`Commit ${requested.commit.slice(0, 7)} not found in this repository.`);
166
- }
167
- const parent = await commitParent(cwd, commit);
168
- const [diffText, names] = await Promise.all([
169
- parent
170
- ? git(cwd, ["diff", ...DIFF_FLAGS, parent, commit])
171
- : git(cwd, ["show", ...DIFF_FLAGS, "--format=", "--root", commit]),
172
- parent
173
- ? git(cwd, ["diff", "--name-only", "-z", parent, commit])
174
- : git(cwd, ["diff-tree", "--root", "--no-commit-id", "--name-only", "-r", "-z", commit]),
175
- ]);
176
- const changedFiles = parseNullList(names);
177
- if (changedFiles.length === 0) return undefined;
178
- return {
179
- requestedTarget: requested,
180
- target: { kind: "commit", commit, ...(parent ? { parentCommit: parent } : {}) },
181
- title: `Commit ${commit.slice(0, 7)}`,
182
- changedFiles,
183
- diffText,
184
- stats: parseDiffStats(diffText, changedFiles.length),
185
- };
186
- }
187
-
188
- export interface CommitChoice {
189
- commit: string;
190
- label: string;
191
- }
192
-
193
- /** List local branches with resolved commit ids for the interactive adapter. */
194
- export async function listLocalBranches(cwd: string): Promise<CommitChoice[]> {
195
- const output = await git(cwd, [
196
- "for-each-ref",
197
- // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
198
- "--format=%(objectname)%00%(refname:short)",
199
- "refs/heads",
200
- ]);
201
- return output
202
- .trim()
203
- .split("\n")
204
- .flatMap((line) => {
205
- const [commit, label] = line.split("\0");
206
- return commit && label ? [{ commit, label }] : [];
207
- });
208
- }
209
-
210
- /** List recent commits with resolved ids for the interactive adapter. */
211
- export async function listRecentCommits(cwd: string, limit = 30): Promise<CommitChoice[]> {
212
- const output = await git(cwd, [
213
- "log",
214
- `--max-count=${limit}`,
215
- // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
216
- "--format=%H%x00%s",
217
- ]);
218
- return output
219
- .trim()
220
- .split("\n")
221
- .flatMap((line) => {
222
- const [commit, subject] = line.split("\0");
223
- return commit && subject ? [{ commit, label: `${commit.slice(0, 7)} ${subject}` }] : [];
224
- });
225
- }
226
-
227
- /** Pin target identities and capture the target's changed files, patch, and stats. */
228
- export function resolveReviewSnapshot(
229
- cwd: string,
230
- target: ReviewTargetSpec,
231
- ): Promise<ReviewSnapshot | undefined> {
232
- switch (target.kind) {
233
- case "working-tree":
234
- return workingTreeSnapshot(cwd);
235
- case "comparison":
236
- return comparisonSnapshot(cwd, target);
237
- case "commit":
238
- return commitSnapshot(cwd, target);
239
- }
240
- }
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";
241
21
 
242
- /** Remove the potentially large patch while retaining pinned target metadata. */
243
- export function summarizeReviewSnapshot(snapshot: ReviewSnapshot): ReviewSnapshotSummary {
244
- const { diffText: _, ...summary } = snapshot;
245
- return summary;
246
- }
22
+ export { resolveReviewSnapshot, summarizeReviewSnapshot } from "./target/resolve.ts";
247
23
 
248
24
  async function showBlob(
249
25
  cwd: string,
@@ -259,8 +35,25 @@ async function showBlob(
259
35
  }
260
36
  }
261
37
 
262
- async function isWorkingTreePathAllowed(cwd: string, head: string, path: string): Promise<boolean> {
263
- 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) => {
264
57
  const output = await git(
265
58
  cwd,
266
59
  literalPathspec(["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", path]),
@@ -272,120 +65,159 @@ async function isWorkingTreePathAllowed(cwd: string, head: string, path: string)
272
65
 
273
66
  /** Read one before/after file from the target rather than an unrelated live checkout. */
274
67
  export async function readReviewFile(
275
- cwd: string,
68
+ _cwd: string,
276
69
  snapshot: ReviewSnapshot,
277
70
  path: string,
278
71
  side: "before" | "after" = "after",
279
72
  ): Promise<string | undefined> {
280
- const safe = resolveReviewPath(cwd, path);
73
+ const root = snapshot.repositoryRoot;
74
+ const safe = resolveReviewPath(root, path);
281
75
  const target = snapshot.target;
282
76
  if (target.kind === "working-tree") {
283
- if (side === "before") return showBlob(cwd, target.headCommit, safe.path);
284
- 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))) {
285
81
  throw new Error(`${safe.path} is not part of the selected working-tree target.`);
286
82
  }
287
- return readWorkingTreeFile(cwd, safe.path);
83
+ return readWorkingTreeFile(root, safe.path);
288
84
  }
289
85
  if (target.kind === "comparison") {
290
- 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
+ );
291
91
  }
292
- 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
+ });
293
121
  }
294
122
 
295
- /** 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. */
296
124
  export async function readReviewDiff(
297
- cwd: string,
125
+ _cwd: string,
298
126
  snapshot: ReviewSnapshot,
299
- path: string,
127
+ path?: string,
300
128
  ): Promise<string> {
301
- const safe = resolveReviewPath(cwd, path);
302
- 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)) {
303
132
  throw new Error(`${safe.path} is not changed by this target.`);
304
133
  }
305
134
  const target = snapshot.target;
306
135
  if (target.kind === "working-tree") {
307
- return withHeadIndex(cwd, target.headCommit, async (indexFile) => {
308
- const tracked = await git(
309
- cwd,
310
- literalPathspec(["diff", ...DIFF_FLAGS, "HEAD", "--", safe.path]),
311
- indexFile,
312
- );
313
- return tracked || diffUntrackedFile(cwd, safe.path);
314
- });
136
+ return readWorkingTreeDiff(root, target, safe?.path);
315
137
  }
138
+ const pathArgs = safe ? ["--", safe.path] : [];
316
139
  if (target.kind === "comparison") {
317
140
  return git(
318
- cwd,
141
+ root,
319
142
  literalPathspec([
320
143
  "diff",
321
144
  ...DIFF_FLAGS,
322
145
  target.mergeBaseCommit,
323
146
  target.headCommit,
324
- "--",
325
- safe.path,
147
+ ...pathArgs,
326
148
  ]),
327
149
  );
328
150
  }
329
151
  return target.parentCommit
330
152
  ? git(
331
- cwd,
332
- literalPathspec([
333
- "diff",
334
- ...DIFF_FLAGS,
335
- target.parentCommit,
336
- target.commit,
337
- "--",
338
- safe.path,
339
- ]),
153
+ root,
154
+ literalPathspec(["diff", ...DIFF_FLAGS, target.parentCommit, target.commit, ...pathArgs]),
340
155
  )
341
156
  : git(
342
- cwd,
343
- literalPathspec([
344
- "show",
345
- ...DIFF_FLAGS,
346
- "--format=",
347
- "--root",
348
- target.commit,
349
- "--",
350
- safe.path,
351
- ]),
157
+ root,
158
+ literalPathspec(["show", ...DIFF_FLAGS, "--format=", "--root", target.commit, ...pathArgs]),
352
159
  );
353
160
  }
354
161
 
355
162
  /** List files present on the target's after side, excluding ignored untracked files. */
356
- 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;
357
165
  const target = snapshot.target;
358
166
  if (target.kind !== "working-tree") {
359
167
  const commit = target.kind === "comparison" ? target.headCommit : target.commit;
360
- 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]));
361
169
  }
362
- return withHeadIndex(cwd, target.headCommit, async (indexFile) => {
170
+ return withWorkingTreeIndex(root, target, async (indexFile) => {
363
171
  const candidates = parseNullList(
364
- await git(cwd, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], indexFile),
172
+ await git(root, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], indexFile),
365
173
  );
366
- return filterExistingReviewPaths(cwd, candidates);
174
+ return filterExistingReviewPaths(root, candidates);
367
175
  });
368
176
  }
369
177
 
370
- /** 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. */
371
197
  export async function searchReviewFiles(
372
- cwd: string,
198
+ _cwd: string,
373
199
  snapshot: ReviewSnapshot,
374
200
  query: string,
375
- path?: string,
201
+ options: ReviewSearchOptions = {},
376
202
  ): Promise<string> {
377
- const pathArgs = path ? ["--", resolveReviewPath(cwd, path).path] : [];
203
+ const root = snapshot.repositoryRoot;
204
+ const pathArgs = options.path ? ["--", resolveReviewPath(root, options.path).path] : [];
378
205
  const target = snapshot.target;
379
- const args = literalPathspec(["grep", "-n", "-F", "--untracked", "-e", query, ...pathArgs]);
380
- if (target.kind === "working-tree") {
381
- return withHeadIndex(cwd, target.headCommit, (indexFile) =>
382
- 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),
383
213
  );
384
214
  }
385
- const commit = target.kind === "comparison" ? target.headCommit : target.commit;
215
+
216
+ const commit = resolveSearchCommit(target, side);
217
+ if (!commit) return "";
386
218
  return gitAllowExit(
387
- cwd,
388
- literalPathspec(["grep", "-n", "-F", "-e", query, commit, ...pathArgs]),
219
+ root,
220
+ literalPathspec(["grep", "-n", modeFlag, "-e", query, commit, ...pathArgs]),
389
221
  [1],
390
222
  );
391
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
  }