@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,66 @@
1
+ /**
2
+ * CR-SM-407 — wer traegt ein Risiko? Je Risiko seine Traeger, je Traeger seine Risiken.
3
+ *
4
+ * Ein Risiko ist eine REQ mit Rolle `risk`, seine Gegenmassnahmen die REQs mit Rolle `mitigation`
5
+ * unter ihm (`compose`) — woertlich die Definition von FM-02. TRAEGER sind die Funktionen, die eine
6
+ * Gegenmassnahme erfuellen. Je weniger Funktionen ein Risiko tragen, desto leichter ist es zu
7
+ * fuehren; gemessen 2026-10-11 trennt das die Modelle der Familie deutlich (energymanager: 8 von 8
8
+ * Risiken an genau einer Funktion, sigllm: 2 von 16).
9
+ *
10
+ * ## Diese Datei URTEILT NICHT
11
+ *
12
+ * Keine Regel, keine Schwelle, kein Katalogeintrag — dieselbe Trennung wie `functionCriticality`
13
+ * und `chainMetrics`. Drei Regelkandidaten (Risiko am Modul, Gegenmassnahme am System, Fluss mit
14
+ * gemischter Kopplung) sind im Review geprueft und verworfen (CR-SM-407).
15
+ *
16
+ * ## Traeger sind BLATTFUNKTIONEN
17
+ *
18
+ * | Erfueller | Traeger |
19
+ * |---|---|
20
+ * | FUNC | sie selbst; ein Block ist kein Erfueller (FC-03, Fehler) |
21
+ * | MOD | die Blattfunktionen seines Teilbaums (`subtreeFuncs` — derselbe Modulbegriff wie R-04) |
22
+ * | FCHAIN | ihre Glieder (direkte compose-Kante, R-30s Definition); ein Block ist kein Glied (FC-03, Fehler) |
23
+ * | SYS | KEINE |
24
+ *
25
+ * Eine Gegenmassnahme am System „gilt quer": sie zaehlt nicht in die Traeger, sonst truege jede
26
+ * Funktion jedes solche Risiko und die Flaeche zeigte keinen Fortschritt. Der Ort am System IST
27
+ * die Kennzeichnung — es gibt dafuer kein Attribut. Der Erfueller steht in `satisfiers`; ein
28
+ * Risiko, das nur dort haengt, hat eine leere Traegerliste und ist trotzdem nicht ohne Erfueller.
29
+ *
30
+ * ## Zwei Listen, eine Relation
31
+ *
32
+ * `risks` und `surface` sind dieselben Paare (Risiko, Traeger), einmal je Risiko, einmal je
33
+ * Traeger. Alles Weitere ist ablesbar und steht deshalb NICHT als Feld da:
34
+ *
35
+ * - die Flaeche ist die Laenge von `surface`;
36
+ * - der Sockel sind die `satisfiers`, deren `by` ein SYS ist;
37
+ * - ein Risiko ohne Erfueller ist eine Zeile mit leeren `satisfiers` (FM-02 meldet das Risiko
38
+ * ohne Gegenmassnahme, RD-01 die Gegenmassnahme ohne Erfueller);
39
+ * - wie viel an einem Traeger haengt, steht in seinen `risks` und in `functionCriticality().chains`.
40
+ *
41
+ * Kein Gewicht: die Summe ueber das Modell war in der Probe nachgetragen und ist aus den zwei
42
+ * Listen bildbar.
43
+ *
44
+ * Jede Liste ist nach Kennung sortiert.
45
+ *
46
+ * @author andreas@siglochconsulting
47
+ */
48
+ import { z } from 'zod/v4';
49
+ import type { OntologyGraph } from './ontology.js';
50
+ export declare const RiskCarriers: z.ZodObject<{
51
+ risks: z.ZodArray<z.ZodObject<{
52
+ riskId: z.ZodString;
53
+ carriers: z.ZodArray<z.ZodString>;
54
+ satisfiers: z.ZodArray<z.ZodObject<{
55
+ mitigation: z.ZodString;
56
+ by: z.ZodString;
57
+ }, z.core.$strict>>;
58
+ }, z.core.$strict>>;
59
+ surface: z.ZodArray<z.ZodObject<{
60
+ funcId: z.ZodString;
61
+ risks: z.ZodArray<z.ZodString>;
62
+ }, z.core.$strict>>;
63
+ }, z.core.$strict>;
64
+ export type RiskCarriers = z.infer<typeof RiskCarriers>;
65
+ /** Die Traeger je Risiko und die Risiken je Traeger dieses Graphen. */
66
+ export declare function riskCarriers(graph: OntologyGraph): RiskCarriers;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * CR-SM-407 — wer traegt ein Risiko? Je Risiko seine Traeger, je Traeger seine Risiken.
3
+ *
4
+ * Ein Risiko ist eine REQ mit Rolle `risk`, seine Gegenmassnahmen die REQs mit Rolle `mitigation`
5
+ * unter ihm (`compose`) — woertlich die Definition von FM-02. TRAEGER sind die Funktionen, die eine
6
+ * Gegenmassnahme erfuellen. Je weniger Funktionen ein Risiko tragen, desto leichter ist es zu
7
+ * fuehren; gemessen 2026-10-11 trennt das die Modelle der Familie deutlich (energymanager: 8 von 8
8
+ * Risiken an genau einer Funktion, sigllm: 2 von 16).
9
+ *
10
+ * ## Diese Datei URTEILT NICHT
11
+ *
12
+ * Keine Regel, keine Schwelle, kein Katalogeintrag — dieselbe Trennung wie `functionCriticality`
13
+ * und `chainMetrics`. Drei Regelkandidaten (Risiko am Modul, Gegenmassnahme am System, Fluss mit
14
+ * gemischter Kopplung) sind im Review geprueft und verworfen (CR-SM-407).
15
+ *
16
+ * ## Traeger sind BLATTFUNKTIONEN
17
+ *
18
+ * | Erfueller | Traeger |
19
+ * |---|---|
20
+ * | FUNC | sie selbst; ein Block ist kein Erfueller (FC-03, Fehler) |
21
+ * | MOD | die Blattfunktionen seines Teilbaums (`subtreeFuncs` — derselbe Modulbegriff wie R-04) |
22
+ * | FCHAIN | ihre Glieder (direkte compose-Kante, R-30s Definition); ein Block ist kein Glied (FC-03, Fehler) |
23
+ * | SYS | KEINE |
24
+ *
25
+ * Eine Gegenmassnahme am System „gilt quer": sie zaehlt nicht in die Traeger, sonst truege jede
26
+ * Funktion jedes solche Risiko und die Flaeche zeigte keinen Fortschritt. Der Ort am System IST
27
+ * die Kennzeichnung — es gibt dafuer kein Attribut. Der Erfueller steht in `satisfiers`; ein
28
+ * Risiko, das nur dort haengt, hat eine leere Traegerliste und ist trotzdem nicht ohne Erfueller.
29
+ *
30
+ * ## Zwei Listen, eine Relation
31
+ *
32
+ * `risks` und `surface` sind dieselben Paare (Risiko, Traeger), einmal je Risiko, einmal je
33
+ * Traeger. Alles Weitere ist ablesbar und steht deshalb NICHT als Feld da:
34
+ *
35
+ * - die Flaeche ist die Laenge von `surface`;
36
+ * - der Sockel sind die `satisfiers`, deren `by` ein SYS ist;
37
+ * - ein Risiko ohne Erfueller ist eine Zeile mit leeren `satisfiers` (FM-02 meldet das Risiko
38
+ * ohne Gegenmassnahme, RD-01 die Gegenmassnahme ohne Erfueller);
39
+ * - wie viel an einem Traeger haengt, steht in seinen `risks` und in `functionCriticality().chains`.
40
+ *
41
+ * Kein Gewicht: die Summe ueber das Modell war in der Probe nachgetragen und ist aus den zwei
42
+ * Listen bildbar.
43
+ *
44
+ * Jede Liste ist nach Kennung sortiert.
45
+ *
46
+ * @author andreas@siglochconsulting
47
+ */
48
+ import { z } from 'zod/v4';
49
+ import { readReqRole } from './ontology.js';
50
+ import { indexOf } from './graph-index.js';
51
+ import { subtreeFuncs } from './module-crossings.js';
52
+ // CR-SM-361: ein Zod-Vertrag, kein Typ — der Erzeuger prueft sein Ergebnis.
53
+ export const RiskCarriers = z.strictObject({
54
+ /** Eine Zeile je Risiko. */
55
+ risks: z.array(z.strictObject({
56
+ riskId: z.string(),
57
+ /** Die Blattfunktionen, die eine Gegenmassnahme dieses Risikos tragen — ohne die des Systems. */
58
+ carriers: z.array(z.string()),
59
+ /** Je satisfy-Kante an einer Gegenmassnahme: die Gegenmassnahme und ihr Erfueller, wie modelliert. */
60
+ satisfiers: z.array(z.strictObject({ mitigation: z.string(), by: z.string() })),
61
+ })),
62
+ /** Die Umkehrung: eine Zeile je Traeger mit den Risiken, die er traegt. Ihre Laenge ist die Flaeche. */
63
+ surface: z.array(z.strictObject({ funcId: z.string(), risks: z.array(z.string()).min(1) })),
64
+ });
65
+ const hasRole = (e, role) => {
66
+ if (e?.type !== 'REQ')
67
+ return false;
68
+ const r = readReqRole(e.attributes);
69
+ return r.state === 'bound' && r.value === role;
70
+ };
71
+ const byId = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
72
+ /** Die Traeger je Risiko und die Risiken je Traeger dieses Graphen. */
73
+ export function riskCarriers(graph) {
74
+ const idx = indexOf(graph);
75
+ const element = new Map(graph.elements.map((e) => [e.id, e]));
76
+ const isLeaf = (func) => !idx.out(func, 'compose').some((t) => idx.typeOf(t.target) === 'FUNC');
77
+ const carriersOf = (satisfier) => {
78
+ switch (idx.typeOf(satisfier)) {
79
+ case 'FUNC': return [satisfier]; // sie selbst — ein Block als Erfueller ist FC-03s Fehler (CR-SM-410)
80
+ case 'MOD': return [...subtreeFuncs(graph, satisfier)].filter(isLeaf);
81
+ case 'FCHAIN': // die Glieder, wie sie stehen — ein Block als Glied ist FC-03s Fehler (CR-SM-410)
82
+ return idx.out(satisfier, 'compose').map((t) => t.target).filter((id) => idx.typeOf(id) === 'FUNC');
83
+ default: return []; // SYS gilt quer; jeder andere Typ ist kein legaler Erfueller (R-18).
84
+ }
85
+ };
86
+ const risksOf = new Map();
87
+ const risks = graph.elements.filter((e) => hasRole(e, 'risk')).map((risk) => {
88
+ const mitigations = [...new Set(idx.out(risk.id, 'compose').map((t) => t.target).filter((id) => hasRole(element.get(id), 'mitigation')))];
89
+ const carriers = new Set();
90
+ const satisfiers = new Map();
91
+ for (const mitigation of mitigations) {
92
+ for (const t of idx.in(mitigation, 'satisfy')) {
93
+ satisfiers.set(`${mitigation} ${t.source}`, { mitigation, by: t.source });
94
+ for (const func of carriersOf(t.source))
95
+ carriers.add(func);
96
+ }
97
+ }
98
+ for (const func of carriers)
99
+ (risksOf.get(func) ?? risksOf.set(func, new Set()).get(func)).add(risk.id);
100
+ return {
101
+ riskId: risk.id,
102
+ carriers: [...carriers].sort(byId),
103
+ satisfiers: [...satisfiers.values()].sort((a, b) => byId(a.mitigation, b.mitigation) || byId(a.by, b.by)),
104
+ };
105
+ }).sort((a, b) => byId(a.riskId, b.riskId));
106
+ const surface = [...risksOf.entries()].sort(([a], [b]) => byId(a, b))
107
+ .map(([funcId, ids]) => ({ funcId, risks: [...ids].sort(byId) }));
108
+ return RiskCarriers.parse({ risks, surface });
109
+ }
@@ -124,16 +124,10 @@ export const RULE_HELP = {
124
124
  se: "One element tracked by more than one `CR` with `status` open/in-progress.",
125
125
  vorschlag: 'Kläre, welcher der offenen Änderungsaufträge an {n} zuerst ändert.',
126
126
  },
