crysk 0.0.0-stage → 0.3.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 (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  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/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,139 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { loadGlobalConfigLayer } from "#config/config";
6
+ import { remoteHeadRef, resolveRepoRoot } from "#git/git";
7
+ import { resolveBaseRef } from "#git/refs";
8
+ import {
9
+ BUNDLED_AGENTS_DIR_LABEL,
10
+ type CliOptions,
11
+ GOTCHAS_TEMPLATE,
12
+ initConfigTemplate,
13
+ initGitReminder,
14
+ initGotchasInstructions,
15
+ initTemplateOmissions,
16
+ } from "#review/preflight";
17
+ import { log } from "#ui/primitives";
18
+ import { readBrandEnv } from "../brand";
19
+ import { resolveRepoDir } from "../brand-paths";
20
+
21
+ // `pr-hero init` — the other half of making `pr-hero review` a zero-flag
22
+ // command. It writes the two files local mode looks for and nothing else, and
23
+ // it never overwrites: a config or a gotchas file already on disk is the
24
+ // user's work, and the whole value of gotchas is that a human wrote them.
25
+ export async function init(options: CliOptions): Promise<number> {
26
+ const repoRoot = await resolveRepoRoot(options.repo);
27
+ const dir = resolveRepoDir(repoRoot);
28
+ await mkdir(dir, { recursive: true });
29
+
30
+ // NOT resolveAgentsDirSetting: that one is the review-time precedence
31
+ // (flag > config > env) and it throws when nothing is set. init has no
32
+ // config to read yet — it is writing one — and a missing prompt set must
33
+ // still produce a usable scaffold. When no flag or env is given, agents_dir
34
+ // is omitted entirely so the repo uses the engine's bundled default.
35
+ const agentsFromEnv = readBrandEnv(process.env, "AGENTS_DIR");
36
+ const agentsSeed = options.agents
37
+ ? { dir: path.resolve(options.agents), source: "--agents" }
38
+ : agentsFromEnv?.value
39
+ ? { dir: path.resolve(agentsFromEnv.value), source: agentsFromEnv.name }
40
+ : undefined;
41
+ const baseSeed = resolveBaseRef({
42
+ flag: options.base,
43
+ remoteHead: await remoteHeadRef(repoRoot),
44
+ });
45
+
46
+ // C5 O-9. The global file is read but never written: init scaffolds the TEAM
47
+ // file, and the person/capped keys the global already supplies are left OUT
48
+ // of it. Without this the command ships the duplication C5 exists to delete
49
+ // — §0.5 measured three byte-identical configs on one machine, all three
50
+ // restating the same agents_dir and summary block.
51
+ const { filePath: globalConfigPath, layer: globalLayer } =
52
+ await loadGlobalConfigLayer(os.homedir());
53
+ const templateInput = {
54
+ ...(agentsSeed === undefined ? {} : { agentsDir: agentsSeed.dir }),
55
+ defaultBase: baseSeed.ref,
56
+ ...(globalLayer === undefined ? {} : { global: globalLayer }),
57
+ agentsDirFromFlag: options.agents !== undefined,
58
+ };
59
+ const omitted = initTemplateOmissions(templateInput);
60
+
61
+ // `repoConfigPath`, not `configPath`: C5 put a second config.json under
62
+ // ~/.prhero/, and a bare `configPath` in a codebase where PrheroLayout
63
+ // deliberately retired that name (home-preflight.ts) is the same ambiguity
64
+ // the retirement exists to delete. `init` writes the TEAM file and only the
65
+ // team file — the global layer is the operator's own, and scaffolding it
66
+ // from inside a repo would be this command reaching outside its checkout.
67
+ const repoConfigPath = path.join(dir, "config.json");
68
+ const gotchasPath = path.join(dir, "gotchas.md");
69
+ const wrote: string[] = [];
70
+ const kept: string[] = [];
71
+ for (const [file, contents] of [
72
+ [repoConfigPath, initConfigTemplate(templateInput)],
73
+ [gotchasPath, GOTCHAS_TEMPLATE],
74
+ ] as const) {
75
+ if (existsSync(file)) {
76
+ kept.push(file);
77
+ continue;
78
+ }
79
+ await Bun.write(file, contents);
80
+ wrote.push(file);
81
+ }
82
+
83
+ log(`crysk init — ${dir}`);
84
+ log();
85
+ for (const file of wrote) log(` wrote ${file}`);
86
+ for (const file of kept) log(` kept ${file} (already exists, untouched)`);
87
+ log();
88
+ // The seed line has to follow the FILE, not the seed: a scaffold that
89
+ // omitted agents_dir while the terminal still reported "agents_dir <path>
90
+ // (from the suggested clean set)" would send the reader looking for a line
91
+ // that is not in the file they were just told was written.
92
+ log(
93
+ omitted.agentsDir
94
+ ? globalLayer?.agents_dir
95
+ ? ` agents_dir ${globalLayer.agents_dir} (from ${globalConfigPath})`
96
+ : ` agents_dir ${BUNDLED_AGENTS_DIR_LABEL}`
97
+ : ` agents_dir ${agentsSeed?.dir} (from ${agentsSeed?.source})`,
98
+ );
99
+ log(` default_base ${baseSeed.ref} (from ${baseSeed.source})`);
100
+ if (omitted.keys.length > 0) {
101
+ log();
102
+ log(
103
+ ` Left out of ${repoConfigPath}: ${omitted.keys.join(", ")} — ` +
104
+ `${globalConfigPath} already supplies ${
105
+ omitted.keys.length === 1 ? "that key" : "those keys"
106
+ }, and restating them here is the duplication the global layer ` +
107
+ "exists to delete.",
108
+ );
109
+ }
110
+ log();
111
+ // Unconditional on purpose, and NOT "consistency-fixed" below: this is
112
+ // advice ("commit the config dir or ignore it"), true in every state this command
113
+ // can leave the repo in. It asserts nothing about the contents of a file.
114
+ log(initGitReminder(path.basename(dir)));
115
+ log();
116
+ // The block that follows DOES assert file contents, and the write above is
117
+ // skipped whenever the file already exists — so it is a function of which of
118
+ // `wrote`/`kept` the gotchas file landed in, never a constant. Printed
119
+ // unconditionally it told a repo with real gotchas to delete a marker line
120
+ // that is not in its file. When the file was kept, the only honest source
121
+ // for what to say about it is the gate itself, over the bytes on disk.
122
+ const gotchasOutcome = wrote.includes(gotchasPath)
123
+ ? ({ written: true } as const)
124
+ : ({
125
+ written: false,
126
+ // `.catch("")`: the file was on disk a moment ago — that is why it was
127
+ // kept — and a read that loses that race must not turn `init` into a
128
+ // crash. An empty read renders the "empty" arm, which is the correct
129
+ // advice for a file that is no longer there.
130
+ contents: await Bun.file(gotchasPath)
131
+ .text()
132
+ .catch(() => ""),
133
+ } as const);
134
+ const dirName = path.basename(dir);
135
+ for (const line of initGotchasInstructions(gotchasOutcome, dirName)) {
136
+ log(line);
137
+ }
138
+ return 0;
139
+ }
@@ -0,0 +1,10 @@
1
+ import { runMcpServer } from "#mcp/mcp";
2
+ import type { CliOptions } from "#review/preflight";
3
+
4
+ export async function mcpCommand(options: CliOptions): Promise<number> {
5
+ await runMcpServer({
6
+ socketPath: options.socket,
7
+ dbPath: options.db,
8
+ });
9
+ return 0;
10
+ }
@@ -0,0 +1,129 @@
1
+ import os from "node:os";
2
+ import { activityCommand } from "#commands/activity";
3
+ import { doctorCommand } from "#commands/doctor";
4
+ import { init } from "#commands/init";
5
+ import { uninstallCommand } from "#commands/uninstall";
6
+ import { upgradeCommand } from "#commands/upgrade";
7
+ import { loadEffectiveConfig } from "#config/config";
8
+ import { resolveRepoRoot } from "#git/git";
9
+ import type { CliOptions, LocalConfig } from "#review/preflight";
10
+ import { review } from "#review/review";
11
+ import {
12
+ runConfigSubmenu,
13
+ runLifecycleSubmenu,
14
+ runMenuLoop,
15
+ runWatcherSubmenu,
16
+ } from "#ui/menu";
17
+ import { styleEnabled, terminalWidth } from "#ui/primitives";
18
+ import { runReviewMenu } from "#ui/review-menu";
19
+ import { watchCommand } from "#watch/watch";
20
+ import { resolveMenuContext } from "../menu-context";
21
+ import { runWizard } from "../wizard";
22
+
23
+ export async function menuCommand(options: CliOptions): Promise<number> {
24
+ const repoRoot = options.repo
25
+ ? await resolveRepoRoot(options.repo).catch(() => undefined)
26
+ : await resolveRepoRoot(process.cwd()).catch(() => undefined);
27
+ const context = await resolveMenuContext(repoRoot ?? process.cwd());
28
+
29
+ return await runMenuLoop({
30
+ context,
31
+ styles: styleEnabled(process.stderr),
32
+ width: terminalWidth(),
33
+ dispatchAction: async (action) => {
34
+ switch (action) {
35
+ case "review": {
36
+ let effectiveConfig: LocalConfig | undefined;
37
+ if (repoRoot) {
38
+ try {
39
+ const loaded = await loadEffectiveConfig({
40
+ root: repoRoot,
41
+ home: os.homedir(),
42
+ configFlag: options.config,
43
+ });
44
+ effectiveConfig = loaded.effective;
45
+ } catch {
46
+ // ignore
47
+ }
48
+ }
49
+ const res = await runReviewMenu({
50
+ styles: styleEnabled(process.stderr),
51
+ width: terminalWidth(),
52
+ effectiveConfig,
53
+ defaultBase:
54
+ context.kind === "configured-repo"
55
+ ? context.defaultBase
56
+ : undefined,
57
+ });
58
+ if (res.action === "launch") {
59
+ return await review(res.options);
60
+ }
61
+ return "back";
62
+ }
63
+ case "init": {
64
+ return await init(options);
65
+ }
66
+ case "activity": {
67
+ return await activityCommand(options);
68
+ }
69
+ case "doctor": {
70
+ return await doctorCommand(options);
71
+ }
72
+ case "config": {
73
+ return await runConfigSubmenu({
74
+ styles: styleEnabled(process.stderr),
75
+ width: terminalWidth(),
76
+ repoRoot: repoRoot ?? undefined,
77
+ home: os.homedir(),
78
+ });
79
+ }
80
+ case "watcher": {
81
+ return await runWatcherSubmenu({
82
+ styles: styleEnabled(process.stderr),
83
+ width: terminalWidth(),
84
+ inRepo: context.kind !== "not-a-repo",
85
+ home: os.homedir(),
86
+ dispatch: async (subcmd) => {
87
+ if (subcmd === "status")
88
+ return await watchCommand({ ...options, watch: "status" });
89
+ if (subcmd === "install")
90
+ return await watchCommand({ ...options, watch: "install" });
91
+ if (subcmd === "uninstall")
92
+ return await watchCommand({ ...options, watch: "uninstall" });
93
+ if (subcmd === "add")
94
+ return await watchCommand({ ...options, watch: "add" });
95
+ if (subcmd === "add-on-push")
96
+ return await watchCommand({
97
+ ...options,
98
+ watch: "add",
99
+ onPush: true,
100
+ });
101
+ if (subcmd === "remove")
102
+ return await watchCommand({ ...options, watch: "remove" });
103
+ return 0;
104
+ },
105
+ });
106
+ }
107
+ case "lifecycle": {
108
+ return await runLifecycleSubmenu({
109
+ styles: styleEnabled(process.stderr),
110
+ width: terminalWidth(),
111
+ dispatch: async (subcmd) => {
112
+ if (subcmd === "upgrade") return await upgradeCommand(options);
113
+ if (subcmd === "setup")
114
+ return await runWizard({ cwd: repoRoot ?? process.cwd() });
115
+ if (subcmd === "uninstall")
116
+ return await uninstallCommand(options);
117
+ return 0;
118
+ },
119
+ });
120
+ }
121
+ case "quit": {
122
+ return 0;
123
+ }
124
+ default:
125
+ return 0;
126
+ }
127
+ },
128
+ });
129
+ }
@@ -0,0 +1,302 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { assertRunMatchesPr } from "#ci/gates";
4
+ import { resolveRepoRoot } from "#git/git";
5
+ import { postingExitCode } from "#pr/inline";
6
+ import {
7
+ ghCurrentBranchPr,
8
+ ghRepoWebUrl,
9
+ missingRereviewBlockMessage,
10
+ postInlineFindings,
11
+ resolveInlinePostPlan,
12
+ vanishedPriorSummaryMessage,
13
+ writePostReceipt,
14
+ } from "#pr/pr";
15
+ import { resolveCurrentPrNumber } from "#pr/preflight";
16
+ import {
17
+ type RereviewProvenance,
18
+ readRereviewProvenance,
19
+ } from "#rereview/prepare";
20
+ import { validateFindingsDocument } from "#review/findings";
21
+ import type { CliOptions } from "#review/preflight";
22
+ import { log } from "#ui/primitives";
23
+ import { CliError, CliUsageError } from "../errors";
24
+
25
+ // `pr-hero post --pr <n> --from <run-dir> [--dry-run]` (ROADMAP B6, spec
26
+ // "Offline replay via `post` verb"): the `ledger` verb's precedent — read a
27
+ // prior run's artifacts off disk — applied to publishing instead of
28
+ // aggregating. Exists because PR-mode `--dry-run` returns at reviewPr's own
29
+ // step 3, BEFORE any findings exist (see the comment there): it is
30
+ // structurally impossible for `--pr --dry-run` to preview a comment plan, so
31
+ // this verb is the only way to preview one at $0.
32
+ //
33
+ // `postCommand` itself stays unexported and untestable on purpose — it is
34
+ // nothing but `resolveRepoRoot` (a real `git rev-parse`) plus flag
35
+ // narrowing. Everything that can actually go wrong (dry-run vs live, the
36
+ // run-status guard, `assertRunMatchesPr`, the receipt) lives in
37
+ // `runPostCommand`, exported and `spawnFn`-injectable on EVERY gh-touching
38
+ // path including dry-run (CRIT-B, verify-report-pr3 #3305: an unexported
39
+ // verb whose dry-run branch never threaded spawnFn could not be proven not
40
+ // to reach a real `gh` — this is the $0 gate standing in front of the first
41
+ // live GitHub write this project will ever make, and it must not be
42
+ // possible to invert it with a green suite).
43
+ export async function postCommand(options: CliOptions): Promise<number> {
44
+ const operatorRoot = await resolveRepoRoot(options.repo);
45
+ // parseArgs already enforces both of these for the "post" command; the
46
+ // checks here are the type-narrowing TypeScript needs, not new validation.
47
+ if (options.pr === undefined) {
48
+ throw new CliUsageError("post requires --pr <n>");
49
+ }
50
+ if (options.from === undefined) {
51
+ throw new CliUsageError("post requires --from <run-dir>");
52
+ }
53
+ const prNumber =
54
+ options.pr === "current"
55
+ ? resolveCurrentPrNumber(await ghCurrentBranchPr(operatorRoot))
56
+ : options.pr;
57
+ return runPostCommand({
58
+ operatorRoot,
59
+ pr: prNumber,
60
+ from: options.from,
61
+ dryRun: options.dryRun,
62
+ });
63
+ }
64
+
65
+ export async function runPostCommand(input: {
66
+ operatorRoot: string;
67
+ pr: number;
68
+ from: string;
69
+ dryRun: boolean;
70
+ spawnFn?: typeof Bun.spawn;
71
+ }): Promise<number> {
72
+ const { operatorRoot, pr: prNumber, dryRun, spawnFn } = input;
73
+ const runDir = path.resolve(input.from);
74
+ const findingsPath = path.join(runDir, "findings.json");
75
+ // anchor.patch is the full PR diff inline comments anchor against; run dirs
76
+ // from before it existed only have diff.patch (the push delta on a re-review).
77
+ const anchorPath = path.join(runDir, "anchor.patch");
78
+ const diffPath = existsSync(anchorPath)
79
+ ? anchorPath
80
+ : path.join(runDir, "diff.patch");
81
+ if (!existsSync(findingsPath) || !existsSync(diffPath)) {
82
+ throw new CliUsageError(
83
+ `${runDir} is missing findings.json or diff.patch — point --from at ` +
84
+ 'a completed run directory ("crysk review --pr <n>" writes both)',
85
+ );
86
+ }
87
+ const doc = validateFindingsDocument(
88
+ JSON.parse(await Bun.file(findingsPath).text()),
89
+ );
90
+ // Design Threat Matrix, "Git repository selection" row (deferred from
91
+ // PR2's verification, WARN-1's scope note): --from names a directory, and
92
+ // a directory is not the PR it was reviewed for — reject a run-dir whose
93
+ // OWN artifact disagrees with --pr rather than silently publishing PR
94
+ // #17's findings to PR #18 because someone reused a stale --from.
95
+ assertRunMatchesPr(doc, prNumber, runDir);
96
+ const diffPatch = await Bun.file(diffPath).text();
97
+ // Juanma's decision (verify-report-pr3, #3305): guard on the PERSISTED
98
+ // `sessionFailed`, matching `--pr --post` (cli.ts's `postInlineIfEligible`
99
+ // call, guarded on `result.sessionFailed`) exactly — a partial run with
100
+ // findings from SOME hunters still publishes, same as the live path.
101
+ //
102
+ // Back-compat is mandatory: `sessionFailed` is additive/optional
103
+ // (review/findings.ts), so a run written before this change has no such field.
104
+ // Absent MUST mean "unknown", never "false" — falling back to `false`
105
+ // would publish a dead run's clean bill. The fallback is today's
106
+ // conservative proxy, `run_status !== "complete"`: every genuinely
107
+ // sessionFailed run IS "partial" (mergeRunEnvelope forces it), so the
108
+ // proxy never UNDER-fires; it can only OVER-fire on a partial run that
109
+ // failed for some other reason, which is still the honest "do not publish
110
+ // this as a clean review" answer.
111
+ const sessionFailedEquivalent =
112
+ doc.sessionFailed ?? doc.run_status !== "complete";
113
+ if (sessionFailedEquivalent) {
114
+ log(
115
+ `post skipped: ${findingsPath} is not a complete run ` +
116
+ `(run_status=${doc.run_status}), so there is no review to publish`,
117
+ );
118
+ return dryRun ? 0 : 1;
119
+ }
120
+
121
+ // Item 7, and the reason this block exists at all: a re-review's case,
122
+ // `live[]` and verified-gone count live ONLY in the run's `pipeline.json`
123
+ // once the process that computed them has exited. Read back here, they make
124
+ // `post --from`'s summary say what the review actually checked; NOT read
125
+ // back — the defect this repairs — the summary silently falls through to
126
+ // `MatchResult.resolved`, prints "3 resolved" for 2 checks, and writes no
127
+ // state block, which then costs the NEXT run its priors as well.
128
+ //
129
+ // Validated rather than trusted: a block that half-parses would feed the
130
+ // same fallback with none of the noise. Absent is a legitimate answer (a
131
+ // first review, or a run dir from before item 7) — the precondition inside
132
+ // `postInlineFindings` is what tells those apart from a re-review whose
133
+ // block went missing, because only it can see whether the PR already has a
134
+ // summary.
135
+ const pipelinePath = path.join(runDir, "pipeline.json");
136
+ let rereview: RereviewProvenance | undefined;
137
+ if (existsSync(pipelinePath)) {
138
+ let parsed: unknown;
139
+ try {
140
+ parsed = JSON.parse(await Bun.file(pipelinePath).text());
141
+ } catch (error) {
142
+ throw new CliError(
143
+ `${pipelinePath} is not valid JSON (${(error as Error).message}) — ` +
144
+ "a re-review's case and live findings are only recoverable from it",
145
+ );
146
+ }
147
+ const read = readRereviewProvenance(parsed);
148
+ if (read.kind === "invalid") {
149
+ throw new CliError(
150
+ `${pipelinePath} has an unreadable re-review block (${read.problem}) — ` +
151
+ "publishing it would report the old absence matcher's counts and " +
152
+ `write no state block. Re-run \`crysk review --pr ${prNumber} --post\`.`,
153
+ );
154
+ }
155
+ if (read.kind === "ok") rereview = read.rereview;
156
+ }
157
+
158
+ // The one field of the `--pr --post` call that a run directory genuinely
159
+ // cannot supply. Collapse binds every verified-gone id to its review thread
160
+ // through the FULL prior set (`bindPriorsToPosted`, one-to-one over carried
161
+ // priors too) — and `live[]` is not that set: `assembleLive` retires a
162
+ // verified-gone entry from it, by design (§3.6), so the very rows collapse
163
+ // needs are the rows the artifact no longer holds. Re-deriving them from
164
+ // the PR at post time is not a substitute either: the `state === null`
165
+ // fallback renumbers `R###` positionally, so ids from `resolved_ids` would
166
+ // point at whichever comments happen to sit in those positions now — the
167
+ // exact over-match that puts "✅ RESOLVED · verified gone" on a live
168
+ // finding.
169
+ //
170
+ // So: nothing verified gone → `[]` is the whole truth and collapse is a
171
+ // no-op. Something verified gone → refuse, loudly, and name the path that
172
+ // still holds the priors in memory. A `post --from` that published the
173
+ // right summary and silently skipped the collapse it cannot compute would
174
+ // be the third thing this feature forbids.
175
+ const verifiedGoneIds = rereview?.resolved_ids ?? [];
176
+ if (verifiedGoneIds.length > 0) {
177
+ throw new CliError(
178
+ `${pipelinePath} records ${verifiedGoneIds.length} verified-gone ` +
179
+ `finding(s) (${verifiedGoneIds.join(", ")}), and their prior records ` +
180
+ "are not in the run directory — `live[]` retires a verified-gone " +
181
+ "entry — so `post --from` cannot bind them to their review threads " +
182
+ `to collapse them. Re-run \`crysk review --pr ${prNumber} --post\`, ` +
183
+ "which holds the priors from the run that checked them.",
184
+ );
185
+ }
186
+
187
+ if (dryRun) {
188
+ const { plan, previousHeadSha, existingSummaryId } =
189
+ await resolveInlinePostPlan({
190
+ operatorRoot,
191
+ pr: prNumber,
192
+ headSha: doc.head_sha,
193
+ doc,
194
+ diffPatch,
195
+ spawnFn,
196
+ });
197
+ // The preview refuses whatever the post would refuse. A dry run that
198
+ // prints a plan for a run dir the live path then rejects is a $0 gate
199
+ // that answered a different question than the one asked.
200
+ if (rereview === undefined && existingSummaryId !== null) {
201
+ throw new CliError(
202
+ missingRereviewBlockMessage(prNumber, existingSummaryId),
203
+ );
204
+ }
205
+ // Both directions, or the preview is only half a gate — and narrowed to
206
+ // `summary_marker` for the same reason the live guard is (S-A).
207
+ if (
208
+ rereview?.last_head_source === "summary_marker" &&
209
+ existingSummaryId === null
210
+ ) {
211
+ throw new CliError(vanishedPriorSummaryMessage(prNumber));
212
+ }
213
+ log(
214
+ `plan: ${plan.reviewComments.length} review comment(s), ` +
215
+ `${plan.issueComments.length} outside diff, ` +
216
+ `${plan.persisting.length} already posted (skipped)` +
217
+ (previousHeadSha === undefined
218
+ ? `, ${plan.resolved.length} resolved`
219
+ : ""),
220
+ );
221
+ if (previousHeadSha === undefined) {
222
+ log(
223
+ `delta: ${plan.delta.resolved} resolved · ${plan.delta.new} new · ` +
224
+ `${plan.delta.persist} persist`,
225
+ );
226
+ } else {
227
+ log(
228
+ `delta: re-review (MatchResult.resolved not shown; gate outcomes only)`,
229
+ );
230
+ }
231
+ for (const finding of plan.reviewComments) {
232
+ log(` review ${finding.path}:${finding.line} ${finding.id}`);
233
+ }
234
+ for (const finding of plan.issueComments) {
235
+ log(` outside ${finding.path}:${finding.line} ${finding.id}`);
236
+ }
237
+ log("dry run: nothing was fetched-for-mutation or posted.");
238
+ return 0;
239
+ }
240
+
241
+ const repoWebUrl = await ghRepoWebUrl(operatorRoot, { spawnFn });
242
+ if (repoWebUrl === undefined) {
243
+ log("repo web url unavailable: posting plain locations");
244
+ }
245
+ const outcome = await postInlineFindings({
246
+ operatorRoot,
247
+ pr: prNumber,
248
+ headSha: doc.head_sha,
249
+ doc,
250
+ diffPatch,
251
+ webUrl: repoWebUrl,
252
+ spawnFn,
253
+ ...(rereview === undefined ? {} : { rereview, rereviewPriors: [] }),
254
+ requireRereviewOnPriorSummary: true,
255
+ refuseOnVanishedPriorSummary: true,
256
+ });
257
+ await writePostReceipt(runDir, prNumber, doc.head_sha, outcome);
258
+ log(
259
+ `posted: review ${outcome.reviewOutcome} (${outcome.reviewFindingCount} ` +
260
+ `finding(s)), ${outcome.outsideDiffCount} outside diff, ` +
261
+ `summary ${outcome.summary.action} comment ${outcome.summary.commentId}`,
262
+ );
263
+ // GitHub #39: `post --from` reaches the same `movedHeadSha` re-read inside
264
+ // the post sequence, so it can carry the same disclosure. Unconditional,
265
+ // not chained into the else-if below — a moved head is orthogonal to both a
266
+ // dropped finding and a 422, and can happen alongside either.
267
+ //
268
+ // "Same sequence, therefore same everything" is what this comment used to
269
+ // say, and it was false in a way that cost a live run: the sequence is
270
+ // shared, its INPUTS are not. `--pr --post` hands over the `rereview` block
271
+ // and the phase-B priors it is still holding; this path has only a
272
+ // directory, so it reconstructs the block from `pipeline.json` above,
273
+ // refuses when that block is unreadable or when collapse would need priors
274
+ // it does not have, and passes `requireRereviewOnPriorSummary` so a missing
275
+ // block on a PR that already has a summary cannot be published as a first
276
+ // review. Equivalence here is enforced, never assumed.
277
+ //
278
+ // `refuseOnVanishedPriorSummary` is the other half of that, and it is where
279
+ // the two paths are enforced UNEQUAL: a re-review whose summary has
280
+ // vanished costs this caller nothing to refuse (re-run `review --pr <n>
281
+ // --post` and the answer is correct), while refusing it on `--pr --post`
282
+ // would discard a review already paid for. Set here, unset there.
283
+ if (outcome.movedHeadSha) {
284
+ log(
285
+ `warning: the PR head moved while the review ran — reviewed ` +
286
+ `${doc.head_sha}, head is now ${outcome.movedHeadSha}; the comments ` +
287
+ "are pinned to the reviewed commit",
288
+ );
289
+ }
290
+ if (outcome.droppedFindingIds.length > 0) {
291
+ log(
292
+ `error: ${outcome.droppedFindingIds.length} finding(s) reached ` +
293
+ `neither channel: ${outcome.droppedFindingIds.join(", ")}`,
294
+ );
295
+ } else if (outcome.reviewOutcome === "demoted") {
296
+ log(
297
+ "warning: the review submission was rejected (422) and recovered " +
298
+ "into the summary Outside Diff bucket",
299
+ );
300
+ }
301
+ return postingExitCode(outcome);
302
+ }
@@ -0,0 +1,83 @@
1
+ // `pr-hero skills install`: the non-interactive twin of the wizard's skills step. It installs
2
+ // pr-hero's bundled agent skills (crysk-loop, plus crysk-ci-setup, crysk-pr, and the general crysk
3
+ // skill when bundled) into every detected coding agent that has a skills directory, so an agent
4
+ // can run it with no TTY. It never registers the MCP server and never touches launchd; the wizard
5
+ // still owns those.
6
+
7
+ import os from "node:os";
8
+ import { detectAgentEnvironments, syncSkills } from "../agent-env";
9
+ import { resolveEngineAssets } from "../assets";
10
+ import type { CliOptions } from "../review/preflight";
11
+
12
+ export interface SkillsInstallDeps {
13
+ home?: string;
14
+ exists?: (path: string) => boolean;
15
+ readFile?: (path: string) => string | undefined;
16
+ writeFile?: (path: string, content: string) => Promise<void> | void;
17
+ which?: (binary: string) => string | null | Promise<string | null>;
18
+ log?: (line: string) => void;
19
+ }
20
+
21
+ export async function skillsInstallCommand(
22
+ options: CliOptions,
23
+ deps: SkillsInstallDeps = {},
24
+ ): Promise<number> {
25
+ const log = deps.log ?? ((line: string) => process.stderr.write(`${line}\n`));
26
+ const home = deps.home ?? os.homedir();
27
+ const envs = await detectAgentEnvironments({
28
+ home,
29
+ exists: deps.exists,
30
+ which: deps.which,
31
+ });
32
+ const assets = resolveEngineAssets();
33
+
34
+ let withSkillsDir = 0;
35
+ let failed = false;
36
+ for (const env of envs) {
37
+ if (!env.skillsDir) continue;
38
+ withSkillsDir += 1;
39
+ const res = await syncSkills(env, assets, {
40
+ exists: deps.exists,
41
+ readFile: deps.readFile,
42
+ writeFile: deps.writeFile,
43
+ force: options.force === true,
44
+ });
45
+ // An old-name copy the sync removed, or kept because of the user's edits.
46
+ for (const old of res.legacy ?? []) {
47
+ log(
48
+ old.status === "removed"
49
+ ? `removed the old ${old.skill} skill from ${env.displayName}`
50
+ : `kept the old ${old.skill} skill in ${env.displayName} (${old.reason}); delete it by hand when you no longer need it`,
51
+ );
52
+ }
53
+ if (res.driftDetected && !options.force) {
54
+ failed = true;
55
+ log(
56
+ `local edits found in ${env.displayName}'s crysk skills; rerun with --force to overwrite them`,
57
+ );
58
+ continue;
59
+ }
60
+ if (res.errors.length > 0) {
61
+ failed = true;
62
+ for (const message of res.errors) {
63
+ log(`error: ${env.displayName}: ${message}`);
64
+ }
65
+ continue;
66
+ }
67
+ if (res.upToDate) {
68
+ log(`skills already up to date for ${env.displayName}`);
69
+ continue;
70
+ }
71
+ log(
72
+ `installed ${res.synced.length} skill file(s) for ${env.displayName} (${env.skillsDir})`,
73
+ );
74
+ }
75
+
76
+ if (withSkillsDir === 0) {
77
+ log(
78
+ "no coding agent with a skills directory was found (Claude Code, Cursor, Windsurf, Codex, Antigravity, OpenCode)",
79
+ );
80
+ return 1;
81
+ }
82
+ return failed ? 1 : 0;
83
+ }