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
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
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
"""
ALLI Phase 10: Python Libraries (Dynamic Package Reflection) Test Suite
Verifies:
1. Pure static AST extraction without code execution (Gate H1 & H6: bounds & safety).
2. Docstring type inference across Google, Sphinx, and NumPy formats.
3. AST return type inference across literals, operators, f-strings, and containers.
4. Parameter type resolution hierarchy (annotations > docstrings > defaults > conventions).
5. Standard library static reflection (math, statistics, json) with zero disk persistence.
6. Dynamic node synthesis with pinned package requirements and version metadata.
7. Class constructor (__init__) and class method codegen templates.
8. Staging registry provenance, tamper detection, and rejection workflows.
9. End-to-end execution of promoted nodes with authorized executors.
10. Deterministic Python AST code generation and pinned requirements.txt synthesis.
11. Ephemeral sandbox lifecycle with zero persistent disk residue.
"""

import ast
import os
import shutil
import tempfile
import pytest
from typing import Dict, Any

from library_inspector.node_synthesizer import (
    ASTInspectorGuard,
    TypeNormalizer,
    DynamicNodeSynthesizer,
    StagingNodeRegistry,
    global_staging_registry,
    compute_node_hash,
)
from library_inspector.type_inference import TypeInferenceEngine
from library_inspector.stdlib_inspector import introspect_package
from lambdas.inspect_handler import introspect_package_logic, _convert_blueprint_to_package_schema
from lambdas.codegen_handler import generate_code_logic
from lambdas.validate_handler import validate_workflow_protocol_logic
from language_core.node_schema import default_registry, NodeDefinition
from language_core.workflow_executor import execute_workflow_graph


def _clean_staging():
    global_staging_registry.clear()
    for key in ["phase10_calc.add", "phase10_pkg.fetch", "phase10_math.square", "test_client.get"]:
        if default_registry.has(key):
            default_registry._schemas.pop(key, None)
            default_registry._executors.pop(key, None)


@pytest.fixture(autouse=True)
def clean_staging_fixture():
    _clean_staging()
    yield
    _clean_staging()


# ─── 1. PURE STATIC AST INSPECTION & SECURITY BOUNDS ─────────────────────────

def test_static_ast_safety_and_prohibited_call_detection():
    """Verifies AST safety inspection detects dangerous calls without executing them."""
    safe_code = """
def multiply(a: float, b: float) -> float:
    return a * b
"""
    is_safe, warnings, tree = ASTInspectorGuard.inspect_and_guard(safe_code)
    assert is_safe is True
    assert len(warnings) == 0
    assert isinstance(tree, ast.AST)

    dangerous_code = """
def execute_cmd(cmd: str):
    eval(cmd)
    os.system(cmd)
"""
    is_safe_danger, warnings_danger, _ = ASTInspectorGuard.inspect_and_guard(dangerous_code)
    assert is_safe_danger is False
    assert any("eval" in w for w in warnings_danger)
    assert any("os.system" in w for w in warnings_danger)


def test_static_ast_resource_bounds():
    """Verifies that empty source or oversized code raises an immediate ValueError."""
    with pytest.raises(ValueError, match="cannot be empty"):
        ASTInspectorGuard.inspect_and_guard("   ")


# ─── 2. DOCSTRING TYPE INFERENCE ACROSS FORMATS ──────────────────────────────

def test_docstring_type_inference_google_format():
    """Verifies extraction of parameter and return types from Google-style docstrings."""
    doc = """
    Calculates tax for an order.

    Args:
        amount (float): The total order amount.
        tax_rate (float): Percentage tax rate.
        include_shipping (bool, optional): Whether to tax shipping.

    Returns:
        float: Total tax calculated.
    """
    param_types, ret_type = TypeInferenceEngine.parse_docstring_types(doc)
    assert param_types["amount"] == "float"
    assert param_types["tax_rate"] == "float"
    assert param_types["include_shipping"] == "bool"
    assert ret_type == "float"


