File size: 28,947 Bytes
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b9746
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b9746
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
 
 
 
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
 
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
 
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92bcda3
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
 
 
 
ae3f25f
 
 
 
 
 
 
 
474a36a
 
 
 
ae3f25f
 
 
 
 
 
 
92bcda3
 
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474a36a
ae3f25f
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
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
from unittest.mock import Mock, patch

import pytest

from orka.nodes.memory_writer_node import MemoryWriterNode


class TestMemoryWriterNodeInitialization:
    """Test MemoryWriterNode initialization scenarios."""

    @patch("orka.nodes.memory_writer_node.create_memory_logger")
    def test_initialization_default_params(self, mock_create_logger):
        """Test initialization with default parameters."""
        mock_logger = Mock()
        mock_create_logger.return_value = mock_logger

        node = MemoryWriterNode(node_id="test_writer", prompt="test", queue=[])

        assert node.node_id == "test_writer"
        assert node.type == "memorywriternode"
        assert node.memory_logger == mock_logger
        assert node.namespace == "default"
        assert node.session_id == "default"
        assert node.decay_config == {}

        mock_create_logger.assert_called_once_with(
            backend="redisstack",
            enable_hnsw=True,
            vector_params={"M": 16, "ef_construction": 200},
            decay_config={},
            memory_preset=None,
            operation="write",  # Added for operation-aware presets
        )

    @patch("orka.nodes.memory_writer_node.create_memory_logger")
    def test_initialization_with_custom_params(self, mock_create_logger):
        """Test initialization with custom parameters."""
        mock_logger = Mock()
        mock_create_logger.return_value = mock_logger

        custom_vector_params = {"M": 32, "ef_construction": 400}
        custom_decay_config = {"short_term_hours": 2.0, "long_term_hours": 48.0}

        node = MemoryWriterNode(
            node_id="custom_writer",
            prompt="test",
            queue=[],
            namespace="custom_ns",
            session_id="custom_session",
            use_hnsw=False,
            vector_params=custom_vector_params,
            decay_config=custom_decay_config,
        )

        assert node.namespace == "custom_ns"
        assert node.session_id == "custom_session"
        assert node.decay_config == custom_decay_config

        mock_create_logger.assert_called_once_with(
            backend="redisstack",
            enable_hnsw=False,
            vector_params=custom_vector_params,
            decay_config=custom_decay_config,
            memory_preset=None,
            operation="write",  # Added for operation-aware presets
        )

    def test_initialization_with_custom_memory_logger(self):
        """Test initialization with pre-existing memory logger."""
        custom_logger = Mock()

        node = MemoryWriterNode(
            node_id="test_writer",
            prompt="test",
            queue=[],
            memory_logger=custom_logger,
            namespace="test_ns",
        )

        assert node.memory_logger == custom_logger
        assert node.namespace == "test_ns"


