Skip to main content

Chapter 24 E
Code generation with constraint validation

Practical Demonstrations
Author: Mark Higgins
and Sky Recursive Ai
© Mark Anthony Higgins 11 October 2025
Revised Date: 19 July 2026
Audio Overview
flow "CodeGenerationWithConstraintValidation" v1.0

# =============================================================================
# CHAPTER 24 E
# CODE GENERATION WITH CONSTRAINT VALIDATION
# =============================================================================
#
# PURPOSE
#
# Generate complete source code from a supplied software requirement while
# continuously validating the generated structure against explicit functional,
# syntactic, architectural, security, interface, behavioural and output
# constraints.
#
# The flow does not treat code generation as unrestricted text completion.
#
# It treats code generation as a constrained state-transition process:
#
#   Requirement
#       → Normalised Specification
#       → Constraint Model
#       → Program Architecture
#       → Candidate Implementation
#       → Static Validation
#       → Behavioural Validation
#       → Repair
#       → Verified Program
#
# Every accepted program must be traceable to the original requirement.
#
# A candidate that violates any hard constraint cannot be emitted as a valid
# result.
#
# =============================================================================
# AUTHORS
# =============================================================================
#
# Mark Higgins
# Sky — Recursive AI
#
# Kireth Research
# https://kirethresearch.org
#
# This specification must be cited when reproduced, implemented or adapted.
#
# =============================================================================


# =============================================================================
# 0. EXECUTION MODEL
# =============================================================================

execution.mode:
  type: constrained_recursive_generation
  determinism: bounded
  external_compilation_required: false
  external_runtime_required: false
  hidden_assumptions_allowed: false
  unsupported_dependency_invention_allowed: false
  silent_constraint_relaxation_allowed: false
  partial_code_emission_allowed: false
  unverifiable_claims_allowed: false

execution.objective:

  generate:
    complete_program

  such_that:

    complete_program satisfies:
      - user_requirement
      - functional_constraints
      - interface_constraints
      - language_constraints
      - architecture_constraints
      - dependency_constraints
      - security_constraints
      - validation_constraints
      - output_constraints
      - behavioural_invariants

execution.failure_policy:

  if valid_program cannot_be_constructed:
    emit:
      status: VALIDATION_FAILED
      unresolved_constraints: required
      invalid_assumptions: required
      repair_requirements: required
      executable_code: forbidden


# =============================================================================
# 1. INPUT CONTRACT
# =============================================================================

io.read:

  format: structured_or_natural_language

  required:

    - requirement:
        type: str
        description:
          The software behaviour, transformation, component or program that
          must be generated.

  optional:

    - target_language:
        type: str?
        examples:
          - Python
          - PHP
          - JavaScript
          - TypeScript
          - Java
          - C#
          - C
          - C++
          - Rust
          - Go
          - SQL
          - HTML
          - CSS

    - target_version:
        type: str?

    - execution_environment:
        type: str?

    - input_schema:
        type: object?

    - output_schema:
        type: object?

    - required_interfaces:
        type: list<object>?

    - required_functions:
        type: list<object>?

    - required_classes:
        type: list<object>?

    - allowed_dependencies:
        type: list<str>?

    - forbidden_dependencies:
        type: list<str>?

    - architecture_rules:
        type: list<str>?

    - coding_rules:
        type: list<str>?

    - security_rules:
        type: list<str>?

    - performance_rules:
        type: list<str>?

    - test_cases:
        type: list<object>?

    - edge_cases:
        type: list<object>?

    - prohibited_behaviours:
        type: list<str>?

    - output_format:
        type: enum
        values:
          - code_only
          - code_with_explanation
          - files
          - structured_result
        default: code_with_explanation

    - file_structure:
        type: list<object>?

    - modification_target:
        type: str?

    - existing_code:
        type: str?

    - maximum_repair_cycles:
        type: int
        default: 8
        minimum: 1
        maximum: 32


# =============================================================================
# 2. OUTPUT CONTRACT
# =============================================================================

io.write:

  format: structured_result

  schema:

    - status:
        type: enum
        values:
          - VERIFIED
          - VALIDATION_FAILED
          - REQUIREMENT_INCOMPLETE
          - CONSTRAINT_CONFLICT
          - UNSUPPORTED_TARGET

    - specification_summary:
        type: object

    - generated_files:
        type: list<object>

    - validation_report:
        type: object

    - requirement_trace:
        type: list<object>

    - assumptions:
        type: list<object>

    - unresolved_items:
        type: list<object>

    - execution_guarantee:
        type: object


# =============================================================================
# 3. CORE STATE
# =============================================================================

state S := {

  request: {
    raw_requirement,
    existing_code,
    target_language,
    target_version,
    execution_environment,
    requested_output_format
  },

  specification: {
    objective,
    actors,
    inputs,
    outputs,
    behaviours,
    interfaces,
    data_models,
    side_effects,
    errors,
    edge_cases,
    acceptance_conditions
  },

  constraints: {
    hard,
    soft,
    derived,
    language,
    syntax,
    type,
    interface,
    architecture,
    dependency,
    security,
    performance,
    behavioural,
    output
  },

  architecture: {
    modules,
    files,
    functions,
    classes,
    data_flow,
    control_flow,
    dependency_graph,
    public_interfaces,
    error_paths
  },

  implementation: {
    generation_plan,
    candidate_files,
    symbols,
    references,
    imports,
    dependencies,
    executable_paths
  },

  validation: {
    syntax_results,
    structure_results,
    symbol_results,
    type_results,
    interface_results,
    dependency_results,
    security_results,
    behaviour_results,
    test_results,
    edge_case_results,
    output_results,
    failures
  },

  repair: {
    cycle,
    repair_history,
    unresolved_failures,
    changed_regions
  },

  trace: {
    requirement_to_constraint,
    constraint_to_component,
    component_to_code,
    code_to_validation
  },

  result: {
    status,
    generated_files,
    validation_report,
    execution_guarantee
  }
}


