dsh-memorytree-rule 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/rules.mjs ADDED
@@ -0,0 +1,635 @@
1
+ // lib/rules.mjs — 主干规则的编号、重排与引用改写(纯函数)。
2
+ //
3
+ // 设计边界:
4
+ // - 只处理 AGENTS.md 的 §1 主干;§2–§5 不解析、不改号。
5
+ // - 改号是「整段 §1 重排」:先摘出被移动的规则,再按目标号升序插入,
6
+ // 最后从 1 开始顺序重编号;正文里的 §1-x-y 引用用占位符一次性映射,避免连环错位。
7
+ // - 只改正文、不改编号的补丁走最小改动路径(逐条替换规则块),不重排整段。
8
+ // - ### 变更记录 是历史记录,引用替换时跳过。
9
+ import { checksum } from "./text.mjs";
10
+ import { parseAgents } from "./ingest.mjs";
11
+
12
+ const RULE_NUM_RE = /^§1-(\d+)-(\d+)$/;
13
+ const REF_RE = /§1-(\d+)-(\d+)/g;
14
+ const CHANGE_LOG_RE = /^###\s+变更记录\s*$/m;
15
+
16
+ function normalizeEol(s) {
17
+ return String(s ?? "").replace(/\r\n?/g, "\n");
18
+ }
19
+
20
+ /** 把用户输入的编号归一化为 §1-g-n。接受 trunk:§1-1-3 / §1-1-3 / 1-1-3。 */
21
+ export function normalizeNumberInput(input) {
22
+ let s = String(input ?? "").trim();
23
+ if (!s) return { ok: false, error: "库内编号不能为空。" };
24
+ s = s.replace(/[\s\u3000]+/g, "").replace(/^trunk:/i, "").replace(/[–—-]/g, "-");
25
+ if (!/^§/.test(s)) s = "§" + s.replace(/^§+/, "");
26
+ const m = /^§1-(\d+)-(\d+)$/.exec(s);
27
+ if (!m) {
28
+ if (/^§[2-5]-/.test(s)) return { ok: false, error: "v1 只支持 §1 主干的编号;§2–§5 暂不支持改号。" };
29
+ return { ok: false, error: "编号格式应为 trunk:§1-1-3(或 §1-1-3)。" };
30
+ }
31
+ const groupNum = Number(m[1]);
32
+ const index = Number(m[2]);
33
+ if (groupNum < 1 || index < 1) return { ok: false, error: "编号必须从 1 开始。" };
34
+ return {
35
+ ok: true,
36
+ num: "§1-" + groupNum + "-" + index,
37
+ group: "§1-" + groupNum,
38
+ groupNum,
39
+ index,
40
+ uid: "trunk:§1-" + groupNum + "-" + index,
41
+ };
42
+ }
43
+
44
+ /** 解析 §1-g-n;不是这个形状就返回 null。 */
45
+ export function parseRuleNum(num) {
46
+ const m = RULE_NUM_RE.exec(String(num ?? "").trim());
47
+ if (!m) return null;
48
+ return { groupNum: Number(m[1]), index: Number(m[2]), group: "§1-" + m[1] };
49
+ }
50
+
51
+ /** 排序权重:组号优先,其次组内序号。 */
52
+ export function ruleRank(num) {
53
+ const p = parseRuleNum(num);
54
+ return p ? p.groupNum * 1000 + p.index : 999999;
55
+ }
56
+
57
+ /** §1 下的分组标题(### 或 #### §1-x 标题)。 */
58
+ export function trunkGroups(raw) {
59
+ const lines = normalizeEol(raw).split("\n");
60
+ const groups = [];
61
+ let cur = null;
62
+ for (let i = 0; i < lines.length; i += 1) {
63
+ const line = lines[i];
64
+ const h = /^(#{2,4})\s+(.+?)\s*$/.exec(line);
65
+ if (h) {
66
+ const level = h[1].length;
67
+ if (cur && level <= cur.level) {
68
+ cur.endLine = i;
69
+ groups.push(cur);
70
+ cur = null;
71
+ }
72
+ if (level === 3 || level === 4) {
73
+ const m = /^§1-(\d+)[\s\u3000]+(.+)$/.exec(h[2].trim());
74
+ if (m) {
75
+ cur = {
76
+ key: "§1-" + m[1],
77
+ num: Number(m[1]),
78
+ title: m[2].trim(),
79
+ level,
80
+ startLine: i + 1,
81
+ endLine: lines.length,
82
+ };
83
+ }
84
+ }
85
+ continue;
86
+ }
87
+ if (cur && /^##\s+§[2-5][\s\u3000]/.test(line)) {
88
+ cur.endLine = i;
89
+ groups.push(cur);
90
+ cur = null;
91
+ }
92
+ }
93
+ if (cur) groups.push(cur);
94
+ return groups;
95
+ }
96
+
97
+ function splitRuleText(text, fallbackTitle) {
98
+ const src = String(text ?? "").replace(/\r\n?/g, "\n").trim();
99
+ const firstBreak = src.indexOf("\n");
100
+ const first = firstBreak >= 0 ? src.slice(0, firstBreak) : src;
101
+ const rest = firstBreak >= 0 ? src.slice(firstBreak + 1) : "";
102
+ const m = /^([^::]{1,120})[::]\s*([\s\S]*)$/.exec(first);
103
+ const title = m ? m[1].trim() : String(fallbackTitle || "").trim();
104
+ const bodyFirst = m ? m[2].trim() : first.trim();
105
+ return { title, bodyFirst, rest };
106
+ }
107
+
108
+ /** 生成一条规则块(不含末尾空行)。num 可以是占位符,渲染后再替换。 */
109
+ export function buildRuleBlock(num, title, text) {
110
+ const { title: t, bodyFirst, rest } = splitRuleText(text, title);
111
+ const lines = ["- **" + num + " " + (t || title || "未命名规则") + "**:" + bodyFirst];
112
+ if (rest !== "") {
113
+ for (const line of rest.split("\n")) {
114
+ if (line.trim() === "") {
115
+ lines.push("");
116
+ } else if (/^\s/.test(line)) {
117
+ lines.push(line);
118
+ } else {
119
+ lines.push(" " + line);
120
+ }
121
+ }
122
+ }
123
+ return lines;
124
+ }
125
+
126
+ function findRule(raw, node) {
127
+ const parsed = parseAgents(raw);
128
+ const num = String(node.uid || "").startsWith("trunk:") ? String(node.uid).slice(6) : "";
129
+ return parsed.rules.find((r) => (num && r.num === num) || r.title === node.title) || null;
130
+ }
131
+
132
+ /** 用编辑后的正文替换 AGENTS.md 中对应规则块,返回新全文。 */
133
+ export function replaceRuleInAgents(raw, node, newText) {
134
+ const rule = findRule(raw, node);
135
+ if (!rule) return { ok: false, error: "AGENTS.md 里找不到这条规则(可能已被移动或删除),请先同步再试。" };
136
+ const src = normalizeEol(raw);
137
+ const lines = src.split("\n");
138
+ const start = Math.max(0, rule.startLine - 1);
139
+ const end = Math.min(lines.length, rule.endLine);
140
+ const block = buildRuleBlock(rule.num, rule.title, newText);
141
+ const after = lines.slice(end);
142
+ const before = lines.slice(0, start);
143
+ if (after.length && after[0].trim() !== "") after.unshift("");
144
+ return { ok: true, text: before.concat(block, after).join("\n"), rule };
145
+ }
146
+
147
+ /** 从 AGENTS.md 里删除对应规则块,返回新全文。 */
148
+ export function removeRuleFromAgents(raw, node) {
149
+ const rule = findRule(raw, node);
150
+ if (!rule) return { ok: false, error: "AGENTS.md 里找不到这条规则(可能已被移动或删除),请先同步再试。" };
151
+ const src = normalizeEol(raw);
152
+ const lines = src.split("\n");
153
+ const start = Math.max(0, rule.startLine - 1);
154
+ let end = Math.min(lines.length, rule.endLine);
155
+ if (end < lines.length && lines[end].trim() === "") end += 1;
156
+ return { ok: true, text: lines.slice(0, start).concat(lines.slice(end)).join("\n"), rule };
157
+ }
158
+
159
+ const SECTION_HEAD_RE = /^##\s+(§[2-4])\s+(.+?)\s*$/;
160
+ const SECTION_RULE_RE = /^-\s+\*\*(§[2-4]-\d+)[\s\u3000]+([^*]+?)\*\*\s*[::]\s*(.*)$/;
161
+
162
+ /**
163
+ * 解析 AGENTS.md 的 §2–§4 规则(只读;带行号,供看板展示与编辑使用)。
164
+ * 返回 [{ key:"§2", title:"情感枝", rules:[{num,title,text,startLine,endLine}] }]。
165
+ */
166
+ export function parseAgentSections(raw) {
167
+ const lines = normalizeEol(raw).split("\n");
168
+ const sections = [];
169
+ let section = null;
170
+ let rule = null;
171
+ const flushRule = (end) => {
172
+ if (!rule) return;
173
+ let e = end;
174
+ while (e > rule.startLine - 1 && lines[e - 1] && lines[e - 1].trim() === "") e -= 1;
175
+ rule.endLine = e;
176
+ rule.text = rule.title + ":" + rule.body.join("\n").trim();
177
+ delete rule.body;
178
+ rule = null;
179
+ };
180
+ const flushSection = (end) => {
181
+ flushRule(end);
182
+ if (section) sections.push(section);
183
+ section = null;
184
+ };
185
+ for (let i = 0; i < lines.length; i += 1) {
186
+ const line = lines[i];
187
+ const h = SECTION_HEAD_RE.exec(line);
188
+ if (h) {
189
+ flushSection(i);
190
+ section = { key: h[1], title: h[2].trim(), rules: [] };
191
+ continue;
192
+ }
193
+ if (/^##\s+§[15]\b/.test(line)) {
194
+ flushSection(i);
195
+ continue;
196
+ }
197
+ if (!section) continue;
198
+ const r = SECTION_RULE_RE.exec(line);
199
+ if (r) {
200
+ flushRule(i);
201
+ rule = { num: r[1], title: r[2].trim(), body: [r[3]], startLine: i + 1 };
202
+ section.rules.push(rule);
203
+ continue;
204
+ }
205
+ if (rule && line.trim()) rule.body.push(line.trim());
206
+ }
207
+ flushSection(lines.length);
208
+ return sections;
209
+ }
210
+
211
+ /** 找 §2–§4 的一条规则;不存在返回 null。 */
212
+ export function findAgentSectionRule(raw, num) {
213
+ const want = String(num ?? "").trim();
214
+ if (!/^§[2-4]-\d+$/.test(want)) return null;
215
+ for (const sec of parseAgentSections(raw)) {
216
+ const rule = sec.rules.find((r) => r.num === want);
217
+ if (rule) return { ...rule, section: sec.key, sectionTitle: sec.title };
218
+ }
219
+ return null;
220
+ }
221
+
222
+ /** 替换 AGENTS.md 中一条 §2–§4 规则块,返回新全文。 */
223
+ export function replaceAgentSectionRule(raw, num, newText) {
224
+ const rule = findAgentSectionRule(raw, num);
225
+ if (!rule) return { ok: false, error: "AGENTS.md 里找不到 " + num + "(可能已被移动或删除),请刷新看板再试。" };
226
+ const src = normalizeEol(raw);
227
+ const lines = src.split("\n");
228
+ const start = Math.max(0, rule.startLine - 1);
229
+ const end = Math.min(lines.length, rule.endLine);
230
+ const block = buildRuleBlock(rule.num, rule.title, newText);
231
+ const before = lines.slice(0, start);
232
+ const after = lines.slice(end);
233
+ if (after.length && after[0].trim() !== "") after.unshift("");
234
+ return { ok: true, text: before.concat(block, after).join("\n"), rule };
235
+ }
236
+
237
+ /** 从 AGENTS.md 删除一条 §2–§4 规则块,返回新全文。 */
238
+ export function removeAgentSectionRule(raw, num) {
239
+ const rule = findAgentSectionRule(raw, num);
240
+ if (!rule) return { ok: false, error: "AGENTS.md 里找不到 " + num + "(可能已被移动或删除),请刷新看板再试。" };
241
+ const src = normalizeEol(raw);
242
+ const lines = src.split("\n");
243
+ const start = Math.max(0, rule.startLine - 1);
244
+ const end = Math.min(lines.length, rule.endLine);
245
+ return { ok: true, text: lines.slice(0, start).concat(lines.slice(end)).join("\n"), rule };
246
+ }
247
+
248
+ function collectRefLines(srcLines, refMap) {
249
+ const out = [];
250
+ let inChangeLog = false;
251
+ for (let i = 0; i < srcLines.length; i += 1) {
252
+ const line = srcLines[i];
253
+ if (/^###\s+变更记录\s*$/.test(line)) {
254
+ inChangeLog = true;
255
+ continue;
256
+ }
257
+ if (inChangeLog) continue;
258
+ if (!/§1-\d+-\d+/.test(line)) continue;
259
+ let changed = false;
260
+ const after = line.replace(REF_RE, (m, g, n) => {
261
+ const old = "§1-" + g + "-" + n;
262
+ const next = refMap.get(old);
263
+ if (next && next !== old) {
264
+ changed = true;
265
+ return next;
266
+ }
267
+ return old;
268
+ });
269
+ if (changed) out.push({ line: i + 1, before: line.trim(), after: after.trim() });
270
+ if (out.length >= 200) break;
271
+ }
272
+ return out;
273
+ }
274
+
275
+ function tokenPlan(valid) {
276
+ const items = valid
277
+ .map((p) => [p.uid, p.newNum, checksum(String(p.newText).trim())])
278
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])));
279
+ return checksum(JSON.stringify(items));
280
+ }
281
+
282
+ /**
283
+ * 计算待写入补丁的最终结果。
284
+ * @param {string} raw AGENTS.md 全文
285
+ * @param {Array} patches 待写入补丁(pending_patch 行)
286
+ * @returns {{ok:boolean, mode?:string, newText?:string, mapping?:Array, groups?:Array,
287
+ * refLines?:Array, refsChanged?:number, conflicts?:Array, planToken?:string, fileChecksum?:string}}
288
+ */
289
+ export function planRenumber(raw, patches = []) {
290
+ const src = normalizeEol(raw);
291
+ const srcLines = src.split("\n");
292
+ const parsed = parseAgents(src);
293
+ if (!parsed.trunk) return { ok: false, mode: "blocked", error: "AGENTS.md 里没有 §1 主干。", conflicts: [{ code: "no-trunk", message: "AGENTS.md 里没有 §1 主干。" }] };
294
+ const fileChecksum = checksum(src);
295
+ const groups = trunkGroups(src).sort((a, b) => a.num - b.num);
296
+ const groupByKey = new Map(groups.map((g) => [g.key, g]));
297
+ const ruleByNum = new Map(parsed.rules.map((r) => [r.num, r]));
298
+ const conflicts = [];
299
+ const valid = [];
300
+ const seenUid = new Set();
301
+
302
+ for (const p of patches) {
303
+ const uid = String(p.uid ?? p.uid ?? "");
304
+ if (!uid) {
305
+ conflicts.push({ code: "bad-patch", message: "有一条待写入记录缺少规则 uid。" });
306
+ continue;
307
+ }
308
+ if (seenUid.has(uid)) {
309
+ conflicts.push({ code: "duplicate-rule", message: "同一规则有多条待写入:" + uid, uid });
310
+ continue;
311
+ }
312
+ seenUid.add(uid);
313
+ const oldNum = String(p.oldNum ?? p.old_num ?? "");
314
+ const rule = ruleByNum.get(oldNum);
315
+ if (!rule) {
316
+ conflicts.push({ code: "missing-rule", message: "AGENTS.md 里找不到 " + (oldNum || uid) + "(可能已被移动或删除)。", uid });
317
+ continue;
318
+ }
319
+ const baseChecksum = String(p.baseChecksum ?? p.base_checksum ?? "");
320
+ if (baseChecksum && baseChecksum !== fileChecksum) {
321
+ conflicts.push({ code: "stale-file", message: oldNum + " 暂存后 AGENTS.md 被改过;请删除这条待写入后重做。", uid });
322
+ continue;
323
+ }
324
+ if (String(rule.text).trim() !== String(p.oldText ?? p.old_text ?? "").trim()) {
325
+ conflicts.push({ code: "stale-text", message: oldNum + " 的正文在暂存后被改过;请删除这条待写入后重做。", uid });
326
+ continue;
327
+ }
328
+ const nn = normalizeNumberInput(p.newNum ?? p.new_num ?? oldNum);
329
+ if (!nn.ok) {
330
+ conflicts.push({ code: "bad-number", message: nn.error, uid });
331
+ continue;
332
+ }
333
+ if (!groupByKey.has(nn.group)) {
334
+ conflicts.push({ code: "missing-group", message: "目标分组 " + nn.group + " 不存在。", uid });
335
+ continue;
336
+ }
337
+ const newText = String(p.newText ?? p.new_text ?? rule.text).trim();
338
+ if (!newText) {
339
+ conflicts.push({ code: "empty-text", message: oldNum + " 的新正文是空的。", uid });
340
+ continue;
341
+ }
342
+ valid.push({
343
+ uid,
344
+ oldNum: rule.num,
345
+ newNum: nn.num,
346
+ groupNum: nn.groupNum,
347
+ index: nn.index,
348
+ moved: nn.num !== rule.num,
349
+ rule,
350
+ newText,
351
+ });
352
+ }
353
+
354
+ // 文件里「看起来是 §1 规则但没被解析」的行:宁可拦下,也不能在重排时漏掉/挪错。
355
+ let inTrunk = false;
356
+ const parsedStarts = new Set(parsed.rules.map((r) => r.startLine));
357
+ for (let i = 0; i < srcLines.length; i += 1) {
358
+ const line = srcLines[i];
359
+ if (/^##\s+§1[\s\u3000]/.test(line)) {
360
+ inTrunk = true;
361
+ continue;
362
+ }
363
+ if (/^##\s+§[2-5][\s\u3000]/.test(line)) {
364
+ inTrunk = false;
365
+ continue;
366
+ }
367
+ if (!inTrunk) continue;
368
+ if (/^\s*[-*]\s+\*\*§1-\d+-\d+/.test(line) && !parsedStarts.has(i + 1)) {
369
+ conflicts.push({
370
+ code: "unparsed-rule",
371
+ line: i + 1,
372
+ message: "第 " + (i + 1) + " 行看起来是 §1 规则,但格式没被解析(`**…**` 后应为中文冒号 `:`)。",
373
+ });
374
+ }
375
+ }
376
+
377
+ for (const rule of parsed.rules) {
378
+ const p = parseRuleNum(rule.num);
379
+ if (!p) {
380
+ conflicts.push({ code: "bad-rule-num", message: "无法识别的规则编号:" + rule.num, uid: rule.uid });
381
+ continue;
382
+ }
383
+ if (!groupByKey.has("§1-" + p.groupNum)) {
384
+ conflicts.push({ code: "missing-group", message: "规则 " + rule.num + " 没有对应的 #### §1-" + p.groupNum + " 分组标题。", uid: rule.uid });
385
+ }
386
+ }
387
+
388
+ // 同一分组里两条移动补丁争同一个目标序号 → 歧义,必须人工改开。
389
+ const targets = new Map();
390
+ for (const p of valid.filter((x) => x.moved)) {
391
+ const key = p.groupNum + ":" + p.index;
392
+ if (targets.has(key)) {
393
+ conflicts.push({ code: "duplicate-target", message: "两条待写入都要进 " + ("§1-" + p.groupNum + "-" + p.index) + ";请改开其中一条的目标号。", uid: p.uid });
394
+ } else {
395
+ targets.set(key, p);
396
+ }
397
+ }
398
+
399
+ const planTokenValue = tokenPlan(valid);
400
+ if (conflicts.length) {
401
+ return {
402
+ ok: false,
403
+ mode: "blocked",
404
+ error: conflicts[0].message,
405
+ conflicts,
406
+ fileChecksum,
407
+ planToken: planTokenValue,
408
+ pendingCount: patches.length,
409
+ };
410
+ }
411
+
412
+ if (valid.length === 0) {
413
+ return {
414
+ ok: true,
415
+ mode: "none",
416
+ newText: src,
417
+ mapping: [],
418
+ groups: [],
419
+ refLines: [],
420
+ refsChanged: 0,
421
+ numberChanged: false,
422
+ conflicts: [],
423
+ fileChecksum,
424
+ planToken: planTokenValue,
425
+ pendingCount: patches.length,
426
+ };
427
+ }
428
+
429
+ const numberChanged = valid.some((p) => p.moved);
430
+ if (!numberChanged) {
431
+ // 只改正文:逐条替换,保留文件其余格式与行距。
432
+ let next = src;
433
+ for (const p of valid) {
434
+ const replaced = replaceRuleInAgents(next, { uid: p.uid, title: p.rule.title }, p.newText);
435
+ if (!replaced.ok) {
436
+ return {
437
+ ok: false,
438
+ mode: "blocked",
439
+ error: replaced.error,
440
+ conflicts: [{ code: "replace-failed", message: replaced.error, uid: p.uid }],
441
+ fileChecksum,
442
+ planToken: planTokenValue,
443
+ pendingCount: patches.length,
444
+ };
445
+ }
446
+ next = replaced.text;
447
+ }
448
+ const mapping = valid.map((p) => {
449
+ const title = splitRuleText(p.newText, p.rule.title).title;
450
+ return { old: p.oldNum, new: p.oldNum, uid: p.uid, title, changed: false };
451
+ });
452
+ return {
453
+ ok: true,
454
+ mode: "content",
455
+ newText: next,
456
+ mapping,
457
+ groups: [],
458
+ refLines: [],
459
+ refsChanged: 0,
460
+ numberChanged: false,
461
+ conflicts: [],
462
+ fileChecksum,
463
+ planToken: planTokenValue,
464
+ pendingCount: patches.length,
465
+ };
466
+ }
467
+
468
+ // 有编号变化:整段 §1 重排。
469
+ const movedOldNums = new Set(valid.filter((p) => p.moved).map((p) => p.oldNum));
470
+ const contentByOld = new Map(valid.filter((p) => !p.moved).map((p) => [p.oldNum, p]));
471
+ const byGroup = new Map(groups.map((g) => [g.num, { group: g, base: [], incoming: [] }]));
472
+ for (const rule of parsed.rules) {
473
+ const p = parseRuleNum(rule.num);
474
+ if (!p) continue;
475
+ const bucket = byGroup.get(p.groupNum);
476
+ if (!bucket) continue;
477
+ if (movedOldNums.has(rule.num)) continue;
478
+ const cp = contentByOld.get(rule.num);
479
+ bucket.base.push({ rule, text: cp ? cp.newText : rule.text, patch: cp || null });
480
+ }
481
+ for (const p of valid.filter((x) => x.moved)) {
482
+ const bucket = byGroup.get(p.groupNum);
483
+ if (!bucket) continue;
484
+ bucket.incoming.push(p);
485
+ }
486
+
487
+ for (const [groupNum, bucket] of byGroup) {
488
+ const finalCount = bucket.base.length + bucket.incoming.length;
489
+ const used = new Set();
490
+ for (const p of bucket.incoming) {
491
+ if (p.index > finalCount) {
492
+ return {
493
+ ok: false,
494
+ mode: "blocked",
495
+ error: "§1-" + groupNum + "-" + p.index + " 超出目标分组重排后的范围(最多 §1-" + groupNum + "-" + finalCount + ")。",
496
+ conflicts: [{ code: "target-out-of-range", message: "§1-" + groupNum + "-" + p.index + " 超出目标分组重排后的范围(最多 §1-" + groupNum + "-" + finalCount + ")。", uid: p.uid }],
497
+ fileChecksum,
498
+ planToken: planTokenValue,
499
+ pendingCount: patches.length,
500
+ };
501
+ }
502
+ const key = groupNum + ":" + p.index;
503
+ if (used.has(key)) {
504
+ return {
505
+ ok: false,
506
+ mode: "blocked",
507
+ error: "两条待写入都要进 §1-" + groupNum + "-" + p.index + ";请改开其中一条。",
508
+ conflicts: [{ code: "duplicate-target", message: "两条待写入都要进 §1-" + groupNum + "-" + p.index + ";请改开其中一条。", uid: p.uid }],
509
+ fileChecksum,
510
+ planToken: planTokenValue,
511
+ pendingCount: patches.length,
512
+ };
513
+ }
514
+ used.add(key);
515
+ }
516
+ }
517
+
518
+ const firstGroup = groups[0];
519
+ const sec2Index = srcLines.findIndex((l) => /^##\s+§2[\s\u3000]/.test(l));
520
+ // 重排会重建 §1 的规则块;分组内若有说明文字/注释,重建时会丢失。宁可拒绝,也不静默删内容。
521
+ if (firstGroup) {
522
+ const known = new Set();
523
+ for (const r of parsed.rules) {
524
+ for (let ln = r.startLine; ln <= r.endLine; ln += 1) known.add(ln);
525
+ }
526
+ for (const g of groups) known.add(g.startLine);
527
+ const endLine = sec2Index >= 0 ? sec2Index : srcLines.length;
528
+ for (let ln = firstGroup.startLine; ln <= endLine; ln += 1) {
529
+ const text = srcLines[ln - 1] ?? "";
530
+ if (text.trim() === "" || known.has(ln)) continue;
531
+ return {
532
+ ok: false,
533
+ mode: "blocked",
534
+ error: "§1 分组内有非规则文字(第 " + ln + " 行),编号重排会丢失它;请先移出该段或只改正文。",
535
+ conflicts: [{ code: "non-rule-text", message: "非规则文字会丢失", line: ln }],
536
+ fileChecksum,
537
+ planToken: planTokenValue,
538
+ pendingCount: patches.length,
539
+ };
540
+ }
541
+ }
542
+ const prefixEnd = firstGroup ? firstGroup.startLine - 1 : sec2Index >= 0 ? sec2Index : srcLines.length;
543
+ const out = srcLines.slice(0, prefixEnd);
544
+ while (out.length && out[out.length - 1].trim() === "") out.pop();
545
+
546
+ const tokenMap = new Map();
547
+ let tokenSeq = 0;
548
+ const refMap = new Map();
549
+ const mapping = [];
550
+ const groupPreview = [];
551
+
552
+ for (const group of groups) {
553
+ const bucket = byGroup.get(group.num);
554
+ if (!bucket) continue;
555
+ const list = [...bucket.base].sort((a, b) => (parseRuleNum(a.rule.num)?.index ?? 0) - (parseRuleNum(b.rule.num)?.index ?? 0));
556
+ for (const p of [...bucket.incoming].sort((a, b) => a.index - b.index)) {
557
+ list.splice(Math.max(0, p.index - 1), 0, { rule: p.rule, text: p.newText, patch: p });
558
+ }
559
+ const items = [];
560
+ for (let i = 0; i < list.length; i += 1) {
561
+ const entry = list[i];
562
+ const oldNum = entry.patch ? entry.patch.oldNum : entry.rule.num;
563
+ const newNum = "§1-" + group.num + "-" + (i + 1);
564
+ refMap.set(oldNum, newNum);
565
+ const title = splitRuleText(entry.text, entry.rule.title).title;
566
+ mapping.push({ old: oldNum, new: newNum, uid: entry.patch ? entry.patch.uid : entry.rule.uid, title, changed: oldNum !== newNum });
567
+ const token = "@@MTNUM_" + tokenSeq + "@@";
568
+ tokenSeq += 1;
569
+ tokenMap.set(token, newNum);
570
+ items.push({ oldNum, newNum, title, text: entry.text, token, changed: oldNum !== newNum });
571
+ }
572
+ groupPreview.push({
573
+ key: group.key,
574
+ title: group.title,
575
+ items: items.map((x) => ({ old: x.oldNum, new: x.newNum, title: x.title, changed: x.changed })),
576
+ });
577
+ if (out.length && out[out.length - 1].trim() !== "") out.push("");
578
+ const heading = srcLines[group.startLine - 1] || "#### " + group.key + " " + group.title;
579
+ out.push(heading, "");
580
+ for (const item of items) {
581
+ out.push(...buildRuleBlock(item.token, item.title, item.text));
582
+ }
583
+ if (out.length && out[out.length - 1].trim() !== "") out.push("");
584
+ }
585
+
586
+ while (out.length && out[out.length - 1].trim() === "") out.pop();
587
+ if (sec2Index >= 0) {
588
+ out.push("");
589
+ out.push(...srcLines.slice(sec2Index));
590
+ } else {
591
+ out.push("");
592
+ }
593
+
594
+ let nextText = out.join("\n");
595
+
596
+ // 引用一次性映射:规则编号此时还是 @@MTNUM_n@@ 占位符,不会被联动替换误伤;
597
+ // 先映射正文里的旧引用,再把占位符换成新编号。
598
+ let refsChanged = 0;
599
+ const changeMatch = CHANGE_LOG_RE.exec(nextText);
600
+ const changeAt = changeMatch ? changeMatch.index : -1;
601
+ const head = changeAt >= 0 ? nextText.slice(0, changeAt) : nextText;
602
+ const rest = changeAt >= 0 ? nextText.slice(changeAt) : "";
603
+ const remapped = head.replace(REF_RE, (m, g, n) => {
604
+ const oldNum = "§1-" + g + "-" + n;
605
+ const next = refMap.get(oldNum);
606
+ if (next && next !== oldNum) {
607
+ refsChanged += 1;
608
+ return next;
609
+ }
610
+ return oldNum;
611
+ });
612
+ nextText = remapped + rest;
613
+ nextText = nextText.replace(/@@MTNUM_(\d+)@@/g, (m, i) => tokenMap.get("@@MTNUM_" + i + "@@") ?? m);
614
+
615
+ const refLines = collectRefLines(srcLines, refMap);
616
+ return {
617
+ ok: true,
618
+ mode: "renumber",
619
+ newText: nextText,
620
+ mapping,
621
+ groups: groupPreview,
622
+ refLines,
623
+ refsChanged,
624
+ numberChanged: true,
625
+ conflicts: [],
626
+ fileChecksum,
627
+ planToken: planTokenValue,
628
+ pendingCount: patches.length,
629
+ };
630
+ }
631
+
632
+ /** 给看板/测试用:把一条规则正文拆成标题与正文。 */
633
+ export function ruleTitleOf(text, fallbackTitle) {
634
+ return splitRuleText(text, fallbackTitle).title;
635
+ }