Commit Graph
100 Commits
Author SHA1 Message Date
Sameer Kadam 2ac3eaffd7 Merge branch 'main' into fix/issue-994-embed-fallback-recursion-corrupt-output 2026-08-19 19:07:06 +05:30
Sameer6305 3fbe3cfd2d fix(explorer): address edge label review findings 2026-08-18 20:34:54 +05:30
Sameer Kadam 75bc6255d4 Merge branch 'main' into fix/1009-edge-labels 2026-08-18 20:01:47 +05:30
Sameer6305 a96f1590f1 docs(explorer): document WebSocket authentication 2026-08-18 19:20:44 +05:30
Sameer Kadam 063f447202 Merge branch 'main' into fix/docs-explorer-auth-note 2026-08-18 19:00:47 +05:30
Sameer Kadam 5109c6fab2 Merge branch 'main' into fix/docs-explorer-auth-note 2026-08-18 14:41:09 +05:30
Sameer6305 12b9694a8e fix(explorer): complete edge label rendering 2026-08-18 14:19:25 +05:30
Sameer Kadam 55bde673c9 Merge branch 'main' into fix/1009-edge-labels 2026-08-18 13:11:35 +05:30
Sameer KadamandKaifAhmad1 04602a0e0e fix(security): prevent Authorization header leakage across redirects (#947) (#1067)
* fix(security): prevent auth header leakage across redirects

* fix(security): harden redirect credential handling

Address Copilot and Qodo review findings for #947.

- Remove unused variables, imports, and unnecessary pass statements from tests.
- Harden cross-origin redirect handling for per-request auth credentials.
- Strip session-level auth handlers before cross-origin redirect hops.
- Prevent session.auth from regenerating Authorization headers.
- Disable trust_env during cross-origin hops to prevent .netrc credential injection.
- Restore session auth and trust_env state reliably with try/finally.
- Add regression coverage for auth=, session.auth, trust_env, and multi-hop redirects.
- Preserve existing security behavior and same-origin authentication semantics.

Validated with 189/189 security and affected tests passing.

* fix(security): scope allow_private_ips to same-host redirects, fix error handling gaps

Follow-up to review findings on #1067:

- MCPClient hardcoded allow_private_ips=True for every redirect hop, not
  just its operator-configured host, so a compromised/malicious MCP server
  could 302 into private address space (e.g. cloud metadata) unchecked.
  request_with_ssrf_guard() gains allow_private_ips_on_redirect: a redirect
  target inherits the original host's private-IP trust only when it matches
  that host; MCPClient now pins it to False.
- detect_public_api() only caught requests.exceptions.RequestException, but
  the SSRF guard raises ValidationError for blocked hosts/redirects, unlike
  its sibling ingest_public_api(). Now catches and re-raises it the same way.
- detect_public_api()/ingest_public_api() forwarded session/allow_private_ips
  through **options into request_with_ssrf_guard(), which already passes
  both explicitly -- a caller supplying either would hit a duplicate-kwarg
  TypeError. Both are now popped from request_options first.

New regression coverage for all three in tests/ingest/, plus a CHANGELOG
entry under Unreleased/Security.

---------

Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-08-17 18:55:38 +05:30
Sameer6305 c7415f2e92 fix: complete spaCy model cache integration 2026-08-17 12:40:10 +05:30
Sameer Kadam 3331df28ad Merge branch 'main' into spacy-cache-split-chunking 2026-08-17 11:18:52 +05:30
Sameer6305 b8e8b2f227 fix(mcp): use semantica.__version__ as authoritative MCP version source
The previous implementation used importlib.metadata.version('semantica') as
the primary version source with a PackageNotFoundError fallback to
semantica.__version__. This caused two of the three new regression tests to
fail in editable/development installs, where dist-info (egg-info) is written
at install time and is not automatically updated on subsequent version bumps.

In this repo, pyproject.toml declares version as a static field (not dynamic),
and semantica/__init__.py maintains __version__ in sync with it by convention.
semantica.__version__ is therefore the authoritative source of truth and is
always present whenever semantica.mcp_server is importable -- the importlib
.metadata indirection adds no value and can return a stale value.

Changes:
- semantica/mcp_server/__init__.py: replace the importlib.metadata try/except
  block with a direct 'from semantica import __version__ as _SEMANTICA_VERSION'
- tests/test_mcp_server_version.py: rewrite tests to assert both MCP version
  surfaces (SERVER_INFO['version'] and semantica://schema/info) against
  semantica.__version__ as the single ground truth; add 0.4.0 regression
  canaries and a cross-surface consistency assertion; remove the mirrored
  importlib.metadata resolution that masked the staleness problem

The root-level mcp/ directory (a separate unpublished companion implementation
not included in the built package) is intentionally left unchanged -- it is
outside the scope of issue #863 which targets the semantica-mcp entry point.
2026-08-12 13:56:02 +05:30
Sameer Kadam f821fa7e2e Merge branch 'main' into fix/mcp-server-version 2026-08-12 13:01:29 +05:30
Sameer Kadam 8ef7c9f760 Merge branch 'main' into fix/mcp-server-version 2026-08-12 12:49:31 +05:30
Sameer Kadam a0aa415fc4 Merge branch 'main' into security/ssrf-dns-pinning-and-object-iri 2026-08-11 20:49:18 +05:30
Sameer6305 c5981aa306 fix: address qodo review findings on _PREFIX_DECL and query-length guard
Two follow-up fixes to the initial ReDoS patch (CodeQL py/polynomial-redos
#1897), raised during code review:

--- Fix 1: _PREFIX_DECL regression — inline prologues and CRLF (#review-1) ---

The first ReDoS fix replaced the ambiguous trailing \s* with [ \t]*(?:\n|$),
but that introduced a behavioral regression:

  * Inline prologues — PREFIX ex: <...> SELECT ... on a single line were no
    longer stripped because the mandatory (?:\n|$) anchor never matched when
    non-whitespace content followed the IRI on the same line.
  * CRLF line endings — PREFIX ex: <...>\r\n failed because \r is not in
    [ \t]* and the anchor expected a bare \n.

Root cause: the end-of-line anchor was unnecessary; the only thing needed
to eliminate backtracking ambiguity is ensuring the IRI body character class
and the trailing whitespace quantifier are disjoint.

Fix: change the IRI body from <[^>]*> to <[^>\r\n]*>, which:
  - excludes CR and LF from the IRI match (semantically correct — SPARQL
    IRIs cannot span line boundaries)
  - makes [^>\r\n]* and the trailing [ \t]* have zero character overlap,
    eliminating all backtracking ambiguity without any end-of-line anchor

No anchor is used, so both inline prologues and CRLF/LF endings work
naturally. ReDoS payloads (base< + !< x 10,000) still complete in <1 ms.

--- Fix 2: oversized-query length guard obscured error (#review-2) ---

The initial patch placed the _SPARQL_MAX_QUERY_LEN guard inside
_is_read_only_query(), which caused execute_sparql() to return the same
generic 'Only SELECT' error for both genuinely disallowed query types and
oversized inputs. Clients could not distinguish the two rejection reasons.

Fix: move the length check out of _is_read_only_query() and into
execute_sparql() as an explicit early gate, alongside the other resource
limits (_SPARQL_MAX_ROWS, _SPARQL_MAX_GRAPH_NODES). Oversized queries now
return a specific message naming the limit, the received length, and the
remediation step. _is_read_only_query() is documented to be length-agnostic.
_SPARQL_MAX_QUERY_LEN is relocated to the resource-limits block with the
other constants.

--- Tests added ---

tests/test_security_regression.py:
  - test_inline_prefix_before_select_allowed   (Fix 1 regression)
  - test_crlf_line_endings_with_prefix         (Fix 1 regression)
  - test_crlf_multiple_prefixes_then_select    (Fix 1 regression)
  - test_inline_prefix_before_insert_still_blocked (Fix 1 security check)
  - test_long_valid_query_not_rejected_by_is_read_only (Fix 2 separation)

tests/explorer/test_sparql_route.py:
  - test_oversized_query_returns_distinct_length_error (Fix 2 error message)
  - test_oversized_query_never_touches_the_graph       (Fix 2 short-circuit)
  - test_query_exactly_at_length_limit_is_accepted     (Fix 2 boundary)

All 82 tests pass.
2026-08-11 18:37:50 +05:30
Sameer6305 d507fda1b0 fix: resolve ReDoS in _PREFIX_DECL regex (CodeQL #1897)
The _PREFIX_DECL pattern used \s* as a trailing quantifier after
<[^>]*>. On inputs that start with ase< but contain no closing >
(e.g. ase<!<<!<<!<...), the regex engine explores exponentially many
ways to split the match between [^>]* and \s*, causing polynomial
backtracking against user-controlled SPARQL query input.

Fix:
- Replace ^\s* / \s+ / \s* with ^[ \t]* / [ \t]+ / [ \t]*
  so the leading/internal whitespace quantifiers only match horizontal
  whitespace (no overlap with the <[^>]*> IRI part).
- Replace the ambiguous trailing \s* with [ \t]*(?:\n|$), which
  matches only horizontal whitespace followed by a hard line boundary.
  [^>]* and [ \t]* have disjoint character sets, eliminating the
  backtracking ambiguity entirely.
- Add _SPARQL_MAX_QUERY_LEN = 10_000 guard at the top of
  _is_read_only_query as defence-in-depth: rejects oversized input
  before any regex work, bounding worst-case cost even if a future
  pattern change reintroduces ambiguity.

Verified: ReDoS payload ase< + !< x 5000 completes in <1 ms.
Normal PREFIX/BASE stripping and read-only query detection unchanged.

Fixes: CodeQL py/polynomial-redos alert #1897
CWE: CWE-1333, CWE-730, CWE-400
2026-08-11 18:05:29 +05:30
Sameer6305 1c3ac66fd9 fix(rdf4j): preserve literal objects in delete_triplet 2026-08-11 16:27:52 +05:30
Sameer Kadam bde6e2d68e Merge branch 'main' into fix/mcp-server-version 2026-08-10 21:38:16 +05:30
Sameer Kadam 01bd908f86 Merge branch 'main' into fix/mcp-server-version 2026-08-10 20:50:49 +05:30
Sameer Kadam bd35d6031b docs: clarify contributor issue workflow (#895) 2026-08-10 19:45:54 +05:30
Sameer Kadam 7654d8c6c7 Merge branch 'main' into fix/AttributError_in_filter_by_metadata_on_persistent_backend 2026-08-10 17:33:48 +05:30
Sameer6305 70109133b5 fix(vector-store): harden metadata filtering across backends 2026-08-10 17:26:39 +05:30
Sameer6305 8e0419c864 fixed qodo review
Adds similarity_unavailable marker and warning logs to build_decision_context and explain_decision when a persistent backend (like FAISS) fails to reconstruct a vector. Updates docstrings to explicitly state this degraded-path behavior and guarantees schema stability. Adds regression tests to test vector retrieval failure behavior via caplog and context assertions.
2026-08-08 13:16:50 +05:30
Sameer6305 0d51608547 fix(vector_store): stop bypassing backend abstraction in build_decision_context/explain_decision/_filter_by_metadata (closes #848)
- build_decision_context() and explain_decision(include_paths=True) both
  accessed self.vectors directly, which is only initialized for the
  inmemory backend, crashing with AttributeError on any persistent
  backend (FAISS, Qdrant, Pinecone, etc.). Replaced with self.get_vector()
  (#843's backend-agnostic accessor) + an is-not-None check — a verified
  1:1 behavioral equivalent for the old 'decision_id in self.vectors'
  guard on the inmemory path.
- Found a third, undocumented instance of the same bug during
  verification: _filter_by_metadata() also accessed self.metadata/
  self.vectors directly. Initial fix silently returned [] for persistent
  backends, which was itself a new silent-failure bug (indistinguishable
  from a genuine zero-match result). Reconciled to raise
  NotImplementedError instead, matching the established precedent from
  get_vector()/get_metadata() (#843) for 'backend exists but doesn't
  support this operation' — confirmed via full grep of all 7 backend
  wrapper classes that none currently implement filter_by_metadata,
  so this path was previously dead-code-masked-as-working.

Tests: 14 new tests across two rounds — inmemory behavioral equivalence,
real (non-mocked) FAISS backend regression tests for all three methods,
and explicit coverage proving the NotImplementedError fires with a clear
message rather than the old silent-[] behavior. Full suite: 53 passed,
0 failed, 0 regressions across the 39 pre-existing tests.
2026-08-08 12:57:42 +05:30
Sameer6305 f75469f472 Merge remote-tracking branch 'semantica-agi/main' into fix/843-vectorstore-persistent-backend-accessors 2026-08-07 22:23:39 +05:30
Sameer6305 40b81d0582 fixed qodo reviews: standardize search results schema, score metric, and ID types
- Removed total=False from SearchResult TypedDict so all fields are strictly required

- Ensured distance: None is returned from backends that don't natively expose distance (Qdrant, Pinecone, SQLite, pgvector, in-memory)

- Standardized search result score to a consistent 0.0 - 1.0 similarity metric scale across all backend adapters

- Relaxed SearchResult id type to Union[str, int] to accommodate native integer IDs from Milvus and Qdrant without casting

- Updated schema verification tests
2026-08-07 21:34:43 +05:30
Sameer6305 5db0adc18a fix(vector-store): standardize search_vectors output schema 2026-08-07 19:39:14 +05:30
Sameer6305 dd42b7fa95 fix(milvus): add backward compatibility alias and sanitize query
- Added insert_vectors alias to add_vectors for backward compatibility.
- Sanitized vector_id in get_vector and get_metadata to prevent query injection.
2026-08-07 12:11:48 +05:30
Sameer6305 248d028b09 fixed qodo reviews
- FAISSStore: get_metadata now correctly retrieves from self.metadata instead of raising NotImplementedError.
- MilvusStore:
  - Changed schema to support String IDs (VARCHAR) instead of auto-generated INT64, preventing loss of IDs during insert.
  - Added metadata storage using JSON.
  - Replaced insert_vectors with add_vectors accepting ids and metadata (added insert_vectors alias for backward compatibility).
  - Implemented get_vector and get_metadata with safe parameterized querying to prevent query injection.
- PgVectorStore & SQLiteVecStore:
  - Fixed get_vector and get_metadata to call self.get([vector_id]) instead of the non-existent get_vectors([vector_id]), fixing the silent None return bug.
2026-08-07 12:04:47 +05:30
Sameer6305 c8b59b47f5 fix(vector-store): fix get_vector/get_metadata crash on persistent backends (#843)
- VectorStore.get_vector() and get_metadata() were hardcoded to access
  self.vectors and self.metadata dicts, which are only initialized for
  the inmemory backend, causing AttributeError on all persistent backends
  (FAISS, Qdrant, Pinecone, Milvus, Weaviate, PgVector, SQLiteVec).

Changes:
- Refactor VectorStore.get_vector() and get_metadata() to branch on
  self.backend == 'inmemory' (zero behavior change) and delegate to
  self._backend_store otherwise.
- Harden save() to use getattr(self, 'vectors', {}) / getattr(self,
  'metadata', {}) to prevent crash when saving a persistent backend store.
- Add get_vector() and get_metadata() to all 7 backend wrappers:
  - FAISSStore: get_vector uses index.reconstruct(); get_metadata raises
    NotImplementedError (FAISS has no metadata storage natively).
  - QdrantStore: uses client.retrieve() with with_vectors/with_payload.
  - PineconeStore: wraps existing fetch_vectors() call.
  - MilvusStore: raises NotImplementedError (auto_id=True schema discards
    string IDs at insert time, making by-ID lookup impossible in this
    wrapper's current schema).
  - WeaviateStore: uses collection.query.fetch_object_by_id().
  - PgVectorStore: wraps existing get_vectors() SQL method.
  - SQLiteVecStore: wraps existing get_vectors() SQL method.
- Add TestVectorStoreRetrieval regression tests covering inmemory and
  FAISS backends with real (non-mocked) assertions.

All 28 tests pass.
2026-08-07 11:21:42 +05:30
Sameer Kadam 36071819b5 Merge branch 'main' into fix/839-decisionembeddingpipeline-backend-support 2026-08-06 20:15:05 +05:30
Sameer6305 a4dac2342b fixed qodo reviews 2026-08-06 19:44:23 +05:30
Sameer6305 7d272f40e8 Fix #839: Support persistent backends in DecisionEmbeddingPipeline
- Replace direct .vectors and .metadata access with VectorStore.search_vectors().
- Add a fallback in HybridSimilarityCalculator (via ind_similar_decisions) to use the search score when backend vector databases do not natively return the raw vector array.
- Fix get_decision_statistics to gracefully fall back when .metadata is not fully supported by the underlying DB.
- Add regression tests utilizing the real FAISS and inmemory backends directly without mocking.
2026-08-06 19:11:35 +05:30
Sameer6305 cb716cec61 Merge semantica-agi/main into fix/833-hybridsearch-attributeerror-non-inmemory-backends 2026-08-05 21:12:11 +05:30
Sameer6305 712a6e6d4c test(hybrid_search): add backend delegation regression coverage 2026-08-05 20:31:59 +05:30
Sameer6305 bd8d6c5913 docs: add #830 Explorer Temporal panel fix to CHANGELOG.md 2026-08-05 18:06:45 +05:30
Sameer6305 667e69a0c1 refactor: tighten comments across #830 changes for clarity
- pluginRegistryPredicates.ts: consolidate 8-line JSDoc to 5 lines,
  removing redundant detail that restated implementation mechanics
  already obvious from the code.

- GraphWorkspace.tsx: shorten the lastScrubberMsRef comment from 5 lines
  to 2; trim the handleDiagnosticsChange block comment by removing the
  'rather than bailing out' implementation-alternative sentence; tighten
  the distanceVisual inline comment.

- pluginRegistry.temporal.test.mjs: replace 17-line file-level JSDoc
  with 9 lines focused on the invariant rather than the root-cause
  narrative (already covered in pluginRegistryPredicates.ts); remove
  two tsx loader implementation-detail comments; tighten two test-level
  inline comments.

No logic, types, or test assertions changed. All 42 tests pass.
2026-08-05 17:52:21 +05:30
Sameer6305 80de3652cf fixed qodo findings
Two issues addressed:

1. Plugin-loading useEffect unnecessarily depended on temporalState.
   After the #830 fix, no shouldLoad predicate reads temporalState, but
   the effect's dep array still included it, causing extra re-runs on
   every scrubber update. Removed temporalState from the dep array and
   the shouldLoad call site. Made temporalState optional in the
   LazyPluginRegistryEntry shouldLoad context type to match.

2. Regression test imported a local copy of shouldLoad instead of the
   production predicate. Extracted all three shouldLoad predicates into
   pluginRegistryPredicates.ts (pure module, no React/DOM dependencies),
   wired GraphWorkspace.tsx to use the imported functions, and updated
   the test to import and exercise the real production code via tsx.
   Verified: introducing the old broken condition causes the test to fail;
   the correct implementation passes all 7 assertions.
2026-08-05 17:37:33 +05:30
Sameer6305 8d52281cdf chore(explorer): clean up #830 branch — remove #793 file, add regression test
temporalDiffState.ts belongs to feat/793-temporal-diff-ui and should not
appear in the #830 diff. Remove it from this branch's tracked files.

Add the pluginRegistry.temporal.test.mjs regression test that covers the
shouldLoad fix committed in the main #830 commit (it was never committed).

Add test:plugin-registry script to package.json so the regression test
can be run via npm run test:plugin-registry.
2026-08-05 16:26:24 +05:30
Sameer6305 6a0eecbe02 fix(explorer): resolve #830 — Maximum update depth exceeded on Temporal panel open
Two independent render loops were causing the Temporal panel to remain
stuck on 'Loading temporal...' in npm run dev:

Loop 1 — diagnostics state churn (GraphWorkspace.tsx):
  handleDiagnosticsChange unconditionally called setGraphDiagnosticsState
  with a new object on every invocation. buildEffectAvailability (called
  inside GraphCanvas's diagnostics useEffect) always returns a new object,
  so setGraphDiagnosticsState was called on every effect run, creating a
  cycle: setGraphDiagnosticsState  graphDiagnosticsState new
  diagnosticsSnapshot new  pluginContext new  handleInteractionStateChange
  new  GraphCanvas re-renders  diagnostics effect fires again.

  Fix: before calling setGraphDiagnosticsState, compare the incoming
  diagnostics field-by-field against the last accepted snapshot via a ref
  (lastDiagnosticsRef). All effectAvailability entries, edgeClasses.updatedAt,
  structureLayer.cacheKey/lastDrawAt/enabled, and distanceVisual identity
  must differ for a state update to proceed. The ref approach avoids
  scheduling a re-render at all, rather than bailing out inside a functional
  updater after the render has already been committed.

Loop 2 — scrubberTime churn (GraphWorkspace.tsx + GraphWorkspaceShell.tsx):
  TimelinePanel.tsx calls onTimeChange(defaultTime) whenever its useEffect
  re-runs. React 18 concurrent mode re-runs effects with structurally-new
  Date objects for the same timestamp when speculative renders discard
  useMemo caches, causing setScrubberTime to be called repeatedly with a
  new Date that has the same millisecond value — triggering temporalState
  churn, the diagnostics effect, and eventually the same loop.

  Fix: wrap setScrubberTime in an onTimeChange useCallback that compares the
  incoming time's millisecond value against the last sent value (via
  lastScrubberMsRef). Redundant calls with the same timestamp are dropped
  before reaching setScrubberTime. Stable useCallback identity also prevents
  TimelinePanel's useEffect from re-firing solely due to prop identity churn.

Both fixes applied to GraphWorkspace.tsx and identically to
GraphWorkspaceShell.tsx which has the same pattern.

Verified:
- npm run dev: 0 'Maximum update depth exceeded' errors
- Temporal panel renders with real data in dev mode
- Effects and Neighbors panels unaffected
- npm run build + preview: identical behavior, 0 errors
- All 42 frontend tests pass (34 graph-workspace, 1 graph-store, 7 plugin-registry)
2026-08-05 16:01:18 +05:30
Sameer6305 aa85535d47 fixed copilot review 2026-08-04 16:45:33 +05:30
Sameer6305 7d936d0f7c fix(explorer): write diff highlights to displayGraph as well as store graph
fixed qodo review

applyDiffHighlight/clearDiffHighlight were writing baseColor only to
graphStore.graph (the store singleton), but Sigma is constructed with
displayGraphRef.current and the nodeReducer reads attributes from that
instance. When the display graph is a derived copy (aggregated,
focused, or grouped view), the store write has no effect on the
currently-rendered frame -- sigma.scheduleRefresh() flushes the
reducer over the display graph, which did not receive the mutation.

Fix: introduce writeBaseColor(context, nodeId, color) which writes to
BOTH the store graph (so the color propagates into the next display
graph rebuild via aggregateDisplayGraph's shallow attribute copy) AND
context.displayGraph (the live Graph instance currently bound to
Sigma, so the change is visible in the current frame immediately).

The dg !== graph guard skips the display-graph write when they happen
to be the same object (non-aggregated full view), avoiding a redundant
double-write in that case.

Original baseColor is still captured from the store graph (the
authoritative source, since aggregateDisplayGraph copies from there),
so restore remains correct across all view modes.
2026-08-04 16:32:04 +05:30
Sameer6305 47531d8365 feat(explorer): add temporal diff comparison to the Temporal panel
Adds a Compare section to the existing Temporal Context panel
(temporalOverlayPlugin.tsx) that lets a user pick two ISO timestamps
and diff the graph's node set between them via the existing, previously
UI-less GET /api/temporal/diff backend route.

- New temporalDiffState.ts: typed fetch wrapper (fetchTemporalDiff)
  matching the route's added_nodes/removed_nodes response shape.
- Diff results recolor affected nodes via baseColor (not
  ringColor/haloColor -- traced and confirmed those are only read by
  the sigma reducer for hovered/selected/path-state nodes and are
  silently discarded for default-state nodes).
- Validates both timestamps are present, parseable, and from < to
  before firing a request.
- Distinct idle/loading/error/empty/success states -- an empty diff
  (no changes) is rendered as its own state, not as an error.
- Cancels any in-flight request via AbortController on re-submission
  and on unmount; restores each highlighted node's original baseColor
  (captured before overwrite, not cleared to a fallback default) on
  both paths.
- Reuses existing theme tokens (GRAPH_THEME.palette.semantic[2],
  ui.control.dangerText) and existing button/input/loading/error
  visual patterns already established in this same plugins directory
  and in GraphInspectorPanel.tsx, rather than introducing new styling.
2026-08-04 15:57:53 +05:30
Sameer6305 e9e05fedbd fix(provenance): reset in-memory chain state on clear 2026-08-04 00:01:50 +05:30
Sameer6305 74c093facb fixed issues from qodo and copilot 2026-08-03 21:37:26 +05:30
Sameer6305 aae4c946ea test(provenance): expand storage failure regression coverage (#785) 2026-08-03 21:05:26 +05:30
Sameer KadamandKaifAhmad1 76edaeb1c0 fix(agno): make _eval_rule raise instead of silently returning compliant=True on unevaluable rules (closes #778) (#822)
* fix(agno): surface unevaluable policy rules (#778)

* fix(agno): fixed qodo reviews

check_policy previously let unevaluable policy rules silently return
compliant=True with no signal (issue #778): a rule referencing a field
missing from decision_data, or a rule string not matching the expected
<field> <op> <value> format, both fell through _eval_rule's `return
True` and were treated as passed.

Both now raise ValueError, which routes through check_policy's existing
exception handler and surfaces as a `warnings` entry instead. compliant/
violations semantics are unchanged for every case that previously worked
correctly; an unevaluable rule is not counted as a violation since it's
genuinely unknown whether it would have passed.

Follow-up fixes from code review:
- policy_rules decoded via json.loads without checking it was a list;
  a JSON-encoded bare string decoded to a Python str, so iterating it
  evaluated one "rule" per character, amplifying a single input-shape
  mistake into a wall of per-character warnings. A decoded string is
  now treated as a single rule; any other non-list shape or non-string
  list element produces exactly one warning instead.
- _eval_rule used `data.get(field) is None` to detect a missing field,
  which can't distinguish an absent key from a key present with JSON
  null - both produced the same "undefined field" warning. Field
  presence is now checked with `field not in data` first, and a
  present-but-null value gets its own distinct message.

Added regression tests for all of the above in
tests/integrations/agno/test_decision_kit.py (38 tests in the file,
128 passing across tests/integrations/agno/).

* fix(agno): reject non-object decision_data in check_policy

check_policy only validated that decision_data was well-formed JSON,
not that it decoded to an object. When it decoded to a list, `field
not in data` in _eval_rule silently became list-membership testing
of values instead of a dict key check - e.g. "confidence" not in
["confidence", 0.95] evaluates to False - so a matching rule fell
through to data["confidence"], raising a raw internal TypeError
("list indices must be integers or slices, not str") instead of any
meaningful diagnostic. Numbers, strings, and bools produced similarly
opaque TypeErrors deep inside _eval_rule.

check_policy now checks isinstance(data, dict) right after decoding
and rejects any other shape with a single clear violations entry,
the same way it already rejects malformed JSON.

Added 5 regression tests in tests/integrations/agno/test_decision_kit.py
covering list/number/string/bool/null decision_data shapes (43 tests
in the file, 133 passing across tests/integrations/agno/).

Addresses Copilot PR review comment on the #778 fix branch.

* docs(changelog): reference PR #822 in the check_policy changelog entry

---------

Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-08-03 12:23:49 +05:30
Sameer6305 6f6c825f3d fixed qodo reviews
- Removed unused `validate_skos_hierarchy` import from
  test_ontology_subissue3.py (flake8 F401); the test uses a `wraps=` spy
  on the real add_nodes_and_edges instead of calling the helper directly.
- refresh_ontology tests now percent-encode the ontology URI with
  urllib.parse.quote before interpolating it into the {ontology_uri:path}
  request path, matching the already-encoded unknown-uri refresh test in
  the same file instead of embedding a raw http://... URI with slashes.
- Reworded the cyclic-SKOS refresh test's comment and section header:
  GraphSession.add_nodes_and_edges() documents pre-write validation and
  lock-based mutual exclusion, not transactional rollback, so "atomic"
  was replaced with "single combined add_nodes_and_edges() call" to avoid
  implying rollback guarantees that don't exist.

Verified: tests/explorer/test_ontology_subissue3.py (34 passed) and
tests/explorer/ (204 passed), no regressions.
2026-08-01 19:36:16 +05:30
Sameer6305 d293ca6009 fix(explorer): complete atomic ontology refresh writes (#775) 2026-08-01 19:12:00 +05:30
Sameer6305 aa58b46d4d Merge semantica-agi/main into fix/779-record-decision-logging 2026-07-31 18:28:20 +05:30
Sameer6305 633d485045 fixed qodo review
- Added exc_info=True to both store failed and record_decision failed warning logs in _AgentScopedStore.upsert_memory() to preserve full traceback context for debugging

- Updated CHANGELOG.md entry to document traceback preservation
2026-07-31 18:19:50 +05:30
Sameer6305 d21e5e9944 fix(agno): log decision tracking failures in shared context - #779 2026-07-31 17:50:40 +05:30
Sameer6305 ac64943965 Merge remote-tracking branch 'semantica-agi/main' into fix/783-tracking-methods-honest-failures
# Conflicts:
#	CHANGELOG.md
2026-07-31 16:11:32 +05:30
Sameer6305 4dea295f0d fixed qodo reviews
- split.ProvenanceTracker: Check _unified_manager.track_chunk() return value and fall back to legacy storage when None is returned (storage failure)

- split.ProvenanceTracker: Initialize legacy stores (_provenance_store and _chunk_registry) unconditionally in __init__ so legacy fallback storage works safely even when initialized with use_unified=True

- split.ProvenanceTracker: Update get_provenance() to check legacy storage when no record is found in unified storage, ensuring fallback-tracked chunks remain retrievable

- SourceTracker: Change track_sources_batch() condition from if entry is not None: to if ok: to respect the boolean return contract (-> bool) of track_entity_source(), track_property_source(), and track_relationship_source()

- Tests: Add regression test test_unified_tracking_returns_none_triggers_fallback and update test_track_sources_batch_failure_not_counted to test boolean failure return_value=False
2026-07-31 16:05:37 +05:30
Sameer6305 1ae1e6d57a docs(provenance): document Optional return types and failure behavior (#783) 2026-07-31 15:01:33 +05:30
Sameer6305 495e29d543 fix(provenance): log tracking failures and return None on storage error (closes #783) 2026-07-31 15:00:23 +05:30
Sameer6305 66be1630fa fix(agno): fail fast on toolkit registration failures - #780 2026-07-30 20:43:26 +05:30
Sameer6305 a1f835c9b2 refactor(mcp): harden handle_get_causal_chain inputs and signature introspection (#781)
- Add safe input validation and bounds clamping on max_depth (1..100) to prevent DoS/memory exhaustion

- Use inspect.signature for accurate keyword dispatch with precise TypeError fallback

- Prevent masking of genuine internal TypeError exceptions inside graph backends

- Add security and input hardening regression tests
2026-07-30 19:09:22 +05:30
Sameer6305 12172d03b4 fix(mcp): fixed qodo reviews (#781)
- Support legacy (depth kwarg) and positional-only get_causal_chain backend signatures in fallback path

- Add regression tests for signature compatibility
2026-07-30 19:04:00 +05:30
Sameer6305 60f362817f fix(mcp): return error when causal chain analysis unsupported (#781)
- Return explicit error dictionary when graph lacks get_causal_chain instead of silent empty list

- Forward direction and max_depth in fallback graph.get_causal_chain call

- Add regression tests for error signaling and parameter forwarding
2026-07-30 18:11:04 +05:30
Sameer6305 4d1e5cf37c fixed qodo reviews 2026-07-30 16:58:19 +05:30
Sameer6305 16893c28a4 docs(provenance): document atomic rollback behavior (#782) 2026-07-30 16:28:40 +05:30
Sameer6305 577967a549 fix(provenance): make track_entity writes atomic (closes #782) 2026-07-30 16:28:40 +05:30
Sameer KadamandKaifAhmad1 e197977172 refactor(provenance): centralize duplicated store-and-swallow logic into _save_entry() (#784) (#815)
* refactor(provenance): centralize duplicated store-and-swallow logic into _save_entry() (closes #784)

- Added ProvenanceManager._save_entry(entry) as the single shared
  checksum-compute + storage.store() + graceful-failure-swallow
  pipeline, previously duplicated identically across track_entity,
  track_relationship, track_chunk, and track_property_source.
- track_entities_batch/track_chunks_batch already delegate to
  track_entity/track_chunk in a loop, so they inherit the fix for
  free — left untouched, confirmed no direct duplication there.
- Byte-for-byte preserves today's swallow-and-continue behavior and
  comment text; this is an architecture-only refactor. The silent-
  failure behavior itself is unchanged and out of scope here — a fix
  to it now only needs to happen in one place instead of four.
- Added 4 new regression tests (previously 0 of the 4 single-item
  methods had failure-path coverage) proving storage.store() raising
  is still caught and each method still returns its ProvenanceEntry.

Tests: tests/provenance/ 228 passed (+4 new), tests/explorer/test_provenance_manager_wiring.py 8 passed. 236/236, 0 failed.

* fix(provenance): drop out-of-transaction store attempt in track_entity fallback

The _save_entry refactor changed track_entity's pre-build exception
fallback (entry is None branch) to call _save_entry(), which makes a
real self.storage.store(entry) call. The original code only computed
a checksum here and never attempted storage again, since this branch
fires when something already failed before the entry was built inside
the atomic transaction. Storing outside that transaction bypasses the
BEGIN IMMEDIATE serialization #807 added, risking the same race it
fixed. Restored checksum-only behavior and added a regression test
asserting storage.store is not called on this path.

Also removed an untested hasattr(_store_with_conn) defensive branch
added during the refactor that wasn't in the original code, and added
a changelog entry.

---------

Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
2026-07-29 22:18:05 +05:30
Sameer6305 dabeb0e833 docs: add changelog entry for #807 2026-07-28 23:44:14 +05:30
Sameer6305 9458cf5b2b docs: update provenance documentation for SQLiteStorage WAL and batch tracking (#807) 2026-07-28 23:42:14 +05:30
Sameer6305 3db35a6871 fixed qodo reviews 2026-07-28 23:37:46 +05:30
Sameer6305 b1daf238ca perf(provenance): optimize SQLite transaction lifecycle and lineage traversal 2026-07-28 23:06:23 +05:30
Sameer6305 8d3c99ba30 perf(provenance): optimize lineage integrity checks and clean up top-level imports (#792)
- Reuse lineage['integrity_verified'] in _build_provenance in O(1) time when available, eliminating redundant SHA-256 verification loops across lineage chains.

- Improve compute_checksum dictionary handling in semantica/provenance/integrity.py so None values fall back cleanly to ProvenanceEntry defaults.

- Move json and verify_checksum imports to module top-level in semantica/provenance/manager.py to avoid function-local import overhead during get_lineage calls.
2026-07-28 17:25:01 +05:30
Sameer6305 c2079d8e92 fix(explorer): preserve audit evidence fields in provenance nodes and reports (#792)
- Extend ProvenanceNode in semantica/explorer/schemas.py with audit evidence fields: source_document, source_location, source_quote, confidence, and checksum.

- Update _transform_audit_lineage in semantica/explorer/routes/provenance.py to populate these evidence fields for each lineage node from ProvenanceEntry records, while keeping default None values for orphan nodes.

- Include source_document, confidence, and checksum in markdown report rendering (_render_markdown) so exported markdown reports surface attribution and integrity evidence.

- Add unit test test_provenance_audit_evidence_fields_preserved in test_provenance_manager_wiring.py verifying that evidence fields are present across /api/provenance JSON responses and exported JSON/markdown reports.
2026-07-28 17:15:49 +05:30
Sameer6305 cc864362aa fix(provenance): verify checksum integrity of lineage entries before labeling source as audit (#792)
- Update verify_checksum and compute_checksum in semantica/provenance/integrity.py to support both ProvenanceEntry objects and serialized dictionary entries.

- Add integrity_verified flag computed via verify_checksum to the dictionary returned by ProvenanceManager.get_lineage().

- Update _build_provenance in semantica/explorer/routes/provenance.py to verify every returned lineage entry before labeling the result as source=audit. If verification fails due to missing checksums or corrupted records, log a warning and fall back cleanly to graph traversal.

- Add unit test test_provenance_manager_wiring_checksum_failure_falls_back in test_provenance_manager_wiring.py verifying that tampered lineage entries trigger fallback to source=graph_traversal.
2026-07-28 17:08:12 +05:30
Sameer6305 d30aea79a7 fix(explorer): classify multi-hop audit lineage as upstream and enforce provenance storage configuration (#792)
- Fix _transform_audit_lineage to classify all non-downstream ancestor derivation edges as 'upstream' instead of 'lateral', correcting multi-hop lineage direction in JSON and markdown reports.

- Add GraphSession.set_provenance_storage_path() to explicitly reject conflicting preconfigured storage paths or path mutations after provenance_manager initialization.

- Update create_app() to call active_session.set_provenance_storage_path(prov_path), preventing silent retention of conflicting paths or un-redirectable cached managers.

- Remove unused logging import in app.py.

- Add comprehensive unit tests in test_provenance_manager_wiring.py for upstream edge classification, markdown report grouping, conflicting path rejection, and manager initialization lockouts.
2026-07-28 16:57:38 +05:30
Sameer6305 2ee4da0b47 fix(explorer): wire ProvenanceManager into provenance routes (closes #792)
- Explorer's /api/provenance now queries the audit-grade ProvenanceManager
  (SQLite-backed, checksummed) first, falling back to the naive 2-hop
  graph traversal when no audit records exist for a node.
- Fixed a process-global mutable-state risk in the initial approach:
  provenance storage path is threaded per-session via GraphSession,
  not via ProvenanceManager's global set_default_storage_path classmethod.
- Added source: 'audit' | 'graph_traversal' to the response so callers
  can distinguish which path served the data.
- Documented a known limitation: ProvenanceManager currently only
  traces upstream/ancestor lineage, not descendants — the naive
  fallback remains the only source for downstream relationships until
  ProvenanceManager gains a reverse lookup (tracked separately).
- Warns (rather than silently no-ops) if a provided session's
  provenance_manager was already constructed before create_app()
  applied a provenance_storage_path.
- Never lets a provenance-manager failure crash the route; degrades
  to the naive path with a logged warning instead.

Tests: 5 new tests in test_provenance_manager_wiring.py covering the
audit path, empty-record fallback, storage-failure degradation, app
startup wiring, and cross-session storage isolation. Full
tests/explorer/ + tests/provenance/ suite passing, order-invariant.
2026-07-28 16:23:02 +05:30
Sameer6305 ce914b396a docs: clarify Snowflake OAuth auth, add ArrowIngestor and non-re-exported ingestors (PR #808) 2026-07-28 15:00:02 +05:30
Sameer6305 db95cedf34 fixed qodo reviews and hardened implementation 2026-07-27 15:42:49 +05:30
Sameer6305 3a9c7c082f Merge branch 'main' into fix/773-sparql-test-coverage 2026-07-27 15:08:14 +05:30
Sameer6305 dd7b090aec test(explorer): add coverage for SPARQL route (#773)
sparql.py handles direct SPARQL query execution against the live graph with no test coverage anywhere in the repo. Adds coverage for the read-only allowlist (the actual security boundary here), row/timeout limits, error handling, and RDF projection fidelity.
2026-07-27 15:00:47 +05:30
Sameer6305 8430d4a56e fix(ontology): address qodo review findings for SHACL validation
- DoS guardrails: enforce byte size, triple count, concurrency, and timeout limits on /shacl/validate

- Slash namespace resolution: preserve trailing slash in _resolve_uri so local terms match SHACL shapes

- Truncation safety: raise GraphTruncationError and report unavailable/413/critical when graphs exceed analysis limits

- JSON-LD dict lists: unwrap uri/id/@id in _as_uri_list and _data_graph_turtle_for_uri property loops

- Observability & efficiency: add warning logs on truncation and avoid duplicate UTF-8 encoding in size check
2026-07-27 14:01:45 +05:30
Sameer6305 3a1ab1a8a6 fix(ontology): wire live SHACL validation into /shacl/validate and /health
Closes #772
2026-07-27 13:02:04 +05:30
Sameer6305 40d6fa05d0 fix(context): normalize timestamps in _markdown_record_matches for idempotency 2026-07-26 18:49:30 +05:30
Sameer6305 ac69c27b86 fixes reviews from qodo free for open source 2026-07-26 16:56:06 +05:30
Sameer6305 a16bd9600b fixes reviews from qodo free for open source 2026-07-26 16:46:50 +05:30
Sameer6305 fd84be8b66 fixed qodo reviews 2026-07-26 16:26:47 +05:30
Sameer6305 6cc2e67b92 fix(provenance): populate entries alias in get_lineage and read lineage_chain in lineage()
- Add entries alias in get_lineage() return dictionary so CLI and programmatic callers can access lineage entries via either key

- Update lineage() wrapper method to fallback to lineage_chain when entries is missing

- Add assertions in test_cli_lineage confirming lineage and entries lists are non-empty
2026-07-26 16:10:26 +05:30
Sameer6305 2dd06aadcd feat(provenance): implement Global Default Storage pattern, CLI methods, and orchestrator config wiring
- Add _default_storage_path, set_default_storage_path(), and test-isolation context manager default_storage_path() in ProvenanceManager

- Accept config kwarg in ProvenanceManager.__init__ to fix CLI initialization bug

- Implement audit_log(), lineage(), export_prov(), and check() on ProvenanceManager matching cli.py expectations

- Wire provenance.storage_path in Semantica.__init__ before pipeline stages execute

- Add comprehensive unit tests in tests/provenance/test_manager.py for CLI methods and test isolation
2026-07-26 16:01:50 +05:30
Sameer6305 2a0bc7051a fix(security): switch to metadata.annotations for CKV_K8S_21 suppressions 2026-07-25 17:45:53 +05:30
Sameer6305 be2f8f8cd8 Implement global default storage pattern for ProvenanceManager 2026-07-24 23:27:58 +05:30
Sameer6305 a2f10dfbdd trigger CI re-run for failed runners 2026-07-24 23:16:10 +05:30
Sameer6305 495c2a2fbd fixes qodo reviews 2026-07-24 21:39:57 +05:30
Sameer6305 eb8156ddb3 Fix GraphWorkspace infinite render loop by tracking stringified open panel IDs 2026-07-24 21:19:54 +05:30
Sameer6305 1c3d2b949f Merge main to fix conflicts 2026-07-24 21:09:34 +05:30
Sameer6305 343d2bc418 Fix #769: Resolve all react-hooks/set-state-in-effect lint errors project-wide 2026-07-24 20:56:11 +05:30
Sameer6305 adb46134c4 fix(#768): remove componentDidUpdate auto-reset to avoid premature reset on Suspense fallback 2026-07-24 16:15:34 +05:30
Sameer6305 d2d38a0509 fix(#768): ensure ErrorBoundary retryCount only resets on recovery transition 2026-07-24 16:11:14 +05:30
Sameer6305 9a21e523f0 fix(#768): add ErrorBoundary to workspace Suspense blocks 2026-07-24 15:53:33 +05:30
Sameer6305 e7696f462a fixing qodo findings 2026-07-24 00:38:49 +05:30
Sameer6305 d6c7154fa9 Fix #767: Harden workspaces against silent error swallowing and 207 statuses
Ensures network errors, API failures, and 207 Partial Success statuses are surfaced correctly to the user instead of failing silently in the frontend UI.
2026-07-24 00:16:46 +05:30
Sameer6305 637bfe7314 Fix #788: pin httpx<0.28.0 globally to fix TestClient breakage
Adds an explicit httpx<0.28.0 constraint to [project.dependencies] so it
applies globally across all environments, not just dev. Without this,
different environments could resolve an incompatible transitive httpx
version and hit the same Starlette TestClient breakage independently.

Verified via git stash comparison: the unmodified baseline fails to even
collect the test suite (TestClient TypeError during collection), so this
pin doesn't just fix tests, it's what allows the full suite to run at all.

Closes #788
2026-07-23 16:36:58 +05:30
Sameer6305 9b7a33031c solving qodo review 2026-07-23 15:34:53 +05:30