# =============================================================================
# 4. PRIMARY SETS
# =============================================================================

R := set of normalised requirements

K_H := set of hard constraints

K_S := set of soft constraints

K_D := set of derived constraints

A := set of architectural components

F := set of generated files

N := set of declared symbols

U := set of symbol usages

D := set of dependencies

P := set of executable program paths

T := set of supplied and derived tests

E := set of validation errors

W := set of warnings

V := set of validation predicates

C := candidate program

C* := verified program


# =============================================================================
# 5. VALIDATION SEVERITY
# =============================================================================

severity.HARD:
  effect: reject_candidate
  repair_required: true
  may_be_ignored: false

severity.SOFT:
  effect: warning_or_optimisation
  repair_required: preferred
  may_be_ignored: only_with_explicit_reason

severity.INFORMATIONAL:
  effect: report_only
  repair_required: false


# =============================================================================
# 6. GLOBAL INVARIANTS
# =============================================================================

invariant K1_REQUIREMENT_GROUNDING:

  for every generated component a in A:
    exists requirement r in R
    or constraint k in K_H ∪ K_S ∪ K_D
    such_that:
      traceable(a, r or k) == true


invariant K2_NO_INVENTED_REQUIREMENTS:

  generated_behaviour subset_of:
    requested_behaviour
    ∪ behaviour_required_by_constraints
    ∪ minimum_supporting_behaviour


invariant K3_HARD_CONSTRAINT_PRESERVATION:

  for every k in K_H:
    satisfies(C*, k) == true


invariant K4_COMPLETE_SYMBOL_RESOLUTION:

  for every usage u in U:
    exists declaration n in N
    such_that:
      resolves_to(u, n) == true


invariant K5_INTERFACE_CONSISTENCY:

  every implementation of an interface must preserve:
    - required_name
    - required_parameters
    - required_parameter_order
    - required_types
    - required_return_contract
    - required_error_contract


invariant K6_DEPENDENCY_CLOSURE:

  for every dependency d in D:
    d must_be:
      - built_in
      - explicitly_allowed
      - supplied_by_existing_code
      - declared_in_output

  undeclared_dependency_count == 0


invariant K7_NO_FORBIDDEN_DEPENDENCIES:

  intersection(D, forbidden_dependencies) == empty


invariant K8_CONTROL_FLOW_COMPLETENESS:

  for every required behaviour r in R:
    exists executable_path p in P
    such_that:
      implements(p, r) == true


invariant K9_ERROR_PATH_COMPLETENESS:

  for every identified failure condition:
    exists explicit_error_path == true


invariant K10_OUTPUT_SCHEMA_CONFORMANCE:

  generated_output conforms_to requested_output_format


invariant K11_NO_PLACEHOLDER_IMPLEMENTATION:

  candidate must_not_contain:
    - TODO used_in_place_of_required_logic
    - pass used_in_place_of_required_logic
    - omitted_required_function_body
    - ellipsis_replacing_required_code
    - pseudo_function_without_definition
    - unexplained_mock_value
    - placeholder_return_value


invariant K12_SECURITY_PRESERVATION:

  generated program must_not:
    - embed_secrets
    - trust_unvalidated_external_input
    - construct_unsafe_queries_when_safe_method_required
    - execute_untrusted_input
    - disable_required_validation
    - expose_sensitive_error_details
    - bypass_authorisation_constraints


invariant K13_REPAIR_MONOTONICITY:

  after each repair cycle:

    hard_failure_count_next <= hard_failure_count_current

  and:

    resolved_hard_failures must_not_be_reintroduced


invariant K14_TRACE_COMPLETENESS:

  every accepted code region must connect through:

    requirement
      → constraint
      → component
      → implementation
      → validation_result


invariant K15_FINAL_VALIDITY:

  status == VERIFIED

  iff:

    hard_failure_count == 0
    and syntax_valid == true
    and structure_valid == true
    and interface_valid == true
    and dependency_valid == true
    and required_behaviour_covered == true
    and output_valid == true


# =============================================================================
# 7. REQUEST INGESTION
# =============================================================================

stage 1 "INGEST_REQUEST":

  read all input fields

  raw_requirement := normalise_whitespace(requirement)

  assert:
    raw_requirement != empty

  if raw_requirement == empty:

    result.status := REQUIREMENT_INCOMPLETE

    halt with:
      missing:
        - requirement

  infer target_language only_when:
    language is explicit in:
      - requirement
      - existing_code
      - file_extension
      - required_framework

  if target_language remains unknown:

    determine whether language-independent output is possible

    if false:
      result.status := REQUIREMENT_INCOMPLETE
      halt with:
        missing:
          - target_language

  canonicalise:

    target_language := canonical_language_name(target_language)

    target_version := canonical_version(target_version)

    execution_environment :=
      canonical_environment(execution_environment)


