@sigloch/graph-view-edit 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/vite.config.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, mkdirSync, unlinkSync, existsSync, readdirSync, realpathSync, statSync, watch } from 'node:fs';
1
+ import { readFileSync, writeFileSync, mkdirSync, unlinkSync, existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
2
  import { execFileSync } from 'node:child_process';
3
3
  import { join, basename, dirname, sep } from 'node:path';
4
4
  import { createRequire } from 'node:module';
@@ -38,9 +38,12 @@ import {
38
38
  groupViolations,
39
39
  countByStage,
40
40
  callHost,
41
+ readHostSnapshot,
42
+ subscribeHost,
41
43
  HOST_SOCK_BASENAME,
42
44
  } from '@sigloch/graphcode-client';
43
45
  import { loadConfig } from './src/config.mjs';
46
+ import { codeOf, openInEditor } from './src/code-lookup.mjs';
44
47
 
45
48
  /**
46
49
  * Static config (CR-GVE-138 / REQ-ops-config-static) — loadConfig validates
@@ -83,6 +86,14 @@ function resolveRepoRoot() {
83
86
  return process.env.GVE_REPO_ROOT || process.cwd();
84
87
  }
85
88
 
89
+ /** Der Graph dieses Repos: der konfigurierte Pfad, sonst die erste Datei in docs/graph/. */
90
+ function servedGraphPath(repoRoot) {
91
+ if (existsSync(join(repoRoot, APP_CONFIG.graph.path))) return APP_CONFIG.graph.path;
92
+ const graphDir = join(repoRoot, 'docs', 'graph');
93
+ const hit = existsSync(graphDir) ? readdirSync(graphDir).find((f) => f.endsWith('.graph.json')) : null;
94
+ return hit ? `docs/graph/${hit}` : APP_CONFIG.graph.path;
95
+ }
96
+
86
97
  /**
87
98
  * The repo this instance serves, as a PHYSICAL path — the identity signal a
88
99
  * launcher needs to tell "the viewer already serving MY repo" apart from "some
@@ -222,6 +233,8 @@ function graphStaticPlugin() {
222
233
  res.setHeader('Content-Type', 'application/json');
223
234
  // Die Frische-Ampel der Doc-View vergleicht gegen diesen Stempel.
224
235
  res.setHeader('Last-Modified', statSync(filePath).mtime.toUTCString());
236
+ // Ohne Cache-Control hält der Browser die Datei heuristisch und zeigt nach einem Export den alten Stand.
237
+ res.setHeader('Cache-Control', 'no-cache');
225
238
  res.end(readFileSync(filePath));
226
239
  };
227
240
  return {
@@ -259,13 +272,7 @@ function configApiPlugin() {
259
272
  const repoRoot = resolveRepoRoot();
260
273
  const config = structuredClone(APP_CONFIG);
261
274
  config.repoRoot = servedRepoRoot();
262
- if (!existsSync(join(repoRoot, config.graph.path))) {
263
- const graphDir = join(repoRoot, 'docs', 'graph');
264
- const hit = existsSync(graphDir)
265
- ? readdirSync(graphDir).find((f) => f.endsWith('.graph.json'))
266
- : null;
267
- if (hit) config.graph.path = `docs/graph/${hit}`;
268
- }
275
+ config.graph.path = servedGraphPath(repoRoot);
269
276
  res.setHeader('Content-Type', 'application/json');
270
277
  res.end(JSON.stringify(config));
271
278
  };
@@ -528,28 +535,36 @@ const ARCH_RULE_LABELS = {
528
535
  * Karte 2, Tabellenteil (CR-GVE-262) — die Architektur-Befunde aus dem
529
536
  * VORHANDENEN Engine-Lauf (dieselben Violations, die rules_evaluate liefert),
530
537
  * gefiltert auf R-04/RD-04/MT-02/R-23. `numbers` sind die Zahlen aus der
531
- * Regel-Meldung SELBST (keine zweite Rechnung neben der Regel); `applicable`
532
- * ist der Join gegen graph_suggest: true/false = Suggestion vorhanden und
533
- * vom Gate durchgelassen/abgelehnt, null = kein Vorschlag zu diesem Befund
534
- * (oder graph_suggest nicht erreichbar — das sagt `suggestAvailable`).
538
+ * Regel-Meldung SELBST (keine zweite Rechnung neben der Regel).
539
+ *
540
+ * CR-GVE-401: die Anwendbarkeit (`applicable`) steht NICHT mehr hier — sie braucht
541
+ * graph_suggest, und das läuft nur auf Klick (`GET /api/suggest`, `applicabilityOf`).
535
542
  */
536
- export function architectureFindings(violations, suggest) {
543
+ export function architectureFindings(violations) {
537
544
  return violations
538
545
  .filter((v) => Object.hasOwn(ARCH_RULE_LABELS, v.ruleId))
539
- .map((v) => {
540
- const s = suggest?.suggestions?.find((x) => x.ruleId === v.ruleId && x.elementId === v.elementId);
541
- return {
542
- ruleId: v.ruleId,
543
- label: ARCH_RULE_LABELS[v.ruleId],
544
- elementId: v.elementId,
545
- severity: v.severity,
546
- // Kein Treffer mitten in einem Bezeichner: die 4 in "LCOM4=6" ist Teil
547
- // des Regelnamens, keine Zahl der Meldung (Lookbehind auf Buchstaben).
548
- numbers: (v.message.match(/(?<![A-Za-z])\d+(?:[.,]\d+)?/g) ?? []).join(' / '),
549
- message: v.message,
550
- applicable: s ? s.applicable === true : null,
551
- };
552
- });
546
+ .map((v) => ({
547
+ ruleId: v.ruleId,
548
+ label: ARCH_RULE_LABELS[v.ruleId],
549
+ elementId: v.elementId,
550
+ severity: v.severity,
551
+ // Kein Treffer mitten in einem Bezeichner: die 4 in "LCOM4=6" ist Teil
552
+ // des Regelnamens, keine Zahl der Meldung (Lookbehind auf Buchstaben).
553
+ numbers: (v.message.match(/(?<![A-Za-z])\d+(?:[.,]\d+)?/g) ?? []).join(' / '),
554
+ message: v.message,
555
+ }));
556
+ }
557
+
558
+ /**
559
+ * CR-GVE-401: das Anwendbarkeits-Urteil je Befund, aus der Antwort von graph_suggest —
560
+ * `true`/`false` = Vorschlag vorhanden und vom Gate durchgelassen/abgelehnt. Ein Befund
561
+ * ohne Vorschlag steht nicht in der Liste; die Karte liest das als „kein Vorschlag".
562
+ * Nur die Architektur-Regeln der Tabelle reisen mit.
563
+ */
564
+ export function applicabilityOf(suggest) {
565
+ return (suggest?.suggestions ?? [])
566
+ .filter((s) => Object.hasOwn(ARCH_RULE_LABELS, s.ruleId))
567
+ .map((s) => ({ ruleId: s.ruleId, elementId: s.elementId, applicable: s.applicable === true }));
553
568
  }
554
569
 
555
570
  /**
@@ -993,58 +1008,60 @@ export async function fetchRuleHelp(repoRoot, ruleIds, callHostImpl = callHost)
993
1008
  }
994
1009
 
995
1010
  /**
996
- * „Der nächste Zug" (CR-GC-433, Trigger-Art 2+3) — Architektur- und
997
- * Hygiene-Empfehlung NEBENEINANDER, permanent, ohne Handoff-Endzustand als
998
- * Voraussetzung (Entscheidung (a): Architektur läuft parallel zur Hygiene,
999
- * nicht dahinter).
1011
+ * „Der nächste Zug", Architektur-Hälfte (CR-GC-433) — Top-1 von `graph_suggest`.
1000
1012
  *
1001
- * `step` ist der `GenerationStep` aus `graph_generate` (CR-GVE-302), `suggest` die
1002
- * Antwort von `graph_suggest`.
1013
+ * Reine Zusammenführung einer Host-Antwort: hier wird nichts gerankt und nichts
1014
+ * gerechnet. `graph_suggest` liefert seine Liste bereits anwendbar-zuerst
1015
+ * (CR-GC-431), also ist Top-1 schlicht das erste Element. `applicable` und
1016
+ * `applicableCount` trennen „ausführbarer Zug" von „Fund ohne Zug", `available: false`
1017
+ * trennt beides von „kein Host".
1003
1018
  *
1004
- * Reine Zusammenführung zweier Host-Antworten — hier wird nichts gerankt und
1005
- * nichts gerechnet: `graph_suggest` liefert seine Liste bereits anwendbar-zuerst
1006
- * (CR-GC-431), also ist Top-1 schlicht das erste Element. Was der Payload
1007
- * zusätzlich trägt, ist die EHRLICHKEIT der Zeile: `applicable` und
1008
- * `applicableCount` trennen „ausführbarer Zug" von „Fund ohne Zug", und
1009
- * `available: false` trennt beides von „kein Host" — drei Zustände, die als
1010
- * einer dargestellt eine Empfehlung vortäuschen würden, die es nicht gibt.
1019
+ * CR-GVE-401: kommt nur noch aus `GET /api/suggest` — nie beim Öffnen des Dashboards.
1011
1020
  */
1012
- export function nextMovePayload(step, suggest) {
1021
+ export function architectureMovePayload(suggest) {
1013
1022
  const top = suggest?.suggestions?.[0] ?? null;
1014
1023
  const edit = top?.edit ?? null;
1024
+ return {
1025
+ available: suggest != null,
1026
+ // Anwendbar = vom Gate durchgelassen UND Δm trägt in die Zielrichtung.
1027
+ // Ein positiver Score allein reicht nicht (der kann von der generischen
1028
+ // Sonde stammen), das Gate-Urteil allein auch nicht (score ≤ 0 = weg vom Ziel).
1029
+ applicableCount: (suggest?.suggestions ?? []).filter((s) => s.applicable === true && s.score > 0).length,
1030
+ top: top && {
1031
+ ruleId: top.ruleId,
1032
+ elementId: top.elementId,
1033
+ message: top.message,
1034
+ score: top.score,
1035
+ // CR-GVE-302 (vorher CR-GVE-297, Dimension): die STUFE der Regel des Zuges — aus
1036
+ // `ALL_RULE_DEFS[].stage`, derselben Angabe, aus der `countByStage` und der
1037
+ // Hygiene-Kanal ihre Stufen nehmen. Keine zweite Zuordnung im Viewer: sonst
1038
+ // koennte derselbe Zug hier unter einer anderen Stufe stehen als dort.
1039
+ stage: stageOfRule(top.ruleId),
1040
+ applicable: top.applicable === true,
1041
+ // Der konkrete Zug, nicht nur der Fund. `retire` gesetzt heißt Umhängen:
1042
+ // anwenden als EIN graph_mutate-Batch (CR-GC-435), `codeImpact` benennt
1043
+ // die Code-Arbeit, die daran hängt.
1044
+ edit: edit && {
1045
+ source: edit.source,
1046
+ target: edit.target,
1047
+ type: edit.type,
1048
+ retire: edit.retire ? { source: edit.retire.source, target: edit.retire.target, type: edit.retire.type } : null,
1049
+ codeImpact: edit.codeImpact ?? null,
1050
+ },
1051
+ },
1052
+ };
1053
+ }
1054
+
1055
+ /**
1056
+ * „Der nächste Zug", Hygiene-Hälfte (CR-GC-433, Trigger-Art 2+3) — der Schritt der
1057
+ * Maschine, `step` ist der `GenerationStep` aus `graph_generate` (CR-GVE-302).
1058
+ * Die Architektur-Hälfte läuft nur auf Klick (`architectureMovePayload`, CR-GVE-401).
1059
+ */
1060
+ export function nextMovePayload(step) {
1015
1061
  // Nur ein Schritt der Phase `expand` arbeitet an Befunden einer Stufe; im Kaltstart
1016
1062
  // trägt `focusStage` einen Seed-Schlüssel (`seed:sys`), bei Übergabe/Festgefahren nichts.
1017
1063
  const stage = step?.phase === 'expand' ? (step.focusStage ?? null) : null;
1018
1064
  return {
1019
- architecture: {
1020
- available: suggest != null,
1021
- // Anwendbar = vom Gate durchgelassen UND Δm trägt in die Zielrichtung.
1022
- // Ein positiver Score allein reicht nicht (der kann von der generischen
1023
- // Sonde stammen), das Gate-Urteil allein auch nicht (score ≤ 0 = weg vom Ziel).
1024
- applicableCount: (suggest?.suggestions ?? []).filter((s) => s.applicable === true && s.score > 0).length,
1025
- top: top && {
1026
- ruleId: top.ruleId,
1027
- elementId: top.elementId,
1028
- message: top.message,
1029
- score: top.score,
1030
- // CR-GVE-302 (vorher CR-GVE-297, Dimension): die STUFE der Regel des Zuges — aus
1031
- // `ALL_RULE_DEFS[].stage`, derselben Angabe, aus der `countByStage` und der
1032
- // Hygiene-Kanal ihre Stufen nehmen. Keine zweite Zuordnung im Viewer: sonst
1033
- // koennte derselbe Zug hier unter einer anderen Stufe stehen als dort.
1034
- stage: stageOfRule(top.ruleId),
1035
- applicable: top.applicable === true,
1036
- // Der konkrete Zug, nicht nur der Fund. `retire` gesetzt heißt Umhängen:
1037
- // anwenden als EIN graph_mutate-Batch (CR-GC-435), `codeImpact` benennt
1038
- // die Code-Arbeit, die daran hängt.
1039
- edit: edit && {
1040
- source: edit.source,
1041
- target: edit.target,
1042
- type: edit.type,
1043
- retire: edit.retire ? { source: edit.retire.source, target: edit.retire.target, type: edit.retire.type } : null,
1044
- codeImpact: edit.codeImpact ?? null,
1045
- },
1046
- },
1047
- },
1048
1065
  hygiene: {
1049
1066
  // Ein Schritt ohne Stufe (Übergabe, Festgefahren, Kaltstart) heißt „kein Befund-Schritt
1050
1067
  // offen", NICHT „nicht messbar" — deshalb hängt `available` am Host, nicht an der Stufe.
@@ -1149,10 +1166,7 @@ function dashboardApiPlugin() {
1149
1166
  // CR-GC-433: readiness UND der Schritt (graph_generate, CR-GVE-302) in EINER Welle. Beide sind reine
1150
1167
  // Lesezugriffe auf denselben Graphen und stören einander nicht; nacheinander
1151
1168
  // gerufen kostete der dritte Host-Roundtrip so viel, dass die Dashboard-Tests
1152
- // in ihr 5-s-Fenster liefen (gemessen 4,1 s → 6 s). graph_suggest bleibt
1153
- // BEWUSST danach und allein: es fährt je Kandidat einen dryRun und stellt die
1154
- // In-Memory-Kopie danach wieder her — parallel dazu zu lesen hieße, den
1155
- // Zwischenstand einer Sonde zu messen.
1169
+ // in ihr 5-s-Fenster liefen (gemessen 4,1 s → 6 s).
1156
1170
  // CR-GVE-272: graph_metrics reist in DERSELBEN Welle mit — auch ein reiner
1157
1171
  // Lesezugriff auf denselben Graphen, also derselbe Grund wie bei next_step.
1158
1172
  const [host, nextStep, hostMetrics] = await Promise.all([
@@ -1165,16 +1179,13 @@ function dashboardApiPlugin() {
1165
1179
  // EINE Liste für Empfehlungen und Architektur-Befunde — die
1166
1180
  // des Reports, egal aus welcher der beiden Quellen er stammt.
1167
1181
  const violations = report.violations ?? [];
1168
- // CR-GVE-262: graph_suggest liefert das Anwendbarkeits-Urteil — nur mit
1169
- // laufendem Host; ohne bleibt suggest null und die Karte sagt es.
1182
+ // CR-GVE-401: graph_suggest läuft NICHT hier. Es kostet 4,3–4,6 s und blockiert dabei
1183
+ // den Host; es gehört zu GET /api/suggest und läuft nur auf Klick.
1170
1184
  //
1171
1185
  // CR-GVE-301: hat in der ersten Welle KEINER der drei Aufrufe einen Host erreicht,
1172
- // wird nicht ein viertes Mal gefragt. `callHost` wartet je Aufruf 2 s auf einen
1173
- // noch bootenden Socket; die zweite Welle verdoppelte das auf 4 s und ließ die
1174
- // Antwort ohne Host unter Last über das 5-s-Fenster der Tests laufen. Die Antwort
1175
- // stünde ohnehin fest (null) — dieselbe Klammer wie bei `ruleHelp` unten.
1186
+ // wird nicht ein weiteres Mal gefragt (`ruleHelp` unten): `callHost` wartet je Aufruf
1187
+ // 2 s auf einen noch bootenden Socket, die Antwort stünde ohnehin fest (leer).
1176
1188
  const hostAnswered = host.report != null || nextStep != null || hostMetrics.metrics != null;
1177
- const suggest = hostAnswered ? await fetchSuggest(cwd) : null;
1178
1189
  const payload = {
1179
1190
  member: basename(file).replace(/\.graph\.json$/, ''),
1180
1191
  repoRoot: servedRepoRoot(),
@@ -1197,7 +1208,7 @@ function dashboardApiPlugin() {
1197
1208
  // CR-GVE-262: die zwei Architektur-Karten — Kohäsion aus der
1198
1209
  // graph_metrics-Referenzrechnung (contracts moduleMetrics, auf dem RAW
1199
1210
  // OntologyGraph der committeten Datei), Befunde aus demselben
1200
- // Engine-Lauf wie rules_evaluate, applicable aus graph_suggest.
1211
+ // Engine-Lauf wie rules_evaluate.
1201
1212
  // CR-GVE-272: Modulzahlen, Schwellen und Ist-Vektor kommen aus EINER
1202
1213
  // Host-Antwort (graph_metrics) statt aus drei lokalen Pfaden; `origin`
1203
1214
  // sagt an, wenn stattdessen der Fallback gerechnet hat. `findings` bleibt,
@@ -1209,13 +1220,11 @@ function dashboardApiPlugin() {
1209
1220
  ontologyJson: hostMetrics.metrics ? null : JSON.parse(readFileSync(file, 'utf8')),
1210
1221
  repoRoot: cwd,
1211
1222
  }),
1212
- findings: architectureFindings(violations, suggest),
1213
- suggestAvailable: suggest != null,
1223
+ findings: architectureFindings(violations),
1214
1224
  },
1215
- // CR-GC-433 (Trigger-Art 2+3): die permanente Zeile „Der nächste Zug" —
1216
- // Architektur (graph_suggest Top-1) und Hygiene (graph_generate, der Schritt)
1217
- // nebeneinander, unabhängig davon, ob irgendeine Marke erreicht ist.
1218
- nextMove: nextMovePayload(nextStep, suggest),
1225
+ // CR-GC-433 (Trigger-Art 2+3): die permanente Zeile „Der nächste Zug" — hier die
1226
+ // Hygiene (graph_generate, der Schritt); die Architektur-Hälfte kommt aus /api/suggest.
1227
+ nextMove: nextMovePayload(nextStep),
1219
1228
  // CR-GVE-257: Repo ohne Trajektorie → null (Karte zeigt den Hinweis).
1220
1229
  autopilot: existsSync(TRAJECTORY_FILE) ? autopilotStats(readFileSync(TRAJECTORY_FILE, 'utf8')) : null,
1221
1230
  computedAt: new Date().toISOString(),
@@ -1231,7 +1240,6 @@ function dashboardApiPlugin() {
1231
1240
  // CR-GVE-301: je Marke ihre Erklärung (graph_help kennt SRR…Bau) und die Regeln, die sie halten.
1232
1241
  ...payload.readiness.marks.flatMap((m) => [m.id, ...m.holdingGroups.map((grp) => grp.ruleId)]),
1233
1242
  ...payload.architecture.findings.map((f) => f.ruleId),
1234
- payload.nextMove.architecture.top?.ruleId,
1235
1243
  payload.nextMove.hygiene.ruleId,
1236
1244
  // CR-GVE-273: die Kennzahl-Namen, die Karte 2 zeigt — dieselbe Quelle wie
1237
1245
  // die Regeltexte (CR-GC-458). Gefragt wird nach dem, was gezeichnet wird:
@@ -1241,6 +1249,23 @@ function dashboardApiPlugin() {
1241
1249
  return payload;
1242
1250
  }
1243
1251
 
1252
+ /**
1253
+ * GET /api/suggest (CR-GVE-401) — alles, was an `graph_suggest` hängt: der Architektur-Zug
1254
+ * für „Der nächste Zug", die Anwendbarkeit je Architektur-Befund und die Erklärung der
1255
+ * Regel des Zuges. Ohne Host: `available: false`, sonst nichts (kein erfundener Wert).
1256
+ */
1257
+ async function buildSuggest() {
1258
+ const suggest = await fetchSuggest(cwd);
1259
+ const architecture = architectureMovePayload(suggest);
1260
+ return {
1261
+ available: suggest != null,
1262
+ architecture,
1263
+ applicability: applicabilityOf(suggest),
1264
+ ruleHelp: suggest == null ? {} : await fetchRuleHelp(cwd, [architecture.top?.ruleId]),
1265
+ computedAt: new Date().toISOString(),
1266
+ };
1267
+ }
1268
+
1244
1269
  /**
1245
1270
  * GET /api/view-doc?id=<viewId> (CR-GVE-250) — der einzige Weg zu
1246
1271
  * docs/views/<name>.md, gelesen vom Dokumentfenster (DocView): `dist/` liefert
@@ -1299,8 +1324,17 @@ function dashboardApiPlugin() {
1299
1324
  });
1300
1325
  return;
1301
1326
  }
1327
+ // CR-GVE-401: graph_suggest nur auf Klick. Es fährt je Kandidat einen dryRun am Host und
1328
+ // blockiert ihn 4–5 s — deshalb nicht im Status-Payload, sondern hier.
1329
+ if (url.pathname === '/api/suggest') {
1330
+ buildSuggest().then((payload) => {
1331
+ res.setHeader('Content-Type', 'application/json');
1332
+ res.end(JSON.stringify(payload));
1333
+ });
1334
+ return;
1335
+ }
1302
1336
  if (url.pathname !== '/api/dashboard') return next();
1303
- // CR-GVE-262: buildDashboard ist async (graph_suggest über host.sock).
1337
+ // buildDashboard ist async (Host-Aufrufe über host.sock).
1304
1338
  buildDashboard().then((payload) => {
1305
1339
  res.setHeader('Content-Type', 'application/json');
1306
1340
  res.end(JSON.stringify(payload));
@@ -1484,15 +1518,66 @@ function mutateApiPlugin() {
1484
1518
  }
1485
1519
 
1486
1520
  /**
1487
- * SSE Invalidate hub (CR-GVE-139 / REQ-live-sse), factored out of the plugin
1488
- * HTTP glue for direct unit-testability (same DI pattern as
1489
- * handleMutateRequest). GET /api/events holds the response open as a
1490
- * text/event-stream client; broadcast() pushes an `invalidate`
1491
- * LiveUpdateEvent naming the affected domains, which sse-client.mjs
1492
- * (createSSEClient) hands to each panel for a SELECTIVE refresh.
1521
+ * GET /api/code?func=<id> und POST /api/open-code { funcId } (CR-GVE-390) — der Code einer FUNC für die Detailspalte
1522
+ * und der Start des Editors. Beide lesen den `realRef` aus dem Graphen auf der Platte; siehe src/code-lookup.mjs.
1523
+ */
1524
+ function codeApiPlugin() {
1525
+ const repoRoot = resolveRepoRoot();
1526
+ const locate = (funcId) => codeOf(JSON.parse(readFileSync(join(repoRoot, servedGraphPath(repoRoot)), 'utf8')), funcId, repoRoot);
1527
+ const send = (res, status, body) => {
1528
+ res.statusCode = status;
1529
+ res.setHeader('Content-Type', 'application/json');
1530
+ res.end(JSON.stringify(body));
1531
+ };
1532
+
1533
+ const middleware = (req, res, next) => {
1534
+ const url = new URL(req.url ?? '/', 'http://localhost');
1535
+ if (url.pathname === '/api/code') {
1536
+ const code = locate(url.searchParams.get('func'));
1537
+ send(res, code.status === 'unknown' ? 404 : 200, code);
1538
+ return;
1539
+ }
1540
+ if (url.pathname !== '/api/open-code' || req.method !== 'POST') return next();
1541
+ let raw = '';
1542
+ req.on('data', (chunk) => { raw += chunk; });
1543
+ req.on('end', async () => {
1544
+ let funcId;
1545
+ try {
1546
+ ({ funcId } = JSON.parse(raw));
1547
+ } catch {
1548
+ send(res, 400, { success: false, error: 'invalid JSON body' });
1549
+ return;
1550
+ }
1551
+ const code = locate(funcId);
1552
+ if (code.status !== 'ok') {
1553
+ send(res, 404, { success: false, error: `kein Code zu ${funcId}: ${code.status}` });
1554
+ return;
1555
+ }
1556
+ send(res, 200, await openInEditor(code, APP_CONFIG.editor.command));
1557
+ });
1558
+ };
1559
+
1560
+ return {
1561
+ name: 'gve-code-api',
1562
+ configureServer(server) {
1563
+ server.middlewares.use(middleware);
1564
+ },
1565
+ configurePreviewServer(server) {
1566
+ server.middlewares.use(middleware);
1567
+ },
1568
+ };
1569
+ }
1570
+
1571
+ /**
1572
+ * SSE hub (CR-GVE-139 / REQ-live-sse), factored out of the plugin HTTP glue for direct unit-testability (same DI
1573
+ * pattern as handleMutateRequest). GET /api/events holds the response open as a text/event-stream client; `broadcast`
1574
+ * forwards a host event unchanged under its own type, sse-client.mjs hands it on. A new client hears at once whether
1575
+ * a host is there and at which version: that is its gap check after a reconnect (CR-GVE-394).
1493
1576
  */
1494
1577
  export function createEventsHub() {
1495
1578
  const clients = new Set();
1579
+ let host = { type: 'host', connected: false };
1580
+ const frameOf = (event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
1496
1581
  return {
1497
1582
  middleware(req, res, next) {
1498
1583
  if (req.url !== '/api/events') return next();
@@ -1501,12 +1586,14 @@ export function createEventsHub() {
1501
1586
  'Cache-Control': 'no-cache',
1502
1587
  Connection: 'keep-alive',
1503
1588
  });
1504
- res.write('retry: 3000\n\n');
1589
+ res.write(`retry: 3000\n\n${frameOf(host)}`);
1505
1590
  clients.add(res);
1506
1591
  req.on('close', () => clients.delete(res));
1507
1592
  },
1508
- broadcast(domains) {
1509
- const frame = `event: invalidate\ndata: ${JSON.stringify({ domains })}\n\n`;
1593
+ broadcast(event) {
1594
+ if (event.type === 'host') host = event;
1595
+ else if (event.version !== undefined) host = { ...host, version: event.version };
1596
+ const frame = frameOf(event);
1510
1597
  for (const res of clients) res.write(frame);
1511
1598
  },
1512
1599
  clientCount: () => clients.size,
@@ -1514,39 +1601,98 @@ export function createEventsHub() {
1514
1601
  }
1515
1602
 
1516
1603
  /**
1517
- * GET /api/events (CR-GVE-139). The invalidate TRIGGER is a watcher on
1518
- * docs/graph/*.graph.json — the single point every write converges on
1519
- * (own edits via /api/mutate's post-mutate export AND external writers like
1520
- * a graphcode MCP session exporting), so there's exactly one refresh path
1521
- * instead of a per-writer special case. A graph change also invalidates
1522
- * rules/readiness — both are derived from the same committed file.
1604
+ * Das Abo am Host (CR-GVE-356, CR-GVE-394): reicht jedes Event an die Browser und meldet, ob ein Host da ist. Stirbt
1605
+ * der Host, baut der Nachfolger seinen Socket neu auf; bis dahin läuft der Versuch im Takt `retryMs` weiter.
1523
1606
  */
1524
- function eventsApiPlugin() {
1525
- const hub = createEventsHub();
1526
- const graphDir = join(resolveRepoRoot(), 'docs', 'graph');
1527
- let debounce = null;
1528
- function armWatcher() {
1529
- if (!existsSync(graphDir)) return;
1530
- const watcher = watch(graphDir, (eventType, filename) => {
1531
- if (!filename?.endsWith('.graph.json')) return;
1532
- clearTimeout(debounce);
1533
- debounce = setTimeout(() => hub.broadcast(['graph', 'rules', 'readiness']), 150);
1607
+ export function startHostFeed({ socketPath, hub, subscribe = subscribeHost, retryMs = 1000 }) {
1608
+ let sub = null;
1609
+ let timer = null;
1610
+ let stopped = false;
1611
+ const connect = () => {
1612
+ sub = subscribe(socketPath, (frame) => {
1613
+ if (frame.type === 'snapshot') hub.broadcast({ type: 'host', connected: true, version: frame.version });
1614
+ else hub.broadcast(frame);
1615
+ }, () => {
1616
+ if (stopped) return;
1617
+ hub.broadcast({ type: 'host', connected: false });
1618
+ timer = setTimeout(connect, retryMs);
1619
+ timer.unref?.();
1534
1620
  });
1535
- // Never hold the process open (vitest runs this config's plugins too —
1536
- // an un-unref'd FSWatcher kept its worker from exiting).
1537
- watcher.unref();
1621
+ };
1622
+ connect();
1623
+ return { stop() { stopped = true; clearTimeout(timer); sub?.close(); } };
1624
+ }
1625
+
1626
+ /**
1627
+ * GET /api/graph (CR-GVE-356): der ganze Graph samt Version beim Host. 503 = kein Host, 409 = der Viewer zeigt per
1628
+ * `graph.path` einen anderen Graphen, als der Host bedient: beide Antworten schicken den Browser an die Datei.
1629
+ */
1630
+ export function createGraphApi({ repoRoot, readSnapshot = readHostSnapshot }) {
1631
+ return async (req, res, next) => {
1632
+ if (req.url !== '/api/graph') return next();
1633
+ res.setHeader('Content-Type', 'application/json');
1634
+ res.setHeader('Cache-Control', 'no-store');
1635
+ if (!servedGraphPath(repoRoot).startsWith('docs/graph/')) {
1636
+ res.statusCode = 409;
1637
+ res.end(JSON.stringify({ error: 'graph.path zeigt nicht auf den Graphen des Hosts' }));
1638
+ return;
1639
+ }
1640
+ try {
1641
+ const { version, formatE } = await readSnapshot(join(repoRoot, '.graphcode', HOST_SOCK_BASENAME));
1642
+ res.end(JSON.stringify({ version, formatE }));
1643
+ } catch (err) {
1644
+ res.statusCode = 503;
1645
+ res.end(JSON.stringify({ error: err.message }));
1646
+ }
1647
+ };
1648
+ }
1649
+
1650
+ /**
1651
+ * Wer hat seit dem Commit was geändert (CR-GVE-358): je uid der letzte `consumerId` aus dem Audit. `commands` nennen
1652
+ * den Batch, nicht seine Kaskaden; ein mitgelöschtes Element trägt deshalb keinen Urheber.
1653
+ */
1654
+ export function authorsSince(auditText, since) {
1655
+ const authors = {};
1656
+ for (const line of auditText.split('\n')) {
1657
+ if (!line.trim()) continue;
1658
+ const entry = JSON.parse(line);
1659
+ if (entry.result !== 'applied' || entry.timestamp <= since) continue;
1660
+ for (const c of entry.commands ?? []) {
1661
+ const uid = c.node?.uid ?? c.uid ?? c.targetUid;
1662
+ if (uid) authors[uid] = entry.consumerId;
1663
+ }
1538
1664
  }
1539
- return {
1540
- name: 'gve-events-api',
1541
- configureServer(server) {
1542
- armWatcher();
1543
- server.middlewares.use(hub.middleware);
1544
- },
1545
- configurePreviewServer(server) {
1546
- armWatcher();
1547
- server.middlewares.use(hub.middleware);
1548
- },
1665
+ return authors;
1666
+ }
1667
+
1668
+ /** GET /api/changes (CR-GVE-358): der Graph im letzten Commit samt Urhebern. Vergleichen tut der Browser. */
1669
+ export function createChangesApi({ repoRoot, git = gitOut }) {
1670
+ return (req, res, next) => {
1671
+ if (req.url !== '/api/changes') return next();
1672
+ res.setHeader('Content-Type', 'application/json');
1673
+ res.setHeader('Cache-Control', 'no-store');
1674
+ const path = servedGraphPath(repoRoot);
1675
+ const text = git(repoRoot, ['show', `HEAD:${path}`]);
1676
+ if (!text) return res.end(JSON.stringify({ base: null, authors: {} }));
1677
+ const since = new Date(git(repoRoot, ['log', '-1', '--format=%cI', '--', path]).trim()).toISOString();
1678
+ const audit = join(repoRoot, '.graphcode', 'audit.jsonl');
1679
+ res.end(JSON.stringify({ base: JSON.parse(text), authors: existsSync(audit) ? authorsSince(readFileSync(audit, 'utf8'), since) : {} }));
1680
+ };
1681
+ }
1682
+
1683
+ function eventsApiPlugin() {
1684
+ const hub = createEventsHub();
1685
+ const repoRoot = resolveRepoRoot();
1686
+ const graphApi = createGraphApi({ repoRoot });
1687
+ const changesApi = createChangesApi({ repoRoot });
1688
+ const wire = (server) => {
1689
+ const feed = startHostFeed({ socketPath: join(repoRoot, '.graphcode', HOST_SOCK_BASENAME), hub });
1690
+ server.httpServer?.once('close', () => feed.stop());
1691
+ server.middlewares.use(hub.middleware);
1692
+ server.middlewares.use(graphApi);
1693
+ server.middlewares.use(changesApi);
1549
1694
  };
1695
+ return { name: 'gve-events-api', configureServer: wire, configurePreviewServer: wire };
1550
1696
  }
1551
1697
 
1552
1698
  /**
@@ -1590,7 +1736,7 @@ function dashboardUrlPlugin() {
1590
1736
  }
1591
1737
 
1592
1738
  export default defineConfig({
1593
- plugins: [react(), graphStaticPlugin(), configApiPlugin(), dashboardApiPlugin(), mutateApiPlugin(), eventsApiPlugin(), dashboardUrlPlugin()],
1739
+ plugins: [react(), graphStaticPlugin(), configApiPlugin(), dashboardApiPlugin(), mutateApiPlugin(), codeApiPlugin(), eventsApiPlugin(), dashboardUrlPlugin()],
1594
1740
  // config.port is the default; an explicit CLI --port (e.g. the test suites'
1595
1741
  // tests/helpers/dev-server.mjs, which picks a free OS-assigned port with
1596
1742
  // --strictPort) still overrides it, per Vite's precedence.