diff --git a/src/cli/commands/corps.test.ts b/src/cli/commands/corps.test.ts index 258e8ea..9a92d97 100644 --- a/src/cli/commands/corps.test.ts +++ b/src/cli/commands/corps.test.ts @@ -7,7 +7,8 @@ import { runCli } from "../runner.js"; const ORIGINAL_ENV = { enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, config: process.env.SEAL_USE_CONFIG_FILE, - tokenStore: process.env.SEAL_USE_TOKEN_STORE + tokenStore: process.env.SEAL_USE_TOKEN_STORE, + usageFile: process.env.SEAL_USE_USAGE_FILE }; const ORIGINAL_FETCH = globalThis.fetch; const tempDirs: string[] = []; @@ -16,6 +17,7 @@ afterEach(() => { restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises); restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config); restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore); + restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile); globalThis.fetch = ORIGINAL_FETCH; for (const dir of tempDirs.splice(0)) { @@ -415,3 +417,76 @@ function restoreEnv(name: string, value: string | undefined) { if (value === undefined) delete process.env[name]; else process.env[name] = value; } + +describe("corps list sorting and limit", () => { + test("limits output to 10 by default and sorts by 7-day usage frequency", async () => { + const enterprisesDir = setupConfigEnv(); + mkdirSync(enterprisesDir, { recursive: true }); + const usageDir = mkdtempSync(join(tmpdir(), "seal-usage-test-")); + tempDirs.push(usageDir); + const usageFile = join(usageDir, "usage.json"); + process.env.SEAL_USE_USAGE_FILE = usageFile; + + // Create 12 corporations: corp-01 to corp-12 + for (let i = 1; i <= 12; i++) { + const id = `corp-${String(i).padStart(2, "0")}`; + writeFileSync( + join(enterprisesDir, `${id}.json`), + JSON.stringify({ + id, + name: `Enterprise ${id}`, + environment: "production", + seal: { url: `https://${id}.sealai.cc` }, + source: { + type: "hose", + domain: "https://dd2.hosecloud.com", + appKey: "key", + appSecurity: "sec", + corpId: id, + staffId: id + }, + auth: { refreshTtl: 300 } + }) + ); + } + + // Record usage: corp-05 has 20 hits, corp-02 has 10 hits, corp-11 has 5 hits + const today = new Date().toISOString().slice(0, 10); + writeFileSync( + usageFile, + JSON.stringify({ + "corp-05": { [today]: 20 }, + "corp-02": { [today]: 10 }, + "corp-11": { [today]: 5 } + }) + ); + + // 1. Default list should limit to 10 and show hint in stderr + const defaultList = await runCli(["corps", "list"]); + expect(defaultList.isError).toBe(false); + const defaultItems = JSON.parse(defaultList.stdout); + expect(defaultItems.length).toBe(10); + expect(defaultItems[0].id).toBe("corp-05"); + expect(defaultItems[1].id).toBe("corp-02"); + expect(defaultItems[2].id).toBe("corp-11"); + expect(defaultList.stderr).toContain("当前共有 12 家企业,已按最近 7 天使用频次展示前 10 家"); + expect(defaultList.stderr).toContain("seal-use corps list --all"); + + // 2. --all should output all 12 without truncation + const allList = await runCli(["corps", "list", "--all"]); + expect(allList.isError).toBe(false); + const allItems = JSON.parse(allList.stdout); + expect(allItems.length).toBe(12); + expect(allItems[0].id).toBe("corp-05"); + expect(allItems[1].id).toBe("corp-02"); + expect(allItems[2].id).toBe("corp-11"); + expect(allList.stderr).not.toContain("展示前 10 家"); + + // 3. Custom --limit should respect given number + const limitedList = await runCli(["corps", "list", "--limit", "3"]); + expect(limitedList.isError).toBe(false); + const limitedItems = JSON.parse(limitedList.stdout); + expect(limitedItems.length).toBe(3); + expect(limitedItems.map((c: any) => c.id)).toEqual(["corp-05", "corp-02", "corp-11"]); + }); +}); diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index 7778869..69a05fa 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -22,6 +22,7 @@ import { updateCorpConfig } from "../../core/config/loader.js"; import { filterCorpsFuzzy } from "../../core/search/fuzzy.js"; +import { sortCorpsByUsageAndRecency } from "../../core/stats/usage-tracker.js"; import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js"; import type { CorpConfig, CorpEnvironment, SealSource } from "../../core/config/types.js"; import * as api from "../../domains/seal/api.js"; @@ -147,7 +148,27 @@ export async function handleCorpsCommand(action: string | undefined, maybeName: console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`); } - printJson(filtered.map((item) => ({ + const sorted = sortCorpsByUsageAndRecency(filtered, currentCorpId); + + const isList = !action || action === "list"; + const isAll = booleanOption(args.options.all) === true; + const limitOpt = numberOption(args.options.limit); + const defaultLimit = 10; + const effectiveLimit = limitOpt !== undefined ? Math.max(1, limitOpt) : (isList && !isAll ? defaultLimit : undefined); + + let displayList = sorted; + if (effectiveLimit !== undefined && sorted.length > effectiveLimit) { + displayList = sorted.slice(0, effectiveLimit); + if (isList && !isAll && limitOpt === undefined) { + console.error( + `ℹ️ 当前共有 ${sorted.length} 家企业,已按最近 7 天使用频次展示前 ${effectiveLimit} 家。\n` + + `👉 查看全部请添加: seal-use corps list --all\n` + + `👉 检索指定企业请使用: seal-use corps search ` + ); + } + } + + printJson(displayList.map((item) => ({ id: item.id, name: item.name, environment: item.environment ?? "production", diff --git a/src/cli/help.ts b/src/cli/help.ts index c9a9bf5..8a136a9 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -30,9 +30,11 @@ export const HELP_REGISTRY: AreaHelp[] = [ commands: [ { name: "list", - summary: "List all configured enterprises", - usage: ["seal-use corps list [query] [--env ] [--strict] [--corp ]"], + summary: "List configured enterprises sorted by 7-day usage frequency", + usage: ["seal-use corps list [query] [--all] [--limit ] [--env ] [--strict] [--corp ]"], options: [ + { flag: "--all", description: "Display all configured enterprises without the default 10-item limit" }, + { flag: "--limit ", description: "Maximum number of enterprises to display (defaults to 10)" }, { flag: "--env ", description: "Filter enterprises by environment ('production' or 'test')" }, { flag: "--strict", description: "Use strict exact substring matching instead of default soft fuzzy search" } ] diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts index be6da40..2e75862 100644 --- a/src/cli/helpers.ts +++ b/src/cli/helpers.ts @@ -1,5 +1,6 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolveGlobalConfigFile } from "../core/config/loader.js"; import { resolveCorpConfig } from "../core/config/manager.js"; +import { recordCorpUsage } from "../core/stats/usage-tracker.js"; import { createSealClient } from "../core/http/factory.js"; import { sealTools, type SealTool } from "../domains/seal/tools.js"; import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; @@ -9,7 +10,7 @@ import type { OutputOptions } from "./types.js"; export function selectCorp(corpId?: string): CorpConfig { const corps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); - return resolveCorpConfig( + const corp = resolveCorpConfig( corps, { stateful: globalConfig.stateful, @@ -18,6 +19,8 @@ export function selectCorp(corpId?: string): CorpConfig { }, getEnterprisesDirCandidates() ); + recordCorpUsage(corp.id); + return corp; } export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) { diff --git a/src/core/stats/usage-tracker.test.ts b/src/core/stats/usage-tracker.test.ts new file mode 100644 index 0000000..1446fbd --- /dev/null +++ b/src/core/stats/usage-tracker.test.ts @@ -0,0 +1,114 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { + computeWindowCutoff, + getRecentCorpUsageScores, + loadUsageStats, + pruneExpiredStats, + recordCorpUsage, + resolveUsageFilePath, + sortCorpsByUsageAndRecency, + toDateKey, + USAGE_FILE_ENV +} from "./usage-tracker.js"; + +describe("usage-tracker", () => { + const originalUsageFileEnv = process.env[USAGE_FILE_ENV]; + let testDir: string; + let testUsageFile: string; + + beforeEach(() => { + testDir = join(tmpdir(), `seal-use-usage-test-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`); + mkdirSync(testDir, { recursive: true }); + testUsageFile = join(testDir, "usage.json"); + process.env[USAGE_FILE_ENV] = testUsageFile; + }); + + afterEach(() => { + if (originalUsageFileEnv !== undefined) { + process.env[USAGE_FILE_ENV] = originalUsageFileEnv; + } else { + delete process.env[USAGE_FILE_ENV]; + } + rmSync(testDir, { recursive: true, force: true }); + }); + + test("resolves custom usage file path from env", () => { + expect(resolveUsageFilePath()).toBe(testUsageFile); + }); + + test("computes correct date keys and window cutoffs", () => { + const fixedDate = new Date("2026-09-13T12:00:00.000Z"); + expect(toDateKey(fixedDate)).toBe("2026-09-13"); + expect(computeWindowCutoff(7, fixedDate)).toBe("2026-09-07"); + expect(computeWindowCutoff(1, fixedDate)).toBe("2026-09-13"); + }); + + test("records usage and aggregates 7-day scores", () => { + const day1 = new Date("2026-09-10T10:00:00.000Z"); + const day2 = new Date("2026-09-13T15:00:00.000Z"); + + recordCorpUsage("corp-a", day1); + recordCorpUsage("corp-a", day1); + recordCorpUsage("corp-a", day2); + recordCorpUsage("corp-b", day2); + + const scores = getRecentCorpUsageScores(["corp-a", "corp-b", "corp-c"], 7, day2); + expect(scores.get("corp-a")).toBe(3); + expect(scores.get("corp-b")).toBe(1); + expect(scores.get("corp-c")).toBe(0); + }); + + test("prunes entries older than 7 days when recording new usage", () => { + const oldDay = new Date("2026-09-01T10:00:00.000Z"); + const currentDay = new Date("2026-09-13T10:00:00.000Z"); + + recordCorpUsage("corp-old", oldDay); + const initialStats = loadUsageStats(); + expect(initialStats["corp-old"]?.["2026-09-01"]).toBe(1); + + // Recording on current day should prune the 2026-09-01 entry + recordCorpUsage("corp-new", currentDay); + const updatedStats = loadUsageStats(); + expect(updatedStats["corp-new"]?.["2026-09-13"]).toBe(1); + expect(updatedStats["corp-old"]).toBeUndefined(); + }); + + test("handles corrupted usage file gracefully without throwing", () => { + writeFileSync(testUsageFile, "not-valid-json{{{", "utf-8"); + expect(() => recordCorpUsage("corp-safe")).not.toThrow(); + + const stats = loadUsageStats(); + expect(stats["corp-safe"]).toBeDefined(); + }); + + test("sorts corporations by current selection, usage score, then name", () => { + const corps = [ + { id: "corp-low", name: "低频企业" }, + { id: "corp-current", name: "当前企业" }, + { id: "corp-high", name: "高频企业" }, + { id: "corp-zero-b", name: "零频企业B" }, + { id: "corp-zero-a", name: "零频企业A" } + ]; + + const scores = new Map([ + ["corp-low", 2], + ["corp-current", 1], // Even with lower score, currentCorpId should be on top + ["corp-high", 20], + ["corp-zero-b", 0], + ["corp-zero-a", 0] + ]); + + const sorted = sortCorpsByUsageAndRecency(corps, "corp-current", scores); + + expect(sorted.map((c) => c.id)).toEqual([ + "corp-current", + "corp-high", + "corp-low", + "corp-zero-a", + "corp-zero-b" + ]); + }); +}); diff --git a/src/core/stats/usage-tracker.ts b/src/core/stats/usage-tracker.ts new file mode 100644 index 0000000..a3f09ce --- /dev/null +++ b/src/core/stats/usage-tracker.ts @@ -0,0 +1,157 @@ +import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE"; +const DEFAULT_USAGE_FILE = join(homedir(), ".config", "seal-use", "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 { + writeFileSync(tempPath, JSON.stringify(stats, null, 2), "utf-8"); + 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); + }); +}