dsh-session-sync 0.3.0 → 0.3.2

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/ARCHITECTURE.md CHANGED
@@ -19,6 +19,7 @@
19
19
  | `lib/paths.mjs` | Path resolution, nesting checks, and fork-file naming — pure |
20
20
  | `lib/sanitize.mjs` | Pure display/log redaction (remote-URL credentials, tokens, `key=value` secrets, path-containment display) |
21
21
  | `lib/merge.mjs` | Append-only three-way merge classification — pure |
22
+ | `lib/durability.mjs` | Host durability wait before an auto push: calls the public `ctx.sessions.flush(session)` barrier (the JSONL writer batches live events for up to 200 ms) with a timeout; never throws and never blocks the session |
22
23
  | `lib/mirror.mjs` | Byte mirror from the session store into the worktree, restore back into the live store, and deletion protection (`node:fs`). Projection-aware: projected local copies are skipped as sources and reattached to the mirror's original header frame; `followSessionSymlinks` opts into contained links only |
23
24
  | `lib/cwdmap.mjs` | Restore-time cwd matching/projection — pure (`cwdMap` longest-prefix + segment boundary, host-compatible `projectKey`, `--unmapped--` fallback) |
24
25
  | `lib/sessionlog.mjs` | Session-log first frame read/rewrite (`node:zlib`): the header is its own zstd frame, so a projection replaces only that frame |
