@kanadego/dsh-heartbeat 2.0.1 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -57
- package/client.js +500 -125
- package/config/interests.json +1 -1
- package/config/policy.json +3 -2
- package/dist/{chunk-TVX4HV4Y.js → chunk-63E5OYSI.js} +56 -5
- package/dist/chunk-63E5OYSI.js.map +1 -0
- package/dist/{chunk-NCPKOWS7.js → chunk-AT32XCCI.js} +2 -2
- package/dist/{chunk-DC5HMCJC.js → chunk-DLOYERAK.js} +3 -3
- package/dist/{chunk-544QOJN5.js → chunk-ECXYNTEV.js} +2 -2
- package/dist/{chunk-IFRMKVIC.js → chunk-HE6IF6OU.js} +5 -2
- package/dist/chunk-HE6IF6OU.js.map +1 -0
- package/dist/{chunk-DZ7YCFGX.js → chunk-KZLVR4J7.js} +2 -2
- package/dist/{chunk-6XM6KY7M.js → chunk-LPPRI53J.js} +39 -37
- package/dist/chunk-LPPRI53J.js.map +1 -0
- package/dist/chunk-LQKOYTRL.js +59 -0
- package/dist/chunk-LQKOYTRL.js.map +1 -0
- package/dist/{chunk-AKIJ4LS2.js → chunk-M72T5MZU.js} +44 -1
- package/dist/chunk-M72T5MZU.js.map +1 -0
- package/dist/{chunk-6MVKWICX.js → chunk-XCMGPIUQ.js} +99 -23
- package/dist/chunk-XCMGPIUQ.js.map +1 -0
- package/dist/cli/index.js +51 -11
- package/dist/cli/index.js.map +1 -1
- package/dist/focus-store-RNHBAFYS.js +20 -0
- package/dist/{inbox-OWBK6PE2.js → inbox-ZLX2MH7A.js} +3 -3
- package/dist/index.d.ts +16 -3
- package/dist/index.js +119 -69
- package/dist/index.js.map +1 -1
- package/dist/{migrate-TQ5PB2DI.js → migrate-XFZU5EBE.js} +3 -3
- package/dist/{orchestrator-P7AEWVYR.js → orchestrator-MNFCPH43.js} +27 -8
- package/dist/{pool-2T6TVS2L.js → pool-MAABBHC4.js} +9 -3
- package/dist/{snapshot-F5B2DD56.js → snapshot-SU2VGM4C.js} +4 -4
- package/dist/snapshot-SU2VGM4C.js.map +1 -0
- package/icon.svg +11 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +11 -6
- package/dist/chunk-6MVKWICX.js.map +0 -1
- package/dist/chunk-6XM6KY7M.js.map +0 -1
- package/dist/chunk-AKIJ4LS2.js.map +0 -1
- package/dist/chunk-IFRMKVIC.js.map +0 -1
- package/dist/chunk-TVX4HV4Y.js.map +0 -1
- /package/dist/{chunk-NCPKOWS7.js.map → chunk-AT32XCCI.js.map} +0 -0
- /package/dist/{chunk-DC5HMCJC.js.map → chunk-DLOYERAK.js.map} +0 -0
- /package/dist/{chunk-544QOJN5.js.map → chunk-ECXYNTEV.js.map} +0 -0
- /package/dist/{chunk-DZ7YCFGX.js.map → chunk-KZLVR4J7.js.map} +0 -0
- /package/dist/{inbox-OWBK6PE2.js.map → focus-store-RNHBAFYS.js.map} +0 -0
- /package/dist/{migrate-TQ5PB2DI.js.map → inbox-ZLX2MH7A.js.map} +0 -0
- /package/dist/{orchestrator-P7AEWVYR.js.map → migrate-XFZU5EBE.js.map} +0 -0
- /package/dist/{pool-2T6TVS2L.js.map → orchestrator-MNFCPH43.js.map} +0 -0
- /package/dist/{snapshot-F5B2DD56.js.map → pool-MAABBHC4.js.map} +0 -0
package/config/interests.json
CHANGED
package/config/policy.json
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
"heartbeat": {
|
|
3
3
|
"intervalMin": 60,
|
|
4
4
|
"idleMode": false,
|
|
5
|
-
"archiveRotatedHome": true
|
|
5
|
+
"archiveRotatedHome": true,
|
|
6
|
+
"intervalJitterPct": 20
|
|
6
7
|
},
|
|
7
8
|
"gate": {
|
|
8
9
|
"maxDailySend": 10,
|
|
@@ -24,7 +25,7 @@
|
|
|
24
25
|
}
|
|
25
26
|
],
|
|
26
27
|
"minIntervalHours": 4,
|
|
27
|
-
"maxSeedsPerVisit":
|
|
28
|
+
"maxSeedsPerVisit": 4
|
|
28
29
|
},
|
|
29
30
|
"seeds": {
|
|
30
31
|
"maxActive": 30,
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
loadEncryptedText,
|
|
3
3
|
saveEncryptedText,
|
|
4
4
|
withFileLock
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-M72T5MZU.js";
|
|
6
6
|
|
|
7
7
|
// src/seeds/pool.ts
|
|
8
8
|
import path from "path";
|
|
@@ -34,6 +34,39 @@ var CATEGORY_VALUES = ["topic", "chat"];
|
|
|
34
34
|
function normalizeCategory(v) {
|
|
35
35
|
return typeof v === "string" && CATEGORY_VALUES.includes(v) ? v : "topic";
|
|
36
36
|
}
|
|
37
|
+
var SEED_SIMILARITY_THRESHOLD = 0.85;
|
|
38
|
+
var DEDUP_ARCHIVE_WINDOW_MS = 30 * DAY_MS;
|
|
39
|
+
var DEDUP_ARCHIVE_MAX = 50;
|
|
40
|
+
var DEDUP_SIMILAR_MIN_CHARS = 12;
|
|
41
|
+
function normalizeSeedText(s) {
|
|
42
|
+
return s.normalize("NFKC").toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
|
|
43
|
+
}
|
|
44
|
+
function seedSimilarity(a, b) {
|
|
45
|
+
const na = normalizeSeedText(a);
|
|
46
|
+
const nb = normalizeSeedText(b);
|
|
47
|
+
if (na === nb) return 1;
|
|
48
|
+
if (na.length < 2 || nb.length < 2) return 0;
|
|
49
|
+
const gramCount = (t) => {
|
|
50
|
+
const m = /* @__PURE__ */ new Map();
|
|
51
|
+
for (let i = 0; i < t.length - 1; i++) {
|
|
52
|
+
const g = t.slice(i, i + 2);
|
|
53
|
+
m.set(g, (m.get(g) ?? 0) + 1);
|
|
54
|
+
}
|
|
55
|
+
return m;
|
|
56
|
+
};
|
|
57
|
+
const A = gramCount(na);
|
|
58
|
+
const B = gramCount(nb);
|
|
59
|
+
let inter = 0;
|
|
60
|
+
let sizeA = 0;
|
|
61
|
+
let sizeB = 0;
|
|
62
|
+
for (const c of A.values()) sizeA += c;
|
|
63
|
+
for (const c of B.values()) sizeB += c;
|
|
64
|
+
for (const [g, c] of A) inter += Math.min(c, B.get(g) ?? 0);
|
|
65
|
+
return 2 * inter / (sizeA + sizeB);
|
|
66
|
+
}
|
|
67
|
+
function recentArchived(db, now) {
|
|
68
|
+
return archivedSeeds(db).filter((s) => now - parseIso(s.retiredAt ?? "") <= DEDUP_ARCHIVE_WINDOW_MS).sort((a, b) => parseIso(b.retiredAt ?? "") - parseIso(a.retiredAt ?? "")).slice(0, DEDUP_ARCHIVE_MAX);
|
|
69
|
+
}
|
|
37
70
|
var TTL_KEYS = ["news", "fandom", "scene", "promise"];
|
|
38
71
|
function normalizeTag(tag) {
|
|
39
72
|
if (tag && TTL_KEYS.includes(tag)) return tag;
|
|
@@ -122,13 +155,28 @@ function addSeedLocked(guard, file, policy, input, now, audit) {
|
|
|
122
155
|
const source = input.source ?? "chat";
|
|
123
156
|
const category = normalizeCategory(input.category ?? (source === "chat" ? "chat" : "topic"));
|
|
124
157
|
const confidence = input.confidence ?? SEED_SOURCE_DEFAULT_CONFIDENCE[source];
|
|
125
|
-
const
|
|
126
|
-
|
|
158
|
+
const textNorm = normalizeSeedText(text);
|
|
159
|
+
for (const cand of [...activeSeeds(db), ...recentArchived(db, now)]) {
|
|
160
|
+
if (cand.text === text) {
|
|
161
|
+
emit(audit, { event: "seed_duplicate", id: cand.id, reason: "exact" });
|
|
162
|
+
return { kind: "duplicate", seed: cand, reason: "exact" };
|
|
163
|
+
}
|
|
164
|
+
const candNorm = normalizeSeedText(cand.text);
|
|
165
|
+
if (candNorm === textNorm) {
|
|
166
|
+
emit(audit, { event: "seed_duplicate", id: cand.id, reason: "normalized", similarity: 1 });
|
|
167
|
+
return { kind: "duplicate", seed: cand, reason: "normalized" };
|
|
168
|
+
}
|
|
169
|
+
if (textNorm.length < DEDUP_SIMILAR_MIN_CHARS || candNorm.length < DEDUP_SIMILAR_MIN_CHARS) continue;
|
|
170
|
+
const sim = seedSimilarity(cand.text, text);
|
|
171
|
+
if (sim <= SEED_SIMILARITY_THRESHOLD) continue;
|
|
172
|
+
emit(audit, { event: "seed_duplicate", id: cand.id, reason: "similar", similarity: Number(sim.toFixed(3)) });
|
|
173
|
+
return { kind: "duplicate", seed: cand, reason: "similar" };
|
|
174
|
+
}
|
|
127
175
|
const nowIso = new Date(now).toISOString();
|
|
128
176
|
const ttlMs = (policy.seeds.ttlDays[tag] || 14) * DAY_MS;
|
|
129
177
|
const sameTopic = activeSeeds(db).filter((s) => s.topic === (input.topic ?? text.slice(0, 24)));
|
|
130
178
|
let seed;
|
|
131
|
-
if (sameTopic.length > 0) {
|
|
179
|
+
if (sameTopic.length > 0 && !input.noMerge) {
|
|
132
180
|
const kept = sameTopic[0];
|
|
133
181
|
kept.text = text;
|
|
134
182
|
kept.tag = tag;
|
|
@@ -296,6 +344,9 @@ function deleteSeed(guard, file, id, audit = NO_AUDIT) {
|
|
|
296
344
|
export {
|
|
297
345
|
SEED_CATEGORY_CAPS,
|
|
298
346
|
normalizeCategory,
|
|
347
|
+
SEED_SIMILARITY_THRESHOLD,
|
|
348
|
+
normalizeSeedText,
|
|
349
|
+
seedSimilarity,
|
|
299
350
|
TTL_KEYS,
|
|
300
351
|
normalizeTag,
|
|
301
352
|
seedsFilePath,
|
|
@@ -312,4 +363,4 @@ export {
|
|
|
312
363
|
restoreSeed,
|
|
313
364
|
deleteSeed
|
|
314
365
|
};
|
|
315
|
-
//# sourceMappingURL=chunk-
|
|
366
|
+
//# sourceMappingURL=chunk-63E5OYSI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/seeds/pool.ts","../src/seeds/types.ts"],"sourcesContent":["// Material pool engine (design doc §4). All four eviction rules are\n// deterministic code - no LLM involvement (§4.2). Storage: data/seeds.jsonl,\n// one seed per JSON line, DPAPI-encrypted at rest (D14).\n\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadEncryptedText, saveEncryptedText } from '../vault/vault.js';\nimport { withFileLock } from '../core/file-lock.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n SEED_SOURCE_DEFAULT_CONFIDENCE,\n emptySeedDb,\n type Seed,\n type SeedCategory,\n type SeedDb,\n type SeedRetireReason,\n type SeedSource,\n type SeedTag,\n} from './types.js';\n\nconst DAY_MS = 86_400_000;\n\n// ── lifecycle audit (2026-10-06 / v1.9.0) ───────────────────────────────\n// The pool used to mutate in silence: a seed could appear, be evicted for\n// capacity, or be dropped from the archive with nothing in the log. Every\n// mutator now takes an optional sink and reports what it did. IDs and\n// metadata ONLY — heartbeat.jsonl is plaintext by charter and must never\n// carry conversation text; the seed text itself stays in the DPAPI pool.\nexport type SeedAuditFn = (entry: Record<string, unknown>) => void;\n\nconst NO_AUDIT: SeedAuditFn = () => {};\n\n/** Audit must never break the pool (or the beat that called it). */\nfunction emit(audit: SeedAuditFn, entry: Record<string, unknown>): void {\n try {\n audit(entry);\n } catch {\n /* audit is diagnostic; a failed append is not a pool failure */\n }\n}\n\n// Per-category pool caps (2026-09-18 spec ⑤): topic stock vs conversation-grown\n// chat material, decoupled from `source`; sum == the global maxActive default.\nexport const SEED_CATEGORY_CAPS: Record<SeedCategory, number> = { topic: 16, chat: 14 };\n\nconst CATEGORY_VALUES: readonly string[] = ['topic', 'chat'];\n\n/** Lenient category coercion for on-disk rows: anything missing/unknown (all\n * pre-v1.5 seeds) counts as topic stock. */\nexport function normalizeCategory(v: unknown): SeedCategory {\n return typeof v === 'string' && (CATEGORY_VALUES as readonly string[]).includes(v)\n ? (v as SeedCategory)\n : 'topic';\n}\n\nexport interface AddSeedInput {\n text: string;\n topic?: string;\n tag?: SeedTag;\n source?: SeedSource;\n /** Loop role (spec ⑤); defaults from source: chat->chat, everything else->topic. */\n category?: SeedCategory;\n confidence?: number;\n /** Skip the §4.3 same-topic merge: callers registering several items under\n * one focus in a single pass (wander) set this so each item survives as\n * its own seed instead of collapsing into the first. */\n noMerge?: boolean;\n}\n\nexport type DuplicateReason = 'exact' | 'normalized' | 'similar';\n\nexport interface AddSeedResult {\n kind: 'added' | 'merged' | 'duplicate';\n seed: Seed;\n evicted?: Seed;\n /** Why a 'duplicate' was judged; absent on other kinds. */\n reason?: DuplicateReason;\n}\n\n// ── dedup (2026-10-29): wander keeps re-seeding the same material, so the add\n// path compares against actives AND recently archived seeds on three levels —\n// raw text, NFKC-normalized text, and character-bigram Dice similarity.\nexport const SEED_SIMILARITY_THRESHOLD = 0.85;\nconst DEDUP_ARCHIVE_WINDOW_MS = 30 * DAY_MS;\nconst DEDUP_ARCHIVE_MAX = 50;\n/** Short strings are all shared bigrams: \"话题素材 1\" vs \"话题素材 11\" scores\n * 0.889 and \"没有新证据的话题\" vs \"有新证据的话题\" 0.923, i.e. the similarity\n * layer would kill genuinely distinct short headlines. Below this normalized\n * length only the exact and normalized layers run (2026-10-30 review; the\n * old seeds.test.ts cap cases caught it as a real regression). */\nconst DEDUP_SIMILAR_MIN_CHARS = 12;\n\n/** Full-width -> half-width (NFKC), lowercase, strip all whitespace and\n * punctuation: only the surviving characters may make two seeds collide. */\nexport function normalizeSeedText(s: string): string {\n return s\n .normalize('NFKC')\n .toLowerCase()\n .replace(/[\\s\\p{P}\\p{S}]+/gu, '');\n}\n\n/** Dice coefficient over character bigrams of the NORMALIZED texts:\n * 2*|A∩B| / (|A|+|B|). Identical normalizations are 1; either side short\n * enough to have no bigrams only matches when they are identical. */\nexport function seedSimilarity(a: string, b: string): number {\n const na = normalizeSeedText(a);\n const nb = normalizeSeedText(b);\n if (na === nb) return 1;\n if (na.length < 2 || nb.length < 2) return 0;\n const gramCount = (t: string): Map<string, number> => {\n const m = new Map<string, number>();\n for (let i = 0; i < t.length - 1; i++) {\n const g = t.slice(i, i + 2);\n m.set(g, (m.get(g) ?? 0) + 1);\n }\n return m;\n };\n const A = gramCount(na);\n const B = gramCount(nb);\n let inter = 0;\n let sizeA = 0;\n let sizeB = 0;\n for (const c of A.values()) sizeA += c;\n for (const c of B.values()) sizeB += c;\n for (const [g, c] of A) inter += Math.min(c, B.get(g) ?? 0);\n return (2 * inter) / (sizeA + sizeB);\n}\n\n/** Archive side of the dedup scope: recently retired only (within 30 days,\n * newest first, at most 50) — the archive is a forensic trail, not a corpus\n * to scan on every add. */\nfunction recentArchived(db: SeedDb, now: number): Seed[] {\n return archivedSeeds(db)\n .filter((s) => now - parseIso(s.retiredAt ?? '') <= DEDUP_ARCHIVE_WINDOW_MS)\n .sort((a, b) => parseIso(b.retiredAt ?? '') - parseIso(a.retiredAt ?? ''))\n .slice(0, DEDUP_ARCHIVE_MAX);\n}\n\nexport interface GcReport {\n consumed: number;\n expired: number;\n coldBench: number;\n activeAfter: number;\n /** v1.9.0: archived rows dropped to honor seeds.archiveCap (oldest first). */\n archiveTrimmed: number;\n}\n\nexport const TTL_KEYS: readonly SeedTag[] = ['news', 'fandom', 'scene', 'promise'];\n\nexport function normalizeTag(tag: string | undefined): SeedTag {\n if (tag && (TTL_KEYS as readonly string[]).includes(tag)) return tag as SeedTag;\n return 'scene';\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n// ── storage ─────────────────────────────────────────────────────────────\n\nexport function seedsFilePath(dataDir: string): string {\n return path.join(dataDir, 'seeds.jsonl');\n}\n\nexport function loadPool(guard: PathGuard, file: string): SeedDb {\n const raw = loadEncryptedText(guard, file);\n if (raw === null) return emptySeedDb();\n const db = emptySeedDb();\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const obj = JSON.parse(trimmed) as Seed;\n if (typeof obj.id === 'string' && obj.id.startsWith('s')) {\n // spec ⑤ loadPool tolerance: only the id is load-bearing; a missing or\n // unknown category (every pre-v1.5 row) falls back to topic stock.\n obj.category = normalizeCategory(obj.category);\n db.seeds.push(obj);\n const n = Number(obj.id.slice(1));\n if (Number.isFinite(n) && n > db.seq) db.seq = n;\n }\n } catch {\n // corrupt line: skip (pool is a cache; journal-level audit lives elsewhere)\n }\n }\n return db;\n}\n\nexport function savePool(guard: PathGuard, file: string, db: SeedDb): void {\n const body = db.seeds.map((s) => JSON.stringify(s)).join('\\n');\n saveEncryptedText(guard, file, body ? body + '\\n' : '');\n}\n\n/**\n * H-20 (minimal tier): every pool writer goes through here, so the load happens\n * INSIDE the cross-process lock and cannot be based on a read that went stale\n * while it was being mutated — the CLI is a second process sharing this file,\n * and an interleaved write used to be silently overwritten. The ciphertext is a\n * whole-file rewrite, so append/merge does not apply here; the append-only pool\n * with compaction is v2.0 work (ledger #8649f9).\n */\nfunction update<T>(guard: PathGuard, file: string, fn: (db: SeedDb) => T): T {\n return withFileLock(file, () => fn(loadPool(guard, file)));\n}\n\n// ── queries ─────────────────────────────────────────────────────────────\n\nexport const activeSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'active');\nexport const archivedSeeds = (db: SeedDb): Seed[] => db.seeds.filter((s) => s.status === 'archived');\n\n// ── eviction scoring (rule 4) ───────────────────────────────────────────\n\n/**\n * Comprehensive score (§4.2): freshness x0.4 + unused x0.3 + confidence x0.3.\n * Higher = keep. Lowest-scoring active is evicted when the pool is full.\n */\nexport function evictionScore(seed: Seed, policy: Policy, now: number): number {\n const ttlDays = policy.seeds.ttlDays[seed.tag] || 14;\n const daysStale = Math.max(0, (now - parseIso(seed.lastEvidenceAt)) / DAY_MS);\n const freshness = Math.max(0, 1 - daysStale / ttlDays);\n const unused = seed.used === 0 ? 1 : 1 / seed.used;\n const w = policy.seeds.scoreWeights;\n return freshness * w.freshness + unused * w.unused + seed.confidence * w.confidence;\n}\n\n/** Pick the eviction victim: unprotected actives first (§4.2 加权保护); with\n * `category`, only that category's actives compete (spec ⑤ per-category caps). */\nexport function pickEvictionVictim(db: SeedDb, policy: Policy, now: number, category?: SeedCategory): Seed | null {\n const actives = activeSeeds(db).filter((s) => category === undefined || normalizeCategory(s.category) === category);\n if (actives.length === 0) return null;\n const unprotected = actives.filter((s) => !s.protected);\n const candidates = unprotected.length > 0 ? unprotected : actives;\n let worst: Seed | null = null;\n let worstScore = Number.POSITIVE_INFINITY;\n for (const s of candidates) {\n const score = evictionScore(s, policy, now);\n if (score < worstScore) {\n worstScore = score;\n worst = s;\n }\n }\n return worst;\n}\n\nfunction archiveSeed(seed: Seed, reason: SeedRetireReason, now: number): void {\n seed.status = 'archived';\n seed.retireReason = reason;\n seed.retiredAt = new Date(now).toISOString();\n}\n\n/** Spec ④: chat-grown material is consumed ONCE (conversation freshness);\n * every other category follows the policy-wide retireAfterUsed. */\nfunction retireLimit(s: Seed, policy: Policy): number {\n return normalizeCategory(s.category) === 'chat' ? 1 : policy.seeds.retireAfterUsed;\n}\n\n/**\n * Rule 1 (§4.2): used up to its limit AND no evidence newer than the PREVIOUS\n * use. `prevUsedAt` MUST be read before bumping `lastUsedAt` — comparing the\n * just-written value against `lastEvidenceAt` is vacuously true (H-22), which\n * retired seeds that had received fresh evidence in the same beat. Both\n * callers (gc and surface) share this, so the rule cannot drift again.\n *\n * `prevUsedAt === 0` means \"never used before\": there is no earlier use for\n * the evidence to be newer THAN, so the exemption cannot apply — a one-shot\n * (chat) seed still retires on its first surfacing (spec ④), which is the\n * contract, not a regression.\n */\nfunction isConsumed(s: Seed, policy: Policy, prevUsedAt: number, sinceEvidence: number): boolean {\n if (s.used < retireLimit(s, policy)) return false;\n return !(prevUsedAt > 0 && sinceEvidence > prevUsedAt);\n}\n\n// ── operations ──────────────────────────────────────────────────────────\n\nexport function addSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): AddSeedResult {\n // H-20: the read-modify-write below runs under the cross-process pool lock\n // (same guard as `update`, kept as a named body to avoid re-indenting it).\n return withFileLock(file, () => addSeedLocked(guard, file, policy, input, now, audit));\n}\n\nfunction addSeedLocked(\n guard: PathGuard,\n file: string,\n policy: Policy,\n input: AddSeedInput,\n now: number,\n audit: SeedAuditFn,\n): AddSeedResult {\n const db = loadPool(guard, file);\n const text = input.text.trim();\n if (!text) throw new Error('seed text must not be empty');\n const tag = normalizeTag(input.tag);\n const source: SeedSource = input.source ?? 'chat';\n const category = normalizeCategory(input.category ?? (source === 'chat' ? 'chat' : 'topic'));\n const confidence = input.confidence ?? SEED_SOURCE_DEFAULT_CONFIDENCE[source];\n\n // Three-layer dedup against actives + recently archived. Exact hits audit\n // without a score; normalized hits score 1 by definition. The similarity\n // layer is skipped for short texts (see DEDUP_SIMILAR_MIN_CHARS): distinct\n // short headlines share too many bigrams to be told apart by Dice alone.\n const textNorm = normalizeSeedText(text);\n for (const cand of [...activeSeeds(db), ...recentArchived(db, now)]) {\n if (cand.text === text) {\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'exact' });\n return { kind: 'duplicate', seed: cand, reason: 'exact' };\n }\n const candNorm = normalizeSeedText(cand.text);\n if (candNorm === textNorm) {\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'normalized', similarity: 1 });\n return { kind: 'duplicate', seed: cand, reason: 'normalized' };\n }\n if (textNorm.length < DEDUP_SIMILAR_MIN_CHARS || candNorm.length < DEDUP_SIMILAR_MIN_CHARS) continue;\n const sim = seedSimilarity(cand.text, text);\n if (sim <= SEED_SIMILARITY_THRESHOLD) continue;\n emit(audit, { event: 'seed_duplicate', id: cand.id, reason: 'similar', similarity: Number(sim.toFixed(3)) });\n return { kind: 'duplicate', seed: cand, reason: 'similar' };\n }\n\n const nowIso = new Date(now).toISOString();\n const ttlMs = (policy.seeds.ttlDays[tag] || 14) * DAY_MS;\n\n // Same-topic merge (§4.3): collapse all same-topic actives + the new item.\n // `noMerge` opts out — wander registers several items under one focus per\n // pass and each must land as its own seed.\n const sameTopic = activeSeeds(db).filter((s) => s.topic === (input.topic ?? text.slice(0, 24)));\n let seed: Seed;\n if (sameTopic.length > 0 && !input.noMerge) {\n const kept = sameTopic[0]!;\n kept.text = text; // brief takes the latest\n kept.tag = tag;\n kept.source = source;\n kept.category = normalizeCategory(input.category ?? kept.category ?? category);\n kept.confidence = Math.max(kept.confidence, confidence);\n kept.used = sameTopic.reduce((acc, s) => acc + s.used, 0); // used accumulates\n kept.lastEvidenceAt = [kept.lastEvidenceAt, nowIso, ...sameTopic.map((s) => s.lastEvidenceAt)]\n .reduce((a, b) => (parseIso(b) > parseIso(a) ? b : a));\n kept.expiresAt = new Date(Math.max(parseIso(kept.expiresAt), now + ttlMs)).toISOString();\n kept.protected = kept.protected || source === 'hand' || (source === 'profile' && confidence >= 0.7);\n // remove the other same-topic actives (merged into kept)\n for (const extra of sameTopic.slice(1)) {\n extra.status = 'archived';\n extra.retireReason = 'completed';\n extra.retiredAt = nowIso;\n emit(audit, { event: 'seed_retired', id: extra.id, reason: 'completed', via: 'merge', into: kept.id });\n }\n seed = kept;\n // capacity still applies after growth check below if kept is somehow over cap\n if (activeSeeds(db).length > policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, normalizeCategory(kept.category));\n if (victim && victim.id !== kept.id) {\n archiveSeed(victim, 'pool_cap', now);\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n emit(audit, { event: 'seed_retired', id: victim.id, reason: 'pool_cap', via: 'merge', into: kept.id });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept, evicted: victim };\n }\n }\n emit(audit, { event: 'seed_added', id: kept.id, kind: 'merged', tag: kept.tag, source: kept.source, category: kept.category, confidence: kept.confidence, mergedFrom: sameTopic.length - 1 });\n savePool(guard, file, db);\n return { kind: 'merged', seed: kept };\n }\n\n // Capacity first (rules 4 + spec ⑤): per-category cap evicts within its own\n // pool; the global cap evicts in the incoming seed's category (a full topic\n // stock must not push chat material out and vice versa).\n let evicted: Seed | undefined;\n const catCount = activeSeeds(db).filter((s) => normalizeCategory(s.category) === category).length;\n if (catCount >= SEED_CATEGORY_CAPS[category]) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = victim;\n }\n }\n if (activeSeeds(db).length >= policy.seeds.maxActive) {\n const victim = pickEvictionVictim(db, policy, now, category);\n if (victim) {\n archiveSeed(victim, 'pool_cap', now);\n evicted = evicted ?? victim;\n }\n }\n\n db.seq += 1;\n seed = {\n id: `s${db.seq}`,\n text,\n topic: input.topic ?? text.slice(0, 24),\n tag,\n source,\n category,\n confidence,\n protected: source === 'hand' || (source === 'profile' && confidence >= 0.7),\n used: 0,\n bornAt: nowIso,\n expiresAt: new Date(now + ttlMs).toISOString(),\n lastUsedAt: null,\n lastEvidenceAt: nowIso,\n status: 'active',\n };\n db.seeds.push(seed);\n emit(audit, { event: 'seed_added', id: seed.id, kind: 'added', tag: seed.tag, source: seed.source, category: seed.category, confidence: seed.confidence });\n if (evicted) emit(audit, { event: 'seed_retired', id: evicted.id, reason: 'pool_cap', via: 'add', into: seed.id });\n savePool(guard, file, db);\n return { kind: 'added', seed, evicted };\n}\n\n/**\n * Deterministic gc (rules 1-3 of §4.2). Rule 4 (pool cap) fires on add only.\n * v1.9.0: the archive area is ALSO capped (seeds.archiveCap) — the archive is\n * a forensic trail, not a hoard; trim oldest-retired first.\n */\nexport function gcPool(guard: PathGuard, file: string, policy: Policy, now = Date.now(), audit: SeedAuditFn = NO_AUDIT): GcReport {\n return update(guard, file, (db) => {\n const report: GcReport = { consumed: 0, expired: 0, coldBench: 0, activeAfter: 0, archiveTrimmed: 0 };\n for (const s of activeSeeds(db)) {\n const ageMs = now - parseIso(s.bornAt);\n const sinceEvidence = parseIso(s.lastEvidenceAt);\n const sinceUsed = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n if (isConsumed(s, policy, sinceUsed, sinceEvidence)) {\n archiveSeed(s, 'consumed', now);\n report.consumed += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'gc', used: s.used });\n } else if (now > parseIso(s.expiresAt)) {\n archiveSeed(s, 'expired', now);\n report.expired += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'expired', via: 'gc', used: s.used });\n } else if (s.used === 0 && ageMs >= policy.seeds.coldBenchDays * DAY_MS) {\n archiveSeed(s, 'cold_bench', now);\n report.coldBench += 1;\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'cold_bench', via: 'gc', used: s.used });\n }\n }\n // archive cap: drop the oldest-retired rows beyond the cap (retiredAt may be\n // missing on pre-v1.5 rows — parseIso('') = 0 sorts them oldest).\n const archived = db.seeds.filter((s) => s.status === 'archived');\n if (archived.length > policy.seeds.archiveCap) {\n const drop = [...archived]\n .sort((a, b) => parseIso(a.retiredAt ?? '') - parseIso(b.retiredAt ?? ''))\n .slice(0, archived.length - policy.seeds.archiveCap);\n const dropped = new Set(drop.map((s) => s.id));\n db.seeds = db.seeds.filter((s) => !dropped.has(s.id));\n report.archiveTrimmed = drop.length;\n // These rows are GONE (not archived — deleted): the log is the only trace\n // left, so name them. IDs only, and cap the list in case a first GC trims\n // a legacy archive wholesale.\n emit(audit, { event: 'seed_archive_trimmed', count: drop.length, ids: drop.slice(0, 50).map((s) => s.id) });\n }\n report.activeAfter = activeSeeds(db).length;\n savePool(guard, file, db);\n return report;\n });\n}\n\n/** The seed surfaced in a real expression: count + maybe retire (rule 1). */\nexport function surfaceSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n // H-22: snapshot the PREVIOUS use time before bumping it — the retirement\n // check must compare against the last use, not against this one.\n const prevUsedAt = s.lastUsedAt ? parseIso(s.lastUsedAt) : 0;\n s.used += 1;\n s.lastUsedAt = new Date(now).toISOString();\n if (isConsumed(s, policy, prevUsedAt, parseIso(s.lastEvidenceAt))) {\n archiveSeed(s, 'consumed', now);\n emit(audit, { event: 'seed_retired', id: s.id, reason: 'consumed', via: 'surface', used: s.used });\n }\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Deliberate retirement (item completed / no longer relevant). */\nexport function archiveSeedById(\n guard: PathGuard,\n file: string,\n id: string,\n reason: SeedRetireReason = 'completed',\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): Seed | null {\n return update(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'active');\n if (!s) return null;\n archiveSeed(s, reason, now);\n emit(audit, { event: 'seed_retired', id: s.id, reason, via: 'manual' });\n savePool(guard, file, db);\n return s;\n });\n}\n\n/** Restore an archived seed to the active pool (UI operation; resets TTL). */\nexport function restoreSeed(\n guard: PathGuard,\n file: string,\n policy: Policy,\n id: string,\n now = Date.now(),\n audit: SeedAuditFn = NO_AUDIT,\n): { ok: true; seed: Seed } | { ok: false; reason: string } {\n return update<{ ok: true; seed: Seed } | { ok: false; reason: string }>(guard, file, (db) => {\n const s = db.seeds.find((x) => x.id === id && x.status === 'archived');\n if (!s) return { ok: false, reason: 'archived seed not found' };\n // H-23: a restore must satisfy the same two caps an add does — the global\n // one AND the per-category one. The add path evicts a neighbour instead, but\n // restoring a memory is a user action: refuse it rather than silently\n // pushing someone else's material out.\n const category = normalizeCategory(s.category);\n const catCap = SEED_CATEGORY_CAPS[category];\n const inCategory = activeSeeds(db).filter((x) => normalizeCategory(x.category) === category).length;\n if (inCategory >= catCap) {\n return { ok: false, reason: `category full (${category}: ${catCap}); archive something in it first` };\n }\n if (activeSeeds(db).length >= policy.seeds.maxActive) {\n return { ok: false, reason: `pool full (${policy.seeds.maxActive}); archive something first` };\n }\n s.status = 'active';\n s.retireReason = undefined;\n s.retiredAt = undefined;\n // H-23: reset bornAt as well — cold-bench eviction (used === 0 && age >=\n // coldBenchDays) keys off bornAt, so a restored seed used to be re-archived\n // by the very next maintenance beat (\"restored, then gone one beat later\").\n s.bornAt = new Date(now).toISOString();\n s.expiresAt = new Date(now + (policy.seeds.ttlDays[s.tag] || 14) * DAY_MS).toISOString();\n s.lastEvidenceAt = new Date(now).toISOString();\n emit(audit, { event: 'seed_restored', id: s.id });\n savePool(guard, file, db);\n return { ok: true, seed: s };\n });\n}\n\n/** Hard delete (UI explicit action with confirm; the caller audits it). */\nexport function deleteSeed(guard: PathGuard, file: string, id: string, audit: SeedAuditFn = NO_AUDIT): boolean {\n return update(guard, file, (db) => {\n const before = db.seeds.length;\n db.seeds = db.seeds.filter((x) => x.id !== id);\n if (db.seeds.length === before) return false;\n emit(audit, { event: 'seed_deleted', id });\n savePool(guard, file, db);\n return true;\n });\n}\n","// Material pool (\"素材池\") types. Charter (axiom 3): this pool is a CACHE,\n// not memory - volatile, evictable, burnable; long-term memory only absorbs\n// conversation-validated content. Everything here may be destroyed.\n\nexport type SeedTag = 'news' | 'fandom' | 'scene' | 'promise';\nexport type SeedSource = 'chat' | 'screen' | 'browse' | 'hand' | 'profile';\nexport type SeedCategory = 'topic' | 'chat';\nexport type SeedRetireReason = 'consumed' | 'expired' | 'cold_bench' | 'pool_cap' | 'completed';\n\nexport interface Seed {\n id: string;\n /** Short brief shown to the reflection prompt. */\n text: string;\n /** Merge key (§4.3): same-topic actives collapse into one. */\n topic: string;\n tag: SeedTag;\n source: SeedSource;\n /** Loop role, decoupled from source (2026-09-18 spec ⑤): 'topic' = wander/\n * hand/profile stock (random pick), 'chat' = conversation-grown, consumed\n * once. Absent on pre-v1.5 rows; loadPool defaults them to 'topic'. */\n category?: SeedCategory;\n /** 0..1 trust level; handwriting and high-confidence profile sources gain eviction protection. */\n confidence: number;\n /** Eviction protection (§4.2 pool-cap rule): handwritten / high-confidence profile sources. */\n protected: boolean;\n /** Times this seed surfaced in an actual expression. */\n used: number;\n bornAt: string;\n /** bornAt + ttlDays[tag]; archived when passed (rule 2). */\n expiresAt: string;\n lastUsedAt: string | null;\n /** Fresh-evidence watermark: rule 1 spares seeds with evidence newer than last use. */\n lastEvidenceAt: string;\n status: 'active' | 'archived';\n retireReason?: SeedRetireReason;\n retiredAt?: string;\n}\n\nexport interface SeedDb {\n seq: number;\n seeds: Seed[];\n}\n\nexport function emptySeedDb(): SeedDb {\n return { seq: 0, seeds: [] };\n}\n\nexport const SEED_SOURCE_DEFAULT_CONFIDENCE: Record<SeedSource, number> = {\n hand: 1.0,\n profile: 0.7,\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n};\n"],"mappings":";;;;;;;AAIA,OAAO,UAAU;;;ACuCV,SAAS,cAAsB;AACpC,SAAO,EAAE,KAAK,GAAG,OAAO,CAAC,EAAE;AAC7B;AAEO,IAAM,iCAA6D;AAAA,EACxE,MAAM;AAAA,EACN,SAAS;AAAA,EACT,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AACV;;;ADjCA,IAAM,SAAS;AAUf,IAAM,WAAwB,MAAM;AAAC;AAGrC,SAAS,KAAK,OAAoB,OAAsC;AACtE,MAAI;AACF,UAAM,KAAK;AAAA,EACb,QAAQ;AAAA,EAER;AACF;AAIO,IAAM,qBAAmD,EAAE,OAAO,IAAI,MAAM,GAAG;AAEtF,IAAM,kBAAqC,CAAC,SAAS,MAAM;AAIpD,SAAS,kBAAkB,GAA0B;AAC1D,SAAO,OAAO,MAAM,YAAa,gBAAsC,SAAS,CAAC,IAC5E,IACD;AACN;AA6BO,IAAM,4BAA4B;AACzC,IAAM,0BAA0B,KAAK;AACrC,IAAM,oBAAoB;AAM1B,IAAM,0BAA0B;AAIzB,SAAS,kBAAkB,GAAmB;AACnD,SAAO,EACJ,UAAU,MAAM,EAChB,YAAY,EACZ,QAAQ,qBAAqB,EAAE;AACpC;AAKO,SAAS,eAAe,GAAW,GAAmB;AAC3D,QAAM,KAAK,kBAAkB,CAAC;AAC9B,QAAM,KAAK,kBAAkB,CAAC;AAC9B,MAAI,OAAO,GAAI,QAAO;AACtB,MAAI,GAAG,SAAS,KAAK,GAAG,SAAS,EAAG,QAAO;AAC3C,QAAM,YAAY,CAAC,MAAmC;AACpD,UAAM,I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|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-M72T5MZU.js";
|
|
6
6
|
|
|
7
7
|
// src/vault/migrate.ts
|
|
8
8
|
import fs from "fs";
|
|
@@ -260,4 +260,4 @@ export {
|
|
|
260
260
|
decryptContainer,
|
|
261
261
|
applyMigrationEntries
|
|
262
262
|
};
|
|
263
|
-
//# sourceMappingURL=chunk-
|
|
263
|
+
//# sourceMappingURL=chunk-AT32XCCI.js.map
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
journalFilePath,
|
|
5
5
|
replayJournal,
|
|
6
6
|
snapshotFilePath
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-ECXYNTEV.js";
|
|
8
8
|
import {
|
|
9
9
|
saveJson
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-M72T5MZU.js";
|
|
11
11
|
|
|
12
12
|
// src/profile/snapshot.ts
|
|
13
13
|
import fs from "fs";
|
|
@@ -84,4 +84,4 @@ export {
|
|
|
84
84
|
snapshotProfile,
|
|
85
85
|
snapshotIfDue
|
|
86
86
|
};
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
87
|
+
//# sourceMappingURL=chunk-DLOYERAK.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
readText,
|
|
5
5
|
saveJson,
|
|
6
6
|
writeText
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-M72T5MZU.js";
|
|
8
8
|
import {
|
|
9
9
|
atomicWriteFileSync
|
|
10
10
|
} from "./chunk-IBBAISSW.js";
|
|
@@ -851,4 +851,4 @@ export {
|
|
|
851
851
|
rebuildProfile,
|
|
852
852
|
wipeProfile
|
|
853
853
|
};
|
|
854
|
-
//# sourceMappingURL=chunk-
|
|
854
|
+
//# sourceMappingURL=chunk-ECXYNTEV.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readText,
|
|
3
3
|
writeText
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-M72T5MZU.js";
|
|
5
5
|
import {
|
|
6
6
|
atomicWriteFileSync
|
|
7
7
|
} from "./chunk-IBBAISSW.js";
|
|
@@ -84,6 +84,9 @@ function assertPolicy(input) {
|
|
|
84
84
|
}
|
|
85
85
|
if (typeof hb.idleMode !== "boolean") fail("heartbeat.idleMode must be boolean");
|
|
86
86
|
if (typeof hb.archiveRotatedHome !== "boolean") fail("heartbeat.archiveRotatedHome must be boolean");
|
|
87
|
+
if (hb.intervalJitterPct !== void 0 && (typeof hb.intervalJitterPct !== "number" || hb.intervalJitterPct < 0 || hb.intervalJitterPct > 50)) {
|
|
88
|
+
fail("heartbeat.intervalJitterPct must be a number in [0, 50]");
|
|
89
|
+
}
|
|
87
90
|
const g = p.gate;
|
|
88
91
|
if (!isPlainObject(g)) fail("gate missing");
|
|
89
92
|
if (typeof g.maxDailySend !== "number" || g.maxDailySend < 0) fail("gate.maxDailySend must be >= 0");
|
|
@@ -394,4 +397,4 @@ export {
|
|
|
394
397
|
describeInstall,
|
|
395
398
|
presetStatus
|
|
396
399
|
};
|
|
397
|
-
//# sourceMappingURL=chunk-
|
|
400
|
+
//# sourceMappingURL=chunk-HE6IF6OU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/path-guard.ts","../src/config/schema.ts","../src/config/load.ts","../src/excerpt/excerpt.ts","../src/core/preset-install.ts"],"sourcesContent":["// Path whitelist guard (requirement 8 / design doc §10.2).\n//\n// Every fs write/delete must have its target canonicalized first, then be\n// checked against the canonical workspace prefix with a separator boundary.\n// A raw startsWith check is bypassable via \"..\", symlinks/junctions, and\n// case variants; canonical realpath closes all of those on Windows.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport class PathOutsideWorkspaceError extends Error {\n constructor(target: string, workspace: string) {\n super(`path outside workspace: \"${target}\" (workspace: \"${workspace}\")`);\n this.name = 'PathOutsideWorkspaceError';\n }\n}\n\n/**\n * Resolve to an absolute canonical path. For targets that do not exist yet,\n * realpath the deepest existing ancestor and re-append the virtual tail, so\n * planned files under the workspace validate while `..` escapes still resolve\n * through the real filesystem.\n */\nexport function canonicalize(target: string): string {\n const abs = path.resolve(target);\n try {\n return fs.realpathSync(abs);\n } catch {\n // Walk up from the missing leaf, recording each missing component, until\n // an existing ancestor is found; re-append the missing tail afterwards.\n const tail: string[] = [];\n let dir = abs;\n for (;;) {\n const base = path.basename(dir);\n const parent = path.dirname(dir);\n if (parent === dir) {\n throw new Error(`cannot canonicalize \"${target}\": no existing ancestor`);\n }\n tail.push(base);\n dir = parent;\n try {\n const realDir = fs.realpathSync(dir);\n return path.join(realDir, ...tail.reverse());\n } catch {\n continue;\n }\n }\n }\n}\n\n/**\n * True when `targetCanon` equals the workspace dir or lies under it.\n * Comparison is case-insensitive (Windows filesystems) and requires a\n * separator boundary so `D:\\ws-data-evil` does not match workspace `D:\\ws-data`.\n */\nexport function isInsideWorkspace(workspaceCanon: string, targetCanon: string): boolean {\n const norm = (p: string) => {\n let n = path.normalize(p).toLowerCase();\n if (!n.endsWith(path.sep)) n += path.sep;\n return n;\n };\n const w = norm(workspaceCanon);\n const t = norm(targetCanon);\n return t === w || t.startsWith(w);\n}\n\nexport interface PathGuard {\n /** Canonical workspace boundary. */\n readonly workspace: string;\n /** Canonicalize then validate; returns the canonical path or throws. */\n assert(target: string): string;\n /** Canonicalize then validate; returns null instead of throwing. */\n check(target: string): string | null;\n}\n\nexport function createPathGuard(workspaceDir: string): PathGuard {\n const workspace = canonicalize(workspaceDir);\n const guard: PathGuard = {\n workspace,\n check(target: string): string | null {\n const canon = canonicalize(target);\n return isInsideWorkspace(workspace, canon) ? canon : null;\n },\n assert(target: string): string {\n const canon = guard.check(target);\n if (canon === null) throw new PathOutsideWorkspaceError(target, workspace);\n return canon;\n },\n };\n return guard;\n}\n","// Policy shape + runtime validation. Factory defaults live in config/policy.json\n// (read-only); the user layer in data/settings/policy.json overrides via deep\n// merge (design doc §13, D3).\n\nexport interface QuietHours {\n start: string; // \"HH:MM\"\n end: string; // \"HH:MM\"\n}\n\nexport interface BrowseWindow {\n start: string;\n end: string;\n}\n\nexport interface Policy {\n heartbeat: {\n intervalMin: number;\n idleMode: boolean;\n archiveRotatedHome: boolean;\n /** v2.1.0 interval jitter: each hop draws interval × (1 + u), u uniform in\n * [-p, +p] with p = this/100. Range [0, 50]. OPTIONAL in the type so\n * pre-existing policy layers still validate; when absent the runtime\n * applies the factory default ±20 (clampJitterPct in the orchestrator). */\n intervalJitterPct?: number;\n };\n gate: {\n maxDailySend: number;\n cooldownMinutes: number;\n quietHours: QuietHours;\n };\n browse: {\n windows: BrowseWindow[];\n minIntervalHours: number;\n maxSeedsPerVisit: number;\n };\n seeds: {\n maxActive: number;\n ttlDays: { news: number; fandom: number; scene: number; promise: number };\n coldBenchDays: number;\n /** Archive-area cap (v1.9.0): gc trims archived seeds beyond this, oldest first. */\n archiveCap: number;\n retireAfterUsed: number;\n scoreWeights: { freshness: number; unused: number; confidence: number };\n };\n profile: {\n consolidation: { minIntervalHours: number; inboxBacklog: number };\n partitionCap: number;\n maxOpsPerRun: number;\n confidenceCap: { chat: number; screen: number; browse: number };\n volatileDays: number;\n stableLowActivityDays: number;\n psyEnabled: boolean;\n };\n /** Observation depth (v1.8.0): how much of each user message enters the inbox. */\n observe: { maxChars: number; perBeat: number };\n weekly: {\n enabled: boolean;\n /** v2.0 (item 5): how many past reports the store keeps and the card lists. */\n keepReports: number;\n };\n retention: { envPulseHours: number; decisionLogDays: number };\n}\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction fail(msg: string): never {\n throw new Error(`policy: ${msg}`);\n}\n\nexport function assertPolicy(input: unknown): asserts input is Policy {\n if (!isPlainObject(input)) fail('root must be an object');\n const p = input;\n const hb = p.heartbeat;\n if (!isPlainObject(hb)) fail('heartbeat missing');\n if (typeof hb.intervalMin !== 'number' || hb.intervalMin < 1 || hb.intervalMin > 1440) {\n fail('heartbeat.intervalMin must be a number in [1, 1440]');\n }\n if (typeof hb.idleMode !== 'boolean') fail('heartbeat.idleMode must be boolean');\n if (typeof hb.archiveRotatedHome !== 'boolean') fail('heartbeat.archiveRotatedHome must be boolean');\n // v2.1.0: optional — pre-existing policy layers (and hand-built literals in\n // tests) predate it; the runtime default lives in the orchestrator.\n if (hb.intervalJitterPct !== undefined\n && (typeof hb.intervalJitterPct !== 'number' || hb.intervalJitterPct < 0 || hb.intervalJitterPct > 50)) {\n fail('heartbeat.intervalJitterPct must be a number in [0, 50]');\n }\n const g = p.gate;\n if (!isPlainObject(g)) fail('gate missing');\n if (typeof g.maxDailySend !== 'number' || g.maxDailySend < 0) fail('gate.maxDailySend must be >= 0');\n if (typeof g.cooldownMinutes !== 'number' || g.cooldownMinutes < 0) fail('gate.cooldownMinutes must be >= 0');\n const qh = g.quietHours;\n if (!isPlainObject(qh)) fail('gate.quietHours missing');\n if (typeof qh.start !== 'string' || !HHMM.test(qh.start) || typeof qh.end !== 'string' || !HHMM.test(qh.end)) {\n fail('gate.quietHours must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n const b = p.browse;\n if (!isPlainObject(b)) fail('browse missing');\n if (!Array.isArray(b.windows) || b.windows.length === 0) fail('browse.windows must be a non-empty array');\n for (const w of b.windows) {\n if (!isPlainObject(w)) fail('browse.windows entries must be objects');\n if (typeof w.start !== 'string' || !HHMM.test(w.start) || typeof w.end !== 'string' || !HHMM.test(w.end)) {\n fail('browse.windows entries must be {start:\"HH:MM\", end:\"HH:MM\"}');\n }\n }\n if (typeof b.minIntervalHours !== 'number' || b.minIntervalHours <= 0) fail('browse.minIntervalHours must be > 0');\n if (typeof b.maxSeedsPerVisit !== 'number' || b.maxSeedsPerVisit < 1) fail('browse.maxSeedsPerVisit must be >= 1');\n const s = p.seeds;\n if (!isPlainObject(s)) fail('seeds missing');\n if (typeof s.maxActive !== 'number' || s.maxActive < 1) fail('seeds.maxActive must be >= 1');\n if (!isPlainObject(s.ttlDays)) fail('seeds.ttlDays missing');\n for (const k of ['news', 'fandom', 'scene', 'promise'] as const) {\n if (typeof s.ttlDays[k] !== 'number') fail(`seeds.ttlDays.${k} missing`);\n }\n if (typeof s.coldBenchDays !== 'number') fail('seeds.coldBenchDays missing');\n if (typeof s.archiveCap !== 'number' || s.archiveCap < 1) fail('seeds.archiveCap must be >= 1');\n if (typeof s.retireAfterUsed !== 'number' || s.retireAfterUsed < 1) fail('seeds.retireAfterUsed must be >= 1');\n if (!isPlainObject(s.scoreWeights)) fail('seeds.scoreWeights missing');\n const pr = p.profile;\n if (!isPlainObject(pr)) fail('profile missing');\n const c = pr.consolidation;\n if (!isPlainObject(c)) fail('profile.consolidation missing');\n if (typeof c.minIntervalHours !== 'number' || typeof c.inboxBacklog !== 'number') fail('profile.consolidation fields missing');\n if (typeof pr.partitionCap !== 'number' || pr.partitionCap < 1) fail('profile.partitionCap must be >= 1');\n if (typeof pr.maxOpsPerRun !== 'number' || pr.maxOpsPerRun < 1) fail('profile.maxOpsPerRun must be >= 1');\n const cc = pr.confidenceCap;\n if (!isPlainObject(cc)) fail('profile.confidenceCap missing');\n if (typeof cc.chat !== 'number' || typeof cc.screen !== 'number' || typeof cc.browse !== 'number') {\n fail('profile.confidenceCap fields missing');\n }\n if (typeof pr.volatileDays !== 'number' || pr.volatileDays < 1) fail('profile.volatileDays must be >= 1');\n if (typeof pr.stableLowActivityDays !== 'number' || pr.stableLowActivityDays < 1) fail('profile.stableLowActivityDays must be >= 1');\n if (typeof pr.psyEnabled !== 'boolean') fail('profile.psyEnabled must be boolean');\n const ob = p.observe;\n if (!isPlainObject(ob)) fail('observe missing');\n if (typeof ob.maxChars !== 'number' || ob.maxChars < 20 || ob.maxChars > 2000) fail('observe.maxChars must be in [20, 2000]');\n if (typeof ob.perBeat !== 'number' || ob.perBeat < 1 || ob.perBeat > 100) fail('observe.perBeat must be in [1, 100]');\n if (!isPlainObject(p.weekly)) fail('weekly missing');\n if (typeof p.weekly.enabled !== 'boolean') fail('weekly.enabled must be boolean');\n if (typeof p.weekly.keepReports !== 'number' || p.weekly.keepReports < 1 || p.weekly.keepReports > 52) {\n fail('weekly.keepReports must be a number in [1, 52]');\n }\n const r = p.retention;\n if (!isPlainObject(r)) fail('retention missing');\n if (typeof r.envPulseHours !== 'number' || typeof r.decisionLogDays !== 'number') fail('retention fields missing');\n}\n\n/** Recursive merge: user values win; objects merge, arrays and scalars replace. */\nexport function deepMerge<T>(base: T, override: unknown): T {\n if (!isPlainObject(base) || !isPlainObject(override)) {\n return (override === undefined ? base : (override as T));\n }\n const out: Record<string, unknown> = { ...base };\n for (const [k, v] of Object.entries(override)) {\n out[k] = v === undefined ? (base as Record<string, unknown>)[k] : deepMerge((base as Record<string, unknown>)[k], v);\n }\n return out as T;\n}","// Two-layer policy loading (D3): factory defaults (config/policy.json, read-only)\n// + user layer (data/settings/policy.json). Missing user layer is normal; an\n// invalid factory file or user layer is fail-closed (throw at startup).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { assertPolicy, deepMerge, type Policy } from './schema.js';\nimport { atomicWriteFileSync } from '../core/atomic-fs.js';\n\nexport const USER_POLICY_FILE = 'policy.json';\n\nexport function loadPolicy(guard: PathGuard, configDir: string, settingsDir: string): Policy {\n const factoryPath = path.join(configDir, 'policy.json');\n let factoryRaw: unknown;\n try {\n factoryRaw = JSON.parse(fs.readFileSync(factoryPath, 'utf8'));\n } catch (e) {\n throw new Error(`factory policy unreadable at ${factoryPath}: ${String(e)}`);\n }\n assertPolicy(factoryRaw);\n\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let merged: Policy = factoryRaw;\n if (fs.existsSync(userPath)) {\n try {\n const userRaw: unknown = JSON.parse(fs.readFileSync(userPath, 'utf8'));\n merged = deepMerge(factoryRaw, userRaw);\n } catch (e) {\n throw new Error(`user policy layer unparseable at ${userPath}: ${String(e)}`);\n }\n }\n assertPolicy(merged);\n return merged;\n}\n\n/**\n * Merge `patch` into the user policy layer (data/settings/policy.json) without\n * touching the factory file. Used by the settings card for policy-backed\n * toggles (psyEnabled, v1.7.0). No full-Policy validation here: the layer is\n * merged over the factory and validated together at the next loadPolicy.\n */\nexport function updateUserPolicy(guard: PathGuard, settingsDir: string, patch: Record<string, unknown>): Record<string, unknown> {\n const userPath = guard.assert(path.join(settingsDir, USER_POLICY_FILE));\n let user: Record<string, unknown> = {};\n try {\n user = JSON.parse(fs.readFileSync(userPath, 'utf8')) as Record<string, unknown>;\n if (!user || typeof user !== 'object' || Array.isArray(user)) user = {};\n } catch {\n user = {}; // fresh layer\n }\n const merged = deepMerge(user, patch) as Record<string, unknown>;\n fs.mkdirSync(path.dirname(userPath), { recursive: true });\n atomicWriteFileSync(userPath, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n","// Excerpt book (\"摘抄本\") - the place for lines worth keeping.\n//\n// Deliberately plaintext Markdown, like the ledger: a notebook that cannot be\n// read is not a notebook. The two plaintext files in data/ are the ledger\n// (his todos) and this one (her clippings); everything private stays in KHBV2\n// containers. The user may edit it by hand, so the parser is tolerant:\n// unrecognised lines are preserved verbatim on rewrite.\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { readText, writeText } from '../vault/vault.js';\n\nexport interface ExcerptEntry {\n id: string;\n date: string; // \"YYYY-MM-DD\"\n time: string; // \"HH:MM\"\n text: string;\n}\n\n/** Used both as the read fallback and as the file the settings card opens, so\n * a fresh notebook already carries the two lines that explain it. */\nexport const EXCERPT_HEADER = '# 摘抄本\\n\\n> 留句子和小事的地方。可以直接手编,改乱了也不影响:认不出的行会原样留着。\\n\\n';\n\nexport function excerptFilePath(dataDir: string): string {\n return path.join(dataDir, 'excerpts.md');\n}\n\nconst LINE_RE = /^- \\[(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2})\\]\\[#([0-9a-f]{6})\\] (.*)$/;\n\nfunction renderEntry(e: ExcerptEntry): string {\n return `- [${e.date} ${e.time}][#${e.id}] ${e.text}`;\n}\n\nexport function readExcerpts(guard: PathGuard, file: string): { entries: ExcerptEntry[]; rawLines: string[] } {\n const raw = readText(guard, file, EXCERPT_HEADER);\n const rawLines: string[] = [];\n const entries: ExcerptEntry[] = [];\n for (const line of raw.split('\\n')) {\n const m = LINE_RE.exec(line);\n if (m) entries.push({ date: m[1]!, time: m[2]!, id: m[3]!, text: m[4]! });\n rawLines.push(line);\n }\n return { entries, rawLines };\n}\n\n/** Append one clipping, stamped with the local wall clock (like the ledger). */\nexport function appendExcerpt(guard: PathGuard, file: string, text: string, now = Date.now()): ExcerptEntry {\n const trimmed = text.trim();\n if (!trimmed) throw new Error('excerpt must not be empty');\n const d = new Date(now);\n const pad = (n: number) => String(n).padStart(2, '0');\n const entry: ExcerptEntry = {\n id: randomUUID().slice(0, 6),\n date: `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`,\n time: `${pad(d.getHours())}:${pad(d.getMinutes())}`,\n text: trimmed.replace(/\\r?\\n/g, ' '),\n };\n const { rawLines } = readExcerpts(guard, file);\n rawLines.push(renderEntry(entry));\n writeText(guard, file, rawLines.join('\\n').replace(/\\n*$/, '\\n'));\n return entry;\n}\n\n/** Tear one page out by id (preferred) or unique text substring. Unlike the\n * ledger there is no done-state: a clipping either stays or is gone. */\nexport function removeExcerpt(guard: PathGuard, file: string, key: string): ExcerptEntry | null {\n const { rawLines, entries } = readExcerpts(guard, file);\n const target = entries.find((e) => e.id === key || e.text.includes(key));\n if (!target) return null;\n const out = rawLines.filter((line) => !line.startsWith(`- [${target.date} ${target.time}][#${target.id}] `));\n writeText(guard, file, out.join('\\n').replace(/\\n*$/, '\\n'));\n return target;\n}\n\n/** The tail of the notebook, oldest-first among the newest `limit` entries. */\nexport function recentExcerpts(guard: PathGuard, file: string, limit: number): ExcerptEntry[] {\n const { entries } = readExcerpts(guard, file);\n return limit > 0 ? entries.slice(-limit) : [];\n}\n","// Bundled agent-preset installation (contract C13).\n//\n// Why this exists: the heartbeat agent is created by the host `agents` service,\n// which does NOT go through the session-start preset picker. A bare agent joins\n// no preset, and dsh-agent-presets states the consequence verbatim — \"its tools,\n// prompt sections, and skill catalog resolve against the empty global layer\" —\n// so it cannot even see `web_search`. The preset is therefore not optional, and\n// asking the operator to hand-copy two YAML files was the most error-prone step\n// of setup. The plugin now materialises its own bundled template in the roster's\n// USER root on first run.\n//\n// Two properties keep that safe:\n// 1. An existing preset is NEVER overwritten — the composition file belongs to\n// whoever edited it. Only a missing (or ghost) directory is filled in.\n// 2. The target comes from the roster's OWN roots (`agentPresets.roots`,\n// trust === \"user\") rather than a guessed `~/.dsh`, so `$DSH_HOME` and a\n// configured home are honoured without re-deriving them here.\n//\n// Timing: dsh-agent-presets re-scans the filesystem on every read\n// (`list()` -> `discoverPresets` -> `scanRoot`, no cache), so a directory\n// created here is visible to the very next `mount()` — no restart in between.\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport const COMPOSITION_FILE = 'agent.cordis.yml';\nexport const METADATA_FILE = 'preset.yml';\n/** The template this package ships, in `assets/presets/<id>/`. */\nexport const BUNDLED_PRESET_ID = 'heartbeat';\n\n/** One entry of the roster's root list (`AgentPresets.roots`). */\nexport interface PresetRootLike {\n path?: string;\n trust?: string;\n}\n\nexport type PresetInstallAction =\n | 'exists'\n | 'created'\n | 'repaired'\n | 'restored'\n | 'skipped-disabled'\n | 'skipped-custom-id'\n | 'skipped-no-root'\n | 'error';\n\nexport interface PresetInstallResult {\n action: PresetInstallAction;\n id: string;\n /** Where the preset lives (or would live). */\n dir?: string;\n /** Where the bundled template was read from. */\n bundledDir?: string;\n detail?: string;\n}\n\n/**\n * Locate the bundled template directory by walking up from a module URL.\n * Works from both entry points (`dist/index.js` and `dist/cli/index.js`) and\n * from the pnpm copy of an installed package.\n */\nexport function bundledPresetDir(\n moduleUrl: string,\n id: string = BUNDLED_PRESET_ID,\n): string | undefined {\n let dir: string;\n try {\n dir = path.dirname(fileURLToPath(moduleUrl));\n } catch {\n return undefined;\n }\n for (let depth = 0; depth < 5; depth += 1) {\n const candidate = path.join(dir, 'assets', 'presets', id);\n if (fs.existsSync(path.join(candidate, COMPOSITION_FILE))) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/** The roster's user-trust root, which is where locally authored presets live. */\nexport function userPresetRoot(roots?: readonly PresetRootLike[]): string | undefined {\n const found = roots?.find(\n (root) => root?.trust === 'user' && typeof root.path === 'string' && root.path.length > 0,\n );\n return found?.path === undefined ? undefined : path.resolve(found.path);\n}\n\n/**\n * `<dshHome>/.agent-presets` derived from the documented precedence\n * (`$DSH_HOME`, then `~/.dsh`). Only used where no roster is available — the\n * plugin itself prefers {@link userPresetRoot}.\n */\nexport function conventionalUserPresetRoot(\n env: NodeJS.ProcessEnv = process.env,\n home: string = os.homedir(),\n): string {\n const override = env.DSH_HOME?.trim();\n const root = override && override.length > 0 ? override : path.join(home, '.dsh');\n return path.join(root, '.agent-presets');\n}\n\nexport interface InstallPresetOptions {\n /** `import.meta.url` of the calling entry point. */\n moduleUrl: string;\n /** Preset id the heartbeat agent will join (config `agentPreset`). */\n id?: string;\n /** User-trust root reported by the roster. */\n root?: string;\n /** True when the roster answered — then an absent user root is a fact, not a guess. */\n rosterKnown?: boolean;\n /** `false` disables the install (config `installPreset`). */\n enabled?: boolean;\n /** Overwrite an existing composition file with the bundled one. */\n force?: boolean;\n}\n\n/**\n * Materialise the bundled preset in the roster's user root when it is absent.\n * Never destructive: an existing composition file is kept unless `force`.\n */\nexport function installBundledPreset(options: InstallPresetOptions): PresetInstallResult {\n const id = options.id && options.id.length > 0 ? options.id : BUNDLED_PRESET_ID;\n if (options.enabled === false) {\n return { action: 'skipped-disabled', id, detail: 'installPreset=false' };\n }\n const bundledDir = bundledPresetDir(options.moduleUrl, BUNDLED_PRESET_ID);\n if (id !== BUNDLED_PRESET_ID) {\n return {\n action: 'skipped-custom-id',\n id,\n ...(bundledDir === undefined ? {} : { bundledDir }),\n detail: `only \"${BUNDLED_PRESET_ID}\" ships with the plugin; \"${id}\" is yours to provide`,\n };\n }\n if (bundledDir === undefined) {\n return {\n action: 'error',\n id,\n detail: 'bundled template not found next to the plugin (assets/presets/heartbeat)',\n };\n }\n const root =\n options.root ?? (options.rosterKnown ? undefined : conventionalUserPresetRoot());\n if (root === undefined) {\n return {\n action: 'skipped-no-root',\n id,\n bundledDir,\n detail: 'the roster mounts no user preset root (includeUserRoot=false)',\n };\n }\n const dir = path.join(root, id);\n const composition = path.join(dir, COMPOSITION_FILE);\n try {\n if (fs.existsSync(composition)) {\n if (options.force !== true) {\n const drifted = !sameBytes(composition, path.join(bundledDir, COMPOSITION_FILE));\n return {\n action: 'exists',\n id,\n dir,\n bundledDir,\n detail: drifted ? 'kept as-is (differs from the bundled template)' : 'kept as-is',\n };\n }\n fs.copyFileSync(path.join(bundledDir, COMPOSITION_FILE), composition);\n return {\n action: 'restored',\n id,\n dir,\n bundledDir,\n detail: 'composition replaced from the bundled template',\n };\n }\n const existed = fs.existsSync(dir);\n fs.mkdirSync(dir, { recursive: true });\n fs.copyFileSync(path.join(bundledDir, COMPOSITION_FILE), composition);\n const metadata = path.join(dir, METADATA_FILE);\n // A directory with a composition but no metadata is legal; only fill a void.\n if (!fs.existsSync(metadata)) fs.copyFileSync(path.join(bundledDir, METADATA_FILE), metadata);\n return {\n action: existed ? 'repaired' : 'created',\n id,\n dir,\n bundledDir,\n detail: existed\n ? 'directory existed without a composition file (it occupied the id as a broken row)'\n : undefined,\n };\n } catch (error) {\n return { action: 'error', id, dir, bundledDir, detail: String(error).slice(0, 200) };\n }\n}\n\n/** One line suitable for the audit log and `ctx.logger`. */\nexport function describeInstall(result: PresetInstallResult): string {\n const where = result.dir === undefined ? '' : ` (${result.dir})`;\n const why = result.detail === undefined ? '' : ` — ${result.detail}`;\n return `preset ${result.id} ${result.action}${where}${why}`;\n}\n\nexport interface PresetStatus {\n id: string;\n dir: string;\n bundledDir?: string;\n installed: boolean;\n compositionMatches: boolean;\n metadataMatches: boolean;\n}\n\n/** Read-only inspection for the CLI (`preset status`). */\nexport function presetStatus(\n moduleUrl: string,\n id: string = BUNDLED_PRESET_ID,\n root: string = conventionalUserPresetRoot(),\n): PresetStatus {\n const dir = path.join(root, id);\n const bundledDir = bundledPresetDir(moduleUrl, id);\n const installed = fs.existsSync(path.join(dir, COMPOSITION_FILE));\n return {\n id,\n dir,\n ...(bundledDir === undefined ? {} : { bundledDir }),\n installed,\n compositionMatches:\n installed && bundledDir !== undefined && sameBytes(path.join(dir, COMPOSITION_FILE), path.join(bundledDir, COMPOSITION_FILE)),\n metadataMatches:\n bundledDir !== undefined &&\n fs.existsSync(path.join(dir, METADATA_FILE)) &&\n sameBytes(path.join(dir, METADATA_FILE), path.join(bundledDir, METADATA_FILE)),\n };\n}\n\nfunction sameBytes(left: string, right: string): boolean {\n try {\n return fs.readFileSync(left).equals(fs.readFileSync(right));\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;AAOA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEV,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,YAAY,QAAgB,WAAmB;AAC7C,UAAM,4BAA4B,MAAM,kBAAkB,SAAS,IAAI;AACvE,SAAK,OAAO;AAAA,EACd;AACF;AAQO,SAAS,aAAa,QAAwB;AACnD,QAAM,MAAM,KAAK,QAAQ,MAAM;AAC/B,MAAI;AACF,WAAO,GAAG,aAAa,GAAG;AAAA,EAC5B,QAAQ;AAGN,UAAM,OAAiB,CAAC;AACxB,QAAI,MAAM;AACV,eAAS;AACP,YAAM,OAAO,KAAK,SAAS,GAAG;AAC9B,YAAM,SAAS,KAAK,QAAQ,GAAG;AAC/B,UAAI,WAAW,KAAK;A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MAAM,GAAG,GAAG,EAAE;AAAA,EACrF;AACF;AAGO,SAAS,gBAAgB,QAAqC;AACnE,QAAM,QAAQ,OAAO,QAAQ,SAAY,KAAK,KAAK,OAAO,GAAG;AAC7D,QAAM,MAAM,OAAO,WAAW,SAAY,KAAK,WAAM,OAAO,MAAM;AAClE,SAAO,UAAU,OAAO,EAAE,IAAI,OAAO,MAAM,GAAG,KAAK,GAAG,GAAG;AAC3D;AAYO,SAAS,aACd,WACA,KAAa,mBACb,OAAe,2BAA2B,GAC5B;AACd,QAAM,MAAMA,MAAK,KAAK,MAAM,EAAE;AAC9B,QAAM,aAAa,iBAAiB,WAAW,EAAE;AACjD,QAAM,YAAYD,IAAG,WAAWC,MAAK,KAAK,KAAK,gBAAgB,CAAC;AAChE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,GAAI,eAAe,SAAY,CAAC,IAAI,EAAE,WAAW;AAAA,IACjD;AAAA,IACA,oBACE,aAAa,eAAe,UAAa,UAAUA,MAAK,KAAK,KAAK,gBAAgB,GAAGA,MAAK,KAAK,YAAY,gBAAgB,CAAC;AAAA,IAC9H,iBACE,eAAe,UACfD,IAAG,WAAWC,MAAK,KAAK,KAAK,aAAa,CAAC,KAC3C,UAAUA,MAAK,KAAK,KAAK,aAAa,GAAGA,MAAK,KAAK,YAAY,aAAa,CAAC;AAAA,EACjF;AACF;AAEA,SAAS,UAAU,MAAc,OAAwB;AACvD,MAAI;AACF,WAAOD,IAAG,aAAa,IAAI,EAAE,OAAOA,IAAG,aAAa,KAAK,CAAC;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["fs","path","path","fs","path","path","fs","path"]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
loadEncryptedText,
|
|
3
3
|
saveEncryptedText,
|
|
4
4
|
tryWithFileLock
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-M72T5MZU.js";
|
|
6
6
|
|
|
7
7
|
// src/profile/inbox.ts
|
|
8
8
|
import fs from "fs";
|
|
@@ -140,4 +140,4 @@ export {
|
|
|
140
140
|
inboxHealthCheck,
|
|
141
141
|
inboxFileExists
|
|
142
142
|
};
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
143
|
+
//# sourceMappingURL=chunk-KZLVR4J7.js.map
|
|
@@ -3,10 +3,10 @@ import {
|
|
|
3
3
|
loadPool,
|
|
4
4
|
normalizeCategory,
|
|
5
5
|
seedsFilePath
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-63E5OYSI.js";
|
|
7
7
|
import {
|
|
8
8
|
appendAuditLine
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-ECXYNTEV.js";
|
|
10
10
|
import {
|
|
11
11
|
loadEncryptedText,
|
|
12
12
|
loadJson,
|
|
@@ -15,11 +15,38 @@ import {
|
|
|
15
15
|
saveJson,
|
|
16
16
|
workspace,
|
|
17
17
|
writeText
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-M72T5MZU.js";
|
|
19
19
|
import {
|
|
20
20
|
atomicWriteJsonSync
|
|
21
21
|
} from "./chunk-IBBAISSW.js";
|
|
22
22
|
|
|
23
|
+
// src/core/time-window.ts
|
|
24
|
+
var HH_MM = /^(\d{1,2}):(\d{2})$/;
|
|
25
|
+
function parseHhMm(text) {
|
|
26
|
+
const m = HH_MM.exec(String(text).trim());
|
|
27
|
+
if (!m) return null;
|
|
28
|
+
const h = Number(m[1]);
|
|
29
|
+
const min = Number(m[2]);
|
|
30
|
+
if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;
|
|
31
|
+
return h * 60 + min;
|
|
32
|
+
}
|
|
33
|
+
function minutesOfDay(now) {
|
|
34
|
+
return now.getHours() * 60 + now.getMinutes();
|
|
35
|
+
}
|
|
36
|
+
function inHhMmWindow(start, end, mins) {
|
|
37
|
+
const s = parseHhMm(start);
|
|
38
|
+
const e = parseHhMm(end);
|
|
39
|
+
if (s === null || e === null) return false;
|
|
40
|
+
if (s === e) return false;
|
|
41
|
+
return s > e ? mins >= s || mins < e : mins >= s && mins < e;
|
|
42
|
+
}
|
|
43
|
+
function localDayKey(d = /* @__PURE__ */ new Date()) {
|
|
44
|
+
const y = d.getFullYear();
|
|
45
|
+
const m = String(d.getMonth() + 1).padStart(2, "0");
|
|
46
|
+
const day = String(d.getDate()).padStart(2, "0");
|
|
47
|
+
return `${y}-${m}-${day}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
23
50
|
// src/ledger/ledger.ts
|
|
24
51
|
import path from "path";
|
|
25
52
|
import { randomUUID } from "crypto";
|
|
@@ -27,7 +54,7 @@ var DAY_MS = 864e5;
|
|
|
27
54
|
function ledgerFilePath(dataDir) {
|
|
28
55
|
return path.join(dataDir, "ledger.md");
|
|
29
56
|
}
|
|
30
|
-
var LINE_RE = /^- \[(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})\]\[(open|done)\]\[#([
|
|
57
|
+
var LINE_RE = /^- \[(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})\]\[(open|done)\]\[#([^\]\s]+)\] (.*)$/;
|
|
31
58
|
function renderEntry(e) {
|
|
32
59
|
return `- [${e.date} ${e.time}][${e.status}][#${e.id}] ${e.text}`;
|
|
33
60
|
}
|
|
@@ -83,7 +110,7 @@ function scanPending(guard, file, now = Date.now()) {
|
|
|
83
110
|
return entries.filter((e) => e.status === "open").sort((a, b) => a.date < b.date ? -1 : 1);
|
|
84
111
|
}
|
|
85
112
|
function pendingOlderThan(guard, file, days, now = Date.now()) {
|
|
86
|
-
const cutoff = new Date(now - days * DAY_MS)
|
|
113
|
+
const cutoff = localDayKey(new Date(now - days * DAY_MS));
|
|
87
114
|
return scanPending(guard, file, now).filter((e) => e.date <= cutoff);
|
|
88
115
|
}
|
|
89
116
|
|
|
@@ -167,29 +194,6 @@ function preferenceWeight(state, topic, now) {
|
|
|
167
194
|
// src/browse/browse.ts
|
|
168
195
|
import fs from "fs";
|
|
169
196
|
import path3 from "path";
|
|
170
|
-
|
|
171
|
-
// src/core/time-window.ts
|
|
172
|
-
var HH_MM = /^(\d{1,2}):(\d{2})$/;
|
|
173
|
-
function parseHhMm(text) {
|
|
174
|
-
const m = HH_MM.exec(String(text).trim());
|
|
175
|
-
if (!m) return null;
|
|
176
|
-
const h = Number(m[1]);
|
|
177
|
-
const min = Number(m[2]);
|
|
178
|
-
if (!Number.isFinite(h) || !Number.isFinite(min) || h > 23 || min > 59) return null;
|
|
179
|
-
return h * 60 + min;
|
|
180
|
-
}
|
|
181
|
-
function minutesOfDay(now) {
|
|
182
|
-
return now.getHours() * 60 + now.getMinutes();
|
|
183
|
-
}
|
|
184
|
-
function inHhMmWindow(start, end, mins) {
|
|
185
|
-
const s = parseHhMm(start);
|
|
186
|
-
const e = parseHhMm(end);
|
|
187
|
-
if (s === null || e === null) return false;
|
|
188
|
-
if (s === e) return false;
|
|
189
|
-
return s > e ? mins >= s || mins < e : mins >= s && mins < e;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// src/browse/browse.ts
|
|
193
197
|
function emptyBrowseState() {
|
|
194
198
|
return { wander: { focusHistory: {}, focusCount: {}, last_wander_at: 0, refillCount: {}, sessionCount: {} } };
|
|
195
199
|
}
|
|
@@ -326,12 +330,6 @@ function completeWander(guard, paths, focus, now = Date.now(), opts = {}) {
|
|
|
326
330
|
saveJson(guard, browseStatePath(paths), state);
|
|
327
331
|
return { focus, count: state.wander.focusCount[focus], ...refillsToday === void 0 ? {} : { refillsToday } };
|
|
328
332
|
}
|
|
329
|
-
function localDayKey(d) {
|
|
330
|
-
const y = d.getFullYear();
|
|
331
|
-
const m = String(d.getMonth() + 1).padStart(2, "0");
|
|
332
|
-
const day = String(d.getDate()).padStart(2, "0");
|
|
333
|
-
return `${y}-${m}-${day}`;
|
|
334
|
-
}
|
|
335
333
|
var REFILL_TOPIC_THRESHOLD = 4;
|
|
336
334
|
var REFILL_MAX_PER_DAY = 2;
|
|
337
335
|
function adviseRefillWander(guard, paths, policy, now = /* @__PURE__ */ new Date()) {
|
|
@@ -363,6 +361,9 @@ import path4 from "path";
|
|
|
363
361
|
import { execFile } from "child_process";
|
|
364
362
|
function runPowerShell(args, timeoutMs, signal) {
|
|
365
363
|
if (signal?.aborted) return Promise.resolve({ status: 1, stdout: "", stderr: "aborted" });
|
|
364
|
+
if (process.platform !== "win32") {
|
|
365
|
+
return Promise.resolve({ status: 1, stdout: "", stderr: `powershell unavailable on ${process.platform}` });
|
|
366
|
+
}
|
|
366
367
|
return new Promise((resolve) => {
|
|
367
368
|
let settled = false;
|
|
368
369
|
const done = (r) => {
|
|
@@ -567,6 +568,9 @@ function renderTemplateReport(facts) {
|
|
|
567
568
|
}
|
|
568
569
|
|
|
569
570
|
export {
|
|
571
|
+
minutesOfDay,
|
|
572
|
+
inHhMmWindow,
|
|
573
|
+
localDayKey,
|
|
570
574
|
ledgerFilePath,
|
|
571
575
|
readLedger,
|
|
572
576
|
appendEntry,
|
|
@@ -575,8 +579,6 @@ export {
|
|
|
575
579
|
pendingOlderThan,
|
|
576
580
|
runPowerShell,
|
|
577
581
|
runPowerShellFile,
|
|
578
|
-
minutesOfDay,
|
|
579
|
-
inHhMmWindow,
|
|
580
582
|
preferenceFilePath,
|
|
581
583
|
recordDelivery,
|
|
582
584
|
loadInterests,
|
|
@@ -597,4 +599,4 @@ export {
|
|
|
597
599
|
buildWeeklyPrompt,
|
|
598
600
|
renderTemplateReport
|
|
599
601
|
};
|
|
600
|
-
//# sourceMappingURL=chunk-
|
|
602
|
+
//# sourceMappingURL=chunk-LPPRI53J.js.map
|