@stackmemoryai/stackmemory 0.5.67 → 0.6.1

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.
@@ -35,16 +35,16 @@ const distDir = join(__dirname, '..', 'dist');
35
35
  * Returns true if user consents, false otherwise
36
36
  */
37
37
  async function askForConsent() {
38
- // Skip prompt if:
39
- // 1. Not a TTY (CI/CD, piped input)
40
- // 2. STACKMEMORY_AUTO_HOOKS=true is set
41
- // 3. Running in CI environment
42
- if (
43
- !process.stdin.isTTY ||
44
- process.env.STACKMEMORY_AUTO_HOOKS === 'true' ||
45
- process.env.CI === 'true'
46
- ) {
47
- // In non-interactive mode, skip hook installation silently
38
+ // Auto-install if STACKMEMORY_AUTO_HOOKS=true (no prompt needed)
39
+ if (process.env.STACKMEMORY_AUTO_HOOKS === 'true') {
40
+ console.log(
41
+ 'STACKMEMORY_AUTO_HOOKS=true installing hooks automatically.'
42
+ );
43
+ return true;
44
+ }
45
+
46
+ // Skip prompt if not interactive (CI/CD, piped input)
47
+ if (!process.stdin.isTTY || process.env.CI === 'true') {
48
48
  console.log(
49
49
  'StackMemory installed. Run "stackmemory setup-mcp" to configure Claude Code integration.'
50
50
  );
@@ -58,6 +58,8 @@ async function askForConsent() {
58
58
  console.log(' - Track tool usage for better context');
59
59
  console.log(' - Enable session persistence across restarts');
60
60
  console.log(' - Sync context with Linear (optional)');
61
+ console.log(' - Auto-update PROMPT_PLAN on task completion');
62
+ console.log(' - Recommend relevant skills based on your prompts');
61
63
  console.log('\nThis will modify files in ~/.claude/\n');
62
64
 
63
65
  return new Promise((resolve) => {
@@ -89,11 +91,19 @@ async function installClaudeHooks() {
89
91
  console.log('Created ~/.claude/hooks directory');
90
92
  }
91
93
 
92
- // Copy hook files
93
- const hookFiles = ['tool-use-trace.js', 'on-startup.js', 'on-clear.js'];
94
+ // Copy hook files (scripts + data files)
95
+ const hookFiles = [
96
+ 'tool-use-trace.js',
97
+ 'on-startup.js',
98
+ 'on-clear.js',
99
+ 'on-task-complete.js',
100
+ 'skill-eval.sh',
101
+ 'skill-eval.cjs',
102
+ ];
103
+ const dataFiles = ['skill-rules.json'];
94
104
  let installed = 0;
95
105
 
96
- for (const hookFile of hookFiles) {
106
+ for (const hookFile of [...hookFiles, ...dataFiles]) {
97
107
  const srcPath = join(templatesDir, hookFile);
98
108
  const destPath = join(claudeHooksDir, hookFile);
99
109
 
@@ -107,12 +117,14 @@ async function installClaudeHooks() {
107
117
 
108
118
  copyFileSync(srcPath, destPath);
109
119
 
110
- // Make executable
111
- try {
112
- const { execSync } = await import('child_process');
113
- execSync(`chmod +x "${destPath}"`, { stdio: 'ignore' });
114
- } catch {
115
- // Silent fail on chmod
120
+ // Make executable (scripts only, not data files)
121
+ if (!dataFiles.includes(hookFile)) {
122
+ try {
123
+ const { execSync } = await import('child_process');
124
+ execSync(`chmod +x "${destPath}"`, { stdio: 'ignore' });
125
+ } catch {
126
+ // Silent fail on chmod
127
+ }
116
128
  }
117
129
 
118
130
  installed++;
@@ -136,6 +148,8 @@ async function installClaudeHooks() {
136
148
  'tool-use-approval': join(claudeHooksDir, 'tool-use-trace.js'),
137
149
  'on-startup': join(claudeHooksDir, 'on-startup.js'),
138
150
  'on-clear': join(claudeHooksDir, 'on-clear.js'),
151
+ 'on-task-complete': join(claudeHooksDir, 'on-task-complete.js'),
152
+ 'user-prompt-submit': join(claudeHooksDir, 'skill-eval.sh'),
139
153
  };
140
154
 
141
155
  writeFileSync(claudeConfigFile, JSON.stringify(newHooksConfig, null, 2));
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "tool-use-approval": "~/.claude/hooks/tool-use-trace.js",
3
3
  "on-startup": "~/.claude/hooks/on-startup.js",
4
- "on-clear": "~/.claude/hooks/on-clear.js"
5
- }
4
+ "on-clear": "~/.claude/hooks/on-clear.js",
5
+ "on-task-complete": "~/.claude/hooks/on-task-complete.js",
6
+ "user-prompt-submit": "~/.claude/hooks/skill-eval.sh"
7
+ }
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * On-task-complete hook for StackMemory
5
+ * Triggers when a task is marked as done in Claude Code.
6
+ *
7
+ * Actions:
8
+ * 1. Auto-updates PROMPT_PLAN.md checkboxes (fuzzy match on task keywords)
9
+ * 2. Syncs Linear tasks (if STA-* identifier present)
10
+ * 3. Logs to ~/.stackmemory/logs/hook-errors.log on failure (non-blocking)
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ async function onTaskComplete() {
17
+ try {
18
+ const input = JSON.parse(fs.readFileSync(0, 'utf-8'));
19
+
20
+ // Sync Linear if STA task
21
+ if (input.task && input.task.includes('STA-')) {
22
+ try {
23
+ const syncScript = path.join(
24
+ process.cwd(),
25
+ 'scripts',
26
+ 'sync-linear-graphql.js'
27
+ );
28
+ if (fs.existsSync(syncScript)) {
29
+ const { execSync } = require('child_process');
30
+ execSync(`node "${syncScript}"`, {
31
+ stdio: 'ignore',
32
+ timeout: 10000,
33
+ });
34
+ }
35
+ } catch (_e) {
36
+ // Non-blocking
37
+ }
38
+ }
39
+
40
+ // Auto-update PROMPT_PLAN checkboxes if spec exists
41
+ const promptPlanPath = path.join(
42
+ process.cwd(),
43
+ 'docs',
44
+ 'specs',
45
+ 'PROMPT_PLAN.md'
46
+ );
47
+ if (fs.existsSync(promptPlanPath) && input.task) {
48
+ try {
49
+ const content = fs.readFileSync(promptPlanPath, 'utf-8');
50
+ const taskWords = input.task.split(/\s+/).filter((w) => w.length > 3);
51
+ const lines = content.split('\n');
52
+ let updated = false;
53
+ for (let i = 0; i < lines.length; i++) {
54
+ if (
55
+ lines[i].includes('- [ ]') &&
56
+ taskWords.some((w) =>
57
+ lines[i].toLowerCase().includes(w.toLowerCase())
58
+ )
59
+ ) {
60
+ lines[i] = lines[i].replace('- [ ]', '- [x]');
61
+ updated = true;
62
+ break;
63
+ }
64
+ }
65
+ if (updated) {
66
+ fs.writeFileSync(promptPlanPath, lines.join('\n'));
67
+ }
68
+ } catch (_e) {
69
+ // Silently fail
70
+ }
71
+ }
72
+ } catch (error) {
73
+ const logDir = path.join(
74
+ process.env.HOME || '/tmp',
75
+ '.stackmemory',
76
+ 'logs'
77
+ );
78
+ try {
79
+ fs.mkdirSync(logDir, { recursive: true });
80
+ fs.appendFileSync(
81
+ path.join(logDir, 'hook-errors.log'),
82
+ `[${new Date().toISOString()}] on-task-complete: ${error.message}\n`
83
+ );
84
+ } catch (_e) {
85
+ // Last resort: silent
86
+ }
87
+ }
88
+ }
89
+
90
+ onTaskComplete();
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Skill Evaluation Engine v2.0
4
+ *
5
+ * Intelligent skill activation based on:
6
+ * - Keywords and patterns in prompts
7
+ * - File paths mentioned or being edited
8
+ * - Directory mappings
9
+ * - Intent detection
10
+ * - Content pattern matching
11
+ *
12
+ * Outputs a structured reminder with matched skills and reasons.
13
+ */
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ // Configuration
19
+ const RULES_PATH = path.join(__dirname, 'skill-rules.json');
20
+
21
+ /**
22
+ * @typedef {Object} SkillMatch
23
+ * @property {string} name - Skill name
24
+ * @property {number} score - Confidence score
25
+ * @property {string[]} reasons - Why this skill was matched
26
+ * @property {number} priority - Skill priority
27
+ */
28
+
29
+ /**
30
+ * Load skill rules from JSON file
31
+ * @returns {Object} Parsed skill rules
32
+ */
33
+ function loadRules() {
34
+ try {
35
+ const content = fs.readFileSync(RULES_PATH, 'utf-8');
36
+ return JSON.parse(content);
37
+ } catch (error) {
38
+ console.error(`Failed to load skill rules: ${error.message}`);
39
+ process.exit(0); // Exit gracefully to not block the prompt
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Extract file paths mentioned in the prompt
45
+ * @param {string} prompt - User's prompt text
46
+ * @returns {string[]} Array of detected file paths
47
+ */
48
+ function extractFilePaths(prompt) {
49
+ const paths = new Set();
50
+
51
+ // Match explicit paths with extensions (.tsx, .ts, .jsx, .js, .json, .gql, .yaml, .yml, .md, .sh)
52
+ const extensionPattern =
53
+ /(?:^|\s|["'`])([\w\-./]+\.(?:[tj]sx?|json|gql|ya?ml|md|sh))\b/gi;
54
+ let match;
55
+ while ((match = extensionPattern.exec(prompt)) !== null) {
56
+ paths.add(match[1]);
57
+ }
58
+
59
+ // Match paths starting with common directories
60
+ const dirPattern =
61
+ /(?:^|\s|["'`])((?:src|app|components|screens|hooks|utils|services|navigation|graphql|localization|\.claude|\.github|\.maestro)\/[\w\-./]+)/gi;
62
+ while ((match = dirPattern.exec(prompt)) !== null) {
63
+ paths.add(match[1]);
64
+ }
65
+
66
+ // Match quoted paths
67
+ const quotedPattern = /["'`]([\w\-./]+\/[\w\-./]+)["'`]/g;
68
+ while ((match = quotedPattern.exec(prompt)) !== null) {
69
+ paths.add(match[1]);
70
+ }
71
+
72
+ return Array.from(paths);
73
+ }
74
+
75
+ /**
76
+ * Check if a pattern matches the text
77
+ * @param {string} text - Text to search in
78
+ * @param {string} pattern - Regex pattern
79
+ * @param {string} flags - Regex flags
80
+ * @returns {boolean}
81
+ */
82
+ function matchesPattern(text, pattern, flags = 'i') {
83
+ try {
84
+ const regex = new RegExp(pattern, flags);
85
+ return regex.test(text);
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Check if a glob pattern matches a file path
93
+ * @param {string} filePath - File path to check
94
+ * @param {string} globPattern - Glob pattern (simplified)
95
+ * @returns {boolean}
96
+ */
97
+ function matchesGlob(filePath, globPattern) {
98
+ // Convert glob to regex (simplified)
99
+ const regexPattern = globPattern
100
+ .replace(/\./g, '\\.')
101
+ .replace(/\*\*\//g, '<<<DOUBLESTARSLASH>>>')
102
+ .replace(/\*\*/g, '<<<DOUBLESTAR>>>')
103
+ .replace(/\*/g, '[^/]*')
104
+ .replace(/<<<DOUBLESTARSLASH>>>/g, '(.*\\/)?')
105
+ .replace(/<<<DOUBLESTAR>>>/g, '.*')
106
+ .replace(/\?/g, '.');
107
+
108
+ try {
109
+ const regex = new RegExp(`^${regexPattern}$`, 'i');
110
+ return regex.test(filePath);
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Check if file path matches any directory mapping
118
+ * @param {string} filePath - File path to check
119
+ * @param {Object} mappings - Directory to skill mappings
120
+ * @returns {string|null} Matched skill name or null
121
+ */
122
+ function matchDirectoryMapping(filePath, mappings) {
123
+ for (const [dir, skillName] of Object.entries(mappings)) {
124
+ if (filePath === dir || filePath.startsWith(dir + '/')) {
125
+ return skillName;
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * Evaluate a single skill against the prompt and context
133
+ * @param {string} skillName - Name of the skill
134
+ * @param {Object} skill - Skill configuration
135
+ * @param {string} prompt - User's prompt
136
+ * @param {string} promptLower - Lowercase prompt
137
+ * @param {string[]} filePaths - Extracted file paths
138
+ * @param {Object} rules - Full rules object
139
+ * @returns {SkillMatch|null}
140
+ */
141
+ function evaluateSkill(
142
+ skillName,
143
+ skill,
144
+ prompt,
145
+ promptLower,
146
+ filePaths,
147
+ rules
148
+ ) {
149
+ const { triggers = {}, excludePatterns = [], priority = 5 } = skill;
150
+ const scoring = rules.scoring;
151
+
152
+ let score = 0;
153
+ const reasons = [];
154
+
155
+ // Check exclude patterns first
156
+ for (const excludePattern of excludePatterns) {
157
+ if (matchesPattern(promptLower, excludePattern)) {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ // 1. Check keywords
163
+ if (triggers.keywords) {
164
+ for (const keyword of triggers.keywords) {
165
+ if (promptLower.includes(keyword.toLowerCase())) {
166
+ score += scoring.keyword;
167
+ reasons.push(`keyword "${keyword}"`);
168
+ }
169
+ }
170
+ }
171
+
172
+ // 2. Check keyword patterns (regex)
173
+ if (triggers.keywordPatterns) {
174
+ for (const pattern of triggers.keywordPatterns) {
175
+ if (matchesPattern(promptLower, pattern)) {
176
+ score += scoring.keywordPattern;
177
+ reasons.push(`pattern /${pattern}/`);
178
+ }
179
+ }
180
+ }
181
+
182
+ // 3. Check intent patterns
183
+ if (triggers.intentPatterns) {
184
+ for (const pattern of triggers.intentPatterns) {
185
+ if (matchesPattern(promptLower, pattern)) {
186
+ score += scoring.intentPattern;
187
+ reasons.push(`intent detected`);
188
+ break;
189
+ }
190
+ }
191
+ }
192
+
193
+ // 4. Check context patterns
194
+ if (triggers.contextPatterns) {
195
+ for (const pattern of triggers.contextPatterns) {
196
+ if (promptLower.includes(pattern.toLowerCase())) {
197
+ score += scoring.contextPattern;
198
+ reasons.push(`context "${pattern}"`);
199
+ }
200
+ }
201
+ }
202
+
203
+ // 5. Check file paths against path patterns
204
+ if (triggers.pathPatterns && filePaths.length > 0) {
205
+ for (const filePath of filePaths) {
206
+ for (const pattern of triggers.pathPatterns) {
207
+ if (matchesGlob(filePath, pattern)) {
208
+ score += scoring.pathPattern;
209
+ reasons.push(`path "${filePath}"`);
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ // 6. Check directory mappings
217
+ if (rules.directoryMappings && filePaths.length > 0) {
218
+ for (const filePath of filePaths) {
219
+ const mappedSkill = matchDirectoryMapping(
220
+ filePath,
221
+ rules.directoryMappings
222
+ );
223
+ if (mappedSkill === skillName) {
224
+ score += scoring.directoryMatch;
225
+ reasons.push(`directory mapping`);
226
+ break;
227
+ }
228
+ }
229
+ }
230
+
231
+ // 7. Check content patterns in prompt (for code snippets)
232
+ if (triggers.contentPatterns) {
233
+ for (const pattern of triggers.contentPatterns) {
234
+ if (matchesPattern(prompt, pattern)) {
235
+ score += scoring.contentPattern;
236
+ reasons.push(`code pattern detected`);
237
+ break;
238
+ }
239
+ }
240
+ }
241
+
242
+ if (score > 0) {
243
+ return {
244
+ name: skillName,
245
+ score,
246
+ reasons: [...new Set(reasons)],
247
+ priority,
248
+ };
249
+ }
250
+
251
+ return null;
252
+ }
253
+
254
+ /**
255
+ * Get related skills that should also be suggested
256
+ * @param {SkillMatch[]} matches - Current matches
257
+ * @param {Object} skills - All skill definitions
258
+ * @returns {string[]} Additional skill names to suggest
259
+ */
260
+ function getRelatedSkills(matches, skills) {
261
+ const matchedNames = new Set(matches.map((m) => m.name));
262
+ const related = new Set();
263
+
264
+ for (const match of matches) {
265
+ const skill = skills[match.name];
266
+ if (skill?.relatedSkills) {
267
+ for (const relatedName of skill.relatedSkills) {
268
+ if (!matchedNames.has(relatedName)) {
269
+ related.add(relatedName);
270
+ }
271
+ }
272
+ }
273
+ }
274
+
275
+ return Array.from(related);
276
+ }
277
+
278
+ /**
279
+ * Format confidence level based on score
280
+ * @param {number} score - Confidence score
281
+ * @param {number} minScore - Minimum threshold
282
+ * @returns {string} Confidence label
283
+ */
284
+ function formatConfidence(score, minScore) {
285
+ if (score >= minScore * 3) return 'HIGH';
286
+ if (score >= minScore * 2) return 'MEDIUM';
287
+ return 'LOW';
288
+ }
289
+
290
+ /**
291
+ * Main evaluation function
292
+ * @param {string} prompt - User's prompt
293
+ * @returns {string} Formatted output
294
+ */
295
+ function evaluate(prompt) {
296
+ const rules = loadRules();
297
+ const { config, skills } = rules;
298
+
299
+ const promptLower = prompt.toLowerCase();
300
+ const filePaths = extractFilePaths(prompt);
301
+
302
+ // Evaluate all skills
303
+ const matches = [];
304
+ for (const [name, skill] of Object.entries(skills)) {
305
+ const match = evaluateSkill(
306
+ name,
307
+ skill,
308
+ prompt,
309
+ promptLower,
310
+ filePaths,
311
+ rules
312
+ );
313
+ if (match && match.score >= config.minConfidenceScore) {
314
+ matches.push(match);
315
+ }
316
+ }
317
+
318
+ if (matches.length === 0) {
319
+ return '';
320
+ }
321
+
322
+ // Sort by score (descending), then by priority (descending)
323
+ matches.sort((a, b) => {
324
+ if (b.score !== a.score) return b.score - a.score;
325
+ return b.priority - a.priority;
326
+ });
327
+
328
+ // Limit to max skills
329
+ const topMatches = matches.slice(0, config.maxSkillsToShow);
330
+
331
+ // Check for related skills
332
+ const relatedSkills = getRelatedSkills(topMatches, skills);
333
+
334
+ // Format output
335
+ let output = '<user-prompt-submit-hook>\n';
336
+ output += 'SKILL ACTIVATION REQUIRED\n\n';
337
+
338
+ if (filePaths.length > 0) {
339
+ output += `Detected file paths: ${filePaths.join(', ')}\n\n`;
340
+ }
341
+
342
+ output += 'Matched skills (ranked by relevance):\n';
343
+
344
+ for (let i = 0; i < topMatches.length; i++) {
345
+ const match = topMatches[i];
346
+ const confidence = formatConfidence(match.score, config.minConfidenceScore);
347
+
348
+ output += `${i + 1}. ${match.name} (${confidence} confidence)\n`;
349
+
350
+ if (config.showMatchReasons && match.reasons.length > 0) {
351
+ output += ` Matched: ${match.reasons.slice(0, 3).join(', ')}\n`;
352
+ }
353
+ }
354
+
355
+ if (relatedSkills.length > 0) {
356
+ output += `\nRelated skills to consider: ${relatedSkills.join(', ')}\n`;
357
+ }
358
+
359
+ output += '\nBefore implementing, you MUST:\n';
360
+ output += '1. EVALUATE: State YES/NO for each skill with brief reasoning\n';
361
+ output += '2. ACTIVATE: Invoke the Skill tool for each YES skill\n';
362
+ output += '3. IMPLEMENT: Only proceed after skill activation\n';
363
+ output += '\nExample evaluation:\n';
364
+ output += `- ${topMatches[0].name}: YES - [your reasoning]\n`;
365
+ if (topMatches.length > 1) {
366
+ output += `- ${topMatches[1].name}: NO - [your reasoning]\n`;
367
+ }
368
+ output += '\nDO NOT skip this step. Invoke relevant skills NOW.\n';
369
+ output += '</user-prompt-submit-hook>';
370
+
371
+ return output;
372
+ }
373
+
374
+ // Main execution
375
+ function main() {
376
+ let input = '';
377
+
378
+ process.stdin.setEncoding('utf8');
379
+
380
+ process.stdin.on('data', (chunk) => {
381
+ input += chunk;
382
+ });
383
+
384
+ process.stdin.on('end', () => {
385
+ let prompt = '';
386
+
387
+ try {
388
+ const data = JSON.parse(input);
389
+ prompt = data.prompt || '';
390
+ } catch {
391
+ prompt = input;
392
+ }
393
+
394
+ if (!prompt.trim()) {
395
+ process.exit(0);
396
+ }
397
+
398
+ try {
399
+ const output = evaluate(prompt);
400
+ if (output) {
401
+ console.log(output);
402
+ }
403
+ } catch (error) {
404
+ console.error(`Skill evaluation failed: ${error.message}`);
405
+ }
406
+
407
+ process.exit(0);
408
+ });
409
+ }
410
+
411
+ main();
@@ -0,0 +1,31 @@
1
+ #!/bin/bash
2
+ # Skill Evaluation Hook v2.0
3
+ # Wrapper script that delegates to the Node.js evaluation engine
4
+ #
5
+ # This hook runs on UserPromptSubmit and analyzes the prompt for:
6
+ # - Keywords and patterns indicating skill relevance
7
+ # - File paths mentioned in the prompt
8
+ # - Intent patterns (what the user wants to do)
9
+ # - Directory mappings (what directories map to which skills)
10
+ #
11
+ # Configuration is in skill-rules.json
12
+
13
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+ NODE_SCRIPT="$SCRIPT_DIR/skill-eval.cjs"
15
+
16
+ # Check if Node.js is available
17
+ if ! command -v node &>/dev/null; then
18
+ # Fallback: exit silently if Node.js not found
19
+ exit 0
20
+ fi
21
+
22
+ # Check if the Node script exists
23
+ if [[ ! -f "$NODE_SCRIPT" ]]; then
24
+ exit 0
25
+ fi
26
+
27
+ # Pipe stdin to the Node.js script (suppress stderr noise from nvm/shell init)
28
+ cat | node "$NODE_SCRIPT" 2>/dev/null
29
+
30
+ # Always exit 0 to allow the prompt through
31
+ exit 0