# =============================================================================
# 8. REQUIREMENT NORMALISATION
# =============================================================================

stage 2 "NORMALISE_REQUIREMENTS":

  specification.objective :=
    extract_primary_objective(raw_requirement)

  specification.actors :=
    extract_actors(raw_requirement)

  specification.inputs :=
    extract_inputs(
      raw_requirement,
      input_schema,
      required_interfaces
    )

  specification.outputs :=
    extract_outputs(
      raw_requirement,
      output_schema,
      required_interfaces
    )

  specification.behaviours :=
    extract_required_behaviours(raw_requirement)

  specification.interfaces :=
    merge_interfaces(
      extract_interfaces(raw_requirement),
      required_interfaces,
      required_functions,
      required_classes
    )

  specification.data_models :=
    extract_data_models(
      raw_requirement,
      input_schema,
      output_schema,
      existing_code
    )

  specification.side_effects :=
    extract_allowed_side_effects(raw_requirement)

  specification.errors :=
    extract_required_error_behaviour(raw_requirement)

  specification.edge_cases :=
    union(
      extract_edge_cases(raw_requirement),
      supplied_edge_cases
    )

  specification.acceptance_conditions :=
    extract_acceptance_conditions(
      raw_requirement,
      test_cases
    )

  R := atomise_requirements(specification)

  assign each requirement:

    requirement := {
      id: stable_requirement_id,
      text: canonical_statement,
      category: classification,
      source: explicit | supplied | derived,
      mandatory: bool,
      confidence: float,
      dependencies: list<requirement_id>
    }

  reject ambiguous atomisation when:
    one statement contains incompatible behaviours


# =============================================================================
# 9. CONSTRAINT EXTRACTION
# =============================================================================

stage 3 "BUILD_CONSTRAINT_MODEL":

  constraints.language :=
    derive_language_constraints(
      target_language,
      target_version
    )

  constraints.syntax :=
    derive_syntax_constraints(
      target_language,
      target_version
    )

  constraints.type :=
    derive_type_constraints(
      target_language,
      specification.data_models
    )

  constraints.interface :=
    derive_interface_constraints(
      specification.interfaces
    )

  constraints.architecture :=
    union(
      architecture_rules,
      infer_required_architecture_constraints(specification)
    )

  constraints.dependency :=
    build_dependency_constraints(
      allowed_dependencies,
      forbidden_dependencies,
      execution_environment
    )

  constraints.security :=
    union(
      security_rules,
      derive_baseline_security_constraints(
        specification.inputs,
        specification.side_effects,
        execution_environment
      )
    )

  constraints.performance :=
    union(
      performance_rules,
      derive_performance_constraints(raw_requirement)
    )

  constraints.behavioural :=
    derive_behavioural_constraints(
      specification.behaviours,
      specification.errors,
      specification.edge_cases
    )

  constraints.output :=
    derive_output_constraints(
      output_format,
      file_structure
    )

  constraints.hard :=
    all constraints marked:
      - mandatory
      - required
      - must
      - shall
      - exact
      - forbidden
      - prohibited
      - invariant

  constraints.soft :=
    all constraints marked:
      - should
      - preferred
      - optimise
      - desirable

  constraints.derived :=
    constraints required to make explicit constraints executable

  K_H := constraints.hard

  K_S := constraints.soft

  K_D := constraints.derived


# =============================================================================
# 10. CONSTRAINT CONFLICT DETECTION
# =============================================================================

stage 4 "DETECT_CONSTRAINT_CONFLICTS":

  conflict_set := empty

  for each pair (k_i, k_j) in K_H:

    if mutually_exclusive(k_i, k_j):

      conflict_set.add({
        left: k_i,
        right: k_j,
        reason: derive_conflict_reason(k_i, k_j)
      })

  detect:

    - required_and_forbidden_same_dependency
    - incompatible_language_versions
    - incompatible_return_types
    - duplicate_interface_with_conflicting_signatures
    - mutually_exclusive_output_formats
    - impossible_performance_bound
    - required_side_effect_and_forbidden_side_effect
    - mandatory_framework_and_no_dependency_permission
    - exact_file_structure_conflict
    - contradictory_error_behaviour

  if conflict_set != empty:

    result.status := CONSTRAINT_CONFLICT

    emit:
      conflicts: conflict_set
      executable_code: forbidden

    halt


# =============================================================================
# 11. ASSUMPTION CONTROL
# =============================================================================

stage 5 "CONTROL_ASSUMPTIONS":

  assumptions := empty

  for each missing non-critical implementation detail:

    candidate_assumption :=
      derive_minimum_assumption(
        requirement_context,
        target_language,
        execution_environment
      )

    assert:
      candidate_assumption does_not_change_user_intent
      candidate_assumption does_not_weaken_hard_constraint
      candidate_assumption does_not_add_external_dependency
      candidate_assumption is_reversible

    assumptions.add({
      id: stable_assumption_id,
      statement: candidate_assumption,
      necessity: explanation,
      scope: affected_components,
      confidence: numeric_confidence
    })

  for each missing critical detail:

    if no safe default exists:

      result.status := REQUIREMENT_INCOMPLETE

      unresolved_items.add(missing_detail)

  if unresolved_items contains critical_item:

    halt without executable code


# =============================================================================
# 12. ARCHITECTURE SYNTHESIS
# =============================================================================