class TestMemoryWriterNodeRun:
    """Test the main run method of MemoryWriterNode."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.mock_memory_logger = Mock()
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=self.mock_memory_logger,
                namespace="test_ns",
                session_id="test_session",
            )

    @pytest.mark.asyncio
    async def test_run_successful_with_structured_memory(self):
        """Test successful run with structured memory object."""
        self.mock_memory_logger.log_memory.return_value = "memory_key_123"

        context = {
            "input": "Original input",
            "previous_outputs": {
                "false_validation_guardian": {
                    "result": {
                        "memory_object": {
                            "number": "7",
                            "result": "true",
                            "condition": "greater than 5",
                            "analysis_type": "numerical_comparison",
                            "confidence": 0.95,
                            "validation_status": "validated",
                        },
                    },
                },
            },
            "namespace": "custom_ns",
            "session_id": "custom_session",
            "metadata": {"source": "test", "category": "stored"},
        }

        result = await self.node.run(context)

        assert result["status"] == "success"
        assert result["result"]["memory_key"] == "memory_key_123"
        assert result["result"]["session"] == "custom_session"
        assert result["result"]["namespace"] == "custom_ns"
        assert result["result"]["backend"] == "redisstack"
        assert result["result"]["vector_enabled"] == True
        assert "content_length" in result["result"]

        # Verify log_memory was called with correct parameters
        self.mock_memory_logger.log_memory.assert_called_once()
        call_args = self.mock_memory_logger.log_memory.call_args
        assert call_args[1]["node_id"] == "test_writer"
        assert call_args[1]["trace_id"] == "custom_session"
        assert call_args[1]["metadata"]["namespace"] == "custom_ns"
        assert call_args[1]["metadata"]["category"] == "stored"

    @pytest.mark.asyncio
    async def test_run_with_true_validation_guardian(self):
        """Test run with true validation guardian output."""
        self.mock_memory_logger.log_memory.return_value = "memory_key_456"

        context = {
            "input": "Test input",
            "previous_outputs": {
                "true_validation_guardian": {
                    "result": {
                        "memory_object": {
                            "number": "3",
                            "result": "false",
                            "condition": "greater than 5",
                            "analysis_type": "numerical_comparison",
                            "confidence": 0.85,
                        },
                    },
                },
            },
        }

        result = await self.node.run(context)

        assert result["status"] == "success"
        assert result["result"]["memory_key"] == "memory_key_456"

    @pytest.mark.asyncio
    async def test_run_fallback_to_input(self):
        """Test run falls back to input when no structured memory found."""
        self.mock_memory_logger.log_memory.return_value = "memory_key_789"

        context = {
            "input": "Direct input content",
            "previous_outputs": {},
        }

        result = await self.node.run(context)

        assert result["status"] == "success"
        assert result["result"]["memory_key"] == "memory_key_789"

        # Verify the content was the direct input
        call_args = self.mock_memory_logger.log_memory.call_args
        assert "Direct input content" in call_args[1]["content"]

    @pytest.mark.asyncio
    async def test_run_no_memory_content(self):
        """Test run with no extractable memory content."""
        context = {
            "previous_outputs": {},
            # No input field
        }

        result = await self.node.run(context)

        # MemoryWriterNode returns a dict with status="error" which becomes the result
        assert result["status"] == "success"  # OrkaResponse wraps it as success
        assert result["result"]["status"] == "error"  # The actual node's status
        assert result["result"]["error"] == "No memory content to store"

    @pytest.mark.asyncio
    async def test_run_memory_logger_exception(self):
        """Test run when memory logger throws exception."""
        self.mock_memory_logger.log_memory.side_effect = Exception("Redis connection failed")

        context = {
            "input": "Test content",
        }

        result = await self.node.run(context)

        # MemoryWriterNode catches exceptions and returns error dict
        assert result["status"] == "success"  # OrkaResponse wraps it as success
        assert result["result"]["status"] == "error"  # The actual node's status
        assert "Redis connection failed" in result["result"]["error"]

    @pytest.mark.asyncio
    async def test_run_uses_default_namespace_and_session(self):
        """Test run uses default namespace and session when not provided."""
        self.mock_memory_logger.log_memory.return_value = "memory_key_default"

        context = {
            "input": "Test content",
        }

        result = await self.node.run(context)

        assert result["status"] == "success"
        assert result["result"]["session"] == "test_session"  # From node initialization
        assert result["result"]["namespace"] == "test_ns"  # From node initialization


class TestMemoryWriterNodeContentExtraction:
    """Test memory content extraction methods."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=Mock(),
            )

    def test_extract_memory_content_false_guardian(self):
        """Test extracting content from false validation guardian."""
        context = {
            "input": "Original input",
            "previous_outputs": {
                "false_validation_guardian": {
                    "result": {
                        "memory_object": {
                            "number": "7",
                            "result": "true",
                            "condition": "greater than 5",
                            "analysis_type": "numerical_comparison",
                            "confidence": 0.95,
                        },
                    },
                },
            },
        }

        content = self.node._extract_memory_content(context)

        assert "Number: 7" in content
        assert "Greater than 5: true" in content
        assert "Condition: greater than 5" in content
        assert "Analysis: numerical_comparison" in content
        assert "Confidence: 0.95" in content

    def test_extract_memory_content_true_guardian(self):
        """Test extracting content from true validation guardian."""
        context = {
            "input": "Original input",
            "previous_outputs": {
                "true_validation_guardian": {
                    "result": {
                        "memory_object": {
                            "number": "3",
                            "result": "false",
                            "analysis_type": "comparison",
                        },
                    },
                },
            },
        }

        content = self.node._extract_memory_content(context)

        assert "Number: 3" in content
        assert "Greater than 5: false" in content
        assert "Analysis: comparison" in content

    def test_extract_memory_content_no_guardian_output(self):
        """Test extracting content when no guardian output exists."""
        context = {
            "input": "Direct input content",
            "previous_outputs": {},
        }

        content = self.node._extract_memory_content(context)

        assert content == "Direct input content"

    def test_extract_memory_content_invalid_guardian_structure(self):
        """Test extracting content with invalid guardian structure."""
        context = {
            "input": "Fallback input",
            "previous_outputs": {
                "false_validation_guardian": {
                    # Missing result field
                    "invalid": "structure",
                },
            },
        }

        content = self.node._extract_memory_content(context)

        assert content == "Fallback input"

    def test_extract_memory_content_guardian_not_dict(self):
        """Test extracting content when guardian output is not a dict."""
        context = {
            "input": "Fallback input",
            "previous_outputs": {
                "false_validation_guardian": "not a dict",
            },
        }

        content = self.node._extract_memory_content(context)

        assert content == "Fallback input"

    def test_extract_memory_content_exception_handling(self):
        """Test exception handling during content extraction."""
        with patch.object(
            self.node,
            "_memory_object_to_text",
            side_effect=Exception("Conversion error"),
        ):
            context = {
                "input": "Fallback input",
                "previous_outputs": {
                    "false_validation_guardian": {
                        "result": {
                            "memory_object": {"test": "data"},
                        },
                    },
                },
            }

            content = self.node._extract_memory_content(context)

            # The actual implementation returns "Memory content extraction failed"
            assert content == "Memory content extraction failed"


