@imenam/mcp-dependabot-tracker 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +69 -18
  2. package/dist/shared/alerts.d.ts +6 -1
  3. package/dist/shared/alerts.js +7 -0
  4. package/dist/shared/schemas/api.schema.d.ts +45 -10
  5. package/dist/shared/schemas/api.schema.js +5 -1
  6. package/dist/shared/schemas/ipc.schema.d.ts +1 -1
  7. package/dist/shared/schemas/ipc.schema.js +5 -0
  8. package/dist/shared/schemas/model.schema.d.ts +259 -7
  9. package/dist/shared/schemas/model.schema.js +95 -8
  10. package/dist/shared/schemas/settings.schema.d.ts +78 -0
  11. package/dist/shared/schemas/settings.schema.js +42 -0
  12. package/dist/src/core/analysis.d.ts +54 -0
  13. package/dist/src/core/analysis.js +180 -0
  14. package/dist/src/core/audit-all.d.ts +6 -6
  15. package/dist/src/core/audit-all.js +6 -6
  16. package/dist/src/core/claude.d.ts +45 -0
  17. package/dist/src/core/claude.js +200 -0
  18. package/dist/src/core/commands.d.ts +2 -0
  19. package/dist/src/core/commands.js +1 -1
  20. package/dist/src/core/github.js +2 -1
  21. package/dist/src/core/operations.d.ts +27 -12
  22. package/dist/src/core/operations.js +282 -42
  23. package/dist/src/core/organizer.d.ts +57 -0
  24. package/dist/src/core/organizer.js +110 -0
  25. package/dist/src/core/repair.d.ts +31 -0
  26. package/dist/src/core/repair.js +150 -0
  27. package/dist/src/core/repos.d.ts +14 -9
  28. package/dist/src/core/repos.js +45 -20
  29. package/dist/src/core/settings.d.ts +21 -0
  30. package/dist/src/core/settings.js +108 -0
  31. package/dist/src/core/store.d.ts +2 -0
  32. package/dist/src/core/store.js +20 -6
  33. package/dist/src/gui-worker.js +29 -3
  34. package/dist/src/index.js +47 -9
  35. package/dist/src/tools/format.js +20 -8
  36. package/dist/src/tools/tools.js +8 -6
  37. package/dist/src/tools/types.d.ts +2 -0
  38. package/dist/src/tools/types.js +9 -0
  39. package/gui/dist/assets/index-CPYr3dz7.css +1 -0
  40. package/gui/dist/assets/index-CSbeloLm.js +64 -0
  41. package/gui/dist/index.html +2 -2
  42. package/package.json +2 -1
  43. package/gui/dist/assets/index-BdMhGHUf.css +0 -1
  44. package/gui/dist/assets/index-CIIsKFR9.js +0 -64