127
- 'FC-02': {
128
- plain: "A scenario that is not broken into sub-scenarios has no described sequence of steps → add one, even if the steps are done by hand.",
129
- se: "Leaf `UC` (no `UC -compose-> UC`) with no `FCHAIN`. A chain may consist of EXISTING FUNCs an actor strings together — it costs a node plus compose edges, not code.",
130
- prompt: "se:author-uc",
131
- vorschlag: 'Beschreibe die Abläufe {n} als Kette von Funktionen.',
132
- },
133
127
  'FC-03': {
134
- plain: "A step inside a sequence contains further steps, so the sequence has hidden depth → lift them to the same level.",
135
- se: "`FUNC` inside an `FCHAIN` that itself `compose`s other `FUNC`s. Chains are flat by construction.",
136
- vorschlag: 'Hebe die inneren Schritte der Funktionen {n} auf die Ebene ihrer Kette.',
128
+ plain: "A step that contains further steps is used as if it were a single step: it sits in a sequence, or it is named as the one that fulfils a requirement. A container only collects steps → put its inner steps into the chain, and attach the requirement to the inner step that really carries it.",
129
+ se: "`FUNC` that `compose`s other `FUNC`s (a block) and is a member of an `FCHAIN` or `satisfy`s a `REQ`. A block is neither chain member nor satisfier: chains are flat, and a requirement hangs on the leaf function that carries it (a requirement of the whole belongs to `MOD`, `FCHAIN` or `SYS`). Error (CR-SM-410).",
130
+ vorschlag: 'Nimm statt der Blöcke {n} ihre inneren Schritte in die Kette und hänge ihre Anforderung an den Schritt, der sie trägt.',
137
131
  },
