@mcptoolshop/housekeeping 1.5.0 → 1.6.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.
- package/CHANGELOG.md +42 -0
- package/README.md +7 -1
- package/package.json +1 -1
- package/src/analyze.mjs +4 -1
- package/src/atlas-view.mjs +294 -0
- package/src/cli.mjs +63 -0
- package/src/load.mjs +10 -5
- package/src/mcp.mjs +62 -0
- package/src/queue.mjs +332 -0
- package/src/workflow-risks.mjs +18 -3
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,48 @@
|
|
|
3
3
|
All notable changes to this project are recorded here.
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
|
|
6
|
+
## [1.6.1] - 2026-12-05
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- `WF_NO_PATHS_FILTER` no longer fires on a `push:` trigger gated to tags alone
|
|
11
|
+
(`on: { push: { tags: [v*] } }` with no `branches:`), the shape of a tag-push
|
|
12
|
+
release workflow. Its tag patterns already narrow the trigger, and a `paths:`
|
|
13
|
+
filter there would stop the release from firing at all — a tag push carries no
|
|
14
|
+
changed file a paths filter can match. A push that also fires on a branch
|
|
15
|
+
(with or without tags), a bare `on: push`, and `pull_request` (which has no
|
|
16
|
+
tag form) are still flagged. `WF_NO_CONCURRENCY` and `WF_NO_DISPATCH` are
|
|
17
|
+
unchanged and still hold a tag-only release to the same concurrency and
|
|
18
|
+
manual-dispatch rules.
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- The Atlas engine pin moves from 1.27.0 to 1.28.0: the export (`ATLAS_PIN`),
|
|
23
|
+
the regenerated map, and the CI `atlas check` move together, as
|
|
24
|
+
`rules/atlas-map.md` asks.
|
|
25
|
+
|
|
26
|
+
## [1.6.0] - 2026-12-05
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
|
|
30
|
+
- `hk queue` and MCP tool `hk_queue`: deterministic, read-only remediation queue
|
|
31
|
+
grouping every finding from the newest snapshot into seven actionable sweep
|
|
32
|
+
lanes (`security-alerts`, `lockfile-cves`, `mainline-ci`, `atlas-rollout`,
|
|
33
|
+
`workflow-rules`, `pr-backlog`, `repo-hygiene`), ranked by severity and
|
|
34
|
+
health penalty (`--by-lane`, `--lane`, `--category`, `--severity`, `--repo`,
|
|
35
|
+
`--limit`, `--include-meta`, `--json`).
|
|
36
|
+
- `hk atlas` and MCP tool `hk_atlas`: fleet-wide Atlas rollout auditor showing
|
|
37
|
+
engine distribution, unmapped active repositories (`--missing`), repositories
|
|
38
|
+
behind the fleet target or a `--target <semver>` override (`--behind`), and
|
|
39
|
+
aggregated `D1`/`D2` door findings (`--doors`, `--json`).
|
|
40
|
+
|
|
41
|
+
### Security
|
|
42
|
+
|
|
43
|
+
- Updated `cross-spawn` in root `package-lock.json` (`7.1.2`, clearing
|
|
44
|
+
`GHSA-ghv9-86vm-4v8m`, `GHSA-m6qr-m48x-3xhh`, `GHSA-w3gc-668g-rf8f`) and
|
|
45
|
+
bumped `astro` (`7.3.5 -> 7.4.12`) in `site/` (0 audit vulnerabilities,
|
|
46
|
+
cross-platform native bindings preserved).
|
|
47
|
+
|
|
6
48
|
## [1.5.0] - 2026-11-07
|
|
7
49
|
|
|
8
50
|
### Added
|
package/README.md
CHANGED
|
@@ -72,6 +72,8 @@ Questions an agent answers in a call or two:
|
|
|
72
72
|
| `hk_repo` | One repository in full: findings, workflows, open pull requests and issues. |
|
|
73
73
|
| `hk_backlog` | Open pull requests or issues across the organization, oldest first. |
|
|
74
74
|
| `hk_health` | A health score per repository, worst first. |
|
|
75
|
+
| `hk_queue` | A ranked remediation queue: every finding sorted into an actionable sweep lane, by repository or by lane. |
|
|
76
|
+
| `hk_atlas` | Fleet-wide Atlas rollout: which repositories have no map, which lag the fleet engine, and the door findings across the fleet. |
|
|
75
77
|
| `hk_cost` | Actions spend by repository, workflow or job, gross and net apart. |
|
|
76
78
|
| `hk_sql` | One read-only `SELECT` or `WITH` statement against the warehouse. |
|
|
77
79
|
| `hk_schema` | The tables and columns, for writing `hk_sql` queries. |
|
|
@@ -107,7 +109,9 @@ are built to work together.
|
|
|
107
109
|
- **Every map, swept.** A sweep reads each repository's committed map along
|
|
108
110
|
with everything else, and reports which repositories have none, which never
|
|
109
111
|
run `atlas check`, and which carry an engine behind the one the rest of the
|
|
110
|
-
organization pins.
|
|
112
|
+
organization pins. `hk atlas` (and `hk_atlas`) surface that fleet rollout
|
|
113
|
+
directly: which repositories have no map, which lag the fleet engine, and the
|
|
114
|
+
door findings across the fleet.
|
|
111
115
|
- **Where a red run broke.** When a default branch is red, the finding names
|
|
112
116
|
the job and step that failed and, through the map, the command that step
|
|
113
117
|
runs, so the repair starts in the right file.
|
|
@@ -175,6 +179,8 @@ hk summary # portfolio totals
|
|
|
175
179
|
hk ci # repositories whose default branch is red
|
|
176
180
|
hk findings # findings grouped by severity and code
|
|
177
181
|
hk health # per-repository health score, worst first
|
|
182
|
+
hk queue # ranked remediation queue, every finding in a sweep lane
|
|
183
|
+
hk atlas # fleet-wide Atlas rollout: no map, behind the engine, door findings
|
|
178
184
|
hk repo <name> # one repository in full
|
|
179
185
|
hk prs # every open pull request by age
|
|
180
186
|
hk branches # branches by state: merged, moved after merge, no PR
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcptoolshop/housekeeping",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.1",
|
|
4
4
|
"description": "Operational-health warehouse for a GitHub organization: CI, issues, PRs, releases, Actions cost and repo hygiene, collected into SQLite and audited against written rules.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"github",
|
package/src/analyze.mjs
CHANGED
|
@@ -93,7 +93,10 @@ export const CHECKERS = [
|
|
|
93
93
|
{ dep: 'oxlint', invokers: ['oxlint'] },
|
|
94
94
|
];
|
|
95
95
|
export const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
|
|
96
|
-
|
|
96
|
+
// Severity-to-health-penalty, the one weighting both the health score and the
|
|
97
|
+
// queue's per-repo ranking read from. Exported so a second reader cannot drift
|
|
98
|
+
// a private copy of it out of step with healthScores.
|
|
99
|
+
export const SEV_WEIGHT = { critical: 40, high: 15, medium: 6, low: 2, info: 0 };
|
|
97
100
|
|
|
98
101
|
|
|
99
102
|
const norm = v => (v == null ? null : String(v).trim().replace(/^v/i, ''));
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Fleet-wide Atlas rollout, read from the latest snapshot. Powers `hk atlas`
|
|
3
|
+
// and the MCP `hk_atlas` tool (both wired by the orchestrator, not here).
|
|
4
|
+
//
|
|
5
|
+
// rules/atlas-map.md asks three questions of the fleet: which repositories keep
|
|
6
|
+
// a committed Atlas map, which carry a map an older engine made, and which
|
|
7
|
+
// doors a 1.24.0+ map flags (D1/D2). This module answers them as plain data and
|
|
8
|
+
// renders that data as a string -- it never prints, never writes, and runs only
|
|
9
|
+
// SELECTs, so a report is a pure function of one snapshot.
|
|
10
|
+
//
|
|
11
|
+
// The engine comparison is the one trap worth stating once: compareSemver sorts
|
|
12
|
+
// NEWEST FIRST (see load.mjs), so compareSemver(parseSemver(a), parseSemver(b))
|
|
13
|
+
// > 0 means a is OLDER than b. "Behind the target" is exactly that.
|
|
14
|
+
import { parseSemver, compareSemver } from './load.mjs';
|
|
15
|
+
import { doorFindingRows } from './analyze.mjs';
|
|
16
|
+
import { userError } from './errors.mjs';
|
|
17
|
+
|
|
18
|
+
// An engine string with no recorded version is shown under this label rather
|
|
19
|
+
// than dropped: a readable map made before Atlas 1.23.0 records no engine, and
|
|
20
|
+
// "we have a map but do not know what made it" is a real, countable state.
|
|
21
|
+
const UNRECORDED = 'unrecorded';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The target engine version for a snapshot. Pure over the DB (one SELECT).
|
|
25
|
+
*
|
|
26
|
+
* `override` wins when given, and must parse as semver -- a caller that typed
|
|
27
|
+
* `--target vNope` is a usage error, not a silent fall-through. With no override
|
|
28
|
+
* it is the fleet version this snapshot was measured against (atlas_fleet),
|
|
29
|
+
* which load.mjs writes from the collector's reading; null when that row is
|
|
30
|
+
* absent (a snapshot before the atlas pass) or holds no version.
|
|
31
|
+
*/
|
|
32
|
+
export function fleetTarget(db, sid, override) {
|
|
33
|
+
if (override != null && override !== '') {
|
|
34
|
+
if (!parseSemver(override)) {
|
|
35
|
+
throw userError('USAGE', `not a version: ${override}`, 'pass a semver like 1.24.0 to --target');
|
|
36
|
+
}
|
|
37
|
+
return parseSemver(override).version;
|
|
38
|
+
}
|
|
39
|
+
const row = db.prepare('SELECT version FROM atlas_fleet WHERE snapshot_id = ?').get(sid);
|
|
40
|
+
return row?.version ?? null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The population every view shares: active (non-archived) repositories that are
|
|
44
|
+
// not org meta-repos. metaRepos is a fact about the org (config.mjs for the
|
|
45
|
+
// real caller; tests pass it), so it is never hard-coded here. includeMeta
|
|
46
|
+
// keeps them in, which the summary offers so the fleet can be seen whole.
|
|
47
|
+
function activeFilter(opts) {
|
|
48
|
+
const metaRepos = opts.metaRepos ?? [];
|
|
49
|
+
const includeMeta = opts.includeMeta === true;
|
|
50
|
+
const names = includeMeta ? [] : metaRepos;
|
|
51
|
+
// `r.is_archived = 0` and NOT `<> 1`: a NULL is_archived is not a known
|
|
52
|
+
// archive, but no snapshot writes one, so the stricter form is honest.
|
|
53
|
+
const clause = `r.is_archived = 0`
|
|
54
|
+
+ (names.length ? ` AND r.name NOT IN (${names.map(() => '?').join(',')})` : '');
|
|
55
|
+
return { clause, params: names };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The fleet rollout at a glance. JSON-serializable.
|
|
60
|
+
*
|
|
61
|
+
* active = non-archived, non-meta repositories.
|
|
62
|
+
* mapped = those with a committed map on the default branch (has_atlas_map=1).
|
|
63
|
+
* missing = those known to have none (has_atlas_map=0).
|
|
64
|
+
* notCollected = those the snapshot never looked at (has_atlas_map IS NULL) --
|
|
65
|
+
* kept apart from `missing` because a snapshot before collector 1.3.0 reads
|
|
66
|
+
* as "unknown", never as "no map".
|
|
67
|
+
* byEngine groups the mapped repositories by the engine their map records,
|
|
68
|
+
* newest engine first, with the unrecorded ones last.
|
|
69
|
+
*/
|
|
70
|
+
export function atlasSummary(db, sid, opts = {}) {
|
|
71
|
+
const snap = db.prepare('SELECT org, taken_at FROM snapshot WHERE id = ?').get(sid);
|
|
72
|
+
const { clause, params } = activeFilter(opts);
|
|
73
|
+
|
|
74
|
+
const counts = db.prepare(`SELECT
|
|
75
|
+
COUNT(*) active,
|
|
76
|
+
SUM(CASE WHEN r.has_atlas_map = 1 THEN 1 ELSE 0 END) mapped,
|
|
77
|
+
SUM(CASE WHEN r.has_atlas_map = 0 THEN 1 ELSE 0 END) missing,
|
|
78
|
+
SUM(CASE WHEN r.has_atlas_map IS NULL THEN 1 ELSE 0 END) notCollected
|
|
79
|
+
FROM repo r WHERE r.snapshot_id = ? AND ${clause}`).get(sid, ...params);
|
|
80
|
+
|
|
81
|
+
// The engine of each mapped repo's map. A repo counted as mapped always has
|
|
82
|
+
// an atlas_map row (the loader writes one whenever it saw the blob); engine
|
|
83
|
+
// NULL means unrecorded. GROUP BY in SQL would fold NULLs together already,
|
|
84
|
+
// but the ordering is a semver sort, which SQL cannot do, so group here.
|
|
85
|
+
const engineRows = db.prepare(`SELECT m.engine engine, COUNT(*) repos
|
|
86
|
+
FROM atlas_map m JOIN repo r ON r.snapshot_id = m.snapshot_id AND r.name = m.repo
|
|
87
|
+
WHERE m.snapshot_id = ? AND r.has_atlas_map = 1 AND ${clause}
|
|
88
|
+
GROUP BY m.engine`).all(sid, ...params);
|
|
89
|
+
const byEngine = engineRows
|
|
90
|
+
.map(e => ({ engine: e.engine ?? UNRECORDED, repos: e.repos }))
|
|
91
|
+
.sort(engineSort(e => e.engine));
|
|
92
|
+
|
|
93
|
+
const fleetVersion = db.prepare('SELECT version FROM atlas_fleet WHERE snapshot_id = ?').get(sid)?.version ?? null;
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
sid, org: snap?.org ?? null, takenAt: snap?.taken_at ?? null,
|
|
97
|
+
fleetVersion, target: fleetTarget(db, sid, opts.target),
|
|
98
|
+
active: counts.active ?? 0, mapped: counts.mapped ?? 0,
|
|
99
|
+
missing: counts.missing ?? 0, notCollected: counts.notCollected ?? 0,
|
|
100
|
+
byEngine,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Newest-engine-first comparator over a key extractor, unrecorded/unparseable
|
|
105
|
+
// last. Shared by byEngine and the behind-rows so one definition of "newer"
|
|
106
|
+
// serves both.
|
|
107
|
+
function engineSort(key) {
|
|
108
|
+
return (a, b) => {
|
|
109
|
+
const va = parseSemver(key(a)), vb = parseSemver(key(b));
|
|
110
|
+
if (va && vb) return compareSemver(va, vb); // newest first
|
|
111
|
+
if (va) return -1;
|
|
112
|
+
if (vb) return 1;
|
|
113
|
+
return String(key(a)).localeCompare(String(key(b)));
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The active, non-meta repositories that run workflows but keep no committed
|
|
119
|
+
* map (has_atlas_map=0): the ATLAS_MAP_MISSING population, as a worklist.
|
|
120
|
+
* Ordered by repo name so two sweeps read the same.
|
|
121
|
+
*/
|
|
122
|
+
export function atlasMissing(db, sid, opts = {}) {
|
|
123
|
+
const { clause, params } = activeFilter(opts);
|
|
124
|
+
return db.prepare(`SELECT
|
|
125
|
+
r.name repo, r.primary_language, r.is_private, r.pushed_at,
|
|
126
|
+
r.days_since_push, r.workflow_count workflows
|
|
127
|
+
FROM repo r
|
|
128
|
+
WHERE r.snapshot_id = ? AND r.has_atlas_map = 0 AND ${clause}
|
|
129
|
+
ORDER BY r.name`).all(sid, ...params);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Mapped repositories whose recorded engine is OLDER than the target.
|
|
134
|
+
*
|
|
135
|
+
* Skipped, never counted as behind:
|
|
136
|
+
* - a map with `error` set: present but unread, so nothing is known about it;
|
|
137
|
+
* - a map whose engine is NULL or not semver: not comparable to the target.
|
|
138
|
+
* With no target to measure against (no fleet row, no override) the answer is
|
|
139
|
+
* empty -- there is nothing to be behind. An explicit, unparseable --target is
|
|
140
|
+
* a usage error, raised by fleetTarget before we get here.
|
|
141
|
+
*
|
|
142
|
+
* Rows are sorted oldest engine first (then repo), because the oldest is the
|
|
143
|
+
* one a pin-bump wave reaches first.
|
|
144
|
+
*/
|
|
145
|
+
export function atlasBehind(db, sid, opts = {}) {
|
|
146
|
+
const target = fleetTarget(db, sid, opts.target);
|
|
147
|
+
const tv = target ? parseSemver(target) : null;
|
|
148
|
+
if (!tv) return { target: target ?? null, rows: [] };
|
|
149
|
+
|
|
150
|
+
const { clause, params } = activeFilter(opts);
|
|
151
|
+
const maps = db.prepare(`SELECT m.repo, m.engine, m.error, r.primary_language
|
|
152
|
+
FROM atlas_map m JOIN repo r ON r.snapshot_id = m.snapshot_id AND r.name = m.repo
|
|
153
|
+
WHERE m.snapshot_id = ? AND r.has_atlas_map = 1 AND ${clause}`).all(sid, ...params);
|
|
154
|
+
|
|
155
|
+
const rows = [];
|
|
156
|
+
for (const m of maps) {
|
|
157
|
+
if (m.error) continue; // present, unread
|
|
158
|
+
const ev = parseSemver(m.engine);
|
|
159
|
+
if (!ev) continue; // null / not semver
|
|
160
|
+
if (compareSemver(ev, tv) > 0) { // engine older than target
|
|
161
|
+
rows.push({ repo: m.repo, engine: m.engine, target: tv.version, primary_language: m.primary_language });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// Oldest engine first: compareSemver sorts newest first, so negate it.
|
|
165
|
+
rows.sort((a, b) => -compareSemver(parseSemver(a.engine), parseSemver(b.engine)) || a.repo.localeCompare(b.repo));
|
|
166
|
+
return { target: tv.version, rows };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The door findings of the fleet, aggregated. Delegates the measured-population
|
|
171
|
+
* decision and the per-finding sentence to analyze.doorFindingRows, so the
|
|
172
|
+
* report and this view can never disagree about which maps are measured (only
|
|
173
|
+
* a map made by Atlas 1.24.0 or later records door checks) or what a D1/D2
|
|
174
|
+
* finding says. byRule and byRepo are roll-ups of the returned rows, which the
|
|
175
|
+
* mission wants surfaced grouped by rule code and by repository.
|
|
176
|
+
*/
|
|
177
|
+
export function atlasDoors(db, sid, opts = {}) {
|
|
178
|
+
const { clause, params } = activeFilter(opts);
|
|
179
|
+
const maps = db.prepare(`SELECT m.repo, m.engine, m.error
|
|
180
|
+
FROM atlas_map m JOIN repo r ON r.snapshot_id = m.snapshot_id AND r.name = m.repo
|
|
181
|
+
WHERE m.snapshot_id = ? AND ${clause}`).all(sid, ...params);
|
|
182
|
+
const doors = db.prepare(`SELECT d.repo, d.file, d.findings, d.unresolved_checks
|
|
183
|
+
FROM atlas_door d JOIN repo r ON r.snapshot_id = d.snapshot_id AND r.name = d.repo
|
|
184
|
+
WHERE d.snapshot_id = ? AND ${clause}`).all(sid, ...params);
|
|
185
|
+
|
|
186
|
+
const { measured, mapped, rows, unresolved } = doorFindingRows(maps, doors);
|
|
187
|
+
|
|
188
|
+
const ruleMap = new Map(); // rule -> { count, repos:Set }
|
|
189
|
+
const repoMap = new Map(); // repo -> count
|
|
190
|
+
for (const row of rows) {
|
|
191
|
+
if (!ruleMap.has(row.rule)) ruleMap.set(row.rule, { count: 0, repos: new Set() });
|
|
192
|
+
const r = ruleMap.get(row.rule);
|
|
193
|
+
r.count += 1; r.repos.add(row.repo);
|
|
194
|
+
repoMap.set(row.repo, (repoMap.get(row.repo) ?? 0) + 1);
|
|
195
|
+
}
|
|
196
|
+
const byRule = [...ruleMap].map(([rule, v]) => ({ rule, count: v.count, repos: v.repos.size }))
|
|
197
|
+
.sort((a, b) => b.count - a.count || a.rule.localeCompare(b.rule));
|
|
198
|
+
const byRepo = [...repoMap].map(([repo, count]) => ({ repo, count }))
|
|
199
|
+
.sort((a, b) => b.count - a.count || a.repo.localeCompare(b.repo));
|
|
200
|
+
|
|
201
|
+
return { measured, mapped, rows, unresolved, byRule, byRepo };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Dispatcher: always the summary, plus whichever sections the flags ask for.
|
|
206
|
+
* `mode` names the sections requested ('summary' when none), so the formatter
|
|
207
|
+
* and the caller can tell a bare summary from a full report. JSON-serializable.
|
|
208
|
+
*/
|
|
209
|
+
export function atlasView(db, sid, opts = {}) {
|
|
210
|
+
const out = { mode: 'summary', summary: atlasSummary(db, sid, opts) };
|
|
211
|
+
const parts = [];
|
|
212
|
+
if (opts.missing) { out.missing = atlasMissing(db, sid, opts); parts.push('missing'); }
|
|
213
|
+
if (opts.behind) { out.behind = atlasBehind(db, sid, opts); parts.push('behind'); }
|
|
214
|
+
if (opts.doors) { out.doors = atlasDoors(db, sid, opts); parts.push('doors'); }
|
|
215
|
+
if (parts.length) out.mode = parts.join('+');
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- rendering --------------------------------------------------------------
|
|
220
|
+
// Strings only, in the pipe-table aesthetic of mcp.asTable / cli.table. Bounded:
|
|
221
|
+
// a section shows at most ROW_CAP rows and says how many it dropped.
|
|
222
|
+
const ROW_CAP = 50;
|
|
223
|
+
|
|
224
|
+
function pipeTable(rows, cap = ROW_CAP) {
|
|
225
|
+
if (!rows.length) return '(none)';
|
|
226
|
+
const cols = Object.keys(rows[0]);
|
|
227
|
+
const shown = rows.slice(0, cap);
|
|
228
|
+
const out = [
|
|
229
|
+
cols.join(' | '),
|
|
230
|
+
cols.map(() => '---').join(' | '),
|
|
231
|
+
...shown.map(r => cols.map(c => String(r[c] ?? '').replace(/\n/g, ' ')).join(' | ')),
|
|
232
|
+
];
|
|
233
|
+
if (rows.length > shown.length) out.push(`... ${rows.length - shown.length} more`);
|
|
234
|
+
return out.join('\n');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Render an atlasView payload as text, or as JSON when opts.json is set. Pure.
|
|
239
|
+
* The JSON branch is exactly the data, so a caller can parse it back; the text
|
|
240
|
+
* branch leads with the fleet target and the mapped-vs-active headline, then
|
|
241
|
+
* each requested section under its own heading.
|
|
242
|
+
*/
|
|
243
|
+
export function formatAtlas(data, opts = {}) {
|
|
244
|
+
if (opts.json) return JSON.stringify(data, null, 2);
|
|
245
|
+
const s = data.summary;
|
|
246
|
+
const out = [];
|
|
247
|
+
out.push(`Atlas rollout — snapshot ${s.sid}${s.org ? ` (${s.org})` : ''}${s.takenAt ? ` @ ${s.takenAt}` : ''}`);
|
|
248
|
+
out.push(`fleet target engine: ${s.target ?? '(none recorded)'}`
|
|
249
|
+
+ (s.fleetVersion && s.fleetVersion !== s.target ? ` (atlas_fleet: ${s.fleetVersion})` : ''));
|
|
250
|
+
out.push(`mapped ${s.mapped} of ${s.active} active`
|
|
251
|
+
+ ` (missing ${s.missing}, not collected ${s.notCollected})`);
|
|
252
|
+
if (s.byEngine.length) {
|
|
253
|
+
out.push('');
|
|
254
|
+
out.push('By map engine:');
|
|
255
|
+
out.push(pipeTable(s.byEngine));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (data.missing) {
|
|
259
|
+
out.push('');
|
|
260
|
+
out.push(`## Missing a committed map (${data.missing.length})`);
|
|
261
|
+
out.push(pipeTable(data.missing));
|
|
262
|
+
}
|
|
263
|
+
if (data.behind) {
|
|
264
|
+
out.push('');
|
|
265
|
+
out.push(`## Map engine behind ${data.behind.target ?? '(no target)'} (${data.behind.rows.length})`);
|
|
266
|
+
out.push(pipeTable(data.behind.rows));
|
|
267
|
+
}
|
|
268
|
+
if (data.doors) {
|
|
269
|
+
const d = data.doors;
|
|
270
|
+
out.push('');
|
|
271
|
+
out.push(`## Door findings — ${d.rows.length} across ${d.measured} measured map(s) of ${d.mapped} readable`);
|
|
272
|
+
out.push('By rule:');
|
|
273
|
+
out.push(pipeTable(d.byRule));
|
|
274
|
+
out.push('');
|
|
275
|
+
out.push('By repo:');
|
|
276
|
+
out.push(pipeTable(d.byRepo));
|
|
277
|
+
if (d.rows.length) {
|
|
278
|
+
out.push('');
|
|
279
|
+
out.push('Findings:');
|
|
280
|
+
out.push(pipeTable(d.rows));
|
|
281
|
+
}
|
|
282
|
+
if (d.unresolved.length) {
|
|
283
|
+
out.push('');
|
|
284
|
+
out.push('Unresolved checks:');
|
|
285
|
+
out.push(pipeTable(d.unresolved));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return out.join('\n');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Everything in one call: build the view, render it. */
|
|
292
|
+
export function runAtlas(db, sid, opts = {}) {
|
|
293
|
+
return formatAtlas(atlasView(db, sid, opts), opts);
|
|
294
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -11,6 +11,8 @@ import { collect, DRILL_BUDGET } from './collect.mjs';
|
|
|
11
11
|
import { preflight } from './gh.mjs';
|
|
12
12
|
import { resolveOrg, loadConfig } from './config.mjs';
|
|
13
13
|
import { writeReport } from './report.mjs';
|
|
14
|
+
import { runQueue } from './queue.mjs';
|
|
15
|
+
import { runAtlas } from './atlas-view.mjs';
|
|
14
16
|
import { EXIT, HkError, userError, exitCodeFor, formatError, readOnlyQuery, sweepGaps } from './errors.mjs';
|
|
15
17
|
import { info, isDebug, levelFromFlags, parseLevel, setLevel } from './log.mjs';
|
|
16
18
|
|
|
@@ -327,6 +329,65 @@ function sql(args) {
|
|
|
327
329
|
table(rows, { max: 500 });
|
|
328
330
|
}
|
|
329
331
|
|
|
332
|
+
// Parse a command's own flags: `--name value` for the names in `valued`, and
|
|
333
|
+
// `--name` as a boolean for every other `--name`. Positional arguments come
|
|
334
|
+
// back in `rest`. The global flags (--quiet, --debug, ...) are already stripped
|
|
335
|
+
// before a command sees its args, so only command-specific flags arrive here.
|
|
336
|
+
function parseFlags(args, valued) {
|
|
337
|
+
const opts = Object.create(null), rest = [];
|
|
338
|
+
for (let i = 0; i < args.length; i++) {
|
|
339
|
+
const a = args[i];
|
|
340
|
+
if (!a.startsWith('--')) { rest.push(a); continue; }
|
|
341
|
+
const key = a.slice(2);
|
|
342
|
+
if (valued.has(key)) {
|
|
343
|
+
const v = args[++i];
|
|
344
|
+
if (v === undefined) throw userError('USAGE', `--${key} needs a value`, `e.g. --${key} <value>`);
|
|
345
|
+
opts[key] = v;
|
|
346
|
+
} else {
|
|
347
|
+
opts[key] = true;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return { opts, rest };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// hk queue: the org-wide remediation queue (src/queue.mjs). Every flag maps to
|
|
354
|
+
// a collectQueue option; metaRepos comes from the config, as every view's does.
|
|
355
|
+
// collectQueue validates --lane, --severity and --limit, so a bad value is one
|
|
356
|
+
// USAGE error shared by the CLI and the MCP tool.
|
|
357
|
+
function queue(args) {
|
|
358
|
+
const { opts } = parseFlags(args, new Set(['lane', 'category', 'severity', 'repo', 'limit']));
|
|
359
|
+
db = openDb();
|
|
360
|
+
const o = {
|
|
361
|
+
metaRepos: loadConfig().metaRepos,
|
|
362
|
+
includeMeta: opts['include-meta'] === true,
|
|
363
|
+
byLane: opts['by-lane'] === true,
|
|
364
|
+
json: opts.json === true,
|
|
365
|
+
lane: opts.lane ?? null,
|
|
366
|
+
category: opts.category ?? null,
|
|
367
|
+
severity: opts.severity ?? null,
|
|
368
|
+
repo: opts.repo ?? null,
|
|
369
|
+
};
|
|
370
|
+
if (opts.limit !== undefined) o.limit = Number(opts.limit);
|
|
371
|
+
console.log(runQueue(db, latestSid(), o));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// hk atlas: the fleet-wide Atlas rollout view (src/atlas-view.mjs). --target
|
|
375
|
+
// overrides the engine the fleet is measured against; an unparseable one is a
|
|
376
|
+
// USAGE error raised inside the module.
|
|
377
|
+
function atlas(args) {
|
|
378
|
+
const { opts } = parseFlags(args, new Set(['target']));
|
|
379
|
+
db = openDb();
|
|
380
|
+
console.log(runAtlas(db, latestSid(), {
|
|
381
|
+
metaRepos: loadConfig().metaRepos,
|
|
382
|
+
includeMeta: opts['include-meta'] === true,
|
|
383
|
+
missing: opts.missing === true,
|
|
384
|
+
behind: opts.behind === true,
|
|
385
|
+
doors: opts.doors === true,
|
|
386
|
+
target: opts.target,
|
|
387
|
+
json: opts.json === true,
|
|
388
|
+
}));
|
|
389
|
+
}
|
|
390
|
+
|
|
330
391
|
const viaReport = name => args => { db = openDb(); return REPORTS[name](latestSid(), ...args); };
|
|
331
392
|
|
|
332
393
|
const COMMANDS = {
|
|
@@ -338,7 +399,9 @@ const COMMANDS = {
|
|
|
338
399
|
repo: ['<name>', 'one repo in full, with findings', viaReport('repo')],
|
|
339
400
|
findings: ['', 'finding counts by severity, category and code', viaReport('findings')],
|
|
340
401
|
health: ['', 'per-repo health score, worst first', viaReport('health')],
|
|
402
|
+
queue: ['[--by-lane] [--json]', 'remediation queue: findings by sweep lane; filter --lane/--category/--severity/--repo/--limit', queue],
|
|
341
403
|
ci: ['', 'repos whose default branch is red', viaReport('ci')],
|
|
404
|
+
atlas: ['[--json]', 'fleet-wide Atlas rollout: --missing maps, --behind the fleet engine (--target <v>), --doors', atlas],
|
|
342
405
|
actions: ['', 'every workflow and its rule-compliance flags', viaReport('actions')],
|
|
343
406
|
cost: ['', 'Actions cost per repo, gross and net side by side', viaReport('cost')],
|
|
344
407
|
'cost-workflows': ['[repo]', 'which workflow spent the minutes', viaReport('cost-workflows')],
|
package/src/load.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { parse as parseYaml } from 'yaml';
|
|
|
9
9
|
import {
|
|
10
10
|
editsWorkflowFiles, prCreateWithDefaultToken, auditSteps,
|
|
11
11
|
pagesDeployJobs, jobEnvironment, jobRunsOnDefaultBranch, atlasCheckPins,
|
|
12
|
-
resolveFailedStep, scheduleGaps,
|
|
12
|
+
resolveFailedStep, scheduleGaps, isTagOnlyPush,
|
|
13
13
|
} from './workflow-risks.mjs';
|
|
14
14
|
import { safeJson } from './collect.mjs';
|
|
15
15
|
import { reconcileRepos } from './cost.mjs';
|
|
@@ -132,12 +132,17 @@ export function inspectWorkflow(text, path, defaultBranch = null, atlasEnv = nul
|
|
|
132
132
|
out.on_triggers = triggers.join(',');
|
|
133
133
|
out.has_workflow_dispatch = bool(triggers.includes('workflow_dispatch'));
|
|
134
134
|
|
|
135
|
-
// "paths-gated" only means anything for push/pull_request triggers.
|
|
135
|
+
// "paths-gated" only means anything for push/pull_request triggers. A push
|
|
136
|
+
// that fires on tags alone (isTagOnlyPush) is already narrowed by its tag
|
|
137
|
+
// patterns and takes no paths filter -- one would stop its tag releases from
|
|
138
|
+
// firing -- so it is not counted as an ungated push. pull_request has no tag
|
|
139
|
+
// form, so it always counts.
|
|
136
140
|
if (on && typeof on === 'object' && !Array.isArray(on)) {
|
|
137
|
-
const
|
|
138
|
-
|
|
141
|
+
const pushLike = ['push', 'pull_request'].filter(
|
|
142
|
+
t => t in on && !(t === 'push' && isTagOnlyPush(on.push)));
|
|
143
|
+
const gated = pushLike.filter(t => on[t] && typeof on[t] === 'object');
|
|
139
144
|
out.has_paths_filter = bool(
|
|
140
|
-
|
|
145
|
+
pushLike.length === 0 || gated.some(t => on[t]['paths'] || on[t]['paths-ignore'])
|
|
141
146
|
);
|
|
142
147
|
} else {
|
|
143
148
|
// `on: push` bare form is by definition ungated.
|
package/src/mcp.mjs
CHANGED
|
@@ -13,6 +13,9 @@ import { join } from 'node:path';
|
|
|
13
13
|
import { EXIT, formatError, readOnlyQuery, structured, userError } from './errors.mjs';
|
|
14
14
|
import { DATA_DIR, PACKAGE_ROOT } from './paths.mjs';
|
|
15
15
|
import { HEAD_CHECKS_RED } from './analyze.mjs';
|
|
16
|
+
import { loadConfig } from './config.mjs';
|
|
17
|
+
import { runQueue } from './queue.mjs';
|
|
18
|
+
import { runAtlas } from './atlas-view.mjs';
|
|
16
19
|
|
|
17
20
|
const DB_FILE = process.env.HK_DB || join(DATA_DIR, 'housekeeping.db');
|
|
18
21
|
const VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
|
|
@@ -24,6 +27,14 @@ if (!existsSync(DB_FILE)) {
|
|
|
24
27
|
const db = new DatabaseSync(DB_FILE, { readOnly: true });
|
|
25
28
|
const sid = () => db.prepare('SELECT MAX(id) AS id FROM snapshot').get().id;
|
|
26
29
|
|
|
30
|
+
// Meta repos are a fact about the org, read from the config exactly as the CLI
|
|
31
|
+
// reads it, so hk_queue and hk_atlas leave out non-product repositories by
|
|
32
|
+
// default. A malformed config must not take the server down for the other
|
|
33
|
+
// tools, so it falls back to the default meta repo and says so on stderr.
|
|
34
|
+
let META_REPOS = ['.github'];
|
|
35
|
+
try { META_REPOS = loadConfig().metaRepos; }
|
|
36
|
+
catch (e) { console.error(`[hk-mcp] ${formatError(e)} (using default metaRepos ${JSON.stringify(META_REPOS)})`); }
|
|
37
|
+
|
|
27
38
|
/** Render rows as a pipe table: far cheaper in tokens than pretty-printed JSON. */
|
|
28
39
|
function asTable(rows, note) {
|
|
29
40
|
if (!rows.length) return (note ? note + '\n' : '') + '(no rows)';
|
|
@@ -38,6 +49,7 @@ function asTable(rows, note) {
|
|
|
38
49
|
|
|
39
50
|
const str = (d) => ({ type: 'string', description: d });
|
|
40
51
|
const int = (d) => ({ type: 'integer', description: d });
|
|
52
|
+
const bool = (d) => ({ type: 'boolean', description: d });
|
|
41
53
|
|
|
42
54
|
const TOOLS = [
|
|
43
55
|
{
|
|
@@ -180,6 +192,56 @@ const TOOLS = [
|
|
|
180
192
|
WHERE r.snapshot_id=? AND r.is_archived=0
|
|
181
193
|
GROUP BY r.name ORDER BY penalty DESC, r.name LIMIT ?`).all(sid(), limit)),
|
|
182
194
|
},
|
|
195
|
+
{
|
|
196
|
+
name: 'hk_queue',
|
|
197
|
+
description: 'A ranked remediation queue: every finding in the newest snapshot sorted into an '
|
|
198
|
+
+ 'actionable sweep lane (security-alerts, lockfile-cves, mainline-ci, atlas-rollout, '
|
|
199
|
+
+ 'workflow-rules, pr-backlog, repo-hygiene), grouped by repository (worst severity first) or, '
|
|
200
|
+
+ 'with by_lane, by lane. Archived and meta repositories are excluded unless include_meta is set. '
|
|
201
|
+
+ 'Filter by lane, category, a minimum severity floor, or repository.',
|
|
202
|
+
inputSchema: {
|
|
203
|
+
type: 'object',
|
|
204
|
+
properties: {
|
|
205
|
+
by_lane: bool('group by lane instead of by repository'),
|
|
206
|
+
lane: str('one lane: security-alerts | lockfile-cves | mainline-ci | atlas-rollout | workflow-rules | pr-backlog | repo-hygiene'),
|
|
207
|
+
category: str('ci | security | actions | version | hygiene | metadata | docs | backlog | lifecycle | atlas'),
|
|
208
|
+
severity: str('minimum severity floor: critical | high | medium | low | info (high means critical+high)'),
|
|
209
|
+
repo: str('restrict to one repository'),
|
|
210
|
+
limit: int('max groups, default 25'),
|
|
211
|
+
include_meta: bool('include meta / non-product repositories'),
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
run: ({ by_lane, lane, category, severity, repo, limit = 25, include_meta }) =>
|
|
215
|
+
runQueue(db, sid(), {
|
|
216
|
+
metaRepos: META_REPOS, includeMeta: include_meta === true, byLane: by_lane === true,
|
|
217
|
+
lane: lane ?? null, category: category ?? null, severity: severity ?? null,
|
|
218
|
+
repo: repo ?? null, limit,
|
|
219
|
+
}),
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
name: 'hk_atlas',
|
|
223
|
+
description: 'Fleet-wide Atlas rollout from the newest snapshot: the fleet target engine, how many '
|
|
224
|
+
+ 'active repositories carry a committed map versus none, and a breakdown by engine version. '
|
|
225
|
+
+ 'Set missing to list repositories with no map, behind to list maps older than the fleet engine '
|
|
226
|
+
+ '(target overrides the version compared against), or doors to aggregate D1/D2 door findings by '
|
|
227
|
+
+ 'rule and repository.',
|
|
228
|
+
inputSchema: {
|
|
229
|
+
type: 'object',
|
|
230
|
+
properties: {
|
|
231
|
+
missing: bool('list active repositories with no committed Atlas map'),
|
|
232
|
+
behind: bool('list mapped repositories whose engine lags the fleet target'),
|
|
233
|
+
doors: bool('aggregate D1/D2 Atlas door findings by rule and repository'),
|
|
234
|
+
target: str('override the engine version compared against, e.g. 1.28.0'),
|
|
235
|
+
include_meta: bool('include meta / non-product repositories'),
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
run: ({ missing, behind, doors, target, include_meta }) =>
|
|
239
|
+
runAtlas(db, sid(), {
|
|
240
|
+
metaRepos: META_REPOS, includeMeta: include_meta === true,
|
|
241
|
+
missing: missing === true, behind: behind === true, doors: doors === true,
|
|
242
|
+
target: target ?? undefined,
|
|
243
|
+
}),
|
|
244
|
+
},
|
|
183
245
|
{
|
|
184
246
|
name: 'hk_cost',
|
|
185
247
|
description: 'GitHub Actions spend. `scope` picks the grain: "repo" (the invoice, per repo), '
|
package/src/queue.mjs
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The org-wide remediation QUEUE: every finding in the latest snapshot, sorted
|
|
3
|
+
// into the lane that would fix it and ranked so the worst repo reads first.
|
|
4
|
+
//
|
|
5
|
+
// `hk analyze` says WHAT is wrong; this says WHERE TO START. Each lane is one
|
|
6
|
+
// remediation sweep -- a batch a maintainer can pick up and close end to end,
|
|
7
|
+
// rather than a flat list of unrelated defects. The lanes are ordered by the
|
|
8
|
+
// damage left unfixed costs: an open security advisory outranks a missing
|
|
9
|
+
// CHANGELOG, so `security-alerts` sits first and `repo-hygiene` last.
|
|
10
|
+
//
|
|
11
|
+
// Read-only and pure: the module issues one SELECT per call and never writes.
|
|
12
|
+
// Given the same database state and the same options it returns byte-identical
|
|
13
|
+
// output -- no Date.now(), no randomness -- so a rebuild reproduces a queue.
|
|
14
|
+
//
|
|
15
|
+
// The ranking weights (SEV_WEIGHT) and the severity order (SEVERITIES) are
|
|
16
|
+
// imported from analyze.mjs rather than copied, so the queue's per-repo score
|
|
17
|
+
// cannot drift out of step with the health score the analyzer computes.
|
|
18
|
+
import { SEVERITIES, SEV_WEIGHT } from './analyze.mjs';
|
|
19
|
+
import { userError } from './errors.mjs';
|
|
20
|
+
|
|
21
|
+
// The lanes, in priority order. Each is a remediation SWEEP: a batch of
|
|
22
|
+
// findings that one maintainer closes with one kind of change.
|
|
23
|
+
// security-alerts open Dependabot exposure and the settings that keep it open
|
|
24
|
+
// lockfile-cves advisories the committed lockfile carries that GitHub missed
|
|
25
|
+
// mainline-ci the default branch's checks are red, or Pages/handbook is broken
|
|
26
|
+
// atlas-rollout the committed Atlas map is missing, behind, or not in CI
|
|
27
|
+
// workflow-rules a workflow breaks rules/github-actions.md (cost, shape)
|
|
28
|
+
// pr-backlog pull requests and issues piling up, conflicted or stale
|
|
29
|
+
// repo-hygiene documentation, topics, tags, releases -- the slow leaks
|
|
30
|
+
export const LANES = [
|
|
31
|
+
'security-alerts', 'lockfile-cves', 'mainline-ci', 'atlas-rollout',
|
|
32
|
+
'workflow-rules', 'pr-backlog', 'repo-hygiene',
|
|
33
|
+
];
|
|
34
|
+
const LANE_INDEX = new Map(LANES.map((l, i) => [l, i]));
|
|
35
|
+
|
|
36
|
+
// Exact code -> lane. Checked FIRST, so a code listed here never reaches the
|
|
37
|
+
// fallbacks below. Every code in a lane shares that lane's one repair.
|
|
38
|
+
const EXPLICIT = new Map(Object.entries({
|
|
39
|
+
// security-alerts
|
|
40
|
+
SECURITY_ALERTS_OPEN: 'security-alerts',
|
|
41
|
+
SECURITY_FIXES_DISABLED: 'security-alerts',
|
|
42
|
+
SECURITY_SCANNING_DISABLED: 'security-alerts',
|
|
43
|
+
SECURITY_AUDIT_GATE_DEFANGED: 'security-alerts',
|
|
44
|
+
// lockfile-cves
|
|
45
|
+
SECURITY_LOCKFILE_UNREPORTED: 'lockfile-cves',
|
|
46
|
+
SECURITY_LOCKFILE_UNREPORTED_DEV: 'lockfile-cves',
|
|
47
|
+
// mainline-ci
|
|
48
|
+
CI_RUN_FAILING: 'mainline-ci',
|
|
49
|
+
CI_FAILING: 'mainline-ci',
|
|
50
|
+
CI_PAGES_NOT_ENABLED: 'mainline-ci',
|
|
51
|
+
HANDBOOK_SIDEBAR_INCOMPATIBLE: 'mainline-ci',
|
|
52
|
+
CI_SCHEDULED_FAILING: 'mainline-ci',
|
|
53
|
+
CI_REQUIRED_CHECK_GATED: 'mainline-ci',
|
|
54
|
+
// atlas-rollout
|
|
55
|
+
ATLAS_MAP_MISSING: 'atlas-rollout',
|
|
56
|
+
ATLAS_ENGINE_BEHIND: 'atlas-rollout',
|
|
57
|
+
ATLAS_CHECK_NOT_IN_CI: 'atlas-rollout',
|
|
58
|
+
// pr-backlog
|
|
59
|
+
PR_PILEUP: 'pr-backlog',
|
|
60
|
+
PR_CONFLICTED: 'pr-backlog',
|
|
61
|
+
PR_STALE: 'pr-backlog',
|
|
62
|
+
CI_DEPENDABOT_FAILING: 'pr-backlog',
|
|
63
|
+
CI_BRANCH_FAILING: 'pr-backlog',
|
|
64
|
+
// repo-hygiene
|
|
65
|
+
NO_SECURITY: 'repo-hygiene',
|
|
66
|
+
NO_CHANGELOG: 'repo-hygiene',
|
|
67
|
+
NO_TOPICS: 'repo-hygiene',
|
|
68
|
+
NO_TRANSLATIONS: 'repo-hygiene',
|
|
69
|
+
PKG_CHECKER_NEVER_RUN: 'repo-hygiene',
|
|
70
|
+
NEVER_TAGGED: 'repo-hygiene',
|
|
71
|
+
RELEASE_MISSING: 'repo-hygiene',
|
|
72
|
+
}));
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The remediation lane a finding belongs to. Pure, total, deterministic:
|
|
76
|
+
* every (code, category) maps to exactly one member of LANES.
|
|
77
|
+
*
|
|
78
|
+
* The explicit map wins first; the ordered fallbacks then catch codes this
|
|
79
|
+
* version has not seen by name, so a finding code added to analyze.mjs later
|
|
80
|
+
* still lands in a sensible lane without a change here. `category` is only
|
|
81
|
+
* consulted after every code-prefix rule has missed.
|
|
82
|
+
*/
|
|
83
|
+
export function laneFor(code, category) {
|
|
84
|
+
const c = String(code ?? '');
|
|
85
|
+
const explicit = EXPLICIT.get(c);
|
|
86
|
+
if (explicit) return explicit;
|
|
87
|
+
// Fallbacks, first match wins. Prefix rules read the code; the last two read
|
|
88
|
+
// the category only once no prefix matched.
|
|
89
|
+
if (c.startsWith('ATLAS_')) return 'atlas-rollout';
|
|
90
|
+
if (c.startsWith('WF_') || c.startsWith('ACTIONS_COST')) return 'workflow-rules';
|
|
91
|
+
if (c.startsWith('SECURITY_LOCKFILE')) return 'lockfile-cves';
|
|
92
|
+
if (c.startsWith('SECURITY_')) return 'security-alerts';
|
|
93
|
+
if (c.startsWith('PR_') || c.startsWith('ISSUE_')) return 'pr-backlog';
|
|
94
|
+
if (category === 'backlog') return 'pr-backlog';
|
|
95
|
+
if (c.startsWith('CI_') || c.startsWith('HANDBOOK_')) return 'mainline-ci';
|
|
96
|
+
if (category === 'ci') return 'mainline-ci';
|
|
97
|
+
return 'repo-hygiene';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Severity ordinal: index in SEVERITIES (critical=0 ... info=4). A smaller
|
|
101
|
+
// ordinal is worse. `severity:'high'` keeps ordinal <= 1, i.e. critical+high.
|
|
102
|
+
const ORD = new Map(SEVERITIES.map((s, i) => [s, i]));
|
|
103
|
+
const ordOf = sev => (ORD.has(sev) ? ORD.get(sev) : SEVERITIES.length);
|
|
104
|
+
|
|
105
|
+
const isPosInt = n => Number.isInteger(n) && n > 0;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Pull every finding of snapshot `sid`, classify each into a lane, and group
|
|
109
|
+
* and rank them. Read-only: one SELECT, no writes.
|
|
110
|
+
*
|
|
111
|
+
* opts:
|
|
112
|
+
* metaRepos (array, default []) repos exempt from the queue unless includeMeta
|
|
113
|
+
* includeMeta(bool, default false) keep meta repos too
|
|
114
|
+
* lane (one of LANES) keep only this lane; else USAGE
|
|
115
|
+
* category (string) keep only this finding category
|
|
116
|
+
* repo (string) keep only this repo
|
|
117
|
+
* severity (one of SEVERITIES) minimum floor: keep ordinal <= floor; else USAGE
|
|
118
|
+
* limit (positive int, def 50) cap on the number of GROUPS; else USAGE
|
|
119
|
+
* byLane (bool) group by lane instead of by repo
|
|
120
|
+
*/
|
|
121
|
+
export function collectQueue(db, sid, opts = {}) {
|
|
122
|
+
const {
|
|
123
|
+
metaRepos = [], includeMeta = false,
|
|
124
|
+
lane = null, category = null, repo = null, severity = null,
|
|
125
|
+
byLane = false,
|
|
126
|
+
} = opts;
|
|
127
|
+
const limit = opts.limit === undefined ? 50 : opts.limit;
|
|
128
|
+
|
|
129
|
+
if (lane !== null && !LANE_INDEX.has(lane)) {
|
|
130
|
+
throw userError('USAGE', `unknown lane "${lane}"`, `one of: ${LANES.join(', ')}`);
|
|
131
|
+
}
|
|
132
|
+
if (severity !== null && !ORD.has(severity)) {
|
|
133
|
+
throw userError('USAGE', `unknown severity "${severity}"`, `one of: ${SEVERITIES.join(', ')}`);
|
|
134
|
+
}
|
|
135
|
+
if (!isPosInt(limit)) {
|
|
136
|
+
throw userError('USAGE', `limit must be a positive integer, got ${JSON.stringify(opts.limit)}`,
|
|
137
|
+
'try --limit 20');
|
|
138
|
+
}
|
|
139
|
+
const floor = severity === null ? SEVERITIES.length - 1 : ordOf(severity);
|
|
140
|
+
|
|
141
|
+
const snap = db.prepare('SELECT org, taken_at FROM snapshot WHERE id = ?').get(sid);
|
|
142
|
+
const org = snap?.org ?? null;
|
|
143
|
+
const takenAt = snap?.taken_at ?? null;
|
|
144
|
+
|
|
145
|
+
const meta = new Set(metaRepos);
|
|
146
|
+
|
|
147
|
+
// One SELECT, findings joined to their repo (same snapshot) so is_archived is
|
|
148
|
+
// known and the lane can be computed. Ordering here is not relied on -- the
|
|
149
|
+
// deterministic sort happens in JS below -- but a stable order keeps the
|
|
150
|
+
// query itself reproducible.
|
|
151
|
+
const all = db.prepare(`
|
|
152
|
+
SELECT f.repo AS repo, f.code AS code, f.severity AS severity,
|
|
153
|
+
f.category AS category, f.message AS message, f.evidence AS evidence,
|
|
154
|
+
r.is_archived AS is_archived
|
|
155
|
+
FROM finding f
|
|
156
|
+
JOIN repo r ON r.snapshot_id = f.snapshot_id AND r.name = f.repo
|
|
157
|
+
WHERE f.snapshot_id = ?
|
|
158
|
+
ORDER BY f.repo, f.code`).all(sid);
|
|
159
|
+
|
|
160
|
+
// Filter. Archived repos are always out; meta repos out unless includeMeta;
|
|
161
|
+
// then the equality filters and the severity floor.
|
|
162
|
+
const kept = [];
|
|
163
|
+
for (const row of all) {
|
|
164
|
+
if (row.is_archived === 1) continue;
|
|
165
|
+
if (!includeMeta && meta.has(row.repo)) continue;
|
|
166
|
+
const ln = laneFor(row.code, row.category);
|
|
167
|
+
if (lane !== null && ln !== lane) continue;
|
|
168
|
+
if (category !== null && row.category !== category) continue;
|
|
169
|
+
if (repo !== null && row.repo !== repo) continue;
|
|
170
|
+
if (ordOf(row.severity) > floor) continue;
|
|
171
|
+
kept.push({
|
|
172
|
+
repo: row.repo, lane: ln, severity: row.severity, code: row.code,
|
|
173
|
+
category: row.category, message: row.message, evidence: row.evidence,
|
|
174
|
+
ord: ordOf(row.severity), weight: SEV_WEIGHT[row.severity] ?? 0,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---- per-repo rollup -----------------------------------------------------
|
|
179
|
+
const repoMap = new Map();
|
|
180
|
+
for (const f of kept) {
|
|
181
|
+
let r = repoMap.get(f.repo);
|
|
182
|
+
if (!r) { r = { repo: f.repo, worstOrd: Infinity, score: 0, findings: 0, lanes: {} }; repoMap.set(f.repo, r); }
|
|
183
|
+
r.findings += 1;
|
|
184
|
+
r.score += f.weight;
|
|
185
|
+
if (f.ord < r.worstOrd) r.worstOrd = f.ord;
|
|
186
|
+
r.lanes[f.lane] = (r.lanes[f.lane] ?? 0) + 1;
|
|
187
|
+
}
|
|
188
|
+
// Ranked: worst severity ASC (lowest ordinal first), then score DESC, then name ASC.
|
|
189
|
+
const repoRank = [...repoMap.values()].sort((a, b) =>
|
|
190
|
+
a.worstOrd - b.worstOrd || b.score - a.score || a.repo.localeCompare(b.repo));
|
|
191
|
+
const repoOrder = new Map(repoRank.map((r, i) => [r.repo, i]));
|
|
192
|
+
const repos = repoRank.map(r => ({
|
|
193
|
+
repo: r.repo, worst: SEVERITIES[r.worstOrd] ?? null, score: r.score,
|
|
194
|
+
findings: r.findings,
|
|
195
|
+
// Lane counts in LANES order, so the object is deterministic.
|
|
196
|
+
lanes: orderedLanes(r.lanes),
|
|
197
|
+
}));
|
|
198
|
+
|
|
199
|
+
// ---- per-lane summary ----------------------------------------------------
|
|
200
|
+
const laneMap = new Map();
|
|
201
|
+
for (const f of kept) {
|
|
202
|
+
let l = laneMap.get(f.lane);
|
|
203
|
+
if (!l) { l = { lane: f.lane, findings: 0, repos: new Set(), critical: 0, high: 0, medium: 0, low: 0, info: 0 }; laneMap.set(f.lane, l); }
|
|
204
|
+
l.findings += 1;
|
|
205
|
+
l.repos.add(f.repo);
|
|
206
|
+
if (f.severity in l) l[f.severity] += 1;
|
|
207
|
+
}
|
|
208
|
+
const laneSummary = LANES.filter(l => laneMap.has(l)).map(l => {
|
|
209
|
+
const s = laneMap.get(l);
|
|
210
|
+
return { lane: l, findings: s.findings, repos: s.repos.size,
|
|
211
|
+
critical: s.critical, high: s.high, medium: s.medium, low: s.low, info: s.info };
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// ---- the flat, fully sorted rows ----------------------------------------
|
|
215
|
+
// repo rank, then lane order, then severity ordinal, then code.
|
|
216
|
+
const rows = kept.slice().sort((a, b) =>
|
|
217
|
+
(repoOrder.get(a.repo) - repoOrder.get(b.repo))
|
|
218
|
+
|| (LANE_INDEX.get(a.lane) - LANE_INDEX.get(b.lane))
|
|
219
|
+
|| (a.ord - b.ord)
|
|
220
|
+
|| a.code.localeCompare(b.code)
|
|
221
|
+
).map(f => ({ repo: f.repo, lane: f.lane, severity: f.severity, code: f.code,
|
|
222
|
+
category: f.category, message: f.message, evidence: f.evidence }));
|
|
223
|
+
|
|
224
|
+
// ---- groups, honouring `limit` ------------------------------------------
|
|
225
|
+
let groups, total;
|
|
226
|
+
if (byLane) {
|
|
227
|
+
const full = laneSummary.map(s => ({
|
|
228
|
+
lane: s.lane, findings: s.findings, repos: s.repos,
|
|
229
|
+
rows: rows.filter(r => r.lane === s.lane),
|
|
230
|
+
}));
|
|
231
|
+
total = full.length;
|
|
232
|
+
groups = full.slice(0, limit);
|
|
233
|
+
} else {
|
|
234
|
+
const full = repos.map(r => ({
|
|
235
|
+
repo: r.repo, worst: r.worst, score: r.score,
|
|
236
|
+
rows: rows.filter(x => x.repo === r.repo),
|
|
237
|
+
}));
|
|
238
|
+
total = full.length;
|
|
239
|
+
groups = full.slice(0, limit);
|
|
240
|
+
}
|
|
241
|
+
const truncated = groups.length < total;
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
sid, org, takenAt,
|
|
245
|
+
filters: { lane, category, severity, repo, byLane, includeMeta, limit },
|
|
246
|
+
totals: { findings: kept.length, repos: repoMap.size, lanes: laneMap.size },
|
|
247
|
+
laneSummary,
|
|
248
|
+
repos,
|
|
249
|
+
rows,
|
|
250
|
+
groups,
|
|
251
|
+
truncated,
|
|
252
|
+
shown: groups.length,
|
|
253
|
+
total,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// A lane->count object rebuilt in LANES order, dropping empty lanes.
|
|
258
|
+
function orderedLanes(counts) {
|
|
259
|
+
const out = {};
|
|
260
|
+
for (const l of LANES) if (counts[l]) out[l] = counts[l];
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---- rendering --------------------------------------------------------------
|
|
265
|
+
// Strings only; the module never prints. The aesthetic follows cli.mjs table()
|
|
266
|
+
// (padded columns) and mcp.mjs asTable() (pipe tables) so a reader sees the
|
|
267
|
+
// same shapes the rest of the tool produces.
|
|
268
|
+
|
|
269
|
+
const MSG_WIDTH = 80; // messages are clipped so a row stays on one line
|
|
270
|
+
const ROWS_PER_GROUP = 20; // a group shows at most this many rows, then "... N more"
|
|
271
|
+
const clip = (s, n = MSG_WIDTH) => {
|
|
272
|
+
const t = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
273
|
+
return t.length > n ? t.slice(0, n - 1) + '…' : t;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// A padded table in the spirit of cli.mjs table(): a header, a rule, padded
|
|
277
|
+
// cells joined by two spaces. Returns the lines (no trailing newline).
|
|
278
|
+
function padTable(cols, rows) {
|
|
279
|
+
const w = cols.map((c, i) => Math.max(c.length, ...rows.map(r => String(r[i] ?? '').length), 1));
|
|
280
|
+
const line = cells => cells.map((s, i) => String(s ?? '').padEnd(w[i])).join(' ');
|
|
281
|
+
return [line(cols), w.map(n => '-'.repeat(n)).join(' '), ...rows.map(line)].join('\n');
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Render the queue as a string. Pure.
|
|
286
|
+
* opts.json return JSON.stringify(data, null, 2) instead of the report.
|
|
287
|
+
*/
|
|
288
|
+
export function formatQueue(data, opts = {}) {
|
|
289
|
+
if (opts.json || opts.format === 'json') return JSON.stringify(data, null, 2);
|
|
290
|
+
|
|
291
|
+
const out = [];
|
|
292
|
+
const { sid, org, takenAt, totals, laneSummary, groups, filters } = data;
|
|
293
|
+
out.push(`queue: snapshot ${sid} of ${org}, taken ${takenAt}`);
|
|
294
|
+
out.push(`${totals.findings} findings across ${totals.repos} repos in ${totals.lanes} lanes`);
|
|
295
|
+
out.push('');
|
|
296
|
+
|
|
297
|
+
// The lane-summary table, every non-empty lane in priority order.
|
|
298
|
+
if (laneSummary.length) {
|
|
299
|
+
out.push(padTable(
|
|
300
|
+
['lane', 'findings', 'repos', 'crit', 'high', 'med', 'low', 'info'],
|
|
301
|
+
laneSummary.map(s => [s.lane, s.findings, s.repos, s.critical, s.high, s.medium, s.low, s.info]),
|
|
302
|
+
));
|
|
303
|
+
out.push('');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Per-group blocks.
|
|
307
|
+
for (const g of groups) {
|
|
308
|
+
if (filters.byLane) {
|
|
309
|
+
out.push(`## ${g.lane} (${g.findings} findings, ${g.repos} repos)`);
|
|
310
|
+
const rows = g.rows.slice(0, ROWS_PER_GROUP);
|
|
311
|
+
out.push(padTable(['repo', 'severity', 'code', 'message'],
|
|
312
|
+
rows.map(r => [r.repo, r.severity, r.code, clip(r.message)])));
|
|
313
|
+
if (g.rows.length > rows.length) out.push(`... ${g.rows.length - rows.length} more`);
|
|
314
|
+
} else {
|
|
315
|
+
out.push(`## ${g.repo} score ${g.score}, worst ${g.worst}`);
|
|
316
|
+
const rows = g.rows.slice(0, ROWS_PER_GROUP);
|
|
317
|
+
out.push(padTable(['severity', 'lane', 'code', 'message'],
|
|
318
|
+
rows.map(r => [r.severity, r.lane, r.code, clip(r.message)])));
|
|
319
|
+
if (g.rows.length > rows.length) out.push(`... ${g.rows.length - rows.length} more`);
|
|
320
|
+
}
|
|
321
|
+
out.push('');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (data.truncated) out.push(`... ${data.total - data.shown} more ${filters.byLane ? 'lanes' : 'repos'}`);
|
|
325
|
+
|
|
326
|
+
return out.join('\n').replace(/\n+$/, '\n');
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The one call the CLI/MCP make: collect then format. */
|
|
330
|
+
export function runQueue(db, sid, opts = {}) {
|
|
331
|
+
return formatQueue(collectQueue(db, sid, opts), opts);
|
|
332
|
+
}
|
package/src/workflow-risks.mjs
CHANGED
|
@@ -263,6 +263,23 @@ export function filterMatches(patterns, branch) {
|
|
|
263
263
|
return unknown ? null : 0;
|
|
264
264
|
}
|
|
265
265
|
|
|
266
|
+
/**
|
|
267
|
+
* A `push:` trigger that fires on tags alone: it declares `tags`/`tags-ignore`
|
|
268
|
+
* and neither `branches` nor `branches-ignore`, so GitHub starts it only for a
|
|
269
|
+
* tag push and never for a branch push. A bare `push:` (null, `true`, or an
|
|
270
|
+
* empty map) fires on every branch and is NOT this.
|
|
271
|
+
*
|
|
272
|
+
* Such a trigger is already narrowed by its tag patterns, so the paths rule has
|
|
273
|
+
* nothing to say about it: a `paths:` filter would stop its tag releases from
|
|
274
|
+
* firing at all -- paths is a change filter and a tag push carries no changed
|
|
275
|
+
* file it can read -- which is why a tag-only push is not an ungated push.
|
|
276
|
+
*/
|
|
277
|
+
export function isTagOnlyPush(push) {
|
|
278
|
+
if (push == null || push === true || typeof push !== 'object' || Array.isArray(push)) return false;
|
|
279
|
+
if ('branches' in push || 'branches-ignore' in push) return false;
|
|
280
|
+
return 'tags' in push || 'tags-ignore' in push;
|
|
281
|
+
}
|
|
282
|
+
|
|
266
283
|
/**
|
|
267
284
|
* Can a push to `branch` start this workflow? 1, 0 or null.
|
|
268
285
|
*
|
|
@@ -274,9 +291,7 @@ export function filterMatches(patterns, branch) {
|
|
|
274
291
|
export function pushAdmitsBranch(push, branch) {
|
|
275
292
|
if (push == null || push === true || typeof push !== 'object' || Array.isArray(push)) return 1;
|
|
276
293
|
const hasBranches = 'branches' in push, hasIgnore = 'branches-ignore' in push;
|
|
277
|
-
if (!hasBranches && !hasIgnore)
|
|
278
|
-
return ('tags' in push || 'tags-ignore' in push) ? 0 : 1;
|
|
279
|
-
}
|
|
294
|
+
if (!hasBranches && !hasIgnore) return isTagOnlyPush(push) ? 0 : 1;
|
|
280
295
|
if (hasBranches) return filterMatches(push.branches, branch);
|
|
281
296
|
const ignored = filterMatches(push['branches-ignore'], branch);
|
|
282
297
|
return ignored === null ? null : ignored === 1 ? 0 : 1;
|