nexorum 0.0.0-stage → 0.2.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.
@@ -0,0 +1,204 @@
1
+ // Reviewing dream proposals: changes, diff, apply (with the skip rule), reject, history, restore, retention.
2
+ import { sha256Hex, diffDocs, lineDiff } from "./core/index.js";
3
+ import { CliError, UsageError } from "./args.js";
4
+ import { assertDocPath } from "./store.js";
5
+
6
+ const DAY_MS = 86_400_000;
7
+
8
+ /**
9
+ * What the proposal changes relative to the live wiki as it was when the dream started (base.json).
10
+ * Each: {path, kind, before (live now), after (staged), baseSha, conflict (live differs from base)}.
11
+ */
12
+ export function proposalChanges(store, id) {
13
+ const base = store.readBase(id);
14
+ const staged = store.readProposalWiki(id);
15
+ const out = [];
16
+ for (const p of [...new Set([...Object.keys(base), ...Object.keys(staged)])].sort()) {
17
+ const baseSha = base[p] ?? null;
18
+ const after = staged[p] ?? null;
19
+ if ((after === null ? null : sha256Hex(after)) === baseSha) continue;
20
+ const before = store.readDoc(p);
21
+ out.push({
22
+ path: p,
23
+ kind: after === null ? "removed" : baseSha === null ? "added" : "modified",
24
+ before,
25
+ after,
26
+ baseSha,
27
+ conflict: (before === null ? null : sha256Hex(before)) !== baseSha,
28
+ });
29
+ }
30
+ return out;
31
+ }
32
+
33
+ const splitLines = (s) => {
34
+ const lines = s.split("\n");
35
+ if (lines.at(-1) === "") lines.pop();
36
+ return lines;
37
+ };
38
+
39
+ /** Plain unified diff of one page, 3 lines of context, no colours. */
40
+ export function unifiedDiff(p, before, after, context = 3) {
41
+ const header = [`--- ${before === null ? "/dev/null" : `live${p}`}`, `+++ ${after === null ? "/dev/null" : `proposed${p}`}`];
42
+ let ops;
43
+ if (before === null) ops = splitLines(after).map((text) => ({ type: "add", text }));
44
+ else if (after === null) ops = splitLines(before).map((text) => ({ type: "del", text }));
45
+ else {
46
+ ops = lineDiff(before, after);
47
+ while (ops.length && ops.at(-1).type === "same" && ops.at(-1).text === "") ops.pop();
48
+ }
49
+ // Line numbers in the old (o) and new (n) file at each op.
50
+ let o = 1;
51
+ let n = 1;
52
+ const pos = ops.map((op) => {
53
+ const at = { o, n };
54
+ if (op.type !== "add") o++;
55
+ if (op.type !== "del") n++;
56
+ return at;
57
+ });
58
+ const changed = ops.flatMap((op, i) => (op.type === "same" ? [] : [i]));
59
+ if (!changed.length) return [...header, "(no line changes)"].join("\n");
60
+ const hunks = [];
61
+ for (const i of changed) {
62
+ const s = Math.max(0, i - context);
63
+ const e = Math.min(ops.length - 1, i + context);
64
+ const last = hunks.at(-1);
65
+ if (last && s <= last[1] + 1) last[1] = Math.max(last[1], e);
66
+ else hunks.push([s, e]);
67
+ }
68
+ const lines = [...header];
69
+ for (const [s, e] of hunks) {
70
+ const slice = ops.slice(s, e + 1);
71
+ const oc = slice.filter((x) => x.type !== "add").length;
72
+ const nc = slice.filter((x) => x.type !== "del").length;
73
+ lines.push(`@@ -${oc === 0 ? pos[s].o - 1 : pos[s].o},${oc} +${nc === 0 ? pos[s].n - 1 : pos[s].n},${nc} @@`);
74
+ for (const x of slice) lines.push(`${x.type === "add" ? "+" : x.type === "del" ? "-" : " "}${x.text}`);
75
+ }
76
+ return lines.join("\n");
77
+ }
78
+
79
+ export function renderProposalDiff(store, proposal) {
80
+ const changes = proposalChanges(store, proposal.id);
81
+ if (!changes.length) return `Proposal ${proposal.id} has no changes.`;
82
+ // The kind shown is what the live wiki now looks like against the staged copy (a hand-deleted page reads "added").
83
+ const kinds = new Map(
84
+ diffDocs(
85
+ Object.fromEntries(changes.filter((c) => c.before !== null).map((c) => [c.path, c.before])),
86
+ Object.fromEntries(changes.filter((c) => c.after !== null).map((c) => [c.path, c.after])),
87
+ ).map((d) => [d.path, d.kind]),
88
+ );
89
+ return changes
90
+ .map((c) => {
91
+ const note = c.conflict ? " [live file changed since this proposal was made; apply skips it unless --force]" : "";
92
+ return `=== ${c.path} (${kinds.get(c.path) ?? c.kind})${note}\n${unifiedDiff(c.path, c.before, c.after)}`;
93
+ })
94
+ .join("\n\n");
95
+ }
96
+
97
+ /**
98
+ * Writes a proposal to the live wiki. A path is written only while the live page still equals what the dream
99
+ * started from; otherwise it is skipped (unless `force`). When every change was skipped the proposal stays under
100
+ * review and its inputs stay pending.
101
+ * @returns {{applied:string[], skipped:{path:string, reason:string}[], status:string}}
102
+ */
103
+ export function applyProposal(store, proposal, { force = false } = {}) {
104
+ if (proposal.status === "applied") throw new CliError(`Proposal ${proposal.id} was already applied.`);
105
+ if (proposal.status === "rejected") throw new CliError(`Proposal ${proposal.id} was rejected.`);
106
+ const actor = `dream:${proposal.id}`;
107
+ const applied = [];
108
+ const skipped = [];
109
+ for (const c of proposalChanges(store, proposal.id)) {
110
+ if (c.conflict && !force) {
111
+ skipped.push({ path: c.path, reason: "live file changed since the proposal was made" });
112
+ continue;
113
+ }
114
+ if (c.after === null) store.deleteDoc(c.path, { actor });
115
+ else store.writeDoc(c.path, c.after, { actor });
116
+ applied.push(c.path);
117
+ }
118
+ const next = { ...proposal, applied_paths: applied, skipped_paths: skipped };
119
+ if (!applied.length && skipped.length) {
120
+ store.writeProposal(next);
121
+ return { applied, skipped, status: proposal.status };
122
+ }
123
+ consumeInputs(store, proposal);
124
+ store.writeProposal({ ...next, status: "applied", applied_at: new Date().toISOString() });
125
+ return { applied, skipped, status: "applied" };
126
+ }
127
+
128
+ /** Marks the proposal's transcripts dreamed (unless they changed after the dream read them) and moves the notes marker. */
129
+ export function consumeInputs(store, proposal) {
130
+ const ts = new Date().toISOString();
131
+ const versions = proposal.transcript_versions ?? {};
132
+ for (const id of proposal.transcripts ?? []) {
133
+ const t = store.getTranscript(id);
134
+ if (!t) continue;
135
+ if (versions[id] && t.updated_at !== versions[id]) continue;
136
+ store.saveTranscript({ ...t, status: "dreamed", dreamed_at: ts });
137
+ }
138
+ if (proposal.notes_through) {
139
+ const state = store.readState();
140
+ if (!state.notes_consolidated_through || state.notes_consolidated_through < proposal.notes_through) {
141
+ store.writeState({ ...state, notes_consolidated_through: proposal.notes_through });
142
+ }
143
+ }
144
+ }
145
+
146
+ export function rejectProposal(store, proposal) {
147
+ if (proposal.status !== "review") throw new CliError(`Proposal ${proposal.id} is ${proposal.status}, not under review.`);
148
+ store.writeProposal({ ...proposal, status: "rejected", rejected_at: new Date().toISOString() });
149
+ }
150
+
151
+ /** Restores version N, or (without N) the newest version whose content differs from the live page. */
152
+ export function restorePath(store, p, version) {
153
+ assertDocPath(p);
154
+ const versions = store.versionsOf(p);
155
+ if (!versions.length) throw new CliError(`No history for ${p}.`);
156
+ const current = store.readDoc(p);
157
+ let target;
158
+ if (version !== undefined) {
159
+ target = versions.find((v) => v.version === version);
160
+ if (!target) throw new CliError(`${p} has no version ${version} (versions: 1-${versions.length}).`);
161
+ if (!target.file) throw new CliError(`Version ${version} of ${p} is a deletion; pick a version that has content.`);
162
+ } else {
163
+ const curSha = current === null ? null : sha256Hex(current);
164
+ target = [...versions].reverse().find((v) => v.file && v.sha256 !== curSha);
165
+ if (!target) throw new CliError(`${p} has no earlier version to restore.`);
166
+ }
167
+ const content = store.readSnapshotFile(target.file);
168
+ if (content === null) throw new CliError(`The snapshot file for ${p} version ${target.version} is missing.`);
169
+ if (content === current) throw new CliError(`${p} already matches version ${target.version}.`);
170
+ store.writeDoc(p, content, { actor: "restore", operation: "restore" });
171
+ return target;
172
+ }
173
+
174
+ export function formatHistory(store, p) {
175
+ let entries;
176
+ if (p) {
177
+ assertDocPath(p);
178
+ entries = store.versionsOf(p);
179
+ } else {
180
+ const count = new Map();
181
+ entries = store.readHistory().map((e) => {
182
+ const v = (count.get(e.path) ?? 0) + 1;
183
+ count.set(e.path, v);
184
+ return { ...e, version: v };
185
+ });
186
+ }
187
+ if (!entries.length) return p ? `No history for ${p}.` : "No history yet.";
188
+ return entries.map((e) => `${p ? "" : `${e.path} `}v${e.version} ${e.ts} ${e.operation.padEnd(7)} ${e.actor}${e.sha256 ? ` ${e.sha256.slice(0, 8)}` : ""}`).join("\n");
189
+ }
190
+
191
+ /** Deletes transcripts dreamed more than `days` days ago. Pending ones are never touched. */
192
+ export function runRetention(store, days = 30, nowMs = Date.now()) {
193
+ if (!Number.isFinite(days) || days < 0) throw new UsageError("--days must be a non-negative number");
194
+ let removed = 0;
195
+ for (const t of store.listTranscripts()) {
196
+ if (t.status !== "dreamed" || !t.dreamed_at) continue;
197
+ const at = Date.parse(t.dreamed_at);
198
+ if (Number.isFinite(at) && nowMs - at > days * DAY_MS) {
199
+ store.deleteTranscript(t.id);
200
+ removed++;
201
+ }
202
+ }
203
+ return removed;
204
+ }
package/src/store.js ADDED
@@ -0,0 +1,445 @@
1
+ // The memory folder of one space: notes, transcripts, the live wiki with versioned history, and dream proposals.
2
+ //
3
+ // <home>/spaces/<space>/
4
+ // notes.jsonl one note per line
5
+ // state.json notes_consolidated_through (newest note a dream has folded into the wiki)
6
+ // transcripts/<id>.json sessions, status pending -> dreamed
7
+ // wiki/ live markdown pages (_index.md is the catalog)
8
+ // history/log.jsonl one entry per live write; files/<n>-<sha8> holds the content of entry n
9
+ // proposals/<id>/ proposal.json, base.json (live hashes at dream start), wiki/ (staged copy)
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import crypto from "node:crypto";
14
+ import { sha256Hex, newId } from "./core/index.js";
15
+ import { CliError, UsageError } from "./args.js";
16
+
17
+ const DOC_PATH_RE = /^\/[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/;
18
+ const ID_RE = /^[A-Za-z0-9_.-]{1,128}$/;
19
+ const TMP_NAME_RE = /\.tmp-\d+-[0-9a-f]+$/;
20
+
21
+ export function userHome(env = process.env) {
22
+ return env.HOME || env.USERPROFILE || os.homedir();
23
+ }
24
+
25
+ export function nexorumRoot(env = process.env) {
26
+ return env.NEXORUM_HOME ? path.resolve(env.NEXORUM_HOME) : path.join(userHome(env), ".nexorum");
27
+ }
28
+
29
+ /** Characters outside A-Za-z0-9_.- become "-", at most 64 characters, "default" for nothing usable. */
30
+ export function sanitizeSpace(name) {
31
+ const s = String(name ?? "").replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 64);
32
+ return s === "" || s === "." || s === ".." || /^-+$/.test(s) ? "default" : s;
33
+ }
34
+
35
+ /** --space, else $NEXORUM_SPACE, else the name of the current folder. */
36
+ export function resolveSpace({ space, env = process.env, cwd = process.cwd() } = {}) {
37
+ const chosen = space ?? (env.NEXORUM_SPACE || undefined);
38
+ return sanitizeSpace(chosen !== undefined ? chosen : path.basename(path.resolve(cwd)));
39
+ }
40
+
41
+ export function isDocPath(p) {
42
+ return typeof p === "string" && p.length <= 200 && DOC_PATH_RE.test(p) && !p.includes("..") && !p.split("/").includes(".");
43
+ }
44
+
45
+ export function assertDocPath(p) {
46
+ if (!isDocPath(p)) throw new UsageError(`Invalid document path "${p}". Use something like /topic.md (letters, digits, . _ - and folders).`);
47
+ }
48
+
49
+ export function isSafeId(id) {
50
+ return typeof id === "string" && ID_RE.test(id) && id !== "." && id !== "..";
51
+ }
52
+
53
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
54
+
55
+ /** Temp file + rename. Windows can briefly refuse the rename while another process reads the file; retry a few times. */
56
+ export function atomicWrite(file, data) {
57
+ fs.mkdirSync(path.dirname(file), { recursive: true });
58
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString("hex")}`;
59
+ fs.writeFileSync(tmp, data);
60
+ let err;
61
+ for (let attempt = 1; attempt <= 8; attempt++) {
62
+ try {
63
+ fs.renameSync(tmp, file);
64
+ return;
65
+ } catch (e) {
66
+ err = e;
67
+ if (!["EPERM", "EACCES", "EBUSY"].includes(e.code)) break;
68
+ pause(20 * attempt);
69
+ }
70
+ }
71
+ fs.rmSync(tmp, { force: true });
72
+ throw err;
73
+ }
74
+
75
+ function readText(file) {
76
+ try {
77
+ return fs.readFileSync(file, "utf8");
78
+ } catch (e) {
79
+ if (e.code === "ENOENT") return null;
80
+ throw e;
81
+ }
82
+ }
83
+
84
+ function readJson(file, fallback) {
85
+ const text = readText(file);
86
+ if (text === null) return fallback;
87
+ try {
88
+ return JSON.parse(text);
89
+ } catch {
90
+ throw new CliError(`${file} is not valid JSON.`);
91
+ }
92
+ }
93
+
94
+ /** Unparsable lines are skipped. */
95
+ function readJsonLines(file) {
96
+ const text = readText(file);
97
+ if (text === null) return [];
98
+ const out = [];
99
+ for (const line of text.split("\n")) {
100
+ if (!line.trim()) continue;
101
+ try {
102
+ out.push(JSON.parse(line));
103
+ } catch {}
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** Appends one JSON line. If a crash left the last line without "\n", one is added first so both records survive. */
109
+ function appendJsonLine(file, value) {
110
+ let lead = "";
111
+ try {
112
+ const fd = fs.openSync(file, "r");
113
+ try {
114
+ const { size } = fs.fstatSync(fd);
115
+ if (size > 0) {
116
+ const last = Buffer.alloc(1);
117
+ fs.readSync(fd, last, 0, 1, size - 1);
118
+ if (last[0] !== 0x0a) lead = "\n";
119
+ }
120
+ } finally {
121
+ fs.closeSync(fd);
122
+ }
123
+ } catch (e) {
124
+ if (e.code !== "ENOENT") throw e;
125
+ }
126
+ fs.appendFileSync(file, `${lead}${JSON.stringify(value)}\n`);
127
+ }
128
+
129
+ /** Walks a wiki folder: valid document paths only, temp files skipped. `read` false counts without reading. */
130
+ function walkWiki(root, onFile) {
131
+ const walk = (dir, rel) => {
132
+ let entries;
133
+ try {
134
+ entries = fs.readdirSync(dir, { withFileTypes: true });
135
+ } catch (e) {
136
+ if (e.code === "ENOENT") return;
137
+ throw e;
138
+ }
139
+ for (const e of entries) {
140
+ const r = `${rel}/${e.name}`;
141
+ if (e.isDirectory()) walk(path.join(dir, e.name), r);
142
+ else if (e.isFile() && isDocPath(r) && !TMP_NAME_RE.test(e.name)) onFile(r, path.join(dir, e.name));
143
+ }
144
+ };
145
+ walk(root, "");
146
+ }
147
+
148
+ function readTree(root) {
149
+ const out = {};
150
+ walkWiki(root, (rel, file) => (out[rel] = fs.readFileSync(file, "utf8")));
151
+ return Object.fromEntries(Object.entries(out).sort(([a], [b]) => (a < b ? -1 : 1)));
152
+ }
153
+
154
+ const now = () => new Date().toISOString();
155
+ const linesOf = (records) => records.map((r) => `${JSON.stringify(r)}\n`).join("");
156
+
157
+ export class Store {
158
+ constructor(root, space) {
159
+ this.root = root;
160
+ this.space = space;
161
+ this.dir = path.join(root, "spaces", space);
162
+ this.wikiDir = path.join(this.dir, "wiki");
163
+ this.transcriptsDir = path.join(this.dir, "transcripts");
164
+ this.notesFile = path.join(this.dir, "notes.jsonl");
165
+ this.stateFile = path.join(this.dir, "state.json");
166
+ this.historyDir = path.join(this.dir, "history");
167
+ this.historyLog = path.join(this.historyDir, "log.jsonl");
168
+ this.historyFiles = path.join(this.historyDir, "files");
169
+ this.proposalsDir = path.join(this.dir, "proposals");
170
+ }
171
+
172
+ static open({ space, env = process.env, cwd } = {}) {
173
+ return new Store(nexorumRoot(env), resolveSpace({ space, env, cwd }));
174
+ }
175
+
176
+ // ---------------------------------------------------------------- notes
177
+ readNotes() {
178
+ return readJsonLines(this.notesFile).filter((n) => n && typeof n.id === "string" && typeof n.content === "string");
179
+ }
180
+
181
+ appendNote(content, metadata) {
182
+ const note = { id: newId("note"), ts: now(), content };
183
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) note.metadata = metadata;
184
+ fs.mkdirSync(this.dir, { recursive: true });
185
+ appendJsonLine(this.notesFile, note);
186
+ return note;
187
+ }
188
+
189
+ removeNote(id) {
190
+ const notes = this.readNotes();
191
+ const rest = notes.filter((n) => n.id !== id);
192
+ if (rest.length === notes.length) return false;
193
+ atomicWrite(this.notesFile, linesOf(rest));
194
+ return true;
195
+ }
196
+
197
+ /** Same id and position; `ts` becomes now (so the next dream rereads it) and the first time stays in created_at. */
198
+ updateNote(id, content, metadata) {
199
+ const notes = this.readNotes();
200
+ const i = notes.findIndex((n) => n.id === id);
201
+ if (i < 0) return null;
202
+ const old = notes[i];
203
+ notes[i] = { ...old, content, ts: now(), created_at: old.created_at ?? old.ts, ...(metadata !== undefined ? { metadata } : {}) };
204
+ atomicWrite(this.notesFile, linesOf(notes));
205
+ return notes[i];
206
+ }
207
+
208
+ // ---------------------------------------------------------------- state
209
+ readState() {
210
+ const s = readJson(this.stateFile, {});
211
+ return { notes_consolidated_through: typeof s?.notes_consolidated_through === "string" ? s.notes_consolidated_through : null };
212
+ }
213
+
214
+ writeState(state) {
215
+ atomicWrite(this.stateFile, `${JSON.stringify(state, null, 2)}\n`);
216
+ }
217
+
218
+ // ---------------------------------------------------------------- transcripts
219
+ transcriptFile(id) {
220
+ if (!isSafeId(id)) throw new UsageError(`Invalid transcript id "${id}" (letters, digits, _ . - only, up to 128 chars).`);
221
+ return path.join(this.transcriptsDir, `${id}.json`);
222
+ }
223
+
224
+ getTranscript(id) {
225
+ return readJson(this.transcriptFile(id), null);
226
+ }
227
+
228
+ saveTranscript(t) {
229
+ atomicWrite(this.transcriptFile(t.id), `${JSON.stringify(t)}\n`);
230
+ }
231
+
232
+ listTranscripts() {
233
+ let names;
234
+ try {
235
+ names = fs.readdirSync(this.transcriptsDir);
236
+ } catch (e) {
237
+ if (e.code === "ENOENT") return [];
238
+ throw e;
239
+ }
240
+ const out = [];
241
+ for (const n of names) {
242
+ if (!n.endsWith(".json")) continue;
243
+ try {
244
+ const t = JSON.parse(fs.readFileSync(path.join(this.transcriptsDir, n), "utf8"));
245
+ if (t && typeof t.id === "string" && Array.isArray(t.events)) out.push(t);
246
+ } catch {}
247
+ }
248
+ return out;
249
+ }
250
+
251
+ deleteTranscript(id) {
252
+ fs.rmSync(this.transcriptFile(id), { force: true });
253
+ }
254
+
255
+ /** Create, or update in place. Changed events make it pending again; identical events change nothing. */
256
+ upsertTranscript({ id, source, externalId = null, events, namespace }) {
257
+ const existing = this.getTranscript(id);
258
+ const ts = now();
259
+ if (existing) {
260
+ if (sha256Hex(JSON.stringify(existing.events)) === sha256Hex(JSON.stringify(events))) return { transcript: existing, changed: false };
261
+ const t = { ...existing, source: source ?? existing.source, events, updated_at: ts, status: "pending", dreamed_at: null };
262
+ this.saveTranscript(t);
263
+ return { transcript: t, changed: true };
264
+ }
265
+ const t = { id, source, external_id: externalId, namespace: namespace ?? this.space, created_at: ts, updated_at: ts, status: "pending", dreamed_at: null, events };
266
+ this.saveTranscript(t);
267
+ return { transcript: t, changed: true };
268
+ }
269
+
270
+ // ---------------------------------------------------------------- live wiki
271
+ docFile(p) {
272
+ assertDocPath(p);
273
+ return path.join(this.wikiDir, ...p.slice(1).split("/"));
274
+ }
275
+
276
+ readDoc(p) {
277
+ try {
278
+ return fs.readFileSync(this.docFile(p), "utf8");
279
+ } catch (e) {
280
+ if (["ENOENT", "EISDIR", "ENOTDIR"].includes(e.code)) return null;
281
+ throw e;
282
+ }
283
+ }
284
+
285
+ wikiSnapshot() {
286
+ return readTree(this.wikiDir);
287
+ }
288
+
289
+ /** Number of wiki pages, without reading them. */
290
+ wikiCount() {
291
+ let n = 0;
292
+ walkWiki(this.wikiDir, () => n++);
293
+ return n;
294
+ }
295
+
296
+ // ---------------------------------------------------------------- history
297
+ readHistory() {
298
+ return readJsonLines(this.historyLog);
299
+ }
300
+
301
+ /** Entries of one path, oldest first, numbered from 1. */
302
+ versionsOf(p) {
303
+ return this.readHistory()
304
+ .filter((e) => e.path === p)
305
+ .map((e, i) => ({ ...e, version: i + 1 }));
306
+ }
307
+
308
+ readSnapshotFile(file) {
309
+ if (!isSafeId(file)) return null; // names are "<n>-<sha8>"; nothing else may reach the file system
310
+ return readText(path.join(this.historyFiles, file));
311
+ }
312
+
313
+ #record({ p, operation, actor, content }) {
314
+ let sha = null;
315
+ let file = null;
316
+ if (content !== null) {
317
+ sha = sha256Hex(content);
318
+ file = `${this.readHistory().length + 1}-${sha.slice(0, 8)}`;
319
+ atomicWrite(path.join(this.historyFiles, file), content);
320
+ }
321
+ const entry = { ts: now(), path: p, operation, actor, sha256: sha, file };
322
+ fs.mkdirSync(this.historyDir, { recursive: true });
323
+ appendJsonLine(this.historyLog, entry);
324
+ return entry;
325
+ }
326
+
327
+ /** A page edited by hand since its last recorded version is recorded first (actor "user"), so it stays restorable. */
328
+ #keepHandEdit(p, current) {
329
+ if (current === null) return;
330
+ const last = this.versionsOf(p).at(-1);
331
+ if (last && last.sha256 === sha256Hex(current)) return;
332
+ this.#record({ p, operation: last ? "update" : "create", actor: "user", content: current });
333
+ }
334
+
335
+ /** Writes one live page and records it. Returns the history entry, or null when the content is unchanged. */
336
+ writeDoc(p, content, { actor = "user", operation } = {}) {
337
+ const file = this.docFile(p);
338
+ const current = this.readDoc(p);
339
+ if (current === content) return null;
340
+ this.#keepHandEdit(p, current);
341
+ const entry = this.#record({ p, operation: operation ?? (current === null ? "create" : "update"), actor, content });
342
+ atomicWrite(file, content);
343
+ return entry;
344
+ }
345
+
346
+ deleteDoc(p, { actor = "user" } = {}) {
347
+ const file = this.docFile(p);
348
+ const current = this.readDoc(p);
349
+ if (current === null) return null;
350
+ this.#keepHandEdit(p, current);
351
+ const entry = this.#record({ p, operation: "delete", actor, content: null });
352
+ fs.rmSync(file, { force: true });
353
+ // Remove folders the deletion left empty.
354
+ for (let dir = path.dirname(file); dir !== this.wikiDir && dir.startsWith(this.wikiDir); dir = path.dirname(dir)) {
355
+ try {
356
+ fs.rmdirSync(dir);
357
+ } catch {
358
+ break;
359
+ }
360
+ }
361
+ return entry;
362
+ }
363
+
364
+ // ---------------------------------------------------------------- proposals
365
+ proposalDir(id) {
366
+ if (!isSafeId(id)) throw new UsageError(`Invalid proposal id "${id}".`);
367
+ return path.join(this.proposalsDir, id);
368
+ }
369
+
370
+ newProposalId() {
371
+ const stamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
372
+ return `dream-${stamp}-${crypto.randomBytes(3).toString("hex")}`;
373
+ }
374
+
375
+ readProposal(id) {
376
+ return readJson(path.join(this.proposalDir(id), "proposal.json"), null);
377
+ }
378
+
379
+ writeProposal(p) {
380
+ atomicWrite(path.join(this.proposalDir(p.id), "proposal.json"), `${JSON.stringify(p, null, 2)}\n`);
381
+ }
382
+
383
+ readBase(id) {
384
+ return readJson(path.join(this.proposalDir(id), "base.json"), {});
385
+ }
386
+
387
+ writeBase(id, base) {
388
+ atomicWrite(path.join(this.proposalDir(id), "base.json"), `${JSON.stringify(base, null, 2)}\n`);
389
+ }
390
+
391
+ proposalWikiDir(id) {
392
+ return path.join(this.proposalDir(id), "wiki");
393
+ }
394
+
395
+ /** Replaces the staged copy with `snapshot` ({path: content}). */
396
+ writeProposalWiki(id, snapshot) {
397
+ const dir = this.proposalWikiDir(id);
398
+ fs.rmSync(dir, { recursive: true, force: true });
399
+ fs.mkdirSync(dir, { recursive: true });
400
+ for (const [p, content] of Object.entries(snapshot)) {
401
+ assertDocPath(p);
402
+ atomicWrite(path.join(dir, ...p.slice(1).split("/")), content);
403
+ }
404
+ }
405
+
406
+ readProposalWiki(id) {
407
+ return readTree(this.proposalWikiDir(id));
408
+ }
409
+
410
+ /** Oldest first. Folders without a readable proposal.json (open agent-dream drafts) are left out. */
411
+ listProposals() {
412
+ let names;
413
+ try {
414
+ names = fs.readdirSync(this.proposalsDir);
415
+ } catch (e) {
416
+ if (e.code === "ENOENT") return [];
417
+ throw e;
418
+ }
419
+ const out = [];
420
+ for (const n of names) {
421
+ if (!isSafeId(n)) continue;
422
+ try {
423
+ const p = this.readProposal(n);
424
+ if (p && p.id === n) out.push(p);
425
+ } catch {}
426
+ }
427
+ return out.sort((a, b) => (a.created_at < b.created_at ? -1 : a.created_at > b.created_at ? 1 : a.id < b.id ? -1 : 1));
428
+ }
429
+
430
+ /** By id or unique id prefix; without one, the newest proposal in `preferStatus`, else the newest of all. */
431
+ pickProposal(id, preferStatus = "review") {
432
+ const all = this.listProposals();
433
+ if (id) {
434
+ const exact = all.find((p) => p.id === id);
435
+ if (exact) return exact;
436
+ const hits = all.filter((p) => p.id.startsWith(id));
437
+ if (hits.length === 1) return hits[0];
438
+ if (hits.length > 1) throw new UsageError(`"${id}" matches several proposals; use a longer id.`);
439
+ throw new CliError(`No proposal "${id}" in space "${this.space}". Run: nexorum proposals`);
440
+ }
441
+ const chosen = all.filter((p) => p.status === preferStatus).at(-1) ?? all.at(-1);
442
+ if (!chosen) throw new CliError(`No proposals in space "${this.space}". Run: nexorum dream`);
443
+ return chosen;
444
+ }
445
+ }
@@ -0,0 +1,40 @@
1
+ // Transcripts from agents without hooks: `nexorum log` and the save_transcript MCP tool.
2
+ import { scrubSecrets, newId } from "./core/index.js";
3
+ import { UsageError } from "./args.js";
4
+ import { isSafeId } from "./store.js";
5
+
6
+ export const ROLES = new Set(["user", "assistant", "system", "tool"]);
7
+ export const MAX_EVENTS = 5000;
8
+ export const MAX_TRANSCRIPT_CHARS = 2_000_000;
9
+
10
+ /** Validates {role, content, name?, ts?} events and redacts secrets. Throws UsageError. */
11
+ export function normalizeEvents(list) {
12
+ if (!Array.isArray(list) || list.length === 0) throw new UsageError("Expected a non-empty array of events ({role, content}).");
13
+ if (list.length > MAX_EVENTS) throw new UsageError(`At most ${MAX_EVENTS} events per transcript (got ${list.length}); split it or send the most recent ones.`);
14
+ let chars = 0;
15
+ const events = list.map((e, i) => {
16
+ if (!e || typeof e !== "object" || !ROLES.has(e.role)) throw new UsageError(`Event ${i}: role must be one of user, assistant, system, tool.`);
17
+ const content = typeof e.content === "string" ? e.content : JSON.stringify(e.content ?? "");
18
+ chars += content.length;
19
+ const ev = { role: e.role, content: scrubSecrets(content).text };
20
+ if (typeof e.name === "string") ev.name = e.name;
21
+ if (typeof e.ts === "string" || typeof e.ts === "number") ev.ts = e.ts;
22
+ return ev;
23
+ });
24
+ if (chars > MAX_TRANSCRIPT_CHARS) throw new UsageError(`Transcript is ${chars} characters; the limit is ${MAX_TRANSCRIPT_CHARS}. Send the most recent part.`);
25
+ return events;
26
+ }
27
+
28
+ /**
29
+ * Stores a session. The same id replaces it, and it becomes pending again only when the events changed, so an
30
+ * agent can re-send a growing session.
31
+ * @returns {{id:string, count:number, changed:boolean, status:string}}
32
+ */
33
+ export function saveTranscript(store, { events, id, source }) {
34
+ const clean = normalizeEvents(events);
35
+ const tid = id ?? newId("trn");
36
+ if (!isSafeId(tid)) throw new UsageError("id may only contain letters, digits, _ . - (up to 128 characters).");
37
+ const src = typeof source === "string" && source ? source.slice(0, 64) : "mcp";
38
+ const { transcript, changed } = store.upsertTranscript({ id: tid, source: src, externalId: id ?? null, events: clean });
39
+ return { id: transcript.id, count: clean.length, changed, status: transcript.status };
40
+ }
package/src/version.js ADDED
@@ -0,0 +1,4 @@
1
+ // The version printed by --version and reported by the MCP server: always the one in package.json.
2
+ import fs from "node:fs";
3
+
4
+ export const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;