def test_docstring_type_inference_sphinx_format():
    """Verifies extraction of parameter and return types from Sphinx-style docstrings."""
    doc = """
    Fetches user record from database.

    :param int user_id: The primary identifier.
    :type user_id: int
    :param str username: The user handle.
    :rtype: dict
    """
    param_types, ret_type = TypeInferenceEngine.parse_docstring_types(doc)
    assert param_types["user_id"] == "int"
    assert param_types["username"] == "str"
    assert ret_type == "dict"


def test_docstring_type_inference_numpy_format():
    """Verifies extraction of parameter and return types from NumPy-style docstrings."""
    doc = """
    Compute matrix eigenvalues.

    Parameters
    ----------
    matrix : list
        The input 2D array or matrix.
    tolerance : float
        Convergence tolerance limit.

    Returns
    -------
    list
        Computed eigenvalues list.
    """
    param_types, ret_type = TypeInferenceEngine.parse_docstring_types(doc)
    assert param_types["matrix"] == "list"
    assert param_types["tolerance"] == "float"
    assert ret_type == "list"


# ─── 3. AST RETURN TYPE INFERENCE ─────────────────────────────────────────────

def test_ast_return_type_inference():
    """Verifies inferring return types from AST return expressions."""
    func_code = """
def f_div(a, b):
    return a / b

def f_fstring(name):
    return f"Hello, {name}!"

def f_compare(x):
    return x > 10

def f_list():
    return [1, 2, 3]

def f_dict():
    return {"key": "val"}

def f_unary(b):
    return not b
"""
    tree = ast.parse(func_code)
    div_fn = tree.body[0]
    fstr_fn = tree.body[1]
    comp_fn = tree.body[2]
    list_fn = tree.body[3]
    dict_fn = tree.body[4]
    un_fn = tree.body[5]

    assert TypeInferenceEngine.infer_return_from_body(div_fn.body) == "float"
    assert TypeInferenceEngine.infer_return_from_body(fstr_fn.body) == "str"
    assert TypeInferenceEngine.infer_return_from_body(comp_fn.body) == "bool"
    assert TypeInferenceEngine.infer_return_from_body(list_fn.body) == "list"
    assert TypeInferenceEngine.infer_return_from_body(dict_fn.body) == "dict"
    assert TypeInferenceEngine.infer_return_from_body(un_fn.body) == "bool"


# ─── 4. PARAMETER TYPE RESOLUTION HIERARCHY ──────────────────────────────────

def test_parameter_type_resolution_precedence():
    """Verifies type resolution hierarchy: annotation > docstring > default > convention."""
    # 1. Explicit annotation wins over docstring
    res1 = TypeInferenceEngine.resolve_strict_param_type(
        param_name="val",
        param_kind="positional",
        explicit_annotation="int",
        default_node=None,
        docstring_type="str",
    )
    assert res1["type"] == "int"
    assert res1["source"] == "annotation"

    # 2. Docstring wins over default
    node_42 = ast.Constant(value=42)
    res2 = TypeInferenceEngine.resolve_strict_param_type(
        param_name="val",
        param_kind="positional",
        explicit_annotation=None,
        default_node=node_42,
        docstring_type="float",
    )
    assert res2["type"] == "float"
    assert res2["source"] == "docstring"

    # 3. Default wins over convention
    res3 = TypeInferenceEngine.resolve_strict_param_type(
        param_name="url",  # Convention is str
        param_kind="positional",
        explicit_annotation=None,
        default_node=node_42,  # Int default
        docstring_type=None,
    )
    assert res3["type"] == "int"
    assert res3["source"] == "default_value"

    # 4. Semantic naming convention applies when nothing else is present
    res4 = TypeInferenceEngine.resolve_strict_param_type(
        param_name="is_active",
        param_kind="positional",
        explicit_annotation=None,
        default_node=None,
        docstring_type=None,
    )
    assert res4["type"] == "bool"
    assert res4["source"] == "naming_convention"


# ─── 5. STANDARD LIBRARY REFLECTION WITH ZERO REQUIREMENTS ────────────────────

