Metadata-Version: 2.4
Name: sourcecode
Version: 1.31.0
Summary: Deterministic codebase context for AI coding agents
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other formats.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other transformations
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submit" means any form of electronic, verbal, or
              written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any Contributor
              Contribution constitutes direct or contributory patent infringement,
              then any patent rights granted to You under this License for that Work
              shall terminate as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, You must include a readable copy of the
                  attribution notices contained within such NOTICE file, in
                  at least one of the following places: within a NOTICE text
                  file distributed as part of the Derivative Works; within
                  the Source form or documentation, if provided along with the
                  Derivative Works; or, within a display generated by the
                  Derivative Works, if and wherever such third-party notices
                  normally appear. The contents of the NOTICE file are for
                  informational purposes only and do not modify the License.
                  You may add Your own attribution notices within Derivative
                  Works that You distribute, alongside or in addition to the
                  NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, copy, modify, merge,
              publish, distribute, sublicense, and/or sell copies of the
              Derivative Works, as separate terms and conditions for their use,
              reproduction, and distribution, or alongside or as supplement to
              any license terms for such Derivative Works as a whole, provided
              Your use, reproduction, and distribution of the Work otherwise
              complies with the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Liability. While redistributing the Work or
              Derivative Works thereof, You may choose to offer, and charge a fee
              for, acceptance of support, warranty, indemnity, or other liability
              obligations and/or rights consistent with this License. However, in
              accepting such obligations, You may offer such obligations only on
              Your own behalf and on Your sole responsibility, not on behalf of
              any other Contributor, and only if You agree to indemnify, defend,
              and hold each Contributor harmless for any liability incurred by,
              or claims asserted against, such Contributor by reason of your
              accepting any warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2024 sourcecode contributors
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: agents,ai,codebase,context,developer-tools,llm
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Utilities
Requires-Python: >=3.9
Requires-Dist: pathspec>=1.0
Requires-Dist: ruamel-yaml>=0.18
Requires-Dist: tomli>=2.0; python_version < '3.11'
Requires-Dist: typer>=0.24
Provides-Extra: ast
Requires-Dist: tree-sitter-javascript>=0.21; extra == 'ast'
Requires-Dist: tree-sitter-typescript>=0.21; extra == 'ast'
Requires-Dist: tree-sitter>=0.21; extra == 'ast'
Provides-Extra: dev
Requires-Dist: mcp>=1.0.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.15; extra == 'dev'
Provides-Extra: mcp
Requires-Dist: mcp>=1.0.0; extra == 'mcp'
Description-Content-Type: text/markdown

# sourcecode

**Deterministic, behavior-aware codebase context for AI agents and PR review.**

