add-skill-kit 3.2.2 → 3.2.4
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/bin/lib/commands/install.js +67 -45
- package/lib/agent-cli/README.md +21 -0
- package/lib/agent-cli/bin/ag-smart.js +158 -0
- package/lib/agent-cli/lib/audit.js +154 -0
- package/lib/agent-cli/lib/audit.test.js +100 -0
- package/lib/agent-cli/lib/auto-learn.js +319 -0
- package/lib/agent-cli/lib/auto_preview.py +148 -0
- package/lib/agent-cli/lib/backup.js +138 -0
- package/lib/agent-cli/lib/backup.test.js +78 -0
- package/lib/agent-cli/lib/checklist.py +222 -0
- package/lib/agent-cli/lib/cognitive-lesson.js +476 -0
- package/lib/agent-cli/lib/completion.js +149 -0
- package/lib/agent-cli/lib/config.js +35 -0
- package/lib/agent-cli/lib/eslint-fix.js +238 -0
- package/lib/agent-cli/lib/evolution-signal.js +215 -0
- package/lib/agent-cli/lib/export.js +86 -0
- package/lib/agent-cli/lib/export.test.js +65 -0
- package/lib/agent-cli/lib/fix.js +337 -0
- package/lib/agent-cli/lib/fix.test.js +80 -0
- package/lib/agent-cli/lib/gemini-export.js +83 -0
- package/lib/agent-cli/lib/generate-registry.js +42 -0
- package/lib/agent-cli/lib/hooks/install-hooks.js +152 -0
- package/lib/agent-cli/lib/hooks/lint-learn.js +172 -0
- package/lib/agent-cli/lib/ignore.js +116 -0
- package/lib/agent-cli/lib/ignore.test.js +58 -0
- package/lib/agent-cli/lib/init.js +124 -0
- package/lib/agent-cli/lib/learn.js +255 -0
- package/lib/agent-cli/lib/learn.test.js +70 -0
- package/lib/agent-cli/lib/migrate-to-v4.js +322 -0
- package/lib/agent-cli/lib/proposals.js +199 -0
- package/lib/agent-cli/lib/proposals.test.js +56 -0
- package/lib/agent-cli/lib/recall.js +820 -0
- package/lib/agent-cli/lib/recall.test.js +107 -0
- package/lib/agent-cli/lib/selfevolution-bridge.js +167 -0
- package/lib/agent-cli/lib/session_manager.py +120 -0
- package/lib/agent-cli/lib/settings.js +203 -0
- package/lib/agent-cli/lib/skill-learn.js +296 -0
- package/lib/agent-cli/lib/stats.js +132 -0
- package/lib/agent-cli/lib/stats.test.js +94 -0
- package/lib/agent-cli/lib/types.js +33 -0
- package/lib/agent-cli/lib/ui/audit-ui.js +146 -0
- package/lib/agent-cli/lib/ui/backup-ui.js +107 -0
- package/lib/agent-cli/lib/ui/clack-helpers.js +317 -0
- package/lib/agent-cli/lib/ui/common.js +83 -0
- package/lib/agent-cli/lib/ui/completion-ui.js +126 -0
- package/lib/agent-cli/lib/ui/custom-select.js +69 -0
- package/lib/agent-cli/lib/ui/dashboard-ui.js +123 -0
- package/lib/agent-cli/lib/ui/evolution-signals-ui.js +107 -0
- package/lib/agent-cli/lib/ui/export-ui.js +94 -0
- package/lib/agent-cli/lib/ui/fix-all-ui.js +191 -0
- package/lib/agent-cli/lib/ui/help-ui.js +49 -0
- package/lib/agent-cli/lib/ui/index.js +169 -0
- package/lib/agent-cli/lib/ui/init-ui.js +56 -0
- package/lib/agent-cli/lib/ui/knowledge-ui.js +55 -0
- package/lib/agent-cli/lib/ui/learn-ui.js +706 -0
- package/lib/agent-cli/lib/ui/lessons-ui.js +148 -0
- package/lib/agent-cli/lib/ui/pretty.js +145 -0
- package/lib/agent-cli/lib/ui/proposals-ui.js +99 -0
- package/lib/agent-cli/lib/ui/recall-ui.js +342 -0
- package/lib/agent-cli/lib/ui/routing-demo.js +79 -0
- package/lib/agent-cli/lib/ui/routing-ui.js +325 -0
- package/lib/agent-cli/lib/ui/settings-ui.js +381 -0
- package/lib/agent-cli/lib/ui/stats-ui.js +123 -0
- package/lib/agent-cli/lib/ui/watch-ui.js +236 -0
- package/lib/agent-cli/lib/verify_all.py +327 -0
- package/lib/agent-cli/lib/watcher.js +181 -0
- package/lib/agent-cli/lib/watcher.test.js +85 -0
- package/lib/agent-cli/package.json +51 -0
- package/lib/agentskillskit-cli/README.md +21 -0
- package/lib/agentskillskit-cli/ag-smart.js +158 -0
- package/lib/agentskillskit-cli/package.json +51 -0
- package/package.json +11 -6
|
@@ -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
|
+
* ag-smart auto-learn # Run all
|
|
12
|
+
* ag-smart auto-learn --eslint # ESLint only
|
|
13
|
+
* ag-smart auto-learn --test # Test failures only
|
|
14
|
+
* ag-smart 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
|
+
ag-smart auto-learn Run all analyzers
|
|
301
|
+
ag-smart auto-learn --eslint ESLint only
|
|
302
|
+
ag-smart auto-learn --typescript TypeScript only
|
|
303
|
+
ag-smart 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,148 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Auto Preview - Agent Skill Kit
|
|
4
|
+
==============================
|
|
5
|
+
Manages (start/stop/status) the local development server for previewing the application.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
python .agent/scripts/auto_preview.py start [port]
|
|
9
|
+
python .agent/scripts/auto_preview.py stop
|
|
10
|
+
python .agent/scripts/auto_preview.py status
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
import json
|
|
17
|
+
import signal
|
|
18
|
+
import argparse
|
|
19
|
+
import subprocess
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
AGENT_DIR = Path(".agent")
|
|
23
|
+
PID_FILE = AGENT_DIR / "preview.pid"
|
|
24
|
+
LOG_FILE = AGENT_DIR / "preview.log"
|
|
25
|
+
|
|
26
|
+
def get_project_root():
|
|
27
|
+
return Path(".").resolve()
|
|
28
|
+
|
|
29
|
+
def is_running(pid):
|
|
30
|
+
try:
|
|
31
|
+
os.kill(pid, 0)
|
|
32
|
+
return True
|
|
33
|
+
except OSError:
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
def get_start_command(root):
|
|
37
|
+
pkg_file = root / "package.json"
|
|
38
|
+
if not pkg_file.exists():
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
with open(pkg_file, 'r') as f:
|
|
42
|
+
data = json.load(f)
|
|
43
|
+
|
|
44
|
+
scripts = data.get("scripts", {})
|
|
45
|
+
if "dev" in scripts:
|
|
46
|
+
return ["npm", "run", "dev"]
|
|
47
|
+
elif "start" in scripts:
|
|
48
|
+
return ["npm", "start"]
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
def start_server(port=3000):
|
|
52
|
+
if PID_FILE.exists():
|
|
53
|
+
try:
|
|
54
|
+
pid = int(PID_FILE.read_text().strip())
|
|
55
|
+
if is_running(pid):
|
|
56
|
+
print(f"⚠️ Preview already running (PID: {pid})")
|
|
57
|
+
return
|
|
58
|
+
except:
|
|
59
|
+
pass # Invalid PID file
|
|
60
|
+
|
|
61
|
+
root = get_project_root()
|
|
62
|
+
cmd = get_start_command(root)
|
|
63
|
+
|
|
64
|
+
if not cmd:
|
|
65
|
+
print("❌ No 'dev' or 'start' script found in package.json")
|
|
66
|
+
sys.exit(1)
|
|
67
|
+
|
|
68
|
+
# Add port env var if needed (simple heuristic)
|
|
69
|
+
env = os.environ.copy()
|
|
70
|
+
env["PORT"] = str(port)
|
|
71
|
+
|
|
72
|
+
print(f"🚀 Starting preview on port {port}...")
|
|
73
|
+
|
|
74
|
+
with open(LOG_FILE, "w") as log:
|
|
75
|
+
process = subprocess.Popen(
|
|
76
|
+
cmd,
|
|
77
|
+
cwd=str(root),
|
|
78
|
+
stdout=log,
|
|
79
|
+
stderr=log,
|
|
80
|
+
env=env,
|
|
81
|
+
shell=True # Required for npm on windows often, or consistent path handling
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
PID_FILE.write_text(str(process.pid))
|
|
85
|
+
print(f"✅ Preview started! (PID: {process.pid})")
|
|
86
|
+
print(f" Logs: {LOG_FILE}")
|
|
87
|
+
print(f" URL: http://localhost:{port}")
|
|
88
|
+
|
|
89
|
+
def stop_server():
|
|
90
|
+
if not PID_FILE.exists():
|
|
91
|
+
print("ℹ️ No preview server found.")
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
pid = int(PID_FILE.read_text().strip())
|
|
96
|
+
if is_running(pid):
|
|
97
|
+
# Try gentle kill first
|
|
98
|
+
os.kill(pid, signal.SIGTERM) if sys.platform != 'win32' else subprocess.call(['taskkill', '/F', '/T', '/PID', str(pid)])
|
|
99
|
+
print(f"🛑 Preview stopped (PID: {pid})")
|
|
100
|
+
else:
|
|
101
|
+
print("ℹ️ Process was not running.")
|
|
102
|
+
except Exception as e:
|
|
103
|
+
print(f"❌ Error stopping server: {e}")
|
|
104
|
+
finally:
|
|
105
|
+
if PID_FILE.exists():
|
|
106
|
+
PID_FILE.unlink()
|
|
107
|
+
|
|
108
|
+
def status_server():
|
|
109
|
+
running = False
|
|
110
|
+
pid = None
|
|
111
|
+
url = "Unknown"
|
|
112
|
+
|
|
113
|
+
if PID_FILE.exists():
|
|
114
|
+
try:
|
|
115
|
+
pid = int(PID_FILE.read_text().strip())
|
|
116
|
+
if is_running(pid):
|
|
117
|
+
running = True
|
|
118
|
+
# Heuristic for URL, strictly we should save it
|
|
119
|
+
url = "http://localhost:3000"
|
|
120
|
+
except:
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
print("\n=== Preview Status ===")
|
|
124
|
+
if running:
|
|
125
|
+
print(f"✅ Status: Running")
|
|
126
|
+
print(f"🔢 PID: {pid}")
|
|
127
|
+
print(f"🌐 URL: {url} (Likely)")
|
|
128
|
+
print(f"📝 Logs: {LOG_FILE}")
|
|
129
|
+
else:
|
|
130
|
+
print("⚪ Status: Stopped")
|
|
131
|
+
print("===================\n")
|
|
132
|
+
|
|
133
|
+
def main():
|
|
134
|
+
parser = argparse.ArgumentParser()
|
|
135
|
+
parser.add_argument("action", choices=["start", "stop", "status"])
|
|
136
|
+
parser.add_argument("port", nargs="?", default="3000")
|
|
137
|
+
|
|
138
|
+
args = parser.parse_args()
|
|
139
|
+
|
|
140
|
+
if args.action == "start":
|
|
141
|
+
start_server(int(args.port))
|
|
142
|
+
elif args.action == "stop":
|
|
143
|
+
stop_server()
|
|
144
|
+
elif args.action == "status":
|
|
145
|
+
status_server()
|
|
146
|
+
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
main()
|
|
@@ -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
|
+
});
|