@bbcsoftwarefactory/cli 0.1.0 → 1.1.2
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.
- package/dist/audit-ledger.d.ts +2 -0
- package/dist/audit-ledger.js +71 -0
- package/dist/bbc-install.d.ts +2 -0
- package/dist/bbc-install.js +1250 -0
- package/dist/bbc.d.ts +2 -0
- package/dist/bbc.js +124 -0
- package/dist/bigo/complexity.d.ts +18 -0
- package/dist/bigo/complexity.js +139 -0
- package/dist/bigo/functions.d.ts +5 -0
- package/dist/bigo/functions.js +174 -0
- package/dist/bigo/keywords.d.ts +1 -0
- package/dist/bigo/keywords.js +43 -0
- package/dist/bigo/lexical.d.ts +14 -0
- package/dist/bigo/lexical.js +69 -0
- package/dist/bigo/source-files.d.ts +1 -0
- package/dist/bigo/source-files.js +80 -0
- package/dist/change-lane/classification.d.ts +41 -0
- package/dist/change-lane/classification.js +104 -0
- package/dist/change-lane/git.d.ts +8 -0
- package/dist/change-lane/git.js +105 -0
- package/dist/check-issue-claim.d.ts +2 -0
- package/dist/check-issue-claim.js +146 -0
- package/dist/check-worktree-guard.d.ts +2 -0
- package/dist/check-worktree-guard.js +114 -0
- package/dist/classify-change-lane.d.ts +2 -0
- package/dist/classify-change-lane.js +128 -0
- package/dist/diff-scope/git-diff.d.ts +25 -0
- package/dist/diff-scope/git-diff.js +146 -0
- package/dist/error-scan.d.ts +3 -0
- package/dist/error-scan.js +216 -0
- package/dist/export-public.d.ts +9 -0
- package/dist/export-public.js +274 -0
- package/dist/extract-diff-scope.d.ts +2 -0
- package/dist/extract-diff-scope.js +111 -0
- package/dist/fetch-issue-attachments.d.ts +22 -0
- package/dist/fetch-issue-attachments.js +325 -0
- package/dist/issue-claim/evaluation.d.ts +66 -0
- package/dist/issue-claim/evaluation.js +259 -0
- package/dist/issue-claim/loaders.d.ts +5 -0
- package/dist/issue-claim/loaders.js +116 -0
- package/dist/list-zed-commands.d.ts +7 -0
- package/dist/list-zed-commands.js +288 -0
- package/dist/measure-bigo.d.ts +2 -0
- package/dist/measure-bigo.js +84 -0
- package/dist/plan-issue-triage.d.ts +3 -0
- package/dist/plan-issue-triage.js +404 -0
- package/dist/question-gate/ledger.d.ts +5 -0
- package/dist/question-gate/ledger.js +115 -0
- package/dist/question-gate/rules.d.ts +40 -0
- package/dist/question-gate/rules.js +483 -0
- package/dist/recap/board.d.ts +5 -0
- package/dist/recap/board.js +384 -0
- package/dist/recap/git-and-github.d.ts +11 -0
- package/dist/recap/git-and-github.js +620 -0
- package/dist/recap/report-and-hud.d.ts +2 -0
- package/dist/recap/report-and-hud.js +294 -0
- package/dist/recap/time-and-refs.d.ts +27 -0
- package/dist/recap/time-and-refs.js +148 -0
- package/dist/recap.d.ts +2 -0
- package/dist/recap.js +217 -0
- package/dist/render-workflow.d.ts +2 -0
- package/dist/render-workflow.js +142 -0
- package/dist/resolve-containers.d.ts +2 -0
- package/dist/resolve-containers.js +96 -0
- package/dist/review-loop.d.ts +7 -0
- package/dist/review-loop.js +622 -0
- package/dist/save-counts.d.ts +2 -0
- package/dist/save-counts.js +191 -0
- package/dist/summarize-logs.d.ts +2 -0
- package/dist/summarize-logs.js +41 -0
- package/dist/sweep-github.d.ts +10 -0
- package/dist/sweep-github.js +453 -0
- package/dist/sweep-issues.d.ts +56 -0
- package/dist/sweep-issues.js +650 -0
- package/dist/sweep.d.ts +2 -0
- package/dist/sweep.js +301 -0
- package/dist/triage-question.d.ts +2 -0
- package/dist/triage-question.js +189 -0
- package/dist/validate-skills.d.ts +2 -0
- package/dist/validate-skills.js +48 -0
- package/dist/watch-live.d.ts +7 -0
- package/dist/watch-live.js +83 -0
- package/dist/watcher/config.d.ts +11 -0
- package/dist/watcher/config.js +265 -0
- package/dist/watcher/live-classifier.d.ts +52 -0
- package/dist/watcher/live-classifier.js +510 -0
- package/dist/watcher/safe-fs.d.ts +9 -0
- package/dist/watcher/safe-fs.js +159 -0
- package/dist/watcher/stream.d.ts +27 -0
- package/dist/watcher/stream.js +340 -0
- package/dist/watcher/summarizer.d.ts +19 -0
- package/dist/watcher/summarizer.js +121 -0
- package/dist/wave3/process.d.ts +14 -0
- package/dist/wave3/process.js +84 -0
- package/dist/wave4/process.d.ts +14 -0
- package/dist/wave4/process.js +128 -0
- package/dist/workflow/render.d.ts +13 -0
- package/dist/workflow/render.js +31 -0
- package/dist/workflow/schema.d.ts +25 -0
- package/dist/workflow/schema.js +99 -0
- package/dist/workflow-auditor/audit.d.ts +27 -0
- package/dist/workflow-auditor/audit.js +583 -0
- package/dist/workflow-auditor/ledger-io.d.ts +5 -0
- package/dist/workflow-auditor/ledger-io.js +99 -0
- package/dist/workflow-auditor/skills-validator.d.ts +10 -0
- package/dist/workflow-auditor/skills-validator.js +533 -0
- package/dist/worktree-guard/evaluation.d.ts +19 -0
- package/dist/worktree-guard/evaluation.js +84 -0
- package/dist/worktree-guard/git.d.ts +3 -0
- package/dist/worktree-guard/git.js +61 -0
- package/package.json +32 -33
- package/src/bbc.ts +0 -39
- package/src/bigo/complexity.ts +0 -138
- package/src/bigo/functions.ts +0 -183
- package/src/bigo/keywords.ts +0 -41
- package/src/bigo/lexical.ts +0 -68
- package/src/bigo/source-files.ts +0 -80
- package/src/change-lane/classification.ts +0 -128
- package/src/change-lane/git.ts +0 -110
- package/src/classify-change-lane.ts +0 -140
- package/src/diff-scope/git-diff.ts +0 -161
- package/src/extract-diff-scope.ts +0 -130
- package/src/measure-bigo.ts +0 -86
- package/src/render-workflow.ts +0 -144
- package/src/workflow/render.ts +0 -40
- package/src/workflow/schema.ts +0 -141
|
@@ -0,0 +1,650 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Application
|
|
3
|
+
* Contains: Offline issue sweeper planner implementing rules SW1-SW8.
|
|
4
|
+
* Rules: Never call GitHub; close only on SW1 or SW3; preserve markers and visual gap lines.
|
|
5
|
+
* BigO: O(n log n) score:4
|
|
6
|
+
* keywords: [SweepPlan, SweepRule, IssueMetrics, ReportMarkdown]
|
|
7
|
+
* GOAL: Evaluate a GitHub issue snapshot and policy into a capped, deterministic sweep plan.
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
export const sweepIssuesUsage = 'bbc sweep-issues --snapshot <file> --sweeper-login <login> [--config <file>] [--now <ISO-8601>]';
|
|
11
|
+
const LANGUAGES = new Set(['es', 'en']);
|
|
12
|
+
const DEFAULTS = {
|
|
13
|
+
language: 'es',
|
|
14
|
+
max_writes_per_run: 20,
|
|
15
|
+
needs_info_days: 14,
|
|
16
|
+
claim_stale_days: 7,
|
|
17
|
+
inactive_days: 30,
|
|
18
|
+
sweeper_login: 'github-actions[bot]',
|
|
19
|
+
labels: {
|
|
20
|
+
stale: 'stale',
|
|
21
|
+
needs_info: 'needs-info',
|
|
22
|
+
close_review: 'needs-close-review',
|
|
23
|
+
claim: 'status:in-progress',
|
|
24
|
+
},
|
|
25
|
+
exempt_labels: ['security', 'frozen', 'lifecycle/frozen', 'pinned'],
|
|
26
|
+
exempt_priorities: ['P0', 'P1'],
|
|
27
|
+
report_title: 'Estado de issues',
|
|
28
|
+
};
|
|
29
|
+
const INT_KEYS = ['max_writes_per_run', 'needs_info_days', 'claim_stale_days', 'inactive_days'];
|
|
30
|
+
const WRITE_ORDER = ['SW1', 'SW3', 'SW2', 'SW5', 'SW7', 'SW6'];
|
|
31
|
+
const CLOSING_RE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b\s*:?\s+(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/|([\w.-]+\/[\w.-]+)?#)(\d+)\b/gi;
|
|
32
|
+
const PRIORITY_NAME = /^(?:(?:priority|prioridad|prio)\s*[:/_ -]\s*(.+)|(p[0-3])\b.*)$/;
|
|
33
|
+
const LEVEL_WORDS = new Map([
|
|
34
|
+
['p0', 0], ['critical', 0], ['critica', 0], ['crítica', 0], ['urgent', 0], ['urgente', 0], ['blocker', 0],
|
|
35
|
+
['p1', 1], ['high', 1], ['alta', 1],
|
|
36
|
+
['p2', 2], ['medium', 2], ['media', 2], ['normal', 2],
|
|
37
|
+
['p3', 3], ['low', 3], ['baja', 3], ['minor', 3],
|
|
38
|
+
]);
|
|
39
|
+
const GAP_LINE = {
|
|
40
|
+
es: '🟡 GAP visual: no hay captura; la evidencia es {evidence}.',
|
|
41
|
+
en: '🟡 GAP visual: no screenshot; the evidence is {evidence}.',
|
|
42
|
+
};
|
|
43
|
+
const TEXT = {
|
|
44
|
+
es: {
|
|
45
|
+
SW1: 'Cierro esta issue: el PR {pr} declara cerrarla y se fusionó el {date} (commit `{sha}`).',
|
|
46
|
+
SW2: '{who}: el PR {pr} se fusionó el {date} y menciona esta issue, pero no declara cerrarla. ¿Está resuelta? Si es así, ciérrenla; si no, comenten qué falta.',
|
|
47
|
+
SW3: 'Cierro esta issue como no planificada: `{label}` lleva {days} días sin respuesta de @{author}. Si aportas la información, se puede reabrir.',
|
|
48
|
+
SW5: '{who}: esta issue está reclamada pero lleva {days} días sin actividad ni PR abierto. ¿Sigue en curso? Si no, liberen el reclamo.',
|
|
49
|
+
SW6: 'Marco esta issue como `{label}`: {days} días sin actividad, sin PR y sin responsable. No se cerrará por esto; cualquier comentario quita la marca.',
|
|
50
|
+
pr_evidence: 'el PR enlazado',
|
|
51
|
+
timeline_evidence: 'la línea de tiempo de la issue',
|
|
52
|
+
},
|
|
53
|
+
en: {
|
|
54
|
+
SW1: 'Closing this issue: pull request {pr} declares closing it and was merged on {date} (commit `{sha}`).',
|
|
55
|
+
SW2: '{who}: pull request {pr} was merged on {date} and mentions this issue without declaring it closed. Is it resolved? If so, close it; if not, comment on what is missing.',
|
|
56
|
+
SW3: 'Closing this issue as not planned: `{label}` has had no answer from @{author} for {days} days. It can be reopened once the information is provided.',
|
|
57
|
+
SW5: '{who}: this issue is claimed but has had no activity or open pull request for {days} days. Is it still in progress? If not, please release the claim.',
|
|
58
|
+
SW6: 'Marking this issue `{label}`: {days} days without activity, a pull request, or an owner. It will not be closed for this; any comment removes the label.',
|
|
59
|
+
pr_evidence: 'the linked pull request',
|
|
60
|
+
timeline_evidence: 'the issue timeline',
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
const REPORT_TEXT = {
|
|
64
|
+
es: {
|
|
65
|
+
title: 'Estado de issues',
|
|
66
|
+
generated: 'Generado',
|
|
67
|
+
run_by: 'Ejecutado por',
|
|
68
|
+
metric: 'Métrica',
|
|
69
|
+
value: 'Valor',
|
|
70
|
+
actions: 'Acciones',
|
|
71
|
+
deferred: 'Diferidas por el tope por ejecución',
|
|
72
|
+
report_only: 'Solo informe',
|
|
73
|
+
gaps: 'Brechas',
|
|
74
|
+
none: 'Ninguna.',
|
|
75
|
+
'missing-label': 'falta la etiqueta',
|
|
76
|
+
incomplete: 'línea de tiempo incompleta',
|
|
77
|
+
evidence: 'el snapshot de esta ejecución',
|
|
78
|
+
},
|
|
79
|
+
en: {
|
|
80
|
+
title: 'Issue status',
|
|
81
|
+
generated: 'Generated',
|
|
82
|
+
run_by: 'Run by',
|
|
83
|
+
metric: 'Metric',
|
|
84
|
+
value: 'Value',
|
|
85
|
+
actions: 'Actions',
|
|
86
|
+
deferred: 'Deferred by the per-run cap',
|
|
87
|
+
report_only: 'Report only',
|
|
88
|
+
gaps: 'Gaps',
|
|
89
|
+
none: 'None.',
|
|
90
|
+
'missing-label': 'missing label',
|
|
91
|
+
incomplete: 'incomplete timeline',
|
|
92
|
+
evidence: 'the snapshot of this run',
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
const REPORT_ROWS = 100;
|
|
96
|
+
const METRIC_KEYS = [
|
|
97
|
+
'open',
|
|
98
|
+
'with_pr',
|
|
99
|
+
'assigned',
|
|
100
|
+
'merged_but_open',
|
|
101
|
+
'stale_claims',
|
|
102
|
+
'duplicate_work',
|
|
103
|
+
'waiting_info',
|
|
104
|
+
'inactive',
|
|
105
|
+
'exempt',
|
|
106
|
+
'age_days_p50',
|
|
107
|
+
'age_days_p90',
|
|
108
|
+
];
|
|
109
|
+
const HELP = 'Usage: bbc sweep-issues --snapshot <file> --sweeper-login <login>\n' +
|
|
110
|
+
' [--config <file>] [--now <ISO-8601>]\n' +
|
|
111
|
+
' --snapshot <file> output of: bbc sweep-github fetch --repo <owner/repo> --out <file>\n' +
|
|
112
|
+
' --sweeper-login <login> the gh account that will apply the plan (its sweep writes are not activity)\n' +
|
|
113
|
+
' --config <file> optional .github/issue-sweeper.json: thresholds, labels, exemptions, language\n' +
|
|
114
|
+
'Prints the plan as JSON. Exit 0: plan ready; 2: unusable input or config.';
|
|
115
|
+
export class SweepUnusableError extends Error {
|
|
116
|
+
}
|
|
117
|
+
function fold(value) {
|
|
118
|
+
return typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
119
|
+
}
|
|
120
|
+
function bare(login) {
|
|
121
|
+
const f = fold(login);
|
|
122
|
+
return f.endsWith('[bot]') ? f.slice(0, -5) : f;
|
|
123
|
+
}
|
|
124
|
+
function parseIsoMs(value) {
|
|
125
|
+
if (typeof value !== 'string')
|
|
126
|
+
return null;
|
|
127
|
+
const trimmed = value.trim();
|
|
128
|
+
if (!trimmed)
|
|
129
|
+
return null;
|
|
130
|
+
const normalized = trimmed.endsWith('Z') || /[+-]\d{2}:\d{2}$/.test(trimmed) ? trimmed : `${trimmed}Z`;
|
|
131
|
+
const ms = Date.parse(normalized);
|
|
132
|
+
return Number.isFinite(ms) ? ms : null;
|
|
133
|
+
}
|
|
134
|
+
function formatUtcIso(ms) {
|
|
135
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
136
|
+
}
|
|
137
|
+
function isPlainObject(value) {
|
|
138
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
139
|
+
}
|
|
140
|
+
function isStringArray(value) {
|
|
141
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string' && item.trim().length > 0);
|
|
142
|
+
}
|
|
143
|
+
function loadJson(path, label) {
|
|
144
|
+
let raw;
|
|
145
|
+
try {
|
|
146
|
+
raw = readFileSync(path, 'utf8');
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
throw new SweepUnusableError(`${label} cannot be read.`);
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
return JSON.parse(raw);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
throw new SweepUnusableError(`${label} is not valid JSON.`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
export function loadSweepConfig(path, sweeperLogin) {
|
|
159
|
+
const raw = path ? loadJson(path, 'Config') : {};
|
|
160
|
+
if (!isPlainObject(raw)) {
|
|
161
|
+
throw new SweepUnusableError('Config must be an object.');
|
|
162
|
+
}
|
|
163
|
+
const merged = { ...DEFAULTS, ...raw };
|
|
164
|
+
const rawLabels = isPlainObject(raw.labels) ? raw.labels : raw.labels == null ? {} : null;
|
|
165
|
+
if (rawLabels === null) {
|
|
166
|
+
throw new SweepUnusableError('Config "labels" values must be label names.');
|
|
167
|
+
}
|
|
168
|
+
const labels = { ...DEFAULTS.labels, ...rawLabels };
|
|
169
|
+
if (typeof merged.language !== 'string' || !LANGUAGES.has(merged.language)) {
|
|
170
|
+
throw new SweepUnusableError(`Config "language" must be one of: ${[...LANGUAGES].join(', ')}.`);
|
|
171
|
+
}
|
|
172
|
+
for (const key of INT_KEYS) {
|
|
173
|
+
const val = merged[key];
|
|
174
|
+
if (typeof val !== 'number' || !Number.isInteger(val) || val < 1) {
|
|
175
|
+
throw new SweepUnusableError(`Config "${key}" must be a positive integer.`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
for (const val of Object.values(labels)) {
|
|
179
|
+
if (typeof val !== 'string' || !val.trim()) {
|
|
180
|
+
throw new SweepUnusableError('Config "labels" values must be label names.');
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
for (const key of ['exempt_labels', 'exempt_priorities']) {
|
|
184
|
+
const val = merged[key];
|
|
185
|
+
if (!Array.isArray(val) || (val.length > 0 && !isStringArray(val))) {
|
|
186
|
+
throw new SweepUnusableError(`Config "${key}" must be an array of names.`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (typeof merged.report_title !== 'string' || !merged.report_title.trim()) {
|
|
190
|
+
throw new SweepUnusableError('Config "report_title" must be a title.');
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
language: merged.language,
|
|
194
|
+
max_writes_per_run: merged.max_writes_per_run,
|
|
195
|
+
needs_info_days: merged.needs_info_days,
|
|
196
|
+
claim_stale_days: merged.claim_stale_days,
|
|
197
|
+
inactive_days: merged.inactive_days,
|
|
198
|
+
sweeper_login: sweeperLogin,
|
|
199
|
+
labels: labels,
|
|
200
|
+
exempt_labels: merged.exempt_labels,
|
|
201
|
+
exempt_priorities: merged.exempt_priorities,
|
|
202
|
+
report_title: merged.report_title,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
export function loadSnapshot(path) {
|
|
206
|
+
const raw = loadJson(path, 'Snapshot');
|
|
207
|
+
if (!isPlainObject(raw) || typeof raw.repo !== 'string' || !raw.repo.includes('/')) {
|
|
208
|
+
throw new SweepUnusableError('Snapshot needs "repo" as owner/name.');
|
|
209
|
+
}
|
|
210
|
+
if (!Array.isArray(raw.issues) || !Array.isArray(raw.labels)) {
|
|
211
|
+
throw new SweepUnusableError('Snapshot "issues" and "labels" must be arrays.');
|
|
212
|
+
}
|
|
213
|
+
for (const item of raw.issues) {
|
|
214
|
+
if (!isPlainObject(item) || typeof item.number !== 'number' || !Number.isInteger(item.number) || parseIsoMs(item.created_at) === null) {
|
|
215
|
+
throw new SweepUnusableError('Every snapshot issue needs a number and created_at.');
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return raw;
|
|
219
|
+
}
|
|
220
|
+
function priorityLevel(name) {
|
|
221
|
+
const match = PRIORITY_NAME.exec(fold(name));
|
|
222
|
+
if (!match)
|
|
223
|
+
return null;
|
|
224
|
+
const word = match[2] ?? (match[1] ?? '').trim().split(/[\s:/_-]+/)[0] ?? '';
|
|
225
|
+
return LEVEL_WORDS.get(word) ?? null;
|
|
226
|
+
}
|
|
227
|
+
class IssueModel {
|
|
228
|
+
raw;
|
|
229
|
+
number;
|
|
230
|
+
author;
|
|
231
|
+
createdMs;
|
|
232
|
+
labels;
|
|
233
|
+
labelNames;
|
|
234
|
+
assignees;
|
|
235
|
+
incomplete;
|
|
236
|
+
prs;
|
|
237
|
+
events = [];
|
|
238
|
+
labelEvents = [];
|
|
239
|
+
markers = new Map();
|
|
240
|
+
lastActivityMs;
|
|
241
|
+
openPrs;
|
|
242
|
+
mergedPrs;
|
|
243
|
+
repoFolded;
|
|
244
|
+
constructor(raw, repo, config) {
|
|
245
|
+
this.raw = raw;
|
|
246
|
+
this.number = raw.number;
|
|
247
|
+
this.author = typeof raw.author === 'string' && raw.author ? raw.author : 'ghost';
|
|
248
|
+
this.createdMs = parseIsoMs(raw.created_at);
|
|
249
|
+
this.labelNames = (Array.isArray(raw.labels) ? raw.labels : []).filter((n) => typeof n === 'string');
|
|
250
|
+
this.labels = new Set(this.labelNames.map((n) => fold(n)));
|
|
251
|
+
this.assignees = (Array.isArray(raw.assignees) ? raw.assignees : []).filter((n) => typeof n === 'string' && n.length > 0);
|
|
252
|
+
this.incomplete = raw.incomplete === true;
|
|
253
|
+
this.prs = (Array.isArray(raw.prs) ? raw.prs : []).filter((pr) => isPlainObject(pr) && typeof pr.number === 'number' && Number.isInteger(pr.number));
|
|
254
|
+
const sweeper = bare(config.sweeper_login);
|
|
255
|
+
const ownLabels = new Set([fold(config.labels.stale), fold(config.labels.close_review)]);
|
|
256
|
+
for (const ev of Array.isArray(raw.events) ? raw.events : []) {
|
|
257
|
+
if (!isPlainObject(ev))
|
|
258
|
+
continue;
|
|
259
|
+
const atMs = parseIsoMs(ev.at);
|
|
260
|
+
if (atMs === null)
|
|
261
|
+
continue;
|
|
262
|
+
const evType = typeof ev.type === 'string' ? ev.type : '';
|
|
263
|
+
const parsed = {
|
|
264
|
+
type: evType,
|
|
265
|
+
atMs,
|
|
266
|
+
actor: typeof ev.actor === 'string' ? ev.actor : undefined,
|
|
267
|
+
label: typeof ev.label === 'string' ? ev.label : undefined,
|
|
268
|
+
marker: typeof ev.marker === 'string' ? ev.marker : null,
|
|
269
|
+
};
|
|
270
|
+
if (evType !== 'comment') {
|
|
271
|
+
this.labelEvents.push(parsed);
|
|
272
|
+
}
|
|
273
|
+
if (evType === 'comment' && parsed.marker) {
|
|
274
|
+
const prev = this.markers.get(parsed.marker);
|
|
275
|
+
this.markers.set(parsed.marker, prev !== undefined ? Math.max(atMs, prev) : atMs);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (bare(parsed.actor) === sweeper && ownLabels.has(fold(parsed.label))) {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
this.events.push(parsed);
|
|
282
|
+
}
|
|
283
|
+
let maxTime = this.createdMs;
|
|
284
|
+
for (const ev of this.events) {
|
|
285
|
+
if (ev.atMs > maxTime)
|
|
286
|
+
maxTime = ev.atMs;
|
|
287
|
+
}
|
|
288
|
+
for (const pr of this.prs) {
|
|
289
|
+
const refMs = parseIsoMs(pr.referenced_at);
|
|
290
|
+
if (refMs !== null && refMs > maxTime)
|
|
291
|
+
maxTime = refMs;
|
|
292
|
+
}
|
|
293
|
+
this.lastActivityMs = maxTime;
|
|
294
|
+
this.openPrs = this.prs.filter((pr) => pr.state === 'OPEN');
|
|
295
|
+
this.mergedPrs = this.prs.filter((pr) => pr.state === 'MERGED' && parseIsoMs(pr.merged_at) !== null);
|
|
296
|
+
this.repoFolded = fold(repo);
|
|
297
|
+
}
|
|
298
|
+
has(label) {
|
|
299
|
+
return this.labels.has(fold(label));
|
|
300
|
+
}
|
|
301
|
+
declaresClosing(pr) {
|
|
302
|
+
if (pr.will_close === true || pr.manual_link === true)
|
|
303
|
+
return true;
|
|
304
|
+
const text = typeof pr.text === 'string' ? pr.text : '';
|
|
305
|
+
const sameRepo = fold(pr.repo) === this.repoFolded;
|
|
306
|
+
for (const match of text.matchAll(CLOSING_RE)) {
|
|
307
|
+
const target = fold(match[1] ?? match[2]) || (sameRepo ? this.repoFolded : '');
|
|
308
|
+
if (target === this.repoFolded && match[3] && Number.parseInt(match[3], 10) === this.number) {
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
lastEvent(kind, label) {
|
|
315
|
+
const labelFolded = label === undefined ? null : fold(label);
|
|
316
|
+
let maxMs = null;
|
|
317
|
+
for (const ev of this.labelEvents) {
|
|
318
|
+
if (ev.type !== kind)
|
|
319
|
+
continue;
|
|
320
|
+
if (labelFolded !== null && fold(ev.label) !== labelFolded)
|
|
321
|
+
continue;
|
|
322
|
+
if (maxMs === null || ev.atMs > maxMs)
|
|
323
|
+
maxMs = ev.atMs;
|
|
324
|
+
}
|
|
325
|
+
return maxMs;
|
|
326
|
+
}
|
|
327
|
+
commentedSince(rule) {
|
|
328
|
+
const markerMs = this.markers.get(rule);
|
|
329
|
+
return markerMs !== undefined && markerMs > this.lastActivityMs;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function shortSha(sha) {
|
|
333
|
+
return typeof sha === 'string' ? sha.slice(0, 7) : '?';
|
|
334
|
+
}
|
|
335
|
+
function formatDate(value) {
|
|
336
|
+
const ms = parseIsoMs(value);
|
|
337
|
+
return ms !== null ? new Date(ms).toISOString().slice(0, 10) : '?';
|
|
338
|
+
}
|
|
339
|
+
function prRef(pr, repo) {
|
|
340
|
+
const num = `#${pr.number}`;
|
|
341
|
+
return fold(pr.repo) === fold(repo) ? num : `${String(pr.repo)}${num}`;
|
|
342
|
+
}
|
|
343
|
+
function who(issue) {
|
|
344
|
+
const list = issue.assignees.length > 0 ? issue.assignees : [issue.author];
|
|
345
|
+
return list.map((login) => `@${login}`).join(' ');
|
|
346
|
+
}
|
|
347
|
+
function formatTemplate(template, values) {
|
|
348
|
+
let out = template;
|
|
349
|
+
for (const [key, val] of Object.entries(values)) {
|
|
350
|
+
out = out.replaceAll(`{${key}}`, String(val));
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
function makeComment(rule, language, evidence, values) {
|
|
355
|
+
const text = (TEXT[language] ?? TEXT.en);
|
|
356
|
+
const gapTmpl = (GAP_LINE[language] ?? GAP_LINE.en);
|
|
357
|
+
const body = formatTemplate(text[rule] ?? '', values);
|
|
358
|
+
const gap = formatTemplate(gapTmpl, { evidence: text[evidence] ?? '' });
|
|
359
|
+
return {
|
|
360
|
+
action: 'comment',
|
|
361
|
+
marker: rule,
|
|
362
|
+
body: `${body}\n\n${gap}\n\n<!-- issue-sweeper:${rule} -->`,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function escapeCell(value) {
|
|
366
|
+
return String(value).replaceAll('|', '\\|').replaceAll('\n', ' ');
|
|
367
|
+
}
|
|
368
|
+
function formatEntries(entries, text) {
|
|
369
|
+
if (entries.length === 0)
|
|
370
|
+
return [text.none ?? ''];
|
|
371
|
+
const lines = [];
|
|
372
|
+
for (const entry of entries.slice(0, REPORT_ROWS)) {
|
|
373
|
+
const stepsList = 'steps' in entry && Array.isArray(entry.steps) ? entry.steps : [];
|
|
374
|
+
const stepsText = stepsList.map((s) => s.action + (s.label ? ` \`${s.label}\`` : '')).join(', ') || '—';
|
|
375
|
+
lines.push(`- #${entry.issue} — \`${entry.rule}\` — ${escapeCell(stepsText)}`);
|
|
376
|
+
}
|
|
377
|
+
if (entries.length > REPORT_ROWS) {
|
|
378
|
+
lines.push(`- … +${entries.length - REPORT_ROWS}`);
|
|
379
|
+
}
|
|
380
|
+
return lines;
|
|
381
|
+
}
|
|
382
|
+
export function renderSweepReport(plan, language) {
|
|
383
|
+
const text = (REPORT_TEXT[language] ?? REPORT_TEXT.en);
|
|
384
|
+
const gapTmpl = (GAP_LINE[language] ?? GAP_LINE.en);
|
|
385
|
+
const lines = [
|
|
386
|
+
`## ${text.title ?? ''}`,
|
|
387
|
+
'',
|
|
388
|
+
`- ${text.generated ?? ''}: ${plan.generated_at}`,
|
|
389
|
+
`- ${text.run_by ?? ''}: @${escapeCell(plan.run_by)}`,
|
|
390
|
+
'',
|
|
391
|
+
`| ${text.metric ?? ''} | ${text.value ?? ''} |`,
|
|
392
|
+
'|---|---|',
|
|
393
|
+
...METRIC_KEYS.map((key) => `| \`${key}\` | ${plan.metrics[key]} |`),
|
|
394
|
+
];
|
|
395
|
+
const sections = [
|
|
396
|
+
['actions', plan.actions],
|
|
397
|
+
['deferred', plan.deferred],
|
|
398
|
+
['report_only', plan.report_only],
|
|
399
|
+
];
|
|
400
|
+
for (const [key, list] of sections) {
|
|
401
|
+
if (list.length > 0 || key === 'actions') {
|
|
402
|
+
lines.push('', `### ${text[key] ?? ''}`, '', ...formatEntries(list, text));
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
lines.push('', `### ${text.gaps ?? ''}`, '');
|
|
406
|
+
if (plan.gaps.length === 0) {
|
|
407
|
+
lines.push(text.none ?? '');
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
for (const gap of plan.gaps) {
|
|
411
|
+
const kind = String(gap.kind);
|
|
412
|
+
const target = 'label' in gap ? `\`${String(gap.label)}\`` : `#${String(gap.issue)}`;
|
|
413
|
+
lines.push(`- ${text[kind] ?? ''} ${target}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
lines.push('', formatTemplate(gapTmpl, { evidence: text.evidence ?? '' }), '', '<!-- issue-sweeper:report -->');
|
|
417
|
+
return lines.join('\n');
|
|
418
|
+
}
|
|
419
|
+
export function evaluateSweepPlan(snapshot, config, nowMs) {
|
|
420
|
+
const repo = snapshot.repo;
|
|
421
|
+
const lang = config.language;
|
|
422
|
+
const repoLabels = new Set(snapshot.labels.filter((n) => typeof n === 'string').map((n) => fold(n)));
|
|
423
|
+
const exemptLabels = new Set(config.exempt_labels.map((n) => fold(n)));
|
|
424
|
+
const exemptLevels = new Set(config.exempt_priorities.map((n) => priorityLevel(n)).filter((lvl) => lvl !== null));
|
|
425
|
+
const tally = { stale_claims: 0, duplicate_work: 0, inactive: 0 };
|
|
426
|
+
const daysSince = (ms) => Math.floor((nowMs - ms) / 86_400_000);
|
|
427
|
+
const labelStep = (action, key) => {
|
|
428
|
+
const name = config.labels[key];
|
|
429
|
+
return repoLabels.has(fold(name)) ? [{ action, label: name }] : [];
|
|
430
|
+
};
|
|
431
|
+
const isExempt = (issue) => {
|
|
432
|
+
for (const lbl of issue.labels) {
|
|
433
|
+
if (exemptLabels.has(lbl))
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
return issue.labelNames.some((name) => {
|
|
437
|
+
const lvl = priorityLevel(name);
|
|
438
|
+
return lvl !== null && exemptLevels.has(lvl);
|
|
439
|
+
});
|
|
440
|
+
};
|
|
441
|
+
const decideMerged = (issue) => {
|
|
442
|
+
if (issue.mergedPrs.length === 0)
|
|
443
|
+
return null;
|
|
444
|
+
const declaring = issue.mergedPrs.filter((pr) => issue.declaresClosing(pr));
|
|
445
|
+
if (declaring.length > 0) {
|
|
446
|
+
const latest = declaring.reduce((best, cur) => parseIsoMs(cur.merged_at) > parseIsoMs(best.merged_at) ? cur : best);
|
|
447
|
+
const latestMs = parseIsoMs(latest.merged_at);
|
|
448
|
+
const reopened = issue.lastEvent('reopened');
|
|
449
|
+
const blocked = (reopened !== null && reopened > latestMs) || issue.openPrs.some((pr) => issue.declaresClosing(pr));
|
|
450
|
+
if (!blocked) {
|
|
451
|
+
const comment = makeComment('SW1', lang, 'pr_evidence', {
|
|
452
|
+
pr: prRef(latest, repo),
|
|
453
|
+
date: formatDate(latest.merged_at),
|
|
454
|
+
sha: shortSha(latest.merge_commit),
|
|
455
|
+
});
|
|
456
|
+
return ['SW1', [comment, { action: 'close', state_reason: 'completed' }]];
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (issue.commentedSince('SW2'))
|
|
460
|
+
return null;
|
|
461
|
+
const latest = issue.mergedPrs.reduce((best, cur) => parseIsoMs(cur.merged_at) > parseIsoMs(best.merged_at) ? cur : best);
|
|
462
|
+
const steps = issue.has(config.labels.close_review) ? [] : labelStep('add-label', 'close_review');
|
|
463
|
+
steps.push(makeComment('SW2', lang, 'pr_evidence', {
|
|
464
|
+
who: who(issue),
|
|
465
|
+
pr: prRef(latest, repo),
|
|
466
|
+
date: formatDate(latest.merged_at),
|
|
467
|
+
}));
|
|
468
|
+
return ['SW2', steps];
|
|
469
|
+
};
|
|
470
|
+
const needsInfoUnanswered = (issue) => {
|
|
471
|
+
const label = config.labels.needs_info;
|
|
472
|
+
if (!issue.has(label))
|
|
473
|
+
return false;
|
|
474
|
+
const asked = issue.lastEvent('labeled', label);
|
|
475
|
+
if (asked === null || daysSince(asked) < config.needs_info_days)
|
|
476
|
+
return false;
|
|
477
|
+
const authorFolded = fold(issue.author);
|
|
478
|
+
return !issue.events.some((ev) => ev.atMs > asked && ev.type === 'comment' && fold(ev.actor) === authorFolded);
|
|
479
|
+
};
|
|
480
|
+
const decideIdle = (issue) => {
|
|
481
|
+
const idleDays = daysSince(issue.lastActivityMs);
|
|
482
|
+
const claimed = issue.has(config.labels.claim) && issue.assignees.length > 0;
|
|
483
|
+
if (claimed) {
|
|
484
|
+
if (issue.openPrs.length > 0 || idleDays < config.claim_stale_days)
|
|
485
|
+
return [null, []];
|
|
486
|
+
tally.stale_claims += 1;
|
|
487
|
+
if (issue.commentedSince('SW5'))
|
|
488
|
+
return [null, []];
|
|
489
|
+
return ['SW5', [makeComment('SW5', lang, 'timeline_evidence', { who: who(issue), days: idleDays })]];
|
|
490
|
+
}
|
|
491
|
+
const stale = config.labels.stale;
|
|
492
|
+
if (issue.has(stale)) {
|
|
493
|
+
const marked = issue.markers.get('SW6') ?? issue.lastEvent('labeled', stale);
|
|
494
|
+
if (marked !== null && issue.lastActivityMs > marked && idleDays < config.inactive_days) {
|
|
495
|
+
return ['SW7', [{ action: 'remove-label', label: stale }]];
|
|
496
|
+
}
|
|
497
|
+
tally.inactive += 1;
|
|
498
|
+
return [null, []];
|
|
499
|
+
}
|
|
500
|
+
if (issue.openPrs.length > 0 || issue.mergedPrs.length > 0 || idleDays < config.inactive_days) {
|
|
501
|
+
return [null, []];
|
|
502
|
+
}
|
|
503
|
+
tally.inactive += 1;
|
|
504
|
+
if (issue.commentedSince('SW6'))
|
|
505
|
+
return [null, []];
|
|
506
|
+
const steps = labelStep('add-label', 'stale');
|
|
507
|
+
steps.push(makeComment('SW6', lang, 'timeline_evidence', { label: stale, days: idleDays }));
|
|
508
|
+
return ['SW6', steps];
|
|
509
|
+
};
|
|
510
|
+
const decide = (issue) => {
|
|
511
|
+
if (isExempt(issue))
|
|
512
|
+
return ['SW8', []];
|
|
513
|
+
if (issue.incomplete)
|
|
514
|
+
return [null, []];
|
|
515
|
+
if (issue.mergedPrs.length > 0) {
|
|
516
|
+
const merged = decideMerged(issue);
|
|
517
|
+
if (merged !== null)
|
|
518
|
+
return merged;
|
|
519
|
+
return [null, []];
|
|
520
|
+
}
|
|
521
|
+
if (needsInfoUnanswered(issue)) {
|
|
522
|
+
const label = config.labels.needs_info;
|
|
523
|
+
const asked = issue.lastEvent('labeled', label);
|
|
524
|
+
const comment = makeComment('SW3', lang, 'timeline_evidence', {
|
|
525
|
+
label,
|
|
526
|
+
days: daysSince(asked),
|
|
527
|
+
author: issue.author,
|
|
528
|
+
});
|
|
529
|
+
return ['SW3', [comment, { action: 'close', state_reason: 'not_planned' }]];
|
|
530
|
+
}
|
|
531
|
+
if (issue.openPrs.length > 1) {
|
|
532
|
+
tally.duplicate_work += 1;
|
|
533
|
+
return ['SW4', []];
|
|
534
|
+
}
|
|
535
|
+
return decideIdle(issue);
|
|
536
|
+
};
|
|
537
|
+
const reportIssue = typeof snapshot.report_issue === 'number' ? snapshot.report_issue : null;
|
|
538
|
+
const issues = snapshot.issues
|
|
539
|
+
.filter((raw) => raw.number !== reportIssue)
|
|
540
|
+
.map((raw) => new IssueModel(raw, repo, config));
|
|
541
|
+
const writes = [];
|
|
542
|
+
const reportOnly = [];
|
|
543
|
+
const gaps = [];
|
|
544
|
+
for (const name of Object.values(config.labels)) {
|
|
545
|
+
if (!repoLabels.has(fold(name))) {
|
|
546
|
+
gaps.push({ kind: 'missing-label', label: name });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
for (const issue of issues) {
|
|
550
|
+
if (issue.incomplete) {
|
|
551
|
+
gaps.push({ kind: 'incomplete', issue: issue.number });
|
|
552
|
+
}
|
|
553
|
+
const [rule, steps] = decide(issue);
|
|
554
|
+
if (rule === null)
|
|
555
|
+
continue;
|
|
556
|
+
const entry = {
|
|
557
|
+
issue: issue.number,
|
|
558
|
+
rule,
|
|
559
|
+
url: typeof issue.raw.url === 'string' ? issue.raw.url : null,
|
|
560
|
+
steps,
|
|
561
|
+
};
|
|
562
|
+
if (steps.length > 0)
|
|
563
|
+
writes.push(entry);
|
|
564
|
+
else
|
|
565
|
+
reportOnly.push(entry);
|
|
566
|
+
}
|
|
567
|
+
writes.sort((a, b) => {
|
|
568
|
+
const orderA = WRITE_ORDER.indexOf(a.rule);
|
|
569
|
+
const orderB = WRITE_ORDER.indexOf(b.rule);
|
|
570
|
+
return orderA !== orderB ? orderA - orderB : a.issue - b.issue;
|
|
571
|
+
});
|
|
572
|
+
const cap = config.max_writes_per_run;
|
|
573
|
+
const chosen = writes.slice(0, cap);
|
|
574
|
+
const deferred = writes.slice(cap).map((e) => ({ issue: e.issue, rule: e.rule, url: e.url }));
|
|
575
|
+
const ages = issues.map((issue) => daysSince(issue.createdMs)).sort((a, b) => a - b);
|
|
576
|
+
const rank = (share) => (ages.length > 0 ? ages[Math.max(0, Math.ceil(share * ages.length) - 1)] ?? 0 : 0);
|
|
577
|
+
const exemptCount = reportOnly.filter((e) => e.rule === 'SW8').length;
|
|
578
|
+
const metrics = {
|
|
579
|
+
open: issues.length,
|
|
580
|
+
with_pr: issues.filter((i) => i.openPrs.length > 0 || i.mergedPrs.length > 0).length,
|
|
581
|
+
assigned: issues.filter((i) => i.assignees.length > 0).length,
|
|
582
|
+
merged_but_open: issues.filter((i) => i.mergedPrs.length > 0).length,
|
|
583
|
+
waiting_info: issues.filter((i) => i.has(config.labels.needs_info)).length,
|
|
584
|
+
exempt: exemptCount,
|
|
585
|
+
age_days_p50: rank(0.5),
|
|
586
|
+
age_days_p90: rank(0.9),
|
|
587
|
+
...tally,
|
|
588
|
+
};
|
|
589
|
+
const basePlan = {
|
|
590
|
+
verdict: 'ok',
|
|
591
|
+
repo,
|
|
592
|
+
run_by: config.sweeper_login,
|
|
593
|
+
generated_at: formatUtcIso(nowMs),
|
|
594
|
+
report_issue: reportIssue,
|
|
595
|
+
report_title: config.report_title,
|
|
596
|
+
actions: chosen,
|
|
597
|
+
deferred,
|
|
598
|
+
report_only: reportOnly,
|
|
599
|
+
gaps,
|
|
600
|
+
metrics,
|
|
601
|
+
};
|
|
602
|
+
return {
|
|
603
|
+
...basePlan,
|
|
604
|
+
report_markdown: renderSweepReport(basePlan, lang),
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function parseArgs(argv) {
|
|
608
|
+
if (argv.includes('--help') || argv.includes('-h'))
|
|
609
|
+
return null;
|
|
610
|
+
const args = {};
|
|
611
|
+
for (let idx = 0; idx < argv.length; idx += 2) {
|
|
612
|
+
const key = argv[idx];
|
|
613
|
+
const value = argv[idx + 1];
|
|
614
|
+
if (!['--snapshot', '--config', '--now', '--sweeper-login'].includes(key) || value === undefined) {
|
|
615
|
+
throw new SweepUnusableError(`Unknown or incomplete argument: ${key}`);
|
|
616
|
+
}
|
|
617
|
+
args[key.slice(2)] = value;
|
|
618
|
+
}
|
|
619
|
+
for (const key of ['snapshot', 'sweeper-login']) {
|
|
620
|
+
if (!(key in args)) {
|
|
621
|
+
throw new SweepUnusableError(`Missing --${key}.`);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return args;
|
|
625
|
+
}
|
|
626
|
+
export function sweepIssues(argv) {
|
|
627
|
+
try {
|
|
628
|
+
const args = parseArgs(argv);
|
|
629
|
+
if (args === null) {
|
|
630
|
+
process.stdout.write(`${HELP}\n`);
|
|
631
|
+
return 0;
|
|
632
|
+
}
|
|
633
|
+
const nowMs = args.now !== undefined ? parseIsoMs(args.now) : Date.now();
|
|
634
|
+
if (nowMs === null) {
|
|
635
|
+
throw new SweepUnusableError('--now must be ISO-8601.');
|
|
636
|
+
}
|
|
637
|
+
const config = loadSweepConfig(args.config, args['sweeper-login']);
|
|
638
|
+
const snapshot = loadSnapshot(args.snapshot);
|
|
639
|
+
const plan = evaluateSweepPlan(snapshot, config, nowMs);
|
|
640
|
+
process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
|
|
641
|
+
return 0;
|
|
642
|
+
}
|
|
643
|
+
catch (error) {
|
|
644
|
+
if (error instanceof SweepUnusableError) {
|
|
645
|
+
process.stdout.write(`${JSON.stringify({ verdict: 'unusable', reason: error.message }, null, 2)}\n`);
|
|
646
|
+
return 2;
|
|
647
|
+
}
|
|
648
|
+
throw error;
|
|
649
|
+
}
|
|
650
|
+
}
|
package/dist/sweep.d.ts
ADDED