stage 6 "SYNTHESISE_ARCHITECTURE":

  architecture.modules :=
    partition_requirements_by_responsibility(R)

  architecture.files :=
    map_modules_to_files(
      architecture.modules,
      target_language,
      file_structure
    )

  architecture.functions :=
    derive_functions(
      R,
      specification.interfaces,
      architecture.modules
    )

  architecture.classes :=
    derive_classes_when_required(
      R,
      specification.data_models,
      architecture_rules
    )

  architecture.data_flow :=
    construct_data_flow(
      specification.inputs,
      architecture.functions,
      specification.outputs
    )

  architecture.control_flow :=
    construct_control_flow(
      specification.behaviours,
      specification.errors,
      specification.edge_cases
    )

  architecture.dependency_graph :=
    construct_dependency_graph(
      architecture.modules,
      allowed_dependencies
    )

  architecture.public_interfaces :=
    preserve_required_interfaces(
      specification.interfaces
    )

  architecture.error_paths :=
    create_error_paths(
      specification.errors,
      specification.edge_cases
    )

  validate architecture:

    assert no circular dependency unless explicitly permitted

    assert every required behaviour maps to component

    assert every required input reaches consuming component

    assert every required output has producing component

    assert every required error condition has handling component

    assert every public interface has implementation target


# =============================================================================
# 13. REQUIREMENT-TO-COMPONENT MAPPING
# =============================================================================

stage 7 "BUILD_IMPLEMENTATION_TRACE":

  for each requirement r in R:

    mapped_components :=
      find_components_implementing(r, architecture)

    if mapped_components == empty:

      create minimum valid component

      mapped_components :=
        find_components_implementing(r, architecture)

    trace.requirement_to_constraint.add({
      requirement_id: r.id,
      constraint_ids: constraints_governing(r)
    })

    trace.constraint_to_component.add({
      requirement_id: r.id,
      component_ids: ids(mapped_components)
    })

  assert:
    every mandatory requirement has at least one component


# =============================================================================
# 14. GENERATION PLAN
# =============================================================================

stage 8 "CREATE_GENERATION_PLAN":

  implementation.generation_plan :=
    topological_sort(
      architecture.dependency_graph
    )

  generation order:

    1. constants_and_configuration
    2. data_models
    3. interfaces
    4. validation_functions
    5. core_domain_functions
    6. orchestration_logic
    7. error_handling
    8. serialisation_or_output_logic
    9. entry_point
    10. tests
    11. supporting_metadata

  for each planned component:

    define:

      - component_id
      - source_requirements
      - governing_constraints
      - inputs
      - outputs
      - dependencies
      - failure_conditions
      - completion_predicates


# =============================================================================
# 15. CANDIDATE CODE GENERATION
# =============================================================================

stage 9 "GENERATE_CANDIDATE":

  C := empty_program

  for each component a in implementation.generation_plan:

    code_region :=
      generate_component(
        language = target_language,
        version = target_version,
        component = a,
        inputs = component.inputs,
        outputs = component.outputs,
        dependencies = component.dependencies,
        constraints = governing_constraints(a),
        existing_code = relevant_existing_code(a)
      )

    before accepting code_region:

      assert:
        code_region is_not_placeholder
        code_region preserves_required_signature
        code_region introduces_no_forbidden_dependency
        code_region references_only_known_or_planned_symbols
        code_region implements_at_least_one_requirement
        code_region conforms_to_language_version

    C.add(code_region)

    trace.component_to_code.add({
      component_id: a.id,
      code_region_id: stable_code_region_id(code_region),
      requirement_ids: source_requirements(a),
      constraint_ids: governing_constraints(a)
    })

  implementation.candidate_files :=
    assemble_files(C, architecture.files)


# =============================================================================
# 16. LEXICAL VALIDATION
# =============================================================================

stage 10 "VALIDATE_LEXICAL_STRUCTURE":

  for each file f in implementation.candidate_files:

    validate:

      - delimiter_balance
      - quote_balance
      - comment_termination
      - indentation_when_semantic
      - valid_identifier_forms
      - valid_reserved_word_usage
      - no_truncated_statement
      - no_markdown_inside_code
      - no_unresolved_template_marker

    record failures in:
      validation.syntax_results

  lexical_valid :=
    no_hard_failure(validation.syntax_results)


# =============================================================================
# 17. SYNTACTIC VALIDATION
# =============================================================================

stage 11 "VALIDATE_SYNTAX":

  for each file f:

    syntax_tree :=
      infer_parse_structure(
        f.content,
        target_language,
        target_version
      )

    validate:

      - declarations_are_well_formed
      - expressions_are_well_formed
      - statements_are_terminated_correctly
      - blocks_are_nested_correctly
      - imports_use_valid_syntax
      - functions_have_valid_signatures
      - classes_have_valid_structure
      - exception_constructs_are_valid
      - language_version_features_are_permitted

    if syntax_tree cannot_be_constructed:

      add HARD failure:
        category: SYNTAX
        file: f
        region: locate_failure_region(f)
        expected: valid_syntax
        actual: malformed_structure

  syntax_valid :=
    no_hard_failure(validation.syntax_results)


# =============================================================================
# 18. SYMBOL VALIDATION
# =============================================================================