138
132
  'FC-04': {
139
133
  plain: "A sequence either has nobody starting it or nothing coming back out → wire both ends to whoever uses it.",
@@ -250,9 +244,9 @@ export const RULE_HELP = {
250
244
  vorschlag: 'Lege zuerst das System an und benenne, was gebaut wird.',
251
245
  },
252
246
  'R-08': {
253
- plain: "A link points at something that no longer exists → repair or remove the broken link.",
254
- se: "Trace whose source or target element is missing (dangling reference).",
255
- vorschlag: 'Repariere oder entferne die Verbindungen an {n}, deren Ziel fehlt.',
247
+ plain: "The stored model contradicts its own format: a link points at something that no longer exists, or an element carries a value its field does not know → repair or remove the link, set the field to a known value.",
248
+ se: "Two cases (CR-SM-411): a trace whose source or target element is missing (dangling reference), or an element field outside the element contract (`OntologyElement`: `kinds`, `status`, `method`, …; `role` at a `REQ`). The second case names field and value; it is legacy data that entered past the gate.",
249
+ vorschlag: 'Richte den Bestand an {n}: entferne Verbindungen, deren Ziel fehlt, und setze Felder mit unbekanntem Wert auf einen Wert, den der Vertrag kennt.',
256
250
  },
257
251
  'R-10': {
258
252
  plain: "A piece of data goes nowhere — nothing produces or consumes it → connect it to a function or a person/outside system.",
@@ -303,9 +297,14 @@ export const RULE_HELP = {
303
297
  },
304
298
  'R-22': {
305
299
  plain: "A function isn't assigned to any building block, so it has no home in the structure → put it on a module.",
306
- se: "`FUNC` with no `allocate` trace to a `MOD` (deployment assignment); every function lives on exactly one module.",
300
+ se: "Leaf `FUNC` (no `compose` child of type `FUNC`) with no `allocate` trace to a `MOD`; every leaf function lives on exactly one module. A block spans modules and has none (R-35, CR-SM-413).",
307
301
  vorschlag: 'Ordne die Funktionen {n} Modulen zu.',
308
302
  },
303
+ 'R-35': {
304
+ plain: "A function that only groups other functions is placed on a building block. Its inner functions often sit on different blocks, so no single one is right → remove the assignment; the inner functions keep theirs.",
305
+ se: "`FUNC` with `compose` children of type `FUNC` (a block) carrying an `allocate` trace to a `MOD`. The function tree and the module tree do not mirror each other; a block spans modules. Error (CR-SM-413).",
306
+ vorschlag: 'Löse die Modulzuordnung der Blöcke {n}; ihre inneren Funktionen behalten ihre Module.',
307
+ },
309
308
  'R-23': {
310
309
  plain: "A building block is empty — no function is assigned to it or to any block inside it → put a function on it, or remove the empty block.",
311
310
  se: "`MOD` with no `FUNC` ─allocate→ trace anywhere in its `compose` subtree (`subtreeFuncs`, the same count R-04 uses, CR-SM-321); the module-side complement of R-22 (empty-container signal like R-14/R-16/R-17). A container `MOD` whose sub-modules hold functions is not empty.",
@@ -382,6 +381,21 @@ export const RULE_HELP = {
382
381
  se: "`MOD` with neither a `path` attribute nor an allocated `FUNC` carrying a bound `realRef` — the only two ways a file resolves to a module. Without either, RC-05 and the boundary measurement are blind for this module by construction (sigllm: 0 RC-05 findings at 19 % import coverage, 8 at 81 %). The message names the cost from `importCoverage`. `external` modules are exempt, as for R-20 (CR-SM-344). Stage 11: due only once the build is open — an open CR or a first `realRef`/`testRefs` in the graph; before that it is not evaluated, not passed (CR-SM-395).",
383
382
  vorschlag: 'Gib den Modulen {n} ihren Quellordner.',
384
383
  },
384
+ 'RC-11': {
385
+ plain: "A code file belongs to no building block, so nobody checks which boundaries its imports cross → give the block that owns it its source folder, or point one of the block's functions at the file.",
386
+ se: "Import endpoint (a file that imports or is imported, tests and non-code excluded by the extractor) that resolves to no `MOD` — neither via the `realRef` of an allocated `FUNC` nor via a `MOD.path` prefix. Same resolution as RC-05 and `importCoverage`; one finding per file, anchored at the `SYS`. Stage 12: holds Bau (CR-SM-405).",
387
+ vorschlag: 'Ordne die Dateien {n} einem Modul zu.',
388
+ },
389
+ 'RC-12': {
390
+ plain: "The model says one function hands data to another and waits, but in the code neither calls the other → point the flow at the pair that really calls each other, or note in the flow where the hand-over happens.",
391
+ se: "`FLOW` with `sync: sync` whose producer and consumer `FUNC` both carry a `realRef` symbol in a file of `callScope`, yet `callEdges` holds no path of at most 3 calls between them in either direction (the answer flows from callee to caller). Silent when the `FLOW` carries a `realRef` whose symbol is declared (hand-over by callback, registry or socket, checked by the author). Pairs without binding, outside `callScope`, `async` or without `sync` are not judged; `callCoverage` counts them. Absent `callEdges` is SILENCE (CR-SM-415).",
392
+ vorschlag: 'Prüfe die Flüsse {n} gegen die Aufrufe im Code.',
393
+ },
394
+ 'RC-13': {
395
+ plain: "In the code one function calls another, but the model has no flow between them → add the flow, including the ones for setting up, starting and stopping.",
396
+ se: "Path of at most 3 calls in `callEdges` from one anchored `FUNC` (bound `realRef` symbol, file in `callScope`) to another, with no `FLOW` between the two in either direction, `sync` or `async`. A call site belongs to its innermost anchor (a method with its own `FUNC` does not count for its class); a path ends at the first other anchored `FUNC` — a path through a third one is two flows. One finding per pair, at the caller. The counterpart of RC-12; absent `callEdges` is SILENCE (CR-SM-415).",
397
+ vorschlag: 'Trage die Aufrufe von {n} als Fluss ins Modell ein.',
398
+ },
385
399
  'RD-01': {
386
400
  plain: "A smallest-piece feature has nothing built to fulfil it → add what implements it.",
387
401
  se: "Leaf `REQ` (no `compose`→`REQ` children) with no `satisfy` from a `FUNC`/`FCHAIN`/`MOD`/`SYS`.",
@@ -421,7 +435,7 @@ export const RULE_HELP = {
421
435
  },
422
436
  'UC-03': {
423
437
  plain: "A scenario says what should be possible but not how it runs → describe the steps as a chain of functions.",
424
- se: "`UC` with no `compose` trace to an `FCHAIN`. No behavioural scenario is declared.",
438
+ se: "Leaf `UC` (no `UC -compose-> UC`) with no `compose` trace to an `FCHAIN`. No behavioural scenario is declared. A chain may consist of EXISTING FUNCs an actor strings together — it costs a node plus compose edges, not code. A parent UC needs no chain of its own (CR-SM-412, formerly FC-02).",
425
439
  prompt: "se:author-uc",
426
440
  vorschlag: 'Beschreibe die Abläufe {n} als Kette von Funktionen.',
427
441
  },
@@ -161,6 +161,7 @@ export declare const ViolationContext: z.ZodObject<{
161
161
  }, z.core.$strip>>;
162
162
  value: z.ZodOptional<z.ZodNumber>;
163
163
  threshold: z.ZodOptional<z.ZodNumber>;
164
+ file: z.ZodOptional<z.ZodString>;
164
165
  }, z.core.$strip>;
165
166
  export type ViolationContext = z.infer<typeof ViolationContext>;
166
167
  export declare const RuleViolation: z.ZodObject<{
@@ -300,6 +301,7 @@ export declare const RuleViolation: z.ZodObject<{
300
301
  }, z.core.$strip>>;
301
302
  value: z.ZodOptional<z.ZodNumber>;
302
303
  threshold: z.ZodOptional<z.ZodNumber>;
304
+ file: z.ZodOptional<z.ZodString>;
303
305
  }, z.core.$strip>>;
304
306
  }, z.core.$strip>;
305
307
  export type RuleViolation = z.infer<typeof RuleViolation>;
@@ -370,6 +372,23 @@ export declare function decomposedFuncs(graph: OntologyGraph): Set<string>;
370
372
  * die zweite Wahrheit, die CR-SM-286/-302 beseitigt haben.
371
373
  */
372
374
  export declare function flowProducers(graph: OntologyGraph): Map<string, Set<string>>;
375
+ /**
376
+ * CR-SM-409 — EINE Rechnung „Funktion ohne io-Eingang oder -Ausgang", drei Abnehmer.
377
+ *
378
+ * Je FUNC, der eine Seite fehlt, die fehlenden Seiten. Eine io-Kante zaehlt, wenn ihr anderes Ende
379
+ * ein FLOW ist — die Grammatik kennt an einer FUNC nur `FLOW -io-> FUNC` und `FUNC -io-> FLOW`.
380
+ *
381
+ * Die Menge laeuft ueber ALLE FUNCs; die Grundgesamtheit legt der Abnehmer an:
382
+ * - R-31 meldet die BLAETTER daraus (durch einen Block fliessen keine Daten, CR-SM-256);
383
+ * - `chainMetrics` nennt eine Kette `loose-member`, wenn eines ihrer GLIEDER darin liegt;
384
+ * - FC-05 enthaelt sich an einer solchen Kette (eine Ursache, ein Befund).
385
+ *
386
+ * Bis hierher pruefte jede der drei Stellen selbst. Gemessen ueber 30 Modelle der Familie
387
+ * (2026-10-11): 453 Kettenglieder, 70 lose, 0 Abweichungen — kein Widerspruch, aber drei Stellen
388
+ * fuer eine Frage. R-31 zaehlte dabei jede io-Kante, die beiden anderen nur die an einem FLOW;
389
+ * auseinander liefen sie allein an einer Kante, die R-18 als Fehler meldet (in den 30 Modellen: 0).
390
+ */
391
+ export declare function unwiredFuncs(graph: OntologyGraph): Map<string, Array<'input' | 'output'>>;
373
392
  /** Der Anker eines Befunds an einem Graphen ohne SYS — kein Element traegt diese Id. */
374
393
  export declare const GRAPH_ANCHOR = "graph";
375
394
  /**
package/dist/se/rules.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * @sigloch/contracts/se — single source of truth for SE validation rules.
5
5
  */
6
6
  import { z } from 'zod/v4';
7
- import { ElementType, TraceType, readTestRefs, readRealRef } from './ontology.js';
7
+ import { ElementType, TraceType, OntologyElement, ReqKind, ReqRole, VerificationMethod, normalizeReqKinds, readReqRole, readTestRefs, readRealRef } from './ontology.js';
8
8
  import { traceRejection, admittingAlternatives, isValidTrace, BOUNDED_PATTERNS, REQUIRED_PATTERNS, maxOccurs } from './meta-model.js';
9
9
  import { indexOf } from './graph-index.js';
10
10
  import { whenDue } from './rule-due.js';
@@ -96,6 +96,12 @@ export const ViolationContext = z.object({
96
96
  */
97
97
  value: z.number().optional(),
98
98
  threshold: z.number().optional(),
99
+ /**
100
+ * CR-SM-405: die Datei, um die es geht, wenn der Befund an keinem Element haengen kann. RC-11 meldet je
101
+ * Datei ohne Modul einen Befund am SYS; ohne dieses Feld stuende die Datei nur im Meldungstext. RC-11
102
+ * setzte es seit a0c2f55, das Schema kannte es nicht — `tsc` brach ab, die Tests (ohne Typpruefung) nicht.
103
+ */
104
+ file: z.string().optional(),
99
105
  });
100
106
  export const RuleViolation = z.object({
101
107
  rule_id: z.string(),
@@ -357,13 +363,59 @@ function testMustVerifyReq(graph) {
357
363
  // R-07: DELETED — absorbed into BQ-07 (CR-180)
358
364
  // ---------------------------------------------------------------------------
359
365
  // ---------------------------------------------------------------------------
360
- // R-08: Bidirectional trace consistency
366
+ // R-08: Datenintegritaet des Bestands — zwei Faelle, eine Aussage: die gespeicherten Daten
367
+ // widersprechen ihrem Schema.
368
+ // 1. eine Kante zeigt auf ein Element, das es nicht gibt;
369
+ // 2. ein Element traegt in einem Feld einen Wert, den der Element-Vertrag nicht kennt (CR-SM-411).
361
370
  // ---------------------------------------------------------------------------
371
+ const ELEMENT_CONTRACT_HINT = `Set the field to a value the contract knows: kinds ∈ ${ReqKind.options.join('|')} ` +
372
+ `(${ReqRole.options.join('|')} is REQ.attributes.role, not a kind) · ` +
373
+ `status ∈ ${OntologyElement.shape.status.unwrap().options.join('|')} · ` +
374
+ `method ∈ ${VerificationMethod.options.join('|')}`;
375
+ /**
376
+ * CR-SM-411: der zweite Fall. Bis hierher wurde der Element-Vertrag nur an dem geprueft, was ein Zug
377
+ * schreibt (graphcode-Gate, lokale Kennung `SCHEMA-02`). Was am Gate vorbei ins Modell kam (Import,
378
+ * Seed), nannte keine Regel: 100 Verstoesse in 6 von 36 Modelldateien der Familie (98 an `kinds`
379
+ * aus der Zeit vor CR-SM-366, 2 an `status`), und die Messung in graphcode brach daran ab (CR-GC-786).
380
+ *
381
+ * Die Regel fuehrt KEINE Feldliste: sie haelt jedes Feld, das das Element traegt, gegen sein Schema
382
+ * in `OntologyElement`. Fehlend und `null` ist kein Verstoss — ungueltig ist nicht fehlend, und die
383
+ * flache SSOT traegt z. B. kein `created_at`. `kinds` wird gelesen wie ueberall (`normalizeReqKinds`:
384
+ * ein String ist die Schreibform von Format-E, kein Verstoss). `role` ist kein Schema-Feld, sondern
385
+ * ein Attribut der Anforderung mit einem Leser (`readReqRole`); dessen `invalid` ist derselbe Verstoss.
386
+ *
387
+ * Der Text nennt nur Kennung, Feld und Wert: das Gate vergleicht Befunde vorher und nachher am Text,
388
+ * und ein anderer Zug am selben Element darf keinen neuen Befund erzeugen.
389
+ */
390
+ function elementContract(graph) {
391
+ const finding = (e, field, value) => ({
392
+ rule_id: 'R-08',
393
+ severity: 'error',
394
+ element_id: e.id,
395
+ message: `${e.id}.${field} = ${JSON.stringify(value)} is outside the element contract`,
396
+ fix_hint: ELEMENT_CONTRACT_HINT,
397
+ context: { element_type: e.type, element_name: e.name },
398
+ });
399
+ return graph.elements.flatMap((e) => {
400
+ const out = [];
401
+ for (const [field, schema] of Object.entries(OntologyElement.shape)) {
402
+ const raw = e[field];
403
+ if (raw === undefined || raw === null)
404
+ continue;
405
+ const value = field === 'kinds' ? normalizeReqKinds(raw) : raw;
406
+ if (!schema.safeParse(value).success)
407
+ out.push(finding(e, field, value));
408
+ }
409
+ if (e.type === 'REQ' && readReqRole(e.attributes).state === 'invalid')
410
+ out.push(finding(e, 'role', e.attributes?.role));
411
+ return out;
412
+ });
413
+ }
362
414
  function traceConsistency(graph) {
363
415
  const idx = indexOf(graph);
364
416
  // CR-SM-266 D5: kein `category !== 'audit'`-Filter mehr — das Attribut ist weg, und mit ihm
365
417
  // die Moeglichkeit, eine Kante per Selbstauskunft aus der Referenzintegritaet zu nehmen.
366
- return graph.traces
418
+ const dangling = graph.traces
367
419
  .filter(t => {
368
420
  const sourceExists = idx.byId.has(t.source);
369
421
  const targetExists = idx.byId.has(t.target);
@@ -375,6 +427,7 @@ function traceConsistency(graph) {
375
427
  element_id: t.source,
376
428
  message: `Trace ${t.source}→${t.target} references non-existent element`,
377
429
  }));
430
+ return [...dangling, ...elementContract(graph)];
378
431
  }
379
432
  // ---------------------------------------------------------------------------
380
433
  // R-09: DELETED — superseded by RD-01..RD-03 (CR-180)
@@ -1447,7 +1500,11 @@ function fchainMustHaveIntegrationTest(graph, policy) {
1447
1500
  // ---------------------------------------------------------------------------
1448
1501
  function funcMustBeAllocated(graph) {
1449
1502
  const idx = indexOf(graph);
1450
- const funcs = idx.elementsOfType('FUNC');
1503
+ // CR-SM-413: Grundgesamtheit sind die BLAETTER, wie bei R-31. Ein Block gliedert den Funktionsbaum,
1504
+ // ein MOD den Abhaengigkeitsbaum; seine Kinder liegen regelmaessig auf verschiedenen Modulen, also
1505
+ // gibt es fuer ihn kein richtiges Modul. Traegt er trotzdem eins, meldet das R-35.
1506
+ const decomposed = decomposedFuncs(graph);
1507
+ const funcs = idx.elementsOfType('FUNC').filter(fn => !decomposed.has(fn.id));
1451
1508
  const mods = idx.elementsOfType('MOD');
1452
1509
  const modIds = new Set(mods.map(m => m.id));
1453
1510
  return funcs
@@ -1466,6 +1523,27 @@ function funcMustBeAllocated(graph) {
1466
1523
  }));
1467
1524
  }
1468
1525
  // ---------------------------------------------------------------------------
1526
+ // R-35: ein Block (FUNC mit FUNC-Kindern) hat kein Modul (CR-SM-413) — Fehler. Er ueberspannt Module;
1527
+ // eine `allocate`-Kante stellt ihn in die Modulsicht und laesst Modulmetriken ihn neben seinen Blaettern
1528
+ // zaehlen. Eigene Kennung statt eines Beins an FC-03: die Regel braucht MOD, also Stufe 7.
1529
+ // ---------------------------------------------------------------------------
1530
+ function blockMustNotBeAllocated(graph) {
1531
+ const idx = indexOf(graph);
1532
+ const decomposed = decomposedFuncs(graph);
1533
+ return idx.elementsOfType('FUNC')
1534
+ .filter(fn => decomposed.has(fn.id))
1535
+ .map(fn => ({ fn, mods: idx.out(fn.id, 'allocate').map(t => t.target).filter(id => idx.typeOf(id) === 'MOD') }))
1536
+ .filter(({ mods }) => mods.length > 0)
1537
+ .map(({ fn, mods }) => ({
1538
+ rule_id: 'R-35',
1539
+ severity: 'error',
1540
+ element_id: fn.id,
1541
+ message: `${fn.id} composes other FUNCs but is allocated to ${mods.join(', ')} — a block spans modules and has none of its own`,
1542
+ fix_hint: `Delete the allocate trace${mods.length > 1 ? 's' : ''} (${mods.map(m => `- ${fn.id} -allocate-> ${m}`).join('; ')}); its leaf functions keep their modules`,
1543
+ context: { element_type: fn.type, element_name: fn.name },
1544
+ }));
1545
+ }
1546
+ // ---------------------------------------------------------------------------
1469
1547
  // R-23: MOD must have an allocated FUNC (CR-208) — the MOD-side complement of
1470
1548
  // R-22. R-04 only checks the upper bound (>8 FUNCs); nothing checks the lower.
1471
1549
  // An empty module is a legal intermediate state in the model (the view no longer
@@ -1627,6 +1705,44 @@ function funcMustBeInEffectChain(graph) {
1627
1705
  // EIN Befund je FUNC (nicht je fehlender Seite): sonst uebersteigt der Zaehler den
1628
1706
  // eigenen Nenner-Beitrag, was CR-SM-242 fuer IO-01 als Fehlmessung nachgewiesen hat.
1629
1707
  // ---------------------------------------------------------------------------
1708
+ /**
1709
+ * CR-SM-409 — EINE Rechnung „Funktion ohne io-Eingang oder -Ausgang", drei Abnehmer.
1710
+ *
1711
+ * Je FUNC, der eine Seite fehlt, die fehlenden Seiten. Eine io-Kante zaehlt, wenn ihr anderes Ende
1712
+ * ein FLOW ist — die Grammatik kennt an einer FUNC nur `FLOW -io-> FUNC` und `FUNC -io-> FLOW`.
1713
+ *
1714
+ * Die Menge laeuft ueber ALLE FUNCs; die Grundgesamtheit legt der Abnehmer an:
1715
+ * - R-31 meldet die BLAETTER daraus (durch einen Block fliessen keine Daten, CR-SM-256);
1716
+ * - `chainMetrics` nennt eine Kette `loose-member`, wenn eines ihrer GLIEDER darin liegt;
1717
+ * - FC-05 enthaelt sich an einer solchen Kette (eine Ursache, ein Befund).
1718
+ *
1719
+ * Bis hierher pruefte jede der drei Stellen selbst. Gemessen ueber 30 Modelle der Familie
1720
+ * (2026-10-11): 453 Kettenglieder, 70 lose, 0 Abweichungen — kein Widerspruch, aber drei Stellen
1721
+ * fuer eine Frage. R-31 zaehlte dabei jede io-Kante, die beiden anderen nur die an einem FLOW;
1722
+ * auseinander liefen sie allein an einer Kante, die R-18 als Fehler meldet (in den 30 Modellen: 0).
1723
+ */
1724
+ export function unwiredFuncs(graph) {
1725
+ const idx = indexOf(graph);
1726
+ const hasInput = new Set(); // FLOW -io-> FUNC
1727
+ const hasOutput = new Set(); // FUNC -io-> FLOW
1728
+ for (const t of idx.tracesOfType('io')) {
1729
+ if (idx.typeOf(t.source) === 'FLOW')
1730
+ hasInput.add(t.target);
1731
+ if (idx.typeOf(t.target) === 'FLOW')
1732
+ hasOutput.add(t.source);
1733
+ }
1734
+ const out = new Map();
1735
+ for (const fn of idx.elementsOfType('FUNC')) {
1736
+ const missing = [];
1737
+ if (!hasInput.has(fn.id))
1738
+ missing.push('input');
1739
+ if (!hasOutput.has(fn.id))
1740
+ missing.push('output');
1741
+ if (missing.length > 0)
1742
+ out.set(fn.id, missing);
1743
+ }
1744
+ return out;
1745
+ }
1630
1746
  function funcMustBeWired(graph) {
1631
1747
  const idx = indexOf(graph);
1632
1748
  // CR-SM-256: Grundgesamtheit sind die BLAETTER, wie bei R-02 und R-30. Durch einen
@@ -1635,21 +1751,11 @@ function funcMustBeWired(graph) {
1635
1751
  // bewusst nicht"); die Messung liegt jetzt vor: 12 von 13 Bloecken am
1636
1752
  // graphcode-Selbstmodell melden nur deshalb, und keiner aus einem anderen Grund.
1637
1753
  const decomposed = decomposedFuncs(graph);
1638
- const funcs = idx.elementsOfType('FUNC').filter(e => !decomposed.has(e.id));
1639
1754
  const flows = idx.elementsOfType('FLOW');
1640
- const io = idx.tracesOfType('io');
1641
- const hasInput = new Set(io.map(t => t.target)); // FLOW -io-> FUNC
1642
- const hasOutput = new Set(io.map(t => t.source)); // FUNC -io-> FLOW
1643
- return funcs
1644
- .map(fn => {
1645
- const missing = [];
1646
- if (!hasInput.has(fn.id))
1647
- missing.push('input');
1648
- if (!hasOutput.has(fn.id))
1649
- missing.push('output');
1650
- return { fn, missing };
1651
- })
1652
- .filter(({ missing }) => missing.length > 0)
1755
+ const unwired = unwiredFuncs(graph); // CR-SM-409: die eine Rechnung, hier ueber die Blaetter
1756
+ return idx.elementsOfType('FUNC')
1757
+ .filter(fn => !decomposed.has(fn.id) && unwired.has(fn.id))
1758
+ .map(fn => ({ fn, missing: unwired.get(fn.id) }))
1653
1759
  .map(({ fn, missing }) => ({
1654
1760
  rule_id: 'R-31',
1655
1761
  severity: 'warning',
@@ -1713,7 +1819,7 @@ export const V3_RULES = whenDue([
1713
1819
  { id: 'R-15', name: 'FCHAIN completeness', severity: 'warning', stage: 5, role: 'existence', evaluate: fchainCompleteness, domain: ['FCHAIN'] },
1714
1820
  { id: 'R-16', name: 'ACTOR must have io', severity: 'warning', stage: 2, evaluate: actorMustHaveTrace, domain: ['ACTOR'] },
1715
1821
  { id: 'R-17', name: 'SYS must have a use case', severity: 'warning', stage: 2, role: 'existence', evaluate: sysMustHaveUseCase, domain: ['SYS'] },
1716
- { id: 'R-08', name: 'Trace consistency', severity: 'error', stage: 'immer', evaluate: traceConsistency, domain: ['all'] },
1822
+ { id: 'R-08', name: 'Data integrity', severity: 'error', stage: 'immer', evaluate: traceConsistency, domain: ['all'] },
1717
1823
  // CR-SM-242: domain ist FLOW, nicht FUNC — die Regel iteriert ueber FLOWs und meldet am FLOW.
1718
1824
  // Als ['FUNC'] deklariert erhoehte sie den Zaehler einer Grundgesamtheit, zu der ihre
1719
1825
  // Verstoesse nicht gehoerten (bis zu 2 Legs je FLOW gegen einen FUNC-Nenner).
@@ -1727,6 +1833,7 @@ export const V3_RULES = whenDue([
1727
1833
  { id: 'R-20', name: 'FUNC realRef binding', severity: 'warning', stage: 11, evaluate: funcMustHaveCodeBinding, domain: ['FUNC'] },
1728
1834
  { id: 'R-21', name: 'FUNC↔FUNC handover needs a shared chain covered by member REQs or an integration test', severity: 'warning', stage: 9, evaluate: fchainMustHaveIntegrationTest, domain: ['FCHAIN', 'FUNC'] },
1729
1835
  { id: 'R-22', name: 'FUNC must be allocated to MOD', severity: 'warning', stage: 7, role: 'existence', evaluate: funcMustBeAllocated, domain: ['FUNC'] },
1836
+ { id: 'R-35', name: 'Block is not allocated to a module', severity: 'error', stage: 7, evaluate: blockMustNotBeAllocated, domain: ['FUNC'] },
1730
1837
  { id: 'R-23', name: 'MOD must have allocated FUNC', severity: 'warning', stage: 7, evaluate: modMustHaveAllocatedFunc, domain: ['MOD'] },
1731
1838
  { id: 'R-26', name: 'SCHEMA must have realRef', severity: 'warning', stage: 11, evaluate: schemaMustHaveSchemaRef, domain: ['SCHEMA'] },
1732
1839
  { id: 'R-32', name: 'SCHEMA must have contract TEST', severity: 'warning', stage: 9, role: 'existence', evaluate: schemaMustHaveContractTest, domain: ['SCHEMA'] },
@@ -76,12 +76,19 @@ export function uc02HasActor(graph) {
76
76
  }));
77
77
  }
78
78
  // ---------------------------------------------------------------------------
79
- // UC-03: UC must have compose→FCHAIN (scenario)
79
+ // UC-03: Leaf UC must have compose→FCHAIN (scenario). Die Blatt-Bedingung stammt aus FC-02, das
80
+ // dieselbe Aussage unter zweiter Kennung meldete (CR-SM-412): ein UC mit `compose → UC`-Kindern
81
+ // braucht keine eigene Kette. Heute Vorsorge — `UC -compose-> UC` steht nicht in der Matrix.
80
82
  // ---------------------------------------------------------------------------
81
83
  export function uc03HasScenario(graph) {
82
84
  const idx = indexOf(graph);
83
85
  return idx.elementsOfType('UC')
84
- .filter(uc => !idx.out(uc.id, 'compose').some(t => idx.typeOf(t.target) === 'FCHAIN'))
86
+ .filter(uc => {
87
+ const composed = idx.out(uc.id, 'compose');
88
+ if (composed.some(t => idx.typeOf(t.target) === 'UC'))
89
+ return false;
90
+ return !composed.some(t => idx.typeOf(t.target) === 'FCHAIN');
91
+ })
85
92
  .map(uc => ({
86
93
  rule_id: 'UC-03',
87
94
  severity: 'warning',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sigloch/contracts",
3
- "version": "12.0.0",
3
+ "version": "12.7.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",