dsh-procedures 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cards.mjs ADDED
@@ -0,0 +1,619 @@
1
+ import {
2
+ appendFileSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { basename, join, relative, resolve } from 'node:path';
11
+
12
+ import { hitsOf, outcomesOf, readStats, readStatsAt } from './stats.mjs';
13
+
14
+ export const CARD_LIMIT_BYTES = 2048;
15
+ export const RARE_LIMIT_BYTES = 3072;
16
+ const FRONT_MATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
17
+ const REQUIRED_SECTIONS = ['首选', '别再来', '注意'];
18
+
19
+ function unquote(value) {
20
+ const text = String(value ?? '').trim();
21
+ if (text.length >= 2) {
22
+ const first = text[0];
23
+ const last = text[text.length - 1];
24
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
25
+ return text.slice(1, -1);
26
+ }
27
+ }
28
+ return text;
29
+ }
30
+
31
+ /** Parse the small YAML subset used by card front matter. */
32
+ export function parseYamlLite(source) {
33
+ const out = {};
34
+ const lines = String(source ?? '').split(/\r?\n/);
35
+ let key = null;
36
+ for (let index = 0; index < lines.length; index += 1) {
37
+ const line = lines[index].replace(/\s+$/, '');
38
+ if (!line.trim() || line.trimStart().startsWith('#')) continue;
39
+
40
+ const item = /^\s*-\s+(.*)$/.exec(line);
41
+ if (item && key !== null) {
42
+ if (!Array.isArray(out[key])) out[key] = [];
43
+ out[key].push(unquote(item[1]));
44
+ continue;
45
+ }
46
+
47
+ const pair = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line);
48
+ if (!pair) continue;
49
+ key = pair[1];
50
+ const raw = pair[2].trim();
51
+ if (raw === '|' || raw === '>') {
52
+ const block = [];
53
+ let cursor = index + 1;
54
+ while (cursor < lines.length) {
55
+ const next = lines[cursor];
56
+ if (next.trim() === '') {
57
+ block.push('');
58
+ cursor += 1;
59
+ continue;
60
+ }
61
+ if (!/^\s+/.test(next)) break;
62
+ block.push(next);
63
+ cursor += 1;
64
+ }
65
+ const nonEmpty = block.filter((row) => row.trim().length > 0);
66
+ const indent = nonEmpty.length > 0
67
+ ? Math.min(...nonEmpty.map((row) => /^\s*/.exec(row)[0].length))
68
+ : 0;
69
+ const content = block.map((row) => row.slice(indent)).join('\n');
70
+ out[key] = raw === '|' ? content.replace(/\s+$/, '') : content.replace(/\s+/g, ' ').trim();
71
+ index = cursor - 1;
72
+ continue;
73
+ }
74
+ if (raw === '') {
75
+ out[key] = [];
76
+ continue;
77
+ }
78
+ if (raw === 'null' || raw === '~') {
79
+ out[key] = null;
80
+ continue;
81
+ }
82
+ if (raw.startsWith('[') && raw.endsWith(']')) {
83
+ out[key] = raw
84
+ .slice(1, -1)
85
+ .split(',')
86
+ .map((part) => unquote(part))
87
+ .filter(Boolean);
88
+ continue;
89
+ }
90
+ out[key] = unquote(raw);
91
+ }
92
+ return out;
93
+ }
94
+
95
+ export function parseFrontMatter(text) {
96
+ const match = FRONT_MATTER_RE.exec(String(text ?? ''));
97
+ if (!match) return { data: {}, body: String(text ?? ''), hasFrontMatter: false };
98
+ return {
99
+ data: parseYamlLite(match[1]),
100
+ body: String(text ?? '').slice(match[0].length),
101
+ hasFrontMatter: true,
102
+ };
103
+ }
104
+
105
+ function normalizeList(value) {
106
+ if (value === null || value === undefined) return [];
107
+ if (Array.isArray(value)) {
108
+ return value.map((item) => String(item).trim()).filter(Boolean);
109
+ }
110
+ return String(value)
111
+ .split(/[,,、;;\n]/)
112
+ .map((item) => item.trim())
113
+ .filter(Boolean);
114
+ }
115
+
116
+ function firstHeading(body) {
117
+ const match = /^#\s+(.+)$/m.exec(body);
118
+ return match ? match[1].trim() : '';
119
+ }
120
+
121
+ function legacyField(body, label) {
122
+ const pattern = new RegExp(
123
+ `^\\s*(?:>\\s*)?(?:\\*\\*)?${label}(?:\\*\\*)?\\s*[::]\\s*(.+)$`,
124
+ 'm',
125
+ );
126
+ const match = pattern.exec(body);
127
+ return match ? match[1].trim() : '';
128
+ }
129
+
130
+ function normalizeLegacyAnchors(raw) {
131
+ return raw
132
+ .split(/[,,、;;]/)
133
+ .map((item) => item.trim())
134
+ .filter(Boolean);
135
+ }
136
+
137
+ function firstFencedCode(body) {
138
+ const match = /```([^\n`]*)\r?\n([\s\S]*?)```/.exec(body);
139
+ if (!match) return { language: '', code: '' };
140
+ return { language: match[1].trim(), code: match[2].trim() };
141
+ }
142
+
143
+ export function parseCard(text, filePath = '<memory>') {
144
+ const source = String(text ?? '');
145
+ const { data, body, hasFrontMatter } = parseFrontMatter(source);
146
+ const legacyTrigger = legacyField(body, '触发');
147
+ const legacyAnchor = legacyField(body, '锚点');
148
+
149
+ const anchors = normalizeList(data.anchors ?? data.anchor)
150
+ .concat(normalizeLegacyAnchors(legacyAnchor))
151
+ .filter((item, index, list) => list.indexOf(item) === index);
152
+ const triggers = normalizeList(data.triggers ?? data.trigger).concat(
153
+ legacyTrigger ? [legacyTrigger] : [],
154
+ );
155
+
156
+ const file = basename(filePath);
157
+ const id = String(data.id ?? file.replace(/\.md$/i, '')).trim();
158
+ const title = String(data.title ?? firstHeading(body) ?? file).trim() || file;
159
+ const type = String(data.type ?? 'trap').trim().toLowerCase() || 'trap';
160
+ const rarity = String(data.rarity ?? 'common').trim().toLowerCase() || 'common';
161
+ const fenced = firstFencedCode(body);
162
+ const actionableCode = String(data.actionable_code ?? '').trim() || fenced.code;
163
+ const language = String(data.language ?? fenced.language ?? '').trim();
164
+ const requires = normalizeList(data.requires ?? data.require);
165
+ const excludes = normalizeList(data.excludes ?? data.exclude);
166
+ const validUntil = data.valid_until ?? data.expires ?? null;
167
+ const validUntilTime = (() => {
168
+ if (validUntil === null || validUntil === undefined || validUntil === '') return null;
169
+ const time = Date.parse(String(validUntil));
170
+ return Number.isFinite(time) ? time : null;
171
+ })();
172
+
173
+ return {
174
+ path: filePath,
175
+ file,
176
+ id,
177
+ title,
178
+ type,
179
+ isSpell: type === 'spell',
180
+ rarity,
181
+ anchors,
182
+ triggers,
183
+ requires,
184
+ excludes,
185
+ anchorKeys: anchors.map((item) => item.toLowerCase()),
186
+ triggerKeys: triggers.map((item) => item.toLowerCase()),
187
+ requireKeys: requires.map((item) => item.toLowerCase()),
188
+ excludeKeys: excludes.map((item) => item.toLowerCase()),
189
+ actionableCode,
190
+ language,
191
+ validUntil,
192
+ validUntilTime,
193
+ environment: data.environment ?? null,
194
+ created: data.created ?? null,
195
+ lastHit: data.last_hit ?? null,
196
+ hits: Number.parseInt(String(data.hits ?? '0'), 10) || 0,
197
+ body,
198
+ text: source,
199
+ hasFrontMatter,
200
+ size: Buffer.byteLength(source, 'utf8'),
201
+ };
202
+ }
203
+
204
+ function listMarkdownFiles(dir) {
205
+ const files = [];
206
+ if (!existsSync(dir)) return files;
207
+ for (const name of readdirSync(dir)) {
208
+ if (!name.toLowerCase().endsWith('.md')) continue;
209
+ if (name.startsWith('_')) continue;
210
+ if (name === 'INDEX.md' || name === 'README.md') continue;
211
+ files.push(resolve(dir, name));
212
+ }
213
+ return files;
214
+ }
215
+
216
+ const CARD_CACHE = new Map();
217
+ const CARD_CACHE_TTL_MS = 750;
218
+
219
+ export function clearCardCache() {
220
+ CARD_CACHE.clear();
221
+ }
222
+
223
+ function collectCardFiles(root) {
224
+ const files = new Set();
225
+ for (const file of listMarkdownFiles(join(root, 'cards'))) files.add(file);
226
+ for (const file of listMarkdownFiles(root)) files.add(file);
227
+ return [...files].sort();
228
+ }
229
+
230
+ function signatureOf(files) {
231
+ return files.map((file) => {
232
+ try {
233
+ const stat = statSync(file);
234
+ return `${file}:${stat.mtimeMs}:${stat.size}`;
235
+ } catch {
236
+ return `${file}:missing`;
237
+ }
238
+ }).join('|');
239
+ }
240
+
241
+ export function loadCards(dir, options = {}) {
242
+ const root = resolve(dir);
243
+ const scope = options.scope ?? 'workspace';
244
+ const files = collectCardFiles(root);
245
+ const key = `${root}\u0000${scope}`;
246
+ const cached = CARD_CACHE.get(key);
247
+ const now = Date.now();
248
+ if (!options.refresh && cached !== undefined && now - cached.checkedAt < CARD_CACHE_TTL_MS) {
249
+ return cached.cards;
250
+ }
251
+
252
+ const signature = signatureOf(files);
253
+ if (!options.refresh && cached !== undefined && cached.signature === signature) {
254
+ cached.checkedAt = now;
255
+ return cached.cards;
256
+ }
257
+
258
+ const cards = files.map((file) => ({
259
+ ...parseCard(readFileSync(file, 'utf8'), file),
260
+ scope,
261
+ }));
262
+ CARD_CACHE.set(key, { signature, cards, checkedAt: now });
263
+ return cards;
264
+ }
265
+
266
+ export function isExpired(card, now = Date.now()) {
267
+ if (Number.isFinite(card.validUntilTime)) return card.validUntilTime < now;
268
+ if (card.validUntilTime === null) return false;
269
+ if (card.validUntil === null || card.validUntil === undefined || card.validUntil === '') {
270
+ return false;
271
+ }
272
+ const time = Date.parse(String(card.validUntil));
273
+ return Number.isFinite(time) && time < now;
274
+ }
275
+
276
+ function tokens(text) {
277
+ return String(text ?? '')
278
+ .normalize('NFKC')
279
+ .toLowerCase()
280
+ .split(/[^\p{L}\p{N}]+/u)
281
+ .filter((token) => token.length >= 2);
282
+ }
283
+
284
+ function matchTrigger(trigger, triggerLower, query, lowerQuery) {
285
+ const text = String(trigger ?? '').trim();
286
+ if (!text) return false;
287
+ const regex = /^\/(.+)\/([a-z]*)$/s.exec(text);
288
+ if (regex) {
289
+ try {
290
+ return new RegExp(regex[1], regex[2]).test(query);
291
+ } catch {
292
+ return false;
293
+ }
294
+ }
295
+ return triggerLower.length >= 2 && lowerQuery.includes(triggerLower);
296
+ }
297
+
298
+ /**
299
+ * Rank cards against a task/error string. Anchors outrank triggers; body text
300
+ * is only a last resort so a long error message does not match everything.
301
+ * `strict` disables title/body fallback; `globalDir` adds a read-only library
302
+ * where workspace cards with the same id win.
303
+ */
304
+ export function searchCards(dir, query, options = {}) {
305
+ const rawQuery = String(query ?? '').trim();
306
+ if (!rawQuery) return [];
307
+ const now = options.now ?? Date.now();
308
+ const lowerQuery = rawQuery.toLowerCase();
309
+ const max = Number.isInteger(options.max) ? options.max : 3;
310
+ const scored = [];
311
+
312
+ const workspaceCards = loadCards(dir, { scope: 'workspace' });
313
+ let cards = workspaceCards;
314
+ if (options.globalDir) {
315
+ const workspaceIds = new Set(workspaceCards.map((card) => card.id));
316
+ const globalCards = loadCards(options.globalDir, { scope: 'global' })
317
+ .filter((card) => !workspaceIds.has(card.id));
318
+ cards = workspaceCards.concat(globalCards);
319
+ }
320
+
321
+ for (const card of cards) {
322
+ const expired = isExpired(card, now);
323
+ if (expired && !options.includeExpired) continue;
324
+
325
+ const excluded = card.excludeKeys.some(
326
+ (term) => term.length >= 2 && lowerQuery.includes(term),
327
+ );
328
+ if (excluded) continue;
329
+ const missingRequired = card.requireKeys.some(
330
+ (term) => term.length >= 2 && !lowerQuery.includes(term),
331
+ );
332
+ if (missingRequired) continue;
333
+
334
+ let score = 0;
335
+ const matched = [];
336
+
337
+ card.anchorKeys.forEach((anchorKey, index) => {
338
+ if (anchorKey.length >= 2 && lowerQuery.includes(anchorKey)) {
339
+ score += 3;
340
+ matched.push({ on: 'anchor', value: card.anchors[index] });
341
+ }
342
+ });
343
+ card.triggers.forEach((trigger, index) => {
344
+ if (matchTrigger(trigger, card.triggerKeys[index], rawQuery, lowerQuery)) {
345
+ score += 2;
346
+ matched.push({ on: 'trigger', value: trigger });
347
+ }
348
+ });
349
+ if (score === 0 && options.strict !== true) {
350
+ for (const token of tokens(`${card.title} ${card.file}`)) {
351
+ if (token.length >= 4 && lowerQuery.includes(token)) {
352
+ score += 1;
353
+ matched.push({ on: 'title', value: token });
354
+ }
355
+ }
356
+ }
357
+ if (score === 0 && options.strict !== true && rawQuery.length >= 3 && rawQuery.length <= 120) {
358
+ if (card.body.toLowerCase().includes(lowerQuery)) {
359
+ score += 1;
360
+ matched.push({ on: 'body', value: rawQuery });
361
+ }
362
+ }
363
+
364
+ const penalty = card.scope === 'global' && Number.isFinite(Number(options.globalPenalty))
365
+ ? Number(options.globalPenalty)
366
+ : 0;
367
+ const adjusted = score - penalty;
368
+ if (adjusted > 0) scored.push({ ...card, score: adjusted, matched, expired });
369
+ }
370
+
371
+ scored.sort((left, right) => right.score - left.score
372
+ || (left.scope === right.scope ? 0 : left.scope === 'workspace' ? -1 : 1)
373
+ || left.file.localeCompare(right.file));
374
+ return scored.slice(0, max);
375
+ }
376
+
377
+ export function auditCards(dir, options = {}) {
378
+ const now = options.now ?? Date.now();
379
+ const staleDays = Number.isFinite(Number(options.staleDays)) && Number(options.staleDays) > 0
380
+ ? Number(options.staleDays)
381
+ : 90;
382
+ const workspaceCards = loadCards(dir, { refresh: true, scope: 'workspace' });
383
+ const workspaceStats = readStats(dir);
384
+ const globalCards = options.globalDir
385
+ ? loadCards(options.globalDir, { refresh: true, scope: 'global' })
386
+ : [];
387
+ const globalStats = options.globalStatsFile
388
+ ? readStatsAt(options.globalStatsFile)
389
+ : { version: 1, cards: {}, updated_at: null };
390
+
391
+ const entries = [
392
+ ...workspaceCards.map((card) => ({ card, scope: 'workspace', stats: workspaceStats })),
393
+ ...globalCards.map((card) => ({ card, scope: 'global', stats: globalStats })),
394
+ ];
395
+ const issues = [];
396
+ const seenIds = new Map();
397
+
398
+ for (const { card, scope, stats } of entries) {
399
+ const report = (severity, code, message) => {
400
+ issues.push({ severity, code, file: card.file, scope, message });
401
+ };
402
+
403
+ if (!card.hasFrontMatter) {
404
+ report('warn', 'no-front-matter', '缺少 YAML front matter(按旧卡兼容读取)');
405
+ }
406
+ if (!card.id) report('error', 'no-id', '缺少 id');
407
+ if (!card.title) report('error', 'no-title', '缺少 title');
408
+ if (card.anchors.length === 0) {
409
+ report('error', 'no-anchors', '缺少 anchors,失败时无法精确命中');
410
+ } else if (card.anchors.length < 3) {
411
+ report('warn', 'few-anchors', `只有 ${card.anchors.length} 个锚点,建议 3–8 个`);
412
+ } else if (card.anchors.length > 8) {
413
+ report('warn', 'many-anchors', `有 ${card.anchors.length} 个锚点,过多等于没筛`);
414
+ }
415
+ if (card.triggers.length === 0) report('warn', 'no-triggers', '缺少 triggers');
416
+ if (card.type === 'spell') {
417
+ if (!card.actionableCode) {
418
+ report('error', 'spell-without-code', 'spell 卡缺少 actionable_code 或代码块');
419
+ }
420
+ if (!card.language) {
421
+ report('warn', 'spell-without-language', 'spell 卡建议标注 language');
422
+ }
423
+ if (!card.body.includes('验证')) {
424
+ report('error', 'spell-without-verify', 'spell 卡缺少「验证」段');
425
+ }
426
+ } else if (card.type !== 'trap') {
427
+ report('warn', 'unknown-type', `未知 type「${card.type}」,按 trap 处理`);
428
+ }
429
+ const limit = card.rarity === 'rare' ? RARE_LIMIT_BYTES : CARD_LIMIT_BYTES;
430
+ if (card.size > limit) {
431
+ report('error', 'oversize', `${card.size} B 超过 ${limit} B 上限(${card.rarity})`);
432
+ }
433
+ if (!['common', 'rare'].includes(card.rarity)) {
434
+ report('warn', 'unknown-rarity', `未知 rarity「${card.rarity}」,按 common 处理`);
435
+ }
436
+ const hits = hitsOf(stats, card);
437
+ const outcomes = outcomesOf(stats, card);
438
+ if (hits >= 3 && card.rarity !== 'rare') {
439
+ report('info', 'promotion-candidate', `命中 ${hits} 次,可考虑升 rare(需人工改 YAML)`);
440
+ }
441
+ if (card.rarity === 'rare' && hits < 3) {
442
+ report('warn', 'rare-with-few-hits', `rare 但只命中 ${hits} 次,确认是否够格`);
443
+ }
444
+ if (outcomes.repeated >= 2 && outcomes.repeated >= outcomes.noRepeat) {
445
+ report(
446
+ 'warn',
447
+ 'repeat-after-hint',
448
+ `命中后同类错误复发 ${outcomes.repeated} 次 / 未复发 ${outcomes.noRepeat} 次;检查锚点或解法`,
449
+ );
450
+ }
451
+ for (const section of REQUIRED_SECTIONS) {
452
+ if (!card.body.includes(section)) {
453
+ report('error', 'missing-section', `缺少「${section}」段`);
454
+ }
455
+ }
456
+ if (!card.body.includes('证据')) report('warn', 'no-evidence', '缺少「证据」段');
457
+ if (isExpired(card, now)) {
458
+ report('warn', 'expired', `valid_until ${card.validUntil} 已过期`);
459
+ }
460
+ if (scope === 'global') {
461
+ const last = stats.cards?.[card.id]?.last_hit;
462
+ const baselineText = typeof last === 'string' ? last : card.created;
463
+ const baseline = baselineText ? Date.parse(String(baselineText)) : NaN;
464
+ if (Number.isFinite(baseline) && now - baseline > staleDays * 86400000) {
465
+ report('warn', 'stale-global', `global 卡最后活动 ${baselineText},超过 ${staleDays} 天;考虑复核/退役`);
466
+ }
467
+ }
468
+ const key = `${scope}\u0000${card.id}`;
469
+ if (seenIds.has(key)) {
470
+ report('error', 'duplicate-id', `id 与 ${seenIds.get(key)} 重复`);
471
+ } else {
472
+ seenIds.set(key, card.file);
473
+ }
474
+ }
475
+
476
+ const order = { error: 0, warn: 1, info: 2 };
477
+ issues.sort((left, right) => order[left.severity] - order[right.severity]
478
+ || (left.scope === right.scope ? 0 : left.scope === 'workspace' ? -1 : 1)
479
+ || left.file.localeCompare(right.file));
480
+ return {
481
+ dir: resolve(dir),
482
+ globalDir: options.globalDir ? resolve(options.globalDir) : null,
483
+ cards: entries.length,
484
+ scopes: { workspace: workspaceCards.length, global: globalCards.length },
485
+ stats: {
486
+ tracked: Object.keys(workspaceStats.cards).length,
487
+ globalTracked: Object.keys(globalStats.cards).length,
488
+ },
489
+ issues,
490
+ ok: issues.every((issue) => issue.severity !== 'error'),
491
+ };
492
+ }
493
+
494
+ function oneLine(text) {
495
+ return String(text ?? '').replace(/\s+/g, ' ').trim();
496
+ }
497
+
498
+ function timestamp(date = new Date()) {
499
+ const pad = (value) => String(value).padStart(2, '0');
500
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
501
+ }
502
+
503
+ /** Append one inbox line; duplicate signatures inside the tail are skipped. */
504
+ export function appendInbox(dir, entry = {}) {
505
+ const root = resolve(dir);
506
+ if (!existsSync(root)) return { added: false, reason: 'missing-dir' };
507
+ const file = join(root, '_inbox.md');
508
+ const tool = oneLine(entry.tool ?? 'tool') || 'tool';
509
+ const message = oneLine(entry.message ?? '').slice(0, 160);
510
+ if (!message) return { added: false, reason: 'empty-message' };
511
+ const line = `- ${timestamp(entry.time instanceof Date ? entry.time : new Date())} [${tool}] ${message}`;
512
+
513
+ let current = '';
514
+ if (existsSync(file)) current = readFileSync(file, 'utf8');
515
+ const tail = current.split(/\r?\n/).slice(-100);
516
+ const duplicated = tail.some((row) => {
517
+ const match = /^-\s+\S+ \S+\s+\[([^\]]+)\]\s+(.*)$/.exec(row);
518
+ return match !== null
519
+ && match[1] === tool
520
+ && match[2].slice(0, 120) === message.slice(0, 120);
521
+ });
522
+ if (duplicated) {
523
+ return { added: false, reason: 'duplicate' };
524
+ }
525
+
526
+ mkdirSync(root, { recursive: true });
527
+ const prefix = current.length === 0
528
+ ? ''
529
+ : current.endsWith('\n\n')
530
+ ? ''
531
+ : current.endsWith('\n')
532
+ ? '\n'
533
+ : '\n\n';
534
+ appendFileSync(file, `${prefix}${line}\n`, 'utf8');
535
+ return { added: true, line, file };
536
+ }
537
+
538
+ export function readInbox(dir) {
539
+ const file = join(resolve(dir), '_inbox.md');
540
+ if (!existsSync(file)) return [];
541
+ return readFileSync(file, 'utf8')
542
+ .split(/\r?\n/)
543
+ .map((line) => /^-\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2})\s+\[([^\]]+)\]\s+(.*)$/.exec(line))
544
+ .filter(Boolean)
545
+ .map((match) => ({ time: match[1], tool: match[2], message: match[3] }));
546
+ }
547
+
548
+ /** Turn inbox lines into review drafts. No model call, no promotion. */
549
+ export function synthesizeDrafts(dir, options = {}) {
550
+ const root = resolve(dir);
551
+ const outDir = resolve(options.outDir ?? join(root, '_drafts'));
552
+ const entries = readInbox(root);
553
+ if (entries.length === 0) return { created: [], skipped: 0, outDir };
554
+
555
+ const unique = [];
556
+ const seen = new Set();
557
+ for (const entry of entries) {
558
+ const key = `${entry.tool}|${entry.message.slice(0, 100)}`;
559
+ if (seen.has(key)) continue;
560
+ seen.add(key);
561
+ unique.push(entry);
562
+ }
563
+
564
+ mkdirSync(outDir, { recursive: true });
565
+ const created = [];
566
+ let skipped = 0;
567
+ unique.slice(0, Number(options.max ?? 20)).forEach((entry, index) => {
568
+ const date = entry.time.slice(0, 10).replaceAll('-', '');
569
+ const name = `draft-${date}-${String(index + 1).padStart(2, '0')}.md`;
570
+ const file = join(outDir, name);
571
+ if (existsSync(file)) {
572
+ skipped += 1;
573
+ return;
574
+ }
575
+ const slug = `${entry.tool}-${entry.message.slice(0, 24)}`.replace(/[^\p{L}\p{N}-]+/gu, '-');
576
+ const content = `---
577
+ id: draft-${date}-${index + 1}
578
+ title: TODO ${slug}
579
+ type: trap
580
+ triggers: []
581
+ anchors: []
582
+ valid_until: null
583
+ environment: ""
584
+ created: ${entry.time.slice(0, 10)}
585
+ last_hit: null
586
+ hits: 0
587
+ ---
588
+
589
+ # TODO-${slug}
590
+
591
+ ## 触发
592
+ - ${entry.message}
593
+
594
+ ## 首选
595
+ TODO
596
+
597
+ ## 被挡时
598
+ TODO
599
+
600
+ ## 别再来
601
+ | 弯路 | 为什么不通 |
602
+ | --- | --- |
603
+ | TODO | TODO |
604
+
605
+ ## 注意
606
+ - 先确认这是不是复发;孤例不要升成正式卡。
607
+
608
+ 证据:_inbox.md ${entry.time}
609
+ `;
610
+ writeFileSync(file, content, 'utf8');
611
+ created.push(file);
612
+ });
613
+
614
+ return { created, skipped, outDir };
615
+ }
616
+
617
+ export function relativeCardPath(fromDir, cardPath) {
618
+ return relative(resolve(fromDir), resolve(cardPath)).replaceAll('\\', '/');
619
+ }
package/lib/hint.mjs ADDED
@@ -0,0 +1,17 @@
1
+ import { relative } from 'node:path';
2
+
3
+ /** One-line hint for a matched card. Pure Node so other harnesses can reuse it. */
4
+ export function buildHint(hit, cwd) {
5
+ const target = hit.scope === 'global'
6
+ ? `global:${hit.file}`
7
+ : relative(cwd, hit.path).replaceAll('\\', '/');
8
+ const matched = Array.isArray(hit.matched) ? hit.matched : [];
9
+ const anchor = matched.find((match) => match.on === 'anchor')?.value
10
+ ?? matched[0]?.value
11
+ ?? '';
12
+ const suffix = anchor ? `(锚点:${anchor})` : '';
13
+ if (hit.type === 'spell' && hit.actionableCode) {
14
+ return `[procedures] 命中技能卡 ${target}${suffix},语言:${hit.language || 'unknown'}。先读卡,确认安全后再执行其中的代码片段,不要盲目运行。`;
15
+ }
16
+ return `[procedures] 命中经验卡 ${target}${suffix}。先读这张卡,再重试或换路,别直接重复刚才的调用。`;
17
+ }
@@ -0,0 +1,26 @@
1
+ /** Resident convention injected into sessions that opt in with a procedures/ directory. */
2
+ export const HOOK_TEXT = `【经验流程 · procedures】
3
+ 本工作区 procedures/ 存踩过的坑与解法,不常驻,按需读。
4
+
5
+ - 动手前,两步:
6
+ ① 冷启动:任务里出现 URL / 仓库链接 /「装不装、值不值得装」时,先按任务里的名词搜一次,命中就直接打开第一张卡;第一次失败后必须回头查一次卡库,再动手修。
7
+ ② 撞上现象(网页抓不到正文 / 改了不生效 / 报错原文):先搜卡再修,一次打开一张。
8
+ PowerShell:Select-String -Path procedures\\*.md,procedures\\cards\\*.md -Pattern "<任务词>"
9
+ grep:grep -ril "<任务词>" procedures/*.md procedures/cards/*.md
10
+ 用任务里的名词 / 报错原文搜,别搜「触发」这种字面词;别用 glob / 列目录挑卡。
11
+ - 踩坑当时:不是照卡走通、而是又试错了几轮 → 立刻往 procedures/_inbox.md 记一行(现象 + 一句话解法),别等收尾。
12
+ - 收尾:只看 _inbox.md,够格的照 _模板.md 整理成卡;不扫全库、不复制卡正文。`;
13
+
14
+ /** Global-only variant: the workspace has no procedures/ but globalDir is configured. */
15
+ export function globalHookText(globalDir) {
16
+ const root = String(globalDir ?? '').replaceAll('\\', '/').replace(/\/+$/, '');
17
+ return `【经验流程 · procedures(全局库)】
18
+ 本工作区没有 procedures/;已配置只读全局卡库:${root}
19
+
20
+ - 撞上现象(网页抓不到正文 / 改了不生效 / 报错原文):先搜全局卡库,再修。
21
+ PowerShell:Select-String -Path "${root}/*.md","${root}/cards/*.md" -Pattern "<任务词>"
22
+ grep:grep -ril "<任务词>" "${root}"/*.md "${root}"/cards/*.md
23
+ - 命中提示会写 global:<文件名>;按提示打开那张卡,不要重复刚才的调用。
24
+ - 踩坑当时:本工作区没有 procedures/,在回复末尾写一行「待记 inbox」;要持久化就在本工作区建 procedures/,插件会自动接管。
25
+ - 收尾:全局卡只读,不要在全局库写卡;本工作区有 _inbox.md 时只看它。`;
26
+ }