kenaz 0.3.2 → 0.3.5

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 (71) hide show
  1. package/core/.claude/commands/Ansuz.md +36 -35
  2. package/core/.claude/hooks/__tests__/task-2395-project-registration.test.js +84 -0
  3. package/core/.claude/hooks/_ansuz-conversation.js +1 -0
  4. package/core/.claude/hooks/_ansuz-conversation.test.js +6 -0
  5. package/core/.claude/hooks/_run-user-prompt.js +0 -4
  6. package/core/.claude/hooks/_run-user-prompt.test.js +2 -3
  7. package/core/.claude/hooks/handoff-staleness.js +2 -2
  8. package/core/.claude/hooks/turn-context.js +50 -2
  9. package/core/.claude/settings.json +0 -37
  10. package/core/.collaboration/core/task-api.js +4 -12
  11. package/core/.formation/README.md +21 -146
  12. package/core/.formation/bifrost/codex-doctor.js +37 -2
  13. package/core/.formation/bifrost/codex-doctor.test.js +18 -0
  14. package/core/.formation/bifrost/launch.js +1 -1
  15. package/core/.formation/bifrost/openai/codex-hook-shim.js +6 -0
  16. package/core/.formation/bifrost/openai/codex-hook-shim.test.js +11 -1
  17. package/core/.formation/bifrost/setup-codex.js +3 -0
  18. package/core/.formation/spec/task_operations.parity.test.js +0 -1
  19. package/core/.formation/tools/dashboard-models-chain.test.js +0 -6
  20. package/core/.formation/tools/dispatch-detail/cross-project-worktree.md +1 -9
  21. package/core/.formation/tools/dispatch-detail/worktree-subagent-mode.md +2 -2
  22. package/core/.formation/tools/dispatch.js +28 -549
  23. package/core/.formation/tools/mcp-allowlist.test.js +0 -1
  24. package/core/.formation/tools/post-complete/task2345.test.js +0 -5
  25. package/core/.formation/tools/pre-dispatch-snapshot.test.js +0 -100
  26. package/core/.formation/tools/prompt.js +66 -1607
  27. package/core/.formation/tools/prompt.test.js +43 -582
  28. package/core/.kenaz/claude-hooks-manifest.json +16 -16
  29. package/core/.specialist/Ansuz/RULES.md +6 -10
  30. package/core/.specialist/tools/__tests__/freya-cli-contract.test.js +0 -1
  31. package/core/.specialist/tools/__tests__/task-2218-boot-session-id.test.js +17 -1
  32. package/core/.specialist/tools/__tests__/task-2222-session-identity-interleave.test.js +17 -1
  33. package/core/.specialist/tools/__tests__/task-2254-handoff-archive-contract.test.js +6 -5
  34. package/core/.specialist/tools/ansuz-boot-fast.js +44 -100
  35. package/core/.specialist/tools/ansuz-boot-fast.test.js +45 -1
  36. package/core/KENAZ_CORE_VERSION +1 -1
  37. package/core/dev/plans/ANSUZ_SLIM_PLAN.md +68 -0
  38. package/core/plugins/kenaz/commands/Amelia.md +1 -1
  39. package/core/plugins/kenaz/commands/Ansuz.md +36 -35
  40. package/core/plugins/kenaz/hooks/hooks.json +1 -5
  41. package/core/plugins/kenaz/hooks/kenaz-hook.js +0 -4
  42. package/core/plugins/kenaz/scripts/kenaz-mode.js +11 -1
  43. package/core/plugins/kenaz/scripts/kenaz.test.js +1 -1
  44. package/core/plugins/kenaz/scripts/sync.js +6 -2
  45. package/core/plugins/kenaz/scripts/ygg.js +13 -1
  46. package/core/plugins/kenaz/skills/product_manager/SKILL.md +12 -12
  47. package/lib/cli.js +47 -6
  48. package/lib/cli.test.js +24 -0
  49. package/lib/dashboard.js +10 -0
  50. package/package.json +11 -7
  51. package/vendor/install-kenaz-cli.js +18 -7
  52. package/core/.formation/tools/broadcast.js +0 -103
  53. package/core/.formation/tools/dispatch-dryrun.test.js +0 -54
  54. package/core/.formation/tools/dispatch-notifier.js +0 -84
  55. package/core/.formation/tools/formations.js +0 -1203
  56. package/core/.formation/tools/headless-branch-recovery.test.js +0 -64
  57. package/core/.formation/tools/headless-dryrun.test.js +0 -79
  58. package/core/.formation/tools/headless-v2.js +0 -659
  59. package/core/.formation/tools/headless.js +0 -1071
  60. package/core/.formation/tools/legacy-scheduler.js +0 -1994
  61. package/core/.formation/tools/logger.js +0 -273
  62. package/core/.formation/tools/memory-loader.js +0 -422
  63. package/core/.formation/tools/process-state.js +0 -33
  64. package/core/.formation/tools/remote-conflict.js +0 -98
  65. package/core/.formation/tools/runner.js +0 -1332
  66. package/core/.formation/tools/task-utils.js +0 -344
  67. package/core/.formation/tools/task2028-headless-worktree.test.js +0 -112
  68. package/core/.formation/tools/tests/headless-mcp-args-plumbing.test.js +0 -123
  69. package/core/.formation/tools/worktree-leak.test.js +0 -162
  70. package/core/.specialist/tools/__tests__/task-1863-boot-lease-reuse.test.js +0 -99
  71. package/core/.specialist/tools/__tests__/task-1977-banner-cap.test.js +0 -129