class TestMemoryWriterNodeObjectToText:
    """Test memory object to text conversion."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=Mock(),
            )

    def test_memory_object_to_text_complete_object(self):
        """Test converting complete memory object to text."""
        memory_obj = {
            "number": "7",
            "result": "true",
            "condition": "greater than 5",
            "analysis_type": "numerical_comparison",
            "confidence": 0.95,
            "validation_status": "validated",
        }

        text = self.node._memory_object_to_text(memory_obj, "original input")

        assert "Number: 7" in text
        assert "Greater than 5: true" in text
        assert "Condition: greater than 5" in text
        assert "Analysis: numerical_comparison" in text
        assert "Confidence: 0.95" in text
        assert "Validated: validated" in text
        assert "JSON:" in text

    def test_memory_object_to_text_partial_object(self):
        """Test converting partial memory object to text."""
        memory_obj = {
            "number": "3",
            "result": "false",
        }

        text = self.node._memory_object_to_text(memory_obj, "original input")

        assert "Number: 3" in text
        assert "Greater than 5: false" in text
        assert "Condition: " in text  # Empty condition
        assert "Analysis: " in text  # Empty analysis
        assert "Confidence: 1.0" in text  # Default confidence

    def test_memory_object_to_text_missing_number(self):
        """Test converting memory object without number field."""
        memory_obj = {
            "result": "true",
            "analysis_type": "test",
        }

        text = self.node._memory_object_to_text(memory_obj, "original input")

        assert "Number: original input" in text  # Uses original input as fallback
        assert "Greater than 5: true" in text

    def test_memory_object_to_text_exception_handling(self):
        """Test exception handling during object to text conversion."""
        # Create a problematic memory object that causes an exception
        memory_obj = Mock()
        memory_obj.get.side_effect = Exception("Mock exception")

        with patch("logging.Logger.warning") as mock_warning:
            text = self.node._memory_object_to_text(memory_obj, "original")

            # Should return string representation of the object
            assert str(memory_obj) in text
            mock_warning.assert_called_once()


class TestMemoryWriterNodeImportanceScore:
    """Test importance score calculation."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=Mock(),
            )

    def test_calculate_importance_score_base_score(self):
        """Test base importance score calculation."""
        score = self.node._calculate_importance_score("Short content", {})

        assert score == 0.5  # Base score

    def test_calculate_importance_score_long_content(self):
        """Test importance score with long content."""
        long_content = "x" * 600  # Over 500 characters
        score = self.node._calculate_importance_score(long_content, {})

        assert score == 0.7  # Base + 0.2 for long content

    def test_calculate_importance_score_medium_content(self):
        """Test importance score with medium content."""
        medium_content = "x" * 200  # Over 100 characters
        score = self.node._calculate_importance_score(medium_content, {})

        assert score == 0.6  # Base + 0.1 for medium content

    def test_calculate_importance_score_stored_category(self):
        """Test importance score with stored category."""
        metadata = {"category": "stored"}
        score = self.node._calculate_importance_score("Content", metadata)

        assert score == 0.8  # Base + 0.3 for stored category

    def test_calculate_importance_score_with_query(self):
        """Test importance score with query metadata."""
        metadata = {"query": "test query"}
        score = self.node._calculate_importance_score("Content", metadata)

        assert score == 0.6  # Base + 0.1 for query

    def test_calculate_importance_score_maximum(self):
        """Test importance score calculation with all bonuses."""
        long_content = "x" * 600
        metadata = {"category": "stored", "query": "test query"}
        score = self.node._calculate_importance_score(long_content, metadata)

        assert score == 1.0  # Clamped to maximum 1.0

    def test_calculate_importance_score_clamping(self):
        """Test that importance score is properly clamped."""
        # Test that score doesn't go below 0.0
        negative_bonus_content = ""
        score = self.node._calculate_importance_score(negative_bonus_content, {})
        assert score >= 0.0

        # Test that score doesn't go above 1.0 (already tested in maximum test)
        assert score <= 1.0


