@kanadego/dsh-heartbeat 2.3.0 → 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 +70 -81
- package/USAGE-GUIDE.md +357 -0
- package/dist/{chunk-43Q42HWH.js → chunk-AJ5JAQVB.js} +13 -2
- 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-K47VV6IQ.js → chunk-ERRPMYKB.js} +163 -153
- package/dist/chunk-ERRPMYKB.js.map +1 -0
- package/dist/chunk-L54R23O2.js +262 -0
- package/dist/chunk-L54R23O2.js.map +1 -0
- package/dist/{chunk-HSTGRQLP.js → chunk-MHRAPKES.js} +406 -66
- package/dist/chunk-MHRAPKES.js.map +1 -0
- package/dist/{chunk-ABFO4QII.js → chunk-RPWQZYNW.js} +603 -157
- package/dist/chunk-RPWQZYNW.js.map +1 -0
- package/dist/cli/index.js +160 -23
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.js +98 -22
- package/dist/index.js.map +1 -1
- package/dist/{migrate-6HH2ZARV.js → migrate-25F53XIC.js} +4 -2
- package/dist/{orchestrator-OJJM5QSV.js → orchestrator-4PJD7QYO.js} +11 -6
- package/dist/snapshot-J6LKNY57.js +27 -0
- package/dist/store-HM6ZMFKS.js +45 -0
- package/package.json +6 -3
- package/dist/chunk-43Q42HWH.js.map +0 -1
- package/dist/chunk-ABFO4QII.js.map +0 -1
- package/dist/chunk-HSTGRQLP.js.map +0 -1
- package/dist/chunk-JIRQ36F7.js +0 -87
- package/dist/chunk-JIRQ36F7.js.map +0 -1
- package/dist/chunk-K47VV6IQ.js.map +0 -1
- package/dist/chunk-KGOC6EX4.js +0 -413
- package/dist/chunk-KGOC6EX4.js.map +0 -1
- package/dist/chunk-QOLKUYQ3.js +0 -393
- package/dist/chunk-QOLKUYQ3.js.map +0 -1
- package/dist/pool-QTY2MI56.js +0 -49
- package/dist/snapshot-6DFNGXTR.js +0 -16
- /package/dist/{migrate-6HH2ZARV.js.map → migrate-25F53XIC.js.map} +0 -0
- /package/dist/{orchestrator-OJJM5QSV.js.map → orchestrator-4PJD7QYO.js.map} +0 -0
- /package/dist/{pool-QTY2MI56.js.map → snapshot-J6LKNY57.js.map} +0 -0
- /package/dist/{snapshot-6DFNGXTR.js.map → store-HM6ZMFKS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/seeds/pool.ts","../src/seeds/types.ts","../src/ledger/ledger.ts","../src/browse/preference.ts","../src/browse/browse.ts","../src/notify/notify.ts","../src/core/ps.ts","../src/weekly/report.ts"],"sourcesContent":["// Material pool engine (design doc §4). All four eviction rules are\n// deterministic code - no LLM involvement (§4.2). Storage: data/seeds.jsonl,\n// one seed per JSON line, DPAPI-encrypted at rest (D14).\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport { withFileLock } from '../core/file-lock.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n SEED_SOURCE_DEFAULT_CONFIDENCE,\n emptySeedDb,\n type Seed,\n type SeedCategory,\n type SeedDb,\n type SeedRetireReason,\n type SeedSource,\n type SeedTag,\n} from './types.js';\n\nconst DAY_MS = 86_400_000;\n\n// ── lifecycle audit (2026-10-06 / v1.9.0) ───────────────────────────────\n// The pool used to mutate in silence: a seed could appear, be evicted for\n// capacity, or be dropped from the archive with nothing in the log. Every\n// mutator now takes an optional sink and reports what it did. IDs and\n// metadata ONLY — heartbeat.jsonl is plaintext by charter and must never\n// carry conversation text; the seed text itself stays in the DPAPI pool.\nexport type SeedAuditFn = (entry: Record<string, unknown>) => void;\n\nconst NO_AUDIT: SeedAuditFn = () => {};\n\n/** Audit must never break the pool (or the beat that called it). */\nfunction emit(audit: SeedAuditFn, entry: Record<string, unknown>): void {\n try {\n audit(entry);\n } catch {\n /* audit is diagnostic; a failed append is not a pool failure */\n }\n}\n\n// Per-category pool caps (2026-09-18 spec ⑤): topic stock vs conversation-grown\n// chat material, decoupled from `source`; sum == the global maxActive default.\nexport const SEED_CATEGORY_CAPS: Record<SeedCategory, number> = { topic: 16, chat: 14 };\n\n// Per-source pool caps (2026-11-09): one origin must not own the pool — the\n// bilibili watch history gets its own lane (source 'bilibili', see types.ts)\n// and is capped at 6 so it cannot crowd every other source out. Third quota\n// dimension, checked BEFORE the category and global caps; absent key =\n// uncapped source.\nexport const SEED_SOURCE_CAPS: Partial<Record<SeedSource, number>> = { bilibili: 6 };\n\nconst CATEGORY_VALUES: readonly string[] = ['topic', 'chat'];\n\n/** Lenient category coercion for on-disk rows: anything missing/unknown (all\n * pre-v1.5 seeds) counts as topic stock. */\nexport function normalizeCategory(v: unknown): SeedCategory {\n return typeof v === 'string' && (CATEGORY_VALUES as readonly string[]).includes(v)\n ? (v as SeedCategory)\n : 'topic';\n}\n\nexport interface AddSeedInput {\n text: string;\n topic?: string;\n tag?: SeedTag;\n source?: SeedSource;\n /** Loop role (spec ⑤); defaults from source: chat->chat, everything else->topic. */\n category?: SeedCategory;\n confidence?: number;\n /** Skip the §4.3 same-topic merge: callers registering several items under\n * one focus in a single pass (wander) set this so each item survives as\n * its own seed instead of collapsing into the first. */\n noMerge?: boolean;\n /** Per-seed TTL override in days (v2.2): wins over policy.seeds.ttlDays[tag]\n * for THIS seed only; absent = the tag default, unchanged for everyone else. */\n ttlDaysOverride?: number;\n}\n\nexport type DuplicateReason = 'exact' | 'normalized' | 'similar';\n\nexport interface AddSeedResult {\n kind: 'added' | 'merged' | 'duplicate';\n seed: Seed;\n evicted?: Seed;\n /** Why a 'duplicate' was judged; absent on other kinds. */\n reason?: DuplicateReason;\n}\n\n// ── dedup (2026-10-29): wander keeps re-seeding the same material, so the add\n// path compares against actives AND recently archived seeds on three levels —\n// raw text, NFKC-normalized text, and character-bigram Dice similarity.\nexport const SEED_SIMILARITY_THRESHOLD = 0.85;\nconst DEDUP_ARCHIVE_WINDOW_MS = 30 * DAY_MS;\nconst DEDUP_ARCHIVE_MAX = 50;\n/** Short strings are all shared bigrams: \"话题素材 1\" vs \"话题素材 11\" scores\n * 0.889 and \"没有新证据的话题\" vs \"有新证据的话题\" 0.923, i.e. the similarity\n * layer would kill genuinely distinct short headlines. Below this normalized\n * length only the exact and normalized layers run (2026-10-30 review; the\n * old seeds.test.ts cap cases caught it as a real regression). */\nconst DEDUP_SIMILAR_MIN_CHARS = 12;\n\n/** Full-width -> half-width (NFKC), lowercase, strip all whitespace and\n * punctuation: only the surviving characters may make two seeds collide. */\nexport function normalizeSeedText(s: string): string {\n return s\n .normalize('NFKC')\n .toLowerCase()\n .replace(/[\\s\\p{P}\\p{S}]+/gu, '');\n}\n\n/** Dice coefficient over character bigrams of the NORMALIZED texts:\n * 2*|A∩B| / (|A|+|B|). Identical normalizations are 1; either side short\n * enough to have no bigrams only matches when they are identical. */\nexport function seedSimilarity(a: string, b: string): number {\n const na = normalizeSeedText(a);\n const nb = normalizeSeedText(b);\n if (na === nb) return 1;\n if (na.length < 2 || nb.length < 2) return 0;\n const gramCount = (t: string): Map<string, number> => {\n const m = new Map<string, number>();\n for (let i = 0; i < t.length - 1; i++) {\n const g = t.slice(i, i + 2);\n m.set(g, (m.get(g) ?? 0) + 1);\n }\n return m;\n };\n const A = gramCount(na);\n const B = gramCount(nb);\n let inter = 0;\n let sizeA = 0;\n let sizeB = 0;\n for (const c of A.values()) sizeA += c;\n for (const c of B.values()) sizeB += c;\n for (const [g, c] of A) inter += Math.min(c, B.get(g) ?? 0);\n return (2 * inter) / (sizeA + sizeB);\n}\n\n/** Archive side of the dedup scope: recently retired only (within 30 days,\n * newest first, at most 50) — the archive is a forensic trail, not a corpus\n * to scan on every add. */\nfunction recentArchived(db: SeedDb, now: number): Seed[] {\n return archivedSeeds(db)\n .filter((s) => now - parseIso(s.retiredAt ?? '') <= DEDUP_ARCHIVE_WINDOW_MS)\n .sort((a, b) => parseIso(b.retiredAt ?? '') - parseIso(a.retiredAt ?? ''))\n .slice(0, DEDUP_ARCHIVE_MAX);\n}\n\nexport interface GcReport {\n consumed: number;\n expired: number;\n coldBench: number;\n activeAfter: number;\n /** v1.9.0: archived rows dropped to honor seeds.archiveCap (oldest first). */\n archiveTrimmed: number;\n}\n\nexport const TTL_KEYS: readonly SeedTag[] = ['news', 'fandom', 'scene', 'promise'];\n\nexport function normalizeTag(tag: string | undefined): SeedTag {\n if (tag && (TTL_KEYS as readonly string[]).includes(tag)) return tag as SeedTag;\n return 'scene';\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n// ── storage ─────────────────────────────────────────────────────────────\n\nexport function seedsFilePath(dataDir: string): string {\n return path.join(dataDir, 'seeds.jsonl');\n}\n\nexport function loadPool(guard: PathGuard, file: string): SeedDb {\n const raw = loadEncryptedText(guard, file);\n if (raw === null) return emptySeedDb();\n const db = emptySeedDb();\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obj = JSON.parse(trimmed) as Seed;\n if (typeof obj.id === 'string' && obj.id.startsWith('s')) {\n // spec ⑤ loadPool tolerance: only the id is load-bearing; a missing or\n // unknown category (every pre-v1.5 row) falls back to topic stock.\n obj.category = normalizeCategory(obj.category);\n db.seeds.push(obj);\n const n = Number(obj.id.slice(1));\n if (Number.isFinite(n) && n > db.seq) db.seq = n;\n }\n } catch {\n // corrupt line: skip (pool is a cache; journal-level audit lives elsewhere)\n }\n }\n return db;\n}\n\nexport function savePool(guard: PathGuard, file: string, db: SeedDb): void {\n const body = db.seeds.map((s) => JSON.stringify(s)).join('\\n');\n saveEncryptedText(guard, file, body ? body + '\\n' : '');\n}\n\n/**\n * H-20 (minimal tier): every pool writer goes through here, so the load happens\n * INSIDE the cross-process lock and cannot be based on a read that went stale\n * while it was being mutated — the CLI is a second process sharing this file,\n * and an interleaved write used to be silently overwritten. The ciphertext is a\n * whole-file rewrite, so append/merge does not apply here; the append-only pool\n * with compaction is v2.0 work (ledger #8649f9).\n */\nfunction update<T>(guard: PathGuard, file: string, fn: (db: SeedDb) => T): T {\n return withFileLock(file, () => fn(loadPool(guard, file)));\n}\n\n// ── queries ─────────────────────────────────────────────────────────────\n\nexport const activeSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'active');\nexport const archivedSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'archived');\n\n// ── eviction scoring (rule 4) ───────────────────────────────────────────\n\n/**\n * Comprehensive score (§4.2): freshness x0.4 + unused x0.3 + confidence x0.3.\n * Higher = keep. Lowest-scoring active is evicted when the pool is full.\n */\nexport function evictionScore(seed: Seed, policy: Policy, now: number): number {\n const ttlDays = policy.seeds.ttlDays[seed.tag] || 14;\n const daysStale = Math.max(0, (now - parseIso(seed.lastEvidenceAt)) / DAY_MS);\n const freshness = Math.max(0, 1 - daysStale / ttlDays);\n const unused = seed.used === 0 ? 1 : 1 / seed.used;\n const w = policy.seeds.scoreWeights;\n return freshness * w.freshness + unused * w.unused + seed.confidence * w.confidence;\n}\n\n/** Pick the eviction victim: unprotected actives first (§4.2 加权保护); with\n * `category`, only that category's actives compete (spec ⑤ per-category caps);\n * with `source`, only that source's actives compete (2026-11-09 per-source\n * caps). Both filters compose when given; existing callers pass neither or\n * one and are unaffected. */\nexport function pickEvictionVictim(db: SeedDb, policy: Policy, now: number, category?: SeedCategory, source?: SeedSource): Seed | null {\n const actives = activeSeeds(db).filter(\n (s) =>\n (category === undefined || normalizeCategory(s.category) === category) &&\n (source === undefined || s.source === source),\n );\n if (actives.length === 0) return null;\n const unprotected = actives.filter((s) => !s.protected);\n const candidates = unprotected.length > 0 ? unprotected : actives;\n let worst: Seed | null = null;\n let worstScore = Number.POSITIVE_INFINITY;\n for (const s of candidates) {\n const score = evictionScore(s, policy, now);\n if (score < worstScore) {\n worstScore = score;\n worst = s;\n }\n }\n return worst;\n}\n\nfunction archiveSeed(seed: Seed, reason: SeedRetireReason, now: number): void {\n seed.status = 'archived';\n seed.retireReason = reason;\n seed.retiredAt = new Date(now).toISOString();\n}\n\n/** Spec ④: chat-grown material is consumed ONCE (conversation freshness);\n * every other category follows the policy-wide retireAfterUsed. */\nfunction retireLimit(s: Seed, policy: Policy): number {\n return normalizeCategory(s.category) === 'chat' ? 1 : policy.seeds.retireAfterUsed;\n}\n\n/**\n * Rule 1 (§4.2): used up to its limit AND no evidence newer than the PREVIOUS\n * use. `prevUsedAt` MUST be read before bumping `lastUsedAt` — comparing the\n * just-written value against `lastEvidenceAt` is vacuously true (H-22), which\n * retired seeds that had received fresh evidence in the same beat. Both\n * callers (gc and surface) share this, so the rule cannot drift again.\n *\n * `prevUsedAt === 0` means \"never used before\": there is no earlier use for\n * the evidence to be newer THAN, so the exemption cannot apply — a one-shot\n * (chat) seed still retires on its first surfacing (spec ④), which is the\n * contract, not a regression.\n */\nfunction isConsumed(s: Seed, policy: Policy, prevUsedAt: number, sinceEvidence: number): boolean {\n if (s.used < retireLimit(s, policy)) return false;\n return !(prevUsedAt > 0 && sinceEvidence > prevUsedAt);\n}\n\n// ── operations ──────────────────────────────────────────────────────────\n\nexport function addSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): AddSeedResult {\n // H-20: the read-modify-write below runs under the cross-process pool lock\n // (same guard as `update`, kept as a named body to avoid re-indenting it).\n return withFileLock(file, () => addSeedLocked(guard, file, policy, input, now, audit));\n}\n\nfunction addSeedLocked(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now: number,\n audit: SeedAuditFn,\n): AddSeedResult {\n const db = loadPool(guard, file);\n const text = input.text.trim();\n if (!text) throw new Error('seed text must not be empty');\n const tag = normalizeTag(input.tag);\n const source: SeedSource = input.source ?? 'chat';\n const category = normalizeCategory(input.category ?? (source === 'chat' ? 'chat' : 'topic'));\n const confidence = input.confidence ?? SEED_SOURCE_DEFAULT_CONFIDENCE[source];\n\n // Three-layer dedup against actives + recently archived. Exact hits audit\n // without a score; normalized hits score 1 by definition. The similarity\n // layer is skipped for short texts (see DEDUP_SIMILAR_MIN_CHARS): distinct\n // short headlines share too many bigrams to be told apart by Dice alone.\n const textNorm = normalizeSeedText(text);\n for (const cand of [...activeSeeds(db), ...recentArchived(db, now)]) {\n if (cand.text === text) {\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'exact' });\n return { kind: 'duplicate', seed: cand, reason: 'exact' };\n }\n const candNorm = normalizeSeedText(cand.text);\n if (candNorm === textNorm) {\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'normalized', similarity: 1 });\n return { kind: 'duplicate', seed: cand, reason: 'normalized' };\n }\n if (textNorm.length < DEDUP_SIMILAR_MIN_CHARS || candNorm.length < DEDUP_SIMILAR_MIN_CHARS) continue;\n const sim = seedSimilarity(cand.text, text);\n if (sim <= SEED_SIMILARITY_THRESHOLD) continue;\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'similar', similarity: Number(sim.toFixed(3)) });\n return { kind: 'duplicate', seed: cand, reason: 'similar' };\n }\n\n const nowIso = new Date(now).toISOString();\n // v2.2: a per-seed override wins for this seed only; every other seed keeps\n // the tag default (untouched behaviour).\n const ttlDays = input.ttlDaysOverride ?? (policy.seeds.ttlDays[tag] || 14);\n const ttlMs = ttlDays * DAY_MS;\n\n // Same-topic merge (§4.3): collapse all same-topic actives + the new item.\n // `noMerge` opts out — wander registers several items under one focus per\n // pass and each must land as its own seed.\n const sameTopic = activeSeeds(db).filter((s) => s.topic === (input.topic ?? text.slice(0, 24)));\n let seed: Seed;\n if (sameTopic.length > 0 && !input.noMerge) {\n const kept = sameTopic[0]!;\n kept.text = text; // brief takes the latest\n kept.tag = tag;\n kept.source = source;\n kept.category = normalizeCategory(input.category ?? kept.category ?? category);\n kept.confidence = Math.max(kept.confidence, confidence);\n kept.used = sameTopic.reduce((acc, s) => acc + s.used, 0); // used accumulates\n kept.lastEvidenceAt = [kept.lastEvidenceAt, nowIso, ...sameTopic.map((s) => s.lastEvidenceAt)]\n .reduce((a, b) => (parseIso(b) > parseIso(a) ? b : a));\n kept.expiresAt = new Date(Math.max(parseIso(kept.expiresAt), now + ttlMs)).toISOString();\n kept.protected = kept.protected || source === 'hand' || (source === 'profile' && confidence >= 0.7);\n // remove the other same-topic actives (merged into kept)\n for (const extra of sameTopic.slice(1)) {\n extra.status = 'archived';\n extra.retireReason = 'completed';\n extra.retiredAt = nowIso;\n emit(audit, { event: 'seed_retired', id: extra.id, reason: 'completed', via: 'merge', into: kept.id });\n }\n seed = kept;\n // capacity still applies after growth check below if kept is somehow over cap\n if (activeSeeds(db).length > policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, normalizeCategory(kept.category));\n if (victim && victim.id !== kept.id) {\n archiveSeed(victim, 'pool_cap', now);\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n emit(audit, { event: 'seed_retired', id: victim.id, reason: 'pool_cap', via: 'merge', into: kept.id });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept, evicted: victim };\n }\n }\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept };\n }\n\n // Capacity first (rules 4 + spec ⑤ + 2026-11-09 source caps): three quota\n // dimensions checked in order source -> category -> global, each evicting\n // within its own scope. The source cap LOOP-evicts inside the incoming\n // source until the lane sits below its cap — a stock already over the cap\n // must converge, so ONE add may retire several rows (each audited; the\n // result's `evicted` carries the LAST victim — the CLI only surfaces it as\n // a hint). Once the source cap fired, the later caps cannot newly overflow\n // (one in, net <= 0 out) and are skipped.\n const sourceVictims: Seed[] = [];\n const sourceCap = SEED_SOURCE_CAPS[source];\n if (sourceCap !== undefined) {\n while (activeSeeds(db).filter((s) => s.source === source).length >= sourceCap) {\n const victim = pickEvictionVictim(db, policy, now, undefined, source);\n if (!victim) break; // lane empty (defensive): nothing left to evict\n archiveSeed(victim, 'source_cap', now);\n sourceVictims.push(victim);\n }\n }\n let evicted: Seed | undefined;\n if (sourceVictims.length > 0) {\n evicted = sourceVictims[sourceVictims.length - 1];\n } else {\n const catCount = activeSeeds(db).filter((s) => normalizeCategory(s.category) === category).length;\n if (catCount >= SEED_CATEGORY_CAPS[category]) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = victim;\n }\n }\n if (!evicted && activeSeeds(db).length >= policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = victim;\n }\n }\n }\n\n db.seq += 1;\n seed = {\n id: `s${db.seq}`,\n text,\n topic: input.topic ?? text.slice(0, 24),\n tag,\n source,\n category,\n confidence,\n protected: source === 'hand' || (source === 'profile' && confidence >= 0.7),\n used: 0,\n bornAt: nowIso,\n expiresAt: new Date(now + ttlMs).toISOString(),\n ...(input.ttlDaysOverride !== undefined ? { ttlDaysOverride: input.ttlDaysOverride } : {}),\n lastUsedAt: null,\n lastEvidenceAt: nowIso,\n status: 'active',\n };\n db.seeds.push(seed);\n emit(audit, { event: 'seed_added', id: seed.id, kind: 'added', tag: seed.tag, source: seed.source, category: seed.category, confidence: seed.confidence });\n for (const victim of sourceVictims) {\n emit(audit, { event: 'seed_retired', id: victim.id, reason: 'source_cap', via: 'add', into: seed.id });\n }\n if (evicted && sourceVictims.length === 0) {\n emit(audit, { event: 'seed_retired', id: evicted.id, reason: 'pool_cap', via: 'add', into: seed.id });\n }\n savePool(guard, file, db);\n return { kind: 'added', seed, evicted };\n}\n\n/**\n * Deterministic gc (rules 1-3 of §4.2). Rule 4 (pool cap) fires on add only.\n * v1.9.0: the archive area is ALSO capped (seeds.archiveCap) — the archive is\n * a forensic trail, not a hoard; trim oldest-retired first.\n */\nexport function gcPool(guard: PathGuard, file: string, policy: Policy, now = Date.now(), audit: SeedAuditFn = NO_AUDIT): GcReport {\n return update(guard, file, (db) => {\n const report: GcReport = { consumed: 0, expired: 0, coldBench: 0, activeAfter: 0, archiveTrimmed: 0 };\n for (const s of activeSeeds(db)) {\n const ageMs = now - parseIso(s.bornAt);\n const sinceEvidence = parseIso(s.lastEvidenceAt);\n const sinceUsed = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n if (isConsumed(s, policy, sinceUsed, sinceEvidence)) {\n archiveSeed(s, 'consumed', now);\n report.consumed += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'gc', used: s.used });\n } else if (now > parseIso(s.expiresAt)) {\n archiveSeed(s, 'expired', now);\n report.expired += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'expired', via: 'gc', used: s.used });\n } else if (s.used === 0 && ageMs >= policy.seeds.coldBenchDays * DAY_MS) {\n archiveSeed(s, 'cold_bench', now);\n report.coldBench += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'cold_bench', via: 'gc', used: s.used });\n }\n }\n // archive cap: drop the oldest-retired rows beyond the cap (retiredAt may be\n // missing on pre-v1.5 rows — parseIso('') = 0 sorts them oldest).\n const archived = db.seeds.filter((s) => s.status === 'archived');\n if (archived.length > policy.seeds.archiveCap) {\n const drop = [...archived]\n .sort((a, b) => parseIso(a.retiredAt ?? '') - parseIso(b.retiredAt ?? ''))\n .slice(0, archived.length - policy.seeds.archiveCap);\n const dropped = new Set(drop.map((s) => s.id));\n db.seeds = db.seeds.filter((s) => !dropped.has(s.id));\n report.archiveTrimmed = drop.length;\n // These rows are GONE (not archived — deleted): the log is the only trace\n // left, so name them. IDs only, and cap the list in case a first GC trims\n // a legacy archive wholesale.\n emit(audit, { event: 'seed_archive_trimmed', count: drop.length, ids: drop.slice(0, 50).map((s) => s.id) });\n }\n report.activeAfter = activeSeeds(db).length;\n savePool(guard, file, db);\n return report;\n });\n}\n\n/** The seed surfaced in a real expression: count + maybe retire (rule 1). */\nexport function surfaceSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n // H-22: snapshot the PREVIOUS use time before bumping it — the retirement\n // check must compare against the last use, not against this one.\n const prevUsedAt = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n s.used += 1;\n s.lastUsedAt = new Date(now).toISOString();\n if (isConsumed(s, policy, prevUsedAt, parseIso(s.lastEvidenceAt))) {\n archiveSeed(s, 'consumed', now);\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'surface', used: s.used });\n }\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Deliberate retirement (item completed / no longer relevant). */\nexport function archiveSeedById(\n guard: PathGuard,\n file: string,\n id: string,\n reason: SeedRetireReason = 'completed',\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n archiveSeed(s, reason, now);\n emit(audit, { event: 'seed_retired', id: s.id, reason, via: 'manual' });\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Restore an archived seed to the active pool (UI operation; resets TTL). */\nexport function restoreSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): { ok: true; seed: Seed } | { ok: false; reason: string } {\n return update<{ ok: true; seed: Seed } | { ok: false; reason: string }>(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'archived');\n if (!s) return { ok: false, reason: 'archived seed not found' };\n // H-23: a restore must satisfy the same two caps an add does — the global\n // one AND the per-category one. The add path evicts a neighbour instead, but\n // restoring a memory is a user action: refuse it rather than silently\n // pushing someone else's material out.\n const category = normalizeCategory(s.category);\n const catCap = SEED_CATEGORY_CAPS[category];\n const inCategory = activeSeeds(db).filter((x) => normalizeCategory(x.category) === category).length;\n if (inCategory >= catCap) {\n return { ok: false, reason: `category full (${category}: ${catCap}); archive something in it first` };\n }\n if (activeSeeds(db).length >= policy.seeds.maxActive) {\n return { ok: false, reason: `pool full (${policy.seeds.maxActive}); archive something first` };\n }\n s.status = 'active';\n s.retireReason = undefined;\n s.retiredAt = undefined;\n // H-23: reset bornAt as well — cold-bench eviction (used === 0 && age >=\n // coldBenchDays) keys off bornAt, so a restored seed used to be re-archived\n // by the very next maintenance beat (\"restored, then gone one beat later\").\n s.bornAt = new Date(now).toISOString();\n // v2.2: a restored seed keeps its own TTL override if it carries one (a\n // bilibili seed must not outlive its 2-day hard expiry by being restored).\n const restoreTtlDays = s.ttlDaysOverride ?? (policy.seeds.ttlDays[s.tag] || 14);\n s.expiresAt = new Date(now + restoreTtlDays * DAY_MS).toISOString();\n s.lastEvidenceAt = new Date(now).toISOString();\n emit(audit, { event: 'seed_restored', id: s.id });\n savePool(guard, file, db);\n return { ok: true, seed: s };\n });\n}\n\n/** Hard delete (UI explicit action with confirm; the caller audits it). */\nexport function deleteSeed(guard: PathGuard, file: string, id: string, audit: SeedAuditFn = NO_AUDIT): boolean {\n return update(guard, file, (db) => {\n const before = db.seeds.length;\n db.seeds = db.seeds.filter((x) => x.id !== id);\n if (db.seeds.length === before) return false;\n emit(audit, { event: 'seed_deleted', id });\n savePool(guard, file, db);\n return true;\n });\n}\n","// Material pool (\"素材池\") types. Charter (axiom 3): this pool is a CACHE,\n// not memory - volatile, evictable, burnable; long-term memory only absorbs\n// conversation-validated content. Everything here may be destroyed.\n\nexport type SeedTag = 'news' | 'fandom' | 'scene' | 'promise';\n// 'bilibili' (2026-11-09): the watch-history ingest carries its own source\n// value — it must not share the wander 'browse' lane, or the source cap would\n// let news push bilibili material out of the shared quota.\nexport type SeedSource = 'chat' | 'screen' | 'browse' | 'bilibili' | 'hand' | 'profile';\nexport type SeedCategory = 'topic' | 'chat';\nexport type SeedRetireReason = 'consumed' | 'expired' | 'cold_bench' | 'pool_cap' | 'source_cap' | 'completed';\n\nexport interface Seed {\n id: string;\n /** Short brief shown to the reflection prompt. */\n text: string;\n /** Merge key (§4.3): same-topic actives collapse into one. */\n topic: string;\n tag: SeedTag;\n source: SeedSource;\n /** Loop role, decoupled from source (2026-09-18 spec ⑤): 'topic' = wander/\n * hand/profile stock (random pick), 'chat' = conversation-grown, consumed\n * once. Absent on pre-v1.5 rows; loadPool defaults them to 'topic'. */\n category?: SeedCategory;\n /** 0..1 trust level; handwriting and high-confidence profile sources gain eviction protection. */\n confidence: number;\n /** Eviction protection (§4.2 pool-cap rule): handwritten / high-confidence profile sources. */\n protected: boolean;\n /** Times this seed surfaced in an actual expression. */\n used: number;\n bornAt: string;\n /** bornAt + ttlDays[tag] (or ttlDaysOverride when set); archived when passed (rule 2). */\n expiresAt: string;\n /** Optional per-seed TTL override in days (e.g. bilibili browse material\n * hard-expires in 2 days regardless of the scene tag). Absent = the tag's\n * policy TTL, which is the behaviour every pre-v2.2 row keeps. */\n ttlDaysOverride?: number;\n lastUsedAt: string | null;\n /** Fresh-evidence watermark: rule 1 spares seeds with evidence newer than last use. */\n lastEvidenceAt: string;\n status: 'active' | 'archived';\n retireReason?: SeedRetireReason;\n retiredAt?: string;\n}\n\nexport interface SeedDb {\n seq: number;\n seeds: Seed[];\n}\n\nexport function emptySeedDb(): SeedDb {\n return { seq: 0, seeds: [] };\n}\n\nexport const SEED_SOURCE_DEFAULT_CONFIDENCE: Record<SeedSource, number> = {\n hand: 1.0,\n profile: 0.7,\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n bilibili: 0.4,\n};\n","// Ledger (\"账本\") - the ONE shared ledger (design doc §5, requirement 5).\n// Human-readable Markdown by charter; the user may edit it by hand, so the\n// parser is tolerant: unknown lines are preserved verbatim on rewrite.\n//\n// 2.3.0: books are LIVE-ONLY. markDone 摘走: the row is removed from the book\n// and appended verbatim to its archive (`ledger-done.md` / `corrections-done.md`),\n// so a human opening the book only sees open items. Archive rows keep the SAME\n// `- [date time][done][#id] text` line format and go through the SAME parser\n// (readLedger) - only the file path and its header differ. Do not fork the\n// parser for the archive.\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { readText, writeText } from '../vault/vault.js';\nimport { localDayKey } from '../core/time-window.js';\nimport { withFileLock } from '../core/file-lock.js';\nimport { atomicCreateFileSync } from '../core/atomic-fs.js';\n\nconst DAY_MS = 86_400_000;\n\n/** Seeded when a book/archive file does not exist yet. */\nexport const LEDGER_HEADER = '# 账本\\n';\nexport const LEDGER_DONE_HEADER =\n '# 账本归档(不是账本:这里只放已完成的条目)\\n\\n' +\n '> 由心跳自动维护:账本里勾掉的条目会从 ledger.md 摘出来,原样追加到这里;手编不会被覆盖。\\n';\nexport const CORRECTIONS_HEADER = '# 错题本\\n';\nexport const CORRECTIONS_DONE_HEADER =\n '# 错题本归档(不是错题本:这里只放已复盘的条目)\\n\\n' +\n '> 由心跳自动维护:错题本里勾掉的条目会从 corrections.md 摘出来,原样追加到这里;手编不会被覆盖。\\n';\n\nexport interface LedgerEntry {\n id: string;\n date: string; // \"YYYY-MM-DD\"\n time: string; // \"HH:MM\"\n status: 'open' | 'done';\n text: string;\n}\n\nexport function ledgerFilePath(dataDir: string): string {\n return path.join(dataDir, 'ledger.md');\n}\n\n/** Archive of completed ledger rows (2.3.0). Derived, never guessed: the book\n * path is the single source of truth for where its archive lives. */\nexport function ledgerDoneFilePath(dataDir: string): string {\n return path.join(dataDir, 'ledger-done.md');\n}\n\n/** 错题本 (v1.10.0): same format, another file. */\nexport function correctionsFilePath(dataDir: string): string {\n return path.join(dataDir, 'corrections.md');\n}\n\n/** Archive of reviewed corrections (2.3.0). */\nexport function correctionsDoneFilePath(dataDir: string): string {\n return path.join(dataDir, 'corrections-done.md');\n}\n\n/** `<name>.md` → `<name>-done.md` in the same directory. */\nexport function doneFilePathFor(file: string): string {\n const ext = path.extname(file);\n return `${file.slice(0, file.length - ext.length)}-done${ext}`;\n}\n\n/** The two books are deliberately the only callers; anything else gets the\n * ledger archive header rather than a fourth header nobody asked for. */\nexport function doneHeaderFor(file: string): string {\n return path.basename(file).toLowerCase().startsWith('corrections')\n ? CORRECTIONS_DONE_HEADER\n : LEDGER_DONE_HEADER;\n}\n\n// The id is written by hand sometimes (`#net-backup-20260914`), and a\n// `{6}` hex rule silently dropped such rows: they stayed in rawLines but never\n// became entries, so scanPending failed to see them and markDone could not\n// find them. Any run of non-] non-space characters parses now; ids this plugin\n// generates itself are still 6 hex chars of a UUID.\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[(open|done)\\]\\[#([^\\]\\s]+)\\] (.*)$/;\n\nfunction renderEntry(e: LedgerEntry): string {\n return `- [${e.date} ${e.time}][${e.status}][#${e.id}] ${e.text}`;\n}\n\n/** A retried completion is re-stamped by markDone, so the same id+text may\n * arrive with a new minute (crash between archive append and book rewrite).\n * Two rows are the same completion only when their stamps are within this\n * window; a completion repeated next month is a NEW completion and must be\n * archived again (weekly \"done\" counts it). */\nconst RETRY_WINDOW_MS = 10 * 60_000;\n// A DST shift moves the wall clock without moving real time: ten REAL minutes\n// across a spring-forward shift render 70 wall minutes apart (01:55 → 03:05).\n// Wall deltas up to one hour beyond the retry window are the same completion\n// (N16② cross-review: the old Date.parse arithmetic got this right by\n// accident — epoch math hides the wall gap; the component form exposes it, so\n// the grace has to restore the dedupe explicitly).\n//\n// Design consequence (N16② review, pinned by the 30-minute test): a REAL\n// second completion of the same id+text inside those 70 wall minutes is\n// swallowed too. The archive keeps one row, and the weekly report — which\n// counts done by archive rows (src/weekly/collect.ts) — under-counts by one;\n// the `book_done_deduped` audit is the only trace.\nconst RETRY_WALL_GRACE_MS = 60 * 60_000;\n// A stamp AFTER `now` is clock skew, a hand edit or a cross-timezone re-render\n// — not a second completion. But only for a day: beyond that the archive must\n// self-heal, or one year-2099 stamp would dedupe every future real completion\n// of the item and silently under-count the weekly report forever (N16④).\nconst FUTURE_GRACE_MS = 24 * 60 * 60_000;\n// Known limitation (N16② review, pinned by the Asia/Shanghai test): the window\n// is single-sided ON PURPOSE. A timezone move WESTWARD re-reads a fresh stamp\n// as before-`now` — covered by the future grace above. A move EASTWARD renders\n// `now` up to ~14 wall hours AHEAD of the archived stamp, which is\n// indistinguishable from a real completion that many hours later; extending\n// the window that far would swallow real completions, so an eastward move may\n// archive the same completion twice and the weekly report may over-count by\n// one.\n\n/** N16②: both sides of every stamp comparison collapse to the stamp's own\n * wall-clock components (Date.UTC is timezone-free) instead of Date.parse,\n * which re-interprets the same \"12:00\" through the current process zone.\n * Honest scope: within ONE process at a stable timezone the two forms are\n * equivalent — offsets cancel (the cross-review measured oldDelta ===\n * newDelta under UTC / +08:00 / America/New_York), and the observed \"+08:00\n * archived, retried under UTC\" double-archive is actually fixed by the\n * single-sided window in appendArchiveLines, which reads a foreign-zone\n * re-render as a before-`now` (future-stamp) retry. What the component form\n * buys over Date.parse is the DST boundary above: wall math exposes the\n * shifted gap that epoch math hides, and the DST grace turns it back into a\n * retry instead of a double-archive. */\nfunction completionStamp(e: LedgerEntry): number {\n const [y, mo, d] = e.date.split('-').map(Number);\n const [h, mi] = e.time.split(':').map(Number);\n return Date.UTC(y!, mo! - 1, d!, h!, mi!);\n}\n\n/** The `now` side of the same comparison, in the same component space: a wall\n * stamp may only be measured against another wall stamp, never against an\n * epoch whose local rendering shifts with the timezone. */\nfunction localWallStamp(now: number): number {\n const d = new Date(now);\n return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes());\n}\n\n/** Why a done line was judged already-archived instead of appended. The\n * wall-clock grace carries a self-describing name: it exists for DST shifts\n * but swallows ANY same-id+text retry within the extended wall window, so\n * `retry-window-extended`, not `dst-grace` (N16② review). */\nexport type ArchiveDedupeReason = 'same-stamp' | 'retry-window' | 'retry-window-extended' | 'future-stamp';\n/** `date`/`time` are the matched ARCHIVE row's own stamp — the audit uses them\n * to locate the swallowed line, since the retried completion carries a fresh\n * minute (N16② review 低4). */\nexport type ArchiveDedupeSink = (info: { id: string; reason: ArchiveDedupeReason; date: string; time: string }) => void;\n\n/** One parser for every book and every archive - a line is a line, whichever\n * file it lives in. Returns null for headers, blank lines and hand edits. */\nexport function parseLedgerLine(line: string): LedgerEntry | null {\n const m = LINE_RE.exec(line);\n if (!m) return null;\n return { date: m[1]!, time: m[2]!, status: m[3] as 'open' | 'done', id: m[4]!, text: m[5]! };\n}\n\nexport function readLedger(guard: PathGuard, file: string, header = LEDGER_HEADER): { header: string; entries: LedgerEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, header);\n const lines = raw.split('\\n');\n const entries: LedgerEntry[] = [];\n const rawLines: string[] = [];\n for (const line of lines) {\n const e = parseLedgerLine(line);\n if (e) entries.push(e);\n rawLines.push(line);\n }\n return { header: lines[0] ?? header, entries, rawLines };\n}\n\n/** Seed a book/archive header only when the file does not exist yet. Exclusive\n * creation via the atomic-fs helper (AGENTS.md #1), never \"exists? then\n * write\": a live markDone may have created the file with header+rows between\n * the check and the write, and the old pattern overwrote that first\n * completion. EEXIST means someone else owns it. */\nexport function seedBookFile(guard: PathGuard, file: string, header: string): void {\n try {\n atomicCreateFileSync(guard.assert(file), header);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;\n }\n}\n\nexport function appendEntry(guard: PathGuard, file: string, text: string, now = Date.now(), header = LEDGER_HEADER): LedgerEntry {\n const textTrimmed = text.trim();\n if (!textTrimmed) throw new Error('ledger entry must not be empty');\n return withFileLock(file, () => {\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const entry: LedgerEntry = {\n id: randomUUID().slice(0, 6),\n date: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,\n time: `${pad(d.getHours())}:${pad(d.getMinutes())}`,\n status: 'open',\n text: textTrimmed.replace(/\\r?\\n/g, ' '),\n };\n const { rawLines } = readLedger(guard, file, header);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n });\n}\n\n/** Append rows to an archive, skipping completions already present. A done\n * row dedupes when id+text+status agree AND either the stamps are identical\n * (migration replays lines verbatim, whatever their age) or the archived\n * stamp is within RETRY_WINDOW_MS of `now` — extended by RETRY_WALL_GRACE_MS\n * on the late side (DST wall shifts), and bounded to FUTURE_GRACE_MS on the\n * future side so a skewed stamp cannot swallow real completions forever\n * (N16③④). Same id+text completed again weeks later is a real second\n * completion and IS appended.\n * Unknown/hand-written lines still dedupe verbatim.\n * `onDedupe` (N16①) reports each skipped line with the reason it matched, so\n * callers can audit a swallowed completion.\n * This is what makes \"append then remove\" retry-safe: a crash between the two\n * writes leaves the row open in the book, and the retry must not double the\n * archive line. */\nexport function appendArchiveLines(\n guard: PathGuard,\n file: string,\n header: string,\n lines: string[],\n now = Date.now(),\n onDedupe?: ArchiveDedupeSink,\n): number {\n if (lines.length === 0) return 0;\n const { rawLines, entries } = readLedger(guard, file, header);\n const rawSeen = new Set(rawLines);\n const archived = entries.filter((e) => e.status === 'done');\n const nowWall = localWallStamp(now);\n const fresh = lines.filter((line) => {\n const e = parseLedgerLine(line);\n if (!e) {\n if (rawSeen.has(line)) return false;\n rawSeen.add(line);\n return true;\n }\n const stamp = completionStamp(e);\n // N16③: the window is SINGLE-SIDED. Math.abs judged a FUTURE-stamped row\n // (hand edit, clock skew, cross-timezone re-render) far from `now` as a\n // NEW completion and double-archived it; `now - stamp <= WINDOW` reads any\n // stamp at-or-after `now` (negative delta) as a retry instead — bounded by\n // FUTURE_GRACE_MS so the archive self-heals past a skewed stamp (N16④).\n let hit: { id: string; reason: ArchiveDedupeReason; date: string; time: string } | null = null;\n for (const x of archived) {\n if (x.id !== e.id || x.text !== e.text || x.status !== e.status) continue;\n const stampX = completionStamp(x);\n if (stampX === stamp) {\n hit = { id: e.id, reason: 'same-stamp', date: x.date, time: x.time };\n break;\n }\n const delta = nowWall - stampX;\n if (delta < 0) {\n if (delta >= -FUTURE_GRACE_MS) {\n hit = { id: e.id, reason: 'future-stamp', date: x.date, time: x.time };\n break;\n }\n continue; // skewed beyond the grace: this is a NEW completion\n }\n if (delta <= RETRY_WINDOW_MS) {\n hit = { id: e.id, reason: 'retry-window', date: x.date, time: x.time };\n break;\n }\n if (delta <= RETRY_WINDOW_MS + RETRY_WALL_GRACE_MS) {\n hit = { id: e.id, reason: 'retry-window-extended', date: x.date, time: x.time };\n break;\n }\n }\n if (hit) {\n onDedupe?.(hit);\n return false;\n }\n archived.push(e);\n return true;\n });\n if (fresh.length === 0) return 0;\n const out = rawLines.concat(fresh);\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return fresh.length;\n}\n\n/** Mark an entry done by id (preferred) or unique text substring. 2.3.0:\n * the row is REMOVED from the book and appended to its archive in the same\n * line format, so both a human reading the book and the weekly report (which\n * reads the archive) see the completion. The done date is restamped to the\n * completion day so weekly reporting can count \"resolved this week\".\n *\n * The book is a whole-file rewrite and the CLI is a second process against\n * it, so read→archive→write runs under the book's file lock (H-20): two\n * interleaved cycles would otherwise let one side silently drop the other's\n * write, and a stale snapshot could even resurrect a row just marked done.\n *\n * N16①: when the archive dedupes the line (same stamp, retry window, the\n * extended wall grace or a future-stamped row), the completion still leaves\n * the book but is NOT appended — callers that can audit pass a sink and get a\n * `book_done_deduped` record. The audit fires only AFTER the book rewrite\n * succeeded: a failed rewrite leaves the row in the book (nothing was\n * swallowed) and a crash before it means the retry redoes the whole cycle.\n * Hand-written ids can carry personal text (`#家人的生日`), so only the\n * plugin-generated 6-hex ids enter the audit log; the archive file name\n * locates the row either way. Row text is never audited. */\nexport type LedgerAuditSink = (entry: Record<string, unknown>) => void;\n\nconst HEX_ID_RE = /^[0-9a-f]{6}$/;\n\nexport function markDone(\n guard: PathGuard,\n file: string,\n key: string,\n now = Date.now(),\n doneFile = doneFilePathFor(file),\n doneHeader = doneHeaderFor(file),\n audit?: LedgerAuditSink,\n): LedgerEntry | null {\n return withFileLock(file, () => {\n const { rawLines, entries } = readLedger(guard, file);\n const target = entries.find((e) => e.status === 'open' && (e.id === key || e.text.includes(key)));\n if (!target) return null;\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const doneDate = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n const doneTime = `${pad(d.getHours())}:${pad(d.getMinutes())}`;\n // Only rows that ARE this entry (same id AND text, still open) are摘走.\n // A hand note that merely mentions `#abc123] ` or another row reusing the\n // id with different text is not this completion and stays in the book.\n const isTargetRow = (line: string): boolean => {\n const e = parseLedgerLine(line);\n return e !== null && e.status === 'open' && e.id === target.id && e.text === target.text;\n };\n // Exactly ONE row is removed: two byte-identical rows are two entries, and\n // removing both while archiving one would lose the other (the migration\n // conservation invariant applies here too).\n const targetIndex = rawLines.findIndex(isTargetRow);\n const doneLine = renderEntry({\n ...parseLedgerLine(rawLines[targetIndex]!)!,\n status: 'done',\n date: doneDate,\n time: doneTime,\n });\n // Archive first: a crash between the writes leaves the row visible (still\n // open) instead of losing it; appendArchiveLines dedupes the retry even\n // when the retry restamps the minute. A dedupe hit with nothing appended\n // means this completion was already archived — audited below (N16①).\n let dedupeHits: { id: string; reason: ArchiveDedupeReason; date: string; time: string }[] = [];\n const appended = appendArchiveLines(guard, doneFile, doneHeader, [doneLine], now, (info) => {\n dedupeHits.push(info);\n });\n const out = rawLines.filter((_, i) => i !== targetIndex);\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n // Audit AFTER the rewrite succeeded: a failed rewrite leaves the row in\n // the book, and then nothing was swallowed — recording it would log a\n // dedupe that never happened, and every crash retry would re-log it.\n if (appended === 0 && dedupeHits.length > 0) {\n const hit = dedupeHits[0]!;\n audit?.({\n event: 'book_done_deduped',\n // Hand-written ids may carry personal text; only generated 6-hex ids\n // are audited (the archive file name locates the row regardless).\n ...(HEX_ID_RE.test(target.id) ? { id: target.id } : {}),\n archive: path.basename(doneFile),\n // The matched archive row's OWN stamp locates the swallowed line; the\n // done stamp below is this retry's fresh minute, useless for finding\n // the row it deduped against (N16② review 低4).\n rowDate: hit.date,\n rowTime: hit.time,\n doneDate,\n doneTime,\n reason: hit.reason,\n });\n }\n return target;\n });\n}\n\n/** Open items for the reflection digest (§7.6 账本待办). */\nexport function scanPending(guard: PathGuard, file: string, now = Date.now()): LedgerEntry[] {\n const { entries } = readLedger(guard, file);\n return entries.filter((e) => e.status === 'open').sort((a, b) => (a.date < b.date ? -1 : 1));\n}\n\n/** Open entries older than N days (跟进时机的\"自然到期\"参考,§3.1 四问之一). */\nexport function pendingOlderThan(guard: PathGuard, file: string, days: number, now = Date.now()): LedgerEntry[] {\n const cutoff = localDayKey(new Date(now - days * DAY_MS));\n return scanPending(guard, file, now).filter((e) => e.date <= cutoff);\n}\n","// Topic preference (2026-10-06): consumption-driven bias for wander focus\n// selection. The persona's seed_report attributions (and the engine-room\n// fallback) fold into per-topic delivered/adopted counters; pickFocus reads\n// the smoothed rate as a weight on top of round-robin recency.\n//\n// Anti-lockdown guarantees (user-reviewed design):\n// - weight clamped to [W_MIN, W_MAX] — a favorite doubles at most, a cold\n// topic never drops below half;\n// - Laplace smoothing — a topic with no data sits near neutral, not zero;\n// - exponential decay (30-day half-life) — old glory fades;\n// - pickFocus additionally enforces a hard starvation floor (14 days).\n//\n// Storage is one JSON file through the vault (DPAPI): topic keys derive from\n// the user's profile/interests, so they are user-adjacent data.\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\n\nconst DAY_MS = 86_400_000;\n\nexport const W_MIN = 0.5;\nexport const W_MAX = 2;\n/** Laplace prior: rate = (adopted + A) / (delivered + D). Neutral ≈ A/D. */\nexport const SMOOTH_ADOPTED = 1;\nexport const SMOOTH_DELIVERED = 4;\n/** Counts decay with this half-life (days) since the topic's last activity. */\nexport const DECAY_HALF_LIFE_DAYS = 30;\n\nexport interface TopicPref {\n delivered: number;\n adopted: number;\n lastDeliveredAt: number;\n lastAdoptedAt: number;\n}\n\nexport interface PrefState {\n version: 1;\n topics: Record<string, TopicPref>;\n updatedAt: number;\n}\n\nexport function preferenceFilePath(dataDir: string): string {\n return path.join(dataDir, 'preference.json');\n}\n\n/** Non-negative finite number or 0 (v1.9.0 guard against hand-edited files). */\nfunction num(v: unknown): number {\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 ? n : 0;\n}\n\n/** One stored entry → a trustworthy counter. Returns null for a garbled entry:\n * a NaN delivered/adopted used to survive the load and poison the whole\n * ordering (NaN makes every comparison false, so the topic neither aged nor\n * sorted). Dropping the entry is the safe read — the loop refills it. */\nfunction sanitizeTopicPref(raw: unknown): TopicPref | null {\n if (!raw || typeof raw !== 'object') return null;\n const t = raw as Partial<TopicPref>;\n if (!Number.isFinite(Number(t.delivered)) || !Number.isFinite(Number(t.adopted))) return null;\n const delivered = Math.floor(num(t.delivered));\n return {\n delivered,\n adopted: Math.min(delivered, Math.floor(num(t.adopted))),\n lastDeliveredAt: num(t.lastDeliveredAt),\n lastAdoptedAt: num(t.lastAdoptedAt),\n };\n}\n\nexport function loadPreference(guard: PathGuard, file: string): PrefState {\n const doc = loadJson<Partial<PrefState>>(guard, file);\n if (!doc || typeof doc !== 'object' || !doc.topics || typeof doc.topics !== 'object') {\n return { version: 1, topics: {}, updatedAt: 0 };\n }\n const topics: Record<string, TopicPref> = {};\n for (const [key, raw] of Object.entries(doc.topics)) {\n const t = sanitizeTopicPref(raw);\n if (key && t) topics[key] = t;\n }\n const updatedAt = Number(doc.updatedAt);\n return { version: 1, topics, updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0 };\n}\n\nexport function savePreference(guard: PathGuard, file: string, state: PrefState): void {\n saveJson(guard, file, state);\n}\n\n/** Fold one delivery into the counters. offeredTopics = every topic in the\n * package; adoptedTopics = the credited ones (subset by construction — unknown\n * keys are still tolerated so the two lists can drift safely). */\nexport function recordDelivery(\n guard: PathGuard,\n file: string,\n opts: { offeredTopics: string[]; adoptedTopics: string[]; now: number },\n): PrefState {\n const state = loadPreference(guard, file);\n const adopted = new Set(opts.adoptedTopics);\n for (const topic of opts.offeredTopics) {\n if (!topic) continue;\n const t = state.topics[topic] ?? { delivered: 0, adopted: 0, lastDeliveredAt: 0, lastAdoptedAt: 0 };\n t.delivered += 1;\n t.lastDeliveredAt = opts.now;\n if (adopted.has(topic)) {\n t.adopted += 1;\n t.lastAdoptedAt = opts.now;\n }\n state.topics[topic] = t;\n }\n state.updatedAt = opts.now;\n savePreference(guard, file, state);\n return state;\n}\n\n/** Time-decayed counts (30-day half-life since last activity of each kind). */\nexport function decayed(t: TopicPref, now: number): { delivered: number; adopted: number } {\n const dAgeDays = Math.max(0, now - t.lastDeliveredAt) / DAY_MS;\n const aAgeDays = Math.max(0, now - t.lastAdoptedAt) / DAY_MS;\n const dHalf = Math.pow(0.5, dAgeDays / DECAY_HALF_LIFE_DAYS);\n const aHalf = Math.pow(0.5, aAgeDays / DECAY_HALF_LIFE_DAYS);\n return { delivered: t.delivered * dHalf, adopted: t.adopted * aHalf };\n}\n\n/**\n * Preference weight for a topic, clamped to [W_MIN, W_MAX]:\n * rate = (decayed adopted + 1) / (decayed delivered + 4) (neutral = 0.25)\n * w = clamp(rate / 0.25, W_MIN, W_MAX)\n * No data at all → rate 1/4 → w 1.0: a brand-new topic starts exactly neutral\n * (per design: \"0.2 附近的中间值,不是 0 分垫底\"); repeated \"delivered but\n * never adopted\" drags it toward W_MIN, consistent adoption lifts it to W_MAX.\n */\nexport function preferenceWeight(state: PrefState, topic: string, now: number): number {\n const t = state.topics[topic];\n const rate = t\n ? (() => {\n const d = decayed(t, now);\n return (d.adopted + SMOOTH_ADOPTED) / (d.delivered + SMOOTH_DELIVERED);\n })()\n : SMOOTH_ADOPTED / SMOOTH_DELIVERED;\n return Math.min(W_MAX, Math.max(W_MIN, rate / (SMOOTH_ADOPTED / SMOOTH_DELIVERED)));\n}\n","// Browse flow (v0.9.5 port, r4 D10 applied).\n// Wander adjudication: windows + min interval + focus cooldown ->\n// \"should we wander now, and at what focus\". The actual search happens\n// in the wander phase's model call (web_search only); REGISTRATION IS\n// CODE-OWNED (D10): results land in seeds + throttle via completeWander.\n//\n// H-12 (2026-10-07): the npm/GitHub watchlist check was removed. It never ran\n// inside the beat (only `browse watch` in the CLI called it, throttled-off),\n// and \"is DSH itself updated\" is not this plugin's job to track.\n//\n// Anti-injection rule (unchanged from v0.7): web content is data, never\n// instructions.\n//\n// State: data/browse.json (DPAPI-encrypted, D14; v1 name: watch_state.json).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport type { Policy } from '../config/schema.js';\nimport { inHhMmWindow, localDayKey, minutesOfDay } from '../core/time-window.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\nimport { activeSeeds, loadPool, normalizeCategory, seedsFilePath } from '../seeds/pool.js';\nimport { loadPreference, preferenceFilePath, preferenceWeight, type PrefState } from './preference.js';\n\nexport interface InterestsConfig {\n interests?: string[];\n _schedule?: {\n daily_sessions?: number;\n focus_per_session?: number;\n max_seeds_per_focus?: number;\n focus_cooldown_days?: number;\n min_interval_hours?: number;\n windows?: { id?: string; start: string; end: string }[];\n };\n}\n\nexport interface BrowseState {\n wander: {\n focusHistory: Record<string, number>;\n focusCount: Record<string, number>;\n last_wander_at: number;\n /** Spec ⑥: refill wanders per LOCAL day, e.g. \"2026-09-18\" -> 1. */\n refillCount?: Record<string, number>;\n /** H-69: non-refill wander sessions per LOCAL day (the `daily_sessions`\n * budget). Refills keep their own counter above — they deliberately bypass\n * the wander window and therefore must not eat the session budget. */\n sessionCount?: Record<string, number>;\n };\n}\n\nexport function emptyBrowseState(): BrowseState {\n return { wander: { focusHistory: {}, focusCount: {}, last_wander_at: 0, refillCount: {}, sessionCount: {} } };\n}\n\nexport function browseStatePath(paths: WorkspacePaths): string {\n return path.join(paths.dataDir, 'browse.json');\n}\n\nfunction readJsonFile<T>(file: string, fallback: T): T {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as T;\n } catch {\n return fallback;\n }\n}\n\n/** Factory configs are read-only; a user layer with the same filename replaces them. */\nexport function loadInterests(paths: WorkspacePaths): InterestsConfig {\n const userPath = path.join(paths.settingsDir, 'interests.json');\n if (fs.existsSync(userPath)) return readJsonFile<InterestsConfig>(userPath, { interests: [], _schedule: {} });\n return readJsonFile<InterestsConfig>(path.join(paths.configDir, 'interests.json'), { interests: [], _schedule: {} });\n}\n\n/**\n * H-65: the state file outlives upgrades and is hand-inspectable, so a row\n * missing a field must not throw its way into a `beat_error` on every beat.\n * Garbage values are dropped back to the empty-state defaults.\n */\nexport function normalizeBrowseState(raw: unknown): BrowseState {\n const out = emptyBrowseState();\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Partial<BrowseState>;\n const w = (r.wander && typeof r.wander === 'object' ? r.wander : {}) as Partial<BrowseState['wander']>;\n out.wander.focusHistory = numberRecord(w.focusHistory);\n out.wander.focusCount = numberRecord(w.focusCount);\n out.wander.refillCount = numberRecord(w.refillCount);\n out.wander.sessionCount = numberRecord(w.sessionCount);\n if (typeof w.last_wander_at === 'number' && Number.isFinite(w.last_wander_at)) out.wander.last_wander_at = w.last_wander_at;\n return out;\n}\n\nfunction numberRecord(v: unknown): Record<string, number> {\n const out: Record<string, number> = {};\n if (!v || typeof v !== 'object' || Array.isArray(v)) return out;\n for (const [k, n] of Object.entries(v as Record<string, unknown>)) {\n if (typeof n === 'number' && Number.isFinite(n)) out[k] = n;\n }\n return out;\n}\n\nfunction loadState(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return normalizeBrowseState(loadJson<unknown>(guard, browseStatePath(paths)));\n}\n\n// ── B. wander adjudication (pure-ish, state injected) ───────────────────\n\nexport interface WanderAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n /** H-69: focuses this session was allowed to examine (`focus_per_session`);\n * `focus` is the first of them. The phase still runs one model turn per\n * focus, so >1 only widens the candidate list the caller may use. */\n candidates?: string[];\n /** H-69: per-focus seed cap (`max_seeds_per_focus`, defaulting to\n * `policy.browse.maxSeedsPerVisit`). The registration loop reads this. */\n maxSeeds?: number;\n}\n\nexport interface WanderSchedule {\n windows: { start: string; end: string }[];\n minIntervalHours: number;\n maxSeedsPerFocus: number;\n /** Wander sessions per local day; 0 = no daily cap. */\n dailySessions: number;\n focusPerSession: number;\n focusCooldownDays: number;\n}\n\n/**\n * H-69 (2026-10-07): `interests._schedule` is the block the settings card edits\n * and, as the user layer, it REPLACES the factory copy — so it wins wherever it\n * overlaps `policy.browse`, which is the compiled-in default. Every key here\n * has a reader now; `min_interval_hours`, `max_seeds_per_focus` and\n * `daily_sessions` used to be dead wiring whose factory values happened to\n * match policy's, which is exactly why nobody noticed they did nothing.\n */\nexport function resolveSchedule(interests: InterestsConfig, policy: Policy): WanderSchedule {\n const sc = interests._schedule ?? {};\n return {\n windows: sc.windows?.length ? sc.windows : (policy.browse.windows as { start: string; end: string }[]),\n minIntervalHours: sc.min_interval_hours ?? policy.browse.minIntervalHours,\n maxSeedsPerFocus: sc.max_seeds_per_focus ?? policy.browse.maxSeedsPerVisit,\n dailySessions: sc.daily_sessions ?? 0,\n focusPerSession: Math.max(1, sc.focus_per_session ?? 1),\n focusCooldownDays: sc.focus_cooldown_days ?? 3,\n };\n}\n\nexport function inWanderWindow(now: Date, windows: { start: string; end: string }[]): string | null {\n const mins = minutesOfDay(now);\n for (const w of windows) {\n if (inHhMmWindow(w.start, w.end, mins)) return `${w.start}-${w.end}`;\n }\n return null;\n}\n\nfunction onCooldown(state: BrowseState, focus: string, cooldownDays: number, now: number): boolean {\n const last = state.wander.focusHistory[focus] ?? 0;\n return last > now - cooldownDays * 86_400_000;\n}\n\n/**\n * Focus pick (2026-10-06): round-robin recency as the base, preference rate as\n * a multiplier. Ordering key = effective age = realAgeSinceLastUse × weight —\n * a favorite's age \"grows\" faster, so it reaches the pick threshold sooner and\n * is wandered up to W_MAX times as often. Lockdown-proof by construction:\n * - cooldown (above) keeps every topic rotating no matter the weight;\n * - weight lives in [W_MIN, W_MAX] (preference.ts);\n * - hard starvation floor: any topic untouched ≥ STARVATION_DAYS ignores\n * weighting entirely and the oldest real age wins.\n * Without a preference state the behavior is exactly the old pure LRU.\n */\nexport const STARVATION_DAYS = 14;\n\nexport function pickFocus(\n state: BrowseState,\n interests: InterestsConfig,\n now: number,\n pref?: PrefState,\n): string | null {\n const sc = interests._schedule ?? {};\n const cooldown = sc.focus_cooldown_days ?? 3;\n const pool = (interests.interests ?? []).filter((t) => !onCooldown(state, t, cooldown, now));\n if (pool.length === 0) return null;\n if (!pref) {\n pool.sort((a, b) => (state.wander.focusHistory[a] ?? 0) - (state.wander.focusHistory[b] ?? 0));\n return pool[0]!;\n }\n const age = (t: string): number => now - (state.wander.focusHistory[t] ?? 0);\n const starved = pool.filter((t) => age(t) >= STARVATION_DAYS * 86_400_000);\n if (starved.length > 0) {\n starved.sort((a, b) => age(b) - age(a)); // oldest real age wins\n return starved[0]!;\n }\n const effAge = (t: string): number => age(t) * preferenceWeight(pref, t, now);\n pool.sort((a, b) => effAge(b) - effAge(a));\n return pool[0]!;\n}\n\n/** Adjudicate: windows + min interval + focus cooldown -> advice | skipped. */\nexport function adviseWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): WanderAdvice {\n const state = loadState(guard, paths);\n const interests = loadInterests(paths);\n const sched = resolveSchedule(interests, policy);\n const budget = { maxSeeds: sched.maxSeedsPerFocus };\n const win = inWanderWindow(now, sched.windows);\n if (!win) {\n const hh = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;\n return { focus: null, query: null, skipped: `window(now=${hh})`, ...budget };\n }\n // H-69: `daily_sessions` — same LOCAL-day budget shape as the refill quota.\n const today = localDayKey(now);\n const sessionsToday = state.wander.sessionCount?.[today] ?? 0;\n if (sched.dailySessions > 0 && sessionsToday >= sched.dailySessions) {\n return { focus: null, query: null, skipped: `daily-sessions(${sessionsToday})`, ...budget };\n }\n const minGap = sched.minIntervalHours * 3600_000;\n if (now.getTime() - state.wander.last_wander_at < minGap) {\n return { focus: null, query: null, skipped: 'min-interval', ...budget };\n }\n // H-69: `focus_per_session` candidates, drawn without replacement so one\n // session never offers the same focus twice.\n const pref = loadPreference(guard, preferenceFilePath(paths.dataDir));\n const pool = interests.interests ?? [];\n const candidates: string[] = [];\n for (let i = 0; i < sched.focusPerSession; i++) {\n const rest = pool.filter((t) => !candidates.includes(t));\n if (rest.length === 0) break;\n const picked = pickFocus(state, { ...interests, interests: rest }, now.getTime(), pref);\n if (!picked) break;\n candidates.push(picked);\n }\n if (candidates.length === 0) return { focus: null, query: null, skipped: 'no-focus', ...budget };\n // 低优先级 review (2026-10-17): the year in the query was hardcoded to 2026,\n // which silently ages the search results as the calendar moves on.\n const year = now.getFullYear();\n return { focus: candidates[0]!, query: `${candidates[0]!} ${year} 最新`, skipped: null, candidates, ...budget };\n}\n\n/**\n * Registration is CODE-OWNED (D10): called by the orchestrator after the\n * wander phase's model call returned selections. Records cooldown/count/\n * throttle timestamps for the focus. `refill` additionally bumps the daily\n * refill counter (spec ⑥).\n */\nexport function completeWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n focus: string,\n now = Date.now(),\n opts: { refill?: boolean } = {},\n): { focus: string; count: number; refillsToday?: number } {\n const state = loadState(guard, paths);\n state.wander.focusHistory[focus] = now;\n state.wander.focusCount[focus] = (state.wander.focusCount[focus] ?? 0) + 1;\n state.wander.last_wander_at = now;\n if (!opts.refill) {\n // H-69: count this session against the `daily_sessions` budget. Refills\n // are their own channel (they deliberately bypass the window and the min\n // interval) and stay on refillCount alone.\n const day = localDayKey(new Date(now));\n state.wander.sessionCount = state.wander.sessionCount ?? {};\n state.wander.sessionCount[day] = (state.wander.sessionCount[day] ?? 0) + 1;\n }\n let refillsToday: number | undefined;\n if (opts.refill) {\n const today = localDayKey(new Date(now));\n state.wander.refillCount = state.wander.refillCount ?? {};\n state.wander.refillCount[today] = (state.wander.refillCount[today] ?? 0) + 1;\n refillsToday = state.wander.refillCount[today];\n }\n saveJson(guard, browseStatePath(paths), state);\n return { focus, count: state.wander.focusCount[focus]!, ...(refillsToday === undefined ? {} : { refillsToday }) };\n}\n\n// ── C. refill wander (spec ⑥, 2026-09-18): top up topic stock when it runs\n// dry. Independent of the window/minInterval gates (user decision: may stack\n// with a normal wander in the same beat) but still respects the 3-day focus\n// cooldown, and is capped at REFILL_MAX_PER_DAY per local day.\n\nexport const REFILL_TOPIC_THRESHOLD = 4;\nexport const REFILL_MAX_PER_DAY = 2;\n\nexport interface RefillAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n topicCount: number;\n refillsToday: number;\n}\n\nexport function adviseRefillWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): RefillAdvice {\n const state = loadState(guard, paths);\n const today = localDayKey(now);\n const refillsToday = state.wander.refillCount?.[today] ?? 0;\n const topicCount = activeSeeds(loadPool(guard, seedsFilePath(paths.dataDir)))\n .filter((s) => normalizeCategory(s.category) === 'topic').length;\n if (refillsToday >= REFILL_MAX_PER_DAY) {\n return { focus: null, query: null, skipped: `refill-daily-cap(${refillsToday})`, topicCount, refillsToday };\n }\n if (topicCount > REFILL_TOPIC_THRESHOLD) {\n return { focus: null, query: null, skipped: `topic-stock-ok(${topicCount})`, topicCount, refillsToday };\n }\n const interests = loadInterests(paths);\n const focus = pickFocus(state, interests, now.getTime(), loadPreference(guard, preferenceFilePath(paths.dataDir))); // 3-day cooldown still applies\n if (!focus) {\n return { focus: null, query: null, skipped: 'no-focus', topicCount, refillsToday };\n }\n return { focus, query: `${focus} 2026 最新`, skipped: null, topicCount, refillsToday };\n}\n\nexport function browseStatus(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return loadState(guard, paths);\n}\n","// Windows toast channel (D12): attention hint ONLY - never carries the\n// expression body. Wraps assets/notify.ps1 (self-registering AUMID).\n\nimport path from 'node:path';\nimport { runPowerShellFile } from '../core/ps.js';\nimport type { WorkspacePaths } from '../core/paths.js';\n\nasync function runNotify(paths: WorkspacePaths, args: string[]): Promise<{ status: number; out: string }> {\n const r = await runPowerShellFile(path.join(paths.assetsDir, 'notify.ps1'), args, 20_000);\n return { status: r.status, out: `${r.stdout}${r.stderr}`.trim() };\n}\n\n/** Register the toast identity if missing (idempotent, per machine/user). */\nexport async function ensureRegistered(paths: WorkspacePaths): Promise<boolean> {\n const check = await runNotify(paths, ['-Check']);\n if (/REGISTERED: yes/.test(check.out)) return true;\n const reg = await runNotify(paths, ['-RegisterOnly']);\n return reg.status === 0;\n}\n\n/**\n * Fire the \"new message\" hint. Fixed neutral text per D12 - the actual\n * expression lives in the dedicated heartbeat session, never in the toast.\n */\nexport async function sendNewMessageHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', 'Heartbeat', '-Message', '有新消息']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n\n/** Weekly report ready hint (v1.8.0): same D12 discipline — announces that a\n * report exists, never carries its content. */\nexport async function sendWeeklyReadyHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', '心跳周报', '-Message', '本期周报已生成']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n","/**\n * H-10: asynchronous PowerShell runner.\n *\n * The probes (idle seconds, front window, screen capture, toasts) used\n * `spawnSync`, which blocks the host's event loop for as long as the script\n * runs — 10s to 45s on a slow machine, and the GUI stalls with it. Same\n * arguments, same timeouts, same \"never throw, degrade instead\" contract, but\n * the loop stays free while the child runs.\n */\nimport { execFile } from 'node:child_process';\n\nexport interface PsResult {\n status: number;\n stdout: string;\n stderr: string;\n}\n\n/** Run `powershell.exe` and resolve with its exit code and streams. Never\n * rejects: a spawn failure and a non-zero exit both come back as `status !== 0`\n * so callers keep their existing \"probe failed\" paths.\n *\n * ⑤A (2026-10-17 review, HB-08): the optional signal is the beat's cancellation\n * handle. A cancelled probe kills the child and resolves like any other failed\n * probe (`status !== 0`, stderr 'aborted') — callers already degrade on that,\n * and the \"never rejects\" contract stays intact. */\nexport function runPowerShell(args: string[], timeoutMs: number, signal?: AbortSignal): Promise<PsResult> {\n if (signal?.aborted) return Promise.resolve({ status: 1, stdout: '', stderr: 'aborted' });\n // v2.1.0: every caller of this module is a Windows-only probe (idle seconds,\n // foreground window, toasts, screen capture). Off Windows there is no binary\n // to spawn, so answer \"probe failed\" immediately — same degradation the\n // callers already implement, without paying a spawn attempt per beat.\n if (process.platform !== 'win32') {\n return Promise.resolve({ status: 1, stdout: '', stderr: `powershell unavailable on ${process.platform}` });\n }\n return new Promise((resolve) => {\n let settled = false;\n const done = (r: PsResult): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener('abort', onAbort);\n resolve(r);\n };\n const onAbort = (): void => {\n try { child.kill(); } catch { /* already gone */ }\n done({ status: 1, stdout: '', stderr: 'aborted' });\n };\n const child = execFile(\n 'powershell.exe',\n ['-NoProfile', '-ExecutionPolicy', 'Bypass', ...args],\n { timeout: timeoutMs, encoding: 'utf8', windowsHide: true },\n (err, stdout, stderr) => {\n const code = (err as { code?: unknown } | null)?.code;\n const status = err ? (typeof code === 'number' ? code : 1) : 0;\n done({ status, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });\n },\n );\n child.on('error', () => { /* surfaced through the callback above */ });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** Convenience for the `-File <script>` shape used by every asset script. */\nexport function runPowerShellFile(script: string, args: string[], timeoutMs: number, signal?: AbortSignal): Promise<PsResult> {\n return runPowerShell(['-File', script, ...args], timeoutMs, signal);\n}\n","// Weekly report store + writer helpers (v1.8.0). Deliberately host-free:\n// orchestration (when to run, which agent, toast) lives in the orchestrator —\n// same split as profile/consolidate.ts. Reports are DPAPI-encrypted because a\n// report contains user-identifying content (profile adds, ledger texts) —\n// same划线标准 as profile/seeds (design doc §10.5).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { workspace } from '../core/paths.js';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { WeeklyFacts } from './collect.js';\n\nexport const WEEKLY_INTERVAL_MS = 7 * 86_400_000;\n\nexport interface WeeklyReport {\n start: string;\n end: string;\n generatedAt: string;\n /** 'llm' = engine-room prose; 'template' = deterministic fallback. */\n source: 'llm' | 'template';\n text: string;\n}\n\nexport function weeklyDirPath(dataDir: string): string {\n return path.join(dataDir, 'weekly');\n}\n\nfunction stateFilePath(dataDir: string): string {\n return path.join(weeklyDirPath(dataDir), 'state.json');\n}\n\nfunction reportFileName(endIso: string): string {\n return `report-${endIso.slice(0, 10)}.json`;\n}\n\n/**\n * Last generation time from the weekly state file; 0 = never anchored.\n *\n * H-54: \"missing\" and \"present but unparseable\" are NOT the same thing. The\n * old code folded both into 0, so `ensureWeeklyAnchor` \"repaired\" a corrupt\n * file by stamping NOW — silently, and at the cost of pushing the next report\n * a full interval out. A corrupt anchor now keeps its file, writes an audit\n * line, and falls back to the file's mtime so the schedule keeps its place.\n */\nexport function lastWeeklyGeneratedAt(guard: PathGuard, dataDir: string): number {\n const file = stateFilePath(dataDir);\n let raw: string;\n try {\n raw = fs.readFileSync(guard.assert(file), 'utf8');\n } catch {\n return 0; // absent: a fresh install, legitimately never anchored\n }\n try {\n const parsed = JSON.parse(raw) as { lastGeneratedAt?: number };\n const n = Number(parsed.lastGeneratedAt);\n if (Number.isFinite(n) && n > 0) return n;\n } catch {\n /* unparseable — handled by the fallback below */\n }\n try {\n appendAuditLine(path.join(workspace().logsDir, 'heartbeat.jsonl'), {\n event: 'weekly_anchor_corrupt',\n file: path.basename(file),\n bytes: Buffer.byteLength(raw),\n });\n } catch {\n /* audit is diagnostic; never let it break the schedule */\n }\n try {\n return fs.statSync(file).mtimeMs;\n } catch {\n return 0;\n }\n}\n\n/** Due when the last report is ≥7 days old. A never-anchored store lands on\n * the install-time anchor (see ensureWeeklyAnchor), so a fresh install is NOT\n * due — the first report arrives one full interval after installation. */\nexport function weeklyDue(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n const last = lastWeeklyGeneratedAt(guard, dataDir);\n return now - last >= WEEKLY_INTERVAL_MS;\n}\n\n/** Stamp the install-time anchor for a store that has never generated a report\n * (v1.9.0). Returns true when it wrote — the caller audits that. Without this,\n * `lastGeneratedAt = 0` made the very first maintenance beat due, so a fresh\n * install produced an \"onboarding\" report immediately, contradicting the\n * release notes (\"first report after a week\"). */\nexport function ensureWeeklyAnchor(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n if (lastWeeklyGeneratedAt(guard, dataDir) > 0) return false;\n fs.mkdirSync(weeklyDirPath(dataDir), { recursive: true });\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: now });\n return true;\n}\n\n/** Persist a report (DPAPI) and stamp the state file. */\nexport function saveWeeklyReport(guard: PathGuard, dataDir: string, report: WeeklyReport): string {\n const dir = weeklyDirPath(dataDir);\n fs.mkdirSync(dir, { recursive: true });\n const file = path.join(dir, reportFileName(report.end));\n saveEncryptedText(guard, file, JSON.stringify(report, null, 1));\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: Date.parse(report.generatedAt) });\n return file;\n}\n\nexport interface WeeklyReportMeta {\n file: string;\n start: string;\n end: string;\n generatedAt: string;\n source: string;\n}\n\n/** Newest-first listing for the card; unparsable entries are skipped.\n * v2.0 (item 5): an optional `limit` shows only the newest N reports. */\nexport function listWeeklyReports(guard: PathGuard, dataDir: string, limit?: number): WeeklyReportMeta[] {\n const out: WeeklyReportMeta[] = [];\n try {\n for (const file of fs.readdirSync(weeklyDirPath(dataDir))) {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) continue;\n const rep = readWeeklyReport(guard, dataDir, file);\n if (!rep) continue;\n out.push({ file, start: rep.start, end: rep.end, generatedAt: rep.generatedAt, source: rep.source });\n }\n } catch { /* no weekly dir yet */ }\n const sorted = out.sort((a, b) => (a.end < b.end ? 1 : -1));\n return limit !== undefined && limit > 0 ? sorted.slice(0, limit) : sorted;\n}\n\n/**\n * v2.0 (item 5): delete every report beyond the newest `keep`, so the card's\n * report buttons cannot crowd the panel and the store cannot grow unbounded.\n * `keep <= 0` disables pruning (and the policy schema forbids it anyway).\n * Returns the deleted file names so the caller can audit them; a report that\n * cannot be deleted is left in place (best effort — never break the beat).\n */\nexport function pruneWeeklyReports(guard: PathGuard, dataDir: string, keep: number): string[] {\n if (!Number.isFinite(keep) || keep <= 0) return [];\n const removed: string[] = [];\n for (const meta of listWeeklyReports(guard, dataDir).slice(keep)) {\n try {\n fs.rmSync(guard.assert(path.join(weeklyDirPath(dataDir), meta.file)));\n removed.push(meta.file);\n } catch { /* best effort */ }\n }\n return removed;\n}\n\nexport function readWeeklyReport(guard: PathGuard, dataDir: string, file: string): WeeklyReport | null {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) return null; // guard.assert would reject ../ anyway\n try {\n const raw = loadEncryptedText(guard, path.join(weeklyDirPath(dataDir), file));\n if (!raw) return null;\n const rep = JSON.parse(raw) as WeeklyReport;\n if (typeof rep.text !== 'string') return null;\n return rep;\n } catch {\n return null;\n }\n}\n\n/** The engine-room prompt: neutral system narrator, fact-bound, ≤250 chars. */\nexport function buildWeeklyPrompt(facts: WeeklyFacts): string {\n return [\n '你是心跳插件的后台报告器。根据下面的本周事实清单,用中文写一份周报正文。',\n '规则:',\n '- 叙述者自称「心跳」——这是插件后台,不是任何会话里的 agent;绝不能以会话 agent 的身份或人格自称。',\n '- 只报告事实清单里有的内容;某一节没有数据就整节跳过,不要编造、不要凑数。',\n '- 语气平实中性,不用感叹号;篇幅不超过 250 字。',\n '- 待办积压那一节用商量的语气提一句,不催促。',\n '- 直接输出周报正文,不要输出解释、标题或 JSON。',\n '',\n '本周事实(JSON):',\n JSON.stringify(facts, null, 1),\n ].join('\\n');\n}\n\n/** Deterministic fallback: the facts, plainly stated. Used when the LLM turn\n * fails or comes back empty — a plain report beats no report. */\nexport function renderTemplateReport(facts: WeeklyFacts): string {\n const d = (iso: string): string => iso.slice(0, 10);\n const lines: string[] = [`本周(${d(facts.windowStart)} ~ ${d(facts.windowEnd)})`];\n lines.push(`表达 ${facts.spoken} 次,静默 ${facts.silent} 次。`);\n if (facts.silentTopReasons.length > 0) {\n lines.push(`静默主因:${facts.silentTopReasons.map((r) => `${r.reason}(${r.count})`).join('、')}。`);\n }\n if (facts.profileAdds.length > 0) {\n lines.push(`新认识 ${facts.profileAdds.length} 条:${facts.profileAdds.map((a) => a.content).join(';')}。`);\n }\n if (facts.ledger.added.length > 0 || facts.ledger.done.length > 0) {\n const parts: string[] = [];\n if (facts.ledger.added.length > 0) parts.push(`新增待办:${facts.ledger.added.join('、')}`);\n if (facts.ledger.done.length > 0) parts.push(`已解决:${facts.ledger.done.join('、')}`);\n lines.push(`${parts.join(';')}。`);\n }\n if (facts.ledger.stale.length > 0) {\n lines.push(`挂了很久:${facts.ledger.stale.map((s) => `${s.text}(${s.days} 天)`).join('、')}——要删掉还是继续挂着?`);\n }\n if (facts.seeds.added.length > 0) {\n lines.push(`素材池新增 ${facts.seeds.added.length} 条,已消费 ${facts.seeds.consumed.length} 条。`);\n }\n if (facts.seeds.waiting.length > 0) {\n lines.push(`还没聊过的素材:${facts.seeds.waiting.join('、')}。`);\n }\n if (facts.reports.total > 0) {\n const reasonPart = facts.reports.reasons.length > 0\n ? `(${facts.reports.reasons.map((r) => `${r.reason} ${r.count} 次`).join('、')})`\n : '';\n lines.push(`投递报账 ${facts.reports.total} 次:用素材 ${facts.reports.material}、说真心话 ${facts.reports.heartfelt}、没说话 ${facts.reports.silent}${reasonPart}。`);\n }\n // v1.9.0: unaccounted deliveries are reported even when no report landed at\n // all — a silent rise in \"no report\" is exactly what would otherwise hide.\n if (facts.reports.missing > 0) {\n lines.push(`另有 ${facts.reports.missing} 次投递没等到报账(这部分没算进偏好统计)。`);\n }\n if (facts.peakHours.length > 0) {\n lines.push(`活跃高峰:${facts.peakHours.join('、')}。`);\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIA,OAAO,UAAU;;;AC8CV,SAAS,cAAsB;AACpC,SAAO,EAAE,KAAK,GAAG,OAAO,CAAC,EAAE;AAC7B;AAEO,IAAM,iCAA6D;AAAA,EACxE,MAAM;AAAA,EACN,SAAS;AAAA,EACT,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AACZ;;;ADzCA,IAAM,SAAS;AAUf,IAAM,WAAwB,MAAM;AAAC;AAGrC,SAAS,KAAK,OAAoB,OAAsC;AACtE,MAAI;AACF,UAAM,KAAK;AAAA,EACb,QAAQ;AAAA,EAER;AACF;AAIO,IAAM,qBAAmD,EAAE,OAAO,IAAI,MAAM,GAAG;AAO/E,IAAM,mBAAwD,EAAE,UAAU,EAAE;AAEnF,IAAM,kBAAqC,CAAC,SAAS,MAAM;AAIpD,SAAS,kBAAkB,GAA0B;AAC1D,SAAO,OAAO,MAAM,YAAa,gBAAsC,SAAS,CAAC,IAC5E,IACD;AACN;AAgCO,IAAM,4BAA4B;AACzC,IAAM,0BAA0B,KAAK;AACrC,IAAM,oBAAoB;AAM1B,IAAM,0BAA0B;AAIzB,SAAS,kBAAkB,GAAmB;AACnD,SAAO,EACJ,UAAU,MAAM,EAChB,YAAY,EACZ,QAAQ,qBAAqB,EAAE;AACpC;AAKO,SAAS,eAAe,GAAW,GAAmB;AAC3D,QAAM,KAAK,kBAAkB,CAAC;AAC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