diff --git a/src/cli/help.ts b/src/cli/help.ts index 4ee02f0..1b89b8c 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -659,7 +659,7 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--note ", description: "Optional adjudication note" }, { flag: "--reviewed-by ", description: "Optional reviewer name for the audit trail" } ], - description: "Append-only local JSONL per tenant+month (~/.config/seal-use/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store." + description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store." }, { name: "review list", diff --git a/src/core/auth/token-store.ts b/src/core/auth/token-store.ts index 63ab0a1..288c6da 100644 --- a/src/core/auth/token-store.ts +++ b/src/core/auth/token-store.ts @@ -1,6 +1,6 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { homedir } from "node:os"; +import { SEAL_CONFIG_DIR } from "../paths.js"; import { CorpTokenCache, HoseAuthCache, @@ -9,14 +9,14 @@ import { TokenStoreSchema } from "./types.js"; -const PRIMARY_TOKEN_STORE = join(homedir(), ".config", "seal-use", "sealTokens.json"); -const LEGACY_TOKEN_STORE = join(homedir(), ".config", "seal-home", "sealTokens.json"); +const PRIMARY_TOKEN_STORE = join(SEAL_CONFIG_DIR, "tokens.json"); +const MIGRATION_TOKEN_STORE = join(SEAL_CONFIG_DIR, "sealTokens.json"); function resolveReadStorePath(): string { const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim(); if (configured) return configured; if (existsSync(PRIMARY_TOKEN_STORE)) return PRIMARY_TOKEN_STORE; - if (existsSync(LEGACY_TOKEN_STORE)) return LEGACY_TOKEN_STORE; + if (existsSync(MIGRATION_TOKEN_STORE)) return MIGRATION_TOKEN_STORE; return PRIMARY_TOKEN_STORE; } diff --git a/src/core/doctor/diagnose.ts b/src/core/doctor/diagnose.ts index 30503e9..0e2e688 100644 --- a/src/core/doctor/diagnose.ts +++ b/src/core/doctor/diagnose.ts @@ -112,10 +112,15 @@ function findGroupOrWorldReadable(paths: string[]): string[] { export function diagnoseSystem(): DoctorDiagnosis { const home = homedir(); const configDir = join(home, ".config", "seal-use"); + const stateDir = join(configDir, "state"); const enterprisesDir = join(configDir, "enterprises"); const globalConfigFile = join(configDir, "config.json"); - const tokenStore = join(configDir, "sealTokens.json"); - const mappingsDir = join(configDir, "mappings"); + const tokenStore = existsSync(join(configDir, "tokens.json")) + ? join(configDir, "tokens.json") + : existsSync(join(configDir, "sealTokens.json")) + ? join(configDir, "sealTokens.json") + : join(configDir, "tokens.json"); + const mappingsDir = existsSync(join(stateDir, "mappings")) ? join(stateDir, "mappings") : join(configDir, "mappings"); const agentSkillDir = getDefaultGlobalSkillDir(); const exportDir = join(home, "Downloads"); diff --git a/src/core/doctor/knowledge.ts b/src/core/doctor/knowledge.ts index eb9ef2b..4164bbd 100644 --- a/src/core/doctor/knowledge.ts +++ b/src/core/doctor/knowledge.ts @@ -8,7 +8,7 @@ export interface DirectorySpec { name: string; - category: "config" | "binary" | "skill" | "export" | "temp"; + category: "config" | "binary" | "skill" | "export" | "temp" | "cache"; standardPath: string; purpose: string; accessMode: "read-write" | "executable" | "transient"; @@ -55,19 +55,27 @@ export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [ { name: "会话凭据安全缓存", category: "config", - standardPath: "~/.config/seal-use/sealTokens.json", + standardPath: "~/.config/seal-use/tokens.json", purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。", accessMode: "read-write", retention: "cache" }, { - name: "规则版本映射快照", + name: "业务持久状态目录", category: "config", - standardPath: "~/.config/seal-use/mappings", - purpose: "存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。", + standardPath: "~/.config/seal-use/state", + purpose: "业务持久状态统一子目录,存放规则映射对照(mappings)、发布快照(snapshots)与人工复核账本(reviews)。", accessMode: "read-write", retention: "persistent" }, + { + name: "运行时缓存根目录", + category: "cache", + standardPath: "~/.cache/seal-use", + purpose: "用户本地运行时缓存目录,存放版本检测缓存、打点度量、官方只读校验器及报告离线资源,可随时安全清理。", + accessMode: "read-write", + retention: "cache" + }, { name: "全局命令行程序", category: "binary", diff --git a/src/core/paths.ts b/src/core/paths.ts index 1e71ebd..106558c 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -2,5 +2,12 @@ import { homedir } from "node:os"; import { join } from "node:path"; export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use"); -export const PRIMARY_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters"); -export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, "official"); +export const SEAL_STATE_DIR = join(SEAL_CONFIG_DIR, "state"); +export const SEAL_CACHE_DIR = join(homedir(), ".cache", "seal-use"); + +/** 用户全局自定义校验器存放目录(属于用户资产,保留在 ~/.config/,防止随缓存被误删) */ +export const USER_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters"); +export const PRIMARY_LINTERS_DIR = USER_LINTERS_DIR; + +/** 官方明文下发校验器目录(由 CLI 自动同步与重写,属于只读缓存,归位于 ~/.cache/) */ +export const OFFICIAL_LINTERS_DIR = join(SEAL_CACHE_DIR, "linters", "official"); diff --git a/src/core/stats/usage-tracker.ts b/src/core/stats/usage-tracker.ts index 5f73126..c904b0b 100644 --- a/src/core/stats/usage-tracker.ts +++ b/src/core/stats/usage-tracker.ts @@ -1,9 +1,10 @@ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; 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(homedir(), ".config", "seal-use", "usage.json"); +const DEFAULT_USAGE_FILE = join(SEAL_CACHE_DIR, "usage.json"); const DEFAULT_WINDOW_DAYS = 7; export type CorpUsageDailyStats = Record; diff --git a/src/core/update-cache.ts b/src/core/update-cache.ts index 1432619..d956b82 100644 --- a/src/core/update-cache.ts +++ b/src/core/update-cache.ts @@ -1,14 +1,15 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { spawn } from "node:child_process"; import type { LauncherConfig } from "./runtime.js"; import { formatBeijingIso, normalizeBeijingIso } from "./config/timestamps.js"; +import { SEAL_CACHE_DIR } from "./paths.js"; + export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE"; export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours -const DEFAULT_UPDATE_CACHE_FILE = join(homedir(), ".config", "seal-use", "update-cache.json"); +const DEFAULT_UPDATE_CACHE_FILE = join(SEAL_CACHE_DIR, "update-cache.json"); export interface UpdateCacheData { checkedAt: string; diff --git a/src/domains/seal/linter/loader.ts b/src/domains/seal/linter/loader.ts index 5cf2e8a..203e3d2 100644 --- a/src/domains/seal/linter/loader.ts +++ b/src/domains/seal/linter/loader.ts @@ -26,7 +26,7 @@ export interface AvailableLinterItem { } /** - * 强制同步"明文下发"的官方校验器到 ~/.config/seal-use/linters/official/, + * 强制同步"明文下发"的官方校验器到 ~/.cache/seal-use/linters/official/, * 并清理 official 目录下任何非清单内的多余文件。 * 哪些校验器明文下发由 manifest.ts 的 plaintext 标记决定; * 明文源码字符串由 plaintext.generated.ts 提供(生成物,勿手改)。 diff --git a/src/domains/seal/linter/manifest.ts b/src/domains/seal/linter/manifest.ts index fd2427e..f7d56a4 100644 --- a/src/domains/seal/linter/manifest.ts +++ b/src/domains/seal/linter/manifest.ts @@ -7,7 +7,7 @@ import { strictRuleLinter } from "./checkers/strict.js"; * 官方校验器清单 —— "存在哪些校验器、是否明文下发"的唯一事实源。 * * - `plaintext: true` 的条目,其源码会被 `syncOfficialLinters` 明文写入 - * `~/.config/seal-use/linters/official/`(源码字符串由 + * `~/.cache/seal-use/linters/official/`(源码字符串由 * `plaintext.generated.ts` 提供,经 `bun run generate:linter-plaintext` 从本目录生成,勿手改)。 * - `plaintext: false` 的条目只以进程内函数存在,不下发明文。 */ @@ -16,7 +16,7 @@ export interface OfficialLinterMeta { name: string; /** linters/ 下的源码文件名 */ file: string; - /** 是否明文下发到 ~/.config/seal-use/linters/official/ */ + /** 是否明文下发到 ~/.cache/seal-use/linters/official/ */ plaintext: boolean; description: string; /** 兼容别名 */ diff --git a/src/domains/seal/reports/review-store.ts b/src/domains/seal/reports/review-store.ts index 353f71e..6eed47c 100644 --- a/src/domains/seal/reports/review-store.ts +++ b/src/domains/seal/reports/review-store.ts @@ -1,5 +1,4 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; -import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { validationError } from "../../../core/errors.js"; @@ -44,13 +43,15 @@ const VERDICTS: ReadonlySet = new Set([ "undecided" ]); +import { SEAL_STATE_DIR } from "../../../core/paths.js"; + const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR"; -/** 裁决存储根目录:~/.config/seal-use/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */ +/** 裁决存储根目录:~/.config/seal-use/state/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */ export function reviewsDir(): string { const configured = process.env[REVIEWS_DIR_ENV]?.trim(); if (configured) return configured; - return join(homedir(), ".config", "seal-use", "reviews"); + return join(SEAL_STATE_DIR, "reviews"); } /** 分片路径:/-.jsonl */ diff --git a/src/domains/seal/rule-mapping.ts b/src/domains/seal/rule-mapping.ts index 6b127fb..a3c19c1 100644 --- a/src/domains/seal/rule-mapping.ts +++ b/src/domains/seal/rule-mapping.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { join } from "node:path"; import { normalizeBeijingIso } from "../../core/config/timestamps.js"; +import { SEAL_STATE_DIR } from "../../core/paths.js"; export interface RuleMappingItem { index: number; @@ -41,7 +41,7 @@ export interface RuleMappingSnapshot { export function getMappingsDir(): string { const custom = process.env.SEAL_USE_MAPPINGS_DIR?.trim(); if (custom) return custom; - return join(homedir(), ".config", "seal-use", "mappings"); + return join(SEAL_STATE_DIR, "mappings"); } export function saveRuleMappingSnapshot(snapshot: RuleMappingSnapshot): string { diff --git a/src/domains/seal/rule-version-snapshot.test.ts b/src/domains/seal/rule-version-snapshot.test.ts index 8499423..bd8edd8 100644 --- a/src/domains/seal/rule-version-snapshot.test.ts +++ b/src/domains/seal/rule-version-snapshot.test.ts @@ -39,5 +39,26 @@ describe("published rule version identity snapshots", () => { const hydrated = hydrateRuleVersionStableIds("corp/a", version); expect(hydrated.rules.map((rule) => rule.stableId)).toEqual(["draft-a", "draft-b"]); }); + + test("prunes snapshots to at most 20 files via LRU", () => { + testDir = mkdtempSync(join(tmpdir(), "seal-use-rule-snapshot-lru-")); + process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR = testDir; + + for (let i = 1; i <= 25; i++) { + const version = { + id: `published-${i}`, + versionNumber: i, + rules: [] + } as RuleSetVersion; + savePublishedRuleVersionSnapshot("corp-test", version, []); + } + + const { readdirSync } = require("node:fs"); + const remaining = readdirSync(testDir).filter((f: string) => f.endsWith(".json")); + expect(remaining.length).toBe(20); + // Oldest version 1 should have been pruned, latest version 25 must exist + expect(loadPublishedRuleVersionSnapshot("corp-test", { versionNumber: 1 } as any)).toBeNull(); + expect(loadPublishedRuleVersionSnapshot("corp-test", { versionNumber: 25 } as any)).not.toBeNull(); + }); }); diff --git a/src/domains/seal/rule-version-snapshot.ts b/src/domains/seal/rule-version-snapshot.ts index 615cbf0..5544eb1 100644 --- a/src/domains/seal/rule-version-snapshot.ts +++ b/src/domains/seal/rule-version-snapshot.ts @@ -1,9 +1,11 @@ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { formatBeijingIso } from "../../core/config/timestamps.js"; +import { SEAL_STATE_DIR } from "../../core/paths.js"; import type { ApprovalRule, RuleSetVersion } from "./types.js"; +export const MAX_RETAINED_RULE_SNAPSHOTS = 20; + export type PersistedRuleIdentity = { stableId: string; code?: string | number; @@ -33,7 +35,7 @@ function signature(rule: { description?: string; scope?: string; strictness?: st export function getRuleVersionSnapshotsDir(): string { return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim() || - join(homedir(), ".config", "seal-use", "rule-version-snapshots"); + join(SEAL_STATE_DIR, "snapshots"); } function safeCorpId(corpId: string): string { @@ -87,6 +89,25 @@ export function savePublishedRuleVersionSnapshot( const temp = `${path}.${process.pid}.tmp`; writeFileSync(temp, `${JSON.stringify(snapshot, null, 2)}\n`, { encoding: "utf8", mode: 0o600 }); renameSync(temp, path); + + try { + const files = readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".json")) + .map((entry) => { + const fullPath = join(dir, entry.name); + return { path: fullPath, mtimeMs: statSync(fullPath).mtimeMs }; + }) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + + if (files.length > MAX_RETAINED_RULE_SNAPSHOTS) { + for (const extra of files.slice(MAX_RETAINED_RULE_SNAPSHOTS)) { + unlinkSync(extra.path); + } + } + } catch { + // Non-fatal if LRU pruning fails + } + return path; }