clud-bug 0.7.0-rc.2 → 0.7.0-rc.21

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 (147) hide show
  1. package/README.md +20 -0
  2. package/data/canonical-v1.json +37 -0
  3. package/dist/cli/configure-github.d.ts +58 -0
  4. package/dist/cli/configure-github.d.ts.map +1 -0
  5. package/dist/cli/configure-github.js +242 -0
  6. package/dist/cli/configure-github.js.map +1 -0
  7. package/dist/cli/hooks.d.ts +51 -0
  8. package/dist/cli/hooks.d.ts.map +1 -0
  9. package/dist/cli/hooks.js +138 -0
  10. package/dist/cli/hooks.js.map +1 -0
  11. package/dist/cli/index.d.ts +1 -0
  12. package/dist/cli/index.d.ts.map +1 -1
  13. package/dist/cli/index.js +1 -0
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cli/main.d.ts.map +1 -1
  16. package/dist/cli/main.js +949 -35
  17. package/dist/cli/main.js.map +1 -1
  18. package/dist/cli/post-check-run.d.ts +16 -0
  19. package/dist/cli/post-check-run.d.ts.map +1 -0
  20. package/dist/cli/post-check-run.js +93 -0
  21. package/dist/cli/post-check-run.js.map +1 -0
  22. package/dist/cli/review-prompt.d.ts +43 -0
  23. package/dist/cli/review-prompt.d.ts.map +1 -0
  24. package/dist/cli/review-prompt.js +287 -0
  25. package/dist/cli/review-prompt.js.map +1 -0
  26. package/dist/cli/skills.d.ts +7 -0
  27. package/dist/cli/skills.d.ts.map +1 -1
  28. package/dist/cli/skills.js +42 -2
  29. package/dist/cli/skills.js.map +1 -1
  30. package/dist/cli/update-notifier.d.ts +17 -0
  31. package/dist/cli/update-notifier.d.ts.map +1 -0
  32. package/dist/cli/update-notifier.js +88 -0
  33. package/dist/cli/update-notifier.js.map +1 -0
  34. package/dist/cli/update.d.ts.map +1 -1
  35. package/dist/cli/update.js +60 -11
  36. package/dist/cli/update.js.map +1 -1
  37. package/dist/core/auto-resolve.d.ts +235 -0
  38. package/dist/core/auto-resolve.d.ts.map +1 -0
  39. package/dist/core/auto-resolve.js +293 -0
  40. package/dist/core/auto-resolve.js.map +1 -0
  41. package/dist/core/budget-plan.d.ts +125 -0
  42. package/dist/core/budget-plan.d.ts.map +1 -0
  43. package/dist/core/budget-plan.js +211 -0
  44. package/dist/core/budget-plan.js.map +1 -0
  45. package/dist/core/check-verdict.d.ts +31 -0
  46. package/dist/core/check-verdict.d.ts.map +1 -0
  47. package/dist/core/check-verdict.js +66 -0
  48. package/dist/core/check-verdict.js.map +1 -0
  49. package/dist/core/configure-github.d.ts +179 -0
  50. package/dist/core/configure-github.d.ts.map +1 -0
  51. package/dist/core/configure-github.js +289 -0
  52. package/dist/core/configure-github.js.map +1 -0
  53. package/dist/core/design.d.ts +37 -0
  54. package/dist/core/design.d.ts.map +1 -0
  55. package/dist/core/design.js +47 -0
  56. package/dist/core/design.js.map +1 -0
  57. package/dist/core/diff-findings.d.ts +96 -0
  58. package/dist/core/diff-findings.d.ts.map +1 -0
  59. package/dist/core/diff-findings.js +261 -0
  60. package/dist/core/diff-findings.js.map +1 -0
  61. package/dist/core/formal-review.d.ts +79 -0
  62. package/dist/core/formal-review.d.ts.map +1 -0
  63. package/dist/core/formal-review.js +71 -0
  64. package/dist/core/formal-review.js.map +1 -0
  65. package/dist/core/index.d.ts +15 -2
  66. package/dist/core/index.d.ts.map +1 -1
  67. package/dist/core/index.js +53 -1
  68. package/dist/core/index.js.map +1 -1
  69. package/dist/core/inline-threads.d.ts +160 -0
  70. package/dist/core/inline-threads.d.ts.map +1 -0
  71. package/dist/core/inline-threads.js +369 -0
  72. package/dist/core/inline-threads.js.map +1 -0
  73. package/dist/core/multi-pass-aggregate.d.ts +161 -0
  74. package/dist/core/multi-pass-aggregate.d.ts.map +1 -0
  75. package/dist/core/multi-pass-aggregate.js +457 -0
  76. package/dist/core/multi-pass-aggregate.js.map +1 -0
  77. package/dist/core/plan-review.d.ts +57 -0
  78. package/dist/core/plan-review.d.ts.map +1 -0
  79. package/dist/core/plan-review.js +77 -0
  80. package/dist/core/plan-review.js.map +1 -0
  81. package/dist/core/prompt-builder.d.ts +18 -0
  82. package/dist/core/prompt-builder.d.ts.map +1 -1
  83. package/dist/core/prompt-builder.js +24 -2
  84. package/dist/core/prompt-builder.js.map +1 -1
  85. package/dist/core/render.d.ts.map +1 -1
  86. package/dist/core/render.js +1 -19
  87. package/dist/core/render.js.map +1 -1
  88. package/dist/core/resolve-verifier.d.ts +53 -0
  89. package/dist/core/resolve-verifier.d.ts.map +1 -0
  90. package/dist/core/resolve-verifier.js +204 -0
  91. package/dist/core/resolve-verifier.js.map +1 -0
  92. package/dist/core/review-context.d.ts +39 -0
  93. package/dist/core/review-context.d.ts.map +1 -0
  94. package/dist/core/review-context.js +99 -0
  95. package/dist/core/review-context.js.map +1 -0
  96. package/dist/core/review-plan.d.ts +219 -0
  97. package/dist/core/review-plan.d.ts.map +1 -0
  98. package/dist/core/review-plan.js +274 -0
  99. package/dist/core/review-plan.js.map +1 -0
  100. package/dist/core/review-writeback.d.ts +74 -0
  101. package/dist/core/review-writeback.d.ts.map +1 -1
  102. package/dist/core/review-writeback.js +71 -4
  103. package/dist/core/review-writeback.js.map +1 -1
  104. package/dist/core/skills.d.ts +25 -0
  105. package/dist/core/skills.d.ts.map +1 -1
  106. package/dist/core/skills.js +100 -4
  107. package/dist/core/skills.js.map +1 -1
  108. package/dist/core/version.d.ts +2 -0
  109. package/dist/core/version.d.ts.map +1 -0
  110. package/dist/core/version.js +4 -0
  111. package/dist/core/version.js.map +1 -0
  112. package/package.json +11 -5
  113. package/src/cli/configure-github.ts +329 -0
  114. package/src/cli/hooks.ts +155 -0
  115. package/src/cli/index.ts +6 -0
  116. package/src/cli/main.ts +1031 -37
  117. package/src/cli/post-check-run.ts +115 -0
  118. package/src/cli/review-prompt.ts +355 -0
  119. package/src/cli/skills.ts +42 -2
  120. package/src/cli/update-notifier.ts +100 -0
  121. package/src/cli/update.ts +60 -11
  122. package/src/core/auto-resolve.ts +488 -0
  123. package/src/core/budget-plan.ts +324 -0
  124. package/src/core/check-verdict.ts +93 -0
  125. package/src/core/configure-github.ts +497 -0
  126. package/src/core/design.ts +73 -0
  127. package/src/core/diff-findings.ts +323 -0
  128. package/src/core/formal-review.ts +168 -0
  129. package/src/core/index.ts +188 -0
  130. package/src/core/inline-threads.ts +471 -0
  131. package/src/core/multi-pass-aggregate.ts +591 -0
  132. package/src/core/plan-review.ts +136 -0
  133. package/src/core/prompt-builder.ts +44 -2
  134. package/src/core/render.ts +10 -16
  135. package/src/core/resolve-verifier.ts +254 -0
  136. package/src/core/review-context.ts +106 -0
  137. package/src/core/review-plan.ts +485 -0
  138. package/src/core/review-writeback.ts +161 -4
  139. package/src/core/skills.ts +128 -5
  140. package/src/core/version.ts +3 -0
  141. package/templates/clud-bug-review.md.tmpl +115 -0
  142. package/templates/skills/design/design-system-consistency.md +41 -0
  143. package/templates/skills/design/frontend-a11y.md +41 -0
  144. package/templates/skills/design/visual-polish.md +41 -0
  145. package/templates/workflow-py.yml.tmpl +92 -2
  146. package/templates/workflow-ts.yml.tmpl +92 -2
  147. package/templates/workflow.yml.tmpl +173 -2