@@ -2,10 +2,12 @@ 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";
8
9
  import { diffLockfiles, forceCandidates, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
10
+ import { repairVulnerabilities } from "./repair.js";
9
11
  import { assertNotDeprecated, isActive } from "./store.js";
10
12
  /** Intervalle de lecture de la demande d'annulation pendant une étape. */
11
13
  const CANCEL_POLL_MS = 500;
@@ -15,6 +17,12 @@ const MAX_LOG_TEXT = 4000;
15
17
  const CLONE_DIR = "repo";
16
18
  /** Paquets listés dans le corps de la pull request. */
17
19
  const MAX_PR_CHANGES = 60;
20
+ /** Dernières actions de Claude gardées dans l'opération pendant l'analyse et les corrections. */
21
+ const ANALYSIS_ACTIVITY = 3;
22
+ /** Fichiers suivis par les commits du tracker : tout le clone, sauf les node_modules qu'installe Claude. */
23
+ const STAGED_PATHS = ["--", ".", ":(exclude,glob)**/node_modules/**"];
24
+ /** Co-auteur du commit des corrections par Claude. */
25
+ const CLAUDE_TRAILER = "Co-Authored-By: Claude <noreply@anthropic.com>";
18
26
  function now() {
19
27
  return new Date().toISOString();
20
28
  }
@@ -45,6 +53,10 @@ function gitAuthEnv(config) {
45
53
  * que npm 12 classe en dépendances distantes avec `--package-lock-only`.
46
54
  */
47
55
  const NPM_ENV = { npm_config_update_notifier: "false", npm_config_fund: "false", npm_config_allow_remote: "all" };
56
+ /** Options npm qui limitent l'audit et ses corrections au périmètre `scope`. */
57
+ function scopeArgs(scope) {
58
+ return scope === "production" ? ["--omit=dev"] : [];
59
+ }
48
60
  /** Sous-commande git d'une liste d'arguments, après les options `-c clé=valeur`. */
49
61
  function subcommand(args) {
50
62
  let index = 0;
@@ -52,13 +64,14 @@ function subcommand(args) {
52
64
  index += 2;
53
65
  return args[index] ?? "";
54
66
  }
55
- function newOperation(repo, kind, origin) {
67
+ function newOperation(repo, kind, origin, scope) {
56
68
  const createdAt = now();
57
69
  return {
58
70
  id: `op-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`,
59
71
  repoId: repo.id,
60
72
  kind,
61
73
  origin,
74
+ scope,
62
75
  status: "running",
63
76
  createdAt,
64
77
  updatedAt: createdAt,
@@ -66,9 +79,9 @@ function newOperation(repo, kind, origin) {
66
79
  workDir: null,
67
80
  baseBranch: repo.branch,
68
81
  cancelRequested: false,
69
- steps: { clone: "pending", audit: "pending", fix: "pending", force: "pending", push: "pending" },
82
+ steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", repair: "pending", push: "pending" },
70
83
  projects: [],
71
- counts: { initial: null, afterFix: null, afterForce: null },
84
+ counts: { initial: null, afterFix: null, afterForce: null, afterRepair: null },
72
85
  found: [],
73
86
  remaining: [],
74
87
  forceCandidates: [],
@@ -76,6 +89,8 @@ function newOperation(repo, kind, origin) {
76
89
  commitMessage: DEFAULT_COMMIT_MESSAGE,
77
90
  branch: null,
78
91
  pullRequest: null,
92
+ analysis: null,
93
+ repair: null,
79
94
  error: null,
80
95
  log: [],
81
96
  };
@@ -87,6 +102,8 @@ class Runner {
87
102
  signal;
88
103
  config;
89
104
  cloneDir;
105
+ /** Dernier rapport `npm audit --json` de chaque projet, lu par l'analyse. */
106
+ auditReports = new Map();
90
107
  constructor(ctx, id, signal, config, cloneDir) {
91
108
  this.ctx = ctx;
92
109
  this.id = id;
@@ -178,7 +195,9 @@ async function cloneStep(runner) {
178
195
  async function auditAll(runner, count) {
179
196
  const vulnerabilities = [];
180
197
  for (const project of runner.operation.projects) {
181
- vulnerabilities.push(...parseAuditReport(await runner.npm(project, ["audit", "--json"]), project));
198
+ const report = await runner.npm(project, ["audit", ...scopeArgs(runner.operation.scope), "--json"]);
199
+ runner.auditReports.set(project, report);
200
+ vulnerabilities.push(...parseAuditReport(report, project));
182
201
  }
183
202
  runner.log(`${vulnerabilities.length} vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"}`);
184
203
  runner.update((operation) => ({
@@ -188,6 +207,14 @@ async function auditAll(runner, count) {
188
207
  }));
189
208
  return vulnerabilities;
190
209
  }
210
+ /** Vulnérabilités restantes de chaque projet, d'après un nouvel `npm audit`, sans toucher aux comptes de l'opération. */
211
+ async function currentAuditFacts(runner) {
212
+ const facts = [];
213
+ for (const project of runner.operation.projects) {
214
+ facts.push(...auditFacts(await runner.npm(project, ["audit", ...scopeArgs(runner.operation.scope), "--json"]), project));
215
+ }
216
+ return facts;
217
+ }
191
218
  /** Paquets modifiés depuis le commit cloné, dans tous les projets. */
192
219
  async function refreshChanges(runner) {
193
220
  const changes = [];
@@ -208,7 +235,7 @@ async function fixStep(runner, vulnerabilities) {
208
235
  runner.setStep("fix", "running");
209
236
  const projects = new Set(vulnerabilities.map((vulnerability) => vulnerability.project));
210
237
  for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
211
- await runner.npm(project, ["audit", "fix", "--package-lock-only", "--ignore-scripts", "--json"]);
238
+ await runner.npm(project, ["audit", "fix", ...scopeArgs(runner.operation.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
212
239
  }
213
240
  const remaining = await auditAll(runner, "afterFix");
214
241
  await refreshChanges(runner);
@@ -217,25 +244,185 @@ async function fixStep(runner, vulnerabilities) {
217
244
  runner.setStep("fix", "done");
218
245
  return remaining;
219
246
  }
247
+ /**
248
+ * Analyse par Claude des vulnérabilités restantes, quand l'analyse automatique
249
+ * est activée ; passée sinon, ou s'il ne reste rien. Son échec est enregistré
250
+ * dans l'analyse et laisse l'opération se poursuivre ; seule une annulation
251
+ * l'interrompt.
252
+ */
253
+ async function analysisStep(runner, ctx) {
254
+ const settings = ctx.settings();
255
+ if (!settings.analysis.auto || runner.operation.remaining.length === 0) {
256
+ runner.setStep("analysis", "skipped");
257
+ return;
258
+ }
259
+ runner.setStep("analysis", "running");
260
+ runner.update((operation) => ({
261
+ ...operation,
262
+ analysis: { startedAt: now(), endedAt: null, turns: 0, activity: [], report: null, task: null, error: null },
263
+ }));
264
+ const analysed = (fn) => runner.update((operation) => ({ ...operation, analysis: operation.analysis && fn(operation.analysis) }));
265
+ try {
266
+ const operation = runner.operation;
267
+ const { report, task } = await analyseVulnerabilities({
268
+ repoId: operation.repoId,
269
+ branch: operation.baseBranch,
270
+ scope: operation.scope,
271
+ cwd: runner.repoDir,
272
+ workDir: operation.workDir,
273
+ facts: operation.projects.flatMap((project) => auditFacts(runner.auditReports.get(project), project)),
274
+ forceCandidates: operation.forceCandidates,
275
+ settings,
276
+ claude: ctx.claude,
277
+ signal: runner.signal,
278
+ onLine: (line, turns) => {
279
+ runner.log(`claude: ${line}`);
280
+ analysed((analysis) => ({ ...analysis, turns, activity: [...analysis.activity, line].slice(-ANALYSIS_ACTIVITY) }));
281
+ },
282
+ });
283
+ runner.log(`Organizer task ${task.key}: ${task.url}`);
284
+ analysed((analysis) => ({ ...analysis, endedAt: now(), report, task }));
285
+ runner.setStep("analysis", "done");
286
+ }
287
+ catch (err) {
288
+ if (err instanceof CommandAbortedError || runner.signal.aborted)
289
+ throw err;
290
+ const message = err?.message ?? String(err);
291
+ runner.log(`Analysis failed: ${message}`);
292
+ analysed((analysis) => ({ ...analysis, endedAt: now(), error: message }));
293
+ runner.setStep("analysis", "failed");
294
+ }
295
+ }
296
+ /** Options git qui signent un commit au nom de l'utilisateur du token GitHub. */
297
+ async function commitIdentity(runner) {
298
+ const user = await new GitHubClient(runner.config).getAuthenticatedUser();
299
+ return ["-c", `user.name=${user.name ?? user.login}`, "-c", `user.email=${user.id}+${user.login}@users.noreply.github.com`];
300
+ }
301
+ /** Vrai si l'index contient des changements à commiter. */
302
+ async function hasStagedChanges(runner) {
303
+ return (await runner.git(["diff", "--cached", "--name-only"])).trim() !== "";
304
+ }
305
+ /**
306
+ * Crée la branche de la correction et y commite les lockfiles modifiés par
307
+ * `npm audit fix`, s'ils ont changé ; rend le commit sur lequel reposeront les
308
+ * corrections par Claude, et celui de `npm audit fix`, null sans changement.
309
+ */
310
+ async function commitAuditFixes(runner) {
311
+ const branch = runner.operation.branch ?? branchName(new Date());
312
+ runner.update((operation) => ({ ...operation, branch }));
313
+ await runner.git(["checkout", "-b", branch]);
314
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
315
+ const committed = await hasStagedChanges(runner);
316
+ if (committed)
317
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", runner.operation.commitMessage]);
318
+ const base = (await runner.git(["rev-parse", "HEAD"])).trim();
319
+ return { base, auditCommit: committed ? base : null };
320
+ }
321
+ /**
322
+ * Remplace le commit des corrections par Claude par un seul commit de tout ce
323
+ * qui a changé depuis `base` ; rend ce commit, ou null quand rien n'a changé.
324
+ */
325
+ async function commitRepair(runner, base, message) {
326
+ await runner.git(["reset", "--soft", base]);
327
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
328
+ if (!(await hasStagedChanges(runner)))
329
+ return null;
330
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", message, "-m", CLAUDE_TRAILER]);
331
+ return (await runner.git(["rev-parse", "HEAD"])).trim();
332
+ }
220
333
  /** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
221
334
  async function forceStep(runner) {
222
335
  runner.setStep("force", "running");
223
336
  const projects = new Set(runner.operation.forceCandidates.map((candidate) => candidate.project));
224
337
  for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
225
- await runner.npm(project, ["audit", "fix", "--force", "--package-lock-only", "--ignore-scripts", "--json"]);
338
+ await runner.npm(project, ["audit", "fix", "--force", ...scopeArgs(runner.operation.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
226
339
  }
227
340
  await auditAll(runner, "afterForce");
228
341
  await refreshChanges(runner);
229
342
  runner.setStep("force", "done");
230
343
  }
344
+ /**
345
+ * Corrections par Claude, d'après la tâche de l'analyse et les remarques de
346
+ * l'utilisateur : la première fois, la branche est créée et `npm audit fix`
347
+ * y est commité ; les corrections de Claude font ensuite un seul commit, qui
348
+ * remplace celui d'un passage précédent. Un échec remet le clone dans l'état
349
+ * du passage précédent et garde ses résultats ; seule une annulation
350
+ * interrompt l'opération.
351
+ */
352
+ async function repairStep(runner, ctx) {
353
+ runner.setStep("repair", "running");
354
+ const previous = runner.operation.repair;
355
+ const { base, auditCommit } = previous ?? (await commitAuditFixes(runner));
356
+ const repair = {
357
+ runs: (previous?.runs ?? 0) + 1,
358
+ startedAt: now(),
359
+ endedAt: null,
360
+ turns: 0,
361
+ activity: [],
362
+ base,
363
+ auditCommit,
364
+ commit: previous?.commit ?? null,
365
+ report: previous?.report ?? null,
366
+ task: previous?.task ?? null,
367
+ error: null,
368
+ };
369
+ runner.update((operation) => ({ ...operation, repair }));
370
+ const repaired = (fn) => runner.update((operation) => ({ ...operation, repair: operation.repair && fn(operation.repair) }));
371
+ try {
372
+ const operation = runner.operation;
373
+ const analysisTask = operation.analysis?.task;
374
+ if (!analysisTask)
375
+ throw new TrackerError("The fixes by Claude need the organizer task of the analysis.");
376
+ const { report, task } = await repairVulnerabilities({
377
+ repoId: operation.repoId,
378
+ branch: operation.baseBranch,
379
+ scope: operation.scope,
380
+ cwd: runner.repoDir,
381
+ workDir: operation.workDir,
382
+ facts: await currentAuditFacts(runner),
383
+ forceApplied: operation.steps.force === "done",
384
+ analysisTask: analysisTask.key,
385
+ reportTask: previous?.task?.key ?? null,
386
+ settings: ctx.settings(),
387
+ claude: ctx.claude,
388
+ signal: runner.signal,
389
+ onLine: (line, turns) => {
390
+ runner.log(`claude: ${line}`);
391
+ repaired((current) => ({ ...current, turns, activity: [...current.activity, line].slice(-ANALYSIS_ACTIVITY) }));
392
+ },
393
+ });
394
+ const commit = await commitRepair(runner, base, report.commitMessage);
395
+ runner.log(`Development report ${task.key}: ${task.url}`);
396
+ await auditAll(runner, "afterRepair");
397
+ await refreshChanges(runner);
398
+ repaired((current) => ({ ...current, endedAt: now(), commit, report, task }));
399
+ runner.setStep("repair", "done");
400
+ }
401
+ catch (err) {
402
+ if (err instanceof CommandAbortedError || runner.signal.aborted)
403
+ throw err;
404
+ const message = err?.message ?? String(err);
405
+ runner.log(`Fixes by Claude failed: ${message}`);
406
+ await runner.git(["reset", "--hard", "HEAD"]);
407
+ await runner.git(["clean", "-fd", "-e", "node_modules"]);
408
+ repaired((current) => ({ ...current, endedAt: now(), error: message }));
409
+ runner.setStep("repair", previous?.report ? "done" : "failed");
410
+ }
411
+ }
231
412
  function pullRequestBody(operation) {
232
- const after = operation.counts.afterForce ?? operation.counts.afterFix;
413
+ const after = operation.counts.afterRepair ?? operation.counts.afterForce ?? operation.counts.afterFix;
414
+ const repair = operation.repair?.report ? operation.repair : null;
415
+ const command = ["npm audit fix", ...scopeArgs(operation.scope), "--package-lock-only --ignore-scripts"].join(" ");
233
416
  const lines = [
234
- "Automated `npm audit` fixes, made by mcp-dependabot-tracker in a temporary clone (`npm audit fix --package-lock-only --ignore-scripts`).",
417
+ `Automated \`npm audit\` fixes, made by mcp-dependabot-tracker in a temporary clone (\`${command}\`).`,
235
418
  "",
419
+ operation.scope === "production"
420
+ ? "- Scope: production dependencies only; the vulnerabilities of the devDependencies were neither audited nor fixed."
421
+ : "- Scope: all dependencies, devDependencies included.",
236
422
  `- Vulnerabilities before: ${operation.counts.initial}`,
237
423
  `- Vulnerabilities after: ${after}`,
238
424
  `- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
425
+ ...(operation.analysis?.task ? [`- Remaining vulnerabilities analysed by Claude: organizer task ${operation.analysis.task.key}`] : []),
239
426
  "",
240
427
  `Updated packages (${operation.changes.length}):`,
241
428
  "",
@@ -245,31 +432,34 @@ function pullRequestBody(operation) {
245
432
  }
246
433
  if (operation.changes.length > MAX_PR_CHANGES)
247
434
  lines.push(`- … and ${operation.changes.length - MAX_PR_CHANGES} more`);
435
+ if (repair?.report) {
436
+ lines.push("", `Fixes by Claude Code${repair.task ? `, detailed in organizer task ${repair.task.key}` : ""}:`, "", repair.report.summary, "");
437
+ for (const change of repair.report.changes)
438
+ lines.push(`- \`${change.file}\`: ${change.change}`);
439
+ lines.push(`- Tests: ${repair.report.tests.outcome.replace("_", " ")} — ${repair.report.tests.detail}`);
440
+ }
248
441
  return lines.join("\n");
249
442
  }
250
- /** Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull request vers la branche par défaut. */
443
+ /**
444
+ * Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull
445
+ * request vers la branche analysée. Après des corrections par Claude, la
446
+ * branche et ses commits existent déjà : seuls le push et la pull request
447
+ * restent à faire.
448
+ */
251
449
  async function pushStep(runner) {
252
450
  runner.setStep("push", "running");
253
451
  const operation = runner.operation;
254
452
  const [owner, name] = operation.repoId.split("/");
255
453
  const github = new GitHubClient(runner.config);
256
- const user = await github.getAuthenticatedUser();
257
454
  const branch = operation.branch ?? branchName(new Date());
258
455
  runner.update((current) => ({ ...current, branch }));
259
- await runner.git(["checkout", "-b", branch]);
260
- await runner.git(["add", "-A"]);
261
- if ((await runner.git(["status", "--porcelain"])).trim() === "") {
262
- throw new TrackerError("Nothing to commit: the fixes left the files unchanged.");
263
- }
264
- await runner.git([
265
- "-c",
266
- `user.name=${user.name ?? user.login}`,
267
- "-c",
268
- `user.email=${user.id}+${user.login}@users.noreply.github.com`,
269
- "commit",
270
- "-m",
271
- operation.commitMessage,
272
- ]);
456
+ if (!operation.repair) {
457
+ await runner.git(["checkout", "-b", branch]);
458
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
459
+ if (!(await hasStagedChanges(runner)))
460
+ throw new TrackerError("Nothing to commit: the fixes left the files unchanged.");
461
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", operation.commitMessage]);
462
+ }
273
463
  await runner.git(["push", "origin", `HEAD:refs/heads/${branch}`], { auth: true });
274
464
  const title = operation.commitMessage.split(/\r?\n/)[0];
275
465
  let pullRequest;
@@ -297,13 +487,36 @@ function finish(runner) {
297
487
  * branche qui sera poussée, ou l'opération se termine s'il n'y a rien à pousser.
298
488
  */
299
489
  function settleForPush(runner) {
300
- if (runner.operation.changes.length > 0) {
301
- runner.update((operation) => ({ ...operation, status: "waiting_push", branch: branchName(new Date()) }));
490
+ const operation = runner.operation;
491
+ if (operation.changes.length > 0 || operation.repair?.commit) {
492
+ runner.update((current) => ({ ...current, status: "waiting_push", branch: current.branch ?? branchName(new Date()) }));
302
493
  }
303
494
  else {
304
495
  finish(runner);
305
496
  }
306
497
  }
498
+ /** Vrai quand Claude peut corriger : son analyse a créé une tâche et des vulnérabilités restent. */
499
+ function canRepair(operation) {
500
+ return operation.analysis?.task != null && operation.remaining.length > 0;
501
+ }
502
+ /** Après `npm audit fix` et la décision sur `--force` : les corrections par Claude attendent l'utilisateur quand elles sont possibles, sinon le push. */
503
+ function settleAfterFixes(runner) {
504
+ if (canRepair(runner.operation)) {
505
+ runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
506
+ return;
507
+ }
508
+ runner.setStep("repair", "skipped");
509
+ settleForPush(runner);
510
+ }
511
+ /** Après un passage de Claude : le push attend quand un passage a abouti, sinon les corrections attendent de nouveau. */
512
+ function settleAfterRepair(runner) {
513
+ if (runner.operation.repair?.report) {
514
+ settleForPush(runner);
515
+ }
516
+ else {
517
+ runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
518
+ }
519
+ }
307
520
  /**
308
521
  * Exécute `body` pour l'opération `id`, avec un signal déclenché par une demande
309
522
  * d'annulation enregistrée par n'importe quel processus. Une erreur fait échouer
@@ -364,40 +577,42 @@ function inBackground(ctx, id, run) {
364
577
  }
365
578
  // --- Entrées ---------------------------------------------------------------------
366
579
  /**
367
- * Lance une correction depuis la GUI : clone, audit et `npm audit fix` s'exécutent
368
- * en arrière-plan, puis l'opération attend la décision sur `--force` ou le push.
369
- * Refusé sur un dépôt déprécié.
580
+ * Lance une correction depuis la GUI, sur le périmètre `scope` : clone, audit,
581
+ * `npm audit fix` et l'analyse par Claude s'exécutent en arrière-plan, puis
582
+ * l'opération attend la décision sur `--force`, les corrections par Claude ou
583
+ * le push. Refusé sur un dépôt déprécié.
370
584
  */
371
- export function startUserFix(ctx, repoId) {
585
+ export function startUserFix(ctx, repoId, scope) {
372
586
  ctx.githubConfig();
373
587
  const repo = ctx.store.getRepo(repoId);
374
588
  assertNotDeprecated(repo);
375
- const operation = ctx.store.createOperation(newOperation(repo, "fix", "user"));
589
+ const operation = ctx.store.createOperation(newOperation(repo, "fix", "user", scope));
376
590
  inBackground(ctx, operation.id, execute(ctx, operation.id, async (runner) => {
377
591
  await cloneStep(runner);
378
592
  const vulnerabilities = await auditStep(runner);
379
593
  if (vulnerabilities.length === 0)
380
594
  return finish(runner);
381
595
  await fixStep(runner, vulnerabilities);
596
+ await analysisStep(runner, ctx);
382
597
  if (runner.operation.forceCandidates.length > 0) {
383
598
  runner.update((current) => ({ ...current, status: "waiting_force" }));
384
599
  return;
385
600
  }
386
601
  runner.setStep("force", "skipped");
387
- settleForPush(runner);
602
+ settleAfterFixes(runner);
388
603
  }));
389
604
  return operation;
390
605
  }
391
606
  /**
392
- * Audit de la branche par défaut, celle que Dependabot analyse, lancé par
393
- * l'utilisateur et attendu jusqu'à sa fin. Refusé si une opération est en
394
- * cours sur le dépôt, ou s'il est déprécié.
607
+ * Audit de la branche par défaut, celle que Dependabot analyse, sur le
608
+ * périmètre `scope`, lancé par l'utilisateur et attendu jusqu'à sa fin. Refusé
609
+ * si une opération est en cours sur le dépôt, ou s'il est déprécié.
395
610
  */
396
- export async function runDefaultBranchAudit(ctx, repoId) {
611
+ export async function runDefaultBranchAudit(ctx, repoId, scope) {
397
612
  ctx.githubConfig();
398
613
  const repo = ctx.store.getRepo(repoId);
399
614
  assertNotDeprecated(repo);
400
- const operation = ctx.store.createOperation({ ...newOperation(repo, "audit", "user"), baseBranch: repo.defaultBranch });
615
+ const operation = ctx.store.createOperation({ ...newOperation(repo, "audit", "user", scope), baseBranch: repo.defaultBranch });
401
616
  return execute(ctx, operation.id, async (runner) => {
402
617
  await cloneStep(runner);
403
618
  await auditStep(runner);
@@ -414,7 +629,30 @@ export function decideForce(ctx, id, apply) {
414
629
  else {
415
630
  runner.setStep("force", "skipped");
416
631
  }
417
- settleForPush(runner);
632
+ settleAfterFixes(runner);
633
+ }));
634
+ return operation;
635
+ }
636
+ /**
637
+ * Lance ou passe les corrections par Claude d'une opération qui les attend ;
638
+ * `run` sur une opération qui attend le push après un passage relance Claude
639
+ * avec les remarques de l'utilisateur.
640
+ */
641
+ export function decideRepair(ctx, id, run) {
642
+ const relaunch = run && ctx.store.getOperation(id).status === "waiting_push";
643
+ const operation = resume(ctx, id, relaunch ? "waiting_push" : "waiting_repair", (current) => {
644
+ if (relaunch && !current.repair?.report)
645
+ throw new ConflictError(`Operation ${id} has no fixes by Claude to run again.`);
646
+ return current;
647
+ });
648
+ inBackground(ctx, id, execute(ctx, id, async (runner) => {
649
+ if (!run) {
650
+ runner.setStep("repair", "skipped");
651
+ settleForPush(runner);
652
+ return;
653
+ }
654
+ await repairStep(runner, ctx);
655
+ settleAfterRepair(runner);
418
656
  }));
419
657
  return operation;
420
658
  }
@@ -448,21 +686,23 @@ export function cancelOperation(ctx, id) {
448
686
  return cleanUp(ctx, operation.id);
449
687
  }
450
688
  /**
451
- * Opération menée par l'agent d'un bout à l'autre, attendue jusqu'à sa fin :
452
- * `audit` s'arrête après `npm audit` ; `fix` enchaîne `npm audit fix`, puis
453
- * `--force` et le push selon `plan`. Refusé sur un dépôt déprécié.
689
+ * Opération menée par l'agent d'un bout à l'autre, sur le périmètre de `plan`,
690
+ * attendue jusqu'à sa fin : `audit` s'arrête après `npm audit` ; `fix` enchaîne
691
+ * `npm audit fix`, puis `--force` et le push selon `plan`. Refusé sur un dépôt
692
+ * déprécié.
454
693
  */
455
694
  export async function runAgentOperation(ctx, repoId, kind, plan) {
456
695
  ctx.githubConfig();
457
696
  const repo = ctx.store.getRepo(repoId);
458
697
  assertNotDeprecated(repo);
459
- const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent"), commitMessage: plan.commitMessage });
698
+ const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent", plan.scope), commitMessage: plan.commitMessage });
460
699
  return execute(ctx, operation.id, async (runner) => {
461
700
  await cloneStep(runner);
462
701
  const vulnerabilities = await auditStep(runner);
463
702
  if (kind === "audit" || vulnerabilities.length === 0)
464
703
  return finish(runner);
465
704
  await fixStep(runner, vulnerabilities);
705
+ runner.setStep("analysis", "skipped");
466
706
  if (plan.force && runner.operation.forceCandidates.length > 0) {
467
707
  await forceStep(runner);
468
708
  }
@@ -0,0 +1,57 @@
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
+ /** Tâche de l'espace ; `parentKey` est la clé de sa tâche parente, null pour une tâche de premier niveau. */
20
+ export interface OrganizerTask {
21
+ id: string;
22
+ key: string;
23
+ title: string;
24
+ status: (typeof TASK_STATUSES)[number];
25
+ parentKey: string | null;
26
+ assigneeIds: string[];
27
+ tags: string[];
28
+ }
29
+ /** Commentaire d'une tâche ; `author` est le nom de son auteur. */
30
+ export interface OrganizerComment {
31
+ author: string;
32
+ body: string;
33
+ createdAt: string;
34
+ }
35
+ /**
36
+ * Adresse du site, validée : absolue, en https sauf pour un site de cette
37
+ * machine (le token passerait en clair), sans identifiants, requête ni fragment.
38
+ */
39
+ export declare function organizerUrl(raw: string): string;
40
+ export declare class OrganizerClient {
41
+ private readonly connection;
42
+ constructor(connection: OrganizerConnection);
43
+ /** Adresse de la page d'une tâche sur le site. */
44
+ taskUrl(taskId: string): string;
45
+ /** Espace du token et son propriétaire. */
46
+ space(): Promise<OrganizerSpace>;
47
+ /** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
48
+ task(ref: string): Promise<OrganizerTask>;
49
+ /** Tâche de l'espace et ses commentaires récents, du plus ancien au plus récent. */
50
+ taskWithComments(ref: string): Promise<{
51
+ task: OrganizerTask;
52
+ comments: OrganizerComment[];
53
+ }>;
54
+ private parseTask;
55
+ /** 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. */
56
+ private get;
57
+ }