@@ -1,273 +0,0 @@
1
- /**
2
- * Formation Logger
3
- * Claude subagent 輸出的 stream-json 格式化
4
- *
5
- * 支援的 entry types:
6
- * - system: init, hook 事件
7
- * - assistant: agent 的文字輸出和工具呼叫
8
- * - user: tool_use_result、teammate 訊息
9
- * - result: session 結束摘要
10
- */
11
-
12
- const fs = require('fs');
13
- const path = require('path');
14
- const { LOG_DIR, getLogDir } = require('./utils');
15
-
16
- /**
17
- * Local wall-clock HH:MM:SS for per-line log prefixes.
18
- *
19
- * LOCAL (not UTC) on purpose — TASK_1845: file mtime displays in local time,
20
- * so the last log line's timestamp must be directly comparable with the file's
21
- * mtime without timezone arithmetic. The previous UTC prefix
22
- * (`toISOString().slice(11,19)`) was misread as "agent stalled for 8 hours"
23
- * in a UTC+8 environment when the file had been written 13 seconds earlier.
24
- *
25
- * The `[HH:MM:SS]` shape is unchanged (downstream parsers depend on it). Cross-timezone readers can
26
- * anchor via the header, which carries both the ISO-8601 `Started:` line and
27
- * an explicit `Timezone: UTC±HH:MM` line.
28
- */
29
- function localHHMMSS() {
30
- const d = new Date();
31
- const p = (n) => String(n).padStart(2, '0');
32
- return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
33
- }
34
-
35
- /** UTC offset of this machine as `UTC±HH:MM` (e.g. `UTC+08:00`). */
36
- function localUtcOffset() {
37
- const offMin = -new Date().getTimezoneOffset();
38
- const sign = offMin >= 0 ? '+' : '-';
39
- const abs = Math.abs(offMin);
40
- const p = (n) => String(n).padStart(2, '0');
41
- return `UTC${sign}${p(Math.floor(abs / 60))}:${p(abs % 60)}`;
42
- }
43
-
44
- /**
45
- * 建立 log writer
46
- * @param {object} opts
47
- * @param {string} opts.formation
48
- * @param {string} opts.skill
49
- * @param {string} opts.sessionId
50
- * @param {string} [opts.outputPath] - 自訂輸出路徑
51
- * @param {string} [opts.memberId] - Squad 成員 ID(可選)
52
- * @param {string} [opts.projectPath] - 專案路徑(多專案支援)
53
- * @returns {{ stream: WriteStream, path: string, writeHeader: Function, writeFooter: Function }}
54
- */
55
- function createLogWriter(opts) {
56
- const { formation, skill, sessionId, outputPath, memberId, projectPath } = opts;
57
-
58
- // logs 按 formation 分目錄:logs/unit/, logs/squad/, ...
59
- // 多專案:根據 projectPath 決定 log 根目錄
60
- const logRoot = projectPath ? getLogDir(projectPath) : LOG_DIR;
61
- const formationLogDir = path.join(logRoot, formation || 'misc');
62
- if (!fs.existsSync(formationLogDir)) {
63
- fs.mkdirSync(formationLogDir, { recursive: true });
64
- }
65
-
66
- const suffix = memberId ? `_${memberId}` : '';
67
- const logPath = outputPath || path.join(formationLogDir, `${skill}${suffix}_${sessionId}.log`);
68
- const stream = fs.createWriteStream(logPath, { flags: 'w' });
69
-
70
- return {
71
- stream,
72
- path: logPath,
73
-
74
- writeHeader() {
75
- stream.write(`Formation: ${formation} | Skill: ${skill}${memberId ? ` | Member: ${memberId}` : ''}\n`);
76
- stream.write(`Session: ${sessionId}\n`);
77
- stream.write(`Started: ${new Date().toISOString()}\n`);
78
- stream.write(`Timezone: ${localUtcOffset()} (per-line [HH:MM:SS] timestamps are local time, directly comparable to file mtime)\n`);
79
- stream.write(`${'='.repeat(60)}\n\n`);
80
- },
81
-
82
- writeFooter(exitCode) {
83
- stream.write(`\n${'='.repeat(60)}\n`);
84
- stream.write(`Finished: ${new Date().toISOString()}\n`);
85
- stream.write(`Exit Code: ${exitCode}\n`);
86
- stream.end();
87
- }
88
- };
89
- }
90
-
91
- /**
92
- * 格式化 stream-json 的一條 entry
93
- * @param {object} entry - JSON parsed entry from claude --output-format stream-json
94
- * @returns {string|null}
95
- */
96
- function formatEntry(entry) {
97
- const ts = localHHMMSS();
98
- const { type } = entry;
99
-
100
- // ── system events ──
101
- if (type === 'system') {
102
- return formatSystem(ts, entry);
103
- }
104
-
105
- // ── assistant(agent 的輸出和工具呼叫)──
106
- if (type === 'assistant' && entry.message?.content) {
107
- const parts = [];
108
- for (const block of entry.message.content) {
109
- if (block.type === 'text' && block.text?.trim()) {
110
- const clean = block.text
111
- .replace(/^#{1,6}\s+/gm, '')
112
- .replace(/\*\*([^*]+)\*\*/g, '$1')
113
- .trim();
114
- const lines = clean.split('\n').filter(l => l.trim());
115
- for (const l of lines) {
116
- parts.push(`[${ts}][Agent] ${l.trim()}`);
117
- }
118
- } else if (block.type === 'tool_use') {
119
- parts.push(formatToolUse(ts, block));
120
- }
121
- }
122
- return parts.length ? parts.join('\n') : null;
123
- }
124
-
125
- // ── user(tool results、teammate 訊息)──
126
- if (type === 'user') {
127
- return formatUser(ts, entry);
128
- }
129
-
130
- // ── result(session 結束)──
131
- if (type === 'result') {
132
- return formatResult(ts, entry);
133
- }
134
-
135
- return null;
136
- }
137
-
138
- // ─────────────────────────────────────────
139
- // system events
140
- // ─────────────────────────────────────────
141
-
142
- function formatSystem(ts, entry) {
143
- const { subtype } = entry;
144
- if (subtype === 'init') {
145
- return `[${ts}][SYSTEM][INIT] model=${entry.model || ''} cwd=${entry.cwd || ''}`;
146
- }
147
- if (subtype === 'hook_started') {
148
- return `[${ts}][SYSTEM][HOOK] ${entry.hook_name || ''} started`;
149
- }
150
- if (subtype === 'hook_response') {
151
- const status = entry.outcome === 'error' ? 'FAILED' : 'OK';
152
- return `[${ts}][SYSTEM][HOOK] ${entry.hook_name || ''} ${status}`;
153
- }
154
- return null;
155
- }
156
-
157
- // ─────────────────────────────────────────
158
- // tool_use formatting(差異 4 修正)
159
- // ─────────────────────────────────────────
160
-
161
- function formatToolUse(ts, block) {
162
- const tool = block.name;
163
- const input = block.input || {};
164
-
165
- const toolFormatters = {
166
- Bash: () => input.description || input.command?.slice(0, 60) || '',
167
- Read: () => input.file_path || '',
168
- Write: () => input.file_path || '',
169
- Edit: () => input.file_path || '',
170
- Glob: () => input.pattern || '',
171
- Grep: () => input.pattern || '',
172
-
173
- // Agent Teams 工具(與 Sunny format-output.js 對齊)
174
- TeamCreate: () => `team="${input.team_name || ''}"`,
175
- TeamDelete: () => '',
176
- Task: () => {
177
- const name = input.name || input.description?.slice(0, 30) || '';
178
- const agentType = input.subagent_type || '';
179
- return name ? `spawn="${name}" type=${agentType}` : agentType;
180
- },
181
- SendMessage: () => {
182
- const recipient = input.recipient || '';
183
- const msgType = input.type || 'message';
184
- return `to=${recipient} type=${msgType}`;
185
- },
186
- TodoWrite: () => '',
187
- };
188
-
189
- const detail = (toolFormatters[tool] || (() => ''))();
190
- const line = `[${ts}][Agent][${tool}] ${detail}`;
191
-
192
- // SendMessage:附加完整訊息內容(與 Sunny 一致)
193
- if (tool === 'SendMessage' && input.content) {
194
- const msgLines = input.content.split('\n');
195
- const formatted = msgLines.map(ml => ` | ${ml}`).join('\n');
196
- return `${line}\n${formatted}`;
197
- }
198
-
199
- return line;
200
- }
201
-
202
- // ─────────────────────────────────────────
203
- // user events(差異 3 修正)
204
- // ─────────────────────────────────────────
205
-
206
- function formatUser(ts, entry) {
207
- const parts = [];
208
-
209
- // tool_use_result(teammate spawn 確認等)
210
- if (entry.tool_use_result) {
211
- const result = entry.tool_use_result;
212
- if (result.status === 'teammate_spawned') {
213
- parts.push(`[${ts}][SYSTEM][Spawned] Teammate "${result.name || ''}" model=${result.model || ''}`);
214
- } else if (result.team_name && result.success !== undefined) {
215
- const status = result.success ? 'OK' : 'FAILED';
216
- parts.push(`[${ts}][SYSTEM][TeamOp] ${status}: ${result.team_name}`);
217
- }
218
- }
219
-
220
- // 收到的訊息(來自 teammates 的 SendMessage)
221
- if (entry.message?.content) {
222
- for (const block of entry.message.content) {
223
- if (block.type === 'text' && block.text) {
224
- const text = block.text;
225
-
226
- // 嘗試提取 teammate 名稱
227
- let teammateName = 'Unknown';
228
- const nameMatch = text.match(/(?:from|From)\s+["']?(\w+[-\w]*)["']?/i);
229
- if (nameMatch) {
230
- teammateName = nameMatch[1];
231
- }
232
-
233
- // 判斷是否是 teammate 訊息
234
- if (text.includes('Message from') || text.includes('teammate') || text.includes('Teammate')) {
235
- parts.push(`[${ts}][Teammate:${teammateName}]`);
236
- const msgLines = text.split('\n').filter(l => l.trim());
237
- for (const ml of msgLines) {
238
- parts.push(` | ${ml}`);
239
- }
240
- }
241
- }
242
- }
243
- }
244
-
245
- return parts.length > 0 ? parts.join('\n') : null;
246
- }
247
-
248
- // ─────────────────────────────────────────
249
- // result(session 結束摘要,加入 token 統計)
250
- // ─────────────────────────────────────────
251
-
252
- function formatResult(ts, entry) {
253
- const lines = [];
254
- lines.push(`[${ts}][RESULT] ${(entry.subtype || '').toUpperCase()}`);
255
- lines.push(` Duration: ${((entry.duration_ms || 0) / 1000).toFixed(1)}s`);
256
- lines.push(` Cost: $${(entry.total_cost_usd || 0).toFixed(4)}`);
257
-
258
- // Token 統計(與 Sunny 對齊)
259
- if (entry.num_turns) {
260
- lines.push(` Turns: ${entry.num_turns}`);
261
- }
262
-
263
- if (entry.result) {
264
- const clean = entry.result.replace(/\*\*([^*]+)\*\*/g, '$1').trim();
265
- const resultLines = clean.split('\n').filter(l => l.trim()).slice(0, 10);
266
- for (const rl of resultLines) {
267
- lines.push(` ${rl}`);
268
- }
269
- }
270
- return lines.join('\n');
271
- }
272
-
273
- module.exports = { createLogWriter, formatEntry };
@@ -1,422 +0,0 @@
1
- /**
2
- * Memory Loader for Formation Prompt Builder
3
- * 從三個記憶系統載入相關經驗,注入到 agent prompt 中
4
- *
5
- * 系統:
6
- * 1. .failure/ — 失敗經驗(YAML,按 category 分目錄)
7
- * 2. .memory/ — 專案記憶(JSON,含 registry.json 索引)
8
- * 3. .kenaz/main-memory/ — 主記憶(Markdown,唯讀知識庫)
9
- *
10
- * 設計原則:
11
- * - 輕量:不跑 Node 子進程,直接讀檔
12
- * - 容錯:任何系統不可用時 graceful degradation
13
- * - Token 友善:按任務相關度裁剪,控制總 token 預算
14
- */
15
-
16
- const fs = require('fs');
17
- const path = require('path');
18
-
19
- const ROOT = path.resolve(__dirname, '..', '..');
20
-
21
- // ─────────────────────────────────────────
22
- // 配置
23
- // ─────────────────────────────────────────
24
-
25
- const DEFAULT_CONFIG = {
26
- // Token 預算(字元數,粗略 1 token ≈ 4 chars)
27
- MAX_CHARS: 3000,
28
-
29
- // 各系統最大條目數
30
- MAX_FAILURES: 3,
31
- MAX_MEMORIES: 5,
32
- MAX_MAIN_MEMORY: 3,
33
-
34
- // .failure/ 路徑
35
- FAILURE_DIR: path.join(ROOT, '.failure'),
36
-
37
- // .memory/ 路徑
38
- MEMORY_DIR: path.join(ROOT, '.memory'),
39
- MEMORY_REGISTRY: path.join(ROOT, '.memory', 'registry.json'),
40
-
41
- // .kenaz/main-memory/ 路徑
42
- MAIN_MEMORY_DIR: path.join(ROOT, '.kenaz', 'main-memory'),
43
- MAIN_MEMORY_REGISTRY: path.join(ROOT, '.kenaz', 'main-memory', 'registry.json'),
44
- };
45
-
46
- // Keep a mutable reference so callers that imported CONFIG still work
47
- const CONFIG = { ...DEFAULT_CONFIG };
48
-
49
- /**
50
- * Build config paths from a given core root directory.
51
- * When corePath differs from ROOT, re-points .failure/, .memory/, .kenaz/main-memory/
52
- * to the core project so sub-projects can load system-level memories.
53
- */
54
- function resolveConfig(corePath) {
55
- if (!corePath || path.resolve(corePath) === path.resolve(ROOT)) {
56
- return DEFAULT_CONFIG;
57
- }
58
- return {
59
- ...DEFAULT_CONFIG,
60
- FAILURE_DIR: path.join(corePath, '.failure'),
61
- MEMORY_DIR: path.join(corePath, '.memory'),
62
- MEMORY_REGISTRY: path.join(corePath, '.memory', 'registry.json'),
63
- MAIN_MEMORY_DIR: path.join(corePath, '.kenaz', 'main-memory'),
64
- MAIN_MEMORY_REGISTRY: path.join(corePath, '.kenaz', 'main-memory', 'registry.json'),
65
- };
66
- }
67
-
68
- // ─────────────────────────────────────────
69
- // 主入口
70
- // ─────────────────────────────────────────
71
-
72
- /**
73
- * 載入與任務相關的記憶 context
74
- * @param {object} opts
75
- * @param {string} [opts.taskTitle] - 任務標題
76
- * @param {string} [opts.role] - 角色(frontend/backend/developer/...)
77
- * @param {string[]} [opts.scopePaths] - scope 路徑
78
- * @param {string[]} [opts.tags] - 任務標籤
79
- * @param {string} [opts.priority] - P0/P1/P2/P3
80
- * @param {boolean} [opts.skipFailures] - TASK_1998 R2 (+ follow-up
81
- * 2026-09-22): skip Known Failures (rigor:low prompt diet only — rigor:medium
82
- * restores this section).
83
- * @param {boolean} [opts.skipMemory] - TASK_1998 R2: skip Project Memory
84
- * (rigor low/medium prompt diet). Knowledge Base (main-memory) always loads
85
- * regardless of either flag — it isn't part of the ritual collapse.
86
- * @returns {string} 組裝好的記憶 context 區塊(可直接 append 到 prompt)
87
- */
88
- function loadMemoryContext(opts = {}) {
89
- // Resolve config from corePath (supports sub-projects pointing to core)
90
- const cfg = resolveConfig(opts.corePath);
91
- const sections = [];
92
-
93
- // TASK_1998 R2 (+ follow-up 2026-09-22): Known Failures and Project Memory
94
- // are two of the six ritual sections collapsed into prompt.js's "## Working
95
- // contract" for rigor low/medium — but Known Failures is now restored for
96
- // rigor:medium (only rigor:low drops it); Project Memory stays dropped for
97
- // both. Knowledge Base (step 3, main-memory) is unaffected by either flag.
98
- if (!opts.skipFailures) {
99
- // 1. .failure/ — 失敗經驗(最高優先)
100
- try {
101
- const failures = loadFailures(opts, cfg);
102
- if (failures.length > 0) {
103
- sections.push(formatFailures(failures));
104
- }
105
- } catch { /* graceful degradation */ }
106
- }
107
-
108
- if (!opts.skipMemory) {
109
- // 2. .memory/ — 專案記憶
110
- try {
111
- const memories = loadProjectMemories(opts, cfg);
112
- if (memories.length > 0) {
113
- sections.push(formatMemories(memories));
114
- }
115
- } catch { /* graceful degradation */ }
116
- }
117
-
118
- // 3. .kenaz/main-memory/ — 主記憶
119
- try {
120
- const mainMem = loadMainMemory(opts, cfg);
121
- if (mainMem.length > 0) {
122
- sections.push(formatMainMemory(mainMem));
123
- }
124
- } catch { /* graceful degradation */ }
125
-
126
- if (sections.length === 0) return '';
127
-
128
- // 組裝 + 裁剪
129
- let result = sections.join('\n');
130
- if (result.length > cfg.MAX_CHARS) {
131
- result = result.slice(0, cfg.MAX_CHARS) + '\n...(記憶已裁剪)';
132
- }
133
-
134
- return result;
135
- }
136
-
137
- // ─────────────────────────────────────────
138
- // .failure/ 載入
139
- // ─────────────────────────────────────────
140
-
141
- // TASK_2371: entries from Heimdall REVERT/guardian health events and entries about
142
- // removed systems are stale noise in dispatch prompts. Phase 9 / cognitive checkpoint
143
- // entries describe the phase ritual archived in TASK_2372.
144
- const STALE_FAILURE_RE = /Heimdall|guardian health|Kuzu|\bNorn\b|thalamus|\breflex\b|Formation squad|\bREVERT\b|Phase 9|[Cc]ognitive checkpoint/;
145
-
146
- function loadFailures(opts, cfg = DEFAULT_CONFIG) {
147
- const indexPath = path.join(cfg.FAILURE_DIR, 'INDEX.yaml');
148
- if (!fs.existsSync(indexPath)) return [];
149
-
150
- // 掃描所有子目錄的 FAIL-*.yaml 和 FAIL-*.md
151
- const results = [];
152
- const categories = ['agent-execution', 'code-quality', 'architecture', 'pipeline', 'data-integrity'];
153
-
154
- for (const cat of categories) {
155
- const catDir = path.join(cfg.FAILURE_DIR, cat);
156
- if (!fs.existsSync(catDir)) continue;
157
-
158
- const files = fs.readdirSync(catDir).filter(f => f.startsWith('FAIL-'));
159
- for (const file of files) {
160
- const filePath = path.join(catDir, file);
161
- try {
162
- const content = fs.readFileSync(filePath, 'utf-8');
163
- if (STALE_FAILURE_RE.test(content)) continue;
164
- const entry = parseFailureEntry(content, file, cat);
165
- if (entry) {
166
- entry.seq = Number((file.match(/(\d+)/) || [])[1] || 0);
167
- entry.relevance = scoreRelevance(entry, opts);
168
- results.push(entry);
169
- }
170
- } catch { /* skip unreadable files */ }
171
- }
172
- }
173
-
174
- // Sort by relevance, then filter by task tags/category if provided, cap at MAX_FAILURES
175
- results.sort((a, b) => b.relevance - a.relevance);
176
- let filtered = results;
177
- if (opts.tags && opts.tags.length > 0) {
178
- const tagSet = new Set(opts.tags.map(t => t.toLowerCase()));
179
- const tagMatches = results.filter(e => tagSet.has(e.category.replace(/-/g, '_')) || e.keywords.some(k => tagSet.has(k)));
180
- if (tagMatches.length > 0) filtered = tagMatches;
181
- }
182
- // TASK_2371: newest first = highest FAIL number (mtime is checkout time in worktrees; relevance only decides which entries survive the tag filter)
183
- return filtered.sort((a, b) => b.seq - a.seq).slice(0, cfg.MAX_FAILURES);
184
- }
185
-
186
- /**
187
- * 解析 .failure/ 條目(支援 YAML 和 Markdown 格式)
188
- */
189
- function parseFailureEntry(content, filename, category) {
190
- // 提取標題
191
- let title = filename;
192
- const titleMatch = content.match(/^#\s+\[?(FAIL-\d+)\]?\s*(.*)/m)
193
- || content.match(/title:\s*["']?(.+?)["']?\s*$/m);
194
- if (titleMatch) {
195
- // Markdown header: use [0] stripped; YAML title: use capture group [1]
196
- title = titleMatch[0].trim().startsWith('#')
197
- ? titleMatch[0].replace(/^#\s+/, '').trim()
198
- : (titleMatch[1] || titleMatch[0]).replace(/['"]?/g, '').trim();
199
- }
200
-
201
- // 提取 severity
202
- let severity = 'medium';
203
- const sevMatch = content.match(/severity:\s*["']?(\w+)["']?/i);
204
- if (sevMatch) severity = sevMatch[1].toLowerCase();
205
-
206
- // 提取摘要(取前 3 行非空非標題內容)
207
- const lines = content.split('\n');
208
- const summaryLines = [];
209
- let started = false;
210
- for (const line of lines) {
211
- const trimmed = line.trim();
212
- if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('_meta') || trimmed.startsWith('---') || /^\w+\s*:/.test(trimmed)) {
213
- if (started) continue;
214
- continue;
215
- }
216
- started = true;
217
- summaryLines.push(trimmed);
218
- if (summaryLines.length >= 3) break;
219
- }
220
-
221
- return {
222
- id: filename.replace(/\.(yaml|md)$/, ''),
223
- title,
224
- severity,
225
- category,
226
- summary: summaryLines.join(' ').slice(0, 200),
227
- keywords: extractKeywords(content),
228
- };
229
- }
230
-
231
- // ─────────────────────────────────────────
232
- // .memory/ 載入
233
- // ─────────────────────────────────────────
234
-
235
- function loadProjectMemories(opts, cfg = DEFAULT_CONFIG) {
236
- if (!fs.existsSync(cfg.MEMORY_REGISTRY)) return [];
237
-
238
- let registry;
239
- try {
240
- registry = JSON.parse(fs.readFileSync(cfg.MEMORY_REGISTRY, 'utf-8'));
241
- } catch { return []; }
242
-
243
- const memories = registry.memories || [];
244
- if (memories.length === 0) return [];
245
-
246
- // 評分 + 排序
247
- const scored = memories.map(m => ({
248
- ...m,
249
- relevance: scoreMemoryRelevance(m, opts),
250
- }));
251
-
252
- scored.sort((a, b) => {
253
- // 先按相關度,再按 importance
254
- const relDiff = b.relevance - a.relevance;
255
- if (relDiff !== 0) return relDiff;
256
- return (b.importance || 0) - (a.importance || 0);
257
- });
258
-
259
- // 取前 N 個,importance >= 3 的
260
- return scored
261
- .filter(m => (m.importance || 0) >= 3)
262
- .slice(0, CONFIG.MAX_MEMORIES);
263
- }
264
-
265
- // ─────────────────────────────────────────
266
- // .kenaz/main-memory/ 載入
267
- // ─────────────────────────────────────────
268
-
269
- function loadMainMemory(opts, cfg = DEFAULT_CONFIG) {
270
- if (!fs.existsSync(cfg.MAIN_MEMORY_REGISTRY)) return [];
271
-
272
- let registry;
273
- try {
274
- registry = JSON.parse(fs.readFileSync(cfg.MAIN_MEMORY_REGISTRY, 'utf-8'));
275
- } catch { return []; }
276
-
277
- const entries = registry.entries || registry.memories || [];
278
- if (entries.length === 0) return [];
279
-
280
- // 按相關度排序
281
- const scored = entries.map(e => ({
282
- ...e,
283
- relevance: scoreMainMemoryRelevance(e, opts),
284
- }));
285
-
286
- scored.sort((a, b) => b.relevance - a.relevance);
287
- return scored.slice(0, CONFIG.MAX_MAIN_MEMORY);
288
- }
289
-
290
- // ─────────────────────────────────────────
291
- // 相關度評分
292
- // ─────────────────────────────────────────
293
-
294
- /**
295
- * .failure/ 條目相關度評分
296
- */
297
- function scoreRelevance(entry, opts) {
298
- let score = 0;
299
-
300
- // severity 加分
301
- if (entry.severity === 'critical') score += 3;
302
- else if (entry.severity === 'high') score += 2;
303
- else if (entry.severity === 'medium') score += 1;
304
-
305
- // 關鍵字匹配
306
- if (opts.role && entry.keywords.includes(opts.role)) score += 2;
307
- if (opts.taskTitle) {
308
- const titleLower = opts.taskTitle.toLowerCase();
309
- for (const kw of entry.keywords) {
310
- if (titleLower.includes(kw)) score += 1;
311
- }
312
- }
313
- if (opts.tags) {
314
- for (const tag of opts.tags) {
315
- if (entry.keywords.includes(tag.toLowerCase())) score += 1;
316
- }
317
- }
318
-
319
- // agent-execution 類別對所有 agent 都相關
320
- if (entry.category === 'agent-execution') score += 1;
321
-
322
- return score;
323
- }
324
-
325
- /**
326
- * .memory/ 條目相關度評分
327
- */
328
- function scoreMemoryRelevance(entry, opts) {
329
- let score = (entry.importance || 0) * 0.5;
330
-
331
- // failure 類型加分(避免重蹈覆轍)
332
- if (entry.type === 'failure') score += 2;
333
- if (entry.type === 'decision') score += 1;
334
-
335
- // 標題關鍵字匹配
336
- if (opts.taskTitle && entry.title) {
337
- const titleWords = opts.taskTitle.toLowerCase().split(/\s+/);
338
- const entryTitle = entry.title.toLowerCase();
339
- for (const w of titleWords) {
340
- if (w.length > 2 && entryTitle.includes(w)) score += 1;
341
- }
342
- }
343
-
344
- return score;
345
- }
346
-
347
- /**
348
- * .kenaz/main-memory/ 條目相關度評分
349
- */
350
- function scoreMainMemoryRelevance(entry, opts) {
351
- let score = 1;
352
-
353
- const entryStr = JSON.stringify(entry).toLowerCase();
354
-
355
- if (opts.role && entryStr.includes(opts.role.toLowerCase())) score += 2;
356
- if (opts.taskTitle) {
357
- const words = opts.taskTitle.toLowerCase().split(/\s+/);
358
- for (const w of words) {
359
- if (w.length > 2 && entryStr.includes(w)) score += 1;
360
- }
361
- }
362
-
363
- return score;
364
- }
365
-
366
- // ─────────────────────────────────────────
367
- // 格式化輸出
368
- // ─────────────────────────────────────────
369
-
370
- function formatFailures(failures) {
371
- const lines = ['## Known Failures (避免重蹈覆轍)', ''];
372
- for (const f of failures) {
373
- const sev = f.severity === 'critical' ? '🔴' : f.severity === 'high' ? '🟠' : '🟡';
374
- // Extract first sentence as lesson (ends at . or end of summary)
375
- const lessonMatch = f.summary && f.summary.match(/^[^.!?]+[.!?]/);
376
- const lesson = lessonMatch ? lessonMatch[0].trim() : f.summary;
377
- const lessonPart = lesson ? ' — ' + lesson : '';
378
- lines.push(`- ${sev} **${f.title}**${lessonPart}`);
379
- }
380
- lines.push('');
381
- return lines.join('\n');
382
- }
383
-
384
- function formatMemories(memories) {
385
- const lines = ['## Project Memory (歷史經驗)', ''];
386
- for (const m of memories) {
387
- const typeIcon = m.type === 'failure' ? '⚠️' : m.type === 'decision' ? '📌' : m.type === 'pattern' ? '✅' : 'ℹ️';
388
- lines.push(`- ${typeIcon} [${m.type}] **${m.title}** (importance: ${m.importance || '?'})`);
389
- }
390
- lines.push('');
391
- return lines.join('\n');
392
- }
393
-
394
- function formatMainMemory(entries) {
395
- const lines = ['## Knowledge Base (通用知識)', ''];
396
- for (const e of entries) {
397
- const title = e.title || e.id || 'Unknown';
398
- lines.push(`- 📖 ${title}`);
399
- if (e.summary) lines.push(` ${e.summary}`);
400
- }
401
- lines.push('');
402
- return lines.join('\n');
403
- }
404
-
405
- // ─────────────────────────────────────────
406
- // 工具函數
407
- // ─────────────────────────────────────────
408
-
409
- /**
410
- * 從文字中提取關鍵字(小寫化)
411
- */
412
- function extractKeywords(text) {
413
- const words = text.toLowerCase()
414
- .replace(/[^a-z0-9\u4e00-\u9fff\s_-]/g, ' ')
415
- .split(/\s+/)
416
- .filter(w => w.length > 2);
417
-
418
- // 去重
419
- return [...new Set(words)];
420
- }
421
-
422
- module.exports = { loadMemoryContext, loadFailures, CONFIG };