@xsok/dsh-enhanced 0.2.2-10 → 0.2.2-11

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/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  版本号前三位对应主程序版本,最后一段是插件自身的发布序号。
4
4
 
5
+ ## 0.2.2-11
6
+
7
+ ### 修复
8
+
9
+ - 取消归档不生效:归档快照在合并前写入、取消事件被过早清理,导致后续取消不产生事件或被其他机器加回(经反复测试,归档同步终于稳定了。。)。
10
+ - 配置同步下载取错来源:新增配置总是复制本机副本,导致同一文件被反复提示、永不收敛。
11
+
12
+ ### 优化
13
+
14
+ - 归档与取消归档也会触发自动同步,并与空闲触发同样受最小间隔约束。
15
+
5
16
  ## 0.2.2-10
6
17
 
7
18
  ### 修复
@@ -89,16 +89,56 @@ export function mergeArchiveEvents(existing, incoming) {
89
89
  return merged;
90
90
  }
91
91
 
92
+ /** Snapshot of every machine's last recorded archived set, for the pruner. */
93
+ export async function readAllArchiveSnapshots(stateDir) {
94
+ const snapshots = [];
95
+ let names = [];
96
+ try {
97
+ names = await fsp.readdir(stateDir);
98
+ } catch {
99
+ return snapshots;
100
+ }
101
+ for (const name of names) {
102
+ if (!/^archive-.+\.json$/u.test(name)) continue;
103
+ if (name === 'archive-events.json') continue;
104
+ const doc = await readJson(path.join(stateDir, name), { ids: [] });
105
+ if (Array.isArray(doc?.ids)) snapshots.push(new Set(doc.ids));
106
+ }
107
+ return snapshots;
108
+ }
109
+
92
110
  /**
93
- * Keep only events that still matter: an `archived` event states current intent
94
- * for every machine, while an `active` event stops mattering once no document
95
- * lists that session as archived. Without this the table grows forever.
111
+ * Keep only events that still matter.
112
+ *
113
+ * An event must survive until **every** machine has observed it: a machine that
114
+ * has not synced yet still holds the old set, and its next merge would undo the
115
+ * change if the intent were already gone. Snapshots are exactly that record —
116
+ * dropping an `active` event early is what let an unarchived session reappear.
117
+ *
118
+ * A grace window keeps recent intent even when snapshots look converged, so a
119
+ * machine that has never synced (no snapshot yet) still receives it.
96
120
  */
