-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlabeling.agent.js
More file actions
594 lines (553 loc) · 16.8 KB
/
labeling.agent.js
File metadata and controls
594 lines (553 loc) · 16.8 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
* Unified Labeling Agent for LightSpeedWP
* Applies, enforces, and standardizes labels on issues and PRs.
* Includes content-based issue type detection, branch pattern matching, and file path analysis.
* Uses canonical config from .github/labels.yml, .github/labeler.yml, .github/issue-types.yml.
* Replaces all prior split agents.
*
* @module scripts/agents/labeling.agent.js
* @see .github/agents/labeling.agent.md
* @version 2.0.0
* @author LightSpeedWP
*/
import fs from "fs";
import yaml from "js-yaml";
import core from "@actions/core";
import github from "@actions/github";
import {
fetchCanonicalLabels,
buildLabelAliasMap,
findStandardLabel,
} from "./includes/label-lookup.js";
import {
enforceOneHotLabels,
applyDefaultStatus,
applyDefaultPriority,
applyDefaultType,
} from "./includes/status-enforcer.js";
import {
fetchLabelerRules,
applyLabelerRules,
} from "./includes/labeler-utils.js";
import {
buildLabelingReport,
formatErrors,
} from "./includes/label-reporting.js";
// Environment configurable paths (fallback to repo defaults)
const LABELS_CONFIG = process.env.LABELS_CONFIG || ".github/labels.yml";
const ISSUE_TYPES_CONFIG =
process.env.ISSUE_TYPES_CONFIG || ".github/issue-types.yml";
const LABELER_RULES = process.env.LABELER_RULES || ".github/labeler.yml";
// Enhanced content-based type detection heuristics
const KEYWORD_TYPE_MAP = {
bug: "type:bug",
fix: "type:bug",
"fixes #": "type:bug",
"closes #": "type:bug",
defect: "type:bug",
error: "type:bug",
issue: "type:bug",
feature: "type:feature",
feat: "type:feature",
enhancement: "type:feature",
"new feature": "type:feature",
improvement: "type:feature",
docs: "type:documentation",
doc: "type:documentation",
documentation: "type:documentation",
readme: "type:documentation",
guide: "type:documentation",
test: "type:test",
testing: "type:test",
"unit test": "type:test",
"integration test": "type:test",
perf: "type:performance",
performance: "type:performance",
optimization: "type:performance",
optimize: "type:performance",
security: "type:security",
vulnerability: "type:security",
cve: "type:security",
refactor: "type:refactor",
refactoring: "type:refactor",
restructure: "type:refactor",
chore: "type:chore",
maintenance: "type:chore",
cleanup: "type:chore",
dependencies: "type:dependencies",
dependency: "type:dependencies",
"bump version": "type:dependencies",
ci: "type:ci",
"continuous integration": "type:ci",
workflow: "type:ci",
a11y: "type:accessibility",
accessibility: "type:accessibility",
wcag: "type:accessibility",
};
// Branch prefix to type mapping for PRs
const BRANCH_PREFIX_TYPE_MAP = {
"feat/": "type:feature",
"feature/": "type:feature",
"fix/": "type:bug",
"bugfix/": "type:bug",
"hotfix/": "type:bug",
"docs/": "type:documentation",
"doc/": "type:documentation",
"test/": "type:test",
"tests/": "type:test",
"perf/": "type:performance",
"refactor/": "type:refactor",
"chore/": "type:chore",
"ci/": "type:ci",
"deps/": "type:dependencies",
"security/": "type:security",
"a11y/": "type:accessibility",
};
function readYamlArrayFile(path, purpose) {
if (!fs.existsSync(path)) {
throw new Error(`[labeling.agent] Missing ${purpose} file at: ${path}`);
}
const raw = fs.readFileSync(path, "utf8");
const data = yaml.load(raw);
if (!Array.isArray(data)) {
throw new Error(
`[labeling.agent] Expected array in ${purpose} file: ${path}`,
);
}
return data;
}
/**
* Loads canonical label definitions from LABELS_CONFIG.
* @returns {Set<string>} Set of canonical label names.
*/
function loadCanonicalLabels() {
const labelsData = readYamlArrayFile(LABELS_CONFIG, "labels config");
return new Set(labelsData.map((l) => (typeof l === "string" ? l : l.name)));
}
/**
* Loads alias mapping from LABELS_CONFIG.
* @returns {Object} aliasMap - Maps alias to canonical label.
*/
function loadAliasMap() {
const labelsData = readYamlArrayFile(LABELS_CONFIG, "labels config");
return buildLabelAliasMap(labelsData);
}
/**
* Detect issue type from branch name using prefix patterns
* @param {string} branchName - Branch name to analyze
* @returns {string|null} Canonical type label or null if none matched
*/
function detectTypeFromBranch(branchName = "") {
if (!branchName) return null;
const lowerBranch = branchName.toLowerCase();
for (const [prefix, typeLabel] of Object.entries(BRANCH_PREFIX_TYPE_MAP)) {
if (lowerBranch.startsWith(prefix)) {
core.info(
`[labeling.agent] Detected type from branch prefix '${prefix}': ${typeLabel}`,
);
return typeLabel;
}
}
return null;
}
/**
* Detect issue type from content (title + body) using keyword heuristics
* Enhanced with priority ordering - checks title first for higher confidence
* @param {string} title - Issue/PR title
* @param {string} body - Issue/PR body
* @returns {string|null} Canonical type label or null if none matched
*/
function detectIssueTypeFromContent(title = "", body = "") {
// Check title first (higher confidence)
const lowerTitle = title.toLowerCase();
for (const [keyword, typeLabel] of Object.entries(KEYWORD_TYPE_MAP)) {
if (lowerTitle.includes(keyword.toLowerCase())) {
core.info(
`[labeling.agent] Detected type from title keyword '${keyword}': ${typeLabel}`,
);
return typeLabel;
}
}
// Check body if no match in title
const lowerBody = body.toLowerCase();
for (const [keyword, typeLabel] of Object.entries(KEYWORD_TYPE_MAP)) {
if (lowerBody.includes(keyword.toLowerCase())) {
core.info(
`[labeling.agent] Detected type from body keyword '${keyword}': ${typeLabel}`,
);
return typeLabel;
}
}
return null;
}
/**
* Removes or migrates any label on an issue/PR that is not in the canonical set.
* @param {Object} github - Octokit instance.
* @param {string} owner
* @param {string} repo
* @param {number} number - Issue/PR number.
* @param {string[]} currentLabels
* @param {Set<string>} canonicalSet
* @param {Object} aliasMap
* @param {boolean} dryRun
* @param {function} log
*/
async function standardizeLabelsOnItem(
github,
owner,
repo,
number,
currentLabels,
canonicalSet,
aliasMap = {},
dryRun = false,
log = console.log,
) {
for (const label of currentLabels) {
if (!canonicalSet.has(label)) {
// Migrate legacy/alias to canonical
const canonical = findStandardLabel(label, aliasMap, canonicalSet);
if (canonical) {
if (!dryRun) {
await github.rest.issues.addLabels({
owner,
repo,
issue_number: number,
labels: [canonical],
});
}
log(
`[labeling.agent] Migrated: ${label} -> ${canonical} on #${number}`,
);
}
// Remove non-canonical label
if (!dryRun) {
await github.rest.issues.removeLabel({
owner,
repo,
issue_number: number,
name: label,
});
}
log(
`[labeling.agent] Removed non-canonical label: ${label} from #${number}`,
);
}
}
}
/**
* Main orchestrator for labeling agent with comprehensive error handling
* @param {Object} opts - Configuration options
* @param {Object} [opts.context=github.context] - GitHub context
* @param {Object} [opts.github] - Octokit instance
* @param {boolean} [opts.dryRun=false] - Dry run mode
* @param {number} [opts.maxRetries=3] - Maximum retry attempts for API calls
* @returns {Promise<Object>} Report object with summary of actions taken
*/
async function runLabelingAgent(opts = {}) {
const startTime = Date.now();
const report = {
success: false,
added: [],
removed: [],
migrated: [],
errors: [],
rulesApplied: [],
duration: 0,
};
try {
// Initialize context and GitHub client
const context = opts.context || github.context;
const octokit =
opts.github ||
github.getOctokit(
core.getInput("github-token") || process.env.GITHUB_TOKEN,
);
const dryRun = !!opts.dryRun;
const maxRetries = opts.maxRetries || 3;
const owner = context.repo.owner;
const repo = context.repo.repo;
const isPR = !!context.payload.pull_request;
const isIssue = !!context.payload.issue;
const number = isIssue
? context.payload.issue.number
: isPR
? context.payload.pull_request.number
: null;
if (!number) {
core.info("[labeling.agent] No issue or PR in context");
report.success = true;
report.duration = Date.now() - startTime;
return report;
}
core.info(
`[labeling.agent] Processing ${isPR ? "PR" : "Issue"} #${number}`,
);
if (dryRun) {
core.info("[labeling.agent] Running in DRY RUN mode");
}
// Load canonical configurations with error handling
let canonicalSet, aliasMap, labelerRules;
try {
core.startGroup("Loading canonical configurations");
canonicalSet = loadCanonicalLabels();
core.info(
`[labeling.agent] Loaded ${canonicalSet.size} canonical labels`,
);
aliasMap = loadAliasMap();
core.info(
`[labeling.agent] Loaded ${Object.keys(aliasMap).length} label aliases`,
);
labelerRules = fetchLabelerRules(LABELER_RULES);
core.info(
`[labeling.agent] Loaded ${Object.keys(labelerRules).length} labeler rules`,
);
core.endGroup();
} catch (error) {
core.error(
`[labeling.agent] Configuration loading failed: ${error.message}`,
);
core.endGroup();
report.errors.push(`Configuration error: ${error.message}`);
core.setFailed(error.message);
report.duration = Date.now() - startTime;
return report;
}
// Get current labels
const currentLabels = isIssue
? (context.payload.issue.labels || []).map((l) => l.name)
: (context.payload.pull_request.labels || []).map((l) => l.name);
core.info(
`[labeling.agent] Current labels (${currentLabels.length}): ${currentLabels.join(", ") || "none"}`,
);
// Step 1: Apply labeler rules (branch patterns and file changes)
try {
core.startGroup("Applying labeler rules");
const appliedFromRules = await applyLabelerRules({
github: octokit,
context,
labelerRules,
currentLabels,
dryRun,
maxRetries,
});
if (appliedFromRules.length > 0) {
report.added.push(...appliedFromRules);
report.rulesApplied.push(
`File/branch patterns matched: ${appliedFromRules.join(", ")}`,
);
}
core.endGroup();
} catch (error) {
core.warning(
`[labeling.agent] Labeler rules application failed: ${error.message}`,
);
report.errors.push(`Labeler rules error: ${error.message}`);
core.endGroup();
}
// Step 2: Detect type from branch prefix (for PRs)
if (isPR) {
try {
const branchName = context.payload.pull_request.head.ref;
const branchType = detectTypeFromBranch(branchName);
if (branchType && !currentLabels.includes(branchType)) {
if (!dryRun) {
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: number,
labels: [branchType],
});
}
report.added.push(branchType);
report.rulesApplied.push(`Branch prefix detection: ${branchType}`);
}
} catch (error) {
core.warning(
`[labeling.agent] Branch type detection failed: ${error.message}`,
);
report.errors.push(`Branch detection error: ${error.message}`);
}
}
// Step 3: Enforce one-hot constraints (status, priority, type)
try {
core.startGroup("Enforcing one-hot label constraints");
await enforceOneHotLabels({
github: octokit,
owner,
repo,
number,
currentLabels,
dryRun,
});
core.endGroup();
} catch (error) {
core.warning(
`[labeling.agent] One-hot enforcement failed: ${error.message}`,
);
report.errors.push(`One-hot enforcement error: ${error.message}`);
core.endGroup();
}
// Step 4: Apply defaults for missing required labels
try {
core.startGroup("Applying default labels");
await applyDefaultStatus({
github: octokit,
owner,
repo,
number,
currentLabels,
dryRun,
isPR,
});
await applyDefaultPriority({
github: octokit,
owner,
repo,
number,
currentLabels,
dryRun,
});
await applyDefaultType({
github: octokit,
owner,
repo,
number,
currentLabels,
dryRun,
isPR,
});
core.endGroup();
} catch (error) {
core.warning(
`[labeling.agent] Default label application failed: ${error.message}`,
);
report.errors.push(`Default labels error: ${error.message}`);
core.endGroup();
}
// Step 5: Content-based type detection (if no type label yet)
const hasTypeLabel = currentLabels.some((l) => l.startsWith("type:"));
if (!hasTypeLabel) {
try {
const title = isIssue
? context.payload.issue.title
: context.payload.pull_request.title;
const body = isIssue
? context.payload.issue.body
: context.payload.pull_request.body;
const detectedType = detectIssueTypeFromContent(title, body);
if (detectedType) {
if (!dryRun) {
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: number,
labels: [detectedType],
});
}
report.added.push(detectedType);
report.rulesApplied.push(
`Content-based type detection: ${detectedType}`,
);
}
} catch (error) {
core.warning(
`[labeling.agent] Content type detection failed: ${error.message}`,
);
report.errors.push(`Content detection error: ${error.message}`);
}
}
// Step 6: Changelog nudge for PRs
if (isPR) {
try {
const changelogLabels = [
"meta:no-changelog",
"meta:needs-changelog",
"meta:changelog",
];
if (!currentLabels.some((l) => changelogLabels.includes(l))) {
if (!dryRun) {
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: number,
labels: ["meta:needs-changelog"],
});
}
report.added.push("meta:needs-changelog");
core.info("[labeling.agent] Added meta:needs-changelog");
}
} catch (error) {
core.warning(
`[labeling.agent] Changelog label application failed: ${error.message}`,
);
report.errors.push(`Changelog label error: ${error.message}`);
}
}
// Step 7: Standardize/migrate non-canonical labels
try {
core.startGroup("Standardizing labels");
await standardizeLabelsOnItem(
octokit,
owner,
repo,
number,
currentLabels,
canonicalSet,
aliasMap,
dryRun,
core.info,
);
core.endGroup();
} catch (error) {
core.warning(
`[labeling.agent] Label standardization failed: ${error.message}`,
);
report.errors.push(`Standardization error: ${error.message}`);
core.endGroup();
}
// Generate summary report
report.success = true;
report.duration = Date.now() - startTime;
core.info(
`[labeling.agent] Completed in ${report.duration}ms (DRY_RUN=${dryRun})`,
);
core.info(
`[labeling.agent] Summary: ${report.added.length} added, ${report.removed.length} removed, ${report.migrated.length} migrated, ${report.errors.length} errors`,
);
// Output structured report
const summaryReport = buildLabelingReport({
added: report.added,
removed: report.removed,
migrated: report.migrated,
rulesApplied: report.rulesApplied,
errors: report.errors,
context,
});
core.summary.addRaw(summaryReport).write();
return report;
} catch (error) {
core.error(`[labeling.agent] Fatal error: ${error.message}`);
core.error(error.stack);
report.errors.push(`Fatal error: ${error.message}`);
report.duration = Date.now() - startTime;
core.setFailed(error.message);
return report;
}
}
// Check if this module is being run directly
if (import.meta.url === `file://${process.argv[1]}`) {
runLabelingAgent().catch((error) => {
core.error(`[labeling.agent] Unhandled error: ${error.message}`);
core.error(error.stack);
core.setFailed(error.message);
process.exit(1);
});
}
export {
runLabelingAgent,
detectIssueTypeFromContent,
detectTypeFromBranch,
loadCanonicalLabels,
loadAliasMap,
};