pikakit 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.
Files changed (145) hide show
  1. package/README.md +239 -0
  2. package/bin/add-skill-kit.js +3 -0
  3. package/bin/cli.mjs +6 -0
  4. package/bin/kit.mjs +89 -0
  5. package/bin/lib/agents.js +208 -0
  6. package/bin/lib/commands/analyze.js +70 -0
  7. package/bin/lib/commands/cache.js +65 -0
  8. package/bin/lib/commands/doctor.js +75 -0
  9. package/bin/lib/commands/help.js +155 -0
  10. package/bin/lib/commands/info.js +38 -0
  11. package/bin/lib/commands/init.js +39 -0
  12. package/bin/lib/commands/install.js +803 -0
  13. package/bin/lib/commands/list.js +43 -0
  14. package/bin/lib/commands/lock.js +57 -0
  15. package/bin/lib/commands/uninstall.js +307 -0
  16. package/bin/lib/commands/update.js +55 -0
  17. package/bin/lib/commands/validate.js +69 -0
  18. package/bin/lib/commands/verify.js +56 -0
  19. package/bin/lib/config.js +81 -0
  20. package/bin/lib/helpers.js +196 -0
  21. package/bin/lib/helpers.test.js +60 -0
  22. package/bin/lib/installer.js +164 -0
  23. package/bin/lib/skills.js +119 -0
  24. package/bin/lib/skills.test.js +109 -0
  25. package/bin/lib/types.js +82 -0
  26. package/bin/lib/ui.js +329 -0
  27. package/lib/agent-cli/README.md +21 -0
  28. package/lib/agent-cli/__tests__/adaptive_engine.test.js +190 -0
  29. package/lib/agent-cli/__tests__/integration/cross_script.test.js +222 -0
  30. package/lib/agent-cli/__tests__/integration/full_cycle.test.js +230 -0
  31. package/lib/agent-cli/__tests__/pattern_analyzer.test.js +173 -0
  32. package/lib/agent-cli/__tests__/pre_execution_check.test.js +167 -0
  33. package/lib/agent-cli/__tests__/skill_injector.test.js +191 -0
  34. package/lib/agent-cli/bin/agent.js +191 -0
  35. package/lib/agent-cli/dashboard/dashboard_server.js +340 -0
  36. package/lib/agent-cli/dashboard/index.html +538 -0
  37. package/lib/agent-cli/lib/audit.js +154 -0
  38. package/lib/agent-cli/lib/audit.test.js +100 -0
  39. package/lib/agent-cli/lib/auto-learn.js +319 -0
  40. package/lib/agent-cli/lib/backup.js +138 -0
  41. package/lib/agent-cli/lib/backup.test.js +78 -0
  42. package/lib/agent-cli/lib/cognitive-lesson.js +476 -0
  43. package/lib/agent-cli/lib/completion.js +149 -0
  44. package/lib/agent-cli/lib/config.js +35 -0
  45. package/lib/agent-cli/lib/eslint-fix.js +238 -0
  46. package/lib/agent-cli/lib/evolution-signal.js +215 -0
  47. package/lib/agent-cli/lib/export.js +86 -0
  48. package/lib/agent-cli/lib/export.test.js +65 -0
  49. package/lib/agent-cli/lib/fix.js +337 -0
  50. package/lib/agent-cli/lib/fix.test.js +80 -0
  51. package/lib/agent-cli/lib/gemini-export.js +83 -0
  52. package/lib/agent-cli/lib/generate-registry.js +42 -0
  53. package/lib/agent-cli/lib/hooks/install-hooks.js +152 -0
  54. package/lib/agent-cli/lib/hooks/lint-learn.js +172 -0
  55. package/lib/agent-cli/lib/ignore.js +116 -0
  56. package/lib/agent-cli/lib/ignore.test.js +58 -0
  57. package/lib/agent-cli/lib/init.js +124 -0
  58. package/lib/agent-cli/lib/learn.js +255 -0
  59. package/lib/agent-cli/lib/learn.test.js +70 -0
  60. package/lib/agent-cli/lib/migrate-to-v4.js +322 -0
  61. package/lib/agent-cli/lib/proposals.js +199 -0
  62. package/lib/agent-cli/lib/proposals.test.js +56 -0
  63. package/lib/agent-cli/lib/recall.js +820 -0
  64. package/lib/agent-cli/lib/recall.test.js +107 -0
  65. package/lib/agent-cli/lib/selfevolution-bridge.js +167 -0
  66. package/lib/agent-cli/lib/settings.js +227 -0
  67. package/lib/agent-cli/lib/skill-learn.js +296 -0
  68. package/lib/agent-cli/lib/stats.js +132 -0
  69. package/lib/agent-cli/lib/stats.test.js +94 -0
  70. package/lib/agent-cli/lib/types.js +33 -0
  71. package/lib/agent-cli/lib/ui/audit-ui.js +146 -0
  72. package/lib/agent-cli/lib/ui/backup-ui.js +107 -0
  73. package/lib/agent-cli/lib/ui/clack-helpers.js +317 -0
  74. package/lib/agent-cli/lib/ui/common.js +83 -0
  75. package/lib/agent-cli/lib/ui/completion-ui.js +126 -0
  76. package/lib/agent-cli/lib/ui/custom-select.js +69 -0
  77. package/lib/agent-cli/lib/ui/dashboard-ui.js +222 -0
  78. package/lib/agent-cli/lib/ui/evolution-signals-ui.js +107 -0
  79. package/lib/agent-cli/lib/ui/export-ui.js +94 -0
  80. package/lib/agent-cli/lib/ui/fix-all-ui.js +191 -0
  81. package/lib/agent-cli/lib/ui/help-ui.js +49 -0
  82. package/lib/agent-cli/lib/ui/index.js +199 -0
  83. package/lib/agent-cli/lib/ui/init-ui.js +56 -0
  84. package/lib/agent-cli/lib/ui/knowledge-ui.js +55 -0
  85. package/lib/agent-cli/lib/ui/learn-ui.js +706 -0
  86. package/lib/agent-cli/lib/ui/lessons-ui.js +148 -0
  87. package/lib/agent-cli/lib/ui/pretty.js +145 -0
  88. package/lib/agent-cli/lib/ui/proposals-ui.js +99 -0
  89. package/lib/agent-cli/lib/ui/recall-ui.js +342 -0
  90. package/lib/agent-cli/lib/ui/routing-demo.js +79 -0
  91. package/lib/agent-cli/lib/ui/routing-ui.js +325 -0
  92. package/lib/agent-cli/lib/ui/settings-ui.js +381 -0
  93. package/lib/agent-cli/lib/ui/stats-ui.js +123 -0
  94. package/lib/agent-cli/lib/ui/watch-ui.js +236 -0
  95. package/lib/agent-cli/lib/watcher.js +181 -0
  96. package/lib/agent-cli/lib/watcher.test.js +85 -0
  97. package/lib/agent-cli/package.json +51 -0
  98. package/lib/agent-cli/scripts/adaptive_engine.js +381 -0
  99. package/lib/agent-cli/scripts/dashboard_server.js +224 -0
  100. package/lib/agent-cli/scripts/error_sensor.js +565 -0
  101. package/lib/agent-cli/scripts/learn_from_failure.js +225 -0
  102. package/lib/agent-cli/scripts/pattern_analyzer.js +781 -0
  103. package/lib/agent-cli/scripts/pre_execution_check.js +623 -0
  104. package/lib/agent-cli/scripts/rule_sharing.js +374 -0
  105. package/lib/agent-cli/scripts/skill_injector.js +387 -0
  106. package/lib/agent-cli/scripts/success_sensor.js +500 -0
  107. package/lib/agent-cli/scripts/user_correction_sensor.js +426 -0
  108. package/lib/agent-cli/services/auto-learn-service.js +247 -0
  109. package/lib/agent-cli/src/MIGRATION.md +418 -0
  110. package/lib/agent-cli/src/README.md +367 -0
  111. package/lib/agent-cli/src/core/evolution/evolution-signal.js +42 -0
  112. package/lib/agent-cli/src/core/evolution/index.js +17 -0
  113. package/lib/agent-cli/src/core/evolution/review-gate.js +40 -0
  114. package/lib/agent-cli/src/core/evolution/signal-detector.js +137 -0
  115. package/lib/agent-cli/src/core/evolution/signal-queue.js +79 -0
  116. package/lib/agent-cli/src/core/evolution/threshold-checker.js +79 -0
  117. package/lib/agent-cli/src/core/index.js +15 -0
  118. package/lib/agent-cli/src/core/learning/cognitive-enhancer.js +282 -0
  119. package/lib/agent-cli/src/core/learning/index.js +12 -0
  120. package/lib/agent-cli/src/core/learning/lesson-synthesizer.js +83 -0
  121. package/lib/agent-cli/src/core/scanning/index.js +14 -0
  122. package/lib/agent-cli/src/data/index.js +13 -0
  123. package/lib/agent-cli/src/data/repositories/index.js +8 -0
  124. package/lib/agent-cli/src/data/repositories/lesson-repository.js +130 -0
  125. package/lib/agent-cli/src/data/repositories/signal-repository.js +119 -0
  126. package/lib/agent-cli/src/data/storage/index.js +8 -0
  127. package/lib/agent-cli/src/data/storage/json-storage.js +64 -0
  128. package/lib/agent-cli/src/data/storage/yaml-storage.js +66 -0
  129. package/lib/agent-cli/src/infrastructure/index.js +13 -0
  130. package/lib/agent-cli/src/presentation/formatters/skill-formatter.js +232 -0
  131. package/lib/agent-cli/src/services/export-service.js +162 -0
  132. package/lib/agent-cli/src/services/index.js +13 -0
  133. package/lib/agent-cli/src/services/learning-service.js +99 -0
  134. package/lib/agent-cli/types/index.d.ts +343 -0
  135. package/lib/agent-cli/utils/benchmark.js +269 -0
  136. package/lib/agent-cli/utils/logger.js +303 -0
  137. package/lib/agent-cli/utils/ml_patterns.js +300 -0
  138. package/lib/agent-cli/utils/recovery.js +312 -0
  139. package/lib/agent-cli/utils/telemetry.js +290 -0
  140. package/lib/agentskillskit-cli/README.md +21 -0
  141. package/lib/agentskillskit-cli/ag-smart.js +158 -0
  142. package/lib/agentskillskit-cli/package.json +51 -0
  143. package/package.json +79 -0
  144. package/specs/ADD_SKILL_SPEC.md +333 -0
  145. package/specs/REGISTRY_V2_SPEC.md +334 -0
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @fileoverview Tests for audit.js functionality
3
+ */
4
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import os from "os";
8
+
9
+ const TEST_DIR = path.join(os.tmpdir(), "agent-skill-kit-audit-test");
10
+ const AGENT_DIR = path.join(TEST_DIR, ".agent");
11
+
12
+ describe("Audit - Governance Check", () => {
13
+ beforeEach(() => {
14
+ fs.mkdirSync(AGENT_DIR, { recursive: true });
15
+ });
16
+
17
+ afterEach(() => {
18
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
19
+ });
20
+
21
+ it("detects GEMINI.md presence", () => {
22
+ const geminiPath = path.join(AGENT_DIR, "GEMINI.md");
23
+
24
+ // Before creation
25
+ expect(fs.existsSync(geminiPath)).toBe(false);
26
+
27
+ // After creation
28
+ fs.writeFileSync(geminiPath, "# Test", "utf8");
29
+ expect(fs.existsSync(geminiPath)).toBe(true);
30
+ });
31
+
32
+ it("detects ARCHITECTURE.md presence", () => {
33
+ const archPath = path.join(AGENT_DIR, "ARCHITECTURE.md");
34
+ fs.writeFileSync(archPath, "# Architecture", "utf8");
35
+
36
+ expect(fs.existsSync(archPath)).toBe(true);
37
+ });
38
+
39
+ it("counts skills in skills directory", () => {
40
+ const skillsDir = path.join(AGENT_DIR, "skills");
41
+ fs.mkdirSync(skillsDir, { recursive: true });
42
+
43
+ // Create mock skills
44
+ fs.mkdirSync(path.join(skillsDir, "skill-1"));
45
+ fs.mkdirSync(path.join(skillsDir, "skill-2"));
46
+
47
+ const skills = fs.readdirSync(skillsDir).filter(f =>
48
+ fs.statSync(path.join(skillsDir, f)).isDirectory()
49
+ );
50
+
51
+ expect(skills.length).toBe(2);
52
+ });
53
+ });
54
+
55
+ describe("Audit - Compliance Results", () => {
56
+ it("calculates pass/fail status correctly", () => {
57
+ const results = {
58
+ errors: 0,
59
+ warnings: 2,
60
+ total: 2
61
+ };
62
+
63
+ // Errors = 0 means pass
64
+ expect(results.errors === 0).toBe(true);
65
+ });
66
+
67
+ it("fails when errors exist", () => {
68
+ const results = {
69
+ errors: 1,
70
+ warnings: 0,
71
+ total: 1
72
+ };
73
+
74
+ expect(results.errors > 0).toBe(true);
75
+ });
76
+
77
+ it("calculates total correctly", () => {
78
+ const violations = [
79
+ { lesson: { severity: "ERROR" }, matches: [1, 2] },
80
+ { lesson: { severity: "WARNING" }, matches: [1] }
81
+ ];
82
+
83
+ let total = 0;
84
+ let errors = 0;
85
+ let warnings = 0;
86
+
87
+ violations.forEach(v => {
88
+ total += v.matches.length;
89
+ if (v.lesson.severity === "ERROR") {
90
+ errors += v.matches.length;
91
+ } else {
92
+ warnings += v.matches.length;
93
+ }
94
+ });
95
+
96
+ expect(total).toBe(3);
97
+ expect(errors).toBe(2);
98
+ expect(warnings).toBe(1);
99
+ });
100
+ });
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Smart Auto-Learn - True Self-Learning Engine
4
+ *
5
+ * Automatically learns from:
6
+ * 1. ESLint output (runs ESLint and parses)
7
+ * 2. Test failures (runs tests and parses)
8
+ * 3. TypeScript errors (runs tsc and parses)
9
+ *
10
+ * Usage:
11
+ * agent auto-learn # Run all
12
+ * agent auto-learn --eslint # ESLint only
13
+ * agent auto-learn --test # Test failures only
14
+ * agent auto-learn --typescript # TypeScript only
15
+ */
16
+
17
+ import fs from "fs";
18
+ import path from "path";
19
+ import { execSync, spawnSync } from "child_process";
20
+ import { loadKnowledge, saveKnowledge } from "./recall.js";
21
+ import { VERSION } from "./config.js";
22
+
23
+ // ============================================================================
24
+ // ESLINT AUTO-LEARN
25
+ // ============================================================================
26
+
27
+ const ESLINT_PATTERN_MAP = {
28
+ "no-console": { pattern: "console\\.(log|warn|error|info|debug)", message: "Avoid console statements in production" },
29
+ "no-debugger": { pattern: "\\bdebugger\\b", message: "Remove debugger statements" },
30
+ "no-var": { pattern: "\\bvar\\s+\\w", message: "Use const/let instead of var" },
31
+ "eqeqeq": { pattern: "[^!=]==[^=]", message: "Use === instead of ==" },
32
+ "no-eval": { pattern: "\\beval\\s*\\(", message: "Avoid eval() for security" },
33
+ "no-alert": { pattern: "\\balert\\s*\\(", message: "Avoid alert() in production" },
34
+ "no-implicit-globals": { pattern: "^(?!const|let|var|function|class|import|export)", message: "Avoid implicit globals" },
35
+ "prefer-const": { pattern: "\\blet\\s+\\w+\\s*=\\s*[^;]+;(?![\\s\\S]*\\1\\s*=)", message: "Use const for variables that are never reassigned" },
36
+ "no-unused-expressions": { pattern: "^\\s*['\"`]use strict['\"`];?\\s*$", message: "Remove unused expressions" },
37
+ "semi": { pattern: "[^;{}]\\s*$", message: "Missing semicolon" },
38
+ "quotes": { pattern: '(?<![\\w])"(?![^"]*"[,\\]\\}\\)])', message: "Prefer single quotes" },
39
+ "no-empty": { pattern: "\\{\\s*\\}", message: "Empty block statement" },
40
+ "no-extra-semi": { pattern: ";;", message: "Unnecessary semicolon" },
41
+ "no-unreachable": { pattern: "(?:return|throw|break|continue)[^}]*[\\n\\r]+[^}]+", message: "Unreachable code" }
42
+ };
43
+
44
+ function runEslintAutoLearn(projectRoot) {
45
+ console.log("\n🔍 Running ESLint analysis...\n");
46
+
47
+ try {
48
+ // Try to run ESLint with JSON output
49
+ const result = spawnSync("npx", ["eslint", ".", "--format", "json", "--no-error-on-unmatched-pattern"], {
50
+ cwd: projectRoot,
51
+ encoding: "utf8",
52
+ shell: true,
53
+ timeout: 60000
54
+ });
55
+
56
+ if (!result.stdout) {
57
+ console.log(" ℹ️ ESLint not configured or no files to lint.");
58
+ return [];
59
+ }
60
+
61
+ const eslintResults = JSON.parse(result.stdout);
62
+ const ruleViolations = {};
63
+
64
+ eslintResults.forEach(file => {
65
+ if (!file.messages) return;
66
+ file.messages.forEach(msg => {
67
+ if (!msg.ruleId) return;
68
+ if (!ruleViolations[msg.ruleId]) {
69
+ ruleViolations[msg.ruleId] = {
70
+ rule: msg.ruleId,
71
+ count: 0,
72
+ severity: msg.severity === 2 ? "ERROR" : "WARNING",
73
+ sample: msg.message
74
+ };
75
+ }
76
+ ruleViolations[msg.ruleId].count++;
77
+ });
78
+ });
79
+
80
+ return Object.values(ruleViolations).sort((a, b) => b.count - a.count);
81
+ } catch (e) {
82
+ console.log(" ⚠️ ESLint analysis skipped:", e.message);
83
+ return [];
84
+ }
85
+ }
86
+
87
+ // ============================================================================
88
+ // TEST FAILURE AUTO-LEARN
89
+ // ============================================================================
90
+
91
+ const TEST_PATTERN_MAP = {
92
+ "undefined is not a function": { pattern: "\\w+\\s*\\(", message: "Function may be undefined before call" },
93
+ "cannot read property": { pattern: "\\w+\\.\\w+", message: "Object property access may fail if undefined" },
94
+ "null is not an object": { pattern: "\\.\\w+", message: "Null check needed before property access" },
95
+ "expected.*to equal": { pattern: "expect\\s*\\(", message: "Assertion expectation mismatch" },
96
+ "timeout": { pattern: "async|await|Promise", message: "Async operation may need longer timeout" },
97
+ "not defined": { pattern: "\\b\\w+\\b", message: "Variable may not be defined in scope" }
98
+ };
99
+
100
+ function runTestAutoLearn(projectRoot) {
101
+ console.log("\n🧪 Running test analysis...\n");
102
+
103
+ try {
104
+ // Try common test runners
105
+ const testCommands = [
106
+ { cmd: "npm", args: ["test", "--", "--json", "--passWithNoTests"], name: "npm test" },
107
+ { cmd: "npx", args: ["vitest", "run", "--reporter=json"], name: "vitest" },
108
+ { cmd: "npx", args: ["jest", "--json", "--passWithNoTests"], name: "jest" }
109
+ ];
110
+
111
+ for (const tc of testCommands) {
112
+ const result = spawnSync(tc.cmd, tc.args, {
113
+ cwd: projectRoot,
114
+ encoding: "utf8",
115
+ shell: true,
116
+ timeout: 120000
117
+ });
118
+
119
+ // Look for test failures in output
120
+ const output = result.stdout + result.stderr;
121
+ const failures = [];
122
+
123
+ // Parse failure messages
124
+ const failurePatterns = [
125
+ /FAIL\s+(.+)/g,
126
+ /✕\s+(.+)/g,
127
+ /Error:\s+(.+)/g,
128
+ /AssertionError:\s+(.+)/g
129
+ ];
130
+
131
+ failurePatterns.forEach(regex => {
132
+ let match;
133
+ while ((match = regex.exec(output)) !== null) {
134
+ failures.push(match[1].trim());
135
+ }
136
+ });
137
+
138
+ if (failures.length > 0) {
139
+ console.log(` Found ${failures.length} test failure(s) from ${tc.name}`);
140
+ return failures.map(f => ({ message: f, source: tc.name }));
141
+ }
142
+ }
143
+
144
+ console.log(" ✅ All tests passing or no tests found.");
145
+ return [];
146
+ } catch (e) {
147
+ console.log(" ⚠️ Test analysis skipped:", e.message);
148
+ return [];
149
+ }
150
+ }
151
+
152
+ // ============================================================================
153
+ // TYPESCRIPT ERROR AUTO-LEARN
154
+ // ============================================================================
155
+
156
+ const TS_PATTERN_MAP = {
157
+ "TS2304": { pattern: "\\b\\w+\\b", message: "TypeScript: Cannot find name" },
158
+ "TS2322": { pattern: ":\\s*\\w+", message: "TypeScript: Type mismatch" },
159
+ "TS2345": { pattern: "\\(.*\\)", message: "TypeScript: Argument type mismatch" },
160
+ "TS2339": { pattern: "\\.\\w+", message: "TypeScript: Property does not exist" },
161
+ "TS7006": { pattern: "\\(\\w+\\)", message: "TypeScript: Parameter implicitly has 'any' type" },
162
+ "TS2531": { pattern: "\\w+\\.", message: "TypeScript: Object is possibly 'null'" },
163
+ "TS2532": { pattern: "\\w+\\.", message: "TypeScript: Object is possibly 'undefined'" }
164
+ };
165
+
166
+ function runTypescriptAutoLearn(projectRoot) {
167
+ console.log("\n📘 Running TypeScript analysis...\n");
168
+
169
+ try {
170
+ const result = spawnSync("npx", ["tsc", "--noEmit", "--pretty", "false"], {
171
+ cwd: projectRoot,
172
+ encoding: "utf8",
173
+ shell: true,
174
+ timeout: 60000
175
+ });
176
+
177
+ const output = result.stdout + result.stderr;
178
+ const errors = {};
179
+
180
+ // Parse TS errors: file(line,col): error TS1234: message
181
+ const tsErrorRegex = /error (TS\d+):\s*(.+)/g;
182
+ let match;
183
+
184
+ while ((match = tsErrorRegex.exec(output)) !== null) {
185
+ const code = match[1];
186
+ const message = match[2];
187
+
188
+ if (!errors[code]) {
189
+ errors[code] = { code, message, count: 0 };
190
+ }
191
+ errors[code].count++;
192
+ }
193
+
194
+ const errorList = Object.values(errors).sort((a, b) => b.count - a.count);
195
+
196
+ if (errorList.length > 0) {
197
+ console.log(` Found ${errorList.length} unique TypeScript error type(s)`);
198
+ } else {
199
+ console.log(" ✅ No TypeScript errors found.");
200
+ }
201
+
202
+ return errorList;
203
+ } catch (e) {
204
+ console.log(" ⚠️ TypeScript analysis skipped:", e.message);
205
+ return [];
206
+ }
207
+ }
208
+
209
+ // ============================================================================
210
+ // MAIN AUTO-LEARN ENGINE
211
+ // ============================================================================
212
+
213
+ function autoLearn(projectRoot, options = {}) {
214
+ console.log(`\n🧠 Smart Auto-Learn Engine v${VERSION}`);
215
+ console.log(`📂 Project: ${projectRoot}\n`);
216
+ console.log("─".repeat(50));
217
+
218
+ const db = loadKnowledge();
219
+ let totalAdded = 0;
220
+
221
+ // ESLint
222
+ if (!options.onlyTest && !options.onlyTypescript) {
223
+ const eslintViolations = runEslintAutoLearn(projectRoot);
224
+
225
+ eslintViolations.forEach(v => {
226
+ const mapping = ESLINT_PATTERN_MAP[v.rule];
227
+ if (!mapping) return;
228
+
229
+ // Check if already exists
230
+ if (db.lessons.some(l => l.pattern === mapping.pattern)) return;
231
+
232
+ const id = `AUTO-${String(db.lessons.length + 1).padStart(3, "0")}`;
233
+ db.lessons.push({
234
+ id,
235
+ pattern: mapping.pattern,
236
+ message: `${mapping.message} (ESLint: ${v.rule})`,
237
+ severity: v.severity,
238
+ source: "auto-eslint",
239
+ hitCount: v.count,
240
+ autoEscalated: false,
241
+ addedAt: new Date().toISOString()
242
+ });
243
+ totalAdded++;
244
+ console.log(` ✅ Auto-learned: [${id}] ${v.rule} (${v.count} occurrences)`);
245
+ });
246
+ }
247
+
248
+ // TypeScript
249
+ if (!options.onlyEslint && !options.onlyTest) {
250
+ const tsErrors = runTypescriptAutoLearn(projectRoot);
251
+
252
+ tsErrors.slice(0, 5).forEach(e => { // Top 5 only
253
+ const mapping = TS_PATTERN_MAP[e.code];
254
+ if (!mapping) return;
255
+
256
+ if (db.lessons.some(l => l.message.includes(e.code))) return;
257
+
258
+ const id = `AUTO-${String(db.lessons.length + 1).padStart(3, "0")}`;
259
+ db.lessons.push({
260
+ id,
261
+ pattern: mapping.pattern,
262
+ message: `${mapping.message} (${e.code})`,
263
+ severity: "WARNING",
264
+ source: "auto-typescript",
265
+ hitCount: e.count,
266
+ autoEscalated: false,
267
+ addedAt: new Date().toISOString()
268
+ });
269
+ totalAdded++;
270
+ console.log(` ✅ Auto-learned: [${id}] ${e.code} (${e.count} occurrences)`);
271
+ });
272
+ }
273
+
274
+ // Summary
275
+ console.log("\n" + "─".repeat(50));
276
+
277
+ if (totalAdded > 0) {
278
+ saveKnowledge(db);
279
+ console.log(`\n🎓 Auto-learned ${totalAdded} new pattern(s)!`);
280
+ console.log(`📊 Total lessons in memory: ${db.lessons.length}\n`);
281
+ } else {
282
+ console.log("\n✅ No new patterns discovered. Code looks clean!\n");
283
+ }
284
+
285
+ return totalAdded;
286
+ }
287
+
288
+ // ============================================================================
289
+ // CLI
290
+ // ============================================================================
291
+
292
+ const args = process.argv.slice(2);
293
+ const projectRoot = process.cwd();
294
+
295
+ if (args.includes("--help")) {
296
+ console.log(`
297
+ 🧠 Smart Auto-Learn - True Self-Learning Engine
298
+
299
+ Usage:
300
+ agent auto-learn Run all analyzers
301
+ agent auto-learn --eslint ESLint only
302
+ agent auto-learn --typescript TypeScript only
303
+ agent auto-learn --test Test failures only
304
+
305
+ The engine automatically:
306
+ 1. Runs ESLint and learns from violations
307
+ 2. Runs TypeScript and learns from type errors
308
+ 3. Runs tests and learns from failures
309
+
310
+ Patterns are automatically added to knowledge base!
311
+ `);
312
+ process.exit(0);
313
+ }
314
+
315
+ autoLearn(projectRoot, {
316
+ onlyEslint: args.includes("--eslint"),
317
+ onlyTypescript: args.includes("--typescript"),
318
+ onlyTest: args.includes("--test")
319
+ });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * @fileoverview Backup and Restore for Agent Skill Kit
3
+ * Protects lessons before changes
4
+ */
5
+
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import { KNOWLEDGE_DIR, LESSONS_PATH } from "./config.js";
9
+ import { SETTINGS_PATH } from "./settings.js";
10
+
11
+ /** Backup directory */
12
+ const BACKUPS_DIR = path.join(KNOWLEDGE_DIR, "backups");
13
+
14
+ /**
15
+ * Create a timestamped backup of lessons and settings
16
+ * @returns {{ path: string, timestamp: string } | null}
17
+ */
18
+ export function createBackup() {
19
+ try {
20
+ fs.mkdirSync(BACKUPS_DIR, { recursive: true });
21
+
22
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
23
+ const backupDir = path.join(BACKUPS_DIR, timestamp);
24
+ fs.mkdirSync(backupDir, { recursive: true });
25
+
26
+ // Backup lessons
27
+ if (fs.existsSync(LESSONS_PATH)) {
28
+ fs.copyFileSync(
29
+ LESSONS_PATH,
30
+ path.join(backupDir, "lessons-learned.yaml")
31
+ );
32
+ }
33
+
34
+ // Backup settings
35
+ if (fs.existsSync(SETTINGS_PATH)) {
36
+ fs.copyFileSync(
37
+ SETTINGS_PATH,
38
+ path.join(backupDir, "settings.yaml")
39
+ );
40
+ }
41
+
42
+ return { path: backupDir, timestamp };
43
+ } catch (e) {
44
+ console.error("Failed to create backup:", e.message);
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * List available backups
51
+ * @returns {Array<{ name: string, date: Date, path: string }>}
52
+ */
53
+ export function listBackups() {
54
+ try {
55
+ if (!fs.existsSync(BACKUPS_DIR)) {
56
+ return [];
57
+ }
58
+
59
+ const entries = fs.readdirSync(BACKUPS_DIR, { withFileTypes: true });
60
+ return entries
61
+ .filter(e => e.isDirectory())
62
+ .map(e => ({
63
+ name: e.name,
64
+ date: parseBackupDate(e.name),
65
+ path: path.join(BACKUPS_DIR, e.name)
66
+ }))
67
+ .sort((a, b) => b.date - a.date); // Newest first
68
+ } catch (e) {
69
+ return [];
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Parse backup folder name to date
75
+ * @param {string} name - Folder name (ISO timestamp with - instead of :)
76
+ * @returns {Date}
77
+ */
78
+ function parseBackupDate(name) {
79
+ try {
80
+ // Convert 2026-01-25T17-30-00-000Z back to valid ISO
81
+ const iso = name.replace(/-(\d{2})-(\d{2})-(\d{3})Z/, ":$1:$2.$3Z");
82
+ return new Date(iso);
83
+ } catch (e) {
84
+ return new Date(0);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Restore from a backup
90
+ * @param {string} backupPath - Path to backup folder
91
+ * @returns {boolean}
92
+ */
93
+ export function restoreBackup(backupPath) {
94
+ try {
95
+ const lessonsBackup = path.join(backupPath, "lessons-learned.yaml");
96
+ const settingsBackup = path.join(backupPath, "settings.yaml");
97
+
98
+ if (fs.existsSync(lessonsBackup)) {
99
+ fs.copyFileSync(lessonsBackup, LESSONS_PATH);
100
+ }
101
+
102
+ if (fs.existsSync(settingsBackup)) {
103
+ fs.copyFileSync(settingsBackup, SETTINGS_PATH);
104
+ }
105
+
106
+ return true;
107
+ } catch (e) {
108
+ console.error("Failed to restore backup:", e.message);
109
+ return false;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Delete old backups, keep last N
115
+ * @param {number} keep - Number of backups to keep
116
+ */
117
+ export function pruneBackups(keep = 5) {
118
+ const backups = listBackups();
119
+
120
+ if (backups.length <= keep) return;
121
+
122
+ const toDelete = backups.slice(keep);
123
+ for (const backup of toDelete) {
124
+ try {
125
+ fs.rmSync(backup.path, { recursive: true, force: true });
126
+ } catch (e) {
127
+ // Ignore deletion errors
128
+ }
129
+ }
130
+ }
131
+
132
+ export default {
133
+ createBackup,
134
+ listBackups,
135
+ restoreBackup,
136
+ pruneBackups,
137
+ BACKUPS_DIR
138
+ };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @fileoverview Tests for backup module
3
+ */
4
+
5
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import os from "os";
9
+
10
+ describe("backup", () => {
11
+ const testDir = path.join(os.tmpdir(), "test-backup-" + Date.now());
12
+
13
+ beforeEach(() => {
14
+ fs.mkdirSync(testDir, { recursive: true });
15
+ });
16
+
17
+ afterEach(() => {
18
+ if (fs.existsSync(testDir)) {
19
+ fs.rmSync(testDir, { recursive: true, force: true });
20
+ }
21
+ });
22
+
23
+ describe("backup file format", () => {
24
+ it("creates timestamped filename", () => {
25
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
26
+ const filename = `backup-${timestamp}.yaml`;
27
+
28
+ expect(filename).toMatch(/^backup-\d{4}-\d{2}-\d{2}/);
29
+ });
30
+
31
+ it("backup contains valid YAML", () => {
32
+ const backupContent = `lessons:\n - id: TEST\n pattern: "x"`;
33
+ const backupPath = path.join(testDir, "backup.yaml");
34
+ fs.writeFileSync(backupPath, backupContent);
35
+
36
+ expect(fs.existsSync(backupPath)).toBe(true);
37
+ expect(fs.readFileSync(backupPath, "utf8")).toContain("lessons:");
38
+ });
39
+ });
40
+
41
+ describe("listBackups", () => {
42
+ it("returns empty array when no backups", () => {
43
+ const backupDir = path.join(testDir, "backups");
44
+ fs.mkdirSync(backupDir, { recursive: true });
45
+
46
+ const files = fs.readdirSync(backupDir);
47
+ expect(files).toHaveLength(0);
48
+ });
49
+
50
+ it("lists backup files", () => {
51
+ const backupDir = path.join(testDir, "backups");
52
+ fs.mkdirSync(backupDir, { recursive: true });
53
+ fs.writeFileSync(path.join(backupDir, "backup-2024.yaml"), "test");
54
+
55
+ const files = fs.readdirSync(backupDir);
56
+ expect(files).toHaveLength(1);
57
+ });
58
+ });
59
+
60
+ describe("pruneBackups", () => {
61
+ it("keeps specified number of backups", () => {
62
+ const backupDir = path.join(testDir, "backups");
63
+ fs.mkdirSync(backupDir, { recursive: true });
64
+
65
+ // Create 5 backups
66
+ for (let i = 1; i <= 5; i++) {
67
+ fs.writeFileSync(path.join(backupDir, `backup-${i}.yaml`), "test");
68
+ }
69
+
70
+ // Simulate pruning to keep 2
71
+ const files = fs.readdirSync(backupDir).sort().reverse();
72
+ const toDelete = files.slice(2);
73
+ toDelete.forEach(f => fs.unlinkSync(path.join(backupDir, f)));
74
+
75
+ expect(fs.readdirSync(backupDir)).toHaveLength(2);
76
+ });
77
+ });
78
+ });