# Mechanical Diagnostic Contract

This document defines the data contracts for the Agent4 mechanical design diagnostic flow.
The current supported knowledge scope is Chapter 18 only.

## 0. Historical Alignment Reference

This section is a historical comparison note only. Agent4 does not read evidence from `agent3` at runtime; the diagnostic flow uses Agent4's own `SectionBrepExtractor`, `BrepFaultProbe`, backend API, and Chapter 18 knowledge index.

Agent4 should align with the formal historical contract defined in:

- `D:\CSharpProjects\agent3\tools\SectionBrepExtractor\Program.cs`
  - `BuildSemanticFusionContract()`
  - `LocalSemanticUnitSchema`
  - `BrepFactBundleSchema`
  - `DedupPolicy`
  - `RetrievalPolicy`
- `D:\CSharpProjects\agent3\机械设计禁忌1000例_知识库提取\build_rule_cards_v1.py`
  - `retrieval_unit_policy`
  - `build_retrieval_index`
  - `build_rule_store`

The important Agent3 rules are:

1. The model side is knowledge-blind before retrieval.
   It must not include rule ids, final fault words, or detailed rule-store conclusions.

2. `LocalSemanticUnit.retrieval_sentence` is the main query.
   `primary_view` and `secondary_views` are filters or weights.

3. The model-side `retrieval_sentence` must be a neutral fact sentence.
   The knowledge-side `retrieval_sentence` may be a design principle sentence.

4. Detailed `verification_rule` is loaded only after retrieval.
   Final judgement compares `LocalSemanticUnit.fact_bundle` plus global semantic graph evidence against `verification_rule`.

5. If required extractable facts are missing, the system should request second-pass extraction instead of guessing.

6. Deduplication happens before retrieval/judgement:
   merge local units with the same `primary_view`, same anchor, and same core relation signature.

7. Raw B-rep ids are evidence references, not retrieval semantics.
   Agent3 separates `retrieval_sentence` from `brep_evidence`, `source_semantic_ids`, and `fact_bundle`.
   Therefore Agent4 must not use ids such as `sketch_edge_1` as retrieval terms.

## 1. Mechanical Semantic Graph

Schema: `mechanical_semantic_graph_v1`

Purpose:
- Convert B-rep facts and rendered SolidWorks images into mechanical semantics.
- Preserve traceable evidence internally.
- Avoid using raw B-rep ids as user-facing semantics or retrieval text.

Agent3 semantic fusion pipeline:

1. Extract assembly B-rep once.
   For an assembly, every component's B-rep facts must come from its assembly component instance, including assembly transforms and contacts.
2. Build `ComponentEvidencePackages`.
   Keep each component's faces, features, contacts, and planned images separated by SolidWorks instance name and file path.
3. Export baseline assembly images, component highlight images, part-file images, physical-interface/contact highlight images, and internal component group context images. Section images are disabled.
4. VLM must analyze physical-interface/contact highlight images together with B-rep contacts, SolidWorks mates, adjacent component context, and component function profiles. The result is a per-interface contact function description, not a whole-component purpose.
5. AI first diagnoses assembly-level issues: contacts, fits, locating, disassembly, interference, accessibility, support, sealing, lubrication, and motion relations.
5. For every component with `review_scope=part_design_required`, use its part-file images according to `PartImagePlan`, but do not re-extract or mix part B-rep.
6. Components with `review_scope=assembly_context_only` are standard or purchased context. Do not run nonstandard part-structure taboo checks on them unless the task is standard-part selection/calculation.
7. The backend builds a component work queue for every `part_design_required` component instance.
8. AI generates local subgraphs directly per component. First round uses target B-rep/images, highlighted assembly/context images, direct contacts/mates, and adjacent component summaries.
9. If a component-local subgraph needs neighbor geometry, AI returns `neighbor_detail_request`; the backend retries that component with the requested neighbor B-rep/image/contact evidence.
10. The backend merges per-component results into a thin compatibility graph file and retrieves knowledge rules by `LocalSemanticUnit.primary_view/secondary_views` and `retrieval_sentence`.
11. Load detailed `verification_rule` only for retrieved candidates and judge with the current `fact_bundle`, local subgraph evidence, and attached images.
12. If a candidate rule lacks required extractable facts, request additional standard/context images or computed B-rep checks instead of guessing.

