import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { SEAL_CACHE_DIR } from "../paths.js"; export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE"; const DEFAULT_USAGE_FILE = join(SEAL_CACHE_DIR, "usage.json"); const DEFAULT_WINDOW_DAYS = 7; export type CorpUsageDailyStats = Record; export type CorpUsageStats = Record; export function resolveUsageFilePath(): string { const custom = process.env[USAGE_FILE_ENV]?.trim(); if (custom) return custom; return DEFAULT_USAGE_FILE; } export function toDateKey(date: Date = new Date()): string { return date.toISOString().slice(0, 10); } export function computeWindowCutoff(windowDays: number = DEFAULT_WINDOW_DAYS, now: Date = new Date()): string { const cutoffTime = now.getTime() - Math.max(0, windowDays - 1) * 86400000; return new Date(cutoffTime).toISOString().slice(0, 10); } export function loadUsageStats(filePath: string = resolveUsageFilePath()): CorpUsageStats { if (!existsSync(filePath)) { return {}; } try { const raw = readFileSync(filePath, "utf-8"); const parsed = JSON.parse(raw); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { return parsed as CorpUsageStats; } return {}; } catch { return {}; } } export function pruneExpiredStats(stats: CorpUsageStats, cutoffKey: string): CorpUsageStats { const pruned: CorpUsageStats = {}; for (const [corpId, daily] of Object.entries(stats)) { if (!daily || typeof daily !== "object") continue; const keptDaily: CorpUsageDailyStats = {}; let hasKeys = false; for (const [dateKey, count] of Object.entries(daily)) { if (typeof count === "number" && count > 0 && dateKey >= cutoffKey) { keptDaily[dateKey] = count; hasKeys = true; } } if (hasKeys) { pruned[corpId] = keptDaily; } } return pruned; } function saveUsageStatsAtomic(stats: CorpUsageStats, targetPath: string = resolveUsageFilePath()): void { const dir = dirname(targetPath); if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o700 }); } const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`; try { // 0o600 like `tokens.json`: usage rows name the enterprises this machine has been // operating, so keep them owner-only instead of inheriting the 0o644 default. writeFileSync(tempPath, JSON.stringify(stats, null, 2), { encoding: "utf-8", mode: 0o600 }); renameSync(tempPath, targetPath); } catch (err) { try { if (existsSync(tempPath)) unlinkSync(tempPath); } catch {} throw err; } } export function recordCorpUsage(corpId: string, now: Date = new Date()): void { if (!corpId || typeof corpId !== "string") return; try { const filePath = resolveUsageFilePath(); const stats = loadUsageStats(filePath); const today = toDateKey(now); const cutoffKey = computeWindowCutoff(DEFAULT_WINDOW_DAYS, now); const pruned = pruneExpiredStats(stats, cutoffKey); pruned[corpId] = pruned[corpId] || {}; pruned[corpId][today] = (pruned[corpId][today] ?? 0) + 1; saveUsageStatsAtomic(pruned, filePath); } catch { // Fail-safe: recording stats must never throw or disrupt CLI commands. } } export function getRecentCorpUsageScores( corpIds?: string[], windowDays: number = DEFAULT_WINDOW_DAYS, now: Date = new Date() ): Map { const scores = new Map(); try { const stats = loadUsageStats(); const cutoffKey = computeWindowCutoff(windowDays, now); const today = toDateKey(now); const targets = corpIds ?? Object.keys(stats); for (const id of targets) { const daily = stats[id]; if (!daily) { scores.set(id, 0); continue; } let total = 0; for (const [dateKey, count] of Object.entries(daily)) { if (dateKey >= cutoffKey && dateKey <= today && typeof count === "number") { total += count; } } scores.set(id, total); } } catch { if (corpIds) { for (const id of corpIds) scores.set(id, 0); } } return scores; } export function sortCorpsByUsageAndRecency( corps: T[], currentCorpId?: string, scores?: Map ): T[] { const usageScores = scores ?? getRecentCorpUsageScores(corps.map((c) => c.id)); return [...corps].sort((a, b) => { if (currentCorpId) { if (a.id === currentCorpId && b.id !== currentCorpId) return -1; if (b.id === currentCorpId && a.id !== currentCorpId) return 1; } const scoreA = usageScores.get(a.id) ?? 0; const scoreB = usageScores.get(b.id) ?? 0; if (scoreA !== scoreB) { return scoreB - scoreA; } const nameA = a.name ?? a.id; const nameB = b.name ?? b.id; const cmp = nameA.localeCompare(nameB, "zh-CN"); if (cmp !== 0) return cmp; return a.id.localeCompare(b.id); }); }