- 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>
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>
- 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>
- 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>
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>
- 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>
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>
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>
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>
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>
- 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>
- 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>
- 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>
- 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