@triedotdev/mcp 1.0.50 → 1.0.52
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/README.md +545 -406
- package/dist/agent-smith-BECRZH73.js +12 -0
- package/dist/{agent-smith-runner-3AWGEOZC.js → agent-smith-runner-LZRXM2Q2.js} +7 -7
- package/dist/agent-smith-runner-LZRXM2Q2.js.map +1 -0
- package/dist/{chunk-3SQK2RKF.js → chunk-A43476GB.js} +9 -9
- package/dist/chunk-A43476GB.js.map +1 -0
- package/dist/{chunk-IMFD4SJC.js → chunk-ASGSTVVF.js} +1 -1
- package/dist/chunk-ASGSTVVF.js.map +1 -0
- package/dist/chunk-C3AS5OXW.js +1177 -0
- package/dist/chunk-C3AS5OXW.js.map +1 -0
- package/dist/{chunk-GLC62PGD.js → chunk-KB5ZN6K2.js} +2 -2
- package/dist/{chunk-37U65YW7.js → chunk-TOE75CFZ.js} +1855 -206
- package/dist/chunk-TOE75CFZ.js.map +1 -0
- package/dist/chunk-WCHIJDCD.js +2051 -0
- package/dist/chunk-WCHIJDCD.js.map +1 -0
- package/dist/{chunk-GERAB55E.js → chunk-YKUCIKTU.js} +94 -1259
- package/dist/chunk-YKUCIKTU.js.map +1 -0
- package/dist/cli/create-agent.js +2 -2
- package/dist/cli/main.js +501 -111
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +8 -7
- package/dist/cli/yolo-daemon.js.map +1 -1
- package/dist/comprehension-46F7ZNKL.js +821 -0
- package/dist/comprehension-46F7ZNKL.js.map +1 -0
- package/dist/index.js +457 -131
- package/dist/index.js.map +1 -1
- package/dist/workers/agent-worker.js +10 -11
- package/dist/workers/agent-worker.js.map +1 -1
- package/package.json +3 -1
- package/dist/agent-smith-RVXIMAL6.js +0 -11
- package/dist/agent-smith-runner-3AWGEOZC.js.map +0 -1
- package/dist/chunk-37U65YW7.js.map +0 -1
- package/dist/chunk-3SQK2RKF.js.map +0 -1
- package/dist/chunk-6T7S77U7.js +0 -852
- package/dist/chunk-6T7S77U7.js.map +0 -1
- package/dist/chunk-GERAB55E.js.map +0 -1
- package/dist/chunk-IMFD4SJC.js.map +0 -1
- package/dist/chunk-PZDQIFKO.js +0 -1598
- package/dist/chunk-PZDQIFKO.js.map +0 -1
- /package/dist/{agent-smith-RVXIMAL6.js.map → agent-smith-BECRZH73.js.map} +0 -0
- /package/dist/{chunk-GLC62PGD.js.map → chunk-KB5ZN6K2.js.map} +0 -0
|
@@ -0,0 +1,2051 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Executor,
|
|
3
|
+
Triager
|
|
4
|
+
} from "./chunk-C3AS5OXW.js";
|
|
5
|
+
import {
|
|
6
|
+
getWorkingDirectory
|
|
7
|
+
} from "./chunk-ASGSTVVF.js";
|
|
8
|
+
import {
|
|
9
|
+
Trie
|
|
10
|
+
} from "./chunk-6NLHFIYA.js";
|
|
11
|
+
|
|
12
|
+
// src/cli/checkpoint.ts
|
|
13
|
+
import { existsSync } from "fs";
|
|
14
|
+
import { mkdir, writeFile, readFile } from "fs/promises";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
async function saveCheckpoint(options) {
|
|
17
|
+
const workDir = options.workDir || getWorkingDirectory(void 0, true);
|
|
18
|
+
const trieDir = join(workDir, ".trie");
|
|
19
|
+
const checkpointPath = join(trieDir, "checkpoints.json");
|
|
20
|
+
await mkdir(trieDir, { recursive: true });
|
|
21
|
+
let log = { checkpoints: [] };
|
|
22
|
+
try {
|
|
23
|
+
if (existsSync(checkpointPath)) {
|
|
24
|
+
log = JSON.parse(await readFile(checkpointPath, "utf-8"));
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
log = { checkpoints: [] };
|
|
28
|
+
}
|
|
29
|
+
const checkpoint = {
|
|
30
|
+
id: `cp-${Date.now().toString(36)}`,
|
|
31
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
32
|
+
files: options.files || [],
|
|
33
|
+
createdBy: options.createdBy || "cli"
|
|
34
|
+
};
|
|
35
|
+
if (options.message) checkpoint.message = options.message;
|
|
36
|
+
if (options.notes) checkpoint.notes = options.notes;
|
|
37
|
+
log.checkpoints.push(checkpoint);
|
|
38
|
+
log.lastCheckpoint = checkpoint.id;
|
|
39
|
+
if (log.checkpoints.length > 50) {
|
|
40
|
+
log.checkpoints = log.checkpoints.slice(-50);
|
|
41
|
+
}
|
|
42
|
+
await writeFile(checkpointPath, JSON.stringify(log, null, 2));
|
|
43
|
+
await updateAgentsMdWithCheckpoint(checkpoint, workDir);
|
|
44
|
+
return checkpoint;
|
|
45
|
+
}
|
|
46
|
+
async function listCheckpoints(workDir) {
|
|
47
|
+
const dir = workDir || getWorkingDirectory(void 0, true);
|
|
48
|
+
const checkpointPath = join(dir, ".trie", "checkpoints.json");
|
|
49
|
+
try {
|
|
50
|
+
if (existsSync(checkpointPath)) {
|
|
51
|
+
const log = JSON.parse(await readFile(checkpointPath, "utf-8"));
|
|
52
|
+
return log.checkpoints;
|
|
53
|
+
}
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
async function getLastCheckpoint(workDir) {
|
|
59
|
+
const checkpoints = await listCheckpoints(workDir);
|
|
60
|
+
const last = checkpoints[checkpoints.length - 1];
|
|
61
|
+
return last ?? null;
|
|
62
|
+
}
|
|
63
|
+
async function updateAgentsMdWithCheckpoint(checkpoint, workDir) {
|
|
64
|
+
const agentsPath = join(workDir, ".trie", "AGENTS.md");
|
|
65
|
+
let content = "";
|
|
66
|
+
try {
|
|
67
|
+
if (existsSync(agentsPath)) {
|
|
68
|
+
content = await readFile(agentsPath, "utf-8");
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
content = "";
|
|
72
|
+
}
|
|
73
|
+
const checkpointSection = `
|
|
74
|
+
## Last Checkpoint
|
|
75
|
+
|
|
76
|
+
- **ID:** ${checkpoint.id}
|
|
77
|
+
- **Time:** ${checkpoint.timestamp}
|
|
78
|
+
${checkpoint.message ? `- **Message:** ${checkpoint.message}` : ""}
|
|
79
|
+
${checkpoint.files.length > 0 ? `- **Files:** ${checkpoint.files.length} files` : ""}
|
|
80
|
+
${checkpoint.notes ? `- **Notes:** ${checkpoint.notes}` : ""}
|
|
81
|
+
`;
|
|
82
|
+
const checkpointRegex = /## Last Checkpoint[\s\S]*?(?=\n## |\n---|\Z)/;
|
|
83
|
+
if (checkpointRegex.test(content)) {
|
|
84
|
+
content = content.replace(checkpointRegex, checkpointSection.trim());
|
|
85
|
+
} else {
|
|
86
|
+
content = content.trim() + "\n\n" + checkpointSection.trim() + "\n";
|
|
87
|
+
}
|
|
88
|
+
await writeFile(agentsPath, content);
|
|
89
|
+
}
|
|
90
|
+
async function handleCheckpointCommand(args) {
|
|
91
|
+
const subcommand = args[0] || "save";
|
|
92
|
+
switch (subcommand) {
|
|
93
|
+
case "save": {
|
|
94
|
+
let message;
|
|
95
|
+
let notes;
|
|
96
|
+
const files = [];
|
|
97
|
+
for (let i = 1; i < args.length; i++) {
|
|
98
|
+
const arg = args[i];
|
|
99
|
+
if (arg === "-m" || arg === "--message") {
|
|
100
|
+
message = args[++i] ?? "";
|
|
101
|
+
} else if (arg === "-n" || arg === "--notes") {
|
|
102
|
+
notes = args[++i] ?? "";
|
|
103
|
+
} else if (arg === "-f" || arg === "--file") {
|
|
104
|
+
const file = args[++i];
|
|
105
|
+
if (file) files.push(file);
|
|
106
|
+
} else if (arg && !arg.startsWith("-")) {
|
|
107
|
+
message = arg;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const opts = { files };
|
|
111
|
+
if (message) opts.message = message;
|
|
112
|
+
if (notes) opts.notes = notes;
|
|
113
|
+
const checkpoint = await saveCheckpoint(opts);
|
|
114
|
+
console.log("\n Checkpoint saved\n");
|
|
115
|
+
console.log(` ID: ${checkpoint.id}`);
|
|
116
|
+
console.log(` Time: ${checkpoint.timestamp}`);
|
|
117
|
+
if (checkpoint.message) {
|
|
118
|
+
console.log(` Message: ${checkpoint.message}`);
|
|
119
|
+
}
|
|
120
|
+
if (checkpoint.files.length > 0) {
|
|
121
|
+
console.log(` Files: ${checkpoint.files.join(", ")}`);
|
|
122
|
+
}
|
|
123
|
+
console.log("\n Context saved to .trie/\n");
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
case "list": {
|
|
127
|
+
const checkpoints = await listCheckpoints();
|
|
128
|
+
if (checkpoints.length === 0) {
|
|
129
|
+
console.log("\n No checkpoints yet. Run `trie checkpoint` to save one.\n");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
console.log("\n Checkpoints:\n");
|
|
133
|
+
for (const cp of checkpoints.slice(-10).reverse()) {
|
|
134
|
+
const date = new Date(cp.timestamp).toLocaleString();
|
|
135
|
+
console.log(` ${cp.id} ${date} ${cp.message || "(no message)"}`);
|
|
136
|
+
}
|
|
137
|
+
console.log("");
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case "last": {
|
|
141
|
+
const checkpoint = await getLastCheckpoint();
|
|
142
|
+
if (!checkpoint) {
|
|
143
|
+
console.log("\n No checkpoints yet. Run `trie checkpoint` to save one.\n");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
console.log("\n Last Checkpoint:\n");
|
|
147
|
+
console.log(` ID: ${checkpoint.id}`);
|
|
148
|
+
console.log(` Time: ${new Date(checkpoint.timestamp).toLocaleString()}`);
|
|
149
|
+
if (checkpoint.message) {
|
|
150
|
+
console.log(` Message: ${checkpoint.message}`);
|
|
151
|
+
}
|
|
152
|
+
if (checkpoint.notes) {
|
|
153
|
+
console.log(` Notes: ${checkpoint.notes}`);
|
|
154
|
+
}
|
|
155
|
+
if (checkpoint.files.length > 0) {
|
|
156
|
+
console.log(` Files: ${checkpoint.files.join(", ")}`);
|
|
157
|
+
}
|
|
158
|
+
console.log("");
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
default:
|
|
162
|
+
console.log(`
|
|
163
|
+
Usage: trie checkpoint [command] [options]
|
|
164
|
+
|
|
165
|
+
Commands:
|
|
166
|
+
save [message] Save a checkpoint (default)
|
|
167
|
+
list List recent checkpoints
|
|
168
|
+
last Show the last checkpoint
|
|
169
|
+
|
|
170
|
+
Options:
|
|
171
|
+
-m, --message Checkpoint message
|
|
172
|
+
-n, --notes Additional notes
|
|
173
|
+
-f, --file File to include (can be repeated)
|
|
174
|
+
|
|
175
|
+
Examples:
|
|
176
|
+
trie checkpoint "finished auth flow"
|
|
177
|
+
trie checkpoint save -m "WIP: payment integration" -n "needs testing"
|
|
178
|
+
trie checkpoint list
|
|
179
|
+
`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/bootstrap/stack-detector.ts
|
|
184
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
185
|
+
import { existsSync as existsSync2 } from "fs";
|
|
186
|
+
import { join as join2 } from "path";
|
|
187
|
+
var SKILL_MAPPINGS = {
|
|
188
|
+
// Frontend Frameworks - React/Next.js
|
|
189
|
+
"next": [
|
|
190
|
+
"vercel-labs/agent-skills vercel-react-best-practices",
|
|
191
|
+
"vercel-labs/agent-skills web-design-guidelines",
|
|
192
|
+
"anthropics/skills frontend-design",
|
|
193
|
+
"wshobson/agents nextjs-app-router-patterns"
|
|
194
|
+
],
|
|
195
|
+
"react": [
|
|
196
|
+
"vercel-labs/agent-skills vercel-react-best-practices",
|
|
197
|
+
"anthropics/skills frontend-design",
|
|
198
|
+
"wshobson/agents react-state-management"
|
|
199
|
+
],
|
|
200
|
+
// Vue/Nuxt Ecosystem
|
|
201
|
+
"vue": [
|
|
202
|
+
"hyf0/vue-skills vue-best-practices",
|
|
203
|
+
"hyf0/vue-skills pinia-best-practices",
|
|
204
|
+
"hyf0/vue-skills vueuse-best-practices",
|
|
205
|
+
"onmax/nuxt-skills vue"
|
|
206
|
+
],
|
|
207
|
+
"nuxt": [
|
|
208
|
+
"onmax/nuxt-skills nuxt",
|
|
209
|
+
"onmax/nuxt-skills nuxt-ui",
|
|
210
|
+
"onmax/nuxt-skills nuxt-content",
|
|
211
|
+
"onmax/nuxt-skills nuxt-modules",
|
|
212
|
+
"onmax/nuxt-skills nuxt-better-auth",
|
|
213
|
+
"onmax/nuxt-skills nuxthub"
|
|
214
|
+
],
|
|
215
|
+
"pinia": [
|
|
216
|
+
"hyf0/vue-skills pinia-best-practices"
|
|
217
|
+
],
|
|
218
|
+
"@vueuse/core": [
|
|
219
|
+
"hyf0/vue-skills vueuse-best-practices",
|
|
220
|
+
"onmax/nuxt-skills vueuse"
|
|
221
|
+
],
|
|
222
|
+
// Mobile - Expo
|
|
223
|
+
"expo": [
|
|
224
|
+
"expo/skills building-native-ui",
|
|
225
|
+
"expo/skills upgrading-expo",
|
|
226
|
+
"expo/skills native-data-fetching",
|
|
227
|
+
"expo/skills expo-dev-client",
|
|
228
|
+
"expo/skills expo-deployment",
|
|
229
|
+
"expo/skills expo-api-routes",
|
|
230
|
+
"expo/skills expo-tailwind-setup",
|
|
231
|
+
"expo/skills expo-cicd-workflows",
|
|
232
|
+
"expo/skills use-dom"
|
|
233
|
+
],
|
|
234
|
+
// Mobile - React Native
|
|
235
|
+
"react-native": [
|
|
236
|
+
"callstackincubator/agent-skills react-native-best-practices",
|
|
237
|
+
"wshobson/agents react-native-architecture"
|
|
238
|
+
],
|
|
239
|
+
// Backend Frameworks
|
|
240
|
+
"@nestjs/core": [
|
|
241
|
+
"kadajett/agent-nestjs-skills nestjs-best-practices"
|
|
242
|
+
],
|
|
243
|
+
"nestjs": [
|
|
244
|
+
"kadajett/agent-nestjs-skills nestjs-best-practices"
|
|
245
|
+
],
|
|
246
|
+
"elysia": [
|
|
247
|
+
"elysiajs/skills elysiajs"
|
|
248
|
+
],
|
|
249
|
+
"hono": [
|
|
250
|
+
"elysiajs/skills elysiajs"
|
|
251
|
+
],
|
|
252
|
+
// Database/BaaS
|
|
253
|
+
"@supabase/supabase-js": [
|
|
254
|
+
"supabase/agent-skills supabase-postgres-best-practices"
|
|
255
|
+
],
|
|
256
|
+
"convex": [
|
|
257
|
+
"waynesutton/convexskills convex-best-practices"
|
|
258
|
+
],
|
|
259
|
+
"pg": [
|
|
260
|
+
"wshobson/agents postgresql-table-design"
|
|
261
|
+
],
|
|
262
|
+
"postgres": [
|
|
263
|
+
"wshobson/agents postgresql-table-design"
|
|
264
|
+
],
|
|
265
|
+
// Auth
|
|
266
|
+
"better-auth": [
|
|
267
|
+
"better-auth/skills better-auth-best-practices",
|
|
268
|
+
"better-auth/skills create-auth-skill"
|
|
269
|
+
],
|
|
270
|
+
// Payments
|
|
271
|
+
"stripe": [
|
|
272
|
+
"stripe/ai stripe-best-practices"
|
|
273
|
+
],
|
|
274
|
+
"@stripe/stripe-js": [
|
|
275
|
+
"stripe/ai stripe-best-practices"
|
|
276
|
+
],
|
|
277
|
+
// Media/Graphics
|
|
278
|
+
"remotion": [
|
|
279
|
+
"remotion-dev/skills remotion-best-practices"
|
|
280
|
+
],
|
|
281
|
+
"three": [
|
|
282
|
+
"cloudai-x/threejs-skills threejs-fundamentals",
|
|
283
|
+
"cloudai-x/threejs-skills threejs-animation",
|
|
284
|
+
"cloudai-x/threejs-skills threejs-materials",
|
|
285
|
+
"cloudai-x/threejs-skills threejs-shaders",
|
|
286
|
+
"cloudai-x/threejs-skills threejs-lighting",
|
|
287
|
+
"cloudai-x/threejs-skills threejs-geometry",
|
|
288
|
+
"cloudai-x/threejs-skills threejs-textures",
|
|
289
|
+
"cloudai-x/threejs-skills threejs-loaders",
|
|
290
|
+
"cloudai-x/threejs-skills threejs-interaction",
|
|
291
|
+
"cloudai-x/threejs-skills threejs-postprocessing"
|
|
292
|
+
],
|
|
293
|
+
// UI Libraries
|
|
294
|
+
"tailwindcss": [
|
|
295
|
+
"wshobson/agents tailwind-design-system",
|
|
296
|
+
"jezweb/claude-skills tailwind-v4-shadcn",
|
|
297
|
+
"wshobson/agents responsive-design"
|
|
298
|
+
],
|
|
299
|
+
"@shadcn/ui": [
|
|
300
|
+
"giuseppe-trisciuoglio/developer-kit shadcn-ui"
|
|
301
|
+
],
|
|
302
|
+
"shadcn": [
|
|
303
|
+
"giuseppe-trisciuoglio/developer-kit shadcn-ui"
|
|
304
|
+
],
|
|
305
|
+
"@radix-ui/react-slot": [
|
|
306
|
+
"onmax/nuxt-skills reka-ui"
|
|
307
|
+
],
|
|
308
|
+
// State Management
|
|
309
|
+
"@tanstack/react-query": [
|
|
310
|
+
"jezweb/claude-skills tanstack-query"
|
|
311
|
+
],
|
|
312
|
+
// Testing
|
|
313
|
+
"playwright": [
|
|
314
|
+
"anthropics/skills webapp-testing",
|
|
315
|
+
"wshobson/agents e2e-testing-patterns"
|
|
316
|
+
],
|
|
317
|
+
"puppeteer": [
|
|
318
|
+
"anthropics/skills webapp-testing"
|
|
319
|
+
],
|
|
320
|
+
"vitest": [
|
|
321
|
+
"wshobson/agents e2e-testing-patterns"
|
|
322
|
+
],
|
|
323
|
+
"jest": [
|
|
324
|
+
"wshobson/agents e2e-testing-patterns"
|
|
325
|
+
],
|
|
326
|
+
// DevTools/MCP
|
|
327
|
+
"@modelcontextprotocol/sdk": [
|
|
328
|
+
"anthropics/skills mcp-builder"
|
|
329
|
+
],
|
|
330
|
+
// Security
|
|
331
|
+
"semgrep": [
|
|
332
|
+
"trailofbits/skills semgrep"
|
|
333
|
+
],
|
|
334
|
+
// Monorepos
|
|
335
|
+
"turbo": [
|
|
336
|
+
"wshobson/agents monorepo-management"
|
|
337
|
+
],
|
|
338
|
+
"nx": [
|
|
339
|
+
"wshobson/agents monorepo-management"
|
|
340
|
+
],
|
|
341
|
+
"lerna": [
|
|
342
|
+
"wshobson/agents monorepo-management"
|
|
343
|
+
],
|
|
344
|
+
// TypeScript (handled separately based on tsconfig.json)
|
|
345
|
+
"typescript": [
|
|
346
|
+
"wshobson/agents typescript-advanced-types"
|
|
347
|
+
]
|
|
348
|
+
};
|
|
349
|
+
var SKILL_CATEGORIES = {
|
|
350
|
+
documents: [
|
|
351
|
+
"anthropics/skills pdf",
|
|
352
|
+
"anthropics/skills xlsx",
|
|
353
|
+
"anthropics/skills pptx",
|
|
354
|
+
"anthropics/skills docx",
|
|
355
|
+
"anthropics/skills doc-coauthoring"
|
|
356
|
+
],
|
|
357
|
+
design: [
|
|
358
|
+
"anthropics/skills canvas-design",
|
|
359
|
+
"anthropics/skills theme-factory",
|
|
360
|
+
"anthropics/skills web-artifacts-builder",
|
|
361
|
+
"anthropics/skills algorithmic-art",
|
|
362
|
+
"anthropics/skills brand-guidelines",
|
|
363
|
+
"anthropics/skills slack-gif-creator",
|
|
364
|
+
"nextlevelbuilder/ui-ux-pro-max ui-ux-pro-max",
|
|
365
|
+
"superdesigndev/superdesign-skill superdesign",
|
|
366
|
+
"wshobson/agents design-system-patterns"
|
|
367
|
+
],
|
|
368
|
+
marketing: [
|
|
369
|
+
"coreyhaines31/marketingskills seo-audit",
|
|
370
|
+
"coreyhaines31/marketingskills copywriting",
|
|
371
|
+
"coreyhaines31/marketingskills marketing-psychology",
|
|
372
|
+
"coreyhaines31/marketingskills programmatic-seo",
|
|
373
|
+
"coreyhaines31/marketingskills marketing-ideas",
|
|
374
|
+
"coreyhaines31/marketingskills copy-editing",
|
|
375
|
+
"coreyhaines31/marketingskills pricing-strategy",
|
|
376
|
+
"coreyhaines31/marketingskills social-content",
|
|
377
|
+
"coreyhaines31/marketingskills launch-strategy",
|
|
378
|
+
"coreyhaines31/marketingskills page-cro",
|
|
379
|
+
"coreyhaines31/marketingskills competitor-alternatives",
|
|
380
|
+
"coreyhaines31/marketingskills analytics-tracking",
|
|
381
|
+
"coreyhaines31/marketingskills schema-markup",
|
|
382
|
+
"coreyhaines31/marketingskills onboarding-cro",
|
|
383
|
+
"coreyhaines31/marketingskills email-sequence",
|
|
384
|
+
"coreyhaines31/marketingskills paid-ads",
|
|
385
|
+
"coreyhaines31/marketingskills signup-flow-cro",
|
|
386
|
+
"coreyhaines31/marketingskills free-tool-strategy",
|
|
387
|
+
"coreyhaines31/marketingskills form-cro",
|
|
388
|
+
"coreyhaines31/marketingskills paywall-upgrade-cro",
|
|
389
|
+
"coreyhaines31/marketingskills referral-program",
|
|
390
|
+
"coreyhaines31/marketingskills popup-cro",
|
|
391
|
+
"coreyhaines31/marketingskills ab-test-setup"
|
|
392
|
+
],
|
|
393
|
+
development: [
|
|
394
|
+
"obra/superpowers brainstorming",
|
|
395
|
+
"obra/superpowers test-driven-development",
|
|
396
|
+
"obra/superpowers systematic-debugging",
|
|
397
|
+
"obra/superpowers writing-plans",
|
|
398
|
+
"obra/superpowers executing-plans",
|
|
399
|
+
"obra/superpowers verification-before-completion",
|
|
400
|
+
"obra/superpowers using-superpowers",
|
|
401
|
+
"obra/superpowers subagent-driven-development",
|
|
402
|
+
"obra/superpowers requesting-code-review",
|
|
403
|
+
"obra/superpowers writing-skills",
|
|
404
|
+
"obra/superpowers dispatching-parallel-agents",
|
|
405
|
+
"obra/superpowers receiving-code-review",
|
|
406
|
+
"obra/superpowers using-git-worktrees",
|
|
407
|
+
"obra/superpowers finishing-a-development-branch",
|
|
408
|
+
"wshobson/agents code-review-excellence",
|
|
409
|
+
"wshobson/agents api-design-principles",
|
|
410
|
+
"wshobson/agents architecture-patterns",
|
|
411
|
+
"wshobson/agents error-handling-patterns",
|
|
412
|
+
"wshobson/agents nodejs-backend-patterns",
|
|
413
|
+
"wshobson/agents microservices-patterns",
|
|
414
|
+
"wshobson/agents modern-javascript-patterns",
|
|
415
|
+
"wshobson/agents web-component-design",
|
|
416
|
+
"wshobson/agents async-python-patterns",
|
|
417
|
+
"wshobson/agents python-testing-patterns",
|
|
418
|
+
"boristane/agent-skills logging-best-practices"
|
|
419
|
+
],
|
|
420
|
+
productivity: [
|
|
421
|
+
"softaworks/agent-toolkit daily-meeting-update",
|
|
422
|
+
"softaworks/agent-toolkit agent-md-refactor",
|
|
423
|
+
"softaworks/agent-toolkit session-handoff",
|
|
424
|
+
"softaworks/agent-toolkit meme-factory",
|
|
425
|
+
"softaworks/agent-toolkit qa-test-planner",
|
|
426
|
+
"softaworks/agent-toolkit writing-clearly-and-concisely",
|
|
427
|
+
"softaworks/agent-toolkit commit-work",
|
|
428
|
+
"softaworks/agent-toolkit mermaid-diagrams",
|
|
429
|
+
"softaworks/agent-toolkit dependency-updater",
|
|
430
|
+
"softaworks/agent-toolkit crafting-effective-readmes",
|
|
431
|
+
"softaworks/agent-toolkit reducing-entropy",
|
|
432
|
+
"softaworks/agent-toolkit feedback-mastery",
|
|
433
|
+
"softaworks/agent-toolkit marp-slide",
|
|
434
|
+
"softaworks/agent-toolkit professional-communication",
|
|
435
|
+
"softaworks/agent-toolkit difficult-workplace-conversations",
|
|
436
|
+
"anthropics/skills internal-comms",
|
|
437
|
+
"othmanadi/planning-with-files planning-with-files"
|
|
438
|
+
],
|
|
439
|
+
security: [
|
|
440
|
+
"trailofbits/skills semgrep",
|
|
441
|
+
"trailofbits/skills secure-workflow-guide",
|
|
442
|
+
"trailofbits/skills codeql",
|
|
443
|
+
"trailofbits/skills property-based-testing",
|
|
444
|
+
"trailofbits/skills variant-analysis",
|
|
445
|
+
"trailofbits/skills guidelines-advisor",
|
|
446
|
+
"trailofbits/skills sharp-edges",
|
|
447
|
+
"trailofbits/skills differential-review",
|
|
448
|
+
"trailofbits/skills ask-questions-if-underspecified",
|
|
449
|
+
"squirrelscan/skills audit-website"
|
|
450
|
+
],
|
|
451
|
+
mobile: [
|
|
452
|
+
"wshobson/agents mobile-ios-design",
|
|
453
|
+
"wshobson/agents mobile-android-design",
|
|
454
|
+
"dimillian/skills swiftui-ui-patterns",
|
|
455
|
+
"dimillian/skills swiftui-liquid-glass"
|
|
456
|
+
],
|
|
457
|
+
obsidian: [
|
|
458
|
+
"kepano/obsidian-skills obsidian-markdown",
|
|
459
|
+
"kepano/obsidian-skills obsidian-bases",
|
|
460
|
+
"kepano/obsidian-skills json-canvas"
|
|
461
|
+
],
|
|
462
|
+
prompts: [
|
|
463
|
+
"f/awesome-chatgpt-prompts skill-lookup",
|
|
464
|
+
"f/awesome-chatgpt-prompts prompt-lookup",
|
|
465
|
+
"wshobson/agents prompt-engineering-patterns"
|
|
466
|
+
],
|
|
467
|
+
browser: [
|
|
468
|
+
"vercel-labs/agent-browser agent-browser"
|
|
469
|
+
],
|
|
470
|
+
content: [
|
|
471
|
+
"op7418/humanizer-zh humanizer-zh",
|
|
472
|
+
"blader/humanizer humanizer",
|
|
473
|
+
"op7418/youtube-clipper-skill youtube-clipper",
|
|
474
|
+
"jimliu/baoyu-skills baoyu-slide-deck",
|
|
475
|
+
"jimliu/baoyu-skills baoyu-article-illustrator",
|
|
476
|
+
"jimliu/baoyu-skills baoyu-cover-image",
|
|
477
|
+
"jimliu/baoyu-skills baoyu-comic",
|
|
478
|
+
"jimliu/baoyu-skills baoyu-infographic",
|
|
479
|
+
"jimliu/baoyu-skills baoyu-image-gen"
|
|
480
|
+
],
|
|
481
|
+
integrations: [
|
|
482
|
+
"intellectronica/agent-skills context7",
|
|
483
|
+
"softaworks/agent-toolkit gemini",
|
|
484
|
+
"softaworks/agent-toolkit codex"
|
|
485
|
+
]
|
|
486
|
+
};
|
|
487
|
+
async function detectStack(projectDir) {
|
|
488
|
+
const stack = {
|
|
489
|
+
suggestedSkills: [],
|
|
490
|
+
suggestedAgents: ["security", "privacy", "bugs"],
|
|
491
|
+
dependencies: /* @__PURE__ */ new Set()
|
|
492
|
+
};
|
|
493
|
+
if (existsSync2(join2(projectDir, "tsconfig.json"))) {
|
|
494
|
+
stack.language = "TypeScript";
|
|
495
|
+
stack.suggestedAgents.push("typecheck");
|
|
496
|
+
stack.suggestedSkills.push("wshobson/agents typescript-advanced-types");
|
|
497
|
+
} else if (existsSync2(join2(projectDir, "package.json"))) {
|
|
498
|
+
stack.language = "JavaScript";
|
|
499
|
+
} else if (existsSync2(join2(projectDir, "requirements.txt")) || existsSync2(join2(projectDir, "pyproject.toml"))) {
|
|
500
|
+
stack.language = "Python";
|
|
501
|
+
} else if (existsSync2(join2(projectDir, "go.mod"))) {
|
|
502
|
+
stack.language = "Go";
|
|
503
|
+
} else if (existsSync2(join2(projectDir, "Cargo.toml"))) {
|
|
504
|
+
stack.language = "Rust";
|
|
505
|
+
}
|
|
506
|
+
if (existsSync2(join2(projectDir, "Package.swift")) || existsSync2(join2(projectDir, "project.pbxproj")) || existsSync2(join2(projectDir, "*.xcodeproj"))) {
|
|
507
|
+
stack.language = "Swift";
|
|
508
|
+
stack.suggestedSkills.push("dimillian/skills swiftui-ui-patterns");
|
|
509
|
+
stack.suggestedSkills.push("dimillian/skills swiftui-liquid-glass");
|
|
510
|
+
}
|
|
511
|
+
if (existsSync2(join2(projectDir, "pnpm-lock.yaml"))) {
|
|
512
|
+
stack.packageManager = "pnpm";
|
|
513
|
+
} else if (existsSync2(join2(projectDir, "yarn.lock"))) {
|
|
514
|
+
stack.packageManager = "yarn";
|
|
515
|
+
} else if (existsSync2(join2(projectDir, "bun.lockb"))) {
|
|
516
|
+
stack.packageManager = "bun";
|
|
517
|
+
} else if (existsSync2(join2(projectDir, "package-lock.json"))) {
|
|
518
|
+
stack.packageManager = "npm";
|
|
519
|
+
}
|
|
520
|
+
if (existsSync2(join2(projectDir, ".github", "workflows"))) {
|
|
521
|
+
stack.suggestedSkills.push("wshobson/agents github-actions-templates");
|
|
522
|
+
}
|
|
523
|
+
try {
|
|
524
|
+
const pkgPath = join2(projectDir, "package.json");
|
|
525
|
+
if (existsSync2(pkgPath)) {
|
|
526
|
+
const pkgContent = await readFile2(pkgPath, "utf-8");
|
|
527
|
+
const pkg = JSON.parse(pkgContent);
|
|
528
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
529
|
+
for (const dep of Object.keys(deps)) {
|
|
530
|
+
stack.dependencies.add(dep);
|
|
531
|
+
}
|
|
532
|
+
for (const dep of Object.keys(deps)) {
|
|
533
|
+
const skills = SKILL_MAPPINGS[dep];
|
|
534
|
+
if (skills) {
|
|
535
|
+
stack.suggestedSkills.push(...skills);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (deps["next"]) {
|
|
539
|
+
stack.framework = `Next.js ${deps["next"].replace("^", "")}`;
|
|
540
|
+
stack.suggestedAgents.push("accessibility", "design");
|
|
541
|
+
} else if (deps["react"]) {
|
|
542
|
+
stack.framework = `React ${deps["react"].replace("^", "")}`;
|
|
543
|
+
stack.suggestedAgents.push("accessibility");
|
|
544
|
+
} else if (deps["vue"]) {
|
|
545
|
+
stack.framework = `Vue ${deps["vue"].replace("^", "")}`;
|
|
546
|
+
} else if (deps["nuxt"]) {
|
|
547
|
+
stack.framework = `Nuxt ${deps["nuxt"].replace("^", "")}`;
|
|
548
|
+
} else if (deps["svelte"]) {
|
|
549
|
+
stack.framework = "Svelte";
|
|
550
|
+
} else if (deps["express"]) {
|
|
551
|
+
stack.framework = "Express.js";
|
|
552
|
+
} else if (deps["fastify"]) {
|
|
553
|
+
stack.framework = "Fastify";
|
|
554
|
+
} else if (deps["hono"]) {
|
|
555
|
+
stack.framework = "Hono";
|
|
556
|
+
} else if (deps["elysia"]) {
|
|
557
|
+
stack.framework = "Elysia";
|
|
558
|
+
} else if (deps["@nestjs/core"]) {
|
|
559
|
+
stack.framework = "NestJS";
|
|
560
|
+
}
|
|
561
|
+
if (deps["next-auth"] || deps["@auth/core"]) {
|
|
562
|
+
stack.auth = "NextAuth.js";
|
|
563
|
+
} else if (deps["passport"]) {
|
|
564
|
+
stack.auth = "Passport.js";
|
|
565
|
+
} else if (deps["@clerk/nextjs"] || deps["@clerk/clerk-react"]) {
|
|
566
|
+
stack.auth = "Clerk";
|
|
567
|
+
} else if (deps["better-auth"]) {
|
|
568
|
+
stack.auth = "Better Auth";
|
|
569
|
+
}
|
|
570
|
+
if (deps["prisma"] || deps["@prisma/client"]) {
|
|
571
|
+
stack.database = "Prisma ORM";
|
|
572
|
+
} else if (deps["drizzle-orm"]) {
|
|
573
|
+
stack.database = "Drizzle ORM";
|
|
574
|
+
} else if (deps["@supabase/supabase-js"]) {
|
|
575
|
+
stack.database = "Supabase";
|
|
576
|
+
} else if (deps["mongoose"]) {
|
|
577
|
+
stack.database = "MongoDB (Mongoose)";
|
|
578
|
+
} else if (deps["pg"]) {
|
|
579
|
+
stack.database = "PostgreSQL";
|
|
580
|
+
} else if (deps["convex"]) {
|
|
581
|
+
stack.database = "Convex";
|
|
582
|
+
}
|
|
583
|
+
if (deps["stripe"] || deps["@stripe/stripe-js"]) {
|
|
584
|
+
stack.suggestedAgents.push("moneybags");
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
} catch {
|
|
588
|
+
}
|
|
589
|
+
if (!stack.database) {
|
|
590
|
+
if (existsSync2(join2(projectDir, "prisma", "schema.prisma"))) {
|
|
591
|
+
stack.database = "Prisma ORM";
|
|
592
|
+
} else if (existsSync2(join2(projectDir, "drizzle.config.ts"))) {
|
|
593
|
+
stack.database = "Drizzle ORM";
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
stack.suggestedSkills = [...new Set(stack.suggestedSkills)];
|
|
597
|
+
stack.suggestedAgents = [...new Set(stack.suggestedAgents)];
|
|
598
|
+
return stack;
|
|
599
|
+
}
|
|
600
|
+
function getSkillsByCategory(category) {
|
|
601
|
+
return SKILL_CATEGORIES[category] || [];
|
|
602
|
+
}
|
|
603
|
+
function getSkillCategories() {
|
|
604
|
+
return Object.entries(SKILL_CATEGORIES).map(([name, skills]) => ({
|
|
605
|
+
name,
|
|
606
|
+
count: skills.length
|
|
607
|
+
}));
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// src/bootstrap/files.ts
|
|
611
|
+
import { readFile as readFile3, writeFile as writeFile2, unlink, mkdir as mkdir2 } from "fs/promises";
|
|
612
|
+
import { existsSync as existsSync3 } from "fs";
|
|
613
|
+
import { join as join3 } from "path";
|
|
614
|
+
var BOOTSTRAP_FILES = [
|
|
615
|
+
{ name: "PROJECT.md", type: "user", description: "Project overview and conventions" },
|
|
616
|
+
{ name: "RULES.md", type: "user", description: "Coding standards agents enforce" },
|
|
617
|
+
{ name: "TEAM.md", type: "user", description: "Team ownership and escalation" },
|
|
618
|
+
{ name: "BOOTSTRAP.md", type: "one-time", description: "First-run setup (deleted after)" },
|
|
619
|
+
{ name: "AGENTS.md", type: "auto", description: "Auto-generated scan context" }
|
|
620
|
+
];
|
|
621
|
+
async function loadBootstrapContext(workDir) {
|
|
622
|
+
const projectDir = workDir || getWorkingDirectory(void 0, true);
|
|
623
|
+
const trieDir = join3(projectDir, ".trie");
|
|
624
|
+
const files = [];
|
|
625
|
+
const contentParts = [];
|
|
626
|
+
let needsBootstrap2 = false;
|
|
627
|
+
for (const file of BOOTSTRAP_FILES) {
|
|
628
|
+
const filePath = join3(trieDir, file.name);
|
|
629
|
+
const exists = existsSync3(filePath);
|
|
630
|
+
if (file.name === "BOOTSTRAP.md" && exists) {
|
|
631
|
+
needsBootstrap2 = true;
|
|
632
|
+
}
|
|
633
|
+
let content;
|
|
634
|
+
if (exists) {
|
|
635
|
+
try {
|
|
636
|
+
content = await readFile3(filePath, "utf-8");
|
|
637
|
+
if (content.trim() && file.type !== "one-time") {
|
|
638
|
+
contentParts.push(`<!-- ${file.name} -->
|
|
639
|
+
${content}`);
|
|
640
|
+
}
|
|
641
|
+
} catch {
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const fileEntry = {
|
|
645
|
+
name: file.name,
|
|
646
|
+
path: filePath,
|
|
647
|
+
type: file.type,
|
|
648
|
+
exists
|
|
649
|
+
};
|
|
650
|
+
if (content) fileEntry.content = content;
|
|
651
|
+
files.push(fileEntry);
|
|
652
|
+
}
|
|
653
|
+
return {
|
|
654
|
+
files,
|
|
655
|
+
injectedContent: contentParts.join("\n\n---\n\n"),
|
|
656
|
+
needsBootstrap: needsBootstrap2
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
async function initializeBootstrapFiles(options = {}) {
|
|
660
|
+
const projectDir = options.workDir || getWorkingDirectory(void 0, true);
|
|
661
|
+
const trieDir = join3(projectDir, ".trie");
|
|
662
|
+
await mkdir2(trieDir, { recursive: true });
|
|
663
|
+
const created = [];
|
|
664
|
+
const skipped = [];
|
|
665
|
+
const stack = await detectStack(projectDir);
|
|
666
|
+
for (const file of BOOTSTRAP_FILES) {
|
|
667
|
+
const filePath = join3(trieDir, file.name);
|
|
668
|
+
const exists = existsSync3(filePath);
|
|
669
|
+
if (exists && !options.force) {
|
|
670
|
+
skipped.push(file.name);
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (file.name === "BOOTSTRAP.md" && options.skipBootstrap) {
|
|
674
|
+
skipped.push(file.name);
|
|
675
|
+
continue;
|
|
676
|
+
}
|
|
677
|
+
if (file.name === "AGENTS.md") {
|
|
678
|
+
skipped.push(file.name);
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const template = getFileTemplate(file.name, stack);
|
|
682
|
+
if (template) {
|
|
683
|
+
await writeFile2(filePath, template);
|
|
684
|
+
created.push(file.name);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return { created, skipped, stack };
|
|
688
|
+
}
|
|
689
|
+
async function completeBootstrap(workDir) {
|
|
690
|
+
const projectDir = workDir || getWorkingDirectory(void 0, true);
|
|
691
|
+
const bootstrapPath = join3(projectDir, ".trie", "BOOTSTRAP.md");
|
|
692
|
+
try {
|
|
693
|
+
await unlink(bootstrapPath);
|
|
694
|
+
return true;
|
|
695
|
+
} catch {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
function needsBootstrap(workDir) {
|
|
700
|
+
const projectDir = workDir || getWorkingDirectory(void 0, true);
|
|
701
|
+
const bootstrapPath = join3(projectDir, ".trie", "BOOTSTRAP.md");
|
|
702
|
+
return existsSync3(bootstrapPath);
|
|
703
|
+
}
|
|
704
|
+
async function loadRules(workDir) {
|
|
705
|
+
const projectDir = workDir || getWorkingDirectory(void 0, true);
|
|
706
|
+
const rulesPath = join3(projectDir, ".trie", "RULES.md");
|
|
707
|
+
try {
|
|
708
|
+
if (existsSync3(rulesPath)) {
|
|
709
|
+
return await readFile3(rulesPath, "utf-8");
|
|
710
|
+
}
|
|
711
|
+
} catch {
|
|
712
|
+
}
|
|
713
|
+
return null;
|
|
714
|
+
}
|
|
715
|
+
async function loadTeamInfo(workDir) {
|
|
716
|
+
const projectDir = workDir || getWorkingDirectory(void 0, true);
|
|
717
|
+
const teamPath = join3(projectDir, ".trie", "TEAM.md");
|
|
718
|
+
try {
|
|
719
|
+
if (existsSync3(teamPath)) {
|
|
720
|
+
return await readFile3(teamPath, "utf-8");
|
|
721
|
+
}
|
|
722
|
+
} catch {
|
|
723
|
+
}
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
function getFileTemplate(fileName, stack) {
|
|
727
|
+
switch (fileName) {
|
|
728
|
+
case "PROJECT.md":
|
|
729
|
+
return getProjectTemplate(stack);
|
|
730
|
+
case "RULES.md":
|
|
731
|
+
return getRulesTemplate(stack);
|
|
732
|
+
case "TEAM.md":
|
|
733
|
+
return getTeamTemplate();
|
|
734
|
+
case "BOOTSTRAP.md":
|
|
735
|
+
return getBootstrapTemplate(stack);
|
|
736
|
+
default:
|
|
737
|
+
return null;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
function getProjectTemplate(stack) {
|
|
741
|
+
const lines = ["# Project Overview", "", "> Define your project context here. AI assistants read this first.", ""];
|
|
742
|
+
lines.push("## Description", "", "[Describe what this project does and who it's for]", "");
|
|
743
|
+
lines.push("## Technology Stack", "");
|
|
744
|
+
if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);
|
|
745
|
+
if (stack.language) lines.push(`- **Language:** ${stack.language}`);
|
|
746
|
+
if (stack.database) lines.push(`- **Database:** ${stack.database}`);
|
|
747
|
+
if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);
|
|
748
|
+
if (!stack.framework && !stack.language && !stack.database) {
|
|
749
|
+
lines.push("[Add your technology stack]");
|
|
750
|
+
}
|
|
751
|
+
lines.push("");
|
|
752
|
+
lines.push("## Architecture", "", "[Key patterns and design decisions]", "");
|
|
753
|
+
lines.push("## Coding Conventions", "", "[Style rules agents should follow]", "");
|
|
754
|
+
lines.push("## AI Instructions", "", "When working on this project:", "1. [Instruction 1]", "2. [Instruction 2]", "3. [Instruction 3]", "");
|
|
755
|
+
lines.push("---", "", "*Edit this file to provide project context to AI assistants.*");
|
|
756
|
+
return lines.join("\n");
|
|
757
|
+
}
|
|
758
|
+
function getRulesTemplate(stack) {
|
|
759
|
+
const packageManager = stack.packageManager || "npm";
|
|
760
|
+
return `# Project Rules
|
|
761
|
+
|
|
762
|
+
> These rules are enforced by Trie agents during scans.
|
|
763
|
+
> Violations appear as issues with [RULES] prefix.
|
|
764
|
+
|
|
765
|
+
## Code Style
|
|
766
|
+
|
|
767
|
+
1. Use named exports, not default exports
|
|
768
|
+
2. Prefer \`${packageManager}\` for package management
|
|
769
|
+
3. Maximum file length: 300 lines
|
|
770
|
+
4. Use TypeScript strict mode
|
|
771
|
+
|
|
772
|
+
## Testing Requirements
|
|
773
|
+
|
|
774
|
+
1. Critical paths require unit tests
|
|
775
|
+
2. API endpoints require integration tests
|
|
776
|
+
3. Minimum coverage: 70%
|
|
777
|
+
|
|
778
|
+
## Security Rules
|
|
779
|
+
|
|
780
|
+
1. Never log sensitive data (passwords, tokens, PII)
|
|
781
|
+
2. All API routes require authentication
|
|
782
|
+
3. Rate limiting required on public endpoints
|
|
783
|
+
4. SQL queries must use parameterized statements
|
|
784
|
+
|
|
785
|
+
## Review Requirements
|
|
786
|
+
|
|
787
|
+
1. All PRs require at least 1 reviewer
|
|
788
|
+
2. Security-sensitive changes require security review
|
|
789
|
+
3. Database migrations require review
|
|
790
|
+
|
|
791
|
+
---
|
|
792
|
+
|
|
793
|
+
*Edit this file to define your project's coding standards.*
|
|
794
|
+
`;
|
|
795
|
+
}
|
|
796
|
+
function getTeamTemplate() {
|
|
797
|
+
return `# Team Structure
|
|
798
|
+
|
|
799
|
+
## Code Ownership
|
|
800
|
+
|
|
801
|
+
| Area | Owner | Backup | Review Required |
|
|
802
|
+
|------|-------|--------|-----------------|
|
|
803
|
+
| \`/src/api/\` | @backend-team | - | 1 approver |
|
|
804
|
+
| \`/src/ui/\` | @frontend-team | - | 1 approver |
|
|
805
|
+
| \`/src/auth/\` | @security-team | - | Security review |
|
|
806
|
+
|
|
807
|
+
## Escalation
|
|
808
|
+
|
|
809
|
+
| Severity | First Contact | Escalate To | SLA |
|
|
810
|
+
|----------|--------------|-------------|-----|
|
|
811
|
+
| Critical | Team lead | CTO | 1 hour |
|
|
812
|
+
| Serious | PR reviewer | Team lead | 4 hours |
|
|
813
|
+
| Moderate | Self-serve | - | 1 day |
|
|
814
|
+
|
|
815
|
+
## Contacts
|
|
816
|
+
|
|
817
|
+
- **Security:** [email/slack]
|
|
818
|
+
- **Privacy:** [email/slack]
|
|
819
|
+
- **Emergencies:** [phone/pager]
|
|
820
|
+
|
|
821
|
+
---
|
|
822
|
+
|
|
823
|
+
*Edit this file to define your team structure.*
|
|
824
|
+
`;
|
|
825
|
+
}
|
|
826
|
+
function getBootstrapTemplate(stack) {
|
|
827
|
+
const skillCommands = stack.suggestedSkills.map((s) => `trie skills add ${s}`).join("\n");
|
|
828
|
+
const agentList = stack.suggestedAgents.join(", ");
|
|
829
|
+
const lines = [
|
|
830
|
+
"# Trie Bootstrap Checklist",
|
|
831
|
+
"",
|
|
832
|
+
"This file guides your first scan setup. **Delete when complete.**",
|
|
833
|
+
"",
|
|
834
|
+
"## Auto-Detected Stack",
|
|
835
|
+
"",
|
|
836
|
+
"Based on your project, Trie detected:"
|
|
837
|
+
];
|
|
838
|
+
if (stack.framework) lines.push(`- **Framework:** ${stack.framework}`);
|
|
839
|
+
if (stack.language) lines.push(`- **Language:** ${stack.language}`);
|
|
840
|
+
if (stack.database) lines.push(`- **Database:** ${stack.database}`);
|
|
841
|
+
if (stack.auth) lines.push(`- **Auth:** ${stack.auth}`);
|
|
842
|
+
lines.push("", "## Recommended Actions", "", "### 1. Skills to Install", "Based on your stack, consider installing:", "```bash");
|
|
843
|
+
lines.push(skillCommands || "# No specific skills detected - browse https://skills.sh");
|
|
844
|
+
lines.push("```", "", "### 2. Agents to Enable", `Your stack suggests these agents: ${agentList || "security, privacy, bugs"}`, "");
|
|
845
|
+
lines.push("### 3. Configure Rules", "Add your coding standards to `.trie/RULES.md`.", "");
|
|
846
|
+
lines.push("### 4. Run First Scan", "```bash", "trie scan", "```", "");
|
|
847
|
+
lines.push("---", "", "**Delete this file after completing setup.** Run:", "```bash", "rm .trie/BOOTSTRAP.md", "```");
|
|
848
|
+
return lines.join("\n");
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// src/context/graph.ts
|
|
852
|
+
import crypto from "crypto";
|
|
853
|
+
import path2 from "path";
|
|
854
|
+
|
|
855
|
+
// src/context/store.ts
|
|
856
|
+
import Database from "better-sqlite3";
|
|
857
|
+
import fs from "fs";
|
|
858
|
+
import path from "path";
|
|
859
|
+
var ContextStore = class {
|
|
860
|
+
db;
|
|
861
|
+
dbFilePath;
|
|
862
|
+
constructor(projectPath, dbFilePath) {
|
|
863
|
+
this.dbFilePath = dbFilePath ?? path.join(projectPath, ".trie", "context.db");
|
|
864
|
+
this.ensureDirectory();
|
|
865
|
+
this.db = new Database(this.dbFilePath);
|
|
866
|
+
this.configure();
|
|
867
|
+
this.prepareSchema();
|
|
868
|
+
}
|
|
869
|
+
get databasePath() {
|
|
870
|
+
return this.dbFilePath;
|
|
871
|
+
}
|
|
872
|
+
addNode(node) {
|
|
873
|
+
const stmt = this.db.prepare(
|
|
874
|
+
`INSERT INTO nodes (id, type, data, created_at, updated_at)
|
|
875
|
+
VALUES (@id, @type, @data, @created_at, @updated_at)`
|
|
876
|
+
);
|
|
877
|
+
stmt.run({
|
|
878
|
+
id: node.id,
|
|
879
|
+
type: node.type,
|
|
880
|
+
data: JSON.stringify(node.data),
|
|
881
|
+
created_at: node.created_at,
|
|
882
|
+
updated_at: node.updated_at
|
|
883
|
+
});
|
|
884
|
+
return node;
|
|
885
|
+
}
|
|
886
|
+
upsertNode(node) {
|
|
887
|
+
const stmt = this.db.prepare(
|
|
888
|
+
`INSERT INTO nodes (id, type, data, created_at, updated_at)
|
|
889
|
+
VALUES (@id, @type, @data, @created_at, @updated_at)
|
|
890
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
891
|
+
type=excluded.type,
|
|
892
|
+
data=excluded.data,
|
|
893
|
+
updated_at=excluded.updated_at`
|
|
894
|
+
);
|
|
895
|
+
stmt.run({
|
|
896
|
+
id: node.id,
|
|
897
|
+
type: node.type,
|
|
898
|
+
data: JSON.stringify(node.data),
|
|
899
|
+
created_at: node.created_at,
|
|
900
|
+
updated_at: node.updated_at
|
|
901
|
+
});
|
|
902
|
+
return node;
|
|
903
|
+
}
|
|
904
|
+
getNode(id) {
|
|
905
|
+
const row = this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(id);
|
|
906
|
+
return row ? this.mapNodeRow(row) : null;
|
|
907
|
+
}
|
|
908
|
+
getNodeByType(type, id) {
|
|
909
|
+
const row = this.db.prepare("SELECT * FROM nodes WHERE id = ? AND type = ?").get(id, type);
|
|
910
|
+
return row ? this.mapNodeRow(row) : null;
|
|
911
|
+
}
|
|
912
|
+
updateNode(id, updates, updatedAt) {
|
|
913
|
+
const existing = this.getNode(id);
|
|
914
|
+
if (!existing) {
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
const merged = {
|
|
918
|
+
...existing,
|
|
919
|
+
data: { ...existing.data, ...updates },
|
|
920
|
+
updated_at: updatedAt
|
|
921
|
+
};
|
|
922
|
+
this.db.prepare(
|
|
923
|
+
`UPDATE nodes SET data = @data, updated_at = @updated_at
|
|
924
|
+
WHERE id = @id`
|
|
925
|
+
).run({
|
|
926
|
+
id,
|
|
927
|
+
data: JSON.stringify(merged.data),
|
|
928
|
+
updated_at: merged.updated_at
|
|
929
|
+
});
|
|
930
|
+
return merged;
|
|
931
|
+
}
|
|
932
|
+
deleteNode(id) {
|
|
933
|
+
const deleteEdges = this.db.prepare("DELETE FROM edges WHERE from_id = ? OR to_id = ?");
|
|
934
|
+
const deleteNodeStmt = this.db.prepare("DELETE FROM nodes WHERE id = ?");
|
|
935
|
+
const transaction = this.db.transaction((nodeId) => {
|
|
936
|
+
deleteEdges.run(nodeId, nodeId);
|
|
937
|
+
deleteNodeStmt.run(nodeId);
|
|
938
|
+
});
|
|
939
|
+
transaction(id);
|
|
940
|
+
}
|
|
941
|
+
listNodes() {
|
|
942
|
+
const rows = this.db.prepare("SELECT * FROM nodes").all();
|
|
943
|
+
return rows.map((row) => this.mapNodeRow(row));
|
|
944
|
+
}
|
|
945
|
+
findNodesByType(type) {
|
|
946
|
+
const rows = this.db.prepare("SELECT * FROM nodes WHERE type = ?").all(type);
|
|
947
|
+
return rows.map((row) => this.mapNodeRow(row));
|
|
948
|
+
}
|
|
949
|
+
addEdge(edge) {
|
|
950
|
+
const stmt = this.db.prepare(
|
|
951
|
+
`INSERT INTO edges (id, from_id, to_id, type, weight, metadata, created_at)
|
|
952
|
+
VALUES (@id, @from_id, @to_id, @type, @weight, @metadata, @created_at)`
|
|
953
|
+
);
|
|
954
|
+
stmt.run({
|
|
955
|
+
id: edge.id,
|
|
956
|
+
from_id: edge.from_id,
|
|
957
|
+
to_id: edge.to_id,
|
|
958
|
+
type: edge.type,
|
|
959
|
+
weight: edge.weight,
|
|
960
|
+
metadata: JSON.stringify(edge.metadata ?? {}),
|
|
961
|
+
created_at: edge.created_at
|
|
962
|
+
});
|
|
963
|
+
return edge;
|
|
964
|
+
}
|
|
965
|
+
upsertEdge(edge) {
|
|
966
|
+
const stmt = this.db.prepare(
|
|
967
|
+
`INSERT INTO edges (id, from_id, to_id, type, weight, metadata, created_at)
|
|
968
|
+
VALUES (@id, @from_id, @to_id, @type, @weight, @metadata, @created_at)
|
|
969
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
970
|
+
from_id=excluded.from_id,
|
|
971
|
+
to_id=excluded.to_id,
|
|
972
|
+
type=excluded.type,
|
|
973
|
+
weight=excluded.weight,
|
|
974
|
+
metadata=excluded.metadata`
|
|
975
|
+
);
|
|
976
|
+
stmt.run({
|
|
977
|
+
id: edge.id,
|
|
978
|
+
from_id: edge.from_id,
|
|
979
|
+
to_id: edge.to_id,
|
|
980
|
+
type: edge.type,
|
|
981
|
+
weight: edge.weight,
|
|
982
|
+
metadata: JSON.stringify(edge.metadata ?? {}),
|
|
983
|
+
created_at: edge.created_at
|
|
984
|
+
});
|
|
985
|
+
return edge;
|
|
986
|
+
}
|
|
987
|
+
getEdge(id) {
|
|
988
|
+
const row = this.db.prepare("SELECT * FROM edges WHERE id = ?").get(id);
|
|
989
|
+
return row ? this.mapEdgeRow(row) : null;
|
|
990
|
+
}
|
|
991
|
+
getEdges(nodeId, direction = "both") {
|
|
992
|
+
let rows;
|
|
993
|
+
if (direction === "in") {
|
|
994
|
+
rows = this.db.prepare("SELECT * FROM edges WHERE to_id = ?").all(nodeId);
|
|
995
|
+
} else if (direction === "out") {
|
|
996
|
+
rows = this.db.prepare("SELECT * FROM edges WHERE from_id = ?").all(nodeId);
|
|
997
|
+
} else {
|
|
998
|
+
rows = this.db.prepare("SELECT * FROM edges WHERE from_id = ? OR to_id = ?").all(nodeId, nodeId);
|
|
999
|
+
}
|
|
1000
|
+
return rows.map((row) => this.mapEdgeRow(row));
|
|
1001
|
+
}
|
|
1002
|
+
listEdges() {
|
|
1003
|
+
const rows = this.db.prepare("SELECT * FROM edges").all();
|
|
1004
|
+
return rows.map((row) => this.mapEdgeRow(row));
|
|
1005
|
+
}
|
|
1006
|
+
deleteEdge(id) {
|
|
1007
|
+
this.db.prepare("DELETE FROM edges WHERE id = ?").run(id);
|
|
1008
|
+
}
|
|
1009
|
+
close() {
|
|
1010
|
+
this.db.close();
|
|
1011
|
+
}
|
|
1012
|
+
ensureDirectory() {
|
|
1013
|
+
fs.mkdirSync(path.dirname(this.dbFilePath), { recursive: true });
|
|
1014
|
+
}
|
|
1015
|
+
configure() {
|
|
1016
|
+
this.db.pragma("journal_mode = WAL");
|
|
1017
|
+
this.db.pragma("busy_timeout = 5000");
|
|
1018
|
+
this.db.pragma("synchronous = NORMAL");
|
|
1019
|
+
}
|
|
1020
|
+
prepareSchema() {
|
|
1021
|
+
this.db.exec(`
|
|
1022
|
+
CREATE TABLE IF NOT EXISTS nodes (
|
|
1023
|
+
id TEXT PRIMARY KEY,
|
|
1024
|
+
type TEXT NOT NULL,
|
|
1025
|
+
data TEXT NOT NULL,
|
|
1026
|
+
created_at TEXT NOT NULL,
|
|
1027
|
+
updated_at TEXT NOT NULL
|
|
1028
|
+
);
|
|
1029
|
+
|
|
1030
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
1031
|
+
id TEXT PRIMARY KEY,
|
|
1032
|
+
from_id TEXT NOT NULL,
|
|
1033
|
+
to_id TEXT NOT NULL,
|
|
1034
|
+
type TEXT NOT NULL,
|
|
1035
|
+
weight REAL NOT NULL DEFAULT 1,
|
|
1036
|
+
metadata TEXT DEFAULT '{}',
|
|
1037
|
+
created_at TEXT NOT NULL
|
|
1038
|
+
);
|
|
1039
|
+
|
|
1040
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type);
|
|
1041
|
+
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id);
|
|
1042
|
+
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id);
|
|
1043
|
+
CREATE INDEX IF NOT EXISTS idx_edges_type ON edges(type);
|
|
1044
|
+
`);
|
|
1045
|
+
}
|
|
1046
|
+
mapNodeRow(row) {
|
|
1047
|
+
return {
|
|
1048
|
+
id: row.id,
|
|
1049
|
+
type: row.type,
|
|
1050
|
+
data: JSON.parse(row.data),
|
|
1051
|
+
created_at: row.created_at,
|
|
1052
|
+
updated_at: row.updated_at
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
mapEdgeRow(row) {
|
|
1056
|
+
return {
|
|
1057
|
+
id: row.id,
|
|
1058
|
+
from_id: row.from_id,
|
|
1059
|
+
to_id: row.to_id,
|
|
1060
|
+
type: row.type,
|
|
1061
|
+
weight: row.weight,
|
|
1062
|
+
created_at: row.created_at,
|
|
1063
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : {}
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
// src/context/graph.ts
|
|
1069
|
+
var ContextGraph = class {
|
|
1070
|
+
store;
|
|
1071
|
+
projectPath;
|
|
1072
|
+
constructor(projectPath, dbPath, store) {
|
|
1073
|
+
this.projectPath = projectPath;
|
|
1074
|
+
this.store = store ?? new ContextStore(projectPath, dbPath);
|
|
1075
|
+
}
|
|
1076
|
+
get projectRoot() {
|
|
1077
|
+
return this.projectPath;
|
|
1078
|
+
}
|
|
1079
|
+
async addNode(type, data) {
|
|
1080
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1081
|
+
const id = this.generateNodeId(type, data);
|
|
1082
|
+
const node = {
|
|
1083
|
+
id,
|
|
1084
|
+
type,
|
|
1085
|
+
data,
|
|
1086
|
+
created_at: now,
|
|
1087
|
+
updated_at: now
|
|
1088
|
+
};
|
|
1089
|
+
this.store.addNode(node);
|
|
1090
|
+
return node;
|
|
1091
|
+
}
|
|
1092
|
+
async getNode(type, id) {
|
|
1093
|
+
return this.store.getNodeByType(type, id);
|
|
1094
|
+
}
|
|
1095
|
+
async updateNode(type, id, updates) {
|
|
1096
|
+
const updated = this.store.updateNode(id, updates, (/* @__PURE__ */ new Date()).toISOString());
|
|
1097
|
+
if (updated && updated.type !== type) {
|
|
1098
|
+
throw new Error(`Type mismatch for node ${id}: expected ${type} but found ${updated.type}`);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
async deleteNode(_type, id) {
|
|
1102
|
+
this.store.deleteNode(id);
|
|
1103
|
+
}
|
|
1104
|
+
async addEdge(fromId, toId, type, metadata = {}, weight = 1) {
|
|
1105
|
+
const edge = {
|
|
1106
|
+
id: crypto.randomUUID(),
|
|
1107
|
+
from_id: fromId,
|
|
1108
|
+
to_id: toId,
|
|
1109
|
+
type,
|
|
1110
|
+
weight,
|
|
1111
|
+
metadata,
|
|
1112
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1113
|
+
};
|
|
1114
|
+
this.store.addEdge(edge);
|
|
1115
|
+
return edge;
|
|
1116
|
+
}
|
|
1117
|
+
async getEdges(nodeId, direction = "both") {
|
|
1118
|
+
return this.store.getEdges(nodeId, direction);
|
|
1119
|
+
}
|
|
1120
|
+
async getIncidentsForFile(filePath) {
|
|
1121
|
+
const fileNode = this.findFileNode(filePath);
|
|
1122
|
+
if (!fileNode) return [];
|
|
1123
|
+
const incidents = /* @__PURE__ */ new Map();
|
|
1124
|
+
const affectEdges = this.store.getEdges(fileNode.id, "in").filter((edge) => edge.type === "affects");
|
|
1125
|
+
for (const edge of affectEdges) {
|
|
1126
|
+
const changeId = edge.from_id;
|
|
1127
|
+
const leadEdges = this.store.getEdges(changeId, "out").filter((e) => e.type === "leadTo");
|
|
1128
|
+
const causedByEdges = this.store.getEdges(changeId, "in").filter((e) => e.type === "causedBy");
|
|
1129
|
+
for (const le of leadEdges) {
|
|
1130
|
+
const incident = this.store.getNodeByType("incident", le.to_id);
|
|
1131
|
+
if (incident) incidents.set(incident.id, incident);
|
|
1132
|
+
}
|
|
1133
|
+
for (const ce of causedByEdges) {
|
|
1134
|
+
const incident = this.store.getNodeByType("incident", ce.from_id);
|
|
1135
|
+
if (incident) incidents.set(incident.id, incident);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
return Array.from(incidents.values());
|
|
1139
|
+
}
|
|
1140
|
+
async getPatternsForFile(filePath) {
|
|
1141
|
+
const normalized = this.normalizePath(filePath);
|
|
1142
|
+
const nodes = this.store.findNodesByType("pattern");
|
|
1143
|
+
return nodes.filter(
|
|
1144
|
+
(node) => node.data.appliesTo.some((pattern) => normalized.includes(pattern) || filePath.includes(pattern))
|
|
1145
|
+
);
|
|
1146
|
+
}
|
|
1147
|
+
async getRecentChanges(limit) {
|
|
1148
|
+
const nodes = this.store.findNodesByType("change");
|
|
1149
|
+
return nodes.sort((a, b) => new Date(b.data.timestamp).getTime() - new Date(a.data.timestamp).getTime()).slice(0, limit);
|
|
1150
|
+
}
|
|
1151
|
+
async calculateFileRisk(filePath) {
|
|
1152
|
+
const fileNode = this.findFileNode(filePath);
|
|
1153
|
+
if (!fileNode) return "low";
|
|
1154
|
+
const incidentScore = Math.min(fileNode.data.incidentCount * 2, 6);
|
|
1155
|
+
const changeScore = Math.min(fileNode.data.changeCount, 4);
|
|
1156
|
+
const baseScore = this.riskLevelToScore(fileNode.data.riskLevel);
|
|
1157
|
+
const total = baseScore + incidentScore + changeScore;
|
|
1158
|
+
if (total >= 10) return "critical";
|
|
1159
|
+
if (total >= 7) return "high";
|
|
1160
|
+
if (total >= 4) return "medium";
|
|
1161
|
+
return "low";
|
|
1162
|
+
}
|
|
1163
|
+
async listNodes() {
|
|
1164
|
+
return this.store.listNodes();
|
|
1165
|
+
}
|
|
1166
|
+
async listEdges() {
|
|
1167
|
+
return this.store.listEdges();
|
|
1168
|
+
}
|
|
1169
|
+
async deleteEdge(id) {
|
|
1170
|
+
this.store.deleteEdge(id);
|
|
1171
|
+
}
|
|
1172
|
+
async getSnapshot() {
|
|
1173
|
+
return {
|
|
1174
|
+
nodes: this.store.listNodes(),
|
|
1175
|
+
edges: this.store.listEdges(),
|
|
1176
|
+
exported_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
async applySnapshot(snapshot) {
|
|
1180
|
+
for (const node of snapshot.nodes) {
|
|
1181
|
+
const existing = this.store.getNode(node.id);
|
|
1182
|
+
if (!existing || this.isNewer(node.updated_at, existing.updated_at)) {
|
|
1183
|
+
this.store.upsertNode(node);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
for (const edge of snapshot.edges) {
|
|
1187
|
+
const existing = this.store.getEdge(edge.id);
|
|
1188
|
+
if (!existing) {
|
|
1189
|
+
this.store.upsertEdge(edge);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
generateNodeId(type, data) {
|
|
1194
|
+
if (type === "file") {
|
|
1195
|
+
const fileData = data;
|
|
1196
|
+
return this.normalizePath(fileData.path);
|
|
1197
|
+
}
|
|
1198
|
+
if (type === "change") {
|
|
1199
|
+
const changeData = data;
|
|
1200
|
+
if (changeData.commitHash) {
|
|
1201
|
+
return changeData.commitHash;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
return crypto.randomUUID();
|
|
1205
|
+
}
|
|
1206
|
+
findFileNode(filePath) {
|
|
1207
|
+
const normalized = this.normalizePath(filePath);
|
|
1208
|
+
const nodes = this.store.findNodesByType("file");
|
|
1209
|
+
return nodes.find(
|
|
1210
|
+
(node) => node.id === normalized || this.normalizePath(node.data.path) === normalized || node.data.path === filePath
|
|
1211
|
+
) ?? null;
|
|
1212
|
+
}
|
|
1213
|
+
normalizePath(filePath) {
|
|
1214
|
+
return path2.resolve(this.projectPath, filePath);
|
|
1215
|
+
}
|
|
1216
|
+
riskLevelToScore(level) {
|
|
1217
|
+
switch (level) {
|
|
1218
|
+
case "critical":
|
|
1219
|
+
return 6;
|
|
1220
|
+
case "high":
|
|
1221
|
+
return 4;
|
|
1222
|
+
case "medium":
|
|
1223
|
+
return 2;
|
|
1224
|
+
default:
|
|
1225
|
+
return 0;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
isNewer(incoming, existing) {
|
|
1229
|
+
return new Date(incoming).getTime() >= new Date(existing).getTime();
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
|
|
1233
|
+
// src/agent/perceive.ts
|
|
1234
|
+
import path4 from "path";
|
|
1235
|
+
|
|
1236
|
+
// src/agent/diff-analyzer.ts
|
|
1237
|
+
var RISKY_PATTERNS = [/auth/i, /token/i, /password/i, /secret/i, /validate/i, /sanitize/i];
|
|
1238
|
+
function analyzeDiff(diff) {
|
|
1239
|
+
const files = [];
|
|
1240
|
+
let current = null;
|
|
1241
|
+
const lines = diff.split("\n");
|
|
1242
|
+
for (const line of lines) {
|
|
1243
|
+
if (line.startsWith("+++ b/")) {
|
|
1244
|
+
const filePath = line.replace("+++ b/", "").trim();
|
|
1245
|
+
current = {
|
|
1246
|
+
filePath,
|
|
1247
|
+
added: 0,
|
|
1248
|
+
removed: 0,
|
|
1249
|
+
functionsModified: [],
|
|
1250
|
+
riskyPatterns: []
|
|
1251
|
+
};
|
|
1252
|
+
files.push(current);
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
if (!current) {
|
|
1256
|
+
continue;
|
|
1257
|
+
}
|
|
1258
|
+
if (line.startsWith("@@")) {
|
|
1259
|
+
const match = line.match(/@@.*?(function\s+([\w$]+)|class\s+([\w$]+)|([\w$]+\s*\())/i);
|
|
1260
|
+
const fnName = match?.[2] || match?.[3] || match?.[4];
|
|
1261
|
+
if (fnName) {
|
|
1262
|
+
current.functionsModified.push(fnName.replace("(", "").trim());
|
|
1263
|
+
}
|
|
1264
|
+
continue;
|
|
1265
|
+
}
|
|
1266
|
+
if (line.startsWith("+") && !line.startsWith("+++")) {
|
|
1267
|
+
current.added += 1;
|
|
1268
|
+
markRisk(line, current);
|
|
1269
|
+
} else if (line.startsWith("-") && !line.startsWith("---")) {
|
|
1270
|
+
current.removed += 1;
|
|
1271
|
+
markRisk(line, current);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
const totalAdded = files.reduce((acc, f) => acc + f.added, 0);
|
|
1275
|
+
const totalRemoved = files.reduce((acc, f) => acc + f.removed, 0);
|
|
1276
|
+
const riskyFiles = files.filter((f) => f.riskyPatterns.length > 0).map((f) => f.filePath);
|
|
1277
|
+
return {
|
|
1278
|
+
files,
|
|
1279
|
+
totalAdded,
|
|
1280
|
+
totalRemoved,
|
|
1281
|
+
riskyFiles
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
function markRisk(line, file) {
|
|
1285
|
+
for (const pattern of RISKY_PATTERNS) {
|
|
1286
|
+
if (pattern.test(line)) {
|
|
1287
|
+
const label = pattern.toString();
|
|
1288
|
+
if (!file.riskyPatterns.includes(label)) {
|
|
1289
|
+
file.riskyPatterns.push(label);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/agent/git.ts
|
|
1296
|
+
import { execFile } from "child_process";
|
|
1297
|
+
import { existsSync as existsSync4 } from "fs";
|
|
1298
|
+
import path3 from "path";
|
|
1299
|
+
import { promisify } from "util";
|
|
1300
|
+
var execFileAsync = promisify(execFile);
|
|
1301
|
+
async function execGit(args, cwd) {
|
|
1302
|
+
try {
|
|
1303
|
+
const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
|
|
1304
|
+
maxBuffer: 10 * 1024 * 1024
|
|
1305
|
+
});
|
|
1306
|
+
return stdout.trim();
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
const stderr = error?.stderr?.toString();
|
|
1309
|
+
if (stderr?.includes("not a git repository") || stderr?.includes("does not have any commits")) {
|
|
1310
|
+
return null;
|
|
1311
|
+
}
|
|
1312
|
+
throw error;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
async function ensureRepo(projectPath) {
|
|
1316
|
+
const result = await execGit(["rev-parse", "--is-inside-work-tree"], projectPath);
|
|
1317
|
+
return result === "true";
|
|
1318
|
+
}
|
|
1319
|
+
function parseNameStatus(output) {
|
|
1320
|
+
return output.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
|
|
1321
|
+
const parts = line.split(" ");
|
|
1322
|
+
const status = parts[0] ?? "";
|
|
1323
|
+
const filePath = parts[1] ?? "";
|
|
1324
|
+
const oldPath = parts[2];
|
|
1325
|
+
const change = { status, path: filePath };
|
|
1326
|
+
if (oldPath) change.oldPath = oldPath;
|
|
1327
|
+
return change;
|
|
1328
|
+
}).filter((entry) => entry.path.length > 0);
|
|
1329
|
+
}
|
|
1330
|
+
async function getStagedChanges(projectPath) {
|
|
1331
|
+
const isRepo = await ensureRepo(projectPath);
|
|
1332
|
+
if (!isRepo) return [];
|
|
1333
|
+
const output = await execGit(["diff", "--cached", "--name-status"], projectPath);
|
|
1334
|
+
if (!output) return [];
|
|
1335
|
+
return parseNameStatus(output);
|
|
1336
|
+
}
|
|
1337
|
+
async function getUncommittedChanges(projectPath) {
|
|
1338
|
+
const isRepo = await ensureRepo(projectPath);
|
|
1339
|
+
if (!isRepo) return [];
|
|
1340
|
+
const changes = [];
|
|
1341
|
+
const unstaged = await execGit(["diff", "--name-status"], projectPath);
|
|
1342
|
+
if (unstaged) {
|
|
1343
|
+
changes.push(...parseNameStatus(unstaged));
|
|
1344
|
+
}
|
|
1345
|
+
const untracked = await execGit(["ls-files", "--others", "--exclude-standard"], projectPath);
|
|
1346
|
+
if (untracked) {
|
|
1347
|
+
changes.push(
|
|
1348
|
+
...untracked.split("\n").map((p) => p.trim()).filter(Boolean).map((p) => ({ status: "??", path: p }))
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
return changes;
|
|
1352
|
+
}
|
|
1353
|
+
async function getWorkingTreeDiff(projectPath, stagedOnly = false) {
|
|
1354
|
+
const isRepo = await ensureRepo(projectPath);
|
|
1355
|
+
if (!isRepo) return "";
|
|
1356
|
+
const args = stagedOnly ? ["diff", "--cached", "--unified=3", "--no-color"] : ["diff", "--unified=3", "--no-color"];
|
|
1357
|
+
const diff = await execGit(args, projectPath);
|
|
1358
|
+
return diff ?? "";
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// src/agent/perceive.ts
|
|
1362
|
+
async function perceiveCurrentChanges(projectPath, graph) {
|
|
1363
|
+
const ctxGraph = graph ?? new ContextGraph(projectPath);
|
|
1364
|
+
const [staged, unstaged] = await Promise.all([
|
|
1365
|
+
getStagedChanges(projectPath),
|
|
1366
|
+
getUncommittedChanges(projectPath)
|
|
1367
|
+
]);
|
|
1368
|
+
const stagedDiff = await getWorkingTreeDiff(projectPath, true);
|
|
1369
|
+
const unstagedDiff = await getWorkingTreeDiff(projectPath, false);
|
|
1370
|
+
const combinedDiff = [stagedDiff, unstagedDiff].filter(Boolean).join("\n");
|
|
1371
|
+
const diffSummary = analyzeDiff(combinedDiff);
|
|
1372
|
+
const filesTouched = /* @__PURE__ */ new Set();
|
|
1373
|
+
staged.forEach((c) => filesTouched.add(c.path));
|
|
1374
|
+
unstaged.forEach((c) => filesTouched.add(c.path));
|
|
1375
|
+
diffSummary.files.forEach((f) => filesTouched.add(f.filePath));
|
|
1376
|
+
const changeId = await upsertWorkingChange(ctxGraph, Array.from(filesTouched), projectPath);
|
|
1377
|
+
const result = {
|
|
1378
|
+
staged,
|
|
1379
|
+
unstaged,
|
|
1380
|
+
diffSummary
|
|
1381
|
+
};
|
|
1382
|
+
if (changeId) result.changeNodeId = changeId;
|
|
1383
|
+
return result;
|
|
1384
|
+
}
|
|
1385
|
+
async function upsertWorkingChange(graph, files, projectPath) {
|
|
1386
|
+
if (files.length === 0) return void 0;
|
|
1387
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1388
|
+
const change = await graph.addNode("change", {
|
|
1389
|
+
commitHash: null,
|
|
1390
|
+
files,
|
|
1391
|
+
message: "workspace changes",
|
|
1392
|
+
diff: null,
|
|
1393
|
+
author: null,
|
|
1394
|
+
timestamp: now,
|
|
1395
|
+
outcome: "unknown"
|
|
1396
|
+
});
|
|
1397
|
+
for (const filePath of files) {
|
|
1398
|
+
const fileNode = await ensureFileNode(graph, filePath, projectPath);
|
|
1399
|
+
await graph.addEdge(change.id, fileNode.id, "affects");
|
|
1400
|
+
}
|
|
1401
|
+
return change.id;
|
|
1402
|
+
}
|
|
1403
|
+
async function ensureFileNode(graph, filePath, projectPath) {
|
|
1404
|
+
const normalized = path4.resolve(projectPath, filePath);
|
|
1405
|
+
const existing = await graph.getNode("file", normalized);
|
|
1406
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1407
|
+
if (existing) {
|
|
1408
|
+
const data2 = existing.data;
|
|
1409
|
+
await graph.updateNode("file", existing.id, {
|
|
1410
|
+
changeCount: (data2.changeCount ?? 0) + 1,
|
|
1411
|
+
lastChanged: now
|
|
1412
|
+
});
|
|
1413
|
+
return await graph.getNode("file", existing.id);
|
|
1414
|
+
}
|
|
1415
|
+
const data = {
|
|
1416
|
+
path: filePath,
|
|
1417
|
+
extension: path4.extname(filePath),
|
|
1418
|
+
purpose: "",
|
|
1419
|
+
riskLevel: "medium",
|
|
1420
|
+
whyRisky: null,
|
|
1421
|
+
changeCount: 1,
|
|
1422
|
+
lastChanged: now,
|
|
1423
|
+
incidentCount: 0,
|
|
1424
|
+
createdAt: now
|
|
1425
|
+
};
|
|
1426
|
+
return await graph.addNode("file", data);
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// src/agent/risk-scorer.ts
|
|
1430
|
+
import path5 from "path";
|
|
1431
|
+
var BASE_RISK = {
|
|
1432
|
+
low: 10,
|
|
1433
|
+
medium: 35,
|
|
1434
|
+
high: 65,
|
|
1435
|
+
critical: 85
|
|
1436
|
+
};
|
|
1437
|
+
var SENSITIVE_PATHS = [
|
|
1438
|
+
{ pattern: /auth|login|token|session/i, weight: 20, reason: "touches authentication" },
|
|
1439
|
+
{ pattern: /payment|billing|stripe|paypal|checkout/i, weight: 25, reason: "touches payments" },
|
|
1440
|
+
{ pattern: /secret|credential|env|config\/security/i, weight: 15, reason: "touches secrets/security config" },
|
|
1441
|
+
{ pattern: /gdpr|privacy|pii|phi/i, weight: 15, reason: "touches sensitive data" }
|
|
1442
|
+
];
|
|
1443
|
+
function levelFromScore(score) {
|
|
1444
|
+
if (score >= 90) return "critical";
|
|
1445
|
+
if (score >= 65) return "high";
|
|
1446
|
+
if (score >= 40) return "medium";
|
|
1447
|
+
return "low";
|
|
1448
|
+
}
|
|
1449
|
+
async function scoreFile(graph, filePath, matchedPatterns = []) {
|
|
1450
|
+
const reasons = [];
|
|
1451
|
+
const normalized = path5.resolve(graph.projectRoot, filePath);
|
|
1452
|
+
const node = await graph.getNode("file", normalized);
|
|
1453
|
+
const incidents = await graph.getIncidentsForFile(filePath);
|
|
1454
|
+
let score = 10;
|
|
1455
|
+
const data = node?.data;
|
|
1456
|
+
if (data) {
|
|
1457
|
+
score = BASE_RISK[data.riskLevel] ?? score;
|
|
1458
|
+
reasons.push(`baseline ${data.riskLevel}`);
|
|
1459
|
+
if (data.incidentCount > 0) {
|
|
1460
|
+
const incBoost = Math.min(data.incidentCount * 12, 36);
|
|
1461
|
+
score += incBoost;
|
|
1462
|
+
reasons.push(`historical incidents (+${incBoost})`);
|
|
1463
|
+
}
|
|
1464
|
+
if (data.changeCount > 5) {
|
|
1465
|
+
const changeBoost = Math.min((data.changeCount - 5) * 2, 12);
|
|
1466
|
+
score += changeBoost;
|
|
1467
|
+
reasons.push(`frequent changes (+${changeBoost})`);
|
|
1468
|
+
}
|
|
1469
|
+
if (data.lastChanged) {
|
|
1470
|
+
const lastChanged = new Date(data.lastChanged).getTime();
|
|
1471
|
+
const days = (Date.now() - lastChanged) / (1e3 * 60 * 60 * 24);
|
|
1472
|
+
if (days > 60 && data.incidentCount === 0) {
|
|
1473
|
+
score -= 5;
|
|
1474
|
+
reasons.push("stable for 60d (-5)");
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
for (const { pattern, weight, reason } of SENSITIVE_PATHS) {
|
|
1479
|
+
if (pattern.test(filePath)) {
|
|
1480
|
+
score += weight;
|
|
1481
|
+
reasons.push(reason);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
if (matchedPatterns.length > 0) {
|
|
1485
|
+
const patternBoost = Math.min(
|
|
1486
|
+
matchedPatterns.reduce((acc, p) => acc + (p.data.confidence ?? 50) / 10, 0),
|
|
1487
|
+
20
|
|
1488
|
+
);
|
|
1489
|
+
score += patternBoost;
|
|
1490
|
+
reasons.push(`pattern match (+${Math.round(patternBoost)})`);
|
|
1491
|
+
}
|
|
1492
|
+
if (incidents.length > 0) {
|
|
1493
|
+
const timestamps = incidents.map((i) => new Date(i.data.timestamp).getTime()).sort((a, b) => b - a);
|
|
1494
|
+
const recent = timestamps[0];
|
|
1495
|
+
const daysSince = (Date.now() - recent) / (1e3 * 60 * 60 * 24);
|
|
1496
|
+
if (daysSince > 90) {
|
|
1497
|
+
score -= 5;
|
|
1498
|
+
reasons.push("no incidents in 90d (-5)");
|
|
1499
|
+
} else {
|
|
1500
|
+
score += 8;
|
|
1501
|
+
reasons.push("recent incident (+8)");
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
const level = levelFromScore(score);
|
|
1505
|
+
return {
|
|
1506
|
+
file: filePath,
|
|
1507
|
+
score,
|
|
1508
|
+
level,
|
|
1509
|
+
reasons,
|
|
1510
|
+
incidents,
|
|
1511
|
+
matchedPatterns
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
async function scoreChangeSet(graph, files, patternMatches = {}) {
|
|
1515
|
+
const fileResults = [];
|
|
1516
|
+
for (const file of files) {
|
|
1517
|
+
const patterns = patternMatches[file] ?? [];
|
|
1518
|
+
fileResults.push(await scoreFile(graph, file, patterns));
|
|
1519
|
+
}
|
|
1520
|
+
const maxScore = Math.max(...fileResults.map((f) => f.score), 10);
|
|
1521
|
+
const spreadBoost = files.length > 5 ? Math.min((files.length - 5) * 2, 10) : 0;
|
|
1522
|
+
const overallScore = maxScore + spreadBoost;
|
|
1523
|
+
const overall = levelFromScore(overallScore);
|
|
1524
|
+
const shouldEscalate = overall === "critical" || overall === "high";
|
|
1525
|
+
return {
|
|
1526
|
+
files: fileResults,
|
|
1527
|
+
overall,
|
|
1528
|
+
score: overallScore,
|
|
1529
|
+
shouldEscalate
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
// src/agent/pattern-matcher.ts
|
|
1534
|
+
async function matchPatternsForFiles(graph, files) {
|
|
1535
|
+
const matches = [];
|
|
1536
|
+
const byFile = {};
|
|
1537
|
+
for (const file of files) {
|
|
1538
|
+
const patterns = await graph.getPatternsForFile(file);
|
|
1539
|
+
if (patterns.length === 0) continue;
|
|
1540
|
+
byFile[file] = patterns;
|
|
1541
|
+
for (const pattern of patterns) {
|
|
1542
|
+
matches.push({
|
|
1543
|
+
file,
|
|
1544
|
+
pattern,
|
|
1545
|
+
confidence: pattern.data.confidence,
|
|
1546
|
+
isAntiPattern: pattern.data.isAntiPattern
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
return { matches, byFile };
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// src/agent/reason.ts
|
|
1554
|
+
function buildDefaultCodeContext() {
|
|
1555
|
+
return {
|
|
1556
|
+
changeType: "general",
|
|
1557
|
+
isNewFeature: false,
|
|
1558
|
+
touchesUserData: false,
|
|
1559
|
+
touchesAuth: false,
|
|
1560
|
+
touchesPayments: false,
|
|
1561
|
+
touchesDatabase: false,
|
|
1562
|
+
touchesAPI: false,
|
|
1563
|
+
touchesUI: false,
|
|
1564
|
+
touchesHealthData: false,
|
|
1565
|
+
touchesSecurityConfig: false,
|
|
1566
|
+
linesChanged: 50,
|
|
1567
|
+
filePatterns: [],
|
|
1568
|
+
framework: "unknown",
|
|
1569
|
+
language: "typescript",
|
|
1570
|
+
touchesCrypto: false,
|
|
1571
|
+
touchesFileSystem: false,
|
|
1572
|
+
touchesThirdPartyAPI: false,
|
|
1573
|
+
touchesLogging: false,
|
|
1574
|
+
touchesErrorHandling: false,
|
|
1575
|
+
hasTests: false,
|
|
1576
|
+
complexity: "medium",
|
|
1577
|
+
patterns: {
|
|
1578
|
+
hasAsyncCode: false,
|
|
1579
|
+
hasFormHandling: false,
|
|
1580
|
+
hasFileUploads: false,
|
|
1581
|
+
hasEmailHandling: false,
|
|
1582
|
+
hasRateLimiting: false,
|
|
1583
|
+
hasWebSockets: false,
|
|
1584
|
+
hasCaching: false,
|
|
1585
|
+
hasQueue: false
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
function buildExplanation(result) {
|
|
1590
|
+
const top = [...result.files].sort((a, b) => b.score - a.score)[0];
|
|
1591
|
+
if (!top) return `Risk level ${result.overall} (no files provided)`;
|
|
1592
|
+
return `Risk level ${result.overall} because ${top.file} ${top.reasons.join(", ")}`;
|
|
1593
|
+
}
|
|
1594
|
+
function buildRecommendation(risk, hasAntiPattern) {
|
|
1595
|
+
if (hasAntiPattern || risk === "critical") {
|
|
1596
|
+
return "Block until reviewed: address anti-patterns and rerun targeted tests.";
|
|
1597
|
+
}
|
|
1598
|
+
if (risk === "high") {
|
|
1599
|
+
return "Require senior review and run full test suite before merge.";
|
|
1600
|
+
}
|
|
1601
|
+
if (risk === "medium") {
|
|
1602
|
+
return "Proceed with caution; run impacted tests and sanity checks.";
|
|
1603
|
+
}
|
|
1604
|
+
return "Low risk; proceed but keep an eye on recent changes.";
|
|
1605
|
+
}
|
|
1606
|
+
async function reasonAboutChanges(projectPath, files, options = {}) {
|
|
1607
|
+
const graph = new ContextGraph(projectPath);
|
|
1608
|
+
const { matches, byFile } = await matchPatternsForFiles(graph, files);
|
|
1609
|
+
const changeRisk = await scoreChangeSet(graph, files, byFile);
|
|
1610
|
+
const incidents = [];
|
|
1611
|
+
for (const file of files) {
|
|
1612
|
+
const fileIncidents = await graph.getIncidentsForFile(file);
|
|
1613
|
+
incidents.push(...fileIncidents);
|
|
1614
|
+
}
|
|
1615
|
+
const hasAntiPattern = matches.some((m) => m.isAntiPattern);
|
|
1616
|
+
const riskLevel = hasAntiPattern ? "critical" : changeRisk.overall;
|
|
1617
|
+
const shouldBlock = hasAntiPattern || riskLevel === "critical" || riskLevel === "high";
|
|
1618
|
+
const reasoning = {
|
|
1619
|
+
riskLevel,
|
|
1620
|
+
shouldBlock,
|
|
1621
|
+
explanation: buildExplanation(changeRisk),
|
|
1622
|
+
relevantIncidents: incidents,
|
|
1623
|
+
matchedPatterns: matches.map((m) => m.pattern),
|
|
1624
|
+
recommendation: buildRecommendation(riskLevel, hasAntiPattern),
|
|
1625
|
+
files: changeRisk.files
|
|
1626
|
+
};
|
|
1627
|
+
if (options.runAgents) {
|
|
1628
|
+
const codeContext = options.codeContext ?? buildDefaultCodeContext();
|
|
1629
|
+
const triager = new Triager();
|
|
1630
|
+
const agents = await triager.selectAgents(codeContext, riskLevel);
|
|
1631
|
+
if (agents.length > 0) {
|
|
1632
|
+
const executor = new Executor();
|
|
1633
|
+
const scanContext = {
|
|
1634
|
+
workingDir: projectPath,
|
|
1635
|
+
...options.scanContext
|
|
1636
|
+
};
|
|
1637
|
+
if (codeContext.framework) scanContext.framework = codeContext.framework;
|
|
1638
|
+
if (codeContext.language) scanContext.language = codeContext.language;
|
|
1639
|
+
reasoning.agentResults = await executor.executeAgents(agents, files, scanContext, {
|
|
1640
|
+
parallel: true,
|
|
1641
|
+
timeoutMs: options.scanContext?.config?.timeoutMs ?? 6e4
|
|
1642
|
+
});
|
|
1643
|
+
} else {
|
|
1644
|
+
reasoning.agentResults = [];
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return reasoning;
|
|
1648
|
+
}
|
|
1649
|
+
async function reasonAboutChangesHumanReadable(projectPath, files, options = {}) {
|
|
1650
|
+
const reasoning = await reasonAboutChanges(projectPath, files, options);
|
|
1651
|
+
const { humanizeReasoning } = await import("./comprehension-46F7ZNKL.js");
|
|
1652
|
+
return humanizeReasoning(reasoning);
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
// src/utils/errors.ts
|
|
1656
|
+
var TrieError = class extends Error {
|
|
1657
|
+
code;
|
|
1658
|
+
recoverable;
|
|
1659
|
+
userMessage;
|
|
1660
|
+
constructor(message, code, userMessage, recoverable = true) {
|
|
1661
|
+
super(message);
|
|
1662
|
+
this.code = code;
|
|
1663
|
+
this.recoverable = recoverable;
|
|
1664
|
+
this.userMessage = userMessage;
|
|
1665
|
+
}
|
|
1666
|
+
};
|
|
1667
|
+
function formatFriendlyError(error) {
|
|
1668
|
+
if (error instanceof TrieError) {
|
|
1669
|
+
return { userMessage: error.userMessage, code: error.code };
|
|
1670
|
+
}
|
|
1671
|
+
return {
|
|
1672
|
+
userMessage: "Something went wrong. Try again or run with --offline.",
|
|
1673
|
+
code: "UNKNOWN"
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// src/context/sync.ts
|
|
1678
|
+
import fs2 from "fs/promises";
|
|
1679
|
+
import path6 from "path";
|
|
1680
|
+
var DEFAULT_JSON_NAME = "context.json";
|
|
1681
|
+
async function exportToJson(graph, targetPath) {
|
|
1682
|
+
const snapshot = await graph.getSnapshot();
|
|
1683
|
+
const json = JSON.stringify(snapshot, null, 2);
|
|
1684
|
+
const outputPath = targetPath ?? path6.join(graph.projectRoot, ".trie", DEFAULT_JSON_NAME);
|
|
1685
|
+
await fs2.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
1686
|
+
await fs2.writeFile(outputPath, json, "utf8");
|
|
1687
|
+
return json;
|
|
1688
|
+
}
|
|
1689
|
+
async function importFromJson(graph, json, sourcePath) {
|
|
1690
|
+
const payload = json.trim().length > 0 ? json : await fs2.readFile(sourcePath ?? path6.join(graph.projectRoot, ".trie", DEFAULT_JSON_NAME), "utf8");
|
|
1691
|
+
const snapshot = JSON.parse(payload);
|
|
1692
|
+
await graph.applySnapshot(snapshot);
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// src/context/incident-index.ts
|
|
1696
|
+
import path8 from "path";
|
|
1697
|
+
|
|
1698
|
+
// src/context/file-trie.ts
|
|
1699
|
+
import fs3 from "fs";
|
|
1700
|
+
import path7 from "path";
|
|
1701
|
+
import { performance } from "perf_hooks";
|
|
1702
|
+
function normalizePath(filePath) {
|
|
1703
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
1704
|
+
return normalized.startsWith("./") ? normalized.slice(2) : normalized;
|
|
1705
|
+
}
|
|
1706
|
+
var FilePathTrie = class {
|
|
1707
|
+
trie = new Trie();
|
|
1708
|
+
persistPath;
|
|
1709
|
+
constructor(persistPath) {
|
|
1710
|
+
if (persistPath) this.persistPath = persistPath;
|
|
1711
|
+
if (persistPath && fs3.existsSync(persistPath)) {
|
|
1712
|
+
try {
|
|
1713
|
+
const raw = fs3.readFileSync(persistPath, "utf-8");
|
|
1714
|
+
if (raw.trim().length > 0) {
|
|
1715
|
+
const json = JSON.parse(raw);
|
|
1716
|
+
this.trie = Trie.fromJSON(json);
|
|
1717
|
+
}
|
|
1718
|
+
} catch {
|
|
1719
|
+
this.trie = new Trie();
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
addIncident(filePath, incident) {
|
|
1724
|
+
const key = normalizePath(filePath);
|
|
1725
|
+
const existing = this.trie.search(key);
|
|
1726
|
+
const incidents = existing.found && Array.isArray(existing.value) ? existing.value : [];
|
|
1727
|
+
incidents.push(incident);
|
|
1728
|
+
this.trie.insert(key, incidents);
|
|
1729
|
+
this.persist();
|
|
1730
|
+
}
|
|
1731
|
+
getIncidents(filePath) {
|
|
1732
|
+
const key = normalizePath(filePath);
|
|
1733
|
+
const result = this.trie.search(key);
|
|
1734
|
+
return result.found && Array.isArray(result.value) ? result.value : [];
|
|
1735
|
+
}
|
|
1736
|
+
getDirectoryIncidents(prefix) {
|
|
1737
|
+
const normalizedPrefix = normalizePath(prefix);
|
|
1738
|
+
const matches = this.trie.getWithPrefix(normalizedPrefix);
|
|
1739
|
+
return matches.flatMap((m) => Array.isArray(m.value) ? m.value : []).filter(Boolean);
|
|
1740
|
+
}
|
|
1741
|
+
getHotZones(threshold) {
|
|
1742
|
+
const matches = this.trie.getWithPrefix("");
|
|
1743
|
+
const zones = [];
|
|
1744
|
+
for (const match of matches) {
|
|
1745
|
+
const incidents = Array.isArray(match.value) ? match.value : [];
|
|
1746
|
+
if (incidents.length >= threshold) {
|
|
1747
|
+
zones.push({
|
|
1748
|
+
path: match.pattern,
|
|
1749
|
+
incidentCount: incidents.length,
|
|
1750
|
+
confidence: this.calculateConfidence(incidents.length)
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
return zones.sort((a, b) => b.incidentCount - a.incidentCount);
|
|
1755
|
+
}
|
|
1756
|
+
suggestPaths(partial, limit = 5) {
|
|
1757
|
+
const normalized = normalizePath(partial);
|
|
1758
|
+
const results = this.trie.getWithPrefix(normalized);
|
|
1759
|
+
return results.map((r) => ({
|
|
1760
|
+
path: r.pattern,
|
|
1761
|
+
incidentCount: Array.isArray(r.value) ? r.value.length : 0
|
|
1762
|
+
})).sort((a, b) => b.incidentCount - a.incidentCount).slice(0, limit);
|
|
1763
|
+
}
|
|
1764
|
+
timeLookup(path9) {
|
|
1765
|
+
const start = performance.now();
|
|
1766
|
+
this.getIncidents(path9);
|
|
1767
|
+
return performance.now() - start;
|
|
1768
|
+
}
|
|
1769
|
+
toJSON() {
|
|
1770
|
+
return this.trie.toJSON();
|
|
1771
|
+
}
|
|
1772
|
+
calculateConfidence(count) {
|
|
1773
|
+
const capped = Math.min(count, 10);
|
|
1774
|
+
return Math.round(capped / 10 * 100) / 100;
|
|
1775
|
+
}
|
|
1776
|
+
persist() {
|
|
1777
|
+
if (!this.persistPath) return;
|
|
1778
|
+
try {
|
|
1779
|
+
const dir = path7.dirname(this.persistPath);
|
|
1780
|
+
if (!fs3.existsSync(dir)) {
|
|
1781
|
+
fs3.mkdirSync(dir, { recursive: true });
|
|
1782
|
+
}
|
|
1783
|
+
fs3.writeFileSync(this.persistPath, JSON.stringify(this.trie.toJSON()), "utf-8");
|
|
1784
|
+
} catch {
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
|
|
1789
|
+
// src/context/incident-index.ts
|
|
1790
|
+
var IncidentIndex = class _IncidentIndex {
|
|
1791
|
+
graph;
|
|
1792
|
+
trie;
|
|
1793
|
+
projectRoot;
|
|
1794
|
+
constructor(graph, projectRoot, options) {
|
|
1795
|
+
this.graph = graph;
|
|
1796
|
+
this.projectRoot = projectRoot;
|
|
1797
|
+
this.trie = new FilePathTrie(
|
|
1798
|
+
options?.persistPath ?? path8.join(projectRoot, ".trie", "incident-trie.json")
|
|
1799
|
+
);
|
|
1800
|
+
}
|
|
1801
|
+
static async build(graph, projectRoot, options) {
|
|
1802
|
+
const index = new _IncidentIndex(graph, projectRoot, options);
|
|
1803
|
+
await index.rebuild();
|
|
1804
|
+
return index;
|
|
1805
|
+
}
|
|
1806
|
+
async rebuild() {
|
|
1807
|
+
const nodes = await this.graph.listNodes();
|
|
1808
|
+
const incidents = nodes.filter((n) => n.type === "incident");
|
|
1809
|
+
for (const incident of incidents) {
|
|
1810
|
+
const files = await this.getFilesForIncident(incident.id);
|
|
1811
|
+
this.addIncidentToTrie(incident, files);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
addIncidentToTrie(incident, files) {
|
|
1815
|
+
const meta = {
|
|
1816
|
+
id: incident.id,
|
|
1817
|
+
file: "",
|
|
1818
|
+
description: incident.data.description,
|
|
1819
|
+
severity: incident.data.severity,
|
|
1820
|
+
timestamp: incident.data.timestamp
|
|
1821
|
+
};
|
|
1822
|
+
for (const file of files) {
|
|
1823
|
+
const normalized = this.normalizePath(file);
|
|
1824
|
+
this.trie.addIncident(normalized, { ...meta, file: normalized });
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
getFileTrie() {
|
|
1828
|
+
return this.trie;
|
|
1829
|
+
}
|
|
1830
|
+
async getFilesForIncident(incidentId) {
|
|
1831
|
+
const files = /* @__PURE__ */ new Set();
|
|
1832
|
+
const edges = await this.graph.getEdges(incidentId, "both");
|
|
1833
|
+
for (const edge of edges) {
|
|
1834
|
+
if (edge.type === "causedBy" || edge.type === "leadTo") {
|
|
1835
|
+
const changeId = edge.type === "causedBy" ? edge.to_id : edge.from_id;
|
|
1836
|
+
const change = await this.graph.getNode("change", changeId);
|
|
1837
|
+
if (change?.data && "files" in change.data && Array.isArray(change.data.files)) {
|
|
1838
|
+
change.data.files.forEach((f) => files.add(f));
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
if (edge.type === "affects") {
|
|
1842
|
+
const fileNode = await this.graph.getNode("file", edge.to_id) || await this.graph.getNode("file", edge.from_id);
|
|
1843
|
+
if (fileNode && typeof fileNode.data?.path === "string") {
|
|
1844
|
+
files.add(fileNode.data.path);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return Array.from(files);
|
|
1849
|
+
}
|
|
1850
|
+
normalizePath(filePath) {
|
|
1851
|
+
const absolute = path8.isAbsolute(filePath) ? filePath : path8.join(this.projectRoot, filePath);
|
|
1852
|
+
const relative = path8.relative(this.projectRoot, absolute);
|
|
1853
|
+
return relative.replace(/\\/g, "/");
|
|
1854
|
+
}
|
|
1855
|
+
};
|
|
1856
|
+
|
|
1857
|
+
// src/agent/confidence.ts
|
|
1858
|
+
function adjustConfidence(current, outcome, step = 0.1) {
|
|
1859
|
+
const delta = outcome === "positive" ? step : -step;
|
|
1860
|
+
return clamp(current + delta);
|
|
1861
|
+
}
|
|
1862
|
+
function clamp(value) {
|
|
1863
|
+
if (Number.isNaN(value)) return 0.5;
|
|
1864
|
+
return Math.min(1, Math.max(0, value));
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
// src/agent/pattern-discovery.ts
|
|
1868
|
+
var TriePatternDiscovery = class {
|
|
1869
|
+
constructor(graph, incidentIndex) {
|
|
1870
|
+
this.graph = graph;
|
|
1871
|
+
this.incidentIndex = incidentIndex;
|
|
1872
|
+
}
|
|
1873
|
+
discoverHotPatterns(threshold = 3) {
|
|
1874
|
+
const trie = this.incidentIndex.getFileTrie();
|
|
1875
|
+
const hotZones = trie.getHotZones(threshold);
|
|
1876
|
+
return hotZones.map((zone) => ({
|
|
1877
|
+
type: zone.path.endsWith("/") ? "directory" : "file",
|
|
1878
|
+
path: zone.path,
|
|
1879
|
+
incidentCount: zone.incidentCount,
|
|
1880
|
+
confidence: zone.confidence,
|
|
1881
|
+
relatedFiles: trie.getDirectoryIncidents(zone.path).map((i) => i.file)
|
|
1882
|
+
}));
|
|
1883
|
+
}
|
|
1884
|
+
async discoverCoOccurrences(minCount = 3) {
|
|
1885
|
+
const incidents = await this.getAllIncidents();
|
|
1886
|
+
const coOccurrences = /* @__PURE__ */ new Map();
|
|
1887
|
+
for (const inc of incidents) {
|
|
1888
|
+
const files = await this.getFilesForIncident(inc);
|
|
1889
|
+
for (let i = 0; i < files.length; i++) {
|
|
1890
|
+
for (let j = i + 1; j < files.length; j++) {
|
|
1891
|
+
const a = files[i];
|
|
1892
|
+
const b = files[j];
|
|
1893
|
+
if (!coOccurrences.has(a)) coOccurrences.set(a, /* @__PURE__ */ new Map());
|
|
1894
|
+
const counts = coOccurrences.get(a);
|
|
1895
|
+
counts.set(b, (counts.get(b) || 0) + 1);
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
const patterns = [];
|
|
1900
|
+
for (const [a, map] of coOccurrences.entries()) {
|
|
1901
|
+
for (const [b, count] of map.entries()) {
|
|
1902
|
+
if (count >= minCount) {
|
|
1903
|
+
const denom = Math.min(
|
|
1904
|
+
this.incidentIndex.getFileTrie().getIncidents(a).length || 1,
|
|
1905
|
+
this.incidentIndex.getFileTrie().getIncidents(b).length || 1
|
|
1906
|
+
);
|
|
1907
|
+
patterns.push({
|
|
1908
|
+
files: [a, b],
|
|
1909
|
+
coOccurrences: count,
|
|
1910
|
+
confidence: Math.min(1, count / denom)
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
return patterns.sort((x, y) => y.confidence - x.confidence);
|
|
1916
|
+
}
|
|
1917
|
+
async getAllIncidents() {
|
|
1918
|
+
const nodes = await this.graph.listNodes();
|
|
1919
|
+
return nodes.filter((n) => n.type === "incident");
|
|
1920
|
+
}
|
|
1921
|
+
async getFilesForIncident(incident) {
|
|
1922
|
+
const files = /* @__PURE__ */ new Set();
|
|
1923
|
+
const edges = await this.graph.getEdges(incident.id, "both");
|
|
1924
|
+
for (const edge of edges) {
|
|
1925
|
+
if (edge.type === "causedBy" || edge.type === "leadTo") {
|
|
1926
|
+
const changeId = edge.type === "causedBy" ? edge.to_id : edge.from_id;
|
|
1927
|
+
const change = await this.graph.getNode("change", changeId);
|
|
1928
|
+
if (change?.data?.files && Array.isArray(change.data.files)) {
|
|
1929
|
+
change.data.files.forEach((f) => files.add(f));
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
return Array.from(files).map((f) => f.replace(/\\/g, "/"));
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
|
|
1937
|
+
// src/agent/learning.ts
|
|
1938
|
+
var LearningSystem = class {
|
|
1939
|
+
constructor(graph, projectPath) {
|
|
1940
|
+
this.graph = graph;
|
|
1941
|
+
this.incidentIndex = new IncidentIndex(graph, projectPath);
|
|
1942
|
+
this.discovery = new TriePatternDiscovery(graph, this.incidentIndex);
|
|
1943
|
+
}
|
|
1944
|
+
incidentIndex;
|
|
1945
|
+
discovery;
|
|
1946
|
+
async onWarningHeeded(files) {
|
|
1947
|
+
await this.adjustPatterns(files, "positive");
|
|
1948
|
+
}
|
|
1949
|
+
async onWarningIgnored(files) {
|
|
1950
|
+
await this.adjustPatterns(files, "negative");
|
|
1951
|
+
}
|
|
1952
|
+
async onIncidentReported(incidentId, files) {
|
|
1953
|
+
const incident = await this.graph.getNode("incident", incidentId);
|
|
1954
|
+
if (incident && incident.type === "incident") {
|
|
1955
|
+
this.incidentIndex.addIncidentToTrie(incident, files);
|
|
1956
|
+
}
|
|
1957
|
+
await this.discoverAndStorePatterns();
|
|
1958
|
+
}
|
|
1959
|
+
async onFeedback(helpful, files = []) {
|
|
1960
|
+
await this.adjustPatterns(files, helpful ? "positive" : "negative");
|
|
1961
|
+
}
|
|
1962
|
+
async adjustPatterns(files, outcome) {
|
|
1963
|
+
if (!files.length) return;
|
|
1964
|
+
for (const file of files) {
|
|
1965
|
+
const patterns = await this.graph.getPatternsForFile(file);
|
|
1966
|
+
await Promise.all(patterns.map((p) => this.updatePatternConfidence(p, outcome)));
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
async updatePatternConfidence(pattern, outcome) {
|
|
1970
|
+
const current = pattern.data.confidence ?? 0.5;
|
|
1971
|
+
const updated = adjustConfidence(current, outcome, 0.05);
|
|
1972
|
+
await this.graph.updateNode("pattern", pattern.id, { confidence: updated, lastSeen: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1973
|
+
}
|
|
1974
|
+
async discoverAndStorePatterns() {
|
|
1975
|
+
const hotPatterns = this.discovery.discoverHotPatterns();
|
|
1976
|
+
for (const hot of hotPatterns) {
|
|
1977
|
+
await this.graph.addNode("pattern", {
|
|
1978
|
+
description: `${hot.type === "directory" ? "Directory" : "File"} hot zone: ${hot.path}`,
|
|
1979
|
+
appliesTo: [hot.path],
|
|
1980
|
+
confidence: hot.confidence,
|
|
1981
|
+
occurrences: hot.incidentCount,
|
|
1982
|
+
firstSeen: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1983
|
+
lastSeen: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1984
|
+
isAntiPattern: true,
|
|
1985
|
+
source: "local"
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
};
|
|
1990
|
+
|
|
1991
|
+
// src/tools/feedback.ts
|
|
1992
|
+
var TrieFeedbackTool = class {
|
|
1993
|
+
async execute(input) {
|
|
1994
|
+
try {
|
|
1995
|
+
const projectPath = input.directory || getWorkingDirectory(void 0, true);
|
|
1996
|
+
const graph = new ContextGraph(projectPath);
|
|
1997
|
+
const learning = new LearningSystem(graph, projectPath);
|
|
1998
|
+
const decision = await graph.addNode("decision", {
|
|
1999
|
+
context: input.target ?? "unspecified",
|
|
2000
|
+
decision: input.helpful ? "helpful" : "not helpful",
|
|
2001
|
+
reasoning: input.note ?? null,
|
|
2002
|
+
outcome: input.helpful ? "good" : "bad",
|
|
2003
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
2004
|
+
});
|
|
2005
|
+
if (input.files && input.files.length) {
|
|
2006
|
+
for (const file of input.files) {
|
|
2007
|
+
const fileNode = await graph.getNode("file", file);
|
|
2008
|
+
if (fileNode) {
|
|
2009
|
+
await graph.addEdge(decision.id, fileNode.id, "affects");
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
await learning.onFeedback(input.helpful, input.files);
|
|
2013
|
+
}
|
|
2014
|
+
return {
|
|
2015
|
+
content: [{
|
|
2016
|
+
type: "text",
|
|
2017
|
+
text: input.helpful ? "\u{1F44D} Thanks \u2014 I will prioritize more responses like this." : "\u{1F44E} Understood \u2014 I will adjust future guidance."
|
|
2018
|
+
}]
|
|
2019
|
+
};
|
|
2020
|
+
} catch (error) {
|
|
2021
|
+
const friendly = formatFriendlyError(error);
|
|
2022
|
+
return { content: [{ type: "text", text: friendly.userMessage }] };
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
|
|
2027
|
+
export {
|
|
2028
|
+
SKILL_CATEGORIES,
|
|
2029
|
+
detectStack,
|
|
2030
|
+
getSkillsByCategory,
|
|
2031
|
+
getSkillCategories,
|
|
2032
|
+
loadBootstrapContext,
|
|
2033
|
+
initializeBootstrapFiles,
|
|
2034
|
+
completeBootstrap,
|
|
2035
|
+
needsBootstrap,
|
|
2036
|
+
loadRules,
|
|
2037
|
+
loadTeamInfo,
|
|
2038
|
+
saveCheckpoint,
|
|
2039
|
+
listCheckpoints,
|
|
2040
|
+
getLastCheckpoint,
|
|
2041
|
+
handleCheckpointCommand,
|
|
2042
|
+
ContextGraph,
|
|
2043
|
+
perceiveCurrentChanges,
|
|
2044
|
+
reasonAboutChangesHumanReadable,
|
|
2045
|
+
formatFriendlyError,
|
|
2046
|
+
exportToJson,
|
|
2047
|
+
importFromJson,
|
|
2048
|
+
IncidentIndex,
|
|
2049
|
+
TrieFeedbackTool
|
|
2050
|
+
};
|
|
2051
|
+
//# sourceMappingURL=chunk-WCHIJDCD.js.map
|