@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.
package/src/config.mjs CHANGED
@@ -8,12 +8,17 @@
8
8
  //
9
9
  // housekeeping.config.json
10
10
  // { "org": "your-org", "metaRepos": [".github", "design-assets"],
11
- // "homeOrgs": ["your-org", "your-other-org"] }
11
+ // "homeOrgs": ["your-org", "your-other-org"],
12
+ // "watch": ["repo-a", "repo-b"] }
12
13
  //
13
14
  // `homeOrgs` names the organizations whose projects count as the org's own.
14
15
  // A fork of a project outside them is exempt from the map rule. Unset, it is
15
16
  // the swept org alone.
16
17
  //
18
+ // `watch` names the repos `hk watch` reports on when it is given none: a short
19
+ // list someone reviews every week. It narrows a view, never the sweep, and
20
+ // changes no finding.
21
+ //
17
22
  // No network and no database here, so every branch is unit-testable.
18
23
  import { readFileSync } from 'node:fs';
19
24
  import { join } from 'node:path';
@@ -22,7 +27,7 @@ import { WORK_DIR } from './paths.mjs';
22
27
 
23
28
  export const CONFIG_PATH = process.env.HK_CONFIG ?? join(WORK_DIR, 'housekeeping.config.json');
24
29
 
25
- const KEYS = ['org', 'metaRepos', 'homeOrgs'];
30
+ const KEYS = ['org', 'metaRepos', 'homeOrgs', 'watch'];
26
31
  const invalid = message => userError('CONFIG_INVALID', message,
27
32
  'fix housekeeping.config.json; housekeeping.config.example.json shows the shape');
28
33
  const DEFAULT_META = ['.github'];
@@ -56,7 +61,11 @@ export function parseConfig(text) {
56
61
  if (home !== null && (!Array.isArray(home) || !home.length || home.some(o => typeof o !== 'string' || !o.trim()))) {
57
62
  throw invalid('housekeeping config: "homeOrgs" must be a non-empty array of organization names');
58
63
  }
59
- return { org, metaRepos: [...meta], homeOrgs: home ? [...home] : null };
64
+ const watch = raw.watch ?? [];
65
+ if (!Array.isArray(watch) || watch.some(w => typeof w !== 'string' || !w.trim())) {
66
+ throw invalid('housekeeping config: "watch" must be an array of repo names');
67
+ }
68
+ return { org, metaRepos: [...meta], homeOrgs: home ? [...home] : null, watch: [...watch] };
60
69
  }
61
70
 
62
71
  /** Read the config file. A missing file is the defaults; an unreadable or malformed one throws. */
