@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
@@ -0,0 +1,125 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { DiffStats, ReviewChange } from "../types.ts";
3
+
4
+ interface ParsedPathChange {
5
+ status: string;
6
+ path: string;
7
+ previousPath?: string;
8
+ }
9
+
10
+ interface ParsedNumstat {
11
+ path: string;
12
+ previousPath?: string;
13
+ additions: number | null;
14
+ deletions: number | null;
15
+ }
16
+
17
+ function parseNameStatus(text: string): ParsedPathChange[] {
18
+ const tokens = text.split("\0");
19
+ const changes: ParsedPathChange[] = [];
20
+ for (let index = 0; index < tokens.length; ) {
21
+ const status = tokens[index++];
22
+ if (!status) continue;
23
+ if (status.startsWith("R") || status.startsWith("C")) {
24
+ const previousPath = tokens[index++];
25
+ const path = tokens[index++];
26
+ if (previousPath && path) changes.push({ status, previousPath, path });
27
+ continue;
28
+ }
29
+ const path = tokens[index++];
30
+ if (path) changes.push({ status, path });
31
+ }
32
+ return changes;
33
+ }
34
+
35
+ function parseNumstatCount(value: string): number | null {
36
+ if (value === "-") return null;
37
+ const parsed = Number(value);
38
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
39
+ }
40
+
41
+ function parseNumstat(text: string): ParsedNumstat[] {
42
+ const tokens = text.split("\0");
43
+ const stats: ParsedNumstat[] = [];
44
+ for (let index = 0; index < tokens.length; ) {
45
+ const entry = tokens[index++];
46
+ if (!entry) continue;
47
+ const firstTab = entry.indexOf("\t");
48
+ const secondTab = entry.indexOf("\t", firstTab + 1);
49
+ if (firstTab < 0 || secondTab < 0) continue;
50
+ const additions = parseNumstatCount(entry.slice(0, firstTab));
51
+ const deletions = parseNumstatCount(entry.slice(firstTab + 1, secondTab));
52
+ const inlinePath = entry.slice(secondTab + 1);
53
+ if (inlinePath) {
54
+ stats.push({ path: inlinePath, additions, deletions });
55
+ continue;
56
+ }
57
+ const previousPath = tokens[index++];
58
+ const path = tokens[index++];
59
+ if (previousPath && path) stats.push({ previousPath, path, additions, deletions });
60
+ }
61
+ return stats;
62
+ }
63
+
64
+ /** Reconcile Git name-status and numstat records into one deterministic inventory. */
65
+ export function buildReviewChanges(nameStatus: string, numstat: string): ReviewChange[] {
66
+ const statsByPath = new Map(parseNumstat(numstat).map((entry) => [entry.path, entry]));
67
+ return parseNameStatus(nameStatus)
68
+ .map((entry) => {
69
+ const stats = statsByPath.get(entry.path);
70
+ return {
71
+ ...entry,
72
+ additions: stats?.additions ?? null,
73
+ deletions: stats?.deletions ?? null,
74
+ } satisfies ReviewChange;
75
+ })
76
+ .sort((left, right) => left.path.localeCompare(right.path));
77
+ }
78
+
79
+ /** Count patch additions and deletions without interpreting binary payloads. */
80
+ export function parseDiffStats(text: string, fileCount?: number): DiffStats {
81
+ let additions = 0;
82
+ let deletions = 0;
83
+ let files = 0;
84
+ for (const line of text.split("\n")) {
85
+ if (line.startsWith("diff --git ")) files++;
86
+ else if (line.startsWith("+") && !line.startsWith("+++")) additions++;
87
+ else if (line.startsWith("-") && !line.startsWith("---")) deletions++;
88
+ }
89
+ return { files: fileCount ?? files, additions, deletions };
90
+ }
91
+
92
+ /** Derive metadata for one non-ignored untracked path from its exact patch. */
93
+ export function untrackedPatchChange(path: string, patch: string): ReviewChange {
94
+ if (patch.includes("GIT binary patch") || patch.includes("Binary files")) {
95
+ return { status: "A", path, additions: null, deletions: null };
96
+ }
97
+ const stats = parseDiffStats(patch);
98
+ return { status: "A", path, additions: stats.additions, deletions: stats.deletions };
99
+ }
100
+
101
+ /** Incrementally hash and count canonical patch parts without retaining their aggregate text. */
102
+ export function createDiffAccumulator(): {
103
+ append(diff: string): void;
104
+ finish(fileCount: number): { diffHash: string; stats: DiffStats };
105
+ } {
106
+ const hash = createHash("sha256");
107
+ let additions = 0;
108
+ let deletions = 0;
109
+ return {
110
+ append(diff) {
111
+ if (!diff) return;
112
+ hash.update(diff, "utf8");
113
+ if (!diff.endsWith("\n")) hash.update("\n", "utf8");
114
+ const stats = parseDiffStats(diff);
115
+ additions += stats.additions;
116
+ deletions += stats.deletions;
117
+ },
118
+ finish(fileCount) {
119
+ return {
120
+ diffHash: hash.digest("hex"),
121
+ stats: { files: fileCount, additions, deletions },
122
+ };
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,43 @@
1
+ import { runGitAllowExit as gitAllowExit, literalPathspec } from "../git-command.ts";
2
+ import { resolveReviewPath } from "../review-path.ts";
3
+
4
+ /** Maximum aggregate full-diff text materialized by one reviewer tool call. */
5
+ export const MAX_FULL_DIFF_CHARACTERS = 50 * 1024 * 1024;
6
+
7
+ /** Reject aggregate full-diff materialization above the process-safe tool bound. */
8
+ export function assertFullDiffCharacters(totalCharacters: number): void {
9
+ if (totalCharacters > MAX_FULL_DIFF_CHARACTERS) {
10
+ throw new Error(
11
+ `Full target diff exceeds ${MAX_FULL_DIFF_CHARACTERS} characters; read changed paths individually.`,
12
+ );
13
+ }
14
+ }
15
+
16
+ /** Stable patch flags that disable external transformations and retain binary evidence. */
17
+ export const DIFF_FLAGS = ["--no-ext-diff", "--no-textconv", "--binary"] as const;
18
+
19
+ /** Parse and deterministically sort a NUL-delimited Git path list. */
20
+ export function parseNullList(text: string): string[] {
21
+ return text
22
+ .split("\0")
23
+ .filter(Boolean)
24
+ .sort((left, right) => left.localeCompare(right));
25
+ }
26
+
27
+ /** Render one untracked path as a deterministic `/dev/null`-to-file patch. */
28
+ export async function diffUntrackedFile(cwd: string, path: string): Promise<string> {
29
+ const safe = resolveReviewPath(cwd, path);
30
+ return gitAllowExit(
31
+ cwd,
32
+ literalPathspec(["diff", ...DIFF_FLAGS, "--no-index", "--", "/dev/null", safe.path]),
33
+ [1],
34
+ );
35
+ }
36
+
37
+ /** Join canonical patch parts with exactly one required trailing newline per non-empty part. */
38
+ export function joinDiffParts(parts: string[]): string {
39
+ const populated = parts.filter(Boolean);
40
+ const totalCharacters = populated.reduce((total, part) => total + part.length + 1, 0);
41
+ assertFullDiffCharacters(totalCharacters);
42
+ return populated.map((part) => (part.endsWith("\n") ? part : `${part}\n`)).join("");
43
+ }
@@ -0,0 +1,40 @@
1
+ import type { ReviewChange } from "../types.ts";
2
+
3
+ export interface FileManifestOptions {
4
+ maxFiles?: number;
5
+ maxCharacters?: number;
6
+ }
7
+
8
+ function formatLineStats(change: ReviewChange): string {
9
+ if (change.additions === null || change.deletions === null) return "binary";
10
+ return `+${change.additions} -${change.deletions}`;
11
+ }
12
+
13
+ /** Render one deterministic changed-path inventory row. */
14
+ export function formatReviewChange(change: ReviewChange): string {
15
+ const path = change.previousPath
16
+ ? `${JSON.stringify(change.previousPath)} -> ${JSON.stringify(change.path)}`
17
+ : JSON.stringify(change.path);
18
+ return `${change.status} ${formatLineStats(change)} ${path}`;
19
+ }
20
+
21
+ /** Render a deterministic bounded change manifest with an explicit omission count. */
22
+ export function buildFileManifest(
23
+ changes: ReviewChange[],
24
+ options: FileManifestOptions = {},
25
+ ): string[] {
26
+ const maxFiles = options.maxFiles ?? 200;
27
+ const maxCharacters = options.maxCharacters ?? 8_000;
28
+ const lines: string[] = [];
29
+ let size = 0;
30
+ for (const change of changes) {
31
+ const line = `- ${formatReviewChange(change)}`;
32
+ if (lines.length >= maxFiles || size + line.length + 1 > maxCharacters - 100) break;
33
+ lines.push(line);
34
+ size += line.length + 1;
35
+ }
36
+ const omitted = changes.length - lines.length;
37
+ if (omitted > 0)
38
+ lines.push(`- … ${omitted} additional change(s) omitted; use list_review_changes`);
39
+ return lines;
40
+ }
@@ -7,16 +7,24 @@ import type {
7
7
  ReviewSnapshot,
8
8
  ReviewTask,
9
9
  } from "../types.ts";
10
+ import { buildFileManifest } from "./file-manifest.ts";
10
11
 
11
12
  /** Protocol version included in every canonical reviewer packet for future evolution. */
12
- export const REVIEW_PACKET_PROTOCOL_VERSION = "1";
13
+ export const REVIEW_PACKET_PROTOCOL_VERSION = "3";
13
14
 
14
15
  function sha256(value: string): string {
15
16
  return createHash("sha256").update(value, "utf8").digest("hex");
16
17
  }
17
18
 
18
19
  function targetIdentity(target: ResolvedReviewTarget): string {
19
- if (target.kind === "working-tree") return `working-tree head=${target.headCommit}`;
20
+ if (target.kind === "working-tree") {
21
+ return [
22
+ "working-tree",
23
+ `head=${target.headCommit}`,
24
+ ...(target.requestedBaseCommit ? [`requested-base=${target.requestedBaseCommit}`] : []),
25
+ ...(target.mergeBaseCommit ? [`merge-base=${target.mergeBaseCommit}`] : []),
26
+ ].join(" ");
27
+ }
20
28
  if (target.kind === "comparison") {
21
29
  return [
22
30
  "comparison",
@@ -46,9 +54,9 @@ export function buildReviewPacket(
46
54
  `Task id: ${task.id}`,
47
55
  `Target: ${snapshot.title}`,
48
56
  `Target identity: ${targetIdentity(snapshot.target)}`,
49
- `Target diff SHA-256: ${sha256(snapshot.diffText)}`,
57
+ `Target diff SHA-256: ${snapshot.diffHash}`,
50
58
  `Reviewer model: ${model.canonicalId}`,
51
- `Changed files: ${snapshot.changedFiles.length}`,
59
+ `Changed files: ${snapshot.changes.length}`,
52
60
  `Diff stats: +${snapshot.stats.additions} / -${snapshot.stats.deletions}`,
53
61
  ];
54
62
  if (review.sharedContext?.trim()) {
@@ -60,10 +68,13 @@ export function buildReviewPacket(
60
68
  task.instructions.trim(),
61
69
  "",
62
70
  "## Changed files",
63
- ...snapshot.changedFiles.map((file) => `- ${JSON.stringify(file)}`),
71
+ ...buildFileManifest(snapshot.changes),
64
72
  "",
65
73
  "## Inspection",
66
- "Use list_review_files, read_review_diff, read_review_file, and search_review_files.",
74
+ "Use list_review_changes for the complete changed-path set.",
75
+ "Use list_review_files, read_review_diff, read_review_file, and search_review_files for target context.",
76
+ "read_review_diff without a path returns the bounded paged full target diff; oversized targets require per-path reads. read_review_file supports line-range selection.",
77
+ "search_review_files supports before/after sides and literal/extended-regex modes.",
67
78
  "All tools resolve against the selected review target.",
68
79
  "",
69
80
  "## Delivery",
@@ -0,0 +1,209 @@
1
+ import {
2
+ runGit as git,
3
+ runGitAllowExit as gitAllowExit,
4
+ resolveGitRepositoryRoot,
5
+ withReviewIndex,
6
+ } from "../git-command.ts";
7
+ import type { ReviewSnapshot, ReviewSnapshotSummary, ReviewTargetSpec } from "../types.ts";
8
+ import {
9
+ buildReviewChanges,
10
+ createDiffAccumulator,
11
+ untrackedPatchChange,
12
+ } from "./change-metadata.ts";
13
+ import { DIFF_FLAGS, diffUntrackedFile, parseNullList } from "./diff.ts";
14
+
15
+ async function resolveCommit(cwd: string, value: string): Promise<string | undefined> {
16
+ const canonical = (await gitAllowExit(cwd, ["rev-parse", "--verify", value], [1, 128])).trim();
17
+ if (!canonical) return undefined;
18
+ const type = (await gitAllowExit(cwd, ["cat-file", "-t", canonical], [128])).trim();
19
+ if (type !== "commit") return undefined;
20
+ return canonical.toLowerCase();
21
+ }
22
+
23
+ async function headCommit(cwd: string): Promise<string | undefined> {
24
+ const value = (
25
+ await gitAllowExit(
26
+ cwd,
27
+ [
28
+ "rev-parse",
29
+ "--verify",
30
+ // biome-ignore lint/security/noSecrets: Git revision syntax, not a secret
31
+ "HEAD^{commit}",
32
+ ],
33
+ [1, 128],
34
+ )
35
+ ).trim();
36
+ return value || undefined;
37
+ }
38
+
39
+ async function commitParent(cwd: string, commit: string): Promise<string | undefined> {
40
+ const body = await git(cwd, ["cat-file", "-p", commit]);
41
+ const parent = body.match(/^parent ([0-9a-f]+)$/m)?.[1];
42
+ if (!parent) return undefined;
43
+ const type = (await gitAllowExit(cwd, ["cat-file", "-t", parent], [128])).trim();
44
+ if (type !== "commit") {
45
+ throw new Error(`First parent ${parent} for ${commit} is unavailable.`);
46
+ }
47
+ return parent;
48
+ }
49
+
50
+ async function resolveWorkingTreeBase(
51
+ cwd: string,
52
+ requested: Extract<ReviewTargetSpec, { kind: "working-tree" }>,
53
+ head: string,
54
+ ): Promise<{
55
+ baseline: string;
56
+ requestedBaseCommit?: string;
57
+ mergeBaseCommit?: string;
58
+ }> {
59
+ if (!requested.baseCommit) return { baseline: head };
60
+ const base = await resolveCommit(cwd, requested.baseCommit);
61
+ if (!base) {
62
+ throw new Error(`Commit ${requested.baseCommit.slice(0, 7)} not found in this repository.`);
63
+ }
64
+ const mergeBase = (await gitAllowExit(cwd, ["merge-base", base, head], [1])).trim();
65
+ if (!mergeBase) {
66
+ throw new Error(`No common ancestor between ${base.slice(0, 7)} and ${head.slice(0, 7)}.`);
67
+ }
68
+ return { baseline: mergeBase, requestedBaseCommit: base, mergeBaseCommit: mergeBase };
69
+ }
70
+
71
+ async function workingTreeSnapshot(
72
+ cwd: string,
73
+ requested: Extract<ReviewTargetSpec, { kind: "working-tree" }>,
74
+ ): Promise<ReviewSnapshot | undefined> {
75
+ const head = await headCommit(cwd);
76
+ if (!head) return undefined;
77
+ const base = await resolveWorkingTreeBase(cwd, requested, head);
78
+ return withReviewIndex(cwd, head, base.baseline, async (indexFile) => {
79
+ const [nameStatus, numstat, trackedDiff, untrackedText] = await Promise.all([
80
+ git(cwd, ["diff", ...DIFF_FLAGS, "--name-status", "-z", base.baseline], indexFile),
81
+ git(cwd, ["diff", ...DIFF_FLAGS, "--numstat", "-z", base.baseline], indexFile),
82
+ git(cwd, ["diff", ...DIFF_FLAGS, base.baseline], indexFile),
83
+ git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"], indexFile),
84
+ ]);
85
+ const changes = buildReviewChanges(nameStatus, numstat);
86
+ const diff = createDiffAccumulator();
87
+ diff.append(trackedDiff);
88
+ for (const path of parseNullList(untrackedText)) {
89
+ const patch = await diffUntrackedFile(cwd, path);
90
+ diff.append(patch);
91
+ changes.push(untrackedPatchChange(path, patch));
92
+ }
93
+ changes.sort((left, right) => left.path.localeCompare(right.path));
94
+ if (changes.length === 0) return undefined;
95
+
96
+ return {
97
+ repositoryRoot: cwd,
98
+ requestedTarget: requested,
99
+ target: {
100
+ kind: "working-tree",
101
+ headCommit: head,
102
+ ...(base.requestedBaseCommit ? { requestedBaseCommit: base.requestedBaseCommit } : {}),
103
+ ...(base.mergeBaseCommit ? { mergeBaseCommit: base.mergeBaseCommit } : {}),
104
+ },
105
+ title: base.mergeBaseCommit
106
+ ? `Working tree changes ${base.mergeBaseCommit.slice(0, 7)}..filesystem`
107
+ : "Working tree changes",
108
+ changes,
109
+ ...diff.finish(changes.length),
110
+ };
111
+ });
112
+ }
113
+
114
+ async function comparisonSnapshot(
115
+ cwd: string,
116
+ requested: Extract<ReviewTargetSpec, { kind: "comparison" }>,
117
+ ): Promise<ReviewSnapshot | undefined> {
118
+ const [base, head] = await Promise.all([
119
+ resolveCommit(cwd, requested.baseCommit),
120
+ headCommit(cwd),
121
+ ]);
122
+ if (!base) {
123
+ throw new Error(`Commit ${requested.baseCommit.slice(0, 7)} not found in this repository.`);
124
+ }
125
+ if (!head) throw new Error("No HEAD commit found in this repository.");
126
+ const mergeBase = (await gitAllowExit(cwd, ["merge-base", base, head], [1])).trim();
127
+ if (!mergeBase) {
128
+ throw new Error(`No common ancestor between ${base.slice(0, 7)} and ${head.slice(0, 7)}.`);
129
+ }
130
+ const [diffText, nameStatus, numstat] = await Promise.all([
131
+ git(cwd, ["diff", ...DIFF_FLAGS, mergeBase, head]),
132
+ git(cwd, ["diff", ...DIFF_FLAGS, "--name-status", "-z", mergeBase, head]),
133
+ git(cwd, ["diff", ...DIFF_FLAGS, "--numstat", "-z", mergeBase, head]),
134
+ ]);
135
+ const changes = buildReviewChanges(nameStatus, numstat);
136
+ if (changes.length === 0) return undefined;
137
+ const diff = createDiffAccumulator();
138
+ diff.append(diffText);
139
+ return {
140
+ repositoryRoot: cwd,
141
+ requestedTarget: requested,
142
+ target: {
143
+ kind: "comparison",
144
+ requestedBaseCommit: base,
145
+ mergeBaseCommit: mergeBase,
146
+ headCommit: head,
147
+ },
148
+ title: `Changes ${mergeBase.slice(0, 7)}..${head.slice(0, 7)}`,
149
+ changes,
150
+ ...diff.finish(changes.length),
151
+ };
152
+ }
153
+
154
+ async function commitSnapshot(
155
+ cwd: string,
156
+ requested: Extract<ReviewTargetSpec, { kind: "commit" }>,
157
+ ): Promise<ReviewSnapshot | undefined> {
158
+ const commit = await resolveCommit(cwd, requested.commit);
159
+ if (!commit) {
160
+ throw new Error(`Commit ${requested.commit.slice(0, 7)} not found in this repository.`);
161
+ }
162
+ const parent = await commitParent(cwd, commit);
163
+ const baseArgs = ["diff-tree", ...DIFF_FLAGS, "--root", "--no-commit-id"];
164
+ const [diffText, nameStatus, numstat] = await Promise.all([
165
+ parent
166
+ ? git(cwd, ["diff", ...DIFF_FLAGS, parent, commit])
167
+ : git(cwd, ["show", ...DIFF_FLAGS, "--format=", "--root", commit]),
168
+ parent
169
+ ? git(cwd, ["diff", ...DIFF_FLAGS, "--name-status", "-z", parent, commit])
170
+ : git(cwd, [...baseArgs, "--name-status", "-r", "-z", commit]),
171
+ parent
172
+ ? git(cwd, ["diff", ...DIFF_FLAGS, "--numstat", "-z", parent, commit])
173
+ : git(cwd, [...baseArgs, "--numstat", "-r", "-z", commit]),
174
+ ]);
175
+ const changes = buildReviewChanges(nameStatus, numstat);
176
+ if (changes.length === 0) return undefined;
177
+ const diff = createDiffAccumulator();
178
+ diff.append(diffText);
179
+ return {
180
+ repositoryRoot: cwd,
181
+ requestedTarget: requested,
182
+ target: { kind: "commit", commit, ...(parent ? { parentCommit: parent } : {}) },
183
+ title: `Commit ${commit.slice(0, 7)}`,
184
+ changes,
185
+ ...diff.finish(changes.length),
186
+ };
187
+ }
188
+
189
+ /** Pin target identities and capture the target's changed paths, patch hash, and stats. */
190
+ export async function resolveReviewSnapshot(
191
+ cwd: string,
192
+ target: ReviewTargetSpec,
193
+ ): Promise<ReviewSnapshot | undefined> {
194
+ const root = await resolveGitRepositoryRoot(cwd);
195
+ switch (target.kind) {
196
+ case "working-tree":
197
+ return workingTreeSnapshot(root, target);
198
+ case "comparison":
199
+ return comparisonSnapshot(root, target);
200
+ case "commit":
201
+ return commitSnapshot(root, target);
202
+ }
203
+ }
204
+
205
+ /** Return the public, patch-free snapshot summary. */
206
+ export function summarizeReviewSnapshot(snapshot: ReviewSnapshot): ReviewSnapshotSummary {
207
+ const { repositoryRoot: _, ...summary } = snapshot;
208
+ return { ...summary, changes: snapshot.changes.map((change) => ({ ...change })) };
209
+ }
@@ -5,10 +5,11 @@ import type { ReviewInput, ReviewTargetSpec } from "../types.ts";
5
5
  import { reviewInputSchema } from "./schemas.ts";
6
6
 
7
7
  const commitId = Type.String({
8
- minLength: 40,
8
+ minLength: 7,
9
9
  maxLength: 64,
10
- pattern: "^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$",
11
- description: "Full hexadecimal Git commit object id (40 or 64 characters).",
10
+ pattern: "^[0-9a-fA-F]{7,64}$",
11
+ description:
12
+ "Git commit hash (7-64 hex characters). Short hashes are resolved to full commit ids.",
12
13
  });
13
14
  const targetSchema = Type.Object(
14
15
  {
@@ -46,7 +47,9 @@ export const runReviewSchema = Type.Object(
46
47
  mode: StringEnum(["direct", "prepared"] as const),
47
48
  target: Type.Optional(targetSchema),
48
49
  review: Type.Optional(reviewInputSchema),
49
- planId: Type.Optional(Type.String({ minLength: 1, description: "Session-scoped plan id." })),
50
+ planId: Type.Optional(
51
+ Type.String({ minLength: 1, maxLength: 128, description: "Session-scoped plan id." }),
52
+ ),
50
53
  decision: Type.Optional(preparedDecisionSchema),
51
54
  },
52
55
  { additionalProperties: false, description: "Direct or Prepared Review execution request." },
@@ -73,16 +76,25 @@ function parseTarget(input: {
73
76
  baseCommit?: string;
74
77
  commit?: string;
75
78
  }): ReviewTargetSpec {
76
- if (input.kind === "working-tree" && !input.baseCommit && !input.commit) {
77
- return { kind: "working-tree" };
79
+ if (input.kind === "working-tree") {
80
+ return {
81
+ kind: "working-tree",
82
+ ...(input.baseCommit ? { baseCommit: input.baseCommit } : {}),
83
+ };
78
84
  }
79
- if (input.kind === "comparison" && input.baseCommit && !input.commit) {
85
+ if (input.kind === "comparison") {
86
+ if (!input.baseCommit) {
87
+ throw new Error("Comparison targets require a baseCommit (7-64 hexadecimal characters).");
88
+ }
80
89
  return { kind: "comparison", baseCommit: input.baseCommit };
81
90
  }
82
- if (input.kind === "commit" && input.commit && !input.baseCommit) {
91
+ if (input.kind === "commit") {
92
+ if (!input.commit) {
93
+ throw new Error("Commit targets require a commit field (7-64 hexadecimal characters).");
94
+ }
83
95
  return { kind: "commit", commit: input.commit };
84
96
  }
85
- throw new Error(`Target fields do not match target kind "${input.kind}".`);
97
+ throw new Error(`Unknown target kind "${input.kind}".`);
86
98
  }
87
99
 
88
100
  /** Validate and narrow preparation input after provider-level JSON parsing. */