@kanadego/dsh-heartbeat 2.0.1 → 2.1.1

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.
Files changed (50) hide show
  1. package/README.md +82 -57
  2. package/client.js +500 -125
  3. package/config/interests.json +1 -1
  4. package/config/policy.json +3 -2
  5. package/dist/{chunk-TVX4HV4Y.js → chunk-63E5OYSI.js} +56 -5
  6. package/dist/chunk-63E5OYSI.js.map +1 -0
  7. package/dist/{chunk-NCPKOWS7.js → chunk-AT32XCCI.js} +2 -2
  8. package/dist/{chunk-DC5HMCJC.js → chunk-DLOYERAK.js} +3 -3
  9. package/dist/{chunk-544QOJN5.js → chunk-ECXYNTEV.js} +2 -2
  10. package/dist/{chunk-IFRMKVIC.js → chunk-HE6IF6OU.js} +5 -2
  11. package/dist/chunk-HE6IF6OU.js.map +1 -0
  12. package/dist/{chunk-DZ7YCFGX.js → chunk-KZLVR4J7.js} +2 -2
  13. package/dist/{chunk-6XM6KY7M.js → chunk-LPPRI53J.js} +39 -37
  14. package/dist/chunk-LPPRI53J.js.map +1 -0
  15. package/dist/chunk-LQKOYTRL.js +59 -0
  16. package/dist/chunk-LQKOYTRL.js.map +1 -0
  17. package/dist/{chunk-AKIJ4LS2.js → chunk-M72T5MZU.js} +44 -1
  18. package/dist/chunk-M72T5MZU.js.map +1 -0
  19. package/dist/{chunk-6MVKWICX.js → chunk-XCMGPIUQ.js} +99 -23
  20. package/dist/chunk-XCMGPIUQ.js.map +1 -0
  21. package/dist/cli/index.js +51 -11
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/focus-store-RNHBAFYS.js +20 -0
  24. package/dist/{inbox-OWBK6PE2.js → inbox-ZLX2MH7A.js} +3 -3
  25. package/dist/index.d.ts +16 -3
  26. package/dist/index.js +119 -69
  27. package/dist/index.js.map +1 -1
  28. package/dist/{migrate-TQ5PB2DI.js → migrate-XFZU5EBE.js} +3 -3
  29. package/dist/{orchestrator-P7AEWVYR.js → orchestrator-MNFCPH43.js} +27 -8
  30. package/dist/{pool-2T6TVS2L.js → pool-MAABBHC4.js} +9 -3
  31. package/dist/{snapshot-F5B2DD56.js → snapshot-SU2VGM4C.js} +4 -4
  32. package/dist/snapshot-SU2VGM4C.js.map +1 -0
  33. package/icon.svg +11 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +11 -6
  37. package/dist/chunk-6MVKWICX.js.map +0 -1
  38. package/dist/chunk-6XM6KY7M.js.map +0 -1
  39. package/dist/chunk-AKIJ4LS2.js.map +0 -1
  40. package/dist/chunk-IFRMKVIC.js.map +0 -1
  41. package/dist/chunk-TVX4HV4Y.js.map +0 -1
  42. /package/dist/{chunk-NCPKOWS7.js.map → chunk-AT32XCCI.js.map} +0 -0
  43. /package/dist/{chunk-DC5HMCJC.js.map → chunk-DLOYERAK.js.map} +0 -0
  44. /package/dist/{chunk-544QOJN5.js.map → chunk-ECXYNTEV.js.map} +0 -0
  45. /package/dist/{chunk-DZ7YCFGX.js.map → chunk-KZLVR4J7.js.map} +0 -0
  46. /package/dist/{inbox-OWBK6PE2.js.map → focus-store-RNHBAFYS.js.map} +0 -0
  47. /package/dist/{migrate-TQ5PB2DI.js.map → inbox-ZLX2MH7A.js.map} +0 -0
  48. /package/dist/{orchestrator-P7AEWVYR.js.map → migrate-XFZU5EBE.js.map} +0 -0
  49. /package/dist/{pool-2T6TVS2L.js.map → orchestrator-MNFCPH43.js.map} +0 -0
  50. /package/dist/{snapshot-F5B2DD56.js.map → pool-MAABBHC4.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/time-window.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":["// 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","// 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\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';\n\nconst DAY_MS = 86_400_000;\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// 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\nexport function readLedger(guard: PathGuard, file: string): { header: string; entries: LedgerEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, '# 账本\\n');\n const lines = raw.split('\\n');\n const entries: LedgerEntry[] = [];\n const rawLines: string[] = [];\n for (const line of lines) {\n const m = LINE_RE.exec(line);\n if (m) {\n entries.push({ date: m[1]!, time: m[2]!, status: m[3] as 'open' | 'done', id: m[4]!, text: m[5]! });\n }\n rawLines.push(line);\n }\n return { header: lines[0] ?? '# 账本', entries, rawLines };\n}\n\nexport function appendEntry(guard: PathGuard, file: string, text: string, now = Date.now()): LedgerEntry {\n const textTrimmed = text.trim();\n if (!textTrimmed) throw new Error('ledger entry must not be empty');\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);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n}\n\n/** Mark an entry done by id (preferred) or unique text substring. The date is\n * restamped to the completion day (time was already) so weekly reporting can\n * count \"resolved this week\" — the creation timestamp lives on in nothing,\n * but done entries are rarely aged against. */\nexport function markDone(guard: PathGuard, file: string, key: string, now = Date.now()): LedgerEntry | null {\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 out = rawLines.map((line) => {\n if (line.includes(`#${target.id}] `)) {\n return `- [${doneDate} ${pad(d.getHours())}:${pad(d.getMinutes())}][done][#${target.id}] ${target.text}`;\n }\n return line;\n });\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return target;\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":";;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAM,QAAQ;AAGP,SAAS,UAAU,MAA6B;AACrD,QAAM,IAAI,MAAM,KAAK,OAAO,IAAI,EAAE,KAAK,CAAC;AACxC,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,IAAI,OAAO,EAAE,CAAC,CAAC;AACrB,QAAM,MAAM,OAAO,EAAE,CAAC,CAAC;AACvB,MAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,GAAG,KAAK,IAAI,MAAM,MAAM,GAAI,QAAO;AAC/E,SAAO,IAAI,KAAK;AAClB;AAEO,SAAS,aAAa,KAAmB;AAC9C,SAAO,IAAI,SAAS,IAAI,KAAK,IAAI,WAAW;AAC9C;AAGO,SAAS,aAAa,OAAe,KAAa,MAAuB;AAC9E,QAAM,IAAI,UAAU,KAAK;AACzB,QAAM,IAAI,UAAU,GAAG;AACvB,MAAI,MAAM,QAAQ,MAAM,KAAM,QAAO;AACrC,MAAI,MAAM,EAAG,QAAO;AACpB,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AK,IAAI;AACxB;","names":["path","DAY_MS","path","path","path","path","path","fs","path","path","fs"]}
@@ -0,0 +1,59 @@
1
+ import {
2
+ atomicWriteJsonSync
3
+ } from "./chunk-IBBAISSW.js";
4
+
5
+ // src/core/focus-store.ts
6
+ import fs from "fs";
7
+ import path from "path";
8
+ var FOCUS_MIN_MINUTES = 1;
9
+ var FOCUS_MAX_MINUTES = 1440;
10
+ function focusStatePath(paths) {
11
+ return path.join(paths.dataDir, "focus.json");
12
+ }
13
+ function readFocusState(guard, paths, now = Date.now()) {
14
+ try {
15
+ const raw = fs.readFileSync(guard.assert(focusStatePath(paths)), "utf8");
16
+ const parsed = JSON.parse(raw);
17
+ const until = Number(parsed.until);
18
+ if (!Number.isFinite(until) || until <= now) return null;
19
+ return {
20
+ until,
21
+ minutes: Number(parsed.minutes) || 0,
22
+ since: Number(parsed.since) || 0,
23
+ via: String(parsed.via ?? "unknown")
24
+ };
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ function writeFocusState(guard, paths, minutes, now = Date.now(), via = "cli") {
30
+ const m = Math.max(FOCUS_MIN_MINUTES, Math.min(FOCUS_MAX_MINUTES, Math.floor(minutes)));
31
+ const state = { until: now + m * 6e4, minutes: m, since: now, via };
32
+ atomicWriteJsonSync(guard.assert(focusStatePath(paths)), state);
33
+ return state;
34
+ }
35
+ function clearFocusState(guard, paths) {
36
+ try {
37
+ const file = guard.assert(focusStatePath(paths));
38
+ if (!fs.existsSync(file)) return false;
39
+ fs.rmSync(file, { force: true });
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ function resolveFocusUntil(guard, paths, memoryUntil, now = Date.now()) {
46
+ const file = readFocusState(guard, paths, now)?.until ?? 0;
47
+ return Math.max(memoryUntil > now ? memoryUntil : 0, file);
48
+ }
49
+
50
+ export {
51
+ FOCUS_MIN_MINUTES,
52
+ FOCUS_MAX_MINUTES,
53
+ focusStatePath,
54
+ readFocusState,
55
+ writeFocusState,
56
+ clearFocusState,
57
+ resolveFocusUntil
58
+ };
59
+ //# sourceMappingURL=chunk-LQKOYTRL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/focus-store.ts"],"sourcesContent":["// Focus-mode persistence (v2.1.0 ①).\n//\n// THE BUG THIS FILE EXISTS FOR: `pauseFocus()`/resumeFocus()` are module state,\n// and the operational CLI runs as its OWN process (`node dist/cli/index.js`),\n// so a pause set there never reached the host's orchestrator. The pause now\n// lives in `data/focus.json`: the CLI writes it, the host reads it at the top\n// of every beat, and the RPC/settings-card path keeps both copies in sync\n// (module state = immediate, file = cross-process and survives a restart).\n//\n// The file is deliberately NOT cleared at startup: a pause that outlives a\n// restart is what a debugging session actually wants, and the status line\n// always names the lift time (\"专注模式 · 至 HH:MM\"), so it is never invisible.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from './path-guard.js';\nimport type { WorkspacePaths } from './paths.js';\nimport { atomicWriteJsonSync } from './atomic-fs.js';\n\nexport interface FocusState {\n /** Epoch ms when the pause lifts. */\n until: number;\n /** Requested minutes (clamped 1-1440). */\n minutes: number;\n /** Epoch ms when it was set. */\n since: number;\n /** Who set it: 'cli' | 'rpc' | 'settings-card' | ... */\n via: string;\n}\n\nexport const FOCUS_MIN_MINUTES = 1;\nexport const FOCUS_MAX_MINUTES = 1440;\n\nexport function focusStatePath(paths: WorkspacePaths): string {\n return path.join(paths.dataDir, 'focus.json');\n}\n\n/** The pause as stored on disk, or null when absent / malformed / already expired. */\nexport function readFocusState(guard: PathGuard, paths: WorkspacePaths, now = Date.now()): FocusState | null {\n try {\n const raw = fs.readFileSync(guard.assert(focusStatePath(paths)), 'utf8');\n const parsed = JSON.parse(raw) as Partial<FocusState>;\n const until = Number(parsed.until);\n if (!Number.isFinite(until) || until <= now) return null;\n return {\n until,\n minutes: Number(parsed.minutes) || 0,\n since: Number(parsed.since) || 0,\n via: String(parsed.via ?? 'unknown'),\n };\n } catch {\n return null; // missing, unparsable, or outside the guard: \"no pause\"\n }\n}\n\nexport function writeFocusState(\n guard: PathGuard,\n paths: WorkspacePaths,\n minutes: number,\n now = Date.now(),\n via = 'cli',\n): FocusState {\n const m = Math.max(FOCUS_MIN_MINUTES, Math.min(FOCUS_MAX_MINUTES, Math.floor(minutes)));\n const state: FocusState = { until: now + m * 60_000, minutes: m, since: now, via };\n atomicWriteJsonSync(guard.assert(focusStatePath(paths)), state);\n return state;\n}\n\n/** Lift the on-disk pause; true when a file was actually removed. */\nexport function clearFocusState(guard: PathGuard, paths: WorkspacePaths): boolean {\n try {\n const file = guard.assert(focusStatePath(paths));\n if (!fs.existsSync(file)) return false;\n fs.rmSync(file, { force: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The effective pause instant for a beat: the OR of module state and disk.\n * A beat that starts before this returns considers itself paused. */\nexport function resolveFocusUntil(guard: PathGuard, paths: WorkspacePaths, memoryUntil: number, now = Date.now()): number {\n const file = readFocusState(guard, paths, now)?.until ?? 0;\n return Math.max(memoryUntil > now ? memoryUntil : 0, file);\n}\n"],"mappings":";;;;;AAaA,OAAO,QAAQ;AACf,OAAO,UAAU;AAgBV,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAE1B,SAAS,eAAe,OAA+B;AAC5D,SAAO,KAAK,KAAK,MAAM,SAAS,YAAY;AAC9C;AAGO,SAAS,eAAe,OAAkB,OAAuB,MAAM,KAAK,IAAI,GAAsB;AAC3G,MAAI;AACF,UAAM,MAAM,GAAG,aAAa,MAAM,OAAO,eAAe,KAAK,CAAC,GAAG,MAAM;AACvE,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,UAAM,QAAQ,OAAO,OAAO,KAAK;AACjC,QAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,IAAK,QAAO;AACpD,WAAO;AAAA,MACL;AAAA,MACA,SAAS,OAAO,OAAO,OAAO,KAAK;AAAA,MACnC,OAAO,OAAO,OAAO,KAAK,KAAK;AAAA,MAC/B,KAAK,OAAO,OAAO,OAAO,SAAS;AAAA,IACrC;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,gBACd,OACA,OACA,SACA,MAAM,KAAK,IAAI,GACf,MAAM,OACM;AACZ,QAAM,IAAI,KAAK,IAAI,mBAAmB,KAAK,IAAI,mBAAmB,KAAK,MAAM,OAAO,CAAC,CAAC;AACtF,QAAM,QAAoB,EAAE,OAAO,MAAM,IAAI,KAAQ,SAAS,GAAG,OAAO,KAAK,IAAI;AACjF,sBAAoB,MAAM,OAAO,eAAe,KAAK,CAAC,GAAG,KAAK;AAC9D,SAAO;AACT;AAGO,SAAS,gBAAgB,OAAkB,OAAgC;AAChF,MAAI;AACF,UAAM,OAAO,MAAM,OAAO,eAAe,KAAK,CAAC;AAC/C,QAAI,CAAC,GAAG,WAAW,IAAI,EAAG,QAAO;AACjC,OAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;AAC/B,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIO,SAAS,kBAAkB,OAAkB,OAAuB,aAAqB,MAAM,KAAK,IAAI,GAAW;AACxH,QAAM,OAAO,eAAe,OAAO,OAAO,GAAG,GAAG,SAAS;AACzD,SAAO,KAAK,IAAI,cAAc,MAAM,cAAc,GAAG,IAAI;AAC3D;","names":[]}
@@ -381,6 +381,13 @@ var V2_AAD = Buffer.concat([MAGIC_V22, Buffer.from([V2_VERSION])]);
381
381
  var KEY_BYTES = 32;
382
382
  var KEY_FILE_NAME = "vault.key";
383
383
  var VAULT_TIMEOUT_MS = 3e4;
384
+ var platformOverride = null;
385
+ function vaultPlatform() {
386
+ return platformOverride ?? process.platform;
387
+ }
388
+ function dpapiAvailable() {
389
+ return vaultPlatform() === "win32";
390
+ }
384
391
  var cachedScriptPath = null;
385
392
  function vaultScriptPath() {
386
393
  if (cachedScriptPath) return cachedScriptPath;
@@ -396,6 +403,11 @@ function tmpEncName(target) {
396
403
  return path4.join(workspace().tmpDir, `.${path4.basename(target)}.${randomUUID().slice(0, 8)}.enc`);
397
404
  }
398
405
  function runVault(guard, args) {
406
+ if (!dpapiAvailable()) {
407
+ throw new Error(
408
+ `vault: ${args[0]} needs Windows DPAPI, which ${vaultPlatform()} does not have \u2014 KHBV1 containers are Windows-only and heartbeat data does not migrate across platforms`
409
+ );
410
+ }
399
411
  const r = spawnSync(
400
412
  "powershell.exe",
401
413
  ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", vaultScriptPath(), ...args],
@@ -483,6 +495,18 @@ function decodeKeyFile(guard, file) {
483
495
  `vault: ${file} is an AES container, but the master key cannot be stored AES-encrypted \u2014 restore it from a backup or re-import the data`
484
496
  );
485
497
  }
498
+ if (!dpapiAvailable()) {
499
+ if (kind === "v1") {
500
+ throw new Error(
501
+ `vault: ${file} is a DPAPI (KHBV1) container \u2014 the master key was created on Windows and cannot be unwrapped on ${vaultPlatform()}; heartbeat data does not migrate across platforms, so start a fresh data dir here`
502
+ );
503
+ }
504
+ const key = fs5.readFileSync(file);
505
+ if (key.length !== KEY_BYTES) {
506
+ throw new Error(`vault: master key has ${key.length} bytes, expected ${KEY_BYTES}`);
507
+ }
508
+ return key;
509
+ }
486
510
  if (kind !== "v1") throw new Error(`vault: ${file} is not a DPAPI container (not a usable master key)`);
487
511
  const tmp = tmpPlainName(file);
488
512
  try {
@@ -496,6 +520,20 @@ function decodeKeyFile(guard, file) {
496
520
  burnFileSync(tmp);
497
521
  }
498
522
  }
523
+ function publishPlainKeyFile(file, key) {
524
+ const tmp = tmpPlainName(file);
525
+ try {
526
+ fs5.writeFileSync(tmp, key, { mode: 384 });
527
+ if (!fs5.readFileSync(tmp).equals(key)) throw new Error("vault: master key round-trip mismatch");
528
+ fs5.renameSync(tmp, file);
529
+ try {
530
+ fs5.chmodSync(file, 384);
531
+ } catch {
532
+ }
533
+ } finally {
534
+ burnFileSync(tmp);
535
+ }
536
+ }
499
537
  function masterKey(guard) {
500
538
  if (cachedMasterKey) return cachedMasterKey;
501
539
  sweepVaultScratch();
@@ -509,6 +547,11 @@ function masterKey(guard) {
509
547
  try {
510
548
  created = withFileLock(file, () => {
511
549
  if (fs5.existsSync(file)) return null;
550
+ if (!dpapiAvailable()) {
551
+ const key = randomBytes(KEY_BYTES);
552
+ publishPlainKeyFile(file, key);
553
+ return key;
554
+ }
512
555
  const plain = tmpPlainName(file);
513
556
  const enc = tmpEncName(file);
514
557
  try {
@@ -677,4 +720,4 @@ export {
677
720
  upgradeVaultTree,
678
721
  upgradeOneLegacyVaultFile
679
722
  };
680
- //# sourceMappingURL=chunk-AKIJ4LS2.js.map
723
+ //# sourceMappingURL=chunk-M72T5MZU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/paths.ts","../src/core/data-relocate.ts","../src/core/file-lock.ts","../src/core/fs-walk.ts","../src/vault/vault.ts"],"sourcesContent":["// Workspace/data directory resolution and package asset location.\n//\n// The data dir is the ONLY directory the plugin writes to at runtime\n// (requirement 8). Resolution order: env override > plugin config > default\n// (`$DSH_HOME/heartbeat-data`) — with a legacy fallback to `packageRoot()/data`\n// for installs that predate v1.9.2, which is relocated out of the package on\n// first sight (issue #2: a reinstall replaced the package dir and took the\n// user's data with it). All fs writes must go through the path guard created\n// from this dir (see core/path-guard.ts).\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { hasPayload, relocateDataDir, type RelocateResult } from './data-relocate.js';\n\nexport interface WorkspacePaths {\n /** Guard boundary and the only writable tree at runtime. */\n dataDir: string;\n settingsDir: string;\n logsDir: string;\n tmpDir: string;\n exportsDir: string;\n /** Package root (where package.json lives). Read-only at runtime. */\n packageRoot: string;\n configDir: string;\n assetsDir: string;\n /**\n * Set only when a legacy package-local data dir was found: the outcome of\n * the one-time relocation. Absent for explicit dirs and fresh installs.\n */\n relocation?: RelocateResult;\n}\n\nexport interface WorkspaceConfigInput {\n dataDir?: string | null;\n}\n\nlet resolved: WorkspacePaths | null = null;\n\n/** Walk up from a module file to the directory containing package.json. */\nexport function findPackageRoot(startFile: string): string {\n let dir = path.dirname(path.resolve(startFile));\n for (;;) {\n if (fs.existsSync(path.join(dir, 'package.json'))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error('package.json not found above ' + startFile);\n dir = parent;\n }\n}\n\nexport function packageRoot(): string {\n return findPackageRoot(fileURLToPath(import.meta.url));\n}\n\n/**\n * Default data dir: `$DSH_HOME/heartbeat-data` (or `~/.dsh/heartbeat-data`).\n * Deliberately outside the package tree — reinstalling or upgrading the plugin\n * replaces that directory and must not touch user data (issue #2).\n */\nexport function defaultDataDir(\n env: NodeJS.ProcessEnv = process.env,\n home: string = os.homedir(),\n): string {\n return path.join(dshHomeDir(env, home), 'heartbeat-data');\n}\n\n/**\n * The DSH home: `$DSH_HOME` when set, else `~/.dsh`.\n *\n * HB-20 (2026-10-17): this is the ONLY place that computes it. Callers used to\n * hard-code `path.join(os.homedir(), '.dsh')`, which silently ignored the\n * `$DSH_HOME` override — a relocated host got its sessions/storages read from\n * the wrong tree (and, for the data dir, wrote to the wrong one).\n */\nexport function dshHomeDir(\n env: NodeJS.ProcessEnv = process.env,\n home: string = os.homedir(),\n): string {\n const override = env.DSH_HOME?.trim();\n return override && override.length > 0 ? override : path.join(home, '.dsh');\n}\n\n/**\n * Resolve and create the workspace layout. Idempotent; must be called once\n * from the plugin entry before any fs write happens.\n */\nexport function initWorkspace(config: WorkspaceConfigInput = {}): WorkspacePaths {\n if (resolved) return resolved;\n const root = packageRoot();\n const explicit = process.env.HEARTBEAT_DATA_DIR || config.dataDir;\n const homeDir = path.resolve(defaultDataDir());\n const legacyDir = path.join(root, 'data');\n let dataDir: string;\n let relocation: RelocateResult | undefined;\n if (explicit) {\n // Explicit configuration always wins, and never moves anything.\n dataDir = path.resolve(explicit);\n } else if (hasPayload(homeDir)) {\n // Already on the new home (a previous run, or a reinstall that kept it).\n dataDir = homeDir;\n } else if (hasPayload(legacyDir)) {\n // Pre-v1.9.2 install: the data lived inside the package. Move it out, and\n // keep serving the legacy tree unless the move verified end to end.\n relocation = relocateDataDir({ srcDir: legacyDir, dstDir: homeDir });\n dataDir = relocation.action === 'relocated' ? homeDir : legacyDir;\n } else {\n dataDir = homeDir;\n }\n const paths: WorkspacePaths = {\n dataDir,\n settingsDir: path.join(dataDir, 'settings'),\n logsDir: path.join(dataDir, 'logs'),\n tmpDir: path.join(dataDir, 'tmp'),\n exportsDir: path.join(dataDir, 'exports'),\n packageRoot: root,\n configDir: path.join(root, 'config'),\n assetsDir: path.join(root, 'assets'),\n ...(relocation ? { relocation } : {}),\n };\n // Bootstrap creation happens before the guard exists; creating exactly one\n // directory tree at a known location is the safe window for this.\n for (const dir of [\n paths.dataDir,\n paths.settingsDir,\n paths.logsDir,\n paths.tmpDir,\n paths.exportsDir,\n ]) {\n fs.mkdirSync(dir, { recursive: true });\n }\n resolved = paths;\n return paths;\n}\n\n/** Access already-initialized paths. Throws if initWorkspace was not called. */\nexport function workspace(): WorkspacePaths {\n if (!resolved) throw new Error('workspace not initialized: call initWorkspace() first');\n return resolved;\n}\n\n/** Test-only: forget the resolved singleton so a later init re-resolves. */\nexport function resetWorkspaceForTest(): void {\n resolved = null;\n}\n","// One-time relocation of the data dir out of the package tree (issue #2).\n//\n// Installs created before v1.9.2 defaulted to `packageRoot()/data`, and every\n// `dsh plugin add` / upgrade replaces the package directory wholesale — so a\n// reinstall deleted the profile, the gate and the ledger, which the original\n// design meant to keep until an explicit CLI `burn`. The default now lives at\n// `$DSH_HOME/heartbeat-data`; this module moves an existing package-local tree\n// there.\n//\n// Safety order — a failure at any point leaves the original untouched:\n// 1. copy src -> backup (kept until the move is verified and committed)\n// 2. copy src -> dst.staging-<stamp>\n// 3. verify staging against src: same file list, same size + sha256, and\n// every plaintext .json/.jsonl still parses\n// 4. rename staging -> dst (same volume, atomic)\n// 5. only then delete src and the backup\n// The caller keeps using `src` unless the result is `relocated`.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { createHash } from 'node:crypto';\n\n/** Directories the bootstrap always creates: their presence alone is no payload. */\nconst SKELETON_DIRS = ['settings', 'logs', 'tmp', 'exports'];\n/** Scratch space (decrypt windows, downloads): never copied, never verified. */\nconst SCRATCH_DIR = 'tmp';\nconst MAGIC_V1 = Buffer.from('KHBV1', 'ascii');\nconst MAGIC_V2 = Buffer.from('KHBV2', 'ascii');\n\nexport interface RelocateOptions {\n srcDir: string;\n dstDir: string;\n /** Injectable clock, so tests get deterministic backup/staging names. */\n now?: number;\n}\n\nexport type RelocateResult =\n | {\n action: 'relocated';\n /** Package-local tree the data came from (now deleted). */\n srcDir: string;\n dstDir: string;\n backupDir: string;\n files: number;\n bytes: number;\n /** Plaintext JSON/JSONL that does not parse (verified byte-identical). */\n warnings: string[];\n /** Paths that could not be deleted after the move (cosmetic leftovers). */\n leftovers: string[];\n }\n | { action: 'skipped'; reason: 'source-missing' | 'no-payload' | 'destination-exists' }\n | {\n action: 'failed';\n stage: 'backup' | 'copy' | 'verify' | 'commit';\n problems: string[];\n /** Null when the backup itself could not be created. */\n backupDir: string | null;\n };\n\nexport interface VerifyResult {\n /** Byte-for-byte the same file list, sizes and contents. */\n ok: boolean;\n files: number;\n bytes: number;\n problems: string[];\n /**\n * Plaintext JSON/JSONL files that do not parse. They are reported but do not\n * fail the move: an identical copy of a file that was already damaged is\n * still byte-for-byte the user's data, and refusing to relocate would strand\n * the data dir in the package forever.\n */\n warnings: string[];\n}\n\n/**\n * True when a data dir holds real user data. An empty bootstrap skeleton\n * (`settings/ logs/ tmp/ exports/`, all empty) does not count — otherwise a\n * freshly created default dir would shadow a legacy tree with actual data.\n */\nexport function hasPayload(dir: string): boolean {\n if (!fs.existsSync(dir)) return false;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) return true;\n if (!SKELETON_DIRS.includes(entry.name)) return true;\n if (entry.name === SCRATCH_DIR) continue;\n if (fs.readdirSync(path.join(dir, entry.name)).length > 0) return true;\n }\n return false;\n}\n\n/** Every file under `dir` (relative, `/`-separated, sorted), excluding tmp/. */\nfunction walk(dir: string, prefix = '', out: string[] = []): string[] {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!prefix && entry.name === SCRATCH_DIR) continue;\n walk(path.join(dir, entry.name), rel, out);\n } else if (entry.isFile()) {\n out.push(rel);\n }\n }\n return out.sort();\n}\n\nfunction copyTree(src: string, dst: string): void {\n const scratch = path.resolve(path.join(src, SCRATCH_DIR));\n fs.cpSync(src, dst, {\n recursive: true,\n force: true,\n preserveTimestamps: true,\n filter: (from) => path.resolve(from) !== scratch,\n });\n}\n\nfunction removeTree(dir: string): void {\n fs.rmSync(dir, { recursive: true, force: true });\n}\n\nfunction sha256(file: string): string {\n return createHash('sha256').update(fs.readFileSync(file)).digest('hex');\n}\n\n/**\n * Encrypted-container header check (local copy: importing vault here would\n * cycle through paths). Both generations count: KHBV1 is the DPAPI legacy\n * container, KHBV2 the AES-GCM one v2.0 writes.\n */\nfunction isEncryptedFile(file: string): boolean {\n const fd = fs.openSync(file, 'r');\n try {\n const head = Buffer.alloc(MAGIC_V2.length);\n const read = fs.readSync(fd, head, 0, head.length, 0);\n if (read === MAGIC_V1.length && head.subarray(0, MAGIC_V1.length).equals(MAGIC_V1)) return true;\n return read === MAGIC_V2.length && head.equals(MAGIC_V2);\n } finally {\n fs.closeSync(fd);\n }\n}\n\n/**\n * Schema-free readability check: an encrypted container is opaque here (its\n * bytes were already compared by hash), a plaintext .json/.jsonl must still\n * parse — that is what catches a half-written or truncated copy.\n */\nfunction parsesAsJson(file: string): boolean {\n if (isEncryptedFile(file)) return true;\n const text = fs.readFileSync(file, 'utf8');\n try {\n if (file.endsWith('.jsonl')) {\n for (const line of text.split('\\n')) if (line.trim()) JSON.parse(line);\n return true;\n }\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Compare a copy against its source: identical file list, identical size and\n * content (the hard gate), plus a readability report on the plaintext\n * JSON/JSONL in the copy (warnings only — see VerifyResult).\n */\nexport function verifyTrees(srcDir: string, dstDir: string): VerifyResult {\n const problems: string[] = [];\n const warnings: string[] = [];\n let files = 0;\n let bytes = 0;\n if (!fs.existsSync(dstDir)) {\n return { ok: false, files: 0, bytes: 0, problems: [`copy missing: ${dstDir}`], warnings };\n }\n const expected = walk(srcDir);\n const actual = walk(dstDir);\n const actualSet = new Set(actual);\n const expectedSet = new Set(expected);\n for (const rel of expected) if (!actualSet.has(rel)) problems.push(`missing: ${rel}`);\n for (const rel of actual) if (!expectedSet.has(rel)) problems.push(`unexpected: ${rel}`);\n for (const rel of expected) {\n const from = path.join(srcDir, rel);\n const to = path.join(dstDir, rel);\n if (!fs.existsSync(to)) continue; // already reported above\n const sizeFrom = fs.statSync(from).size;\n const sizeTo = fs.statSync(to).size;\n files += 1;\n bytes += sizeFrom;\n if (sizeFrom !== sizeTo) {\n problems.push(`size differs: ${rel} (${sizeFrom} -> ${sizeTo})`);\n continue;\n }\n if (sha256(from) !== sha256(to)) {\n problems.push(`content differs: ${rel}`);\n continue;\n }\n if (/\\.(json|jsonl)$/i.test(rel) && !parsesAsJson(to)) warnings.push(`unparseable: ${rel}`);\n }\n return { ok: problems.length === 0, files, bytes, problems, warnings };\n}\n\nfunction stamp(now: number): string {\n const d = new Date(now);\n const pad = (n: number): string => String(n).padStart(2, '0');\n return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Move a package-local data dir to its new home. Never throws: every failure\n * is reported as `failed` with the original tree left in place.\n */\nexport function relocateDataDir(opts: RelocateOptions): RelocateResult {\n const srcDir = path.resolve(opts.srcDir);\n const dstDir = path.resolve(opts.dstDir);\n if (!fs.existsSync(srcDir)) return { action: 'skipped', reason: 'source-missing' };\n if (!hasPayload(srcDir)) return { action: 'skipped', reason: 'no-payload' };\n if (hasPayload(dstDir)) return { action: 'skipped', reason: 'destination-exists' };\n\n const suffix = stamp(opts.now ?? Date.now());\n const backupDir = `${srcDir}.bak-relocate-${suffix}`;\n const stagingDir = `${dstDir}.staging-${suffix}`;\n\n // 1. backup first — the user asked for a copy that outlives a failed move.\n try {\n copyTree(srcDir, backupDir);\n } catch (error) {\n return { action: 'failed', stage: 'backup', problems: [errorText(error)], backupDir: null };\n }\n\n // 2. copy to a staging dir beside the destination (same volume → atomic rename).\n try {\n copyTree(srcDir, stagingDir);\n } catch (error) {\n return { action: 'failed', stage: 'copy', problems: [errorText(error)], backupDir };\n }\n\n // 3. verify before anything is deleted or published.\n const verified = verifyTrees(srcDir, stagingDir);\n if (!verified.ok) {\n try {\n removeTree(stagingDir);\n } catch {\n // A stranded staging dir is harmless: the next run overwrites it.\n }\n return { action: 'failed', stage: 'verify', problems: verified.problems, backupDir };\n }\n\n // 4. publish: the destination may hold an empty skeleton from an earlier\n // bootstrap, which is not payload (checked above), so clear it and rename.\n try {\n if (fs.existsSync(dstDir)) removeTree(dstDir);\n fs.renameSync(stagingDir, dstDir);\n } catch (error) {\n try {\n removeTree(stagingDir);\n } catch {\n // best effort\n }\n return { action: 'failed', stage: 'commit', problems: [errorText(error)], backupDir };\n }\n\n // 5. the new tree is live; the originals go last. A leftover only wastes\n // space — the destination already wins on the next resolve.\n const leftovers: string[] = [];\n try {\n removeTree(srcDir);\n } catch {\n leftovers.push(srcDir);\n }\n try {\n removeTree(backupDir);\n } catch {\n leftovers.push(backupDir);\n }\n\n return {\n action: 'relocated',\n srcDir,\n dstDir,\n backupDir,\n files: verified.files,\n bytes: verified.bytes,\n warnings: verified.warnings,\n leftovers,\n };\n}\n","// Cross-process advisory file lock (H-20, minimal tier).\n//\n// The seed pool and the observation inbox are WHOLE-FILE rewrites of DPAPI\n// ciphertext — the vault cannot append to them — and the CLI runs as a second\n// process against the same files. Two interleaved load→mutate→save cycles\n// therefore let one side silently overwrite the other's write. The full fix\n// (append-only journal + compaction) is v2.0 work; this keeps the writers\n// honest in the meantime.\n//\n// The lock itself is a sibling file created with O_EXCL. A lock older than\n// STALE_MS is treated as abandoned (its holder died mid-write) and reclaimed.\n//\n// HB-03 (2026-10-17 review) fixed the two ways the minimal tier was lying:\n// 1. Waiting out WAIT_MS and then running `fn` ANYWAY made the lock advisory\n// in name only — the very interleaved rewrite it exists to prevent could\n// still happen, with the loser's data silently lost. Acquisition failure\n// is now fail-closed: `fn` never runs without the lock. Callers that must\n// keep going use `tryWithFileLock` and handle the `null`.\n// 2. Staleness was mtime alone, so a LIVE holder whose write ran longer than\n// STALE_MS had its lock deleted underneath it (both writers then hold it).\n// A lock is now reclaimed only when the pid it names is no longer running.\n\nimport fs from 'node:fs';\n\nconst STALE_MS = 15_000;\nconst WAIT_MS = 3_000;\nconst POLL_MS = 25;\n/** A lock whose owner cannot be identified is only reclaimed after this long. */\nconst UNKNOWN_HOLDER_MS = 2 * STALE_MS;\n\n/** Thrown when the lock could not be taken: the guarded write did NOT happen. */\nexport class FileLockTimeoutError extends Error {\n readonly target: string;\n readonly waitedMs: number;\n constructor(target: string, waitedMs: number) {\n super(`file lock timeout after ${waitedMs}ms: ${target}`);\n this.name = 'FileLockTimeoutError';\n this.target = target;\n this.waitedMs = waitedMs;\n }\n}\n\nexport interface FileLockOpts {\n /** How long to wait for the lock; defaults to WAIT_MS (3s). */\n waitMs?: number;\n}\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\n/** Is the process named in the lock file still running? Every doubt (\"cannot\n * read it\", \"no pid in it\") counts as alive until UNKNOWN_HOLDER_MS has passed:\n * deleting a live holder's lock is the failure this replaced. */\nfunction holderAlive(lock: string, ageMs: number): boolean {\n let raw = '';\n try {\n raw = fs.readFileSync(lock, 'utf8');\n } catch {\n return ageMs < UNKNOWN_HOLDER_MS; // vanished or unreadable mid-write\n }\n const pid = Number.parseInt(raw.trim().split(/\\s+/)[0] ?? '', 10);\n if (!Number.isInteger(pid) || pid <= 0) return ageMs < UNKNOWN_HOLDER_MS;\n if (pid === process.pid) return true; // our own re-entrant look; never steal\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return (e as NodeJS.ErrnoException).code === 'EPERM'; // alive, not ours\n }\n}\n\nfunction tryAcquire(lock: string): boolean {\n try {\n const fd = fs.openSync(lock, 'wx');\n fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}\\n`);\n fs.closeSync(fd);\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;\n // Reclaim a lock whose holder is gone.\n try {\n const ageMs = Date.now() - fs.statSync(lock).mtimeMs;\n if (ageMs > STALE_MS && !holderAlive(lock, ageMs)) {\n fs.rmSync(lock, { force: true });\n return tryAcquire(lock);\n }\n } catch {\n return tryAcquire(lock); // vanished between open and stat\n }\n return false;\n }\n}\n\n/** Take the lock, or give up after `waitMs`. Never blocks past the deadline. */\nfunction acquire(lock: string, waitMs: number): boolean {\n const deadline = Date.now() + waitMs;\n for (;;) {\n if (tryAcquire(lock)) return true;\n if (Date.now() >= deadline) return false;\n sleepSync(POLL_MS);\n }\n}\n\nfunction release(lock: string): void {\n try {\n fs.rmSync(lock, { force: true });\n } catch { /* already gone */ }\n}\n\n/**\n * Run `fn` while holding the lock for `target`. Fail-closed (HB-03): if the\n * lock cannot be taken within `waitMs`, this throws FileLockTimeoutError and\n * `fn` is never called — a write without the lock is exactly the corruption the\n * lock exists to prevent. Use `tryWithFileLock` when \"skip this write\" is a\n * valid answer for the caller.\n */\nexport function withFileLock<T>(target: string, fn: () => T, opts: FileLockOpts = {}): T {\n const waitMs = opts.waitMs ?? WAIT_MS;\n const lock = `${target}.lock`;\n if (!acquire(lock, waitMs)) throw new FileLockTimeoutError(target, waitMs);\n try {\n return fn();\n } finally {\n release(lock);\n }\n}\n\n/**\n * `withFileLock`, but a lock that cannot be taken yields `null` instead of\n * throwing, and `fn` still never runs without the lock. Callers use this when\n * dropping the write (and saying so in the audit log) beats failing the beat.\n */\nexport function tryWithFileLock<T>(target: string, fn: () => T, opts: FileLockOpts = {}): T | null {\n const waitMs = opts.waitMs ?? WAIT_MS;\n const lock = `${target}.lock`;\n if (!acquire(lock, waitMs)) return null;\n try {\n return fn();\n } finally {\n release(lock);\n }\n}\n","// Recursive file matching below a data directory (HB-07 / HB-21).\n//\n// The burn list and `profile wipe` both need \"every file anywhere under\n// dataDir whose name matches this pattern\". Migration backups\n// (`${abs}.bak-migrate-${stamp}`) and crash leftovers (`.incoming-`) sit next\n// to whatever they copied, so a target that only reads the top level would\n// leave a full copy of the memory behind.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Relative POSIX-style paths of files below `root` whose NAME matches `match`,\n * sorted. The pattern is used as a plain test: a `g` flag is stripped so a\n * caller-supplied regexp cannot carry lastIndex state between files. `root`\n * must already be resolved/validated by the caller's path guard.\n */\nexport function matchFilesRecursive(root: string, match: RegExp): string[] {\n const re = new RegExp(match.source, match.flags.replace(/g/g, ''));\n const out: string[] = [];\n const walk = (dir: string, prefix: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const rel = prefix ? `${prefix}/${e.name}` : e.name;\n if (e.isDirectory()) {\n walk(path.join(dir, e.name), rel);\n continue;\n }\n if (!e.isFile()) continue;\n if (re.test(e.name)) out.push(rel);\n }\n };\n walk(root, '');\n return out.sort();\n}\n","// Transparent encryption read/write layer.\n//\n// Two container generations live side by side on disk:\n// KHBV1 legacy — DPAPI (CurrentUser) over the whole payload, produced by\n// assets/vault.ps1. Every read/write costs one PowerShell process,\n// which is why a beat that touches many files paid seconds of spawn\n// time (HB-11).\n// KHBV2 current — AES-256-GCM applied in-process, keyed by a 32-byte random\n// master key. The key itself is stored DPAPI-protected in\n// <dataDir>/vault.key, so the only thing that still needs DPAPI is\n// unwrapping that one file, and that happens once per process (cached).\n//\n// Platform support (v2.1.0): DPAPI only exists on Windows. Everywhere else the\n// master key file holds the raw 32 key bytes, published 0600 and owned by the\n// account the plugin runs as — the OS keyring is not available to lean on, so\n// filesystem permissions are the whole guard. KHBV1 containers are Windows-only\n// and are NOT portable: opening one off-Windows throws a plain error instead of\n// spawning a PowerShell that does not exist.\n//\n// Migration contract (v2.0): an upgraded plugin keeps opening everything an\n// older version wrote — reads accept BOTH containers, while writes always\n// produce KHBV2. Legacy files are rewritten in place by upgradeVaultTree(),\n// which the CLI runs on demand. Going the other way is one-way: a 1.x build\n// cannot read KHBV2, so once `vault upgrade` has run, do not downgrade.\n// Encryption stays fail-closed: a missing or unreadable master key throws, and\n// no path ever falls back to plaintext.\n//\n// Plaintext never touches the disk on the KHBV2 path: the payload goes straight\n// from a Buffer through AES-GCM into the temp container that is renamed into\n// place. (KHBV1 needed a plaintext window under data/tmp for PowerShell.)\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { workspace } from '../core/paths.js';\nimport { burnFileSync } from '../core/atomic-fs.js';\nimport { FileLockTimeoutError, withFileLock } from '../core/file-lock.js';\nimport { matchFilesRecursive } from '../core/fs-walk.js';\n\n/** Legacy container: 5-byte magic + DPAPI blob. */\nconst MAGIC_V1 = Buffer.from('KHBV1', 'ascii');\n/** Current container: magic + version + nonce + tag + ciphertext. */\nconst MAGIC_V2 = Buffer.from('KHBV2', 'ascii');\nconst V2_VERSION = 1;\nconst V2_NONCE_BYTES = 12;\nconst V2_TAG_BYTES = 16;\nconst V2_HEADER_BYTES = MAGIC_V2.length + 1 + V2_NONCE_BYTES + V2_TAG_BYTES;\n/** Additional authenticated data: pins the header, so a container cannot be relabelled. */\nconst V2_AAD = Buffer.concat([MAGIC_V2, Buffer.from([V2_VERSION])]);\nconst KEY_BYTES = 32;\nconst KEY_FILE_NAME = 'vault.key';\nconst VAULT_TIMEOUT_MS = 30_000;\n\n/** Test seam: what the vault should pretend to run on (null = the real one). */\nlet platformOverride: NodeJS.Platform | null = null;\n\n/** Force a platform for tests (and drop the cached key, which is keyed by it). */\nexport function setVaultPlatformForTest(platform: NodeJS.Platform | null): void {\n platformOverride = platform;\n cachedMasterKey = null;\n}\n\nfunction vaultPlatform(): NodeJS.Platform {\n return platformOverride ?? process.platform;\n}\n\n/** DPAPI — and therefore every KHBV1 container — exists only on Windows. */\nfunction dpapiAvailable(): boolean {\n return vaultPlatform() === 'win32';\n}\n\nlet cachedScriptPath: string | null = null;\n\nfunction vaultScriptPath(): string {\n if (cachedScriptPath) return cachedScriptPath;\n const script = path.join(workspace().assetsDir, 'vault.ps1');\n if (!fs.existsSync(script)) throw new Error(`vault script missing: ${script}`);\n cachedScriptPath = script;\n return script;\n}\n\nfunction tmpPlainName(target: string): string {\n return path.join(workspace().tmpDir, `.${path.basename(target)}.${randomUUID().slice(0, 8)}.plain`);\n}\n\nfunction tmpEncName(target: string): string {\n return path.join(workspace().tmpDir, `.${path.basename(target)}.${randomUUID().slice(0, 8)}.enc`);\n}\n\nfunction runVault(guard: PathGuard, args: string[]): void {\n if (!dpapiAvailable()) {\n throw new Error(\n `vault: ${args[0]} needs Windows DPAPI, which ${vaultPlatform()} does not have — KHBV1 containers are Windows-only and heartbeat data does not migrate across platforms`,\n );\n }\n const r = spawnSync(\n 'powershell.exe',\n ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', vaultScriptPath(), ...args],\n { timeout: VAULT_TIMEOUT_MS, encoding: 'utf8' },\n );\n if (r.error) throw new Error(`vault spawn failed: ${String(r.error)}`);\n if (r.status !== 0) {\n const detail = (r.stderr || r.stdout || '').trim().split('\\n').slice(-3).join('; ');\n throw new Error(`vault ${args[0]} failed (exit ${r.status}): ${detail}`);\n }\n}\n\n/** How long a scratch file may sit before it is treated as crash debris. */\nconst SCRATCH_STALE_MS = 10 * 60_000;\nlet scratchSwept = false;\n\n/**\n * Burn plaintext scratch files a crash left behind in data/tmp (低优先级 review,\n * 2026-10-17). The writers there are wrapped in `finally`, but a kill leaves the\n * bytes on disk. Only files older than SCRATCH_STALE_MS are touched, so a\n * concurrent process's live window is never yanked out from under it.\n */\nexport function sweepVaultScratch(): number {\n if (scratchSwept) return 0;\n scratchSwept = true;\n let burned = 0;\n try {\n const dir = workspace().tmpDir;\n for (const name of fs.readdirSync(dir)) {\n if (!/\\.(plain|enc)$/.test(name)) continue;\n const p = path.join(dir, name);\n try {\n if (Date.now() - fs.statSync(p).mtimeMs < SCRATCH_STALE_MS) continue;\n } catch {\n continue; // vanished between readdir and stat\n }\n burnFileSync(p);\n burned += 1;\n }\n } catch {\n /* no tmp dir yet — nothing to sweep */\n }\n return burned;\n}\n\nexport type ContainerKind = 'v2' | 'v1' | 'plain';\n\n/** Which container a file carries, decided from its first bytes. */\nexport function containerKind(file: string): ContainerKind {\n if (!fs.existsSync(file)) return 'plain';\n const fd = fs.openSync(file, 'r');\n try {\n const head = Buffer.alloc(MAGIC_V2.length);\n const read = fs.readSync(fd, head, 0, head.length, 0);\n if (read === MAGIC_V1.length && head.subarray(0, MAGIC_V1.length).equals(MAGIC_V1)) return 'v1';\n if (read === MAGIC_V2.length && head.equals(MAGIC_V2)) return 'v2';\n return 'plain';\n } finally {\n fs.closeSync(fd);\n }\n}\n\n/** True for either container generation (plaintext files stay plaintext). */\nexport function isEncrypted(file: string): boolean {\n return containerKind(file) !== 'plain';\n}\n\nfunction encryptBlob(key: Buffer, plain: Buffer): Buffer {\n const nonce = randomBytes(V2_NONCE_BYTES);\n const cipher = createCipheriv('aes-256-gcm', key, nonce);\n cipher.setAAD(V2_AAD);\n const body = Buffer.concat([cipher.update(plain), cipher.final()]);\n return Buffer.concat([MAGIC_V2, Buffer.from([V2_VERSION]), nonce, cipher.getAuthTag(), body]);\n}\n\nfunction decryptBlob(key: Buffer, raw: Buffer): Buffer {\n if (raw.length < V2_HEADER_BYTES) throw new Error('vault: truncated KHBV2 container');\n if (!raw.subarray(0, MAGIC_V2.length).equals(MAGIC_V2)) throw new Error('vault: missing KHBV2 header');\n const version = raw[MAGIC_V2.length]!;\n if (version !== V2_VERSION) throw new Error(`vault: unsupported KHBV2 version ${version}`);\n const nonceAt = MAGIC_V2.length + 1;\n const tagAt = nonceAt + V2_NONCE_BYTES;\n const bodyAt = tagAt + V2_TAG_BYTES;\n const decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(nonceAt, tagAt));\n decipher.setAAD(Buffer.concat([MAGIC_V2, Buffer.from([version])]));\n decipher.setAuthTag(raw.subarray(tagAt, bodyAt));\n // final() throws when the tag does not verify (tampered or wrong key).\n return Buffer.concat([decipher.update(raw.subarray(bodyAt)), decipher.final()]);\n}\n\nfunction legacyUnprotect(guard: PathGuard, file: string, out: string): void {\n runVault(guard, ['unprotect', '-InFile', file, '-OutFile', out]);\n}\n\nfunction legacyProtect(guard: PathGuard, inFile: string, out: string): void {\n runVault(guard, ['protect', '-InFile', inFile, '-OutFile', out]);\n}\n\n/** Path of the DPAPI-wrapped master key that every KHBV2 container is keyed by. */\nexport function vaultKeyPath(): string {\n return path.join(workspace().dataDir, KEY_FILE_NAME);\n}\n\nlet cachedMasterKey: Buffer | null = null;\n\n/** Drop the cached key and the once-per-process sweep flag. Tests use it after\n * pointing the workspace elsewhere. */\nexport function resetVaultKeyCacheForTest(): void {\n cachedMasterKey = null;\n scratchSwept = false;\n}\n\nfunction decodeKeyFile(guard: PathGuard, file: string): Buffer {\n const kind = containerKind(file);\n if (kind === 'v2') {\n throw new Error(\n `vault: ${file} is an AES container, but the master key cannot be stored AES-encrypted — restore it from a backup or re-import the data`,\n );\n }\n if (!dpapiAvailable()) {\n if (kind === 'v1') {\n throw new Error(\n `vault: ${file} is a DPAPI (KHBV1) container — the master key was created on Windows and cannot be unwrapped on ${vaultPlatform()}; heartbeat data does not migrate across platforms, so start a fresh data dir here`,\n );\n }\n const key = fs.readFileSync(file);\n if (key.length !== KEY_BYTES) {\n throw new Error(`vault: master key has ${key.length} bytes, expected ${KEY_BYTES}`);\n }\n return key;\n }\n if (kind !== 'v1') throw new Error(`vault: ${file} is not a DPAPI container (not a usable master key)`);\n const tmp = tmpPlainName(file);\n try {\n legacyUnprotect(guard, file, tmp);\n const key = fs.readFileSync(tmp);\n if (key.length !== KEY_BYTES) {\n throw new Error(`vault: master key has ${key.length} bytes, expected ${KEY_BYTES}`);\n }\n return key;\n } finally {\n burnFileSync(tmp);\n }\n}\n\n/**\n * Publish a fresh master key on a host without DPAPI: the 32 raw bytes ARE the\n * file. Written to scratch first and renamed, so a concurrent reader sees either\n * no key or a complete one, and 0600 is applied before the bytes land in place.\n */\nfunction publishPlainKeyFile(file: string, key: Buffer): void {\n const tmp = tmpPlainName(file);\n try {\n fs.writeFileSync(tmp, key, { mode: 0o600 });\n // Re-open what we are about to publish: a key nobody can read is dead data.\n if (!fs.readFileSync(tmp).equals(key)) throw new Error('vault: master key round-trip mismatch');\n fs.renameSync(tmp, file);\n try {\n fs.chmodSync(file, 0o600);\n } catch {\n /* best effort: the mode was already set at creation time */\n }\n } finally {\n burnFileSync(tmp);\n }\n}\n\n/**\n * The process-wide master key. Created on first use under a file lock, then\n * cached for the rest of the process's life.\n *\n * A key file that EXISTS but cannot be read is a hard error, never a reason to\n * generate a fresh key: every container already on disk is encrypted with the\n * old one, so replacing it would silently turn the user's memory into garbage.\n */\nexport function masterKey(guard: PathGuard): Buffer {\n if (cachedMasterKey) return cachedMasterKey;\n sweepVaultScratch();\n const file = guard.assert(vaultKeyPath());\n if (fs.existsSync(file)) {\n cachedMasterKey = decodeKeyFile(guard, file);\n return cachedMasterKey;\n }\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // HB-03: acquisition is fail-closed, so a lock held by another process that is\n // creating the key right now surfaces as FileLockTimeoutError instead of a\n // second key. Re-check before bubbling it up: `rename` publishes atomically,\n // so the file is either absent or complete, and a second key would scramble\n // every container the first one already wrote.\n let created: Buffer | null;\n try {\n created = withFileLock(file, (): Buffer | null => {\n if (fs.existsSync(file)) return null; // another process created it first\n if (!dpapiAvailable()) {\n const key = randomBytes(KEY_BYTES);\n publishPlainKeyFile(file, key);\n return key;\n }\n const plain = tmpPlainName(file);\n const enc = tmpEncName(file);\n try {\n const key = randomBytes(KEY_BYTES);\n fs.writeFileSync(plain, key);\n legacyProtect(guard, plain, enc);\n // Open the container we are about to publish: a master key nobody can\n // unwrap is dead data, so verify the round trip before it goes live.\n const check = tmpPlainName(file);\n try {\n legacyUnprotect(guard, enc, check);\n if (!fs.readFileSync(check).equals(key)) throw new Error('vault: master key round-trip mismatch');\n } finally {\n burnFileSync(check);\n }\n fs.renameSync(enc, file);\n return key;\n } finally {\n burnFileSync(plain);\n fs.rmSync(enc, { force: true });\n }\n });\n } catch (e) {\n if (e instanceof FileLockTimeoutError && fs.existsSync(file)) {\n cachedMasterKey = decodeKeyFile(guard, file);\n return cachedMasterKey;\n }\n throw e;\n }\n cachedMasterKey = created ?? decodeKeyFile(guard, file);\n return cachedMasterKey;\n}\n\n/** Ciphertext of any container generation -> plaintext bytes. */\nfunction readContainer(guard: PathGuard, file: string): Buffer {\n const kind = containerKind(file);\n if (kind === 'v2') return decryptBlob(masterKey(guard), fs.readFileSync(file));\n if (kind === 'v1') {\n const tmp = tmpPlainName(file);\n try {\n legacyUnprotect(guard, file, tmp);\n return fs.readFileSync(tmp);\n } finally {\n burnFileSync(tmp);\n }\n }\n return fs.readFileSync(file);\n}\n\n/** Plaintext bytes -> KHBV2 container, renamed into place (atomic replace). */\nfunction writeContainer(guard: PathGuard, file: string, data: Buffer): void {\n const f = guard.assert(file);\n fs.mkdirSync(path.dirname(f), { recursive: true });\n const enc = tmpEncName(f);\n try {\n fs.writeFileSync(enc, encryptBlob(masterKey(guard), data));\n fs.renameSync(enc, f);\n } finally {\n fs.rmSync(enc, { force: true });\n }\n}\n\n/**\n * Read JSON: encrypted files are decrypted in memory (or through a shredded\n * data/tmp window for legacy containers); plaintext stays compatible.\n */\nexport function loadJson<T>(guard: PathGuard, file: string): T | null {\n const f = guard.assert(file);\n if (!fs.existsSync(f)) return null;\n if (containerKind(f) === 'plain') {\n try {\n return JSON.parse(fs.readFileSync(f, 'utf8')) as T;\n } catch {\n return null;\n }\n }\n // Encrypted file: a failure here is a damaged container or a foreign master\n // key. Report it instead of \"no file\" — callers treat null as an empty store\n // and would overwrite the user's data with a fresh one.\n return JSON.parse(readContainer(guard, f).toString('utf8')) as T;\n}\n\n/** Write JSON as a KHBV2 container. */\nexport function saveJson(guard: PathGuard, file: string, value: unknown): void {\n writeContainer(guard, file, Buffer.from(JSON.stringify(value, null, 2), 'utf8'));\n}\n\n/** Read a plaintext UTF-8 text file (ledger etc.), with fallback. */\nexport function readText(guard: PathGuard, file: string, fallback = ''): string {\n const f = guard.assert(file);\n try {\n return fs.readFileSync(f, 'utf8');\n } catch {\n return fallback;\n }\n}\n\n/** Write a plaintext UTF-8 text file atomically (ledger etc.). */\nexport function writeText(guard: PathGuard, file: string, content: string): void {\n const f = guard.assert(file);\n fs.mkdirSync(path.dirname(f), { recursive: true });\n const tmp = tmpPlainName(f);\n try {\n fs.writeFileSync(tmp, content, 'utf8');\n fs.renameSync(tmp, f);\n } finally {\n burnFileSync(tmp);\n }\n}\n\n/** Read an encrypted UTF-8 text file (e.g. seeds.jsonl). Missing -> null. */\nexport function loadEncryptedText(guard: PathGuard, file: string): string | null {\n const f = guard.assert(file);\n if (!fs.existsSync(f)) return null;\n return readContainer(guard, f).toString('utf8');\n}\n\n/** Write an encrypted UTF-8 text file as a KHBV2 container. */\nexport function saveEncryptedText(guard: PathGuard, file: string, content: string): void {\n writeContainer(guard, file, Buffer.from(content, 'utf8'));\n}\n\n/** Encrypt any binary file (e.g. screenshot): inFile -> encrypted outFile. */\nexport function encryptFile(guard: PathGuard, inFile: string, outFile: string): void {\n const inPath = guard.assert(inFile);\n writeContainer(guard, outFile, fs.readFileSync(inPath));\n}\n\n/**\n * Decrypt an encrypted file to a plaintext output (caller must place the\n * output under data/tmp and delete it after use; \"use then burn\" discipline).\n */\nexport function decryptFile(guard: PathGuard, inFile: string, outFile: string): void {\n const inPath = guard.assert(inFile);\n const outPath = guard.assert(outFile);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n const data = readContainer(guard, inPath);\n const tmp = tmpPlainName(outPath);\n try {\n fs.writeFileSync(tmp, data);\n fs.renameSync(tmp, outPath);\n } finally {\n burnFileSync(tmp);\n }\n}\n\nexport interface VaultUpgradeResult {\n /** Files whose header was inspected. */\n scanned: number;\n /** Legacy KHBV1 containers rewritten as KHBV2. */\n upgraded: number;\n /** Files that could not be migrated (the original file is left untouched). */\n failed: { file: string; reason: string }[];\n}\n\n/** Rewrite one legacy container as KHBV2. Returns false when there is nothing to do. */\nexport function upgradeVaultFile(guard: PathGuard, file: string): boolean {\n const f = guard.assert(file);\n if (containerKind(f) !== 'v1') return false;\n const data = readContainer(guard, f); // DPAPI unwrap (throws if it is not ours)\n writeContainer(guard, f, data); // AES-GCM wrap; the rename replaces the original\n return true;\n}\n\n/**\n * Walk every file under the data dir and rewrite legacy containers in place, so\n * an upgraded plugin stops paying a PowerShell process per legacy file. The\n * tmp scratch dir and the master key itself are left alone.\n */\nexport function upgradeVaultTree(guard: PathGuard, dataDir: string): VaultUpgradeResult {\n const result: VaultUpgradeResult = { scanned: 0, upgraded: 0, failed: [] };\n for (const rel of matchFilesRecursive(dataDir, /./)) {\n if (rel === KEY_FILE_NAME || rel.startsWith('tmp/') || rel.startsWith('tmp\\\\')) continue;\n const abs = path.join(dataDir, rel.split('/').join(path.sep));\n try {\n result.scanned += 1;\n if (upgradeVaultFile(guard, abs)) result.upgraded += 1;\n } catch (e) {\n result.failed.push({ file: rel, reason: (e as Error).message });\n }\n }\n return result;\n}\n\n/**\n * Rewrite ONE legacy container, for callers that have to stay inside a bounded\n * window: the beat's maintenance phase calls this once per beat, so a back\n * catalogue drains gradually instead of spending a whole maintenance window (or\n * a startup) on DPAPI round trips. A file that cannot be migrated is left\n * exactly as it is and retried next beat; `vault upgrade` remains the \"do them\n * all now\" path.\n */\nexport function upgradeOneLegacyVaultFile(guard: PathGuard, dataDir: string): string | null {\n for (const rel of matchFilesRecursive(dataDir, /./)) {\n if (rel === KEY_FILE_NAME || rel.startsWith('tmp/') || rel.startsWith('tmp\\\\')) continue;\n const abs = path.join(dataDir, rel.split('/').join(path.sep));\n try {\n if (upgradeVaultFile(guard, abs)) return rel;\n } catch {\n /* unreadable container: keep the original and try again next beat */\n }\n }\n return null;\n}\n"],"mappings":";;;;;AAUA,OAAOA,SAAQ;AACf,OAAO,QAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,qBAAqB;;;ACK9B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAG3B,IAAM,gBAAgB,CAAC,YAAY,QAAQ,OAAO,SAAS;AAE3D,IAAM,cAAc;AACpB,IAAM,WAAW,OAAO,KAAK,SAAS,OAAO;AAC7C,IAAM,WAAW,OAAO,KAAK,SAAS,OAAO;AAoDtC,SAAS,WAAW,KAAsB;AAC/C,MAAI,CAAC,GAAG,WAAW,GAAG,EAAG,QAAO;AAChC,aAAW,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;AAChE,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,QAAI,CAAC,cAAc,SAAS,MAAM,IAAI,EAAG,QAAO;AAChD,QAAI,MAAM,SAAS,YAAa;AAChC,QAAI,GAAG,YAAY,KAAK,KAAK,KAAK,MAAM,IAAI,CAAC,EAAE,SAAS,EAAG,QAAO;AAAA,EACpE;AACA,SAAO;AACT;AAGA,SAAS,KAAK,KAAa,SAAS,IAAI,MAAgB,CAAC,GAAa;AACpE,aAAW,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;AAChE,UAAM,MAAM,SAAS,GAAG,MAAM,IAAI,MA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