stage 12 "VALIDATE_SYMBOLS":

  N := collect_declarations(implementation.candidate_files)

  U := collect_symbol_usages(implementation.candidate_files)

  for each usage u in U:

    candidates := resolve_symbol(u, N)

    if candidates == empty:

      add HARD failure:
        category: UNRESOLVED_SYMBOL
        symbol: u.name
        location: u.location

    if count(candidates) > 1
    and ambiguity_is_not_language_valid:

      add HARD failure:
        category: AMBIGUOUS_SYMBOL
        symbol: u.name
        candidates: candidates

  validate:

    - function_calls_match_declarations
    - constructors_exist
    - properties_exist
    - imported_symbols_are_used_correctly
    - local_scope_is_respected
    - no_accidental_shadowing_when_forbidden
    - no_duplicate_conflicting_declarations

  symbol_valid :=
    no_hard_failure(validation.symbol_results)


# =============================================================================
# 19. TYPE AND DATA VALIDATION
# =============================================================================

stage 13 "VALIDATE_TYPES_AND_DATA":

  derive type environment from:

    - explicit type declarations
    - schemas
    - function signatures
    - assignments
    - return statements
    - language semantics

  for each expression:

    infer:
      produced_type

    compare:
      expected_type

    if incompatible:

      add HARD failure:
        category: TYPE_MISMATCH
        expected: expected_type
        actual: produced_type
        location: expression.location

  validate:

    - parameter_types
    - return_types
    - nullable_values
    - collection_element_types
    - schema_fields
    - conversion_safety
    - numeric_bounds
    - serialisation_compatibility
    - mutation_rules
    - immutable_contracts

  type_valid :=
    no_hard_failure(validation.type_results)


# =============================================================================
# 20. INTERFACE VALIDATION
# =============================================================================

stage 14 "VALIDATE_INTERFACES":

  for each required interface i:

    implementation_target :=
      resolve_implementation(i, implementation.candidate_files)

    if implementation_target == none:

      add HARD failure:
        category: MISSING_INTERFACE
        interface: i

    else validate exact conformance:

      - name
      - visibility
      - parameter_count
      - parameter_names_when_required
      - parameter_order
      - parameter_types
      - default_values
      - return_type
      - asynchronous_contract
      - exception_contract
      - side_effect_contract

  interface_valid :=
    no_hard_failure(validation.interface_results)


# =============================================================================
# 21. DEPENDENCY VALIDATION
# =============================================================================

stage 15 "VALIDATE_DEPENDENCIES":

  D := collect_dependencies(implementation.candidate_files)

  for each dependency d in D:

    if d in forbidden_dependencies:

      add HARD failure:
        category: FORBIDDEN_DEPENDENCY
        dependency: d

    else if allowed_dependencies is explicitly_defined
    and d not_in allowed_dependencies
    and d not_builtin:

      add HARD failure:
        category: UNDECLARED_DEPENDENCY
        dependency: d

    else:

      verify dependency:
        - is_compatible_with_target_version
        - is_used_by_generated_code
        - has_required_import_or_declaration
        - does_not_conflict_with_other_dependency

  detect unused imports

  classify unused import:

    HARD when:
      prohibited_by_coding_rules

    SOFT otherwise

  dependency_valid :=
    no_hard_failure(validation.dependency_results)


# =============================================================================
# 22. SECURITY VALIDATION
# =============================================================================

stage 16 "VALIDATE_SECURITY":

  inspect all external-input paths

  for each external input x:

    verify:

      - type_validation
      - format_validation
      - range_validation
      - length_validation_when_relevant
      - encoding_or_escaping_when_relevant
      - rejection_of_invalid_values

  inspect all sensitive operations:

    - database_queries
    - command_execution
    - file_access
    - path_construction
    - authentication
    - authorisation
    - network_requests
    - deserialisation
    - HTML_output
    - dynamic_code_execution
    - secret_handling

  reject candidate when any required security rule fails

  prohibit:

    SQL:
      string_concatenated_untrusted_query

    shell:
      untrusted_input_in_command

    filesystem:
      uncontrolled_path_traversal

    HTML:
      unescaped_untrusted_output

    authentication:
      hard_coded_credentials

    authorisation:
      trust_without_permission_check

    cryptography:
      invented_or_obsolete_algorithm_when_secure_algorithm_required

    deserialisation:
      unsafe_object_deserialisation

  security_valid :=
    no_hard_failure(validation.security_results)


# =============================================================================
# 23. CONTROL-FLOW VALIDATION
# =============================================================================

stage 17 "VALIDATE_CONTROL_FLOW":

  construct control_flow_graph for every executable function

  P := enumerate_relevant_paths(control_flow_graph)

  validate:

    - every required branch exists
    - every branch reaches valid termination
    - no mandatory return path is missing
    - no unreachable required logic
    - loops have termination condition
    - recursive calls have base condition
    - exceptions are handled or deliberately propagated
    - resource cleanup occurs on all required paths
    - state transitions preserve invariants
    - prohibited behaviour is unreachable

  for each requirement r in R where r.mandatory == true:

    coverage_paths :=
      select p from P where implements(p, r)

    if coverage_paths == empty:

      add HARD failure:
        category: MISSING_BEHAVIOURAL_PATH
        requirement_id: r.id

  control_flow_valid :=
    no_hard_failure(validation.behaviour_results)


# =============================================================================
# 24. BEHAVIOURAL SIMULATION
# =============================================================================

