@befe/vault-system 0.1.15 → 0.1.18
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/INSTALL.md +1 -1
- package/SKILL.md +29 -23
- package/bin/_vault-inner-cli.ts +22 -0
- package/package.json +1 -1
- package/src/core/api-version.ts +2 -1
- package/src/core/comate-rules.ts +753 -0
- package/src/core/ctag-shape.ts +6 -6
- package/src/core/ctag.ts +4 -4
- package/src/core/format.ts +17 -0
- package/src/core/local-branch.ts +256 -0
- package/src/core/local-temp.ts +245 -0
- package/src/core/query.ts +2 -2
- package/src/core/quick-demo.ts +503 -0
- package/src/core/wskey.ts +2 -2
- package/src/server/app.ts +207 -4
- package/src/server/index.ts +28 -0
- package/web/dist/assets/{abnfDiagram-WEYOIA3C-BqORnHjB.js → abnfDiagram-WEYOIA3C-rZaG2iSs.js} +1 -1
- package/web/dist/assets/{arc-BGXAJ40C.js → arc-D-YRXgrg.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZHVYKT53-DbI1J5ln.js → architectureDiagram-ZHVYKT53-BBkgnnhu.js} +1 -1
- package/web/dist/assets/{blockDiagram-RJAE7QA3-D8sgErpR.js → blockDiagram-RJAE7QA3-D_UPuzcL.js} +1 -1
- package/web/dist/assets/{c4Diagram-XDPPPE54-BlcsC3ms.js → c4Diagram-XDPPPE54-rRkxxACp.js} +1 -1
- package/web/dist/assets/channel-CX2cpODM.js +1 -0
- package/web/dist/assets/{chunk-2E7WHVMD-D9gu33g-.js → chunk-2E7WHVMD-BRH_4_am.js} +1 -1
- package/web/dist/assets/{chunk-2Q5K7J3B-BWL4Ro5L.js → chunk-2Q5K7J3B-Ca9Nzrlh.js} +1 -1
- package/web/dist/assets/{chunk-4EMNKR2T-Cc4lXBgU.js → chunk-4EMNKR2T-EeIUtWEL.js} +1 -1
- package/web/dist/assets/{chunk-55XCU76K-D8ob_9K1.js → chunk-55XCU76K-BSK00in2.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-BTOyV50N.js → chunk-5VM5RSS4-C861XhrM.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-BN2iCP4K.js → chunk-JWPE2WC7-v2zmmZ8M.js} +1 -1
- package/web/dist/assets/{chunk-VQ5W62QI-DrI7WJyZ.js → chunk-VQ5W62QI-D66wyirI.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-B0ECAomZ.js → chunk-XXDRQBXY-EVyGdP8d.js} +1 -1
- package/web/dist/assets/{chunk-ZCHMQSOR-gkiGBWtj.js → chunk-ZCHMQSOR-DXtpKq5T.js} +2 -2
- package/web/dist/assets/{classDiagram-v2-4MYWR3UA-DlZPd_0h.js → classDiagram-v2-4MYWR3UA-Cr43uJqI.js} +1 -1
- package/web/dist/assets/{cose-bilkent-JH36ORCC-BkMzHwYp.js → cose-bilkent-JH36ORCC-Cuuq6WQQ.js} +1 -1
- package/web/dist/assets/{cynefin-EF2NZ3EQ-CnqmXHNk.js → cynefin-EF2NZ3EQ-C3iyCS68.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-WF24UDRP-I1TNaluJ.js → cynefinDiagram-WF24UDRP-bKF_V24p.js} +1 -1
- package/web/dist/assets/{dagre-NK4GIZVX-Bu6YSRkV.js → dagre-NK4GIZVX-BP6HiUix.js} +1 -1
- package/web/dist/assets/{diagram-CBK3MWTC-C5pY_twa.js → diagram-CBK3MWTC--Bdnc_hg.js} +1 -1
- package/web/dist/assets/{diagram-I5XIIV2D-_gC1ENOs.js → diagram-I5XIIV2D-Cb_w9kpf.js} +1 -1
- package/web/dist/assets/{diagram-ODIL2UCW-BbKSmcuz.js → diagram-ODIL2UCW-dTgly2Fz.js} +1 -1
- package/web/dist/assets/{diagram-PFBEJUXE-qm-infA9.js → diagram-PFBEJUXE-BjGtD0ca.js} +1 -1
- package/web/dist/assets/{diagram-RJA3I4VV-DLq7IKhr.js → diagram-RJA3I4VV-7yxAtb-a.js} +1 -1
- package/web/dist/assets/{diagram-TYUNFSNR-CdBrLvN9.js → diagram-TYUNFSNR-CdDNua7n.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-V4P3TTPT-BAWFVoKa.js → ebnfDiagram-V4P3TTPT-BNdBmqlo.js} +1 -1
- package/web/dist/assets/{elk-QONTBCTQ-SJNpaRjl.js → elk-QONTBCTQ-CmnC5D_R.js} +1 -1
- package/web/dist/assets/{erDiagram-KYQIGQAA-CexgxkpY.js → erDiagram-KYQIGQAA-DbvWu-TF.js} +1 -1
- package/web/dist/assets/{flowDiagram-IUGLLWBU-oh443ekR.js → flowDiagram-IUGLLWBU-ElkzAMUI.js} +1 -1
- package/web/dist/assets/{ganttDiagram-R7GPNTJY-DHhjW7y_.js → ganttDiagram-R7GPNTJY-CT2YIzjy.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-PDYL7XHY-CgT6CQYG.js → gitGraphDiagram-PDYL7XHY-DAXq_4wb.js} +1 -1
- package/web/dist/assets/index-6AtKnj5r.css +1 -0
- package/web/dist/assets/index-CvSLBFhG.js +99 -0
- package/web/dist/assets/{infoDiagram-MVDRKAX5-gf0mvh0K.js → infoDiagram-MVDRKAX5-DRP-H8zh.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-HPEHV2GE-Co4No1V-.js → ishikawaDiagram-HPEHV2GE-BNoK_XsT.js} +1 -1
- package/web/dist/assets/{journeyDiagram-BOSHW7O7-Cuw6t66k.js → journeyDiagram-BOSHW7O7-pkpw5r9x.js} +1 -1
- package/web/dist/assets/{kanban-definition-FNSA4HC5-BFbb4VUA.js → kanban-definition-FNSA4HC5-Dt6SzUmC.js} +1 -1
- package/web/dist/assets/{linear-CwCTtONX.js → linear-FQQ9tQr_.js} +1 -1
- package/web/dist/assets/{mermaid.core-DwqCylVV.js → mermaid.core-BZ6wQkn-.js} +4 -4
- package/web/dist/assets/{mindmap-definition-6OY57UG3-BjDVptkO.js → mindmap-definition-6OY57UG3-Bb2sk6RX.js} +1 -1
- package/web/dist/assets/{pegDiagram-ECIUJNBX-Bhc-V9KG.js → pegDiagram-ECIUJNBX-CQKk04_1.js} +1 -1
- package/web/dist/assets/{pieDiagram-GNMPY74T-FS2ZVJhq.js → pieDiagram-GNMPY74T-BfKw-loG.js} +1 -1
- package/web/dist/assets/{quadrantDiagram-D57K4MC3-CPT_0u7e.js → quadrantDiagram-D57K4MC3-CuWo9HYa.js} +1 -1
- package/web/dist/assets/{railroadDiagram-Y72NRBL7-B7qsTucO.js → railroadDiagram-Y72NRBL7-Di4q_SJ_.js} +1 -1
- package/web/dist/assets/{requirementDiagram-EQYSW5RA-BL4y81KM.js → requirementDiagram-EQYSW5RA-DC4GU4Pk.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-SY24JHO5-BWo3NFss.js → sankeyDiagram-SY24JHO5-_fgVuzHE.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-BLEHNHQU-DKVssnuv.js → sequenceDiagram-BLEHNHQU-Bqlr7yoo.js} +1 -1
- package/web/dist/assets/{sizeCapture-INFHLROL-BJPby32y.js → sizeCapture-INFHLROL-CbbBAQPu.js} +1 -1
- package/web/dist/assets/{stateDiagram-v2-A6IESKWZ-UASkbNv2.js → stateDiagram-v2-A6IESKWZ-DoMyztsn.js} +1 -1
- package/web/dist/assets/{swimlanes-B3ENRKFQ-CcUnGJtW.js → swimlanes-B3ENRKFQ-BvuDLV2j.js} +1 -1
- package/web/dist/assets/swimlanesDiagram-AYQRV4AK-Dxt3sSM3.js +8 -0
- package/web/dist/assets/{timeline-definition-JXYKGLGB-DVZSIpZI.js → timeline-definition-JXYKGLGB-Bvrh9DNs.js} +1 -1
- package/web/dist/assets/{usecaseDiagram-WPOLBNNX-DuhA1xDM.js → usecaseDiagram-WPOLBNNX-DPY4EcsJ.js} +1 -1
- package/web/dist/assets/{vennDiagram-Q3Y3IDCW-DqUleZHw.js → vennDiagram-Q3Y3IDCW-BFo8so0I.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-IVAIDKWA-ClDlz1oX.js → wardleyDiagram-IVAIDKWA-DYzIhyA5.js} +1 -1
- package/web/dist/assets/{xychartDiagram-4URNHDU4-Dy71tZPC.js → xychartDiagram-4URNHDU4-l_k66Yd_.js} +1 -1
- package/web/dist/index.html +2 -2
- package/web/dist/assets/channel-4swFvr8Y.js +0 -1
- package/web/dist/assets/index-B0QYXVhN.js +0 -89
- package/web/dist/assets/index-CjgDGJ8N.css +0 -1
- package/web/dist/assets/swimlanesDiagram-AYQRV4AK-cWzdf-uW.js +0 -8
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* comate-rules.ts — 把个人主记忆、vault-system 技能与个人追加文件同步成 Comate rules(不依赖 Hono)。
|
|
3
|
+
*
|
|
4
|
+
* 口径见 ref#file_后续需求_comate规则自动维护.261121_xndmy6_ctag.:
|
|
5
|
+
* - 个人配置:<话题根>/config/{uuap}/vault-system-comate-rules.yaml(与 quick-demo 同目录、同一套话题根解析)
|
|
6
|
+
* - 服务启动时身份确认后,非 demo_ 账号缺配置就写一份默认配置(enabled: false),已存在不改
|
|
7
|
+
* - 生成物只放 $WK/.comate/rules/wk-auto/*.mdr;只建 / 删这个目录里的 .mdr,.comate/rules/ 其他文件一律不碰
|
|
8
|
+
* - 全量:清空 wk-auto/*.mdr 后全部重写(启动、配置修改时间变化、切换身份、POST /comate-rules/sync)
|
|
9
|
+
* - 定时(30 秒):比对源文件 mtimeMs 与生成文件头部注释里的 mtimeMs=,只重写变了的那份;源文件被删就删对应 .mdr
|
|
10
|
+
* - 配置写坏:按关闭处理但不清空已有生成物;取不到身份:什么都不动
|
|
11
|
+
* - 后台服务输出被丢弃:所有提示进内存摘要,经 /status 与 comate-rules sync 输出给人看
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
existsSync,
|
|
16
|
+
lstatSync,
|
|
17
|
+
mkdirSync,
|
|
18
|
+
readdirSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
realpathSync,
|
|
21
|
+
renameSync,
|
|
22
|
+
statSync,
|
|
23
|
+
unlinkSync,
|
|
24
|
+
writeFileSync,
|
|
25
|
+
} from 'node:fs';
|
|
26
|
+
import { dirname, isAbsolute, join, posix, relative, sep } from 'node:path';
|
|
27
|
+
import { isValidQuickDemoSegment, quickDemoTopicRoot } from './quick-demo.js';
|
|
28
|
+
import { resolveUuap } from './workspace.js';
|
|
29
|
+
|
|
30
|
+
/** 个人配置文件名 */
|
|
31
|
+
export const COMATE_RULES_CONFIG_FILE = 'vault-system-comate-rules.yaml';
|
|
32
|
+
|
|
33
|
+
/** 生成物目录(相对 $WK) */
|
|
34
|
+
export const COMATE_RULES_OUT_DIR = '.comate/rules/wk-auto';
|
|
35
|
+
|
|
36
|
+
/** 定时检查间隔(毫秒) */
|
|
37
|
+
export const COMATE_RULES_TICK_MS = 30_000;
|
|
38
|
+
|
|
39
|
+
/** 单份超过这个行数照样生成,但给提示 */
|
|
40
|
+
export const COMATE_RULES_MAX_LINES = 500;
|
|
41
|
+
|
|
42
|
+
/** 二进制判定:前 8KB 里出现 NUL 字节 */
|
|
43
|
+
const BINARY_SNIFF_BYTES = 8192;
|
|
44
|
+
|
|
45
|
+
/** 自动创建时写入的默认配置(也是需求文档里的样张) */
|
|
46
|
+
export const COMATE_RULES_DEFAULT_CONFIG = `version: 1
|
|
47
|
+
enabled: false # 总开关;改成 true 才生成,false 时清空 .comate/rules/wk-auto/
|
|
48
|
+
presets:
|
|
49
|
+
main-memory: true # 当前身份的 memory/{uuap}/_index.md
|
|
50
|
+
vault-system: true # skills/vault-system/SKILL.md
|
|
51
|
+
extra: [] # 个人追加,路径相对工作区根,按顺序生成 extra-01.mdr …,例如:
|
|
52
|
+
# - docs/_index.md
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
type YamlParse = (text: string) => unknown;
|
|
56
|
+
|
|
57
|
+
/** 默认 YAML 解析:Bun.YAML.parse(与 quick-demo 同口径,不新增依赖) */
|
|
58
|
+
const bunYamlParse: YamlParse = (text) => {
|
|
59
|
+
const yaml = (globalThis as { Bun?: { YAML?: { parse?: YamlParse } } }).Bun?.YAML;
|
|
60
|
+
if (!yaml?.parse) throw new Error('当前运行环境没有 Bun.YAML.parse(需要 bun >= 1.4.2)');
|
|
61
|
+
return yaml.parse(text);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
65
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ───────────────────────── 配置位置与自动创建 ─────────────────────────
|
|
69
|
+
|
|
70
|
+
/** 某个身份的配置文件绝对路径;uuap 不合规或话题根取不到返回 null */
|
|
71
|
+
export function comateRulesConfigPath(wk: string, uuap: string): string | null {
|
|
72
|
+
if (!isValidQuickDemoSegment(uuap)) return null;
|
|
73
|
+
const root = quickDemoTopicRoot(wk);
|
|
74
|
+
return root ? join(root, 'config', uuap, COMATE_RULES_CONFIG_FILE) : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 模拟登录账号(demo_ 开头)不自动建配置 */
|
|
78
|
+
export function isDemoUuap(uuap: string): boolean {
|
|
79
|
+
return uuap.startsWith('demo_');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type EnsureConfigResult = 'created' | 'exists' | 'demo' | 'no_path' | 'no_identity';
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 缺配置就写默认配置:文件不存在才建(wx 独占创建,绝不覆盖),demo_ 账号与取不到身份不建。
|
|
86
|
+
* 写盘失败抛错,交给调用方提示。
|
|
87
|
+
*/
|
|
88
|
+
export function ensureComateRulesConfig(wk: string, uuap: string | null): EnsureConfigResult {
|
|
89
|
+
if (!uuap) return 'no_identity';
|
|
90
|
+
if (isDemoUuap(uuap)) return 'demo';
|
|
91
|
+
const file = comateRulesConfigPath(wk, uuap);
|
|
92
|
+
if (!file) return 'no_path';
|
|
93
|
+
if (existsSync(file)) return 'exists';
|
|
94
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
95
|
+
try {
|
|
96
|
+
writeFileSync(file, COMATE_RULES_DEFAULT_CONFIG, { flag: 'wx' });
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if ((e as NodeJS.ErrnoException).code === 'EEXIST') return 'exists';
|
|
99
|
+
throw e;
|
|
100
|
+
}
|
|
101
|
+
return 'created';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ───────────────────────── 配置解析 ─────────────────────────
|
|
105
|
+
|
|
106
|
+
export interface ComateRulesConfig {
|
|
107
|
+
enabled: boolean;
|
|
108
|
+
mainMemory: boolean;
|
|
109
|
+
vaultSystem: boolean;
|
|
110
|
+
/** 配置里的原文,按顺序;校验在生成时逐条做 */
|
|
111
|
+
extra: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type ComateRulesParseResult = { ok: true; config: ComateRulesConfig } | { ok: false; problems: string[] };
|
|
115
|
+
|
|
116
|
+
/** 顶层 key 所在行(1 起);只认块状写法,找不到不给行号 */
|
|
117
|
+
function keyLine(text: string, key: string): number | undefined {
|
|
118
|
+
const re = new RegExp(`^${key}\\s*:`);
|
|
119
|
+
const i = text.split(/\r?\n/).findIndex((l) => re.test(l));
|
|
120
|
+
return i < 0 ? undefined : i + 1;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** presets 下某个开关所在行 */
|
|
124
|
+
function presetLine(text: string, key: string): number | undefined {
|
|
125
|
+
const re = new RegExp(`^\\s+${key}\\s*:`);
|
|
126
|
+
const i = text.split(/\r?\n/).findIndex((l) => re.test(l));
|
|
127
|
+
return i < 0 ? undefined : i + 1;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const at = (line: number | undefined) => (line ? `第 ${line} 行,` : '');
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 解析配置文本(纯函数)。缺省:enabled 缺省 = false;presets 缺省 = 两个都开;extra 缺省 = []。
|
|
134
|
+
* 语法错 / 顶层不是映射 / version 不是 1 / 字段类型不对 → 写坏(ok: false)。
|
|
135
|
+
*/
|
|
136
|
+
export function parseComateRulesConfig(text: string, parseYaml: YamlParse = bunYamlParse): ComateRulesParseResult {
|
|
137
|
+
let doc: unknown;
|
|
138
|
+
try {
|
|
139
|
+
doc = parseYaml(text);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
return { ok: false, problems: [`配置 YAML 解析失败:${String((e as Error).message ?? e)}`] };
|
|
142
|
+
}
|
|
143
|
+
if (!isRecord(doc)) return { ok: false, problems: ['配置顶层必须是映射(含 version、enabled、presets、extra)'] };
|
|
144
|
+
if (doc.version !== 1) {
|
|
145
|
+
const msg = doc.version === undefined ? '缺少 version(当前只支持 version: 1)' : 'version 只支持 1';
|
|
146
|
+
return { ok: false, problems: [`配置${at(keyLine(text, 'version'))}${msg}`] };
|
|
147
|
+
}
|
|
148
|
+
const problems: string[] = [];
|
|
149
|
+
let enabled = false;
|
|
150
|
+
if (doc.enabled !== undefined && doc.enabled !== null) {
|
|
151
|
+
if (typeof doc.enabled !== 'boolean') problems.push(`配置${at(keyLine(text, 'enabled'))}enabled 必须是 true 或 false`);
|
|
152
|
+
else enabled = doc.enabled;
|
|
153
|
+
}
|
|
154
|
+
let mainMemory = true;
|
|
155
|
+
let vaultSystem = true;
|
|
156
|
+
if (doc.presets !== undefined && doc.presets !== null) {
|
|
157
|
+
if (!isRecord(doc.presets)) {
|
|
158
|
+
problems.push(`配置${at(keyLine(text, 'presets'))}presets 必须是映射(main-memory / vault-system 开关)`);
|
|
159
|
+
} else {
|
|
160
|
+
const pick = (key: string, def: boolean): boolean => {
|
|
161
|
+
const v = (doc as { presets: Record<string, unknown> }).presets[key];
|
|
162
|
+
if (v === undefined || v === null) return def;
|
|
163
|
+
if (typeof v === 'boolean') return v;
|
|
164
|
+
problems.push(`配置${at(presetLine(text, key))}presets.${key} 必须是 true 或 false`);
|
|
165
|
+
return def;
|
|
166
|
+
};
|
|
167
|
+
mainMemory = pick('main-memory', true);
|
|
168
|
+
vaultSystem = pick('vault-system', true);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
let extra: string[] = [];
|
|
172
|
+
if (doc.extra !== undefined && doc.extra !== null) {
|
|
173
|
+
if (!Array.isArray(doc.extra)) {
|
|
174
|
+
problems.push(`配置${at(keyLine(text, 'extra'))}extra 必须是路径列表`);
|
|
175
|
+
} else if (doc.extra.some((x) => typeof x !== 'string')) {
|
|
176
|
+
problems.push(`配置${at(keyLine(text, 'extra'))}extra 的每一项都必须是路径字符串`);
|
|
177
|
+
} else {
|
|
178
|
+
extra = doc.extra as string[];
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (problems.length) return { ok: false, problems };
|
|
182
|
+
return { ok: true, config: { enabled, mainMemory, vaultSystem, extra } };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ───────────────────────── 生成文件格式 ─────────────────────────
|
|
186
|
+
|
|
187
|
+
/** 本地时区的 ISO 时间(秒级,带 +08:00 这样的偏移) */
|
|
188
|
+
export function isoLocal(ms: number): string {
|
|
189
|
+
const d = new Date(ms);
|
|
190
|
+
const p = (n: number) => String(n).padStart(2, '0');
|
|
191
|
+
const off = -d.getTimezoneOffset();
|
|
192
|
+
const sign = off >= 0 ? '+' : '-';
|
|
193
|
+
const a = Math.abs(off);
|
|
194
|
+
return (
|
|
195
|
+
`${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` +
|
|
196
|
+
`T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}${sign}${p(Math.floor(a / 60))}:${p(a % 60)}`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export type ComateRuleKind = 'main-memory' | 'vault-system' | 'extra';
|
|
201
|
+
|
|
202
|
+
/** 一份要生成的 rule */
|
|
203
|
+
export interface ComateRuleEntry {
|
|
204
|
+
kind: ComateRuleKind;
|
|
205
|
+
/** 生成文件名(wk-auto/ 下),如 main-memory.mdr、extra-01.mdr */
|
|
206
|
+
file: string;
|
|
207
|
+
/** 源文件相对 $WK 的路径(POSIX 写法) */
|
|
208
|
+
rel: string;
|
|
209
|
+
/** extra 在配置里的原文(报错用) */
|
|
210
|
+
raw?: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function ruleDescription(e: ComateRuleEntry): string {
|
|
214
|
+
if (e.kind === 'main-memory') return `个人主记忆的同步副本(${e.rel})`;
|
|
215
|
+
if (e.kind === 'vault-system') return `vault-system 技能的同步副本(${e.rel})`;
|
|
216
|
+
return `个人追加文件的同步副本(${e.rel})`;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function ruleHint(e: ComateRuleEntry): string {
|
|
220
|
+
if (e.kind === 'vault-system') {
|
|
221
|
+
return `**本规则 = vault-system 技能(${e.rel})的同步副本,已生效,等同于已激活该技能,不用再激活或读该文件。**`;
|
|
222
|
+
}
|
|
223
|
+
return `**本规则 = ${e.rel} 的同步副本,已生效,不用再读该文件;要改时改源文件。**`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 拼出生成文件全文:rule frontmatter → 加粗提示 → 自动生成说明(HTML 注释)→ 源文件原文(一字不改) */
|
|
227
|
+
export function renderComateRule(e: ComateRuleEntry, content: string, mtimeMs: number): string {
|
|
228
|
+
const ms = Math.floor(mtimeMs);
|
|
229
|
+
return [
|
|
230
|
+
'---',
|
|
231
|
+
`description: ${ruleDescription(e)}`,
|
|
232
|
+
'globs:',
|
|
233
|
+
'alwaysApply: true',
|
|
234
|
+
'---',
|
|
235
|
+
'',
|
|
236
|
+
ruleHint(e),
|
|
237
|
+
'',
|
|
238
|
+
`<!-- 自动生成,改源文件,不要改这里;source=${e.rel};源文件修改时间 ${isoLocal(ms)};mtimeMs=${ms} -->`,
|
|
239
|
+
'',
|
|
240
|
+
content,
|
|
241
|
+
].join('\n');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const HEADER_RE = /^<!-- 自动生成,改源文件,不要改这里;source=([^;\n]*);源文件修改时间 [^;\n]*;mtimeMs=(\d+) -->$/m;
|
|
245
|
+
|
|
246
|
+
/** 从生成文件里读出 source= 与 mtimeMs=;读不到 / 格式不对返回 null */
|
|
247
|
+
export function parseComateRuleHeader(text: string): { source: string; mtimeMs: number } | null {
|
|
248
|
+
// 头部注释固定在第 9 行附近,只看开头一段,避免匹配到源文件正文里的同款文字
|
|
249
|
+
const head = text.split('\n').slice(0, 12).join('\n');
|
|
250
|
+
const m = head.match(HEADER_RE);
|
|
251
|
+
return m ? { source: m[1], mtimeMs: Number(m[2]) } : null;
|
|
252
|
+
}
|
|
253
|
+
// ───────────────────────── 条目与校验 ─────────────────────────
|
|
254
|
+
|
|
255
|
+
/** 按配置列出要生成的条目;extra 的编号 = 在列表里的位置(1 起、两位),前面的条目被跳过也不前移 */
|
|
256
|
+
export function comateRuleEntries(cfg: ComateRulesConfig, uuap: string): ComateRuleEntry[] {
|
|
257
|
+
const out: ComateRuleEntry[] = [];
|
|
258
|
+
if (cfg.mainMemory) out.push({ kind: 'main-memory', file: 'main-memory.mdr', rel: `memory/${uuap}/_index.md` });
|
|
259
|
+
if (cfg.vaultSystem) out.push({ kind: 'vault-system', file: 'vault-system.mdr', rel: 'skills/vault-system/SKILL.md' });
|
|
260
|
+
cfg.extra.forEach((raw, i) => {
|
|
261
|
+
const norm = posix.normalize(raw.replace(/\\/g, '/'));
|
|
262
|
+
out.push({ kind: 'extra', file: `extra-${String(i + 1).padStart(2, '0')}.mdr`, rel: norm, raw });
|
|
263
|
+
});
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function isInside(root: string, p: string): boolean {
|
|
268
|
+
const r = relative(root, p);
|
|
269
|
+
return r === '' || (r !== '..' && !r.startsWith(`..${sep}`) && !isAbsolute(r));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** extra 路径的字面校验:必须相对 $WK、不能跳出 $WK */
|
|
273
|
+
function checkExtraPath(raw: string): string | null {
|
|
274
|
+
if (!raw.trim()) return '路径不能为空';
|
|
275
|
+
if (isAbsolute(raw) || raw.startsWith('/') || raw.startsWith('\\') || /^[A-Za-z]:/.test(raw)) {
|
|
276
|
+
return '必须是相对工作区根的路径,不能写绝对路径';
|
|
277
|
+
}
|
|
278
|
+
const norm = posix.normalize(raw.replace(/\\/g, '/'));
|
|
279
|
+
if (norm === '..' || norm.startsWith('../')) return '不能跳出工作区根';
|
|
280
|
+
if (norm === '.' || norm === './') return '必须指向一个文件';
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 条目在提示里的称呼 */
|
|
285
|
+
function entryLabel(e: ComateRuleEntry): string {
|
|
286
|
+
return e.kind === 'extra' ? `${e.file.replace(/\.mdr$/, '')}(${e.raw ?? e.rel})` : `${e.kind}(${e.rel})`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** 校验源文件:存在、是文件;extra 另外校验路径不跳出 $WK(含真实路径)。通过返回绝对路径与 stat */
|
|
290
|
+
function checkSource(
|
|
291
|
+
wk: string,
|
|
292
|
+
e: ComateRuleEntry,
|
|
293
|
+
): { ok: true; abs: string; mtimeMs: number } | { ok: false; problem: string } {
|
|
294
|
+
const bad = (why: string) => ({ ok: false as const, problem: `${entryLabel(e)}:${why},已跳过` });
|
|
295
|
+
if (e.kind === 'extra') {
|
|
296
|
+
const why = checkExtraPath(e.raw ?? e.rel);
|
|
297
|
+
if (why) return bad(why);
|
|
298
|
+
}
|
|
299
|
+
const abs = join(wk, e.rel);
|
|
300
|
+
let st;
|
|
301
|
+
try {
|
|
302
|
+
st = statSync(abs); // 跟随软链(skills/vault-system 通常是软链)
|
|
303
|
+
} catch {
|
|
304
|
+
return bad('源文件不存在');
|
|
305
|
+
}
|
|
306
|
+
if (!st.isFile()) return bad('不是文件');
|
|
307
|
+
if (e.kind === 'extra') {
|
|
308
|
+
try {
|
|
309
|
+
if (!isInside(realpathSync(wk), realpathSync(abs))) return bad('真实路径跳出了工作区根');
|
|
310
|
+
} catch {
|
|
311
|
+
return bad('源文件不存在');
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return { ok: true, abs, mtimeMs: Math.floor(st.mtimeMs) };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function isBinary(buf: Buffer): boolean {
|
|
318
|
+
return buf.subarray(0, BINARY_SNIFF_BYTES).includes(0);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function countLines(text: string): number {
|
|
322
|
+
if (!text) return 0;
|
|
323
|
+
const n = text.split('\n').length;
|
|
324
|
+
return text.endsWith('\n') ? n - 1 : n;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ───────────────────────── 生成目录操作(只碰 wk-auto/*.mdr 与本模块自己的临时文件) ─────────────────────────
|
|
328
|
+
|
|
329
|
+
const OUT_PARTS = COMATE_RULES_OUT_DIR.split('/');
|
|
330
|
+
|
|
331
|
+
/** 写入用的临时文件:`.{名字}.mdr.tmp-{pid}`,不以 .mdr 结尾(Comate 不会把它当 rule 读),写完 rename 到正式名 */
|
|
332
|
+
const TMP_RE = /^\.[A-Za-z0-9_-]+\.mdr\.tmp-\d+$/;
|
|
333
|
+
|
|
334
|
+
function outDir(wk: string): string {
|
|
335
|
+
return join(wk, ...OUT_PARTS);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export type OutDirCheck = { ok: true; exists: boolean } | { ok: false; problem: string };
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* 生成目录的安全检查:`.comate`、`.comate/rules`、`wk-auto` 三级都必须是真实目录(lstat,不能是软链),
|
|
342
|
+
* 且 realpath(wk-auto) === realpath($WK)/.comate/rules/wk-auto;否则什么都不做,交给调用方记提示。
|
|
343
|
+
* create=true 时不存在的级别逐级建(不用 recursive,免得穿过软链建到别处)。
|
|
344
|
+
*/
|
|
345
|
+
export function checkOutDir(wk: string, create: boolean): OutDirCheck {
|
|
346
|
+
const fail = (why: string): OutDirCheck => ({
|
|
347
|
+
ok: false,
|
|
348
|
+
problem: `${COMATE_RULES_OUT_DIR}/ 不安全(${why}),未生成也未清理`,
|
|
349
|
+
});
|
|
350
|
+
let cur = wk;
|
|
351
|
+
const seen: string[] = [];
|
|
352
|
+
for (const part of OUT_PARTS) {
|
|
353
|
+
cur = join(cur, part);
|
|
354
|
+
seen.push(part);
|
|
355
|
+
const rel = seen.join('/');
|
|
356
|
+
let st;
|
|
357
|
+
try {
|
|
358
|
+
st = lstatSync(cur);
|
|
359
|
+
} catch (e) {
|
|
360
|
+
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') return fail(`${rel} 读不了`);
|
|
361
|
+
if (!create) return { ok: true, exists: false };
|
|
362
|
+
mkdirSync(cur);
|
|
363
|
+
st = lstatSync(cur);
|
|
364
|
+
}
|
|
365
|
+
if (st.isSymbolicLink()) return fail(`${rel} 是符号链接`);
|
|
366
|
+
if (!st.isDirectory()) return fail(`${rel} 不是目录`);
|
|
367
|
+
}
|
|
368
|
+
try {
|
|
369
|
+
if (realpathSync(cur) !== join(realpathSync(wk), ...OUT_PARTS)) return fail('真实路径不在工作区的 .comate/rules/wk-auto');
|
|
370
|
+
} catch {
|
|
371
|
+
return fail('取不到真实路径');
|
|
372
|
+
}
|
|
373
|
+
return { ok: true, exists: true };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** wk-auto/ 下现有的 .mdr 文件名(排序);目录不存在或不安全返回 [] */
|
|
377
|
+
function listMdr(wk: string): string[] {
|
|
378
|
+
const g = checkOutDir(wk, false);
|
|
379
|
+
if (!g.ok || !g.exists) return [];
|
|
380
|
+
const dir = outDir(wk);
|
|
381
|
+
let names: string[];
|
|
382
|
+
try {
|
|
383
|
+
names = readdirSync(dir);
|
|
384
|
+
} catch {
|
|
385
|
+
return [];
|
|
386
|
+
}
|
|
387
|
+
return names
|
|
388
|
+
.filter((n) => n.endsWith('.mdr'))
|
|
389
|
+
.filter((n) => {
|
|
390
|
+
try {
|
|
391
|
+
const st = lstatSync(join(dir, n));
|
|
392
|
+
return st.isFile() || st.isSymbolicLink();
|
|
393
|
+
} catch {
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
.sort();
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** 删一个 .mdr 或本模块留下的临时文件(unlink 只删链接本身,不碰软链指向) */
|
|
401
|
+
function removeOut(wk: string, name: string): void {
|
|
402
|
+
if (!(name.endsWith('.mdr') || TMP_RE.test(name)) || name.includes('/') || name.includes('\\')) return;
|
|
403
|
+
try {
|
|
404
|
+
unlinkSync(join(outDir(wk), name));
|
|
405
|
+
} catch (e) {
|
|
406
|
+
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 清掉残留的临时文件(只认 TMP_RE 这一种名字) */
|
|
411
|
+
function removeTmp(wk: string): void {
|
|
412
|
+
let names: string[];
|
|
413
|
+
try {
|
|
414
|
+
names = readdirSync(outDir(wk));
|
|
415
|
+
} catch {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
for (const n of names) if (TMP_RE.test(n)) removeOut(wk, n);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 调用前须已过 checkOutDir */
|
|
422
|
+
function clearMdr(wk: string): void {
|
|
423
|
+
for (const n of listMdr(wk)) removeOut(wk, n);
|
|
424
|
+
removeTmp(wk);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* 先写临时文件(wx:已有同名就先删,绝不跟随软链写),再 rename 到正式名。
|
|
429
|
+
* rename 替换的是目标目录项本身:目标是软链时换掉的是链接,不会写到链接指向的文件;读者也看不到写了一半的文件。
|
|
430
|
+
*/
|
|
431
|
+
function writeMdr(wk: string, name: string, text: string): void {
|
|
432
|
+
const dir = outDir(wk);
|
|
433
|
+
const tmp = join(dir, `.${name}.tmp-${process.pid}`);
|
|
434
|
+
try {
|
|
435
|
+
unlinkSync(tmp);
|
|
436
|
+
} catch {
|
|
437
|
+
/* 没有残留 */
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
writeFileSync(tmp, text, { flag: 'wx' });
|
|
441
|
+
renameSync(tmp, join(dir, name));
|
|
442
|
+
} catch (e) {
|
|
443
|
+
try {
|
|
444
|
+
unlinkSync(tmp);
|
|
445
|
+
} catch {
|
|
446
|
+
/* 已经没了 */
|
|
447
|
+
}
|
|
448
|
+
throw e;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 删掉头部 source= 指向别人主记忆目录(memory/<他人>/…)的 .mdr;配置读不了、要保留生成物时也不能留着上一个人的记忆 */
|
|
453
|
+
function dropForeignMemory(wk: string, uuap: string): void {
|
|
454
|
+
for (const n of listMdr(wk)) {
|
|
455
|
+
const text = readText(join(outDir(wk), n));
|
|
456
|
+
const src = text === null ? null : parseComateRuleHeader(text)?.source;
|
|
457
|
+
const m = src ? /^memory\/([^/]+)\//.exec(src) : null;
|
|
458
|
+
if (m && m[1] !== uuap) removeOut(wk, n);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function readText(file: string): string | null {
|
|
463
|
+
try {
|
|
464
|
+
return readFileSync(file, 'utf8');
|
|
465
|
+
} catch {
|
|
466
|
+
return null;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
// ───────────────────────── 同步器 ─────────────────────────
|
|
470
|
+
|
|
471
|
+
export type ComateRulesState = 'off' | 'on' | 'broken' | 'no_identity';
|
|
472
|
+
|
|
473
|
+
/** 内存摘要:经 /status 的 comateRules 与 comate-rules sync 的输出给人看 */
|
|
474
|
+
export interface ComateRulesSummary {
|
|
475
|
+
enabled: boolean;
|
|
476
|
+
/** 配置文件路径:在 $WK 内写相对路径,否则绝对路径;取不到为 null */
|
|
477
|
+
configPath: string | null;
|
|
478
|
+
state: ComateRulesState;
|
|
479
|
+
/** wk-auto/ 下当前的 .mdr 文件名 */
|
|
480
|
+
files: string[];
|
|
481
|
+
/** 跳过、超长、源文件被删、配置写坏、取不到身份等提示 */
|
|
482
|
+
problems: string[];
|
|
483
|
+
lastSyncAt: string | null;
|
|
484
|
+
uuap: string | null;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export interface ComateRulesSyncOptions {
|
|
488
|
+
/** 时钟(毫秒),默认 Date.now;只用于 lastSyncAt */
|
|
489
|
+
now?: () => number;
|
|
490
|
+
parseYaml?: YamlParse;
|
|
491
|
+
/** 取身份,取不到抛错;默认 resolveUuap(wk) */
|
|
492
|
+
identity?: () => string;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export interface ComateRulesSync {
|
|
496
|
+
/** 服务启动时调用:缺配置就写默认配置(demo_ 与取不到身份不写) */
|
|
497
|
+
ensureConfig(): EnsureConfigResult;
|
|
498
|
+
/** 全量重建:清空 wk-auto/*.mdr 后按配置全部重写 */
|
|
499
|
+
full(): ComateRulesSummary;
|
|
500
|
+
/** 定时检查:身份或配置修改时间变了走全量,否则只重写源文件变了的那几份 */
|
|
501
|
+
tick(): ComateRulesSummary;
|
|
502
|
+
summary(): ComateRulesSummary;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export function createComateRulesSync(wk: string, opts: ComateRulesSyncOptions = {}): ComateRulesSync {
|
|
506
|
+
const now = opts.now ?? Date.now;
|
|
507
|
+
const parseYaml = opts.parseYaml ?? bunYamlParse;
|
|
508
|
+
const identity = opts.identity ?? (() => resolveUuap(wk));
|
|
509
|
+
|
|
510
|
+
let summary: ComateRulesSummary = {
|
|
511
|
+
enabled: false,
|
|
512
|
+
configPath: null,
|
|
513
|
+
state: 'off',
|
|
514
|
+
files: [],
|
|
515
|
+
problems: [],
|
|
516
|
+
lastSyncAt: null,
|
|
517
|
+
uuap: null,
|
|
518
|
+
};
|
|
519
|
+
/** 上次全量时的身份与配置修改时间(-1 = 配置不存在);身份为 null 表示还没成功全量过 */
|
|
520
|
+
let lastUuap: string | null = null;
|
|
521
|
+
let lastCfgMtime = Number.NaN;
|
|
522
|
+
/** 上次全量读到的有效配置;配置关闭 / 写坏时为 null,定时检查就什么都不做 */
|
|
523
|
+
let activeCfg: ComateRulesConfig | null = null;
|
|
524
|
+
/** 每份生成物上次写入时的源文件 mtime 与提示(超长等),定时检查源文件没变时沿用 */
|
|
525
|
+
const written = new Map<string, { mtimeMs: number; warnings: string[] }>();
|
|
526
|
+
|
|
527
|
+
const display = (file: string | null): string | null => {
|
|
528
|
+
if (!file) return null;
|
|
529
|
+
// file 已经落在话题根的真实路径下(quickDemoTopicRoot 取的是 realpath),$WK 也按真实路径比
|
|
530
|
+
try {
|
|
531
|
+
const wkReal = realpathSync(wk);
|
|
532
|
+
if (isInside(wkReal, file)) return relative(wkReal, file).split(sep).join('/');
|
|
533
|
+
} catch {
|
|
534
|
+
/* 取不到真实路径:退回绝对路径 */
|
|
535
|
+
}
|
|
536
|
+
return file;
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
const finish = (s: Omit<ComateRulesSummary, 'files' | 'lastSyncAt'>): ComateRulesSummary => {
|
|
540
|
+
summary = { ...s, files: listMdr(wk), lastSyncAt: isoLocal(now()) };
|
|
541
|
+
return summary;
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
const resolveIdentity = (): string | null => {
|
|
545
|
+
try {
|
|
546
|
+
return identity();
|
|
547
|
+
} catch {
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
const cfgMtime = (file: string): number => {
|
|
553
|
+
try {
|
|
554
|
+
return statSync(file).mtimeMs;
|
|
555
|
+
} catch {
|
|
556
|
+
return -1;
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
/** 逐条生成;force=true 一律重写,否则只在头部 source / mtimeMs 对不上时重写。调用前须已过 checkOutDir */
|
|
561
|
+
const apply = (cfg: ComateRulesConfig, uuap: string, force: boolean): string[] => {
|
|
562
|
+
const problems: string[] = [];
|
|
563
|
+
const entries = comateRuleEntries(cfg, uuap);
|
|
564
|
+
const keep = new Set<string>();
|
|
565
|
+
const dir = outDir(wk);
|
|
566
|
+
const skip = (e: ComateRuleEntry, problem: string) => {
|
|
567
|
+
removeOut(wk, e.file);
|
|
568
|
+
written.delete(e.file);
|
|
569
|
+
problems.push(problem);
|
|
570
|
+
};
|
|
571
|
+
for (const e of entries) {
|
|
572
|
+
const src = checkSource(wk, e);
|
|
573
|
+
if (!src.ok) {
|
|
574
|
+
skip(e, src.problem);
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
const target = join(dir, e.file);
|
|
578
|
+
if (!force) {
|
|
579
|
+
const old = readText(target);
|
|
580
|
+
const head = old === null ? null : parseComateRuleHeader(old);
|
|
581
|
+
if (head && head.source === e.rel && head.mtimeMs === src.mtimeMs) {
|
|
582
|
+
keep.add(e.file);
|
|
583
|
+
problems.push(...(written.get(e.file)?.warnings ?? []));
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
let buf: Buffer;
|
|
588
|
+
try {
|
|
589
|
+
buf = readFileSync(src.abs);
|
|
590
|
+
} catch (err) {
|
|
591
|
+
skip(e, `${entryLabel(e)}:读取失败(${(err as NodeJS.ErrnoException).code ?? String(err)}),已跳过`);
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (isBinary(buf)) {
|
|
595
|
+
skip(e, `${entryLabel(e)}:不是文本文件,已跳过`);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
const content = buf.toString('utf8');
|
|
599
|
+
const warnings: string[] = [];
|
|
600
|
+
const lines = countLines(content);
|
|
601
|
+
if (lines > COMATE_RULES_MAX_LINES) {
|
|
602
|
+
warnings.push(`${entryLabel(e)}:共 ${lines} 行,超过建议的 ${COMATE_RULES_MAX_LINES} 行(照样生成)`);
|
|
603
|
+
}
|
|
604
|
+
const g = checkOutDir(wk, true); // 不存在的级别逐级建;建的过程中被换成软链也会在这里拦下
|
|
605
|
+
if (!g.ok) throw new Error(g.problem);
|
|
606
|
+
writeMdr(wk, e.file, renderComateRule(e, content, src.mtimeMs));
|
|
607
|
+
written.set(e.file, { mtimeMs: src.mtimeMs, warnings });
|
|
608
|
+
keep.add(e.file);
|
|
609
|
+
problems.push(...warnings);
|
|
610
|
+
}
|
|
611
|
+
// 清掉不在本次条目里的旧 .mdr(如 extra 列表变短后残留的编号)与残留临时文件
|
|
612
|
+
for (const n of listMdr(wk)) if (!keep.has(n)) removeOut(wk, n);
|
|
613
|
+
removeTmp(wk);
|
|
614
|
+
return problems;
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
/** 清空「上次全量」的记录:下一次 tick 必然走全量重试,不会因为半途失败而永远提前返回 */
|
|
618
|
+
const resetState = () => {
|
|
619
|
+
lastUuap = null;
|
|
620
|
+
lastCfgMtime = Number.NaN;
|
|
621
|
+
activeCfg = null;
|
|
622
|
+
written.clear();
|
|
623
|
+
};
|
|
624
|
+
|
|
625
|
+
/** 成功后才记录上次全量的身份、配置修改时间与有效配置 */
|
|
626
|
+
const commit = (uuap: string, mtime: number, cfg: ComateRulesConfig | null) => {
|
|
627
|
+
lastUuap = uuap;
|
|
628
|
+
lastCfgMtime = mtime;
|
|
629
|
+
activeCfg = cfg;
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
const fullInner = (): ComateRulesSummary => {
|
|
633
|
+
const uuap = resolveIdentity();
|
|
634
|
+
if (!uuap) {
|
|
635
|
+
resetState();
|
|
636
|
+
return finish({
|
|
637
|
+
enabled: false,
|
|
638
|
+
configPath: null,
|
|
639
|
+
state: 'no_identity',
|
|
640
|
+
problems: ['取不到身份(UUAP.md / git user.name),未生成也未清理 .comate/rules/wk-auto/'],
|
|
641
|
+
uuap: null,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
const file = comateRulesConfigPath(wk, uuap);
|
|
645
|
+
const configPath = display(file);
|
|
646
|
+
const guard = checkOutDir(wk, false);
|
|
647
|
+
if (!guard.ok) {
|
|
648
|
+
resetState(); // 每次 tick 都重试,目录修好后自动恢复
|
|
649
|
+
return finish({ enabled: false, configPath, state: 'broken', problems: [guard.problem], uuap });
|
|
650
|
+
}
|
|
651
|
+
if (!file) {
|
|
652
|
+
dropForeignMemory(wk, uuap);
|
|
653
|
+
written.clear();
|
|
654
|
+
commit(uuap, Number.NaN, null);
|
|
655
|
+
const why = isValidQuickDemoSegment(uuap)
|
|
656
|
+
? '找不到 skills/vault-system 的真实目录,读不到个人配置'
|
|
657
|
+
: `身份 ${uuap} 含不允许的字符,读不到个人配置`;
|
|
658
|
+
return finish({ enabled: false, configPath: null, state: 'broken', problems: [`${why};已有生成物保留`], uuap });
|
|
659
|
+
}
|
|
660
|
+
const mtime = cfgMtime(file); // 先取修改时间再读:读完之后又被改,下次 tick 也能发现
|
|
661
|
+
const text = readText(file);
|
|
662
|
+
if (text === null) {
|
|
663
|
+
clearMdr(wk);
|
|
664
|
+
written.clear();
|
|
665
|
+
commit(uuap, mtime, null);
|
|
666
|
+
const problems = existsSync(file) ? ['配置文件读取失败,按关闭处理'] : [];
|
|
667
|
+
return finish({ enabled: false, configPath, state: 'off', problems, uuap });
|
|
668
|
+
}
|
|
669
|
+
const parsed = parseComateRulesConfig(text, parseYaml);
|
|
670
|
+
if (!parsed.ok) {
|
|
671
|
+
dropForeignMemory(wk, uuap);
|
|
672
|
+
written.clear();
|
|
673
|
+
commit(uuap, mtime, null);
|
|
674
|
+
return finish({
|
|
675
|
+
enabled: false,
|
|
676
|
+
configPath,
|
|
677
|
+
state: 'broken',
|
|
678
|
+
problems: [...parsed.problems, '配置写坏:按关闭处理,已有生成物保留(别人主记忆的副本除外)'],
|
|
679
|
+
uuap,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
if (!parsed.config.enabled) {
|
|
683
|
+
clearMdr(wk);
|
|
684
|
+
written.clear();
|
|
685
|
+
commit(uuap, mtime, null);
|
|
686
|
+
return finish({ enabled: false, configPath, state: 'off', problems: [], uuap });
|
|
687
|
+
}
|
|
688
|
+
clearMdr(wk);
|
|
689
|
+
written.clear();
|
|
690
|
+
const problems = apply(parsed.config, uuap, true);
|
|
691
|
+
commit(uuap, mtime, parsed.config);
|
|
692
|
+
return finish({ enabled: true, configPath, state: 'on', problems, uuap });
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
/** 同步半途抛错:清空记录(下次 tick 重试全量),错误进摘要,不往外抛 */
|
|
696
|
+
const failed = (e: unknown): ComateRulesSummary => {
|
|
697
|
+
resetState();
|
|
698
|
+
return finish({
|
|
699
|
+
enabled: false,
|
|
700
|
+
configPath: summary.configPath,
|
|
701
|
+
state: 'broken',
|
|
702
|
+
problems: [`同步失败(下次检查会重试全量):${String((e as Error)?.message ?? e)}`],
|
|
703
|
+
uuap: summary.uuap,
|
|
704
|
+
});
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
const full = (): ComateRulesSummary => {
|
|
708
|
+
try {
|
|
709
|
+
return fullInner();
|
|
710
|
+
} catch (e) {
|
|
711
|
+
return failed(e);
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
const tick = (): ComateRulesSummary => {
|
|
716
|
+
try {
|
|
717
|
+
const uuap = resolveIdentity();
|
|
718
|
+
if (!uuap) return fullInner(); // 取不到身份时 full 什么都不动,只更新摘要
|
|
719
|
+
const file = comateRulesConfigPath(wk, uuap);
|
|
720
|
+
const mtime = file ? cfgMtime(file) : Number.NaN;
|
|
721
|
+
if (uuap !== lastUuap || !Object.is(mtime, lastCfgMtime)) return fullInner();
|
|
722
|
+
if (!activeCfg) return summary; // 关闭 / 写坏:配置没变就不动
|
|
723
|
+
const guard = checkOutDir(wk, false);
|
|
724
|
+
if (!guard.ok) {
|
|
725
|
+
resetState();
|
|
726
|
+
return finish({ ...summary, state: 'broken', problems: [guard.problem] });
|
|
727
|
+
}
|
|
728
|
+
const problems = apply(activeCfg, uuap, false);
|
|
729
|
+
return finish({ ...summary, problems });
|
|
730
|
+
} catch (e) {
|
|
731
|
+
return failed(e);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
return {
|
|
736
|
+
ensureConfig: () => ensureComateRulesConfig(wk, resolveIdentity()),
|
|
737
|
+
full,
|
|
738
|
+
tick,
|
|
739
|
+
summary: () => summary,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** 进程内每个 $WK 一个同步器:服务启动钩子、定时器与 HTTP 路由共用同一份摘要 */
|
|
744
|
+
const registry = new Map<string, ComateRulesSync>();
|
|
745
|
+
|
|
746
|
+
export function getComateRulesSync(wk: string): ComateRulesSync {
|
|
747
|
+
let s = registry.get(wk);
|
|
748
|
+
if (!s) {
|
|
749
|
+
s = createComateRulesSync(wk);
|
|
750
|
+
registry.set(wk, s);
|
|
751
|
+
}
|
|
752
|
+
return s;
|
|
753
|
+
}
|