@mrclrchtr/supi-review 3.1.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 -294
  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 +150 -62
  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 +9 -4
  21. package/src/tool/agent-review-tools.ts +46 -14
  22. package/src/tool/child-failure-diagnostics.ts +26 -49
  23. package/src/tool/child-lifecycle-trace.ts +3 -16
  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 +146 -82
  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 +8 -13
  37. package/src/tui/prepare.ts +57 -31
  38. package/src/tui/run.ts +13 -3
  39. package/src/types.ts +60 -21
package/README.md CHANGED
@@ -13,8 +13,9 @@ This is a beta package with intentionally unstable interfaces.
13
13
  ## Surfaces
14
14
 
15
15
  - `/supi-review` — interactive Direct or Planner-assisted review
16
- - `supi_review_prepare` — optional one-shot preparation with `planning: "none" | "suggest"`
16
+ - `supi_review_prepare` — optional preparation with `planning: "none" | "suggest"`
17
17
  - `supi_review_run` — universal Direct or Prepared Review execution
18
+ - `supi_review_output` — retrieve continuation pages from review/preparation output
18
19
 
19
20
  Preparation is optional. Skills and agents that already know how to review should use Direct Review.
20
21
 
@@ -25,7 +26,7 @@ Preparation is optional. Skills and agents that already know how to review shoul
25
26
  "mode": "direct",
26
27
  "target": {
27
28
  "kind": "comparison",
28
- "baseCommit": "<full commit object id>"
29
+ "baseCommit": "9510d68"
29
30
  },
30
31
  "review": {
31
32
  "sharedContext": "The change implements issue #123.",
@@ -43,7 +44,7 @@ Preparation is optional. Skills and agents that already know how to review shoul
43
44
  }
44
45
  ```
45
46
 
46
- All tasks use one reviewer model and run concurrently. A run accepts one to four tasks. Direct and Prepared adapters use the same canonical packet compiler; every task result includes the SHA-256 of the exact packet bytes.
47
+ All tasks use one reviewer model and run concurrently. A run accepts one to four tasks. Direct and Prepared adapters use the same canonical packet compiler; every task result includes the SHA-256 of the exact packet bytes and nested-model usage when the provider reports it.
47
48
 
48
49
  ## Prepared Review
49
50
 
@@ -54,7 +55,9 @@ All tasks use one reviewer model and run concurrently. A run accepts one to four
54
55
  }
55
56
  ```
56
57
 
57
- Preparation returns a session-scoped, one-shot `planId` and optional Planner Draft. Execute it with an explicit decision:
58
+ Preparation returns a session-scoped `planId` and optional Planner Draft. Planner generation is advisory: provider, timeout, or structured-output failure returns a usable no-draft plan with bounded diagnostics. Continue with `use-review` in that case.
59
+
60
+ Execute a draft with an explicit decision:
58
61
 
59
62
  ```json
60
63
  {
@@ -64,30 +67,44 @@ Preparation returns a session-scoped, one-shot `planId` and optional Planner Dra
64
67
  }
65
68
  ```
66
69
 
67
- Use `use-review` with a complete replacement review when the draft needs editing.
70
+ Use `use-review` with a complete replacement review when the draft needs editing. Invalid decisions do not consume the plan. Execution leases it against concurrent calls; any completed task consumes it, while an all-failed or all-canceled batch releases it for retry.
68
71
 
69
72
  ## Targets
70
73
 
71
- - `working-tree` — net `HEAD` to current filesystem, plus non-ignored untracked files, computed through a temporary HEAD-seeded index rather than the caller's real index
72
- - `comparison` — merge base of a full `baseCommit` and captured `HEAD` to captured `HEAD`
73
- - `commit` — first parent (or empty tree) to a full commit object id
74
+ The Review Engine resolves the Git worktree root once. Review paths and target identity are always relative to the entire worktree, even when Pi starts in a subdirectory.
75
+
76
+ - `working-tree` — net current filesystem plus non-ignored untracked files against `HEAD`, or against `merge-base(baseCommit, HEAD)` when optional `baseCommit` is supplied; computed through a temporary HEAD-seeded union index rather than the caller's real index
77
+ - `comparison` — merge base of `baseCommit` and captured `HEAD` to captured `HEAD`
78
+ - `commit` — first parent (or empty tree) to `commit`
79
+
80
+ To review a dirty feature branch including its committed and uncommitted work:
81
+
82
+ ```json
83
+ { "kind": "working-tree", "baseCommit": "9510d68" }
84
+ ```
74
85
 