97
- export function pruneArchiveEvents(events, keepIds) {
121
+ export function pruneArchiveEvents(events, keepIds, options = {}) {
122
+ const snapshots = Array.isArray(options.snapshots) ? options.snapshots : [];
123
+ const now = Number.isFinite(options.now) ? options.now : Date.now();
124
+ const graceMs = Math.max(0, Number(options.graceDays ?? 30)) * 24 * 60 * 60 * 1000;
98
125
  const kept = {};
99
126
  let removed = 0;
100
127
  for (const [id, event] of Object.entries(events)) {
101
- if (event?.state === 'archived' || keepIds.has(id)) kept[id] = event;
128
+ const at = Date.parse(event?.at ?? '');
129
+ const fresh = !Number.isFinite(at) || now - at < graceMs;
130
+ // With no snapshots at all we cannot prove every machine has seen it, so the
131
+ // event stays; otherwise old intents would vanish before a new machine synced.
132
+ const unknownMachines = snapshots.length === 0;
133
+ let keep;
134
+ if (event?.state === 'archived') {
135
+ const learned = !unknownMachines && snapshots.every((snapshot) => snapshot.has(id));
136
+ keep = fresh || !learned;
137
+ } else {
138
+ const stillHeld = unknownMachines || keepIds.has(id) || snapshots.some((snapshot) => snapshot.has(id));
139
+ keep = fresh || stillHeld;
140
+ }
141
+ if (keep) kept[id] = event;
102
142
  else removed += 1;
103
143
  }
104
144
  return { events: kept, removed };
@@ -130,6 +170,39 @@ export function applyArchiveEvents(archived, events) {
130
170
  return { kept: [...kept], released, added };
131
171
  }
132
172
 
173
+ /**
174
+ * Fold the archive result into both workspace documents.
175
+ *
176
+ * Exported so the whole rule can be exercised without a running Harness: this is
177
+ * where "archived elsewhere" and "unarchived here" are decided.
178
+ *
179
+ * @returns the ids that were released and how many entries the local document
180
+ * gained or lost compared with `archivedBefore`.
181
+ */
182
+ export function mergeArchivedIntoDocuments(deps) {
183
+ const { localDoc, sharedDoc, archivedBefore, archive, events } = deps;
184
+ const released = new Set(archive?.released ?? []);
185
+ // An active event must also release ids this machine no longer lists: the local
186
+ // document dropped them when the reader unarchived, and without this the union
187
+ // below would add them straight back from the shared document.
188
+ for (const [id, event] of Object.entries(events ?? {})) {
189
+ if (event?.state === 'active') released.add(id);
190
+ }
191
+ const effective = Array.isArray(archive?.archived) ? archive.archived : [];
192
+ for (const doc of [localDoc, sharedDoc]) {
193
+ if (doc === null || doc === undefined) continue;
194
+ doc.global = doc.global ?? {};
195
+ const own = Array.isArray(doc.global.archivedSessionIds) ? doc.global.archivedSessionIds : [];
196
+ const merged = new Set([...own, ...effective].filter((id) => id && !released.has(id)));
197
+ doc.global.archivedSessionIds = [...merged].sort();
198
+ }
199
+ const finalLocal = new Set(localDoc?.global?.archivedSessionIds ?? []);
200
+ let changed = 0;
201
+ for (const id of finalLocal) if (!archivedBefore.has(id)) changed += 1;
202
+ for (const id of archivedBefore) if (!finalLocal.has(id)) changed += 1;
203
+ return { changed, released, finalLocal };
204
+ }
205
+
133
206
  /**
134
207
  * Run the archive half of a sync.
135
208
  * @returns the effective archived list plus what changed.
@@ -154,6 +154,7 @@ export async function syncConfigFiles(deps) {
154
154
  const staged = path.join(stagingDir, ...rel.split('/'));
155
155
  await fsp.mkdir(path.dirname(staged), { recursive: true });
156
156
  await fsp.copyFile(entry.file, staged);
157
+ if (Number.isFinite(entry.mtime)) await fsp.utimes(staged, entry.mtime / 1000, entry.mtime / 1000).catch(() => {});
157
158
  details.push({ action: 'staged', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
158
159
  copied += 1;
159
160
  return;
@@ -202,8 +203,11 @@ export async function syncConfigFiles(deps) {
202
203
  skipped += 1;
203
204
  continue;
204
205
  }
206
+ // `entry` is this machine's copy, `other` is the share: a pull must copy the
207
+ // share's file, otherwise the "download" writes the local copy to itself and
208
+ // the pair never converges.
205
209
  if (entry.mtime > other.mtime) await push(rel, entry, other);
206
- else await pull(rel, entry, other);
210
+ else await pull(rel, other, entry);
207
211
  }
208
212
  for (const [rel, entry] of shared) {
209
213
  if (local.has(rel)) continue;
@@ -14,7 +14,14 @@ import { scanSessionGroups, scanSessions } from './scan.js';
14
14
  import { readSessionFile } from './session.js';
15
15
  import { loadPathMap, resolveLocalPath } from './paths.js';
16
16
  import { mergeWorkspaceFiles } from './workspace.js';
17
- import { pruneArchiveEvents, syncArchiveState, writeArchiveEvents } from './archive.js';
17
+ import {
18
+ mergeArchivedIntoDocuments,
19
+ pruneArchiveEvents,
20
+ readAllArchiveSnapshots,
21
+ syncArchiveState,
22
+ writeArchiveEvents,
23
+ writeArchiveSnapshot,
24
+ } from './archive.js';
18
25
  import { mergeProjcacheTitles } from './projcache.js';
19
26
  import { syncConfigFiles } from './config.js';
20
27
  import { syncPluginList } from './pluginlist.js';
@@ -223,31 +230,25 @@ async function runSyncJsInner(deps) {
223
230
  for (const doc of [workspace.local, workspace.shared]) {
224
231
  for (const id of doc.global?.archivedSessionIds ?? []) stillArchived.add(id);
225
232
  }
226
- prunedEvents = pruneArchiveEvents(archive.events, stillArchived);
233
+ const archiveSnapshots = await readAllArchiveSnapshots(stateDir);
234
+ prunedEvents = pruneArchiveEvents(archive.events, stillArchived, { snapshots: archiveSnapshots });
227
235
  if (apply && prunedEvents.removed > 0) await writeArchiveEvents(stateDir, prunedEvents.events);
228
236
 
229
- const released = new Set(archive.released);
230
- // An active event must also release ids this machine no longer lists: the
231
- // local document dropped them when the reader unarchived, and without this
232
- // the union below would add them straight back from the shared document.
233
- for (const [id, event] of Object.entries(prunedEvents.events ?? archive.events ?? {})) {
234
- if (event?.state === 'active') released.add(id);
235
- }
236
- const effective = archive.archived;
237
- for (const doc of [workspace.local, workspace.shared]) {
238
- doc.global = doc.global ?? {};
239
- const own = Array.isArray(doc.global.archivedSessionIds) ? doc.global.archivedSessionIds : [];
240
- const merged = new Set([...own, ...effective].filter((id) => id && !released.has(id)));
241
- doc.global.archivedSessionIds = [...merged].sort();
242
- }
243
- // What the merge actually produced for this machine decides whether the list
244
- // changes: it covers both archive events and ids arriving via workspace.json.
245
- const finalLocalArchived = new Set(workspace.local.global?.archivedSessionIds ?? []);
246
- let mergedArchiveChanged = 0;
247
- for (const id of finalLocalArchived) if (!archivedBefore.has(id)) mergedArchiveChanged += 1;
248
- for (const id of archivedBefore) if (!finalLocalArchived.has(id)) mergedArchiveChanged += 1;
249
- archive.changed = mergedArchiveChanged;
237
+ const mergedArchive = mergeArchivedIntoDocuments({
238
+ localDoc: workspace.local,
239
+ sharedDoc: workspace.shared,
240
+ archivedBefore,
241
+ archive,
242
+ events: prunedEvents.events ?? archive.events ?? {},
243
+ });
244
+ const finalLocalArchived = mergedArchive.finalLocal;
245
+ archive.changed = mergedArchive.changed;
250
246
  if (apply) {
247
+ // The snapshot must describe the set this machine ends the run with, not
248
+ // the one the archive step saw: ids that arrived through workspace.json
249
+ // would otherwise never be remembered, and a later unarchive would emit
250
+ // no event at all.
251
+ await writeArchiveSnapshot(stateDir, machineId, finalLocalArchived).catch(() => {});
251
252
  if (validWorkspaceDoc(workspace.local)) {
252
253
  await writeJson(path.join(dshHome, 'storages', 'workspace.json'), workspace.local);
253
254
  } else {
package/host/restart.js CHANGED
@@ -87,12 +87,12 @@ if (-not $cleaned -and (Test-Path -LiteralPath $cookies)) {
87
87
  }
88
88
  }
89
89
 
90
- $pendingRoot = Join-Path (Join-Path $env:USERPROFILE '.dsh\dsh-enhanced') 'pending\profiles'
90
+ $pendingRoot = Join-Path (Join-Path $env:USERPROFILE '.dsh\\dsh-enhanced') 'pending\\profiles'
91
91
  if (Test-Path -LiteralPath $pendingRoot) {
92
92
  Get-ChildItem -LiteralPath $pendingRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
93
93
  $src = Join-Path $_.FullName 'cordis.patch.yml'
94
94
  if (Test-Path -LiteralPath $src) {
95
- $dst = Join-Path (Join-Path (Join-Path $env:USERPROFILE '.dsh\profiles') $_.Name) 'cordis.patch.yml'
95
+ $dst = Join-Path (Join-Path (Join-Path $env:USERPROFILE '.dsh\\profiles') $_.Name) 'cordis.patch.yml'
96
96
  try {
97
97
  if (Test-Path -LiteralPath $dst) { Copy-Item -LiteralPath $dst -Destination ($dst + '.bak') -Force }
98
98
  Copy-Item -LiteralPath $src -Destination $dst -Force
package/host/schedule.js CHANGED
@@ -311,5 +311,9 @@ async function autoRun(reason) {
311
311
  watchers.clear();
312
312
  };
313
313
 
314
- return { dispose, status, resume, subscribe };
314
+ // Any caller (idle, archive, …) goes through autoRun, so the cooldown and its
315
+ // deferred retry apply to every trigger alike.
316
+ const trigger = (reason) => { void autoRun(reason); };
317
+
318
+ return { dispose, status, resume, subscribe, trigger };
315
319
  }
package/index.js CHANGED
@@ -31,6 +31,7 @@ import { inspectOverride, overwriteCloud, overwriteLocal } from './host/overwrit
31
31
  import { moveCandidates, moveSession, readAllEvents } from './host/move.js';
32
32
  import { inspectSyncTarget, readSyncHistory, readSyncState, recordOverwrite, resolveSyncTarget, runSync } from './host/sync.js';
33
33
  import { installSyncScheduler } from './host/schedule.js';
34
+ import { applyPendingConfig } from './host/engine/pending.js';
34
35
  import { appVersion, readEnvRecord, runEnvironmentCheck, writeEnvironmentReport, writeEnvRecord } from './host/envcheck.js';
35
36
  import { testConnection } from './host/webdav.js';
36
37
  import { pullMirror, pushMirror } from './host/mirror.js';
@@ -79,6 +80,21 @@ export function apply(ctx, config = {}) {
79
80
  }
80
81
  })();
81
82
 
83
+ // A config staged by an earlier sync is moved into place here, because a manual
84
+ // restart never runs the helper that normally does it.
85
+ void (async () => {
86
+ try {
87
+ const dshHome = path.dirname(paths.base);
88
+ const applied = await applyPendingConfig(dshHome);
89
+ if (applied > 0) {
90
+ await appendFile(path.join(paths.base, 'restart.log'), `${new Date().toISOString()} applied ${String(applied)} staged config file(s)
91
+ `, 'utf8').catch(() => {});
92
+ }
93
+ } catch {
94
+ // Never block the plugin on a staged file.
95
+ }
96
+ })();
97
+
82
98
  // Bumped for every committed user message; the composer badge watches it to
83
99
  // know the reader sent something and the finished-sync line may go away.
84
100
  let userMessageSeq = 0;
@@ -335,6 +351,26 @@ export function apply(ctx, config = {}) {
335
351
  const scheduler = installSyncScheduler(ctx, { paths, agents: ctx.get('agents') });
336
352
  ctx.effect(() => () => scheduler.dispose(), 'dsh-enhanced: sync scheduler');
337
353
 
354
+ // Archiving changes the shared state, so it asks for a sync like an idle edge
355
+ // does; autoRun keeps the cooldown and schedules the deferred retry.
356
+ ctx.effect(() => ctx.on('workspace/session-archived', () => { scheduler.trigger('archive'); }), 'dsh-enhanced: archive sync trigger');
357
+ ctx.effect(() => {
358
+ let timer = null;
359
+ const dispose = ctx.on('workspace/session-unarchiving', () => {
360
+ // This event fires before the archive flag is removed, so wait a moment
361
+ // before asking for a sync; the run reads the updated document.
362
+ if (timer !== null) clearTimeout(timer);
363
+ timer = setTimeout(() => {
364
+ timer = null;
365
+ scheduler.trigger('unarchive');
366
+ }, 1500);
367
+ });
368
+ return () => {
369
+ if (timer !== null) clearTimeout(timer);
370
+ if (typeof dispose === 'function') dispose();
371
+ };
372
+ }, 'dsh-enhanced: unarchive sync trigger');
373
+
338
374
  // Deleting a workspace drops every recycle-bin record it owned, immediately:
339
375
  // the workspace domain write that removes the record is the same commit the
340
376
  // sidebar sees. The lazy check in `listTrash` stays as a fallback for
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xsok/dsh-enhanced",
3
- "version": "0.2.2-10",
3
+ "version": "0.2.2-11",
4
4
  "description": "DeepSeek Harness 增强插件:会话删除与找回、跨工作区移动、全库内容搜索、自动加载历史,以及多设备同步(本地目录 / WebDAV)。",
5
5
  "type": "module",
6
6
  "license": "MIT",