Commit Graph
193 Commits
Author SHA1 Message Date
KaifAhmad1andClaude Sonnet 4.6 f677b638e2 fix(explorer): resolve test crash, import error handling, cycle safety, and missing utils package
- test_vocabulary.py: remove sys.modules['spacy'] = MagicMock() — caused
  ValueError in pytest collection when transformers called
  importlib.util.find_spec('spacy') on a MagicMock without __spec__;
  add setup_function() reset_mock() to prevent cross-test state pollution;
  expand from 3 to 16 tests covering narrower edges, topConceptOf,
  hasTopConcept, flat scheme, empty scheme, missing param, cycle safety,
  .rdf/.owl format path, invalid file 422, and metadata envelope fallback
- vocabulary.py: /import returned HTTP 200 with {"status":"error"} on parse
  failure — now raises HTTPException(422) so clients get a proper error code;
  replace bare except with ValueError-specific catch, move add_nodes/add_edges
  outside the try block
- vocabulary.py: get_hierarchy tree assembly had no cycle detection — cyclic
  broader/narrower edges in real-world SKOS data would cause infinite recursion
  during Pydantic serialization; replaced inline loop with recursive
  _attach_children() that carries a visited set
- semantica/explorer/utils/: branch was based on main and missing rdf_parser.py
  and __init__.py (introduced in #425); copied from ebd2be3 so vocabulary.py
  import resolves correctly
- tests/explorer/test_rdf_parser.py: carried forward from #425 (32 tests)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 19:02:24 +05:30
ZohaibHassan16 2537976e8f feat(explorer): implement SKOS vocabulary routes and integration tests 2026-03-30 17:01:11 +05:00
Mohd KaifandClaude Sonnet 4.6 e30ef6cb76 Kg Context Explainability Output Fixes (#419)
* feat(#401): temporal provenance, OWL-Time export, stable snapshot schema

- ProvenanceTracker: auto-attach recorded_at (UTC) to every new record;
  add query_recorded_between(), revision_history(), export_audit_log()
- RDFExporter.export_to_rdf: add include_temporal + time_axis params;
  emit OWL-Time triples (time:Interval, time:Instant, inXSDDateTimeStamp)
  for relationships with valid_from/valid_until; TemporalBound.OPEN
  represented via semantica:openEndedInterval instead of time:hasEnd
- TemporalVersionManager.create_snapshot: stamp format_version "1.0"
  on every snapshot; add validate_snapshot() and migrate_snapshot()
- New: semantica/kg/schemas/temporal_snapshot_v1.json (JSON Schema draft-2020)
- Tests: 28 new tests covering all acceptance criteria (451 passing, 0 failed)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(#401): add changelog entry for temporal provenance & export

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(#402): Temporal GraphRAG Integration — TemporalGraphRetriever & TemporalQueryRewriter

- Add TemporalGraphRetriever to context_retriever.py (no new file per project convention)
  - Drop-in wrapper for ContextRetriever; filters related_entities/related_relationships
    via reconstruct_at_time(); at_time=None is a true passthrough
  - Returns new RetrievedContext objects (no in-place mutation)
  - Graceful ImportError if temporal modules unavailable

- Add at_time + header_template to ContextRetriever._generate_reasoned_response()
  and query_with_reasoning()
  - Temporal header prepended to LLM context block only when at_time is set
  - Naive datetimes normalised to UTC before formatting
  - Header built with str.replace (not .format) to prevent format-string injection

- Add TemporalQueryRewriter + TemporalQueryResult to semantica/kg/
  - Regex-only (default) and LLM-assisted extraction modes
  - Resolves temporal phrases via TemporalNormalizer (deterministic, zero LLM)
  - Word-boundary guards on intent keywords; year fallback for noun-phrase dates
  - Never calls reconstruct_at_time — extraction only

- Export TemporalGraphRetriever from semantica.context
- Export TemporalQueryRewriter, TemporalQueryResult from semantica.kg

- Add 99 tests across two new test files
  - tests/context/test_temporal_retriever.py (56 tests)
  - tests/kg/test_temporal_query_rewriter.py (43 tests)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(#402): add changelog entry for Temporal GraphRAG Integration

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: rewrite and polish documentation site (#413)

- Rewrote index.md to match README (tagline, badges, Problem/Solution text)
- Improved getting-started, concepts, quickstart, installation, faq, use-cases, contributing, glossary, learning-more, examples, modules, architecture, cookbook, deep-dive pages: tighter prose, fixed headings/bullets, removed inconsistencies and duplicate sections
- Removed overuse of emojis from headings in integration pages (docling, snowflake)
- Fixed change_management reference page: closed unclosed JSON code block that broke the right TOC, demoted noisy sub-headings to bold text
- CSS layout: widened content area (max-width 1440px grid, left sidebar 11rem, right TOC narrowed to 11rem for broader content), tightened TOC spacing and font size, fixed word-wrap/overflow on TOC links
- Added mkdocs_local.yml for local serving without mkdocs-jupyter plugin

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(#318): SHACL Shape Generation & Validation (Phase 1 + Phase 2)

Phase 1 — Generation:
- Add SHACLGenerator, SHACLGraph, NodeShape, PropertyShape to ontology_generator.py
- 6-stage pipeline: class index → node shapes → property shapes → inheritance propagation → quality tier → serialization
- Three output formats: Turtle, JSON-LD, N-Triples
- Three quality tiers: basic / standard (default) / strict (sh:closed)
- 3-level+ inheritance propagation, cycle-safe, no duplicate shapes
- No-domain properties attach to all node shapes
- OntologyEngine.to_shacl(), export_shacl() added to engine.py
- RDFExporter.export_shacl() added to rdf_exporter.py

Phase 2 — Runtime Validation:
- Add SHACLViolation, SHACLValidationReport, _run_pyshacl to ontology_validator.py
- OntologyEngine.validate_graph() with shacl= or ontology= arguments
- explain_violations(): rule-based plain-English explanations for all 7 SHACL constraint types
- summary(), to_dict() on SHACLValidationReport for pipeline and LLM consumers
- pyshacl/rdflib are optional deferred imports (pip install semantica[shacl])

Security & reliability fixes:
- Replace path-heuristic (len/newline) with os.path.exists() in validate_graph
- Add shacl_format parameter to validate_graph and _run_pyshacl; thread format through correctly
- Fix validate_output format alias map in to_shacl (json-ld, n-triples aliases)
- Deep-copy PropertyShape in _propagate_inheritance (dataclasses.replace) — no shared mutable refs
- Deterministic Turtle prefix output via sorted(graph.prefixes.items())
- Use full rdf:type URI in sh:ignoredProperties — no prefix dependency

Tests & docs:
- Add TestSHACLGeneration (16 tests) to test_ontology_comprehensive.py
- Add TestSHACLHierarchicalAndValidation (18 tests) to test_ontology_advanced.py
- 34 new tests, 0 failures, 0 regressions across 1111-test suite
- Update README: Unreleased section, Features, Modules table, Ontology code block, Installation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(#318): add CHANGELOG entry for SHACL Shape Generation & Validation

Covers Phase 1 (generation), Phase 2 (runtime validation), all 5
security/reliability fixes, test results, and README updates.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(#319): SKOS Vocabulary Module — namespace helpers, store helpers, OntologyEngine APIs, tests, docs

Extends the existing ontology and triplet-store stack with first-class
SKOS support without adding any new top-level packages.

### semantica/ontology/namespace_manager.py
- `get_skos_uri(local_name)` — build full skos:core# URI from local name
- `build_concept_scheme_uri(name)` — slug a human name into a stable
  ConceptScheme URI anchored at the configured base URI

### semantica/triplet_store/triplet_store.py
- `add_skos_concept(concept_uri, scheme_uri, pref_label, ...)` — asserts
  ConceptScheme + Concept triples, prefLabel, altLabel, broader, narrower,
  related, definition, notation via existing `add_triplets()` API
- `get_skos_concepts(scheme_uri=None)` — SPARQL SELECT via `execute_query()`,
  collapses multi-valued bindings into concept dicts

### semantica/ontology/engine.py
- `list_vocabularies()` — list all skos:ConceptScheme instances
- `list_concepts(scheme_uri)` — list concepts in a scheme with alt labels
- `search_concepts(query, scheme_uri=None)` — case-insensitive substring
  search over prefLabel + altLabel; sanitises user input against SPARQL injection

### tests
- `TestSKOSOntologyEngine` (14 tests) in test_ontology_comprehensive.py
- `TestSKOSTripletStore` (6 tests) in test_triplet_store.py
- All 1162 existing + new tests pass, 0 failures

### docs/reference/ontology.md
- New "SKOS Vocabulary Management" section: data-model table, import
  examples (add_skos_concept + rdflib bulk), list/search API, NamespaceManager helpers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(#319): add CHANGELOG entry for SKOS Vocabulary Module

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add comprehensive test suites for Temporal Semantics (#395) and all Unreleased changelog features

- tests/test_395_temporal_semantics_comprehensive.py — 113 tests covering
  #396–#399: bitemporal model, temporal consistency validation, query
  time-range aggregation, ContextGraph.state_at(), causal chain trace_at_time()
- tests/test_unreleased_changelog_comprehensive.py — 92 tests covering all
  unreleased changelog gaps: AgentContext checkpoints (#399), audit trail /
  named tags / rollback protection (#394), snapshot schema compatibility (#393),
  ContextGraph pagination & min_weight & thread safety (#385), SKOS helpers
  (#319), SHACL quality tiers & export (#318), OllamaProvider base_url (#408),
  DatalogReasoner multi-hop & graph load (#371)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: Context Explainability Output Fixes — regression tests and centrality fix

- Fixed CentralityCalculator._build_adjacency() to handle ContextGraph edges
  (ContextEdge dataclass objects with source_id/target_id) so degree centrality
  and related algorithms return correct results instead of empty dicts
- Added 23 regression tests in tests/context/test_context_explainability_regression.py
  covering readable decision text preservation, enriched causal/path outputs,
  PolicyEngine consistent metadata across Cypher and fallback branches,
  EntityLinker similarity payloads, and KG consumer compatibility
- Updated CHANGELOG.md [Unreleased] to reflect the bug fix and test additions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 13:03:52 +05:30
Mohd KaifandClaude Sonnet 4.6 cf7a78fa10 test: add comprehensive test suites for Temporal Semantics (#395) and all Unreleased changelog features (#417)
- tests/test_395_temporal_semantics_comprehensive.py — 113 tests covering
  #396–#399: bitemporal model, temporal consistency validation, query
  time-range aggregation, ContextGraph.state_at(), causal chain trace_at_time()
- tests/test_unreleased_changelog_comprehensive.py — 92 tests covering all
  unreleased changelog gaps: AgentContext checkpoints (#399), audit trail /
  named tags / rollback protection (#394), snapshot schema compatibility (#393),
  ContextGraph pagination & min_weight & thread safety (#385), SKOS helpers
  (#319), SHACL quality tiers & export (#318), OllamaProvider base_url (#408),
  DatalogReasoner multi-hop & graph load (#371)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 18:48:04 +05:30
KaifAhmad1andClaude Sonnet 4.6 71d037f581 feat(#319): SKOS Vocabulary Module — namespace helpers, store helpers, OntologyEngine APIs, tests, docs
Extends the existing ontology and triplet-store stack with first-class
SKOS support without adding any new top-level packages.

### semantica/ontology/namespace_manager.py
- `get_skos_uri(local_name)` — build full skos:core# URI from local name
- `build_concept_scheme_uri(name)` — slug a human name into a stable
  ConceptScheme URI anchored at the configured base URI

### semantica/triplet_store/triplet_store.py
- `add_skos_concept(concept_uri, scheme_uri, pref_label, ...)` — asserts
  ConceptScheme + Concept triples, prefLabel, altLabel, broader, narrower,
  related, definition, notation via existing `add_triplets()` API
- `get_skos_concepts(scheme_uri=None)` — SPARQL SELECT via `execute_query()`,
  collapses multi-valued bindings into concept dicts

### semantica/ontology/engine.py
- `list_vocabularies()` — list all skos:ConceptScheme instances
- `list_concepts(scheme_uri)` — list concepts in a scheme with alt labels
- `search_concepts(query, scheme_uri=None)` — case-insensitive substring
  search over prefLabel + altLabel; sanitises user input against SPARQL injection

### tests
- `TestSKOSOntologyEngine` (14 tests) in test_ontology_comprehensive.py
- `TestSKOSTripletStore` (6 tests) in test_triplet_store.py
- All 1162 existing + new tests pass, 0 failures

### docs/reference/ontology.md
- New "SKOS Vocabulary Management" section: data-model table, import
  examples (add_skos_concept + rdflib bulk), list/search API, NamespaceManager helpers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 13:59:23 +05:30
KaifAhmad1andClaude Sonnet 4.6 dae368532c feat(#318): SHACL Shape Generation & Validation (Phase 1 + Phase 2)
Phase 1 — Generation:
- Add SHACLGenerator, SHACLGraph, NodeShape, PropertyShape to ontology_generator.py
- 6-stage pipeline: class index → node shapes → property shapes → inheritance propagation → quality tier → serialization
- Three output formats: Turtle, JSON-LD, N-Triples
- Three quality tiers: basic / standard (default) / strict (sh:closed)
- 3-level+ inheritance propagation, cycle-safe, no duplicate shapes
- No-domain properties attach to all node shapes
- OntologyEngine.to_shacl(), export_shacl() added to engine.py
- RDFExporter.export_shacl() added to rdf_exporter.py

Phase 2 — Runtime Validation:
- Add SHACLViolation, SHACLValidationReport, _run_pyshacl to ontology_validator.py
- OntologyEngine.validate_graph() with shacl= or ontology= arguments
- explain_violations(): rule-based plain-English explanations for all 7 SHACL constraint types
- summary(), to_dict() on SHACLValidationReport for pipeline and LLM consumers
- pyshacl/rdflib are optional deferred imports (pip install semantica[shacl])

Security & reliability fixes:
- Replace path-heuristic (len/newline) with os.path.exists() in validate_graph
- Add shacl_format parameter to validate_graph and _run_pyshacl; thread format through correctly
- Fix validate_output format alias map in to_shacl (json-ld, n-triples aliases)
- Deep-copy PropertyShape in _propagate_inheritance (dataclasses.replace) — no shared mutable refs
- Deterministic Turtle prefix output via sorted(graph.prefixes.items())
- Use full rdf:type URI in sh:ignoredProperties — no prefix dependency

Tests & docs:
- Add TestSHACLGeneration (16 tests) to test_ontology_comprehensive.py
- Add TestSHACLHierarchicalAndValidation (18 tests) to test_ontology_advanced.py
- 34 new tests, 0 failures, 0 regressions across 1111-test suite
- Update README: Unreleased section, Features, Modules table, Ontology code block, Installation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 17:42:46 +05:30
KaifAhmad1andClaude Sonnet 4.6 0f0800f109 feat(#402): Temporal GraphRAG Integration — TemporalGraphRetriever & TemporalQueryRewriter
- Add TemporalGraphRetriever to context_retriever.py (no new file per project convention)
  - Drop-in wrapper for ContextRetriever; filters related_entities/related_relationships
    via reconstruct_at_time(); at_time=None is a true passthrough
  - Returns new RetrievedContext objects (no in-place mutation)
  - Graceful ImportError if temporal modules unavailable

- Add at_time + header_template to ContextRetriever._generate_reasoned_response()
  and query_with_reasoning()
  - Temporal header prepended to LLM context block only when at_time is set
  - Naive datetimes normalised to UTC before formatting
  - Header built with str.replace (not .format) to prevent format-string injection

- Add TemporalQueryRewriter + TemporalQueryResult to semantica/kg/
  - Regex-only (default) and LLM-assisted extraction modes
  - Resolves temporal phrases via TemporalNormalizer (deterministic, zero LLM)
  - Word-boundary guards on intent keywords; year fallback for noun-phrase dates
  - Never calls reconstruct_at_time — extraction only

- Export TemporalGraphRetriever from semantica.context
- Export TemporalQueryRewriter, TemporalQueryResult from semantica.kg

- Add 99 tests across two new test files
  - tests/context/test_temporal_retriever.py (56 tests)
  - tests/kg/test_temporal_query_rewriter.py (43 tests)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 14:20:38 +05:30
Mohd KaifandClaude Sonnet 4.6 9e68266563 feat(#401): Temporal Provenance & Export (#411)
* feat(#401): temporal provenance, OWL-Time export, stable snapshot schema

- ProvenanceTracker: auto-attach recorded_at (UTC) to every new record;
  add query_recorded_between(), revision_history(), export_audit_log()
- RDFExporter.export_to_rdf: add include_temporal + time_axis params;
  emit OWL-Time triples (time:Interval, time:Instant, inXSDDateTimeStamp)
  for relationships with valid_from/valid_until; TemporalBound.OPEN
  represented via semantica:openEndedInterval instead of time:hasEnd
- TemporalVersionManager.create_snapshot: stamp format_version "1.0"
  on every snapshot; add validate_snapshot() and migrate_snapshot()
- New: semantica/kg/schemas/temporal_snapshot_v1.json (JSON Schema draft-2020)
- Tests: 28 new tests covering all acceptance criteria (451 passing, 0 failed)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(#401): add changelog entry for temporal provenance & export

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 12:38:24 +05:30
KaifAhmad1andClaude Sonnet 4.6 b9af181625 feat(semantic-extract): temporal metadata extraction from text (#400)
- Add `extract_temporal_bounds: bool = False` to `extract_relations_llm()`.
  When True the LLM prompt is extended with a calibrated confidence scale
  and four few-shot examples; each returned Relation gains valid_from,
  valid_until, temporal_confidence, and temporal_source_text in metadata.
  Low confidence (<0.5) with non-null dates logs a WARNING. Default False
  preserves 100% backward compatibility.

- Add `RelationWithTemporalOut` / `RelationsWithTemporalResponse` Pydantic
  schemas so the four temporal fields are captured from structured LLM
  output (separate from RelationOut which uses extra="ignore").

- New `semantica/kg/temporal_normalizer.py` — `TemporalNormalizer` class
  (zero LLM calls, pure regex + dateutil arithmetic):
    * normalize(value) → (start, end) UTC datetimes or None
    * Resolution order: ISO 8601 → partial dates (year/month/Q) →
      ambiguity detection → domain phrase map → relative phrases
    * normalize_phrase(phrase) → metadata dict or None
    * Default phrase map covers 13 domains: General, Policy, Healthcare,
      Drug Discovery, Cybersecurity, Supply Chain, Finance, Energy
    * TemporalAmbiguityWarning for DD/MM/YYYY-style ambiguous inputs
    * Custom phrase_map at construction (merged over defaults)

- Add `TemporalAmbiguityWarning(UserWarning)` to exceptions.py.
- Export `TemporalNormalizer` from `semantica/kg/__init__.py`.
- Propagate `extract_temporal_bounds` through `_extract_relations_chunked`
  and add flag to cache key to prevent cross-mode cache pollution.

- 53 new tests in tests/semantic_extract/test_temporal_extraction.py;
  zero real LLM calls, suite runs in ~3.5s. 873 existing tests unaffected.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 21:42:57 +05:30
KaifAhmad1andClaude Sonnet 4.6 19665b9db2 fix(semantic-extract): pass base_url as host when initialising OllamaProvider client
Closes #408

Previously `_init_client` assigned the raw `ollama` module to
`self.client`, so the `base_url` parameter was silently ignored and
every request hit the default localhost:11434. Now an `ollama.Client`
instance is created with `host=self.base_url`, so remote Ollama servers
are reachable.

Three regression tests added to prevent recurrence:
- default base_url is forwarded as host
- custom base_url (e.g. http://192.168.1.3:11434) is forwarded as host
- self.client is never the raw module

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 19:36:22 +05:30
KaifAhmad1andClaude Sonnet 4.6 01ba7d113b feat(context): add temporal awareness to ContextGraph and AgentContext
- Add valid_from/valid_until fields to Decision dataclass and record_decision()
- Add include_superseded and as_of filters to find_precedents_by_scenario()
- Add _decision_matches_temporal_filters() and _normalize_temporal_input() helpers
- Add ContextGraph.state_at(timestamp) for point-in-time graph snapshots
- Stamp recorded_at on causal relationship edges
- Add CausalChainAnalyzer.trace_at_time() for transaction-time causal chain tracing
- Add AgentContext.checkpoint(), diff_checkpoints(), flush_checkpoint() for named context snapshots
- 93 tests passing (33 context_graph, 36 causal_analyzer, 24 agent_context)

Closes #399

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 12:18:25 +05:30
KaifAhmad1 a3a0848577 Fix semantic extract spaCy fallback review issues 2026-03-23 23:31:01 +05:30
Mohd Kaif eeda5f5b80 Merge branch 'main' into semantic-extract 2026-03-23 23:16:19 +05:30
KaifAhmad1 62b03d4fa5 Harden spaCy NER fallback in semantic extract 2026-03-23 23:12:48 +05:30
KaifAhmad1 8de7cc1b6d Fix temporal reasoning review issues 2026-03-23 19:43:12 +05:30
KaifAhmad1 c6dc9d87aa Add deterministic temporal reasoning engine 2026-03-23 19:12:18 +05:30
KaifAhmad1 b2b823a5c3 Fix temporal query review follow-ups 2026-03-23 17:13:02 +05:30
KaifAhmad1 3c863e860e Implement temporal point-in-time correctness (#397) 2026-03-23 16:39:49 +05:30
KaifAhmad1 8be16f782e Fix temporal revision integrity follow-ups 2026-03-23 16:12:29 +05:30
KaifAhmad1 9faa5661f8 Core temporal data model overhaul (#396) 2026-03-23 15:53:13 +05:30
OpenAI CodexandKaifAhmad1 e13ea740cd merge: resolve main conflicts for PR #394
Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-03-22 20:12:01 +05:30
OpenAI CodexandKaifAhmad1 e2b79ada9a fix(change-management): preserve snapshot compatibility and audit integrity
Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-03-22 19:45:58 +05:30
Mohd Kaif 4147f0ca3b Merge branch 'main' into fix/snapshot-key-mismatch 2026-03-22 17:42:32 +05:30
OpenAI Codex adac6f7a7b fix(change-management): preserve snapshot schema compatibility 2026-03-22 17:26:07 +05:30
Mohd Kaif ca8a916373 Merge branch 'main' into fix/issue-379-decision-query-fallback 2026-03-21 17:10:52 +05:30
KaifAhmad1andClaude Sonnet 4.6 13eed9cf6d fix(context): fix isinstance regression, hoist BFS find_edges, expand tests
- Replace isinstance(graph_store, ContextGraph) with type() is ContextGraph
  in all 12 guards across decision_query.py and decision_recorder.py.
  Fixes 2 regressions where Mock(spec=ContextGraph) triggered fallback
  paths, causing TypeError on iteration of mock return values.

- Hoist find_edges() calls out of the BFS while-loop in trace_decision_path
  so edges are fetched once per call instead of once per visited node,
  eliminating O(nodes * total_edges) repeated full-graph fetches.

- Expand test_decision_query_fallback.py: keep the original integration
  test and add 13 targeted unit tests covering all 7 DecisionQuery and
  4 DecisionRecorder ContextGraph fallback methods, including tz-aware/naive
  datetime mixing and Mock guard validation.

Result: 353 passed, 0 failed (was 338 passed, 2 failed on this branch)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 17:08:44 +05:30
KaifAhmad1andClaude Sonnet 4.6 ac047f917a fix(explorer): resolve merge-artifact syntax errors and clean up all route files
app.py:
- Fix unclosed '(' in generic_error_handler (two implementations were merged,
  leaving the return JSONResponse( call with no closing paren)
- Remove duplicate 'from fastapi import FastAPI, Request' import
- Remove unused 'import traceback'
- Remove duplicate static file mount (was mounted twice: once conditionally,
  once unconditionally creating the dir — FastAPI raises on duplicate mounts)

decisions.py:
- Remove stub 'return ComplianceResponse(compliant=True)' with unclosed '('
  that was left in front of the real edge-scan implementation

temporal.py:
- Remove blocking get_nodes/get_edges calls (without asyncio.to_thread) that
  were left as dead code above the correct async versions
- Fix empty 'except Exception:' clause before 'except ImportError:' that
  caused a SyntaxError

tests/explorer/test_explorer_api.py:
- Remove all merge-artifact duplicate class definitions (TestAnalytics x2,
  TestReasoning x2, TestAnnotations x2) — Python silently used the second
  definition, hiding the first; collapsed into single canonical classes
- Fix test_snapshot_at referencing undefined 'body' (no request was made);
  merged its assertions into test_snapshot_now
- Fix test_compliance asserting isinstance(body, list) on a dict response;
  the displaced precedents-check code is now in test_precedents where it
  belongs
- Fix test_compliance_with_violation using wrong session reference
- Remove duplicate node-lookup and duplicate assertions throughout
- Add test_search_content_populated: asserts search results carry non-empty
  content (regression guard for the to_dict envelope fix)
- Add test_import_edge_metadata_preserved: asserts edge metadata survives the
  import round-trip (regression guard for the properties/metadata fallback fix)

All 51 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 00:18:08 +05:30
Mohd Kaif a0e7e9a1c9 Merge branch 'main' into fix/cg-thpag 2026-03-19 23:39:20 +05:30
88bd7d6b05 fix(explorer): resolve all PR review issues — bugs, tests, refactor
Bugs fixed:
- enrich.py: predict_links called predictor.predict_links() with wrong
  signature (graph_dict as graph_store, node_id as node_labels, top_n
  instead of top_k). Rewrote to iterate candidate nodes and call
  score_link(session.graph, src, candidate) directly.
- enrich.py: detect_duplicates called session.get_nodes() synchronously
  in an async handler, blocking the event loop. Wrapped in to_thread().
- export_import.py: temp file was leaked on export exception. Now always
  cleaned up via try/finally. Moved `import os` to module level.
- pyproject.toml: missing comma between two strings in the `all` extra
  caused a TOML syntax error breaking `pip install semantica[all]`.
- app.py: generic Exception handler swallowed HTTPException(503) raised
  by get_session dependency. Now re-raises HTTPException explicitly.
- decisions.py: compliance endpoint imported PolicyEngine then discarded
  it, always returning compliant=True. Replaced with in-graph check:
  scans for violates/non_compliant/breaches edges from the decision node.
- app.py: removed unused `import traceback`.

Refactor:
- session.py: added build_graph_dict(node_ids=None) method to eliminate
  _build_graph_dict() duplication across graph.py, analytics.py, and
  export_import.py (three identical copies).
- session.py: all 8 lazy analytics properties now initialise under _lock
  to prevent double-instantiation under concurrent requests.
- graph.py: find_path now dispatches to dijkstra_shortest_path or
  bfs_shortest_path based on the `algorithm` query param (was always BFS).
- annotations.py: removed unnecessary get_annotations() round-trip in
  create_annotation — add_annotation mutates ann_data in-place.
- temporal.py: split bare `except Exception` into ImportError (silent)
  and Exception (logs warning), so real bugs are no longer hidden.

Tests (49 total, all passing):
- Added TestEnrichExtract, TestLinkPrediction, TestDedup classes.
- Added test_compliance_with_violation to verify real violation detection.
- Added test_snapshot_at_excludes_temporal_node, test_diff assertions,
  test_export_json_subset, test_import_with_edges, test_import_unsupported_format.
- Strengthened analytics, search, and annotation assertions.
- Reasoning test now asserts response shape when status is 200.

Co-authored-by: ZohaibHassan16 <zohaibhassan16@users.noreply.github.com>
Co-authored-by: KaifAhmad1 <kaifahmad1@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 16:27:17 +05:30
Zohaib e3a0c84b90 Merge branch 'main' into feat/gitgraph 2026-03-19 01:56:46 +05:00
ZohaibHassan16 6bbb8f929f add unit tests 2026-03-19 01:50:48 +05:00
Mohd Kaif e7a13f7de6 Merge branch 'main' into fix/cg-thpag 2026-03-18 16:37:32 +05:30
Mohd Kaif fedbd8de8e Merge branch 'main' into feat/explorer-api-377 2026-03-18 16:33:51 +05:30
KaifAhmad1andClaude Sonnet 4.6 b2a2d24b14 fix: address all Qodo code review issues in Agno integration
Package & distribution
- pyproject.toml: add integrations* to packages.find include so pip
  install semantica[agno] ships the integration

context_store.py
- upsert_memory(): run NERExtractor after store() to index entities
  into the ContextGraph
- delete_memory() / drop_table() / clear(): call AgentContext.forget()
  to propagate deletions to vector/graph storage
- find_precedents(): pass limit parameter to find_precedents_advanced()
- retrieve(): pass limit as max_results to AgentContext.retrieve()
- add get_context_for_prompt() for automatic system-prompt injection

knowledge_graph.py
- __init__: wire graph_builder.graph_store = self._graph so build()
  persists into the ContextGraph
- add internal AgentContext for vector retrieval (shared ContextGraph)
- search(): use AgentContext.retrieve() for vector similarity; keyword
  scoring as fallback
- _ingest_text(): add paragraph-level chunking before NER/relation
  extraction (parse → split → NER → relation extract → graph build)
- get_graph_context(): return structured subgraph with edge types via
  ContextGraph.get_neighbors()
- load_urls(): validate scheme (http/https only) to prevent SSRF

decision_kit.py
- check_policy(): replace broken PolicyEngine.check_compliance() call
  with inline _eval_rule() that evaluates simple field-op-value rules;
  return compliant=False (not True) on failure — closes security bug

kg_toolkit.py
- add_to_graph(): fix add_node(node_id=, node_type=) and
  add_edge(source_id=, target_id=, edge_type=) to match real API
- query_graph(): use find_nodes() (no label param) + keyword filter
- find_related(): use get_neighbors(node_id=) returning List[Dict]
- infer_facts() / export_subgraph(): use find_nodes() public API
  instead of private _nodes dict

shared_context.py
- _AgentScopedStore: store shared context as self._context (not
  self._ctx) so all inherited AgnoContextStore methods work correctly

tests/integrations/agno/test_kg_toolkit.py
- _FakeGraph: rewrite to match real ContextGraph signatures —
  find_nodes(node_type=), add_node(node_id, node_type, **),
  add_edge(source_id, target_id, edge_type, **),
  get_neighbors(node_id, hops=1, ...) returning List[Dict]

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 04:21:48 +05:30
KaifAhmad1andClaude Sonnet 4.6 62c7970b32 feat(integrations): add Agno agentic framework integration (#249)
Implements the full Semantica × Agno integration stack as described in
issue #249, wiring Semantica's semantic intelligence layer into Agno's
agent/team primitives via five focused components.

## New components

### integrations/agno/
- `AgnoContextStore`    — graph-backed MemoryDb (AgentMemory/storage)
- `AgnoKnowledgeGraph`  — relational AgentKnowledge with multi-hop GraphRAG
- `AgnoDecisionKit`     — Agno Toolkit: 6 decision-intelligence tools
- `AgnoKGToolkit`       — Agno Toolkit: 7 knowledge-graph tools
- `AgnoSharedContext`   — team-level shared ContextGraph with role scoping

### tests/integrations/agno/
- 110 tests, 0 failures
- conftest.py installs comprehensive agno stubs for offline testing
- Covers MemoryDb protocol, tool registration, shared memory pool,
  thread-safety, GraphRAG search, NER/relation extraction, and inference

### cookbook/integrations/
- agno_decision_intelligence.ipynb     (finance/loan underwriting)
- agno_graphrag_context.ipynb          (regulatory compliance GraphRAG)
- agno_multi_agent_shared_context.ipynb (multi-agent product strategy team)

### docs/integrations/agno.md
- Full reference documentation with examples for all 5 components

## pyproject.toml
- Added `agno = ["agno>=1.0.0"]` optional dependency
- Added agno to the `all` extra

## Design notes
- Zero breaking changes — fully additive
- Graceful degradation when agno is not installed
- Auto-creates VectorStore(backend="faiss") when none provided
- _tools always populated for inspection regardless of agno install state
- Works with both real agno package and offline stubs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 03:25:14 +05:30
Mohd Kaif 4235840a9e Merge pull request #390 from Hawksight-AI/utils
ci: Optimize CI/CD Workflows — Scope Triggers to Avoid Redundant Runs
2026-03-18 01:12:44 +05:30
KaifAhmad1andClaude Sonnet 4.6 9a6c07417e fix: correct Entity import path in test_novita_integration
semantica.semantic_extract.models does not exist; Entity is defined in
ner_extractor.py and exported from semantica.semantic_extract directly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:17:08 +05:30
Mohd Kaif 3f55a34eff Merge branch 'main' into novita-integration 2026-03-17 22:34:33 +05:30
KaifAhmad1andClaude Sonnet 4.6 c5fb2d24fd fix: correct Novita base_url to /v1 and add proper test assertions
- Fix base_url from 'https://api.novita.ai/openai' to 'https://api.novita.ai/v1'
  to match the OpenAI-compatible endpoint convention used by other providers
  (Groq uses /openai/v1, Novita docs specify /v1)
- Rewrite test_novita_integration.py with proper pytest assertions and
  pytestmark skip when NOVITA_API_KEY is unset; tests now fail on errors
  instead of silently printing and returning

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 22:29:09 +05:30
Mohd Kaif 2cea2708a6 Merge branch 'main' into datalog#368 2026-03-17 17:07:45 +05:30
KaifAhmad1andClaude Sonnet 4.6 ad9ea48d26 fix: resolve review issues in DatalogReasoner
- Remove forced progress_tracker.enabled=True (was mutating global singleton)
- Wrap derive_all() fixpoint loop in try/finally so stop_tracking is always called
- Add _derived flag to cache fixpoint result; query() no longer re-runs derive_all() on every call
- Reset _derived to False in add_fact(), add_rule(), and clear()
- Warn (instead of silently drop) when add_fact() receives an unrecognised dict format
- Fix syntax error on line 9 of test file (stray dashes caused SyntaxError, broke CI)
- Add missing TestContextGraphIntegration tests: test_edge_becomes_fact and test_derive_after_load
- All 18 tests pass

Co-Authored-By: KaifAhmad1 <kaifahmad087@gmail.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 17:01:26 +05:30
KaifAhmad1andZohaibHassan16 665771f230 fix: address all review feedback on ontology diff implementation
- Fix typo in ChangeCategory enum: "potenitally_breaking" → "potentially_breaking"
- Fix missing space in _classify_change description string: "New{type}" → "New {type}"
- Add null-value guard in _analyze_field_changes for unset constraint fields
- Make ChangeLogAnalyzer stateless: pass report as arg to _generate_recommendations
- Remove no-op __init__ from ChangeLogAnalyzer
- Replace non-portable emoji markers in recommendations with plain-text tags
- Extend diff_ontologies to cover individuals and axioms (not just classes/properties)
- Fix exception chaining in compare_versions: raise ... from e
- Remove silent ImportError swallow for GraphValidator (it is a first-party module)
- Add comment on deferred VersionManager import explaining circular-import reason
- Fix import-before-docstring in test_managers.py
- Add tests: version-not-found error path, individuals/axioms diff coverage,
  null constraint flagged as breaking
- Fix broken Markdown link syntax in docs JSON example block
- Update docs recommendations example to match new plain-text tag format

Co-authored-by: ZohaibHassan16 <zohaib179949@gmail.com>
Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-03-16 22:05:12 +05:30
Mohd Kaif 9d4d682883 Merge branch 'main' into clean-ontology-diff 2026-03-16 21:48:47 +05:30
ZohaibHassan16 ee7c00f655 fix(context): resolve DecisionQuery fallback bugs and metadata preservation 2026-03-16 16:44:42 +05:00
Mohd Kaif 9bb71a45f2 Merge branch 'main' into onto-alignment 2026-03-16 16:43:07 +05:30
ZohaibHassan16 4146fbf277 fix(context): Implement ContextGraph traversal fallbacks for DecisionQuery 2026-03-16 02:12:49 +05:00
ZohaibHassan16 99a4db3ece feat: implement Knowledge Explorer API backend 2026-03-15 20:29:41 +05:00
Alex-wuhu de03d05600 Add Novita AI provider integration
- Add NovitaProvider class implementing OpenAI-compatible API
- Support for Novita AI API endpoint (https://api.novita.ai/openai)
- Configure via NOVITA_API_KEY environment variable or constructor
- Register 'novita' as built-in provider
- Update config.py to load NOVITA_API_KEY from environment
- Add test_novita_integration.py for provider testing

Default model: deepseek/deepseek-v3.2
2026-03-15 00:33:28 +08:00
KaifAhmad1 b309451398 Fix review issues in context explainability PR 2026-03-14 14:47:20 +05:30
KaifAhmad1 c2a6e944fe Improve context explainability outputs 2026-03-13 06:31:38 +05:30