75
- Agent-facing commit values must be full hexadecimal object ids. The repository must remain stable from preparation or Direct invocation until reviewers finish; drift is not detected.
86
+ Agent-facing commit values accept 7–64 hexadecimal characters and are pinned to full commit object ids during resolution. The repository must remain stable from preparation or Direct invocation through reviewer completion, including retries; drift is not detected.
76
87
 
77
88
  ## Reviewer protocol
78
89
 
79
- Callers own task methodology. The Review Engine owns:
90
+ Callers own task methodology. The Review Engine owns target resolution, target-aware read-only tools, minimal finding-quality instructions, structured submission, child lifecycle, usage accounting, and per-task verdict derivation.
80
91
 
81
- - target resolution
82
- - target-aware read-only tools
83
- - minimal finding-quality instructions
84
- - structured submission
85
- - child lifecycle handling
86
- - per-task verdict derivation
92
+ Reviewers receive only:
87
93
 
88
- Reviewers receive no shell, arbitrary extension tools, Pi context files, skills, or prompt templates. Discovered `SYSTEM.md` and `APPEND_SYSTEM.md` files are explicitly suppressed; only the package-owned reviewer protocol is appended to Pi's base system prompt. In-memory child settings disable compaction and retries so provider limits apply to the original packet. Inspection-tool and parent-visible outputs are paged/bounded; canonical packet bytes are never truncated.
94
+ - `list_review_changes` — complete changed-path status and per-file `+/-` inventory
95
+ - `list_review_files` — after-side file inventory
96
+ - `read_review_diff` — the bounded paged full diff or one changed path's diff; oversized aggregate diffs require per-path reads
97
+ - `read_review_file` — before/after file content with optional `startLine`/`lineCount` selection
98
+ - `search_review_files` — before/after literal or extended-regex target search
99
+ - `submit_review`
89
100
 
90
- ## Result
101
+ They receive no shell, arbitrary extension tools, Pi context files, skills, or prompt templates. Discovered `SYSTEM.md` and `APPEND_SYSTEM.md` files are explicitly suppressed. In-memory child settings disable compaction and retries, so provider limits apply to the original packet.
102
+
103
+ Reviewer sessions have no package-owned wall-clock, turn, tool-use, or token cutoff. Agent-tool cancellation and the interactive Escape loader abort them explicitly; host cleanup stops waiting for an unresponsive provider abort after a short grace period.
104
+
105
+ Changed-file manifests include status and per-file numstat but remain bounded; `list_review_changes` provides the complete inventory. Input/result strings, finding counts, working-tree reads, and individual tool pages are also bounded. Working-tree patch hashing processes untracked files sequentially and does not retain the aggregate patch in the Review Plan.
106
+
107
+ ## Results and continuation
91
108
 
92
109
  Each successful task returns a summary and ordered findings. Findings contain:
93
110
 
@@ -97,8 +114,12 @@ Each successful task returns a summary and ordered findings. Findings contain:
97
114
  - `confidence`: `0..1`
98
115
  - optional target-relative location
99
116
 
