@imenam/mcp-dependabot-tracker 1.0.18 → 1.0.21

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.
@@ -2,13 +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";
6
5
  import { activityLine } from "./claude.js";
7
6
  import { CommandAbortedError, runCommand, tail } from "./commands.js";
8
7
  import { ConflictError, TrackerError } from "./errors.js";
9
8
  import { GitHubClient } from "./github.js";
10
- import { diffLockfiles, forceCandidates, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
11
- import { analysisRemarks, assertSandboxAvailable, repairVulnerabilities } from "./repair.js";
9
+ import { diffLockfiles, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
10
+ import { auditFacts, repairVulnerabilities } from "./repair.js";
12
11
  import { assertNotDeprecated, isActive } from "./store.js";
13
12
  /** Intervalle de lecture de la demande d'annulation pendant une étape. */
14
13
  const CANCEL_POLL_MS = 500;
@@ -18,36 +17,10 @@ const MAX_LOG_TEXT = 4000;
18
17
  const CLONE_DIR = "repo";
19
18
  /** Paquets listés dans le corps de la pull request. */
20
19
  const MAX_PR_CHANGES = 60;
21
- /** Dernières actions de Claude gardées dans l'opération pendant l'analyse et les corrections. */
22
- const ANALYSIS_ACTIVITY = 3;
23
- /** Éléments du déroulé gardés par session de Claude, les plus récents. */
20
+ /** Dernières actions de Claude affichées pendant les corrections. */
21
+ const CLAUDE_ACTIVITY = 3;
22
+ /** Éléments du déroulé de la session de Claude gardés, les plus récents. */
24
23
  const SESSION_EVENTS = 500;
25
- function newSession(kind, run, tasks) {
26
- return {
27
- kind,
28
- run,
29
- startedAt: now(),
30
- endedAt: null,
31
- turns: 0,
32
- outcome: "running",
33
- error: null,
34
- remarks: [],
35
- tasks,
36
- events: [],
37
- analysisReport: null,
38
- repairReport: null,
39
- commit: null,
40
- remaining: null,
41
- };
42
- }
43
- /** Sessions de l'opération, la dernière transformée par `fn`. */
44
- function withLastSession(operation, fn) {
45
- return operation.sessions.map((session, index) => (index === operation.sessions.length - 1 ? fn(session) : session));
46
- }
47
- /** Termine la dernière session : réussie, échouée avec sa raison, ou annulée. */
48
- function endSession(runner, outcome, changes = {}) {
49
- runner.update((operation) => ({ ...operation, sessions: withLastSession(operation, (session) => ({ ...session, ...changes, outcome, endedAt: now() })) }));
50
- }
51
24
  /** Fichiers suivis par les commits du tracker : tout le clone, sauf les node_modules qu'installe Claude. */
52
25
  const STAGED_PATHS = ["--", ".", ":(exclude,glob)**/node_modules/**"];
53
26
  /** Co-auteur du commit des corrections par Claude. */
@@ -108,19 +81,16 @@ function newOperation(repo, kind, origin, scope) {
108
81
  workDir: null,
109
82
  baseBranch: repo.branch,
110
83
  cancelRequested: false,
111
- steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", repair: "pending", push: "pending" },
84
+ steps: { clone: "pending", audit: "pending", fix: "pending", repair: "pending", push: "pending" },
112
85
  projects: [],
113
- counts: { initial: null, afterFix: null, afterForce: null, afterRepair: null },
86
+ counts: { initial: null, afterFix: null, afterRepair: null },
114
87
  found: [],
115
88
  remaining: [],
116
- forceCandidates: [],
117
89
  changes: [],
118
90
  commitMessage: DEFAULT_COMMIT_MESSAGE,
119
91
  branch: null,
120
92
  pullRequest: null,
121
- analysis: null,
122
93
  repair: null,
123
- sessions: [],
124
94
  error: null,
125
95
  log: [],
126
96
  };
@@ -132,8 +102,6 @@ class Runner {
132
102
  signal;
133
103
  config;
134
104
  cloneDir;
135
- /** Dernier rapport `npm audit --json` de chaque projet, lu par l'analyse. */
136
- auditReports = new Map();
137
105
  constructor(ctx, id, signal, config, cloneDir) {
138
106
  this.ctx = ctx;
139
107
  this.id = id;
@@ -237,14 +205,13 @@ async function auditAll(runner, count) {
237
205
  const vulnerabilities = [];
238
206
  for (const project of runner.operation.projects) {
239
207
  const report = await runner.npm(project, ["audit", ...scopeArgs(runner.operation.scope), "--json"]);
240
- runner.auditReports.set(project, report);
241
208
  vulnerabilities.push(...parseAuditReport(report, project));
242
209
  }
243
210
  runner.log(`${vulnerabilities.length} vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"}`);
244
211
  runner.update((operation) => ({
245
212
  ...operation,
246
213
  counts: { ...operation.counts, [count]: vulnerabilities.length },
247
- remaining: vulnerabilities.map(({ project, name, severity, fix }) => ({ project, name, severity, fix })),
214
+ remaining: vulnerabilities,
248
215
  }));
249
216
  return vulnerabilities;
250
217
  }
@@ -280,70 +247,9 @@ async function fixStep(runner, vulnerabilities) {
280
247
  }
281
248
  const remaining = await auditAll(runner, "afterFix");
282
249
  await refreshChanges(runner);
283
- const locks = Object.fromEntries(runner.operation.projects.map((project) => [project, runner.readLock(project)]));
284
- runner.update((operation) => ({ ...operation, forceCandidates: forceCandidates(remaining, locks) }));
285
250
  runner.setStep("fix", "done");
286
251
  return remaining;
287
252
  }
288
- /**
289
- * Analyse par Claude des vulnérabilités restantes, quand l'analyse automatique
290
- * est activée ; passée sinon, ou s'il ne reste rien. Son échec est enregistré
291
- * dans l'analyse et laisse l'opération se poursuivre ; seule une annulation
292
- * l'interrompt.
293
- */
294
- async function analysisStep(runner, ctx) {
295
- const settings = ctx.settings();
296
- if (!settings.analysis.auto || runner.operation.remaining.length === 0) {
297
- runner.setStep("analysis", "skipped");
298
- return;
299
- }
300
- runner.setStep("analysis", "running");
301
- runner.update((operation) => ({
302
- ...operation,
303
- analysis: { startedAt: now(), endedAt: null, turns: 0, activity: [], report: null, task: null, error: null },
304
- sessions: [...operation.sessions, newSession("analysis", 1, [])],
305
- }));
306
- const analysed = (fn) => runner.update((operation) => ({ ...operation, analysis: operation.analysis && fn(operation.analysis) }));
307
- try {
308
- const operation = runner.operation;
309
- const { report, task } = await analyseVulnerabilities({
310
- repoId: operation.repoId,
311
- branch: operation.baseBranch,
312
- scope: operation.scope,
313
- cwd: runner.repoDir,
314
- workDir: operation.workDir,
315
- facts: operation.projects.flatMap((project) => auditFacts(runner.auditReports.get(project), project)),
316
- forceCandidates: operation.forceCandidates,
317
- settings,
318
- claude: ctx.claude,
319
- signal: runner.signal,
320
- onEvent: (event, turns) => {
321
- const line = activityLine(event);
322
- runner.log(`claude: ${line}`);
323
- runner.update((current) => ({
324
- ...current,
325
- analysis: current.analysis && { ...current.analysis, turns, activity: [...current.analysis.activity, line].slice(-ANALYSIS_ACTIVITY) },
326
- sessions: withLastSession(current, (session) => ({ ...session, turns, events: [...session.events, event].slice(-SESSION_EVENTS) })),
327
- }));
328
- },
329
- });
330
- runner.log(`Organizer task ${task.key}: ${task.url}`);
331
- analysed((analysis) => ({ ...analysis, endedAt: now(), report, task }));
332
- endSession(runner, "done", { tasks: [{ task, role: "created" }], analysisReport: report });
333
- runner.setStep("analysis", "done");
334
- }
335
- catch (err) {
336
- if (err instanceof CommandAbortedError || runner.signal.aborted) {
337
- endSession(runner, "cancelled");
338
- throw err;
339
- }
340
- const message = err?.message ?? String(err);
341
- runner.log(`Analysis failed: ${message}`);
342
- analysed((analysis) => ({ ...analysis, endedAt: now(), error: message }));
343
- endSession(runner, "failed", { error: message });
344
- runner.setStep("analysis", "failed");
345
- }
346
- }
347
253
  /** Options git qui signent un commit au nom de l'utilisateur du token GitHub. */
348
254
  async function commitIdentity(runner) {
349
255
  const user = await new GitHubClient(runner.config).getAuthenticatedUser();
@@ -381,54 +287,20 @@ async function commitRepair(runner, base, message) {
381
287
  await runner.git([...(await commitIdentity(runner)), "commit", "-m", message, "-m", CLAUDE_TRAILER]);
382
288
  return (await runner.git(["rev-parse", "HEAD"])).trim();
383
289
  }
384
- /** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
385
- async function forceStep(runner) {
386
- runner.setStep("force", "running");
387
- const projects = new Set(runner.operation.forceCandidates.map((candidate) => candidate.project));
388
- for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
389
- await runner.npm(project, ["audit", "fix", "--force", ...scopeArgs(runner.operation.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
390
- }
391
- await auditAll(runner, "afterForce");
392
- await refreshChanges(runner);
393
- runner.setStep("force", "done");
394
- }
395
290
  /**
396
- * Corrections par Claude, d'après la tâche de l'analyse et les remarques de
397
- * l'utilisateur : la première fois, la branche est créée et `npm audit fix`
398
- * y est commité ; les corrections de Claude font ensuite un seul commit, qui
399
- * remplace celui d'un passage précédent. Un échec remet le clone dans l'état
400
- * du passage précédent et garde ses résultats ; seule une annulation
401
- * interrompt l'opération.
291
+ * Corrections par Claude des vulnérabilités restantes : la branche est créée et
292
+ * `npm audit fix` y est commité, puis Claude analyse et corrige en une session,
293
+ * dont les changements font un seul commit. Un échec, configuration manquante
294
+ * comprise, remet le clone dans l'état du commit de `npm audit fix` et laisse
295
+ * l'opération se poursuivre ; seule une annulation l'interrompt.
402
296
  */
403
297
  async function repairStep(runner, ctx) {
404
298
  runner.setStep("repair", "running");
405
- const previous = runner.operation.repair;
406
- const { base, auditCommit } = previous ?? (await commitAuditFixes(runner));
407
- const repair = {
408
- runs: (previous?.runs ?? 0) + 1,
409
- startedAt: now(),
410
- endedAt: null,
411
- turns: 0,
412
- activity: [],
413
- base,
414
- auditCommit,
415
- commit: previous?.commit ?? null,
416
- report: previous?.report ?? null,
417
- task: previous?.task ?? null,
418
- error: null,
419
- };
420
- const analysisTask = runner.operation.analysis?.task ?? null;
421
- runner.update((operation) => ({
422
- ...operation,
423
- repair,
424
- sessions: [...operation.sessions, newSession("repair", repair.runs, analysisTask ? [{ task: analysisTask, role: "read" }] : [])],
425
- }));
299
+ const { base, auditCommit } = await commitAuditFixes(runner);
300
+ const repair = { startedAt: now(), endedAt: null, turns: 0, activity: [], events: [], base, auditCommit, commit: null, report: null, task: null, error: null };
301
+ runner.update((operation) => ({ ...operation, repair }));
426
302
  const repaired = (fn) => runner.update((operation) => ({ ...operation, repair: operation.repair && fn(operation.repair) }));
427
303
  try {
428
- if (!analysisTask)
429
- throw new TrackerError("The fixes by Claude need the organizer task of the analysis.");
430
- const { remarks } = await analysisRemarks(ctx.settings(), runner.operation);
431
- runner.update((current) => ({ ...current, sessions: withLastSession(current, (session) => ({ ...session, remarks })) }));
432
304
  const operation = runner.operation;
433
305
  const { report, task } = await repairVulnerabilities({
434
306
  repoId: operation.repoId,
@@ -437,54 +309,55 @@ async function repairStep(runner, ctx) {
437
309
  cwd: runner.repoDir,
438
310
  workDir: operation.workDir,
439
311
  facts: await currentAuditFacts(runner),
440
- forceApplied: operation.steps.force === "done",
441
- analysisTask: analysisTask.key,
442
- reportTask: previous?.task?.key ?? null,
443
312
  settings: ctx.settings(),
444
313
  claude: ctx.claude,
445
314
  signal: runner.signal,
446
315
  onEvent: (event, turns) => {
447
316
  const line = activityLine(event);
448
317
  runner.log(`claude: ${line}`);
449
- runner.update((current) => ({
318
+ repaired((current) => ({
450
319
  ...current,
451
- repair: current.repair && { ...current.repair, turns, activity: [...current.repair.activity, line].slice(-ANALYSIS_ACTIVITY) },
452
- sessions: withLastSession(current, (session) => ({ ...session, turns, events: [...session.events, event].slice(-SESSION_EVENTS) })),
320
+ turns,
321
+ activity: [...current.activity, line].slice(-CLAUDE_ACTIVITY),
322
+ events: [...current.events, event].slice(-SESSION_EVENTS),
453
323
  }));
454
324
  },
455
325
  });
456
326
  const commit = await commitRepair(runner, base, report.commitMessage);
457
- runner.log(`Development report ${task.key}: ${task.url}`);
327
+ runner.log(`Report of Claude ${task.key}: ${task.url}`);
458
328
  await auditAll(runner, "afterRepair");
459
329
  await refreshChanges(runner);
460
330
  repaired((current) => ({ ...current, endedAt: now(), commit, report, task }));
461
- endSession(runner, "done", {
462
- tasks: [{ task: analysisTask, role: "read" }, { task, role: previous?.task ? "updated" : "created" }],
463
- repairReport: report,
464
- commit,
465
- remaining: runner.operation.counts.afterRepair,
466
- });
467
331
  runner.setStep("repair", "done");
468
332
  }
469
333
  catch (err) {
470
- if (err instanceof CommandAbortedError || runner.signal.aborted) {
471
- endSession(runner, "cancelled");
334
+ if (err instanceof CommandAbortedError || runner.signal.aborted)
472
335
  throw err;
473
- }
474
336
  const message = err?.message ?? String(err);
475
337
  runner.log(`Fixes by Claude failed: ${message}`);
476
338
  await runner.git(["reset", "--hard", "HEAD"]);
477
339
  await runner.git(["clean", "-fd", "-e", "node_modules"]);
478
340
  repaired((current) => ({ ...current, endedAt: now(), error: message }));
479
- endSession(runner, "failed", { error: message });
480
- runner.setStep("repair", previous?.report ? "done" : "failed");
341
+ runner.setStep("repair", "failed");
342
+ }
343
+ }
344
+ /** Avertissements en tête de la pull request : échec de Claude, ou tests en échec après ses corrections. */
345
+ function pullRequestWarnings(operation) {
346
+ const repair = operation.repair;
347
+ if (repair?.error) {
348
+ return [`> [!WARNING]`, `> Claude Code could not fix the remaining vulnerabilities: ${repair.error}`, `> This pull request only holds the fixes of \`npm audit fix\`.`, ""];
481
349
  }
350
+ if (repair?.report?.tests.outcome === "failed") {
351
+ return [`> [!WARNING]`, `> The tests failed after the fixes by Claude Code: ${repair.report.tests.detail}`, ""];
352
+ }
353
+ return [];
482
354
  }
483
355
  function pullRequestBody(operation) {
484
- const after = operation.counts.afterRepair ?? operation.counts.afterForce ?? operation.counts.afterFix;
356
+ const after = operation.counts.afterRepair ?? operation.counts.afterFix;
485
357
  const repair = operation.repair?.report ? operation.repair : null;
486
358
  const command = ["npm audit fix", ...scopeArgs(operation.scope), "--package-lock-only --ignore-scripts"].join(" ");
487
359
  const lines = [
360
+ ...pullRequestWarnings(operation),
488
361
  `Automated \`npm audit\` fixes, made by mcp-dependabot-tracker in a temporary clone (\`${command}\`).`,
489
362
  "",
490
363
  operation.scope === "production"
@@ -492,8 +365,6 @@ function pullRequestBody(operation) {
492
365
  : "- Scope: all dependencies, devDependencies included.",
493
366
  `- Vulnerabilities before: ${operation.counts.initial}`,
494
367
  `- Vulnerabilities after: ${after}`,
495
- `- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
496
- ...(operation.analysis?.task ? [`- Remaining vulnerabilities analysed by Claude: organizer task ${operation.analysis.task.key}`] : []),
497
368
  "",
498
369
  `Updated packages (${operation.changes.length}):`,
499
370
  "",
@@ -504,7 +375,7 @@ function pullRequestBody(operation) {
504
375
  if (operation.changes.length > MAX_PR_CHANGES)
505
376
  lines.push(`- … and ${operation.changes.length - MAX_PR_CHANGES} more`);
506
377
  if (repair?.report) {
507
- lines.push("", `Fixes by Claude Code${repair.task ? `, detailed in organizer task ${repair.task.key}` : ""}:`, "", repair.report.summary, "");
378
+ lines.push("", `Fixes by Claude Code${repair.task ? `, reported in organizer task ${repair.task.key}` : ""}:`, "", repair.report.summary, "");
508
379
  for (const change of repair.report.changes)
509
380
  lines.push(`- \`${change.file}\`: ${change.change}`);
510
381
  lines.push(`- Tests: ${repair.report.tests.outcome.replace("_", " ")} — ${repair.report.tests.detail}`);
@@ -513,7 +384,7 @@ function pullRequestBody(operation) {
513
384
  }
514
385
  /**
515
386
  * Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull
516
- * request vers la branche analysée. Après des corrections par Claude, la
387
+ * request vers la branche analysée. Après les corrections par Claude, la
517
388
  * branche et ses commits existent déjà : seuls le push et la pull request
518
389
  * restent à faire.
519
390
  */
@@ -553,40 +424,9 @@ function finish(runner) {
553
424
  steps: Object.fromEntries(Object.entries(operation.steps).map(([step, state]) => [step, state === "pending" ? "skipped" : state])),
554
425
  }));
555
426
  }
556
- /**
557
- * Après les corrections : la suite attend l'utilisateur, avec le nom de la
558
- * branche qui sera poussée, ou l'opération se termine s'il n'y a rien à pousser.
559
- */
560
- function settleForPush(runner) {
561
- const operation = runner.operation;
562
- if (operation.changes.length > 0 || operation.repair?.auditCommit || operation.repair?.commit) {
563
- runner.update((current) => ({ ...current, status: "waiting_push", branch: current.branch ?? branchName(new Date()) }));
564
- }
565
- else {
566
- finish(runner);
567
- }
568
- }
569
- /** Vrai quand Claude peut corriger : son analyse a créé une tâche et des vulnérabilités restent. */
570
- function canRepair(operation) {
571
- return operation.analysis?.task != null && operation.remaining.length > 0;
572
- }
573
- /** 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. */
574
- function settleAfterFixes(runner) {
575
- if (canRepair(runner.operation)) {
576
- runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
577
- return;
578
- }
579
- runner.setStep("repair", "skipped");
580
- settleForPush(runner);
581
- }
582
- /** Après un passage de Claude : le push attend quand un passage a abouti, sinon les corrections attendent de nouveau. */
583
- function settleAfterRepair(runner) {
584
- if (runner.operation.repair?.report) {
585
- settleForPush(runner);
586
- }
587
- else {
588
- runner.update((operation) => ({ ...operation, status: "waiting_repair" }));
589
- }
427
+ /** Vrai quand la correction a quelque chose à pousser : des lockfiles modifiés ou un commit sur sa branche. */
428
+ function hasChangesToPush(operation) {
429
+ return operation.changes.length > 0 || operation.repair?.auditCommit != null || operation.repair?.commit != null;
590
430
  }
591
431
  /**
592
432
  * Exécute `body` pour l'opération `id`, avec un signal déclenché par une demande
@@ -633,25 +473,16 @@ function cleanUp(ctx, id) {
633
473
  fs.rmSync(operation.workDir, { recursive: true, force: true });
634
474
  return ctx.store.updateOperation(id, (current) => ({ ...current, workDir: null }));
635
475
  }
636
- /** Passe une opération en attente à `running` dans ce processus ; refusé si elle n'attend pas `expected`. */
637
- function resume(ctx, id, expected, fn) {
638
- return ctx.store.updateOperation(id, (operation) => {
639
- if (operation.status !== expected) {
640
- throw new ConflictError(`Operation ${id} is ${operation.status}, not ${expected}.`);
641
- }
642
- return fn({ ...operation, status: "running", pid: process.pid });
643
- });
644
- }
645
476
  /** Laisse une exécution se poursuivre en arrière-plan ; une erreur imprévue est journalisée. */
646
477
  function inBackground(ctx, id, run) {
647
478
  run.catch((err) => ctx.logError(`Operation ${id} could not be recorded: ${err?.stack ?? err}`));
648
479
  }
649
480
  // --- Entrées ---------------------------------------------------------------------
650
481
  /**
651
- * Lance une correction depuis la GUI, sur le périmètre `scope` : clone, audit,
652
- * `npm audit fix` et l'analyse par Claude s'exécutent en arrière-plan, puis
653
- * l'opération attend la décision sur `--force`, les corrections par Claude ou
654
- * le push. Refusé sur un dépôt déprécié.
482
+ * Lance une correction depuis la GUI, sur le périmètre `scope`, menée en
483
+ * arrière-plan jusqu'au bout sans intervention : clone, audit, `npm audit fix`,
484
+ * corrections par Claude s'il reste des vulnérabilités, puis commit, push et
485
+ * pull request s'il y a quelque chose à pousser. Refusé sur un dépôt déprécié.
655
486
  */
656
487
  export function startUserFix(ctx, repoId, scope) {
657
488
  ctx.githubConfig();
@@ -663,14 +494,16 @@ export function startUserFix(ctx, repoId, scope) {
663
494
  const vulnerabilities = await auditStep(runner);
664
495
  if (vulnerabilities.length === 0)
665
496
  return finish(runner);
666
- await fixStep(runner, vulnerabilities);
667
- await analysisStep(runner, ctx);
668
- if (runner.operation.forceCandidates.length > 0) {
669
- runner.update((current) => ({ ...current, status: "waiting_force" }));
670
- return;
497
+ const remaining = await fixStep(runner, vulnerabilities);
498
+ if (remaining.length > 0) {
499
+ await repairStep(runner, ctx);
500
+ }
501
+ else {
502
+ runner.setStep("repair", "skipped");
671
503
  }
672
- runner.setStep("force", "skipped");
673
- settleAfterFixes(runner);
504
+ if (hasChangesToPush(runner.operation))
505
+ await pushStep(runner);
506
+ finish(runner);
674
507
  }));
675
508
  return operation;
676
509
  }
@@ -690,80 +523,23 @@ export async function runDefaultBranchAudit(ctx, repoId, scope) {
690
523
  finish(runner);
691
524
  });
692
525
  }
693
- /** Applique ou passe `npm audit fix --force` sur une opération qui attend cette décision. */
694
- export function decideForce(ctx, id, apply) {
695
- const operation = resume(ctx, id, "waiting_force", (current) => current);
696
- inBackground(ctx, id, execute(ctx, id, async (runner) => {
697
- if (apply) {
698
- await forceStep(runner);
699
- }
700
- else {
701
- runner.setStep("force", "skipped");
702
- }
703
- settleAfterFixes(runner);
704
- }));
705
- return operation;
706
- }
707
526
  /**
708
- * Lance ou passe les corrections par Claude d'une opération qui les attend ;
709
- * `run` sur une opération qui attend le push après un passage relance Claude
710
- * avec les remarques de l'utilisateur. Un lancement est refusé tant que le
711
- * bac à sable de Claude Code ne peut pas démarrer sur le serveur.
712
- */
713
- export async function decideRepair(ctx, id, run) {
714
- if (run)
715
- await assertSandboxAvailable();
716
- const relaunch = run && ctx.store.getOperation(id).status === "waiting_push";
717
- const operation = resume(ctx, id, relaunch ? "waiting_push" : "waiting_repair", (current) => {
718
- if (relaunch && !current.repair?.report)
719
- throw new ConflictError(`Operation ${id} has no fixes by Claude to run again.`);
720
- return current;
721
- });
722
- inBackground(ctx, id, execute(ctx, id, async (runner) => {
723
- if (!run) {
724
- runner.setStep("repair", "skipped");
725
- settleForPush(runner);
726
- return;
727
- }
728
- await repairStep(runner, ctx);
729
- settleAfterRepair(runner);
730
- }));
731
- return operation;
732
- }
733
- /** Commit, push et pull request d'une opération qui attend le push. */
734
- export function pushOperation(ctx, id, commitMessage) {
735
- const operation = resume(ctx, id, "waiting_push", (current) => ({ ...current, commitMessage }));
736
- inBackground(ctx, id, execute(ctx, id, async (runner) => {
737
- await pushStep(runner);
738
- finish(runner);
739
- }));
740
- return operation;
741
- }
742
- /**
743
- * Annule une opération : une opération en attente se termine aussitôt ; une
744
- * opération en cours reçoit une demande d'annulation, lue par le processus qui
527
+ * Demande l'annulation d'une opération en cours, lue par le processus qui
745
528
  * l'exécute, qui arrête sa commande.
746
529
  */
747
530
  export function cancelOperation(ctx, id) {
748
531
  ctx.store.failOrphanedOperations();
749
- const operation = ctx.store.updateOperation(id, (current) => {
532
+ return ctx.store.updateOperation(id, (current) => {
750
533
  if (!isActive(current))
751
534
  throw new ConflictError(`Operation ${id} is already ${current.status}.`);
752
- if (current.status === "running")
753
- return { ...current, cancelRequested: true };
754
- return {
755
- ...current,
756
- status: "cancelled",
757
- steps: Object.fromEntries(Object.entries(current.steps).map(([step, state]) => [step, state === "pending" ? "skipped" : state])),
758
- };
535
+ return { ...current, cancelRequested: true };
759
536
  });
760
- return cleanUp(ctx, operation.id);
761
537
  }
762
538
  /**
763
539
  * Opération menée par l'agent d'un bout à l'autre, sur le périmètre de `plan`,
764
540
  * attendue jusqu'à sa fin : `audit` s'arrête après `npm audit` ; `fix` enchaîne
765
- * `npm audit fix`, puis `--force` et le push selon `plan`. Refusé sur un dépôt
766
- * déprécié.
541
+ * `npm audit fix`, puis le push selon `plan`, sans corrections par Claude.
542
+ * Refusé sur un dépôt déprécié.
767
543
  */
768
544
  export async function runAgentOperation(ctx, repoId, kind, plan) {
769
545
  ctx.githubConfig();
@@ -776,13 +552,7 @@ export async function runAgentOperation(ctx, repoId, kind, plan) {
776
552
  if (kind === "audit" || vulnerabilities.length === 0)
777
553
  return finish(runner);
778
554
  await fixStep(runner, vulnerabilities);
779
- runner.setStep("analysis", "skipped");
780
- if (plan.force && runner.operation.forceCandidates.length > 0) {
781
- await forceStep(runner);
782
- }
783
- else {
784
- runner.setStep("force", "skipped");
785
- }
555
+ runner.setStep("repair", "skipped");
786
556
  if (plan.push && runner.operation.changes.length > 0)
787
557
  await pushStep(runner);
788
558
  finish(runner);
@@ -4,7 +4,7 @@ export interface OrganizerConnection {
4
4
  url: string;
5
5
  token: string;
6
6
  }
7
- /** Espace du token et son propriétaire, à qui les tâches de l'analyse sont assignées. */
7
+ /** Espace du token et son propriétaire, à qui les tâches de rapport de Claude sont assignées. */
8
8
  export interface OrganizerSpace {
9
9
  space: {
10
10
  id: string;
@@ -1,7 +1,22 @@
1
- import type { RemarksResponse } from "../../shared/schemas/api.schema.js";
2
- import { type AnalysisTask, type AuditScope, type Operation, type RepairReport, type SessionEvent } from "../../shared/schemas/model.schema.js";
1
+ import { type AuditScope, type Operation, type OrganizerTask, type RepairReport, type SessionEvent } from "../../shared/schemas/model.schema.js";
3
2
  import type { Settings } from "../../shared/schemas/settings.schema.js";
4
3
  import { type ClaudeRuntime } from "./claude.js";
4
+ import { type OrganizerConnection } from "./organizer.js";
5
+ import type { Store } from "./store.js";
6
+ /**
7
+ * Corrections par Claude des vulnérabilités que `npm audit fix` laisse dans un
8
+ * clone, en une seule session. Claude analyse chaque vulnérabilité dans le
9
+ * code, la corrige quand il le peut en modifiant le clone (Read, Grep, Glob,
10
+ * Edit, Write), sans git ni écriture hors du clone, et lance les commandes npm
11
+ * (lockfile, audit, installation, tests) par les outils du serveur `npm-tools`,
12
+ * que le tracker exécute dans son propre bac à sable, sans aucun token. Il rend
13
+ * compte de son travail dans une seule tâche de l'organizer, assignée au
14
+ * propriétaire de l'espace et taguée du nom du dépôt, puis rend un rapport
15
+ * structuré. Le tracker relit la tâche sur l'organizer : absente, mal assignée
16
+ * ou mal taguée, elle fait échouer les corrections.
17
+ */
18
+ /** Nom du serveur MCP organizer dans la configuration de la session. */
19
+ export declare const ORGANIZER_SERVER = "organizer";
5
20
  /**
6
21
  * Vérifie, sous Linux, que bubblewrap crée un bac à sable pour le compte et
7
22
  * avec les restrictions du serveur : le tracker s'en sert pour lancer les
@@ -9,6 +24,19 @@ import { type ClaudeRuntime } from "./claude.js";
9
24
  * dit quoi installer ou régler ; sans effet sur les autres systèmes.
10
25
  */
11
26
  export declare function assertSandboxAvailable(platform?: NodeJS.Platform, command?: string): Promise<void>;
27
+ /** Vulnérabilités d'un rapport `npm audit --json`, réduites à ce qui sert les corrections. */
28
+ export declare function auditFacts(report: any, project: string): unknown[];
29
+ /** JSON des vulnérabilités dans la limite de taille ; au-delà, les dernières sont seulement comptées. */
30
+ export declare function factsJson(facts: unknown[]): string;
31
+ /** Serveur MCP organizer de la session, lancé par `npx` avec le token réglé dans la GUI. */
32
+ export declare function organizerServer(connection: OrganizerConnection): {
33
+ command: string;
34
+ args: string[];
35
+ env: {
36
+ ORGANIZER_URL: string;
37
+ ORGANIZER_TOKEN: string;
38
+ };
39
+ };
12
40
  export interface RepairInput {
13
41
  repoId: string;
14
42
  branch: string;
@@ -19,20 +47,20 @@ export interface RepairInput {
19
47
  workDir: string;
20
48
  /** Vulnérabilités restantes, d'après `npm audit --json`. */
21
49
  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
50
  settings: Settings;
28
51
  claude: ClaudeRuntime;
29
52
  signal: AbortSignal;
30
53
  onEvent: (event: SessionEvent, turns: number) => void;
31
54
  }
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. */
55
+ /**
56
+ * Lance les corrections, puis vérifie sur l'organizer la tâche que Claude dit
57
+ * avoir créée. Lève une erreur sans l'organizer ou le token Claude.
58
+ */
35
59
  export declare function repairVulnerabilities(input: RepairInput): Promise<{
36
60
  report: RepairReport;
37
- task: AnalysisTask;
61
+ task: OrganizerTask;
38
62
  }>;
63
+ /** Dernière opération du dépôt dont les corrections ont créé une tâche ; `operations` va de la plus récente à la plus ancienne. */
64
+ export declare function latestReported(operations: Operation[]): Operation | null;
65
+ /** Relit sur l'organizer le statut de la dernière tâche de rapport du dépôt, tant qu'elle n'est pas terminée. */
66
+ export declare function refreshReportTask(store: Store, settings: Settings, repoId: string): Promise<void>;