@sigloch/contracts 12.0.0 → 12.7.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.
@@ -0,0 +1,31 @@
1
+ import type { OntologyGraph } from './ontology.js';
2
+ import type { RuleViolation } from './rules.js';
3
+ import type { CodeFacts } from './conformance-rules.js';
4
+ /**
5
+ * Hoechstens so viele Aufrufkanten liegen zwischen zwei FUNCs, deren Fluss ein Aufruf belegt (RC-12) oder
6
+ * deren Aufruf einen Fluss verlangt (RC-13). Eine Invariante, keine Einstellung (Entscheid CR-SM-415):
7
+ * dasselbe Modell bekommt in jedem Repo dasselbe Urteil.
8
+ */
9
+ export declare const CALL_PATH_MAX_EDGES = 3;
10
+ /**
11
+ * Wie viel konnte RC-12 ansehen? Eine MESSUNG wie `importCoverage`, kein Befund. Gezaehlt werden die Paare
12
+ * (Erzeuger-FUNC, Abnehmer-FUNC) je FLOW; `anchored` sind die FUNCs, zwischen denen RC-13 Aufrufe sucht.
13
+ * „RC-12: 0 Befunde" heisst nur zusammen mit `checked` etwas.
14
+ */
15
+ export interface CallCoverage {
16
+ /** Synchrone Paare, die RC-12 beurteilt hat. */
17
+ checked: number;
18
+ /** Synchrone Paare mit einer Seite ohne `realRef`-Symbol. Ein Paar sind zwei FUNCs; ein Akteur zaehlt nicht. */
19
+ unbound: number;
20
+ /** Synchrone Paare mit einer Datei ausserhalb `callScope` (andere Sprache, Nachbarpaket, kein Lieferant). */
21
+ outOfScope: number;
22
+ /** Paare eines `async`-FLOW — nicht geprueft. */
23
+ async: number;
24
+ /** Paare eines FLOW ohne `sync` — die Kopplung ist unbekannt, nicht geprueft. */
25
+ syncUnknown: number;
26
+ /** FUNCs mit `realRef`-Symbol in einer Datei aus `callScope`. */
27
+ anchored: number;
28
+ }
29
+ export declare function callCoverage(graph: OntologyGraph, facts: CodeFacts): CallCoverage;
30
+ export declare function syncFlowNeedsCall(graph: OntologyGraph, facts: CodeFacts): RuleViolation[];
31
+ export declare function callNeedsFlow(graph: OntologyGraph, facts: CodeFacts): RuleViolation[];
@@ -0,0 +1,272 @@
1
+ /**
2
+ * RC-12 / RC-13 (CR-SM-415) — Fluss und Aufruf decken sich.
3
+ *
4
+ * Ein FLOW mit `sync: sync` sagt: der Erzeuger ruft den Abnehmer und wartet (oder der Abnehmer ruft den
5
+ * Erzeuger und bekommt den Inhalt als Antwort). RC-12 prueft das gegen die Aufrufe im Code, RC-13 die
6
+ * Gegenrichtung: ein Aufruf zwischen zwei verankerten FUNCs, fuer den kein FLOW steht.
7
+ *
8
+ * Gemessen vorher als Skript in graphcode (CR-GC-843, `scripts/fluss-aufruf.mjs`): 285 synchrone Paare,
9
+ * 158 pruefbar, 0 ohne Aufruf, nachdem falsche Abnehmer gerichtet waren. Die Gegenrichtung (Spike zu
10
+ * CR-GC-849): 71 verankerte FUNCs, 34 Aufrufpaare ohne FLOW, nach CR-GC-849 0.
11
+ *
12
+ * Rein ueber (graph, facts): die Aufrufkanten liefert der Lieferant je Sprache (`callEdges`, graphcode fuer
13
+ * TS, CR-GC-846). Die Regeln kennen keine Sprache. Ein Symbol in `callEdges` ist der PFAD seiner Deklaration,
14
+ * Glieder mit `.` getrennt, aeusseres zuerst (`GraphStore.open`). Daraus folgt, welche FUNC fuer einen
15
+ * Aufrufort steht: jede FUNC, deren `realRef.symbol` ein Glied dieses Pfads ist (in derselben Datei) — die
16
+ * Klasse steht fuer ihre Methoden, wie im Skript.
17
+ *
18
+ * @author andreas@siglochconsulting
19
+ */
20
+ import { readFlowSync, readRealRef } from './ontology.js';
21
+ /**
22
+ * Hoechstens so viele Aufrufkanten liegen zwischen zwei FUNCs, deren Fluss ein Aufruf belegt (RC-12) oder
23
+ * deren Aufruf einen Fluss verlangt (RC-13). Eine Invariante, keine Einstellung (Entscheid CR-SM-415):
24
+ * dasselbe Modell bekommt in jedem Repo dasselbe Urteil.
25
+ */
26
+ export const CALL_PATH_MAX_EDGES = 3;
27
+ const keyOf = (n) => `${n.file}#${n.symbol}`;
28
+ /** Die FUNC mit `realRef` samt Symbol — gebunden, unabhaengig von `callScope`. */
29
+ function boundFuncs(graph) {
30
+ const out = new Map();
31
+ for (const el of graph.elements) {
32
+ if (el.type !== 'FUNC')
33
+ continue;
34
+ const r = readRealRef(el.attributes);
35
+ if (r.state !== 'bound' || r.value.symbol === undefined)
36
+ continue;
37
+ out.set(el.id, { id: el.id, file: r.value.file, segments: r.value.symbol.split('.') });
38
+ }
39
+ return out;
40
+ }
41
+ /** Die Dateien, deren Aufrufe der Lieferant vollstaendig liefert. Ohne `callEdges` ist es keine. */
42
+ function scopeOf(facts) {
43
+ return facts.callEdges === undefined ? new Set() : new Set(facts.callScope ?? []);
44
+ }
45
+ /**
46
+ * Wo im Pfad `symbol` die FUNC `a` endet — der Index ihres letzten Glieds, oder -1, wenn `a` nicht fuer diesen
47
+ * Aufrufort steht. Der groessere Index ist der innere Anker.
48
+ */
49
+ function anchorDepth(a, node) {
50
+ if (node.file !== a.file)
51
+ return -1;
52
+ const path = node.symbol.split('.');
53
+ for (let end = path.length - 1; end >= a.segments.length - 1; end--) {
54
+ const start = end - a.segments.length + 1;
55
+ if (a.segments.every((s, i) => path[start + i] === s))
56
+ return end;
57
+ }
58
+ return -1;
59
+ }
60
+ /** Die Aufrufkanten als Nachbarschaft und alle Aufrufstellen, die darin vorkommen. */
61
+ function callGraph(facts) {
62
+ const next = new Map();
63
+ const nodes = new Map();
64
+ for (const e of facts.callEdges ?? []) {
65
+ nodes.set(keyOf(e.from), e.from);
66
+ nodes.set(keyOf(e.to), e.to);
67
+ const list = next.get(keyOf(e.from)) ?? [];
68
+ list.push(e.to);
69
+ next.set(keyOf(e.from), list);
70
+ }
71
+ // Sortiert: welcher von zwei gleich kurzen Wegen in der Meldung steht, haengt nicht an der Lieferreihenfolge.
72
+ for (const list of next.values())
73
+ list.sort((x, y) => keyOf(x).localeCompare(keyOf(y)));
74
+ return { next, nodes };
75
+ }
76
+ /** Die Aufrufstellen, fuer die `a` steht (jede Tiefe). */
77
+ function coveredBy(a, nodes) {
78
+ return new Set([...nodes].filter(([, n]) => anchorDepth(a, n) >= 0).map(([k]) => k));
79
+ }
80
+ /** Kuerzester Weg von `from` nach `to` ueber hoechstens CALL_PATH_MAX_EDGES Kanten — oder null. */
81
+ function shortestPath(next, from, to) {
82
+ let frontier = [...from].sort().map((k) => [k]);
83
+ const seen = new Set(from);
84
+ for (let d = 1; d <= CALL_PATH_MAX_EDGES; d++) {
85
+ const following = [];
86
+ for (const path of frontier) {
87
+ for (const n of next.get(path[path.length - 1]) ?? []) {
88
+ const k = keyOf(n);
89
+ if (to.has(k))
90
+ return [...path, k];
91
+ if (seen.has(k))
92
+ continue;
93
+ seen.add(k);
94
+ following.push([...path, k]);
95
+ }
96
+ }
97
+ frontier = following;
98
+ }
99
+ return null;
100
+ }
101
+ /** Je FLOW die Paare (Erzeuger-FUNC, Abnehmer-FUNC), getrennt nach `sync`, `async` und unbekannt. */
102
+ function flowPairs(graph) {
103
+ const typeOf = new Map(graph.elements.map((e) => [e.id, e.type]));
104
+ const io = graph.traces.filter((t) => t.type === 'io');
105
+ const out = { sync: [], async: 0, unknown: 0 };
106
+ for (const flow of [...graph.elements].filter((e) => e.type === 'FLOW').sort((a, b) => a.id.localeCompare(b.id))) {
107
+ const producers = io.filter((t) => t.target === flow.id && typeOf.get(t.source) === 'FUNC').map((t) => t.source).sort();
108
+ const consumers = io.filter((t) => t.source === flow.id && typeOf.get(t.target) === 'FUNC').map((t) => t.target).sort();
109
+ const n = producers.length * consumers.length;
110
+ if (n === 0)
111
+ continue;
112
+ const sync = readFlowSync(flow.attributes);
113
+ if (sync.state !== 'bound') {
114
+ out.unknown += n;
115
+ continue;
116
+ }
117
+ if (sync.value === 'async') {
118
+ out.async += n;
119
+ continue;
120
+ }
121
+ for (const from of producers)
122
+ for (const to of consumers)
123
+ out.sync.push({ flowId: flow.id, from, to });
124
+ }
125
+ return out;
126
+ }
127
+ function pairVerdict(p, bound, scope) {
128
+ const a = bound.get(p.from);
129
+ const b = bound.get(p.to);
130
+ if (!a || !b)
131
+ return 'unbound';
132
+ if (!scope.has(a.file) || !scope.has(b.file))
133
+ return 'outOfScope';
134
+ return 'checked';
135
+ }
136
+ export function callCoverage(graph, facts) {
137
+ const bound = boundFuncs(graph);
138
+ const scope = scopeOf(facts);
139
+ const pairs = flowPairs(graph);
140
+ const count = { checked: 0, unbound: 0, outOfScope: 0 };
141
+ for (const p of pairs.sync)
142
+ count[pairVerdict(p, bound, scope)]++;
143
+ const anchored = [...bound.values()].filter((a) => scope.has(a.file)).length;
144
+ return { ...count, async: pairs.async, syncUnknown: pairs.unknown, anchored };
145
+ }
146
+ /** Der FLOW belegt die Uebergabe selbst: `realRef` mit Symbol, das in seiner Datei deklariert ist. */
147
+ function handOverProven(attributes, facts) {
148
+ const r = readRealRef(attributes);
149
+ if (r.state === 'absent')
150
+ return { ok: false };
151
+ if (r.state === 'invalid')
152
+ return { ok: false, ref: 'invalid' };
153
+ const ref = `${r.value.file}#${r.value.symbol ?? ''}`;
154
+ const f = facts.files[r.value.file];
155
+ const ok = r.value.symbol !== undefined && f?.exists === true && f.declaredSymbols.includes(r.value.symbol);
156
+ return { ok, ref };
157
+ }
158
+ // RC-12: ein synchroner Fluss ohne Aufruf. Je Paar ein Befund am FLOW. Ohne `callEdges` still (wie RC-05
159
+ // ohne `importEdges`); ein Paar ohne Bindung oder ausserhalb `callScope` ist still und in `callCoverage`
160
+ // gezaehlt. Ein Weg in einer der beiden Richtungen zaehlt: die Antwort fliesst vom Gerufenen zum Aufrufer.
161
+ export function syncFlowNeedsCall(graph, facts) {
162
+ if (facts.callEdges === undefined)
163
+ return [];
164
+ const bound = boundFuncs(graph);
165
+ const scope = scopeOf(facts);
166
+ const { next, nodes } = callGraph(facts);
167
+ const byId = new Map(graph.elements.map((e) => [e.id, e]));
168
+ const violations = [];
169
+ for (const p of flowPairs(graph).sync) {
170
+ if (pairVerdict(p, bound, scope) !== 'checked')
171
+ continue;
172
+ const a = coveredBy(bound.get(p.from), nodes);
173
+ const b = coveredBy(bound.get(p.to), nodes);
174
+ if ([...a].some((k) => b.has(k)))
175
+ continue; // eine FUNC steht in der anderen: kein Aufruf noetig
176
+ if (shortestPath(next, a, b) ?? shortestPath(next, b, a))
177
+ continue;
178
+ const flow = byId.get(p.flowId);
179
+ const proof = handOverProven(flow.attributes, facts);
180
+ if (proof.ok)
181
+ continue;
182
+ const broken = proof.ref === undefined ? '' : ` — FLOW realRef '${proof.ref}' does not resolve`;
183
+ violations.push({
184
+ rule_id: 'RC-12',
185
+ severity: 'warning',
186
+ element_id: flow.id,
187
+ message: `${flow.id} is sync, but no call between ${p.from} and ${p.to} within ${CALL_PATH_MAX_EDGES} calls in either direction${broken}`,
188
+ fix_hint: proof.ref === undefined
189
+ ? `Re-point the flow at the FUNC pair that calls each other — or, if the hand-over is no call (callback, registry, socket), record the hand-over site via graph_mutate Format-E \`~ ${flow.id} @realRef {"file":…,"symbol":…}\``
190
+ : `Re-point the FLOW realRef at the current hand-over site via graph_mutate Format-E \`~ ${flow.id} @realRef {"file":…,"symbol":…}\` — or re-point the flow at the FUNC pair that calls each other`,
191
+ context: { element_type: 'FLOW', element_name: flow.name },
192
+ });
193
+ }
194
+ return violations;
195
+ }
196
+ // RC-13: ein Aufruf zwischen zwei verankerten FUNCs ohne FLOW (sync oder async, eine der beiden Richtungen).
197
+ // Ein Aufrufort gehoert dem INNERSTEN Anker — ohne das zaehlte `GraphStore.open` fuer die Klasse und fuer die
198
+ // Methode (Spike CR-GC-849: 36 statt 34 Paare). Ein Weg endet an der ersten anderen verankerten FUNC: ein Weg
199
+ // durch eine dritte sind zwei Fluesse, nicht einer. Je ungeordnetem Paar ein Befund, am Aufrufer; rufen beide
200
+ // einander, an dem mit der kleineren uid. Die Anker laufen sortiert, das Ergebnis haengt nicht an der
201
+ // Reihenfolge im Graphen.
202
+ export function callNeedsFlow(graph, facts) {
203
+ if (facts.callEdges === undefined)
204
+ return [];
205
+ const scope = scopeOf(facts);
206
+ const anchors = [...boundFuncs(graph).values()].filter((a) => scope.has(a.file)).sort((x, y) => x.id.localeCompare(y.id));
207
+ if (anchors.length < 2)
208
+ return [];
209
+ const { next, nodes } = callGraph(facts);
210
+ const owner = new Map();
211
+ for (const [k, n] of nodes) {
212
+ let best;
213
+ for (const a of anchors) {
214
+ const depth = anchorDepth(a, n);
215
+ if (depth >= 0 && (!best || depth > best.depth))
216
+ best = { id: a.id, depth };
217
+ }
218
+ if (best)
219
+ owner.set(k, best.id);
220
+ }
221
+ const flowPairKeys = new Set();
222
+ const typeOf = new Map(graph.elements.map((e) => [e.id, e.type]));
223
+ const io = graph.traces.filter((t) => t.type === 'io');
224
+ for (const flow of graph.elements.filter((e) => e.type === 'FLOW')) {
225
+ const ins = io.filter((t) => t.target === flow.id && typeOf.get(t.source) === 'FUNC').map((t) => t.source);
226
+ const outs = io.filter((t) => t.source === flow.id && typeOf.get(t.target) === 'FUNC').map((t) => t.target);
227
+ for (const x of ins)
228
+ for (const y of outs)
229
+ flowPairKeys.add([x, y].sort().join('|'));
230
+ }
231
+ const nameOf = new Map(graph.elements.map((e) => [e.id, e.name]));
232
+ const reported = new Set();
233
+ const violations = [];
234
+ for (const a of anchors) {
235
+ const seen = coveredBy(a, nodes);
236
+ let frontier = [...seen].filter((k) => owner.get(k) === a.id).sort().map((k) => [k]);
237
+ for (let d = 1; d <= CALL_PATH_MAX_EDGES; d++) {
238
+ const following = [];
239
+ for (const path of frontier) {
240
+ for (const n of next.get(path[path.length - 1]) ?? []) {
241
+ const k = keyOf(n);
242
+ if (seen.has(k))
243
+ continue;
244
+ seen.add(k);
245
+ const other = owner.get(k);
246
+ if (other === undefined) {
247
+ following.push([...path, k]);
248
+ continue;
249
+ }
250
+ const pair = [a.id, other].sort().join('|');
251
+ if (reported.has(pair) || flowPairKeys.has(pair))
252
+ continue;
253
+ reported.add(pair);
254
+ violations.push({
255
+ rule_id: 'RC-13',
256
+ severity: 'warning',
257
+ element_id: a.id,
258
+ message: `${a.id} calls ${other} without a flow — path: ${[...path, k].join(' → ')}`,
259
+ fix_hint: `Model the call as a FLOW between ${a.id} and ${other} (FUNC -io-> FLOW -io-> FUNC, with its SCHEMA and sync) — construction, start and stop count too`,
260
+ context: {
261
+ element_type: 'FUNC',
262
+ element_name: nameOf.get(a.id),
263
+ candidate_targets: [{ id: other, type: 'FUNC', name: nameOf.get(other) ?? other }],
264
+ },
265
+ });
266
+ }
267
+ }
268
+ frontier = following;
269
+ }
270
+ }
271
+ return violations;
272
+ }
@@ -27,6 +27,8 @@
27
27
  * - `loose-member`: ein Glied ohne io-Eingang oder -Ausgang. Das ist die Bedingung, unter der
