Repository navigation
369 lines (321 loc) · 16.1 KB
/
Copy pathsquad-triage.yml
File metadata and controls
369 lines (321 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
name: Squad Triage
on:
issues:
types: [labeled]
permissions:
issues: write
contents: read
actions: write
# CI Hardening Phase 3 item A1: Prevent parallel runs from competing for resources
concurrency:
group: ${{ github.workflow }}-${{ github.event.issue.number || github.ref }}
cancel-in-progress: true
jobs:
triage:
if: github.event.label.name == 'squad'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7
# CI Hardening: GitHub API rate limit monitoring (item 9)
# Triage makes multiple API calls (list issues, add labels, create comments).
- name: "📊 Check GitHub API rate limit"
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 #v9
with:
script: |
const { data: rateLimit } = await github.rest.rateLimit.get();
const { remaining, limit, reset } = rateLimit.rate;
// Security: mask numeric values to prevent fingerprinting via CI logs
core.setSecret(String(remaining));
core.setSecret(String(limit));
const resetDate = new Date(reset * 1000).toISOString();
if (remaining < 10) {
core.setFailed(`❌ Rate limit: CRITICAL — below minimum threshold. Aborting to prevent silent failures.`);
} else if (remaining < 100) {
core.warning(`⚠️ Rate limit: WARNING — below safe threshold (resets ${resetDate})`);
} else {
core.info(`✅ Rate limit: OK — above safe threshold (resets ${resetDate})`);
}
- name: Triage issue via deterministic keyword routing
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 #v9
with:
script: |
const fs = require('fs');
const issue = context.payload.issue;
// Read team roster — check .squad/ first, fall back to .ai-team/
let teamFile = '.squad/team.md';
if (!fs.existsSync(teamFile)) {
teamFile = '.ai-team/team.md';
}
if (!fs.existsSync(teamFile)) {
core.warning('No .squad/team.md or .ai-team/team.md found — cannot triage');
return;
}
const content = fs.readFileSync(teamFile, 'utf8');
const lines = content.split('\n');
if (issue.labels.some(label => /^squad:.+/.test(label.name))) {
core.info(`Issue #${issue.number} already has a squad member label — skipping conflicting triage.`);
return;
}
const autoAssign = /<!--\s*copilot-auto-assign:\s*true\s*-->/i.test(content);
// Check if @copilot is on the team
const hasCopilot = content.includes('🤖 Coding Agent');
// Parse @copilot capability profile
let goodFitKeywords = [];
let needsReviewKeywords = [];
let notSuitableKeywords = [];
if (hasCopilot) {
// Extract capability tiers from team.md
const goodFitMatch = content.match(/🟢\s*Good fit[^:]*:\s*(.+)/i);
const needsReviewMatch = content.match(/🟡\s*Needs review[^:]*:\s*(.+)/i);
const notSuitableMatch = content.match(/🔴\s*Not suitable[^:]*:\s*(.+)/i);
if (goodFitMatch) {
goodFitKeywords = goodFitMatch[1].toLowerCase().split(',').map(s => s.trim());
} else {
goodFitKeywords = ['bug fix', 'test coverage', 'lint', 'format', 'dependency update', 'small feature', 'scaffolding', 'doc fix', 'documentation'];
}
if (needsReviewMatch) {
needsReviewKeywords = needsReviewMatch[1].toLowerCase().split(',').map(s => s.trim());
} else {
needsReviewKeywords = ['medium feature', 'refactoring', 'api endpoint', 'migration'];
}
if (notSuitableMatch) {
notSuitableKeywords = notSuitableMatch[1].toLowerCase().split(',').map(s => s.trim());
} else {
notSuitableKeywords = ['architecture', 'system design', 'security', 'auth', 'encryption', 'performance'];
}
}
const members = [];
let inMembersTable = false;
for (const line of lines) {
if (line.match(/^##\s+(Members|Team Roster)/i)) {
inMembersTable = true;
continue;
}
if (inMembersTable && line.startsWith('## ')) {
break;
}
if (inMembersTable && line.startsWith('|') && !line.includes('---') && !line.includes('Name')) {
const cells = line.split('|').map(c => c.trim()).filter(Boolean);
if (cells.length >= 2 && cells[0] !== 'Scribe') {
members.push({
name: cells[0],
role: cells[1]
});
}
}
}
// Read routing rules — check .squad/ first, fall back to .ai-team/
let routingFile = '.squad/routing.md';
if (!fs.existsSync(routingFile)) {
routingFile = '.ai-team/routing.md';
}
let routingContent = '';
if (fs.existsSync(routingFile)) {
routingContent = fs.readFileSync(routingFile, 'utf8');
}
function findLead(teamMembers) {
const hasRoleToken = (member, token) => {
const roleWords = member.role.toLowerCase().match(/[a-z0-9]+/g) || [];
return roleWords.includes(token);
};
return teamMembers.find(member => hasRoleToken(member, 'lead')) ||
teamMembers.find(member => hasRoleToken(member, 'architect'));
}
function slugify(t) { return t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); }
function tableCells(line) {
const cells = line.trim().split('|');
if (cells[0] === '') cells.shift();
if (cells[cells.length - 1] === '') cells.pop();
return cells.map(cell => cell.trim());
}
function normalizeRouteDestination(value) {
return value
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
.replace(/[*_`]/g, '')
.replace(/\p{Extended_Pictographic}/gu, '')
.replace(/[\u200d\ufe0f]/g, '')
.trim()
.toLowerCase()
.replace(/\s+/g, ' ');
}
function routingRules(markdown, teamMembers) {
const routingLines = markdown.split('\n');
const rules = [];
for (let index = 0; index < routingLines.length; index++) {
const line = routingLines[index];
if (!line.trim().startsWith('|')) continue;
const headers = tableCells(line).map(cell => cell.toLowerCase());
const workTypeIndex = headers.indexOf('work type');
const routeIndex = headers.findIndex(header =>
header === 'route to' ||
header === 'agent' ||
header === 'primary' ||
header === 'primary agent'
);
const examplesIndex = headers.indexOf('examples');
if (workTypeIndex < 0 || routeIndex < 0) continue;
for (let rowIndex = index + 2; rowIndex < routingLines.length; rowIndex++) {
const row = routingLines[rowIndex];
if (!row.trim().startsWith('|')) break;
const cells = tableCells(row);
const workType = cells[workTypeIndex] || '';
const routeCell = cells[routeIndex] || '';
const examples = examplesIndex >= 0 ? (cells[examplesIndex] || '') : '';
if (!workType || !routeCell) continue;
const destinationName = normalizeRouteDestination(routeCell);
const member = teamMembers.find(candidate =>
normalizeRouteDestination(candidate.name) === destinationName
);
if (member) rules.push({ member, workType, examples });
}
break;
}
return rules;
}
function routeScore(issueText, rule) {
const genericWorkTypeTokens = new Set([
'agent', 'engineer', 'engineering', 'management', 'owner',
'specialist', 'system', 'work',
]);
function tokens(value) {
return value.toLowerCase().match(/[a-z0-9]+(?:[+#.][a-z0-9+#.]*)?(?<!\.)/g) || [];
}
function containsPhrase(haystack, needle) {
if (needle.length === 0 || needle.length > haystack.length) return false;
return haystack.some((_, index) =>
needle.every((token, offset) => haystack[index + offset] === token)
);
}
const issueTokens = tokens(issueText);
const workTypeTokens = tokens(rule.workType)
.filter(token => !genericWorkTypeTokens.has(token));
const rawPhrases = [rule.workType, ...workTypeTokens, ...rule.examples.split(/[,;]+/)]
.flatMap(phrase => phrase.includes('/') ? [phrase, ...phrase.split('/')] : [phrase]);
return rawPhrases.reduce((best, phrase) => {
const phraseTokens = tokens(phrase);
if (!containsPhrase(issueTokens, phraseTokens)) return best;
const specificity = phraseTokens.length * 100;
return Math.max(best, specificity);
}, 0);
}
function selectRoutingAssignment(issueText, routingContent, teamMembers, lead) {
const scoredRoutes = routingRules(routingContent, teamMembers)
.map(rule => ({ rule, score: routeScore(issueText, rule) }))
.filter(candidate => candidate.score > 0)
.sort((left, right) => right.score - left.score);
if (scoredRoutes.length === 0) {
return { member: lead, workType: null };
}
const bestScore = scoredRoutes[0].score;
const bestRoutes = scoredRoutes.filter(candidate => candidate.score === bestScore);
const bestMembers = new Set(bestRoutes.map(candidate =>
normalizeRouteDestination(candidate.rule.member.name)
));
if (bestMembers.size !== 1) {
return { member: lead, workType: null };
}
const best = bestRoutes[0];
return { member: best.rule.member, workType: best.rule.workType };
}
const lead = findLead(members);
if (!lead) {
core.warning('No Lead role found in team roster — cannot triage');
return;
}
// Build triage context
const memberList = members.map(m =>
`- **${m.name}** (${m.role}) → label: \`squad:${slugify(m.name)}\``
).join('\n');
// Determine best assignee based on issue content and routing
const issueText = `${issue.title}\n${issue.body || ''}`.toLowerCase();
let assignedMember = null;
let triageReason = '';
let copilotTier = null;
// First, evaluate @copilot fit if enabled
if (hasCopilot) {
const isNotSuitable = notSuitableKeywords.some(kw => issueText.includes(kw));
const isGoodFit = !isNotSuitable && goodFitKeywords.some(kw => issueText.includes(kw));
const isNeedsReview = !isNotSuitable && !isGoodFit && needsReviewKeywords.some(kw => issueText.includes(kw));
if (isGoodFit) {
copilotTier = 'good-fit';
assignedMember = { name: '@copilot', role: 'Coding Agent' };
triageReason = '🟢 Good fit for @copilot — matches capability profile';
} else if (isNeedsReview) {
copilotTier = 'needs-review';
assignedMember = { name: '@copilot', role: 'Coding Agent' };
triageReason = '🟡 Routing to @copilot (needs review) — a squad member should review the PR';
} else if (isNotSuitable) {
copilotTier = 'not-suitable';
// Fall through to normal routing
}
}
// If not routed to @copilot, score the repository's current routing table.
if (!assignedMember) {
const assignment = selectRoutingAssignment(issueText, routingContent, members, lead);
assignedMember = assignment.member;
triageReason = assignment.workType
? `Matched routing rule "${assignment.workType}"`
: 'No specific domain match — assigned to Lead for further analysis';
}
const isCopilot = assignedMember.name === '@copilot';
const assignLabel = isCopilot ? 'squad:copilot' : `squad:${slugify(assignedMember.name)}`;
// Add the member-specific label
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: [assignLabel]
});
// Apply default triage verdict
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: ['go:needs-research']
});
// Labels route work; only squad-issue-assign.yml assigns Copilot.
// Build copilot evaluation note
let copilotNote = '';
if (hasCopilot && !isCopilot) {
if (copilotTier === 'not-suitable') {
copilotNote = `\n\n**@copilot evaluation:** 🔴 Not suitable — issue involves work outside the coding agent's capability profile.`;
} else {
copilotNote = `\n\n**@copilot evaluation:** No strong capability match — routed to squad member.`;
}
}
// Post triage comment
const comment = [
`### 🏗️ Squad Triage — Automated keyword routing`,
'',
`**Provenance:** Deterministic keyword matching against the capability profile in \`.squad/team.md\` and rules in \`.squad/routing.md\`; no Lead-agent analysis was performed.`,
`**Issue:** #${issue.number} — ${issue.title}`,
`**Assigned to:** ${assignedMember.name} (${assignedMember.role})`,
`**Reason:** ${triageReason}`,
copilotTier === 'needs-review' ? `\n⚠️ **PR review recommended** — a squad member should review @copilot's work on this one.` : '',
copilotNote,
'',
`---`,
'',
`**Team roster:**`,
memberList,
hasCopilot ? `- **@copilot** (Coding Agent) → label: \`squad:copilot\`` : '',
'',
`> To reassign, remove the current \`squad:*\` label and add the correct one.`,
].filter(Boolean).join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: comment
});
core.info(`Triaged issue #${issue.number} → ${assignedMember.name} (${assignLabel})`);
if (isCopilot && autoAssign) {
await github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'squad-issue-assign.yml',
ref: context.payload.repository.default_branch,
inputs: { issue_number: String(issue.number) }
});
core.info(`Dispatched squad-issue-assign.yml for auto-assigned issue #${issue.number}`);
}