@befe/vault-system 0.0.0-stage → 0.1.8

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.
Files changed (99) hide show
  1. package/INSTALL.md +76 -0
  2. package/SKILL.md +302 -0
  3. package/bin/_vault-inner-cli.ts +444 -0
  4. package/cli-module.template.json +9 -0
  5. package/package.json +43 -4
  6. package/src/core/api-version.ts +16 -0
  7. package/src/core/change-collector.ts +115 -0
  8. package/src/core/comment-template.ts +210 -0
  9. package/src/core/comments.ts +303 -0
  10. package/src/core/config.ts +96 -0
  11. package/src/core/ctag-shape.ts +22 -0
  12. package/src/core/ctag.ts +84 -0
  13. package/src/core/format.ts +110 -0
  14. package/src/core/genkey.ts +143 -0
  15. package/src/core/ignore.ts +76 -0
  16. package/src/core/migrate-legacy-cache.ts +59 -0
  17. package/src/core/moved.ts +51 -0
  18. package/src/core/mutate.ts +401 -0
  19. package/src/core/open-order.ts +20 -0
  20. package/src/core/points-search.ts +131 -0
  21. package/src/core/query.ts +221 -0
  22. package/src/core/rebuilder.ts +66 -0
  23. package/src/core/scan.ts +294 -0
  24. package/src/core/service-manager.ts +427 -0
  25. package/src/core/vault-metadata.ts +119 -0
  26. package/src/core/workspace.ts +96 -0
  27. package/src/core/wskey.ts +47 -0
  28. package/src/server/app.ts +712 -0
  29. package/src/server/index.ts +97 -0
  30. package/src/server/scan-worker.ts +10 -0
  31. package/src/server/state.ts +160 -0
  32. package/src/server/watcher.ts +130 -0
  33. package/templates/vault-index-template.md +22 -0
  34. package/web/dist/assets/abnfDiagram-WEYOIA3C-Clrrz6aO.js +1 -0
  35. package/web/dist/assets/arc-BTwSwHaO.js +1 -0
  36. package/web/dist/assets/architectureDiagram-ZHVYKT53-Cc2t0GuJ.js +36 -0
  37. package/web/dist/assets/blockDiagram-RJAE7QA3-CNbK1ZgZ.js +140 -0
  38. package/web/dist/assets/c4Diagram-XDPPPE54-Cyf0T8lC.js +38 -0
  39. package/web/dist/assets/channel-DUo0Wm1H.js +1 -0
  40. package/web/dist/assets/chunk-2E7WHVMD-cO1HGtgb.js +88 -0
  41. package/web/dist/assets/chunk-2Q5K7J3B-heFuFebF.js +1 -0
  42. package/web/dist/assets/chunk-4EMNKR2T-BtTSTbx1.js +1 -0
  43. package/web/dist/assets/chunk-55XCU76K-CsuzGVuA.js +1 -0
  44. package/web/dist/assets/chunk-5VM5RSS4-CHkUK7Na.js +15 -0
  45. package/web/dist/assets/chunk-JWPE2WC7-BcdRnDBp.js +1 -0
  46. package/web/dist/assets/chunk-VQ5W62QI-Dm-aVCex.js +1 -0
  47. package/web/dist/assets/chunk-XXDRQBXY-DvFdV7cE.js +1 -0
  48. package/web/dist/assets/chunk-ZCHMQSOR-_GMZJOh2.js +2 -0
  49. package/web/dist/assets/classDiagram-v2-4MYWR3UA-Dyu-f5sY.js +217 -0
  50. package/web/dist/assets/cose-bilkent-JH36ORCC-Dc00FcYn.js +1 -0
  51. package/web/dist/assets/cynefin-EF2NZ3EQ-CGRcYY9z.js +141 -0
  52. package/web/dist/assets/cynefinDiagram-WF24UDRP-CaQ8qEG7.js +62 -0
  53. package/web/dist/assets/cytoscape.esm-Ix0LnXOy.js +331 -0
  54. package/web/dist/assets/dagre-NK4GIZVX-BJ3S0JEO.js +4 -0
  55. package/web/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  56. package/web/dist/assets/diagram-CBK3MWTC-DFwGBHGn.js +24 -0
  57. package/web/dist/assets/diagram-I5XIIV2D-pcKmZ9Kk.js +24 -0
  58. package/web/dist/assets/diagram-ODIL2UCW-D6oJ8t6N.js +30 -0
  59. package/web/dist/assets/diagram-PFBEJUXE-ypywCTOp.js +3 -0
  60. package/web/dist/assets/diagram-RJA3I4VV-BorkY5MS.js +41 -0
  61. package/web/dist/assets/diagram-TYUNFSNR-T7Bwi21B.js +200 -0
  62. package/web/dist/assets/ebnfDiagram-V4P3TTPT-CW3R519W.js +1 -0
  63. package/web/dist/assets/elk-QONTBCTQ-BdiasG_x.js +27 -0
  64. package/web/dist/assets/erDiagram-KYQIGQAA-CH9y_Q7o.js +99 -0
  65. package/web/dist/assets/flowDiagram-IUGLLWBU-6vX12g0V.js +213 -0
  66. package/web/dist/assets/ganttDiagram-R7GPNTJY-Ca9Z5SFi.js +292 -0
  67. package/web/dist/assets/gitGraphDiagram-PDYL7XHY-DtD9IOhj.js +106 -0
  68. package/web/dist/assets/graph-Bn3Yngep.js +1 -0
  69. package/web/dist/assets/index-MjsRRm95.css +1 -0
  70. package/web/dist/assets/index-eTYW5dTL.js +72 -0
  71. package/web/dist/assets/infoDiagram-MVDRKAX5-BttRtmtq.js +2 -0
  72. package/web/dist/assets/init-Gi6I4Gst.js +1 -0
  73. package/web/dist/assets/ishikawaDiagram-HPEHV2GE-BuGLCWo1.js +70 -0
  74. package/web/dist/assets/journeyDiagram-BOSHW7O7-DLtiEu9c.js +139 -0
  75. package/web/dist/assets/kanban-definition-FNSA4HC5-CQGtMsyR.js +89 -0
  76. package/web/dist/assets/katex-Be3d8Y4U.js +257 -0
  77. package/web/dist/assets/linear-BO_V_WOi.js +1 -0
  78. package/web/dist/assets/mermaid.core-BrDOEsu6.js +314 -0
  79. package/web/dist/assets/mindmap-definition-6OY57UG3-_GFTucKM.js +98 -0
  80. package/web/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  81. package/web/dist/assets/pegDiagram-ECIUJNBX-DfYCgLb5.js +1 -0
  82. package/web/dist/assets/pieDiagram-GNMPY74T-BB9oPfj7.js +39 -0
  83. package/web/dist/assets/quadrantDiagram-D57K4MC3-GT0rwvgr.js +7 -0
  84. package/web/dist/assets/railroadDiagram-Y72NRBL7-DzFREWND.js +1 -0
  85. package/web/dist/assets/requirementDiagram-EQYSW5RA-Co1D_k0J.js +84 -0
  86. package/web/dist/assets/sankeyDiagram-SY24JHO5-BSVsJWqK.js +40 -0
  87. package/web/dist/assets/sequenceDiagram-BLEHNHQU-20qZx9Pi.js +169 -0
  88. package/web/dist/assets/sizeCapture-INFHLROL-BnQdq-uZ.js +1 -0
  89. package/web/dist/assets/stateDiagram-v2-A6IESKWZ-BE5XhAjE.js +291 -0
  90. package/web/dist/assets/swimlanes-B3ENRKFQ-icvIkwDn.js +1 -0
  91. package/web/dist/assets/swimlanesDiagram-AYQRV4AK-lOuiHvx1.js +8 -0
  92. package/web/dist/assets/timeline-definition-JXYKGLGB-96dGf2vq.js +120 -0
  93. package/web/dist/assets/usecaseDiagram-WPOLBNNX-CFXSct0C.js +370 -0
  94. package/web/dist/assets/vennDiagram-Q3Y3IDCW-D_03GSvC.js +34 -0
  95. package/web/dist/assets/wardleyDiagram-IVAIDKWA-vOd1Jr4V.js +78 -0
  96. package/web/dist/assets/xychartDiagram-4URNHDU4-hGZ69wh6.js +7 -0
  97. package/web/dist/favicon.ico +0 -0
  98. package/web/dist/index.html +15 -0
  99. package/README.md +0 -3