@@ -0,0 +1,329 @@
1
+ // `clud-bug configure-github` CLI command — applies the SPEC §7 canonical
2
+ // branch protection ruleset to a target repo.
3
+ //
4
+ // External users installing the App expect "best practice branch protection"
5
+ // applied automatically. This command lets them opt in offline + dry-run
6
+ // safely BEFORE the App's auto-setup runs server-side. Same core logic
7
+ // powers both paths (the App imports `applyCanonicalRuleset` from
8
+ // clud-bug/core; this CLI passes a `gh api`-wrapping adapter so users
9
+ // don't need `@octokit/rest` on their machine).
10
+ //
11
+ // Usage:
12
+ //
13
+ // clud-bug configure-github <owner>/<repo>
14
+ // clud-bug configure-github <owner>/<repo> --dry-run
15
+ // clud-bug configure-github <owner>/<repo> --branch develop
16
+ //
17
+ // Auth ladder:
18
+ //
19
+ // 1. `GITHUB_TOKEN` env var (CI-friendly, no `gh` install required)
20
+ // 2. `gh auth token` (developer workstation default)
21
+ //
22
+ // If neither produces a token, exits 1 with a recovery message.
23
+
24
+ import { spawn, spawnSync } from 'node:child_process';
25
+ import {
26
+ applyCanonicalRuleset,
27
+ loadCanonicalV1,
28
+ type OctokitLike,
29
+ type ApplyResult,
30
+ } from '../core/configure-github.js';
31
+
32
+ export interface RunConfigureGithubOptions {
33
+ /** "owner/repo" target — required. */
34
+ target?: string | null;
35
+ /** Target branch (default `main`). */
36
+ branch?: string;
37
+ /** Render diff only; skip PATCH calls. */
38
+ dryRun?: boolean;
39
+ /** Suppress progress chatter; emit only the final `ok` summary. */
40
+ quiet?: boolean;
41
+ /** Emit the SPEC §3.23.1 status payload as JSON instead of key-colon-value. */
42
+ json?: boolean;
43
+ /** Resolver for the GitHub token (tests pass a stub). */
44
+ resolveToken?: () => Promise<string | null>;
45
+ /** Octokit factory (tests inject a fake; defaults to the gh-adapter). */
46
+ octokitFactory?: (token: string) => OctokitLike;
47
+ /** Stdout writer (tests capture). */
48
+ stdout?: (msg: string) => void;
49
+ /** Stderr writer (tests capture). */
50
+ stderr?: (msg: string) => void;
51
+ }
52
+
53
+ const HELP = `clud-bug configure-github — apply SPEC §7 canonical branch protection.
54
+
55
+ Usage:
56
+ clud-bug configure-github <owner>/<repo> [options]
57
+
58
+ Options:
59
+ --dry-run Compute diff and print it, but do NOT call PATCH endpoints.
60
+ --branch <name> Target branch (default: main).
61
+ --quiet,-q Suppress progress chatter; emit only the final summary.
62
+ --json Emit the status payload as JSON (machine consumption).
63
+ --help,-h Show this help.
64
+
65
+ Auth (resolved in order):
66
+ 1. GITHUB_TOKEN env var (CI-friendly)
67
+ 2. \`gh auth token\` (developer workstation)
68
+
69
+ Exit codes:
70
+ 0 success or already-canonical
71
+ 1 auth missing, PATCH error, or unrecoverable transport failure
72
+ 2 CLI usage error (missing target, bad flag)
73
+ `;
74
+
75
+ /** Resolved outcome of a configure-github run, for the §3.23.1 status payload. */
76
+ export interface ConfigureSummary {
77
+ owner: string;
78
+ repo: string;
79
+ /** True when the repo already matches canonical-v1 (idempotent no-op). */
80
+ alreadyCanonical: boolean;
81
+ /** True when this was a --dry-run (no PATCH calls made). */
82
+ dryRun: boolean;
83
+ /** Number of changes (applied, or pending for dry-run; 0 for a no-op). */
84
+ changes: number;
85
+ }
86
+
87
+ /**
88
+ * SPEC §3.23.1 (NORMATIVE): emit a single-line status payload carrying
89
+ * `alreadyCanonical` + `rulesetVersion` as named fields — JSON for machine
90
+ * consumption, key-colon-value for humans.
91
+ */
92
+ export function formatConfigureSummary(summary: ConfigureSummary, json: boolean): string {
93
+ const { owner, repo, alreadyCanonical, dryRun, changes } = summary;
94
+ if (json) {
95
+ return (
96
+ JSON.stringify({ owner, repo, alreadyCanonical, rulesetVersion: 'v1', dryRun, changes }) + '\n'
97
+ );
98
+ }
99
+ if (alreadyCanonical) {
100
+ return `ok configure-github: owner: ${owner} repo: ${repo} alreadyCanonical: true rulesetVersion: v1\n`;
101
+ }
102
+ const plural = changes === 1 ? '' : 's';
103
+ if (dryRun) {
104
+ return `ok configure-github: dry-run on ${owner}/${repo} — ${changes} change${plural} pending\n`;
105
+ }
106
+ return `ok configure-github: ${owner}/${repo} converged to canonical-v1 (${changes} change${plural})\n`;
107
+ }
108
+
109
+ /**
110
+ * Entry point — wired into `clud-bug.js` dispatch. Returns a Node-style
111
+ * exit code so the dispatcher can `process.exit()` deterministically. We
112
+ * don't call `process.exit` ourselves so tests can drive the function
113
+ * without taking down the harness.
114
+ */
115
+ export async function runConfigureGithub(
116
+ options: RunConfigureGithubOptions,
117
+ ): Promise<number> {
118
+ const {
119
+ target,
120
+ branch = 'main',
121
+ dryRun = false,
122
+ quiet = false,
123
+ json = false,
124
+ resolveToken = defaultResolveToken,
125
+ octokitFactory = ghCliOctokit,
126
+ stdout = (msg) => process.stdout.write(msg),
127
+ stderr = (msg) => process.stderr.write(msg),
128
+ } = options;
129
+
130
+ if (!target) {
131
+ stderr(HELP);
132
+ return 2;
133
+ }
134
+ const match = /^([^/]+)\/([^/]+)$/.exec(target);
135
+ if (!match) {
136
+ stderr(
137
+ `clud-bug configure-github: target must be in owner/repo form, got "${target}".\n`,
138
+ );
139
+ return 2;
140
+ }
141
+ const [, owner, repo] = match as unknown as [unknown, string, string];
142
+
143
+ const token = await resolveToken();
144
+ if (!token) {
145
+ stderr(
146
+ 'clud-bug configure-github: no GitHub token found.\n' +
147
+ ' Set GITHUB_TOKEN, or install + auth gh: brew install gh && gh auth login\n',
148
+ );
149
+ return 1;
150
+ }
151
+
152
+ if (!quiet) {
153
+ stdout(
154
+ `\u{1F41B} configure-github: applying canonical-v1 ruleset to ${owner}/${repo} (branch=${branch})\n`,
155
+ );
156
+ }
157
+
158
+ // Single-call orchestration: the CLI previously called
159
+ // applyCanonicalRuleset twice in apply mode (dry-run first to display the
160
+ // planned changes, then a real call to apply). That two-read pattern
161
+ // opened a TOCTOU window — concurrent changes between the two reads
162
+ // could make the displayed list diverge from the actually-applied list,
163
+ // and the dry-run cost a redundant API round-trip every time. Drop the
164
+ // preview-first read: pass `dryRun` straight through. The function's
165
+ // idempotency contract (returns `alreadyCanonical: true` + empty changes
166
+ // on a no-op) means we don't need a separate "look before you leap"
167
+ // call. Users who want preview semantics run `--dry-run` first as a
168
+ // distinct invocation — idiomatic CLI behavior. Surfaced by PR #166
169
+ // reviewer (CTO follow-up 2026-06-17).
170
+ const octokit = octokitFactory(token);
171
+ let result: ApplyResult;
172
+ try {
173
+ result = await applyCanonicalRuleset(octokit, {
174
+ owner,
175
+ repo,
176
+ branch,
177
+ dryRun,
178
+ });
179
+ } catch (err) {
180
+ stderr(
181
+ `clud-bug configure-github: ${dryRun ? 'failed to read current state' : 'PATCH failed'}: ${stringifyError(err)}\n`,
182
+ );
183
+ return 1;
184
+ }
185
+
186
+ if (result.alreadyCanonical) {
187
+ if (!quiet) stdout(' No changes — repo already matches canonical-v1.\n');
188
+ stdout(formatConfigureSummary({ owner, repo, alreadyCanonical: true, dryRun, changes: 0 }, json));
189
+ return 0;
190
+ }
191
+
192
+ if (!quiet) {
193
+ const verb = dryRun ? 'Planned' : 'Applied';
194
+ stdout(` ${verb} changes (${result.changes.length}):\n`);
195
+ for (const c of result.changes) stdout(` - ${c}\n`);
196
+ }
197
+
198
+ if (dryRun) {
199
+ stdout(formatConfigureSummary({ owner, repo, alreadyCanonical: false, dryRun: true, changes: result.changes.length }, json));
200
+ return 0;
201
+ }
202
+
203
+ stdout(formatConfigureSummary({ owner, repo, alreadyCanonical: false, dryRun: false, changes: result.changes.length }, json));
204
+ return 0;
205
+ }
206
+
207
+ /**
208
+ * Auth ladder: env var first, then `gh auth token`. Surfaces a token
209
+ * string on success or `null` if neither source has one (caller prints
210
+ * the recovery hint).
211
+ */
212
+ async function defaultResolveToken(): Promise<string | null> {
213
+ const fromEnv = process.env.GITHUB_TOKEN?.trim();
214
+ if (fromEnv) return fromEnv;
215
+ const result = spawnSync('gh', ['auth', 'token'], { encoding: 'utf8' });
216
+ if (result.status === 0) {
217
+ const tok = result.stdout.trim();
218
+ if (tok) return tok;
219
+ }
220
+ return null;
221
+ }
222
+
223
+ /**
224
+ * Builds an `OctokitLike` instance backed by `gh api` shell-outs. This
225
+ * lets us satisfy the structural interface without pulling in
226
+ * `@octokit/rest` as a runtime dep (~200KB). The App passes its real
227
+ * Octokit instance instead.
228
+ */
229
+ export function ghCliOctokit(token: string): OctokitLike {
230
+ // We pass GITHUB_TOKEN through the spawn env so gh's API surface picks
231
+ // it up consistently whether the user supplied env or gh auth.
232
+ const env = { ...process.env, GITHUB_TOKEN: token };
233
+
234
+ function ghApi<T>(
235
+ method: 'GET' | 'PUT' | 'PATCH' | 'POST',
236
+ path: string,
237
+ body?: unknown,
238
+ ): Promise<T> {
239
+ return new Promise<T>((resolve, reject) => {
240
+ const args: string[] = ['api', '-X', method];
241
+ if (body !== undefined) {
242
+ args.push('--input', '-');
243
+ }
244
+ args.push(path);
245
+ // Add an Accept header so 404s return the structured error, not a
246
+ // friendlier shell hint. The wrapping err.message detection in
247
+ // `isBranchNotProtected` keys on the structured form.
248
+ args.push('-H', 'Accept: application/vnd.github+json');
249
+ const child = spawn('gh', args, {
250
+ env,
251
+ stdio: ['pipe', 'pipe', 'pipe'],
252
+ });
253
+ let stdout = '';
254
+ let stderr = '';
255
+ child.stdout!.on('data', (d: Buffer) => {
256
+ stdout += d.toString();
257
+ });
258
+ child.stderr!.on('data', (d: Buffer) => {
259
+ stderr += d.toString();
260
+ });
261
+ child.on('error', reject);
262
+ child.on('close', (code) => {
263
+ if (code !== 0) {
264
+ const httpMatch = /HTTP (\d{3})/.exec(stderr);
265
+ const status = httpMatch ? Number(httpMatch[1]) : undefined;
266
+ const err = new Error(
267
+ (stderr.trim() || stdout.trim() || `gh api exited ${code}`).slice(
268
+ 0,
269
+ 500,
270
+ ),
271
+ ) as Error & { status?: number };
272
+ if (status !== undefined) err.status = status;
273
+ reject(err);
274
+ return;
275
+ }
276
+ try {
277
+ resolve(stdout ? (JSON.parse(stdout) as T) : ({} as T));
278
+ } catch (parseErr) {
279
+ reject(parseErr);
280
+ }
281
+ });
282
+ if (body !== undefined) {
283
+ child.stdin!.end(JSON.stringify(body));
284
+ } else {
285
+ child.stdin!.end();
286
+ }
287
+ });
288
+ }
289
+
290
+ return {
291
+ repos: {
292
+ async getBranchProtection({ owner, repo, branch }) {
293
+ const data = await ghApi<unknown>(
294
+ 'GET',
295
+ `/repos/${owner}/${repo}/branches/${branch}/protection`,
296
+ );
297
+ return { data: data as Awaited<ReturnType<OctokitLike['repos']['getBranchProtection']>>['data'] };
298
+ },
299
+ async updateBranchProtection({ owner, repo, branch, ...rest }) {
300
+ return ghApi(
301
+ 'PUT',
302
+ `/repos/${owner}/${repo}/branches/${branch}/protection`,
303
+ rest,
304
+ );
305
+ },
306
+ async get({ owner, repo }) {
307
+ const data = await ghApi<unknown>(
308
+ 'GET',
309
+ `/repos/${owner}/${repo}`,
310
+ );
311
+ return { data: data as Awaited<ReturnType<OctokitLike['repos']['get']>>['data'] };
312
+ },
313
+ async update({ owner, repo, ...rest }) {
314
+ return ghApi('PATCH', `/repos/${owner}/${repo}`, rest);
315
+ },
316
+ },
317
+ };
318
+ }
319
+
320
+ function stringifyError(err: unknown): string {
321
+ if (err instanceof Error) return err.message;
322
+ return String(err);
323
+ }
324
+
325
+ /**
326
+ * Re-exported so callers can preload the ruleset (e.g. for a `--show-ruleset`
327
+ * flag in future). Currently exists for parity with the App's pattern.
328
+ */
329
+ export { loadCanonicalV1 };
@@ -0,0 +1,155 @@
1
+ // Wave 6b (rc.17 fix) — Claude Code `type: command` commit-review hook scaffolding.
2
+ //
3
+ // `clud-bug init --with-hooks` writes a native Claude Code hook that, on every
4
+ // `git commit`, runs clud-bug's review recipe ON THIS SESSION'S SUBSCRIPTION
5
+ // (no API key), in the background (the commit never blocks).
6
+ //
7
+ // WHY `type: command`, NOT `type: agent`: a Claude Code `type: agent` hook
8
+ // spawns a subagent restricted to Read/Grep/Glob — it has NO Bash and the tool
9
+ // set is not configurable (see code.claude.com/docs/en/hooks: "spawn a subagent
10
+ // that can use tools like Read, Grep, and Glob"). The original Wave 6b hook used
11
+ // `type: agent` and told the subagent to run `npx clud-bug review-prompt` — a
12
+ // Bash CLI call an agent hook can never make — so the review NEVER ran for
13
+ // anyone. A `type: command` hook CAN run the CLI: it fetches the engine's recipe
14
+ // and surfaces it to the session via exit-2 (`asyncRewake`), so the MAIN agent —
15
+ // which has Bash, git, gh, and the subscription — performs the review. The hook
16
+ // exits 0 on any failure, so a review that can't run is a quiet no-op and the
17
+ // commit is NEVER blocked.
18
+
19
+ /** Stable marker embedded in our hook so re-runs — and upgrades from the old,
20
+ * broken `type: agent` hook — replace it in place. */
21
+ export const CLUD_BUG_HOOK_MARKER = 'clud-bug-local-review';
22
+
23
+ /**
24
+ * Build the shell `command` of the commit-review hook. Pins to a FLOATING npm
25
+ * dist-tag (`next` by default) rather than an exact version, so every repo's hook
26
+ * auto-fetches the latest review recipe — no per-release re-pin rollout. (The
27
+ * original exact-pin guarded against a `latest` that predated the `review-prompt`
28
+ * verb; that verb now ships in every channel, so floating is safe + frictionless.)
29
+ * Max mode is advisory, so "always newest recipe" is the right default for a
30
+ * review tool. `pin` is overridable for a repo that wants a frozen, exact version.
31
+ *
32
+ * The command, in order:
33
+ * 1. Idempotency — skip if this exact HEAD was already surfaced (avoids a
34
+ * re-review on an amend-with-no-change or a double-fire). The reviewed SHA
35
+ * is recorded under `.git/` (untracked), reusing the "last-reviewed-sha"
36
+ * idea the hosted bot uses on PR comments.
37
+ * 2. Fetch a fresh recipe tailored to THIS repo: `review-prompt --trigger
38
+ * commit` (an instruction recipe — `git show HEAD` + the skills + the
39
+ * report format — NOT raw data; it is meant to be FOLLOWED by an agent).
40
+ * 3. Surface it to the session by printing it and `exit 2`, so `asyncRewake`
41
+ * shows it to the main agent as a system reminder. The agent then reviews
42
+ * the commit on the session subscription.
43
+ * 4. Any failure or empty output → `exit 0` (quiet; the commit is never blocked).
44
+ */
45
+ export function buildCommitReviewCommand(pin: string = 'next'): string {
46
+ return [
47
+ // Marker as a `#` comment (NOT a `:` no-op) so its free text can never break
48
+ // `sh` — a paren / quote / `$` in the marker line would be a syntax error
49
+ // under `: ...`. The dogfood caught this. `isOurHook` finds the marker here.
50
+ `# ${CLUD_BUG_HOOK_MARKER} v2 — clud-bug commit review on the session subscription`,
51
+ // Belt-and-suspenders gate. The `if: Bash(git commit *)` / `Bash(logmind log *)`
52
+ // field filters at the platform on Claude Code >= 2.1.85; OLDER CC ignores
53
+ // `if` and would fire this on EVERY Bash call (a review recipe after every
54
+ // command). Command hooks get the event JSON on stdin — re-check it here. If
55
+ // stdin is empty (a CC that doesn't pipe it), fall through and trust `if`.
56
+ `ev=$(cat 2>/dev/null)`,
57
+ `if [ -n "$ev" ]; then case "$ev" in *'git commit'*|*'logmind log'*) ;; *) exit 0 ;; esac; fi`,
58
+ `sha=$(git rev-parse HEAD 2>/dev/null) || exit 0`,
59
+ `gitdir=$(git rev-parse --git-dir 2>/dev/null) || exit 0`,
60
+ `marker="$gitdir/clud-bug-last-commit-review"`,
61
+ `[ "$(cat "$marker" 2>/dev/null)" = "$sha" ] && exit 0`,
62
+ // H4 — one retry on a transient npx/network blip (a stale lock, a slow
63
+ // registry) before giving up, so a hiccup doesn't silently skip the review.
64
+ // `|| recipe=` clears it on a NON-ZERO exit so partial/error stdout from a
65
+ // mid-run crash (or an old npm warning on stdout) is never mistaken for a
66
+ // valid recipe — only a clean, exit-0 run surfaces.
67
+ `recipe=$(npx clud-bug@${pin} review-prompt --trigger commit 2>/dev/null) || recipe=`,
68
+ `if [ -z "$recipe" ]; then sleep 1; recipe=$(npx clud-bug@${pin} review-prompt --trigger commit 2>/dev/null) || recipe=; fi`,
69
+ // H4 — when the recipe still can't be fetched, leave a diagnostic marker so a
70
+ // FAILED review is distinguishable from a CLEAN one (a clean review surfaces
71
+ // the recipe + the agent reports clean). Never blocks the commit.
72
+ `if [ -z "$recipe" ]; then printf '%s' "$sha" > "$gitdir/clud-bug-review-skipped" 2>/dev/null || true; exit 0; fi`,
73
+ `printf '%s' "$sha" > "$marker" 2>/dev/null || true`,
74
+ `printf '%s\\n\\n%s\\n' "clud-bug commit review (max mode — on this session's subscription): a commit was just made. Follow this recipe now — review that commit against the skills it names and surface any findings." "$recipe"`,
75
+ `exit 2`,
76
+ ].join('\n');
77
+ }
78
+
79
+ /** One Claude Code hook entry: a tool matcher plus its hook list. */
80
+ export interface HookMatcherEntry {
81
+ matcher?: string;
82
+ hooks: Array<Record<string, unknown>>;
83
+ }
84
+
85
+ /** Minimal shape of the `.claude/settings.json` we read + merge into. */
86
+ export interface ClaudeSettings {
87
+ hooks?: Record<string, HookMatcherEntry[]>;
88
+ [key: string]: unknown;
89
+ }
90
+
91
+ /**
92
+ * Builds the PostToolUse entry that runs the commit-review command: a native
93
+ * `type: command` hook, backgrounded (`async`), surfacing the recipe back to the
94
+ * session (`asyncRewake` + exit 2), firing only on `git commit` (`if`).
95
+ */
96
+ export function buildLocalReviewHook(command: string): HookMatcherEntry {
97
+ const base = { type: 'command', async: true, asyncRewake: true, timeout: 180, command } as const;
98
+ return {
99
+ matcher: 'Bash',
100
+ hooks: [
101
+ { ...base, if: 'Bash(git commit *)' },
102
+ // thrillmade repos (and any logmind user) commit via `logmind log`, which
103
+ // wraps `git commit` inside its own binary — so the Bash tool call is
104
+ // `logmind log ...`, which `Bash(git commit *)` never matches. Fire on it
105
+ // too, or max mode never triggers in a logmind repo. The idempotency
106
+ // SHA-marker means whichever path runs, a commit is reviewed exactly once.
107
+ { ...base, if: 'Bash(logmind log *)' },
108
+ ],
109
+ };
110
+ }
111
+
112
+ function isOurHook(h: Record<string, unknown> | undefined): boolean {
113
+ // Match our marker in `command` (current `type: command` hook) OR `prompt`
114
+ // (the old, broken `type: agent` hook) so a re-install / `clud-bug update`
115
+ // replaces either in place.
116
+ const field = h?.['command'] ?? h?.['prompt'];
117
+ return typeof field === 'string' && field.includes(CLUD_BUG_HOOK_MARKER);
118
+ }
119
+
120
+ function isCludBugReviewEntry(entry: HookMatcherEntry | undefined): boolean {
121
+ return !!entry && Array.isArray(entry.hooks) && entry.hooks.some(isOurHook);
122
+ }
123
+
124
+ /**
125
+ * Merges the clud-bug commit-review hook into an existing `.claude/settings.json`
126
+ * object. **Idempotent** (replaces any prior clud-bug entry — including the old
127
+ * `type: agent` one — rather than duplicating) and **non-clobbering** (preserves
128
+ * every other top-level key, event, and hook). Tolerates a missing/malformed
129
+ * `existing` value.
130
+ */
131
+ export function mergeLocalReviewHook(existing: unknown, command: string): ClaudeSettings {
132
+ const base: ClaudeSettings =
133
+ existing && typeof existing === 'object' ? { ...(existing as ClaudeSettings) } : {};
134
+ const hooks: Record<string, HookMatcherEntry[]> = { ...(base.hooks ?? {}) };
135
+ const priorPost = Array.isArray(hooks.PostToolUse) ? hooks.PostToolUse : [];
136
+
137
+ // Preserve every non-clud-bug hook — including any the user co-located INSIDE
138
+ // our own matcher entry: drop only the hook(s) carrying our marker, never the
139
+ // whole entry.
140
+ const ours = buildLocalReviewHook(command);
141
+ const otherEntries: HookMatcherEntry[] = [];
142
+ const coLocatedUserHooks: Array<Record<string, unknown>> = [];
143
+ for (const entry of priorPost) {
144
+ if (isCludBugReviewEntry(entry)) {
145
+ for (const h of entry.hooks) if (!isOurHook(h)) coLocatedUserHooks.push(h);
146
+ } else {
147
+ otherEntries.push(entry);
148
+ }
149
+ }
150
+ const ourEntry: HookMatcherEntry =
151
+ coLocatedUserHooks.length > 0 ? { ...ours, hooks: [...coLocatedUserHooks, ...ours.hooks] } : ours;
152
+ hooks.PostToolUse = [...otherEntries, ourEntry];
153
+ base.hooks = hooks;
154
+ return base;
155
+ }
package/src/cli/index.ts CHANGED
@@ -99,3 +99,9 @@ export {
99
99
  type UpdateSkippedRecord,
100
100
  type RunUpdateResult,
101
101
  } from './update.js';
102
+
103
+ export {
104
+ runConfigureGithub,
105
+ ghCliOctokit,
106
+ type RunConfigureGithubOptions,
107
+ } from './configure-github.js';