@imenam/mcp-dependabot-tracker 1.0.10 → 1.0.12

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 +33 -14
  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 +41 -9
  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 +2 -0
  8. package/dist/shared/schemas/model.schema.d.ts +159 -7
  9. package/dist/shared/schemas/model.schema.js +63 -8
  10. package/dist/src/core/analysis.d.ts +26 -1
  11. package/dist/src/core/analysis.js +6 -3
  12. package/dist/src/core/audit-all.d.ts +6 -6
  13. package/dist/src/core/audit-all.js +6 -6
  14. package/dist/src/core/claude.d.ts +2 -0
  15. package/dist/src/core/claude.js +8 -4
  16. package/dist/src/core/commands.d.ts +2 -2
  17. package/dist/src/core/commands.js +1 -1
  18. package/dist/src/core/github.js +2 -1
  19. package/dist/src/core/npm-sandbox.d.ts +17 -0
  20. package/dist/src/core/npm-sandbox.js +89 -0
  21. package/dist/src/core/operations.d.ts +22 -12
  22. package/dist/src/core/operations.js +239 -44
  23. package/dist/src/core/organizer.d.ts +14 -0
  24. package/dist/src/core/organizer.js +17 -2
  25. package/dist/src/core/repair.d.ts +38 -0
  26. package/dist/src/core/repair.js +191 -0
  27. package/dist/src/core/repos.d.ts +11 -8
  28. package/dist/src/core/repos.js +38 -20
  29. package/dist/src/core/store.d.ts +2 -0
  30. package/dist/src/core/store.js +14 -5
  31. package/dist/src/gui-worker.js +20 -3
  32. package/dist/src/index.js +23 -8
  33. package/dist/src/npm-tools.d.ts +10 -0
  34. package/dist/src/npm-tools.js +136 -0
  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-D98CR3xl.js +64 -0
  40. package/gui/dist/assets/index-DETLqB3f.css +1 -0
  41. package/gui/dist/index.html +2 -2
  42. package/package.json +1 -1
  43. package/gui/dist/assets/index-C1Ml-XiM.css +0 -1
  44. package/gui/dist/assets/index-DQPqW5Uq.js +0 -64
@@ -7,6 +7,7 @@ import { CommandAbortedError, runCommand, tail } from "./commands.js";
7
7
  import { ConflictError, TrackerError } from "./errors.js";
8
8
  import { GitHubClient } from "./github.js";
