crysk 0.0.0 → 0.3.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.
Files changed (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
package/src/git/git.ts ADDED
@@ -0,0 +1,396 @@
1
+ // The git domain: the shared `git()` spawn wrapper, the base-ref
2
+ // `.prheroignore` read, and the local-mode git-derived resolvers (repo root,
3
+ // remote base, diff-from range, remote/result links) that used to live
4
+ // duplicated across cli.ts and six other shells (store/gc.ts, home.ts,
5
+ // pr/pr.ts, watch/watch.ts, pr/reverts.ts, corpus/corpus.ts). Every consumer
6
+ // now imports from here instead of carrying its own copy.
7
+ //
8
+ // Pure extraction: every WHY comment below is carried over verbatim from
9
+ // cli.ts, unchanged in meaning or behavior.
10
+
11
+ import path from "node:path";
12
+ import type {
13
+ BaseRefResolution,
14
+ CliOptions,
15
+ LocalConfig,
16
+ } from "#review/preflight";
17
+ import { dim, markerRowLines } from "#ui/primitives";
18
+ import type { ResultLinks } from "#ui/result";
19
+ import { IGNORE_FILE_NAME, LEGACY_IGNORE_FILE_NAME } from "../brand-paths";
20
+ import { CliError } from "../errors";
21
+ import {
22
+ IgnoreFileError,
23
+ parseIgnoreFile,
24
+ parseIgnoreLsTree,
25
+ } from "../ignore-file";
26
+ import {
27
+ type IgnoreFileReadResult,
28
+ reContextualizeIgnoreError,
29
+ } from "../ignore-read";
30
+ import {
31
+ headContainedInBaseMessage,
32
+ isFullCommitId,
33
+ listPaths,
34
+ parseRemoteHead,
35
+ repoWebUrlFromRemote,
36
+ resolveBaseRef,
37
+ } from "./refs";
38
+
39
+ // Exclusions are a MUTATION of the reviewed diff, so they are stated out
40
+ // loud: an operator who is told "3 files reviewed" must be able to see that
41
+ // two more were dropped, and where the unfiltered bytes went. It sits in the
42
+ // decision block because an exclusion is what the size gate's numbers were
43
+ // computed after.
44
+ //
45
+ // "excluded file(s)", not "generated file(s)": the 9 built-in defaults are
46
+ // generated content, but a ignore-file user rule can drop anything —
47
+ // this line describes what happened to the diff, not why the operator chose
48
+ // to.
49
+ export function exclusionLines(
50
+ droppedPaths: string[],
51
+ styles: boolean,
52
+ width: number,
53
+ ): string[] {
54
+ if (droppedPaths.length === 0) return [];
55
+ return markerRowLines(
56
+ "!",
57
+ `exclusions: ${droppedPaths.length} excluded file(s) dropped from the ` +
58
+ `reviewed diff (${listPaths(droppedPaths)}); the unfiltered diff is ` +
59
+ "kept as diff.raw.patch",
60
+ dim,
61
+ styles,
62
+ width,
63
+ );
64
+ }
65
+
66
+ export async function git(
67
+ repo: string,
68
+ args: string[],
69
+ ): Promise<{ ok: boolean; stdout: string; stderr: string }> {
70
+ // Args as an ARRAY, never an interpolated shell string: `base` and `head`
71
+ // are user input that reaches git verbatim, and a shell in the middle would
72
+ // turn a branch name into an execution surface.
73
+ const proc = Bun.spawn(["git", "-C", repo, ...args], {
74
+ stdout: "pipe",
75
+ stderr: "pipe",
76
+ });
77
+ const [stdout, stderr, exitCode] = await Promise.all([
78
+ new Response(proc.stdout).text(),
79
+ new Response(proc.stderr).text(),
80
+ proc.exited,
81
+ ]);
82
+ return { ok: exitCode === 0, stdout, stderr };
83
+ }
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // ignore-file reads (ROADMAP prheroignore, Phase 3): local working tree
87
+ // and base-ref, mirroring the gotchas read's shape but never its fallback —
88
+ // a lookup failure here must never silently fall back to defaults-only, and
89
+ // a malformed file aborts the WHOLE review before any spend (same register
90
+ // as gotchasErrorMessage).
91
+
92
+ // The git runner shape `readBaseRefIgnoreRules` needs — the private `git()`
93
+ // above has no injectable seam of its own (unlike `gh()`'s `spawnFn`), so
94
+ // this function takes one explicitly and production wiring passes `git`
95
+ // itself; tests pass a scripted fake.
96
+ export type GitRunner = (
97
+ repo: string,
98
+ args: string[],
99
+ ) => Promise<{ ok: boolean; stdout: string; stderr: string }>;
100
+
101
+ // Base-ref read (CI mode) — design D2: `ls-tree` then `cat-file`, never
102
+ // `git show`, because `git show <ref>:<path>` exits 128 for BOTH an absent
103
+ // file and a bad rev, and this needs to tell those apart without parsing
104
+ // stderr. `ls-tree` alone does: exit 0 + empty stdout is absent (normal,
105
+ // defaults apply); non-zero exit is a genuine lookup failure.
106
+ //
107
+ // NEVER falls back to the working tree on any failure branch: the entire
108
+ // point of a base-ref read is that the PR author cannot choose which
109
+ // the ignore file governs their own review (design D1), and a fallback here
110
+ // would silently reopen that hole the moment the lookup itself failed —
111
+ // trading a loud, cheap abort for a quiet, expensive one.
112
+ export async function readBaseRefIgnoreRules(
113
+ runGit: GitRunner,
114
+ repo: string,
115
+ baseSha: string,
116
+ ): Promise<IgnoreFileReadResult> {
117
+ // .cryskignore wins; the legacy .prheroignore is read only when the new name
118
+ // is ABSENT at this ref. A .cryskignore that is present but unusable aborts
119
+ // (inside the helper) instead of falling through to the old file.
120
+ for (const name of [IGNORE_FILE_NAME, LEGACY_IGNORE_FILE_NAME]) {
121
+ const read = await readBaseRefIgnoreFile(runGit, repo, baseSha, name);
122
+ if (read !== undefined) return read;
123
+ }
124
+ return { rules: [], found: false };
125
+ }
126
+
127
+ // One name's ls-tree + cat-file; undefined when it is absent at the ref.
128
+ async function readBaseRefIgnoreFile(
129
+ runGit: GitRunner,
130
+ repo: string,
131
+ baseSha: string,
132
+ name: string,
133
+ ): Promise<IgnoreFileReadResult | undefined> {
134
+ // `--full-tree` makes the pathspec repo-root-relative regardless of what
135
+ // `repo` itself is cwd-ed to — see D2.
136
+ const lsTree = await runGit(repo, [
137
+ "ls-tree",
138
+ "--full-tree",
139
+ baseSha,
140
+ "--",
141
+ name,
142
+ ]);
143
+ if (!lsTree.ok) {
144
+ throw new CliError(
145
+ `${name} lookup failed at ${baseSha}: git ls-tree exited ` +
146
+ `non-zero — ${lsTree.stderr.trim()}`,
147
+ );
148
+ }
149
+ const parsed = parseIgnoreLsTree(lsTree.stdout);
150
+ if (parsed.kind === "absent") return undefined;
151
+ if (parsed.kind === "reject") {
152
+ // A root SYMLINK commits as mode 120000 with type `blob` (verified in a
153
+ // scratch repo — see #5518): a type check alone would pass it through,
154
+ // and `cat-file blob` on it returns the link TARGET (e.g. `/etc/passwd`)
155
+ // for the parser to read as ignore patterns. Only the mode allowlist
156
+ // (100644/100755) catches it; 040000 (tree/submodule-as-directory) and
157
+ // 160000 (gitlink) are rejected the same way.
158
+ throw new CliError(
159
+ `${name} at ${baseSha} has mode ${parsed.mode}, not a regular ` +
160
+ "file (100644/100755); refusing to read it as ignore rules",
161
+ );
162
+ }
163
+ // parsed.kind === "blob". The sha came back from a subprocess, so it is
164
+ // still untrusted input here — validated before it is handed to a SECOND
165
+ // git invocation.
166
+ if (!isFullCommitId(parsed.sha)) {
167
+ throw new CliError(
168
+ `${name} blob sha from git ls-tree is not a 40-hex sha: ` +
169
+ JSON.stringify(parsed.sha),
170
+ );
171
+ }
172
+ const catFile = await runGit(repo, ["cat-file", "blob", parsed.sha]);
173
+ if (!catFile.ok) {
174
+ throw new CliError(
175
+ `${name} blob read failed at ${baseSha}: git cat-file exited ` +
176
+ `non-zero — ${catFile.stderr.trim()}`,
177
+ );
178
+ }
179
+ try {
180
+ return {
181
+ rules: parseIgnoreFile(catFile.stdout, "user", name),
182
+ found: true,
183
+ };
184
+ } catch (error) {
185
+ if (error instanceof IgnoreFileError) {
186
+ throw new CliError(
187
+ reContextualizeIgnoreError(error, `${baseSha}:${name}`),
188
+ );
189
+ }
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ export async function gitCommitExists(
195
+ repo: string,
196
+ sha: string,
197
+ ): Promise<boolean> {
198
+ const result = await git(repo, ["cat-file", "-e", `${sha}^{commit}`]);
199
+ return result.ok;
200
+ }
201
+
202
+ export async function gitIsAncestor(
203
+ repo: string,
204
+ ancestor: string,
205
+ descendant: string,
206
+ ): Promise<boolean> {
207
+ const result = await git(repo, [
208
+ "merge-base",
209
+ "--is-ancestor",
210
+ ancestor,
211
+ descendant,
212
+ ]);
213
+ return result.ok;
214
+ }
215
+
216
+ // Parses `git diff --name-only` output: dedupes, drops blanks, sorts. It lived
217
+ // in rereview/prepare.ts until the git adapter was extracted, at which point
218
+ // keeping it there inverted the dependency -- this module is the bottom layer
219
+ // and would have been importing a feature domain to read git's own output.
220
+ export function parseNameOnly(stdout: string): string[] {
221
+ const out: string[] = [];
222
+ const seen = new Set<string>();
223
+ for (const line of stdout.split("\n")) {
224
+ const path = line.trim();
225
+ if (path.length === 0 || seen.has(path)) continue;
226
+ seen.add(path);
227
+ out.push(path);
228
+ }
229
+ out.sort();
230
+ return out;
231
+ }
232
+
233
+ export async function gitNameOnly(
234
+ repo: string,
235
+ from: string,
236
+ to: string,
237
+ ): Promise<string[]> {
238
+ const result = await git(repo, ["diff", "--name-only", `${from}..${to}`]);
239
+ if (!result.ok) {
240
+ throw new CliError(`git diff --name-only failed: ${result.stderr.trim()}`);
241
+ }
242
+ return parseNameOnly(result.stdout);
243
+ }
244
+
245
+ export async function gitNameStatus(
246
+ repo: string,
247
+ from: string,
248
+ to: string,
249
+ ): Promise<string> {
250
+ const result = await git(repo, ["diff", "--name-status", `${from}..${to}`]);
251
+ if (!result.ok) {
252
+ throw new CliError(
253
+ `git diff --name-status failed: ${result.stderr.trim()}`,
254
+ );
255
+ }
256
+ return result.stdout;
257
+ }
258
+
259
+ export async function resolveCommit(
260
+ repo: string,
261
+ rev: string,
262
+ ): Promise<string> {
263
+ // `--end-of-options` stops a ref that starts with a dash from being read as
264
+ // an option; `^{commit}` forces a tag or annotated object down to the
265
+ // commit it points at.
266
+ const result = await git(repo, [
267
+ "rev-parse",
268
+ "--verify",
269
+ "--end-of-options",
270
+ `${rev}^{commit}`,
271
+ ]);
272
+ const sha = result.stdout.trim();
273
+ if (!result.ok || !isFullCommitId(sha)) {
274
+ throw new CliError(
275
+ `cannot resolve "${rev}" to a commit in ${repo}` +
276
+ (result.stderr.trim() ? `: ${result.stderr.trim()}` : ""),
277
+ );
278
+ }
279
+ return sha;
280
+ }
281
+
282
+ // The repo's web url from the remote already on disk — no `gh`, no network,
283
+ // no cost, which is precisely why the terminal can afford a link on EVERY run
284
+ // and not only on a `--post` one (see repoWebUrlFromRemote's WHY). Cosmetic by
285
+ // contract, same as ghRepoWebUrl: any failure returns undefined and the block
286
+ // prints plain locations.
287
+ export async function gitRemoteWebUrl(
288
+ repo: string,
289
+ ): Promise<string | undefined> {
290
+ const remote = await git(repo, ["remote", "get-url", "origin"]);
291
+ if (!remote.ok) return undefined;
292
+ return repoWebUrlFromRemote(remote.stdout);
293
+ }
294
+
295
+ // Local mode's links, and the ONE extra condition PR mode does not need: a PR
296
+ // head was fetched from origin, so it is pushed by construction, but a local
297
+ // `--head HEAD` is usually a commit that exists only here — and a blob link to
298
+ // an unpushed commit is a 404. `git branch -r --contains` answers "does any
299
+ // remote-tracking ref already contain this commit" from the local object db:
300
+ // free, offline, and the only thing standing between the block and a dead link.
301
+ //
302
+ // Safe because local mode reviews a COMMITTED range (`diffFromSha..headSha`,
303
+ // step 8) — every finding's line lives in headSha itself, so a link pinned to
304
+ // that sha points at the bytes the hunters actually read. Were the working
305
+ // tree ever reviewed directly, containment would prove nothing and this would
306
+ // have to go back to printing no links at all.
307
+ export async function localResultLinks(
308
+ repoRoot: string,
309
+ headSha: string,
310
+ ): Promise<ResultLinks | undefined> {
311
+ const webUrl = await gitRemoteWebUrl(repoRoot);
312
+ if (webUrl === undefined) return undefined;
313
+ const contains = await git(repoRoot, ["branch", "-r", "--contains", headSha]);
314
+ if (!contains.ok || contains.stdout.trim().length === 0) return undefined;
315
+ return { webUrl, headSha };
316
+ }
317
+
318
+ export async function resolveRepoRoot(repoOption: string): Promise<string> {
319
+ const repoArg = path.resolve(repoOption);
320
+ const toplevel = await git(repoArg, ["rev-parse", "--show-toplevel"]);
321
+ if (!toplevel.ok) {
322
+ throw new CliError(`not a git repository: ${repoArg}`);
323
+ }
324
+ return toplevel.stdout.trim();
325
+ }
326
+
327
+ // The one git call the pure resolver cannot make. `symbolic-ref --quiet` exits
328
+ // non-zero when origin/HEAD is unset — normal on a local-only clone — so a
329
+ // failure here means "no remote head", not an error worth stopping for.
330
+ export async function remoteHeadRef(
331
+ repoRoot: string,
332
+ ): Promise<string | undefined> {
333
+ const result = await git(repoRoot, [
334
+ "symbolic-ref",
335
+ "--quiet",
336
+ "refs/remotes/origin/HEAD",
337
+ ]);
338
+ return result.ok ? parseRemoteHead(result.stdout) : undefined;
339
+ }
340
+
341
+ export async function resolveBase(
342
+ repoRoot: string,
343
+ options: CliOptions,
344
+ config: LocalConfig,
345
+ ): Promise<BaseRefResolution> {
346
+ // Only ask git when the answer can still change it: a flag or a configured
347
+ // default_base already decides the ref, and a subprocess whose result is
348
+ // discarded is just latency.
349
+ const needsRemote = !options.base && !config.default_base;
350
+ return resolveBaseRef({
351
+ flag: options.base,
352
+ configDefaultBase: config.default_base,
353
+ remoteHead: needsRemote ? await remoteHeadRef(repoRoot) : undefined,
354
+ });
355
+ }
356
+
357
+ // THE range fix. `git diff base..head` is a two-POINT diff: once base has
358
+ // advanced past the branch point, every commit base gained since shows up in
359
+ // the review as a REVERSED change the branch never made. Measured on the real
360
+ // target repo: for a branch already merged into `dev`, `git diff dev..branch`
361
+ // reported 111 files and 6175 deletions belonging to other people's work,
362
+ // while the correct range was empty.
363
+ //
364
+ // So the default diffs from the MERGE BASE (equivalent to `base...head`), and
365
+ // the merge-base commit is resolved EXPLICITLY rather than left implicit in a
366
+ // three-dot range: the plan has to print it, and the recorded base_sha has to
367
+ // be the commit the review was actually computed against.
368
+ //
369
+ // A failure here is unrelated histories, and it fails loud: silently falling
370
+ // back to the two-dot range would reintroduce exactly the bug this replaces.
371
+ export async function resolveDiffFrom(
372
+ repoRoot: string,
373
+ twoDot: boolean,
374
+ baseLabel: string,
375
+ headLabel: string,
376
+ baseSha: string,
377
+ headSha: string,
378
+ ): Promise<string> {
379
+ if (twoDot) return baseSha;
380
+ const result = await git(repoRoot, ["merge-base", baseSha, headSha]);
381
+ const sha = result.stdout.trim();
382
+ if (!result.ok || !isFullCommitId(sha)) {
383
+ throw new CliError(
384
+ `no merge base between ${baseLabel} (${baseSha}) and ${headLabel} ` +
385
+ `(${headSha})` +
386
+ (result.stderr.trim() ? `: ${result.stderr.trim()}` : "") +
387
+ ". The histories are unrelated, so there is no branch point to " +
388
+ "review from. Pick a --base that shares history, or pass --two-dot " +
389
+ "to diff the literal two-point range anyway.",
390
+ );
391
+ }
392
+ if (sha === headSha) {
393
+ throw new CliError(headContainedInBaseMessage(baseLabel, headLabel));
394
+ }
395
+ return sha;
396
+ }
@@ -0,0 +1,64 @@
1
+ // The engine's own identity -- name, version, and the commit it was built from.
2
+ //
3
+ // This lives in git/ rather than beside deriveEngineIdentity in assets.ts, and the
4
+ // reason is a cycle. It was first moved into assets.ts, which then had to import
5
+ // git(); but review/preflight.ts already imports assets.ts, and git/git.ts imports
6
+ // review/preflight.ts, so the move closed review/preflight -> assets -> git ->
7
+ // review/preflight. A file-level cycle detector caught it: value-import cycles
8
+ // went from 6 to 8. The pure half, deriveEngineIdentity, stays in assets.ts where
9
+ // it belongs; only this impure wrapper -- the part that actually runs
10
+ // `git rev-parse` -- moves out, and nothing on that cycle imports this module.
11
+
12
+ import {
13
+ deriveEngineIdentity,
14
+ type EngineAssets,
15
+ engineCheckoutRoot,
16
+ resolveEngineAssets,
17
+ } from "../assets";
18
+ import { git } from "./git";
19
+
20
+ // The version comes from resolveEngineAssets(), never from a package.json
21
+ // read of its own. A compiled binary's `import.meta.dir` is /$bunfs/root and
22
+ // package.json is NOT among the embedded assets, so the old read rejected with
23
+ // `ENOENT: /$bunfs/package.json` inside a try/finally that had no catch —
24
+ // every `pr-hero upgrade` on a shipped binary died there. assets.version
25
+ // already answers the same question correctly in all three modes (the baked
26
+ // `__PRHERO_VERSION__` define when compiled, the guarded package.json
27
+ // otherwise), so a second source could only ever be the wrong one.
28
+ //
29
+ // The name is left to deriveEngineIdentity's documented "pr-hero" fallback:
30
+ // package.json's `name` IS "pr-hero", and a build cannot rename itself.
31
+ //
32
+ // `assets` is injectable because detectAssetMode() reads `import.meta.dir`,
33
+ // which under `bun test` always reports "dev" — without the seam the compiled
34
+ // branch below is unreachable from the offline suite, which is precisely how
35
+ // the ENOENT above survived it.
36
+ export async function engineIdentity(assets?: EngineAssets): Promise<{
37
+ name: string;
38
+ version: string;
39
+ revision?: string;
40
+ }> {
41
+ const resolved = assets ?? resolveEngineAssets();
42
+ if (resolved.mode === "compiled") {
43
+ // No spawn at all, rather than one that is guaranteed to fail: a compiled
44
+ // binary carries no checkout, so `git rev-parse` in its virtual root can
45
+ // only ever exit non-zero. deriveEngineIdentity already omits the field
46
+ // for a failed lookup, so the artifact is identical either way — this
47
+ // just declines to pay for a subprocess on every run to learn something
48
+ // already known, and says so instead of pretending it tried.
49
+ return deriveEngineIdentity(
50
+ { version: resolved.version },
51
+ { ok: false, stdout: "" },
52
+ );
53
+ }
54
+ // `import.meta.dir` and not cwd: the revision that matters is the ENGINE's,
55
+ // and in PR mode the process is routinely pointed at a worktree of somebody
56
+ // else's repository. Reading that repo's HEAD here would stamp a review with
57
+ // the reviewed project's commit and quietly make the field a lie.
58
+ const revision = await git(engineCheckoutRoot(), [
59
+ "rev-parse",
60
+ "--short",
61
+ "HEAD",
62
+ ]);
63
+ return deriveEngineIdentity({ version: resolved.version }, revision);
64
+ }
@@ -0,0 +1,140 @@
1
+ // Pure git/ref helpers: commit-id shape, remote-HEAD parsing, the github web
2
+ // url derivation, base-ref precedence, and the small message/formatting
3
+ // helpers that read on top of them. None of this touches the filesystem, a
4
+ // subprocess, or the network — every impure git call that FEEDS these lives
5
+ // in git.ts.
6
+ //
7
+ // C1 git-layering slice: extracted out of review/preflight.ts, which
8
+ // imported these by value into git.ts — the bottom layer importing a
9
+ // review-domain module. review/preflight.ts still re-exports every symbol
10
+ // below for the ~55 existing consumers (see the re-export note there); only
11
+ // git.ts was repointed at this file in that slice.
12
+
13
+ import type { BaseRefResolution } from "#review/preflight";
14
+
15
+ // The LAST resort only. WHY it is not simply "the default": a hardcoded
16
+ // default branch silently reviews the wrong range on every repo that does not
17
+ // use `main` — musive's default branch is `dev`, so "main" there is not a
18
+ // sensible fallback, it is a wrong answer with a plausible face. See
19
+ // resolveBaseRef for the order that reaches this constant.
20
+ export const DEFAULT_BASE_REF = "main";
21
+
22
+ // `git symbolic-ref refs/remotes/origin/HEAD` answers with the full ref name
23
+ // (`refs/remotes/origin/dev`); everything downstream wants the branch. Split
24
+ // out as its own function because the shell can only hand it a string, and a
25
+ // prefix strip that is wrong by one character reviews a ref nobody named.
26
+ // Returns undefined for anything that is not that shape — including the empty
27
+ // output of a repo whose origin/HEAD was never set, which is not an error.
28
+ export function parseRemoteHead(raw: string): string | undefined {
29
+ const trimmed = raw.trim();
30
+ const prefix = "refs/remotes/origin/";
31
+ if (!trimmed.startsWith(prefix)) return undefined;
32
+ const branch = trimmed.slice(prefix.length);
33
+ return branch.length > 0 ? branch : undefined;
34
+ }
35
+
36
+ // The repository's web URL, derived from a git remote instead of asked of
37
+ // `gh`. WHY it exists next to pr/pr.ts's ghRepoWebUrl rather than replacing it:
38
+ // ghRepoWebUrl is one `gh repo view` process per call and used to live ONLY
39
+ // inside the `--post` branch, so every run without --post had no web URL and
40
+ // the terminal could not print a single clickable link. The remote is already
41
+ // on disk — free, offline, no API — which is what makes a link affordable on
42
+ // EVERY run. Posting keeps ghRepoWebUrl: it is the authority GitHub itself
43
+ // answers with (renames, transfers, forks), and the comment bodies it feeds
44
+ // are published artifacts, not a terminal nicety.
45
+ //
46
+ // The three shapes a github remote actually takes, all normalised to the same
47
+ // canonical https form: SCP-style `git@github.com:owner/repo(.git)`,
48
+ // `https://github.com/owner/repo(.git)(/)`, and `ssh://git@github.com/owner/
49
+ // repo(.git)`. ANYTHING else — a non-github host, an enterprise host, a
50
+ // missing remote, an owner/repo that does not parse — returns undefined, and
51
+ // the caller degrades to a plain `path:line`. A GUESSED url is strictly worse
52
+ // than no url: a 404 teaches the reader to stop trusting every link in the
53
+ // block (the same honesty rule as cli.ts's "repo web url unavailable:
54
+ // posting plain locations").
55
+ const GITHUB_HOST = "github.com";
56
+
57
+ export function repoWebUrlFromRemote(remote: string): string | undefined {
58
+ const trimmed = remote.trim();
59
+ if (trimmed.length === 0) return undefined;
60
+ // SCP syntax first: it is NOT a URL (no scheme), so `new URL` rejects it —
61
+ // and it is the shape a cloned-over-ssh checkout carries by default.
62
+ const scp = /^[^@/\s]+@([^:/\s]+):(.+)$/.exec(trimmed);
63
+ let host: string;
64
+ let repoPath: string;
65
+ if (scp?.[1] !== undefined && scp[2] !== undefined) {
66
+ host = scp[1];
67
+ repoPath = scp[2];
68
+ } else {
69
+ let parsed: URL;
70
+ try {
71
+ parsed = new URL(trimmed);
72
+ } catch {
73
+ return undefined;
74
+ }
75
+ host = parsed.hostname;
76
+ repoPath = parsed.pathname;
77
+ }
78
+ if (host.toLowerCase() !== GITHUB_HOST) return undefined;
79
+ const slug = repoPath
80
+ .replace(/^\/+/, "")
81
+ .replace(/\/+$/, "")
82
+ .replace(/\.git$/, "");
83
+ // Exactly owner/repo. A deeper path is not a repository root, and building
84
+ // a blob url on top of one produces a link that resolves to nothing.
85
+ if (!/^[^/\s]+\/[^/\s]+$/.test(slug)) return undefined;
86
+ return `https://${GITHUB_HOST}/${slug}`;
87
+ }
88
+
89
+ // WHY this order, and WHY it is a function rather than a default: the base ref
90
+ // decides WHICH range gets reviewed, and a hardcoded "main" is silently wrong
91
+ // on any repo that does not use it (musive is on `dev`). So the explicit flag
92
+ // wins, then the repo's own recorded choice, then what the remote actually
93
+ // says its default branch is, and only then the historical literal. The git
94
+ // call that produces `remoteHead` lives in the shell; this stays pure so every
95
+ // branch of the precedence is tested without a repo.
96
+ export function resolveBaseRef(input: {
97
+ flag?: string | undefined;
98
+ configDefaultBase?: string | undefined;
99
+ remoteHead?: string | undefined;
100
+ }): BaseRefResolution {
101
+ if (input.flag) return { ref: input.flag, source: "flag" };
102
+ if (input.configDefaultBase) {
103
+ return { ref: input.configDefaultBase, source: "config" };
104
+ }
105
+ if (input.remoteHead) return { ref: input.remoteHead, source: "remote" };
106
+ return { ref: DEFAULT_BASE_REF, source: "fallback" };
107
+ }
108
+
109
+ // The already-merged branch, spelled out. This is not a rare edge: reviewing a
110
+ // branch that has already landed is exactly what someone does when they want
111
+ // to see what the reviewer would have said, and "empty diff" alone reads as a
112
+ // bug in the tool rather than as the true answer.
113
+ export function headContainedInBaseMessage(
114
+ baseRef: string,
115
+ headRef: string,
116
+ ): string {
117
+ return (
118
+ `the merge base of ${baseRef} and ${headRef} IS ${headRef}: head is ` +
119
+ "already contained in base; there is nothing this branch adds. If the " +
120
+ "branch has already been merged, review it against its own parent (" +
121
+ "--base <the-commit-before-it>) or pass --two-dot to diff the literal " +
122
+ "two-point range."
123
+ );
124
+ }
125
+
126
+ // Enough paths to recognise the diff, never a wall of them: a lockfile-only
127
+ // PR is the common case and a hundred-line list helps nobody.
128
+ export function listPaths(paths: string[], limit = 5): string {
129
+ if (paths.length <= limit) return paths.join(", ");
130
+ return `${paths.slice(0, limit).join(", ")}, +${paths.length - limit} more`;
131
+ }
132
+
133
+ // A full 40-hex commit id and nothing else. WHY it is enforced this hard: an
134
+ // abbreviated head sha once made a COMPLETED three-replicate arm — $29.15
135
+ // already spent — unscoreable, because nothing downstream could match the
136
+ // recorded run to the tree it reviewed. Refs are canonicalized before they
137
+ // are written anywhere.
138
+ export function isFullCommitId(candidate: string): boolean {
139
+ return /^[0-9a-f]{40}$/.test(candidate.trim());
140
+ }