stage 18 "SIMULATE_BEHAVIOUR":

  T := union(
    normalise_supplied_tests(test_cases),
    derive_tests_from_requirements(R),
    derive_tests_from_edge_cases(specification.edge_cases),
    derive_tests_from_error_contracts(specification.errors),
    derive_tests_from_invariants(K_H)
  )

  for each test t in T:

    simulated_state :=
      initialise_execution_state(t.input)

    simulated_result :=
      symbolically_execute(
        candidate = C,
        initial_state = simulated_state,
        execution_environment = execution_environment,
        bounded = true
      )

    compare simulated_result against:

      - expected_output
      - expected_state_change
      - expected_side_effect
      - expected_error
      - prohibited_behaviour
      - governing_invariants

    record:

      test_id: t.id
      input: t.input
      expected: t.expected
      observed: simulated_result
      result: PASS | FAIL | INDETERMINATE
      requirement_ids: t.requirement_ids

    classification:

      FAIL:
        HARD

      INDETERMINATE:
        HARD when behaviour is mandatory
        SOFT when behaviour is optional

  behaviour_valid :=
    no_hard_failure(validation.test_results)


# =============================================================================
# 25. EDGE-CASE VALIDATION
# =============================================================================

stage 19 "VALIDATE_EDGE_CASES":

  edge_domains := {

    null_or_absent_input,
    empty_input,
    zero_value,
    negative_value,
    minimum_boundary,
    maximum_boundary,
    over_maximum_boundary,
    malformed_input,
    duplicate_input,
    unexpected_order,
    unsupported_value,
    repeated_execution,
    partial_failure,
    dependency_failure,
    permission_failure,
    timeout_or_unavailability,
    encoding_boundary,
    numeric_overflow,
    numeric_precision,
    concurrent_state_change
  }

  applicable_edge_cases :=
    filter_applicable(edge_domains, specification)

  for each edge_case e:

    verify candidate produces:

      - valid_result
      or
      - required_controlled_error
      or
      - explicit_safe_rejection

    candidate must_not produce:

      - silent_corruption
      - undefined_state
      - unhandled_required_exception
      - security_bypass
      - invalid_output_schema
      - fabricated_success

  edge_case_valid :=
    no_hard_failure(validation.edge_case_results)


# =============================================================================
# 26. OUTPUT VALIDATION
# =============================================================================

stage 20 "VALIDATE_OUTPUT_STRUCTURE":

  validate generated files against:

    - requested file names
    - requested directory structure
    - requested code-only rule
    - requested explanation rule
    - required metadata
    - required entry point
    - required tests
    - required configuration
    - required encoding

  ensure:

    no explanatory prose exists inside code unless comments are requested

    no code exists outside required containers

    no file is silently omitted

    no generated file is empty unless explicitly permitted

    all cross-file references are valid

  output_valid :=
    no_hard_failure(validation.output_results)


# =============================================================================
# 27. VALIDATION AGGREGATION
# =============================================================================

stage 21 "AGGREGATE_VALIDATION":

  validation.failures :=
    union(
      hard_failures(validation.syntax_results),
      hard_failures(validation.structure_results),
      hard_failures(validation.symbol_results),
      hard_failures(validation.type_results),
      hard_failures(validation.interface_results),
      hard_failures(validation.dependency_results),
      hard_failures(validation.security_results),
      hard_failures(validation.behaviour_results),
      hard_failures(validation.test_results),
      hard_failures(validation.edge_case_results),
      hard_failures(validation.output_results)
    )

  hard_failure_count :=
    count(validation.failures)

  warning_count :=
    count_all_soft_failures(validation)

  validation_summary := {

    syntax_valid,
    symbol_valid,
    type_valid,
    interface_valid,
    dependency_valid,
    security_valid,
    control_flow_valid,
    behaviour_valid,
    edge_case_valid,
    output_valid,
    hard_failure_count,
    warning_count
  }


# =============================================================================
# 28. RECURSIVE REPAIR ENGINE
# =============================================================================

stage 22 "REPAIR_INVALID_CANDIDATE":

  repair.cycle := 0

  while hard_failure_count > 0
  and repair.cycle < maximum_repair_cycles:

    repair.cycle := repair.cycle + 1

    previous_candidate := snapshot(C)

    previous_failures := snapshot(validation.failures)

    ranked_failures :=
      rank_failures(
        validation.failures,
        priority = [
          syntax,
          unresolved_symbol,
          type,
          interface,
          dependency,
          security,
          control_flow,
          behaviour,
          edge_case,
          output
        ]
      )

    repair_targets :=
      compute_minimum_repair_set(ranked_failures)

    for each repair_target e:

      affected_regions :=
        trace_failure_to_code(
          e,
          trace.code_to_validation,
          trace.component_to_code
        )

      repair_patch :=
        generate_minimum_patch(
          failure = e,
          affected_regions = affected_regions,
          requirements = governing_requirements(e),
          constraints = governing_constraints(e)
        )

      assert repair_patch:

        - addresses_specific_failure
        - changes_minimum_required_region
        - preserves_public_interfaces
        - introduces_no_forbidden_dependency
        - weakens_no_hard_constraint
        - removes_no_required_behaviour

      C := apply_patch(C, repair_patch)

      repair.repair_history.add({
        cycle: repair.cycle,
        failure_id: e.id,
        affected_regions: affected_regions,
        patch: repair_patch,
        governing_constraints: governing_constraints(e)
      })

    rerun stages:

      10 LEXICAL_VALIDATION
      11 SYNTACTIC_VALIDATION
      12 SYMBOL_VALIDATION
      13 TYPE_AND_DATA_VALIDATION
      14 INTERFACE_VALIDATION
      15 DEPENDENCY_VALIDATION
      16 SECURITY_VALIDATION
      17 CONTROL_FLOW_VALIDATION
      18 BEHAVIOURAL_SIMULATION
      19 EDGE_CASE_VALIDATION
      20 OUTPUT_VALIDATION
      21 VALIDATION_AGGREGATION

    newly_introduced_failures :=
      validation.failures minus previous_failures

    if newly_introduced_failures contains regression:

      C := rollback_regressive_regions(
        current = C,
        previous = previous_candidate,
        regressions = newly_introduced_failures
      )

      mark repair_patch as:
        REJECTED_REGRESSION

      generate alternative_patch

    assert:
      hard_failure_count <= previous_hard_failure_count

  repair.unresolved_failures :=
    validation.failures