100
- The Review Engine derives `pass` or `issues` per task and never aggregates or reranks tasks. Batch details also record `mode`, caller/planner provenance, and each task's packet hash.
117
+ The Review Engine derives `pass` or `issues` per task and never aggregates or reranks tasks. Batch details record `mode`, caller/planner provenance, packet hashes, and per-task usage. `supi_review_prepare` reports Planner usage; `supi_review_run` reports reviewer usage without charging Planner usage again.
118
+
119
+ Parent-facing text is stored as a bounded session artifact. When the first 12,000-character page is incomplete, the response includes an exact `supi_review_output` call containing `artifactId` and `offset`. Pages are repeatable until the bounded artifact expires or is evicted.
120
+
121
+ Non-success diagnostics retain allowlisted lifecycle metadata and optional provider-owned error summaries only. Error summaries are secret-redacted, control-character-stripped, and capped at 500 characters; reviewer conversation, repository evidence, tool arguments, and tool results are never retained as diagnostics.
101
122
 
102
123
  ## Models
103
124
 
104
- `/supi-review` asks for the reviewer model. Agent-triggered runs use `review.agentModel`. Optional planning uses the separately configured `review.plannerModel` at low thinking effort. Both settings default to the current session model for availability; configure `review.plannerModel` to a lightweight model when using Planner suggestions.
125
+ `/supi-review` asks for the reviewer model. Agent-triggered runs use `review.agentModel`. Optional planning uses the separately configured `review.plannerModel` at low thinking effort. Both settings default to the current session model. If the configured Planner is unavailable, preparation still returns a no-draft plan.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-core",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "SuPi core — shared infrastructure for SuPi extensions (XML context tags, config system)",
5
5
  "license": "MIT",
6
6
  "repository": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-review",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "SuPi Review extension — caller-defined read-only review tasks for users and agents",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "README.md"
32
32
  ],
33
33
  "dependencies": {
34
- "@mrclrchtr/supi-core": "3.1.0"
34
+ "@mrclrchtr/supi-core": "3.2.0"
35
35
  },
36
36
  "bundledDependencies": [
37
37
  "@mrclrchtr/supi-core"
@@ -0,0 +1,42 @@
1
+ import { resolveGitRepositoryRoot, runGit } from "./git-command.ts";
2
+
3
+ export interface CommitChoice {
4
+ commit: string;
5
+ label: string;
6
+ }
7
+
8
+ /** List local branches with resolved commit ids for the interactive adapter. */
9
+ export async function listLocalBranches(cwd: string): Promise<CommitChoice[]> {
10
+ const root = await resolveGitRepositoryRoot(cwd);
11
+ const output = await runGit(root, [
12
+ "for-each-ref",
13
+ // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
14
+ "--format=%(objectname)%00%(refname:short)",
15
+ "refs/heads",
16
+ ]);
17
+ return output
18
+ .trim()
19
+ .split("\n")
20
+ .flatMap((line) => {
21
+ const [commit, label] = line.split("\0");
22
+ return commit && label ? [{ commit, label }] : [];
23
+ });
24
+ }
25
+
26
+ /** List recent commits with resolved ids for the interactive adapter. */
27
+ export async function listRecentCommits(cwd: string, limit = 30): Promise<CommitChoice[]> {
28
+ const root = await resolveGitRepositoryRoot(cwd);
29
+ const output = await runGit(root, [
30
+ "log",
31
+ `--max-count=${limit}`,
32
+ // biome-ignore lint/security/noSecrets: Git format syntax, not a secret
33
+ "--format=%H%x00%s",
34
+ ]);
35
+ return output
36
+ .trim()
37
+ .split("\n")
38
+ .flatMap((line) => {
39
+ const [commit, subject] = line.split("\0");
40
+ return commit && subject ? [{ commit, label: `${commit.slice(0, 7)} ${subject}` }] : [];
41
+ });
42
+ }
@@ -1,7 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
- import { mkdtemp, rm } from "node:fs/promises";
2
+ import { lstatSync } from "node:fs";
3
+ import { mkdtemp, realpath, rm } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
+ import { join, resolve } from "node:path";
5
6
  import { promisify } from "node:util";
6
7
 
7
8
  const execFileAsync = promisify(execFile);
@@ -19,6 +20,13 @@ export async function runGit(cwd: string, args: string[], indexFile?: string): P
19
20
  return (await execFileAsync("git", args, gitOptions(cwd, indexFile))).stdout;
20
21
  }
