@tduyng/pi-review 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,178 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ Use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 tduyng
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @tduyng/pi-review
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A `/review` command that works out what to review and sends one focused review prompt.
4
+
5
+ ## The incremental loop
6
+
7
+ Every `/review` snapshots the whole worktree (tracked and untracked) as a dangling git commit. No ref, no stash change, no branch commit. The snapshot sha sits in the session as a custom entry that never enters model context.
8
+
9
+ Run `/review` and the agent reviews what moved since the last run. The delta is a tree-to-tree diff, so it covers edits to files that were untracked at checkpoint time and deletions of tracked files. When nothing moved, the command says so and sends nothing.
10
+
11
+ Every review refreshes the snapshot, whichever target you named, so the next bare `/review` starts from that point. Git prunes the snapshot objects after roughly two weeks, and a pruned snapshot falls back to the default below. In an ephemeral `--no-session` run the snapshot lasts only for that process.
12
+
13
+ ## Targets
14
+
15
+ A bare `/review` is resolved in code, with no model in the loop:
16
+
17
+ 1. The staged changes with `--staged`, which names the target outright, whatever the snapshot says.
18
+ 2. What moved since the last snapshot, if that snapshot still exists.
19
+ 3. Any uncommitted work, untracked files included.
20
+ 4. This branch against its merge base with the default branch.
21
+
22
+ ## What it adds
23
+
24
+ - `/review [target]`. Bare resolves as above, anything else is passed through.
25
+ - `--lean`. Adds a second pass for removable implementation complexity in the same change, and prints `Lean already.` when there is none.
26
+ - `--extra "<text>"`. Acceptance criteria for the review. Repeatable, last wins.
27
+ - `--model provider/model`. Runs the review on that model through the `subagent` tool. Without that tool the review runs inline and says the override could not be honored.
28
+ - `--staged`. Reviews only the staged changes.
29
+
30
+ Anything you type is the reviewer's request and goes to the prompt as written: `/review the change between main and HEAD`, `/review src/auth`, `/review first commit on this branch`. The prompt caps target resolution at three commands and tells the reviewer not to narrate them.
31
+
32
+ ## Focused review contract
33
+
34
+ The extension resolves the diff and hands it over with two lines of context around each change, so the reviewer spends no tool calls on git. The diff is capped at 12,000 characters. Past that the stat still lists every file, and the reviewer is told how many characters it did not read.
35
+
36
+ The reviewer writes the change's intent in one line first and judges the implementation against it. Supplied criteria replace that line. It reads the diff before opening any file, opens at most two files the diff does not already show, and runs at most one targeted command, all inside a budget of eight tool calls including any target resolution.
37
+
38
+ The response is under 15 lines: a verdict, the intent line, one line per finding with a P0 to P3 severity and a concrete fix, and one `Checks:` line.
39
+
40
+ ## Examples
41
+
42
+ ```
43
+ /review # what moved, or the branch default
44
+ /review --staged # staged changes only
45
+ /review the change between main and HEAD # any target you describe
46
+ /review --lean --extra "retries must not double-charge" src/auth
47
+ /review --model opencode-go/gpt-6-luna the retry logic
48
+ ```
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ pi install npm:@tduyng/pi-review
54
+ ```
55
+
56
+ Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-review`
57
+
58
+ ## Configure
59
+
60
+ None. It works out of the box inside a git repository.
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@tduyng/pi-review",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "/review resolves a target from git, collects project ground truth, and sends a structured review prompt inline or through a subagent.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "code-review",
11
+ "git"
12
+ ],
13
+ "homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-review#readme",
14
+ "bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
15
+ "license": "Apache-2.0",
16
+ "author": "tduyng",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://gitlab.com/tduyng/pi-agent.git",
20
+ "directory": "extensions/pi-review"
21
+ },
22
+ "type": "module",
23
+ "files": [
24
+ "src",
25
+ "!src/**/*.test.ts",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-coding-agent": "*"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "pi": {
36
+ "extensions": [
37
+ "./src/index.ts"
38
+ ]
39
+ },
40
+ "dependencies": {
41
+ "ata-validator": "^1.62.1"
42
+ }
43
+ }
package/src/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # review
2
+
3
+ A native `/review` command. It resolves what to review from a sentence and injects
4
+ a focused code-change review prompt into the current session. The review runs here,
5
+ on the model you are already talking to. Change the model with `--model`, which
6
+ asks the agent to delegate through the `subagent` tool when that tool is active.
7
+
8
+ Every review leaves a checkpoint, so a bare `/review` afterwards reviews only
9
+ what changed since (see Checkpoints below).
10
+
11
+ ## Usage
12
+
13
+ ```
14
+ /review # smart default
15
+ /review current diff
16
+ /review staged
17
+ /review the change between feature and main
18
+ /review from v1.2.0 to HEAD
19
+ /review commit 3f9a1c2
20
+ /review HEAD~2
21
+ /review first commit
22
+ /review https://github.com/org/repo/pull/123
23
+ /review https://gitlab.com/group/proj/-/merge_requests/45
24
+ /review pr 42
25
+ /review src/auth tests # snapshot of these paths
26
+ /review --lean --extra "focus on the retry logic"
27
+ /review --model opencode-go/gpt-6-luna src/auth
28
+ ```
29
+
30
+ ## How it picks the target
31
+
32
+ `resolve.ts` walks a fixed order and stops at the first match. It runs on a
33
+ lowercase copy for keywords but resolves every ref against the original text.
34
+
35
+ 1. `--base <ref>` overrides everything and reviews `HEAD` against that ref.
36
+ 2. An empty query uses the smart default below.
37
+ 3. A PR or MR URL. GitHub, GitLab, and Bitbucket links are recognized.
38
+ 4. `pr 42`, `mr 42`, `pull request 42`, `merge request 42`.
39
+ 5. A range. `a...b` is a merge-base diff, `a..b` is a two-dot diff.
40
+ 6. Keywords. `current diff`, `current changes`, `working tree`, `uncommitted`,
41
+ `local changes`, `my changes`, `my diff`, `what i changed`, `staged`,
42
+ `unstaged`, `first commit`, `initial commit`, `root commit`, `last commit`,
43
+ `latest commit`, `head commit`, `tip`, and `since last review` (with its
44
+ variants).
45
+ 7. A pair. `from X to Y`, `between X and Y`, `compare X and Y`, `X vs Y`,
46
+ `X versus Y`, `X against Y`. The base side is the default branch when one of
47
+ the two is the default branch, otherwise the first ref is the base.
48
+ 8. A single base ref. `against X`, `vs X`, `compared to X`, `base X`, `branch X`.
49
+ 9. A single commit. A 7 to 40 char hex sha, or `HEAD`, `HEAD~2`, `HEAD^`, `@`.
50
+ 10. A single branch or ref name that is not the current branch. It becomes the
51
+ base and `HEAD` is the head.
52
+ 11. One or more existing paths. This is a snapshot review of the current state,
53
+ not a diff. A leading `folder`, `files`, `path`, or `dir` is dropped.
54
+ 12. Anything left becomes a free-form request. The prompt tells the agent to work
55
+ out the refs with `git status`, `git branch`, `git log`, and `git remote`
56
+ before reviewing.
57
+
58
+ ## Smart default
59
+
60
+ With no arguments:
61
+
62
+ - With a checkpoint from a previous review and a non-empty delta: review only
63
+ what changed since that checkpoint.
64
+ - Dirty tree, tracked or untracked: review the uncommitted changes.
65
+ - Clean, on a branch other than the default base, and ahead of that base: review
66
+ the whole active branch against its merge-base with the default base.
67
+ - Otherwise: review `HEAD`.
68
+
69
+ ## Focused review
70
+
71
+ The default review reads the exact git target, then inspects changed implementation
72
+ files and only the direct imports, callers, serializers, migrations, generated
73
+ interfaces, and tests needed to prove that contracts still fit. It uses the
74
+ conventions of each changed language and follows direct consumers across language
75
+ boundaries. It checks renamed symbols, signatures, schemas, required and optional
76
+ fields, nullability, runtime producers and consumers, and changed behavior. It
77
+ does not scan the whole repository, inspect unrelated history, or run the full
78
+ test suite. It uses at most eight tool calls and returns a verdict, concrete
79
+ findings, and the exact checks it ran.
80
+
81
+ `--extra` is the acceptance criteria for the review. Use it to state the specific
82
+ requirement to verify.
83
+
84
+ ## Checkpoints
85
+
86
+ After every `/review` (any target), the extension snapshots the whole worktree,
87
+ tracked and untracked, as a dangling git commit object: no ref, no commit on
88
+ your branch, no index or stash change. The snapshot sha and a timestamp are
89
+ appended to the session as a `review/checkpoint` custom entry, which never
90
+ enters model context.
91
+
92
+ The next bare `/review` diffs the checkpoint snapshot against a fresh snapshot
93
+ and reviews only that delta. This is the review loop without any GUI: run
94
+ `/review`, let the agent work, run `/review` again and pay only for the new
95
+ changes. When nothing changed since the checkpoint, the command says so and
96
+ sends nothing.
97
+
98
+ Details that follow from the mechanism:
99
+
100
+ - Any explicit target (`review uncommitted`, `review main`, a PR, whatever)
101
+ still refreshes the checkpoint, so the next bare `/review` is a delta from
102
+ there. This is also the reset path.
103
+ - `since last review` asks for the delta explicitly. Without a checkpoint it
104
+ falls back to the smart default.
105
+ - The delta is a tree-to-tree diff, so it covers edits to files that were
106
+ untracked at checkpoint time and deletions, not just edits to tracked files.
107
+ - Checkpoints ride the session: resuming or branching a session keeps its own
108
+ review state. Git prunes the snapshot objects after roughly two weeks, and a
109
+ pruned checkpoint falls back to the full smart default.
110
+ - In an ephemeral `--no-session` run, the checkpoint lasts only for that
111
+ process.
112
+
113
+ ## Rubric
114
+
115
+ `prompt.ts` carries the focused review contract. It limits the review to the
116
+ requested change and its direct consumers in any language, calibrates severity,
117
+ and requires each finding to name `file:line` and a concrete fix. The response
118
+ stays under 15 lines and includes one `Checks:` line.
119
+
120
+ ## Flags
121
+
122
+ | Flag | Effect |
123
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
124
+ | `--lean` | Adds a second pass for removable implementation complexity in the same change. A clean pass reads `Lean already.` |
125
+ | `--model provider/model` | Asks the agent to run the review on that model through the `subagent` tool when it is active. With no such tool, the prompt says the override could not be honored and the review runs inline. |
126
+ | `--extra "<text>"` | Sets the acceptance criteria for the review. Repeatable, the last wins. |
127
+ | `--base <ref>` | Reviews `HEAD` against `<ref>` regardless of the rest of the query. |
128
+ | `--staged` | Reviews only staged changes when the target is otherwise uncommitted. |
129
+
130
+ ## Files
131
+
132
+ - `index.ts` registers `/review` and runs resolve, prompt, send.
133
+ - `resolve.ts` turns a query and flags into a `ReviewTarget`.
134
+ - `args.ts` splits flags from the free-form query with a quote-aware tokenizer.
135
+ - `git.ts` is the real `Git` implementation over `pi.exec`, including the
136
+ worktree snapshot and the empty-delta probe.
137
+ - `checkpoint.ts` reads and writes the session checkpoint entries.
138
+ - `prompt.ts` holds the rubric and builds the injected prompt.
139
+ - `types.ts` holds the shared types and the `Git` interface.
140
+
141
+ Tests live in `../tests/review-*.test.ts` and cover the resolver, the arg parser,
142
+ the prompt builder, the command handler, and the git layer against a real
143
+ repository.
package/src/args.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { ParsedArgs, ReviewFlags } from './types.js'
2
+
3
+ const VALUE_FLAGS = ['extra', 'model'] as const
4
+ const BOOLEAN_FLAGS = ['lean', 'staged'] as const
5
+
6
+ function takeValue(raw: string, name: string): [string | null, string] {
7
+ const match = new RegExp(`--${name}(?:=|\\s+)("([^"]*)"|'([^']*)'|(\\S+))`).exec(raw)
8
+ if (match === null) return [null, raw]
9
+ const value = match[2] ?? match[3] ?? match[4] ?? ''
10
+ if (value.startsWith('--')) return [null, raw]
11
+ const rest = raw.slice(0, match.index) + ' ' + raw.slice(match.index + match[0].length)
12
+ return [value, rest]
13
+ }
14
+
15
+ export function parseReviewArgs(raw: string): ParsedArgs {
16
+ const flags: ReviewFlags = { lean: false, staged: false }
17
+ let query = raw
18
+
19
+ for (const name of VALUE_FLAGS) {
20
+ let taken = takeValue(query, name)
21
+ while (taken[0] !== null) {
22
+ if (taken[0].trim() !== '') flags[name] = taken[0]
23
+ query = taken[1]
24
+ taken = takeValue(query, name)
25
+ }
26
+ }
27
+
28
+ for (const name of BOOLEAN_FLAGS) {
29
+ const match = new RegExp(`(?:^|\\s)--${name}(?=\\s|$)`).exec(query)
30
+ if (match !== null) {
31
+ flags[name] = true
32
+ query = query.slice(0, match.index) + ' ' + query.slice(match.index + match[0].length)
33
+ }
34
+ }
35
+
36
+ const dangling = /(?:^|\s)--(extra|model)(?=\s|$)/.exec(query)
37
+ if (dangling !== null) return { flags, query: '', error: `Missing value for --${dangling[1]}` }
38
+
39
+ return { flags, query: query.replace(/\s+/g, ' ').trim() }
40
+ }
@@ -0,0 +1,26 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent'
2
+ import { Validator } from 'ata-validator'
3
+ import { t } from 'ata-validator/t'
4
+
5
+ import type { ReviewCheckpoint } from './types.js'
6
+
7
+ export const CHECKPOINT_ENTRY = 'review/checkpoint'
8
+
9
+ const CheckpointSchema = t.object({
10
+ version: t.literal(1),
11
+ baseSha: t.string({ pattern: '^[0-9a-f]{40}$' }),
12
+ createdAt: t.number()
13
+ })
14
+ const isCheckpointSchema = new Validator(CheckpointSchema).isValidObject
15
+
16
+ export function latestCheckpoint(ctx: ExtensionCommandContext): ReviewCheckpoint | null {
17
+ for (const entry of ctx.sessionManager.getBranch().toReversed()) {
18
+ if (entry.type !== 'custom' || entry.customType !== CHECKPOINT_ENTRY) continue
19
+ if (isCheckpointSchema(entry.data)) return entry.data
20
+ }
21
+ return null
22
+ }
23
+
24
+ export function saveCheckpoint(pi: ExtensionAPI, baseSha: string): void {
25
+ pi.appendEntry<ReviewCheckpoint>(CHECKPOINT_ENTRY, { version: 1, baseSha, createdAt: Date.now() })
26
+ }
package/src/git.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
6
+
7
+ import type { Git } from './types.js'
8
+
9
+ interface RunResult {
10
+ code: number
11
+ stdout: string
12
+ }
13
+
14
+ export function createGit(pi: ExtensionAPI, cwd: string): Git {
15
+ async function run(args: string[]): Promise<RunResult> {
16
+ const result = await pi.exec('git', args, { cwd })
17
+ return { code: result.code, stdout: result.stdout }
18
+ }
19
+
20
+ async function revParse(ref: string): Promise<string | null> {
21
+ const { code, stdout } = await run(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
22
+ const sha = stdout.trim()
23
+ return code === 0 && sha ? sha : null
24
+ }
25
+
26
+ async function emptyTree(): Promise<string | null> {
27
+ const indexFile = join(tmpdir(), `pi-review-${randomUUID()}`)
28
+ try {
29
+ const tree = await pi.exec('env', [`GIT_INDEX_FILE=${indexFile}`, 'git', 'write-tree'], { cwd })
30
+ const sha = tree.stdout.trim()
31
+ return tree.code === 0 && /^[0-9a-f]{40}$/.test(sha) ? sha : null
32
+ } catch {
33
+ return null
34
+ } finally {
35
+ rmSync(indexFile, { force: true })
36
+ }
37
+ }
38
+
39
+ return {
40
+ revParse,
41
+ emptyTree,
42
+
43
+ async mergeBase(a: string, b: string): Promise<string | null> {
44
+ const { code, stdout } = await run(['merge-base', a, b])
45
+ const sha = stdout.trim()
46
+ return code === 0 && sha ? sha : null
47
+ },
48
+
49
+ async defaultBranch(): Promise<string> {
50
+ const symbolic = await run(['symbolic-ref', 'refs/remotes/origin/HEAD', '--short'])
51
+ const remoteHead = symbolic.stdout.trim()
52
+ if (symbolic.code === 0 && remoteHead.startsWith('origin/')) return remoteHead.slice('origin/'.length)
53
+ if ((await revParse('refs/heads/main')) !== null) return 'main'
54
+ if ((await revParse('refs/heads/master')) !== null) return 'master'
55
+ return 'main'
56
+ },
57
+
58
+ async isDirty(): Promise<boolean> {
59
+ const { code, stdout } = await run(['status', '--porcelain'])
60
+ return code === 0 && stdout.trim().length > 0
61
+ },
62
+
63
+ async snapshotWorktree(): Promise<string | null> {
64
+ const indexFile = join(tmpdir(), `pi-review-${randomUUID()}`)
65
+ const env = (args: string[]) => pi.exec('env', [`GIT_INDEX_FILE=${indexFile}`, 'git', ...args], { cwd })
66
+ try {
67
+ const head = await revParse('HEAD')
68
+ if (head !== null) await env(['read-tree', 'HEAD'])
69
+ await env(['add', '-A'])
70
+ const tree = await env(['write-tree'])
71
+ const treeSha = tree.stdout.trim()
72
+ if (tree.code !== 0 || !/^[0-9a-f]{40}$/.test(treeSha)) return null
73
+ const parent = head !== null ? ['-p', head] : []
74
+ const commit = await run(['commit-tree', treeSha, ...parent, '-m', 'review checkpoint'])
75
+ const sha = commit.stdout.trim()
76
+ return commit.code === 0 && /^[0-9a-f]{40}$/.test(sha) ? sha : null
77
+ } catch {
78
+ return null
79
+ } finally {
80
+ rmSync(indexFile, { force: true })
81
+ }
82
+ },
83
+
84
+ async diffEmpty(a: string, b: string): Promise<boolean> {
85
+ return (await run(['diff', '--quiet', a, b])).code === 0
86
+ },
87
+
88
+ async diffText(args: string[]): Promise<string | null> {
89
+ const { code, stdout } = await run(['diff', ...args])
90
+ return code === 0 ? stdout : null
91
+ }
92
+ }
93
+ }
package/src/index.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
2
+
3
+ import { parseReviewArgs } from './args.js'
4
+ import { latestCheckpoint, saveCheckpoint } from './checkpoint.js'
5
+ import { createGit } from './git.js'
6
+ import { buildReviewPrompt, describeTarget } from './prompt.js'
7
+ import { defaultTarget, targetRefs } from './target.js'
8
+ import type { Git, ReviewDiff, ReviewTarget } from './types.js'
9
+
10
+ const MAX_DIFF_CHARS = 12_000
11
+ const SINCE_LAST_REVIEW = /\bsince (?:my )?(?:the )?last review\b/
12
+
13
+ async function reviewDiff(git: Git, target: ReviewTarget, worktree: string | null): Promise<ReviewDiff | null> {
14
+ const refs = await targetRefs(git, target, worktree)
15
+ if (refs === null) return null
16
+ const [stat, diff] = await Promise.all([git.diffText([...refs, '--stat']), git.diffText([...refs, '-U2'])])
17
+ if (diff === null) return null
18
+ return {
19
+ stat: stat ?? '',
20
+ body: diff.slice(0, MAX_DIFF_CHARS),
21
+ truncated: diff.length > MAX_DIFF_CHARS,
22
+ total: diff.length
23
+ }
24
+ }
25
+
26
+ export default function reviewExtension(pi: ExtensionAPI): void {
27
+ pi.registerCommand('review', {
28
+ description: 'Review a diff, what moved since the last review, or a target you describe.',
29
+ handler: async (args, ctx) => {
30
+ const repo = await pi.exec('git', ['rev-parse', '--git-dir'], { cwd: ctx.cwd })
31
+ if (repo.code !== 0) {
32
+ ctx.ui.notify('Not a git repository', 'error')
33
+ return
34
+ }
35
+
36
+ const parsed = parseReviewArgs(args)
37
+ if (parsed.error !== undefined) {
38
+ ctx.ui.notify(parsed.error, 'error')
39
+ return
40
+ }
41
+
42
+ const git = createGit(pi, ctx.cwd)
43
+ const checkpoint = latestCheckpoint(ctx)
44
+ const target =
45
+ parsed.query === '' || (checkpoint !== null && SINCE_LAST_REVIEW.test(parsed.query))
46
+ ? await defaultTarget(git, checkpoint, parsed.flags.staged)
47
+ : { kind: 'request' as const, text: parsed.query }
48
+ if (target === null) {
49
+ ctx.ui.notify('Nothing to review.', 'info')
50
+ return
51
+ }
52
+
53
+ const boundary = target.kind === 'since' ? target.nowSha : await git.snapshotWorktree()
54
+ const diff = await reviewDiff(git, target, boundary)
55
+ if (diff !== null && diff.total === 0) {
56
+ ctx.ui.notify('Nothing to review.', 'info')
57
+ return
58
+ }
59
+ // A request target has no refs to diff, so the reviewer resolves it itself; every
60
+ // other target that could not produce a diff must not advance the checkpoint, or
61
+ // the next bare /review would skip the changes that were never reviewed.
62
+ if (boundary !== null && (diff !== null || target.kind === 'request')) saveCheckpoint(pi, boundary)
63
+
64
+ ctx.ui.notify('Reviewing ' + describeTarget(target), 'info')
65
+ pi.sendUserMessage(
66
+ buildReviewPrompt({
67
+ target,
68
+ diff,
69
+ flags: parsed.flags,
70
+ subagentAvailable: pi.getActiveTools().includes('subagent')
71
+ })
72
+ )
73
+ }
74
+ })
75
+ }
package/src/prompt.ts ADDED
@@ -0,0 +1,103 @@
1
+ import type { ReviewDiff, ReviewFlags, ReviewTarget } from './types.js'
2
+
3
+ export const FOCUSED_REVIEW_RUBRIC = `# Focused code-change review
4
+
5
+ Review only the requested change, and judge whether the changed implementation does what the
6
+ change claims. This is not a repository audit.
7
+
8
+ Write the change's intent in one line before anything else, from the diff and the request alone.
9
+ That line is your criteria. Supplied acceptance criteria replace it.
10
+
11
+ Then, in this order:
12
+ 1. Read the whole diff below before opening any file. When it is truncated, say in the Checks
13
+ line how many characters you did not read, and review only what you can see.
14
+ 2. Read the changed implementation files. Open at most two files the diff does not already
15
+ show you, and only when a changed line names a symbol whose definition you have not seen.
16
+ 3. Check what the change breaks: renamed symbols, signatures, schemas, required and optional
17
+ fields, nullability, runtime producers and consumers, changed behavior. Cross into another
18
+ language only when the diff changes a contract that crosses it.
19
+ 4. Run at most one targeted compiler, typecheck, lint or test command, only to settle a doubt
20
+ the diff raised. Never the full suite.
21
+
22
+ Eight tool calls is the whole budget, including any spent working out the target. Never announce a
23
+ tool call or restate the plan before making it. Do not search the repository, read unrelated
24
+ history or broad project documentation. A doubt you cannot prove from what you read is not a
25
+ finding: say it is unproven and stop.
26
+
27
+ Report only what this change introduced and the author would fix: a stale symbol, a caller that
28
+ was not updated, a wrong runtime value, an invalid contract, a broken test. Not findings:
29
+ pre-existing problems, style preference, unrequested refactors, and anything you cannot point at
30
+ a changed line for.
31
+
32
+ P0 release-blocking. P1 urgent correctness. P2 normal bug. P3 minor. Use the lowest severity the
33
+ evidence supports.`
34
+
35
+ const LEAN_PASS = `## Lean pass
36
+
37
+ Only after correctness, list removable implementation complexity in the same diff. One line per
38
+ finding: \`file:line\`, what to cut, and the replacement. Do not propose removing input validation,
39
+ security, accessibility, or error handling. On a clean pass write exactly \`Lean already.\``
40
+
41
+ const OUTPUT_BLOCK = `## Output
42
+
43
+ Keep the response under 15 lines:
44
+ 1. First line: \`correct\` or \`needs attention\`.
45
+ 2. Second line: \`Intent: <the one-line intent>\`.
46
+ 3. Findings, one per line: \`[P0|P1|P2|P3] file:line - problem. fix: <specific change>\`.
47
+ Reference changed lines. If none, write \`No findings.\`
48
+ 4. One \`Checks:\` line with the exact command run and its result, or \`not run\`.`
49
+
50
+ function resolveMergeBase(base: string): string {
51
+ return `Review what this branch would merge into \`${base}\`. Run \`git merge-base ${base} HEAD\` first, then read that diff with \`--no-prefix -U0\`.`
52
+ }
53
+
54
+ function resolveRequest(text: string): string {
55
+ return `The reviewer's request: ${text}\n\nWork the target out yourself in at most three commands: \`git status --porcelain\`, \`git log --oneline -10\`, \`git branch -a\`. Do not narrate them. Then read that diff with \`--no-prefix -U0\`. If the request is ambiguous, name the target you picked in one line and review it.`
56
+ }
57
+
58
+ function whatToReview(target: ReviewTarget, diff: ReviewDiff | null): string {
59
+ if (target.kind === 'request') return resolveRequest(target.text)
60
+ if (target.kind === 'base' && target.mergeBase === null) return resolveMergeBase(target.base)
61
+ if (diff === null) return 'git returned no diff for this target.'
62
+
63
+ const cut = diff.truncated ? `\n\n[truncated: ${diff.total} characters in total]` : ''
64
+ return `The stat, then the diff.\n\n${diff.stat}\n${diff.body}${cut}`
65
+ }
66
+
67
+ export function describeTarget(target: ReviewTarget): string {
68
+ switch (target.kind) {
69
+ case 'uncommitted':
70
+ return target.staged ? 'staged changes' : 'uncommitted changes'
71
+ case 'since':
72
+ return 'changes since the last review'
73
+ case 'base':
74
+ return `this branch against ${target.base}`
75
+ case 'request':
76
+ return `request "${target.text}"`
77
+ }
78
+ }
79
+
80
+ export interface BuildReviewPromptInput {
81
+ target: ReviewTarget
82
+ diff: ReviewDiff | null
83
+ flags: ReviewFlags
84
+ subagentAvailable: boolean
85
+ }
86
+
87
+ function modelOverride(model: string, subagentAvailable: boolean): string {
88
+ if (!subagentAvailable) {
89
+ return `## Model override\n\nThe user asked for model \`${model}\` and no delegation tool is available here. Review on the current model and say in one line that \`--model ${model}\` could not be honored.`
90
+ }
91
+ return `## Model override\n\nThe user asked for this review to run on model \`${model}\`. Delegate it to the subagent tool with model: "${model}" and a read-only profile. Pass this entire prompt, then relay the result verbatim.`
92
+ }
93
+
94
+ export function buildReviewPrompt(input: BuildReviewPromptInput): string {
95
+ const blocks = [FOCUSED_REVIEW_RUBRIC, '---', `## What to review\n\n${whatToReview(input.target, input.diff)}`]
96
+
97
+ if (input.flags.extra !== undefined) blocks.push(`## Acceptance criteria\n\n${input.flags.extra}`)
98
+ if (input.flags.lean) blocks.push(LEAN_PASS)
99
+ if (input.flags.model !== undefined) blocks.push(modelOverride(input.flags.model, input.subagentAvailable))
100
+ blocks.push(OUTPUT_BLOCK)
101
+
102
+ return blocks.join('\n\n')
103
+ }
package/src/target.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { Git, ReviewCheckpoint, ReviewTarget } from './types.js'
2
+
3
+ export async function defaultTarget(
4
+ git: Git,
5
+ checkpoint: ReviewCheckpoint | null,
6
+ staged: boolean
7
+ ): Promise<ReviewTarget | null> {
8
+ if (staged) return { kind: 'uncommitted', staged: true }
9
+ if (checkpoint !== null && (await git.revParse(checkpoint.baseSha)) !== null) {
10
+ const nowSha = await git.snapshotWorktree()
11
+ if (nowSha !== null) {
12
+ return (await git.diffEmpty(checkpoint.baseSha, nowSha))
13
+ ? null
14
+ : { kind: 'since', baseSha: checkpoint.baseSha, nowSha }
15
+ }
16
+ }
17
+
18
+ if (await git.isDirty()) return { kind: 'uncommitted', staged: false }
19
+
20
+ const base = await git.defaultBranch()
21
+ const mergeBase = await git.mergeBase(base, 'HEAD')
22
+ if (mergeBase !== null && (await git.diffEmpty(mergeBase, 'HEAD'))) return null
23
+ return { kind: 'base', base, mergeBase }
24
+ }
25
+
26
+ export async function targetRefs(git: Git, target: ReviewTarget, worktree: string | null): Promise<string[] | null> {
27
+ switch (target.kind) {
28
+ case 'uncommitted': {
29
+ if (target.staged) return ['--cached']
30
+ if (worktree === null) return ['HEAD']
31
+ const base = (await git.revParse('HEAD')) ?? (await git.emptyTree())
32
+ return base === null ? ['HEAD'] : [base, worktree]
33
+ }
34
+ case 'since':
35
+ return [target.baseSha, target.nowSha]
36
+ case 'base':
37
+ return target.mergeBase === null ? null : [target.mergeBase, 'HEAD']
38
+ case 'request':
39
+ return null
40
+ }
41
+ }
package/src/types.ts ADDED
@@ -0,0 +1,42 @@
1
+ export type ReviewTarget =
2
+ | { kind: 'uncommitted'; staged: boolean }
3
+ | { kind: 'since'; baseSha: string; nowSha: string }
4
+ | { kind: 'base'; base: string; mergeBase: string | null }
5
+ | { kind: 'request'; text: string }
6
+
7
+ export interface ReviewFlags {
8
+ lean: boolean
9
+ staged: boolean
10
+ model?: string
11
+ extra?: string
12
+ }
13
+
14
+ export interface ParsedArgs {
15
+ flags: ReviewFlags
16
+ query: string
17
+ error?: string
18
+ }
19
+
20
+ export interface ReviewDiff {
21
+ stat: string
22
+ body: string
23
+ truncated: boolean
24
+ total: number
25
+ }
26
+
27
+ export interface Git {
28
+ revParse(ref: string): Promise<string | null>
29
+ emptyTree(): Promise<string | null>
30
+ mergeBase(a: string, b: string): Promise<string | null>
31
+ defaultBranch(): Promise<string>
32
+ isDirty(): Promise<boolean>
33
+ snapshotWorktree(): Promise<string | null>
34
+ diffEmpty(a: string, b: string): Promise<boolean>
35
+ diffText(args: string[]): Promise<string | null>
36
+ }
37
+
38
+ export interface ReviewCheckpoint {
39
+ version: 1
40
+ baseSha: string
41
+ createdAt: number
42
+ }