Required root shape:

```json
{
  "schema": "mechanical_semantic_graph_v1",
  "model_identity": {
    "name": "string",
    "source_assembly_path": "string",
    "likely_equipment_type": "string",
    "confidence": 0.0,
    "evidence": ["internal evidence refs"]
  },
  "nodes": [],
  "edges": [],
  "measurements": [],
  "local_semantic_units": [],
  "local_subgraphs": [],
  "uncertain_roles": [],
  "missing_facts": [],
  "evidence_index": []
}
```

Component-by-component context policy:
- For assembly inputs, analyze part-design issues per SolidWorks component instance.
- Each nonstandard component instance should use its own assembly-derived B-rep subset, isolated part-file images for external shape/manufacturability, and assembly context images where the whole component instance is highlighted.
- Standard or purchased components with `review_scope=assembly_context_only` are not diagnostic targets and should not generate part-structure local units, but they remain valid occlusion blockers, contact boundary components, and assembly-function context.
- Reusable context/isolate group images are generated only for geometrically internal component groups. These groups are identified before AI function understanding by six-axis BBox occlusion analysis plus contact-graph expansion.
- Internal occlusion analysis checks `+X/-X/+Y/-Y/+Z/-Z`; each direction uses four extreme projection samples and only the first-hit blockers. A direction is occluded when first-hit blocker projection coverage of the target projection is `> 0.5`. A component is internal when at least four directions are occluded. Stop early when occluded directions reach four or open directions reach three.
- Internal group display mode is `strict_internal_only`: show the internal members, hide all other components, and record contact boundary components without showing them by default.
- If the same part file appears in multiple assembly locations, keep separate component-instance evidence and local units; do not merge them by file path alone.
- For internal components, use temporary hide/show context isolation group images instead of section views. The image exporter must restore every component's original visibility after saving images and must not save the SolidWorks model.
- Assembly function understanding must not rely only on SolidWorks mate records. B-rep-derived physical contacts and exported `physical_interfaces` highlight images are first-class evidence.
- The bridge must export a standalone per-contact/per-interface function file at `diagnostic_context/interface_function_descriptions.json`, plus a readable Markdown companion. This file is the stable downstream source for drawing tolerance binding and for reviewing contact-surface functions separately from component purposes.

Important rule:
- Internal evidence may contain ids such as `sketch_edge_1`, `face_3`, or `patch_r0_c1`.
- Mechanical semantics must use readable structure terms such as `外圆柱面`, `端部台阶`, `局部凸台`, `加工面`, `非加工面`, `配合面`, `孔口`, `壳体外表面`.

## 2. Local Semantic Unit

Schema field: `local_semantic_units`

Purpose:
- This is the model-side retrieval unit.
- It is generated directly by AI from one component's B-rep, images, assembly position, contacts/mates, and optional neighbor evidence.
- It must be knowledge-blind: no rule id, no final fault judgement.

Required item shape:

