thumbgate 1.12.2 → 1.14.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.
@@ -0,0 +1,421 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * PR Manager — High-Throughput Merge & Blocker Diagnosis
4
+ *
5
+ * Inspired by the 2026 GitHub 'Quick Access' update. Centralizes merge status
6
+ * detection and triggers autonomous self-healing for common blockers.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const { spawnSync } = require('node:child_process');
14
+ const PR_FIELDS = 'number,state,mergeable,mergeStateStatus,statusCheckRollup,reviewDecision,isDraft,title,url,headRefOid,baseRefName,mergeCommit,mergedAt,mergedBy';
15
+ const PR_CHECK_FIELDS = 'bucket,name,state,workflow,link,event';
16
+ const MERGE_QUALITY_CHECKS = JSON.parse(
17
+ fs.readFileSync(path.join(__dirname, '..', 'config', 'merge-quality-checks.json'), 'utf8')
18
+ );
19
+ const FIXED_GH_BINARIES = [
20
+ '/usr/bin/gh',
21
+ '/usr/local/bin/gh',
22
+ '/opt/homebrew/bin/gh',
23
+ ];
24
+ const SUCCESSFUL_CHECK_CONCLUSIONS = new Set(['SUCCESS', 'SKIPPED', 'NEUTRAL']);
25
+ const FAILING_CHECK_CONCLUSIONS = new Set([
26
+ 'ACTION_REQUIRED',
27
+ 'CANCELLED',
28
+ 'FAILURE',
29
+ 'STALE',
30
+ 'STARTUP_FAILURE',
31
+ 'TIMED_OUT',
32
+ ]);
33
+ const PASSING_BUCKETS = new Set((MERGE_QUALITY_CHECKS.passingBuckets || []).map((value) => String(value || '').toLowerCase()));
34
+ const PENDING_BUCKETS = new Set((MERGE_QUALITY_CHECKS.pendingBuckets || []).map((value) => String(value || '').toLowerCase()));
35
+ const FAILING_BUCKETS = new Set((MERGE_QUALITY_CHECKS.failingBuckets || []).map((value) => String(value || '').toLowerCase()));
36
+
37
+ function assertSafeGhArgs(args) {
38
+ if (!Array.isArray(args) || args.length === 0) {
39
+ throw new Error('GH CLI args must be a non-empty array.');
40
+ }
41
+
42
+ return args.map((arg) => {
43
+ const normalized = String(arg ?? '');
44
+ if (!normalized || /\0/.test(normalized)) {
45
+ throw new Error(`Unsafe GH CLI arg: ${arg}`);
46
+ }
47
+ return normalized;
48
+ });
49
+ }
50
+
51
+ function normalizePrNumber(prNumber, { allowEmpty = true } = {}) {
52
+ const normalized = String(prNumber ?? '').trim();
53
+ if (!normalized) {
54
+ if (allowEmpty) {
55
+ return '';
56
+ }
57
+ throw new Error('PR number is required.');
58
+ }
59
+
60
+ if (!/^[1-9]\d*$/.test(normalized)) {
61
+ throw new Error(`Unsafe PR number: ${prNumber}`);
62
+ }
63
+
64
+ return normalized;
65
+ }
66
+
67
+ function resolveGhBinary(options = {}) {
68
+ const accessSync = options.accessSync || fs.accessSync;
69
+ const candidates = [];
70
+ const configuredBinary = String(process.env.THUMBGATE_GH_BIN || '').trim();
71
+
72
+ if (configuredBinary) {
73
+ if (!path.isAbsolute(configuredBinary)) {
74
+ throw new Error(`Unsafe GH binary path: ${configuredBinary}`);
75
+ }
76
+ candidates.push(configuredBinary);
77
+ }
78
+
79
+ candidates.push(...FIXED_GH_BINARIES);
80
+
81
+ for (const candidate of candidates) {
82
+ try {
83
+ accessSync(candidate, fs.constants.X_OK);
84
+ return candidate;
85
+ } catch {
86
+ continue;
87
+ }
88
+ }
89
+
90
+ throw new Error(`Unable to locate GH CLI in fixed paths: ${candidates.join(', ')}`);
91
+ }
92
+
93
+ function runGh(args, options = {}) {
94
+ return spawnSync(resolveGhBinary(options), assertSafeGhArgs(args), {
95
+ encoding: 'utf-8',
96
+ stdio: ['ignore', 'pipe', 'pipe'],
97
+ });
98
+ }
99
+
100
+ function formatGhError(result) {
101
+ return (result.stderr || result.stdout || 'Unknown GH CLI failure').trim();
102
+ }
103
+
104
+ function isMissingCurrentBranchPr(result, prNumber) {
105
+ if (prNumber) {
106
+ return false;
107
+ }
108
+
109
+ return /no pull requests found for branch/i.test(formatGhError(result));
110
+ }
111
+
112
+ /**
113
+ * Fetch granular PR status using GH CLI
114
+ */
115
+ function getPrStatus(prNumber = '', runner = runGh) {
116
+ const normalizedPrNumber = normalizePrNumber(prNumber);
117
+ const args = ['pr', 'view'];
118
+ if (normalizedPrNumber) args.push(normalizedPrNumber);
119
+ args.push('--json', PR_FIELDS);
120
+
121
+ const result = runner(args);
122
+ if (result.status !== 0) {
123
+ if (isMissingCurrentBranchPr(result, normalizedPrNumber)) {
124
+ return null;
125
+ }
126
+
127
+ throw new Error(`Failed to fetch PR status: ${formatGhError(result)}`);
128
+ }
129
+ return JSON.parse(result.stdout);
130
+ }
131
+
132
+ function getPrChecks(prNumber = '', runner = runGh) {
133
+ const normalizedPrNumber = normalizePrNumber(prNumber, { allowEmpty: false });
134
+ const result = runner(['pr', 'checks', normalizedPrNumber, '--json', PR_CHECK_FIELDS]);
135
+ if (result.status !== 0) {
136
+ throw new Error(`Failed to fetch PR checks: ${formatGhError(result)}`);
137
+ }
138
+
139
+ return JSON.parse(result.stdout || '[]');
140
+ }
141
+
142
+ function listOpenPrs(runner = runGh) {
143
+ const result = runner(['pr', 'list', '--state', 'open', '--json', PR_FIELDS]);
144
+ if (result.status !== 0) {
145
+ throw new Error(`Failed to list open PRs: ${formatGhError(result)}`);
146
+ }
147
+
148
+ return JSON.parse(result.stdout || '[]');
149
+ }
150
+
151
+ function isOpenPr(pr) {
152
+ return Boolean(pr) && String(pr.state || 'OPEN').toUpperCase() === 'OPEN';
153
+ }
154
+
155
+ function loadManagedPrs(prNumber = '', runner = runGh) {
156
+ if (prNumber) {
157
+ return [getPrStatus(prNumber, runner)];
158
+ }
159
+
160
+ const currentBranchPr = getPrStatus('', runner);
161
+ if (isOpenPr(currentBranchPr)) {
162
+ return [currentBranchPr];
163
+ }
164
+
165
+ return listOpenPrs(runner);
166
+ }
167
+
168
+ function summarizeChecks(checks = []) {
169
+ const failing = [];
170
+ const pending = [];
171
+
172
+ for (const check of checks) {
173
+ const name = check.name || 'unknown-check';
174
+ const bucket = String(check.bucket || '').toLowerCase();
175
+ if (bucket) {
176
+ if (FAILING_BUCKETS.has(bucket)) {
177
+ failing.push(name);
178
+ continue;
179
+ }
180
+
181
+ if (PENDING_BUCKETS.has(bucket)) {
182
+ pending.push(name);
183
+ continue;
184
+ }
185
+
186
+ if (PASSING_BUCKETS.has(bucket)) {
187
+ continue;
188
+ }
189
+ }
190
+
191
+ const conclusion = check.conclusion || null;
192
+ const status = check.status || (conclusion ? 'COMPLETED' : 'UNKNOWN');
193
+
194
+ if (status !== 'COMPLETED') {
195
+ pending.push(name);
196
+ continue;
197
+ }
198
+
199
+ if (conclusion && FAILING_CHECK_CONCLUSIONS.has(conclusion)) {
200
+ failing.push(name);
201
+ continue;
202
+ }
203
+
204
+ if (conclusion && !SUCCESSFUL_CHECK_CONCLUSIONS.has(conclusion)) {
205
+ pending.push(name);
206
+ }
207
+ }
208
+
209
+ return { failing, pending };
210
+ }
211
+
212
+ function sleep(ms) {
213
+ if (!ms || ms <= 0) return;
214
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
215
+ }
216
+
217
+ /**
218
+ * Diagnose and resolve blockers autonomously
219
+ */
220
+ async function resolveBlockers(pr, runner = runGh) {
221
+ const title = pr.title || 'Untitled PR';
222
+ const mergeState = pr.mergeStateStatus || 'UNKNOWN';
223
+ const mergeable = pr.mergeable || 'UNKNOWN';
224
+
225
+ console.log(`[PR Manager] Diagnosing PR #${pr.number}: "${title}"`);
226
+ console.log(`[PR Manager] Merge State: ${mergeState} | Mergeable: ${mergeable}`);
227
+
228
+ if (pr.isDraft) {
229
+ console.log('[PR Manager] PR is a draft. Skipping.');
230
+ return { status: 'skipped', reason: 'draft' };
231
+ }
232
+
233
+ // 1. Handle Outdated Branch (BEHIND)
234
+ if (pr.mergeStateStatus === 'BEHIND') {
235
+ console.log('[PR Manager] PR is behind main. Triggering auto-update...');
236
+ const update = runner(['pr', 'update-branch', pr.number.toString()]);
237
+ if (update.status === 0) {
238
+ return { status: 'healing', action: 'update-branch' };
239
+ }
240
+ }
241
+
242
+ // 2. Handle Merge Conflicts (DIRTY)
243
+ if (pr.mergeStateStatus === 'DIRTY' || pr.mergeable === 'CONFLICTING') {
244
+ console.log('[PR Manager] CRITICAL: Merge conflicts detected. Manual intervention or advanced rebase required.');
245
+ return { status: 'blocked', reason: 'conflicts' };
246
+ }
247
+
248
+ // 3. Handle CI Failures
249
+ let checks = pr.statusCheckRollup || [];
250
+ let checkSource = 'statusCheckRollup';
251
+
252
+ if (pr.number) {
253
+ try {
254
+ checks = getPrChecks(pr.number, runner);
255
+ checkSource = 'gh pr checks';
256
+ } catch (error) {
257
+ console.warn(`[PR Manager] Falling back to statusCheckRollup for PR #${pr.number}: ${error.message}`);
258
+ }
259
+ }
260
+
261
+ const checkSummary = summarizeChecks(checks);
262
+ const failingChecks = checkSummary.failing;
263
+
264
+ if (failingChecks.length > 0) {
265
+ console.log(`[PR Manager] BLOCKED: ${failingChecks.length} failing quality checks via ${checkSource}.`);
266
+ return { status: 'blocked', reason: 'ci_failure', checks: failingChecks, checkSource };
267
+ }
268
+
269
+ if (checkSummary.pending.length > 0) {
270
+ console.log(`[PR Manager] BLOCKED: ${checkSummary.pending.length} quality checks still pending via ${checkSource}.`);
271
+ return { status: 'blocked', reason: 'ci_pending', checks: checkSummary.pending, checkSource };
272
+ }
273
+
274
+ // 4. Handle Review Blockers
275
+ if (pr.reviewDecision === 'CHANGES_REQUESTED') {
276
+ console.log('[PR Manager] BLOCKED: Changes requested by reviewer.');
277
+ return { status: 'blocked', reason: 'changes_requested' };
278
+ }
279
+
280
+ if (pr.reviewDecision === 'REVIEW_REQUIRED') {
281
+ console.log('[PR Manager] BLOCKED: Required review is still outstanding.');
282
+ return { status: 'blocked', reason: 'review_required' };
283
+ }
284
+
285
+ // 5. Ready to Merge
286
+ if (pr.mergeStateStatus === 'CLEAN' && pr.mergeable === 'MERGEABLE') {
287
+ console.log('[PR Manager] SUCCESS: PR is ready for protected autonomous merge.');
288
+ return { status: 'ready' };
289
+ }
290
+
291
+ return { status: 'pending', reason: 'unknown_state' };
292
+ }
293
+
294
+ function waitForMergeCommit(prNumber, runner = runGh, options = {}) {
295
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 300000;
296
+ const intervalMs = Number.isFinite(options.intervalMs) ? options.intervalMs : 10000;
297
+ const startedAt = Date.now();
298
+
299
+ do {
300
+ const pr = getPrStatus(prNumber, runner);
301
+ if (pr && String(pr.state || '').toUpperCase() === 'MERGED' && pr.mergeCommit && pr.mergeCommit.oid) {
302
+ return {
303
+ finalized: true,
304
+ merged: true,
305
+ mergeCommit: pr.mergeCommit.oid,
306
+ mergedAt: pr.mergedAt || null,
307
+ mergedBy: pr.mergedBy && pr.mergedBy.login ? pr.mergedBy.login : null,
308
+ pr,
309
+ };
310
+ }
311
+
312
+ if (pr && String(pr.state || '').toUpperCase() === 'CLOSED') {
313
+ return {
314
+ finalized: true,
315
+ merged: false,
316
+ reason: 'closed_without_merge',
317
+ pr,
318
+ };
319
+ }
320
+
321
+ if (intervalMs <= 0) {
322
+ break;
323
+ }
324
+
325
+ if ((Date.now() - startedAt + intervalMs) > timeoutMs) {
326
+ break;
327
+ }
328
+
329
+ sleep(intervalMs);
330
+ } while ((Date.now() - startedAt) <= timeoutMs);
331
+
332
+ return {
333
+ finalized: false,
334
+ merged: false,
335
+ reason: 'merge_commit_pending',
336
+ };
337
+ }
338
+
339
+ /**
340
+ * Perform autonomous merge
341
+ */
342
+ function performMerge(prNumber, runner = runGh, options = {}) {
343
+ const normalizedPrNumber = normalizePrNumber(prNumber, { allowEmpty: false });
344
+ const args = ['pr', 'merge', normalizedPrNumber, '--squash', '--delete-branch'];
345
+ console.log(`[PR Manager] Initiating protected squash merge for PR #${normalizedPrNumber}...`);
346
+ const result = runner(args);
347
+ if (result.status === 0) {
348
+ const output = `${result.stdout || ''}\n${result.stderr || ''}`;
349
+ const mode = /merge queue|queued/i.test(output) ? 'queued' : 'merged';
350
+ console.log(`[PR Manager] Merge accepted for PR #${normalizedPrNumber} (${mode}).`);
351
+ const mergeStatus = options.waitForMerge === false
352
+ ? { finalized: false, merged: false, reason: 'merge_commit_pending' }
353
+ : waitForMergeCommit(normalizedPrNumber, runner, options);
354
+ return { ok: true, mode, args, ...mergeStatus };
355
+ } else {
356
+ console.error(`[PR Manager] Merge failed: ${formatGhError(result)}`);
357
+ return { ok: false, mode: 'failed', args, error: formatGhError(result) };
358
+ }
359
+ }
360
+
361
+ async function managePrs(prNumber = '', runner = runGh, options = {}) {
362
+ const prs = loadManagedPrs(prNumber, runner).filter(Boolean);
363
+
364
+ if (prs.length === 0) {
365
+ console.log('[PR Manager] No open pull requests found.');
366
+ return { status: 'noop', prs: [] };
367
+ }
368
+
369
+ const results = [];
370
+ for (const pr of prs) {
371
+ const outcome = await resolveBlockers(pr, runner);
372
+ if (outcome.status === 'ready') {
373
+ const mergeResult = performMerge(pr.number, runner, options);
374
+ outcome.mergeRequested = mergeResult.ok;
375
+ outcome.mergeMode = mergeResult.mode;
376
+ if (mergeResult.mergeCommit) {
377
+ outcome.mergeCommit = mergeResult.mergeCommit;
378
+ }
379
+ if (mergeResult.finalized !== undefined) {
380
+ outcome.mergeFinalized = mergeResult.finalized;
381
+ }
382
+ if (mergeResult.reason) {
383
+ outcome.mergeResolution = mergeResult.reason;
384
+ }
385
+ }
386
+
387
+ results.push({
388
+ number: pr.number,
389
+ title: pr.title,
390
+ outcome,
391
+ });
392
+ }
393
+
394
+ return { status: 'ok', prs: results };
395
+ }
396
+
397
+ if (require.main === module) {
398
+ const prNum = process.argv[2];
399
+ managePrs(prNum).then(() => {
400
+ process.exit(0);
401
+ }).catch((err) => {
402
+ console.error(err.message);
403
+ process.exit(1);
404
+ });
405
+ }
406
+
407
+ module.exports = {
408
+ assertSafeGhArgs,
409
+ getPrStatus,
410
+ getPrChecks,
411
+ listOpenPrs,
412
+ isOpenPr,
413
+ loadManagedPrs,
414
+ normalizePrNumber,
415
+ resolveBlockers,
416
+ resolveGhBinary,
417
+ waitForMergeCommit,
418
+ performMerge,
419
+ managePrs,
420
+ summarizeChecks,
421
+ };
@@ -1156,6 +1156,22 @@ const TOOLS = [
1156
1156
  },
1157
1157
  },
1158
1158
  }),
1159
+ readOnlyTool({
1160
+ name: 'generate_operator_artifact',
1161
+ description: 'Dynamic operator artifact generator. Turns ThumbGate PR, reliability, revenue, and release data into a decision-ready pulse with metrics, evidence, and next actions.',
1162
+ inputSchema: {
1163
+ type: 'object',
1164
+ properties: {
1165
+ type: {
1166
+ type: 'string',
1167
+ enum: ['pr-pulse', 'reliability-pulse', 'revenue-pulse', 'release-readiness'],
1168
+ description: 'Artifact to generate. Defaults to reliability-pulse.',
1169
+ },
1170
+ windowHours: { type: 'number', description: 'Lookback window in hours (default 24, max 720)' },
1171
+ format: { type: 'string', enum: ['json', 'markdown'], description: 'Response format. Defaults to json.' },
1172
+ },
1173
+ },
1174
+ }),
1159
1175
  readOnlyTool({
1160
1176
  name: 'context_stuff_lessons',
1161
1177
  description: 'Dump ALL prevention lessons into a single text block for context-window injection. Bypasses RAG/search — returns every lesson sorted by confidence. For most projects (20-200 lessons), fits in 1K-10K tokens.',