![Version](https://img.shields.io/badge/version-1.31.0-blue)
![Python](https://img.shields.io/badge/python-3.10%2B-green)

---

## What is it?

`sourcecode` analyzes a repository and produces structured JSON or YAML designed to be fed directly to AI agents or language models. It solves the "stuff the whole repo into the prompt" problem by extracting a deterministic, high-signal summary: stack detection, entry points, dependencies, git hotspots, inline annotations, and confidence metadata.

For PR review specifically, `sourcecode` extracts **execution paths**: ordered chains from entry point through service to data access, with runtime signals (auth guards, cache short-circuits, async execution) anchored to the specific step where they affect behavior. A reviewer sees _what the system does_ under this change, not just which files changed.

Optimized for Java/Spring Boot monorepos. Works on any codebase.

---

## Installation

### Homebrew (macOS / Linux)

```bash
brew tap haroundominique/sourcecode
brew install sourcecode
```

### pip / pipx

```bash
pip install sourcecode
# or with isolation:
pipx install sourcecode
```

### Verify

```bash
sourcecode version
# sourcecode 1.31.0
```

---

## Quickstart

```bash
# High-signal summary (1000–3000 tokens depending on repo size) — recommended starting point
sourcecode --compact

# Add git hotspots and uncommitted file count
sourcecode --compact --git-context

# Analyze a specific path
sourcecode /path/to/repo --compact

# Copy result to clipboard
sourcecode --compact --copy

# Structured output for AI agents (identity, entry points, dependencies, confidence)
sourcecode --agent

# Only process git-modified files (forces compact output)
sourcecode --changed-only
```

Example output for a Spring Boot project (`--compact`):

```json
{
  "project_type": "api",
  "stacks": [{ "stack": "java", "detection_method": "manifest", "confidence": "high",
               "primary": true, "frameworks": ["Spring Boot", "MyBatis"] }],
  "entry_points": {
    "bootstrap": ["src/main/java/io/spring/RealWorldApplication.java"],
    "security":  ["src/main/java/io/spring/api/security/WebSecurityConfig.java"],
    "controllers": { "count": 8, "sample": ["src/main/java/io/spring/api/ArticleApi.java"] }
  },
  "key_dependencies": [
    { "name": "org.mybatis.spring.boot:mybatis-spring-boot-starter",
      "version": "2.2.2", "risk_flags": ["spring-boot-2.x-eol"] }
  ],
  "language_version": "11",
  "deployment": { "spring_boot_version": "2.6.3", "packaging": "jar" },
  "mybatis": { "mapper_interfaces": 4, "xml_files": 4 },
  "confidence_summary": { "overall": "high", "stack": "high", "entry_points": "high" }
}
```

---

## Flags reference

| Flag | Alias | Default | Description |
|------|-------|---------|-------------|
| `--compact` | | off | High-signal summary (1000–3000 tokens): stacks, entry points, dependencies, risk flags, confidence, gaps. Includes `security_surface`, `mybatis`, and `transactional_boundaries` for Java projects. |
| `--agent` | | off | Structured noise-free JSON for AI agents: identity, entry points, dependencies, confidence, gaps. Auto-enables dependency, env-var, and code-notes analysis. |
| `--full` | | off | Remove truncation limits on `transactional_boundaries`, `mybatis.dto_mappers`, and other capped lists. |
| `--git-context` | `-g` | off | Include git activity: recent commits, change hotspots, and uncommitted changes. |
| `--changed-only` | | off | Limit output to git-modified files (staged, unstaged, untracked). Forces compact output. |
| `--depth` | | `4` | File tree traversal depth (1–20). Java/Maven projects auto-adjust to 12. |
| `--format` | `-f` | `json` | Output format: `json` or `yaml`. |
| `--output` | `-o` | stdout | Write output to a file instead of stdout. |
| `--copy` | `-c` | off | Copy output to clipboard after a successful run. No-op when `--output` is set or clipboard is unavailable. |
| `--no-redact` | | off | Disable automatic secret redaction. Output may contain sensitive values. |
| `--version` | `-v` | — | Show version and exit. |

---

## `prepare-context` — task-specific context

Generates a focused context bundle for a specific AI coding task. More targeted than `--compact`: each task re-ranks files according to its own signal priorities.

```bash
sourcecode prepare-context TASK [PATH] [OPTIONS]
```

### Tasks

| Task | What it surfaces | Primary use |
|------|-----------------|-------------|
| `explain` | Architecture, entry points, key dependencies | Onboarding an LLM to a new project |
| `onboard` | Full structural context: entry points, architecture, key files, dependencies | New developer or agent joining the codebase |
| `fix-bug` | Files ranked by risk (annotations, churn, uncommitted changes), suspected areas | Debugging session |
| `refactor` | Structural problems, improvement opportunities, high-annotation files | Code quality review |
| `generate-tests` | Source files without test pairs, coverage gap analysis | Writing missing tests |
| `review-pr` | Execution paths with per-step runtime signals, security/transactional impact, test coverage gaps | Pre-merge behavior review |
| `delta` | Changed files with multi-hop impact analysis, structural import graph, system-level impact summary | Incremental CI/review context |

### Options

| Option | Description |
|--------|-------------|
| `--since REF` | Git ref for `delta` task (e.g. `HEAD~3`, `main`, `v1.2.0`). Required for `delta`; ignored for other tasks. |
| `--symptom TEXT` | *(fix-bug only)* Keyword hint for the bug — boosts matching files and surfaces related code notes. |
| `--format TEXT` | Output format: `json` (default) \| `github-comment` (Markdown PR comment, `review-pr` only). |
| `--llm-prompt` | Append a ready-to-use LLM prompt to the output. |
| `--dry-run` | Show what would be analyzed without running it. |
| `--copy` / `-c` | Copy output to clipboard after a successful run. |
| `--output` / `-o` | Write output to a file. |
| `--task-help` | List all tasks with descriptions and exit. |

### Examples

```bash
# Explain the current repo
sourcecode prepare-context explain

# Focus on bug-prone files, with a symptom hint
sourcecode prepare-context fix-bug --symptom "NullPointerException in OrderService"

# Incremental context: files changed since branch diverged from main
sourcecode prepare-context delta . --since main

# Onboard with a ready-to-paste LLM prompt
sourcecode prepare-context onboard --llm-prompt

# PR analysis as a GitHub Markdown comment (paste directly into PR)
sourcecode prepare-context review-pr --since main --format github-comment

# List all tasks
sourcecode prepare-context --task-help
```

---

## `delta` — incremental impact analysis

The `delta` task is the recommended mode for CI pipelines and PR reviews. It goes beyond listing changed files: it builds a structural import graph and propagates impact transitively up to 3 hops.

```bash
sourcecode prepare-context delta [PATH] --since REF
```

**Output fields:**

| Field | Description |
|-------|-------------|
| `changed_files` | Files modified in the git range |
| `relevant_files` | Changed files + files pulled in by the import graph (scored by artifact type and hop distance) |
| `impact_summary` | Human-readable summary: artifact types changed and active risk areas |
| `affected_modules` | DDD domain modules touched by the change |
| `risk_areas` | Per-area severity breakdown (`security`, `api`, `persistence`, etc.) |
| `change_type` | Closed taxonomy: `behavioral_change`, `structural_change`, `configuration_change`, `dependency_change`, `security_change` |
| `system_impact` | Subsystems affected, behavioral changes, runtime impact notes |
| `dependency_graph_summary` | Verified structural import edges (hop 1–3) and `propagation_depth`. **Only real imports — no heuristics, no test files.** |
| `impact_score_per_file` | Per-file numeric impact score (0–1) |
| `since` | The git ref used |
| `gaps` | What the analysis could not determine |

**How the import graph works:**

1. Each changed file is classified by artifact type (`controller`, `service`, `repository`, `security`, `spring_config`, etc.).
2. A BFS traversal walks the import graph **repo-wide** (not restricted to the same module), up to 3 hops deep.
3. `dependency_graph_summary.edges` only contains verified `import` / `@Autowired` / constructor-injection relationships. Test files and heuristic proximity matches are excluded from edges (they appear in `relevant_files` only if they have real imports of changed files).
4. Score decays 30% per hop: a directly-changed `SecurityConfig.java` scores 0.90; its direct importer scores 0.63; a transitive importer scores 0.44.

```bash
# Changed service → controller → facade (3 hops)
sourcecode prepare-context delta . --since main

# Output includes:
# dependency_graph_summary.edges:
#   hop-1: OrderService.java → OrderRepository.java
#   hop-2: OrderRepository.java → OrderController.java
#   hop-3: OrderController.java → OrderFacade.java
# propagation_depth: 3
```

---

## `review-pr` — behavior-aware PR analysis

Extracts **execution paths**: ordered chains from entry point through service to data access layer, with runtime signals anchored to the specific step where they affect behavior.

```bash
sourcecode prepare-context review-pr [PATH] --since REF
# or against uncommitted working-tree changes:
sourcecode prepare-context review-pr
```

**`execution_paths` schema:**

```json
{
  "execution_paths": [
    {
      "name": "Order",
      "entry_point": {
        "step": "OrderController.createOrder",
        "notes": [
          { "note": "condition: authorization check present (@PreAuthorize / @Secured)",
            "epistemic_level": "STRUCTURAL SIGNAL" }
        ]
      },
      "path": [
        {
          "step": "ShippingService.process",
          "notes": [
            { "note": "branch: Spring cache annotation present — downstream call may be short-circuited",
              "epistemic_level": "STRUCTURAL SIGNAL" },
            { "note": "async: @Async annotation present — runs in separate thread",
              "epistemic_level": "STRUCTURAL SIGNAL" }
          ]
        },
        { "step": "OrderRepository.save", "notes": [] }
      ],
      "end_state": "DB write",
      "end_state_epistemic_level": "INFERRED (LOW CONFIDENCE)"
    }
  ]
}
```

**Path rules:**

- One path per changed entry point — most-evident downstream call, not all branches
- Each step requires direct code evidence: field injection, constructor param, method call, or type annotation
- `notes` are scanned from that step's own source file — no cross-contamination between steps
- Path terminates where evidence ends; no gap-filling by naming convention or module similarity

**Runtime signals detected per step:**

| Signal | Example code | Note emitted | Epistemic level |
|--------|-------------|--------------|-----------------|
| Auth guard | `@PreAuthorize`, `@Secured` | `condition: authorization check present (@PreAuthorize / @Secured)` | `STRUCTURAL SIGNAL` |
| Auth context read | `isAuthenticated()`, `SecurityContextHolder` | `condition: reads authentication context` | `STRUCTURAL SIGNAL` |
| Feature flag | `featureFlag.isEnabled()`, `FeatureToggle` | `condition: feature flag gates execution` | `INFERRED (LOW CONFIDENCE)` |
| Null/empty guard | `if (x == null) return` | `condition: null/empty guard with early return` | `STRUCTURAL SIGNAL` |
| Spring cache | `@Cacheable`, `@CacheEvict` | `branch: Spring cache annotation present — downstream call may be short-circuited` | `STRUCTURAL SIGNAL` |
| Manual cache | `cache.get()`, `cacheManager.` | `branch: manual cache lookup detected — downstream call may be short-circuited` | `INFERRED (LOW CONFIDENCE)` |
| Optional absence | `Optional<>`, `.orElseThrow()` | `branch: Optional type in use — result may be absent` | `STRUCTURAL SIGNAL` |
| Async thread | `@Async` | `async: @Async annotation present — runs in separate thread` | `STRUCTURAL SIGNAL` |
| CompletableFuture | `CompletableFuture`, `.supplyAsync()` | `async: CompletableFuture detected — non-blocking execution` | `STRUCTURAL SIGNAL` |
| Event publishing | `publishEvent()`, `applicationEventPublisher` | `async: Spring application event emitted` | `STRUCTURAL SIGNAL` |
| Kafka | `kafkaTemplate.`, `KafkaProducer` | `async: Kafka producer detected` | `STRUCTURAL SIGNAL` |
| RabbitMQ | `rabbitTemplate.`, `amqpTemplate.` | `async: RabbitMQ producer detected` | `STRUCTURAL SIGNAL` |

**Epistemic contract:**

Every output field in `review-pr` carries an explicit `epistemic_level`:

| Level | Meaning |
|-------|---------|
| `FACT` | Directly observed in diff (file present, config changed) |
| `STRUCTURAL SIGNAL` | Annotation or type-system evidence in source (`@Service`, `@Transactional`, injection) |
| `INFERRED (LOW CONFIDENCE)` | Heuristic pattern match — no full structural proof |
| `OMITTED` | Insufficient evidence — field not emitted |

No field blends certainty levels without labeling. `end_state` (e.g. `"DB write"`) is always accompanied by `end_state_epistemic_level: "INFERRED (LOW CONFIDENCE)"` — it is a keyword-match heuristic, not an AST-verified fact.

**Other `review-pr` output fields:**

| Field | Description |
|-------|-------------|
| `review_hotspots` | Top changed files ranked by impact score |
| `suggested_review_order` | Security → API → Service → Persistence → Config |
| `security_impact` | Changed security-classified files (`epistemic_level: STRUCTURAL SIGNAL`) + risk note (`INFERRED (LOW CONFIDENCE)`) |
| `transactional_impact` | Changed service/business-logic files with possible transaction boundary effect |
| `test_coverage_risk` | Changed source files with no corresponding test (`epistemic_level: INFERRED (LOW CONFIDENCE)`) |
| `affected_modules` | DDD domain modules touched by the change |

---

## Output schema

All outputs include a `confidence_summary` block with `overall`, `stack`, and `entry_points` confidence levels (`high` / `medium` / `low`), plus an `analysis_gaps` list describing what could not be analyzed and why.

### Java/Spring-specific fields

When a Java manifest (`pom.xml` or `build.gradle`) is detected, the output includes additional fields:

| Field | Description |
|-------|-------------|
| `language_version` | Java version from `maven.compiler.source` or equivalent |
| `deployment.spring_boot_version` | Spring Boot version |
| `deployment.packaging` | `jar` or `war` |
| `deployment.app_server_hint` | `weblogic`, `wildfly`, etc. (when detectable) |
| `security_surface.resource_names` | Values of `@M3FiltroSeguridad(nombreRecurso=...)` annotations across all controllers |
| `mybatis` | Mapper interface / XML file pairing summary |
| `transactional_boundaries` | Classes annotated with `@Transactional` |
| `deployment_risks` | Static risk flags: `spring-boot-2.x-eol`, `legacy-java-runtime`, `legacy-app-server-deployment` |

---

## Telemetry

Anonymous, opt-in telemetry collects: version, OS, commands used, flags, duration, repo size range, and errors. No source code, paths, secrets, or output content is ever collected.

```bash
sourcecode telemetry status    # current setting
sourcecode telemetry enable    # opt in
sourcecode telemetry disable   # opt out (permanent)
```

Alternatively, set the environment variable:

```bash
export SOURCECODE_TELEMETRY=0
```

---

## Configuration

```bash
sourcecode config    # show version, config file path, telemetry status
```
