@kanadego/dsh-heartbeat 2.2.1 → 2.4.0
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/README.md +105 -311
- package/USAGE-GUIDE.md +357 -0
- package/client.js +186 -24
- package/dist/{bili-login-XQVEE4M6.js → bili-login-KDDU63Z2.js} +4 -4
- package/dist/{bindings-U2M3CO2D.js → bindings-LTSGGNIH.js} +3 -3
- package/dist/{chunk-LQKOYTRL.js → chunk-4OQXAHU5.js} +2 -2
- package/dist/{chunk-3QJJRXIR.js → chunk-5CVAW5AS.js} +11 -2
- package/dist/chunk-5CVAW5AS.js.map +1 -0
- package/dist/{chunk-IBBAISSW.js → chunk-66IUDHCY.js} +50 -1
- package/dist/chunk-66IUDHCY.js.map +1 -0
- package/dist/{chunk-3DNGY4DS.js → chunk-77UYDI2A.js} +2 -2
- package/dist/{chunk-AT32XCCI.js → chunk-AJ5JAQVB.js} +20 -3
- package/dist/chunk-AJ5JAQVB.js.map +1 -0
- package/dist/chunk-CRRN6UD3.js +389 -0
- package/dist/chunk-CRRN6UD3.js.map +1 -0
- package/dist/{chunk-ECXYNTEV.js → chunk-ERRPMYKB.js} +164 -152
- package/dist/chunk-ERRPMYKB.js.map +1 -0
- package/dist/{chunk-M72T5MZU.js → chunk-GOLMRQRW.js} +3 -2
- package/dist/{chunk-KZLVR4J7.js → chunk-IPTNSXOY.js} +2 -2
- package/dist/chunk-L54R23O2.js +262 -0
- package/dist/chunk-L54R23O2.js.map +1 -0
- package/dist/chunk-MHRAPKES.js +1081 -0
- package/dist/chunk-MHRAPKES.js.map +1 -0
- package/dist/{chunk-SIY3YHFY.js → chunk-MMI6OBEC.js} +2 -2
- package/dist/{chunk-CJK6RTMH.js → chunk-RPWQZYNW.js} +1485 -310
- package/dist/chunk-RPWQZYNW.js.map +1 -0
- package/dist/cli/index.js +244 -36
- package/dist/cli/index.js.map +1 -1
- package/dist/{focus-store-RNHBAFYS.js → focus-store-XGTPIVF6.js} +3 -3
- package/dist/{inbox-ZLX2MH7A.js → inbox-7GGEMBUD.js} +4 -4
- package/dist/index.d.ts +66 -1
- package/dist/index.js +556 -167
- package/dist/index.js.map +1 -1
- package/dist/{migrate-XFZU5EBE.js → migrate-25F53XIC.js} +6 -4
- package/dist/{orchestrator-5BHYQ77Y.js → orchestrator-4PJD7QYO.js} +25 -11
- package/dist/runtime-RGZKOFP3.js +15 -0
- package/dist/snapshot-J6LKNY57.js +27 -0
- package/dist/store-HM6ZMFKS.js +45 -0
- package/package.json +6 -3
- package/dist/chunk-3QJJRXIR.js.map +0 -1
- package/dist/chunk-AT32XCCI.js.map +0 -1
- package/dist/chunk-CJK6RTMH.js.map +0 -1
- package/dist/chunk-DLOYERAK.js +0 -87
- package/dist/chunk-DLOYERAK.js.map +0 -1
- package/dist/chunk-ECXYNTEV.js.map +0 -1
- package/dist/chunk-F2XVKX55.js +0 -413
- package/dist/chunk-F2XVKX55.js.map +0 -1
- package/dist/chunk-IBBAISSW.js.map +0 -1
- package/dist/chunk-N6SMIGYJ.js +0 -393
- package/dist/chunk-N6SMIGYJ.js.map +0 -1
- package/dist/chunk-XYBII5PR.js +0 -602
- package/dist/chunk-XYBII5PR.js.map +0 -1
- package/dist/pool-76VLAZER.js +0 -49
- package/dist/runtime-W2OWJIHY.js +0 -11
- package/dist/snapshot-SU2VGM4C.js +0 -16
- /package/dist/{bili-login-XQVEE4M6.js.map → bili-login-KDDU63Z2.js.map} +0 -0
- /package/dist/{bindings-U2M3CO2D.js.map → bindings-LTSGGNIH.js.map} +0 -0
- /package/dist/{chunk-LQKOYTRL.js.map → chunk-4OQXAHU5.js.map} +0 -0
- /package/dist/{chunk-3DNGY4DS.js.map → chunk-77UYDI2A.js.map} +0 -0
- /package/dist/{chunk-M72T5MZU.js.map → chunk-GOLMRQRW.js.map} +0 -0
- /package/dist/{chunk-KZLVR4J7.js.map → chunk-IPTNSXOY.js.map} +0 -0
- /package/dist/{chunk-SIY3YHFY.js.map → chunk-MMI6OBEC.js.map} +0 -0
- /package/dist/{focus-store-RNHBAFYS.js.map → focus-store-XGTPIVF6.js.map} +0 -0
- /package/dist/{inbox-ZLX2MH7A.js.map → inbox-7GGEMBUD.js.map} +0 -0
- /package/dist/{migrate-XFZU5EBE.js.map → migrate-25F53XIC.js.map} +0 -0
- /package/dist/{orchestrator-5BHYQ77Y.js.map → orchestrator-4PJD7QYO.js.map} +0 -0
- /package/dist/{pool-76VLAZER.js.map → runtime-RGZKOFP3.js.map} +0 -0
- /package/dist/{runtime-W2OWJIHY.js.map → snapshot-J6LKNY57.js.map} +0 -0
- /package/dist/{snapshot-SU2VGM4C.js.map → store-HM6ZMFKS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vault/migrate.ts"],"sourcesContent":["// Cross-machine migration (v1.8.0). DPAPI binds the sensitive stores to one\n// machine + account, so a new machine cannot read them — this module packs\n// the memory files into ONE passphrase-encrypted container (AES-256-GCM,\n// scrypt-derived key, node:crypto only) that can travel safely, and restores\n// them on the other side re-encrypted with the LOCAL DPAPI.\n//\n// Restore is byte-identical: for each file we record whether it was DPAPI\n// encrypted on disk (isEncrypted magic check) and write it back through the\n// same path — no per-module write semantics to keep in sync. Existing files\n// are backed up before overwrite (rule 4).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n scryptSync,\n} from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { isEncrypted, loadEncryptedText, saveEncryptedText } from './vault.js';\n// v2.4.0: dated snapshot archives travel with the memory (each is one fold's\n// full doc — leaving them out moves a user and drops every restore point).\nimport { SNAPSHOT_ARCHIVE_NAME_RE } from '../profile/snapshot.js';\n\nexport const MIGRATE_MAGIC = 'HBMIG1';\nexport const MIGRATE_VERSION = 1;\n/** scrypt cost for NEW containers (2^14 = Node's default, 16 MiB of work).\n * Reading is parameterised by the container's own kdf.N, so raising this\n * never orphans an existing export. */\nconst KDF_N = 163_84;\n/** Hard bounds for a container-supplied N: a hostile/broken container must not\n * be able to make the import allocate unbounded memory. */\nconst KDF_N_MIN = 1 << 12; // 2^12 = 4 MiB\nconst KDF_N_MAX = 1 << 16; // 2^16 = 64 MiB\n/** Node's scrypt maxmem defaults to 32 MiB, which N=2^15 already exceeds — a\n * legal container with a larger N would fail without an explicit cap. */\nconst SCRYPT_MAXMEM = 128 * 1024 * 1024;\nconst KEY_LEN = 32;\n\n/** Memory-relevant runtime files (dataDir-relative). Deliberately NOT here:\n * gate.json (machine-local counters + home session id — the new machine\n * builds its own) and screen snapshots (per-beat transients, not memory). */\nexport const MIGRATE_FILES = [\n 'profile.json',\n 'profile_snapshot.json',\n 'profile_inbox.jsonl',\n 'profile_journal.jsonl',\n 'profile_rhythm.json',\n 'sent.json',\n 'browse.json',\n 'seeds.jsonl',\n 'ledger.md',\n // 2.3.0: books are live-only, so the archives (and the corrections book)\n // carry memory the main rows used to. Leaving them out moves a user and\n // silently drops the completions / the whole corrections book.\n 'ledger-done.md',\n 'corrections.md',\n 'corrections-done.md',\n 'cursors.json',\n // v1.9.0: persona report log + topic preference stats\n 'seed_report.jsonl',\n 'preference.json',\n];\n\n/** HB-18: an import writes with the user's privileges inside data/, so the set\n * of names a container may touch is closed, not merely sanitised. Anything an\n * export can produce is here; everything else (gate.json, settings/, vault.key,\n * other modules' files) is refused. */\nconst MIGRATE_ARCHIVE_RE = /^profile_journal\\.archive-\\d+\\.jsonl$/;\nconst MIGRATE_WEEKLY_RE = /^weekly\\/[^/\\\\]+\\.json$/;\n\nexport function isMigratablePath(rel: string): boolean {\n if (MIGRATE_FILES.includes(rel)) return true;\n if (MIGRATE_ARCHIVE_RE.test(rel)) return true;\n if (SNAPSHOT_ARCHIVE_NAME_RE.test(rel)) return true; // v2.4.0: dated snapshot archives\n if (MIGRATE_WEEKLY_RE.test(rel)) return true;\n return false;\n}\n\n/** HB-18: budget for a container-supplied payload. Generous next to a real\n * memory (a few MB), small next to what a hostile container would like. */\nexport const MIGRATE_MAX_FILES = 5_000;\nexport const MIGRATE_MAX_BYTES = 64 * 1024 * 1024;\n\nexport interface MigrateEntry {\n path: string; // dataDir-relative\n encrypted: boolean; // was DPAPI-encrypted on the source machine\n content: string;\n}\n\nexport interface MigrateProgress {\n packed: string[];\n missing: string[];\n}\n\nfunction collectWeeklyFiles(guard: PathGuard, paths: WorkspacePaths): string[] {\n const dir = path.join(paths.dataDir, 'weekly');\n try {\n return fs.readdirSync(guard.assert(dir))\n .filter((f) => f.endsWith('.json'))\n .map((f) => path.join('weekly', f).replace(/\\\\/g, '/'));\n } catch {\n return [];\n }\n}\n\n/** Journal archive shards (snapshot rotation output) travel with the memory. */\nfunction collectJournalArchives(guard: PathGuard, paths: WorkspacePaths): string[] {\n try {\n return fs.readdirSync(guard.assert(paths.dataDir))\n .filter((f) => f.startsWith('profile_journal.archive-') && f.endsWith('.jsonl'));\n } catch {\n return [];\n }\n}\n\n/** Dated snapshot archives (v2.4.0 restore points) travel with the memory too. */\nfunction collectSnapshotArchives(guard: PathGuard, paths: WorkspacePaths): string[] {\n try {\n return fs.readdirSync(guard.assert(paths.dataDir))\n .filter((f) => SNAPSHOT_ARCHIVE_NAME_RE.test(f));\n } catch {\n return [];\n }\n}\n\n/** Read every migration file. A DPAPI file that fails to decrypt aborts the\n * export — a silent half-memory container would be worse than a loud error. */\nexport function collectMigrationEntries(guard: PathGuard, paths: WorkspacePaths): { entries: MigrateEntry[]; progress: MigrateProgress } {\n const entries: MigrateEntry[] = [];\n const packed: string[] = [];\n const missing: string[] = [];\n const rels = [...MIGRATE_FILES, ...collectJournalArchives(guard, paths), ...collectSnapshotArchives(guard, paths), ...collectWeeklyFiles(guard, paths)];\n for (const rel of rels) {\n const abs = path.join(paths.dataDir, rel);\n let absCanon: string;\n try {\n absCanon = guard.assert(abs);\n } catch {\n missing.push(rel);\n continue;\n }\n if (!fs.existsSync(absCanon)) {\n missing.push(rel);\n continue;\n }\n const encrypted = isEncrypted(absCanon);\n const content = encrypted\n ? loadEncryptedText(guard, absCanon) ?? (() => { throw new Error(`cannot decrypt ${rel} on this machine`); })()\n : fs.readFileSync(absCanon, 'utf8');\n entries.push({ path: rel.replace(/\\\\/g, '/'), encrypted, content });\n packed.push(rel);\n }\n return { entries, progress: { packed, missing } };\n}\n\n/** Derive the key with the container's OWN cost parameter. `n` must already\n * have passed assertKdfN (export uses the current default). */\nfunction deriveKey(passphrase: string, salt: Buffer, n: number): Buffer {\n return scryptSync(passphrase, salt, KEY_LEN, { N: n, r: 8, p: 1, maxmem: SCRYPT_MAXMEM });\n}\n\n/** Validate the scrypt cost carried by a container. A missing/absurd N is a\n * BROKEN container — reported as such, never as \"wrong passphrase\" (before\n * 2026-10-06 the N in the container was ignored and the two were the same\n * error, so raising the cost would have orphaned every old export). */\nfunction assertKdfN(v: unknown): number {\n const n = Number(v);\n if (!Number.isInteger(n) || n <= 0 || (n & (n - 1)) !== 0) {\n throw new Error('migrate: container has invalid kdf parameters (N must be a power of two)');\n }\n if (n < KDF_N_MIN || n > KDF_N_MAX) {\n throw new Error(`migrate: container kdf N ${n} is outside the supported range [${KDF_N_MIN}, ${KDF_N_MAX}]`);\n }\n return n;\n}\n\n/** HB-18: a container does not get to decide how much work the import does. */\nfunction assertMigrateBudget(files: unknown[]): asserts files is MigrateEntry[] {\n if (files.length > MIGRATE_MAX_FILES) {\n throw new Error(`migrate: container lists ${files.length} files, over the ${MIGRATE_MAX_FILES} limit`);\n }\n let bytes = 0;\n for (const f of files) {\n const entry = f as { path?: unknown; content?: unknown } | null;\n if (!entry || typeof entry.path !== 'string' || typeof entry.content !== 'string') {\n throw new Error('migrate: container file entry is malformed');\n }\n bytes += Buffer.byteLength(entry.content, 'utf8');\n if (bytes > MIGRATE_MAX_BYTES) {\n throw new Error(`migrate: container payload exceeds ${MIGRATE_MAX_BYTES} bytes`);\n }\n }\n}\n\n/** Build the container file content. Everything sensitive lives inside the\n * ciphertext; the outer JSON carries only crypto parameters. */\nexport function encryptContainer(entries: MigrateEntry[], passphrase: string, now = new Date()): string {\n if (!passphrase) throw new Error('migrate: passphrase must not be empty');\n const salt = randomBytes(16);\n const iv = randomBytes(12);\n const key = deriveKey(passphrase, salt, KDF_N);\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const plain = Buffer.from(JSON.stringify({ version: MIGRATE_VERSION, createdAt: now.toISOString(), files: entries }), 'utf8');\n const data = Buffer.concat([cipher.update(plain), cipher.final()]);\n const tag = cipher.getAuthTag();\n return JSON.stringify({\n magic: MIGRATE_MAGIC,\n kdf: { name: 'scrypt', salt: salt.toString('hex'), N: KDF_N },\n iv: iv.toString('hex'),\n tag: tag.toString('hex'),\n data: data.toString('base64'),\n }, null, 1) + '\\n';\n}\n\n/** Parse + decrypt a container. Throws (loudly) on a wrong passphrase or a\n * corrupted file — never returns partial data. */\nexport function decryptContainer(text: string, passphrase: string): { createdAt: string; files: MigrateEntry[] } {\n let outer: { magic?: string; kdf?: { salt?: string; N?: unknown }; iv?: string; tag?: string; data?: string };\n try {\n outer = JSON.parse(text);\n } catch {\n throw new Error('migrate: not a migration container (bad JSON)');\n }\n if (outer.magic !== MIGRATE_MAGIC) throw new Error('migrate: not a migration container (bad magic)');\n const n = assertKdfN(outer.kdf?.N);\n const salt = Buffer.from(String(outer.kdf?.salt ?? ''), 'hex');\n const iv = Buffer.from(String(outer.iv ?? ''), 'hex');\n const tag = Buffer.from(String(outer.tag ?? ''), 'hex');\n // HB-18: refuse an oversized payload before decoding it. base64 runs ~4/3 of\n // the ciphertext, so this cheap length check bounds the allocation below.\n const dataB64 = String(outer.data ?? '');\n if (dataB64.length > MIGRATE_MAX_BYTES * 2) {\n throw new Error(`migrate: container payload is too large (${dataB64.length} base64 chars)`);\n }\n const data = Buffer.from(dataB64, 'base64');\n const key = deriveKey(passphrase, salt, n);\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n let plain: Buffer;\n try {\n plain = Buffer.concat([decipher.update(data), decipher.final()]);\n } catch {\n throw new Error('migrate: wrong passphrase or corrupted container');\n }\n const inner = JSON.parse(plain.toString('utf8')) as { version: number; createdAt: string; files: MigrateEntry[] };\n if (inner.version !== MIGRATE_VERSION) throw new Error(`migrate: unsupported container version ${inner.version}`);\n if (!Array.isArray(inner.files)) throw new Error('migrate: container has no file list');\n assertMigrateBudget(inner.files);\n return { createdAt: inner.createdAt, files: inner.files };\n}\n\nexport interface MigrateImportResult {\n restored: string[];\n backedUp: string[];\n skipped: string[];\n /** H-21: files put back from their backups after a failed commit phase. */\n rolledBack?: string[];\n /** H-21: set when the commit phase failed and the import was rolled back. */\n error?: string;\n}\n\n/**\n * Restore entries into the local dataDir, re-encrypting DPAPI files with the\n * LOCAL machine key.\n *\n * H-21: this used to be a per-file \"back up, then overwrite\" loop with no\n * pre-flight and no rollback — a failure halfway through left a mixed memory\n * (a new `profile.json` next to a stale `profile_journal.jsonl`). Now it runs\n * in two phases: stage every entry next to its target (nothing visible changes\n * yet), then commit each one by rename. A commit failure rolls the\n * already-committed files back from their backups.\n *\n * HB-06 (2026-10-17): the phases are all-or-nothing at BOTH ends. Earlier a\n * staging failure only skipped that entry and the rest were still committed,\n * so one bad path was enough to leave a half-migrated memory. Now any skipped\n * entry aborts the whole import with nothing written; the reason is returned\n * in `error` alongside the offending names.\n */\nexport function applyMigrationEntries(guard: PathGuard, paths: WorkspacePaths, files: MigrateEntry[], now = Date.now()): MigrateImportResult {\n const restored: string[] = [];\n const backedUp: string[] = [];\n const skipped: string[] = [];\n const stamp = new Date(now).toISOString().replace(/[-:T]/g, '').slice(0, 14);\n const staged: Array<{ rel: string; abs: string; incoming: string }> = [];\n for (const f of files) {\n const rel = String(f.path ?? '');\n // String-level rejection BEFORE the path is resolved: the guard's realpath\n // check already refuses escapes, but an import must not depend on another\n // module staying correct. HB-18: and the name must be one an export can\n // produce - a container may not reach settings/, gate.json or vault.key.\n if (!rel || rel.includes('..') || path.isAbsolute(rel) || !isMigratablePath(rel)) {\n skipped.push(rel);\n continue;\n }\n const abs = path.join(paths.dataDir, rel);\n let absCanon: string;\n try {\n absCanon = guard.assert(abs);\n } catch {\n skipped.push(rel); // path refused by the guard — never write it\n continue;\n }\n const incoming = `${absCanon}.incoming-${stamp}`;\n try {\n fs.mkdirSync(path.dirname(absCanon), { recursive: true });\n if (f.encrypted) saveEncryptedText(guard, incoming, f.content);\n else fs.writeFileSync(incoming, f.content, 'utf8');\n staged.push({ rel, abs: absCanon, incoming });\n } catch {\n skipped.push(rel);\n try {\n fs.rmSync(incoming, { force: true });\n } catch {\n /* nothing staged */\n }\n }\n }\n // HB-06: staging is the point of no return. A single entry that could not be\n // staged used to be skipped while the rest were committed, which left a\n // half-migrated memory (a new profile.json next to a stale journal). Any skip\n // now aborts the import with nothing written; the reason travels in `error`.\n if (skipped.length > 0) {\n for (const s of staged) {\n try {\n fs.rmSync(s.incoming, { force: true });\n } catch {\n /* nothing staged */\n }\n }\n return {\n restored: [],\n backedUp: [],\n skipped,\n error: `staging failed for ${skipped.length} file(s): ${skipped.join(', ')}; nothing was imported`,\n };\n }\n const committed: Array<{ rel: string; abs: string; backup: string | null }> = [];\n try {\n for (const s of staged) {\n let backup: string | null = null;\n if (fs.existsSync(s.abs)) {\n backup = `${s.abs}.bak-migrate-${stamp}`;\n fs.copyFileSync(s.abs, backup);\n backedUp.push(s.rel);\n }\n fs.renameSync(s.incoming, s.abs);\n committed.push({ rel: s.rel, abs: s.abs, backup });\n restored.push(s.rel);\n }\n return { restored, backedUp, skipped };\n } catch (e) {\n // Roll back so the dataDir never holds a half-migrated mix; staged files\n // that were never committed are simply dropped.\n const rolledBack: string[] = [];\n for (const c of committed.reverse()) {\n try {\n if (c.backup) fs.renameSync(c.backup, c.abs);\n else fs.rmSync(c.abs, { force: true });\n rolledBack.push(c.rel);\n } catch {\n /* best effort — the backup file itself is still on disk */\n }\n }\n for (const s of staged) {\n if (committed.some((c) => c.abs === s.abs)) continue;\n try {\n fs.rmSync(s.incoming, { force: true });\n } catch {\n /* already gone */\n }\n }\n return { restored: [], backedUp, skipped, rolledBack, error: String(e) };\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQA,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AAI/B,IAAM,QAAQ;AAGd,IAAM,YAAY,KAAK;AACvB,IAAM,YAAY,KAAK;AAGvB,IAAM,gBAAgB,MAAM,OAAO;AACnC,IAAM,UAAU;AAKT,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAMA,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAEnB,SAAS,iBAAiB,KAAsB;AACrD,MAAI,cAAc,SAAS,GAAG,EAAG,QAAO;AACxC,MAAI,mBAAmB,KAAK,GAAG,EAAG,QAAO;AACzC,MAAI,yBAAyB,KAAK,GAAG,EAAG,QAAO;AAC/C,MAAI,kBAAkB,KAAK,GAAG,EAAG,QAAO;AACxC,SAAO;AACT;AAIO,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB,KAAK,OAAO;AAa7C,SAAS,mBAAmB,OAAkB,OAAiC;AAC7E,QAAM,MAAM,KAAK,KAAK,MAAM,SAAS,QAAQ;AAC7C,MAAI;AACF,WAAO,GAAG,YAAY,MAAM,OAAO,GAAG,CAAC,EACpC,OAAO,CAAC,MAAM,EAAE,SAAS,OAAO,CAAC,EACjC,IAAI,CAAC,MAAM,KAAK,KAAK,UAAU,CAAC,EAAE,QAAQ,OAAO,GAAG,CAAC;AAAA,EAC1D,QAAQ;AACN,WAAO,C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AAW,KAAK,UAAU,QAAQ,GAAG;AACnC,UAAI;AACF,YAAI,EAAE,OAAQ,IAAG,WAAW,EAAE,QAAQ,EAAE,GAAG;AAAA,YACtC,IAAG,OAAO,EAAE,KAAK,EAAE,OAAO,KAAK,CAAC;AACrC,mBAAW,KAAK,EAAE,GAAG;AAAA,MACvB,QAAQ;AAAA,MAER;AAAA,IACF;AACA,eAAW,KAAK,QAAQ;AACtB,UAAI,UAAU,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAG;AAC5C,UAAI;AACF,WAAG,OAAO,EAAE,UAAU,EAAE,OAAO,KAAK,CAAC;AAAA,MACvC,QAAQ;AAAA,MAER;AAAA,IACF;AACA,WAAO,EAAE,UAAU,CAAC,GAAG,UAAU,SAAS,YAAY,OAAO,OAAO,CAAC,EAAE;AAAA,EACzE;AACF;","names":[]}
|
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ARCHIVE_PREFIX,
|
|
3
|
+
SNAPSHOT_ARCHIVE_NAME_RE,
|
|
4
|
+
SNAPSHOT_ARCHIVE_PREFIX,
|
|
5
|
+
journalFilePath,
|
|
6
|
+
listSnapshots,
|
|
7
|
+
replayJournal,
|
|
8
|
+
snapshotFilePath
|
|
9
|
+
} from "./chunk-ERRPMYKB.js";
|
|
10
|
+
import {
|
|
11
|
+
saveJson
|
|
12
|
+
} from "./chunk-GOLMRQRW.js";
|
|
13
|
+
import {
|
|
14
|
+
atomicWriteFileSync
|
|
15
|
+
} from "./chunk-66IUDHCY.js";
|
|
16
|
+
|
|
17
|
+
// src/profile/snapshot.ts
|
|
18
|
+
import fs3 from "fs";
|
|
19
|
+
import path3 from "path";
|
|
20
|
+
|
|
21
|
+
// src/core/audit-log.ts
|
|
22
|
+
import fs from "fs";
|
|
23
|
+
import path from "path";
|
|
24
|
+
function appendAuditLine(file, event) {
|
|
25
|
+
try {
|
|
26
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
27
|
+
const line = JSON.stringify({ ts: event.ts ?? (/* @__PURE__ */ new Date()).toISOString(), ...event });
|
|
28
|
+
fs.appendFileSync(file, line + "\n", "utf8");
|
|
29
|
+
return true;
|
|
30
|
+
} catch (e) {
|
|
31
|
+
process.stderr.write(`[heartbeat] audit append failed: ${file}: ${String(e)}
|
|
32
|
+
`);
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function readAuditLines(file) {
|
|
37
|
+
if (!fs.existsSync(file)) return [];
|
|
38
|
+
const out = [];
|
|
39
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
40
|
+
for (const line of raw.split("\n")) {
|
|
41
|
+
const trimmed = line.trim();
|
|
42
|
+
if (!trimmed) continue;
|
|
43
|
+
try {
|
|
44
|
+
out.push(JSON.parse(trimmed));
|
|
45
|
+
} catch {
|
|
46
|
+
out.push({ ts: "", corrupt: true, raw: trimmed.slice(0, 200) });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
function pruneAuditFile(file, maxAgeMs, now = Date.now()) {
|
|
52
|
+
if (!fs.existsSync(file)) return 0;
|
|
53
|
+
const lines = readAuditLines(file);
|
|
54
|
+
const kept = lines.filter((e) => {
|
|
55
|
+
const ev = e;
|
|
56
|
+
const ts = Date.parse(ev.ts ?? "");
|
|
57
|
+
if (!Number.isFinite(ts)) return true;
|
|
58
|
+
return now - ts <= maxAgeMs;
|
|
59
|
+
});
|
|
60
|
+
const removed = lines.length - kept.length;
|
|
61
|
+
if (removed === 0) return 0;
|
|
62
|
+
const body = kept.map((e) => JSON.stringify(e)).join("\n");
|
|
63
|
+
atomicWriteFileSync(file, body ? body + "\n" : "");
|
|
64
|
+
return removed;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/config/load.ts
|
|
68
|
+
import fs2 from "fs";
|
|
69
|
+
import path2 from "path";
|
|
70
|
+
|
|
71
|
+
// src/config/schema.ts
|
|
72
|
+
var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
73
|
+
function isPlainObject(v) {
|
|
74
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
75
|
+
}
|
|
76
|
+
function fail(msg) {
|
|
77
|
+
throw new Error(`policy: ${msg}`);
|
|
78
|
+
}
|
|
79
|
+
function assertPolicy(input) {
|
|
80
|
+
if (!isPlainObject(input)) fail("root must be an object");
|
|
81
|
+
const p = input;
|
|
82
|
+
const hb = p.heartbeat;
|
|
83
|
+
if (!isPlainObject(hb)) fail("heartbeat missing");
|
|
84
|
+
if (typeof hb.intervalMin !== "number" || hb.intervalMin < 1 || hb.intervalMin > 1440) {
|
|
85
|
+
fail("heartbeat.intervalMin must be a number in [1, 1440]");
|
|
86
|
+
}
|
|
87
|
+
if (typeof hb.idleMode !== "boolean") fail("heartbeat.idleMode must be boolean");
|
|
88
|
+
if (typeof hb.archiveRotatedHome !== "boolean") fail("heartbeat.archiveRotatedHome must be boolean");
|
|
89
|
+
if (hb.intervalJitterPct !== void 0 && (typeof hb.intervalJitterPct !== "number" || hb.intervalJitterPct < 0 || hb.intervalJitterPct > 50)) {
|
|
90
|
+
fail("heartbeat.intervalJitterPct must be a number in [0, 50]");
|
|
91
|
+
}
|
|
92
|
+
const g = p.gate;
|
|
93
|
+
if (!isPlainObject(g)) fail("gate missing");
|
|
94
|
+
if (typeof g.maxDailySend !== "number" || g.maxDailySend < 0) fail("gate.maxDailySend must be >= 0");
|
|
95
|
+
if (typeof g.cooldownMinutes !== "number" || g.cooldownMinutes < 0) fail("gate.cooldownMinutes must be >= 0");
|
|
96
|
+
const qh = g.quietHours;
|
|
97
|
+
if (!isPlainObject(qh)) fail("gate.quietHours missing");
|
|
98
|
+
if (typeof qh.start !== "string" || !HHMM.test(qh.start) || typeof qh.end !== "string" || !HHMM.test(qh.end)) {
|
|
99
|
+
fail('gate.quietHours must be {start:"HH:MM", end:"HH:MM"}');
|
|
100
|
+
}
|
|
101
|
+
const b = p.browse;
|
|
102
|
+
if (!isPlainObject(b)) fail("browse missing");
|
|
103
|
+
if (!Array.isArray(b.windows) || b.windows.length === 0) fail("browse.windows must be a non-empty array");
|
|
104
|
+
for (const w of b.windows) {
|
|
105
|
+
if (!isPlainObject(w)) fail("browse.windows entries must be objects");
|
|
106
|
+
if (typeof w.start !== "string" || !HHMM.test(w.start) || typeof w.end !== "string" || !HHMM.test(w.end)) {
|
|
107
|
+
fail('browse.windows entries must be {start:"HH:MM", end:"HH:MM"}');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (typeof b.minIntervalHours !== "number" || b.minIntervalHours <= 0) fail("browse.minIntervalHours must be > 0");
|
|
111
|
+
if (typeof b.maxSeedsPerVisit !== "number" || b.maxSeedsPerVisit < 1) fail("browse.maxSeedsPerVisit must be >= 1");
|
|
112
|
+
const s = p.seeds;
|
|
113
|
+
if (!isPlainObject(s)) fail("seeds missing");
|
|
114
|
+
if (typeof s.maxActive !== "number" || s.maxActive < 1) fail("seeds.maxActive must be >= 1");
|
|
115
|
+
if (!isPlainObject(s.ttlDays)) fail("seeds.ttlDays missing");
|
|
116
|
+
for (const k of ["news", "fandom", "scene", "promise"]) {
|
|
117
|
+
if (typeof s.ttlDays[k] !== "number") fail(`seeds.ttlDays.${k} missing`);
|
|
118
|
+
}
|
|
119
|
+
if (typeof s.coldBenchDays !== "number") fail("seeds.coldBenchDays missing");
|
|
120
|
+
if (typeof s.archiveCap !== "number" || s.archiveCap < 1) fail("seeds.archiveCap must be >= 1");
|
|
121
|
+
if (typeof s.retireAfterUsed !== "number" || s.retireAfterUsed < 1) fail("seeds.retireAfterUsed must be >= 1");
|
|
122
|
+
if (!isPlainObject(s.scoreWeights)) fail("seeds.scoreWeights missing");
|
|
123
|
+
const pr = p.profile;
|
|
124
|
+
if (!isPlainObject(pr)) fail("profile missing");
|
|
125
|
+
const c = pr.consolidation;
|
|
126
|
+
if (!isPlainObject(c)) fail("profile.consolidation missing");
|
|
127
|
+
if (typeof c.minIntervalHours !== "number" || typeof c.inboxBacklog !== "number") fail("profile.consolidation fields missing");
|
|
128
|
+
if (typeof pr.partitionCap !== "number" || pr.partitionCap < 1) fail("profile.partitionCap must be >= 1");
|
|
129
|
+
if (typeof pr.maxOpsPerRun !== "number" || pr.maxOpsPerRun < 1) fail("profile.maxOpsPerRun must be >= 1");
|
|
130
|
+
const cc = pr.confidenceCap;
|
|
131
|
+
if (!isPlainObject(cc)) fail("profile.confidenceCap missing");
|
|
132
|
+
if (typeof cc.chat !== "number" || typeof cc.screen !== "number" || typeof cc.browse !== "number") {
|
|
133
|
+
fail("profile.confidenceCap fields missing");
|
|
134
|
+
}
|
|
135
|
+
if (typeof pr.volatileDays !== "number" || pr.volatileDays < 1) fail("profile.volatileDays must be >= 1");
|
|
136
|
+
if (typeof pr.stableLowActivityDays !== "number" || pr.stableLowActivityDays < 1) fail("profile.stableLowActivityDays must be >= 1");
|
|
137
|
+
if (typeof pr.psyEnabled !== "boolean") fail("profile.psyEnabled must be boolean");
|
|
138
|
+
const ob = p.observe;
|
|
139
|
+
if (!isPlainObject(ob)) fail("observe missing");
|
|
140
|
+
if (typeof ob.maxChars !== "number" || ob.maxChars < 20 || ob.maxChars > 2e3) fail("observe.maxChars must be in [20, 2000]");
|
|
141
|
+
if (typeof ob.perBeat !== "number" || ob.perBeat < 1 || ob.perBeat > 100) fail("observe.perBeat must be in [1, 100]");
|
|
142
|
+
if (!isPlainObject(p.weekly)) fail("weekly missing");
|
|
143
|
+
if (typeof p.weekly.enabled !== "boolean") fail("weekly.enabled must be boolean");
|
|
144
|
+
if (typeof p.weekly.keepReports !== "number" || p.weekly.keepReports < 1 || p.weekly.keepReports > 52) {
|
|
145
|
+
fail("weekly.keepReports must be a number in [1, 52]");
|
|
146
|
+
}
|
|
147
|
+
const r = p.retention;
|
|
148
|
+
if (!isPlainObject(r)) fail("retention missing");
|
|
149
|
+
if (typeof r.envPulseHours !== "number" || typeof r.decisionLogDays !== "number") fail("retention fields missing");
|
|
150
|
+
if (p.sources !== void 0) {
|
|
151
|
+
if (!isPlainObject(p.sources)) fail("sources must be an object when present");
|
|
152
|
+
const bili = p.sources.bilibili;
|
|
153
|
+
if (bili !== void 0) {
|
|
154
|
+
if (!isPlainObject(bili)) fail("sources.bilibili must be an object when present");
|
|
155
|
+
if (bili.enabled !== void 0 && typeof bili.enabled !== "boolean") {
|
|
156
|
+
fail("sources.bilibili.enabled must be boolean when present");
|
|
157
|
+
}
|
|
158
|
+
if (bili.cookieFile !== void 0 && typeof bili.cookieFile !== "string") {
|
|
159
|
+
fail("sources.bilibili.cookieFile must be a string when present");
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function deepMerge(base, override) {
|
|
165
|
+
if (!isPlainObject(base) || !isPlainObject(override)) {
|
|
166
|
+
return override === void 0 ? base : override;
|
|
167
|
+
}
|
|
168
|
+
const out = { ...base };
|
|
169
|
+
for (const [k, v] of Object.entries(override)) {
|
|
170
|
+
out[k] = v === void 0 ? base[k] : deepMerge(base[k], v);
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/config/load.ts
|
|
176
|
+
var USER_POLICY_FILE = "policy.json";
|
|
177
|
+
function loadPolicy(guard, configDir, settingsDir) {
|
|
178
|
+
const factoryPath = path2.join(configDir, "policy.json");
|
|
179
|
+
let factoryRaw;
|
|
180
|
+
try {
|
|
181
|
+
factoryRaw = JSON.parse(fs2.readFileSync(factoryPath, "utf8"));
|
|
182
|
+
} catch (e) {
|
|
183
|
+
throw new Error(`factory policy unreadable at ${factoryPath}: ${String(e)}`);
|
|
184
|
+
}
|
|
185
|
+
assertPolicy(factoryRaw);
|
|
186
|
+
const userPath = guard.assert(path2.join(settingsDir, USER_POLICY_FILE));
|
|
187
|
+
let merged = factoryRaw;
|
|
188
|
+
if (fs2.existsSync(userPath)) {
|
|
189
|
+
try {
|
|
190
|
+
const userRaw = JSON.parse(fs2.readFileSync(userPath, "utf8"));
|
|
191
|
+
merged = deepMerge(factoryRaw, userRaw);
|
|
192
|
+
} catch (e) {
|
|
193
|
+
throw new Error(`user policy layer unparseable at ${userPath}: ${String(e)}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
assertPolicy(merged);
|
|
197
|
+
return merged;
|
|
198
|
+
}
|
|
199
|
+
function updateUserPolicy(guard, settingsDir, patch) {
|
|
200
|
+
const userPath = guard.assert(path2.join(settingsDir, USER_POLICY_FILE));
|
|
201
|
+
let user = {};
|
|
202
|
+
try {
|
|
203
|
+
user = JSON.parse(fs2.readFileSync(userPath, "utf8"));
|
|
204
|
+
if (!user || typeof user !== "object" || Array.isArray(user)) user = {};
|
|
205
|
+
} catch {
|
|
206
|
+
user = {};
|
|
207
|
+
}
|
|
208
|
+
const merged = deepMerge(user, patch);
|
|
209
|
+
fs2.mkdirSync(path2.dirname(userPath), { recursive: true });
|
|
210
|
+
atomicWriteFileSync(userPath, JSON.stringify(merged, null, 2) + "\n");
|
|
211
|
+
return merged;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/core/time-window.ts
|
|
215
|
+
var HH_MM = /^(\d{1,2}):(\d{2})$/;
|
|
216
|
+
function parseHhMm(text) {
|
|
217
|
+
const m = HH_MM.exec(String(text).trim());
|
|
218
|
+
if (!m) return null;
|
|
219
|
+
const h = Number(m[1]);
|
|
220
|
+
const min = Number(m[2]);
|
|
221
|
+
if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;
|
|
222
|
+
return h * 60 + min;
|
|
223
|
+
}
|
|
224
|
+
function minutesOfDay(now) {
|
|
225
|
+
return now.getHours() * 60 + now.getMinutes();
|
|
226
|
+
}
|
|
227
|
+
function inHhMmWindow(start, end, mins) {
|
|
228
|
+
const s = parseHhMm(start);
|
|
229
|
+
const e = parseHhMm(end);
|
|
230
|
+
if (s === null || e === null) return false;
|
|
231
|
+
if (s === e) return false;
|
|
232
|
+
return s > e ? mins >= s || mins < e : mins >= s && mins < e;
|
|
233
|
+
}
|
|
234
|
+
function localDayKey(d = /* @__PURE__ */ new Date()) {
|
|
235
|
+
const y = d.getFullYear();
|
|
236
|
+
const m = String(d.getMonth() + 1).padStart(2, "0");
|
|
237
|
+
const day = String(d.getDate()).padStart(2, "0");
|
|
238
|
+
return `${y}-${m}-${day}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// src/profile/snapshot.ts
|
|
242
|
+
var SNAPSHOT_THRESHOLD = 5e3;
|
|
243
|
+
var SNAPSHOT_RETENTION_DAYS = 30;
|
|
244
|
+
var RETENTION_MAX_DAYS = 3650;
|
|
245
|
+
var DAY_MS = 864e5;
|
|
246
|
+
function resolveRetentionDays(guard, dataDir) {
|
|
247
|
+
const file = path3.join(dataDir, "settings", USER_POLICY_FILE);
|
|
248
|
+
let raw;
|
|
249
|
+
try {
|
|
250
|
+
raw = JSON.parse(fs3.readFileSync(guard.assert(file), "utf8"));
|
|
251
|
+
} catch {
|
|
252
|
+
return SNAPSHOT_RETENTION_DAYS;
|
|
253
|
+
}
|
|
254
|
+
const v = raw?.profile?.retentionDays;
|
|
255
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > RETENTION_MAX_DAYS) {
|
|
256
|
+
return SNAPSHOT_RETENTION_DAYS;
|
|
257
|
+
}
|
|
258
|
+
return v;
|
|
259
|
+
}
|
|
260
|
+
function snapshotDue(guard, dataDir, threshold = SNAPSHOT_THRESHOLD) {
|
|
261
|
+
let lines = 0;
|
|
262
|
+
try {
|
|
263
|
+
const raw = fs3.readFileSync(guard.assert(journalFilePath(dataDir)), "utf8");
|
|
264
|
+
lines = raw.split("\n").filter((l) => l.trim()).length;
|
|
265
|
+
} catch {
|
|
266
|
+
return { needed: false, lines: 0 };
|
|
267
|
+
}
|
|
268
|
+
return { needed: lines >= threshold, lines };
|
|
269
|
+
}
|
|
270
|
+
function snapshotProfile(guard, dataDir, now = Date.now()) {
|
|
271
|
+
const journalFile = journalFilePath(dataDir);
|
|
272
|
+
let raw = "";
|
|
273
|
+
try {
|
|
274
|
+
raw = fs3.readFileSync(guard.assert(journalFile), "utf8");
|
|
275
|
+
} catch {
|
|
276
|
+
return { ok: false, reason: "no journal" };
|
|
277
|
+
}
|
|
278
|
+
const liveRecords = raw.split("\n").filter((l) => l.trim());
|
|
279
|
+
if (liveRecords.length === 0) return { ok: false, reason: "journal empty, nothing to fold" };
|
|
280
|
+
const replayed = replayJournal(guard, dataDir);
|
|
281
|
+
const lastTs = lastRecordTs(raw) ?? new Date(now).toISOString();
|
|
282
|
+
const snapshot = {
|
|
283
|
+
version: 1,
|
|
284
|
+
baselineTs: lastTs,
|
|
285
|
+
recordsFolded: replayed.records,
|
|
286
|
+
doc: replayed.doc
|
|
287
|
+
};
|
|
288
|
+
saveJson(guard, snapshotFilePath(dataDir), snapshot);
|
|
289
|
+
const parsedTs = Date.parse(lastTs);
|
|
290
|
+
const baselineMs = Number.isFinite(parsedTs) ? parsedTs : now;
|
|
291
|
+
const archiveName = `${SNAPSHOT_ARCHIVE_PREFIX}${baselineMs}.json`;
|
|
292
|
+
saveJson(guard, path3.join(dataDir, archiveName), snapshot);
|
|
293
|
+
try {
|
|
294
|
+
const keepDay = localDayKey(new Date(baselineMs));
|
|
295
|
+
for (const f of fs3.readdirSync(guard.assert(dataDir))) {
|
|
296
|
+
if (f === archiveName || !SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;
|
|
297
|
+
const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -".json".length));
|
|
298
|
+
if (Number.isFinite(ms) && localDayKey(new Date(ms)) === keepDay) {
|
|
299
|
+
fs3.rmSync(guard.assert(path3.join(dataDir, f)), { force: true });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
}
|
|
304
|
+
const stamp = new Date(now).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
305
|
+
const archiveFile = `${ARCHIVE_PREFIX}${stamp}.jsonl`;
|
|
306
|
+
fs3.writeFileSync(path3.join(dataDir, archiveFile), liveRecords.join("\n") + "\n", "utf8");
|
|
307
|
+
fs3.writeFileSync(guard.assert(journalFile), "", "utf8");
|
|
308
|
+
return {
|
|
309
|
+
ok: true,
|
|
310
|
+
baselineTs: lastTs,
|
|
311
|
+
folded: replayed.records,
|
|
312
|
+
archiveFile,
|
|
313
|
+
liveRemaining: 0,
|
|
314
|
+
snapshotArchive: archiveName
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
function lastRecordTs(raw) {
|
|
318
|
+
const lines = raw.split("\n").filter((l) => l.trim());
|
|
319
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
320
|
+
try {
|
|
321
|
+
return String(JSON.parse(lines[i]).ts ?? "") || null;
|
|
322
|
+
} catch {
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
function pruneSnapshots(guard, dataDir, retentionDays, now = Date.now()) {
|
|
328
|
+
const cutoff = now - Math.max(0, retentionDays) * DAY_MS;
|
|
329
|
+
const removed = [];
|
|
330
|
+
try {
|
|
331
|
+
for (const f of fs3.readdirSync(guard.assert(dataDir))) {
|
|
332
|
+
if (!SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;
|
|
333
|
+
const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -".json".length));
|
|
334
|
+
if (!Number.isFinite(ms) || ms >= cutoff) continue;
|
|
335
|
+
try {
|
|
336
|
+
fs3.rmSync(guard.assert(path3.join(dataDir, f)), { force: true });
|
|
337
|
+
removed.push(f);
|
|
338
|
+
} catch {
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
} catch {
|
|
342
|
+
}
|
|
343
|
+
return removed;
|
|
344
|
+
}
|
|
345
|
+
function snapshotIfDue(guard, dataDir, auditFile, why, now = Date.now(), opts = {}) {
|
|
346
|
+
try {
|
|
347
|
+
const { needed, lines } = snapshotDue(guard, dataDir);
|
|
348
|
+
let daily = false;
|
|
349
|
+
if (!needed && lines > 0) {
|
|
350
|
+
const refs = listSnapshots(guard, dataDir);
|
|
351
|
+
const latest = refs.length > 0 ? refs[refs.length - 1].baselineTs : Number.NaN;
|
|
352
|
+
daily = !Number.isFinite(latest) || localDayKey(new Date(latest)) !== localDayKey(new Date(now));
|
|
353
|
+
}
|
|
354
|
+
if (!needed && !daily) return;
|
|
355
|
+
const report = snapshotProfile(guard, dataDir, now);
|
|
356
|
+
appendAuditLine(auditFile, { event: "profile_snapshot", why, lines, daily: !needed, ...report });
|
|
357
|
+
if (report.ok) {
|
|
358
|
+
const pruned = pruneSnapshots(guard, dataDir, opts.retentionDays ?? resolveRetentionDays(guard, dataDir), now);
|
|
359
|
+
if (pruned.length > 0) {
|
|
360
|
+
appendAuditLine(auditFile, { event: "profile_snapshot_pruned", why, pruned: pruned.length, files: pruned.slice(0, 20) });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
} catch (e) {
|
|
364
|
+
try {
|
|
365
|
+
appendAuditLine(auditFile, { event: "profile_snapshot_failed", why, error: String(e).slice(0, 160) });
|
|
366
|
+
} catch {
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export {
|
|
372
|
+
appendAuditLine,
|
|
373
|
+
readAuditLines,
|
|
374
|
+
pruneAuditFile,
|
|
375
|
+
deepMerge,
|
|
376
|
+
loadPolicy,
|
|
377
|
+
updateUserPolicy,
|
|
378
|
+
minutesOfDay,
|
|
379
|
+
inHhMmWindow,
|
|
380
|
+
localDayKey,
|
|
381
|
+
SNAPSHOT_THRESHOLD,
|
|
382
|
+
SNAPSHOT_RETENTION_DAYS,
|
|
383
|
+
resolveRetentionDays,
|
|
384
|
+
snapshotDue,
|
|
385
|
+
snapshotProfile,
|
|
386
|
+
pruneSnapshots,
|
|
387
|
+
snapshotIfDue
|
|
388
|
+
};
|
|
389
|
+
//# sourceMappingURL=chunk-CRRN6UD3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/profile/snapshot.ts","../src/core/audit-log.ts","../src/config/load.ts","../src/config/schema.ts","../src/core/time-window.ts"],"sourcesContent":["// Journal snapshot + shard rotation (v1.8.0, design doc §14 ③). The journal\n// grows without bound; past the threshold the maintenance phase folds it into\n// a DPAPI snapshot and moves the folded records into a timestamped archive\n// shard, so replay cost stays bounded while the raw history survives on disk.\n//\n// v2.4.0 (dev plan §二3): each fold additionally keeps a DATED archive copy\n// `profile_snapshot.<baselineTs>.json` (epoch-ms name), so every fold is a\n// named restore point for `profile restore`. Same local day keeps only the\n// last copy; pruneSnapshots drops archives past policy.profile.retentionDays\n// (default 30). The canonical profile_snapshot.json keeps its name and its\n// role as replayJournal's basepoint — replay semantics are untouched.\n//\n// Safety: replayJournal (store.ts) is the single authority reader and already\n// understands snapshot → archives → live journal, so verify/rebuild keep\n// working across rotations with no special-casing.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { USER_POLICY_FILE } from '../config/load.js';\nimport { localDayKey } from '../core/time-window.js';\nimport { saveJson } from '../vault/vault.js';\nimport {\n journalFilePath,\n replayJournal,\n snapshotFilePath,\n SNAPSHOT_ARCHIVE_PREFIX,\n SNAPSHOT_ARCHIVE_NAME_RE,\n ARCHIVE_PREFIX,\n listSnapshots,\n type ProfileSnapshot,\n} from './store.js';\n\n// Vault layers (burn-list / migrate) match these archive files by name — the\n// constants live in store.ts next to the snapshot format, re-exported here as\n// the public face for them (dev plan: \"导出归档文件名正则/前缀常量\").\nexport { SNAPSHOT_ARCHIVE_PREFIX, SNAPSHOT_ARCHIVE_NAME_RE };\n\n/** Fold the journal once the live file reaches this many records. */\nexport const SNAPSHOT_THRESHOLD = 5000;\n\n/** Snapshot archive retention (dev plan §二3): archives older than this many\n * days are pruned. Default — used when data/settings/policy.json does not\n * set profile.retentionDays (see resolveRetentionDays below). */\nexport const SNAPSHOT_RETENTION_DAYS = 30;\n\n/** Defensible upper bound for a hand-edited retentionDays: anything above is\n * treated as a typo and falls back to the default instead of disabling\n * pruning for years. */\nconst RETENTION_MAX_DAYS = 3650;\n\nconst DAY_MS = 86_400_000;\n\n/** profile.retentionDays from the USER policy layer (data/settings/policy.json)\n * — the Policy type deliberately does not carry it, so this reads the layer\n * directly instead of forcing a key through the schema. Tolerant by design:\n * a missing/unparseable/out-of-range value falls back to the default, because\n * pruning rides the maintenance beat and must never break it. */\nexport function resolveRetentionDays(guard: PathGuard, dataDir: string): number {\n const file = path.join(dataDir, 'settings', USER_POLICY_FILE);\n let raw: unknown;\n try {\n raw = JSON.parse(fs.readFileSync(guard.assert(file), 'utf8'));\n } catch {\n return SNAPSHOT_RETENTION_DAYS;\n }\n const v = (raw as { profile?: { retentionDays?: unknown } } | null)?.profile?.retentionDays;\n if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0 || v > RETENTION_MAX_DAYS) {\n return SNAPSHOT_RETENTION_DAYS;\n }\n return v;\n}\n\nexport interface SnapshotReport {\n ok: boolean;\n reason?: string;\n baselineTs?: string;\n folded?: number;\n archiveFile?: string;\n liveRemaining?: number;\n /** Dated archive copy written for this fold (restore point). */\n snapshotArchive?: string;\n}\n\n/** How far the live journal is from the snapshot threshold. */\nexport function snapshotDue(guard: PathGuard, dataDir: string, threshold = SNAPSHOT_THRESHOLD): { needed: boolean; lines: number } {\n let lines = 0;\n try {\n const raw = fs.readFileSync(guard.assert(journalFilePath(dataDir)), 'utf8');\n lines = raw.split('\\n').filter((l) => l.trim()).length;\n } catch {\n return { needed: false, lines: 0 };\n }\n return { needed: lines >= threshold, lines };\n}\n\n/** Fold the live journal into a snapshot and shard the folded records into an\n * archive file. Also writes the dated snapshot archive (the restore point)\n * and collapses same-day archives to this one. Returns a report; never throws\n * on missing data (nothing to fold is a no-op, reported as such). */\nexport function snapshotProfile(guard: PathGuard, dataDir: string, now = Date.now()): SnapshotReport {\n const journalFile = journalFilePath(dataDir);\n let raw = '';\n try {\n raw = fs.readFileSync(guard.assert(journalFile), 'utf8');\n } catch {\n return { ok: false, reason: 'no journal' };\n }\n const liveRecords = raw.split('\\n').filter((l) => l.trim());\n if (liveRecords.length === 0) return { ok: false, reason: 'journal empty, nothing to fold' };\n\n // Replay the CURRENT live journal only — prior snapshots + shards are\n // already inside the accumulated view; the live tail is what we fold.\n const replayed = replayJournal(guard, dataDir);\n const lastTs = lastRecordTs(raw) ?? new Date(now).toISOString();\n const snapshot: ProfileSnapshot = {\n version: 1,\n baselineTs: lastTs,\n recordsFolded: replayed.records,\n doc: replayed.doc,\n };\n saveJson(guard, snapshotFilePath(dataDir), snapshot);\n\n // Dated archive copy (v2.4.0): the restore point this fold creates. Named\n // after the baseline in epoch ms so listSnapshots/restore can find it\n // without decrypting; written through the same encrypted-container path as\n // the canonical file.\n const parsedTs = Date.parse(lastTs);\n const baselineMs = Number.isFinite(parsedTs) ? parsedTs : now;\n const archiveName = `${SNAPSHOT_ARCHIVE_PREFIX}${baselineMs}.json`;\n saveJson(guard, path.join(dataDir, archiveName), snapshot);\n\n // Same local day keeps exactly ONE archive: drop the day's earlier copies\n // (never overwrite in place — the survivor's name carries its own baseline).\n // A failure here only leaves an extra restore point behind; cleanup settles\n // it later, so it must not fail the fold.\n try {\n const keepDay = localDayKey(new Date(baselineMs));\n for (const f of fs.readdirSync(guard.assert(dataDir))) {\n if (f === archiveName || !SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;\n const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -'.json'.length));\n if (Number.isFinite(ms) && localDayKey(new Date(ms)) === keepDay) {\n fs.rmSync(guard.assert(path.join(dataDir, f)), { force: true });\n }\n }\n } catch { /* listing failed: extra archives survive until pruned */ }\n\n // Shard: move the folded records out of the live journal. The shard is a\n // closed file (never appended again); the live journal restarts empty. A\n // torn shard write is tolerated by replay (corrupt lines are skipped).\n // stamp used to slice(0,15), keeping the ISO milliseconds' dot — shard names\n // came out `archive-<14digits>..jsonl` and migrate's import whitelist\n // (/^profile_journal\\.archive-\\d+\\.jsonl$/) could never match them. 14\n // digits = seconds precision, same convention as the migrate backup stamps.\n const stamp = new Date(now).toISOString().replace(/[-:T]/g, '').slice(0, 14);\n const archiveFile = `${ARCHIVE_PREFIX}${stamp}.jsonl`;\n fs.writeFileSync(path.join(dataDir, archiveFile), liveRecords.join('\\n') + '\\n', 'utf8');\n fs.writeFileSync(guard.assert(journalFile), '', 'utf8');\n\n return {\n ok: true,\n baselineTs: lastTs,\n folded: replayed.records,\n archiveFile,\n liveRemaining: 0,\n snapshotArchive: archiveName,\n };\n}\n\nfunction lastRecordTs(raw: string): string | null {\n const lines = raw.split('\\n').filter((l) => l.trim());\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n return String((JSON.parse(lines[i]!) as { ts?: string }).ts ?? '') || null;\n } catch { /* skip a torn tail line */ }\n }\n return null;\n}\n\n/** Delete snapshot archives whose baseline is older than `retentionDays` days\n * (v2.4.0, dev plan §二3). The canonical snapshot is NEVER touched — it is\n * the basepoint replayJournal replays from regardless of age. Returns the\n * removed file names (dataDir-relative). */\nexport function pruneSnapshots(guard: PathGuard, dataDir: string, retentionDays: number, now = Date.now()): string[] {\n const cutoff = now - Math.max(0, retentionDays) * DAY_MS;\n const removed: string[] = [];\n try {\n for (const f of fs.readdirSync(guard.assert(dataDir))) {\n if (!SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;\n const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -'.json'.length));\n if (!Number.isFinite(ms) || ms >= cutoff) continue;\n try {\n fs.rmSync(guard.assert(path.join(dataDir, f)), { force: true });\n removed.push(f);\n } catch { /* already gone */ }\n }\n } catch { /* no dataDir listing: nothing to prune */ }\n return removed;\n}\n\n/** Maintenance hook: fold when over the threshold, or when the newest snapshot\n * is not from today (v2.4.0「每日至少一份」— a quiet day still leaves a daily\n * restore point). An empty live journal never fires: without journal records\n * the accumulated state cannot have changed, and folding would only audit\n * \"nothing to fold\" every beat. Audits + never throws.\n * After a successful fold, archives past `opts.retentionDays` are pruned\n * (folds only add archive files, pruning only removes — the two never race,\n * dev plan §七). */\nexport function snapshotIfDue(\n guard: PathGuard,\n dataDir: string,\n auditFile: string,\n why: string,\n now = Date.now(),\n opts: { retentionDays?: number } = {},\n): void {\n try {\n const { needed, lines } = snapshotDue(guard, dataDir);\n let daily = false;\n if (!needed && lines > 0) {\n const refs = listSnapshots(guard, dataDir);\n const latest = refs.length > 0 ? refs[refs.length - 1]!.baselineTs : Number.NaN;\n daily = !Number.isFinite(latest) || localDayKey(new Date(latest)) !== localDayKey(new Date(now));\n }\n if (!needed && !daily) return;\n const report = snapshotProfile(guard, dataDir, now);\n appendAuditLine(auditFile, { event: 'profile_snapshot', why, lines, daily: !needed, ...report });\n if (report.ok) {\n const pruned = pruneSnapshots(guard, dataDir, opts.retentionDays ?? resolveRetentionDays(guard, dataDir), now);\n if (pruned.length > 0) {\n appendAuditLine(auditFile, { event: 'profile_snapshot_pruned', why, pruned: pruned.length, files: pruned.slice(0, 20) });\n }\n }\n } catch (e) {\n try {\n appendAuditLine(auditFile, { event: 'profile_snapshot_failed', why, error: String(e).slice(0, 160) });\n } catch { /* audit must never break the beat */ }\n }\n}\n","// Append-only JSONL audit log with age-based retention pruning.\n// Audit files are plaintext by charter (transparency), and must never contain\n// sensitive raw observations (window titles, conversation text).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFileSync } from './atomic-fs.js';\n\nexport interface AuditEvent {\n ts: string;\n [key: string]: unknown;\n}\n\n/**\n * H-15: audit is best-effort by contract — a full disk, a locked log file or an\n * unserialisable payload must never abort a beat (one caller inside a catch\n * block turning a handled failure into an unhandled one is the worst case).\n * Failures go to stderr so they stay visible instead of silently vanishing.\n * N18-a3 中3: returns whether the line actually landed — true on success, false\n * on the caught failure (it still never THROWS). Callers that use the audit as\n * a once-per-typo memory (auditInvalidVisionEngines) must treat `false` as\n * \"not written\" and let the entry retry on the next beat.\n */\nexport function appendAuditLine(file: string, event: Omit<AuditEvent, 'ts'> & { ts?: string }): boolean {\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const line = JSON.stringify({ ts: event.ts ?? new Date().toISOString(), ...event });\n fs.appendFileSync(file, line + '\\n', 'utf8');\n return true;\n } catch (e) {\n process.stderr.write(`[heartbeat] audit append failed: ${file}: ${String(e)}\\n`);\n return false;\n }\n}\n\nexport function readAuditLines<T = AuditEvent>(file: string): T[] {\n if (!fs.existsSync(file)) return [];\n const out: T[] = [];\n const raw = fs.readFileSync(file, 'utf8');\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n out.push(JSON.parse(trimmed) as T);\n } catch {\n // Skip corrupt lines; the log is diagnostic, not authoritative data.\n out.push({ ts: '', corrupt: true, raw: trimmed.slice(0, 200) } as unknown as T);\n }\n }\n return out;\n}\n\n/**\n * Drop entries older than maxAgeMs. Returns the number of removed lines.\n * Rewrites the file atomically; on rewrite failure the original is untouched.\n */\nexport function pruneAuditFile(file: string, maxAgeMs: number, now = Date.now()): number {\n if (!fs.existsSync(file)) return 0;\n const lines = readAuditLines(file);\n const kept = lines.filter((e) => {\n const ev = e as unknown as AuditEvent;\n const ts = Date.parse(ev.ts ?? '');\n if (!Number.isFinite(ts)) return true; // keep unparseable lines, never lose audit data silently\n return now - ts <= maxAgeMs;\n });\n const removed = lines.length - kept.length;\n if (removed === 0) return 0;\n const body = kept.map((e) => JSON.stringify(e)).join('\\n');\n atomicWriteFileSync(file, body ? body + '\\n' : '');\n return removed;\n}\n","// Two-layer policy loading (D3): factory defaults (config/policy.json, read-only)\n// + user layer (data/settings/policy.json). Missing user layer is normal; an\n// invalid factory file or user layer is fail-closed (throw at startup).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { assertPolicy, deepMerge, type Policy } from './schema.js';\nimport { atomicWriteFileSync } from '../core/atomic-fs.js';\n\nexport const USER_POLICY_FILE = 'policy.json';\n\nexport function loadPolicy(guard: PathGuard, configDir: string, settingsDir: string): Policy {\n const factoryPath = path.join(configDir, 'policy.json');\n let factoryRaw: unknown;\n try {\n factoryRaw = JSON.parse(fs.readFileSync(factoryPath, 'utf8'));\n } catch (e) {\n throw new Error(`factory policy unreadable at ${factoryPath}: ${String(e)}`);\n }\n assertPolicy(factoryRaw);\n\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let merged: Policy = factoryRaw;\n if (fs.existsSync(userPath)) {\n try {\n const userRaw: unknown = JSON.parse(fs.readFileSync(userPath, 'utf8'));\n merged = deepMerge(factoryRaw, userRaw);\n } catch (e) {\n throw new Error(`user policy layer unparseable at ${userPath}: ${String(e)}`);\n }\n }\n assertPolicy(merged);\n return merged;\n}\n\n/**\n * Merge `patch` into the user policy layer (data/settings/policy.json) without\n * touching the factory file. Used by the settings card for policy-backed\n * toggles (psyEnabled, v1.7.0). No full-Policy validation here: the layer is\n * merged over the factory and validated together at the next loadPolicy.\n */\nexport function updateUserPolicy(guard: PathGuard, settingsDir: string, patch: Record<string, unknown>): Record<string, unknown> {\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let user: Record<string, unknown> = {};\n try {\n user = JSON.parse(fs.readFileSync(userPath, 'utf8')) as Record<string, unknown>;\n if (!user || typeof user !== 'object' || Array.isArray(user)) user = {};\n } catch {\n user = {}; // fresh layer\n }\n const merged = deepMerge(user, patch) as Record<string, unknown>;\n fs.mkdirSync(path.dirname(userPath), { recursive: true });\n atomicWriteFileSync(userPath, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n","// Policy shape + runtime validation. Factory defaults live in config/policy.json\n// (read-only); the user layer in data/settings/policy.json overrides via deep\n// merge (design doc §13, D3).\n\nexport interface QuietHours {\n start: string; // \"HH:MM\"\n end: string; // \"HH:MM\"\n}\n\nexport interface BrowseWindow {\n start: string;\n end: string;\n}\n\nexport interface Policy {\n heartbeat: {\n intervalMin: number;\n idleMode: boolean;\n archiveRotatedHome: boolean;\n /** v2.1.0 interval jitter: each hop draws interval × (1 + u), u uniform in\n * [-p, +p] with p = this/100. Range [0, 50]. OPTIONAL in the type so\n * pre-existing policy layers still validate; when absent the runtime\n * applies the factory default ±20 (clampJitterPct in the orchestrator). */\n intervalJitterPct?: number;\n };\n gate: {\n maxDailySend: number;\n cooldownMinutes: number;\n quietHours: QuietHours;\n };\n browse: {\n windows: BrowseWindow[];\n minIntervalHours: number;\n maxSeedsPerVisit: number;\n };\n seeds: {\n maxActive: number;\n ttlDays: { news: number; fandom: number; scene: number; promise: number };\n coldBenchDays: number;\n /** Archive-area cap (v1.9.0): gc trims archived seeds beyond this, oldest first. */\n archiveCap: number;\n retireAfterUsed: number;\n scoreWeights: { freshness: number; unused: number; confidence: number };\n };\n profile: {\n consolidation: { minIntervalHours: number; inboxBacklog: number };\n partitionCap: number;\n maxOpsPerRun: number;\n confidenceCap: { chat: number; screen: number; browse: number };\n volatileDays: number;\n stableLowActivityDays: number;\n psyEnabled: boolean;\n };\n /** Observation depth (v1.8.0): how much of each user message enters the inbox. */\n observe: { maxChars: number; perBeat: number };\n weekly: {\n enabled: boolean;\n /** v2.0 (item 5): how many past reports the store keeps and the card lists. */\n keepReports: number;\n };\n retention: { envPulseHours: number; decisionLogDays: number };\n /** v2.2 optional per-source config. Absent = every source's own default\n * behaviour (bilibili: on iff a credential exists). OPTIONAL so pre-2.2\n * policy layers still validate. */\n sources?: {\n bilibili?: {\n /** false = hard-disable the source even with a credential. */\n enabled?: boolean;\n /** Fallback credential: text file whose content parses as SESSDATA. */\n cookieFile?: string;\n };\n };\n}\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction fail(msg: string): never {\n throw new Error(`policy: ${msg}`);\n}\n\nexport function assertPolicy(input: unknown): asserts input is Policy {\n if (!isPlainObject(input)) fail('root must be an object');\n const p = input;\n const hb = p.heartbeat;\n if (!isPlainObject(hb)) fail('heartbeat missing');\n if (typeof hb.intervalMin !== 'number' || hb.intervalMin < 1 || hb.intervalMin > 1440) {\n fail('heartbeat.intervalMin must be a number in [1, 1440]');\n }\n if (typeof hb.idleMode !== 'boolean') fail('heartbeat.idleMode must be boolean');\n if (typeof hb.archiveRotatedHome !== 'boolean') fail('heartbeat.archiveRotatedHome must be boolean');\n // v2.1.0: optional — pre-existing policy layers (and hand-built literals in\n // tests) predate it; the runtime default lives in the orchestrator.\n if (hb.intervalJitterPct !== undefined\n && (typeof hb.intervalJitterPct !== 'number' || hb.intervalJitterPct < 0 || hb.intervalJitterPct > 50)) {\n fail('heartbeat.intervalJitterPct must be a number in [0, 50]');\n }\n const g = p.gate;\n if (!isPlainObject(g)) fail('gate missing');\n if (typeof g.maxDailySend !== 'number' || g.maxDailySend < 0) fail('gate.maxDailySend must be >= 0');\n if (typeof g.cooldownMinutes !== 'number' || g.cooldownMinutes < 0) fail('gate.cooldownMinutes must be >= 0');\n const qh = g.quietHours;\n if (!isPlainObject(qh)) fail('gate.quietHours missing');\n if (typeof qh.start !== 'string' || !HHMM.test(qh.start) || typeof qh.end !== 'string' || !HHMM.test(qh.end)) {\n fail('gate.quietHours must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n const b = p.browse;\n if (!isPlainObject(b)) fail('browse missing');\n if (!Array.isArray(b.windows) || b.windows.length === 0) fail('browse.windows must be a non-empty array');\n for (const w of b.windows) {\n if (!isPlainObject(w)) fail('browse.windows entries must be objects');\n if (typeof w.start !== 'string' || !HHMM.test(w.start) || typeof w.end !== 'string' || !HHMM.test(w.end)) {\n fail('browse.windows entries must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n }\n if (typeof b.minIntervalHours !== 'number' || b.minIntervalHours <= 0) fail('browse.minIntervalHours must be > 0');\n if (typeof b.maxSeedsPerVisit !== 'number' || b.maxSeedsPerVisit < 1) fail('browse.maxSeedsPerVisit must be >= 1');\n const s = p.seeds;\n if (!isPlainObject(s)) fail('seeds missing');\n if (typeof s.maxActive !== 'number' || s.maxActive < 1) fail('seeds.maxActive must be >= 1');\n if (!isPlainObject(s.ttlDays)) fail('seeds.ttlDays missing');\n for (const k of ['news', 'fandom', 'scene', 'promise'] as const) {\n if (typeof s.ttlDays[k] !== 'number') fail(`seeds.ttlDays.${k} missing`);\n }\n if (typeof s.coldBenchDays !== 'number') fail('seeds.coldBenchDays missing');\n if (typeof s.archiveCap !== 'number' || s.archiveCap < 1) fail('seeds.archiveCap must be >= 1');\n if (typeof s.retireAfterUsed !== 'number' || s.retireAfterUsed < 1) fail('seeds.retireAfterUsed must be >= 1');\n if (!isPlainObject(s.scoreWeights)) fail('seeds.scoreWeights missing');\n const pr = p.profile;\n if (!isPlainObject(pr)) fail('profile missing');\n const c = pr.consolidation;\n if (!isPlainObject(c)) fail('profile.consolidation missing');\n if (typeof c.minIntervalHours !== 'number' || typeof c.inboxBacklog !== 'number') fail('profile.consolidation fields missing');\n if (typeof pr.partitionCap !== 'number' || pr.partitionCap < 1) fail('profile.partitionCap must be >= 1');\n if (typeof pr.maxOpsPerRun !== 'number' || pr.maxOpsPerRun < 1) fail('profile.maxOpsPerRun must be >= 1');\n const cc = pr.confidenceCap;\n if (!isPlainObject(cc)) fail('profile.confidenceCap missing');\n if (typeof cc.chat !== 'number' || typeof cc.screen !== 'number' || typeof cc.browse !== 'number') {\n fail('profile.confidenceCap fields missing');\n }\n if (typeof pr.volatileDays !== 'number' || pr.volatileDays < 1) fail('profile.volatileDays must be >= 1');\n if (typeof pr.stableLowActivityDays !== 'number' || pr.stableLowActivityDays < 1) fail('profile.stableLowActivityDays must be >= 1');\n if (typeof pr.psyEnabled !== 'boolean') fail('profile.psyEnabled must be boolean');\n const ob = p.observe;\n if (!isPlainObject(ob)) fail('observe missing');\n if (typeof ob.maxChars !== 'number' || ob.maxChars < 20 || ob.maxChars > 2000) fail('observe.maxChars must be in [20, 2000]');\n if (typeof ob.perBeat !== 'number' || ob.perBeat < 1 || ob.perBeat > 100) fail('observe.perBeat must be in [1, 100]');\n if (!isPlainObject(p.weekly)) fail('weekly missing');\n if (typeof p.weekly.enabled !== 'boolean') fail('weekly.enabled must be boolean');\n if (typeof p.weekly.keepReports !== 'number' || p.weekly.keepReports < 1 || p.weekly.keepReports > 52) {\n fail('weekly.keepReports must be a number in [1, 52]');\n }\n const r = p.retention;\n if (!isPlainObject(r)) fail('retention missing');\n if (typeof r.envPulseHours !== 'number' || typeof r.decisionLogDays !== 'number') fail('retention fields missing');\n // v2.2: sources is entirely optional and only validated when present — old\n // policy layers (and hand-built test literals) must keep validating.\n if (p.sources !== undefined) {\n if (!isPlainObject(p.sources)) fail('sources must be an object when present');\n const bili = p.sources.bilibili;\n if (bili !== undefined) {\n if (!isPlainObject(bili)) fail('sources.bilibili must be an object when present');\n if (bili.enabled !== undefined && typeof bili.enabled !== 'boolean') {\n fail('sources.bilibili.enabled must be boolean when present');\n }\n if (bili.cookieFile !== undefined && typeof bili.cookieFile !== 'string') {\n fail('sources.bilibili.cookieFile must be a string when present');\n }\n }\n }\n}\n\n/** Recursive merge: user values win; objects merge, arrays and scalars replace. */\nexport function deepMerge<T>(base: T, override: unknown): T {\n if (!isPlainObject(base) || !isPlainObject(override)) {\n return (override === undefined ? base : (override as T));\n }\n const out: Record<string, unknown> = { ...base };\n for (const [k, v] of Object.entries(override)) {\n out[k] = v === undefined ? (base as Record<string, unknown>)[k] : deepMerge((base as Record<string, unknown>)[k], v);\n }\n return out as T;\n}","// Shared HH:MM window arithmetic.\n//\n// H-14: quiet hours (`gate.ts`) and wander windows (`browse.ts`) each carried\n// their own copy of this comparison, and only ONE of them handled a window\n// that crosses midnight — so a `22:00-02:00` wander window silently never\n// matched. One implementation, one set of semantics, no drift.\n//\n// Interval is left-closed / right-open, so `22:00-02:00` and `02:00-06:00`\n// never overlap and every minute belongs to at most one window.\n\nconst HH_MM = /^(\\d{1,2}):(\\d{2})$/;\n\n/** \"22:30\" -> 1350; null when malformed (callers treat that as \"never matches\"). */\nexport function parseHhMm(text: string): number | null {\n const m = HH_MM.exec(String(text).trim());\n if (!m) return null;\n const h = Number(m[1]);\n const min = Number(m[2]);\n if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;\n return h * 60 + min;\n}\n\nexport function minutesOfDay(now: Date): number {\n return now.getHours() * 60 + now.getMinutes();\n}\n\n/** TRUE when `mins` (minutes since local midnight) falls inside [start, end). */\nexport function inHhMmWindow(start: string, end: string, mins: number): boolean {\n const s = parseHhMm(start);\n const e = parseHhMm(end);\n if (s === null || e === null) return false;\n if (s === e) return false; // zero-length window matches nothing\n return s > e ? mins >= s || mins < e : mins >= s && mins < e;\n}\n\n/** LOCAL calendar day key \"YYYY-MM-DD\" (H-88, 2026-10-29).\n *\n * \"Today\" is a human day, not a UTC day: a user at 07:00 local in UTC+8 is\n * still on the previous UTC date, so a UTC key rolls the day over mid-morning\n * and every daily budget resets at the wrong hour. Browsing's refill quota\n * already worked this way (it kept a private copy); the ledger's aging\n * window, the rhythm ring and the export filenames now share this one. */\nexport function localDayKey(d: Date = new Date()): string {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,OAAOA,SAAQ;AACf,OAAOC,WAAU;;;ACbjB,OAAO,QAAQ;AACf,OAAO,UAAU;AAkBV,SAAS,gBAAgB,MAAc,OAA0D;AACtG,MAAI;AACF,OAAG,UAAU,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACpD,UAAM,OAAO,KAAK,UAAU,EAAE,IAAI,MAAM,OAAM,oBAAI,KAAK,GAAE,YAAY,GAAG,GAAG,MAAM,CAAC;AAClF,OAAG,eAAe,MAAM,OAAO,M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