@imenam/mcp-feature-analyzer 1.0.31 → 1.0.32

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 (103) hide show
  1. package/README.md +46 -3
  2. package/dist/shared/labels.d.ts +2 -0
  3. package/dist/shared/labels.js +2 -0
  4. package/dist/shared/schemas/analysis.schema.d.ts +34 -0
  5. package/dist/shared/schemas/analysis.schema.js +16 -0
  6. package/dist/shared/schemas/api.schema.d.ts +16 -1
  7. package/dist/shared/schemas/api.schema.js +11 -1
  8. package/dist/shared/schemas/ipc.schema.d.ts +1 -1
  9. package/dist/shared/schemas/ipc.schema.js +1 -0
  10. package/dist/src/core/analysis-store.d.ts +4 -0
  11. package/dist/src/core/analysis-store.js +9 -5
  12. package/dist/src/core/invariants.js +7 -0
  13. package/dist/src/core/migrate.d.ts +2 -0
  14. package/dist/src/core/migrate.js +11 -0
  15. package/dist/src/core/notifications.d.ts +67 -0
  16. package/dist/src/core/notifications.js +273 -0
  17. package/dist/src/core/review-actions.d.ts +12 -3
  18. package/dist/src/core/review-actions.js +50 -4
  19. package/dist/src/gui-worker.js +80 -2
  20. package/dist/src/index.js +99 -4
  21. package/dist/src/tools/get-analysis.js +7 -1
  22. package/dist/src/tools/notifications.d.ts +27 -0
  23. package/dist/src/tools/notifications.js +137 -0
  24. package/gui/dist/assets/{angular-html-CmKD3qPJ.js → angular-html-CCsi6pU-.js} +1 -1
  25. package/gui/dist/assets/{angular-ts-CUV4f-7a.js → angular-ts-D3b0p2ec.js} +1 -1
  26. package/gui/dist/assets/{apl-DCOueFDH.js → apl-B_lcYoHG.js} +1 -1
  27. package/gui/dist/assets/{astro-BD_jikG2.js → astro-C8m0ax-G.js} +1 -1
  28. package/gui/dist/assets/{blade--LKfGpL_.js → blade-BTaoP0KJ.js} +1 -1
  29. package/gui/dist/assets/{c-C64vu1wx.js → c-SDXfbR0a.js} +1 -1
  30. package/gui/dist/assets/{chapel-CdXV9nyw.js → chapel-CvA97ZeU.js} +1 -1
  31. package/gui/dist/assets/{cobol-CIeHGuXr.js → cobol-CVtUeO01.js} +1 -1
  32. package/gui/dist/assets/{coffee-Bkn2a3NA.js → coffee-hRo5RQ8B.js} +1 -1
  33. package/gui/dist/assets/{cpp-C3fB8Y2b.js → cpp-BxoU2Hxs.js} +1 -1
  34. package/gui/dist/assets/{crystal-DAd9h7ft.js → crystal-CcX36hHQ.js} +1 -1
  35. package/gui/dist/assets/{css-DBARcyqi.js → css-CxWhmvIC.js} +1 -1
  36. package/gui/dist/assets/{edge-BNZ8haox.js → edge-QJOy4xlO.js} +1 -1
  37. package/gui/dist/assets/{elixir-D9JArLjY.js → elixir-C9LrWwAh.js} +1 -1
  38. package/gui/dist/assets/{elm-BdV8wsvX.js → elm-BR3U0yD_.js} +1 -1
  39. package/gui/dist/assets/{erb-C9NJWWn2.js → erb-CiOJpaDo.js} +1 -1
  40. package/gui/dist/assets/{git-rebase-C7eVPIjR.js → git-rebase-BYl4P3ox.js} +1 -1
  41. package/gui/dist/assets/{glimmer-js-BYHDLB8h.js → glimmer-js-Blh2OVv1.js} +1 -1
  42. package/gui/dist/assets/{glimmer-ts-2zbF0Evu.js → glimmer-ts-DXr9mcSj.js} +1 -1
  43. package/gui/dist/assets/{glsl-DkVhwxyT.js → glsl-CnZQZULb.js} +1 -1
  44. package/gui/dist/assets/{graphql-c5VbsYm4.js → graphql-8Rdi2_E3.js} +1 -1
  45. package/gui/dist/assets/{hack-ZGsLC-jN.js → hack-CKSTrDJQ.js} +1 -1
  46. package/gui/dist/assets/{haml-CbXyCehf.js → haml-BXUwL6Gi.js} +1 -1
  47. package/gui/dist/assets/{handlebars-C-NYLeBr.js → handlebars-CoB9_4Wu.js} +1 -1
  48. package/gui/dist/assets/{html-B0yhsy4d.js → html-B6C5qCrz.js} +1 -1
  49. package/gui/dist/assets/{html-derivative-VQyqZXW8.js → html-derivative-Bk9jovvn.js} +1 -1
  50. package/gui/dist/assets/{http-C-aT1t0_.js → http-BjGXUZ-r.js} +1 -1
  51. package/gui/dist/assets/{hurl-Dl1RZ9Gp.js → hurl-DTlVMspc.js} +1 -1
  52. package/gui/dist/assets/index-Cr9HJaGX.css +1 -0
  53. package/gui/dist/assets/{index-DnIoVeij.js → index-dM30WmvE.js} +18 -18
  54. package/gui/dist/assets/{java-0vBBZHSu.js → java-Bh1jVWfi.js} +1 -1
  55. package/gui/dist/assets/{javascript-DeblizDv.js → javascript-CAp5Mnzl.js} +1 -1
  56. package/gui/dist/assets/{jinja-CvT6pZVi.js → jinja-rB-QNUyu.js} +1 -1
  57. package/gui/dist/assets/{jison-xhWB-hJt.js → jison-VA6AlkMv.js} +1 -1
  58. package/gui/dist/assets/{json-lrbKMNAx.js → json-D_3nkZlx.js} +1 -1
  59. package/gui/dist/assets/{jsx-AvOeMWx5.js → jsx-vCtnSopd.js} +1 -1
  60. package/gui/dist/assets/{julia-CCVS_Afm.js → julia-DzWcxIlS.js} +1 -1
  61. package/gui/dist/assets/{just-D0rQgjf2.js → just-Cib470fM.js} +1 -1
  62. package/gui/dist/assets/{latex-DgGx6yXU.js → latex-B9Rt9Nm7.js} +1 -1
  63. package/gui/dist/assets/{liquid-D95OegEg.js → liquid-CpUpBdB-.js} +1 -1
  64. package/gui/dist/assets/{lua-5KNos9qZ.js → lua-ABZXQo7L.js} +1 -1
  65. package/gui/dist/assets/{marko-BpMwNtg_.js → marko-BqS1ITvl.js} +1 -1
  66. package/gui/dist/assets/{mdc-Dul0I4vt.js → mdc-BU5NTqUw.js} +1 -1
  67. package/gui/dist/assets/{nginx-B2gDZimP.js → nginx-CPJvj-oD.js} +1 -1
  68. package/gui/dist/assets/{nim-D9V6BvZF.js → nim-DP5c8JP-.js} +1 -1
  69. package/gui/dist/assets/{org-BDDVerq9.js → org-z8oygnoy.js} +1 -1
  70. package/gui/dist/assets/{perl-BeFJyiyg.js → perl-BOKTfCaa.js} +1 -1
  71. package/gui/dist/assets/{php-ClsyOlLU.js → php-Bxp7SLwc.js} +1 -1
  72. package/gui/dist/assets/{pug-Bw7ZuWMB.js → pug-YbOie-Gt.js} +1 -1
  73. package/gui/dist/assets/{qml-VKAIx01f.js → qml-BoW83Fyx.js} +1 -1
  74. package/gui/dist/assets/{r-BbmN2hL3.js → r-BOTGEI5j.js} +1 -1
  75. package/gui/dist/assets/{razor-x_jMVj8b.js → razor-Ci4nB3jF.js} +1 -1
  76. package/gui/dist/assets/{regexp-COLYAzG8.js → regexp-BumEaKrn.js} +1 -1
  77. package/gui/dist/assets/{rst-Cr40Lerq.js → rst-DtqBiJDu.js} +1 -1
  78. package/gui/dist/assets/{ruby-CLGGotZ-.js → ruby-D1kPpSHI.js} +1 -1
  79. package/gui/dist/assets/{sas-DWBWO9Y5.js → sas-14YEmckC.js} +1 -1
  80. package/gui/dist/assets/{scss-BzKAiQYV.js → scss-DFjEDCH3.js} +1 -1
  81. package/gui/dist/assets/{shellscript-D2u4cPDX.js → shellscript-DPod_v0w.js} +1 -1
  82. package/gui/dist/assets/{shellsession-Ccl-2bAD.js → shellsession-tu7P7CZw.js} +1 -1
  83. package/gui/dist/assets/{soy-iOU5rhs2.js → soy-CGE1c2SC.js} +1 -1
  84. package/gui/dist/assets/{sql-BEWq1vME.js → sql-CaS7isii.js} +1 -1
  85. package/gui/dist/assets/{stata-yz3nZ7Wz.js → stata-Q1HKOyRT.js} +1 -1
  86. package/gui/dist/assets/{surrealql-DQG5rJ06.js → surrealql-BtSPewz7.js} +1 -1
  87. package/gui/dist/assets/{svelte-CF3TXZKT.js → svelte-U6EZswjv.js} +1 -1
  88. package/gui/dist/assets/{templ-C4GJOtRU.js → templ-Dv6Hh6ZK.js} +1 -1
  89. package/gui/dist/assets/{tex-D2FpWKcl.js → tex-FNxy8pwc.js} +1 -1
  90. package/gui/dist/assets/{ts-tags-CUP-vv3j.js → ts-tags-QwSPCwFk.js} +1 -1
  91. package/gui/dist/assets/{tsx-dMhwOSyy.js → tsx-DD4r3epl.js} +1 -1
  92. package/gui/dist/assets/{twig-BTWubnl3.js → twig-CF2Q5rKi.js} +1 -1
  93. package/gui/dist/assets/{typescript-C8UFvOTX.js → typescript-BH94Wa6R.js} +1 -1
  94. package/gui/dist/assets/{typst-CJXqwXsh.js → typst-FVLFkJ8V.js} +1 -1
  95. package/gui/dist/assets/{vue-X9Wwm2mD.js → vue-CgIy39RZ.js} +1 -1
  96. package/gui/dist/assets/{vue-html-DRPxRQ6-.js → vue-html-BK18RzGS.js} +1 -1
  97. package/gui/dist/assets/{vue-vine-Bt58w4aD.js → vue-vine-Ca-3XU_O.js} +1 -1
  98. package/gui/dist/assets/{xml-lUPi6MU7.js → xml-CrlmnYy6.js} +1 -1
  99. package/gui/dist/assets/{xsl-BieZRR5a.js → xsl-CTdshCNA.js} +1 -1
  100. package/gui/dist/assets/{yaml-DAVBBHYU.js → yaml-DVKeB6J_.js} +1 -1
  101. package/gui/dist/index.html +2 -2
  102. package/package.json +1 -1
  103. package/gui/dist/assets/index-V1Ga6Ikg.css +0 -1
