dsh-shiori 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +304 -249
- package/client/index.js +1356 -552
- package/client/shiori.css +23 -0
- package/docs/plugin/client.md +127 -6
- package/package.json +1 -1
- package/src/core/render.mjs +84 -69
- package/src/core/topics.mjs +146 -136
- package/src/host/tools.mjs +582 -582
- package/src/organize/executor.mjs +766 -680
- package/src/organize/queue.mjs +1584 -1350
- package/src/plugin/management.mjs +165 -21
- package/src/plugin/protocol.mjs +90 -14
- package/src/plugin/state.mjs +677 -666
- package/src/semantic/local.mjs +2 -2
- package/src/service/index.mjs +304 -231
- package/src/sparks/graph.mjs +305 -278
- package/src/sparks/store.mjs +1954 -1930
- package/src/storage/errors.mjs +58 -46
- package/src/storage/frontmatter.mjs +186 -186
- package/src/storage/fsutil.mjs +181 -134
- package/src/storage/journal.mjs +133 -127
- package/src/storage/store.mjs +1085 -1079
package/src/organize/queue.mjs
CHANGED
|
@@ -1,1350 +1,1584 @@
|
|
|
1
|
-
// Shiori P3-QUEUE-DIFF · K 槽位:可恢复候选队列与审阅 diff 草案
|
|
2
|
-
//
|
|
3
|
-
// 职责边界:
|
|
4
|
-
// - createCandidateQueue:内存中的候选队列,可 JSON 快照恢复;本模块不持久化任何用户文件。
|
|
5
|
-
// 入队 / 审核只改变队列自身状态;reviewed 是「已审阅」不是「已批准 / 已执行」,
|
|
6
|
-
// 队列不产生任何业务写入,也不携带 approval / operationId 语义到 Plan。
|
|
7
|
-
// - buildDraft:把 (candidate, records, proposal) 变成确定性的 Plan + digest + 展示用 diff。
|
|
8
|
-
// Plan 是 L 执行器的输入草案,本身不含 digest/approval/operationId,禁止未知字段。
|
|
9
|
-
//
|
|
10
|
-
// 实现独立性:本文件按契约独立实现 stable/digest/schema 校验,只 import node:crypto,
|
|
11
|
-
// 不 import 任何冻结 src 文件、也不 import 其他槽位(J/L)尚未合入的模块。
|
|
12
|
-
// 少数标识符规则(scopeId / spark id / topic key / operationId)按既有冻结实现的
|
|
13
|
-
// 同一规则在本文件内镜像实现,仅作输入校验,不改变其语义。
|
|
14
|
-
//
|
|
15
|
-
// 错误码统一为 Error.code:INVALID_INPUT / REVISION_CONFLICT / NOT_FOUND /
|
|
16
|
-
// INVALID_STATE / UNSUPPORTED(本模块不产生 APPROVAL_REQUIRED;执行授权属于 L)。
|
|
17
|
-
|
|
18
|
-
import { createHash } from 'node:crypto';
|
|
19
|
-
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
// 基础工具:错误 / 比较 / 协议 JSON / stable / digest / 克隆
|
|
22
|
-
// ---------------------------------------------------------------------------
|
|
23
|
-
|
|
24
|
-
function fail(code, message, details) {
|
|
25
|
-
const err = new Error(message);
|
|
26
|
-
err.code = code;
|
|
27
|
-
if (details !== undefined) err.details = details;
|
|
28
|
-
throw err;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// UTF-16 二进制比较:与平台 locale 无关(契约 §1)
|
|
32
|
-
const byCodepoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
33
|
-
|
|
34
|
-
const OBJECT_PROTO = Object.prototype;
|
|
35
|
-
const RESERVED_JSON_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
36
|
-
|
|
37
|
-
function isPlainObject(value) {
|
|
38
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
39
|
-
const proto = Object.getPrototypeOf(value);
|
|
40
|
-
return proto === OBJECT_PROTO || proto === null;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* 协议 JSON 校验:undefined / function / symbol / bigint / NaN / Infinity /
|
|
45
|
-
* 循环引用 / 稀疏数组孔洞 / 类实例 / 孤立代理码元字符串一律拒绝(契约 §1)。
|
|
46
|
-
* 通过后才允许进入 stable()/digest()/deepClone()。
|
|
47
|
-
*/
|
|
48
|
-
function assertProtocolJson(value, where, ancestors = new Set()) {
|
|
49
|
-
if (value === null) return;
|
|
50
|
-
const type = typeof value;
|
|
51
|
-
if (type === 'string') {
|
|
52
|
-
if (!value.isWellFormed()) {
|
|
53
|
-
fail('INVALID_INPUT', `${where} 含孤立代理码元,不是无损 UTF-8 文本`);
|
|
54
|
-
}
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
if (type === 'number') {
|
|
58
|
-
if (!Number.isFinite(value)) {
|
|
59
|
-
fail('INVALID_INPUT', `${where} 含 NaN/Infinity,不属于协议 JSON`);
|
|
60
|
-
}
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
if (type === 'boolean') return;
|
|
64
|
-
if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint') {
|
|
65
|
-
fail('INVALID_INPUT', `${where} 含 ${type} 值,不属于协议 JSON`);
|
|
66
|
-
}
|
|
67
|
-
// typeof === 'object'
|
|
68
|
-
if (ancestors.has(value)) fail('INVALID_INPUT', `${where} 含循环引用`);
|
|
69
|
-
ancestors.add(value);
|
|
70
|
-
try {
|
|
71
|
-
if (Array.isArray(value)) {
|
|
72
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
73
|
-
if (!Object.hasOwn(value, i)) {
|
|
74
|
-
fail('INVALID_INPUT', `${where}[${i}] 是稀疏数组孔洞,不属于协议 JSON`);
|
|
75
|
-
}
|
|
76
|
-
assertProtocolJson(value[i], `${where}[${i}]`, ancestors);
|
|
77
|
-
}
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
if (!isPlainObject(value)) {
|
|
81
|
-
fail('INVALID_INPUT', `${where} 必须是普通对象或数组(拒绝类实例等非 JSON 值)`);
|
|
82
|
-
}
|
|
83
|
-
for (const key of Object.keys(value)) {
|
|
84
|
-
// 键与值同属协议文本(§9/§11):对象键同样必须是无损 UTF-8。
|
|
85
|
-
// JSON.stringify 会把孤立代理码元转义成 "\ud800" 文本,掩盖有损事实,
|
|
86
|
-
// 故对键显式校验(a1 反例 K-2);合法非 ASCII 键与配对代理键照常接受。
|
|
87
|
-
if (!key.isWellFormed()) {
|
|
88
|
-
fail('INVALID_INPUT', `${where} 的对象键 ${JSON.stringify(key)} 含孤立代理码元,不是无损 UTF-8 文本`);
|
|
89
|
-
}
|
|
90
|
-
assertProtocolJson(value[key], `${where}.${key === '' ? '""' : key}`, ancestors);
|
|
91
|
-
}
|
|
92
|
-
} finally {
|
|
93
|
-
ancestors.delete(value);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** stable(value):递归按 UTF-16 序排序普通对象键后的 JSON 文本;数组顺序保持(契约 §1)。 */
|
|
98
|
-
function stable(value) {
|
|
99
|
-
return JSON.stringify(value, function canonical(_key, v) {
|
|
100
|
-
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
|
|
101
|
-
return Object.fromEntries(Object.keys(v).sort(byCodepoint).map((k) => [k, v[k]]));
|
|
102
|
-
}
|
|
103
|
-
return v;
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** digest = SHA256(UTF8(stable(value))),小写 64 hex。 */
|
|
108
|
-
function digest(value) {
|
|
109
|
-
return createHash('sha256').update(Buffer.from(stable(value), 'utf8')).digest('hex');
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** 深克隆:仅对已通过协议 JSON 校验的值调用(JSON 序列化无损失,且不泄露内部引用)。 */
|
|
113
|
-
const deepClone = (value) => JSON.parse(JSON.stringify(value));
|
|
114
|
-
|
|
115
|
-
// operationId -> operation 记录的安全字典(a1 反例 K-1):
|
|
116
|
-
// `constructor`/`toString`/`hasOwnProperty` 等继承属性名是合法 operationId,
|
|
117
|
-
// 普通对象上直接索引会把它们误读为历史账项;null 原型字典 + own-property
|
|
118
|
-
// 查找让任何键都只是普通数据键(`__proto__` 形态也不触发原型 setter,
|
|
119
|
-
// 防止原型污染/账项丢失)。写入、克隆、快照与恢复全程保持该语义。
|
|
120
|
-
function newOperationRegistry() {
|
|
121
|
-
return Object.create(null);
|
|
122
|
-
}
|
|
123
|
-
function lookupOperation(operations, operationId) {
|
|
124
|
-
return Object.hasOwn(operations, operationId) ? operations[operationId] : undefined;
|
|
125
|
-
}
|
|
126
|
-
/** operations 克隆:逐条深克隆并保持安全字典(null 原型),不泄露内部引用。 */
|
|
127
|
-
function cloneOperations(operations) {
|
|
128
|
-
const out = newOperationRegistry();
|
|
129
|
-
for (const [operationId, entry] of Object.entries(operations)) {
|
|
130
|
-
out[operationId] = deepClone(entry);
|
|
131
|
-
}
|
|
132
|
-
return out;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** 断言 plain object 且键集合恰好为 expected(缺失/未知均拒绝)。 */
|
|
136
|
-
function assertExactKeys(obj, expected, where) {
|
|
137
|
-
if (!isPlainObject(obj)) {
|
|
138
|
-
fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
139
|
-
}
|
|
140
|
-
for (const key of expected) {
|
|
141
|
-
if (!Object.hasOwn(obj, key)) {
|
|
142
|
-
fail('INVALID_INPUT', `${where} 缺少必填字段 "${key}"`);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
for (const key of Object.keys(obj)) {
|
|
146
|
-
if (!expected.includes(key)) {
|
|
147
|
-
fail('INVALID_INPUT', `${where} 含未知字段 "${key}"(允许:${expected.join('/')})`, { key });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// ---------------------------------------------------------------------------
|
|
153
|
-
// 标识符规则(镜像既有冻结实现的同一规则,仅用于输入校验)
|
|
154
|
-
// ---------------------------------------------------------------------------
|
|
155
|
-
|
|
156
|
-
const WINDOWS_RESERVED = new Set([
|
|
157
|
-
'CON', 'PRN', 'AUX', 'NUL',
|
|
158
|
-
'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
|
|
159
|
-
'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9',
|
|
160
|
-
]);
|
|
161
|
-
|
|
162
|
-
/** scopeId:非空、≤128 UTF-16、无首尾空白、无控制字符、无孤立代理码元(镜像 core/topics.mjs)。 */
|
|
163
|
-
function validateScopeIdLocal(value, name = 'scopeId') {
|
|
164
|
-
if (typeof value !== 'string' || value.length === 0) {
|
|
165
|
-
fail('INVALID_INPUT', `${name} 必须是非空字符串`);
|
|
166
|
-
}
|
|
167
|
-
if (value.length > 128) {
|
|
168
|
-
fail('INVALID_INPUT', `${name} 不得超过 128 UTF-16(实际 ${value.length})`);
|
|
169
|
-
}
|
|
170
|
-
if (value !== value.trim()) {
|
|
171
|
-
fail('INVALID_INPUT', `${name} 不得含首尾空白`);
|
|
172
|
-
}
|
|
173
|
-
for (const ch of value) {
|
|
174
|
-
const cp = ch.codePointAt(0);
|
|
175
|
-
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
176
|
-
fail('INVALID_INPUT', `${name} 不得含孤立代理码元`);
|
|
177
|
-
}
|
|
178
|
-
if (cp <= 0x1f || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)) {
|
|
179
|
-
fail('INVALID_INPUT', `${name} 不得含控制字符`);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
return value;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** spark 卡 id:≤64 UTF-16、字母数字开头、仅 [A-Za-z0-9._-]、非保留名(镜像 sparks/store.mjs)。 */
|
|
186
|
-
function validateSparkIdLocal(id, field = 'id') {
|
|
187
|
-
if (typeof id !== 'string' || id.length === 0) {
|
|
188
|
-
fail('INVALID_INPUT', `${field} 必须是非空字符串`);
|
|
189
|
-
}
|
|
190
|
-
if (id.length > 64) {
|
|
191
|
-
fail('INVALID_INPUT', `${field} 超过 64 UTF-16(实际 ${id.length})`);
|
|
192
|
-
}
|
|
193
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) {
|
|
194
|
-
fail('INVALID_INPUT', `${field} 只允许字母/数字/点/下划线/连字符且以字母数字开头`);
|
|
195
|
-
}
|
|
196
|
-
if (id.endsWith('.')) {
|
|
197
|
-
fail('INVALID_INPUT', `${field} 不得以点结尾`);
|
|
198
|
-
}
|
|
199
|
-
if (RESERVED_JSON_KEYS.has(id)) {
|
|
200
|
-
fail('INVALID_INPUT', `${field} 与对象键保留名冲突`);
|
|
201
|
-
}
|
|
202
|
-
const stem = id.replace(/\.[A-Za-z0-9_-]+$/, '').toUpperCase();
|
|
203
|
-
if (WINDOWS_RESERVED.has(stem)) {
|
|
204
|
-
fail('INVALID_INPUT', `${field} 与 Windows 保留设备名冲突`);
|
|
205
|
-
}
|
|
206
|
-
return id;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** topic key:跨平台文件名安全规则(镜像 core/keys.mjs)。 */
|
|
210
|
-
function validateTopicKeyLocal(key, field = 'topic.key') {
|
|
211
|
-
if (typeof key !== 'string' || key.length === 0) {
|
|
212
|
-
fail('INVALID_INPUT', `${field} 必须是非空字符串`);
|
|
213
|
-
}
|
|
214
|
-
if (key.length > 128) {
|
|
215
|
-
fail('INVALID_INPUT', `${field} 不得超过 128 UTF-16(实际 ${key.length})`);
|
|
216
|
-
}
|
|
217
|
-
const forbidden = new Set([...'<>:"/\\|?*']);
|
|
218
|
-
for (const ch of key) {
|
|
219
|
-
const cp = ch.codePointAt(0);
|
|
220
|
-
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
221
|
-
fail('INVALID_INPUT', `${field} 不得含孤立代理码元`);
|
|
222
|
-
}
|
|
223
|
-
if (cp <= 0x1f || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)) {
|
|
224
|
-
fail('INVALID_INPUT', `${field} 不得含控制字符`);
|
|
225
|
-
}
|
|
226
|
-
if (forbidden.has(ch)) {
|
|
227
|
-
fail('INVALID_INPUT', `${field} 含非法文件名字符 "${ch}"`);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
if (/^\.+$/.test(key)) fail('INVALID_INPUT', `${field} 不得只由点组成`);
|
|
231
|
-
if (key.startsWith(' ')) fail('INVALID_INPUT', `${field} 不得以空格开头`);
|
|
232
|
-
if (key.endsWith(' ') || key.endsWith('.')) {
|
|
233
|
-
fail('INVALID_INPUT', `${field} 不得以空格或点结尾`);
|
|
234
|
-
}
|
|
235
|
-
const firstSegment = key.split('.')[0].replace(/[. ]+$/, '').toUpperCase();
|
|
236
|
-
if (WINDOWS_RESERVED.has(firstSegment)) {
|
|
237
|
-
fail('INVALID_INPUT', `${field} 与 Windows 保留设备名冲突`);
|
|
238
|
-
}
|
|
239
|
-
if (key.toLowerCase() === 'core' || key.toLowerCase() === 'core.md') {
|
|
240
|
-
fail('INVALID_INPUT', `${field} 与 Shiori 保留别名 "core" 冲突`);
|
|
241
|
-
}
|
|
242
|
-
return key;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** operationId:≤128 UTF-16、字母数字开头、仅 [A-Za-z0-9._-](镜像 storage/paths.mjs)。 */
|
|
246
|
-
function validateOperationIdLocal(operationId) {
|
|
247
|
-
if (typeof operationId !== 'string' || operationId.length === 0) {
|
|
248
|
-
fail('INVALID_INPUT', 'operationId 必须是非空字符串');
|
|
249
|
-
}
|
|
250
|
-
if (operationId.length > 128) {
|
|
251
|
-
fail('INVALID_INPUT', `operationId 超过 128 UTF-16(实际 ${operationId.length})`);
|
|
252
|
-
}
|
|
253
|
-
if (operationId !== operationId.trim()) {
|
|
254
|
-
fail('INVALID_INPUT', 'operationId 不得含首尾空白');
|
|
255
|
-
}
|
|
256
|
-
if (/[/\\:]/.test(operationId) || operationId === '.' || operationId === '..') {
|
|
257
|
-
fail('INVALID_INPUT', 'operationId 含非法字符');
|
|
258
|
-
}
|
|
259
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(operationId)) {
|
|
260
|
-
fail('INVALID_INPUT', 'operationId 只允许字母/数字/点/下划线/连字符且以字母数字开头');
|
|
261
|
-
}
|
|
262
|
-
const stem = operationId.replace(/\.[A-Za-z0-9_-]+$/, '').toUpperCase();
|
|
263
|
-
if (WINDOWS_RESERVED.has(stem)) {
|
|
264
|
-
fail('INVALID_INPUT', 'operationId 与 Windows 保留设备名冲突');
|
|
265
|
-
}
|
|
266
|
-
return operationId;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// ---------------------------------------------------------------------------
|
|
270
|
-
// 候选(Candidate)校验 —— 与 J 槽契约同形,K 侧重验防篡改
|
|
271
|
-
// ---------------------------------------------------------------------------
|
|
272
|
-
|
|
273
|
-
const CANDIDATE_KINDS = new Set(['isolated', 'link', 'cluster']);
|
|
274
|
-
|
|
275
|
-
/** SourceRef 列表:{id,revision} 精确形状、revision>=1、id 唯一且按 UTF-16 升序(契约 §1)。 */
|
|
276
|
-
function validateSourceRefs(sources, where) {
|
|
277
|
-
if (!Array.isArray(sources) || sources.length === 0) {
|
|
278
|
-
fail('INVALID_INPUT', `${where} 必须是非空 SourceRef 数组`);
|
|
279
|
-
}
|
|
280
|
-
const seen = new Set();
|
|
281
|
-
let prev = null;
|
|
282
|
-
for (let i = 0; i < sources.length; i += 1) {
|
|
283
|
-
const ref = sources[i];
|
|
284
|
-
assertExactKeys(ref, ['id', 'revision'], `${where}[${i}]`);
|
|
285
|
-
validateSparkIdLocal(ref.id, `${where}[${i}].id`);
|
|
286
|
-
if (!Number.isInteger(ref.revision) || ref.revision < 1) {
|
|
287
|
-
fail('INVALID_INPUT', `${where}[${i}].revision 必须是 >=1 的整数`);
|
|
288
|
-
}
|
|
289
|
-
if (seen.has(ref.id)) {
|
|
290
|
-
fail('INVALID_INPUT', `${where} 存在重复 id "${ref.id}"`);
|
|
291
|
-
}
|
|
292
|
-
seen.add(ref.id);
|
|
293
|
-
if (prev !== null && byCodepoint(prev, ref.id) >= 0) {
|
|
294
|
-
fail('INVALID_INPUT', `${where} 必须按 id 的 UTF-16 序升序排列("${ref.id}" 之前应为更大 id)`);
|
|
295
|
-
}
|
|
296
|
-
prev = ref.id;
|
|
297
|
-
}
|
|
298
|
-
return sources;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* 完整候选校验:形状 / kind / scope 一致 / sources 规范化 / 证据协议 JSON,
|
|
303
|
-
* 并重算 id=digest({kind,scopeId,sources,evidence}) 防候选篡改(契约 §3「所有candidate重新核验id与scope」)。
|
|
304
|
-
*/
|
|
305
|
-
function validateCandidate(candidate, expectedScopeId, where) {
|
|
306
|
-
assertProtocolJson(candidate, where);
|
|
307
|
-
assertExactKeys(candidate, ['id', 'kind', 'scopeId', 'sources', 'evidence'], where);
|
|
308
|
-
if (!CANDIDATE_KINDS.has(candidate.kind)) {
|
|
309
|
-
fail('INVALID_INPUT', `${where}.kind 必须是 isolated/link/cluster(得到 ${JSON.stringify(candidate.kind)})`);
|
|
310
|
-
}
|
|
311
|
-
if (candidate.scopeId !== expectedScopeId) {
|
|
312
|
-
fail('INVALID_INPUT', `${where}.scopeId 与队列 scope 不一致,跨 scope 候选拒绝`, {
|
|
313
|
-
candidateScopeId: candidate.scopeId, queueScopeId: expectedScopeId,
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
validateSourceRefs(candidate.sources, `${where}.sources`);
|
|
317
|
-
if (!isPlainObject(candidate.evidence)) {
|
|
318
|
-
fail('INVALID_INPUT', `${where}.evidence 必须是对象`);
|
|
319
|
-
}
|
|
320
|
-
if (typeof candidate.id !== 'string' || !/^[0-9a-f]{64}$/.test(candidate.id)) {
|
|
321
|
-
fail('INVALID_INPUT', `${where}.id 必须是小写 64 位 hex`);
|
|
322
|
-
}
|
|
323
|
-
const recomputed = digest({
|
|
324
|
-
kind: candidate.kind, scopeId: candidate.scopeId,
|
|
325
|
-
sources: candidate.sources, evidence: candidate.evidence,
|
|
326
|
-
});
|
|
327
|
-
if (recomputed !== candidate.id) {
|
|
328
|
-
fail('INVALID_INPUT', `${where}.id 与 digest({kind,scopeId,sources,evidence}) 不一致,候选疑似被篡改`, {
|
|
329
|
-
declaredId: candidate.id, recomputedId: recomputed,
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
return candidate;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// ---------------------------------------------------------------------------
|
|
336
|
-
// createCandidateQueue
|
|
337
|
-
// ---------------------------------------------------------------------------
|
|
338
|
-
//
|
|
339
|
-
// 快照编码(K 文档声明,恢复时严格校验):
|
|
340
|
-
// snapshot = { version:1, scopeId, revision, items, operations }
|
|
341
|
-
// items[i] = { candidate, status: 'pending'|'reviewed'|'dismissed' }(按入队顺序)
|
|
342
|
-
// operations[operationId] = { kind:'enqueue'|'review', fingerprint:64hex,
|
|
343
|
-
// request:{...原请求载荷}, result:{version:1,scopeId,revision,items} }
|
|
344
|
-
// result 是不含 operations 的业务快照(避免递归指数膨胀,契约 §5);request 被保留
|
|
345
|
-
// 供恢复时从空队列做确定性全量重放:重放结果必须与 items/revision 完全一致,
|
|
346
|
-
// 因此顶层 revision 不可被单独信任。重放命中幂等时返回「首次业务结果 + 当前 operations 克隆」。
|
|
347
|
-
// operations 字典在内存与快照输出中均为 null 原型安全字典:键读取一律按
|
|
348
|
-
// own-property 语义(`constructor`/`toString` 等继承名是合法 operationId,
|
|
349
|
-
// 不与 Object.prototype 属性混淆;`__proto__` 形态不触发原型 setter)。
|
|
350
|
-
|
|
351
|
-
const ITEM_STATUSES = new Set(['pending', 'reviewed', 'dismissed']);
|
|
352
|
-
const OP_KINDS = new Set(['enqueue', 'review', 'converge']);
|
|
353
|
-
|
|
354
|
-
function businessSnapshotOf(state) {
|
|
355
|
-
return {
|
|
356
|
-
version: 1,
|
|
357
|
-
scopeId: state.scopeId,
|
|
358
|
-
revision: state.revision,
|
|
359
|
-
items: deepClone(state.items),
|
|
360
|
-
};
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
function fullSnapshotOf(state) {
|
|
364
|
-
return { ...businessSnapshotOf(state), operations: cloneOperations(state.operations) };
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
/** enqueue 业务逻辑(输入已校验、已克隆):相同 id 相同 payload 去重不重复入队。 */
|
|
368
|
-
function applyEnqueue(state, candidates) {
|
|
369
|
-
for (const candidate of candidates) {
|
|
370
|
-
const existing = state.items.find((item) => item.candidate.id === candidate.id);
|
|
371
|
-
if (existing === undefined) {
|
|
372
|
-
state.items.push({ candidate, status: 'pending' });
|
|
373
|
-
} else if (stable(existing.candidate) !== stable(candidate)) {
|
|
374
|
-
// id 经 digest 核验后理论上不可达;保留为对损坏状态的防御。
|
|
375
|
-
fail('INVALID_STATE', `队列内已存在同 id 不同内容的候选 "${candidate.id}",疑似状态损坏`, {
|
|
376
|
-
candidateId: candidate.id,
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/** review 业务逻辑(输入已校验):只有 pending 可 review。 */
|
|
383
|
-
function applyReview(state, candidateId, decision) {
|
|
384
|
-
const item = state.items.find((entry) => entry.candidate.id === candidateId);
|
|
385
|
-
if (item === undefined) {
|
|
386
|
-
fail('NOT_FOUND', `候选 "${candidateId}" 不在队列中`, { candidateId });
|
|
387
|
-
}
|
|
388
|
-
if (item.status !== 'pending') {
|
|
389
|
-
fail('INVALID_STATE', `候选 "${candidateId}" 状态为 ${item.status},只有 pending 可以 review`, {
|
|
390
|
-
candidateId, status: item.status,
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
item.status = decision;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* converge 业务逻辑(输入已校验、已克隆;P-A 队列收敛):
|
|
398
|
-
* 以本次分析派生的候选集为准——仍在场的候选保留既有 status(reviewed 不因
|
|
399
|
-
* 重新分析退回 pending),新出现的候选以 pending 追加,本次不再出现的候选
|
|
400
|
-
* (源卡已 merged/archived 或派生条件消失)从队列移除。确定性:给定重放到的
|
|
401
|
-
* 中间状态与同一候选集,产出唯一终态。
|
|
402
|
-
*/
|
|
403
|
-
function applyConverge(state, candidates, keepAbsentIds = null) {
|
|
404
|
-
const currentIds = new Set(candidates.map((candidate) => candidate.id));
|
|
405
|
-
// 截断保护(P-A 残留):分析候选达到 limit 上限时,"不在本次候选集"不再
|
|
406
|
-
// 等价于"失效"——keepAbsentIds 列出的既有队列项按原 status 保留。
|
|
407
|
-
const keepIds = keepAbsentIds === null ? null : new Set(keepAbsentIds);
|
|
408
|
-
const kept = [];
|
|
409
|
-
const keptIds = new Set();
|
|
410
|
-
for (const item of state.items) {
|
|
411
|
-
if (currentIds.has(item.candidate.id) || (keepIds !== null && keepIds.has(item.candidate.id))) {
|
|
412
|
-
kept.push(item);
|
|
413
|
-
keptIds.add(item.candidate.id);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
for (const candidate of candidates) {
|
|
417
|
-
if (!keptIds.has(candidate.id)) {
|
|
418
|
-
kept.push({ candidate, status: 'pending' });
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
state.items = kept;
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/** 校验 opts 形状并返回规范化值;optionalKeys 中的键可缺席,其余未知键拒绝。 */
|
|
425
|
-
function readQueueOpts(opts, expectedKeys, method, optionalKeys = []) {
|
|
426
|
-
if (!isPlainObject(opts)) fail('INVALID_INPUT', `${method} opts 必须是普通对象`);
|
|
427
|
-
const allowed = [...expectedKeys, ...optionalKeys];
|
|
428
|
-
for (const key of expectedKeys) {
|
|
429
|
-
if (!Object.hasOwn(opts, key)) fail('INVALID_INPUT', `${method} opts 缺少必填字段 "${key}"`);
|
|
430
|
-
}
|
|
431
|
-
for (const key of Object.keys(opts)) {
|
|
432
|
-
if (!allowed.includes(key)) {
|
|
433
|
-
fail('INVALID_INPUT', `${method} opts 含未知字段 "${key}"(允许:${allowed.join('/')})`, { key });
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
if (!Number.isInteger(opts.expectedRevision) || opts.expectedRevision < 0) {
|
|
437
|
-
fail('INVALID_INPUT', `${method} opts.expectedRevision 必须是 >=0 的整数`);
|
|
438
|
-
}
|
|
439
|
-
validateOperationIdLocal(opts.operationId);
|
|
440
|
-
return opts;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
/** 校验一份业务快照(items/revision),用于 operations[].result 与恢复路径。 */
|
|
444
|
-
function validateBusinessSnapshot(value, scopeId, where) {
|
|
445
|
-
assertExactKeys(value, ['version', 'scopeId', 'revision', 'items'], where);
|
|
446
|
-
if (value.version !== 1) fail('INVALID_INPUT', `${where}.version 必须是 1`);
|
|
447
|
-
if (value.scopeId !== scopeId) {
|
|
448
|
-
fail('INVALID_INPUT', `${where}.scopeId 与队列 scope 不一致`);
|
|
449
|
-
}
|
|
450
|
-
if (!Number.isInteger(value.revision) || value.revision < 0) {
|
|
451
|
-
fail('INVALID_INPUT', `${where}.revision 必须是 >=0 的整数`);
|
|
452
|
-
}
|
|
453
|
-
validateItems(value.items, scopeId, `${where}.items`);
|
|
454
|
-
return value;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
function validateItems(items, scopeId, where) {
|
|
458
|
-
if (!Array.isArray(items)) fail('INVALID_INPUT', `${where} 必须是数组`);
|
|
459
|
-
const seen = new Set();
|
|
460
|
-
for (let i = 0; i < items.length; i += 1) {
|
|
461
|
-
const item = items[i];
|
|
462
|
-
assertExactKeys(item, ['candidate', 'status'], `${where}[${i}]`);
|
|
463
|
-
if (!ITEM_STATUSES.has(item.status)) {
|
|
464
|
-
fail('INVALID_INPUT', `${where}[${i}].status 必须是 pending/reviewed/dismissed`);
|
|
465
|
-
}
|
|
466
|
-
validateCandidate(item.candidate, scopeId, `${where}[${i}].candidate`);
|
|
467
|
-
if (seen.has(item.candidate.id)) {
|
|
468
|
-
fail('INVALID_INPUT', `${where} 存在重复候选 id "${item.candidate.id}"`);
|
|
469
|
-
}
|
|
470
|
-
seen.add(item.candidate.id);
|
|
471
|
-
}
|
|
472
|
-
return items;
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
/** 校验单条 operation 记录(含 fingerprint 与 request 的一致性)。 */
|
|
476
|
-
function validateOperationEntry(entry, operationId, scopeId, where) {
|
|
477
|
-
assertExactKeys(entry, ['kind', 'fingerprint', 'request', 'result'], where);
|
|
478
|
-
if (!OP_KINDS.has(entry.kind)) {
|
|
479
|
-
fail('INVALID_INPUT', `${where}.kind 必须是 enqueue/review/converge`);
|
|
480
|
-
}
|
|
481
|
-
if (typeof entry.fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(entry.fingerprint)) {
|
|
482
|
-
fail('INVALID_INPUT', `${where}.fingerprint 必须是小写 64 位 hex`);
|
|
483
|
-
}
|
|
484
|
-
const request = entry.request;
|
|
485
|
-
if (entry.kind === 'enqueue') {
|
|
486
|
-
assertExactKeys(request, ['kind', 'candidates'], `${where}.request`);
|
|
487
|
-
if (request.kind !== 'enqueue') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
488
|
-
if (!Array.isArray(request.candidates) || request.candidates.length === 0) {
|
|
489
|
-
fail('INVALID_INPUT', `${where}.request.candidates 必须是非空数组`);
|
|
490
|
-
}
|
|
491
|
-
const seen = new Set();
|
|
492
|
-
for (let i = 0; i < request.candidates.length; i += 1) {
|
|
493
|
-
validateCandidate(request.candidates[i], scopeId, `${where}.request.candidates[${i}]`);
|
|
494
|
-
const cid = request.candidates[i].id;
|
|
495
|
-
if (seen.has(cid)) fail('INVALID_INPUT', `${where}.request.candidates 存在重复 id "${cid}"`);
|
|
496
|
-
seen.add(cid);
|
|
497
|
-
}
|
|
498
|
-
} else if (entry.kind === 'converge') {
|
|
499
|
-
// keepAbsentIds 可选(旧快照无此键;截断保护引入)。未知键仍拒绝。
|
|
500
|
-
const requestKeys = Object.keys(request);
|
|
501
|
-
for (const key of requestKeys) {
|
|
502
|
-
if (key !== 'kind' && key !== 'candidates' && key !== 'keepAbsentIds') {
|
|
503
|
-
fail('INVALID_INPUT', `${where}.request 含未知字段 "${key}"(允许:kind/candidates/keepAbsentIds)`);
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
if (!requestKeys.includes('kind')) fail('INVALID_INPUT', `${where}.request 缺少必填字段 "kind"`);
|
|
507
|
-
if (!requestKeys.includes('candidates')) fail('INVALID_INPUT', `${where}.request 缺少必填字段 "candidates"`);
|
|
508
|
-
if (request.kind !== 'converge') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
509
|
-
// 收敛允许空数组(本次分析无候选 = 清空失效候选)。
|
|
510
|
-
if (!Array.isArray(request.candidates)) {
|
|
511
|
-
fail('INVALID_INPUT', `${where}.request.candidates 必须是数组(可为空)`);
|
|
512
|
-
}
|
|
513
|
-
const seen = new Set();
|
|
514
|
-
for (let i = 0; i < request.candidates.length; i += 1) {
|
|
515
|
-
validateCandidate(request.candidates[i], scopeId, `${where}.request.candidates[${i}]`);
|
|
516
|
-
const cid = request.candidates[i].id;
|
|
517
|
-
if (seen.has(cid)) fail('INVALID_INPUT', `${where}.request.candidates 存在重复 id "${cid}"`);
|
|
518
|
-
seen.add(cid);
|
|
519
|
-
}
|
|
520
|
-
if (requestKeys.includes('keepAbsentIds')) {
|
|
521
|
-
if (!Array.isArray(request.keepAbsentIds)) {
|
|
522
|
-
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须是数组`);
|
|
523
|
-
}
|
|
524
|
-
const seenKeep = new Set();
|
|
525
|
-
for (const id of request.keepAbsentIds) {
|
|
526
|
-
if (typeof id !== 'string' || !/^[0-9a-f]{64}$/.test(id)) {
|
|
527
|
-
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须全是小写 64 位 hex 候选 id`);
|
|
528
|
-
}
|
|
529
|
-
if (seenKeep.has(id)) fail('INVALID_INPUT', `${where}.request.keepAbsentIds 存在重复 id "${id}"`);
|
|
530
|
-
seenKeep.add(id);
|
|
531
|
-
}
|
|
532
|
-
if (JSON.stringify([...seenKeep].sort(byCodepoint)) !== JSON.stringify(request.keepAbsentIds)) {
|
|
533
|
-
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须按码点升序去重存放`);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
} else {
|
|
537
|
-
assertExactKeys(request, ['kind', 'candidateId', 'decision'], `${where}.request`);
|
|
538
|
-
if (request.kind !== 'review') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
539
|
-
if (typeof request.candidateId !== 'string' || !/^[0-9a-f]{64}$/.test(request.candidateId)) {
|
|
540
|
-
fail('INVALID_INPUT', `${where}.request.candidateId 必须是小写 64 位 hex`);
|
|
541
|
-
}
|
|
542
|
-
if (request.decision !== 'reviewed' && request.decision !== 'dismissed') {
|
|
543
|
-
fail('INVALID_INPUT', `${where}.request.decision 必须是 reviewed/dismissed`);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
if (digest(request) !== entry.fingerprint) {
|
|
547
|
-
fail('INVALID_INPUT', `${where}.fingerprint 与 request 内容不匹配,操作记录疑似被篡改`);
|
|
548
|
-
}
|
|
549
|
-
validateBusinessSnapshot(entry.result, scopeId, `${where}.result`);
|
|
550
|
-
return entry;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* 从快照恢复:结构校验 + 从空队列按 result.revision 升序确定性重放全部 operations,
|
|
555
|
-
* 每一步的中间业务快照必须与记录的 result 完全一致,最终状态必须与顶层
|
|
556
|
-
* items/revision 完全一致 —— 顶层 revision 不被单独信任。
|
|
557
|
-
*/
|
|
558
|
-
function restoreState(snapshot, scopeId) {
|
|
559
|
-
assertProtocolJson(snapshot, 'snapshot');
|
|
560
|
-
assertExactKeys(snapshot, ['version', 'scopeId', 'revision', 'items', 'operations'], 'snapshot');
|
|
561
|
-
if (snapshot.version !== 1) fail('INVALID_INPUT', 'snapshot.version 必须是 1');
|
|
562
|
-
if (snapshot.scopeId !== scopeId) {
|
|
563
|
-
fail('INVALID_INPUT', 'snapshot.scopeId 与工厂 scopeId 不一致,拒绝恢复');
|
|
564
|
-
}
|
|
565
|
-
if (!Number.isInteger(snapshot.revision) || snapshot.revision < 0) {
|
|
566
|
-
fail('INVALID_INPUT', 'snapshot.revision 必须是 >=0 的整数');
|
|
567
|
-
}
|
|
568
|
-
validateItems(snapshot.items, scopeId, 'snapshot.items');
|
|
569
|
-
if (!isPlainObject(snapshot.operations)) {
|
|
570
|
-
fail('INVALID_INPUT', 'snapshot.operations 必须是对象');
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
const entries = [];
|
|
574
|
-
for (const [operationId, entry] of Object.entries(snapshot.operations)) {
|
|
575
|
-
validateOperationIdLocal(operationId);
|
|
576
|
-
validateOperationEntry(entry, operationId, scopeId, `snapshot.operations.${operationId}`);
|
|
577
|
-
entries.push({ operationId, entry });
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
// 不变量:每个成功队列事务 revision+1 并恰好记录一条 operation,
|
|
581
|
-
// 因此 operations 数必须等于顶层 revision,且各 result.revision 恰为 1..N。
|
|
582
|
-
if (entries.length !== snapshot.revision) {
|
|
583
|
-
fail('INVALID_STATE', `snapshot.revision (${snapshot.revision}) 与 operations 条数 (${entries.length}) 不一致,拒绝恢复`);
|
|
584
|
-
}
|
|
585
|
-
const revisions = entries.map(({ entry }) => entry.result.revision).sort((a, b) => a - b);
|
|
586
|
-
for (let i = 0; i < revisions.length; i += 1) {
|
|
587
|
-
if (revisions[i] !== i + 1) {
|
|
588
|
-
fail('INVALID_STATE', `operations 的 result.revision 必须恰好覆盖 1..${entries.length}(发现 ${revisions[i]})`);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
const state = { scopeId, revision: 0, items: [], operations: newOperationRegistry() };
|
|
593
|
-
entries.sort((a, b) => a.entry.result.revision - b.entry.result.revision);
|
|
594
|
-
for (const { operationId, entry } of entries) {
|
|
595
|
-
if (entry.kind === 'enqueue') {
|
|
596
|
-
applyEnqueue(state, deepClone(entry.request.candidates));
|
|
597
|
-
} else if (entry.kind === 'converge') {
|
|
598
|
-
applyConverge(state, deepClone(entry.request.candidates), entry.request.keepAbsentIds ?? null);
|
|
599
|
-
} else {
|
|
600
|
-
applyReview(state, entry.request.candidateId, entry.request.decision);
|
|
601
|
-
}
|
|
602
|
-
state.revision += 1;
|
|
603
|
-
const produced = businessSnapshotOf(state);
|
|
604
|
-
if (stable(produced) !== stable(entry.result)) {
|
|
605
|
-
fail('INVALID_STATE', `operation "${operationId}" 的重放结果与记录的 result 不一致,快照历史被篡改`, {
|
|
606
|
-
operationId,
|
|
607
|
-
});
|
|
608
|
-
}
|
|
609
|
-
state.operations[operationId] = {
|
|
610
|
-
kind: entry.kind,
|
|
611
|
-
fingerprint: entry.fingerprint,
|
|
612
|
-
request: deepClone(entry.request),
|
|
613
|
-
result: deepClone(entry.result),
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
if (state.revision !== snapshot.revision
|
|
617
|
-
|| stable(businessSnapshotOf(state)) !== stable({
|
|
618
|
-
version: 1, scopeId, revision: snapshot.revision, items: snapshot.items,
|
|
619
|
-
})) {
|
|
620
|
-
fail('INVALID_STATE', '重放终态与快照顶层 items/revision 不一致,拒绝恢复');
|
|
621
|
-
}
|
|
622
|
-
return state;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
/** 断言 plain object:required 必须在场,optional 可选,其余未知键拒绝。 */
|
|
626
|
-
function assertAllowedKeys(obj, required, optional, where) {
|
|
627
|
-
if (!isPlainObject(obj)) {
|
|
628
|
-
fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
629
|
-
}
|
|
630
|
-
for (const key of required) {
|
|
631
|
-
if (!Object.hasOwn(obj, key)) {
|
|
632
|
-
fail('INVALID_INPUT', `${where} 缺少必填字段 "${key}"`);
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
const allowed = new Set([...required, ...optional]);
|
|
636
|
-
for (const key of Object.keys(obj)) {
|
|
637
|
-
if (!allowed.has(key)) {
|
|
638
|
-
fail('INVALID_INPUT', `${where} 含未知字段 "${key}"(允许:${[...allowed].join('/')})`, { key });
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
/**
|
|
644
|
-
* 建立候选队列。
|
|
645
|
-
*
|
|
646
|
-
* @param {object} params
|
|
647
|
-
* @param {string} params.scopeId 显式 scope(factory-only;不从 cwd/HOME/global 猜测)
|
|
648
|
-
* @param {object} [params.snapshot] 可选快照;提供时执行严格恢复校验
|
|
649
|
-
* @returns {object} queue = { snapshot(), enqueue(), review() }
|
|
650
|
-
*/
|
|
651
|
-
export function createCandidateQueue(params) {
|
|
652
|
-
if (!isPlainObject(params)) {
|
|
653
|
-
fail('INVALID_INPUT', 'createCandidateQueue 参数必须是对象');
|
|
654
|
-
}
|
|
655
|
-
assertAllowedKeys(params, ['scopeId'], ['snapshot'], 'createCandidateQueue 参数');
|
|
656
|
-
const { scopeId, snapshot } = params;
|
|
657
|
-
validateScopeIdLocal(scopeId);
|
|
658
|
-
const state = snapshot === undefined
|
|
659
|
-
? { scopeId, revision: 0, items: [], operations: newOperationRegistry() }
|
|
660
|
-
: restoreState(snapshot, scopeId);
|
|
661
|
-
|
|
662
|
-
const queue = {
|
|
663
|
-
/** 当前完整快照的深克隆(修改返回值不影响队列内部状态)。 */
|
|
664
|
-
snapshot() {
|
|
665
|
-
return fullSnapshotOf(state);
|
|
666
|
-
},
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* 入队:幂等按 operationId 先于 CAS(重放不受 expectedRevision 约束);
|
|
670
|
-
* 同 operationId 异 payload 拒绝;相同 id 相同 payload 不重复入队,
|
|
671
|
-
* 即便去重 no-op 也算一次队列事务(revision+1)。
|
|
672
|
-
*/
|
|
673
|
-
enqueue(candidates, opts) {
|
|
674
|
-
if (!Array.isArray(candidates) || candidates.length === 0) {
|
|
675
|
-
fail('INVALID_INPUT', 'enqueue 的 candidates 必须是非空数组');
|
|
676
|
-
}
|
|
677
|
-
for (let i = 0; i < candidates.length; i += 1) {
|
|
678
|
-
validateCandidate(candidates[i], scopeId, `candidates[${i}]`);
|
|
679
|
-
}
|
|
680
|
-
const batchIds = new Set();
|
|
681
|
-
for (const candidate of candidates) {
|
|
682
|
-
if (batchIds.has(candidate.id)) {
|
|
683
|
-
fail('INVALID_INPUT', `同一批 enqueue 内存在重复候选 id "${candidate.id}"`);
|
|
684
|
-
}
|
|
685
|
-
batchIds.add(candidate.id);
|
|
686
|
-
}
|
|
687
|
-
readQueueOpts(opts, ['expectedRevision', 'operationId'], 'enqueue');
|
|
688
|
-
|
|
689
|
-
const request = { kind: 'enqueue', candidates: deepClone(candidates) };
|
|
690
|
-
const fingerprint = digest(request);
|
|
691
|
-
|
|
692
|
-
// 幂等先于 CAS:同 operationId 同 payload 直接重放首次业务结果 + 当前 operations 克隆。
|
|
693
|
-
// 查找必须走 own-property(安全字典),继承属性名不得被误读为历史账项(K-1)。
|
|
694
|
-
const prior = lookupOperation(state.operations, opts.operationId);
|
|
695
|
-
if (prior !== undefined) {
|
|
696
|
-
if (prior.fingerprint !== fingerprint) {
|
|
697
|
-
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
698
|
-
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'enqueue',
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
if (opts.expectedRevision !== state.revision) {
|
|
705
|
-
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
706
|
-
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
707
|
-
});
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
applyEnqueue(state, request.candidates);
|
|
711
|
-
state.revision += 1;
|
|
712
|
-
state.operations[opts.operationId] = {
|
|
713
|
-
kind: 'enqueue', fingerprint, request, result: businessSnapshotOf(state),
|
|
714
|
-
};
|
|
715
|
-
return fullSnapshotOf(state);
|
|
716
|
-
},
|
|
717
|
-
|
|
718
|
-
/**
|
|
719
|
-
* 审核:只有 pending 可以 review;reviewed 是「已审阅」而非「已批准/已执行」,
|
|
720
|
-
* 不产生任何业务写入。失败(NOT_FOUND/INVALID_STATE/CAS 冲突)时队列原样。
|
|
721
|
-
*/
|
|
722
|
-
review(candidateId, opts) {
|
|
723
|
-
if (typeof candidateId !== 'string' || !/^[0-9a-f]{64}$/.test(candidateId)) {
|
|
724
|
-
fail('INVALID_INPUT', 'candidateId 必须是小写 64 位 hex(候选 id 即 digest)');
|
|
725
|
-
}
|
|
726
|
-
readQueueOpts(opts, ['decision', 'expectedRevision', 'operationId'], 'review');
|
|
727
|
-
if (opts.decision !== 'reviewed' && opts.decision !== 'dismissed') {
|
|
728
|
-
fail('INVALID_INPUT', 'review opts.decision 必须是 reviewed 或 dismissed');
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
const request = { kind: 'review', candidateId, decision: opts.decision };
|
|
732
|
-
const fingerprint = digest(request);
|
|
733
|
-
|
|
734
|
-
const prior = lookupOperation(state.operations, opts.operationId);
|
|
735
|
-
if (prior !== undefined) {
|
|
736
|
-
if (prior.fingerprint !== fingerprint) {
|
|
737
|
-
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
738
|
-
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'review',
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
if (opts.expectedRevision !== state.revision) {
|
|
745
|
-
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
746
|
-
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
747
|
-
});
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
applyReview(state, candidateId, opts.decision);
|
|
751
|
-
state.revision += 1;
|
|
752
|
-
state.operations[opts.operationId] = {
|
|
753
|
-
kind: 'review', fingerprint, request, result: businessSnapshotOf(state),
|
|
754
|
-
};
|
|
755
|
-
return fullSnapshotOf(state);
|
|
756
|
-
},
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* 收敛(P-A):以本次分析派生的候选集为准对齐队列——保留在场候选的既有
|
|
760
|
-
* status(reviewed 不退回)、新候选以 pending 追加、不在场的候选移除
|
|
761
|
-
* (其源卡已 merged/archived 或派生条件消失)。candidates 允许空数组。
|
|
762
|
-
* opts.keepAbsentIds(可选,null 或 64-hex id 数组):截断保护——调用方
|
|
763
|
-
* 在候选集被 limit 截断时,把"不在候选集但源卡仍全部 active"的既有队列项
|
|
764
|
-
* 列在这里,它们按原 status 保留而非移除;未截断时传 null(缺省),
|
|
765
|
-
* "不在场 = 移除"语义不变。与 enqueue 同幂等语义:同 operationId 同
|
|
766
|
-
* payload 重放首次业务结果;即便集合无变化也记一次队列事务
|
|
767
|
-
* (revision+1),保持「operations 数 === revision」的恢复不变量与严格
|
|
768
|
-
* 幂等。keepAbsentIds 入 journal request(排序规范化),重放逐字一致。
|
|
769
|
-
*/
|
|
770
|
-
converge(candidates, opts) {
|
|
771
|
-
if (!Array.isArray(candidates)) {
|
|
772
|
-
fail('INVALID_INPUT', 'converge 的 candidates 必须是数组(可为空)');
|
|
773
|
-
}
|
|
774
|
-
for (let i = 0; i < candidates.length; i += 1) {
|
|
775
|
-
validateCandidate(candidates[i], scopeId, `candidates[${i}]`);
|
|
776
|
-
}
|
|
777
|
-
const batchIds = new Set();
|
|
778
|
-
for (const candidate of candidates) {
|
|
779
|
-
if (batchIds.has(candidate.id)) {
|
|
780
|
-
fail('INVALID_INPUT', `同一批 converge 内存在重复候选 id "${candidate.id}"`);
|
|
781
|
-
}
|
|
782
|
-
batchIds.add(candidate.id);
|
|
783
|
-
}
|
|
784
|
-
readQueueOpts(opts, ['expectedRevision', 'operationId'], 'converge', ['keepAbsentIds']);
|
|
785
|
-
let keepAbsentIds = null;
|
|
786
|
-
if (opts.keepAbsentIds !== undefined && opts.keepAbsentIds !== null) {
|
|
787
|
-
if (!Array.isArray(opts.keepAbsentIds)) {
|
|
788
|
-
fail('INVALID_INPUT', 'converge opts.keepAbsentIds 必须是数组或 null');
|
|
789
|
-
}
|
|
790
|
-
const seenKeep = new Set();
|
|
791
|
-
for (const id of opts.keepAbsentIds) {
|
|
792
|
-
if (typeof id !== 'string' || !/^[0-9a-f]{64}$/.test(id)) {
|
|
793
|
-
fail('INVALID_INPUT', 'converge opts.keepAbsentIds 必须全是小写 64 位 hex 候选 id');
|
|
794
|
-
}
|
|
795
|
-
if (seenKeep.has(id)) {
|
|
796
|
-
fail('INVALID_INPUT', `converge opts.keepAbsentIds 存在重复 id "${id}"`);
|
|
797
|
-
}
|
|
798
|
-
seenKeep.add(id);
|
|
799
|
-
}
|
|
800
|
-
keepAbsentIds = [...seenKeep].sort(byCodepoint);
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
const request = { kind: 'converge', candidates: deepClone(candidates) };
|
|
804
|
-
if (keepAbsentIds !== null) request.keepAbsentIds = keepAbsentIds;
|
|
805
|
-
const fingerprint = digest(request);
|
|
806
|
-
|
|
807
|
-
const prior = lookupOperation(state.operations, opts.operationId);
|
|
808
|
-
if (prior !== undefined) {
|
|
809
|
-
if (prior.fingerprint !== fingerprint) {
|
|
810
|
-
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
811
|
-
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'converge',
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
if (opts.expectedRevision !== state.revision) {
|
|
818
|
-
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
819
|
-
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
820
|
-
});
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
applyConverge(state, request.candidates, keepAbsentIds);
|
|
824
|
-
state.revision += 1;
|
|
825
|
-
state.operations[opts.operationId] = {
|
|
826
|
-
kind: 'converge', fingerprint, request, result: businessSnapshotOf(state),
|
|
827
|
-
};
|
|
828
|
-
return fullSnapshotOf(state);
|
|
829
|
-
},
|
|
830
|
-
};
|
|
831
|
-
return queue;
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// ---------------------------------------------------------------------------
|
|
835
|
-
//
|
|
836
|
-
// ---------------------------------------------------------------------------
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
if (!
|
|
872
|
-
for (
|
|
873
|
-
|
|
874
|
-
if (!
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
if (
|
|
1035
|
-
fail('INVALID_INPUT',
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
})
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
};
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
}
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
}
|
|
1
|
+
// Shiori P3-QUEUE-DIFF · K 槽位:可恢复候选队列与审阅 diff 草案
|
|
2
|
+
//
|
|
3
|
+
// 职责边界:
|
|
4
|
+
// - createCandidateQueue:内存中的候选队列,可 JSON 快照恢复;本模块不持久化任何用户文件。
|
|
5
|
+
// 入队 / 审核只改变队列自身状态;reviewed 是「已审阅」不是「已批准 / 已执行」,
|
|
6
|
+
// 队列不产生任何业务写入,也不携带 approval / operationId 语义到 Plan。
|
|
7
|
+
// - buildDraft:把 (candidate, records, proposal) 变成确定性的 Plan + digest + 展示用 diff。
|
|
8
|
+
// Plan 是 L 执行器的输入草案,本身不含 digest/approval/operationId,禁止未知字段。
|
|
9
|
+
//
|
|
10
|
+
// 实现独立性:本文件按契约独立实现 stable/digest/schema 校验,只 import node:crypto,
|
|
11
|
+
// 不 import 任何冻结 src 文件、也不 import 其他槽位(J/L)尚未合入的模块。
|
|
12
|
+
// 少数标识符规则(scopeId / spark id / topic key / operationId)按既有冻结实现的
|
|
13
|
+
// 同一规则在本文件内镜像实现,仅作输入校验,不改变其语义。
|
|
14
|
+
//
|
|
15
|
+
// 错误码统一为 Error.code:INVALID_INPUT / REVISION_CONFLICT / NOT_FOUND /
|
|
16
|
+
// INVALID_STATE / UNSUPPORTED(本模块不产生 APPROVAL_REQUIRED;执行授权属于 L)。
|
|
17
|
+
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// 基础工具:错误 / 比较 / 协议 JSON / stable / digest / 克隆
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
function fail(code, message, details) {
|
|
25
|
+
const err = new Error(message);
|
|
26
|
+
err.code = code;
|
|
27
|
+
if (details !== undefined) err.details = details;
|
|
28
|
+
throw err;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// UTF-16 二进制比较:与平台 locale 无关(契约 §1)
|
|
32
|
+
const byCodepoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
33
|
+
|
|
34
|
+
const OBJECT_PROTO = Object.prototype;
|
|
35
|
+
const RESERVED_JSON_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
36
|
+
|
|
37
|
+
function isPlainObject(value) {
|
|
38
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
39
|
+
const proto = Object.getPrototypeOf(value);
|
|
40
|
+
return proto === OBJECT_PROTO || proto === null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 协议 JSON 校验:undefined / function / symbol / bigint / NaN / Infinity /
|
|
45
|
+
* 循环引用 / 稀疏数组孔洞 / 类实例 / 孤立代理码元字符串一律拒绝(契约 §1)。
|
|
46
|
+
* 通过后才允许进入 stable()/digest()/deepClone()。
|
|
47
|
+
*/
|
|
48
|
+
function assertProtocolJson(value, where, ancestors = new Set()) {
|
|
49
|
+
if (value === null) return;
|
|
50
|
+
const type = typeof value;
|
|
51
|
+
if (type === 'string') {
|
|
52
|
+
if (!value.isWellFormed()) {
|
|
53
|
+
fail('INVALID_INPUT', `${where} 含孤立代理码元,不是无损 UTF-8 文本`);
|
|
54
|
+
}
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (type === 'number') {
|
|
58
|
+
if (!Number.isFinite(value)) {
|
|
59
|
+
fail('INVALID_INPUT', `${where} 含 NaN/Infinity,不属于协议 JSON`);
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (type === 'boolean') return;
|
|
64
|
+
if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint') {
|
|
65
|
+
fail('INVALID_INPUT', `${where} 含 ${type} 值,不属于协议 JSON`);
|
|
66
|
+
}
|
|
67
|
+
// typeof === 'object'
|
|
68
|
+
if (ancestors.has(value)) fail('INVALID_INPUT', `${where} 含循环引用`);
|
|
69
|
+
ancestors.add(value);
|
|
70
|
+
try {
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
73
|
+
if (!Object.hasOwn(value, i)) {
|
|
74
|
+
fail('INVALID_INPUT', `${where}[${i}] 是稀疏数组孔洞,不属于协议 JSON`);
|
|
75
|
+
}
|
|
76
|
+
assertProtocolJson(value[i], `${where}[${i}]`, ancestors);
|
|
77
|
+
}
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!isPlainObject(value)) {
|
|
81
|
+
fail('INVALID_INPUT', `${where} 必须是普通对象或数组(拒绝类实例等非 JSON 值)`);
|
|
82
|
+
}
|
|
83
|
+
for (const key of Object.keys(value)) {
|
|
84
|
+
// 键与值同属协议文本(§9/§11):对象键同样必须是无损 UTF-8。
|
|
85
|
+
// JSON.stringify 会把孤立代理码元转义成 "\ud800" 文本,掩盖有损事实,
|
|
86
|
+
// 故对键显式校验(a1 反例 K-2);合法非 ASCII 键与配对代理键照常接受。
|
|
87
|
+
if (!key.isWellFormed()) {
|
|
88
|
+
fail('INVALID_INPUT', `${where} 的对象键 ${JSON.stringify(key)} 含孤立代理码元,不是无损 UTF-8 文本`);
|
|
89
|
+
}
|
|
90
|
+
assertProtocolJson(value[key], `${where}.${key === '' ? '""' : key}`, ancestors);
|
|
91
|
+
}
|
|
92
|
+
} finally {
|
|
93
|
+
ancestors.delete(value);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** stable(value):递归按 UTF-16 序排序普通对象键后的 JSON 文本;数组顺序保持(契约 §1)。 */
|
|
98
|
+
function stable(value) {
|
|
99
|
+
return JSON.stringify(value, function canonical(_key, v) {
|
|
100
|
+
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
|
|
101
|
+
return Object.fromEntries(Object.keys(v).sort(byCodepoint).map((k) => [k, v[k]]));
|
|
102
|
+
}
|
|
103
|
+
return v;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** digest = SHA256(UTF8(stable(value))),小写 64 hex。 */
|
|
108
|
+
function digest(value) {
|
|
109
|
+
return createHash('sha256').update(Buffer.from(stable(value), 'utf8')).digest('hex');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 深克隆:仅对已通过协议 JSON 校验的值调用(JSON 序列化无损失,且不泄露内部引用)。 */
|
|
113
|
+
const deepClone = (value) => JSON.parse(JSON.stringify(value));
|
|
114
|
+
|
|
115
|
+
// operationId -> operation 记录的安全字典(a1 反例 K-1):
|
|
116
|
+
// `constructor`/`toString`/`hasOwnProperty` 等继承属性名是合法 operationId,
|
|
117
|
+
// 普通对象上直接索引会把它们误读为历史账项;null 原型字典 + own-property
|
|
118
|
+
// 查找让任何键都只是普通数据键(`__proto__` 形态也不触发原型 setter,
|
|
119
|
+
// 防止原型污染/账项丢失)。写入、克隆、快照与恢复全程保持该语义。
|
|
120
|
+
function newOperationRegistry() {
|
|
121
|
+
return Object.create(null);
|
|
122
|
+
}
|
|
123
|
+
function lookupOperation(operations, operationId) {
|
|
124
|
+
return Object.hasOwn(operations, operationId) ? operations[operationId] : undefined;
|
|
125
|
+
}
|
|
126
|
+
/** operations 克隆:逐条深克隆并保持安全字典(null 原型),不泄露内部引用。 */
|
|
127
|
+
function cloneOperations(operations) {
|
|
128
|
+
const out = newOperationRegistry();
|
|
129
|
+
for (const [operationId, entry] of Object.entries(operations)) {
|
|
130
|
+
out[operationId] = deepClone(entry);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 断言 plain object 且键集合恰好为 expected(缺失/未知均拒绝)。 */
|
|
136
|
+
function assertExactKeys(obj, expected, where) {
|
|
137
|
+
if (!isPlainObject(obj)) {
|
|
138
|
+
fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
139
|
+
}
|
|
140
|
+
for (const key of expected) {
|
|
141
|
+
if (!Object.hasOwn(obj, key)) {
|
|
142
|
+
fail('INVALID_INPUT', `${where} 缺少必填字段 "${key}"`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (const key of Object.keys(obj)) {
|
|
146
|
+
if (!expected.includes(key)) {
|
|
147
|
+
fail('INVALID_INPUT', `${where} 含未知字段 "${key}"(允许:${expected.join('/')})`, { key });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// 标识符规则(镜像既有冻结实现的同一规则,仅用于输入校验)
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
const WINDOWS_RESERVED = new Set([
|
|
157
|
+
'CON', 'PRN', 'AUX', 'NUL',
|
|
158
|
+
'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
|
|
159
|
+
'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9',
|
|
160
|
+
]);
|
|
161
|
+
|
|
162
|
+
/** scopeId:非空、≤128 UTF-16、无首尾空白、无控制字符、无孤立代理码元(镜像 core/topics.mjs)。 */
|
|
163
|
+
function validateScopeIdLocal(value, name = 'scopeId') {
|
|
164
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
165
|
+
fail('INVALID_INPUT', `${name} 必须是非空字符串`);
|
|
166
|
+
}
|
|
167
|
+
if (value.length > 128) {
|
|
168
|
+
fail('INVALID_INPUT', `${name} 不得超过 128 UTF-16(实际 ${value.length})`);
|
|
169
|
+
}
|
|
170
|
+
if (value !== value.trim()) {
|
|
171
|
+
fail('INVALID_INPUT', `${name} 不得含首尾空白`);
|
|
172
|
+
}
|
|
173
|
+
for (const ch of value) {
|
|
174
|
+
const cp = ch.codePointAt(0);
|
|
175
|
+
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
176
|
+
fail('INVALID_INPUT', `${name} 不得含孤立代理码元`);
|
|
177
|
+
}
|
|
178
|
+
if (cp <= 0x1f || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)) {
|
|
179
|
+
fail('INVALID_INPUT', `${name} 不得含控制字符`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return value;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** spark 卡 id:≤64 UTF-16、字母数字开头、仅 [A-Za-z0-9._-]、非保留名(镜像 sparks/store.mjs)。 */
|
|
186
|
+
function validateSparkIdLocal(id, field = 'id') {
|
|
187
|
+
if (typeof id !== 'string' || id.length === 0) {
|
|
188
|
+
fail('INVALID_INPUT', `${field} 必须是非空字符串`);
|
|
189
|
+
}
|
|
190
|
+
if (id.length > 64) {
|
|
191
|
+
fail('INVALID_INPUT', `${field} 超过 64 UTF-16(实际 ${id.length})`);
|
|
192
|
+
}
|
|
193
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) {
|
|
194
|
+
fail('INVALID_INPUT', `${field} 只允许字母/数字/点/下划线/连字符且以字母数字开头`);
|
|
195
|
+
}
|
|
196
|
+
if (id.endsWith('.')) {
|
|
197
|
+
fail('INVALID_INPUT', `${field} 不得以点结尾`);
|
|
198
|
+
}
|
|
199
|
+
if (RESERVED_JSON_KEYS.has(id)) {
|
|
200
|
+
fail('INVALID_INPUT', `${field} 与对象键保留名冲突`);
|
|
201
|
+
}
|
|
202
|
+
const stem = id.replace(/\.[A-Za-z0-9_-]+$/, '').toUpperCase();
|
|
203
|
+
if (WINDOWS_RESERVED.has(stem)) {
|
|
204
|
+
fail('INVALID_INPUT', `${field} 与 Windows 保留设备名冲突`);
|
|
205
|
+
}
|
|
206
|
+
return id;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** topic key:跨平台文件名安全规则(镜像 core/keys.mjs)。 */
|
|
210
|
+
function validateTopicKeyLocal(key, field = 'topic.key') {
|
|
211
|
+
if (typeof key !== 'string' || key.length === 0) {
|
|
212
|
+
fail('INVALID_INPUT', `${field} 必须是非空字符串`);
|
|
213
|
+
}
|
|
214
|
+
if (key.length > 128) {
|
|
215
|
+
fail('INVALID_INPUT', `${field} 不得超过 128 UTF-16(实际 ${key.length})`);
|
|
216
|
+
}
|
|
217
|
+
const forbidden = new Set([...'<>:"/\\|?*']);
|
|
218
|
+
for (const ch of key) {
|
|
219
|
+
const cp = ch.codePointAt(0);
|
|
220
|
+
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
221
|
+
fail('INVALID_INPUT', `${field} 不得含孤立代理码元`);
|
|
222
|
+
}
|
|
223
|
+
if (cp <= 0x1f || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)) {
|
|
224
|
+
fail('INVALID_INPUT', `${field} 不得含控制字符`);
|
|
225
|
+
}
|
|
226
|
+
if (forbidden.has(ch)) {
|
|
227
|
+
fail('INVALID_INPUT', `${field} 含非法文件名字符 "${ch}"`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (/^\.+$/.test(key)) fail('INVALID_INPUT', `${field} 不得只由点组成`);
|
|
231
|
+
if (key.startsWith(' ')) fail('INVALID_INPUT', `${field} 不得以空格开头`);
|
|
232
|
+
if (key.endsWith(' ') || key.endsWith('.')) {
|
|
233
|
+
fail('INVALID_INPUT', `${field} 不得以空格或点结尾`);
|
|
234
|
+
}
|
|
235
|
+
const firstSegment = key.split('.')[0].replace(/[. ]+$/, '').toUpperCase();
|
|
236
|
+
if (WINDOWS_RESERVED.has(firstSegment)) {
|
|
237
|
+
fail('INVALID_INPUT', `${field} 与 Windows 保留设备名冲突`);
|
|
238
|
+
}
|
|
239
|
+
if (key.toLowerCase() === 'core' || key.toLowerCase() === 'core.md') {
|
|
240
|
+
fail('INVALID_INPUT', `${field} 与 Shiori 保留别名 "core" 冲突`);
|
|
241
|
+
}
|
|
242
|
+
return key;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** operationId:≤128 UTF-16、字母数字开头、仅 [A-Za-z0-9._-](镜像 storage/paths.mjs)。 */
|
|
246
|
+
function validateOperationIdLocal(operationId) {
|
|
247
|
+
if (typeof operationId !== 'string' || operationId.length === 0) {
|
|
248
|
+
fail('INVALID_INPUT', 'operationId 必须是非空字符串');
|
|
249
|
+
}
|
|
250
|
+
if (operationId.length > 128) {
|
|
251
|
+
fail('INVALID_INPUT', `operationId 超过 128 UTF-16(实际 ${operationId.length})`);
|
|
252
|
+
}
|
|
253
|
+
if (operationId !== operationId.trim()) {
|
|
254
|
+
fail('INVALID_INPUT', 'operationId 不得含首尾空白');
|
|
255
|
+
}
|
|
256
|
+
if (/[/\\:]/.test(operationId) || operationId === '.' || operationId === '..') {
|
|
257
|
+
fail('INVALID_INPUT', 'operationId 含非法字符');
|
|
258
|
+
}
|
|
259
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(operationId)) {
|
|
260
|
+
fail('INVALID_INPUT', 'operationId 只允许字母/数字/点/下划线/连字符且以字母数字开头');
|
|
261
|
+
}
|
|
262
|
+
const stem = operationId.replace(/\.[A-Za-z0-9_-]+$/, '').toUpperCase();
|
|
263
|
+
if (WINDOWS_RESERVED.has(stem)) {
|
|
264
|
+
fail('INVALID_INPUT', 'operationId 与 Windows 保留设备名冲突');
|
|
265
|
+
}
|
|
266
|
+
return operationId;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
// 候选(Candidate)校验 —— 与 J 槽契约同形,K 侧重验防篡改
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
const CANDIDATE_KINDS = new Set(['isolated', 'link', 'cluster']);
|
|
274
|
+
|
|
275
|
+
/** SourceRef 列表:{id,revision} 精确形状、revision>=1、id 唯一且按 UTF-16 升序(契约 §1)。 */
|
|
276
|
+
function validateSourceRefs(sources, where) {
|
|
277
|
+
if (!Array.isArray(sources) || sources.length === 0) {
|
|
278
|
+
fail('INVALID_INPUT', `${where} 必须是非空 SourceRef 数组`);
|
|
279
|
+
}
|
|
280
|
+
const seen = new Set();
|
|
281
|
+
let prev = null;
|
|
282
|
+
for (let i = 0; i < sources.length; i += 1) {
|
|
283
|
+
const ref = sources[i];
|
|
284
|
+
assertExactKeys(ref, ['id', 'revision'], `${where}[${i}]`);
|
|
285
|
+
validateSparkIdLocal(ref.id, `${where}[${i}].id`);
|
|
286
|
+
if (!Number.isInteger(ref.revision) || ref.revision < 1) {
|
|
287
|
+
fail('INVALID_INPUT', `${where}[${i}].revision 必须是 >=1 的整数`);
|
|
288
|
+
}
|
|
289
|
+
if (seen.has(ref.id)) {
|
|
290
|
+
fail('INVALID_INPUT', `${where} 存在重复 id "${ref.id}"`);
|
|
291
|
+
}
|
|
292
|
+
seen.add(ref.id);
|
|
293
|
+
if (prev !== null && byCodepoint(prev, ref.id) >= 0) {
|
|
294
|
+
fail('INVALID_INPUT', `${where} 必须按 id 的 UTF-16 序升序排列("${ref.id}" 之前应为更大 id)`);
|
|
295
|
+
}
|
|
296
|
+
prev = ref.id;
|
|
297
|
+
}
|
|
298
|
+
return sources;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 完整候选校验:形状 / kind / scope 一致 / sources 规范化 / 证据协议 JSON,
|
|
303
|
+
* 并重算 id=digest({kind,scopeId,sources,evidence}) 防候选篡改(契约 §3「所有candidate重新核验id与scope」)。
|
|
304
|
+
*/
|
|
305
|
+
function validateCandidate(candidate, expectedScopeId, where) {
|
|
306
|
+
assertProtocolJson(candidate, where);
|
|
307
|
+
assertExactKeys(candidate, ['id', 'kind', 'scopeId', 'sources', 'evidence'], where);
|
|
308
|
+
if (!CANDIDATE_KINDS.has(candidate.kind)) {
|
|
309
|
+
fail('INVALID_INPUT', `${where}.kind 必须是 isolated/link/cluster(得到 ${JSON.stringify(candidate.kind)})`);
|
|
310
|
+
}
|
|
311
|
+
if (candidate.scopeId !== expectedScopeId) {
|
|
312
|
+
fail('INVALID_INPUT', `${where}.scopeId 与队列 scope 不一致,跨 scope 候选拒绝`, {
|
|
313
|
+
candidateScopeId: candidate.scopeId, queueScopeId: expectedScopeId,
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
validateSourceRefs(candidate.sources, `${where}.sources`);
|
|
317
|
+
if (!isPlainObject(candidate.evidence)) {
|
|
318
|
+
fail('INVALID_INPUT', `${where}.evidence 必须是对象`);
|
|
319
|
+
}
|
|
320
|
+
if (typeof candidate.id !== 'string' || !/^[0-9a-f]{64}$/.test(candidate.id)) {
|
|
321
|
+
fail('INVALID_INPUT', `${where}.id 必须是小写 64 位 hex`);
|
|
322
|
+
}
|
|
323
|
+
const recomputed = digest({
|
|
324
|
+
kind: candidate.kind, scopeId: candidate.scopeId,
|
|
325
|
+
sources: candidate.sources, evidence: candidate.evidence,
|
|
326
|
+
});
|
|
327
|
+
if (recomputed !== candidate.id) {
|
|
328
|
+
fail('INVALID_INPUT', `${where}.id 与 digest({kind,scopeId,sources,evidence}) 不一致,候选疑似被篡改`, {
|
|
329
|
+
declaredId: candidate.id, recomputedId: recomputed,
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
return candidate;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ---------------------------------------------------------------------------
|
|
336
|
+
// createCandidateQueue
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
//
|
|
339
|
+
// 快照编码(K 文档声明,恢复时严格校验):
|
|
340
|
+
// snapshot = { version:1, scopeId, revision, items, operations }
|
|
341
|
+
// items[i] = { candidate, status: 'pending'|'reviewed'|'dismissed' }(按入队顺序)
|
|
342
|
+
// operations[operationId] = { kind:'enqueue'|'review', fingerprint:64hex,
|
|
343
|
+
// request:{...原请求载荷}, result:{version:1,scopeId,revision,items} }
|
|
344
|
+
// result 是不含 operations 的业务快照(避免递归指数膨胀,契约 §5);request 被保留
|
|
345
|
+
// 供恢复时从空队列做确定性全量重放:重放结果必须与 items/revision 完全一致,
|
|
346
|
+
// 因此顶层 revision 不可被单独信任。重放命中幂等时返回「首次业务结果 + 当前 operations 克隆」。
|
|
347
|
+
// operations 字典在内存与快照输出中均为 null 原型安全字典:键读取一律按
|
|
348
|
+
// own-property 语义(`constructor`/`toString` 等继承名是合法 operationId,
|
|
349
|
+
// 不与 Object.prototype 属性混淆;`__proto__` 形态不触发原型 setter)。
|
|
350
|
+
|
|
351
|
+
const ITEM_STATUSES = new Set(['pending', 'reviewed', 'dismissed']);
|
|
352
|
+
const OP_KINDS = new Set(['enqueue', 'review', 'converge']);
|
|
353
|
+
|
|
354
|
+
function businessSnapshotOf(state) {
|
|
355
|
+
return {
|
|
356
|
+
version: 1,
|
|
357
|
+
scopeId: state.scopeId,
|
|
358
|
+
revision: state.revision,
|
|
359
|
+
items: deepClone(state.items),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function fullSnapshotOf(state) {
|
|
364
|
+
return { ...businessSnapshotOf(state), operations: cloneOperations(state.operations) };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** enqueue 业务逻辑(输入已校验、已克隆):相同 id 相同 payload 去重不重复入队。 */
|
|
368
|
+
function applyEnqueue(state, candidates) {
|
|
369
|
+
for (const candidate of candidates) {
|
|
370
|
+
const existing = state.items.find((item) => item.candidate.id === candidate.id);
|
|
371
|
+
if (existing === undefined) {
|
|
372
|
+
state.items.push({ candidate, status: 'pending' });
|
|
373
|
+
} else if (stable(existing.candidate) !== stable(candidate)) {
|
|
374
|
+
// id 经 digest 核验后理论上不可达;保留为对损坏状态的防御。
|
|
375
|
+
fail('INVALID_STATE', `队列内已存在同 id 不同内容的候选 "${candidate.id}",疑似状态损坏`, {
|
|
376
|
+
candidateId: candidate.id,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** review 业务逻辑(输入已校验):只有 pending 可 review。 */
|
|
383
|
+
function applyReview(state, candidateId, decision) {
|
|
384
|
+
const item = state.items.find((entry) => entry.candidate.id === candidateId);
|
|
385
|
+
if (item === undefined) {
|
|
386
|
+
fail('NOT_FOUND', `候选 "${candidateId}" 不在队列中`, { candidateId });
|
|
387
|
+
}
|
|
388
|
+
if (item.status !== 'pending') {
|
|
389
|
+
fail('INVALID_STATE', `候选 "${candidateId}" 状态为 ${item.status},只有 pending 可以 review`, {
|
|
390
|
+
candidateId, status: item.status,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
item.status = decision;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* converge 业务逻辑(输入已校验、已克隆;P-A 队列收敛):
|
|
398
|
+
* 以本次分析派生的候选集为准——仍在场的候选保留既有 status(reviewed 不因
|
|
399
|
+
* 重新分析退回 pending),新出现的候选以 pending 追加,本次不再出现的候选
|
|
400
|
+
* (源卡已 merged/archived 或派生条件消失)从队列移除。确定性:给定重放到的
|
|
401
|
+
* 中间状态与同一候选集,产出唯一终态。
|
|
402
|
+
*/
|
|
403
|
+
function applyConverge(state, candidates, keepAbsentIds = null) {
|
|
404
|
+
const currentIds = new Set(candidates.map((candidate) => candidate.id));
|
|
405
|
+
// 截断保护(P-A 残留):分析候选达到 limit 上限时,"不在本次候选集"不再
|
|
406
|
+
// 等价于"失效"——keepAbsentIds 列出的既有队列项按原 status 保留。
|
|
407
|
+
const keepIds = keepAbsentIds === null ? null : new Set(keepAbsentIds);
|
|
408
|
+
const kept = [];
|
|
409
|
+
const keptIds = new Set();
|
|
410
|
+
for (const item of state.items) {
|
|
411
|
+
if (currentIds.has(item.candidate.id) || (keepIds !== null && keepIds.has(item.candidate.id))) {
|
|
412
|
+
kept.push(item);
|
|
413
|
+
keptIds.add(item.candidate.id);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
for (const candidate of candidates) {
|
|
417
|
+
if (!keptIds.has(candidate.id)) {
|
|
418
|
+
kept.push({ candidate, status: 'pending' });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
state.items = kept;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** 校验 opts 形状并返回规范化值;optionalKeys 中的键可缺席,其余未知键拒绝。 */
|
|
425
|
+
function readQueueOpts(opts, expectedKeys, method, optionalKeys = []) {
|
|
426
|
+
if (!isPlainObject(opts)) fail('INVALID_INPUT', `${method} opts 必须是普通对象`);
|
|
427
|
+
const allowed = [...expectedKeys, ...optionalKeys];
|
|
428
|
+
for (const key of expectedKeys) {
|
|
429
|
+
if (!Object.hasOwn(opts, key)) fail('INVALID_INPUT', `${method} opts 缺少必填字段 "${key}"`);
|
|
430
|
+
}
|
|
431
|
+
for (const key of Object.keys(opts)) {
|
|
432
|
+
if (!allowed.includes(key)) {
|
|
433
|
+
fail('INVALID_INPUT', `${method} opts 含未知字段 "${key}"(允许:${allowed.join('/')})`, { key });
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (!Number.isInteger(opts.expectedRevision) || opts.expectedRevision < 0) {
|
|
437
|
+
fail('INVALID_INPUT', `${method} opts.expectedRevision 必须是 >=0 的整数`);
|
|
438
|
+
}
|
|
439
|
+
validateOperationIdLocal(opts.operationId);
|
|
440
|
+
return opts;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 校验一份业务快照(items/revision),用于 operations[].result 与恢复路径。 */
|
|
444
|
+
function validateBusinessSnapshot(value, scopeId, where) {
|
|
445
|
+
assertExactKeys(value, ['version', 'scopeId', 'revision', 'items'], where);
|
|
446
|
+
if (value.version !== 1) fail('INVALID_INPUT', `${where}.version 必须是 1`);
|
|
447
|
+
if (value.scopeId !== scopeId) {
|
|
448
|
+
fail('INVALID_INPUT', `${where}.scopeId 与队列 scope 不一致`);
|
|
449
|
+
}
|
|
450
|
+
if (!Number.isInteger(value.revision) || value.revision < 0) {
|
|
451
|
+
fail('INVALID_INPUT', `${where}.revision 必须是 >=0 的整数`);
|
|
452
|
+
}
|
|
453
|
+
validateItems(value.items, scopeId, `${where}.items`);
|
|
454
|
+
return value;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function validateItems(items, scopeId, where) {
|
|
458
|
+
if (!Array.isArray(items)) fail('INVALID_INPUT', `${where} 必须是数组`);
|
|
459
|
+
const seen = new Set();
|
|
460
|
+
for (let i = 0; i < items.length; i += 1) {
|
|
461
|
+
const item = items[i];
|
|
462
|
+
assertExactKeys(item, ['candidate', 'status'], `${where}[${i}]`);
|
|
463
|
+
if (!ITEM_STATUSES.has(item.status)) {
|
|
464
|
+
fail('INVALID_INPUT', `${where}[${i}].status 必须是 pending/reviewed/dismissed`);
|
|
465
|
+
}
|
|
466
|
+
validateCandidate(item.candidate, scopeId, `${where}[${i}].candidate`);
|
|
467
|
+
if (seen.has(item.candidate.id)) {
|
|
468
|
+
fail('INVALID_INPUT', `${where} 存在重复候选 id "${item.candidate.id}"`);
|
|
469
|
+
}
|
|
470
|
+
seen.add(item.candidate.id);
|
|
471
|
+
}
|
|
472
|
+
return items;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** 校验单条 operation 记录(含 fingerprint 与 request 的一致性)。 */
|
|
476
|
+
function validateOperationEntry(entry, operationId, scopeId, where) {
|
|
477
|
+
assertExactKeys(entry, ['kind', 'fingerprint', 'request', 'result'], where);
|
|
478
|
+
if (!OP_KINDS.has(entry.kind)) {
|
|
479
|
+
fail('INVALID_INPUT', `${where}.kind 必须是 enqueue/review/converge`);
|
|
480
|
+
}
|
|
481
|
+
if (typeof entry.fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(entry.fingerprint)) {
|
|
482
|
+
fail('INVALID_INPUT', `${where}.fingerprint 必须是小写 64 位 hex`);
|
|
483
|
+
}
|
|
484
|
+
const request = entry.request;
|
|
485
|
+
if (entry.kind === 'enqueue') {
|
|
486
|
+
assertExactKeys(request, ['kind', 'candidates'], `${where}.request`);
|
|
487
|
+
if (request.kind !== 'enqueue') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
488
|
+
if (!Array.isArray(request.candidates) || request.candidates.length === 0) {
|
|
489
|
+
fail('INVALID_INPUT', `${where}.request.candidates 必须是非空数组`);
|
|
490
|
+
}
|
|
491
|
+
const seen = new Set();
|
|
492
|
+
for (let i = 0; i < request.candidates.length; i += 1) {
|
|
493
|
+
validateCandidate(request.candidates[i], scopeId, `${where}.request.candidates[${i}]`);
|
|
494
|
+
const cid = request.candidates[i].id;
|
|
495
|
+
if (seen.has(cid)) fail('INVALID_INPUT', `${where}.request.candidates 存在重复 id "${cid}"`);
|
|
496
|
+
seen.add(cid);
|
|
497
|
+
}
|
|
498
|
+
} else if (entry.kind === 'converge') {
|
|
499
|
+
// keepAbsentIds 可选(旧快照无此键;截断保护引入)。未知键仍拒绝。
|
|
500
|
+
const requestKeys = Object.keys(request);
|
|
501
|
+
for (const key of requestKeys) {
|
|
502
|
+
if (key !== 'kind' && key !== 'candidates' && key !== 'keepAbsentIds') {
|
|
503
|
+
fail('INVALID_INPUT', `${where}.request 含未知字段 "${key}"(允许:kind/candidates/keepAbsentIds)`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (!requestKeys.includes('kind')) fail('INVALID_INPUT', `${where}.request 缺少必填字段 "kind"`);
|
|
507
|
+
if (!requestKeys.includes('candidates')) fail('INVALID_INPUT', `${where}.request 缺少必填字段 "candidates"`);
|
|
508
|
+
if (request.kind !== 'converge') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
509
|
+
// 收敛允许空数组(本次分析无候选 = 清空失效候选)。
|
|
510
|
+
if (!Array.isArray(request.candidates)) {
|
|
511
|
+
fail('INVALID_INPUT', `${where}.request.candidates 必须是数组(可为空)`);
|
|
512
|
+
}
|
|
513
|
+
const seen = new Set();
|
|
514
|
+
for (let i = 0; i < request.candidates.length; i += 1) {
|
|
515
|
+
validateCandidate(request.candidates[i], scopeId, `${where}.request.candidates[${i}]`);
|
|
516
|
+
const cid = request.candidates[i].id;
|
|
517
|
+
if (seen.has(cid)) fail('INVALID_INPUT', `${where}.request.candidates 存在重复 id "${cid}"`);
|
|
518
|
+
seen.add(cid);
|
|
519
|
+
}
|
|
520
|
+
if (requestKeys.includes('keepAbsentIds')) {
|
|
521
|
+
if (!Array.isArray(request.keepAbsentIds)) {
|
|
522
|
+
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须是数组`);
|
|
523
|
+
}
|
|
524
|
+
const seenKeep = new Set();
|
|
525
|
+
for (const id of request.keepAbsentIds) {
|
|
526
|
+
if (typeof id !== 'string' || !/^[0-9a-f]{64}$/.test(id)) {
|
|
527
|
+
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须全是小写 64 位 hex 候选 id`);
|
|
528
|
+
}
|
|
529
|
+
if (seenKeep.has(id)) fail('INVALID_INPUT', `${where}.request.keepAbsentIds 存在重复 id "${id}"`);
|
|
530
|
+
seenKeep.add(id);
|
|
531
|
+
}
|
|
532
|
+
if (JSON.stringify([...seenKeep].sort(byCodepoint)) !== JSON.stringify(request.keepAbsentIds)) {
|
|
533
|
+
fail('INVALID_INPUT', `${where}.request.keepAbsentIds 必须按码点升序去重存放`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
} else {
|
|
537
|
+
assertExactKeys(request, ['kind', 'candidateId', 'decision'], `${where}.request`);
|
|
538
|
+
if (request.kind !== 'review') fail('INVALID_INPUT', `${where}.request.kind 与 entry.kind 不一致`);
|
|
539
|
+
if (typeof request.candidateId !== 'string' || !/^[0-9a-f]{64}$/.test(request.candidateId)) {
|
|
540
|
+
fail('INVALID_INPUT', `${where}.request.candidateId 必须是小写 64 位 hex`);
|
|
541
|
+
}
|
|
542
|
+
if (request.decision !== 'reviewed' && request.decision !== 'dismissed') {
|
|
543
|
+
fail('INVALID_INPUT', `${where}.request.decision 必须是 reviewed/dismissed`);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (digest(request) !== entry.fingerprint) {
|
|
547
|
+
fail('INVALID_INPUT', `${where}.fingerprint 与 request 内容不匹配,操作记录疑似被篡改`);
|
|
548
|
+
}
|
|
549
|
+
validateBusinessSnapshot(entry.result, scopeId, `${where}.result`);
|
|
550
|
+
return entry;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 从快照恢复:结构校验 + 从空队列按 result.revision 升序确定性重放全部 operations,
|
|
555
|
+
* 每一步的中间业务快照必须与记录的 result 完全一致,最终状态必须与顶层
|
|
556
|
+
* items/revision 完全一致 —— 顶层 revision 不被单独信任。
|
|
557
|
+
*/
|
|
558
|
+
function restoreState(snapshot, scopeId) {
|
|
559
|
+
assertProtocolJson(snapshot, 'snapshot');
|
|
560
|
+
assertExactKeys(snapshot, ['version', 'scopeId', 'revision', 'items', 'operations'], 'snapshot');
|
|
561
|
+
if (snapshot.version !== 1) fail('INVALID_INPUT', 'snapshot.version 必须是 1');
|
|
562
|
+
if (snapshot.scopeId !== scopeId) {
|
|
563
|
+
fail('INVALID_INPUT', 'snapshot.scopeId 与工厂 scopeId 不一致,拒绝恢复');
|
|
564
|
+
}
|
|
565
|
+
if (!Number.isInteger(snapshot.revision) || snapshot.revision < 0) {
|
|
566
|
+
fail('INVALID_INPUT', 'snapshot.revision 必须是 >=0 的整数');
|
|
567
|
+
}
|
|
568
|
+
validateItems(snapshot.items, scopeId, 'snapshot.items');
|
|
569
|
+
if (!isPlainObject(snapshot.operations)) {
|
|
570
|
+
fail('INVALID_INPUT', 'snapshot.operations 必须是对象');
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const entries = [];
|
|
574
|
+
for (const [operationId, entry] of Object.entries(snapshot.operations)) {
|
|
575
|
+
validateOperationIdLocal(operationId);
|
|
576
|
+
validateOperationEntry(entry, operationId, scopeId, `snapshot.operations.${operationId}`);
|
|
577
|
+
entries.push({ operationId, entry });
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// 不变量:每个成功队列事务 revision+1 并恰好记录一条 operation,
|
|
581
|
+
// 因此 operations 数必须等于顶层 revision,且各 result.revision 恰为 1..N。
|
|
582
|
+
if (entries.length !== snapshot.revision) {
|
|
583
|
+
fail('INVALID_STATE', `snapshot.revision (${snapshot.revision}) 与 operations 条数 (${entries.length}) 不一致,拒绝恢复`);
|
|
584
|
+
}
|
|
585
|
+
const revisions = entries.map(({ entry }) => entry.result.revision).sort((a, b) => a - b);
|
|
586
|
+
for (let i = 0; i < revisions.length; i += 1) {
|
|
587
|
+
if (revisions[i] !== i + 1) {
|
|
588
|
+
fail('INVALID_STATE', `operations 的 result.revision 必须恰好覆盖 1..${entries.length}(发现 ${revisions[i]})`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const state = { scopeId, revision: 0, items: [], operations: newOperationRegistry() };
|
|
593
|
+
entries.sort((a, b) => a.entry.result.revision - b.entry.result.revision);
|
|
594
|
+
for (const { operationId, entry } of entries) {
|
|
595
|
+
if (entry.kind === 'enqueue') {
|
|
596
|
+
applyEnqueue(state, deepClone(entry.request.candidates));
|
|
597
|
+
} else if (entry.kind === 'converge') {
|
|
598
|
+
applyConverge(state, deepClone(entry.request.candidates), entry.request.keepAbsentIds ?? null);
|
|
599
|
+
} else {
|
|
600
|
+
applyReview(state, entry.request.candidateId, entry.request.decision);
|
|
601
|
+
}
|
|
602
|
+
state.revision += 1;
|
|
603
|
+
const produced = businessSnapshotOf(state);
|
|
604
|
+
if (stable(produced) !== stable(entry.result)) {
|
|
605
|
+
fail('INVALID_STATE', `operation "${operationId}" 的重放结果与记录的 result 不一致,快照历史被篡改`, {
|
|
606
|
+
operationId,
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
state.operations[operationId] = {
|
|
610
|
+
kind: entry.kind,
|
|
611
|
+
fingerprint: entry.fingerprint,
|
|
612
|
+
request: deepClone(entry.request),
|
|
613
|
+
result: deepClone(entry.result),
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
if (state.revision !== snapshot.revision
|
|
617
|
+
|| stable(businessSnapshotOf(state)) !== stable({
|
|
618
|
+
version: 1, scopeId, revision: snapshot.revision, items: snapshot.items,
|
|
619
|
+
})) {
|
|
620
|
+
fail('INVALID_STATE', '重放终态与快照顶层 items/revision 不一致,拒绝恢复');
|
|
621
|
+
}
|
|
622
|
+
return state;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** 断言 plain object:required 必须在场,optional 可选,其余未知键拒绝。 */
|
|
626
|
+
function assertAllowedKeys(obj, required, optional, where) {
|
|
627
|
+
if (!isPlainObject(obj)) {
|
|
628
|
+
fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
629
|
+
}
|
|
630
|
+
for (const key of required) {
|
|
631
|
+
if (!Object.hasOwn(obj, key)) {
|
|
632
|
+
fail('INVALID_INPUT', `${where} 缺少必填字段 "${key}"`);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const allowed = new Set([...required, ...optional]);
|
|
636
|
+
for (const key of Object.keys(obj)) {
|
|
637
|
+
if (!allowed.has(key)) {
|
|
638
|
+
fail('INVALID_INPUT', `${where} 含未知字段 "${key}"(允许:${[...allowed].join('/')})`, { key });
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* 建立候选队列。
|
|
645
|
+
*
|
|
646
|
+
* @param {object} params
|
|
647
|
+
* @param {string} params.scopeId 显式 scope(factory-only;不从 cwd/HOME/global 猜测)
|
|
648
|
+
* @param {object} [params.snapshot] 可选快照;提供时执行严格恢复校验
|
|
649
|
+
* @returns {object} queue = { snapshot(), enqueue(), review() }
|
|
650
|
+
*/
|
|
651
|
+
export function createCandidateQueue(params) {
|
|
652
|
+
if (!isPlainObject(params)) {
|
|
653
|
+
fail('INVALID_INPUT', 'createCandidateQueue 参数必须是对象');
|
|
654
|
+
}
|
|
655
|
+
assertAllowedKeys(params, ['scopeId'], ['snapshot'], 'createCandidateQueue 参数');
|
|
656
|
+
const { scopeId, snapshot } = params;
|
|
657
|
+
validateScopeIdLocal(scopeId);
|
|
658
|
+
const state = snapshot === undefined
|
|
659
|
+
? { scopeId, revision: 0, items: [], operations: newOperationRegistry() }
|
|
660
|
+
: restoreState(snapshot, scopeId);
|
|
661
|
+
|
|
662
|
+
const queue = {
|
|
663
|
+
/** 当前完整快照的深克隆(修改返回值不影响队列内部状态)。 */
|
|
664
|
+
snapshot() {
|
|
665
|
+
return fullSnapshotOf(state);
|
|
666
|
+
},
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* 入队:幂等按 operationId 先于 CAS(重放不受 expectedRevision 约束);
|
|
670
|
+
* 同 operationId 异 payload 拒绝;相同 id 相同 payload 不重复入队,
|
|
671
|
+
* 即便去重 no-op 也算一次队列事务(revision+1)。
|
|
672
|
+
*/
|
|
673
|
+
enqueue(candidates, opts) {
|
|
674
|
+
if (!Array.isArray(candidates) || candidates.length === 0) {
|
|
675
|
+
fail('INVALID_INPUT', 'enqueue 的 candidates 必须是非空数组');
|
|
676
|
+
}
|
|
677
|
+
for (let i = 0; i < candidates.length; i += 1) {
|
|
678
|
+
validateCandidate(candidates[i], scopeId, `candidates[${i}]`);
|
|
679
|
+
}
|
|
680
|
+
const batchIds = new Set();
|
|
681
|
+
for (const candidate of candidates) {
|
|
682
|
+
if (batchIds.has(candidate.id)) {
|
|
683
|
+
fail('INVALID_INPUT', `同一批 enqueue 内存在重复候选 id "${candidate.id}"`);
|
|
684
|
+
}
|
|
685
|
+
batchIds.add(candidate.id);
|
|
686
|
+
}
|
|
687
|
+
readQueueOpts(opts, ['expectedRevision', 'operationId'], 'enqueue');
|
|
688
|
+
|
|
689
|
+
const request = { kind: 'enqueue', candidates: deepClone(candidates) };
|
|
690
|
+
const fingerprint = digest(request);
|
|
691
|
+
|
|
692
|
+
// 幂等先于 CAS:同 operationId 同 payload 直接重放首次业务结果 + 当前 operations 克隆。
|
|
693
|
+
// 查找必须走 own-property(安全字典),继承属性名不得被误读为历史账项(K-1)。
|
|
694
|
+
const prior = lookupOperation(state.operations, opts.operationId);
|
|
695
|
+
if (prior !== undefined) {
|
|
696
|
+
if (prior.fingerprint !== fingerprint) {
|
|
697
|
+
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
698
|
+
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'enqueue',
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
if (opts.expectedRevision !== state.revision) {
|
|
705
|
+
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
706
|
+
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
applyEnqueue(state, request.candidates);
|
|
711
|
+
state.revision += 1;
|
|
712
|
+
state.operations[opts.operationId] = {
|
|
713
|
+
kind: 'enqueue', fingerprint, request, result: businessSnapshotOf(state),
|
|
714
|
+
};
|
|
715
|
+
return fullSnapshotOf(state);
|
|
716
|
+
},
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* 审核:只有 pending 可以 review;reviewed 是「已审阅」而非「已批准/已执行」,
|
|
720
|
+
* 不产生任何业务写入。失败(NOT_FOUND/INVALID_STATE/CAS 冲突)时队列原样。
|
|
721
|
+
*/
|
|
722
|
+
review(candidateId, opts) {
|
|
723
|
+
if (typeof candidateId !== 'string' || !/^[0-9a-f]{64}$/.test(candidateId)) {
|
|
724
|
+
fail('INVALID_INPUT', 'candidateId 必须是小写 64 位 hex(候选 id 即 digest)');
|
|
725
|
+
}
|
|
726
|
+
readQueueOpts(opts, ['decision', 'expectedRevision', 'operationId'], 'review');
|
|
727
|
+
if (opts.decision !== 'reviewed' && opts.decision !== 'dismissed') {
|
|
728
|
+
fail('INVALID_INPUT', 'review opts.decision 必须是 reviewed 或 dismissed');
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const request = { kind: 'review', candidateId, decision: opts.decision };
|
|
732
|
+
const fingerprint = digest(request);
|
|
733
|
+
|
|
734
|
+
const prior = lookupOperation(state.operations, opts.operationId);
|
|
735
|
+
if (prior !== undefined) {
|
|
736
|
+
if (prior.fingerprint !== fingerprint) {
|
|
737
|
+
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
738
|
+
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'review',
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (opts.expectedRevision !== state.revision) {
|
|
745
|
+
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
746
|
+
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
applyReview(state, candidateId, opts.decision);
|
|
751
|
+
state.revision += 1;
|
|
752
|
+
state.operations[opts.operationId] = {
|
|
753
|
+
kind: 'review', fingerprint, request, result: businessSnapshotOf(state),
|
|
754
|
+
};
|
|
755
|
+
return fullSnapshotOf(state);
|
|
756
|
+
},
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* 收敛(P-A):以本次分析派生的候选集为准对齐队列——保留在场候选的既有
|
|
760
|
+
* status(reviewed 不退回)、新候选以 pending 追加、不在场的候选移除
|
|
761
|
+
* (其源卡已 merged/archived 或派生条件消失)。candidates 允许空数组。
|
|
762
|
+
* opts.keepAbsentIds(可选,null 或 64-hex id 数组):截断保护——调用方
|
|
763
|
+
* 在候选集被 limit 截断时,把"不在候选集但源卡仍全部 active"的既有队列项
|
|
764
|
+
* 列在这里,它们按原 status 保留而非移除;未截断时传 null(缺省),
|
|
765
|
+
* "不在场 = 移除"语义不变。与 enqueue 同幂等语义:同 operationId 同
|
|
766
|
+
* payload 重放首次业务结果;即便集合无变化也记一次队列事务
|
|
767
|
+
* (revision+1),保持「operations 数 === revision」的恢复不变量与严格
|
|
768
|
+
* 幂等。keepAbsentIds 入 journal request(排序规范化),重放逐字一致。
|
|
769
|
+
*/
|
|
770
|
+
converge(candidates, opts) {
|
|
771
|
+
if (!Array.isArray(candidates)) {
|
|
772
|
+
fail('INVALID_INPUT', 'converge 的 candidates 必须是数组(可为空)');
|
|
773
|
+
}
|
|
774
|
+
for (let i = 0; i < candidates.length; i += 1) {
|
|
775
|
+
validateCandidate(candidates[i], scopeId, `candidates[${i}]`);
|
|
776
|
+
}
|
|
777
|
+
const batchIds = new Set();
|
|
778
|
+
for (const candidate of candidates) {
|
|
779
|
+
if (batchIds.has(candidate.id)) {
|
|
780
|
+
fail('INVALID_INPUT', `同一批 converge 内存在重复候选 id "${candidate.id}"`);
|
|
781
|
+
}
|
|
782
|
+
batchIds.add(candidate.id);
|
|
783
|
+
}
|
|
784
|
+
readQueueOpts(opts, ['expectedRevision', 'operationId'], 'converge', ['keepAbsentIds']);
|
|
785
|
+
let keepAbsentIds = null;
|
|
786
|
+
if (opts.keepAbsentIds !== undefined && opts.keepAbsentIds !== null) {
|
|
787
|
+
if (!Array.isArray(opts.keepAbsentIds)) {
|
|
788
|
+
fail('INVALID_INPUT', 'converge opts.keepAbsentIds 必须是数组或 null');
|
|
789
|
+
}
|
|
790
|
+
const seenKeep = new Set();
|
|
791
|
+
for (const id of opts.keepAbsentIds) {
|
|
792
|
+
if (typeof id !== 'string' || !/^[0-9a-f]{64}$/.test(id)) {
|
|
793
|
+
fail('INVALID_INPUT', 'converge opts.keepAbsentIds 必须全是小写 64 位 hex 候选 id');
|
|
794
|
+
}
|
|
795
|
+
if (seenKeep.has(id)) {
|
|
796
|
+
fail('INVALID_INPUT', `converge opts.keepAbsentIds 存在重复 id "${id}"`);
|
|
797
|
+
}
|
|
798
|
+
seenKeep.add(id);
|
|
799
|
+
}
|
|
800
|
+
keepAbsentIds = [...seenKeep].sort(byCodepoint);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const request = { kind: 'converge', candidates: deepClone(candidates) };
|
|
804
|
+
if (keepAbsentIds !== null) request.keepAbsentIds = keepAbsentIds;
|
|
805
|
+
const fingerprint = digest(request);
|
|
806
|
+
|
|
807
|
+
const prior = lookupOperation(state.operations, opts.operationId);
|
|
808
|
+
if (prior !== undefined) {
|
|
809
|
+
if (prior.fingerprint !== fingerprint) {
|
|
810
|
+
fail('INVALID_INPUT', `operationId "${opts.operationId}" 已被不同语义的请求使用,拒绝执行`, {
|
|
811
|
+
operationId: opts.operationId, previousKind: prior.kind, attemptedKind: 'converge',
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
return { ...deepClone(prior.result), operations: cloneOperations(state.operations) };
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
if (opts.expectedRevision !== state.revision) {
|
|
818
|
+
fail('REVISION_CONFLICT', `队列 revision CAS 失败(期望 ${opts.expectedRevision},当前 ${state.revision})`, {
|
|
819
|
+
expectedRevision: opts.expectedRevision, currentRevision: state.revision,
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
applyConverge(state, request.candidates, keepAbsentIds);
|
|
824
|
+
state.revision += 1;
|
|
825
|
+
state.operations[opts.operationId] = {
|
|
826
|
+
kind: 'converge', fingerprint, request, result: businessSnapshotOf(state),
|
|
827
|
+
};
|
|
828
|
+
return fullSnapshotOf(state);
|
|
829
|
+
},
|
|
830
|
+
};
|
|
831
|
+
return queue;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// ---------------------------------------------------------------------------
|
|
835
|
+
// listQueue:候选队列的展示投影(source 标题补全 / 分组与状态计数 / 可选分页)
|
|
836
|
+
// ---------------------------------------------------------------------------
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* 把队列 items(业务快照里的 {candidate,status} 列表)投影成客户端一次请求
|
|
840
|
+
* 即可渲染的列表视图:
|
|
841
|
+
* - items[i].candidate.sources[j] 在既有字段(id/revision 等)之外补 title
|
|
842
|
+
* (按 id 从 records 取卡片标题;取不到给 null;不删原字段、不改顺序);
|
|
843
|
+
* - 候选对象的既有字段(含 evidence)原样保留,只增不改;
|
|
844
|
+
* - 顶层补 groups(按候选 kind 计数)与 statusCounts(按条目 status 计数),
|
|
845
|
+
* 计数恒覆盖分页前的全量 items;
|
|
846
|
+
* - limit / offset 可选分页:缺省(都不传)时行为与不分页完全一致;
|
|
847
|
+
* total 恒为分页前的 items 总数;
|
|
848
|
+
* - records 提供时(非 undefined/null):每个条目副本补 stale 布尔(候选
|
|
849
|
+
* sources 里任一源 revision 与 records 不一致、源卡已不在 records、或
|
|
850
|
+
* ref.revision 缺失/非整数即视为过期,fail-closed),顶层补 staleCount
|
|
851
|
+
* (分页前全量 items 里 stale 为真的条数,口径同 total/groups,不受分页
|
|
852
|
+
* 影响)。records 缺省时不加 stale / staleCount,形状与旧版完全一致。
|
|
853
|
+
*
|
|
854
|
+
* 本函数是纯只读投影:不重算候选 digest(那是 createCandidateQueue /
|
|
855
|
+
* buildDraft 的职责)、不写任何状态、不产生队列事务;修改返回值不影响输入。
|
|
856
|
+
*
|
|
857
|
+
* @param {object} input
|
|
858
|
+
* @param {Array} input.items 业务快照 items({candidate,status} 数组)
|
|
859
|
+
* @param {Array} [input.records] 完整 active 卡记录(store.listActive 形状);缺省时 title 一律 null
|
|
860
|
+
* @param {number} [input.limit] 页大小(>=0 整数;缺省不截断)
|
|
861
|
+
* @param {number} [input.offset] 页起点(>=0 整数;缺省 0)
|
|
862
|
+
* @returns {{items: Array, total: number,
|
|
863
|
+
* groups: {cluster: number, link: number, isolated: number},
|
|
864
|
+
* statusCounts: {pending: number, reviewed: number, dismissed: number},
|
|
865
|
+
* staleCount?: number}}
|
|
866
|
+
*/
|
|
867
|
+
export function listQueue(input) {
|
|
868
|
+
if (!isPlainObject(input)) fail('INVALID_INPUT', 'listQueue 参数必须是对象');
|
|
869
|
+
assertAllowedKeys(input, ['items'], ['records', 'limit', 'offset'], 'listQueue 参数');
|
|
870
|
+
const { items, records } = input;
|
|
871
|
+
if (!Array.isArray(items)) fail('INVALID_INPUT', 'listQueue items 必须是数组');
|
|
872
|
+
for (let i = 0; i < items.length; i += 1) {
|
|
873
|
+
const item = items[i];
|
|
874
|
+
if (!isPlainObject(item)) fail('INVALID_INPUT', `listQueue items[${i}] 必须是普通对象`);
|
|
875
|
+
if (!isPlainObject(item.candidate)) {
|
|
876
|
+
fail('INVALID_INPUT', `listQueue items[${i}].candidate 必须是普通对象`);
|
|
877
|
+
}
|
|
878
|
+
if (!CANDIDATE_KINDS.has(item.candidate.kind)) {
|
|
879
|
+
fail('INVALID_INPUT', `listQueue items[${i}].candidate.kind 必须是 isolated/link/cluster(得到 ${JSON.stringify(item.candidate.kind)})`);
|
|
880
|
+
}
|
|
881
|
+
if (!Array.isArray(item.candidate.sources)) {
|
|
882
|
+
fail('INVALID_INPUT', `listQueue items[${i}].candidate.sources 必须是数组`);
|
|
883
|
+
}
|
|
884
|
+
for (let j = 0; j < item.candidate.sources.length; j += 1) {
|
|
885
|
+
const sourceRef = item.candidate.sources[j];
|
|
886
|
+
if (!isPlainObject(sourceRef) || typeof sourceRef.id !== 'string') {
|
|
887
|
+
fail('INVALID_INPUT', `listQueue items[${i}].candidate.sources[${j}] 必须是含字符串 id 的普通对象`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (!ITEM_STATUSES.has(item.status)) {
|
|
891
|
+
fail('INVALID_INPUT', `listQueue items[${i}].status 必须是 pending/reviewed/dismissed`);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// title 索引:只认字符串标题;同 id 重复记录取先到者(store 的 listActive
|
|
896
|
+
// 不会重复给 id,这里仅为防御,不静默覆盖)。
|
|
897
|
+
// revisions 索引:只认整数 revision(供 stale 判定);同 id 重复取先到者,
|
|
898
|
+
// 与 titlesById 的防御口径一致。
|
|
899
|
+
const titlesById = new Map();
|
|
900
|
+
const revisionsById = new Map();
|
|
901
|
+
let recordsProvided = false;
|
|
902
|
+
if (records !== undefined && records !== null) {
|
|
903
|
+
recordsProvided = true;
|
|
904
|
+
if (!Array.isArray(records)) fail('INVALID_INPUT', 'listQueue records 必须是数组');
|
|
905
|
+
for (let i = 0; i < records.length; i += 1) {
|
|
906
|
+
const record = records[i];
|
|
907
|
+
if (!isPlainObject(record) || typeof record.id !== 'string') {
|
|
908
|
+
fail('INVALID_INPUT', `listQueue records[${i}] 必须是含字符串 id 的普通对象`);
|
|
909
|
+
}
|
|
910
|
+
if (!titlesById.has(record.id) && typeof record.title === 'string' && record.title.isWellFormed()) {
|
|
911
|
+
titlesById.set(record.id, record.title);
|
|
912
|
+
}
|
|
913
|
+
if (!revisionsById.has(record.id) && Number.isInteger(record.revision)) {
|
|
914
|
+
revisionsById.set(record.id, record.revision);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const total = items.length;
|
|
920
|
+
const groups = { cluster: 0, link: 0, isolated: 0 };
|
|
921
|
+
const statusCounts = { pending: 0, reviewed: 0, dismissed: 0 };
|
|
922
|
+
for (const item of items) {
|
|
923
|
+
groups[item.candidate.kind] += 1;
|
|
924
|
+
statusCounts[item.status] += 1;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// stale:按分页前全量 items 判定(staleCount 口径同 total/groups,不受分页
|
|
928
|
+
// 影响)。fail-closed:ref.revision 缺失/非整数、源卡不在 records、或
|
|
929
|
+
// records.revision 与 ref 不严格相等,一律视为过期。
|
|
930
|
+
const itemStale = recordsProvided
|
|
931
|
+
? items.map((item) => item.candidate.sources.some((ref) => isStaleSourceRef(ref, revisionsById)))
|
|
932
|
+
: null;
|
|
933
|
+
const staleCount = recordsProvided
|
|
934
|
+
? itemStale.reduce((n, stale) => (stale ? n + 1 : n), 0)
|
|
935
|
+
: 0;
|
|
936
|
+
|
|
937
|
+
let offset = 0;
|
|
938
|
+
if (input.offset !== undefined) {
|
|
939
|
+
if (!Number.isInteger(input.offset) || input.offset < 0) {
|
|
940
|
+
fail('INVALID_INPUT', `listQueue offset 必须是 >=0 的整数(实际 ${JSON.stringify(input.offset)})`);
|
|
941
|
+
}
|
|
942
|
+
offset = input.offset;
|
|
943
|
+
}
|
|
944
|
+
let limit = total;
|
|
945
|
+
if (input.limit !== undefined) {
|
|
946
|
+
if (!Number.isInteger(input.limit) || input.limit < 0) {
|
|
947
|
+
fail('INVALID_INPUT', `listQueue limit 必须是 >=0 的整数(实际 ${JSON.stringify(input.limit)})`);
|
|
948
|
+
}
|
|
949
|
+
limit = input.limit;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const page = items.slice(offset, offset + limit).map((item, i) => {
|
|
953
|
+
const clone = deepClone(item);
|
|
954
|
+
clone.candidate.sources = clone.candidate.sources.map((ref) => ({
|
|
955
|
+
...ref,
|
|
956
|
+
title: titlesById.get(ref.id) ?? null,
|
|
957
|
+
}));
|
|
958
|
+
// stale 与 title 补全同在分页后的副本上,只增不改;records 缺省时不加该键。
|
|
959
|
+
if (recordsProvided) clone.stale = itemStale[offset + i];
|
|
960
|
+
return clone;
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
return recordsProvided
|
|
964
|
+
? { items: page, total, groups, statusCounts, staleCount }
|
|
965
|
+
: { items: page, total, groups, statusCounts };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* 单个 source ref 是否过期(fail-closed):revision 缺失/非整数、源卡不在
|
|
970
|
+
* records(revisionsById 没有该 id)、或 records.revision 与 ref.revision 不
|
|
971
|
+
* 严格相等,都算过期。
|
|
972
|
+
*/
|
|
973
|
+
function isStaleSourceRef(ref, revisionsById) {
|
|
974
|
+
if (!Number.isInteger(ref.revision)) return true;
|
|
975
|
+
const recordRevision = revisionsById.get(ref.id);
|
|
976
|
+
return recordRevision === undefined || recordRevision !== ref.revision;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// ---------------------------------------------------------------------------
|
|
980
|
+
// buildDraft:候选 + 完整 active records + proposal -> { plan, digest, diff, changedItems }
|
|
981
|
+
// ---------------------------------------------------------------------------
|
|
982
|
+
|
|
983
|
+
const PLAN_KINDS = new Set(['link', 'merge-topic', 'archive-topic']);
|
|
984
|
+
// link 草案 sources 上限:与 executor.mjs 的 LINK_SOURCES_MAX 同值(64)。
|
|
985
|
+
// 本模块按契约只 import node:crypto、不 import 其他槽位模块,故此处同值镜像;
|
|
986
|
+
// 两处的一致性由测试锁定(buildDraft 65 源与执行器 65 源双双拒绝)。
|
|
987
|
+
const LINK_SOURCES_MAX = 64;
|
|
988
|
+
// 镜像冻结 sparks/store.mjs 的 LIMITS(仅用于输入校验,保证草案可被执行器接受)
|
|
989
|
+
const CARD_LIMITS = Object.freeze({
|
|
990
|
+
titleChars: 80, summaryChars: 120, contentChars: 2000,
|
|
991
|
+
wordChars: 64, relChars: 64, triggersMax: 32, entitiesMax: 32, linksMax: 32,
|
|
992
|
+
});
|
|
993
|
+
const VITALITIES = new Set(['evergreen', 'ephemeral']);
|
|
994
|
+
const MAX_CHANGED_ITEMS = 20;
|
|
995
|
+
|
|
996
|
+
const SOURCES_MARKER = '<!-- shiori-p3-sources -->';
|
|
997
|
+
const SOURCES_CLOSE_MARKER = '<!-- /shiori-p3-sources -->';
|
|
998
|
+
const SOURCES_BLOCK_OPEN = '\n<!-- shiori-p3-sources -->\n';
|
|
999
|
+
const SOURCES_BLOCK_CLOSE = '\n<!-- /shiori-p3-sources -->\n';
|
|
1000
|
+
|
|
1001
|
+
function checkText(value, where, { min = 0, max = null }) {
|
|
1002
|
+
if (typeof value !== 'string') {
|
|
1003
|
+
fail('INVALID_INPUT', `${where} 必须是字符串`);
|
|
1004
|
+
}
|
|
1005
|
+
if (!value.isWellFormed()) {
|
|
1006
|
+
fail('INVALID_INPUT', `${where} 含孤立代理码元,不是无损 UTF-8 文本`);
|
|
1007
|
+
}
|
|
1008
|
+
if (value.length < min) {
|
|
1009
|
+
fail('INVALID_INPUT', `${where} 长度必须 >= ${min} UTF-16(实际 ${value.length})`);
|
|
1010
|
+
}
|
|
1011
|
+
if (max !== null && value.length > max) {
|
|
1012
|
+
fail('INVALID_INPUT', `${where} 长度必须 <= ${max} UTF-16(实际 ${value.length})`);
|
|
1013
|
+
}
|
|
1014
|
+
return value;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** 完整 active 卡记录校验(store.listActive 形状;记录只认 active,契约 §1)。 */
|
|
1018
|
+
function validateRecord(record, expectedScopeId, where) {
|
|
1019
|
+
assertProtocolJson(record, where);
|
|
1020
|
+
if (!isPlainObject(record)) fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
1021
|
+
for (const field of ['id', 'scopeId', 'revision', 'state', 'title', 'summary', 'content',
|
|
1022
|
+
'triggers', 'entities', 'links', 'vitality']) {
|
|
1023
|
+
if (!Object.hasOwn(record, field)) {
|
|
1024
|
+
fail('INVALID_INPUT', `${where} 缺少必填字段 "${field}"(须为完整 active card 记录)`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
validateSparkIdLocal(record.id, `${where}.id`);
|
|
1028
|
+
if (record.scopeId !== expectedScopeId) {
|
|
1029
|
+
fail('INVALID_INPUT', `${where}.scopeId (${JSON.stringify(record.scopeId)}) 与候选 scope 不一致,跨 scope 记录拒绝`);
|
|
1030
|
+
}
|
|
1031
|
+
if (!Number.isInteger(record.revision) || record.revision < 1) {
|
|
1032
|
+
fail('INVALID_INPUT', `${where}.revision 必须是 >=1 的整数`);
|
|
1033
|
+
}
|
|
1034
|
+
if (record.state !== 'active') {
|
|
1035
|
+
fail('INVALID_INPUT', `${where}.state 必须是 active(只认完整 active card 记录),得到 ${JSON.stringify(record.state)}`);
|
|
1036
|
+
}
|
|
1037
|
+
checkText(record.title, `${where}.title`, { min: 1, max: CARD_LIMITS.titleChars });
|
|
1038
|
+
checkText(record.summary, `${where}.summary`, { min: 0, max: CARD_LIMITS.summaryChars });
|
|
1039
|
+
checkText(record.content, `${where}.content`, { min: 1, max: CARD_LIMITS.contentChars });
|
|
1040
|
+
for (const [field, maxCount] of [['triggers', CARD_LIMITS.triggersMax], ['entities', CARD_LIMITS.entitiesMax]]) {
|
|
1041
|
+
if (!Array.isArray(record[field])) fail('INVALID_INPUT', `${where}.${field} 必须是字符串数组`);
|
|
1042
|
+
if (record[field].length > maxCount) {
|
|
1043
|
+
fail('INVALID_INPUT', `${where}.${field} 最多 ${maxCount} 项(实际 ${record[field].length})`);
|
|
1044
|
+
}
|
|
1045
|
+
for (let i = 0; i < record[field].length; i += 1) {
|
|
1046
|
+
checkText(record[field][i], `${where}.${field}[${i}]`, { min: 1, max: CARD_LIMITS.wordChars });
|
|
1047
|
+
if (record[field][i].trim() === '') {
|
|
1048
|
+
fail('INVALID_INPUT', `${where}.${field}[${i}] 不得为纯空白`);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
validateCardLinks(record.links, `${where}.links`);
|
|
1053
|
+
if (!VITALITIES.has(record.vitality)) {
|
|
1054
|
+
fail('INVALID_INPUT', `${where}.vitality 必须是 evergreen/ephemeral`);
|
|
1055
|
+
}
|
|
1056
|
+
return record;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/** 卡上 links(P2 实际形状 {target,rel}):形状、去重、上限校验。 */
|
|
1060
|
+
function validateCardLinks(links, where) {
|
|
1061
|
+
if (!Array.isArray(links)) fail('INVALID_INPUT', `${where} 必须是 {target,rel} 数组`);
|
|
1062
|
+
if (links.length > CARD_LIMITS.linksMax) {
|
|
1063
|
+
fail('INVALID_INPUT', `${where} 最多 ${CARD_LIMITS.linksMax} 项(实际 ${links.length})`);
|
|
1064
|
+
}
|
|
1065
|
+
const seen = new Set();
|
|
1066
|
+
for (let i = 0; i < links.length; i += 1) {
|
|
1067
|
+
const entry = links[i];
|
|
1068
|
+
assertExactKeys(entry, ['target', 'rel'], `${where}[${i}]`);
|
|
1069
|
+
validateSparkIdLocal(entry.target, `${where}[${i}].target`);
|
|
1070
|
+
checkText(entry.rel, `${where}[${i}].rel`, { min: 1, max: CARD_LIMITS.relChars });
|
|
1071
|
+
if (entry.rel.trim() === '') {
|
|
1072
|
+
fail('INVALID_INPUT', `${where}[${i}].rel 不得为纯空白`);
|
|
1073
|
+
}
|
|
1074
|
+
const key = `${entry.target}\u0000${entry.rel}`;
|
|
1075
|
+
if (seen.has(key)) {
|
|
1076
|
+
fail('INVALID_INPUT', `${where}[${i}] 与既有 (target,rel) 重复:(${entry.target},${entry.rel})`);
|
|
1077
|
+
}
|
|
1078
|
+
seen.add(key);
|
|
1079
|
+
}
|
|
1080
|
+
return links;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const linkKey = (l) => `${l.target}\u0000${l.rel}`;
|
|
1084
|
+
const compareLinks = (a, b) => byCodepoint(a.target, b.target) || byCodepoint(a.rel, b.rel);
|
|
1085
|
+
|
|
1086
|
+
/** 源保全块用的记录投影:仅这十个字段,triggers/entities/links 保持原数组顺序(契约 §5)。 */
|
|
1087
|
+
function projectRecordForBlock(record) {
|
|
1088
|
+
return {
|
|
1089
|
+
id: record.id,
|
|
1090
|
+
scopeId: record.scopeId,
|
|
1091
|
+
revision: record.revision,
|
|
1092
|
+
title: record.title,
|
|
1093
|
+
summary: record.summary,
|
|
1094
|
+
content: record.content,
|
|
1095
|
+
triggers: [...record.triggers],
|
|
1096
|
+
entities: [...record.entities],
|
|
1097
|
+
links: record.links.map((l) => ({ target: l.target, rel: l.rel })),
|
|
1098
|
+
vitality: record.vitality,
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/** archive-topic 的 topic 元数据校验(恰好 key/expectedRevision/archivedAt 三键)。 */
|
|
1103
|
+
function validateArchiveTopicPlanTopic(topic, where) {
|
|
1104
|
+
assertExactKeys(topic, ['key', 'expectedRevision', 'archivedAt'], where);
|
|
1105
|
+
validateTopicKeyLocal(topic.key, `${where}.key`);
|
|
1106
|
+
checkText(topic.expectedRevision, `${where}.expectedRevision`, { min: 1, max: 16384 });
|
|
1107
|
+
// archivedAt:null = 恢复;字符串 = 归档(必须能被 Date.parse 解析)。
|
|
1108
|
+
if (topic.archivedAt !== null) {
|
|
1109
|
+
checkText(topic.archivedAt, `${where}.archivedAt`, { min: 1 });
|
|
1110
|
+
if (Number.isNaN(Date.parse(topic.archivedAt))) {
|
|
1111
|
+
fail('INVALID_INPUT', `${where}.archivedAt 必须是 null 或能被 Date.parse 解析的时间串`);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
return topic;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/** Plan 结构校验(供 buildDraft 自检与 digestPlan 外部校验共用;纯结构,不查 records)。 */
|
|
1118
|
+
function validatePlanShape(plan, where = 'plan') {
|
|
1119
|
+
assertProtocolJson(plan, where);
|
|
1120
|
+
if (!isPlainObject(plan)) fail('INVALID_INPUT', `${where} 必须是普通对象`);
|
|
1121
|
+
if (plan.version !== 1) fail('INVALID_INPUT', `${where}.version 必须是 1`);
|
|
1122
|
+
if (!PLAN_KINDS.has(plan.kind)) {
|
|
1123
|
+
fail('INVALID_INPUT', `${where}.kind 必须是 link/merge-topic/archive-topic`);
|
|
1124
|
+
}
|
|
1125
|
+
validateScopeIdLocal(plan.scopeId, `${where}.scopeId`);
|
|
1126
|
+
const base = ['version', 'scopeId', 'candidateId', 'kind', 'sources'];
|
|
1127
|
+
if (plan.kind === 'archive-topic') {
|
|
1128
|
+
// archive-topic 不依赖候选队列:candidateId 是确定性别名,不是 64hex 候选
|
|
1129
|
+
// id;sources 恒为空数组(本计划不动任何 spark 卡)。
|
|
1130
|
+
assertExactKeys(plan, [...base, 'topic'], where);
|
|
1131
|
+
if (!isPlainObject(plan.topic)) fail('INVALID_INPUT', `${where}.topic 必须是普通对象`);
|
|
1132
|
+
if (typeof plan.candidateId !== 'string'
|
|
1133
|
+
|| plan.candidateId !== `archive-topic:${plan.topic.key}`) {
|
|
1134
|
+
fail('INVALID_INPUT', `${where}.candidateId 必须是 "archive-topic:<topicKey>"`);
|
|
1135
|
+
}
|
|
1136
|
+
if (!Array.isArray(plan.sources) || plan.sources.length !== 0) {
|
|
1137
|
+
fail('INVALID_INPUT', `${where}.sources 必须是空数组(archive-topic 不动任何 spark 卡)`);
|
|
1138
|
+
}
|
|
1139
|
+
validateArchiveTopicPlanTopic(plan.topic, `${where}.topic`);
|
|
1140
|
+
return plan;
|
|
1141
|
+
}
|
|
1142
|
+
if (typeof plan.candidateId !== 'string' || !/^[0-9a-f]{64}$/.test(plan.candidateId)) {
|
|
1143
|
+
fail('INVALID_INPUT', `${where}.candidateId 必须是小写 64 位 hex`);
|
|
1144
|
+
}
|
|
1145
|
+
validateSourceRefs(plan.sources, `${where}.sources`);
|
|
1146
|
+
if (plan.kind === 'link') {
|
|
1147
|
+
assertExactKeys(plan, [...base, 'links'], where);
|
|
1148
|
+
if (!Array.isArray(plan.links) || plan.links.length === 0) {
|
|
1149
|
+
fail('INVALID_INPUT', `${where}.links 必须是非空数组`);
|
|
1150
|
+
}
|
|
1151
|
+
if (plan.links.length > MAX_CHANGED_ITEMS) {
|
|
1152
|
+
fail('INVALID_INPUT', `${where}.links 超过单轮 ${MAX_CHANGED_ITEMS} 上限(实际 ${plan.links.length})`);
|
|
1153
|
+
}
|
|
1154
|
+
const seen = new Set();
|
|
1155
|
+
let prevId = null;
|
|
1156
|
+
for (let i = 0; i < plan.links.length; i += 1) {
|
|
1157
|
+
const entry = plan.links[i];
|
|
1158
|
+
assertExactKeys(entry, ['id', 'expectedRevision', 'before', 'after'], `${where}.links[${i}]`);
|
|
1159
|
+
validateSparkIdLocal(entry.id, `${where}.links[${i}].id`);
|
|
1160
|
+
if (!Number.isInteger(entry.expectedRevision) || entry.expectedRevision < 1) {
|
|
1161
|
+
fail('INVALID_INPUT', `${where}.links[${i}].expectedRevision 必须是 >=1 的整数`);
|
|
1162
|
+
}
|
|
1163
|
+
validateCardLinks(entry.before, `${where}.links[${i}].before`);
|
|
1164
|
+
validateCardLinks(entry.after, `${where}.links[${i}].after`);
|
|
1165
|
+
if (seen.has(entry.id)) fail('INVALID_INPUT', `${where}.links 存在重复被改源 "${entry.id}"`);
|
|
1166
|
+
seen.add(entry.id);
|
|
1167
|
+
if (prevId !== null && byCodepoint(prevId, entry.id) >= 0) {
|
|
1168
|
+
fail('INVALID_INPUT', `${where}.links 必须按 id 的 UTF-16 序升序排列`);
|
|
1169
|
+
}
|
|
1170
|
+
prevId = entry.id;
|
|
1171
|
+
for (const l of entry.after) {
|
|
1172
|
+
if (l.target === entry.id) fail('INVALID_INPUT', `${where}.links[${i}].after 不允许自环`);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
} else if (plan.kind === 'merge-topic') {
|
|
1176
|
+
assertExactKeys(plan, [...base, 'topic'], where);
|
|
1177
|
+
validatePlanTopic(plan.topic, `${where}.topic`);
|
|
1178
|
+
}
|
|
1179
|
+
return plan;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/** merge-topic 的 topic 元数据校验(before/after 为正文文本,expectedRevision 为 service 不透明 token)。 */
|
|
1183
|
+
function validatePlanTopic(topic, where) {
|
|
1184
|
+
assertExactKeys(topic, ['key', 'expectedRevision', 'before', 'after', 'title', 'summary', 'updated'], where);
|
|
1185
|
+
validateTopicKeyLocal(topic.key, `${where}.key`);
|
|
1186
|
+
checkText(topic.expectedRevision, `${where}.expectedRevision`, { min: 1, max: 16384 });
|
|
1187
|
+
checkText(topic.before, `${where}.before`, { min: 0 });
|
|
1188
|
+
checkText(topic.after, `${where}.after`, { min: 0 });
|
|
1189
|
+
checkText(topic.title, `${where}.title`, { min: 1 });
|
|
1190
|
+
checkText(topic.summary, `${where}.summary`, { min: 0, max: 60 });
|
|
1191
|
+
if (topic.summary.includes('\n') || topic.summary.includes('\r')) {
|
|
1192
|
+
fail('INVALID_INPUT', `${where}.summary 不得含换行`);
|
|
1193
|
+
}
|
|
1194
|
+
checkText(topic.updated, `${where}.updated`, { min: 1 });
|
|
1195
|
+
return topic;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/** 对外部传入 plan 计算 digest(先做完整结构校验,防止对非协议值求指纹)。 */
|
|
1199
|
+
export function digestPlan(plan) {
|
|
1200
|
+
validatePlanShape(plan);
|
|
1201
|
+
return digest(plan);
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// --- link 草案 -------------------------------------------------------------
|
|
1205
|
+
|
|
1206
|
+
function buildLinkDraft(candidate, recordsById, proposal) {
|
|
1207
|
+
assertExactKeys(proposal, ['kind', 'links'], 'proposal');
|
|
1208
|
+
if (!Array.isArray(proposal.links) || proposal.links.length === 0) {
|
|
1209
|
+
fail('INVALID_INPUT', 'proposal.links 必须是非空数组');
|
|
1210
|
+
}
|
|
1211
|
+
if (proposal.links.length > MAX_CHANGED_ITEMS) {
|
|
1212
|
+
fail('INVALID_INPUT', `proposal.links 超过单轮 ${MAX_CHANGED_ITEMS} 上限(实际 ${proposal.links.length})`);
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
const sourceIds = new Set(candidate.sources.map((ref) => ref.id));
|
|
1216
|
+
const seenEntryIds = new Set();
|
|
1217
|
+
const entries = [];
|
|
1218
|
+
for (let i = 0; i < proposal.links.length; i += 1) {
|
|
1219
|
+
const entry = proposal.links[i];
|
|
1220
|
+
assertExactKeys(entry, ['id', 'after'], `proposal.links[${i}]`);
|
|
1221
|
+
// 被改源必须是候选源中的卡(details 供客户端结构化提示;message 前缀
|
|
1222
|
+
// 保持原样——前端仍按 message 兜底,错误码不变)。
|
|
1223
|
+
if (!sourceIds.has(entry.id)) {
|
|
1224
|
+
fail('INVALID_INPUT', `proposal.links[${i}].id "${entry.id}" 必须是 candidate.sources 中的卡`, {
|
|
1225
|
+
field: `proposal.links[${i}].id`,
|
|
1226
|
+
reason: `"${entry.id}" 不在本次候选的 candidate.sources 中`,
|
|
1227
|
+
hint: '这次预览用的候选已经变了,请刷新后重新分析',
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
if (seenEntryIds.has(entry.id)) {
|
|
1231
|
+
fail('INVALID_INPUT', `proposal.links 存在重复被改源 "${entry.id}"`);
|
|
1232
|
+
}
|
|
1233
|
+
seenEntryIds.add(entry.id);
|
|
1234
|
+
if (!Array.isArray(entry.after) || entry.after.length === 0) {
|
|
1235
|
+
fail('INVALID_INPUT', `proposal.links[${i}].after 必须是非空数组`);
|
|
1236
|
+
}
|
|
1237
|
+
// 规范化之前先拒绝重复 (target,rel) 输入;同时禁止自环与未知目标
|
|
1238
|
+
const seenPairs = new Set();
|
|
1239
|
+
for (let j = 0; j < entry.after.length; j += 1) {
|
|
1240
|
+
const pair = entry.after[j];
|
|
1241
|
+
assertExactKeys(pair, ['target', 'rel'], `proposal.links[${i}].after[${j}]`);
|
|
1242
|
+
validateSparkIdLocal(pair.target, `proposal.links[${i}].after[${j}].target`);
|
|
1243
|
+
checkText(pair.rel, `proposal.links[${i}].after[${j}].rel`, { min: 1, max: CARD_LIMITS.relChars });
|
|
1244
|
+
if (pair.rel.trim() === '') {
|
|
1245
|
+
fail('INVALID_INPUT', `proposal.links[${i}].after[${j}].rel 不得为纯空白`);
|
|
1246
|
+
}
|
|
1247
|
+
if (pair.target === entry.id) {
|
|
1248
|
+
fail('INVALID_INPUT', `proposal.links[${i}].after[${j}] 不允许自环(target === 被改源 "${entry.id}")`);
|
|
1249
|
+
}
|
|
1250
|
+
const key = linkKey(pair);
|
|
1251
|
+
if (seenPairs.has(key)) {
|
|
1252
|
+
fail('INVALID_INPUT', `proposal.links[${i}].after 重复 (target,rel):(${pair.target},${pair.rel}),规范化前拒绝`);
|
|
1253
|
+
}
|
|
1254
|
+
seenPairs.add(key);
|
|
1255
|
+
if (!recordsById.has(pair.target)) {
|
|
1256
|
+
fail('NOT_FOUND', `link 目标 "${pair.target}" 不在传入的完整 active records 中(须同 scope、active)`, {
|
|
1257
|
+
target: pair.target,
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
const record = recordsById.get(entry.id);
|
|
1263
|
+
// 保留全部 before 边:after = before ∪ 新增,按 target 再 rel 排序。
|
|
1264
|
+
// active 卡的既有边指向已退休/未随行传入的卡是合法数据形态(store 的
|
|
1265
|
+
// archive 只改目标状态、不改入边)。隐式保留的 before 边目标同样必须
|
|
1266
|
+
// 在 records 中:缺失时按契约返回 NOT_FOUND —— 不静默丢边、不抛原生
|
|
1267
|
+
// TypeError(a1 反例 K-3)。
|
|
1268
|
+
const before = record.links.map((l) => ({ target: l.target, rel: l.rel }));
|
|
1269
|
+
for (const l of before) {
|
|
1270
|
+
if (!recordsById.has(l.target)) {
|
|
1271
|
+
fail('NOT_FOUND', `被改源 "${entry.id}" 的既有边目标 "${l.target}" 不在传入的完整 active records 中,无法绑定 revision(请将全部被引用卡纳入 records,或先清理该边)`, {
|
|
1272
|
+
target: l.target, sourceId: entry.id,
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
const beforeKeys = new Set(before.map(linkKey));
|
|
1277
|
+
const afterMap = new Map(before.map((l) => [linkKey(l), { target: l.target, rel: l.rel }]));
|
|
1278
|
+
let added = 0;
|
|
1279
|
+
for (const key of seenPairs) {
|
|
1280
|
+
if (!beforeKeys.has(key)) added += 1;
|
|
1281
|
+
}
|
|
1282
|
+
if (added === 0) {
|
|
1283
|
+
fail('INVALID_INPUT', `proposal.links[${i}] 对 "${entry.id}" 没有新增边(拒绝无变化草案)`);
|
|
1284
|
+
}
|
|
1285
|
+
for (const pair of entry.after) afterMap.set(linkKey(pair), { target: pair.target, rel: pair.rel });
|
|
1286
|
+
const after = [...afterMap.values()].sort(compareLinks);
|
|
1287
|
+
if (after.length > CARD_LIMITS.linksMax) {
|
|
1288
|
+
fail('INVALID_INPUT', `"${entry.id}" 合并后 links 将达 ${after.length} 项,超过存储上限 ${CARD_LIMITS.linksMax}`);
|
|
1289
|
+
}
|
|
1290
|
+
entries.push({
|
|
1291
|
+
id: entry.id,
|
|
1292
|
+
expectedRevision: record.revision,
|
|
1293
|
+
before,
|
|
1294
|
+
after,
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
entries.sort((a, b) => byCodepoint(a.id, b.id));
|
|
1299
|
+
|
|
1300
|
+
// sources = 候选全部源 ∪ 被改源 ∪ 全部引用目标;候选源、after 新增目标与
|
|
1301
|
+
// 隐式保留的 before 目标均已逐一校验存在于 records,此处再留一道组装防御。
|
|
1302
|
+
const sourceIdSet = new Set(candidate.sources.map((ref) => ref.id));
|
|
1303
|
+
for (const entry of entries) {
|
|
1304
|
+
sourceIdSet.add(entry.id);
|
|
1305
|
+
for (const l of entry.after) sourceIdSet.add(l.target);
|
|
1306
|
+
}
|
|
1307
|
+
const sources = [...sourceIdSet].sort(byCodepoint).map((id) => {
|
|
1308
|
+
const record = recordsById.get(id);
|
|
1309
|
+
if (record === undefined) {
|
|
1310
|
+
fail('NOT_FOUND', `引用目标 "${id}" 不在传入的完整 active records 中,无法绑定 revision`, {
|
|
1311
|
+
target: id,
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
return { id, revision: record.revision };
|
|
1315
|
+
});
|
|
1316
|
+
// P1-1:与执行器同口径(executor.mjs LINK_SOURCES_MAX,同值 64,测试锁定)。
|
|
1317
|
+
// 候选源 ∪ 被改源 ∪ 全部边目标可能超出单轮执行上限;草案层先拒,避免
|
|
1318
|
+
// 用户确认后才在执行器处失败。只加校验,不放宽执行器。
|
|
1319
|
+
if (sources.length > LINK_SOURCES_MAX) {
|
|
1320
|
+
fail('INVALID_INPUT', `plan.sources 达 ${sources.length} 项,超过单轮 ${LINK_SOURCES_MAX} 上限,请拆成多轮整理`, {
|
|
1321
|
+
actual: sources.length, max: LINK_SOURCES_MAX,
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
const plan = {
|
|
1326
|
+
version: 1,
|
|
1327
|
+
scopeId: candidate.scopeId,
|
|
1328
|
+
candidateId: candidate.id,
|
|
1329
|
+
kind: 'link',
|
|
1330
|
+
sources,
|
|
1331
|
+
links: entries,
|
|
1332
|
+
};
|
|
1333
|
+
const diff = entries.map((entry) => ({
|
|
1334
|
+
path: `spark:${entry.id}`,
|
|
1335
|
+
oldText: stable(entry.before),
|
|
1336
|
+
newText: stable(entry.after),
|
|
1337
|
+
}));
|
|
1338
|
+
return { plan, diff, changedItems: entries.length };
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// --- merge-topic 草案 ------------------------------------------------------
|
|
1342
|
+
|
|
1343
|
+
function buildMergeTopicDraft(candidate, recordsById, proposal) {
|
|
1344
|
+
assertExactKeys(proposal, ['kind', 'topic'], 'proposal');
|
|
1345
|
+
const topic = proposal.topic;
|
|
1346
|
+
assertExactKeys(topic, ['key', 'expectedRevision', 'before', 'after', 'title', 'summary', 'updated'], 'proposal.topic');
|
|
1347
|
+
validatePlanTopic(topic, 'proposal.topic');
|
|
1348
|
+
|
|
1349
|
+
if (candidate.kind !== 'cluster') {
|
|
1350
|
+
fail('INVALID_INPUT', `merge-topic 草案要求 cluster 候选(得到 kind=${JSON.stringify(candidate.kind)})`);
|
|
1351
|
+
}
|
|
1352
|
+
if (candidate.sources.length < 8 || candidate.sources.length > 19) {
|
|
1353
|
+
fail('INVALID_INPUT', `merge-topic 草案要求 cluster 候选源数量在 8..19(实际 ${candidate.sources.length})`);
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// append-only:after 必须以 before 为前缀
|
|
1357
|
+
if (!topic.after.startsWith(topic.before)) {
|
|
1358
|
+
fail('INVALID_INPUT', 'proposal.topic.after 必须保留 before 全文(append only)');
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// 源保全块:只包含本次 sources,按 id 排序,完整十个字段,数组保持原顺序
|
|
1362
|
+
const projected = candidate.sources.map((ref) => projectRecordForBlock(recordsById.get(ref.id)));
|
|
1363
|
+
const block = SOURCES_BLOCK_OPEN + stable(projected) + SOURCES_BLOCK_CLOSE;
|
|
1364
|
+
|
|
1365
|
+
let finalAfter;
|
|
1366
|
+
if (topic.after.includes(block)) {
|
|
1367
|
+
finalAfter = topic.after; // 已存在完全相同块,不重复追加
|
|
1368
|
+
} else if (topic.after.includes(SOURCES_MARKER) || topic.after.includes(SOURCES_CLOSE_MARKER)) {
|
|
1369
|
+
fail('INVALID_INPUT', 'proposal.topic.after 已含不同内容的源保全块标记,拒绝叠加第二个块(正文以既有块为准需人工处理)');
|
|
1370
|
+
} else {
|
|
1371
|
+
finalAfter = topic.after + block;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
const plan = {
|
|
1375
|
+
version: 1,
|
|
1376
|
+
scopeId: candidate.scopeId,
|
|
1377
|
+
candidateId: candidate.id,
|
|
1378
|
+
kind: 'merge-topic',
|
|
1379
|
+
sources: deepClone(candidate.sources),
|
|
1380
|
+
topic: {
|
|
1381
|
+
key: topic.key,
|
|
1382
|
+
expectedRevision: topic.expectedRevision,
|
|
1383
|
+
before: topic.before,
|
|
1384
|
+
after: finalAfter,
|
|
1385
|
+
title: topic.title,
|
|
1386
|
+
summary: topic.summary,
|
|
1387
|
+
updated: topic.updated,
|
|
1388
|
+
},
|
|
1389
|
+
};
|
|
1390
|
+
const diff = [
|
|
1391
|
+
{ path: `topic:${topic.key}`, oldText: topic.before, newText: finalAfter },
|
|
1392
|
+
...candidate.sources.map((ref) => {
|
|
1393
|
+
const record = recordsById.get(ref.id);
|
|
1394
|
+
const before = stable({ ...projectRecordForBlock(record), state: record.state });
|
|
1395
|
+
const after = stable({
|
|
1396
|
+
...projectRecordForBlock(record),
|
|
1397
|
+
state: 'merged',
|
|
1398
|
+
revision: record.revision + 1,
|
|
1399
|
+
});
|
|
1400
|
+
return { path: `spark:${ref.id}`, oldText: before, newText: after };
|
|
1401
|
+
}),
|
|
1402
|
+
];
|
|
1403
|
+
return { plan, diff, changedItems: candidate.sources.length + 1 };
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
// --- archive-topic 草案(0.2.2 专题归档/恢复) ------------------------------
|
|
1407
|
+
|
|
1408
|
+
/**
|
|
1409
|
+
* 0.2.2 专题归档/恢复计划草案:不依赖候选队列(candidateId 是确定性别名
|
|
1410
|
+
* "archive-topic:<key>",不是 64hex 候选 id),不引用任何 spark 卡(sources
|
|
1411
|
+
* 恒为空数组)。archivedAt 为可被 Date.parse 解析的时间串 = 归档;null = 恢复。
|
|
1412
|
+
* expectedRevision 由调用方(management.previewPlan)从 service.readTopic 取
|
|
1413
|
+
* fresh.revision(service 签发的 topic revision token);currentArchivedAt 为
|
|
1414
|
+
* 当前归档标记(缺省未归档传 null)。目标状态与当前状态一致(重复归档/重复
|
|
1415
|
+
* 恢复)时拒绝(拒绝无变化草案)。
|
|
1416
|
+
*
|
|
1417
|
+
* @param {object} input
|
|
1418
|
+
* @param {string} input.scopeId
|
|
1419
|
+
* @param {string} input.key topic key
|
|
1420
|
+
* @param {string} input.expectedRevision service revision token(非空字符串)
|
|
1421
|
+
* @param {string|null} input.archivedAt ISO 时间串(归档)或 null(恢复)
|
|
1422
|
+
* @param {string|null} input.currentArchivedAt 当前 archivedAt(null = 未归档)
|
|
1423
|
+
* @returns {{plan, digest, diff, changedItems: 1}}
|
|
1424
|
+
*/
|
|
1425
|
+
export function buildArchiveTopicPlan(input) {
|
|
1426
|
+
if (!isPlainObject(input)) fail('INVALID_INPUT', 'buildArchiveTopicPlan 参数必须是对象');
|
|
1427
|
+
assertExactKeys(
|
|
1428
|
+
input,
|
|
1429
|
+
['scopeId', 'key', 'expectedRevision', 'archivedAt', 'currentArchivedAt'],
|
|
1430
|
+
'buildArchiveTopicPlan 参数',
|
|
1431
|
+
);
|
|
1432
|
+
const { scopeId, key, expectedRevision, archivedAt, currentArchivedAt } = input;
|
|
1433
|
+
validateScopeIdLocal(scopeId, 'scopeId');
|
|
1434
|
+
validateTopicKeyLocal(key, 'key');
|
|
1435
|
+
checkText(expectedRevision, 'expectedRevision', { min: 1, max: 16384 });
|
|
1436
|
+
if (archivedAt !== null) {
|
|
1437
|
+
checkText(archivedAt, 'archivedAt', { min: 1 });
|
|
1438
|
+
if (Number.isNaN(Date.parse(archivedAt))) {
|
|
1439
|
+
fail('INVALID_INPUT', 'archivedAt 必须是 null 或能被 Date.parse 解析的 ISO 时间串');
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
if (currentArchivedAt !== null) {
|
|
1443
|
+
checkText(currentArchivedAt, 'currentArchivedAt', { min: 1 });
|
|
1444
|
+
if (Number.isNaN(Date.parse(currentArchivedAt))) {
|
|
1445
|
+
fail('INVALID_INPUT', 'currentArchivedAt 必须是 null 或能被 Date.parse 解析的 ISO 时间串');
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
if ((archivedAt !== null) === (currentArchivedAt !== null)) {
|
|
1449
|
+
fail('INVALID_INPUT', '专题已在目标状态');
|
|
1450
|
+
}
|
|
1451
|
+
const plan = {
|
|
1452
|
+
version: 1,
|
|
1453
|
+
scopeId,
|
|
1454
|
+
candidateId: `archive-topic:${key}`,
|
|
1455
|
+
kind: 'archive-topic',
|
|
1456
|
+
sources: [],
|
|
1457
|
+
topic: { key, expectedRevision, archivedAt },
|
|
1458
|
+
};
|
|
1459
|
+
const diff = [{
|
|
1460
|
+
path: `topic:${key}`,
|
|
1461
|
+
oldText: `archivedAt: ${currentArchivedAt ?? '(未归档)'}`,
|
|
1462
|
+
newText: `archivedAt: ${archivedAt ?? '(未归档)'}`,
|
|
1463
|
+
}];
|
|
1464
|
+
validatePlanShape(plan); // 自检:Plan 无未知字段、无 digest/approval/operationId
|
|
1465
|
+
return { plan, digest: digest(plan), diff, changedItems: 1 };
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// ---------------------------------------------------------------------------
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* 构建审阅草案。所有 candidate 重新核验 id 与 scope;records 必须含全部被引用卡
|
|
1472
|
+
* (候选源、被改源、link 的全部边目标——含隐式保留的既有边目标),且 revision
|
|
1473
|
+
* 全部吻合(陈旧源 / 缺失源拒绝);返回的 diff 仅是展示内容,
|
|
1474
|
+
* 不注入批准 / 执行状态。
|
|
1475
|
+
*
|
|
1476
|
+
* @param {object} input
|
|
1477
|
+
* @param {object} input.candidate J 槽形状的候选(id 重算核验)
|
|
1478
|
+
* @param {Array} input.records 完整 active 卡记录(store.listActive 形状)
|
|
1479
|
+
* @param {object} input.proposal {kind:'link'|'merge-topic', ...}
|
|
1480
|
+
* @returns {{plan, digest, diff, changedItems}}
|
|
1481
|
+
*/
|
|
1482
|
+
export function buildDraft(input) {
|
|
1483
|
+
if (!isPlainObject(input)) {
|
|
1484
|
+
fail('INVALID_INPUT', 'buildDraft 参数必须是对象');
|
|
1485
|
+
}
|
|
1486
|
+
assertExactKeys(input, ['candidate', 'records', 'proposal'], 'buildDraft 参数');
|
|
1487
|
+
const { candidate, records, proposal } = input;
|
|
1488
|
+
|
|
1489
|
+
validateCandidate(candidate, candidate?.scopeId, 'candidate');
|
|
1490
|
+
assertProtocolJson(records, 'records');
|
|
1491
|
+
if (!Array.isArray(records)) {
|
|
1492
|
+
fail('INVALID_INPUT', 'records 必须是数组(完整 active card 记录列表)');
|
|
1493
|
+
}
|
|
1494
|
+
const recordsById = new Map();
|
|
1495
|
+
for (let i = 0; i < records.length; i += 1) {
|
|
1496
|
+
validateRecord(records[i], candidate.scopeId, `records[${i}]`);
|
|
1497
|
+
if (recordsById.has(records[i].id)) {
|
|
1498
|
+
fail('INVALID_INPUT', `records 存在重复 id "${records[i].id}"`);
|
|
1499
|
+
}
|
|
1500
|
+
recordsById.set(records[i].id, records[i]);
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// 候选源覆盖:缺失 -> NOT_FOUND;revision 不吻合 -> REVISION_CONFLICT(陈旧源)
|
|
1504
|
+
for (const ref of candidate.sources) {
|
|
1505
|
+
const record = recordsById.get(ref.id);
|
|
1506
|
+
if (record === undefined) {
|
|
1507
|
+
fail('NOT_FOUND', `候选源 "${ref.id}" 不在传入 records 中,无法绑定 revision`, { id: ref.id });
|
|
1508
|
+
}
|
|
1509
|
+
if (record.revision !== ref.revision) {
|
|
1510
|
+
fail('REVISION_CONFLICT', `候选源 "${ref.id}" revision 陈旧(候选绑定 ${ref.revision},records 当前 ${record.revision})`, {
|
|
1511
|
+
id: ref.id, candidateRevision: ref.revision, recordRevision: record.revision,
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
assertProtocolJson(proposal, 'proposal');
|
|
1517
|
+
if (!isPlainObject(proposal)) fail('INVALID_INPUT', 'proposal 必须是普通对象');
|
|
1518
|
+
if (typeof proposal.kind !== 'string' || !PLAN_KINDS.has(proposal.kind)) {
|
|
1519
|
+
fail('INVALID_INPUT', 'proposal.kind 必须是 link/merge-topic');
|
|
1520
|
+
}
|
|
1521
|
+
if (proposal.kind === 'archive-topic') {
|
|
1522
|
+
// archive-topic 不走候选队列草案通道(无候选/无 records),独立构建入口
|
|
1523
|
+
// 见 buildArchiveTopicPlan;此处显式拒绝,避免误入其他草案分支报错。
|
|
1524
|
+
fail('INVALID_INPUT', 'buildDraft 不接受 archive-topic(专题归档计划请用 buildArchiveTopicPlan 构建)');
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// proposal.kind ∈ {link, merge-topic}(PLAN_KINDS 闭包 + archive-topic 已拒)。
|
|
1528
|
+
let built;
|
|
1529
|
+
if (proposal.kind === 'link') {
|
|
1530
|
+
built = buildLinkDraft(candidate, recordsById, proposal);
|
|
1531
|
+
} else {
|
|
1532
|
+
built = buildMergeTopicDraft(candidate, recordsById, proposal);
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
validatePlanShape(built.plan); // 自检:Plan 无未知字段、无 digest/approval/operationId
|
|
1536
|
+
return {
|
|
1537
|
+
plan: built.plan,
|
|
1538
|
+
digest: digest(built.plan),
|
|
1539
|
+
diff: built.diff,
|
|
1540
|
+
changedItems: built.changedItems,
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* P-B:forgetting 归档计划的展示 diff——与 merge-topic 的源卡条目同形状
|
|
1546
|
+
* (path `spark:<id>`;oldText/newText 为投影卡记录 + state/revision 的
|
|
1547
|
+
* stable JSON)。执行时 createForgetExecutor 负责 CAS 与 archivedAt/rev+1
|
|
1548
|
+
* 的真实落盘;本 diff 仅是确认前的展示内容。recordsById 必须来自与 plan
|
|
1549
|
+
* 同一次分析的 listActive 快照(卡缺失/revision 漂移都 fail-closed,不猜测)。
|
|
1550
|
+
*
|
|
1551
|
+
* @param {object} plan analyzeForgetting 产出的 archive-ephemeral plan
|
|
1552
|
+
* @param {Map<string, object>} recordsById 卡 id -> 完整 active 记录
|
|
1553
|
+
* @returns {Array<{path: string, oldText: string, newText: string}>}
|
|
1554
|
+
*/
|
|
1555
|
+
export function buildForgetArchiveDiff(plan, recordsById) {
|
|
1556
|
+
if (!isPlainObject(plan) || plan.kind !== 'archive-ephemeral') {
|
|
1557
|
+
fail('INVALID_INPUT', 'buildForgetArchiveDiff 需要 archive-ephemeral plan');
|
|
1558
|
+
}
|
|
1559
|
+
if (!isPlainObject(recordsById) && !(recordsById instanceof Map)) {
|
|
1560
|
+
fail('INVALID_INPUT', 'recordsById 必须是普通对象或 Map');
|
|
1561
|
+
}
|
|
1562
|
+
const get = typeof recordsById.get === 'function'
|
|
1563
|
+
? (id) => recordsById.get(id)
|
|
1564
|
+
: (id) => recordsById[id];
|
|
1565
|
+
return plan.sources.map((ref) => {
|
|
1566
|
+
const record = get(ref.id);
|
|
1567
|
+
if (record === undefined) {
|
|
1568
|
+
fail('INVALID_STATE', `归档计划源卡 "${ref.id}" 不在分析快照中,拒绝生成展示 diff`, { id: ref.id });
|
|
1569
|
+
}
|
|
1570
|
+
if (record.revision !== ref.revision) {
|
|
1571
|
+
fail('REVISION_CONFLICT', `归档计划源卡 "${ref.id}" revision 漂移(plan 绑定 ${ref.revision},快照 ${record.revision})`, {
|
|
1572
|
+
id: ref.id, planRevision: ref.revision, recordRevision: record.revision,
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
const projected = projectRecordForBlock(record);
|
|
1576
|
+
const before = stable({ ...projected, state: record.state });
|
|
1577
|
+
const after = stable({
|
|
1578
|
+
...projected,
|
|
1579
|
+
state: 'archived',
|
|
1580
|
+
revision: record.revision + 1,
|
|
1581
|
+
});
|
|
1582
|
+
return { path: `spark:${ref.id}`, oldText: before, newText: after };
|
|
1583
|
+
});
|
|
1584
|
+
}
|