@mcptoolshop/housekeeping 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "org": "your-org",
3
3
  "metaRepos": [".github"],
4
- "homeOrgs": ["your-org"]
4
+ "homeOrgs": ["your-org"],
5
+ "watch": []
5
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcptoolshop/housekeeping",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
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
- const SEV_WEIGHT = { critical: 40, high: 15, medium: 6, low: 2, info: 0 };
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
@@ -9,8 +9,10 @@ import { openDb, loadSnapshot, latestSnapshotFile, DB_PATH } from './load.mjs';
9
9
  import { analyze, healthScores, RUN_IS_LIVE_MAINLINE_SIGNAL, HEAD_CHECKS_RED } from './analyze.mjs';
10
10
  import { collect, DRILL_BUDGET } from './collect.mjs';
11
11
  import { preflight } from './gh.mjs';
12
- import { resolveOrg } from './config.mjs';
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
 
@@ -141,6 +143,35 @@ const REPORTS = {
141
143
  disk_usage_kb kb, days_since_push push_age, open_issues iss, open_prs prs,
142
144
  release_count rels, ci_rollup, workflow_count wfs
143
145
  FROM repo WHERE snapshot_id=? ORDER BY name`).all(sid), { max: 200 }),
146
+ // Branches by repo: what a cleanup would delete (merged), what it must not
147
+ // (merged_moved: commits after the merge), and what has no PR at all.
148
+ branches: (sid, repo) => {
149
+ if (!db.prepare('SELECT 1 FROM repo_branches WHERE snapshot_id=? LIMIT 1').get(sid)) {
150
+ return console.log('no branch data in this snapshot (collector 1.6.0 or later) - run `hk refresh`');
151
+ }
152
+ if (repo) {
153
+ return table(db.prepare(`SELECT name, state, age_days age, pr_number pr, SUBSTR(head_oid,1,7) head
154
+ FROM branch WHERE snapshot_id=? AND repo=? ORDER BY state, age_days DESC`).all(sid, repo), { max: 500 });
155
+ }
156
+ table(db.prepare(`SELECT s.repo, CASE s.delete_on_merge WHEN 1 THEN 'on' WHEN 0 THEN 'off' END auto_delete,
157
+ s.branch_count branches,
158
+ SUM(b.state='merged') merged, SUM(b.state='merged_moved') moved,
159
+ SUM(b.state='closed') closed, SUM(b.state='no_pr' AND b.age_days>=${STALE_BRANCH_DAYS}) no_pr_stale,
160
+ SUM(b.state IN ('open_pr','open_base')) open
161
+ FROM repo_branches s LEFT JOIN branch b ON b.snapshot_id=s.snapshot_id AND b.repo=s.repo
162
+ WHERE s.snapshot_id=? GROUP BY s.repo HAVING s.branch_count > 1
163
+ ORDER BY merged + moved + closed + no_pr_stale DESC, s.repo`).all(sid), { max: 200 });
164
+ },
165
+ watch: (sid, ...names) => {
166
+ const repos = names.length ? names : loadConfig().watch;
167
+ if (!repos.length) {
168
+ throw userError('USAGE', 'no repositories to watch',
169
+ 'name them (hk watch <repo> ...) or set "watch" in housekeeping.config.json');
170
+ }
171
+ const s = db.prepare('SELECT taken_at, collector_version FROM snapshot WHERE id=?').get(sid);
172
+ console.log(`watch: ${repos.join(', ')}\nsnapshot ${sid}, taken ${s.taken_at} (collector ${s.collector_version})`);
173
+ for (const name of repos) watchRepo(sid, name);
174
+ },
144
175
  repo: (sid, name) => {
145
176
  if (!name) throw userError('USAGE', '`hk repo` needs a repository name', 'hk repo <name>');
146
177
  table(db.prepare('SELECT * FROM repo WHERE snapshot_id=? AND name=?').all(sid, name));
@@ -155,6 +186,56 @@ const REPORTS = {
155
186
 
156
187
  function latestOr(sid) { return sid; }
157
188
 
189
+ // A branch with no PR and no commit for this long is listed as stale. The
190
+ // number is the Publisher's sweep brief of 2026-10-11, not an org rule.
191
+ const STALE_BRANCH_DAYS = 7;
192
+
193
+ // One watched repo: open PRs by idle time, open alerts, and the branches a
194
+ // cleanup would touch. Every section says when it was not measured, because
195
+ // an empty list from an unscanned repo reads exactly like a clean one.
196
+ function watchRepo(sid, name) {
197
+ const r = db.prepare('SELECT is_archived FROM repo WHERE snapshot_id=? AND name=?').get(sid, name);
198
+ console.log(`\n== ${name}`);
199
+ if (!r) return console.log('not in this snapshot (misspelt, or not in the org)');
200
+ if (r.is_archived) console.log('archived');
201
+
202
+ const prs = db.prepare(`SELECT number, stale_days idle, age_days age, is_draft draft, mergeable,
203
+ base_ref base, head_ref head, SUBSTR(title,1,60) title
204
+ FROM pull_request WHERE snapshot_id=? AND repo=? ORDER BY stale_days DESC, number`).all(sid, name);
205
+ console.log(`\n-- open PRs (${prs.length}), longest idle first --`);
206
+ table(prs);
207
+
208
+ const sec = db.prepare('SELECT vuln_alerts FROM repo_security WHERE snapshot_id=? AND repo=?').get(sid, name);
209
+ console.log('\n-- open Dependabot alerts --');
210
+ if (!sec) console.log('not measured (the security pass did not read this repo)');
211
+ else if (sec.vuln_alerts === 0) console.log('NOT SCANNED: vulnerability alerts are off, so no alert can appear');
212
+ else {
213
+ if (sec.vuln_alerts === null) console.log('(whether alerts are on could not be read)');
214
+ table(db.prepare(`SELECT number, severity, package, manifest, fixed_version fix, age_days age, ghsa
215
+ FROM security_alert WHERE snapshot_id=? AND repo=?
216
+ ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END, number`)
217
+ .all(sid, name));
218
+ }
219
+
220
+ const set = db.prepare('SELECT delete_on_merge, branch_count FROM repo_branches WHERE snapshot_id=? AND repo=?').get(sid, name);
221
+ console.log('\n-- branches --');
222
+ if (!set) return console.log('not measured (no branch data for this repo in this snapshot)');
223
+ const auto = set.delete_on_merge === 1 ? 'on' : set.delete_on_merge === 0 ? 'off' : 'unknown';
224
+ const rows = db.prepare(`SELECT name, state, age_days age, pr_number pr, SUBSTR(head_oid,1,7) head
225
+ FROM branch WHERE snapshot_id=? AND repo=? ORDER BY name`).all(sid, name);
226
+ const of = st => rows.filter(b => b.state === st);
227
+ const stale = of('no_pr').filter(b => b.age_days >= STALE_BRANCH_DAYS);
228
+ console.log(`${set.branch_count} branches; auto-delete head branches: ${auto}; ` +
229
+ `open ${of('open_pr').length + of('open_base').length}, merged ${of('merged').length}, ` +
230
+ `moved after merge ${of('merged_moved').length}, closed ${of('closed').length}, ` +
231
+ `no PR ${of('no_pr').length} (${stale.length} idle ${STALE_BRANCH_DAYS}+ days)`);
232
+ const list = (label, bs) => { if (bs.length) { console.log(`\n${label}:`); table(bs); } };
233
+ list('merged, tip = merged head (deletable; restorable from the PR page)', of('merged'));
234
+ list('MOVED after merge (commits exist only here; do not delete unconfirmed)', of('merged_moved'));
235
+ list('closed without merging', of('closed'));
236
+ list(`no PR, idle ${STALE_BRANCH_DAYS}+ days`, stale);
237
+ }
238
+
158
239
  // ---- commands ---------------------------------------------------------------
159
240
  // One table drives both the dispatch and `hk help`, so the help text cannot
160
241
  // describe a command that does not exist or omit one that does.
@@ -178,7 +259,9 @@ async function refresh(args) {
178
259
  // silently.
179
260
  const pre = await preflight({
180
261
  rest: 300 + Math.min(DRILL_BUDGET, 900),
181
- graphql: 300,
262
+ // ~195 for the repo pages and workflow files, ~1 per repo for the
263
+ // branch pass (collector 1.6.0, measured 2026-10-11), with headroom.
264
+ graphql: 450,
182
265
  });
183
266
  if (!pre.ok && !force) {
184
267
  if (pre.limit === 'secondary') {
@@ -246,6 +329,65 @@ function sql(args) {
246
329
  table(rows, { max: 500 });
247
330
  }
248
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
+
249
391
  const viaReport = name => args => { db = openDb(); return REPORTS[name](latestSid(), ...args); };
250
392
 
251
393
  const COMMANDS = {
@@ -257,7 +399,9 @@ const COMMANDS = {
257
399
  repo: ['<name>', 'one repo in full, with findings', viaReport('repo')],
258
400
  findings: ['', 'finding counts by severity, category and code', viaReport('findings')],
259
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],
260
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],
261
405
  actions: ['', 'every workflow and its rule-compliance flags', viaReport('actions')],
262
406
  cost: ['', 'Actions cost per repo, gross and net side by side', viaReport('cost')],
263
407
  'cost-workflows': ['[repo]', 'which workflow spent the minutes', viaReport('cost-workflows')],
@@ -265,6 +409,8 @@ const COMMANDS = {
265
409
  versions: ['', 'package.json against git tag against npm', viaReport('versions')],
266
410
  prs: ['', 'every open pull request by age', viaReport('prs')],
267
411
  issues: ['', 'every open issue by staleness', viaReport('issues')],
412
+ branches: ['[repo]', 'branches by state: merged, moved after merge, closed, no PR', viaReport('branches')],
413
+ watch: ['[repo ...]', 'open PRs, alerts and branches for the watch list in the config', viaReport('watch')],
268
414
  snapshots: ['', 'the snapshots loaded into the database', () => {
269
415
  db = openDb();
270
416
  table(db.prepare('SELECT id, taken_at, org, repo_count, duration_ms FROM snapshot ORDER BY id').all());
package/src/collect.mjs CHANGED
@@ -14,7 +14,7 @@ import { priceRun, ratesFromUsage, withFallback, runnerClass } from './cost.mjs'
14
14
  import { pagesDeployJobs, jobEnvironment } from './workflow-risks.mjs';
15
15
  import { DATA_DIR } from './paths.mjs';
16
16
 
17
- export const COLLECTOR_VERSION = '1.5.0';
17
+ export const COLLECTOR_VERSION = '1.6.0';
18
18
 
19
19
  const REPO_FIELDS = `
20
20
  id name description url homepageUrl
@@ -622,7 +622,7 @@ function readAtlasCache() {
622
622
  */
623
623
  async function atlasFleetVersion(fetchImpl = fetch) {
624
624
  try {
625
- const res = await fetchImpl(`https://registry.npmjs.org/${ATLAS_PACKAGE.replace('/', '%2f')}`, {
625
+ const res = await fetchImpl(`https://registry.npmjs.org/${encodeURIComponent(ATLAS_PACKAGE)}`, {
626
626
  headers: { accept: 'application/vnd.npm.install-v1+json' }, signal: AbortSignal.timeout(30_000),
627
627
  });
628
628
  if (!res.ok) return { version: null, source: 'npm dist-tags latest', error: `http_${res.status}` };
@@ -694,7 +694,7 @@ async function collectNpm(repos, concurrency = 12) {
694
694
  .filter(x => x.pkg && x.pkg.name && !x.pkg.private);
695
695
 
696
696
  const results = await pMap(named, async x => {
697
- const res = await fetch(`https://registry.npmjs.org/${x.pkg.name.replace('/', '%2f')}`, {
697
+ const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(x.pkg.name)}`, {
698
698
  headers: { accept: 'application/vnd.npm.install-v1+json' },
699
699
  });
700
700
  if (res.status === 404) return { repo: x.repo, pkg_name: x.pkg.name, status: 'unpublished' };
@@ -817,6 +817,74 @@ async function collectSecurity(org, repos, concurrency = 10) {
817
817
  return { ok: alertsOk, alerts, auto_security_fixes: fixes, vulnerability_alerts: scanned };
818
818
  }
819
819
 
820
+ // Every branch, the pull requests it was the head of, and whether the repo
821
+ // deletes a head branch when its pull request merges.
822
+ //
823
+ // A merged PR's branch is restorable from the PR page only while its tip is
824
+ // the commit the PR merged; a branch pushed to after its merge carries work
825
+ // that exists nowhere else. So the head commit is kept beside each PR's
826
+ // headRefOid, and the loader tells the two apart.
827
+ //
828
+ // Cost: one GraphQL query per non-archived, non-empty repo, plus one per
829
+ // further 100 branches. Measured 2026-10-11 by rateLimit(dryRun): 1 point per
830
+ // repo at first:100 with five associated PRs per branch (8 repos: 8 points).
831
+ const BRANCH_QUERY = `
832
+ query($owner:String!, $name:String!, $cursor:String) {
833
+ repository(owner:$owner, name:$name) {
834
+ deleteBranchOnMerge
835
+ refs(refPrefix:"refs/heads/", first:100, after:$cursor) {
836
+ totalCount
837
+ pageInfo { hasNextPage endCursor }
838
+ nodes {
839
+ name
840
+ target { ... on Commit { oid committedDate } }
841
+ associatedPullRequests(first:5, orderBy:{field:UPDATED_AT, direction:DESC}) {
842
+ nodes { number state headRefOid }
843
+ }
844
+ }
845
+ }
846
+ }
847
+ }`;
848
+
849
+ export async function collectBranches(org, repos, { query = graphql, concurrency = 6 } = {}) {
850
+ const out = {};
851
+ const errors = [];
852
+ const targets = repos.filter(r => !r.isArchived && !r.isEmpty);
853
+ await pMap(targets, async r => {
854
+ const branches = [];
855
+ let cursor = null, total = 0, deleteOnMerge = null;
856
+ try {
857
+ for (;;) {
858
+ const body = await query(BRANCH_QUERY, { owner: org, name: r.name, cursor });
859
+ const repo = body.data?.repository;
860
+ if (!repo) throw new Error('repository not visible');
861
+ deleteOnMerge = repo.deleteBranchOnMerge ?? null;
862
+ total = repo.refs?.totalCount ?? 0;
863
+ for (const b of repo.refs?.nodes ?? []) {
864
+ branches.push({
865
+ name: b.name,
866
+ oid: b.target?.oid ?? null,
867
+ committed_at: b.target?.committedDate ?? null,
868
+ prs: (b.associatedPullRequests?.nodes ?? []).map(p => ({
869
+ number: p.number, state: p.state, head_oid: p.headRefOid ?? null,
870
+ })),
871
+ });
872
+ }
873
+ cursor = repo.refs?.pageInfo?.hasNextPage ? repo.refs.pageInfo.endCursor : null;
874
+ if (!cursor) break;
875
+ }
876
+ out[r.name] = { delete_branch_on_merge: deleteOnMerge, total, branches };
877
+ } catch (e) {
878
+ // A repo that could not be read gets no record at all, never an empty
879
+ // one: no branches would read as "nothing to clean up".
880
+ errors.push({ repo: r.name, stage: 'branches', message: String(e.message ?? e).slice(0, 200) });
881
+ }
882
+ }, concurrency);
883
+ const n = Object.values(out).reduce((s, x) => s + x.branches.length, 0);
884
+ log(`branches: ${n} in ${Object.keys(out).length} repos, ${errors.length} unreadable`);
885
+ return { ok: errors.length === 0, repos: out, errors };
886
+ }
887
+
820
888
  // ---------------------------------------------------------------------------
821
889
  // Committed lockfiles, audited by the warehouse itself. See lockfile.mjs for
822
890
  // why GitHub's own count cannot be trusted per manifest.
@@ -1097,6 +1165,7 @@ async function sweep(org, ctx) {
1097
1165
  ctx.stage = 'deploy_settings'; const deploySettings = await collectDeploySettings(org, repos, workflowFiles);
1098
1166
  ctx.stage = 'npm'; const npm = await collectNpm(repos);
1099
1167
  ctx.stage = 'security'; const security = await collectSecurity(org, repos);
1168
+ ctx.stage = 'branches'; const branches = await collectBranches(org, repos);
1100
1169
  ctx.stage = 'lockfiles'; const lockfiles = await collectLockfiles(org, repos);
1101
1170
  ctx.stage = 'atlas_maps'; const atlasMaps = await collectAtlasMaps(org, repos);
1102
1171
  ctx.stage = 'billing'; const billing = await collectBilling(org);
@@ -1121,13 +1190,14 @@ async function sweep(org, ctx) {
1121
1190
  deploy_settings: { ok: deploySettings.ok, calls: deploySettings.calls, repos: deploySettings.repos },
1122
1191
  npm,
1123
1192
  security,
1193
+ branches: { ok: branches.ok, repos: branches.repos },
1124
1194
  lockfiles,
1125
1195
  // fetched/cached counts are left out: they describe this machine's cache,
1126
1196
  // not the org, and would make two identical observations look different.
1127
1197
  atlas_maps: { ok: atlasMaps.ok, fleet_version: atlasMaps.fleet_version, repos: atlasMaps.repos },
1128
1198
  billing,
1129
1199
  run_costs: runCosts,
1130
- errors: errors.concat(deploySettings.errors ?? [], runCosts.errors ?? [],
1200
+ errors: errors.concat(deploySettings.errors ?? [], runCosts.errors ?? [], branches.errors,
1131
1201
  failedSteps.runs.filter(x => x.error).map(x => ({ repo: x.repo, stage: 'failed_steps', message: x.error }))),
1132
1202
  };
1133
1203