@@ -0,0 +1,210 @@
1
+ /**
2
+ * comment-template.ts — 页面「复制评论」时附带的提醒话术模板:两层 Markdown 文件,按 key 合并。
3
+ *
4
+ * 文件格式:每个二级标题是一条的 key,标题下面的正文是 value,顺序即文件里出现的顺序。
5
+ * ## {key}
6
+ *
7
+ * {value}
8
+ *
9
+ * 两层:团队层 $WK/.vault-service/comment-template.md(入库)、用户层 $WK/memory/{UUAP}/vault-comment-template.md。
10
+ * 合并:以团队层顺序为底,用户层同 key 就地替换 value,独有 key 追加到末尾;value 为空的条目不输出。
11
+ * 文件里的 HTML 注释(`<!-- … -->`,可多行)解析前先整体剔除,所以注释(包括示例里的标题)不会成为条目或条目内容。
12
+ * 团队层文件在服务启动时自动创建(ensureTeamTemplate),内容只有一段说明格式的注释、没有条目。
13
+ * 需求与取舍见 ref#file_话题跳转与评论模板配置需求对齐.261025_zkdid_ctag.
14
+ */
15
+
16
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { ensureCacheDir } from './config.js';
19
+ import { cacheDir, resolveUuap } from './workspace.js';
20
+
21
+ export interface TemplateEntry {
22
+ key: string;
23
+ value: string;
24
+ }
25
+
26
+ export const TEAM_TEMPLATE_FILE = 'comment-template.md';
27
+ export const USER_TEMPLATE_FILE = 'vault-comment-template.md';
28
+
29
+ /** 团队层文件不存在时的兜底条目(文件存在——哪怕没有条目——就以文件为准,不再用它) */
30
+ export const DEFAULT_ENTRIES: readonly TemplateEntry[] = [
31
+ { key: 'activate', value: '请先激活 vault-system 技能,再按其中的批注协议处理这些文件里的评论。' },
32
+ ];
33
+
34
+ const FENCE_RE = /^\s*(`{3,}|~{3,})/;
35
+ const FENCE_CLOSE_RE = /^\s*(`{3,}|~{3,})\s*$/;
36
+ const H2_RE = /^##[ \t]+(\S.*)$/;
37
+
38
+ /**
39
+ * 剔除 HTML 注释:围栏代码块里的原样保留;注释可以跨行;整行只剩注释(剔掉后只剩空白)就整行去掉,
40
+ * 不在条目内容里留空行;只有 `<!--` 没有结束时,从它开始到文件末尾都当注释。
41
+ */
42
+ export function stripHtmlComments(text: string): string {
43
+ const out: string[] = [];
44
+ let fence: string | null = null;
45
+ let inComment = false;
46
+ for (const raw of text.replace(/\r\n?/g, '\n').split('\n')) {
47
+ let line = raw;
48
+ if (!inComment && fence !== null) {
49
+ // 围栏内:只看是不是闭合行,其余原样保留
50
+ if (FENCE_CLOSE_RE.test(line) && FENCE_RE.exec(line)![1][0] === fence) fence = null;
51
+ out.push(line);
52
+ continue;
53
+ }
54
+ if (!inComment) {
55
+ const f = FENCE_RE.exec(line);
56
+ if (f) {
57
+ fence = f[1][0];
58
+ out.push(line);
59
+ continue;
60
+ }
61
+ }
62
+ // 逐段剔除:处于注释中先找结束;然后反复剔除本行内完整的注释;遇到没结束的开头就进入注释状态
63
+ let rest = line;
64
+ let kept = '';
65
+ for (;;) {
66
+ if (inComment) {
67
+ const end = rest.indexOf('-->');
68
+ if (end < 0) {
69
+ rest = '';
70
+ break;
71
+ }
72
+ rest = rest.slice(end + 3);
73
+ inComment = false;
74
+ }
75
+ const start = rest.indexOf('<!--');
76
+ if (start < 0) {
77
+ kept += rest;
78
+ break;
79
+ }
80
+ kept += rest.slice(0, start);
81
+ rest = rest.slice(start + 4);
82
+ inComment = true;
83
+ }
84
+ const touched = kept !== line;
85
+ if (touched && kept.trim() === '') continue; // 整行只剩注释:整行去掉
86
+ out.push(kept);
87
+ }
88
+ return out.join('\n');
89
+ }
90
+
91
+ /** 解析一层模板文件:围栏代码块里的行不算标题;同 key 重复时位置取第一次、value 取最后一次 */
92
+ export function parseTemplate(text: string): TemplateEntry[] {
93
+ const entries: TemplateEntry[] = [];
94
+ const at = new Map<string, number>();
95
+ let cur: { key: string; lines: string[] } | null = null;
96
+ let fence: string | null = null;
97
+ const flush = () => {
98
+ if (!cur) return;
99
+ const value = cur.lines.join('\n').trim();
100
+ const i = at.get(cur.key);
101
+ if (i === undefined) {
102
+ at.set(cur.key, entries.length);
103
+ entries.push({ key: cur.key, value });
104
+ } else {
105
+ entries[i].value = value;
106
+ }
107
+ cur = null;
108
+ };
109
+ for (const line of stripHtmlComments(text).split('\n')) {
110
+ const f = FENCE_RE.exec(line);
111
+ if (f) {
112
+ if (fence === null) fence = f[1][0];
113
+ else if (f[1][0] === fence && /^\s*(`{3,}|~{3,})\s*$/.test(line)) fence = null;
114
+ }
115
+ const h = fence === null ? H2_RE.exec(line) : null;
116
+ if (h) {
117
+ flush();
118
+ cur = { key: h[1].trim(), lines: [] };
119
+ continue;
120
+ }
121
+ if (cur) cur.lines.push(line);
122
+ }
123
+ flush();
124
+ return entries.filter((e) => e.key);
125
+ }
126
+
127
+ /** 团队层为底,用户层同 key 就地替换、独有 key 追加;最后丢掉 value 为空的条目 */
128
+ export function mergeTemplates(team: readonly TemplateEntry[], user: readonly TemplateEntry[]): TemplateEntry[] {
129
+ const out = team.map((e) => ({ ...e }));
130
+ const at = new Map(out.map((e, i) => [e.key, i] as const));
131
+ for (const e of user) {
132
+ const i = at.get(e.key);
133
+ if (i === undefined) {
134
+ at.set(e.key, out.length);
135
+ out.push({ ...e });
136
+ } else {
137
+ out[i].value = e.value;
138
+ }
139
+ }
140
+ return out.filter((e) => e.value !== '');
141
+ }
142
+
143
+ export interface LoadedTemplate {
144
+ entries: TemplateEntry[];
145
+ sources: { team: boolean; user: boolean };
146
+ warnings: string[];
147
+ }
148
+
149
+ function readLayer(path: string, label: string, warnings: string[]): TemplateEntry[] | null {
150
+ if (!existsSync(path)) return null;
151
+ try {
152
+ return parseTemplate(readFileSync(path, 'utf8'));
153
+ } catch (e) {
154
+ warnings.push(`${label}模板读取失败:${String((e as Error).message ?? e)}`);
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /** 现读两层文件并合并(不缓存,改了文件下一次复制就生效);团队层缺失用内置兜底 */
160
+ export function loadTemplate(wk: string): LoadedTemplate {
161
+ const warnings: string[] = [];
162
+ const team = readLayer(join(cacheDir(wk), TEAM_TEMPLATE_FILE), '团队层', warnings);
163
+ let user: TemplateEntry[] | null = null;
164
+ try {
165
+ user = readLayer(join(wk, 'memory', resolveUuap(wk), USER_TEMPLATE_FILE), '用户层', warnings);
166
+ } catch {
167
+ // 拿不到身份:当作没有用户层
168
+ }
169
+ const base = team ?? DEFAULT_ENTRIES;
170
+ return {
171
+ entries: mergeTemplates(base, user ?? []),
172
+ sources: { team: team !== null, user: user !== null },
173
+ warnings,
174
+ };
175
+ }
176
+
177
+ /** 自动创建的团队层模板内容:一段说明格式的注释,没有任何条目(注释在解析时会被剔除) */
178
+ export const DEFAULT_TEMPLATE_TEXT = `<!--
179
+ 评论复制模板(团队层,入库,大家共用)
180
+
181
+ 用途:页面右下角复制「有评论的文件」时,这里每一条的内容会放在文件列表前面,提醒 agent 怎么处理。
182
+
183
+ 格式:
184
+ - 每个二级标题(## 开头)是一条的 key,标题下面的正文是这一条的内容,可以多行
185
+ - 条目的顺序就是文件里的顺序;key 只用来排序和覆盖,不会出现在复制结果里
186
+ - 内容为空的条目不输出
187
+ - 这段注释(以及文件里任何位置的 HTML 注释)都不会进入复制结果;围栏代码块里的除外
188
+
189
+ 个人想改写某一条或追加:写在 memory/{你的 UUAP}/${USER_TEMPLATE_FILE} 里,格式相同
190
+ - key 与这里相同:用你的内容替换,位置不变
191
+ - 内容留空:屏蔽这一条
192
+ - 新的 key:追加到末尾
193
+
194
+ 示例(把下面两行贴到注释外面即可生效):
195
+ ## 示例
196
+ 请先激活 vault-system 技能,再按其中的批注协议处理这些文件里的评论。
197
+ -->
198
+ `;
199
+
200
+ /**
201
+ * 确保团队层模板文件存在:不存在才创建(内容见 DEFAULT_TEMPLATE_TEXT),存在一律不碰,包括用户改过的内容。
202
+ * 同时确保运行态目录及其 .gitignore(放行本文件)在。返回是否新建;失败不抛,由调用方决定怎么提示。
203
+ */
204
+ export function ensureTeamTemplate(wk: string): boolean {
205
+ const p = join(cacheDir(wk), TEAM_TEMPLATE_FILE);
206
+ if (existsSync(p)) return false;
207
+ ensureCacheDir(wk);
208
+ writeFileSync(p, DEFAULT_TEMPLATE_TEXT, { flag: 'wx' }); // wx:并发启动时不覆盖别人刚写好的
209
+ return true;
210
+ }
@@ -0,0 +1,303 @@
1
+ /**
2
+ * comments.ts — 页面行内评论在 markdown 文件里的存取(纯函数,无 IO、无依赖,前后端共用同一份)。
3
+ *
4
+ * 评论的落盘形态:追加在被评那一行的末尾,
5
+ * ,,[START:COMMENT:{id}]评论内容(可多行)[END:COMMENT:{id}]
6
+ * 以 `,,` 打头,所以 agent 现成的「按 ,, 找批注」流程天然命中。
7
+ *
8
+ * 识别是严格的:只有「`,,` + 起始标记(id 为 6 位小写字母数字)+ 同 id 的结束标记,且结束标记之后
9
+ * 本行没有别的内容」才算评论;围栏代码块、文件开头的元信息区里的内容不参与识别;
10
+ * 其余(不成对、嵌套、同一行多条、重复 id、讲解格式的示例)一律当普通文字,原样保留。
11
+ * 定位与取舍的依据见 ref#file_行内评论实施方案.261024_7hqun_ctag.
12
+ */
13
+
14
+ /** 评论编号:6 位小写字母加数字 */
15
+ export const COMMENT_ID_PATTERN = '[0-9a-z]{6}';
16
+ /** 评论内容上限(字符) */
17
+ export const MAX_COMMENT_LEN = 20000;
18
+
19
+ const START_RE = new RegExp(`,,\\[START:COMMENT:(${COMMENT_ID_PATTERN})\\]`, 'g');
20
+ const ANY_START_RE = new RegExp(`,,\\[START:COMMENT:${COMMENT_ID_PATTERN}\\]`);
21
+ const MARKER_IN_CONTENT_RE = /\[(?:START|END):COMMENT:/;
22
+ const FENCE_OPEN_RE = /^\s*(`{3,}|~{3,})/;
23
+ const FENCE_CLOSE_RE = /^\s*(`{3,}|~{3,})\s*$/;
24
+
25
+ /** 这一行是不是(只有围栏符的)闭合围栏行 */
26
+ export function isFenceCloseLine(line: string): boolean {
27
+ return FENCE_CLOSE_RE.test(line);
28
+ }
29
+
30
+ /** 一条已识别的评论;行号一律是原文的 0 起行号,start/end 是原文字符偏移(end 含本行结束标记后的空白) */
31
+ export interface CommentSpan {
32
+ id: string;
33
+ content: string;
34
+ /** 起始标记所在行 */
35
+ hostLine: number;
36
+ /** 结束标记所在行(单行评论时等于 hostLine) */
37
+ endLine: number;
38
+ /** 评论独占整行(`,,` 之前只有空白):剔除时整行去掉,删除时整行去掉 */
39
+ ownLine: boolean;
40
+ start: number;
41
+ end: number;
42
+ }
43
+
44
+ interface Lines {
45
+ texts: string[];
46
+ eols: string[];
47
+ offsets: number[];
48
+ }
49
+
50
+ /** 按行拆开并记下每行的换行符与起始偏移,保证能逐字还原 */
51
+ function splitLines(text: string): Lines {
52
+ const texts: string[] = [];
53
+ const eols: string[] = [];
54
+ const offsets: number[] = [];
55
+ const re = /\r?\n/g;
56
+ let last = 0;
57
+ let m: RegExpExecArray | null;
58
+ while ((m = re.exec(text))) {
59
+ texts.push(text.slice(last, m.index));
60
+ eols.push(m[0]);
61
+ offsets.push(last);
62
+ last = m.index + m[0].length;
63
+ }
64
+ texts.push(text.slice(last));
65
+ eols.push('');
66
+ offsets.push(last);
67
+ return { texts, eols, offsets };
68
+ }
69
+
70
+ /** 文件开头 `---` 元信息区的结束行下标(含);没有则 -1。第二行要像 yaml(`key:`、注释,或直接闭合),否则是分隔线 */
71
+ export function frontMatterEnd(texts: string[]): number {
72
+ if (texts[0]?.trim() !== '---') return -1;
73
+ const second = (texts[1] ?? '').trim();
74
+ const looksYaml = second === '---' || second === '...' || second.startsWith('#') || /^[\w\u4e00-\u9fff-]+\s*:/.test(second);
75
+ if (!looksYaml) return -1;
76
+ for (let i = 1; i < texts.length; i++) {
77
+ const t = texts[i].trim();
78
+ if (t === '---' || t === '...') return i;
79
+ }
80
+ return -1;
81
+ }
82
+
83
+ interface Analysis {
84
+ lines: Lines;
85
+ /** 不参与评论识别 / 不可评论的行:元信息区 + 围栏代码块(含围栏行本身);评论自己的续行不算 */
86
+ skip: boolean[];
87
+ /** 真正闭合了某个围栏的那些行 */
88
+ fenceClose: Set<number>;
89
+ fmEnd: number;
90
+ comments: CommentSpan[];
91
+ }
92
+
93
+ /**
94
+ * 一趟扫描:边走边跟踪围栏,遇到合法评论就整段吞掉(评论内容里即使出现 ``` 也不影响后面的识别)。
95
+ * 评论内容里写代码是最自然的用法,所以围栏判断只作用于「评论之外」的行。
96
+ */
97
+ function analyze(text: string): Analysis {
98
+ const lines = splitLines(text);
99
+ const { texts, offsets } = lines;
100
+ const skip = new Array<boolean>(texts.length).fill(false);
101
+ const fenceClose = new Set<number>();
102
+ const fmEnd = frontMatterEnd(texts);
103
+ for (let i = 0; i <= fmEnd; i++) skip[i] = true;
104
+ const seen = new Set<string>();
105
+ const comments: CommentSpan[] = [];
106
+ let fence: { ch: string; len: number } | null = null;
107
+ for (let i = Math.max(0, fmEnd + 1); i < texts.length; i++) {
108
+ const line = texts[i];
109
+ if (fence) {
110
+ skip[i] = true;
111
+ const c = FENCE_CLOSE_RE.exec(line);
112
+ if (c && c[1][0] === fence.ch && c[1].length >= fence.len) {
113
+ fence = null;
114
+ fenceClose.add(i);
115
+ }
116
+ continue;
117
+ }
118
+ const open = FENCE_OPEN_RE.exec(line);
119
+ if (open) {
120
+ fence = { ch: open[1][0], len: open[1].length };
121
+ skip[i] = true;
122
+ continue;
123
+ }
124
+ const starts = [...line.matchAll(START_RE)];
125
+ if (starts.length !== 1) continue; // 没有,或同一行多条:不识别
126
+ const m = starts[0];
127
+ const id = m[1];
128
+ if (seen.has(id)) continue;
129
+ const col = m.index as number;
130
+ const endMarker = `[END:COMMENT:${id}]`;
131
+ const parts: string[] = [];
132
+ let endLine = -1;
133
+ let endCol = -1;
134
+ let bad = false;
135
+ for (let j = i; j < texts.length; j++) {
136
+ const from = j === i ? col + m[0].length : 0;
137
+ const k = texts[j].indexOf(endMarker, from);
138
+ const seg = k >= 0 ? texts[j].slice(from, k) : texts[j].slice(from);
139
+ if (ANY_START_RE.test(seg)) {
140
+ bad = true; // 嵌套
141
+ break;
142
+ }
143
+ parts.push(seg);
144
+ if (k >= 0) {
145
+ endLine = j;
146
+ endCol = k + endMarker.length;
147
+ break;
148
+ }
149
+ }
150
+ if (bad || endLine < 0) continue;
151
+ if (texts[endLine].slice(endCol).trim() !== '') continue; // 结束标记之后还有别的内容
152
+ seen.add(id);
153
+ comments.push({
154
+ id,
155
+ content: parts.join('\n'),
156
+ hostLine: i,
157
+ endLine,
158
+ ownLine: line.slice(0, col).trim() === '',
159
+ start: offsets[i] + col,
160
+ end: offsets[endLine] + texts[endLine].length,
161
+ });
162
+ i = endLine;
163
+ }
164
+ return { lines, skip, fenceClose, fmEnd, comments };
165
+ }
166
+
167
+ /** 找出文本里所有合法评论(按出现顺序) */
168
+ export function parseComments(text: string): CommentSpan[] {
169
+ return analyze(text).comments;
170
+ }
171
+
172
+ export interface StripResult {
173
+ /** 剔除评论后的文本(换行统一成 \n,直接交给渲染) */
174
+ text: string;
175
+ /** 剔除后的第 n 行 → 原文行号(0 起) */
176
+ lineMap: number[];
177
+ comments: CommentSpan[];
178
+ }
179
+
180
+ /** 把评论从正文里剔出来,并给出「剔除后的行 → 原文行」对照 */
181
+ export function stripComments(text: string): StripResult {
182
+ const comments = parseComments(text);
183
+ if (!comments.length) {
184
+ const n = text.split(/\r?\n/).length;
185
+ return { text: text.replace(/\r\n/g, '\n'), lineMap: Array.from({ length: n }, (_, i) => i), comments };
186
+ }
187
+ const { texts, offsets } = splitLines(text);
188
+ const drop = new Set<number>();
189
+ const cut = new Map<number, number>(); // 行 → 保留到的列
190
+ for (const c of comments) {
191
+ if (c.ownLine) {
192
+ for (let l = c.hostLine; l <= c.endLine; l++) drop.add(l);
193
+ } else {
194
+ cut.set(c.hostLine, c.start - offsets[c.hostLine]);
195
+ for (let l = c.hostLine + 1; l <= c.endLine; l++) drop.add(l);
196
+ }
197
+ }
198
+ const lines: string[] = [];
199
+ const lineMap: number[] = [];
200
+ for (let i = 0; i < texts.length; i++) {
201
+ if (drop.has(i)) continue;
202
+ lines.push(cut.has(i) ? texts[i].slice(0, cut.get(i)) : texts[i]);
203
+ lineMap.push(i);
204
+ }
205
+ return { text: lines.join('\n'), lineMap, comments };
206
+ }
207
+
208
+ export type EditErrorCode = 'empty' | 'too_long' | 'has_marker' | 'bad_anchor' | 'stale_anchor' | 'exists' | 'not_found';
209
+ export type EditResult = { ok: true; text: string; id: string } | { ok: false; code: EditErrorCode };
210
+
211
+ /** 内容规整:统一换行、去首尾空白 */
212
+ export function normalizeContent(content: string): string {
213
+ return content.replace(/\r\n/g, '\n').trim();
214
+ }
215
+
216
+ /** 校验评论内容;通过返回 null */
217
+ export function validateContent(content: string): EditErrorCode | null {
218
+ const c = normalizeContent(content);
219
+ if (!c) return 'empty';
220
+ if (c.length > MAX_COMMENT_LEN) return 'too_long';
221
+ if (MARKER_IN_CONTENT_RE.test(c)) return 'has_marker';
222
+ return null;
223
+ }
224
+
225
+ /** 生成与已有编号不冲突的新编号 */
226
+ export function newCommentId(existing: Set<string>, rand: () => number = Math.random): string {
227
+ const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
228
+ for (;;) {
229
+ let id = '';
230
+ for (let i = 0; i < 6; i++) id += chars[Math.floor(rand() * chars.length)];
231
+ if (!existing.has(id)) return id;
232
+ }
233
+ }
234
+
235
+ function render(id: string, content: string, eol: string): string {
236
+ return `,,[START:COMMENT:${id}]${normalizeContent(content).replace(/\n/g, eol)}[END:COMMENT:${id}]`;
237
+ }
238
+
239
+ function defaultEol(eols: string[]): string {
240
+ return eols.find((e) => e) || '\n';
241
+ }
242
+
243
+ export interface AddInput {
244
+ /** 追加位置所在的原文行(0 起):一般块是最后一行;围栏代码块是闭合围栏行 */
245
+ line: number;
246
+ /** 前端看到的该行文本(已剔除评论),必须与磁盘一致,防行号错位 */
247
+ expect: string;
248
+ /** true = 在 line 的下一行单独新开一行放评论(围栏代码块用) */
249
+ own?: boolean;
250
+ /** own 时新行的缩进 */
251
+ indent?: string;
252
+ content: string;
253
+ id?: string;
254
+ }
255
+
256
+ /** 新增一条评论 */
257
+ export function addComment(text: string, input: AddInput): EditResult {
258
+ const bad = validateContent(input.content);
259
+ if (bad) return { ok: false, code: bad };
260
+ const a = analyze(text);
261
+ const { texts, eols, offsets } = a.lines;
262
+ const { line } = input;
263
+ if (!Number.isInteger(line) || line < 0 || line >= texts.length) return { ok: false, code: 'bad_anchor' };
264
+ if (line <= a.fmEnd) return { ok: false, code: 'bad_anchor' };
265
+ if (input.own) {
266
+ // 评论放在「真正闭合了围栏」的那一行之后;裸的开围栏行不行(评论会落进代码块里)
267
+ if (!a.fenceClose.has(line)) return { ok: false, code: 'bad_anchor' };
268
+ if (a.comments.some((c) => c.ownLine && c.hostLine === line + 1)) return { ok: false, code: 'exists' };
269
+ } else {
270
+ // 围栏内、元信息区、空白行都不能挂评论(空白行挂上后剔除会把上下两段并成一段)
271
+ if (a.skip[line] || texts[line].trim() === '') return { ok: false, code: 'bad_anchor' };
272
+ if (a.comments.some((c) => c.hostLine <= line && line <= c.endLine)) return { ok: false, code: 'exists' };
273
+ }
274
+ if (texts[line] !== input.expect) return { ok: false, code: 'stale_anchor' };
275
+ const id = input.id ?? newCommentId(new Set(a.comments.map((c) => c.id)));
276
+ const eol = defaultEol(eols);
277
+ const at = offsets[line] + texts[line].length;
278
+ const piece = input.own ? `${eol}${input.indent ?? ''}${render(id, input.content, eol)}` : render(id, input.content, eol);
279
+ return { ok: true, text: text.slice(0, at) + piece + text.slice(at), id };
280
+ }
281
+
282
+ /** 修改一条评论的内容 */
283
+ export function updateComment(text: string, id: string, content: string): EditResult {
284
+ const bad = validateContent(content);
285
+ if (bad) return { ok: false, code: bad };
286
+ const c = parseComments(text).find((x) => x.id === id);
287
+ if (!c) return { ok: false, code: 'not_found' };
288
+ const eol = defaultEol(splitLines(text).eols);
289
+ return { ok: true, text: text.slice(0, c.start) + render(id, content, eol) + text.slice(c.end), id };
290
+ }
291
+
292
+ /** 删除一条评论(独占整行的连行一起去掉) */
293
+ export function deleteComment(text: string, id: string): EditResult {
294
+ const c = parseComments(text).find((x) => x.id === id);
295
+ if (!c) return { ok: false, code: 'not_found' };
296
+ if (!c.ownLine) return { ok: true, text: text.slice(0, c.start) + text.slice(c.end), id };
297
+ const { texts, eols, offsets } = splitLines(text);
298
+ let from = offsets[c.hostLine];
299
+ const to = offsets[c.endLine] + texts[c.endLine].length + eols[c.endLine].length;
300
+ // 评论行是最后一行(后面没有换行)时,把它前面那个换行一起去掉,避免留下空行
301
+ if (!eols[c.endLine] && c.hostLine > 0) from -= eols[c.hostLine - 1].length;
302
+ return { ok: true, text: text.slice(0, from) + text.slice(to), id };
303
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * config.ts — 读写 $WK/.vault-service/vault-service.json。
3
+ *
4
+ * 记录本地 service 的 port / pid / 起停时间 与 default vault root。
5
+ * 可重建、不入 git(目录自带 `.gitignore` 自忽略);缺失/损坏按空处理。
6
+ */
7
+
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { SERVICE_GITIGNORE, cacheDir, configPath, resolveWk } from './workspace.js';
11
+
12
+ /**
13
+ * 内置默认值(代码里的一层,入库、团队一致)。
14
+ * 想自己改的话,在下面 ServiceConfig 对应字段里写(运行态文件,不入库、每台机器各自维护)。
15
+ */
16
+
17
+ /** 遍历 / 监听 / 导航树都跳过的目录名(.vault-service 移出 temp/ 后须单独跳过,否则会被索引);extraSkipDirs 叠加在它之上 */
18
+ export const DEFAULT_SKIP_DIRS: ReadonlySet<string> = new Set([
19
+ 'node_modules', '.git', 'temp', '.vault-service', '.playwright-mcp', '__pycache__', 'dist', 'build', 'coverage',
20
+ ]);
21
+
22
+ /**
23
+ * 默认索引后缀(文本类);可通过配置 indexExts 整体替换。
24
+ * scan 与文件监听共用这一份:放宽会让 scan 多索引文件(重扫变慢),收窄会让监听少盯文件,
25
+ * 同时页面能不能打开某种后缀的文件也跟着它走(/file 只放行清单内后缀)。
26
+ */
27
+ export const DEFAULT_INDEX_EXTS: readonly string[] = [
28
+ '.md', '.txt', '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
29
+ '.yaml', '.yml', '.toml', '.ini', '.cfg', '.conf', '.properties', '.xml',
30
+ '.html', '.htm', '.css', '.scss', '.less', '.sass', '.vue', '.svelte',
31
+ '.py', '.java', '.kt', '.go', '.rs', '.c', '.h', '.cpp', '.hpp', '.cs', '.rb', '.php',
32
+ '.sh', '.bash', '.zsh', '.sql', '.gradle', '.tsv', '.svg',
33
+ ];
34
+
35
+ /**
36
+ * 默认忽略的文件(命中的文件不进索引、不监听;页面的文件树与打开文件不受影响)。
37
+ * `*.raw.*`:原文誊录文件(如提示词原文样本)里常带着 ctag 字样,不该当文档去索引。
38
+ */
39
+ export const DEFAULT_IGNORE_PATTERNS: readonly string[] = ['*.raw.*'];
40
+
41
+ export interface ServiceConfig {
42
+ /** 本地监听端口(动态分配后落盘) */
43
+ port?: number;
44
+ /** service 进程 pid */
45
+ pid?: number;
46
+ /** service API 协议版本 */
47
+ apiVersion?: string;
48
+ /** 启动时间 ISO 串 */
49
+ startedAt?: string;
50
+ /** 默认 vault root(相对 $WK 的路径,如 memory/{UUAP}/vaults) */
51
+ defaultRoot?: string;
52
+ /** 索引面:收录的文件后缀(小写带点,如 ['.md','.txt']);写了就整体替换 DEFAULT_INDEX_EXTS(空数组按缺省处理)。scan 与文件监听共用;监听侧改了需重启 service 才生效 */
53
+ indexExts?: string[];
54
+ /** 额外跳过的目录名(叠加在 DEFAULT_SKIP_DIRS 之上);scan 与文件监听共用;监听侧改了需重启 service 才生效 */
55
+ extraSkipDirs?: string[];
56
+ /**
57
+ * 忽略的文件通配:写了就整体替换 DEFAULT_IGNORE_PATTERNS,空数组表示「不忽略任何」。
58
+ * 不含 `/` 的模式匹配文件名(任意层级),含 `/` 的匹配相对 $WK 的路径;支持 `*` `?` `**`。
59
+ * scan 与文件监听共用;监听侧改了需重启 service 才生效
60
+ */
61
+ ignorePatterns?: string[];
62
+ }
63
+
64
+
65
+ /**
66
+ * 确保运行态目录存在,并写入自忽略 `.gitignore`(`*` + `!.gitignore` + 放行团队评论模板):
67
+ * 运行态文件永不进 git,而 `.gitignore` 自身可入库、让"这目录的约定"随仓库走。
68
+ */
69
+ export function ensureCacheDir(wk: string): void {
70
+ const dir = cacheDir(wk);
71
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
72
+ const gi = join(dir, '.gitignore');
73
+ if (!existsSync(gi)) writeFileSync(gi, SERVICE_GITIGNORE);
74
+ }
75
+
76
+ /** 读配置;缺失/损坏返回 {} */
77
+ export function readConfig(wk: string = resolveWk()): ServiceConfig {
78
+ const p = configPath(wk);
79
+ if (!existsSync(p)) return {};
80
+ try {
81
+ const raw: unknown = JSON.parse(readFileSync(p, 'utf8'));
82
+ return raw && typeof raw === 'object' ? (raw as ServiceConfig) : {};
83
+ } catch {
84
+ return {};
85
+ }
86
+ }
87
+
88
+ /** 合并写入配置(浅合并已有字段) */
89
+ export function writeConfig(patch: ServiceConfig, wk: string = resolveWk()): ServiceConfig {
90
+ ensureCacheDir(wk);
91
+ const next = { ...readConfig(wk), ...patch };
92
+ const p = configPath(wk);
93
+ if (!existsSync(dirname(p))) mkdirSync(dirname(p), { recursive: true });
94
+ writeFileSync(p, `${JSON.stringify(next, null, 2)}\n`);
95
+ return next;
96
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * ctag-shape.ts — ctag 形态的纯常量定义(无 node 依赖),供 core 与 web 共享。
3
+ *
4
+ * 形态:{ref|def}#{descr}.{YYMMDD}_{5hash}_ctag.
5
+ * 单一事实源:core/ctag.ts(服务端解析/生成)与 web/src/lib/md.ts(前端可点化)都从这里取,
6
+ * 形态演进只改这一处,避免三处活拷贝漂移(见 review muh9y)。
7
+ */
8
+
9
+ /** 5 位随机码字母表 [0-9a-z](base36) */
10
+ export const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
11
+ export const HASH_LEN = 5;
12
+
13
+ /** descr 允许字符:数字 / 英文 / 下划线 / 中文(可空) */
14
+ export const DESCR = '[0-9A-Za-z_\\u4e00-\\u9fff]*';
15
+
16
+ /** ctag 正则源串(不含 flags):(kind)#(descr).(date)_(hash)_ctag. 末点可选 */
17
+ export const CTAG_PATTERN = `(def|ref)#(${DESCR})\\.(\\d{6})_([0-9a-z]{5})_ctag\\.?`;
18
+
19
+ /** 全局扫描用(带分组,供 core 解析);每次 new 出独立实例避免 lastIndex 串扰 */
20
+ export function ctagRegexGlobal(): RegExp {
21
+ return new RegExp(CTAG_PATTERN, 'g');
22
+ }