28
28
  * FC-05 sich ENTHAELT (R-31 meldet das Glied) — ohne diesen Grund haette eine solche Kette weder
29
29
  * einen FC-05-Befund noch einen Grund und bekaeme Zahlen.
30
+ * CR-SM-409: gerechnet von `unwiredFuncs` (`rules.ts`), derselben Rechnung, die R-31 und die
31
+ * Enthaltung von FC-05 lesen — hier ueber die GLIEDER, auch ein Block als Glied zaehlt.
30
32
  * - `no-entry` / `no-exit`: kein FLOW von bzw. zu einem Knoten AUSSERHALB der Kette. Weiter als
31
33
  * FC-04, das nur einen ACTOR gelten laesst: eine Kette, die eine andere fortsetzt, ist messbar.
32
34
  * - `empty`: keine FUNC (R-15).
@@ -55,10 +57,32 @@
55
57
  * Kettenkante gelesen. `moduleCrossings().pairs` selbst traegt die Vertraege des GANZEN Graphen
56
58
  * je ungerichtetem Paar und kann „elf Kanten auf einem Vertrag" in EINER Kette nicht zeigen.
57
59
  *
60
+ * ## CR-SM-408 — der ANTWORTWEG je Kette
61
+ *
62
+ * Die Glieder, auf die die Antwort an einen Akteur wartet: vom ACTOR rueckwaerts ueber die Fluesse,
63
+ * die `sync` tragen (`readFlowSync`; Sicht des Abnehmers, Deklaration in `ontology.ts`). Ein Fluss
64
+ * mit `async` ist vorab geliefert, an ihm endet der Weg. Portiert aus der Probe (graphanalyze
65
+ * `docs/messung/flaechen-2026-10-11/laufzeit_sync.py`), mit zwei Festlegungen des Autors, die die
66
+ * Probe nicht kannte:
67
+ *
68
+ * - Geraten wird nicht. Die Probe las „nicht als asynchron gelistet" als synchron; hier ist ein Fluss
69
+ * ohne lesbares Merkmal ein Hindernis: `answerPath` ist `null`, der Fluss steht in
70
+ * `answerPathBlockedBy`.
71
+ * - Der Weg verlaesst seine Kette nicht. Wartet ein Glied synchron auf eine FUNC, die kein Glied
72
+ * ist, ist das ebenso ein Hindernis. Die Kette zu schliessen ist Arbeit am Modell.
73
+ *
74
+ * Gelesen wird je Paar (Fluss, erzeugende FUNC), und zwar an jedem Abnehmer gleich: der ACTOR
75
+ * wartet auf das Glied, das ihm einen Fluss mit `sync` liefert (das ist die Antwort; ein Fluss mit
76
+ * `async` an einen ACTOR ist keine), ein Glied auf die Erzeuger seiner Eingaenge mit `sync`. Ein
77
+ * Fluss, den nur ein ACTOR erzeugt, ist der Eingang der Kette und fuehrt zu keinem Glied. Wer
78
+ * liefert — eine Funktion, die rechnet, oder eine, die nur haelt — unterscheidet die Rechnung
79
+ * nicht. Eine Kette ohne Antwort an einen Akteur hat den leeren Weg `[]`: niemand wartet, nichts
80
+ * hindert.
81
+ *
58
82
  * @author andreas@siglochconsulting
