@sigloch/contracts 11.0.0 → 12.6.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/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';
@@ -357,13 +357,59 @@ function testMustVerifyReq(graph) {
357
357
  // R-07: DELETED — absorbed into BQ-07 (CR-180)
358
358
  // ---------------------------------------------------------------------------
359
359
  // ---------------------------------------------------------------------------
360
- // R-08: Bidirectional trace consistency
360
+ // R-08: Datenintegritaet des Bestands — zwei Faelle, eine Aussage: die gespeicherten Daten
361
+ // widersprechen ihrem Schema.
362
+ // 1. eine Kante zeigt auf ein Element, das es nicht gibt;
363
+ // 2. ein Element traegt in einem Feld einen Wert, den der Element-Vertrag nicht kennt (CR-SM-411).
361
364
  // ---------------------------------------------------------------------------
365
+ const ELEMENT_CONTRACT_HINT = `Set the field to a value the contract knows: kinds ∈ ${ReqKind.options.join('|')} ` +
366
+ `(${ReqRole.options.join('|')} is REQ.attributes.role, not a kind) · ` +
367
+ `status ∈ ${OntologyElement.shape.status.unwrap().options.join('|')} · ` +
368
+ `method ∈ ${VerificationMethod.options.join('|')}`;
369
+ /**
370
+ * CR-SM-411: der zweite Fall. Bis hierher wurde der Element-Vertrag nur an dem geprueft, was ein Zug
371
+ * schreibt (graphcode-Gate, lokale Kennung `SCHEMA-02`). Was am Gate vorbei ins Modell kam (Import,
372
+ * Seed), nannte keine Regel: 100 Verstoesse in 6 von 36 Modelldateien der Familie (98 an `kinds`
373
+ * aus der Zeit vor CR-SM-366, 2 an `status`), und die Messung in graphcode brach daran ab (CR-GC-786).
374
+ *
375
+ * Die Regel fuehrt KEINE Feldliste: sie haelt jedes Feld, das das Element traegt, gegen sein Schema
376
+ * in `OntologyElement`. Fehlend und `null` ist kein Verstoss — ungueltig ist nicht fehlend, und die
377
+ * flache SSOT traegt z. B. kein `created_at`. `kinds` wird gelesen wie ueberall (`normalizeReqKinds`:
378
+ * ein String ist die Schreibform von Format-E, kein Verstoss). `role` ist kein Schema-Feld, sondern
379
+ * ein Attribut der Anforderung mit einem Leser (`readReqRole`); dessen `invalid` ist derselbe Verstoss.
380
+ *
381
+ * Der Text nennt nur Kennung, Feld und Wert: das Gate vergleicht Befunde vorher und nachher am Text,
382
+ * und ein anderer Zug am selben Element darf keinen neuen Befund erzeugen.
383
+ */
384
+ function elementContract(graph) {
385
+ const finding = (e, field, value) => ({
386
+ rule_id: 'R-08',
387
+ severity: 'error',
388
+ element_id: e.id,
389
+ message: `${e.id}.${field} = ${JSON.stringify(value)} is outside the element contract`,
390
+ fix_hint: ELEMENT_CONTRACT_HINT,
391
+ context: { element_type: e.type, element_name: e.name },
392
+ });
393
+ return graph.elements.flatMap((e) => {
394
+ const out = [];
395
+ for (const [field, schema] of Object.entries(OntologyElement.shape)) {
396
+ const raw = e[field];
397
+ if (raw === undefined || raw === null)
398
+ continue;
399
+ const value = field === 'kinds' ? normalizeReqKinds(raw) : raw;
400
+ if (!schema.safeParse(value).success)
401
+ out.push(finding(e, field, value));
402
+ }
403
+ if (e.type === 'REQ' && readReqRole(e.attributes).state === 'invalid')
404
+ out.push(finding(e, 'role', e.attributes?.role));
405
+ return out;
406
+ });
407
+ }
362
408
  function traceConsistency(graph) {
363
409
  const idx = indexOf(graph);
364
410
  // CR-SM-266 D5: kein `category !== 'audit'`-Filter mehr — das Attribut ist weg, und mit ihm
365
411
  // die Moeglichkeit, eine Kante per Selbstauskunft aus der Referenzintegritaet zu nehmen.
366
- return graph.traces
412
+ const dangling = graph.traces
367
413
  .filter(t => {
368
414
  const sourceExists = idx.byId.has(t.source);
369
415
  const targetExists = idx.byId.has(t.target);
@@ -375,6 +421,7 @@ function traceConsistency(graph) {
375
421
  element_id: t.source,
376
422
  message: `Trace ${t.source}→${t.target} references non-existent element`,
377
423
  }));
424
+ return [...dangling, ...elementContract(graph)];
378
425
  }
379
426
  // ---------------------------------------------------------------------------
380
427
  // R-09: DELETED — superseded by RD-01..RD-03 (CR-180)
@@ -1627,6 +1674,44 @@ function funcMustBeInEffectChain(graph) {
1627
1674
  // EIN Befund je FUNC (nicht je fehlender Seite): sonst uebersteigt der Zaehler den
1628
1675
  // eigenen Nenner-Beitrag, was CR-SM-242 fuer IO-01 als Fehlmessung nachgewiesen hat.
1629
1676
  // ---------------------------------------------------------------------------
1677
+ /**
1678
+ * CR-SM-409 — EINE Rechnung „Funktion ohne io-Eingang oder -Ausgang", drei Abnehmer.
1679
+ *
1680
+ * Je FUNC, der eine Seite fehlt, die fehlenden Seiten. Eine io-Kante zaehlt, wenn ihr anderes Ende
1681
+ * ein FLOW ist — die Grammatik kennt an einer FUNC nur `FLOW -io-> FUNC` und `FUNC -io-> FLOW`.
1682
+ *
1683
+ * Die Menge laeuft ueber ALLE FUNCs; die Grundgesamtheit legt der Abnehmer an:
1684
+ * - R-31 meldet die BLAETTER daraus (durch einen Block fliessen keine Daten, CR-SM-256);
1685
+ * - `chainMetrics` nennt eine Kette `loose-member`, wenn eines ihrer GLIEDER darin liegt;
1686
+ * - FC-05 enthaelt sich an einer solchen Kette (eine Ursache, ein Befund).
1687
+ *
1688
+ * Bis hierher pruefte jede der drei Stellen selbst. Gemessen ueber 30 Modelle der Familie
1689
+ * (2026-10-11): 453 Kettenglieder, 70 lose, 0 Abweichungen — kein Widerspruch, aber drei Stellen
1690
+ * fuer eine Frage. R-31 zaehlte dabei jede io-Kante, die beiden anderen nur die an einem FLOW;
1691
+ * auseinander liefen sie allein an einer Kante, die R-18 als Fehler meldet (in den 30 Modellen: 0).
1692
+ */
1693
+ export function unwiredFuncs(graph) {
1694
+ const idx = indexOf(graph);
1695
+ const hasInput = new Set(); // FLOW -io-> FUNC
1696
+ const hasOutput = new Set(); // FUNC -io-> FLOW
1697
+ for (const t of idx.tracesOfType('io')) {
1698
+ if (idx.typeOf(t.source) === 'FLOW')
1699
+ hasInput.add(t.target);
1700
+ if (idx.typeOf(t.target) === 'FLOW')
1701
+ hasOutput.add(t.source);
1702
+ }
1703
+ const out = new Map();
1704
+ for (const fn of idx.elementsOfType('FUNC')) {
1705
+ const missing = [];
1706
+ if (!hasInput.has(fn.id))
1707
+ missing.push('input');
1708
+ if (!hasOutput.has(fn.id))
1709
+ missing.push('output');
1710
+ if (missing.length > 0)
1711
+ out.set(fn.id, missing);
1712
+ }
1713
+ return out;
1714
+ }
1630
1715
  function funcMustBeWired(graph) {
1631
1716
  const idx = indexOf(graph);
1632
1717
  // CR-SM-256: Grundgesamtheit sind die BLAETTER, wie bei R-02 und R-30. Durch einen
@@ -1635,21 +1720,11 @@ function funcMustBeWired(graph) {
1635
1720
  // bewusst nicht"); die Messung liegt jetzt vor: 12 von 13 Bloecken am
1636
1721
  // graphcode-Selbstmodell melden nur deshalb, und keiner aus einem anderen Grund.
1637
1722
  const decomposed = decomposedFuncs(graph);
1638
- const funcs = idx.elementsOfType('FUNC').filter(e => !decomposed.has(e.id));
1639
1723
  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)
1724
+ const unwired = unwiredFuncs(graph); // CR-SM-409: die eine Rechnung, hier ueber die Blaetter
1725
+ return idx.elementsOfType('FUNC')
1726
+ .filter(fn => !decomposed.has(fn.id) && unwired.has(fn.id))
1727
+ .map(fn => ({ fn, missing: unwired.get(fn.id) }))
1653
1728
  .map(({ fn, missing }) => ({
1654
1729
  rule_id: 'R-31',
1655
1730
  severity: 'warning',
@@ -1713,7 +1788,7 @@ export const V3_RULES = whenDue([
1713
1788
  { id: 'R-15', name: 'FCHAIN completeness', severity: 'warning', stage: 5, role: 'existence', evaluate: fchainCompleteness, domain: ['FCHAIN'] },
1714
1789
  { id: 'R-16', name: 'ACTOR must have io', severity: 'warning', stage: 2, evaluate: actorMustHaveTrace, domain: ['ACTOR'] },
1715
1790
  { 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'] },
1791
+ { id: 'R-08', name: 'Data integrity', severity: 'error', stage: 'immer', evaluate: traceConsistency, domain: ['all'] },
1717
1792
  // CR-SM-242: domain ist FLOW, nicht FUNC — die Regel iteriert ueber FLOWs und meldet am FLOW.
1718
1793
  // Als ['FUNC'] deklariert erhoehte sie den Zaehler einer Grundgesamtheit, zu der ihre
1719
1794
  // Verstoesse nicht gehoerten (bis zu 2 Legs je FLOW gegen einen FUNC-Nenner).
@@ -52,14 +52,6 @@ function firstWord(name) {
52
52
  return text.toLowerCase().split(/[^\p{L}\p{N}]+/u).find(w => w.length > 0) ?? '';
53
53
  }
54
54
  const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
55
- /** Feld-Menge eines SCHEMA: `attributes.fields` (Array), sonst Beschreibungs-Token. */
56
- function schemaFields(el) {
57
- const fields = el.attributes?.fields;
58
- if (Array.isArray(fields) && fields.length > 0) {
59
- return new Set(fields.map(f => String(typeof f === 'object' && f !== null ? (f.name ?? JSON.stringify(f)) : f).toLowerCase()));
60
- }
61
- return tokens(el.description);
62
- }
63
55
  const CACHE = new WeakMap();
64
56
  function build(graph) {
65
57
  // ND-01: 0.35*descr_jaccard + 0.25*verb_match + 0.25*io_topology + 0.15*req_overlap
@@ -77,14 +69,16 @@ function build(graph) {
77
69
  + 0.15 * jaccard(fReq[i], fReq[j]))),
78
70
  };
79
71
  // ND-02: 0.50*field_jaccard + 0.30*descr_jaccard + 0.20*usage_overlap
72
+ // CR-SM-399: die Feldmenge eines SCHEMA IST seine Beschreibung — das Attribut `fields` (nie
73
+ // deklariert, 0 Traeger) wird nicht mehr gelesen. Beide Terme bleiben getrennt stehen: zu 0.8
74
+ // zusammengezogen wiche der Wert in der letzten Stelle ab, und kein Score soll sich bewegen.
80
75
  const schemas = graph.elements.filter(e => e.type === 'SCHEMA').sort(byId);
81
- const sFields = schemas.map(schemaFields);
82
76
  const sDescr = schemas.map(s => tokens(s.description));
83
77
  const sUse = schemas.map(s => partners(graph, s.id, ['relation', 'io', 'compose']));
84
78
  const schema = {
85
79
  ids: schemas.map(s => s.id),
86
80
  matrix: schemas.map((_, i) => schemas.map((_, j) => i === j ? 1
87
- : 0.5 * jaccard(sFields[i], sFields[j])
81
+ : 0.5 * jaccard(sDescr[i], sDescr[j])
88
82
  + 0.3 * jaccard(sDescr[i], sDescr[j])
89
83
  + 0.2 * jaccard(sUse[i], sUse[j]))),
90
84
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sigloch/contracts",
3
- "version": "11.0.0",
3
+ "version": "12.6.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",