Hidden Contract Investigator
Overview
A skill for extracting implicit contracts from existing code before reuse. Instead of trusting function names, comments, or type annotations at face value, this skill systematically uncovers the actual behavioral contracts embedded in code: what a function really returns, what side effects it triggers, what hidden preconditions it assumes, and how it behaves across different environments.
The root motivation: many production defects originate not from new code bugs, but from misunderstanding the actual behavior of reused code. A function named keepTwoDecimal() that returns a comma-formatted string instead of a numeric value, a variable that shadows another in a different scope, a utility that silently depends on production-only configuration -- these hidden contracts are the real source of integration failures.
Scope Boundary: This skill focuses on pre-implementation investigation of existing code assets. For reviewing already-written code, use critical-code-reviewer. For post-incident root cause analysis, use incident-rca-specialist.
When to Use
- Reusing existing functions/modules/services in new feature implementation
- Working with legacy code where names and comments may be unreliable
- Investigating actual return types, side effects, and exception paths before integration
- Assessing whether an existing code asset is safe to reuse as-is
- Preparing contract tests for critical integration points
- Onboarding onto an unfamiliar codebase and need to understand actual behavior
- Post-RCA follow-up: hardening reuse patterns that caused incidents
Prerequisites
- Target code available: Source code of the reuse candidate must be readable
- Caller context identified: Know which new feature or module will consume the reused code
- Related artifacts accessible: Tests, bug tickets, and caller code provide critical evidence
- No active incident: This is a pre-implementation investigation skill, not incident response
Inputs
- Target code (function, class, module, or service boundary)
- Caller code or planned integration point
- Type definitions / interface definitions (if any)
- Existing test code covering the target
- Bug tickets or RCA reports related to the target (if available)
Outputs
- Implicit Contract Sheet -- documented actual contracts vs. stated contracts (includes Mismatch List as the "Risk" and "Observed contract" columns per entry in
assets/implicit_contract_sheet_template.md)
- Reuse Risk Register -- risk assessment for each reuse candidate
- Contract Verification Test Ideas -- test designs to lock down critical contracts
- Adoption Recommendation -- reuse decision with guardrails and prerequisites
Workflows
Workflow 1: Target Identification (対象特定)
Define the investigation boundary and scope.
- Identify reuse candidates at the appropriate granularity:
- Single function: utility, formatter, calculator, validator
- Class / module: a cohesive unit with internal state
- Screen flow: a UI workflow with multiple state transitions
- Service boundary: an API or microservice with request/response contracts
- DB persistence boundary: ORM models, repositories, migration scripts
- External API / library call: third-party dependencies with version-sensitive behavior
- For each candidate, document:
- Where it lives (file, module, package)
- Who currently calls it (known consumers)
- When it was last modified (staleness risk)
- Whether tests exist (coverage signal)
- Prioritize investigation order by:
- Criticality to the new feature (high-impact reuse first)
- Complexity of the target (more complex = more hidden contracts)
- Staleness and lack of documentation (higher risk of drift)
Workflow 2: Surface Contract Recording (見た目の契約記録)
Record what the code appears to promise -- without yet verifying it.
- Capture the name-implied contract: what the function/method name suggests it does
- Capture the documented contract: docstrings, comments, README mentions, API docs
- Capture the type-declared contract: type annotations, interface definitions, schema files
- Capture the caller-assumed contract: how existing callers use the return value, what they pass in
- Record all of these in the Implicit Contract Sheet using
assets/implicit_contract_sheet_template.md
- Mark everything as UNVERIFIED at this stage -- trust nothing yet
Workflow 3: Actual Contract Extraction (実際の契約抽出)
Read the actual implementation to discover the real behavioral contract.
Load references/contract_extraction_guide.md for the extraction methodology and priority order.
- Return value analysis:
- Actual return type (not just annotation -- trace the code path)
- Value formatting (does it add commas, currency symbols, units?)
- Null/empty/undefined handling (what happens on edge inputs?)
- Multiple return paths (does it return different types on different branches?)
- Side effect discovery:
- Database writes, cache updates, file system operations
- Event emission, message queue publishing, webhook calls
- Global/module state mutation
- Logging with sensitive data
- Hidden precondition identification:
- Implicit ordering requirements (must call A before B)
- Required initialization state (singleton must be configured first)
- Assumed input constraints not enforced by validation
- Environment variable dependencies
- Exception path mapping:
- Which exceptions are thrown vs. caught and swallowed
- Error return values vs. exception throwing (mixed patterns)
- Retry behavior (does it retry internally? how many times?)
- Environment-dependent behavior:
Load references/environment_behavior_guide.md for environment boundary patterns
- Configuration-driven branching (dev vs. prod behavior)
- Database dialect differences (SQLite vs. PostgreSQL)
- Timezone-sensitive operations
- Locale-dependent formatting
Workflow 4: Mismatch Classification (不一致分類)
Compare surface contracts (Workflow 2) against actual contracts (Workflow 3) and classify every discrepancy.
Load references/hidden_spec_patterns.md for the full pattern catalog.
Classify each mismatch into one or more of these 6 categories:
| Category |
Description |
Example |
| Naming Mismatch |
Function/variable name implies different behavior than actual |
keepTwoDecimal() returns comma-formatted string |
| Type Mismatch |
Return type or parameter type differs from expectation |
Annotated as float, actually returns str |
| Scope Mismatch |
Same-named identifiers exist in different scopes |
config in module scope vs. config in function scope |
| State Dependency |
Behavior depends on external mutable state |
Result changes based on global cache content |
| Environment Dependency |
Behavior varies across environments |
Works in dev (SQLite), fails in prod (PostgreSQL) |
| Hidden Side Effect |
Undocumented writes, mutations, or event emissions |
calculate_total() also updates a database record |
For each mismatch:
- Rate severity: Critical / High / Medium / Low
- Rate likelihood of triggering: High / Medium / Low
- Identify the blast radius: what breaks if this mismatch causes a defect
- Document the evidence: specific code lines, test results, or observations
Workflow 5: Reuse Feasibility Judgment (再利用可否判定)
Determine whether each target can be safely reused and under what conditions.
Load references/reuse_risk_classification.md for the full classification framework.
Apply the 5-level reuse classification:
| Level |
Verdict |
Meaning |
Action Required |
| A |
Reuse as-is |
Contracts match, behavior verified |
Add contract test only |
| B |
Reuse with wrapper |
Core behavior is correct but interface needs adaptation |
Build thin wrapper, add contract test |
| C |
Reuse with adapter |
Significant interface mismatch but logic is sound |
Build adapter layer, add integration test |
| D |
Contract test required first |
Behavior is uncertain, need verification before deciding |
Write contract tests, then re-evaluate |
| E |
Do not reuse / redesign |
Fundamental mismatch or unacceptable risk |
Redesign or implement from scratch |
For each reuse candidate:
- Assign a reuse level (A-E)
- Document the rationale with evidence from Workflow 4
- Specify guardrails: what callers must do (or never do) to use safely
- Identify naming improvements if the current name is misleading
- Record results in
assets/reuse_risk_register_template.md and assets/adoption_recommendation_template.md
Workflow 6: Verification Design (検証設計)
Design contract tests and verification strategies for critical implicit contracts.
Load references/runtime_boundary_checklist.md for boundary-specific test patterns.
- For each critical mismatch from Workflow 4, design a minimal contract test:
- What to verify: the specific contract (return type, side effect absence, etc.)
- Minimal test case: simplest possible test that would catch a contract violation
- Boundary data sets: edge cases and environment-sensitive inputs
- Failure signal: what a test failure means (which contract broke)
- Regression value: how this test prevents future incidents
- Prioritize tests by:
- Severity of the mismatch (Critical/High first)
- Blast radius of a contract violation
- Ease of test implementation
- Design environment-boundary tests for any Environment Dependency mismatches:
- DB dialect tests (SQLite vs. PostgreSQL behavior)
- Timezone tests (naive vs. aware datetime handling)
- Serialization round-trip tests (JSON, pickle, protobuf)
- Record all test ideas in
assets/contract_test_idea_template.md
- Connect each test back to the mismatch it guards against (traceability)
Resources
| Resource |
Type |
Purpose |
When to Load |
references/contract_extraction_guide.md |
Reference |
Extraction methodology, evidence priority, behavior-first approach |
Workflow 3 |
references/hidden_spec_patterns.md |
Reference |
Full catalog of mismatch patterns with examples |
Workflow 4 |
references/runtime_boundary_checklist.md |
Reference |
Boundary-specific checklists for DB, serialization, timezone, retry, locale |
Workflow 6 |
references/reuse_risk_classification.md |
Reference |
5-level reuse classification framework and decision criteria |
Workflow 5 |
references/environment_behavior_guide.md |
Reference |
Environment-dependent behavior patterns and verification strategies |
Workflow 3, 6 |
assets/implicit_contract_sheet_template.md |
Template |
Document stated vs. observed contracts with evidence |
Workflow 2, 3 |
assets/reuse_risk_register_template.md |
Template |
Risk register for reuse candidates |
Workflow 5 |
assets/contract_test_idea_template.md |
Template |
Contract test designs with data sets and failure signals |
Workflow 6 |
assets/adoption_recommendation_template.md |
Template |
Final reuse decision with guardrails and prerequisites |
Workflow 5 |
Best Practices
Behavior Over Documentation
- Never trust names alone:
formatCurrency() might truncate, isValid() might have side effects, getUser() might return cached stale data
- Never trust comments alone: comments drift from code; the implementation is the only source of truth
- Read callers before comments: how existing callers use a function reveals the actual contract more reliably than what the docstring claims
- Read tests before code: test assertions encode verified behavior; passing tests are machine-checked contracts
Evidence Hierarchy
When extracting contracts, prioritize evidence sources in this order:
- Passing test assertions (machine-verified behavior)
- Caller usage patterns (real-world consumption reveals actual contracts)
- Implementation code (the authoritative behavioral specification)
- Bug tickets and RCA reports (documented contract violations)
- Type annotations (may be outdated or incomplete)
- Comments and docstrings (lowest priority; most likely to drift)
Systematic Boundary Awareness
- Every time data crosses a boundary (function, module, service, DB, serialization), contracts can shift
- Pay special attention to: type coercion at boundaries, timezone handling at persistence layers, encoding changes at serialization points
- The most dangerous hidden contracts live at boundaries, not inside pure logic
Mismatch Taxonomy Discipline
- Always classify mismatches using the 6-category taxonomy -- do not use vague labels like "bug" or "issue"
- A single finding may belong to multiple categories (e.g., both Naming Mismatch and Type Mismatch)
- Rate severity and likelihood independently -- a low-likelihood Critical mismatch still needs a contract test
Connect to Prevention
- Every critical mismatch should produce at least one contract test idea
- Contract tests are not unit tests -- they verify the interface promise, not the internal logic
- Name tests after the contract they protect:
test_keepTwoDecimal_returns_numeric_not_string
- Contract tests are the skill's primary deliverable for long-term value
1---2name: hidden-contract-investigator3description: 既存コード・既存関数・既存モジュールの暗黙契約を抽出するスキル。 戻り値型、副作用、例外、前提条件、境界条件、環境依存挙動を確認し、 reuse前のリスクを可視化する。名前やコメントではなく実際の挙動から 契約を読み取り、不一致を分類し、再利用可否を判定する。 Use when reusing legacy code, verifying actual behavior of existing functions, or extracting implicit contracts before implementation. Covers: hidden contract, implicit contract, reuse risk, legacy behavior, 暗黙契約, 既存資産調査. Analyzes return types, side effects, exceptions, preconditions, boundary conditions, and environment-dependent behavior.4---56# Hidden Contract Investigator78## Overview910A skill for extracting **implicit contracts** from existing code before reuse. Instead of trusting function names, comments, or type annotations at face value, this skill systematically uncovers the actual behavioral contracts embedded in code: what a function really returns, what side effects it triggers, what hidden preconditions it assumes, and how it behaves across different environments.1112The root motivation: many production defects originate not from new code bugs, but from **misunderstanding the actual behavior of reused code**. A function named `keepTwoDecimal()` that returns a comma-formatted string instead of a numeric value, a variable that shadows another in a different scope, a utility that silently depends on production-only configuration -- these hidden contracts are the real source of integration failures.1314**Scope Boundary**: This skill focuses on pre-implementation investigation of existing code assets. For reviewing already-written code, use `critical-code-reviewer`. For post-incident root cause analysis, use `incident-rca-specialist`.1516## When to Use1718- Reusing existing functions/modules/services in new feature implementation19- Working with legacy code where names and comments may be unreliable20- Investigating actual return types, side effects, and exception paths before integration21- Assessing whether an existing code asset is safe to reuse as-is22- Preparing contract tests for critical integration points23- Onboarding onto an unfamiliar codebase and need to understand actual behavior24- Post-RCA follow-up: hardening reuse patterns that caused incidents2526## Prerequisites2728- **Target code available**: Source code of the reuse candidate must be readable29- **Caller context identified**: Know which new feature or module will consume the reused code30- **Related artifacts accessible**: Tests, bug tickets, and caller code provide critical evidence31- **No active incident**: This is a pre-implementation investigation skill, not incident response3233## Inputs3435- Target code (function, class, module, or service boundary)36- Caller code or planned integration point37- Type definitions / interface definitions (if any)38- Existing test code covering the target39- Bug tickets or RCA reports related to the target (if available)4041## Outputs42431. **Implicit Contract Sheet** -- documented actual contracts vs. stated contracts (includes Mismatch List as the "Risk" and "Observed contract" columns per entry in `assets/implicit_contract_sheet_template.md`)442. **Reuse Risk Register** -- risk assessment for each reuse candidate453. **Contract Verification Test Ideas** -- test designs to lock down critical contracts464. **Adoption Recommendation** -- reuse decision with guardrails and prerequisites4748## Workflows4950### Workflow 1: Target Identification (対象特定)5152Define the investigation boundary and scope.53541. Identify reuse candidates at the appropriate granularity:55 - **Single function**: utility, formatter, calculator, validator56 - **Class / module**: a cohesive unit with internal state57 - **Screen flow**: a UI workflow with multiple state transitions58 - **Service boundary**: an API or microservice with request/response contracts59 - **DB persistence boundary**: ORM models, repositories, migration scripts60 - **External API / library call**: third-party dependencies with version-sensitive behavior612. For each candidate, document:62 - Where it lives (file, module, package)63 - Who currently calls it (known consumers)64 - When it was last modified (staleness risk)65 - Whether tests exist (coverage signal)663. Prioritize investigation order by:67 - Criticality to the new feature (high-impact reuse first)68 - Complexity of the target (more complex = more hidden contracts)69 - Staleness and lack of documentation (higher risk of drift)7071### Workflow 2: Surface Contract Recording (見た目の契約記録)7273Record what the code **appears** to promise -- without yet verifying it.74751. Capture the **name-implied contract**: what the function/method name suggests it does762. Capture the **documented contract**: docstrings, comments, README mentions, API docs773. Capture the **type-declared contract**: type annotations, interface definitions, schema files784. Capture the **caller-assumed contract**: how existing callers use the return value, what they pass in795. Record all of these in the Implicit Contract Sheet using `assets/implicit_contract_sheet_template.md`806. **Mark everything as UNVERIFIED** at this stage -- trust nothing yet8182### Workflow 3: Actual Contract Extraction (実際の契約抽出)8384Read the actual implementation to discover the real behavioral contract.8586> Load `references/contract_extraction_guide.md` for the extraction methodology and priority order.87881. **Return value analysis**:89 - Actual return type (not just annotation -- trace the code path)90 - Value formatting (does it add commas, currency symbols, units?)91 - Null/empty/undefined handling (what happens on edge inputs?)92 - Multiple return paths (does it return different types on different branches?)932. **Side effect discovery**:94 - Database writes, cache updates, file system operations95 - Event emission, message queue publishing, webhook calls96 - Global/module state mutation97 - Logging with sensitive data983. **Hidden precondition identification**:99 - Implicit ordering requirements (must call A before B)100 - Required initialization state (singleton must be configured first)101 - Assumed input constraints not enforced by validation102 - Environment variable dependencies1034. **Exception path mapping**:104 - Which exceptions are thrown vs. caught and swallowed105 - Error return values vs. exception throwing (mixed patterns)106 - Retry behavior (does it retry internally? how many times?)1075. **Environment-dependent behavior**:108 > Load `references/environment_behavior_guide.md` for environment boundary patterns109 - Configuration-driven branching (dev vs. prod behavior)110 - Database dialect differences (SQLite vs. PostgreSQL)111 - Timezone-sensitive operations112 - Locale-dependent formatting113114### Workflow 4: Mismatch Classification (不一致分類)115116Compare surface contracts (Workflow 2) against actual contracts (Workflow 3) and classify every discrepancy.117118> Load `references/hidden_spec_patterns.md` for the full pattern catalog.119120Classify each mismatch into one or more of these 6 categories:121122| Category | Description | Example |123|----------|-------------|---------|124| **Naming Mismatch** | Function/variable name implies different behavior than actual | `keepTwoDecimal()` returns comma-formatted string |125| **Type Mismatch** | Return type or parameter type differs from expectation | Annotated as `float`, actually returns `str` |126| **Scope Mismatch** | Same-named identifiers exist in different scopes | `config` in module scope vs. `config` in function scope |127| **State Dependency** | Behavior depends on external mutable state | Result changes based on global cache content |128| **Environment Dependency** | Behavior varies across environments | Works in dev (SQLite), fails in prod (PostgreSQL) |129| **Hidden Side Effect** | Undocumented writes, mutations, or event emissions | `calculate_total()` also updates a database record |130131For each mismatch:1321. Rate **severity**: Critical / High / Medium / Low1332. Rate **likelihood of triggering**: High / Medium / Low1343. Identify the **blast radius**: what breaks if this mismatch causes a defect1354. Document the **evidence**: specific code lines, test results, or observations136137### Workflow 5: Reuse Feasibility Judgment (再利用可否判定)138139Determine whether each target can be safely reused and under what conditions.140141> Load `references/reuse_risk_classification.md` for the full classification framework.142143Apply the 5-level reuse classification:144145| Level | Verdict | Meaning | Action Required |146|-------|---------|---------|-----------------|147| **A** | Reuse as-is | Contracts match, behavior verified | Add contract test only |148| **B** | Reuse with wrapper | Core behavior is correct but interface needs adaptation | Build thin wrapper, add contract test |149| **C** | Reuse with adapter | Significant interface mismatch but logic is sound | Build adapter layer, add integration test |150| **D** | Contract test required first | Behavior is uncertain, need verification before deciding | Write contract tests, then re-evaluate |151| **E** | Do not reuse / redesign | Fundamental mismatch or unacceptable risk | Redesign or implement from scratch |152153For each reuse candidate:1541. Assign a reuse level (A-E)1552. Document the rationale with evidence from Workflow 41563. Specify guardrails: what callers must do (or never do) to use safely1574. Identify naming improvements if the current name is misleading1585. Record results in `assets/reuse_risk_register_template.md` and `assets/adoption_recommendation_template.md`159160### Workflow 6: Verification Design (検証設計)161162Design contract tests and verification strategies for critical implicit contracts.163164> Load `references/runtime_boundary_checklist.md` for boundary-specific test patterns.1651661. For each critical mismatch from Workflow 4, design a minimal contract test:167 - **What to verify**: the specific contract (return type, side effect absence, etc.)168 - **Minimal test case**: simplest possible test that would catch a contract violation169 - **Boundary data sets**: edge cases and environment-sensitive inputs170 - **Failure signal**: what a test failure means (which contract broke)171 - **Regression value**: how this test prevents future incidents1722. Prioritize tests by:173 - Severity of the mismatch (Critical/High first)174 - Blast radius of a contract violation175 - Ease of test implementation1763. Design environment-boundary tests for any Environment Dependency mismatches:177 - DB dialect tests (SQLite vs. PostgreSQL behavior)178 - Timezone tests (naive vs. aware datetime handling)179 - Serialization round-trip tests (JSON, pickle, protobuf)1804. Record all test ideas in `assets/contract_test_idea_template.md`1815. Connect each test back to the mismatch it guards against (traceability)182183## Resources184185| Resource | Type | Purpose | When to Load |186|----------|------|---------|--------------|187| `references/contract_extraction_guide.md` | Reference | Extraction methodology, evidence priority, behavior-first approach | Workflow 3 |188| `references/hidden_spec_patterns.md` | Reference | Full catalog of mismatch patterns with examples | Workflow 4 |189| `references/runtime_boundary_checklist.md` | Reference | Boundary-specific checklists for DB, serialization, timezone, retry, locale | Workflow 6 |190| `references/reuse_risk_classification.md` | Reference | 5-level reuse classification framework and decision criteria | Workflow 5 |191| `references/environment_behavior_guide.md` | Reference | Environment-dependent behavior patterns and verification strategies | Workflow 3, 6 |192| `assets/implicit_contract_sheet_template.md` | Template | Document stated vs. observed contracts with evidence | Workflow 2, 3 |193| `assets/reuse_risk_register_template.md` | Template | Risk register for reuse candidates | Workflow 5 |194| `assets/contract_test_idea_template.md` | Template | Contract test designs with data sets and failure signals | Workflow 6 |195| `assets/adoption_recommendation_template.md` | Template | Final reuse decision with guardrails and prerequisites | Workflow 5 |196197## Best Practices198199### Behavior Over Documentation200201- **Never trust names alone**: `formatCurrency()` might truncate, `isValid()` might have side effects, `getUser()` might return cached stale data202- **Never trust comments alone**: comments drift from code; the implementation is the only source of truth203- **Read callers before comments**: how existing callers use a function reveals the actual contract more reliably than what the docstring claims204- **Read tests before code**: test assertions encode verified behavior; passing tests are machine-checked contracts205206### Evidence Hierarchy207208When extracting contracts, prioritize evidence sources in this order:2092101. **Passing test assertions** (machine-verified behavior)2112. **Caller usage patterns** (real-world consumption reveals actual contracts)2123. **Implementation code** (the authoritative behavioral specification)2134. **Bug tickets and RCA reports** (documented contract violations)2145. **Type annotations** (may be outdated or incomplete)2156. **Comments and docstrings** (lowest priority; most likely to drift)216217### Systematic Boundary Awareness218219- Every time data crosses a boundary (function, module, service, DB, serialization), contracts can shift220- Pay special attention to: type coercion at boundaries, timezone handling at persistence layers, encoding changes at serialization points221- The most dangerous hidden contracts live at boundaries, not inside pure logic222223### Mismatch Taxonomy Discipline224225- Always classify mismatches using the 6-category taxonomy -- do not use vague labels like "bug" or "issue"226- A single finding may belong to multiple categories (e.g., both Naming Mismatch and Type Mismatch)227- Rate severity and likelihood independently -- a low-likelihood Critical mismatch still needs a contract test228229### Connect to Prevention230231- Every critical mismatch should produce at least one contract test idea232- Contract tests are not unit tests -- they verify the **interface promise**, not the internal logic233- Name tests after the contract they protect: `test_keepTwoDecimal_returns_numeric_not_string`234- Contract tests are the skill's primary deliverable for long-term value