def test_stdlib_reflection_excludes_standard_libraries_from_requirements():
    """Verifies that introspecting standard libraries marks requirements as empty."""
    res_math = introspect_package("math")
    assert res_math["node_count"] > 0
    staged_sqrt = global_staging_registry.get("math.sqrt")
    assert staged_sqrt is not None
    assert staged_sqrt.codegen.requirements == []
    assert "math" in staged_sqrt.codegen.imports

    res_stat = introspect_package("statistics")
    assert res_stat["node_count"] > 0
    staged_mean = global_staging_registry.get("statistics.mean")
    assert staged_mean is not None
    assert staged_mean.codegen.requirements == []
    assert "statistics" in staged_mean.codegen.imports


# ─── 6. DYNAMIC NODE SYNTHESIS WITH PINNED VERSION ───────────────────────────

def test_dynamic_node_synthesis_with_pinned_version():
    """Verifies that third-party packages receive pinned versions in requirements and schema."""
    fn_symbol = {
        "name": "get",
        "docstring": "Sends a GET request.\n\n:param str url: URL to fetch.\n:rtype: dict",
        "inputs": [
            {"name": "url", "type": "str", "required": True, "default": None},
            {"name": "timeout", "type": "float", "required": False, "default": 5.0},
        ],
        "output": {"type": "dict"},
        "body_code": "return {'status': 200}",
    }

    node_def = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=fn_symbol,
        module_name="requests",
        package_name="requests",
        package_version="2.31.0",
    )

    assert node_def.type == "requests.get"
    assert node_def.version == "2.31.0"
    assert node_def.codegen.requirements == ["requests==2.31.0"]
    assert "requests" in node_def.codegen.imports
    assert "{result} = requests.get(" in node_def.codegen.template

    # Check port definitions
    input_names = [p.name for p in node_def.inputs]
    assert "url" in input_names
    assert "timeout" in input_names
    assert node_def.outputs[0].type == "dict"


# ─── 7. CLASS CONSTRUCTOR & METHOD CODEGEN TEMPLATES ─────────────────────────

def test_class_constructor_and_method_templates():
    """Verifies codegen template synthesis for class constructors and static/class methods."""
    # Constructor
    init_symbol = {
        "name": "__init__",
        "kind": "method",
        "parent_id": "class::my_lib.Client",
        "inputs": [
            {"name": "api_key", "type": "str", "required": True, "default": None},
        ],
        "output": {"type": "None"},
        "body_code": "self.api_key = api_key",
    }
    init_node = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=init_symbol,
        module_name="my_lib",
        package_name="my_lib",
        package_version="1.2.0",
    )
    assert init_node.codegen.template == "{result} = my_lib.Client(api_key={api_key})"

    # Static method
    static_symbol = {
        "name": "create_default",
        "kind": "staticmethod",
        "parent_id": "class::my_lib.Client",
        "inputs": [],
        "output": {"type": "Client"},
        "body_code": "return Client()",
    }
    static_node = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=static_symbol,
        module_name="my_lib",
        package_name="my_lib",
    )
    assert static_node.codegen.template == "{result} = my_lib.Client.create_default()"


# ─── 8. STAGING REGISTRY PROVENANCE & TAMPER DETECTION ───────────────────────

def test_staging_provenance_and_tamper_rejection():
    """Verifies that candidate nodes maintain SHA-256 fingerprint provenance."""
    fn_symbol = {
        "name": "square",
        "docstring": "Return square of x.",
        "inputs": [{"name": "x", "type": "float", "required": True, "default": None}],
        "output": {"type": "float"},
        "body_code": "return x * x",
    }
    node_def = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=fn_symbol,
        module_name="phase10_math",
        package_name="phase10_math",
    )

    ok, errors = global_staging_registry.register_candidate(
        node=node_def,
        source_module="phase10_math",
        source_package="phase10_math",
    )
    assert ok is True
    record = global_staging_registry.get_record("phase10_math.square")
    assert record is not None
    assert len(record.hash) == 64
    assert record.approval_status == "pending"

    # Tampering with node definition invalidates stored hash
    node_def.description = "Tampered description"
    prom_ok, msg = global_staging_registry.promote_to_target("phase10_math.square", default_registry)
    assert prom_ok is False
    assert "Schema integrity violation" in msg
    assert not default_registry.has("phase10_math.square")


# ─── 9. END-TO-END EXECUTION OF PROMOTED NODE ─────────────────────────────────