59
83
  */
60
84
  import { z } from 'zod/v4';
61
- import type { OntologyGraph } from './ontology.js';
85
+ import { type OntologyGraph } from './ontology.js';
62
86
  export declare const ChainMetrics: z.ZodObject<{
63
87
  chains: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
64
88
  measurable: z.ZodLiteral<true>;
@@ -91,6 +115,8 @@ export declare const ChainMetrics: z.ZodObject<{
91
115
  flow: z.ZodString;
92
116
  func: z.ZodString;
93
117
  }, z.core.$strict>>;
118
+ answerPath: z.ZodNullable<z.ZodArray<z.ZodString>>;
119
+ answerPathBlockedBy: z.ZodArray<z.ZodString>;
94
120
  chainId: z.ZodString;
95
121
  chainName: z.ZodString;
96
122
  }, z.core.$strict>, z.ZodObject<{
@@ -27,6 +27,8 @@
27
27
  * - `loose-member`: ein Glied ohne io-Eingang oder -Ausgang. Das ist die Bedingung, unter der
28
28
  * FC-05 sich ENTHAELT (R-31 meldet das Glied) — ohne diesen Grund haette eine solche Kette weder
29
29
  * einen FC-05-Befund noch einen Grund und bekaeme Zahlen.
30
+ * CR-SM-409: gerechnet von `unwiredFuncs` (`rules.ts`), derselben Rechnung, die R-31 und die
31
+ * Enthaltung von FC-05 lesen — hier ueber die GLIEDER, auch ein Block als Glied zaehlt.
30
32
  * - `no-entry` / `no-exit`: kein FLOW von bzw. zu einem Knoten AUSSERHALB der Kette. Weiter als
31
33
  * FC-04, das nur einen ACTOR gelten laesst: eine Kette, die eine andere fortsetzt, ist messbar.
32
34
  * - `empty`: keine FUNC (R-15).
@@ -55,12 +57,36 @@
55
57
  * Kettenkante gelesen. `moduleCrossings().pairs` selbst traegt die Vertraege des GANZEN Graphen
56
58
  * je ungerichtetem Paar und kann „elf Kanten auf einem Vertrag" in EINER Kette nicht zeigen.
57
59
  *
60
+ * ## CR-SM-408 — der ANTWORTWEG je Kette
61
+ *
62
+ * Die Glieder, auf die die Antwort an einen Akteur wartet: vom ACTOR rueckwaerts ueber die Fluesse,
63
+ * die `sync` tragen (`readFlowSync`; Sicht des Abnehmers, Deklaration in `ontology.ts`). Ein Fluss
64
+ * mit `async` ist vorab geliefert, an ihm endet der Weg. Portiert aus der Probe (graphanalyze
65
+ * `docs/messung/flaechen-2026-10-11/laufzeit_sync.py`), mit zwei Festlegungen des Autors, die die
66
+ * Probe nicht kannte:
67
+ *
68
+ * - Geraten wird nicht. Die Probe las „nicht als asynchron gelistet" als synchron; hier ist ein Fluss
69
+ * ohne lesbares Merkmal ein Hindernis: `answerPath` ist `null`, der Fluss steht in
70
+ * `answerPathBlockedBy`.
71
+ * - Der Weg verlaesst seine Kette nicht. Wartet ein Glied synchron auf eine FUNC, die kein Glied
72
+ * ist, ist das ebenso ein Hindernis. Die Kette zu schliessen ist Arbeit am Modell.
73
+ *
74
+ * Gelesen wird je Paar (Fluss, erzeugende FUNC), und zwar an jedem Abnehmer gleich: der ACTOR
75
+ * wartet auf das Glied, das ihm einen Fluss mit `sync` liefert (das ist die Antwort; ein Fluss mit
76
+ * `async` an einen ACTOR ist keine), ein Glied auf die Erzeuger seiner Eingaenge mit `sync`. Ein
77
+ * Fluss, den nur ein ACTOR erzeugt, ist der Eingang der Kette und fuehrt zu keinem Glied. Wer
78
+ * liefert — eine Funktion, die rechnet, oder eine, die nur haelt — unterscheidet die Rechnung
79
+ * nicht. Eine Kette ohne Antwort an einen Akteur hat den leeren Weg `[]`: niemand wartet, nichts
80
+ * hindert.
81
+ *
58
82
  * @author andreas@siglochconsulting
59
83
  */
60
84
  import { z } from 'zod/v4';
85
+ import { readFlowSync } from './ontology.js';
61
86
  import { indexOf } from './graph-index.js';
62
87
  import { chainsByFunc } from './function-criticality.js';
63
88
  import { fc05ChainConnected } from './fchain-quality-rules.js';
89
+ import { unwiredFuncs } from './rules.js';
64
90
  import { contractsOfFlow } from './module-crossings.js';
65
91
  const count = z.number().int().nonnegative();
66
92
  const identity = { chainId: z.string(), chainName: z.string() };
@@ -91,7 +117,10 @@ const MeasuredChain = z.strictObject({
91
117
  * Konzeptbegriff verlangt „synchron durchlaufen"; ohne `FLOW.sync` zaehlt jeder Durchgang.
92
118
  */
93
119
  bottlenecks: count,
94
- /** Synchrone Tiefe — in dieser Stufe nie berechnet: braucht den Leser von `FLOW.sync` (CR-SM-364). */
120
+ /**
121
+ * Synchrone Tiefe — nie berechnet und Streichkandidat fuer den naechsten Major (CR-SM-408): der
122
+ * Antwortweg ist eine Menge, keine Tiefe; die Tiefe der Probe hing an der Reihenfolge der Kanten.
123
+ */
95
124
  syncDepth: z.null(),
96
125
  /** Fehlerpfad-Tiefe — nicht berechenbar: Fehlerfluesse traegt kein Attribut (CR-SM-364, `kind` verworfen). */
97
126
  errorPathDepth: z.null(),
@@ -123,6 +152,20 @@ const MeasuredChain = z.strictObject({
123
152
  * mindestens eine FUNC verbraucht und kein Glied der Kette.
124
153
  */
125
154
  handovers: z.array(FlowAtFunc),
155
+ /**
156
+ * CR-SM-408 — der Antwortweg: die Glieder, auf die die Antwort an einen ACTOR wartet (die Glieder,
157
+ * die einem ACTOR einen Fluss mit `sync` liefern, und rueckwaerts ueber Fluesse mit `sync` ihre
158
+ * Lieferanten in der Kette). `[]`, wenn kein Glied einem ACTOR einen Fluss mit `sync` liefert.
159
+ * `null`, sobald `answerPathBlockedBy` etwas nennt — keine geratene Menge.
160
+ */
161
+ answerPath: z.array(z.string()).nullable(),
162
+ /**
163
+ * Die Fluesse, die die Aussage verhindern: ein Fluss von einem Glied an einen ACTOR oder von
164
+ * einer FUNC in ein Glied des Wegs, der das Merkmal `sync` nicht lesbar traegt, oder der `sync`
165
+ * traegt und von einer FUNC ausserhalb der Kette kommt. Leer genau dann, wenn `answerPath` nicht
166
+ * `null` ist.
167
+ */
168
+ answerPathBlockedBy: z.array(z.string()),
126
169
  });
127
170
  /** Eine nicht bewertbare Kette: der Grund statt der Zahl. Reihenfolge der Gruende ist fest. */
128
171
  const UnmeasurableChain = z.strictObject({
@@ -143,6 +186,8 @@ export function chainMetrics(graph) {
143
186
  const chainsOf = chainsByFunc(graph);
144
187
  // FC-05 ist der EINE Leser fuer „gerichtet zusammenhaengend" — hier zaehlt nur, ob er meldet.
145
188
  const fc05 = new Set(fc05ChainConnected(graph).map((v) => v.element_id));
189
+ // CR-SM-409: „ohne io-Eingang oder -Ausgang" rechnet EINE Stelle (R-31s Rechnung); hier zaehlt, ob ein Glied darin liegt.
190
+ const unwired = unwiredFuncs(graph);
146
191
  const flowsInto = (id) => idx.in(id, 'io').map((t) => t.source).filter((s) => idx.typeOf(s) === 'FLOW');
147
192
  const flowsOutOf = (id) => idx.out(id, 'io').map((t) => t.target).filter((s) => idx.typeOf(s) === 'FLOW');
148
193
  const moduleOf = (func) => idx.out(func, 'allocate').map((t) => t.target).find((m) => idx.typeOf(m) === 'MOD');
@@ -157,12 +202,9 @@ export function chainMetrics(graph) {
157
202
  const carriers = new Map(); // Kettenkante `a b` -> die FLOWs, die sie tragen
158
203
  let entry = false;
159
204
  let exit = false;
160
- let loose = false;
161
205
  for (const m of members) {
162
206
  const ins = flowsInto(m);
163
207
  const outs = flowsOutOf(m);
164
- if (ins.length === 0 || outs.length === 0)
165
- loose = true;
166
208
  for (const flow of ins)
167
209
  if (idx.in(flow, 'io').some((t) => !inChain.has(t.source)))
168
210
  entry = true;
@@ -183,7 +225,7 @@ export function chainMetrics(graph) {
183
225
  const reasons = [];
184
226
  if (fc05.has(fc.id))
185
227
  reasons.push('FC-05');
186
- if (loose)
228
+ if (members.some((m) => unwired.has(m)))
187
229
  reasons.push('loose-member');
188
230
  if (!entry)
189
231
  reasons.push('no-entry');
@@ -283,6 +325,32 @@ export function chainMetrics(graph) {
283
325
  };
284
326
  const at = (flows, farEnds) => own.flatMap((func) => [...new Set(flows(func))].sort()
285
327
  .filter((flow) => foreign(farEnds(flow))).map((flow) => ({ flow, func })));
328
+ // Antwortweg (CR-SM-408): vom ACTOR rueckwaerts ueber die Fluesse mit `sync`. Jeder Abnehmer liest
329
+ // den Fluss gleich — der ACTOR den Ausgang, ein Glied seinen Eingang.
330
+ const waits = new Set();
331
+ const blockedBy = new Set();
332
+ const open = [];
333
+ const follow = (flow, producer) => {
334
+ const sync = readFlowSync(idx.byId.get(flow)?.attributes);
335
+ if (sync.state !== 'bound' || (sync.value === 'sync' && !inChain.has(producer)))
336
+ blockedBy.add(flow);
337
+ else if (sync.value === 'sync' && !waits.has(producer)) {
338
+ waits.add(producer);
339
+ open.push(producer);
340
+ }
341
+ };
342
+ for (const m of members) {
343
+ for (const flow of flowsOutOf(m))
344
+ if (idx.out(flow, 'io').some((t) => idx.typeOf(t.target) === 'ACTOR'))
345
+ follow(flow, m);
346
+ }
347
+ while (open.length > 0) {
348
+ for (const flow of flowsInto(open.pop())) {
349
+ for (const t of idx.in(flow, 'io'))
350
+ if (idx.typeOf(t.source) === 'FUNC')
351
+ follow(flow, t.source);
352
+ }
353
+ }
286
354
  return {
287
355
  ...who,
288
356
  measurable: true,
@@ -301,6 +369,8 @@ export function chainMetrics(graph) {
301
369
  boundaries: allocated ? boundaries : null,
302
370
  imports: at(flowsInto, (flow) => idx.in(flow, 'io').map((t) => t.source)),
303
371
  handovers: at(flowsOutOf, (flow) => idx.out(flow, 'io').map((t) => t.target)),
372
+ answerPath: blockedBy.size === 0 ? [...waits].sort() : null,
373
+ answerPathBlockedBy: [...blockedBy].sort(),
304
374
  };
305
375
  });
306
376
  const measurable = chains.filter((c) => c.measurable).length;
@@ -34,6 +34,28 @@ export declare const ImportEdgeSchema: z.ZodObject<{
34
34
  to: z.ZodString;
35
35
  }, z.core.$strip>;
36
36
  export type ImportEdge = z.infer<typeof ImportEdgeSchema>;
37
+ /**
38
+ * Eine Aufrufstelle (CR-SM-415): Datei und der PFAD der Deklaration, Glieder mit `.` getrennt, aeusseres
39
+ * zuerst — `GraphStore.open`, nicht `open`. Erst der Pfad sagt, welche FUNC fuer die Stelle steht, wenn eine
40
+ * Klasse und ihre Methode je eine eigene FUNC tragen (RC-13, innerster Anker). Sprachneutral: ein Rust-
41
+ * Lieferant schreibt `Store.open` fuer `impl Store { fn open }`.
42
+ */
43
+ export declare const CallSiteSchema: z.ZodObject<{
44
+ file: z.ZodString;
45
+ symbol: z.ZodString;
46
+ }, z.core.$strip>;
47
+ /** Eine Aufrufkante: `from` ruft `to` (CR-SM-415, RC-12/RC-13). */
48
+ export declare const CallEdgeSchema: z.ZodObject<{
49
+ from: z.ZodObject<{
50
+ file: z.ZodString;
51
+ symbol: z.ZodString;
52
+ }, z.core.$strip>;
53
+ to: z.ZodObject<{
54
+ file: z.ZodString;
55
+ symbol: z.ZodString;
56
+ }, z.core.$strip>;
57
+ }, z.core.$strip>;
58
+ export type CallEdge = z.infer<typeof CallEdgeSchema>;
37
59
  /**
38
60
  * Deterministic, serializable code facts — the data contract between the
39
61
  * facts extractor (graphcode: TS parser today, ast-grep later — CR-GC-254)
@@ -61,6 +83,17 @@ export declare const CodeFactsSchema: z.ZodObject<{
61
83
  all: "all";
62
84
  referenced: "referenced";
63
85
  }>>;
86
+ callEdges: z.ZodOptional<z.ZodArray<z.ZodObject<{
87
+ from: z.ZodObject<{
88
+ file: z.ZodString;
89
+ symbol: z.ZodString;
90
+ }, z.core.$strip>;
91
+ to: z.ZodObject<{
92
+ file: z.ZodString;
93
+ symbol: z.ZodString;
94
+ }, z.core.$strip>;
95
+ }, z.core.$strip>>>;
96
+ callScope: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
97
  }, z.core.$strip>;
65
98
  export type CodeFacts = z.infer<typeof CodeFactsSchema>;
66
99
  /** A conformance rule: pure over (graph, facts) — never touches I/O itself. */
@@ -18,6 +18,7 @@ import { z } from 'zod/v4';
18
18
  import { readTestRefs, readRealRef } from './ontology.js';
19
19
  import { CLOSED_STATUS } from './cr-quality-rules.js';
20
20
  import { whenDue } from './rule-due.js';
21
+ import { callNeedsFlow, syncFlowNeedsCall } from './call-rules.js';
21
22
  /** Parser facts about one source file (extracted by the executor). */
22
23
  export const FileFactsSchema = z.object({
23
24
  /** File exists on disk (repo-relative path). */
@@ -42,6 +43,15 @@ export const ImportEdgeSchema = z.object({
42
43
  from: z.string(),
43
44
  to: z.string(),
44
45
  });
46
+ /**
47
+ * Eine Aufrufstelle (CR-SM-415): Datei und der PFAD der Deklaration, Glieder mit `.` getrennt, aeusseres
48
+ * zuerst — `GraphStore.open`, nicht `open`. Erst der Pfad sagt, welche FUNC fuer die Stelle steht, wenn eine
49
+ * Klasse und ihre Methode je eine eigene FUNC tragen (RC-13, innerster Anker). Sprachneutral: ein Rust-
50
+ * Lieferant schreibt `Store.open` fuer `impl Store { fn open }`.
51
+ */
52
+ export const CallSiteSchema = z.object({ file: z.string(), symbol: z.string() });
53
+ /** Eine Aufrufkante: `from` ruft `to` (CR-SM-415, RC-12/RC-13). */
54
+ export const CallEdgeSchema = z.object({ from: CallSiteSchema, to: CallSiteSchema });
45
55
  /**
46
56
  * Deterministic, serializable code facts — the data contract between the
47
57
  * facts extractor (graphcode: TS parser today, ast-grep later — CR-GC-254)
@@ -81,6 +91,18 @@ export const CodeFactsSchema = z.object({
81
91
  * would report the absence of what it never looked at. ABSENT = `referenced`.
82
92
  */
83
93
  fileScope: z.enum(['referenced', 'all']).optional(),
94
+ /**
95
+ * Die Aufrufkanten des Codes, fuer RC-12 und RC-13 (CR-SM-415). Der Lieferant waehlt nach `realRef.lang`
96
+ * (graphcode liefert TS, CR-GC-846). ABSENT = Stille, wie `importEdges` fuer RC-05: der Lieferant hat nicht
97
+ * gesucht.
98
+ */
99
+ callEdges: z.array(CallEdgeSchema).optional(),
100
+ /**
101
+ * Die Dateien, deren Aufrufe `callEdges` VOLLSTAENDIG enthaelt — eine Liste repo-relativer Pfade wie die
102
+ * Schluessel von `files`, kein Muster. Nur zwischen diesen Dateien darf ein fehlender Weg ein Befund sein;
103
+ * alles andere zaehlt `callCoverage` als `outOfScope`. ABSENT = leer.
104
+ */
105
+ callScope: z.array(z.string()).optional(),
84
106
  });
85
107
  const missingFile = (facts, file) => facts.files[file]?.exists !== true;
86
108
  // RC-01: every valid FUNC realRef must resolve — file on disk, symbol declared in
@@ -685,6 +707,27 @@ function modMustBeResolvable(graph, facts) {
685
707
  context: { element_type: el.type, element_name: el.name },
686
708
  }));
687
709
  }
710
+ // ---------------------------------------------------------------------------
711
+ // RC-11: Code, der in keinem Modul liegt (CR-SM-405). `importCoverage` war eine Messung, kein Befund:
712
+ // RC-10 meldet das Modul ohne Dateien, RC-05 nur Importe zwischen zwei aufgeloesten Modulen — eine
713
+ // Datei in GAR KEINEM Modul sah keine Regel, und die Marke Bau fiel trotzdem (energymanager/lokal-1:
714
+ // 9 von 18 Endpunkten ohne Modul). Eine Datei ist kein Element; der Befund haengt am SYS, der Anker
715
+ // ist determiniert (kleinste uid). Ohne SYS schweigt die Regel, R-33 meldet den fehlenden SYS.
716
+ // Warning wie jede RC-Regel (CR-SM-353: RC laeuft nie am Gate); auf Stufe 12 haelt jeder Befund Bau.
717
+ // ---------------------------------------------------------------------------
718
+ function codeMustBelongToModule(graph, facts) {
719
+ const sys = graph.elements.filter(e => e.type === 'SYS').map(e => e.id).sort()[0];
720
+ if (sys === undefined)
721
+ return [];
722
+ return importCoverage(graph, facts).unassigned.map(file => ({
723
+ rule_id: 'RC-11',
724
+ severity: 'warning',
725
+ element_id: sys,
726
+ message: `${file} imports or is imported, but belongs to no module — no rule can judge its boundaries`,
727
+ fix_hint: `Set the source directory of the module that owns it (\`~ MOD-x @path <dir>\`), or bind a FUNC of that module to it (\`@realRef {"file":"${file}",…}\`)`,
728
+ context: { file },
729
+ }));
730
+ }
688
731
  // CR-SM-395: Stufe 12 — der Abgleich ist faellig, sobald der Bau eroeffnet ist (s. rule-due.ts).
689
732
  // Zwei Regeln warten nicht auf den Bau und liegen deshalb auf Stufe 10, der letzten Stufe, deren
690
733
  // Faelligkeit die `domain` ist; ihre Befunde halten weiter die Marke Bau:
@@ -705,6 +748,10 @@ export const CODE_CONFORMANCE_RULES = whenDue([
705
748
  { id: 'RC-08', name: 'SCHEMA realRef is a Zod schema', severity: 'warning', stage: 12, domain: ['SCHEMA'], evaluate: schemaRefMustBeZod },
706
749
  { id: 'RC-09', name: 'SCHEMA is parsed only at its modelled interface', severity: 'warning', stage: 12, domain: ['SCHEMA'], evaluate: schemaParsedOnlyAtInterface },
707
750
  { id: 'RC-10', name: 'MOD has resolvable files', severity: 'warning', stage: 12, domain: ['MOD'], evaluate: modMustBeResolvable },
751
+ { id: 'RC-11', name: 'Code file belongs to a module', severity: 'warning', stage: 12, domain: ['SYS'], evaluate: codeMustBelongToModule },
752
+ // CR-SM-415: Fluss und Aufruf decken sich, in beiden Richtungen (call-rules.ts).
753
+ { id: 'RC-12', name: 'Sync flow has a call', severity: 'warning', stage: 12, domain: ['FLOW'], evaluate: syncFlowNeedsCall },
754
+ { id: 'RC-13', name: 'Call between anchored functions has a flow', severity: 'warning', stage: 12, domain: ['FUNC'], evaluate: callNeedsFlow },
708
755
  ]);
709
756
  /** Run all RC rules against a graph + extracted code facts. */
710
757
  export function evaluateConformanceRules(graph, facts) {
@@ -1,10 +1,9 @@
1
1
  /**
2
- * FC-02..FC-05 — FCHAIN quality rules (CR-121 Phase 1; FC-05 CR-SM-363).
2
+ * FC-03..FC-05 — FCHAIN quality rules (CR-121 Phase 1; FC-05 CR-SM-363; FC-02 in UC-03 aufgegangen, CR-SM-412).
3
3
  */
4
4
  import type { OntologyGraph } from './ontology.js';
5
5
  import type { RuleDefinition, RuleViolation } from './rules.js';
6
6
  import type { MetricPolicy } from './policy.js';
7
- export declare function fc02LeafUcHasFchain(graph: OntologyGraph): RuleViolation[];
8
7
  export declare function fc03FchainFlat(graph: OntologyGraph): RuleViolation[];
9
8
  export declare function fc04ActorBounded(graph: OntologyGraph): RuleViolation[];
10
9
  export declare function fc05ChainConnected(graph: OntologyGraph): RuleViolation[];