@kanadego/dsh-heartbeat 1.9.2 → 2.0.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 (57) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +344 -396
  3. package/client.js +108 -20
  4. package/config/policy.json +74 -73
  5. package/config/profile-schema.json +306 -306
  6. package/dist/{bindings-225SI7KC.js → bindings-U2M3CO2D.js} +3 -3
  7. package/dist/{chunk-TY6UP74X.js → chunk-3DNGY4DS.js} +2 -2
  8. package/dist/{chunk-CUOSICYJ.js → chunk-544QOJN5.js} +397 -23
  9. package/dist/chunk-544QOJN5.js.map +1 -0
  10. package/dist/{chunk-AJ5HLAL7.js → chunk-6MVKWICX.js} +708 -154
  11. package/dist/chunk-6MVKWICX.js.map +1 -0
  12. package/dist/{chunk-IG6YMUHW.js → chunk-6XM6KY7M.js} +43 -12
  13. package/dist/chunk-6XM6KY7M.js.map +1 -0
  14. package/dist/chunk-AKIJ4LS2.js +680 -0
  15. package/dist/chunk-AKIJ4LS2.js.map +1 -0
  16. package/dist/{chunk-KB5SMG3F.js → chunk-DC5HMCJC.js} +3 -3
  17. package/dist/{chunk-3MDBU6WY.js → chunk-DZ7YCFGX.js} +37 -7
  18. package/dist/chunk-DZ7YCFGX.js.map +1 -0
  19. package/dist/{chunk-WRUTATW4.js → chunk-IBBAISSW.js} +13 -2
  20. package/dist/chunk-IBBAISSW.js.map +1 -0
  21. package/dist/{chunk-ZLV4NMFX.js → chunk-IFRMKVIC.js} +85 -21
  22. package/dist/chunk-IFRMKVIC.js.map +1 -0
  23. package/dist/{chunk-XFNCTOW7.js → chunk-NCPKOWS7.js} +52 -4
  24. package/dist/chunk-NCPKOWS7.js.map +1 -0
  25. package/dist/{chunk-JDH2LDFS.js → chunk-TVX4HV4Y.js} +4 -6
  26. package/dist/{chunk-JDH2LDFS.js.map → chunk-TVX4HV4Y.js.map} +1 -1
  27. package/dist/cli/index.js +149 -26
  28. package/dist/cli/index.js.map +1 -1
  29. package/dist/{inbox-P26DDMWC.js → inbox-OWBK6PE2.js} +8 -7
  30. package/dist/index.d.ts +50 -315
  31. package/dist/index.js +288 -920
  32. package/dist/index.js.map +1 -1
  33. package/dist/migrate-TQ5PB2DI.js +27 -0
  34. package/dist/{orchestrator-EUTZ3KG6.js → orchestrator-P7AEWVYR.js} +27 -12
  35. package/dist/{pool-UTXQJJ5C.js → pool-2T6TVS2L.js} +4 -5
  36. package/dist/{snapshot-K5VHETTK.js → snapshot-F5B2DD56.js} +5 -5
  37. package/package.json +84 -83
  38. package/dist/chunk-3MDBU6WY.js.map +0 -1
  39. package/dist/chunk-AJ5HLAL7.js.map +0 -1
  40. package/dist/chunk-CUOSICYJ.js.map +0 -1
  41. package/dist/chunk-IG6YMUHW.js.map +0 -1
  42. package/dist/chunk-IV2ZWQA3.js +0 -56
  43. package/dist/chunk-IV2ZWQA3.js.map +0 -1
  44. package/dist/chunk-K5Y6JP2B.js +0 -399
  45. package/dist/chunk-K5Y6JP2B.js.map +0 -1
  46. package/dist/chunk-WRUTATW4.js.map +0 -1
  47. package/dist/chunk-XFNCTOW7.js.map +0 -1
  48. package/dist/chunk-ZLV4NMFX.js.map +0 -1
  49. package/dist/migrate-D4VKAKYT.js +0 -21
  50. /package/dist/{bindings-225SI7KC.js.map → bindings-U2M3CO2D.js.map} +0 -0
  51. /package/dist/{chunk-TY6UP74X.js.map → chunk-3DNGY4DS.js.map} +0 -0
  52. /package/dist/{chunk-KB5SMG3F.js.map → chunk-DC5HMCJC.js.map} +0 -0
  53. /package/dist/{inbox-P26DDMWC.js.map → inbox-OWBK6PE2.js.map} +0 -0
  54. /package/dist/{migrate-D4VKAKYT.js.map → migrate-TQ5PB2DI.js.map} +0 -0
  55. /package/dist/{orchestrator-EUTZ3KG6.js.map → orchestrator-P7AEWVYR.js.map} +0 -0
  56. /package/dist/{pool-UTXQJJ5C.js.map → pool-2T6TVS2L.js.map} +0 -0
  57. /package/dist/{snapshot-K5VHETTK.js.map → snapshot-F5B2DD56.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"],"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 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';\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(doc: ProfileDoc, text: string, baselineTs: string, stats: { records: number; truncatedTail: number; isLive: boolean }): 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 try {\n const rec = JSON.parse(trimmed) as JournalRecord;\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 for (const op of rec.applied ?? []) applyOpPermissive(doc, op, rec.ts);\n stats.records += 1;\n } catch {\n // Torn tail only counts on the LIVE journal — archives are closed files.\n const isLast = lines.slice(i + 1).every((l) => !l.trim());\n if (stats.isLive && isLast) {\n stats.truncatedTail = lines.length - i;\n break;\n }\n // mid-file corrupt record: skip (journal stays append-only/immutable)\n }\n }\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, 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, 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 };\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 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 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 if (op.changes.content !== undefined) entry.content = op.changes.content.trim();\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 entry.confidence = Math.min(op.changes.confidence, cap);\n }\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\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 applied.push(op);\n continue;\n }\n }\n return { applied, rejected };\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 } {\n const nowIso = new Date(now).toISOString();\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 }\n } else if (!e.lowActivity && now - lastEvidence > policy.profile.stableLowActivityDays * DAY_MS) {\n e.lowActivity = true;\n lowActivityMarked += 1;\n }\n }\n }\n return { volatileExpired, lowActivityMarked };\n}\n\n/** Persist the materialized view atomically + append the journal record. */\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 line = JSON.stringify({ ts: new Date().toISOString(), ...record });\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}\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","// 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\nexport interface JournalRecord {\n ts: string;\n runId: string;\n applied: ProfileOp[];\n rejected: { op: ProfileOp; reason: string }[];\n}\n\nexport interface ApplyReport {\n applied: ProfileOp[];\n rejected: { op: ProfileOp; reason: string }[];\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"],"mappings":";;;;;;;;;;;AAIA,OAAO,QAAQ;AACf,OAAO,UAAU;AAcV,SAAS,gBAAgB,MAAc,OAAuD;AACnG,MAAI;AACF,OAAG,UAAU,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACpD,UAAM,OAAO,KAAK,UAAU,EAAE,IAAI,MAAM,OAAM,oBAAI,KAAK,GAAE,YAAY,GAAG,GAAG,MAAM,CAAC;AAClF,OAAG,eAAe,MAAM,OAAO,MAAM,MAAM;AAAA,EAC7C,SAAS,GAAG;AACV,YAAQ,OAAO,MAAM,oCAAoC,IAAI,KAAK,OAAO,CAAC,CAAC;AAAA,CAAI;AAAA,EACjF;AACF;AAEO,SAAS,eAA+B,MAAmB;AAChE,MAAI,CAAC,GAAG,WAAW,IAAI,EAAG,QAAO,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cAAc,OAAO,OAAO;AAC7C,QAAM,SAAS,gBAAgB,OAAO;AACtC,MAAI,KAAK,OAAO;AACd,UAAM,SAAS,YAAY,OAAO,MAAM;AACxC,UAAM,OAAO,KAAK,UAAU,MAAM,MAAM,KAAK,UAAU,SAAS,GAAG;AACnE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,eAAe,SAAS;AAAA,MACxB,SAAS,SAAS;AAAA,MAClB,OAAO;AAAA,MACP,aAAa,OAAO,YAAY;AAAA,IAClC;AAAA,EACF;AACA,WAAS,OAAO,QAAQ,SAAS,GAAG;AACpC,MAAI,SAAS,gBAAgB,GAAG;AAE9B;AAAA,MACE;AAAA,MACAD,MAAK,KAAK,SAAS,QAAQ,oBAAoB;AAAA,MAC/C,qBAAqB,SAAS,aAAa,kCAAkC,SAAS,OAAO;AAAA;AAAA,IAC/F;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,eAAe,SAAS,eAAe,SAAS,SAAS,SAAS,OAAO,KAAK;AACnG;","names":["path","fs","fs","path","path","fs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ledger/ledger.ts","../src/browse/preference.ts","../src/browse/browse.ts","../src/core/time-window.ts","../src/notify/notify.ts","../src/core/ps.ts","../src/weekly/report.ts"],"sourcesContent":["// Ledger (\"账本\") - the ONE shared ledger (design doc §5, requirement 5).\n// Human-readable Markdown by charter; the user may edit it by hand, so the\n// parser is tolerant: unknown lines are preserved verbatim on rewrite.\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { readText, writeText } from '../vault/vault.js';\n\nconst DAY_MS = 86_400_000;\n\nexport interface LedgerEntry {\n id: string;\n date: string; // \"YYYY-MM-DD\"\n time: string; // \"HH:MM\"\n status: 'open' | 'done';\n text: string;\n}\n\nexport function ledgerFilePath(dataDir: string): string {\n return path.join(dataDir, 'ledger.md');\n}\n\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[(open|done)\\]\\[#([0-9a-f]{6})\\] (.*)$/;\n\nfunction renderEntry(e: LedgerEntry): string {\n return `- [${e.date} ${e.time}][${e.status}][#${e.id}] ${e.text}`;\n}\n\nexport function readLedger(guard: PathGuard, file: string): { header: string; entries: LedgerEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, '# 账本\\n');\n const lines = raw.split('\\n');\n const entries: LedgerEntry[] = [];\n const rawLines: string[] = [];\n for (const line of lines) {\n const m = LINE_RE.exec(line);\n if (m) {\n entries.push({ date: m[1]!, time: m[2]!, status: m[3] as 'open' | 'done', id: m[4]!, text: m[5]! });\n }\n rawLines.push(line);\n }\n return { header: lines[0] ?? '# 账本', entries, rawLines };\n}\n\nexport function appendEntry(guard: PathGuard, file: string, text: string, now = Date.now()): LedgerEntry {\n const textTrimmed = text.trim();\n if (!textTrimmed) throw new Error('ledger entry must not be empty');\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const entry: LedgerEntry = {\n id: randomUUID().slice(0, 6),\n date: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,\n time: `${pad(d.getHours())}:${pad(d.getMinutes())}`,\n status: 'open',\n text: textTrimmed.replace(/\\r?\\n/g, ' '),\n };\n const { rawLines } = readLedger(guard, file);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n}\n\n/** Mark an entry done by id (preferred) or unique text substring. The date is\n * restamped to the completion day (time was already) so weekly reporting can\n * count \"resolved this week\" — the creation timestamp lives on in nothing,\n * but done entries are rarely aged against. */\nexport function markDone(guard: PathGuard, file: string, key: string, now = Date.now()): LedgerEntry | null {\n const { rawLines, entries } = readLedger(guard, file);\n const target = entries.find((e) => e.status === 'open' && (e.id === key || e.text.includes(key)));\n if (!target) return null;\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const doneDate = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n const out = rawLines.map((line) => {\n if (line.includes(`#${target.id}] `)) {\n return `- [${doneDate} ${pad(d.getHours())}:${pad(d.getMinutes())}][done][#${target.id}] ${target.text}`;\n }\n return line;\n });\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return target;\n}\n\n/** Open items for the reflection digest (§7.6 账本待办). */\nexport function scanPending(guard: PathGuard, file: string, now = Date.now()): LedgerEntry[] {\n const { entries } = readLedger(guard, file);\n return entries.filter((e) => e.status === 'open').sort((a, b) => (a.date < b.date ? -1 : 1));\n}\n\n/** Open entries older than N days (跟进时机的\"自然到期\"参考,§3.1 四问之一). */\nexport function pendingOlderThan(guard: PathGuard, file: string, days: number, now = Date.now()): LedgerEntry[] {\n const cutoff = new Date(now - days * DAY_MS).toISOString().slice(0, 10);\n return scanPending(guard, file, now).filter((e) => e.date <= cutoff);\n}\n","// Topic preference (2026-10-06): consumption-driven bias for wander focus\n// selection. The persona's seed_report attributions (and the engine-room\n// fallback) fold into per-topic delivered/adopted counters; pickFocus reads\n// the smoothed rate as a weight on top of round-robin recency.\n//\n// Anti-lockdown guarantees (user-reviewed design):\n// - weight clamped to [W_MIN, W_MAX] — a favorite doubles at most, a cold\n// topic never drops below half;\n// - Laplace smoothing — a topic with no data sits near neutral, not zero;\n// - exponential decay (30-day half-life) — old glory fades;\n// - pickFocus additionally enforces a hard starvation floor (14 days).\n//\n// Storage is one JSON file through the vault (DPAPI): topic keys derive from\n// the user's profile/interests, so they are user-adjacent data.\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\n\nconst DAY_MS = 86_400_000;\n\nexport const W_MIN = 0.5;\nexport const W_MAX = 2;\n/** Laplace prior: rate = (adopted + A) / (delivered + D). Neutral ≈ A/D. */\nexport const SMOOTH_ADOPTED = 1;\nexport const SMOOTH_DELIVERED = 4;\n/** Counts decay with this half-life (days) since the topic's last activity. */\nexport const DECAY_HALF_LIFE_DAYS = 30;\n\nexport interface TopicPref {\n delivered: number;\n adopted: number;\n lastDeliveredAt: number;\n lastAdoptedAt: number;\n}\n\nexport interface PrefState {\n version: 1;\n topics: Record<string, TopicPref>;\n updatedAt: number;\n}\n\nexport function preferenceFilePath(dataDir: string): string {\n return path.join(dataDir, 'preference.json');\n}\n\n/** Non-negative finite number or 0 (v1.9.0 guard against hand-edited files). */\nfunction num(v: unknown): number {\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 ? n : 0;\n}\n\n/** One stored entry → a trustworthy counter. Returns null for a garbled entry:\n * a NaN delivered/adopted used to survive the load and poison the whole\n * ordering (NaN makes every comparison false, so the topic neither aged nor\n * sorted). Dropping the entry is the safe read — the loop refills it. */\nfunction sanitizeTopicPref(raw: unknown): TopicPref | null {\n if (!raw || typeof raw !== 'object') return null;\n const t = raw as Partial<TopicPref>;\n if (!Number.isFinite(Number(t.delivered)) || !Number.isFinite(Number(t.adopted))) return null;\n const delivered = Math.floor(num(t.delivered));\n return {\n delivered,\n adopted: Math.min(delivered, Math.floor(num(t.adopted))),\n lastDeliveredAt: num(t.lastDeliveredAt),\n lastAdoptedAt: num(t.lastAdoptedAt),\n };\n}\n\nexport function loadPreference(guard: PathGuard, file: string): PrefState {\n const doc = loadJson<Partial<PrefState>>(guard, file);\n if (!doc || typeof doc !== 'object' || !doc.topics || typeof doc.topics !== 'object') {\n return { version: 1, topics: {}, updatedAt: 0 };\n }\n const topics: Record<string, TopicPref> = {};\n for (const [key, raw] of Object.entries(doc.topics)) {\n const t = sanitizeTopicPref(raw);\n if (key && t) topics[key] = t;\n }\n const updatedAt = Number(doc.updatedAt);\n return { version: 1, topics, updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0 };\n}\n\nexport function savePreference(guard: PathGuard, file: string, state: PrefState): void {\n saveJson(guard, file, state);\n}\n\n/** Fold one delivery into the counters. offeredTopics = every topic in the\n * package; adoptedTopics = the credited ones (subset by construction — unknown\n * keys are still tolerated so the two lists can drift safely). */\nexport function recordDelivery(\n guard: PathGuard,\n file: string,\n opts: { offeredTopics: string[]; adoptedTopics: string[]; now: number },\n): PrefState {\n const state = loadPreference(guard, file);\n const adopted = new Set(opts.adoptedTopics);\n for (const topic of opts.offeredTopics) {\n if (!topic) continue;\n const t = state.topics[topic] ?? { delivered: 0, adopted: 0, lastDeliveredAt: 0, lastAdoptedAt: 0 };\n t.delivered += 1;\n t.lastDeliveredAt = opts.now;\n if (adopted.has(topic)) {\n t.adopted += 1;\n t.lastAdoptedAt = opts.now;\n }\n state.topics[topic] = t;\n }\n state.updatedAt = opts.now;\n savePreference(guard, file, state);\n return state;\n}\n\n/** Time-decayed counts (30-day half-life since last activity of each kind). */\nexport function decayed(t: TopicPref, now: number): { delivered: number; adopted: number } {\n const dAgeDays = Math.max(0, now - t.lastDeliveredAt) / DAY_MS;\n const aAgeDays = Math.max(0, now - t.lastAdoptedAt) / DAY_MS;\n const dHalf = Math.pow(0.5, dAgeDays / DECAY_HALF_LIFE_DAYS);\n const aHalf = Math.pow(0.5, aAgeDays / DECAY_HALF_LIFE_DAYS);\n return { delivered: t.delivered * dHalf, adopted: t.adopted * aHalf };\n}\n\n/**\n * Preference weight for a topic, clamped to [W_MIN, W_MAX]:\n * rate = (decayed adopted + 1) / (decayed delivered + 4) (neutral = 0.25)\n * w = clamp(rate / 0.25, W_MIN, W_MAX)\n * No data at all → rate 1/4 → w 1.0: a brand-new topic starts exactly neutral\n * (per design: \"0.2 附近的中间值,不是 0 分垫底\"); repeated \"delivered but\n * never adopted\" drags it toward W_MIN, consistent adoption lifts it to W_MAX.\n */\nexport function preferenceWeight(state: PrefState, topic: string, now: number): number {\n const t = state.topics[topic];\n const rate = t\n ? (() => {\n const d = decayed(t, now);\n return (d.adopted + SMOOTH_ADOPTED) / (d.delivered + SMOOTH_DELIVERED);\n })()\n : SMOOTH_ADOPTED / SMOOTH_DELIVERED;\n return Math.min(W_MAX, Math.max(W_MIN, rate / (SMOOTH_ADOPTED / SMOOTH_DELIVERED)));\n}\n","// Browse flow (v0.9.5 port, r4 D10 applied).\n// Wander adjudication: windows + min interval + focus cooldown ->\n// \"should we wander now, and at what focus\". The actual search happens\n// in the wander phase's model call (web_search only); REGISTRATION IS\n// CODE-OWNED (D10): results land in seeds + throttle via completeWander.\n//\n// H-12 (2026-10-07): the npm/GitHub watchlist check was removed. It never ran\n// inside the beat (only `browse watch` in the CLI called it, throttled-off),\n// and \"is DSH itself updated\" is not this plugin's job to track.\n//\n// Anti-injection rule (unchanged from v0.7): web content is data, never\n// instructions.\n//\n// State: data/browse.json (DPAPI-encrypted, D14; v1 name: watch_state.json).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport type { Policy } from '../config/schema.js';\nimport { inHhMmWindow, minutesOfDay } from '../core/time-window.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\nimport { activeSeeds, loadPool, normalizeCategory, seedsFilePath } from '../seeds/pool.js';\nimport { loadPreference, preferenceFilePath, preferenceWeight, type PrefState } from './preference.js';\n\nexport interface InterestsConfig {\n interests?: string[];\n _schedule?: {\n daily_sessions?: number;\n focus_per_session?: number;\n max_seeds_per_focus?: number;\n focus_cooldown_days?: number;\n min_interval_hours?: number;\n windows?: { id?: string; start: string; end: string }[];\n };\n}\n\nexport interface BrowseState {\n wander: {\n focusHistory: Record<string, number>;\n focusCount: Record<string, number>;\n last_wander_at: number;\n /** Spec ⑥: refill wanders per LOCAL day, e.g. \"2026-09-18\" -> 1. */\n refillCount?: Record<string, number>;\n /** H-69: non-refill wander sessions per LOCAL day (the `daily_sessions`\n * budget). Refills keep their own counter above — they deliberately bypass\n * the wander window and therefore must not eat the session budget. */\n sessionCount?: Record<string, number>;\n };\n}\n\nexport function emptyBrowseState(): BrowseState {\n return { wander: { focusHistory: {}, focusCount: {}, last_wander_at: 0, refillCount: {}, sessionCount: {} } };\n}\n\nexport function browseStatePath(paths: WorkspacePaths): string {\n return path.join(paths.dataDir, 'browse.json');\n}\n\nfunction readJsonFile<T>(file: string, fallback: T): T {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as T;\n } catch {\n return fallback;\n }\n}\n\n/** Factory configs are read-only; a user layer with the same filename replaces them. */\nexport function loadInterests(paths: WorkspacePaths): InterestsConfig {\n const userPath = path.join(paths.settingsDir, 'interests.json');\n if (fs.existsSync(userPath)) return readJsonFile<InterestsConfig>(userPath, { interests: [], _schedule: {} });\n return readJsonFile<InterestsConfig>(path.join(paths.configDir, 'interests.json'), { interests: [], _schedule: {} });\n}\n\n/**\n * H-65: the state file outlives upgrades and is hand-inspectable, so a row\n * missing a field must not throw its way into a `beat_error` on every beat.\n * Garbage values are dropped back to the empty-state defaults.\n */\nexport function normalizeBrowseState(raw: unknown): BrowseState {\n const out = emptyBrowseState();\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Partial<BrowseState>;\n const w = (r.wander && typeof r.wander === 'object' ? r.wander : {}) as Partial<BrowseState['wander']>;\n out.wander.focusHistory = numberRecord(w.focusHistory);\n out.wander.focusCount = numberRecord(w.focusCount);\n out.wander.refillCount = numberRecord(w.refillCount);\n out.wander.sessionCount = numberRecord(w.sessionCount);\n if (typeof w.last_wander_at === 'number' && Number.isFinite(w.last_wander_at)) out.wander.last_wander_at = w.last_wander_at;\n return out;\n}\n\nfunction numberRecord(v: unknown): Record<string, number> {\n const out: Record<string, number> = {};\n if (!v || typeof v !== 'object' || Array.isArray(v)) return out;\n for (const [k, n] of Object.entries(v as Record<string, unknown>)) {\n if (typeof n === 'number' && Number.isFinite(n)) out[k] = n;\n }\n return out;\n}\n\nfunction loadState(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return normalizeBrowseState(loadJson<unknown>(guard, browseStatePath(paths)));\n}\n\n// ── B. wander adjudication (pure-ish, state injected) ───────────────────\n\nexport interface WanderAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n /** H-69: focuses this session was allowed to examine (`focus_per_session`);\n * `focus` is the first of them. The phase still runs one model turn per\n * focus, so >1 only widens the candidate list the caller may use. */\n candidates?: string[];\n /** H-69: per-focus seed cap (`max_seeds_per_focus`, defaulting to\n * `policy.browse.maxSeedsPerVisit`). The registration loop reads this. */\n maxSeeds?: number;\n}\n\nexport interface WanderSchedule {\n windows: { start: string; end: string }[];\n minIntervalHours: number;\n maxSeedsPerFocus: number;\n /** Wander sessions per local day; 0 = no daily cap. */\n dailySessions: number;\n focusPerSession: number;\n focusCooldownDays: number;\n}\n\n/**\n * H-69 (2026-10-07): `interests._schedule` is the block the settings card edits\n * and, as the user layer, it REPLACES the factory copy — so it wins wherever it\n * overlaps `policy.browse`, which is the compiled-in default. Every key here\n * has a reader now; `min_interval_hours`, `max_seeds_per_focus` and\n * `daily_sessions` used to be dead wiring whose factory values happened to\n * match policy's, which is exactly why nobody noticed they did nothing.\n */\nexport function resolveSchedule(interests: InterestsConfig, policy: Policy): WanderSchedule {\n const sc = interests._schedule ?? {};\n return {\n windows: sc.windows?.length ? sc.windows : (policy.browse.windows as { start: string; end: string }[]),\n minIntervalHours: sc.min_interval_hours ?? policy.browse.minIntervalHours,\n maxSeedsPerFocus: sc.max_seeds_per_focus ?? policy.browse.maxSeedsPerVisit,\n dailySessions: sc.daily_sessions ?? 0,\n focusPerSession: Math.max(1, sc.focus_per_session ?? 1),\n focusCooldownDays: sc.focus_cooldown_days ?? 3,\n };\n}\n\nexport function inWanderWindow(now: Date, windows: { start: string; end: string }[]): string | null {\n const mins = minutesOfDay(now);\n for (const w of windows) {\n if (inHhMmWindow(w.start, w.end, mins)) return `${w.start}-${w.end}`;\n }\n return null;\n}\n\nfunction onCooldown(state: BrowseState, focus: string, cooldownDays: number, now: number): boolean {\n const last = state.wander.focusHistory[focus] ?? 0;\n return last > now - cooldownDays * 86_400_000;\n}\n\n/**\n * Focus pick (2026-10-06): round-robin recency as the base, preference rate as\n * a multiplier. Ordering key = effective age = realAgeSinceLastUse × weight —\n * a favorite's age \"grows\" faster, so it reaches the pick threshold sooner and\n * is wandered up to W_MAX times as often. Lockdown-proof by construction:\n * - cooldown (above) keeps every topic rotating no matter the weight;\n * - weight lives in [W_MIN, W_MAX] (preference.ts);\n * - hard starvation floor: any topic untouched ≥ STARVATION_DAYS ignores\n * weighting entirely and the oldest real age wins.\n * Without a preference state the behavior is exactly the old pure LRU.\n */\nexport const STARVATION_DAYS = 14;\n\nexport function pickFocus(\n state: BrowseState,\n interests: InterestsConfig,\n now: number,\n pref?: PrefState,\n): string | null {\n const sc = interests._schedule ?? {};\n const cooldown = sc.focus_cooldown_days ?? 3;\n const pool = (interests.interests ?? []).filter((t) => !onCooldown(state, t, cooldown, now));\n if (pool.length === 0) return null;\n if (!pref) {\n pool.sort((a, b) => (state.wander.focusHistory[a] ?? 0) - (state.wander.focusHistory[b] ?? 0));\n return pool[0]!;\n }\n const age = (t: string): number => now - (state.wander.focusHistory[t] ?? 0);\n const starved = pool.filter((t) => age(t) >= STARVATION_DAYS * 86_400_000);\n if (starved.length > 0) {\n starved.sort((a, b) => age(b) - age(a)); // oldest real age wins\n return starved[0]!;\n }\n const effAge = (t: string): number => age(t) * preferenceWeight(pref, t, now);\n pool.sort((a, b) => effAge(b) - effAge(a));\n return pool[0]!;\n}\n\n/** Adjudicate: windows + min interval + focus cooldown -> advice | skipped. */\nexport function adviseWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): WanderAdvice {\n const state = loadState(guard, paths);\n const interests = loadInterests(paths);\n const sched = resolveSchedule(interests, policy);\n const budget = { maxSeeds: sched.maxSeedsPerFocus };\n const win = inWanderWindow(now, sched.windows);\n if (!win) {\n const hh = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;\n return { focus: null, query: null, skipped: `window(now=${hh})`, ...budget };\n }\n // H-69: `daily_sessions` — same LOCAL-day budget shape as the refill quota.\n const today = localDayKey(now);\n const sessionsToday = state.wander.sessionCount?.[today] ?? 0;\n if (sched.dailySessions > 0 && sessionsToday >= sched.dailySessions) {\n return { focus: null, query: null, skipped: `daily-sessions(${sessionsToday})`, ...budget };\n }\n const minGap = sched.minIntervalHours * 3600_000;\n if (now.getTime() - state.wander.last_wander_at < minGap) {\n return { focus: null, query: null, skipped: 'min-interval', ...budget };\n }\n // H-69: `focus_per_session` candidates, drawn without replacement so one\n // session never offers the same focus twice.\n const pref = loadPreference(guard, preferenceFilePath(paths.dataDir));\n const pool = interests.interests ?? [];\n const candidates: string[] = [];\n for (let i = 0; i < sched.focusPerSession; i++) {\n const rest = pool.filter((t) => !candidates.includes(t));\n if (rest.length === 0) break;\n const picked = pickFocus(state, { ...interests, interests: rest }, now.getTime(), pref);\n if (!picked) break;\n candidates.push(picked);\n }\n if (candidates.length === 0) return { focus: null, query: null, skipped: 'no-focus', ...budget };\n return { focus: candidates[0]!, query: `${candidates[0]!} 2026 最新`, skipped: null, candidates, ...budget };\n}\n\n/**\n * Registration is CODE-OWNED (D10): called by the orchestrator after the\n * wander phase's model call returned selections. Records cooldown/count/\n * throttle timestamps for the focus. `refill` additionally bumps the daily\n * refill counter (spec ⑥).\n */\nexport function completeWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n focus: string,\n now = Date.now(),\n opts: { refill?: boolean } = {},\n): { focus: string; count: number; refillsToday?: number } {\n const state = loadState(guard, paths);\n state.wander.focusHistory[focus] = now;\n state.wander.focusCount[focus] = (state.wander.focusCount[focus] ?? 0) + 1;\n state.wander.last_wander_at = now;\n if (!opts.refill) {\n // H-69: count this session against the `daily_sessions` budget. Refills\n // are their own channel (they deliberately bypass the window and the min\n // interval) and stay on refillCount alone.\n const day = localDayKey(new Date(now));\n state.wander.sessionCount = state.wander.sessionCount ?? {};\n state.wander.sessionCount[day] = (state.wander.sessionCount[day] ?? 0) + 1;\n }\n let refillsToday: number | undefined;\n if (opts.refill) {\n const today = localDayKey(new Date(now));\n state.wander.refillCount = state.wander.refillCount ?? {};\n state.wander.refillCount[today] = (state.wander.refillCount[today] ?? 0) + 1;\n refillsToday = state.wander.refillCount[today];\n }\n saveJson(guard, browseStatePath(paths), state);\n return { focus, count: state.wander.focusCount[focus]!, ...(refillsToday === undefined ? {} : { refillsToday }) };\n}\n\n/** LOCAL day key (refill quota is a daily human-day budget, not a UTC day). */\nfunction localDayKey(d: Date): string {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n\n// ── C. refill wander (spec ⑥, 2026-09-18): top up topic stock when it runs\n// dry. Independent of the window/minInterval gates (user decision: may stack\n// with a normal wander in the same beat) but still respects the 3-day focus\n// cooldown, and is capped at REFILL_MAX_PER_DAY per local day.\n\nexport const REFILL_TOPIC_THRESHOLD = 4;\nexport const REFILL_MAX_PER_DAY = 2;\n\nexport interface RefillAdvice {\n focus: string | null;\n query: string | null;\n skipped: string | null;\n topicCount: number;\n refillsToday: number;\n}\n\nexport function adviseRefillWander(\n guard: PathGuard,\n paths: WorkspacePaths,\n policy: Policy,\n now = new Date(),\n): RefillAdvice {\n const state = loadState(guard, paths);\n const today = localDayKey(now);\n const refillsToday = state.wander.refillCount?.[today] ?? 0;\n const topicCount = activeSeeds(loadPool(guard, seedsFilePath(paths.dataDir)))\n .filter((s) => normalizeCategory(s.category) === 'topic').length;\n if (refillsToday >= REFILL_MAX_PER_DAY) {\n return { focus: null, query: null, skipped: `refill-daily-cap(${refillsToday})`, topicCount, refillsToday };\n }\n if (topicCount > REFILL_TOPIC_THRESHOLD) {\n return { focus: null, query: null, skipped: `topic-stock-ok(${topicCount})`, topicCount, refillsToday };\n }\n const interests = loadInterests(paths);\n const focus = pickFocus(state, interests, now.getTime(), loadPreference(guard, preferenceFilePath(paths.dataDir))); // 3-day cooldown still applies\n if (!focus) {\n return { focus: null, query: null, skipped: 'no-focus', topicCount, refillsToday };\n }\n return { focus, query: `${focus} 2026 最新`, skipped: null, topicCount, refillsToday };\n}\n\nexport function browseStatus(guard: PathGuard, paths: WorkspacePaths): BrowseState {\n return loadState(guard, paths);\n}\n","// Shared HH:MM window arithmetic.\n//\n// H-14: quiet hours (`gate.ts`) and wander windows (`browse.ts`) each carried\n// their own copy of this comparison, and only ONE of them handled a window\n// that crosses midnight — so a `22:00-02:00` wander window silently never\n// matched. One implementation, one set of semantics, no drift.\n//\n// Interval is left-closed / right-open, so `22:00-02:00` and `02:00-06:00`\n// never overlap and every minute belongs to at most one window.\n\nconst HH_MM = /^(\\d{1,2}):(\\d{2})$/;\n\n/** \"22:30\" -> 1350; null when malformed (callers treat that as \"never matches\"). */\nexport function parseHhMm(text: string): number | null {\n const m = HH_MM.exec(String(text).trim());\n if (!m) return null;\n const h = Number(m[1]);\n const min = Number(m[2]);\n if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;\n return h * 60 + min;\n}\n\nexport function minutesOfDay(now: Date): number {\n return now.getHours() * 60 + now.getMinutes();\n}\n\n/** TRUE when `mins` (minutes since local midnight) falls inside [start, end). */\nexport function inHhMmWindow(start: string, end: string, mins: number): boolean {\n const s = parseHhMm(start);\n const e = parseHhMm(end);\n if (s === null || e === null) return false;\n if (s === e) return false; // zero-length window matches nothing\n return s > e ? mins >= s || mins < e : mins >= s && mins < e;\n}\n","// Windows toast channel (D12): attention hint ONLY - never carries the\n// expression body. Wraps assets/notify.ps1 (self-registering AUMID).\n\nimport path from 'node:path';\nimport { runPowerShellFile } from '../core/ps.js';\nimport type { WorkspacePaths } from '../core/paths.js';\n\nasync function runNotify(paths: WorkspacePaths, args: string[]): Promise<{ status: number; out: string }> {\n const r = await runPowerShellFile(path.join(paths.assetsDir, 'notify.ps1'), args, 20_000);\n return { status: r.status, out: `${r.stdout}${r.stderr}`.trim() };\n}\n\n/** Register the toast identity if missing (idempotent, per machine/user). */\nexport async function ensureRegistered(paths: WorkspacePaths): Promise<boolean> {\n const check = await runNotify(paths, ['-Check']);\n if (/REGISTERED: yes/.test(check.out)) return true;\n const reg = await runNotify(paths, ['-RegisterOnly']);\n return reg.status === 0;\n}\n\n/**\n * Fire the \"new message\" hint. Fixed neutral text per D12 - the actual\n * expression lives in the dedicated heartbeat session, never in the toast.\n */\nexport async function sendNewMessageHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', 'Heartbeat', '-Message', '有新消息']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n\n/** Weekly report ready hint (v1.8.0): same D12 discipline — announces that a\n * report exists, never carries its content. */\nexport async function sendWeeklyReadyHint(paths: WorkspacePaths): Promise<boolean> {\n const r = await runNotify(paths, ['-Title', '心跳周报', '-Message', '本期周报已生成']);\n return r.status === 0 && /TOAST_SENT/.test(r.out);\n}\n","/**\n * H-10: asynchronous PowerShell runner.\n *\n * The probes (idle seconds, front window, screen capture, toasts) used\n * `spawnSync`, which blocks the host's event loop for as long as the script\n * runs — 10s to 45s on a slow machine, and the GUI stalls with it. Same\n * arguments, same timeouts, same \"never throw, degrade instead\" contract, but\n * the loop stays free while the child runs.\n */\nimport { execFile } from 'node:child_process';\n\nexport interface PsResult {\n status: number;\n stdout: string;\n stderr: string;\n}\n\n/** Run `powershell.exe` and resolve with its exit code and streams. Never\n * rejects: a spawn failure and a non-zero exit both come back as `status !== 0`\n * so callers keep their existing \"probe failed\" paths. */\nexport function runPowerShell(args: string[], timeoutMs: number): Promise<PsResult> {\n return new Promise((resolve) => {\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 resolve({ status, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });\n },\n );\n child.on('error', () => { /* surfaced through the callback above */ });\n });\n}\n\n/** Convenience for the `-File <script>` shape used by every asset script. */\nexport function runPowerShellFile(script: string, args: string[], timeoutMs: number): Promise<PsResult> {\n return runPowerShell(['-File', script, ...args], timeoutMs);\n}\n","// Weekly report store + writer helpers (v1.8.0). Deliberately host-free:\r\n// orchestration (when to run, which agent, toast) lives in the orchestrator —\r\n// same split as profile/consolidate.ts. Reports are DPAPI-encrypted because a\r\n// report contains user-identifying content (profile adds, ledger texts) —\r\n// same划线标准 as profile/seeds (design doc §10.5).\r\n\r\nimport fs from 'node:fs';\r\nimport path from 'node:path';\r\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\r\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\r\nimport type { PathGuard } from '../core/path-guard.js';\r\nimport { workspace } from '../core/paths.js';\r\nimport { appendAuditLine } from '../core/audit-log.js';\r\nimport type { WeeklyFacts } from './collect.js';\r\n\r\nexport const WEEKLY_INTERVAL_MS = 7 * 86_400_000;\r\n\r\nexport interface WeeklyReport {\r\n start: string;\r\n end: string;\r\n generatedAt: string;\r\n /** 'llm' = engine-room prose; 'template' = deterministic fallback. */\r\n source: 'llm' | 'template';\r\n text: string;\r\n}\r\n\r\nexport function weeklyDirPath(dataDir: string): string {\r\n return path.join(dataDir, 'weekly');\r\n}\r\n\r\nfunction stateFilePath(dataDir: string): string {\r\n return path.join(weeklyDirPath(dataDir), 'state.json');\r\n}\r\n\r\nfunction reportFileName(endIso: string): string {\r\n return `report-${endIso.slice(0, 10)}.json`;\r\n}\r\n\r\n/**\r\n * Last generation time from the weekly state file; 0 = never anchored.\r\n *\r\n * H-54: \"missing\" and \"present but unparseable\" are NOT the same thing. The\r\n * old code folded both into 0, so `ensureWeeklyAnchor` \"repaired\" a corrupt\r\n * file by stamping NOW — silently, and at the cost of pushing the next report\r\n * a full interval out. A corrupt anchor now keeps its file, writes an audit\r\n * line, and falls back to the file's mtime so the schedule keeps its place.\r\n */\r\nexport function lastWeeklyGeneratedAt(guard: PathGuard, dataDir: string): number {\r\n const file = stateFilePath(dataDir);\r\n let raw: string;\r\n try {\r\n raw = fs.readFileSync(guard.assert(file), 'utf8');\r\n } catch {\r\n return 0; // absent: a fresh install, legitimately never anchored\r\n }\r\n try {\r\n const parsed = JSON.parse(raw) as { lastGeneratedAt?: number };\r\n const n = Number(parsed.lastGeneratedAt);\r\n if (Number.isFinite(n) && n > 0) return n;\r\n } catch {\r\n /* unparseable — handled by the fallback below */\r\n }\r\n try {\r\n appendAuditLine(path.join(workspace().logsDir, 'heartbeat.jsonl'), {\r\n event: 'weekly_anchor_corrupt',\r\n file: path.basename(file),\r\n bytes: Buffer.byteLength(raw),\r\n });\r\n } catch {\r\n /* audit is diagnostic; never let it break the schedule */\r\n }\r\n try {\r\n return fs.statSync(file).mtimeMs;\r\n } catch {\r\n return 0;\r\n }\r\n}\r\n\r\n/** Due when the last report is ≥7 days old. A never-anchored store lands on\r\n * the install-time anchor (see ensureWeeklyAnchor), so a fresh install is NOT\r\n * due — the first report arrives one full interval after installation. */\r\nexport function weeklyDue(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\r\n const last = lastWeeklyGeneratedAt(guard, dataDir);\r\n return now - last >= WEEKLY_INTERVAL_MS;\r\n}\r\n\r\n/** Stamp the install-time anchor for a store that has never generated a report\r\n * (v1.9.0). Returns true when it wrote — the caller audits that. Without this,\r\n * `lastGeneratedAt = 0` made the very first maintenance beat due, so a fresh\r\n * install produced an \"onboarding\" report immediately, contradicting the\r\n * release notes (\"first report after a week\"). */\r\nexport function ensureWeeklyAnchor(guard: PathGuard, dataDir: string, now = Date.now()): boolean {\r\n if (lastWeeklyGeneratedAt(guard, dataDir) > 0) return false;\r\n fs.mkdirSync(weeklyDirPath(dataDir), { recursive: true });\r\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: now });\r\n return true;\r\n}\r\n\r\n/** Persist a report (DPAPI) and stamp the state file. */\r\nexport function saveWeeklyReport(guard: PathGuard, dataDir: string, report: WeeklyReport): string {\r\n const dir = weeklyDirPath(dataDir);\r\n fs.mkdirSync(dir, { recursive: true });\r\n const file = path.join(dir, reportFileName(report.end));\r\n saveEncryptedText(guard, file, JSON.stringify(report, null, 1));\r\n atomicWriteJsonSync(stateFilePath(dataDir), { lastGeneratedAt: Date.parse(report.generatedAt) });\r\n return file;\r\n}\r\n\r\nexport interface WeeklyReportMeta {\r\n file: string;\r\n start: string;\r\n end: string;\r\n generatedAt: string;\r\n source: string;\r\n}\r\n\r\n/** Newest-first listing for the card; unparsable entries are skipped. */\r\nexport function listWeeklyReports(guard: PathGuard, dataDir: string): WeeklyReportMeta[] {\r\n const out: WeeklyReportMeta[] = [];\r\n try {\r\n for (const file of fs.readdirSync(weeklyDirPath(dataDir))) {\r\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) continue;\r\n const rep = readWeeklyReport(guard, dataDir, file);\r\n if (!rep) continue;\r\n out.push({ file, start: rep.start, end: rep.end, generatedAt: rep.generatedAt, source: rep.source });\r\n }\r\n } catch { /* no weekly dir yet */ }\r\n return out.sort((a, b) => (a.end < b.end ? 1 : -1));\r\n}\r\n\r\nexport function readWeeklyReport(guard: PathGuard, dataDir: string, file: string): WeeklyReport | null {\r\n if (!/^report-\\d{4}-\\d{2}-\\d{2}\\.json$/.test(file)) return null; // guard.assert would reject ../ anyway\r\n try {\r\n const raw = loadEncryptedText(guard, path.join(weeklyDirPath(dataDir), file));\r\n if (!raw) return null;\r\n const rep = JSON.parse(raw) as WeeklyReport;\r\n if (typeof rep.text !== 'string') return null;\r\n return rep;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/** The engine-room prompt: neutral system narrator, fact-bound, ≤250 chars. */\r\nexport function buildWeeklyPrompt(facts: WeeklyFacts): string {\r\n return [\r\n '你是心跳插件的后台报告器。根据下面的本周事实清单,用中文写一份周报正文。',\r\n '规则:',\r\n '- 叙述者自称「心跳」——这是插件后台,不是任何会话里的 agent;绝不能以会话 agent 的身份或人格自称。',\r\n '- 只报告事实清单里有的内容;某一节没有数据就整节跳过,不要编造、不要凑数。',\r\n '- 语气平实中性,不用感叹号;篇幅不超过 250 字。',\r\n '- 待办积压那一节用商量的语气提一句,不催促。',\r\n '- 直接输出周报正文,不要输出解释、标题或 JSON。',\r\n '',\r\n '本周事实(JSON):',\r\n JSON.stringify(facts, null, 1),\r\n ].join('\\n');\r\n}\r\n\r\n/** Deterministic fallback: the facts, plainly stated. Used when the LLM turn\r\n * fails or comes back empty — a plain report beats no report. */\r\nexport function renderTemplateReport(facts: WeeklyFacts): string {\r\n const d = (iso: string): string => iso.slice(0, 10);\r\n const lines: string[] = [`本周(${d(facts.windowStart)} ~ ${d(facts.windowEnd)})`];\r\n lines.push(`表达 ${facts.spoken} 次,静默 ${facts.silent} 次。`);\r\n if (facts.silentTopReasons.length > 0) {\r\n lines.push(`静默主因:${facts.silentTopReasons.map((r) => `${r.reason}(${r.count})`).join('、')}。`);\r\n }\r\n if (facts.profileAdds.length > 0) {\r\n lines.push(`新认识 ${facts.profileAdds.length} 条:${facts.profileAdds.map((a) => a.content).join(';')}。`);\r\n }\r\n if (facts.ledger.added.length > 0 || facts.ledger.done.length > 0) {\r\n const parts: string[] = [];\r\n if (facts.ledger.added.length > 0) parts.push(`新增待办:${facts.ledger.added.join('、')}`);\r\n if (facts.ledger.done.length > 0) parts.push(`已解决:${facts.ledger.done.join('、')}`);\r\n lines.push(`${parts.join(';')}。`);\r\n }\r\n if (facts.ledger.stale.length > 0) {\r\n lines.push(`挂了很久:${facts.ledger.stale.map((s) => `${s.text}(${s.days} 天)`).join('、')}——要删掉还是继续挂着?`);\r\n }\r\n if (facts.seeds.added.length > 0) {\r\n lines.push(`素材池新增 ${facts.seeds.added.length} 条,已消费 ${facts.seeds.consumed.length} 条。`);\r\n }\r\n if (facts.seeds.waiting.length > 0) {\r\n lines.push(`还没聊过的素材:${facts.seeds.waiting.join('、')}。`);\r\n }\r\n if (facts.reports.total > 0) {\r\n const reasonPart = facts.reports.reasons.length > 0\r\n ? `(${facts.reports.reasons.map((r) => `${r.reason} ${r.count} 次`).join('、')})`\r\n : '';\r\n lines.push(`投递报账 ${facts.reports.total} 次:用素材 ${facts.reports.material}、说真心话 ${facts.reports.heartfelt}、没说话 ${facts.reports.silent}${reasonPart}。`);\r\n }\r\n // v1.9.0: unaccounted deliveries are reported even when no report landed at\r\n // all — a silent rise in \"no report\" is exactly what would otherwise hide.\r\n if (facts.reports.missing > 0) {\r\n lines.push(`另有 ${facts.reports.missing} 次投递没等到报账(这部分没算进偏好统计)。`);\r\n }\r\n if (facts.peakHours.length > 0) {\r\n lines.push(`活跃高峰:${facts.peakHours.join('、')}。`);\r\n }\r\n return lines.join('\\n');\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAI3B,IAAM,SAAS;AAUR,SAAS,eAAe,SAAyB;AACtD,SAAO,KAAK,KAAK,SAAS,WAAW;AACvC;AAEA,IAAM,UAAU;AAEhB,SAAS,YAAY,GAAwB;AAC3C,SAAO,MAAM,EAAE,IAAI,IAAI,EAAE,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI;AACjE;AAEO,SAAS,WAAW,OAAkB,MAA8E;AACzH,QAAM,MAAM,SAAS,OAAO,MAAM,kBAAQ;AAC1C,QAAM,QAAQ,IAAI,MAAM,IAAI;AAC5B,QAAM,UAAyB,CAAC;AAChC,QAAM,WAAqB,CAAC;AAC5B,aAAW,QAAQ,OAAO;AACxB,UAAM,IAAI,QAAQ,KAAK,IAAI;AAC3B,QAAI,GAAG;AACL,cAAQ,KAAK,EAAE,MAAM,EAAE,CAAC,GAAI,MAAM,EAAE,CAAC,GAAI,QAAQ,EAAE,CAAC,GAAsB,IAAI,EAAE,CAAC,GAAI,MAAM,EAAE,CAAC,EAAG,CAAC;AAAA,IACpG;AACA,aAAS,KAAK,IAAI;AAAA,EACpB;AACA,SAAO,EAAE,QAAQ,MAAM,CAAC,KAAK,kBAAQ,SAAS,SAAS;AACzD;AAEO,SAAS,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fs from "fs";
3
- var STALE_MS = 15e3;
4
- var WAIT_MS = 3e3;
5
- var POLL_MS = 25;
6
- function sleepSync(ms) {
7
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
- }
9
- function tryAcquire(lock) {
10
- try {
11
- const fd = fs.openSync(lock, "wx");
12
- fs.writeSync(fd, `${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}
13
- `);
14
- fs.closeSync(fd);
15
- return true;
16
- } catch (e) {
17
- if (e.code !== "EEXIST") throw e;
18
- try {
19
- if (Date.now() - fs.statSync(lock).mtimeMs > STALE_MS) {
20
- fs.rmSync(lock, { force: true });
21
- return tryAcquire(lock);
22
- }
23
- } catch {
24
- return tryAcquire(lock);
25
- }
26
- return false;
27
- }
28
- }
29
- function withFileLock(target, fn) {
30
- const lock = `${target}.lock`;
31
- const deadline = Date.now() + WAIT_MS;
32
- let held = false;
33
- for (; ; ) {
34
- if (tryAcquire(lock)) {
35
- held = true;
36
- break;
37
- }
38
- if (Date.now() >= deadline) break;
39
- sleepSync(POLL_MS);
40
- }
41
- try {
42
- return fn();
43
- } finally {
44
- if (held) {
45
- try {
46
- fs.rmSync(lock, { force: true });
47
- } catch {
48
- }
49
- }
50
- }
51
- }
52
-
53
- export {
54
- withFileLock
55
- };
56
- //# sourceMappingURL=chunk-IV2ZWQA3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/file-lock.ts"],"sourcesContent":["// Cross-process advisory file lock (H-20, minimal tier).\n//\n// The seed pool and the observation inbox are WHOLE-FILE rewrites of DPAPI\n// ciphertext — the vault cannot append to them — and the CLI runs as a second\n// process against the same files. Two interleaved load→mutate→save cycles\n// therefore let one side silently overwrite the other's write. The full fix\n// (append-only journal + compaction) is v2.0 work; this keeps the writers\n// honest in the meantime.\n//\n// The lock itself is a sibling file created with O_EXCL. A lock older than\n// STALE_MS is treated as abandoned (its holder died mid-write) and reclaimed.\n\nimport fs from 'node:fs';\n\nconst STALE_MS = 15_000;\nconst WAIT_MS = 3_000;\nconst POLL_MS = 25;\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\nfunction tryAcquire(lock: string): boolean {\n try {\n const fd = fs.openSync(lock, 'wx');\n fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}\\n`);\n fs.closeSync(fd);\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;\n // Reclaim a lock whose holder is gone.\n try {\n if (Date.now() - fs.statSync(lock).mtimeMs > STALE_MS) {\n fs.rmSync(lock, { force: true });\n return tryAcquire(lock);\n }\n } catch {\n return tryAcquire(lock); // vanished between open and stat\n }\n return false;\n }\n}\n\n/**\n * Run `fn` while holding the lock for `target`. Acquisition waits up to\n * WAIT_MS, then gives up and runs anyway: a heartbeat must not be stopped by a\n * stale lock, and the caller's own read-modify-write is still the last writer\n * in the common (uncontended) case.\n */\nexport function withFileLock<T>(target: string, fn: () => T): T {\n const lock = `${target}.lock`;\n const deadline = Date.now() + WAIT_MS;\n let held = false;\n for (;;) {\n if (tryAcquire(lock)) {\n held = true;\n break;\n }\n if (Date.now() >= deadline) break;\n sleepSync(POLL_MS);\n }\n try {\n return fn();\n } finally {\n if (held) {\n try {\n fs.rmSync(lock, { force: true });\n } catch { /* already gone */ }\n }\n }\n}\n"],"mappings":";AAYA,OAAO,QAAQ;AAEf,IAAM,WAAW;AACjB,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,SAAS,UAAU,IAAkB;AACnC,UAAQ,KAAK,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,GAAG,GAAG,GAAG,EAAE;AACjE;AAEA,SAAS,WAAW,MAAuB;AACzC,MAAI;AACF,UAAM,KAAK,GAAG,SAAS,MAAM,IAAI;AACjC,OAAG,UAAU,IAAI,GAAG,QAAQ,GAAG,KAAI,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,CAAI;AAC/D,OAAG,UAAU,EAAE;AACf,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAK,EAA4B,SAAS,SAAU,OAAM;AAE1D,QAAI;AACF,UAAI,KAAK,IAAI,IAAI,GAAG,SAAS,IAAI,EAAE,UAAU,UAAU;AACrD,WAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;AAC/B,eAAO,WAAW,IAAI;AAAA,MACxB;AAAA,IACF,QAAQ;AACN,aAAO,WAAW,IAAI;AAAA,IACxB;AACA,WAAO;AAAA,EACT;AACF;AAQO,SAAS,aAAgB,QAAgB,IAAgB;AAC9D,QAAM,OAAO,GAAG,MAAM;AACtB,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,MAAI,OAAO;AACX,aAAS;AACP,QAAI,WAAW,IAAI,GAAG;AACpB,aAAO;AACP;AAAA,IACF;AACA,QAAI,KAAK,IAAI,KAAK,SAAU;AAC5B,cAAU,OAAO;AAAA,EACnB;AACA,MAAI;AACF,WAAO,GAAG;AAAA,EACZ,UAAE;AACA,QAAI,MAAM;AACR,UAAI;AACF,WAAG,OAAO,MAAM,EAAE,OAAO,KAAK,CAAC;AAAA,MACjC,QAAQ;AAAA,MAAqB;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}