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/llm.mjs ADDED
@@ -0,0 +1,243 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+
4
+ import { parseCard, readInbox } from './cards.mjs';
5
+
6
+ export const DEFAULT_BASE_URL = 'https://api.deepseek.com';
7
+ export const DEFAULT_MODEL = 'deepseek-chat';
8
+ const DRAFT_LIMIT_BYTES = 2048;
9
+
10
+ export function resolveLlmConfig(options = {}, env = process.env) {
11
+ const apiKey = String(
12
+ options.apiKey
13
+ ?? env.DSH_PROCEDURES_API_KEY
14
+ ?? env.DEEPSEEK_API_KEY
15
+ ?? env.OPENAI_API_KEY
16
+ ?? '',
17
+ ).trim();
18
+ const baseUrl = String(
19
+ options.baseUrl
20
+ ?? env.DSH_PROCEDURES_BASE_URL
21
+ ?? env.DEEPSEEK_BASE_URL
22
+ ?? env.OPENAI_BASE_URL
23
+ ?? DEFAULT_BASE_URL,
24
+ ).trim().replace(/\/+$/, '');
25
+ const model = String(
26
+ options.model
27
+ ?? env.DSH_PROCEDURES_MODEL
28
+ ?? env.DEEPSEEK_MODEL
29
+ ?? DEFAULT_MODEL,
30
+ ).trim();
31
+ return { apiKey, baseUrl, model };
32
+ }
33
+
34
+ function isLocal(baseUrl) {
35
+ try {
36
+ const host = new URL(baseUrl).hostname;
37
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1';
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ export function redactConfig(config) {
44
+ return { baseUrl: config.baseUrl, model: config.model, hasKey: Boolean(config.apiKey) };
45
+ }
46
+
47
+ function uniqueEntries(entries) {
48
+ const seen = new Set();
49
+ const unique = [];
50
+ for (const entry of entries) {
51
+ const key = `${entry.tool}|${entry.message.slice(0, 100)}`;
52
+ if (seen.has(key)) continue;
53
+ seen.add(key);
54
+ unique.push(entry);
55
+ }
56
+ return unique;
57
+ }
58
+
59
+ export function buildSynthesisPrompt({ entries = [], context = '' } = {}) {
60
+ const records = entries
61
+ .map((entry) => `- [${entry.tool}] ${entry.message}`)
62
+ .join('\n');
63
+ return `你是经验卡编辑。下面是一条 agent 踩坑记录(可能含报错原文)。请把它整理成一张可复用的经验卡草稿。
64
+
65
+ 只输出 Markdown 正文,不要解释,不要在外层加代码围栏。
66
+
67
+ 硬性要求:
68
+ 1. 文件必须以 YAML front matter 开头(--- 开头,--- 结尾),字段齐全:
69
+ id, title, type, triggers, anchors, requires, excludes, valid_until, environment, created, last_hit, hits。
70
+ 2. type 只能是 trap 或 spell。trap = 陷阱/反面清单;spell = 可复用的修复动作。
71
+ 如果是 spell,正文必须有「## 可执行」和一个带语言标记的代码块。
72
+ 3. 正文必须包含这些段落:## 触发 / ## 首选 / ## 被挡时 / ## 别再来 / ## 注意 / 证据:。
73
+ 4. anchors 写 3–8 个「任务或报错里会原样出现」的英文/符号(命令名、域名、扩展名、报错原文);中文描述放 triggers,不要放 anchors。
74
+ 5. 不要编造记录里没有的命令、路径、报错、版本号;不确定就写 TODO。
75
+ 6. 全文 ≤ 2 KB。删叙述,保留命令、报错原文、判据。
76
+ 7. requires / excludes 可留空数组;用它们表达“必须同时出现”/“出现就跳过”的词。
77
+
78
+ 踩坑记录:
79
+ ${records}
80
+
81
+ 可选的会话上下文(可能为空):
82
+ ${String(context).slice(0, 8000) || '(无)'}
83
+ `;
84
+ }
85
+
86
+ export function stripFences(text) {
87
+ const source = String(text ?? '').trim();
88
+ const match = /^```[a-zA-Z0-9_-]*\s*\n([\s\S]*?)\n```$/.exec(source);
89
+ return (match ? match[1] : source).trim();
90
+ }
91
+
92
+ export function validateDraft(markdown) {
93
+ const card = parseCard(String(markdown ?? ''), 'draft.md');
94
+ if (!card.hasFrontMatter) return { ok: false, reason: 'missing YAML front matter', card };
95
+ if (!card.id) return { ok: false, reason: 'missing id', card };
96
+ if (!card.title) return { ok: false, reason: 'missing title', card };
97
+ if (!['trap', 'spell'].includes(card.type)) {
98
+ return { ok: false, reason: `unknown type: ${card.type}`, card };
99
+ }
100
+ if (card.anchors.length === 0) return { ok: false, reason: 'missing anchors', card };
101
+ if (card.size > DRAFT_LIMIT_BYTES) {
102
+ return { ok: false, reason: `oversize: ${card.size} B`, card };
103
+ }
104
+ for (const section of ['首选', '别再来', '注意']) {
105
+ if (!card.body.includes(section)) {
106
+ return { ok: false, reason: `missing section: ${section}`, card };
107
+ }
108
+ }
109
+ if (card.type === 'spell') {
110
+ if (!card.actionableCode) return { ok: false, reason: 'spell without code', card };
111
+ if (!card.body.includes('验证')) return { ok: false, reason: 'spell without 验证', card };
112
+ }
113
+ return { ok: true, card };
114
+ }
115
+
116
+ export async function callChatCompletion({
117
+ config,
118
+ prompt,
119
+ fetchImpl = globalThis.fetch,
120
+ signal,
121
+ }) {
122
+ if (typeof fetchImpl !== 'function') throw new Error('fetch is unavailable in this runtime');
123
+ const headers = { 'content-type': 'application/json' };
124
+ if (config.apiKey) headers.authorization = `Bearer ${config.apiKey}`;
125
+ const response = await fetchImpl(`${config.baseUrl}/chat/completions`, {
126
+ method: 'POST',
127
+ headers,
128
+ signal,
129
+ body: JSON.stringify({
130
+ model: config.model,
131
+ temperature: 0.2,
132
+ max_tokens: 2000,
133
+ messages: [
134
+ { role: 'system', content: '你是严谨的经验卡编辑,只输出 Markdown,不输出解释。' },
135
+ { role: 'user', content: prompt },
136
+ ],
137
+ }),
138
+ });
139
+ if (!response || response.ok !== true) {
140
+ const status = response?.status ?? 'unknown';
141
+ let detail = '';
142
+ try {
143
+ detail = typeof response?.text === 'function' ? await response.text() : '';
144
+ } catch {
145
+ detail = '';
146
+ }
147
+ throw new Error(`LLM HTTP ${status}: ${String(detail).slice(0, 300)}`);
148
+ }
149
+ const data = await response.json();
150
+ const text = data?.choices?.[0]?.message?.content;
151
+ if (typeof text !== 'string' || !text.trim()) {
152
+ throw new Error('LLM returned empty content');
153
+ }
154
+ return stripFences(text);
155
+ }
156
+
157
+ function stamp(date = new Date()) {
158
+ const pad = (value) => String(value).padStart(2, '0');
159
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
160
+ }
161
+
162
+ function safeSlug(value, fallback = 'card') {
163
+ const slug = String(value ?? '')
164
+ .toLowerCase()
165
+ .replace(/[^\p{L}\p{N}-]+/gu, '-')
166
+ .replace(/^-+|-+$/g, '')
167
+ .slice(0, 40);
168
+ return slug || fallback;
169
+ }
170
+
171
+ /**
172
+ * Draft cards with an OpenAI-compatible chat endpoint. Drafts only: this
173
+ * function never writes to cards/ and never promotes a card.
174
+ */
175
+ export async function synthesizeWithLlm(options = {}) {
176
+ const dir = resolve(options.dir ?? 'procedures');
177
+ const outDir = resolve(options.outDir ?? join(dir, '_drafts'));
178
+ const entries = uniqueEntries(readInbox(dir));
179
+ if (entries.length === 0) {
180
+ return { created: [], rejected: [], entries: 0, outDir, dryRun: false };
181
+ }
182
+
183
+ const config = resolveLlmConfig(options, options.env ?? process.env);
184
+ const max = Math.max(1, Math.min(Number.parseInt(String(options.max ?? '5'), 10) || 5, 20));
185
+ const selected = entries.slice(0, max);
186
+ const context = String(options.context ?? '').slice(0, 8000);
187
+ const firstPrompt = buildSynthesisPrompt({ entries: [selected[0]], context });
188
+
189
+ if (options.dryRun) {
190
+ return {
191
+ created: [],
192
+ rejected: [],
193
+ entries: selected.length,
194
+ outDir,
195
+ dryRun: true,
196
+ prompt: firstPrompt,
197
+ config: redactConfig(config),
198
+ };
199
+ }
200
+ if (!config.apiKey && !isLocal(config.baseUrl)) {
201
+ throw new Error(
202
+ 'missing API key: set DEEPSEEK_API_KEY or DSH_PROCEDURES_API_KEY (or use --dry-run / a local base URL)',
203
+ );
204
+ }
205
+
206
+ mkdirSync(outDir, { recursive: true });
207
+ const created = [];
208
+ const rejected = [];
209
+ const base = stamp();
210
+
211
+ for (let index = 0; index < selected.length; index += 1) {
212
+ const entry = selected[index];
213
+ const prompt = buildSynthesisPrompt({ entries: [entry], context });
214
+ let output;
215
+ try {
216
+ output = options.complete
217
+ ? await options.complete(prompt, entry)
218
+ : await callChatCompletion({
219
+ config,
220
+ prompt,
221
+ fetchImpl: options.fetchImpl,
222
+ signal: options.signal,
223
+ });
224
+ } catch (error) {
225
+ rejected.push({ entry, reason: String(error) });
226
+ continue;
227
+ }
228
+
229
+ const check = validateDraft(output);
230
+ const name = `draft-${base}-${String(index + 1).padStart(2, '0')}-${safeSlug(check.card?.id ?? entry.tool)}`;
231
+ if (check.ok) {
232
+ const file = join(outDir, `${name}.md`);
233
+ writeFileSync(file, `${output.trim()}\n`, 'utf8');
234
+ created.push(file);
235
+ } else {
236
+ const file = join(outDir, `${name}.rejected.md`);
237
+ writeFileSync(file, `<!-- rejected: ${check.reason} -->\n\n${output.trim()}\n`, 'utf8');
238
+ rejected.push({ entry, reason: check.reason, file });
239
+ }
240
+ }
241
+
242
+ return { created, rejected, entries: selected.length, outDir, dryRun: false };
243
+ }
package/lib/stats.mjs ADDED
@@ -0,0 +1,103 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+
4
+ export const STATS_FILE = '_stats.json';
5
+
6
+ export function statsPath(dir) {
7
+ return join(resolve(dir), STATS_FILE);
8
+ }
9
+
10
+ export function emptyStats() {
11
+ return { version: 1, cards: {}, updated_at: null };
12
+ }
13
+
14
+ export function readStatsAt(file) {
15
+ if (!file || !existsSync(file)) return emptyStats();
16
+ try {
17
+ const data = JSON.parse(readFileSync(file, 'utf8'));
18
+ const cards = data && typeof data.cards === 'object' && data.cards !== null ? data.cards : {};
19
+ return {
20
+ version: 1,
21
+ cards,
22
+ updated_at: typeof data?.updated_at === 'string' ? data.updated_at : null,
23
+ };
24
+ } catch {
25
+ return emptyStats();
26
+ }
27
+ }
28
+
29
+ export function readStats(dir) {
30
+ return readStatsAt(statsPath(dir));
31
+ }
32
+
33
+ /** Increment one card's hit count in an explicit stats file. Card YAML is never touched. */
34
+ export function recordHitAt(file, card, options = {}) {
35
+ const id = String(card?.id ?? '').trim();
36
+ if (!file || !id) return null;
37
+
38
+ const stats = readStatsAt(file);
39
+ const previous = stats.cards[id] ?? { hits: 0, last_hit: null, last_session: null };
40
+ const now = options.now instanceof Date ? options.now : new Date();
41
+ const entry = {
42
+ ...previous,
43
+ hits: (Number(previous.hits) || 0) + 1,
44
+ last_hit: now.toISOString(),
45
+ last_session: options.sessionId ?? previous.last_session ?? null,
46
+ };
47
+ stats.cards[id] = entry;
48
+ stats.updated_at = now.toISOString();
49
+ mkdirSync(dirname(file), { recursive: true });
50
+ writeFileSync(file, `${JSON.stringify(stats, null, 2)}\n`, 'utf8');
51
+ return entry;
52
+ }
53
+
54
+ /** Record what happened after a hint: the same card repeated, or the window closed clean. */
55
+ export function recordOutcomeAt(file, card, outcome, options = {}) {
56
+ const id = String(card?.id ?? '').trim();
57
+ if (!file || !id) return null;
58
+ if (outcome !== 'repeated' && outcome !== 'no_repeat') return null;
59
+
60
+ const stats = readStatsAt(file);
61
+ const previous = stats.cards[id] ?? {
62
+ hits: 0,
63
+ last_hit: null,
64
+ last_session: null,
65
+ repeated: 0,
66
+ no_repeat: 0,
67
+ };
68
+ const now = options.now instanceof Date ? options.now : new Date();
69
+ const entry = {
70
+ ...previous,
71
+ repeated: (Number(previous.repeated) || 0) + (outcome === 'repeated' ? 1 : 0),
72
+ no_repeat: (Number(previous.no_repeat) || 0) + (outcome === 'no_repeat' ? 1 : 0),
73
+ last_outcome: outcome,
74
+ last_outcome_at: now.toISOString(),
75
+ };
76
+ stats.cards[id] = entry;
77
+ stats.updated_at = now.toISOString();
78
+ mkdirSync(dirname(file), { recursive: true });
79
+ writeFileSync(file, `${JSON.stringify(stats, null, 2)}\n`, 'utf8');
80
+ return entry;
81
+ }
82
+
83
+ /** Workspace sidecar under <dir>/_stats.json. */
84
+ export function recordHit(dir, card, options = {}) {
85
+ const root = resolve(dir);
86
+ if (!existsSync(root)) return null;
87
+ return recordHitAt(statsPath(root), card, options);
88
+ }
89
+
90
+ export function hitsOf(stats, card) {
91
+ const stored = Number(stats?.cards?.[card?.id]?.hits);
92
+ if (Number.isFinite(stored) && stored > 0) return stored;
93
+ return Number(card?.hits) || 0;
94
+ }
95
+
96
+ export function outcomesOf(stats, card) {
97
+ const entry = stats?.cards?.[card?.id] ?? {};
98
+ return {
99
+ repeated: Number(entry.repeated) || 0,
100
+ noRepeat: Number(entry.no_repeat) || 0,
101
+ lastOutcome: typeof entry.last_outcome === 'string' ? entry.last_outcome : null,
102
+ };
103
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Procedures",
4
+ "description": "File-based experience cards: a conditional hook, failure hints, and inbox capture."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "经验卡库",
4
+ "description": "文件化经验卡:按工作区注入钩子,失败时提示命中卡,并自动记录 inbox。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "dsh-procedures",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "File-based experience cards for DSH and other agents: conditional hook, failure hints, stats, rarity, global library, and a portable kit.",
6
+ "license": "MIT",
7
+ "author": "MiHjy12138",
8
+ "homepage": "https://github.com/fubai-fenzhi/dsh-procedures#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/fubai-fenzhi/dsh-procedures.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/fubai-fenzhi/dsh-procedures/issues"
15
+ },
16
+ "keywords": [
17
+ "dsh",
18
+ "deepseek-harness",
19
+ "agents",
20
+ "procedures",
21
+ "memory",
22
+ "hooks",
23
+ "experience-cards"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18",
27
+ "dsh": ">=0.2.1-rc.3"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "exports": {
33
+ ".": "./index.js",
34
+ "./locale/*.json": "./locale/*.json",
35
+ "./icon": "./icon.svg"
36
+ },
37
+ "files": [
38
+ "index.js",
39
+ "lib/*.mjs",
40
+ "bin/*.mjs",
41
+ "bench/*.mjs",
42
+ "portable",
43
+ "cordis.patch.yml",
44
+ "locale/*.json",
45
+ "icon.svg",
46
+ "README.md",
47
+ "README.en.md",
48
+ "CHANGELOG.md",
49
+ "PRO.md",
50
+ "LICENSE"
51
+ ],
52
+ "dsh": {
53
+ "bundle": {
54
+ "patch": "./cordis.patch.yml"
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,17 @@
1
+ # 经验流程(procedures)— 通用钩子片段
2
+
3
+ 【经验流程 · procedures】
4
+ 本工作区 procedures/ 存踩过的坑与解法,不常驻,按需读。
5
+
6
+ - 动手前,两步:
7
+ ① 冷启动:任务里出现 URL / 仓库链接 /「装不装、值不值得装」时,先按任务里的名词搜一次,命中就直接打开第一张卡;第一次失败后必须回头查一次卡库,再动手修。
8
+ ② 撞上现象(网页抓不到正文 / 改了不生效 / 报错原文):先搜卡再修,一次打开一张。
9
+ grep:grep -ril "<任务词>" procedures/*.md procedures/cards/*.md
10
+ Windows:Select-String -Path procedures\*.md,procedures\cards\*.md -Pattern "<任务词>"
11
+ 装了本工具:node "{{KIT_DIR}}/bin/procedures.mjs" search "<任务词>" --dir procedures
12
+ 用任务里的名词 / 报错原文搜,别搜「触发」这种字面词;别用 glob / 列目录挑卡。
13
+ - 踩坑当时:不是照卡走通、而是又试错了几轮 → 立刻往 procedures/_inbox.md 记一行(现象 + 一句话解法),别等收尾。
14
+ - 收尾:只看 _inbox.md,够格的照 _模板.md 整理成卡;不扫全库、不复制卡正文。
15
+ - 如果 harness 支持 post-tool hook:把 `{tool, error}` 传给
16
+ `node "{{KIT_DIR}}/bin/hint.mjs" --stdin --dir procedures`,
17
+ 把 stdout 追加到下一轮上下文;stdout 为空表示没命中,不要为此报错。
@@ -0,0 +1,121 @@
1
+ # procedures 通用本地版(给非 DSH 的 agent)
2
+
3
+ 同一套**经验卡 + 索引 + inbox + 检索/审计 CLI**,不依赖 DSH。任何能跑 shell、能读指令文件的 agent 都能用。
4
+
5
+ ## 和 DSH 插件的区别
6
+
7
+ | 能力 | DSH 插件 | 通用本地版 |
8
+ |---|---|---|
9
+ | 常驻约定 | 条件注入 system prompt | 写进 `AGENTS.md` / `CLAUDE.md` 等指令文件 |
10
+ | 失败时自动提示 | `tools/result` 自动匹配 + 注入 | 靠 agent 按约定自己搜;或 harness hook 调 `bin/hint.mjs` |
11
+ | 自动 inbox | 未命中自动写 | 手动 `inbox add`;或 `hint.mjs --inbox` |
12
+ | 命中/复发统计 | 有 | CLI 有 stats 读取,但需要 harness 调 `hint.mjs` 才能自动累积 |
13
+ | 卡片/检索/审计/抽卡 | 有 | **完全一样** |
14
+
15
+ 一句话:**卡库和引擎是通用的;自动拦截是 DSH 专属的,其他 harness 要么靠约定,要么接 `hint.mjs`。**
16
+
17
+ ## 要求
18
+
19
+ - Node.js ≥ 18
20
+ - 一个能执行命令的 shell
21
+ - 一个该 agent 会读的指令文件(`AGENTS.md` / `CLAUDE.md` / `GEMINI.md` / 等价物)
22
+
23
+ ## 快速开始
24
+
25
+ 把整个 `dsh-procedures/` 目录复制到目标机器(或者解压分享的 zip),然后:
26
+
27
+ ```powershell
28
+ node portable/setup.mjs --workspace E:\YourProject --write
29
+ ```
30
+
31
+ 它会:
32
+
33
+ 1. 创建 `E:\YourProject\procedures\`,放入 `INDEX.md`、`_模板.md`、`_模板-spell.md`、`_inbox.md`;
34
+ 2. 把 `AGENTS-snippet.md` 追加到 `E:\YourProject\AGENTS.md`(已有同款钩子会跳过);
35
+ 3. 打印下一步命令。
36
+
37
+ `--agent-file CLAUDE.md` / `GEMINI.md` 可换目标文件;`--force` 覆盖已存在的模板;不加 `--write` 只打印片段,不改任何文件。
38
+
39
+ ## 手动安装
40
+
41
+ 1. 在目标工作区建 `procedures/`,复制 `portable/templates/` 里的四份模板。
42
+ 2. 把 `portable/AGENTS-snippet.md` 粘进该 agent 的指令文件,把 `{{KIT_DIR}}` 换成 `dsh-procedures` 的绝对路径。
43
+ 3. 写第一张卡(照 `_模板.md`),然后:
44
+
45
+ ```powershell
46
+ node "<KIT_DIR>\bin\procedures.mjs" audit --dir procedures
47
+ ```
48
+
49
+ ## CLI
50
+
51
+ ```powershell
52
+ # 检索
53
+ node "<KIT_DIR>\bin\procedures.mjs" search "app.asar ENOENT" --dir procedures
54
+
55
+ # 审计(结构/体积/过期/重复 id/spell 完整性)
56
+ node "<KIT_DIR>\bin\procedures.mjs" audit --dir procedures
57
+
58
+ # 列表 + 命中/复发/未复发
59
+ node "<KIT_DIR>\bin\procedures.mjs" list --dir procedures
60
+
61
+ # 手动记 inbox
62
+ node "<KIT_DIR>\bin\procedures.mjs" inbox add "只拿到 SPA 外壳" --tool web_fetch --dir procedures
63
+
64
+ # 从 inbox 生成 TODO 草稿
65
+ node "<KIT_DIR>\bin\procedures.mjs" synthesize --dir procedures
66
+
67
+ # 可选:调 DeepSeek / OpenAI 兼容接口写草稿(只写 _drafts/,不转正)
68
+ $env:DEEPSEEK_API_KEY = "sk-..."
69
+ node "<KIT_DIR>\bin\procedures.mjs" synthesize --llm --max 3 --dir procedures
70
+ ```
71
+
72
+ ## 接 harness hook(可选)
73
+
74
+ `bin/hint.mjs` 是给任何 harness 用的通用适配器:
75
+
76
+ ```powershell
77
+ # 参数方式
78
+ node "<KIT_DIR>\bin\hint.mjs" --tool pwsh --error "Cannot find path ..." --dir procedures
79
+
80
+ # stdin JSON 方式(推荐给 hook)
81
+ '{"tool":"pwsh","error":"Cannot find path ..."}' | node "<KIT_DIR>\bin\hint.mjs" --stdin --dir procedures
82
+ ```
83
+
84
+ - 命中时 stdout 输出一行 `[procedures] ...`;没命中时 stdout 为空、退出码 0。
85
+ - `--inbox`:没命中时把这一行写进 `procedures/_inbox.md`。
86
+ - `--json`:输出 `{hit, hint}`,方便 hook 程序解析。
87
+ - 接到 harness 的 post-tool hook:把 `{tool,error}` 传进去,把 stdout 追加到下一轮上下文;不要因为 stdout 为空报错。
88
+
89
+ 典型接法:
90
+
91
+ ```text
92
+ PostToolUse(tool, error):
93
+ out = shell("node <KIT_DIR>/bin/hint.mjs --stdin --dir procedures", {tool, error})
94
+ if out: append_to_context(out)
95
+ ```
96
+
97
+ 具体 hook 配置名(Claude Code / Codex / OpenClaw / Cursor)各不相同,按各自文档把上面这条命令接进去即可。
98
+
99
+ ## 给其他 DSH profile
100
+
101
+ 如果对方也是 DSH,只是换了 profile:直接用完整插件,比通用版好——把 `dsh-procedures/` 复制过去,用 `plugin_manager` 的 `install_bundle` 安装,或把 profile 的 `node_modules/dsh-procedures` 指向这个目录。完整插件才有自动提示、自动 inbox、stats 和复发统计。
102
+
103
+ ## 分享
104
+
105
+ ```powershell
106
+ Compress-Archive -Path dsh-procedures -DestinationPath dsh-procedures-portable.zip -Force
107
+ ```
108
+
109
+ 对方解压后跑 `node portable/setup.mjs --workspace <项目> --write`。只需要 Node,不需要 DSH。
110
+
111
+ ## 限制
112
+
113
+ - 通用版没有自动注入;agent 不按指令搜卡,就不会触发。
114
+ - `hint.mjs` 只负责“匹配 + 输出一行”,不维护 session 级 pending;复发/未复发统计要 harness 自己按事件调用并记录。
115
+ - 指令文件是常驻的,成本和 DSH 的 1 KB section 相当;这是“让 agent 知道有卡库”的必要开销。
116
+ - 卡片匹配仍是字面锚点/关键词,不做语义检索。
117
+ - spell 卡不会自动执行。
118
+
119
+ ## 授权
120
+
121
+ MIT,见上一级 `LICENSE`。
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Scaffold a portable procedures/ directory and optionally append the hook to
4
+ * an agent instruction file (AGENTS.md / CLAUDE.md / GEMINI.md / ...).
5
+ */
6
+ import {
7
+ appendFileSync,
8
+ cpSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ readFileSync,
12
+ } from 'node:fs';
13
+ import { dirname, join, resolve } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const USAGE = `procedures-setup — portable procedures kit
17
+
18
+ Usage:
19
+ node portable/setup.mjs [--workspace DIR] [--write] [--agent-file AGENTS.md] [--force]
20
+
21
+ --workspace target project (default: current directory)
22
+ --write append the hook to the agent instruction file if missing
23
+ --agent-file instruction file name (default: AGENTS.md; e.g. CLAUDE.md)
24
+ --force overwrite existing template files
25
+
26
+ Without --write the rendered hook snippet is printed for manual pasting.`;
27
+
28
+ function parseArgs(argv) {
29
+ const flags = {};
30
+ for (let index = 0; index < argv.length; index += 1) {
31
+ const arg = argv[index];
32
+ if (!arg.startsWith('--')) continue;
33
+ const body = arg.slice(2);
34
+ const equals = body.indexOf('=');
35
+ if (equals >= 0) {
36
+ flags[body.slice(0, equals)] = body.slice(equals + 1);
37
+ continue;
38
+ }
39
+ if (index + 1 < argv.length && !argv[index + 1].startsWith('--')) {
40
+ flags[body] = argv[index + 1];
41
+ index += 1;
42
+ continue;
43
+ }
44
+ flags[body] = true;
45
+ }
46
+ return flags;
47
+ }
48
+
49
+ const here = dirname(fileURLToPath(import.meta.url));
50
+ const kitDir = resolve(here, '..').replaceAll('\\', '/');
51
+ const flags = parseArgs(process.argv.slice(2));
52
+
53
+ if (flags.help) {
54
+ process.stdout.write(`${USAGE}\n`);
55
+ process.exit(0);
56
+ }
57
+
58
+ const workspace = resolve(process.cwd(), typeof flags.workspace === 'string' ? flags.workspace : '.');
59
+ const procedures = join(workspace, 'procedures');
60
+ const templates = ['INDEX.md', '_模板.md', '_模板-spell.md', '_inbox.md'];
61
+ const copied = [];
62
+ const skipped = [];
63
+
64
+ mkdirSync(join(procedures, 'cards'), { recursive: true });
65
+ for (const name of templates) {
66
+ const source = join(here, 'templates', name);
67
+ const target = join(procedures, name);
68
+ if (!existsSync(source)) continue;
69
+ if (existsSync(target) && flags.force !== true) {
70
+ skipped.push(name);
71
+ continue;
72
+ }
73
+ cpSync(source, target);
74
+ copied.push(name);
75
+ }
76
+
77
+ const snippet = readFileSync(join(here, 'AGENTS-snippet.md'), 'utf8')
78
+ .replaceAll('{{KIT_DIR}}', kitDir);
79
+
80
+ let agentFile = null;
81
+ let agentState = 'not-written';
82
+ if (flags.write) {
83
+ const name = typeof flags['agent-file'] === 'string' ? flags['agent-file'] : 'AGENTS.md';
84
+ agentFile = resolve(workspace, name);
85
+ mkdirSync(dirname(agentFile), { recursive: true });
86
+ const current = existsSync(agentFile) ? readFileSync(agentFile, 'utf8') : '';
87
+ if (current.includes('经验流程 · procedures')) {
88
+ agentState = 'already-present';
89
+ } else {
90
+ const prefix = current.length === 0
91
+ ? ''
92
+ : current.endsWith('\n\n')
93
+ ? ''
94
+ : current.endsWith('\n')
95
+ ? '\n'
96
+ : '\n\n';
97
+ appendFileSync(agentFile, `${prefix}${snippet}\n`, 'utf8');
98
+ agentState = 'appended';
99
+ }
100
+ }
101
+
102
+ process.stdout.write(`workspace: ${workspace}\n`);
103
+ process.stdout.write(`procedures: ${procedures}\n`);
104
+ process.stdout.write(`templates copied: ${copied.join(', ') || '(none)'}\n`);
105
+ if (skipped.length > 0) {
106
+ process.stdout.write(`templates skipped (already exist): ${skipped.join(', ')}\n`);
107
+ }
108
+ if (agentFile) {
109
+ process.stdout.write(`agent file: ${agentFile} (${agentState})\n`);
110
+ } else {
111
+ process.stdout.write('\n--- paste this into AGENTS.md / CLAUDE.md / GEMINI.md ---\n');
112
+ process.stdout.write(`${snippet}\n`);
113
+ }
114
+ process.stdout.write('\nnext: create a card from _模板.md, then run\n');
115
+ process.stdout.write(` node "${kitDir}/bin/procedures.mjs" audit --dir "${procedures}"\n`);
@@ -0,0 +1,9 @@
1
+ # 经验卡索引(只放消歧,不逐卡列)
2
+
3
+ | 容易混的现象 | 先读哪张 |
4
+ | --- | --- |
5
+ | 路径不存在 / ENOENT / 读不到文件 | 先分清是权限、沙箱、还是真不存在;本机特有路径单独成卡 |
6
+ | 网页只拿到标题 / 200 但没有正文 | 先怀疑 SPA 或登录墙;换公开链接或让用户提供正文 |
7
+ | 改了配置不生效 | 先确认进程是否重启、缓存是否命中 |
8
+
9
+ 卡名本身就是索引,新卡不用回来改这张表。