9
9
  import { diffLockfiles, forceCandidates, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
10
+ import { assertSandboxAvailable, repairVulnerabilities } from "./repair.js";
10
11
  import { assertNotDeprecated, isActive } from "./store.js";
11
12
  /** Intervalle de lecture de la demande d'annulation pendant une étape. */
12
13
  const CANCEL_POLL_MS = 500;
@@ -16,8 +17,12 @@ const MAX_LOG_TEXT = 4000;
16
17
  const CLONE_DIR = "repo";
17
18
  /** Paquets listés dans le corps de la pull request. */
18
19
  const MAX_PR_CHANGES = 60;
19
- /** Dernières actions de Claude gardées dans l'opération pendant l'analyse. */
20
+ /** Dernières actions de Claude gardées dans l'opération pendant l'analyse et les corrections. */
20
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>";
21
26
  function now() {
22
27
  return new Date().toISOString();
23
28
  }
@@ -48,6 +53,10 @@ function gitAuthEnv(config) {
48
53
  * que npm 12 classe en dépendances distantes avec `--package-lock-only`.
49
54
  */
50
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
+ }
51
60
  /** Sous-commande git d'une liste d'arguments, après les options `-c clé=valeur`. */
52
61
  function subcommand(args) {
53
62
  let index = 0;
@@ -55,13 +64,14 @@ function subcommand(args) {
55
64
  index += 2;
56
65
  return args[index] ?? "";
57
66
  }
58
- function newOperation(repo, kind, origin) {
67
+ function newOperation(repo, kind, origin, scope) {
59
68
  const createdAt = now();
60
69
  return {
61
70
  id: `op-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`,
62
71
  repoId: repo.id,
63
72
  kind,
64
73
  origin,
74
+ scope,
65
75
  status: "running",
66
76
  createdAt,
67
77
  updatedAt: createdAt,
@@ -69,9 +79,9 @@ function newOperation(repo, kind, origin) {
69
79
  workDir: null,
70
80
  baseBranch: repo.branch,
71
81
  cancelRequested: false,
72
- steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", push: "pending" },
82
+ steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", repair: "pending", push: "pending" },
73
83
  projects: [],
74
- counts: { initial: null, afterFix: null, afterForce: null },
84
+ counts: { initial: null, afterFix: null, afterForce: null, afterRepair: null },
75
85
  found: [],
76
86
  remaining: [],
77
87
  forceCandidates: [],
@@ -80,6 +90,7 @@ function newOperation(repo, kind, origin) {
80
90
  branch: null,
81
91
  pullRequest: null,
82
92
  analysis: null,
93
+ repair: null,
83
94
  error: null,
84
95
  log: [],
85
96
  };
@@ -149,10 +160,21 @@ class Runner {
149
160
  const file = path.join(this.repoDir, project, "package-lock.json");
150
161
  return parseLockfile(fs.readFileSync(file, "utf-8"), project);
151
162
  }
163
+ /**
164
+ * Commit cloné : HEAD tant que le tracker n'a rien commité ; après le commit
165
+ * de `npm audit fix`, son parent, et sans ce commit, la base des corrections
166
+ * par Claude.
167
+ */
168
+ get clonedCommit() {
169
+ const repair = this.operation.repair;
170
+ if (!repair)
171
+ return "HEAD";
172
+ return repair.auditCommit ? `${repair.auditCommit}~1` : repair.base;
173
+ }
152
174
  /** Lockfile du projet tel qu'il est dans le commit cloné. */
153
175
  async originalLock(project) {
154
176
  const file = project === "" ? "package-lock.json" : `${project}/package-lock.json`;
155
- return parseLockfile(await this.git(["show", `HEAD:${file}`]), project);
177
+ return parseLockfile(await this.git(["show", `${this.clonedCommit}:${file}`]), project);
156
178
  }
157
179
  }
158
180
  // --- Étapes -------------------------------------------------------------------
@@ -184,7 +206,7 @@ async function cloneStep(runner) {
184
206
  async function auditAll(runner, count) {
185
207
  const vulnerabilities = [];
186
208
  for (const project of runner.operation.projects) {
187
- const report = await runner.npm(project, ["audit", "--json"]);
209
+ const report = await runner.npm(project, ["audit", ...scopeArgs(runner.operation.scope), "--json"]);
188
210
  runner.auditReports.set(project, report);
189
211
  vulnerabilities.push(...parseAuditReport(report, project));
190
212
  }
@@ -196,6 +218,14 @@ async function auditAll(runner, count) {
196
218
  }));
197
219
  return vulnerabilities;
198
220
  }
221
+ /** Vulnérabilités restantes de chaque projet, d'après un nouvel `npm audit`, sans toucher aux comptes de l'opération. */
222
+ async function currentAuditFacts(runner) {
223
+ const facts = [];
224
+ for (const project of runner.operation.projects) {
225
+ facts.push(...auditFacts(await runner.npm(project, ["audit", ...scopeArgs(runner.operation.scope), "--json"]), project));
226
+ }
227
+ return facts;
228
+ }
199
229
  /** Paquets modifiés depuis le commit cloné, dans tous les projets. */
200
230
  async function refreshChanges(runner) {
201
231
  const changes = [];
@@ -216,7 +246,7 @@ async function fixStep(runner, vulnerabilities) {
216
246
  runner.setStep("fix", "running");
217
247
  const projects = new Set(vulnerabilities.map((vulnerability) => vulnerability.project));
218
248
  for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
219
- await runner.npm(project, ["audit", "fix", "--package-lock-only", "--ignore-scripts", "--json"]);
249
+ await runner.npm(project, ["audit", "fix", ...scopeArgs(runner.operation.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
220
250
  }
221
251
  const remaining = await auditAll(runner, "afterFix");
222
252
  await refreshChanges(runner);
@@ -248,6 +278,7 @@ async function analysisStep(runner, ctx) {
248
278
  const { report, task } = await analyseVulnerabilities({
249
279
  repoId: operation.repoId,
250
280
  branch: operation.baseBranch,
281
+ scope: operation.scope,
251
282
  cwd: runner.repoDir,
252
283
  workDir: operation.workDir,
253
284
  facts: operation.projects.flatMap((project) => auditFacts(runner.auditReports.get(project), project)),
@@ -273,22 +304,132 @@ async function analysisStep(runner, ctx) {
273
304
  runner.setStep("analysis", "failed");
274
305
  }
275
306
  }
307
+ /** Options git qui signent un commit au nom de l'utilisateur du token GitHub. */
308
+ async function commitIdentity(runner) {
309
+ const user = await new GitHubClient(runner.config).getAuthenticatedUser();
310
+ return ["-c", `user.name=${user.name ?? user.login}`, "-c", `user.email=${user.id}+${user.login}@users.noreply.github.com`];
311
+ }
312
+ /** Vrai si l'index contient des changements à commiter. */
313
+ async function hasStagedChanges(runner) {
314
+ return (await runner.git(["diff", "--cached", "--name-only"])).trim() !== "";
315
+ }
316
+ /**
317
+ * Crée la branche de la correction et y commite les lockfiles modifiés par
318
+ * `npm audit fix`, s'ils ont changé ; rend le commit sur lequel reposeront les
319
+ * corrections par Claude, et celui de `npm audit fix`, null sans changement.
320
+ */
321
+ async function commitAuditFixes(runner) {
322
+ const branch = runner.operation.branch ?? branchName(new Date());
323
+ runner.update((operation) => ({ ...operation, branch }));
324
+ await runner.git(["checkout", "-b", branch]);
325
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
326
+ const committed = await hasStagedChanges(runner);
327
+ if (committed)
328
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", runner.operation.commitMessage]);
329
+ const base = (await runner.git(["rev-parse", "HEAD"])).trim();
330
+ return { base, auditCommit: committed ? base : null };
331
+ }
332
+ /**
333
+ * Remplace le commit des corrections par Claude par un seul commit de tout ce
334
+ * qui a changé depuis `base` ; rend ce commit, ou null quand rien n'a changé.
335
+ */
336
+ async function commitRepair(runner, base, message) {
337
+ await runner.git(["reset", "--soft", base]);
338
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
339
+ if (!(await hasStagedChanges(runner)))
340
+ return null;
341
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", message, "-m", CLAUDE_TRAILER]);
342
+ return (await runner.git(["rev-parse", "HEAD"])).trim();
343
+ }
276
344
  /** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
277
345
  async function forceStep(runner) {
278
346
  runner.setStep("force", "running");
279
347
  const projects = new Set(runner.operation.forceCandidates.map((candidate) => candidate.project));
280
348
  for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
281
- await runner.npm(project, ["audit", "fix", "--force", "--package-lock-only", "--ignore-scripts", "--json"]);
349
+ await runner.npm(project, ["audit", "fix", "--force", ...scopeArgs(runner.operation.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
282
350
  }
283
351
  await auditAll(runner, "afterForce");
284
352
  await refreshChanges(runner);
285
353
  runner.setStep("force", "done");
286
354
  }
355
+ /**
356
+ * Corrections par Claude, d'après la tâche de l'analyse et les remarques de
357
+ * l'utilisateur : la première fois, la branche est créée et `npm audit fix`
358
+ * y est commité ; les corrections de Claude font ensuite un seul commit, qui
359
+ * remplace celui d'un passage précédent. Un échec remet le clone dans l'état
360
+ * du passage précédent et garde ses résultats ; seule une annulation
361
+ * interrompt l'opération.
362
+ */
363
+ async function repairStep(runner, ctx) {
364
+ runner.setStep("repair", "running");
365
+ const previous = runner.operation.repair;
366
+ const { base, auditCommit } = previous ?? (await commitAuditFixes(runner));
367
+ const repair = {
368
+ runs: (previous?.runs ?? 0) + 1,
369
+ startedAt: now(),
370
+ endedAt: null,
371
+ turns: 0,
372
+ activity: [],
373
+ base,
374
+ auditCommit,
375
+ commit: previous?.commit ?? null,
376
+ report: previous?.report ?? null,
377
+ task: previous?.task ?? null,
378
+ error: null,
379
+ };
380
+ runner.update((operation) => ({ ...operation, repair }));
381
+ const repaired = (fn) => runner.update((operation) => ({ ...operation, repair: operation.repair && fn(operation.repair) }));
382
+ try {
383
+ const operation = runner.operation;
384
+ const analysisTask = operation.analysis?.task;
385
+ if (!analysisTask)
386
+ throw new TrackerError("The fixes by Claude need the organizer task of the analysis.");
387
+ const { report, task } = await repairVulnerabilities({
388
+ repoId: operation.repoId,
389
+ branch: operation.baseBranch,
390
+ scope: operation.scope,
391
+ cwd: runner.repoDir,
392
+ workDir: operation.workDir,
393
+ facts: await currentAuditFacts(runner),
394
+ forceApplied: operation.steps.force === "done",
395
+ analysisTask: analysisTask.key,
396
+ reportTask: previous?.task?.key ?? null,
397
+ settings: ctx.settings(),
398
+ claude: ctx.claude,
399
+ signal: runner.signal,
400
+ onLine: (line, turns) => {
401
+ runner.log(`claude: ${line}`);
402
+ repaired((current) => ({ ...current, turns, activity: [...current.activity, line].slice(-ANALYSIS_ACTIVITY) }));
403
+ },
404
+ });
405
+ const commit = await commitRepair(runner, base, report.commitMessage);
406
+ runner.log(`Development report ${task.key}: ${task.url}`);
407
+ await auditAll(runner, "afterRepair");
408
+ await refreshChanges(runner);
409
+ repaired((current) => ({ ...current, endedAt: now(), commit, report, task }));
410
+ runner.setStep("repair", "done");
411
+ }
412
+ catch (err) {
413
+ if (err instanceof CommandAbortedError || runner.signal.aborted)
414
+ throw err;
415
+ const message = err?.message ?? String(err);
416
+ runner.log(`Fixes by Claude failed: ${message}`);
417
+ await runner.git(["reset", "--hard", "HEAD"]);
418
+ await runner.git(["clean", "-fd", "-e", "node_modules"]);
419
+ repaired((current) => ({ ...current, endedAt: now(), error: message }));
420
+ runner.setStep("repair", previous?.report ? "done" : "failed");
421
+ }
422
+ }
287
423
  function pullRequestBody(operation) {
288
- const after = operation.counts.afterForce ?? operation.counts.afterFix;
424
+ const after = operation.counts.afterRepair ?? operation.counts.afterForce ?? operation.counts.afterFix;
425
+ const repair = operation.repair?.report ? operation.repair : null;
426
+ const command = ["npm audit fix", ...scopeArgs(operation.scope), "--package-lock-only --ignore-scripts"].join(" ");
289
427
  const lines = [
290
- "Automated `npm audit` fixes, made by mcp-dependabot-tracker in a temporary clone (`npm audit fix --package-lock-only --ignore-scripts`).",
428
+ `Automated \`npm audit\` fixes, made by mcp-dependabot-tracker in a temporary clone (\`${command}\`).`,
291
429
  "",
430
+ operation.scope === "production"
431
+ ? "- Scope: production dependencies only; the vulnerabilities of the devDependencies were neither audited nor fixed."
432
+ : "- Scope: all dependencies, devDependencies included.",
292
433
  `- Vulnerabilities before: ${operation.counts.initial}`,
293
434
  `- Vulnerabilities after: ${after}`,
294
435
  `- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
@@ -302,31 +443,34 @@ function pullRequestBody(operation) {
302
443
  }
303
444
  if (operation.changes.length > MAX_PR_CHANGES)
304
445
  lines.push(`- … and ${operation.changes.length - MAX_PR_CHANGES} more`);
446
+ if (repair?.report) {
447
+ lines.push("", `Fixes by Claude Code${repair.task ? `, detailed in organizer task ${repair.task.key}` : ""}:`, "", repair.report.summary, "");
448
+ for (const change of repair.report.changes)
449
+ lines.push(`- \`${change.file}\`: ${change.change}`);
450
+ lines.push(`- Tests: ${repair.report.tests.outcome.replace("_", " ")} — ${repair.report.tests.detail}`);
451
+ }
305
452
  return lines.join("\n");
306
453
  }
307
- /** Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull request vers la branche par défaut. */
454
+ /**
455
+ * Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull
456
+ * request vers la branche analysée. Après des corrections par Claude, la
457
+ * branche et ses commits existent déjà : seuls le push et la pull request
458
+ * restent à faire.
459
+ */
308
460
  async function pushStep(runner) {
309
461
  runner.setStep("push", "running");
310
462
  const operation = runner.operation;
311
463
  const [owner, name] = operation.repoId.split("/");
312
464
  const github = new GitHubClient(runner.config);
313
- const user = await github.getAuthenticatedUser();
314
465
  const branch = operation.branch ?? branchName(new Date());
315
466
  runner.update((current) => ({ ...current, branch }));
316
- await runner.git(["checkout", "-b", branch]);
317
- await runner.git(["add", "-A"]);
318
- if ((await runner.git(["status", "--porcelain"])).trim() === "") {
319
- throw new TrackerError("Nothing to commit: the fixes left the files unchanged.");
320
- }
321
- await runner.git([
322
- "-c",
323
- `user.name=${user.name ?? user.login}`,
324
- "-c",
325
- `user.email=${user.id}+${user.login}@users.noreply.github.com`,
326
- "commit",
327
- "-m",
328
- operation.commitMessage,
329
- ]);
467
+ if (!operation.repair) {
468
+ await runner.git(["checkout", "-b", branch]);
469
+ await runner.git(["add", "-A", ...STAGED_PATHS]);
470
+ if (!(await hasStagedChanges(runner)))
471
+ throw new TrackerError("Nothing to commit: the fixes left the files unchanged.");
472
+ await runner.git([...(await commitIdentity(runner)), "commit", "-m", operation.commitMessage]);
473
+ }
330
474
  await runner.git(["push", "origin", `HEAD:refs/heads/${branch}`], { auth: true });
331
475
  const title = operation.commitMessage.split(/\r?\n/)[0];
332
476
  let pullRequest;
@@ -354,13 +498,36 @@ function finish(runner) {
354
498
  * branche qui sera poussée, ou l'opération se termine s'il n'y a rien à pousser.
355
499
  */
356
500
  function settleForPush(runner) {
357
- if (runner.operation.changes.length > 0) {
358
- runner.update((operation) => ({ ...operation, status: "waiting_push", branch: branchName(new Date()) }));
501
+ const operation = runner.operation;
502
+ if (operation.changes.length > 0 || operation.repair?.auditCommit || operation.repair?.commit) {
503
+ runner.update((current) => ({ ...current, status: "waiting_push", branch: current.branch ?? branchName(new Date()) }));
359
504
  }
360
505
  else {
361
506
  finish(runner);
362
507
  }
363
508
  }
509
+ /** Vrai quand Claude peut corriger : son analyse a créé une tâche et des vulnérabilités restent. */
510
+ function canRepair(operation) {
511
+ return operation.analysis?.task != null && operation.remaining.length > 0;
512
+ }
513
+ /** 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. */
514
+ function settleAfterFixes(runner) {
515
+ if (canRepair(runner.operation)) {
516
+ runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
517
+ return;
518
+ }
519
+ runner.setStep("repair", "skipped");
520
+ settleForPush(runner);
521
+ }
522
+ /** Après un passage de Claude : le push attend quand un passage a abouti, sinon les corrections attendent de nouveau. */
523
+ function settleAfterRepair(runner) {
524
+ if (runner.operation.repair?.report) {
525
+ settleForPush(runner);
526
+ }
527
+ else {
528
+ runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
529
+ }
530
+ }
364
531
  /**
365
532
  * Exécute `body` pour l'opération `id`, avec un signal déclenché par une demande
366
533
  * d'annulation enregistrée par n'importe quel processus. Une erreur fait échouer
@@ -421,15 +588,16 @@ function inBackground(ctx, id, run) {
421
588
  }
422
589
  // --- Entrées ---------------------------------------------------------------------
423
590
  /**
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é.
591
+ * Lance une correction depuis la GUI, sur le périmètre `scope` : clone, audit,
592
+ * `npm audit fix` et l'analyse par Claude s'exécutent en arrière-plan, puis
593
+ * l'opération attend la décision sur `--force`, les corrections par Claude ou
594
+ * le push. Refusé sur un dépôt déprécié.
427
595
  */
428
- export function startUserFix(ctx, repoId) {
596
+ export function startUserFix(ctx, repoId, scope) {
429
597
  ctx.githubConfig();
430
598
  const repo = ctx.store.getRepo(repoId);
431
599
  assertNotDeprecated(repo);
432
- const operation = ctx.store.createOperation(newOperation(repo, "fix", "user"));
600
+ const operation = ctx.store.createOperation(newOperation(repo, "fix", "user", scope));
433
601
  inBackground(ctx, operation.id, execute(ctx, operation.id, async (runner) => {
434
602
  await cloneStep(runner);
435
603
  const vulnerabilities = await auditStep(runner);
@@ -442,20 +610,20 @@ export function startUserFix(ctx, repoId) {
442
610
  return;
443
611
  }
444
612
  runner.setStep("force", "skipped");
445
- settleForPush(runner);
613
+ settleAfterFixes(runner);
446
614
  }));
447
615
  return operation;
448
616
  }
449
617
  /**
450
- * Audit de la branche par défaut, celle que Dependabot analyse, lancé par
451
- * l'utilisateur et attendu jusqu'à sa fin. Refusé si une opération est en
452
- * cours sur le dépôt, ou s'il est déprécié.
618
+ * Audit de la branche par défaut, celle que Dependabot analyse, sur le
619
+ * périmètre `scope`, lancé par l'utilisateur et attendu jusqu'à sa fin. Refusé
620
+ * si une opération est en cours sur le dépôt, ou s'il est déprécié.
453
621
  */
454
- export async function runDefaultBranchAudit(ctx, repoId) {
622
+ export async function runDefaultBranchAudit(ctx, repoId, scope) {
455
623
  ctx.githubConfig();
456
624
  const repo = ctx.store.getRepo(repoId);
457
625
  assertNotDeprecated(repo);
458
- const operation = ctx.store.createOperation({ ...newOperation(repo, "audit", "user"), baseBranch: repo.defaultBranch });
626
+ const operation = ctx.store.createOperation({ ...newOperation(repo, "audit", "user", scope), baseBranch: repo.defaultBranch });
459
627
  return execute(ctx, operation.id, async (runner) => {
460
628
  await cloneStep(runner);
461
629
  await auditStep(runner);
@@ -472,7 +640,33 @@ export function decideForce(ctx, id, apply) {
472
640
  else {
473
641
  runner.setStep("force", "skipped");
474
642
  }
475
- settleForPush(runner);
643
+ settleAfterFixes(runner);
644
+ }));
645
+ return operation;
646
+ }
647
+ /**
648
+ * Lance ou passe les corrections par Claude d'une opération qui les attend ;
649
+ * `run` sur une opération qui attend le push après un passage relance Claude
650
+ * avec les remarques de l'utilisateur. Un lancement est refusé tant que le
651
+ * bac à sable de Claude Code ne peut pas démarrer sur le serveur.
652
+ */
653
+ export async function decideRepair(ctx, id, run) {
654
+ if (run)
655
+ await assertSandboxAvailable();
656
+ const relaunch = run && ctx.store.getOperation(id).status === "waiting_push";
657
+ const operation = resume(ctx, id, relaunch ? "waiting_push" : "waiting_repair", (current) => {
658
+ if (relaunch && !current.repair?.report)
659
+ throw new ConflictError(`Operation ${id} has no fixes by Claude to run again.`);
660
+ return current;
661
+ });
662
+ inBackground(ctx, id, execute(ctx, id, async (runner) => {
663
+ if (!run) {
664
+ runner.setStep("repair", "skipped");
665
+ settleForPush(runner);
666
+ return;
667
+ }
668
+ await repairStep(runner, ctx);
669
+ settleAfterRepair(runner);
476
670
  }));
477
671
  return operation;
478
672
  }
@@ -506,15 +700,16 @@ export function cancelOperation(ctx, id) {
506
700
  return cleanUp(ctx, operation.id);
507
701
  }
508
702
  /**
509
- * Opération menée par l'agent d'un bout à l'autre, attendue jusqu'à sa fin :
510
- * `audit` s'arrête après `npm audit` ; `fix` enchaîne `npm audit fix`, puis
511
- * `--force` et le push selon `plan`. Refusé sur un dépôt déprécié.
703
+ * Opération menée par l'agent d'un bout à l'autre, sur le périmètre de `plan`,
704
+ * attendue jusqu'à sa fin : `audit` s'arrête après `npm audit` ; `fix` enchaîne
705
+ * `npm audit fix`, puis `--force` et le push selon `plan`. Refusé sur un dépôt
706
+ * déprécié.
512
707
  */
513
708
  export async function runAgentOperation(ctx, repoId, kind, plan) {
514
709
  ctx.githubConfig();
515
710
  const repo = ctx.store.getRepo(repoId);
516
711
  assertNotDeprecated(repo);
517
- const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent"), commitMessage: plan.commitMessage });
712
+ const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent", plan.scope), commitMessage: plan.commitMessage });
518
713
  return execute(ctx, operation.id, async (runner) => {
519
714
  await cloneStep(runner);
520
715
  const vulnerabilities = await auditStep(runner);
@@ -16,14 +16,22 @@ export interface OrganizerSpace {
16
16
  email: string;
17
17
  };
18
18
  }
19
+ /** Tâche de l'espace ; `parentKey` est la clé de sa tâche parente, null pour une tâche de premier niveau. */
19
20
  export interface OrganizerTask {
20
21
  id: string;
21
22
  key: string;
22
23
  title: string;
23
24
  status: (typeof TASK_STATUSES)[number];
25
+ parentKey: string | null;
24
26
  assigneeIds: string[];
25
27
  tags: string[];
26
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
+ }
27
35
  /**
28
36
  * Adresse du site, validée : absolue, en https sauf pour un site de cette
29
37
  * machine (le token passerait en clair), sans identifiants, requête ni fragment.
@@ -38,6 +46,12 @@ export declare class OrganizerClient {
38
46
  space(): Promise<OrganizerSpace>;
39
47
  /** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
40
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;
41
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. */
42
56
  private get;
43
57
  }
@@ -49,16 +49,31 @@ export class OrganizerClient {
49
49
  }
50
50
  /** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
51
51
  async task(ref) {
52
- const task = (await this.get(`tasks/${encodeURIComponent(ref)}`))?.task;
52
+ return this.parseTask((await this.get(`tasks/${encodeURIComponent(ref)}`))?.task, ref);
53
+ }
54
+ /** Tâche de l'espace et ses commentaires récents, du plus ancien au plus récent. */
55
+ async taskWithComments(ref) {
56
+ const data = await this.get(`tasks/${encodeURIComponent(ref)}`);
57
+ const comments = data?.comments;
58
+ if (!Array.isArray(comments) || !comments.every((comment) => typeof comment?.authorName === "string" && typeof comment.body === "string" && typeof comment.createdAt === "string")) {
59
+ throw new TrackerError(`The organizer at ${this.connection.url} sent an unexpected answer for the comments of task ${ref}: check that it is up to date.`);
60
+ }
61
+ return {
62
+ task: this.parseTask(data.task, ref),
63
+ comments: comments.map((comment) => ({ author: comment.authorName, body: comment.body, createdAt: comment.createdAt })),
64
+ };
65
+ }
66
+ parseTask(task, ref) {
53
67
  if (typeof task?.id !== "string" ||
54
68
  typeof task.key !== "string" ||
55
69
  typeof task.title !== "string" ||
56
70
  !TASK_STATUSES.includes(task.status) ||
71
+ (task.parentKey !== null && typeof task.parentKey !== "string") ||
57
72
  !Array.isArray(task.assigneeIds) ||
58
73
  !Array.isArray(task.tags)) {
59
74
  throw new TrackerError(`The organizer at ${this.connection.url} sent an unexpected answer for task ${ref}: check that it is up to date.`);
60
75
  }
61
- return { id: task.id, key: task.key, title: task.title, status: task.status, assigneeIds: task.assigneeIds, tags: task.tags };
76
+ return { id: task.id, key: task.key, title: task.title, status: task.status, parentKey: task.parentKey, assigneeIds: task.assigneeIds, tags: task.tags };
62
77
  }
63
78
  /** 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. */
64
79
  async get(path) {
@@ -0,0 +1,38 @@
1
+ import type { RemarksResponse } from "../../shared/schemas/api.schema.js";
2
+ import { type AnalysisTask, type AuditScope, type Operation, type RepairReport } from "../../shared/schemas/model.schema.js";
3
+ import type { Settings } from "../../shared/schemas/settings.schema.js";
4
+ import { type ClaudeRuntime } from "./claude.js";
5
+ /**
6
+ * Vérifie, sous Linux, que bubblewrap crée un bac à sable pour le compte et
7
+ * avec les restrictions du serveur : le tracker s'en sert pour lancer les
8
+ * commandes npm de Claude, et Claude Code refuse de démarrer sans lui. Lève une erreur qui
9
+ * dit quoi installer ou régler ; sans effet sur les autres systèmes.
10
+ */
11
+ export declare function assertSandboxAvailable(platform?: NodeJS.Platform, command?: string): Promise<void>;
12
+ export interface RepairInput {
13
+ repoId: string;
14
+ branch: string;
15
+ scope: AuditScope;
16
+ /** Clone du dépôt : dossier de travail de Claude. */
17
+ cwd: string;
18
+ /** Dossier de l'opération, hors du clone : configuration MCP de la session. */
19
+ workDir: string;
20
+ /** Vulnérabilités restantes, d'après `npm audit --json`. */
21
+ facts: unknown[];
22
+ forceApplied: boolean;
23
+ /** Clé de la tâche de l'analyse, dont les commentaires portent les remarques de l'utilisateur. */
24
+ analysisTask: string;
25
+ /** Clé de la sous-tâche d'un passage précédent, dont le clone contient encore les corrections. */
26
+ reportTask: string | null;
27
+ settings: Settings;
28
+ claude: ClaudeRuntime;
29
+ signal: AbortSignal;
30
+ onLine: (line: string, turns: number) => void;
31
+ }
32
+ /** Tâche de l'analyse d'une opération et ses commentaires : les remarques que Claude prendra en compte. */
33
+ export declare function analysisRemarks(settings: Settings, operation: Operation): Promise<RemarksResponse>;
34
+ /** Lance les corrections, puis vérifie sur l'organizer la sous-tâche que Claude dit avoir créée ou mise à jour. */
35
+ export declare function repairVulnerabilities(input: RepairInput): Promise<{
36
+ report: RepairReport;
37
+ task: AnalysisTask;
38
+ }>;