21
22
 
23
+ /** Resolve the canonical top-level worktree containing an invocation directory. */
24
+ export async function resolveGitRepositoryRoot(cwd: string): Promise<string> {
25
+ const root = (await runGit(cwd, ["rev-parse", "--show-toplevel"])).trim();
26
+ if (!root) throw new Error(`No Git worktree contains ${cwd}.`);
27
+ return realpath(root);
28
+ }
29
+
22
30
  export function expectedGitExitOutput(error: unknown, allowedCodes: number[]): string | undefined {
23
31
  if (!error || typeof error !== "object") return undefined;
24
32
  const failure = error as {
@@ -72,6 +80,168 @@ export async function withHeadIndex<T>(
72
80
  }
73
81
  }
74
82
 
83
+ interface TreeIndexEntry {
84
+ mode: string;
85
+ objectId: string;
86
+ path: string;
87
+ }
88
+
89
+ function parseTreeIndexEntries(text: string): TreeIndexEntry[] {
90
+ return text.split("\0").flatMap((entry) => {
91
+ if (!entry) return [];
92
+ const tab = entry.indexOf("\t");
93
+ if (tab < 0) return [];
94
+ const [mode, _type, objectId] = entry.slice(0, tab).split(" ");
95
+ const path = entry.slice(tab + 1);
96
+ return mode && objectId && path ? [{ mode, objectId, path }] : [];
97
+ });
98
+ }
99
+
100
+ function filesystemMatchesEntry(cwd: string, entry: TreeIndexEntry): boolean {
101
+ try {
102
+ const stat = lstatSync(resolve(cwd, entry.path));
103
+ if (entry.mode === "120000") return stat.isSymbolicLink();
104
+ if (entry.mode === "160000") return stat.isDirectory();
105
+ return stat.isFile();
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+
111
+ function pathOrder(left: TreeIndexEntry, right: TreeIndexEntry): number {
112
+ return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
113
+ }
114
+
115
+ function descendantEntries(path: string, sortedEntries: TreeIndexEntry[]): TreeIndexEntry[] {
116
+ const prefix = `${path}/`;
117
+ let low = 0;
118
+ let high = sortedEntries.length;
119
+ while (low < high) {
120
+ const middle = Math.floor((low + high) / 2);
121
+ if ((sortedEntries[middle]?.path ?? "") < prefix) low = middle + 1;
122
+ else high = middle;
123
+ }
124
+ const descendants: TreeIndexEntry[] = [];
125
+ for (let index = low; index < sortedEntries.length; index++) {
126
+ const candidate = sortedEntries[index];
127
+ if (!candidate?.path.startsWith(prefix)) break;
128
+ descendants.push(candidate);
129
+ }
130
+ return descendants;
131
+ }
132
+
133
+ function findPathConflicts(
134
+ entry: TreeIndexEntry,
135
+ sortedHeadEntries: TreeIndexEntry[],
136
+ headByPath: Map<string, TreeIndexEntry>,
137
+ ): TreeIndexEntry[] {
138
+ let separator = entry.path.lastIndexOf("/");
139
+ while (separator > 0) {
140
+ const ancestor = headByPath.get(entry.path.slice(0, separator));
141
+ if (ancestor) return [ancestor];
142
+ separator = entry.path.lastIndexOf("/", separator - 1);
143
+ }
144
+ return descendantEntries(entry.path, sortedHeadEntries);
145
+ }
146
+
147
+ const GIT_ARG_CHUNK_CHARACTERS = 64 * 1024;
148
+
149
+ function chunkByArgumentSize<T>(values: T[], sizeOf: (value: T) => number): T[][] {
150
+ const chunks: T[][] = [];
151
+ let chunk: T[] = [];
152
+ let size = 0;
153
+ for (const value of values) {
154
+ const valueSize = sizeOf(value);
155
+ if (chunk.length > 0 && size + valueSize > GIT_ARG_CHUNK_CHARACTERS) {
156
+ chunks.push(chunk);
157
+ chunk = [];
158
+ size = 0;
159
+ }
160
+ chunk.push(value);
161
+ size += valueSize;
162
+ }
163
+ if (chunk.length > 0) chunks.push(chunk);
164
+ return chunks;
165
+ }
166
+
167
+ async function removeIndexEntries(cwd: string, indexFile: string, paths: string[]): Promise<void> {
168
+ for (const chunk of chunkByArgumentSize(paths, (path) => path.length + 1)) {
169
+ await runGit(cwd, ["update-index", "--force-remove", "--", ...chunk], indexFile);
170
+ }
171
+ }
172
+
173
+ async function addIndexEntries(
174
+ cwd: string,
175
+ indexFile: string,
176
+ entries: TreeIndexEntry[],
177
+ ): Promise<void> {
178
+ for (const chunk of chunkByArgumentSize(
179
+ entries,
180
+ (entry) => entry.mode.length + entry.objectId.length + entry.path.length + 16,
181
+ )) {
182
+ const args = ["update-index", "--add"];
183
+ for (const entry of chunk) {
184
+ args.push("--cacheinfo", entry.mode, entry.objectId, entry.path);
185
+ }
186
+ await runGit(cwd, args, indexFile);
187
+ }
188
+ }
189
+
190
+ async function addBaselineOnlyEntries(
191
+ cwd: string,
192
+ indexFile: string,
193
+ baseline: string,
194
+ head: string,
195
+ ): Promise<void> {
196
+ const [baselineTree, headTree] = await Promise.all([
197
+ runGit(cwd, ["ls-tree", "-r", "-z", baseline]),
198
+ runGit(cwd, ["ls-tree", "-r", "-z", head]),
199
+ ]);
200
+ const headEntries = parseTreeIndexEntries(headTree).sort(pathOrder);
201
+ const headByPath = new Map(headEntries.map((entry) => [entry.path, entry]));
202
+ const headPaths = new Set(headByPath.keys());
203
+ const baselineOnly = parseTreeIndexEntries(baselineTree).filter(
204
+ (entry) => !headPaths.has(entry.path),
205
+ );
206
+ const additions: TreeIndexEntry[] = [];
207
+ const removals = new Set<string>();
208
+
209
+ for (const entry of baselineOnly) {
210
+ const conflicts = findPathConflicts(entry, headEntries, headByPath);
211
+ if (conflicts.length === 0) {
212
+ additions.push(entry);
213
+ continue;
214
+ }
215
+ const currentUsesBaselineShape = filesystemMatchesEntry(cwd, entry);
216
+ const currentUsesHeadShape = conflicts.some((candidate) =>
217
+ filesystemMatchesEntry(cwd, candidate),
218
+ );
219
+ if (!currentUsesBaselineShape && currentUsesHeadShape) continue;
220
+ for (const conflict of conflicts) removals.add(conflict.path);
221
+ additions.push(entry);
222
+ }
223
+
224
+ await removeIndexEntries(cwd, indexFile, Array.from(removals));
225
+ await addIndexEntries(cwd, indexFile, additions);
226
+ }
227
+
228
+ /**
229
+ * Execute against a temporary union index containing paths tracked by either
230
+ * captured HEAD or the selected baseline. This lets Git compare the baseline
231
+ * directly with the current filesystem after branch-level deletions/renames.
232
+ */
233
+ export async function withReviewIndex<T>(
234
+ cwd: string,
235
+ head: string,
236
+ baseline: string,
237
+ operation: (indexFile: string) => Promise<T>,
238
+ ): Promise<T> {
239
+ return withHeadIndex(cwd, head, async (indexFile) => {
240
+ if (baseline !== head) await addBaselineOnlyEntries(cwd, indexFile, baseline, head);
241
+ return operation(indexFile);
242
+ });
243
+ }
244
+
75
245
  /** Disable Git pathspec magic for a path-taking command. */
76
246
  export function literalPathspec(args: string[]): string[] {
77
247
  return ["--literal-pathspecs", ...args];