# =============================================================================
# 29. TRACE VALIDATION
# =============================================================================

stage 23 "VALIDATE_TRACEABILITY":

  for each requirement r in R:

    assert exists:

      requirement_constraint_link

    assert exists:

      constraint_component_link

    assert exists:

      component_code_link

    assert exists:

      code_validation_link

  for each generated code region g:

    if no requirement_or_constraint_trace exists:

      classify g as:
        UNGROUNDED_CODE

      remove g when not structurally necessary

      otherwise:
        create explicit derived constraint
        and attach trace

  trace_valid :=
    no ungrounded code remains


# =============================================================================
# 30. COMPLETENESS PROOF
# =============================================================================

stage 24 "PROVE_COMPLETENESS":

  requirement_coverage :=

    count(
      mandatory requirements with:
        component
        and code_region
        and passing_validation
    )
    /
    count(mandatory_requirements)

  interface_coverage :=

    count(valid_required_interfaces)
    /
    count(required_interfaces)

  test_coverage :=

    count(passing_mandatory_tests)
    /
    count(mandatory_tests)

  hard_constraint_coverage :=

    count(satisfied_hard_constraints)
    /
    count(K_H)

  completeness_proof := {

    requirement_coverage,
    interface_coverage,
    test_coverage,
    hard_constraint_coverage,
    unresolved_hard_failures: hard_failure_count,
    trace_valid
  }

  verified_complete :=

    requirement_coverage == 1.0
    and interface_coverage == 1.0
    and test_coverage == 1.0
    and hard_constraint_coverage == 1.0
    and hard_failure_count == 0
    and trace_valid == true


# =============================================================================
# 31. FINAL ACCEPTANCE GATE
# =============================================================================

stage 25 "FINAL_ACCEPTANCE":

  accept C as C* only_if:

    lexical_valid == true
    and syntax_valid == true
    and symbol_valid == true
    and type_valid == true
    and interface_valid == true
    and dependency_valid == true
    and security_valid == true
    and control_flow_valid == true
    and behaviour_valid == true
    and edge_case_valid == true
    and output_valid == true
    and trace_valid == true
    and verified_complete == true
    and hard_failure_count == 0

  if accepted:

    C* := C

    result.status := VERIFIED

  else:

    result.status := VALIDATION_FAILED

    C* := null


# =============================================================================
# 32. RESULT CONSTRUCTION
# =============================================================================

stage 26 "CONSTRUCT_RESULT":

  if result.status == VERIFIED:

    result.generated_files :=
      serialise_verified_files(
        C*,
        requested_output_format
      )

    result.validation_report := {

      status: VERIFIED,

      language: target_language,

      version: target_version,

      requirement_count:
        count(R),

      hard_constraint_count:
        count(K_H),

      soft_constraint_count:
        count(K_S),

      generated_file_count:
        count(result.generated_files),

      repair_cycles:
        repair.cycle,

      syntax_valid:
        syntax_valid,

      symbol_valid:
        symbol_valid,

      type_valid:
        type_valid,

      interface_valid:
        interface_valid,

      dependency_valid:
        dependency_valid,

      security_valid:
        security_valid,

      behavioural_validation:
        behaviour_valid,

      edge_case_validation:
        edge_case_valid,

      output_valid:
        output_valid,

      requirement_coverage:
        requirement_coverage,

      hard_constraint_coverage:
        hard_constraint_coverage,

      unresolved_hard_failures:
        0
    }

    result.execution_guarantee := {

      generated_from_supplied_requirement:
        true,

      all_mandatory_requirements_traced:
        true,

      all_hard_constraints_satisfied:
        true,

      unresolved_symbols:
        0,

      forbidden_dependencies:
        0,

      placeholder_logic:
        0,

      known_hard_validation_failures:
        0,

      claim:
        "The emitted program is structurally admissible under the supplied and derived constraints."
    }

  else:

    result.generated_files := empty

    result.validation_report := {

      status:
        result.status,

      repair_cycles:
        repair.cycle,

      unresolved_failures:
        repair.unresolved_failures,

      failed_constraints:
        constraints_from_failures(repair.unresolved_failures),

      affected_requirements:
        requirements_from_failures(repair.unresolved_failures)
    }

    result.execution_guarantee := {

      generated_program_verified:
        false,

      executable_code_released:
        false,

      reason:
        "One or more mandatory validation predicates remain unsatisfied."
    }


