@akjamie/agentic-sdlc 1.9.3 → 2.0.0-alpha.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.
@@ -0,0 +1,566 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { resolveGitHostAndRepo } from './githost.js';
3
+ import { resolveGitCredentials } from './auth.js';
4
+
5
+ /**
6
+ * GraphQL query for fetching PR review threads, review decision, and commit anchor.
7
+ */
8
+ export const PULL_REQUEST_THREADS_QUERY = `
9
+ query PullRequestReviewThreads($owner: String!, $repo: String!, $number: Int!) {
10
+ repository(owner: $owner, name: $repo) {
11
+ pullRequest(number: $number) {
12
+ reviewDecision
13
+ headRefOid
14
+ commits(last: 1) { nodes { commit { committedDate, oid } } }
15
+ reviewThreads(first: 100) {
16
+ nodes {
17
+ id
18
+ isResolved
19
+ isOutdated
20
+ path
21
+ line
22
+ originalLine
23
+ comments(first: 20) {
24
+ nodes {
25
+ id
26
+ databaseId
27
+ author { login }
28
+ body
29
+ createdAt
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ `.trim();
38
+
39
+ const DEFAULT_AGENT_LOGINS = [
40
+ 'asdlc-bot',
41
+ 'asdlc-bot[bot]',
42
+ 'github-actions',
43
+ 'github-actions[bot]',
44
+ 'dependabot[bot]',
45
+ ];
46
+
47
+ const THREAD_TRAILER_RE = /\bref:\s*#([A-Za-z0-9_=-]+)/g;
48
+ const SUGGESTION_BLOCK_RE = /```suggestion\r?\n([\s\S]*?)```/;
49
+
50
+ const ACTION_IMPERATIVE_RE = /\b(please|fix|add|remove|delete|rename|change|update|handle|refactor|avoid|should|must|need to|needs to|missing|bug|error|broken|fail|invalid|nullable|null check|throw|catch|test)\b/i;
51
+ const MIXED_SIGNAL_RE = /\b(lgtm|looks good|nice|great|good)\b.*\b(but|however|except|though|although|nit|please)\b/i;
52
+ const QUESTION_RE = /(\?|\b(why|how|what if|could you explain|can you explain|what does|is this|are we|should this)\b)/i;
53
+ const PRAISE_ONLY_RE = /^(?:lgtm|looks good(?: to me)?|nice(?: work| approach| job)?|good(?: job| catch| work)?|great|awesome|ship it|\+1|👍|🎉|🚀|✅)[!.\s]*$/i;
54
+
55
+ /**
56
+ * Extracts review thread IDs already resolved via commit trailers (`ref: #<threadId>`).
57
+ */
58
+ export function extractAddressedThreadIds(commitMessages = []) {
59
+ const ids = new Set();
60
+ for (const msg of commitMessages) {
61
+ if (!msg) continue;
62
+ for (const match of String(msg).matchAll(THREAD_TRAILER_RE)) {
63
+ ids.add(match[1]);
64
+ }
65
+ }
66
+ return ids;
67
+ }
68
+
69
+ /**
70
+ * Returns true if the comment author is an automated bot or self-agent account.
71
+ */
72
+ export function isBotOrSelfAuthor(login, { agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
73
+ if (!login) return true;
74
+ const norm = String(login).trim().toLowerCase();
75
+ if (norm.endsWith('[bot]')) return true;
76
+ return agentLogins.some((a) => String(a).toLowerCase() === norm);
77
+ }
78
+
79
+ /**
80
+ * Tier 1 Ingestion Filter:
81
+ * Selects unresolved threads not already referenced in commit trailers whose latest comment
82
+ * was authored by a human reviewer (never bots/self, preventing infinite loops).
83
+ */
84
+ export function filterUnaddressedThreads(threads = [], { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
85
+ const addressedIds = extractAddressedThreadIds(commitMessages);
86
+ const candidates = [];
87
+
88
+ for (const thread of threads) {
89
+ if (!thread || thread.isResolved === true) continue;
90
+ if (thread.id && addressedIds.has(thread.id)) continue;
91
+
92
+ const nodes = thread.comments?.nodes || thread.comments || [];
93
+ if (!Array.isArray(nodes) || nodes.length === 0) continue;
94
+
95
+ const latestComment = nodes[nodes.length - 1];
96
+ const authorLogin = latestComment?.author?.login ?? latestComment?.author ?? '';
97
+ if (isBotOrSelfAuthor(authorLogin, { agentLogins })) continue;
98
+
99
+ candidates.push({
100
+ ...thread,
101
+ latestComment,
102
+ latestBody: String(latestComment?.body ?? ''),
103
+ latestAuthor: authorLogin,
104
+ });
105
+ }
106
+
107
+ return candidates;
108
+ }
109
+
110
+ /**
111
+ * Tier 2 4-Way Semantic Intent Classifier:
112
+ * - Category B: SUGGESTION_BLOCK (GitHub ```suggestion``` block)
113
+ * - Category A: ACTION_REQUIRED (imperative demand, defect, or conservative mixed-signal fallback)
114
+ * - Category C: INFORMATIONAL_QUESTION (architectural/rationale inquiry; zero code mutation)
115
+ * - Category D: NON_ACTIONABLE (pure praise / acknowledgment)
116
+ */
117
+ export function classifyReviewComment(body, { path = null, line = null } = {}) {
118
+ const text = String(body ?? '').trim();
119
+
120
+ // Category B: Native suggestion diff block
121
+ const suggMatch = text.match(SUGGESTION_BLOCK_RE);
122
+ if (suggMatch) {
123
+ return {
124
+ category: 'B',
125
+ intent: 'SUGGESTION_BLOCK',
126
+ actionable: true,
127
+ requiresCodeOrSpecEdit: true,
128
+ suggestedText: suggMatch[1].replace(/\r\n/g, '\n').replace(/\n$/, ''),
129
+ path,
130
+ line,
131
+ body: text,
132
+ };
133
+ }
134
+
135
+ // Category A: Mixed-signal conservative guard ("LGTM, but fix X") or explicit action imperative
136
+ if (MIXED_SIGNAL_RE.test(text) || ACTION_IMPERATIVE_RE.test(text)) {
137
+ return {
138
+ category: 'A',
139
+ intent: 'ACTION_REQUIRED',
140
+ actionable: true,
141
+ requiresCodeOrSpecEdit: true,
142
+ suggestedText: null,
143
+ path,
144
+ line,
145
+ body: text,
146
+ };
147
+ }
148
+
149
+ // Category D: Pure non-actionable praise
150
+ if (!text || PRAISE_ONLY_RE.test(text)) {
151
+ return {
152
+ category: 'D',
153
+ intent: 'NON_ACTIONABLE',
154
+ actionable: false,
155
+ requiresCodeOrSpecEdit: false,
156
+ suggestedText: null,
157
+ path,
158
+ line,
159
+ body: text,
160
+ };
161
+ }
162
+
163
+ // Category C: Informational rationale question
164
+ if (QUESTION_RE.test(text)) {
165
+ return {
166
+ category: 'C',
167
+ intent: 'INFORMATIONAL_QUESTION',
168
+ actionable: true,
169
+ requiresCodeOrSpecEdit: false,
170
+ suggestedText: null,
171
+ path,
172
+ line,
173
+ body: text,
174
+ };
175
+ }
176
+
177
+ // Conservative Intent Invariant: ambiguous unmatched text defaults to ACTION_REQUIRED
178
+ return {
179
+ category: 'A',
180
+ intent: 'ACTION_REQUIRED',
181
+ actionable: true,
182
+ requiresCodeOrSpecEdit: true,
183
+ suggestedText: null,
184
+ path,
185
+ line,
186
+ body: text,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Evaluates a full Pull Request payload through Tier 1 filtering + Tier 2 classification.
192
+ * Captures actionable feedback regardless of whether reviewDecision is COMMENTED or CHANGES_REQUESTED.
193
+ */
194
+ export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
195
+ const threads = prPayload.reviewThreads?.nodes || prPayload.reviewThreads || [];
196
+ const unaddressed = filterUnaddressedThreads(threads, { commitMessages, agentLogins });
197
+
198
+ const actionableThreads = [];
199
+ const suggestionThreads = [];
200
+ const questionThreads = [];
201
+ const nonActionableThreads = [];
202
+
203
+ for (const thread of unaddressed) {
204
+ const classification = classifyReviewComment(thread.latestBody, {
205
+ path: thread.path || null,
206
+ line: thread.line ?? thread.originalLine ?? null,
207
+ });
208
+ const item = { ...thread, classification };
209
+ if (classification.intent === 'SUGGESTION_BLOCK') {
210
+ suggestionThreads.push(item);
211
+ } else if (classification.intent === 'ACTION_REQUIRED') {
212
+ actionableThreads.push(item);
213
+ } else if (classification.intent === 'INFORMATIONAL_QUESTION') {
214
+ questionThreads.push(item);
215
+ } else {
216
+ nonActionableThreads.push(item);
217
+ }
218
+ }
219
+
220
+ // Also triage top-level issue/PR discussion comments if provided
221
+ const topComments = [];
222
+ for (const c of (prPayload.issueComments || [])) {
223
+ const login = c?.author?.login ?? c?.author ?? '';
224
+ if (isBotOrSelfAuthor(login, { agentLogins })) continue;
225
+ const cls = classifyReviewComment(c.body);
226
+ if (cls.actionable) {
227
+ topComments.push({ id: c.id, author: login, body: c.body, classification: cls });
228
+ }
229
+ }
230
+
231
+ const reviewDecision = prPayload.reviewDecision || null;
232
+ const hasHumanFeedback = reviewDecision === 'CHANGES_REQUESTED'
233
+ || actionableThreads.length > 0
234
+ || suggestionThreads.length > 0
235
+ || questionThreads.length > 0
236
+ || topComments.some((c) => c.classification.requiresCodeOrSpecEdit);
237
+
238
+ return {
239
+ reviewDecision,
240
+ unaddressedCount: unaddressed.length,
241
+ actionableThreads,
242
+ suggestionThreads,
243
+ questionThreads,
244
+ nonActionableThreads,
245
+ topComments,
246
+ hasHumanFeedback,
247
+ requiresFixCommit: actionableThreads.length > 0 || suggestionThreads.length > 0 || topComments.some((c) => c.classification.requiresCodeOrSpecEdit),
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Applies a Category B GitHub suggestion block to file contents cleanly in memory.
253
+ * Lines are 1-indexed inclusive.
254
+ */
255
+ export function applySuggestionToLines(fileContent, { startLine = null, endLine = null, line = null, suggestedText = '' } = {}) {
256
+ const normalized = String(fileContent ?? '').replace(/\r\n/g, '\n');
257
+ const hadTrailingNewline = normalized.endsWith('\n');
258
+ const lines = normalized.split('\n');
259
+ if (hadTrailingNewline) lines.pop();
260
+
261
+ const start = Number(startLine ?? line ?? 1);
262
+ const end = Number(endLine ?? line ?? start);
263
+ const replacementLines = String(suggestedText ?? '').replace(/\r\n/g, '\n').split('\n');
264
+
265
+ if (start < 1 || end < start || start > lines.length) {
266
+ throw new Error(`Invalid suggestion line range [${start}, ${end}] for file with ${lines.length} lines`);
267
+ }
268
+
269
+ const updated = [
270
+ ...lines.slice(0, start - 1),
271
+ ...replacementLines,
272
+ ...lines.slice(end),
273
+ ];
274
+
275
+ return updated.join('\n') + (hadTrailingNewline ? '\n' : '');
276
+ }
277
+
278
+ /**
279
+ * Tier 3 Resolution Plan:
280
+ * Generates traceable commit trailer, GraphQL reply mutation, and optional thread resolution mutation.
281
+ * Category C informational answers reply without committing or force-resolving the thread.
282
+ */
283
+ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, summary = '', answerBody = null } = {}) {
284
+ const intent = triagedThread?.classification?.intent;
285
+ const threadId = triagedThread.id;
286
+
287
+ if (intent === 'INFORMATIONAL_QUESTION') {
288
+ const replyBody = answerBody || summary || 'Answered in technical explanation above.';
289
+ return {
290
+ threadId,
291
+ commitMessage: null,
292
+ shouldResolve: false,
293
+ replyMutation: {
294
+ query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
295
+ variables: { threadId, body: replyBody },
296
+ },
297
+ resolveMutation: null,
298
+ };
299
+ }
300
+
301
+ const shortSha = commitSha ? String(commitSha).slice(0, 7) : 'HEAD';
302
+ const cleanSummary = summary || 'address PR review feedback';
303
+ const commitMessage = `fix(review): ${cleanSummary} (ref: #${threadId})`;
304
+ const replyBody = `Resolved in commit \`${shortSha}\`: ${cleanSummary}`;
305
+
306
+ return {
307
+ threadId,
308
+ commitMessage,
309
+ shouldResolve: true,
310
+ replyMutation: {
311
+ query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
312
+ variables: { threadId, body: replyBody },
313
+ },
314
+ resolveMutation: {
315
+ query: 'mutation ResolveThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }',
316
+ variables: { threadId },
317
+ },
318
+ };
319
+ }
320
+
321
+ /**
322
+ * Enforces the Anti-Thrashing 3-Round Circuit Breaker:
323
+ * If unresolved feedback persists beyond `maxRounds` (default: 3), halts automated mutation,
324
+ * produces a structured synthesis report for Human Tech Lead adjudication, and attaches `asdlc:needs-human-arbitration`.
325
+ */
326
+ export function checkAntiThrashingCircuitBreaker({
327
+ currentRound = 1,
328
+ maxRounds = 3,
329
+ unresolvedThreads = [],
330
+ changeId = 'unknown',
331
+ prNumber = null,
332
+ } = {}) {
333
+ if (currentRound <= maxRounds || unresolvedThreads.length === 0) {
334
+ return {
335
+ tripped: false,
336
+ currentRound,
337
+ maxRounds,
338
+ remainingCount: unresolvedThreads.length,
339
+ };
340
+ }
341
+
342
+ const prLabel = prNumber ? `PR #${prNumber}` : 'Active PR';
343
+ const bullets = unresolvedThreads.map((t, idx) => {
344
+ const loc = t.path ? `\`${t.path}${t.line ? `:${t.line}` : ''}\`` : 'General thread';
345
+ const bodySnippet = String(t.latestBody ?? t.body ?? '').replace(/\s+/g, ' ').slice(0, 140);
346
+ return `${idx + 1}. **${loc}** (thread \`${t.id || 'n/a'}\`, @${t.latestAuthor || 'reviewer'}): "${bodySnippet}"`;
347
+ });
348
+
349
+ const synthesisReport = [
350
+ `## Escalation: Anti-Thrashing Circuit Breaker Tripped (${changeId})`,
351
+ '',
352
+ `- **PR**: ${prLabel}`,
353
+ `- **Automated Rounds Attempted**: ${maxRounds} (Round ${currentRound} exceeded cap)`,
354
+ `- **Status**: \`PAUSED_NEEDS_HUMAN_ARBITRATION\``,
355
+ `- **Label Applied**: \`asdlc:needs-human-arbitration\``,
356
+ '',
357
+ '### Remaining Unresolved Review Threads',
358
+ ...bullets,
359
+ '',
360
+ '> Automated edits have paused to prevent infinite feedback loops. Please review the remaining items above and post your adjudication.',
361
+ '',
362
+ ].join('\n');
363
+
364
+ return {
365
+ tripped: true,
366
+ exitCode: 2,
367
+ label: 'asdlc:needs-human-arbitration',
368
+ status: 'PAUSED_NEEDS_HUMAN_ARBITRATION',
369
+ currentRound,
370
+ maxRounds,
371
+ synthesisReport,
372
+ };
373
+ }
374
+
375
+ function resolveOwnerRepo(repoRoot, explicitRepo = null) {
376
+ if (explicitRepo) {
377
+ const parsed = resolveGitHostAndRepo(explicitRepo, { repoRoot });
378
+ return { owner: parsed.owner, repo: parsed.repo, host: parsed.host };
379
+ }
380
+ try {
381
+ const gitRes = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: repoRoot, encoding: 'utf8', timeout: 5000 });
382
+ if (gitRes.status === 0 && gitRes.stdout) {
383
+ const parsed = resolveGitHostAndRepo(gitRes.stdout.trim(), { repoRoot });
384
+ return { owner: parsed.owner, repo: parsed.repo, host: parsed.host };
385
+ }
386
+ } catch {
387
+ // ignore
388
+ }
389
+ return { owner: null, repo: null, host: 'github.com' };
390
+ }
391
+
392
+ /**
393
+ * Fetches full PR review context (review threads, issue comments, review decision) via GraphQL
394
+ * using gh CLI or direct API fetchFn.
395
+ */
396
+ export async function fetchGitHubPrReviewContext(prNumber, {
397
+ repoRoot = process.cwd(),
398
+ repo = null,
399
+ host = null,
400
+ env = process.env,
401
+ fetchFn = null,
402
+ ghRunner = null,
403
+ } = {}) {
404
+ const num = Number(String(prNumber).replace(/^#/, ''));
405
+ if (!Number.isFinite(num) || num <= 0) {
406
+ return {};
407
+ }
408
+
409
+ const { owner, repo: repoName, host: targetHost } = resolveOwnerRepo(repoRoot, repo);
410
+ const effectiveHost = host || targetHost || 'github.com';
411
+
412
+ // 1. If fetchFn is provided, call GraphQL API directly
413
+ if (typeof fetchFn === 'function') {
414
+ const creds = await resolveGitCredentials({ env, host: effectiveHost, fetchFn });
415
+ const apiEndpoint = effectiveHost === 'github.com' ? 'https://api.github.com/graphql' : `https://${effectiveHost}/api/graphql`;
416
+ const headers = {
417
+ Authorization: `Bearer ${creds?.token || ''}`,
418
+ 'Content-Type': 'application/json',
419
+ 'User-Agent': 'agentic-sdlc',
420
+ };
421
+ try {
422
+ const res = await fetchFn(apiEndpoint, {
423
+ method: 'POST',
424
+ headers,
425
+ body: JSON.stringify({
426
+ query: PULL_REQUEST_THREADS_QUERY,
427
+ variables: { owner: owner || 'unknown', repo: repoName || 'unknown', number: num },
428
+ }),
429
+ });
430
+ if (res.ok) {
431
+ const json = await res.json();
432
+ const pr = json?.data?.repository?.pullRequest;
433
+ return {
434
+ prNumber: num,
435
+ headRefOid: pr?.headRefOid || null,
436
+ reviewDecision: pr?.reviewDecision || null,
437
+ reviewThreads: pr?.reviewThreads?.nodes || [],
438
+ issueComments: [],
439
+ };
440
+ }
441
+ } catch {
442
+ // fallback
443
+ }
444
+ }
445
+
446
+ // 2. Default: Use GitHub CLI (`gh api graphql`)
447
+ try {
448
+ const runGh = ghRunner || ((cmd, args) => spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8', env, timeout: 15000 }));
449
+ if (owner && repoName) {
450
+ const gqlRes = runGh('gh', [
451
+ 'api',
452
+ 'graphql',
453
+ '-H', 'Accept: application/vnd.github.v3+json',
454
+ '-F', `owner=${owner}`,
455
+ '-F', `repo=${repoName}`,
456
+ '-F', `number=${num}`,
457
+ '-f', `query=${PULL_REQUEST_THREADS_QUERY}`,
458
+ ]);
459
+ if (gqlRes && gqlRes.status === 0 && gqlRes.stdout) {
460
+ const json = JSON.parse(gqlRes.stdout);
461
+ const pr = json?.data?.repository?.pullRequest;
462
+ const threads = pr?.reviewThreads?.nodes || [];
463
+ const viewRes = runGh('gh', ['pr', 'view', String(num), '--json', 'title,headRefName,labels,state,comments']);
464
+ let parsedView = {};
465
+ if (viewRes && viewRes.status === 0 && viewRes.stdout) {
466
+ parsedView = JSON.parse(viewRes.stdout);
467
+ }
468
+ return {
469
+ prNumber: num,
470
+ title: parsedView.title || null,
471
+ headRefName: parsedView.headRefName || null,
472
+ labels: parsedView.labels || [],
473
+ state: parsedView.state || 'OPEN',
474
+ headRefOid: pr?.headRefOid || null,
475
+ reviewDecision: pr?.reviewDecision || null,
476
+ reviewThreads: threads,
477
+ issueComments: parsedView.comments || [],
478
+ };
479
+ }
480
+ }
481
+
482
+ // Fallback: gh pr view json if graphql fails
483
+ const viewRes = runGh('gh', ['pr', 'view', String(num), '--json', 'title,headRefName,labels,state,comments']);
484
+ if (viewRes && viewRes.status === 0 && viewRes.stdout) {
485
+ const parsedView = JSON.parse(viewRes.stdout);
486
+ return {
487
+ prNumber: num,
488
+ title: parsedView.title || null,
489
+ headRefName: parsedView.headRefName || null,
490
+ labels: parsedView.labels || [],
491
+ state: parsedView.state || 'OPEN',
492
+ reviewThreads: [],
493
+ issueComments: parsedView.comments || [],
494
+ };
495
+ }
496
+ } catch {
497
+ // offline / missing gh
498
+ }
499
+
500
+ return { prNumber: num, reviewThreads: [], issueComments: [] };
501
+ }
502
+
503
+ /**
504
+ * Replies to an inline PR review thread and resolves the conversation via GraphQL.
505
+ */
506
+ export async function replyAndResolveGitHubThread(threadId, replyBody = '', options = {}) {
507
+ let effectiveThreadId = threadId;
508
+ let effectiveReplyBody = replyBody;
509
+ let opts = options;
510
+
511
+ if (typeof threadId === 'object' && threadId !== null) {
512
+ effectiveThreadId = threadId.threadId || threadId.id;
513
+ effectiveReplyBody = threadId.replyBody || threadId.body || '';
514
+ opts = { ...threadId, ...options };
515
+ }
516
+
517
+ if (!effectiveThreadId) return { ok: false };
518
+ const {
519
+ repoRoot = process.cwd(),
520
+ host = 'github.com',
521
+ env = process.env,
522
+ fetchFn = null,
523
+ ghRunner = null,
524
+ } = opts;
525
+
526
+ const replyMutation = 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }';
527
+ const resolveMutation = 'mutation ResolveThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }';
528
+
529
+ if (typeof fetchFn === 'function') {
530
+ const creds = await resolveGitCredentials({ env, host, fetchFn });
531
+ const apiEndpoint = host === 'github.com' ? 'https://api.github.com/graphql' : `https://${host}/api/graphql`;
532
+ const headers = { Authorization: `Bearer ${creds?.token || ''}`, 'Content-Type': 'application/json' };
533
+ try {
534
+ const res1 = await fetchFn(apiEndpoint, { method: 'POST', headers, body: JSON.stringify({ query: replyMutation, variables: { threadId: effectiveThreadId, body: effectiveReplyBody } }) });
535
+ if (!res1 || !res1.ok) return { ok: false, threadId: effectiveThreadId };
536
+ const json1 = await res1.json().catch(() => null);
537
+ if (json1?.errors?.length) return { ok: false, threadId: effectiveThreadId, errors: json1.errors };
538
+
539
+ const res2 = await fetchFn(apiEndpoint, { method: 'POST', headers, body: JSON.stringify({ query: resolveMutation, variables: { threadId: effectiveThreadId } }) });
540
+ if (!res2 || !res2.ok) return { ok: false, threadId: effectiveThreadId };
541
+ const json2 = await res2.json().catch(() => null);
542
+ if (json2?.errors?.length) return { ok: false, threadId: effectiveThreadId, errors: json2.errors };
543
+
544
+ return { ok: true, replied: true, resolved: true, threadId: effectiveThreadId };
545
+ } catch (err) {
546
+ return { ok: false, threadId: effectiveThreadId, error: err.message };
547
+ }
548
+ }
549
+
550
+ try {
551
+ const runGh = ghRunner || ((cmd, args) => spawnSync(cmd, args, { cwd: repoRoot, encoding: 'utf8', env, timeout: 15000 }));
552
+ // Pass literal string parameters with -f (preventing bodies starting with '@' from being parsed as files)
553
+ const r1 = runGh('gh', ['api', 'graphql', '-f', `query=${replyMutation}`, '-f', `threadId=${effectiveThreadId}`, '-f', `body=${effectiveReplyBody}`]);
554
+ if (r1 && r1.status !== 0) {
555
+ return { ok: false, threadId: effectiveThreadId, error: r1.stderr || r1.status };
556
+ }
557
+ const r2 = runGh('gh', ['api', 'graphql', '-f', `query=${resolveMutation}`, '-f', `threadId=${effectiveThreadId}`]);
558
+ if (r2 && r2.status !== 0) {
559
+ return { ok: false, threadId: effectiveThreadId, error: r2.stderr || r2.status };
560
+ }
561
+ return { ok: true, replied: true, resolved: true, threadId: effectiveThreadId };
562
+ } catch (err) {
563
+ return { ok: false, threadId: effectiveThreadId, error: err.message };
564
+ }
565
+ }
566
+