thumbgate 1.39.1 → 1.40.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +5 -4
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +82 -7
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +128 -15
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +1 -0
- package/config/post-deploy-marketing-pages.json +3 -3
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +98 -31
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +1 -2
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +773 -481
- package/public/diagnostic.html +8 -3
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +181 -205
- package/public/install.html +12 -11
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +103 -46
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +61 -327
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-report.js +363 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/check-update.js +236 -0
- package/scripts/cli-schema.js +1 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +576 -169
- package/scripts/decision-journal.js +7 -4
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/gate-stats.js +8 -2
- package/scripts/gates-engine.js +694 -230
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hybrid-feedback-context.js +5 -2
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/intervention-policy.js +2 -1
- package/scripts/latency-budget.js +164 -0
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-integrity.js +436 -3
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/session-report.js +120 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/task-outcomes.js +29 -2
- package/scripts/telemetry-analytics.js +238 -13
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/src/api/server.js +2371 -451
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const readline = require('node:readline');
|
|
7
|
+
const billing = require('./billing');
|
|
8
|
+
|
|
9
|
+
const JSON_LIMIT = 8 * 1024 * 1024;
|
|
10
|
+
const LOG_LIMIT = 16 * 1024 * 1024;
|
|
11
|
+
const RESPONSE_LIMIT = 1024 * 1024;
|
|
12
|
+
const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
|
|
13
|
+
const SECTIONS = new Set(['overview', 'data', 'analytics', 'observability']);
|
|
14
|
+
const PRIVATE_HEADERS = Object.freeze({ 'Cache-Control': 'private, no-store', Vary: 'Cookie', 'X-Robots-Tag': 'noindex, nofollow', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' });
|
|
15
|
+
let activeCollections = 0;
|
|
16
|
+
const text = (value, max = 256) => typeof value === 'string' ? value.slice(0, max) : null;
|
|
17
|
+
const number = (value) => Number.isFinite(value) ? value : null;
|
|
18
|
+
const id = (value) => text(typeof value === 'object' ? value?.id : value, 128);
|
|
19
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
const stopped = (signal) => { if (signal?.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' }); };
|
|
21
|
+
const failure = (code) => Object.assign(new Error(code), { code });
|
|
22
|
+
|
|
23
|
+
function adminPath(raw) {
|
|
24
|
+
try {
|
|
25
|
+
const decoded = decodeURIComponent(raw);
|
|
26
|
+
return { matched: decoded === '/admin' || decoded === '/admin.html' || decoded.startsWith('/admin/') || decoded === '/v1/admin' || decoded.startsWith('/v1/admin/'), pathname: decoded };
|
|
27
|
+
} catch { return { matched: true, pathname: null }; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function parseAdminRoute(pathname, params) {
|
|
31
|
+
if (pathname === '/admin' || pathname === '/admin/' || pathname === '/admin.html') {
|
|
32
|
+
if ([...params].length) throw failure('invalid_query');
|
|
33
|
+
return { page: true };
|
|
34
|
+
}
|
|
35
|
+
const match = /^\/v1\/admin\/([^/]+)(?:\/([^/]+))?$/.exec(pathname || '');
|
|
36
|
+
if (!match || (!SECTIONS.has(match[1]) && match[1] !== 'stripe')) return null;
|
|
37
|
+
const section = match[1];
|
|
38
|
+
const resource = match[2];
|
|
39
|
+
if (section === 'stripe' ? !Object.hasOwn(RESOURCES, resource || '') : Boolean(resource)) return null;
|
|
40
|
+
const allowed = section === 'stripe' ? ['limit', 'starting_after', ...(resource === 'subscription-items' ? ['subscription'] : [])] : section === 'data' ? ['limit', 'cursor'] : [];
|
|
41
|
+
for (const key of params.keys()) if (!allowed.includes(key) || params.getAll(key).length !== 1) throw failure('invalid_query');
|
|
42
|
+
const limitRaw = params.get('limit');
|
|
43
|
+
const max = section === 'data' ? 50 : 100;
|
|
44
|
+
if (limitRaw !== null && (!/^[1-9][0-9]*$/.test(limitRaw) || Number(limitRaw) > max)) throw failure('invalid_query');
|
|
45
|
+
const limit = limitRaw === null ? 25 : Number(limitRaw);
|
|
46
|
+
const cursor = params.get(section === 'data' ? 'cursor' : 'starting_after') || '';
|
|
47
|
+
if (section === 'stripe' && cursor && !new RegExp(`^${RESOURCES[resource]}_[A-Za-z0-9]{1,120}$`).test(cursor)) throw failure('invalid_query');
|
|
48
|
+
let offset = 0;
|
|
49
|
+
if (section === 'data' && cursor) {
|
|
50
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(cursor)) throw failure('invalid_query');
|
|
51
|
+
const decoded = Buffer.from(cursor, 'base64url').toString();
|
|
52
|
+
if (!/^accounts:[0-9]{1,6}$/.test(decoded) || Buffer.from(decoded).toString('base64url') !== cursor) throw failure('invalid_query');
|
|
53
|
+
offset = Number(decoded.split(':')[1]);
|
|
54
|
+
}
|
|
55
|
+
const subscription = params.get('subscription');
|
|
56
|
+
if (resource === 'subscription-items' && !/^sub_[A-Za-z0-9]{1,120}$/.test(subscription || '')) throw failure('invalid_query');
|
|
57
|
+
return { section, resource, limit, cursor, offset, subscription };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function guardPath(root, candidate) {
|
|
61
|
+
const lexicalRoot = path.resolve(root);
|
|
62
|
+
const absoluteRoot = fs.realpathSync(lexicalRoot);
|
|
63
|
+
const resolved = path.resolve(candidate);
|
|
64
|
+
const within = (value, base) => value === base || value.startsWith(base + path.sep);
|
|
65
|
+
if (!within(resolved, lexicalRoot) && !within(resolved, absoluteRoot)) throw failure('unsafe_path');
|
|
66
|
+
const relative = path.relative(within(resolved, lexicalRoot) ? lexicalRoot : absoluteRoot, resolved);
|
|
67
|
+
let current = absoluteRoot;
|
|
68
|
+
for (const component of relative.split(path.sep).filter(Boolean)) {
|
|
69
|
+
current = path.join(current, component);
|
|
70
|
+
try { if (fs.lstatSync(current).isSymbolicLink()) throw failure('unsafe_path'); }
|
|
71
|
+
catch (error) { if (error.code === 'ENOENT') break; throw error; }
|
|
72
|
+
}
|
|
73
|
+
return path.join(absoluteRoot, relative);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readObject(root, filename) {
|
|
77
|
+
let fd;
|
|
78
|
+
try {
|
|
79
|
+
const target = guardPath(root, path.join(root, filename));
|
|
80
|
+
fd = fs.openSync(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
81
|
+
const stat = fs.fstatSync(fd);
|
|
82
|
+
if (!stat.isFile() || stat.size > JSON_LIMIT) return { state: 'oversized', value: {} };
|
|
83
|
+
const value = JSON.parse(fs.readFileSync(fd, 'utf8'));
|
|
84
|
+
if (!object(value)) return { state: 'corrupt', value: {} };
|
|
85
|
+
return { state: 'ok', value };
|
|
86
|
+
} catch (error) { return { state: error.code === 'ENOENT' ? 'missing' : 'corrupt', value: {} }; }
|
|
87
|
+
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readOwnerIdentity({ feedbackDir, token, isOwner, now = Date.now() }) {
|
|
91
|
+
if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) return null;
|
|
92
|
+
const store = readObject(feedbackDir, 'auth-sessions.json');
|
|
93
|
+
if (store.state !== 'ok') return null;
|
|
94
|
+
const entry = store.value[crypto.createHash('sha256').update(token).digest('hex')];
|
|
95
|
+
if (!object(entry) || !['apple', 'google'].includes(entry.ssoProvider) || !Number.isFinite(entry.expiresAt)
|
|
96
|
+
|| entry.expiresAt <= now || !isOwner(entry.ssoEmail)) return null;
|
|
97
|
+
return { provider: entry.ssoProvider };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function envelope(source, data, warnings = [], status = warnings.length ? 'partial' : 'ok') {
|
|
101
|
+
return { status, generatedAt: new Date().toISOString(), source, data, warnings };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function createRuntimeObservations(now = Date.now()) {
|
|
105
|
+
const errors = [];
|
|
106
|
+
const buckets = new Map();
|
|
107
|
+
const trim = (stamp) => { for (const key of buckets.keys()) if (key < Math.floor(stamp / 1000) - 59) buckets.delete(key); };
|
|
108
|
+
return {
|
|
109
|
+
recordResponse(status, route, stamp = Date.now()) {
|
|
110
|
+
if (status < 500 || status > 599) return;
|
|
111
|
+
errors.push({ timestamp: new Date(stamp).toISOString(), status, route: ['admin', 'telemetry', 'health', 'api', 'page'].includes(route) ? route : 'other' });
|
|
112
|
+
if (errors.length > 100) errors.shift();
|
|
113
|
+
},
|
|
114
|
+
recordTelemetry(persisted, stamp = Date.now()) {
|
|
115
|
+
if (!persisted) return;
|
|
116
|
+
trim(stamp);
|
|
117
|
+
const key = Math.floor(stamp / 1000);
|
|
118
|
+
buckets.set(key, (buckets.get(key) || 0) + 1);
|
|
119
|
+
},
|
|
120
|
+
snapshot(stamp = Date.now()) {
|
|
121
|
+
trim(stamp);
|
|
122
|
+
let events = 0;
|
|
123
|
+
for (const [second, count] of buckets) if (second <= Math.floor(stamp / 1000)) events += count;
|
|
124
|
+
return { processStartedAt: new Date(now).toISOString(), recentErrors: errors.slice(), errorRetention: 'last_100_http_5xx_since_process_start', telemetry: { events, windowSeconds: Math.min(60, Math.max(0, (stamp - now) / 1000)), observationStartedAt: new Date(now).toISOString(), resolutionSeconds: 1, retainedSeconds: buckets.size, windowStart: new Date(Math.max(now, (Math.floor(stamp / 1000) - 59) * 1000)).toISOString() } };
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function projectStripe(resource, row) {
|
|
130
|
+
const customer = object(row.customer) ? row.customer : null;
|
|
131
|
+
const base = { id: id(row.id), created: number(row.created), livemode: typeof row.livemode === 'boolean' ? row.livemode : typeof row.charge?.livemode === 'boolean' ? row.charge.livemode : null, classification: billing.classifyRevenueRecord(row) };
|
|
132
|
+
const price = (item) => ({ id: id(item.id), product: id(item.product), active: typeof item.active === 'boolean' ? item.active : null, unit_amount: number(item.unit_amount), currency: text(item.currency, 3), recurring: item.recurring ? { interval: text(item.recurring.interval, 16), interval_count: number(item.recurring.interval_count) } : null });
|
|
133
|
+
if (resource === 'subscription-items') return { ...base, quantity: number(row.quantity), current_period_end: number(row.current_period_end), price: price(row.price || {}) };
|
|
134
|
+
if (resource === 'customers') return { ...base, name: text(row.name), email: text(row.email, 320) };
|
|
135
|
+
if (resource === 'subscriptions') return { ...base, customer: id(row.customer), customerName: text(customer?.name), customerEmail: text(customer?.email, 320), status: text(row.status, 32), current_period_end: number(row.current_period_end), cancel_at_period_end: row.cancel_at_period_end === true, items: (row.items?.data || []).slice(0, 100).map((item) => ({ quantity: number(item.quantity), current_period_end: number(item.current_period_end), price: price(item.price || {}) })), itemsComplete: row.items?.has_more !== true };
|
|
136
|
+
if (resource === 'payments') return { ...base, customer: id(row.customer), amount: number(row.amount), currency: text(row.currency, 3), paid: row.paid === true, status: text(row.status, 32), amount_refunded: number(row.amount_refunded) };
|
|
137
|
+
if (resource === 'refunds') return { ...base, charge: id(row.charge), amount: number(row.amount), currency: text(row.currency, 3), status: text(row.status, 32) };
|
|
138
|
+
if (resource === 'products') return { ...base, name: text(row.name), active: row.active === true };
|
|
139
|
+
return { ...base, ...price(row) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function collectStripe(route, deps, signal) {
|
|
143
|
+
stopped(signal);
|
|
144
|
+
const stripe = (deps.getStripeClient || billing.getStripeClient)();
|
|
145
|
+
const api = stripe[route.resource === 'payments' ? 'charges' : route.resource === 'subscription-items' ? 'subscriptionItems' : route.resource];
|
|
146
|
+
const params = { limit: route.limit, ...(route.cursor ? { starting_after: route.cursor } : {}) };
|
|
147
|
+
if (route.resource === 'subscriptions') params.status = 'all';
|
|
148
|
+
if (route.resource === 'subscription-items') params.subscription = route.subscription;
|
|
149
|
+
if (['subscriptions', 'payments'].includes(route.resource)) params.expand = ['data.customer'];
|
|
150
|
+
if (route.resource === 'refunds') params.expand = ['data.charge.customer'];
|
|
151
|
+
const result = await deadline(billing.withStripeReadSlot(() => api.list(params, { timeout: 8000, maxNetworkRetries: 0 }), { signal }), 8000, signal);
|
|
152
|
+
stopped(signal);
|
|
153
|
+
if (!Array.isArray(result?.data)) throw failure('provider_unavailable');
|
|
154
|
+
const records = result.data.map((row) => projectStripe(route.resource, row));
|
|
155
|
+
const warnings = records.some((row) => row.itemsComplete === false) ? ['subscription_items_incomplete'] : [];
|
|
156
|
+
return envelope('stripe_account', { records, hasMore: result.has_more === true, nextCursor: result.has_more && records.length ? records.at(-1).id : null }, warnings);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function countRecords(root, target, signal) {
|
|
160
|
+
stopped(signal);
|
|
161
|
+
let stream;
|
|
162
|
+
let lines;
|
|
163
|
+
let total = 0;
|
|
164
|
+
let malformedLines = 0;
|
|
165
|
+
try {
|
|
166
|
+
const safe = guardPath(root, target);
|
|
167
|
+
const stat = await fs.promises.lstat(safe);
|
|
168
|
+
if (!stat.isFile()) throw failure('unsafe_path');
|
|
169
|
+
stream = fs.createReadStream(safe, { flags: fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW, start: 0, end: LOG_LIMIT - 1, signal });
|
|
170
|
+
lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
171
|
+
let scanned = 0;
|
|
172
|
+
for await (const line of lines) {
|
|
173
|
+
stopped(signal);
|
|
174
|
+
if (!line.trim()) continue;
|
|
175
|
+
scanned += 1;
|
|
176
|
+
try { if (object(JSON.parse(line))) total += 1; else malformedLines += 1; } catch { malformedLines += 1; }
|
|
177
|
+
if (scanned >= 100000) return { total, complete: false, malformedLines, state: 'truncated' };
|
|
178
|
+
}
|
|
179
|
+
const complete = stat.size <= LOG_LIMIT && !malformedLines;
|
|
180
|
+
return { total, complete, malformedLines, state: complete ? 'ok' : stat.size > LOG_LIMIT ? 'truncated' : 'corrupt' };
|
|
181
|
+
} catch (error) {
|
|
182
|
+
stopped(signal);
|
|
183
|
+
return { total: null, complete: false, malformedLines, state: error.code === 'ENOENT' ? 'missing' : 'unavailable' };
|
|
184
|
+
} finally { lines?.close(); stream?.destroy(); }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function countPartition(root, partition, signal) {
|
|
188
|
+
if (!/^(tenant|sso_free)_[a-f0-9]{24}$/.test(partition)) throw failure('unsafe_path');
|
|
189
|
+
const dir = guardPath(root, path.join(root, 'tenants', partition));
|
|
190
|
+
try { await fs.promises.access(dir); } catch (error) {
|
|
191
|
+
if (error.code !== 'ENOENT') throw error;
|
|
192
|
+
return { partition, state: 'no_hosted_data', feedback: { total: 0, complete: true, state: 'absent_tenant', malformedLines: 0 }, lessons: { total: 0, complete: true, state: 'absent_tenant', malformedLines: 0 } };
|
|
193
|
+
}
|
|
194
|
+
const feedback = await countRecords(root, path.join(dir, 'feedback-log.jsonl'), signal);
|
|
195
|
+
const lessons = await countRecords(root, path.join(dir, 'memory-log.jsonl'), signal);
|
|
196
|
+
return { partition, state: feedback.complete && lessons.complete ? 'ok' : 'partial', feedback, lessons };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function collectData(route, deps, signal) {
|
|
200
|
+
const root = deps.feedbackDir;
|
|
201
|
+
const keys = readObject(root, 'api-keys.json');
|
|
202
|
+
const sessions = readObject(root, 'auth-sessions.json');
|
|
203
|
+
const warnings = [];
|
|
204
|
+
if (keys.state !== 'ok' || !object(keys.value.keys)) warnings.push('key_store_' + (keys.state === 'ok' ? 'corrupt' : keys.state));
|
|
205
|
+
if (sessions.state !== 'ok') warnings.push('session_store_' + sessions.state);
|
|
206
|
+
const usableKeys = keys.state === 'ok' && object(keys.value.keys);
|
|
207
|
+
const usableSessions = sessions.state === 'ok';
|
|
208
|
+
if (!usableKeys && !usableSessions) return envelope('current_known_accounts', null, warnings, 'unavailable');
|
|
209
|
+
const inventoryComplete = usableKeys && usableSessions;
|
|
210
|
+
const accounts = new Map();
|
|
211
|
+
const emailCustomers = new Map();
|
|
212
|
+
const normalized = (email) => typeof email === 'string' ? email.trim().toLowerCase() : '';
|
|
213
|
+
for (const meta of Object.values(usableKeys ? keys.value.keys : {})) {
|
|
214
|
+
if (!object(meta) || typeof meta.customerId !== 'string' || !meta.customerId) continue;
|
|
215
|
+
const email = normalized(meta.customerEmail);
|
|
216
|
+
const key = 'paid:' + meta.customerId;
|
|
217
|
+
if (!accounts.has(key)) accounts.set(key, { customerId: meta.customerId, email, createdAt: text(meta.createdAt), hasActiveKey: false, hasCurrentSession: false, freeEmails: new Set() });
|
|
218
|
+
accounts.get(key).hasActiveKey ||= meta.active === true;
|
|
219
|
+
if (email) { const matches = emailCustomers.get(email) || new Set(); matches.add(key); emailCustomers.set(email, matches); }
|
|
220
|
+
}
|
|
221
|
+
for (const session of Object.values(sessions.value)) {
|
|
222
|
+
if (!object(session) || !['apple', 'google'].includes(session.ssoProvider) || !(session.expiresAt > Date.now())) continue;
|
|
223
|
+
const email = normalized(session.ssoEmail);
|
|
224
|
+
if (!email) continue;
|
|
225
|
+
const customerKey = session.customerId ? 'paid:' + session.customerId : null;
|
|
226
|
+
if (customerKey && !accounts.has(customerKey)) accounts.set(customerKey, { customerId: session.customerId, email, createdAt: Number.isFinite(session.createdAt) ? new Date(session.createdAt).toISOString() : null, hasActiveKey: false, hasCurrentSession: true, freeEmails: new Set() });
|
|
227
|
+
const matches = emailCustomers.get(email);
|
|
228
|
+
const joined = customerKey && accounts.has(customerKey) ? customerKey : matches?.size === 1 ? [...matches][0] : null;
|
|
229
|
+
const key = joined || 'sso:' + email;
|
|
230
|
+
if (!accounts.has(key)) accounts.set(key, { customerId: null, email, createdAt: Number.isFinite(session.createdAt) ? new Date(session.createdAt).toISOString() : null, hasActiveKey: false, hasCurrentSession: true, possibleDuplicate: Boolean(matches?.size > 1), freeEmails: new Set() });
|
|
231
|
+
accounts.get(key).hasCurrentSession = true;
|
|
232
|
+
if (!session.customerId || session.subjectType === 'sso_free') accounts.get(key).freeEmails.add(email);
|
|
233
|
+
}
|
|
234
|
+
const ordered = [...accounts.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
235
|
+
const page = ordered.slice(route.offset, route.offset + route.limit);
|
|
236
|
+
const records = [];
|
|
237
|
+
for (const [, account] of page) {
|
|
238
|
+
stopped(signal);
|
|
239
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
240
|
+
const partitions = new Set();
|
|
241
|
+
if (account.customerId) partitions.add(deps.buildHostedTenantIdentity({ valid: true, customerId: account.customerId }).partition);
|
|
242
|
+
for (const email of account.freeEmails) partitions.add(deps.hashDataIdentity('sso_free', email));
|
|
243
|
+
const counts = [];
|
|
244
|
+
for (const partition of partitions) counts.push(await countPartition(root, partition, signal));
|
|
245
|
+
if (counts.some((row) => row.state === 'partial')) warnings.push('account_counts_partial');
|
|
246
|
+
records.push({ accountId: account.customerId ? text(account.customerId, 128) : [...partitions][0], email: text(account.email, 320), createdAt: account.createdAt, hasActiveKey: account.hasActiveKey, hasCurrentSession: account.hasCurrentSession, possibleDuplicate: account.possibleDuplicate === true, classification: billing.classifyRevenueRecord({ email: account.email }), partitions: counts });
|
|
247
|
+
}
|
|
248
|
+
stopped(signal);
|
|
249
|
+
const feedback = await countRecords(root, path.join(root, 'feedback-log.jsonl'), signal);
|
|
250
|
+
const lessons = await countRecords(root, path.join(root, 'memory-log.jsonl'), signal);
|
|
251
|
+
if (!feedback.complete || !lessons.complete) warnings.push('legacy_counts_partial');
|
|
252
|
+
return envelope('current_known_accounts', { records, totalKnown: ordered.length, total: inventoryComplete ? ordered.length : null, inventoryComplete, hasMore: route.offset + page.length < ordered.length, nextCursor: route.offset + page.length < ordered.length ? Buffer.from('accounts:' + (route.offset + page.length)).toString('base64url') : null, coverage: 'current_known_accounts_not_lifetime_signups', unattributedLegacy: { feedback, lessons }, projects: { status: 'unavailable', reason: 'project_scope_not_integrated' } }, [...new Set(warnings)]);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const numericFields = (value, names) => Object.fromEntries(names.map((name) => [name, number(value?.[name])]));
|
|
256
|
+
const currencies = (value) => Object.fromEntries(Object.entries(value || {}).filter(([key, amount]) => /^[A-Z]{3}$/.test(key) && Number.isSafeInteger(amount)));
|
|
257
|
+
function projectAnalytics(summary) {
|
|
258
|
+
const external = summary.revenue?.external;
|
|
259
|
+
return {
|
|
260
|
+
funnel: { ...numericFields(summary.funnel, ['totalEvents', 'uniqueAcquisitionLeads', 'uniquePaidCustomers', 'excludedSyntheticCheckoutSessions']), stageCounts: numericFields(summary.funnel?.stageCounts, ['acquisition', 'activation', 'paid']), conversionRates: numericFields(summary.funnel?.conversionRates, ['acquisitionToActivation', 'activationToPaid', 'acquisitionToPaid']) },
|
|
261
|
+
signups: numericFields(summary.signups, ['total', 'uniqueLeads', 'emailSignups', 'emailRecords', 'checkoutSessionsCreated']),
|
|
262
|
+
revenue: { external: { ...numericFields(external, ['paidOrders', 'amountUnknownOrders', 'duplicates']), bookedRevenueByCurrency: currencies(external?.bookedRevenueByCurrency), refundedByCurrency: currencies(external?.refundedByCurrency), excluded: numericFields(external?.excluded, ['internal', 'test', 'unknown']) }, broadAccounting: { ...numericFields(summary.revenue, ['paidOrders', 'paidCustomers', 'amountKnownOrders', 'amountUnknownOrders']), bookedRevenueByCurrency: currencies(summary.revenue?.bookedRevenueByCurrency) } },
|
|
263
|
+
trafficMetrics: numericFields(summary.trafficMetrics, ['visitors', 'sessions', 'pageViews', 'ctaClicks', 'checkoutStarts', 'checkoutPaidConfirmations']),
|
|
264
|
+
attribution: { coverageRate: number(summary.dataQuality?.attributionCoverage) },
|
|
265
|
+
dataQuality: { ...numericFields(summary.dataQuality, ['telemetryCoverage', 'attributionCoverage', 'amountKnownCoverage', 'unreconciledPaidEvents']), telemetryLogTruncated: summary.dataQuality?.telemetryLogTruncated === true, telemetryWindowComplete: summary.dataQuality?.telemetryWindowComplete === true },
|
|
266
|
+
reconciliation: { status: ['ok', 'partial', 'timeout', 'unavailable', 'unconfigured'].includes(summary.reconciliation?.status) ? summary.reconciliation.status : 'unavailable', complete: summary.reconciliation?.complete === true },
|
|
267
|
+
window: '30d',
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function preflightAnalytics(root) {
|
|
272
|
+
let total = 0;
|
|
273
|
+
for (const source of billing.getBillingAnalyticsReadPaths()) {
|
|
274
|
+
try {
|
|
275
|
+
const stat = await fs.promises.stat(guardPath(root, source));
|
|
276
|
+
total += stat.size;
|
|
277
|
+
if (!stat.isFile() || total > JSON_LIMIT) throw failure('analytics_source_budget');
|
|
278
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function collectObservability(deps, signal) {
|
|
283
|
+
stopped(signal);
|
|
284
|
+
let disk = null;
|
|
285
|
+
const warnings = [];
|
|
286
|
+
try {
|
|
287
|
+
const stats = await fs.promises.statfs(guardPath(deps.feedbackDir, deps.feedbackDir));
|
|
288
|
+
disk = { capacityBytes: stats.blocks * stats.bsize, freeBytes: stats.bavail * stats.bsize, usedBytes: (stats.blocks - stats.bfree) * stats.bsize, scope: 'volume_filesystem' };
|
|
289
|
+
} catch { warnings.push('disk_unavailable'); }
|
|
290
|
+
return envelope('current_process', { ...deps.health(), ...deps.runtime.snapshot(), deployment: { id: text(process.env.RAILWAY_DEPLOYMENT_ID, 128), commit: text(process.env.RAILWAY_GIT_COMMIT_SHA, 64), deployedAt: null, deploymentTimeStatus: 'unavailable', buildGeneratedAt: text(deps.buildMetadata?.generatedAt, 64) }, disk }, warnings);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function deadline(promise, ms, signal) {
|
|
294
|
+
return new Promise((resolve, reject) => {
|
|
295
|
+
const abort = () => finish(reject, failure('collection_timeout'));
|
|
296
|
+
const timer = setTimeout(abort, ms);
|
|
297
|
+
const finish = (fn, value) => { clearTimeout(timer); signal?.removeEventListener('abort', abort); fn(value); };
|
|
298
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
299
|
+
if (signal?.aborted) abort();
|
|
300
|
+
Promise.resolve(promise).then((value) => finish(resolve, value), (error) => finish(reject, error));
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function collectAdminSection(route, deps, externalSignal) {
|
|
305
|
+
if (activeCollections >= 2) throw failure('collection_busy');
|
|
306
|
+
activeCollections += 1;
|
|
307
|
+
const controller = new AbortController();
|
|
308
|
+
const abort = () => controller.abort();
|
|
309
|
+
externalSignal?.addEventListener('abort', abort, { once: true });
|
|
310
|
+
if (externalSignal?.aborted) abort();
|
|
311
|
+
const timer = setTimeout(abort, deps.sectionTimeoutMs || 10000);
|
|
312
|
+
try {
|
|
313
|
+
const operation = async () => {
|
|
314
|
+
stopped(controller.signal);
|
|
315
|
+
if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
|
|
316
|
+
if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
|
|
317
|
+
if (route.section === 'data') return collectData(route, deps, controller.signal);
|
|
318
|
+
if (route.section === 'observability') return collectObservability(deps, controller.signal);
|
|
319
|
+
await preflightAnalytics(deps.feedbackDir);
|
|
320
|
+
stopped(controller.signal);
|
|
321
|
+
const summary = await (deps.getBillingSummaryLive || billing.getBillingSummaryLive)({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal: controller.signal });
|
|
322
|
+
stopped(controller.signal);
|
|
323
|
+
if (summary.error) throw failure('analytics_unavailable');
|
|
324
|
+
const data = projectAnalytics(summary);
|
|
325
|
+
const warnings = data.reconciliation.status !== 'ok' || !data.reconciliation.complete ? ['stripe_reconciliation_' + data.reconciliation.status] : [];
|
|
326
|
+
if (summary.sourceDiagnostics?.warnings?.length) warnings.push('source_quality_warning');
|
|
327
|
+
if (!data.dataQuality.telemetryWindowComplete) warnings.push('telemetry_incomplete');
|
|
328
|
+
return envelope('shared_billing_summary_30d', data, warnings);
|
|
329
|
+
};
|
|
330
|
+
return await deadline(operation(), deps.sectionTimeoutMs || 10000, controller.signal);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
return envelope(route.section, null, [error.code === 'collection_timeout' ? 'collection_timeout' : error.code === 'analytics_source_budget' ? 'analytics_source_budget' : 'source_unavailable'], 'unavailable');
|
|
333
|
+
} finally {
|
|
334
|
+
abort(); clearTimeout(timer); externalSignal?.removeEventListener('abort', abort); activeCollections -= 1;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, collectAdminSection, createRuntimeObservations, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
package/scripts/pr-manager.js
CHANGED
|
@@ -482,8 +482,197 @@ 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';
|
|
486
|
+
const SWEEP_LIST_LIMIT = '1000';
|
|
487
|
+
const SWEEP_REQUIRED_CHECKS_BASE = 'main';
|
|
488
|
+
const DEFAULT_RED_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
489
|
+
const DEFAULT_DRAFT_IDLE_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
|
|
490
|
+
const REQUIRED_CHECK_SET = new Set(MERGE_QUALITY_CHECKS.requiredStatusCheckContexts || []);
|
|
491
|
+
|
|
492
|
+
function isProtectedSweepBranch(pr = {}) {
|
|
493
|
+
const headRef = String(pr.headRefName || '').trim();
|
|
494
|
+
const authorLogin = String(pr.author?.login || '').trim().toLowerCase();
|
|
495
|
+
if (headRef.startsWith('dependabot/') || headRef.startsWith('trunk-merge/')) {
|
|
496
|
+
return true;
|
|
497
|
+
}
|
|
498
|
+
return authorLogin === 'dependabot[bot]' || authorLogin === 'app/dependabot' || authorLogin === 'dependabot';
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function isRequiredCheckFailing(check = {}) {
|
|
502
|
+
const name = check.name || check.context || '';
|
|
503
|
+
if (!name || SELF_REFERENTIAL_CHECKS.has(name) || OPTIONAL_CHECKS.has(name)) {
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
if (REQUIRED_CHECK_SET.size > 0 && !REQUIRED_CHECK_SET.has(name)) {
|
|
507
|
+
return false;
|
|
508
|
+
}
|
|
509
|
+
const bucket = String(check.bucket || '').toLowerCase();
|
|
510
|
+
if (bucket) {
|
|
511
|
+
return FAILING_BUCKETS.has(bucket);
|
|
512
|
+
}
|
|
513
|
+
const conclusion = String(check.conclusion || check.state || '').toUpperCase();
|
|
514
|
+
return FAILING_CHECK_CONCLUSIONS.has(conclusion) || conclusion === 'ERROR';
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function classifyStalePr(pr = {}, options = {}) {
|
|
518
|
+
const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
|
|
519
|
+
const redMaxAgeMs = Number.isFinite(options.redMaxAgeMs) ? options.redMaxAgeMs : DEFAULT_RED_MAX_AGE_MS;
|
|
520
|
+
const draftIdleMaxAgeMs = Number.isFinite(options.draftIdleMaxAgeMs)
|
|
521
|
+
? options.draftIdleMaxAgeMs
|
|
522
|
+
: DEFAULT_DRAFT_IDLE_MAX_AGE_MS;
|
|
523
|
+
|
|
524
|
+
if (isProtectedSweepBranch(pr)) {
|
|
525
|
+
return {
|
|
526
|
+
action: 'skip',
|
|
527
|
+
reason: 'protected_branch',
|
|
528
|
+
headRefName: pr.headRefName || '',
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (pr.isDraft) {
|
|
533
|
+
const updatedMs = Date.parse(pr.updatedAt || pr.createdAt || '');
|
|
534
|
+
if (Number.isFinite(updatedMs) && (nowMs - updatedMs) > draftIdleMaxAgeMs) {
|
|
535
|
+
const idleDays = Math.floor((nowMs - updatedMs) / (24 * 60 * 60 * 1000));
|
|
536
|
+
return {
|
|
537
|
+
action: 'close',
|
|
538
|
+
reason: 'draft_idle_over_3d',
|
|
539
|
+
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.`,
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
return { action: 'keep', reason: 'draft_active' };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const checks = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];
|
|
547
|
+
const failingRequired = checks.filter((check) => isRequiredCheckFailing(check));
|
|
548
|
+
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
|
+
return { action: 'keep', reason: 'required_checks_unknown_for_base', baseRefName: pr.baseRefName || '' };
|
|
552
|
+
}
|
|
553
|
+
if (failingRequired.length > 0) {
|
|
554
|
+
const checkTimestamps = failingRequired
|
|
555
|
+
.map((check) => Date.parse(check.completedAt || check.startedAt || ''))
|
|
556
|
+
.filter((ts) => Number.isFinite(ts));
|
|
557
|
+
const fallbackMs = Date.parse(pr.updatedAt || pr.createdAt || '');
|
|
558
|
+
const redSinceMs = checkTimestamps.length > 0
|
|
559
|
+
? Math.max(...checkTimestamps)
|
|
560
|
+
: fallbackMs;
|
|
561
|
+
|
|
562
|
+
if (Number.isFinite(redSinceMs) && (nowMs - redSinceMs) > redMaxAgeMs) {
|
|
563
|
+
const redHours = Math.floor((nowMs - redSinceMs) / (60 * 60 * 1000));
|
|
564
|
+
const failingNames = [...new Set(failingRequired.map((c) => c.name || c.context))];
|
|
565
|
+
return {
|
|
566
|
+
action: 'close',
|
|
567
|
+
reason: 'red_checks_over_24h',
|
|
568
|
+
redHours,
|
|
569
|
+
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.`,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
return { action: 'keep', reason: 'active' };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function stillEligibleForClose(number, options, runner) {
|
|
579
|
+
const viewResult = runner(['pr', 'view', String(number), '--json', SWEEP_PR_FIELDS]);
|
|
580
|
+
if (viewResult.status !== 0) {
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
584
|
+
const fresh = JSON.parse(viewResult.stdout || '{}');
|
|
585
|
+
return fresh.state === 'OPEN' && classifyStalePr(fresh, options).action === 'close';
|
|
586
|
+
} catch {
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function sweepStalePrs(options = {}, runner = runGh) {
|
|
592
|
+
const dryRun = Boolean(options.dryRun);
|
|
593
|
+
// A high limit makes gh paginate through every open PR, so none are silently skipped.
|
|
594
|
+
const listResult = runner(['pr', 'list', '--state', 'open', '--limit', SWEEP_LIST_LIMIT, '--json', SWEEP_PR_FIELDS]);
|
|
595
|
+
if (listResult.status !== 0) {
|
|
596
|
+
throw new Error(`Failed to list open PRs for sweep: ${formatGhError(listResult)}`);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const prs = JSON.parse(listResult.stdout || '[]');
|
|
600
|
+
const decisions = [];
|
|
601
|
+
let closedCount = 0;
|
|
602
|
+
let skippedCount = 0;
|
|
603
|
+
let keptCount = 0;
|
|
604
|
+
|
|
605
|
+
for (const pr of prs) {
|
|
606
|
+
const verdict = classifyStalePr(pr, options);
|
|
607
|
+
const record = {
|
|
608
|
+
number: pr.number,
|
|
609
|
+
title: pr.title || '',
|
|
610
|
+
headRefName: pr.headRefName || '',
|
|
611
|
+
isDraft: Boolean(pr.isDraft),
|
|
612
|
+
...verdict,
|
|
613
|
+
applied: false,
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
if (verdict.action === 'skip') {
|
|
617
|
+
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).
|
|
620
|
+
record.action = 'keep';
|
|
621
|
+
record.reason = 'eligibility_changed';
|
|
622
|
+
keptCount += 1;
|
|
623
|
+
} else if (verdict.action === 'close') {
|
|
624
|
+
closedCount += 1;
|
|
625
|
+
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)}`);
|
|
634
|
+
}
|
|
635
|
+
record.applied = true;
|
|
636
|
+
}
|
|
637
|
+
} else {
|
|
638
|
+
keptCount += 1;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
decisions.push(record);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
return {
|
|
645
|
+
status: 'ok',
|
|
646
|
+
dryRun,
|
|
647
|
+
closedCount,
|
|
648
|
+
skippedCount,
|
|
649
|
+
keptCount,
|
|
650
|
+
decisions,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
485
654
|
if (require.main === module) {
|
|
486
|
-
const
|
|
655
|
+
const argv = process.argv.slice(2);
|
|
656
|
+
if (argv.includes('--sweep') || argv.includes('--sweep-stale')) {
|
|
657
|
+
try {
|
|
658
|
+
const summary = sweepStalePrs({
|
|
659
|
+
dryRun: argv.includes('--dry-run'),
|
|
660
|
+
});
|
|
661
|
+
if (argv.includes('--json')) {
|
|
662
|
+
console.log(JSON.stringify(summary, null, 2));
|
|
663
|
+
} else {
|
|
664
|
+
console.log(
|
|
665
|
+
`[PR Sweeper] dryRun=${summary.dryRun} closed=${summary.closedCount} skipped=${summary.skippedCount} kept=${summary.keptCount}`,
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
process.exit(0);
|
|
669
|
+
} catch (err) {
|
|
670
|
+
console.error(err.message);
|
|
671
|
+
process.exit(1);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
const prNum = argv[0];
|
|
487
676
|
managePrs(prNum).then(() => {
|
|
488
677
|
process.exit(0);
|
|
489
678
|
}).catch((err) => {
|
|
@@ -495,8 +684,11 @@ if (require.main === module) {
|
|
|
495
684
|
module.exports = {
|
|
496
685
|
assertSafeGhArgs,
|
|
497
686
|
buildGhEnv,
|
|
687
|
+
classifyStalePr,
|
|
498
688
|
getPrStatus,
|
|
499
689
|
getPrChecks,
|
|
690
|
+
isProtectedSweepBranch,
|
|
691
|
+
isRequiredCheckFailing,
|
|
500
692
|
listOpenPrs,
|
|
501
693
|
isOpenPr,
|
|
502
694
|
loadManagedPrs,
|
|
@@ -507,5 +699,6 @@ module.exports = {
|
|
|
507
699
|
performMerge,
|
|
508
700
|
managePrs,
|
|
509
701
|
summarizeChecks,
|
|
702
|
+
sweepStalePrs,
|
|
510
703
|
inspectRepositoryRulesets,
|
|
511
704
|
};
|