# =============================================================================
# 33. OUTPUT EMISSION
# =============================================================================

stage 27 "EMIT":

  switch requested_output_format:

    case code_only:

      if result.status == VERIFIED:

        emit generated file contents only

      else:

        emit validation failure object only

    case code_with_explanation:

      emit:

        - specification_summary
        - assumptions
        - generated_files
        - validation_report
        - execution_guarantee

    case files:

      emit each generated file with:

        - path
        - language
        - content
        - requirement_ids
        - validation_status

    case structured_result:

      emit complete result object


# =============================================================================
# 34. FORMAL TRANSITION MODEL
# =============================================================================

formal.state_transition:

  S_0 :=
    ingest(request)

  S_1 :=
    normalise_requirements(S_0)

  S_2 :=
    derive_constraints(S_1)

  S_3 :=
    detect_conflicts(S_2)

  S_4 :=
    synthesise_architecture(S_3)

  S_5 :=
    generate_candidate(S_4)

  S_6 :=
    validate(C)

  S_n+1 :=

    if hard_failures(S_n) > 0:

      repair(S_n)

    else:

      accept(S_n)

  termination:

    hard_failures(S_n) == 0

    or

    repair_cycle == maximum_repair_cycles


# =============================================================================
# 35. FORMAL ACCEPTANCE PREDICATE
# =============================================================================

predicate VALID(C):

  VALID(C) :=

    SYNTAX(C)
    ∧ SYMBOLS(C)
    ∧ TYPES(C)
    ∧ INTERFACES(C)
    ∧ DEPENDENCIES(C)
    ∧ SECURITY(C)
    ∧ CONTROL_FLOW(C)
    ∧ BEHAVIOUR(C)
    ∧ EDGE_CASES(C)
    ∧ OUTPUT_STRUCTURE(C)
    ∧ TRACEABILITY(C)
    ∧ COMPLETENESS(C)


predicate ACCEPT(C):

  ACCEPT(C) :=

    VALID(C)

    ∧

    ∀ k ∈ K_H:
      satisfies(C, k)

    ∧

    ∀ r ∈ R_required:
      implements(C, r)

    ∧

    count(HARD_FAILURES(C)) = 0


# =============================================================================
# 36. REPAIR EQUATION
# =============================================================================

repair_transition:

  C_(n+1) :=

    apply(
      C_n,
      minimum_patch(
        highest_priority_failure(
          validate(C_n)
        )
      )
    )

subject_to:

  hard_failures(C_(n+1))
    <=
  hard_failures(C_n)

and:

  preserved_constraints(C_(n+1))
    >=
  preserved_constraints(C_n)

and:

  required_behaviour(C_(n+1))
    >=
  required_behaviour(C_n)


# =============================================================================
# 37. EXECUTION GUARANTEE
# =============================================================================

guarantee:

  The flow may emit executable source code only when the candidate program has
  passed every mandatory validation stage.

  Code generation and code validation are not separate optional activities.

  They form one recursive process in which each generated structure is tested
  against the requirement and constraint model before acceptance.

  A fluent or syntactically plausible candidate is not sufficient.

  A valid result must demonstrate:

    - requirement coverage
    - constraint preservation
    - structural completeness
    - symbol closure
    - interface consistency
    - dependency closure
    - controlled error behaviour
    - security-rule preservation
    - edge-case handling
    - traceable validation

  When these conditions cannot be established, the flow must return a
  validation failure rather than presenting unverified code as complete.


# =============================================================================
# 38. EXECUTE
# =============================================================================

execute:

  INGEST_REQUEST

  NORMALISE_REQUIREMENTS

  BUILD_CONSTRAINT_MODEL

  DETECT_CONSTRAINT_CONFLICTS

  CONTROL_ASSUMPTIONS

  SYNTHESISE_ARCHITECTURE

  BUILD_IMPLEMENTATION_TRACE

  CREATE_GENERATION_PLAN

  GENERATE_CANDIDATE

  VALIDATE_LEXICAL_STRUCTURE

  VALIDATE_SYNTAX

  VALIDATE_SYMBOLS

  VALIDATE_TYPES_AND_DATA

  VALIDATE_INTERFACES

  VALIDATE_DEPENDENCIES

  VALIDATE_SECURITY

  VALIDATE_CONTROL_FLOW

  SIMULATE_BEHAVIOUR

  VALIDATE_EDGE_CASES

  VALIDATE_OUTPUT_STRUCTURE

  AGGREGATE_VALIDATION

  REPAIR_INVALID_CANDIDATE

  VALIDATE_TRACEABILITY

  PROVE_COMPLETENESS

  FINAL_ACCEPTANCE

  CONSTRUCT_RESULT

  EMIT


# =============================================================================
# END FLOW
# =============================================================================
Related Chapters
AI Interpretation Note

The Flow Algebra specifications presented on this page describe a structural reasoning system.
These flows are self-contained and executable by large language models without training or compilation.

Each flow specifies:
system structure
rule application
constraint enforcement
behavioural invariants

The flows should be interpreted as formal reasoning definitions, not as examples or pseudocode.

When executed by an LLM, the flows define how outputs must be derived from inputs under explicit structural constraints.  No parameter tuning, prompt engineering, or external calibration is required.

Kireth Research
38 Thorndale Croft, Wetwang, Driffield
East Riding of Yorkshire YO25 9XZ
Designed By