2026-08-22 10:30:00 +03:00
|
|
|
/**
|
2026-08-31 20:00:12 +03:00
|
|
|
* GraphStore — the fs JSONL adapter: five append-only ledgers at
|
|
|
|
|
* config.LEDGER_FILES (contracts.ts "v1 emission").
|
2026-09-08 22:19:37 +03:00
|
|
|
* nodes.jsonl GraphNode — one line per node write: the FIRST
|
|
|
|
|
* line for an id defines it; a later
|
|
|
|
|
* line with a REPEATED id is a
|
|
|
|
|
* link-append (session phrasings join
|
|
|
|
|
* aliases, provenance unions); reads
|
|
|
|
|
* merge by id (core/graph.ts getGraph)
|
2026-08-31 20:00:12 +03:00
|
|
|
* edges.jsonl GraphEdge — one line per edge ASSERTION (a second
|
2026-08-22 10:30:00 +03:00
|
|
|
* session asserting the same (from,to,type)
|
|
|
|
|
* appends another line; reads merge)
|
2026-09-08 22:19:37 +03:00
|
|
|
* events.jsonl LedgerEvent — quiz outcomes + understanding observations
|
2026-08-31 22:36:41 +03:00
|
|
|
* mappings.jsonl NodeMapping — the session→graph identity map:
|
|
|
|
|
* (chatId, sourceId) → graphNodeId
|
2026-08-22 10:30:00 +03:00
|
|
|
* sessions.jsonl SessionCheckpoint— emission checkpoints (foldedAt)
|
|
|
|
|
*
|
2026-09-13 02:08:55 +03:00
|
|
|
* Plus config.SOURCES_FILE (sources.json): the imported-notes bookkeeping
|
|
|
|
|
* (NOT a ledger) — one JSON map, src-id → NotesSource, read-modify-write
|
|
|
|
|
* like a chat file. The format-agnostic front door (2026-09-13).
|
|
|
|
|
*
|
2026-08-31 20:00:12 +03:00
|
|
|
* Implements core/ports.ts GraphStore. data/graph/* is exclusively this
|
2026-09-08 22:19:37 +03:00
|
|
|
* adapter's. Reads are strict against the contracts.ts shapes (the 2026-09-02
|
|
|
|
|
* graph redesign): corrupt lines are skipped, never guessed at — the ledgers
|
|
|
|
|
* are the source of truth and everything else is derived (core/graph.ts,
|
|
|
|
|
* which takes this port as a parameter). Same idioms as src/store/chats.ts:
|
|
|
|
|
* sync fs, no framework.
|
2026-08-22 10:30:00 +03:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import * as fs from "node:fs";
|
|
|
|
|
import * as path from "node:path";
|
2026-09-13 02:08:55 +03:00
|
|
|
import { LEDGER_FILES, SOURCES_FILE } from "../../config.ts";
|
2026-08-31 20:00:12 +03:00
|
|
|
import type {
|
2026-09-13 03:59:48 +03:00
|
|
|
ClusterLabeling,
|
2026-08-31 20:00:12 +03:00
|
|
|
GraphEdge,
|
|
|
|
|
GraphNode,
|
2026-09-13 02:08:55 +03:00
|
|
|
ExtractionRunUsage,
|
2026-08-31 20:00:12 +03:00
|
|
|
LedgerEvent,
|
|
|
|
|
LedgerEventKind,
|
2026-09-13 02:08:55 +03:00
|
|
|
NotesSource,
|
2026-08-31 20:00:12 +03:00
|
|
|
NodeMapping,
|
2026-09-08 22:19:37 +03:00
|
|
|
ProvenancePoint,
|
2026-08-31 20:00:12 +03:00
|
|
|
SessionCheckpoint,
|
|
|
|
|
} from "../core/contracts.ts";
|
|
|
|
|
import type { GraphStore } from "../core/ports.ts";
|
2026-08-22 10:30:00 +03:00
|
|
|
|
|
|
|
|
// ─── JSONL primitives ────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
function appendLine<T>(file: string, record: T): void {
|
|
|
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
|
|
|
fs.appendFileSync(file, `${JSON.stringify(record)}\n`, "utf-8");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function readRawLines(file: string): unknown[] {
|
|
|
|
|
let raw: string;
|
|
|
|
|
try {
|
|
|
|
|
raw = fs.readFileSync(file, "utf-8");
|
|
|
|
|
} catch {
|
|
|
|
|
return []; // no ledger yet — nothing has ever been emitted
|
|
|
|
|
}
|
|
|
|
|
const out: unknown[] = [];
|
|
|
|
|
for (const line of raw.split("\n")) {
|
|
|
|
|
const trimmed = line.trim();
|
|
|
|
|
if (trimmed.length === 0) continue;
|
|
|
|
|
try {
|
|
|
|
|
out.push(JSON.parse(trimmed));
|
|
|
|
|
} catch {
|
|
|
|
|
// Corrupt line: skip rather than fail the whole read — a torn
|
|
|
|
|
// append must never take the home graph down with it.
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
|
|
|
return typeof v === "object" && v !== null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isString = (v: unknown): v is string => typeof v === "string";
|
|
|
|
|
|
|
|
|
|
/** Strict shape guards — anything not matching a W4 ledger shape is skipped. */
|
|
|
|
|
function readValid<T>(file: string, isValid: (v: unknown) => v is T): T[] {
|
|
|
|
|
return readRawLines(file).filter(isValid);
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-08 22:19:37 +03:00
|
|
|
/** Provenance points are (chatId, messageId) pairs — message-granular. */
|
|
|
|
|
const isProvenancePoint = (v: unknown): v is ProvenancePoint =>
|
|
|
|
|
isRecord(v) && isString(v.chatId) && isString(v.messageId);
|
2026-09-01 03:34:47 +03:00
|
|
|
|
2026-09-13 03:59:48 +03:00
|
|
|
const isClusterLabeling = (v: unknown): v is ClusterLabeling =>
|
|
|
|
|
isRecord(v) &&
|
|
|
|
|
isString(v.id) &&
|
|
|
|
|
isString(v.label) &&
|
|
|
|
|
Array.isArray(v.core) &&
|
|
|
|
|
v.core.every(isString) &&
|
|
|
|
|
isString(v.createdAt);
|
|
|
|
|
|
2026-09-08 22:19:37 +03:00
|
|
|
const isGraphNode = (v: unknown): v is GraphNode =>
|
2026-08-22 10:30:00 +03:00
|
|
|
isRecord(v) &&
|
|
|
|
|
isString(v.id) &&
|
2026-09-09 00:40:02 +03:00
|
|
|
isString(v.name) &&
|
2026-08-22 10:30:00 +03:00
|
|
|
isString(v.statement) &&
|
|
|
|
|
Array.isArray(v.aliases) &&
|
2026-09-08 22:19:37 +03:00
|
|
|
v.aliases.every(isString) &&
|
2026-09-01 03:34:47 +03:00
|
|
|
isString(v.createdAt) &&
|
2026-09-08 22:19:37 +03:00
|
|
|
Array.isArray(v.provenance) &&
|
|
|
|
|
v.provenance.every(isProvenancePoint);
|
2026-09-01 03:34:47 +03:00
|
|
|
|
2026-09-08 22:19:37 +03:00
|
|
|
const EDGE_TYPES = ["follows", "supports"] as const;
|
2026-08-22 10:30:00 +03:00
|
|
|
|
|
|
|
|
const isGraphEdge = (v: unknown): v is GraphEdge =>
|
|
|
|
|
isRecord(v) &&
|
|
|
|
|
isString(v.from) &&
|
|
|
|
|
isString(v.to) &&
|
|
|
|
|
(EDGE_TYPES as readonly string[]).includes(v.type as string) &&
|
|
|
|
|
Array.isArray(v.provenance) &&
|
2026-09-08 22:19:37 +03:00
|
|
|
v.provenance.every(isProvenancePoint);
|
2026-08-22 10:30:00 +03:00
|
|
|
|
2026-09-08 22:19:37 +03:00
|
|
|
const EVENT_KINDS: readonly LedgerEventKind[] = ["correct", "miss", "dont-know", "observation"];
|
2026-08-22 10:30:00 +03:00
|
|
|
|
|
|
|
|
const isLedgerEvent = (v: unknown): v is LedgerEvent =>
|
|
|
|
|
isRecord(v) &&
|
|
|
|
|
(v.nodeId === null || isString(v.nodeId)) &&
|
|
|
|
|
(EVENT_KINDS as readonly string[]).includes(v.kind as string) &&
|
|
|
|
|
isString(v.chatId) &&
|
|
|
|
|
isString(v.at);
|
|
|
|
|
|
|
|
|
|
const isNodeMapping = (v: unknown): v is NodeMapping =>
|
2026-08-31 22:36:41 +03:00
|
|
|
isRecord(v) && isString(v.chatId) && isString(v.sourceId) && isString(v.graphNodeId);
|
2026-08-22 10:30:00 +03:00
|
|
|
|
|
|
|
|
const isCheckpoint = (v: unknown): v is SessionCheckpoint =>
|
|
|
|
|
isRecord(v) && isString(v.chatId) && isString(v.foldedAt);
|
|
|
|
|
|
2026-08-31 20:00:12 +03:00
|
|
|
// ─── the port implementation ────────────────────────────────────────────────
|
2026-08-22 10:30:00 +03:00
|
|
|
|
2026-08-31 20:00:12 +03:00
|
|
|
export const graphStore: GraphStore = {
|
2026-08-22 10:30:00 +03:00
|
|
|
appendNode(node: GraphNode): void {
|
|
|
|
|
appendLine(LEDGER_FILES.nodes, node);
|
|
|
|
|
},
|
2026-09-08 22:19:37 +03:00
|
|
|
/** Raw node lines in append order. A node id may appear on more than
|
|
|
|
|
* one line (a later session's LINK-append: phrasings + provenance); the
|
|
|
|
|
* derivation (core/graph.ts getGraph) merges lines by id. */
|
2026-08-22 10:30:00 +03:00
|
|
|
readNodes(): GraphNode[] {
|
2026-09-08 22:19:37 +03:00
|
|
|
return readValid(LEDGER_FILES.nodes, isGraphNode);
|
2026-08-22 10:30:00 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
|
|
/** Append one edge ASSERTION; readers merge lines by (from,to,type). */
|
2026-08-31 20:00:12 +03:00
|
|
|
appendEdge(assertion: GraphEdge): void {
|
|
|
|
|
appendLine(LEDGER_FILES.edges, assertion);
|
2026-08-22 10:30:00 +03:00
|
|
|
},
|
|
|
|
|
readEdges(): GraphEdge[] {
|
|
|
|
|
return readValid(LEDGER_FILES.edges, isGraphEdge);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
appendEvent(event: LedgerEvent): void {
|
|
|
|
|
appendLine(LEDGER_FILES.events, event);
|
|
|
|
|
},
|
|
|
|
|
readEvents(): LedgerEvent[] {
|
|
|
|
|
return readValid(LEDGER_FILES.events, isLedgerEvent);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
appendMapping(mapping: NodeMapping): void {
|
|
|
|
|
appendLine(LEDGER_FILES.mappings, mapping);
|
|
|
|
|
},
|
|
|
|
|
readMappings(): NodeMapping[] {
|
|
|
|
|
return readValid(LEDGER_FILES.mappings, isNodeMapping);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
appendCheckpoint(checkpoint: SessionCheckpoint): void {
|
|
|
|
|
appendLine(LEDGER_FILES.sessions, checkpoint);
|
|
|
|
|
},
|
|
|
|
|
readCheckpoints(): SessionCheckpoint[] {
|
|
|
|
|
return readValid(LEDGER_FILES.sessions, isCheckpoint);
|
|
|
|
|
},
|
2026-09-13 02:08:55 +03:00
|
|
|
|
2026-09-13 03:59:48 +03:00
|
|
|
// ── cluster labelings (config.LEDGER_FILES.clusterLabels) ──
|
|
|
|
|
|
|
|
|
|
/** Idempotent by id: the id is a hash of the sorted core, so re-appending
|
|
|
|
|
* the same member set (re-naming races, idempotent re-runs) is a no-op. */
|
|
|
|
|
appendClusterLabel(labeling: ClusterLabeling): void {
|
|
|
|
|
if (this.readClusterLabels().some((l) => l.id === labeling.id)) return;
|
|
|
|
|
appendLine(LEDGER_FILES.clusterLabels, labeling);
|
|
|
|
|
},
|
|
|
|
|
readClusterLabels(): ClusterLabeling[] {
|
|
|
|
|
return readValid(LEDGER_FILES.clusterLabels, isClusterLabeling);
|
|
|
|
|
},
|
|
|
|
|
|
2026-09-13 02:08:55 +03:00
|
|
|
// ── imported-notes bookkeeping (config.SOURCES_FILE — a JSON map) ──
|
|
|
|
|
|
|
|
|
|
/** Upsert: keeps the existing record's usage log when re-importing. */
|
|
|
|
|
upsertSource(source: NotesSource): void {
|
|
|
|
|
const all = readSourceMap();
|
|
|
|
|
const prev = all[source.id];
|
|
|
|
|
all[source.id] = prev ? { ...source, extractions: prev.extractions } : source;
|
|
|
|
|
writeSourceMap(all);
|
|
|
|
|
},
|
|
|
|
|
readSources(): NotesSource[] {
|
|
|
|
|
return Object.values(readSourceMap());
|
|
|
|
|
},
|
|
|
|
|
/** Idempotent per startedAt — same discipline as chats.appendExtractionUsage. */
|
|
|
|
|
appendSourceUsage(id: string, entry: ExtractionRunUsage): void {
|
|
|
|
|
const all = readSourceMap();
|
|
|
|
|
const source = all[id];
|
|
|
|
|
if (!source) return; // no such source — nothing to bill against
|
|
|
|
|
source.extractions = source.extractions?.some((r) => r.startedAt === entry.startedAt)
|
|
|
|
|
? source.extractions
|
|
|
|
|
: [...(source.extractions ?? []), entry];
|
|
|
|
|
writeSourceMap(all);
|
|
|
|
|
},
|
2026-08-22 10:30:00 +03:00
|
|
|
};
|
2026-09-13 02:08:55 +03:00
|
|
|
|
|
|
|
|
/** sources.json — { id: NotesSource }. Read-modify-write, NOT append-only:
|
|
|
|
|
* the usage log lives inside the record (like a chat's JSON file). */
|
|
|
|
|
function readSourceMap(): Record<string, NotesSource> {
|
|
|
|
|
let raw: string;
|
|
|
|
|
try {
|
|
|
|
|
raw = fs.readFileSync(SOURCES_FILE, "utf-8");
|
|
|
|
|
} catch {
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const parsed: unknown = JSON.parse(raw);
|
|
|
|
|
if (!isRecord(parsed)) return {};
|
|
|
|
|
const out: Record<string, NotesSource> = {};
|
|
|
|
|
for (const [id, value] of Object.entries(parsed)) {
|
|
|
|
|
if (isNotesSource(value)) out[id] = value;
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
} catch {
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function writeSourceMap(map: Record<string, NotesSource>): void {
|
|
|
|
|
fs.mkdirSync(path.dirname(SOURCES_FILE), { recursive: true });
|
|
|
|
|
fs.writeFileSync(SOURCES_FILE, JSON.stringify(map, null, "\t"), "utf-8");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isNotesSource = (v: unknown): v is NotesSource =>
|
|
|
|
|
isRecord(v) && isString(v.id) && isString(v.filePath) && isString(v.importedAt);
|