```json
{
  "local_id": "unit_machined_unmachined_boundary_1",
  "linked_subgraph_id": "subgraph_machined_unmachined_boundary_1",
  "pattern_type": "machined_unmachined_surface_boundary",
  "primary_view": "surface_role_boundary",
  "secondary_views": ["part_local_shape"],
  "retrieval_sentence": "壳体局部加工候选面与周围非加工候选表面处于同一连续外表面区域，缺少台阶或沟槽形成明确分界。",
  "inferred_functions": [
    "装配接触",
    "定位",
    "加工候选"
  ],
  "inferred_attributes": [
    {
      "name": "machined_surface_candidate",
      "value": true,
      "confidence": 0.78,
      "reason": "该局部面与其他零件存在接触/配合关系，可能需要加工保证装配"
    },
    {
      "name": "unmachined_surface_candidate",
      "value": true,
      "confidence": 0.62,
      "reason": "周围大面积外表面未见接触或定位功能，疑似铸造非加工面"
    }
  ],
  "retrieval_fact_tags": [
    "small_local_contact_face",
    "surrounding_large_surface",
    "near_coplanar_surface_boundary",
    "machined_unmachined_surface_candidate"
  ],
  "retrieval_relations": [
    "局部接触面与周围大面积外表面相邻且近似共面"
  ],
  "normalized_measurements": [
    {
      "name": "step_height",
      "value": null,
      "unit": "mm",
      "confidence": 0.0
    }
  ],
  "fact_bundle": {
    "anchor": {
      "kind": "feature",
      "id": "internal feature or face-group id",
      "solidworks_name": "real SolidWorks component or feature owner name",
      "component_file_name": "real component file name",
      "inferred_role": "AI role label, never replacing the real name"
    },
    "related_parts": [
      "SolidWorks instance names, file names, paths, and inferred role candidates"
    ],
    "related_features": [
      "feature ids and role candidates"
    ],
    "known_relations": [
      {
        "type": "adjacent_to | contacts | fits_with | supports | locates",
        "a": "internal evidence ref",
        "b": "internal evidence ref",
        "confidence": 0.0,
        "evidence_refs": []
      }
    ],
    "brep_facts": [
      {
        "name": "step_height",
        "value": null,
        "unit": "mm",
        "confidence": 0.0,
        "source_ref": "internal evidence ref"
      }
    ],
    "image_facts": [
      {
        "view": "section_main_axis_longitudinal",
        "observation": "局部表面与周围壳体外表面连续过渡",
        "confidence": 0.0
      }
    ],
    "missing_facts": [
      {
        "fact": "step height between local machined candidate and surrounding surface",
        "why_needed": "needed to verify whether there is a clear boundary",
        "suggested_extraction": "additional standard/context image or computed B-rep step-height check"
      }
    ],
    "confidence": 0.0,
    "evidence_status": "candidate"
  },
  "dedup_key": "machined_unmachined_boundary_shell_outer_surface"
}
```

Rules:
- `retrieval_sentence` is the primary retrieval text.
- `inferred_functions`, `inferred_attributes`, `retrieval_fact_tags`, `retrieval_relations`, and `normalized_measurements` are retrieval enrichment fields. They may contain AI-inferred function or process attributes such as machined/unmachined surface candidates, but every inference must carry confidence and evidence-grounded reason.
- `retrieval_sentence` must be a neutral fact sentence.
- `retrieval_sentence` must not contain raw B-rep ids such as `sketch_edge_1`, `edge_12`, `face_3`, `patch_r0_c1`, `region_outside`, or `measurement_1`.
- `retrieval_sentence` must not contain rule ids or judgement words such as `错误`, `违反`, `应该`, `不应`, `fault`, `violation`, `wrong`.
- `fact_bundle` may keep raw ids inside `anchor`, `related_features`, `known_relations`, `brep_facts.source_ref`, or `evidence_refs` for traceability, but these ids are not knowledge retrieval terms.

## 3. Local Subgraph

Schema field: `local_subgraphs`

Purpose:
- This is the graph-side evidence package linked to `local_semantic_units`.
- It records which semantic nodes, relations, measurements, and evidence support the local unit.

Required item shape:

```json
{
  "id": "subgraph_machined_unmachined_boundary_1",
  "pattern_type": "machined_unmachined_surface_boundary",
  "primary_view": "surface_role_boundary",
  "secondary_views": ["part_local_shape"],
  "node_ids": ["node_shell_body", "node_local_face", "node_surrounding_surface"],
  "edge_ids": ["semantic_edge_adjacent_surface_boundary"],
  "measurement_ids": ["measurement_step_height"],
  "roles": [
    "host_body",
    "local_machined_face_candidate",
    "surrounding_unmachined_surface_candidate"
  ],
  "evidence": ["internal ids and image evidence refs"],
  "confidence": 0.0,
  "reason": "why this local graph can retrieve a design taboo rule"
}
```

Rules:
- `local_subgraphs` may carry raw evidence ids.
- `local_subgraphs` is not the main retrieval text.
- The paired `local_semantic_units.retrieval_sentence` is the main retrieval text.

## 4. Knowledge Rule Retrieval Unit

Current files:
- `机械设计禁忌1000例_知识库提取/diagnostic_index/chapter18_rule_index_v1.json`
- `机械设计禁忌1000例_知识库提取/diagnostic_index/chapter18_rule_store_v1.json`

Current scope:
- Only rules whose `rule_id` starts with `18.` are eligible.

Knowledge index item shape:

