@akjamie/agentic-sdlc 1.9.2 → 1.10.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,369 @@
1
+ /**
2
+ * GraphQL query for fetching PR review threads, review decision, and commit anchor.
3
+ */
4
+ export const PULL_REQUEST_THREADS_QUERY = `
5
+ query PullRequestReviewThreads($owner: String!, $repo: String!, $number: Int!) {
6
+ repository(owner: $owner, name: $repo) {
7
+ pullRequest(number: $number) {
8
+ reviewDecision
9
+ headRefOid
10
+ commits(last: 1) { nodes { commit { committedDate, oid } } }
11
+ reviewThreads(first: 100) {
12
+ nodes {
13
+ id
14
+ isResolved
15
+ isOutdated
16
+ path
17
+ line
18
+ originalLine
19
+ comments(first: 20) {
20
+ nodes {
21
+ id
22
+ databaseId
23
+ author { login }
24
+ body
25
+ createdAt
26
+ }
27
+ }
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
33
+ `.trim();
34
+
35
+ const DEFAULT_AGENT_LOGINS = [
36
+ 'asdlc-bot',
37
+ 'asdlc-bot[bot]',
38
+ 'github-actions',
39
+ 'github-actions[bot]',
40
+ 'dependabot[bot]',
41
+ ];
42
+
43
+ const THREAD_TRAILER_RE = /\bref:\s*#([A-Za-z0-9_=-]+)/g;
44
+ const SUGGESTION_BLOCK_RE = /```suggestion\r?\n([\s\S]*?)```/;
45
+
46
+ 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;
47
+ const MIXED_SIGNAL_RE = /\b(lgtm|looks good|nice|great|good)\b.*\b(but|however|except|though|although|nit|please)\b/i;
48
+ const QUESTION_RE = /(\?|\b(why|how|what if|could you explain|can you explain|what does|is this|are we|should this)\b)/i;
49
+ const PRAISE_ONLY_RE = /^(?:lgtm|looks good(?: to me)?|nice(?: work| approach| job)?|good(?: job| catch| work)?|great|awesome|ship it|\+1|👍|🎉|🚀|✅)[!.\s]*$/i;
50
+
51
+ /**
52
+ * Extracts review thread IDs already resolved via commit trailers (`ref: #<threadId>`).
53
+ */
54
+ export function extractAddressedThreadIds(commitMessages = []) {
55
+ const ids = new Set();
56
+ for (const msg of commitMessages) {
57
+ if (!msg) continue;
58
+ for (const match of String(msg).matchAll(THREAD_TRAILER_RE)) {
59
+ ids.add(match[1]);
60
+ }
61
+ }
62
+ return ids;
63
+ }
64
+
65
+ /**
66
+ * Returns true if the comment author is an automated bot or self-agent account.
67
+ */
68
+ export function isBotOrSelfAuthor(login, { agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
69
+ if (!login) return true;
70
+ const norm = String(login).trim().toLowerCase();
71
+ if (norm.endsWith('[bot]')) return true;
72
+ return agentLogins.some((a) => String(a).toLowerCase() === norm);
73
+ }
74
+
75
+ /**
76
+ * Tier 1 Ingestion Filter:
77
+ * Selects unresolved threads not already referenced in commit trailers whose latest comment
78
+ * was authored by a human reviewer (never bots/self, preventing infinite loops).
79
+ */
80
+ export function filterUnaddressedThreads(threads = [], { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
81
+ const addressedIds = extractAddressedThreadIds(commitMessages);
82
+ const candidates = [];
83
+
84
+ for (const thread of threads) {
85
+ if (!thread || thread.isResolved === true) continue;
86
+ if (thread.id && addressedIds.has(thread.id)) continue;
87
+
88
+ const nodes = thread.comments?.nodes || thread.comments || [];
89
+ if (!Array.isArray(nodes) || nodes.length === 0) continue;
90
+
91
+ const latestComment = nodes[nodes.length - 1];
92
+ const authorLogin = latestComment?.author?.login ?? latestComment?.author ?? '';
93
+ if (isBotOrSelfAuthor(authorLogin, { agentLogins })) continue;
94
+
95
+ candidates.push({
96
+ ...thread,
97
+ latestComment,
98
+ latestBody: String(latestComment?.body ?? ''),
99
+ latestAuthor: authorLogin,
100
+ });
101
+ }
102
+
103
+ return candidates;
104
+ }
105
+
106
+ /**
107
+ * Tier 2 4-Way Semantic Intent Classifier:
108
+ * - Category B: SUGGESTION_BLOCK (GitHub ```suggestion``` block)
109
+ * - Category A: ACTION_REQUIRED (imperative demand, defect, or conservative mixed-signal fallback)
110
+ * - Category C: INFORMATIONAL_QUESTION (architectural/rationale inquiry; zero code mutation)
111
+ * - Category D: NON_ACTIONABLE (pure praise / acknowledgment)
112
+ */
113
+ export function classifyReviewComment(body, { path = null, line = null } = {}) {
114
+ const text = String(body ?? '').trim();
115
+
116
+ // Category B: Native suggestion diff block
117
+ const suggMatch = text.match(SUGGESTION_BLOCK_RE);
118
+ if (suggMatch) {
119
+ return {
120
+ category: 'B',
121
+ intent: 'SUGGESTION_BLOCK',
122
+ actionable: true,
123
+ requiresCodeOrSpecEdit: true,
124
+ suggestedText: suggMatch[1].replace(/\r\n/g, '\n').replace(/\n$/, ''),
125
+ path,
126
+ line,
127
+ body: text,
128
+ };
129
+ }
130
+
131
+ // Category A: Mixed-signal conservative guard ("LGTM, but fix X") or explicit action imperative
132
+ if (MIXED_SIGNAL_RE.test(text) || ACTION_IMPERATIVE_RE.test(text)) {
133
+ return {
134
+ category: 'A',
135
+ intent: 'ACTION_REQUIRED',
136
+ actionable: true,
137
+ requiresCodeOrSpecEdit: true,
138
+ suggestedText: null,
139
+ path,
140
+ line,
141
+ body: text,
142
+ };
143
+ }
144
+
145
+ // Category D: Pure non-actionable praise
146
+ if (!text || PRAISE_ONLY_RE.test(text)) {
147
+ return {
148
+ category: 'D',
149
+ intent: 'NON_ACTIONABLE',
150
+ actionable: false,
151
+ requiresCodeOrSpecEdit: false,
152
+ suggestedText: null,
153
+ path,
154
+ line,
155
+ body: text,
156
+ };
157
+ }
158
+
159
+ // Category C: Informational rationale question
160
+ if (QUESTION_RE.test(text)) {
161
+ return {
162
+ category: 'C',
163
+ intent: 'INFORMATIONAL_QUESTION',
164
+ actionable: true,
165
+ requiresCodeOrSpecEdit: false,
166
+ suggestedText: null,
167
+ path,
168
+ line,
169
+ body: text,
170
+ };
171
+ }
172
+
173
+ // Conservative Intent Invariant: ambiguous unmatched text defaults to ACTION_REQUIRED
174
+ return {
175
+ category: 'A',
176
+ intent: 'ACTION_REQUIRED',
177
+ actionable: true,
178
+ requiresCodeOrSpecEdit: true,
179
+ suggestedText: null,
180
+ path,
181
+ line,
182
+ body: text,
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Evaluates a full Pull Request payload through Tier 1 filtering + Tier 2 classification.
188
+ * Captures actionable feedback regardless of whether reviewDecision is COMMENTED or CHANGES_REQUESTED.
189
+ */
190
+ export function triagePullRequest(prPayload = {}, { commitMessages = [], agentLogins = DEFAULT_AGENT_LOGINS } = {}) {
191
+ const threads = prPayload.reviewThreads?.nodes || prPayload.reviewThreads || [];
192
+ const unaddressed = filterUnaddressedThreads(threads, { commitMessages, agentLogins });
193
+
194
+ const actionableThreads = [];
195
+ const suggestionThreads = [];
196
+ const questionThreads = [];
197
+ const nonActionableThreads = [];
198
+
199
+ for (const thread of unaddressed) {
200
+ const classification = classifyReviewComment(thread.latestBody, {
201
+ path: thread.path || null,
202
+ line: thread.line ?? thread.originalLine ?? null,
203
+ });
204
+ const item = { ...thread, classification };
205
+ if (classification.intent === 'SUGGESTION_BLOCK') {
206
+ suggestionThreads.push(item);
207
+ } else if (classification.intent === 'ACTION_REQUIRED') {
208
+ actionableThreads.push(item);
209
+ } else if (classification.intent === 'INFORMATIONAL_QUESTION') {
210
+ questionThreads.push(item);
211
+ } else {
212
+ nonActionableThreads.push(item);
213
+ }
214
+ }
215
+
216
+ // Also triage top-level issue/PR discussion comments if provided
217
+ const topComments = [];
218
+ for (const c of (prPayload.issueComments || [])) {
219
+ const login = c?.author?.login ?? c?.author ?? '';
220
+ if (isBotOrSelfAuthor(login, { agentLogins })) continue;
221
+ const cls = classifyReviewComment(c.body);
222
+ if (cls.actionable) {
223
+ topComments.push({ id: c.id, author: login, body: c.body, classification: cls });
224
+ }
225
+ }
226
+
227
+ const reviewDecision = prPayload.reviewDecision || null;
228
+ const hasHumanFeedback = reviewDecision === 'CHANGES_REQUESTED'
229
+ || actionableThreads.length > 0
230
+ || suggestionThreads.length > 0
231
+ || questionThreads.length > 0
232
+ || topComments.some((c) => c.classification.requiresCodeOrSpecEdit);
233
+
234
+ return {
235
+ reviewDecision,
236
+ unaddressedCount: unaddressed.length,
237
+ actionableThreads,
238
+ suggestionThreads,
239
+ questionThreads,
240
+ nonActionableThreads,
241
+ topComments,
242
+ hasHumanFeedback,
243
+ requiresFixCommit: actionableThreads.length > 0 || suggestionThreads.length > 0 || topComments.some((c) => c.classification.requiresCodeOrSpecEdit),
244
+ };
245
+ }
246
+
247
+ /**
248
+ * Applies a Category B GitHub suggestion block to file contents cleanly in memory.
249
+ * Lines are 1-indexed inclusive.
250
+ */
251
+ export function applySuggestionToLines(fileContent, { startLine = null, endLine = null, line = null, suggestedText = '' } = {}) {
252
+ const normalized = String(fileContent ?? '').replace(/\r\n/g, '\n');
253
+ const hadTrailingNewline = normalized.endsWith('\n');
254
+ const lines = normalized.split('\n');
255
+ if (hadTrailingNewline) lines.pop();
256
+
257
+ const start = Number(startLine ?? line ?? 1);
258
+ const end = Number(endLine ?? line ?? start);
259
+ const replacementLines = String(suggestedText ?? '').replace(/\r\n/g, '\n').split('\n');
260
+
261
+ if (start < 1 || end < start || start > lines.length) {
262
+ throw new Error(`Invalid suggestion line range [${start}, ${end}] for file with ${lines.length} lines`);
263
+ }
264
+
265
+ const updated = [
266
+ ...lines.slice(0, start - 1),
267
+ ...replacementLines,
268
+ ...lines.slice(end),
269
+ ];
270
+
271
+ return updated.join('\n') + (hadTrailingNewline ? '\n' : '');
272
+ }
273
+
274
+ /**
275
+ * Tier 3 Resolution Plan:
276
+ * Generates traceable commit trailer, GraphQL reply mutation, and optional thread resolution mutation.
277
+ * Category C informational answers reply without committing or force-resolving the thread.
278
+ */
279
+ export function buildThreadResolutionPlan(triagedThread, { commitSha = null, summary = '', answerBody = null } = {}) {
280
+ const intent = triagedThread?.classification?.intent;
281
+ const threadId = triagedThread.id;
282
+
283
+ if (intent === 'INFORMATIONAL_QUESTION') {
284
+ const replyBody = answerBody || summary || 'Answered in technical explanation above.';
285
+ return {
286
+ threadId,
287
+ commitMessage: null,
288
+ shouldResolve: false,
289
+ replyMutation: {
290
+ query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
291
+ variables: { threadId, body: replyBody },
292
+ },
293
+ resolveMutation: null,
294
+ };
295
+ }
296
+
297
+ const shortSha = commitSha ? String(commitSha).slice(0, 7) : 'HEAD';
298
+ const cleanSummary = summary || 'address PR review feedback';
299
+ const commitMessage = `fix(review): ${cleanSummary} (ref: #${threadId})`;
300
+ const replyBody = `Resolved in commit \`${shortSha}\`: ${cleanSummary}`;
301
+
302
+ return {
303
+ threadId,
304
+ commitMessage,
305
+ shouldResolve: true,
306
+ replyMutation: {
307
+ query: 'mutation ReplyThread($threadId: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) { comment { id } } }',
308
+ variables: { threadId, body: replyBody },
309
+ },
310
+ resolveMutation: {
311
+ query: 'mutation ResolveThread($threadId: ID!) { resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } } }',
312
+ variables: { threadId },
313
+ },
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Enforces the Anti-Thrashing 3-Round Circuit Breaker:
319
+ * If unresolved feedback persists beyond `maxRounds` (default: 3), halts automated mutation,
320
+ * produces a structured synthesis report for Human Tech Lead adjudication, and attaches `asdlc:needs-human-arbitration`.
321
+ */
322
+ export function checkAntiThrashingCircuitBreaker({
323
+ currentRound = 1,
324
+ maxRounds = 3,
325
+ unresolvedThreads = [],
326
+ changeId = 'unknown',
327
+ prNumber = null,
328
+ } = {}) {
329
+ if (currentRound <= maxRounds || unresolvedThreads.length === 0) {
330
+ return {
331
+ tripped: false,
332
+ currentRound,
333
+ maxRounds,
334
+ remainingCount: unresolvedThreads.length,
335
+ };
336
+ }
337
+
338
+ const prLabel = prNumber ? `PR #${prNumber}` : 'Active PR';
339
+ const bullets = unresolvedThreads.map((t, idx) => {
340
+ const loc = t.path ? `\`${t.path}${t.line ? `:${t.line}` : ''}\`` : 'General thread';
341
+ const bodySnippet = String(t.latestBody ?? t.body ?? '').replace(/\s+/g, ' ').slice(0, 140);
342
+ return `${idx + 1}. **${loc}** (thread \`${t.id || 'n/a'}\`, @${t.latestAuthor || 'reviewer'}): "${bodySnippet}"`;
343
+ });
344
+
345
+ const synthesisReport = [
346
+ `## Escalation: Anti-Thrashing Circuit Breaker Tripped (${changeId})`,
347
+ '',
348
+ `- **PR**: ${prLabel}`,
349
+ `- **Automated Rounds Attempted**: ${maxRounds} (Round ${currentRound} exceeded cap)`,
350
+ `- **Status**: \`PAUSED_NEEDS_HUMAN_ARBITRATION\``,
351
+ `- **Label Applied**: \`asdlc:needs-human-arbitration\``,
352
+ '',
353
+ '### Remaining Unresolved Review Threads',
354
+ ...bullets,
355
+ '',
356
+ '> Automated edits have paused to prevent infinite feedback loops. Please review the remaining items above and post your adjudication.',
357
+ '',
358
+ ].join('\n');
359
+
360
+ return {
361
+ tripped: true,
362
+ exitCode: 2,
363
+ label: 'asdlc:needs-human-arbitration',
364
+ status: 'PAUSED_NEEDS_HUMAN_ARBITRATION',
365
+ currentRound,
366
+ maxRounds,
367
+ synthesisReport,
368
+ };
369
+ }
@@ -1,80 +0,0 @@
1
- ---
2
- name: asdlc-review
3
- description: "Independent fresh-context spec review helper. Primary reviews run via asdlc-spec-review and asdlc-impl-review agent sessions."
4
- ---
5
-
6
- # /asdlc:review - Independent Spec Review Helper
7
-
8
- > [!NOTE]
9
- > **Independent Agent Session Review**:
10
- > Spec and implementation reviews are executed by dedicated **Independent Review Agent Sessions** (`asdlc-spec-review` and `asdlc-impl-review`) adhering to the **Player ≠ Referee** principle.
11
- > This skill (`asdlc-review`) is retained as a local fresh-context dry-run helper to inspect changes and generate or preview `review.md`.
12
-
13
- When invoked, it switches into the **Independent Reviewer** role (Player ≠ Referee). The reviewer MUST NOT be the authoring agent of the change.
14
-
15
- ---
16
-
17
- ## Review Dimensions
18
-
19
- Every change is evaluated along six core dimensions:
20
-
21
- 1. **Completeness**: Are all user journeys covered? Are edge cases, error conditions, and nil/empty inputs handled?
22
- 2. **Ambiguity**: Are requirements clear and unambiguous? Does each use strict normative language (`SHALL` / `MUST`) rather than passive voice?
23
- 3. **Cross-repo consistency**: Does this change break or impact cross-repo API/event contracts? If so, is a System Design Amendment required?
24
- 4. **Contract impact**: Are breaking changes flagged with `**BREAKING**` in `proposal.md`? Are backwards compatibility guarantees documented?
25
- 5. **Testability**: Does every requirement have verifiable Acceptance Criteria (`AC<n>`) with concrete test paths?
26
- 6. **Security**: Are authentication, authorization, input validation, secret hygiene, and data privacy respected?
27
-
28
- ---
29
-
30
- ## Workflow Sequence
31
-
32
- ### Step 1: Read Change Context (Read-Only)
33
- Inspect all intent files under `openspec/changes/<CHANGE_ID>/`:
34
- - `proposal.md`
35
- - `specs/**/*.md`
36
- - `explore.md`
37
-
38
- ### Step 2: Formulate Findings
39
- Categorize findings by severity:
40
- - **Blocker**: Spec violation, missing acceptance criteria, untestable assertion, or security risk.
41
- - **Major**: Ambiguous scenario, missing `**GIVEN**`, or unaddressed edge cases.
42
- - **Minor / Advisory**: Documentation clarity, style suggestions.
43
-
44
- ### Step 3: Author `review.md`
45
- Write `openspec/changes/<CHANGE_ID>/review.md` with the following structure:
46
-
47
- ```markdown
48
- # Review: <CHANGE_ID>
49
-
50
- ## Summary
51
- <2-3 sentences summarizing the change and the evaluation outcome>
52
-
53
- ## Dimensions Evaluation
54
- - Completeness: PASS | CONCERN | FAIL
55
- - Ambiguity: PASS | CONCERN | FAIL
56
- - Cross-repo consistency: PASS | CONCERN | FAIL
57
- - Contract impact: PASS | CONCERN | FAIL
58
- - Testability: PASS | CONCERN | FAIL
59
- - Security: PASS | CONCERN | FAIL
60
-
61
- ## Requirement -> Implementation -> Test Traceability
62
- | Requirement | Acceptance Criteria | Target Test | Status |
63
- |---|---|---|---|
64
- | Req 1 | AC1: ... | test/foo.test.js | VERIFIED |
65
-
66
- ## Blocking Findings
67
- (none)
68
- <!-- Or list: 1. [Blocker] <description> -->
69
-
70
- ## Advisory Notes
71
- <Optional recommendations>
72
-
73
- ## Verdict
74
- APPROVE
75
- <!-- Or: NEEDS_REVISION -->
76
- ```
77
-
78
- ### Step 4: Next Steps
79
- - If verdict is `APPROVE`: Guide the author to run `/asdlc:lint <CHANGE_ID>` and submit the Spec PR.
80
- - If verdict is `NEEDS_REVISION`: List blocking items that the spec author must address.