@@ -64,7 +73,7 @@ export function loadConfig(path = CONFIG_PATH) {
64
73
  let text;
65
74
  try { text = readFileSync(path, 'utf8'); }
66
75
  catch (e) {
67
- if (e.code === 'ENOENT') return { org: null, metaRepos: [...DEFAULT_META], homeOrgs: null };
76
+ if (e.code === 'ENOENT') return { org: null, metaRepos: [...DEFAULT_META], homeOrgs: null, watch: [] };
68
77
  throw e;
69
78
  }
70
79
  return parseConfig(text);
package/src/load.mjs CHANGED
@@ -103,8 +103,10 @@ export function openDb(path = DB_PATH, { fresh = false } = {}) {
103
103
  *
104
104
  * `atlasEnv` maps a job key to the `environment` the repository's Atlas map
105
105
  * records for it (Atlas 1.24.0 and later), when the map has this file.
106
+ * `isPrivate` is the repository's visibility, which decides whether a job
107
+ * gated to public repositories can run at all.
106
108
  */
107
- export function inspectWorkflow(text, path, defaultBranch = null, atlasEnv = null) {
109
+ export function inspectWorkflow(text, path, defaultBranch = null, atlasEnv = null, isPrivate = false) {
108
110
  const out = {
109
111
  path, name: path.split('/').pop(), state: 'unknown',
110
112
  has_paths_filter: 0, has_workflow_dispatch: 0, has_concurrency: 0,
@@ -197,7 +199,7 @@ export function inspectWorkflow(text, path, defaultBranch = null, atlasEnv = nul
197
199
  out.schedule_gaps = gaps ? gaps.join('\n') : null;
198
200
 
199
201
  // The deploy doors, joined in analyze.mjs to the settings they depend on.
200
- out.pages_deploy_jobs = pagesDeployJobs(jobEntries).join('\n');
202
+ out.pages_deploy_jobs = pagesDeployJobs(jobEntries, { isPrivate }).join('\n');
201
203
  // The environment a job deploys to is a fact Atlas also records, so where
202
204
  // the map names one it is preferred: one definition for both tools. This
203
205
  // file's own reading is kept beside it, so a disagreement stays visible.
@@ -467,6 +469,38 @@ export function failedStepRows(record, text) {
467
469
  return rows;
468
470
  }
469
471
 
472
+ /**
473
+ * Classify one repo's branches (schema.sql, table `branch`). Pure.
474
+ *
475
+ * Order matters, and each step was a real case on 2026-10-11:
476
+ * - an open PR beats a merged one: a branch reused for a second PR is live;
477
+ * - being an open PR's BASE beats being merged: a stacked PR targets it, and
478
+ * deleting it would retarget or close that PR;
479
+ * - "merged" needs the tip to equal the merged head. Four branches had commits
480
+ * pushed after their PR merged, which the PR page's restore cannot bring back.
481
+ */
482
+ export function branchRows(record, { defaultBranch = null, openBases = [] } = {}) {
483
+ const bases = new Set(openBases);
484
+ const rows = [];
485
+ for (const b of record?.branches ?? []) {
486
+ if (b.name === defaultBranch) continue;
487
+ const prs = b.prs ?? [];
488
+ const open = prs.find(p => p.state === 'OPEN');
489
+ const merged = prs.filter(p => p.state === 'MERGED');
490
+ const exact = merged.find(p => p.head_oid && p.head_oid === b.oid);
491
+ let state, pr = null;
492
+ if (open) { state = 'open_pr'; pr = open.number; }
493
+ else if (bases.has(b.name)) state = 'open_base';
494
+ else if (exact) { state = 'merged'; pr = exact.number; }
495
+ else if (merged.length) { state = 'merged_moved'; pr = merged[0].number; }
496
+ else if (prs.length) { state = 'closed'; pr = prs[0].number; }
497
+ else state = 'no_pr';
498
+ rows.push({ name: b.name, state, head_oid: b.oid ?? null,
499
+ committed_at: b.committed_at ?? null, age_days: daysSince(b.committed_at), pr_number: pr });
500
+ }
501
+ return rows;
502
+ }
503
+
470
504
  export function isWorkspaceRoot(pkg, rootEntryNames = [], pnpmWorkspaceText) {
471
505
  if (pkg?.workspaces) return true;
472
506
  const names = new Set(rootEntryNames.map(n => String(n).toLowerCase()));
@@ -542,6 +576,8 @@ function loadSnapshotInner(db, snap) {
542
576
  lock: insertInto('lockfile'),
543
577
  lockAdv: insertInto('lockfile_advisory'),
544
578
  bprot: insertInto('branch_protection'),
579
+ branch: insertInto('branch'),
580
+ repoBranches: insertInto('repo_branches'),
545
581
  ctx: insertInto('check_context'),
546
582
  bill: insertInto('billing_usage'),
547
583
  runCost: insertInto('run_cost'),
@@ -692,7 +728,7 @@ function loadSnapshotInner(db, snap) {
692
728
  const atlasEnvByFile = new Map(mapDoors.filter(d => Array.isArray(d.jobs)).map(d => [d.file,
693
729
  new Map(d.jobs.filter(j => j && typeof j.name === 'string' && j.environment).map(j => [j.name, j.environment]))]));
694
730
  for (const f of wfFiles) {
695
- const w = inspectWorkflow(f.text, f.path, r.defaultBranchRef?.name ?? null, atlasEnvByFile.get(f.path) ?? null);
731
+ const w = inspectWorkflow(f.text, f.path, r.defaultBranchRef?.name ?? null, atlasEnvByFile.get(f.path) ?? null, !!r.isPrivate);
696
732
  stmts.wf.run(sid, r.name, w.path, w.name, w.state,
697
733
  w.has_paths_filter, w.has_workflow_dispatch, w.has_concurrency,
698
734
  w.runners, w.uses_macos, w.uses_windows,
@@ -791,6 +827,22 @@ function loadSnapshotInner(db, snap) {
791
827
  }
792
828
  }
793
829
 
830
+ // ---- branches ------------------------------------------------------------
831
+ // Absent `branches` (an older snapshot) or a repo missing from it (archived,
832
+ // empty, unreadable) leaves no rows: not measured, never "nothing to clean".
833
+ if (snap.branches) {
834
+ for (const r of snap.repos) {
835
+ const rec = snap.branches.repos?.[r.name];
836
+ if (!rec) continue;
837
+ stmts.repoBranches.run(sid, r.name,
838
+ rec.delete_branch_on_merge === null ? null : bool(rec.delete_branch_on_merge), rec.total ?? null);
839
+ const openBases = (r.prList?.nodes ?? []).map(p => p.baseRefName).filter(Boolean);
840
+ for (const b of branchRows(rec, { defaultBranch: r.defaultBranchRef?.name ?? null, openBases })) {
841
+ stmts.branch.run(sid, r.name, b.name, b.state, b.head_oid, b.committed_at, b.age_days, b.pr_number);
842
+ }
843
+ }
844
+ }
845
+
794
846
  // ---- committed lockfiles, audited directly ------------------------------
795
847
  // Absent `lockfiles` means the pass did not run (older snapshot): no rows,
796
848
  // and the analyzer stays silent rather than reporting zero exposure.
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/schema.sql CHANGED
@@ -371,6 +371,31 @@ CREATE TABLE IF NOT EXISTS cost_reconciliation (
371
371
  ratio REAL, trustworthy INTEGER, reason TEXT
372
372
  );
373
373
 
374
+ -- One row per non-default branch (collect.mjs collectBranches). `state` is
375
+ -- decided at load time (load.mjs branchRows), first match wins:
376
+ -- open_pr the head of an open pull request
377
+ -- open_base the base of an open pull request (a stacked PR targets it)
378
+ -- merged its PR merged and the tip IS the merged head: restorable
379
+ -- from the PR page, so deleting it loses nothing
380
+ -- merged_moved its PR merged, but the tip moved after: those commits exist
381
+ -- only on this branch
382
+ -- closed only closed, unmerged pull requests
383
+ -- no_pr never the head of a pull request
384
+ -- Data, not findings: no org rule names stale branches. No rows for a repo
385
+ -- means not measured (archived, empty, unreadable, or an older snapshot).
386
+ CREATE TABLE IF NOT EXISTS branch (
387
+ snapshot_id INTEGER, repo TEXT, name TEXT, state TEXT,
388
+ head_oid TEXT, committed_at TEXT, age_days INTEGER,
389
+ pr_number INTEGER -- the PR the state was decided by, if any
390
+ );
391
+
392
+ -- Per-repo branch settings, one row per repo the branch pass read.
393
+ CREATE TABLE IF NOT EXISTS repo_branches (
394
+ snapshot_id INTEGER, repo TEXT,
395
+ delete_on_merge INTEGER, -- "Automatically delete head branches": 1 on, 0 off
396
+ branch_count INTEGER -- every branch, the default included
397
+ );
398
+
374
399
  CREATE TABLE IF NOT EXISTS finding (
375
400
  snapshot_id INTEGER, repo TEXT, code TEXT, severity TEXT,
376
401
  category TEXT, message TEXT, evidence TEXT
@@ -387,6 +412,7 @@ CREATE INDEX IF NOT EXISTS idx_wf_snap ON workflow(snapshot_id, repo);
387
412
  CREATE INDEX IF NOT EXISTS idx_wfrun_snap ON workflow_run(snapshot_id, repo);
388
413
  CREATE INDEX IF NOT EXISTS idx_finding_snap ON finding(snapshot_id, severity, code);
389
414
  CREATE INDEX IF NOT EXISTS idx_bprot_snap ON branch_protection(snapshot_id, repo);
415
+ CREATE INDEX IF NOT EXISTS idx_branch_snap ON branch(snapshot_id, repo);
390
416
  CREATE INDEX IF NOT EXISTS idx_ctx_snap ON check_context(snapshot_id, repo);
391
417
  CREATE INDEX IF NOT EXISTS idx_bill_snap ON billing_usage(snapshot_id, repo);
392
418
  CREATE INDEX IF NOT EXISTS idx_rcost_snap ON run_cost(snapshot_id, repo);
@@ -184,14 +184,47 @@ export function auditSteps(doc, jobs) {
184
184
 
185
185
  const jobSteps = job => (job && typeof job === 'object' && Array.isArray(job.steps) ? job.steps : []);
186
186
 
187
- /** Job ids with a step that uses actions/deploy-pages, at any version. */
188
- export function pagesDeployJobs(jobEntries) {
187
+ /**
188
+ * Job ids with a step that uses actions/deploy-pages, at any version.
189
+ *
190
+ * In a private repository a job that skips itself there is left out: Pages on
191
+ * a private repo is a plan feature, and a deploy gated on
192
+ * `!github.event.repository.private` is how a workflow says "only when public".
193
+ * That job never reaches deploy-pages, so Pages being off refuses nothing.
194
+ */
195
+ export function pagesDeployJobs(jobEntries, { isPrivate = false } = {}) {
196
+ const byId = new Map(jobEntries);
189
197
  return jobEntries
190
198
  .filter(([, job]) => jobSteps(job).some(st =>
191
199
  typeof st?.uses === 'string' && /^actions\/deploy-pages(?:@|$)/i.test(st.uses.trim())))
200
+ .filter(([id]) => !(isPrivate && skipsWhenPrivate(byId, id)))
192
201
  .map(([id]) => id);
193
202
  }
194
203
 
204
+ // A term that is false exactly when the repository is private.
205
+ const PUBLIC_ONLY = /^(?:!\s*github\.event\.repository\.private|github\.event\.repository\.private\s*==\s*false|github\.event\.repository\.private\s*!=\s*true|github\.event\.repository\.visibility\s*==\s*'public')$/;
206
+
207
+ /**
208
+ * True when the job cannot run in a private repository: its own `if:` is a
209
+ * conjunction with a public-only term, or it has no `if:` of its own (so
210
+ * GitHub's implicit success() applies) and a job it needs cannot run. Any
211
+ * `||`, or anything else this cannot read, is false: unknown never excuses.
212
+ */
213
+ export function skipsWhenPrivate(byId, id, seen = new Set()) {
214
+ if (seen.has(id)) return false;
215
+ seen.add(id);
216
+ const job = byId.get(id);
217
+ if (!job || typeof job !== 'object') return false;
218
+ if (job.if !== undefined) {
219
+ if (typeof job.if !== 'string') return false;
220
+ const expr = job.if.trim().replace(/^\$\{\{\s*([\s\S]*?)\s*\}\}$/, '$1');
221
+ if (expr.includes('||')) return false;
222
+ return expr.split('&&').some(t => PUBLIC_ONLY.test(t.trim().replace(/^\((.*)\)$/, '$1').trim()));
223
+ }
224
+ const needs = typeof job.needs === 'string' ? [job.needs] : (Array.isArray(job.needs) ? job.needs : []);
225
+ return needs.some(n => skipsWhenPrivate(byId, n, seen));
226
+ }
227
+
195
228
  /**
196
229
  * The environment a job names, or null when it names none or names it with an
197
230
  * expression. `environment:` is either a string or `{ name, url }`. A name built