@kanadego/dsh-heartbeat 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -23
- package/client.js +498 -125
- package/config/interests.json +1 -1
- package/config/policy.json +3 -2
- package/dist/{chunk-TVX4HV4Y.js → chunk-63E5OYSI.js} +56 -5
- package/dist/chunk-63E5OYSI.js.map +1 -0
- package/dist/{chunk-NCPKOWS7.js → chunk-AT32XCCI.js} +2 -2
- package/dist/{chunk-DC5HMCJC.js → chunk-DLOYERAK.js} +3 -3
- package/dist/{chunk-544QOJN5.js → chunk-ECXYNTEV.js} +2 -2
- package/dist/{chunk-IFRMKVIC.js → chunk-HE6IF6OU.js} +5 -2
- package/dist/chunk-HE6IF6OU.js.map +1 -0
- package/dist/{chunk-DZ7YCFGX.js → chunk-KZLVR4J7.js} +2 -2
- package/dist/{chunk-6XM6KY7M.js → chunk-LPPRI53J.js} +39 -37
- package/dist/chunk-LPPRI53J.js.map +1 -0
- package/dist/chunk-LQKOYTRL.js +59 -0
- package/dist/chunk-LQKOYTRL.js.map +1 -0
- package/dist/{chunk-AKIJ4LS2.js → chunk-M72T5MZU.js} +44 -1
- package/dist/chunk-M72T5MZU.js.map +1 -0
- package/dist/{chunk-6MVKWICX.js → chunk-XCMGPIUQ.js} +99 -23
- package/dist/chunk-XCMGPIUQ.js.map +1 -0
- package/dist/cli/index.js +51 -11
- package/dist/cli/index.js.map +1 -1
- package/dist/focus-store-RNHBAFYS.js +20 -0
- package/dist/{inbox-OWBK6PE2.js → inbox-ZLX2MH7A.js} +3 -3
- package/dist/index.d.ts +16 -3
- package/dist/index.js +119 -69
- package/dist/index.js.map +1 -1
- package/dist/{migrate-TQ5PB2DI.js → migrate-XFZU5EBE.js} +3 -3
- package/dist/{orchestrator-P7AEWVYR.js → orchestrator-MNFCPH43.js} +27 -8
- package/dist/{pool-2T6TVS2L.js → pool-MAABBHC4.js} +9 -3
- package/dist/{snapshot-F5B2DD56.js → snapshot-SU2VGM4C.js} +4 -4
- package/dist/snapshot-SU2VGM4C.js.map +1 -0
- package/icon.svg +11 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +11 -6
- package/dist/chunk-6MVKWICX.js.map +0 -1
- package/dist/chunk-6XM6KY7M.js.map +0 -1
- package/dist/chunk-AKIJ4LS2.js.map +0 -1
- package/dist/chunk-IFRMKVIC.js.map +0 -1
- package/dist/chunk-TVX4HV4Y.js.map +0 -1
- /package/dist/{chunk-NCPKOWS7.js.map → chunk-AT32XCCI.js.map} +0 -0
- /package/dist/{chunk-DC5HMCJC.js.map → chunk-DLOYERAK.js.map} +0 -0
- /package/dist/{chunk-544QOJN5.js.map → chunk-ECXYNTEV.js.map} +0 -0
- /package/dist/{chunk-DZ7YCFGX.js.map → chunk-KZLVR4J7.js.map} +0 -0
- /package/dist/{inbox-OWBK6PE2.js.map → focus-store-RNHBAFYS.js.map} +0 -0
- /package/dist/{migrate-TQ5PB2DI.js.map → inbox-ZLX2MH7A.js.map} +0 -0
- /package/dist/{orchestrator-P7AEWVYR.js.map → migrate-XFZU5EBE.js.map} +0 -0
- /package/dist/{pool-2T6TVS2L.js.map → orchestrator-MNFCPH43.js.map} +0 -0
- /package/dist/{snapshot-F5B2DD56.js.map → pool-MAABBHC4.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ledger/ledger.ts","../src/browse/preference.ts","../src/browse/browse.ts","../src/core/time-window.ts","../src/notify/notify.ts","../src/core/ps.ts","../src/weekly/report.ts"],"sourcesContent":["// 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';\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\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[(open|done)\\]\\[#([0-9a-f]{6})\\] (.*)$/;\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 = new Date(now - days * DAY_MS).toISOString().slice(0, 10);\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, 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/** LOCAL day key (refill quota is a daily human-day budget, not a UTC day). */\nfunction localDayKey(d: 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\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","// 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","// 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 return new Promise((resolve) => {\n let settled = false;\n const done = (r: PsResult): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener('abort', onAbort);\n resolve(r);\n };\n const onAbort = (): void => {\n try { child.kill(); } catch { /* already gone */ }\n done({ status: 1, stdout: '', stderr: 'aborted' });\n };\n const child = execFile(\n 'powershell.exe',\n ['-NoProfile', '-ExecutionPolicy', 'Bypass', ...args],\n { timeout: timeoutMs, encoding: 'utf8', windowsHide: true },\n (err, stdout, stderr) => {\n const code = (err as { code?: unknown } | null)?.code;\n const status = err ? (typeof code === 'number' ? code : 1) : 0;\n done({ status, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });\n },\n );\n child.on('error', () => { /* surfaced through the callback above */ });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** Convenience for the `-File <script>` shape used by every asset script. */\nexport function runPowerShellFile(script: string, args: string[], timeoutMs: number, signal?: AbortSignal): Promise<PsResult> {\n return runPowerShell(['-File', script, ...args], timeoutMs, signal);\n}\n","// Weekly report store + writer helpers (v1.8.0). Deliberately host-free:\n// orchestration (when to run, which agent, toast) lives in the orchestrator —\n// same split as profile/consolidate.ts. Reports are DPAPI-encrypted because a\n// report contains user-identifying content (profile adds, ledger texts) —\n// same划线标准 as profile/seeds (design doc §10.5).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { workspace } from '../core/paths.js';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { WeeklyFacts } from './collect.js';\n\nexport const WEEKLY_INTERVAL_MS = 7 * 86_400_000;\n\nexport interface WeeklyReport {\n start: string;\n end: string;\n generatedAt: string;\n /** 'llm' = engine-room prose; 'template' = deterministic fallback. */\n source: 'llm' | 'template';\n text: string;\n}\n\nexport function weeklyDirPath(dataDir: string): string {\n return path.join(dataDir, 'weekly');\n}\n\nfunction stateFilePath(dataDir: string): string {\n return path.join(weeklyDirPath(dataDir), 'state.json');\n}\n\nfunction reportFileName(endIso: string): string {\n return `report-${endIso.slice(0, 10)}.json`;\n}\n\n/**\n * Last generation time from the weekly state file; 0 = never anchored.\n *\n * H-54: \"missing\" and \"present but unparseable\" are NOT the same thing. The\n * old code folded both into 0, so `ensureWeeklyAnchor` \"repaired\" a corrupt\n * file by stamping NOW — silently, and at the cost of pushing the next report\n * a full interval out. A corrupt anchor now keeps its file, writes an audit\n * line, and falls back to the file's mtime so the schedule keeps its place.\n */\nexport function lastWeeklyGeneratedAt(guard: PathGuard, dataDir: string): number {\n const file = stateFilePath(dataDir);\n let raw: string;\n try {\n raw = fs.readFileSync(guard.assert(file), 'utf8');\n } catch {\n return 0; // absent: a fresh install, legitimately never anchored\n }\n try {\n const parsed = JSON.parse(raw) as { lastGeneratedAt?: number };\n const n = Number(parsed.lastGeneratedAt);\n if (Number.isFinite(n) && n > 0) return n;\n } catch {\n /* unparseable — handled by the fallback below */\n }\n try {\n appendAuditLine(path.join(workspace().logsDir, 'heartbeat.jsonl'), {\n event: 'weekly_anchor_corrupt',\n file: path.basename(file),\n bytes: Buffer.byteLength(raw),\n });\n } catch {\n /* audit is diagnostic; never let it break the schedule */\n }\n try {\n return fs.statSync(file).mtimeMs;\n } catch {\n return 0;\n }\n}\n\n/** Due when the last report is ≥7 days old. A never-anchored store lands on\n * the install-time anchor (see ensureWeeklyAnchor), so a fresh install is NOT\n * due — the first report arrives one full interval after installation. */\nexport function weeklyDue(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n const last = lastWeeklyGeneratedAt(guard, dataDir);\n return now - last >= WEEKLY_INTERVAL_MS;\n}\n\n/** Stamp the install-time anchor for a store that has never generated a report\n * (v1.9.0). Returns true when it wrote — the caller audits that. Without this,\n * `lastGeneratedAt = 0` made the very first maintenance beat due, so a fresh\n * install produced an \"onboarding\" report immediately, contradicting the\n * release notes (\"first report after a week\"). */\nexport function ensureWeeklyAnchor(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n if (lastWeeklyGeneratedAt(guard, dataDir) > 0) return false;\n fs.mkdirSync(weeklyDirPath(dataDir), { recursive: true });\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: now });\n return true;\n}\n\n/** Persist a report (DPAPI) and stamp the state file. */\nexport function saveWeeklyReport(guard: PathGuard, dataDir: string, report: WeeklyReport): string {\n const dir = weeklyDirPath(dataDir);\n fs.mkdirSync(dir, { recursive: true });\n const file = path.join(dir, reportFileName(report.end));\n saveEncryptedText(guard, file, JSON.stringify(report, null, 1));\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: Date.parse(report.generatedAt) });\n return file;\n}\n\nexport interface WeeklyReportMeta {\n file: string;\n start: string;\n end: string;\n generatedAt: string;\n source: string;\n}\n\n/** Newest-first listing for the card; unparsable entries are skipped.\n * v2.0 (item 5): an optional `limit` shows only the newest N reports. */\nexport function listWeeklyReports(guard: PathGuard, dataDir: string, limit?: number): WeeklyReportMeta[] {\n const out: WeeklyReportMeta[] = [];\n try {\n for (const file of fs.readdirSync(weeklyDirPath(dataDir))) {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) continue;\n const rep = readWeeklyReport(guard, dataDir, file);\n if (!rep) continue;\n out.push({ file, start: rep.start, end: rep.end, generatedAt: rep.generatedAt, source: rep.source });\n }\n } catch { /* no weekly dir yet */ }\n const sorted = out.sort((a, b) => (a.end < b.end ? 1 : -1));\n return limit !== undefined && limit > 0 ? sorted.slice(0, limit) : sorted;\n}\n\n/**\n * v2.0 (item 5): delete every report beyond the newest `keep`, so the card's\n * report buttons cannot crowd the panel and the store cannot grow unbounded.\n * `keep <= 0` disables pruning (and the policy schema forbids it anyway).\n * Returns the deleted file names so the caller can audit them; a report that\n * cannot be deleted is left in place (best effort — never break the beat).\n */\nexport function pruneWeeklyReports(guard: PathGuard, dataDir: string, keep: number): string[] {\n if (!Number.isFinite(keep) || keep <= 0) return [];\n const removed: string[] = [];\n for (const meta of listWeeklyReports(guard, dataDir).slice(keep)) {\n try {\n fs.rmSync(guard.assert(path.join(weeklyDirPath(dataDir), meta.file)));\n removed.push(meta.file);\n } catch { /* best effort */ }\n }\n return removed;\n}\n\nexport function readWeeklyReport(guard: PathGuard, dataDir: string, file: string): WeeklyReport | null {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) return null; // guard.assert would reject ../ anyway\n try {\n const raw = loadEncryptedText(guard, path.join(weeklyDirPath(dataDir), file));\n if (!raw) return null;\n const rep = JSON.parse(raw) as WeeklyReport;\n if (typeof rep.text !== 'string') return null;\n return rep;\n } catch {\n return null;\n }\n}\n\n/** The engine-room prompt: neutral system narrator, fact-bound, ≤250 chars. */\nexport function buildWeeklyPrompt(facts: WeeklyFacts): string {\n return [\n '你是心跳插件的后台报告器。根据下面的本周事实清单,用中文写一份周报正文。',\n '规则:',\n '- 叙述者自称「心跳」——这是插件后台,不是任何会话里的 agent;绝不能以会话 agent 的身份或人格自称。',\n '- 只报告事实清单里有的内容;某一节没有数据就整节跳过,不要编造、不要凑数。',\n '- 语气平实中性,不用感叹号;篇幅不超过 250 字。',\n '- 待办积压那一节用商量的语气提一句,不催促。',\n '- 直接输出周报正文,不要输出解释、标题或 JSON。',\n '',\n '本周事实(JSON):',\n JSON.stringify(facts, null, 1),\n ].join('\\n');\n}\n\n/** Deterministic fallback: the facts, plainly stated. Used when the LLM turn\n * fails or comes back empty — a plain report beats no report. */\nexport function renderTemplateReport(facts: WeeklyFacts): string {\n const d = (iso: string): string => iso.slice(0, 10);\n const lines: string[] = [`本周(${d(facts.windowStart)} ~ ${d(facts.windowEnd)})`];\n lines.push(`表达 ${facts.spoken} 次,静默 ${facts.silent} 次。`);\n if (facts.silentTopReasons.length > 0) {\n lines.push(`静默主因:${facts.silentTopReasons.map((r) => `${r.reason}(${r.count})`).join('、')}。`);\n }\n if (facts.profileAdds.length > 0) {\n lines.push(`新认识 ${facts.profileAdds.length} 条:${facts.profileAdds.map((a) => a.content).join(';')}。`);\n }\n if (facts.ledger.added.length > 0 || facts.ledger.done.length > 0) {\n const parts: string[] = [];\n if (facts.ledger.added.length > 0) parts.push(`新增待办:${facts.ledger.added.join('、')}`);\n if (facts.ledger.done.length > 0) parts.push(`已解决:${facts.ledger.done.join('、')}`);\n lines.push(`${parts.join(';')}。`);\n }\n if (facts.ledger.stale.length > 0) {\n lines.push(`挂了很久:${facts.ledger.stale.map((s) => `${s.text}(${s.days} 天)`).join('、')}——要删掉还是继续挂着?`);\n }\n if (facts.seeds.added.length > 0) {\n lines.push(`素材池新增 ${facts.seeds.added.length} 条,已消费 ${facts.seeds.consumed.length} 条。`);\n }\n if (facts.seeds.waiting.length > 0) {\n lines.push(`还没聊过的素材:${facts.seeds.waiting.join('、')}。`);\n }\n if (facts.reports.total > 0) {\n const reasonPart = facts.reports.reasons.length > 0\n ? `(${facts.reports.reasons.map((r) => `${r.reason} ${r.count} 次`).join('、')})`\n : '';\n lines.push(`投递报账 ${facts.reports.total} 次:用素材 ${facts.reports.material}、说真心话 ${facts.reports.heartfelt}、没说话 ${facts.reports.silent}${reasonPart}。`);\n }\n // v1.9.0: unaccounted deliveries are reported even when no report landed at\n // all — a silent rise in \"no report\" is exactly what would otherwise hide.\n if (facts.reports.missing > 0) {\n lines.push(`另有 ${facts.reports.missing} 次投递没等到报账(这部分没算进偏好统计)。`);\n }\n if (facts.peakHours.length > 0) {\n lines.push(`活跃高峰:${facts.peakHours.join('、')}。`);\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAI3B,IAAM,SAAS;AAUR,SAAS,eAAe,SAAyB;AACtD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,UAAM,KAAK,4BAAQ,MAAM,QAAQ,KAAK,mCAAU,MAAM,QAAQ,QAAQ,kCAAS,MAAM,QAAQ,SAAS,4BAAQ,MAAM,QAAQ,MAAM,GAAG,UAAU,QAAG;AAAA,EACpJ;AAGA,MAAI,MAAM,QAAQ,UAAU,GAAG;AAC7B,UAAM,KAAK,gBAAM,MAAM,QAAQ,OAAO,iIAAwB;AAAA,EAChE;AACA,MAAI,MAAM,UAAU,SAAS,GAAG;AAC9B,UAAM,KAAK,iCAAQ,MAAM,UAAU,KAAK,QAAG,CAAC,QAAG;AAAA,EACjD;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["path","DAY_MS","path","path","path","path","path","fs","path","path","fs"]}
|
|
@@ -1 +0,0 @@
|
|
|
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// 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\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 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 (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 * 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 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,MAAM,IAAI,KAAK,MAAM;AACvD,QAAI,MAAM,YAAY,GAAG;AACvB,UAAI,CAAC,UAAU,MAAM,SAAS,YAAa;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,WAAW,MAAM,KAAK,IAAI,WAAW,OAAO,EAAG;AAChF,UAAM,MAAMA,MAAK,KAAK,SAAS,IAAI,MAAM,GAAG,EAAE,KAAKA,MAAK,GAAG,CAAC;AAC5D,QAAI;AACF,UAAI,iBAAiB,OAAO,GAAG,EAAG,QAAO;AAAA,IAC3C,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;","names":["fs","path","path","fs","fs","fs","path","walk","fs","path","MAGIC_V1","MAGIC_V2","path","fs","fs","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/path-guard.ts","../src/config/schema.ts","../src/config/load.ts","../src/excerpt/excerpt.ts","../src/core/preset-install.ts"],"sourcesContent":["// Path whitelist guard (requirement 8 / design doc §10.2).\n//\n// Every fs write/delete must have its target canonicalized first, then be\n// checked against the canonical workspace prefix with a separator boundary.\n// A raw startsWith check is bypassable via \"..\", symlinks/junctions, and\n// case variants; canonical realpath closes all of those on Windows.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport class PathOutsideWorkspaceError extends Error {\n constructor(target: string, workspace: string) {\n super(`path outside workspace: \"${target}\" (workspace: \"${workspace}\")`);\n this.name = 'PathOutsideWorkspaceError';\n }\n}\n\n/**\n * Resolve to an absolute canonical path. For targets that do not exist yet,\n * realpath the deepest existing ancestor and re-append the virtual tail, so\n * planned files under the workspace validate while `..` escapes still resolve\n * through the real filesystem.\n */\nexport function canonicalize(target: string): string {\n const abs = path.resolve(target);\n try {\n return fs.realpathSync(abs);\n } catch {\n // Walk up from the missing leaf, recording each missing component, until\n // an existing ancestor is found; re-append the missing tail afterwards.\n const tail: string[] = [];\n let dir = abs;\n for (;;) {\n const base = path.basename(dir);\n const parent = path.dirname(dir);\n if (parent === dir) {\n throw new Error(`cannot canonicalize \"${target}\": no existing ancestor`);\n }\n tail.push(base);\n dir = parent;\n try {\n const realDir = fs.realpathSync(dir);\n return path.join(realDir, ...tail.reverse());\n } catch {\n continue;\n }\n }\n }\n}\n\n/**\n * True when `targetCanon` equals the workspace dir or lies under it.\n * Comparison is case-insensitive (Windows filesystems) and requires a\n * separator boundary so `D:\\ws-data-evil` does not match workspace `D:\\ws-data`.\n */\nexport function isInsideWorkspace(workspaceCanon: string, targetCanon: string): boolean {\n const norm = (p: string) => {\n let n = path.normalize(p).toLowerCase();\n if (!n.endsWith(path.sep)) n += path.sep;\n return n;\n };\n const w = norm(workspaceCanon);\n const t = norm(targetCanon);\n return t === w || t.startsWith(w);\n}\n\nexport interface PathGuard {\n /** Canonical workspace boundary. */\n readonly workspace: string;\n /** Canonicalize then validate; returns the canonical path or throws. */\n assert(target: string): string;\n /** Canonicalize then validate; returns null instead of throwing. */\n check(target: string): string | null;\n}\n\nexport function createPathGuard(workspaceDir: string): PathGuard {\n const workspace = canonicalize(workspaceDir);\n const guard: PathGuard = {\n workspace,\n check(target: string): string | null {\n const canon = canonicalize(target);\n return isInsideWorkspace(workspace, canon) ? canon : null;\n },\n assert(target: string): string {\n const canon = guard.check(target);\n if (canon === null) throw new PathOutsideWorkspaceError(target, workspace);\n return canon;\n },\n };\n return guard;\n}\n","// Policy shape + runtime validation. Factory defaults live in config/policy.json\n// (read-only); the user layer in data/settings/policy.json overrides via deep\n// merge (design doc §13, D3).\n\nexport interface QuietHours {\n start: string; // \"HH:MM\"\n end: string; // \"HH:MM\"\n}\n\nexport interface BrowseWindow {\n start: string;\n end: string;\n}\n\nexport interface Policy {\n heartbeat: { intervalMin: number; idleMode: boolean; archiveRotatedHome: boolean };\n gate: {\n maxDailySend: number;\n cooldownMinutes: number;\n quietHours: QuietHours;\n };\n browse: {\n windows: BrowseWindow[];\n minIntervalHours: number;\n maxSeedsPerVisit: number;\n };\n seeds: {\n maxActive: number;\n ttlDays: { news: number; fandom: number; scene: number; promise: number };\n coldBenchDays: number;\n /** Archive-area cap (v1.9.0): gc trims archived seeds beyond this, oldest first. */\n archiveCap: number;\n retireAfterUsed: number;\n scoreWeights: { freshness: number; unused: number; confidence: number };\n };\n profile: {\n consolidation: { minIntervalHours: number; inboxBacklog: number };\n partitionCap: number;\n maxOpsPerRun: number;\n confidenceCap: { chat: number; screen: number; browse: number };\n volatileDays: number;\n stableLowActivityDays: number;\n psyEnabled: boolean;\n };\n /** Observation depth (v1.8.0): how much of each user message enters the inbox. */\n observe: { maxChars: number; perBeat: number };\n weekly: {\n enabled: boolean;\n /** v2.0 (item 5): how many past reports the store keeps and the card lists. */\n keepReports: number;\n };\n retention: { envPulseHours: number; decisionLogDays: number };\n}\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction fail(msg: string): never {\n throw new Error(`policy: ${msg}`);\n}\n\nexport function assertPolicy(input: unknown): asserts input is Policy {\n if (!isPlainObject(input)) fail('root must be an object');\n const p = input;\n const hb = p.heartbeat;\n if (!isPlainObject(hb)) fail('heartbeat missing');\n if (typeof hb.intervalMin !== 'number' || hb.intervalMin < 1 || hb.intervalMin > 1440) {\n fail('heartbeat.intervalMin must be a number in [1, 1440]');\n }\n if (typeof hb.idleMode !== 'boolean') fail('heartbeat.idleMode must be boolean');\n if (typeof hb.archiveRotatedHome !== 'boolean') fail('heartbeat.archiveRotatedHome must be boolean');\n const g = p.gate;\n if (!isPlainObject(g)) fail('gate missing');\n if (typeof g.maxDailySend !== 'number' || g.maxDailySend < 0) fail('gate.maxDailySend must be >= 0');\n if (typeof g.cooldownMinutes !== 'number' || g.cooldownMinutes < 0) fail('gate.cooldownMinutes must be >= 0');\n const qh = g.quietHours;\n if (!isPlainObject(qh)) fail('gate.quietHours missing');\n if (typeof qh.start !== 'string' || !HHMM.test(qh.start) || typeof qh.end !== 'string' || !HHMM.test(qh.end)) {\n fail('gate.quietHours must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n const b = p.browse;\n if (!isPlainObject(b)) fail('browse missing');\n if (!Array.isArray(b.windows) || b.windows.length === 0) fail('browse.windows must be a non-empty array');\n for (const w of b.windows) {\n if (!isPlainObject(w)) fail('browse.windows entries must be objects');\n if (typeof w.start !== 'string' || !HHMM.test(w.start) || typeof w.end !== 'string' || !HHMM.test(w.end)) {\n fail('browse.windows entries must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n }\n if (typeof b.minIntervalHours !== 'number' || b.minIntervalHours <= 0) fail('browse.minIntervalHours must be > 0');\n if (typeof b.maxSeedsPerVisit !== 'number' || b.maxSeedsPerVisit < 1) fail('browse.maxSeedsPerVisit must be >= 1');\n const s = p.seeds;\n if (!isPlainObject(s)) fail('seeds missing');\n if (typeof s.maxActive !== 'number' || s.maxActive < 1) fail('seeds.maxActive must be >= 1');\n if (!isPlainObject(s.ttlDays)) fail('seeds.ttlDays missing');\n for (const k of ['news', 'fandom', 'scene', 'promise'] as const) {\n if (typeof s.ttlDays[k] !== 'number') fail(`seeds.ttlDays.${k} missing`);\n }\n if (typeof s.coldBenchDays !== 'number') fail('seeds.coldBenchDays missing');\n if (typeof s.archiveCap !== 'number' || s.archiveCap < 1) fail('seeds.archiveCap must be >= 1');\n if (typeof s.retireAfterUsed !== 'number' || s.retireAfterUsed < 1) fail('seeds.retireAfterUsed must be >= 1');\n if (!isPlainObject(s.scoreWeights)) fail('seeds.scoreWeights missing');\n const pr = p.profile;\n if (!isPlainObject(pr)) fail('profile missing');\n const c = pr.consolidation;\n if (!isPlainObject(c)) fail('profile.consolidation missing');\n if (typeof c.minIntervalHours !== 'number' || typeof c.inboxBacklog !== 'number') fail('profile.consolidation fields missing');\n if (typeof pr.partitionCap !== 'number' || pr.partitionCap < 1) fail('profile.partitionCap must be >= 1');\n if (typeof pr.maxOpsPerRun !== 'number' || pr.maxOpsPerRun < 1) fail('profile.maxOpsPerRun must be >= 1');\n const cc = pr.confidenceCap;\n if (!isPlainObject(cc)) fail('profile.confidenceCap missing');\n if (typeof cc.chat !== 'number' || typeof cc.screen !== 'number' || typeof cc.browse !== 'number') {\n fail('profile.confidenceCap fields missing');\n }\n if (typeof pr.volatileDays !== 'number' || pr.volatileDays < 1) fail('profile.volatileDays must be >= 1');\n if (typeof pr.stableLowActivityDays !== 'number' || pr.stableLowActivityDays < 1) fail('profile.stableLowActivityDays must be >= 1');\n if (typeof pr.psyEnabled !== 'boolean') fail('profile.psyEnabled must be boolean');\n const ob = p.observe;\n if (!isPlainObject(ob)) fail('observe missing');\n if (typeof ob.maxChars !== 'number' || ob.maxChars < 20 || ob.maxChars > 2000) fail('observe.maxChars must be in [20, 2000]');\n if (typeof ob.perBeat !== 'number' || ob.perBeat < 1 || ob.perBeat > 100) fail('observe.perBeat must be in [1, 100]');\n if (!isPlainObject(p.weekly)) fail('weekly missing');\n if (typeof p.weekly.enabled !== 'boolean') fail('weekly.enabled must be boolean');\n if (typeof p.weekly.keepReports !== 'number' || p.weekly.keepReports < 1 || p.weekly.keepReports > 52) {\n fail('weekly.keepReports must be a number in [1, 52]');\n }\n const r = p.retention;\n if (!isPlainObject(r)) fail('retention missing');\n if (typeof r.envPulseHours !== 'number' || typeof r.decisionLogDays !== 'number') fail('retention fields missing');\n}\n\n/** Recursive merge: user values win; objects merge, arrays and scalars replace. */\nexport function deepMerge<T>(base: T, override: unknown): T {\n if (!isPlainObject(base) || !isPlainObject(override)) {\n return (override === undefined ? base : (override as T));\n }\n const out: Record<string, unknown> = { ...base };\n for (const [k, v] of Object.entries(override)) {\n out[k] = v === undefined ? (base as Record<string, unknown>)[k] : deepMerge((base as Record<string, unknown>)[k], v);\n }\n return out as T;\n}","// Two-layer policy loading (D3): factory defaults (config/policy.json, read-only)\n// + user layer (data/settings/policy.json). Missing user layer is normal; an\n// invalid factory file or user layer is fail-closed (throw at startup).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { assertPolicy, deepMerge, type Policy } from './schema.js';\nimport { atomicWriteFileSync } from '../core/atomic-fs.js';\n\nexport const USER_POLICY_FILE = 'policy.json';\n\nexport function loadPolicy(guard: PathGuard, configDir: string, settingsDir: string): Policy {\n const factoryPath = path.join(configDir, 'policy.json');\n let factoryRaw: unknown;\n try {\n factoryRaw = JSON.parse(fs.readFileSync(factoryPath, 'utf8'));\n } catch (e) {\n throw new Error(`factory policy unreadable at ${factoryPath}: ${String(e)}`);\n }\n assertPolicy(factoryRaw);\n\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let merged: Policy = factoryRaw;\n if (fs.existsSync(userPath)) {\n try {\n const userRaw: unknown = JSON.parse(fs.readFileSync(userPath, 'utf8'));\n merged = deepMerge(factoryRaw, userRaw);\n } catch (e) {\n throw new Error(`user policy layer unparseable at ${userPath}: ${String(e)}`);\n }\n }\n assertPolicy(merged);\n return merged;\n}\n\n/**\n * Merge `patch` into the user policy layer (data/settings/policy.json) without\n * touching the factory file. Used by the settings card for policy-backed\n * toggles (psyEnabled, v1.7.0). No full-Policy validation here: the layer is\n * merged over the factory and validated together at the next loadPolicy.\n */\nexport function updateUserPolicy(guard: PathGuard, settingsDir: string, patch: Record<string, unknown>): Record<string, unknown> {\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let user: Record<string, unknown> = {};\n try {\n user = JSON.parse(fs.readFileSync(userPath, 'utf8')) as Record<string, unknown>;\n if (!user || typeof user !== 'object' || Array.isArray(user)) user = {};\n } catch {\n user = {}; // fresh layer\n }\n const merged = deepMerge(user, patch) as Record<string, unknown>;\n fs.mkdirSync(path.dirname(userPath), { recursive: true });\n atomicWriteFileSync(userPath, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n","// Excerpt book (\"摘抄本\") - the place for lines worth keeping.\n//\n// Deliberately plaintext Markdown, like the ledger: a notebook that cannot be\n// read is not a notebook. The two plaintext files in data/ are the ledger\n// (his todos) and this one (her clippings); everything private stays in KHBV2\n// containers. The user may edit it by hand, so the parser is tolerant:\n// unrecognised 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';\n\nexport interface ExcerptEntry {\n id: string;\n date: string; // \"YYYY-MM-DD\"\n time: string; // \"HH:MM\"\n text: string;\n}\n\n/** Used both as the read fallback and as the file the settings card opens, so\n * a fresh notebook already carries the two lines that explain it. */\nexport const EXCERPT_HEADER = '# 摘抄本\\n\\n> 留句子和小事的地方。可以直接手编,改乱了也不影响:认不出的行会原样留着。\\n\\n';\n\nexport function excerptFilePath(dataDir: string): string {\n return path.join(dataDir, 'excerpts.md');\n}\n\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[#([0-9a-f]{6})\\] (.*)$/;\n\nfunction renderEntry(e: ExcerptEntry): string {\n return `- [${e.date} ${e.time}][#${e.id}] ${e.text}`;\n}\n\nexport function readExcerpts(guard: PathGuard, file: string): { entries: ExcerptEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, EXCERPT_HEADER);\n const rawLines: string[] = [];\n const entries: ExcerptEntry[] = [];\n for (const line of raw.split('\\n')) {\n const m = LINE_RE.exec(line);\n if (m) entries.push({ date: m[1]!, time: m[2]!, id: m[3]!, text: m[4]! });\n rawLines.push(line);\n }\n return { entries, rawLines };\n}\n\n/** Append one clipping, stamped with the local wall clock (like the ledger). */\nexport function appendExcerpt(guard: PathGuard, file: string, text: string, now = Date.now()): ExcerptEntry {\n const trimmed = text.trim();\n if (!trimmed) throw new Error('excerpt must not be empty');\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const entry: ExcerptEntry = {\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 text: trimmed.replace(/\\r?\\n/g, ' '),\n };\n const { rawLines } = readExcerpts(guard, file);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n}\n\n/** Tear one page out by id (preferred) or unique text substring. Unlike the\n * ledger there is no done-state: a clipping either stays or is gone. */\nexport function removeExcerpt(guard: PathGuard, file: string, key: string): ExcerptEntry | null {\n const { rawLines, entries } = readExcerpts(guard, file);\n const target = entries.find((e) => e.id === key || e.text.includes(key));\n if (!target) return null;\n const out = rawLines.filter((line) => !line.startsWith(`- [${target.date} ${target.time}][#${target.id}] `));\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return target;\n}\n\n/** The tail of the notebook, oldest-first among the newest `limit` entries. */\nexport function recentExcerpts(guard: PathGuard, file: string, limit: number): ExcerptEntry[] {\n const { entries } = readExcerpts(guard, file);\n return limit > 0 ? entries.slice(-limit) : [];\n}\n","// Bundled agent-preset installation (contract C13).\n//\n// Why this exists: the heartbeat agent is created by the host `agents` service,\n// which does NOT go through the session-start preset picker. A bare agent joins\n// no preset, and dsh-agent-presets states the consequence verbatim — \"its tools,\n// prompt sections, and skill catalog resolve against the empty global layer\" —\n// so it cannot even see `web_search`. The preset is therefore not optional, and\n// asking the operator to hand-copy two YAML files was the most error-prone step\n// of setup. The plugin now materialises its own bundled template in the roster's\n// USER root on first run.\n//\n// Two properties keep that safe:\n// 1. An existing preset is NEVER overwritten — the composition file belongs to\n// whoever edited it. Only a missing (or ghost) directory is filled in.\n// 2. The target comes from the roster's OWN roots (`agentPresets.roots`,\n// trust === \"user\") rather than a guessed `~/.dsh`, so `$DSH_HOME` and a\n// configured home are honoured without re-deriving them here.\n//\n// Timing: dsh-agent-presets re-scans the filesystem on every read\n// (`list()` -> `discoverPresets` -> `scanRoot`, no cache), so a directory\n// created here is visible to the very next `mount()` — no restart in between.\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport const COMPOSITION_FILE = 'agent.cordis.yml';\nexport const METADATA_FILE = 'preset.yml';\n/** The template this package ships, in `assets/presets/<id>/`. */\nexport const BUNDLED_PRESET_ID = 'heartbeat';\n\n/** One entry of the roster's root list (`AgentPresets.roots`). */\nexport interface PresetRootLike {\n path?: string;\n trust?: string;\n}\n\nexport type PresetInstallAction =\n | 'exists'\n | 'created'\n | 'repaired'\n | 'restored'\n | 'skipped-disabled'\n | 'skipped-custom-id'\n | 'skipped-no-root'\n | 'error';\n\nexport interface PresetInstallResult {\n action: PresetInstallAction;\n id: string;\n /** Where the preset lives (or would live). */\n dir?: string;\n /** Where the bundled template was read from. */\n bundledDir?: string;\n detail?: string;\n}\n\n/**\n * Locate the bundled template directory by walking up from a module URL.\n * Works from both entry points (`dist/index.js` and `dist/cli/index.js`) and\n * from the pnpm copy of an installed package.\n */\nexport function bundledPresetDir(\n moduleUrl: string,\n id: string = BUNDLED_PRESET_ID,\n): string | undefined {\n let dir: string;\n try {\n dir = path.dirname(fileURLToPath(moduleUrl));\n } catch {\n return undefined;\n }\n for (let depth = 0; depth < 5; depth += 1) {\n const candidate = path.join(dir, 'assets', 'presets', id);\n if (fs.existsSync(path.join(candidate, COMPOSITION_FILE))) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/** The roster's user-trust root, which is where locally authored presets live. */\nexport function userPresetRoot(roots?: readonly PresetRootLike[]): string | undefined {\n const found = roots?.find(\n (root) => root?.trust === 'user' && typeof root.path === 'string' && root.path.length > 0,\n );\n return found?.path === undefined ? undefined : path.resolve(found.path);\n}\n\n/**\n * `<dshHome>/.agent-presets` derived from the documented precedence\n * (`$DSH_HOME`, then `~/.dsh`). Only used where no roster is available — the\n * plugin itself prefers {@link userPresetRoot}.\n */\nexport function conventionalUserPresetRoot(\n env: NodeJS.ProcessEnv = process.env,\n home: string = os.homedir(),\n): string {\n const override = env.DSH_HOME?.trim();\n const root = override && override.length > 0 ? override : path.join(home, '.dsh');\n return path.join(root, '.agent-presets');\n}\n\nexport interface InstallPresetOptions {\n /** `import.meta.url` of the calling entry point. */\n moduleUrl: string;\n /** Preset id the heartbeat agent will join (config `agentPreset`). */\n id?: string;\n /** User-trust root reported by the roster. */\n root?: string;\n /** True when the roster answered — then an absent user root is a fact, not a guess. */\n rosterKnown?: boolean;\n /** `false` disables the install (config `installPreset`). */\n enabled?: boolean;\n /** Overwrite an existing composition file with the bundled one. */\n force?: boolean;\n}\n\n/**\n * Materialise the bundled preset in the roster's user root when it is absent.\n * Never destructive: an existing composition file is kept unless `force`.\n */\nexport function installBundledPreset(options: InstallPresetOptions): PresetInstallResult {\n const id = options.id && options.id.length > 0 ? options.id : BUNDLED_PRESET_ID;\n if (options.enabled === false) {\n return { action: 'skipped-disabled', id, detail: 'installPreset=false' };\n }\n const bundledDir = bundledPresetDir(options.moduleUrl, BUNDLED_PRESET_ID);\n if (id !== BUNDLED_PRESET_ID) {\n return {\n action: 'skipped-custom-id',\n id,\n ...(bundledDir === undefined ? {} : { bundledDir }),\n detail: `only \"${BUNDLED_PRESET_ID}\" ships with the plugin; \"${id}\" is yours to provide`,\n };\n }\n if (bundledDir === undefined) {\n return {\n action: 'error',\n id,\n detail: 'bundled template not found next to the plugin (assets/presets/heartbeat)',\n };\n }\n const root =\n options.root ?? (options.rosterKnown ? undefined : conventionalUserPresetRoot());\n if (root === undefined) {\n return {\n action: 'skipped-no-root',\n id,\n bundledDir,\n detail: 'the roster mounts no user preset root (includeUserRoot=false)',\n };\n }\n const dir = path.join(root, id);\n const composition = path.join(dir, COMPOSITION_FILE);\n try {\n if (fs.existsSync(composition)) {\n if (options.force !== true) {\n const drifted = !sameBytes(composition, path.join(bundledDir, COMPOSITION_FILE));\n return {\n action: 'exists',\n id,\n dir,\n bundledDir,\n detail: drifted ? 'kept as-is (differs from the bundled template)' : 'kept as-is',\n };\n }\n fs.copyFileSync(path.join(bundledDir, COMPOSITION_FILE), composition);\n return {\n action: 'restored',\n id,\n dir,\n bundledDir,\n detail: 'composition replaced from the bundled template',\n };\n }\n const existed = fs.existsSync(dir);\n fs.mkdirSync(dir, { recursive: true });\n fs.copyFileSync(path.join(bundledDir, COMPOSITION_FILE), composition);\n const metadata = path.join(dir, METADATA_FILE);\n // A directory with a composition but no metadata is legal; only fill a void.\n if (!fs.existsSync(metadata)) fs.copyFileSync(path.join(bundledDir, METADATA_FILE), metadata);\n return {\n action: existed ? 'repaired' : 'created',\n id,\n dir,\n bundledDir,\n detail: existed\n ? 'directory existed without a composition file (it occupied the id as a broken row)'\n : undefined,\n };\n } catch (error) {\n return { action: 'error', id, dir, bundledDir, detail: String(error).slice(0, 200) };\n }\n}\n\n/** One line suitable for the audit log and `ctx.logger`. */\nexport function describeInstall(result: PresetInstallResult): string {\n const where = result.dir === undefined ? '' : ` (${result.dir})`;\n const why = result.detail === undefined ? '' : ` — ${result.detail}`;\n return `preset ${result.id} ${result.action}${where}${why}`;\n}\n\nexport interface PresetStatus {\n id: string;\n dir: string;\n bundledDir?: string;\n installed: boolean;\n compositionMatches: boolean;\n metadataMatches: boolean;\n}\n\n/** Read-only inspection for the CLI (`preset status`). */\nexport function presetStatus(\n moduleUrl: string,\n id: string = BUNDLED_PRESET_ID,\n root: string = conventionalUserPresetRoot(),\n): PresetStatus {\n const dir = path.join(root, id);\n const bundledDir = bundledPresetDir(moduleUrl, id);\n const installed = fs.existsSync(path.join(dir, COMPOSITION_FILE));\n return {\n id,\n dir,\n ...(bundledDir === undefined ? {} : { bundledDir }),\n installed,\n compositionMatches:\n installed && bundledDir !== undefined && sameBytes(path.join(dir, COMPOSITION_FILE), path.join(bundledDir, COMPOSITION_FILE)),\n metadataMatches:\n bundledDir !== undefined &&\n fs.existsSync(path.join(dir, METADATA_FILE)) &&\n sameBytes(path.join(dir, METADATA_FILE), path.join(bundledDir, METADATA_FILE)),\n };\n}\n\nfunction sameBytes(left: string, right: string): boolean {\n try {\n return fs.readFileSync(left).equals(fs.readFileSync(right));\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;AAOA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEV,IAAM,4BAAN,cAAw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A,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["fs","path","path","fs","path","path","fs","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/seeds/pool.ts","../src/seeds/types.ts"],"sourcesContent":["// Material pool engine (design doc §4). All four eviction rules are\n// deterministic code - no LLM involvement (§4.2). Storage: data/seeds.jsonl,\n// one seed per JSON line, DPAPI-encrypted at rest (D14).\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport { withFileLock } from '../core/file-lock.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n SEED_SOURCE_DEFAULT_CONFIDENCE,\n emptySeedDb,\n type Seed,\n type SeedCategory,\n type SeedDb,\n type SeedRetireReason,\n type SeedSource,\n type SeedTag,\n} from './types.js';\n\nconst DAY_MS = 86_400_000;\n\n// ── lifecycle audit (2026-10-06 / v1.9.0) ───────────────────────────────\n// The pool used to mutate in silence: a seed could appear, be evicted for\n// capacity, or be dropped from the archive with nothing in the log. Every\n// mutator now takes an optional sink and reports what it did. IDs and\n// metadata ONLY — heartbeat.jsonl is plaintext by charter and must never\n// carry conversation text; the seed text itself stays in the DPAPI pool.\nexport type SeedAuditFn = (entry: Record<string, unknown>) => void;\n\nconst NO_AUDIT: SeedAuditFn = () => {};\n\n/** Audit must never break the pool (or the beat that called it). */\nfunction emit(audit: SeedAuditFn, entry: Record<string, unknown>): void {\n try {\n audit(entry);\n } catch {\n /* audit is diagnostic; a failed append is not a pool failure */\n }\n}\n\n// Per-category pool caps (2026-09-18 spec ⑤): topic stock vs conversation-grown\n// chat material, decoupled from `source`; sum == the global maxActive default.\nexport const SEED_CATEGORY_CAPS: Record<SeedCategory, number> = { topic: 16, chat: 14 };\n\nconst CATEGORY_VALUES: readonly string[] = ['topic', 'chat'];\n\n/** Lenient category coercion for on-disk rows: anything missing/unknown (all\n * pre-v1.5 seeds) counts as topic stock. */\nexport function normalizeCategory(v: unknown): SeedCategory {\n return typeof v === 'string' && (CATEGORY_VALUES as readonly string[]).includes(v)\n ? (v as SeedCategory)\n : 'topic';\n}\n\nexport interface AddSeedInput {\n text: string;\n topic?: string;\n tag?: SeedTag;\n source?: SeedSource;\n /** Loop role (spec ⑤); defaults from source: chat->chat, everything else->topic. */\n category?: SeedCategory;\n confidence?: number;\n}\n\nexport interface AddSeedResult {\n kind: 'added' | 'merged' | 'duplicate';\n seed: Seed;\n evicted?: Seed;\n}\n\nexport interface GcReport {\n consumed: number;\n expired: number;\n coldBench: number;\n activeAfter: number;\n /** v1.9.0: archived rows dropped to honor seeds.archiveCap (oldest first). */\n archiveTrimmed: number;\n}\n\nexport const TTL_KEYS: readonly SeedTag[] = ['news', 'fandom', 'scene', 'promise'];\n\nexport function normalizeTag(tag: string | undefined): SeedTag {\n if (tag && (TTL_KEYS as readonly string[]).includes(tag)) return tag as SeedTag;\n return 'scene';\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n// ── storage ─────────────────────────────────────────────────────────────\n\nexport function seedsFilePath(dataDir: string): string {\n return path.join(dataDir, 'seeds.jsonl');\n}\n\nexport function loadPool(guard: PathGuard, file: string): SeedDb {\n const raw = loadEncryptedText(guard, file);\n if (raw === null) return emptySeedDb();\n const db = emptySeedDb();\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obj = JSON.parse(trimmed) as Seed;\n if (typeof obj.id === 'string' && obj.id.startsWith('s')) {\n // spec ⑤ loadPool tolerance: only the id is load-bearing; a missing or\n // unknown category (every pre-v1.5 row) falls back to topic stock.\n obj.category = normalizeCategory(obj.category);\n db.seeds.push(obj);\n const n = Number(obj.id.slice(1));\n if (Number.isFinite(n) && n > db.seq) db.seq = n;\n }\n } catch {\n // corrupt line: skip (pool is a cache; journal-level audit lives elsewhere)\n }\n }\n return db;\n}\n\nexport function savePool(guard: PathGuard, file: string, db: SeedDb): void {\n const body = db.seeds.map((s) => JSON.stringify(s)).join('\\n');\n saveEncryptedText(guard, file, body ? body + '\\n' : '');\n}\n\n/**\n * H-20 (minimal tier): every pool writer goes through here, so the load happens\n * INSIDE the cross-process lock and cannot be based on a read that went stale\n * while it was being mutated — the CLI is a second process sharing this file,\n * and an interleaved write used to be silently overwritten. The ciphertext is a\n * whole-file rewrite, so append/merge does not apply here; the append-only pool\n * with compaction is v2.0 work (ledger #8649f9).\n */\nfunction update<T>(guard: PathGuard, file: string, fn: (db: SeedDb) => T): T {\n return withFileLock(file, () => fn(loadPool(guard, file)));\n}\n\n// ── queries ─────────────────────────────────────────────────────────────\n\nexport const activeSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'active');\nexport const archivedSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'archived');\n\n// ── eviction scoring (rule 4) ───────────────────────────────────────────\n\n/**\n * Comprehensive score (§4.2): freshness x0.4 + unused x0.3 + confidence x0.3.\n * Higher = keep. Lowest-scoring active is evicted when the pool is full.\n */\nexport function evictionScore(seed: Seed, policy: Policy, now: number): number {\n const ttlDays = policy.seeds.ttlDays[seed.tag] || 14;\n const daysStale = Math.max(0, (now - parseIso(seed.lastEvidenceAt)) / DAY_MS);\n const freshness = Math.max(0, 1 - daysStale / ttlDays);\n const unused = seed.used === 0 ? 1 : 1 / seed.used;\n const w = policy.seeds.scoreWeights;\n return freshness * w.freshness + unused * w.unused + seed.confidence * w.confidence;\n}\n\n/** Pick the eviction victim: unprotected actives first (§4.2 加权保护); with\n * `category`, only that category's actives compete (spec ⑤ per-category caps). */\nexport function pickEvictionVictim(db: SeedDb, policy: Policy, now: number, category?: SeedCategory): Seed | null {\n const actives = activeSeeds(db).filter((s) => category === undefined || normalizeCategory(s.category) === category);\n if (actives.length === 0) return null;\n const unprotected = actives.filter((s) => !s.protected);\n const candidates = unprotected.length > 0 ? unprotected : actives;\n let worst: Seed | null = null;\n let worstScore = Number.POSITIVE_INFINITY;\n for (const s of candidates) {\n const score = evictionScore(s, policy, now);\n if (score < worstScore) {\n worstScore = score;\n worst = s;\n }\n }\n return worst;\n}\n\nfunction archiveSeed(seed: Seed, reason: SeedRetireReason, now: number): void {\n seed.status = 'archived';\n seed.retireReason = reason;\n seed.retiredAt = new Date(now).toISOString();\n}\n\n/** Spec ④: chat-grown material is consumed ONCE (conversation freshness);\n * every other category follows the policy-wide retireAfterUsed. */\nfunction retireLimit(s: Seed, policy: Policy): number {\n return normalizeCategory(s.category) === 'chat' ? 1 : policy.seeds.retireAfterUsed;\n}\n\n/**\n * Rule 1 (§4.2): used up to its limit AND no evidence newer than the PREVIOUS\n * use. `prevUsedAt` MUST be read before bumping `lastUsedAt` — comparing the\n * just-written value against `lastEvidenceAt` is vacuously true (H-22), which\n * retired seeds that had received fresh evidence in the same beat. Both\n * callers (gc and surface) share this, so the rule cannot drift again.\n *\n * `prevUsedAt === 0` means \"never used before\": there is no earlier use for\n * the evidence to be newer THAN, so the exemption cannot apply — a one-shot\n * (chat) seed still retires on its first surfacing (spec ④), which is the\n * contract, not a regression.\n */\nfunction isConsumed(s: Seed, policy: Policy, prevUsedAt: number, sinceEvidence: number): boolean {\n if (s.used < retireLimit(s, policy)) return false;\n return !(prevUsedAt > 0 && sinceEvidence > prevUsedAt);\n}\n\n// ── operations ──────────────────────────────────────────────────────────\n\nexport function addSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): AddSeedResult {\n // H-20: the read-modify-write below runs under the cross-process pool lock\n // (same guard as `update`, kept as a named body to avoid re-indenting it).\n return withFileLock(file, () => addSeedLocked(guard, file, policy, input, now, audit));\n}\n\nfunction addSeedLocked(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now: number,\n audit: SeedAuditFn,\n): AddSeedResult {\n const db = loadPool(guard, file);\n const text = input.text.trim();\n if (!text) throw new Error('seed text must not be empty');\n const tag = normalizeTag(input.tag);\n const source: SeedSource = input.source ?? 'chat';\n const category = normalizeCategory(input.category ?? (source === 'chat' ? 'chat' : 'topic'));\n const confidence = input.confidence ?? SEED_SOURCE_DEFAULT_CONFIDENCE[source];\n\n // Exact-text dedup against actives.\n const dup = activeSeeds(db).find((s) => s.text === text);\n if (dup) return { kind: 'duplicate', seed: dup };\n\n const nowIso = new Date(now).toISOString();\n const ttlMs = (policy.seeds.ttlDays[tag] || 14) * DAY_MS;\n\n // Same-topic merge (§4.3): collapse all same-topic actives + the new item.\n const sameTopic = activeSeeds(db).filter((s) => s.topic === (input.topic ?? text.slice(0, 24)));\n let seed: Seed;\n if (sameTopic.length > 0) {\n const kept = sameTopic[0]!;\n kept.text = text; // brief takes the latest\n kept.tag = tag;\n kept.source = source;\n kept.category = normalizeCategory(input.category ?? kept.category ?? category);\n kept.confidence = Math.max(kept.confidence, confidence);\n kept.used = sameTopic.reduce((acc, s) => acc + s.used, 0); // used accumulates\n kept.lastEvidenceAt = [kept.lastEvidenceAt, nowIso, ...sameTopic.map((s) => s.lastEvidenceAt)]\n .reduce((a, b) => (parseIso(b) > parseIso(a) ? b : a));\n kept.expiresAt = new Date(Math.max(parseIso(kept.expiresAt), now + ttlMs)).toISOString();\n kept.protected = kept.protected || source === 'hand' || (source === 'profile' && confidence >= 0.7);\n // remove the other same-topic actives (merged into kept)\n for (const extra of sameTopic.slice(1)) {\n extra.status = 'archived';\n extra.retireReason = 'completed';\n extra.retiredAt = nowIso;\n emit(audit, { event: 'seed_retired', id: extra.id, reason: 'completed', via: 'merge', into: kept.id });\n }\n seed = kept;\n // capacity still applies after growth check below if kept is somehow over cap\n if (activeSeeds(db).length > policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, normalizeCategory(kept.category));\n if (victim && victim.id !== kept.id) {\n archiveSeed(victim, 'pool_cap', now);\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n emit(audit, { event: 'seed_retired', id: victim.id, reason: 'pool_cap', via: 'merge', into: kept.id });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept, evicted: victim };\n }\n }\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept };\n }\n\n // Capacity first (rules 4 + spec ⑤): per-category cap evicts within its own\n // pool; the global cap evicts in the incoming seed's category (a full topic\n // stock must not push chat material out and vice versa).\n let evicted: Seed | undefined;\n const catCount = activeSeeds(db).filter((s) => normalizeCategory(s.category) === category).length;\n if (catCount >= SEED_CATEGORY_CAPS[category]) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = victim;\n }\n }\n if (activeSeeds(db).length >= policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = evicted ?? victim;\n }\n }\n\n db.seq += 1;\n seed = {\n id: `s${db.seq}`,\n text,\n topic: input.topic ?? text.slice(0, 24),\n tag,\n source,\n category,\n confidence,\n protected: source === 'hand' || (source === 'profile' && confidence >= 0.7),\n used: 0,\n bornAt: nowIso,\n expiresAt: new Date(now + ttlMs).toISOString(),\n lastUsedAt: null,\n lastEvidenceAt: nowIso,\n status: 'active',\n };\n db.seeds.push(seed);\n emit(audit, { event: 'seed_added', id: seed.id, kind: 'added', tag: seed.tag, source: seed.source, category: seed.category, confidence: seed.confidence });\n if (evicted) emit(audit, { event: 'seed_retired', id: evicted.id, reason: 'pool_cap', via: 'add', into: seed.id });\n savePool(guard, file, db);\n return { kind: 'added', seed, evicted };\n}\n\n/**\n * Deterministic gc (rules 1-3 of §4.2). Rule 4 (pool cap) fires on add only.\n * v1.9.0: the archive area is ALSO capped (seeds.archiveCap) — the archive is\n * a forensic trail, not a hoard; trim oldest-retired first.\n */\nexport function gcPool(guard: PathGuard, file: string, policy: Policy, now = Date.now(), audit: SeedAuditFn = NO_AUDIT): GcReport {\n return update(guard, file, (db) => {\n const report: GcReport = { consumed: 0, expired: 0, coldBench: 0, activeAfter: 0, archiveTrimmed: 0 };\n for (const s of activeSeeds(db)) {\n const ageMs = now - parseIso(s.bornAt);\n const sinceEvidence = parseIso(s.lastEvidenceAt);\n const sinceUsed = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n if (isConsumed(s, policy, sinceUsed, sinceEvidence)) {\n archiveSeed(s, 'consumed', now);\n report.consumed += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'gc', used: s.used });\n } else if (now > parseIso(s.expiresAt)) {\n archiveSeed(s, 'expired', now);\n report.expired += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'expired', via: 'gc', used: s.used });\n } else if (s.used === 0 && ageMs >= policy.seeds.coldBenchDays * DAY_MS) {\n archiveSeed(s, 'cold_bench', now);\n report.coldBench += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'cold_bench', via: 'gc', used: s.used });\n }\n }\n // archive cap: drop the oldest-retired rows beyond the cap (retiredAt may be\n // missing on pre-v1.5 rows — parseIso('') = 0 sorts them oldest).\n const archived = db.seeds.filter((s) => s.status === 'archived');\n if (archived.length > policy.seeds.archiveCap) {\n const drop = [...archived]\n .sort((a, b) => parseIso(a.retiredAt ?? '') - parseIso(b.retiredAt ?? ''))\n .slice(0, archived.length - policy.seeds.archiveCap);\n const dropped = new Set(drop.map((s) => s.id));\n db.seeds = db.seeds.filter((s) => !dropped.has(s.id));\n report.archiveTrimmed = drop.length;\n // These rows are GONE (not archived — deleted): the log is the only trace\n // left, so name them. IDs only, and cap the list in case a first GC trims\n // a legacy archive wholesale.\n emit(audit, { event: 'seed_archive_trimmed', count: drop.length, ids: drop.slice(0, 50).map((s) => s.id) });\n }\n report.activeAfter = activeSeeds(db).length;\n savePool(guard, file, db);\n return report;\n });\n}\n\n/** The seed surfaced in a real expression: count + maybe retire (rule 1). */\nexport function surfaceSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n // H-22: snapshot the PREVIOUS use time before bumping it — the retirement\n // check must compare against the last use, not against this one.\n const prevUsedAt = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n s.used += 1;\n s.lastUsedAt = new Date(now).toISOString();\n if (isConsumed(s, policy, prevUsedAt, parseIso(s.lastEvidenceAt))) {\n archiveSeed(s, 'consumed', now);\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'surface', used: s.used });\n }\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Deliberate retirement (item completed / no longer relevant). */\nexport function archiveSeedById(\n guard: PathGuard,\n file: string,\n id: string,\n reason: SeedRetireReason = 'completed',\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n archiveSeed(s, reason, now);\n emit(audit, { event: 'seed_retired', id: s.id, reason, via: 'manual' });\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Restore an archived seed to the active pool (UI operation; resets TTL). */\nexport function restoreSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): { ok: true; seed: Seed } | { ok: false; reason: string } {\n return update<{ ok: true; seed: Seed } | { ok: false; reason: string }>(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'archived');\n if (!s) return { ok: false, reason: 'archived seed not found' };\n // H-23: a restore must satisfy the same two caps an add does — the global\n // one AND the per-category one. The add path evicts a neighbour instead, but\n // restoring a memory is a user action: refuse it rather than silently\n // pushing someone else's material out.\n const category = normalizeCategory(s.category);\n const catCap = SEED_CATEGORY_CAPS[category];\n const inCategory = activeSeeds(db).filter((x) => normalizeCategory(x.category) === category).length;\n if (inCategory >= catCap) {\n return { ok: false, reason: `category full (${category}: ${catCap}); archive something in it first` };\n }\n if (activeSeeds(db).length >= policy.seeds.maxActive) {\n return { ok: false, reason: `pool full (${policy.seeds.maxActive}); archive something first` };\n }\n s.status = 'active';\n s.retireReason = undefined;\n s.retiredAt = undefined;\n // H-23: reset bornAt as well — cold-bench eviction (used === 0 && age >=\n // coldBenchDays) keys off bornAt, so a restored seed used to be re-archived\n // by the very next maintenance beat (\"restored, then gone one beat later\").\n s.bornAt = new Date(now).toISOString();\n s.expiresAt = new Date(now + (policy.seeds.ttlDays[s.tag] || 14) * DAY_MS).toISOString();\n s.lastEvidenceAt = new Date(now).toISOString();\n emit(audit, { event: 'seed_restored', id: s.id });\n savePool(guard, file, db);\n return { ok: true, seed: s };\n });\n}\n\n/** Hard delete (UI explicit action with confirm; the caller audits it). */\nexport function deleteSeed(guard: PathGuard, file: string, id: string, audit: SeedAuditFn = NO_AUDIT): boolean {\n return update(guard, file, (db) => {\n const before = db.seeds.length;\n db.seeds = db.seeds.filter((x) => x.id !== id);\n if (db.seeds.length === before) return false;\n emit(audit, { event: 'seed_deleted', id });\n savePool(guard, file, db);\n return true;\n });\n}\n","// Material pool (\"素材池\") types. Charter (axiom 3): this pool is a CACHE,\n// not memory - volatile, evictable, burnable; long-term memory only absorbs\n// conversation-validated content. Everything here may be destroyed.\n\nexport type SeedTag = 'news' | 'fandom' | 'scene' | 'promise';\nexport type SeedSource = 'chat' | 'screen' | 'browse' | 'hand' | 'profile';\nexport type SeedCategory = 'topic' | 'chat';\nexport type SeedRetireReason = 'consumed' | 'expired' | 'cold_bench' | 'pool_cap' | 'completed';\n\nexport interface Seed {\n id: string;\n /** Short brief shown to the reflection prompt. */\n text: string;\n /** Merge key (§4.3): same-topic actives collapse into one. */\n topic: string;\n tag: SeedTag;\n source: SeedSource;\n /** Loop role, decoupled from source (2026-09-18 spec ⑤): 'topic' = wander/\n * hand/profile stock (random pick), 'chat' = conversation-grown, consumed\n * once. Absent on pre-v1.5 rows; loadPool defaults them to 'topic'. */\n category?: SeedCategory;\n /** 0..1 trust level; handwriting and high-confidence profile sources gain eviction protection. */\n confidence: number;\n /** Eviction protection (§4.2 pool-cap rule): handwritten / high-confidence profile sources. */\n protected: boolean;\n /** Times this seed surfaced in an actual expression. */\n used: number;\n bornAt: string;\n /** bornAt + ttlDays[tag]; archived when passed (rule 2). */\n expiresAt: string;\n lastUsedAt: string | null;\n /** Fresh-evidence watermark: rule 1 spares seeds with evidence newer than last use. */\n lastEvidenceAt: string;\n status: 'active' | 'archived';\n retireReason?: SeedRetireReason;\n retiredAt?: string;\n}\n\nexport interface SeedDb {\n seq: number;\n seeds: Seed[];\n}\n\nexport function emptySeedDb(): SeedDb {\n return { seq: 0, seeds: [] };\n}\n\nexport const SEED_SOURCE_DEFAULT_CONFIDENCE: Record<SeedSource, number> = {\n hand: 1.0,\n profile: 0.7,\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n};\n"],"mappings":";;;;;;;AAIA,OAAO,UAAU;;;ACuCV,SAAS,cAAsB;AACpC,SAAO,EAAE,KAAK,GAAG,OAAO,CAAC,EAAE;AAC7B;AAEO,IAAM,iCAA6D;AAAA,EACxE,MAAM;AAAA,EACN,SAAS;AAAA,EACT,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AACV;;;ADjCA,IAAM,SAAS;AAUf,IAAM,WAAwB,MAAM;AAAC;AAGrC,SAAS,KAAK,OAAoB,OAAsC;AACtE,MAAI;AACF,UAAM,KAAK;AAAA,EACb,QAAQ;AAAA,EAER;AACF;AAIO,IAAM,qBAAmD,EAAE,OAAO,IAAI,MAAM,GAAG;AAEtF,IAAM,kBAAqC,CAAC,SAAS,MAAM;AAIpD,SAAS,kBAAkB,GAA0B;AAC1D,SAAO,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ACA,QAAI,YAAY,EAAE,EAAE,UAAU,OAAO,MAAM,WAAW;AACpD,aAAO,EAAE,IAAI,OAAO,QAAQ,cAAc,OAAO,MAAM,SAAS,6BAA6B;AAAA,IAC/F;AACA,MAAE,SAAS;AACX,MAAE,eAAe;AACjB,MAAE,YAAY;AAId,MAAE,SAAS,IAAI,KAAK,GAAG,EAAE,YAAY;AACrC,MAAE,YAAY,IAAI,KAAK,OAAO,OAAO,MAAM,QAAQ,EAAE,GAAG,KAAK,MAAM,MAAM,EAAE,YAAY;AACvF,MAAE,iBAAiB,IAAI,KAAK,GAAG,EAAE,YAAY;AAC7C,SAAK,OAAO,EAAE,OAAO,iBAAiB,IAAI,EAAE,GAAG,CAAC;AAChD,aAAS,OAAO,MAAM,EAAE;AACxB,WAAO,EAAE,IAAI,MAAM,MAAM,EAAE;AAAA,EAC3B,CAAC;AACH;AAGO,SAAS,WAAW,OAAkB,MAAc,IAAY,QAAqB,UAAmB;AAC7G,SAAO,OAAO,OAAO,MAAM,CAAC,OAAO;AACjC,UAAM,SAAS,GAAG,MAAM;AACxB,OAAG,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE;AAC7C,QAAI,GAAG,MAAM,WAAW,OAAQ,QAAO;AACvC,SAAK,OAAO,EAAE,OAAO,gBAAgB,GAAG,CAAC;AACzC,aAAS,OAAO,MAAM,EAAE;AACxB,WAAO;AAAA,EACT,CAAC;AACH;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|