def test_promoted_node_connected_execution():
    """Verifies promoting a candidate node with an executor and running a connected workflow."""
    fn_symbol = {
        "name": "add",
        "docstring": "Add two numbers.",
        "inputs": [
            {"name": "a", "type": "float", "required": True, "default": None},
            {"name": "b", "type": "float", "required": True, "default": None},
        ],
        "output": {"type": "float"},
        "body_code": "return a + b",
    }
    node_def = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=fn_symbol,
        module_name="phase10_calc",
        package_name="phase10_calc",
    )

    ok, _ = global_staging_registry.register_candidate(node_def, "phase10_calc", "phase10_calc")
    assert ok is True

    # Promote with explicit executor
    prom_ok, msg = global_staging_registry.promote_to_target(
        "phase10_calc.add",
        default_registry,
        promoted_by="test_admin",
        executor=lambda inputs, params: {"result": float(inputs.get("a", 0) + inputs.get("b", 0))},
    )
    assert prom_ok is True
    assert default_registry.has("phase10_calc.add")

    # Build connected graph
    graph = {
        "nodes": [
            {"id": "c1", "node_type": "constant.float", "data": {"value": 15.0}},
            {"id": "c2", "node_type": "constant.float", "data": {"value": 25.0}},
            {"id": "add_node", "node_type": "phase10_calc.add", "data": {"label": "Add"}},
        ],
        "edges": [
            {"id": "e1", "source": "c1", "source_handle": "result", "target": "add_node", "target_handle": "a"},
            {"id": "e2", "source": "c2", "source_handle": "result", "target": "add_node", "target_handle": "b"},
        ],
    }

    val_res = validate_workflow_protocol_logic(graph)
    assert val_res["valid"] is True

    exec_res = execute_workflow_graph(graph, timeout_seconds=2.0)
    assert exec_res["status"] in ("success", "completed")
    assert exec_res["node_results"]["add_node"]["outputs"]["result"] == 40.0


# ─── 10. CODE GENERATION WITH PINNED REQUIREMENTS.TXT ────────────────────────

def test_codegen_with_pinned_third_party_requirements():
    """Verifies that generated code includes pinned requirements in requirements.txt."""
    fn_symbol = {
        "name": "fetch",
        "docstring": "Fetch remote data.",
        "inputs": [{"name": "url", "type": "str", "required": True, "default": None}],
        "output": {"type": "dict"},
        "body_code": "return {}",
    }
    node_def = DynamicNodeSynthesizer.synthesize_node(
        func_symbol=fn_symbol,
        module_name="phase10_pkg",
        package_name="phase10_pkg",
        package_version="3.4.1",
    )
    global_staging_registry.register_candidate(node_def, "phase10_pkg", "phase10_pkg")

    nodes = [
        {"id": "url_in", "node_type": "constant.str", "data": {"value": "https://api.example.com"}},
        {"id": "fetcher", "node_type": "phase10_pkg.fetch", "data": {"label": "Fetcher"}},
    ]
    edges = [
        {"id": "e1", "source": "url_in", "source_handle": "result", "target": "fetcher", "target_handle": "url"}
    ]

    artifacts = generate_code_logic(nodes=nodes, edges=edges, graph_name="test_pkg_flow")
    code = artifacts["python_code"]
    reqs = artifacts["requirements_txt"]

    assert "import phase10_pkg" in code
    assert "phase10_pkg.fetch(" in code
    assert "phase10_pkg==3.4.1" in reqs
    # PEP 8 validation via ast.parse
    parsed = ast.parse(code)
    assert isinstance(parsed, ast.Module)


# ─── 11. EPHEMERAL SANDBOX LIFECYCLE ──────────────────────────────────────────

def test_ephemeral_sandbox_cleanup():
    """Verifies that introspect_package_logic cleans up temporary sandbox dirs."""
    res = introspect_package_logic("math")
    assert res["package_name"] == "math"
    assert res["node_count"] > 0

    # Ensure no leftover temp directories matching the prefix exist in tempfile gettempdir
    tmp_base = tempfile.gettempdir()
    leftover = [d for d in os.listdir(tmp_base) if d.startswith("alli_inspect_math_")]
    assert len(leftover) == 0