Summary
CommonSenseEngine provides common-sense knowledge and reasoning capabilities. Implements ConceptNet-style relational knowledge (Liu & Singh 2004), qualitative physics (Hayes 1985), naive psychology (Schank & Abelson 1977 scripts), and plausibility-based inference (Collins & Michalski 1989).
Data Structures
CommonSenseRelation Enum
class CommonSenseRelation(str, Enum):
IS_A = "IsA" # taxonomic
HAS_PROPERTY = "HasProperty" # attribute
CAPABLE_OF = "CapableOf" # ability
USED_FOR = "UsedFor" # function
AT_LOCATION = "AtLocation" # spatial
CAUSES = "Causes" # causal
HAS_PREREQUISITE = "HasPrerequisite" # precondition
HAS_EFFECT = "HasEffect" # consequence (Schank causal chain)
MOTIVATED_BY = "MotivatedByGoal" # naive psychology
DESIRES = "Desires" # agent goals
CREATED_BY = "CreatedBy" # origin
MADE_OF = "MadeOf" # composition
RECEIVES_ACTION = "ReceivesAction" # patient role
DISTINCT_FROM = "DistinctFrom" # negative knowledge
CommonSenseAssertion Frozen Dataclass
@dataclass(frozen=True, slots=True)
class CommonSenseAssertion:
assertion_id: str
subject: str # source concept
relation: CommonSenseRelation
object: str # target concept
confidence: float # [0, 1] — assertion confidence
source: str # provenance (e.g. "experience", "bootstrap", "analogy")
context: Optional[str] = None # situational qualifier
weight: float = 1.0 # ConceptNet-style weight (positive real)
PlausibilityScore Frozen Dataclass
@dataclass(frozen=True, slots=True)
class PlausibilityScore:
score: float # [-1, 1] — plausible to implausible
supporting_assertions: Tuple[str, ...] # assertion_ids that support
contradicting_assertions: Tuple[str, ...] # assertion_ids that contradict
confidence: float # meta-confidence in the score
reasoning_chain: Tuple[str, ...] # explanation steps
ExpectationFrame Frozen Dataclass
@dataclass(frozen=True, slots=True)
class ExpectationFrame:
frame_id: str
context: str # situation description
expected_events: Tuple[str, ...] # Schank script — expected sequence
expected_properties: FrozenSet[str] # expected attributes
violation_threshold: float = 0.3 # surprise if deviation > threshold
Protocol
@runtime_checkable
class CommonSenseEngine(Protocol):
async def query(self, subject: str, relation: CommonSenseRelation,
limit: int = 10) -> Tuple[CommonSenseAssertion, ...]: ...
async def infer(self, subject: str, relation: CommonSenseRelation,
max_hops: int = 3) -> Tuple[CommonSenseAssertion, ...]: ...
async def validate_plausibility(self, statement: str) -> PlausibilityScore: ...
async def generate_expectations(self, context: str) -> ExpectationFrame: ...
async def explain(self, subject: str, object: str) -> Tuple[str, ...]: ...
async def add_assertion(self, assertion: CommonSenseAssertion) -> None: ...
async def get_related(self, concept: str, limit: int = 20) -> Tuple[CommonSenseAssertion, ...]: ...
Implementation: HybridCommonSenseEngine
- Knowledge base:
dict[str, list[CommonSenseAssertion]] indexed by subject, with secondary index by relation type
- Query: Direct lookup by subject + relation, sorted by weight × confidence
- Multi-hop inference: BFS/DFS over assertion graph up to
max_hops, combining confidence via product rule: conf_chain = ∏ conf_i × decay^hop
- Plausibility scoring: Three-signal fusion:
- Direct evidence: matching assertions pro/con
- Analogical transfer: find analogous concepts via ConceptGraph similarity, transfer assertions with confidence penalty
- Script consistency: check against ExpectationFrame — violations reduce plausibility
- Expectation generation: Given context string, retrieve relevant assertions, construct Schank-style script of expected events using causal chain (CAUSES → HAS_EFFECT → HAS_PREREQUISITE)
- Explanation: Find shortest path between subject and object in assertion graph, return human-readable chain
- Thread safety:
asyncio.Lock on assertion store mutation; reads are lock-free
Null Implementation: NullCommonSenseEngine
Returns empty tuples, neutral PlausibilityScore(0.0). For testing.
Factory
def make_common_sense_engine(*, backend: str = "hybrid") -> CommonSenseEngine:
match backend:
case "hybrid": return HybridCommonSenseEngine()
case "null": return NullCommonSenseEngine()
case _: raise ValueError(f"Unknown backend: {backend}")
Metrics (Prometheus)
| Metric |
Type |
Description |
common_sense_assertions_total |
Gauge |
Total assertions in KB |
common_sense_query_seconds |
Histogram |
Query latency |
common_sense_inference_hops |
Histogram |
Hops per multi-hop inference |
common_sense_plausibility_score |
Histogram |
Plausibility score distribution |
common_sense_expectations_generated_total |
Counter |
Expectation frames generated |
Test Targets (12)
test_add_assertion_stores
test_query_by_subject_and_relation
test_query_sorted_by_weight
test_infer_single_hop
test_infer_multi_hop_confidence_decay
test_validate_plausibility_positive
test_validate_plausibility_contradicted
test_generate_expectations_causal_chain
test_explain_shortest_path
test_get_related_returns_all_relations
test_analogical_transfer_confidence_penalty
test_null_engine_returns_neutral
Integration Points
- ConceptGraph (26.1): Similarity queries for analogical transfer
- AnalogicalReasoner (20.2): Structured analogy mapping enriches inference
- WorldModel (13.1): World model entities provide grounding for assertions
- SurpriseDetector (13.4): Expectation violations trigger surprise signals
References
- Liu, H. & Singh, P. (2004). ConceptNet — A practical commonsense reasoning toolkit
- Lenat, D.B. (1995). CYC: A large-scale investment in knowledge infrastructure
- Schank, R.C. & Abelson, R.P. (1977). Scripts, Plans, Goals, and Understanding
- Collins, A. & Michalski, R. (1989). The logic of plausible reasoning
- Hayes, P.J. (1985). The second naive physics manifesto
Phase 26 Planning: #577 | Depends on: #578 (26.1)
Summary
CommonSenseEngineprovides common-sense knowledge and reasoning capabilities. Implements ConceptNet-style relational knowledge (Liu & Singh 2004), qualitative physics (Hayes 1985), naive psychology (Schank & Abelson 1977 scripts), and plausibility-based inference (Collins & Michalski 1989).Data Structures
CommonSenseRelationEnumCommonSenseAssertionFrozen DataclassPlausibilityScoreFrozen DataclassExpectationFrameFrozen DataclassProtocol
Implementation:
HybridCommonSenseEnginedict[str, list[CommonSenseAssertion]]indexed by subject, with secondary index by relation typemax_hops, combining confidence via product rule:conf_chain = ∏ conf_i × decay^hopasyncio.Lockon assertion store mutation; reads are lock-freeNull Implementation:
NullCommonSenseEngineReturns empty tuples, neutral PlausibilityScore(0.0). For testing.
Factory
Metrics (Prometheus)
common_sense_assertions_totalcommon_sense_query_secondscommon_sense_inference_hopscommon_sense_plausibility_scorecommon_sense_expectations_generated_totalTest Targets (12)
test_add_assertion_storestest_query_by_subject_and_relationtest_query_sorted_by_weighttest_infer_single_hoptest_infer_multi_hop_confidence_decaytest_validate_plausibility_positivetest_validate_plausibility_contradictedtest_generate_expectations_causal_chaintest_explain_shortest_pathtest_get_related_returns_all_relationstest_analogical_transfer_confidence_penaltytest_null_engine_returns_neutralIntegration Points
References
Phase 26 Planning: #577 | Depends on: #578 (26.1)