flow-comet 1.6.0 → 1.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.flow-comet/skills/flow-comet/GUIDANCE.md +26 -5
- package/.flow-comet/skills/flow-comet/INSTALLED_VERSION +1 -1
- package/.flow-comet/skills/flow-comet/SKILL.md +51 -2
- package/.flow-comet/skills/flow-comet/reference/KNOWN-ISSUES-template.md +3 -3
- package/.flow-comet/skills/flow-comet/reference/TEST-MATRIX.md +15 -15
- package/.flow-comet/skills/flow-comet/reference/dsh-platform.md +19 -11
- package/.flow-comet/skills/flow-comet/reference/recovery.md +1 -7
- package/.flow-comet/skills/flow-comet/reference/workflow-protocol.json +1 -1
- package/.flow-comet/skills/flow-comet/reference/worktree-notes.md +21 -3
- package/.flow-comet/skills/flow-comet/scripts/context-init.mjs +129 -3
- package/.flow-comet/skills/flow-comet/scripts/context-scan.mjs +396 -0
- package/.flow-comet/skills/flow-comet/scripts/contract-check.mjs +41 -31
- package/.flow-comet/skills/flow-comet/scripts/evolve.mjs +778 -0
- package/.flow-comet/skills/flow-comet/scripts/guard-self-test.mjs +5499 -596
- package/.flow-comet/skills/flow-comet/scripts/health.mjs +664 -0
- package/.flow-comet/skills/flow-comet/scripts/protocol-utils.mjs +1 -1
- package/.flow-comet/skills/flow-comet/scripts/route-node.mjs +459 -11
- package/.flow-comet/skills/flow-comet/scripts/state-schema.mjs +58 -3
- package/.flow-comet/skills/flow-comet/scripts/system-test.mjs +1024 -11
- package/.flow-comet/skills/flow-comet/scripts/time-utils.mjs +133 -0
- package/.flow-comet/skills/flow-comet/scripts/workflow-guard.mjs +285 -227
- package/.flow-comet/skills/flow-comet/scripts/workflow-handoff.mjs +6 -4
- package/.flow-comet/skills/flow-comet/scripts/workflow-state.mjs +515 -31
- package/.flow-comet/skills/flow-comet-archive/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-change/SKILL.md +13 -1
- package/.flow-comet/skills/flow-comet-design/SKILL.md +6 -2
- package/.flow-comet/skills/flow-comet-dev/SKILL.md +3 -1
- package/.flow-comet/skills/flow-comet-evolve/SKILL.md +46 -11
- package/.flow-comet/skills/flow-comet-execute/SKILL.md +6 -4
- package/.flow-comet/skills/flow-comet-health/SKILL.md +57 -16
- package/.flow-comet/skills/flow-comet-integration/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-open/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-plan/SKILL.md +17 -6
- package/.flow-comet/skills/flow-comet-requirement/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-review/SKILL.md +7 -5
- package/.flow-comet/skills/flow-comet-subagent-execute/SKILL.md +12 -9
- package/.flow-comet/skills/flow-comet-task/SKILL.md +7 -3
- package/.flow-comet/skills/flow-comet-test/SKILL.md +2 -0
- package/.flow-comet/skills/flow-comet-ui-design/SKILL.md +28 -3
- package/.flow-comet/skills/flow-comet-verify/SKILL.md +7 -5
- package/README.md +45 -119
- package/package.json +1 -1
- package/scripts/dsh-bridge.mjs +2 -2
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// evolve.mjs — 架构沉淀同步(横向命令):只读扫描归档 change 的设计文档沉淀段 → 候选清单;
|
|
3
|
+
// 逐项应用 → patch 项目级文档 + 落 EVOLVE 报告 + 双落点时间戳。
|
|
4
|
+
//
|
|
5
|
+
// 用法:
|
|
6
|
+
// node evolve.mjs scan [--root <项目根>] [--stdout]
|
|
7
|
+
// node evolve.mjs apply <候选 id> [<候选 id> ...] [--root <项目根>] [--scanner <执行工具>] [--stdout]
|
|
8
|
+
// node evolve.mjs --help | -h
|
|
9
|
+
//
|
|
10
|
+
// 单一权威(L-067):「沉淀段在场」判定(hasSection9)与归档窗口判定(isArchivedAfterTimestamp)
|
|
11
|
+
// 一律 import time-utils.mjs;时间形态 / 解析 / 天差走 nowTimestamp / formatLocalDate /
|
|
12
|
+
// parseTimestamp / daysSince——本模块不内联第二份时间正则,也不自行拼接时间字符串。
|
|
13
|
+
// 「改写前备份」的命名族与失败处置走 state-schema.mjs 的 backupBeforeWrite(单一来源)——
|
|
14
|
+
// 本模块不再自持 `.bak-` 命名族与复制调用(第二处表达)。
|
|
15
|
+
// 模板段标题的归一走 route-node.mjs 导出的共享实现(normalizeHeading),不另起一份。
|
|
16
|
+
// 协议路径走 state-schema.mjs 的 resolveProtocolPathWithState(唯一选择器),不自持候选布局表。
|
|
17
|
+
// 侧命令 CLI 契约(parseSideCommandArgs)也落本模块:三条横向命令共用一份解析——
|
|
18
|
+
// 本模块在导入时不执行命令(另两条在导入时即跑 main),是唯一可被安全导入的一方。
|
|
19
|
+
//
|
|
20
|
+
// 只读边界:scan 零写入;apply 的写入面只有三处——项目级文档(CONTEXT.md / ARCHITECTURE.md)、
|
|
21
|
+
// .specs/evolve/ 下的报告、以及 state 的 last_evolve_at(经 workflow-state.mjs 的 config set
|
|
22
|
+
// 通道写入,本脚本不直写 state 文件)。扫描内容严格限定在归档设计文档的沉淀段。
|
|
23
|
+
|
|
24
|
+
import { spawnSync } from 'child_process';
|
|
25
|
+
import { promises as fs } from 'fs';
|
|
26
|
+
import path from 'path';
|
|
27
|
+
import { fileURLToPath } from 'url';
|
|
28
|
+
import { normalizeHeading } from './route-node.mjs';
|
|
29
|
+
import { readProtocolFile, validateProtocolSchema } from './protocol-utils.mjs';
|
|
30
|
+
import {
|
|
31
|
+
writeFileAtomic,
|
|
32
|
+
backupBeforeWrite,
|
|
33
|
+
EVOLVE_METADATA_SECTION,
|
|
34
|
+
EVOLVE_METADATA_FIELDS,
|
|
35
|
+
resolveProtocolPathWithState,
|
|
36
|
+
validateStateFields,
|
|
37
|
+
RUNTIME_DIR,
|
|
38
|
+
RUNTIME_STATE_FILE_NAME,
|
|
39
|
+
} from './state-schema.mjs';
|
|
40
|
+
import {
|
|
41
|
+
archiveDateFromName,
|
|
42
|
+
daysSince,
|
|
43
|
+
formatLocalDate,
|
|
44
|
+
hasSection9,
|
|
45
|
+
isArchivedAfterTimestamp,
|
|
46
|
+
nowTimestamp,
|
|
47
|
+
parseTimestamp,
|
|
48
|
+
EVOLVE_DUE_NEW_ARCHIVE_CHANGES,
|
|
49
|
+
EVOLVE_STALE_DAYS,
|
|
50
|
+
} from './time-utils.mjs';
|
|
51
|
+
|
|
52
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
53
|
+
const __dirname = path.dirname(__filename);
|
|
54
|
+
// 技能包根(协议默认落点与子进程 workflow-state.mjs 同源推导:脚本目录的上一级)
|
|
55
|
+
const packageRoot = path.resolve(__dirname, '..');
|
|
56
|
+
|
|
57
|
+
const SPECS_DIR = '.specs';
|
|
58
|
+
const ARCHIVE_DIR = 'archive';
|
|
59
|
+
const REPORT_DIR = 'evolve';
|
|
60
|
+
const DESIGN_FILE = 'DESIGN.md';
|
|
61
|
+
const CONTEXT_FILE = 'CONTEXT.md';
|
|
62
|
+
const ARCHITECTURE_FILE = 'ARCHITECTURE.md';
|
|
63
|
+
const DOC_CONTEXT = SPECS_DIR + '/' + CONTEXT_FILE;
|
|
64
|
+
const DOC_ARCHITECTURE = SPECS_DIR + '/' + ARCHITECTURE_FILE;
|
|
65
|
+
const STATE_SCRIPT = 'workflow-state.mjs';
|
|
66
|
+
// `## evolve 元数据` 的段名与三字段名来自 state-schema.mjs 的单一常量集(写方 = 本节 / 校验方 =
|
|
67
|
+
// context-init.mjs 的格式校验同源);段侧字段序即常量序,双落点首字段与 state 的 STATE_KEY 同名。
|
|
68
|
+
const EVOLVE_SECTION = EVOLVE_METADATA_SECTION;
|
|
69
|
+
const [STATE_KEY, SCANNER_FIELD, SUGGESTION_FIELD] = EVOLVE_METADATA_FIELDS;
|
|
70
|
+
const SOURCE_PREFIX = '来源 @.specs/' + ARCHIVE_DIR + '/';
|
|
71
|
+
|
|
72
|
+
// 候选落点:目标文档 + 目标段。段名按模板标题的前缀匹配(标题常带括注后缀)。
|
|
73
|
+
// 落点判定只看子段标题的关键词(上游把沉淀分五类:抽象 / 决策 / 契约 / 依赖 / 禁动清单)。
|
|
74
|
+
const TARGETS = {
|
|
75
|
+
abstract: { doc: DOC_CONTEXT, section: '既有抽象索引', level: 2, label: '既有抽象索引' },
|
|
76
|
+
decision: { doc: DOC_CONTEXT, section: '已锁决策', level: 2, label: '已锁决策' },
|
|
77
|
+
dependency: { doc: DOC_CONTEXT, section: '技术栈', level: 2, label: '技术栈' },
|
|
78
|
+
forbidden: { doc: DOC_CONTEXT, section: '禁动清单', level: 3, parent: '既有抽象索引', label: '既有抽象索引 · 禁动清单' },
|
|
79
|
+
contract: { doc: DOC_ARCHITECTURE, section: '跨模块契约', level: 2, label: '跨模块契约' },
|
|
80
|
+
};
|
|
81
|
+
const KIND_RULES = [
|
|
82
|
+
{ kind: 'forbidden', pattern: /禁动清单/ },
|
|
83
|
+
{ kind: 'abstract', pattern: /可复用抽象|抽象索引/ },
|
|
84
|
+
{ kind: 'dependency', pattern: /依赖/ },
|
|
85
|
+
{ kind: 'contract', pattern: /契约|跨模块|事件总线|API|Schema/ },
|
|
86
|
+
{ kind: 'decision', pattern: /技术决策|已锁决策|ADR/ },
|
|
87
|
+
];
|
|
88
|
+
const KIND_LABELS = { abstract: '抽象', decision: '决策', dependency: '依赖', forbidden: '禁动', contract: '契约' };
|
|
89
|
+
// 围栏块内的「无沉淀建议」声明——块整段为声明时不产出候选(表格行 / 列表项不走此判定)
|
|
90
|
+
const NO_SEDIMENT_BLOCK = /无架构层面沉淀建议|无沉淀建议|无新增可复用抽象/;
|
|
91
|
+
|
|
92
|
+
function fail(message) {
|
|
93
|
+
console.error('BLOCKED: ' + message);
|
|
94
|
+
process.exit(1);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function escapeRegExp(text) {
|
|
98
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function usage() {
|
|
102
|
+
return [
|
|
103
|
+
'用法:',
|
|
104
|
+
' node evolve.mjs scan [--root <项目根>] [--stdout]',
|
|
105
|
+
' node evolve.mjs apply <候选 id> [<候选 id> ...] [--root <项目根>] [--scanner <执行工具>] [--stdout]',
|
|
106
|
+
' node evolve.mjs --help | -h',
|
|
107
|
+
'说明:',
|
|
108
|
+
' --root <目录> 项目根(缺省 = 当前目录;`--root=<目录>` 等号形等价)',
|
|
109
|
+
' --scanner <文本> apply 落盘报告里的执行工具名(缺省 flow-comet-evolve)',
|
|
110
|
+
' --stdout scan 本就零写入且全量输出到标准输出;apply 时把本次追加进报告的内容原样输出',
|
|
111
|
+
' --help, -h 打印本用法后退出(不做任何读写)',
|
|
112
|
+
].join('\n');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---------- 侧命令 CLI 契约(单一来源) ----------
|
|
116
|
+
// 根相对 POSIX 路径标签:三条横向命令的 CLI 摘要行与工件段落都要把绝对路径显示成项目根相对形态
|
|
117
|
+
// (跨机器可读、可直接粘回命令行)。此前 evolve 内联、context-scan 自持一份同名助手——同一显示
|
|
118
|
+
// 决定的第二份表达;现由本模块(侧命令共享助手的既有落点)导出,三条命令同源消费。
|
|
119
|
+
export function relativeLabel(root, file) {
|
|
120
|
+
return path.relative(root, file).split(path.sep).join('/');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 三条横向命令(evolve / health / context-scan)共用本解析器:`--root <目录>` 与 `--root=<目录>`
|
|
124
|
+
// 两种形态、`--stdout`、`--help`/`-h`、未知参数**各只在此处表达一次**——此前三份自写脚手架必然分叉
|
|
125
|
+
// (一条不支持等号形、`--help` 只有一条有、错误构造三份各写一遍)。位置参数语义(evolve 的
|
|
126
|
+
// scan|apply 子命令与候选 id)与命令自有取值开关由调用方声明,本解析器不认识任何业务词元。
|
|
127
|
+
// 契约要点:用法错误一律 throw(各命令顶层错误处理决定前缀,退出码统一 1);`--help` 在位置参数
|
|
128
|
+
// 之前短路(子命令之后写 `--help` 也只看用法);取值开关悬空与未知参数一律可见报错,不静默忽略。
|
|
129
|
+
export function parseSideCommandArgs(argv, { usage: usageText, valueOptions = {}, positionals = null } = {}) {
|
|
130
|
+
if (typeof usageText !== 'string' || usageText.trim() === '') {
|
|
131
|
+
throw new Error('parseSideCommandArgs 需要非空用法文本(--help 与用法错误共用同一份)');
|
|
132
|
+
}
|
|
133
|
+
const options = { root: process.cwd(), rootArg: null, stdout: false, help: false, values: {}, tokens: [] };
|
|
134
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
135
|
+
const token = argv[i];
|
|
136
|
+
if (token === '--help' || token === '-h') { options.help = true; continue; }
|
|
137
|
+
if (token === '--stdout') { options.stdout = true; continue; }
|
|
138
|
+
if (token === '--root' || token.startsWith('--root=')) {
|
|
139
|
+
const value = token === '--root' ? argv[i + 1] : token.slice('--root='.length);
|
|
140
|
+
if (typeof value !== 'string' || value.trim() === '') throw new Error('--root 需要一个目录参数\n' + usageText);
|
|
141
|
+
options.root = path.resolve(value.trim());
|
|
142
|
+
options.rootArg = value;
|
|
143
|
+
if (token === '--root') i += 1;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const flag = Object.keys(valueOptions).find((name) => token === name || token.startsWith(name + '='));
|
|
147
|
+
if (flag) {
|
|
148
|
+
const value = token === flag ? argv[i + 1] : token.slice(flag.length + 1);
|
|
149
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
150
|
+
throw new Error(flag + ' 需要' + valueOptions[flag] + '\n' + usageText);
|
|
151
|
+
}
|
|
152
|
+
options.values[flag] = value;
|
|
153
|
+
if (token === flag) i += 1;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (token.startsWith('-') && token !== '-') throw new Error('未知参数: ' + token + '\n' + usageText);
|
|
157
|
+
options.tokens.push(token);
|
|
158
|
+
}
|
|
159
|
+
if (options.help) return options;
|
|
160
|
+
if (positionals) positionals(options);
|
|
161
|
+
return options;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// evolve 的位置参数语义:首词元是子命令,apply 的其余词元是候选 id(scan 不接受位置参数)。
|
|
165
|
+
// 返回 { error } 形态沿用本命令既有约定(main 走 fail() → BLOCKED + exit 1)。
|
|
166
|
+
export function parseArgs(argv) {
|
|
167
|
+
const options = parseSideCommandArgs(argv, {
|
|
168
|
+
usage: usage(),
|
|
169
|
+
valueOptions: { '--scanner': '一段文本' },
|
|
170
|
+
positionals: (parsed) => {
|
|
171
|
+
parsed.command = parsed.tokens[0] ?? '';
|
|
172
|
+
parsed.ids = parsed.tokens.slice(1);
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
options.scanner = options.values['--scanner'] ?? 'flow-comet-evolve';
|
|
176
|
+
if (options.help) return options;
|
|
177
|
+
if (options.command !== 'scan' && options.command !== 'apply') {
|
|
178
|
+
return { error: '未知子命令: ' + (options.command || '(空)') + '\n' + usage() };
|
|
179
|
+
}
|
|
180
|
+
if (options.command === 'scan' && options.ids.length > 0) {
|
|
181
|
+
return { error: 'scan 不接受位置参数: ' + options.ids[0] };
|
|
182
|
+
}
|
|
183
|
+
if (options.command === 'apply' && options.ids.length === 0) {
|
|
184
|
+
return { error: 'apply 需要至少一个候选 id\n' + usage() };
|
|
185
|
+
}
|
|
186
|
+
return options;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ---------- 段定位(Markdown 结构操作,非沉淀段判据) ----------
|
|
190
|
+
|
|
191
|
+
// 行尾归一:CRLF 文档按行切开后每行尾部带 `\r`,而行首/行尾锚定的正则里 `.` 不匹配 `\r`
|
|
192
|
+
// (`## 名称\r` 会整行失配)——解析前统一剥掉行尾回退符,写回时再按文档自身的行尾约定拼。
|
|
193
|
+
function stripCr(line) {
|
|
194
|
+
return String(line ?? '').replace(/\r$/, '');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function headingOf(line) {
|
|
198
|
+
const matched = /^(#{1,6})[ \t]+(.+?)[ \t]*$/.exec(stripCr(line));
|
|
199
|
+
if (!matched) return null;
|
|
200
|
+
return { level: matched[1].length, title: normalizeHeading(matched[2]) };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function sectionEnd(lines, start, level, to) {
|
|
204
|
+
for (let i = start + 1; i < to; i++) {
|
|
205
|
+
const heading = headingOf(lines[i]);
|
|
206
|
+
if (heading && heading.level <= level) return i;
|
|
207
|
+
}
|
|
208
|
+
return to;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 按标题层级定位段;标题以给定名前缀开头即命中(模板标题带括注后缀,归一委托共享实现)
|
|
212
|
+
function findSection(lines, name, level, from = 0, to = lines.length) {
|
|
213
|
+
const wanted = normalizeHeading(name);
|
|
214
|
+
if (wanted === '') return null;
|
|
215
|
+
for (let i = from; i < to; i++) {
|
|
216
|
+
const heading = headingOf(lines[i]);
|
|
217
|
+
if (!heading || heading.level !== level) continue;
|
|
218
|
+
if (!heading.title.startsWith(wanted)) continue;
|
|
219
|
+
return { start: i, end: sectionEnd(lines, i, level, to) };
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 段内插入点:段体末尾,但跳过尾部的空行、分隔线与引用注记(条目插在正文之后、尾注之前)
|
|
225
|
+
function bodyInsertIndex(lines, section) {
|
|
226
|
+
let at = section.end;
|
|
227
|
+
while (at > section.start + 1) {
|
|
228
|
+
const text = lines[at - 1].trim();
|
|
229
|
+
if (text === '' || text === '---' || text.startsWith('>')) { at -= 1; continue; }
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
return at;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function locateInsertion(lines, target) {
|
|
236
|
+
if (target.parent) {
|
|
237
|
+
const parent = findSection(lines, target.parent, 2);
|
|
238
|
+
if (parent) {
|
|
239
|
+
const sub = findSection(lines, target.section, target.level, parent.start + 1, parent.end);
|
|
240
|
+
if (sub) return sub;
|
|
241
|
+
return parent;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return findSection(lines, target.section, target.level);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ---------- 沉淀段解析(严格限定在沉淀段切片内) ----------
|
|
248
|
+
|
|
249
|
+
// 切出沉淀段:起始行由 hasSection9 判定(单一权威),段体止于同级或更高级标题。
|
|
250
|
+
export function locateSedimentSection(text) {
|
|
251
|
+
const lines = String(text ?? '').split('\n');
|
|
252
|
+
const start = lines.findIndex((line) => hasSection9(line));
|
|
253
|
+
if (start < 0) return null;
|
|
254
|
+
const heading = /^(#{1,6})/.exec(lines[start]);
|
|
255
|
+
const level = heading ? heading[1].length : 2;
|
|
256
|
+
return { lines: lines.slice(start, sectionEnd(lines, start, level, lines.length)) };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function isTableSeparator(line) {
|
|
260
|
+
return /^\s*\|[\s:|-]+\|\s*$/.test(line);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function splitTableRow(line) {
|
|
264
|
+
return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim());
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// 段内候选抽取:表格数据行一条、列表项一条、围栏块整块一条(块取首行作条目)。
|
|
268
|
+
// 子段标题决定落点类别;围栏块内整段只有「无沉淀建议」时不产出候选(表格行与列表项本身就是
|
|
269
|
+
// 逐条陈述,不做内容过滤——「无新增」一类条目照实列出,由评审逐条决定去留)。
|
|
270
|
+
export function parseSedimentCandidates(sectionLines) {
|
|
271
|
+
const found = [];
|
|
272
|
+
let subsection = '';
|
|
273
|
+
let i = 0;
|
|
274
|
+
const push = (cells) => {
|
|
275
|
+
const parts = cells.map((cell) => String(cell).trim()).filter((cell) => cell.length > 0);
|
|
276
|
+
if (parts.length === 0) return;
|
|
277
|
+
found.push({ subsection, title: parts[0], detail: parts.slice(1).join(' · ') });
|
|
278
|
+
};
|
|
279
|
+
while (i < sectionLines.length) {
|
|
280
|
+
const line = stripCr(sectionLines[i]);
|
|
281
|
+
const heading = /^(#{2,6})[ \t]+(.+?)[ \t]*$/.exec(line);
|
|
282
|
+
if (heading) { subsection = heading[2].trim(); i += 1; continue; }
|
|
283
|
+
if (/^\s*\|/.test(line)) {
|
|
284
|
+
const rows = [];
|
|
285
|
+
while (i < sectionLines.length && /^\s*\|/.test(stripCr(sectionLines[i]))) {
|
|
286
|
+
if (!isTableSeparator(stripCr(sectionLines[i]))) rows.push(splitTableRow(stripCr(sectionLines[i])));
|
|
287
|
+
i += 1;
|
|
288
|
+
}
|
|
289
|
+
for (const cells of rows.slice(1)) push(cells); // 首行是表头
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (/^\s*```/.test(line)) {
|
|
293
|
+
const block = [];
|
|
294
|
+
i += 1;
|
|
295
|
+
while (i < sectionLines.length && !/^\s*```/.test(stripCr(sectionLines[i]))) {
|
|
296
|
+
block.push(stripCr(sectionLines[i]).trim());
|
|
297
|
+
i += 1;
|
|
298
|
+
}
|
|
299
|
+
i += 1;
|
|
300
|
+
const content = block.filter((text) => text.length > 0);
|
|
301
|
+
// 块首行若是列表项,剥掉列表符号后作条目(条目文本不带 Markdown 列表标记)
|
|
302
|
+
const first = content.length > 0 ? content[0].replace(/^[-*][ \t]+/, '') : '';
|
|
303
|
+
if (first.length > 0 && !NO_SEDIMENT_BLOCK.test(content.join(' '))) push([first]);
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const bullet = /^\s*[-*][ \t]+(.*)$/.exec(line);
|
|
307
|
+
if (bullet) {
|
|
308
|
+
const parts = [bullet[1].trim()];
|
|
309
|
+
i += 1;
|
|
310
|
+
while (i < sectionLines.length && /^\s+\S/.test(stripCr(sectionLines[i]))
|
|
311
|
+
&& !/^\s*[-*][ \t]+/.test(stripCr(sectionLines[i])) && !/^\s*\|/.test(stripCr(sectionLines[i]))) {
|
|
312
|
+
parts.push(stripCr(sectionLines[i]).trim());
|
|
313
|
+
i += 1;
|
|
314
|
+
}
|
|
315
|
+
push([parts.join(' ')]);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
i += 1;
|
|
319
|
+
}
|
|
320
|
+
return found;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function targetFor(subsection) {
|
|
324
|
+
for (const rule of KIND_RULES) {
|
|
325
|
+
if (rule.pattern.test(subsection)) return { kind: rule.kind, ...TARGETS[rule.kind] };
|
|
326
|
+
}
|
|
327
|
+
return { kind: 'abstract', ...TARGETS.abstract };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function candidateEntry(candidate) {
|
|
331
|
+
const detail = candidate.detail ? ' · ' + candidate.detail : '';
|
|
332
|
+
return '- ' + candidate.title + detail + ' · ' + SOURCE_PREFIX + candidate.dirName + '/' + DESIGN_FILE;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function candidateComment(candidate, ts) {
|
|
336
|
+
return ' <!-- flow-comet-evolve ' + formatLocalDate(parseTimestamp(ts)) + ': from ' + candidate.id + ' -->';
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// 幂等判据的「日期无关」身份片段:标记注释的形态是 `<!-- flow-comet-evolve <当次运行的本地日期>:
|
|
340
|
+
// from <id> -->`——日期分量**每次运行都不同**,拿整条注释做包含判定,隔天重跑必然失配;此时若条目
|
|
341
|
+
// 文本又被人工改写过(`body.includes(entry)` 同时失配),同一候选就会被二次插入。判定只取与时刻
|
|
342
|
+
// 无关的身份段:写盘形态不变(既有的旧标记同样被识别,不回改用户文档),判据也不再随日期失效。
|
|
343
|
+
function candidateMarker(candidate) {
|
|
344
|
+
return ': from ' + candidate.id + ' -->';
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function nextSuggestion() {
|
|
348
|
+
return '约 ' + EVOLVE_STALE_DAYS + ' 天后,或新增 ≥ ' + EVOLVE_DUE_NEW_ARCHIVE_CHANGES + ' 个带 §9 内容的 change 之后';
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------- 扫描 ----------
|
|
352
|
+
|
|
353
|
+
async function readText(file) {
|
|
354
|
+
try { return await fs.readFile(file, 'utf8'); } catch { return null; }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function pathExists(target) {
|
|
358
|
+
try { await fs.access(target); return true; } catch { return false; }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 写盘走状态层单一来源的原子写(state-schema.mjs 的 writeFileAtomic):目标文档要么是旧内容、
|
|
362
|
+
// 要么是新内容,不会留下被截断的半写状态。
|
|
363
|
+
// state 读取三态(**单一实现**:本导出同时是 context-scan 的读入口):**不在场**(文件缺失)/ 可读 /
|
|
364
|
+
// **损坏**(在场但解析不出状态对象)。两者必须分开——把损坏折叠成「没有状态」,增量窗口会静默退化
|
|
365
|
+
// 为全量,措辞还把不可信状态说成正常冷启动。读失败(权限 / 目录占位)同样按不可信处理,不冒充
|
|
366
|
+
// 「不在场」。调用方按 `exists && state === null` 判损坏并 fail-closed。
|
|
367
|
+
export async function readStateInfo(root) {
|
|
368
|
+
const file = path.join(root, RUNTIME_DIR, RUNTIME_STATE_FILE_NAME);
|
|
369
|
+
let raw;
|
|
370
|
+
try {
|
|
371
|
+
raw = await fs.readFile(file, 'utf8');
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error && error.code === 'ENOENT') return { exists: false, state: null };
|
|
374
|
+
return { exists: true, state: null };
|
|
375
|
+
}
|
|
376
|
+
let parsed;
|
|
377
|
+
try {
|
|
378
|
+
parsed = JSON.parse(raw.replace(/^\uFEFF/, ''));
|
|
379
|
+
} catch {
|
|
380
|
+
return { exists: true, state: null };
|
|
381
|
+
}
|
|
382
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
383
|
+
return { exists: true, state: null };
|
|
384
|
+
}
|
|
385
|
+
return { exists: true, state: parsed };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// 损坏态的统一处置(单一表达):状态不可信 → fail-closed,绝不按「首次运行」放行,也不写任何东西。
|
|
389
|
+
function unreadableStateError(root) {
|
|
390
|
+
return new Error('引擎状态文件在场但无法解析(' + RUNTIME_DIR + '/' + RUNTIME_STATE_FILE_NAME
|
|
391
|
+
+ ',根 ' + root + ')——本次零写入、零候选;先修复该文件再重跑'
|
|
392
|
+
+ '(项目本未接入时删除它,即回到「state 不在场」口径)');
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export async function scanProject(root) {
|
|
396
|
+
const stateInfo = await readStateInfo(root);
|
|
397
|
+
if (stateInfo.exists && stateInfo.state === null) throw unreadableStateError(root);
|
|
398
|
+
const stored = stateInfo.state && typeof stateInfo.state[STATE_KEY] === 'string'
|
|
399
|
+
? stateInfo.state[STATE_KEY].trim() : '';
|
|
400
|
+
const baseline = stored !== '' && !Number.isNaN(parseTimestamp(stored)) ? stored : '';
|
|
401
|
+
// 三态措辞互斥(单一表达):「首次运行」只限「state 可读且字段缺席」——不在场与损坏各有自己的
|
|
402
|
+
// 说法,任何一个都不得冒充冷启动(措辞即判定,误导性措辞等于把缺陷藏起来)。
|
|
403
|
+
const baselineNote = baseline !== '' ? ''
|
|
404
|
+
: !stateInfo.exists ? '无基线(state 不在场——项目未接入,按全量扫描)'
|
|
405
|
+
: stored === '' ? '无基线(首次运行,全量扫描)'
|
|
406
|
+
: '上次沉淀时间不可解析(按全量扫描)';
|
|
407
|
+
|
|
408
|
+
const archiveRoot = path.join(root, SPECS_DIR, ARCHIVE_DIR);
|
|
409
|
+
let names = [];
|
|
410
|
+
try {
|
|
411
|
+
names = (await fs.readdir(archiveRoot, { withFileTypes: true }))
|
|
412
|
+
.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
413
|
+
} catch { names = []; }
|
|
414
|
+
|
|
415
|
+
const changes = [];
|
|
416
|
+
for (const dirName of names) {
|
|
417
|
+
const text = await readText(path.join(archiveRoot, dirName, DESIGN_FILE));
|
|
418
|
+
const section = text === null ? null : locateSedimentSection(text);
|
|
419
|
+
const parsed = section === null ? [] : parseSedimentCandidates(section.lines);
|
|
420
|
+
const candidates = parsed.map((item, index) => ({
|
|
421
|
+
...item,
|
|
422
|
+
...targetFor(item.subsection),
|
|
423
|
+
id: dirName + '#' + (index + 1),
|
|
424
|
+
dirName,
|
|
425
|
+
}));
|
|
426
|
+
changes.push({
|
|
427
|
+
dirName,
|
|
428
|
+
archiveDate: archiveDateFromName(dirName),
|
|
429
|
+
hasDesign: text !== null,
|
|
430
|
+
hasSediment: section !== null,
|
|
431
|
+
candidates,
|
|
432
|
+
inWindow: baseline === '' ? true : isArchivedAfterTimestamp(dirName, baseline),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
const scanned = changes.filter((change) => change.inWindow);
|
|
436
|
+
return {
|
|
437
|
+
root,
|
|
438
|
+
state: stateInfo.state,
|
|
439
|
+
stateExists: stateInfo.exists,
|
|
440
|
+
baseline,
|
|
441
|
+
baselineNote,
|
|
442
|
+
changes,
|
|
443
|
+
scanned,
|
|
444
|
+
candidates: scanned.flatMap((change) => change.candidates),
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function describeWindow(plan) {
|
|
449
|
+
const since = plan.baseline === ''
|
|
450
|
+
? '窗口 起始 = ' + plan.baselineNote
|
|
451
|
+
: '窗口 起始 = ' + plan.baseline + '(距今 ' + daysSince(plan.baseline).toFixed(1) + ' 天)';
|
|
452
|
+
const withSediment = plan.scanned.filter((change) => change.hasSediment).length;
|
|
453
|
+
return since + ' · 归档 ' + plan.changes.length + ' 个 · 窗口内 ' + plan.scanned.length
|
|
454
|
+
+ ' 个 · 含沉淀段 ' + withSediment + ' 个';
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function changeSummary(change) {
|
|
458
|
+
if (!change.hasDesign) return change.dirName + '(无 ' + DESIGN_FILE + ')';
|
|
459
|
+
if (!change.hasSediment) return change.dirName + '(无沉淀段)';
|
|
460
|
+
return change.dirName + '(候选 ' + change.candidates.length + ' 条)';
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function candidateLine(candidate) {
|
|
464
|
+
const target = candidate.doc + '「' + candidate.label + '」';
|
|
465
|
+
const detail = candidate.detail ? ' · ' + candidate.detail : '';
|
|
466
|
+
return ' [' + candidate.id + '] ' + KIND_LABELS[candidate.kind] + ' · ' + candidate.title + detail
|
|
467
|
+
+ '\n 目标 ' + target;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function printScan(plan, out = console) {
|
|
471
|
+
out.log('EVOLVE: 扫描 ' + plan.root + '/' + SPECS_DIR + '/' + ARCHIVE_DIR + '/*/' + DESIGN_FILE
|
|
472
|
+
+ ' 的沉淀段(只读,零写入)');
|
|
473
|
+
out.log('EVOLVE: ' + describeWindow(plan));
|
|
474
|
+
if (plan.candidates.length === 0) {
|
|
475
|
+
out.log('EVOLVE: 候选 0 条(窗口内没有待沉淀条目)');
|
|
476
|
+
} else {
|
|
477
|
+
out.log('候选清单(' + plan.candidates.length + ' 条):');
|
|
478
|
+
for (const candidate of plan.candidates) out.log(candidateLine(candidate));
|
|
479
|
+
const missingDocs = [];
|
|
480
|
+
for (const doc of new Set(plan.candidates.map((candidate) => candidate.doc))) {
|
|
481
|
+
if (!(await pathExists(path.join(plan.root, doc)))) missingDocs.push(doc);
|
|
482
|
+
}
|
|
483
|
+
for (const doc of missingDocs) {
|
|
484
|
+
out.log('EVOLVE: 目标文档不在场 ' + doc + '——该文档内的候选在 apply 前需先建立它');
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (plan.scanned.length > 0) {
|
|
488
|
+
out.log('EVOLVE: 已扫 change 清单:' + plan.scanned.map(changeSummary).join(' · '));
|
|
489
|
+
}
|
|
490
|
+
out.log('EVOLVE: 应用请执行 evolve.mjs apply <id> --root <根>(未应用的候选不会写入)');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// ---------- 应用 ----------
|
|
494
|
+
|
|
495
|
+
function fieldLine(key, value) {
|
|
496
|
+
return '- **' + key + '**: `' + value + '`';
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// 文件末尾追加「块」:`split('\n')` 对**以换行收尾**的文档留有一个零长度哨兵元素——它不是文档里的
|
|
500
|
+
// 一行,而是「最后一行终结符」的占位。直接在哨兵之后 push 会拼出一条**裸 LF 空行**:CRLF 文档里
|
|
501
|
+
// 同一文件出现两种行尾(评审实测 `-->\r\n\n\r\n---`),且末行终结符退化成一个孤立的 `\r`。
|
|
502
|
+
// 追加前摘下哨兵、追加后放回 —— 整篇行尾一致,末尾换行约定不变(LF 文档同样收敛为**单空行**)。
|
|
503
|
+
function appendBlock(lines, eol, blockLines) {
|
|
504
|
+
const sentinel = lines.length > 0 && lines[lines.length - 1] === '' ? lines.pop() : null;
|
|
505
|
+
for (const line of blockLines) lines.push(line + eol);
|
|
506
|
+
if (sentinel !== null) lines.push(sentinel);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// 双落点之段侧:在场则就地更新三字段,缺席则新建成段(段为可选段,缺席不报错)。eol = 文档行尾约定
|
|
510
|
+
function upsertEvolveSection(lines, ts, scanner, eol = '') {
|
|
511
|
+
const fields = [[STATE_KEY, ts], [SCANNER_FIELD, scanner], [SUGGESTION_FIELD, nextSuggestion()]];
|
|
512
|
+
const section = findSection(lines, EVOLVE_SECTION, 2);
|
|
513
|
+
if (!section) {
|
|
514
|
+
const lastText = [...lines].reverse().find((line) => line.trim() !== '') ?? '';
|
|
515
|
+
const block = [];
|
|
516
|
+
if (lastText.trim() !== '---') block.push('', '---');
|
|
517
|
+
block.push('', '## ' + EVOLVE_SECTION, '', ...fields.map(([key, value]) => fieldLine(key, value)));
|
|
518
|
+
appendBlock(lines, eol, block);
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const missing = [];
|
|
522
|
+
for (const [key, value] of fields) {
|
|
523
|
+
const pattern = new RegExp('^\\s*[-*]\\s*\\*\\*' + escapeRegExp(key) + '\\*\\*\\s*:');
|
|
524
|
+
let replaced = false;
|
|
525
|
+
for (let i = section.start + 1; i < section.end; i++) {
|
|
526
|
+
if (pattern.test(lines[i])) { lines[i] = fieldLine(key, value) + eol; replaced = true; break; }
|
|
527
|
+
}
|
|
528
|
+
if (!replaced) missing.push(fieldLine(key, value) + eol);
|
|
529
|
+
}
|
|
530
|
+
if (missing.length > 0) lines.splice(bodyInsertIndex(lines, section), 0, ...missing);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// 落盘一个目标文档:备份(共享助手,单一来源)→ 追加条目 → 同批更新元数据段(仅 CONTEXT.md)。
|
|
534
|
+
// 插入行沿用文档自身的行尾约定——CRLF 文档里插入 LF 行会造成同一文件两种行尾。
|
|
535
|
+
async function patchDocument(root, doc, entries, ts, scanner, out = console) {
|
|
536
|
+
const file = path.join(root, doc);
|
|
537
|
+
const original = await fs.readFile(file, 'utf8');
|
|
538
|
+
const eol = original.includes('\r\n') ? '\r' : '';
|
|
539
|
+
const lines = original.split('\n');
|
|
540
|
+
const written = [];
|
|
541
|
+
const present = [];
|
|
542
|
+
for (const candidate of entries) {
|
|
543
|
+
const entry = candidateEntry(candidate);
|
|
544
|
+
const insertion = locateInsertion(lines, candidate);
|
|
545
|
+
if (!insertion) {
|
|
546
|
+
throw new Error('目标段未找到: ' + candidate.doc + '「' + candidate.label + '」');
|
|
547
|
+
}
|
|
548
|
+
const body = lines.slice(insertion.start + 1, insertion.end).join('\n');
|
|
549
|
+
if (body.includes(entry) || body.includes(candidateMarker(candidate))) {
|
|
550
|
+
present.push(candidate);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
lines.splice(bodyInsertIndex(lines, insertion), 0, entry + eol, candidateComment(candidate, ts) + eol);
|
|
554
|
+
written.push(candidate);
|
|
555
|
+
out.log('EVOLVE-APPLY: [' + candidate.id + '] → ' + candidate.doc + '「' + candidate.label + '」');
|
|
556
|
+
}
|
|
557
|
+
if (doc === DOC_CONTEXT) upsertEvolveSection(lines, ts, scanner, eol);
|
|
558
|
+
const updated = lines.join('\n');
|
|
559
|
+
if (updated !== original) {
|
|
560
|
+
await backupBeforeWrite(file, ts);
|
|
561
|
+
await writeFileAtomic(file, updated);
|
|
562
|
+
}
|
|
563
|
+
return { written, present };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function reportBlocks(plan, ts, requested, applied, present) {
|
|
567
|
+
const lines = [];
|
|
568
|
+
lines.push('## 扫描范围', '');
|
|
569
|
+
lines.push('- 起始:' + (plan.baseline === ''
|
|
570
|
+
? plan.baselineNote + '(窗口内 = 全部归档 change)'
|
|
571
|
+
: plan.baseline + '(距今 ' + daysSince(plan.baseline).toFixed(1) + ' 天)之后归档的 change'));
|
|
572
|
+
lines.push('- 归档 ' + plan.changes.length + ' 个 · 窗口内 ' + plan.scanned.length + ' 个 · 含沉淀段 '
|
|
573
|
+
+ plan.scanned.filter((change) => change.hasSediment).length + ' 个');
|
|
574
|
+
lines.push('- 已扫 change 清单:', '');
|
|
575
|
+
lines.push(' | 归档 change | 归档日期 | 沉淀段 | 候选 |', ' |---|---|---|---|');
|
|
576
|
+
for (const change of plan.scanned) {
|
|
577
|
+
lines.push(' | ' + change.dirName + ' | ' + (change.archiveDate ?? '未按日期命名') + ' | '
|
|
578
|
+
+ (change.hasDesign ? (change.hasSediment ? '有' : '无') : '无设计文档') + ' | ' + change.candidates.length + ' |');
|
|
579
|
+
}
|
|
580
|
+
lines.push('', '## 候选汇总', '');
|
|
581
|
+
lines.push('- 候选 ' + plan.candidates.length + ' 条 · 本次应用 ' + applied.length + ' 条 · 未应用 '
|
|
582
|
+
+ (plan.candidates.length - applied.length) + ' 条');
|
|
583
|
+
lines.push('', '## 应用 patch', '');
|
|
584
|
+
if (applied.length === 0) {
|
|
585
|
+
lines.push('- (无——本次没有新增写入;已在场条目见下方跳过项)');
|
|
586
|
+
} else {
|
|
587
|
+
for (const candidate of applied) {
|
|
588
|
+
lines.push('- [' + candidate.id + '] → `' + candidate.doc + '`「' + candidate.label + '」');
|
|
589
|
+
// 条目文本自带列表符号(candidateEntry 的 `- ` 前缀)——这里只加**缩进**,不再叠一层 `- `:
|
|
590
|
+
// ` - - <条目>` 会被 Markdown 渲染成「空壳父项 + 子项」两条,报告读者数不清应用了几条。
|
|
591
|
+
lines.push(' ' + candidateEntry(candidate));
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
lines.push('', '## 跳过项 + 理由', '');
|
|
595
|
+
if (present.length === 0) {
|
|
596
|
+
lines.push('- (无)');
|
|
597
|
+
} else {
|
|
598
|
+
for (const candidate of present) {
|
|
599
|
+
lines.push('- [' + candidate.id + '] 目标段已存在该条目(重复应用按幂等处理,未重复写入)');
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
lines.push('', '## 未应用项(保留在报告中,可凭 id 继续 apply)', '');
|
|
603
|
+
const pending = plan.candidates.filter((candidate) => !requested.some((item) => item.id === candidate.id));
|
|
604
|
+
if (pending.length === 0) {
|
|
605
|
+
lines.push('- (无)');
|
|
606
|
+
} else {
|
|
607
|
+
for (const candidate of pending) {
|
|
608
|
+
lines.push('- [' + candidate.id + '] ' + KIND_LABELS[candidate.kind] + ' · ' + candidate.title
|
|
609
|
+
+ ' → `' + candidate.doc + '`「' + candidate.label + '」');
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
lines.push('', '## 双落点时间戳', '');
|
|
613
|
+
lines.push('- `state.' + STATE_KEY + '` = `' + ts + '`(经 ' + STATE_SCRIPT + ' 的 config set 通道写入)');
|
|
614
|
+
lines.push('- `' + DOC_CONTEXT + '`「## ' + EVOLVE_SECTION + '」= `' + ts + '`(同批写入,取值一致;冲突以 state 为准)');
|
|
615
|
+
lines.push('', '## 下次建议同步时间', '');
|
|
616
|
+
lines.push('- ' + nextSuggestion());
|
|
617
|
+
lines.push('');
|
|
618
|
+
return lines;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function writeReport(root, plan, ts, requested, applied, present) {
|
|
622
|
+
const date = formatLocalDate(parseTimestamp(ts));
|
|
623
|
+
const dir = path.join(root, SPECS_DIR, REPORT_DIR);
|
|
624
|
+
await fs.mkdir(dir, { recursive: true });
|
|
625
|
+
const file = path.join(dir, date + '-EVOLVE.md');
|
|
626
|
+
const exists = await pathExists(file);
|
|
627
|
+
const blocks = reportBlocks(plan, ts, requested, applied, present);
|
|
628
|
+
const body = exists
|
|
629
|
+
? ['', '---', '', '> 运行 ' + ts + ' · 应用 ' + applied.length + ' 条(在场 ' + present.length + ' 条)', '', ...blocks].join('\n')
|
|
630
|
+
: ['# 架构演进同步 · ' + date, '', ...blocks].join('\n');
|
|
631
|
+
await fs.appendFile(file, body, 'utf8');
|
|
632
|
+
// 本次追加的正文回传调用方:`--stdout` 原样输出**本次写入的内容**(与落盘块逐字节相同,
|
|
633
|
+
// 不是一个重新渲染的近似物——重渲染会与落盘漂移,恰好是「--stdout 与落盘一致」的反面)。
|
|
634
|
+
return { file, body };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// state 通道的协议路径(单一来源):子进程 workflow-state.mjs 的受保护读取要求协议文件位于项目根内,
|
|
638
|
+
// 而「协议在哪」的唯一权威是 state-schema.mjs 的 resolveProtocolPathWithState(state.protocolPath >
|
|
639
|
+
// FLOW_COMET_PROTOCOL 环境变量 > 内置默认,与 guard 同一入口)。本模块只把该选择结果透传给子进程
|
|
640
|
+
// (FLOW_COMET_PROTOCOL),**不再自持候选布局表**:那张表是第二套「协议在哪」的表达——state 已绑定
|
|
641
|
+
// 协议的项目会被它盖过(绑定静默失效,判定落到另一份协议上),布局变化也无人提醒。
|
|
642
|
+
function writeStateTimestamp(root, ts, state, out = console) {
|
|
643
|
+
const resolved = resolveProtocolPathWithState({ packageRoot, runRoot: root, state, cliArgs: [] });
|
|
644
|
+
const result = spawnSync(process.execPath, [path.join(__dirname, STATE_SCRIPT), 'config', 'set', STATE_KEY, ts], {
|
|
645
|
+
cwd: root,
|
|
646
|
+
env: { ...process.env, FLOW_COMET_PROTOCOL: resolved.protocolPath },
|
|
647
|
+
encoding: 'utf8',
|
|
648
|
+
});
|
|
649
|
+
const text = ((result.stdout ?? '') + (result.stderr ?? '')).trim();
|
|
650
|
+
if (text !== '') out.log(text);
|
|
651
|
+
if (result.status !== 0) {
|
|
652
|
+
throw new Error('state 写入通道失败(时间戳未推进;项目级文档已落盘、报告未落盘,重跑同一命令按幂等处理)'
|
|
653
|
+
+ '——协议路径来源 ' + resolved.source + '(' + resolved.protocolPath + '),按 state.protocolPath > '
|
|
654
|
+
+ 'FLOW_COMET_PROTOCOL > 内置默认的顺序解析且不回退候选布局:请修正 state.protocolPath'
|
|
655
|
+
+ ' 或把它指向项目内的协议副本后重试');
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// state 通道预检(与 validateInsertions 同址、同理由:写入前全验,避免「第一份已写、第二处抛错」的
|
|
660
|
+
// 半成品)。目标文档落盘**不可回滚**,而 state 通道排在文档之后——通道不可用时先写的文档就成了半成品
|
|
661
|
+
// (条目已在场、`## evolve 元数据` 段已推进,state 却停在原值,双落点被拆成两半)。这里在任何文档改动
|
|
662
|
+
// 之前把通道的两条确定性闸门各走一遍:① 协议能不能用(受保护读取 + schema 校验——与子进程
|
|
663
|
+
// workflow-state.mjs 的 main 首两步同源);② 本次要写入的 state 字段合不合法(validateStateFields——
|
|
664
|
+
// 与子进程 writeState 同一判据)。判据一律**消费单一来源**,本模块不复刻第二份「通道能不能用」的实现。
|
|
665
|
+
// 预检通过后通道仍可能因 I/O 失败(磁盘满 / 权限 / 占用)——那部分不可预判,故失败消息如实分述,
|
|
666
|
+
// 不谎称「零改动」。
|
|
667
|
+
async function preflightStateChannel(root, ts, state) {
|
|
668
|
+
const resolved = resolveProtocolPathWithState({ packageRoot, runRoot: root, state, cliArgs: [] });
|
|
669
|
+
let reason = null;
|
|
670
|
+
let guidance = '按 state.protocolPath > FLOW_COMET_PROTOCOL > 内置默认的顺序解析且不回退候选布局:'
|
|
671
|
+
+ '请修正 state.protocolPath 或把它指向项目内的协议副本后重试';
|
|
672
|
+
try {
|
|
673
|
+
validateProtocolSchema(await readProtocolFile(root, resolved.protocolPath));
|
|
674
|
+
} catch (error) {
|
|
675
|
+
reason = error && error.message ? error.message : String(error);
|
|
676
|
+
}
|
|
677
|
+
if (reason === null) {
|
|
678
|
+
const projected = { ...(state && typeof state === 'object' ? state : {}), [STATE_KEY]: ts };
|
|
679
|
+
const bad = validateStateFields(projected);
|
|
680
|
+
if (bad.length > 0) {
|
|
681
|
+
reason = 'state 字段校验不通过: ' + bad.join(', ');
|
|
682
|
+
guidance = '先修正上述 state 字段再重试(本次写入 ' + STATE_KEY + ')';
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (reason === null) return;
|
|
686
|
+
fail('state 写入通道失败(写入前预检不通过:' + reason + ')——本次零文档改动(写入前全验,不留半成品);'
|
|
687
|
+
+ '协议路径来源 ' + resolved.source + '(' + resolved.protocolPath + '),' + guidance);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
async function runScan(options, out = console) {
|
|
691
|
+
const plan = await scanProject(options.root);
|
|
692
|
+
await printScan(plan, out);
|
|
693
|
+
return plan;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// 写入前预检(两道,均在**任何文档改动之前**否决,预检失败即零改动退出):
|
|
697
|
+
// ① 每个候选的目标段都能定位——多目标文档时先全验后写,避免「第一份已写、第二份抛错」的半成品;
|
|
698
|
+
// ② state 通道可用(协议 + 字段两条确定性闸门,见 preflightStateChannel)。
|
|
699
|
+
async function validateInsertions(root, requested) {
|
|
700
|
+
const texts = new Map();
|
|
701
|
+
for (const candidate of requested) {
|
|
702
|
+
if (!texts.has(candidate.doc)) {
|
|
703
|
+
texts.set(candidate.doc, (await fs.readFile(path.join(root, candidate.doc), 'utf8')).split('\n'));
|
|
704
|
+
}
|
|
705
|
+
if (!locateInsertion(texts.get(candidate.doc), candidate)) {
|
|
706
|
+
fail('目标段未找到: ' + candidate.doc + '「' + candidate.label + '」(本次零改动)');
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function runApply(options, out = console) {
|
|
712
|
+
const plan = await scanProject(options.root);
|
|
713
|
+
const index = new Map();
|
|
714
|
+
for (const change of plan.changes) {
|
|
715
|
+
for (const candidate of change.candidates) index.set(candidate.id, candidate);
|
|
716
|
+
}
|
|
717
|
+
const unknown = options.ids.filter((id) => !index.has(id));
|
|
718
|
+
if (unknown.length > 0) {
|
|
719
|
+
fail('候选 id 未找到: ' + unknown.join(', ') + '(可用: ' + ([...index.keys()].join(', ') || '无') + ')');
|
|
720
|
+
}
|
|
721
|
+
const requested = options.ids.map((id) => index.get(id));
|
|
722
|
+
const absent = [];
|
|
723
|
+
for (const candidate of requested) {
|
|
724
|
+
if (!(await pathExists(path.join(options.root, candidate.doc)))) {
|
|
725
|
+
absent.push('[' + candidate.id + '] → ' + candidate.doc);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (absent.length > 0) {
|
|
729
|
+
fail('目标文档不在场,本次零改动: ' + absent.join(';')
|
|
730
|
+
+ '(跨模块契约类条目需先建立 ' + DOC_ARCHITECTURE + ',或改落 ' + DOC_CONTEXT + ')');
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
out.log('EVOLVE: 应用 ' + requested.length + ' 条候选(根 ' + options.root + ')');
|
|
734
|
+
out.log('EVOLVE: ' + describeWindow(plan));
|
|
735
|
+
await validateInsertions(options.root, requested);
|
|
736
|
+
const ts = nowTimestamp();
|
|
737
|
+
// 第二道写入前全验:state 通道(文档一旦落盘就不可回滚,通道排在文档之后)
|
|
738
|
+
await preflightStateChannel(options.root, ts, plan.state);
|
|
739
|
+
const byDoc = new Map();
|
|
740
|
+
for (const candidate of requested) {
|
|
741
|
+
if (!byDoc.has(candidate.doc)) byDoc.set(candidate.doc, []);
|
|
742
|
+
byDoc.get(candidate.doc).push(candidate);
|
|
743
|
+
}
|
|
744
|
+
const applied = [];
|
|
745
|
+
const present = [];
|
|
746
|
+
for (const [doc, entries] of byDoc) {
|
|
747
|
+
const result = await patchDocument(options.root, doc, entries, ts, options.scanner, out);
|
|
748
|
+
applied.push(...result.written);
|
|
749
|
+
present.push(...result.present);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
writeStateTimestamp(options.root, ts, plan.state, out);
|
|
753
|
+
const readBack = await readStateInfo(options.root);
|
|
754
|
+
if (!readBack.state || readBack.state[STATE_KEY] !== ts) {
|
|
755
|
+
throw new Error('state 回读不一致: 期望 ' + ts + ' 实得 ' + String(readBack.state && readBack.state[STATE_KEY]));
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const report = await writeReport(options.root, plan, ts, requested, applied, present);
|
|
759
|
+
out.log('EVOLVE-REPORT: ' + relativeLabel(options.root, report.file));
|
|
760
|
+
if (options.stdout) out.log(report.body);
|
|
761
|
+
out.log('EVOLVE: 双落点一致 state = ' + ts + ' · 段 = ' + ts + '(state 为唯一真相)');
|
|
762
|
+
out.log('EVOLVE-OK');
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
async function main(argv) {
|
|
766
|
+
const options = parseArgs(argv);
|
|
767
|
+
if (options.error) fail(options.error);
|
|
768
|
+
if (options.help) { console.log(usage()); return; }
|
|
769
|
+
if (options.command === 'scan') await runScan(options);
|
|
770
|
+
else await runApply(options);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
|
|
774
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
775
|
+
console.error('BLOCKED: ' + error.message);
|
|
776
|
+
process.exit(1);
|
|
777
|
+
});
|
|
778
|
+
}
|