@kabxx/dsh-message-revision 0.0.0-stage → 0.1.1

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/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @kabxx/dsh-message-revision
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 编辑 DeepSeek Harness 历史用户消息,自动回退该消息之后的对话轮次并重新发送。
4
+
5
+ - 在空闲主会话的用户消息气泡旁悬停显示编辑按钮,点击即可原位展开编辑器
6
+ - 直接复用 DSH 原生输入框组件,支持附件增删、模型选择、思考强度和权限模式,并在提交失败时于当前页面保留草稿
7
+ - 在受限子进程中流式扫描并准备候选日志,按编辑时间点一并截断或移除关联的子智能体会话,并自动同步多标签页子智能体会话视图
8
+ - 基于跨平台原生内核排他锁(Linux / macOS `flock`、Windows 命名内核信号量)与预写式事务日志原子替换会话记录,异常中断自动回滚并支持重发投递恢复
9
+
10
+ ## 安装
11
+
12
+ 支持 Linux / WSL、macOS 与 Windows 上的 DSH 宿主(Node.js >= 24.9.0):
13
+
14
+ ```bash
15
+ dsh plugin --profile web add @kabxx/dsh-message-revision
16
+ ```
17
+
18
+ 也可以在 DSH 插件管理器中填写 `@kabxx/dsh-message-revision` 安装并启用。
19
+
20
+ ## 开发
21
+
22
+ ```bash
23
+ npm run check
24
+ npm test
25
+ npm pack --dry-run
26
+ ```
27
+
28
+ ## 项目结构
29
+
30
+ | 路径 | 说明 |
31
+ | --- | --- |
32
+ | [package.json](package.json) | 包清单与 DSH 插件导出配置 |
33
+ | [cordis.patch.yml](cordis.patch.yml) | 默认插件预设注入规则 |
34
+ | [src/index.js](src/index.js) | 服务端插件入口、RPC 路由、会话重开与投递恢复协调 |
35
+ | [src/client.js](src/client.js) | 前端消息悬停编辑按钮、原位编辑器与视图同步 |
36
+ | [src/bounded-revision.js](src/bounded-revision.js) | 有界流式编辑规划与子智能体家族树核验 |
37
+ | [src/bounded-commit.js](src/bounded-commit.js) | 多会话排他锁获取、原子替换提交与失败回滚 |
38
+ | [src/revision-candidates.js](src/revision-candidates.js) | 候选会话文件暂存目录生命周期管理 |
39
+ | [src/revision-notifications.js](src/revision-notifications.js) | 改写提交后的跨标签页子智能体会话变更通知流 |
40
+ | [src/rollback-events.js](src/rollback-events.js) | 崩溃恢复期间可安全回退的临时恢复标记判定 |
41
+ | [src/platform.js](src/platform.js) | Linux / macOS / Windows 宿主原生锁、Job Object、原子替换与进程标识适配 |
42
+ | [src/native-lease.js](src/native-lease.js) | 跨平台内核会话排他写锁封装(与 DSH `SessionWriteLease` 互通) |
43
+ | [src/rollout-process.js](src/rollout-process.js) | 受内存与超时约束的日志准备子进程调度(Linux `systemd-run`/`prlimit`、Windows Job Object、macOS RSS 监控) |
44
+ | [src/rollout-worker.js](src/rollout-worker.js) | 流式日志扫描、截断边界计算与候选日志写出 |
45
+ | [src/rollout-stream.js](src/rollout-stream.js) | V4 JSONL / Zstandard 流式逐行读写与完整性校验 |
46
+ | [src/revision.js](src/revision.js) | 消息内容改写、子智能体目录切分与单文件校验辅助 |
47
+ | [src/rewrite-journal.js](src/rewrite-journal.js) | 预写式改写事务日志与启动崩溃恢复 |
48
+ | [locale/](locale/) | 插件管理页中英文多语言资源 |
49
+ | [test/](test/) | 前后端、流式子进程与崩溃恢复测试 |
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: message-revision
3
+ name: '@kabxx/dsh-message-revision'
package/icon.svg ADDED
@@ -0,0 +1,23 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
2
+ <!--
3
+ Lucide square-pen: https://lucide.dev/icons/square-pen
4
+ ISC License
5
+ Copyright (c) 2026 Lucide Icons and Contributors
6
+
7
+ Permission to use, copy, modify, and/or distribute this software for any
8
+ purpose with or without fee is hereby granted, provided that the above
9
+ copyright notice and this permission notice appear in all copies.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
+ -->
19
+ <g transform="translate(6 6)" fill="none" stroke="#808080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
20
+ <path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
21
+ <path d="M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z"/>
22
+ </g>
23
+ </svg>
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh-message-revision",
4
+ "description": "Edit and resend sent messages in place, rewinding subsequent turns and associated subagent sessions."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh-message-revision",
4
+ "description": "原位编辑并重新发送历史消息,同步回退后续对话及关联的子智能体会话。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@kabxx/dsh-message-revision",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Edit and resend sent messages in place for DeepSeek Harness.",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/kabxx/dsh-message-revision.git"
12
+ },
13
+ "exports": {
14
+ ".": "./src/index.js",
15
+ "./client": "./src/client.js",
16
+ "./locale/*.json": "./locale/*.json",
17
+ "./icon": "./icon.svg"
18
+ },
19
+ "files": [
20
+ "src/",
21
+ "cordis.patch.yml",
22
+ "locale/",
23
+ "icon.svg"
24
+ ],
25
+ "scripts": {
26
+ "check": "node --input-type=module -e \"import { readdirSync } from 'node:fs'; import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; const files = []; for (const root of ['src', 'test']) for (const entry of readdirSync(root, { withFileTypes: true, recursive: true })) if (entry.isFile() && entry.name.endsWith('.js')) files.push(join(entry.parentPath, entry.name)); files.sort(); if (files.length === 0) process.exit(1); for (const file of files) { const r = spawnSync(process.execPath, ['--check', file], { stdio: 'inherit' }); if (r.error) throw r.error; if (r.status || r.signal) process.exit(r.status || 1); }\"",
27
+ "test": "node --test test/*.test.js"
28
+ },
29
+ "engines": {
30
+ "node": ">=24.9.0",
31
+ "dsh": "0.2.2-rc.5"
32
+ },
33
+ "dsh": {
34
+ "bundle": {
35
+ "patch": "./cordis.patch.yml"
36
+ },
37
+ "client": {
38
+ "platform": "web",
39
+ "inject": [
40
+ "@deepseek-ai/dsh-api-remote-access",
41
+ "@deepseek-ai/dsh-client-ui-chat",
42
+ "@deepseek-ai/dsh-client-ui-session",
43
+ "@deepseek-ai/dsh-client-ui-workspace"
44
+ ]
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,121 @@
1
+ import { join, relative } from 'node:path';
2
+ import { RevisionError } from './revision.js';
3
+ import { rolloutStorageRoot } from './platform.js';
4
+ import { artifactIdentity, revalidateWork } from './bounded-revision.js';
5
+ import { acquireNativeLease } from './native-lease.js';
6
+ import { runRolloutWorker } from './rollout-process.js';
7
+ import {
8
+ clearFailedCommitMarker, forgetRewriteJournal, markRewriteCommitted, prepareRewriteSetJournal,
9
+ publishRewriteSetArtifacts, resolveRewriteSetChildPath, restoreRewriteSetArtifacts, retireRewriteJournal, rewriteSetArtifactPath,
10
+ scheduleSettledRewriteRetirement, stageWithdrawnChildren,
11
+ } from './rewrite-journal.js';
12
+
13
+ class RewriteRollbackConflictError extends Error {
14
+ constructor(options) {
15
+ super('上次编辑后会话已有新增内容,未覆盖现有记录,请刷新后检查会话。', options);
16
+ this.name = 'RewriteRollbackConflictError';
17
+ }
18
+ }
19
+
20
+ async function withLeases(entries, operation) {
21
+ const leases = [];
22
+ try {
23
+ const paths = new Map(entries.map(({ path, dshPath }) => [path, dshPath]));
24
+ for (const [path, dshPath] of paths) leases.push(await acquireNativeLease(path, dshPath));
25
+ return await operation(async () => {
26
+ for (const lease of leases) await lease.assertHeld();
27
+ });
28
+ } finally {
29
+ const result = await Promise.allSettled(leases.toReversed().map(lease => lease.close()));
30
+ const failure = result.find(entry => entry.status === 'rejected');
31
+ if (failure) throw failure.reason;
32
+ }
33
+ }
34
+
35
+ function pathsForRestore(journal) {
36
+ return journal.intent.artifacts.map((_, index) => rewriteSetArtifactPath(journal, index));
37
+ }
38
+
39
+ export async function restoreBoundedJournal(journal, { beforeCommit, canRollback, afterRestore } = {}) {
40
+ const withdrawn = await Promise.all(journal.intent.children.map((_, index) => resolveRewriteSetChildPath(journal, index)));
41
+ const root = rolloutStorageRoot(journal.parentPath);
42
+ const dshRoot = rolloutStorageRoot(journal.dshPath ?? journal.parentPath);
43
+ const entries = [...pathsForRestore(journal), ...withdrawn].map(path => ({ path, dshPath: join(dshRoot, relative(root, path)) }));
44
+ await withLeases(entries, async assertHeld => {
45
+ const verifyClosed = () => canRollback?.() ?? true;
46
+ if (!verifyClosed()) throw new RevisionError('会话仍在使用,无法恢复上次编辑。');
47
+ await beforeCommit?.(journal.intent.artifacts.map(entry => entry.id));
48
+ await assertHeld();
49
+ await restoreRewriteSetArtifacts(journal, {
50
+ async canRestoreArtifact(artifact, match, index, path) {
51
+ if (!verifyClosed()) return false;
52
+ if (match !== 'candidate') return true;
53
+ const current = await artifactIdentity(path);
54
+ if (current.size === BigInt(artifact.candidate.size)) return true;
55
+ const inspection = await runRolloutWorker('inspect', {
56
+ path, sessionId: artifact.id, fromSeq: artifact.candidate.records,
57
+ permitResumeMarker: artifact.id === journal.intent.parentId,
58
+ });
59
+ if (!inspection.provisional) throw new RewriteRollbackConflictError();
60
+ return verifyClosed();
61
+ },
62
+ });
63
+ await afterRestore?.();
64
+ });
65
+ }
66
+
67
+ export async function commitBoundedRevision(persistence, work, {
68
+ beforeCommit, verifyReload, canRollback, closeFailedReload, afterCommit, onCleanupError, messageId,
69
+ }) {
70
+ let journal;
71
+ let committed = false;
72
+ let delivered = messageId === undefined;
73
+ let markerFailed = false;
74
+ const removedChildren = work.withdrawn.map(entry => entry.header.id);
75
+ try {
76
+ await withLeases(work.entries, async assertHeld => {
77
+ await revalidateWork(persistence, work);
78
+ journal = await prepareRewriteSetJournal(work.parent, work.withdrawn, work.artifacts, { messageId });
79
+ await assertHeld();
80
+ await revalidateWork(persistence, work);
81
+ await beforeCommit?.([...work.artifacts.map(entry => entry.header.id), ...removedChildren]);
82
+ await assertHeld();
83
+ await stageWithdrawnChildren(journal);
84
+ await publishRewriteSetArtifacts(journal);
85
+ });
86
+ await verifyReload();
87
+ try {
88
+ await markRewriteCommitted(journal);
89
+ } catch (error) {
90
+ markerFailed = true;
91
+ throw error;
92
+ }
93
+ committed = true;
94
+ const result = { removedChildren };
95
+ const accepted = await afterCommit(result, journal);
96
+ delivered ||= accepted === true;
97
+ return result;
98
+ } catch (error) {
99
+ if (committed || !journal) throw error;
100
+ try {
101
+ if (markerFailed) {
102
+ await closeFailedReload?.();
103
+ // Only clear a partially persisted marker if no runtime still owns the
104
+ // provisional state or has actually consumed the revised prompt.
105
+ if (canRollback && !canRollback()) throw new Error('Cannot restore a running candidate');
106
+ await clearFailedCommitMarker(journal);
107
+ }
108
+ await restoreBoundedJournal(journal, { beforeCommit, canRollback });
109
+ await retireRewriteJournal(journal, { deferCleanup: true, onCleanupError });
110
+ } catch (rollbackError) {
111
+ const cause = new AggregateError([error, rollbackError]);
112
+ if (rollbackError instanceof RewriteRollbackConflictError) throw new RewriteRollbackConflictError({ cause });
113
+ throw new Error('编辑回滚失败,请刷新后检查会话。', { cause });
114
+ }
115
+ throw new RevisionError('无法完成编辑,已恢复原记录。', { cause: error });
116
+ } finally {
117
+ if (committed && delivered) scheduleSettledRewriteRetirement(journal, { onCleanupError });
118
+ // A committed journal with an unsettled prompt remains available for recovery.
119
+ forgetRewriteJournal(journal);
120
+ }
121
+ }
@@ -0,0 +1,250 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { basename, isAbsolute, join } from 'node:path';
3
+ import { RevisionError, splitChildCatalog } from './revision.js';
4
+ import { createRevisionCandidateDirectory } from './revision-candidates.js';
5
+ import { runRolloutWorker } from './rollout-process.js';
6
+ import { fileIdentity, legacyLogName, nativeLogName } from './rollout-stream.js';
7
+ import { MAX_NATIVE_LEASES } from './native-lease.js';
8
+ import { isCanonicalPath, isSamePath, isSupportedPlatform, resolveRolloutPath, rolloutStorageRoot } from './platform.js';
9
+
10
+ const maxSessions = MAX_NATIVE_LEASES;
11
+ let preparing = false;
12
+
13
+ function check(condition, message) {
14
+ if (!condition) throw new RevisionError(message);
15
+ }
16
+
17
+ const stale = '会话状态已变更,请重新提交。';
18
+
19
+ function assertSession(snapshot, retainedChild) {
20
+ const path = snapshot?.location?.path;
21
+ check(typeof snapshot?.header?.id === 'string' && typeof snapshot.revision === 'string'
22
+ && snapshot.location?.kind === 'jsonl' && typeof path === 'string' && isAbsolute(path),
23
+ '当前会话存储格式不支持编辑。');
24
+ const name = basename(path);
25
+ const legacy = legacyLogName.test(name);
26
+ check(nativeLogName.test(name) || (retainedChild === true && legacy), legacy && retainedChild === false
27
+ ? '请在 DSH 中迁移需要撤回的旧版子会话,再试一次。' : '当前会话存储格式不支持编辑。');
28
+ return { path, legacy };
29
+ }
30
+
31
+ export function sameIdentity(a, b) {
32
+ return ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every(key => a[key] === b[key]);
33
+ }
34
+
35
+ export async function artifactIdentity(path) {
36
+ const st = await lstat(path, { bigint: true });
37
+ check(st.isFile() && await isCanonicalPath(path), '会话日志路径异常。');
38
+ return st;
39
+ }
40
+
41
+ async function entryFor(snapshot, retainedChild) {
42
+ const { path: dshPath, legacy } = assertSession(snapshot, retainedChild);
43
+ const path = await resolveRolloutPath(dshPath);
44
+ check(path !== undefined, '会话日志路径异常。');
45
+ return { path, dshPath, legacy, header: snapshot.header, revision: snapshot.revision, identity: await artifactIdentity(path) };
46
+ }
47
+
48
+ const lineageFields = ['id', 'parentSession', 'origin', 'createdAt', 'cwd', 'isSeeded', 'delegationDepth', 'agentPreset'];
49
+
50
+ function matchingHeader(first, second) {
51
+ return first.version === second.version && lineageFields.every(key => first[key] === second[key]);
52
+ }
53
+
54
+ export async function revalidateWork(persistence, work, { signal } = {}) {
55
+ const retainedLegacy = work.entries.filter(entry => entry.legacy);
56
+ if (retainedLegacy.length > 0) {
57
+ // A v3 revision includes the entire storage corpus because DSH may add
58
+ // missing catalog entries during migration. These files stay at v3. Check
59
+ // the selected physical source and the relevant parent edges instead.
60
+ const expected = new Map(work.entries.map(entry => [entry.header.id, entry]));
61
+ const legacyIds = new Set(retainedLegacy.map(entry => entry.header.id));
62
+ const observedLegacy = new Set();
63
+ for (const snapshot of await persistence.list({ signal })) {
64
+ const { header } = snapshot;
65
+ const entry = expected.get(header.id);
66
+ if (header.origin === 'subagent' && legacyIds.has(header.parentSession)) {
67
+ check(entry?.header.parentSession === header.parentSession, stale);
68
+ }
69
+ if (!entry?.legacy) continue;
70
+ check(!observedLegacy.has(header.id) && matchingHeader(header, entry.header)
71
+ && snapshot.location?.kind === 'jsonl' && isSamePath(snapshot.location.path, entry.dshPath), stale);
72
+ observedLegacy.add(header.id);
73
+ }
74
+ check(observedLegacy.size === retainedLegacy.length, stale);
75
+ }
76
+ for (const entry of work.entries) {
77
+ signal?.throwIfAborted();
78
+ if (!entry.legacy) {
79
+ const snapshot = await persistence.stat(entry.header.id, { signal });
80
+ check(snapshot?.location?.kind === 'jsonl' && isSamePath(snapshot.location.path, entry.dshPath)
81
+ && snapshot.revision === entry.revision, stale);
82
+ }
83
+ if (!isSamePath(entry.dshPath, entry.path)) {
84
+ check(isSamePath(await resolveRolloutPath(entry.dshPath), entry.path), stale);
85
+ }
86
+ check(sameIdentity(entry.identity, await artifactIdentity(entry.path)), stale);
87
+ }
88
+ }
89
+
90
+ function parseBirth(entry, parent, event) {
91
+ const { header } = entry;
92
+ check(header.origin === 'subagent' && header.parentSession === parent.header.id
93
+ && Number.isSafeInteger(header.createdAt) && header.createdAt >= parent.header.createdAt,
94
+ '子智能体会话的实际归属或创建时间与登记不匹配。');
95
+ if (event) check(event.data.childCreatedAt === header.createdAt, '子智能体会话的创建时间与登记不匹配。');
96
+ }
97
+
98
+ function restoredCatalog(events, cut, time) {
99
+ return events.filter(event => event.seq >= cut).map(event => ({ ...event, time }));
100
+ }
101
+
102
+ /** Prepare closed candidate files without acquiring a native writer or touching history. */
103
+ export async function prepareBoundedRevision(persistence, snapshot, messageId, amend, { signal, inheritedCount, eventCount } = {}) {
104
+ check(isSupportedPlatform(process.platform), '历史消息编辑需要 DSH 宿主运行在 Linux、macOS 或 Windows 上。');
105
+ const deadline = AbortSignal.timeout(180_000);
106
+ signal = signal ? AbortSignal.any([signal, deadline]) : deadline;
107
+ check(!preparing, '已有会话正在准备编辑,请稍后重试。');
108
+ preparing = true;
109
+ let staging;
110
+ let ready = false;
111
+ try {
112
+ const parent = await entryFor(snapshot);
113
+ const root = rolloutStorageRoot(parent.path);
114
+ const dshRoot = rolloutStorageRoot(parent.dshPath);
115
+ const worker = (op, input) => runRolloutWorker(op, input, { signal });
116
+ const native = entry => ({ path: entry.path, sessionId: entry.header.id });
117
+ const main = await worker('plan', { ...native(parent), messageId, inheritedCount });
118
+ check(main.header.id === parent.header.id && main.header.origin !== 'subagent'
119
+ && sameIdentity(fileIdentity(parent.identity), main.identity)
120
+ && (eventCount === undefined || main.stats.records === eventCount), '会话日志与当前版本不匹配,请重新提交。');
121
+ const { plan } = main;
122
+ const amendment = await amend(plan);
123
+ if (!amendment) return undefined;
124
+ const keep = [];
125
+ const withdrawn = [];
126
+ const changed = [];
127
+ const entries = [parent];
128
+ const seen = new Set([parent.header.id]);
129
+ // A child may have reached disk before its first catalog event. List
130
+ // native headers even when the parent log has no child registrations.
131
+ // The rc.5 persistence service offers no parent-filtered inventory. The
132
+ // related-session limit is enforced while walking descendants below.
133
+ const all = await persistence.list({ signal });
134
+ const childrenByParent = new Map();
135
+ for (const candidate of all) {
136
+ const { origin, parentSession } = candidate.header;
137
+ if (origin !== 'subagent' || !parentSession) continue;
138
+ const children = childrenByParent.get(parentSession) ?? [];
139
+ children.push(candidate);
140
+ childrenByParent.set(parentSession, children);
141
+ }
142
+ check(!plan.timestampAmbiguous || (main.catalog.length === 0 && !childrenByParent.has(parent.header.id)),
143
+ '主会话日志的时间顺序与编辑点冲突,无法安全回退子智能体会话。');
144
+ const split = splitChildCatalog(main.catalog, plan);
145
+
146
+ async function schedule(ancestor, catalog, retained, cutoff) {
147
+ const physical = childrenByParent.get(ancestor.header.id) ?? [];
148
+ const registered = new Map(catalog.map(event => [event.data.childId, event]));
149
+ const physicalIds = new Set(physical.map(item => item.header.id));
150
+ for (const event of registered.values()) {
151
+ check(event.data.mode !== 'external', '存在外部子任务,无法安全回退关联记录。');
152
+ check(physicalIds.has(event.data.childId), '子智能体会话记录不可用,无法核对其历史与后代。');
153
+ }
154
+ const keptIds = new Set(retained.map(event => event.data.childId));
155
+ for (const child of physical) {
156
+ const id = child.header.id;
157
+ const registeredEvent = registered.get(id);
158
+ // An unregistered file may belong to an earlier rejected/removed branch.
159
+ // Refuse to implicitly remove or rewind it in a branch that is kept.
160
+ if (cutoff !== undefined && !registeredEvent) {
161
+ // Persisted parent links for unsubscribed descendants are still real.
162
+ // Without an event we cannot distinguish prior branch state from a
163
+ // current registration that was lost or is in flight.
164
+ if (ancestor.legacy) {
165
+ throw new RevisionError(`旧版子会话 ${ancestor.header.id} 缺少直属子会话的原生登记,请先在 DSH 中迁移这个直接父会话。`);
166
+ }
167
+ throw new RevisionError('发现没有原生登记的子智能体会话,无法安全确定其回退边界。');
168
+ }
169
+ check(entries.length < maxSessions && !seen.has(id), '本次编辑涉及的会话过多(上限 128 个)或归属不明确。');
170
+ const retainedChild = cutoff !== undefined && keptIds.has(id);
171
+ const entry = await entryFor(child, retainedChild);
172
+ check(isSamePath(rolloutStorageRoot(entry.dshPath), dshRoot) && isSamePath(rolloutStorageRoot(entry.path), root),
173
+ '子智能体会话与主会话不在同一个原生存储目录。');
174
+ parseBirth(entry, ancestor, registeredEvent);
175
+ seen.add(id);
176
+ entries.push(entry);
177
+ if (cutoff !== undefined && keptIds.has(id)) keep.push(entry);
178
+ else withdrawn.push(entry);
179
+ }
180
+ }
181
+
182
+ await schedule(parent, main.catalog, split.retained, plan.time);
183
+ let keptCount = 0;
184
+ let removedCount = 0;
185
+ while (keptCount < keep.length || removedCount < withdrawn.length) {
186
+ while (removedCount < withdrawn.length) await schedule(withdrawn[removedCount++], [], [], undefined);
187
+ if (keptCount >= keep.length) continue;
188
+ signal?.throwIfAborted();
189
+ const batch = keep.slice(keptCount);
190
+ keptCount += batch.length;
191
+ const scans = await worker('scanMany', { items: batch.map(entry => ({ ...native(entry),
192
+ cutoff: plan.time, allowLegacy: entry.legacy,
193
+ })) });
194
+ for (const [index, scan] of scans.entries()) {
195
+ const child = batch[index];
196
+ check(scan.header.id === child.header.id && sameIdentity(fileIdentity(child.identity), scan.identity) && !scan.inTurn,
197
+ '子智能体会话的历史顺序或轮次状态无法安全核对。');
198
+ if (child.legacy) {
199
+ check(lineageFields.every(key => scan.header[key] === child.header[key]),
200
+ '旧版子会话的物理日志头与 DSH 记录不匹配。');
201
+ check(!scan.crosses && !scan.ambiguous, '旧版子会话跨过编辑点或边界不明确,请先在 DSH 中迁移该子会话。');
202
+ }
203
+ check(!scan.ambiguous, '无法确定子智能体会话事件与编辑点的先后顺序。');
204
+ const edges = splitChildCatalog(scan.catalog, { cut: scan.cut, time: plan.time });
205
+ if (scan.crosses) {
206
+ check(!scan.inTurnAtCut && scan.cut > scan.inheritedCount,
207
+ '子智能体会话有轮次横跨编辑点,找不到安全的截断位置。');
208
+ changed.push({ entry: child, scan, appendEvents: restoredCatalog(edges.retained, scan.cut, plan.time) });
209
+ }
210
+ await schedule(child, scan.catalog, edges.retained, plan.time);
211
+ }
212
+ }
213
+
214
+ await revalidateWork(persistence, { entries }, { signal });
215
+ staging = await createRevisionCandidateDirectory(parent.path);
216
+ const artifact = async (entry, parts, index) => ({ ...entry,
217
+ ...await worker('prepare', { ...native(entry), identity: fileIdentity(entry.identity),
218
+ output: join(staging.directory, String(index)), ...parts }),
219
+ });
220
+ const controls = amendment.controls ?? [];
221
+ const appendEvents = [...restoredCatalog(split.retained, plan.cut, plan.time), ...controls];
222
+ const files = [
223
+ { entry: parent, parts: { cut: plan.cut, inputCopies: plan.retainedInputs, message: amendment.message,
224
+ appendEvents, prefix: main.prefix } },
225
+ ...changed.map(({ entry, scan, appendEvents: records }) => ({
226
+ entry, parts: { cut: scan.cut, appendEvents: records, prefix: scan.prefix },
227
+ })),
228
+ ];
229
+ const artifacts = [];
230
+ for (const [index, { entry, parts }] of files.entries()) {
231
+ const prepared = await artifact(entry, parts, index);
232
+ artifacts.push({ ...prepared, candidatePath: prepared.path, path: entry.path });
233
+ }
234
+ const withdrawnIds = new Set(withdrawn.map(entry => entry.header.id));
235
+ const affectedParentIds = [...new Set(withdrawn.map(entry => entry.header.parentSession)
236
+ .filter(id => !withdrawnIds.has(id)))];
237
+ ready = true;
238
+ return { parent, entries, withdrawn, artifacts, affectedParentIds, dispose: staging.dispose };
239
+ } catch (error) {
240
+ if (staging) await staging.dispose().catch(() => {});
241
+ if (error.name === 'RolloutWorkerError') {
242
+ const message = error.reason !== undefined ? error.message : '处理会话日志时超过资源上限,或无法确认日志格式。';
243
+ throw new RevisionError(message, { cause: error });
244
+ }
245
+ throw error;
246
+ } finally {
247
+ preparing = false;
248
+ if (!ready && staging) await staging.dispose().catch(() => {});
249
+ }
250
+ }