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/ui/menu.ts ADDED
@@ -0,0 +1,1325 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { DEFAULT_MAX_VERIFICATION_STEPS } from "#review/preflight";
5
+ import { DEFAULT_SIZE_GATE } from "#review/size-gate";
6
+ import { listActiveRuns } from "#store/activity";
7
+ import { DEFAULT_DAILY_CAP } from "#watch/preflight";
8
+ import { resolveHomeDir, resolveRepoDir } from "../brand-paths";
9
+ import { runDoctor } from "../doctor";
10
+ import {
11
+ getMenuOptions,
12
+ type MenuItem,
13
+ type MenuStatusInfo,
14
+ type RepoContext,
15
+ resolveMenuContext,
16
+ } from "../menu-context";
17
+ import {
18
+ cycleStringPreset,
19
+ DEFAULT_CARD_ACTIONS,
20
+ getEditableLayerEntries,
21
+ renderConfigEditCard,
22
+ saveLayerConfig,
23
+ stepNumericValue,
24
+ } from "./config-edit";
25
+ import {
26
+ bold,
27
+ box,
28
+ cyan,
29
+ dim,
30
+ sanitizeText,
31
+ terminalWidth,
32
+ } from "./primitives";
33
+ import { type KeyReader, parseKey, splitKeys } from "./select";
34
+
35
+ const SOLID_BANNER_LINES = [
36
+ "██████╗ ██████╗ ██╗ ██╗███████╗██████╗ ██████╗ ",
37
+ "██╔══██╗██╔══██╗ ██║ ██║██╔════╝██╔══██╗██╔═══██╗",
38
+ "██████╔╝██████╔╝█████╗███████║█████╗ ██████╔╝██║ ██║",
39
+ "██╔═══╝ ██╔══██╗╚════╝██╔══██║██╔══╝ ██╔══██╗██║ ██║",
40
+ "██║ ██║ ██║ ██║ ██║███████╗██║ ██║╚██████╔╝",
41
+ "╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ",
42
+ ];
43
+
44
+ export function renderSolidHeader(width: number, styles: boolean): string[] {
45
+ if (width >= 60) {
46
+ return SOLID_BANNER_LINES.map((line) => cyan(bold(line, styles), styles));
47
+ }
48
+ const title = "PR-HERO — Multi-Agent PR Review";
49
+ const truncated =
50
+ width < title.length ? title.slice(0, Math.max(0, width)) : title;
51
+ return [cyan(bold(truncated, styles), styles)];
52
+ }
53
+
54
+ export function renderContextBox(
55
+ context: RepoContext,
56
+ width: number,
57
+ styles: boolean,
58
+ ): string[] {
59
+ const lines: string[] = [];
60
+
61
+ if (context.kind === "configured-repo") {
62
+ const name = sanitizeText(context.name);
63
+ const root = sanitizeText(context.root);
64
+ const base = context.defaultBase
65
+ ? sanitizeText(context.defaultBase)
66
+ : "auto";
67
+ lines.push(`Repository: ${name} (${root})`, `Base branch: ${base}`);
68
+ } else if (context.kind === "unconfigured-repo") {
69
+ const name = sanitizeText(context.name);
70
+ const root = sanitizeText(context.root);
71
+ lines.push(
72
+ `Unconfigured Repository: ${name} (${root})`,
73
+ "Run 'Initialize repo' to scaffold .crysk/ configuration.",
74
+ );
75
+ } else {
76
+ const cwd = sanitizeText(context.cwd);
77
+ lines.push(
78
+ `Not inside a repository (${cwd})`,
79
+ "Global commands and configuration are available.",
80
+ );
81
+ }
82
+
83
+ return box("Current Context", lines, {
84
+ width,
85
+ styles,
86
+ borderStyle: "double",
87
+ });
88
+ }
89
+
90
+ export function renderMenuCard(
91
+ items: MenuItem[],
92
+ selectedIndex: number,
93
+ width: number,
94
+ styles: boolean,
95
+ ): string[] {
96
+ const lines: string[] = [];
97
+
98
+ items.forEach((item, index) => {
99
+ const isSelected = index === selectedIndex;
100
+ const prefix = isSelected ? "▸ " : " ";
101
+ const num = `${index + 1}. `;
102
+ const badge = item.badge ? ` (${item.badge})` : "";
103
+ const submenu = item.isSubmenu ? " →" : "";
104
+
105
+ const rawLine = `${prefix}${num}${item.label}${badge}${submenu} - ${item.desc}`;
106
+ lines.push(sanitizeText(rawLine));
107
+ });
108
+
109
+ return box("Main Menu", lines, {
110
+ width,
111
+ styles,
112
+ borderStyle: "double",
113
+ });
114
+ }
115
+
116
+ export function renderPersistentFooter(
117
+ selectedItem: MenuItem | undefined,
118
+ _width: number,
119
+ styles: boolean,
120
+ ): string[] {
121
+ const enterAction = selectedItem?.isSubmenu ? "open submenu" : "run";
122
+ const hints = `j/k: move • 1-9: select • enter: ${enterAction} • q: quit`;
123
+
124
+ const lines = [dim(hints, styles)];
125
+
126
+ if (selectedItem) {
127
+ lines.push(dim(`$ crysk ${selectedItem.cliHint}`, styles));
128
+ }
129
+
130
+ return lines;
131
+ }
132
+
133
+ export async function gatherMenuStatus(
134
+ home: string = os.homedir(),
135
+ cwd: string = process.cwd(),
136
+ ): Promise<MenuStatusInfo> {
137
+ let upgradeAvailable = false;
138
+ try {
139
+ const upgradeCache = path.join(resolveHomeDir(home), "upgrade-check.json");
140
+ if (existsSync(upgradeCache)) {
141
+ const parsed = JSON.parse(readFileSync(upgradeCache, "utf-8"));
142
+ upgradeAvailable = Boolean(
143
+ parsed.latestVersion && parsed.updateAvailable,
144
+ );
145
+ }
146
+ } catch {
147
+ // Ignore
148
+ }
149
+
150
+ let activeReviewsCount = 0;
151
+ try {
152
+ const active = await listActiveRuns({ home });
153
+ activeReviewsCount = active.length;
154
+ } catch {
155
+ // Ignore
156
+ }
157
+
158
+ let doctorStatus: MenuStatusInfo["doctorStatus"];
159
+ try {
160
+ const report = await runDoctor({ home, cwd });
161
+ doctorStatus = report.overall;
162
+ } catch {
163
+ // Ignore
164
+ }
165
+
166
+ return {
167
+ upgradeAvailable,
168
+ activeReviewsCount,
169
+ doctorStatus,
170
+ };
171
+ }
172
+
173
+ export interface MenuLoopIo {
174
+ write: (text: string) => void;
175
+ line: (text?: string) => void;
176
+ }
177
+
178
+ export interface MenuLoopOptions {
179
+ context?: RepoContext;
180
+ status?: MenuStatusInfo;
181
+ // `context`/`status` pin only the FIRST render. Every time an action
182
+ // returns, the loop refreshes them — and that refresh used the real
183
+ // `resolveMenuContext` (a git subprocess) and `gatherMenuStatus` (the full
184
+ // doctor: real `Bun.spawn` of git/claude/gh/codegraph, `gh auth status`
185
+ // among them, which is a live network round trip). A caller that injected
186
+ // both values still shelled out, so the refresh needs a seam of its own.
187
+ // Both default to the real resolvers; no production caller passes either.
188
+ resolveContext?: (cwd: string) => Promise<RepoContext>;
189
+ gatherStatus?: (home: string, cwd: string) => Promise<MenuStatusInfo>;
190
+ createReader?: () => KeyReader;
191
+ io?: MenuLoopIo;
192
+ styles?: boolean;
193
+ width?: number;
194
+ home?: string;
195
+ cwd?: string;
196
+ dispatchAction?: (
197
+ action: string,
198
+ item?: MenuItem,
199
+ ) => Promise<number | "back">;
200
+ }
201
+
202
+ export function createDefaultStdinReader(): KeyReader {
203
+ const stdin = process.stdin;
204
+ if (!stdin.isTTY || typeof stdin.setRawMode !== "function") {
205
+ return {
206
+ raw: false,
207
+ read: async () => undefined,
208
+ close: () => {},
209
+ };
210
+ }
211
+ stdin.setRawMode(true);
212
+ stdin.resume();
213
+ stdin.setEncoding("utf8");
214
+ const pending: string[] = [];
215
+ let deliver: ((chunk: string) => void) | undefined;
216
+ const onData = (chunk: string): void => {
217
+ if (deliver === undefined) {
218
+ pending.push(chunk);
219
+ return;
220
+ }
221
+ const resolve = deliver;
222
+ deliver = undefined;
223
+ resolve(chunk);
224
+ };
225
+ stdin.on("data", onData);
226
+ return {
227
+ raw: true,
228
+ read: () => {
229
+ const queued = pending.shift();
230
+ if (queued !== undefined) return Promise.resolve(queued);
231
+ return new Promise<string>((resolve) => {
232
+ deliver = resolve;
233
+ });
234
+ },
235
+ close: () => {
236
+ stdin.off("data", onData);
237
+ stdin.pause();
238
+ try {
239
+ stdin.setRawMode(false);
240
+ } catch {
241
+ // Ignore
242
+ }
243
+ },
244
+ };
245
+ }
246
+
247
+ export function clearDrawnLines(
248
+ io: MenuLoopIo,
249
+ drawn: number,
250
+ repaint: boolean,
251
+ ): void {
252
+ if (!repaint || drawn <= 0) return;
253
+ const ESC = "\x1b";
254
+ let eraseBuf = `${ESC}[${drawn}A`;
255
+ for (let i = 0; i < drawn; i++) {
256
+ eraseBuf += `${ESC}[2K\n`;
257
+ }
258
+ eraseBuf += `${ESC}[${drawn}A`;
259
+ io.write(eraseBuf);
260
+ }
261
+
262
+ export async function runMenuLoop(
263
+ options: MenuLoopOptions = {},
264
+ ): Promise<number> {
265
+ const home = options.home ?? os.homedir();
266
+ const cwd = options.cwd ?? process.cwd();
267
+ const io = options.io ?? {
268
+ write: (t) => process.stderr.write(t),
269
+ line: (t = "") => process.stderr.write(`${t}\n`),
270
+ };
271
+ const styles = options.styles ?? false;
272
+ let width = options.width ?? terminalWidth();
273
+
274
+ const resolveContext = options.resolveContext ?? resolveMenuContext;
275
+ const gatherStatus = options.gatherStatus ?? gatherMenuStatus;
276
+
277
+ let context = options.context ?? (await resolveContext(cwd));
278
+ let status = options.status ?? (await gatherStatus(home, cwd));
279
+ let items = getMenuOptions(context, status);
280
+ let cursor = 0;
281
+
282
+ const createReader = options.createReader ?? createDefaultStdinReader;
283
+
284
+ let isInteractive = true;
285
+ const ESC = "\x1b";
286
+ const repaint = styles;
287
+ let drawn = 0;
288
+
289
+ const render = (clearScreen = false) => {
290
+ const lines: string[] = [];
291
+ lines.push("");
292
+ lines.push(...renderSolidHeader(width, styles));
293
+ lines.push("");
294
+ lines.push(...renderContextBox(context, width, styles));
295
+ lines.push("");
296
+ lines.push(...renderMenuCard(items, cursor, width, styles));
297
+ lines.push("");
298
+ lines.push(...renderPersistentFooter(items[cursor], width, styles));
299
+
300
+ let buf = "";
301
+ if (repaint && clearScreen) {
302
+ buf += `${ESC}[2J${ESC}[H`;
303
+ drawn = 0;
304
+ } else if (repaint && drawn > 0) {
305
+ buf += `${ESC}[${drawn}A`;
306
+ }
307
+ for (const line of lines) {
308
+ if (repaint && drawn > 0) buf += `${ESC}[2K`;
309
+ buf += `${line}\n`;
310
+ }
311
+ io.write(buf);
312
+ drawn = lines.length;
313
+ };
314
+
315
+ const onResize = () => {
316
+ if (!isInteractive) return;
317
+ width = terminalWidth();
318
+ render(true);
319
+ };
320
+ process.on("SIGWINCH", onResize);
321
+
322
+ try {
323
+ if (repaint) io.write(`${ESC}[?25l`);
324
+ let needsClear = true;
325
+ for (;;) {
326
+ render(needsClear);
327
+ needsClear = false;
328
+ const reader = createReader();
329
+ let chosenItem: MenuItem | undefined;
330
+
331
+ try {
332
+ for (;;) {
333
+ const chunk = await reader.read();
334
+ if (chunk === undefined) {
335
+ return 0;
336
+ }
337
+
338
+ let shouldBreakInner = false;
339
+ for (const rawKey of splitKeys(chunk)) {
340
+ const key = parseKey(rawKey);
341
+ if (
342
+ key.type === "escape" ||
343
+ (key.type === "char" && key.char === "q")
344
+ ) {
345
+ return 0;
346
+ }
347
+ if (key.type === "ctrl-c") {
348
+ return 130;
349
+ }
350
+ if (
351
+ key.type === "up" ||
352
+ (key.type === "char" && key.char === "k")
353
+ ) {
354
+ cursor = (cursor - 1 + items.length) % items.length;
355
+ render(false);
356
+ continue;
357
+ }
358
+ if (
359
+ key.type === "down" ||
360
+ (key.type === "char" && key.char === "j")
361
+ ) {
362
+ cursor = (cursor + 1) % items.length;
363
+ render(false);
364
+ continue;
365
+ }
366
+ if (key.type === "char" && /^[1-9]$/.test(key.char)) {
367
+ const numIdx = Number(key.char) - 1;
368
+ if (numIdx >= 0 && numIdx < items.length) {
369
+ cursor = numIdx;
370
+ render(false);
371
+ }
372
+ continue;
373
+ }
374
+ if (key.type === "enter") {
375
+ chosenItem = items[cursor];
376
+ shouldBreakInner = true;
377
+ break;
378
+ }
379
+ }
380
+
381
+ if (shouldBreakInner) break;
382
+ }
383
+ } finally {
384
+ reader.close();
385
+ }
386
+
387
+ if (!chosenItem) continue;
388
+ if (chosenItem.id === "quit") return 0;
389
+
390
+ // Dispatch action
391
+ if (options.dispatchAction) {
392
+ isInteractive = false;
393
+ drawn = 0;
394
+ if (repaint) io.write(`${ESC}[?25h`);
395
+ let exit: number | "back";
396
+ try {
397
+ exit = await options.dispatchAction(chosenItem.id, chosenItem);
398
+ } finally {
399
+ isInteractive = true;
400
+ width = terminalWidth();
401
+ drawn = 0;
402
+ if (repaint) io.write(`${ESC}[?25l`);
403
+ }
404
+ if (exit === "back") {
405
+ context = await resolveContext(cwd);
406
+ status = await gatherStatus(home, cwd);
407
+ items = getMenuOptions(context, status);
408
+ cursor = Math.min(cursor, items.length - 1);
409
+ needsClear = true;
410
+ continue;
411
+ }
412
+ if (
413
+ typeof exit === "number" &&
414
+ (chosenItem.id === "review" || chosenItem.id === "lifecycle")
415
+ ) {
416
+ return exit;
417
+ }
418
+ } else {
419
+ io.line(`\n[Action: ${chosenItem.label}]`);
420
+ }
421
+
422
+ // Pause before returning to menu
423
+ drawn = 0;
424
+ if (repaint) io.write(`${ESC}[?25h`);
425
+ io.line();
426
+ io.line(dim("Press any key to return to menu...", styles));
427
+ const pauseReader = createReader();
428
+ try {
429
+ await pauseReader.read();
430
+ } finally {
431
+ pauseReader.close();
432
+ if (repaint) io.write(`${ESC}[?25l`);
433
+ }
434
+
435
+ // Refresh context and status on return
436
+ drawn = 0;
437
+ context = await resolveContext(cwd);
438
+ status = await gatherStatus(home, cwd);
439
+ items = getMenuOptions(context, status);
440
+ cursor = Math.min(cursor, items.length - 1);
441
+ needsClear = true;
442
+ }
443
+ } finally {
444
+ clearDrawnLines(io, drawn, repaint);
445
+ drawn = 0;
446
+ if (repaint) io.write(`${ESC}[?25h`);
447
+ process.off("SIGWINCH", onResize);
448
+ }
449
+ }
450
+
451
+ export async function runLifecycleSubmenu(deps: {
452
+ createReader?: () => KeyReader;
453
+ io?: MenuLoopIo;
454
+ styles?: boolean;
455
+ width?: number;
456
+ dispatch?: (cmd: string) => Promise<number>;
457
+ }): Promise<number | "back"> {
458
+ const io = deps.io ?? {
459
+ write: (t) => process.stderr.write(t),
460
+ line: (t = "") => process.stderr.write(`${t}\n`),
461
+ };
462
+ const styles = deps.styles ?? false;
463
+ const width = deps.width ?? 80;
464
+ const createReader = deps.createReader ?? createDefaultStdinReader;
465
+
466
+ const items = [
467
+ {
468
+ id: "upgrade",
469
+ label: "Upgrade & sync",
470
+ desc: "Upgrade crysk and reconcile skills",
471
+ isTerminal: true,
472
+ },
473
+ {
474
+ id: "setup",
475
+ label: "Sync skills & MCP",
476
+ desc: "Reconcile installed skills and MCP registrations",
477
+ isTerminal: false,
478
+ },
479
+ {
480
+ id: "uninstall",
481
+ label: "Managed uninstall",
482
+ desc: "Remove daemon, skills and registrations",
483
+ isTerminal: true,
484
+ },
485
+ {
486
+ id: "back",
487
+ label: "Back",
488
+ desc: "Return to main menu",
489
+ isTerminal: false,
490
+ },
491
+ ];
492
+
493
+ let cursor = 0;
494
+ const ESC = "\x1b";
495
+ const repaint = styles;
496
+ let drawn = 0;
497
+
498
+ const render = (clearScreen = false) => {
499
+ const cardLines = items.map((item, idx) => {
500
+ const prefix = idx === cursor ? "▸ " : " ";
501
+ return `${prefix}${idx + 1}. ${item.label} - ${item.desc}`;
502
+ });
503
+ const lines: string[] = [
504
+ "",
505
+ ...box("Lifecycle & Maintenance", cardLines, {
506
+ width,
507
+ styles,
508
+ borderStyle: "double",
509
+ }),
510
+ dim("j/k: move • enter: select • q/esc: back", styles),
511
+ ];
512
+
513
+ let buf = "";
514
+ if (repaint && clearScreen) {
515
+ buf += `${ESC}[2J${ESC}[H`;
516
+ drawn = 0;
517
+ } else if (repaint && drawn > 0) {
518
+ buf += `${ESC}[${drawn}A`;
519
+ }
520
+ for (const l of lines) {
521
+ if (repaint && drawn > 0) buf += `${ESC}[2K`;
522
+ buf += `${l}\n`;
523
+ }
524
+ io.write(buf);
525
+ drawn = lines.length;
526
+ };
527
+
528
+ try {
529
+ if (repaint) io.write(`${ESC}[?25l`);
530
+ let needsClear = true;
531
+ for (;;) {
532
+ render(needsClear);
533
+ needsClear = false;
534
+ const reader = createReader();
535
+ let chosen: (typeof items)[0] | undefined;
536
+ try {
537
+ for (;;) {
538
+ const chunk = await reader.read();
539
+ if (chunk === undefined) return "back";
540
+ let done = false;
541
+ for (const raw of splitKeys(chunk)) {
542
+ const key = parseKey(raw);
543
+ if (
544
+ key.type === "escape" ||
545
+ key.type === "ctrl-c" ||
546
+ (key.type === "char" && key.char === "q")
547
+ ) {
548
+ return "back";
549
+ }
550
+ if (
551
+ key.type === "up" ||
552
+ (key.type === "char" && key.char === "k")
553
+ ) {
554
+ cursor = (cursor - 1 + items.length) % items.length;
555
+ render(false);
556
+ continue;
557
+ }
558
+ if (
559
+ key.type === "down" ||
560
+ (key.type === "char" && key.char === "j")
561
+ ) {
562
+ cursor = (cursor + 1) % items.length;
563
+ render(false);
564
+ continue;
565
+ }
566
+ if (key.type === "char" && /^[1-4]$/.test(key.char)) {
567
+ cursor = Number(key.char) - 1;
568
+ render(false);
569
+ continue;
570
+ }
571
+ if (key.type === "enter") {
572
+ chosen = items[cursor];
573
+ done = true;
574
+ break;
575
+ }
576
+ }
577
+ if (done) break;
578
+ }
579
+ } finally {
580
+ reader.close();
581
+ }
582
+
583
+ if (!chosen || chosen.id === "back") return "back";
584
+ if (deps.dispatch) {
585
+ drawn = 0;
586
+ if (repaint) io.write(`${ESC}[?25h`);
587
+ let code = 0;
588
+ try {
589
+ code = await deps.dispatch(chosen.id);
590
+ } finally {
591
+ drawn = 0;
592
+ if (repaint) io.write(`${ESC}[?25l`);
593
+ }
594
+ if (chosen.isTerminal) return code;
595
+
596
+ io.line();
597
+ io.line(dim("Press any key to return to menu...", styles));
598
+ const pauseReader = createReader();
599
+ try {
600
+ await pauseReader.read();
601
+ } finally {
602
+ pauseReader.close();
603
+ if (repaint) io.write(`${ESC}[?25l`);
604
+ }
605
+ needsClear = true;
606
+ }
607
+ }
608
+ } finally {
609
+ clearDrawnLines(io, drawn, repaint);
610
+ drawn = 0;
611
+ if (repaint) io.write(`${ESC}[?25h`);
612
+ }
613
+ }
614
+
615
+ export async function runWatcherSubmenu(deps: {
616
+ createReader?: () => KeyReader;
617
+ io?: MenuLoopIo;
618
+ styles?: boolean;
619
+ width?: number;
620
+ inRepo?: boolean;
621
+ home?: string;
622
+ dispatch?: (subcommand: string) => Promise<number>;
623
+ }): Promise<number | "back"> {
624
+ const io = deps.io ?? {
625
+ write: (t) => process.stderr.write(t),
626
+ line: (t = "") => process.stderr.write(`${t}\n`),
627
+ };
628
+ const styles = deps.styles ?? false;
629
+ const width = deps.width ?? 80;
630
+ const inRepo = deps.inRepo ?? true;
631
+ const home = deps.home ?? os.homedir();
632
+ const createReader = deps.createReader ?? createDefaultStdinReader;
633
+
634
+ const items = [
635
+ {
636
+ id: "status",
637
+ label: "Watcher status",
638
+ desc: "View watcher daemon status and enrolled repos",
639
+ },
640
+ {
641
+ id: "config",
642
+ label: "Configure limits & window",
643
+ desc: "Edit daily review cap and active time window (~/.crysk/watch.json)",
644
+ },
645
+ {
646
+ id: "install",
647
+ label: "Install launchd daemon",
648
+ desc: "Enable background background daemon",
649
+ },
650
+ {
651
+ id: "uninstall",
652
+ label: "Uninstall launchd daemon",
653
+ desc: "Disable background daemon",
654
+ },
655
+ ...(inRepo
656
+ ? [
657
+ {
658
+ id: "add",
659
+ label: "Add current repo to watcher",
660
+ desc: "Enroll this repository in background watcher",
661
+ },
662
+ {
663
+ id: "add-on-push",
664
+ label: "Add repo with on-push re-reviews",
665
+ desc: "Enroll repository and trigger review on each push",
666
+ },
667
+ {
668
+ id: "remove",
669
+ label: "Remove repo from watcher",
670
+ desc: "Unenroll a repository",
671
+ },
672
+ ]
673
+ : []),
674
+ { id: "back", label: "Back", desc: "Return to main menu" },
675
+ ];
676
+
677
+ let cursor = 0;
678
+ const ESC = "\x1b";
679
+ const repaint = styles;
680
+ let drawn = 0;
681
+
682
+ const render = (clearScreen = false) => {
683
+ const cardLines = items.map((item, idx) => {
684
+ const prefix = idx === cursor ? "▸ " : " ";
685
+ return `${prefix}${idx + 1}. ${item.label} - ${item.desc}`;
686
+ });
687
+ const lines: string[] = [
688
+ "",
689
+ ...box("Watcher Daemon Submenu", cardLines, {
690
+ width,
691
+ styles,
692
+ borderStyle: "double",
693
+ }),
694
+ dim("j/k: move • enter: select • q/esc: back", styles),
695
+ ];
696
+
697
+ let buf = "";
698
+ if (repaint && clearScreen) {
699
+ buf += `${ESC}[2J${ESC}[H`;
700
+ drawn = 0;
701
+ } else if (repaint && drawn > 0) {
702
+ buf += `${ESC}[${drawn}A`;
703
+ }
704
+ for (const l of lines) {
705
+ if (repaint && drawn > 0) buf += `${ESC}[2K`;
706
+ buf += `${l}\n`;
707
+ }
708
+ io.write(buf);
709
+ drawn = lines.length;
710
+ };
711
+
712
+ try {
713
+ if (repaint) io.write(`${ESC}[?25l`);
714
+ let needsClear = true;
715
+ for (;;) {
716
+ if (repaint) io.write(`${ESC}[?25l`);
717
+ render(needsClear);
718
+ needsClear = false;
719
+ const reader = createReader();
720
+ let chosen: (typeof items)[0] | undefined;
721
+ try {
722
+ for (;;) {
723
+ const chunk = await reader.read();
724
+ if (chunk === undefined) return "back";
725
+ let done = false;
726
+ for (const raw of splitKeys(chunk)) {
727
+ const key = parseKey(raw);
728
+ if (
729
+ key.type === "escape" ||
730
+ key.type === "ctrl-c" ||
731
+ (key.type === "char" && key.char === "q")
732
+ ) {
733
+ return "back";
734
+ }
735
+ if (
736
+ key.type === "up" ||
737
+ (key.type === "char" && key.char === "k")
738
+ ) {
739
+ cursor = (cursor - 1 + items.length) % items.length;
740
+ render(false);
741
+ continue;
742
+ }
743
+ if (
744
+ key.type === "down" ||
745
+ (key.type === "char" && key.char === "j")
746
+ ) {
747
+ cursor = (cursor + 1) % items.length;
748
+ render(false);
749
+ continue;
750
+ }
751
+ if (key.type === "char" && /^[1-9]$/.test(key.char)) {
752
+ const idx = Number(key.char) - 1;
753
+ if (idx >= 0 && idx < items.length) {
754
+ cursor = idx;
755
+ render(false);
756
+ }
757
+ continue;
758
+ }
759
+ if (key.type === "enter") {
760
+ chosen = items[cursor];
761
+ done = true;
762
+ break;
763
+ }
764
+ }
765
+ if (done) break;
766
+ }
767
+ } finally {
768
+ reader.close();
769
+ }
770
+
771
+ if (!chosen || chosen.id === "back") return "back";
772
+
773
+ if (chosen.id === "config") {
774
+ drawn = 0;
775
+ await runLayerConfigCardEditor({
776
+ layer: "watch",
777
+ title: `Watcher Daemon Configuration (${path.join(resolveHomeDir(home), "watch.json")})`,
778
+ createReader,
779
+ io,
780
+ styles,
781
+ width,
782
+ home,
783
+ });
784
+ drawn = 0;
785
+ needsClear = true;
786
+ continue;
787
+ }
788
+
789
+ if (deps.dispatch) {
790
+ drawn = 0;
791
+ if (repaint) io.write(`${ESC}[?25h`);
792
+ try {
793
+ await deps.dispatch(chosen.id);
794
+ } finally {
795
+ drawn = 0;
796
+ if (repaint) io.write(`${ESC}[?25l`);
797
+ }
798
+ io.line();
799
+ io.line(dim("Press any key to return to menu...", styles));
800
+ const pauseReader = createReader();
801
+ try {
802
+ await pauseReader.read();
803
+ } finally {
804
+ pauseReader.close();
805
+ if (repaint) io.write(`${ESC}[?25l`);
806
+ }
807
+ needsClear = true;
808
+ }
809
+ }
810
+ } finally {
811
+ clearDrawnLines(io, drawn, repaint);
812
+ drawn = 0;
813
+ if (repaint) io.write(`${ESC}[?25h`);
814
+ }
815
+ }
816
+
817
+ export async function runLayerConfigCardEditor(deps: {
818
+ layer: "team" | "person" | "watch";
819
+ title: string;
820
+ createReader: () => KeyReader;
821
+ io: MenuLoopIo;
822
+ styles: boolean;
823
+ width: number;
824
+ repoRoot?: string;
825
+ home?: string;
826
+ }): Promise<void> {
827
+ const home = deps.home ?? os.homedir();
828
+ const repoRoot = deps.repoRoot;
829
+ const ESC = "\x1b";
830
+ const repaint = deps.styles;
831
+ let drawn = 0;
832
+ let editCursor = 0;
833
+ let annotation: string | undefined;
834
+
835
+ const readLayerData = (): Record<string, unknown> => {
836
+ let filePath: string | undefined;
837
+ if (deps.layer === "team") {
838
+ if (!repoRoot) return {};
839
+ filePath = path.join(resolveRepoDir(repoRoot), "config.json");
840
+ } else if (deps.layer === "person") {
841
+ filePath = path.join(resolveHomeDir(home), "config.json");
842
+ } else if (deps.layer === "watch") {
843
+ filePath = path.join(resolveHomeDir(home), "watch.json");
844
+ }
845
+ if (filePath && existsSync(filePath)) {
846
+ try {
847
+ return JSON.parse(readFileSync(filePath, "utf-8"));
848
+ } catch {
849
+ return {};
850
+ }
851
+ }
852
+ return {};
853
+ };
854
+
855
+ const draft: Record<string, unknown> = readLayerData();
856
+ const actions = DEFAULT_CARD_ACTIONS;
857
+
858
+ const render = (clearScreen = false) => {
859
+ const entries = getEditableLayerEntries(deps.layer, draft);
860
+ const lines: string[] = [
861
+ "",
862
+ ...renderConfigEditCard(
863
+ deps.title,
864
+ entries,
865
+ editCursor,
866
+ deps.width,
867
+ deps.styles,
868
+ annotation,
869
+ actions,
870
+ ),
871
+ dim(
872
+ "j/k: move • space: toggle • ←/→: adjust • enter: select/save • u: reset • q/esc: discard",
873
+ deps.styles,
874
+ ),
875
+ ];
876
+
877
+ let buf = "";
878
+ if (repaint && clearScreen) {
879
+ buf += `${ESC}[2J${ESC}[H`;
880
+ drawn = 0;
881
+ } else if (repaint && drawn > 0) {
882
+ buf += `${ESC}[${drawn}A`;
883
+ }
884
+ for (const l of lines) {
885
+ if (repaint && drawn > 0) buf += `${ESC}[2K`;
886
+ buf += `${l}\n`;
887
+ }
888
+ deps.io.write(buf);
889
+ drawn = lines.length;
890
+ };
891
+
892
+ try {
893
+ if (repaint) deps.io.write(`${ESC}[?25l`);
894
+ let needsClear = true;
895
+ for (;;) {
896
+ render(needsClear);
897
+ needsClear = false;
898
+
899
+ const entries = getEditableLayerEntries(deps.layer, draft);
900
+ const totalItems = entries.length + actions.length;
901
+ if (entries.length === 0) return;
902
+
903
+ const reader = deps.createReader();
904
+ let shouldExit = false;
905
+
906
+ try {
907
+ for (;;) {
908
+ const chunk = await reader.read();
909
+ if (chunk === undefined) {
910
+ shouldExit = true;
911
+ break;
912
+ }
913
+ let actionTaken = false;
914
+ for (const raw of splitKeys(chunk)) {
915
+ const key = parseKey(raw);
916
+ if (
917
+ key.type === "escape" ||
918
+ key.type === "ctrl-c" ||
919
+ (key.type === "char" && key.char === "q")
920
+ ) {
921
+ shouldExit = true;
922
+ break;
923
+ }
924
+ if (
925
+ key.type === "up" ||
926
+ (key.type === "char" && key.char === "k")
927
+ ) {
928
+ editCursor = (editCursor - 1 + totalItems) % totalItems;
929
+ annotation = undefined;
930
+ render(false);
931
+ continue;
932
+ }
933
+ if (
934
+ key.type === "down" ||
935
+ (key.type === "char" && key.char === "j")
936
+ ) {
937
+ editCursor = (editCursor + 1) % totalItems;
938
+ annotation = undefined;
939
+ render(false);
940
+ continue;
941
+ }
942
+ if (key.type === "char" && /^[1-9]$/.test(key.char)) {
943
+ const idx = Number(key.char) - 1;
944
+ if (idx < totalItems) {
945
+ editCursor = idx;
946
+ annotation = undefined;
947
+ render(false);
948
+ }
949
+ continue;
950
+ }
951
+
952
+ // If cursor is on Action buttons:
953
+ if (editCursor >= entries.length) {
954
+ const actionIdx = editCursor - entries.length;
955
+ if (key.type === "enter") {
956
+ if (actionIdx === 0) {
957
+ // Save changes
958
+ const res = await saveLayerConfig({
959
+ layer: deps.layer,
960
+ draft,
961
+ home,
962
+ repoRoot,
963
+ });
964
+ annotation = res.annotation;
965
+ actionTaken = true;
966
+ break;
967
+ }
968
+ if (actionIdx === 1) {
969
+ // Discard & back
970
+ shouldExit = true;
971
+ break;
972
+ }
973
+ if (actionIdx === 2) {
974
+ // Clear all (unset)
975
+ for (const k of Object.keys(draft)) delete draft[k];
976
+ annotation =
977
+ "✓ Cleared draft overrides to (not set) (hit Save changes to apply)";
978
+ actionTaken = true;
979
+ break;
980
+ }
981
+ }
982
+ continue;
983
+ }
984
+
985
+ // Cursor is on a field:
986
+ const currentEntry = entries[editCursor];
987
+ if (!currentEntry) continue;
988
+
989
+ // Space: Boolean toggle in draft
990
+ if (key.type === "char" && key.char === " ") {
991
+ if (
992
+ currentEntry.type === "boolean" ||
993
+ currentEntry.key === "summary.enabled"
994
+ ) {
995
+ const currentBool = currentEntry.currentRaw === true;
996
+ const nextBool = !currentBool;
997
+ if (currentEntry.key === "summary.enabled") {
998
+ draft.summary = {
999
+ ...(typeof draft.summary === "object" &&
1000
+ draft.summary !== null
1001
+ ? (draft.summary as Record<string, unknown>)
1002
+ : {}),
1003
+ enabled: nextBool,
1004
+ };
1005
+ } else {
1006
+ draft[currentEntry.key] = nextBool;
1007
+ }
1008
+ actionTaken = true;
1009
+ break;
1010
+ }
1011
+ }
1012
+
1013
+ // Left: Decrement numeric in draft
1014
+ if (
1015
+ key.type === "left" ||
1016
+ (key.type === "char" && key.char === "h")
1017
+ ) {
1018
+ if (currentEntry.type === "number") {
1019
+ let delta = -1;
1020
+ let min = 0;
1021
+ if (currentEntry.key === "max_changed_lines") delta = -250;
1022
+ else if (currentEntry.key === "max_changed_files") delta = -25;
1023
+ else if (currentEntry.key === "daily_cap") {
1024
+ delta = -1;
1025
+ min = 1;
1026
+ }
1027
+
1028
+ const currentNum =
1029
+ typeof currentEntry.currentRaw === "number"
1030
+ ? currentEntry.currentRaw
1031
+ : currentEntry.key === "max_changed_lines"
1032
+ ? DEFAULT_SIZE_GATE.maxChangedLines
1033
+ : currentEntry.key === "max_changed_files"
1034
+ ? DEFAULT_SIZE_GATE.maxChangedFiles
1035
+ : currentEntry.key === "max_verification_steps"
1036
+ ? DEFAULT_MAX_VERIFICATION_STEPS
1037
+ : currentEntry.key === "daily_cap"
1038
+ ? DEFAULT_DAILY_CAP
1039
+ : 1;
1040
+
1041
+ const nextNum = stepNumericValue(currentNum, delta, min);
1042
+ draft[currentEntry.key] = nextNum;
1043
+ actionTaken = true;
1044
+ break;
1045
+ }
1046
+ }
1047
+
1048
+ // Right: Increment numeric in draft
1049
+ if (
1050
+ key.type === "right" ||
1051
+ (key.type === "char" && key.char === "l")
1052
+ ) {
1053
+ if (currentEntry.type === "number") {
1054
+ let delta = 1;
1055
+ let min = 0;
1056
+ if (currentEntry.key === "max_changed_lines") delta = 250;
1057
+ else if (currentEntry.key === "max_changed_files") delta = 25;
1058
+ else if (currentEntry.key === "daily_cap") {
1059
+ delta = 1;
1060
+ min = 1;
1061
+ }
1062
+
1063
+ const currentNum =
1064
+ typeof currentEntry.currentRaw === "number"
1065
+ ? currentEntry.currentRaw
1066
+ : currentEntry.key === "max_changed_lines"
1067
+ ? DEFAULT_SIZE_GATE.maxChangedLines
1068
+ : currentEntry.key === "max_changed_files"
1069
+ ? DEFAULT_SIZE_GATE.maxChangedFiles
1070
+ : currentEntry.key === "max_verification_steps"
1071
+ ? DEFAULT_MAX_VERIFICATION_STEPS
1072
+ : currentEntry.key === "daily_cap"
1073
+ ? DEFAULT_DAILY_CAP
1074
+ : 1;
1075
+
1076
+ const nextNum = stepNumericValue(currentNum, delta, min);
1077
+ draft[currentEntry.key] = nextNum;
1078
+ actionTaken = true;
1079
+ break;
1080
+ }
1081
+ }
1082
+
1083
+ // Enter: Cycle presets or boolean toggle
1084
+ if (key.type === "enter") {
1085
+ if (
1086
+ currentEntry.type === "boolean" ||
1087
+ currentEntry.key === "summary.enabled"
1088
+ ) {
1089
+ const currentBool = currentEntry.currentRaw === true;
1090
+ const nextBool = !currentBool;
1091
+ if (currentEntry.key === "summary.enabled") {
1092
+ draft.summary = {
1093
+ ...(typeof draft.summary === "object" &&
1094
+ draft.summary !== null
1095
+ ? (draft.summary as Record<string, unknown>)
1096
+ : {}),
1097
+ enabled: nextBool,
1098
+ };
1099
+ } else {
1100
+ draft[currentEntry.key] = nextBool;
1101
+ }
1102
+ actionTaken = true;
1103
+ break;
1104
+ }
1105
+ if (currentEntry.key === "default_base") {
1106
+ const currentStr =
1107
+ typeof currentEntry.currentRaw === "string"
1108
+ ? currentEntry.currentRaw
1109
+ : "main";
1110
+ const nextStr = cycleStringPreset(currentStr, [
1111
+ "main",
1112
+ "master",
1113
+ "develop",
1114
+ ]);
1115
+ draft.default_base = nextStr;
1116
+ actionTaken = true;
1117
+ break;
1118
+ }
1119
+ }
1120
+
1121
+ // u: Reset key in draft
1122
+ if (key.type === "char" && key.char === "u") {
1123
+ if (currentEntry.key.startsWith("summary.")) {
1124
+ if (
1125
+ typeof draft.summary === "object" &&
1126
+ draft.summary !== null
1127
+ ) {
1128
+ delete (draft.summary as Record<string, unknown>).enabled;
1129
+ }
1130
+ } else {
1131
+ delete draft[currentEntry.key];
1132
+ }
1133
+ annotation = `✓ Draft reset ${currentEntry.key} to default`;
1134
+ actionTaken = true;
1135
+ break;
1136
+ }
1137
+ }
1138
+ if (shouldExit || actionTaken) break;
1139
+ }
1140
+ } finally {
1141
+ reader.close();
1142
+ }
1143
+
1144
+ if (shouldExit) return;
1145
+ }
1146
+ } finally {
1147
+ clearDrawnLines(deps.io, drawn, repaint);
1148
+ drawn = 0;
1149
+ if (repaint) deps.io.write(`${ESC}[?25h`);
1150
+ }
1151
+ }
1152
+
1153
+ export async function runConfigSubmenu(deps: {
1154
+ createReader?: () => KeyReader;
1155
+ io?: MenuLoopIo;
1156
+ styles?: boolean;
1157
+ width?: number;
1158
+ repoRoot?: string;
1159
+ home?: string;
1160
+ }): Promise<number | "back"> {
1161
+ const io = deps.io ?? {
1162
+ write: (t) => process.stderr.write(t),
1163
+ line: (t = "") => process.stderr.write(`${t}\n`),
1164
+ };
1165
+ const styles = deps.styles ?? false;
1166
+ const width = deps.width ?? 80;
1167
+ const home = deps.home ?? os.homedir();
1168
+ const repoRoot = deps.repoRoot;
1169
+ const inRepo = Boolean(repoRoot);
1170
+ const createReader = deps.createReader ?? createDefaultStdinReader;
1171
+
1172
+ const ESC = "\x1b";
1173
+ const repaint = styles;
1174
+ let drawn = 0;
1175
+ let layerCursor = 0;
1176
+
1177
+ const layerItems = [
1178
+ {
1179
+ id: "team" as const,
1180
+ label: "Repository configuration",
1181
+ file: repoRoot
1182
+ ? path.join(resolveRepoDir(repoRoot), "config.json")
1183
+ : ".crysk/config.json",
1184
+ disabled: !inRepo,
1185
+ },
1186
+ {
1187
+ id: "person" as const,
1188
+ label: "Global configuration",
1189
+ file: path.join(resolveHomeDir(home), "config.json"),
1190
+ disabled: false,
1191
+ },
1192
+ {
1193
+ id: "back" as const,
1194
+ label: "Back",
1195
+ file: "Return to main menu",
1196
+ disabled: false,
1197
+ },
1198
+ ];
1199
+
1200
+ const render = (clearScreen = false) => {
1201
+ const cardLines = layerItems.map((item, idx) => {
1202
+ const isSelected = idx === layerCursor;
1203
+ const prefix = isSelected ? "▸ " : " ";
1204
+ const suffix = item.disabled
1205
+ ? " (disabled outside git repository)"
1206
+ : ` (${item.file})`;
1207
+ const line = sanitizeText(`${prefix}${idx + 1}. ${item.label}${suffix}`);
1208
+ return isSelected
1209
+ ? bold(cyan(line, styles), styles)
1210
+ : item.disabled
1211
+ ? dim(line, styles)
1212
+ : line;
1213
+ });
1214
+ const lines = [
1215
+ "",
1216
+ ...box("Select Configuration Layer", cardLines, {
1217
+ width,
1218
+ styles,
1219
+ borderStyle: "double",
1220
+ }),
1221
+ dim("j/k: move • enter: select • q/esc: back", styles),
1222
+ ];
1223
+
1224
+ let buf = "";
1225
+ if (repaint && clearScreen) {
1226
+ buf += `${ESC}[2J${ESC}[H`;
1227
+ drawn = 0;
1228
+ } else if (repaint && drawn > 0) {
1229
+ buf += `${ESC}[${drawn}A`;
1230
+ }
1231
+ for (const l of lines) {
1232
+ if (repaint && drawn > 0) buf += `${ESC}[2K`;
1233
+ buf += `${l}\n`;
1234
+ }
1235
+ io.write(buf);
1236
+ drawn = lines.length;
1237
+ };
1238
+
1239
+ try {
1240
+ if (repaint) io.write(`${ESC}[?25l`);
1241
+ let needsClear = true;
1242
+ for (;;) {
1243
+ if (repaint) io.write(`${ESC}[?25l`);
1244
+ render(needsClear);
1245
+ needsClear = false;
1246
+
1247
+ const reader = createReader();
1248
+ let selectedNext: "team" | "person" | "back" | undefined;
1249
+ try {
1250
+ for (;;) {
1251
+ const chunk = await reader.read();
1252
+ if (chunk === undefined) return "back";
1253
+ let shouldBreak = false;
1254
+ for (const raw of splitKeys(chunk)) {
1255
+ const key = parseKey(raw);
1256
+ if (
1257
+ key.type === "escape" ||
1258
+ key.type === "ctrl-c" ||
1259
+ (key.type === "char" && key.char === "q")
1260
+ ) {
1261
+ return "back";
1262
+ }
1263
+ if (
1264
+ key.type === "up" ||
1265
+ (key.type === "char" && key.char === "k")
1266
+ ) {
1267
+ layerCursor =
1268
+ (layerCursor - 1 + layerItems.length) % layerItems.length;
1269
+ render(false);
1270
+ continue;
1271
+ }
1272
+ if (
1273
+ key.type === "down" ||
1274
+ (key.type === "char" && key.char === "j")
1275
+ ) {
1276
+ layerCursor = (layerCursor + 1) % layerItems.length;
1277
+ render(false);
1278
+ continue;
1279
+ }
1280
+ if (key.type === "char" && /^[1-3]$/.test(key.char)) {
1281
+ layerCursor = Number(key.char) - 1;
1282
+ render(false);
1283
+ continue;
1284
+ }
1285
+ if (key.type === "enter") {
1286
+ const item = layerItems[layerCursor];
1287
+ if (item.disabled) continue;
1288
+ selectedNext = item.id;
1289
+ shouldBreak = true;
1290
+ break;
1291
+ }
1292
+ }
1293
+ if (shouldBreak) break;
1294
+ }
1295
+ } finally {
1296
+ reader.close();
1297
+ }
1298
+
1299
+ if (selectedNext === "back" || !selectedNext) return "back";
1300
+
1301
+ const title =
1302
+ selectedNext === "team"
1303
+ ? `Repository Configuration (${path.join(resolveRepoDir(repoRoot ?? "."), "config.json")})`
1304
+ : `Global Configuration (${path.join(resolveHomeDir(home), "config.json")})`;
1305
+
1306
+ drawn = 0;
1307
+ await runLayerConfigCardEditor({
1308
+ layer: selectedNext,
1309
+ title,
1310
+ createReader,
1311
+ io,
1312
+ styles,
1313
+ width,
1314
+ repoRoot,
1315
+ home,
1316
+ });
1317
+ drawn = 0;
1318
+ needsClear = true;
1319
+ }
1320
+ } finally {
1321
+ clearDrawnLines(io, drawn, repaint);
1322
+ drawn = 0;
1323
+ if (repaint) io.write(`${ESC}[?25h`);
1324
+ }
1325
+ }