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,443 @@
1
+ // Everything the global ~/.crysk/ product home (W3 / GitHub #24) must
2
+ // decide, expressed as pure functions so it is all testable offline. The
3
+ // I/O shell in home.ts (and the CLI/watch shells that call it) reads origin,
4
+ // the registry file, and the owner-present check. The one filesystem touch is
5
+ // resolveHomeDir (~/.crysk, else a legacy ~/.prhero); no git, no clock.
6
+ //
7
+ // WHY a module the watcher does not own: ~/.prhero/ used to be watch-only
8
+ // (watch.json, log, lock, plist). Worktrees and run artifacts lived as
9
+ // siblings of each operator checkout, so two clones of the same GitHub repo
10
+ // produced two trees for one PR. The product home now owns ephemeral machine
11
+ // state; the watcher is one tenant. Per-repo trust (config, gotchas) stays
12
+ // in <checkout>/.crysk/ (or a legacy .prhero/).
13
+
14
+ import path from "node:path";
15
+ import { resolveHomeDir } from "./brand-paths";
16
+ import { CliUsageError } from "./errors";
17
+
18
+ export const GC_TTL_HOURS = 72;
19
+
20
+ export interface PrheroLayout {
21
+ dir: string;
22
+ // Compiled binaries resolve optional packages from this directory, not
23
+ // from the embedded filesystem. `upgrade --reconcile` installs the
24
+ // OpenCode SDK here when routing needs it.
25
+ nodeModulesDir: string;
26
+ reposDir: string;
27
+ // C5: two config files live in this dir and NEITHER of them is called
28
+ // configPath. The watcher's opt-in registry (watch.json) and the global
29
+ // review config (config.json) are both `string`, so re-pointing a single
30
+ // `configPath` identifier from one file to the other would have kept
31
+ // compiling at all 19 `paths.configPath` sites in watch/watch.ts while silently
32
+ // reading the wrong file. The name was RETIRED rather than reused: an
33
+ // identifier that no longer exists is the one thing tsc can flag, and no
34
+ // test can enumerate call sites the way the type checker does.
35
+ watchConfigPath: string;
36
+ // Nothing reads this yet — a later C5 unit wires the global review config.
37
+ // It ships now on purpose: arriving beside a retired name is what makes
38
+ // the change above a rename instead of a silent re-point.
39
+ reviewConfigPath: string;
40
+ logPath: string;
41
+ lockPath: string;
42
+ launchdLogPath: string;
43
+ // W4 (#23): ONE global sqlite db, siblings with reposDir rather than
44
+ // nested under it, so GC's `glob.scan({ cwd: reposDir })` (store/gc.ts)
45
+ // structurally cannot enumerate or delete it.
46
+ metricsDbPath: string;
47
+ // Canonical product database (Fundamentals #6 / observability-canonical-store.md)
48
+ prheroDbPath: string;
49
+ // Local store server Unix domain socket
50
+ storeSocketPath: string;
51
+ // Upgrade check TTL cache
52
+ upgradeCheckPath: string;
53
+ // D1-08 PR3 (§9.2/Q5): the persisted, non-secret HMAC key that derives
54
+ // rate-limit bucket IDs. Sibling of the other home files for the same
55
+ // reason as metricsDbPath: one place, no drift between the layout and the
56
+ // consumer that reads it. Rotation is delete-the-file.
57
+ bucketKeyPath: string;
58
+ }
59
+
60
+ export function prheroLayout(
61
+ home: string,
62
+ exists?: (p: string) => boolean,
63
+ ): PrheroLayout {
64
+ const dir = resolveHomeDir(home, exists);
65
+ return {
66
+ dir,
67
+ nodeModulesDir: path.join(dir, "node_modules"),
68
+ reposDir: path.join(dir, "repos"),
69
+ watchConfigPath: path.join(dir, "watch.json"),
70
+ reviewConfigPath: path.join(dir, "config.json"),
71
+ logPath: path.join(dir, "watch.log"),
72
+ lockPath: path.join(dir, "watch.lock"),
73
+ launchdLogPath: path.join(dir, "launchd.log"),
74
+ metricsDbPath: path.join(dir, "metrics.db"),
75
+ prheroDbPath: path.join(dir, "prhero.db"),
76
+ storeSocketPath: path.join(dir, "store.sock"),
77
+ upgradeCheckPath: path.join(dir, "upgrade-check.json"),
78
+ bucketKeyPath: path.join(dir, "bucket-key"),
79
+ };
80
+ }
81
+
82
+ export interface RepoHomePaths {
83
+ repoId: string;
84
+ root: string;
85
+ registry: string;
86
+ worktrees: string;
87
+ runs: string;
88
+ }
89
+
90
+ export function repoHomePaths(home: string, repoId: string): RepoHomePaths {
91
+ const root = path.join(prheroLayout(home).reposDir, repoId);
92
+ return {
93
+ repoId,
94
+ root,
95
+ registry: path.join(root, "registry.json"),
96
+ worktrees: path.join(root, "worktrees"),
97
+ runs: path.join(root, "runs"),
98
+ };
99
+ }
100
+
101
+ // Review trees live under the product home, keyed by canonical remote, not
102
+ // by the operator checkout basename. Two clones of the same GitHub repo
103
+ // therefore share one worktree for PR N.
104
+ export function prWorktreePath(
105
+ home: string,
106
+ repoId: string,
107
+ pr: number,
108
+ ): string {
109
+ return path.join(repoHomePaths(home, repoId).worktrees, `pr-${pr}`);
110
+ }
111
+
112
+ // Run artifacts NEVER live inside the reviewed tree. The default root is
113
+ // now the same home as the worktrees, so ledger/watch/GC scan one place.
114
+ export function defaultRunRoot(home: string, repoId: string): string {
115
+ return repoHomePaths(home, repoId).runs;
116
+ }
117
+
118
+ // The pre-W3 sibling formulas, kept only so a leftover tree can be named
119
+ // in a migration hint. New reviews never create these paths.
120
+ export function legacyWorktreePath(operatorRoot: string, pr: number): string {
121
+ const parent = path.dirname(operatorRoot);
122
+ return path.join(
123
+ parent,
124
+ `${path.basename(operatorRoot)}-worktrees`,
125
+ `pr-${pr}`,
126
+ );
127
+ }
128
+
129
+ export function legacyRunRoot(operatorRoot: string): string {
130
+ const parent = path.dirname(operatorRoot);
131
+ return path.join(parent, `${path.basename(operatorRoot)}-prhero-runs`);
132
+ }
133
+
134
+ export function worktreeLockPath(
135
+ home: string,
136
+ repoId: string,
137
+ pr: number,
138
+ ): string {
139
+ return `${prWorktreePath(home, repoId, pr)}.lock`;
140
+ }
141
+
142
+ export function registryLockPath(registryPath: string): string {
143
+ return `${registryPath}.lock`;
144
+ }
145
+
146
+ // Exclusive pid-file lock (O_EXCL create, steal a dead holder, fail loud
147
+ // on a live one). The I/O shell in home.ts enacts this; GC asks
148
+ // worktreeInFlight, which is the same "live pid" predicate.
149
+ export type PidLockDecision =
150
+ | { action: "create" }
151
+ | { action: "steal"; deadPid: number | null }
152
+ | { action: "held"; pid: number };
153
+
154
+ export function decidePidLock(input: {
155
+ fileExists: boolean;
156
+ existingPid: number | null;
157
+ holderAlive: boolean;
158
+ }): PidLockDecision {
159
+ if (!input.fileExists) return { action: "create" };
160
+ if (input.existingPid === null || !input.holderAlive) {
161
+ return { action: "steal", deadPid: input.existingPid };
162
+ }
163
+ return { action: "held", pid: input.existingPid };
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Repo identity: origin URL → a filesystem-safe id.
168
+ //
169
+ // origin only (extra remotes ignored). SSH and HTTPS of the same GitHub
170
+ // repo must collide. The id is nested (`github.com/org/repo`) so a human
171
+ // can find it; `..` and empty segments are rejected so a weird remote
172
+ // cannot escape ~/.prhero/repos/. GitHub's namespace is case-insensitive,
173
+ // so the path is folded there; other hosts may treat Org/Repo and org/repo
174
+ // as distinct, and folding them would share one git-dir owner across two
175
+ // remotes.
176
+
177
+ export function canonicalRemoteId(originUrl: string): string {
178
+ const trimmed = originUrl.trim();
179
+ if (trimmed.length === 0) {
180
+ throw new CliUsageError("origin URL is empty");
181
+ }
182
+ // Reject before URL.parse: the parser collapses `/../`, which would let a
183
+ // remote escape ~/.prhero/repos/ as a lookalike of a real host/path.
184
+ if (
185
+ trimmed
186
+ .split(/[/\\:]/)
187
+ .some((segment) => segment === "." || segment === "..")
188
+ ) {
189
+ throw new CliUsageError(
190
+ `origin URL contains an empty or parent path segment: ` +
191
+ JSON.stringify(originUrl),
192
+ );
193
+ }
194
+ let host: string;
195
+ let repoPath: string;
196
+ const scp = /^([^@\s/]+)@([^:]+):(.+)$/.exec(trimmed);
197
+ if (scp !== null && !trimmed.includes("://")) {
198
+ host = scp[2] ?? "";
199
+ repoPath = scp[3] ?? "";
200
+ } else {
201
+ let parsed: URL;
202
+ try {
203
+ parsed = new URL(trimmed);
204
+ } catch {
205
+ throw new CliUsageError(
206
+ `origin URL is not a valid remote: ${JSON.stringify(originUrl)}`,
207
+ );
208
+ }
209
+ host = parsed.hostname;
210
+ repoPath = parsed.pathname;
211
+ }
212
+ host = host.toLowerCase();
213
+ repoPath = repoPath.replaceAll("\\", "/").replace(/^\/+/, "");
214
+ repoPath = repoPath.replace(/\.git$/i, "").replace(/\/+$/, "");
215
+ if (host === "github.com" || host.endsWith(".github.com")) {
216
+ repoPath = repoPath.toLowerCase();
217
+ }
218
+ if (host.length === 0 || repoPath.length === 0) {
219
+ throw new CliUsageError(
220
+ `origin URL is missing a host or path: ${JSON.stringify(originUrl)}`,
221
+ );
222
+ }
223
+ const segments = [host, ...repoPath.split("/")];
224
+ for (const segment of segments) {
225
+ if (segment.length === 0 || segment === "." || segment === "..") {
226
+ throw new CliUsageError(
227
+ `origin URL contains an empty or parent path segment: ` +
228
+ JSON.stringify(originUrl),
229
+ );
230
+ }
231
+ }
232
+ return segments.join("/");
233
+ }
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // registry.json — which checkout owns `git worktree add` for this remote.
237
+ //
238
+ // git worktree add is bound to one git dir. Two independent clones cannot
239
+ // share a worktree without picking a single owner. First registration wins;
240
+ // a second clone of the same origin is appended and does not steal ownership.
241
+ // If the owner path is gone, fail loud — do not silently promote the cwd.
242
+
243
+ export interface WorktreeStamp {
244
+ last_review_at: string;
245
+ }
246
+
247
+ export interface RepoRegistry {
248
+ canonical_remote: string;
249
+ origin_url: string;
250
+ git_dir_owner: string;
251
+ operator_checkouts: string[];
252
+ worktrees: Record<string, WorktreeStamp>;
253
+ }
254
+
255
+ export type RegistryUpsert =
256
+ | { action: "create"; registry: RepoRegistry }
257
+ | { action: "append-checkout"; registry: RepoRegistry }
258
+ | { action: "unchanged"; registry: RepoRegistry }
259
+ | { action: "owner-gone"; registry: RepoRegistry; message: string };
260
+
261
+ export function decideRegistryUpsert(input: {
262
+ existing: RepoRegistry | null;
263
+ canonicalRemote: string;
264
+ originUrl: string;
265
+ checkoutPath: string;
266
+ ownerPresent: boolean;
267
+ }): RegistryUpsert {
268
+ const checkout = path.resolve(input.checkoutPath);
269
+ if (input.existing === null) {
270
+ return {
271
+ action: "create",
272
+ registry: {
273
+ canonical_remote: input.canonicalRemote,
274
+ origin_url: input.originUrl,
275
+ git_dir_owner: checkout,
276
+ operator_checkouts: [checkout],
277
+ worktrees: {},
278
+ },
279
+ };
280
+ }
281
+ const registry = input.existing;
282
+ if (!input.ownerPresent) {
283
+ return {
284
+ action: "owner-gone",
285
+ registry,
286
+ message:
287
+ `git-dir owner ${registry.git_dir_owner} is gone or is no longer a ` +
288
+ `git directory. Delete ${input.canonicalRemote}'s registry.json and ` +
289
+ `re-run from a live clone so that checkout becomes the new owner.`,
290
+ };
291
+ }
292
+ const known = registry.operator_checkouts.some(
293
+ (stored) => path.resolve(stored) === checkout,
294
+ );
295
+ if (known) {
296
+ return { action: "unchanged", registry };
297
+ }
298
+ return {
299
+ action: "append-checkout",
300
+ registry: {
301
+ ...registry,
302
+ operator_checkouts: [...registry.operator_checkouts, checkout],
303
+ },
304
+ };
305
+ }
306
+
307
+ export function touchWorktreeStamp(
308
+ registry: RepoRegistry,
309
+ pr: number,
310
+ isoTimestamp: string,
311
+ ): RepoRegistry {
312
+ return {
313
+ ...registry,
314
+ worktrees: {
315
+ ...registry.worktrees,
316
+ [String(pr)]: { last_review_at: isoTimestamp },
317
+ },
318
+ };
319
+ }
320
+
321
+ export function parseRepoRegistry(raw: string): RepoRegistry {
322
+ let parsed: unknown;
323
+ try {
324
+ parsed = JSON.parse(raw);
325
+ } catch (error) {
326
+ throw new CliUsageError(
327
+ `registry.json is not valid JSON: ${(error as Error).message}`,
328
+ );
329
+ }
330
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
331
+ throw new CliUsageError("registry.json must be a single JSON object");
332
+ }
333
+ const record = parsed as Record<string, unknown>;
334
+ const canonical = requiredString(record, "canonical_remote");
335
+ const originUrl = requiredString(record, "origin_url");
336
+ const owner = requiredString(record, "git_dir_owner");
337
+ const checkouts = record.operator_checkouts;
338
+ if (!Array.isArray(checkouts) || checkouts.length === 0) {
339
+ throw new CliUsageError(
340
+ `registry.json "operator_checkouts" must be a non-empty array, got: ` +
341
+ JSON.stringify(checkouts),
342
+ );
343
+ }
344
+ const operator_checkouts: string[] = [];
345
+ for (let i = 0; i < checkouts.length; i++) {
346
+ const entry = checkouts[i];
347
+ if (typeof entry !== "string" || entry.trim().length === 0) {
348
+ throw new CliUsageError(
349
+ `registry.json operator_checkouts[${i}] must be a non-empty string, ` +
350
+ `got: ${JSON.stringify(entry)}`,
351
+ );
352
+ }
353
+ operator_checkouts.push(entry);
354
+ }
355
+ return {
356
+ canonical_remote: canonical,
357
+ origin_url: originUrl,
358
+ git_dir_owner: owner,
359
+ operator_checkouts,
360
+ worktrees: parseWorktreeStamps(record.worktrees),
361
+ };
362
+ }
363
+
364
+ function requiredString(record: Record<string, unknown>, key: string): string {
365
+ const value = record[key];
366
+ if (typeof value !== "string" || value.trim().length === 0) {
367
+ throw new CliUsageError(
368
+ `registry.json "${key}" must be a non-empty string, got: ` +
369
+ JSON.stringify(value),
370
+ );
371
+ }
372
+ return value;
373
+ }
374
+
375
+ function parseWorktreeStamps(raw: unknown): Record<string, WorktreeStamp> {
376
+ if (raw === undefined) return {};
377
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
378
+ throw new CliUsageError(
379
+ `registry.json "worktrees" must be an object, got: ${JSON.stringify(raw)}`,
380
+ );
381
+ }
382
+ const stamps: Record<string, WorktreeStamp> = {};
383
+ for (const [pr, value] of Object.entries(raw as Record<string, unknown>)) {
384
+ if (!/^\d+$/.test(pr) || Number(pr) < 1) {
385
+ throw new CliUsageError(
386
+ `registry.json worktrees key must be a positive PR number, got: ` +
387
+ JSON.stringify(pr),
388
+ );
389
+ }
390
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
391
+ throw new CliUsageError(
392
+ `registry.json worktrees[${pr}] must be an object`,
393
+ );
394
+ }
395
+ const stamp = value as Record<string, unknown>;
396
+ if (
397
+ typeof stamp.last_review_at !== "string" ||
398
+ stamp.last_review_at.trim().length === 0
399
+ ) {
400
+ throw new CliUsageError(
401
+ `registry.json worktrees[${pr}].last_review_at must be a non-empty ` +
402
+ `string, got: ${JSON.stringify(stamp.last_review_at)}`,
403
+ );
404
+ }
405
+ stamps[pr] = { last_review_at: stamp.last_review_at };
406
+ }
407
+ return stamps;
408
+ }
409
+
410
+ export function serializeRepoRegistry(registry: RepoRegistry): string {
411
+ return `${JSON.stringify(registry, null, 2)}\n`;
412
+ }
413
+
414
+ export function ownerGoneMessage(
415
+ registryPath: string,
416
+ message: string,
417
+ ): string {
418
+ return `${message} (registry: ${registryPath})`;
419
+ }
420
+
421
+ // Loud, copy-pasteable, and never a move. The leftover tree's .git file
422
+ // still points at the old clone; auto-moving it is how you detach a live
423
+ // codegraph daemon. The next review recreates under the home.
424
+ export function legacyMigrationHint(input: {
425
+ operatorRoot: string;
426
+ legacyWorktree: string;
427
+ newWorktree: string;
428
+ }): string[] {
429
+ return [
430
+ `legacy worktree still at ${input.legacyWorktree}`,
431
+ `Crysk now keeps review trees under ${input.newWorktree}`,
432
+ "remove the leftover with:",
433
+ ` git -C ${input.operatorRoot} worktree remove --force ${input.legacyWorktree}`,
434
+ ];
435
+ }
436
+
437
+ export function missingOriginMessage(repoRoot: string): string {
438
+ return (
439
+ `no git remote named origin in ${repoRoot} — Crysk keys worktrees ` +
440
+ "and run artifacts by the origin URL, so a checkout without origin " +
441
+ "cannot use the global home. Add origin, or pass --out for this run."
442
+ );
443
+ }
package/src/home.ts ADDED
@@ -0,0 +1,243 @@
1
+ // I/O for the global ~/.prhero/ product home (W3 / #24). Every decision it
2
+ // acts on lives in home-preflight.ts. cli.ts and watch/watch.ts call this so the
3
+ // registry read/write and the origin lookup are not copied across shells.
4
+ //
5
+ // Same git-runner rule as the other shells: args as an ARRAY, never an
6
+ // interpolated shell string.
7
+
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { mkdir, open, rename, rm } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { git } from "#git/git";
12
+ import { parseLockPid } from "#watch/preflight";
13
+ import { CliError } from "./errors";
14
+ import {
15
+ canonicalRemoteId,
16
+ decidePidLock,
17
+ decideRegistryUpsert,
18
+ missingOriginMessage,
19
+ ownerGoneMessage,
20
+ parseRepoRegistry,
21
+ type RepoHomePaths,
22
+ type RepoRegistry,
23
+ registryLockPath,
24
+ repoHomePaths,
25
+ serializeRepoRegistry,
26
+ touchWorktreeStamp,
27
+ } from "./home-preflight";
28
+
29
+ const PID_LOCK_ATTEMPTS = 3;
30
+
31
+ export async function gitOriginUrl(repoRoot: string): Promise<string> {
32
+ const result = await git(repoRoot, ["remote", "get-url", "origin"]);
33
+ if (!result.ok) {
34
+ throw new CliError(missingOriginMessage(repoRoot));
35
+ }
36
+ const url = result.stdout.trim();
37
+ if (url.length === 0) {
38
+ throw new CliError(missingOriginMessage(repoRoot));
39
+ }
40
+ return url;
41
+ }
42
+
43
+ // The `--out` escape hatch (W4 Phase 6 remediation, GitHub #23 option D)
44
+ // needs to know whether origin is resolvable WITHOUT the no-origin case
45
+ // being an error: gitOriginUrl throws CliError precisely for "no remote" /
46
+ // "empty remote", and that is the only failure this function should ever
47
+ // swallow. Anything else (a spawn failure, a permissions error) propagates —
48
+ // resolving origin quietly failing open on unexpected errors would ingest
49
+ // runs under a wrong-looking blank slate instead of surfacing the fault.
50
+ export async function tryOriginRepoId(
51
+ repoRoot: string,
52
+ ): Promise<string | null> {
53
+ let url: string;
54
+ try {
55
+ url = await gitOriginUrl(repoRoot);
56
+ } catch (error) {
57
+ if (error instanceof CliError) return null;
58
+ throw error;
59
+ }
60
+ return canonicalRemoteId(url);
61
+ }
62
+
63
+ export function ownerPresent(ownerPath: string): boolean {
64
+ return existsSync(ownerPath) && existsSync(path.join(ownerPath, ".git"));
65
+ }
66
+
67
+ function pidAlive(pid: number): boolean {
68
+ try {
69
+ process.kill(pid, 0);
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ function isEexist(error: unknown): boolean {
77
+ return (
78
+ typeof error === "object" &&
79
+ error !== null &&
80
+ "code" in error &&
81
+ (error as { code: unknown }).code === "EEXIST"
82
+ );
83
+ }
84
+
85
+ export function worktreeInFlight(lockPath: string): boolean {
86
+ const snapshot = readLockPidSync(lockPath);
87
+ return snapshot.existingPid !== null && pidAlive(snapshot.existingPid);
88
+ }
89
+
90
+ function readLockPidSync(lockPath: string): {
91
+ fileExists: boolean;
92
+ existingPid: number | null;
93
+ } {
94
+ if (!existsSync(lockPath)) {
95
+ return { fileExists: false, existingPid: null };
96
+ }
97
+ try {
98
+ const raw = readFileSync(lockPath, "utf8");
99
+ return { fileExists: true, existingPid: parseLockPid(raw) };
100
+ } catch {
101
+ return { fileExists: true, existingPid: null };
102
+ }
103
+ }
104
+
105
+ export async function acquirePidLock(lockPath: string): Promise<void> {
106
+ await mkdir(path.dirname(lockPath), { recursive: true });
107
+ for (let attempt = 0; attempt < PID_LOCK_ATTEMPTS; attempt++) {
108
+ try {
109
+ const handle = await open(lockPath, "wx");
110
+ try {
111
+ await handle.writeFile(`${process.pid}\n`);
112
+ } finally {
113
+ await handle.close();
114
+ }
115
+ return;
116
+ } catch (error) {
117
+ if (!isEexist(error)) throw error;
118
+ }
119
+ const snapshot = readLockPidSync(lockPath);
120
+ const holderAlive =
121
+ snapshot.existingPid !== null && pidAlive(snapshot.existingPid);
122
+ const decision = decidePidLock({
123
+ fileExists: snapshot.fileExists,
124
+ existingPid: snapshot.existingPid,
125
+ holderAlive,
126
+ });
127
+ if (decision.action === "held") {
128
+ throw new CliError(`lock held by pid ${decision.pid}: ${lockPath}`);
129
+ }
130
+ if (decision.action === "create") continue;
131
+ await rm(lockPath, { force: true });
132
+ }
133
+ throw new CliError(`could not acquire lock: ${lockPath}`);
134
+ }
135
+
136
+ export async function releasePidLock(lockPath: string): Promise<void> {
137
+ await rm(lockPath, { force: true });
138
+ }
139
+
140
+ export interface ResolvedRepoHome {
141
+ repoId: string;
142
+ paths: RepoHomePaths;
143
+ registry: RepoRegistry;
144
+ gitDirOwner: string;
145
+ upsertAction: "create" | "append-checkout" | "unchanged";
146
+ }
147
+
148
+ async function readRegistry(
149
+ registryPath: string,
150
+ ): Promise<RepoRegistry | null> {
151
+ if (!existsSync(registryPath)) return null;
152
+ return parseRepoRegistry(await Bun.file(registryPath).text());
153
+ }
154
+
155
+ function upsertFromExisting(
156
+ existing: RepoRegistry | null,
157
+ repoId: string,
158
+ originUrl: string,
159
+ operatorRoot: string,
160
+ ): ReturnType<typeof decideRegistryUpsert> {
161
+ return decideRegistryUpsert({
162
+ existing,
163
+ canonicalRemote: repoId,
164
+ originUrl,
165
+ checkoutPath: operatorRoot,
166
+ ownerPresent:
167
+ existing === null ? true : ownerPresent(existing.git_dir_owner),
168
+ });
169
+ }
170
+
171
+ export async function resolveRepoHome(input: {
172
+ home: string;
173
+ operatorRoot: string;
174
+ persist: boolean;
175
+ }): Promise<ResolvedRepoHome> {
176
+ const originUrl = await gitOriginUrl(input.operatorRoot);
177
+ const repoId = canonicalRemoteId(originUrl);
178
+ const paths = repoHomePaths(input.home, repoId);
179
+ const apply = async (existing: RepoRegistry | null) => {
180
+ const decision = upsertFromExisting(
181
+ existing,
182
+ repoId,
183
+ originUrl,
184
+ input.operatorRoot,
185
+ );
186
+ if (decision.action === "owner-gone") {
187
+ throw new CliError(ownerGoneMessage(paths.registry, decision.message));
188
+ }
189
+ if (input.persist && decision.action !== "unchanged") {
190
+ await writeRepoRegistry(paths.registry, decision.registry);
191
+ }
192
+ return {
193
+ repoId,
194
+ paths,
195
+ registry: decision.registry,
196
+ gitDirOwner: decision.registry.git_dir_owner,
197
+ upsertAction: decision.action,
198
+ } satisfies ResolvedRepoHome;
199
+ };
200
+ if (!input.persist) {
201
+ return apply(await readRegistry(paths.registry));
202
+ }
203
+ const lockPath = registryLockPath(paths.registry);
204
+ await acquirePidLock(lockPath);
205
+ try {
206
+ return await apply(await readRegistry(paths.registry));
207
+ } finally {
208
+ await releasePidLock(lockPath);
209
+ }
210
+ }
211
+
212
+ export async function writeRepoRegistry(
213
+ registryPath: string,
214
+ registry: RepoRegistry,
215
+ ): Promise<void> {
216
+ await mkdir(path.dirname(registryPath), { recursive: true });
217
+ const tmp = `${registryPath}.tmp`;
218
+ await Bun.write(tmp, serializeRepoRegistry(registry));
219
+ await rename(tmp, registryPath);
220
+ }
221
+
222
+ export async function stampWorktree(
223
+ registryPath: string,
224
+ pr: number,
225
+ isoTimestamp: string,
226
+ ): Promise<RepoRegistry> {
227
+ const lockPath = registryLockPath(registryPath);
228
+ await acquirePidLock(lockPath);
229
+ try {
230
+ const existing = await readRegistry(registryPath);
231
+ if (existing === null) {
232
+ throw new CliError(
233
+ `registry.json is missing; cannot stamp worktree pr-${pr} ` +
234
+ `(${registryPath})`,
235
+ );
236
+ }
237
+ const next = touchWorktreeStamp(existing, pr, isoTimestamp);
238
+ await writeRepoRegistry(registryPath, next);
239
+ return next;
240
+ } finally {
241
+ await releasePidLock(lockPath);
242
+ }
243
+ }