@kanadego/dsh-heartbeat 2.2.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -311
- package/USAGE-GUIDE.md +357 -0
- package/client.js +186 -24
- package/dist/{bili-login-XQVEE4M6.js → bili-login-KDDU63Z2.js} +4 -4
- package/dist/{bindings-U2M3CO2D.js → bindings-LTSGGNIH.js} +3 -3
- package/dist/{chunk-LQKOYTRL.js → chunk-4OQXAHU5.js} +2 -2
- package/dist/{chunk-3QJJRXIR.js → chunk-5CVAW5AS.js} +11 -2
- package/dist/chunk-5CVAW5AS.js.map +1 -0
- package/dist/{chunk-IBBAISSW.js → chunk-66IUDHCY.js} +50 -1
- package/dist/chunk-66IUDHCY.js.map +1 -0
- package/dist/{chunk-3DNGY4DS.js → chunk-77UYDI2A.js} +2 -2
- package/dist/{chunk-AT32XCCI.js → chunk-AJ5JAQVB.js} +20 -3
- package/dist/chunk-AJ5JAQVB.js.map +1 -0
- package/dist/chunk-CRRN6UD3.js +389 -0
- package/dist/chunk-CRRN6UD3.js.map +1 -0
- package/dist/{chunk-ECXYNTEV.js → chunk-ERRPMYKB.js} +164 -152
- package/dist/chunk-ERRPMYKB.js.map +1 -0
- package/dist/{chunk-M72T5MZU.js → chunk-GOLMRQRW.js} +3 -2
- package/dist/{chunk-KZLVR4J7.js → chunk-IPTNSXOY.js} +2 -2
- package/dist/chunk-L54R23O2.js +262 -0
- package/dist/chunk-L54R23O2.js.map +1 -0
- package/dist/chunk-MHRAPKES.js +1081 -0
- package/dist/chunk-MHRAPKES.js.map +1 -0
- package/dist/{chunk-SIY3YHFY.js → chunk-MMI6OBEC.js} +2 -2
- package/dist/{chunk-CJK6RTMH.js → chunk-RPWQZYNW.js} +1485 -310
- package/dist/chunk-RPWQZYNW.js.map +1 -0
- package/dist/cli/index.js +244 -36
- package/dist/cli/index.js.map +1 -1
- package/dist/{focus-store-RNHBAFYS.js → focus-store-XGTPIVF6.js} +3 -3
- package/dist/{inbox-ZLX2MH7A.js → inbox-7GGEMBUD.js} +4 -4
- package/dist/index.d.ts +66 -1
- package/dist/index.js +556 -167
- package/dist/index.js.map +1 -1
- package/dist/{migrate-XFZU5EBE.js → migrate-25F53XIC.js} +6 -4
- package/dist/{orchestrator-5BHYQ77Y.js → orchestrator-4PJD7QYO.js} +25 -11
- package/dist/runtime-RGZKOFP3.js +15 -0
- package/dist/snapshot-J6LKNY57.js +27 -0
- package/dist/store-HM6ZMFKS.js +45 -0
- package/package.json +6 -3
- package/dist/chunk-3QJJRXIR.js.map +0 -1
- package/dist/chunk-AT32XCCI.js.map +0 -1
- package/dist/chunk-CJK6RTMH.js.map +0 -1
- package/dist/chunk-DLOYERAK.js +0 -87
- package/dist/chunk-DLOYERAK.js.map +0 -1
- package/dist/chunk-ECXYNTEV.js.map +0 -1
- package/dist/chunk-F2XVKX55.js +0 -413
- package/dist/chunk-F2XVKX55.js.map +0 -1
- package/dist/chunk-IBBAISSW.js.map +0 -1
- package/dist/chunk-N6SMIGYJ.js +0 -393
- package/dist/chunk-N6SMIGYJ.js.map +0 -1
- package/dist/chunk-XYBII5PR.js +0 -602
- package/dist/chunk-XYBII5PR.js.map +0 -1
- package/dist/pool-76VLAZER.js +0 -49
- package/dist/runtime-W2OWJIHY.js +0 -11
- package/dist/snapshot-SU2VGM4C.js +0 -16
- /package/dist/{bili-login-XQVEE4M6.js.map → bili-login-KDDU63Z2.js.map} +0 -0
- /package/dist/{bindings-U2M3CO2D.js.map → bindings-LTSGGNIH.js.map} +0 -0
- /package/dist/{chunk-LQKOYTRL.js.map → chunk-4OQXAHU5.js.map} +0 -0
- /package/dist/{chunk-3DNGY4DS.js.map → chunk-77UYDI2A.js.map} +0 -0
- /package/dist/{chunk-M72T5MZU.js.map → chunk-GOLMRQRW.js.map} +0 -0
- /package/dist/{chunk-KZLVR4J7.js.map → chunk-IPTNSXOY.js.map} +0 -0
- /package/dist/{chunk-SIY3YHFY.js.map → chunk-MMI6OBEC.js.map} +0 -0
- /package/dist/{focus-store-RNHBAFYS.js.map → focus-store-XGTPIVF6.js.map} +0 -0
- /package/dist/{inbox-ZLX2MH7A.js.map → inbox-7GGEMBUD.js.map} +0 -0
- /package/dist/{migrate-XFZU5EBE.js.map → migrate-25F53XIC.js.map} +0 -0
- /package/dist/{orchestrator-5BHYQ77Y.js.map → orchestrator-4PJD7QYO.js.map} +0 -0
- /package/dist/{pool-76VLAZER.js.map → runtime-RGZKOFP3.js.map} +0 -0
- /package/dist/{runtime-W2OWJIHY.js.map → snapshot-J6LKNY57.js.map} +0 -0
- /package/dist/{snapshot-SU2VGM4C.js.map → store-HM6ZMFKS.js.map} +0 -0
|
@@ -4,59 +4,12 @@ import {
|
|
|
4
4
|
readText,
|
|
5
5
|
saveJson,
|
|
6
6
|
writeText
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import {
|
|
9
|
-
atomicWriteFileSync
|
|
10
|
-
} from "./chunk-IBBAISSW.js";
|
|
11
|
-
|
|
12
|
-
// src/core/audit-log.ts
|
|
13
|
-
import fs from "fs";
|
|
14
|
-
import path from "path";
|
|
15
|
-
function appendAuditLine(file, event) {
|
|
16
|
-
try {
|
|
17
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
18
|
-
const line = JSON.stringify({ ts: event.ts ?? (/* @__PURE__ */ new Date()).toISOString(), ...event });
|
|
19
|
-
fs.appendFileSync(file, line + "\n", "utf8");
|
|
20
|
-
} catch (e) {
|
|
21
|
-
process.stderr.write(`[heartbeat] audit append failed: ${file}: ${String(e)}
|
|
22
|
-
`);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
function readAuditLines(file) {
|
|
26
|
-
if (!fs.existsSync(file)) return [];
|
|
27
|
-
const out = [];
|
|
28
|
-
const raw = fs.readFileSync(file, "utf8");
|
|
29
|
-
for (const line of raw.split("\n")) {
|
|
30
|
-
const trimmed = line.trim();
|
|
31
|
-
if (!trimmed) continue;
|
|
32
|
-
try {
|
|
33
|
-
out.push(JSON.parse(trimmed));
|
|
34
|
-
} catch {
|
|
35
|
-
out.push({ ts: "", corrupt: true, raw: trimmed.slice(0, 200) });
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return out;
|
|
39
|
-
}
|
|
40
|
-
function pruneAuditFile(file, maxAgeMs, now = Date.now()) {
|
|
41
|
-
if (!fs.existsSync(file)) return 0;
|
|
42
|
-
const lines = readAuditLines(file);
|
|
43
|
-
const kept = lines.filter((e) => {
|
|
44
|
-
const ev = e;
|
|
45
|
-
const ts = Date.parse(ev.ts ?? "");
|
|
46
|
-
if (!Number.isFinite(ts)) return true;
|
|
47
|
-
return now - ts <= maxAgeMs;
|
|
48
|
-
});
|
|
49
|
-
const removed = lines.length - kept.length;
|
|
50
|
-
if (removed === 0) return 0;
|
|
51
|
-
const body = kept.map((e) => JSON.stringify(e)).join("\n");
|
|
52
|
-
atomicWriteFileSync(file, body ? body + "\n" : "");
|
|
53
|
-
return removed;
|
|
54
|
-
}
|
|
7
|
+
} from "./chunk-GOLMRQRW.js";
|
|
55
8
|
|
|
56
9
|
// src/profile/store.ts
|
|
57
|
-
import
|
|
10
|
+
import path2 from "path";
|
|
58
11
|
import { randomUUID } from "crypto";
|
|
59
|
-
import
|
|
12
|
+
import fs2 from "fs";
|
|
60
13
|
|
|
61
14
|
// src/profile/types.ts
|
|
62
15
|
var JOURNAL_VERSION = 2;
|
|
@@ -76,21 +29,21 @@ function emptyProfile() {
|
|
|
76
29
|
}
|
|
77
30
|
|
|
78
31
|
// src/profile/schema.ts
|
|
79
|
-
import
|
|
80
|
-
import
|
|
32
|
+
import fs from "fs";
|
|
33
|
+
import path from "path";
|
|
81
34
|
function loadProfileSchema(paths) {
|
|
82
|
-
const userPath =
|
|
83
|
-
const factoryPath =
|
|
35
|
+
const userPath = path.join(paths.settingsDir, "profile-schema.json");
|
|
36
|
+
const factoryPath = path.join(paths.configDir, "profile-schema.json");
|
|
84
37
|
const read = (file) => {
|
|
85
38
|
try {
|
|
86
|
-
const raw = JSON.parse(
|
|
39
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
87
40
|
if (!raw.partitions) return { error: "partitions missing" };
|
|
88
41
|
return { schema: raw, error: "" };
|
|
89
42
|
} catch (e) {
|
|
90
43
|
return { error: String(e) };
|
|
91
44
|
}
|
|
92
45
|
};
|
|
93
|
-
const user =
|
|
46
|
+
const user = fs.existsSync(userPath) ? read(userPath) : null;
|
|
94
47
|
if (user?.schema) return { schema: user.schema, source: "user" };
|
|
95
48
|
const factory = read(factoryPath);
|
|
96
49
|
if (factory.schema) {
|
|
@@ -311,75 +264,6 @@ var NoopShape = closed(
|
|
|
311
264
|
["op", "why"],
|
|
312
265
|
["op"]
|
|
313
266
|
);
|
|
314
|
-
function parseObservationRefs(value, label) {
|
|
315
|
-
if (value === void 0) return [];
|
|
316
|
-
if (!Array.isArray(value)) throw new ShapeError(`${label}: expected an array of observation ids`);
|
|
317
|
-
return value.map((v, i) => {
|
|
318
|
-
if (typeof v !== "string" || !v.trim()) {
|
|
319
|
-
throw new ShapeError(`${label}[${i}]: expected an observation id like "o1" (refs, timestamps and kinds are code-generated)`);
|
|
320
|
-
}
|
|
321
|
-
return v.trim();
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
function parseProposedOp(raw, label) {
|
|
325
|
-
if (!isPlainObject(raw)) throw new ShapeError(`${label}: expected an object, got ${describe(raw)}`);
|
|
326
|
-
const tag = raw.op;
|
|
327
|
-
if (tag === "ADD") {
|
|
328
|
-
const o = check(AddShape, raw, label);
|
|
329
|
-
const evidenceRefs = parseObservationRefs(o.evidence, `${label}.evidence`);
|
|
330
|
-
if (evidenceRefs.length === 0) {
|
|
331
|
-
throw new ShapeError(`${label}.evidence: ADD needs at least one observation id (axiom 1: no provenance, no memory)`);
|
|
332
|
-
}
|
|
333
|
-
return {
|
|
334
|
-
op: "ADD",
|
|
335
|
-
partition: o.partition,
|
|
336
|
-
topic: String(o.topic),
|
|
337
|
-
subTopic: String(o.subTopic),
|
|
338
|
-
content: String(o.content),
|
|
339
|
-
...o.temporal === void 0 ? {} : { temporal: o.temporal },
|
|
340
|
-
...o.confidence === void 0 ? {} : { confidence: Number(o.confidence) },
|
|
341
|
-
why: typeof o.why === "string" ? o.why : "",
|
|
342
|
-
evidenceRefs
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
if (tag === "UPDATE") {
|
|
346
|
-
const o = check(UpdateShape, raw, label);
|
|
347
|
-
const changes = o.changes;
|
|
348
|
-
const out = {};
|
|
349
|
-
if (changes.content !== void 0) out.content = String(changes.content);
|
|
350
|
-
if (changes.confidence !== void 0) out.confidence = Number(changes.confidence);
|
|
351
|
-
if (out.content === void 0 && out.confidence === void 0) {
|
|
352
|
-
throw new ShapeError(`${label}.changes: needs content or confidence`);
|
|
353
|
-
}
|
|
354
|
-
return { op: "UPDATE", id: String(o.id), changes: out, why: typeof o.why === "string" ? o.why : "" };
|
|
355
|
-
}
|
|
356
|
-
if (tag === "INVALIDATE") {
|
|
357
|
-
const o = check(InvalidateShape, raw, label);
|
|
358
|
-
return {
|
|
359
|
-
op: "INVALIDATE",
|
|
360
|
-
id: String(o.id),
|
|
361
|
-
why: typeof o.why === "string" ? o.why : "",
|
|
362
|
-
evidenceRefs: parseObservationRefs(o.evidence, `${label}.evidence`)
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
if (tag === "NOOP") {
|
|
366
|
-
const o = check(NoopShape, raw, label);
|
|
367
|
-
return { op: "NOOP", why: typeof o.why === "string" ? o.why : "" };
|
|
368
|
-
}
|
|
369
|
-
throw new ShapeError(`${label}.op: unknown op ${JSON.stringify(tag)}`);
|
|
370
|
-
}
|
|
371
|
-
function parseProposedOps(list) {
|
|
372
|
-
const ops = [];
|
|
373
|
-
const rejected = [];
|
|
374
|
-
list.forEach((raw, i) => {
|
|
375
|
-
try {
|
|
376
|
-
ops.push(parseProposedOp(raw, `op[${i}]`));
|
|
377
|
-
} catch (e) {
|
|
378
|
-
rejected.push({ op: raw, reason: e instanceof Error ? e.message : String(e) });
|
|
379
|
-
}
|
|
380
|
-
});
|
|
381
|
-
return { ops, rejected };
|
|
382
|
-
}
|
|
383
267
|
function materializeEvidence(refs, observations, label) {
|
|
384
268
|
const evidence = [];
|
|
385
269
|
for (const ref of refs) {
|
|
@@ -412,29 +296,52 @@ function tryParseJournalRecord(value) {
|
|
|
412
296
|
// src/profile/store.ts
|
|
413
297
|
var DAY_MS = 864e5;
|
|
414
298
|
function profileFilePath(dataDir) {
|
|
415
|
-
return
|
|
299
|
+
return path2.join(dataDir, "profile.json");
|
|
416
300
|
}
|
|
417
301
|
function journalFilePath(dataDir) {
|
|
418
|
-
return
|
|
302
|
+
return path2.join(dataDir, "profile_journal.jsonl");
|
|
419
303
|
}
|
|
420
304
|
var SNAPSHOT_FILE = "profile_snapshot.json";
|
|
421
305
|
var ARCHIVE_PREFIX = "profile_journal.archive-";
|
|
306
|
+
var SNAPSHOT_ARCHIVE_PREFIX = "profile_snapshot.";
|
|
307
|
+
var SNAPSHOT_ARCHIVE_NAME_RE = /^profile_snapshot\.\d+\.json$/;
|
|
422
308
|
function snapshotFilePath(dataDir) {
|
|
423
|
-
return
|
|
309
|
+
return path2.join(dataDir, SNAPSHOT_FILE);
|
|
424
310
|
}
|
|
425
|
-
function
|
|
426
|
-
const snap = loadJson(guard,
|
|
311
|
+
function readSnapshotFile(guard, file) {
|
|
312
|
+
const snap = loadJson(guard, file);
|
|
427
313
|
if (!snap || snap.version !== 1 || typeof snap.baselineTs !== "string" || !snap.doc?.partitions) return null;
|
|
428
314
|
return snap;
|
|
429
315
|
}
|
|
316
|
+
function loadSnapshot(guard, dataDir) {
|
|
317
|
+
return readSnapshotFile(guard, snapshotFilePath(dataDir));
|
|
318
|
+
}
|
|
319
|
+
function listSnapshots(guard, dataDir) {
|
|
320
|
+
const refs = [];
|
|
321
|
+
const canonical = loadSnapshot(guard, dataDir);
|
|
322
|
+
if (canonical) {
|
|
323
|
+
refs.push({ baselineTs: Date.parse(canonical.baselineTs) || 0, path: snapshotFilePath(dataDir) });
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
for (const f of fs2.readdirSync(guard.assert(dataDir))) {
|
|
327
|
+
if (!SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;
|
|
328
|
+
const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -".json".length));
|
|
329
|
+
if (!Number.isFinite(ms)) continue;
|
|
330
|
+
refs.push({ baselineTs: ms, path: path2.join(dataDir, f) });
|
|
331
|
+
}
|
|
332
|
+
} catch {
|
|
333
|
+
}
|
|
334
|
+
refs.sort((a, b) => a.baselineTs - b.baselineTs);
|
|
335
|
+
return refs;
|
|
336
|
+
}
|
|
430
337
|
function listArchiveFiles(guard, dataDir) {
|
|
431
338
|
try {
|
|
432
|
-
return
|
|
339
|
+
return fs2.readdirSync(guard.assert(dataDir)).filter((f) => f.startsWith(ARCHIVE_PREFIX) && f.endsWith(".jsonl")).sort();
|
|
433
340
|
} catch {
|
|
434
341
|
return [];
|
|
435
342
|
}
|
|
436
343
|
}
|
|
437
|
-
function replayText(doc, text, baselineTs, stats) {
|
|
344
|
+
function replayText(doc, text, baselineTs, stats, untilTs) {
|
|
438
345
|
const lines = text.split("\n");
|
|
439
346
|
for (let i = 0; i < lines.length; i++) {
|
|
440
347
|
const trimmed = lines[i].trim();
|
|
@@ -459,6 +366,10 @@ function replayText(doc, text, baselineTs, stats) {
|
|
|
459
366
|
continue;
|
|
460
367
|
}
|
|
461
368
|
if (baselineTs && rec.ts && String(rec.ts) <= baselineTs) continue;
|
|
369
|
+
if (untilTs !== void 0 && rec.ts) {
|
|
370
|
+
const t = Date.parse(String(rec.ts));
|
|
371
|
+
if (Number.isFinite(t) && t > untilTs) continue;
|
|
372
|
+
}
|
|
462
373
|
try {
|
|
463
374
|
if (rec.v === JOURNAL_VERSION && rec.entries) {
|
|
464
375
|
for (const entry of rec.entries) upsertEntry(doc, entry);
|
|
@@ -496,26 +407,35 @@ function upsertEntry(doc, entry) {
|
|
|
496
407
|
}
|
|
497
408
|
bucketFor(doc, next.partition).entries.push(next);
|
|
498
409
|
}
|
|
499
|
-
function
|
|
500
|
-
const
|
|
410
|
+
function basepointFor(guard, dataDir, untilTs) {
|
|
411
|
+
const refs = listSnapshots(guard, dataDir);
|
|
412
|
+
for (let i = refs.length - 1; i >= 0; i--) {
|
|
413
|
+
const snap = readSnapshotFile(guard, refs[i].path);
|
|
414
|
+
if (snap && Date.parse(snap.baselineTs) <= untilTs) return snap;
|
|
415
|
+
}
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
function replayJournal(guard, dataDir, opts = {}) {
|
|
419
|
+
const untilTs = opts.untilTs;
|
|
420
|
+
const snap = untilTs === void 0 ? loadSnapshot(guard, dataDir) : basepointFor(guard, dataDir, untilTs);
|
|
501
421
|
const doc = snap ? snap.doc : emptyProfile();
|
|
502
422
|
const baselineTs = snap?.baselineTs ?? "";
|
|
503
423
|
const stats = { records: snap?.recordsFolded ?? 0, truncatedTail: 0, badRecords: 0, isLive: false };
|
|
504
424
|
for (const file of listArchiveFiles(guard, dataDir)) {
|
|
505
425
|
try {
|
|
506
|
-
replayText(doc,
|
|
426
|
+
replayText(doc, fs2.readFileSync(path2.join(dataDir, file), "utf8"), baselineTs, { records: 0, truncatedTail: 0, badRecords: 0, isLive: false }, untilTs);
|
|
507
427
|
} catch {
|
|
508
428
|
}
|
|
509
429
|
}
|
|
510
430
|
stats.isLive = true;
|
|
511
|
-
replayText(doc, readText(guard, journalFilePath(dataDir), ""), baselineTs, stats);
|
|
431
|
+
replayText(doc, readText(guard, journalFilePath(dataDir), ""), baselineTs, stats, untilTs);
|
|
512
432
|
return { doc, truncatedTail: stats.truncatedTail, records: stats.records, badRecords: stats.badRecords };
|
|
513
433
|
}
|
|
514
434
|
function readJournalTexts(guard, dataDir) {
|
|
515
435
|
const texts = [];
|
|
516
436
|
for (const file of listArchiveFiles(guard, dataDir)) {
|
|
517
437
|
try {
|
|
518
|
-
texts.push(
|
|
438
|
+
texts.push(fs2.readFileSync(path2.join(dataDir, file), "utf8"));
|
|
519
439
|
} catch {
|
|
520
440
|
}
|
|
521
441
|
}
|
|
@@ -537,9 +457,9 @@ function parseIso(v) {
|
|
|
537
457
|
function refExists(guard, dataDir, ref) {
|
|
538
458
|
const base = ref.split("#")[0] ?? "";
|
|
539
459
|
if (!base) return false;
|
|
540
|
-
const target =
|
|
460
|
+
const target = path2.join(dataDir, base);
|
|
541
461
|
try {
|
|
542
|
-
return
|
|
462
|
+
return fs2.existsSync(guard.assert(target));
|
|
543
463
|
} catch {
|
|
544
464
|
return false;
|
|
545
465
|
}
|
|
@@ -705,10 +625,10 @@ function persistWithJournal(guard, dataDir, doc, record) {
|
|
|
705
625
|
const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record, v });
|
|
706
626
|
const journal = journalFilePath(dataDir);
|
|
707
627
|
try {
|
|
708
|
-
|
|
628
|
+
fs2.appendFileSync(guard.assert(journal), line + "\n", "utf8");
|
|
709
629
|
} catch {
|
|
710
|
-
|
|
711
|
-
|
|
630
|
+
fs2.mkdirSync(dataDir, { recursive: true });
|
|
631
|
+
fs2.appendFileSync(guard.assert(journal), line + "\n", "utf8");
|
|
712
632
|
}
|
|
713
633
|
}
|
|
714
634
|
function applyOpPermissive(doc, op, ts) {
|
|
@@ -790,25 +710,114 @@ function rebuildProfile(guard, dataDir, opts = {}) {
|
|
|
790
710
|
if (replayed.truncatedTail > 0) {
|
|
791
711
|
writeText(
|
|
792
712
|
guard,
|
|
793
|
-
|
|
713
|
+
path2.join(dataDir, "logs", "rebuild-report.txt"),
|
|
794
714
|
`rebuild truncated ${replayed.truncatedTail} torn line(s) at journal tail; ${replayed.records} records applied
|
|
795
715
|
`
|
|
796
716
|
);
|
|
797
717
|
}
|
|
798
718
|
return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records, wrote: true };
|
|
799
719
|
}
|
|
720
|
+
var isNoDiff = (d) => d.added === 0 && d.removed === 0 && d.changed === 0;
|
|
721
|
+
function diffAgainstDisk(nowDoc, atDoc) {
|
|
722
|
+
const nowIds = /* @__PURE__ */ new Map();
|
|
723
|
+
const atIds = /* @__PURE__ */ new Map();
|
|
724
|
+
for (const p of PARTITIONS) {
|
|
725
|
+
for (const e of nowDoc.partitions[p].entries) nowIds.set(e.id, e.content);
|
|
726
|
+
for (const e of atDoc.partitions[p].entries) atIds.set(e.id, e.content);
|
|
727
|
+
}
|
|
728
|
+
let added = 0;
|
|
729
|
+
let removed = 0;
|
|
730
|
+
let changed = 0;
|
|
731
|
+
for (const [id, content] of nowIds) {
|
|
732
|
+
if (!atIds.has(id)) added += 1;
|
|
733
|
+
else if (atIds.get(id) !== content) changed += 1;
|
|
734
|
+
}
|
|
735
|
+
for (const id of atIds.keys()) {
|
|
736
|
+
if (!nowIds.has(id)) removed += 1;
|
|
737
|
+
}
|
|
738
|
+
return { entriesNow: nowIds.size, entriesAt: atIds.size, added, removed, changed };
|
|
739
|
+
}
|
|
740
|
+
function maxRecordTsAtMost(guard, dataDir, bound) {
|
|
741
|
+
let max = 0;
|
|
742
|
+
for (const text of readJournalTexts(guard, dataDir)) {
|
|
743
|
+
for (const line of text.split("\n")) {
|
|
744
|
+
const s = line.trim();
|
|
745
|
+
if (!s) continue;
|
|
746
|
+
let ts = "";
|
|
747
|
+
try {
|
|
748
|
+
ts = String(JSON.parse(s).ts ?? "");
|
|
749
|
+
} catch {
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
if (!ts) continue;
|
|
753
|
+
const t = Date.parse(ts);
|
|
754
|
+
if (Number.isFinite(t) && t <= bound && t > max) max = t;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return max;
|
|
758
|
+
}
|
|
759
|
+
function restoreAt(guard, dataDir, iso, opts = {}) {
|
|
760
|
+
const tMs = Date.parse(iso);
|
|
761
|
+
if (!Number.isFinite(tMs)) throw new Error(`restore: invalid ISO timestamp: ${iso}`);
|
|
762
|
+
const newest = maxRecordTsAtMost(guard, dataDir, Number.MAX_SAFE_INTEGER);
|
|
763
|
+
const toNow = newest > 0 && tMs >= newest;
|
|
764
|
+
const disk = loadProfile(guard, profileFilePath(dataDir));
|
|
765
|
+
let target;
|
|
766
|
+
let diff;
|
|
767
|
+
if (toNow) {
|
|
768
|
+
target = replayJournal(guard, dataDir, { untilTs: newest }).doc;
|
|
769
|
+
diff = diffAgainstDisk(disk, target);
|
|
770
|
+
if (isNoDiff(diff)) {
|
|
771
|
+
return { restoredTo: newest, backupPath: "", wrote: false, toNow, diff };
|
|
772
|
+
}
|
|
773
|
+
} else {
|
|
774
|
+
target = replayJournal(guard, dataDir, { untilTs: tMs }).doc;
|
|
775
|
+
diff = diffAgainstDisk(disk, target);
|
|
776
|
+
}
|
|
777
|
+
const report = {
|
|
778
|
+
restoredTo: maxRecordTsAtMost(guard, dataDir, tMs),
|
|
779
|
+
backupPath: "",
|
|
780
|
+
wrote: false,
|
|
781
|
+
toNow,
|
|
782
|
+
diff
|
|
783
|
+
};
|
|
784
|
+
if (opts.dryRun) return report;
|
|
785
|
+
const profileAbs = profileFilePath(dataDir);
|
|
786
|
+
let backupPath = "";
|
|
787
|
+
if (fs2.existsSync(guard.assert(profileAbs))) {
|
|
788
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
789
|
+
let candidate = path2.join(dataDir, `profile.json.before-restore-${stamp}`);
|
|
790
|
+
let n = 1;
|
|
791
|
+
while (fs2.existsSync(guard.assert(candidate))) {
|
|
792
|
+
candidate = path2.join(dataDir, `profile.json.before-restore-${stamp}-${n}`);
|
|
793
|
+
n += 1;
|
|
794
|
+
}
|
|
795
|
+
writeText(guard, candidate, fs2.readFileSync(guard.assert(profileAbs), "utf8"));
|
|
796
|
+
backupPath = candidate;
|
|
797
|
+
}
|
|
798
|
+
saveJson(guard, profileAbs, target);
|
|
799
|
+
report.backupPath = backupPath;
|
|
800
|
+
report.wrote = true;
|
|
801
|
+
return report;
|
|
802
|
+
}
|
|
800
803
|
var WIPE_FILES = ["profile.json", "profile_inbox.jsonl", "profile_journal.jsonl", SNAPSHOT_FILE];
|
|
801
804
|
var WIPE_PATTERNS = [
|
|
802
805
|
/^profile_journal\.archive-/,
|
|
806
|
+
// v2.4.0: the dated snapshot archives (profile/snapshot.ts) are restore
|
|
807
|
+
// basepoints — a wipe that left them behind let `profile restore` regrow the
|
|
808
|
+
// memory (the HB-21 hole, second time around). Same for the pre-restore
|
|
809
|
+
// backups restoreAt writes. Keep in sync with SNAPSHOT_ARCHIVE_NAME_RE above.
|
|
810
|
+
/^profile_snapshot\.\d+\.json$/,
|
|
811
|
+
/^profile\.json\.before-restore-\d{14}(-\d+)?$/,
|
|
803
812
|
/\.bak-migrate-\d{14}$/,
|
|
804
813
|
/\.incoming-\d{14}$/
|
|
805
814
|
];
|
|
806
815
|
function wipeProfile(guard, dataDir) {
|
|
807
816
|
const removed = [];
|
|
808
817
|
for (const f of WIPE_FILES) {
|
|
809
|
-
const abs = guard.assert(
|
|
810
|
-
if (
|
|
811
|
-
|
|
818
|
+
const abs = guard.assert(path2.join(dataDir, f));
|
|
819
|
+
if (fs2.existsSync(abs)) {
|
|
820
|
+
fs2.rmSync(abs, { force: true });
|
|
812
821
|
removed.push(f);
|
|
813
822
|
}
|
|
814
823
|
}
|
|
@@ -821,7 +830,7 @@ function wipeProfile(guard, dataDir) {
|
|
|
821
830
|
}
|
|
822
831
|
for (const rel of rels) {
|
|
823
832
|
try {
|
|
824
|
-
|
|
833
|
+
fs2.rmSync(guard.assert(path2.join(dataDir, rel)), { force: true });
|
|
825
834
|
removed.push(rel);
|
|
826
835
|
} catch {
|
|
827
836
|
}
|
|
@@ -831,16 +840,18 @@ function wipeProfile(guard, dataDir) {
|
|
|
831
840
|
}
|
|
832
841
|
|
|
833
842
|
export {
|
|
834
|
-
|
|
835
|
-
readAuditLines,
|
|
836
|
-
pruneAuditFile,
|
|
843
|
+
PARTITIONS,
|
|
837
844
|
loadProfileSchema,
|
|
838
|
-
parseProposedOps,
|
|
839
845
|
materializeEvidence,
|
|
840
846
|
profileFilePath,
|
|
841
847
|
journalFilePath,
|
|
848
|
+
SNAPSHOT_FILE,
|
|
842
849
|
ARCHIVE_PREFIX,
|
|
850
|
+
SNAPSHOT_ARCHIVE_PREFIX,
|
|
851
|
+
SNAPSHOT_ARCHIVE_NAME_RE,
|
|
843
852
|
snapshotFilePath,
|
|
853
|
+
readSnapshotFile,
|
|
854
|
+
listSnapshots,
|
|
844
855
|
replayJournal,
|
|
845
856
|
readJournalTexts,
|
|
846
857
|
loadProfile,
|
|
@@ -849,6 +860,7 @@ export {
|
|
|
849
860
|
persistWithJournal,
|
|
850
861
|
verifyProfile,
|
|
851
862
|
rebuildProfile,
|
|
863
|
+
restoreAt,
|
|
852
864
|
wipeProfile
|
|
853
865
|
};
|
|
854
|
-
//# sourceMappingURL=chunk-
|
|
866
|
+
//# sourceMappingURL=chunk-ERRPMYKB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/profile/store.ts","../src/profile/types.ts","../src/profile/schema.ts","../src/profile/shapes.ts"],"sourcesContent":["// Profile store: materialized view + journal (the journal is the ONLY\n// authority; profile.json is a pure projection - r2 §14 verify/rebuild).\n// Every LLM-proposed op passes deterministic guards here (LLM nominates,\n// code decides - §3.3).\n\nimport path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { loadJson, saveJson, readText, writeText } from '../vault/vault.js';\nimport type { Policy } from '../config/schema.js';\nimport {\n CONFIDENCE_CAP,\n emptyProfile,\n JOURNAL_VERSION,\n PARTITIONS,\n type ApplyReport,\n type Evidence,\n type EvidenceKind,\n type InboxItem,\n type JournalRecord,\n type Partition,\n type ProfileDoc,\n type ProfileEntry,\n type ProfileOp,\n} from './types.js';\nimport { checkAddAgainstSchema, type ProfileSchema } from './schema.js';\nimport { tryParseJournalRecord } from './shapes.js';\nimport { matchFilesRecursive } from '../core/fs-walk.js';\n\nconst DAY_MS = 86_400_000;\n\nexport function profileFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile.json');\n}\n\nexport function journalFilePath(dataDir: string): string {\n return path.join(dataDir, 'profile_journal.jsonl');\n}\n\n// ── snapshot basepoint (v1.8.0, design doc §14 ③) ─────────────────────────\n// The journal grows forever; the snapshot folds its history into one DPAPI\n// document and moves the folded records into a timestamped archive shard.\n// Replay order: snapshot → archives (name order) → live journal, skipping\n// records at or before the snapshot baseline — so verify/rebuild stay correct\n// without knowing whether a snapshot exists.\n\nexport const SNAPSHOT_FILE = 'profile_snapshot.json';\nexport const ARCHIVE_PREFIX = 'profile_journal.archive-';\n\n// ── snapshot versioning (v2.4.0, dev plan §二3) ────────────────────────────\n// Each fold now also keeps a dated archive `profile_snapshot.<baselineTs>.json`\n// (epoch-ms name, written by profile/snapshot.ts) so restore points survive\n// later folds. Defined here because store owns the snapshot format; re-exported\n// by profile/snapshot.ts for the vault layers (burn/migrate). MUST stay in sync\n// with the name snapshot.ts writes.\nexport const SNAPSHOT_ARCHIVE_PREFIX = 'profile_snapshot.';\nexport const SNAPSHOT_ARCHIVE_NAME_RE = /^profile_snapshot\\.\\d+\\.json$/;\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\n/** Load + validate a snapshot document (canonical or dated archive). Null when\n * absent or malformed — every caller treats that as \"no snapshot\". */\nexport function readSnapshotFile(guard: PathGuard, file: string): ProfileSnapshot | null {\n const snap = loadJson<ProfileSnapshot>(guard, file);\n if (!snap || snap.version !== 1 || typeof snap.baselineTs !== 'string' || !snap.doc?.partitions) return null;\n return snap;\n}\n\nfunction loadSnapshot(guard: PathGuard, dataDir: string): ProfileSnapshot | null {\n return readSnapshotFile(guard, snapshotFilePath(dataDir));\n}\n\n/** Every restore point on disk: the canonical snapshot plus the dated archive\n * copies, ascending by baseline (v2.4.0 restore). Archives are listed by name\n * (the epoch-ms is the filename — content is only decrypted when actually\n * used as a basepoint). Ties sort the archive before the canonical file; same\n * state either way. */\nexport interface SnapshotRef {\n /** Snapshot baseline as epoch ms. */\n baselineTs: number;\n /** Absolute path of the snapshot file. */\n path: string;\n}\n\nexport function listSnapshots(guard: PathGuard, dataDir: string): SnapshotRef[] {\n const refs: SnapshotRef[] = [];\n const canonical = loadSnapshot(guard, dataDir);\n if (canonical) {\n refs.push({ baselineTs: Date.parse(canonical.baselineTs) || 0, path: snapshotFilePath(dataDir) });\n }\n try {\n for (const f of fs.readdirSync(guard.assert(dataDir))) {\n if (!SNAPSHOT_ARCHIVE_NAME_RE.test(f)) continue;\n const ms = Number(f.slice(SNAPSHOT_ARCHIVE_PREFIX.length, -'.json'.length));\n if (!Number.isFinite(ms)) continue;\n refs.push({ baselineTs: ms, path: path.join(dataDir, f) });\n }\n } catch { /* no dataDir listing: no archives */ }\n refs.sort((a, b) => a.baselineTs - b.baselineTs);\n return refs;\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.\n * `untilTs` (v2.4.0 restore) additionally drops records NEWER than the bound —\n * undefined keeps the historical behaviour byte-for-byte. */\nfunction replayText(\n doc: ProfileDoc,\n text: string,\n baselineTs: string,\n stats: { records: number; truncatedTail: number; badRecords: number; isLive: boolean },\n untilTs?: number,\n): void {\n const lines = text.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n // A torn tail only counts on the LIVE journal — archives are closed files.\n const tornTail = (): boolean => {\n const isLast = lines.slice(i + 1).every((l) => !l.trim());\n if (stats.isLive && isLast) {\n stats.truncatedTail = lines.length - i;\n return true;\n }\n return false;\n };\n let rec: JournalRecord | null = null;\n try {\n rec = tryParseJournalRecord(JSON.parse(trimmed));\n } catch {\n rec = null;\n }\n if (!rec) {\n if (tornTail()) break;\n // mid-file unreadable record: count it and keep going (the journal is\n // append-only/immutable, so a bad line is never rewritten).\n stats.badRecords += 1;\n continue;\n }\n // Baseline skip: only records CARRYING a ts can be proven folded. A\n // ts-less record is always applied (applyOpPermissive tolerates it).\n if (baselineTs && rec.ts && String(rec.ts) <= baselineTs) continue;\n // untilTs bound: a record with a usable ts beyond the restore target is not\n // part of the as-of state. Ts-less records stay applied — same policy as\n // the baseline skip above.\n if (untilTs !== undefined && rec.ts) {\n const t = Date.parse(String(rec.ts));\n if (Number.isFinite(t) && t > untilTs) continue;\n }\n try {\n if (rec.v === JOURNAL_VERSION && rec.entries) {\n // v2 (③A): the record carries each touched entry's FULL final state,\n // so replay is an upsert; live and replay share one state machine (HB-09).\n for (const entry of rec.entries) upsertEntry(doc, entry);\n } else {\n for (const op of rec.applied ?? []) applyOpPermissive(doc, op, rec.ts);\n }\n stats.records += 1;\n } catch {\n stats.badRecords += 1;\n }\n }\n}\n\nfunction bucketFor(doc: ProfileDoc, partition: Partition): { entries: ProfileEntry[] } {\n let bucket = doc.partitions[partition];\n if (!bucket) {\n bucket = { entries: [] };\n doc.partitions[partition] = bucket;\n }\n return bucket;\n}\n\n/** Journal v2 replay: `entry` is the entry's final state, so replay is an\n * upsert by id (position preserved for updates, appended for new entries). */\nfunction upsertEntry(doc: ProfileDoc, entry: ProfileEntry): void {\n const next = structuredClone(entry);\n for (const p of PARTITIONS) {\n const list = doc.partitions[p]?.entries;\n if (!list) continue;\n const at = list.findIndex((e) => e.id === next.id);\n if (at < 0) continue;\n if (p === next.partition) {\n list[at] = next;\n } else {\n list.splice(at, 1);\n bucketFor(doc, next.partition).entries.push(next);\n }\n return;\n }\n bucketFor(doc, next.partition).entries.push(next);\n}\n\nexport interface ReplayOptions {\n /** Upper time bound (epoch ms): only records with `ts <= untilTs` are\n * applied. Omit for the historical full replay — the result is unchanged. */\n untilTs?: number;\n}\n\n/** Latest snapshot whose baseline is at or before `untilTs` (content-validated,\n * newest first). Null when none qualifies or none parses. */\nfunction basepointFor(guard: PathGuard, dataDir: string, untilTs: number): ProfileSnapshot | null {\n const refs = listSnapshots(guard, dataDir);\n for (let i = refs.length - 1; i >= 0; i--) {\n const snap = readSnapshotFile(guard, refs[i]!.path);\n if (snap && Date.parse(snap.baselineTs) <= untilTs) return snap;\n }\n return null;\n}\n\n/** Full replay: snapshot basepoint + archive shards + live journal. With\n * `opts.untilTs` (v2.4.0 restore) it is an as-of replay: the basepoint is the\n * latest snapshot at or before the bound, and only records `ts <= untilTs`\n * are applied on top. */\nexport function replayJournal(guard: PathGuard, dataDir: string, opts: ReplayOptions = {}): ReplayResult {\n const untilTs = opts.untilTs;\n const snap = untilTs === undefined ? loadSnapshot(guard, dataDir) : basepointFor(guard, dataDir, untilTs);\n const doc = snap ? snap.doc : emptyProfile();\n const baselineTs = snap?.baselineTs ?? '';\n const stats = { records: snap?.recordsFolded ?? 0, truncatedTail: 0, badRecords: 0, isLive: false };\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n // shard record counts are not reported (the snapshot already folded\n // them); only the live journal's torn tail is meaningful.\n replayText(doc, fs.readFileSync(path.join(dataDir, file), 'utf8'), baselineTs, { records: 0, truncatedTail: 0, badRecords: 0, isLive: false }, untilTs);\n } catch { /* unreadable shard: skip */ }\n }\n stats.isLive = true;\n replayText(doc, readText(guard, journalFilePath(dataDir), ''), baselineTs, stats, untilTs);\n return { doc, truncatedTail: stats.truncatedTail, records: stats.records, badRecords: stats.badRecords };\n}\n\n/** Every plaintext journal text in chronological order: archive shards first,\n * then the live journal — the RAW record timeline, for callers that need the\n * history itself rather than the accumulated doc (the weekly report counts\n * the week's ADD ops). A rotation must not hide history from them (H-01). */\nexport function readJournalTexts(guard: PathGuard, dataDir: string): string[] {\n const texts: string[] = [];\n for (const file of listArchiveFiles(guard, dataDir)) {\n try {\n texts.push(fs.readFileSync(path.join(dataDir, file), 'utf8'));\n } catch { /* unreadable shard: skip */ }\n }\n texts.push(readText(guard, journalFilePath(dataDir), ''));\n return texts;\n}\n\nexport function loadProfile(guard: PathGuard, file: string): ProfileDoc {\n const doc = loadJson<ProfileDoc>(guard, file);\n if (!doc || !doc.partitions) return emptyProfile();\n // ensure all partitions exist\n for (const p of PARTITIONS) {\n if (!doc.partitions[p]) doc.partitions[p] = { entries: [] };\n }\n return doc;\n}\n\nfunction parseIso(v: string): number {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** ref format \"<datafile>#<locator>\": the referenced file must exist under data/. */\nfunction refExists(guard: PathGuard, dataDir: string, ref: string): boolean {\n const base = ref.split('#')[0] ?? '';\n if (!base) return false;\n const target = path.join(dataDir, base);\n try {\n return fs.existsSync(guard.assert(target));\n } catch {\n return false;\n }\n}\n\nfunction capForKinds(kinds: EvidenceKind[]): number {\n if (kinds.length === 0) return 0.4;\n return Math.min(...kinds.map((k) => CONFIDENCE_CAP[k] ?? 0.4));\n}\n\nfunction findActive(doc: ProfileDoc, id: string): ProfileEntry | undefined {\n for (const p of PARTITIONS) {\n const hit = doc.partitions[p]!.entries.find((e) => e.id === id && e.validTo === null);\n if (hit) return hit;\n }\n return undefined;\n}\n\n/**\n * Apply validated ops to the doc (mutates). Returns applied/rejected.\n * Guards (§3.3): whitelist, evidence gate, per-run ops cap is enforced by the\n * caller, confidence caps by evidence kind, psy gating, INVALIDATE ownership:\n * volatile expiry is code-driven (LLM may not), stable invalidation needs a\n * contradicting observation attached.\n */\nexport function applyOpsToDoc(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n ops: ProfileOp[],\n schema: ProfileSchema | undefined,\n policy: Policy,\n now: number,\n): ApplyReport {\n const applied: ProfileOp[] = [];\n const rejected: { op: ProfileOp; reason: string }[] = [];\n // Journal v2 events: one FULL snapshot per touched entry (HB-09).\n const entries: ProfileEntry[] = [];\n const nowIso = new Date(now).toISOString();\n\n for (const op of ops) {\n if (op.op === 'NOOP') {\n applied.push(op);\n continue;\n }\n if (op.op === 'ADD') {\n if (op.partition === 'psy' && !policy.profile.psyEnabled) {\n rejected.push({ op, reason: 'psy partition is disabled' });\n continue;\n }\n let temporal: 'stable' | 'volatile' = 'stable';\n if (schema) {\n const check = checkAddAgainstSchema(schema, op.partition, op.topic, op.subTopic, op.temporal);\n if (!check.ok) {\n rejected.push({ op, reason: check.reason! });\n continue;\n }\n temporal = check.temporal;\n } else if (!(op.partition in doc.partitions)) {\n // H-17: no usable schema — the partition set is the only boundary left.\n rejected.push({ op, reason: `unknown partition: ${op.partition}` });\n continue;\n } else {\n temporal = op.temporal === 'volatile' ? 'volatile' : 'stable';\n }\n if (!op.evidence || op.evidence.length === 0) {\n rejected.push({ op, reason: 'ADD without evidence (no provenance, axiom 1)' });\n continue;\n }\n const badRef = op.evidence.find((e) => !refExists(guard, dataDir, e.ref));\n if (badRef) {\n rejected.push({ op, reason: `evidence ref does not resolve: ${badRef.ref}` });\n continue;\n }\n const cap = capForKinds(op.evidence.map((e) => e.kind));\n const active = doc.partitions[op.partition]!.entries.filter((e) => e.validTo === null);\n if (active.length >= policy.profile.partitionCap) {\n rejected.push({ op, reason: `partition ${op.partition} at cap (${policy.profile.partitionCap}); converge first` });\n continue;\n }\n dbSeq += 1;\n const entry: ProfileEntry = {\n id: `p${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content.trim(),\n confidence: Math.min(op.confidence ?? cap, cap),\n temporal,\n validFrom: nowIso,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: nowIso,\n updatedAt: nowIso,\n updateCount: 0,\n };\n op.assignedId = entry.id; // journal replay must reproduce this id\n doc.partitions[op.partition]!.entries.push(entry);\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n if (op.op === 'UPDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n // HB-04 (2026-10-17): validate BEFORE mutating. The old order wrote\n // `content` first and then bailed out on the confidence rule, so an\n // UPDATE that was reported as REJECTED had already changed the text.\n let nextConfidence: number | null = null;\n if (op.changes.confidence !== undefined) {\n const cap = capForKinds(entry.evidence.map((e) => e.kind));\n // confidence upgrades need a second confirming observation (§3.3):\n // only allowed up to cap, and only when the entry already has 2+ evidence\n if (op.changes.confidence > entry.confidence && entry.evidence.length < 2) {\n rejected.push({ op, reason: 'confidence upgrade requires a second confirming observation' });\n continue;\n }\n nextConfidence = Math.min(op.changes.confidence, cap);\n }\n if (op.changes.content !== undefined) entry.content = op.changes.content.trim();\n if (nextConfidence !== null) entry.confidence = nextConfidence;\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n if (op.op === 'INVALIDATE') {\n const entry = findActive(doc, op.id);\n if (!entry) {\n rejected.push({ op, reason: `unknown or inactive entry: ${op.id}` });\n continue;\n }\n if (entry.temporal === 'volatile') {\n rejected.push({ op, reason: 'volatile expiry is code-owned (time-driven), not LLM-nominated' });\n continue;\n }\n // stable: rebuttal-driven; requires a contradicting observation attached\n const hasNewObservation = (op.evidence ?? []).length > 0\n && (op.evidence ?? []).some((e) => parseIso(e.at) > parseIso(entry.evidence[entry.evidence.length - 1]?.at ?? ''));\n if (!hasNewObservation) {\n rejected.push({ op, reason: 'stable INVALIDATE requires a newer contradicting observation' });\n continue;\n }\n entry.validTo = nowIso;\n entry.supersededBy = null;\n entry.updatedAt = nowIso;\n entry.updateCount += 1;\n if (op.evidence) entry.evidence.push(...op.evidence);\n entries.push(structuredClone(entry));\n applied.push(op);\n continue;\n }\n }\n return { applied, rejected, entries };\n}\n\nlet dbSeq = 0;\n\n/** Deterministic aging (D9): volatile expiry + stable low-activity marking. */\nexport function runDeterministicAging(\n doc: ProfileDoc,\n policy: Policy,\n now: number,\n): { volatileExpired: number; lowActivityMarked: number; entries: ProfileEntry[] } {\n const nowIso = new Date(now).toISOString();\n const entries: ProfileEntry[] = [];\n let volatileExpired = 0;\n let lowActivityMarked = 0;\n for (const p of PARTITIONS) {\n for (const e of doc.partitions[p]!.entries) {\n if (e.validTo !== null) continue;\n const lastEvidence = Math.max(...e.evidence.map((x) => parseIso(x.at)), parseIso(e.updatedAt));\n if (e.temporal === 'volatile') {\n if (now - lastEvidence > policy.profile.volatileDays * DAY_MS) {\n e.validTo = nowIso;\n e.updatedAt = nowIso;\n e.updateCount += 1;\n volatileExpired += 1;\n entries.push(structuredClone(e));\n }\n } else if (!e.lowActivity && now - lastEvidence > policy.profile.stableLowActivityDays * DAY_MS) {\n e.lowActivity = true;\n lowActivityMarked += 1;\n entries.push(structuredClone(e));\n }\n }\n }\n return { volatileExpired, lowActivityMarked, entries };\n}\n\n/** Persist the materialized view atomically + append the journal record.\n * A record carrying `entries` (every touched entry's final state) is written\n * as v2 so replay is an upsert; a record without them stays v1 and replays\n * permissively, so old journals keep working unchanged. */\nexport function persistWithJournal(\n guard: PathGuard,\n dataDir: string,\n doc: ProfileDoc,\n record: Omit<JournalRecord, 'ts'>,\n): void {\n saveJson(guard, profileFilePath(dataDir), doc);\n const v = record.entries === undefined ? undefined : JOURNAL_VERSION;\n const line = JSON.stringify({ ts: new Date().toISOString(), ...record, v });\n const journal = journalFilePath(dataDir);\n try {\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n } catch {\n fs.mkdirSync(dataDir, { recursive: true });\n fs.appendFileSync(guard.assert(journal), line + '\\n', 'utf8');\n }\n}\n\n// ── journal replay (verify / rebuild, r2 §14) ───────────────────────────\n\nfunction applyOpPermissive(doc: ProfileDoc, op: ProfileOp, ts: string): void {\n // Journal is trusted history: replay applies without revalidation.\n if (op.op === 'ADD') {\n dbSeq += 1;\n doc.partitions[op.partition]!.entries.push({\n id: op.assignedId ?? `r${dbSeq.toString(36)}${randomUUID().slice(0, 4)}`,\n partition: op.partition,\n topic: op.topic,\n subTopic: op.subTopic,\n content: op.content,\n confidence: op.confidence ?? 0.5,\n temporal: op.temporal ?? 'stable',\n validFrom: ts,\n validTo: null,\n supersededBy: null,\n evidence: op.evidence,\n createdAt: ts,\n updatedAt: ts,\n updateCount: 0,\n });\n return;\n }\n if (op.op === 'UPDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n if (op.changes.content !== undefined) e.content = op.changes.content;\n if (op.changes.confidence !== undefined) e.confidence = op.changes.confidence;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n return;\n }\n if (op.op === 'INVALIDATE') {\n const e = [...PARTITIONS].flatMap((p) => doc.partitions[p]!.entries).find((x) => x.id === op.id);\n if (e) {\n e.validTo = ts;\n e.updatedAt = ts;\n e.updateCount += 1;\n }\n }\n // NOOP: nothing\n}\n\nexport interface ReplayResult {\n doc: ProfileDoc;\n truncatedTail: number;\n records: number;\n /** Journal lines that neither parsed nor replayed (counted, never fatal). */\n badRecords?: number;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n firstDivergence?: { id: string; expected: string; actual: string };\n truncatedTail: number;\n records: number;\n}\n\n/** profile verify: replay vs disk, report first divergence, never fix. */\nexport function verifyProfile(guard: PathGuard, dataDir: string): VerifyReport {\n const replayed = replayJournal(guard, dataDir);\n const onDisk = loadProfile(guard, profileFilePath(dataDir));\n // Timestamps legitimately differ (journal record ts >= op ts); identity\n // fields are also normalized. Compare semantic content only.\n const strip = (doc: ProfileDoc): string =>\n JSON.stringify(doc.partitions, (k, v) => (['id', 'supersededBy', 'validFrom', 'createdAt', 'updatedAt', 'retiredAt'].includes(k) ? '<norm>' : v));\n const ok = strip(replayed.doc) === strip(onDisk);\n if (ok) return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records };\n // first divergence: first entry id present in only one view\n const diskIds = new Set([...PARTITIONS].flatMap((p) => onDisk.partitions[p]!.entries.map((e) => e.content))); const replayIds = new Set([...PARTITIONS].flatMap((p) => replayed.doc.partitions[p]!.entries.map((e) => e.content)));\n const onlyDisk = [...diskIds].find((c) => !replayIds.has(c));\n const onlyReplay = [...replayIds].find((c) => !diskIds.has(c));\n return {\n ok: false,\n firstDivergence: {\n id: onlyDisk ?? onlyReplay ?? '(content)',\n expected: onlyReplay ? 'absent in journal replay' : 'present in journal replay',\n actual: onlyDisk ? 'present on disk' : 'absent on disk',\n },\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n };\n}\n\nexport interface RebuildReport {\n ok: boolean;\n truncatedTail: number;\n records: number;\n wrote: boolean;\n}\n\n/** profile rebuild: journal is authoritative; atomic replace; torn tail reported. */\nexport function rebuildProfile(\n guard: PathGuard,\n dataDir: string,\n opts: { check?: boolean } = {},\n): RebuildReport & { diffSummary?: string } {\n const replayed = replayJournal(guard, dataDir);\n const target = profileFilePath(dataDir);\n if (opts.check) {\n const onDisk = loadProfile(guard, target);\n const same = JSON.stringify(onDisk) === JSON.stringify(replayed.doc);\n return {\n ok: same,\n truncatedTail: replayed.truncatedTail,\n records: replayed.records,\n wrote: false,\n diffSummary: same ? 'no diff' : 'materialized view differs from journal replay',\n };\n }\n saveJson(guard, target, replayed.doc);\n if (replayed.truncatedTail > 0) {\n // explicit audit: never silently rebuild a view that lost its tail\n writeText(\n guard,\n path.join(dataDir, 'logs', 'rebuild-report.txt'),\n `rebuild truncated ${replayed.truncatedTail} torn line(s) at journal tail; ${replayed.records} records applied\\n`,\n );\n }\n return { ok: true, truncatedTail: replayed.truncatedTail, records: replayed.records, wrote: true };\n}\n\n// ── point-in-time restore (v2.4.0, dev plan §二3 / §四9-11) ────────────────\n// The journal already IS the version chain: every record carries each touched\n// entry's full final state, and each fold leaves a dated snapshot behind. So a\n// restore is just a replay with an upper time bound over the newest basepoint\n// at or before the target — no change-log layer, no new interpreter (the same\n// replayText/upsert machinery does the work).\n//\n// The journal stays the authority: a restore rewrites only the materialized\n// view (profile.json), never the journal — so `profile verify` will report a\n// divergence afterwards until the next rebuild back to now. That is the\n// feature, not a bug: profile.json holds the as-of state, the journal still\n// holds everything.\n\nexport interface RestoreDiff {\n entriesNow: number;\n entriesAt: number;\n /** ids on disk now but absent at the target instant. */\n added: number;\n /** ids at the target instant but absent now (forgotten since). */\n removed: number;\n /** present in both but content differs. */\n changed: number;\n}\n\nexport interface RestoreReport {\n restoredTo: number;\n /** Absolute path of the pre-restore backup; '' when none was written\n * (dry-run, genuine no-op, or no profile.json yet). */\n backupPath: string;\n wrote: boolean;\n /** True when the target instant is at/after the newest record (\"restore to\n * now\") — the as-of state is the full replay state. */\n toNow: boolean;\n /** Disk view vs as-of view (informational; always computed). */\n diff: RestoreDiff;\n}\n\nconst isNoDiff = (d: RestoreDiff): boolean => d.added === 0 && d.removed === 0 && d.changed === 0;\n\n/** Disk view vs as-of view, compared by entry id / content. */\nfunction diffAgainstDisk(nowDoc: ProfileDoc, atDoc: ProfileDoc): RestoreDiff {\n const nowIds = new Map<string, string>();\n const atIds = new Map<string, string>();\n for (const p of PARTITIONS) {\n for (const e of nowDoc.partitions[p]!.entries) nowIds.set(e.id, e.content);\n for (const e of atDoc.partitions[p]!.entries) atIds.set(e.id, e.content);\n }\n let added = 0;\n let removed = 0;\n let changed = 0;\n for (const [id, content] of nowIds) {\n if (!atIds.has(id)) added += 1;\n else if (atIds.get(id) !== content) changed += 1;\n }\n for (const id of atIds.keys()) {\n if (!nowIds.has(id)) removed += 1;\n }\n return { entriesNow: nowIds.size, entriesAt: atIds.size, added, removed, changed };\n}\n\n/** ts (epoch ms) of the newest journal record with `ts <= bound`, 0 when none. */\nfunction maxRecordTsAtMost(guard: PathGuard, dataDir: string, bound: number): number {\n let max = 0;\n for (const text of readJournalTexts(guard, dataDir)) {\n for (const line of text.split('\\n')) {\n const s = line.trim();\n if (!s) continue;\n let ts = '';\n try {\n ts = String((JSON.parse(s) as { ts?: unknown }).ts ?? '');\n } catch {\n continue;\n }\n if (!ts) continue;\n const t = Date.parse(ts);\n if (Number.isFinite(t) && t <= bound && t > max) max = t;\n }\n }\n return max;\n}\n\n/** Restore the materialized view to its state at `iso` (v2.4.0).\n * - target at/after the newest record → \"restore to now\": a true no-op only\n * when the disk view already equals the as-of-now replay; a stale view\n * (e.g. right after a restore to the past) IS restored back to latest;\n * - dry-run → compute + diff only, never touches disk;\n * - otherwise → back up profile.json to `profile.json.before-restore-<ts>`\n * (atomic, byte-identical copy) and write the as-of view back.\n * Throws on an unparseable `iso`. */\nexport function restoreAt(guard: PathGuard, dataDir: string, iso: string, opts: { dryRun?: boolean } = {}): RestoreReport {\n const tMs = Date.parse(iso);\n if (!Number.isFinite(tMs)) throw new Error(`restore: invalid ISO timestamp: ${iso}`);\n const newest = maxRecordTsAtMost(guard, dataDir, Number.MAX_SAFE_INTEGER);\n const toNow = newest > 0 && tMs >= newest;\n const disk = loadProfile(guard, profileFilePath(dataDir));\n // One replay, one diff: replayJournal({ untilTs }) already knows how to pick\n // the basepoint and bound the records — restore must not re-implement it.\n let target: ProfileDoc;\n let diff: RestoreDiff;\n if (toNow) {\n target = replayJournal(guard, dataDir, { untilTs: newest }).doc;\n diff = diffAgainstDisk(disk, target);\n if (isNoDiff(diff)) {\n // genuinely current: report and return without writing anything\n return { restoredTo: newest, backupPath: '', wrote: false, toNow, diff };\n }\n } else {\n target = replayJournal(guard, dataDir, { untilTs: tMs }).doc;\n diff = diffAgainstDisk(disk, target);\n }\n const report: RestoreReport = {\n restoredTo: maxRecordTsAtMost(guard, dataDir, tMs),\n backupPath: '',\n wrote: false,\n toNow,\n diff,\n };\n if (opts.dryRun) return report;\n\n const profileAbs = profileFilePath(dataDir);\n let backupPath = '';\n if (fs.existsSync(guard.assert(profileAbs))) {\n // pre-restore backup first (atomic plaintext copy of the encrypted\n // container — byte-identical, still DPAPI-readable on this machine)\n const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);\n let candidate = path.join(dataDir, `profile.json.before-restore-${stamp}`);\n let n = 1;\n while (fs.existsSync(guard.assert(candidate))) {\n candidate = path.join(dataDir, `profile.json.before-restore-${stamp}-${n}`);\n n += 1;\n }\n writeText(guard, candidate, fs.readFileSync(guard.assert(profileAbs), 'utf8'));\n backupPath = candidate;\n }\n saveJson(guard, profileAbs, target);\n report.backupPath = backupPath;\n report.wrote = true;\n return report;\n}\n\n// ── wipe (HB-21, 2026-10-17) ───────────────────────────────────────────────\n// `profile wipe` used to delete three files: the materialized view, the inbox\n// and the live journal. The journal is the authority, and its history lives on\n// in profile_snapshot.json plus the archive shards — so a rebuild after a wipe\n// replayed the whole memory back, and a user who asked to forget got the\n// profile regrown instead. Migration backups (HB-07) and crash leftovers carry\n// copies of the same data.\n//\n// Wipe therefore removes every file the profile can be rebuilt from, and only\n// that: settings, seeds, weekly reports and audit logs are not profile data and\n// stay (burn is the tool for a full shred). Shredding remains burn's job — wipe\n// is a delete, not a destroy.\n\nconst WIPE_FILES = ['profile.json', 'profile_inbox.jsonl', 'profile_journal.jsonl', SNAPSHOT_FILE];\nconst WIPE_PATTERNS: RegExp[] = [\n /^profile_journal\\.archive-/,\n // v2.4.0: the dated snapshot archives (profile/snapshot.ts) are restore\n // basepoints — a wipe that left them behind let `profile restore` regrow the\n // memory (the HB-21 hole, second time around). Same for the pre-restore\n // backups restoreAt writes. Keep in sync with SNAPSHOT_ARCHIVE_NAME_RE above.\n /^profile_snapshot\\.\\d+\\.json$/,\n /^profile\\.json\\.before-restore-\\d{14}(-\\d+)?$/,\n /\\.bak-migrate-\\d{14}$/,\n /\\.incoming-\\d{14}$/,\n];\n\n/** Delete every file the profile can be rebuilt from; returns what was removed\n * (relative to dataDir, sorted per family). */\nexport function wipeProfile(guard: PathGuard, dataDir: string): string[] {\n const removed: string[] = [];\n for (const f of WIPE_FILES) {\n const abs = guard.assert(path.join(dataDir, f));\n if (fs.existsSync(abs)) {\n fs.rmSync(abs, { force: true });\n removed.push(f);\n }\n }\n for (const re of WIPE_PATTERNS) {\n let rels: string[] = [];\n try {\n rels = matchFilesRecursive(guard.assert(dataDir), re);\n } catch {\n rels = [];\n }\n for (const rel of rels) {\n try {\n fs.rmSync(guard.assert(path.join(dataDir, rel)), { force: true });\n removed.push(rel);\n } catch {\n /* already gone */\n }\n }\n }\n return removed;\n}\n","// User profile types (design doc §3). Fourth store: warm, structured,\n// slow-evolving model of the user. Not the material pool (hot cache), not\n// DSH long-term memory (conversation-validated layer).\n\nexport type Partition = 'interest' | 'projects' | 'comm' | 'psy';\nexport type Temporal = 'volatile' | 'stable';\nexport type EvidenceKind = 'chat' | 'screen' | 'browse' | 'hand' | 'ledger';\n\nexport interface Evidence {\n kind: EvidenceKind;\n at: string;\n /** Pointer to an existing audit/log location, e.g. \"heartbeat.jsonl#2026-09-06T12:00:00Z\". */\n ref: string;\n /** At most ONE short quote (<=1 sentence). Never raw conversation/screen text. */\n quote?: string;\n}\n\nexport interface ProfileEntry {\n id: string;\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n /** 0..1; capped per source kind (chat .6 / screen .4 / browse .4). */\n confidence: number;\n temporal: Temporal;\n validFrom: string;\n validTo: string | null;\n supersededBy: string | null;\n evidence: Evidence[];\n createdAt: string;\n updatedAt: string;\n updateCount: number;\n /** stable-tier audit flag (180d without observation): digest deprioritizes. */\n lowActivity?: boolean;\n}\n\nexport interface ProfileDoc {\n version: number;\n partitions: Record<Partition, { entries: ProfileEntry[] }>;\n}\n\nexport interface InboxItem {\n id?: string;\n kind: EvidenceKind;\n at: string;\n ref: string;\n /** <= 1 short sentence; never raw conversation/screen text (truncated by writer). */\n note: string;\n}\n\nexport type ProfileOp =\n | {\n op: 'ADD';\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n temporal?: Temporal;\n confidence?: number;\n why: string;\n evidence: Evidence[];\n /** Assigned by the store at apply time so journal replay preserves ids. */\n assignedId?: string;\n }\n | { op: 'UPDATE'; id: string; changes: { content?: string; confidence?: number }; why: string }\n | { op: 'INVALIDATE'; id: string; why: string; evidence?: Evidence[] }\n | { op: 'NOOP'; why: string };\n\n/**\n * Journal line schema version. Absent = v1: replay applies the applied ops\n * permissively. v2 adds entries — the canonical, code-written post-run entry\n * states (aging included) — and replay upserts those verbatim. That is what\n * makes the live write path and replay ONE state machine (review ③A / HB-09).\n */\nexport const JOURNAL_VERSION = 2;\n\nexport interface JournalRecord {\n v?: number;\n ts: string;\n runId: string;\n /** The model's original intent: audit mirror + the v1 replay path. */\n applied: ProfileOp[];\n rejected: { op: unknown; reason: string }[];\n /** v2 replay path: one full entry snapshot per entry this run touched.\n * Written by code; the model can never reach this field. */\n entries?: ProfileEntry[];\n}\n\nexport interface ApplyReport {\n applied: ProfileOp[];\n rejected: { op: unknown; reason: string }[];\n /** v2 journal events: the full post-state of every entry this run touched. */\n entries?: ProfileEntry[];\n}\n\nexport const PARTITIONS: readonly Partition[] = ['interest', 'projects', 'comm', 'psy'];\n\nexport const CONFIDENCE_CAP: Record<EvidenceKind, number> = {\n chat: 0.6,\n screen: 0.4,\n browse: 0.4,\n hand: 1.0,\n ledger: 0.6,\n};\n\nexport function emptyProfile(): ProfileDoc {\n return {\n version: 1,\n partitions: { interest: { entries: [] }, projects: { entries: [] }, comm: { entries: [] }, psy: { entries: [] } },\n };\n}\n","// profile-schema.json loading + ADD validation (r4 B10: temporal tier is an\n// ENTRY-level attribute; the schema declares, per sub_topic, the ALLOWED tier\n// set and the DEFAULT. Unlisted defaults to 'stable'.)\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Partition, Temporal } from './types.js';\n\nexport interface SubTopicDecl {\n allowed?: Temporal[];\n default?: Temporal;\n}\n\nexport interface ProfileSchema {\n version: number;\n partitions: Partial<Record<Partition, {\n topics: Record<string, { subtopics: Record<string, SubTopicDecl> }>;\n }>>;\n}\n\nexport interface SchemaLoad {\n /** The schema to use, or undefined when even the factory copy is unusable. */\n schema?: ProfileSchema;\n /** Where the returned schema came from. */\n source: 'user' | 'factory' | 'none';\n /** Set when the chosen schema is not the first choice (H-17 fallback). */\n fallbackReason?: string;\n}\n\n/**\n * H-17: three-tier load. This file is user-editable by design, so a broken\n * comma used to throw on every beat — `runConsolidation` aborted before\n * `inboxClear`, the inbox grew forever and the profile froze with no way back.\n * Now: a bad user copy falls back to the factory copy (audited by the caller);\n * an unusable factory copy yields `undefined`, which callers read as \"no\n * whitelist\" instead of a fatal error.\n */\nexport function loadProfileSchema(paths: { configDir: string; settingsDir: string }): SchemaLoad {\n const userPath = path.join(paths.settingsDir, 'profile-schema.json');\n const factoryPath = path.join(paths.configDir, 'profile-schema.json');\n const read = (file: string): { schema?: ProfileSchema; error: string } => {\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as ProfileSchema;\n if (!raw.partitions) return { error: 'partitions missing' };\n return { schema: raw, error: '' };\n } catch (e) {\n return { error: String(e) };\n }\n };\n const user = fs.existsSync(userPath) ? read(userPath) : null;\n if (user?.schema) return { schema: user.schema, source: 'user' };\n const factory = read(factoryPath);\n if (factory.schema) {\n return user\n ? {\n schema: factory.schema,\n source: 'factory',\n fallbackReason: `user profile-schema.json unusable (${user.error}) — fell back to the factory copy`,\n }\n : { schema: factory.schema, source: 'factory' };\n }\n return {\n source: 'none',\n fallbackReason: `no usable profile-schema.json (user: ${user?.error ?? 'absent'}; factory: ${factory.error})`,\n };\n}\n\nexport interface SchemaCheck {\n ok: boolean;\n reason?: string;\n temporal: Temporal;\n}\n\n/**\n * Validate an ADD against the whitelist and resolve the entry's temporal tier:\n * LLM nominates within the sub_topic's allowed set; missing nomination falls\n * back to the declared default; fully unlisted -> reject (charter boundary).\n */\nexport function checkAddAgainstSchema(\n schema: ProfileSchema,\n partition: Partition,\n topic: string,\n subTopic: string,\n nominated?: Temporal,\n): SchemaCheck {\n const p = schema.partitions[partition];\n if (!p) return { ok: false, reason: `partition not in schema: ${partition}`, temporal: 'stable' };\n const t = p.topics[topic];\n if (!t) return { ok: false, reason: `topic not in schema: ${partition}/${topic}`, temporal: 'stable' };\n const st = t.subtopics[subTopic];\n if (!st) return { ok: false, reason: `sub_topic not in schema: ${partition}/${topic}/${subTopic}`, temporal: 'stable' };\n const allowed: Temporal[] = st.allowed && st.allowed.length > 0 ? st.allowed : ['stable'];\n const def: Temporal = st.default && allowed.includes(st.default) ? st.default : allowed[0]!;\n if (!nominated) return { ok: true, temporal: def };\n if (!allowed.includes(nominated)) {\n return {\n ok: false,\n reason: `temporal \"${nominated}\" not allowed for ${partition}/${topic}/${subTopic} (allowed: ${allowed.join('|')})`,\n temporal: def,\n };\n }\n return { ok: true, temporal: nominated };\n}\n","// Foreign-shape boundaries (review 2026-10-17 ⑧A). Every place that accepts\n// data this code did not just build itself — the model's op array, journal\n// lines, inbox lines, migration packages, RPC payloads — is checked against\n// ONE schemastery definition here, instead of poking at properties ad hoc at\n// each call site (HB-12: a malformed op used to reach the guards and throw\n// somewhere in the middle of apply).\n//\n// schemastery objects are permissive on purpose: an absent field is simply\n// absent (no error) and unknown keys ride through. Profile boundaries need the\n// opposite, so closed() adds the two rules schemastery leaves out — required\n// keys and a closed key set — and check() applies them before field types run.\n\nimport z from '@deepseek-ai/schemastery';\nimport {\n JOURNAL_VERSION,\n PARTITIONS,\n type Evidence,\n type EvidenceKind,\n type InboxItem,\n type JournalRecord,\n type Partition,\n type ProfileEntry,\n type ProfileOp,\n type Temporal,\n} from './types.js';\n\nexport class ShapeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ShapeError';\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describe(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'an array';\n return typeof v;\n}\n\n/** A required key. A nullable one accepts `null` as a real value (validTo /\n * supersededBy) instead of reading it as absent. */\ntype Req = string | { key: string; nullable: true };\n\ninterface Closed {\n schema: Schemastery<any, any>;\n keys: readonly string[];\n required: readonly Req[];\n}\n\nfunction closed(\n schema: Schemastery<any, any>,\n keys: readonly string[],\n required: readonly Req[] = keys,\n): Closed {\n return { schema, keys, required };\n}\n\n/** object-ness -> required keys -> closed key set -> schemastery field types. */\nfunction check(shape: Closed, value: unknown, label: string): Record<string, unknown> {\n if (!isPlainObject(value)) throw new ShapeError(`${label}: expected an object, got ${describe(value)}`);\n for (const req of shape.required) {\n const key = typeof req === 'string' ? req : req.key;\n const nullable = typeof req !== 'string' && req.nullable;\n if (value[key] === undefined || (value[key] === null && !nullable)) {\n throw new ShapeError(`${label}.${key}: missing required value`);\n }\n }\n for (const k of Object.keys(value)) {\n if (!shape.keys.includes(k)) throw new ShapeError(`${label}.${k}: unknown field`);\n }\n try {\n return shape.schema(value) as Record<string, unknown>;\n } catch (e) {\n throw new ShapeError(`${label}: ${e instanceof Error ? e.message : String(e)}`);\n }\n}\n\nconst Str = z.string().required();\nconst Num = z.number().required();\n// No .required() on this one: schemastery reads null as \"absent\", but null is\n// a real value for validTo / supersededBy. check() enforces presence instead.\nconst NullableStr = z.union([z.string(), z.const(null)]);\nconst PartitionEnum = z.union(PARTITIONS.map((p) => z.const(p))).required();\nconst TemporalEnum = z.union([z.const('stable'), z.const('volatile')]).required();\n/** Same set, optional: the model may omit temporal and take the schema default. */\nconst OptionalTemporal = z.union([z.const('stable'), z.const('volatile')]);\nconst KindEnum = z.union([\n z.const('chat'),\n z.const('screen'),\n z.const('browse'),\n z.const('hand'),\n z.const('ledger'),\n]).required();\nconst ConfidenceNum = z.number().min(0).max(1).required();\n\n// ── evidence ────────────────────────────────────────────────────────────────\n\nconst EvidenceShape = closed(\n z.object({ kind: KindEnum, at: Str, ref: Str, quote: z.string() }),\n ['kind', 'at', 'ref', 'quote'],\n ['kind', 'at', 'ref'],\n);\n\nexport function parseEvidence(value: unknown, label = 'evidence'): Evidence {\n const o = check(EvidenceShape, value, label);\n return {\n kind: o.kind as EvidenceKind,\n at: String(o.at),\n ref: String(o.ref),\n ...(o.quote === undefined ? {} : { quote: String(o.quote) }),\n };\n}\n\nfunction parseEvidenceList(value: unknown, label: string): Evidence[] {\n if (!Array.isArray(value)) throw new ShapeError(`${label}: expected an array`);\n return value.map((v, i) => parseEvidence(v, `${label}[${i}]`));\n}\n\n// ── stored entry (journal v2 / migration packages) ──────────────────────────\n\nconst EntryShape = closed(\n z.object({\n id: Str,\n partition: PartitionEnum,\n topic: Str,\n subTopic: Str,\n content: Str,\n confidence: ConfidenceNum,\n temporal: TemporalEnum,\n validFrom: Str,\n validTo: NullableStr,\n supersededBy: NullableStr,\n evidence: z.array(z.any()).required(),\n createdAt: Str,\n updatedAt: Str,\n updateCount: Num,\n lowActivity: z.boolean(),\n }),\n ['id', 'partition', 'topic', 'subTopic', 'content', 'confidence', 'temporal', 'validFrom', 'validTo',\n 'supersededBy', 'evidence', 'createdAt', 'updatedAt', 'updateCount', 'lowActivity'],\n ['id', 'partition', 'topic', 'subTopic', 'content', 'confidence', 'temporal', 'validFrom',\n { key: 'validTo', nullable: true }, { key: 'supersededBy', nullable: true },\n 'evidence', 'createdAt', 'updatedAt', 'updateCount'],\n);\n\nexport function parseProfileEntry(value: unknown, label = 'entry'): ProfileEntry {\n const o = check(EntryShape, value, label);\n return {\n id: String(o.id),\n partition: o.partition as Partition,\n topic: String(o.topic),\n subTopic: String(o.subTopic),\n content: String(o.content),\n confidence: Number(o.confidence),\n temporal: o.temporal as Temporal,\n validFrom: String(o.validFrom),\n validTo: o.validTo === null ? null : String(o.validTo),\n supersededBy: o.supersededBy === null ? null : String(o.supersededBy),\n evidence: parseEvidenceList(o.evidence, `${label}.evidence`),\n createdAt: String(o.createdAt),\n updatedAt: String(o.updatedAt),\n updateCount: Number(o.updateCount),\n ...(o.lowActivity === undefined ? {} : { lowActivity: Boolean(o.lowActivity) }),\n };\n}\n\n// ── inbox line ──────────────────────────────────────────────────────────────\n\nconst InboxShape = closed(\n z.object({ id: z.string(), kind: KindEnum, at: Str, ref: Str, note: z.string() }),\n ['id', 'kind', 'at', 'ref', 'note'],\n ['kind', 'at', 'ref'],\n);\n\nexport function parseInboxItem(value: unknown, label = 'inbox item'): InboxItem {\n const o = check(InboxShape, value, label);\n return {\n ...(o.id === undefined ? {} : { id: String(o.id) }),\n kind: o.kind as EvidenceKind,\n at: String(o.at),\n ref: String(o.ref),\n note: o.note === undefined ? '' : String(o.note),\n };\n}\n\n// ── the model's op array (③A: ids in, evidence out) ─────────────────────────\n//\n// The model never supplies refs, timestamps or evidence kinds any more — it\n// cites observation ids from THIS batch (o1, o2, …) and the caller turns them\n// into Evidence objects. HB-05's forged provenance (a made-up \"hand\" ref used\n// to pin confidence at 1.0) is unreachable by construction.\n\nexport type ProposedOp =\n | {\n op: 'ADD';\n partition: Partition;\n topic: string;\n subTopic: string;\n content: string;\n temporal?: Temporal;\n confidence?: number;\n why: string;\n evidenceRefs: string[];\n }\n | { op: 'UPDATE'; id: string; changes: { content?: string; confidence?: number }; why: string }\n | { op: 'INVALIDATE'; id: string; why: string; evidenceRefs: string[] }\n | { op: 'NOOP'; why: string };\n\nconst AddShape = closed(\n z.object({\n op: z.const('ADD').required(),\n partition: PartitionEnum,\n topic: Str,\n subTopic: Str,\n content: Str,\n temporal: OptionalTemporal,\n confidence: z.number().min(0).max(1),\n why: z.string(),\n evidence: z.array(z.any()).required(),\n }),\n ['op', 'partition', 'topic', 'subTopic', 'content', 'temporal', 'confidence', 'why', 'evidence'],\n ['op', 'partition', 'topic', 'subTopic', 'content', 'evidence'],\n);\n\nconst UpdateShape = closed(\n z.object({\n op: z.const('UPDATE').required(),\n id: Str,\n changes: z.object({ content: z.string(), confidence: z.number().min(0).max(1) }),\n why: z.string(),\n }),\n ['op', 'id', 'changes', 'why'],\n ['op', 'id', 'changes'],\n);\n\nconst InvalidateShape = closed(\n z.object({\n op: z.const('INVALIDATE').required(),\n id: Str,\n why: z.string(),\n evidence: z.array(z.any()),\n }),\n ['op', 'id', 'why', 'evidence'],\n ['op', 'id'],\n);\n\nconst NoopShape = closed(\n z.object({ op: z.const('NOOP').required(), why: z.string() }),\n ['op', 'why'],\n ['op'],\n);\n\nfunction parseObservationRefs(value: unknown, label: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new ShapeError(`${label}: expected an array of observation ids`);\n return value.map((v, i) => {\n if (typeof v !== 'string' || !v.trim()) {\n throw new ShapeError(`${label}[${i}]: expected an observation id like \"o1\" (refs, timestamps and kinds are code-generated)`);\n }\n return v.trim();\n });\n}\n\nfunction parseProposedOp(raw: unknown, label: string): ProposedOp {\n if (!isPlainObject(raw)) throw new ShapeError(`${label}: expected an object, got ${describe(raw)}`);\n const tag = raw.op;\n if (tag === 'ADD') {\n const o = check(AddShape, raw, label);\n const evidenceRefs = parseObservationRefs(o.evidence, `${label}.evidence`);\n if (evidenceRefs.length === 0) {\n throw new ShapeError(`${label}.evidence: ADD needs at least one observation id (axiom 1: no provenance, no memory)`);\n }\n return {\n op: 'ADD',\n partition: o.partition as Partition,\n topic: String(o.topic),\n subTopic: String(o.subTopic),\n content: String(o.content),\n ...(o.temporal === undefined ? {} : { temporal: o.temporal as Temporal }),\n ...(o.confidence === undefined ? {} : { confidence: Number(o.confidence) }),\n why: typeof o.why === 'string' ? o.why : '',\n evidenceRefs,\n };\n }\n if (tag === 'UPDATE') {\n const o = check(UpdateShape, raw, label);\n const changes = o.changes as Record<string, unknown>;\n const out: { content?: string; confidence?: number } = {};\n if (changes.content !== undefined) out.content = String(changes.content);\n if (changes.confidence !== undefined) out.confidence = Number(changes.confidence);\n if (out.content === undefined && out.confidence === undefined) {\n throw new ShapeError(`${label}.changes: needs content or confidence`);\n }\n return { op: 'UPDATE', id: String(o.id), changes: out, why: typeof o.why === 'string' ? o.why : '' };\n }\n if (tag === 'INVALIDATE') {\n const o = check(InvalidateShape, raw, label);\n return {\n op: 'INVALIDATE',\n id: String(o.id),\n why: typeof o.why === 'string' ? o.why : '',\n evidenceRefs: parseObservationRefs(o.evidence, `${label}.evidence`),\n };\n }\n if (tag === 'NOOP') {\n const o = check(NoopShape, raw, label);\n return { op: 'NOOP', why: typeof o.why === 'string' ? o.why : '' };\n }\n throw new ShapeError(`${label}.op: unknown op ${JSON.stringify(tag)}`);\n}\n\nexport interface OpParseResult {\n ops: ProposedOp[];\n /** One malformed row never discards the rest of the batch, but it is always\n * reported — silence here used to look like \"the model proposed nothing\". */\n rejected: { op: unknown; reason: string }[];\n}\n\nexport function parseProposedOps(list: unknown[]): OpParseResult {\n const ops: ProposedOp[] = [];\n const rejected: { op: unknown; reason: string }[] = [];\n list.forEach((raw, i) => {\n try {\n ops.push(parseProposedOp(raw, `op[${i}]`));\n } catch (e) {\n rejected.push({ op: raw, reason: e instanceof Error ? e.message : String(e) });\n }\n });\n return { ops, rejected };\n}\n\n/** Turn cited observation ids into code-built evidence. Unknown ids are a\n * rejection, never a silent drop: the op then has no provenance. */\nexport function materializeEvidence(\n refs: string[],\n observations: Map<string, InboxItem>,\n label: string,\n): { evidence: Evidence[]; reason?: string } {\n const evidence: Evidence[] = [];\n for (const ref of refs) {\n const item = observations.get(ref);\n if (!item) return { evidence: [], reason: `${label}: ${ref} does not match any observation in this batch` };\n evidence.push({ kind: item.kind, at: item.at, ref: item.ref });\n }\n return { evidence };\n}\n\n// ── journal line reader (replay path) ───────────────────────────────────────\n//\n// Lenient on purpose: a line this code did not write is skipped by the caller,\n// never fatal. The journal is append-only and immutable, so one bad line must\n// not freeze the profile — but it IS counted (ReplayResult.badRecords) so a\n// silent data loss is visible in profile verify.\n\nexport function tryParseJournalRecord(value: unknown): JournalRecord | null {\n try {\n if (!isPlainObject(value)) return null;\n const rec: JournalRecord = {\n ts: typeof value.ts === 'string' ? value.ts : '',\n runId: typeof value.runId === 'string' ? value.runId : '',\n applied: Array.isArray(value.applied) ? (value.applied as ProfileOp[]) : [],\n rejected: Array.isArray(value.rejected) ? (value.rejected as { op: unknown; reason: string }[]) : [],\n };\n if (value.v === JOURNAL_VERSION) {\n if (!Array.isArray(value.entries)) return null;\n rec.v = JOURNAL_VERSION;\n rec.entries = value.entries.map((e, i) => parseProfileEntry(e, `entries[${i}]`));\n }\n return rec;\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;AAKA,OAAOA,WAAU;AACjB,SAAS,kBAAkB;AAC3B,OAAOC,SAAQ;;;ACoER,IAAM,kBAAkB;AAqBxB,IAAM,aAAmC,CAAC,YAAY,YAAY,QAAQ,KAAK;AAE/E,IAAM,iBAA+C;AAAA,EAC1D,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,QAAQ;AACV;AAEO,SAAS,eAA2B;AACzC,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY,EAAE,UAAU,EAAE,SAAS,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,CAAC,EAAE,GAAG,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE;AAAA,EAClH;AACF;;;AC3GA,OAAO,QAAQ;AACf,OAAO,UAAU;AAgCV,SAAS,kBAAkB,OAA+D;AAC/F,QAAM,WAAW,KAAK,KAAK,MAAM,aAAa,qBAAqB;AACnE,QAAM,cAAc,KAAK,KAAK,MAAM,WAAW,qBAAqB;AACpE,QAAM,OAAO,CAAC,SAA4D;AACxE,QAAI;AACF,YAAM,MAAM,KAAK,MAAM,GAAG,aAAa,MAAM,MAAM,CAAC;AACpD,UAAI,CAAC,IAAI,WAAY,QAAO,EAAE,OAAO,qBAAqB;AAC1D,aAAO,EAAE,QAAQ,KAAK,OAAO,GAAG;AAAA,IAClC,SAAS,GAAG;AACV,aAAO,EAAE,OAAO,OAAO,CAAC,EAAE;AAAA,IAC5B;AAAA,EACF;AACA,QAAM,OAAO,GAAG,WAAW,QAAQ,IAAI,KAAK,QAAQ,IAAI;AACxD,MAAI,MAAM,OAAQ,QAAO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