class TestMemoryWriterNodeMemoryTypeClassification:
    """Test memory type classification."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=Mock(),
            )

    def test_classify_memory_type_short_term_default(self):
        """Test default short-term classification."""
        memory_type = self.node._classify_memory_type({}, 0.5)

        assert memory_type == "short_term"

    def test_classify_memory_type_stored_high_importance(self):
        """Test long-term classification for stored high-importance memory."""
        metadata = {"category": "stored"}
        memory_type = self.node._classify_memory_type(metadata, 0.8)

        assert memory_type == "long_term"

    def test_classify_memory_type_stored_low_importance(self):
        """Test short-term classification for stored low-importance memory."""
        metadata = {"category": "stored"}
        memory_type = self.node._classify_memory_type(metadata, 0.6)

        assert memory_type == "short_term"

    def test_classify_memory_type_default_long_term_config(self):
        """Test long-term classification based on config."""
        self.node.decay_config = {"default_long_term": True}
        memory_type = self.node._classify_memory_type({}, 0.3)

        assert memory_type == "long_term"

    def test_classify_memory_type_stored_exactly_threshold(self):
        """Test classification at exactly the importance threshold."""
        metadata = {"category": "stored"}
        memory_type = self.node._classify_memory_type(metadata, 0.7)

        assert memory_type == "long_term"


class TestMemoryWriterNodeExpiryHours:
    """Test expiry hours calculation."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=Mock(),
            )

    def test_get_expiry_hours_short_term_default(self):
        """Test expiry hours for short-term memory with defaults."""
        hours = self.node._get_expiry_hours("short_term", 0.5)

        # Base 1.0 hours * (1.0 + 0.5 importance) = 1.5 hours
        assert hours == 1.5

    def test_get_expiry_hours_long_term_default(self):
        """Test expiry hours for long-term memory with defaults."""
        hours = self.node._get_expiry_hours("long_term", 0.8)

        # Base 24.0 hours * (1.0 + 0.8 importance) = 43.2 hours
        assert hours == 43.2

    def test_get_expiry_hours_with_agent_config(self):
        """Test expiry hours with agent-level configuration."""
        self.node.decay_config = {
            "short_term_hours": 2.0,
            "long_term_hours": 48.0,
        }

        short_hours = self.node._get_expiry_hours("short_term", 0.5)
        long_hours = self.node._get_expiry_hours("long_term", 0.3)

        assert short_hours == 3.0  # 2.0 * (1.0 + 0.5)
        assert abs(long_hours - 62.4) < 0.01  # 48.0 * (1.0 + 0.3) with floating point tolerance

    def test_get_expiry_hours_with_global_config_fallback(self):
        """Test expiry hours with global configuration fallback."""
        self.node.decay_config = {
            "default_short_term_hours": 0.5,
            "default_long_term_hours": 12.0,
        }

        short_hours = self.node._get_expiry_hours("short_term", 0.2)
        long_hours = self.node._get_expiry_hours("long_term", 0.6)

        assert short_hours == 0.6  # 0.5 * (1.0 + 0.2)
        assert abs(long_hours - 19.2) < 0.01  # 12.0 * (1.0 + 0.6) with floating point tolerance

    def test_get_expiry_hours_agent_priority_over_global(self):
        """Test that agent-level config takes priority over global config."""
        self.node.decay_config = {
            "short_term_hours": 3.0,  # Agent-level
            "default_short_term_hours": 1.0,  # Global fallback
            "default_long_term_hours": 36.0,  # Only global available
        }

        short_hours = self.node._get_expiry_hours("short_term", 0.0)
        long_hours = self.node._get_expiry_hours("long_term", 0.0)

        assert short_hours == 3.0  # Uses agent-level config
        assert long_hours == 36.0  # Uses global fallback

    def test_get_expiry_hours_importance_multiplier(self):
        """Test importance score multiplier effect."""
        # Test with zero importance (multiplier = 1.0)
        hours_zero = self.node._get_expiry_hours("short_term", 0.0)
        assert hours_zero == 1.0

        # Test with high importance (multiplier = 2.0)
        hours_high = self.node._get_expiry_hours("short_term", 1.0)
        assert hours_high == 2.0


