@kanadego/dsh-heartbeat 2.2.1 → 2.3.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.
Files changed (61) hide show
  1. package/README.md +108 -303
  2. package/client.js +186 -24
  3. package/dist/{bili-login-XQVEE4M6.js → bili-login-KDDU63Z2.js} +4 -4
  4. package/dist/{bindings-U2M3CO2D.js → bindings-LTSGGNIH.js} +3 -3
  5. package/dist/{chunk-AT32XCCI.js → chunk-43Q42HWH.js} +8 -2
  6. package/dist/chunk-43Q42HWH.js.map +1 -0
  7. package/dist/{chunk-LQKOYTRL.js → chunk-4OQXAHU5.js} +2 -2
  8. package/dist/{chunk-3QJJRXIR.js → chunk-5CVAW5AS.js} +11 -2
  9. package/dist/chunk-5CVAW5AS.js.map +1 -0
  10. package/dist/{chunk-IBBAISSW.js → chunk-66IUDHCY.js} +50 -1
  11. package/dist/chunk-66IUDHCY.js.map +1 -0
  12. package/dist/{chunk-3DNGY4DS.js → chunk-77UYDI2A.js} +2 -2
  13. package/dist/{chunk-CJK6RTMH.js → chunk-ABFO4QII.js} +896 -167
  14. package/dist/chunk-ABFO4QII.js.map +1 -0
  15. package/dist/{chunk-M72T5MZU.js → chunk-GOLMRQRW.js} +3 -2
  16. package/dist/{chunk-XYBII5PR.js → chunk-HSTGRQLP.js} +178 -39
  17. package/dist/chunk-HSTGRQLP.js.map +1 -0
  18. package/dist/{chunk-KZLVR4J7.js → chunk-IPTNSXOY.js} +2 -2
  19. package/dist/{chunk-DLOYERAK.js → chunk-JIRQ36F7.js} +3 -3
  20. package/dist/{chunk-ECXYNTEV.js → chunk-K47VV6IQ.js} +5 -3
  21. package/dist/chunk-K47VV6IQ.js.map +1 -0
  22. package/dist/{chunk-F2XVKX55.js → chunk-KGOC6EX4.js} +3 -3
  23. package/dist/{chunk-SIY3YHFY.js → chunk-MMI6OBEC.js} +2 -2
  24. package/dist/{chunk-N6SMIGYJ.js → chunk-QOLKUYQ3.js} +2 -2
  25. package/dist/cli/index.js +94 -23
  26. package/dist/cli/index.js.map +1 -1
  27. package/dist/{focus-store-RNHBAFYS.js → focus-store-XGTPIVF6.js} +3 -3
  28. package/dist/{inbox-ZLX2MH7A.js → inbox-7GGEMBUD.js} +4 -4
  29. package/dist/index.d.ts +60 -1
  30. package/dist/index.js +468 -155
  31. package/dist/index.js.map +1 -1
  32. package/dist/{migrate-XFZU5EBE.js → migrate-6HH2ZARV.js} +4 -4
  33. package/dist/{orchestrator-5BHYQ77Y.js → orchestrator-OJJM5QSV.js} +20 -11
  34. package/dist/{pool-76VLAZER.js → pool-QTY2MI56.js} +4 -4
  35. package/dist/runtime-RGZKOFP3.js +15 -0
  36. package/dist/{snapshot-SU2VGM4C.js → snapshot-6DFNGXTR.js} +5 -5
  37. package/package.json +1 -1
  38. package/dist/chunk-3QJJRXIR.js.map +0 -1
  39. package/dist/chunk-AT32XCCI.js.map +0 -1
  40. package/dist/chunk-CJK6RTMH.js.map +0 -1
  41. package/dist/chunk-ECXYNTEV.js.map +0 -1
  42. package/dist/chunk-IBBAISSW.js.map +0 -1
  43. package/dist/chunk-XYBII5PR.js.map +0 -1
  44. package/dist/runtime-W2OWJIHY.js +0 -11
  45. /package/dist/{bili-login-XQVEE4M6.js.map → bili-login-KDDU63Z2.js.map} +0 -0
  46. /package/dist/{bindings-U2M3CO2D.js.map → bindings-LTSGGNIH.js.map} +0 -0
  47. /package/dist/{chunk-LQKOYTRL.js.map → chunk-4OQXAHU5.js.map} +0 -0
  48. /package/dist/{chunk-3DNGY4DS.js.map → chunk-77UYDI2A.js.map} +0 -0
  49. /package/dist/{chunk-M72T5MZU.js.map → chunk-GOLMRQRW.js.map} +0 -0
  50. /package/dist/{chunk-KZLVR4J7.js.map → chunk-IPTNSXOY.js.map} +0 -0
  51. /package/dist/{chunk-DLOYERAK.js.map → chunk-JIRQ36F7.js.map} +0 -0
  52. /package/dist/{chunk-F2XVKX55.js.map → chunk-KGOC6EX4.js.map} +0 -0
  53. /package/dist/{chunk-SIY3YHFY.js.map → chunk-MMI6OBEC.js.map} +0 -0
  54. /package/dist/{chunk-N6SMIGYJ.js.map → chunk-QOLKUYQ3.js.map} +0 -0
  55. /package/dist/{focus-store-RNHBAFYS.js.map → focus-store-XGTPIVF6.js.map} +0 -0
  56. /package/dist/{inbox-ZLX2MH7A.js.map → inbox-7GGEMBUD.js.map} +0 -0
  57. /package/dist/{migrate-XFZU5EBE.js.map → migrate-6HH2ZARV.js.map} +0 -0
  58. /package/dist/{orchestrator-5BHYQ77Y.js.map → orchestrator-OJJM5QSV.js.map} +0 -0
  59. /package/dist/{pool-76VLAZER.js.map → pool-QTY2MI56.js.map} +0 -0
  60. /package/dist/{runtime-W2OWJIHY.js.map → runtime-RGZKOFP3.js.map} +0 -0
  61. /package/dist/{snapshot-SU2VGM4C.js.map → snapshot-6DFNGXTR.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/audit-log.ts","../src/profile/store.ts","../src/profile/types.ts","../src/profile/schema.ts","../src/profile/shapes.ts"],"sourcesContent":["// Append-only JSONL audit log with age-based retention pruning.\n// Audit files are plaintext by charter (transparency), and must never contain\n// sensitive raw observations (window titles, conversation text).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteFileSync } from './atomic-fs.js';\n\nexport interface AuditEvent {\n ts: string;\n [key: string]: unknown;\n}\n\n/**\n * H-15: audit is best-effort by contract — a full disk, a locked log file or an\n * unserialisable payload must never abort a beat (one caller inside a catch\n * block turning a handled failure into an unhandled one is the worst case).\n * Failures go to stderr so they stay visible instead of silently vanishing.\n */\nexport function appendAuditLine(file: string, event: Omit<AuditEvent, 'ts'> & { ts?: string }): void {\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const line = JSON.stringify({ ts: event.ts ?? new Date().toISOString(), ...event });\n fs.appendFileSync(file, line + '\\n', 'utf8');\n } catch (e) {\n process.stderr.write(`[heartbeat] audit append failed: ${file}: ${String(e)}\\n`);\n }\n}\n\nexport function readAuditLines<T = AuditEvent>(file: string): T[] {\n if (!fs.existsSync(file)) return [];\n const out: T[] = [];\n const raw = fs.readFileSync(file, 'utf8');\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n out.push(JSON.parse(trimmed) as T);\n } catch {\n // Skip corrupt lines; the log is diagnostic, not authoritative data.\n out.push({ ts: '', corrupt: true, raw: trimmed.slice(0, 200) } as unknown as T);\n }\n }\n return out;\n}\n\n/**\n * Drop entries older than maxAgeMs. Returns the number of removed lines.\n * Rewrites the file atomically; on rewrite failure the original is untouched.\n */\nexport function pruneAuditFile(file: string, maxAgeMs: number, now = Date.now()): number {\n if (!fs.existsSync(file)) return 0;\n const lines = readAuditLines(file);\n const kept = lines.filter((e) => {\n const ev = e as unknown as AuditEvent;\n const ts = Date.parse(ev.ts ?? '');\n if (!Number.isFinite(ts)) return true; // keep unparseable lines, never lose audit data silently\n return now - ts <= maxAgeMs;\n });\n const removed = lines.length - kept.length;\n if (removed === 0) return 0;\n const body = kept.map((e) => JSON.stringify(e)).join('\\n');\n atomicWriteFileSync(file, body ? body + '\\n' : '');\n return removed;\n}\n","// Profile store: materialized view + journal (the journal is the ONLY\n// authority; profile.json is a pure projection - r2 §14 verify/rebuild).\n// Every LLM-proposed op passes deterministic guards here (LLM nominates,\n// code decides - §3.3).\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson, readText, writeText } from '../vault/vault.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n CONFIDENCE_CAP,\n emptyProfile,\n JOURNAL_VERSION,\n PARTITIONS,\n type ApplyReport,\n type Evidence,\n type EvidenceKind,\n type InboxItem,\n type JournalRecord,\n type Partition,\n type ProfileDoc,\n type ProfileEntry,\n type ProfileOp,\n} from './types.js';\nimport { checkAddAgainstSchema, type ProfileSchema } from './schema.js';\nimport { tryParseJournalRecord } from './shapes.js';\nimport { matchFilesRecursive } from '../core/fs-walk.js';\n\nconst DAY_MS = 86_400_000;\n\nexport function profileFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile.json');\n}\n\nexport function journalFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile_journal.jsonl');\n}\n\n// ── snapshot basepoint (v1.8.0, design doc §14 ③) ─────────────────────────\n// The journal grows forever; the snapshot folds its history into one DPAPI\n// document and moves the folded records into a timestamped archive shard.\n// Replay order: snapshot → archives (name order) → live journal, skipping\n// records at or before the snapshot baseline — so verify/rebuild stay correct\n// without knowing whether a snapshot exists.\n\nexport const SNAPSHOT_FILE = 'profile_snapshot.json';\nexport const ARCHIVE_PREFIX = 'profile_journal.archive-';\n\nexport interface ProfileSnapshot {\n version: 1;\n /** ts of the LAST journal record folded into `doc`. */\n baselineTs: string;\n recordsFolded: number;\n doc: ProfileDoc;\n}\n\nexport function snapshotFilePath(dataDir: string): string {\n return path.join(dataDir, SNAPSHOT_FILE);\n}\n\nfunction loadSnapshot(guard: PathGuard, dataDir: string): ProfileSnapshot | null {\n const snap = loadJson<ProfileSnapshot>(guard, snapshotFilePath(dataDir));\n if (!snap || snap.version !== 1 || typeof snap.baselineTs !== 'string' || !snap.doc?.partitions) return null;\n return snap;\n}\n\nfunction listArchiveFiles(guard: PathGuard, dataDir: string): string[] {\n try {\n return fs.readdirSync(guard.assert(dataDir))\n .filter((f) => f.startsWith(ARCHIVE_PREFIX) && f.endsWith('.jsonl'))\n .sort(); // timestamped names sort chronologically\n } catch {\n return [];\n }\n}\n\n/** Replay one JSONL text into `doc`, skipping records at/before the baseline. */\nfunction replayText(\n doc: ProfileDoc,\n text: string,\n baselineTs: string,\n stats: { records: number; truncatedTail: number; badRecords: number; isLive: boolean },\n): void {\n const lines = text.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n // A torn tail only counts on the LIVE journal — archives are closed files.\n const tornTail = (): boolean => {\n const isLast = lines.slice(i + 1).every((l) => !l.trim());\n if (stats.isLive && isLast) {\n stats.truncatedTail = lines.length - i;\n return true;\n }\n return false;\n };\n let rec: JournalRecord | null = null;\n try {\n rec = tryParseJournalRecord(JSON.parse(trimmed));\n } catch {\n rec = null;\n }\n if (!rec) {\n if (tornTail()) break;\n // mid-file unreadable record: count it and keep going (the journal is\n // append-only/immutable, so a bad line is never rewritten).\n stats.badRecords += 1;\n continue;\n }\n // Baseline skip: only records CARRYING a ts can be proven folded. A\n // ts-less record is always applied (applyOpPermissive tolerates it).\n if (baselineTs && rec.ts && String(rec.ts) <= baselineTs) continue;\n try {\n if (rec.v === JOURNAL_VERSION && rec.entries) {\n // v2 (③A): the record carries each touched entry's FULL final state,\n // so replay is an upsert; live and replay share one state machine (HB-09).\n for (const entry of rec.entries) upsertEntry(doc, entry);\n } else {\n for (const op of rec.applied ?? []) applyOpPermissive(doc, op, rec.ts);\n }\n stats.records += 1;\n } catch {\n stats.badRecords += 1;\n }\n }\n}\n\nfunction bucketFor(doc: ProfileDoc, partition: Partition): { entries: ProfileEntry[] } {\n let bucket = doc.partitions[partition];\n if (!bucket) {\n bucket = { entries: [] };\n doc.partitions[partition] = bucket;\n }\n return bucket;\n}\n\n/** Journal v2 replay: `entry` is the entry's final state, so replay is an\n * upsert by id (position preserved for updates, appended for new entries). */\nfunction upsertEntry(doc: ProfileDoc, entry: ProfileEntry): void {\n const next = structuredClone(entry);\n for (const p of PARTITIONS) {\n const list = doc.partitions[p]?.entries;\n if (!list) continue;\n const at = list.findIndex((e) => e.id === next.id);\n if (at < 0) continue;\n if (p === next.partition) {\n list[at] = next;\n } else {\n list.splice(at, 1);\n bucketFor(doc, next.partition).entries.push(next);\n }\n return;\n }\n bucketFor(doc, next.partition).entries.push(next);\n}\n\n/** Full replay: snapshot basepoint + archive shards + live journal. */\nexport function replayJournal(guard: PathGuard, dataDir: string): ReplayResult {\n const snap = loadSnapshot(guard, dataDir);\n const doc = snap ? snap.doc : emptyProfile();\n const baselineTs = snap?.baselineTs ?? '';\n const stats = { records: snap?.recordsFolded ?? 0, truncatedTail: 0, badRecords: 0, isLive: false };\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n // shard record counts are not reported (the snapshot already folded\n // them); only the live journal's torn tail is meaningful.\n replayText(doc, fs.readFileSync(path.join(dataDir, file), 'utf8'), baselineTs, { records: 0, truncatedTail: 0, badRecords: 0, isLive: false });\n } catch { /* unreadable shard: skip */ }\n }\n stats.isLive = true;\n replayText(doc, readText(guard, journalFilePath(dataDir), ''), baselineTs, stats);\n return { doc, truncatedTail: stats.truncatedTail, records: stats.records, badRecords: stats.badRecords };\n}\n\n/** Every plaintext journal text in chronological order: archive shards first,\n * then the live journal — the RAW record timeline, for callers that need the\n * history itself rather than the accumulated doc (the weekly report counts\n * the week's ADD ops). A rotation must not hide history from them (H-01). */\nexport function readJournalTexts(guard: PathGuard, dataDir: string): string[] {\n const texts: string[] = [];\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n texts.push(fs.readFileSync(path.join(dataDir, file), 'utf8'));\n } catch { /* unreadable shard: skip */ }\n }\n texts.push(readText(guard, journalFilePath(dataDir), ''));\n return texts;\n}\n\nexport function loadProfile(guard: PathGuard, file: string): ProfileDoc {\n const doc = loadJson<ProfileDoc>(guard, file);\n if (!doc || !doc.partitions) return emptyProfile();\n // ensure all partitions exist\n for (const p of PARTITIONS) {\n if (!doc.partitions[p]) doc.partitions[p] = { entries: [] };\n }\n return doc;\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** ref format \"<datafile>#<locator>\": the referenced file must exist under data/. */\nfunction refExists(guard: PathGuard, dataDir: string, ref: string): boolean {\n const base = ref.split('#')[0] ?? '';\n if (!base) return false;\n const target = path.join(dataDir, base);\n try {\n return fs.existsSync(guard.assert(target));\n } catch {\n return false;\n }\n}\n\nfunction capForKinds(kinds: EvidenceKind[]): number {\n if (kinds.length === 0) return 0.4;\n return Math.min(...kinds.map((k) => CONFIDENCE_CAP[k] ?? 0.4));\n}\n\nfunction findActive(doc: ProfileDoc, id: string): ProfileEntry | undefined {\n for (const p of PARTITIONS) {\n const hit = doc.partitions[p]!.entries.find((e) => e.id === id && e.validTo === null);\n if (hit) return hit;\n }\n return undefined;\n}\n\n/**\n * Apply validated ops to the doc (mutates). Returns applied/rejected.\n * Guards (§3.3): whitelist, evidence gate, per-run ops cap is enforced by the\n * caller, confidence caps by evidence kind, psy gating, INVALIDATE ownership:\n * volatile expiry is code-driven (LLM may not), stable invalidation needs a\n * contradicting observation attached.\n */\nexport function applyOpsToDoc(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n ops: ProfileOp[],\n schema: ProfileSchema | undefined,\n policy: Policy,\n now: number,\n): ApplyReport {\n const applied: ProfileOp[] = [];\n const rejected: { op: ProfileOp; reason: string }[] = [];\n // Journal v2 events: one FULL snapshot per touched entry (HB-09).\n const entries: ProfileEntry[] = [];\n const nowIso = new Date(now).toISOString();\n\n for (const op of ops) {\n if (op.op === 'NOOP') {\n applied.push(op);\n continue;\n }\n if (op.op === 'ADD') {\n if (op.partition === 'psy' && !policy.profile.psyEnabled) {\n rejected.push({ op, reason: 'psy partition is disabled' });\n continue;\n }\n let temporal: 'stable' | 'volatile' = 'stable';\n if (schema) {\n const check = checkAddAgainstSchema(schema, op.partition, op.topic, op.subTopic, op.temporal);\n if (!check.ok) {\n rejected.push({ op, reason: check.reason! });\n continue;\n }\n temporal = check.temporal;\n } else if (!(op.partition in doc.partitions)) {\n // H-17: no usable schema — the partition set is the only boundary left.\n rejected.push({ op, reason: `unknown partition: ${op.partition}` });\n continue;\n } else {\n temporal = op.temporal === 'volatile' ? 'volatile' : 'stable';\n }\n if (!op.evidence || op.evidence.length === 0) {\n rejected.push({ op, reason: 'ADD without evidence (no provenance, axiom 1)' });\n continue;\n }\n const badRef = op.evidence.find((e) => !refExists(guard, dataDir, e.ref));\n if (badRef) {\n rejected.push({ op, reason: `evidence ref does not resolve: ${badRef.ref}` });\n continue;\n }\n const cap = capForKinds(op.evidence.map((e) => e.kind));\n const active = doc.partitions[op.partition]!.entries.filter((e) => e.validTo === null);\n if (active.length >= policy.profile.partitionCap) {\n rejected.push({ op, reason: `partition ${op.partition} at cap (${policy.profile.partitionCap}); converge first` });\n continue;\n }\n dbSeq += 1;\n const entry: ProfileEntry = {\n id: `p${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content.trim(),\n confidence: Math.min(op.confidence ?? cap, cap),\n temporal,\n validFrom: nowIso,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: nowIso,\n updatedAt: nowIso,\n updateCount: 0,\n };\n op.assignedId = entry.id; // journal replay must reproduce this id\n doc.partitions[op.partition]!.entries.push(entry);\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n if (op.op === 'UPDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n // HB-04 (2026-10-17): validate BEFORE mutating. The old order wrote\n // `content` first and then bailed out on the confidence rule, so an\n // UPDATE that was reported as REJECTED had already changed the text.\n let nextConfidence: number | null = null;\n if (op.changes.confidence !== undefined) {\n const cap = capForKinds(entry.evidence.map((e) => e.kind));\n // confidence upgrades need a second confirming observation (§3.3):\n // only allowed up to cap, and only when the entry already has 2+ evidence\n if (op.changes.confidence > entry.confidence && entry.evidence.length < 2) {\n rejected.push({ op, reason: 'confidence upgrade requires a second confirming observation' });\n continue;\n }\n nextConfidence = Math.min(op.changes.confidence, cap);\n }\n if (op.changes.content !== undefined) entry.content = op.changes.content.trim();\n if (nextConfidence !== null) entry.confidence = nextConfidence;\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n if (op.op === 'INVALIDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n if (entry.temporal === 'volatile') {\n rejected.push({ op, reason: 'volatile expiry is code-owned (time-driven), not LLM-nominated' });\n continue;\n }\n // stable: rebuttal-driven; requires a contradicting observation attached\n const hasNewObservation = (op.evidence ?? []).length > 0\n && (op.evidence ?? []).some((e) => parseIso(e.at) > parseIso(entry.evidence[entry.evidence.length - 1]?.at ?? ''));\n if (!hasNewObservation) {\n rejected.push({ op, reason: 'stable INVALIDATE requires a newer contradicting observation' });\n continue;\n }\n entry.validTo = nowIso;\n entry.supersededBy = null;\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n if (op.evidence) entry.evidence.push(...op.evidence);\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n }\n return { applied, rejected, entries };\n}\n\nlet dbSeq = 0;\n\n/** Deterministic aging (D9): volatile expiry + stable low-activity marking. */\nexport function runDeterministicAging(\n doc: ProfileDoc,\n policy: Policy,\n now: number,\n): { volatileExpired: number; lowActivityMarked: number; entries: ProfileEntry[] } {\n const nowIso = new Date(now).toISOString();\n const entries: ProfileEntry[] = [];\n let volatileExpired = 0;\n let lowActivityMarked = 0;\n for (const p of PARTITIONS) {\n for (const e of doc.partitions[p]!.entries) {\n if (e.validTo !== null) continue;\n const lastEvidence = Math.max(...e.evidence.map((x) => parseIso(x.at)), parseIso(e.updatedAt));\n if (e.temporal === 'volatile') {\n if (now - lastEvidence > policy.profile.volatileDays * DAY_MS) {\n e.validTo = nowIso;\n e.updatedAt = nowIso;\n e.updateCount += 1;\n volatileExpired += 1;\n entries.push(structuredClone(e));\n }\n } else if (!e.lowActivity && now - lastEvidence > policy.profile.stableLowActivityDays * DAY_MS) {\n e.lowActivity = true;\n lowActivityMarked += 1;\n entries.push(structuredClone(e));\n }\n }\n }\n return { volatileExpired, lowActivityMarked, entries };\n}\n\n/** Persist the materialized view atomically + append the journal record.\n * A record carrying `entries` (every touched entry's final state) is written\n * as v2 so replay is an upsert; a record without them stays v1 and replays\n * permissively, so old journals keep working unchanged. */\nexport function persistWithJournal(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n record: Omit<JournalRecord, 'ts'>,\n): void {\n saveJson(guard, profileFilePath(dataDir), doc);\n const v = record.entries === undefined ? undefined : JOURNAL_VERSION;\n const line = JSON.stringify({ ts: new Date().toISOString(), ...record, v });\n const journal = journalFilePath(dataDir);\n try {\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n } catch {\n fs.mkdirSync(dataDir, { recursive: true });\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n }\n}\n\n// ── journal replay (verify / rebuild, r2 §14) ───────────────────────────\n\nfunction applyOpPermissive(doc: ProfileDoc, op: ProfileOp, ts: string): void {\n // Journal is trusted history: replay applies without revalidation.\n if (op.op === 'ADD') {\n dbSeq += 1;\n doc.partitions[op.partition]!.entries.push({\n id: op.assignedId ?? `r${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content,\n confidence: op.confidence ?? 0.5,\n temporal: op.temporal ?? 'stable',\n validFrom: ts,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: ts,\n updatedAt: ts,\n updateCount: 0,\n });\n return;\n }\n if (op.op === 'UPDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n if (op.changes.content !== undefined) e.content = op.changes.content;\n if (op.changes.confidence !== undefined) e.confidence = op.changes.confidence;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n return;\n }\n if (op.op === 'INVALIDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n e.validTo = ts;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n }\n // NOOP: nothing\n}\n\nexport interface ReplayResult {\n doc: ProfileDoc;\n truncatedTail: number;\n records: number;\n /** Journal lines that neither parsed nor replayed (counted, never fatal). */\n badRecords?: number;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n firstDivergence?: { id: string; expected: string; actual: string };\n truncatedTail: number;\n records: number;\n}\n\n/** profile verify: replay vs disk, report first divergence, never fix. */\nexport function verifyProfile(guard: PathGuard, dataDir: string): VerifyReport {\n const replayed = replayJournal(guard, dataDir);\n const onDisk = loadProfile(guard, profileFilePath(dataDir));\n // Timestamps legitimately differ (journal record ts >= op ts); identity\n // fields are also normalized. Compare semantic content only.\n const strip = (doc: ProfileDoc): string =>\n JSON.stringify(doc.partitions, (k, v) => (['id', 'supersededBy', 'validFrom', 'createdAt', 'updatedAt', 'retiredAt'].includes(k) ? '<norm>' : v));\n const ok = strip(replayed.doc) === strip(onDisk);\n if (ok) return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records };\n // first divergence: first entry id present in only one view\n const diskIds = new Set([...PARTITIONS].flatMap((p) => onDisk.partitions[p]!.entries.map((e) => e.content))); const replayIds = new Set([...PARTITIONS].flatMap((p) => replayed.doc.partitions[p]!.entries.map((e) => e.content)));\n const onlyDisk = [...diskIds].find((c) => !replayIds.has(c));\n const onlyReplay = [...replayIds].find((c) => !diskIds.has(c));\n return {\n ok: false,\n firstDivergence: {\n id: onlyDisk ?? onlyReplay ?? '(content)',\n expected: onlyReplay ? 'absent in journal replay' : 'present in journal replay',\n actual: onlyDisk ? 'present on disk' : 'absent on disk',\n },\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n };\n}\n\nexport interface RebuildReport {\n ok: boolean;\n truncatedTail: number;\n records: number;\n wrote: boolean;\n}\n\n/** profile rebuild: journal is authoritative; atomic replace; torn tail reported. */\nexport function rebuildProfile(\n guard: PathGuard,\n dataDir: string,\n opts: { check?: boolean } = {},\n): RebuildReport & { diffSummary?: string } {\n const replayed = replayJournal(guard, dataDir);\n const target = profileFilePath(dataDir);\n if (opts.check) {\n const onDisk = loadProfile(guard, target);\n const same = JSON.stringify(onDisk) === JSON.stringify(replayed.doc);\n return {\n ok: same,\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n wrote: false,\n diffSummary: same ? 'no diff' : 'materialized view differs from journal replay',\n };\n }\n saveJson(guard, target, replayed.doc);\n if (replayed.truncatedTail > 0) {\n // explicit audit: never silently rebuild a view that lost its tail\n writeText(\n guard,\n path.join(dataDir, 'logs', 'rebuild-report.txt'),\n `rebuild truncated ${replayed.truncatedTail} torn line(s) at journal tail; ${replayed.records} records applied\\n`,\n );\n }\n return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records, wrote: true };\n}\n\n// ── wipe (HB-21, 2026-10-17) ───────────────────────────────────────────────\n// `profile wipe` used to delete three files: the materialized view, the inbox\n// and the live journal. The journal is the authority, and its history lives on\n// in profile_snapshot.json plus the archive shards — so a rebuild after a wipe\n// replayed the whole memory back, and a user who asked to forget got the\n// profile regrown instead. Migration backups (HB-07) and crash leftovers carry\n// copies of the same data.\n//\n// Wipe therefore removes every file the profile can be rebuilt from, and only\n// that: settings, seeds, weekly reports and audit logs are not profile data and\n// stay (burn is the tool for a full shred). Shredding remains burn's job — wipe\n// is a delete, not a destroy.\n\nconst WIPE_FILES = ['profile.json', 'profile_inbox.jsonl', 'profile_journal.jsonl', SNAPSHOT_FILE];\nconst WIPE_PATTERNS: RegExp[] = [\n /^profile_journal\\.archive-/,\n /\\.bak-migrate-\\d{14}$/,\n /\\.incoming-\\d{14}$/,\n];\n\n/** Delete every file the profile can be rebuilt from; returns what was removed\n * (relative to dataDir, sorted per family). */\nexport function wipeProfile(guard: PathGuard, dataDir: string): string[] {\n const removed: string[] = [];\n for (const f of WIPE_FILES) {\n const abs = guard.assert(path.join(dataDir, f));\n if (fs.existsSync(abs)) {\n fs.rmSync(abs, { force: true });\n removed.push(f);\n }\n }\n for (const re of WIPE_PATTERNS) {\n let rels: string[] = [];\n try {\n rels = matchFilesRecursive(guard.assert(dataDir), re);\n } catch {\n rels = [];\n }\n for (const rel of rels) {\n try {\n fs.rmSync(guard.assert(path.join(dataDir, rel)), { force: true });\n removed.push(rel);\n } catch {\n /* already gone */\n }\n }\n }\n return removed;\n}\n","// User profile types (design doc §3). Fourth store: warm, structured,\n// slow-evolving model of the user. Not the material pool (hot cache), not\n// DSH long-term memory (conversation-validated layer).\n\nexport type Partition = 'interest' | 'projects' | 'comm' | 'psy';\nexport type Temporal = 'volatile' | 'stable';\nexport type EvidenceKind = 'chat' | 'screen' | 'browse' | 'hand' | 'ledger';\n\nexport interface Evidence {\n kind: EvidenceKind;\n at: string;\n /** Pointer to an existing audit/log location, e.g. \"heartbeat.jsonl#2026-09-06T12:00:00Z\". */\n ref: string;\n /** At most ONE short quote (<=1 sentence). Never raw conversation/screen text. */\n quote?: string;\n}\n\nexport interface ProfileEntry {\n id: string;\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n /** 0..1; capped per source kind (chat .6 / screen .4 / browse .4). */\n confidence: number;\n temporal: Temporal;\n validFrom: string;\n validTo: string | null;\n supersededBy: string | null;\n evidence: Evidence[];\n createdAt: string;\n updatedAt: string;\n updateCount: number;\n /** stable-tier audit flag (180d without observation): digest deprioritizes. */\n lowActivity?: boolean;\n}\n\nexport interface ProfileDoc {\n version: number;\n partitions: Record<Partition, { entries: ProfileEntry[] }>;\n}\n\nexport interface InboxItem {\n id?: string;\n kind: EvidenceKind;\n at: string;\n ref: string;\n /** <= 1 short sentence; never raw conversation/screen text (truncated by writer). */\n note: string;\n}\n\nexport type ProfileOp =\n | {\n op: 'ADD';\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n temporal?: Temporal;\n confidence?: number;\n why: string;\n evidence: Evidence[];\n /** Assigned by the store at apply time so journal replay preserves ids. */\n assignedId?: string;\n }\n | { op: 'UPDATE'; id: string; changes: { content?: string; confidence?: number }; why: string }\n | { op: 'INVALIDATE'; id: string; why: string; evidence?: Evidence[] }\n | { op: 'NOOP'; why: string };\n\n/**\n * Journal line schema version. Absent = v1: replay applies the applied ops\n * permissively. v2 adds entries — the canonical, code-written post-run entry\n * states (aging included) — and replay upserts those verbatim. That is what\n * makes the live write path and replay ONE state machine (review ③A / HB-09).\n */\nexport const JOURNAL_VERSION = 2;\n\nexport interface JournalRecord {\n v?: number;\n ts: string;\n runId: string;\n /** The model's original intent: audit mirror + the v1 replay path. */\n applied: ProfileOp[];\n rejected: { op: unknown; reason: string }[];\n /** v2 replay path: one full entry snapshot per entry this run touched.\n * Written by code; the model can never reach this field. */\n entries?: ProfileEntry[];\n}\n\nexport interface ApplyReport {\n applied: ProfileOp[];\n rejected: { op: unknown; reason: string }[];\n /** v2 journal events: the full post-state of every entry this run touched. */\n entries?: ProfileEntry[];\n}\n\nexport const PARTITIONS: readonly Partition[] = ['interest', 'projects', 'comm', 'psy'];\n\nexport const CONFIDENCE_CAP: Record<EvidenceKind, number> = {\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n hand: 1.0,\n ledger: 0.6,\n};\n\nexport function emptyProfile(): ProfileDoc {\n return {\n version: 1,\n partitions: { interest: { entries: [] }, projects: { entries: [] }, comm: { entries: [] }, psy: { entries: [] } },\n };\n}\n","// profile-schema.json loading + ADD validation (r4 B10: temporal tier is an\n// ENTRY-level attribute; the schema declares, per sub_topic, the ALLOWED tier\n// set and the DEFAULT. Unlisted defaults to 'stable'.)\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Partition, Temporal } from './types.js';\n\nexport interface SubTopicDecl {\n allowed?: Temporal[];\n default?: Temporal;\n}\n\nexport interface ProfileSchema {\n version: number;\n partitions: Partial<Record<Partition, {\n topics: Record<string, { subtopics: Record<string, SubTopicDecl> }>;\n }>>;\n}\n\nexport interface SchemaLoad {\n /** The schema to use, or undefined when even the factory copy is unusable. */\n schema?: ProfileSchema;\n /** Where the returned schema came from. */\n source: 'user' | 'factory' | 'none';\n /** Set when the chosen schema is not the first choice (H-17 fallback). */\n fallbackReason?: string;\n}\n\n/**\n * H-17: three-tier load. This file is user-editable by design, so a broken\n * comma used to throw on every beat — `runConsolidation` aborted before\n * `inboxClear`, the inbox grew forever and the profile froze with no way back.\n * Now: a bad user copy falls back to the factory copy (audited by the caller);\n * an unusable factory copy yields `undefined`, which callers read as \"no\n * whitelist\" instead of a fatal error.\n */\nexport function loadProfileSchema(paths: { configDir: string; settingsDir: string }): SchemaLoad {\n const userPath = path.join(paths.settingsDir, 'profile-schema.json');\n const factoryPath = path.join(paths.configDir, 'profile-schema.json');\n const read = (file: string): { schema?: ProfileSchema; error: string } => {\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as ProfileSchema;\n if (!raw.partitions) return { error: 'partitions missing' };\n return { schema: raw, error: '' };\n } catch (e) {\n return { error: String(e) };\n }\n };\n const user = fs.existsSync(userPath) ? read(userPath) : null;\n if (user?.schema) return { schema: user.schema, source: 'user' };\n const factory = read(factoryPath);\n if (factory.schema) {\n return user\n ? {\n schema: factory.schema,\n source: 'factory',\n fallbackReason: `user profile-schema.json unusable (${user.error}) — fell back to the factory copy`,\n }\n : { schema: factory.schema, source: 'factory' };\n }\n return {\n source: 'none',\n fallbackReason: `no usable profile-schema.json (user: ${user?.error ?? 'absent'}; factory: ${factory.error})`,\n };\n}\n\nexport interface SchemaCheck {\n ok: boolean;\n reason?: string;\n temporal: Temporal;\n}\n\n/**\n * Validate an ADD against the whitelist and resolve the entry's temporal tier:\n * LLM nominates within the sub_topic's allowed set; missing nomination falls\n * back to the declared default; fully unlisted -> reject (charter boundary).\n */\nexport function checkAddAgainstSchema(\n schema: ProfileSchema,\n partition: Partition,\n topic: string,\n subTopic: string,\n nominated?: Temporal,\n): SchemaCheck {\n const p = schema.partitions[partition];\n if (!p) return { ok: false, reason: `partition not in schema: ${partition}`, temporal: 'stable' };\n const t = p.topics[topic];\n if (!t) return { ok: false, reason: `topic not in schema: ${partition}/${topic}`, temporal: 'stable' };\n const st = t.subtopics[subTopic];\n if (!st) return { ok: false, reason: `sub_topic not in schema: ${partition}/${topic}/${subTopic}`, temporal: 'stable' };\n const allowed: Temporal[] = st.allowed && st.allowed.length > 0 ? st.allowed : ['stable'];\n const def: Temporal = st.default && allowed.includes(st.default) ? st.default : allowed[0]!;\n if (!nominated) return { ok: true, temporal: def };\n if (!allowed.includes(nominated)) {\n return {\n ok: false,\n reason: `temporal \"${nominated}\" not allowed for ${partition}/${topic}/${subTopic} (allowed: ${allowed.join('|')})`,\n temporal: def,\n };\n }\n return { ok: true, temporal: nominated };\n}\n","// Foreign-shape boundaries (review 2026-10-17 ⑧A). Every place that accepts\n// data this code did not just build itself — the model's op array, journal\n// lines, inbox lines, migration packages, RPC payloads — is checked against\n// ONE schemastery definition here, instead of poking at properties ad hoc at\n// each call site (HB-12: a malformed op used to reach the guards and throw\n// somewhere in the middle of apply).\n//\n// schemastery objects are permissive on purpose: an absent field is simply\n// absent (no error) and unknown keys ride through. Profile boundaries need the\n// opposite, so closed() adds the two rules schemastery leaves out — required\n// keys and a closed key set — and check() applies them before field types run.\n\nimport z from '@deepseek-ai/schemastery';\nimport {\n JOURNAL_VERSION,\n PARTITIONS,\n type Evidence,\n type EvidenceKind,\n type InboxItem,\n type JournalRecord,\n type Partition,\n type ProfileEntry,\n type ProfileOp,\n type Temporal,\n} from './types.js';\n\nexport class ShapeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ShapeError';\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describe(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'an array';\n return typeof v;\n}\n\n/** A required key. A nullable one accepts `null` as a real value (validTo /\n * supersededBy) instead of reading it as absent. */\ntype Req = string | { key: string; nullable: true };\n\ninterface Closed {\n schema: Schemastery<any, any>;\n keys: readonly string[];\n required: readonly Req[];\n}\n\nfunction closed(\n schema: Schemastery<any, any>,\n keys: readonly string[],\n required: readonly Req[] = keys,\n): Closed {\n return { schema, keys, required };\n}\n\n/** object-ness -> required keys -> closed key set -> schemastery field types. */\nfunction check(shape: Closed, value: unknown, label: string): Record<string, unknown> {\n if (!isPlainObject(value)) throw new ShapeError(`${label}: expected an object, got ${describe(value)}`);\n for (const req of shape.required) {\n const key = typeof req === 'string' ? req : req.key;\n const nullable = typeof req !== 'string' && req.nullable;\n if (value[key] === undefined || (value[key] === null && !nullable)) {\n throw new ShapeError(`${label}.${key}: missing required value`);\n }\n }\n for (const k of Object.keys(value)) {\n if (!shape.keys.includes(k)) throw new ShapeError(`${label}.${k}: unknown field`);\n }\n try {\n return shape.schema(value) as Record<string, unknown>;\n } catch (e) {\n throw new ShapeError(`${label}: ${e instanceof Error ? e.message : String(e)}`);\n }\n}\n\nconst Str = z.string().required();\nconst Num = z.number().required();\n// No .required() on this one: schemastery reads null as \"absent\", but null is\n// a real value for validTo / supersededBy. check() enforces presence instead.\nconst NullableStr = z.union([z.string(), z.const(null)]);\nconst PartitionEnum = z.union(PARTITIONS.map((p) => z.const(p))).required();\nconst TemporalEnum = z.union([z.const('stable'), z.const('volatile')]).required();\n/** Same set, optional: the model may omit temporal and take the schema default. */\nconst OptionalTemporal = z.union([z.const('stable'), z.const('volatile')]);\nconst KindEnum = z.union([\n z.const('chat'),\n z.const('screen'),\n z.const('browse'),\n z.const('hand'),\n z.const('ledger'),\n]).required();\nconst ConfidenceNum = z.number().min(0).max(1).required();\n\n// ── evidence ────────────────────────────────────────────────────────────────\n\nconst EvidenceShape = closed(\n z.object({ kind: KindEnum, at: Str, ref: Str, quote: z.string() }),\n ['kind', 'at', 'ref', 'quote'],\n ['kind', 'at', 'ref'],\n);\n\nexport function parseEvidence(value: unknown, label = 'evidence'): Evidence {\n const o = check(EvidenceShape, value, label);\n return {\n kind: o.kind as EvidenceKind,\n at: String(o.at),\n ref: String(o.ref),\n ...(o.quote === undefined ? {} : { quote: String(o.quote) }),\n };\n}\n\nfunction parseEvidenceList(value: unknown, label: string): Evidence[] {\n if (!Array.isArray(value)) throw new ShapeError(`${label}: expected an array`);\n return value.map((v, i) => parseEvidence(v, `${label}[${i}]`));\n}\n\n// ── stored entry (journal v2 / migration packages) ──────────────────────────\n\nconst EntryShape = closed(\n z.object({\n id: Str,\n partition: PartitionEnum,\n topic: Str,\n subTopic: Str,\n content: Str,\n confidence: ConfidenceNum,\n temporal: TemporalEnum,\n validFrom: Str,\n validTo: NullableStr,\n supersededBy: NullableStr,\n evidence: z.array(z.any()).required(),\n createdAt: Str,\n updatedAt: Str,\n updateCount: Num,\n lowActivity: z.boolean(),\n }),\n ['id', 'partition', 'topic', 'subTopic', 'content', 'confidence', 'temporal', 'validFrom', 'validTo',\n 'supersededBy', 'evidence', 'createdAt', 'updatedAt', 'updateCount', 'lowActivity'],\n ['id', 'partition', 'topic', 'subTopic', 'content', 'confidence', 'temporal', 'validFrom',\n { key: 'validTo', nullable: true }, { key: 'supersededBy', nullable: true },\n 'evidence', 'createdAt', 'updatedAt', 'updateCount'],\n);\n\nexport function parseProfileEntry(value: unknown, label = 'entry'): ProfileEntry {\n const o = check(EntryShape, value, label);\n return {\n id: String(o.id),\n partition: o.partition as Partition,\n topic: String(o.topic),\n subTopic: String(o.subTopic),\n content: String(o.content),\n confidence: Number(o.confidence),\n temporal: o.temporal as Temporal,\n validFrom: String(o.validFrom),\n validTo: o.validTo === null ? null : String(o.validTo),\n supersededBy: o.supersededBy === null ? null : String(o.supersededBy),\n evidence: parseEvidenceList(o.evidence, `${label}.evidence`),\n createdAt: String(o.createdAt),\n updatedAt: String(o.updatedAt),\n updateCount: Number(o.updateCount),\n ...(o.lowActivity === undefined ? {} : { lowActivity: Boolean(o.lowActivity) }),\n };\n}\n\n// ── inbox line ──────────────────────────────────────────────────────────────\n\nconst InboxShape = closed(\n z.object({ id: z.string(), kind: KindEnum, at: Str, ref: Str, note: z.string() }),\n ['id', 'kind', 'at', 'ref', 'note'],\n ['kind', 'at', 'ref'],\n);\n\nexport function parseInboxItem(value: unknown, label = 'inbox item'): InboxItem {\n const o = check(InboxShape, value, label);\n return {\n ...(o.id === undefined ? {} : { id: String(o.id) }),\n kind: o.kind as EvidenceKind,\n at: String(o.at),\n ref: String(o.ref),\n note: o.note === undefined ? '' : String(o.note),\n };\n}\n\n// ── the model's op array (③A: ids in, evidence out) ─────────────────────────\n//\n// The model never supplies refs, timestamps or evidence kinds any more — it\n// cites observation ids from THIS batch (o1, o2, …) and the caller turns them\n// into Evidence objects. HB-05's forged provenance (a made-up \"hand\" ref used\n// to pin confidence at 1.0) is unreachable by construction.\n\nexport type ProposedOp =\n | {\n op: 'ADD';\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n temporal?: Temporal;\n confidence?: number;\n why: string;\n evidenceRefs: string[];\n }\n | { op: 'UPDATE'; id: string; changes: { content?: string; confidence?: number }; why: string }\n | { op: 'INVALIDATE'; id: string; why: string; evidenceRefs: string[] }\n | { op: 'NOOP'; why: string };\n\nconst AddShape = closed(\n z.object({\n op: z.const('ADD').required(),\n partition: PartitionEnum,\n topic: Str,\n subTopic: Str,\n content: Str,\n temporal: OptionalTemporal,\n confidence: z.number().min(0).max(1),\n why: z.string(),\n evidence: z.array(z.any()).required(),\n }),\n ['op', 'partition', 'topic', 'subTopic', 'content', 'temporal', 'confidence', 'why', 'evidence'],\n ['op', 'partition', 'topic', 'subTopic', 'content', 'evidence'],\n);\n\nconst UpdateShape = closed(\n z.object({\n op: z.const('UPDATE').required(),\n id: Str,\n changes: z.object({ content: z.string(), confidence: z.number().min(0).max(1) }),\n why: z.string(),\n }),\n ['op', 'id', 'changes', 'why'],\n ['op', 'id', 'changes'],\n);\n\nconst InvalidateShape = closed(\n z.object({\n op: z.const('INVALIDATE').required(),\n id: Str,\n why: z.string(),\n evidence: z.array(z.any()),\n }),\n ['op', 'id', 'why', 'evidence'],\n ['op', 'id'],\n);\n\nconst NoopShape = closed(\n z.object({ op: z.const('NOOP').required(), why: z.string() }),\n ['op', 'why'],\n ['op'],\n);\n\nfunction parseObservationRefs(value: unknown, label: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new ShapeError(`${label}: expected an array of observation ids`);\n return value.map((v, i) => {\n if (typeof v !== 'string' || !v.trim()) {\n throw new ShapeError(`${label}[${i}]: expected an observation id like \"o1\" (refs, timestamps and kinds are code-generated)`);\n }\n return v.trim();\n });\n}\n\nfunction parseProposedOp(raw: unknown, label: string): ProposedOp {\n if (!isPlainObject(raw)) throw new ShapeError(`${label}: expected an object, got ${describe(raw)}`);\n const tag = raw.op;\n if (tag === 'ADD') {\n const o = check(AddShape, raw, label);\n const evidenceRefs = parseObservationRefs(o.evidence, `${label}.evidence`);\n if (evidenceRefs.length === 0) {\n throw new ShapeError(`${label}.evidence: ADD needs at least one observation id (axiom 1: no provenance, no memory)`);\n }\n return {\n op: 'ADD',\n partition: o.partition as Partition,\n topic: String(o.topic),\n subTopic: String(o.subTopic),\n content: String(o.content),\n ...(o.temporal === undefined ? {} : { temporal: o.temporal as Temporal }),\n ...(o.confidence === undefined ? {} : { confidence: Number(o.confidence) }),\n why: typeof o.why === 'string' ? o.why : '',\n evidenceRefs,\n };\n }\n if (tag === 'UPDATE') {\n const o = check(UpdateShape, raw, label);\n const changes = o.changes as Record<string, unknown>;\n const out: { content?: string; confidence?: number } = {};\n if (changes.content !== undefined) out.content = String(changes.content);\n if (changes.confidence !== undefined) out.confidence = Number(changes.confidence);\n if (out.content === undefined && out.confidence === undefined) {\n throw new ShapeError(`${label}.changes: needs content or confidence`);\n }\n return { op: 'UPDATE', id: String(o.id), changes: out, why: typeof o.why === 'string' ? o.why : '' };\n }\n if (tag === 'INVALIDATE') {\n const o = check(InvalidateShape, raw, label);\n return {\n op: 'INVALIDATE',\n id: String(o.id),\n why: typeof o.why === 'string' ? o.why : '',\n evidenceRefs: parseObservationRefs(o.evidence, `${label}.evidence`),\n };\n }\n if (tag === 'NOOP') {\n const o = check(NoopShape, raw, label);\n return { op: 'NOOP', why: typeof o.why === 'string' ? o.why : '' };\n }\n throw new ShapeError(`${label}.op: unknown op ${JSON.stringify(tag)}`);\n}\n\nexport interface OpParseResult {\n ops: ProposedOp[];\n /** One malformed row never discards the rest of the batch, but it is always\n * reported — silence here used to look like \"the model proposed nothing\". */\n rejected: { op: unknown; reason: string }[];\n}\n\nexport function parseProposedOps(list: unknown[]): OpParseResult {\n const ops: ProposedOp[] = [];\n const rejected: { op: unknown; reason: string }[] = [];\n list.forEach((raw, i) => {\n try {\n ops.push(parseProposedOp(raw, `op[${i}]`));\n } catch (e) {\n rejected.push({ op: raw, reason: e instanceof Error ? e.message : String(e) });\n }\n });\n return { ops, rejected };\n}\n\n/** Turn cited observation ids into code-built evidence. Unknown ids are a\n * rejection, never a silent drop: the op then has no provenance. */\nexport function materializeEvidence(\n refs: string[],\n observations: Map<string, InboxItem>,\n label: string,\n): { evidence: Evidence[]; reason?: string } {\n const evidence: Evidence[] = [];\n for (const ref of refs) {\n const item = observations.get(ref);\n if (!item) return { evidence: [], reason: `${label}: ${ref} does not match any observation in this batch` };\n evidence.push({ kind: item.kind, at: item.at, ref: item.ref });\n }\n return { evidence };\n}\n\n// ── journal line reader (replay path) ───────────────────────────────────────\n//\n// Lenient on purpose: a line this code did not write is skipped by the caller,\n// never fatal. The journal is append-only and immutable, so one bad line must\n// not freeze the profile — but it IS counted (ReplayResult.badRecords) so a\n// silent data loss is visible in profile verify.\n\nexport function tryParseJournalRecord(value: unknown): JournalRecord | null {\n try {\n if (!isPlainObject(value)) return null;\n const rec: JournalRecord = {\n ts: typeof value.ts === 'string' ? value.ts : '',\n runId: typeof value.runId === 'string' ? value.runId : '',\n applied: Array.isArray(value.applied) ? (value.applied as ProfileOp[]) : [],\n rejected: Array.isArray(value.rejected) ? (value.rejected as { op: unknown; reason: string }[]) : [],\n };\n if (value.v === JOURNAL_VERSION) {\n if (!Array.isArray(value.entries)) return null;\n rec.v = JOURNAL_VERSION;\n rec.entries = value.entries.map((e, i) => parseProfileEntry(e, `entries[${i}]`));\n }\n return rec;\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAIA,OAAO,QAAQ;AACf,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Q;AACN,aAAO,CAAC;AAAA,IACV;AACA,eAAW,OAAO,MAAM;AACtB,UAAI;AACF,QAAAA,IAAG,OAAO,MAAM,OAAOD,MAAK,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC;AAChE,gBAAQ,KAAK,GAAG;AAAA,MAClB,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":["path","fs","fs","path","path","fs","check"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/atomic-fs.ts"],"sourcesContent":["// Crash-safe file replacement: write to a random-suffix temp file in the SAME\n// directory as the target, then rename over it. Same-directory rename stays\n// on one volume (atomic) and Node's rename replaces existing files on Windows.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { randomUUID, randomFillSync } from 'node:crypto';\n\nexport function tmpSibling(target: string, tag = 'w'): string {\n return path.join(\n path.dirname(target),\n `.${path.basename(target)}.${tag}-${randomUUID().slice(0, 8)}.tmp`,\n );\n}\n\nexport function atomicWriteFileSync(target: string, data: string | Uint8Array): void {\n const tmp = tmpSibling(target);\n let fd: number | null = null;\n try {\n fd = fs.openSync(tmp, 'w');\n fs.writeFileSync(fd, data);\n // 低优先级 review (2026-10-17): rename is atomic against a crash of THIS\n // process, but without a flush the renamed file can still point at blocks\n // the OS never wrote — a power loss then leaves an empty or partial file\n // where a complete one is promised. Flush before publishing.\n fs.fsyncSync(fd);\n fs.closeSync(fd);\n fd = null;\n fs.renameSync(tmp, target);\n } finally {\n if (fd !== null) {\n try { fs.closeSync(fd); } catch { /* the write path already failed */ }\n }\n fs.rmSync(tmp, { force: true });\n }\n}\n\nexport function atomicWriteJsonSync(target: string, value: unknown): void {\n atomicWriteFileSync(target, JSON.stringify(value, null, 2));\n}\n\n/** Overwrite a file's bytes with random data before unlinking. */\nexport function shredFileSync(target: string, passes = 3): void {\n const stat = fs.statSync(target);\n if (!stat.isFile()) throw new Error(`shred: not a file: ${target}`);\n const buf = Buffer.alloc(Math.max(stat.size, 1));\n for (let i = 0; i < passes; i++) {\n randomFillSync(buf);\n fs.writeFileSync(target, buf);\n }\n fs.rmSync(target, { force: true });\n}\n\n/**\n * Best-effort burn for a plaintext window: shred it when it exists, ignore it\n * when it is already gone (H-59 — `rm` alone leaves the bytes on disk).\n */\nexport function burnFileSync(target: string): void {\n try {\n shredFileSync(target);\n } catch {\n fs.rmSync(target, { force: true });\n }\n}\n"],"mappings":";AAIA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,YAAY,sBAAsB;AAEpC,SAAS,WAAW,QAAgB,MAAM,KAAa;AAC5D,SAAO,KAAK;AAAA,IACV,KAAK,QAAQ,MAAM;AAAA,IACnB,IAAI,KAAK,SAAS,MAAM,CAAC,IAAI,GAAG,IAAI,WAAW,EAAE,MAAM,GAAG,CAAC,CAAC;AAAA,EAC9D;AACF;AAEO,SAAS,oBAAoB,QAAgB,MAAiC;AACnF,QAAM,MAAM,WAAW,MAAM;AAC7B,MAAI,KAAoB;AACxB,MAAI;AACF,SAAK,GAAG,SAAS,KAAK,GAAG;AACzB,OAAG,cAAc,IAAI,IAAI;AAKzB,OAAG,UAAU,EAAE;AACf,OAAG,UAAU,EAAE;AACf,SAAK;AACL,OAAG,WAAW,KAAK,MAAM;AAAA,EAC3B,UAAE;AACA,QAAI,OAAO,MAAM;AACf,UAAI;AAAE,WAAG,UAAU,EAAE;AAAA,MAAG,QAAQ;AAAA,MAAsC;AAAA,IACxE;AACA,OAAG,OAAO,KAAK,EAAE,OAAO,KAAK,CAAC;AAAA,EAChC;AACF;AAEO,SAAS,oBAAoB,QAAgB,OAAsB;AACxE,sBAAoB,QAAQ,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAC5D;AAGO,SAAS,cAAc,QAAgB,SAAS,GAAS;AAC9D,QAAM,OAAO,GAAG,SAAS,MAAM;AAC/B,MAAI,CAAC,KAAK,OAAO,EAAG,OAAM,IAAI,MAAM,sBAAsB,MAAM,EAAE;AAClE,QAAM,MAAM,OAAO,MAAM,KAAK,IAAI,KAAK,MAAM,CAAC,CAAC;AAC/C,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,mBAAe,GAAG;AAClB,OAAG,cAAc,QAAQ,GAAG;AAAA,EAC9B;AACA,KAAG,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AACnC;AAMO,SAAS,aAAa,QAAsB;AACjD,MAAI;AACF,kBAAc,MAAM;AAAA,EACtB,QAAQ;AACN,OAAG,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,EACnC;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/time-window.ts","../src/ledger/ledger.ts","../src/browse/preference.ts","../src/browse/browse.ts","../src/notify/notify.ts","../src/core/ps.ts","../src/weekly/report.ts"],"sourcesContent":["// Shared HH:MM window arithmetic.\n//\n// H-14: quiet hours (`gate.ts`) and wander windows (`browse.ts`) each carried\n// their own copy of this comparison, and only ONE of them handled a window\n// that crosses midnight — so a `22:00-02:00` wander window silently never\n// matched. One implementation, one set of semantics, no drift.\n//\n// Interval is left-closed / right-open, so `22:00-02:00` and `02:00-06:00`\n// never overlap and every minute belongs to at most one window.\n\nconst HH_MM = /^(\\d{1,2}):(\\d{2})$/;\n\n/** \"22:30\" -> 1350; null when malformed (callers treat that as \"never matches\"). */\nexport function parseHhMm(text: string): number | null {\n const m = HH_MM.exec(String(text).trim());\n if (!m) return null;\n const h = Number(m[1]);\n const min = Number(m[2]);\n if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;\n return h * 60 + min;\n}\n\nexport function minutesOfDay(now: Date): number {\n return now.getHours() * 60 + now.getMinutes();\n}\n\n/** TRUE when `mins` (minutes since local midnight) falls inside [start, end). */\nexport function inHhMmWindow(start: string, end: string, mins: number): boolean {\n const s = parseHhMm(start);\n const e = parseHhMm(end);\n if (s === null || e === null) return false;\n if (s === e) return false; // zero-length window matches nothing\n return s > e ? mins >= s || mins < e : mins >= s && mins < e;\n}\n\n/** LOCAL calendar day key \"YYYY-MM-DD\" (H-88, 2026-10-29).\n *\n * \"Today\" is a human day, not a UTC day: a user at 07:00 local in UTC+8 is\n * still on the previous UTC date, so a UTC key rolls the day over mid-morning\n * and every daily budget resets at the wrong hour. Browsing's refill quota\n * already worked this way (it kept a private copy); the ledger's aging\n * window, the rhythm ring and the export filenames now share this one. */\nexport function localDayKey(d: Date = new Date()): string {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n","// Ledger (\"账本\") - the ONE shared ledger (design doc §5, requirement 5).\n// Human-readable Markdown by charter; the user may edit it by hand, so the\n// parser is tolerant: unknown lines are preserved verbatim on rewrite.\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { readText, writeText } from '../vault/vault.js';\nimport { localDayKey } from '../core/time-window.js';\n\nconst DAY_MS = 86_400_000;\n\nexport interface LedgerEntry {\n id: string;\n date: string; // \"YYYY-MM-DD\"\n time: string; // \"HH:MM\"\n status: 'open' | 'done';\n text: string;\n}\n\nexport function ledgerFilePath(dataDir: string): string {\n return path.join(dataDir, 'ledger.md');\n}\n\n// The id is written by hand sometimes (`#net-backup-20260914`), and a\n// `{6}` hex rule silently dropped such rows: they stayed in rawLines but never\n// became entries, so scanPending failed to see them and markDone could not\n// find them. Any run of non-] non-space characters parses now; ids this plugin\n// generates itself are still 6 hex chars of a UUID.\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[(open|done)\\]\\[#([^\\]\\s]+)\\] (.*)$/;\n\nfunction renderEntry(e: LedgerEntry): string {\n return `- [${e.date} ${e.time}][${e.status}][#${e.id}] ${e.text}`;\n}\n\nexport function readLedger(guard: PathGuard, file: string): { header: string; entries: LedgerEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, '# 账本\\n');\n const lines = raw.split('\\n');\n const entries: LedgerEntry[] = [];\n const rawLines: string[] = [];\n for (const line of lines) {\n const m = LINE_RE.exec(line);\n if (m) {\n entries.push({ date: m[1]!, time: m[2]!, status: m[3] as 'open' | 'done', id: m[4]!, text: m[5]! });\n }\n rawLines.push(line);\n }\n return { header: lines[0] ?? '# 账本', entries, rawLines };\n}\n\nexport function appendEntry(guard: PathGuard, file: string, text: string, now = Date.now()): LedgerEntry {\n const textTrimmed = text.trim();\n if (!textTrimmed) throw new Error('ledger entry must not be empty');\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const entry: LedgerEntry = {\n id: randomUUID().slice(0, 6),\n date: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,\n time: `${pad(d.getHours())}:${pad(d.getMinutes())}`,\n status: 'open',\n text: textTrimmed.replace(/\\r?\\n/g, ' '),\n };\n const { rawLines } = readLedger(guard, file);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n}\n\n/** Mark an entry done by id (preferred) or unique text substring. The date is\n * restamped to the completion day (time was already) so weekly reporting can\n * count \"resolved this week\" — the creation timestamp lives on in nothing,\n * but done entries are rarely aged against. */\nexport function markDone(guard: PathGuard, file: string, key: string, now = Date.now()): LedgerEntry | null {\n const { rawLines, entries } = readLedger(guard, file);\n const target = entries.find((e) => e.status === 'open' && (e.id === key || e.text.includes(key)));\n if (!target) return null;\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const doneDate = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n const out = rawLines.map((line) => {\n if (line.includes(`#${target.id}] `)) {\n return `- [${doneDate} ${pad(d.getHours())}:${pad(d.getMinutes())}][done][#${target.id}] ${target.text}`;\n }\n return line;\n });\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return target;\n}\n\n/** Open items for the reflection digest (§7.6 账本待办). */\nexport function scanPending(guard: PathGuard, file: string, now = Date.now()): LedgerEntry[] {\n const { entries } = readLedger(guard, file);\n return entries.filter((e) => e.status === 'open').sort((a, b) => (a.date < b.date ? -1 : 1));\n}\n\n/** Open entries older than N days (跟进时机的\"自然到期\"参考,§3.1 四问之一). */\nexport function pendingOlderThan(guard: PathGuard, file: string, days: number, now = Date.now()): LedgerEntry[] {\n const cutoff = localDayKey(new Date(now - days * DAY_MS));\n return scanPending(guard, file, now).filter((e) => e.date <= cutoff);\n}\n","// Topic preference (2026-10-06): consumption-driven bias for wander focus\n// selection. The persona's seed_report attributions (and the engine-room\n// fallback) fold into per-topic delivered/adopted counters; pickFocus reads\n// the smoothed rate as a weight on top of round-robin recency.\n//\n// Anti-lockdown guarantees (user-reviewed design):\n// - weight clamped to [W_MIN, W_MAX] — a favorite doubles at most, a cold\n// topic never drops below half;\n// - Laplace smoothing — a topic with no data sits near neutral, not zero;\n// - exponential decay (30-day half-life) — old glory fades;\n// - pickFocus additionally enforces a hard starvation floor (14 days).\n//\n// Storage is one JSON file through the vault (DPAPI): topic keys derive from\n// the user's profile/interests, so they are user-adjacent data.\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\n\nconst DAY_MS = 86_400_000;\n\nexport const W_MIN = 0.5;\nexport const W_MAX = 2;\n/** Laplace prior: rate = (adopted + A) / (delivered + D). Neutral ≈ A/D. */\nexport const SMOOTH_ADOPTED = 1;\nexport const SMOOTH_DELIVERED = 4;\n/** Counts decay with this half-life (days) since the topic's last activity. */\nexport const DECAY_HALF_LIFE_DAYS = 30;\n\nexport interface TopicPref {\n delivered: number;\n adopted: number;\n lastDeliveredAt: number;\n lastAdoptedAt: number;\n}\n\nexport interface PrefState {\n version: 1;\n topics: Record<string, TopicPref>;\n updatedAt: number;\n}\n\nexport function preferenceFilePath(dataDir: string): string {\n return path.join(dataDir, 'preference.json');\n}\n\n/** Non-negative finite number or 0 (v1.9.0 guard against hand-edited files). */\nfunction num(v: unknown): number {\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 ? n : 0;\n}\n\n/** One stored entry → a trustworthy counter. Returns null for a garbled entry:\n * a NaN delivered/adopted used to survive the load and poison the whole\n * ordering (NaN makes every comparison false, so the topic neither aged nor\n * sorted). Dropping the entry is the safe read — the loop refills it. */\nfunction sanitizeTopicPref(raw: unknown): TopicPref | null {\n if (!raw || typeof raw !== 'object') return null;\n const t = raw as Partial<TopicPref>;\n if (!Number.isFinite(Number(t.delivered)) || !Number.isFinite(Number(t.adopted))) return null;\n const delivered = Math.floor(num(t.delivered));\n return {\n delivered,\n adopted: Math.min(delivered, Math.floor(num(t.adopted))),\n lastDeliveredAt: num(t.lastDeliveredAt),\n lastAdoptedAt: num(t.lastAdoptedAt),\n };\n}\n\nexport function loadPreference(guard: PathGuard, file: string): PrefState {\n const doc = loadJson<Partial<PrefState>>(guard, file);\n if (!doc || typeof doc !== 'object' || !doc.topics || typeof doc.topics !== 'object') {\n return { version: 1, topics: {}, updatedAt: 0 };\n }\n const topics: Record<string, TopicPref> = {};\n for (const [key, raw] of Object.entries(doc.topics)) {\n const t = sanitizeTopicPref(raw);\n if (key && t) topics[key] = t;\n }\n const updatedAt = Number(doc.updatedAt);\n return { version: 1, topics, updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0 };\n}\n\nexport function savePreference(guard: PathGuard, file: string, state: PrefState): void {\n saveJson(guard, file, state);\n}\n\n/** Fold one delivery into the counters. offeredTopics = every topic in the\n * package; adoptedTopics = the credited ones (subset by construction — unknown\n * keys are still tolerated so the two lists can drift safely). */\nexport function recordDelivery(\n guard: PathGuard,\n file: string,\n opts: { offeredTopics: string[]; adoptedTopics: string[]; now: number },\n): PrefState {\n const state = loadPreference(guard, file);\n const adopted = new Set(opts.adoptedTopics);\n for (const topic of opts.offeredTopics) {\n if (!topic) continue;\n const t = state.topics[topic] ?? { delivered: 0, adopted: 0, lastDeliveredAt: 0, lastAdoptedAt: 0 };\n t.delivered += 1;\n t.lastDeliveredAt = opts.now;\n if (adopted.has(topic)) {\n t.adopted += 1;\n t.lastAdoptedAt = opts.now;\n }\n state.topics[topic] = t;\n }\n state.updatedAt = opts.now;\n savePreference(guard, file, state);\n return state;\n}\n\n/** Time-decayed counts (30-day half-life since last activity of each kind). */\nexport function decayed(t: TopicPref, now: number): { delivered: number; adopted: number } {\n const dAgeDays = Math.max(0, now - t.lastDeliveredAt) / DAY_MS;\n const aAgeDays = Math.max(0, now - t.lastAdoptedAt) / DAY_MS;\n const dHalf = Math.pow(0.5, dAgeDays / DECAY_HALF_LIFE_DAYS);\n const aHalf = Math.pow(0.5, aAgeDays / DECAY_HALF_LIFE_DAYS);\n return { delivered: t.delivered * dHalf, adopted: t.adopted * aHalf };\n}\n\n/**\n * Preference weight for a topic, clamped to [W_MIN, W_MAX]:\n * rate = (decayed adopted + 1) / (decayed delivered + 4) (neutral = 0.25)\n * w = clamp(rate / 0.25, W_MIN, W_MAX)\n * No data at all → rate 1/4 → w 1.0: a brand-new topic starts exactly neutral\n * (per design: \"0.2 附近的中间值,不是 0 分垫底\"); repeated \"delivered but\n * never adopted\" drags it toward W_MIN, consistent adoption lifts it to W_MAX.\n */\nexport function preferenceWeight(state: PrefState, topic: string, now: number): number {\n const t = state.topics[topic];\n const rate = t\n ? (() => {\n const d = decayed(t, now);\n return (d.adopted + SMOOTH_ADOPTED) / (d.delivered + SMOOTH_DELIVERED);\n })()\n : SMOOTH_ADOPTED / SMOOTH_DELIVERED;\n return Math.min(W_MAX, Math.max(W_MIN, rate / (SMOOTH_ADOPTED / SMOOTH_DELIVERED)));\n}\n","// Browse flow (v0.9.5 port, r4 D10 applied).\n// Wander adjudication: windows + min interval + focus cooldown ->\n// \"should we wander now, and at what focus\". The actual search happens\n// in the wander phase's model call (web_search only); REGISTRATION IS\n// CODE-OWNED (D10): results land in seeds + throttle via completeWander.\n//\n// H-12 (2026-10-07): the npm/GitHub watchlist check was removed. It never ran\n// inside the beat (only `browse watch` in the CLI called it, throttled-off),\n// and \"is DSH itself updated\" is not this plugin's job to track.\n//\n// Anti-injection rule (unchanged from v0.7): web content is data, never\n// instructions.\n//\n// State: data/browse.json (DPAPI-encrypted, D14; v1 name: watch_state.json).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport type { Policy } from '../config/schema.js';\nimport { inHhMmWindow, localDayKey, minutesOfDay } from '../core/time-window.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\nimport { activeSeeds, loadPool, normalizeCategory, seedsFilePath } from '../seeds/pool.js';\nimport { loadPreference, preferenceFilePath, preferenceWeight, type PrefState } from './preference.js';\n\nexport interface InterestsConfig {\n interests?: string[];\n _schedule?: {\n daily_sessions?: number;\n focus_per_session?: number;\n max_seeds_per_focus?: number;\n focus_cooldown_days?: number;\n min_interval_hours?: number;\n windows?: { id?: string; start: string; end: string }[];\n };\n}\n\nexport interface BrowseState {\n wander: {\n focusHistory: Record<string, number>;\n focusCount: Record<string, number>;\n last_wander_at: number;\n /** Spec ⑥: refill wanders per LOCAL day, e.g. \"2026-09-18\" -> 1. */\n refillCount?: Record<string, number>;\n /** H-69: non-refill wander sessions per LOCAL day (the `daily_sessions`\n * budget). Refills keep their own counter above — they deliberately bypass\n * the wander window and therefore must not eat the session budget. */\n sessionCount?: Record<string, number>;\n };\n}\n\nexport function emptyBrowseState(): BrowseState {\n return { wander: { focusHistory: {}, focusCount: {}, last_wander_at: 0, refillCount: {}, sessionCount: {} } };\n}\n\nexport function browseStatePath(paths: WorkspacePaths): string {\n return path.join(paths.dataDir, 'browse.json');\n}\n\nfunction readJsonFile<T>(file: string, fallback: T): T {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as T;\n } catch {\n return fallback;\n }\n}\n\n/** Factory configs are read-only; a user layer with the same filename replaces them. */\nexport function loadInterests(paths: WorkspacePaths): InterestsConfig {\n const userPath = path.join(paths.settingsDir, 'interests.json');\n if (fs.existsSync(userPath)) return readJsonFile<InterestsConfig>(userPath, { interests: [], _schedule: {} });\n return readJsonFile<InterestsConfig>(path.join(paths.configDir, 'interests.json'), { interests: [], _schedule: {} });\n}\n\n/**\n * H-65: the state file outlives upgrades and is hand-inspectable, so a row\n * missing a field must not throw its way into a `beat_error` on every beat.\n * Garbage values are dropped back to the empty-state defaults.\n */\nexport function normalizeBrowseState(raw: unknown): BrowseState {\n const out = emptyBrowseState();\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Partial<BrowseState>;\n const w = (r.wander && typeof r.wander === 'object' ? r.wander : {}) as Partial<BrowseState['wander']>;\n out.wander.focusHistory = numberRecord(w.focusHistory);\n out.wander.focusCount = numberRecord(w.focusCount);\n out.wander.refillCount = numberRecord(w.refillCount);\n out.wander.sessionCount = numberRecord(w.sessionCount);\n if (typeof w.last_wander_at === 'number' && Number.isFinite(w.last_wander_at)) out.wander.last_wander_at = w.last_wander_at;\n return out;\n}\n\nfunction numberRecord(v: unknown): Record<string, number> {\n const out: Record<string, number> = {};\n if (!v || typeof v !== 'object' || Array.isArray(v)) return out;\n for (const [k, n] of Object.entries(v as Record<string, unknown>)) {\n if (typeof n === 'number' && Number.isFinite(n)) out[k] = n;\n }\n return out;\n}\n\nfunction loadState(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return normalizeBrowseState(loadJson<unknown>(guard, browseStatePath(paths)));\n}\n\n// ── B. wander adjudication (pure-ish, state injected) ───────────────────\n\nexport interface WanderAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n /** H-69: focuses this session was allowed to examine (`focus_per_session`);\n * `focus` is the first of them. The phase still runs one model turn per\n * focus, so >1 only widens the candidate list the caller may use. */\n candidates?: string[];\n /** H-69: per-focus seed cap (`max_seeds_per_focus`, defaulting to\n * `policy.browse.maxSeedsPerVisit`). The registration loop reads this. */\n maxSeeds?: number;\n}\n\nexport interface WanderSchedule {\n windows: { start: string; end: string }[];\n minIntervalHours: number;\n maxSeedsPerFocus: number;\n /** Wander sessions per local day; 0 = no daily cap. */\n dailySessions: number;\n focusPerSession: number;\n focusCooldownDays: number;\n}\n\n/**\n * H-69 (2026-10-07): `interests._schedule` is the block the settings card edits\n * and, as the user layer, it REPLACES the factory copy — so it wins wherever it\n * overlaps `policy.browse`, which is the compiled-in default. Every key here\n * has a reader now; `min_interval_hours`, `max_seeds_per_focus` and\n * `daily_sessions` used to be dead wiring whose factory values happened to\n * match policy's, which is exactly why nobody noticed they did nothing.\n */\nexport function resolveSchedule(interests: InterestsConfig, policy: Policy): WanderSchedule {\n const sc = interests._schedule ?? {};\n return {\n windows: sc.windows?.length ? sc.windows : (policy.browse.windows as { start: string; end: string }[]),\n minIntervalHours: sc.min_interval_hours ?? policy.browse.minIntervalHours,\n maxSeedsPerFocus: sc.max_seeds_per_focus ?? policy.browse.maxSeedsPerVisit,\n dailySessions: sc.daily_sessions ?? 0,\n focusPerSession: Math.max(1, sc.focus_per_session ?? 1),\n focusCooldownDays: sc.focus_cooldown_days ?? 3,\n };\n}\n\nexport function inWanderWindow(now: Date, windows: { start: string; end: string }[]): string | null {\n const mins = minutesOfDay(now);\n for (const w of windows) {\n if (inHhMmWindow(w.start, w.end, mins)) return `${w.start}-${w.end}`;\n }\n return null;\n}\n\nfunction onCooldown(state: BrowseState, focus: string, cooldownDays: number, now: number): boolean {\n const last = state.wander.focusHistory[focus] ?? 0;\n return last > now - cooldownDays * 86_400_000;\n}\n\n/**\n * Focus pick (2026-10-06): round-robin recency as the base, preference rate as\n * a multiplier. Ordering key = effective age = realAgeSinceLastUse × weight —\n * a favorite's age \"grows\" faster, so it reaches the pick threshold sooner and\n * is wandered up to W_MAX times as often. Lockdown-proof by construction:\n * - cooldown (above) keeps every topic rotating no matter the weight;\n * - weight lives in [W_MIN, W_MAX] (preference.ts);\n * - hard starvation floor: any topic untouched ≥ STARVATION_DAYS ignores\n * weighting entirely and the oldest real age wins.\n * Without a preference state the behavior is exactly the old pure LRU.\n */\nexport const STARVATION_DAYS = 14;\n\nexport function pickFocus(\n state: BrowseState,\n interests: InterestsConfig,\n now: number,\n pref?: PrefState,\n): string | null {\n const sc = interests._schedule ?? {};\n const cooldown = sc.focus_cooldown_days ?? 3;\n const pool = (interests.interests ?? []).filter((t) => !onCooldown(state, t, cooldown, now));\n if (pool.length === 0) return null;\n if (!pref) {\n pool.sort((a, b) => (state.wander.focusHistory[a] ?? 0) - (state.wander.focusHistory[b] ?? 0));\n return pool[0]!;\n }\n const age = (t: string): number => now - (state.wander.focusHistory[t] ?? 0);\n const starved = pool.filter((t) => age(t) >= STARVATION_DAYS * 86_400_000);\n if (starved.length > 0) {\n starved.sort((a, b) => age(b) - age(a)); // oldest real age wins\n return starved[0]!;\n }\n const effAge = (t: string): number => age(t) * preferenceWeight(pref, t, now);\n pool.sort((a, b) => effAge(b) - effAge(a));\n return pool[0]!;\n}\n\n/** Adjudicate: windows + min interval + focus cooldown -> advice | skipped. */\nexport function adviseWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): WanderAdvice {\n const state = loadState(guard, paths);\n const interests = loadInterests(paths);\n const sched = resolveSchedule(interests, policy);\n const budget = { maxSeeds: sched.maxSeedsPerFocus };\n const win = inWanderWindow(now, sched.windows);\n if (!win) {\n const hh = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;\n return { focus: null, query: null, skipped: `window(now=${hh})`, ...budget };\n }\n // H-69: `daily_sessions` — same LOCAL-day budget shape as the refill quota.\n const today = localDayKey(now);\n const sessionsToday = state.wander.sessionCount?.[today] ?? 0;\n if (sched.dailySessions > 0 && sessionsToday >= sched.dailySessions) {\n return { focus: null, query: null, skipped: `daily-sessions(${sessionsToday})`, ...budget };\n }\n const minGap = sched.minIntervalHours * 3600_000;\n if (now.getTime() - state.wander.last_wander_at < minGap) {\n return { focus: null, query: null, skipped: 'min-interval', ...budget };\n }\n // H-69: `focus_per_session` candidates, drawn without replacement so one\n // session never offers the same focus twice.\n const pref = loadPreference(guard, preferenceFilePath(paths.dataDir));\n const pool = interests.interests ?? [];\n const candidates: string[] = [];\n for (let i = 0; i < sched.focusPerSession; i++) {\n const rest = pool.filter((t) => !candidates.includes(t));\n if (rest.length === 0) break;\n const picked = pickFocus(state, { ...interests, interests: rest }, now.getTime(), pref);\n if (!picked) break;\n candidates.push(picked);\n }\n if (candidates.length === 0) return { focus: null, query: null, skipped: 'no-focus', ...budget };\n // 低优先级 review (2026-10-17): the year in the query was hardcoded to 2026,\n // which silently ages the search results as the calendar moves on.\n const year = now.getFullYear();\n return { focus: candidates[0]!, query: `${candidates[0]!} ${year} 最新`, skipped: null, candidates, ...budget };\n}\n\n/**\n * Registration is CODE-OWNED (D10): called by the orchestrator after the\n * wander phase's model call returned selections. Records cooldown/count/\n * throttle timestamps for the focus. `refill` additionally bumps the daily\n * refill counter (spec ⑥).\n */\nexport function completeWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n focus: string,\n now = Date.now(),\n opts: { refill?: boolean } = {},\n): { focus: string; count: number; refillsToday?: number } {\n const state = loadState(guard, paths);\n state.wander.focusHistory[focus] = now;\n state.wander.focusCount[focus] = (state.wander.focusCount[focus] ?? 0) + 1;\n state.wander.last_wander_at = now;\n if (!opts.refill) {\n // H-69: count this session against the `daily_sessions` budget. Refills\n // are their own channel (they deliberately bypass the window and the min\n // interval) and stay on refillCount alone.\n const day = localDayKey(new Date(now));\n state.wander.sessionCount = state.wander.sessionCount ?? {};\n state.wander.sessionCount[day] = (state.wander.sessionCount[day] ?? 0) + 1;\n }\n let refillsToday: number | undefined;\n if (opts.refill) {\n const today = localDayKey(new Date(now));\n state.wander.refillCount = state.wander.refillCount ?? {};\n state.wander.refillCount[today] = (state.wander.refillCount[today] ?? 0) + 1;\n refillsToday = state.wander.refillCount[today];\n }\n saveJson(guard, browseStatePath(paths), state);\n return { focus, count: state.wander.focusCount[focus]!, ...(refillsToday === undefined ? {} : { refillsToday }) };\n}\n\n// ── C. refill wander (spec ⑥, 2026-09-18): top up topic stock when it runs\n// dry. Independent of the window/minInterval gates (user decision: may stack\n// with a normal wander in the same beat) but still respects the 3-day focus\n// cooldown, and is capped at REFILL_MAX_PER_DAY per local day.\n\nexport const REFILL_TOPIC_THRESHOLD = 4;\nexport const REFILL_MAX_PER_DAY = 2;\n\nexport interface RefillAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n topicCount: number;\n refillsToday: number;\n}\n\nexport function adviseRefillWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): RefillAdvice {\n const state = loadState(guard, paths);\n const today = localDayKey(now);\n const refillsToday = state.wander.refillCount?.[today] ?? 0;\n const topicCount = activeSeeds(loadPool(guard, seedsFilePath(paths.dataDir)))\n .filter((s) => normalizeCategory(s.category) === 'topic').length;\n if (refillsToday >= REFILL_MAX_PER_DAY) {\n return { focus: null, query: null, skipped: `refill-daily-cap(${refillsToday})`, topicCount, refillsToday };\n }\n if (topicCount > REFILL_TOPIC_THRESHOLD) {\n return { focus: null, query: null, skipped: `topic-stock-ok(${topicCount})`, topicCount, refillsToday };\n }\n const interests = loadInterests(paths);\n const focus = pickFocus(state, interests, now.getTime(), loadPreference(guard, preferenceFilePath(paths.dataDir))); // 3-day cooldown still applies\n if (!focus) {\n return { focus: null, query: null, skipped: 'no-focus', topicCount, refillsToday };\n }\n return { focus, query: `${focus} 2026 最新`, skipped: null, topicCount, refillsToday };\n}\n\nexport function browseStatus(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return loadState(guard, paths);\n}\n","// Windows toast channel (D12): attention hint ONLY - never carries the\n// expression body. Wraps assets/notify.ps1 (self-registering AUMID).\n\nimport path from 'node:path';\nimport { runPowerShellFile } from '../core/ps.js';\nimport type { WorkspacePaths } from '../core/paths.js';\n\nasync function runNotify(paths: WorkspacePaths, args: string[]): Promise<{ status: number; out: string }> {\n const r = await runPowerShellFile(path.join(paths.assetsDir, 'notify.ps1'), args, 20_000);\n return { status: r.status, out: `${r.stdout}${r.stderr}`.trim() };\n}\n\n/** Register the toast identity if missing (idempotent, per machine/user). */\nexport async function ensureRegistered(paths: WorkspacePaths): Promise<boolean> {\n const check = await runNotify(paths, ['-Check']);\n if (/REGISTERED: yes/.test(check.out)) return true;\n const reg = await runNotify(paths, ['-RegisterOnly']);\n return reg.status === 0;\n}\n\n/**\n * Fire the \"new message\" hint. Fixed neutral text per D12 - the actual\n * expression lives in the dedicated heartbeat session, never in the toast.\n */\nexport async function sendNewMessageHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', 'Heartbeat', '-Message', '有新消息']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n\n/** Weekly report ready hint (v1.8.0): same D12 discipline — announces that a\n * report exists, never carries its content. */\nexport async function sendWeeklyReadyHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', '心跳周报', '-Message', '本期周报已生成']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n","/**\n * H-10: asynchronous PowerShell runner.\n *\n * The probes (idle seconds, front window, screen capture, toasts) used\n * `spawnSync`, which blocks the host's event loop for as long as the script\n * runs — 10s to 45s on a slow machine, and the GUI stalls with it. Same\n * arguments, same timeouts, same \"never throw, degrade instead\" contract, but\n * the loop stays free while the child runs.\n */\nimport { execFile } from 'node:child_process';\n\nexport interface PsResult {\n status: number;\n stdout: string;\n stderr: string;\n}\n\n/** Run `powershell.exe` and resolve with its exit code and streams. Never\n * rejects: a spawn failure and a non-zero exit both come back as `status !== 0`\n * so callers keep their existing \"probe failed\" paths.\n *\n * ⑤A (2026-10-17 review, HB-08): the optional signal is the beat's cancellation\n * handle. A cancelled probe kills the child and resolves like any other failed\n * probe (`status !== 0`, stderr 'aborted') — callers already degrade on that,\n * and the \"never rejects\" contract stays intact. */\nexport function runPowerShell(args: string[], timeoutMs: number, signal?: AbortSignal): Promise<PsResult> {\n if (signal?.aborted) return Promise.resolve({ status: 1, stdout: '', stderr: 'aborted' });\n // v2.1.0: every caller of this module is a Windows-only probe (idle seconds,\n // foreground window, toasts, screen capture). Off Windows there is no binary\n // to spawn, so answer \"probe failed\" immediately — same degradation the\n // callers already implement, without paying a spawn attempt per beat.\n if (process.platform !== 'win32') {\n return Promise.resolve({ status: 1, stdout: '', stderr: `powershell unavailable on ${process.platform}` });\n }\n return new Promise((resolve) => {\n let settled = false;\n const done = (r: PsResult): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener('abort', onAbort);\n resolve(r);\n };\n const onAbort = (): void => {\n try { child.kill(); } catch { /* already gone */ }\n done({ status: 1, stdout: '', stderr: 'aborted' });\n };\n const child = execFile(\n 'powershell.exe',\n ['-NoProfile', '-ExecutionPolicy', 'Bypass', ...args],\n { timeout: timeoutMs, encoding: 'utf8', windowsHide: true },\n (err, stdout, stderr) => {\n const code = (err as { code?: unknown } | null)?.code;\n const status = err ? (typeof code === 'number' ? code : 1) : 0;\n done({ status, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });\n },\n );\n child.on('error', () => { /* surfaced through the callback above */ });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** Convenience for the `-File <script>` shape used by every asset script. */\nexport function runPowerShellFile(script: string, args: string[], timeoutMs: number, signal?: AbortSignal): Promise<PsResult> {\n return runPowerShell(['-File', script, ...args], timeoutMs, signal);\n}\n","// Weekly report store + writer helpers (v1.8.0). Deliberately host-free:\n// orchestration (when to run, which agent, toast) lives in the orchestrator —\n// same split as profile/consolidate.ts. Reports are DPAPI-encrypted because a\n// report contains user-identifying content (profile adds, ledger texts) —\n// same划线标准 as profile/seeds (design doc §10.5).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { workspace } from '../core/paths.js';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { WeeklyFacts } from './collect.js';\n\nexport const WEEKLY_INTERVAL_MS = 7 * 86_400_000;\n\nexport interface WeeklyReport {\n start: string;\n end: string;\n generatedAt: string;\n /** 'llm' = engine-room prose; 'template' = deterministic fallback. */\n source: 'llm' | 'template';\n text: string;\n}\n\nexport function weeklyDirPath(dataDir: string): string {\n return path.join(dataDir, 'weekly');\n}\n\nfunction stateFilePath(dataDir: string): string {\n return path.join(weeklyDirPath(dataDir), 'state.json');\n}\n\nfunction reportFileName(endIso: string): string {\n return `report-${endIso.slice(0, 10)}.json`;\n}\n\n/**\n * Last generation time from the weekly state file; 0 = never anchored.\n *\n * H-54: \"missing\" and \"present but unparseable\" are NOT the same thing. The\n * old code folded both into 0, so `ensureWeeklyAnchor` \"repaired\" a corrupt\n * file by stamping NOW — silently, and at the cost of pushing the next report\n * a full interval out. A corrupt anchor now keeps its file, writes an audit\n * line, and falls back to the file's mtime so the schedule keeps its place.\n */\nexport function lastWeeklyGeneratedAt(guard: PathGuard, dataDir: string): number {\n const file = stateFilePath(dataDir);\n let raw: string;\n try {\n raw = fs.readFileSync(guard.assert(file), 'utf8');\n } catch {\n return 0; // absent: a fresh install, legitimately never anchored\n }\n try {\n const parsed = JSON.parse(raw) as { lastGeneratedAt?: number };\n const n = Number(parsed.lastGeneratedAt);\n if (Number.isFinite(n) && n > 0) return n;\n } catch {\n /* unparseable — handled by the fallback below */\n }\n try {\n appendAuditLine(path.join(workspace().logsDir, 'heartbeat.jsonl'), {\n event: 'weekly_anchor_corrupt',\n file: path.basename(file),\n bytes: Buffer.byteLength(raw),\n });\n } catch {\n /* audit is diagnostic; never let it break the schedule */\n }\n try {\n return fs.statSync(file).mtimeMs;\n } catch {\n return 0;\n }\n}\n\n/** Due when the last report is ≥7 days old. A never-anchored store lands on\n * the install-time anchor (see ensureWeeklyAnchor), so a fresh install is NOT\n * due — the first report arrives one full interval after installation. */\nexport function weeklyDue(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n const last = lastWeeklyGeneratedAt(guard, dataDir);\n return now - last >= WEEKLY_INTERVAL_MS;\n}\n\n/** Stamp the install-time anchor for a store that has never generated a report\n * (v1.9.0). Returns true when it wrote — the caller audits that. Without this,\n * `lastGeneratedAt = 0` made the very first maintenance beat due, so a fresh\n * install produced an \"onboarding\" report immediately, contradicting the\n * release notes (\"first report after a week\"). */\nexport function ensureWeeklyAnchor(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\n if (lastWeeklyGeneratedAt(guard, dataDir) > 0) return false;\n fs.mkdirSync(weeklyDirPath(dataDir), { recursive: true });\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: now });\n return true;\n}\n\n/** Persist a report (DPAPI) and stamp the state file. */\nexport function saveWeeklyReport(guard: PathGuard, dataDir: string, report: WeeklyReport): string {\n const dir = weeklyDirPath(dataDir);\n fs.mkdirSync(dir, { recursive: true });\n const file = path.join(dir, reportFileName(report.end));\n saveEncryptedText(guard, file, JSON.stringify(report, null, 1));\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: Date.parse(report.generatedAt) });\n return file;\n}\n\nexport interface WeeklyReportMeta {\n file: string;\n start: string;\n end: string;\n generatedAt: string;\n source: string;\n}\n\n/** Newest-first listing for the card; unparsable entries are skipped.\n * v2.0 (item 5): an optional `limit` shows only the newest N reports. */\nexport function listWeeklyReports(guard: PathGuard, dataDir: string, limit?: number): WeeklyReportMeta[] {\n const out: WeeklyReportMeta[] = [];\n try {\n for (const file of fs.readdirSync(weeklyDirPath(dataDir))) {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) continue;\n const rep = readWeeklyReport(guard, dataDir, file);\n if (!rep) continue;\n out.push({ file, start: rep.start, end: rep.end, generatedAt: rep.generatedAt, source: rep.source });\n }\n } catch { /* no weekly dir yet */ }\n const sorted = out.sort((a, b) => (a.end < b.end ? 1 : -1));\n return limit !== undefined && limit > 0 ? sorted.slice(0, limit) : sorted;\n}\n\n/**\n * v2.0 (item 5): delete every report beyond the newest `keep`, so the card's\n * report buttons cannot crowd the panel and the store cannot grow unbounded.\n * `keep <= 0` disables pruning (and the policy schema forbids it anyway).\n * Returns the deleted file names so the caller can audit them; a report that\n * cannot be deleted is left in place (best effort — never break the beat).\n */\nexport function pruneWeeklyReports(guard: PathGuard, dataDir: string, keep: number): string[] {\n if (!Number.isFinite(keep) || keep <= 0) return [];\n const removed: string[] = [];\n for (const meta of listWeeklyReports(guard, dataDir).slice(keep)) {\n try {\n fs.rmSync(guard.assert(path.join(weeklyDirPath(dataDir), meta.file)));\n removed.push(meta.file);\n } catch { /* best effort */ }\n }\n return removed;\n}\n\nexport function readWeeklyReport(guard: PathGuard, dataDir: string, file: string): WeeklyReport | null {\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) return null; // guard.assert would reject ../ anyway\n try {\n const raw = loadEncryptedText(guard, path.join(weeklyDirPath(dataDir), file));\n if (!raw) return null;\n const rep = JSON.parse(raw) as WeeklyReport;\n if (typeof rep.text !== 'string') return null;\n return rep;\n } catch {\n return null;\n }\n}\n\n/** The engine-room prompt: neutral system narrator, fact-bound, ≤250 chars. */\nexport function buildWeeklyPrompt(facts: WeeklyFacts): string {\n return [\n '你是心跳插件的后台报告器。根据下面的本周事实清单,用中文写一份周报正文。',\n '规则:',\n '- 叙述者自称「心跳」——这是插件后台,不是任何会话里的 agent;绝不能以会话 agent 的身份或人格自称。',\n '- 只报告事实清单里有的内容;某一节没有数据就整节跳过,不要编造、不要凑数。',\n '- 语气平实中性,不用感叹号;篇幅不超过 250 字。',\n '- 待办积压那一节用商量的语气提一句,不催促。',\n '- 直接输出周报正文,不要输出解释、标题或 JSON。',\n '',\n '本周事实(JSON):',\n JSON.stringify(facts, null, 1),\n ].join('\\n');\n}\n\n/** Deterministic fallback: the facts, plainly stated. Used when the LLM turn\n * fails or comes back empty — a plain report beats no report. */\nexport function renderTemplateReport(facts: WeeklyFacts): string {\n const d = (iso: string): string => iso.slice(0, 10);\n const lines: string[] = [`本周(${d(facts.windowStart)} ~ ${d(facts.windowEnd)})`];\n lines.push(`表达 ${facts.spoken} 次,静默 ${facts.silent} 次。`);\n if (facts.silentTopReasons.length > 0) {\n lines.push(`静默主因:${facts.silentTopReasons.map((r) => `${r.reason}(${r.count})`).join('、')}。`);\n }\n if (facts.profileAdds.length > 0) {\n lines.push(`新认识 ${facts.profileAdds.length} 条:${facts.profileAdds.map((a) => a.content).join(';')}。`);\n }\n if (facts.ledger.added.length > 0 || facts.ledger.done.length > 0) {\n const parts: string[] = [];\n if (facts.ledger.added.length > 0) parts.push(`新增待办:${facts.ledger.added.join('、')}`);\n if (facts.ledger.done.length > 0) parts.push(`已解决:${facts.ledger.done.join('、')}`);\n lines.push(`${parts.join(';')}。`);\n }\n if (facts.ledger.stale.length > 0) {\n lines.push(`挂了很久:${facts.ledger.stale.map((s) => `${s.text}(${s.days} 天)`).join('、')}——要删掉还是继续挂着?`);\n }\n if (facts.seeds.added.length > 0) {\n lines.push(`素材池新增 ${facts.seeds.added.length} 条,已消费 ${facts.seeds.consumed.length} 条。`);\n }\n if (facts.seeds.waiting.length > 0) {\n lines.push(`还没聊过的素材:${facts.seeds.waiting.join('、')}。`);\n }\n if (facts.reports.total > 0) {\n const reasonPart = facts.reports.reasons.length > 0\n ? `(${facts.reports.reasons.map((r) => `${r.reason} ${r.count} 次`).join('、')})`\n : '';\n lines.push(`投递报账 ${facts.reports.total} 次:用素材 ${facts.reports.material}、说真心话 ${facts.reports.heartfelt}、没说话 ${facts.reports.silent}${reasonPart}。`);\n }\n // v1.9.0: unaccounted deliveries are reported even when no report landed at\n // all — a silent rise in \"no report\" is exactly what would otherwise hide.\n if (facts.reports.missing > 0) {\n lines.push(`另有 ${facts.reports.missing} 次投递没等到报账(这部分没算进偏好统计)。`);\n }\n if (facts.peakHours.length > 0) {\n lines.push(`活跃高峰:${facts.peakHours.join('、')}。`);\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;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K,QAAG,CAAC,QAAG;AAAA,EACxD;AACA,MAAI,MAAM,QAAQ,QAAQ,GAAG;AAC3B,UAAM,aAAa,MAAM,QAAQ,QAAQ,SAAS,IAC9C,SAAI,MAAM,QAAQ,QAAQ,IAAI,CAAC,MAAM,GAAG,EAAE,MAAM,IAAI,EAAE,KAAK,SAAI,EAAE,KAAK,QAAG,CAAC,WAC1E;AACJ,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,11 +0,0 @@
1
- import {
2
- getRuntime,
3
- resetRuntimeForTest,
4
- setRuntime
5
- } from "./chunk-3QJJRXIR.js";
6
- export {
7
- getRuntime,
8
- resetRuntimeForTest,
9
- setRuntime
10
- };
11
- //# sourceMappingURL=runtime-W2OWJIHY.js.map