thumbgate 1.40.10 → 1.40.13

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.
Files changed (53) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/README.md +46 -40
  4. package/adapters/claude/.mcp.json +3 -3
  5. package/adapters/forge/forge.yaml +3 -3
  6. package/adapters/future-agi/.mcp.json +1 -1
  7. package/adapters/future-agi/config.toml +1 -1
  8. package/adapters/future-agi/opencode.json +1 -1
  9. package/adapters/herdr/herdr-plugin.toml +2 -2
  10. package/adapters/mcp/server-stdio.js +1 -1
  11. package/adapters/opencode/opencode.json +1 -1
  12. package/bin/cli.js +9 -8
  13. package/bin/postinstall.js +2 -2
  14. package/config/unit-costs.json +47 -0
  15. package/package.json +16 -5
  16. package/public/admin.html +284 -29
  17. package/public/agent-manager.html +2 -2
  18. package/public/agents-cost-savings.html +1 -1
  19. package/public/codex-enterprise.html +2 -2
  20. package/public/compare.html +3 -3
  21. package/public/dashboard.html +28 -9
  22. package/public/diagnostic.html +1 -1
  23. package/public/founders.html +1 -1
  24. package/public/guide.html +4 -4
  25. package/public/index.html +80 -116
  26. package/public/install.html +19 -19
  27. package/public/js/connect-panel.js +21 -7
  28. package/public/learn.html +8 -0
  29. package/public/lessons.html +1 -1
  30. package/public/numbers.html +2 -2
  31. package/public/pricing.html +12 -9
  32. package/public/pro.html +96 -137
  33. package/public/project-switcher.js +50 -19
  34. package/scripts/auto-wire-hooks.js +36 -2
  35. package/scripts/billing.js +3 -1
  36. package/scripts/cli-schema.js +2 -3
  37. package/scripts/commercial-offer.js +1 -1
  38. package/scripts/cost-meter.js +161 -0
  39. package/scripts/gates-engine.js +26 -8
  40. package/scripts/hook-runtime.js +18 -1
  41. package/scripts/mailer/resend-mailer.js +2 -0
  42. package/scripts/owner-admin.js +338 -16
  43. package/scripts/owner-alerts.js +79 -0
  44. package/scripts/owner-telemetry.js +113 -3
  45. package/scripts/pr-manager.js +156 -41
  46. package/scripts/project-catalog.js +3 -1
  47. package/scripts/project-identity.js +10 -2
  48. package/scripts/seo-gsd.js +1 -1
  49. package/scripts/telemetry-analytics.js +7 -1
  50. package/scripts/unit-economics.js +138 -0
  51. package/server.json +2 -2
  52. package/src/api/server.js +62 -4
  53. package/src/mcp-writeguard.js +2 -2
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Owner console alerts. Pure rules over the Money board and the Observability report: each alert says what happened,
5
+ * with its numbers, and what to do next. No alert fires on a source that could not be read; that is its own alert.
6
+ *
7
+ * Delivery is off unless THUMBGATE_OWNER_ALERT_WEBHOOK is set (a Slack, Discord or Teams incoming webhook, all free).
8
+ * A message goes out only when an alert appears that was not firing at the last check, so a standing problem is sent once.
9
+ */
10
+
11
+ const LEVELS = { red: 0, amber: 1, info: 2 };
12
+ const dropped = (week, key, floor) => {
13
+ const before = week?.prior7?.[key];
14
+ const now = week?.last7?.[key];
15
+ return Number.isFinite(before) && Number.isFinite(now) && before >= floor && now <= before / 2 ? { before, now } : null;
16
+ };
17
+ const percent = (part, whole) => Math.round((part / whole) * 100);
18
+
19
+ function evaluateAlerts({ money = null, report = null } = {}) {
20
+ const alerts = [];
21
+ const add = (id, level, text, action, tab) => alerts.push({ id, level, text, action, tab });
22
+
23
+ if (report) {
24
+ const errors = report.errors || {};
25
+ if (Number.isFinite(errors.lastHour) && errors.lastHour >= 5) add('server_errors', 'red', errors.lastHour + ' server errors in the last hour.', 'Open Health to see which requests fail.', 'observability');
26
+ const uptime = report.uptime || {};
27
+ if (Number.isFinite(uptime.percent) && uptime.percent < 99.5) add('uptime', 'amber', 'Uptime is ' + uptime.percent + '% over about ' + uptime.observedDays + ' days.', 'Check the last outage on Health and the Railway deploy log.', 'observability');
28
+ const hooks = report.webhooks || {};
29
+ if (Number.isFinite(hooks.failures24h) && hooks.failures24h > 0) add('stripe_webhooks', 'red', hooks.failures24h + ' Stripe notifications failed in 24 hours, so a payment may not have unlocked Pro.', 'Check Stripe, Developers, Webhooks, and resend the failed events.', 'observability');
30
+ const disk = report.disk || {};
31
+ if (Number.isFinite(disk.percent) && disk.percent >= 85) add('disk', disk.percent >= 95 ? 'red' : 'amber', 'The data disk is ' + disk.percent + '% full.', 'Grow the Railway volume or rotate the telemetry log.', 'observability');
32
+ const signIn = report.signIn || {};
33
+ if (Number.isFinite(signIn.failed24h) && signIn.failed24h >= 10) add('sign_in', 'amber', signIn.failed24h + ' failed sign-ins in 24 hours.', 'Open Health to see the most common reason.', 'observability');
34
+ }
35
+
36
+ if (money) {
37
+ const why = money.reasons || {};
38
+ const stripeDown = ['payingCustomers', 'revenue', 'checkouts', 'mrr'].map((key) => why[key]).filter(Boolean);
39
+ if (stripeDown.length) add('stripe_unreadable', 'amber', 'Stripe could not be read: ' + stripeDown[0] + '.', 'Refresh in a minute. If it stays, check the Stripe key on Railway.', 'money');
40
+ if (why.visitors && why.visitors !== 'telemetry store empty') add('telemetry_unreadable', 'amber', 'Site and CLI telemetry could not be read: ' + why.visitors + '.', 'Refresh in a minute, then check the Railway volume.', 'analytics');
41
+
42
+ const week = money.weekOverWeek;
43
+ const visitors = dropped(week, 'realVisitors', 20);
44
+ if (visitors) add('visitors_drop', 'amber', 'People on the site fell from ' + visitors.before + ' to ' + visitors.now + ' this week.', 'Check that the last deploy did not break a page, then check your launch posts and links.', 'analytics');
45
+ const starts = dropped(week, 'checkoutStarts', 4);
46
+ if (starts) add('checkout_drop', 'amber', 'Checkout starts fell from ' + starts.before + ' to ' + starts.now + ' this week.', 'Click through the pricing page to the Stripe checkout yourself.', 'money');
47
+ const installs = dropped(week, 'activeInstalls', 4);
48
+ if (installs) add('installs_drop', 'amber', 'Active CLI installs fell from ' + installs.before + ' to ' + installs.now + ' this week.', 'Run npx thumbgate init on a clean machine to check install still works.', 'analytics');
49
+
50
+ const usage = money.usage30d;
51
+ if (usage && usage.activeInstalls30d >= 10 && usage.activatedInstalls / usage.activeInstalls30d < 0.2) add('activation_low', 'amber', 'Only ' + usage.activatedInstalls + ' of ' + usage.activeInstalls30d + ' active installs (' + percent(usage.activatedInstalls, usage.activeInstalls30d) + '%) captured any feedback.', 'Make the first thumbs-down easier to reach in init.', 'analytics');
52
+
53
+ if (Number.isFinite(money.cancellingAtPeriodEnd) && money.cancellingAtPeriodEnd > 0) add('cancelling', 'amber', money.cancellingAtPeriodEnd + ' subscriber' + (money.cancellingAtPeriodEnd === 1 ? ' is' : 's are') + ' set to cancel at the end of the period.', 'Look them up under Stripe records, Subscriptions, and ask why before the period ends.', 'stripe');
54
+ const churned = money.recurring30d?.churnedSubscriptions;
55
+ if (Number.isFinite(churned) && churned > 0) add('churned', 'amber', churned + ' subscription' + (churned === 1 ? '' : 's') + ' cancelled in the past 30 days.', 'Read the cancellation reasons in Stripe.', 'stripe');
56
+ }
57
+
58
+ return alerts.sort((a, b) => LEVELS[a.level] - LEVELS[b.level]);
59
+ }
60
+
61
+ function formatAlertMessage(alerts) {
62
+ const lines = alerts.map((alert) => (alert.level === 'red' ? '[urgent] ' : '') + alert.text + ' ' + alert.action);
63
+ return { title: 'ThumbGate: ' + alerts.length + ' thing' + (alerts.length === 1 ? '' : 's') + ' need you', message: lines.join('\n') + '\nhttps://thumbgate.ai/admin' };
64
+ }
65
+
66
+ // Returns the alerts that are new since the last call, and remembers the current set.
67
+ function createAlertTracker() {
68
+ let firing = new Set();
69
+ return {
70
+ fresh(alerts) {
71
+ const now = new Set(alerts.map((alert) => alert.id));
72
+ const added = alerts.filter((alert) => !firing.has(alert.id));
73
+ firing = now;
74
+ return added;
75
+ },
76
+ };
77
+ }
78
+
79
+ module.exports = { evaluateAlerts, formatAlertMessage, createAlertTracker };
@@ -101,6 +101,17 @@ async function scanTelemetry({ feedbackDir, days = 30, now = Date.now(), maxByte
101
101
  const kind = (entry) => String(entry.eventType || entry.event || '').toLowerCase();
102
102
  const isWeb = (entry) => (entry.clientType || entry.client) === 'web';
103
103
  const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal === true || entry.isTest === true;
104
+ const isCli = (entry) => (entry.clientType || entry.client) === 'cli';
105
+ // The CLI labels its own runs: `owner` for the owner's machines and `ci` for build servers. Older stored rows carry only
106
+ // that label, not the ingest flags, so both are checked.
107
+ const isOwnOrCiInstall = (entry) => isFlagged(entry) || ['owner', 'ci'].includes(String(entry.visitorType || '').toLowerCase());
108
+ // An install counts as activated once it has captured a piece of feedback: that is the first moment ThumbGate does its job.
109
+ const ACTIVATION_EVENT = 'cli_capture';
110
+ // The first value event: a gate really fired and blocked a tool call in the user's own workflow. The CLI sends it once per
111
+ // install with the minutes since install, so time to first value comes from the same ping.
112
+ const FIRST_VALUE_EVENT = 'first_blocked_tool_call';
113
+ const quantile = (sorted, q) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] : null);
114
+ const topCounts = (counts, limit = 10) => Object.fromEntries(Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, limit));
104
115
 
