@kanadego/dsh-heartbeat 1.7.4 → 1.8.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 +33 -12
- package/client.js +93 -0
- package/config/policy.json +9 -1
- package/dist/{chunk-4UE74TUB.js → chunk-63FUJLIF.js} +2 -2
- package/dist/{chunk-LLD7LUNN.js → chunk-IFTFDHZX.js} +2 -1
- package/dist/{chunk-SVP2NDRF.js → chunk-MXJPX3FM.js} +2 -2
- package/dist/chunk-RB3NLLGF.js +87 -0
- package/dist/chunk-RB3NLLGF.js.map +1 -0
- package/dist/{chunk-ON4MSU6E.js → chunk-SQJLKP7L.js} +175 -477
- package/dist/chunk-SQJLKP7L.js.map +1 -0
- package/dist/chunk-UCJR6TC7.js +163 -0
- package/dist/chunk-UCJR6TC7.js.map +1 -0
- package/dist/chunk-VIZNIQLK.js +472 -0
- package/dist/chunk-VIZNIQLK.js.map +1 -0
- package/dist/cli/index.js +138 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/{inbox-MMLHISQV.js → inbox-57NHQHY3.js} +3 -3
- package/dist/index.js +416 -48
- package/dist/index.js.map +1 -1
- package/dist/migrate-43PUK25G.js +20 -0
- package/dist/{pool-YAIBE2L5.js → pool-JQC5JWIZ.js} +3 -3
- package/dist/pool-JQC5JWIZ.js.map +1 -0
- package/dist/snapshot-ZBCSX67Y.js +15 -0
- package/dist/snapshot-ZBCSX67Y.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-ON4MSU6E.js.map +0 -1
- /package/dist/{chunk-4UE74TUB.js.map → chunk-63FUJLIF.js.map} +0 -0
- /package/dist/{chunk-LLD7LUNN.js.map → chunk-IFTFDHZX.js.map} +0 -0
- /package/dist/{chunk-SVP2NDRF.js.map → chunk-MXJPX3FM.js.map} +0 -0
- /package/dist/{inbox-MMLHISQV.js.map → inbox-57NHQHY3.js.map} +0 -0
- /package/dist/{pool-YAIBE2L5.js.map → migrate-43PUK25G.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/path-guard.ts","../src/config/schema.ts","../src/config/load.ts","../src/ledger/ledger.ts","../src/browse/browse.ts","../src/notify/notify.ts","../src/weekly/report.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 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: { enabled: boolean };\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.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 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';\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 fs.writeFileSync(userPath, JSON.stringify(merged, null, 2) + '\\n', 'utf8');\n return merged;\n}\n","// Ledger (\"账本\") - the ONE shared ledger (design doc §5, requirement 5).\n// Human-readable Markdown by charter; the user may edit it by hand, so the\n// parser is tolerant: unknown lines are preserved verbatim on rewrite.\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { readText, writeText } from '../vault/vault.js';\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","// Browse flow (v0.9.5 port, r4 D10 applied).\n// A. Watchlist: npm / GitHub release checks with a 6h throttle; first sight\n// registers only, changes become material items.\n// B. 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// 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 { loadJson, saveJson } from '../vault/vault.js';\nimport { activeSeeds, loadPool, normalizeCategory, seedsFilePath } from '../seeds/pool.js';\n\nconst WATCH_THROTTLE_MS = 6 * 3600_000;\nconst UA = { 'User-Agent': 'dsh-heartbeat/2.0 (+local; personal companion)' };\n\nexport interface WatchTarget {\n id: string;\n type: 'npm' | 'github';\n name?: string;\n repo?: string;\n note?: string;\n}\n\nexport interface WatchlistConfig {\n targets?: WatchTarget[];\n}\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 targets: Record<string, { version: string; seen: string; title?: string }>;\n last_check_at: number;\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 };\n}\n\nexport function emptyBrowseState(): BrowseState {\n return { targets: {}, last_check_at: 0, wander: { focusHistory: {}, focusCount: {}, last_wander_at: 0, refillCount: {} } };\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\nexport function loadWatchlist(paths: WorkspacePaths): WatchlistConfig {\n const userPath = path.join(paths.settingsDir, 'watchlist.json');\n if (fs.existsSync(userPath)) return readJsonFile<WatchlistConfig>(userPath, { targets: [] });\n return readJsonFile<WatchlistConfig>(path.join(paths.configDir, 'watchlist.json'), { targets: [] });\n}\n\nfunction loadState(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return loadJson<BrowseState>(guard, browseStatePath(paths)) ?? emptyBrowseState();\n}\n\n// ── A. watchlist checks (fetcher injectable for tests) ──────────────────\n\nexport type FetchLike = (url: string, init?: { headers?: Record<string, string> }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\nasync function checkNpm(fetcher: FetchLike, name: string): Promise<{ version: string; seen: string; title?: string } | null> {\n const r = await fetcher(`https://registry.npmjs.org/${name}/latest`, { headers: UA });\n if (!r.ok) throw new Error(`npm ${r.status}`);\n const j = await r.json() as { version?: string };\n if (!j.version) throw new Error('npm: no version');\n return { version: j.version, seen: `npm:${j.version}` };\n}\n\nasync function checkGithub(fetcher: FetchLike, repo: string): Promise<{ version: string; seen: string; title?: string } | null> {\n const r = await fetcher(`https://api.github.com/repos/${repo}/releases/latest`, {\n headers: { ...UA, Accept: 'application/vnd.github+json' },\n });\n if (r.status === 404) return null; // repo has no releases yet\n if (!r.ok) throw new Error(`gh ${r.status}`);\n const j = await r.json() as { tag_name?: string; name?: string };\n if (!j.tag_name) throw new Error('gh: no tag');\n return { version: j.tag_name, seen: `gh:${j.tag_name}`, title: j.name || '' };\n}\n\nexport interface WatchReport {\n /** Material texts for the pool (one per changed target). */\n items: { text: string; topic: string; tag: 'news'; source: 'browse'; confidence: number }[];\n errors: string[];\n checked: number;\n}\n\nexport async function checkWatchlist(\n guard: PathGuard,\n paths: WorkspacePaths,\n opts: { fetcher?: FetchLike; throttleOk?: boolean } = {},\n now = Date.now(),\n): Promise<WatchReport> {\n const fetcher = opts.fetcher ?? (globalThis.fetch as unknown as FetchLike);\n const state = loadState(guard, paths);\n if (opts.throttleOk !== true && now - state.last_check_at < WATCH_THROTTLE_MS) {\n return { items: [], errors: [], checked: 0 };\n }\n const watchlist = loadWatchlist(paths);\n const report: WatchReport = { items: [], errors: [], checked: 0 };\n for (const t of watchlist.targets ?? []) {\n report.checked += 1;\n try {\n const info = t.type === 'npm' && t.name ? await checkNpm(fetcher, t.name)\n : t.type === 'github' && t.repo ? await checkGithub(fetcher, t.repo)\n : null;\n if (!info) continue;\n const prev = state.targets[t.id];\n if (prev && prev.seen !== info.seen) {\n const title = info.title ? `(${info.title.slice(0, 60)})` : '';\n report.items.push({\n text: `${t.note || t.id} 有更新:${prev.version} -> ${info.version}${title}`,\n topic: `watch:${t.id}`,\n tag: 'news',\n source: 'browse',\n confidence: 0.4,\n });\n }\n state.targets[t.id] = info; // first sight registers silently (首见不产素材)\n } catch (e) {\n report.errors.push(`${t.id}: ${String(e)}`);\n }\n }\n state.last_check_at = now;\n saveJson(guard, browseStatePath(paths), state);\n return report;\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}\n\nexport function inWanderWindow(now: Date, windows: { start: string; end: string }[]): string | null {\n const hm = now.getHours() * 60 + now.getMinutes();\n for (const w of windows) {\n const [sh, sm] = w.start.split(':').map(Number);\n const [eh, em] = w.end.split(':').map(Number);\n if (hm >= sh! * 60 + sm! && hm <= eh! * 60 + em!) 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/** Round-robin: least-recently-used non-cooling focus wins. */\nexport function pickFocus(state: BrowseState, interests: InterestsConfig, now: number): 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 pool.sort((a, b) => (state.wander.focusHistory[a] ?? 0) - (state.wander.focusHistory[b] ?? 0));\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 windows = interests._schedule?.windows?.length\n ? interests._schedule.windows\n : (policy.browse.windows as { start: string; end: string }[]);\n const win = inWanderWindow(now, 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})` };\n }\n const minGap = policy.browse.minIntervalHours * 3600_000;\n if (now.getTime() - state.wander.last_wander_at < minGap) {\n return { focus: null, query: null, skipped: 'min-interval' };\n }\n const focus = pickFocus(state, interests, now.getTime());\n if (!focus) return { focus: null, query: null, skipped: 'no-focus' };\n return { focus, query: `${focus} 2026 最新`, skipped: null };\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 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()); // 3-day cooldown still applies\n if (!focus) {\n return { focus: null, query: null, skipped: 'no-focus', topicCount, refillsToday };\n }\n return { focus, query: `${focus} 2026 最新`, skipped: null, topicCount, refillsToday };\n}\n\nexport function browseStatus(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return loadState(guard, paths);\n}\n","// Windows toast channel (D12): attention hint ONLY - never carries the\n// expression body. Wraps assets/notify.ps1 (self-registering AUMID).\n\nimport { spawnSync } from 'node:child_process';\nimport path from 'node:path';\nimport type { WorkspacePaths } from '../core/paths.js';\n\nfunction runNotify(paths: WorkspacePaths, args: string[]): { status: number; out: string } {\n const r = spawnSync('powershell.exe',\n ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(paths.assetsDir, 'notify.ps1'), ...args],\n { timeout: 20_000, encoding: 'utf8' });\n return { status: r.status ?? -1, out: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };\n}\n\n/** Register the toast identity if missing (idempotent, per machine/user). */\nexport function ensureRegistered(paths: WorkspacePaths): boolean {\n const check = runNotify(paths, ['-Check']);\n if (/REGISTERED: yes/.test(check.out)) return true;\n const reg = 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 function sendNewMessageHint(paths: WorkspacePaths): boolean {\n const r = 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 function sendWeeklyReadyHint(paths: WorkspacePaths): boolean {\n const r = runNotify(paths, ['-Title', '心跳周报', '-Message', '本期周报已生成']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\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 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/** Last generation time from the weekly state file; 0 = never. */\nexport function lastWeeklyGeneratedAt(guard: PathGuard, dataDir: string): number {\n try {\n const raw = JSON.parse(fs.readFileSync(guard.assert(stateFilePath(dataDir)), 'utf8')) as { lastGeneratedAt?: number };\n return Number(raw.lastGeneratedAt) || 0;\n } catch {\n return 0;\n }\n}\n\n/** Due when the last report is ≥7 days old. Never-generated counts as due:\n * the first run after installing writes an onboarding report from whatever\n * the 7-day window already holds. */\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/** 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. */\nexport function listWeeklyReports(guard: PathGuard, dataDir: string): 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 return out.sort((a, b) => (a.end < b.end ? 1 : -1));\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.peakHours.length > 0) {\n lines.push(`活跃高峰:${facts.peakHours.join('、')}。`);\n }\n return lines.join('\\n');\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,cAAwC,MAAM;AAAA,EACnD,YAAY,QAAgB,WAAmB;AAC7C,UAAM,4BAA4B,MAAM,kBAAkB,SAAS,IAAI;AACvE,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,aAAa,QAAwB;AACnD,QAAM,MAAM,KAAK,QAAQ,MAAM;AAC/B,MAAI;AACF,WAAO,GAAG,aAAa,GAAG;AAAA,EAC5B,QAAQ;AAGN,UAAM,OAAiB,CAAC;AACxB,QAAI,MAAM;AACV,eAAS;AACP,YAAM,OAAO,KAAK,SAAS,GAAG;AAC9B,YAAM,SAAS,KAAK,QAAQ,GAAG;AAC/B,UAAI,WAAW,KAAK;AAClB,cAAM,IAAI,MAAM,wBAAwB,MAAM,yBAAyB;AAAA,MACzE;AACA,WAAK,KAAK,IAAI;AACd,YAAM;AACN,UAAI;AACF,cAAM,UAAU,GAAG,aAAa,GAAG;AACnC,eAAO,KAAK,KAAK,SAAS,GAA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AAK,KAAK,KAAK,gBAAgB,GAAGA,MAAK,KAAK,YAAY,gBAAgB,CAAC;AAAA,IAC9H,iBACE,eAAe,UACfD,IAAG,WAAWC,MAAK,KAAK,KAAK,aAAa,CAAC,KAC3C,UAAUA,MAAK,KAAK,KAAK,aAAa,GAAGA,MAAK,KAAK,YAAY,aAAa,CAAC;AAAA,EACjF;AACF;AAEA,SAAS,UAAU,MAAc,OAAwB;AACvD,MAAI;AACF,WAAOD,IAAG,aAAa,IAAI,EAAE,OAAOA,IAAG,aAAa,KAAK,CAAC;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["fs","path","path","fs","path","path","fs","path","path","fs","path","fs","path","path","fs","fs","path"]}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isEncrypted,
|
|
3
|
+
loadEncryptedText,
|
|
4
|
+
saveEncryptedText
|
|
5
|
+
} from "./chunk-IFTFDHZX.js";
|
|
6
|
+
|
|
7
|
+
// src/vault/migrate.ts
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
import {
|
|
11
|
+
createCipheriv,
|
|
12
|
+
createDecipheriv,
|
|
13
|
+
randomBytes,
|
|
14
|
+
scryptSync,
|
|
15
|
+
timingSafeEqual
|
|
16
|
+
} from "crypto";
|
|
17
|
+
var MIGRATE_MAGIC = "HBMIG1";
|
|
18
|
+
var MIGRATE_VERSION = 1;
|
|
19
|
+
var KDF_N = 16384;
|
|
20
|
+
var KEY_LEN = 32;
|
|
21
|
+
var MIGRATE_FILES = [
|
|
22
|
+
"profile.json",
|
|
23
|
+
"profile_snapshot.json",
|
|
24
|
+
"profile_inbox.jsonl",
|
|
25
|
+
"profile_journal.jsonl",
|
|
26
|
+
"profile_rhythm.json",
|
|
27
|
+
"sent.json",
|
|
28
|
+
"browse.json",
|
|
29
|
+
"seeds.jsonl",
|
|
30
|
+
"ledger.md",
|
|
31
|
+
"cursors.json"
|
|
32
|
+
];
|
|
33
|
+
function collectWeeklyFiles(guard, paths) {
|
|
34
|
+
const dir = path.join(paths.dataDir, "weekly");
|
|
35
|
+
try {
|
|
36
|
+
return fs.readdirSync(guard.assert(dir)).filter((f) => f.endsWith(".json")).map((f) => path.join("weekly", f).replace(/\\/g, "/"));
|
|
37
|
+
} catch {
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function collectJournalArchives(guard, paths) {
|
|
42
|
+
try {
|
|
43
|
+
return fs.readdirSync(guard.assert(paths.dataDir)).filter((f) => f.startsWith("profile_journal.archive-") && f.endsWith(".jsonl"));
|
|
44
|
+
} catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function collectMigrationEntries(guard, paths) {
|
|
49
|
+
const entries = [];
|
|
50
|
+
const packed = [];
|
|
51
|
+
const missing = [];
|
|
52
|
+
const rels = [...MIGRATE_FILES, ...collectJournalArchives(guard, paths), ...collectWeeklyFiles(guard, paths)];
|
|
53
|
+
for (const rel of rels) {
|
|
54
|
+
const abs = path.join(paths.dataDir, rel);
|
|
55
|
+
let absCanon;
|
|
56
|
+
try {
|
|
57
|
+
absCanon = guard.assert(abs);
|
|
58
|
+
} catch {
|
|
59
|
+
missing.push(rel);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (!fs.existsSync(absCanon)) {
|
|
63
|
+
missing.push(rel);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const encrypted = isEncrypted(absCanon);
|
|
67
|
+
const content = encrypted ? loadEncryptedText(guard, absCanon) ?? (() => {
|
|
68
|
+
throw new Error(`cannot decrypt ${rel} on this machine`);
|
|
69
|
+
})() : fs.readFileSync(absCanon, "utf8");
|
|
70
|
+
entries.push({ path: rel.replace(/\\/g, "/"), encrypted, content });
|
|
71
|
+
packed.push(rel);
|
|
72
|
+
}
|
|
73
|
+
return { entries, progress: { packed, missing } };
|
|
74
|
+
}
|
|
75
|
+
function deriveKey(passphrase, salt) {
|
|
76
|
+
return scryptSync(passphrase, salt, KEY_LEN, { N: KDF_N, r: 8, p: 1 });
|
|
77
|
+
}
|
|
78
|
+
function encryptContainer(entries, passphrase, now = /* @__PURE__ */ new Date()) {
|
|
79
|
+
if (!passphrase) throw new Error("migrate: passphrase must not be empty");
|
|
80
|
+
const salt = randomBytes(16);
|
|
81
|
+
const iv = randomBytes(12);
|
|
82
|
+
const key = deriveKey(passphrase, salt);
|
|
83
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
84
|
+
const plain = Buffer.from(JSON.stringify({ version: MIGRATE_VERSION, createdAt: now.toISOString(), files: entries }), "utf8");
|
|
85
|
+
const data = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
86
|
+
const tag = cipher.getAuthTag();
|
|
87
|
+
return JSON.stringify({
|
|
88
|
+
magic: MIGRATE_MAGIC,
|
|
89
|
+
kdf: { name: "scrypt", salt: salt.toString("hex"), N: KDF_N },
|
|
90
|
+
iv: iv.toString("hex"),
|
|
91
|
+
tag: tag.toString("hex"),
|
|
92
|
+
data: data.toString("base64")
|
|
93
|
+
}, null, 1) + "\n";
|
|
94
|
+
}
|
|
95
|
+
function decryptContainer(text, passphrase) {
|
|
96
|
+
let outer;
|
|
97
|
+
try {
|
|
98
|
+
outer = JSON.parse(text);
|
|
99
|
+
} catch {
|
|
100
|
+
throw new Error("migrate: not a migration container (bad JSON)");
|
|
101
|
+
}
|
|
102
|
+
if (outer.magic !== MIGRATE_MAGIC) throw new Error("migrate: not a migration container (bad magic)");
|
|
103
|
+
const salt = Buffer.from(String(outer.kdf?.salt ?? ""), "hex");
|
|
104
|
+
const iv = Buffer.from(String(outer.iv ?? ""), "hex");
|
|
105
|
+
const tag = Buffer.from(String(outer.tag ?? ""), "hex");
|
|
106
|
+
const data = Buffer.from(String(outer.data ?? ""), "base64");
|
|
107
|
+
const key = deriveKey(passphrase, salt);
|
|
108
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
109
|
+
decipher.setAuthTag(tag);
|
|
110
|
+
let plain;
|
|
111
|
+
try {
|
|
112
|
+
plain = Buffer.concat([decipher.update(data), decipher.final()]);
|
|
113
|
+
} catch {
|
|
114
|
+
throw new Error("migrate: wrong passphrase or corrupted container");
|
|
115
|
+
}
|
|
116
|
+
const inner = JSON.parse(plain.toString("utf8"));
|
|
117
|
+
if (inner.version !== MIGRATE_VERSION) throw new Error(`migrate: unsupported container version ${inner.version}`);
|
|
118
|
+
if (!Array.isArray(inner.files)) throw new Error("migrate: container has no file list");
|
|
119
|
+
const v = Buffer.from([inner.version]);
|
|
120
|
+
timingSafeEqual(v, Buffer.from([MIGRATE_VERSION]));
|
|
121
|
+
return { createdAt: inner.createdAt, files: inner.files };
|
|
122
|
+
}
|
|
123
|
+
function applyMigrationEntries(guard, paths, files, now = Date.now()) {
|
|
124
|
+
const restored = [];
|
|
125
|
+
const backedUp = [];
|
|
126
|
+
const skipped = [];
|
|
127
|
+
const stamp = new Date(now).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
128
|
+
for (const f of files) {
|
|
129
|
+
const rel = String(f.path ?? "");
|
|
130
|
+
const abs = path.join(paths.dataDir, rel);
|
|
131
|
+
let absCanon;
|
|
132
|
+
try {
|
|
133
|
+
absCanon = guard.assert(abs);
|
|
134
|
+
} catch {
|
|
135
|
+
skipped.push(rel);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (rel.includes("..") || path.isAbsolute(rel)) {
|
|
139
|
+
skipped.push(rel);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
fs.mkdirSync(path.dirname(absCanon), { recursive: true });
|
|
143
|
+
if (fs.existsSync(absCanon)) {
|
|
144
|
+
fs.copyFileSync(absCanon, `${absCanon}.bak-migrate-${stamp}`);
|
|
145
|
+
backedUp.push(rel);
|
|
146
|
+
}
|
|
147
|
+
if (f.encrypted) saveEncryptedText(guard, absCanon, f.content);
|
|
148
|
+
else fs.writeFileSync(absCanon, f.content, "utf8");
|
|
149
|
+
restored.push(rel);
|
|
150
|
+
}
|
|
151
|
+
return { restored, backedUp, skipped };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export {
|
|
155
|
+
MIGRATE_MAGIC,
|
|
156
|
+
MIGRATE_VERSION,
|
|
157
|
+
MIGRATE_FILES,
|
|
158
|
+
collectMigrationEntries,
|
|
159
|
+
encryptContainer,
|
|
160
|
+
decryptContainer,
|
|
161
|
+
applyMigrationEntries
|
|
162
|
+
};
|
|
163
|
+
//# sourceMappingURL=chunk-UCJR6TC7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vault/migrate.ts"],"sourcesContent":["// Cross-machine migration (v1.8.0). DPAPI binds the sensitive stores to one\n// machine + account, so a new machine cannot read them — this module packs\n// the memory files into ONE passphrase-encrypted container (AES-256-GCM,\n// scrypt-derived key, node:crypto only) that can travel safely, and restores\n// them on the other side re-encrypted with the LOCAL DPAPI.\n//\n// Restore is byte-identical: for each file we record whether it was DPAPI\n// encrypted on disk (isEncrypted magic check) and write it back through the\n// same path — no per-module write semantics to keep in sync. Existing files\n// are backed up before overwrite (rule 4).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n scryptSync,\n timingSafeEqual,\n} from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { isEncrypted, loadEncryptedText, saveEncryptedText } from './vault.js';\n\nexport const MIGRATE_MAGIC = 'HBMIG1';\nexport const MIGRATE_VERSION = 1;\nconst KDF_N = 163_84; // scrypt cost (Node default)\nconst KEY_LEN = 32;\n\n/** Memory-relevant runtime files (dataDir-relative). Deliberately NOT here:\n * gate.json (machine-local counters + home session id — the new machine\n * builds its own) and screen snapshots (per-beat transients, not memory). */\nexport const MIGRATE_FILES = [\n 'profile.json',\n 'profile_snapshot.json',\n 'profile_inbox.jsonl',\n 'profile_journal.jsonl',\n 'profile_rhythm.json',\n 'sent.json',\n 'browse.json',\n 'seeds.jsonl',\n 'ledger.md',\n 'cursors.json',\n];\n\nexport interface MigrateEntry {\n path: string; // dataDir-relative\n encrypted: boolean; // was DPAPI-encrypted on the source machine\n content: string;\n}\n\nexport interface MigrateProgress {\n packed: string[];\n missing: string[];\n}\n\nfunction collectWeeklyFiles(guard: PathGuard, paths: WorkspacePaths): string[] {\n const dir = path.join(paths.dataDir, 'weekly');\n try {\n return fs.readdirSync(guard.assert(dir))\n .filter((f) => f.endsWith('.json'))\n .map((f) => path.join('weekly', f).replace(/\\\\/g, '/'));\n } catch {\n return [];\n }\n}\n\n/** Journal archive shards (snapshot rotation output) travel with the memory. */\nfunction collectJournalArchives(guard: PathGuard, paths: WorkspacePaths): string[] {\n try {\n return fs.readdirSync(guard.assert(paths.dataDir))\n .filter((f) => f.startsWith('profile_journal.archive-') && f.endsWith('.jsonl'));\n } catch {\n return [];\n }\n}\n\n/** Read every migration file. A DPAPI file that fails to decrypt aborts the\n * export — a silent half-memory container would be worse than a loud error. */\nexport function collectMigrationEntries(guard: PathGuard, paths: WorkspacePaths): { entries: MigrateEntry[]; progress: MigrateProgress } {\n const entries: MigrateEntry[] = [];\n const packed: string[] = [];\n const missing: string[] = [];\n const rels = [...MIGRATE_FILES, ...collectJournalArchives(guard, paths), ...collectWeeklyFiles(guard, paths)];\n for (const rel of rels) {\n const abs = path.join(paths.dataDir, rel);\n let absCanon: string;\n try {\n absCanon = guard.assert(abs);\n } catch {\n missing.push(rel);\n continue;\n }\n if (!fs.existsSync(absCanon)) {\n missing.push(rel);\n continue;\n }\n const encrypted = isEncrypted(absCanon);\n const content = encrypted\n ? loadEncryptedText(guard, absCanon) ?? (() => { throw new Error(`cannot decrypt ${rel} on this machine`); })()\n : fs.readFileSync(absCanon, 'utf8');\n entries.push({ path: rel.replace(/\\\\/g, '/'), encrypted, content });\n packed.push(rel);\n }\n return { entries, progress: { packed, missing } };\n}\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return scryptSync(passphrase, salt, KEY_LEN, { N: KDF_N, r: 8, p: 1 });\n}\n\n/** Build the container file content. Everything sensitive lives inside the\n * ciphertext; the outer JSON carries only crypto parameters. */\nexport function encryptContainer(entries: MigrateEntry[], passphrase: string, now = new Date()): string {\n if (!passphrase) throw new Error('migrate: passphrase must not be empty');\n const salt = randomBytes(16);\n const iv = randomBytes(12);\n const key = deriveKey(passphrase, salt);\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const plain = Buffer.from(JSON.stringify({ version: MIGRATE_VERSION, createdAt: now.toISOString(), files: entries }), 'utf8');\n const data = Buffer.concat([cipher.update(plain), cipher.final()]);\n const tag = cipher.getAuthTag();\n return JSON.stringify({\n magic: MIGRATE_MAGIC,\n kdf: { name: 'scrypt', salt: salt.toString('hex'), N: KDF_N },\n iv: iv.toString('hex'),\n tag: tag.toString('hex'),\n data: data.toString('base64'),\n }, null, 1) + '\\n';\n}\n\n/** Parse + decrypt a container. Throws (loudly) on a wrong passphrase or a\n * corrupted file — never returns partial data. */\nexport function decryptContainer(text: string, passphrase: string): { createdAt: string; files: MigrateEntry[] } {\n let outer: { magic?: string; kdf?: { salt?: string }; iv?: string; tag?: string; data?: string };\n try {\n outer = JSON.parse(text);\n } catch {\n throw new Error('migrate: not a migration container (bad JSON)');\n }\n if (outer.magic !== MIGRATE_MAGIC) throw new Error('migrate: not a migration container (bad magic)');\n const salt = Buffer.from(String(outer.kdf?.salt ?? ''), 'hex');\n const iv = Buffer.from(String(outer.iv ?? ''), 'hex');\n const tag = Buffer.from(String(outer.tag ?? ''), 'hex');\n const data = Buffer.from(String(outer.data ?? ''), 'base64');\n const key = deriveKey(passphrase, salt);\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n let plain: Buffer;\n try {\n plain = Buffer.concat([decipher.update(data), decipher.final()]);\n } catch {\n throw new Error('migrate: wrong passphrase or corrupted container');\n }\n const inner = JSON.parse(plain.toString('utf8')) as { version: number; createdAt: string; files: MigrateEntry[] };\n if (inner.version !== MIGRATE_VERSION) throw new Error(`migrate: unsupported container version ${inner.version}`);\n if (!Array.isArray(inner.files)) throw new Error('migrate: container has no file list');\n // Constant-time-ish sanity on the passphrase result is implicit in GCM auth;\n // timingSafeEqual is used for the version check to keep the import path\n // uniform without importing more crypto surface.\n const v = Buffer.from([inner.version]);\n timingSafeEqual(v, Buffer.from([MIGRATE_VERSION]));\n return { createdAt: inner.createdAt, files: inner.files };\n}\n\nexport interface MigrateImportResult {\n restored: string[];\n backedUp: string[];\n skipped: string[];\n}\n\n/** Restore entries into the local dataDir, re-encrypting DPAPI files with the\n * LOCAL machine key. Existing files are copied aside first. */\nexport function applyMigrationEntries(guard: PathGuard, paths: WorkspacePaths, files: MigrateEntry[], now = Date.now()): MigrateImportResult {\n const restored: string[] = [];\n const backedUp: string[] = [];\n const skipped: string[] = [];\n const stamp = new Date(now).toISOString().replace(/[-:T]/g, '').slice(0, 14);\n for (const f of files) {\n const rel = String(f.path ?? '');\n const abs = path.join(paths.dataDir, rel);\n let absCanon: string;\n try {\n absCanon = guard.assert(abs);\n } catch {\n skipped.push(rel); // path refused by the guard — never write it\n continue;\n }\n if (rel.includes('..') || path.isAbsolute(rel)) {\n skipped.push(rel);\n continue;\n }\n fs.mkdirSync(path.dirname(absCanon), { recursive: true });\n if (fs.existsSync(absCanon)) {\n fs.copyFileSync(absCanon, `${absCanon}.bak-migrate-${stamp}`);\n backedUp.push(rel);\n }\n if (f.encrypted) saveEncryptedText(guard, absCanon, f.content);\n else fs.writeFileSync(absCanon, f.content, 'utf8');\n restored.push(rel);\n }\n return { restored, backedUp, skipped };\n}\n"],"mappings":";;;;;;;AAWA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKA,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AAC/B,IAAM,Q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