dsh-cross-memory 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.
- package/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +27 -0
- package/docs/DETAIL.md +13 -0
- package/docs/DETAIL.zh.md +17 -0
- package/icon.svg +1 -0
- package/lib/backfill.js +273 -0
- package/lib/citations.js +305 -0
- package/lib/client.js +1550 -0
- package/lib/config.js +736 -0
- package/lib/consolidate.js +1119 -0
- package/lib/extract.js +570 -0
- package/lib/gate.js +137 -0
- package/lib/git-origin.js +224 -0
- package/lib/index.js +4475 -0
- package/lib/log.js +260 -0
- package/lib/loops.js +186 -0
- package/lib/notices.js +195 -0
- package/lib/notify.js +33 -0
- package/lib/persona.js +112 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +455 -0
- package/lib/render.js +678 -0
- package/lib/retention.js +64 -0
- package/lib/schedule.js +245 -0
- package/lib/search.js +1068 -0
- package/lib/skills.js +220 -0
- package/lib/state.js +701 -0
- package/lib/storage.js +1424 -0
- package/lib/sync-runtime.js +268 -0
- package/lib/sync.js +620 -0
- package/lib/test/activity.test.js +74 -0
- package/lib/test/archive.test.js +182 -0
- package/lib/test/backfill.test.js +144 -0
- package/lib/test/citations.test.js +91 -0
- package/lib/test/client-wiring.test.js +134 -0
- package/lib/test/consolidate-job.test.js +95 -0
- package/lib/test/consolidate.test.js +430 -0
- package/lib/test/consolidation-selection.test.js +152 -0
- package/lib/test/dedupe-keys.test.js +230 -0
- package/lib/test/delta.test.js +93 -0
- package/lib/test/derived.test.js +110 -0
- package/lib/test/disputes-panel.test.js +314 -0
- package/lib/test/eval.test.js +171 -0
- package/lib/test/expand.test.js +164 -0
- package/lib/test/extract.test.js +1020 -0
- package/lib/test/git-origin.test.js +189 -0
- package/lib/test/injection.test.js +440 -0
- package/lib/test/kind-filter.test.js +49 -0
- package/lib/test/legacy-state.test.js +69 -0
- package/lib/test/log.test.js +156 -0
- package/lib/test/loops.test.js +86 -0
- package/lib/test/memory.test.js +855 -0
- package/lib/test/notices.test.js +140 -0
- package/lib/test/persona.test.js +73 -0
- package/lib/test/prefilter.test.js +73 -0
- package/lib/test/preset.test.js +77 -0
- package/lib/test/raw-recall.test.js +186 -0
- package/lib/test/recall.test.js +433 -0
- package/lib/test/reflection.test.js +64 -0
- package/lib/test/remote.test.js +227 -0
- package/lib/test/retention.test.js +117 -0
- package/lib/test/retrieval.test.js +142 -0
- package/lib/test/rotation.test.js +228 -0
- package/lib/test/schedule.test.js +112 -0
- package/lib/test/settings-card.test.js +58 -0
- package/lib/test/skills.test.js +129 -0
- package/lib/test/state.test.js +212 -0
- package/lib/test/subagent-contract.test.js +139 -0
- package/lib/test/sweep.test.js +159 -0
- package/lib/test/sync.test.js +314 -0
- package/lib/test/time.test.js +171 -0
- package/lib/time.js +303 -0
- package/lib/tool.js +330 -0
- package/lib/types/backfill.d.ts +96 -0
- package/lib/types/citations.d.ts +105 -0
- package/lib/types/config.d.ts +811 -0
- package/lib/types/consolidate.d.ts +742 -0
- package/lib/types/extract.d.ts +352 -0
- package/lib/types/gate.d.ts +83 -0
- package/lib/types/git-origin.d.ts +23 -0
- package/lib/types/index.d.ts +1316 -0
- package/lib/types/log.d.ts +144 -0
- package/lib/types/loops.d.ts +82 -0
- package/lib/types/notices.d.ts +117 -0
- package/lib/types/notify.d.ts +12 -0
- package/lib/types/persona.d.ts +43 -0
- package/lib/types/query.d.ts +45 -0
- package/lib/types/raw-recall.d.ts +84 -0
- package/lib/types/reflection.d.ts +122 -0
- package/lib/types/remote.d.ts +233 -0
- package/lib/types/render.d.ts +286 -0
- package/lib/types/retention.d.ts +66 -0
- package/lib/types/schedule.d.ts +116 -0
- package/lib/types/search.d.ts +583 -0
- package/lib/types/skills.d.ts +71 -0
- package/lib/types/state.d.ts +294 -0
- package/lib/types/storage.d.ts +458 -0
- package/lib/types/sync-runtime.d.ts +103 -0
- package/lib/types/sync.d.ts +222 -0
- package/lib/types/test/activity.test.d.ts +1 -0
- package/lib/types/test/archive.test.d.ts +1 -0
- package/lib/types/test/backfill.test.d.ts +1 -0
- package/lib/types/test/citations.test.d.ts +1 -0
- package/lib/types/test/client-wiring.test.d.ts +1 -0
- package/lib/types/test/consolidate-job.test.d.ts +1 -0
- package/lib/types/test/consolidate.test.d.ts +1 -0
- package/lib/types/test/consolidation-selection.test.d.ts +1 -0
- package/lib/types/test/dedupe-keys.test.d.ts +1 -0
- package/lib/types/test/delta.test.d.ts +1 -0
- package/lib/types/test/derived.test.d.ts +1 -0
- package/lib/types/test/disputes-panel.test.d.ts +1 -0
- package/lib/types/test/eval.test.d.ts +1 -0
- package/lib/types/test/expand.test.d.ts +1 -0
- package/lib/types/test/extract.test.d.ts +1 -0
- package/lib/types/test/git-origin.test.d.ts +1 -0
- package/lib/types/test/injection.test.d.ts +1 -0
- package/lib/types/test/kind-filter.test.d.ts +1 -0
- package/lib/types/test/legacy-state.test.d.ts +1 -0
- package/lib/types/test/log.test.d.ts +1 -0
- package/lib/types/test/loops.test.d.ts +1 -0
- package/lib/types/test/memory.test.d.ts +1 -0
- package/lib/types/test/notices.test.d.ts +1 -0
- package/lib/types/test/persona.test.d.ts +1 -0
- package/lib/types/test/prefilter.test.d.ts +1 -0
- package/lib/types/test/preset.test.d.ts +1 -0
- package/lib/types/test/raw-recall.test.d.ts +1 -0
- package/lib/types/test/recall.test.d.ts +1 -0
- package/lib/types/test/reflection.test.d.ts +1 -0
- package/lib/types/test/remote.test.d.ts +1 -0
- package/lib/types/test/retention.test.d.ts +1 -0
- package/lib/types/test/retrieval.test.d.ts +1 -0
- package/lib/types/test/rotation.test.d.ts +1 -0
- package/lib/types/test/schedule.test.d.ts +1 -0
- package/lib/types/test/settings-card.test.d.ts +1 -0
- package/lib/types/test/skills.test.d.ts +1 -0
- package/lib/types/test/state.test.d.ts +1 -0
- package/lib/types/test/subagent-contract.test.d.ts +1 -0
- package/lib/types/test/sweep.test.d.ts +1 -0
- package/lib/types/test/sync.test.d.ts +1 -0
- package/lib/types/test/time.test.d.ts +1 -0
- package/lib/types/time.d.ts +67 -0
- package/lib/types/tool.d.ts +9 -0
- package/lib/types/types.d.ts +374 -0
- package/lib/types/workspace.d.ts +20 -0
- package/lib/types.js +47 -0
- package/lib/workspace.js +65 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +126 -4
package/lib/sync.js
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git-backed transport for the memory store.
|
|
3
|
+
*
|
|
4
|
+
* The store is the same on every machine the user works on, so a memory written
|
|
5
|
+
* here has to reach the others — and a memory written there has to arrive here.
|
|
6
|
+
* This module is that path.
|
|
7
|
+
*
|
|
8
|
+
* Shape of the design:
|
|
9
|
+
*
|
|
10
|
+
* - **The store directory is the working copy.** No mirror, no second copy that
|
|
11
|
+
* can drift: the store's own \`.git\` makes entries, projects, archive, persona,
|
|
12
|
+
* sessions and staged skills ordinary tracked files, so a memory write is a file
|
|
13
|
+
* write and "what is on disk" is "what is in the repository".
|
|
14
|
+
* - **Writes never wait for the network.** A store write queues a debounced local
|
|
15
|
+
* commit; fetch/rebase/push run in the background on their own timer and after
|
|
16
|
+
* that commit. A memory tool call must not fail because GitHub was slow.
|
|
17
|
+
* - **Machine state stays out of git.** state.db, every index.json, pending/ and
|
|
18
|
+
* logs are per-machine caches and watermark counters; tracking them turns every
|
|
19
|
+
* sync into a fake conflict over numbers nobody wrote by hand.
|
|
20
|
+
* - **A conflicting entry is a decision, not a merge conflict.** One memory is one
|
|
21
|
+
* file, so the same id on both sides is the same memory with two edits. The
|
|
22
|
+
* resolver handed to {@link MemorySyncOptions.resolveConflict} decides; without
|
|
23
|
+
* one — or when it fails — the newer \`updated\` stamp wins and the older text
|
|
24
|
+
* stays in git history.
|
|
25
|
+
*
|
|
26
|
+
* Everything here is best-effort: no failure in this module may fail a store
|
|
27
|
+
* write, and no failure may leave the repository mid-rebase.
|
|
28
|
+
*
|
|
29
|
+
* @module dsh-cross-memory/sync
|
|
30
|
+
*/
|
|
31
|
+
import { execFile } from 'node:child_process';
|
|
32
|
+
import { existsSync } from 'node:fs';
|
|
33
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
34
|
+
import { join } from 'node:path';
|
|
35
|
+
import { promisify } from 'node:util';
|
|
36
|
+
import { LOOPS_FILE } from './loops.js';
|
|
37
|
+
import { parseEntry } from './storage.js';
|
|
38
|
+
const run = promisify(execFile);
|
|
39
|
+
/** Files that are per-machine state, never content. */
|
|
40
|
+
export const STORE_GITIGNORE = [
|
|
41
|
+
'# per-machine state: watermarks, caches, in-flight work',
|
|
42
|
+
'state.db',
|
|
43
|
+
'state.db-shm',
|
|
44
|
+
'state.db-wal',
|
|
45
|
+
'index.json',
|
|
46
|
+
'**/index.json',
|
|
47
|
+
'# a project descriptor records THIS machine\'s checkout path',
|
|
48
|
+
'**/project.json',
|
|
49
|
+
'pending/',
|
|
50
|
+
'*.log',
|
|
51
|
+
'.DS_Store',
|
|
52
|
+
'',
|
|
53
|
+
].join('\n');
|
|
54
|
+
/**
|
|
55
|
+
* Whether a repository-relative path is one memory this module can merge.
|
|
56
|
+
*
|
|
57
|
+
* One memory is one file, in the live tree or in the archive: both carry the same
|
|
58
|
+
* frontmatter, so the same arbitration applies. Persona, session notes and staged
|
|
59
|
+
* skills are prose with a different shape — a conflict there aborts the rebase
|
|
60
|
+
* instead of being guessed at.
|
|
61
|
+
*/
|
|
62
|
+
export function isEntryPath(path) {
|
|
63
|
+
if (!path.endsWith('.md'))
|
|
64
|
+
return false;
|
|
65
|
+
return /(^|\/)(entries|archive)\//u.test(path);
|
|
66
|
+
}
|
|
67
|
+
/** The updated stamp of one entry text, or 0 when it cannot be parsed. */
|
|
68
|
+
export function entryStamp(text) {
|
|
69
|
+
return parseEntry(text, 'global', 'unknown')?.updatedAt ?? parseEntry(text, 'project', 'unknown')?.updatedAt ?? 0;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Resolve one conflicting entry by keeping the newer revision.
|
|
73
|
+
*
|
|
74
|
+
* Exported because it is the documented fallback: a caller that wants the model
|
|
75
|
+
* decision first reads this only when the model declined or failed.
|
|
76
|
+
*/
|
|
77
|
+
export function newerEntry(ours, theirs) {
|
|
78
|
+
return entryStamp(theirs) > entryStamp(ours)
|
|
79
|
+
? { text: theirs, oursWon: false }
|
|
80
|
+
: { text: ours, oursWon: true };
|
|
81
|
+
}
|
|
82
|
+
/** Whether one repository path is a session note: prose, but stamped with `at:`. */
|
|
83
|
+
export function isSessionNotePath(path) {
|
|
84
|
+
return /(^|\/)sessions\/[^/]+\.md$/u.test(path);
|
|
85
|
+
}
|
|
86
|
+
/** The `at` stamp of one session note, or 0 when it cannot be parsed. */
|
|
87
|
+
export function sessionNoteStamp(text) {
|
|
88
|
+
const match = /^at:[ \t]*(\S+)[ \t]*$/mu.exec(text);
|
|
89
|
+
const stamp = match?.[1];
|
|
90
|
+
if (stamp === undefined)
|
|
91
|
+
return 0;
|
|
92
|
+
const parsed = Date.parse(stamp);
|
|
93
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Resolve one conflicting session note by keeping the later `at:` stamp.
|
|
97
|
+
*
|
|
98
|
+
* A session note is the extractor's prose summary of one session. The same
|
|
99
|
+
* session can be summarised twice — once on each machine, or again after the
|
|
100
|
+
* conversation grew — and then the two notes conflict on every later sync. The
|
|
101
|
+
* `at:` frontmatter says which summary is the later reading, so the newer one
|
|
102
|
+
* wins the way an entry's `updated` stamp does; the older text stays in git.
|
|
103
|
+
*
|
|
104
|
+
* @returns the winning text, or undefined when neither side carries a stamp.
|
|
105
|
+
*/
|
|
106
|
+
/** Whether one repository path is a per-host descriptor: `projects/<slug>/hosts/<host>.json`. */
|
|
107
|
+
export function isHostDescriptorPath(path) {
|
|
108
|
+
return /(^|\/)hosts\/[^/]+\.json$/u.test(path);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Resolve one conflicting host descriptor by keeping the newer reading.
|
|
112
|
+
*
|
|
113
|
+
* A host descriptor is the machine's own note about one project checkout: where
|
|
114
|
+
* it is, when it was seen last, and its git origin. Only the machine named in
|
|
115
|
+
* the file writes it, but every other machine carries a copy — so a rebase
|
|
116
|
+
* between two machines stops here with an older and a newer reading of the same
|
|
117
|
+
* machine. `lastSeen` says which is newer; when both agree, the side that knows
|
|
118
|
+
* the origin wins because a descriptor written before the origin field existed
|
|
119
|
+
* lacks it.
|
|
120
|
+
*
|
|
121
|
+
* @returns the winning text, or undefined when neither side is a descriptor.
|
|
122
|
+
*/
|
|
123
|
+
export function newerHostDescriptor(ours, theirs) {
|
|
124
|
+
const parse = (text) => {
|
|
125
|
+
try {
|
|
126
|
+
const value = JSON.parse(text);
|
|
127
|
+
return value !== null && typeof value === 'object' ? value : undefined;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const left = parse(ours);
|
|
134
|
+
const right = parse(theirs);
|
|
135
|
+
if (left === undefined && right === undefined)
|
|
136
|
+
return undefined;
|
|
137
|
+
if (left === undefined)
|
|
138
|
+
return theirs;
|
|
139
|
+
if (right === undefined)
|
|
140
|
+
return ours;
|
|
141
|
+
const seen = (row) => typeof row['lastSeen'] === 'number' ? row['lastSeen'] : 0;
|
|
142
|
+
if (seen(right) !== seen(left))
|
|
143
|
+
return seen(right) > seen(left) ? theirs : ours;
|
|
144
|
+
const hasOrigin = (row) => typeof row['origin'] === 'string';
|
|
145
|
+
if (hasOrigin(right) !== hasOrigin(left))
|
|
146
|
+
return hasOrigin(right) ? theirs : ours;
|
|
147
|
+
return ours;
|
|
148
|
+
}
|
|
149
|
+
export function newerSessionNote(ours, theirs) {
|
|
150
|
+
const left = sessionNoteStamp(ours);
|
|
151
|
+
const right = sessionNoteStamp(theirs);
|
|
152
|
+
if (left === 0 && right === 0)
|
|
153
|
+
return undefined;
|
|
154
|
+
return right >= left ? theirs : ours;
|
|
155
|
+
}
|
|
156
|
+
/** How final one loop state is; a user's closure must not be undone by a stale copy. */
|
|
157
|
+
const LOOP_STATE_RANK = { open: 0, expired: 1, dropped: 2, done: 3 };
|
|
158
|
+
/** One text as a loop ledger, or undefined when it is not one. */
|
|
159
|
+
function parseLedgerText(text) {
|
|
160
|
+
try {
|
|
161
|
+
const parsed = JSON.parse(text);
|
|
162
|
+
if (parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.loops)) {
|
|
163
|
+
return parsed;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// not JSON; the caller decides whether that is fatal
|
|
168
|
+
}
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
/** One text with only one branch of every conflict marker block kept. */
|
|
172
|
+
function oneMarkerBranch(text, branch) {
|
|
173
|
+
const kept = [];
|
|
174
|
+
let state = 'normal';
|
|
175
|
+
for (const line of text.split('\n')) {
|
|
176
|
+
if (/^<<<<<<</u.test(line)) {
|
|
177
|
+
state = 'ours';
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (/^=======/u.test(line)) {
|
|
181
|
+
if (state === 'ours')
|
|
182
|
+
state = 'theirs';
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (/^>>>>>>>/u.test(line)) {
|
|
186
|
+
state = 'normal';
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (state === 'normal' || state === branch)
|
|
190
|
+
kept.push(line);
|
|
191
|
+
}
|
|
192
|
+
return kept.join('\n');
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Every ledger one conflict side contributes.
|
|
196
|
+
*
|
|
197
|
+
* Normally that is one. A text with git conflict markers committed into it — a
|
|
198
|
+
* build that aborted a rebase *after* writing the conflicted file did exactly
|
|
199
|
+
* that to this store's `loops.json` — contributes one ledger per branch, so the
|
|
200
|
+
* loops from both halves of the botched merge survive. Splitting on the markers
|
|
201
|
+
* rather than stripping them is what keeps the result valid JSON: each branch
|
|
202
|
+
* is the original file with whole field groups removed.
|
|
203
|
+
*/
|
|
204
|
+
function ledgersIn(text) {
|
|
205
|
+
const direct = parseLedgerText(text);
|
|
206
|
+
if (direct !== undefined)
|
|
207
|
+
return [direct];
|
|
208
|
+
if (!/^(<<<<<<<|=======|>>>>>>>)/mu.test(text))
|
|
209
|
+
return [];
|
|
210
|
+
const ledgers = [];
|
|
211
|
+
for (const branch of ['ours', 'theirs']) {
|
|
212
|
+
const parsed = parseLedgerText(oneMarkerBranch(text, branch));
|
|
213
|
+
if (parsed !== undefined)
|
|
214
|
+
ledgers.push(parsed);
|
|
215
|
+
}
|
|
216
|
+
return ledgers;
|
|
217
|
+
}
|
|
218
|
+
/** The copy of one loop that survives a merge: the most final state, then the most recent reminder. */
|
|
219
|
+
function pickLoop(ours, theirs) {
|
|
220
|
+
const rank = (loop) => LOOP_STATE_RANK[loop.state] ?? 0;
|
|
221
|
+
if (rank(theirs) !== rank(ours))
|
|
222
|
+
return rank(theirs) > rank(ours) ? theirs : ours;
|
|
223
|
+
const reminded = (loop) => loop.remindedAt ?? 0;
|
|
224
|
+
if (reminded(theirs) !== reminded(ours))
|
|
225
|
+
return reminded(theirs) > reminded(ours) ? theirs : ours;
|
|
226
|
+
return ours;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Merge two versions of the open-loop ledger.
|
|
230
|
+
*
|
|
231
|
+
* The ledger is one JSON file both machines append to, so it conflicts as soon
|
|
232
|
+
* as either side opens a loop — and unlike an entry it is not one memory with
|
|
233
|
+
* two edits but many independent rows. The merge is therefore a union by id: a
|
|
234
|
+
* loop only one side knows is kept, and a loop both sides changed takes its most
|
|
235
|
+
* final copy. A side whose file was committed with conflict markers contributes
|
|
236
|
+
* the loops from both branches (see {@link ledgersIn}).
|
|
237
|
+
*
|
|
238
|
+
* @param ours - one side of the conflict, as `git show :2:` returned it.
|
|
239
|
+
* @param theirs - the other side, as `git show :3:` returned it.
|
|
240
|
+
* @returns the merged ledger text, or undefined when neither side is a ledger.
|
|
241
|
+
*/
|
|
242
|
+
export function mergeLoopLedgers(ours, theirs) {
|
|
243
|
+
const ledgers = [...ledgersIn(ours), ...ledgersIn(theirs)];
|
|
244
|
+
if (ledgers.length === 0)
|
|
245
|
+
return undefined;
|
|
246
|
+
const merged = new Map();
|
|
247
|
+
for (const ledger of ledgers) {
|
|
248
|
+
for (const loop of ledger.loops) {
|
|
249
|
+
const existing = merged.get(loop.id);
|
|
250
|
+
merged.set(loop.id, existing === undefined ? loop : pickLoop(existing, loop));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const loops = [...merged.values()].sort((a, b) => a.openedAt - b.openedAt);
|
|
254
|
+
return JSON.stringify({ version: 1, loops }, null, 2) + '\n';
|
|
255
|
+
}
|
|
256
|
+
/** Parse one "HH:MM" clock entry into minutes past midnight, or undefined. */
|
|
257
|
+
export function parseClockTime(value) {
|
|
258
|
+
const match = /^([01]?\d|2[0-3]):([0-5]\d)$/u.exec(value.trim());
|
|
259
|
+
if (match === null)
|
|
260
|
+
return undefined;
|
|
261
|
+
return Number(match[1]) * 60 + Number(match[2]);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Milliseconds from `now` until the next configured clock time.
|
|
265
|
+
*
|
|
266
|
+
* The schedule is local time, so a machine in another timezone syncs at its own
|
|
267
|
+
* 12:05 — which is the point: off-peak pricing and "when nobody is working" are
|
|
268
|
+
* local facts, not UTC ones.
|
|
269
|
+
*
|
|
270
|
+
* @param clock - "HH:MM" entries; unparsable ones are ignored.
|
|
271
|
+
* @param now - clock.
|
|
272
|
+
* @returns the delay, or undefined when no entry parses.
|
|
273
|
+
*/
|
|
274
|
+
export function nextClockDelay(clock, now) {
|
|
275
|
+
const minutes = clock.map(parseClockTime).filter((value) => value !== undefined);
|
|
276
|
+
if (minutes.length === 0)
|
|
277
|
+
return undefined;
|
|
278
|
+
const today = new Date(now);
|
|
279
|
+
const midnight = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
|
|
280
|
+
const elapsed = now - midnight;
|
|
281
|
+
let best;
|
|
282
|
+
for (const minute of minutes) {
|
|
283
|
+
let at = minute * 60_000;
|
|
284
|
+
if (at <= elapsed + 1_000)
|
|
285
|
+
at += 86_400_000;
|
|
286
|
+
if (best === undefined || at < best)
|
|
287
|
+
best = at;
|
|
288
|
+
}
|
|
289
|
+
return best === undefined ? undefined : best - elapsed;
|
|
290
|
+
}
|
|
291
|
+
/** Run one git command and return its stdout. */
|
|
292
|
+
async function git(dir, args, timeout) {
|
|
293
|
+
// core.quotePath=false: a non-ASCII path must come back as itself, not as a
|
|
294
|
+
// C-quoted string, or the conflict resolver cannot tell it is an entry file.
|
|
295
|
+
const { stdout } = await run('git', ['-c', 'core.quotePath=false', '-C', dir, ...args], {
|
|
296
|
+
timeout,
|
|
297
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
298
|
+
env: { ...process.env, GIT_EDITOR: 'true', GIT_TERMINAL_PROMPT: '0' },
|
|
299
|
+
});
|
|
300
|
+
return stdout;
|
|
301
|
+
}
|
|
302
|
+
/** Run one git command, returning undefined instead of throwing. */
|
|
303
|
+
async function tryGit(dir, args, timeout) {
|
|
304
|
+
try {
|
|
305
|
+
return await git(dir, args, timeout);
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** The memory store's git transport. */
|
|
312
|
+
export class MemorySync {
|
|
313
|
+
options;
|
|
314
|
+
dir;
|
|
315
|
+
timer;
|
|
316
|
+
debounce;
|
|
317
|
+
pushing = false;
|
|
318
|
+
inflight;
|
|
319
|
+
lastOutcome;
|
|
320
|
+
constructor(options) {
|
|
321
|
+
this.options = options;
|
|
322
|
+
this.dir = options.memoriesDir;
|
|
323
|
+
}
|
|
324
|
+
/** The outcome of the last completed run, when there was one. */
|
|
325
|
+
get last() {
|
|
326
|
+
return this.lastOutcome;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Make the store a git repository and remember the remote.
|
|
330
|
+
*
|
|
331
|
+
* Idempotent: an existing repository is adopted, never reinitialised, and the
|
|
332
|
+
* remote is only added when it is missing. .gitignore is written only when
|
|
333
|
+
* absent so a hand-edited one is not overwritten.
|
|
334
|
+
*/
|
|
335
|
+
async init() {
|
|
336
|
+
await mkdir(this.dir, { recursive: true });
|
|
337
|
+
const ignore = join(this.dir, '.gitignore');
|
|
338
|
+
if (!existsSync(ignore))
|
|
339
|
+
await writeFile(ignore, STORE_GITIGNORE);
|
|
340
|
+
if (!existsSync(join(this.dir, '.git'))) {
|
|
341
|
+
await git(this.dir, ['init', '-b', 'main'], this.options.gitTimeoutMs);
|
|
342
|
+
await git(this.dir, ['add', '-A'], this.options.gitTimeoutMs);
|
|
343
|
+
await git(this.dir, ['commit', '--quiet', '-m', 'chore(memories): 初始记忆库快照'], this.options.gitTimeoutMs)
|
|
344
|
+
.catch(() => undefined);
|
|
345
|
+
this.options.log.info('dsh-cross-memory: 把记忆库初始化为 git 仓库:%s', this.dir);
|
|
346
|
+
}
|
|
347
|
+
if (this.options.remote.length > 0) {
|
|
348
|
+
const current = await tryGit(this.dir, ['remote', 'get-url', 'origin'], this.options.gitTimeoutMs);
|
|
349
|
+
if (current === undefined) {
|
|
350
|
+
await git(this.dir, ['remote', 'add', 'origin', this.options.remote], this.options.gitTimeoutMs);
|
|
351
|
+
}
|
|
352
|
+
else if (current.trim() !== this.options.remote) {
|
|
353
|
+
await git(this.dir, ['remote', 'set-url', 'origin', this.options.remote], this.options.gitTimeoutMs);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Start the background timer.
|
|
359
|
+
*
|
|
360
|
+
* A clock schedule wins over an interval: two fixed local times are what the
|
|
361
|
+
* owner asked for (sync right after off-peak pricing starts, when a conflict
|
|
362
|
+
* merge costs least), while an interval is the fallback for anyone who wants
|
|
363
|
+
* continuous convergence.
|
|
364
|
+
*/
|
|
365
|
+
start() {
|
|
366
|
+
this.stop();
|
|
367
|
+
const clock = this.options.clock ?? [];
|
|
368
|
+
if (clock.length > 0) {
|
|
369
|
+
this.armClock(clock);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (!(this.options.intervalMs > 0))
|
|
373
|
+
return;
|
|
374
|
+
this.timer = setInterval(() => {
|
|
375
|
+
void this.run('timer').catch((error) => {
|
|
376
|
+
this.options.log.warn('dsh-cross-memory: 记忆库同步失败:%o', error);
|
|
377
|
+
});
|
|
378
|
+
}, this.options.intervalMs);
|
|
379
|
+
this.timer.unref?.();
|
|
380
|
+
}
|
|
381
|
+
/** Arms the next clock run; each run arms the following one. */
|
|
382
|
+
armClock(clock) {
|
|
383
|
+
const delay = nextClockDelay(clock, Date.now());
|
|
384
|
+
if (delay === undefined)
|
|
385
|
+
return;
|
|
386
|
+
this.timer = setTimeout(() => {
|
|
387
|
+
void this.run('clock')
|
|
388
|
+
.catch((error) => {
|
|
389
|
+
this.options.log.warn('dsh-cross-memory: 记忆库同步失败:%o', error);
|
|
390
|
+
})
|
|
391
|
+
.finally(() => {
|
|
392
|
+
if (this.timer !== undefined)
|
|
393
|
+
this.armClock(clock);
|
|
394
|
+
});
|
|
395
|
+
}, delay);
|
|
396
|
+
this.timer.unref?.();
|
|
397
|
+
this.options.log.info('dsh-cross-memory: 下一次记忆库同步在 %s 之后(%s)', Math.round(delay / 60_000) + ' 分钟', clock.join(', '));
|
|
398
|
+
}
|
|
399
|
+
/** Stop the background timer and any queued commit. */
|
|
400
|
+
stop() {
|
|
401
|
+
if (this.timer !== undefined)
|
|
402
|
+
clearInterval(this.timer);
|
|
403
|
+
if (this.debounce !== undefined)
|
|
404
|
+
clearTimeout(this.debounce);
|
|
405
|
+
this.timer = undefined;
|
|
406
|
+
this.debounce = undefined;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Note that the store changed.
|
|
410
|
+
*
|
|
411
|
+
* Deliberately synchronous and cheap: this runs inside a memory write. The
|
|
412
|
+
* commit and the network happen later, on the debounce timer.
|
|
413
|
+
*/
|
|
414
|
+
queueCommit() {
|
|
415
|
+
if (this.debounce !== undefined)
|
|
416
|
+
return;
|
|
417
|
+
this.debounce = setTimeout(() => {
|
|
418
|
+
this.debounce = undefined;
|
|
419
|
+
void this.run('write').catch((error) => {
|
|
420
|
+
this.options.log.warn('dsh-cross-memory: 记忆库提交失败:%o', error);
|
|
421
|
+
});
|
|
422
|
+
}, this.options.debounceMs);
|
|
423
|
+
this.debounce.unref?.();
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Commit, pull and push once.
|
|
427
|
+
*
|
|
428
|
+
* Concurrent calls share one run: two flushes over one directory would index
|
|
429
|
+
* each other's half-written rebase.
|
|
430
|
+
*
|
|
431
|
+
* @param reason - who asked, for the log.
|
|
432
|
+
* @returns what the run did.
|
|
433
|
+
*/
|
|
434
|
+
async run(reason) {
|
|
435
|
+
if (this.inflight !== undefined)
|
|
436
|
+
return await this.inflight;
|
|
437
|
+
this.inflight = this.flush(reason).finally(() => { this.inflight = undefined; });
|
|
438
|
+
const outcome = await this.inflight;
|
|
439
|
+
this.lastOutcome = outcome;
|
|
440
|
+
return outcome;
|
|
441
|
+
}
|
|
442
|
+
/** The body of one run; see {@link run}. */
|
|
443
|
+
async flush(reason) {
|
|
444
|
+
const committed = await this.commit();
|
|
445
|
+
let pulled = 0;
|
|
446
|
+
let pushed = false;
|
|
447
|
+
let conflicts = 0;
|
|
448
|
+
let resolvedByResolver = 0;
|
|
449
|
+
let resolvedByTime = 0;
|
|
450
|
+
let mergedByStructure = 0;
|
|
451
|
+
let stoppedBy;
|
|
452
|
+
if (this.options.remote.length > 0) {
|
|
453
|
+
const pull = await this.pull();
|
|
454
|
+
pulled = pull.pulled;
|
|
455
|
+
conflicts = pull.conflicts;
|
|
456
|
+
resolvedByResolver = pull.resolvedByResolver;
|
|
457
|
+
resolvedByTime = pull.resolvedByTime;
|
|
458
|
+
mergedByStructure = pull.mergedByStructure;
|
|
459
|
+
stoppedBy = pull.stoppedBy;
|
|
460
|
+
pushed = await this.push();
|
|
461
|
+
}
|
|
462
|
+
if (committed > 0 || pulled > 0 || conflicts > 0 || pushed || stoppedBy !== undefined) {
|
|
463
|
+
this.options.log.info('dsh-cross-memory: 记忆库同步(%s):提交 %d、拉取 %d、推送 %s、冲突 %d(AI %d / 时间 %d / 结构 %d)%s', reason, committed, pulled, pushed ? '是' : '否', conflicts, resolvedByResolver, resolvedByTime, mergedByStructure, stoppedBy === undefined ? '' : ',止于 ' + stoppedBy);
|
|
464
|
+
}
|
|
465
|
+
return { committed, pulled, pushed, conflicts, resolvedByResolver, resolvedByTime, mergedByStructure, stoppedBy };
|
|
466
|
+
}
|
|
467
|
+
/** Stage and commit everything the store changed. */
|
|
468
|
+
async commit() {
|
|
469
|
+
// A rebase that was killed leaves conflict markers in the worktree; `add -A`
|
|
470
|
+
// would then commit them into the store — that is how loops.json once
|
|
471
|
+
// reached the remote with `<<<<<<<` lines inside. Roll back first.
|
|
472
|
+
if (this.rebaseInProgress()) {
|
|
473
|
+
await tryGit(this.dir, ['rebase', '--abort'], this.options.gitTimeoutMs);
|
|
474
|
+
this.options.log.warn('dsh-cross-memory: 记忆库停在上一次未完成的 rebase 里,已回滚后才提交');
|
|
475
|
+
}
|
|
476
|
+
await git(this.dir, ['add', '-A'], this.options.gitTimeoutMs).catch(() => undefined);
|
|
477
|
+
const staged = await tryGit(this.dir, ['diff', '--cached', '--name-only'], this.options.gitTimeoutMs);
|
|
478
|
+
const files = (staged ?? '').split('\n').filter((line) => line.length > 0);
|
|
479
|
+
if (files.length === 0)
|
|
480
|
+
return 0;
|
|
481
|
+
const message = 'memory(' + this.options.host + '): ' + files.length + ' 个文件 '
|
|
482
|
+
+ new Date().toISOString().replace('T', ' ').slice(0, 19);
|
|
483
|
+
await git(this.dir, ['commit', '--quiet', '-m', message], this.options.gitTimeoutMs);
|
|
484
|
+
return files.length;
|
|
485
|
+
}
|
|
486
|
+
/** Whether a rebase was interrupted and still owns the index and worktree. */
|
|
487
|
+
rebaseInProgress() {
|
|
488
|
+
return existsSync(join(this.dir, '.git', 'rebase-merge')) || existsSync(join(this.dir, '.git', 'rebase-apply'));
|
|
489
|
+
}
|
|
490
|
+
/** Fetch, then rebase onto the remote branch, resolving entry conflicts. */
|
|
491
|
+
async pull() {
|
|
492
|
+
const nothing = { pulled: 0, conflicts: 0, resolvedByResolver: 0, resolvedByTime: 0, mergedByStructure: 0 };
|
|
493
|
+
const fetched = await tryGit(this.dir, ['fetch', '--quiet', 'origin'], this.options.networkTimeoutMs);
|
|
494
|
+
if (fetched === undefined)
|
|
495
|
+
return nothing;
|
|
496
|
+
const behind = await tryGit(this.dir, ['rev-list', '--count', 'HEAD..origin/main'], this.options.gitTimeoutMs);
|
|
497
|
+
if (behind === undefined || Number.parseInt(behind.trim(), 10) === 0)
|
|
498
|
+
return nothing;
|
|
499
|
+
const count = Number.parseInt(behind.trim(), 10);
|
|
500
|
+
const rebase = await tryGit(this.dir, ['rebase', '--quiet', 'origin/main'], this.options.networkTimeoutMs);
|
|
501
|
+
if (rebase !== undefined)
|
|
502
|
+
return { ...nothing, pulled: count };
|
|
503
|
+
const resolution = await this.resolveRebase();
|
|
504
|
+
return { pulled: count, ...resolution };
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Resolve whatever the rebase stopped on, then finish it.
|
|
508
|
+
*
|
|
509
|
+
* Entry files are resolved automatically (the resolver, then the newer
|
|
510
|
+
* `updated` stamp). The loop ledger is a JSON file of independent rows rather
|
|
511
|
+
* than one memory with two edits, so it gets a structural union merge. Anything
|
|
512
|
+
* else aborts the rebase: a store left mid-rebase is far worse than a sync that
|
|
513
|
+
* skipped a cycle.
|
|
514
|
+
*/
|
|
515
|
+
async resolveRebase() {
|
|
516
|
+
let conflicts = 0;
|
|
517
|
+
let resolvedByResolver = 0;
|
|
518
|
+
let resolvedByTime = 0;
|
|
519
|
+
let mergedByStructure = 0;
|
|
520
|
+
for (let round = 0; round < 200; round += 1) {
|
|
521
|
+
const unmerged = await tryGit(this.dir, ['diff', '--name-only', '--diff-filter=U'], this.options.gitTimeoutMs);
|
|
522
|
+
const paths = (unmerged ?? '').split('\n').filter((line) => line.length > 0);
|
|
523
|
+
if (paths.length === 0) {
|
|
524
|
+
const cont = await tryGit(this.dir, ['rebase', '--continue'], this.options.networkTimeoutMs);
|
|
525
|
+
if (cont !== undefined)
|
|
526
|
+
return { conflicts, resolvedByResolver, resolvedByTime, mergedByStructure };
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
for (const path of paths) {
|
|
530
|
+
const ours = await tryGit(this.dir, ['show', ':' + '2:' + path], this.options.gitTimeoutMs);
|
|
531
|
+
const theirs = await tryGit(this.dir, ['show', ':' + '3:' + path], this.options.gitTimeoutMs);
|
|
532
|
+
if (ours === undefined || theirs === undefined)
|
|
533
|
+
continue;
|
|
534
|
+
conflicts += 1;
|
|
535
|
+
// Both sides already agree byte for byte: nothing to decide, and git only
|
|
536
|
+
// stopped because the replayed commit touched a file upstream had also
|
|
537
|
+
// rewritten to the same text. This is common for per-host descriptors
|
|
538
|
+
// (`projects/*/hosts/<host>.json`), which every machine rewrites on open.
|
|
539
|
+
if (ours === theirs) {
|
|
540
|
+
await writeFile(join(this.dir, path), ours);
|
|
541
|
+
mergedByStructure += 1;
|
|
542
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (!isEntryPath(path)) {
|
|
546
|
+
const merged = path === LOOPS_FILE ? mergeLoopLedgers(ours, theirs) : undefined;
|
|
547
|
+
if (merged !== undefined) {
|
|
548
|
+
await writeFile(join(this.dir, path), merged);
|
|
549
|
+
mergedByStructure += 1;
|
|
550
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
const note = isSessionNotePath(path) ? newerSessionNote(ours, theirs) : undefined;
|
|
554
|
+
if (note !== undefined) {
|
|
555
|
+
await writeFile(join(this.dir, path), note);
|
|
556
|
+
resolvedByTime += 1;
|
|
557
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
const descriptor = isHostDescriptorPath(path) ? newerHostDescriptor(ours, theirs) : undefined;
|
|
561
|
+
if (descriptor !== undefined) {
|
|
562
|
+
await writeFile(join(this.dir, path), descriptor);
|
|
563
|
+
resolvedByTime += 1;
|
|
564
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
await tryGit(this.dir, ['rebase', '--abort'], this.options.gitTimeoutMs);
|
|
568
|
+
this.options.log.warn('dsh-cross-memory: 记忆库 rebase 遇到不可自动处理的冲突(%s),已回滚本次同步', path);
|
|
569
|
+
return { conflicts, resolvedByResolver, resolvedByTime, mergedByStructure, stoppedBy: path };
|
|
570
|
+
}
|
|
571
|
+
let text;
|
|
572
|
+
if (this.options.resolveConflict !== undefined) {
|
|
573
|
+
try {
|
|
574
|
+
text = await this.options.resolveConflict({ path, ours, theirs });
|
|
575
|
+
}
|
|
576
|
+
catch (error) {
|
|
577
|
+
this.options.log.warn('dsh-cross-memory: 冲突解析器失败(%s):%o', path, error);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (text !== undefined && parseEntry(text, 'global', 'unknown') !== undefined) {
|
|
581
|
+
await writeFile(join(this.dir, path), text);
|
|
582
|
+
resolvedByResolver += 1;
|
|
583
|
+
}
|
|
584
|
+
else {
|
|
585
|
+
const decided = newerEntry(ours, theirs);
|
|
586
|
+
await writeFile(join(this.dir, path), decided.text);
|
|
587
|
+
resolvedByTime += 1;
|
|
588
|
+
}
|
|
589
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
await tryGit(this.dir, ['rebase', '--abort'], this.options.gitTimeoutMs);
|
|
593
|
+
this.options.log.warn('dsh-cross-memory: 记忆库 rebase 在 %d 轮后仍未结束,已回滚本次同步', 200);
|
|
594
|
+
return { conflicts, resolvedByResolver, resolvedByTime, mergedByStructure };
|
|
595
|
+
}
|
|
596
|
+
/** Push the current branch, pulling once and retrying when the remote moved. */
|
|
597
|
+
async push() {
|
|
598
|
+
if (this.pushing)
|
|
599
|
+
return false;
|
|
600
|
+
this.pushing = true;
|
|
601
|
+
try {
|
|
602
|
+
const first = await tryGit(this.dir, ['push', '--quiet', 'origin', 'HEAD:main'], this.options.networkTimeoutMs);
|
|
603
|
+
if (first !== undefined)
|
|
604
|
+
return true;
|
|
605
|
+
await this.pull();
|
|
606
|
+
const second = await tryGit(this.dir, ['push', '--quiet', 'origin', 'HEAD:main'], this.options.networkTimeoutMs);
|
|
607
|
+
if (second === undefined)
|
|
608
|
+
this.options.log.warn('dsh-cross-memory: 记忆库推送失败,下一轮再试');
|
|
609
|
+
return second !== undefined;
|
|
610
|
+
}
|
|
611
|
+
finally {
|
|
612
|
+
this.pushing = false;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
/** The memory id of one entry text, for messages about a conflict. */
|
|
617
|
+
export function entryIdOf(text) {
|
|
618
|
+
const entry = parseEntry(text, 'global', 'unknown');
|
|
619
|
+
return entry?.id;
|
|
620
|
+
}
|