dsh-session-sync 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ // lib/constants.mjs — 词汇表与协议常量(零依赖)。
2
+
3
+ // 插件标识、命令名与工具名。
4
+ export const PLUGIN_NAME = 'session-sync'
5
+ export const COMMAND_NAME = 'sync'
6
+ export const TOOL_PUSH = 'sync_push'
7
+ export const TOOL_PULL = 'sync_pull'
8
+ export const TOOL_STATUS = 'sync_status'
9
+
10
+ // ctx.storageDomain 领域名(同步元数据:设备 id、最近推/拉时间与错误)。
11
+ // 下划线命名:storage-domain 的域名正则不允许连字符。
12
+ export const DOMAIN_NAME = 'session_sync'
13
+
14
+ // git 工作树内镜像目录:sessionRoot 的相对镜像落在 <repoDir>/<MIRROR_DIR>/…。
15
+ export const MIRROR_DIR = 'sessions'
16
+
17
+ // 仓库根下的设备身份文件(随机 UUID,提交进仓库供跨设备归属 fork)。
18
+ export const DEVICE_FILE = 'device.txt'
19
+
20
+ // 存储领域 state 表的单例键。
21
+ export const STATE_KEY = 'singleton'
22
+
23
+ // 后端词汇:git 是唯一实现;其余为端到端加密后端预留(加载期响亮失败)。
24
+ export const BACKENDS = Object.freeze({
25
+ GIT: 'git',
26
+ })
27
+
28
+ // Config.confirmVia 的取值。
29
+ export const CONFIRM_CHANNELS = Object.freeze({
30
+ AUTO: 'auto',
31
+ USER_QUESTIONS: 'userQuestions',
32
+ APPROVAL: 'approval',
33
+ })
34
+
35
+ // 冲突分类(lib/merge.mjs 三分支合并的产物,命令/工具渲染与事件共用)。
36
+ export const MERGE_KINDS = Object.freeze({
37
+ IDENTICAL: 'identical',
38
+ OURS_ONLY: 'ours-only',
39
+ THEIRS_ONLY: 'theirs-only',
40
+ APPEND_BOTH: 'append-both',
41
+ DIVERGED: 'diverged',
42
+ })
43
+
44
+ // 会话事件类型(插件自有;运行时是否 append 取决于宿主是否收录该类型,
45
+ // 或宿主 append 是否支持 ignorable 信封,见 lib/gate.mjs 的自适应门)。
46
+ export const SESSION_EVENTS = Object.freeze({
47
+ PUSH: 'sync/push',
48
+ PULL: 'sync/pull',
49
+ CONFLICT: 'sync/conflict',
50
+ })
51
+
52
+ // 领域错误码(稳定、可路由)。
53
+ export const ERROR_CODES = Object.freeze({
54
+ BAD_CONFIG: 'BAD_CONFIG',
55
+ BACKEND_UNSUPPORTED: 'BACKEND_UNSUPPORTED',
56
+ REGISTRY_UNAVAILABLE: 'REGISTRY_UNAVAILABLE',
57
+ GIT_FAILED: 'GIT_FAILED',
58
+ PUSH_REJECTED: 'PUSH_REJECTED',
59
+ SYNC_DENIED: 'SYNC_DENIED',
60
+ PATH_UNSAFE: 'PATH_UNSAFE',
61
+ })
62
+
63
+ // fork 文件名模式:<basename>.remote-fork-<UTC 时间戳>-<设备短 id>;镜像与
64
+ // 清理永不删除、永不覆盖匹配该模式的文件(两边保留的持久载体)。
65
+ export const FORK_NAME_RE = /\.remote-fork-\d{14}-[0-9a-z]{8}(?:\.|$)/iu
66
+
67
+ // 默认值(Config schema 的默认与 DEFAULT_* 常量同源;cordis.yml 可整体覆盖)。
68
+ export const DEFAULTS = Object.freeze({
69
+ ENABLED: true,
70
+ BACKEND: BACKENDS.GIT,
71
+ SESSION_ROOT: '',
72
+ REPO_DIR: '',
73
+ REMOTE: '',
74
+ BRANCH: 'main',
75
+ GIT_BIN: 'git',
76
+ AUTO_PULL_ON_START: false,
77
+ AUTO_PUSH_ON_TURN_END: false,
78
+ PULL_INTERVAL_MINUTES: 0,
79
+ CONFIRM_VIA: CONFIRM_CHANNELS.AUTO,
80
+ GRACE_MS: 10000,
81
+ COMMAND_TIMEOUT_MS: 120000,
82
+ MAX_OUTPUT_BYTES: 262144,
83
+ COMMIT_NAME: 'dsh-session-sync',
84
+ COMMIT_EMAIL: 'dsh-session-sync@localhost',
85
+ REGISTER_COMMAND: true,
86
+ REGISTER_TOOLS: true,
87
+ })
88
+
89
+ // 配置字段合法性边界(加载期校验,越界响亮失败)。
90
+ export const LIMITS = Object.freeze({
91
+ MIN_GRACE_MS: 1000,
92
+ MAX_GRACE_MS: 2_147_483_647, // SubprocessSpawnSpec.graceMs 上限(Node 定时器上限)。
93
+ MIN_COMMAND_TIMEOUT_MS: 1000,
94
+ MAX_COMMAND_TIMEOUT_MS: 3_600_000,
95
+ MIN_MAX_OUTPUT_BYTES: 4096,
96
+ MAX_MAX_OUTPUT_BYTES: 16 * 1024 * 1024,
97
+ MIN_PULL_INTERVAL_MINUTES: 0,
98
+ MAX_PULL_INTERVAL_MINUTES: 10080,
99
+ MAX_COMMIT_MESSAGE_LENGTH: 200,
100
+ MAX_DEVICE_ID_LENGTH: 128,
101
+ })
102
+
103
+ // git 白名单动词(运行时断言;见 lib/git.mjs 的 ALLOWED_VERBS)。
104
+ // 归入 lib/git.mjs 会形成 lib 内循环依赖提示,故这里只放展示用的说明常量。
105
+ export const GIT_ENV = Object.freeze({
106
+ // 终端凭据提示会让 git 挂起等待输入;可选锁避免只读原语触发锁竞争。
107
+ GIT_TERMINAL_PROMPT: '0',
108
+ GIT_OPTIONAL_LOCKS: '0',
109
+ })
package/lib/domain.mjs ADDED
@@ -0,0 +1,29 @@
1
+ // lib/domain.mjs — 'session_sync' 存储领域声明(唯一允许 zod/DSH 包的 lib 模块:
2
+ // 领域记录 schema 是持久边界校验器,zod 与 defineDomain 是 harness 自身词汇)。
3
+
4
+ import { z } from 'zod'
5
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain'
6
+ import { DOMAIN_NAME, LIMITS } from './constants.mjs'
7
+
8
+ /**
9
+ * 同步元数据记录(state 表单例键):设备 id(fork 归属/提交署名)、最近
10
+ * 推/拉时间、最近推送头与最近错误。介质上每条记录在 open 时按此校验
11
+ * (invalid-record 响亮拒绝,绝不静默跳过)。
12
+ */
13
+ export const syncStateSchema = z.object({
14
+ deviceId: z.string().min(1).max(LIMITS.MAX_DEVICE_ID_LENGTH),
15
+ lastPullAt: z.number().int().nonnegative().optional(),
16
+ lastPushAt: z.number().int().nonnegative().optional(),
17
+ lastPushHead: z.string().regex(/^[0-9a-f]{40,64}$/iu).optional(),
18
+ lastError: z.string().max(500).optional(),
19
+ })
20
+
21
+ /**
22
+ * 'session_sync' 领域 spec:一张 'state' 表,键为单例键。
23
+ * version 变更即废弃整介质(预发布立场,无迁移)。
24
+ */
25
+ export const sessionSyncDomainSpec = defineDomain({
26
+ name: DOMAIN_NAME,
27
+ version: 1,
28
+ tables: { state: domainTable(syncStateSchema) },
29
+ })
package/lib/engine.mjs ADDED
@@ -0,0 +1,289 @@
1
+ // lib/engine.mjs — 同步编排(业务层;DSH 服务经回调注入,本模块零 DSH 依赖)。
2
+ //
3
+ // 操作语义:
4
+ // - push:镜像 → 提交 → push;被拒(远端领先)→ fetch + 拉取调和 → 重推一次;
5
+ // 绝不强推。
6
+ // - pull:先镜像 + 提交本地(保证合并基点是已提交状态)→ fetch → 三分支合并
7
+ // (lib/merge.mjs 的 append-only 语义)→ 合并提交。冲突双方字节永不丢弃:
8
+ // 本地保留原路径,远端留存为 fork 文件。
9
+ // - 全部操作经 git.schedule 串行(同一仓库互不穿插)。
10
+
11
+ import { promises as fs } from 'node:fs'
12
+ import path from 'node:path'
13
+ import { MERGE_KINDS, MIRROR_DIR, DEVICE_FILE } from './constants.mjs'
14
+ import { planMerge } from './merge.mjs'
15
+ import { mirrorSessionRoot, ensureDeviceFile } from './mirror.mjs'
16
+ import { collectStatus } from './status.mjs'
17
+ import { forkFileName } from './paths.mjs'
18
+ import { messageOf, SyncError } from './errors.mjs'
19
+ import { redactText, sanitizeRemote } from './sanitize.mjs'
20
+
21
+ /**
22
+ * 同步引擎。
23
+ * @typedef {object} EngineDeps
24
+ * @property {import('./git.mjs').GitBackend} git - git 后端。
25
+ * @property {string} sessionRoot - 会话存储根(绝对)。
26
+ * @property {string} repoDir - 同步仓库根(绝对)。
27
+ * @property {string} remote - 远端地址原文(展示时 sanitize)。
28
+ * @property {string} branch - 分支名。
29
+ * @property {string} deviceId - 设备 id(fork 归属)。
30
+ * @property {(patch: object) => void} reportMeta - 元数据补丁回调(index.mjs 写领域)。
31
+ * @property {(message: string) => void} reportError - 最近错误回调(写领域 lastError)。
32
+ * @property {(forkRelPaths: string[]) => void} onForks - fork 文件产生回调(index.mjs 做会话级 fork + 事件)。
33
+ * @property {{debug: Function, info: Function, warn: Function, error: Function}} logger - 日志。
34
+ */
35
+ export class SyncEngine {
36
+ /** @type {EngineDeps} */
37
+ #deps
38
+
39
+ /** @param {EngineDeps} deps - 依赖。 */
40
+ constructor(deps) {
41
+ this.#deps = deps
42
+ }
43
+
44
+ /** 设备 id(fork 文件名后缀;领域就绪后由 index.mjs 补齐)。 */
45
+ set deviceId(value) {
46
+ this.#deps.deviceId = value
47
+ }
48
+
49
+ /** 设备短 id(fork 文件名后缀,≤8 位小写十六进制)。 */
50
+ get deviceShort() {
51
+ return this.#deps.deviceId.replaceAll('-', '').slice(0, 8).toLowerCase() || 'unknown'
52
+ }
53
+
54
+ /** 串行执行一次同步操作(同仓库互斥)。 */
55
+ #schedule(fn) {
56
+ return this.#deps.git.schedule(fn)
57
+ }
58
+
59
+ /** 失败包装:脱敏 → reportError → 结构化错误结果。 */
60
+ #fail(error) {
61
+ const message = redactText(messageOf(error))
62
+ this.#deps.reportError(message)
63
+ this.#deps.logger.warn(`sync failed: ${message}`)
64
+ return { ok: false, error: message }
65
+ }
66
+
67
+ /** remote 未配置时响亮失败(状态类操作不拦)。 */
68
+ #requireRemote() {
69
+ if (this.#deps.remote === undefined || this.#deps.remote.trim() === '') {
70
+ throw new Error('no sync remote configured — set config.remote (status/diff work without one)')
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 镜像 + 提交(push/pull 共用前置)。
76
+ * @returns {Promise<{deviceWritten: boolean, mirror: {mirrored: number, unchanged: number, deleted: string[], forkedPreserved: string[], skippedLinks: string[]}}>}
77
+ */
78
+ // 镜像(不提交):把 sessionRoot 的字节镜像进工作树 + 确保设备文件。
79
+ // 只写本地工作树,不触网、不确认、不提交。调用方已持有 schedule 锁,
80
+ // 这里绝不能再走 #schedule。
81
+ async #mirrorOnly() {
82
+ const deviceWritten = await ensureDeviceFile(this.#deps.repoDir, DEVICE_FILE, this.#deps.deviceId)
83
+ const mirror = await mirrorSessionRoot({
84
+ sessionRoot: this.#deps.sessionRoot,
85
+ repoDir: this.#deps.repoDir,
86
+ mirrorDir: MIRROR_DIR,
87
+ })
88
+ return { deviceWritten, mirror }
89
+ }
90
+
91
+ // 前置镜像 + 提交。调用方(push/pull)已持有 schedule 锁,这里绝不能再走
92
+ // #schedule —— 嵌套 schedule 会在同一 git 链上自锁(fnM 等 fnP 完成、fnP 等 fnM)。
93
+ async #mirrorAndCommit(message) {
94
+ const { deviceWritten, mirror } = await this.#mirrorOnly()
95
+ if (deviceWritten || mirror.mirrored > 0 || mirror.deleted.length > 0) {
96
+ const committed = await this.#deps.git.commitAll(message)
97
+ return { ...mirror, committed }
98
+ }
99
+ return { ...mirror, committed: null }
100
+ }
101
+
102
+ /**
103
+ * 状态:先本地初始化 + 镜像(不提交),使未同步的会话变更以"未提交文件"
104
+ * 形式进入 dirty;只写本地工作树,不触网、不确认。
105
+ * @returns {Promise<{ok: boolean, branch?: string, remote?: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], error?: string}>}
106
+ */
107
+ status() {
108
+ return this.#schedule(async () => {
109
+ try {
110
+ await fs.mkdir(this.#deps.repoDir, { recursive: true })
111
+ await this.#deps.git.ensureRepo()
112
+ await this.#mirrorOnly()
113
+ } catch {
114
+ // 初始化/镜像失败不阻断状态:collectStatus 会返回带 error 的快照。
115
+ }
116
+ return collectStatus(this.#deps.git, { branch: this.#deps.branch, remote: this.#deps.remote ?? '' })
117
+ })
118
+ }
119
+
120
+ /**
121
+ * 推送:镜像 → 提交 → push;被拒时拉取调和后重推一次。
122
+ * @param {object} [opts] - {signal?: AbortSignal}。
123
+ * @returns {Promise<{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string}>}
124
+ */
125
+ push(opts = {}) {
126
+ return this.#schedule(async () => {
127
+ try {
128
+ this.#requireRemote()
129
+ // git 命令以 repoDir 为 cwd,首次操作前必须保证它存在(cwd 缺失时
130
+ // spawn 静默失败,甚至伪装成 exit 0)。
131
+ await fs.mkdir(this.#deps.repoDir, { recursive: true })
132
+ await this.#deps.git.bootstrap()
133
+ const mirror = await this.#mirrorAndCommit('dsh-session-sync: push snapshot')
134
+ try {
135
+ await this.#deps.git.push({ signal: opts.signal })
136
+ } catch (error) {
137
+ if (!(error instanceof SyncError && error.code === 'PUSH_REJECTED')) {
138
+ throw error
139
+ }
140
+ // 远端领先:先拉取调和(保留双方),再重推一次。
141
+ this.#deps.logger.info('push rejected (remote moved); pulling and reconciling before one retry')
142
+ const pulled = await this.#pullInternal(opts)
143
+ if (!pulled.ok) throw error
144
+ await this.#deps.git.push({ signal: opts.signal })
145
+ }
146
+ const head = await this.#deps.git.headSha()
147
+ this.#deps.reportMeta({ lastPushAt: Date.now(), lastPushHead: head })
148
+ this.#deps.logger.info(`sync push ok: head ${head ?? ''} (${mirror.mirrored} mirrored, ${mirror.deleted} deleted)`)
149
+ return {
150
+ ok: true,
151
+ pushed: true,
152
+ head,
153
+ mirrored: mirror.mirrored,
154
+ deleted: mirror.deleted.length,
155
+ remote: sanitizeRemote(this.#deps.remote),
156
+ }
157
+ } catch (error) {
158
+ return this.#fail(error)
159
+ }
160
+ })
161
+ }
162
+
163
+ /**
164
+ * 拉取:本地提交 → fetch → 三分支合并(append-only 语义)。
165
+ * @param {object} [opts] - {signal?: AbortSignal}。
166
+ * @returns {Promise<{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string}>}
167
+ */
168
+ pull(opts = {}) {
169
+ return this.#schedule(async () => {
170
+ try {
171
+ this.#requireRemote()
172
+ await fs.mkdir(this.#deps.repoDir, { recursive: true })
173
+ await this.#deps.git.bootstrap()
174
+ await this.#mirrorAndCommit('dsh-session-sync: local checkpoint before pull')
175
+ return await this.#pullInternal(opts)
176
+ } catch (error) {
177
+ return this.#fail(error)
178
+ }
179
+ })
180
+ }
181
+
182
+ /**
183
+ * 拉取内部步骤(push 重试路径复用;前置已保证仓库存在且本地已提交)。
184
+ * @param {object} [opts] - {signal?: AbortSignal}。
185
+ * @returns {Promise<object>}
186
+ */
187
+ async #pullInternal(opts = {}) {
188
+ const fetched = await this.#deps.git.fetch({ signal: opts.signal })
189
+ if (!fetched) {
190
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
191
+ return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
192
+ }
193
+ const [head, remoteHead] = [await this.#deps.git.headSha(), await this.#deps.git.remoteHeadSha()]
194
+ if (remoteHead === undefined) {
195
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
196
+ return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
197
+ }
198
+ if (head === remoteHead) {
199
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
200
+ return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
201
+ }
202
+ const behind = await this.#deps.git.countCommitsSafe(head, remoteHead)
203
+ if (behind === 0) {
204
+ // 本地领先(远端无新提交):无拉取内容。
205
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
206
+ return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
207
+ }
208
+ const merged = await this.#deps.git.beginMerge(remoteHead)
209
+ if (!merged.inProgress) {
210
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
211
+ return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
212
+ }
213
+ let result
214
+ if (merged.conflicted) {
215
+ result = await this.#resolveConflicts()
216
+ } else {
217
+ result = { adopted: 0, appended: 0, diverged: 0, forks: [] }
218
+ await this.#deps.git.addAll()
219
+ }
220
+ const newHead = await this.#deps.git.commitMerge()
221
+ this.#deps.reportMeta({ lastPullAt: Date.now() })
222
+ this.#deps.logger.info(`sync pull ok: merged remote head ${remoteHead} → ${newHead ?? ''} (${result.appended} appended-both, ${result.diverged} diverged, ${result.forks.length} forks)`)
223
+ if (result.forks.length > 0) this.#deps.onForks(result.forks)
224
+ return {
225
+ ok: true,
226
+ pulled: true,
227
+ merged: true,
228
+ adopted: result.adopted,
229
+ appended: result.appended,
230
+ diverged: result.diverged,
231
+ forks: result.forks,
232
+ head: newHead ?? undefined,
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 冲突解决:逐路径分类 → ours/theirs 检出 → 远端侧留存为 fork 文件 →
238
+ * 全量暂存(提交由调用方落合并提交)。失败时 abortMerge 恢复。
239
+ * @returns {Promise<{adopted: number, appended: number, diverged: number, forks: string[]}>}
240
+ */
241
+ async #resolveConflicts() {
242
+ try {
243
+ const conflicts = await this.#deps.git.conflictedPaths()
244
+ const entries = []
245
+ for (const conflict of conflicts) {
246
+ const [base, ours, theirs] = await Promise.all([
247
+ this.#deps.git.readStageBlob('1', conflict.path),
248
+ this.#deps.git.readStageBlob('2', conflict.path),
249
+ this.#deps.git.readStageBlob('3', conflict.path),
250
+ ])
251
+ entries.push({ path: conflict.path, base, ours, theirs })
252
+ }
253
+ const { resolutions, summary } = planMerge(entries)
254
+ const forks = []
255
+ const now = new Date()
256
+ const stamp = now.toISOString().replaceAll('-', '').replaceAll(':', '').slice(0, 14)
257
+ for (const resolution of resolutions) {
258
+ if (resolution.adoptTheirs) {
259
+ await this.#deps.git.checkoutStage('theirs', resolution.path)
260
+ continue
261
+ }
262
+ if (resolution.forkTheirs) {
263
+ // 先取 theirs 工作树字节 → 写 fork 文件 → 再检出 ours 回原路径。
264
+ await this.#deps.git.checkoutStage('theirs', resolution.path)
265
+ const absolute = path.join(this.#deps.repoDir, ...resolution.path.split('/'))
266
+ const content = await fs.readFile(absolute)
267
+ const forkName = forkFileName(path.posix.basename(resolution.path), stamp, this.deviceShort)
268
+ await fs.writeFile(path.join(path.dirname(absolute), forkName), content)
269
+ await this.#deps.git.checkoutStage('ours', resolution.path)
270
+ const forkRel = path.posix.join(path.posix.dirname(resolution.path), forkName)
271
+ forks.push(forkRel)
272
+ continue
273
+ }
274
+ await this.#deps.git.checkoutStage('ours', resolution.path)
275
+ }
276
+ await this.#deps.git.addAll()
277
+ return { adopted: summary.adopted, appended: summary.appended, diverged: summary.diverged, forks }
278
+ } catch (error) {
279
+ try {
280
+ await this.#deps.git.abortMerge()
281
+ } catch {
282
+ // 恢复失败以原始错误为主,恢复失败只记录。
283
+ }
284
+ throw error
285
+ }
286
+ }
287
+ }
288
+
289
+ export { MERGE_KINDS }
package/lib/errors.mjs ADDED
@@ -0,0 +1,99 @@
1
+ // lib/errors.mjs — 结构化领域错误(code + details,零依赖)。
2
+
3
+ import { ERROR_CODES } from './constants.mjs'
4
+
5
+ /**
6
+ * 插件领域错误基类:稳定 code 供 UI/日志路由,details 携带机器可读事实。
7
+ */
8
+ export class SyncError extends Error {
9
+ /**
10
+ * @param {string} code - ERROR_CODES 之一。
11
+ * @param {string} message - 面向用户的说明。
12
+ * @param {object} [details] - 可选结构化事实。
13
+ */
14
+ constructor(code, message, details = undefined) {
15
+ super(message)
16
+ this.name = 'SyncError'
17
+ this.code = code
18
+ this.details = details
19
+ }
20
+ }
21
+
22
+ /**
23
+ * 配置非法(加载期响亮失败用)。
24
+ * @param {string} message - 具体非法项说明。
25
+ * @returns {SyncError} code=BAD_CONFIG。
26
+ */
27
+ export function badConfig(message) {
28
+ return new SyncError(ERROR_CODES.BAD_CONFIG, `dsh-session-sync config: ${message}`)
29
+ }
30
+
31
+ /**
32
+ * 配置的 backend 尚未实现(端到端加密后端预留面)。
33
+ * @param {unknown} backend - 配置值。
34
+ * @returns {SyncError} code=BACKEND_UNSUPPORTED。
35
+ */
36
+ export function backendUnsupported(backend) {
37
+ return new SyncError(
38
+ ERROR_CODES.BACKEND_UNSUPPORTED,
39
+ `sync backend ${JSON.stringify(backend)} is not implemented (only "git" is; encrypted backends are reserved, keys never enter the repo)`,
40
+ { backend },
41
+ )
42
+ }
43
+
44
+ /**
45
+ * 同步元数据领域不可用(打开/读写失败)。
46
+ * @param {string} reason - 失败原因。
47
+ * @returns {SyncError} code=REGISTRY_UNAVAILABLE。
48
+ */
49
+ export function registryUnavailable(reason) {
50
+ return new SyncError(ERROR_CODES.REGISTRY_UNAVAILABLE, `session-sync metadata store unavailable: ${reason}`, { reason })
51
+ }
52
+
53
+ /**
54
+ * git 命令失败。
55
+ * @param {string} operation - 失败阶段(bootstrap|status|push|pull|merge…)。
56
+ * @param {string} message - 失败说明(含 exit code/stderr 摘要)。
57
+ * @param {object} [details] - 可选结构化事实。
58
+ * @returns {SyncError} code=GIT_FAILED。
59
+ */
60
+ export function gitFailed(operation, message, details = undefined) {
61
+ return new SyncError(ERROR_CODES.GIT_FAILED, `git ${operation} failed: ${message}`, details)
62
+ }
63
+
64
+ /**
65
+ * push 被远端拒绝(远端领先;调用方应拉取并重试,绝不强推)。
66
+ * @param {string} message - 拒绝说明。
67
+ * @returns {SyncError} code=PUSH_REJECTED。
68
+ */
69
+ export function pushRejected(message) {
70
+ return new SyncError(ERROR_CODES.PUSH_REJECTED, `git push rejected (never force-pushed): ${message}`)
71
+ }
72
+
73
+ /**
74
+ * 确认门拒绝/无回答者(失败关闭)。
75
+ * @param {string} reason - 拒绝或不可用原因。
76
+ * @returns {SyncError} code=SYNC_DENIED。
77
+ */
78
+ export function syncDenied(reason) {
79
+ return new SyncError(ERROR_CODES.SYNC_DENIED, `sync cancelled: ${reason}`, { reason })
80
+ }
81
+
82
+ /**
83
+ * 路径越界(拼接前校验失败:绝不把根外的路径写进工作树或报告)。
84
+ * @param {string} reason - 越界说明。
85
+ * @returns {SyncError} code=PATH_UNSAFE。
86
+ */
87
+ export function pathUnsafe(reason) {
88
+ return new SyncError(ERROR_CODES.PATH_UNSAFE, `unsafe sync path refused: ${reason}`, { reason })
89
+ }
90
+
91
+ /**
92
+ * 任意值 → 稳定消息文本(日志/结果用,不信任其字符串转换)。
93
+ * @param {unknown} error - 任意抛出的值。
94
+ * @returns {string} 消息文本。
95
+ */
96
+ export function messageOf(error) {
97
+ if (error instanceof Error) return error.message
98
+ return String(error)
99
+ }
package/lib/gate.mjs ADDED
@@ -0,0 +1,152 @@
1
+ // lib/gate.mjs — 确认门 + 会话事件自适应门(零依赖)。
2
+
3
+ import { CONFIRM_CHANNELS, PLUGIN_NAME } from './constants.mjs'
4
+
5
+ /**
6
+ * 回退确认结果。
7
+ * @typedef {object} ConfirmVerdict
8
+ * @property {boolean} allowed - 是否放行(false 一律失败关闭)。
9
+ * @property {string} channel - 'userQuestions'|'approval'|'none'。
10
+ * @property {string} [reason] - 拒绝/不可用原因。
11
+ */
12
+
13
+ /** 确认问题 id 与默认选项文案。 */
14
+ export const CONFIRM_QUESTION_ID = 'session-sync-confirm'
15
+
16
+ /**
17
+ * 会话当前是否有开放轮次(last turn/start 未被 turn/end 闭合)。
18
+ * @param {readonly {type: string}[]} [events] - 会话事件。
19
+ * @returns {boolean} 有开放轮次。
20
+ */
21
+ export function hasOpenTurn(events) {
22
+ let open = false
23
+ for (const event of events ?? []) {
24
+ if (event.type === 'turn/start') open = true
25
+ else if (event.type === 'turn/end') open = false
26
+ }
27
+ return open
28
+ }
29
+
30
+ /**
31
+ * 选择确认通道:Config.confirmVia 显式指定,'auto' 优先 userQuestions、
32
+ * 其次 approval;两者皆无 → 'none'(失败关闭)。
33
+ * @param {string} confirmVia - CONFIRM_CHANNELS 之一。
34
+ * @param {{get: (name: string) => unknown}} ctx - Cordis ctx(可选服务查找)。
35
+ * @returns {string} 通道名。
36
+ */
37
+ export function pickChannel(confirmVia, ctx) {
38
+ if (confirmVia === CONFIRM_CHANNELS.USER_QUESTIONS) return CONFIRM_CHANNELS.USER_QUESTIONS
39
+ if (confirmVia === CONFIRM_CHANNELS.APPROVAL) return CONFIRM_CHANNELS.APPROVAL
40
+ if (ctx.get('userQuestions') !== undefined) return CONFIRM_CHANNELS.USER_QUESTIONS
41
+ if (ctx.get('approval') !== undefined) return CONFIRM_CHANNELS.APPROVAL
42
+ return 'none'
43
+ }
44
+
45
+ /**
46
+ * 向用户确认一次拉/推。任何回答者缺失/抛错/取消 → allowed=false(失败关闭)。
47
+ * approval 通道要求会话有开放轮次:/sync 命令运行于轮次之间,无开放轮次时
48
+ * 直接失败关闭并给出可操作原因;sync_* 工具运行于轮次内,approval 可用。
49
+ * @param {object} deps - {ctx, confirmVia, action, summary}:action ∈ pull|push。
50
+ * @param {object} [agent] - 命令/工具所属 agent(userQuestions 路由 + approval 审计归属)。
51
+ * @param {AbortSignal} [signal] - 取消信号(用户关闭 UI = cancelled)。
52
+ * @returns {Promise<ConfirmVerdict>} 裁决。
53
+ */
54
+ export async function confirmSync(deps, agent, signal) {
55
+ const channel = pickChannel(deps.confirmVia, deps.ctx)
56
+ const question = deps.action === 'push'
57
+ ? 'Push local session changes to the sync remote?'
58
+ : 'Pull remote session changes into the sync mirror?'
59
+ const approveLabel = deps.action === 'push' ? 'Push' : 'Pull'
60
+ if (channel === CONFIRM_CHANNELS.USER_QUESTIONS) {
61
+ const service = deps.ctx.get('userQuestions')
62
+ if (service === undefined || typeof service.ask !== 'function') {
63
+ return { allowed: false, channel, reason: 'no userQuestions answerer (fail closed)' }
64
+ }
65
+ try {
66
+ const answer = await service.ask({
67
+ questions: [{
68
+ id: CONFIRM_QUESTION_ID,
69
+ question,
70
+ detail: deps.summary,
71
+ options: [
72
+ { label: approveLabel, description: deps.summary },
73
+ { label: 'Cancel', description: 'Do nothing.' },
74
+ ],
75
+ }],
76
+ agent,
77
+ signal,
78
+ })
79
+ const item = answer?.answers?.find(entry => entry.id === CONFIRM_QUESTION_ID)
80
+ const selected = Array.isArray(item?.selected) ? item.selected : []
81
+ const custom = typeof item?.custom === 'string' && item.custom.length > 0 ? item.custom : undefined
82
+ if (custom !== undefined) {
83
+ return { allowed: false, channel, reason: 'free-text answer is not an approval' }
84
+ }
85
+ if (selected.includes(approveLabel)) return { allowed: true, channel }
86
+ return { allowed: false, channel, reason: `user chose not to ${deps.action}` }
87
+ } catch (error) {
88
+ return { allowed: false, channel, reason: `userQuestions ask failed: ${error instanceof Error ? error.message : String(error)}` }
89
+ }
90
+ }
91
+ if (channel === CONFIRM_CHANNELS.APPROVAL) {
92
+ // 宿主的 approval.request 无开放轮次即抛(审计对必须包在 turn 内);
93
+ // /sync 命令运行于轮次之间,这里前置检测并给出可操作文案。
94
+ if (!hasOpenTurn(agent?.session?.events)) {
95
+ return {
96
+ allowed: false,
97
+ channel,
98
+ reason: 'approval requires an open turn; /sync commands run between turns — mount userQuestions or set confirmVia: userQuestions',
99
+ }
100
+ }
101
+ const service = deps.ctx.get('approval')
102
+ if (service === undefined || typeof service.request !== 'function') {
103
+ return { allowed: false, channel, reason: 'no approval answerer (fail closed)' }
104
+ }
105
+ try {
106
+ const outcome = await service.request({ agent, toolName: deps.action === 'push' ? 'sync_push' : 'sync_pull', reason: deps.summary, signal })
107
+ if (outcome === 'allowed-once') return { allowed: true, channel }
108
+ return { allowed: false, channel, reason: `approval outcome ${JSON.stringify(outcome)}` }
109
+ } catch (error) {
110
+ return { allowed: false, channel, reason: `approval ask failed: ${error instanceof Error ? error.message : String(error)}` }
111
+ }
112
+ }
113
+ return { allowed: false, channel: 'none', reason: 'no confirmation answerer available (fail closed)' }
114
+ }
115
+
116
+ /**
117
+ * 会话事件自适应门:决策函数返回是否 append 以及是否带 ignorable 信封。
118
+ * 宿主 KNOWN_SESSION_EVENT_TYPES 收录的类型直接 append;未收录但宿主 append
119
+ * 支持 ignorable 信封(运行时探测)时以 { ignorable: true } append;其余
120
+ * 拒绝(rc.6:未收录类型落盘会让会话下次加载被持久化层拒绝)。
121
+ * @param {ReadonlySet<string>} knownTypes - KNOWN_SESSION_EVENT_TYPES。
122
+ * @param {boolean} [ignorableAppend] - 宿主 append 是否盖章 ignorable 信封。
123
+ * @returns {(type: string) => {append: boolean, ignorable: boolean}} 决策函数。
124
+ */
125
+ export function makeEventGate(knownTypes, ignorableAppend = false) {
126
+ return (type) => {
127
+ if (knownTypes.has(type)) return { append: true, ignorable: false }
128
+ if (ignorableAppend) return { append: true, ignorable: true }
129
+ return { append: false, ignorable: false }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * 自适应 append:门通过才写会话事件;append 本身失败只警告绝不破坏会话。
135
+ * @param {object|null|undefined} session - Session(缺失即跳过)。
136
+ * @param {string} type - 事件类型。
137
+ * @param {object} data - 载荷。
138
+ * @param {(type: string) => {append: boolean, ignorable: boolean}} gate - makeEventGate 产物。
139
+ * @param {(message: string) => void} warn - 日志警告。
140
+ * @returns {unknown} 已 append 事件或 undefined。
141
+ */
142
+ export function maybeAppendSessionEvent(session, type, data, gate, warn) {
143
+ if (session === null || session === undefined) return undefined
144
+ const decision = gate(type)
145
+ if (!decision.append) return undefined
146
+ try {
147
+ return session.append(type, data, decision.ignorable ? { ignorable: true } : undefined)
148
+ } catch (error) {
149
+ warn(`${PLUGIN_NAME} session event ${type} append failed: ${error instanceof Error ? error.message : String(error)}`)
150
+ return undefined
151
+ }
152
+ }