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
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
"""
AbstractReasoner — Vitalis FSI

Reasons about RELATIONSHIPS between concepts.
Not pattern matching. Not retrieval.
Genuine relational reasoning:
  - Analogy: A is to B as C is to ?
  - Composition: concept_A + concept_B = novel_concept
  - Inversion: what is the opposite of this concept?
  - Transitivity: if A relates to B and B relates to C, what does A relate to C?

Built entirely on HDC operations. No external models.
"""
import numpy as np
import os
import json
import time
from vitalis_ide.math_core.kernel import VitalisKernel
from src.cognition.abstraction import AbstractionEngine
from src.hippocampus import Hippocampus


class AbstractReasoner:
    ANALOGY_THRESHOLD  = 0.25
    COMPOSITION_DECAY  = 0.85
    INVERSION_SHIFT    = 5000

    def __init__(self):
        self.kernel      = VitalisKernel()
        self.abstraction = AbstractionEngine()
        self.hippocampus = Hippocampus()
        self.path        = os.path.expanduser(
            "~/.vitalis_workspace/reasoning_log.json"
        )
        self._log = self._load_log()

    def _load_log(self) -> list:
        if os.path.exists(self.path):
            with open(self.path) as f:
                return json.load(f)
        return []

    def _save_log(self):
        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        with open(self.path, "w") as f:
            json.dump(self._log[-500:], f, indent=2)

    # ------------------------------------------------------------------
    # Core HDC reasoning operations
    # ------------------------------------------------------------------
    def _bind(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
        """Bipolar binding: element-wise multiply."""
        return (a.astype(np.int32) * b.astype(np.int32)).astype(np.int8)

    def _bundle(self, vecs: list) -> np.ndarray:
        """Bipolar bundling: sum then sign."""
        stacked = np.stack(vecs).astype(np.int32).sum(axis=0)
        result = np.sign(stacked).astype(np.int8)
        result[result == 0] = 1
        return result

    def _invert(self, vec: np.ndarray) -> np.ndarray:
        """
        Semantic inversion: cyclic shift by half the vector length.
        Produces a vector maximally dissimilar to the input.
        """
        return np.roll(vec, self.INVERSION_SHIFT)

    # ------------------------------------------------------------------
    # Analogy: A is to B as C is to ?
    # ------------------------------------------------------------------
    def analogy(
        self,
        concept_a: str,
        concept_b: str,
        concept_c: str,
    ) -> dict:
        """
        Solves: A:B :: C:?
        HDC method: ? = bind(bind(A, B), C)
        Searches abstraction space and hippocampus for closest match.
        """
        vec_a = self.kernel.vectorize_tokens(concept_a.split(), positional=False)
        vec_b = self.kernel.vectorize_tokens(concept_b.split(), positional=False)
        vec_c = self.kernel.vectorize_tokens(concept_c.split(), positional=False)

        # ? = B * A^-1 * C  (HDC analogy formula)
        a_inv = self._bind(vec_a, vec_a)  # A bound with itself = identity-like
        relation = self._bind(vec_a, vec_b)  # encode A→B relationship
        answer_vec = self._bind(relation, vec_c)  # apply relation to C

        # Search for closest concept
        candidates = self.abstraction.query_abstractions(answer_vec, top_k=3)
        hipp_results = self.hippocampus.similarity_search(answer_vec, top_k=3)

        best_match = None
        best_score = -1.0

        for score, name, _ in candidates:
            if score > best_score:
                best_score = score
                best_match = name

        result = {
            "type":       "analogy",
            "query":      f"{concept_a}:{concept_b}::{concept_c}:?",
            "answer_vec": answer_vec,
            "best_match": best_match,
            "confidence": round(float(best_score), 4),
            "candidates": [(name, round(float(s), 4)) for s, name, _ in candidates],
            "timestamp":  time.time(),
        }

        self._log.append({k: v for k, v in result.items() if k != "answer_vec"})
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Composition: merge two concepts into a novel one
    # ------------------------------------------------------------------
    def compose(self, concept_a: str, concept_b: str) -> dict:
        """
        Compose two concepts into a novel concept vector.
        The result occupies a position in the space between both inputs.
        Weighted by the COMPOSITION_DECAY to prevent drift.
        """
        vec_a = self.kernel.vectorize_tokens(concept_a.split(), positional=False)
        vec_b = self.kernel.vectorize_tokens(concept_b.split(), positional=False)

        # Bundle with decay weighting
        composed = self._bundle([vec_a, vec_b])

        # Apply composition decay — prevents the result from being
        # too close to either parent
        noise_mask = np.random.choice(
            [-1, 1],
            size=self.kernel.dim,
            p=[1 - self.COMPOSITION_DECAY, self.COMPOSITION_DECAY]
        ).astype(np.int8)
        composed = self._bind(composed, noise_mask)

        # Search for nearest existing concept
        candidates = self.abstraction.query_abstractions(composed, top_k=3)

        result = {
            "type":        "composition",
            "inputs":      [concept_a, concept_b],
            "novel_vec":   composed,
            "nearest":     [(name, round(float(s), 4)) for s, name, _ in candidates],
            "novelty":     round(1.0 - (candidates[0][0] if candidates else 0.0), 4),
            "timestamp":   time.time(),
        }

        self._log.append({k: v for k, v in result.items() if k != "novel_vec"})
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Inversion: what is the conceptual opposite?
    # ------------------------------------------------------------------
    def invert(self, concept: str) -> dict:
        """
        Find the conceptual opposite of a concept.
        Uses cyclic shift inversion then searches concept space.
        """
        vec = self.kernel.vectorize_tokens(concept.split(), positional=False)
        inverted = self._invert(vec)

        candidates = self.abstraction.query_abstractions(inverted, top_k=3)
        hipp_results = self.hippocampus.similarity_search(inverted, top_k=3)

        result = {
            "type":       "inversion",
            "concept":    concept,
            "opposites":  [(name, round(float(s), 4)) for s, name, _ in candidates],
            "confidence": round(float(candidates[0][0]) if candidates else 0.0, 4),
            "timestamp":  time.time(),
        }

        self._log.append(result)
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Transitivity: if A→B and B→C, what is A→C?
    # ------------------------------------------------------------------
    def transitive_chain(self, concepts: list) -> dict:
        """
        Chain reasoning: given [A, B, C, D...],
        derive the relationship between A and the last element.
        Each step binds the accumulated relationship with the next concept.
        """
        if len(concepts) < 2:
            return {"error": "Need at least 2 concepts"}

        vecs = [
            self.kernel.vectorize_tokens(c.split(), positional=False)
            for c in concepts
        ]

        # Accumulate relationship via sequential binding
        accumulated = vecs[0].copy()
        for i in range(1, len(vecs)):
            accumulated = self._bind(accumulated, vecs[i])
            # Apply position-aware permutation at each step
            accumulated = np.roll(accumulated, i * 100)

        candidates = self.abstraction.query_abstractions(accumulated, top_k=3)

        result = {
            "type":       "transitivity",
            "chain":      concepts,
            "conclusion": [(name, round(float(s), 4)) for s, name, _ in candidates],
            "confidence": round(float(candidates[0][0]) if candidates else 0.0, 4),
            "timestamp":  time.time(),
        }

        self._log.append(result)
        self._save_log()
        return result

    def report(self) -> dict:
        if not self._log:
            return {"status": "No reasoning performed yet"}
        type_counts = {}
        for entry in self._log:
            t = entry.get("type", "unknown")
            type_counts[t] = type_counts.get(t, 0) + 1
        return {
            "total_reasoning_ops": len(self._log),
            "by_type":             type_counts,
            "recent":              self._log[-3:],
        }
"""
AbstractReasoner — Vitalis FSI

Reasons about RELATIONSHIPS between concepts.
Not pattern matching. Not retrieval.
Genuine relational reasoning:
  - Analogy: A is to B as C is to ?
  - Composition: concept_A + concept_B = novel_concept
  - Inversion: what is the opposite of this concept?
  - Transitivity: if A relates to B and B relates to C, what does A relate to C?

Built entirely on HDC operations. No external models.
"""
import numpy as np
import os
import json
import time
from vitalis_ide.math_core.kernel import VitalisKernel
from src.cognition.abstraction import AbstractionEngine
from src.hippocampus import Hippocampus


class AbstractReasoner:
    ANALOGY_THRESHOLD  = 0.25
    COMPOSITION_DECAY  = 0.85
    INVERSION_SHIFT    = 5000

    def __init__(self):
        self.kernel      = VitalisKernel()
        self.abstraction = AbstractionEngine()
        self.hippocampus = Hippocampus()
        self.path        = os.path.expanduser(
            "~/.vitalis_workspace/reasoning_log.json"
        )
        self._log = self._load_log()

    def _load_log(self) -> list:
        if os.path.exists(self.path):
            with open(self.path) as f:
                return json.load(f)
        return []

    def _save_log(self):
        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        with open(self.path, "w") as f:
            json.dump(self._log[-500:], f, indent=2)

    # ------------------------------------------------------------------
    # Core HDC reasoning operations
    # ------------------------------------------------------------------
    def _bind(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
        """Bipolar binding: element-wise multiply."""
        return (a.astype(np.int32) * b.astype(np.int32)).astype(np.int8)

    def _bundle(self, vecs: list) -> np.ndarray:
        """Bipolar bundling: sum then sign."""
        stacked = np.stack(vecs).astype(np.int32).sum(axis=0)
        result = np.sign(stacked).astype(np.int8)
        result[result == 0] = 1
        return result

    def _invert(self, vec: np.ndarray) -> np.ndarray:
        """
        Semantic inversion: cyclic shift by half the vector length.
        Produces a vector maximally dissimilar to the input.
        """
        return np.roll(vec, self.INVERSION_SHIFT)

    # ------------------------------------------------------------------
    # Analogy: A is to B as C is to ?
    # ------------------------------------------------------------------
    def analogy(
        self,
        concept_a: str,
        concept_b: str,
        concept_c: str,
    ) -> dict:
        """
        Solves: A:B :: C:?
        HDC method: ? = bind(bind(A, B), C)
        Searches abstraction space and hippocampus for closest match.
        """
        vec_a = self.kernel.vectorize_tokens(concept_a.split(), positional=False)
        vec_b = self.kernel.vectorize_tokens(concept_b.split(), positional=False)
        vec_c = self.kernel.vectorize_tokens(concept_c.split(), positional=False)

        # ? = B * A^-1 * C  (HDC analogy formula)
        a_inv = self._bind(vec_a, vec_a)  # A bound with itself = identity-like
        relation = self._bind(vec_a, vec_b)  # encode A→B relationship
        answer_vec = self._bind(relation, vec_c)  # apply relation to C

        # Search for closest concept
        candidates = self.abstraction.query_abstractions(answer_vec, top_k=3)
        hipp_results = self.hippocampus.similarity_search(answer_vec, top_k=3)

        best_match = None
        best_score = -1.0

        for score, name, _ in candidates:
            if score > best_score:
                best_score = score
                best_match = name

        result = {
            "type":       "analogy",
            "query":      f"{concept_a}:{concept_b}::{concept_c}:?",
            "answer_vec": answer_vec,
            "best_match": best_match,
            "confidence": round(float(best_score), 4),
            "candidates": [(name, round(float(s), 4)) for s, name, _ in candidates],
            "timestamp":  time.time(),
        }

        self._log.append({k: v for k, v in result.items() if k != "answer_vec"})
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Composition: merge two concepts into a novel one
    # ------------------------------------------------------------------
    def compose(self, concept_a: str, concept_b: str) -> dict:
        """
        Compose two concepts into a novel concept vector.
        The result occupies a position in the space between both inputs.
        Weighted by the COMPOSITION_DECAY to prevent drift.
        """
        vec_a = self.kernel.vectorize_tokens(concept_a.split(), positional=False)
        vec_b = self.kernel.vectorize_tokens(concept_b.split(), positional=False)

        # Bundle with decay weighting
        composed = self._bundle([vec_a, vec_b])

        # Apply composition decay — prevents the result from being
        # too close to either parent
        noise_mask = np.random.choice(
            [-1, 1],
            size=self.kernel.dim,
            p=[1 - self.COMPOSITION_DECAY, self.COMPOSITION_DECAY]
        ).astype(np.int8)
        composed = self._bind(composed, noise_mask)

        # Search for nearest existing concept
        candidates = self.abstraction.query_abstractions(composed, top_k=3)

        result = {
            "type":        "composition",
            "inputs":      [concept_a, concept_b],
            "novel_vec":   composed,
            "nearest":     [(name, round(float(s), 4)) for s, name, _ in candidates],
            "novelty":     round(1.0 - (candidates[0][0] if candidates else 0.0), 4),
            "timestamp":   time.time(),
        }

        self._log.append({k: v for k, v in result.items() if k != "novel_vec"})
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Inversion: what is the conceptual opposite?
    # ------------------------------------------------------------------
    def invert(self, concept: str) -> dict:
        """
        Find the conceptual opposite of a concept.
        Uses cyclic shift inversion then searches concept space.
        """
        vec = self.kernel.vectorize_tokens(concept.split(), positional=False)
        inverted = self._invert(vec)

        candidates = self.abstraction.query_abstractions(inverted, top_k=3)
        hipp_results = self.hippocampus.similarity_search(inverted, top_k=3)

        result = {
            "type":       "inversion",
            "concept":    concept,
            "opposites":  [(name, round(float(s), 4)) for s, name, _ in candidates],
            "confidence": round(float(candidates[0][0]) if candidates else 0.0, 4),
            "timestamp":  time.time(),
        }

        self._log.append(result)
        self._save_log()
        return result

    # ------------------------------------------------------------------
    # Transitivity: if A→B and B→C, what is A→C?
    # ------------------------------------------------------------------
    def transitive_chain(self, concepts: list) -> dict:
        """
        Chain reasoning: given [A, B, C, D...],
        derive the relationship between A and the last element.
        Each step binds the accumulated relationship with the next concept.
        """
        if len(concepts) < 2:
            return {"error": "Need at least 2 concepts"}

        vecs = [
            self.kernel.vectorize_tokens(c.split(), positional=False)
            for c in concepts
        ]

        # Accumulate relationship via sequential binding
        accumulated = vecs[0].copy()
        for i in range(1, len(vecs)):
            accumulated = self._bind(accumulated, vecs[i])
            # Apply position-aware permutation at each step
            accumulated = np.roll(accumulated, i * 100)

        candidates = self.abstraction.query_abstractions(accumulated, top_k=3)

        result = {
            "type":       "transitivity",
            "chain":      concepts,
            "conclusion": [(name, round(float(s), 4)) for s, name, _ in candidates],
            "confidence": round(float(candidates[0][0]) if candidates else 0.0, 4),
            "timestamp":  time.time(),
        }

        self._log.append(result)
        self._save_log()
        return result

    def report(self) -> dict:
        if not self._log:
            return {"status": "No reasoning performed yet"}
        type_counts = {}
        for entry in self._log:
            t = entry.get("type", "unknown")
            type_counts[t] = type_counts.get(t, 0) + 1
        return {
            "total_reasoning_ops": len(self._log),
            "by_type":             type_counts,
            "recent":              self._log[-3:],
        }