@imenam/mcp-dependabot-tracker 1.0.9 → 1.0.10
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 +38 -6
- package/dist/shared/schemas/api.schema.d.ts +5 -2
- package/dist/shared/schemas/ipc.schema.d.ts +1 -1
- package/dist/shared/schemas/ipc.schema.js +3 -0
- package/dist/shared/schemas/model.schema.d.ts +102 -2
- package/dist/shared/schemas/model.schema.js +34 -2
- package/dist/shared/schemas/settings.schema.d.ts +78 -0
- package/dist/shared/schemas/settings.schema.js +42 -0
- package/dist/src/core/analysis.d.ts +29 -0
- package/dist/src/core/analysis.js +177 -0
- package/dist/src/core/claude.d.ts +43 -0
- package/dist/src/core/claude.js +196 -0
- package/dist/src/core/commands.d.ts +2 -0
- package/dist/src/core/commands.js +1 -1
- package/dist/src/core/operations.d.ts +9 -3
- package/dist/src/core/operations.js +64 -5
- package/dist/src/core/organizer.d.ts +43 -0
- package/dist/src/core/organizer.js +95 -0
- package/dist/src/core/repos.d.ts +3 -1
- package/dist/src/core/repos.js +7 -0
- package/dist/src/core/settings.d.ts +21 -0
- package/dist/src/core/settings.js +108 -0
- package/dist/src/core/store.js +8 -3
- package/dist/src/gui-worker.js +9 -0
- package/dist/src/index.js +24 -1
- package/gui/dist/assets/{index-BdMhGHUf.css → index-C1Ml-XiM.css} +1 -1
- package/gui/dist/assets/{index-CIIsKFR9.js → index-DQPqW5Uq.js} +4 -4
- package/gui/dist/index.html +2 -2
- package/package.json +2 -1
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { AnalysisReportSchema } from "../../shared/schemas/model.schema.js";
|
|
5
|
+
import { runClaudeSession } from "./claude.js";
|
|
6
|
+
import { TrackerError } from "./errors.js";
|
|
7
|
+
import { OrganizerClient } from "./organizer.js";
|
|
8
|
+
import { organizerConnection } from "./settings.js";
|
|
9
|
+
/**
|
|
10
|
+
* Analyse par Claude des vulnérabilités que `npm audit fix` laisse dans un
|
|
11
|
+
* clone. Claude lit le code du clone (Read, Grep, Glob, sans commande ni
|
|
12
|
+
* écriture) et n'a accès qu'à quelques outils du MCP organizer, lancé pour la
|
|
13
|
+
* session avec le token réglé dans la GUI : il crée une tâche de reprise,
|
|
14
|
+
* l'assigne au propriétaire de l'espace, lui donne pour tag le nom du dépôt, et
|
|
15
|
+
* rend un rapport structuré. Le tracker relit ensuite la tâche sur
|
|
16
|
+
* l'organizer : une tâche absente, mal assignée ou mal taguée fait échouer
|
|
17
|
+
* l'analyse.
|
|
18
|
+
*/
|
|
19
|
+
/** Nom du serveur MCP organizer dans la configuration de la session. */
|
|
20
|
+
const ORGANIZER_SERVER = "organizer";
|
|
21
|
+
const ORGANIZER_PACKAGE = "@imenam/mcp-organizer";
|
|
22
|
+
/** Outils organizer autorisés ; tout autre appel est refusé par `dontAsk`. */
|
|
23
|
+
const ORGANIZER_TOOLS = ["create_task", "set_assignees", "set_tags", "get_task"];
|
|
24
|
+
/** Taille maximale des vulnérabilités transmises dans la consigne. */
|
|
25
|
+
const MAX_FACTS_CHARS = 20_000;
|
|
26
|
+
/** Chemins d'installation gardés par vulnérabilité. */
|
|
27
|
+
const MAX_NODES = 5;
|
|
28
|
+
/** Résultat demandé à Claude : le rapport et la clé de la tâche créée. */
|
|
29
|
+
const OutputSchema = AnalysisReportSchema.extend({ task: z.string().min(1) });
|
|
30
|
+
const OUTPUT_JSON_SCHEMA = {
|
|
31
|
+
type: "object",
|
|
32
|
+
additionalProperties: false,
|
|
33
|
+
required: ["task", "summary", "urgent", "force"],
|
|
34
|
+
properties: {
|
|
35
|
+
task: { type: "string", description: "Key of the organizer task you created, e.g. ORG-42." },
|
|
36
|
+
summary: { type: "string", description: "One sentence, in French." },
|
|
37
|
+
urgent: {
|
|
38
|
+
type: "array",
|
|
39
|
+
description: "Vulnerabilities to fix by hand urgently; empty when none.",
|
|
40
|
+
items: {
|
|
41
|
+
type: "object",
|
|
42
|
+
additionalProperties: false,
|
|
43
|
+
required: ["package", "reason"],
|
|
44
|
+
properties: { package: { type: "string" }, reason: { type: "string", description: "In French." } },
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
force: {
|
|
48
|
+
type: "object",
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
required: ["recommended", "reason"],
|
|
51
|
+
properties: { recommended: { type: "boolean" }, reason: { type: "string", description: "One or two sentences, in French." } },
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
/** Vulnérabilités d'un rapport `npm audit --json`, réduites à ce qui sert l'analyse. */
|
|
56
|
+
export function auditFacts(report, project) {
|
|
57
|
+
return Object.values((report?.vulnerabilities ?? {})).map((entry) => ({
|
|
58
|
+
project: project === "" ? "." : project,
|
|
59
|
+
name: entry.name,
|
|
60
|
+
severity: entry.severity,
|
|
61
|
+
isDirect: entry.isDirect,
|
|
62
|
+
range: entry.range,
|
|
63
|
+
via: (Array.isArray(entry.via) ? entry.via : []).map((via) => typeof via === "string" ? via : { title: via?.title, url: via?.url, range: via?.range, severity: via?.severity }),
|
|
64
|
+
effects: entry.effects,
|
|
65
|
+
fixAvailable: entry.fixAvailable,
|
|
66
|
+
nodes: (Array.isArray(entry.nodes) ? entry.nodes : []).slice(0, MAX_NODES),
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
/** JSON des vulnérabilités dans la limite de taille ; au-delà, les dernières sont seulement comptées. */
|
|
70
|
+
function factsJson(facts) {
|
|
71
|
+
for (let count = facts.length; count > 0; count--) {
|
|
72
|
+
const json = JSON.stringify(facts.slice(0, count), null, 1);
|
|
73
|
+
if (json.length <= MAX_FACTS_CHARS)
|
|
74
|
+
return count === facts.length ? json : `${json}\n(${facts.length - count} more vulnerabilities not listed)`;
|
|
75
|
+
}
|
|
76
|
+
return `(${facts.length} vulnerabilities, too large to list)`;
|
|
77
|
+
}
|
|
78
|
+
function prompt(input, space, owner, tag) {
|
|
79
|
+
const force = input.forceCandidates.length === 0
|
|
80
|
+
? "No major upgrade fixes them: `npm audit fix --force` would change nothing."
|
|
81
|
+
: [
|
|
82
|
+
"`npm audit fix --force` would apply these major upgrades:",
|
|
83
|
+
...input.forceCandidates.map((candidate) => `- ${candidate.project === "" ? "" : `${candidate.project}/`}${candidate.name} ${candidate.from ?? "?"} → ${candidate.to}`),
|
|
84
|
+
].join("\n");
|
|
85
|
+
return [
|
|
86
|
+
`You analyse the npm vulnerabilities that \`npm audit fix\` could not fix in the GitHub repository ${input.repoId} (branch ${input.branch}).`,
|
|
87
|
+
"The current directory is a clone of that branch where `npm audit fix --package-lock-only` already updated the lockfiles. Read the code with Read, Grep and Glob; you cannot run commands nor change files.",
|
|
88
|
+
"",
|
|
89
|
+
"Remaining vulnerabilities, from `npm audit --json` (`project` is the folder of the package-lock.json):",
|
|
90
|
+
"```json",
|
|
91
|
+
factsJson(input.facts),
|
|
92
|
+
"```",
|
|
93
|
+
"",
|
|
94
|
+
force,
|
|
95
|
+
"",
|
|
96
|
+
"Your job:",
|
|
97
|
+
"1. For each vulnerability, find in the code how the vulnerable package is used (directly, or through which dependency), whether the vulnerable code is reachable from this project, and how urgent a fix by hand is.",
|
|
98
|
+
"2. Decide whether `npm audit fix --force` is worth it: check which APIs of the upgraded packages this project uses and whether the major upgrade breaks them.",
|
|
99
|
+
`3. Create one task in the organizer space "${space}" with create_task, without request_id. Write its title and description in French. The description, in markdown, is a complete handover for another agent who will make the fix: the report per vulnerable package (usage in the code, reachability, urgency, advisory link), the decision about --force with its reason, the ordered list of actions, the files concerned, and how to check the result. Set its priority from the urgency.`,
|
|
100
|
+
`4. Assign the task to ${owner.name} with set_assignees (member id ${owner.id}), and set its tags to exactly ["${tag}"] with set_tags.`,
|
|
101
|
+
"5. Finish with the structured report: the key of the task, a one-sentence summary in French, the vulnerabilities to fix by hand urgently (empty when none), and your recommendation about `npm audit fix --force` with its reason, in French.",
|
|
102
|
+
].join("\n");
|
|
103
|
+
}
|
|
104
|
+
/** Serveur MCP organizer de la session, lancé par `npx` avec le token réglé dans la GUI. */
|
|
105
|
+
function organizerServer(connection) {
|
|
106
|
+
const launch = process.platform === "win32" ? { command: "cmd", args: ["/c", "npx", "-y", ORGANIZER_PACKAGE] } : { command: "npx", args: ["-y", ORGANIZER_PACKAGE] };
|
|
107
|
+
return { ...launch, env: { ORGANIZER_URL: connection.url, ORGANIZER_TOKEN: connection.token } };
|
|
108
|
+
}
|
|
109
|
+
/** Lance l'analyse, puis vérifie sur l'organizer la tâche que Claude dit avoir créée. */
|
|
110
|
+
export async function analyseVulnerabilities(input) {
|
|
111
|
+
const connection = organizerConnection(input.settings);
|
|
112
|
+
const token = input.settings.claude.token;
|
|
113
|
+
if (!connection || !token)
|
|
114
|
+
throw new TrackerError("The analysis needs the organizer connection and the Claude token: set them in the settings.");
|
|
115
|
+
const organizer = new OrganizerClient(connection);
|
|
116
|
+
const { space, owner } = await organizer.space();
|
|
117
|
+
const tag = input.repoId.split("/")[1];
|
|
118
|
+
const configFile = path.join(input.workDir, "analysis-mcp.json");
|
|
119
|
+
fs.writeFileSync(configFile, JSON.stringify({ mcpServers: { [ORGANIZER_SERVER]: organizerServer(connection) } }), { encoding: "utf-8", mode: 0o600 });
|
|
120
|
+
let structured;
|
|
121
|
+
try {
|
|
122
|
+
({ structured } = await runClaudeSession(input.claude, {
|
|
123
|
+
cwd: input.cwd,
|
|
124
|
+
prompt: prompt(input, space.name, owner, tag),
|
|
125
|
+
args: [
|
|
126
|
+
"--tools",
|
|
127
|
+
"Read,Grep,Glob",
|
|
128
|
+
"--allowedTools",
|
|
129
|
+
ORGANIZER_TOOLS.map((tool) => `mcp__${ORGANIZER_SERVER}__${tool}`).join(","),
|
|
130
|
+
"--mcp-config",
|
|
131
|
+
configFile,
|
|
132
|
+
"--strict-mcp-config",
|
|
133
|
+
"--json-schema",
|
|
134
|
+
JSON.stringify(OUTPUT_JSON_SCHEMA),
|
|
135
|
+
],
|
|
136
|
+
token,
|
|
137
|
+
maxTurns: input.settings.analysis.maxTurns,
|
|
138
|
+
maxMinutes: input.settings.analysis.maxMinutes,
|
|
139
|
+
signal: input.signal,
|
|
140
|
+
onLine: input.onLine,
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
fs.rmSync(configFile, { force: true });
|
|
145
|
+
}
|
|
146
|
+
const output = OutputSchema.safeParse(structured);
|
|
147
|
+
if (!output.success)
|
|
148
|
+
throw new TrackerError("Claude Code ended without the structured report.");
|
|
149
|
+
const task = await organizer.task(output.data.task);
|
|
150
|
+
if (!task.tags.some((candidate) => candidate.toLowerCase() === tag.toLowerCase())) {
|
|
151
|
+
throw new TrackerError(`Task ${task.key} was created without the tag "${tag}".`);
|
|
152
|
+
}
|
|
153
|
+
if (!task.assigneeIds.includes(owner.id)) {
|
|
154
|
+
throw new TrackerError(`Task ${task.key} was created without being assigned to ${owner.name}.`);
|
|
155
|
+
}
|
|
156
|
+
const { task: _key, ...report } = output.data;
|
|
157
|
+
return { report, task: { key: task.key, title: task.title, url: organizer.taskUrl(task.id), status: task.status } };
|
|
158
|
+
}
|
|
159
|
+
/** Dernière opération du dépôt dont l'analyse a créé une tâche ; `operations` va de la plus récente à la plus ancienne. */
|
|
160
|
+
export function latestAnalysed(operations) {
|
|
161
|
+
return operations.find((operation) => operation.analysis?.task) ?? null;
|
|
162
|
+
}
|
|
163
|
+
/** Relit sur l'organizer le statut de la dernière tâche d'analyse du dépôt, tant qu'elle n'est pas terminée. */
|
|
164
|
+
export async function refreshAnalysisTask(store, settings, repoId) {
|
|
165
|
+
const connection = organizerConnection(settings);
|
|
166
|
+
const operation = latestAnalysed(store.listOperations(repoId));
|
|
167
|
+
const current = operation?.analysis?.task;
|
|
168
|
+
if (!connection || !operation || !current || current.status === "done")
|
|
169
|
+
return;
|
|
170
|
+
const { status } = await new OrganizerClient(connection).task(current.key);
|
|
171
|
+
if (status === current.status)
|
|
172
|
+
return;
|
|
173
|
+
store.updateOperation(operation.id, (latest) => ({
|
|
174
|
+
...latest,
|
|
175
|
+
analysis: latest.analysis && latest.analysis.task ? { ...latest.analysis, task: { ...latest.analysis.task, status } } : latest.analysis,
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessions Claude Code non interactives (`claude -p`, sortie `stream-json`).
|
|
3
|
+
* Claude Code s'authentifie par un token d'abonnement (`claude setup-token`)
|
|
4
|
+
* passé dans CLAUDE_CODE_OAUTH_TOKEN et garde sa configuration dans un dossier
|
|
5
|
+
* propre au tracker. Il ne reçoit aucune autre variable du serveur : ni
|
|
6
|
+
* GITHUB_TOKEN, ni les réglages du tracker. Seuls les réglages du dossier de
|
|
7
|
+
* configuration sont lus, jamais ceux du dossier de travail.
|
|
8
|
+
*/
|
|
9
|
+
export interface ClaudeRuntime {
|
|
10
|
+
/** Commande de Claude Code et ses arguments fixes. */
|
|
11
|
+
command: string[];
|
|
12
|
+
/** Dossier personnel et de configuration de Claude Code. */
|
|
13
|
+
home: string;
|
|
14
|
+
}
|
|
15
|
+
/** Commande du paquet `@anthropic-ai/claude-code` : son lanceur Node, qui exécute le binaire natif de la plateforme. */
|
|
16
|
+
export declare function packagedClaudeCommand(): string[];
|
|
17
|
+
export interface ClaudeSessionOptions {
|
|
18
|
+
/** Dossier de travail : le seul que Claude Code lit sans autorisation. */
|
|
19
|
+
cwd: string;
|
|
20
|
+
prompt: string;
|
|
21
|
+
/** Options propres à la session : outils, configuration MCP, schéma du résultat. */
|
|
22
|
+
args: string[];
|
|
23
|
+
token: string;
|
|
24
|
+
maxTurns: number;
|
|
25
|
+
maxMinutes: number;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
/** Reçoit chaque action lisible de Claude (texte ou appel d'outil) et le nombre de tours écoulés. */
|
|
28
|
+
onLine?: (line: string, turns: number) => void;
|
|
29
|
+
}
|
|
30
|
+
export interface ClaudeSessionResult {
|
|
31
|
+
/** Résultat validé par `--json-schema`, absent sans schéma. */
|
|
32
|
+
structured: unknown;
|
|
33
|
+
turns: number | null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Lance une session et attend sa fin. Les tours sont limités par Claude Code,
|
|
37
|
+
* la durée par le tracker, qui tue alors la session avec ses descendants, comme
|
|
38
|
+
* à l'annulation par `signal`. Une session qui n'aboutit pas lève une erreur
|
|
39
|
+
* avec sa raison ; une annulation lève `CommandAbortedError`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function runClaudeSession(runtime: ClaudeRuntime, options: ClaudeSessionOptions): Promise<ClaudeSessionResult>;
|
|
42
|
+
/** Vérifie un token d'abonnement par une requête minimale ; lève une erreur avec la réponse de Claude Code s'il est refusé. */
|
|
43
|
+
export declare function checkClaudeToken(runtime: ClaudeRuntime, token: string): Promise<void>;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { spawn } from "child_process";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import { createRequire } from "module";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import { CommandAbortedError, killTree } from "./commands.js";
|
|
6
|
+
import { TrackerError } from "./errors.js";
|
|
7
|
+
/** Commande du paquet `@anthropic-ai/claude-code` : son lanceur Node, qui exécute le binaire natif de la plateforme. */
|
|
8
|
+
export function packagedClaudeCommand() {
|
|
9
|
+
const require = createRequire(import.meta.url);
|
|
10
|
+
return [process.execPath, require.resolve("@anthropic-ai/claude-code/cli-wrapper.cjs")];
|
|
11
|
+
}
|
|
12
|
+
/** Variables du serveur transmises à Claude Code : chemins système et langue, aucun secret. */
|
|
13
|
+
const PASSED_ENV = ["PATH", "LANG", "TMPDIR", "TEMP", "TMP", "SystemRoot", "SYSTEMROOT", "APPDATA", "LOCALAPPDATA"];
|
|
14
|
+
function sessionEnv(runtime, token) {
|
|
15
|
+
const env = { HOME: runtime.home, CLAUDE_CONFIG_DIR: runtime.home, CLAUDE_CODE_OAUTH_TOKEN: token };
|
|
16
|
+
for (const name of PASSED_ENV) {
|
|
17
|
+
if (process.env[name] !== undefined)
|
|
18
|
+
env[name] = process.env[name];
|
|
19
|
+
}
|
|
20
|
+
return env;
|
|
21
|
+
}
|
|
22
|
+
const MAX_LINE = 240;
|
|
23
|
+
function shorten(text) {
|
|
24
|
+
const first = text.trim().split(/\r?\n/)[0];
|
|
25
|
+
return first.length > MAX_LINE ? `${first.slice(0, MAX_LINE)}…` : first;
|
|
26
|
+
}
|
|
27
|
+
/** Appel d'outil en clair : `Read src/app.ts`, `Grep mermaid`, `organizer create_task`. */
|
|
28
|
+
function describeTool(name, input, cwd) {
|
|
29
|
+
const relative = (file) => (typeof file === "string" && path.isAbsolute(file) ? path.relative(cwd, file) || "." : String(file ?? ""));
|
|
30
|
+
if (name === "Read")
|
|
31
|
+
return `Read ${relative(input?.file_path)}`;
|
|
32
|
+
if (name === "Grep")
|
|
33
|
+
return `Grep ${input?.pattern ?? ""}${input?.path ? ` in ${relative(input.path)}` : ""}`;
|
|
34
|
+
if (name === "Glob")
|
|
35
|
+
return `Glob ${input?.pattern ?? ""}`;
|
|
36
|
+
const mcp = /^mcp__(.+?)__(.+)$/.exec(name);
|
|
37
|
+
if (mcp)
|
|
38
|
+
return `${mcp[1]} ${mcp[2]}`;
|
|
39
|
+
return name;
|
|
40
|
+
}
|
|
41
|
+
/** Lecture de la sortie `stream-json` : une ligne JSON par évènement, du texte brut pour les messages de Claude Code lui-même. */
|
|
42
|
+
class StreamReader {
|
|
43
|
+
cwd;
|
|
44
|
+
turns = 0;
|
|
45
|
+
result = null;
|
|
46
|
+
lastText = null;
|
|
47
|
+
messages = new Set();
|
|
48
|
+
pending = new Map();
|
|
49
|
+
constructor(cwd) {
|
|
50
|
+
this.cwd = cwd;
|
|
51
|
+
}
|
|
52
|
+
feed(source, chunk) {
|
|
53
|
+
const text = (this.pending.get(source) ?? "") + chunk;
|
|
54
|
+
const lines = text.split(/\r?\n/);
|
|
55
|
+
this.pending.set(source, lines.pop() ?? "");
|
|
56
|
+
return lines.flatMap((line) => this.line(line));
|
|
57
|
+
}
|
|
58
|
+
flush() {
|
|
59
|
+
const rest = [...this.pending.values()];
|
|
60
|
+
this.pending.clear();
|
|
61
|
+
return rest.flatMap((line) => this.line(line));
|
|
62
|
+
}
|
|
63
|
+
line(raw) {
|
|
64
|
+
const line = raw.trim();
|
|
65
|
+
if (line === "")
|
|
66
|
+
return [];
|
|
67
|
+
let event;
|
|
68
|
+
try {
|
|
69
|
+
event = JSON.parse(line);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
this.lastText = shorten(line);
|
|
73
|
+
return [this.lastText];
|
|
74
|
+
}
|
|
75
|
+
if (event?.type === "assistant")
|
|
76
|
+
return this.assistant(event.message ?? {});
|
|
77
|
+
if (event?.type === "result") {
|
|
78
|
+
this.result = event;
|
|
79
|
+
if (typeof event.result === "string" && event.result.trim())
|
|
80
|
+
this.lastText = shorten(event.result);
|
|
81
|
+
}
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
assistant(message) {
|
|
85
|
+
if (typeof message.id === "string" && !this.messages.has(message.id)) {
|
|
86
|
+
this.messages.add(message.id);
|
|
87
|
+
this.turns += 1;
|
|
88
|
+
}
|
|
89
|
+
const lines = [];
|
|
90
|
+
for (const block of Array.isArray(message.content) ? message.content : []) {
|
|
91
|
+
if (block?.type === "text" && typeof block.text === "string" && block.text.trim()) {
|
|
92
|
+
this.lastText = shorten(block.text);
|
|
93
|
+
lines.push(this.lastText);
|
|
94
|
+
}
|
|
95
|
+
else if (block?.type === "tool_use" && typeof block.name === "string") {
|
|
96
|
+
lines.push(describeTool(block.name, block.input, this.cwd));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return lines;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Lance une session et attend sa fin. Les tours sont limités par Claude Code,
|
|
104
|
+
* la durée par le tracker, qui tue alors la session avec ses descendants, comme
|
|
105
|
+
* à l'annulation par `signal`. Une session qui n'aboutit pas lève une erreur
|
|
106
|
+
* avec sa raison ; une annulation lève `CommandAbortedError`.
|
|
107
|
+
*/
|
|
108
|
+
export function runClaudeSession(runtime, options) {
|
|
109
|
+
if (options.signal?.aborted)
|
|
110
|
+
return Promise.reject(new CommandAbortedError());
|
|
111
|
+
fs.mkdirSync(runtime.home, { recursive: true, mode: 0o700 });
|
|
112
|
+
const [command, ...fixed] = runtime.command;
|
|
113
|
+
const args = [
|
|
114
|
+
...fixed,
|
|
115
|
+
"-p",
|
|
116
|
+
options.prompt,
|
|
117
|
+
"--output-format",
|
|
118
|
+
"stream-json",
|
|
119
|
+
"--verbose",
|
|
120
|
+
"--max-turns",
|
|
121
|
+
String(options.maxTurns),
|
|
122
|
+
"--setting-sources",
|
|
123
|
+
"user",
|
|
124
|
+
"--permission-mode",
|
|
125
|
+
"dontAsk",
|
|
126
|
+
...options.args,
|
|
127
|
+
];
|
|
128
|
+
const reader = new StreamReader(options.cwd);
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const child = spawn(command, args, {
|
|
131
|
+
cwd: options.cwd,
|
|
132
|
+
env: sessionEnv(runtime, options.token),
|
|
133
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
134
|
+
detached: process.platform !== "win32",
|
|
135
|
+
windowsHide: true,
|
|
136
|
+
});
|
|
137
|
+
let settled = false;
|
|
138
|
+
let timedOut = false;
|
|
139
|
+
const stop = () => {
|
|
140
|
+
if (child.pid !== undefined && child.exitCode === null)
|
|
141
|
+
killTree(child.pid);
|
|
142
|
+
};
|
|
143
|
+
const timer = setTimeout(() => {
|
|
144
|
+
timedOut = true;
|
|
145
|
+
stop();
|
|
146
|
+
}, options.maxMinutes * 60_000);
|
|
147
|
+
options.signal?.addEventListener("abort", stop);
|
|
148
|
+
const emit = (lines) => {
|
|
149
|
+
for (const line of lines)
|
|
150
|
+
options.onLine?.(line, reader.turns);
|
|
151
|
+
};
|
|
152
|
+
const finish = (fn) => {
|
|
153
|
+
if (settled)
|
|
154
|
+
return;
|
|
155
|
+
settled = true;
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
options.signal?.removeEventListener("abort", stop);
|
|
158
|
+
fn();
|
|
159
|
+
};
|
|
160
|
+
child.stdout.on("data", (chunk) => emit(reader.feed("stdout", String(chunk))));
|
|
161
|
+
child.stderr.on("data", (chunk) => emit(reader.feed("stderr", String(chunk))));
|
|
162
|
+
child.on("error", (err) => finish(() => reject(new TrackerError(`Cannot start Claude Code: ${err.message}`))));
|
|
163
|
+
child.on("close", (code) => {
|
|
164
|
+
emit(reader.flush());
|
|
165
|
+
finish(() => {
|
|
166
|
+
const result = reader.result;
|
|
167
|
+
if (options.signal?.aborted)
|
|
168
|
+
return reject(new CommandAbortedError());
|
|
169
|
+
if (timedOut)
|
|
170
|
+
return reject(new TrackerError(`Claude Code was stopped after ${options.maxMinutes} min.`));
|
|
171
|
+
if (result?.subtype === "error_max_turns")
|
|
172
|
+
return reject(new TrackerError(`Claude Code reached the limit of ${options.maxTurns} turns.`));
|
|
173
|
+
if (code !== 0 || !result || result.is_error === true) {
|
|
174
|
+
return reject(new TrackerError(`Claude Code stopped (exit code ${code})${reader.lastText ? `: ${reader.lastText}` : "."}`));
|
|
175
|
+
}
|
|
176
|
+
resolve({ structured: result.structured_output, turns: typeof result.num_turns === "number" ? result.num_turns : null });
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/** Vérifie un token d'abonnement par une requête minimale ; lève une erreur avec la réponse de Claude Code s'il est refusé. */
|
|
182
|
+
export async function checkClaudeToken(runtime, token) {
|
|
183
|
+
try {
|
|
184
|
+
await runClaudeSession(runtime, {
|
|
185
|
+
cwd: runtime.home,
|
|
186
|
+
prompt: "Reply with OK.",
|
|
187
|
+
args: ["--tools", "", "--model", "haiku"],
|
|
188
|
+
token,
|
|
189
|
+
maxTurns: 1,
|
|
190
|
+
maxMinutes: 2,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
throw new TrackerError(`The Claude token was refused: ${err?.message ?? err}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -13,6 +13,8 @@ export interface CommandOptions {
|
|
|
13
13
|
export declare class CommandAbortedError extends Error {
|
|
14
14
|
constructor();
|
|
15
15
|
}
|
|
16
|
+
/** Arrête le processus et ses enfants : sous Windows, `npm` tourne dans un `cmd.exe` qui ne transmet pas le signal. */
|
|
17
|
+
export declare function killTree(pid: number): void;
|
|
16
18
|
/**
|
|
17
19
|
* Lance `git` ou `npm` sans shell, et attend sa fin. La commande reçoit
|
|
18
20
|
* l'environnement du serveur sans GITHUB_TOKEN, plus `options.env`. Sous Windows,
|
|
@@ -9,7 +9,7 @@ export class CommandAbortedError extends Error {
|
|
|
9
9
|
}
|
|
10
10
|
const DEFAULT_TIMEOUT_MS = 10 * 60_000;
|
|
11
11
|
/** Arrête le processus et ses enfants : sous Windows, `npm` tourne dans un `cmd.exe` qui ne transmet pas le signal. */
|
|
12
|
-
function killTree(pid) {
|
|
12
|
+
export function killTree(pid) {
|
|
13
13
|
if (process.platform === "win32") {
|
|
14
14
|
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
|
|
15
15
|
return;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type Operation, type OperationKind } from "../../shared/schemas/model.schema.js";
|
|
2
|
+
import type { Settings } from "../../shared/schemas/settings.schema.js";
|
|
3
|
+
import type { ClaudeRuntime } from "./claude.js";
|
|
2
4
|
import type { GitHubConfig } from "./config.js";
|
|
3
5
|
import { type Store } from "./store.js";
|
|
4
6
|
/** Accès aux données et à GitHub pour exécuter les opérations. */
|
|
@@ -10,6 +12,10 @@ export interface OperationContext {
|
|
|
10
12
|
cloneDir: () => string;
|
|
11
13
|
/** Journalise une erreur d'une exécution en arrière-plan qui n'a pas pu être enregistrée dans l'opération. */
|
|
12
14
|
logError: (message: string) => void;
|
|
15
|
+
/** Réglages de l'analyse par Claude, relus à chaque correction. */
|
|
16
|
+
settings: () => Settings;
|
|
17
|
+
/** Commande et dossier de configuration de Claude Code. */
|
|
18
|
+
claude: ClaudeRuntime;
|
|
13
19
|
}
|
|
14
20
|
/** Choix de l'agent pour une opération qu'il mène d'un bout à l'autre. */
|
|
15
21
|
export interface AgentPlan {
|
|
@@ -22,9 +28,9 @@ export declare function branchName(date: Date): string;
|
|
|
22
28
|
/** Vrai pour une branche nommée par `branchName`. */
|
|
23
29
|
export declare function isTrackerBranch(branch: string): boolean;
|
|
24
30
|
/**
|
|
25
|
-
* Lance une correction depuis la GUI : clone, audit
|
|
26
|
-
* en arrière-plan, puis l'opération attend la
|
|
27
|
-
* Refusé sur un dépôt déprécié.
|
|
31
|
+
* Lance une correction depuis la GUI : clone, audit, `npm audit fix` et
|
|
32
|
+
* l'analyse par Claude s'exécutent en arrière-plan, puis l'opération attend la
|
|
33
|
+
* décision sur `--force` ou le push. Refusé sur un dépôt déprécié.
|
|
28
34
|
*/
|
|
29
35
|
export declare function startUserFix(ctx: OperationContext, repoId: string): Operation;
|
|
30
36
|
/**
|
|
@@ -2,6 +2,7 @@ import crypto from "crypto";
|
|
|
2
2
|
import fs from "fs";
|
|
3
3
|
import path from "path";
|
|
4
4
|
import { DEFAULT_COMMIT_MESSAGE, } from "../../shared/schemas/model.schema.js";
|
|
5
|
+
import { analyseVulnerabilities, auditFacts } from "./analysis.js";
|
|
5
6
|
import { CommandAbortedError, runCommand, tail } from "./commands.js";
|
|
6
7
|
import { ConflictError, TrackerError } from "./errors.js";
|
|
7
8
|
import { GitHubClient } from "./github.js";
|
|
@@ -15,6 +16,8 @@ const MAX_LOG_TEXT = 4000;
|
|
|
15
16
|
const CLONE_DIR = "repo";
|
|
16
17
|
/** Paquets listés dans le corps de la pull request. */
|
|
17
18
|
const MAX_PR_CHANGES = 60;
|
|
19
|
+
/** Dernières actions de Claude gardées dans l'opération pendant l'analyse. */
|
|
20
|
+
const ANALYSIS_ACTIVITY = 3;
|
|
18
21
|
function now() {
|
|
19
22
|
return new Date().toISOString();
|
|
20
23
|
}
|
|
@@ -66,7 +69,7 @@ function newOperation(repo, kind, origin) {
|
|
|
66
69
|
workDir: null,
|
|
67
70
|
baseBranch: repo.branch,
|
|
68
71
|
cancelRequested: false,
|
|
69
|
-
steps: { clone: "pending", audit: "pending", fix: "pending", force: "pending", push: "pending" },
|
|
72
|
+
steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", push: "pending" },
|
|
70
73
|
projects: [],
|
|
71
74
|
counts: { initial: null, afterFix: null, afterForce: null },
|
|
72
75
|
found: [],
|
|
@@ -76,6 +79,7 @@ function newOperation(repo, kind, origin) {
|
|
|
76
79
|
commitMessage: DEFAULT_COMMIT_MESSAGE,
|
|
77
80
|
branch: null,
|
|
78
81
|
pullRequest: null,
|
|
82
|
+
analysis: null,
|
|
79
83
|
error: null,
|
|
80
84
|
log: [],
|
|
81
85
|
};
|
|
@@ -87,6 +91,8 @@ class Runner {
|
|
|
87
91
|
signal;
|
|
88
92
|
config;
|
|
89
93
|
cloneDir;
|
|
94
|
+
/** Dernier rapport `npm audit --json` de chaque projet, lu par l'analyse. */
|
|
95
|
+
auditReports = new Map();
|
|
90
96
|
constructor(ctx, id, signal, config, cloneDir) {
|
|
91
97
|
this.ctx = ctx;
|
|
92
98
|
this.id = id;
|
|
@@ -178,7 +184,9 @@ async function cloneStep(runner) {
|
|
|
178
184
|
async function auditAll(runner, count) {
|
|
179
185
|
const vulnerabilities = [];
|
|
180
186
|
for (const project of runner.operation.projects) {
|
|
181
|
-
|
|
187
|
+
const report = await runner.npm(project, ["audit", "--json"]);
|
|
188
|
+
runner.auditReports.set(project, report);
|
|
189
|
+
vulnerabilities.push(...parseAuditReport(report, project));
|
|
182
190
|
}
|
|
183
191
|
runner.log(`${vulnerabilities.length} vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"}`);
|
|
184
192
|
runner.update((operation) => ({
|
|
@@ -217,6 +225,54 @@ async function fixStep(runner, vulnerabilities) {
|
|
|
217
225
|
runner.setStep("fix", "done");
|
|
218
226
|
return remaining;
|
|
219
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Analyse par Claude des vulnérabilités restantes, quand l'analyse automatique
|
|
230
|
+
* est activée ; passée sinon, ou s'il ne reste rien. Son échec est enregistré
|
|
231
|
+
* dans l'analyse et laisse l'opération se poursuivre ; seule une annulation
|
|
232
|
+
* l'interrompt.
|
|
233
|
+
*/
|
|
234
|
+
async function analysisStep(runner, ctx) {
|
|
235
|
+
const settings = ctx.settings();
|
|
236
|
+
if (!settings.analysis.auto || runner.operation.remaining.length === 0) {
|
|
237
|
+
runner.setStep("analysis", "skipped");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
runner.setStep("analysis", "running");
|
|
241
|
+
runner.update((operation) => ({
|
|
242
|
+
...operation,
|
|
243
|
+
analysis: { startedAt: now(), endedAt: null, turns: 0, activity: [], report: null, task: null, error: null },
|
|
244
|
+
}));
|
|
245
|
+
const analysed = (fn) => runner.update((operation) => ({ ...operation, analysis: operation.analysis && fn(operation.analysis) }));
|
|
246
|
+
try {
|
|
247
|
+
const operation = runner.operation;
|
|
248
|
+
const { report, task } = await analyseVulnerabilities({
|
|
249
|
+
repoId: operation.repoId,
|
|
250
|
+
branch: operation.baseBranch,
|
|
251
|
+
cwd: runner.repoDir,
|
|
252
|
+
workDir: operation.workDir,
|
|
253
|
+
facts: operation.projects.flatMap((project) => auditFacts(runner.auditReports.get(project), project)),
|
|
254
|
+
forceCandidates: operation.forceCandidates,
|
|
255
|
+
settings,
|
|
256
|
+
claude: ctx.claude,
|
|
257
|
+
signal: runner.signal,
|
|
258
|
+
onLine: (line, turns) => {
|
|
259
|
+
runner.log(`claude: ${line}`);
|
|
260
|
+
analysed((analysis) => ({ ...analysis, turns, activity: [...analysis.activity, line].slice(-ANALYSIS_ACTIVITY) }));
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
runner.log(`Organizer task ${task.key}: ${task.url}`);
|
|
264
|
+
analysed((analysis) => ({ ...analysis, endedAt: now(), report, task }));
|
|
265
|
+
runner.setStep("analysis", "done");
|
|
266
|
+
}
|
|
267
|
+
catch (err) {
|
|
268
|
+
if (err instanceof CommandAbortedError || runner.signal.aborted)
|
|
269
|
+
throw err;
|
|
270
|
+
const message = err?.message ?? String(err);
|
|
271
|
+
runner.log(`Analysis failed: ${message}`);
|
|
272
|
+
analysed((analysis) => ({ ...analysis, endedAt: now(), error: message }));
|
|
273
|
+
runner.setStep("analysis", "failed");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
220
276
|
/** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
|
|
221
277
|
async function forceStep(runner) {
|
|
222
278
|
runner.setStep("force", "running");
|
|
@@ -236,6 +292,7 @@ function pullRequestBody(operation) {
|
|
|
236
292
|
`- Vulnerabilities before: ${operation.counts.initial}`,
|
|
237
293
|
`- Vulnerabilities after: ${after}`,
|
|
238
294
|
`- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
|
|
295
|
+
...(operation.analysis?.task ? [`- Remaining vulnerabilities analysed by Claude: organizer task ${operation.analysis.task.key}`] : []),
|
|
239
296
|
"",
|
|
240
297
|
`Updated packages (${operation.changes.length}):`,
|
|
241
298
|
"",
|
|
@@ -364,9 +421,9 @@ function inBackground(ctx, id, run) {
|
|
|
364
421
|
}
|
|
365
422
|
// --- Entrées ---------------------------------------------------------------------
|
|
366
423
|
/**
|
|
367
|
-
* Lance une correction depuis la GUI : clone, audit
|
|
368
|
-
* en arrière-plan, puis l'opération attend la
|
|
369
|
-
* Refusé sur un dépôt déprécié.
|
|
424
|
+
* Lance une correction depuis la GUI : clone, audit, `npm audit fix` et
|
|
425
|
+
* l'analyse par Claude s'exécutent en arrière-plan, puis l'opération attend la
|
|
426
|
+
* décision sur `--force` ou le push. Refusé sur un dépôt déprécié.
|
|
370
427
|
*/
|
|
371
428
|
export function startUserFix(ctx, repoId) {
|
|
372
429
|
ctx.githubConfig();
|
|
@@ -379,6 +436,7 @@ export function startUserFix(ctx, repoId) {
|
|
|
379
436
|
if (vulnerabilities.length === 0)
|
|
380
437
|
return finish(runner);
|
|
381
438
|
await fixStep(runner, vulnerabilities);
|
|
439
|
+
await analysisStep(runner, ctx);
|
|
382
440
|
if (runner.operation.forceCandidates.length > 0) {
|
|
383
441
|
runner.update((current) => ({ ...current, status: "waiting_force" }));
|
|
384
442
|
return;
|
|
@@ -463,6 +521,7 @@ export async function runAgentOperation(ctx, repoId, kind, plan) {
|
|
|
463
521
|
if (kind === "audit" || vulnerabilities.length === 0)
|
|
464
522
|
return finish(runner);
|
|
465
523
|
await fixStep(runner, vulnerabilities);
|
|
524
|
+
runner.setStep("analysis", "skipped");
|
|
466
525
|
if (plan.force && runner.operation.forceCandidates.length > 0) {
|
|
467
526
|
await forceStep(runner);
|
|
468
527
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { TASK_STATUSES } from "../../shared/schemas/model.schema.js";
|
|
2
|
+
export interface OrganizerConnection {
|
|
3
|
+
/** Adresse publique du site, sans barre oblique finale. */
|
|
4
|
+
url: string;
|
|
5
|
+
token: string;
|
|
6
|
+
}
|
|
7
|
+
/** Espace du token et son propriétaire, à qui les tâches de l'analyse sont assignées. */
|
|
8
|
+
export interface OrganizerSpace {
|
|
9
|
+
space: {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
};
|
|
13
|
+
owner: {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
email: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export interface OrganizerTask {
|
|
20
|
+
id: string;
|
|
21
|
+
key: string;
|
|
22
|
+
title: string;
|
|
23
|
+
status: (typeof TASK_STATUSES)[number];
|
|
24
|
+
assigneeIds: string[];
|
|
25
|
+
tags: string[];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Adresse du site, validée : absolue, en https sauf pour un site de cette
|
|
29
|
+
* machine (le token passerait en clair), sans identifiants, requête ni fragment.
|
|
30
|
+
*/
|
|
31
|
+
export declare function organizerUrl(raw: string): string;
|
|
32
|
+
export declare class OrganizerClient {
|
|
33
|
+
private readonly connection;
|
|
34
|
+
constructor(connection: OrganizerConnection);
|
|
35
|
+
/** Adresse de la page d'une tâche sur le site. */
|
|
36
|
+
taskUrl(taskId: string): string;
|
|
37
|
+
/** Espace du token et son propriétaire. */
|
|
38
|
+
space(): Promise<OrganizerSpace>;
|
|
39
|
+
/** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
|
|
40
|
+
task(ref: string): Promise<OrganizerTask>;
|
|
41
|
+
/** Données d'une lecture de l'API agent. Une redirection n'est jamais suivie : le token ne part que vers l'adresse réglée. */
|
|
42
|
+
private get;
|
|
43
|
+
}
|