协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
schema-inference-engine【开发与工程】Implements intelligent schema inference engine with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: schema-inference-engine compatibility: opencode completeness: 95 content-types:
Orchestrates intelligent skill selection and execution for schema inference engine workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.
┌───────────────────────────────────────────────────────────────────────────────┐ │ Orchestration Flow │ └───────────────────────────────────────────────────────────────────────────────┘
User Request ↓ ┌─────────────────┐ │ Parse Request │ │ & Extract │ │ Features │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Evaluate Available Skills │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Skill A │ │ Skill B │ │ Skill C │ │ │ │ - Match Score│ │ - Match Score│ │ - Match Score│ │ │ │ - Confidence │ │ - Confidence │ │ - Confidence │ │ │ │ - History │ │ - History │ │ - History │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ │ └─────────────────┴─────────────────┘ │ │ ↓ │ │ Select Best Skill │ └─────────────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────┐ │ Execute Skill │ └────────┬────────┘ ↓ ┌─────────────────┐ │ Handle Result │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Error Handling & Fallback │ │ │ │ Success? ────────► Return Result │ │ │ │ Fail? ────────┐ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Fallback Chain │ │ │ │ │ │ │ │ 1. Retry with adjusted parameters │ │ │ │ 2. Try Alternative Skill (if available) │ │ │ │ 3. Defer to Human Operator (if critical) │ │ │ │ 4. Log & Return Error │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
Use this skill when:
Avoid this skill for:
Parse and Analyze Request - Extract intent, entities, and constraints from user input. Checkpoint: All required parameters must be present and in valid format before proceeding.
Score Available Skills - Calculate match scores using multi-factor algorithm:
Checkpoint: Skip to fallback if no skill scores above threshold.
Select Optimal Skill - Choose skill with highest score that meets minimum confidence. Checkpoint: Verify skill has not been disabled or deprecated.
Execute with Fallback - Run skill execution wrapped in retry and fallback logic. Checkpoint: Log all execution attempts for audit trail.
Return or Fallback - Either return successful result or apply fallback chain:
related-skillsCheckpoint: Record outcome with timing and confidence metadata.
def infer_schema_from_sample(
raw_data: List[Dict],
source_metadata: Dict,
min_confidence: float = 0.75
) -> Dict:
"""Infer schema fields from raw data samples with multi-factor scoring.
Applies Law 1 (Early Exit) and Law 2 (Immutable State) to ensure
only valid, well-typed fields are extracted. Returns a new schema dict.
"""
if not raw_data or not isinstance(raw_data, list):
raise ValueError("raw_data must be a non-empty list of records")
inferred_fields = {}
for record in raw_data:
for key, value in record.items():
if key not in inferred_fields:
inferred_fields[key] = {
"name": key,
"type": _detect_type(value),
"nullable": False,
"sample_values": [],
"confidence": 0.0
}
inferred_fields[key]["sample_values"].append(value)
inferred_fields[key]["nullable"] |= value is None
# Calculate multi-factor confidence scores
for field_name, field in inferred_fields.items():
type_confidence = _calculate_type_confidence(field["sample_values"])
consistency_score = _calculate_consistency(field["sample_values"])
field["confidence"] = (type_confidence * 0.6) + (consistency_score * 0.4)
if field["confidence"] < min_confidence:
field["fallback_strategy"] = "human_review"
# Law 3: Return new structure, never mutate input
return {
"schema_version": "1.0",
"fields": list(inferred_fields.values()),
"source": source_metadata.get("source_id"),
"inference_timestamp": time.time()
}
def resolve_schema_conflicts(
primary_schema: Dict,
secondary_schema: Dict,
conflict_resolution_policy: str = "highest_confidence"
) -> Dict:
"""Merge two inferred schemas, resolving field conflicts via fallback chain.
Implements Law 4 (Fail Fast) and fallback logic for ambiguous merges.
"""
if not primary_schema or not secondary_schema:
raise ValueError("Both schemas must be provided for merging")
merged_fields = {f["name"]: dict(f) for f in primary_schema["fields"]}
conflicts = []
for field in secondary_schema["fields"]:
if field["name"] in merged_fields:
existing = merged_fields[field["name"]]
if existing["type"] != field["type"]:
# Fallback Chain: 1. Type coercion, 2. Union type, 3. Human review
if _can_coerce(existing["type"], field["type"]):
existing["type"] = _coerce_type(existing["type"], field["type"])
elif existing["confidence"] >= field["confidence"]:
conflicts.append({
"field": field["name"],
"action": "defer_to_human",
"reason": "type_mismatch_low_confidence"
})
else:
merged_fields[field["name"]] = dict(field)
else:
merged_fields[field["name"]] = dict(field)
# Law 3: Return new merged structure
return {
"merged_schema": list(merged_fields.values()),
"conflicts": conflicts,
"resolution_policy": conflict_resolution_policy,
"audit_log": f"Merged {len(primary_schema['fields'])} + {len(secondary_schema['fields'])} fields"
}
code-philosophy (5 Laws of Elegant Defense) in all logicWhen applying this skill, produce:
| Skill | Purpose |
|---|---|
nosql-data-modeling | Provides data modeling strategies that complement schema inference for non-relational databases |
postgresql-optimization | Uses inferred schemas to generate optimized PostgreSQL queries and indexes |
Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.