@@ -0,0 +1,273 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { noteLocationText } from "../../shared/text.js";
5
+ import { AnalysisStore, writeJsonAtomic } from "./analysis-store.js";
6
+ import { AnalysisError } from "./errors.js";
7
+ /** Durée maximale d'un Monitor côté hôte. */
8
+ export const MONITOR_TIMEOUT_MS = 1_800_000;
9
+ const SCAN_INTERVAL_MS = 1_000;
10
+ export const WATCHER_BEAT_MS = 5_000;
11
+ const WATCHER_STALE_MS = 15_000;
12
+ const HANDOFF_STALE_MS = 7 * 24 * 60 * 60 * 1000;
13
+ const BACKOFF_MAX_MS = 30_000;
14
+ function eventsOf(analysis) {
15
+ const events = [];
16
+ for (const note of analysis.notes) {
17
+ if (note.question === null || note.question.answer !== null)
18
+ continue;
19
+ events.push({
20
+ kind: "question",
21
+ analysisId: analysis.id,
22
+ title: analysis.title,
23
+ questionId: note.id,
24
+ location: note.location,
25
+ text: note.text,
26
+ eventMs: Date.parse(note.question.askedAt),
27
+ });
28
+ }
29
+ const review = analysis.review;
30
+ if (review.state === "submitted" && review.decision !== null && review.submittedAt !== null) {
31
+ events.push({
32
+ kind: "submitted",
33
+ analysisId: analysis.id,
34
+ title: analysis.title,
35
+ decision: review.decision,
36
+ findingCount: review.selectedFindingIds.length,
37
+ noteCount: review.selectedNoteIds.length,
38
+ eventMs: Date.parse(review.submittedAt),
39
+ });
40
+ }
41
+ return events;
42
+ }
43
+ /** Vrai si `id` est `root` ou l'une de ses revues de suivi, d'après les liens `followUpOf`. */
44
+ function inChain(id, root, followUpOf) {
45
+ const seen = new Set();
46
+ let current = id;
47
+ while (current !== undefined && !seen.has(current)) {
48
+ if (current === root)
49
+ return true;
50
+ seen.add(current);
51
+ current = followUpOf.get(current);
52
+ }
53
+ return false;
54
+ }
55
+ /**
56
+ * Lit les événements à annoncer pour une analyse et ses revues de suivi, y
57
+ * compris celles créées après le lancement : questions du relecteur sans réponse
58
+ * et revues soumises. Le curseur est l'instant, en millisecondes, du dernier
59
+ * événement déjà annoncé. Une analyse illisible est ignorée ; le store ne relit
60
+ * que les fichiers modifiés.
61
+ */
62
+ export class ReviewEventScanner {
63
+ store;
64
+ analysisId;
65
+ constructor(store, analysisId) {
66
+ this.store = store;
67
+ this.analysisId = analysisId;
68
+ }
69
+ /** Événements postérieurs à `cursor`, dans l'ordre chronologique. */
70
+ since(cursor) {
71
+ const analyses = [];
72
+ const followUpOf = new Map();
73
+ for (const id of this.store.ids()) {
74
+ try {
75
+ const analysis = this.store.get(id);
76
+ analyses.push(analysis);
77
+ if (analysis.followUpOf !== null)
78
+ followUpOf.set(analysis.id, analysis.followUpOf);
79
+ }
80
+ catch {
81
+ continue;
82
+ }
83
+ }
84
+ const found = [];
85
+ for (const analysis of analyses) {
86
+ if (!inChain(analysis.id, this.analysisId, followUpOf))
87
+ continue;
88
+ for (const event of eventsOf(analysis))
89
+ if (event.eventMs > cursor)
90
+ found.push(event);
91
+ }
92
+ return found.sort((a, b) => a.eventMs - b.eventMs || orderKey(a).localeCompare(orderKey(b)));
93
+ }
94
+ /** Questions sans réponse envoyées jusqu'à `cursor` inclus. */
95
+ pendingQuestionsUntil(cursor) {
96
+ return this.since(0).filter((event) => event.kind === "question" && event.eventMs <= cursor);
97
+ }
98
+ }
99
+ function orderKey(event) {
100
+ return event.kind === "question" ? `${event.analysisId}/${event.questionId}` : event.analysisId;
101
+ }
102
+ /** Curseur après annonce des événements donnés. */
103
+ export function advanceCursor(cursor, announced) {
104
+ return announced.reduce((max, event) => Math.max(max, event.eventMs), cursor);
105
+ }
106
+ function oneLine(text, max) {
107
+ const flat = text.replace(/\s+/g, " ").trim();
108
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
109
+ }
110
+ const DECISION_TEXT = {
111
+ approve: "approved the feature — nothing to process",
112
+ request_changes: "requests changes",
113
+ reject: "rejected the feature",
114
+ };
115
+ /** Ligne de notification : une seule ligne, lisible telle quelle par l'agent. */
116
+ export function formatEvent(event) {
117
+ const origin = `[feature-analyzer] "${oneLine(event.title, 80)}" (${event.analysisId})`;
118
+ if (event.kind === "question") {
119
+ const where = event.location ? ` on ${noteLocationText(event.location)}` : "";
120
+ return (`${origin} — the reviewer asks you${where}: ${oneLine(event.text, 1000)} — ` +
121
+ `answer with answer_question, analysis_id ${event.analysisId}, question_id ${event.questionId}`);
122
+ }
123
+ return (`${origin} — the reviewer submitted the review and ${DECISION_TEXT[event.decision]} ` +
124
+ `(${event.findingCount} finding(s) and ${event.noteCount} note(s) selected) — ` +
125
+ `read it with get_review_feedback, analysis_id ${event.analysisId}`);
126
+ }
127
+ function handoffDir() {
128
+ return path.join(os.homedir(), ".mcp-feature-analyzer", "watch");
129
+ }
130
+ function handoffPath(analysisId) {
131
+ return path.join(handoffDir(), `${analysisId}.json`);
132
+ }
133
+ const written = new Set();
134
+ function readHandoff(analysisId) {
135
+ try {
136
+ const handoff = JSON.parse(fs.readFileSync(handoffPath(analysisId), "utf-8"));
137
+ return handoff.analysisId === analysisId ? handoff : null;
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ }
143
+ function saveHandoff(handoff) {
144
+ fs.mkdirSync(handoffDir(), { recursive: true });
145
+ writeJsonAtomic(handoffPath(handoff.analysisId), { ...handoff, written_at: new Date().toISOString() });
146
+ }
147
+ /** Dépose le relais de l'analyse et renvoie son curseur ; un relais existant garde le sien. */
148
+ export function writeHandoff(analysisId, dataDir) {
149
+ written.add(analysisId);
150
+ const existing = readHandoff(analysisId);
151
+ const cursor = existing?.cursor ?? Date.now();
152
+ saveHandoff({ analysisId, dataDir, cursor });
153
+ pruneStaleHandoffs();
154
+ return cursor;
155
+ }
156
+ /** Retire les relais écrits par ce processus. Synchrone : appelable sur `exit`. */
157
+ export function removeOwnHandoffs() {
158
+ for (const analysisId of written)
159
+ fs.rmSync(handoffPath(analysisId), { force: true });
160
+ written.clear();
161
+ }
162
+ function pruneStaleHandoffs() {
163
+ let entries;
164
+ try {
165
+ entries = fs.readdirSync(handoffDir());
166
+ }
167
+ catch {
168
+ return;
169
+ }
170
+ for (const entry of entries) {
171
+ const file = path.join(handoffDir(), entry);
172
+ try {
173
+ if (Date.now() - fs.statSync(file).mtimeMs > HANDOFF_STALE_MS)
174
+ fs.rmSync(file, { force: true });
175
+ }
176
+ catch {
177
+ // Un relais déjà supprimé ne doit pas faire échouer l'écriture.
178
+ }
179
+ }
180
+ }
181
+ function watchersDir(dataDir) {
182
+ return path.join(dataDir, "watchers");
183
+ }
184
+ /** Signale qu'un veilleur suit l'analyse (et ses revues de suivi) depuis `since`. */
185
+ export function writeWatcherBeat(dataDir, analysisId, since) {
186
+ fs.mkdirSync(watchersDir(dataDir), { recursive: true });
187
+ writeJsonAtomic(path.join(watchersDir(dataDir), `${analysisId}.json`), { analysisId, since, updatedAt: Date.now() });
188
+ }
189
+ function readBeat(file) {
190
+ try {
191
+ const beat = JSON.parse(fs.readFileSync(file, "utf-8"));
192
+ return Date.now() - beat.updatedAt < WATCHER_STALE_MS ? beat : null;
193
+ }
194
+ catch {
195
+ return null;
196
+ }
197
+ }
198
+ /** Date depuis laquelle un veilleur vivant suit cette analyse, ou null. */
199
+ export function liveWatcherSince(dataDir, analysisId) {
200
+ const beat = readBeat(path.join(watchersDir(dataDir), `${analysisId}.json`));
201
+ return beat?.analysisId === analysisId ? beat.since : null;
202
+ }
203
+ /** Analyses suivies par un veilleur vivant ; chacune couvre aussi ses revues de suivi. */
204
+ export function watchedAnalyses(dataDir) {
205
+ let entries;
206
+ try {
207
+ entries = fs.readdirSync(watchersDir(dataDir));
208
+ }
209
+ catch {
210
+ return [];
211
+ }
212
+ const ids = [];
213
+ for (const entry of entries) {
214
+ if (!entry.endsWith(".json"))
215
+ continue;
216
+ const beat = readBeat(path.join(watchersDir(dataDir), entry));
217
+ if (beat)
218
+ ids.push(beat.analysisId);
219
+ }
220
+ return ids;
221
+ }
222
+ /**
223
+ * Mode veilleur local (`--watch <analysis_id>`). Une ligne sur stdout par
224
+ * événement de l'analyse ou de ses revues de suivi, y compris celles créées après
225
+ * le lancement du veilleur : l'outil Monitor de l'hôte réveille l'agent à chaque
226
+ * ligne. Le journal et les erreurs partent sur stderr. Une erreur de lecture se
227
+ * traduit par un réessai.
228
+ */
229
+ export async function runWatchMode(analysisId) {
230
+ if (!analysisId)
231
+ throw new AnalysisError("--watch needs an analysis id: call enable_notifications to get the exact command.");
232
+ const handoff = readHandoff(analysisId);
233
+ if (!handoff) {
234
+ throw new AnalysisError(`No notification handoff for analysis ${analysisId}: call enable_notifications in that MCP session first.`);
235
+ }
236
+ const scanner = new ReviewEventScanner(new AnalysisStore(handoff.dataDir), analysisId);
237
+ const since = new Date().toISOString();
238
+ let cursor = handoff.cursor;
239
+ let lastBeat = 0;
240
+ let backoff = SCAN_INTERVAL_MS;
241
+ process.stderr.write(`[feature-analyzer] watching analysis ${analysisId} and its follow-up reviews in ${handoff.dataDir}\n`);
242
+ for (;;) {
243
+ try {
244
+ if (Date.now() - lastBeat >= WATCHER_BEAT_MS) {
245
+ writeWatcherBeat(handoff.dataDir, analysisId, since);
246
+ lastBeat = Date.now();
247
+ }
248
+ const events = scanner.since(cursor);
249
+ if (events.length > 0) {
250
+ for (const event of events)
251
+ process.stdout.write(`${formatEvent(event)}\n`);
252
+ cursor = advanceCursor(cursor, events);
253
+ saveHandoff({ analysisId, dataDir: handoff.dataDir, cursor });
254
+ }
255
+ backoff = SCAN_INTERVAL_MS;
256
+ await sleep(SCAN_INTERVAL_MS);
257
+ }
258
+ catch (err) {
259
+ process.stderr.write(`[feature-analyzer] scan failed, retrying in ${Math.round(backoff / 1000)} s: ${err?.message ?? err}\n`);
260
+ await sleep(backoff);
261
+ backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
262
+ }
263
+ }
264
+ }
265
+ export function sleep(ms, signal) {
266
+ return new Promise((resolve) => {
267
+ const timer = setTimeout(resolve, ms);
268
+ signal?.addEventListener("abort", () => {
269
+ clearTimeout(timer);
270
+ resolve();
271
+ }, { once: true });
272
+ });
273
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Analysis, Editor } from "../../shared/schemas/analysis.schema.js";
2
- import type { AddNoteBody, DeleteNoteBody, MarkProcessedBody, SetFileLevelBody, SetFileReviewedBody, SetFindingStatusBody, SubmitReviewBody, UpdateNoteBody } from "../../shared/schemas/api.schema.js";
2
+ import type { AddNoteBody, DeleteNoteBody, MarkAnswerSeenBody, MarkProcessedBody, SetFileLevelBody, SetFileReviewedBody, SetFindingStatusBody, SubmitReviewBody, UpdateNoteBody } from "../../shared/schemas/api.schema.js";
3
3
  import type { AnalysisStore, MutateOptions } from "./analysis-store.js";
4
4
  /**
5
5
  * Modifications faites par le relecteur depuis la GUI. Chacune passe par
@@ -23,10 +23,19 @@ export declare function setFileLevel(store: AnalysisStore, analysisId: string, b
23
23
  export declare function setFindingStatus(store: AnalysisStore, analysisId: string, findingId: string, body: SetFindingStatusBody): Analysis;
24
24
  /**
25
25
  * Ajoute une remarque du relecteur sur une ligne du côté « nouveau » ou sur un fichier entier,
26
- * liée au constat `findingId` quand elle y répond.
26
+ * liée au constat `findingId` quand elle y répond. Avec `askAgent`, la remarque est une
27
+ * question envoyée tout de suite à l'agent : elle ne fait pas partie du retour de fin de
28
+ * revue et ne repasse donc pas une revue soumise en attente.
27
29
  */
28
30
  export declare function addNote(store: AnalysisStore, analysisId: string, body: AddNoteBody): Analysis;
29
- /** Remplace le texte d'une remarque. */
31
+ /** Enregistre que le relecteur a lu la réponse de l'agent à une question. */
32
+ export declare function markAnswerSeen(store: AnalysisStore, analysisId: string, noteId: string, body: MarkAnswerSeenBody): Analysis;
33
+ /**
34
+ * Enregistre la réponse de l'agent à une question du relecteur. Refusé pour une
35
+ * remarque qui n'est pas une question ou une question déjà répondue.
36
+ */
37
+ export declare function answerQuestion(store: AnalysisStore, analysisId: string, noteId: string, answer: string): Analysis;
38
+ /** Remplace le texte d'une remarque ; une question déjà envoyée à l'agent ne change plus. */
30
39
  export declare function updateNote(store: AnalysisStore, analysisId: string, noteId: string, body: UpdateNoteBody): Analysis;
31
40
  /** Supprime une remarque et la retire de la sélection de la revue. */
32
41
  export declare function deleteNote(store: AnalysisStore, analysisId: string, noteId: string, body: DeleteNoteBody): Analysis;
@@ -58,7 +58,9 @@ export function setFindingStatus(store, analysisId, findingId, body) {
58
58
  }
59
59
  /**
60
60
  * Ajoute une remarque du relecteur sur une ligne du côté « nouveau » ou sur un fichier entier,
61
- * liée au constat `findingId` quand elle y répond.
61
+ * liée au constat `findingId` quand elle y répond. Avec `askAgent`, la remarque est une
62
+ * question envoyée tout de suite à l'agent : elle ne fait pas partie du retour de fin de
63
+ * revue et ne repasse donc pas une revue soumise en attente.
62
64
  */
63
65
  export function addNote(store, analysisId, body) {
64
66
  return store.mutate(analysisId, "user", (draft) => {
@@ -68,22 +70,62 @@ export function addNote(store, analysisId, body) {
68
70
  if (findingId !== null && !draft.findings.some((finding) => finding.id === findingId)) {
69
71
  throw new NotFoundError(`Finding "${findingId}" not found in analysis "${analysisId}".`);
70
72
  }
71
- reopenSubmittedReview(draft);
73
+ const now = new Date().toISOString();
74
+ const question = body.askAgent ? { askedAt: now, answer: null, answerSeenAt: null } : null;
75
+ if (question === null)
76
+ reopenSubmittedReview(draft);
72
77
  draft.notes.push({
73
78
  id: itemId("note", new Set(draft.notes.map((note) => note.id))),
74
79
  location,
75
80
  findingId,
76
81
  text: body.text,
77
- createdAt: new Date().toISOString(),
82
+ createdAt: now,
83
+ question,
78
84
  });
79
85
  }, { baseRevision: body.baseRevision });
80
86
  }
81
- /** Remplace le texte d'une remarque. */
87
+ /** Enregistre que le relecteur a lu la réponse de l'agent à une question. */
88
+ export function markAnswerSeen(store, analysisId, noteId, body) {
89
+ return store.mutate(analysisId, "user", (draft) => {
90
+ const note = draft.notes.find((entry) => entry.id === noteId);
91
+ if (!note)
92
+ throw new NotFoundError(`Note "${noteId}" not found in analysis "${analysisId}".`);
93
+ if (note.question === null)
94
+ throw new AnalysisError(`Note "${noteId}" is not a question sent to the agent.`);
95
+ if (note.question.answer === null)
96
+ throw new AnalysisError(`The agent has not answered question "${noteId}" yet.`);
97
+ if (note.question.answerSeenAt !== null)
98
+ return;
99
+ note.question.answerSeenAt = new Date().toISOString();
100
+ }, { baseRevision: body.baseRevision });
101
+ }
102
+ /**
103
+ * Enregistre la réponse de l'agent à une question du relecteur. Refusé pour une
104
+ * remarque qui n'est pas une question ou une question déjà répondue.
105
+ */
106
+ export function answerQuestion(store, analysisId, noteId, answer) {
107
+ return store.mutate(analysisId, "agent", (draft) => {
108
+ const note = draft.notes.find((entry) => entry.id === noteId);
109
+ if (!note) {
110
+ throw new NotFoundError(`Question "${noteId}" not found in analysis "${analysisId}". get_analysis lists the reviewer notes and questions.`);
111
+ }
112
+ if (note.question === null) {
113
+ throw new AnalysisError(`Note "${noteId}" is not a question: the reviewer keeps it for the end of the review, and get_review_feedback hands it to you once the review is submitted.`);
114
+ }
115
+ if (note.question.answer !== null) {
116
+ throw new AnalysisError(`Question "${noteId}" was already answered at ${note.question.answer.at}.`);
117
+ }
118
+ note.question.answer = { text: answer, at: new Date().toISOString() };
119
+ });
120
+ }
121
+ /** Remplace le texte d'une remarque ; une question déjà envoyée à l'agent ne change plus. */
82
122
  export function updateNote(store, analysisId, noteId, body) {
83
123
  return store.mutate(analysisId, "user", (draft) => {
84
124
  const note = draft.notes.find((entry) => entry.id === noteId);
85
125
  if (!note)
86
126
  throw new NotFoundError(`Note "${noteId}" not found in analysis "${analysisId}".`);
127
+ if (note.question !== null)
128
+ throw new AnalysisError(`Note "${noteId}" was sent to the agent as a question: its text cannot change.`);
87
129
  if (note.text === body.text)
88
130
  return;
89
131
  reopenSubmittedReview(draft);
@@ -145,6 +187,10 @@ export function submitReview(store, analysisId, body) {
145
187
  return store.mutate(analysisId, "user", (draft) => {
146
188
  assertKnownIds("finding", body.findingIds, draft.findings.map((finding) => finding.id));
147
189
  assertKnownIds("note", body.noteIds, draft.notes.map((note) => note.id));
190
+ const questions = body.noteIds.filter((id) => draft.notes.find((note) => note.id === id)?.question !== null);
191
+ if (questions.length > 0) {
192
+ throw new AnalysisError(`Questions already sent to the agent cannot be selected in the review: ${questions.join(", ")}.`);
193
+ }
148
194
  const previousSubmission = draft.review.state === "submitted" ? recordSubmission(draft) : draft.review.previousSubmission;
149
195
  draft.review = {
150
196
  state: "submitted",
@@ -7,9 +7,10 @@ import fs from "fs";
7
7
  import { fileURLToPath } from "url";
8
8
  import { randomUUID } from "crypto";
9
9
  import { IPCMessageSchema, PUSHED_EVENT_TYPES } from "../shared/schemas/ipc.schema.js";
10
- import { AddNoteBodySchema, DeleteNoteBodySchema, MarkProcessedBodySchema, SetFileLevelBodySchema, SetFileReviewedBodySchema, SetFindingStatusBodySchema, SubmitReviewBodySchema, UpdateNoteBodySchema, } from "../shared/schemas/api.schema.js";
10
+ import { AddNoteBodySchema, DeleteNoteBodySchema, MarkAnswerSeenBodySchema, MarkProcessedBodySchema, SetFileLevelBodySchema, SetFileReviewedBodySchema, SetFindingStatusBodySchema, SubmitReviewBodySchema, UpdateNoteBodySchema, } from "../shared/schemas/api.schema.js";
11
11
  import { resolveDataDir } from "./core/data-dir.js";
12
12
  import { resolveLogDir } from "./core/log-dir.js";
13
+ import { watchedAnalyses } from "./core/notifications.js";
13
14
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
15
  function findProjectRoot(startDir) {
15
16
  let current = startDir;
@@ -45,7 +46,8 @@ function resolveGuiMode() {
45
46
  }
46
47
  const guiMode = resolveGuiMode();
47
48
  const isStandalone = guiMode.kind === "standalone";
48
- setupLogging({ processLabel: "mcp-feature-analyzer:GUI", logDir: resolveLogDir(resolveDataDir()) });
49
+ const dataDir = resolveDataDir();
50
+ setupLogging({ processLabel: "mcp-feature-analyzer:GUI", logDir: resolveLogDir(dataDir) });
49
51
  const logger = createLogger("mcp-feature-analyzer:GUI");
50
52
  process.on("uncaughtException", (err) => {
51
53
  logger.error(`Uncaught Exception: ${err.message}`);
@@ -148,7 +150,73 @@ function changesSince(since, clientEpoch) {
148
150
  events: changesJournal.filter((entry) => entry.seq > since).map((entry) => entry.event),
149
151
  };
150
152
  }
153
+ /** Intervalle de la recherche des analyses écrites par un autre processus. */
154
+ const EXTERNAL_SCAN_MS = 2000;
155
+ /** Signature (date et taille) de chaque fichier d'analyse, à la recherche précédente. */
156
+ let analysisStamps = null;
157
+ function readAnalysisStamps() {
158
+ const stamps = new Map();
159
+ const dir = path.join(dataDir, "analyses");
160
+ for (const file of fs.readdirSync(dir)) {
161
+ if (!file.endsWith(".json"))
162
+ continue;
163
+ try {
164
+ const stat = fs.statSync(path.join(dir, file));
165
+ stamps.set(file.slice(0, -".json".length), `${stat.mtimeMs}:${stat.size}`);
166
+ }
167
+ catch {
168
+ // Fichier supprimé entre la lecture du dossier et sa date : il compte comme absent.
169
+ }
170
+ }
171
+ return stamps;
172
+ }
173
+ /**
174
+ * Journalise un évènement pour chaque analyse créée, modifiée ou supprimée sur
175
+ * disque depuis la recherche précédente, quel que soit le processus qui l'a écrite :
176
+ * une autre session de l'agent sert les mêmes analyses sans passer par ce worker.
177
+ */
178
+ function scanExternalChanges() {
179
+ let stamps;
180
+ try {
181
+ stamps = readAnalysisStamps();
182
+ }
183
+ catch (err) {
184
+ logger.error(`Scanning the analyses folder failed: ${err.message}`);
185
+ return;
186
+ }
187
+ const previous = analysisStamps;
188
+ analysisStamps = stamps;
189
+ if (previous === null)
190
+ return;
191
+ const changed = [...new Set([...stamps.keys(), ...previous.keys()])].filter((id) => stamps.get(id) !== previous.get(id));
192
+ if (changed.length === 0)
193
+ return;
194
+ const timestamp = new Date().toISOString();
195
+ for (const analysisId of changed)
196
+ recordChange({ type: "ANALYSIS_UPDATED", data: { analysisId }, timestamp });
197
+ recordChange({ type: "ANALYSES_UPDATED", data: {}, timestamp });
198
+ }
199
+ /**
200
+ * Prend l'état du disque de l'analyse annoncée par le master comme référence : ce
201
+ * changement n'est pas annoncé une seconde fois par la recherche suivante.
202
+ */
203
+ function acknowledgeOnDisk(analysisId) {
204
+ if (analysisStamps === null)
205
+ return;
206
+ try {
207
+ const stat = fs.statSync(path.join(dataDir, "analyses", `${analysisId}.json`));
208
+ analysisStamps.set(analysisId, `${stat.mtimeMs}:${stat.size}`);
209
+ }
210
+ catch (err) {
211
+ if (err.code === "ENOENT")
212
+ analysisStamps.delete(analysisId);
213
+ else
214
+ logger.error(`Reading the analysis file of ${analysisId} failed: ${err.message}`);
215
+ }
216
+ }
151
217
  function setupIpcHandlers() {
218
+ scanExternalChanges();
219
+ setInterval(scanExternalChanges, EXTERNAL_SCAN_MS);
152
220
  process.on("error", (err) => {
153
221
  if (err.code === "ERR_IPC_CHANNEL_CLOSED")
154
222
  return;
@@ -173,6 +241,8 @@ function setupIpcHandlers() {
173
241
  }
174
242
  if (PUSHED_EVENTS.has(msg.type)) {
175
243
  recordChange(msg);
244
+ if (msg.type === "ANALYSIS_UPDATED" && typeof msg.data?.analysisId === "string")
245
+ acknowledgeOnDisk(msg.data.analysisId);
176
246
  return;
177
247
  }
178
248
  logger.debug(`Unhandled IPC message type: ${msg.type}`);
@@ -277,6 +347,14 @@ app.delete("/api/analyses/:id/notes/:noteId", async (c) => {
277
347
  return read.response;
278
348
  return forward(c, "DELETE_NOTE", { analysisId: c.req.param("id"), noteId: c.req.param("noteId"), body: read.body });
279
349
  });
350
+ app.post("/api/analyses/:id/notes/:noteId/answer-seen", async (c) => {
351
+ const read = await readBody(c, MarkAnswerSeenBodySchema);
352
+ if ("response" in read)
353
+ return read.response;
354
+ return forward(c, "MARK_ANSWER_SEEN", { analysisId: c.req.param("id"), noteId: c.req.param("noteId"), body: read.body });
355
+ });
356
+ /** Analyses suivies par un veilleur de notifications vivant ; chacune couvre aussi ses revues de suivi. */
357
+ app.get("/api/watchers", (c) => c.json({ analysisIds: watchedAnalyses(dataDir) }));
280
358
  app.post("/api/analyses/:id/review", async (c) => {
281
359
  const read = await readBody(c, SubmitReviewBodySchema);
282
360
  if ("response" in read)