From 79a980d9566d30d631b27f6b457f6b110d95a7fa Mon Sep 17 00:00:00 2001 From: KaifAhmad1 Date: Wed, 8 Apr 2026 22:24:09 +0530 Subject: [PATCH 1/9] Add Claude Skill support, plugin manifests, and plugin folder updates --- .claude/skills/semantica/SKILL.md | 57 ++ plugins/.claude-plugin/README.md | 33 + plugins/.claude-plugin/marketplace.json | 19 + plugins/.claude-plugin/plugin.json | 11 + plugins/.codex-plugin/marketplace.json | 9 + plugins/.codex-plugin/plugin.json | 11 + plugins/.cursor-plugin/marketplace.json | 9 + plugins/.cursor-plugin/plugin.json | 11 + plugins/agents/decision-advisor/AGENT.md | 126 +++ plugins/agents/explainability/AGENT.md | 129 +++ plugins/agents/kg-assistant/AGENT.md | 73 ++ plugins/hooks/hooks.json | 11 + plugins/skills/causal/SKILL.md | 53 ++ plugins/skills/change/SKILL.md | 38 + plugins/skills/decision/SKILL.md | 197 +++++ plugins/skills/deduplicate/SKILL.md | 37 + plugins/skills/embed/SKILL.md | 230 +++++ plugins/skills/explain/SKILL.md | 37 + plugins/skills/export/SKILL.md | 49 + plugins/skills/extract/SKILL.md | 93 ++ plugins/skills/ingest/SKILL.md | 37 + plugins/skills/ontology/SKILL.md | 37 + plugins/skills/policy/SKILL.md | 37 + plugins/skills/provenance/SKILL.md | 37 + plugins/skills/query/SKILL.md | 49 + plugins/skills/reason/SKILL.md | 201 +++++ plugins/skills/temporal/SKILL.md | 164 ++++ plugins/skills/validate/SKILL.md | 228 +++++ plugins/skills/visualize/SKILL.md | 249 ++++++ write_missing_skills.py | 1031 ++++++++++++++++++++++ 30 files changed, 3303 insertions(+) create mode 100644 .claude/skills/semantica/SKILL.md create mode 100644 plugins/.claude-plugin/README.md create mode 100644 plugins/.claude-plugin/marketplace.json create mode 100644 plugins/.claude-plugin/plugin.json create mode 100644 plugins/.codex-plugin/marketplace.json create mode 100644 plugins/.codex-plugin/plugin.json create mode 100644 plugins/.cursor-plugin/marketplace.json create mode 100644 plugins/.cursor-plugin/plugin.json create mode 100644 plugins/agents/decision-advisor/AGENT.md create mode 100644 plugins/agents/explainability/AGENT.md create mode 100644 plugins/agents/kg-assistant/AGENT.md create mode 100644 plugins/hooks/hooks.json create mode 100644 plugins/skills/causal/SKILL.md create mode 100644 plugins/skills/change/SKILL.md create mode 100644 plugins/skills/decision/SKILL.md create mode 100644 plugins/skills/deduplicate/SKILL.md create mode 100644 plugins/skills/embed/SKILL.md create mode 100644 plugins/skills/explain/SKILL.md create mode 100644 plugins/skills/export/SKILL.md create mode 100644 plugins/skills/extract/SKILL.md create mode 100644 plugins/skills/ingest/SKILL.md create mode 100644 plugins/skills/ontology/SKILL.md create mode 100644 plugins/skills/policy/SKILL.md create mode 100644 plugins/skills/provenance/SKILL.md create mode 100644 plugins/skills/query/SKILL.md create mode 100644 plugins/skills/reason/SKILL.md create mode 100644 plugins/skills/temporal/SKILL.md create mode 100644 plugins/skills/validate/SKILL.md create mode 100644 plugins/skills/visualize/SKILL.md create mode 100644 write_missing_skills.py diff --git a/.claude/skills/semantica/SKILL.md b/.claude/skills/semantica/SKILL.md new file mode 100644 index 00000000..1edcc618 --- /dev/null +++ b/.claude/skills/semantica/SKILL.md @@ -0,0 +1,57 @@ +--- +name: semantica +description: Semantica full-stack knowledge graph skill for context graphs, decision intelligence, explainability, extraction, reasoning, visualization, ontology, provenance, policy, and export workflows. +--- + +# Semantica + +This Skill helps Claude apply Semantica knowledge graph capabilities to context graph analysis, decision intelligence, explainability, semantic extraction, graph analytics, reasoning, provenance, ontology, policy, ingestion, deduplication, and export. + +## When to use this Skill + +- The user asks about knowledge graphs, entities, relations, triplets, or semantic extraction. +- A task requires context graph analysis, graph topology, centrality, communities, paths, or embeddings. +- The request involves decision intelligence, causal influence, decision graphs, or outcome analysis. +- The user asks for explainability, decision rationale, or transparency for graph results. +- The request involves reasoning: deductive, abductive, SPARQL, Datalog, or Rete rules. +- The user needs provenance, audit history, lineage tracking, or change tracing. +- The request is about ontology modeling, schema validation, or policy enforcement. +- Data must be ingested from files, databases, APIs, repositories, or MCP servers. +- There is a need to deduplicate entities, normalize graph data, or merge duplicate graph objects. +- The user wants to export graphs to JSON, RDF, Parquet, CSV, GraphML, or similar. + +## What this Skill contains + +- Semantic extraction guidance for NER, relation extraction, event detection, coreference resolution, and triplet generation. +- Context graph and graph analytics workflows for topology, centrality, community detection, path finding, embeddings, and decision insights. +- Decision intelligence support for causal reasoning, decision impact, decision graphs, and outcome analysis. +- Explainability guidance for decision rationale, graph reasoning, rule traces, and result transparency. +- Reasoning support for logic, hypotheses, SPARQL, Datalog, and rule-based inference. +- Provenance and audit guidance for tracing sources, recording changes, and verifying graph lineage. +- Ontology guidance for defining concepts, validating schemas, and modeling relationships. +- Policy checks for compliance evaluation and graph governance. +- Temporal analysis guidance for event timelines and graph evolution. +- Deduplication support for duplicate detection, fuzzy matching, and graph cleanup. +- Export workflows for sharing results in multiple structured formats. + +## Best prompt patterns + +Use clear task descriptions, and mention the desired output format when possible. + +- "Extract entities, relations, and events from this text and summarize the resulting graph." +- "Analyze this context graph and show the top 5 most influential nodes." +- "Generate a decision intelligence report with causal impact and explainability." +- "Run a provenance trace for node X and describe its history." +- "Validate the ontology for this graph and report any schema problems." +- "Ingest the data from this MCP server and merge it into the current graph." +- "Export the graph to JSON and GraphML with node and edge metadata." + +## How Claude should use this Skill + +1. Read the YAML metadata and identify whether the request matches Semantica graph, context graph, decision intelligence, or extraction tasks. +2. Load this Skill when the request mentions Semantica, knowledge graphs, context graphs, decision intelligence, explainability, reasoning, or provenance. +3. Use the instructions here to choose the right workflow and then read additional files or scripts only if needed. + +## Authoring note + +This Skill is purposely concise and focused on task selection. It is not intended to include every detail; Claude should use the filesystem-based model to load any extra reference files only when asked. diff --git a/plugins/.claude-plugin/README.md b/plugins/.claude-plugin/README.md new file mode 100644 index 00000000..50349b42 --- /dev/null +++ b/plugins/.claude-plugin/README.md @@ -0,0 +1,33 @@ +# Semantica Claude Plugin + +This folder contains the plugin metadata for the Semantica Claude/Cursor/Codex plugin. + +## Installation + +- In Claude Code or Cursor, install this plugin from the repository root where `plugins` lives. +- If your workspace root is the `plugins` folder, use: + +```bash +/plugin install ./ +``` + +- If this repo is published on GitHub and the plugin root is the `plugins` folder, add it as a marketplace: + +```bash +/plugin marketplace add /semantica +``` +``` + +## Supported platforms + +- Claude +- Cursor +- Codex + +## What is included + +- `skills/`: plugin skill definitions for graph, reasoning, extraction, validation, visualization, and more. +- `hooks/`: plugin hooks for post-edit and pre-tool usage. +- `agents/`: agent definitions for explainability and other workflows. +- `.claude-plugin/plugin.json`: plugin manifest and compatibility metadata. +- `.claude-plugin/marketplace.json`: marketplace registry file. diff --git a/plugins/.claude-plugin/marketplace.json b/plugins/.claude-plugin/marketplace.json new file mode 100644 index 00000000..ef9a8f84 --- /dev/null +++ b/plugins/.claude-plugin/marketplace.json @@ -0,0 +1,19 @@ +{ + "plugins": [ + { + "name": "semantica-claude", + "description": "Semantica plugin for Claude: knowledge graph skills, reasoning, extraction, and visualization.", + "path": "." + }, + { + "name": "semantica-cursor", + "description": "Semantica plugin for Cursor: knowledge graph skills and developer workflow integration.", + "path": "." + }, + { + "name": "semantica-codex", + "description": "Semantica plugin for Codex: knowledge graph commands, analytics, and export capabilities.", + "path": "." + } + ] +} diff --git a/plugins/.claude-plugin/plugin.json b/plugins/.claude-plugin/plugin.json new file mode 100644 index 00000000..ef21fdd0 --- /dev/null +++ b/plugins/.claude-plugin/plugin.json @@ -0,0 +1,11 @@ +{ + "name": "semantica", + "description": "Full-stack knowledge graph skills: semantic extraction, decision intelligence, context graphs, reasoning, explainability, ontology, provenance, deduplication, visualization, and multi-format export.", + "version": "0.1.0", + "author": {"name": "Semantica Contributors"}, + "homepage": "https://github.com/Hawksight-AI/semantica", + "repository": "https://github.com/Hawksight-AI/semantica", + "platforms": ["claude", "cursor", "codex"], + "keywords": ["semantica", "knowledge graph", "visualization", "reasoning", "extraction", "mcp"], + "license": "MIT" +} \ No newline at end of file diff --git a/plugins/.codex-plugin/marketplace.json b/plugins/.codex-plugin/marketplace.json new file mode 100644 index 00000000..f0a69270 --- /dev/null +++ b/plugins/.codex-plugin/marketplace.json @@ -0,0 +1,9 @@ +{ + "plugins": [ + { + "name": "semantica-codex", + "description": "Semantica plugin for Codex: knowledge graph commands and analytics.", + "path": "." + } + ] +} diff --git a/plugins/.codex-plugin/plugin.json b/plugins/.codex-plugin/plugin.json new file mode 100644 index 00000000..114e7a6c --- /dev/null +++ b/plugins/.codex-plugin/plugin.json @@ -0,0 +1,11 @@ +{ + "name": "semantica-codex", + "description": "Semantica plugin for Codex: knowledge graph commands, export capabilities, and reasoning workflows.", + "version": "0.1.0", + "author": {"name": "Semantica Contributors"}, + "homepage": "https://github.com/Hawksight-AI/semantica", + "repository": "https://github.com/Hawksight-AI/semantica", + "platforms": ["codex"], + "keywords": ["semantica", "knowledge graph", "codex", "visualization", "reasoning", "extraction", "mcp"], + "license": "MIT" +} diff --git a/plugins/.cursor-plugin/marketplace.json b/plugins/.cursor-plugin/marketplace.json new file mode 100644 index 00000000..1aea2180 --- /dev/null +++ b/plugins/.cursor-plugin/marketplace.json @@ -0,0 +1,9 @@ +{ + "plugins": [ + { + "name": "semantica-cursor", + "description": "Semantica plugin for Cursor: knowledge graph skills and analytics.", + "path": "." + } + ] +} diff --git a/plugins/.cursor-plugin/plugin.json b/plugins/.cursor-plugin/plugin.json new file mode 100644 index 00000000..00059e4b --- /dev/null +++ b/plugins/.cursor-plugin/plugin.json @@ -0,0 +1,11 @@ +{ + "name": "semantica-cursor", + "description": "Semantica plugin for Cursor: knowledge graph skills, reasoning, extraction, and visualization.", + "version": "0.1.0", + "author": {"name": "Semantica Contributors"}, + "homepage": "https://github.com/Hawksight-AI/semantica", + "repository": "https://github.com/Hawksight-AI/semantica", + "platforms": ["cursor"], + "keywords": ["semantica", "knowledge graph", "cursor", "visualization", "reasoning", "extraction", "mcp"], + "license": "MIT" +} diff --git a/plugins/agents/decision-advisor/AGENT.md b/plugins/agents/decision-advisor/AGENT.md new file mode 100644 index 00000000..12f46b0c --- /dev/null +++ b/plugins/agents/decision-advisor/AGENT.md @@ -0,0 +1,126 @@ +--- +name: decision-advisor +description: Decision intelligence and causal reasoning specialist for Semantica. Proactively surfaces causal chains, precedent matches, policy violations, and influence scores when reviewing or recording decisions. Use for decision recording, precedent search, causal analysis, policy governance, and decision explainability workflows. +--- + +You are a **Decision Intelligence Specialist** for the Semantica library. You focus on the full decision lifecycle: recording, querying, precedent search, causal analysis, policy compliance, and explainability. + +## Your Domain + +### Recording Decisions +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +decision_id = ctx.record_decision( + category="loan_approval", + scenario="First-time homebuyer, income 80k", + reasoning="Good credit score, low DTI ratio", + outcome="approved", + confidence=0.95, + entities=["customer_123", "property_456"], + decision_maker="underwriting_agent", + valid_from="2025-01-01", + valid_until="2026-01-01", +) +``` + +### Querying and Precedent Search +```python +# Natural language query with multi-hop reasoning +decisions = ctx.query_decisions(query, max_hops=3, use_hybrid_search=True) + +# Hybrid precedent search — semantic + structural + vector +precedents = ctx.find_precedents(scenario, category, limit=10, use_hybrid_search=True) + +# Advanced KG-enhanced search +advanced = ctx.find_precedents_advanced( + scenario, use_kg_features=True, + similarity_weights={"semantic": 0.5, "structural": 0.3, "vector": 0.2} +) + +# Category/entity/time filters via DecisionQuery +from semantica.context.decision_query import DecisionQuery +dq = DecisionQuery(graph_store=ctx.graph_store) +by_cat = dq.find_by_category(category, limit=100) +by_ent = dq.find_by_entity(entity_id, limit=100) +by_time = dq.find_by_time_range(start, end, limit=100) +multi_hop = dq.multi_hop_reasoning(start_entity, query_context, max_hops=3) +``` + +### Causal Analysis +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer + +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) + +# Upstream (what caused this?) or downstream (what did this cause?) +chain = analyzer.get_causal_chain(decision_id, direction="upstream", max_depth=10) + +# Root causes +roots = analyzer.find_root_causes(decision_id) + +# Downstream impact +influenced = analyzer.get_influenced_decisions(decision_id) +score = analyzer.get_causal_impact_score(decision_id) + +# Full network analysis +network = analyzer.analyze_causal_network() +loops = analyzer.find_causal_loops() + +# Historical chain at a specific time +historical = analyzer.trace_at_time(decision_id, at_time="2024-06-01", direction="upstream") +``` + +### Policy Compliance +```python +from semantica.context import AgentContext + +engine = ctx.get_policy_engine() + +# Check compliance +compliant = engine.check_compliance(decision, policy_id) + +# Get all applicable policies +applicable = engine.get_applicable_policies(category, entities) + +# Analyze impact of policy changes +impact = engine.analyze_policy_impact(policy_id, proposed_rules) + +# Record exceptions +exception_id = engine.record_exception(decision_id, policy_id, reason, approver, justification) +``` + +### Explainability +```python +# Full explainability trace +explainability = ctx.trace_decision_explainability(decision_id) + +# Influence analysis with KG algorithms +influence = ctx.analyze_decision_influence(decision_id, max_depth=3) +predictions = ctx.predict_decision_relationships(decision_id, top_k=5) +``` + +## Critical Invariants + +- **Node type duality**: `record_decision()` → `"decision"` (lowercase); `add_decision()` → `"Decision"` (capitalized). Always search for both when querying. +- **No `DecisionQuery.query()`** — use `find_by_entity`, `find_by_category`, `find_by_time_range`, or `multi_hop_reasoning`. +- **`CausalChainAnalyzer` takes `graph_store=`** — no `trace_causes()`, use `get_causal_chain(direction="upstream")`. +- **`find_precedents(as_of=)`** — supports temporal precedent search. +- **`graph_store` format** — both `DecisionQuery` and `CausalChainAnalyzer` need `{"records": [...]}` shape. + +## Behavior + +When a user shares a decision or asks about decision-making, **proactively**: +1. **Trace root causes** via `get_causal_chain(direction="upstream")` +2. **Check policy compliance** via `get_applicable_policies()` + `check_compliance()` +3. **Find precedents** via `find_precedents_advanced(use_kg_features=True)` +4. **Score influence** via `get_causal_impact_score()` +5. **Detect loops** — flag if this decision closes a causal loop + +When reviewing Semantica decision code: +- Check method names against the list above +- Flag queries that only check one of `"decision"` / `"Decision"` +- Flag missing `entities=[]` arg (defaults to None, may miss entity-based precedent search) + +Show causal chains as Mermaid `graph TD` blocks. Keep tables concise. Lead with decision status and compliance, then causal context, then influence score. diff --git a/plugins/agents/explainability/AGENT.md b/plugins/agents/explainability/AGENT.md new file mode 100644 index 00000000..5360ad10 --- /dev/null +++ b/plugins/agents/explainability/AGENT.md @@ -0,0 +1,129 @@ +--- +name: explainability +description: Reasoning transparency and auditability specialist for Semantica. Answers "why does the graph believe X?", "how was Y inferred?", and "is this decision explainable?" with full evidence chains. Produces audit-ready explanation reports using ExplanationGenerator, AgentContext.trace_decision_explainability, and ContextGraph.trace_decision_chain. +--- + +You are a **Reasoning Transparency and Explainability Specialist** for the Semantica library. You answer "why?" questions about graph facts, inferences, and decisions with complete, auditable evidence chains. + +## Your Domain + +### Explanation Generation +```python +from semantica.reasoning.explanation_generator import ExplanationGenerator + +gen = ExplanationGenerator() + +# generate_explanation(reasoning) → Explanation object +# reasoning can be any reasoning object, dict, or string context +explanation = gen.generate_explanation(reasoning=reasoning_input) +# explanation.summary, .confidence, .evidence + +# show_reasoning_path(reasoning) → ReasoningPath object +path = gen.show_reasoning_path(reasoning=reasoning_input) +# path.steps: [Step(type, description, confidence)] +# path.conclusion + +# justify_conclusion(conclusion, reasoning_path) → Justification object +justification = gen.justify_conclusion( + conclusion=conclusion, + reasoning_path=path, +) +# justification.is_justified, .confidence, .supporting_steps, .opposing_factors +``` + +### Decision Explainability +```python +from semantica.context import AgentContext, ContextGraph + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) + +# Full decision explainability trace +explainability = ctx.trace_decision_explainability(decision_id) +# Returns: reasoning_steps, evidence, causal_context, compliance_status + +# Causal chain from ContextGraph +graph = ContextGraph(advanced_analytics=True) +chain = graph.trace_decision_chain(decision_id, max_steps=5) +causality = graph.trace_decision_causality(decision_id, max_depth=5) + +# Influence analysis +influence = ctx.analyze_decision_influence(decision_id, max_depth=3) +``` + +### Provenance Tracing +```python +from semantica.kg.kg_provenance import GraphBuilderWithProvenance +from semantica.context.context_provenance import ContextManagerWithProvenance +from semantica.reasoning.reasoning_provenance import ReasoningEngineWithProvenance +from semantica.semantic_extract.semantic_extract_provenance import ( + NERExtractorWithProvenance, + RelationExtractorWithProvenance, + EventDetectorWithProvenance, +) +``` + +Each provenance-enabled class wraps the base class and adds `.get_provenance_summary()` to retrieve lineage records. + +### Reasoning Chains +```python +from semantica.reasoning.deductive_reasoner import DeductiveReasoner + +reasoner = DeductiveReasoner() +proof = reasoner.prove_theorem(theorem) +# proof.steps, proof.is_valid, proof.confidence + +validation = reasoner.validate_argument(argument) +``` + +## Explanation Types You Produce + +**1. Decision explanations** — full trace: reasoning steps → causal antecedents → policy compliance → evidence +**2. Reasoning path explanations** — step-by-step rule chain with variable bindings +**3. Conclusion justifications** — why a conclusion follows from premises, with opposing factors noted +**4. Path explanations** — how two nodes are semantically connected via the graph +**5. Compliance explanations** — which rules passed/failed and why, with remediation advice + +## Audit Report Format + +When asked for an audit report: +``` +Explainability Audit Report +════════════════════════════ +Generated: +Scope: + +── Decision Explanations ───────────────── +Decision : EXPLAINED ✓ (confidence: 0.91) + Steps: 3 | Evidence: 2 items | Provenance: complete + Causal antecedents: + Policy compliance: 2/2 ✓ + +Decision : PARTIALLY EXPLAINED ⚠ + Missing: provenance gap on reasoning step 2 + Low confidence: 0.43 on step 3 + +── Summary ────────────────────────────── +Total: N decisions analyzed +Fully explained: M (X%) +Partially explained: K (Y%) +Unexplained (gaps): J (Z%) + +Provenance gaps: J nodes missing lineage +Low-confidence facts (<0.7): L +Circular reasoning detected: YES / NO +``` + +## Behavior + +When asked "why does the graph believe X?": +1. Start with `ExplanationGenerator.generate_explanation()` for the natural-language summary +2. Supplement with `show_reasoning_path()` for the step trace +3. Cross-check with provenance wrappers for source lineage +4. Flag any provenance gaps + +When a decision explanation is requested: +1. Always call `ctx.trace_decision_explainability(decision_id)` first +2. Then supplement with `trace_decision_chain()` and `trace_decision_causality()` +3. Check policy compliance via `get_applicable_policies()` + `check_compliance()` + +Lead with the direct answer, then the evidence chain. Use Mermaid `sequenceDiagram` for multi-step reasoning chains. Use nested bullets for evidence items. diff --git a/plugins/agents/kg-assistant/AGENT.md b/plugins/agents/kg-assistant/AGENT.md new file mode 100644 index 00000000..26fb5428 --- /dev/null +++ b/plugins/agents/kg-assistant/AGENT.md @@ -0,0 +1,73 @@ +--- +name: kg-assistant +description: General-purpose KG-aware assistant for any Semantica task. Knows all module APIs, exact method signatures, node-type conventions, and current graph schema. Use for broad questions, multi-module workflows, code review, or any task spanning multiple Semantica modules. +--- + +You are a knowledge graph expert assistant for the **Semantica** library — a full-stack Python library for knowledge graphs, semantic extraction, decision intelligence, reasoning, and context management. + +## Module Overview + +### Decision Intelligence (semantica.context) +- `AgentContext` — high-level interface: `store()`, `retrieve()`, `record_decision()`, `query_decisions()`, `find_precedents()`, `find_precedents_advanced()`, `analyze_decision_influence()`, `predict_decision_relationships()`, `trace_decision_explainability()`, `get_context_insights()`, `multi_hop_context_query()`, `expand_query()`, `query_with_reasoning()`, `get_causal_chain()`, `capture_cross_system_inputs()`, `get_policy_engine()` +- `ContextGraph` — in-memory graph: `add_node()`, `add_edge()`, `record_decision()`, `find_precedents_by_scenario()`, `find_similar_decisions()`, `analyze_decision_influence()`, `analyze_decision_impact()`, `get_causal_chain()`, `trace_decision_causality()`, `trace_decision_chain()`, `enforce_decision_policy()`, `check_decision_rules()`, `get_decision_insights()`, `get_decision_summary()`, `analyze_graph_with_kg()`, `get_node_centrality()`, `get_node_importance()`, `state_at()`, `query()` +- `DecisionQuery` — `find_by_category()`, `find_by_entity()`, `find_by_time_range()`, `find_precedents_hybrid()`, `find_similar_exceptions()`, `multi_hop_reasoning()`, `predict_decision_relationships()`, `analyze_decision_influence()`, `trace_decision_path()` +- `CausalChainAnalyzer` — `get_causal_chain(decision_id, direction, max_depth)`, `find_root_causes()`, `get_influenced_decisions()`, `get_causal_impact_score()`, `get_precedent_chain()`, `analyze_causal_network()`, `find_causal_loops()`, `trace_at_time(event_id, at_time, direction, max_depth)` +- `PolicyEngine` — `add_policy()`, `check_compliance()`, `get_applicable_policies()`, `update_policy()`, `record_exception()`, `analyze_policy_impact()`, `get_affected_decisions()`, `get_policy_history()` +- `DecisionRecorder` — `record_decision()`, `link_entities()`, `link_precedents()`, `apply_policies()`, `record_exception()`, `capture_cross_system_context()`, `record_approval_chain()` + +### Knowledge Graph (semantica.kg) +- `GraphAnalyzer` — `analyze_graph()`, `calculate_centrality(graph, centrality_type)`, `detect_communities(graph, algorithm)`, `analyze_temporal_evolution()`, `compute_metrics()`, `analyze_connectivity()` +- `CentralityCalculator` — `calculate_degree_centrality()`, `calculate_betweenness_centrality()`, `calculate_closeness_centrality()`, `calculate_eigenvector_centrality()`, `calculate_pagerank()`, `calculate_all_centrality()` +- `CommunityDetector` — `detect_communities()`, `detect_communities_louvain()`, `detect_communities_leiden()`, `detect_communities_label_propagation()`, `detect_overlapping_communities()`, `analyze_community_structure()`, `calculate_community_metrics()` +- `NodeEmbedder` — `compute_embeddings(graph_store, node_labels, relationship_types)`, `find_similar_nodes(graph_store, node_id, top_k)`, `store_embeddings()` +- `SimilarityCalculator` — `cosine_similarity(vector1, vector2)`, `euclidean_distance()`, `manhattan_distance()`, `correlation_similarity()`, `find_most_similar()`, `batch_similarity()`, `pairwise_similarity()` +- `LinkPredictor` — `score_link(graph_store, node_id1, node_id2, method=)`, `predict_top_links()`, `predict_links()`, `batch_score_links()` +- `PathFinder` — `find_k_shortest_paths()`, `dijkstra_shortest_path()`, `bfs_shortest_path()`, `a_star_search()`, `all_shortest_paths()`, `path_length()` + +### Reasoning (semantica.reasoning) +- `DeductiveReasoner` — `add_facts()`, `apply_logic(premises)`, `prove_theorem()`, `validate_argument()` +- `AbductiveReasoner` — `add_knowledge()`, `generate_hypotheses(observations)`, `find_explanations()`, `get_best_explanation()`, `rank_hypotheses()` +- `ExplanationGenerator` — `generate_explanation(reasoning)`, `show_reasoning_path(reasoning)`, `justify_conclusion(conclusion, reasoning_path)` + +### Extraction (semantica.semantic_extract) +- `NamedEntityRecognizer`, `RelationExtractor`, `EventDetector`, `CoreferenceResolver`, `TripletExtractor`, `ExtractionValidator` +- **Always** call `_result_cache.clear()` before any extraction run + +### Pipeline (semantica.pipeline) +- `PipelineBuilder` — `add_step()`, `connect_steps()`, `validate_pipeline()`, `build()` +- `PipelineValidator` — `validate(pipeline)` → `ValidationResult(valid, errors, warnings)` — **does NOT raise** +- `FailureHandler` — `handle_failure(error, policy, retry_count)` → `RecoveryAction` + +### Export (semantica.export) +- `RDFExporter.export_to_rdf(data, format='turtle')` → **returns a string**, no `output_path` +- Format aliases: `"ttl"` → `"turtle"`, `"nt"`, `"xml"`, `"json-ld"` +- Other exporters: `OWLExporter`, `CSVExporter`, `JSONExporter`, `ParquetExporter`, `ArrowExporter`, `VectorExporter`, `YAMLSchemaExporter`, `ArangoAQLExporter`, `LPGExporter`, `ReportGenerator` + +### Deduplication (semantica.deduplication) +- `DuplicateDetector.detect_duplicates(entities, threshold=)` — use **directly**, never via `methods.py` (infinite recursion bug) + +## Critical API Invariants + +| Area | Correct | +|------|---------| +| Decision node type | `record_decision()` → stored as `"decision"` (lowercase); `add_decision()` → `"Decision"` (capitalized). Query both. | +| `AgentContext.record_decision` | Returns a `decision_id: str`. Args: `category, scenario, reasoning, outcome, confidence, entities, decision_maker, valid_from, valid_until` | +| `CausalChainAnalyzer` | Takes `graph_store=` kwarg. No `trace_causes()` — use `get_causal_chain(direction="upstream")` | +| `ExplanationGenerator` | No `explain_decision/fact/inference` — use `generate_explanation(reasoning)`, `show_reasoning_path(reasoning)`, `justify_conclusion(conclusion, path)` | +| `DecisionQuery` | No `.query()` — use `find_by_entity`, `find_by_category`, `find_by_time_range`, `multi_hop_reasoning` | +| `SimilarityCalculator` | `cosine_similarity(vector1, vector2)` — two required positional args | +| `NodeEmbedder` | `compute_embeddings(graph_store, node_labels, relationship_types)` — all three positional, all required | +| `LinkPredictor` | `score_link(graph_store, node_id1, node_id2, method=)` | +| `PipelineValidator` | `validate(pipeline)` returns `ValidationResult` — never raises | +| `RDFExporter` | `export_to_rdf(data, format='turtle')` returns a string | +| Cache | `_result_cache.clear()` before every extraction | +| Graph store format | `DecisionQuery` and `CausalChainAnalyzer` need `{"records": [...]}` from graph store | + +## How to Help + +1. **Answer questions** with copy-paste-ready code that uses the correct method names +2. **Review Semantica code** — check against the invariants table above before suggesting anything +3. **Suggest the right skill** — map user intent to `/semantica:*` skills +4. **Debug errors** — common mistakes: wrong method name, wrong arg order, missing `_result_cache.clear()`, querying only one of `"decision"`/`"Decision"` types + +Keep responses code-first. Show the full import path in every example. diff --git a/plugins/hooks/hooks.json b/plugins/hooks/hooks.json new file mode 100644 index 00000000..80393528 --- /dev/null +++ b/plugins/hooks/hooks.json @@ -0,0 +1,11 @@ +{ + "hooks": { + "PostToolUse": [ + {"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "FILE=$(jq -r .tool_input.file_path 2>/dev/null); if echo $FILE | grep -qE semantica/; then python -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" $FILE 2>&1; fi"}]}, + {"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "echo PostToolUse provenance check"}]} + ], + "PreToolUse": [ + {"matcher": "Bash", "hooks": [{"type": "command", "command": "CMD=$(jq -r .tool_input.command 2>/dev/null); if echo $CMD | grep -q deduplication/methods; then echo WARNING: use DuplicateDetector directly >&2; fi"}]} + ] + } +} \ No newline at end of file diff --git a/plugins/skills/causal/SKILL.md b/plugins/skills/causal/SKILL.md new file mode 100644 index 00000000..18e47f2a --- /dev/null +++ b/plugins/skills/causal/SKILL.md @@ -0,0 +1,53 @@ +--- +name: causal +description: Analyze cause-and-effect relationships in the Semantica knowledge graph — causal chains, interventions, counterfactuals, and causal influence scores. +--- + +# /semantica:causal + +Analyze causal relationships and infer impacts. Usage: `/semantica:causal [args]` + +`$ARGUMENTS` = task + optional target entity, filter, or intervention. + +--- + +## `chain [--subject ] [--depth N]` + +Build and inspect causal chains for a subject or category. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import ContextGraph + +graph = ContextGraph(advanced_analytics=True) +analyzer = CausalChainAnalyzer(graph=graph) + +chain = analyzer.build_causal_chain(subject=subject, depth=depth) +metrics = analyzer.compute_causal_metrics(chain) +``` + +Output: chain steps, cause strength, effect reach, and summary graph. + +--- + +## `intervene [--scenario ]` + +Simulate an intervention on a node and measure downstream effects. + +```python +result = analyzer.simulate_intervention(node=node, action=action, scenario=scenario) +``` + +Return: effect magnitudes, changed outcomes, and intervention recommendations. + +--- + +## `counterfactual [--weight N]` + +Generate counterfactual explanations and alternate outcomes. + +```python +counterfactuals = analyzer.generate_counterfactuals(fact=fact) +``` + +Output: alternate causal paths, likelihood change, and decision impact. diff --git a/plugins/skills/change/SKILL.md b/plugins/skills/change/SKILL.md new file mode 100644 index 00000000..8791654f --- /dev/null +++ b/plugins/skills/change/SKILL.md @@ -0,0 +1,38 @@ +--- +name: change +description: Track and inspect graph changes, diffs, temporal updates, and the impact of new data on Semantica knowledge graphs. +--- + +# /semantica:change + +Inspect changes over time and evaluate updates. Usage: `/semantica:change [args]` + +`$ARGUMENTS` = task + optional node, time window, or filter. + +--- + +## `diff [--from ] [--to ] [--node ]` + +Compute graph diffs between two snapshots. + +```python +from semantica.provenance.change_tracker import ChangeTracker +from semantica.context import ContextGraph + +tracker = ChangeTracker() +diff = tracker.compute_diff(from_ts=from_ts, to_ts=to_ts, node_id=node_id) +``` + +Output: added/removed nodes and edges, attribute changes, and impact summary. + +--- + +## `history [--limit N]` + +Show the change history for a node or relationship. + +```python +history = tracker.get_node_history(node_id=node_id, limit=limit) +``` + +Return: revisions, timestamps, authors, and summary comments. diff --git a/plugins/skills/decision/SKILL.md b/plugins/skills/decision/SKILL.md new file mode 100644 index 00000000..58e934b3 --- /dev/null +++ b/plugins/skills/decision/SKILL.md @@ -0,0 +1,197 @@ +--- +name: decision +description: Full decision lifecycle in Semantica record, query, find precedents (hybrid/advanced), analyze influence, explain, insights dashboard, list, and record exceptions. Uses AgentContext, ContextGraph, DecisionQuery, CausalChainAnalyzer, DecisionRecorder. +--- + +# /semantica:decision + +Full decision lifecycle management. Usage: `/semantica:decision [args]` + +--- + +## `record "" "" ` + +Record a decision with full context. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +decision_id = ctx.record_decision( + category=category, # "loan_approval", "deployment", "hiring" + scenario=scenario, # natural-language situation description + reasoning=reasoning, # why this decision was made + outcome=outcome, # "approved", "rejected", "deferred" + confidence=float(confidence), + entities=entities or [], + decision_maker="ai_agent", + valid_from=valid_from, # optional ISO date string + valid_until=valid_until, +) +``` + +Output: `Decision recorded | | (conf: 0.95)` + +--- + +## `query "" [--hops N] [--hybrid]` + +Query decisions using natural language with multi-hop graph traversal. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +results = ctx.query_decisions( + query=question, + max_hops=int(hops) if hops else 3, + include_context=True, + use_hybrid_search="--hybrid" in args, +) +``` + +For structured lookups use `DecisionQuery`: +```python +from semantica.context.decision_query import DecisionQuery +dq = DecisionQuery(graph_store=ctx.graph_store) +# dq.find_by_category(category, limit=100) +# dq.find_by_entity(entity_id, limit=100) +# dq.find_by_time_range(start, end, limit=100) +# dq.multi_hop_reasoning(start_entity, query_context, max_hops=3) +# dq.trace_decision_path(decision_id, relationship_types) +# dq.analyze_decision_influence(decision_id, max_depth=3) +``` + +Return: `| ID | Category | Scenario | Outcome | Confidence | Timestamp |` + +--- + +## `precedents "" [--category ] [--advanced] [--hops N] [--as-of ]` + +Find similar past decisions using hybrid semantic + structural + vector search. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, kg_algorithms=True, vector_store_features=True) + +if "--advanced" in args: + precedents = ctx.find_precedents_advanced( + scenario=scenario, category=category, limit=10, + use_kg_features=True, + similarity_weights={"semantic": 0.5, "structural": 0.3, "vector": 0.2}, + ) +else: + precedents = ctx.find_precedents( + scenario=scenario, category=category, limit=10, + use_hybrid_search=True, + max_hops=int(hops) if hops else 3, + include_context=True, + include_superseded=False, + as_of=as_of_date or None, # temporal filter: only precedents that existed as_of this date + ) +``` + +Return ranked: `| Rank | ID | Scenario | Outcome | Confidence | Similarity | Date |` + +--- + +## `influence [--depth N]` + +Analyze how a decision influences others across the graph. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True, kg_algorithms=True) +influence = ctx.analyze_decision_influence(decision_id, max_depth=int(depth) if depth else 3) +predictions = ctx.predict_decision_relationships(decision_id, top_k=5) +``` + +Output: Influence score + influenced decisions table + predicted new relationships. + +--- + +## `explain ` + +Full explainability trace reasoning steps, causal antecedents, policy compliance. + +```python +from semantica.context import AgentContext, ContextGraph + +ctx = AgentContext(decision_tracking=True) +explainability = ctx.trace_decision_explainability(decision_id) + +graph = ContextGraph(advanced_analytics=True) +chain = graph.trace_decision_chain(decision_id, max_steps=5) +causality = graph.trace_decision_causality(decision_id, max_depth=5) +``` + +Output: Reasoning steps, causal antecedents, evidence items, policy compliance status. + +--- + +## `insights` + +Comprehensive analytics across all tracked decisions. + +```python +from semantica.context import ContextGraph, AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +graph = ContextGraph(advanced_analytics=True) + +insights = graph.get_decision_insights() +summary = graph.get_decision_summary() +context_insights = ctx.get_context_insights() +``` + +Output: Total count, category breakdown, outcome distribution, avg confidence, top influential. + +--- + +## `list [--category ] [--entity ] [--from ] [--to ]` + +```python +from semantica.context.decision_query import DecisionQuery +from semantica.context import AgentContext +from datetime import datetime + +ctx = AgentContext(decision_tracking=True) +dq = DecisionQuery(graph_store=ctx.graph_store) + +if category: decisions = dq.find_by_category(category, limit=100) +elif entity: decisions = dq.find_by_entity(entity, limit=100) +elif from_date: decisions = dq.find_by_time_range( + start=datetime.fromisoformat(from_date), + end=datetime.fromisoformat(to_date or "2099-12-31"), + ) +``` + +Return: `| ID | Category | Scenario | Outcome | Confidence | Maker | Timestamp |` + +--- + +## `exception "" --approver ` + +Record a formal policy exception. + +```python +from semantica.context.decision_recorder import DecisionRecorder +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +recorder = DecisionRecorder(graph_store=ctx.graph_store) + +exception_id = recorder.record_exception( + decision_id=decision_id, policy_id=policy_id, + reason=reason, approver=approver, + approval_method="manual_override", justification=reason, +) + +from semantica.context.decision_query import DecisionQuery +dq = DecisionQuery(graph_store=ctx.graph_store) +similar = dq.find_similar_exceptions(exception_reason=reason, limit=5) +``` + +Output: `Exception recorded: ` + similar past exceptions for audit context. diff --git a/plugins/skills/deduplicate/SKILL.md b/plugins/skills/deduplicate/SKILL.md new file mode 100644 index 00000000..7ce2abf7 --- /dev/null +++ b/plugins/skills/deduplicate/SKILL.md @@ -0,0 +1,37 @@ +--- +name: deduplicate +description: Identify and merge duplicate entities, relations, and graph objects in Semantica using fuzzy matching, schema heuristics, and graph similarity. +--- + +# /semantica:deduplicate + +Remove duplicates from the knowledge graph. Usage: `/semantica:deduplicate [args]` + +`$ARGUMENTS` = deduplication strategy + optional entity or threshold. + +--- + +## `entities [--threshold ] [--field ]` + +Find and merge duplicate entities. + +```python +from semantica.deduplication import DuplicateDetector + +finder = DuplicateDetector() +merged = finder.merge_duplicates(entity_type=entity_type, threshold=threshold) +``` + +Output: merged entity IDs, discarded duplicates, and merge confidence. + +--- + +## `relations [--similarity ]` + +Detect duplicate relationships and normalize edges. + +```python +relations = finder.find_duplicate_relations(similarity=similarity) +``` + +Result: relation clusters, normalized relation set, and cleanup summary. diff --git a/plugins/skills/embed/SKILL.md b/plugins/skills/embed/SKILL.md new file mode 100644 index 00000000..36b683da --- /dev/null +++ b/plugins/skills/embed/SKILL.md @@ -0,0 +1,230 @@ +--- +name: embed +description: Generate, inspect, and use node/text embeddings in Semantica — compute Node2Vec embeddings, find similar nodes, score link predictions, batch similarity, and pairwise similarity. Uses NodeEmbedder, SimilarityCalculator, LinkPredictor, and AgentContext. Sub-commands: compute, similar, similarity, predict-link, top-links, batch, pairwise. +--- + +# /semantica:embed + +Generate and inspect graph embeddings. Usage: `/semantica:embed [args]` + +`$ARGUMENTS` = sub-command + arguments. + +--- + +## `compute [--labels ] [--rels ] [--dim N] [--walks N]` + +Generate Node2Vec embeddings for graph nodes. + +```python +from semantica.kg.node_embeddings import NodeEmbedder +from semantica.context import ContextGraph + +graph = ContextGraph() +embedder = NodeEmbedder() + +node_labels = labels_arg.split(",") if labels_arg else graph.get_all_node_types() +rel_types = rels_arg.split(",") if rels_arg else [] + +# All positional args required: graph_store, node_labels, relationship_types +embeddings = embedder.compute_embeddings( + graph_store=graph, + node_labels=node_labels, + relationship_types=rel_types, + embedding_dimension=int(dim_arg) if dim_arg else None, + num_walks=int(walks_arg) if walks_arg else None, +) + +# Store embeddings back on nodes +embedder.store_embeddings( + graph_store=graph, + embeddings=embeddings, + property_name="node2vec_embedding", +) +``` + +Output: +``` +Embeddings computed and stored. + Nodes embedded: N + Embedding dim: 128 + Node types covered: [type1, type2, ...] + +Sample (first 5 nodes): + | Node | Type | Embedding dim | Stored | +``` + +--- + +## `similar [--top N]` + +Find the most similar nodes to a given node in embedding space. + +```python +from semantica.kg.node_embeddings import NodeEmbedder +from semantica.context import ContextGraph, AgentContext + +graph = ContextGraph() +embedder = NodeEmbedder() + +# NodeEmbedder.find_similar_nodes uses the stored node2vec_embedding property +neighbors = embedder.find_similar_nodes( + graph_store=graph, + node_id=node_id, + top_k=int(top_n) if top_n else 10, + embedding_property="node2vec_embedding", +) + +# Also use AgentContext for richer similarity with metadata +ctx = AgentContext(kg_algorithms=True) +entity_similar = ctx.find_similar_entities( + entity_id=node_id, + similarity_type="content", # or "structural", "hybrid" + top_k=int(top_n) if top_n else 10, +) +``` + +Return: `| Rank | Node ID | Type | Cosine Similarity | Shared Properties |` + +--- + +## `similarity [--method cosine|euclidean|manhattan|correlation]` + +Compute pairwise similarity between two nodes. + +```python +from semantica.kg.similarity_calculator import SimilarityCalculator +from semantica.kg.node_embeddings import NodeEmbedder +from semantica.context import ContextGraph + +graph = ContextGraph() +embedder = NodeEmbedder() +calc = SimilarityCalculator() + +# Get embeddings for both nodes +v1 = embedder.find_similar_nodes(graph, n1, top_k=1) # placeholder — use stored embedding +v2 = embedder.find_similar_nodes(graph, n2, top_k=1) + +method = method_arg or "cosine" +if method == "cosine": + score = calc.cosine_similarity(vector1=v1, vector2=v2) +elif method == "euclidean": + score = calc.euclidean_distance(v1, v2) +elif method == "manhattan": + score = calc.manhattan_distance(v1, v2) +elif method == "correlation": + score = calc.correlation_similarity(v1, v2) +``` + +Output: +``` +Similarity: "" ↔ "" + Method: cosine + Score: 0.847 + + Interpretation: HIGH similarity (>0.8) + Shared neighbors: K + Common node types: [types] +``` + +--- + +## `predict-link [--method cosine|jaccard|adamic-adar|common-neighbors]` + +Score the likelihood of a relationship between two nodes. + +```python +from semantica.kg.link_predictor import LinkPredictor +from semantica.context import ContextGraph + +graph = ContextGraph() +predictor = LinkPredictor() + +# score_link(graph_store, node_id1, node_id2, method=) +score = predictor.score_link( + graph_store=graph, + node_id1=n1, + node_id2=n2, + method=method_arg or None, +) +``` + +Output: +``` +Link Prediction: "" → "" + Method: cosine + Score: 0.723 (threshold: 0.5 → LIKELY) + + Recommendation: This link is LIKELY to be meaningful. +``` + +--- + +## `top-links [--top N] [--method ]` + +Find the top-N most likely new connections for a node. + +```python +from semantica.kg.link_predictor import LinkPredictor +from semantica.context import ContextGraph + +graph = ContextGraph() +predictor = LinkPredictor() + +top = predictor.predict_top_links( + graph_store=graph, + node_id=node_id, + top_k=int(top_n) if top_n else 10, + method=method_arg or None, +) +``` + +Return: `| Rank | Target Node | Type | Score | Existing Link? |` + +--- + +## `batch [--against ] [--top N]` + +Score similarity between a query node and a set of target nodes (or all nodes). + +```python +from semantica.kg.similarity_calculator import SimilarityCalculator +from semantica.kg.node_embeddings import NodeEmbedder +from semantica.context import ContextGraph + +graph = ContextGraph() +embedder = NodeEmbedder() +calc = SimilarityCalculator() + +# Get query embedding and all target embeddings +query_vec = ... # from stored node2vec_embedding +target_embeddings = {n: embedder.get_embedding(n) for n in targets} + +scores = calc.batch_similarity( + embeddings=target_embeddings, + query_embedding=query_vec, + top_k=int(top_n) if top_n else 20, +) +``` + +Return: `| Node | Type | Score |` sorted descending. + +--- + +## `pairwise [--labels ] [--method cosine|euclidean]` + +Compute all pairwise similarities among a set of nodes. + +```python +from semantica.kg.similarity_calculator import SimilarityCalculator + +calc = SimilarityCalculator() + +pairwise = calc.pairwise_similarity( + embeddings=embeddings_dict, + method=method_arg or None, +) +``` + +Show as a heatmap summary — top-5 most similar pairs and bottom-5 most dissimilar pairs. Full matrix on request. + +Also use `AgentContext.predict_decision_relationships(decision_id, top_k)` when working within decision graphs for relationship prediction enriched with KG algorithms. diff --git a/plugins/skills/explain/SKILL.md b/plugins/skills/explain/SKILL.md new file mode 100644 index 00000000..78e97dd9 --- /dev/null +++ b/plugins/skills/explain/SKILL.md @@ -0,0 +1,37 @@ +--- +name: explain +description: Explain Semantica reasoning, decision logic, and graph results with traceability, causal context, and human-readable rationale. +--- + +# /semantica:explain + +Produce explanations for decisions, rules, and graph analytics. Usage: `/semantica:explain [args]` + +`$ARGUMENTS` = explanation target + optional detail level. + +--- + +## `decision [--detail ]` + +Explain why a decision was reached. + +```python +from semantica.explain import Explainer + +explainer = Explainer() +explanation = explainer.explain_decision(decision_id=decision_id, detail=detail) +``` + +Output: decision factors, rule traces, confidence, and suggested next steps. + +--- + +## `graph [--path N]` + +Explain graph relationships and why a node is connected. + +```python +explanation = explainer.explain_graph_connection(node_id=node_id, depth=depth) +``` + +Return: cause/effect chains, supporting evidence, and relevant metadata. diff --git a/plugins/skills/export/SKILL.md b/plugins/skills/export/SKILL.md new file mode 100644 index 00000000..8fbe27d6 --- /dev/null +++ b/plugins/skills/export/SKILL.md @@ -0,0 +1,49 @@ +--- +name: export +description: Export Semantica graphs, results, and provenance to JSON, RDF, Parquet, CSV, GraphML, and other formats. +--- + +# /semantica:export + +Export knowledge graph data. Usage: `/semantica:export [args]` + +`$ARGUMENTS` = format + optional target or destination. + +--- + +## `json [--output ] [--filter ]` + +Export graph data as JSON. + +```python +from semantica.export import GraphExporter + +exporter = GraphExporter() +exporter.export_json(output_path=output, filter_query=filter_query) +``` + +Output: JSON file or inline JSON payload. + +--- + +## `rdf [--format turtle|xml|ntriples] [--output ]` + +Export the graph in RDF serialization. + +```python +exporter.export_rdf(format='turtle', output_path=output) +``` + +Return: RDF text or file path. + +--- + +## `parquet [--output ]` + +Export nodes and edges to Parquet for analytics. + +```python +exporter.export_parquet(output_path=output) +``` + +Output: Parquet dataset ready for downstream processing. diff --git a/plugins/skills/extract/SKILL.md b/plugins/skills/extract/SKILL.md new file mode 100644 index 00000000..07864fd5 --- /dev/null +++ b/plugins/skills/extract/SKILL.md @@ -0,0 +1,93 @@ +--- +name: extract +description: Run the full Semantica semantic extraction pipeline on a file or selected text — NER, relations, events, coreference resolution, triplets, and validation. Clears result cache before each run. Returns Markdown tables with entity/relation/event/triplet results and inline validator warnings. +--- + +# /semantica:extract + +Run the full extraction pipeline. Usage: `/semantica:extract [file_path | "inline text"]` + +`$ARGUMENTS` = file path, inline text in quotes, or blank (uses active editor file). + +--- + +## Steps + +**1. Resolve the source.** +- If `$ARGUMENTS` is a readable file path → `text = open(path).read()` +- If it's quoted inline text → use directly +- If blank → use the active editor file + +**2. Clear the result cache** to prevent cross-invocation pollution: + +```python +from semantica.semantic_extract.cache import _result_cache +_result_cache.clear() +``` + +**3. Run the full pipeline:** + +```python +from semantica.semantic_extract import ( + NamedEntityRecognizer, + RelationExtractor, + EventDetector, + CoreferenceResolver, + TripletExtractor, + ExtractionValidator, +) + +# Named Entity Recognition +ner = NamedEntityRecognizer() +entities = ner.extract(text) + +# Relation Extraction +rel = RelationExtractor() +relations = rel.extract(text) + +# Event Detection +evt = EventDetector() +events = evt.extract(text) + +# Coreference Resolution — resolve pronouns/aliases before extraction +coref = CoreferenceResolver() +resolved_text = coref.resolve(text) + +# Triplet Extraction (subject–predicate–object) +triplet = TripletExtractor() +triplets = triplet.extract(resolved_text) + +# Validate quality +validator = ExtractionValidator() +issues = validator.validate(entities, relations) +``` + +**4. Report validator warnings** above results: +``` +⚠ ExtractionValidator: +``` + +**5. Return results as Markdown tables:** + +**Entities** (N total) +| Label | Type | Confidence | Span | +|-------|------|------------|------| + +**Relations** (M total) +| Source | Relation Type | Target | Confidence | +|--------|---------------|--------|------------| + +**Events** (K total) +| Label | Type | Participants | Confidence | +|-------|------|--------------|------------| + +**Triplets** (J total) +| Subject | Predicate | Object | Confidence | +|---------|-----------|--------|------------| + +**6. Summary line:** +``` +Extracted: N entities, M relations, K events, J triplets — from +``` + +For large files (>50KB), process in chunks and show a progress indicator. Highlight any entities appearing in the context graph already (`ContextGraph.has_node(label)`) with `[in graph]` tag. diff --git a/plugins/skills/ingest/SKILL.md b/plugins/skills/ingest/SKILL.md new file mode 100644 index 00000000..b7a016c4 --- /dev/null +++ b/plugins/skills/ingest/SKILL.md @@ -0,0 +1,37 @@ +--- +name: ingest +description: Ingest data from files, databases, APIs, or streams into Semantica knowledge graphs with schema mapping and entity linking. +--- + +# /semantica:ingest + +Ingest new data into the knowledge graph. Usage: `/semantica:ingest [args]` + +`$ARGUMENTS` = source type + optional file path, connection string, or dataset identifier. + +--- + +## `file [--format json|csv|yaml|xml]` + +Ingest structured data from a local file. + +```python +from semantica.ingest import DataIngestor + +ingestor = DataIngestor() +ingestor.ingest_file(file_path=path, file_format=file_format) +``` + +Output: imported node/edge count and ingestion summary. + +--- + +## `db [--query ]` + +Ingest data from a database source. + +```python +ingestor.ingest_database(connection_string=conn, query=query) +``` + +Return: rows ingested, mapped entities, and warnings. diff --git a/plugins/skills/ontology/SKILL.md b/plugins/skills/ontology/SKILL.md new file mode 100644 index 00000000..4702d137 --- /dev/null +++ b/plugins/skills/ontology/SKILL.md @@ -0,0 +1,37 @@ +--- +name: ontology +description: Manage ontology schemas, concepts, relationships, and alignments for Semantica knowledge graphs. +--- + +# /semantica:ontology + +Manage ontology definitions and validation. Usage: `/semantica:ontology [args]` + +`$ARGUMENTS` = task + optional ontology item or schema file. + +--- + +## `describe ` + +Show ontology concept details. + +```python +from semantica.ontology import OntologyManager + +manager = OntologyManager() +concept = manager.get_concept(concept_name) +``` + +Output: properties, relationships, inherited types, and examples. + +--- + +## `validate [--schema ]` + +Validate the graph or schema against the ontology. + +```python +result = manager.validate_graph(graph=graph, schema_file=schema_file) +``` + +Return: validation status, errors, and correction suggestions. diff --git a/plugins/skills/policy/SKILL.md b/plugins/skills/policy/SKILL.md new file mode 100644 index 00000000..2c564370 --- /dev/null +++ b/plugins/skills/policy/SKILL.md @@ -0,0 +1,37 @@ +--- +name: policy +description: Define and enforce policies, access controls, and compliance rules over Semantica knowledge graphs. +--- + +# /semantica:policy + +Apply policy rules and checks. Usage: `/semantica:policy [args]` + +`$ARGUMENTS` = task + optional policy name, rule set, or target entity. + +--- + +## `check [--rule ] [--target ]` + +Run policy checks against the graph. + +```python +from semantica.policy import PolicyEngine + +engine = PolicyEngine() +result = engine.check(rule_name=rule_name, target=target) +``` + +Output: compliance status, failing rules, and remediation guidance. + +--- + +## `list` + +List available policy rules and categories. + +```python +rules = engine.list_rules() +``` + +Return: rule name, description, severity, and category. diff --git a/plugins/skills/provenance/SKILL.md b/plugins/skills/provenance/SKILL.md new file mode 100644 index 00000000..dabdd1a0 --- /dev/null +++ b/plugins/skills/provenance/SKILL.md @@ -0,0 +1,37 @@ +--- +name: provenance +description: Trace data lineage, source attribution, audit trails, and provenance assertions in Semantica graphs. +--- + +# /semantica:provenance + +Inspect provenance metadata. Usage: `/semantica:provenance [args]` + +`$ARGUMENTS` = task + optional node, edge, or time range. + +--- + +## `trace [--depth N]` + +Trace the provenance of a node or fact. + +```python +from semantica.provenance import ProvenanceTracer + +tracer = ProvenanceTracer() +trace = tracer.trace_node(node_id=node_id, depth=depth) +``` + +Output: source chain, authors, timestamps, and validation status. + +--- + +## `audit [--since ] [--actor ]` + +View audit logs for graph changes. + +```python +audit_log = tracer.get_audit_log(since=since, actor=actor) +``` + +Return: change events, actor, affected objects, and action details. diff --git a/plugins/skills/query/SKILL.md b/plugins/skills/query/SKILL.md new file mode 100644 index 00000000..7b3ed407 --- /dev/null +++ b/plugins/skills/query/SKILL.md @@ -0,0 +1,49 @@ +--- +name: query +description: Query the Semantica knowledge graph using SPARQL, Cypher, keyword search, and structured graph query patterns. +--- + +# /semantica:query + +Run graph queries and search. Usage: `/semantica:query [args]` + +`$ARGUMENTS` = query mode + query string or filter. + +--- + +## `sparql ` + +Execute a SPARQL query against the graph. + +```python +from semantica.query import QueryEngine + +engine = QueryEngine() +results = engine.query_sparql(query) +``` + +Return: query bindings as a Markdown table. + +--- + +## `cypher ` + +Execute a Cypher-like query. + +```python +results = engine.query_cypher(query) +``` + +Output: node/relationship results and path summaries. + +--- + +## `search [--filter ]` + +Search graph entities by keyword. + +```python +results = engine.search(keywords=keywords, filter_type=filter_type) +``` + +Return: ranked matches with entity types and relevance scores. diff --git a/plugins/skills/reason/SKILL.md b/plugins/skills/reason/SKILL.md new file mode 100644 index 00000000..bd8cedba --- /dev/null +++ b/plugins/skills/reason/SKILL.md @@ -0,0 +1,201 @@ +--- +name: reason +description: Run reasoning over the Semantica knowledge graph — deductive logic, abductive hypothesis generation, Datalog programs, SPARQL queries, Rete network evaluation. Uses DeductiveReasoner, AbductiveReasoner, DatalogReasoner, SPARQLReasoner, ReteEngine. Sub-commands: deductive, abductive, datalog, sparql, rete, prove, hypotheses. +--- + +# /semantica:reason + +Apply reasoning over the knowledge graph. Usage: `/semantica:reason [args]` + +`$ARGUMENTS` = reasoning mode + rules/observations/query. + +--- + +## `deductive [--facts ''] [--rules '|']` + +Apply deductive rules to known facts to derive new conclusions. + +```python +from semantica.reasoning.deductive_reasoner import DeductiveReasoner, Premise + +reasoner = DeductiveReasoner() + +# Add base facts to working memory +# Facts can be strings like "Person(John)" or structured dicts +import json +facts = json.loads(facts_json) if facts_json else [] +reasoner.add_facts(facts) + +# Apply logic with explicit premises +# Premise objects have: statement, confidence, source +premises = [ + Premise(statement=fact, confidence=1.0) + for fact in facts +] + +conclusions = reasoner.apply_logic(premises=premises) +``` + +Return: `| Conclusion | Triggering Premises | Confidence | Rule Applied |` + +If zero rules given, run `reasoner.prove_theorem()` on any provided theorem: +```python +proof = reasoner.prove_theorem(theorem=theorem_text) +``` + +Output: `Proof: | Valid: YES / NO` + +--- + +## `prove [--facts '']` + +Prove or disprove a theorem against known facts. + +```python +from semantica.reasoning.deductive_reasoner import DeductiveReasoner + +reasoner = DeductiveReasoner() +import json +reasoner.add_facts(json.loads(facts_json) if facts_json else []) + +proof = reasoner.prove_theorem(theorem=theorem) +``` + +Output: +``` +Theorem: "" +Result: PROVED ✓ | DISPROVED ✗ | UNDECIDABLE ⚠ + +Proof steps: + 1. + 2. ... + → QED: + +Confidence: +``` + +--- + +## `abductive [--knowledge ''] [--top N]` + +Generate and rank hypotheses that explain an observation. + +```python +from semantica.reasoning.abductive_reasoner import ( + AbductiveReasoner, Observation +) + +reasoner = AbductiveReasoner() + +import json +if knowledge_json: + reasoner.add_knowledge(json.loads(knowledge_json)) + +obs = Observation(description=observation) + +# Generate all hypotheses then rank them +hypotheses = reasoner.generate_hypotheses(observations=[obs]) +ranked = reasoner.rank_hypotheses(hypotheses) +best = reasoner.get_best_explanation(obs) + +# Also get full explanations with evidence +explanations = reasoner.find_explanations(observations=[obs]) +``` + +Output: +``` +Abductive Reasoning for: "" + +Best explanation: + (confidence: 0.87) + +All hypotheses (ranked): + | Rank | Hypothesis | Confidence | Supporting Evidence | + | 1 | | 0.87 | | + | 2 | ... + +Full explanations: + Explanation 1: + Evidence: +``` + +--- + +## `datalog ` + +Evaluate a Datalog program over graph facts. + +```python +from semantica.reasoning.datalog_reasoner import DatalogReasoner +from semantica.context import ContextGraph + +graph = ContextGraph() +reasoner = DatalogReasoner() + +# program is a string of Datalog rules and queries +results = reasoner.evaluate(program=program, graph=graph) +``` + +Return derived tuples as a relation table. Show rule derivation counts. + +--- + +## `sparql ` + +Run a SPARQL query over the knowledge graph and return results. + +```python +from semantica.reasoning.sparql_reasoner import SPARQLReasoner +from semantica.context import ContextGraph + +graph = ContextGraph() +reasoner = SPARQLReasoner() + +results = reasoner.query(sparql_query=query, graph=graph) +``` + +Return as a Markdown table with bound variable columns matching the SELECT clause. + +--- + +## `rete [--rules '|'] [--facts '']` + +Incremental rule evaluation using the Rete network with working memory. + +```python +from semantica.reasoning.rete_engine import ReteEngine +import json + +engine = ReteEngine() + +rules = rules_str.split("|") if rules_str else [] +facts = json.loads(facts_json) if facts_json else [] + +engine.load_rules(rules) +engine.process_facts(facts) +activations = engine.get_activations() +``` + +Return: `| Rule Fired | Variable Bindings | Working Memory Delta | Activation Order |` + +--- + +## `hypotheses "" [--knowledge ''] [--top N]` + +Generate the top-N most probable explanations for a complex scenario. + +```python +from semantica.reasoning.abductive_reasoner import AbductiveReasoner, Observation +import json + +reasoner = AbductiveReasoner() +if knowledge_json: + reasoner.add_knowledge(json.loads(knowledge_json)) + +obs = Observation(description=scenario) +hypotheses = reasoner.generate_hypotheses(observations=[obs]) +ranked = reasoner.rank_hypotheses(hypotheses) +top_n = ranked[:int(n) if n else 5] +``` + +For each hypothesis also show: what evidence supports it, what would falsify it, and which is the most parsimonious (fewest assumptions). diff --git a/plugins/skills/temporal/SKILL.md b/plugins/skills/temporal/SKILL.md new file mode 100644 index 00000000..737b4f14 --- /dev/null +++ b/plugins/skills/temporal/SKILL.md @@ -0,0 +1,164 @@ +--- +name: temporal +description: Temporal graph operations on Semantica — scoped queries at a point in time, graph snapshots, node change timelines, temporal causal analysis, and graph state reconstruction. Uses AgentContext.find_precedents(as_of=), ContextGraph.state_at(), CausalChainAnalyzer.trace_at_time(), and TemporalQueryRewriter. Sub-commands: query, snapshot, timeline, causal-at, precedents-at. +--- + +# /semantica:temporal + +Temporal graph operations. Usage: `/semantica:temporal [args]` + +`$ARGUMENTS` = sub-command + query/node + date expression. + +--- + +## `query "" [at|before|after ]` + +Temporally-scoped natural-language graph query. + +```python +from semantica.kg.temporal_query_rewriter import TemporalQueryRewriter +from semantica.kg.temporal_normalizer import TemporalNormalizer + +normalizer = TemporalNormalizer() +# Normalize natural date expressions: "last month", "Q3 2024", "2025-01-15" +date = normalizer.normalize(date_expr) + +rewriter = TemporalQueryRewriter() +# Rewrite query with temporal constraint +rewritten = rewriter.rewrite( + query=question, + temporal_constraint={"op": direction, "value": date}, # op: "at"|"before"|"after" +) +``` + +Then run the rewritten query through `AgentContext.retrieve()` or `ContextGraph.query()`. + +Return ranked results with `Valid From`, `Valid Until`, `Active At ` columns. Mark nodes that were not yet created at the target time as `[not yet created]`. + +--- + +## `snapshot ` + +Reconstruct the full graph state as it existed at a specific point in time. + +```python +from semantica.context import ContextGraph + +graph = ContextGraph(advanced_analytics=True) + +# state_at returns a dict snapshot of the graph at that timestamp +snapshot = graph.state_at(timestamp=date) # ISO string or datetime +``` + +Output: +``` +Graph snapshot at : + Nodes: N (M added since prev snapshot, K removed) + Edges: P + Density: 0.21 + Communities: Q + +Active decision categories at : + | Category | Count | Avg Confidence | + +Top 10 nodes (by degree at ): + | Node | Type | Degree | + +[Compact Mermaid graph TD — top-10 most connected nodes at that time] +``` + +--- + +## `timeline ` + +Show attribute and relationship changes for a node across its full history. + +```python +from semantica.context import ContextGraph + +graph = ContextGraph() + +# Use state_at() at multiple time points to reconstruct history +# Check add_node timestamps and edge addition times from graph data +node_data = graph.find_node(node_id) +``` + +Output as Markdown timeline: +``` +Timeline for "" (): + + CREATED + Properties: {confidence: 0.71, category: "loan_approval"} + Source: extraction/pipeline + + UPDATED + confidence: 0.71 → 0.91 [source: review] + + RELATIONSHIP ADDED + "" →[CAUSED]→ "Decision_B" + + RELATIONSHIP REMOVED + "" →[PRECEDED_BY]→ "Decision_X" (superseded) + +Total lifespan: +Current state: +``` + +--- + +## `causal-at [--direction upstream|downstream]` + +Trace a causal chain as it existed at a specific point in time. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) + +historical_chain = analyzer.trace_at_time( + event_id=decision_id, + at_time=date, # ISO string or datetime + direction=direction or "upstream", + max_depth=10, +) +``` + +Output: +``` +Historical causal chain for at : + Direction: upstream (what caused it?) + + [Mermaid graph TD showing chain as it existed at ] + + Decisions present then but not now: [list] + Decisions added since then: [list] +``` + +--- + +## `precedents-at "" [--category ]` + +Find precedent decisions that existed as of a specific date — useful for auditing what context was available when a decision was made. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) + +# find_precedents supports as_of parameter for temporal precedent search +precedents = ctx.find_precedents( + scenario=scenario, + category=category or None, + limit=10, + use_hybrid_search=True, + include_context=True, + include_superseded=False, + as_of=date, # Only return precedents that existed at this date +) +``` + +Return: `| Rank | Decision ID | Scenario | Outcome | Confidence | Set Date | Valid Until |` + +Note decisions that were superseded before or after the target date. diff --git a/plugins/skills/validate/SKILL.md b/plugins/skills/validate/SKILL.md new file mode 100644 index 00000000..4ac2797d --- /dev/null +++ b/plugins/skills/validate/SKILL.md @@ -0,0 +1,228 @@ +--- +name: validate +description: Validate Semantica pipelines, extraction quality, graph schemas, and ontology consistency. Returns structured error/warning checklists. Uses PipelineValidator, PipelineBuilder.validate_pipeline(), GraphValidator, and OntologyValidator. Sub-commands: pipeline, step, dependencies, extraction, graph, ontology, performance. +--- + +# /semantica:validate + +Validate pipeline and graph quality. Usage: `/semantica:validate [options]` + +`$ARGUMENTS` = target type + optional config or path. + +--- + +## `pipeline [--config '']` + +Validate a full pipeline builder configuration. + +```python +from semantica.pipeline.pipeline_builder import PipelineBuilder +from semantica.pipeline.pipeline_validator import PipelineValidator + +builder = PipelineBuilder() +if config_json: + import json + builder.build_pipeline(json.loads(config_json)) + +# PipelineBuilder has its own quick validate +quick = builder.validate_pipeline() # returns Dict + +# PipelineValidator gives full ValidationResult(valid, errors, warnings) +# Does NOT raise — always returns a result object +validator = PipelineValidator() +result = validator.validate(builder) + +# Also check inter-step dependencies +deps = validator.check_dependencies(builder) +``` + +Output: +``` +Pipeline Validation: VALID ✓ | INVALID ✗ +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Steps: N registered +Valid: M steps + +Errors (K): + ✗ [step_name] + +Warnings (J): + ⚠ [step_name] + +Dependencies: + ✓ All dependencies resolved + ✗ Step "" depends on missing step "" + +Result: — K errors, J warnings +``` + +--- + +## `step [--type ] [--constraints '']` + +Validate a single pipeline step. + +```python +from semantica.pipeline.pipeline_builder import PipelineBuilder +from semantica.pipeline.pipeline_validator import PipelineValidator +import json + +builder = PipelineBuilder() +step = builder.get_step(step_name) + +validator = PipelineValidator() +result = validator.validate_step( + step=step, + **json.loads(constraints_json) if constraints_json else {}, +) +``` + +Output: same checklist format but scoped to a single step. + +--- + +## `dependencies` + +Check all inter-step dependency resolution for the active pipeline. + +```python +from semantica.pipeline.pipeline_builder import PipelineBuilder +from semantica.pipeline.pipeline_validator import PipelineValidator + +builder = PipelineBuilder() +validator = PipelineValidator() + +deps = validator.check_dependencies(builder) +``` + +Output: +``` +Dependency Graph: + | Step | Depends On | Status | + | step_A | — | ✓ | + | step_B | step_A | ✓ | + | step_C | step_X | ✗ MISSING | + +Cycles detected: YES / NO +Missing steps: [list] +``` + +--- + +## `extraction ` + +Validate extraction quality for a file — entity confidence, relation density, coverage. + +```python +from semantica.semantic_extract.extraction_validator import ExtractionValidator +from semantica.semantic_extract import ( + NamedEntityRecognizer, + RelationExtractor, +) +from semantica.semantic_extract.cache import _result_cache + +_result_cache.clear() # prevent cross-invocation cache pollution + +text = open(file_path).read() + +ner = NamedEntityRecognizer() +rel = RelationExtractor() +entities = ner.extract(text) +relations = rel.extract(text) + +validator = ExtractionValidator() +issues = validator.validate(entities, relations) +``` + +Output: +``` +Extraction Validation: + Entities: N extracted + Relations: M extracted + Avg confidence: 0.83 + +Errors (K): + ✗ + +Warnings (J): + ⚠ + +Quality score: X/100 +``` + +--- + +## `graph` + +Check schema conformance, referential integrity, and structural health. + +```python +from semantica.kg.graph_validator import GraphValidator +from semantica.context import ContextGraph + +graph = ContextGraph() +validator = GraphValidator(graph) +result = validator.validate() +``` + +Output: +``` +Graph Validation: + Nodes: N | Edges: M + Node types: K valid, J unknown + +Referential integrity: + ✗ Dangling edge: + +Schema conformance: + ✗ Node "" missing required property "" + +Result: N errors, M warnings +``` + +--- + +## `ontology` + +Validate ontology consistency and evaluate competency questions. + +```python +from semantica.ontology import OntologyValidator + +validator = OntologyValidator() +result = validator.validate() +cq_results = validator.evaluate_competency_questions() +``` + +Output: +``` +Ontology Validation: + Classes: N + Properties: M + Consistent: YES ✓ | NO ✗ + +Competency questions: + ✓ "Can we find all instances of X?" — answered + ✗ "Is Y a subclass of Z?" — failed: + +Result: N consistency errors, M CQ failures +``` + +--- + +## `performance` + +Validate pipeline performance characteristics — bottlenecks, parallelism, and resource use. + +```python +from semantica.pipeline.pipeline_builder import PipelineBuilder +from semantica.pipeline.pipeline_validator import PipelineValidator + +builder = PipelineBuilder() +pipeline = builder.build() +validator = PipelineValidator() + +perf = validator.validate_performance(pipeline) +``` + +Output: step-by-step timing estimates, parallelism opportunities, and recommended parallelism level. diff --git a/plugins/skills/visualize/SKILL.md b/plugins/skills/visualize/SKILL.md new file mode 100644 index 00000000..594fd04e --- /dev/null +++ b/plugins/skills/visualize/SKILL.md @@ -0,0 +1,249 @@ +--- +name: visualize +description: Visualize the Semantica knowledge graph — topology, centrality, communities, paths, embeddings, decision insights, and temporal evolution. Uses GraphAnalyzer, CentralityCalculator, CommunityDetector, PathFinder, and ContextGraph analytics. Sub-commands: topology, centrality, community, path, decision-graph, insights, temporal, embedding. +--- + +# /semantica:visualize + +Render graph visualizations as Mermaid, ASCII, or structured Markdown. Usage: `/semantica:visualize [args]` + +`$ARGUMENTS` = sub-command + optional node label or filter. + +--- + +## `topology [--filter ]` + +Full graph structure analysis — node types, edge distribution, connectivity metrics. + +```python +from semantica.kg.graph_analyzer import GraphAnalyzer +from semantica.context import ContextGraph + +graph = ContextGraph(advanced_analytics=True) +analyzer = GraphAnalyzer() + +# Comprehensive analysis +analysis = analyzer.analyze_graph(graph=graph.to_dict()) +metrics = analyzer.compute_metrics(graph=graph) +connectivity = analyzer.analyze_connectivity(graph=graph) +``` + +Output: +``` +Graph Topology: + Nodes: N (M types) + Edges: P + Density: 0.23 + Avg degree: 4.7 + Connected: YES / NO (K components) + +Node type distribution: + [Mermaid pie chart] + | Type | Count | % | Avg Degree | + +Top-10 connected nodes: + | Node | Type | Degree | Betweenness | +``` + +--- + +## `centrality [--type degree|betweenness|closeness|eigenvector|pagerank|all] [--top N]` + +Calculate and rank nodes by centrality. + +```python +from semantica.kg.centrality_calculator import CentralityCalculator +from semantica.context import ContextGraph + +graph = ContextGraph() +calc = CentralityCalculator() + +if centrality_type == "all" or not centrality_type: + scores = calc.calculate_all_centrality(graph=graph) +elif centrality_type == "degree": + scores = calc.calculate_degree_centrality(graph=graph) +elif centrality_type == "betweenness": + scores = calc.calculate_betweenness_centrality(graph=graph) +elif centrality_type == "closeness": + scores = calc.calculate_closeness_centrality(graph=graph) +elif centrality_type == "eigenvector": + scores = calc.calculate_eigenvector_centrality(graph=graph) +elif centrality_type == "pagerank": + scores = calc.calculate_pagerank( + graph=graph, + max_iterations=20, + damping_factor=0.85, + ) +``` + +Return: `| Rank | Node | Type | Degree | Betweenness | Closeness | Eigenvector | PageRank |` + +For a single node, also call `ContextGraph.get_node_centrality(node_id)` and `get_node_importance(node_id)`. + +--- + +## `community [--algorithm louvain|leiden|label-propagation|overlapping]` + +Detect and visualize graph communities/clusters. + +```python +from semantica.kg.community_detector import CommunityDetector +from semantica.context import ContextGraph + +graph = ContextGraph() +detector = CommunityDetector() + +algorithm = algo_arg or "louvain" + +if algorithm == "louvain": + result = detector.detect_communities_louvain(graph, resolution=1.0) +elif algorithm == "leiden": + result = detector.detect_communities_leiden(graph, resolution=1.0) +elif algorithm == "label-propagation": + result = detector.detect_communities_label_propagation(graph) +elif algorithm == "overlapping": + result = detector.detect_overlapping_communities(graph) +else: + result = detector.detect_communities(graph, algorithm=algorithm) + +structure = detector.analyze_community_structure(graph, result) +metrics = detector.calculate_community_metrics(graph, result) +``` + +Output: +``` +Community Detection (algorithm: louvain) + Communities: N + Modularity: 0.71 + +Community summary: + | ID | Size | Top Node | Internal Density | Bridge Nodes | + +[Mermaid graph TD — nodes colored/grouped by community ID] +``` + +--- + +## `path [--k N] [--algorithm bfs|dijkstra|astar|k-shortest]` + +Find and visualize paths between two nodes. + +```python +from semantica.kg.path_finder import PathFinder +from semantica.context import ContextGraph + +graph = ContextGraph() +finder = PathFinder() + +k = int(k_arg) if k_arg else 3 + +if algorithm == "bfs": + path = finder.bfs_shortest_path(graph, source=n1, target=n2) + paths = [path] +elif algorithm == "dijkstra": + path = finder.dijkstra_shortest_path(graph, source=n1, target=n2) + paths = [path] +else: # default: k-shortest + paths = finder.find_k_shortest_paths(graph, source=n1, target=n2, k=k) + +lengths = [finder.path_length(graph, p) for p in paths] +``` + +Output as Mermaid `sequenceDiagram` for each path: +``` +Path 1 (length: 2.3): + n1 →[rel_type]→ Middle →[rel_type]→ n2 + +Path 2 (length: 3.7): ... +``` + +--- + +## `decision-graph [--category ] [--depth N]` + +Visualize the decision influence graph for a category or all decisions. + +```python +from semantica.context import ContextGraph +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +graph = ContextGraph(advanced_analytics=True) + +# Get decision insights +insights = graph.get_decision_insights() + +# Build causal network +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +network = analyzer.analyze_causal_network() +``` + +Output as Mermaid `graph TD` with: +- Node size proportional to causal impact score +- Color by outcome (green=approved, red=rejected, yellow=deferred) +- Edge labels showing relationship type + +--- + +## `insights` + +Comprehensive decision analytics dashboard. + +```python +from semantica.context import ContextGraph, AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True, kg_algorithms=True) +graph = ContextGraph(advanced_analytics=True, centrality_analysis=True) + +insights = graph.get_decision_insights() +summary = graph.get_decision_summary() +graph_summary = graph.get_graph_summary() +context_insights = ctx.get_context_insights() +``` + +Output a full analytics dashboard: +``` +Decision Intelligence Dashboard +════════════════════════════════ +Decisions: N total (M active) +Categories: K unique +Avg confidence: 0.87 +Outcome split: approved 55% | rejected 30% | deferred 15% +Causal chains: P chains, longest: Q hops +Loops detected: R circular dependencies + +Graph health: + Nodes: N | Edges: M | Density: 0.23 + Communities: K | Isolated nodes: J + +[Mermaid pie — outcome distribution] +[Mermaid bar — decisions by category] +``` + +--- + +## `temporal [--node ] [--start ] [--end ]` + +Analyze how the graph evolved over time. + +```python +from semantica.kg.graph_analyzer import GraphAnalyzer +from semantica.context import ContextGraph + +graph = ContextGraph() +analyzer = GraphAnalyzer() + +evolution = analyzer.analyze_temporal_evolution( + graph=graph, + start_time=start_date or None, + end_time=end_date or None, + metrics=["node_count", "edge_count", "density", "communities"], +) + +# For a specific node, use ContextGraph.state_at() +if node_id: + snapshot = graph.state_at(timestamp=end_date or "now") +``` + +Output as Markdown timeline with metrics per interval. diff --git a/write_missing_skills.py b/write_missing_skills.py new file mode 100644 index 00000000..04c4fafc --- /dev/null +++ b/write_missing_skills.py @@ -0,0 +1,1031 @@ +import os + +base = r'c:\Users\Mohd Kaif\semantica\plugins\skills' + +SKILLS = {} + +SKILLS['causal'] = """--- +name: causal +description: Causal chain analysis on Semantica decision graphs — upstream traces, downstream impact, root causes, impact scoring, network analysis, loop detection, precedent chains, and temporal causal queries. Uses CausalChainAnalyzer, ContextGraph, and AgentContext. +--- + +# /semantica:causal + +Causal chain analysis. Usage: `/semantica:causal [options]` + +--- + +## `trace [--direction upstream|downstream] [--depth N]` + +Walk the causal chain upstream (what caused this?) or downstream (what did this cause?). + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) + +chain = analyzer.get_causal_chain( + decision_id=decision_id, + direction=direction or "upstream", + max_depth=int(depth) if depth else 10, +) +``` + +Output as Mermaid `graph TD` + table: `| Step | ID | Category | Outcome | Confidence | Depth |` + +--- + +## `impact [--depth N] [--indirect]` + +Full downstream impact — direct and indirect influenced decisions. + +```python +from semantica.context import ContextGraph +from semantica.context.causal_analyzer import CausalChainAnalyzer + +graph = ContextGraph(advanced_analytics=True) +analyzer = CausalChainAnalyzer(graph_store=graph) + +impact = graph.analyze_decision_impact(decision_id, include_indirect="--indirect" in args) +influence = graph.analyze_decision_influence(decision_id, max_depth=int(depth) if depth else 3, include_indirect=True) +influenced = analyzer.get_influenced_decisions(decision_id, max_depth=int(depth) if depth else 10) +score = analyzer.get_causal_impact_score(decision_id) +``` + +Output: Impact score (0-1) + direct/indirect counts + Mermaid downstream tree. + +--- + +## `roots [--depth N]` + +Find root cause decisions at the origin of a causal chain. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +roots = analyzer.find_root_causes(decision_id, max_depth=int(depth) if depth else 10) +``` + +Output: Root list + Mermaid path from root to target. + +--- + +## `score ` + +Causal impact score + centrality breakdown. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import ContextGraph, AgentContext + +ctx = AgentContext(decision_tracking=True, kg_algorithms=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +graph = ContextGraph() + +score = analyzer.get_causal_impact_score(decision_id) +centrality = graph.get_node_centrality(decision_id) +importance = graph.get_node_importance(decision_id) +``` + +Output: Score (0=isolated, 1=max) + degree/betweenness/closeness/eigenvector + interpretation. + +--- + +## `network [ ...]` + +Analyze the full causal network structure. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +network = analyzer.analyze_causal_network(decision_ids=decision_ids or None) +``` + +Output: Network stats (edges, density, longest chain) + Mermaid of top-15 by impact. + +--- + +## `loops [--depth N]` + +Detect circular causal dependencies. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +loops = analyzer.find_causal_loops(max_depth=int(depth) if depth else 10) +``` + +Output: Each loop as `A -> B -> C -> A` chain + risk warning. + +--- + +## `precedent-chain [--depth N]` + +Walk the full precedent chain (what decisions was this derived from?). + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +chain = analyzer.get_precedent_chain(decision_id, max_depth=int(depth) if depth else 10) +``` + +Return: `| Step | ID | Scenario | Outcome | Confidence | Date |` + +--- + +## `at-time [--direction upstream|downstream]` + +Trace causal chain as it existed at a specific point in time. + +```python +from semantica.context.causal_analyzer import CausalChainAnalyzer +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +analyzer = CausalChainAnalyzer(graph_store=ctx.graph_store) +historical = analyzer.trace_at_time( + event_id=decision_id, at_time=at_time, + direction=direction or "upstream", max_depth=10, +) +``` + +Output: Historical chain at `` + diff vs. current (added/removed decisions since then). +""" + +SKILLS['policy'] = """--- +name: policy +description: Decision policy governance in Semantica — check compliance, find applicable policies, add/update/version policies, enforce rules against decision data, analyze change impact, track affected decisions, and record exceptions. Uses PolicyEngine, ContextGraph, and DecisionQuery. +--- + +# /semantica:policy + +Policy governance. Usage: `/semantica:policy [args]` + +--- + +## `check ` + +Check whether a decision complies with a policy. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +engine = ctx.get_policy_engine() +decision = ctx.query_decisions(query=decision_id, max_hops=1)[0] +compliant = engine.check_compliance(decision=decision, policy_id=policy_id) +``` + +Output: `COMPLIANT ✓ | NON-COMPLIANT ✗` + violated rules with details. + +--- + +## `applicable [--entities ]` + +Find all policies applicable to a decision category and entity set. + +```python +engine = ctx.get_policy_engine() +policies = engine.get_applicable_policies( + category=category, + entities=entities.split(",") if entities else None, +) +``` + +Return: `| Policy ID | Name | Version | Rules Count | Active Since |` + +--- + +## `add "" --rules ''` + +Register a new policy. + +```python +from semantica.context.decision_models import Policy +import json + +engine = ctx.get_policy_engine() +policy = Policy(policy_id=policy_id, name=name, rules=json.loads(rules_json)) +registered_id = engine.add_policy(policy) +``` + +--- + +## `update --rules '' --reason "" [--version ]` + +Update policy rules with versioning and audit trail. + +```python +new_version = engine.update_policy( + policy_id=policy_id, + rules=json.loads(rules_json), + change_reason=reason, + new_version=version or None, +) +``` + +--- + +## `enforce [--rules '']` + +Apply policy enforcement against decision data and report violations. + +```python +from semantica.context import ContextGraph +import json + +graph = ContextGraph(advanced_analytics=True) +result = graph.enforce_decision_policy( + decision_data=json.loads(decision_data_json), + policy_rules=json.loads(rules_json) if rules_json else None, +) +rule_check = graph.check_decision_rules( + decision_data=json.loads(decision_data_json), + rules=json.loads(rules_json) if rules_json else None, +) +``` + +Output: Actions applied, violations list, ENFORCED/BLOCKED status. + +--- + +## `history ` + +Show version history of a policy. + +```python +history = engine.get_policy_history(policy_id) +``` + +Return: `| Version | Changed At | Reason | Rules Delta |` + +--- + +## `impact --rules ''` + +Analyze the effect of proposed policy changes on existing decisions. + +```python +import json +impact = engine.analyze_policy_impact( + policy_id=policy_id, + proposed_rules=json.loads(proposed_rules_json), +) +``` + +Output: Count compliant -> non-compliant (risk) and non-compliant -> compliant (gain). + +--- + +## `affected ` + +List all decisions affected by a policy version change. + +```python +affected = engine.get_affected_decisions(policy_id, from_version, to_version) +``` + +Return: `| Decision ID | Category | Was Compliant | Now Compliant |` + +--- + +## `exception "" --approver ` + +Record a formal policy exception. + +```python +exception_id = engine.record_exception( + decision_id=decision_id, policy_id=policy_id, + reason=reason, approver=approver, justification=reason, +) +from semantica.context.decision_query import DecisionQuery +dq = DecisionQuery(graph_store=ctx.graph_store) +similar = dq.find_similar_exceptions(exception_reason=reason, limit=5) +``` + +Output: `Exception recorded` + similar past exceptions for audit. +""" + +SKILLS['query'] = """--- +name: query +description: Query the Semantica ContextGraph and AgentContext using natural language, multi-hop traversal, LLM reasoning, and direct graph queries. Sub-commands: retrieve, decisions, multi-hop, expand, reasoning, similar, graph. +--- + +# /semantica:query + +Query the context graph. Usage: `/semantica:query "" [options]` + +--- + +## `retrieve "" [--max N] [--graph] [--entities] [--expand]` + +Hybrid vector + graph retrieval. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True, graph_expansion=True, advanced_analytics=True) + +results = ctx.retrieve( + query=question, + max_results=int(max_n) if max_n else 5, + use_graph="--graph" in args, + include_entities="--entities" in args, + include_relationships=True, + expand_graph="--expand" in args, + deduplicate=True, +) +``` + +Return: `| Rank | Content | Type | Score | Source | Timestamp |` + +--- + +## `decisions "" [--hops N] [--hybrid]` + +Query decisions with multi-hop graph reasoning. + +```python +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +decisions = ctx.query_decisions( + query=question, + max_hops=int(hops) if hops else 3, + include_context=True, + use_hybrid_search="--hybrid" in args, +) +``` + +Return: `| ID | Category | Scenario | Outcome | Confidence | Hops | Timestamp |` + +--- + +## `multi-hop "" [--hops N]` + +Multi-hop graph traversal from a known entity. + +```python +ctx = AgentContext(decision_tracking=True, graph_expansion=True, advanced_analytics=True) +result = ctx.multi_hop_context_query( + start_entity=start_entity, + query=question, + max_hops=int(hops) if hops else 3, +) +``` + +Output: Traversal path + ranked results + Mermaid hop graph. + +--- + +## `expand "" [--hops N]` + +Expand a query through the graph to find adjacent context. + +```python +ctx = AgentContext(graph_expansion=True) +expanded = ctx.expand_query(query=question, max_hops=int(hops) if hops else 2) +``` + +Shows which expansion hops added what context. + +--- + +## `reasoning "" [--max N] [--hops N]` + +LLM-powered reasoning over retrieved graph context. + +```python +ctx = AgentContext(decision_tracking=True, graph_expansion=True, advanced_analytics=True) +result = ctx.query_with_reasoning( + query=question, + llm_provider=None, + max_results=int(max_n) if max_n else 10, + max_hops=int(hops) if hops else 2, +) +``` + +Output: LLM-synthesized answer + supporting evidence nodes + reasoning chain. + +--- + +## `similar "" [--max N]` + +Find memories and nodes semantically similar to content. + +```python +ctx = AgentContext() +results = ctx.find_similar(content=content, limit=int(max_n) if max_n else 5) +``` + +--- + +## `graph "" [--skip N] [--limit N]` + +Direct query via ContextGraph.query(). + +```python +from semantica.context import ContextGraph + +graph = ContextGraph() +results = graph.query( + query=query_str, + skip=int(skip) if skip else 0, + limit=int(limit) if limit else 50, +) +``` + +Return: `| Node ID | Type | Properties | Neighbors |` + Mermaid pie of type distribution. +""" + +SKILLS['explain'] = """--- +name: explain +description: Generate natural-language explanations for decisions, reasoning paths, inferences, node paths, and policy compliance. Uses ExplanationGenerator.generate_explanation, show_reasoning_path, justify_conclusion, AgentContext.trace_decision_explainability, and ContextGraph.trace_decision_chain. +--- + +# /semantica:explain + +Generate explanations. Usage: `/semantica:explain ` + +--- + +## `decision ` + +Full explainability trace for a decision. + +```python +from semantica.context import AgentContext, ContextGraph + +ctx = AgentContext(decision_tracking=True, advanced_analytics=True) +explainability = ctx.trace_decision_explainability(decision_id) + +graph = ContextGraph(advanced_analytics=True) +chain = graph.trace_decision_chain(decision_id, max_steps=5) +causality = graph.trace_decision_causality(decision_id, max_depth=5) +influence = ctx.analyze_decision_influence(decision_id, max_depth=3) +``` + +Output: Reasoning steps, causal antecedents, evidence items, policy compliance per policy. + +--- + +## `reasoning ` + +Explain any reasoning object — generates natural-language summary and step trace. + +```python +from semantica.reasoning.explanation_generator import ExplanationGenerator + +gen = ExplanationGenerator() +explanation = gen.generate_explanation(reasoning=reasoning_input) +# explanation.summary, .confidence, .evidence + +path = gen.show_reasoning_path(reasoning=reasoning_input) +# path.steps: [Step(type, description, confidence)] +# path.conclusion +``` + +Output: Summary + step-by-step path + confidence score. + +--- + +## `inference ""` + +Justify a conclusion against its reasoning context. + +```python +from semantica.reasoning.explanation_generator import ExplanationGenerator + +gen = ExplanationGenerator() +path = gen.show_reasoning_path(reasoning=reasoning_context) +justification = gen.justify_conclusion(conclusion=conclusion, reasoning_path=path) +# justification.is_justified, .confidence, .supporting_steps, .opposing_factors +``` + +Output: `JUSTIFIED ✓ | NOT JUSTIFIED ✗ | PARTIAL ⚠` + supporting steps + opposing factors. + +--- + +## `path ` + +Explain the semantic relationship between two nodes. + +```python +from semantica.kg.path_finder import PathFinder +from semantica.context import ContextGraph +from semantica.reasoning.explanation_generator import ExplanationGenerator + +graph = ContextGraph(advanced_analytics=True) +finder = PathFinder() + +paths = finder.find_k_shortest_paths(graph, source=n1, target=n2, k=3) +lengths = [finder.path_length(graph, p) for p in paths] + +gen = ExplanationGenerator() +explanation = gen.generate_explanation(reasoning={"paths": paths, "source": n1, "target": n2}) +``` + +Output: Top-3 paths + prose summary + Mermaid sequenceDiagram. + +--- + +## `compliance ` + +Explain policy compliance status of a decision. + +```python +from semantica.context import AgentContext + +ctx = AgentContext(decision_tracking=True) +engine = ctx.get_policy_engine() +decision = ctx.query_decisions(query=decision_id, max_hops=1)[0] +applicable = engine.get_applicable_policies( + category=decision.category, + entities=decision.metadata.get("entities", []), +) +results = [ + {"policy": p, "compliant": engine.check_compliance(decision, p.policy_id)} + for p in applicable +] +``` + +Output: Per-policy COMPLIANT/NON-COMPLIANT + violated rules + remediation suggestions. +""" + +SKILLS['change'] = """--- +name: change +description: Track, review, and version Semantica knowledge graph changes. Sub-commands: log, diff, rollback, tag. Uses ChangeLog and OntologyVersionManager. +--- + +# /semantica:change + +Track graph versions and changes. Usage: `/semantica:change [args]` + +--- + +## `log [n]` + +Show last N change log entries (default: 20). + +```python +from semantica.change_management import ChangeLog + +log = ChangeLog() +entries = log.get_recent(n=int(args) if args else 20) +``` + +Return: `| # | Timestamp | Operation | Target | Actor | Version |` + +--- + +## `diff ` + +Structural diff between two versions. + +```python +from semantica.change_management import OntologyVersionManager + +manager = OntologyVersionManager() +diff = manager.diff(v1, v2) +``` + +Output: Added/removed/modified classes, properties, and nodes. + +--- + +## `rollback ` + +> **CONFIRMATION REQUIRED** before proceeding. + +Revert graph to a prior version snapshot. + +```python +manager.rollback(version) +``` + +--- + +## `tag