@@ -75,7 +76,7 @@ Sync metadata (`deviceId`, `lastPullAt`, `lastPushAt`, `lastPushHead`, `lastErro
75
76
  Every automatic behavior is a Cordis effect, so stop/hot-reload removes it:
76
77
 
77
78
  - `autoPullOnStart` — `ctx.effect` pulls once on mount.
78
- - `autoPushOnTurnEnd` — `ctx.on('session/event')` pushes after `turn/end`.
79
+ - `autoPushOnTurnEnd` — `ctx.on('session/event')` pushes after `turn/end`, but only after `ctx.sessions.flush(session)` has drained the host's buffered writes (bounded by `durabilityTimeoutMs`, default 2000 ms; on timeout it logs and pushes the current on-disk snapshot).
79
80
  - `pullIntervalMinutes` — `ctx.effect` wraps a `setInterval` periodic pull (the disposer clears the timer).
80
81
 
81
82
  Auto runs are covered by the config grant and never re-confirm.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.1] - 2026-11-14
4
+
5
+ ### Fixed
6
+
7
+ - **An auto push no longer mirrors a `turn/end` the host has not written yet.** The JSONL backend buffers live session events for up to 200 ms (`LIVE_WRITE_BATCH_MAX_DELAY_MS`, `session-persistence-jsonl/src/storage.ts:37`) and only `persistBatch`es on the timer or a `session/flush` (`:275-282`, `:555-562`). The `turn/end` listener used to `push()` immediately, so the mirror could miss the final `turn/end` line — or the whole session file on the first append — and a cross-device restore then saw an unclosed turn. The listener now awaits the host's public durability barrier `ctx.sessions.flush(session)` (`SessionStore.flush` → `session/flush` → backend `drainLive` + `handle.flush`) before mirroring; the wait yields one microtask first so the persistence router has enqueued the very event being handled. It is bounded by the new `durabilityTimeoutMs` (default `2000`, `0` = do not wait): a timeout, a rejecting barrier, or a host without `sessions.flush` (older than 0.2.2) is logged once and the push continues with the current on-disk snapshot, so a stalled backend can never block a turn.
8
+
9
+ ### Changed
10
+
11
+ - devDependencies move from the `0.2.2-rc.1` wave to `0.2.2-rc.3`, including an explicit `@deepseek-ai/dsh-session-projection` pin so the optional peer no longer keeps a `0.2.2-rc.1` copy (and its zod 4.4.3) in the lockfile. The production `zod` pin moves 4.4.3 → 4.6.6 to match `dsh-storage-domain@0.2.2-rc.3`; peer ranges and `engines.dsh` already cover `>=0.2.2-0 <0.3.0`.
12
+
3
13
  ## [0.3.0] - 2026-11-13
4
14
 
5
15
  ### Added
package/LICENSE CHANGED
File without changes
package/PRIVACY.md CHANGED
File without changes
package/README.en.md CHANGED
@@ -159,7 +159,7 @@ Most-used keys:
159
159
  | `confirmVia` | `auto` | Confirmation channel: `auto` (userQuestions first, then approval), `userQuestions`, `approval` |
160
160
 
161
161
  <details>
162
- <summary>Full configuration table (23 keys)</summary>
162
+ <summary>Full configuration table (24 keys)</summary>
163
163
 
164
164
  | Key | Default | Meaning |
165
165
  |---|---|---|
@@ -175,6 +175,7 @@ Most-used keys:
175
175
  | `ageIdentity` | `''` | Path to a passphrase-less age secret key for decryption; empty = cannot decrypt, degrades to plaintext |
176
176
  | `autoPullOnStart` | `false` | Pull once when the plugin mounts (config is the grant; no re-confirm) |
177
177
  | `autoPushOnTurnEnd` | `false` | Push after every closed turn |
178
+ | `durabilityTimeoutMs` | `2000` | Upper bound for waiting on the session durability barrier (`ctx.sessions.flush`) before an auto push — the host JSONL writer batches live events for up to 200 ms; on timeout it logs and pushes anyway; `0` = do not wait |
178
179
  | `pullIntervalMinutes` | `0` | Periodic pull every N minutes (`0` = off, max `10080`) |
179
180
  | `cwdMap` | `[]` | Restore-time cwd projection `[{from, to}]` (longest prefix wins; unmatched cross-platform cwds go read-only under `<sessionRoot>/--unmapped--`) |
180
181
  | `followSessionSymlinks` | `false` | Follow symbolic links whose realpath stays inside `sessionRoot` (Android/proot diagnostics) |
package/README.es.md CHANGED
@@ -159,7 +159,7 @@ Claves más usadas:
159
159
  | `confirmVia` | `auto` | Canal de confirmación: `auto` (primero userQuestions, luego approval), `userQuestions`, `approval` |
160
160
 
161
161
  <details>
162
- <summary>Tabla de configuración completa (23 claves)</summary>
162
+ <summary>Tabla de configuración completa (24 claves)</summary>
163
163
 
164
164
  | Clave | Valor por defecto | Significado |
165
165
  |---|---|---|
@@ -175,6 +175,7 @@ Claves más usadas:
175
175
  | `ageIdentity` | `''` | Ruta a una clave secreta age sin frase de contraseña para descifrar; vacío = no puede descifrar, degrada a texto plano |
176
176
  | `autoPullOnStart` | `false` | Pull una vez al montar el plugin (la configuración es la autorización; no reconfirma) |
177
177
  | `autoPushOnTurnEnd` | `false` | Push tras cada turno cerrado |
178
+ | `durabilityTimeoutMs` | `2000` | Límite de espera de la barrera de durabilidad (`ctx.sessions.flush`) antes de un push automático: el escritor JSONL del host agrupa eventos live hasta 200 ms; al expirar, registra y hace push igualmente; `0` = no esperar |
178
179
  | `pullIntervalMinutes` | `0` | Pull periódico cada N minutos (`0` = apagado, máximo `10080`) |
179
180
  | `cwdMap` | `[]` | Proyección de cwd en la restauración `[{from, to}]` (gana el prefijo más largo; los cwd multiplataforma sin coincidencia quedan en solo lectura bajo `<sessionRoot>/--unmapped--`) |
180
181
  | `followSessionSymlinks` | `false` | Sigue enlaces simbólicos cuyo realpath permanece dentro de `sessionRoot` (diagnóstico para Android/proot) |
package/README.hi.md CHANGED
@@ -159,7 +159,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn
159
159
  | `confirmVia` | `auto` | पुष्टि चैनल: `auto` (पहले userQuestions, फिर approval), `userQuestions`, `approval` |
160
160
 
161
161
  <details>
162
- <summary>पूरी कॉन्फ़िगरेशन तालिका (23 कुंजियाँ)</summary>
162
+ <summary>पूरी कॉन्फ़िगरेशन तालिका (24 कुंजियाँ)</summary>
163
163
 
164
164
  | कुंजी | डिफ़ॉल्ट | अर्थ |
165
165
  |---|---|---|
@@ -175,6 +175,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn
175
175
  | `ageIdentity` | `''` | डिक्रिप्शन के लिए पासफ़्रेज़-रहित age गुप्त कुंजी फ़ाइल का पथ; खाली = डिक्रिप्ट नहीं कर सकता, plaintext पर अवनति |
176
176
  | `autoPullOnStart` | `false` | प्लगइन माउंट होने पर एक बार pull (कॉन्फ़िग ही अनुमति है; दोबारा पुष्टि नहीं) |
177
177
  | `autoPushOnTurnEnd` | `false` | हर बंद टर्न के बाद push |
178
+ | `durabilityTimeoutMs` | `2000` | ऑटो push से पहले सत्र की durability बाधा (`ctx.sessions.flush`) की प्रतीक्षा की सीमा — होस्ट का JSONL writer live इवेंट को 200 ms तक बैच करता है; टाइमआउट पर लॉग करके push जारी रहता है; `0` = प्रतीक्षा नहीं |
178
179
  | `pullIntervalMinutes` | `0` | हर N मिनट में आवधिक pull (`0` = बंद, अधिकतम `10080`) |
179
180
  | `cwdMap` | `[]` | पुनर्स्थापन के समय cwd प्रोजेक्शन `[{from, to}]` (सबसे लंबा प्रीफ़िक्स जीतता है; बिना मेल वाले क्रॉस-प्लेटफ़ॉर्म cwd `<sessionRoot>/--unmapped--` के नीचे केवल-पढ़ने योग्य रहते हैं) |
180
181
  | `followSessionSymlinks` | `false` | उन सिम्बोलिक लिंक का पालन करें जिनका realpath `sessionRoot` के भीतर ही रहता है (Android/proot निदान) |
package/README.md CHANGED
@@ -159,7 +159,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn
159
159
  | `confirmVia` | `auto` | 确认通道:`auto`(优先 userQuestions,其次 approval)、`userQuestions`、`approval` |
160
160
 
161
161
  <details>
162
- <summary>完整配置表(23 个键)</summary>
162
+ <summary>完整配置表(24 个键)</summary>
163
163
 
164
164
  | 键 | 默认值 | 含义 |
165
165
  |---|---|---|
@@ -175,6 +175,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn
175
175
  | `ageIdentity` | `''` | 无口令 age 私钥文件路径(用于解密);空 = 无法解密、降级明文 |
176
176
  | `autoPullOnStart` | `false` | 插件挂载时拉取一次(配置即授权,不再确认) |
177
177
  | `autoPushOnTurnEnd` | `false` | 每个关闭轮次后推送 |
178
+ | `durabilityTimeoutMs` | `2000` | 自动推送前等待该会话落盘的上限:宿主 JSONL 对 live 事件有 200ms 批量写窗,这里调用公开的 `ctx.sessions.flush` 落盘屏障;超时只记日志并照常推送;`0` = 不等待 |
178
179
  | `pullIntervalMinutes` | `0` | 每 N 分钟周期拉取(`0` = 关闭,最大 `10080`) |
179
180
  | `cwdMap` | `[]` | 恢复期 cwd 投影表 `[{from, to}]`(最长前缀优先;未命中的跨平台 cwd 归一到 `<sessionRoot>/--unmapped--`,只读) |
180
181
  | `followSessionSymlinks` | `false` | 是否跟随 realpath 仍在 `sessionRoot` 内的符号链接(Android/proot 诊断) |
package/README.pt.md CHANGED
@@ -159,7 +159,7 @@ Chaves mais usadas:
159
159
  | `confirmVia` | `auto` | Canal de confirmação: `auto` (userQuestions primeiro, depois approval), `userQuestions`, `approval` |
160
160
 
161
161
  <details>
162
- <summary>Tabela de configuração completa (23 chaves)</summary>
162
+ <summary>Tabela de configuração completa (24 chaves)</summary>
163
163
 
164
164
  | Chave | Padrão | Significado |
165
165
  |---|---|---|
@@ -175,6 +175,7 @@ Chaves mais usadas:
175
175
  | `ageIdentity` | `''` | Caminho de uma chave secreta age sem frase de senha para descriptografar; vazio = não consegue descriptografar, degrada para texto plano |
176
176
  | `autoPullOnStart` | `false` | Pull uma vez ao montar o plugin (a configuração é a autorização; sem reconfirmação) |
177
177
  | `autoPushOnTurnEnd` | `false` | Push após cada turno fechado |
178
+ | `durabilityTimeoutMs` | `2000` | Limite de espera pela barreira de durabilidade (`ctx.sessions.flush`) antes de um push automático — o writer JSONL do host agrupa eventos live por até 200 ms; no timeout, registra e faz push mesmo assim; `0` = não aguardar |
178
179
  | `pullIntervalMinutes` | `0` | Pull periódico a cada N minutos (`0` = desligado, máximo `10080`) |
179
180
  | `cwdMap` | `[]` | Projeção de cwd na restauração `[{from, to}]` (o prefixo mais longo vence; cwds multiplataforma sem entrada ficam somente leitura em `<sessionRoot>/--unmapped--`) |
180
181
  | `followSessionSymlinks` | `false` | Segue links simbólicos cujo realpath permanece dentro de `sessionRoot` (diagnóstico Android/proot) |
package/SECURITY.md CHANGED
File without changes
File without changes
package/cordis.patch.yml CHANGED
@@ -35,6 +35,12 @@
35
35
  # covered by the config grant and never re-confirm.
36
36
  autoPullOnStart: false
37
37
  autoPushOnTurnEnd: false
38
+ # Upper bound (ms) for waiting on the host's session durability barrier
39
+ # (ctx.sessions.flush) before an auto push. The JSONL writer batches live
40
+ # events for up to 200 ms, so a push issued exactly at turn/end can miss
41
+ # the final event; on timeout the plugin logs and pushes the current
42
+ # on-disk snapshot anyway. 0 = do not wait.
43
+ durabilityTimeoutMs: 2000
38
44
  pullIntervalMinutes: 0
39
45
  # Confirmation channel for /sync pull|push and the sync_* tools:
40
46
  # auto (userQuestions first, then approval) · userQuestions · approval.
package/icon.svg CHANGED
File without changes
package/index.mjs CHANGED
@@ -57,6 +57,7 @@ import { collectStatus } from './lib/status.mjs'
57
57
  import { renderDiff, renderPull, renderPush, renderStatus, errorValue } from './lib/render.mjs'
58
58
  import { confirmSync, hasOpenTurn, makeEventGate, maybeAppendSessionEvent, openTurnFromProjection } from './lib/gate.mjs'
59
59
  import { sessionSyncDomainSpec } from './lib/domain.mjs'
60
+ import { waitForSessionDurability } from './lib/durability.mjs'
60
61
  import {
61
62
  matchCwdMap,
62
63
  normalizeCwdMap,
@@ -118,6 +119,7 @@ export function probeIgnorableAppend() {
118
119
  * @property {string} [ageIdentity] age 身份文件路径(无口令私钥;空 = 无法解密,降级明文)。
119
120
  * @property {boolean} [autoPullOnStart] 挂载时自动拉取一次(配置即授权,不再确认)。
120
121
  * @property {boolean} [autoPushOnTurnEnd] 每个 turn/end 后自动推送(配置即授权)。
122
+ * @property {number} [durabilityTimeoutMs] 自动推送前等该会话落盘的上限 ms(宿主 JSONL 有 200ms 批量写窗;0 = 不等待,超时只记日志并继续)。
121
123
  * @property {number} [pullIntervalMinutes] 周期自动拉取间隔分钟(0 = 关闭)。
122
124
  * @property {'auto'|'userQuestions'|'approval'} [confirmVia] 确认通道(auto 优先 userQuestions)。
123
125
  * @property {ReadonlyArray<{from: string, to: string}>} [cwdMap] 恢复期 cwd 投影表(最长前缀优先;未命中的跨平台 cwd 归一到 sessionRoot/--unmapped--)。
@@ -145,6 +147,7 @@ export const Config = Schema.object({
145
147
  ageIdentity: Schema.string().default(DEFAULTS.AGE_IDENTITY),
146
148
  autoPullOnStart: Schema.boolean().default(DEFAULTS.AUTO_PULL_ON_START),
147
149
  autoPushOnTurnEnd: Schema.boolean().default(DEFAULTS.AUTO_PUSH_ON_TURN_END),
150
+ durabilityTimeoutMs: Schema.number().default(DEFAULTS.DURABILITY_TIMEOUT_MS),
148
151
  pullIntervalMinutes: Schema.number().default(DEFAULTS.PULL_INTERVAL_MINUTES),
149
152
  confirmVia: Schema.union(Object.values(CONFIRM_CHANNELS)).default(DEFAULTS.CONFIRM_VIA),
150
153
  cwdMap: Schema.array(Schema.object({
@@ -180,6 +183,7 @@ export function resolveConfig(config = {}) {
180
183
  ageIdentity: config.ageIdentity ?? DEFAULTS.AGE_IDENTITY,
181
184
  autoPullOnStart: config.autoPullOnStart ?? DEFAULTS.AUTO_PULL_ON_START,
182
185
  autoPushOnTurnEnd: config.autoPushOnTurnEnd ?? DEFAULTS.AUTO_PUSH_ON_TURN_END,
186
+ durabilityTimeoutMs: config.durabilityTimeoutMs ?? DEFAULTS.DURABILITY_TIMEOUT_MS,
183
187
  pullIntervalMinutes: config.pullIntervalMinutes ?? DEFAULTS.PULL_INTERVAL_MINUTES,
184
188
  confirmVia: config.confirmVia ?? DEFAULTS.CONFIRM_VIA,
185
189
  cwdMap: normalizeCwdMap(config.cwdMap ?? DEFAULTS.CWD_MAP),
@@ -226,6 +230,9 @@ export function resolveConfig(config = {}) {
226
230
  if (!Number.isInteger(resolved.pullIntervalMinutes) || resolved.pullIntervalMinutes < LIMITS.MIN_PULL_INTERVAL_MINUTES || resolved.pullIntervalMinutes > LIMITS.MAX_PULL_INTERVAL_MINUTES) {
227
231
  throw badConfig(`pullIntervalMinutes must be an integer in [${LIMITS.MIN_PULL_INTERVAL_MINUTES}, ${LIMITS.MAX_PULL_INTERVAL_MINUTES}]`)
228
232
  }
233
+ if (!Number.isInteger(resolved.durabilityTimeoutMs) || resolved.durabilityTimeoutMs < LIMITS.MIN_DURABILITY_TIMEOUT_MS || resolved.durabilityTimeoutMs > LIMITS.MAX_DURABILITY_TIMEOUT_MS) {
234
+ throw badConfig(`durabilityTimeoutMs must be an integer in [${LIMITS.MIN_DURABILITY_TIMEOUT_MS}, ${LIMITS.MAX_DURABILITY_TIMEOUT_MS}]`)
235
+ }
229
236
  if (typeof resolved.followSessionSymlinks !== 'boolean') {
230
237
  throw badConfig('followSessionSymlinks must be a boolean')
231
238
  }
@@ -903,25 +910,45 @@ export function apply(ctx, config = {}) {
903
910
  }, `${PLUGIN_NAME}.auto-pull-on-start`)
904
911
  }
905
912
 
906
- // turn/end 自动推送(配置即授权;每轮结束拉一次快照并推送)。
913
+ // turn/end 自动推送(配置即授权;每轮结束先等该会话落盘,再拉快照推送)。
907
914
  if (resolved.autoPushOnTurnEnd) {
908
915
  // #30:有些宿主(Android/proot 的 DSH Go)不发 session/event;把"监听器已
909
916
  // 注册"记进日志,让外部可判断的是宿主事件还是插件注册。
910
- logger.info(`auto push listener registered (session/event turn/end → push); pullIntervalMinutes=${resolved.pullIntervalMinutes}`)
917
+ logger.info(`auto push listener registered (session/event turn/end → push); pullIntervalMinutes=${resolved.pullIntervalMinutes}; durabilityTimeoutMs=${resolved.durabilityTimeoutMs}`)
918
+ let durabilityUnsupportedWarned = false
919
+ const autoPush = async (session) => {
920
+ // 宿主的 JSONL 持久化对 live 事件有 200ms 批量写窗(见 lib/durability.mjs):
921
+ // 不等这层落盘屏障,镜像就会缺最后一条 turn/end —— 跨设备恢复会看到未闭合
922
+ // 轮次。等待有上限且绝不抛出:超时/失败只记日志,照常推送当前盘上快照。
923
+ const durability = await waitForSessionDurability(session, {
924
+ sessions: ctx.sessions,
925
+ timeoutMs: resolved.durabilityTimeoutMs,
926
+ })
927
+ if (durability.timedOut === true) {
928
+ warn(`auto push: session ${session.id} was not durable within ${resolved.durabilityTimeoutMs}ms; mirroring the current on-disk snapshot`)
929
+ } else if (durability.unsupported === true) {
930
+ if (!durabilityUnsupportedWarned) {
931
+ durabilityUnsupportedWarned = true
932
+ warn('auto push: this host exposes no sessions.flush(); mirroring without a durability wait (host older than 0.2.2)')
933
+ }
934
+ } else if (durability.error !== undefined) {
935
+ warn(`auto push: durability wait failed for session ${session.id}: ${durability.error}; mirroring the current on-disk snapshot`)
936
+ }
937
+ const result = await engine.push()
938
+ maybeAppendSessionEvent(session, SESSION_EVENTS.PUSH, {
939
+ sessionId: session.id,
940
+ ok: result.ok,
941
+ error: result.error,
942
+ pushed: result.pushed,
943
+ mirrored: result.mirrored,
944
+ deleted: result.deleted,
945
+ head: result.head,
946
+ }, eventGate, warn)
947
+ if (!result.ok) warn(`auto push failed: ${result.error ?? 'unknown error'}`)
948
+ }
911
949
  ctx.on('session/event', (session, event) => {
912
950
  if (event.type !== 'turn/end') return
913
- void engine.push().then(result => {
914
- maybeAppendSessionEvent(session, SESSION_EVENTS.PUSH, {
915
- sessionId: session.id,
916
- ok: result.ok,
917
- error: result.error,
918
- pushed: result.pushed,
919
- mirrored: result.mirrored,
920
- deleted: result.deleted,
921
- head: result.head,
922
- }, eventGate, warn)
923
- if (!result.ok) warn(`auto push failed: ${result.error ?? 'unknown error'}`)
924
- })
951
+ void autoPush(session).catch(error => warn(`auto push failed: ${messageOf(error)}`))
925
952
  })
926
953
  }
927
954
 
package/lib/age.mjs CHANGED
File without changes
package/lib/backend.mjs CHANGED
File without changes
package/lib/constants.mjs CHANGED
@@ -109,6 +109,8 @@ export const DEFAULTS = Object.freeze({
109
109
  AGE_IDENTITY: '',
110
110
  AUTO_PULL_ON_START: false,
111
111
  AUTO_PUSH_ON_TURN_END: false,
112
+ // 自动推送前等宿主把该会话落盘的上限(ms);见 lib/durability.mjs。
113
+ DURABILITY_TIMEOUT_MS: 2000,
112
114
  PULL_INTERVAL_MINUTES: 0,
113
115
  CONFIRM_VIA: CONFIRM_CHANNELS.AUTO,
114
116
  CWD_MAP: Object.freeze([]),
@@ -132,6 +134,9 @@ export const LIMITS = Object.freeze({
132
134
  MAX_MAX_OUTPUT_BYTES: 16 * 1024 * 1024,
133
135
  MIN_PULL_INTERVAL_MINUTES: 0,
134
136
  MAX_PULL_INTERVAL_MINUTES: 10080,
137
+ // 0 = 不等待(旧行为);上限与 timer 上限无关,只是别让自动推送被拖太久。
138
+ MIN_DURABILITY_TIMEOUT_MS: 0,
139
+ MAX_DURABILITY_TIMEOUT_MS: 60_000,
135
140
  MAX_COMMIT_MESSAGE_LENGTH: 200,
136
141
  MAX_DEVICE_ID_LENGTH: 128,
137
142
  })
package/lib/cwdmap.mjs CHANGED
File without changes
package/lib/domain.mjs CHANGED
File without changes
@@ -0,0 +1,80 @@
1
+ // lib/durability.mjs — 等宿主把该会话的缓冲事件落盘再读(零 DSH 依赖)。
2
+ //
3
+ // 为什么不能"turn/end 一到就镜像":宿主的 JSONL 持久化对 **live 事件**做有界
4
+ // 批量写窗 —— `LIVE_WRITE_BATCH_MAX_DELAY_MS = 200`
5
+ // (session-persistence-jsonl/src/storage.ts:37);`session/event` 只是把事件
6
+ // 交给 `enqueueLive` 缓冲并起一个 200ms 定时器(同文件 :269-283),真正的
7
+ // `persistBatch` 发生在定时器或 `session/flush` 触发时(同文件 :286-341、:555-562)。
8
+ // 因此 `turn/end` 刚 append 时,磁盘上的会话日志通常**还没有这一行**(首次
9
+ // 追加时甚至整个会话文件都还没物化)。在 turn/end 上立刻做字节镜像,推给
10
+ // 别的设备的就是一个**未闭合的轮次**——这正是本插件要避免的跨设备状态不一致。
11
+ //
12
+ // 宿主 0.2.2 给出的公开落盘面是 `SessionStore.flush(session)`
13
+ // (@deepseek-ai/dsh-session 的 `ctx.sessions.flush`;core/session/src/index.ts:1410-1434,
14
+ // 注释明确写着 "THE flush entry point … consumers that flush themselves before
15
+ // reading storage")。它派发 `session/flush`(core/session/src/types.ts:74),
16
+ // 持久化后端随即 `drainLive()` + `handle.flush()`(storage.ts:555-562),
17
+ // 因此 flush 决议时该会话已 append 的事件都已落盘。宿主自己的事件文档也把
18
+ // 这条责任写给了读存储的消费者:"consumers that read storage after
19
+ // `whenIdle()` flush themselves"(core/session/src/types.ts:299-300)。
20
+ //
21
+ // 本模块只包这一件事:调用落盘屏障 + 超时兜底。**任何失败/超时只回报,绝不抛**
22
+ // ——调用方照常镜像(宁可镜像落后一拍,也不让一轮会话被卡死的后端拖住)。
23
+
24
+ import { messageOf } from './errors.mjs'
25
+
26
+ /** 未配置时的落盘等待上限(ms):远大于宿主的 200ms 批量窗,又远小于一轮交互。 */
27
+ export const DURABILITY_TIMEOUT_MS = 2000
28
+
29
+ /**
30
+ * @typedef {object} DurabilityOutcome
31
+ * @property {boolean} ok - true = 屏障已决议(宿主无持久化监听器也算:没有待落盘的东西)。
32
+ * @property {boolean} [timedOut] - 超时(调用方应继续镜像,只记日志)。
33
+ * @property {boolean} [unsupported] - 该宿主没有公开的 `flush` 面(旧宿主),无法等待。
34
+ * @property {boolean} [skipped] - 配置为 0,明确不等待。
35
+ * @property {string} [error] - 屏障自身失败(脱敏后的消息);不是抛出。
36
+ */
37
+
38
+ /**
39
+ * 等待 `session` 的缓冲事件落盘,最多 `timeoutMs`。
40
+ *
41
+ * 顺序契约:本函数**先让出一个微任务**再调用 `flush`。宿主的 `session/event`
42
+ * 监听器是同步派发的(core/session/src/index.ts 的 `commit()` →
43
+ * `invokeContainedSessionObservers`),持久化后端的 `enqueueLive` 与我们的
44
+ * 处理器在同一个同步派发里;微任务只会在整个同步派发结束后运行,所以
45
+ * `drainLive()` 一定看得见触发本次调用的那条 `turn/end`。
46
+ *
47
+ * @param {unknown} session - 宿主的 live `Session`(原样交给 `flush`)。
48
+ * @param {object} [deps] - 依赖与上限。
49
+ * @param {{flush?: (session: unknown) => unknown}} [deps.sessions] - `ctx.sessions`(能力探测:无 `flush` 即旧宿主)。
50
+ * @param {number} [deps.timeoutMs] - 等待上限(ms,≤0 = 不等待)。
51
+ * @returns {Promise<DurabilityOutcome>} 结果对象;永不 reject。
52
+ */
53
+ export async function waitForSessionDurability(session, deps = {}) {
54
+ const sessions = deps?.sessions
55
+ const flush = sessions?.flush
56
+ if (typeof flush !== 'function') return { ok: false, unsupported: true }
57
+ const timeoutMs = Number.isFinite(deps?.timeoutMs) ? Number(deps.timeoutMs) : DURABILITY_TIMEOUT_MS
58
+ if (timeoutMs <= 0) return { ok: false, skipped: true }
59
+ // 见上方「顺序契约」:让同一事件的其余同步监听器先把事件交进持久化缓冲。
60
+ await Promise.resolve()
61
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
62
+ let timer
63
+ // 同步抛出的 flush 也要落到 outcome 里(async 包装把 throw 变成 rejection)。
64
+ const flushed = (async () => flush.call(sessions, session))().then(
65
+ () => ({ kind: /** @type {const} */ ('flushed') }),
66
+ (error) => ({ kind: /** @type {const} */ ('failed'), error }),
67
+ )
68
+ const deadline = new Promise((resolve) => {
69
+ timer = setTimeout(() => resolve({ kind: 'timeout' }), timeoutMs)
70
+ })
71
+ try {
72
+ /** @type {{kind: 'flushed'|'failed'|'timeout', error?: unknown}} */
73
+ const outcome = await Promise.race([flushed, deadline])
74
+ if (outcome.kind === 'flushed') return { ok: true }
75
+ if (outcome.kind === 'timeout') return { ok: false, timedOut: true }
76
+ return { ok: false, error: messageOf(outcome.error) }
77
+ } finally {
78
+ clearTimeout(timer)
79
+ }
80
+ }
package/lib/encrypted.mjs CHANGED
File without changes
package/lib/engine.mjs CHANGED
File without changes
package/lib/errors.mjs CHANGED
File without changes
package/lib/gate.mjs CHANGED
File without changes
package/lib/git.mjs CHANGED
File without changes
package/lib/merge.mjs CHANGED
File without changes
package/lib/mirror.mjs CHANGED
File without changes
package/lib/paths.mjs CHANGED
File without changes
File without changes
package/lib/render.mjs CHANGED
File without changes
package/lib/sanitize.mjs CHANGED
File without changes
File without changes
package/lib/status.mjs CHANGED
File without changes
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-session-sync",
3
3
  "description": "Cross-device sync for DeepSeek Harness sessions: a dedicated git mirror of the session store, append-only three-way merge with keep-both + fork conflict resolution, /sync command, sync_pull/sync_push/sync_status tools, and configurable auto push/pull",
4
- "version": "0.3.0",
4
+ "version": "0.3.2",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/PerryLink/dsh-session-sync.git"
@@ -28,10 +28,10 @@
28
28
  "lib",
29
29
  "cordis.patch.yml",
30
30
  "README.md",
31
- "README-zh.md",
32
- "README-es.md",
33
- "README-pt.md",
34
- "README-hi.md",
31
+ "README.en.md",
32
+ "README.es.md",
33
+ "README.pt.md",
34
+ "README.hi.md",
35
35
  "ARCHITECTURE.md",
36
36
  "CHANGELOG.md",
37
37
  "SECURITY.md",
@@ -47,9 +47,26 @@
47
47
  },
48
48
  "capabilities": [
49
49
  "network:egress",
50
- "subprocess"
50
+ "subprocess",
51
+ "sessions:read",
52
+ "sessions:write"
51
53
  ],
52
- "labels": []
54
+ "labels": [],
55
+ "standards": {
56
+ "schema": "dsh-levels/1",
57
+ "entry": {
58
+ "status": "not-run",
59
+ "evidence": null
60
+ },
61
+ "flow": {
62
+ "status": "not-run",
63
+ "evidence": null
64
+ },
65
+ "boost": {
66
+ "status": "not-measured",
67
+ "evidence": null
68
+ }
69
+ }
53
70
  },
54
71
  "dshWorkshop": {
55
72
  "schema": "omdsh-workshop-package/v1",
@@ -118,32 +135,33 @@
118
135
  }
119
136
  },
120
137
  "dependencies": {
121
- "zod": "4.4.3"
138
+ "zod": "4.6.6"
122
139
  },
123
140
  "devDependencies": {
124
- "@deepseek-ai/dsh-attachment": "0.2.2-rc.1",
141
+ "@deepseek-ai/dsh-attachment": "0.2.2-rc.3",
125
142
  "@deepseek-ai/cordis": "^4.1.0",
126
143
  "@deepseek-ai/cordis-plugin-include": "^1.1.0",
127
144
  "@deepseek-ai/cordis-plugin-loader": "^1.1.0",
128
- "@deepseek-ai/dsh-commands": "0.2.2-rc.1",
129
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
130
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
131
- "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.2-rc.1",
132
- "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.1",
133
- "@deepseek-ai/dsh-storage": "0.2.2-rc.1",
134
- "@deepseek-ai/dsh-storage-domain": "0.2.2-rc.1",
135
- "@deepseek-ai/dsh-storage-json": "0.2.2-rc.1",
136
- "@deepseek-ai/dsh-subprocess": "0.2.2-rc.1",
137
- "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
138
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
139
- "@deepseek-ai/dsh-user-approval": "0.2.2-rc.1",
140
- "@deepseek-ai/dsh-user-questions": "0.2.2-rc.1",
145
+ "@deepseek-ai/dsh-commands": "0.2.2-rc.3",
146
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
147
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
148
+ "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.2-rc.3",
149
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.3",
150
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.3",
151
+ "@deepseek-ai/dsh-storage": "0.2.2-rc.3",
152
+ "@deepseek-ai/dsh-storage-domain": "0.2.2-rc.3",
153
+ "@deepseek-ai/dsh-storage-json": "0.2.2-rc.3",
154
+ "@deepseek-ai/dsh-subprocess": "0.2.2-rc.3",
155
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.3",
156
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
157
+ "@deepseek-ai/dsh-user-approval": "0.2.2-rc.3",
158
+ "@deepseek-ai/dsh-user-questions": "0.2.2-rc.3",
141
159
  "@deepseek-ai/schemastery": "~3.19.0",
142
160
  "@types/node": "^22.19.0",
143
161
  "oxlint": "0.18.1",
144
162
  "typescript": "^5.9.0",
145
- "@deepseek-ai/dsh-working-directory": "0.2.2-rc.1",
146
- "@deepseek-ai/dsh-package-manifest": "0.2.2-rc.1"
163
+ "@deepseek-ai/dsh-working-directory": "0.2.2-rc.3",
164
+ "@deepseek-ai/dsh-package-manifest": "0.2.2-rc.3"
147
165
  },
148
166
  "scripts": {
149
167
  "typecheck": "tsc -p tsconfig.check.json",
package/types.d.ts CHANGED
@@ -94,6 +94,12 @@ export interface Config {
94
94
  autoPullOnStart?: boolean
95
95
  /** 每个 turn/end 后自动推送(配置即授权,不再确认)。 */
96
96
  autoPushOnTurnEnd?: boolean
97
+ /**
98
+ * 自动推送前等待该会话落盘的上限(ms;默认 2000,0 = 不等待)。
99
+ * 宿主的 JSONL 持久化对 live 事件有 200ms 批量写窗;等待调用公开的
100
+ * `ctx.sessions.flush(session)` 落盘屏障,超时只记日志并照常推送。
101
+ */
102
+ durabilityTimeoutMs?: number
97
103
  /** 周期自动拉取间隔分钟(0 = 关闭;上限 10080)。 */
98
104
  pullIntervalMinutes?: number
99
105
  /** 确认通道:auto(userQuestions 优先,其次 approval)· userQuestions · approval。 */