105
116
  // Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
106
117
  //
@@ -108,6 +119,13 @@ const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal ===
108
119
  // so it can exceed `pageViews`, which counts landing_page_view events only. `realVisitors` leaves out identifiers that
109
120
  // carried a bot, internal or test flag on any event. `pageViewers` is the identifiers with at least one landing page view.
110
121
  async function readTrafficWindow(options) {
122
+ const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
123
+ const weekOf = (time) => (time >= nowMs - 7 * DAY_MS ? 'last7' : time >= nowMs - 14 * DAY_MS ? 'prior7' : null);
124
+ const emptyWeek = () => ({ visitors: new Set(), flagged: new Set(), pageViews: 0, checkoutStarts: 0, activeInstalls: new Set() });
125
+ const weeks = { last7: emptyWeek(), prior7: emptyWeek() };
126
+ const installs = new Map();
127
+ const excludedInstalls = new Set();
128
+ const cliEvents = {};
111
129
  const days = new Map();
112
130
  const visitors = new Set();
113
131
  const flagged = new Set();
@@ -118,17 +136,48 @@ async function readTrafficWindow(options) {
118
136
  const dayOf = (time) => {
119
137
  const key = new Date(time).toISOString().slice(0, 10);
120
138
  let day = days.get(key);
121
- if (!day) { day = { date: key, visitors: new Set(), pageViewers: new Set(), sessions: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
139
+ if (!day) { day = { date: key, visitors: new Set(), pageViewers: new Set(), sessions: new Set(), activeInstalls: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
122
140
  return day;
123
141
  };
124
142
  const meta = await scanTelemetry({
125
143
  ...options,
126
144
  onEntry(entry, time) {
145
+ const week = weekOf(time);
146
+ if (isCli(entry)) {
147
+ const install = entry.installId;
148
+ if (!install) return;
149
+ if (isOwnOrCiInstall(entry)) { excludedInstalls.add(install); return; }
150
+ const type = kind(entry) || 'unknown';
151
+ cliEvents[type] = (cliEvents[type] || 0) + 1;
152
+ const day = dayOf(time);
153
+ day.activeInstalls.add(install);
154
+ if (week) weeks[week].activeInstalls.add(install);
155
+ const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, firstValue: false, firstValueMinutes: null, version: null, platform: null };
156
+ seen.days.add(day.date);
157
+ seen.inited ||= type === 'cli_init';
158
+ seen.activated ||= type === ACTIVATION_EVENT;
159
+ if (type === FIRST_VALUE_EVENT) {
160
+ seen.firstValue = true;
161
+ // null or a blank means the CLI could not read its install marker: the install still reached first value, but its
162
+ // duration is unknown, so it stays out of the percentiles (Number(null) would count it as zero minutes).
163
+ const raw = entry.minutesSinceInstall;
164
+ const minutes = raw === null || raw === undefined || raw === '' || typeof raw === 'boolean' ? NaN : Number(raw);
165
+ if (Number.isFinite(minutes) && minutes >= 0 && (seen.firstValueMinutes === null || minutes < seen.firstValueMinutes)) seen.firstValueMinutes = minutes;
166
+ }
167
+ if (time >= seen.lastMs) { seen.lastMs = time; seen.version = entry.version || entry.pkgVersion || seen.version; seen.platform = entry.platform || seen.platform; }
168
+ installs.set(install, seen);
169
+ return;
170
+ }
127
171
  if (!isWeb(entry)) return;
128
172
  totals.webEvents += 1;
129
173
  const day = dayOf(time);
130
174
  const who = entry.visitorId || entry.installId || entry.sessionId || null;
131
175
  if (who) { visitors.add(who); day.visitors.add(who); if (isFlagged(entry)) flagged.add(who); }
176
+ if (week) {
177
+ if (who) { weeks[week].visitors.add(who); if (isFlagged(entry)) weeks[week].flagged.add(who); }
178
+ if (kind(entry) === 'landing_page_view') weeks[week].pageViews += 1;
179
+ if (telemetry.isCheckoutStartEvent(kind(entry))) weeks[week].checkoutStarts += 1;
180
+ }
132
181
  if (entry.sessionId) { sessions.add(entry.sessionId); day.sessions.add(entry.sessionId); }
133
182
  const type = kind(entry);
134
183
  if (type === 'landing_page_view') {
@@ -140,12 +189,73 @@ async function readTrafficWindow(options) {
140
189
  if (type === 'checkout_paid_confirmed') { totals.checkoutPaidConfirmations += 1; day.checkoutPaidConfirmations += 1; }
141
190
  },
142
191
  });
143
- const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
192
+ const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, activeInstalls: day.activeInstalls.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
193
+ const byVersion = {};
194
+ const byPlatform = {};
195
+ let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0; let firstValue = 0;
196
+ const firstValueMinutes = [];
197
+ for (const seen of installs.values()) {
198
+ byVersion[seen.version || 'unknown'] = (byVersion[seen.version || 'unknown'] || 0) + 1;
199
+ byPlatform[seen.platform || 'unknown'] = (byPlatform[seen.platform || 'unknown'] || 0) + 1;
200
+ if (seen.inited) newInstalls += 1;
201
+ if (seen.activated) activated += 1;
202
+ if (seen.firstValue) { firstValue += 1; if (seen.firstValueMinutes !== null) firstValueMinutes.push(seen.firstValueMinutes); }
203
+ if (seen.days.size >= 2) returning += 1;
204
+ if (seen.lastMs >= nowMs - 7 * DAY_MS) active7 += 1;
205
+ }
206
+ const weekNumbers = (week) => ({ realVisitors: week.visitors.size - week.flagged.size, pageViews: week.pageViews, checkoutStarts: week.checkoutStarts, activeInstalls: week.activeInstalls.size });
144
207
  return {
145
208
  ...meta,
209
+ // CLI installs, from the anonymous install id the CLI sends. The owner's machines, CI and flagged pings are left out.
210
+ usage: {
211
+ activeInstalls30d: installs.size,
212
+ activeInstalls7d: active7,
213
+ initsInWindow: newInstalls,
214
+ activatedInstalls: activated,
215
+ returningInstalls: returning,
216
+ // Installs whose first real gate block arrived in the window, and how long after install it came.
217
+ firstValueInstalls: firstValue,
218
+ timeToFirstValue: (() => {
219
+ const sorted = firstValueMinutes.sort((a, b) => a - b);
220
+ return { installs: sorted.length, medianMinutes: quantile(sorted, 0.5), p75Minutes: quantile(sorted, 0.75) };
221
+ })(),
222
+ excludedInstalls: excludedInstalls.size,
223
+ eventsByType: topCounts(cliEvents, 20),
224
+ byVersion: topCounts(byVersion),
225
+ byPlatform: topCounts(byPlatform),
226
+ },
227
+ // The newest 7 days against the 7 days before them, so a change shows without remembering last week.
228
+ weeks: { last7: weekNumbers(weeks.last7), prior7: weekNumbers(weeks.prior7) },
146
229
  traffic: { visitors: visitors.size, realVisitors: visitors.size - flagged.size, botOrInternalVisitors: flagged.size, pageViewers: pageViewers.size, checkoutStartsByType: startsByType, sessions: sessions.size, pageViews: totals.pageViews, ctaClicks: totals.ctaClicks, checkoutStarts: totals.checkoutStarts, checkoutPaidConfirmations: totals.checkoutPaidConfirmations },
147
230
  daily,
148
231
  };
149
232
  }
150
233
 
151
- module.exports = { scanFile, scanTelemetry, readTrafficWindow, DEFAULT_MAX_BYTES };
234
+ // Weekly retention for CLI installs. Week 0 is the newest 7 days. An install joins the cohort of the oldest week it was
235
+ // seen in, and `retained[k]` counts the cohort's installs seen again k weeks later. The oldest cohort also holds installs
236
+ // that began before the read window, so it is marked `includesOlder`.
237
+ async function readInstallCohorts({ weeks = 8, now = Date.now(), ...options }) {
238
+ const seen = new Map();
239
+ const meta = await scanTelemetry({
240
+ ...options,
241
+ days: weeks * 7,
242
+ now,
243
+ onEntry(entry, time) {
244
+ if (!isCli(entry) || !entry.installId || isOwnOrCiInstall(entry)) return;
245
+ const week = Math.min(weeks - 1, Math.max(0, Math.floor((now - time) / (7 * DAY_MS))));
246
+ const set = seen.get(entry.installId) || new Set();
247
+ set.add(week);
248
+ seen.set(entry.installId, set);
249
+ },
250
+ });
251
+ const cohorts = [];
252
+ for (let first = weeks - 1; first >= 0; first -= 1) {
253
+ const members = [...seen.values()].filter((set) => Math.max(...set) === first);
254
+ const retained = [];
255
+ for (let k = 0; k <= first; k += 1) retained.push(members.filter((set) => set.has(first - k)).length);
256
+ cohorts.push({ weekStart: new Date(now - (first + 1) * 7 * DAY_MS).toISOString().slice(0, 10), weeksAgo: first, size: members.length, retained, includesOlder: first === weeks - 1 });
257
+ }
258
+ return { weeks, partial: meta.partial, cohorts };
259
+ }
260
+
261
+ module.exports = { scanFile, scanTelemetry, readTrafficWindow, readInstallCohorts, DEFAULT_MAX_BYTES };
@@ -482,12 +482,41 @@ async function managePrs(prNumber = '', runner = runGh, options = {}) {
482
482
  return { status: 'ok', prs: results };
483
483
  }
484
484
 
485
- const SWEEP_PR_FIELDS = 'number,state,isDraft,title,url,headRefName,baseRefName,updatedAt,createdAt,author,statusCheckRollup';
485
+ // Stale-PR steward. It never closes a PR. Claude Ship's PR Steward fixes PRs
486
+ // instead of closing them; the free version here does the mechanical part
487
+ // (rebase a branch that fell behind main) and labels the rest so the daily
488
+ // steward agent session (docs/ops/ship-pipeline.md) can fix the code.
489
+ // History: the old sweeper closed #5131 after 3 days as a draft.
490
+ const SWEEP_PR_FIELDS = 'number,state,isDraft,title,url,headRefName,headRefOid,baseRefName,updatedAt,createdAt,author,statusCheckRollup,mergeStateStatus,mergeable,labels';
491
+ // main has no "require up to date" rule, so GitHub never reports BEHIND here.
492
+ // The steward asks the compare API instead and updates a branch this far back.
493
+ const SWEEP_BEHIND_THRESHOLD = 10;
486
494
  const SWEEP_LIST_LIMIT = '1000';
487
495
  const SWEEP_REQUIRED_CHECKS_BASE = 'main';
488
496
  const DEFAULT_RED_MAX_AGE_MS = 24 * 60 * 60 * 1000;
489
497
  const DEFAULT_DRAFT_IDLE_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
490
498
  const REQUIRED_CHECK_SET = new Set(MERGE_QUALITY_CHECKS.requiredStatusCheckContexts || []);
499
+ const STEWARD_LABELS = {
500
+ stale: 'stale',
501
+ needsFix: 'needs-fix',
502
+ needsRebase: 'needs-rebase',
503
+ };
504
+ const STEWARD_LABEL_STYLE = {
505
+ stale: ['C5DEF5', 'Steward: draft idle over 3 days'],
506
+ 'needs-fix': ['D93F0B', 'Ship gate: red checks or open review threads'],
507
+ 'needs-rebase': ['FBCA04', 'Steward: conflicts with main'],
508
+ };
509
+
510
+ /** Add a label, creating it first if the repo does not have it yet. */
511
+ function addStewardLabel(number, label, runner) {
512
+ let res = runner(['pr', 'edit', String(number), '--add-label', label]);
513
+ if (res.status !== 0 && /not found/i.test(formatGhError(res))) {
514
+ const [color, description] = STEWARD_LABEL_STYLE[label] || ['EDEDED', 'Steward'];
515
+ runner(['label', 'create', label, '--color', color, '--description', description]);
516
+ res = runner(['pr', 'edit', String(number), '--add-label', label]);
517
+ }
518
+ return res;
519
+ }
491
520
 
492
521
  function isProtectedSweepBranch(pr = {}) {
493
522
  const headRef = String(pr.headRefName || '').trim();
@@ -514,30 +543,60 @@ function isRequiredCheckFailing(check = {}) {
514
543
  return FAILING_CHECK_CONCLUSIONS.has(conclusion) || conclusion === 'ERROR';
515
544
  }
516
545
 
546
+ function prLabels(pr = {}) {
547
+ return new Set((pr.labels || []).map((l) => (typeof l === 'string' ? l : l.name)));
548
+ }
549
+
517
550
  function classifyStalePr(pr = {}, options = {}) {
518
551
  const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
519
552
  const redMaxAgeMs = Number.isFinite(options.redMaxAgeMs) ? options.redMaxAgeMs : DEFAULT_RED_MAX_AGE_MS;
520
553
  const draftIdleMaxAgeMs = Number.isFinite(options.draftIdleMaxAgeMs)
521
554
  ? options.draftIdleMaxAgeMs
522
555
  : DEFAULT_DRAFT_IDLE_MAX_AGE_MS;
556
+ const labels = prLabels(pr);
523
557
 
524
558
  if (isProtectedSweepBranch(pr)) {
525
- return {
526
- action: 'skip',
527
- reason: 'protected_branch',
528
- headRefName: pr.headRefName || '',
529
- };
559
+ return { action: 'skip', reason: 'protected_branch', headRefName: pr.headRefName || '' };
560
+ }
561
+ if (labels.has('do-not-merge')) {
562
+ return { action: 'skip', reason: 'on_hold' };
563
+ }
564
+
565
+ // A branch behind main is rebased whatever else is going on: that alone
566
+ // often turns red checks green, and it keeps drafts mergeable.
567
+ if (String(pr.mergeStateStatus || '').toUpperCase() === 'BEHIND') {
568
+ return { action: 'update_branch', reason: 'behind_main' };
569
+ }
570
+ const behindThreshold = Number.isFinite(options.behindThreshold) ? options.behindThreshold : SWEEP_BEHIND_THRESHOLD;
571
+ if (Number.isFinite(pr.behindBy) && pr.behindBy >= behindThreshold
572
+ && String(pr.mergeStateStatus || '').toUpperCase() !== 'DIRTY') {
573
+ // A merge update, not a rebase: it never rewrites a branch an agent may be working on.
574
+ return { action: 'update_branch', reason: 'behind_main_by_commits', behindBy: pr.behindBy, rebase: false };
575
+ }
576
+ if (String(pr.mergeStateStatus || '').toUpperCase() === 'DIRTY' || String(pr.mergeable || '').toUpperCase() === 'CONFLICTING') {
577
+ return labels.has(STEWARD_LABELS.needsRebase)
578
+ ? { action: 'keep', reason: 'conflict_already_flagged' }
579
+ : {
580
+ action: 'label',
581
+ label: STEWARD_LABELS.needsRebase,
582
+ reason: 'merge_conflict',
583
+ comment: `PR #${pr.number} has a merge conflict with \`main\`. Labelled \`${STEWARD_LABELS.needsRebase}\`; the steward session rebases it and resolves the conflict. Nothing was closed.`,
584
+ };
530
585
  }
531
586
 
532
587
  if (pr.isDraft) {
533
588
  const updatedMs = Date.parse(pr.updatedAt || pr.createdAt || '');
534
589
  if (Number.isFinite(updatedMs) && (nowMs - updatedMs) > draftIdleMaxAgeMs) {
535
590
  const idleDays = Math.floor((nowMs - updatedMs) / (24 * 60 * 60 * 1000));
591
+ if (labels.has(STEWARD_LABELS.stale)) {
592
+ return { action: 'keep', reason: 'draft_idle_already_flagged', idleDays };
593
+ }
536
594
  return {
537
- action: 'close',
595
+ action: 'label',
596
+ label: STEWARD_LABELS.stale,
538
597
  reason: 'draft_idle_over_3d',
539
598
  idleDays,
540
- comment: `Closing draft PR #${pr.number} after ${idleDays}d of inactivity (>3d draft idle threshold). Branch \`${pr.headRefName || 'unknown'}\` is preserved — re-open or open a fresh PR off \`origin/main\` when ready.`,
599
+ comment: `Draft PR #${pr.number} has been idle ${idleDays}d. Labelled \`${STEWARD_LABELS.stale}\` so the steward session finishes it (tests, then ready for review). It stays open.`,
541
600
  };
542
601
  }
543
602
  return { action: 'keep', reason: 'draft_active' };
@@ -546,8 +605,6 @@ function classifyStalePr(pr = {}, options = {}) {
546
605
  const checks = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];
547
606
  const failingRequired = checks.filter((check) => isRequiredCheckFailing(check));
548
607
  if (failingRequired.length > 0 && String(pr.baseRefName || '') !== SWEEP_REQUIRED_CHECKS_BASE) {
549
- // The required-check set is only known for main. For any other base
550
- // (or an unknown one) we cannot tell which red checks matter, so never close.
551
608
  return { action: 'keep', reason: 'required_checks_unknown_for_base', baseRefName: pr.baseRefName || '' };
552
609
  }
553
610
  if (failingRequired.length > 0) {
@@ -555,19 +612,20 @@ function classifyStalePr(pr = {}, options = {}) {
555
612
  .map((check) => Date.parse(check.completedAt || check.startedAt || ''))
556
613
  .filter((ts) => Number.isFinite(ts));
557
614
  const fallbackMs = Date.parse(pr.updatedAt || pr.createdAt || '');
558
- const redSinceMs = checkTimestamps.length > 0
559
- ? Math.max(...checkTimestamps)
560
- : fallbackMs;
561
-
615
+ const redSinceMs = checkTimestamps.length > 0 ? Math.max(...checkTimestamps) : fallbackMs;
562
616
  if (Number.isFinite(redSinceMs) && (nowMs - redSinceMs) > redMaxAgeMs) {
563
617
  const redHours = Math.floor((nowMs - redSinceMs) / (60 * 60 * 1000));
564
618
  const failingNames = [...new Set(failingRequired.map((c) => c.name || c.context))];
619
+ if (labels.has(STEWARD_LABELS.needsFix)) {
620
+ return { action: 'keep', reason: 'red_already_flagged', redHours, failingChecks: failingNames };
621
+ }
565
622
  return {
566
- action: 'close',
623
+ action: 'label',
624
+ label: STEWARD_LABELS.needsFix,
567
625
  reason: 'red_checks_over_24h',
568
626
  redHours,
569
627
  failingChecks: failingNames,
570
- comment: `Closing non-draft PR #${pr.number} because required check(s) (${failingNames.join(', ')}) have been red for ${redHours}h (>24h threshold). Branch \`${pr.headRefName || 'unknown'}\` is preserved — fix locally (` + '`npm test`' + `) and re-open when green.`,
628
+ comment: `Required check(s) ${failingNames.join(', ')} on PR #${pr.number} have been red for ${redHours}h. Labelled \`${STEWARD_LABELS.needsFix}\`; the steward session fixes the failure and pushes. It stays open.`,
571
629
  };
572
630
  }
573
631
  }
@@ -575,22 +633,77 @@ function classifyStalePr(pr = {}, options = {}) {
575
633
  return { action: 'keep', reason: 'active' };
576
634
  }
577
635
 
578
- function stillEligibleForClose(number, options, runner) {
636
+ /**
637
+ * gh pr list often reports mergeable/mergeStateStatus as UNKNOWN (GitHub
638
+ * computes them lazily), and never reports BEHIND without an up-to-date rule.
639
+ * Ask the REST API for the real merge state and how far behind the base the
640
+ * head is. Read-only; skipped when the list gave no head SHA.
641
+ */
642
+ function enrichSweepPr(pr, runner) {
643
+ if (!pr || !pr.headRefOid || !pr.baseRefName || !pr.number) {
644
+ return pr;
645
+ }
646
+ const out = { ...pr };
647
+ const state = runner(['api', `repos/{owner}/{repo}/pulls/${pr.number}`, '--jq', '.mergeable_state']);
648
+ if (state.status === 0) {
649
+ const value = String(state.stdout || '').trim().toUpperCase();
650
+ if (value === 'DIRTY') out.mergeStateStatus = 'DIRTY';
651
+ else if (value === 'BEHIND') out.mergeStateStatus = 'BEHIND';
652
+ }
653
+ const compare = runner(['api', `repos/{owner}/{repo}/compare/${pr.baseRefName}...${pr.headRefOid}`, '--jq', '.behind_by']);
654
+ if (compare.status === 0) {
655
+ const behind = Number(String(compare.stdout || '').trim());
656
+ if (Number.isFinite(behind)) out.behindBy = behind;
657
+ }
658
+ return out;
659
+ }
660
+
661
+ function stillNeedsAction(number, verdict, options, runner) {
579
662
  const viewResult = runner(['pr', 'view', String(number), '--json', SWEEP_PR_FIELDS]);
580
663
  if (viewResult.status !== 0) {
581
664
  return false;
582
665
  }
583
666
  try {
584
- const fresh = JSON.parse(viewResult.stdout || '{}');
585
- return fresh.state === 'OPEN' && classifyStalePr(fresh, options).action === 'close';
667
+ const fresh = enrichSweepPr(JSON.parse(viewResult.stdout || '{}'), runner);
668
+ const again = classifyStalePr(fresh, options);
669
+ return fresh.state === 'OPEN' && again.action === verdict.action && again.reason === verdict.reason;
586
670
  } catch {
587
671
  return false;
588
672
  }
589
673
  }
590
674
 
675
+ function applyStewardAction(pr, verdict, runner) {
676
+ if (verdict.action === 'update_branch') {
677
+ if (verdict.rebase !== false) {
678
+ const rebase = runner(['pr', 'update-branch', String(pr.number), '--rebase']);
679
+ if (rebase.status === 0) {
680
+ return { applied: true, via: 'rebase' };
681
+ }
682
+ }
683
+ // Rebase can fail on a conflict that a merge commit would not hit.
684
+ const merge = runner(['pr', 'update-branch', String(pr.number)]);
685
+ if (merge.status === 0) {
686
+ return { applied: true, via: 'merge' };
687
+ }
688
+ addStewardLabel(pr.number, STEWARD_LABELS.needsRebase, runner);
689
+ return { applied: false, via: 'flagged', error: formatGhError(merge) };
690
+ }
691
+ if (verdict.action === 'label') {
692
+ const labelRes = addStewardLabel(pr.number, verdict.label, runner);
693
+ if (labelRes.status !== 0) {
694
+ throw new Error(`Failed to label PR #${pr.number}: ${formatGhError(labelRes)}`);
695
+ }
696
+ const commentRes = runner(['pr', 'comment', String(pr.number), '--body', verdict.comment]);
697
+ if (commentRes.status !== 0) {
698
+ throw new Error(`Failed to comment on PR #${pr.number}: ${formatGhError(commentRes)}`);
699
+ }
700
+ return { applied: true };
701
+ }
702
+ return { applied: false };
703
+ }
704
+
591
705
  function sweepStalePrs(options = {}, runner = runGh) {
592
706
  const dryRun = Boolean(options.dryRun);
593
- // A high limit makes gh paginate through every open PR, so none are silently skipped.
594
707
  const listResult = runner(['pr', 'list', '--state', 'open', '--limit', SWEEP_LIST_LIMIT, '--json', SWEEP_PR_FIELDS]);
595
708
  if (listResult.status !== 0) {
596
709
  throw new Error(`Failed to list open PRs for sweep: ${formatGhError(listResult)}`);
@@ -598,11 +711,13 @@ function sweepStalePrs(options = {}, runner = runGh) {
598
711
 
599
712
  const prs = JSON.parse(listResult.stdout || '[]');
600
713
  const decisions = [];
601
- let closedCount = 0;
714
+ let actedCount = 0;
602
715
  let skippedCount = 0;
603
716
  let keptCount = 0;
717
+ let errorCount = 0;
604
718
 
605
- for (const pr of prs) {
719
+ for (const listed of prs) {
720
+ const pr = isProtectedSweepBranch(listed) ? listed : enrichSweepPr(listed, runner);
606
721
  const verdict = classifyStalePr(pr, options);
607
722
  const record = {
608
723
  number: pr.number,
@@ -612,45 +727,44 @@ function sweepStalePrs(options = {}, runner = runGh) {
612
727
  ...verdict,
613
728
  applied: false,
614
729
  };
730
+ delete record.comment;
615
731
 
616
732
  if (verdict.action === 'skip') {
617
733
  skippedCount += 1;
618
- } else if (verdict.action === 'close' && !dryRun && !stillEligibleForClose(pr.number, options, runner)) {
619
- // The PR changed after it was listed (new push, checks recovered, undrafted).
734
+ } else if (verdict.action === 'keep') {
735
+ keptCount += 1;
736
+ } else if (!dryRun && !stillNeedsAction(pr.number, verdict, options, runner)) {
620
737
  record.action = 'keep';
621
738
  record.reason = 'eligibility_changed';
622
739
  keptCount += 1;
623
- } else if (verdict.action === 'close') {
624
- closedCount += 1;
740
+ } else {
741
+ actedCount += 1;
625
742
  if (!dryRun) {
626
- const commentRes = runner(['pr', 'comment', String(pr.number), '--body', verdict.comment]);
627
- if (commentRes.status !== 0) {
628
- throw new Error(`Failed to comment on PR #${pr.number}: ${formatGhError(commentRes)}`);
629
- }
630
- // Never pass --delete-branch: branches are preserved by policy.
631
- const closeRes = runner(['pr', 'close', String(pr.number)]);
632
- if (closeRes.status !== 0) {
633
- throw new Error(`Failed to close PR #${pr.number}: ${formatGhError(closeRes)}`);
743
+ // One PR's failure must not stop the sweep for the rest.
744
+ try {
745
+ Object.assign(record, applyStewardAction(pr, verdict, runner));
746
+ } catch (err) {
747
+ record.error = err.message;
748
+ errorCount += 1;
634
749
  }
635
- record.applied = true;
636
750
  }
637
- } else {
638
- keptCount += 1;
639
751
  }
640
-
641
752
  decisions.push(record);
642
753
  }
643
754
 
644
755
  return {
645
756
  status: 'ok',
646
757
  dryRun,
647
- closedCount,
758
+ actedCount,
759
+ closedCount: 0,
648
760
  skippedCount,
649
761
  keptCount,
762
+ errorCount,
650
763
  decisions,
651
764
  };
652
765
  }
653
766
 
767
+
654
768
  if (require.main === module) {
655
769
  const argv = process.argv.slice(2);
656
770
  if (argv.includes('--sweep') || argv.includes('--sweep-stale')) {
@@ -662,10 +776,10 @@ if (require.main === module) {
662
776
  console.log(JSON.stringify(summary, null, 2));
663
777
  } else {
664
778
  console.log(
665
- `[PR Sweeper] dryRun=${summary.dryRun} closed=${summary.closedCount} skipped=${summary.skippedCount} kept=${summary.keptCount}`,
779
+ `[PR Steward] dryRun=${summary.dryRun} acted=${summary.actedCount} skipped=${summary.skippedCount} kept=${summary.keptCount} errors=${summary.errorCount} closed=0`,
666
780
  );
667
781
  }
668
- process.exit(0);
782
+ process.exit(summary.errorCount > 0 ? 1 : 0);
669
783
  } catch (err) {
670
784
  console.error(err.message);
671
785
  process.exit(1);
@@ -685,6 +799,7 @@ module.exports = {
685
799
  assertSafeGhArgs,
686
800
  buildGhEnv,
687
801
  classifyStalePr,
802
+ enrichSweepPr,
688
803
  getPrStatus,
689
804
  getPrChecks,
690
805
  isProtectedSweepBranch,
@@ -238,6 +238,8 @@ function buildProjectCatalog(root, options = {}) {
238
238
  if (stamp && Number.isFinite(Date.parse(stamp)) && (!project.lastActivity || Date.parse(stamp) > Date.parse(project.lastActivity))) project.lastActivity = stamp;
239
239
  }
240
240
  }
241
- return { projects: [...projects.values()].sort((a, b) => a.projectName.localeCompare(b.projectName)), globalGateCount: gates.filter((gate) => gate.scope === 'global' && gate.active !== false && gate.enabled !== false).length };
241
+ // A project with nothing recorded (no feedback, lessons, gates, blocks, tool calls or agents) is a leftover identity, not something to pick.
242
+ const withActivity = (project) => ({ ...project, empty: Object.values(project.counts).every((count) => !count) });
243
+ return { projects: [...projects.values()].map(withActivity).sort((a, b) => a.projectName.localeCompare(b.projectName)), globalGateCount: gates.filter((gate) => gate.scope === 'global' && gate.active !== false && gate.enabled !== false).length };
242
244
  }
243
245
  module.exports = { attributionForFile, uniqueSourceIndex, iterateRows, SIGNAL_FILES, accountDirectories, signalPaths, readRows, accountAttribution, readProjectRows, readProjectGates, buildProjectCatalog };
@@ -105,7 +105,15 @@ function resolveLocalProjectUncached(cwd = process.cwd(), options = {}) {
105
105
  if (canonicalRemote(remote)) return projectFromRemote(remote);
106
106
  // Common git metadata gives remote-less worktrees the identity of their repository.
107
107
  if (common && path.basename(common) === '.git') root = path.dirname(common);
108
- return { projectKey: `local_${hash(`${machineIdentity(options)}\0${root}`)}`, projectName: safeProjectName(path.basename(root), 'Local project'), identitySource: 'local' };
108
+ // A session started in the home folder belongs to no project; naming it after the user's login reads like a project called "<username>".
109
+ const homeFolder = (() => { try { return fs.realpathSync(os.homedir()); } catch { return null; } })();
110
+ const projectName = homeFolder && root === homeFolder ? 'Home folder (no project)' : safeProjectName(path.basename(root), 'Local project');
111
+ return { projectKey: `local_${hash(`${machineIdentity(options)}\0${root}`)}`, projectName, identitySource: 'local' };
112
+ }
113
+ // A folder is a real project only when its git remote identifies it (the same rule as isRealProject in public/project-switcher.js).
114
+ function isProjectFolder(dir, options = {}) {
115
+ if (!dir || typeof dir !== 'string') return false;
116
+ try { return resolveLocalProject(dir, options).identitySource === 'remote'; } catch { return false; }
109
117
  }
110
118
  function legacyAlias(record = {}, options = {}) {
111
119
  const registry = options.recordType === 'agent-registry.jsonl' || record.recordType === 'agent-registry.jsonl';
@@ -179,4 +187,4 @@ function projectForCapture(input = {}, options = {}) {
179
187
  if ((input.projectKey && input.projectKey !== descriptor.projectKey) || (remote && remote.projectKey !== descriptor.projectKey)) throw invalid('Project key does not match execution directory');
180
188
  return descriptor;
181
189
  }
182
- module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
190
+ module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, isProjectFolder, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
@@ -566,7 +566,7 @@ const PRETOOLUSE_HOOK_GUIDE_SPEC = Object.freeze({
566
566
  ],
567
567
  [
568
568
  'Does this run locally or call a cloud service?',
569
- 'Local-first. The PreToolUse decision happens in the hook process on your machine in milliseconds — no network round-trip, no cloud dependency, no data leaving the laptop. Pro adds personal recall, exports, dashboard proof, and managed adapter coverage. Enterprise service work is qualified after intake; hosted rule sharing and a hosted org dashboard are not generally available.',
569
+ 'Local-first. The PreToolUse decision happens in the hook process on your machine in milliseconds — no network round-trip, no cloud dependency, no data leaving the laptop. Pro keeps every learned rule active and adds recall, lesson search, and exports. Enterprise service work is qualified after intake; hosted rule sharing and a hosted org dashboard are not generally available.',
570
570
  ],
571
571
  ],
572
572
  relatedPaths: ['/guides/mcp-tool-governance', '/guides/ai-agent-pre-action-approval-gates', '/guides/ai-coding-agent-zero-trust'],
@@ -449,6 +449,11 @@ function classifyTelemetryAudience(entry = {}, raw = {}, options = {}) {
449
449
  addAudienceReason(reasons, 'internal_host');
450
450
  }
451
451
 
452
+ // The CLI and server classifiers label the owner's own machines and build servers; trust that label.
453
+ if (['owner', 'ci'].includes(String(raw.visitorType || entry.visitorType || '').trim().toLowerCase())) {
454
+ addAudienceReason(reasons, 'internal_operator_or_ci');
455
+ }
456
+
452
457
  if (includesAnyToken([userAgent, ...identityValues], [
453
458
  'codex',
454
459
  'github-actions',
@@ -598,7 +603,8 @@ function sanitizeTelemetryPayload(payload = {}, headers = {}, options = {}) {
598
603
  cookies.thumbgate_acquisition_id,
599
604
  cookies.tg_aid
600
605
  ),
601
- version: pickFirstText(raw.version, raw.appVersion),
606
+ // The CLI sends its package version as `pkgVersion`; without it every CLI ping was stored with no version.
607
+ version: pickFirstText(raw.version, raw.appVersion, raw.pkgVersion),
602
608
  platform: pickFirstText(raw.platform),
603
609
  nodeVersion: pickFirstText(raw.nodeVersion),
604
610
  page: pickFirstText(raw.page, raw.landingPath, raw.path),