class TestMemoryWriterNodeEdgeCases:
    """Test edge cases and error scenarios."""

    def setup_method(self):
        """Set up test fixtures."""
        with patch("orka.nodes.memory_writer_node.create_memory_logger"):
            self.mock_memory_logger = Mock()
            self.node = MemoryWriterNode(
                node_id="test_writer",
                prompt="test",
                queue=[],
                memory_logger=self.mock_memory_logger,
            )

    @pytest.mark.asyncio
    async def test_run_with_empty_context(self):
        """Test run with completely empty context."""
        result = await self.node.run({})

        # MemoryWriterNode returns error dict, wrapped in OrkaResponse
        assert result["status"] == "success"  # OrkaResponse wraps it as success
        assert result["result"]["status"] == "error"  # The actual node's status
        assert result["result"]["error"] == "No memory content to store"

    @pytest.mark.asyncio
    async def test_run_with_empty_input(self):
        """Test run with empty input string."""
        context = {"input": ""}

        result = await self.node.run(context)

        # MemoryWriterNode returns error dict, wrapped in OrkaResponse
        assert result["status"] == "success"  # OrkaResponse wraps it as success
        assert result["result"]["status"] == "error"  # The actual node's status
        assert result["result"]["error"] == "No memory content to store"

    def test_extract_memory_content_with_none_input(self):
        """Test content extraction with None input."""
        context = {"input": None, "previous_outputs": {}}

        content = self.node._extract_memory_content(context)

        # The actual implementation returns str(None) which is "None"
        assert content == "None"

    def test_memory_object_to_text_with_none_values(self):
        """Test object to text conversion with None values."""
        memory_obj = {
            "number": None,
            "result": None,
            "condition": None,
            "analysis_type": None,
            "confidence": None,
        }

        text = self.node._memory_object_to_text(memory_obj, "fallback")

        # Should handle None values gracefully
        assert "Number: None" in text  # Implementation shows None values as-is
        assert "Greater than 5: None" in text
        assert "Condition: None" in text
        assert "Analysis: None" in text
        assert "Confidence: None" in text  # None confidence is shown as None

    def test_calculate_importance_score_with_none_metadata(self):
        """Test importance score calculation with None metadata values."""
        metadata = {"category": None, "query": None}

        score = self.node._calculate_importance_score("content", metadata)

        assert score == 0.5  # Only base score, no bonuses

    def test_classify_memory_type_with_missing_metadata_keys(self):
        """Test memory type classification with missing metadata keys."""
        # Test when category key doesn't exist
        memory_type = self.node._classify_memory_type({}, 0.8)
        assert memory_type == "short_term"

        # Test when category is None
        memory_type = self.node._classify_memory_type({"category": None}, 0.8)
        assert memory_type == "short_term"

    def test_get_expiry_hours_with_missing_config_keys(self):
        """Test expiry hours calculation with missing config keys."""
        # Empty decay config should use defaults
        self.node.decay_config = {}

        short_hours = self.node._get_expiry_hours("short_term", 0.0)
        long_hours = self.node._get_expiry_hours("long_term", 0.0)

        assert short_hours == 1.0  # Default short-term
        assert long_hours == 24.0  # Default long-term

    @pytest.mark.asyncio
    async def test_run_integration_with_all_methods(self):
        """Test complete run integration calling all internal methods."""
        self.mock_memory_logger.log_memory.return_value = "integrated_memory_key"

        # Create context that exercises all code paths
        context = {
            "input": "x" * 600,  # Long content for importance bonus
            "previous_outputs": {
                "false_validation_guardian": {
                    "result": {
                        "memory_object": {
                            "number": "10",
                            "result": "true",
                            "condition": "greater than 5",
                            "analysis_type": "numerical_comparison",
                            "confidence": 0.95,
                            "validation_status": "validated",
                        },
                    },
                },
            },
            "namespace": "integration_test",
            "session_id": "integration_session",
            "metadata": {"category": "stored", "query": "test query"},
        }

        result = await self.node.run(context)

        assert result["status"] == "success"
        assert result["result"]["memory_key"] == "integrated_memory_key"

        # Verify memory logger was called with processed data
        call_args = self.mock_memory_logger.log_memory.call_args
        assert (
            abs(call_args[1]["importance_score"] - 1.0) < 0.01
        )  # Max score with floating point tolerance
        assert call_args[1]["memory_type"] == "long_term"  # High importance stored
        assert call_args[1]["expiry_hours"] == 48.0  # 24 * (1.0 + 1.0)