```json
{
  "rule_id": "18.2.4",
  "title": "加工面与不加工面不应平齐",
  "primary_view": "surface_role_boundary",
  "secondary_views": ["part_local_shape"],
  "knowledge_category": "manufacturing_structure",
  "retrieval_unit": {
    "retrieval_sentence": "不同粗糙度或精度要求的表面连续过渡，缺少台阶、沟槽或明确分界，导致高精度加工范围扩大。",
    "aliases": [],
    "keywords": []
  }
}
```

Knowledge store item adds verification rules:

```json
{
  "rule_id": "18.2.4",
  "title": "加工面与不加工面不应平齐",
  "verification_rule": {
    "required_facts": [],
    "required_model_facts": [],
    "bad_if": "facts that indicate a violation",
    "good_if": "facts that indicate no violation",
    "unknown_if": []
  }
}
```

## 5. Retrieval Logic

Input:
- One `LocalSemanticUnit` at a time.

Query text:
- `retrieval_sentence`
- `primary_view`
- `secondary_views`
- `pattern_type`
- `retrieval_chain`
- `retrieval_semantic_roles`
- `inferred_functions`
- `inferred_attributes`
- `retrieval_fact_tags`
- `retrieval_relations`
- `normalized_measurements`
- cleaned semantic text extracted from `fact_bundle`

Excluded from query text:
- raw B-rep ids
- file paths
- raw JSON dumps
- rule ids from the model side
- final judgement words

Candidate rule text:
- `title`
- `knowledge_category`
- `primary_view`
- `secondary_views`
- `retrieval_unit.retrieval_sentence`
- `retrieval_unit.keywords`
- `retrieval_unit.aliases`

Scoring:
1. Filter to Chapter 18.
2. Tokenize Chinese text with character n-grams.
3. Add score for token overlap.
4. Add score when `primary_view` matches.
5. Add score when `secondary_views` match.
6. Add score when `pattern_type` is compatible with the rule view.
7. If view-matched candidates exist, keep view-matched candidates first.
8. Deduplicate by `rule_id`; keep the highest scoring candidate.

Agent3 retrieval policy:
- Model-side semantic generation is knowledge-blind.
- Use SolidWorks component names/file names as primary names.
- Put AI inferred functional names in `inferred_role` fields only.
- For assembly input, generate local units for assembly relations and for each nonstandard component with `review_scope=part_design_required`.
- Do not run part-structure taboo checks on standard or purchased components with `review_scope=assembly_context_only`.
- Use `LocalSemanticUnit.retrieval_sentence` as the main query.
- Use `primary_view/secondary_views` as filters or weights.
- The retrieval index returns rule ids and lightweight retrieval fields only.
- Load the detailed `verification_rule` only after retrieval.
- Final judgement must cite `fact_bundle` items and `verification_rule.required_model_facts`.
- If a likely candidate lacks required extractable facts, issue a second-pass extraction request rather than guessing.

Agent3 dedup policy:
- Merge local units with the same `primary_view`, same anchor id, and same core relation signature.
- If two units only differ by wording, keep the one with more concrete B-rep facts and merge evidence/missing facts.
- Do not create separate biased units such as `risk`, `boundary`, or `fault` for the same anchor and view before retrieval.
- Keep one neutral fact unit before retrieval.
- The same anchor may appear in multiple views only when the retrieval purpose differs, such as surface boundary vs tool access.
- Never remove uncertainty or missing facts during deduplication.

Runtime retrieval dedup policy:
- Retrieve candidates independently for each local semantic unit.
- The same rule id may be returned for multiple different component instances or local anchors.
- Deduplicate only for final display by `rule_id + component_id + semantic_location + anchor`, not globally during retrieval.

Final judgement:
- Retrieval only finds candidate rules.
- The final AI judgement must compare `fact_bundle` and semantic graph facts with `verification_rule`.
- A rule match alone is not a fault.

## 6. User-Facing Output

The frontend should show:
- one deduplicated Chapter 18 rule candidate per rule id;
- the readable `retrieval_sentence`;
- one relevant evidence image for the issue;
- final AI judgement in Chinese.

The frontend should not show:
- raw B-rep ids as the problem location;
- output files;
- internal runtime paths;
- raw tool stdout;
- whole image galleries unrelated to a specific candidate.
