open-memex 0.3.0 → 0.4.0-alpha.4
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/AGENTS.md +12 -1
- package/README.md +78 -8
- package/README.zh-CN.md +67 -7
- package/dist/cli.js +389 -12
- package/dist/config.js +10 -0
- package/dist/github.js +215 -0
- package/dist/index.js +6 -0
- package/dist/init.js +33 -18
- package/dist/mcp.js +71 -9
- package/dist/paths.js +31 -0
- package/dist/retrieve/inject.js +2 -2
- package/dist/retrieve/search.js +31 -6
- package/dist/review.js +437 -0
- package/dist/store/db.js +3 -2
- package/dist/store/lifecycle.js +28 -13
- package/dist/store/markdown.js +49 -8
- package/dist/store/sync.js +74 -6
- package/dist/submit.js +339 -0
- package/dist/tools/ops.js +163 -6
- package/docs/USER-GUIDE.md +195 -0
- package/docs/USER-GUIDE.zh-CN.md +160 -0
- package/docs/V2-DESIGN.md +129 -6
- package/package.json +1 -1
- package/scripts/smoke-mcp.ts +2 -2
- package/src/cli.ts +401 -13
- package/src/config.ts +16 -0
- package/src/github.ts +257 -0
- package/src/index.ts +6 -0
- package/src/init.ts +33 -17
- package/src/mcp.ts +117 -8
- package/src/paths.ts +32 -0
- package/src/retrieve/inject.ts +2 -2
- package/src/retrieve/search.ts +33 -6
- package/src/review.ts +504 -0
- package/src/store/db.ts +3 -2
- package/src/store/lifecycle.ts +30 -12
- package/src/store/markdown.ts +83 -8
- package/src/store/sync.ts +85 -4
- package/src/submit.ts +411 -0
- package/src/tools/ops.ts +192 -7
package/dist/review.js
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 2B/D26: propose → submit → promote → resolve workflow.
|
|
3
|
+
*
|
|
4
|
+
* - `propose <id> --to project`: copy a personal memory into the project
|
|
5
|
+
* outbox (appdata) as a draft. Never moves — the personal original stays
|
|
6
|
+
* put. Outbox drafts are git-invisible until submitted.
|
|
7
|
+
* - `submit <ids>`: move outbox drafts into a git branch (new `mem/sync-*`
|
|
8
|
+
* by default), as `proposed`, commit locally, print push + PR commands.
|
|
9
|
+
* Push/PR need the user's explicit approval — the tool never pushes.
|
|
10
|
+
* - `promote <id>`: advance a project memory one step up the review ladder
|
|
11
|
+
* (proposed → approved → published), or --reject it with a note.
|
|
12
|
+
* - `resolve [id]`: assist with git merge conflicts inside the in-repo
|
|
13
|
+
* memory dir. Frontmatter gets a field-level 3-way merge; semantic
|
|
14
|
+
* conflicts are reported, never auto-resolved.
|
|
15
|
+
*
|
|
16
|
+
* Git automation line (D25 as revised by D26): local git only (submit's
|
|
17
|
+
* branch + commit). Nothing leaves the machine without approval.
|
|
18
|
+
*/
|
|
19
|
+
import { execFileSync } from "node:child_process";
|
|
20
|
+
import * as fs from "node:fs";
|
|
21
|
+
import * as os from "node:os";
|
|
22
|
+
import * as path from "node:path";
|
|
23
|
+
import { loadConfig } from "./config.js";
|
|
24
|
+
import { inRepoMemoriesDirPath, projectRoot } from "./paths.js";
|
|
25
|
+
import { resolveProjectScope } from "./scope.js";
|
|
26
|
+
import { parse as parseMemory, serialize, ulid, writeMemoryFile, } from "./store/markdown.js";
|
|
27
|
+
import { findMemoryFile } from "./store/lifecycle.js";
|
|
28
|
+
import { upsertFromFile } from "./store/sync.js";
|
|
29
|
+
/** Best-effort author identity: git user.name, else the OS user. */
|
|
30
|
+
export function currentAuthor() {
|
|
31
|
+
try {
|
|
32
|
+
const name = execFileSync("git", ["config", "user.name"], {
|
|
33
|
+
encoding: "utf8",
|
|
34
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
35
|
+
}).trim();
|
|
36
|
+
if (name)
|
|
37
|
+
return name;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
/* git unavailable — fall through */
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
return os.userInfo().username || "unknown";
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return "unknown";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function fail(msg) {
|
|
50
|
+
throw new Error(`[open-memex] ${msg}`);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Copy one personal memory into the project scope as a review candidate.
|
|
54
|
+
* The source memory is untouched (copy, not move — D25).
|
|
55
|
+
* Batch-friendly: validates nothing, copies one — use proposeMemories()
|
|
56
|
+
* for the all-or-nothing multi-id path.
|
|
57
|
+
*/
|
|
58
|
+
export function proposeMemory(sourceId, opts = {}) {
|
|
59
|
+
const src = findMemoryFile(sourceId);
|
|
60
|
+
if (!src)
|
|
61
|
+
fail(`no memory found with id "${sourceId}".`);
|
|
62
|
+
return copyPersonalToProject(sourceId, src.fm, src.body, opts);
|
|
63
|
+
}
|
|
64
|
+
function copyPersonalToProject(sourceId, srcFm, srcBody, opts = {}) {
|
|
65
|
+
if (srcFm.scope === "project")
|
|
66
|
+
fail(`memory "${sourceId}" is already in project scope — nothing to propose.`);
|
|
67
|
+
if (srcFm.scope === "org")
|
|
68
|
+
fail(`memory "${sourceId}" is already shared at org scope.`);
|
|
69
|
+
if (srcFm.status === "retracted" || srcFm.status === "archived")
|
|
70
|
+
fail(`memory "${sourceId}" is ${srcFm.status} — cannot propose it.`);
|
|
71
|
+
const project = resolveProjectScope(projectRoot());
|
|
72
|
+
const author = currentAuthor();
|
|
73
|
+
const now = new Date().toISOString();
|
|
74
|
+
// propose lands in the outbox as a draft (submit moves it to proposed);
|
|
75
|
+
// --local-approve is the solo-dev shortcut straight to approved.
|
|
76
|
+
const targetState = opts.localApprove ? "approved" : "draft";
|
|
77
|
+
const fm = {
|
|
78
|
+
...srcFm,
|
|
79
|
+
id: ulid(),
|
|
80
|
+
scope: "project",
|
|
81
|
+
scope_key: project.key,
|
|
82
|
+
project_name: project.projectName,
|
|
83
|
+
created_at: now,
|
|
84
|
+
updated_at: now,
|
|
85
|
+
supersedes: null,
|
|
86
|
+
superseded_by: null,
|
|
87
|
+
review_state: targetState,
|
|
88
|
+
proposed_by: author,
|
|
89
|
+
approved_by: opts.localApprove ? author : null,
|
|
90
|
+
derived_from: srcFm.id,
|
|
91
|
+
review_history: [
|
|
92
|
+
{
|
|
93
|
+
at: now,
|
|
94
|
+
by: author,
|
|
95
|
+
from: "draft",
|
|
96
|
+
to: targetState,
|
|
97
|
+
note: opts.localApprove
|
|
98
|
+
? `proposed from personal memory ${srcFm.id} (local-approved)`
|
|
99
|
+
: `proposed from personal memory ${srcFm.id}`,
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
};
|
|
103
|
+
const { filePath } = writeMemoryFile(fm, srcBody);
|
|
104
|
+
upsertFromFile({ fm, body: srcBody, filePath, mtimeMs: Date.now() });
|
|
105
|
+
return { id: fm.id, filePath, reviewState: fm.review_state };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Propose several personal memories at once — one branch, one PR.
|
|
109
|
+
* All-or-nothing: every id is validated before anything is copied, so a bad
|
|
110
|
+
* id never leaves a half-proposed batch behind.
|
|
111
|
+
*/
|
|
112
|
+
export function proposeMemories(sourceIds, opts = {}) {
|
|
113
|
+
if (sourceIds.length === 0)
|
|
114
|
+
fail("propose needs at least one memory id.");
|
|
115
|
+
const seen = new Set();
|
|
116
|
+
const sources = sourceIds.map((sourceId) => {
|
|
117
|
+
if (seen.has(sourceId))
|
|
118
|
+
fail(`duplicate id "${sourceId}" — list each memory once.`);
|
|
119
|
+
seen.add(sourceId);
|
|
120
|
+
const src = findMemoryFile(sourceId);
|
|
121
|
+
if (!src)
|
|
122
|
+
fail(`no memory found with id "${sourceId}".`);
|
|
123
|
+
if (src.fm.scope !== "personal")
|
|
124
|
+
fail(`only personal memories can be proposed (memory "${sourceId}" is ${src.fm.scope}).`);
|
|
125
|
+
if (src.fm.status === "retracted" || src.fm.status === "archived")
|
|
126
|
+
fail(`memory "${sourceId}" is ${src.fm.status} — cannot propose it.`);
|
|
127
|
+
return { sourceId, fm: src.fm, body: src.body };
|
|
128
|
+
});
|
|
129
|
+
return sources.map(({ sourceId, fm, body }) => ({
|
|
130
|
+
sourceId,
|
|
131
|
+
result: copyPersonalToProject(sourceId, fm, body, opts),
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
134
|
+
const NEXT_STATE = {
|
|
135
|
+
proposed: "approved",
|
|
136
|
+
approved: "published",
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Advance a project memory one step up the review ladder
|
|
140
|
+
* (proposed → approved → published), reject it with --reject, or send a
|
|
141
|
+
* rejected memory back for another round with --resubmit.
|
|
142
|
+
*
|
|
143
|
+
* A rejection never deletes anything: the file stays on the author's branch.
|
|
144
|
+
* What happens next is the human's call — accept it (close the PR, delete the
|
|
145
|
+
* branch), revise + --resubmit, or keep the rejected file as a record.
|
|
146
|
+
*/
|
|
147
|
+
export function promoteMemory(id, opts = {}) {
|
|
148
|
+
const mf = findMemoryFile(id);
|
|
149
|
+
if (!mf)
|
|
150
|
+
fail(`no memory found with id "${id}".`);
|
|
151
|
+
if (mf.fm.scope !== "project")
|
|
152
|
+
fail(`only project-scope memories go through review (memory "${id}" is ${mf.fm.scope}).`);
|
|
153
|
+
const from = mf.fm.review_state ?? "draft";
|
|
154
|
+
const by = opts.by?.trim() || currentAuthor();
|
|
155
|
+
let to;
|
|
156
|
+
if (opts.resubmit) {
|
|
157
|
+
if (opts.reject)
|
|
158
|
+
fail("choose one: --resubmit or --reject, not both.");
|
|
159
|
+
if (from !== "rejected")
|
|
160
|
+
fail(`only a "rejected" memory can be resubmitted (memory "${id}" is "${from}").`);
|
|
161
|
+
to = "proposed";
|
|
162
|
+
}
|
|
163
|
+
else if (opts.reject) {
|
|
164
|
+
if (from !== "proposed" && from !== "approved")
|
|
165
|
+
fail(`cannot reject from "${from}" — only "proposed" or "approved" can be rejected.`);
|
|
166
|
+
to = "rejected";
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
const next = NEXT_STATE[from];
|
|
170
|
+
if (!next)
|
|
171
|
+
fail(from === "draft"
|
|
172
|
+
? `memory "${id}" is still a draft — run "open-memex propose ${id} --to project" first.`
|
|
173
|
+
: `memory "${id}" is "${from}" — a terminal state, nothing to promote.`);
|
|
174
|
+
to = next;
|
|
175
|
+
}
|
|
176
|
+
const fm = {
|
|
177
|
+
...mf.fm,
|
|
178
|
+
review_state: to,
|
|
179
|
+
updated_at: new Date().toISOString(),
|
|
180
|
+
// A rejection withdraws any earlier approval; a resubmission clears it too
|
|
181
|
+
// (the memory must earn approval again).
|
|
182
|
+
approved_by: to === "approved" ? by : to === "rejected" || to === "proposed" ? null : mf.fm.approved_by,
|
|
183
|
+
review_note: opts.note?.trim() ? opts.note.trim() : mf.fm.review_note,
|
|
184
|
+
// D29: every transition is appended to the audit trail — the note is
|
|
185
|
+
// preserved here even when review_note later gets overwritten.
|
|
186
|
+
review_history: [
|
|
187
|
+
...(mf.fm.review_history ?? []),
|
|
188
|
+
{
|
|
189
|
+
at: new Date().toISOString(),
|
|
190
|
+
by,
|
|
191
|
+
from,
|
|
192
|
+
to,
|
|
193
|
+
note: opts.note?.trim() ? opts.note.trim() : null,
|
|
194
|
+
},
|
|
195
|
+
],
|
|
196
|
+
};
|
|
197
|
+
fs.writeFileSync(mf.filePath, serialize(fm, mf.body), "utf8");
|
|
198
|
+
upsertFromFile({ fm, body: mf.body, filePath: mf.filePath, mtimeMs: Date.now() });
|
|
199
|
+
return { id, from, to, history: fm.review_history };
|
|
200
|
+
}
|
|
201
|
+
/** Render a memory's audit trail as compact human-readable lines (D29). */
|
|
202
|
+
export function formatReviewHistory(history) {
|
|
203
|
+
return history.map((t) => ` ${t.at.slice(0, 10)} ${t.by}: ${t.from} → ${t.to}` +
|
|
204
|
+
(t.note ? ` — ${t.note}` : ""));
|
|
205
|
+
}
|
|
206
|
+
function git(args, cwd) {
|
|
207
|
+
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
208
|
+
}
|
|
209
|
+
function inRepoDir() {
|
|
210
|
+
const root = projectRoot();
|
|
211
|
+
try {
|
|
212
|
+
git(["rev-parse", "--git-dir"], root);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
fail("resolve needs a git repo — this directory is not one.");
|
|
216
|
+
}
|
|
217
|
+
return { root, dir: inRepoMemoriesDirPath(root, loadConfig().memoryDir) };
|
|
218
|
+
}
|
|
219
|
+
/** List in-repo memory files currently in an unmerged (conflicted) state. */
|
|
220
|
+
export function listConflicts() {
|
|
221
|
+
const { root, dir } = inRepoDir();
|
|
222
|
+
let out;
|
|
223
|
+
try {
|
|
224
|
+
out = git(["diff", "--name-only", "--diff-filter=U", "--", dir], root);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
fail("git is unavailable or the repo state cannot be read.");
|
|
228
|
+
}
|
|
229
|
+
return out
|
|
230
|
+
.split("\n")
|
|
231
|
+
.map((s) => s.trim())
|
|
232
|
+
.filter((s) => s && s.endsWith(".md"))
|
|
233
|
+
.map((rel) => ({
|
|
234
|
+
id: path.basename(rel, ".md"),
|
|
235
|
+
filePath: path.join(root, rel),
|
|
236
|
+
}));
|
|
237
|
+
}
|
|
238
|
+
function show(v) {
|
|
239
|
+
if (v === null || v === undefined)
|
|
240
|
+
return "(empty)";
|
|
241
|
+
if (Array.isArray(v))
|
|
242
|
+
return v.length ? v.join(", ") : "(empty)";
|
|
243
|
+
return String(v);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Attempt a field-level 3-way merge of a conflicted memory file.
|
|
247
|
+
* Never auto-resolves semantic conflicts (same field changed differently
|
|
248
|
+
* on both sides) — those are reported for the human to decide.
|
|
249
|
+
*/
|
|
250
|
+
export function resolveConflict(target) {
|
|
251
|
+
const { root, dir } = inRepoDir();
|
|
252
|
+
// Locate the file: by memory id, or as a direct path. Note findMemoryFile
|
|
253
|
+
// returns null for a file with conflict markers (YAML won't parse), so
|
|
254
|
+
// fall back to a direct <id>.md lookup inside the in-repo dir.
|
|
255
|
+
let filePath = null;
|
|
256
|
+
const byId = findMemoryFile(target);
|
|
257
|
+
if (byId) {
|
|
258
|
+
filePath = byId.filePath;
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
const base = path.basename(target).replace(/\.md$/, "");
|
|
262
|
+
const candidates = [
|
|
263
|
+
path.join(dir, `${base}.md`),
|
|
264
|
+
path.isAbsolute(target) ? target : path.join(root, target),
|
|
265
|
+
path.isAbsolute(target) ? `${target}.md` : path.join(root, `${target}.md`),
|
|
266
|
+
];
|
|
267
|
+
for (const c of candidates) {
|
|
268
|
+
if (fs.existsSync(c) && fs.statSync(c).isFile()) {
|
|
269
|
+
filePath = c;
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (!filePath)
|
|
275
|
+
fail(`no memory or file found for "${target}".`);
|
|
276
|
+
// Must actually be in conflict (stages 1/2/3 present).
|
|
277
|
+
const stages = git(["ls-files", "-u", "--", filePath], root)
|
|
278
|
+
.split("\n")
|
|
279
|
+
.map((l) => l.trim())
|
|
280
|
+
.filter(Boolean);
|
|
281
|
+
if (stages.length === 0)
|
|
282
|
+
fail(`"${path.basename(filePath)}" is not in a merge-conflict state.`);
|
|
283
|
+
const blob = (stage) => {
|
|
284
|
+
// Git wants forward slashes even on Windows.
|
|
285
|
+
const rel = path.relative(root, filePath).split(path.sep).join("/");
|
|
286
|
+
try {
|
|
287
|
+
return git(["show", `:${stage}:${rel}`], root);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
fail(`cannot read git stage ${stage} for "${path.basename(filePath)}".`);
|
|
291
|
+
throw new Error("unreachable");
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
const base = parseMemory(blob("1"));
|
|
295
|
+
const ours = parseMemory(blob("2"));
|
|
296
|
+
const theirs = parseMemory(blob("3"));
|
|
297
|
+
if (!base || !ours || !theirs)
|
|
298
|
+
fail(`one of the conflict stages for "${path.basename(filePath)}" is not a valid memory file.`);
|
|
299
|
+
const b = base.fm;
|
|
300
|
+
const o = ours.fm;
|
|
301
|
+
const t = theirs.fm;
|
|
302
|
+
const conflicts = [];
|
|
303
|
+
const autoMerged = [];
|
|
304
|
+
const merged = {};
|
|
305
|
+
// Identity fields: both sides must agree, else this is not the same memory.
|
|
306
|
+
for (const f of ["id", "scope_key", "scope", "project_name", "schema_version"]) {
|
|
307
|
+
if (o[f] !== t[f]) {
|
|
308
|
+
conflicts.push({ field: f, base: show(b[f]), ours: show(o[f]), theirs: show(t[f]) });
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
merged[f] = o[f];
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
// Plain scalar fields: standard 3-way.
|
|
315
|
+
const scalars = [
|
|
316
|
+
"visibility",
|
|
317
|
+
"type",
|
|
318
|
+
"role",
|
|
319
|
+
"importance",
|
|
320
|
+
"status",
|
|
321
|
+
"source",
|
|
322
|
+
"created_at",
|
|
323
|
+
"proposed_by",
|
|
324
|
+
"approved_by",
|
|
325
|
+
"derived_from",
|
|
326
|
+
"review_note",
|
|
327
|
+
"supersedes",
|
|
328
|
+
"superseded_by",
|
|
329
|
+
];
|
|
330
|
+
for (const f of scalars) {
|
|
331
|
+
const bv = b[f];
|
|
332
|
+
const ov = o[f];
|
|
333
|
+
const tv = t[f];
|
|
334
|
+
if (eq(ov, tv)) {
|
|
335
|
+
merged[f] = ov;
|
|
336
|
+
}
|
|
337
|
+
else if (eq(bv, ov)) {
|
|
338
|
+
merged[f] = tv;
|
|
339
|
+
autoMerged.push(f);
|
|
340
|
+
}
|
|
341
|
+
else if (eq(bv, tv)) {
|
|
342
|
+
merged[f] = ov;
|
|
343
|
+
autoMerged.push(f);
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
conflicts.push({ field: f, base: show(bv), ours: show(ov), theirs: show(tv) });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
// review_state: 3-way, but never silently drop a rejection.
|
|
350
|
+
{
|
|
351
|
+
const bv = b.review_state;
|
|
352
|
+
const ov = o.review_state;
|
|
353
|
+
const tv = t.review_state;
|
|
354
|
+
if (ov === tv)
|
|
355
|
+
merged.review_state = ov;
|
|
356
|
+
else if (bv === ov)
|
|
357
|
+
merged.review_state = tv;
|
|
358
|
+
else if (bv === tv)
|
|
359
|
+
merged.review_state = ov;
|
|
360
|
+
else if (ov === "rejected" || tv === "rejected")
|
|
361
|
+
conflicts.push({ field: "review_state", base: bv, ours: ov, theirs: tv });
|
|
362
|
+
else {
|
|
363
|
+
// Both advanced along the ladder; keep the further one.
|
|
364
|
+
const order = ["draft", "proposed", "approved", "published"];
|
|
365
|
+
merged.review_state = order.indexOf(tv) > order.indexOf(ov) ? tv : ov;
|
|
366
|
+
}
|
|
367
|
+
if (!conflicts.some((c) => c.field === "review_state") && merged.review_state !== bv)
|
|
368
|
+
autoMerged.push("review_state");
|
|
369
|
+
}
|
|
370
|
+
// tags: union when both sides changed.
|
|
371
|
+
{
|
|
372
|
+
const bs = new Set(b.tags ?? []);
|
|
373
|
+
const os = new Set(o.tags ?? []);
|
|
374
|
+
const ts = new Set(t.tags ?? []);
|
|
375
|
+
if (eq([...os].sort(), [...ts].sort()))
|
|
376
|
+
merged.tags = [...os];
|
|
377
|
+
else {
|
|
378
|
+
const union = [...new Set([...os, ...ts])].sort();
|
|
379
|
+
merged.tags = union;
|
|
380
|
+
if (!eq([...bs].sort(), union))
|
|
381
|
+
autoMerged.push("tags");
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
// review_history (D29 audit trail): union by identity — a transition that
|
|
385
|
+
// happened on either side is kept; identical entries collapse.
|
|
386
|
+
{
|
|
387
|
+
const key = (e) => `${e.at}|${e.by}|${e.from}|${e.to}`;
|
|
388
|
+
const seen = new Set();
|
|
389
|
+
const union = [];
|
|
390
|
+
const all = [...(b.review_history ?? []), ...(o.review_history ?? []), ...(t.review_history ?? [])];
|
|
391
|
+
for (const e of all) {
|
|
392
|
+
const k = key(e);
|
|
393
|
+
if (!seen.has(k)) {
|
|
394
|
+
seen.add(k);
|
|
395
|
+
union.push(e);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
merged.review_history = union;
|
|
399
|
+
if (union.length !== (b.review_history ?? []).length)
|
|
400
|
+
autoMerged.push("review_history");
|
|
401
|
+
}
|
|
402
|
+
// updated_at: always moves forward — take the latest.
|
|
403
|
+
{
|
|
404
|
+
const latest = [b.updated_at, o.updated_at, t.updated_at].sort().at(-1);
|
|
405
|
+
merged.updated_at = latest;
|
|
406
|
+
if (latest !== b.updated_at)
|
|
407
|
+
autoMerged.push("updated_at");
|
|
408
|
+
}
|
|
409
|
+
// body: 3-way text merge; divergent edits are a human decision.
|
|
410
|
+
const bb = base.body.trimEnd();
|
|
411
|
+
const ob = ours.body.trimEnd();
|
|
412
|
+
const tb = theirs.body.trimEnd();
|
|
413
|
+
let mergedBody;
|
|
414
|
+
if (ob === tb)
|
|
415
|
+
mergedBody = ob;
|
|
416
|
+
else if (bb === ob) {
|
|
417
|
+
mergedBody = tb;
|
|
418
|
+
autoMerged.push("body");
|
|
419
|
+
}
|
|
420
|
+
else if (bb === tb) {
|
|
421
|
+
mergedBody = ob;
|
|
422
|
+
autoMerged.push("body");
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
conflicts.push({ field: "body", base: bb.slice(0, 120), ours: ob.slice(0, 120), theirs: tb.slice(0, 120) });
|
|
426
|
+
mergedBody = bb; // unused when conflicts exist
|
|
427
|
+
}
|
|
428
|
+
if (conflicts.length > 0)
|
|
429
|
+
return { ok: false, filePath, conflicts };
|
|
430
|
+
const fm = merged;
|
|
431
|
+
fs.writeFileSync(filePath, serialize(fm, mergedBody), "utf8");
|
|
432
|
+
upsertFromFile({ fm, body: mergedBody, filePath, mtimeMs: Date.now() });
|
|
433
|
+
return { ok: true, filePath, autoMerged: [...new Set(autoMerged)] };
|
|
434
|
+
}
|
|
435
|
+
function eq(a, b) {
|
|
436
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
437
|
+
}
|
package/dist/store/db.js
CHANGED
|
@@ -34,7 +34,8 @@ CREATE TABLE IF NOT EXISTS memories (
|
|
|
34
34
|
file_path TEXT NOT NULL,
|
|
35
35
|
mtime_ms REAL NOT NULL,
|
|
36
36
|
created_at INTEGER NOT NULL,
|
|
37
|
-
updated_at INTEGER NOT NULL
|
|
37
|
+
updated_at INTEGER NOT NULL,
|
|
38
|
+
review_state TEXT NOT NULL DEFAULT 'draft'
|
|
38
39
|
);
|
|
39
40
|
|
|
40
41
|
CREATE INDEX IF NOT EXISTS idx_memories_scope_updated
|
|
@@ -77,7 +78,7 @@ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
|
77
78
|
END;
|
|
78
79
|
`;
|
|
79
80
|
/** Current index schema version. Bump when TABLE_SCHEMA/FTS_SCHEMA change. */
|
|
80
|
-
const SCHEMA_VERSION =
|
|
81
|
+
const SCHEMA_VERSION = 6;
|
|
81
82
|
function userVersion(d) {
|
|
82
83
|
const row = d.prepare("PRAGMA user_version").get();
|
|
83
84
|
return row.user_version;
|
package/dist/store/lifecycle.js
CHANGED
|
@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { db } from "./db.js";
|
|
5
|
-
import { paths,
|
|
5
|
+
import { paths, projectRoot, inRepoMemoriesDirPath, } from "../paths.js";
|
|
6
|
+
import { loadConfig } from "../config.js";
|
|
6
7
|
import { cjkIndexText } from "../retrieve/cjk.js";
|
|
7
8
|
import { parse, serialize, ulid, msToRfc3339, } from "./markdown.js";
|
|
8
9
|
/**
|
|
@@ -63,28 +64,37 @@ export function findDuplicates(scopeKey, body, excludeId) {
|
|
|
63
64
|
near.sort((x, y) => y.score - x.score);
|
|
64
65
|
return { exact, near: near.slice(0, 3) };
|
|
65
66
|
}
|
|
66
|
-
/** Locate a memory file by id: index first, then
|
|
67
|
+
/** Locate a memory file by id: index file_path first, then dir-scan fallback. */
|
|
67
68
|
export function findMemoryFile(id) {
|
|
68
69
|
const { memories } = paths();
|
|
69
70
|
let filePath = null;
|
|
70
71
|
try {
|
|
71
72
|
const row = db()
|
|
72
|
-
.prepare(`SELECT
|
|
73
|
+
.prepare(`SELECT file_path FROM memories WHERE id = ?`)
|
|
73
74
|
.get(id);
|
|
74
|
-
if (row)
|
|
75
|
-
|
|
76
|
-
if (fs.existsSync(p))
|
|
77
|
-
filePath = p;
|
|
78
|
-
}
|
|
75
|
+
if (row && fs.existsSync(row.file_path))
|
|
76
|
+
filePath = row.file_path;
|
|
79
77
|
}
|
|
80
78
|
catch {
|
|
81
79
|
// index unavailable — fall through to scan
|
|
82
80
|
}
|
|
83
|
-
if (!filePath
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const
|
|
81
|
+
if (!filePath) {
|
|
82
|
+
// Fallback scan: appdata scope dirs + the in-repo dir (2B/D24).
|
|
83
|
+
const dirs = [];
|
|
84
|
+
if (fs.existsSync(memories)) {
|
|
85
|
+
for (const entry of fs.readdirSync(memories, { withFileTypes: true })) {
|
|
86
|
+
if (entry.isDirectory())
|
|
87
|
+
dirs.push(path.join(memories, entry.name));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
dirs.push(inRepoMemoriesDirPath(projectRoot(), loadConfig().memoryDir));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
/* ignore */
|
|
95
|
+
}
|
|
96
|
+
for (const dir of dirs) {
|
|
97
|
+
const p = path.join(dir, `${id}.md`);
|
|
88
98
|
if (fs.existsSync(p)) {
|
|
89
99
|
filePath = p;
|
|
90
100
|
break;
|
|
@@ -167,6 +177,11 @@ export function supersede(oldId, input) {
|
|
|
167
177
|
updated_at: now,
|
|
168
178
|
supersedes: oldId,
|
|
169
179
|
superseded_by: null,
|
|
180
|
+
review_state: "draft",
|
|
181
|
+
proposed_by: null,
|
|
182
|
+
approved_by: null,
|
|
183
|
+
derived_from: null,
|
|
184
|
+
review_note: null,
|
|
170
185
|
};
|
|
171
186
|
const dir = path.dirname(oldMf.filePath);
|
|
172
187
|
const newPath = path.join(dir, `${newFm.id}.md`);
|
package/dist/store/markdown.js
CHANGED
|
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
4
|
import yaml from "js-yaml";
|
|
5
|
-
import { memoriesDirFor, memoriesDirPath } from "../paths.js";
|
|
5
|
+
import { memoriesDirFor, memoriesDirPath, inRepoMemoriesDirPath, } from "../paths.js";
|
|
6
6
|
/** v2 content-kind taxonomy (V2-DESIGN §3.1). `type` = what the memory IS. */
|
|
7
7
|
export const MEMORY_TYPE_TAXONOMY = [
|
|
8
8
|
"preference",
|
|
@@ -18,6 +18,37 @@ export const MEMORY_TYPE_TAXONOMY = [
|
|
|
18
18
|
"observation",
|
|
19
19
|
];
|
|
20
20
|
const TAXONOMY = new Set(MEMORY_TYPE_TAXONOMY);
|
|
21
|
+
/** Defensive parse: malformed entries are dropped, never fatal. */
|
|
22
|
+
export function asReviewHistory(v) {
|
|
23
|
+
if (!Array.isArray(v))
|
|
24
|
+
return [];
|
|
25
|
+
const out = [];
|
|
26
|
+
for (const e of v) {
|
|
27
|
+
if (!e || typeof e !== "object")
|
|
28
|
+
continue;
|
|
29
|
+
const r = e;
|
|
30
|
+
const from = asReviewState(r.from);
|
|
31
|
+
const to = asReviewState(r.to);
|
|
32
|
+
const at = typeof r.at === "string" && r.at ? r.at : null;
|
|
33
|
+
const by = typeof r.by === "string" && r.by ? r.by : null;
|
|
34
|
+
if (!at || !by)
|
|
35
|
+
continue;
|
|
36
|
+
out.push({
|
|
37
|
+
at,
|
|
38
|
+
by,
|
|
39
|
+
from,
|
|
40
|
+
to,
|
|
41
|
+
note: typeof r.note === "string" && r.note ? r.note : null,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
const REVIEW_STATES = ["draft", "proposed", "approved", "rejected", "published"];
|
|
47
|
+
export function asReviewState(v) {
|
|
48
|
+
return typeof v === "string" && REVIEW_STATES.includes(v)
|
|
49
|
+
? v
|
|
50
|
+
: "draft";
|
|
51
|
+
}
|
|
21
52
|
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
22
53
|
/** ULID-ish: 10 chars of base32 timestamp + 16 chars of base32 randomness. */
|
|
23
54
|
export function ulid() {
|
|
@@ -129,6 +160,12 @@ export function normalizeFrontmatter(raw) {
|
|
|
129
160
|
superseded_by: typeof raw.superseded_by === "string" && raw.superseded_by
|
|
130
161
|
? raw.superseded_by
|
|
131
162
|
: null,
|
|
163
|
+
review_state: asReviewState(raw.review_state),
|
|
164
|
+
proposed_by: typeof raw.proposed_by === "string" && raw.proposed_by ? raw.proposed_by : null,
|
|
165
|
+
approved_by: typeof raw.approved_by === "string" && raw.approved_by ? raw.approved_by : null,
|
|
166
|
+
derived_from: typeof raw.derived_from === "string" && raw.derived_from ? raw.derived_from : null,
|
|
167
|
+
review_note: typeof raw.review_note === "string" && raw.review_note ? raw.review_note : null,
|
|
168
|
+
review_history: asReviewHistory(raw.review_history),
|
|
132
169
|
};
|
|
133
170
|
}
|
|
134
171
|
export function isTaxonomyType(t) {
|
|
@@ -161,20 +198,24 @@ export function parse(raw) {
|
|
|
161
198
|
return { fm: normalizeFrontmatter(parsed.rawFm), body: parsed.body };
|
|
162
199
|
}
|
|
163
200
|
export function writeMemoryFile(fm, body) {
|
|
201
|
+
// 2B/D26: project drafts live in appdata (the outbox) — the in-repo dir
|
|
202
|
+
// only ever holds submitted memories (proposed/approved/published).
|
|
203
|
+
// Personal stays in appdata and never leaves the machine.
|
|
164
204
|
const dir = memoriesDirFor(fm.scope_key);
|
|
165
205
|
const filePath = path.join(dir, `${fm.id}.md`);
|
|
166
206
|
fs.writeFileSync(filePath, serialize(fm, body), "utf8");
|
|
167
207
|
const st = fs.statSync(filePath);
|
|
168
208
|
return { filePath, mtimeMs: st.mtimeMs };
|
|
169
209
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
if (fs.existsSync(
|
|
174
|
-
|
|
175
|
-
|
|
210
|
+
/** Yield `*.md` files in the in-repo dir (read path — never creates it). */
|
|
211
|
+
export function* iterInRepoMemoryFiles(root, memoryDir) {
|
|
212
|
+
const dir = inRepoMemoriesDirPath(root, memoryDir);
|
|
213
|
+
if (!fs.existsSync(dir))
|
|
214
|
+
return;
|
|
215
|
+
for (const name of fs.readdirSync(dir)) {
|
|
216
|
+
if (name.endsWith(".md"))
|
|
217
|
+
yield path.join(dir, name);
|
|
176
218
|
}
|
|
177
|
-
return false;
|
|
178
219
|
}
|
|
179
220
|
export function readMemoryFile(filePath) {
|
|
180
221
|
if (!fs.existsSync(filePath))
|