Skip to content

cogant.translate

The cogant.translate package is the semantic-mapping engine: it takes the typed program graph produced by cogant.graph, applies a priority-ordered rule set, runs a bounded fixpoint loop, and emits a set of SemanticMapping records annotated with MappingKind (HIDDEN_STATE / OBSERVATION / ACTION / POLICY / CONSTRAINT / ...) and a confidence score.

Package

cogant.translate

Translation module for converting program graphs to semantic concepts.

ActionRule

Bases: TranslationRule

Maps setter/mutator functions to action modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80) alongside PolicyRule, ContextRule, OrchestratorRule and CircuitBreakerRule. Rationale: action semantics are slightly less specific than PreferenceRule/TestAssertionRule (0.85) because CRUD verbs are the most overloaded lexical category in real codebases. The edge-based fallback writes_only >= 2 was added (commit e1eb463) to recover recall on functional codebases where writes are named apply/reduce rather than set/update. TODO(calibration): sweep the >=2 writes threshold in {1, 2, 3} on the 20-repo corpus.

Source code in py/cogant/translate/rules/semantic.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
class ActionRule(TranslationRule):
    """Maps setter/mutator functions to action modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80)
        alongside ``PolicyRule``, ``ContextRule``, ``OrchestratorRule``
        and ``CircuitBreakerRule``. Rationale: action semantics are
        slightly less specific than ``PreferenceRule``/``TestAssertionRule``
        (0.85) because CRUD verbs are the most overloaded lexical
        category in real codebases. The edge-based fallback
        ``writes_only >= 2`` was added (commit e1eb463) to recover
        recall on functional codebases where writes are named
        ``apply``/``reduce`` rather than ``set``/``update``.
        TODO(calibration): sweep the ``>=2`` writes threshold in
        {1, 2, 3} on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions/methods that mutate state.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched action functions/methods.
        """
        matches = []
        action_keywords = ACTION_KEYWORDS

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            # Token-anchored keyword match (no raw substring containment).
            keyword_match = _matches_keyword(node.name, action_keywords)

            # Count mutations (also used as edge-based fallback trigger)
            out_edges = graph.get_edges_from(node.id)
            writes = sum(1 for e in out_edges if e.kind in (EdgeKind.WRITES, EdgeKind.MUTATES))
            calls = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

            # Fallback threshold: ``writes >= 1`` outgoing WRITES/MUTATES
            # edge. Principled default aligned with the property invariant
            # in ``tests/property/test_translation_invariants.py`` which
            # accepts a single mutation edge as valid structural grounding
            # for the ACTION role. A ``>=2`` floor would reject legitimate
            # mutators whose static graph collapses multiple ``self.X``
            # writes into a single edge to the parent class node (a known
            # tree-sitter Python behaviour on ``self`` attribute writes).
            # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus if
            # false-positive rate on functional codebases exceeds ~5%.
            if keyword_match or writes >= 1:
                matches.append(
                    {
                        "node_id": node.id,
                        "write_count": writes,
                        "call_count": calls,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create action mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for action.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"act_{node_id}_{hashlib.sha256(b'action').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band). Action
        # verbs are slightly overloaded in practice (CRUD terms appear
        # in helpers and wrappers), hence 0.05 below the 0.85 band of
        # ``PreferenceRule``/``TestAssertionRule``. Parser certainty
        # 0.85 = full AST-native band (names + edges both parsed by
        # Python AST, not the tree-sitter fallback).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ACTION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Action",
            description=f"Function/method '{node.name}' performs action (mutates state)",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={
                        "write_count": match["write_count"],
                        "call_count": match["call_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this node performs an action.

        Mirrors the :meth:`matches` decision by checking for action
        keywords in the node name and counting outgoing WRITES/MUTATES
        edges. The rule fires when either (a) the name contains an
        action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge
        exists (the functional-codebase recall threshold).
        """
        if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"action rule only applies to functions/methods; node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        matched_keywords = _matched_keywords(node.name, ACTION_KEYWORDS)

        out_edges = graph.get_edges_from(node.id)
        write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]
        mutate_edges = [e for e in out_edges if e.kind == EdgeKind.MUTATES]
        call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        evidence: list[str] = []
        if matched_keywords:
            evidence.append(f"keyword match: {matched_keywords}")
        evidence.append(f"WRITES count: {len(write_edges)}")
        if mutate_edges:
            evidence.append(f"MUTATES count: {len(mutate_edges)}")
        evidence.append(f"CALLS count: {len(call_edges)}")
        if write_edges:
            write_targets = [e.target_id for e in write_edges]
            evidence.append(f"WRITES targets: {sorted(write_targets)[:5]}")

        keyword_match = bool(matched_keywords)
        mutation_count = len(write_edges) + len(mutate_edges)
        writes_threshold = mutation_count >= 1

        if keyword_match or writes_threshold:
            if keyword_match and writes_threshold:
                reason = (
                    f"name contains action keyword(s) {matched_keywords} "
                    f"AND has {mutation_count} WRITES/MUTATES edge(s) "
                    f"(>=1 threshold)"
                )
            elif keyword_match:
                reason = f"name contains action keyword(s) {matched_keywords}"
            else:
                reason = (
                    f"has {mutation_count} WRITES/MUTATES edge(s) "
                    f"(>=1 mutation threshold) with no action keyword"
                )
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=reason,
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"no action keyword in '{node.name}' and "
                f"{mutation_count} WRITES/MUTATES edges (<1 threshold)"
            ),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "action"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ACTION

    def to_gnn_role(self) -> str:
        """Return the GNN role string for action mappings.

        Returns:
            GNN role identifier.
        """
        return "ACTION"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create action mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for action.

Source code in py/cogant/translate/rules/semantic.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create action mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for action.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"act_{node_id}_{hashlib.sha256(b'action').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band). Action
    # verbs are slightly overloaded in practice (CRUD terms appear
    # in helpers and wrappers), hence 0.05 below the 0.85 band of
    # ``PreferenceRule``/``TestAssertionRule``. Parser certainty
    # 0.85 = full AST-native band (names + edges both parsed by
    # Python AST, not the tree-sitter fallback).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ACTION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Action",
        description=f"Function/method '{node.name}' performs action (mutates state)",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={
                    "write_count": match["write_count"],
                    "call_count": match["call_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

explain(node, graph, query)

Explain whether this node performs an action.

Mirrors the :meth:matches decision by checking for action keywords in the node name and counting outgoing WRITES/MUTATES edges. The rule fires when either (a) the name contains an action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge exists (the functional-codebase recall threshold).

Source code in py/cogant/translate/rules/semantic.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this node performs an action.

    Mirrors the :meth:`matches` decision by checking for action
    keywords in the node name and counting outgoing WRITES/MUTATES
    edges. The rule fires when either (a) the name contains an
    action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge
    exists (the functional-codebase recall threshold).
    """
    if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"action rule only applies to functions/methods; node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    matched_keywords = _matched_keywords(node.name, ACTION_KEYWORDS)

    out_edges = graph.get_edges_from(node.id)
    write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]
    mutate_edges = [e for e in out_edges if e.kind == EdgeKind.MUTATES]
    call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

    evidence: list[str] = []
    if matched_keywords:
        evidence.append(f"keyword match: {matched_keywords}")
    evidence.append(f"WRITES count: {len(write_edges)}")
    if mutate_edges:
        evidence.append(f"MUTATES count: {len(mutate_edges)}")
    evidence.append(f"CALLS count: {len(call_edges)}")
    if write_edges:
        write_targets = [e.target_id for e in write_edges]
        evidence.append(f"WRITES targets: {sorted(write_targets)[:5]}")

    keyword_match = bool(matched_keywords)
    mutation_count = len(write_edges) + len(mutate_edges)
    writes_threshold = mutation_count >= 1

    if keyword_match or writes_threshold:
        if keyword_match and writes_threshold:
            reason = (
                f"name contains action keyword(s) {matched_keywords} "
                f"AND has {mutation_count} WRITES/MUTATES edge(s) "
                f"(>=1 threshold)"
            )
        elif keyword_match:
            reason = f"name contains action keyword(s) {matched_keywords}"
        else:
            reason = (
                f"has {mutation_count} WRITES/MUTATES edge(s) "
                f"(>=1 mutation threshold) with no action keyword"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(
            f"no action keyword in '{node.name}' and "
            f"{mutation_count} WRITES/MUTATES edges (<1 threshold)"
        ),
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find functions/methods that mutate state.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched action functions/methods.

Source code in py/cogant/translate/rules/semantic.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions/methods that mutate state.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched action functions/methods.
    """
    matches = []
    action_keywords = ACTION_KEYWORDS

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        # Token-anchored keyword match (no raw substring containment).
        keyword_match = _matches_keyword(node.name, action_keywords)

        # Count mutations (also used as edge-based fallback trigger)
        out_edges = graph.get_edges_from(node.id)
        writes = sum(1 for e in out_edges if e.kind in (EdgeKind.WRITES, EdgeKind.MUTATES))
        calls = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

        # Fallback threshold: ``writes >= 1`` outgoing WRITES/MUTATES
        # edge. Principled default aligned with the property invariant
        # in ``tests/property/test_translation_invariants.py`` which
        # accepts a single mutation edge as valid structural grounding
        # for the ACTION role. A ``>=2`` floor would reject legitimate
        # mutators whose static graph collapses multiple ``self.X``
        # writes into a single edge to the parent class node (a known
        # tree-sitter Python behaviour on ``self`` attribute writes).
        # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus if
        # false-positive rate on functional codebases exceeds ~5%.
        if keyword_match or writes >= 1:
            matches.append(
                {
                    "node_id": node.id,
                    "write_count": writes,
                    "call_count": calls,
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for action mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
544
545
546
547
548
549
550
def to_gnn_role(self) -> str:
    """Return the GNN role string for action mappings.

    Returns:
        GNN role identifier.
    """
    return "ACTION"

CircuitBreakerRule

Bases: TranslationRule

Maps circuit breaker patterns to circuit-breaker modality.

Detects functions/classes that contain both a GUARDS edge and a retry/fallback pattern (name contains retry/fallback/circuit/breaker keywords or has metadata indicating retry logic).

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule/ContextRule/ OrchestratorRule. Rationale: the combined signal of GUARDS edge + retry keyword (or metadata hit) is much stronger than the keyword-only RetryPatternRule (0.70), so CircuitBreakerRule correctly wins on overlapping fragments. The composite requirement keeps false positives low — a function named retry_helper alone won't fire without a GUARDS edge.

Source code in py/cogant/translate/rules/resilience.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
class CircuitBreakerRule(TranslationRule):
    """Maps circuit breaker patterns to circuit-breaker modality.

    Detects functions/classes that contain both a GUARDS edge and a
    retry/fallback pattern (name contains retry/fallback/circuit/breaker
    keywords or has metadata indicating retry logic).

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``/``ContextRule``/
        ``OrchestratorRule``. Rationale: the combined signal of
        GUARDS edge + retry keyword (or metadata hit) is much
        stronger than the keyword-only ``RetryPatternRule`` (0.70),
        so CircuitBreakerRule correctly wins on overlapping
        fragments. The composite requirement keeps false positives
        low — a function named ``retry_helper`` alone won't fire
        without a GUARDS edge.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with GUARDS edges and retry/fallback indicators.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched circuit breaker nodes.
        """
        matches = []

        circuit_keywords = ["retry", "fallback", "circuit", "breaker"]

        # Find functions, methods, and classes
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for node in functions + methods + classes:
            out_edges = graph.get_edges_from(node.id)

            # Must have at least one GUARDS edge
            guards_edges = [e for e in out_edges if e.kind == EdgeKind.GUARDS]
            if not guards_edges:
                continue

            # Check for retry/fallback pattern via name or metadata
            name_lower = node.name.lower()
            has_keyword = any(kw in name_lower for kw in circuit_keywords)

            has_retry_metadata = False
            if node.metadata:
                meta_str = str(node.metadata).lower()
                has_retry_metadata = any(kw in meta_str for kw in circuit_keywords)

            if has_keyword or has_retry_metadata:
                guarded_ids = [e.target_id for e in guards_edges]
                matches.append(
                    {
                        "node_id": node.id,
                        "guarded_ids": guarded_ids,
                        "guards_count": len(guards_edges),
                        "keyword_match": has_keyword,
                        "metadata_match": has_retry_metadata,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create circuit-breaker mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for circuit breaker.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"cb_{node_id}_{hashlib.sha256(b'circuit_breaker').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # The composite (GUARDS edge + retry keyword/metadata)
        # requirement is a much stronger signal than
        # RetryPatternRule's keyword-only matching (0.70), so this
        # rule correctly wins overlapping conflicts.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CIRCUIT_BREAKER,
            graph_fragment_node_ids=[node_id] + match.get("guarded_ids", []),
            semantic_label=f"{node.name} - Circuit Breaker",
            description=f"{'Function' if node.kind in (NodeKind.FUNCTION, NodeKind.METHOD) else 'Class'} '{node.name}' implements circuit breaker pattern (guards {match['guards_count']} target(s))",
            confidence_score=0.80,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.80,
                    metadata={
                        "guards_count": match["guards_count"],
                        "keyword_match": match["keyword_match"],
                        "metadata_match": match["metadata_match"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native on GUARDS edges
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "circuit_breaker"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CIRCUIT_BREAKER

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create circuit-breaker mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for circuit breaker.

Source code in py/cogant/translate/rules/resilience.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create circuit-breaker mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for circuit breaker.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"cb_{node_id}_{hashlib.sha256(b'circuit_breaker').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # The composite (GUARDS edge + retry keyword/metadata)
    # requirement is a much stronger signal than
    # RetryPatternRule's keyword-only matching (0.70), so this
    # rule correctly wins overlapping conflicts.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CIRCUIT_BREAKER,
        graph_fragment_node_ids=[node_id] + match.get("guarded_ids", []),
        semantic_label=f"{node.name} - Circuit Breaker",
        description=f"{'Function' if node.kind in (NodeKind.FUNCTION, NodeKind.METHOD) else 'Class'} '{node.name}' implements circuit breaker pattern (guards {match['guards_count']} target(s))",
        confidence_score=0.80,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.80,
                metadata={
                    "guards_count": match["guards_count"],
                    "keyword_match": match["keyword_match"],
                    "metadata_match": match["metadata_match"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native on GUARDS edges
    )

matches(graph, query)

Find nodes with GUARDS edges and retry/fallback indicators.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched circuit breaker nodes.

Source code in py/cogant/translate/rules/resilience.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with GUARDS edges and retry/fallback indicators.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched circuit breaker nodes.
    """
    matches = []

    circuit_keywords = ["retry", "fallback", "circuit", "breaker"]

    # Find functions, methods, and classes
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for node in functions + methods + classes:
        out_edges = graph.get_edges_from(node.id)

        # Must have at least one GUARDS edge
        guards_edges = [e for e in out_edges if e.kind == EdgeKind.GUARDS]
        if not guards_edges:
            continue

        # Check for retry/fallback pattern via name or metadata
        name_lower = node.name.lower()
        has_keyword = any(kw in name_lower for kw in circuit_keywords)

        has_retry_metadata = False
        if node.metadata:
            meta_str = str(node.metadata).lower()
            has_retry_metadata = any(kw in meta_str for kw in circuit_keywords)

        if has_keyword or has_retry_metadata:
            guarded_ids = [e.target_id for e in guards_edges]
            matches.append(
                {
                    "node_id": node.id,
                    "guarded_ids": guarded_ids,
                    "guards_count": len(guards_edges),
                    "keyword_match": has_keyword,
                    "metadata_match": has_retry_metadata,
                }
            )

    return matches

ConfidenceModel

Computes and manages confidence scores for semantic mappings.

Combines evidence count, diversity, parser certainty, and conflict penalties to produce confidence tiers and scores.

Source code in py/cogant/translate/confidence.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
class ConfidenceModel:
    """Computes and manages confidence scores for semantic mappings.

    Combines evidence count, diversity, parser certainty, and conflict penalties
    to produce confidence tiers and scores.
    """

    # ------------------------------------------------------------------
    # Confidence-tier thresholds
    # ------------------------------------------------------------------
    # These four scalars carve [0, 1] into the four ConfidenceTier
    # bands used by ``determine_confidence_tier``. They are principled
    # defaults — not empirically calibrated — anchored to the
    # "weak / moderate / strong evidence" bands from classical
    # meta-analysis reporting conventions. Read them as:
    #   0.5  — minimum to accept a static-only mapping; below this the
    #          tier falls back to the lowest band.
    #   0.65 — extra-evidence promotion threshold: static-only rules
    #          with dynamic corroboration need the combined score to
    #          clear this bar (+0.15 over the static-only floor) before
    #          promotion to STATIC_PLUS_RUNTIME.
    #   0.4  — lower bar for runtime-only evidence because dynamic
    #          traces are noisier than static edges (-0.1 dynamic-noise
    #          discount relative to the static floor).
    #   0.9  — strong-consensus band for human-reviewed mappings.
    # See ``docs/evaluation/CALIBRATION.md`` for the full sweep plan.
    # TODO(calibration): sweep {0.4, 0.5, 0.55, 0.6, 0.65, 0.7} over a
    # 20+ repo fixture set and pick the precision/recall sweet spot.
    STATIC_ONLY_THRESHOLD = 0.5  # principled default
    STATIC_PLUS_RUNTIME_THRESHOLD = 0.65  # principled default (+0.15 corroboration bonus)
    RUNTIME_ONLY_THRESHOLD = 0.4  # principled default (-0.1 dynamic-noise discount)
    HUMAN_REVIEWED_THRESHOLD = 0.9  # principled default (strong-consensus band)

    def __init__(self) -> None:
        """Initialize the confidence model."""
        self._scoring_log: list[dict[str, Any]] = []

    def compute(self, mapping: SemanticMapping) -> float:
        """Convenience alias for compute_confidence_score.

        Args:
            mapping: SemanticMapping to score.

        Returns:
            Confidence score between 0.0 and 1.0.
        """
        return self.compute_confidence_score(mapping)

    def compute_confidence_score(self, mapping: SemanticMapping) -> float:
        """Compute overall confidence score from evidence and metadata.

        Args:
            mapping: SemanticMapping to score.

        Returns:
            Confidence score between 0.0 and 1.0.
        """
        if not mapping.provenance:
            return 0.0

        # Base score: unweighted average of per-provenance confidences.
        avg_evidence = sum(p.confidence for p in mapping.provenance) / len(mapping.provenance)

        # Evidence diversity bonus — multiplicative weight 0.1 = "at
        # most a 10-percentage-point reward for multi-source
        # agreement". Principled default: large enough to lift a
        # borderline mapping across the STATIC_ONLY→STATIC_PLUS_RUNTIME
        # boundary (gap=0.15) when combined with dynamic evidence, small
        # enough never to override a strong evidence base on its own.
        # TODO(calibration): sweep {0.05, 0.10, 0.15, 0.20} on the 20+
        # repo fixture set (see CALIBRATION.md).
        diversity_bonus = mapping.evidence_diversity * 0.1

        # Parser certainty factor — multiplicative discount for noisy
        # parsers (e.g. tree-sitter fallback ≈ 0.8 vs. full Python AST
        # ≈ 0.95).
        certainty_factor = mapping.parser_certainty

        # Conflict penalties — 0.05-per-conflict principled default,
        # chosen so two detected conflicts (~0.10) roughly cancel a full
        # diversity bonus. TODO(calibration): log penalty distributions
        # on the 20-repo corpus and retune.
        conflict_penalty = sum(mapping.conflict_penalties) * 0.05

        # Compose: evidence base, lifted by diversity, discounted by
        # parser certainty, reduced by conflict penalties. Clamped to
        # [0, 1] for downstream tier assignment.
        confidence = (avg_evidence + diversity_bonus) * certainty_factor - conflict_penalty
        confidence = max(0.0, min(1.0, confidence))

        return confidence

    def determine_confidence_tier(
        self,
        mapping: SemanticMapping,
        score: float | None = None,
    ) -> ConfidenceTier:
        """Determine confidence tier based on evidence sources and score.

        Args:
            mapping: SemanticMapping to tier.
            score: Optional precomputed confidence score.

        Returns:
            ConfidenceTier for the mapping.
        """
        if score is None:
            score = self.compute_confidence_score(mapping)

        # Check evidence sources
        sources = [p.source for p in mapping.provenance]

        has_static = any("static" in s for s in sources)
        has_dynamic = any("dynamic" in s or "runtime" in s for s in sources)
        has_human = any("human" in s or "review" in s for s in sources)

        # Determine tier
        if has_human:
            return ConfidenceTier.HUMAN_REVIEWED

        if has_static and has_dynamic:
            if score >= self.STATIC_PLUS_RUNTIME_THRESHOLD:
                return ConfidenceTier.STATIC_PLUS_RUNTIME
            # Fallback to lower tier
            if score >= self.STATIC_ONLY_THRESHOLD:
                return ConfidenceTier.STATIC_ONLY

        if has_dynamic and not has_static:
            if score >= self.RUNTIME_ONLY_THRESHOLD:
                return ConfidenceTier.RUNTIME_ONLY

        if has_static:
            if score >= self.STATIC_ONLY_THRESHOLD:
                return ConfidenceTier.STATIC_ONLY

        # Default to lowest tier
        return ConfidenceTier.STATIC_ONLY

    def score_evidence_diversity(self, mapping: SemanticMapping) -> float:
        """Compute diversity score of evidence sources.

        Args:
            mapping: SemanticMapping with provenance.

        Returns:
            Diversity score between 0.0 and 1.0.
        """
        if not mapping.provenance:
            return 0.0

        # Count unique source types
        sources = [p.source for p in mapping.provenance]
        unique_sources = len(set(sources))

        # Normalize by number of total evidence pieces. Cap at 5
        # distinct source types because the evidence-source taxonomy
        # currently defines exactly 5 labels
        # (static_analysis, dynamic_trace, runtime_profile, human_review,
        # llm_review). A single mapping with 5 different labels already
        # saturates the diversity bonus. TODO(calibration): revisit if
        # new evidence sources are added in P5+.
        max_unique = min(len(sources), 5)  # Cap at 5 source types for normalization
        diversity = unique_sources / max(1, max_unique)

        return min(1.0, diversity)

    def detect_conflicts(self, mapping: SemanticMapping) -> list[float]:
        """Detect and score conflicts in evidence.

        Args:
            mapping: SemanticMapping to check.

        Returns:
            List of conflict penalty scores.
        """
        penalties: list[float] = []

        if not mapping.provenance or len(mapping.provenance) < 2:
            return penalties

        # Check for confidence divergence across evidence sources. A
        # spread > 0.3 is flagged as "significant divergence" and
        # incurs a 0.10 penalty. Both thresholds are principled
        # defaults: 0.3 is larger than any two neighbouring tier gaps
        # (max gap = 0.25 between RUNTIME_ONLY and STATIC_PLUS_RUNTIME)
        # so only genuinely disagreeing sources trigger it; 0.10 makes
        # one divergence cost the same as a full diversity bonus.
        # TODO(calibration): retune on observed evidence-spread
        # distributions from the 20-repo corpus (see CALIBRATION.md).
        confidence_values = [p.confidence for p in mapping.provenance]
        max_conf = max(confidence_values)
        min_conf = min(confidence_values)

        if (max_conf - min_conf) > 0.3:
            # Significant divergence
            penalties.append(0.1)

        # Check for conflicting source types
        sources = Counter(p.source for p in mapping.provenance)
        if len(sources) > 1:
            # Multiple source types - check for major conflicts
            static_count = sum(v for k, v in sources.items() if "static" in k)
            dynamic_count = sum(v for k, v in sources.items() if "dynamic" in k or "runtime" in k)

            if static_count > 0 and dynamic_count > 0:
                # Both static and dynamic - check for agreement
                static_conf = sum(p.confidence for p in mapping.provenance if "static" in p.source)
                dynamic_conf = sum(
                    p.confidence
                    for p in mapping.provenance
                    if "dynamic" in p.source or "runtime" in p.source
                )

                static_avg = static_conf / max(1, static_count)
                dynamic_avg = dynamic_conf / max(1, dynamic_count)

                # Static vs. dynamic disagreement threshold = 0.25.
                # Principled default: equals the gap between
                # RUNTIME_ONLY (0.4) and STATIC_PLUS_RUNTIME (0.65), so
                # disagreement only triggers when the two sources would
                # land in non-adjacent tiers. The 0.15 penalty is
                # intentionally larger than the 0.10 spread penalty
                # above because a static-vs-dynamic disagreement is
                # structurally more meaningful than a within-source
                # spread. TODO(calibration): validate on the 20-repo
                # corpus.
                if abs(static_avg - dynamic_avg) > 0.25:
                    penalties.append(0.15)

        return penalties

    def update_mapping_confidence(self, mapping: SemanticMapping) -> None:
        """Update all confidence fields of a mapping in-place.

        Args:
            mapping: SemanticMapping to update.
        """
        # Count evidence
        mapping.evidence_count = len(mapping.provenance)

        # Compute diversity
        mapping.evidence_diversity = self.score_evidence_diversity(mapping)

        # Detect conflicts
        mapping.conflict_penalties = self.detect_conflicts(mapping)

        # Compute overall score
        mapping.confidence_score = self.compute_confidence_score(mapping)

        # Determine tier
        mapping.confidence_tier = self.determine_confidence_tier(mapping, mapping.confidence_score)

        # Log
        self._scoring_log.append(
            {
                "mapping_id": mapping.id,
                "confidence_score": mapping.confidence_score,
                "confidence_tier": mapping.confidence_tier.value,
                "evidence_count": mapping.evidence_count,
            }
        )

    def score_batch(self, mappings: list[SemanticMapping]) -> None:
        """Update confidence for a batch of mappings.

        Args:
            mappings: List of mappings to score.
        """
        for mapping in mappings:
            self.update_mapping_confidence(mapping)

    def get_high_confidence_mappings(
        self,
        mappings: list[SemanticMapping],
        threshold: float = 0.7,
    ) -> list[SemanticMapping]:
        """Filter mappings by minimum confidence score.

        Args:
            mappings: List of mappings.
            threshold: Minimum confidence threshold. Default 0.7 is a
                principled "trust without review" bar — safely above
                ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65) but well below
                ``HUMAN_REVIEWED_THRESHOLD`` (0.9). TODO(calibration):
                tune against observed precision on the 20-repo corpus
                (see ``docs/evaluation/CALIBRATION.md``).

        Returns:
            Filtered list of high-confidence mappings.
        """
        return [m for m in mappings if m.confidence_score >= threshold]

    def get_low_confidence_mappings(
        self,
        mappings: list[SemanticMapping],
        threshold: float = 0.6,
    ) -> list[SemanticMapping]:
        """Find mappings below confidence threshold that may need review.

        Args:
            mappings: List of mappings.
            threshold: Maximum confidence threshold. Default 0.6 is a
                principled "needs reviewer attention" bar — halfway
                between ``STATIC_ONLY_THRESHOLD`` (0.5) and
                ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65), so that
                mappings which pass the accept floor but fail the
                "corroborated" bar are surfaced for human review.
                TODO(calibration): retune against observed human-review
                false-positive rates.

        Returns:
            Filtered list of low-confidence mappings.
        """
        return [m for m in mappings if m.confidence_score < threshold]

    def get_conflicted_mappings(
        self,
        mappings: list[SemanticMapping],
    ) -> list[SemanticMapping]:
        """Find mappings with detected conflicts.

        Args:
            mappings: List of mappings.

        Returns:
            List of mappings with conflict penalties.
        """
        return [m for m in mappings if m.conflict_penalties]

    def get_scoring_report(self) -> dict[str, Any]:
        """Generate a report of confidence scoring.

        Returns:
            Dictionary with scoring statistics.
        """
        if not self._scoring_log:
            return {"total_scored": 0}

        tiers = Counter(entry["confidence_tier"] for entry in self._scoring_log)
        scores = [entry["confidence_score"] for entry in self._scoring_log]
        evidence_counts = [entry["evidence_count"] for entry in self._scoring_log]

        return {
            "total_scored": len(self._scoring_log),
            "average_confidence": sum(scores) / len(scores) if scores else 0.0,
            "min_confidence": min(scores) if scores else 0.0,
            "max_confidence": max(scores) if scores else 0.0,
            "average_evidence_count": sum(evidence_counts) / len(evidence_counts)
            if evidence_counts
            else 0,
            "tier_distribution": dict(tiers),
        }

    def clear_log(self) -> None:
        """Clear the scoring log."""
        self._scoring_log.clear()

__init__()

Initialize the confidence model.

Source code in py/cogant/translate/confidence.py
263
264
265
def __init__(self) -> None:
    """Initialize the confidence model."""
    self._scoring_log: list[dict[str, Any]] = []

clear_log()

Clear the scoring log.

Source code in py/cogant/translate/confidence.py
583
584
585
def clear_log(self) -> None:
    """Clear the scoring log."""
    self._scoring_log.clear()

compute(mapping)

Convenience alias for compute_confidence_score.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to score.

required

Returns:

Type Description
float

Confidence score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
267
268
269
270
271
272
273
274
275
276
def compute(self, mapping: SemanticMapping) -> float:
    """Convenience alias for compute_confidence_score.

    Args:
        mapping: SemanticMapping to score.

    Returns:
        Confidence score between 0.0 and 1.0.
    """
    return self.compute_confidence_score(mapping)

compute_confidence_score(mapping)

Compute overall confidence score from evidence and metadata.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to score.

required

Returns:

Type Description
float

Confidence score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def compute_confidence_score(self, mapping: SemanticMapping) -> float:
    """Compute overall confidence score from evidence and metadata.

    Args:
        mapping: SemanticMapping to score.

    Returns:
        Confidence score between 0.0 and 1.0.
    """
    if not mapping.provenance:
        return 0.0

    # Base score: unweighted average of per-provenance confidences.
    avg_evidence = sum(p.confidence for p in mapping.provenance) / len(mapping.provenance)

    # Evidence diversity bonus — multiplicative weight 0.1 = "at
    # most a 10-percentage-point reward for multi-source
    # agreement". Principled default: large enough to lift a
    # borderline mapping across the STATIC_ONLY→STATIC_PLUS_RUNTIME
    # boundary (gap=0.15) when combined with dynamic evidence, small
    # enough never to override a strong evidence base on its own.
    # TODO(calibration): sweep {0.05, 0.10, 0.15, 0.20} on the 20+
    # repo fixture set (see CALIBRATION.md).
    diversity_bonus = mapping.evidence_diversity * 0.1

    # Parser certainty factor — multiplicative discount for noisy
    # parsers (e.g. tree-sitter fallback ≈ 0.8 vs. full Python AST
    # ≈ 0.95).
    certainty_factor = mapping.parser_certainty

    # Conflict penalties — 0.05-per-conflict principled default,
    # chosen so two detected conflicts (~0.10) roughly cancel a full
    # diversity bonus. TODO(calibration): log penalty distributions
    # on the 20-repo corpus and retune.
    conflict_penalty = sum(mapping.conflict_penalties) * 0.05

    # Compose: evidence base, lifted by diversity, discounted by
    # parser certainty, reduced by conflict penalties. Clamped to
    # [0, 1] for downstream tier assignment.
    confidence = (avg_evidence + diversity_bonus) * certainty_factor - conflict_penalty
    confidence = max(0.0, min(1.0, confidence))

    return confidence

detect_conflicts(mapping)

Detect and score conflicts in evidence.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to check.

required

Returns:

Type Description
list[float]

List of conflict penalty scores.

Source code in py/cogant/translate/confidence.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def detect_conflicts(self, mapping: SemanticMapping) -> list[float]:
    """Detect and score conflicts in evidence.

    Args:
        mapping: SemanticMapping to check.

    Returns:
        List of conflict penalty scores.
    """
    penalties: list[float] = []

    if not mapping.provenance or len(mapping.provenance) < 2:
        return penalties

    # Check for confidence divergence across evidence sources. A
    # spread > 0.3 is flagged as "significant divergence" and
    # incurs a 0.10 penalty. Both thresholds are principled
    # defaults: 0.3 is larger than any two neighbouring tier gaps
    # (max gap = 0.25 between RUNTIME_ONLY and STATIC_PLUS_RUNTIME)
    # so only genuinely disagreeing sources trigger it; 0.10 makes
    # one divergence cost the same as a full diversity bonus.
    # TODO(calibration): retune on observed evidence-spread
    # distributions from the 20-repo corpus (see CALIBRATION.md).
    confidence_values = [p.confidence for p in mapping.provenance]
    max_conf = max(confidence_values)
    min_conf = min(confidence_values)

    if (max_conf - min_conf) > 0.3:
        # Significant divergence
        penalties.append(0.1)

    # Check for conflicting source types
    sources = Counter(p.source for p in mapping.provenance)
    if len(sources) > 1:
        # Multiple source types - check for major conflicts
        static_count = sum(v for k, v in sources.items() if "static" in k)
        dynamic_count = sum(v for k, v in sources.items() if "dynamic" in k or "runtime" in k)

        if static_count > 0 and dynamic_count > 0:
            # Both static and dynamic - check for agreement
            static_conf = sum(p.confidence for p in mapping.provenance if "static" in p.source)
            dynamic_conf = sum(
                p.confidence
                for p in mapping.provenance
                if "dynamic" in p.source or "runtime" in p.source
            )

            static_avg = static_conf / max(1, static_count)
            dynamic_avg = dynamic_conf / max(1, dynamic_count)

            # Static vs. dynamic disagreement threshold = 0.25.
            # Principled default: equals the gap between
            # RUNTIME_ONLY (0.4) and STATIC_PLUS_RUNTIME (0.65), so
            # disagreement only triggers when the two sources would
            # land in non-adjacent tiers. The 0.15 penalty is
            # intentionally larger than the 0.10 spread penalty
            # above because a static-vs-dynamic disagreement is
            # structurally more meaningful than a within-source
            # spread. TODO(calibration): validate on the 20-repo
            # corpus.
            if abs(static_avg - dynamic_avg) > 0.25:
                penalties.append(0.15)

    return penalties

determine_confidence_tier(mapping, score=None)

Determine confidence tier based on evidence sources and score.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to tier.

required
score float | None

Optional precomputed confidence score.

None

Returns:

Type Description
ConfidenceTier

ConfidenceTier for the mapping.

Source code in py/cogant/translate/confidence.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def determine_confidence_tier(
    self,
    mapping: SemanticMapping,
    score: float | None = None,
) -> ConfidenceTier:
    """Determine confidence tier based on evidence sources and score.

    Args:
        mapping: SemanticMapping to tier.
        score: Optional precomputed confidence score.

    Returns:
        ConfidenceTier for the mapping.
    """
    if score is None:
        score = self.compute_confidence_score(mapping)

    # Check evidence sources
    sources = [p.source for p in mapping.provenance]

    has_static = any("static" in s for s in sources)
    has_dynamic = any("dynamic" in s or "runtime" in s for s in sources)
    has_human = any("human" in s or "review" in s for s in sources)

    # Determine tier
    if has_human:
        return ConfidenceTier.HUMAN_REVIEWED

    if has_static and has_dynamic:
        if score >= self.STATIC_PLUS_RUNTIME_THRESHOLD:
            return ConfidenceTier.STATIC_PLUS_RUNTIME
        # Fallback to lower tier
        if score >= self.STATIC_ONLY_THRESHOLD:
            return ConfidenceTier.STATIC_ONLY

    if has_dynamic and not has_static:
        if score >= self.RUNTIME_ONLY_THRESHOLD:
            return ConfidenceTier.RUNTIME_ONLY

    if has_static:
        if score >= self.STATIC_ONLY_THRESHOLD:
            return ConfidenceTier.STATIC_ONLY

    # Default to lowest tier
    return ConfidenceTier.STATIC_ONLY

get_conflicted_mappings(mappings)

Find mappings with detected conflicts.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings with conflict penalties.

Source code in py/cogant/translate/confidence.py
545
546
547
548
549
550
551
552
553
554
555
556
557
def get_conflicted_mappings(
    self,
    mappings: list[SemanticMapping],
) -> list[SemanticMapping]:
    """Find mappings with detected conflicts.

    Args:
        mappings: List of mappings.

    Returns:
        List of mappings with conflict penalties.
    """
    return [m for m in mappings if m.conflict_penalties]

get_high_confidence_mappings(mappings, threshold=0.7)

Filter mappings by minimum confidence score.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required
threshold float

Minimum confidence threshold. Default 0.7 is a principled "trust without review" bar — safely above STATIC_PLUS_RUNTIME_THRESHOLD (0.65) but well below HUMAN_REVIEWED_THRESHOLD (0.9). TODO(calibration): tune against observed precision on the 20-repo corpus (see docs/evaluation/CALIBRATION.md).

0.7

Returns:

Type Description
list[SemanticMapping]

Filtered list of high-confidence mappings.

Source code in py/cogant/translate/confidence.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def get_high_confidence_mappings(
    self,
    mappings: list[SemanticMapping],
    threshold: float = 0.7,
) -> list[SemanticMapping]:
    """Filter mappings by minimum confidence score.

    Args:
        mappings: List of mappings.
        threshold: Minimum confidence threshold. Default 0.7 is a
            principled "trust without review" bar — safely above
            ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65) but well below
            ``HUMAN_REVIEWED_THRESHOLD`` (0.9). TODO(calibration):
            tune against observed precision on the 20-repo corpus
            (see ``docs/evaluation/CALIBRATION.md``).

    Returns:
        Filtered list of high-confidence mappings.
    """
    return [m for m in mappings if m.confidence_score >= threshold]

get_low_confidence_mappings(mappings, threshold=0.6)

Find mappings below confidence threshold that may need review.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required
threshold float

Maximum confidence threshold. Default 0.6 is a principled "needs reviewer attention" bar — halfway between STATIC_ONLY_THRESHOLD (0.5) and STATIC_PLUS_RUNTIME_THRESHOLD (0.65), so that mappings which pass the accept floor but fail the "corroborated" bar are surfaced for human review. TODO(calibration): retune against observed human-review false-positive rates.

0.6

Returns:

Type Description
list[SemanticMapping]

Filtered list of low-confidence mappings.

Source code in py/cogant/translate/confidence.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def get_low_confidence_mappings(
    self,
    mappings: list[SemanticMapping],
    threshold: float = 0.6,
) -> list[SemanticMapping]:
    """Find mappings below confidence threshold that may need review.

    Args:
        mappings: List of mappings.
        threshold: Maximum confidence threshold. Default 0.6 is a
            principled "needs reviewer attention" bar — halfway
            between ``STATIC_ONLY_THRESHOLD`` (0.5) and
            ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65), so that
            mappings which pass the accept floor but fail the
            "corroborated" bar are surfaced for human review.
            TODO(calibration): retune against observed human-review
            false-positive rates.

    Returns:
        Filtered list of low-confidence mappings.
    """
    return [m for m in mappings if m.confidence_score < threshold]

get_scoring_report()

Generate a report of confidence scoring.

Returns:

Type Description
dict[str, Any]

Dictionary with scoring statistics.

Source code in py/cogant/translate/confidence.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def get_scoring_report(self) -> dict[str, Any]:
    """Generate a report of confidence scoring.

    Returns:
        Dictionary with scoring statistics.
    """
    if not self._scoring_log:
        return {"total_scored": 0}

    tiers = Counter(entry["confidence_tier"] for entry in self._scoring_log)
    scores = [entry["confidence_score"] for entry in self._scoring_log]
    evidence_counts = [entry["evidence_count"] for entry in self._scoring_log]

    return {
        "total_scored": len(self._scoring_log),
        "average_confidence": sum(scores) / len(scores) if scores else 0.0,
        "min_confidence": min(scores) if scores else 0.0,
        "max_confidence": max(scores) if scores else 0.0,
        "average_evidence_count": sum(evidence_counts) / len(evidence_counts)
        if evidence_counts
        else 0,
        "tier_distribution": dict(tiers),
    }

score_batch(mappings)

Update confidence for a batch of mappings.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings to score.

required
Source code in py/cogant/translate/confidence.py
492
493
494
495
496
497
498
499
def score_batch(self, mappings: list[SemanticMapping]) -> None:
    """Update confidence for a batch of mappings.

    Args:
        mappings: List of mappings to score.
    """
    for mapping in mappings:
        self.update_mapping_confidence(mapping)

score_evidence_diversity(mapping)

Compute diversity score of evidence sources.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping with provenance.

required

Returns:

Type Description
float

Diversity score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def score_evidence_diversity(self, mapping: SemanticMapping) -> float:
    """Compute diversity score of evidence sources.

    Args:
        mapping: SemanticMapping with provenance.

    Returns:
        Diversity score between 0.0 and 1.0.
    """
    if not mapping.provenance:
        return 0.0

    # Count unique source types
    sources = [p.source for p in mapping.provenance]
    unique_sources = len(set(sources))

    # Normalize by number of total evidence pieces. Cap at 5
    # distinct source types because the evidence-source taxonomy
    # currently defines exactly 5 labels
    # (static_analysis, dynamic_trace, runtime_profile, human_review,
    # llm_review). A single mapping with 5 different labels already
    # saturates the diversity bonus. TODO(calibration): revisit if
    # new evidence sources are added in P5+.
    max_unique = min(len(sources), 5)  # Cap at 5 source types for normalization
    diversity = unique_sources / max(1, max_unique)

    return min(1.0, diversity)

update_mapping_confidence(mapping)

Update all confidence fields of a mapping in-place.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to update.

required
Source code in py/cogant/translate/confidence.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def update_mapping_confidence(self, mapping: SemanticMapping) -> None:
    """Update all confidence fields of a mapping in-place.

    Args:
        mapping: SemanticMapping to update.
    """
    # Count evidence
    mapping.evidence_count = len(mapping.provenance)

    # Compute diversity
    mapping.evidence_diversity = self.score_evidence_diversity(mapping)

    # Detect conflicts
    mapping.conflict_penalties = self.detect_conflicts(mapping)

    # Compute overall score
    mapping.confidence_score = self.compute_confidence_score(mapping)

    # Determine tier
    mapping.confidence_tier = self.determine_confidence_tier(mapping, mapping.confidence_score)

    # Log
    self._scoring_log.append(
        {
            "mapping_id": mapping.id,
            "confidence_score": mapping.confidence_score,
            "confidence_tier": mapping.confidence_tier.value,
            "evidence_count": mapping.evidence_count,
        }
    )

ConfigRule

Bases: TranslationRule

Maps configuration files and structures to context priors.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.90). Top band (0.90) — the highest confidence score in the entire translation rule family. Rationale: ConfigRule fires only when the upstream parser has already classified a node as NodeKind.CONFIGURATION (yaml/toml/ini/json config files, module-level CONFIG = {...} dicts, Settings subclasses). That classification is itself strongly evidenced, so the confidence stacks: parser_certainty 0.95 (highest) plus confidence 0.90 makes this rule effectively unbeatable by heuristic rules, which is correct — explicit config is ground truth for context. TODO(calibration): confirm that NodeKind.CONFIGURATION extraction has <5% false-positive rate on the 20-repo corpus.

Source code in py/cogant/translate/rules/control.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class ConfigRule(TranslationRule):
    """Maps configuration files and structures to context priors.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.90)``. **Top band** (0.90) —
        the highest confidence score in the entire translation rule
        family. Rationale: ``ConfigRule`` fires only when the
        upstream parser has already classified a node as
        ``NodeKind.CONFIGURATION`` (yaml/toml/ini/json config files,
        module-level ``CONFIG = {...}`` dicts, ``Settings`` subclasses).
        That classification is itself strongly evidenced, so the
        confidence stacks: parser_certainty 0.95 (highest) plus
        confidence 0.90 makes this rule effectively unbeatable by
        heuristic rules, which is correct — explicit config is
        ground truth for context. TODO(calibration): confirm that
        ``NodeKind.CONFIGURATION`` extraction has <5% false-positive
        rate on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find configuration nodes.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched configuration nodes.
        """
        matches = []

        # Find configuration nodes
        configs = graph.get_nodes_by_kind(NodeKind.CONFIGURATION)

        for config in configs:
            matches.append(
                {
                    "node_id": config.id,
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping for configuration.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'config').hexdigest()[:8]}"

        # Confidence 0.90 — principled default (top band, highest in
        # entire rule family). The upstream parser has already
        # classified this node as CONFIGURATION, which is a strongly-
        # evidenced classification in its own right. Parser certainty
        # 0.95 is the highest in the family.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Context Prior",
            description=f"Configuration '{node.name}' provides system context",
            confidence_score=0.9,  # principled default (top band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.9,
                )
            ],
            evidence_count=1,
            parser_certainty=0.95,  # highest in family (explicit config)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "config"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping for configuration.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/control.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping for configuration.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'config').hexdigest()[:8]}"

    # Confidence 0.90 — principled default (top band, highest in
    # entire rule family). The upstream parser has already
    # classified this node as CONFIGURATION, which is a strongly-
    # evidenced classification in its own right. Parser certainty
    # 0.95 is the highest in the family.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Context Prior",
        description=f"Configuration '{node.name}' provides system context",
        confidence_score=0.9,  # principled default (top band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.9,
            )
        ],
        evidence_count=1,
        parser_certainty=0.95,  # highest in family (explicit config)
    )

matches(graph, query)

Find configuration nodes.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched configuration nodes.

Source code in py/cogant/translate/rules/control.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find configuration nodes.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched configuration nodes.
    """
    matches = []

    # Find configuration nodes
    configs = graph.get_nodes_by_kind(NodeKind.CONFIGURATION)

    for config in configs:
        matches.append(
            {
                "node_id": config.id,
            }
        )

    return matches

ContainmentRule

Bases: TranslationRule

Analyzes methods within classes to extract observation vs action vs policy roles.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75). Stronger than pure-structural InheritanceRule (0.70) because it aggregates lexical evidence across 5+ methods (majority-vote classification), but weaker than per-function ObservationRule/ActionRule keyword hits (0.80+) because the class-level aggregate can mask mixed-role classes. Method-count threshold = 5 (see matches). TODO(calibration): sweep {3, 5, 8} method thresholds and the max(actions, observations) tie-breaking rule.

Source code in py/cogant/translate/rules/structural.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class ContainmentRule(TranslationRule):
    """Analyzes methods within classes to extract observation vs action vs policy roles.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75).
        Stronger than pure-structural ``InheritanceRule`` (0.70)
        because it aggregates *lexical* evidence across 5+ methods
        (majority-vote classification), but weaker than per-function
        ``ObservationRule``/``ActionRule`` keyword hits (0.80+)
        because the class-level aggregate can mask mixed-role classes.
        Method-count threshold = 5 (see ``matches``). TODO(calibration):
        sweep {3, 5, 8} method thresholds and the
        ``max(actions, observations)`` tie-breaking rule.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes with multiple methods for detailed analysis.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched containment patterns.
        """
        matches = []

        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            # Find CONTAINS edges to methods
            out_edges = graph.get_edges_from(cls.id)
            method_edges = [e for e in out_edges if e.kind == EdgeKind.CONTAINS]
            method_ids = [e.target_id for e in method_edges]

            # Method-count threshold = 5. Principled default: below
            # 5 methods a class is too small for a majority-vote
            # classification to be stable (a single method's lexical
            # signal dominates), and the per-function ObservationRule/
            # ActionRule will already fire on each method anyway. The
            # choice of 5 (rather than 3 or 10) is guided by the
            # "5 ± 2 chunking limit" (Miller 1956) as a convenient
            # small-class/large-class boundary. TODO(calibration):
            # sweep {3, 5, 8} on the 20-repo corpus.
            if len(method_ids) >= 5:
                matches.append(
                    {
                        "node_id": cls.id,
                        "method_ids": method_ids,
                        "method_count": len(method_ids),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create containment analysis mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping summarizing method roles.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        method_ids = match.get("method_ids", [])

        # Analyze method roles
        observation_methods = []
        action_methods = []
        policy_methods = []

        # Keyword lists are maintained centrally in cogant.translate.rules.keywords
        observation_keywords = OBSERVATION_KEYWORDS
        action_keywords = ACTION_KEYWORDS
        policy_keywords = POLICY_KEYWORDS

        for method_id in method_ids:
            method = graph.get_node(method_id)
            if not method:
                continue

            name_lower = method.name.lower()

            # Classify by keyword
            if any(kw in name_lower for kw in observation_keywords):
                observation_methods.append(method_id)
            elif any(kw in name_lower for kw in action_keywords):
                action_methods.append(method_id)
            elif any(kw in name_lower for kw in policy_keywords):
                policy_methods.append(method_id)

        # Infer primary role from method distribution
        primary_role = MappingKind.HIDDEN_STATE
        if len(action_methods) > len(observation_methods):
            primary_role = MappingKind.ACTION
        elif len(observation_methods) > len(action_methods):
            primary_role = MappingKind.OBSERVATION
        elif len(policy_methods) > 0:
            primary_role = MappingKind.POLICY

        mapping_id = f"cont_{node_id}_{hashlib.sha256(b'containment').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Aggregated
        # lexical evidence over 5+ methods is stronger than a pure
        # structural hint (0.70) but weaker than per-function lexical
        # hits (0.80+) because class-level majority voting can mask
        # mixed-role classes. Parser certainty 0.80 = tree-sitter
        # Python-fallback band.
        return SemanticMapping(
            id=mapping_id,
            kind=primary_role,
            graph_fragment_node_ids=[node_id] + method_ids,
            semantic_label=f"{node.name} - Containment Analysis",
            description=f"Class '{node.name}' contains {len(observation_methods)} observations, {len(action_methods)} actions, {len(policy_methods)} policies → primary role: {primary_role.value}",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={
                        "observation_methods": len(observation_methods),
                        "action_methods": len(action_methods),
                        "policy_methods": len(policy_methods),
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "containment"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.HIDDEN_STATE

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create containment analysis mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping summarizing method roles.

Source code in py/cogant/translate/rules/structural.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create containment analysis mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping summarizing method roles.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    method_ids = match.get("method_ids", [])

    # Analyze method roles
    observation_methods = []
    action_methods = []
    policy_methods = []

    # Keyword lists are maintained centrally in cogant.translate.rules.keywords
    observation_keywords = OBSERVATION_KEYWORDS
    action_keywords = ACTION_KEYWORDS
    policy_keywords = POLICY_KEYWORDS

    for method_id in method_ids:
        method = graph.get_node(method_id)
        if not method:
            continue

        name_lower = method.name.lower()

        # Classify by keyword
        if any(kw in name_lower for kw in observation_keywords):
            observation_methods.append(method_id)
        elif any(kw in name_lower for kw in action_keywords):
            action_methods.append(method_id)
        elif any(kw in name_lower for kw in policy_keywords):
            policy_methods.append(method_id)

    # Infer primary role from method distribution
    primary_role = MappingKind.HIDDEN_STATE
    if len(action_methods) > len(observation_methods):
        primary_role = MappingKind.ACTION
    elif len(observation_methods) > len(action_methods):
        primary_role = MappingKind.OBSERVATION
    elif len(policy_methods) > 0:
        primary_role = MappingKind.POLICY

    mapping_id = f"cont_{node_id}_{hashlib.sha256(b'containment').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Aggregated
    # lexical evidence over 5+ methods is stronger than a pure
    # structural hint (0.70) but weaker than per-function lexical
    # hits (0.80+) because class-level majority voting can mask
    # mixed-role classes. Parser certainty 0.80 = tree-sitter
    # Python-fallback band.
    return SemanticMapping(
        id=mapping_id,
        kind=primary_role,
        graph_fragment_node_ids=[node_id] + method_ids,
        semantic_label=f"{node.name} - Containment Analysis",
        description=f"Class '{node.name}' contains {len(observation_methods)} observations, {len(action_methods)} actions, {len(policy_methods)} policies → primary role: {primary_role.value}",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={
                    "observation_methods": len(observation_methods),
                    "action_methods": len(action_methods),
                    "policy_methods": len(policy_methods),
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find classes with multiple methods for detailed analysis.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched containment patterns.

Source code in py/cogant/translate/rules/structural.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes with multiple methods for detailed analysis.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched containment patterns.
    """
    matches = []

    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        # Find CONTAINS edges to methods
        out_edges = graph.get_edges_from(cls.id)
        method_edges = [e for e in out_edges if e.kind == EdgeKind.CONTAINS]
        method_ids = [e.target_id for e in method_edges]

        # Method-count threshold = 5. Principled default: below
        # 5 methods a class is too small for a majority-vote
        # classification to be stable (a single method's lexical
        # signal dominates), and the per-function ObservationRule/
        # ActionRule will already fire on each method anyway. The
        # choice of 5 (rather than 3 or 10) is guided by the
        # "5 ± 2 chunking limit" (Miller 1956) as a convenient
        # small-class/large-class boundary. TODO(calibration):
        # sweep {3, 5, 8} on the 20-repo corpus.
        if len(method_ids) >= 5:
            matches.append(
                {
                    "node_id": cls.id,
                    "method_ids": method_ids,
                    "method_count": len(method_ids),
                }
            )

    return matches

ContextRule

Bases: TranslationRule

Maps configuration and parameter classes to context modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule. Rationale: context keywords config/settings/env/options/params are specific but less strong than a validate/test_ prefix (which get 0.85); they correlate well with configuration roles but also occasionally appear in orchestrators. Note: the dedicated ConfigRule (control.py, confidence 0.90) supersedes this rule when config is in the name — this rule provides the broader settings/params/env fallback.

Source code in py/cogant/translate/rules/semantic.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
class ContextRule(TranslationRule):
    """Maps configuration and parameter classes to context modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``. Rationale: context
        keywords ``config``/``settings``/``env``/``options``/``params``
        are specific but less strong than a ``validate``/``test_``
        prefix (which get 0.85); they correlate well with
        configuration roles but also occasionally appear in
        orchestrators. Note: the dedicated ``ConfigRule`` (control.py,
        confidence 0.90) supersedes this rule when ``config`` is in
        the name — this rule provides the broader
        ``settings``/``params``/``env`` fallback.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find context/configuration classes and functions.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched context nodes.
        """
        matches = []
        context_keywords = [
            "config",
            "settings",
            "env",
            "options",
            "params",
            "env_",
            "world_",
            "state_",
            "context_",
        ]

        # Find classes and functions with context keywords
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            if _matches_keyword(cls.name, context_keywords):
                matches.append(
                    {
                        "node_id": cls.id,
                        "context_type": "class",
                    }
                )

        # Find functions that only read and return values (read-only + returns)
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        for func in functions:
            out_edges = graph.get_edges_from(func.id)
            reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
            returns = sum(1 for e in out_edges if e.kind == EdgeKind.RETURNS)

            # Context function: reads config/state and returns it,
            # OR has context keyword in name
            has_context_keyword = _matches_keyword(func.name, context_keywords)
            if has_context_keyword or (reads > 0 and writes == 0 and returns > 0):
                matches.append(
                    {
                        "node_id": func.id,
                        "context_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'context').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # Parser certainty 0.85 = AST-native band. ``ConfigRule`` in
        # control.py supersedes this rule (confidence 0.90) on exact
        # ``config`` hits.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Context",
            description=f"{'Class' if match['context_type'] == 'class' else 'Function'} '{node.name}' provides system context",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "context"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

    def to_gnn_role(self) -> str:
        """Return the GNN role string for context mappings.

        Returns:
            GNN role identifier.
        """
        return "CONTEXT"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/semantic.py
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'context').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # Parser certainty 0.85 = AST-native band. ``ConfigRule`` in
    # control.py supersedes this rule (confidence 0.90) on exact
    # ``config`` hits.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Context",
        description=f"{'Class' if match['context_type'] == 'class' else 'Function'} '{node.name}' provides system context",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

matches(graph, query)

Find context/configuration classes and functions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched context nodes.

Source code in py/cogant/translate/rules/semantic.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find context/configuration classes and functions.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched context nodes.
    """
    matches = []
    context_keywords = [
        "config",
        "settings",
        "env",
        "options",
        "params",
        "env_",
        "world_",
        "state_",
        "context_",
    ]

    # Find classes and functions with context keywords
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        if _matches_keyword(cls.name, context_keywords):
            matches.append(
                {
                    "node_id": cls.id,
                    "context_type": "class",
                }
            )

    # Find functions that only read and return values (read-only + returns)
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    for func in functions:
        out_edges = graph.get_edges_from(func.id)
        reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
        returns = sum(1 for e in out_edges if e.kind == EdgeKind.RETURNS)

        # Context function: reads config/state and returns it,
        # OR has context keyword in name
        has_context_keyword = _matches_keyword(func.name, context_keywords)
        if has_context_keyword or (reads > 0 and writes == 0 and returns > 0):
            matches.append(
                {
                    "node_id": func.id,
                    "context_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for context mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
971
972
973
974
975
976
977
def to_gnn_role(self) -> str:
    """Return the GNN role string for context mappings.

    Returns:
        GNN role identifier.
    """
    return "CONTEXT"

DataPipelineRule

Bases: TranslationRule

Maps data transformation chains to data-flow modality.

Detects functions that read from one source, transform, and write to another. Pattern: node with both READS and WRITES edges where read sources differ from write targets.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75). The "reads-from-A, writes-to-B (A≠B)" pattern is a strong structural cue for data flow, but we keep it at 0.75 rather than 0.80+ because edge-level precision is lower than name-level precision (tree-sitter occasionally over-reports READS on attribute-chain accesses). TODO(calibration): measure false-positive rate on the 20-repo corpus; if <5%, promote to 0.80.

Source code in py/cogant/translate/rules/structural.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
class DataPipelineRule(TranslationRule):
    """Maps data transformation chains to data-flow modality.

    Detects functions that read from one source, transform, and write to another.
    Pattern: node with both READS and WRITES edges where read sources differ
    from write targets.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75). The
        "reads-from-A, writes-to-B (A≠B)" pattern is a strong
        structural cue for data flow, but we keep it at 0.75 rather
        than 0.80+ because edge-level precision is lower than
        name-level precision (tree-sitter occasionally over-reports
        ``READS`` on attribute-chain accesses). TODO(calibration):
        measure false-positive rate on the 20-repo corpus; if <5%,
        promote to 0.80.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions with both read and write edges to different targets.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched data pipeline nodes.
        """
        matches = []

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            out_edges = graph.get_edges_from(node.id)

            read_edges = [e for e in out_edges if e.kind == EdgeKind.READS]
            write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]

            # Must have both reads and writes
            if not read_edges or not write_edges:
                continue

            read_targets = {e.target_id for e in read_edges}
            write_targets = {e.target_id for e in write_edges}

            # Read sources must differ from write targets (transformation, not echo)
            if read_targets != write_targets:
                matches.append(
                    {
                        "node_id": node.id,
                        "read_targets": list(read_targets),
                        "write_targets": list(write_targets),
                        "read_count": len(read_edges),
                        "write_count": len(write_edges),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create data-flow mapping for data pipeline node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for data flow.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        fragment_node_ids = (
            [node_id] + match.get("read_targets", []) + match.get("write_targets", [])
        )

        mapping_id = f"dpipe_{node_id}_{hashlib.sha256(b'data_pipeline').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Read-from-A
        # / write-to-B (A≠B) is a strong structural cue, but edge-level
        # precision is lower than name-level (tree-sitter sometimes
        # over-reports READS on attribute chains).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.DATA_FLOW,
            graph_fragment_node_ids=fragment_node_ids,
            semantic_label=f"{node.name} - Data Pipeline",
            description=f"Function '{node.name}' transforms data (reads from {match['read_count']} source(s), writes to {match['write_count']} target(s))",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={
                        "read_count": match["read_count"],
                        "write_count": match["write_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "data_pipeline"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.DATA_FLOW

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create data-flow mapping for data pipeline node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for data flow.

Source code in py/cogant/translate/rules/structural.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create data-flow mapping for data pipeline node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for data flow.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    fragment_node_ids = (
        [node_id] + match.get("read_targets", []) + match.get("write_targets", [])
    )

    mapping_id = f"dpipe_{node_id}_{hashlib.sha256(b'data_pipeline').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Read-from-A
    # / write-to-B (A≠B) is a strong structural cue, but edge-level
    # precision is lower than name-level (tree-sitter sometimes
    # over-reports READS on attribute chains).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.DATA_FLOW,
        graph_fragment_node_ids=fragment_node_ids,
        semantic_label=f"{node.name} - Data Pipeline",
        description=f"Function '{node.name}' transforms data (reads from {match['read_count']} source(s), writes to {match['write_count']} target(s))",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={
                    "read_count": match["read_count"],
                    "write_count": match["write_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find functions with both read and write edges to different targets.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched data pipeline nodes.

Source code in py/cogant/translate/rules/structural.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions with both read and write edges to different targets.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched data pipeline nodes.
    """
    matches = []

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        out_edges = graph.get_edges_from(node.id)

        read_edges = [e for e in out_edges if e.kind == EdgeKind.READS]
        write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]

        # Must have both reads and writes
        if not read_edges or not write_edges:
            continue

        read_targets = {e.target_id for e in read_edges}
        write_targets = {e.target_id for e in write_edges}

        # Read sources must differ from write targets (transformation, not echo)
        if read_targets != write_targets:
            matches.append(
                {
                    "node_id": node.id,
                    "read_targets": list(read_targets),
                    "write_targets": list(write_targets),
                    "read_count": len(read_edges),
                    "write_count": len(write_edges),
                }
            )

    return matches

ErrorBoundaryRule

Bases: TranslationRule

Maps error handling boundaries to error-handling modality.

Detects functions/methods with CATCHES or THROWS edges, representing error boundaries in the system.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.70). Bottom band (0.70). Rationale: CATCHES/THROWS edges are directly extracted from try/except / raise Python constructs (high structural precision) but the semantic meaning — "this is an error boundary worth modeling" — is weak because most non-trivial functions have at least one try/except for cleanup. Parser certainty 0.75 (below the 0.80 norm) reflects the fact that tree-sitter does not resolve exception-type hierarchies.

Source code in py/cogant/translate/rules/resilience.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
class ErrorBoundaryRule(TranslationRule):
    """Maps error handling boundaries to error-handling modality.

    Detects functions/methods with CATCHES or THROWS edges, representing
    error boundaries in the system.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.70)``. **Bottom band** (0.70).
        Rationale: CATCHES/THROWS edges are directly extracted from
        ``try/except`` / ``raise`` Python constructs (high structural
        precision) but the *semantic* meaning — "this is an error
        boundary worth modeling" — is weak because most non-trivial
        functions have at least one try/except for cleanup. Parser
        certainty 0.75 (below the 0.80 norm) reflects the fact that
        tree-sitter does not resolve exception-type hierarchies.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with CATCHES or THROWS edges.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched error boundary nodes.
        """
        matches = []

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            out_edges = graph.get_edges_from(node.id)

            catches_edges = [e for e in out_edges if e.kind == EdgeKind.CATCHES]
            throws_edges = [e for e in out_edges if e.kind == EdgeKind.THROWS]

            if not catches_edges and not throws_edges:
                continue

            # Caught exception node IDs form the graph fragment
            caught_node_ids = [e.target_id for e in catches_edges]
            thrown_node_ids = [e.target_id for e in throws_edges]

            matches.append(
                {
                    "node_id": node.id,
                    "caught_node_ids": caught_node_ids,
                    "thrown_node_ids": thrown_node_ids,
                    "catches_count": len(catches_edges),
                    "throws_count": len(throws_edges),
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create error-handling mapping for error boundary node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for error handling.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        fragment_node_ids = (
            [node_id] + match.get("caught_node_ids", []) + match.get("thrown_node_ids", [])
        )

        mapping_id = f"errbnd_{node_id}_{hashlib.sha256(b'error_boundary').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # CATCHES/THROWS edges are structurally precise but
        # semantically overloaded: most non-trivial functions have
        # some error handling. Parser certainty 0.75 reflects the
        # lack of exception-hierarchy resolution in tree-sitter.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ERROR_HANDLING,
            graph_fragment_node_ids=fragment_node_ids,
            semantic_label=f"{node.name} - Error Boundary",
            description=f"Function '{node.name}' handles errors (catches {match['catches_count']}, throws {match['throws_count']})",
            confidence_score=0.70,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.70,
                    metadata={
                        "catches_count": match["catches_count"],
                        "throws_count": match["throws_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.75,  # no exception-hierarchy resolution
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "error_boundary"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ERROR_HANDLING

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create error-handling mapping for error boundary node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for error handling.

Source code in py/cogant/translate/rules/resilience.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create error-handling mapping for error boundary node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for error handling.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    fragment_node_ids = (
        [node_id] + match.get("caught_node_ids", []) + match.get("thrown_node_ids", [])
    )

    mapping_id = f"errbnd_{node_id}_{hashlib.sha256(b'error_boundary').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # CATCHES/THROWS edges are structurally precise but
    # semantically overloaded: most non-trivial functions have
    # some error handling. Parser certainty 0.75 reflects the
    # lack of exception-hierarchy resolution in tree-sitter.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ERROR_HANDLING,
        graph_fragment_node_ids=fragment_node_ids,
        semantic_label=f"{node.name} - Error Boundary",
        description=f"Function '{node.name}' handles errors (catches {match['catches_count']}, throws {match['throws_count']})",
        confidence_score=0.70,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.70,
                metadata={
                    "catches_count": match["catches_count"],
                    "throws_count": match["throws_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.75,  # no exception-hierarchy resolution
    )

matches(graph, query)

Find nodes with CATCHES or THROWS edges.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched error boundary nodes.

Source code in py/cogant/translate/rules/resilience.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with CATCHES or THROWS edges.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched error boundary nodes.
    """
    matches = []

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        out_edges = graph.get_edges_from(node.id)

        catches_edges = [e for e in out_edges if e.kind == EdgeKind.CATCHES]
        throws_edges = [e for e in out_edges if e.kind == EdgeKind.THROWS]

        if not catches_edges and not throws_edges:
            continue

        # Caught exception node IDs form the graph fragment
        caught_node_ids = [e.target_id for e in catches_edges]
        thrown_node_ids = [e.target_id for e in throws_edges]

        matches.append(
            {
                "node_id": node.id,
                "caught_node_ids": caught_node_ids,
                "thrown_node_ids": thrown_node_ids,
                "catches_count": len(catches_edges),
                "throws_count": len(throws_edges),
            }
        )

    return matches

EventBusRule

Bases: TranslationRule

Maps event/subscription systems to observation-action coupling.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75), tied with MutatingSubsystemRule/ContainmentRule/ DataPipelineRule. Rationale: event-bus detection depends on the upstream parser recognizing EVENT node kinds, which is only done for patterns the tree-sitter queries understand (decorator-driven pub/sub). Confidence tier is set to STATIC_PLUS_RUNTIME (not STATIC_ONLY) as a hint that dynamic trace corroboration is especially valuable for event-driven code. TODO(calibration): measure EVENT-node coverage across the 20-repo corpus.

Source code in py/cogant/translate/rules/behavioral.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
class EventBusRule(TranslationRule):
    """Maps event/subscription systems to observation-action coupling.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75),
        tied with ``MutatingSubsystemRule``/``ContainmentRule``/
        ``DataPipelineRule``. Rationale: event-bus detection depends
        on the upstream parser recognizing ``EVENT`` node kinds,
        which is only done for patterns the tree-sitter queries
        understand (decorator-driven pub/sub). Confidence tier is
        set to STATIC_PLUS_RUNTIME (not STATIC_ONLY) as a hint that
        dynamic trace corroboration is especially valuable for
        event-driven code. TODO(calibration): measure EVENT-node
        coverage across the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find event bus and subscription patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched event bus patterns.
        """
        matches = []

        # Look for event nodes and their subscriptions
        events = graph.get_nodes_by_kind(NodeKind.EVENT)

        for event in events:
            # Find subscribing nodes
            incoming = graph.get_edges_to(event.id)
            outgoing = graph.get_edges_from(event.id)

            if incoming or outgoing:
                matches.append(
                    {
                        "node_id": event.id,
                        "subscriber_count": len(
                            [e for e in outgoing if e.kind == EdgeKind.TRIGGERS]
                        ),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation-action coupling mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for event bus.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"event_{node_id}_{hashlib.sha256(b'event_bus').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Event-bus
        # detection depends on upstream EVENT-kind nodes, which are
        # only emitted for patterns the tree-sitter queries
        # understand. Tier set to STATIC_PLUS_RUNTIME as a hint that
        # dynamic trace corroboration is particularly valuable for
        # event-driven code paths.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Event Bus",
            description=f"Event '{node.name}' couples observations to actions",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_PLUS_RUNTIME,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "event_bus"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation-action coupling mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for event bus.

Source code in py/cogant/translate/rules/behavioral.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation-action coupling mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for event bus.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"event_{node_id}_{hashlib.sha256(b'event_bus').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Event-bus
    # detection depends on upstream EVENT-kind nodes, which are
    # only emitted for patterns the tree-sitter queries
    # understand. Tier set to STATIC_PLUS_RUNTIME as a hint that
    # dynamic trace corroboration is particularly valuable for
    # event-driven code paths.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Event Bus",
        description=f"Event '{node.name}' couples observations to actions",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_PLUS_RUNTIME,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find event bus and subscription patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched event bus patterns.

Source code in py/cogant/translate/rules/behavioral.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find event bus and subscription patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched event bus patterns.
    """
    matches = []

    # Look for event nodes and their subscriptions
    events = graph.get_nodes_by_kind(NodeKind.EVENT)

    for event in events:
        # Find subscribing nodes
        incoming = graph.get_edges_to(event.id)
        outgoing = graph.get_edges_from(event.id)

        if incoming or outgoing:
            matches.append(
                {
                    "node_id": event.id,
                    "subscriber_count": len(
                        [e for e in outgoing if e.kind == EdgeKind.TRIGGERS]
                    ),
                }
            )

    return matches

FeatureFlagRule

Bases: TranslationRule

Maps feature flags to latent context selectors.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with PreferenceRule/TestAssertionRule and the keyword branch of ObservationRule. Rationale: feature flags are specific but slightly less unambiguous than raw configuration (which gets 0.90); some "feature flag" patterns are actually dynamic toggles rather than static context selectors. The rule relies on upstream NodeKind.FEATURE_FLAG classification.

Source code in py/cogant/translate/rules/control.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
class FeatureFlagRule(TranslationRule):
    """Maps feature flags to latent context selectors.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85),
        tied with ``PreferenceRule``/``TestAssertionRule`` and the
        keyword branch of ``ObservationRule``. Rationale: feature
        flags are specific but slightly less unambiguous than raw
        configuration (which gets 0.90); some "feature flag"
        patterns are actually dynamic toggles rather than static
        context selectors. The rule relies on upstream
        ``NodeKind.FEATURE_FLAG`` classification.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find feature flag nodes.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched feature flag nodes.
        """
        matches = []

        # Find feature flag nodes
        flags = graph.get_nodes_by_kind(NodeKind.FEATURE_FLAG)

        for flag in flags:
            matches.append(
                {
                    "node_id": flag.id,
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context selector mapping for feature flag.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for feature flag.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"fflag_{node_id}_{hashlib.sha256(b'feature_flag').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). Relies on
        # upstream NodeKind.FEATURE_FLAG classification which is
        # slightly less precise than explicit CONFIGURATION.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Feature Flag",
            description=f"Feature flag '{node.name}' selects system context",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # high AST precision on flag nodes
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "feature_flag"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context selector mapping for feature flag.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for feature flag.

Source code in py/cogant/translate/rules/control.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context selector mapping for feature flag.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for feature flag.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"fflag_{node_id}_{hashlib.sha256(b'feature_flag').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). Relies on
    # upstream NodeKind.FEATURE_FLAG classification which is
    # slightly less precise than explicit CONFIGURATION.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Feature Flag",
        description=f"Feature flag '{node.name}' selects system context",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # high AST precision on flag nodes
    )

matches(graph, query)

Find feature flag nodes.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched feature flag nodes.

Source code in py/cogant/translate/rules/control.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find feature flag nodes.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched feature flag nodes.
    """
    matches = []

    # Find feature flag nodes
    flags = graph.get_nodes_by_kind(NodeKind.FEATURE_FLAG)

    for flag in flags:
        matches.append(
            {
                "node_id": flag.id,
            }
        )

    return matches

InheritanceRule

Bases: TranslationRule

Maps class inheritance to inform semantic roles via base class hierarchy.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.7). Bottom band (0.70) alongside ReadOnlyInputRule and the resilience rules. Rationale: inheritance is a structural hint, not evidence — a subclass of AbstractHandler might be a controller or a test double or a stub. We use the lexical shortcut "name starts with Abstract/Base => POLICY" because Python convention strongly correlates those prefixes with abstract base classes (PEP 3119). Parser certainty 0.75 is slightly below the 0.80 edge-precision band because tree-sitter has known gaps on multi-base metaclass hierarchies. TODO(calibration): measure tier-disagreement rate vs. behavioral rules on the 20-repo corpus; if inheritance routinely gets overruled, demote to an "explanation only" rule that never writes a mapping.

Source code in py/cogant/translate/rules/structural.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
class InheritanceRule(TranslationRule):
    """Maps class inheritance to inform semantic roles via base class hierarchy.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.7)``. **Bottom band** (0.70)
        alongside ``ReadOnlyInputRule`` and the resilience rules.
        Rationale: inheritance is a structural hint, not evidence —
        a subclass of ``AbstractHandler`` might be a controller or a
        test double or a stub. We use the lexical shortcut "name
        starts with ``Abstract``/``Base`` => POLICY" because Python
        convention strongly correlates those prefixes with abstract
        base classes (PEP 3119). Parser certainty 0.75 is slightly
        below the 0.80 edge-precision band because tree-sitter has
        known gaps on multi-base metaclass hierarchies.
        TODO(calibration): measure tier-disagreement rate vs.
        behavioral rules on the 20-repo corpus; if inheritance
        routinely gets overruled, demote to an "explanation only"
        rule that never writes a mapping.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes with inheritance relationships.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched inheritance patterns.
        """
        matches = []

        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            # Find INHERITS edges from this class
            out_edges = graph.get_edges_from(cls.id)
            inherit_edges = [e for e in out_edges if e.kind == EdgeKind.INHERITS]

            if inherit_edges:
                base_ids = [e.target_id for e in inherit_edges]
                matches.append(
                    {
                        "node_id": cls.id,
                        "base_ids": base_ids,
                        "base_count": len(base_ids),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create semantic mapping based on inheritance pattern.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for inheritance-informed role.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        # Infer semantic kind from base class names
        base_ids = match.get("base_ids", [])
        inferred_kind = MappingKind.HIDDEN_STATE  # default

        # Check if abstract or interface-like
        if node.name.startswith("Abstract") or node.name.startswith("Base"):
            inferred_kind = MappingKind.POLICY

        # Otherwise check bases
        for base_id in base_ids:
            base = graph.get_node(base_id)
            if base:
                base_name_lower = base.name.lower()
                if "handler" in base_name_lower or "controller" in base_name_lower:
                    inferred_kind = MappingKind.POLICY
                    break

        mapping_id = f"inh_{node_id}_{hashlib.sha256(b'inheritance').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # Inheritance is a structural hint rather than direct evidence:
        # a subclass of ``AbstractHandler`` might be a real policy, a
        # test double, or a stub. Parser certainty 0.75 (below the
        # 0.80 tree-sitter norm) reflects known gaps on multi-base
        # metaclass hierarchies. TODO(calibration): log agreement with
        # behavioral/semantic rules; if inheritance loses >50% of
        # conflicts it should be demoted to an explanation-only rule.
        return SemanticMapping(
            id=mapping_id,
            kind=inferred_kind,
            graph_fragment_node_ids=[node_id] + base_ids,
            semantic_label=f"{node.name} - Inheritance Role",
            description=f"Class '{node.name}' inherits from {match['base_count']} base(s), mapped to {inferred_kind.value}",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                    metadata={"base_count": match["base_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.75,  # below norm: metaclass gaps
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "inheritance"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create semantic mapping based on inheritance pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for inheritance-informed role.

Source code in py/cogant/translate/rules/structural.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create semantic mapping based on inheritance pattern.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for inheritance-informed role.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    # Infer semantic kind from base class names
    base_ids = match.get("base_ids", [])
    inferred_kind = MappingKind.HIDDEN_STATE  # default

    # Check if abstract or interface-like
    if node.name.startswith("Abstract") or node.name.startswith("Base"):
        inferred_kind = MappingKind.POLICY

    # Otherwise check bases
    for base_id in base_ids:
        base = graph.get_node(base_id)
        if base:
            base_name_lower = base.name.lower()
            if "handler" in base_name_lower or "controller" in base_name_lower:
                inferred_kind = MappingKind.POLICY
                break

    mapping_id = f"inh_{node_id}_{hashlib.sha256(b'inheritance').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # Inheritance is a structural hint rather than direct evidence:
    # a subclass of ``AbstractHandler`` might be a real policy, a
    # test double, or a stub. Parser certainty 0.75 (below the
    # 0.80 tree-sitter norm) reflects known gaps on multi-base
    # metaclass hierarchies. TODO(calibration): log agreement with
    # behavioral/semantic rules; if inheritance loses >50% of
    # conflicts it should be demoted to an explanation-only rule.
    return SemanticMapping(
        id=mapping_id,
        kind=inferred_kind,
        graph_fragment_node_ids=[node_id] + base_ids,
        semantic_label=f"{node.name} - Inheritance Role",
        description=f"Class '{node.name}' inherits from {match['base_count']} base(s), mapped to {inferred_kind.value}",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
                metadata={"base_count": match["base_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.75,  # below norm: metaclass gaps
    )

matches(graph, query)

Find classes with inheritance relationships.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched inheritance patterns.

Source code in py/cogant/translate/rules/structural.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes with inheritance relationships.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched inheritance patterns.
    """
    matches = []

    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        # Find INHERITS edges from this class
        out_edges = graph.get_edges_from(cls.id)
        inherit_edges = [e for e in out_edges if e.kind == EdgeKind.INHERITS]

        if inherit_edges:
            base_ids = [e.target_id for e in inherit_edges]
            matches.append(
                {
                    "node_id": cls.id,
                    "base_ids": base_ids,
                    "base_count": len(base_ids),
                }
            )

    return matches

MutatingSubsystemRule

Bases: TranslationRule

Maps objects with frequent internal mutations to hidden-state modality.

Rule priority (audit 2026-04-09): :meth:priority returns 1 (see override below) so HIDDEN_STATE wins class-level overlaps against aggregate POLICY from :class:InheritanceRule at default priority 0 when both fire on the same CLASS node. The confidence score remains mid band (0.75): a class touched by any WRITES/MUTATES edge is a mild structural cue for hidden state, stronger than a pure read-only module (0.70) but weaker than a lexical action match (0.80) or a configuration hit (0.85+). The mutation-count threshold is deliberately >=1. TODO(calibration): sweep the threshold in {1, 2, 3} on the 20-repo corpus; a higher floor would likely raise precision at the cost of recall on under-instrumented fixtures.

Source code in py/cogant/translate/rules/structural.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
class MutatingSubsystemRule(TranslationRule):
    """Maps objects with frequent internal mutations to hidden-state modality.

    Rule priority (audit 2026-04-09):
        :meth:`priority` returns ``1`` (see override below) so
        ``HIDDEN_STATE`` wins class-level overlaps against aggregate
        ``POLICY`` from :class:`InheritanceRule` at default priority ``0``
        when both fire on the same ``CLASS`` node. The confidence score
        remains **mid band** (0.75): a class touched by any
        ``WRITES``/``MUTATES`` edge is a mild structural cue for hidden
        state, stronger than a pure read-only module (0.70) but weaker
        than a lexical action match (0.80) or a configuration hit
        (0.85+). The mutation-count threshold is deliberately ``>=1``.
        TODO(calibration): sweep the threshold in {1, 2, 3} on the
        20-repo corpus; a higher floor would likely raise precision at
        the cost of recall on under-instrumented fixtures.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find objects/classes with high mutation frequency.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched class/object nodes.
        """
        matches = []

        # Find all classes
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for cls in classes:
            # Count mutations (WRITES and MUTATES edges targeting this class)
            mutation_edges = []
            for edge in graph.edges.values():
                if (edge.target_id == cls.id or edge.source_id == cls.id) and edge.kind in (
                    EdgeKind.WRITES,
                    EdgeKind.MUTATES,
                ):
                    mutation_edges.append(edge)

            # Mutation-count threshold >=1. Principled default: any
            # mutation edge counts, because classes with internal state
            # are typically bursty (rare mutations between long read
            # phases) and a higher floor (e.g. >=3) would miss lazy
            # singletons and state machines with a single setter. The
            # downstream confidence gate (0.75 band) prevents false
            # positives on incidental ``__init__`` assignments.
            # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus.
            if len(mutation_edges) >= 1:
                matches.append(
                    {
                        "node_id": cls.id,
                        "mutation_count": len(mutation_edges),
                        "mutation_edges": [e.id for e in mutation_edges],
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create hidden-state mapping for mutating subsystem.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for hidden-state.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"hs_{node_id}_{hashlib.sha256(b'mutating_subsystem').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Any
        # ``WRITES``/``MUTATES`` edge on a class is a mild structural
        # cue for hidden state: stronger than a pure read-only module
        # (0.70) but weaker than a lexical action match (0.80) or a
        # config hit (0.85+). Parser certainty 0.80 = tree-sitter
        # Python-fallback band (edge extraction is less precise than
        # name extraction, hence below the 0.85–0.90 AST-native band).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.HIDDEN_STATE,
            graph_fragment_node_ids=[node_id],
            graph_fragment_edge_ids=match.get("mutation_edges", []),
            semantic_label=f"{node.name} - Hidden State",
            description=f"Class '{node.name}' maintains internal state (frequent mutations)",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={"mutation_count": match["mutation_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this class is a hidden-state / mutating subsystem.

        The rule only applies to ``CLASS`` nodes and fires when the class
        has at least one edge of kind ``WRITES`` or ``MUTATES`` touching
        it (either as source or as target). This mirrors the match logic
        in :meth:`matches` so the explain report stays honest.
        """
        if node.kind != NodeKind.CLASS:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"mutating_subsystem rule only applies to classes; "
                    f"node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        mutation_edges = []
        for edge in graph.edges.values():
            if (edge.target_id == node.id or edge.source_id == node.id) and edge.kind in (
                EdgeKind.WRITES,
                EdgeKind.MUTATES,
            ):
                mutation_edges.append(edge)

        evidence: list[str] = [
            f"mutation edges (WRITES|MUTATES) touching class: {len(mutation_edges)}",
        ]
        if mutation_edges:
            sample = [f"{e.kind.value}:{e.source_id}->{e.target_id}" for e in mutation_edges[:5]]
            evidence.append(f"sample: {sample}")

        if len(mutation_edges) >= 1:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=(
                    f"class '{node.name}' has {len(mutation_edges)} "
                    f"WRITES/MUTATES edge(s), indicating internal state"
                ),
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(f"class '{node.name}' has no WRITES/MUTATES edges"),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "mutating_subsystem"

    @property
    def priority(self) -> int:
        """Above class-level aggregate rules (e.g. ``ContainmentRule`` at 0).

        ``ContainmentRule`` can emit a class-scoped mapping that overlaps the
        same ``CLASS`` node as this rule. Equal ``(priority, confidence)``
        ties previously dropped the hidden-state mapping lexicographically.
        Hidden-state evidence from WRITES/MUTATES edges should win that tie.
        """
        return 1

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.HIDDEN_STATE

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

priority property

Above class-level aggregate rules (e.g. ContainmentRule at 0).

ContainmentRule can emit a class-scoped mapping that overlaps the same CLASS node as this rule. Equal (priority, confidence) ties previously dropped the hidden-state mapping lexicographically. Hidden-state evidence from WRITES/MUTATES edges should win that tie.

apply(graph, match)

Create hidden-state mapping for mutating subsystem.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for hidden-state.

Source code in py/cogant/translate/rules/structural.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create hidden-state mapping for mutating subsystem.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for hidden-state.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"hs_{node_id}_{hashlib.sha256(b'mutating_subsystem').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Any
    # ``WRITES``/``MUTATES`` edge on a class is a mild structural
    # cue for hidden state: stronger than a pure read-only module
    # (0.70) but weaker than a lexical action match (0.80) or a
    # config hit (0.85+). Parser certainty 0.80 = tree-sitter
    # Python-fallback band (edge extraction is less precise than
    # name extraction, hence below the 0.85–0.90 AST-native band).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.HIDDEN_STATE,
        graph_fragment_node_ids=[node_id],
        graph_fragment_edge_ids=match.get("mutation_edges", []),
        semantic_label=f"{node.name} - Hidden State",
        description=f"Class '{node.name}' maintains internal state (frequent mutations)",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={"mutation_count": match["mutation_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

explain(node, graph, query)

Explain whether this class is a hidden-state / mutating subsystem.

The rule only applies to CLASS nodes and fires when the class has at least one edge of kind WRITES or MUTATES touching it (either as source or as target). This mirrors the match logic in :meth:matches so the explain report stays honest.

Source code in py/cogant/translate/rules/structural.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this class is a hidden-state / mutating subsystem.

    The rule only applies to ``CLASS`` nodes and fires when the class
    has at least one edge of kind ``WRITES`` or ``MUTATES`` touching
    it (either as source or as target). This mirrors the match logic
    in :meth:`matches` so the explain report stays honest.
    """
    if node.kind != NodeKind.CLASS:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"mutating_subsystem rule only applies to classes; "
                f"node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    mutation_edges = []
    for edge in graph.edges.values():
        if (edge.target_id == node.id or edge.source_id == node.id) and edge.kind in (
            EdgeKind.WRITES,
            EdgeKind.MUTATES,
        ):
            mutation_edges.append(edge)

    evidence: list[str] = [
        f"mutation edges (WRITES|MUTATES) touching class: {len(mutation_edges)}",
    ]
    if mutation_edges:
        sample = [f"{e.kind.value}:{e.source_id}->{e.target_id}" for e in mutation_edges[:5]]
        evidence.append(f"sample: {sample}")

    if len(mutation_edges) >= 1:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=(
                f"class '{node.name}' has {len(mutation_edges)} "
                f"WRITES/MUTATES edge(s), indicating internal state"
            ),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(f"class '{node.name}' has no WRITES/MUTATES edges"),
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find objects/classes with high mutation frequency.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched class/object nodes.

Source code in py/cogant/translate/rules/structural.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find objects/classes with high mutation frequency.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched class/object nodes.
    """
    matches = []

    # Find all classes
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for cls in classes:
        # Count mutations (WRITES and MUTATES edges targeting this class)
        mutation_edges = []
        for edge in graph.edges.values():
            if (edge.target_id == cls.id or edge.source_id == cls.id) and edge.kind in (
                EdgeKind.WRITES,
                EdgeKind.MUTATES,
            ):
                mutation_edges.append(edge)

        # Mutation-count threshold >=1. Principled default: any
        # mutation edge counts, because classes with internal state
        # are typically bursty (rare mutations between long read
        # phases) and a higher floor (e.g. >=3) would miss lazy
        # singletons and state machines with a single setter. The
        # downstream confidence gate (0.75 band) prevents false
        # positives on incidental ``__init__`` assignments.
        # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus.
        if len(mutation_edges) >= 1:
            matches.append(
                {
                    "node_id": cls.id,
                    "mutation_count": len(mutation_edges),
                    "mutation_edges": [e.id for e in mutation_edges],
                }
            )

    return matches

ObservationRule

Bases: TranslationRule

Maps getter/query functions and read-only methods to observation modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85) on keyword match, or (0, 0.70) on the edge-based read-only fallback. - Keyword band: high band (0.85), same as PreferenceRule and TestAssertionRule, tied second only to ConfigRule (0.90). Rationale: lexical matches on get_/read_/fetch_ prefixes carry strong prior probability of observation semantics based on PEP 8 naming convention. - Fallback band: bottom band (0.70). The structural "reads, no writes" signal alone is weaker because pure-read helpers are also ubiquitous in private utility code. The bimodal confidence lets conflict resolution automatically prefer keyword-driven observations over structural ones. TODO(calibration): empirically validate the 0.85/0.70 split against a hand-labeled observation fixture.

Source code in py/cogant/translate/rules/semantic.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
class ObservationRule(TranslationRule):
    """Maps getter/query functions and read-only methods to observation modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)`` on keyword match, or
        ``(0, 0.70)`` on the edge-based read-only fallback.
        - Keyword band: **high band** (0.85), same as
          ``PreferenceRule`` and ``TestAssertionRule``, tied second
          only to ``ConfigRule`` (0.90). Rationale: lexical matches
          on ``get_``/``read_``/``fetch_`` prefixes carry strong
          prior probability of observation semantics based on PEP 8
          naming convention.
        - Fallback band: **bottom band** (0.70). The structural "reads,
          no writes" signal alone is weaker because pure-read helpers
          are also ubiquitous in private utility code.
        The bimodal confidence lets conflict resolution automatically
        prefer keyword-driven observations over structural ones.
        TODO(calibration): empirically validate the 0.85/0.70 split
        against a hand-labeled observation fixture.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions/methods that observe state without mutation.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched observation functions/methods.
        """
        matches = []
        observation_keywords = OBSERVATION_KEYWORDS

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            # Token-anchored keyword match (no raw substring containment).
            keyword_match = _matches_keyword(node.name, observation_keywords)

            # Check for read-only pattern: READS but no WRITES
            out_edges = graph.get_edges_from(node.id)
            reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
            mutates = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

            # A write-bearing function is an ACTION, not an OBSERVATION, even
            # when its name lexically suggests a read (``read_sensor`` writes
            # ``self.current_temp``). The structural mutation fact outranks
            # the lexical observation hint, so the keyword signal is only
            # honoured for functions that do not mutate state. This makes
            # ActionRule's precedence over ObservationRule deterministic
            # rather than relying on the 0.85 > 0.80 confidence tiebreak.
            keyword_match = keyword_match and (writes + mutates) == 0

            # Match if keyword match OR (has reads and neither writes nor mutates).
            # A function that mutates state is an ACTION even without a WRITES
            # edge, so the structural read-only branch must also exclude
            # mutations (mirrors the keyword suppression above and explain()).
            if keyword_match or (reads > 0 and writes == 0 and mutates == 0):
                matches.append(
                    {
                        "node_id": node.id,
                        "read_count": reads,
                        "write_count": writes,
                        "keyword_match": keyword_match,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for observation.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"obs_{node_id}_{hashlib.sha256(b'observation').hexdigest()[:8]}"
        # Bimodal confidence — 0.85 on keyword hit (high band, strong
        # PEP 8 naming prior), 0.70 on edge-only fallback (bottom band,
        # weaker because pure-read helpers are ubiquitous in private
        # utility code). The split is principled; the 0.15 gap is
        # chosen to cross the STATIC_ONLY → STATIC_PLUS_RUNTIME boundary
        # (0.65) if dynamic evidence is later added to a keyword-matched
        # mapping.
        confidence = 0.85 if match["keyword_match"] else 0.7

        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Observation",
            description=f"Function/method '{node.name}' observes state (read-only access)",
            confidence_score=confidence,
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=confidence,
                    metadata={
                        "read_count": match["read_count"],
                        "write_count": match["write_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this node is an observation.

        Walks the same decision path used by :meth:`matches`, but
        collects concrete evidence snippets (keyword matches and
        READS/WRITES edge counts) into a :class:`RuleExplanation` so the
        ``cogant explain`` CLI can render a justification report.
        """
        if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"observation rule only applies to functions/methods; "
                    f"node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        matched_keywords = _matched_keywords(node.name, OBSERVATION_KEYWORDS)

        out_edges = graph.get_edges_from(node.id)
        read_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.READS]
        write_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.WRITES]
        mutate_count = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

        evidence: list[str] = []
        if matched_keywords:
            evidence.append(f"keyword match: {matched_keywords}")
        evidence.append(f"READS count: {len(read_targets)}")
        evidence.append(f"WRITES count: {len(write_targets)}")
        if read_targets:
            evidence.append(f"READS targets: {sorted(read_targets)[:5]}")

        # A write-bearing function is an ACTION; suppress the observation
        # keyword signal when the node mutates state (mirrors matches()).
        keyword_match = bool(matched_keywords) and (len(write_targets) + mutate_count) == 0
        read_only = len(read_targets) > 0 and (len(write_targets) + mutate_count) == 0

        if keyword_match or read_only:
            if keyword_match and read_only:
                reason = (
                    f"name contains observation keyword(s) {matched_keywords} "
                    f"AND read-only access pattern (READS={len(read_targets)}, "
                    f"WRITES=0)"
                )
            elif keyword_match:
                reason = f"name contains observation keyword(s) {matched_keywords}"
            else:
                reason = (
                    f"read-only access pattern (READS={len(read_targets)}, "
                    f"WRITES=0) with no observation keyword"
                )
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=reason,
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        if matched_keywords and (len(write_targets) + mutate_count) > 0:
            reason = (
                f"observation keyword(s) {matched_keywords} present but the "
                f"function mutates state (WRITES={len(write_targets)}, "
                f"MUTATES={mutate_count}); the structural mutation fact "
                f"reclassifies it as an action"
            )
        else:
            reason = (
                f"no observation keyword in '{node.name}' and not read-only "
                f"(READS={len(read_targets)}, WRITES={len(write_targets)})"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "observation"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

    def to_gnn_role(self) -> str:
        """Return the GNN role string for observation mappings.

        Returns:
            GNN role identifier.
        """
        return "OBSERVATION"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for observation.

Source code in py/cogant/translate/rules/semantic.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for observation.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"obs_{node_id}_{hashlib.sha256(b'observation').hexdigest()[:8]}"
    # Bimodal confidence — 0.85 on keyword hit (high band, strong
    # PEP 8 naming prior), 0.70 on edge-only fallback (bottom band,
    # weaker because pure-read helpers are ubiquitous in private
    # utility code). The split is principled; the 0.15 gap is
    # chosen to cross the STATIC_ONLY → STATIC_PLUS_RUNTIME boundary
    # (0.65) if dynamic evidence is later added to a keyword-matched
    # mapping.
    confidence = 0.85 if match["keyword_match"] else 0.7

    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Observation",
        description=f"Function/method '{node.name}' observes state (read-only access)",
        confidence_score=confidence,
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=confidence,
                metadata={
                    "read_count": match["read_count"],
                    "write_count": match["write_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,
    )

explain(node, graph, query)

Explain whether this node is an observation.

Walks the same decision path used by :meth:matches, but collects concrete evidence snippets (keyword matches and READS/WRITES edge counts) into a :class:RuleExplanation so the cogant explain CLI can render a justification report.

Source code in py/cogant/translate/rules/semantic.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this node is an observation.

    Walks the same decision path used by :meth:`matches`, but
    collects concrete evidence snippets (keyword matches and
    READS/WRITES edge counts) into a :class:`RuleExplanation` so the
    ``cogant explain`` CLI can render a justification report.
    """
    if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"observation rule only applies to functions/methods; "
                f"node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    matched_keywords = _matched_keywords(node.name, OBSERVATION_KEYWORDS)

    out_edges = graph.get_edges_from(node.id)
    read_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.READS]
    write_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.WRITES]
    mutate_count = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

    evidence: list[str] = []
    if matched_keywords:
        evidence.append(f"keyword match: {matched_keywords}")
    evidence.append(f"READS count: {len(read_targets)}")
    evidence.append(f"WRITES count: {len(write_targets)}")
    if read_targets:
        evidence.append(f"READS targets: {sorted(read_targets)[:5]}")

    # A write-bearing function is an ACTION; suppress the observation
    # keyword signal when the node mutates state (mirrors matches()).
    keyword_match = bool(matched_keywords) and (len(write_targets) + mutate_count) == 0
    read_only = len(read_targets) > 0 and (len(write_targets) + mutate_count) == 0

    if keyword_match or read_only:
        if keyword_match and read_only:
            reason = (
                f"name contains observation keyword(s) {matched_keywords} "
                f"AND read-only access pattern (READS={len(read_targets)}, "
                f"WRITES=0)"
            )
        elif keyword_match:
            reason = f"name contains observation keyword(s) {matched_keywords}"
        else:
            reason = (
                f"read-only access pattern (READS={len(read_targets)}, "
                f"WRITES=0) with no observation keyword"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    if matched_keywords and (len(write_targets) + mutate_count) > 0:
        reason = (
            f"observation keyword(s) {matched_keywords} present but the "
            f"function mutates state (WRITES={len(write_targets)}, "
            f"MUTATES={mutate_count}); the structural mutation fact "
            f"reclassifies it as an action"
        )
    else:
        reason = (
            f"no observation keyword in '{node.name}' and not read-only "
            f"(READS={len(read_targets)}, WRITES={len(write_targets)})"
        )
    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=reason,
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find functions/methods that observe state without mutation.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched observation functions/methods.

Source code in py/cogant/translate/rules/semantic.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions/methods that observe state without mutation.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched observation functions/methods.
    """
    matches = []
    observation_keywords = OBSERVATION_KEYWORDS

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        # Token-anchored keyword match (no raw substring containment).
        keyword_match = _matches_keyword(node.name, observation_keywords)

        # Check for read-only pattern: READS but no WRITES
        out_edges = graph.get_edges_from(node.id)
        reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
        mutates = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

        # A write-bearing function is an ACTION, not an OBSERVATION, even
        # when its name lexically suggests a read (``read_sensor`` writes
        # ``self.current_temp``). The structural mutation fact outranks
        # the lexical observation hint, so the keyword signal is only
        # honoured for functions that do not mutate state. This makes
        # ActionRule's precedence over ObservationRule deterministic
        # rather than relying on the 0.85 > 0.80 confidence tiebreak.
        keyword_match = keyword_match and (writes + mutates) == 0

        # Match if keyword match OR (has reads and neither writes nor mutates).
        # A function that mutates state is an ACTION even without a WRITES
        # edge, so the structural read-only branch must also exclude
        # mutations (mirrors the keyword suppression above and explain()).
        if keyword_match or (reads > 0 and writes == 0 and mutates == 0):
            matches.append(
                {
                    "node_id": node.id,
                    "read_count": reads,
                    "write_count": writes,
                    "keyword_match": keyword_match,
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for observation mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
332
333
334
335
336
337
338
def to_gnn_role(self) -> str:
    """Return the GNN role string for observation mappings.

    Returns:
        GNN role identifier.
    """
    return "OBSERVATION"

OrchestratorRule

Bases: TranslationRule

Maps schedulers and controllers to policy/action structure.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule/ContextRule/ CircuitBreakerRule. Rationale: high call fan-out is a reliable structural signal for orchestration but not unambiguous — utility modules can also have many calls. Call-count threshold = 3 (see matches): below 3, the pattern is indistinguishable from simple helpers. TODO(calibration): sweep {2, 3, 5, 8} on the 20-repo corpus.

Source code in py/cogant/translate/rules/behavioral.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class OrchestratorRule(TranslationRule):
    """Maps schedulers and controllers to policy/action structure.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``/``ContextRule``/
        ``CircuitBreakerRule``. Rationale: high call fan-out is a
        reliable structural signal for orchestration but not
        unambiguous — utility modules can also have many calls.
        Call-count threshold = 3 (see ``matches``): below 3, the
        pattern is indistinguishable from simple helpers.
        TODO(calibration): sweep {2, 3, 5, 8} on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find orchestrator patterns (high out-degree controllers).

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched orchestrator nodes.
        """
        matches = []

        # Look for functions/classes with high out-degree (calling many others)
        for node in graph.nodes.values():
            if node.kind not in (NodeKind.CLASS, NodeKind.FUNCTION, NodeKind.METHOD):
                continue

            out_edges = graph.get_edges_from(node.id)
            call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

            # Call-count threshold = 3. Principled default: below 3
            # calls, high-fan-out is indistinguishable from simple
            # helper functions (2 calls = typical setup/teardown);
            # at >=3 the pattern starts to look like real
            # orchestration (setup/work/cleanup triad or larger).
            # TODO(calibration): sweep {2, 3, 5, 8} on 20-repo corpus.
            if len(call_edges) >= 3:
                matches.append(
                    {
                        "node_id": node.id,
                        "call_count": len(call_edges),
                        "called_node_ids": [e.target_id for e in call_edges],
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create orchestration mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for orchestration.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"orch_{node_id}_{hashlib.sha256(b'orchestrator').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band). High
        # call fan-out is reliable but not unambiguous. Parser
        # certainty 0.90 because call-edge extraction is one of the
        # highest-precision operations in the Python AST substrate.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ORCHESTRATION,
            graph_fragment_node_ids=[node_id] + match.get("called_node_ids", []),
            semantic_label=f"{node.name} - Orchestrator",
            description=f"{'Class' if node.kind == NodeKind.CLASS else 'Function'} '{node.name}' acts as orchestrator (high fan-out)",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={"call_count": match["call_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # high AST precision on CALLS edges
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "orchestrator"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ORCHESTRATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create orchestration mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for orchestration.

Source code in py/cogant/translate/rules/behavioral.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create orchestration mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for orchestration.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"orch_{node_id}_{hashlib.sha256(b'orchestrator').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band). High
    # call fan-out is reliable but not unambiguous. Parser
    # certainty 0.90 because call-edge extraction is one of the
    # highest-precision operations in the Python AST substrate.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ORCHESTRATION,
        graph_fragment_node_ids=[node_id] + match.get("called_node_ids", []),
        semantic_label=f"{node.name} - Orchestrator",
        description=f"{'Class' if node.kind == NodeKind.CLASS else 'Function'} '{node.name}' acts as orchestrator (high fan-out)",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={"call_count": match["call_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # high AST precision on CALLS edges
    )

matches(graph, query)

Find orchestrator patterns (high out-degree controllers).

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched orchestrator nodes.

Source code in py/cogant/translate/rules/behavioral.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find orchestrator patterns (high out-degree controllers).

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched orchestrator nodes.
    """
    matches = []

    # Look for functions/classes with high out-degree (calling many others)
    for node in graph.nodes.values():
        if node.kind not in (NodeKind.CLASS, NodeKind.FUNCTION, NodeKind.METHOD):
            continue

        out_edges = graph.get_edges_from(node.id)
        call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        # Call-count threshold = 3. Principled default: below 3
        # calls, high-fan-out is indistinguishable from simple
        # helper functions (2 calls = typical setup/teardown);
        # at >=3 the pattern starts to look like real
        # orchestration (setup/work/cleanup triad or larger).
        # TODO(calibration): sweep {2, 3, 5, 8} on 20-repo corpus.
        if len(call_edges) >= 3:
            matches.append(
                {
                    "node_id": node.id,
                    "call_count": len(call_edges),
                    "called_node_ids": [e.target_id for e in call_edges],
                }
            )

    return matches

PolicyRule

Bases: TranslationRule

Maps controllers, handlers, and routers to policy modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule, ContextRule, OrchestratorRule, CircuitBreakerRule. Rationale: controller/handler/router vocabulary is a strong web-framework signal (Flask, Django, FastAPI) but carries real ambiguity — "handler" also appears in action and retry contexts. Confidence tie-breaking between policy and action on handle/dispatch is delegated to per-match context. TODO(calibration): measure the policy↔action collision rate on handle/dispatch in the 20-repo corpus.

Source code in py/cogant/translate/rules/semantic.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class PolicyRule(TranslationRule):
    """Maps controllers, handlers, and routers to policy modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``, ``ContextRule``, ``OrchestratorRule``,
        ``CircuitBreakerRule``. Rationale: controller/handler/router
        vocabulary is a strong web-framework signal (Flask, Django,
        FastAPI) but carries real ambiguity — "handler" also appears
        in action and retry contexts. Confidence tie-breaking between
        policy and action on ``handle``/``dispatch`` is delegated to
        per-match context. TODO(calibration): measure the
        policy↔action collision rate on ``handle``/``dispatch`` in
        the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes and functions that implement policy/control logic.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched policy nodes.
        """
        matches = []
        # Policy keywords — sourced from web-framework conventions
        # (Flask view, Django middleware, FastAPI router, express
        # handler). Principled default. The overlap with ACTION_KEYWORDS
        # on ``handle``/``dispatch`` is intentional; conflict resolution
        # in ``_resolve_conflicts`` will pick whichever rule produces
        # higher confidence on that specific match.
        policy_keywords = [
            "middleware",
            "handler",
            "controller",
            "manager",
            "router",
            "dispatcher",
            "scheduler",
            "route",
            "dispatch",
            "handle",
            "select_",
            "choose_",
            "decide_",
            "plan_",
            "strategy",
            "orchestrator",
            "coordinator",
            "supervisor",
        ]

        # Find classes
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            has_keyword = _matches_keyword(cls.name, policy_keywords)

            # Check for __call__ method (callable class = decision logic)
            has_call_method = False
            out_edges = graph.get_edges_from(cls.id)
            # Distinct name from the function-loop ``methods`` below; filtering
            # None here keeps the type ``list[Node]`` (get_node may return None
            # for dangling CONTAINS targets) so attribute access is type-safe.
            contained = [
                node
                for node in (
                    graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
                )
                if node is not None
            ]
            for method in contained:
                if method.name == "__call__":
                    has_call_method = True
                    break

            if has_keyword or has_call_method:
                call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)
                matches.append(
                    {
                        "node_id": cls.id,
                        "call_count": call_count,
                        "node_type": "class",
                        "has_call_method": has_call_method,
                    }
                )

        # Find functions with policy keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            if _matches_keyword(node.name, policy_keywords):
                out_edges = graph.get_edges_from(node.id)
                call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

                matches.append(
                    {
                        "node_id": node.id,
                        "call_count": call_count,
                        "node_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create policy mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for policy.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"pol_{node_id}_{hashlib.sha256(b'policy').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # Parser certainty 0.85 = AST-native (class/function names
        # are extracted by Python AST, not tree-sitter fallback).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Policy",
            description=f"{'Class' if match['node_type'] == 'class' else 'Function'} '{node.name}' implements control policy",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={"call_count": match["call_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "policy"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

    def to_gnn_role(self) -> str:
        """Return the GNN role string for policy mappings.

        Returns:
            GNN role identifier.
        """
        return "POLICY"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create policy mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for policy.

Source code in py/cogant/translate/rules/semantic.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create policy mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for policy.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"pol_{node_id}_{hashlib.sha256(b'policy').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # Parser certainty 0.85 = AST-native (class/function names
    # are extracted by Python AST, not tree-sitter fallback).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Policy",
        description=f"{'Class' if match['node_type'] == 'class' else 'Function'} '{node.name}' implements control policy",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={"call_count": match["call_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

matches(graph, query)

Find classes and functions that implement policy/control logic.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched policy nodes.

Source code in py/cogant/translate/rules/semantic.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes and functions that implement policy/control logic.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched policy nodes.
    """
    matches = []
    # Policy keywords — sourced from web-framework conventions
    # (Flask view, Django middleware, FastAPI router, express
    # handler). Principled default. The overlap with ACTION_KEYWORDS
    # on ``handle``/``dispatch`` is intentional; conflict resolution
    # in ``_resolve_conflicts`` will pick whichever rule produces
    # higher confidence on that specific match.
    policy_keywords = [
        "middleware",
        "handler",
        "controller",
        "manager",
        "router",
        "dispatcher",
        "scheduler",
        "route",
        "dispatch",
        "handle",
        "select_",
        "choose_",
        "decide_",
        "plan_",
        "strategy",
        "orchestrator",
        "coordinator",
        "supervisor",
    ]

    # Find classes
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        has_keyword = _matches_keyword(cls.name, policy_keywords)

        # Check for __call__ method (callable class = decision logic)
        has_call_method = False
        out_edges = graph.get_edges_from(cls.id)
        # Distinct name from the function-loop ``methods`` below; filtering
        # None here keeps the type ``list[Node]`` (get_node may return None
        # for dangling CONTAINS targets) so attribute access is type-safe.
        contained = [
            node
            for node in (
                graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
            )
            if node is not None
        ]
        for method in contained:
            if method.name == "__call__":
                has_call_method = True
                break

        if has_keyword or has_call_method:
            call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)
            matches.append(
                {
                    "node_id": cls.id,
                    "call_count": call_count,
                    "node_type": "class",
                    "has_call_method": has_call_method,
                }
            )

    # Find functions with policy keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        if _matches_keyword(node.name, policy_keywords):
            out_edges = graph.get_edges_from(node.id)
            call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

            matches.append(
                {
                    "node_id": node.id,
                    "call_count": call_count,
                    "node_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for policy mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
710
711
712
713
714
715
716
def to_gnn_role(self) -> str:
    """Return the GNN role string for policy mappings.

    Returns:
        GNN role identifier.
    """
    return "POLICY"

PreferenceRule

Bases: TranslationRule

Maps validators and test functions to preference/constraint modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with TestAssertionRule and the keyword branch of ObservationRule. Rationale: validate/check/ Validator/test_ are exceptionally strong lexical signals — there is essentially no non-constraint use of test_ prefixes in well-formed Python, and PEP 8 + pytest/unittest conventions anchor the other patterns. Parser certainty 0.90 is the highest in the rule family because name-only matching doesn't depend on edge extraction.

Source code in py/cogant/translate/rules/semantic.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
class PreferenceRule(TranslationRule):
    """Maps validators and test functions to preference/constraint modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85), tied
        with ``TestAssertionRule`` and the keyword branch of
        ``ObservationRule``. Rationale: ``validate``/``check``/
        ``Validator``/``test_`` are exceptionally strong lexical
        signals — there is essentially no non-constraint use of
        ``test_`` prefixes in well-formed Python, and PEP 8 +
        pytest/unittest conventions anchor the other patterns.
        Parser certainty 0.90 is the highest in the rule family
        because name-only matching doesn't depend on edge extraction.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find validation and test functions.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched preference/constraint nodes.
        """
        matches = []

        # Preference/constraint keywords covering cost, reward, objective, loss, utility
        constraint_keywords = [
            "validator",
            "checker",
            "test_",
            "assert_",
            "validate",
            "check",
            "cost_",
            "reward_",
            "objective_",
            "loss_",
            "utility_",
            "metric",
        ]

        # Find classes with Validator/Checker/etc in name
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            if _matches_keyword(cls.name, constraint_keywords):
                matches.append(
                    {
                        "node_id": cls.id,
                        "constraint_type": "class",
                    }
                )

        # Find functions/methods with constraint keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            if _matches_keyword(node.name, constraint_keywords):
                matches.append(
                    {
                        "node_id": node.id,
                        "constraint_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create preference/constraint mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for constraint.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"pref_{node_id}_{hashlib.sha256(b'preference').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). The
        # ``test_``/``assert_``/``validate``/``check``/``Validator``
        # vocabulary is exceptionally unambiguous in Python — PEP 8
        # + pytest/unittest conventions anchor these as constraint
        # signals. Parser certainty 0.90 is the highest in the rule
        # family because name-only matching doesn't depend on edge
        # extraction accuracy.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONSTRAINT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Preference/Constraint",
            description=f"{'Class' if match['constraint_type'] == 'class' else 'Function'} '{node.name}' defines system constraints",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # name-only, highest in family
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "preference"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONSTRAINT

    def to_gnn_role(self) -> str:
        """Return the GNN role string for preference/constraint mappings.

        Returns:
            GNN role identifier.
        """
        return "PREFERENCE"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create preference/constraint mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for constraint.

Source code in py/cogant/translate/rules/semantic.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create preference/constraint mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for constraint.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"pref_{node_id}_{hashlib.sha256(b'preference').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). The
    # ``test_``/``assert_``/``validate``/``check``/``Validator``
    # vocabulary is exceptionally unambiguous in Python — PEP 8
    # + pytest/unittest conventions anchor these as constraint
    # signals. Parser certainty 0.90 is the highest in the rule
    # family because name-only matching doesn't depend on edge
    # extraction accuracy.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONSTRAINT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Preference/Constraint",
        description=f"{'Class' if match['constraint_type'] == 'class' else 'Function'} '{node.name}' defines system constraints",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # name-only, highest in family
    )

matches(graph, query)

Find validation and test functions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched preference/constraint nodes.

Source code in py/cogant/translate/rules/semantic.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find validation and test functions.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched preference/constraint nodes.
    """
    matches = []

    # Preference/constraint keywords covering cost, reward, objective, loss, utility
    constraint_keywords = [
        "validator",
        "checker",
        "test_",
        "assert_",
        "validate",
        "check",
        "cost_",
        "reward_",
        "objective_",
        "loss_",
        "utility_",
        "metric",
    ]

    # Find classes with Validator/Checker/etc in name
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        if _matches_keyword(cls.name, constraint_keywords):
            matches.append(
                {
                    "node_id": cls.id,
                    "constraint_type": "class",
                }
            )

    # Find functions/methods with constraint keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        if _matches_keyword(node.name, constraint_keywords):
            matches.append(
                {
                    "node_id": node.id,
                    "constraint_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for preference/constraint mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
841
842
843
844
845
846
847
def to_gnn_role(self) -> str:
    """Return the GNN role string for preference/constraint mappings.

    Returns:
        GNN role identifier.
    """
    return "PREFERENCE"

ReadOnlyInputRule

Bases: TranslationRule

Maps modules with many read-only external inputs to observation modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.7) via the flat-priority=0 design documented in :class:TranslationRule.priority, so conflict resolution falls through to confidence_score = 0.7. This places the rule in the bottom band (0.70) alongside InheritanceRule, RetryPatternRule, ErrorBoundaryRule and the ObservationRule lexical-fallback branch. Rationale: module-level "all reads, no writes" is a weak structural signal (modules nearly always expose some read API), so it should cleanly lose to any function/method-level rule that also fires on the same fragment. TODO(calibration): measure the ReadOnlyInputRule→ObservationRule conflict-loss rate on the 20-repo corpus and promote to a dedicated priority tier only if the loss rate exceeds ~20%.

Source code in py/cogant/translate/rules/structural.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class ReadOnlyInputRule(TranslationRule):
    """Maps modules with many read-only external inputs to observation modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.7)`` via the flat-``priority=0`` design
        documented in :class:`TranslationRule.priority`, so conflict
        resolution falls through to ``confidence_score = 0.7``. This
        places the rule in the **bottom band** (0.70) alongside
        ``InheritanceRule``, ``RetryPatternRule``, ``ErrorBoundaryRule``
        and the ``ObservationRule`` lexical-fallback branch. Rationale:
        module-level "all reads, no writes" is a weak structural signal
        (modules nearly always expose some read API), so it should
        cleanly lose to any function/method-level rule that also fires
        on the same fragment. TODO(calibration): measure the
        ReadOnlyInputRule→ObservationRule conflict-loss rate on the
        20-repo corpus and promote to a dedicated priority tier only
        if the loss rate exceeds ~20%.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find modules with predominance of read operations.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched module nodes.
        """
        matches = []

        # Find all modules
        modules = graph.get_nodes_by_kind(NodeKind.MODULE)

        for module in modules:
            # Get all edges from module
            outgoing_edges = graph.get_edges_from(module.id)
            graph.get_edges_to(module.id)

            # Count read vs write operations
            reads = sum(1 for e in outgoing_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in outgoing_edges if e.kind == EdgeKind.WRITES)

            # Check if predominantly read-only
            if reads > 0 and writes == 0:
                matches.append(
                    {
                        "node_id": module.id,
                        "read_count": reads,
                        "write_count": writes,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation mapping for read-only module.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for observation modality.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"obs_{node_id}_{hashlib.sha256(b'read_only_input').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band). Module-level
        # "reads only" is a weak structural cue (modules almost always
        # export some read API), so this rule is intentionally beaten by
        # any higher-confidence function/method-level rule that fires on
        # the same fragment. 0.70 lands at STATIC_ONLY_THRESHOLD+0.20 in
        # ConfidenceModel, keeping the mapping acceptable on its own.
        # Parser certainty 0.80 = tree-sitter Python-fallback band.
        # TODO(calibration): retune against per-module precision on the
        # 20-repo fixture set.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Read-Only Input",
            description=f"Module '{node.name}' acts as observation source (read-only external input)",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                    metadata={"read_count": match["read_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "read_only_input"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation mapping for read-only module.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for observation modality.

Source code in py/cogant/translate/rules/structural.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation mapping for read-only module.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for observation modality.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"obs_{node_id}_{hashlib.sha256(b'read_only_input').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band). Module-level
    # "reads only" is a weak structural cue (modules almost always
    # export some read API), so this rule is intentionally beaten by
    # any higher-confidence function/method-level rule that fires on
    # the same fragment. 0.70 lands at STATIC_ONLY_THRESHOLD+0.20 in
    # ConfidenceModel, keeping the mapping acceptable on its own.
    # Parser certainty 0.80 = tree-sitter Python-fallback band.
    # TODO(calibration): retune against per-module precision on the
    # 20-repo fixture set.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Read-Only Input",
        description=f"Module '{node.name}' acts as observation source (read-only external input)",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
                metadata={"read_count": match["read_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find modules with predominance of read operations.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched module nodes.

Source code in py/cogant/translate/rules/structural.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find modules with predominance of read operations.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched module nodes.
    """
    matches = []

    # Find all modules
    modules = graph.get_nodes_by_kind(NodeKind.MODULE)

    for module in modules:
        # Get all edges from module
        outgoing_edges = graph.get_edges_from(module.id)
        graph.get_edges_to(module.id)

        # Count read vs write operations
        reads = sum(1 for e in outgoing_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in outgoing_edges if e.kind == EdgeKind.WRITES)

        # Check if predominantly read-only
        if reads > 0 and writes == 0:
            matches.append(
                {
                    "node_id": module.id,
                    "read_count": reads,
                    "write_count": writes,
                }
            )

    return matches

RetryPatternRule

Bases: TranslationRule

Maps retry/backoff/circuit breaker patterns to policy under uncertainty.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.70). Bottom band (0.70), tied with ReadOnlyInputRule, InheritanceRule, ErrorBoundaryRule, and the lexical fallback of ObservationRule. Rationale: keyword matching alone is a weak signal for retry logic — a function named retry_count might be a counter, not a retry executor. This rule intentionally loses to the stronger CircuitBreakerRule (0.80) when both fire. Parser certainty 0.70 is the lowest in the family because tree- sitter pattern detection for retry decorators is incomplete. TODO(calibration): promote to 0.80 if GUARDS edge coverage improves in the parser.

Source code in py/cogant/translate/rules/resilience.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class RetryPatternRule(TranslationRule):
    """Maps retry/backoff/circuit breaker patterns to policy under uncertainty.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.70)``. **Bottom band** (0.70),
        tied with ``ReadOnlyInputRule``, ``InheritanceRule``,
        ``ErrorBoundaryRule``, and the lexical fallback of
        ``ObservationRule``. Rationale: keyword matching alone is
        a weak signal for retry logic — a function named
        ``retry_count`` might be a counter, not a retry executor.
        This rule intentionally loses to the stronger
        ``CircuitBreakerRule`` (0.80) when both fire. Parser
        certainty 0.70 is the lowest in the family because tree-
        sitter pattern detection for retry decorators is
        incomplete. TODO(calibration): promote to 0.80 if GUARDS
        edge coverage improves in the parser.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find retry and circuit breaker patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched pattern nodes.
        """
        matches = []

        # Look for functions/methods with retry/circuit breaker keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        functions.extend(graph.get_nodes_by_kind(NodeKind.METHOD))

        retry_keywords = ["retry", "backoff", "circuit", "breaker", "timeout", "fallback"]

        for func in functions:
            name_lower = func.name.lower()
            if any(keyword in name_lower for keyword in retry_keywords):
                matches.append(
                    {
                        "node_id": func.id,
                        "pattern_type": "retry_or_circuit_breaker",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create policy mapping for retry pattern.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for policy.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"policy_{node_id}_{hashlib.sha256(b'retry_pattern').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # Keyword-only matching is noisy (``retry_count`` might be
        # just a counter). Parser certainty 0.70 is the lowest in
        # the family because decorator-based retry patterns have
        # incomplete tree-sitter coverage. Intentionally loses to
        # CircuitBreakerRule (0.80) on the same fragment.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Retry Policy",
            description=f"Function '{node.name}' implements retry/circuit breaker policy",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                )
            ],
            evidence_count=1,
            parser_certainty=0.7,  # lowest in family (decorator gap)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "retry_pattern"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create policy mapping for retry pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for policy.

Source code in py/cogant/translate/rules/resilience.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create policy mapping for retry pattern.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for policy.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"policy_{node_id}_{hashlib.sha256(b'retry_pattern').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # Keyword-only matching is noisy (``retry_count`` might be
    # just a counter). Parser certainty 0.70 is the lowest in
    # the family because decorator-based retry patterns have
    # incomplete tree-sitter coverage. Intentionally loses to
    # CircuitBreakerRule (0.80) on the same fragment.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Retry Policy",
        description=f"Function '{node.name}' implements retry/circuit breaker policy",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
            )
        ],
        evidence_count=1,
        parser_certainty=0.7,  # lowest in family (decorator gap)
    )

matches(graph, query)

Find retry and circuit breaker patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched pattern nodes.

Source code in py/cogant/translate/rules/resilience.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find retry and circuit breaker patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched pattern nodes.
    """
    matches = []

    # Look for functions/methods with retry/circuit breaker keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    functions.extend(graph.get_nodes_by_kind(NodeKind.METHOD))

    retry_keywords = ["retry", "backoff", "circuit", "breaker", "timeout", "fallback"]

    for func in functions:
        name_lower = func.name.lower()
        if any(keyword in name_lower for keyword in retry_keywords):
            matches.append(
                {
                    "node_id": func.id,
                    "pattern_type": "retry_or_circuit_breaker",
                }
            )

    return matches

ReviewManager

Manages human review of semantic mappings.

Accepts, rejects, edits, splits, and merges mappings while tracking all provenance and changes.

Source code in py/cogant/translate/review.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class ReviewManager:
    """Manages human review of semantic mappings.

    Accepts, rejects, edits, splits, and merges mappings while tracking
    all provenance and changes.
    """

    def __init__(self) -> None:
        """Initialize the review manager."""
        self.mappings: dict[str, SemanticMapping] = {}
        self.review_history: list[dict[str, Any]] = []

    def add_mapping(self, mapping: SemanticMapping) -> None:
        """Add a mapping for potential review.

        Args:
            mapping: Mapping to add.
        """
        self.mappings[mapping.id] = mapping

    def accept_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        feedback: str | None = None,
    ) -> bool:
        """Accept a mapping as valid.

        Args:
            mapping_id: ID of mapping to accept.
            reviewer: Name of reviewer.
            feedback: Optional review feedback.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        mapping.status = "accepted"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)
        mapping.review_feedback = feedback

        # Upgrade confidence tier if human reviewed
        if mapping.confidence_tier != ConfidenceTier.HUMAN_REVIEWED:
            mapping.confidence_tier = ConfidenceTier.HUMAN_REVIEWED
            mapping.confidence_score = min(1.0, mapping.confidence_score + 0.15)

        self._log_review("accept", mapping_id, reviewer, feedback)
        return True

    def reject_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        reason: str,
    ) -> bool:
        """Reject a mapping as invalid.

        Args:
            mapping_id: ID of mapping to reject.
            reviewer: Name of reviewer.
            reason: Reason for rejection.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        mapping.status = "rejected"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)
        mapping.review_feedback = reason
        mapping.confidence_score = 0.0

        self._log_review("reject", mapping_id, reviewer, reason)
        return True

    def edit_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        updates: dict[str, Any],
    ) -> bool:
        """Edit a mapping based on review feedback.

        Args:
            mapping_id: ID of mapping to edit.
            reviewer: Name of reviewer.
            updates: Dictionary of fields to update.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        old_values = {}

        # Apply updates
        for key, value in updates.items():
            if hasattr(mapping, key):
                old_values[key] = getattr(mapping, key)
                setattr(mapping, key, value)

        mapping.status = "edited"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)

        self._log_review(
            "edit", mapping_id, reviewer, {"old_values": old_values, "new_values": updates}
        )
        return True

    def split_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        split_definitions: list[dict[str, Any]],
    ) -> list[str]:
        """Split a mapping into multiple mappings.

        Args:
            mapping_id: ID of mapping to split.
            reviewer: Name of reviewer.
            split_definitions: List of definitions for new mappings.

        Returns:
            List of IDs of new mappings.
        """
        if mapping_id not in self.mappings:
            return []

        original = self.mappings[mapping_id]
        new_ids = []

        for i, definition in enumerate(split_definitions):
            new_id = f"{mapping_id}_split_{i}"

            new_mapping = SemanticMapping(
                id=new_id,
                kind=definition.get("kind", original.kind),
                graph_fragment_node_ids=definition.get("node_ids", []),
                graph_fragment_edge_ids=definition.get("edge_ids", []),
                semantic_label=definition.get("label", original.semantic_label),
                description=definition.get("description", original.description),
                confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
                status="edited",
                reviewed_by=reviewer,
                reviewed_at=datetime.now(UTC),
            )

            self.mappings[new_id] = new_mapping
            new_ids.append(new_id)

        # Mark original as split
        original.status = "split"
        original.reviewed_by = reviewer
        original.reviewed_at = datetime.now(UTC)

        self._log_review("split", mapping_id, reviewer, {"new_mappings": new_ids})
        return new_ids

    def merge_mappings(
        self,
        mapping_ids: list[str],
        reviewer: str,
        merged_definition: dict[str, Any],
    ) -> str | None:
        """Merge multiple mappings into one.

        Args:
            mapping_ids: IDs of mappings to merge.
            reviewer: Name of reviewer.
            merged_definition: Definition of merged mapping.

        Returns:
            ID of new merged mapping, or None if invalid.
        """
        # Verify all mappings exist
        for mid in mapping_ids:
            if mid not in self.mappings:
                return None

        # Create merged mapping
        merged_id = f"merged_{'_'.join(m[:8] for m in mapping_ids)}"

        # Collect all node and edge IDs
        all_node_ids = []
        all_edge_ids = []
        for mid in mapping_ids:
            mapping = self.mappings[mid]
            all_node_ids.extend(mapping.graph_fragment_node_ids)
            all_edge_ids.extend(mapping.graph_fragment_edge_ids)

        # Deduplicate
        all_node_ids = list(set(all_node_ids))
        all_edge_ids = list(set(all_edge_ids))

        merged = SemanticMapping(
            id=merged_id,
            kind=merged_definition.get("kind"),  # type: ignore[arg-type]
            graph_fragment_node_ids=all_node_ids,
            graph_fragment_edge_ids=all_edge_ids,
            semantic_label=merged_definition.get("label", "Merged Mapping"),
            description=merged_definition.get("description", ""),
            confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
            status="merged",
            reviewed_by=reviewer,
            reviewed_at=datetime.now(UTC),
        )

        self.mappings[merged_id] = merged

        # Mark originals as merged
        for mid in mapping_ids:
            self.mappings[mid].status = "merged"
            self.mappings[mid].reviewed_by = reviewer
            self.mappings[mid].reviewed_at = datetime.now(UTC)

        self._log_review("merge", ",".join(mapping_ids), reviewer, {"merged_id": merged_id})
        return merged_id

    def get_mapping_for_review(self, mapping_id: str) -> SemanticMapping | None:
        """Get a mapping for review.

        Args:
            mapping_id: ID of mapping.

        Returns:
            Mapping if found, None otherwise.
        """
        return self.mappings.get(mapping_id)

    def get_mappings_by_status(self, status: str) -> list[SemanticMapping]:
        """Get all mappings with a specific status.

        Args:
            status: Status to filter by.

        Returns:
            List of mappings with that status.
        """
        return [m for m in self.mappings.values() if m.status == status]

    def get_unreviewed_mappings(self) -> list[SemanticMapping]:
        """Get all mappings that haven't been reviewed.

        Returns:
            List of unreviewed mappings.
        """
        return [m for m in self.mappings.values() if m.status == "auto_proposed"]

    def get_review_summary(self) -> dict[str, Any]:
        """Get a summary of review status.

        Returns:
            Dictionary with review statistics.
        """
        statuses: dict[str, int] = {}
        for mapping in self.mappings.values():
            status = mapping.status
            statuses[status] = statuses.get(status, 0) + 1

        return {
            "total_mappings": len(self.mappings),
            "by_status": statuses,
            "unreviewed_count": len(self.get_unreviewed_mappings()),
            "total_review_actions": len(self.review_history),
        }

    def _log_review(self, action: str, mapping_id: str, reviewer: str, detail: Any) -> None:
        """Log a review action.

        Args:
            action: Type of review action.
            mapping_id: ID of affected mapping.
            reviewer: Name of reviewer.
            detail: Action details.
        """
        self.review_history.append(
            {
                "timestamp": datetime.now(UTC),
                "action": action,
                "mapping_id": mapping_id,
                "reviewer": reviewer,
                "detail": detail,
            }
        )

    def get_review_history(self) -> list[dict[str, Any]]:
        """Get the complete review history.

        Returns:
            List of review events.
        """
        return self.review_history.copy()

    def export_reviewed_mappings(self) -> list[SemanticMapping]:
        """Export all mappings that have been accepted or edited by reviewers.

        Returns:
            List of reviewed and approved mappings.
        """
        return [m for m in self.mappings.values() if m.status in ("accepted", "edited", "merged")]

__init__()

Initialize the review manager.

Source code in py/cogant/translate/review.py
16
17
18
19
def __init__(self) -> None:
    """Initialize the review manager."""
    self.mappings: dict[str, SemanticMapping] = {}
    self.review_history: list[dict[str, Any]] = []

accept_mapping(mapping_id, reviewer, feedback=None)

Accept a mapping as valid.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to accept.

required
reviewer str

Name of reviewer.

required
feedback str | None

Optional review feedback.

None

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def accept_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    feedback: str | None = None,
) -> bool:
    """Accept a mapping as valid.

    Args:
        mapping_id: ID of mapping to accept.
        reviewer: Name of reviewer.
        feedback: Optional review feedback.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    mapping.status = "accepted"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)
    mapping.review_feedback = feedback

    # Upgrade confidence tier if human reviewed
    if mapping.confidence_tier != ConfidenceTier.HUMAN_REVIEWED:
        mapping.confidence_tier = ConfidenceTier.HUMAN_REVIEWED
        mapping.confidence_score = min(1.0, mapping.confidence_score + 0.15)

    self._log_review("accept", mapping_id, reviewer, feedback)
    return True

add_mapping(mapping)

Add a mapping for potential review.

Parameters:

Name Type Description Default
mapping SemanticMapping

Mapping to add.

required
Source code in py/cogant/translate/review.py
21
22
23
24
25
26
27
def add_mapping(self, mapping: SemanticMapping) -> None:
    """Add a mapping for potential review.

    Args:
        mapping: Mapping to add.
    """
    self.mappings[mapping.id] = mapping

edit_mapping(mapping_id, reviewer, updates)

Edit a mapping based on review feedback.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to edit.

required
reviewer str

Name of reviewer.

required
updates dict[str, Any]

Dictionary of fields to update.

required

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def edit_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    updates: dict[str, Any],
) -> bool:
    """Edit a mapping based on review feedback.

    Args:
        mapping_id: ID of mapping to edit.
        reviewer: Name of reviewer.
        updates: Dictionary of fields to update.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    old_values = {}

    # Apply updates
    for key, value in updates.items():
        if hasattr(mapping, key):
            old_values[key] = getattr(mapping, key)
            setattr(mapping, key, value)

    mapping.status = "edited"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)

    self._log_review(
        "edit", mapping_id, reviewer, {"old_values": old_values, "new_values": updates}
    )
    return True

export_reviewed_mappings()

Export all mappings that have been accepted or edited by reviewers.

Returns:

Type Description
list[SemanticMapping]

List of reviewed and approved mappings.

Source code in py/cogant/translate/review.py
312
313
314
315
316
317
318
def export_reviewed_mappings(self) -> list[SemanticMapping]:
    """Export all mappings that have been accepted or edited by reviewers.

    Returns:
        List of reviewed and approved mappings.
    """
    return [m for m in self.mappings.values() if m.status in ("accepted", "edited", "merged")]

get_mapping_for_review(mapping_id)

Get a mapping for review.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping.

required

Returns:

Type Description
SemanticMapping | None

Mapping if found, None otherwise.

Source code in py/cogant/translate/review.py
237
238
239
240
241
242
243
244
245
246
def get_mapping_for_review(self, mapping_id: str) -> SemanticMapping | None:
    """Get a mapping for review.

    Args:
        mapping_id: ID of mapping.

    Returns:
        Mapping if found, None otherwise.
    """
    return self.mappings.get(mapping_id)

get_mappings_by_status(status)

Get all mappings with a specific status.

Parameters:

Name Type Description Default
status str

Status to filter by.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings with that status.

Source code in py/cogant/translate/review.py
248
249
250
251
252
253
254
255
256
257
def get_mappings_by_status(self, status: str) -> list[SemanticMapping]:
    """Get all mappings with a specific status.

    Args:
        status: Status to filter by.

    Returns:
        List of mappings with that status.
    """
    return [m for m in self.mappings.values() if m.status == status]

get_review_history()

Get the complete review history.

Returns:

Type Description
list[dict[str, Any]]

List of review events.

Source code in py/cogant/translate/review.py
304
305
306
307
308
309
310
def get_review_history(self) -> list[dict[str, Any]]:
    """Get the complete review history.

    Returns:
        List of review events.
    """
    return self.review_history.copy()

get_review_summary()

Get a summary of review status.

Returns:

Type Description
dict[str, Any]

Dictionary with review statistics.

Source code in py/cogant/translate/review.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_review_summary(self) -> dict[str, Any]:
    """Get a summary of review status.

    Returns:
        Dictionary with review statistics.
    """
    statuses: dict[str, int] = {}
    for mapping in self.mappings.values():
        status = mapping.status
        statuses[status] = statuses.get(status, 0) + 1

    return {
        "total_mappings": len(self.mappings),
        "by_status": statuses,
        "unreviewed_count": len(self.get_unreviewed_mappings()),
        "total_review_actions": len(self.review_history),
    }

get_unreviewed_mappings()

Get all mappings that haven't been reviewed.

Returns:

Type Description
list[SemanticMapping]

List of unreviewed mappings.

Source code in py/cogant/translate/review.py
259
260
261
262
263
264
265
def get_unreviewed_mappings(self) -> list[SemanticMapping]:
    """Get all mappings that haven't been reviewed.

    Returns:
        List of unreviewed mappings.
    """
    return [m for m in self.mappings.values() if m.status == "auto_proposed"]

merge_mappings(mapping_ids, reviewer, merged_definition)

Merge multiple mappings into one.

Parameters:

Name Type Description Default
mapping_ids list[str]

IDs of mappings to merge.

required
reviewer str

Name of reviewer.

required
merged_definition dict[str, Any]

Definition of merged mapping.

required

Returns:

Type Description
str | None

ID of new merged mapping, or None if invalid.

Source code in py/cogant/translate/review.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def merge_mappings(
    self,
    mapping_ids: list[str],
    reviewer: str,
    merged_definition: dict[str, Any],
) -> str | None:
    """Merge multiple mappings into one.

    Args:
        mapping_ids: IDs of mappings to merge.
        reviewer: Name of reviewer.
        merged_definition: Definition of merged mapping.

    Returns:
        ID of new merged mapping, or None if invalid.
    """
    # Verify all mappings exist
    for mid in mapping_ids:
        if mid not in self.mappings:
            return None

    # Create merged mapping
    merged_id = f"merged_{'_'.join(m[:8] for m in mapping_ids)}"

    # Collect all node and edge IDs
    all_node_ids = []
    all_edge_ids = []
    for mid in mapping_ids:
        mapping = self.mappings[mid]
        all_node_ids.extend(mapping.graph_fragment_node_ids)
        all_edge_ids.extend(mapping.graph_fragment_edge_ids)

    # Deduplicate
    all_node_ids = list(set(all_node_ids))
    all_edge_ids = list(set(all_edge_ids))

    merged = SemanticMapping(
        id=merged_id,
        kind=merged_definition.get("kind"),  # type: ignore[arg-type]
        graph_fragment_node_ids=all_node_ids,
        graph_fragment_edge_ids=all_edge_ids,
        semantic_label=merged_definition.get("label", "Merged Mapping"),
        description=merged_definition.get("description", ""),
        confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
        status="merged",
        reviewed_by=reviewer,
        reviewed_at=datetime.now(UTC),
    )

    self.mappings[merged_id] = merged

    # Mark originals as merged
    for mid in mapping_ids:
        self.mappings[mid].status = "merged"
        self.mappings[mid].reviewed_by = reviewer
        self.mappings[mid].reviewed_at = datetime.now(UTC)

    self._log_review("merge", ",".join(mapping_ids), reviewer, {"merged_id": merged_id})
    return merged_id

reject_mapping(mapping_id, reviewer, reason)

Reject a mapping as invalid.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to reject.

required
reviewer str

Name of reviewer.

required
reason str

Reason for rejection.

required

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def reject_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    reason: str,
) -> bool:
    """Reject a mapping as invalid.

    Args:
        mapping_id: ID of mapping to reject.
        reviewer: Name of reviewer.
        reason: Reason for rejection.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    mapping.status = "rejected"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)
    mapping.review_feedback = reason
    mapping.confidence_score = 0.0

    self._log_review("reject", mapping_id, reviewer, reason)
    return True

split_mapping(mapping_id, reviewer, split_definitions)

Split a mapping into multiple mappings.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to split.

required
reviewer str

Name of reviewer.

required
split_definitions list[dict[str, Any]]

List of definitions for new mappings.

required

Returns:

Type Description
list[str]

List of IDs of new mappings.

Source code in py/cogant/translate/review.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def split_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    split_definitions: list[dict[str, Any]],
) -> list[str]:
    """Split a mapping into multiple mappings.

    Args:
        mapping_id: ID of mapping to split.
        reviewer: Name of reviewer.
        split_definitions: List of definitions for new mappings.

    Returns:
        List of IDs of new mappings.
    """
    if mapping_id not in self.mappings:
        return []

    original = self.mappings[mapping_id]
    new_ids = []

    for i, definition in enumerate(split_definitions):
        new_id = f"{mapping_id}_split_{i}"

        new_mapping = SemanticMapping(
            id=new_id,
            kind=definition.get("kind", original.kind),
            graph_fragment_node_ids=definition.get("node_ids", []),
            graph_fragment_edge_ids=definition.get("edge_ids", []),
            semantic_label=definition.get("label", original.semantic_label),
            description=definition.get("description", original.description),
            confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
            status="edited",
            reviewed_by=reviewer,
            reviewed_at=datetime.now(UTC),
        )

        self.mappings[new_id] = new_mapping
        new_ids.append(new_id)

    # Mark original as split
    original.status = "split"
    original.reviewed_by = reviewer
    original.reviewed_at = datetime.now(UTC)

    self._log_review("split", mapping_id, reviewer, {"new_mappings": new_ids})
    return new_ids

RuleExplanation dataclass

Explanation of why a translation rule did or did not fire on a node.

Produced by :meth:TranslationRule.explain during the cogant explain workflow. Each instance records a single (rule, node) decision: the rule's name and priority, whether it fired, a short human-readable reason, and the list of concrete evidence snippets (edge kinds, keyword matches, qualified identifiers) that backed the decision.

The dataclass is deliberately JSON-serialization friendly via :meth:to_dict so the explain CLI can emit either a rich text report or a machine-readable JSON blob without duplicating the payload logic.

Attributes:

Name Type Description
rule_name str

Stable rule identifier (rule.name).

priority int

Rule priority tier (higher fires first).

fired bool

True when the rule actually produced a mapping for this node, False when it was considered but skipped.

reason str

One-line explanation of the decision.

evidence list[str]

Concrete evidence strings collected during matching (e.g. "WRITES self.display", "keyword match: 'set'").

mapping_kind str | None

Semantic kind the rule would have produced, or None when the rule did not fire.

confidence float

Confidence score (0.0–1.0) if rule fired, 0.0 if not fired.

contradictions list[str]

List of contradictory evidence or rule conflicts that might lower confidence in this mapping.

Source code in py/cogant/translate/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass
class RuleExplanation:
    """Explanation of why a translation rule did or did not fire on a node.

    Produced by :meth:`TranslationRule.explain` during the
    ``cogant explain`` workflow. Each instance records a single
    (rule, node) decision: the rule's name and priority, whether it
    fired, a short human-readable reason, and the list of concrete
    evidence snippets (edge kinds, keyword matches, qualified
    identifiers) that backed the decision.

    The dataclass is deliberately JSON-serialization friendly via
    :meth:`to_dict` so the explain CLI can emit either a rich text
    report or a machine-readable JSON blob without duplicating the
    payload logic.

    Attributes:
        rule_name: Stable rule identifier (``rule.name``).
        priority: Rule priority tier (higher fires first).
        fired: True when the rule actually produced a mapping for this
            node, False when it was considered but skipped.
        reason: One-line explanation of the decision.
        evidence: Concrete evidence strings collected during matching
            (e.g. ``"WRITES self.display"``, ``"keyword match: 'set'"``).
        mapping_kind: Semantic kind the rule would have produced, or
            None when the rule did not fire.
        confidence: Confidence score (0.0–1.0) if rule fired, 0.0 if not fired.
        contradictions: List of contradictory evidence or rule conflicts that
            might lower confidence in this mapping.
    """

    rule_name: str
    priority: int
    fired: bool
    reason: str
    evidence: list[str] = field(default_factory=list)
    mapping_kind: str | None = None
    confidence: float = 0.0
    contradictions: list[str] = field(default_factory=list)

    def to_dict(self) -> dict[str, Any]:
        """Serialize to a plain JSON-ready dict."""
        return dataclasses.asdict(self)

to_dict()

Serialize to a plain JSON-ready dict.

Source code in py/cogant/translate/engine.py
60
61
62
def to_dict(self) -> dict[str, Any]:
    """Serialize to a plain JSON-ready dict."""
    return dataclasses.asdict(self)

SingletonAccessRule

Bases: TranslationRule

Maps singleton/global state access to context modality.

Detects variables or classes that are read by many different modules (high in-degree of READS edges from diverse paths). Threshold: 3+ readers from different modules.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.65). Lowest band (0.65) — the lowest confidence score in the entire rule family. Rationale: "accessed by many modules" is a very weak signal (logging facilities, common types, and enum constants all trigger it), so this rule is explicitly the last to win in any conflict. Thresholds: read_edges >= 3 and len(reader_modules) >= 3. The module-diversity check prevents the rule from firing on intra-module utilities. TODO(calibration): if the false-positive rate on the 20-repo corpus exceeds 30%, raise the module-diversity threshold to 5 or combine with a "not in typing/stdlib whitelist" filter.

Source code in py/cogant/translate/rules/resilience.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
class SingletonAccessRule(TranslationRule):
    """Maps singleton/global state access to context modality.

    Detects variables or classes that are read by many different modules
    (high in-degree of READS edges from diverse paths). Threshold: 3+ readers
    from different modules.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.65)``. **Lowest band** (0.65) —
        the lowest confidence score in the entire rule family.
        Rationale: "accessed by many modules" is a very weak signal
        (logging facilities, common types, and enum constants all
        trigger it), so this rule is explicitly the last to win in
        any conflict. Thresholds: ``read_edges >= 3`` and
        ``len(reader_modules) >= 3``. The module-diversity check
        prevents the rule from firing on intra-module utilities.
        TODO(calibration): if the false-positive rate on the
        20-repo corpus exceeds 30%, raise the module-diversity
        threshold to 5 or combine with a "not in typing/stdlib
        whitelist" filter.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with high in-degree READS from diverse modules.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched singleton/global state nodes.
        """
        matches = []

        # Check variables and classes as potential singletons
        variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for node in variables + classes:
            # Find incoming READS edges
            incoming = graph.get_edges_to(node.id)
            read_edges = [e for e in incoming if e.kind == EdgeKind.READS]

            # Read-count threshold = 3. Principled default: below 3
            # readers is indistinguishable from ordinary 2-caller
            # helper code. TODO(calibration): sweep {3, 5, 8} on
            # 20-repo corpus; consider combining with a "stdlib/
            # typing whitelist" filter to cut false positives.
            if len(read_edges) < 3:
                continue

            # Check diversity: count unique module paths among readers
            reader_modules = set()
            reader_ids = []
            for edge in read_edges:
                reader = graph.get_node(edge.source_id)
                if reader and reader.path:
                    # Extract module path (directory portion)
                    parts = reader.path.rsplit("/", 1)
                    module_path = parts[0] if len(parts) > 1 else reader.path
                    reader_modules.add(module_path)
                reader_ids.append(edge.source_id)

            # Module-diversity threshold = 3. Principled default:
            # fewer than 3 distinct module paths in the reader set
            # typically indicates an intra-package helper rather
            # than a true singleton/global. Matches the read-count
            # threshold for symmetry. TODO(calibration): sweep {3,
            # 5, 8} in tandem with the read-count sweep.
            if len(reader_modules) >= 3:
                matches.append(
                    {
                        "node_id": node.id,
                        "reader_ids": reader_ids,
                        "reader_count": len(read_edges),
                        "module_count": len(reader_modules),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping for singleton/global state node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"single_{node_id}_{hashlib.sha256(b'singleton_access').hexdigest()[:8]}"

        # Confidence 0.65 — principled default (LOWEST band in the
        # entire rule family). "Accessed by many modules" is a very
        # weak semantic signal; this rule is explicitly the last to
        # win in any conflict. 0.65 = STATIC_PLUS_RUNTIME_THRESHOLD
        # exactly, so this rule's mapping is *only* promoted past
        # the "trust without review" bar if runtime evidence
        # corroborates it.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id] + match.get("reader_ids", []),
            semantic_label=f"{node.name} - Singleton/Global State",
            description=f"{'Variable' if node.kind == NodeKind.VARIABLE else 'Class'} '{node.name}' is accessed by {match['reader_count']} readers across {match['module_count']} modules",
            confidence_score=0.65,  # principled default (LOWEST in family)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.65,
                    metadata={
                        "reader_count": match["reader_count"],
                        "module_count": match["module_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.7,  # cross-module READS noise
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "singleton_access"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping for singleton/global state node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/resilience.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping for singleton/global state node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"single_{node_id}_{hashlib.sha256(b'singleton_access').hexdigest()[:8]}"

    # Confidence 0.65 — principled default (LOWEST band in the
    # entire rule family). "Accessed by many modules" is a very
    # weak semantic signal; this rule is explicitly the last to
    # win in any conflict. 0.65 = STATIC_PLUS_RUNTIME_THRESHOLD
    # exactly, so this rule's mapping is *only* promoted past
    # the "trust without review" bar if runtime evidence
    # corroborates it.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id] + match.get("reader_ids", []),
        semantic_label=f"{node.name} - Singleton/Global State",
        description=f"{'Variable' if node.kind == NodeKind.VARIABLE else 'Class'} '{node.name}' is accessed by {match['reader_count']} readers across {match['module_count']} modules",
        confidence_score=0.65,  # principled default (LOWEST in family)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.65,
                metadata={
                    "reader_count": match["reader_count"],
                    "module_count": match["module_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.7,  # cross-module READS noise
    )

matches(graph, query)

Find nodes with high in-degree READS from diverse modules.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched singleton/global state nodes.

Source code in py/cogant/translate/rules/resilience.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with high in-degree READS from diverse modules.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched singleton/global state nodes.
    """
    matches = []

    # Check variables and classes as potential singletons
    variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for node in variables + classes:
        # Find incoming READS edges
        incoming = graph.get_edges_to(node.id)
        read_edges = [e for e in incoming if e.kind == EdgeKind.READS]

        # Read-count threshold = 3. Principled default: below 3
        # readers is indistinguishable from ordinary 2-caller
        # helper code. TODO(calibration): sweep {3, 5, 8} on
        # 20-repo corpus; consider combining with a "stdlib/
        # typing whitelist" filter to cut false positives.
        if len(read_edges) < 3:
            continue

        # Check diversity: count unique module paths among readers
        reader_modules = set()
        reader_ids = []
        for edge in read_edges:
            reader = graph.get_node(edge.source_id)
            if reader and reader.path:
                # Extract module path (directory portion)
                parts = reader.path.rsplit("/", 1)
                module_path = parts[0] if len(parts) > 1 else reader.path
                reader_modules.add(module_path)
            reader_ids.append(edge.source_id)

        # Module-diversity threshold = 3. Principled default:
        # fewer than 3 distinct module paths in the reader set
        # typically indicates an intra-package helper rather
        # than a true singleton/global. Matches the read-count
        # threshold for symmetry. TODO(calibration): sweep {3,
        # 5, 8} in tandem with the read-count sweep.
        if len(reader_modules) >= 3:
            matches.append(
                {
                    "node_id": node.id,
                    "reader_ids": reader_ids,
                    "reader_count": len(read_edges),
                    "module_count": len(reader_modules),
                }
            )

    return matches

TestAssertionRule

Bases: TranslationRule

Maps test assertions to preference/constraint modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with PreferenceRule and the keyword branch of ObservationRule. Rationale: a function with "test" in its name plus at least one CALLS edge (proxy for assertion) is one of the most reliable static signals in the entire rule family — pytest/unittest conventions are nearly universal. Parser certainty 0.95 is the highest in the family because both the name match and the call extraction are handled by the native Python AST with minimal ambiguity.

Source code in py/cogant/translate/rules/behavioral.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class TestAssertionRule(TranslationRule):
    """Maps test assertions to preference/constraint modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85), tied
        with ``PreferenceRule`` and the keyword branch of
        ``ObservationRule``. Rationale: a function with "test" in its
        name plus at least one ``CALLS`` edge (proxy for assertion)
        is one of the most reliable static signals in the entire
        rule family — pytest/unittest conventions are nearly
        universal. Parser certainty 0.95 is the *highest* in the
        family because both the name match and the call extraction
        are handled by the native Python AST with minimal ambiguity.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find test nodes and assertion calls.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched test nodes.
        """
        matches = []

        # Find test functions
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        for func in functions:
            # Check if test function (name contains "test")
            if "test" not in func.name.lower():
                continue

            # Find assertion calls
            out_edges = graph.get_edges_from(func.id)
            assertion_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

            if assertion_edges:
                matches.append(
                    {
                        "node_id": func.id,
                        "assertion_count": len(assertion_edges),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create constraint mapping from test assertions.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for constraint.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"const_{node_id}_{hashlib.sha256(b'test_assertion').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). Parser
        # certainty 0.95 is the highest in the rule family because
        # "test"-prefix names and call extraction are both native
        # Python AST operations with near-zero ambiguity.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONSTRAINT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Test Constraint",
            description=f"Test function '{node.name}' defines system constraints",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                    metadata={"assertion_count": match["assertion_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.95,  # highest in family (pytest/unittest conventions)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "test_assertion"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONSTRAINT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create constraint mapping from test assertions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for constraint.

Source code in py/cogant/translate/rules/behavioral.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create constraint mapping from test assertions.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for constraint.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"const_{node_id}_{hashlib.sha256(b'test_assertion').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). Parser
    # certainty 0.95 is the highest in the rule family because
    # "test"-prefix names and call extraction are both native
    # Python AST operations with near-zero ambiguity.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONSTRAINT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Test Constraint",
        description=f"Test function '{node.name}' defines system constraints",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
                metadata={"assertion_count": match["assertion_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.95,  # highest in family (pytest/unittest conventions)
    )

matches(graph, query)

Find test nodes and assertion calls.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched test nodes.

Source code in py/cogant/translate/rules/behavioral.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find test nodes and assertion calls.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched test nodes.
    """
    matches = []

    # Find test functions
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    for func in functions:
        # Check if test function (name contains "test")
        if "test" not in func.name.lower():
            continue

        # Find assertion calls
        out_edges = graph.get_edges_from(func.id)
        assertion_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        if assertion_edges:
            matches.append(
                {
                    "node_id": func.id,
                    "assertion_count": len(assertion_edges),
                }
            )

    return matches

TranslationEngine

Orchestrates translation of program graphs to semantic concepts.

Applies the registered translation rules with iterative rule application plus an idempotent confirmation pass. Rules do not consume prior mappings (TranslationRule.apply only receives the graph and a single match), so a true semantic fixpoint is NOT performed: the first pass produces every mapping the rules can produce, and the second pass exists solely to confirm idempotence (no new mappings) before conflict resolution. max_iterations bounds the loop as a safety margin only. Resolves conflicts when multiple mappings target overlapping node sets.

Source code in py/cogant/translate/engine.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
class TranslationEngine:
    """Orchestrates translation of program graphs to semantic concepts.

    Applies the registered translation rules with iterative rule
    application plus an idempotent confirmation pass. Rules do not consume
    prior mappings (``TranslationRule.apply`` only receives the graph and
    a single match), so a true semantic fixpoint is NOT performed: the
    first pass produces every mapping the rules can produce, and the
    second pass exists solely to confirm idempotence (no new mappings)
    before conflict resolution. ``max_iterations`` bounds the loop as a
    safety margin only. Resolves conflicts when multiple mappings target
    overlapping node sets.
    """

    def __init__(self, max_iterations: int = 10):
        """Initialize the translation engine.

        Args:
            max_iterations: Maximum rule-application passes (default 10).

        Rationale for default ``max_iterations=10``:
            Because rules do not consume prior mappings, the second pass
            never produces new mappings; in practice the loop exits after
            the first pass plus one idempotent confirmation pass (<=2
            passes) on control-positive fixtures and typical corpora. 10
            is a generous safety margin, not an expected iteration count.
            See ``docs/evaluation/CALIBRATION.md``.
        """
        self.rules: list[TranslationRule] = []
        self.mappings: dict[str, SemanticMapping] = {}
        self._match_log: list[dict[str, Any]] = []
        self._rule_priority: dict[str, int] = {}
        self.max_iterations = max_iterations
        self.iterations: list[dict[str, Any]] = []
        self._convergence_iteration: int | None = None

    def register_rule(self, rule: TranslationRule) -> None:
        """Register a translation rule.

        Args:
            rule: Rule to register.
        """
        self.rules.append(rule)

    def translate(
        self,
        graph: ProgramGraph,
        rule_filter: list[str] | None = None,
    ) -> list[SemanticMapping]:
        """Translate a program graph using iterative rule application.

        Rules are applied in repeated passes until a pass produces no new
        mappings or ``max_iterations`` is reached, whichever comes first.
        Because rules do not consume prior mappings, this is single-pass
        rule application followed by one idempotent confirmation pass
        (the second pass re-runs the rules and is expected to add nothing)
        — it is NOT a semantic fixpoint. After the loop exits, conflict
        resolution picks a single winning mapping per node set using
        priority then confidence as the tiebreaker.

        Args:
            graph: Program graph to translate. Must have been built by
                the graph stage; in particular, ``GraphQuery`` must be
                constructable from it.
            rule_filter: Optional list of rule names to apply. ``None``
                (default) applies every registered rule. Pass a subset
                to run a targeted translation, e.g. for unit tests or
                the ``cogant explain`` single-node path.

        Returns:
            List of ``SemanticMapping`` instances kept after conflict
            resolution, in insertion order. May be empty if no rule
            matched.

        Raises:
            RuntimeError: If a registered rule raises an unhandled
                exception. The engine catches and logs per-rule errors
                but re-raises engine-level invariant violations.

        Example:
            >>> engine = TranslationEngine()
            >>> engine.register_rule(ObservationRule())
            >>> mappings = engine.translate(graph)
            >>> all(hasattr(m.kind, "name") for m in mappings)
            True
        """
        self.mappings.clear()
        self._match_log.clear()
        self._rule_priority.clear()
        self._convergence_iteration = None
        self.iterations = []

        n_nodes = len(graph.nodes)
        n_edges = len(graph.edges)
        active_rules = (
            [r for r in self.rules if r.name in rule_filter] if rule_filter else self.rules
        )
        logger.info(
            "Starting translation: %d rules active, %d nodes, %d edges%s",
            len(active_rules),
            n_nodes,
            n_edges,
            f" (filtered to {rule_filter})" if rule_filter else "",
        )

        query = GraphQuery(graph)

        for iteration in range(1, self.max_iterations + 1):
            logger.debug(
                "Translation pass %d starting (%d existing mappings)",
                iteration,
                len(self.mappings),
            )

            new_mappings_this_pass = self._apply_single_pass(
                graph, query, rule_filter=rule_filter, iteration=iteration
            )

            self.iterations.append(
                {
                    "iteration": iteration,
                    "new_mappings": new_mappings_this_pass,
                    "mappings_added": new_mappings_this_pass,
                }
            )

            self._log_match(
                "iteration_complete",
                "engine",
                f"iteration={iteration} new_mappings={new_mappings_this_pass}",
            )
            logger.info("Translation pass %d: %d new mappings", iteration, new_mappings_this_pass)

            if new_mappings_this_pass == 0:
                logger.info(
                    "Idempotence confirmed (no new mappings) after %d pass(es); "
                    "not a semantic fixpoint",
                    iteration,
                )
                self._convergence_iteration = iteration
                break
        else:
            logger.warning(
                "Max passes (%d) reached without an idempotent (zero-new-mapping) pass",
                self.max_iterations,
            )

        # Resolve conflicts among overlapping mappings
        conflicts_before = len(self.mappings)
        self._resolve_conflicts()
        conflicts_removed = conflicts_before - len(self.mappings)
        if conflicts_removed > 0:
            logger.info(
                "Conflict resolution: removed %d overlapping mappings (%d → %d)",
                conflicts_removed,
                conflicts_before,
                len(self.mappings),
            )

        # Log per-kind role distribution
        by_kind: dict[str, int] = {}
        for mapping in self.mappings.values():
            kind = mapping.kind.value
            by_kind[kind] = by_kind.get(kind, 0) + 1
        logger.info(
            "Translation complete: %d mappings across %d roles%s",
            len(self.mappings),
            len(by_kind),
            f" ({', '.join(f'{k}={v}' for k, v in sorted(by_kind.items()))})" if by_kind else "",
        )

        # Log coverage summary
        coverage = self.get_coverage_report(graph)
        logger.info(
            "Node coverage: %.1f%% (%d/%d covered, %d uncovered)",
            coverage["coverage_percent"],
            coverage["covered_nodes"],
            coverage["total_nodes"],
            coverage["uncovered_nodes"],
        )

        return list(self.mappings.values())

    def _apply_single_pass(
        self,
        graph: ProgramGraph,
        query: GraphQuery,
        rule_filter: list[str] | None = None,
        iteration: int = 0,
    ) -> int:
        """Apply all rules once, sorted by priority. Returns count of new mappings created.

        Args:
            graph: Program graph to translate.
            query: Graph query engine bound to ``graph``.
            rule_filter: Optional list of rule names to restrict application.
            iteration: Current translation-pass number (for logging context).

        Returns:
            Number of new mappings created during this pass.
        """
        new_mappings = 0
        sorted_rules = sorted(self.rules, key=lambda r: r.priority, reverse=True)
        per_rule_counts: dict[str, int] = {}
        per_rule_errors: dict[str, int] = {}

        for rule in sorted_rules:
            # Skip if filtered out
            if rule_filter and rule.name not in rule_filter:
                continue

            rule_new = 0
            rule_errors = 0

            # Find matches
            try:
                matches = rule.matches(graph, query)
            except (TypeError, ValueError, KeyError, AttributeError) as e:
                logger.warning(
                    "Rule %r failed during matching (iteration=%d): %s",
                    rule.name,
                    iteration,
                    e,
                )
                self._log_match(
                    "rule_error",
                    rule.name,
                    f"iteration={iteration} error={e}",
                )
                rule_errors += 1
                per_rule_counts[rule.name] = 0
                per_rule_errors[rule.name] = rule_errors
                continue

            # Apply rule to each match
            for match in matches:
                try:
                    mapping = rule.apply(graph, match)
                    if mapping and mapping.id not in self.mappings:
                        mapping.metadata.setdefault("rule_id", rule.name)
                        mapping.metadata.setdefault("rule_priority", rule.priority)
                        mapping.metadata.setdefault("match", match)
                        mapping.metadata.setdefault("iteration", iteration)
                        self.mappings[mapping.id] = mapping
                        self._rule_priority[mapping.id] = rule.priority
                        self._log_match("mapping_created", rule.name, mapping.id)
                        new_mappings += 1
                        rule_new += 1
                except (TypeError, ValueError, KeyError, AttributeError) as e:
                    logger.warning(
                        "Rule %r failed during apply (iteration=%d, match=%r): %s",
                        rule.name,
                        iteration,
                        match,
                        e,
                    )
                    self._log_match(
                        "apply_error",
                        rule.name,
                        f"iteration={iteration} match={match} error={e}",
                    )
                    rule_errors += 1

            per_rule_counts[rule.name] = rule_new
            if rule_errors:
                per_rule_errors[rule.name] = rule_errors

            if rule_new > 0 or rule_errors > 0:
                logger.debug(
                    "Rule %r: %d new mappings, %d errors (iteration=%d, priority=%d, family=%s)",
                    rule.name,
                    rule_new,
                    rule_errors,
                    iteration,
                    rule.priority,
                    rule.mapping_kind.value,
                )

        # Log per-rule summary for this pass when there are new mappings
        if new_mappings > 0:
            active = ", ".join(
                f"{name}={cnt}"
                for name, cnt in sorted(per_rule_counts.items(), key=lambda kv: -kv[1])
                if cnt > 0
            )
            logger.debug(
                "Pass %d rule breakdown: %d new total [%s]",
                iteration,
                new_mappings,
                active,
            )
            if per_rule_errors:
                err_summary = ", ".join(f"{name}={cnt}" for name, cnt in per_rule_errors.items())
                logger.debug("Pass %d rule errors: [%s]", iteration, err_summary)

        return new_mappings

    def translate_with_confidence(
        self,
        graph: ProgramGraph,
        rule_filter: list[str] | None = None,
    ) -> list[SemanticMapping]:
        """Translate and rescore all mappings using the ConfidenceModel.

        Runs the standard iterative-pass translation, then applies the
        ConfidenceModel to update confidence scores, tiers, and
        conflict penalties on every resulting mapping.

        Args:
            graph: Program graph to translate.
            rule_filter: Optional list of rule names to apply (None = all).

        Returns:
            List of semantic mappings with updated confidence scores.
        """
        mappings = self.translate(graph, rule_filter=rule_filter)

        model = ConfidenceModel()
        model.score_batch(mappings)

        # Re-resolve conflicts now that scores are updated
        self._resolve_conflicts()

        return list(self.mappings.values())

    def _resolve_conflicts(self) -> None:
        """Resolve conflicts when multiple mappings target overlapping node sets.

        Uses a node-to-mappings inverted index so conflict detection is
        O(total_node_references) rather than O(n_mappings^2). For each
        colliding pair, the loser is chosen by comparing
        ``(rule_priority, confidence_score)`` tuples (higher wins), with
        the confidence score acting as a tiebreaker when priorities are
        equal.
        """
        # Build inverted index: node_id -> list of mapping IDs touching it.
        node_to_mappings: dict[str, list[str]] = {}
        for mapping in self.mappings.values():
            for node_id in mapping.graph_fragment_node_ids:
                node_to_mappings.setdefault(node_id, []).append(mapping.id)

        # Collect unique colliding pairs via the inverted index.
        conflict_pairs: set[tuple[str, str]] = set()
        for mids in node_to_mappings.values():
            if len(mids) < 2:
                continue
            for i in range(len(mids)):
                for j in range(i + 1, len(mids)):
                    a, b = mids[i], mids[j]
                    conflict_pairs.add((a, b) if a < b else (b, a))

        to_remove: set[str] = set()
        # Sets have undefined iteration order; use sorted pair order so
        # conflict resolution is deterministic for identical inputs (benchmarks
        # vs generate_figures, CI vs local).
        for a_id, b_id in sorted(conflict_pairs):
            if a_id in to_remove or b_id in to_remove:
                continue
            mapping_a = self.mappings.get(a_id)
            mapping_b = self.mappings.get(b_id)
            if mapping_a is None or mapping_b is None:
                continue
            pri_a = self._rule_priority.get(a_id, 0)
            pri_b = self._rule_priority.get(b_id, 0)
            key_a = (pri_a, mapping_a.confidence_score)
            key_b = (pri_b, mapping_b.confidence_score)
            if key_a >= key_b:
                loser, winner = mapping_b, mapping_a
            else:
                loser, winner = mapping_a, mapping_b
            to_remove.add(loser.id)
            overlap = set(mapping_a.graph_fragment_node_ids) & set(
                mapping_b.graph_fragment_node_ids
            )
            winner.metadata.setdefault("conflict_resolution", []).append(
                {
                    "kept": winner.id,
                    "removed": loser.id,
                    "overlap_node_ids": sorted(overlap),
                    "winner_priority": self._rule_priority.get(winner.id, 0),
                    "loser_priority": self._rule_priority.get(loser.id, 0),
                    "winner_confidence": winner.confidence_score,
                    "loser_confidence": loser.confidence_score,
                }
            )
            loser.metadata["conflict_resolution_status"] = "removed"
            self._log_match(
                "conflict_resolved",
                "engine",
                f"removed={loser.id} kept={winner.id} overlap={overlap}",
            )

        for mid in to_remove:
            del self.mappings[mid]

    def get_coverage_report(self, graph: ProgramGraph) -> dict[str, Any]:
        """Report what percentage of graph nodes received at least one mapping.

        Args:
            graph: The program graph that was translated.

        Returns:
            Dictionary with coverage statistics including total nodes,
            covered nodes, uncovered node IDs, and coverage percentage.
        """
        all_node_ids = set(graph.nodes.keys())
        covered_node_ids: set[str] = set()

        for mapping in self.mappings.values():
            covered_node_ids.update(mapping.graph_fragment_node_ids)

        # Intersect with actual graph nodes (in case mappings reference out-of-sync IDs)
        covered_node_ids &= all_node_ids
        uncovered = all_node_ids - covered_node_ids

        total = len(all_node_ids)
        coverage_pct = (len(covered_node_ids) / total * 100.0) if total > 0 else 0.0

        return {
            "total_nodes": total,
            "covered_nodes": len(covered_node_ids),
            "uncovered_nodes": len(uncovered),
            "coverage_percent": round(coverage_pct, 2),
            "uncovered_node_ids": sorted(uncovered),
        }

    def get_mappings_by_kind(self, kind: MappingKind) -> list[SemanticMapping]:
        """Get all mappings of a specific kind.

        Args:
            kind: Kind of mapping to retrieve.

        Returns:
            List of matching mappings.
        """
        return [m for m in self.mappings.values() if m.kind == kind]

    def get_mappings_by_confidence(
        self,
        tier: ConfidenceTier,
    ) -> list[SemanticMapping]:
        """Get all mappings with a specific confidence tier.

        Args:
            tier: Confidence tier to filter by.

        Returns:
            List of mappings at that tier.
        """
        return [m for m in self.mappings.values() if m.confidence_tier == tier]

    def get_mapping(self, mapping_id: str) -> SemanticMapping | None:
        """Get a mapping by ID.

        Args:
            mapping_id: ID of mapping.

        Returns:
            SemanticMapping if found, None otherwise.
        """
        return self.mappings.get(mapping_id)

    def _log_match(self, event_type: str, rule_name: str, detail: str) -> None:
        """Log a match event.

        Args:
            event_type: Type of event.
            rule_name: Name of rule.
            detail: Event details.
        """
        self._match_log.append(
            {
                "event_type": event_type,
                "rule_name": rule_name,
                "detail": detail,
            }
        )

    def get_match_log(self) -> list[dict[str, Any]]:
        """Get the match log.

        Returns:
            List of match events.
        """
        return self._match_log.copy()

    def get_statistics(self) -> dict[str, Any]:
        """Get statistics about translations.

        Returns:
            Dictionary with statistics.
        """
        by_kind: dict[str, int] = {}
        for mapping in self.mappings.values():
            kind = mapping.kind.value
            by_kind[kind] = by_kind.get(kind, 0) + 1

        by_tier: dict[str, int] = {}
        for mapping in self.mappings.values():
            tier = mapping.confidence_tier.value
            by_tier[tier] = by_tier.get(tier, 0) + 1

        return {
            "total_mappings": len(self.mappings),
            "mappings_by_kind": by_kind,
            "mappings_by_confidence_tier": by_tier,
            "rules_registered": len(self.rules),
        }

    def explain(self) -> list[str]:
        """Produce human-readable explanations of which rules fired and why.

        Returns a list of formatted explanation strings describing the
        translation decisions. Each string covers one (rule, node) pair
        that was evaluated during the most recent :meth:`translate` call.
        Empty list if no translation has been run yet.

        Returns:
            List of explanation strings (one per rule evaluation).
        """
        explanations: list[str] = []

        # Group match log entries by rule
        rule_summary: dict[str, int] = {}
        for entry in self._match_log:
            rule_name = entry.get("rule_name", "unknown")
            event_type = entry.get("event_type", "")
            if event_type == "mapping_created":
                rule_summary[rule_name] = rule_summary.get(rule_name, 0) + 1

        # Build human-readable summary
        for rule_name in sorted(rule_summary.keys()):
            count = rule_summary[rule_name]
            explanations.append(f"Rule '{rule_name}' fired {count} time(s)")

        # Add convergence summary
        iteration_events = [
            e for e in self._match_log if e.get("event_type") == "iteration_complete"
        ]
        if iteration_events:
            last_event = iteration_events[-1]
            detail = last_event.get("detail", "")
            explanations.append(f"Translation-pass convergence: {detail}")

        return explanations

    def validate(self) -> list[str]:
        """Validate SemanticMappings for internal consistency.

        Checks all mappings in :attr:`mappings` for:
        - Non-empty node IDs
        - Valid confidence scores (0.0–1.0)
        - Consistent mapping kinds
        - No orphaned node references (node exists in graph)

        Returns:
            List of validation issues (empty = valid). Each string
            describes one inconsistency or violation.
        """
        issues: list[str] = []

        if not self.mappings:
            return issues  # No mappings is valid (empty graph)

        # Get all node IDs from a stored graph (if available)
        # For now, we'll validate the structure without graph reference
        for mapping_id, mapping in self.mappings.items():
            # Check non-empty node IDs
            if not mapping.graph_fragment_node_ids:
                issues.append(f"Mapping '{mapping_id}' has no node IDs in fragment")

            # Check confidence score range
            if not (0.0 <= mapping.confidence_score <= 1.0):
                issues.append(
                    f"Mapping '{mapping_id}' confidence {mapping.confidence_score} "
                    f"out of range [0.0, 1.0]"
                )

            # Check mapping kind is valid
            if not hasattr(mapping.kind, "value"):
                issues.append(f"Mapping '{mapping_id}' has invalid mapping kind")

            # Check consistency between confidence score and tier
            tier = mapping.confidence_tier.value
            score = mapping.confidence_score
            if tier == "STATIC_ONLY" and score < 0.5:
                issues.append(
                    f"Mapping '{mapping_id}' has STATIC_ONLY tier but "
                    f"confidence {score} < 0.5 (inconsistent)"
                )

        return issues

    def get_convergence_info(self) -> dict[str, Any]:
        """Get information about translation-pass convergence.

        "Converged" here means the loop reached a pass that produced no
        new mappings (idempotent confirmation pass) — it does NOT mean a
        semantic fixpoint was computed, since rules do not consume prior
        mappings. The dict keys are kept stable for callers/tests.

        Returns a dictionary with:
        - converged: Whether an idempotent (zero-new-mapping) pass was reached
        - iterations: Number of passes until idempotence (or max_iterations)
        - final_mapping_count: Number of mappings in final result

        Returns:
            Dictionary with pass-convergence metadata.
        """
        return {
            "converged": self._convergence_iteration is not None,
            "iterations": self._convergence_iteration or self.max_iterations,
            "final_mapping_count": len(self.mappings),
        }

__init__(max_iterations=10)

Initialize the translation engine.

Parameters:

Name Type Description Default
max_iterations int

Maximum rule-application passes (default 10).

10

Rationale for default max_iterations=10: Because rules do not consume prior mappings, the second pass never produces new mappings; in practice the loop exits after the first pass plus one idempotent confirmation pass (<=2 passes) on control-positive fixtures and typical corpora. 10 is a generous safety margin, not an expected iteration count. See docs/evaluation/CALIBRATION.md.

Source code in py/cogant/translate/engine.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def __init__(self, max_iterations: int = 10):
    """Initialize the translation engine.

    Args:
        max_iterations: Maximum rule-application passes (default 10).

    Rationale for default ``max_iterations=10``:
        Because rules do not consume prior mappings, the second pass
        never produces new mappings; in practice the loop exits after
        the first pass plus one idempotent confirmation pass (<=2
        passes) on control-positive fixtures and typical corpora. 10
        is a generous safety margin, not an expected iteration count.
        See ``docs/evaluation/CALIBRATION.md``.
    """
    self.rules: list[TranslationRule] = []
    self.mappings: dict[str, SemanticMapping] = {}
    self._match_log: list[dict[str, Any]] = []
    self._rule_priority: dict[str, int] = {}
    self.max_iterations = max_iterations
    self.iterations: list[dict[str, Any]] = []
    self._convergence_iteration: int | None = None

explain()

Produce human-readable explanations of which rules fired and why.

Returns a list of formatted explanation strings describing the translation decisions. Each string covers one (rule, node) pair that was evaluated during the most recent :meth:translate call. Empty list if no translation has been run yet.

Returns:

Type Description
list[str]

List of explanation strings (one per rule evaluation).

Source code in py/cogant/translate/engine.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def explain(self) -> list[str]:
    """Produce human-readable explanations of which rules fired and why.

    Returns a list of formatted explanation strings describing the
    translation decisions. Each string covers one (rule, node) pair
    that was evaluated during the most recent :meth:`translate` call.
    Empty list if no translation has been run yet.

    Returns:
        List of explanation strings (one per rule evaluation).
    """
    explanations: list[str] = []

    # Group match log entries by rule
    rule_summary: dict[str, int] = {}
    for entry in self._match_log:
        rule_name = entry.get("rule_name", "unknown")
        event_type = entry.get("event_type", "")
        if event_type == "mapping_created":
            rule_summary[rule_name] = rule_summary.get(rule_name, 0) + 1

    # Build human-readable summary
    for rule_name in sorted(rule_summary.keys()):
        count = rule_summary[rule_name]
        explanations.append(f"Rule '{rule_name}' fired {count} time(s)")

    # Add convergence summary
    iteration_events = [
        e for e in self._match_log if e.get("event_type") == "iteration_complete"
    ]
    if iteration_events:
        last_event = iteration_events[-1]
        detail = last_event.get("detail", "")
        explanations.append(f"Translation-pass convergence: {detail}")

    return explanations

get_convergence_info()

Get information about translation-pass convergence.

"Converged" here means the loop reached a pass that produced no new mappings (idempotent confirmation pass) — it does NOT mean a semantic fixpoint was computed, since rules do not consume prior mappings. The dict keys are kept stable for callers/tests.

Returns a dictionary with: - converged: Whether an idempotent (zero-new-mapping) pass was reached - iterations: Number of passes until idempotence (or max_iterations) - final_mapping_count: Number of mappings in final result

Returns:

Type Description
dict[str, Any]

Dictionary with pass-convergence metadata.

Source code in py/cogant/translate/engine.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def get_convergence_info(self) -> dict[str, Any]:
    """Get information about translation-pass convergence.

    "Converged" here means the loop reached a pass that produced no
    new mappings (idempotent confirmation pass) — it does NOT mean a
    semantic fixpoint was computed, since rules do not consume prior
    mappings. The dict keys are kept stable for callers/tests.

    Returns a dictionary with:
    - converged: Whether an idempotent (zero-new-mapping) pass was reached
    - iterations: Number of passes until idempotence (or max_iterations)
    - final_mapping_count: Number of mappings in final result

    Returns:
        Dictionary with pass-convergence metadata.
    """
    return {
        "converged": self._convergence_iteration is not None,
        "iterations": self._convergence_iteration or self.max_iterations,
        "final_mapping_count": len(self.mappings),
    }

get_coverage_report(graph)

Report what percentage of graph nodes received at least one mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph that was translated.

required

Returns:

Type Description
dict[str, Any]

Dictionary with coverage statistics including total nodes,

dict[str, Any]

covered nodes, uncovered node IDs, and coverage percentage.

Source code in py/cogant/translate/engine.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def get_coverage_report(self, graph: ProgramGraph) -> dict[str, Any]:
    """Report what percentage of graph nodes received at least one mapping.

    Args:
        graph: The program graph that was translated.

    Returns:
        Dictionary with coverage statistics including total nodes,
        covered nodes, uncovered node IDs, and coverage percentage.
    """
    all_node_ids = set(graph.nodes.keys())
    covered_node_ids: set[str] = set()

    for mapping in self.mappings.values():
        covered_node_ids.update(mapping.graph_fragment_node_ids)

    # Intersect with actual graph nodes (in case mappings reference out-of-sync IDs)
    covered_node_ids &= all_node_ids
    uncovered = all_node_ids - covered_node_ids

    total = len(all_node_ids)
    coverage_pct = (len(covered_node_ids) / total * 100.0) if total > 0 else 0.0

    return {
        "total_nodes": total,
        "covered_nodes": len(covered_node_ids),
        "uncovered_nodes": len(uncovered),
        "coverage_percent": round(coverage_pct, 2),
        "uncovered_node_ids": sorted(uncovered),
    }

get_mapping(mapping_id)

Get a mapping by ID.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping if found, None otherwise.

Source code in py/cogant/translate/engine.py
659
660
661
662
663
664
665
666
667
668
def get_mapping(self, mapping_id: str) -> SemanticMapping | None:
    """Get a mapping by ID.

    Args:
        mapping_id: ID of mapping.

    Returns:
        SemanticMapping if found, None otherwise.
    """
    return self.mappings.get(mapping_id)

get_mappings_by_confidence(tier)

Get all mappings with a specific confidence tier.

Parameters:

Name Type Description Default
tier ConfidenceTier

Confidence tier to filter by.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings at that tier.

Source code in py/cogant/translate/engine.py
645
646
647
648
649
650
651
652
653
654
655
656
657
def get_mappings_by_confidence(
    self,
    tier: ConfidenceTier,
) -> list[SemanticMapping]:
    """Get all mappings with a specific confidence tier.

    Args:
        tier: Confidence tier to filter by.

    Returns:
        List of mappings at that tier.
    """
    return [m for m in self.mappings.values() if m.confidence_tier == tier]

get_mappings_by_kind(kind)

Get all mappings of a specific kind.

Parameters:

Name Type Description Default
kind MappingKind

Kind of mapping to retrieve.

required

Returns:

Type Description
list[SemanticMapping]

List of matching mappings.

Source code in py/cogant/translate/engine.py
634
635
636
637
638
639
640
641
642
643
def get_mappings_by_kind(self, kind: MappingKind) -> list[SemanticMapping]:
    """Get all mappings of a specific kind.

    Args:
        kind: Kind of mapping to retrieve.

    Returns:
        List of matching mappings.
    """
    return [m for m in self.mappings.values() if m.kind == kind]

get_match_log()

Get the match log.

Returns:

Type Description
list[dict[str, Any]]

List of match events.

Source code in py/cogant/translate/engine.py
686
687
688
689
690
691
692
def get_match_log(self) -> list[dict[str, Any]]:
    """Get the match log.

    Returns:
        List of match events.
    """
    return self._match_log.copy()

get_statistics()

Get statistics about translations.

Returns:

Type Description
dict[str, Any]

Dictionary with statistics.

Source code in py/cogant/translate/engine.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def get_statistics(self) -> dict[str, Any]:
    """Get statistics about translations.

    Returns:
        Dictionary with statistics.
    """
    by_kind: dict[str, int] = {}
    for mapping in self.mappings.values():
        kind = mapping.kind.value
        by_kind[kind] = by_kind.get(kind, 0) + 1

    by_tier: dict[str, int] = {}
    for mapping in self.mappings.values():
        tier = mapping.confidence_tier.value
        by_tier[tier] = by_tier.get(tier, 0) + 1

    return {
        "total_mappings": len(self.mappings),
        "mappings_by_kind": by_kind,
        "mappings_by_confidence_tier": by_tier,
        "rules_registered": len(self.rules),
    }

register_rule(rule)

Register a translation rule.

Parameters:

Name Type Description Default
rule TranslationRule

Rule to register.

required
Source code in py/cogant/translate/engine.py
244
245
246
247
248
249
250
def register_rule(self, rule: TranslationRule) -> None:
    """Register a translation rule.

    Args:
        rule: Rule to register.
    """
    self.rules.append(rule)

translate(graph, rule_filter=None)

Translate a program graph using iterative rule application.

Rules are applied in repeated passes until a pass produces no new mappings or max_iterations is reached, whichever comes first. Because rules do not consume prior mappings, this is single-pass rule application followed by one idempotent confirmation pass (the second pass re-runs the rules and is expected to add nothing) — it is NOT a semantic fixpoint. After the loop exits, conflict resolution picks a single winning mapping per node set using priority then confidence as the tiebreaker.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to translate. Must have been built by the graph stage; in particular, GraphQuery must be constructable from it.

required
rule_filter list[str] | None

Optional list of rule names to apply. None (default) applies every registered rule. Pass a subset to run a targeted translation, e.g. for unit tests or the cogant explain single-node path.

None

Returns:

Type Description
list[SemanticMapping]

List of SemanticMapping instances kept after conflict

list[SemanticMapping]

resolution, in insertion order. May be empty if no rule

list[SemanticMapping]

matched.

Raises:

Type Description
RuntimeError

If a registered rule raises an unhandled exception. The engine catches and logs per-rule errors but re-raises engine-level invariant violations.

Example

engine = TranslationEngine() engine.register_rule(ObservationRule()) mappings = engine.translate(graph) all(hasattr(m.kind, "name") for m in mappings) True

Source code in py/cogant/translate/engine.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def translate(
    self,
    graph: ProgramGraph,
    rule_filter: list[str] | None = None,
) -> list[SemanticMapping]:
    """Translate a program graph using iterative rule application.

    Rules are applied in repeated passes until a pass produces no new
    mappings or ``max_iterations`` is reached, whichever comes first.
    Because rules do not consume prior mappings, this is single-pass
    rule application followed by one idempotent confirmation pass
    (the second pass re-runs the rules and is expected to add nothing)
    — it is NOT a semantic fixpoint. After the loop exits, conflict
    resolution picks a single winning mapping per node set using
    priority then confidence as the tiebreaker.

    Args:
        graph: Program graph to translate. Must have been built by
            the graph stage; in particular, ``GraphQuery`` must be
            constructable from it.
        rule_filter: Optional list of rule names to apply. ``None``
            (default) applies every registered rule. Pass a subset
            to run a targeted translation, e.g. for unit tests or
            the ``cogant explain`` single-node path.

    Returns:
        List of ``SemanticMapping`` instances kept after conflict
        resolution, in insertion order. May be empty if no rule
        matched.

    Raises:
        RuntimeError: If a registered rule raises an unhandled
            exception. The engine catches and logs per-rule errors
            but re-raises engine-level invariant violations.

    Example:
        >>> engine = TranslationEngine()
        >>> engine.register_rule(ObservationRule())
        >>> mappings = engine.translate(graph)
        >>> all(hasattr(m.kind, "name") for m in mappings)
        True
    """
    self.mappings.clear()
    self._match_log.clear()
    self._rule_priority.clear()
    self._convergence_iteration = None
    self.iterations = []

    n_nodes = len(graph.nodes)
    n_edges = len(graph.edges)
    active_rules = (
        [r for r in self.rules if r.name in rule_filter] if rule_filter else self.rules
    )
    logger.info(
        "Starting translation: %d rules active, %d nodes, %d edges%s",
        len(active_rules),
        n_nodes,
        n_edges,
        f" (filtered to {rule_filter})" if rule_filter else "",
    )

    query = GraphQuery(graph)

    for iteration in range(1, self.max_iterations + 1):
        logger.debug(
            "Translation pass %d starting (%d existing mappings)",
            iteration,
            len(self.mappings),
        )

        new_mappings_this_pass = self._apply_single_pass(
            graph, query, rule_filter=rule_filter, iteration=iteration
        )

        self.iterations.append(
            {
                "iteration": iteration,
                "new_mappings": new_mappings_this_pass,
                "mappings_added": new_mappings_this_pass,
            }
        )

        self._log_match(
            "iteration_complete",
            "engine",
            f"iteration={iteration} new_mappings={new_mappings_this_pass}",
        )
        logger.info("Translation pass %d: %d new mappings", iteration, new_mappings_this_pass)

        if new_mappings_this_pass == 0:
            logger.info(
                "Idempotence confirmed (no new mappings) after %d pass(es); "
                "not a semantic fixpoint",
                iteration,
            )
            self._convergence_iteration = iteration
            break
    else:
        logger.warning(
            "Max passes (%d) reached without an idempotent (zero-new-mapping) pass",
            self.max_iterations,
        )

    # Resolve conflicts among overlapping mappings
    conflicts_before = len(self.mappings)
    self._resolve_conflicts()
    conflicts_removed = conflicts_before - len(self.mappings)
    if conflicts_removed > 0:
        logger.info(
            "Conflict resolution: removed %d overlapping mappings (%d → %d)",
            conflicts_removed,
            conflicts_before,
            len(self.mappings),
        )

    # Log per-kind role distribution
    by_kind: dict[str, int] = {}
    for mapping in self.mappings.values():
        kind = mapping.kind.value
        by_kind[kind] = by_kind.get(kind, 0) + 1
    logger.info(
        "Translation complete: %d mappings across %d roles%s",
        len(self.mappings),
        len(by_kind),
        f" ({', '.join(f'{k}={v}' for k, v in sorted(by_kind.items()))})" if by_kind else "",
    )

    # Log coverage summary
    coverage = self.get_coverage_report(graph)
    logger.info(
        "Node coverage: %.1f%% (%d/%d covered, %d uncovered)",
        coverage["coverage_percent"],
        coverage["covered_nodes"],
        coverage["total_nodes"],
        coverage["uncovered_nodes"],
    )

    return list(self.mappings.values())

translate_with_confidence(graph, rule_filter=None)

Translate and rescore all mappings using the ConfidenceModel.

Runs the standard iterative-pass translation, then applies the ConfidenceModel to update confidence scores, tiers, and conflict penalties on every resulting mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to translate.

required
rule_filter list[str] | None

Optional list of rule names to apply (None = all).

None

Returns:

Type Description
list[SemanticMapping]

List of semantic mappings with updated confidence scores.

Source code in py/cogant/translate/engine.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def translate_with_confidence(
    self,
    graph: ProgramGraph,
    rule_filter: list[str] | None = None,
) -> list[SemanticMapping]:
    """Translate and rescore all mappings using the ConfidenceModel.

    Runs the standard iterative-pass translation, then applies the
    ConfidenceModel to update confidence scores, tiers, and
    conflict penalties on every resulting mapping.

    Args:
        graph: Program graph to translate.
        rule_filter: Optional list of rule names to apply (None = all).

    Returns:
        List of semantic mappings with updated confidence scores.
    """
    mappings = self.translate(graph, rule_filter=rule_filter)

    model = ConfidenceModel()
    model.score_batch(mappings)

    # Re-resolve conflicts now that scores are updated
    self._resolve_conflicts()

    return list(self.mappings.values())

validate()

Validate SemanticMappings for internal consistency.

Checks all mappings in :attr:mappings for: - Non-empty node IDs - Valid confidence scores (0.0–1.0) - Consistent mapping kinds - No orphaned node references (node exists in graph)

Returns:

Type Description
list[str]

List of validation issues (empty = valid). Each string

list[str]

describes one inconsistency or violation.

Source code in py/cogant/translate/engine.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def validate(self) -> list[str]:
    """Validate SemanticMappings for internal consistency.

    Checks all mappings in :attr:`mappings` for:
    - Non-empty node IDs
    - Valid confidence scores (0.0–1.0)
    - Consistent mapping kinds
    - No orphaned node references (node exists in graph)

    Returns:
        List of validation issues (empty = valid). Each string
        describes one inconsistency or violation.
    """
    issues: list[str] = []

    if not self.mappings:
        return issues  # No mappings is valid (empty graph)

    # Get all node IDs from a stored graph (if available)
    # For now, we'll validate the structure without graph reference
    for mapping_id, mapping in self.mappings.items():
        # Check non-empty node IDs
        if not mapping.graph_fragment_node_ids:
            issues.append(f"Mapping '{mapping_id}' has no node IDs in fragment")

        # Check confidence score range
        if not (0.0 <= mapping.confidence_score <= 1.0):
            issues.append(
                f"Mapping '{mapping_id}' confidence {mapping.confidence_score} "
                f"out of range [0.0, 1.0]"
            )

        # Check mapping kind is valid
        if not hasattr(mapping.kind, "value"):
            issues.append(f"Mapping '{mapping_id}' has invalid mapping kind")

        # Check consistency between confidence score and tier
        tier = mapping.confidence_tier.value
        score = mapping.confidence_score
        if tier == "STATIC_ONLY" and score < 0.5:
            issues.append(
                f"Mapping '{mapping_id}' has STATIC_ONLY tier but "
                f"confidence {score} < 0.5 (inconsistent)"
            )

    return issues

TranslationRule

Bases: ABC

Base class for translation rules.

Source code in py/cogant/translate/engine.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class TranslationRule(ABC):
    """Base class for translation rules."""

    @abstractmethod
    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Check if rule matches graph patterns.

        Args:
            graph: Program graph to analyze.
            query: Graph query engine.

        Returns:
            List of matched fragments, each with node/edge IDs.
        """
        ...

    @abstractmethod
    def apply(
        self,
        graph: ProgramGraph,
        match: dict[str, Any],
    ) -> SemanticMapping | None:
        """Apply rule to a matched pattern.

        Args:
            graph: Program graph.
            match: Matched pattern from matches().

        Returns:
            SemanticMapping if successful, None otherwise.
        """
        ...

    @property
    @abstractmethod
    def name(self) -> str:
        """Name of this rule."""
        ...

    @property
    @abstractmethod
    def mapping_kind(self) -> MappingKind:
        """Kind of semantic mapping produced."""
        ...

    @property
    def priority(self) -> int:
        """Priority of this rule (higher = applied first). Default 0.

        Rationale for default ``priority=0``:
            Most shipped rules keep the default ``0`` and are applied in
            registration order within a single translation pass.
            :class:`~cogant.translate.rules.structural.MutatingSubsystemRule`
            overrides this property to return ``1`` so class-level hidden-state
            evidence wins ties against overlapping class-scoped mappings from
            aggregate rules at equal confidence. Aside from that exception,
            conflict resolution between overlapping mappings falls through to
            the ``(priority, confidence_score)`` lexicographic comparison in
            :meth:`TranslationEngine._resolve_conflicts`. See
            ``docs/evaluation/CALIBRATION.md`` for the full rule priority audit.
            TODO(calibration): if the empirical conflict-loss rate on
            real-world repos exceeds ~5%, broaden explicit priority tiers.
        """
        return 0

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> "RuleExplanation":
        """Explain whether this rule would fire on ``node``.

        This is the default implementation used by the ``cogant explain``
        CLI subcommand. It re-runs :meth:`matches` and checks whether any
        returned match references the target node's id. Subclasses that
        can produce richer evidence (specific edge kinds, keyword hits,
        metric values) should override this method.

        The base implementation never raises: if :meth:`matches` blows
        up, the returned :class:`RuleExplanation` has ``fired=False`` and
        a reason that names the exception type so the CLI can surface it
        instead of aborting the whole explain run.

        Args:
            node: The target node whose role we want to justify.
            graph: Program graph the rule is being evaluated against.
            query: Graph query engine bound to ``graph``.

        Returns:
            A :class:`RuleExplanation` record for this (rule, node) pair.
        """
        try:
            all_matches = self.matches(graph, query)
        except (TypeError, ValueError, KeyError, AttributeError) as exc:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=f"rule error during matching: {type(exc).__name__}: {exc}",
                evidence=[],
                mapping_kind=self.mapping_kind.value,
                confidence=0.0,
                contradictions=[],
            )

        for match in all_matches:
            node_id = match.get("node_id") if isinstance(match, dict) else None
            fragment_ids: list[str] = []
            if isinstance(match, dict):
                fragment_ids = list(match.get("node_ids", []) or [])
            if node_id == node.id or node.id in fragment_ids:
                evidence: list[str] = []
                for key, value in sorted(match.items()):
                    if key in ("node_id", "node_ids"):
                        continue
                    evidence.append(f"{key}={value}")
                return RuleExplanation(
                    rule_name=self.name,
                    priority=self.priority,
                    fired=True,
                    reason=(f"rule '{self.name}' matched node {node.qualified_name or node.name}"),
                    evidence=evidence,
                    mapping_kind=self.mapping_kind.value,
                    confidence=0.75,  # default reasonable confidence
                    contradictions=[],
                )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"rule '{self.name}' considered but did not match "
                f"{node.qualified_name or node.name}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
            confidence=0.0,
            contradictions=[],
        )

mapping_kind abstractmethod property

Kind of semantic mapping produced.

name abstractmethod property

Name of this rule.

priority property

Priority of this rule (higher = applied first). Default 0.

Rationale for default priority=0: Most shipped rules keep the default 0 and are applied in registration order within a single translation pass. :class:~cogant.translate.rules.structural.MutatingSubsystemRule overrides this property to return 1 so class-level hidden-state evidence wins ties against overlapping class-scoped mappings from aggregate rules at equal confidence. Aside from that exception, conflict resolution between overlapping mappings falls through to the (priority, confidence_score) lexicographic comparison in :meth:TranslationEngine._resolve_conflicts. See docs/evaluation/CALIBRATION.md for the full rule priority audit. TODO(calibration): if the empirical conflict-loss rate on real-world repos exceeds ~5%, broaden explicit priority tiers.

apply(graph, match) abstractmethod

Apply rule to a matched pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern from matches().

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping if successful, None otherwise.

Source code in py/cogant/translate/engine.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@abstractmethod
def apply(
    self,
    graph: ProgramGraph,
    match: dict[str, Any],
) -> SemanticMapping | None:
    """Apply rule to a matched pattern.

    Args:
        graph: Program graph.
        match: Matched pattern from matches().

    Returns:
        SemanticMapping if successful, None otherwise.
    """
    ...

explain(node, graph, query)

Explain whether this rule would fire on node.

This is the default implementation used by the cogant explain CLI subcommand. It re-runs :meth:matches and checks whether any returned match references the target node's id. Subclasses that can produce richer evidence (specific edge kinds, keyword hits, metric values) should override this method.

The base implementation never raises: if :meth:matches blows up, the returned :class:RuleExplanation has fired=False and a reason that names the exception type so the CLI can surface it instead of aborting the whole explain run.

Parameters:

Name Type Description Default
node Node

The target node whose role we want to justify.

required
graph ProgramGraph

Program graph the rule is being evaluated against.

required
query GraphQuery

Graph query engine bound to graph.

required

Returns:

Name Type Description
A RuleExplanation

class:RuleExplanation record for this (rule, node) pair.

Source code in py/cogant/translate/engine.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> "RuleExplanation":
    """Explain whether this rule would fire on ``node``.

    This is the default implementation used by the ``cogant explain``
    CLI subcommand. It re-runs :meth:`matches` and checks whether any
    returned match references the target node's id. Subclasses that
    can produce richer evidence (specific edge kinds, keyword hits,
    metric values) should override this method.

    The base implementation never raises: if :meth:`matches` blows
    up, the returned :class:`RuleExplanation` has ``fired=False`` and
    a reason that names the exception type so the CLI can surface it
    instead of aborting the whole explain run.

    Args:
        node: The target node whose role we want to justify.
        graph: Program graph the rule is being evaluated against.
        query: Graph query engine bound to ``graph``.

    Returns:
        A :class:`RuleExplanation` record for this (rule, node) pair.
    """
    try:
        all_matches = self.matches(graph, query)
    except (TypeError, ValueError, KeyError, AttributeError) as exc:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=f"rule error during matching: {type(exc).__name__}: {exc}",
            evidence=[],
            mapping_kind=self.mapping_kind.value,
            confidence=0.0,
            contradictions=[],
        )

    for match in all_matches:
        node_id = match.get("node_id") if isinstance(match, dict) else None
        fragment_ids: list[str] = []
        if isinstance(match, dict):
            fragment_ids = list(match.get("node_ids", []) or [])
        if node_id == node.id or node.id in fragment_ids:
            evidence: list[str] = []
            for key, value in sorted(match.items()):
                if key in ("node_id", "node_ids"):
                    continue
                evidence.append(f"{key}={value}")
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=(f"rule '{self.name}' matched node {node.qualified_name or node.name}"),
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
                confidence=0.75,  # default reasonable confidence
                contradictions=[],
            )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(
            f"rule '{self.name}' considered but did not match "
            f"{node.qualified_name or node.name}"
        ),
        evidence=[],
        mapping_kind=self.mapping_kind.value,
        confidence=0.0,
        contradictions=[],
    )

matches(graph, query) abstractmethod

Check if rule matches graph patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to analyze.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched fragments, each with node/edge IDs.

Source code in py/cogant/translate/engine.py
68
69
70
71
72
73
74
75
76
77
78
79
@abstractmethod
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Check if rule matches graph patterns.

    Args:
        graph: Program graph to analyze.
        query: Graph query engine.

    Returns:
        List of matched fragments, each with node/edge IDs.
    """
    ...

Engine

The core orchestration: TranslationEngine.run() drives the fixpoint loop and the conflict-resolution pass; every rule exposes an .explain() method that returns a RuleExplanation (used by cogant explain).

cogant.translate.engine

Translation engine orchestrating rule application over program graphs.

RuleExplanation dataclass

Explanation of why a translation rule did or did not fire on a node.

Produced by :meth:TranslationRule.explain during the cogant explain workflow. Each instance records a single (rule, node) decision: the rule's name and priority, whether it fired, a short human-readable reason, and the list of concrete evidence snippets (edge kinds, keyword matches, qualified identifiers) that backed the decision.

The dataclass is deliberately JSON-serialization friendly via :meth:to_dict so the explain CLI can emit either a rich text report or a machine-readable JSON blob without duplicating the payload logic.

Attributes:

Name Type Description
rule_name str

Stable rule identifier (rule.name).

priority int

Rule priority tier (higher fires first).

fired bool

True when the rule actually produced a mapping for this node, False when it was considered but skipped.

reason str

One-line explanation of the decision.

evidence list[str]

Concrete evidence strings collected during matching (e.g. "WRITES self.display", "keyword match: 'set'").

mapping_kind str | None

Semantic kind the rule would have produced, or None when the rule did not fire.

confidence float

Confidence score (0.0–1.0) if rule fired, 0.0 if not fired.

contradictions list[str]

List of contradictory evidence or rule conflicts that might lower confidence in this mapping.

Source code in py/cogant/translate/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass
class RuleExplanation:
    """Explanation of why a translation rule did or did not fire on a node.

    Produced by :meth:`TranslationRule.explain` during the
    ``cogant explain`` workflow. Each instance records a single
    (rule, node) decision: the rule's name and priority, whether it
    fired, a short human-readable reason, and the list of concrete
    evidence snippets (edge kinds, keyword matches, qualified
    identifiers) that backed the decision.

    The dataclass is deliberately JSON-serialization friendly via
    :meth:`to_dict` so the explain CLI can emit either a rich text
    report or a machine-readable JSON blob without duplicating the
    payload logic.

    Attributes:
        rule_name: Stable rule identifier (``rule.name``).
        priority: Rule priority tier (higher fires first).
        fired: True when the rule actually produced a mapping for this
            node, False when it was considered but skipped.
        reason: One-line explanation of the decision.
        evidence: Concrete evidence strings collected during matching
            (e.g. ``"WRITES self.display"``, ``"keyword match: 'set'"``).
        mapping_kind: Semantic kind the rule would have produced, or
            None when the rule did not fire.
        confidence: Confidence score (0.0–1.0) if rule fired, 0.0 if not fired.
        contradictions: List of contradictory evidence or rule conflicts that
            might lower confidence in this mapping.
    """

    rule_name: str
    priority: int
    fired: bool
    reason: str
    evidence: list[str] = field(default_factory=list)
    mapping_kind: str | None = None
    confidence: float = 0.0
    contradictions: list[str] = field(default_factory=list)

    def to_dict(self) -> dict[str, Any]:
        """Serialize to a plain JSON-ready dict."""
        return dataclasses.asdict(self)

to_dict()

Serialize to a plain JSON-ready dict.

Source code in py/cogant/translate/engine.py
60
61
62
def to_dict(self) -> dict[str, Any]:
    """Serialize to a plain JSON-ready dict."""
    return dataclasses.asdict(self)

TranslationEngine

Orchestrates translation of program graphs to semantic concepts.

Applies the registered translation rules with iterative rule application plus an idempotent confirmation pass. Rules do not consume prior mappings (TranslationRule.apply only receives the graph and a single match), so a true semantic fixpoint is NOT performed: the first pass produces every mapping the rules can produce, and the second pass exists solely to confirm idempotence (no new mappings) before conflict resolution. max_iterations bounds the loop as a safety margin only. Resolves conflicts when multiple mappings target overlapping node sets.

Source code in py/cogant/translate/engine.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
class TranslationEngine:
    """Orchestrates translation of program graphs to semantic concepts.

    Applies the registered translation rules with iterative rule
    application plus an idempotent confirmation pass. Rules do not consume
    prior mappings (``TranslationRule.apply`` only receives the graph and
    a single match), so a true semantic fixpoint is NOT performed: the
    first pass produces every mapping the rules can produce, and the
    second pass exists solely to confirm idempotence (no new mappings)
    before conflict resolution. ``max_iterations`` bounds the loop as a
    safety margin only. Resolves conflicts when multiple mappings target
    overlapping node sets.
    """

    def __init__(self, max_iterations: int = 10):
        """Initialize the translation engine.

        Args:
            max_iterations: Maximum rule-application passes (default 10).

        Rationale for default ``max_iterations=10``:
            Because rules do not consume prior mappings, the second pass
            never produces new mappings; in practice the loop exits after
            the first pass plus one idempotent confirmation pass (<=2
            passes) on control-positive fixtures and typical corpora. 10
            is a generous safety margin, not an expected iteration count.
            See ``docs/evaluation/CALIBRATION.md``.
        """
        self.rules: list[TranslationRule] = []
        self.mappings: dict[str, SemanticMapping] = {}
        self._match_log: list[dict[str, Any]] = []
        self._rule_priority: dict[str, int] = {}
        self.max_iterations = max_iterations
        self.iterations: list[dict[str, Any]] = []
        self._convergence_iteration: int | None = None

    def register_rule(self, rule: TranslationRule) -> None:
        """Register a translation rule.

        Args:
            rule: Rule to register.
        """
        self.rules.append(rule)

    def translate(
        self,
        graph: ProgramGraph,
        rule_filter: list[str] | None = None,
    ) -> list[SemanticMapping]:
        """Translate a program graph using iterative rule application.

        Rules are applied in repeated passes until a pass produces no new
        mappings or ``max_iterations`` is reached, whichever comes first.
        Because rules do not consume prior mappings, this is single-pass
        rule application followed by one idempotent confirmation pass
        (the second pass re-runs the rules and is expected to add nothing)
        — it is NOT a semantic fixpoint. After the loop exits, conflict
        resolution picks a single winning mapping per node set using
        priority then confidence as the tiebreaker.

        Args:
            graph: Program graph to translate. Must have been built by
                the graph stage; in particular, ``GraphQuery`` must be
                constructable from it.
            rule_filter: Optional list of rule names to apply. ``None``
                (default) applies every registered rule. Pass a subset
                to run a targeted translation, e.g. for unit tests or
                the ``cogant explain`` single-node path.

        Returns:
            List of ``SemanticMapping`` instances kept after conflict
            resolution, in insertion order. May be empty if no rule
            matched.

        Raises:
            RuntimeError: If a registered rule raises an unhandled
                exception. The engine catches and logs per-rule errors
                but re-raises engine-level invariant violations.

        Example:
            >>> engine = TranslationEngine()
            >>> engine.register_rule(ObservationRule())
            >>> mappings = engine.translate(graph)
            >>> all(hasattr(m.kind, "name") for m in mappings)
            True
        """
        self.mappings.clear()
        self._match_log.clear()
        self._rule_priority.clear()
        self._convergence_iteration = None
        self.iterations = []

        n_nodes = len(graph.nodes)
        n_edges = len(graph.edges)
        active_rules = (
            [r for r in self.rules if r.name in rule_filter] if rule_filter else self.rules
        )
        logger.info(
            "Starting translation: %d rules active, %d nodes, %d edges%s",
            len(active_rules),
            n_nodes,
            n_edges,
            f" (filtered to {rule_filter})" if rule_filter else "",
        )

        query = GraphQuery(graph)

        for iteration in range(1, self.max_iterations + 1):
            logger.debug(
                "Translation pass %d starting (%d existing mappings)",
                iteration,
                len(self.mappings),
            )

            new_mappings_this_pass = self._apply_single_pass(
                graph, query, rule_filter=rule_filter, iteration=iteration
            )

            self.iterations.append(
                {
                    "iteration": iteration,
                    "new_mappings": new_mappings_this_pass,
                    "mappings_added": new_mappings_this_pass,
                }
            )

            self._log_match(
                "iteration_complete",
                "engine",
                f"iteration={iteration} new_mappings={new_mappings_this_pass}",
            )
            logger.info("Translation pass %d: %d new mappings", iteration, new_mappings_this_pass)

            if new_mappings_this_pass == 0:
                logger.info(
                    "Idempotence confirmed (no new mappings) after %d pass(es); "
                    "not a semantic fixpoint",
                    iteration,
                )
                self._convergence_iteration = iteration
                break
        else:
            logger.warning(
                "Max passes (%d) reached without an idempotent (zero-new-mapping) pass",
                self.max_iterations,
            )

        # Resolve conflicts among overlapping mappings
        conflicts_before = len(self.mappings)
        self._resolve_conflicts()
        conflicts_removed = conflicts_before - len(self.mappings)
        if conflicts_removed > 0:
            logger.info(
                "Conflict resolution: removed %d overlapping mappings (%d → %d)",
                conflicts_removed,
                conflicts_before,
                len(self.mappings),
            )

        # Log per-kind role distribution
        by_kind: dict[str, int] = {}
        for mapping in self.mappings.values():
            kind = mapping.kind.value
            by_kind[kind] = by_kind.get(kind, 0) + 1
        logger.info(
            "Translation complete: %d mappings across %d roles%s",
            len(self.mappings),
            len(by_kind),
            f" ({', '.join(f'{k}={v}' for k, v in sorted(by_kind.items()))})" if by_kind else "",
        )

        # Log coverage summary
        coverage = self.get_coverage_report(graph)
        logger.info(
            "Node coverage: %.1f%% (%d/%d covered, %d uncovered)",
            coverage["coverage_percent"],
            coverage["covered_nodes"],
            coverage["total_nodes"],
            coverage["uncovered_nodes"],
        )

        return list(self.mappings.values())

    def _apply_single_pass(
        self,
        graph: ProgramGraph,
        query: GraphQuery,
        rule_filter: list[str] | None = None,
        iteration: int = 0,
    ) -> int:
        """Apply all rules once, sorted by priority. Returns count of new mappings created.

        Args:
            graph: Program graph to translate.
            query: Graph query engine bound to ``graph``.
            rule_filter: Optional list of rule names to restrict application.
            iteration: Current translation-pass number (for logging context).

        Returns:
            Number of new mappings created during this pass.
        """
        new_mappings = 0
        sorted_rules = sorted(self.rules, key=lambda r: r.priority, reverse=True)
        per_rule_counts: dict[str, int] = {}
        per_rule_errors: dict[str, int] = {}

        for rule in sorted_rules:
            # Skip if filtered out
            if rule_filter and rule.name not in rule_filter:
                continue

            rule_new = 0
            rule_errors = 0

            # Find matches
            try:
                matches = rule.matches(graph, query)
            except (TypeError, ValueError, KeyError, AttributeError) as e:
                logger.warning(
                    "Rule %r failed during matching (iteration=%d): %s",
                    rule.name,
                    iteration,
                    e,
                )
                self._log_match(
                    "rule_error",
                    rule.name,
                    f"iteration={iteration} error={e}",
                )
                rule_errors += 1
                per_rule_counts[rule.name] = 0
                per_rule_errors[rule.name] = rule_errors
                continue

            # Apply rule to each match
            for match in matches:
                try:
                    mapping = rule.apply(graph, match)
                    if mapping and mapping.id not in self.mappings:
                        mapping.metadata.setdefault("rule_id", rule.name)
                        mapping.metadata.setdefault("rule_priority", rule.priority)
                        mapping.metadata.setdefault("match", match)
                        mapping.metadata.setdefault("iteration", iteration)
                        self.mappings[mapping.id] = mapping
                        self._rule_priority[mapping.id] = rule.priority
                        self._log_match("mapping_created", rule.name, mapping.id)
                        new_mappings += 1
                        rule_new += 1
                except (TypeError, ValueError, KeyError, AttributeError) as e:
                    logger.warning(
                        "Rule %r failed during apply (iteration=%d, match=%r): %s",
                        rule.name,
                        iteration,
                        match,
                        e,
                    )
                    self._log_match(
                        "apply_error",
                        rule.name,
                        f"iteration={iteration} match={match} error={e}",
                    )
                    rule_errors += 1

            per_rule_counts[rule.name] = rule_new
            if rule_errors:
                per_rule_errors[rule.name] = rule_errors

            if rule_new > 0 or rule_errors > 0:
                logger.debug(
                    "Rule %r: %d new mappings, %d errors (iteration=%d, priority=%d, family=%s)",
                    rule.name,
                    rule_new,
                    rule_errors,
                    iteration,
                    rule.priority,
                    rule.mapping_kind.value,
                )

        # Log per-rule summary for this pass when there are new mappings
        if new_mappings > 0:
            active = ", ".join(
                f"{name}={cnt}"
                for name, cnt in sorted(per_rule_counts.items(), key=lambda kv: -kv[1])
                if cnt > 0
            )
            logger.debug(
                "Pass %d rule breakdown: %d new total [%s]",
                iteration,
                new_mappings,
                active,
            )
            if per_rule_errors:
                err_summary = ", ".join(f"{name}={cnt}" for name, cnt in per_rule_errors.items())
                logger.debug("Pass %d rule errors: [%s]", iteration, err_summary)

        return new_mappings

    def translate_with_confidence(
        self,
        graph: ProgramGraph,
        rule_filter: list[str] | None = None,
    ) -> list[SemanticMapping]:
        """Translate and rescore all mappings using the ConfidenceModel.

        Runs the standard iterative-pass translation, then applies the
        ConfidenceModel to update confidence scores, tiers, and
        conflict penalties on every resulting mapping.

        Args:
            graph: Program graph to translate.
            rule_filter: Optional list of rule names to apply (None = all).

        Returns:
            List of semantic mappings with updated confidence scores.
        """
        mappings = self.translate(graph, rule_filter=rule_filter)

        model = ConfidenceModel()
        model.score_batch(mappings)

        # Re-resolve conflicts now that scores are updated
        self._resolve_conflicts()

        return list(self.mappings.values())

    def _resolve_conflicts(self) -> None:
        """Resolve conflicts when multiple mappings target overlapping node sets.

        Uses a node-to-mappings inverted index so conflict detection is
        O(total_node_references) rather than O(n_mappings^2). For each
        colliding pair, the loser is chosen by comparing
        ``(rule_priority, confidence_score)`` tuples (higher wins), with
        the confidence score acting as a tiebreaker when priorities are
        equal.
        """
        # Build inverted index: node_id -> list of mapping IDs touching it.
        node_to_mappings: dict[str, list[str]] = {}
        for mapping in self.mappings.values():
            for node_id in mapping.graph_fragment_node_ids:
                node_to_mappings.setdefault(node_id, []).append(mapping.id)

        # Collect unique colliding pairs via the inverted index.
        conflict_pairs: set[tuple[str, str]] = set()
        for mids in node_to_mappings.values():
            if len(mids) < 2:
                continue
            for i in range(len(mids)):
                for j in range(i + 1, len(mids)):
                    a, b = mids[i], mids[j]
                    conflict_pairs.add((a, b) if a < b else (b, a))

        to_remove: set[str] = set()
        # Sets have undefined iteration order; use sorted pair order so
        # conflict resolution is deterministic for identical inputs (benchmarks
        # vs generate_figures, CI vs local).
        for a_id, b_id in sorted(conflict_pairs):
            if a_id in to_remove or b_id in to_remove:
                continue
            mapping_a = self.mappings.get(a_id)
            mapping_b = self.mappings.get(b_id)
            if mapping_a is None or mapping_b is None:
                continue
            pri_a = self._rule_priority.get(a_id, 0)
            pri_b = self._rule_priority.get(b_id, 0)
            key_a = (pri_a, mapping_a.confidence_score)
            key_b = (pri_b, mapping_b.confidence_score)
            if key_a >= key_b:
                loser, winner = mapping_b, mapping_a
            else:
                loser, winner = mapping_a, mapping_b
            to_remove.add(loser.id)
            overlap = set(mapping_a.graph_fragment_node_ids) & set(
                mapping_b.graph_fragment_node_ids
            )
            winner.metadata.setdefault("conflict_resolution", []).append(
                {
                    "kept": winner.id,
                    "removed": loser.id,
                    "overlap_node_ids": sorted(overlap),
                    "winner_priority": self._rule_priority.get(winner.id, 0),
                    "loser_priority": self._rule_priority.get(loser.id, 0),
                    "winner_confidence": winner.confidence_score,
                    "loser_confidence": loser.confidence_score,
                }
            )
            loser.metadata["conflict_resolution_status"] = "removed"
            self._log_match(
                "conflict_resolved",
                "engine",
                f"removed={loser.id} kept={winner.id} overlap={overlap}",
            )

        for mid in to_remove:
            del self.mappings[mid]

    def get_coverage_report(self, graph: ProgramGraph) -> dict[str, Any]:
        """Report what percentage of graph nodes received at least one mapping.

        Args:
            graph: The program graph that was translated.

        Returns:
            Dictionary with coverage statistics including total nodes,
            covered nodes, uncovered node IDs, and coverage percentage.
        """
        all_node_ids = set(graph.nodes.keys())
        covered_node_ids: set[str] = set()

        for mapping in self.mappings.values():
            covered_node_ids.update(mapping.graph_fragment_node_ids)

        # Intersect with actual graph nodes (in case mappings reference out-of-sync IDs)
        covered_node_ids &= all_node_ids
        uncovered = all_node_ids - covered_node_ids

        total = len(all_node_ids)
        coverage_pct = (len(covered_node_ids) / total * 100.0) if total > 0 else 0.0

        return {
            "total_nodes": total,
            "covered_nodes": len(covered_node_ids),
            "uncovered_nodes": len(uncovered),
            "coverage_percent": round(coverage_pct, 2),
            "uncovered_node_ids": sorted(uncovered),
        }

    def get_mappings_by_kind(self, kind: MappingKind) -> list[SemanticMapping]:
        """Get all mappings of a specific kind.

        Args:
            kind: Kind of mapping to retrieve.

        Returns:
            List of matching mappings.
        """
        return [m for m in self.mappings.values() if m.kind == kind]

    def get_mappings_by_confidence(
        self,
        tier: ConfidenceTier,
    ) -> list[SemanticMapping]:
        """Get all mappings with a specific confidence tier.

        Args:
            tier: Confidence tier to filter by.

        Returns:
            List of mappings at that tier.
        """
        return [m for m in self.mappings.values() if m.confidence_tier == tier]

    def get_mapping(self, mapping_id: str) -> SemanticMapping | None:
        """Get a mapping by ID.

        Args:
            mapping_id: ID of mapping.

        Returns:
            SemanticMapping if found, None otherwise.
        """
        return self.mappings.get(mapping_id)

    def _log_match(self, event_type: str, rule_name: str, detail: str) -> None:
        """Log a match event.

        Args:
            event_type: Type of event.
            rule_name: Name of rule.
            detail: Event details.
        """
        self._match_log.append(
            {
                "event_type": event_type,
                "rule_name": rule_name,
                "detail": detail,
            }
        )

    def get_match_log(self) -> list[dict[str, Any]]:
        """Get the match log.

        Returns:
            List of match events.
        """
        return self._match_log.copy()

    def get_statistics(self) -> dict[str, Any]:
        """Get statistics about translations.

        Returns:
            Dictionary with statistics.
        """
        by_kind: dict[str, int] = {}
        for mapping in self.mappings.values():
            kind = mapping.kind.value
            by_kind[kind] = by_kind.get(kind, 0) + 1

        by_tier: dict[str, int] = {}
        for mapping in self.mappings.values():
            tier = mapping.confidence_tier.value
            by_tier[tier] = by_tier.get(tier, 0) + 1

        return {
            "total_mappings": len(self.mappings),
            "mappings_by_kind": by_kind,
            "mappings_by_confidence_tier": by_tier,
            "rules_registered": len(self.rules),
        }

    def explain(self) -> list[str]:
        """Produce human-readable explanations of which rules fired and why.

        Returns a list of formatted explanation strings describing the
        translation decisions. Each string covers one (rule, node) pair
        that was evaluated during the most recent :meth:`translate` call.
        Empty list if no translation has been run yet.

        Returns:
            List of explanation strings (one per rule evaluation).
        """
        explanations: list[str] = []

        # Group match log entries by rule
        rule_summary: dict[str, int] = {}
        for entry in self._match_log:
            rule_name = entry.get("rule_name", "unknown")
            event_type = entry.get("event_type", "")
            if event_type == "mapping_created":
                rule_summary[rule_name] = rule_summary.get(rule_name, 0) + 1

        # Build human-readable summary
        for rule_name in sorted(rule_summary.keys()):
            count = rule_summary[rule_name]
            explanations.append(f"Rule '{rule_name}' fired {count} time(s)")

        # Add convergence summary
        iteration_events = [
            e for e in self._match_log if e.get("event_type") == "iteration_complete"
        ]
        if iteration_events:
            last_event = iteration_events[-1]
            detail = last_event.get("detail", "")
            explanations.append(f"Translation-pass convergence: {detail}")

        return explanations

    def validate(self) -> list[str]:
        """Validate SemanticMappings for internal consistency.

        Checks all mappings in :attr:`mappings` for:
        - Non-empty node IDs
        - Valid confidence scores (0.0–1.0)
        - Consistent mapping kinds
        - No orphaned node references (node exists in graph)

        Returns:
            List of validation issues (empty = valid). Each string
            describes one inconsistency or violation.
        """
        issues: list[str] = []

        if not self.mappings:
            return issues  # No mappings is valid (empty graph)

        # Get all node IDs from a stored graph (if available)
        # For now, we'll validate the structure without graph reference
        for mapping_id, mapping in self.mappings.items():
            # Check non-empty node IDs
            if not mapping.graph_fragment_node_ids:
                issues.append(f"Mapping '{mapping_id}' has no node IDs in fragment")

            # Check confidence score range
            if not (0.0 <= mapping.confidence_score <= 1.0):
                issues.append(
                    f"Mapping '{mapping_id}' confidence {mapping.confidence_score} "
                    f"out of range [0.0, 1.0]"
                )

            # Check mapping kind is valid
            if not hasattr(mapping.kind, "value"):
                issues.append(f"Mapping '{mapping_id}' has invalid mapping kind")

            # Check consistency between confidence score and tier
            tier = mapping.confidence_tier.value
            score = mapping.confidence_score
            if tier == "STATIC_ONLY" and score < 0.5:
                issues.append(
                    f"Mapping '{mapping_id}' has STATIC_ONLY tier but "
                    f"confidence {score} < 0.5 (inconsistent)"
                )

        return issues

    def get_convergence_info(self) -> dict[str, Any]:
        """Get information about translation-pass convergence.

        "Converged" here means the loop reached a pass that produced no
        new mappings (idempotent confirmation pass) — it does NOT mean a
        semantic fixpoint was computed, since rules do not consume prior
        mappings. The dict keys are kept stable for callers/tests.

        Returns a dictionary with:
        - converged: Whether an idempotent (zero-new-mapping) pass was reached
        - iterations: Number of passes until idempotence (or max_iterations)
        - final_mapping_count: Number of mappings in final result

        Returns:
            Dictionary with pass-convergence metadata.
        """
        return {
            "converged": self._convergence_iteration is not None,
            "iterations": self._convergence_iteration or self.max_iterations,
            "final_mapping_count": len(self.mappings),
        }

__init__(max_iterations=10)

Initialize the translation engine.

Parameters:

Name Type Description Default
max_iterations int

Maximum rule-application passes (default 10).

10

Rationale for default max_iterations=10: Because rules do not consume prior mappings, the second pass never produces new mappings; in practice the loop exits after the first pass plus one idempotent confirmation pass (<=2 passes) on control-positive fixtures and typical corpora. 10 is a generous safety margin, not an expected iteration count. See docs/evaluation/CALIBRATION.md.

Source code in py/cogant/translate/engine.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def __init__(self, max_iterations: int = 10):
    """Initialize the translation engine.

    Args:
        max_iterations: Maximum rule-application passes (default 10).

    Rationale for default ``max_iterations=10``:
        Because rules do not consume prior mappings, the second pass
        never produces new mappings; in practice the loop exits after
        the first pass plus one idempotent confirmation pass (<=2
        passes) on control-positive fixtures and typical corpora. 10
        is a generous safety margin, not an expected iteration count.
        See ``docs/evaluation/CALIBRATION.md``.
    """
    self.rules: list[TranslationRule] = []
    self.mappings: dict[str, SemanticMapping] = {}
    self._match_log: list[dict[str, Any]] = []
    self._rule_priority: dict[str, int] = {}
    self.max_iterations = max_iterations
    self.iterations: list[dict[str, Any]] = []
    self._convergence_iteration: int | None = None

explain()

Produce human-readable explanations of which rules fired and why.

Returns a list of formatted explanation strings describing the translation decisions. Each string covers one (rule, node) pair that was evaluated during the most recent :meth:translate call. Empty list if no translation has been run yet.

Returns:

Type Description
list[str]

List of explanation strings (one per rule evaluation).

Source code in py/cogant/translate/engine.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def explain(self) -> list[str]:
    """Produce human-readable explanations of which rules fired and why.

    Returns a list of formatted explanation strings describing the
    translation decisions. Each string covers one (rule, node) pair
    that was evaluated during the most recent :meth:`translate` call.
    Empty list if no translation has been run yet.

    Returns:
        List of explanation strings (one per rule evaluation).
    """
    explanations: list[str] = []

    # Group match log entries by rule
    rule_summary: dict[str, int] = {}
    for entry in self._match_log:
        rule_name = entry.get("rule_name", "unknown")
        event_type = entry.get("event_type", "")
        if event_type == "mapping_created":
            rule_summary[rule_name] = rule_summary.get(rule_name, 0) + 1

    # Build human-readable summary
    for rule_name in sorted(rule_summary.keys()):
        count = rule_summary[rule_name]
        explanations.append(f"Rule '{rule_name}' fired {count} time(s)")

    # Add convergence summary
    iteration_events = [
        e for e in self._match_log if e.get("event_type") == "iteration_complete"
    ]
    if iteration_events:
        last_event = iteration_events[-1]
        detail = last_event.get("detail", "")
        explanations.append(f"Translation-pass convergence: {detail}")

    return explanations

get_convergence_info()

Get information about translation-pass convergence.

"Converged" here means the loop reached a pass that produced no new mappings (idempotent confirmation pass) — it does NOT mean a semantic fixpoint was computed, since rules do not consume prior mappings. The dict keys are kept stable for callers/tests.

Returns a dictionary with: - converged: Whether an idempotent (zero-new-mapping) pass was reached - iterations: Number of passes until idempotence (or max_iterations) - final_mapping_count: Number of mappings in final result

Returns:

Type Description
dict[str, Any]

Dictionary with pass-convergence metadata.

Source code in py/cogant/translate/engine.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def get_convergence_info(self) -> dict[str, Any]:
    """Get information about translation-pass convergence.

    "Converged" here means the loop reached a pass that produced no
    new mappings (idempotent confirmation pass) — it does NOT mean a
    semantic fixpoint was computed, since rules do not consume prior
    mappings. The dict keys are kept stable for callers/tests.

    Returns a dictionary with:
    - converged: Whether an idempotent (zero-new-mapping) pass was reached
    - iterations: Number of passes until idempotence (or max_iterations)
    - final_mapping_count: Number of mappings in final result

    Returns:
        Dictionary with pass-convergence metadata.
    """
    return {
        "converged": self._convergence_iteration is not None,
        "iterations": self._convergence_iteration or self.max_iterations,
        "final_mapping_count": len(self.mappings),
    }

get_coverage_report(graph)

Report what percentage of graph nodes received at least one mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph that was translated.

required

Returns:

Type Description
dict[str, Any]

Dictionary with coverage statistics including total nodes,

dict[str, Any]

covered nodes, uncovered node IDs, and coverage percentage.

Source code in py/cogant/translate/engine.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def get_coverage_report(self, graph: ProgramGraph) -> dict[str, Any]:
    """Report what percentage of graph nodes received at least one mapping.

    Args:
        graph: The program graph that was translated.

    Returns:
        Dictionary with coverage statistics including total nodes,
        covered nodes, uncovered node IDs, and coverage percentage.
    """
    all_node_ids = set(graph.nodes.keys())
    covered_node_ids: set[str] = set()

    for mapping in self.mappings.values():
        covered_node_ids.update(mapping.graph_fragment_node_ids)

    # Intersect with actual graph nodes (in case mappings reference out-of-sync IDs)
    covered_node_ids &= all_node_ids
    uncovered = all_node_ids - covered_node_ids

    total = len(all_node_ids)
    coverage_pct = (len(covered_node_ids) / total * 100.0) if total > 0 else 0.0

    return {
        "total_nodes": total,
        "covered_nodes": len(covered_node_ids),
        "uncovered_nodes": len(uncovered),
        "coverage_percent": round(coverage_pct, 2),
        "uncovered_node_ids": sorted(uncovered),
    }

get_mapping(mapping_id)

Get a mapping by ID.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping if found, None otherwise.

Source code in py/cogant/translate/engine.py
659
660
661
662
663
664
665
666
667
668
def get_mapping(self, mapping_id: str) -> SemanticMapping | None:
    """Get a mapping by ID.

    Args:
        mapping_id: ID of mapping.

    Returns:
        SemanticMapping if found, None otherwise.
    """
    return self.mappings.get(mapping_id)

get_mappings_by_confidence(tier)

Get all mappings with a specific confidence tier.

Parameters:

Name Type Description Default
tier ConfidenceTier

Confidence tier to filter by.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings at that tier.

Source code in py/cogant/translate/engine.py
645
646
647
648
649
650
651
652
653
654
655
656
657
def get_mappings_by_confidence(
    self,
    tier: ConfidenceTier,
) -> list[SemanticMapping]:
    """Get all mappings with a specific confidence tier.

    Args:
        tier: Confidence tier to filter by.

    Returns:
        List of mappings at that tier.
    """
    return [m for m in self.mappings.values() if m.confidence_tier == tier]

get_mappings_by_kind(kind)

Get all mappings of a specific kind.

Parameters:

Name Type Description Default
kind MappingKind

Kind of mapping to retrieve.

required

Returns:

Type Description
list[SemanticMapping]

List of matching mappings.

Source code in py/cogant/translate/engine.py
634
635
636
637
638
639
640
641
642
643
def get_mappings_by_kind(self, kind: MappingKind) -> list[SemanticMapping]:
    """Get all mappings of a specific kind.

    Args:
        kind: Kind of mapping to retrieve.

    Returns:
        List of matching mappings.
    """
    return [m for m in self.mappings.values() if m.kind == kind]

get_match_log()

Get the match log.

Returns:

Type Description
list[dict[str, Any]]

List of match events.

Source code in py/cogant/translate/engine.py
686
687
688
689
690
691
692
def get_match_log(self) -> list[dict[str, Any]]:
    """Get the match log.

    Returns:
        List of match events.
    """
    return self._match_log.copy()

get_statistics()

Get statistics about translations.

Returns:

Type Description
dict[str, Any]

Dictionary with statistics.

Source code in py/cogant/translate/engine.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def get_statistics(self) -> dict[str, Any]:
    """Get statistics about translations.

    Returns:
        Dictionary with statistics.
    """
    by_kind: dict[str, int] = {}
    for mapping in self.mappings.values():
        kind = mapping.kind.value
        by_kind[kind] = by_kind.get(kind, 0) + 1

    by_tier: dict[str, int] = {}
    for mapping in self.mappings.values():
        tier = mapping.confidence_tier.value
        by_tier[tier] = by_tier.get(tier, 0) + 1

    return {
        "total_mappings": len(self.mappings),
        "mappings_by_kind": by_kind,
        "mappings_by_confidence_tier": by_tier,
        "rules_registered": len(self.rules),
    }

register_rule(rule)

Register a translation rule.

Parameters:

Name Type Description Default
rule TranslationRule

Rule to register.

required
Source code in py/cogant/translate/engine.py
244
245
246
247
248
249
250
def register_rule(self, rule: TranslationRule) -> None:
    """Register a translation rule.

    Args:
        rule: Rule to register.
    """
    self.rules.append(rule)

translate(graph, rule_filter=None)

Translate a program graph using iterative rule application.

Rules are applied in repeated passes until a pass produces no new mappings or max_iterations is reached, whichever comes first. Because rules do not consume prior mappings, this is single-pass rule application followed by one idempotent confirmation pass (the second pass re-runs the rules and is expected to add nothing) — it is NOT a semantic fixpoint. After the loop exits, conflict resolution picks a single winning mapping per node set using priority then confidence as the tiebreaker.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to translate. Must have been built by the graph stage; in particular, GraphQuery must be constructable from it.

required
rule_filter list[str] | None

Optional list of rule names to apply. None (default) applies every registered rule. Pass a subset to run a targeted translation, e.g. for unit tests or the cogant explain single-node path.

None

Returns:

Type Description
list[SemanticMapping]

List of SemanticMapping instances kept after conflict

list[SemanticMapping]

resolution, in insertion order. May be empty if no rule

list[SemanticMapping]

matched.

Raises:

Type Description
RuntimeError

If a registered rule raises an unhandled exception. The engine catches and logs per-rule errors but re-raises engine-level invariant violations.

Example

engine = TranslationEngine() engine.register_rule(ObservationRule()) mappings = engine.translate(graph) all(hasattr(m.kind, "name") for m in mappings) True

Source code in py/cogant/translate/engine.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def translate(
    self,
    graph: ProgramGraph,
    rule_filter: list[str] | None = None,
) -> list[SemanticMapping]:
    """Translate a program graph using iterative rule application.

    Rules are applied in repeated passes until a pass produces no new
    mappings or ``max_iterations`` is reached, whichever comes first.
    Because rules do not consume prior mappings, this is single-pass
    rule application followed by one idempotent confirmation pass
    (the second pass re-runs the rules and is expected to add nothing)
    — it is NOT a semantic fixpoint. After the loop exits, conflict
    resolution picks a single winning mapping per node set using
    priority then confidence as the tiebreaker.

    Args:
        graph: Program graph to translate. Must have been built by
            the graph stage; in particular, ``GraphQuery`` must be
            constructable from it.
        rule_filter: Optional list of rule names to apply. ``None``
            (default) applies every registered rule. Pass a subset
            to run a targeted translation, e.g. for unit tests or
            the ``cogant explain`` single-node path.

    Returns:
        List of ``SemanticMapping`` instances kept after conflict
        resolution, in insertion order. May be empty if no rule
        matched.

    Raises:
        RuntimeError: If a registered rule raises an unhandled
            exception. The engine catches and logs per-rule errors
            but re-raises engine-level invariant violations.

    Example:
        >>> engine = TranslationEngine()
        >>> engine.register_rule(ObservationRule())
        >>> mappings = engine.translate(graph)
        >>> all(hasattr(m.kind, "name") for m in mappings)
        True
    """
    self.mappings.clear()
    self._match_log.clear()
    self._rule_priority.clear()
    self._convergence_iteration = None
    self.iterations = []

    n_nodes = len(graph.nodes)
    n_edges = len(graph.edges)
    active_rules = (
        [r for r in self.rules if r.name in rule_filter] if rule_filter else self.rules
    )
    logger.info(
        "Starting translation: %d rules active, %d nodes, %d edges%s",
        len(active_rules),
        n_nodes,
        n_edges,
        f" (filtered to {rule_filter})" if rule_filter else "",
    )

    query = GraphQuery(graph)

    for iteration in range(1, self.max_iterations + 1):
        logger.debug(
            "Translation pass %d starting (%d existing mappings)",
            iteration,
            len(self.mappings),
        )

        new_mappings_this_pass = self._apply_single_pass(
            graph, query, rule_filter=rule_filter, iteration=iteration
        )

        self.iterations.append(
            {
                "iteration": iteration,
                "new_mappings": new_mappings_this_pass,
                "mappings_added": new_mappings_this_pass,
            }
        )

        self._log_match(
            "iteration_complete",
            "engine",
            f"iteration={iteration} new_mappings={new_mappings_this_pass}",
        )
        logger.info("Translation pass %d: %d new mappings", iteration, new_mappings_this_pass)

        if new_mappings_this_pass == 0:
            logger.info(
                "Idempotence confirmed (no new mappings) after %d pass(es); "
                "not a semantic fixpoint",
                iteration,
            )
            self._convergence_iteration = iteration
            break
    else:
        logger.warning(
            "Max passes (%d) reached without an idempotent (zero-new-mapping) pass",
            self.max_iterations,
        )

    # Resolve conflicts among overlapping mappings
    conflicts_before = len(self.mappings)
    self._resolve_conflicts()
    conflicts_removed = conflicts_before - len(self.mappings)
    if conflicts_removed > 0:
        logger.info(
            "Conflict resolution: removed %d overlapping mappings (%d → %d)",
            conflicts_removed,
            conflicts_before,
            len(self.mappings),
        )

    # Log per-kind role distribution
    by_kind: dict[str, int] = {}
    for mapping in self.mappings.values():
        kind = mapping.kind.value
        by_kind[kind] = by_kind.get(kind, 0) + 1
    logger.info(
        "Translation complete: %d mappings across %d roles%s",
        len(self.mappings),
        len(by_kind),
        f" ({', '.join(f'{k}={v}' for k, v in sorted(by_kind.items()))})" if by_kind else "",
    )

    # Log coverage summary
    coverage = self.get_coverage_report(graph)
    logger.info(
        "Node coverage: %.1f%% (%d/%d covered, %d uncovered)",
        coverage["coverage_percent"],
        coverage["covered_nodes"],
        coverage["total_nodes"],
        coverage["uncovered_nodes"],
    )

    return list(self.mappings.values())

translate_with_confidence(graph, rule_filter=None)

Translate and rescore all mappings using the ConfidenceModel.

Runs the standard iterative-pass translation, then applies the ConfidenceModel to update confidence scores, tiers, and conflict penalties on every resulting mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to translate.

required
rule_filter list[str] | None

Optional list of rule names to apply (None = all).

None

Returns:

Type Description
list[SemanticMapping]

List of semantic mappings with updated confidence scores.

Source code in py/cogant/translate/engine.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def translate_with_confidence(
    self,
    graph: ProgramGraph,
    rule_filter: list[str] | None = None,
) -> list[SemanticMapping]:
    """Translate and rescore all mappings using the ConfidenceModel.

    Runs the standard iterative-pass translation, then applies the
    ConfidenceModel to update confidence scores, tiers, and
    conflict penalties on every resulting mapping.

    Args:
        graph: Program graph to translate.
        rule_filter: Optional list of rule names to apply (None = all).

    Returns:
        List of semantic mappings with updated confidence scores.
    """
    mappings = self.translate(graph, rule_filter=rule_filter)

    model = ConfidenceModel()
    model.score_batch(mappings)

    # Re-resolve conflicts now that scores are updated
    self._resolve_conflicts()

    return list(self.mappings.values())

validate()

Validate SemanticMappings for internal consistency.

Checks all mappings in :attr:mappings for: - Non-empty node IDs - Valid confidence scores (0.0–1.0) - Consistent mapping kinds - No orphaned node references (node exists in graph)

Returns:

Type Description
list[str]

List of validation issues (empty = valid). Each string

list[str]

describes one inconsistency or violation.

Source code in py/cogant/translate/engine.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def validate(self) -> list[str]:
    """Validate SemanticMappings for internal consistency.

    Checks all mappings in :attr:`mappings` for:
    - Non-empty node IDs
    - Valid confidence scores (0.0–1.0)
    - Consistent mapping kinds
    - No orphaned node references (node exists in graph)

    Returns:
        List of validation issues (empty = valid). Each string
        describes one inconsistency or violation.
    """
    issues: list[str] = []

    if not self.mappings:
        return issues  # No mappings is valid (empty graph)

    # Get all node IDs from a stored graph (if available)
    # For now, we'll validate the structure without graph reference
    for mapping_id, mapping in self.mappings.items():
        # Check non-empty node IDs
        if not mapping.graph_fragment_node_ids:
            issues.append(f"Mapping '{mapping_id}' has no node IDs in fragment")

        # Check confidence score range
        if not (0.0 <= mapping.confidence_score <= 1.0):
            issues.append(
                f"Mapping '{mapping_id}' confidence {mapping.confidence_score} "
                f"out of range [0.0, 1.0]"
            )

        # Check mapping kind is valid
        if not hasattr(mapping.kind, "value"):
            issues.append(f"Mapping '{mapping_id}' has invalid mapping kind")

        # Check consistency between confidence score and tier
        tier = mapping.confidence_tier.value
        score = mapping.confidence_score
        if tier == "STATIC_ONLY" and score < 0.5:
            issues.append(
                f"Mapping '{mapping_id}' has STATIC_ONLY tier but "
                f"confidence {score} < 0.5 (inconsistent)"
            )

    return issues

TranslationRule

Bases: ABC

Base class for translation rules.

Source code in py/cogant/translate/engine.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class TranslationRule(ABC):
    """Base class for translation rules."""

    @abstractmethod
    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Check if rule matches graph patterns.

        Args:
            graph: Program graph to analyze.
            query: Graph query engine.

        Returns:
            List of matched fragments, each with node/edge IDs.
        """
        ...

    @abstractmethod
    def apply(
        self,
        graph: ProgramGraph,
        match: dict[str, Any],
    ) -> SemanticMapping | None:
        """Apply rule to a matched pattern.

        Args:
            graph: Program graph.
            match: Matched pattern from matches().

        Returns:
            SemanticMapping if successful, None otherwise.
        """
        ...

    @property
    @abstractmethod
    def name(self) -> str:
        """Name of this rule."""
        ...

    @property
    @abstractmethod
    def mapping_kind(self) -> MappingKind:
        """Kind of semantic mapping produced."""
        ...

    @property
    def priority(self) -> int:
        """Priority of this rule (higher = applied first). Default 0.

        Rationale for default ``priority=0``:
            Most shipped rules keep the default ``0`` and are applied in
            registration order within a single translation pass.
            :class:`~cogant.translate.rules.structural.MutatingSubsystemRule`
            overrides this property to return ``1`` so class-level hidden-state
            evidence wins ties against overlapping class-scoped mappings from
            aggregate rules at equal confidence. Aside from that exception,
            conflict resolution between overlapping mappings falls through to
            the ``(priority, confidence_score)`` lexicographic comparison in
            :meth:`TranslationEngine._resolve_conflicts`. See
            ``docs/evaluation/CALIBRATION.md`` for the full rule priority audit.
            TODO(calibration): if the empirical conflict-loss rate on
            real-world repos exceeds ~5%, broaden explicit priority tiers.
        """
        return 0

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> "RuleExplanation":
        """Explain whether this rule would fire on ``node``.

        This is the default implementation used by the ``cogant explain``
        CLI subcommand. It re-runs :meth:`matches` and checks whether any
        returned match references the target node's id. Subclasses that
        can produce richer evidence (specific edge kinds, keyword hits,
        metric values) should override this method.

        The base implementation never raises: if :meth:`matches` blows
        up, the returned :class:`RuleExplanation` has ``fired=False`` and
        a reason that names the exception type so the CLI can surface it
        instead of aborting the whole explain run.

        Args:
            node: The target node whose role we want to justify.
            graph: Program graph the rule is being evaluated against.
            query: Graph query engine bound to ``graph``.

        Returns:
            A :class:`RuleExplanation` record for this (rule, node) pair.
        """
        try:
            all_matches = self.matches(graph, query)
        except (TypeError, ValueError, KeyError, AttributeError) as exc:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=f"rule error during matching: {type(exc).__name__}: {exc}",
                evidence=[],
                mapping_kind=self.mapping_kind.value,
                confidence=0.0,
                contradictions=[],
            )

        for match in all_matches:
            node_id = match.get("node_id") if isinstance(match, dict) else None
            fragment_ids: list[str] = []
            if isinstance(match, dict):
                fragment_ids = list(match.get("node_ids", []) or [])
            if node_id == node.id or node.id in fragment_ids:
                evidence: list[str] = []
                for key, value in sorted(match.items()):
                    if key in ("node_id", "node_ids"):
                        continue
                    evidence.append(f"{key}={value}")
                return RuleExplanation(
                    rule_name=self.name,
                    priority=self.priority,
                    fired=True,
                    reason=(f"rule '{self.name}' matched node {node.qualified_name or node.name}"),
                    evidence=evidence,
                    mapping_kind=self.mapping_kind.value,
                    confidence=0.75,  # default reasonable confidence
                    contradictions=[],
                )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"rule '{self.name}' considered but did not match "
                f"{node.qualified_name or node.name}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
            confidence=0.0,
            contradictions=[],
        )

mapping_kind abstractmethod property

Kind of semantic mapping produced.

name abstractmethod property

Name of this rule.

priority property

Priority of this rule (higher = applied first). Default 0.

Rationale for default priority=0: Most shipped rules keep the default 0 and are applied in registration order within a single translation pass. :class:~cogant.translate.rules.structural.MutatingSubsystemRule overrides this property to return 1 so class-level hidden-state evidence wins ties against overlapping class-scoped mappings from aggregate rules at equal confidence. Aside from that exception, conflict resolution between overlapping mappings falls through to the (priority, confidence_score) lexicographic comparison in :meth:TranslationEngine._resolve_conflicts. See docs/evaluation/CALIBRATION.md for the full rule priority audit. TODO(calibration): if the empirical conflict-loss rate on real-world repos exceeds ~5%, broaden explicit priority tiers.

apply(graph, match) abstractmethod

Apply rule to a matched pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern from matches().

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping if successful, None otherwise.

Source code in py/cogant/translate/engine.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@abstractmethod
def apply(
    self,
    graph: ProgramGraph,
    match: dict[str, Any],
) -> SemanticMapping | None:
    """Apply rule to a matched pattern.

    Args:
        graph: Program graph.
        match: Matched pattern from matches().

    Returns:
        SemanticMapping if successful, None otherwise.
    """
    ...

explain(node, graph, query)

Explain whether this rule would fire on node.

This is the default implementation used by the cogant explain CLI subcommand. It re-runs :meth:matches and checks whether any returned match references the target node's id. Subclasses that can produce richer evidence (specific edge kinds, keyword hits, metric values) should override this method.

The base implementation never raises: if :meth:matches blows up, the returned :class:RuleExplanation has fired=False and a reason that names the exception type so the CLI can surface it instead of aborting the whole explain run.

Parameters:

Name Type Description Default
node Node

The target node whose role we want to justify.

required
graph ProgramGraph

Program graph the rule is being evaluated against.

required
query GraphQuery

Graph query engine bound to graph.

required

Returns:

Name Type Description
A RuleExplanation

class:RuleExplanation record for this (rule, node) pair.

Source code in py/cogant/translate/engine.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> "RuleExplanation":
    """Explain whether this rule would fire on ``node``.

    This is the default implementation used by the ``cogant explain``
    CLI subcommand. It re-runs :meth:`matches` and checks whether any
    returned match references the target node's id. Subclasses that
    can produce richer evidence (specific edge kinds, keyword hits,
    metric values) should override this method.

    The base implementation never raises: if :meth:`matches` blows
    up, the returned :class:`RuleExplanation` has ``fired=False`` and
    a reason that names the exception type so the CLI can surface it
    instead of aborting the whole explain run.

    Args:
        node: The target node whose role we want to justify.
        graph: Program graph the rule is being evaluated against.
        query: Graph query engine bound to ``graph``.

    Returns:
        A :class:`RuleExplanation` record for this (rule, node) pair.
    """
    try:
        all_matches = self.matches(graph, query)
    except (TypeError, ValueError, KeyError, AttributeError) as exc:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=f"rule error during matching: {type(exc).__name__}: {exc}",
            evidence=[],
            mapping_kind=self.mapping_kind.value,
            confidence=0.0,
            contradictions=[],
        )

    for match in all_matches:
        node_id = match.get("node_id") if isinstance(match, dict) else None
        fragment_ids: list[str] = []
        if isinstance(match, dict):
            fragment_ids = list(match.get("node_ids", []) or [])
        if node_id == node.id or node.id in fragment_ids:
            evidence: list[str] = []
            for key, value in sorted(match.items()):
                if key in ("node_id", "node_ids"):
                    continue
                evidence.append(f"{key}={value}")
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=(f"rule '{self.name}' matched node {node.qualified_name or node.name}"),
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
                confidence=0.75,  # default reasonable confidence
                contradictions=[],
            )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(
            f"rule '{self.name}' considered but did not match "
            f"{node.qualified_name or node.name}"
        ),
        evidence=[],
        mapping_kind=self.mapping_kind.value,
        confidence=0.0,
        contradictions=[],
    )

matches(graph, query) abstractmethod

Check if rule matches graph patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph to analyze.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched fragments, each with node/edge IDs.

Source code in py/cogant/translate/engine.py
68
69
70
71
72
73
74
75
76
77
78
79
@abstractmethod
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Check if rule matches graph patterns.

    Args:
        graph: Program graph to analyze.
        query: Graph query engine.

    Returns:
        List of matched fragments, each with node/edge IDs.
    """
    ...

Confidence

Confidence scoring keeps rule decisions epistemic about the pipeline, not about code quality.

cogant.translate.confidence

Confidence scoring model for COGANT semantic mappings.

Overview

This module implements the confidence layer that sits between COGANT's translation rules (cogant.translate.rules.*) and the state-space / GNN consumers downstream. Every :class:SemanticMapping emitted by a rule carries (i) a continuous confidence score in [0, 1] and (ii) a discrete confidence tier drawn from :class:ConfidenceTier. Both are produced by :class:ConfidenceModel and form the canonical signal that downstream code (state-space compilation, conflict resolution, GNN matrix synthesis) uses to decide whether a mapping is trustworthy enough to keep, surface for review, or discard.

The model is deliberately parametric and transparent: every threshold is a class-level constant or a per-method default, every constant has an inline rationale, and every empirically-tunable constant is annotated with a TODO(calibration) marker linking it to the 20-repo calibration plan. See docs/reference/calibration_guide.md for the corpus, methodology, and per-threshold sweep ranges; see docs/evaluation/CALIBRATION.md for the parameter registry; see docs/evaluation/MUTATION_REPORT.md for the mutation-testing audit (item M9 covers the boundary semantics of this module).

Confidence-tier model

COGANT distinguishes four tiers along an evidence-quality axis:

================================ ===== ================================================ Tier (ConfidenceTier value) Floor Meaning ================================ ===== ================================================ STATIC_ONLY 0.50 Static analysis only (AST / tree-sitter); the baseline tier when no runtime evidence exists. RUNTIME_ONLY 0.40 Runtime / dynamic-trace evidence with no static corroboration. The floor is intentionally below STATIC_ONLY to reflect a -0.10 dynamic-noise discount: traces are noisier than AST edges, so we accept them at a lower absolute score. STATIC_PLUS_RUNTIME 0.65 Both static and runtime evidence present. The floor is +0.15 above STATIC_ONLY — a corroboration bonus — so corroborated mappings must clear a strictly higher bar than either source on its own. HUMAN_REVIEWED 0.90 Reviewed and approved by a human; aligned with the strong-consensus band from classical meta-analysis reporting conventions. ================================ ===== ================================================

The "three-tier model" referred to in design discussions is the evidence-source sub-hierarchy (STATIC_ONLY, RUNTIME_ONLY, STATIC_PLUS_RUNTIME); HUMAN_REVIEWED is an orthogonal override that always wins regardless of computed score (see :meth:ConfidenceModel.determine_confidence_tier).

Threshold table

The following table summarises every numeric knob owned by this module. All values are principled defaults (motivated by convention or algebraic rationale, not yet empirically fit) unless otherwise noted.

========================================== ===== ============================== ========================== Constant Value Sweep range Calibration marker ========================================== ===== ============================== ========================== STATIC_ONLY_THRESHOLD 0.50 {0.4, 0.5, 0.55, 0.6} line ~40 (class scope) STATIC_PLUS_RUNTIME_THRESHOLD 0.65 {0.55, 0.6, 0.65, 0.7} line ~40 (class scope) RUNTIME_ONLY_THRESHOLD 0.40 {0.3, 0.35, 0.4, 0.45} line ~40 (class scope) HUMAN_REVIEWED_THRESHOLD 0.90 {0.85, 0.9, 0.95} line ~40 (class scope) diversity_bonus multiplier 0.10 {0.05, 0.10, 0.15, 0.20} :meth:compute_confidence_score conflict_penalty per-conflict 0.05 {0.02, 0.05, 0.08, 0.10} :meth:compute_confidence_score divergence-flag spread 0.30 {0.2, 0.3, 0.4} :meth:detect_conflicts divergence penalty (mild) 0.10 {0.05, 0.10, 0.15} :meth:detect_conflicts static-vs-dynamic disagreement spread 0.25 {0.15, 0.20, 0.25, 0.30} :meth:detect_conflicts static-vs-dynamic disagreement penalty 0.15 {0.10, 0.15, 0.20} :meth:detect_conflicts get_high_confidence_mappings default 0.70 {0.65, 0.70, 0.75, 0.80} :meth:get_high_confidence_mappings get_low_confidence_mappings default 0.60 {0.50, 0.55, 0.60, 0.65} :meth:get_low_confidence_mappings unique-source cap (diversity normaliser) 5 not calibrated (taxonomy-fixed) :meth:score_evidence_diversity ========================================== ===== ============================== ==========================

Eight of these knobs carry a TODO(calibration) marker in this file (see docs/reference/calibration_guide.md, Confidence combiner section, for the resolution recipe).

Calibration methodology (summary)

Calibration here means threshold tuning against a labelled corpus, not model training in the machine-learning sense. The model itself (linear blend of evidence terms) is held fixed; only the scalar constants in the table above are swept. The procedure is:

  1. Corpus. Twenty repositories under cogant/tests/fixtures/repos/ (Python + JS/TS, balanced small/medium/large). Each repo has a hand-labelled gold-standard set of correct mappings under evaluation/gold_standards/ (TBD; see CALIBRATION.md §4).
  2. Sweep. For each constant, run COGANT end-to-end across the corpus with the constant pinned to each candidate value in its sweep range; collect the resulting :class:SemanticMapping population.
  3. Score. Compute precision / recall / F1 against the gold labels, plus the tier-confusion matrix. For continuous parameters (e.g. diversity_bonus) report the L2 error of the score distribution against an L1-normalised target.
  4. Pick. Choose the value at the elbow of the F1 curve. Tie-break in favour of recall for RUNTIME_ONLY_THRESHOLD (we want noisy traces to surface for review) and in favour of precision for STATIC_PLUS_RUNTIME_THRESHOLD (we want corroborated mappings to be trustworthy by default).
  5. Document. Replace the TODO(calibration) annotation with empirically validated — see CALIBRATION.md §X and update the manuscript supplement with the sweep curve.

Public surface

The module exports a single class, :class:ConfidenceModel. The relevant types are imported from :mod:cogant.schemas.semantic:

  • :class:SemanticMapping — the canonical mapping dataclass (graph fragment + semantic label + provenance, evidence_count, evidence_diversity, parser_certainty, conflict_penalties, confidence_score, confidence_tier). This is the input to every public method on :class:ConfidenceModel and is mutated in-place by :meth:ConfidenceModel.update_mapping_confidence.
  • :class:ConfidenceTier — the four-tier StrEnum described above.
  • :class:ProvenanceRecord — one piece of evidence (source, timestamp, metadata, per-source confidence). Every :class:SemanticMapping carries a list[ProvenanceRecord].

Note on naming: cogant.types.ConfidenceScore is a float type alias for documentation purposes (range [0.0, 1.0]); it is not a separate dataclass. The actual confidence data lives on :class:SemanticMapping (fields confidence_score and confidence_tier); this module's job is to compute those fields.

End-to-end flow of compute_confidence_score

For a mapping m with len(m.provenance) == n:

  1. Empty-evidence guard. If n == 0 the score is 0.0 — un-evidenced mappings are not trusted at all.
  2. Evidence base. avg_evidence = mean(p.confidence for p in m.provenance). Unweighted mean rather than max so that adding weak corroborating evidence does not artificially inflate a strong primary source.
  3. Diversity bonus. diversity_bonus = m.evidence_diversity * 0.10. evidence_diversity is precomputed by :meth:score_evidence_diversity as unique_sources / min(n, 5), capped at the five-label evidence taxonomy. The 0.10 multiplier is sized so that maximum diversity (1.0) contributes exactly one tier-gap of lift (the STATIC_ONLY→STATIC_PLUS_RUNTIME gap is 0.15, and a lone diversity bonus must not overshoot it on its own).
  4. Parser-certainty discount. certainty_factor = m.parser_certainty. This is a multiplicative reliability discount from the underlying parser (≈0.95 for full Python AST, ≈0.80 for the tree-sitter fallback band). Applying it before the conflict penalty is intentional: a noisy parser should reduce both the evidence base and any diversity bonus, but conflicts (which are signal, not noise) survive the discount.
  5. Conflict penalty. conflict_penalty = sum(m.conflict_penalties) * 0.05. The list is precomputed by :meth:detect_conflicts and contains one entry per detected conflict (0.10 for spread divergence, 0.15 for static-vs-dynamic disagreement). The 0.05 multiplier means two typical conflicts (~0.10 total before multiplication) roughly cancel a full diversity bonus.
  6. Compose and clamp. ``confidence = (avg_evidence + diversity_bonus) * certainty_factor
  7. conflict_penalty, then clamped to[0, 1]``.

The resulting score feeds :meth:determine_confidence_tier, which applies the four-tier decision tree:

  • has_human → HUMAN_REVIEWED (overrides everything).
  • has_static and has_dynamic → STATIC_PLUS_RUNTIME if score >= STATIC_PLUS_RUNTIME_THRESHOLD, otherwise fall through to STATIC_ONLY if it meets STATIC_ONLY_THRESHOLD.
  • has_dynamic and not has_static → RUNTIME_ONLY if score >= RUNTIME_ONLY_THRESHOLD.
  • has_static → STATIC_ONLY if score >= STATIC_ONLY_THRESHOLD.
  • Otherwise → STATIC_ONLY (lowest-tier fallback; the mapping is retained but flagged for downstream review).

:meth:update_mapping_confidence orchestrates all of the above: counts evidence, computes diversity, detects conflicts, computes the score, assigns the tier, and appends a record to the internal scoring log (which feeds :meth:get_scoring_report). :meth:score_batch is a trivial loop over :meth:update_mapping_confidence for ergonomic batch processing.

Cross-references

  • docs/reference/calibration_guide.md — methodology, sweep recipes, and resolution checklist for every TODO(calibration) marker in this module.
  • docs/evaluation/CALIBRATION.md — repository-wide parameter registry (§2.3 covers this module specifically).
  • docs/evaluation/MUTATION_REPORT.md — boundary-semantics audit (item M9 covers the >= / > decisions in the tier decision tree).
  • :mod:cogant.translate.rules — the rules whose mappings consume this module's output.
  • :mod:cogant.statespace.variables — the downstream consumer that collapses the four tiers into the coarser ConfidenceLevel categorical view.

ConfidenceModel

Computes and manages confidence scores for semantic mappings.

Combines evidence count, diversity, parser certainty, and conflict penalties to produce confidence tiers and scores.

Source code in py/cogant/translate/confidence.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
class ConfidenceModel:
    """Computes and manages confidence scores for semantic mappings.

    Combines evidence count, diversity, parser certainty, and conflict penalties
    to produce confidence tiers and scores.
    """

    # ------------------------------------------------------------------
    # Confidence-tier thresholds
    # ------------------------------------------------------------------
    # These four scalars carve [0, 1] into the four ConfidenceTier
    # bands used by ``determine_confidence_tier``. They are principled
    # defaults — not empirically calibrated — anchored to the
    # "weak / moderate / strong evidence" bands from classical
    # meta-analysis reporting conventions. Read them as:
    #   0.5  — minimum to accept a static-only mapping; below this the
    #          tier falls back to the lowest band.
    #   0.65 — extra-evidence promotion threshold: static-only rules
    #          with dynamic corroboration need the combined score to
    #          clear this bar (+0.15 over the static-only floor) before
    #          promotion to STATIC_PLUS_RUNTIME.
    #   0.4  — lower bar for runtime-only evidence because dynamic
    #          traces are noisier than static edges (-0.1 dynamic-noise
    #          discount relative to the static floor).
    #   0.9  — strong-consensus band for human-reviewed mappings.
    # See ``docs/evaluation/CALIBRATION.md`` for the full sweep plan.
    # TODO(calibration): sweep {0.4, 0.5, 0.55, 0.6, 0.65, 0.7} over a
    # 20+ repo fixture set and pick the precision/recall sweet spot.
    STATIC_ONLY_THRESHOLD = 0.5  # principled default
    STATIC_PLUS_RUNTIME_THRESHOLD = 0.65  # principled default (+0.15 corroboration bonus)
    RUNTIME_ONLY_THRESHOLD = 0.4  # principled default (-0.1 dynamic-noise discount)
    HUMAN_REVIEWED_THRESHOLD = 0.9  # principled default (strong-consensus band)

    def __init__(self) -> None:
        """Initialize the confidence model."""
        self._scoring_log: list[dict[str, Any]] = []

    def compute(self, mapping: SemanticMapping) -> float:
        """Convenience alias for compute_confidence_score.

        Args:
            mapping: SemanticMapping to score.

        Returns:
            Confidence score between 0.0 and 1.0.
        """
        return self.compute_confidence_score(mapping)

    def compute_confidence_score(self, mapping: SemanticMapping) -> float:
        """Compute overall confidence score from evidence and metadata.

        Args:
            mapping: SemanticMapping to score.

        Returns:
            Confidence score between 0.0 and 1.0.
        """
        if not mapping.provenance:
            return 0.0

        # Base score: unweighted average of per-provenance confidences.
        avg_evidence = sum(p.confidence for p in mapping.provenance) / len(mapping.provenance)

        # Evidence diversity bonus — multiplicative weight 0.1 = "at
        # most a 10-percentage-point reward for multi-source
        # agreement". Principled default: large enough to lift a
        # borderline mapping across the STATIC_ONLY→STATIC_PLUS_RUNTIME
        # boundary (gap=0.15) when combined with dynamic evidence, small
        # enough never to override a strong evidence base on its own.
        # TODO(calibration): sweep {0.05, 0.10, 0.15, 0.20} on the 20+
        # repo fixture set (see CALIBRATION.md).
        diversity_bonus = mapping.evidence_diversity * 0.1

        # Parser certainty factor — multiplicative discount for noisy
        # parsers (e.g. tree-sitter fallback ≈ 0.8 vs. full Python AST
        # ≈ 0.95).
        certainty_factor = mapping.parser_certainty

        # Conflict penalties — 0.05-per-conflict principled default,
        # chosen so two detected conflicts (~0.10) roughly cancel a full
        # diversity bonus. TODO(calibration): log penalty distributions
        # on the 20-repo corpus and retune.
        conflict_penalty = sum(mapping.conflict_penalties) * 0.05

        # Compose: evidence base, lifted by diversity, discounted by
        # parser certainty, reduced by conflict penalties. Clamped to
        # [0, 1] for downstream tier assignment.
        confidence = (avg_evidence + diversity_bonus) * certainty_factor - conflict_penalty
        confidence = max(0.0, min(1.0, confidence))

        return confidence

    def determine_confidence_tier(
        self,
        mapping: SemanticMapping,
        score: float | None = None,
    ) -> ConfidenceTier:
        """Determine confidence tier based on evidence sources and score.

        Args:
            mapping: SemanticMapping to tier.
            score: Optional precomputed confidence score.

        Returns:
            ConfidenceTier for the mapping.
        """
        if score is None:
            score = self.compute_confidence_score(mapping)

        # Check evidence sources
        sources = [p.source for p in mapping.provenance]

        has_static = any("static" in s for s in sources)
        has_dynamic = any("dynamic" in s or "runtime" in s for s in sources)
        has_human = any("human" in s or "review" in s for s in sources)

        # Determine tier
        if has_human:
            return ConfidenceTier.HUMAN_REVIEWED

        if has_static and has_dynamic:
            if score >= self.STATIC_PLUS_RUNTIME_THRESHOLD:
                return ConfidenceTier.STATIC_PLUS_RUNTIME
            # Fallback to lower tier
            if score >= self.STATIC_ONLY_THRESHOLD:
                return ConfidenceTier.STATIC_ONLY

        if has_dynamic and not has_static:
            if score >= self.RUNTIME_ONLY_THRESHOLD:
                return ConfidenceTier.RUNTIME_ONLY

        if has_static:
            if score >= self.STATIC_ONLY_THRESHOLD:
                return ConfidenceTier.STATIC_ONLY

        # Default to lowest tier
        return ConfidenceTier.STATIC_ONLY

    def score_evidence_diversity(self, mapping: SemanticMapping) -> float:
        """Compute diversity score of evidence sources.

        Args:
            mapping: SemanticMapping with provenance.

        Returns:
            Diversity score between 0.0 and 1.0.
        """
        if not mapping.provenance:
            return 0.0

        # Count unique source types
        sources = [p.source for p in mapping.provenance]
        unique_sources = len(set(sources))

        # Normalize by number of total evidence pieces. Cap at 5
        # distinct source types because the evidence-source taxonomy
        # currently defines exactly 5 labels
        # (static_analysis, dynamic_trace, runtime_profile, human_review,
        # llm_review). A single mapping with 5 different labels already
        # saturates the diversity bonus. TODO(calibration): revisit if
        # new evidence sources are added in P5+.
        max_unique = min(len(sources), 5)  # Cap at 5 source types for normalization
        diversity = unique_sources / max(1, max_unique)

        return min(1.0, diversity)

    def detect_conflicts(self, mapping: SemanticMapping) -> list[float]:
        """Detect and score conflicts in evidence.

        Args:
            mapping: SemanticMapping to check.

        Returns:
            List of conflict penalty scores.
        """
        penalties: list[float] = []

        if not mapping.provenance or len(mapping.provenance) < 2:
            return penalties

        # Check for confidence divergence across evidence sources. A
        # spread > 0.3 is flagged as "significant divergence" and
        # incurs a 0.10 penalty. Both thresholds are principled
        # defaults: 0.3 is larger than any two neighbouring tier gaps
        # (max gap = 0.25 between RUNTIME_ONLY and STATIC_PLUS_RUNTIME)
        # so only genuinely disagreeing sources trigger it; 0.10 makes
        # one divergence cost the same as a full diversity bonus.
        # TODO(calibration): retune on observed evidence-spread
        # distributions from the 20-repo corpus (see CALIBRATION.md).
        confidence_values = [p.confidence for p in mapping.provenance]
        max_conf = max(confidence_values)
        min_conf = min(confidence_values)

        if (max_conf - min_conf) > 0.3:
            # Significant divergence
            penalties.append(0.1)

        # Check for conflicting source types
        sources = Counter(p.source for p in mapping.provenance)
        if len(sources) > 1:
            # Multiple source types - check for major conflicts
            static_count = sum(v for k, v in sources.items() if "static" in k)
            dynamic_count = sum(v for k, v in sources.items() if "dynamic" in k or "runtime" in k)

            if static_count > 0 and dynamic_count > 0:
                # Both static and dynamic - check for agreement
                static_conf = sum(p.confidence for p in mapping.provenance if "static" in p.source)
                dynamic_conf = sum(
                    p.confidence
                    for p in mapping.provenance
                    if "dynamic" in p.source or "runtime" in p.source
                )

                static_avg = static_conf / max(1, static_count)
                dynamic_avg = dynamic_conf / max(1, dynamic_count)

                # Static vs. dynamic disagreement threshold = 0.25.
                # Principled default: equals the gap between
                # RUNTIME_ONLY (0.4) and STATIC_PLUS_RUNTIME (0.65), so
                # disagreement only triggers when the two sources would
                # land in non-adjacent tiers. The 0.15 penalty is
                # intentionally larger than the 0.10 spread penalty
                # above because a static-vs-dynamic disagreement is
                # structurally more meaningful than a within-source
                # spread. TODO(calibration): validate on the 20-repo
                # corpus.
                if abs(static_avg - dynamic_avg) > 0.25:
                    penalties.append(0.15)

        return penalties

    def update_mapping_confidence(self, mapping: SemanticMapping) -> None:
        """Update all confidence fields of a mapping in-place.

        Args:
            mapping: SemanticMapping to update.
        """
        # Count evidence
        mapping.evidence_count = len(mapping.provenance)

        # Compute diversity
        mapping.evidence_diversity = self.score_evidence_diversity(mapping)

        # Detect conflicts
        mapping.conflict_penalties = self.detect_conflicts(mapping)

        # Compute overall score
        mapping.confidence_score = self.compute_confidence_score(mapping)

        # Determine tier
        mapping.confidence_tier = self.determine_confidence_tier(mapping, mapping.confidence_score)

        # Log
        self._scoring_log.append(
            {
                "mapping_id": mapping.id,
                "confidence_score": mapping.confidence_score,
                "confidence_tier": mapping.confidence_tier.value,
                "evidence_count": mapping.evidence_count,
            }
        )

    def score_batch(self, mappings: list[SemanticMapping]) -> None:
        """Update confidence for a batch of mappings.

        Args:
            mappings: List of mappings to score.
        """
        for mapping in mappings:
            self.update_mapping_confidence(mapping)

    def get_high_confidence_mappings(
        self,
        mappings: list[SemanticMapping],
        threshold: float = 0.7,
    ) -> list[SemanticMapping]:
        """Filter mappings by minimum confidence score.

        Args:
            mappings: List of mappings.
            threshold: Minimum confidence threshold. Default 0.7 is a
                principled "trust without review" bar — safely above
                ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65) but well below
                ``HUMAN_REVIEWED_THRESHOLD`` (0.9). TODO(calibration):
                tune against observed precision on the 20-repo corpus
                (see ``docs/evaluation/CALIBRATION.md``).

        Returns:
            Filtered list of high-confidence mappings.
        """
        return [m for m in mappings if m.confidence_score >= threshold]

    def get_low_confidence_mappings(
        self,
        mappings: list[SemanticMapping],
        threshold: float = 0.6,
    ) -> list[SemanticMapping]:
        """Find mappings below confidence threshold that may need review.

        Args:
            mappings: List of mappings.
            threshold: Maximum confidence threshold. Default 0.6 is a
                principled "needs reviewer attention" bar — halfway
                between ``STATIC_ONLY_THRESHOLD`` (0.5) and
                ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65), so that
                mappings which pass the accept floor but fail the
                "corroborated" bar are surfaced for human review.
                TODO(calibration): retune against observed human-review
                false-positive rates.

        Returns:
            Filtered list of low-confidence mappings.
        """
        return [m for m in mappings if m.confidence_score < threshold]

    def get_conflicted_mappings(
        self,
        mappings: list[SemanticMapping],
    ) -> list[SemanticMapping]:
        """Find mappings with detected conflicts.

        Args:
            mappings: List of mappings.

        Returns:
            List of mappings with conflict penalties.
        """
        return [m for m in mappings if m.conflict_penalties]

    def get_scoring_report(self) -> dict[str, Any]:
        """Generate a report of confidence scoring.

        Returns:
            Dictionary with scoring statistics.
        """
        if not self._scoring_log:
            return {"total_scored": 0}

        tiers = Counter(entry["confidence_tier"] for entry in self._scoring_log)
        scores = [entry["confidence_score"] for entry in self._scoring_log]
        evidence_counts = [entry["evidence_count"] for entry in self._scoring_log]

        return {
            "total_scored": len(self._scoring_log),
            "average_confidence": sum(scores) / len(scores) if scores else 0.0,
            "min_confidence": min(scores) if scores else 0.0,
            "max_confidence": max(scores) if scores else 0.0,
            "average_evidence_count": sum(evidence_counts) / len(evidence_counts)
            if evidence_counts
            else 0,
            "tier_distribution": dict(tiers),
        }

    def clear_log(self) -> None:
        """Clear the scoring log."""
        self._scoring_log.clear()

__init__()

Initialize the confidence model.

Source code in py/cogant/translate/confidence.py
263
264
265
def __init__(self) -> None:
    """Initialize the confidence model."""
    self._scoring_log: list[dict[str, Any]] = []

clear_log()

Clear the scoring log.

Source code in py/cogant/translate/confidence.py
583
584
585
def clear_log(self) -> None:
    """Clear the scoring log."""
    self._scoring_log.clear()

compute(mapping)

Convenience alias for compute_confidence_score.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to score.

required

Returns:

Type Description
float

Confidence score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
267
268
269
270
271
272
273
274
275
276
def compute(self, mapping: SemanticMapping) -> float:
    """Convenience alias for compute_confidence_score.

    Args:
        mapping: SemanticMapping to score.

    Returns:
        Confidence score between 0.0 and 1.0.
    """
    return self.compute_confidence_score(mapping)

compute_confidence_score(mapping)

Compute overall confidence score from evidence and metadata.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to score.

required

Returns:

Type Description
float

Confidence score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def compute_confidence_score(self, mapping: SemanticMapping) -> float:
    """Compute overall confidence score from evidence and metadata.

    Args:
        mapping: SemanticMapping to score.

    Returns:
        Confidence score between 0.0 and 1.0.
    """
    if not mapping.provenance:
        return 0.0

    # Base score: unweighted average of per-provenance confidences.
    avg_evidence = sum(p.confidence for p in mapping.provenance) / len(mapping.provenance)

    # Evidence diversity bonus — multiplicative weight 0.1 = "at
    # most a 10-percentage-point reward for multi-source
    # agreement". Principled default: large enough to lift a
    # borderline mapping across the STATIC_ONLY→STATIC_PLUS_RUNTIME
    # boundary (gap=0.15) when combined with dynamic evidence, small
    # enough never to override a strong evidence base on its own.
    # TODO(calibration): sweep {0.05, 0.10, 0.15, 0.20} on the 20+
    # repo fixture set (see CALIBRATION.md).
    diversity_bonus = mapping.evidence_diversity * 0.1

    # Parser certainty factor — multiplicative discount for noisy
    # parsers (e.g. tree-sitter fallback ≈ 0.8 vs. full Python AST
    # ≈ 0.95).
    certainty_factor = mapping.parser_certainty

    # Conflict penalties — 0.05-per-conflict principled default,
    # chosen so two detected conflicts (~0.10) roughly cancel a full
    # diversity bonus. TODO(calibration): log penalty distributions
    # on the 20-repo corpus and retune.
    conflict_penalty = sum(mapping.conflict_penalties) * 0.05

    # Compose: evidence base, lifted by diversity, discounted by
    # parser certainty, reduced by conflict penalties. Clamped to
    # [0, 1] for downstream tier assignment.
    confidence = (avg_evidence + diversity_bonus) * certainty_factor - conflict_penalty
    confidence = max(0.0, min(1.0, confidence))

    return confidence

detect_conflicts(mapping)

Detect and score conflicts in evidence.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to check.

required

Returns:

Type Description
list[float]

List of conflict penalty scores.

Source code in py/cogant/translate/confidence.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def detect_conflicts(self, mapping: SemanticMapping) -> list[float]:
    """Detect and score conflicts in evidence.

    Args:
        mapping: SemanticMapping to check.

    Returns:
        List of conflict penalty scores.
    """
    penalties: list[float] = []

    if not mapping.provenance or len(mapping.provenance) < 2:
        return penalties

    # Check for confidence divergence across evidence sources. A
    # spread > 0.3 is flagged as "significant divergence" and
    # incurs a 0.10 penalty. Both thresholds are principled
    # defaults: 0.3 is larger than any two neighbouring tier gaps
    # (max gap = 0.25 between RUNTIME_ONLY and STATIC_PLUS_RUNTIME)
    # so only genuinely disagreeing sources trigger it; 0.10 makes
    # one divergence cost the same as a full diversity bonus.
    # TODO(calibration): retune on observed evidence-spread
    # distributions from the 20-repo corpus (see CALIBRATION.md).
    confidence_values = [p.confidence for p in mapping.provenance]
    max_conf = max(confidence_values)
    min_conf = min(confidence_values)

    if (max_conf - min_conf) > 0.3:
        # Significant divergence
        penalties.append(0.1)

    # Check for conflicting source types
    sources = Counter(p.source for p in mapping.provenance)
    if len(sources) > 1:
        # Multiple source types - check for major conflicts
        static_count = sum(v for k, v in sources.items() if "static" in k)
        dynamic_count = sum(v for k, v in sources.items() if "dynamic" in k or "runtime" in k)

        if static_count > 0 and dynamic_count > 0:
            # Both static and dynamic - check for agreement
            static_conf = sum(p.confidence for p in mapping.provenance if "static" in p.source)
            dynamic_conf = sum(
                p.confidence
                for p in mapping.provenance
                if "dynamic" in p.source or "runtime" in p.source
            )

            static_avg = static_conf / max(1, static_count)
            dynamic_avg = dynamic_conf / max(1, dynamic_count)

            # Static vs. dynamic disagreement threshold = 0.25.
            # Principled default: equals the gap between
            # RUNTIME_ONLY (0.4) and STATIC_PLUS_RUNTIME (0.65), so
            # disagreement only triggers when the two sources would
            # land in non-adjacent tiers. The 0.15 penalty is
            # intentionally larger than the 0.10 spread penalty
            # above because a static-vs-dynamic disagreement is
            # structurally more meaningful than a within-source
            # spread. TODO(calibration): validate on the 20-repo
            # corpus.
            if abs(static_avg - dynamic_avg) > 0.25:
                penalties.append(0.15)

    return penalties

determine_confidence_tier(mapping, score=None)

Determine confidence tier based on evidence sources and score.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to tier.

required
score float | None

Optional precomputed confidence score.

None

Returns:

Type Description
ConfidenceTier

ConfidenceTier for the mapping.

Source code in py/cogant/translate/confidence.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def determine_confidence_tier(
    self,
    mapping: SemanticMapping,
    score: float | None = None,
) -> ConfidenceTier:
    """Determine confidence tier based on evidence sources and score.

    Args:
        mapping: SemanticMapping to tier.
        score: Optional precomputed confidence score.

    Returns:
        ConfidenceTier for the mapping.
    """
    if score is None:
        score = self.compute_confidence_score(mapping)

    # Check evidence sources
    sources = [p.source for p in mapping.provenance]

    has_static = any("static" in s for s in sources)
    has_dynamic = any("dynamic" in s or "runtime" in s for s in sources)
    has_human = any("human" in s or "review" in s for s in sources)

    # Determine tier
    if has_human:
        return ConfidenceTier.HUMAN_REVIEWED

    if has_static and has_dynamic:
        if score >= self.STATIC_PLUS_RUNTIME_THRESHOLD:
            return ConfidenceTier.STATIC_PLUS_RUNTIME
        # Fallback to lower tier
        if score >= self.STATIC_ONLY_THRESHOLD:
            return ConfidenceTier.STATIC_ONLY

    if has_dynamic and not has_static:
        if score >= self.RUNTIME_ONLY_THRESHOLD:
            return ConfidenceTier.RUNTIME_ONLY

    if has_static:
        if score >= self.STATIC_ONLY_THRESHOLD:
            return ConfidenceTier.STATIC_ONLY

    # Default to lowest tier
    return ConfidenceTier.STATIC_ONLY

get_conflicted_mappings(mappings)

Find mappings with detected conflicts.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings with conflict penalties.

Source code in py/cogant/translate/confidence.py
545
546
547
548
549
550
551
552
553
554
555
556
557
def get_conflicted_mappings(
    self,
    mappings: list[SemanticMapping],
) -> list[SemanticMapping]:
    """Find mappings with detected conflicts.

    Args:
        mappings: List of mappings.

    Returns:
        List of mappings with conflict penalties.
    """
    return [m for m in mappings if m.conflict_penalties]

get_high_confidence_mappings(mappings, threshold=0.7)

Filter mappings by minimum confidence score.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required
threshold float

Minimum confidence threshold. Default 0.7 is a principled "trust without review" bar — safely above STATIC_PLUS_RUNTIME_THRESHOLD (0.65) but well below HUMAN_REVIEWED_THRESHOLD (0.9). TODO(calibration): tune against observed precision on the 20-repo corpus (see docs/evaluation/CALIBRATION.md).

0.7

Returns:

Type Description
list[SemanticMapping]

Filtered list of high-confidence mappings.

Source code in py/cogant/translate/confidence.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def get_high_confidence_mappings(
    self,
    mappings: list[SemanticMapping],
    threshold: float = 0.7,
) -> list[SemanticMapping]:
    """Filter mappings by minimum confidence score.

    Args:
        mappings: List of mappings.
        threshold: Minimum confidence threshold. Default 0.7 is a
            principled "trust without review" bar — safely above
            ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65) but well below
            ``HUMAN_REVIEWED_THRESHOLD`` (0.9). TODO(calibration):
            tune against observed precision on the 20-repo corpus
            (see ``docs/evaluation/CALIBRATION.md``).

    Returns:
        Filtered list of high-confidence mappings.
    """
    return [m for m in mappings if m.confidence_score >= threshold]

get_low_confidence_mappings(mappings, threshold=0.6)

Find mappings below confidence threshold that may need review.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings.

required
threshold float

Maximum confidence threshold. Default 0.6 is a principled "needs reviewer attention" bar — halfway between STATIC_ONLY_THRESHOLD (0.5) and STATIC_PLUS_RUNTIME_THRESHOLD (0.65), so that mappings which pass the accept floor but fail the "corroborated" bar are surfaced for human review. TODO(calibration): retune against observed human-review false-positive rates.

0.6

Returns:

Type Description
list[SemanticMapping]

Filtered list of low-confidence mappings.

Source code in py/cogant/translate/confidence.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def get_low_confidence_mappings(
    self,
    mappings: list[SemanticMapping],
    threshold: float = 0.6,
) -> list[SemanticMapping]:
    """Find mappings below confidence threshold that may need review.

    Args:
        mappings: List of mappings.
        threshold: Maximum confidence threshold. Default 0.6 is a
            principled "needs reviewer attention" bar — halfway
            between ``STATIC_ONLY_THRESHOLD`` (0.5) and
            ``STATIC_PLUS_RUNTIME_THRESHOLD`` (0.65), so that
            mappings which pass the accept floor but fail the
            "corroborated" bar are surfaced for human review.
            TODO(calibration): retune against observed human-review
            false-positive rates.

    Returns:
        Filtered list of low-confidence mappings.
    """
    return [m for m in mappings if m.confidence_score < threshold]

get_scoring_report()

Generate a report of confidence scoring.

Returns:

Type Description
dict[str, Any]

Dictionary with scoring statistics.

Source code in py/cogant/translate/confidence.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def get_scoring_report(self) -> dict[str, Any]:
    """Generate a report of confidence scoring.

    Returns:
        Dictionary with scoring statistics.
    """
    if not self._scoring_log:
        return {"total_scored": 0}

    tiers = Counter(entry["confidence_tier"] for entry in self._scoring_log)
    scores = [entry["confidence_score"] for entry in self._scoring_log]
    evidence_counts = [entry["evidence_count"] for entry in self._scoring_log]

    return {
        "total_scored": len(self._scoring_log),
        "average_confidence": sum(scores) / len(scores) if scores else 0.0,
        "min_confidence": min(scores) if scores else 0.0,
        "max_confidence": max(scores) if scores else 0.0,
        "average_evidence_count": sum(evidence_counts) / len(evidence_counts)
        if evidence_counts
        else 0,
        "tier_distribution": dict(tiers),
    }

score_batch(mappings)

Update confidence for a batch of mappings.

Parameters:

Name Type Description Default
mappings list[SemanticMapping]

List of mappings to score.

required
Source code in py/cogant/translate/confidence.py
492
493
494
495
496
497
498
499
def score_batch(self, mappings: list[SemanticMapping]) -> None:
    """Update confidence for a batch of mappings.

    Args:
        mappings: List of mappings to score.
    """
    for mapping in mappings:
        self.update_mapping_confidence(mapping)

score_evidence_diversity(mapping)

Compute diversity score of evidence sources.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping with provenance.

required

Returns:

Type Description
float

Diversity score between 0.0 and 1.0.

Source code in py/cogant/translate/confidence.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def score_evidence_diversity(self, mapping: SemanticMapping) -> float:
    """Compute diversity score of evidence sources.

    Args:
        mapping: SemanticMapping with provenance.

    Returns:
        Diversity score between 0.0 and 1.0.
    """
    if not mapping.provenance:
        return 0.0

    # Count unique source types
    sources = [p.source for p in mapping.provenance]
    unique_sources = len(set(sources))

    # Normalize by number of total evidence pieces. Cap at 5
    # distinct source types because the evidence-source taxonomy
    # currently defines exactly 5 labels
    # (static_analysis, dynamic_trace, runtime_profile, human_review,
    # llm_review). A single mapping with 5 different labels already
    # saturates the diversity bonus. TODO(calibration): revisit if
    # new evidence sources are added in P5+.
    max_unique = min(len(sources), 5)  # Cap at 5 source types for normalization
    diversity = unique_sources / max(1, max_unique)

    return min(1.0, diversity)

update_mapping_confidence(mapping)

Update all confidence fields of a mapping in-place.

Parameters:

Name Type Description Default
mapping SemanticMapping

SemanticMapping to update.

required
Source code in py/cogant/translate/confidence.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def update_mapping_confidence(self, mapping: SemanticMapping) -> None:
    """Update all confidence fields of a mapping in-place.

    Args:
        mapping: SemanticMapping to update.
    """
    # Count evidence
    mapping.evidence_count = len(mapping.provenance)

    # Compute diversity
    mapping.evidence_diversity = self.score_evidence_diversity(mapping)

    # Detect conflicts
    mapping.conflict_penalties = self.detect_conflicts(mapping)

    # Compute overall score
    mapping.confidence_score = self.compute_confidence_score(mapping)

    # Determine tier
    mapping.confidence_tier = self.determine_confidence_tier(mapping, mapping.confidence_score)

    # Log
    self._scoring_log.append(
        {
            "mapping_id": mapping.id,
            "confidence_score": mapping.confidence_score,
            "confidence_tier": mapping.confidence_tier.value,
            "evidence_count": mapping.evidence_count,
        }
    )

Review

Human-in-the-loop API for curating uncovered or low-confidence mappings.

cogant.translate.review

Review manager for semantic mapping validation and curation.

ReviewManager

Manages human review of semantic mappings.

Accepts, rejects, edits, splits, and merges mappings while tracking all provenance and changes.

Source code in py/cogant/translate/review.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class ReviewManager:
    """Manages human review of semantic mappings.

    Accepts, rejects, edits, splits, and merges mappings while tracking
    all provenance and changes.
    """

    def __init__(self) -> None:
        """Initialize the review manager."""
        self.mappings: dict[str, SemanticMapping] = {}
        self.review_history: list[dict[str, Any]] = []

    def add_mapping(self, mapping: SemanticMapping) -> None:
        """Add a mapping for potential review.

        Args:
            mapping: Mapping to add.
        """
        self.mappings[mapping.id] = mapping

    def accept_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        feedback: str | None = None,
    ) -> bool:
        """Accept a mapping as valid.

        Args:
            mapping_id: ID of mapping to accept.
            reviewer: Name of reviewer.
            feedback: Optional review feedback.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        mapping.status = "accepted"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)
        mapping.review_feedback = feedback

        # Upgrade confidence tier if human reviewed
        if mapping.confidence_tier != ConfidenceTier.HUMAN_REVIEWED:
            mapping.confidence_tier = ConfidenceTier.HUMAN_REVIEWED
            mapping.confidence_score = min(1.0, mapping.confidence_score + 0.15)

        self._log_review("accept", mapping_id, reviewer, feedback)
        return True

    def reject_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        reason: str,
    ) -> bool:
        """Reject a mapping as invalid.

        Args:
            mapping_id: ID of mapping to reject.
            reviewer: Name of reviewer.
            reason: Reason for rejection.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        mapping.status = "rejected"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)
        mapping.review_feedback = reason
        mapping.confidence_score = 0.0

        self._log_review("reject", mapping_id, reviewer, reason)
        return True

    def edit_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        updates: dict[str, Any],
    ) -> bool:
        """Edit a mapping based on review feedback.

        Args:
            mapping_id: ID of mapping to edit.
            reviewer: Name of reviewer.
            updates: Dictionary of fields to update.

        Returns:
            True if successful, False if mapping not found.
        """
        if mapping_id not in self.mappings:
            return False

        mapping = self.mappings[mapping_id]
        old_values = {}

        # Apply updates
        for key, value in updates.items():
            if hasattr(mapping, key):
                old_values[key] = getattr(mapping, key)
                setattr(mapping, key, value)

        mapping.status = "edited"
        mapping.reviewed_by = reviewer
        mapping.reviewed_at = datetime.now(UTC)

        self._log_review(
            "edit", mapping_id, reviewer, {"old_values": old_values, "new_values": updates}
        )
        return True

    def split_mapping(
        self,
        mapping_id: str,
        reviewer: str,
        split_definitions: list[dict[str, Any]],
    ) -> list[str]:
        """Split a mapping into multiple mappings.

        Args:
            mapping_id: ID of mapping to split.
            reviewer: Name of reviewer.
            split_definitions: List of definitions for new mappings.

        Returns:
            List of IDs of new mappings.
        """
        if mapping_id not in self.mappings:
            return []

        original = self.mappings[mapping_id]
        new_ids = []

        for i, definition in enumerate(split_definitions):
            new_id = f"{mapping_id}_split_{i}"

            new_mapping = SemanticMapping(
                id=new_id,
                kind=definition.get("kind", original.kind),
                graph_fragment_node_ids=definition.get("node_ids", []),
                graph_fragment_edge_ids=definition.get("edge_ids", []),
                semantic_label=definition.get("label", original.semantic_label),
                description=definition.get("description", original.description),
                confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
                status="edited",
                reviewed_by=reviewer,
                reviewed_at=datetime.now(UTC),
            )

            self.mappings[new_id] = new_mapping
            new_ids.append(new_id)

        # Mark original as split
        original.status = "split"
        original.reviewed_by = reviewer
        original.reviewed_at = datetime.now(UTC)

        self._log_review("split", mapping_id, reviewer, {"new_mappings": new_ids})
        return new_ids

    def merge_mappings(
        self,
        mapping_ids: list[str],
        reviewer: str,
        merged_definition: dict[str, Any],
    ) -> str | None:
        """Merge multiple mappings into one.

        Args:
            mapping_ids: IDs of mappings to merge.
            reviewer: Name of reviewer.
            merged_definition: Definition of merged mapping.

        Returns:
            ID of new merged mapping, or None if invalid.
        """
        # Verify all mappings exist
        for mid in mapping_ids:
            if mid not in self.mappings:
                return None

        # Create merged mapping
        merged_id = f"merged_{'_'.join(m[:8] for m in mapping_ids)}"

        # Collect all node and edge IDs
        all_node_ids = []
        all_edge_ids = []
        for mid in mapping_ids:
            mapping = self.mappings[mid]
            all_node_ids.extend(mapping.graph_fragment_node_ids)
            all_edge_ids.extend(mapping.graph_fragment_edge_ids)

        # Deduplicate
        all_node_ids = list(set(all_node_ids))
        all_edge_ids = list(set(all_edge_ids))

        merged = SemanticMapping(
            id=merged_id,
            kind=merged_definition.get("kind"),  # type: ignore[arg-type]
            graph_fragment_node_ids=all_node_ids,
            graph_fragment_edge_ids=all_edge_ids,
            semantic_label=merged_definition.get("label", "Merged Mapping"),
            description=merged_definition.get("description", ""),
            confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
            status="merged",
            reviewed_by=reviewer,
            reviewed_at=datetime.now(UTC),
        )

        self.mappings[merged_id] = merged

        # Mark originals as merged
        for mid in mapping_ids:
            self.mappings[mid].status = "merged"
            self.mappings[mid].reviewed_by = reviewer
            self.mappings[mid].reviewed_at = datetime.now(UTC)

        self._log_review("merge", ",".join(mapping_ids), reviewer, {"merged_id": merged_id})
        return merged_id

    def get_mapping_for_review(self, mapping_id: str) -> SemanticMapping | None:
        """Get a mapping for review.

        Args:
            mapping_id: ID of mapping.

        Returns:
            Mapping if found, None otherwise.
        """
        return self.mappings.get(mapping_id)

    def get_mappings_by_status(self, status: str) -> list[SemanticMapping]:
        """Get all mappings with a specific status.

        Args:
            status: Status to filter by.

        Returns:
            List of mappings with that status.
        """
        return [m for m in self.mappings.values() if m.status == status]

    def get_unreviewed_mappings(self) -> list[SemanticMapping]:
        """Get all mappings that haven't been reviewed.

        Returns:
            List of unreviewed mappings.
        """
        return [m for m in self.mappings.values() if m.status == "auto_proposed"]

    def get_review_summary(self) -> dict[str, Any]:
        """Get a summary of review status.

        Returns:
            Dictionary with review statistics.
        """
        statuses: dict[str, int] = {}
        for mapping in self.mappings.values():
            status = mapping.status
            statuses[status] = statuses.get(status, 0) + 1

        return {
            "total_mappings": len(self.mappings),
            "by_status": statuses,
            "unreviewed_count": len(self.get_unreviewed_mappings()),
            "total_review_actions": len(self.review_history),
        }

    def _log_review(self, action: str, mapping_id: str, reviewer: str, detail: Any) -> None:
        """Log a review action.

        Args:
            action: Type of review action.
            mapping_id: ID of affected mapping.
            reviewer: Name of reviewer.
            detail: Action details.
        """
        self.review_history.append(
            {
                "timestamp": datetime.now(UTC),
                "action": action,
                "mapping_id": mapping_id,
                "reviewer": reviewer,
                "detail": detail,
            }
        )

    def get_review_history(self) -> list[dict[str, Any]]:
        """Get the complete review history.

        Returns:
            List of review events.
        """
        return self.review_history.copy()

    def export_reviewed_mappings(self) -> list[SemanticMapping]:
        """Export all mappings that have been accepted or edited by reviewers.

        Returns:
            List of reviewed and approved mappings.
        """
        return [m for m in self.mappings.values() if m.status in ("accepted", "edited", "merged")]

__init__()

Initialize the review manager.

Source code in py/cogant/translate/review.py
16
17
18
19
def __init__(self) -> None:
    """Initialize the review manager."""
    self.mappings: dict[str, SemanticMapping] = {}
    self.review_history: list[dict[str, Any]] = []

accept_mapping(mapping_id, reviewer, feedback=None)

Accept a mapping as valid.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to accept.

required
reviewer str

Name of reviewer.

required
feedback str | None

Optional review feedback.

None

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def accept_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    feedback: str | None = None,
) -> bool:
    """Accept a mapping as valid.

    Args:
        mapping_id: ID of mapping to accept.
        reviewer: Name of reviewer.
        feedback: Optional review feedback.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    mapping.status = "accepted"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)
    mapping.review_feedback = feedback

    # Upgrade confidence tier if human reviewed
    if mapping.confidence_tier != ConfidenceTier.HUMAN_REVIEWED:
        mapping.confidence_tier = ConfidenceTier.HUMAN_REVIEWED
        mapping.confidence_score = min(1.0, mapping.confidence_score + 0.15)

    self._log_review("accept", mapping_id, reviewer, feedback)
    return True

add_mapping(mapping)

Add a mapping for potential review.

Parameters:

Name Type Description Default
mapping SemanticMapping

Mapping to add.

required
Source code in py/cogant/translate/review.py
21
22
23
24
25
26
27
def add_mapping(self, mapping: SemanticMapping) -> None:
    """Add a mapping for potential review.

    Args:
        mapping: Mapping to add.
    """
    self.mappings[mapping.id] = mapping

edit_mapping(mapping_id, reviewer, updates)

Edit a mapping based on review feedback.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to edit.

required
reviewer str

Name of reviewer.

required
updates dict[str, Any]

Dictionary of fields to update.

required

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def edit_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    updates: dict[str, Any],
) -> bool:
    """Edit a mapping based on review feedback.

    Args:
        mapping_id: ID of mapping to edit.
        reviewer: Name of reviewer.
        updates: Dictionary of fields to update.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    old_values = {}

    # Apply updates
    for key, value in updates.items():
        if hasattr(mapping, key):
            old_values[key] = getattr(mapping, key)
            setattr(mapping, key, value)

    mapping.status = "edited"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)

    self._log_review(
        "edit", mapping_id, reviewer, {"old_values": old_values, "new_values": updates}
    )
    return True

export_reviewed_mappings()

Export all mappings that have been accepted or edited by reviewers.

Returns:

Type Description
list[SemanticMapping]

List of reviewed and approved mappings.

Source code in py/cogant/translate/review.py
312
313
314
315
316
317
318
def export_reviewed_mappings(self) -> list[SemanticMapping]:
    """Export all mappings that have been accepted or edited by reviewers.

    Returns:
        List of reviewed and approved mappings.
    """
    return [m for m in self.mappings.values() if m.status in ("accepted", "edited", "merged")]

get_mapping_for_review(mapping_id)

Get a mapping for review.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping.

required

Returns:

Type Description
SemanticMapping | None

Mapping if found, None otherwise.

Source code in py/cogant/translate/review.py
237
238
239
240
241
242
243
244
245
246
def get_mapping_for_review(self, mapping_id: str) -> SemanticMapping | None:
    """Get a mapping for review.

    Args:
        mapping_id: ID of mapping.

    Returns:
        Mapping if found, None otherwise.
    """
    return self.mappings.get(mapping_id)

get_mappings_by_status(status)

Get all mappings with a specific status.

Parameters:

Name Type Description Default
status str

Status to filter by.

required

Returns:

Type Description
list[SemanticMapping]

List of mappings with that status.

Source code in py/cogant/translate/review.py
248
249
250
251
252
253
254
255
256
257
def get_mappings_by_status(self, status: str) -> list[SemanticMapping]:
    """Get all mappings with a specific status.

    Args:
        status: Status to filter by.

    Returns:
        List of mappings with that status.
    """
    return [m for m in self.mappings.values() if m.status == status]

get_review_history()

Get the complete review history.

Returns:

Type Description
list[dict[str, Any]]

List of review events.

Source code in py/cogant/translate/review.py
304
305
306
307
308
309
310
def get_review_history(self) -> list[dict[str, Any]]:
    """Get the complete review history.

    Returns:
        List of review events.
    """
    return self.review_history.copy()

get_review_summary()

Get a summary of review status.

Returns:

Type Description
dict[str, Any]

Dictionary with review statistics.

Source code in py/cogant/translate/review.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def get_review_summary(self) -> dict[str, Any]:
    """Get a summary of review status.

    Returns:
        Dictionary with review statistics.
    """
    statuses: dict[str, int] = {}
    for mapping in self.mappings.values():
        status = mapping.status
        statuses[status] = statuses.get(status, 0) + 1

    return {
        "total_mappings": len(self.mappings),
        "by_status": statuses,
        "unreviewed_count": len(self.get_unreviewed_mappings()),
        "total_review_actions": len(self.review_history),
    }

get_unreviewed_mappings()

Get all mappings that haven't been reviewed.

Returns:

Type Description
list[SemanticMapping]

List of unreviewed mappings.

Source code in py/cogant/translate/review.py
259
260
261
262
263
264
265
def get_unreviewed_mappings(self) -> list[SemanticMapping]:
    """Get all mappings that haven't been reviewed.

    Returns:
        List of unreviewed mappings.
    """
    return [m for m in self.mappings.values() if m.status == "auto_proposed"]

merge_mappings(mapping_ids, reviewer, merged_definition)

Merge multiple mappings into one.

Parameters:

Name Type Description Default
mapping_ids list[str]

IDs of mappings to merge.

required
reviewer str

Name of reviewer.

required
merged_definition dict[str, Any]

Definition of merged mapping.

required

Returns:

Type Description
str | None

ID of new merged mapping, or None if invalid.

Source code in py/cogant/translate/review.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def merge_mappings(
    self,
    mapping_ids: list[str],
    reviewer: str,
    merged_definition: dict[str, Any],
) -> str | None:
    """Merge multiple mappings into one.

    Args:
        mapping_ids: IDs of mappings to merge.
        reviewer: Name of reviewer.
        merged_definition: Definition of merged mapping.

    Returns:
        ID of new merged mapping, or None if invalid.
    """
    # Verify all mappings exist
    for mid in mapping_ids:
        if mid not in self.mappings:
            return None

    # Create merged mapping
    merged_id = f"merged_{'_'.join(m[:8] for m in mapping_ids)}"

    # Collect all node and edge IDs
    all_node_ids = []
    all_edge_ids = []
    for mid in mapping_ids:
        mapping = self.mappings[mid]
        all_node_ids.extend(mapping.graph_fragment_node_ids)
        all_edge_ids.extend(mapping.graph_fragment_edge_ids)

    # Deduplicate
    all_node_ids = list(set(all_node_ids))
    all_edge_ids = list(set(all_edge_ids))

    merged = SemanticMapping(
        id=merged_id,
        kind=merged_definition.get("kind"),  # type: ignore[arg-type]
        graph_fragment_node_ids=all_node_ids,
        graph_fragment_edge_ids=all_edge_ids,
        semantic_label=merged_definition.get("label", "Merged Mapping"),
        description=merged_definition.get("description", ""),
        confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
        status="merged",
        reviewed_by=reviewer,
        reviewed_at=datetime.now(UTC),
    )

    self.mappings[merged_id] = merged

    # Mark originals as merged
    for mid in mapping_ids:
        self.mappings[mid].status = "merged"
        self.mappings[mid].reviewed_by = reviewer
        self.mappings[mid].reviewed_at = datetime.now(UTC)

    self._log_review("merge", ",".join(mapping_ids), reviewer, {"merged_id": merged_id})
    return merged_id

reject_mapping(mapping_id, reviewer, reason)

Reject a mapping as invalid.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to reject.

required
reviewer str

Name of reviewer.

required
reason str

Reason for rejection.

required

Returns:

Type Description
bool

True if successful, False if mapping not found.

Source code in py/cogant/translate/review.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def reject_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    reason: str,
) -> bool:
    """Reject a mapping as invalid.

    Args:
        mapping_id: ID of mapping to reject.
        reviewer: Name of reviewer.
        reason: Reason for rejection.

    Returns:
        True if successful, False if mapping not found.
    """
    if mapping_id not in self.mappings:
        return False

    mapping = self.mappings[mapping_id]
    mapping.status = "rejected"
    mapping.reviewed_by = reviewer
    mapping.reviewed_at = datetime.now(UTC)
    mapping.review_feedback = reason
    mapping.confidence_score = 0.0

    self._log_review("reject", mapping_id, reviewer, reason)
    return True

split_mapping(mapping_id, reviewer, split_definitions)

Split a mapping into multiple mappings.

Parameters:

Name Type Description Default
mapping_id str

ID of mapping to split.

required
reviewer str

Name of reviewer.

required
split_definitions list[dict[str, Any]]

List of definitions for new mappings.

required

Returns:

Type Description
list[str]

List of IDs of new mappings.

Source code in py/cogant/translate/review.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def split_mapping(
    self,
    mapping_id: str,
    reviewer: str,
    split_definitions: list[dict[str, Any]],
) -> list[str]:
    """Split a mapping into multiple mappings.

    Args:
        mapping_id: ID of mapping to split.
        reviewer: Name of reviewer.
        split_definitions: List of definitions for new mappings.

    Returns:
        List of IDs of new mappings.
    """
    if mapping_id not in self.mappings:
        return []

    original = self.mappings[mapping_id]
    new_ids = []

    for i, definition in enumerate(split_definitions):
        new_id = f"{mapping_id}_split_{i}"

        new_mapping = SemanticMapping(
            id=new_id,
            kind=definition.get("kind", original.kind),
            graph_fragment_node_ids=definition.get("node_ids", []),
            graph_fragment_edge_ids=definition.get("edge_ids", []),
            semantic_label=definition.get("label", original.semantic_label),
            description=definition.get("description", original.description),
            confidence_tier=ConfidenceTier.HUMAN_REVIEWED,
            status="edited",
            reviewed_by=reviewer,
            reviewed_at=datetime.now(UTC),
        )

        self.mappings[new_id] = new_mapping
        new_ids.append(new_id)

    # Mark original as split
    original.status = "split"
    original.reviewed_by = reviewer
    original.reviewed_at = datetime.now(UTC)

    self._log_review("split", mapping_id, reviewer, {"new_mappings": new_ids})
    return new_ids

Rules

Rule classes are split by theme and priority:

Structural rules

cogant.translate.rules.structural

Structural translation rules.

This module is part of the :mod:cogant.translate.rules package and contains rules that recognise structural patterns in the program graph (reads, writes, containment, inheritance, pipelines). Every class in this file inherits from :class:cogant.translate.engine.TranslationRule and produces :class:cogant.schemas.semantic.SemanticMapping records with full provenance and confidence.

See :mod:cogant.translate.rules for the umbrella re-export and :doc:../../../specs/mappings/code-to-gnn for the family taxonomy.

ContainmentRule

Bases: TranslationRule

Analyzes methods within classes to extract observation vs action vs policy roles.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75). Stronger than pure-structural InheritanceRule (0.70) because it aggregates lexical evidence across 5+ methods (majority-vote classification), but weaker than per-function ObservationRule/ActionRule keyword hits (0.80+) because the class-level aggregate can mask mixed-role classes. Method-count threshold = 5 (see matches). TODO(calibration): sweep {3, 5, 8} method thresholds and the max(actions, observations) tie-breaking rule.

Source code in py/cogant/translate/rules/structural.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class ContainmentRule(TranslationRule):
    """Analyzes methods within classes to extract observation vs action vs policy roles.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75).
        Stronger than pure-structural ``InheritanceRule`` (0.70)
        because it aggregates *lexical* evidence across 5+ methods
        (majority-vote classification), but weaker than per-function
        ``ObservationRule``/``ActionRule`` keyword hits (0.80+)
        because the class-level aggregate can mask mixed-role classes.
        Method-count threshold = 5 (see ``matches``). TODO(calibration):
        sweep {3, 5, 8} method thresholds and the
        ``max(actions, observations)`` tie-breaking rule.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes with multiple methods for detailed analysis.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched containment patterns.
        """
        matches = []

        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            # Find CONTAINS edges to methods
            out_edges = graph.get_edges_from(cls.id)
            method_edges = [e for e in out_edges if e.kind == EdgeKind.CONTAINS]
            method_ids = [e.target_id for e in method_edges]

            # Method-count threshold = 5. Principled default: below
            # 5 methods a class is too small for a majority-vote
            # classification to be stable (a single method's lexical
            # signal dominates), and the per-function ObservationRule/
            # ActionRule will already fire on each method anyway. The
            # choice of 5 (rather than 3 or 10) is guided by the
            # "5 ± 2 chunking limit" (Miller 1956) as a convenient
            # small-class/large-class boundary. TODO(calibration):
            # sweep {3, 5, 8} on the 20-repo corpus.
            if len(method_ids) >= 5:
                matches.append(
                    {
                        "node_id": cls.id,
                        "method_ids": method_ids,
                        "method_count": len(method_ids),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create containment analysis mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping summarizing method roles.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        method_ids = match.get("method_ids", [])

        # Analyze method roles
        observation_methods = []
        action_methods = []
        policy_methods = []

        # Keyword lists are maintained centrally in cogant.translate.rules.keywords
        observation_keywords = OBSERVATION_KEYWORDS
        action_keywords = ACTION_KEYWORDS
        policy_keywords = POLICY_KEYWORDS

        for method_id in method_ids:
            method = graph.get_node(method_id)
            if not method:
                continue

            name_lower = method.name.lower()

            # Classify by keyword
            if any(kw in name_lower for kw in observation_keywords):
                observation_methods.append(method_id)
            elif any(kw in name_lower for kw in action_keywords):
                action_methods.append(method_id)
            elif any(kw in name_lower for kw in policy_keywords):
                policy_methods.append(method_id)

        # Infer primary role from method distribution
        primary_role = MappingKind.HIDDEN_STATE
        if len(action_methods) > len(observation_methods):
            primary_role = MappingKind.ACTION
        elif len(observation_methods) > len(action_methods):
            primary_role = MappingKind.OBSERVATION
        elif len(policy_methods) > 0:
            primary_role = MappingKind.POLICY

        mapping_id = f"cont_{node_id}_{hashlib.sha256(b'containment').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Aggregated
        # lexical evidence over 5+ methods is stronger than a pure
        # structural hint (0.70) but weaker than per-function lexical
        # hits (0.80+) because class-level majority voting can mask
        # mixed-role classes. Parser certainty 0.80 = tree-sitter
        # Python-fallback band.
        return SemanticMapping(
            id=mapping_id,
            kind=primary_role,
            graph_fragment_node_ids=[node_id] + method_ids,
            semantic_label=f"{node.name} - Containment Analysis",
            description=f"Class '{node.name}' contains {len(observation_methods)} observations, {len(action_methods)} actions, {len(policy_methods)} policies → primary role: {primary_role.value}",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={
                        "observation_methods": len(observation_methods),
                        "action_methods": len(action_methods),
                        "policy_methods": len(policy_methods),
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "containment"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.HIDDEN_STATE

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create containment analysis mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping summarizing method roles.

Source code in py/cogant/translate/rules/structural.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create containment analysis mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping summarizing method roles.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    method_ids = match.get("method_ids", [])

    # Analyze method roles
    observation_methods = []
    action_methods = []
    policy_methods = []

    # Keyword lists are maintained centrally in cogant.translate.rules.keywords
    observation_keywords = OBSERVATION_KEYWORDS
    action_keywords = ACTION_KEYWORDS
    policy_keywords = POLICY_KEYWORDS

    for method_id in method_ids:
        method = graph.get_node(method_id)
        if not method:
            continue

        name_lower = method.name.lower()

        # Classify by keyword
        if any(kw in name_lower for kw in observation_keywords):
            observation_methods.append(method_id)
        elif any(kw in name_lower for kw in action_keywords):
            action_methods.append(method_id)
        elif any(kw in name_lower for kw in policy_keywords):
            policy_methods.append(method_id)

    # Infer primary role from method distribution
    primary_role = MappingKind.HIDDEN_STATE
    if len(action_methods) > len(observation_methods):
        primary_role = MappingKind.ACTION
    elif len(observation_methods) > len(action_methods):
        primary_role = MappingKind.OBSERVATION
    elif len(policy_methods) > 0:
        primary_role = MappingKind.POLICY

    mapping_id = f"cont_{node_id}_{hashlib.sha256(b'containment').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Aggregated
    # lexical evidence over 5+ methods is stronger than a pure
    # structural hint (0.70) but weaker than per-function lexical
    # hits (0.80+) because class-level majority voting can mask
    # mixed-role classes. Parser certainty 0.80 = tree-sitter
    # Python-fallback band.
    return SemanticMapping(
        id=mapping_id,
        kind=primary_role,
        graph_fragment_node_ids=[node_id] + method_ids,
        semantic_label=f"{node.name} - Containment Analysis",
        description=f"Class '{node.name}' contains {len(observation_methods)} observations, {len(action_methods)} actions, {len(policy_methods)} policies → primary role: {primary_role.value}",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={
                    "observation_methods": len(observation_methods),
                    "action_methods": len(action_methods),
                    "policy_methods": len(policy_methods),
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find classes with multiple methods for detailed analysis.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched containment patterns.

Source code in py/cogant/translate/rules/structural.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes with multiple methods for detailed analysis.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched containment patterns.
    """
    matches = []

    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        # Find CONTAINS edges to methods
        out_edges = graph.get_edges_from(cls.id)
        method_edges = [e for e in out_edges if e.kind == EdgeKind.CONTAINS]
        method_ids = [e.target_id for e in method_edges]

        # Method-count threshold = 5. Principled default: below
        # 5 methods a class is too small for a majority-vote
        # classification to be stable (a single method's lexical
        # signal dominates), and the per-function ObservationRule/
        # ActionRule will already fire on each method anyway. The
        # choice of 5 (rather than 3 or 10) is guided by the
        # "5 ± 2 chunking limit" (Miller 1956) as a convenient
        # small-class/large-class boundary. TODO(calibration):
        # sweep {3, 5, 8} on the 20-repo corpus.
        if len(method_ids) >= 5:
            matches.append(
                {
                    "node_id": cls.id,
                    "method_ids": method_ids,
                    "method_count": len(method_ids),
                }
            )

    return matches

DataPipelineRule

Bases: TranslationRule

Maps data transformation chains to data-flow modality.

Detects functions that read from one source, transform, and write to another. Pattern: node with both READS and WRITES edges where read sources differ from write targets.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75). The "reads-from-A, writes-to-B (A≠B)" pattern is a strong structural cue for data flow, but we keep it at 0.75 rather than 0.80+ because edge-level precision is lower than name-level precision (tree-sitter occasionally over-reports READS on attribute-chain accesses). TODO(calibration): measure false-positive rate on the 20-repo corpus; if <5%, promote to 0.80.

Source code in py/cogant/translate/rules/structural.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
class DataPipelineRule(TranslationRule):
    """Maps data transformation chains to data-flow modality.

    Detects functions that read from one source, transform, and write to another.
    Pattern: node with both READS and WRITES edges where read sources differ
    from write targets.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75). The
        "reads-from-A, writes-to-B (A≠B)" pattern is a strong
        structural cue for data flow, but we keep it at 0.75 rather
        than 0.80+ because edge-level precision is lower than
        name-level precision (tree-sitter occasionally over-reports
        ``READS`` on attribute-chain accesses). TODO(calibration):
        measure false-positive rate on the 20-repo corpus; if <5%,
        promote to 0.80.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions with both read and write edges to different targets.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched data pipeline nodes.
        """
        matches = []

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            out_edges = graph.get_edges_from(node.id)

            read_edges = [e for e in out_edges if e.kind == EdgeKind.READS]
            write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]

            # Must have both reads and writes
            if not read_edges or not write_edges:
                continue

            read_targets = {e.target_id for e in read_edges}
            write_targets = {e.target_id for e in write_edges}

            # Read sources must differ from write targets (transformation, not echo)
            if read_targets != write_targets:
                matches.append(
                    {
                        "node_id": node.id,
                        "read_targets": list(read_targets),
                        "write_targets": list(write_targets),
                        "read_count": len(read_edges),
                        "write_count": len(write_edges),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create data-flow mapping for data pipeline node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for data flow.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        fragment_node_ids = (
            [node_id] + match.get("read_targets", []) + match.get("write_targets", [])
        )

        mapping_id = f"dpipe_{node_id}_{hashlib.sha256(b'data_pipeline').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Read-from-A
        # / write-to-B (A≠B) is a strong structural cue, but edge-level
        # precision is lower than name-level (tree-sitter sometimes
        # over-reports READS on attribute chains).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.DATA_FLOW,
            graph_fragment_node_ids=fragment_node_ids,
            semantic_label=f"{node.name} - Data Pipeline",
            description=f"Function '{node.name}' transforms data (reads from {match['read_count']} source(s), writes to {match['write_count']} target(s))",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={
                        "read_count": match["read_count"],
                        "write_count": match["write_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "data_pipeline"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.DATA_FLOW

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create data-flow mapping for data pipeline node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for data flow.

Source code in py/cogant/translate/rules/structural.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create data-flow mapping for data pipeline node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for data flow.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    fragment_node_ids = (
        [node_id] + match.get("read_targets", []) + match.get("write_targets", [])
    )

    mapping_id = f"dpipe_{node_id}_{hashlib.sha256(b'data_pipeline').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Read-from-A
    # / write-to-B (A≠B) is a strong structural cue, but edge-level
    # precision is lower than name-level (tree-sitter sometimes
    # over-reports READS on attribute chains).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.DATA_FLOW,
        graph_fragment_node_ids=fragment_node_ids,
        semantic_label=f"{node.name} - Data Pipeline",
        description=f"Function '{node.name}' transforms data (reads from {match['read_count']} source(s), writes to {match['write_count']} target(s))",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={
                    "read_count": match["read_count"],
                    "write_count": match["write_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find functions with both read and write edges to different targets.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched data pipeline nodes.

Source code in py/cogant/translate/rules/structural.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions with both read and write edges to different targets.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched data pipeline nodes.
    """
    matches = []

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        out_edges = graph.get_edges_from(node.id)

        read_edges = [e for e in out_edges if e.kind == EdgeKind.READS]
        write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]

        # Must have both reads and writes
        if not read_edges or not write_edges:
            continue

        read_targets = {e.target_id for e in read_edges}
        write_targets = {e.target_id for e in write_edges}

        # Read sources must differ from write targets (transformation, not echo)
        if read_targets != write_targets:
            matches.append(
                {
                    "node_id": node.id,
                    "read_targets": list(read_targets),
                    "write_targets": list(write_targets),
                    "read_count": len(read_edges),
                    "write_count": len(write_edges),
                }
            )

    return matches

InheritanceRule

Bases: TranslationRule

Maps class inheritance to inform semantic roles via base class hierarchy.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.7). Bottom band (0.70) alongside ReadOnlyInputRule and the resilience rules. Rationale: inheritance is a structural hint, not evidence — a subclass of AbstractHandler might be a controller or a test double or a stub. We use the lexical shortcut "name starts with Abstract/Base => POLICY" because Python convention strongly correlates those prefixes with abstract base classes (PEP 3119). Parser certainty 0.75 is slightly below the 0.80 edge-precision band because tree-sitter has known gaps on multi-base metaclass hierarchies. TODO(calibration): measure tier-disagreement rate vs. behavioral rules on the 20-repo corpus; if inheritance routinely gets overruled, demote to an "explanation only" rule that never writes a mapping.

Source code in py/cogant/translate/rules/structural.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
class InheritanceRule(TranslationRule):
    """Maps class inheritance to inform semantic roles via base class hierarchy.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.7)``. **Bottom band** (0.70)
        alongside ``ReadOnlyInputRule`` and the resilience rules.
        Rationale: inheritance is a structural hint, not evidence —
        a subclass of ``AbstractHandler`` might be a controller or a
        test double or a stub. We use the lexical shortcut "name
        starts with ``Abstract``/``Base`` => POLICY" because Python
        convention strongly correlates those prefixes with abstract
        base classes (PEP 3119). Parser certainty 0.75 is slightly
        below the 0.80 edge-precision band because tree-sitter has
        known gaps on multi-base metaclass hierarchies.
        TODO(calibration): measure tier-disagreement rate vs.
        behavioral rules on the 20-repo corpus; if inheritance
        routinely gets overruled, demote to an "explanation only"
        rule that never writes a mapping.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes with inheritance relationships.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched inheritance patterns.
        """
        matches = []

        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            # Find INHERITS edges from this class
            out_edges = graph.get_edges_from(cls.id)
            inherit_edges = [e for e in out_edges if e.kind == EdgeKind.INHERITS]

            if inherit_edges:
                base_ids = [e.target_id for e in inherit_edges]
                matches.append(
                    {
                        "node_id": cls.id,
                        "base_ids": base_ids,
                        "base_count": len(base_ids),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create semantic mapping based on inheritance pattern.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for inheritance-informed role.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        # Infer semantic kind from base class names
        base_ids = match.get("base_ids", [])
        inferred_kind = MappingKind.HIDDEN_STATE  # default

        # Check if abstract or interface-like
        if node.name.startswith("Abstract") or node.name.startswith("Base"):
            inferred_kind = MappingKind.POLICY

        # Otherwise check bases
        for base_id in base_ids:
            base = graph.get_node(base_id)
            if base:
                base_name_lower = base.name.lower()
                if "handler" in base_name_lower or "controller" in base_name_lower:
                    inferred_kind = MappingKind.POLICY
                    break

        mapping_id = f"inh_{node_id}_{hashlib.sha256(b'inheritance').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # Inheritance is a structural hint rather than direct evidence:
        # a subclass of ``AbstractHandler`` might be a real policy, a
        # test double, or a stub. Parser certainty 0.75 (below the
        # 0.80 tree-sitter norm) reflects known gaps on multi-base
        # metaclass hierarchies. TODO(calibration): log agreement with
        # behavioral/semantic rules; if inheritance loses >50% of
        # conflicts it should be demoted to an explanation-only rule.
        return SemanticMapping(
            id=mapping_id,
            kind=inferred_kind,
            graph_fragment_node_ids=[node_id] + base_ids,
            semantic_label=f"{node.name} - Inheritance Role",
            description=f"Class '{node.name}' inherits from {match['base_count']} base(s), mapped to {inferred_kind.value}",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                    metadata={"base_count": match["base_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.75,  # below norm: metaclass gaps
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "inheritance"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create semantic mapping based on inheritance pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for inheritance-informed role.

Source code in py/cogant/translate/rules/structural.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create semantic mapping based on inheritance pattern.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for inheritance-informed role.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    # Infer semantic kind from base class names
    base_ids = match.get("base_ids", [])
    inferred_kind = MappingKind.HIDDEN_STATE  # default

    # Check if abstract or interface-like
    if node.name.startswith("Abstract") or node.name.startswith("Base"):
        inferred_kind = MappingKind.POLICY

    # Otherwise check bases
    for base_id in base_ids:
        base = graph.get_node(base_id)
        if base:
            base_name_lower = base.name.lower()
            if "handler" in base_name_lower or "controller" in base_name_lower:
                inferred_kind = MappingKind.POLICY
                break

    mapping_id = f"inh_{node_id}_{hashlib.sha256(b'inheritance').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # Inheritance is a structural hint rather than direct evidence:
    # a subclass of ``AbstractHandler`` might be a real policy, a
    # test double, or a stub. Parser certainty 0.75 (below the
    # 0.80 tree-sitter norm) reflects known gaps on multi-base
    # metaclass hierarchies. TODO(calibration): log agreement with
    # behavioral/semantic rules; if inheritance loses >50% of
    # conflicts it should be demoted to an explanation-only rule.
    return SemanticMapping(
        id=mapping_id,
        kind=inferred_kind,
        graph_fragment_node_ids=[node_id] + base_ids,
        semantic_label=f"{node.name} - Inheritance Role",
        description=f"Class '{node.name}' inherits from {match['base_count']} base(s), mapped to {inferred_kind.value}",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
                metadata={"base_count": match["base_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.75,  # below norm: metaclass gaps
    )

matches(graph, query)

Find classes with inheritance relationships.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched inheritance patterns.

Source code in py/cogant/translate/rules/structural.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes with inheritance relationships.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched inheritance patterns.
    """
    matches = []

    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        # Find INHERITS edges from this class
        out_edges = graph.get_edges_from(cls.id)
        inherit_edges = [e for e in out_edges if e.kind == EdgeKind.INHERITS]

        if inherit_edges:
            base_ids = [e.target_id for e in inherit_edges]
            matches.append(
                {
                    "node_id": cls.id,
                    "base_ids": base_ids,
                    "base_count": len(base_ids),
                }
            )

    return matches

MutatingSubsystemRule

Bases: TranslationRule

Maps objects with frequent internal mutations to hidden-state modality.

Rule priority (audit 2026-04-09): :meth:priority returns 1 (see override below) so HIDDEN_STATE wins class-level overlaps against aggregate POLICY from :class:InheritanceRule at default priority 0 when both fire on the same CLASS node. The confidence score remains mid band (0.75): a class touched by any WRITES/MUTATES edge is a mild structural cue for hidden state, stronger than a pure read-only module (0.70) but weaker than a lexical action match (0.80) or a configuration hit (0.85+). The mutation-count threshold is deliberately >=1. TODO(calibration): sweep the threshold in {1, 2, 3} on the 20-repo corpus; a higher floor would likely raise precision at the cost of recall on under-instrumented fixtures.

Source code in py/cogant/translate/rules/structural.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
class MutatingSubsystemRule(TranslationRule):
    """Maps objects with frequent internal mutations to hidden-state modality.

    Rule priority (audit 2026-04-09):
        :meth:`priority` returns ``1`` (see override below) so
        ``HIDDEN_STATE`` wins class-level overlaps against aggregate
        ``POLICY`` from :class:`InheritanceRule` at default priority ``0``
        when both fire on the same ``CLASS`` node. The confidence score
        remains **mid band** (0.75): a class touched by any
        ``WRITES``/``MUTATES`` edge is a mild structural cue for hidden
        state, stronger than a pure read-only module (0.70) but weaker
        than a lexical action match (0.80) or a configuration hit
        (0.85+). The mutation-count threshold is deliberately ``>=1``.
        TODO(calibration): sweep the threshold in {1, 2, 3} on the
        20-repo corpus; a higher floor would likely raise precision at
        the cost of recall on under-instrumented fixtures.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find objects/classes with high mutation frequency.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched class/object nodes.
        """
        matches = []

        # Find all classes
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for cls in classes:
            # Count mutations (WRITES and MUTATES edges targeting this class)
            mutation_edges = []
            for edge in graph.edges.values():
                if (edge.target_id == cls.id or edge.source_id == cls.id) and edge.kind in (
                    EdgeKind.WRITES,
                    EdgeKind.MUTATES,
                ):
                    mutation_edges.append(edge)

            # Mutation-count threshold >=1. Principled default: any
            # mutation edge counts, because classes with internal state
            # are typically bursty (rare mutations between long read
            # phases) and a higher floor (e.g. >=3) would miss lazy
            # singletons and state machines with a single setter. The
            # downstream confidence gate (0.75 band) prevents false
            # positives on incidental ``__init__`` assignments.
            # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus.
            if len(mutation_edges) >= 1:
                matches.append(
                    {
                        "node_id": cls.id,
                        "mutation_count": len(mutation_edges),
                        "mutation_edges": [e.id for e in mutation_edges],
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create hidden-state mapping for mutating subsystem.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for hidden-state.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"hs_{node_id}_{hashlib.sha256(b'mutating_subsystem').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Any
        # ``WRITES``/``MUTATES`` edge on a class is a mild structural
        # cue for hidden state: stronger than a pure read-only module
        # (0.70) but weaker than a lexical action match (0.80) or a
        # config hit (0.85+). Parser certainty 0.80 = tree-sitter
        # Python-fallback band (edge extraction is less precise than
        # name extraction, hence below the 0.85–0.90 AST-native band).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.HIDDEN_STATE,
            graph_fragment_node_ids=[node_id],
            graph_fragment_edge_ids=match.get("mutation_edges", []),
            semantic_label=f"{node.name} - Hidden State",
            description=f"Class '{node.name}' maintains internal state (frequent mutations)",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={"mutation_count": match["mutation_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this class is a hidden-state / mutating subsystem.

        The rule only applies to ``CLASS`` nodes and fires when the class
        has at least one edge of kind ``WRITES`` or ``MUTATES`` touching
        it (either as source or as target). This mirrors the match logic
        in :meth:`matches` so the explain report stays honest.
        """
        if node.kind != NodeKind.CLASS:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"mutating_subsystem rule only applies to classes; "
                    f"node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        mutation_edges = []
        for edge in graph.edges.values():
            if (edge.target_id == node.id or edge.source_id == node.id) and edge.kind in (
                EdgeKind.WRITES,
                EdgeKind.MUTATES,
            ):
                mutation_edges.append(edge)

        evidence: list[str] = [
            f"mutation edges (WRITES|MUTATES) touching class: {len(mutation_edges)}",
        ]
        if mutation_edges:
            sample = [f"{e.kind.value}:{e.source_id}->{e.target_id}" for e in mutation_edges[:5]]
            evidence.append(f"sample: {sample}")

        if len(mutation_edges) >= 1:
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=(
                    f"class '{node.name}' has {len(mutation_edges)} "
                    f"WRITES/MUTATES edge(s), indicating internal state"
                ),
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(f"class '{node.name}' has no WRITES/MUTATES edges"),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "mutating_subsystem"

    @property
    def priority(self) -> int:
        """Above class-level aggregate rules (e.g. ``ContainmentRule`` at 0).

        ``ContainmentRule`` can emit a class-scoped mapping that overlaps the
        same ``CLASS`` node as this rule. Equal ``(priority, confidence)``
        ties previously dropped the hidden-state mapping lexicographically.
        Hidden-state evidence from WRITES/MUTATES edges should win that tie.
        """
        return 1

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.HIDDEN_STATE

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

priority property

Above class-level aggregate rules (e.g. ContainmentRule at 0).

ContainmentRule can emit a class-scoped mapping that overlaps the same CLASS node as this rule. Equal (priority, confidence) ties previously dropped the hidden-state mapping lexicographically. Hidden-state evidence from WRITES/MUTATES edges should win that tie.

apply(graph, match)

Create hidden-state mapping for mutating subsystem.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for hidden-state.

Source code in py/cogant/translate/rules/structural.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create hidden-state mapping for mutating subsystem.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for hidden-state.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"hs_{node_id}_{hashlib.sha256(b'mutating_subsystem').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Any
    # ``WRITES``/``MUTATES`` edge on a class is a mild structural
    # cue for hidden state: stronger than a pure read-only module
    # (0.70) but weaker than a lexical action match (0.80) or a
    # config hit (0.85+). Parser certainty 0.80 = tree-sitter
    # Python-fallback band (edge extraction is less precise than
    # name extraction, hence below the 0.85–0.90 AST-native band).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.HIDDEN_STATE,
        graph_fragment_node_ids=[node_id],
        graph_fragment_edge_ids=match.get("mutation_edges", []),
        semantic_label=f"{node.name} - Hidden State",
        description=f"Class '{node.name}' maintains internal state (frequent mutations)",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={"mutation_count": match["mutation_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

explain(node, graph, query)

Explain whether this class is a hidden-state / mutating subsystem.

The rule only applies to CLASS nodes and fires when the class has at least one edge of kind WRITES or MUTATES touching it (either as source or as target). This mirrors the match logic in :meth:matches so the explain report stays honest.

Source code in py/cogant/translate/rules/structural.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this class is a hidden-state / mutating subsystem.

    The rule only applies to ``CLASS`` nodes and fires when the class
    has at least one edge of kind ``WRITES`` or ``MUTATES`` touching
    it (either as source or as target). This mirrors the match logic
    in :meth:`matches` so the explain report stays honest.
    """
    if node.kind != NodeKind.CLASS:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"mutating_subsystem rule only applies to classes; "
                f"node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    mutation_edges = []
    for edge in graph.edges.values():
        if (edge.target_id == node.id or edge.source_id == node.id) and edge.kind in (
            EdgeKind.WRITES,
            EdgeKind.MUTATES,
        ):
            mutation_edges.append(edge)

    evidence: list[str] = [
        f"mutation edges (WRITES|MUTATES) touching class: {len(mutation_edges)}",
    ]
    if mutation_edges:
        sample = [f"{e.kind.value}:{e.source_id}->{e.target_id}" for e in mutation_edges[:5]]
        evidence.append(f"sample: {sample}")

    if len(mutation_edges) >= 1:
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=(
                f"class '{node.name}' has {len(mutation_edges)} "
                f"WRITES/MUTATES edge(s), indicating internal state"
            ),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(f"class '{node.name}' has no WRITES/MUTATES edges"),
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find objects/classes with high mutation frequency.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched class/object nodes.

Source code in py/cogant/translate/rules/structural.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find objects/classes with high mutation frequency.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched class/object nodes.
    """
    matches = []

    # Find all classes
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for cls in classes:
        # Count mutations (WRITES and MUTATES edges targeting this class)
        mutation_edges = []
        for edge in graph.edges.values():
            if (edge.target_id == cls.id or edge.source_id == cls.id) and edge.kind in (
                EdgeKind.WRITES,
                EdgeKind.MUTATES,
            ):
                mutation_edges.append(edge)

        # Mutation-count threshold >=1. Principled default: any
        # mutation edge counts, because classes with internal state
        # are typically bursty (rare mutations between long read
        # phases) and a higher floor (e.g. >=3) would miss lazy
        # singletons and state machines with a single setter. The
        # downstream confidence gate (0.75 band) prevents false
        # positives on incidental ``__init__`` assignments.
        # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus.
        if len(mutation_edges) >= 1:
            matches.append(
                {
                    "node_id": cls.id,
                    "mutation_count": len(mutation_edges),
                    "mutation_edges": [e.id for e in mutation_edges],
                }
            )

    return matches

ReadOnlyInputRule

Bases: TranslationRule

Maps modules with many read-only external inputs to observation modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.7) via the flat-priority=0 design documented in :class:TranslationRule.priority, so conflict resolution falls through to confidence_score = 0.7. This places the rule in the bottom band (0.70) alongside InheritanceRule, RetryPatternRule, ErrorBoundaryRule and the ObservationRule lexical-fallback branch. Rationale: module-level "all reads, no writes" is a weak structural signal (modules nearly always expose some read API), so it should cleanly lose to any function/method-level rule that also fires on the same fragment. TODO(calibration): measure the ReadOnlyInputRule→ObservationRule conflict-loss rate on the 20-repo corpus and promote to a dedicated priority tier only if the loss rate exceeds ~20%.

Source code in py/cogant/translate/rules/structural.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class ReadOnlyInputRule(TranslationRule):
    """Maps modules with many read-only external inputs to observation modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.7)`` via the flat-``priority=0`` design
        documented in :class:`TranslationRule.priority`, so conflict
        resolution falls through to ``confidence_score = 0.7``. This
        places the rule in the **bottom band** (0.70) alongside
        ``InheritanceRule``, ``RetryPatternRule``, ``ErrorBoundaryRule``
        and the ``ObservationRule`` lexical-fallback branch. Rationale:
        module-level "all reads, no writes" is a weak structural signal
        (modules nearly always expose some read API), so it should
        cleanly lose to any function/method-level rule that also fires
        on the same fragment. TODO(calibration): measure the
        ReadOnlyInputRule→ObservationRule conflict-loss rate on the
        20-repo corpus and promote to a dedicated priority tier only
        if the loss rate exceeds ~20%.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find modules with predominance of read operations.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched module nodes.
        """
        matches = []

        # Find all modules
        modules = graph.get_nodes_by_kind(NodeKind.MODULE)

        for module in modules:
            # Get all edges from module
            outgoing_edges = graph.get_edges_from(module.id)
            graph.get_edges_to(module.id)

            # Count read vs write operations
            reads = sum(1 for e in outgoing_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in outgoing_edges if e.kind == EdgeKind.WRITES)

            # Check if predominantly read-only
            if reads > 0 and writes == 0:
                matches.append(
                    {
                        "node_id": module.id,
                        "read_count": reads,
                        "write_count": writes,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation mapping for read-only module.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for observation modality.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"obs_{node_id}_{hashlib.sha256(b'read_only_input').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band). Module-level
        # "reads only" is a weak structural cue (modules almost always
        # export some read API), so this rule is intentionally beaten by
        # any higher-confidence function/method-level rule that fires on
        # the same fragment. 0.70 lands at STATIC_ONLY_THRESHOLD+0.20 in
        # ConfidenceModel, keeping the mapping acceptable on its own.
        # Parser certainty 0.80 = tree-sitter Python-fallback band.
        # TODO(calibration): retune against per-module precision on the
        # 20-repo fixture set.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Read-Only Input",
            description=f"Module '{node.name}' acts as observation source (read-only external input)",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                    metadata={"read_count": match["read_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "read_only_input"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation mapping for read-only module.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for observation modality.

Source code in py/cogant/translate/rules/structural.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation mapping for read-only module.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for observation modality.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"obs_{node_id}_{hashlib.sha256(b'read_only_input').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band). Module-level
    # "reads only" is a weak structural cue (modules almost always
    # export some read API), so this rule is intentionally beaten by
    # any higher-confidence function/method-level rule that fires on
    # the same fragment. 0.70 lands at STATIC_ONLY_THRESHOLD+0.20 in
    # ConfidenceModel, keeping the mapping acceptable on its own.
    # Parser certainty 0.80 = tree-sitter Python-fallback band.
    # TODO(calibration): retune against per-module precision on the
    # 20-repo fixture set.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Read-Only Input",
        description=f"Module '{node.name}' acts as observation source (read-only external input)",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
                metadata={"read_count": match["read_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find modules with predominance of read operations.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched module nodes.

Source code in py/cogant/translate/rules/structural.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find modules with predominance of read operations.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched module nodes.
    """
    matches = []

    # Find all modules
    modules = graph.get_nodes_by_kind(NodeKind.MODULE)

    for module in modules:
        # Get all edges from module
        outgoing_edges = graph.get_edges_from(module.id)
        graph.get_edges_to(module.id)

        # Count read vs write operations
        reads = sum(1 for e in outgoing_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in outgoing_edges if e.kind == EdgeKind.WRITES)

        # Check if predominantly read-only
        if reads > 0 and writes == 0:
            matches.append(
                {
                    "node_id": module.id,
                    "read_count": reads,
                    "write_count": writes,
                }
            )

    return matches

Semantic rules

cogant.translate.rules.semantic

Semantic translation rules.

This module is part of the :mod:cogant.translate.rules package and contains rules that produce direct semantic-role mappings (observation, action, policy, preference, context). Every class in this file inherits from :class:cogant.translate.engine.TranslationRule and produces :class:cogant.schemas.semantic.SemanticMapping records with full provenance and confidence.

See :mod:cogant.translate.rules for the umbrella re-export and :doc:../../../specs/mappings/code-to-gnn for the family taxonomy.

ActionRule

Bases: TranslationRule

Maps setter/mutator functions to action modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80) alongside PolicyRule, ContextRule, OrchestratorRule and CircuitBreakerRule. Rationale: action semantics are slightly less specific than PreferenceRule/TestAssertionRule (0.85) because CRUD verbs are the most overloaded lexical category in real codebases. The edge-based fallback writes_only >= 2 was added (commit e1eb463) to recover recall on functional codebases where writes are named apply/reduce rather than set/update. TODO(calibration): sweep the >=2 writes threshold in {1, 2, 3} on the 20-repo corpus.

Source code in py/cogant/translate/rules/semantic.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
class ActionRule(TranslationRule):
    """Maps setter/mutator functions to action modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80)
        alongside ``PolicyRule``, ``ContextRule``, ``OrchestratorRule``
        and ``CircuitBreakerRule``. Rationale: action semantics are
        slightly less specific than ``PreferenceRule``/``TestAssertionRule``
        (0.85) because CRUD verbs are the most overloaded lexical
        category in real codebases. The edge-based fallback
        ``writes_only >= 2`` was added (commit e1eb463) to recover
        recall on functional codebases where writes are named
        ``apply``/``reduce`` rather than ``set``/``update``.
        TODO(calibration): sweep the ``>=2`` writes threshold in
        {1, 2, 3} on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions/methods that mutate state.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched action functions/methods.
        """
        matches = []
        action_keywords = ACTION_KEYWORDS

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            # Token-anchored keyword match (no raw substring containment).
            keyword_match = _matches_keyword(node.name, action_keywords)

            # Count mutations (also used as edge-based fallback trigger)
            out_edges = graph.get_edges_from(node.id)
            writes = sum(1 for e in out_edges if e.kind in (EdgeKind.WRITES, EdgeKind.MUTATES))
            calls = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

            # Fallback threshold: ``writes >= 1`` outgoing WRITES/MUTATES
            # edge. Principled default aligned with the property invariant
            # in ``tests/property/test_translation_invariants.py`` which
            # accepts a single mutation edge as valid structural grounding
            # for the ACTION role. A ``>=2`` floor would reject legitimate
            # mutators whose static graph collapses multiple ``self.X``
            # writes into a single edge to the parent class node (a known
            # tree-sitter Python behaviour on ``self`` attribute writes).
            # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus if
            # false-positive rate on functional codebases exceeds ~5%.
            if keyword_match or writes >= 1:
                matches.append(
                    {
                        "node_id": node.id,
                        "write_count": writes,
                        "call_count": calls,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create action mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for action.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"act_{node_id}_{hashlib.sha256(b'action').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band). Action
        # verbs are slightly overloaded in practice (CRUD terms appear
        # in helpers and wrappers), hence 0.05 below the 0.85 band of
        # ``PreferenceRule``/``TestAssertionRule``. Parser certainty
        # 0.85 = full AST-native band (names + edges both parsed by
        # Python AST, not the tree-sitter fallback).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ACTION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Action",
            description=f"Function/method '{node.name}' performs action (mutates state)",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={
                        "write_count": match["write_count"],
                        "call_count": match["call_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this node performs an action.

        Mirrors the :meth:`matches` decision by checking for action
        keywords in the node name and counting outgoing WRITES/MUTATES
        edges. The rule fires when either (a) the name contains an
        action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge
        exists (the functional-codebase recall threshold).
        """
        if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"action rule only applies to functions/methods; node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        matched_keywords = _matched_keywords(node.name, ACTION_KEYWORDS)

        out_edges = graph.get_edges_from(node.id)
        write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]
        mutate_edges = [e for e in out_edges if e.kind == EdgeKind.MUTATES]
        call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        evidence: list[str] = []
        if matched_keywords:
            evidence.append(f"keyword match: {matched_keywords}")
        evidence.append(f"WRITES count: {len(write_edges)}")
        if mutate_edges:
            evidence.append(f"MUTATES count: {len(mutate_edges)}")
        evidence.append(f"CALLS count: {len(call_edges)}")
        if write_edges:
            write_targets = [e.target_id for e in write_edges]
            evidence.append(f"WRITES targets: {sorted(write_targets)[:5]}")

        keyword_match = bool(matched_keywords)
        mutation_count = len(write_edges) + len(mutate_edges)
        writes_threshold = mutation_count >= 1

        if keyword_match or writes_threshold:
            if keyword_match and writes_threshold:
                reason = (
                    f"name contains action keyword(s) {matched_keywords} "
                    f"AND has {mutation_count} WRITES/MUTATES edge(s) "
                    f"(>=1 threshold)"
                )
            elif keyword_match:
                reason = f"name contains action keyword(s) {matched_keywords}"
            else:
                reason = (
                    f"has {mutation_count} WRITES/MUTATES edge(s) "
                    f"(>=1 mutation threshold) with no action keyword"
                )
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=reason,
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"no action keyword in '{node.name}' and "
                f"{mutation_count} WRITES/MUTATES edges (<1 threshold)"
            ),
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "action"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ACTION

    def to_gnn_role(self) -> str:
        """Return the GNN role string for action mappings.

        Returns:
            GNN role identifier.
        """
        return "ACTION"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create action mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for action.

Source code in py/cogant/translate/rules/semantic.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create action mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for action.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"act_{node_id}_{hashlib.sha256(b'action').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band). Action
    # verbs are slightly overloaded in practice (CRUD terms appear
    # in helpers and wrappers), hence 0.05 below the 0.85 band of
    # ``PreferenceRule``/``TestAssertionRule``. Parser certainty
    # 0.85 = full AST-native band (names + edges both parsed by
    # Python AST, not the tree-sitter fallback).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ACTION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Action",
        description=f"Function/method '{node.name}' performs action (mutates state)",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={
                    "write_count": match["write_count"],
                    "call_count": match["call_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

explain(node, graph, query)

Explain whether this node performs an action.

Mirrors the :meth:matches decision by checking for action keywords in the node name and counting outgoing WRITES/MUTATES edges. The rule fires when either (a) the name contains an action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge exists (the functional-codebase recall threshold).

Source code in py/cogant/translate/rules/semantic.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this node performs an action.

    Mirrors the :meth:`matches` decision by checking for action
    keywords in the node name and counting outgoing WRITES/MUTATES
    edges. The rule fires when either (a) the name contains an
    action keyword, or (b) at least 1 outgoing WRITES/MUTATES edge
    exists (the functional-codebase recall threshold).
    """
    if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"action rule only applies to functions/methods; node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    matched_keywords = _matched_keywords(node.name, ACTION_KEYWORDS)

    out_edges = graph.get_edges_from(node.id)
    write_edges = [e for e in out_edges if e.kind == EdgeKind.WRITES]
    mutate_edges = [e for e in out_edges if e.kind == EdgeKind.MUTATES]
    call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

    evidence: list[str] = []
    if matched_keywords:
        evidence.append(f"keyword match: {matched_keywords}")
    evidence.append(f"WRITES count: {len(write_edges)}")
    if mutate_edges:
        evidence.append(f"MUTATES count: {len(mutate_edges)}")
    evidence.append(f"CALLS count: {len(call_edges)}")
    if write_edges:
        write_targets = [e.target_id for e in write_edges]
        evidence.append(f"WRITES targets: {sorted(write_targets)[:5]}")

    keyword_match = bool(matched_keywords)
    mutation_count = len(write_edges) + len(mutate_edges)
    writes_threshold = mutation_count >= 1

    if keyword_match or writes_threshold:
        if keyword_match and writes_threshold:
            reason = (
                f"name contains action keyword(s) {matched_keywords} "
                f"AND has {mutation_count} WRITES/MUTATES edge(s) "
                f"(>=1 threshold)"
            )
        elif keyword_match:
            reason = f"name contains action keyword(s) {matched_keywords}"
        else:
            reason = (
                f"has {mutation_count} WRITES/MUTATES edge(s) "
                f"(>=1 mutation threshold) with no action keyword"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=(
            f"no action keyword in '{node.name}' and "
            f"{mutation_count} WRITES/MUTATES edges (<1 threshold)"
        ),
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find functions/methods that mutate state.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched action functions/methods.

Source code in py/cogant/translate/rules/semantic.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions/methods that mutate state.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched action functions/methods.
    """
    matches = []
    action_keywords = ACTION_KEYWORDS

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        # Token-anchored keyword match (no raw substring containment).
        keyword_match = _matches_keyword(node.name, action_keywords)

        # Count mutations (also used as edge-based fallback trigger)
        out_edges = graph.get_edges_from(node.id)
        writes = sum(1 for e in out_edges if e.kind in (EdgeKind.WRITES, EdgeKind.MUTATES))
        calls = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

        # Fallback threshold: ``writes >= 1`` outgoing WRITES/MUTATES
        # edge. Principled default aligned with the property invariant
        # in ``tests/property/test_translation_invariants.py`` which
        # accepts a single mutation edge as valid structural grounding
        # for the ACTION role. A ``>=2`` floor would reject legitimate
        # mutators whose static graph collapses multiple ``self.X``
        # writes into a single edge to the parent class node (a known
        # tree-sitter Python behaviour on ``self`` attribute writes).
        # TODO(calibration): sweep {1, 2, 3} on the 20-repo corpus if
        # false-positive rate on functional codebases exceeds ~5%.
        if keyword_match or writes >= 1:
            matches.append(
                {
                    "node_id": node.id,
                    "write_count": writes,
                    "call_count": calls,
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for action mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
544
545
546
547
548
549
550
def to_gnn_role(self) -> str:
    """Return the GNN role string for action mappings.

    Returns:
        GNN role identifier.
    """
    return "ACTION"

ContextRule

Bases: TranslationRule

Maps configuration and parameter classes to context modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule. Rationale: context keywords config/settings/env/options/params are specific but less strong than a validate/test_ prefix (which get 0.85); they correlate well with configuration roles but also occasionally appear in orchestrators. Note: the dedicated ConfigRule (control.py, confidence 0.90) supersedes this rule when config is in the name — this rule provides the broader settings/params/env fallback.

Source code in py/cogant/translate/rules/semantic.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
class ContextRule(TranslationRule):
    """Maps configuration and parameter classes to context modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``. Rationale: context
        keywords ``config``/``settings``/``env``/``options``/``params``
        are specific but less strong than a ``validate``/``test_``
        prefix (which get 0.85); they correlate well with
        configuration roles but also occasionally appear in
        orchestrators. Note: the dedicated ``ConfigRule`` (control.py,
        confidence 0.90) supersedes this rule when ``config`` is in
        the name — this rule provides the broader
        ``settings``/``params``/``env`` fallback.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find context/configuration classes and functions.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched context nodes.
        """
        matches = []
        context_keywords = [
            "config",
            "settings",
            "env",
            "options",
            "params",
            "env_",
            "world_",
            "state_",
            "context_",
        ]

        # Find classes and functions with context keywords
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            if _matches_keyword(cls.name, context_keywords):
                matches.append(
                    {
                        "node_id": cls.id,
                        "context_type": "class",
                    }
                )

        # Find functions that only read and return values (read-only + returns)
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        for func in functions:
            out_edges = graph.get_edges_from(func.id)
            reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
            returns = sum(1 for e in out_edges if e.kind == EdgeKind.RETURNS)

            # Context function: reads config/state and returns it,
            # OR has context keyword in name
            has_context_keyword = _matches_keyword(func.name, context_keywords)
            if has_context_keyword or (reads > 0 and writes == 0 and returns > 0):
                matches.append(
                    {
                        "node_id": func.id,
                        "context_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'context').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # Parser certainty 0.85 = AST-native band. ``ConfigRule`` in
        # control.py supersedes this rule (confidence 0.90) on exact
        # ``config`` hits.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Context",
            description=f"{'Class' if match['context_type'] == 'class' else 'Function'} '{node.name}' provides system context",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "context"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

    def to_gnn_role(self) -> str:
        """Return the GNN role string for context mappings.

        Returns:
            GNN role identifier.
        """
        return "CONTEXT"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/semantic.py
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'context').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # Parser certainty 0.85 = AST-native band. ``ConfigRule`` in
    # control.py supersedes this rule (confidence 0.90) on exact
    # ``config`` hits.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Context",
        description=f"{'Class' if match['context_type'] == 'class' else 'Function'} '{node.name}' provides system context",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

matches(graph, query)

Find context/configuration classes and functions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched context nodes.

Source code in py/cogant/translate/rules/semantic.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find context/configuration classes and functions.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched context nodes.
    """
    matches = []
    context_keywords = [
        "config",
        "settings",
        "env",
        "options",
        "params",
        "env_",
        "world_",
        "state_",
        "context_",
    ]

    # Find classes and functions with context keywords
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        if _matches_keyword(cls.name, context_keywords):
            matches.append(
                {
                    "node_id": cls.id,
                    "context_type": "class",
                }
            )

    # Find functions that only read and return values (read-only + returns)
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    for func in functions:
        out_edges = graph.get_edges_from(func.id)
        reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
        returns = sum(1 for e in out_edges if e.kind == EdgeKind.RETURNS)

        # Context function: reads config/state and returns it,
        # OR has context keyword in name
        has_context_keyword = _matches_keyword(func.name, context_keywords)
        if has_context_keyword or (reads > 0 and writes == 0 and returns > 0):
            matches.append(
                {
                    "node_id": func.id,
                    "context_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for context mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
971
972
973
974
975
976
977
def to_gnn_role(self) -> str:
    """Return the GNN role string for context mappings.

    Returns:
        GNN role identifier.
    """
    return "CONTEXT"

ObservationRule

Bases: TranslationRule

Maps getter/query functions and read-only methods to observation modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85) on keyword match, or (0, 0.70) on the edge-based read-only fallback. - Keyword band: high band (0.85), same as PreferenceRule and TestAssertionRule, tied second only to ConfigRule (0.90). Rationale: lexical matches on get_/read_/fetch_ prefixes carry strong prior probability of observation semantics based on PEP 8 naming convention. - Fallback band: bottom band (0.70). The structural "reads, no writes" signal alone is weaker because pure-read helpers are also ubiquitous in private utility code. The bimodal confidence lets conflict resolution automatically prefer keyword-driven observations over structural ones. TODO(calibration): empirically validate the 0.85/0.70 split against a hand-labeled observation fixture.

Source code in py/cogant/translate/rules/semantic.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
class ObservationRule(TranslationRule):
    """Maps getter/query functions and read-only methods to observation modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)`` on keyword match, or
        ``(0, 0.70)`` on the edge-based read-only fallback.
        - Keyword band: **high band** (0.85), same as
          ``PreferenceRule`` and ``TestAssertionRule``, tied second
          only to ``ConfigRule`` (0.90). Rationale: lexical matches
          on ``get_``/``read_``/``fetch_`` prefixes carry strong
          prior probability of observation semantics based on PEP 8
          naming convention.
        - Fallback band: **bottom band** (0.70). The structural "reads,
          no writes" signal alone is weaker because pure-read helpers
          are also ubiquitous in private utility code.
        The bimodal confidence lets conflict resolution automatically
        prefer keyword-driven observations over structural ones.
        TODO(calibration): empirically validate the 0.85/0.70 split
        against a hand-labeled observation fixture.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find functions/methods that observe state without mutation.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched observation functions/methods.
        """
        matches = []
        observation_keywords = OBSERVATION_KEYWORDS

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            # Token-anchored keyword match (no raw substring containment).
            keyword_match = _matches_keyword(node.name, observation_keywords)

            # Check for read-only pattern: READS but no WRITES
            out_edges = graph.get_edges_from(node.id)
            reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
            writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
            mutates = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

            # A write-bearing function is an ACTION, not an OBSERVATION, even
            # when its name lexically suggests a read (``read_sensor`` writes
            # ``self.current_temp``). The structural mutation fact outranks
            # the lexical observation hint, so the keyword signal is only
            # honoured for functions that do not mutate state. This makes
            # ActionRule's precedence over ObservationRule deterministic
            # rather than relying on the 0.85 > 0.80 confidence tiebreak.
            keyword_match = keyword_match and (writes + mutates) == 0

            # Match if keyword match OR (has reads and neither writes nor mutates).
            # A function that mutates state is an ACTION even without a WRITES
            # edge, so the structural read-only branch must also exclude
            # mutations (mirrors the keyword suppression above and explain()).
            if keyword_match or (reads > 0 and writes == 0 and mutates == 0):
                matches.append(
                    {
                        "node_id": node.id,
                        "read_count": reads,
                        "write_count": writes,
                        "keyword_match": keyword_match,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for observation.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"obs_{node_id}_{hashlib.sha256(b'observation').hexdigest()[:8]}"
        # Bimodal confidence — 0.85 on keyword hit (high band, strong
        # PEP 8 naming prior), 0.70 on edge-only fallback (bottom band,
        # weaker because pure-read helpers are ubiquitous in private
        # utility code). The split is principled; the 0.15 gap is
        # chosen to cross the STATIC_ONLY → STATIC_PLUS_RUNTIME boundary
        # (0.65) if dynamic evidence is later added to a keyword-matched
        # mapping.
        confidence = 0.85 if match["keyword_match"] else 0.7

        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Observation",
            description=f"Function/method '{node.name}' observes state (read-only access)",
            confidence_score=confidence,
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=confidence,
                    metadata={
                        "read_count": match["read_count"],
                        "write_count": match["write_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,
        )

    def explain(
        self,
        node: Node,
        graph: ProgramGraph,
        query: GraphQuery,
    ) -> RuleExplanation:
        """Explain whether this node is an observation.

        Walks the same decision path used by :meth:`matches`, but
        collects concrete evidence snippets (keyword matches and
        READS/WRITES edge counts) into a :class:`RuleExplanation` so the
        ``cogant explain`` CLI can render a justification report.
        """
        if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=False,
                reason=(
                    f"observation rule only applies to functions/methods; "
                    f"node kind is {node.kind.value}"
                ),
                evidence=[],
                mapping_kind=self.mapping_kind.value,
            )

        matched_keywords = _matched_keywords(node.name, OBSERVATION_KEYWORDS)

        out_edges = graph.get_edges_from(node.id)
        read_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.READS]
        write_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.WRITES]
        mutate_count = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

        evidence: list[str] = []
        if matched_keywords:
            evidence.append(f"keyword match: {matched_keywords}")
        evidence.append(f"READS count: {len(read_targets)}")
        evidence.append(f"WRITES count: {len(write_targets)}")
        if read_targets:
            evidence.append(f"READS targets: {sorted(read_targets)[:5]}")

        # A write-bearing function is an ACTION; suppress the observation
        # keyword signal when the node mutates state (mirrors matches()).
        keyword_match = bool(matched_keywords) and (len(write_targets) + mutate_count) == 0
        read_only = len(read_targets) > 0 and (len(write_targets) + mutate_count) == 0

        if keyword_match or read_only:
            if keyword_match and read_only:
                reason = (
                    f"name contains observation keyword(s) {matched_keywords} "
                    f"AND read-only access pattern (READS={len(read_targets)}, "
                    f"WRITES=0)"
                )
            elif keyword_match:
                reason = f"name contains observation keyword(s) {matched_keywords}"
            else:
                reason = (
                    f"read-only access pattern (READS={len(read_targets)}, "
                    f"WRITES=0) with no observation keyword"
                )
            return RuleExplanation(
                rule_name=self.name,
                priority=self.priority,
                fired=True,
                reason=reason,
                evidence=evidence,
                mapping_kind=self.mapping_kind.value,
            )

        if matched_keywords and (len(write_targets) + mutate_count) > 0:
            reason = (
                f"observation keyword(s) {matched_keywords} present but the "
                f"function mutates state (WRITES={len(write_targets)}, "
                f"MUTATES={mutate_count}); the structural mutation fact "
                f"reclassifies it as an action"
            )
        else:
            reason = (
                f"no observation keyword in '{node.name}' and not read-only "
                f"(READS={len(read_targets)}, WRITES={len(write_targets)})"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "observation"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

    def to_gnn_role(self) -> str:
        """Return the GNN role string for observation mappings.

        Returns:
            GNN role identifier.
        """
        return "OBSERVATION"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for observation.

Source code in py/cogant/translate/rules/semantic.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for observation.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"obs_{node_id}_{hashlib.sha256(b'observation').hexdigest()[:8]}"
    # Bimodal confidence — 0.85 on keyword hit (high band, strong
    # PEP 8 naming prior), 0.70 on edge-only fallback (bottom band,
    # weaker because pure-read helpers are ubiquitous in private
    # utility code). The split is principled; the 0.15 gap is
    # chosen to cross the STATIC_ONLY → STATIC_PLUS_RUNTIME boundary
    # (0.65) if dynamic evidence is later added to a keyword-matched
    # mapping.
    confidence = 0.85 if match["keyword_match"] else 0.7

    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Observation",
        description=f"Function/method '{node.name}' observes state (read-only access)",
        confidence_score=confidence,
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=confidence,
                metadata={
                    "read_count": match["read_count"],
                    "write_count": match["write_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,
    )

explain(node, graph, query)

Explain whether this node is an observation.

Walks the same decision path used by :meth:matches, but collects concrete evidence snippets (keyword matches and READS/WRITES edge counts) into a :class:RuleExplanation so the cogant explain CLI can render a justification report.

Source code in py/cogant/translate/rules/semantic.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def explain(
    self,
    node: Node,
    graph: ProgramGraph,
    query: GraphQuery,
) -> RuleExplanation:
    """Explain whether this node is an observation.

    Walks the same decision path used by :meth:`matches`, but
    collects concrete evidence snippets (keyword matches and
    READS/WRITES edge counts) into a :class:`RuleExplanation` so the
    ``cogant explain`` CLI can render a justification report.
    """
    if node.kind not in (NodeKind.FUNCTION, NodeKind.METHOD):
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=False,
            reason=(
                f"observation rule only applies to functions/methods; "
                f"node kind is {node.kind.value}"
            ),
            evidence=[],
            mapping_kind=self.mapping_kind.value,
        )

    matched_keywords = _matched_keywords(node.name, OBSERVATION_KEYWORDS)

    out_edges = graph.get_edges_from(node.id)
    read_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.READS]
    write_targets = [e.target_id for e in out_edges if e.kind == EdgeKind.WRITES]
    mutate_count = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

    evidence: list[str] = []
    if matched_keywords:
        evidence.append(f"keyword match: {matched_keywords}")
    evidence.append(f"READS count: {len(read_targets)}")
    evidence.append(f"WRITES count: {len(write_targets)}")
    if read_targets:
        evidence.append(f"READS targets: {sorted(read_targets)[:5]}")

    # A write-bearing function is an ACTION; suppress the observation
    # keyword signal when the node mutates state (mirrors matches()).
    keyword_match = bool(matched_keywords) and (len(write_targets) + mutate_count) == 0
    read_only = len(read_targets) > 0 and (len(write_targets) + mutate_count) == 0

    if keyword_match or read_only:
        if keyword_match and read_only:
            reason = (
                f"name contains observation keyword(s) {matched_keywords} "
                f"AND read-only access pattern (READS={len(read_targets)}, "
                f"WRITES=0)"
            )
        elif keyword_match:
            reason = f"name contains observation keyword(s) {matched_keywords}"
        else:
            reason = (
                f"read-only access pattern (READS={len(read_targets)}, "
                f"WRITES=0) with no observation keyword"
            )
        return RuleExplanation(
            rule_name=self.name,
            priority=self.priority,
            fired=True,
            reason=reason,
            evidence=evidence,
            mapping_kind=self.mapping_kind.value,
        )

    if matched_keywords and (len(write_targets) + mutate_count) > 0:
        reason = (
            f"observation keyword(s) {matched_keywords} present but the "
            f"function mutates state (WRITES={len(write_targets)}, "
            f"MUTATES={mutate_count}); the structural mutation fact "
            f"reclassifies it as an action"
        )
    else:
        reason = (
            f"no observation keyword in '{node.name}' and not read-only "
            f"(READS={len(read_targets)}, WRITES={len(write_targets)})"
        )
    return RuleExplanation(
        rule_name=self.name,
        priority=self.priority,
        fired=False,
        reason=reason,
        evidence=evidence,
        mapping_kind=self.mapping_kind.value,
    )

matches(graph, query)

Find functions/methods that observe state without mutation.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched observation functions/methods.

Source code in py/cogant/translate/rules/semantic.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find functions/methods that observe state without mutation.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched observation functions/methods.
    """
    matches = []
    observation_keywords = OBSERVATION_KEYWORDS

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        # Token-anchored keyword match (no raw substring containment).
        keyword_match = _matches_keyword(node.name, observation_keywords)

        # Check for read-only pattern: READS but no WRITES
        out_edges = graph.get_edges_from(node.id)
        reads = sum(1 for e in out_edges if e.kind == EdgeKind.READS)
        writes = sum(1 for e in out_edges if e.kind == EdgeKind.WRITES)
        mutates = sum(1 for e in out_edges if e.kind == EdgeKind.MUTATES)

        # A write-bearing function is an ACTION, not an OBSERVATION, even
        # when its name lexically suggests a read (``read_sensor`` writes
        # ``self.current_temp``). The structural mutation fact outranks
        # the lexical observation hint, so the keyword signal is only
        # honoured for functions that do not mutate state. This makes
        # ActionRule's precedence over ObservationRule deterministic
        # rather than relying on the 0.85 > 0.80 confidence tiebreak.
        keyword_match = keyword_match and (writes + mutates) == 0

        # Match if keyword match OR (has reads and neither writes nor mutates).
        # A function that mutates state is an ACTION even without a WRITES
        # edge, so the structural read-only branch must also exclude
        # mutations (mirrors the keyword suppression above and explain()).
        if keyword_match or (reads > 0 and writes == 0 and mutates == 0):
            matches.append(
                {
                    "node_id": node.id,
                    "read_count": reads,
                    "write_count": writes,
                    "keyword_match": keyword_match,
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for observation mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
332
333
334
335
336
337
338
def to_gnn_role(self) -> str:
    """Return the GNN role string for observation mappings.

    Returns:
        GNN role identifier.
    """
    return "OBSERVATION"

PolicyRule

Bases: TranslationRule

Maps controllers, handlers, and routers to policy modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule, ContextRule, OrchestratorRule, CircuitBreakerRule. Rationale: controller/handler/router vocabulary is a strong web-framework signal (Flask, Django, FastAPI) but carries real ambiguity — "handler" also appears in action and retry contexts. Confidence tie-breaking between policy and action on handle/dispatch is delegated to per-match context. TODO(calibration): measure the policy↔action collision rate on handle/dispatch in the 20-repo corpus.

Source code in py/cogant/translate/rules/semantic.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class PolicyRule(TranslationRule):
    """Maps controllers, handlers, and routers to policy modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``, ``ContextRule``, ``OrchestratorRule``,
        ``CircuitBreakerRule``. Rationale: controller/handler/router
        vocabulary is a strong web-framework signal (Flask, Django,
        FastAPI) but carries real ambiguity — "handler" also appears
        in action and retry contexts. Confidence tie-breaking between
        policy and action on ``handle``/``dispatch`` is delegated to
        per-match context. TODO(calibration): measure the
        policy↔action collision rate on ``handle``/``dispatch`` in
        the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find classes and functions that implement policy/control logic.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched policy nodes.
        """
        matches = []
        # Policy keywords — sourced from web-framework conventions
        # (Flask view, Django middleware, FastAPI router, express
        # handler). Principled default. The overlap with ACTION_KEYWORDS
        # on ``handle``/``dispatch`` is intentional; conflict resolution
        # in ``_resolve_conflicts`` will pick whichever rule produces
        # higher confidence on that specific match.
        policy_keywords = [
            "middleware",
            "handler",
            "controller",
            "manager",
            "router",
            "dispatcher",
            "scheduler",
            "route",
            "dispatch",
            "handle",
            "select_",
            "choose_",
            "decide_",
            "plan_",
            "strategy",
            "orchestrator",
            "coordinator",
            "supervisor",
        ]

        # Find classes
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            has_keyword = _matches_keyword(cls.name, policy_keywords)

            # Check for __call__ method (callable class = decision logic)
            has_call_method = False
            out_edges = graph.get_edges_from(cls.id)
            # Distinct name from the function-loop ``methods`` below; filtering
            # None here keeps the type ``list[Node]`` (get_node may return None
            # for dangling CONTAINS targets) so attribute access is type-safe.
            contained = [
                node
                for node in (
                    graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
                )
                if node is not None
            ]
            for method in contained:
                if method.name == "__call__":
                    has_call_method = True
                    break

            if has_keyword or has_call_method:
                call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)
                matches.append(
                    {
                        "node_id": cls.id,
                        "call_count": call_count,
                        "node_type": "class",
                        "has_call_method": has_call_method,
                    }
                )

        # Find functions with policy keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            if _matches_keyword(node.name, policy_keywords):
                out_edges = graph.get_edges_from(node.id)
                call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

                matches.append(
                    {
                        "node_id": node.id,
                        "call_count": call_count,
                        "node_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create policy mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for policy.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"pol_{node_id}_{hashlib.sha256(b'policy').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # Parser certainty 0.85 = AST-native (class/function names
        # are extracted by Python AST, not tree-sitter fallback).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Policy",
            description=f"{'Class' if match['node_type'] == 'class' else 'Function'} '{node.name}' implements control policy",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={"call_count": match["call_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "policy"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

    def to_gnn_role(self) -> str:
        """Return the GNN role string for policy mappings.

        Returns:
            GNN role identifier.
        """
        return "POLICY"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create policy mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for policy.

Source code in py/cogant/translate/rules/semantic.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create policy mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for policy.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"pol_{node_id}_{hashlib.sha256(b'policy').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # Parser certainty 0.85 = AST-native (class/function names
    # are extracted by Python AST, not tree-sitter fallback).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Policy",
        description=f"{'Class' if match['node_type'] == 'class' else 'Function'} '{node.name}' implements control policy",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={"call_count": match["call_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native band
    )

matches(graph, query)

Find classes and functions that implement policy/control logic.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched policy nodes.

Source code in py/cogant/translate/rules/semantic.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find classes and functions that implement policy/control logic.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched policy nodes.
    """
    matches = []
    # Policy keywords — sourced from web-framework conventions
    # (Flask view, Django middleware, FastAPI router, express
    # handler). Principled default. The overlap with ACTION_KEYWORDS
    # on ``handle``/``dispatch`` is intentional; conflict resolution
    # in ``_resolve_conflicts`` will pick whichever rule produces
    # higher confidence on that specific match.
    policy_keywords = [
        "middleware",
        "handler",
        "controller",
        "manager",
        "router",
        "dispatcher",
        "scheduler",
        "route",
        "dispatch",
        "handle",
        "select_",
        "choose_",
        "decide_",
        "plan_",
        "strategy",
        "orchestrator",
        "coordinator",
        "supervisor",
    ]

    # Find classes
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        has_keyword = _matches_keyword(cls.name, policy_keywords)

        # Check for __call__ method (callable class = decision logic)
        has_call_method = False
        out_edges = graph.get_edges_from(cls.id)
        # Distinct name from the function-loop ``methods`` below; filtering
        # None here keeps the type ``list[Node]`` (get_node may return None
        # for dangling CONTAINS targets) so attribute access is type-safe.
        contained = [
            node
            for node in (
                graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
            )
            if node is not None
        ]
        for method in contained:
            if method.name == "__call__":
                has_call_method = True
                break

        if has_keyword or has_call_method:
            call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)
            matches.append(
                {
                    "node_id": cls.id,
                    "call_count": call_count,
                    "node_type": "class",
                    "has_call_method": has_call_method,
                }
            )

    # Find functions with policy keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        if _matches_keyword(node.name, policy_keywords):
            out_edges = graph.get_edges_from(node.id)
            call_count = sum(1 for e in out_edges if e.kind == EdgeKind.CALLS)

            matches.append(
                {
                    "node_id": node.id,
                    "call_count": call_count,
                    "node_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for policy mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
710
711
712
713
714
715
716
def to_gnn_role(self) -> str:
    """Return the GNN role string for policy mappings.

    Returns:
        GNN role identifier.
    """
    return "POLICY"

PreferenceRule

Bases: TranslationRule

Maps validators and test functions to preference/constraint modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with TestAssertionRule and the keyword branch of ObservationRule. Rationale: validate/check/ Validator/test_ are exceptionally strong lexical signals — there is essentially no non-constraint use of test_ prefixes in well-formed Python, and PEP 8 + pytest/unittest conventions anchor the other patterns. Parser certainty 0.90 is the highest in the rule family because name-only matching doesn't depend on edge extraction.

Source code in py/cogant/translate/rules/semantic.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
class PreferenceRule(TranslationRule):
    """Maps validators and test functions to preference/constraint modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85), tied
        with ``TestAssertionRule`` and the keyword branch of
        ``ObservationRule``. Rationale: ``validate``/``check``/
        ``Validator``/``test_`` are exceptionally strong lexical
        signals — there is essentially no non-constraint use of
        ``test_`` prefixes in well-formed Python, and PEP 8 +
        pytest/unittest conventions anchor the other patterns.
        Parser certainty 0.90 is the highest in the rule family
        because name-only matching doesn't depend on edge extraction.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find validation and test functions.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched preference/constraint nodes.
        """
        matches = []

        # Preference/constraint keywords covering cost, reward, objective, loss, utility
        constraint_keywords = [
            "validator",
            "checker",
            "test_",
            "assert_",
            "validate",
            "check",
            "cost_",
            "reward_",
            "objective_",
            "loss_",
            "utility_",
            "metric",
        ]

        # Find classes with Validator/Checker/etc in name
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            if _matches_keyword(cls.name, constraint_keywords):
                matches.append(
                    {
                        "node_id": cls.id,
                        "constraint_type": "class",
                    }
                )

        # Find functions/methods with constraint keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            if _matches_keyword(node.name, constraint_keywords):
                matches.append(
                    {
                        "node_id": node.id,
                        "constraint_type": "function",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create preference/constraint mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for constraint.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"pref_{node_id}_{hashlib.sha256(b'preference').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). The
        # ``test_``/``assert_``/``validate``/``check``/``Validator``
        # vocabulary is exceptionally unambiguous in Python — PEP 8
        # + pytest/unittest conventions anchor these as constraint
        # signals. Parser certainty 0.90 is the highest in the rule
        # family because name-only matching doesn't depend on edge
        # extraction accuracy.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONSTRAINT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Preference/Constraint",
            description=f"{'Class' if match['constraint_type'] == 'class' else 'Function'} '{node.name}' defines system constraints",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # name-only, highest in family
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "preference"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONSTRAINT

    def to_gnn_role(self) -> str:
        """Return the GNN role string for preference/constraint mappings.

        Returns:
            GNN role identifier.
        """
        return "PREFERENCE"

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create preference/constraint mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for constraint.

Source code in py/cogant/translate/rules/semantic.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create preference/constraint mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for constraint.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"pref_{node_id}_{hashlib.sha256(b'preference').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). The
    # ``test_``/``assert_``/``validate``/``check``/``Validator``
    # vocabulary is exceptionally unambiguous in Python — PEP 8
    # + pytest/unittest conventions anchor these as constraint
    # signals. Parser certainty 0.90 is the highest in the rule
    # family because name-only matching doesn't depend on edge
    # extraction accuracy.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONSTRAINT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Preference/Constraint",
        description=f"{'Class' if match['constraint_type'] == 'class' else 'Function'} '{node.name}' defines system constraints",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # name-only, highest in family
    )

matches(graph, query)

Find validation and test functions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched preference/constraint nodes.

Source code in py/cogant/translate/rules/semantic.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find validation and test functions.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched preference/constraint nodes.
    """
    matches = []

    # Preference/constraint keywords covering cost, reward, objective, loss, utility
    constraint_keywords = [
        "validator",
        "checker",
        "test_",
        "assert_",
        "validate",
        "check",
        "cost_",
        "reward_",
        "objective_",
        "loss_",
        "utility_",
        "metric",
    ]

    # Find classes with Validator/Checker/etc in name
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        if _matches_keyword(cls.name, constraint_keywords):
            matches.append(
                {
                    "node_id": cls.id,
                    "constraint_type": "class",
                }
            )

    # Find functions/methods with constraint keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        if _matches_keyword(node.name, constraint_keywords):
            matches.append(
                {
                    "node_id": node.id,
                    "constraint_type": "function",
                }
            )

    return matches

to_gnn_role()

Return the GNN role string for preference/constraint mappings.

Returns:

Type Description
str

GNN role identifier.

Source code in py/cogant/translate/rules/semantic.py
841
842
843
844
845
846
847
def to_gnn_role(self) -> str:
    """Return the GNN role string for preference/constraint mappings.

    Returns:
        GNN role identifier.
    """
    return "PREFERENCE"

Behavioral rules

cogant.translate.rules.behavioral

Behavioral translation rules.

This module is part of the :mod:cogant.translate.rules package and contains rules that recognise behavioural patterns (orchestration, event buses, test assertions). Every class in this file inherits from :class:cogant.translate.engine.TranslationRule and produces :class:cogant.schemas.semantic.SemanticMapping records with full provenance and confidence.

See :mod:cogant.translate.rules for the umbrella re-export and :doc:../../../specs/mappings/code-to-gnn for the family taxonomy.

EventBusRule

Bases: TranslationRule

Maps event/subscription systems to observation-action coupling.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75), tied with MutatingSubsystemRule/ContainmentRule/ DataPipelineRule. Rationale: event-bus detection depends on the upstream parser recognizing EVENT node kinds, which is only done for patterns the tree-sitter queries understand (decorator-driven pub/sub). Confidence tier is set to STATIC_PLUS_RUNTIME (not STATIC_ONLY) as a hint that dynamic trace corroboration is especially valuable for event-driven code. TODO(calibration): measure EVENT-node coverage across the 20-repo corpus.

Source code in py/cogant/translate/rules/behavioral.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
class EventBusRule(TranslationRule):
    """Maps event/subscription systems to observation-action coupling.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75),
        tied with ``MutatingSubsystemRule``/``ContainmentRule``/
        ``DataPipelineRule``. Rationale: event-bus detection depends
        on the upstream parser recognizing ``EVENT`` node kinds,
        which is only done for patterns the tree-sitter queries
        understand (decorator-driven pub/sub). Confidence tier is
        set to STATIC_PLUS_RUNTIME (not STATIC_ONLY) as a hint that
        dynamic trace corroboration is especially valuable for
        event-driven code. TODO(calibration): measure EVENT-node
        coverage across the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find event bus and subscription patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched event bus patterns.
        """
        matches = []

        # Look for event nodes and their subscriptions
        events = graph.get_nodes_by_kind(NodeKind.EVENT)

        for event in events:
            # Find subscribing nodes
            incoming = graph.get_edges_to(event.id)
            outgoing = graph.get_edges_from(event.id)

            if incoming or outgoing:
                matches.append(
                    {
                        "node_id": event.id,
                        "subscriber_count": len(
                            [e for e in outgoing if e.kind == EdgeKind.TRIGGERS]
                        ),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create observation-action coupling mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for event bus.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"event_{node_id}_{hashlib.sha256(b'event_bus').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Event-bus
        # detection depends on upstream EVENT-kind nodes, which are
        # only emitted for patterns the tree-sitter queries
        # understand. Tier set to STATIC_PLUS_RUNTIME as a hint that
        # dynamic trace corroboration is particularly valuable for
        # event-driven code paths.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.OBSERVATION,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Event Bus",
            description=f"Event '{node.name}' couples observations to actions",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_PLUS_RUNTIME,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # tree-sitter Python-fallback band
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "event_bus"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.OBSERVATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create observation-action coupling mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for event bus.

Source code in py/cogant/translate/rules/behavioral.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create observation-action coupling mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for event bus.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"event_{node_id}_{hashlib.sha256(b'event_bus').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Event-bus
    # detection depends on upstream EVENT-kind nodes, which are
    # only emitted for patterns the tree-sitter queries
    # understand. Tier set to STATIC_PLUS_RUNTIME as a hint that
    # dynamic trace corroboration is particularly valuable for
    # event-driven code paths.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.OBSERVATION,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Event Bus",
        description=f"Event '{node.name}' couples observations to actions",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_PLUS_RUNTIME,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # tree-sitter Python-fallback band
    )

matches(graph, query)

Find event bus and subscription patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched event bus patterns.

Source code in py/cogant/translate/rules/behavioral.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find event bus and subscription patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched event bus patterns.
    """
    matches = []

    # Look for event nodes and their subscriptions
    events = graph.get_nodes_by_kind(NodeKind.EVENT)

    for event in events:
        # Find subscribing nodes
        incoming = graph.get_edges_to(event.id)
        outgoing = graph.get_edges_from(event.id)

        if incoming or outgoing:
            matches.append(
                {
                    "node_id": event.id,
                    "subscriber_count": len(
                        [e for e in outgoing if e.kind == EdgeKind.TRIGGERS]
                    ),
                }
            )

    return matches

OrchestratorRule

Bases: TranslationRule

Maps schedulers and controllers to policy/action structure.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule/ContextRule/ CircuitBreakerRule. Rationale: high call fan-out is a reliable structural signal for orchestration but not unambiguous — utility modules can also have many calls. Call-count threshold = 3 (see matches): below 3, the pattern is indistinguishable from simple helpers. TODO(calibration): sweep {2, 3, 5, 8} on the 20-repo corpus.

Source code in py/cogant/translate/rules/behavioral.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class OrchestratorRule(TranslationRule):
    """Maps schedulers and controllers to policy/action structure.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``/``ContextRule``/
        ``CircuitBreakerRule``. Rationale: high call fan-out is a
        reliable structural signal for orchestration but not
        unambiguous — utility modules can also have many calls.
        Call-count threshold = 3 (see ``matches``): below 3, the
        pattern is indistinguishable from simple helpers.
        TODO(calibration): sweep {2, 3, 5, 8} on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find orchestrator patterns (high out-degree controllers).

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched orchestrator nodes.
        """
        matches = []

        # Look for functions/classes with high out-degree (calling many others)
        for node in graph.nodes.values():
            if node.kind not in (NodeKind.CLASS, NodeKind.FUNCTION, NodeKind.METHOD):
                continue

            out_edges = graph.get_edges_from(node.id)
            call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

            # Call-count threshold = 3. Principled default: below 3
            # calls, high-fan-out is indistinguishable from simple
            # helper functions (2 calls = typical setup/teardown);
            # at >=3 the pattern starts to look like real
            # orchestration (setup/work/cleanup triad or larger).
            # TODO(calibration): sweep {2, 3, 5, 8} on 20-repo corpus.
            if len(call_edges) >= 3:
                matches.append(
                    {
                        "node_id": node.id,
                        "call_count": len(call_edges),
                        "called_node_ids": [e.target_id for e in call_edges],
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create orchestration mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for orchestration.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"orch_{node_id}_{hashlib.sha256(b'orchestrator').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band). High
        # call fan-out is reliable but not unambiguous. Parser
        # certainty 0.90 because call-edge extraction is one of the
        # highest-precision operations in the Python AST substrate.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ORCHESTRATION,
            graph_fragment_node_ids=[node_id] + match.get("called_node_ids", []),
            semantic_label=f"{node.name} - Orchestrator",
            description=f"{'Class' if node.kind == NodeKind.CLASS else 'Function'} '{node.name}' acts as orchestrator (high fan-out)",
            confidence_score=0.8,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.8,
                    metadata={"call_count": match["call_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # high AST precision on CALLS edges
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "orchestrator"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ORCHESTRATION

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create orchestration mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for orchestration.

Source code in py/cogant/translate/rules/behavioral.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create orchestration mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for orchestration.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"orch_{node_id}_{hashlib.sha256(b'orchestrator').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band). High
    # call fan-out is reliable but not unambiguous. Parser
    # certainty 0.90 because call-edge extraction is one of the
    # highest-precision operations in the Python AST substrate.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ORCHESTRATION,
        graph_fragment_node_ids=[node_id] + match.get("called_node_ids", []),
        semantic_label=f"{node.name} - Orchestrator",
        description=f"{'Class' if node.kind == NodeKind.CLASS else 'Function'} '{node.name}' acts as orchestrator (high fan-out)",
        confidence_score=0.8,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.8,
                metadata={"call_count": match["call_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # high AST precision on CALLS edges
    )

matches(graph, query)

Find orchestrator patterns (high out-degree controllers).

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched orchestrator nodes.

Source code in py/cogant/translate/rules/behavioral.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find orchestrator patterns (high out-degree controllers).

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched orchestrator nodes.
    """
    matches = []

    # Look for functions/classes with high out-degree (calling many others)
    for node in graph.nodes.values():
        if node.kind not in (NodeKind.CLASS, NodeKind.FUNCTION, NodeKind.METHOD):
            continue

        out_edges = graph.get_edges_from(node.id)
        call_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        # Call-count threshold = 3. Principled default: below 3
        # calls, high-fan-out is indistinguishable from simple
        # helper functions (2 calls = typical setup/teardown);
        # at >=3 the pattern starts to look like real
        # orchestration (setup/work/cleanup triad or larger).
        # TODO(calibration): sweep {2, 3, 5, 8} on 20-repo corpus.
        if len(call_edges) >= 3:
            matches.append(
                {
                    "node_id": node.id,
                    "call_count": len(call_edges),
                    "called_node_ids": [e.target_id for e in call_edges],
                }
            )

    return matches

StateMachineRule

Bases: TranslationRule

Maps finite state machine patterns to policy/hidden-state modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule/ContextRule/ OrchestratorRule/CircuitBreakerRule. Rationale: state machines with explicit state enums + transition methods are a strong structural signal for policy/control logic, but depend on the upstream parser recognizing STATE node kinds and transition patterns. Patterns: state enums, on_enter_*/ on_exit_* methods, transitions library usage, explicit state attributes (self.state, self._state). TODO(calibration): measure STATE-node coverage on the 20-repo corpus; if <40%, demote to 0.75 or add heuristics for transitions-library imports.

Source code in py/cogant/translate/rules/behavioral.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
class StateMachineRule(TranslationRule):
    """Maps finite state machine patterns to policy/hidden-state modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``/``ContextRule``/
        ``OrchestratorRule``/``CircuitBreakerRule``. Rationale: state
        machines with explicit state enums + transition methods are a
        strong structural signal for policy/control logic, but depend
        on the upstream parser recognizing STATE node kinds and
        transition patterns. Patterns: state enums, ``on_enter_*``/
        ``on_exit_*`` methods, ``transitions`` library usage, explicit
        state attributes (self.state, self._state).
        TODO(calibration): measure STATE-node coverage on the 20-repo
        corpus; if <40%, demote to 0.75 or add heuristics for
        transitions-library imports.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find finite state machine patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched state machine nodes.
        """
        matches = []

        state_keywords = ["state", "fsm", "stateful", "transitions"]

        # Look for classes with state-like structure
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            name_lower = cls.name.lower()
            has_state_keyword = any(kw in name_lower for kw in state_keywords)

            # Check for on_enter/on_exit methods (state machine pattern)
            out_edges = graph.get_edges_from(cls.id)
            methods = [
                graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
            ]
            transition_methods = sum(
                1
                for m in methods
                if m and ("on_enter" in m.name.lower() or "on_exit" in m.name.lower())
            )

            # Also check for explicit state variable
            has_state_var = any(
                "state" in m.name.lower() for m in methods if m and m.kind == NodeKind.VARIABLE
            )

            if has_state_keyword or transition_methods >= 1 or has_state_var:
                matches.append(
                    {
                        "node_id": cls.id,
                        "transition_count": transition_methods,
                        "has_state_var": has_state_var,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create state machine mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for state machine.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"fsm_{node_id}_{hashlib.sha256(b'state_machine').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # Explicit state enums + transition methods are a strong
        # structural signal, but depend on upstream STATE-node
        # classification. Parser certainty 0.85 for method detection
        # (tree-sitter handles method names reliably).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - State Machine",
            description=f"Class '{node.name}' implements a finite state machine ({match.get('transition_count', 0)} transition method(s))",
            confidence_score=0.80,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.80,
                    metadata={
                        "transition_count": match.get("transition_count", 0),
                        "has_state_var": match.get("has_state_var", False),
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # method name/structure detection
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "state_machine"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create state machine mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for state machine.

Source code in py/cogant/translate/rules/behavioral.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create state machine mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for state machine.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"fsm_{node_id}_{hashlib.sha256(b'state_machine').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # Explicit state enums + transition methods are a strong
    # structural signal, but depend on upstream STATE-node
    # classification. Parser certainty 0.85 for method detection
    # (tree-sitter handles method names reliably).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - State Machine",
        description=f"Class '{node.name}' implements a finite state machine ({match.get('transition_count', 0)} transition method(s))",
        confidence_score=0.80,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.80,
                metadata={
                    "transition_count": match.get("transition_count", 0),
                    "has_state_var": match.get("has_state_var", False),
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # method name/structure detection
    )

matches(graph, query)

Find finite state machine patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched state machine nodes.

Source code in py/cogant/translate/rules/behavioral.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find finite state machine patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched state machine nodes.
    """
    matches = []

    state_keywords = ["state", "fsm", "stateful", "transitions"]

    # Look for classes with state-like structure
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        name_lower = cls.name.lower()
        has_state_keyword = any(kw in name_lower for kw in state_keywords)

        # Check for on_enter/on_exit methods (state machine pattern)
        out_edges = graph.get_edges_from(cls.id)
        methods = [
            graph.get_node(e.target_id) for e in out_edges if e.kind == EdgeKind.CONTAINS
        ]
        transition_methods = sum(
            1
            for m in methods
            if m and ("on_enter" in m.name.lower() or "on_exit" in m.name.lower())
        )

        # Also check for explicit state variable
        has_state_var = any(
            "state" in m.name.lower() for m in methods if m and m.kind == NodeKind.VARIABLE
        )

        if has_state_keyword or transition_methods >= 1 or has_state_var:
            matches.append(
                {
                    "node_id": cls.id,
                    "transition_count": transition_methods,
                    "has_state_var": has_state_var,
                }
            )

    return matches

TestAssertionRule

Bases: TranslationRule

Maps test assertions to preference/constraint modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with PreferenceRule and the keyword branch of ObservationRule. Rationale: a function with "test" in its name plus at least one CALLS edge (proxy for assertion) is one of the most reliable static signals in the entire rule family — pytest/unittest conventions are nearly universal. Parser certainty 0.95 is the highest in the family because both the name match and the call extraction are handled by the native Python AST with minimal ambiguity.

Source code in py/cogant/translate/rules/behavioral.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class TestAssertionRule(TranslationRule):
    """Maps test assertions to preference/constraint modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85), tied
        with ``PreferenceRule`` and the keyword branch of
        ``ObservationRule``. Rationale: a function with "test" in its
        name plus at least one ``CALLS`` edge (proxy for assertion)
        is one of the most reliable static signals in the entire
        rule family — pytest/unittest conventions are nearly
        universal. Parser certainty 0.95 is the *highest* in the
        family because both the name match and the call extraction
        are handled by the native Python AST with minimal ambiguity.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find test nodes and assertion calls.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched test nodes.
        """
        matches = []

        # Find test functions
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        for func in functions:
            # Check if test function (name contains "test")
            if "test" not in func.name.lower():
                continue

            # Find assertion calls
            out_edges = graph.get_edges_from(func.id)
            assertion_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

            if assertion_edges:
                matches.append(
                    {
                        "node_id": func.id,
                        "assertion_count": len(assertion_edges),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create constraint mapping from test assertions.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for constraint.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"const_{node_id}_{hashlib.sha256(b'test_assertion').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). Parser
        # certainty 0.95 is the highest in the rule family because
        # "test"-prefix names and call extraction are both native
        # Python AST operations with near-zero ambiguity.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONSTRAINT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Test Constraint",
            description=f"Test function '{node.name}' defines system constraints",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                    metadata={"assertion_count": match["assertion_count"]},
                )
            ],
            evidence_count=1,
            parser_certainty=0.95,  # highest in family (pytest/unittest conventions)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "test_assertion"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONSTRAINT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create constraint mapping from test assertions.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for constraint.

Source code in py/cogant/translate/rules/behavioral.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create constraint mapping from test assertions.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for constraint.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"const_{node_id}_{hashlib.sha256(b'test_assertion').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). Parser
    # certainty 0.95 is the highest in the rule family because
    # "test"-prefix names and call extraction are both native
    # Python AST operations with near-zero ambiguity.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONSTRAINT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Test Constraint",
        description=f"Test function '{node.name}' defines system constraints",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
                metadata={"assertion_count": match["assertion_count"]},
            )
        ],
        evidence_count=1,
        parser_certainty=0.95,  # highest in family (pytest/unittest conventions)
    )

matches(graph, query)

Find test nodes and assertion calls.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched test nodes.

Source code in py/cogant/translate/rules/behavioral.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find test nodes and assertion calls.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched test nodes.
    """
    matches = []

    # Find test functions
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    for func in functions:
        # Check if test function (name contains "test")
        if "test" not in func.name.lower():
            continue

        # Find assertion calls
        out_edges = graph.get_edges_from(func.id)
        assertion_edges = [e for e in out_edges if e.kind == EdgeKind.CALLS]

        if assertion_edges:
            matches.append(
                {
                    "node_id": func.id,
                    "assertion_count": len(assertion_edges),
                }
            )

    return matches

Control-flow rules

cogant.translate.rules.control

Control translation rules.

This module is part of the :mod:cogant.translate.rules package and contains rules that recognise control-flow modifiers (configuration, feature flags). Every class in this file inherits from :class:cogant.translate.engine.TranslationRule and produces :class:cogant.schemas.semantic.SemanticMapping records with full provenance and confidence.

See :mod:cogant.translate.rules for the umbrella re-export and :doc:../../../specs/mappings/code-to-gnn for the family taxonomy.

ConfigRule

Bases: TranslationRule

Maps configuration files and structures to context priors.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.90). Top band (0.90) — the highest confidence score in the entire translation rule family. Rationale: ConfigRule fires only when the upstream parser has already classified a node as NodeKind.CONFIGURATION (yaml/toml/ini/json config files, module-level CONFIG = {...} dicts, Settings subclasses). That classification is itself strongly evidenced, so the confidence stacks: parser_certainty 0.95 (highest) plus confidence 0.90 makes this rule effectively unbeatable by heuristic rules, which is correct — explicit config is ground truth for context. TODO(calibration): confirm that NodeKind.CONFIGURATION extraction has <5% false-positive rate on the 20-repo corpus.

Source code in py/cogant/translate/rules/control.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class ConfigRule(TranslationRule):
    """Maps configuration files and structures to context priors.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.90)``. **Top band** (0.90) —
        the highest confidence score in the entire translation rule
        family. Rationale: ``ConfigRule`` fires only when the
        upstream parser has already classified a node as
        ``NodeKind.CONFIGURATION`` (yaml/toml/ini/json config files,
        module-level ``CONFIG = {...}`` dicts, ``Settings`` subclasses).
        That classification is itself strongly evidenced, so the
        confidence stacks: parser_certainty 0.95 (highest) plus
        confidence 0.90 makes this rule effectively unbeatable by
        heuristic rules, which is correct — explicit config is
        ground truth for context. TODO(calibration): confirm that
        ``NodeKind.CONFIGURATION`` extraction has <5% false-positive
        rate on the 20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find configuration nodes.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched configuration nodes.
        """
        matches = []

        # Find configuration nodes
        configs = graph.get_nodes_by_kind(NodeKind.CONFIGURATION)

        for config in configs:
            matches.append(
                {
                    "node_id": config.id,
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping for configuration.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'config').hexdigest()[:8]}"

        # Confidence 0.90 — principled default (top band, highest in
        # entire rule family). The upstream parser has already
        # classified this node as CONFIGURATION, which is a strongly-
        # evidenced classification in its own right. Parser certainty
        # 0.95 is the highest in the family.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Context Prior",
            description=f"Configuration '{node.name}' provides system context",
            confidence_score=0.9,  # principled default (top band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.9,
                )
            ],
            evidence_count=1,
            parser_certainty=0.95,  # highest in family (explicit config)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "config"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping for configuration.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/control.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping for configuration.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"ctx_{node_id}_{hashlib.sha256(b'config').hexdigest()[:8]}"

    # Confidence 0.90 — principled default (top band, highest in
    # entire rule family). The upstream parser has already
    # classified this node as CONFIGURATION, which is a strongly-
    # evidenced classification in its own right. Parser certainty
    # 0.95 is the highest in the family.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Context Prior",
        description=f"Configuration '{node.name}' provides system context",
        confidence_score=0.9,  # principled default (top band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.9,
            )
        ],
        evidence_count=1,
        parser_certainty=0.95,  # highest in family (explicit config)
    )

matches(graph, query)

Find configuration nodes.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched configuration nodes.

Source code in py/cogant/translate/rules/control.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find configuration nodes.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched configuration nodes.
    """
    matches = []

    # Find configuration nodes
    configs = graph.get_nodes_by_kind(NodeKind.CONFIGURATION)

    for config in configs:
        matches.append(
            {
                "node_id": config.id,
            }
        )

    return matches

FeatureFlagRule

Bases: TranslationRule

Maps feature flags to latent context selectors.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with PreferenceRule/TestAssertionRule and the keyword branch of ObservationRule. Rationale: feature flags are specific but slightly less unambiguous than raw configuration (which gets 0.90); some "feature flag" patterns are actually dynamic toggles rather than static context selectors. The rule relies on upstream NodeKind.FEATURE_FLAG classification.

Source code in py/cogant/translate/rules/control.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
class FeatureFlagRule(TranslationRule):
    """Maps feature flags to latent context selectors.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85),
        tied with ``PreferenceRule``/``TestAssertionRule`` and the
        keyword branch of ``ObservationRule``. Rationale: feature
        flags are specific but slightly less unambiguous than raw
        configuration (which gets 0.90); some "feature flag"
        patterns are actually dynamic toggles rather than static
        context selectors. The rule relies on upstream
        ``NodeKind.FEATURE_FLAG`` classification.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find feature flag nodes.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched feature flag nodes.
        """
        matches = []

        # Find feature flag nodes
        flags = graph.get_nodes_by_kind(NodeKind.FEATURE_FLAG)

        for flag in flags:
            matches.append(
                {
                    "node_id": flag.id,
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context selector mapping for feature flag.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for feature flag.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"fflag_{node_id}_{hashlib.sha256(b'feature_flag').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). Relies on
        # upstream NodeKind.FEATURE_FLAG classification which is
        # slightly less precise than explicit CONFIGURATION.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Feature Flag",
            description=f"Feature flag '{node.name}' selects system context",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                )
            ],
            evidence_count=1,
            parser_certainty=0.9,  # high AST precision on flag nodes
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "feature_flag"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context selector mapping for feature flag.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for feature flag.

Source code in py/cogant/translate/rules/control.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context selector mapping for feature flag.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for feature flag.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"fflag_{node_id}_{hashlib.sha256(b'feature_flag').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). Relies on
    # upstream NodeKind.FEATURE_FLAG classification which is
    # slightly less precise than explicit CONFIGURATION.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Feature Flag",
        description=f"Feature flag '{node.name}' selects system context",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
            )
        ],
        evidence_count=1,
        parser_certainty=0.9,  # high AST precision on flag nodes
    )

matches(graph, query)

Find feature flag nodes.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched feature flag nodes.

Source code in py/cogant/translate/rules/control.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find feature flag nodes.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched feature flag nodes.
    """
    matches = []

    # Find feature flag nodes
    flags = graph.get_nodes_by_kind(NodeKind.FEATURE_FLAG)

    for flag in flags:
        matches.append(
            {
                "node_id": flag.id,
            }
        )

    return matches

ParameterRule

Bases: TranslationRule

Maps learnable parameters and hyperparameters to context priors.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.85). High band (0.85), tied with PreferenceRule/TestAssertionRule. Rationale: learnable parameters are semantic ground truth for context — they control system behavior but are not part of the observation, action, or policy logic. Patterns: param_, weight_, hyperparameter, learning_rate, typed dataclass fields (float/int), module-level configuration assignments. TODO(calibration): validate that parameter detection covers ML frameworks (PyTorch, TensorFlow, scikit-learn) on the 20-repo corpus.

Source code in py/cogant/translate/rules/control.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
class ParameterRule(TranslationRule):
    """Maps learnable parameters and hyperparameters to context priors.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.85)``. **High band** (0.85), tied
        with ``PreferenceRule``/``TestAssertionRule``. Rationale:
        learnable parameters are semantic ground truth for context —
        they control system behavior but are not part of the observation,
        action, or policy logic. Patterns: ``param_``, ``weight_``,
        ``hyperparameter``, ``learning_rate``, typed dataclass fields
        (float/int), module-level configuration assignments.
        TODO(calibration): validate that parameter detection covers
        ML frameworks (PyTorch, TensorFlow, scikit-learn) on the
        20-repo corpus.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find learnable parameters and hyperparameters.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched parameter nodes.
        """
        matches = []

        parameter_keywords = [
            "param_",
            "weight_",
            "hyperparameter",
            "learning_rate",
            "lr",
            "beta",
            "gamma",
            "alpha",
            "theta",
            "lambda_",
        ]

        # Find variables with parameter keywords
        variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
        for var in variables:
            name_lower = var.name.lower()
            if any(kw in name_lower for kw in parameter_keywords):
                matches.append(
                    {
                        "node_id": var.id,
                        "parameter_type": "variable",
                    }
                )

        # Find classes that are parameter/config dataclasses or contain float/int fields
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            name_lower = cls.name.lower()
            is_param_class = any(
                kw in name_lower for kw in ["param", "config", "settings", "hyperparameter"]
            )

            if is_param_class:
                matches.append(
                    {
                        "node_id": cls.id,
                        "parameter_type": "class",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping for learnable parameter.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"param_{node_id}_{hashlib.sha256(b'parameter').hexdigest()[:8]}"

        # Confidence 0.85 — principled default (high band). Learnable
        # parameters are semantic ground truth for context — they control
        # system behavior but are not part of observation/action/policy.
        # Parser certainty 0.90 for variables (AST-native), 0.85 for
        # classes (dataclass detection is slightly less precise).
        param_type = match.get("parameter_type", "variable")
        parser_certainty = 0.9 if param_type == "variable" else 0.85

        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Learnable Parameter",
            description=f"{'Variable' if param_type == 'variable' else 'Class'} '{node.name}' defines learnable parameters",
            confidence_score=0.85,  # principled default (high band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.85,
                )
            ],
            evidence_count=1,
            parser_certainty=parser_certainty,
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "parameter"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping for learnable parameter.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/control.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping for learnable parameter.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"param_{node_id}_{hashlib.sha256(b'parameter').hexdigest()[:8]}"

    # Confidence 0.85 — principled default (high band). Learnable
    # parameters are semantic ground truth for context — they control
    # system behavior but are not part of observation/action/policy.
    # Parser certainty 0.90 for variables (AST-native), 0.85 for
    # classes (dataclass detection is slightly less precise).
    param_type = match.get("parameter_type", "variable")
    parser_certainty = 0.9 if param_type == "variable" else 0.85

    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Learnable Parameter",
        description=f"{'Variable' if param_type == 'variable' else 'Class'} '{node.name}' defines learnable parameters",
        confidence_score=0.85,  # principled default (high band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.85,
            )
        ],
        evidence_count=1,
        parser_certainty=parser_certainty,
    )

matches(graph, query)

Find learnable parameters and hyperparameters.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched parameter nodes.

Source code in py/cogant/translate/rules/control.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find learnable parameters and hyperparameters.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched parameter nodes.
    """
    matches = []

    parameter_keywords = [
        "param_",
        "weight_",
        "hyperparameter",
        "learning_rate",
        "lr",
        "beta",
        "gamma",
        "alpha",
        "theta",
        "lambda_",
    ]

    # Find variables with parameter keywords
    variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
    for var in variables:
        name_lower = var.name.lower()
        if any(kw in name_lower for kw in parameter_keywords):
            matches.append(
                {
                    "node_id": var.id,
                    "parameter_type": "variable",
                }
            )

    # Find classes that are parameter/config dataclasses or contain float/int fields
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        name_lower = cls.name.lower()
        is_param_class = any(
            kw in name_lower for kw in ["param", "config", "settings", "hyperparameter"]
        )

        if is_param_class:
            matches.append(
                {
                    "node_id": cls.id,
                    "parameter_type": "class",
                }
            )

    return matches

Resilience rules

cogant.translate.rules.resilience

Resilience translation rules.

This module is part of the :mod:cogant.translate.rules package and contains rules that recognise resilience and uncertainty patterns (retry, error boundary, singleton, circuit breaker). Every class in this file inherits from :class:cogant.translate.engine.TranslationRule and produces :class:cogant.schemas.semantic.SemanticMapping records with full provenance and confidence.

See :mod:cogant.translate.rules for the umbrella re-export and :doc:../../../specs/mappings/code-to-gnn for the family taxonomy.

CircuitBreakerRule

Bases: TranslationRule

Maps circuit breaker patterns to circuit-breaker modality.

Detects functions/classes that contain both a GUARDS edge and a retry/fallback pattern (name contains retry/fallback/circuit/breaker keywords or has metadata indicating retry logic).

Rule priority (audit 2026-04-09): Effective priority = (0, 0.80). Upper-mid band (0.80), tied with ActionRule/PolicyRule/ContextRule/ OrchestratorRule. Rationale: the combined signal of GUARDS edge + retry keyword (or metadata hit) is much stronger than the keyword-only RetryPatternRule (0.70), so CircuitBreakerRule correctly wins on overlapping fragments. The composite requirement keeps false positives low — a function named retry_helper alone won't fire without a GUARDS edge.

Source code in py/cogant/translate/rules/resilience.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
class CircuitBreakerRule(TranslationRule):
    """Maps circuit breaker patterns to circuit-breaker modality.

    Detects functions/classes that contain both a GUARDS edge and a
    retry/fallback pattern (name contains retry/fallback/circuit/breaker
    keywords or has metadata indicating retry logic).

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.80)``. **Upper-mid band** (0.80),
        tied with ``ActionRule``/``PolicyRule``/``ContextRule``/
        ``OrchestratorRule``. Rationale: the combined signal of
        GUARDS edge + retry keyword (or metadata hit) is much
        stronger than the keyword-only ``RetryPatternRule`` (0.70),
        so CircuitBreakerRule correctly wins on overlapping
        fragments. The composite requirement keeps false positives
        low — a function named ``retry_helper`` alone won't fire
        without a GUARDS edge.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with GUARDS edges and retry/fallback indicators.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched circuit breaker nodes.
        """
        matches = []

        circuit_keywords = ["retry", "fallback", "circuit", "breaker"]

        # Find functions, methods, and classes
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for node in functions + methods + classes:
            out_edges = graph.get_edges_from(node.id)

            # Must have at least one GUARDS edge
            guards_edges = [e for e in out_edges if e.kind == EdgeKind.GUARDS]
            if not guards_edges:
                continue

            # Check for retry/fallback pattern via name or metadata
            name_lower = node.name.lower()
            has_keyword = any(kw in name_lower for kw in circuit_keywords)

            has_retry_metadata = False
            if node.metadata:
                meta_str = str(node.metadata).lower()
                has_retry_metadata = any(kw in meta_str for kw in circuit_keywords)

            if has_keyword or has_retry_metadata:
                guarded_ids = [e.target_id for e in guards_edges]
                matches.append(
                    {
                        "node_id": node.id,
                        "guarded_ids": guarded_ids,
                        "guards_count": len(guards_edges),
                        "keyword_match": has_keyword,
                        "metadata_match": has_retry_metadata,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create circuit-breaker mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for circuit breaker.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"cb_{node_id}_{hashlib.sha256(b'circuit_breaker').hexdigest()[:8]}"

        # Confidence 0.80 — principled default (upper-mid band).
        # The composite (GUARDS edge + retry keyword/metadata)
        # requirement is a much stronger signal than
        # RetryPatternRule's keyword-only matching (0.70), so this
        # rule correctly wins overlapping conflicts.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CIRCUIT_BREAKER,
            graph_fragment_node_ids=[node_id] + match.get("guarded_ids", []),
            semantic_label=f"{node.name} - Circuit Breaker",
            description=f"{'Function' if node.kind in (NodeKind.FUNCTION, NodeKind.METHOD) else 'Class'} '{node.name}' implements circuit breaker pattern (guards {match['guards_count']} target(s))",
            confidence_score=0.80,  # principled default (upper-mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.80,
                    metadata={
                        "guards_count": match["guards_count"],
                        "keyword_match": match["keyword_match"],
                        "metadata_match": match["metadata_match"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.85,  # AST-native on GUARDS edges
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "circuit_breaker"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CIRCUIT_BREAKER

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create circuit-breaker mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for circuit breaker.

Source code in py/cogant/translate/rules/resilience.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create circuit-breaker mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for circuit breaker.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"cb_{node_id}_{hashlib.sha256(b'circuit_breaker').hexdigest()[:8]}"

    # Confidence 0.80 — principled default (upper-mid band).
    # The composite (GUARDS edge + retry keyword/metadata)
    # requirement is a much stronger signal than
    # RetryPatternRule's keyword-only matching (0.70), so this
    # rule correctly wins overlapping conflicts.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CIRCUIT_BREAKER,
        graph_fragment_node_ids=[node_id] + match.get("guarded_ids", []),
        semantic_label=f"{node.name} - Circuit Breaker",
        description=f"{'Function' if node.kind in (NodeKind.FUNCTION, NodeKind.METHOD) else 'Class'} '{node.name}' implements circuit breaker pattern (guards {match['guards_count']} target(s))",
        confidence_score=0.80,  # principled default (upper-mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.80,
                metadata={
                    "guards_count": match["guards_count"],
                    "keyword_match": match["keyword_match"],
                    "metadata_match": match["metadata_match"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.85,  # AST-native on GUARDS edges
    )

matches(graph, query)

Find nodes with GUARDS edges and retry/fallback indicators.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched circuit breaker nodes.

Source code in py/cogant/translate/rules/resilience.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with GUARDS edges and retry/fallback indicators.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched circuit breaker nodes.
    """
    matches = []

    circuit_keywords = ["retry", "fallback", "circuit", "breaker"]

    # Find functions, methods, and classes
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for node in functions + methods + classes:
        out_edges = graph.get_edges_from(node.id)

        # Must have at least one GUARDS edge
        guards_edges = [e for e in out_edges if e.kind == EdgeKind.GUARDS]
        if not guards_edges:
            continue

        # Check for retry/fallback pattern via name or metadata
        name_lower = node.name.lower()
        has_keyword = any(kw in name_lower for kw in circuit_keywords)

        has_retry_metadata = False
        if node.metadata:
            meta_str = str(node.metadata).lower()
            has_retry_metadata = any(kw in meta_str for kw in circuit_keywords)

        if has_keyword or has_retry_metadata:
            guarded_ids = [e.target_id for e in guards_edges]
            matches.append(
                {
                    "node_id": node.id,
                    "guarded_ids": guarded_ids,
                    "guards_count": len(guards_edges),
                    "keyword_match": has_keyword,
                    "metadata_match": has_retry_metadata,
                }
            )

    return matches

ErrorBoundaryRule

Bases: TranslationRule

Maps error handling boundaries to error-handling modality.

Detects functions/methods with CATCHES or THROWS edges, representing error boundaries in the system.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.70). Bottom band (0.70). Rationale: CATCHES/THROWS edges are directly extracted from try/except / raise Python constructs (high structural precision) but the semantic meaning — "this is an error boundary worth modeling" — is weak because most non-trivial functions have at least one try/except for cleanup. Parser certainty 0.75 (below the 0.80 norm) reflects the fact that tree-sitter does not resolve exception-type hierarchies.

Source code in py/cogant/translate/rules/resilience.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
class ErrorBoundaryRule(TranslationRule):
    """Maps error handling boundaries to error-handling modality.

    Detects functions/methods with CATCHES or THROWS edges, representing
    error boundaries in the system.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.70)``. **Bottom band** (0.70).
        Rationale: CATCHES/THROWS edges are directly extracted from
        ``try/except`` / ``raise`` Python constructs (high structural
        precision) but the *semantic* meaning — "this is an error
        boundary worth modeling" — is weak because most non-trivial
        functions have at least one try/except for cleanup. Parser
        certainty 0.75 (below the 0.80 norm) reflects the fact that
        tree-sitter does not resolve exception-type hierarchies.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with CATCHES or THROWS edges.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched error boundary nodes.
        """
        matches = []

        # Find functions and methods
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            out_edges = graph.get_edges_from(node.id)

            catches_edges = [e for e in out_edges if e.kind == EdgeKind.CATCHES]
            throws_edges = [e for e in out_edges if e.kind == EdgeKind.THROWS]

            if not catches_edges and not throws_edges:
                continue

            # Caught exception node IDs form the graph fragment
            caught_node_ids = [e.target_id for e in catches_edges]
            thrown_node_ids = [e.target_id for e in throws_edges]

            matches.append(
                {
                    "node_id": node.id,
                    "caught_node_ids": caught_node_ids,
                    "thrown_node_ids": thrown_node_ids,
                    "catches_count": len(catches_edges),
                    "throws_count": len(throws_edges),
                }
            )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create error-handling mapping for error boundary node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for error handling.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        fragment_node_ids = (
            [node_id] + match.get("caught_node_ids", []) + match.get("thrown_node_ids", [])
        )

        mapping_id = f"errbnd_{node_id}_{hashlib.sha256(b'error_boundary').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # CATCHES/THROWS edges are structurally precise but
        # semantically overloaded: most non-trivial functions have
        # some error handling. Parser certainty 0.75 reflects the
        # lack of exception-hierarchy resolution in tree-sitter.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.ERROR_HANDLING,
            graph_fragment_node_ids=fragment_node_ids,
            semantic_label=f"{node.name} - Error Boundary",
            description=f"Function '{node.name}' handles errors (catches {match['catches_count']}, throws {match['throws_count']})",
            confidence_score=0.70,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.70,
                    metadata={
                        "catches_count": match["catches_count"],
                        "throws_count": match["throws_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.75,  # no exception-hierarchy resolution
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "error_boundary"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.ERROR_HANDLING

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create error-handling mapping for error boundary node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for error handling.

Source code in py/cogant/translate/rules/resilience.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create error-handling mapping for error boundary node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for error handling.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    fragment_node_ids = (
        [node_id] + match.get("caught_node_ids", []) + match.get("thrown_node_ids", [])
    )

    mapping_id = f"errbnd_{node_id}_{hashlib.sha256(b'error_boundary').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # CATCHES/THROWS edges are structurally precise but
    # semantically overloaded: most non-trivial functions have
    # some error handling. Parser certainty 0.75 reflects the
    # lack of exception-hierarchy resolution in tree-sitter.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.ERROR_HANDLING,
        graph_fragment_node_ids=fragment_node_ids,
        semantic_label=f"{node.name} - Error Boundary",
        description=f"Function '{node.name}' handles errors (catches {match['catches_count']}, throws {match['throws_count']})",
        confidence_score=0.70,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.70,
                metadata={
                    "catches_count": match["catches_count"],
                    "throws_count": match["throws_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.75,  # no exception-hierarchy resolution
    )

matches(graph, query)

Find nodes with CATCHES or THROWS edges.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched error boundary nodes.

Source code in py/cogant/translate/rules/resilience.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with CATCHES or THROWS edges.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched error boundary nodes.
    """
    matches = []

    # Find functions and methods
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        out_edges = graph.get_edges_from(node.id)

        catches_edges = [e for e in out_edges if e.kind == EdgeKind.CATCHES]
        throws_edges = [e for e in out_edges if e.kind == EdgeKind.THROWS]

        if not catches_edges and not throws_edges:
            continue

        # Caught exception node IDs form the graph fragment
        caught_node_ids = [e.target_id for e in catches_edges]
        thrown_node_ids = [e.target_id for e in throws_edges]

        matches.append(
            {
                "node_id": node.id,
                "caught_node_ids": caught_node_ids,
                "thrown_node_ids": thrown_node_ids,
                "catches_count": len(catches_edges),
                "throws_count": len(throws_edges),
            }
        )

    return matches

RateLimiterRule

Bases: TranslationRule

Maps rate-limiting patterns to throttling modality.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.75). Mid band (0.75), tied with MutatingSubsystemRule/ContainmentRule/ DataPipelineRule/EventBusRule. Rationale: rate-limiting detection depends on keyword matching (rate_limit, throttle_) or structural patterns (sleep/backoff loops with rate checks). Patterns: decorator-based rate limiters (@rate_limit), token-bucket implementations, leaky-bucket algorithms, sleep-based backoff with rate calculations. TODO(calibration): measure rate-limiter coverage on the 20-repo corpus; if <30%, promote to 0.80 as the pattern is becoming more common in microservices.

Source code in py/cogant/translate/rules/resilience.py
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
class RateLimiterRule(TranslationRule):
    """Maps rate-limiting patterns to throttling modality.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.75)``. **Mid band** (0.75), tied
        with ``MutatingSubsystemRule``/``ContainmentRule``/
        ``DataPipelineRule``/``EventBusRule``. Rationale: rate-limiting
        detection depends on keyword matching (``rate_limit``,
        ``throttle_``) or structural patterns (sleep/backoff loops with
        rate checks). Patterns: decorator-based rate limiters (``@rate_limit``),
        token-bucket implementations, leaky-bucket algorithms, sleep-based
        backoff with rate calculations. TODO(calibration): measure
        rate-limiter coverage on the 20-repo corpus; if <30%, promote to 0.80
        as the pattern is becoming more common in microservices.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find rate-limiting patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched rate limiter nodes.
        """
        matches = []

        rate_keywords = [
            "rate_limit",
            "throttle_",
            "token_bucket",
            "leaky_bucket",
            "ratelimit",
            "rate_limit",
            "quota",
            "throttle",
            "backoff",
        ]

        # Find functions and methods with rate-limiting keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        methods = graph.get_nodes_by_kind(NodeKind.METHOD)

        for node in functions + methods:
            name_lower = node.name.lower()
            has_rate_keyword = any(kw in name_lower for kw in rate_keywords)

            # Check for sleep/backoff pattern with rate logic
            out_edges = graph.get_edges_from(node.id)
            calls = [e for e in out_edges if e.kind == EdgeKind.CALLS]
            has_sleep_or_backoff = any(
                "sleep" in e.target_id.lower() or "backoff" in e.target_id.lower() for e in calls
            )

            if has_rate_keyword or has_sleep_or_backoff:
                matches.append(
                    {
                        "node_id": node.id,
                        "rate_keyword": has_rate_keyword,
                        "has_backoff": has_sleep_or_backoff,
                    }
                )

        # Find classes that implement rate limiting
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)
        for cls in classes:
            name_lower = cls.name.lower()
            if any(kw in name_lower for kw in rate_keywords):
                matches.append(
                    {
                        "node_id": cls.id,
                        "rate_keyword": True,
                        "has_backoff": False,
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create rate-limiter mapping.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for rate limiter.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"ratelim_{node_id}_{hashlib.sha256(b'rate_limiter').hexdigest()[:8]}"

        # Confidence 0.75 — principled default (mid band). Rate-limiting
        # patterns are identifiable but depend on keyword matching or
        # structural patterns that can have false positives (e.g., any
        # sleep call isn't necessarily rate-limiting). Parser certainty
        # 0.80 for keyword-based detection (AST-native).
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Rate Limiter",
            description=f"Function/class '{node.name}' implements rate limiting or throttling",
            confidence_score=0.75,  # principled default (mid band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.75,
                    metadata={
                        "rate_keyword": match.get("rate_keyword", False),
                        "has_backoff": match.get("has_backoff", False),
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.8,  # keyword detection + call graph
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "rate_limiter"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create rate-limiter mapping.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for rate limiter.

Source code in py/cogant/translate/rules/resilience.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create rate-limiter mapping.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for rate limiter.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"ratelim_{node_id}_{hashlib.sha256(b'rate_limiter').hexdigest()[:8]}"

    # Confidence 0.75 — principled default (mid band). Rate-limiting
    # patterns are identifiable but depend on keyword matching or
    # structural patterns that can have false positives (e.g., any
    # sleep call isn't necessarily rate-limiting). Parser certainty
    # 0.80 for keyword-based detection (AST-native).
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Rate Limiter",
        description=f"Function/class '{node.name}' implements rate limiting or throttling",
        confidence_score=0.75,  # principled default (mid band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.75,
                metadata={
                    "rate_keyword": match.get("rate_keyword", False),
                    "has_backoff": match.get("has_backoff", False),
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.8,  # keyword detection + call graph
    )

matches(graph, query)

Find rate-limiting patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched rate limiter nodes.

Source code in py/cogant/translate/rules/resilience.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find rate-limiting patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched rate limiter nodes.
    """
    matches = []

    rate_keywords = [
        "rate_limit",
        "throttle_",
        "token_bucket",
        "leaky_bucket",
        "ratelimit",
        "rate_limit",
        "quota",
        "throttle",
        "backoff",
    ]

    # Find functions and methods with rate-limiting keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    methods = graph.get_nodes_by_kind(NodeKind.METHOD)

    for node in functions + methods:
        name_lower = node.name.lower()
        has_rate_keyword = any(kw in name_lower for kw in rate_keywords)

        # Check for sleep/backoff pattern with rate logic
        out_edges = graph.get_edges_from(node.id)
        calls = [e for e in out_edges if e.kind == EdgeKind.CALLS]
        has_sleep_or_backoff = any(
            "sleep" in e.target_id.lower() or "backoff" in e.target_id.lower() for e in calls
        )

        if has_rate_keyword or has_sleep_or_backoff:
            matches.append(
                {
                    "node_id": node.id,
                    "rate_keyword": has_rate_keyword,
                    "has_backoff": has_sleep_or_backoff,
                }
            )

    # Find classes that implement rate limiting
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)
    for cls in classes:
        name_lower = cls.name.lower()
        if any(kw in name_lower for kw in rate_keywords):
            matches.append(
                {
                    "node_id": cls.id,
                    "rate_keyword": True,
                    "has_backoff": False,
                }
            )

    return matches

RetryPatternRule

Bases: TranslationRule

Maps retry/backoff/circuit breaker patterns to policy under uncertainty.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.70). Bottom band (0.70), tied with ReadOnlyInputRule, InheritanceRule, ErrorBoundaryRule, and the lexical fallback of ObservationRule. Rationale: keyword matching alone is a weak signal for retry logic — a function named retry_count might be a counter, not a retry executor. This rule intentionally loses to the stronger CircuitBreakerRule (0.80) when both fire. Parser certainty 0.70 is the lowest in the family because tree- sitter pattern detection for retry decorators is incomplete. TODO(calibration): promote to 0.80 if GUARDS edge coverage improves in the parser.

Source code in py/cogant/translate/rules/resilience.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class RetryPatternRule(TranslationRule):
    """Maps retry/backoff/circuit breaker patterns to policy under uncertainty.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.70)``. **Bottom band** (0.70),
        tied with ``ReadOnlyInputRule``, ``InheritanceRule``,
        ``ErrorBoundaryRule``, and the lexical fallback of
        ``ObservationRule``. Rationale: keyword matching alone is
        a weak signal for retry logic — a function named
        ``retry_count`` might be a counter, not a retry executor.
        This rule intentionally loses to the stronger
        ``CircuitBreakerRule`` (0.80) when both fire. Parser
        certainty 0.70 is the lowest in the family because tree-
        sitter pattern detection for retry decorators is
        incomplete. TODO(calibration): promote to 0.80 if GUARDS
        edge coverage improves in the parser.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find retry and circuit breaker patterns.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched pattern nodes.
        """
        matches = []

        # Look for functions/methods with retry/circuit breaker keywords
        functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
        functions.extend(graph.get_nodes_by_kind(NodeKind.METHOD))

        retry_keywords = ["retry", "backoff", "circuit", "breaker", "timeout", "fallback"]

        for func in functions:
            name_lower = func.name.lower()
            if any(keyword in name_lower for keyword in retry_keywords):
                matches.append(
                    {
                        "node_id": func.id,
                        "pattern_type": "retry_or_circuit_breaker",
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create policy mapping for retry pattern.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for policy.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"policy_{node_id}_{hashlib.sha256(b'retry_pattern').hexdigest()[:8]}"

        # Confidence 0.70 — principled default (bottom band).
        # Keyword-only matching is noisy (``retry_count`` might be
        # just a counter). Parser certainty 0.70 is the lowest in
        # the family because decorator-based retry patterns have
        # incomplete tree-sitter coverage. Intentionally loses to
        # CircuitBreakerRule (0.80) on the same fragment.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.POLICY,
            graph_fragment_node_ids=[node_id],
            semantic_label=f"{node.name} - Retry Policy",
            description=f"Function '{node.name}' implements retry/circuit breaker policy",
            confidence_score=0.7,  # principled default (bottom band)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.7,
                )
            ],
            evidence_count=1,
            parser_certainty=0.7,  # lowest in family (decorator gap)
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "retry_pattern"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.POLICY

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create policy mapping for retry pattern.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for policy.

Source code in py/cogant/translate/rules/resilience.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create policy mapping for retry pattern.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for policy.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"policy_{node_id}_{hashlib.sha256(b'retry_pattern').hexdigest()[:8]}"

    # Confidence 0.70 — principled default (bottom band).
    # Keyword-only matching is noisy (``retry_count`` might be
    # just a counter). Parser certainty 0.70 is the lowest in
    # the family because decorator-based retry patterns have
    # incomplete tree-sitter coverage. Intentionally loses to
    # CircuitBreakerRule (0.80) on the same fragment.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.POLICY,
        graph_fragment_node_ids=[node_id],
        semantic_label=f"{node.name} - Retry Policy",
        description=f"Function '{node.name}' implements retry/circuit breaker policy",
        confidence_score=0.7,  # principled default (bottom band)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.7,
            )
        ],
        evidence_count=1,
        parser_certainty=0.7,  # lowest in family (decorator gap)
    )

matches(graph, query)

Find retry and circuit breaker patterns.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched pattern nodes.

Source code in py/cogant/translate/rules/resilience.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find retry and circuit breaker patterns.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched pattern nodes.
    """
    matches = []

    # Look for functions/methods with retry/circuit breaker keywords
    functions = graph.get_nodes_by_kind(NodeKind.FUNCTION)
    functions.extend(graph.get_nodes_by_kind(NodeKind.METHOD))

    retry_keywords = ["retry", "backoff", "circuit", "breaker", "timeout", "fallback"]

    for func in functions:
        name_lower = func.name.lower()
        if any(keyword in name_lower for keyword in retry_keywords):
            matches.append(
                {
                    "node_id": func.id,
                    "pattern_type": "retry_or_circuit_breaker",
                }
            )

    return matches

SingletonAccessRule

Bases: TranslationRule

Maps singleton/global state access to context modality.

Detects variables or classes that are read by many different modules (high in-degree of READS edges from diverse paths). Threshold: 3+ readers from different modules.

Rule priority (audit 2026-04-09): Effective priority = (0, 0.65). Lowest band (0.65) — the lowest confidence score in the entire rule family. Rationale: "accessed by many modules" is a very weak signal (logging facilities, common types, and enum constants all trigger it), so this rule is explicitly the last to win in any conflict. Thresholds: read_edges >= 3 and len(reader_modules) >= 3. The module-diversity check prevents the rule from firing on intra-module utilities. TODO(calibration): if the false-positive rate on the 20-repo corpus exceeds 30%, raise the module-diversity threshold to 5 or combine with a "not in typing/stdlib whitelist" filter.

Source code in py/cogant/translate/rules/resilience.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
class SingletonAccessRule(TranslationRule):
    """Maps singleton/global state access to context modality.

    Detects variables or classes that are read by many different modules
    (high in-degree of READS edges from diverse paths). Threshold: 3+ readers
    from different modules.

    Rule priority (audit 2026-04-09):
        Effective priority = ``(0, 0.65)``. **Lowest band** (0.65) —
        the lowest confidence score in the entire rule family.
        Rationale: "accessed by many modules" is a very weak signal
        (logging facilities, common types, and enum constants all
        trigger it), so this rule is explicitly the last to win in
        any conflict. Thresholds: ``read_edges >= 3`` and
        ``len(reader_modules) >= 3``. The module-diversity check
        prevents the rule from firing on intra-module utilities.
        TODO(calibration): if the false-positive rate on the
        20-repo corpus exceeds 30%, raise the module-diversity
        threshold to 5 or combine with a "not in typing/stdlib
        whitelist" filter.
    """

    def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
        """Find nodes with high in-degree READS from diverse modules.

        Args:
            graph: Program graph.
            query: Graph query engine.

        Returns:
            List of matched singleton/global state nodes.
        """
        matches = []

        # Check variables and classes as potential singletons
        variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
        classes = graph.get_nodes_by_kind(NodeKind.CLASS)

        for node in variables + classes:
            # Find incoming READS edges
            incoming = graph.get_edges_to(node.id)
            read_edges = [e for e in incoming if e.kind == EdgeKind.READS]

            # Read-count threshold = 3. Principled default: below 3
            # readers is indistinguishable from ordinary 2-caller
            # helper code. TODO(calibration): sweep {3, 5, 8} on
            # 20-repo corpus; consider combining with a "stdlib/
            # typing whitelist" filter to cut false positives.
            if len(read_edges) < 3:
                continue

            # Check diversity: count unique module paths among readers
            reader_modules = set()
            reader_ids = []
            for edge in read_edges:
                reader = graph.get_node(edge.source_id)
                if reader and reader.path:
                    # Extract module path (directory portion)
                    parts = reader.path.rsplit("/", 1)
                    module_path = parts[0] if len(parts) > 1 else reader.path
                    reader_modules.add(module_path)
                reader_ids.append(edge.source_id)

            # Module-diversity threshold = 3. Principled default:
            # fewer than 3 distinct module paths in the reader set
            # typically indicates an intra-package helper rather
            # than a true singleton/global. Matches the read-count
            # threshold for symmetry. TODO(calibration): sweep {3,
            # 5, 8} in tandem with the read-count sweep.
            if len(reader_modules) >= 3:
                matches.append(
                    {
                        "node_id": node.id,
                        "reader_ids": reader_ids,
                        "reader_count": len(read_edges),
                        "module_count": len(reader_modules),
                    }
                )

        return matches

    def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
        """Create context mapping for singleton/global state node.

        Args:
            graph: Program graph.
            match: Matched pattern.

        Returns:
            SemanticMapping for context.
        """
        node_id = match["node_id"]
        node = graph.get_node(node_id)

        if not node:
            return None

        mapping_id = f"single_{node_id}_{hashlib.sha256(b'singleton_access').hexdigest()[:8]}"

        # Confidence 0.65 — principled default (LOWEST band in the
        # entire rule family). "Accessed by many modules" is a very
        # weak semantic signal; this rule is explicitly the last to
        # win in any conflict. 0.65 = STATIC_PLUS_RUNTIME_THRESHOLD
        # exactly, so this rule's mapping is *only* promoted past
        # the "trust without review" bar if runtime evidence
        # corroborates it.
        return SemanticMapping(
            id=mapping_id,
            kind=MappingKind.CONTEXT,
            graph_fragment_node_ids=[node_id] + match.get("reader_ids", []),
            semantic_label=f"{node.name} - Singleton/Global State",
            description=f"{'Variable' if node.kind == NodeKind.VARIABLE else 'Class'} '{node.name}' is accessed by {match['reader_count']} readers across {match['module_count']} modules",
            confidence_score=0.65,  # principled default (LOWEST in family)
            confidence_tier=ConfidenceTier.STATIC_ONLY,
            provenance=[
                ProvenanceRecord(
                    source="static_analysis",
                    confidence=0.65,
                    metadata={
                        "reader_count": match["reader_count"],
                        "module_count": match["module_count"],
                    },
                )
            ],
            evidence_count=1,
            parser_certainty=0.7,  # cross-module READS noise
        )

    @property
    def name(self) -> str:
        """Stable identifier for this rule."""
        return "singleton_access"

    @property
    def mapping_kind(self) -> MappingKind:
        """GNN mapping kind produced by this rule."""
        return MappingKind.CONTEXT

mapping_kind property

GNN mapping kind produced by this rule.

name property

Stable identifier for this rule.

apply(graph, match)

Create context mapping for singleton/global state node.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
match dict[str, Any]

Matched pattern.

required

Returns:

Type Description
SemanticMapping | None

SemanticMapping for context.

Source code in py/cogant/translate/rules/resilience.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def apply(self, graph: ProgramGraph, match: dict[str, Any]) -> SemanticMapping | None:
    """Create context mapping for singleton/global state node.

    Args:
        graph: Program graph.
        match: Matched pattern.

    Returns:
        SemanticMapping for context.
    """
    node_id = match["node_id"]
    node = graph.get_node(node_id)

    if not node:
        return None

    mapping_id = f"single_{node_id}_{hashlib.sha256(b'singleton_access').hexdigest()[:8]}"

    # Confidence 0.65 — principled default (LOWEST band in the
    # entire rule family). "Accessed by many modules" is a very
    # weak semantic signal; this rule is explicitly the last to
    # win in any conflict. 0.65 = STATIC_PLUS_RUNTIME_THRESHOLD
    # exactly, so this rule's mapping is *only* promoted past
    # the "trust without review" bar if runtime evidence
    # corroborates it.
    return SemanticMapping(
        id=mapping_id,
        kind=MappingKind.CONTEXT,
        graph_fragment_node_ids=[node_id] + match.get("reader_ids", []),
        semantic_label=f"{node.name} - Singleton/Global State",
        description=f"{'Variable' if node.kind == NodeKind.VARIABLE else 'Class'} '{node.name}' is accessed by {match['reader_count']} readers across {match['module_count']} modules",
        confidence_score=0.65,  # principled default (LOWEST in family)
        confidence_tier=ConfidenceTier.STATIC_ONLY,
        provenance=[
            ProvenanceRecord(
                source="static_analysis",
                confidence=0.65,
                metadata={
                    "reader_count": match["reader_count"],
                    "module_count": match["module_count"],
                },
            )
        ],
        evidence_count=1,
        parser_certainty=0.7,  # cross-module READS noise
    )

matches(graph, query)

Find nodes with high in-degree READS from diverse modules.

Parameters:

Name Type Description Default
graph ProgramGraph

Program graph.

required
query GraphQuery

Graph query engine.

required

Returns:

Type Description
list[dict[str, Any]]

List of matched singleton/global state nodes.

Source code in py/cogant/translate/rules/resilience.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def matches(self, graph: ProgramGraph, query: GraphQuery) -> list[dict[str, Any]]:
    """Find nodes with high in-degree READS from diverse modules.

    Args:
        graph: Program graph.
        query: Graph query engine.

    Returns:
        List of matched singleton/global state nodes.
    """
    matches = []

    # Check variables and classes as potential singletons
    variables = graph.get_nodes_by_kind(NodeKind.VARIABLE)
    classes = graph.get_nodes_by_kind(NodeKind.CLASS)

    for node in variables + classes:
        # Find incoming READS edges
        incoming = graph.get_edges_to(node.id)
        read_edges = [e for e in incoming if e.kind == EdgeKind.READS]

        # Read-count threshold = 3. Principled default: below 3
        # readers is indistinguishable from ordinary 2-caller
        # helper code. TODO(calibration): sweep {3, 5, 8} on
        # 20-repo corpus; consider combining with a "stdlib/
        # typing whitelist" filter to cut false positives.
        if len(read_edges) < 3:
            continue

        # Check diversity: count unique module paths among readers
        reader_modules = set()
        reader_ids = []
        for edge in read_edges:
            reader = graph.get_node(edge.source_id)
            if reader and reader.path:
                # Extract module path (directory portion)
                parts = reader.path.rsplit("/", 1)
                module_path = parts[0] if len(parts) > 1 else reader.path
                reader_modules.add(module_path)
            reader_ids.append(edge.source_id)

        # Module-diversity threshold = 3. Principled default:
        # fewer than 3 distinct module paths in the reader set
        # typically indicates an intra-package helper rather
        # than a true singleton/global. Matches the read-count
        # threshold for symmetry. TODO(calibration): sweep {3,
        # 5, 8} in tandem with the read-count sweep.
        if len(reader_modules) >= 3:
            matches.append(
                {
                    "node_id": node.id,
                    "reader_ids": reader_ids,
                    "reader_count": len(read_edges),
                    "module_count": len(reader_modules),
                }
            )

    return matches

Examples

TranslationEngine, the confidence scorer, the review API, and every rule family above are exercised by: