corpus-atlas-ADR-002 - Method-Scoped AST Macro Comprehension, CompCert-Style IR Passes (Java -> Jlight -> Jminor), and Proof Obligations¶
Status: Accepted Date: 2026-10-28
Context¶
corpus-atlas-ADR-001 introduced brace-balanced method scope extraction (_extract_java_method_scopes) and 3-line class-level Zero-Open search cards (Signatures, Behavior, Practices / Intents). However, two structural comprehension and verification gaps remain when an LLM agent transitions from class discovery to method comprehension and code synthesis:
- The Context-Sensitive Automaton & Boilerplate Tax:
- As illustrated by context-sensitive parser theory (pushdown automaton + stateful symbol table) and real adapter classes such as
BukkitCommandRegistrar, ~60-75% of raw Java method tokens consist of repetitive defensive ceremony (try { ... } catch (RuntimeException | LinkageError e) { PlatformHookBitComponent.record... }, reflection lookups, and package-qualified types) rather than core control-flow intent. - Without a method-scoped AST projection, agents must still call
open(~3,200 B) to inspect a single method's control flow or verify how it discharges safety prohibitions (S-001..S-007). - CompCert-Style Verified Intermediate Representations (
Java <-> Jlight <-> Jminor): - In formally verified compilers such as CompCert (
C -> Clight -> Cminor -> RTL -> Asm), semantic preservation is proven across small, deterministic intermediate representation (IR) passes rather than across a single opaque leap. - For an LLM-facing AST tool to serve both comprehension (lifting verbose Java into a compact shorthand IR with explicit invariant proofs) and future shorthand-to-Java code generation (lowering shorthand IR back into verified Java), both directions must share the same canonical intermediate representations (
JlightandJminor), symbol-table slice, and proof obligations.
Decision¶
Extend corpus-atlas/build_doc_index.py, scripts/repo_ast.py, and corpus-atlas/mcp_server.py (repo_ast_context) with a Method-Scoped AST Macro Emitter, Jlight/Jminor Shorthand IR Lifter, and CompCert-Style Proof Obligation Analyzer addressable via Class#method, Class::method, or Class#*.
1. CompCert-Inspired Two-Pass AST Lifting (Java -> Jlight -> Jminor)¶
extract_java_method_shorthand_cards and _lift_method_body_to_shorthand_ir in corpus-atlas/build_doc_index.py lift raw Java constructor/method scopes through two deterministic passes:
- Pass 1 (Java -> Jlight, Lexical & Type Canonicalization):
- Strips comments while preserving exact 1-based source [start_line, end_line] spans (_strip_java_comments_preserving_lines).
- Canonicalizes method headers into typed functional signatures (<vis> [static] fn name(ParamType arg, ...) -> ReturnType) and strips inline package prefixes using the enclosing class's closed-world import table.
- Pass 2 (Jlight -> Jminor, Semantic Macro & Guard Folding):
- Folds defensive try { ... } catch (...) blocks that emit BIT telemetry or structured logs into @degraded_try(site=..., bit=...) { ... }.
- Folds empty or ignored catch blocks into @silent_try(catch=...) { ... } and flags them with an explicit @silent_catch_hazard macro.
- Folds single-statement guard branches (if (cond) { return x; }) into single-line Jminor guards (if (cond) return x;), compressing 40-line adapter methods into <= 14 lines of readable control flow.
2. First-Class Semantic Macro Catalog & Proof Obligations (_analyze_method_macros_and_proofs)¶
Every method scope extracted into scope_facets_json and query_context("Class#method") computes active semantic macros and explicit proof obligation statuses (DISCHARGED, AUDIT_GUARDED, GUARDED, VIOLATED):
| Macro Tag | Governing Invariant | Proof Obligation Rule |
|---|---|---|
@degraded_try("<site>") |
S-004, ADR-026 |
DISCHARGED when catch block records BIT telemetry (*BitComponent.record*) or logs via RTP.log. |
@rethrow_or_propagate |
S-004 |
DISCHARGED when catch block rethrows or completes future exceptionally. |
@silent_catch_hazard(<Ex>) |
S-004 |
AUDIT_GUARDED when catch block is empty or named ignored (requires non-critical probe justification). |
@reflect_lookup |
ADR-026 |
DISCHARGED if paired with @degraded_try in the same method scope; otherwise GUARDED. |
@folia_region_guard |
Rule F-001 |
DISCHARGED when Bukkit.isOwnedByCurrentRegion guards region-affined state access. |
@scheduler_dispatch |
Rule F-002 |
DISCHARGED when scheduling routes through RTP.scheduler or Folia regional schedulers. |
@async_chunk_io / @sync_chunk_hazard |
S-005 |
DISCHARGED on async chunk APIs; VIOLATED on unguarded synchronous .getChunkAt(...). |
@tracked_ticket |
S-002 |
DISCHARGED when chunk ticket registration/release routes through MemoryTracker / ChunkReservation. |
@api_require_init |
S-006 |
DISCHARGED when pre-init or invalid state fails closed via IllegalStateException. |
DAG Tier Boundary |
ADR-115 |
DISCHARGED when enclosing class imports respect its TIER_1..TIER_4 boundary; VIOLATED if Tier 1/2 imports org.bukkit.*. |
3. Cross-Domain Derivative Enhancements Beyond Signature Maps (e.g., Aider RepoMap)¶
Empirical analysis of existing repository mapping tools (such as Aider's Tree-sitter + PageRank RepoMap) and trial-and-error against LinearRegionReader and Region revealed four structural failure modes in naive AST summaries—and their compiler-theoretic solutions implemented in corpus-atlas:
| Bottleneck in Naive RepoMap / v1 Lifter | Cross-Domain Origin | Derivative Mechanism in corpus-atlas-ADR-002 |
|---|---|---|
1. Signature-Only Blindness (⋮ body elision) & Prefix Truncation |
Dafny / Boogie Weakest-Precondition Hoare Contracts & SSA Use-Before-Def (RAW) Safety |
Hoare Effect Frames (_extract_method_effect_frame) & @guard_throw Folding: Distinguishes Mutates, Reads, Locks, and Requires preconditions. Folds if (cond) throw new Ex(...) into @guard_throw(Ex, when: cond) and coalesces consecutive guards only when intermediate statements do not define variables referenced in cond (preventing Read-After-Write use-before-def hazards). |
2. Middle-Algorithm Truncation on Long Methods (80+ lines) |
Weiser (1984) Static Program Slicing & Program Dependence Graphs (PDG) |
Criterion Slicing (Class#method:var) & Salience Landmark Elision: _slice_ir_statements_by_criterion computes a brace-balanced 2-hop backward/forward data-flow slice for var (e.g., LinearRegionReader#getOrDecompress:regionCache). Default elision scores statements by landmark salience (@macro, synchronized, loops, field mutations, collaborator calls) rather than truncating after line $N$. |
3. Trivial Overload Shadowing & Getter Flood in Class#* |
Cyclomatic / Effect Salience Ranking | Overload Auto-Coalescing & Accessor Folding: Multi-overload lookups (LinearRegionReader#readChunk) automatically promote the highest-salience implementation and attach trivial delegators under Coalesced Overloads. Class#* ranks substantive methods first with [mutates:...; locks:...] badges and collapses 1-line getters/setters onto a single Collapsed Accessors / Delegators line. |
| 4. One-Way Comprehension vs. Verified Code Synthesis | CompCert Lowering (Cminor -> RTL) & Sketch/SyGuS Macro Expansion |
Bidirectional lower_jminor_to_java: Deterministically expands Jminor shorthand (fn, @degraded_try, @guard_throw, @api_require_init, @folia_region_guard) into standard Java 17, resolves closed-world imports, and re-runs _analyze_method_macros_and_proofs to certify S-00x proof obligations (~30-45% token reduction). |
4. Zero-Schema-Bloat MCP Surface (repo_ast_context)¶
repo_ast_context(scripts/repo_ast.pyandcorpus-atlas/mcp_server.py) natively accepts:Class#method(orClass::method): Emits a compact 4-line classGov(c)header plus the target method'sline_span,Coalesced Overloads,Hoare Effect Frame,Active Macros,Proof Obligations,Scope Symbol Table, andJminorShorthand AST block within the<= 40-line card budget.Class#method:criterion(orClass#method?slice=criterion): Emits the Weiser static data-flow slice ofClass#methodwith respect tocriterion.Class#*: Emits a salience-ranked table of substantive method scopes, effect frames, active macros, and proof statuses plus a single collapsed summary of trivial accessors/delegators.CorpusAtlasMcpServer._maybe_reload_code_modules: Automatically hot-reloadsbuild_doc_index.pyandrepo_ast.pyon diskmtime_nschanges so long-livedstdioMCP daemons never serve stale AST lifters.
5. Mechanical Attention Dilution Controls (Front 8)¶
To prevent transformer softmax attention dilution ($\text{softmax}(QK^T / \sqrt{d_k})$) and Lost-in-the-Middle context decay across multi-turn sessions, four mechanical filters operate across corpus-atlas/build_doc_index.py, scripts/repo_ast.py, and corpus-atlas/mcp_server.py:
1. Intra-Card Criterion-Scoped Metadata Intersection (extract_java_method_shorthand_cards): When a Weiser criterion (Class#method:var) is active, effect_frame (mutates, reads, consts, locks, requires) and resolved_symbol_slice (calls, fields, config_refs, throws) are intersected with the filtered statement block (-73.3% out-of-scope metadata items, 100.0% symbol/exception precision).
2. Stateful Session Working-Set Deduplication (CorpusAtlasMcpServer._update_session_attention): Tracks inspected classes in _working_set_classes (invalidated automatically when sync_dirty_files detects an edit). Subsequent Class#method queries on an already-active class emit a 1-line [Session Working Set: ... active @ turn #N — emitting method delta only] marker instead of repeating Path / Module, Gov(c), Hierarchy / SPIs, and Gradle Test Cmd (-26.6% follow-up method bytes, 0 duplicate Gov(c) headers).
3. Mechanical Cross-Tier & Turn-Cadence Attention Anchors ([⚡ ATTENTION ANCHOR]): When an agent transitions across ADR-115 DAG Tier boundaries (TIER_1_SPI_PURE -> TIER_2_CORE_DOMAIN -> TIER_3_PLATFORM_ADAPTER) or executes >= 8 tool calls since the last governance anchor, CorpusAtlasMcpServer injects a top-of-card [⚡ ATTENTION ANCHOR: Boundary Shift / Cadence Refresh] highlighting newly activated Gov(c) / S-00x invariants (100.0% anchor recall).
4. Search Score-Knee Tail Folding (format_search_markdown): Default capability searches (limit <= 8) render full zero-open cards for top hits and fold lower-salience tail hits (idx > 3 with score < 0.65 * top_score or idx > 5) onto a single Collapsed Low-Salience Tail Hits summary line (-30.0% search card bytes).
6. 6-Stage CEGAR Repair & Pluggable LLM-Oracle Side-by-Side Architecture (Front 9)¶
run_cegar_pipeline and compare_side_by_side_pipelines (corpus-atlas/build_doc_index.py, exposed via python3 scripts/repo_ast.py repair <target> --mode {heuristic,llm,hybrid,side-by-side}) decompose automated diagnosis and repair into 6 explicit stages while keeping a pluggable PluggableLlmProposalOracle slot:
1. Stage 1 (stage1_intent): Maps operator symptoms, stack traces, or broken Java/YAML snippets onto canonical intents with explicit confidence and abstention margin (margin_delta = score_1 - score_2).
2. Stage 2 (stage2_investigate): Resolves the ADR-115 Gov(c) neighborhood, DAG Tier, method-scoped Jminor card, and Gradle test command from doc-index.sqlite.
3. Stage 3 (stage3_judgment): Applies hard S-001..S-007 veto gates (DEFEND_INVARIANT_VETO on unsafe prompt/config requests), matches deterministic templates (REPAIR_TEMPLATE_MATCH), or triggers principled abstention (ABSTAIN_ESCALATE_TO_LLM) when confidence < 0.55, margin < 0.15, or out-of-catalog novel algorithmic synthesis is requested.
4. Stage 4 (stage4_suggest_fix): Runs either HEURISTIC_JMINOR_TEMPLATE / HEURISTIC_YAML_SOLVER (0 LLM calls, < 1 ms) or delegates to PluggableLlmProposalOracle (weak_llm, improved_llm Gemini-class, or custom HTTP llm_callable).
5. Stage 5 (stage5_test_fix): Deterministic proof-obligation, closed-world AST/YAML symbol allowlist, ADR-115 tier-import legality, and companion-key verifier (VERIFIED_PASS vs VERIFIED_REJECT).
6. Stage 6 (stage6_publish): Publishes only VERIFIED_PASS candidates (0 unsafe publishes), enabling hybrid_cegar to solve 75.0% (15/20) of the 4-regime adversarial benchmark with 0 LLM calls while routing the 5 abstained cases (1 zero-keyword metaphor + 4 novel algorithms) to the improved LLM oracle for a 100.0% (20/20) verified resolution rate (-75.0% LLM calls, -72.2% LLM tokens).
7. Pre-Derived $N$-Dimensional Positional Integer Lookup Network (Int16PositionalLutNetwork) & Morton Z-Order Curve (Front 10 & Front 11)¶
To eliminate the remaining colloquial, directional-polarity, and non-linear XOR blind spots of linear bag-of-words heuristics without incurring floating-point matrix multiplications or live LLM latency, Int16PositionalLutNetwork (mode=int_lut in corpus-atlas/build_doc_index.py) distills Stage 1/3 inference into an L2-cache-resident (66.9 KB) pure-integer lookup network (LUT-NN / NNUE / CMAC):
1. Factorized int16 Positional & Relational Tables (array('h')): Encodes 8 structural/sentence positional zones $\times$ 256 vocabulary buckets $\times$ 16 hidden accumulator dimensions (lut_pos_feat) plus 9 signed relative-offset polarity bins ($\Delta p \in [-4, +4]$) $\times$ 8 context masks (lut_rel_ctx).
2. 64-Bit Morton (Z-Order Space-Filling Curve) $N$-D Indexing (encode_morton_nd_int64 / decode_morton_nd_int64): Interleaves 4D AST/context coordinates (feature_family, async_or_reflect_flag, dag_tier, hazard_flag) into a single 64-bit integer key queried via bisect_left in $O(\log M)$ integer comparisons.
3. Zero-Float Integer Clipped ReLU (CReLU) Forward Pass (forward_int): Executes int16 table accumulation $\to$ bitshift scaling (>> 6) $\to$ CReLU clamping ([0, 127]) $\to$ int16 linear output dot-product in ~17-21 us median latency (0 float ops), raising Regime 2 colloquial metaphor recall from 75.0% to 100.0% (80.0% overall 20-case 0-LLM solve rate), relational polarity disambiguation (A > B vs B > A) from 25.0% to 100.0%, and non-linear XOR context disambiguation from 50.0% to 100.0% while preserving 100.0% clean abstention on Regime 3 novel algorithmic synthesis.
4. Corpus Log-Odds / PMI Distillation & Blind Holdout Generalization (Front 11, distill_mode="corpus_pmi"):
- Why the v1 Prototype Overfit: Auditing the initial overfit_prototype table exposed that its 72-word lookup dictionary scored 0.0% (0/6, logit=0) when benchmark words (chest, window, pops, click, caves, steep, climbs) were swapped for unseen synonyms (inventory, container, screen, select, hollows, precipices, ram, tps), and relied on negative weights on Regime 3 task words (kalman, pareto, backoff).
- Mathematical Distillation & Generalization Fixes: distill_mode="corpus_pmi" strips all benchmark cheat words (0 cheat words in _VOCAB_BUCKETS), normalizes tokens via _fast_morph_stem + domain concept equivalence groups, derives lut_pos_feat weights via smoothed Pointwise Mutual Information (compute_corpus_pmi_int16_weight), generalizes <inner/min/wake/center> vs <outer/max/sleep/radius> bound polarity across plugins, and routes unmatched technical stems to an Out-of-Catalog novelty bucket (BUCKET_OOC_CONTENT = 255). This raises blind zero-overlap lexical holdout accuracy from 0.0% (0/6) to 100.0% (6/6), cross-plugin LeafSleuth zero-shot transfer from 50.0% (2/4) to 100.0% (4/4), and seen + unseen novel-algorithm abstention from 75.0% (6/8 on ablated prototype) to 100.0% (8/8).
8. Whole-Class Shared-State Peer Index, Eraser Lock-Set Race Detection & Before/After PR AST Visualization¶
To surface concurrent data hazards across methods touching the same state and visualize structural AST deltas in pull requests:
1. Inverted Shared-State Matrix & Peer Cross-References (extract_java_shared_state_matrix, _compute_class_shared_state_matrix):
- Inverts per-method Hoare effect_frames (mutates, reads, locks) across all methods of a class into a field-indexed access matrix (writers, readers, common_locks, writer_common_locks).
- Attaches shared_state_peers to Class#method cards and supports Class:fieldName whole-class shared-state slicing via repo_ast_context("Class:fieldName").
2. Static Race-Hazard Proof Obligation (RACE-HAZARD / @shared_state_race_hazard):
- Cross-checks field declarations (volatile, final, Atomic*, Concurrent*, ThreadLocal, or non-thread-safe HashMap/ArrayList) against lock sets across all runtime accessors:
- LOCK_SET_MISMATCH: $\ge 1$ accessor acquires a lock while another runtime accessor mutates/reads the shared field with an empty lock intersection ($\bigcap \text{locks}(m_i) = \emptyset$), honoring the JCIP §3.1.4 cheap read-write lock pattern when writers share a lock on a volatile/thread-safe field.
- ASYNC_OR_REGION_UNSYNCHRONIZED: Shared non-thread-safe state accessed across @scheduler_dispatch / CompletableFuture or mixed @folia_region_guard scopes without a common lock.
- UNSAFE_COLLECTION_CONCURRENT_ACCESS: Non-thread-safe mutable collection (HashMap, LinkedHashMap, ArrayList, HashSet, TreeMap) mutated/read across methods in a concurrent class without a common lock.
3. Before/After PR AST Diff & Dual Visualization (python3 scripts/repo_ast.py diff & repo_ast_context("diff:<range>")):
- compute_java_ast_diff and query_ast_diff compare BEFORE vs AFTER Java sources (across git revision ranges, working-tree edits, or explicit --before-file / --after-file pairs), classifying methods as ADDED, MODIFIED, REMOVED, or PEER (unchanged methods sharing state with changed methods) and tracking new_race_hazards and resolved_race_hazards.
- Emits both a GitHub-comment-native ```mermaid flowchart LR diagram (render_ast_diff_mermaid) and high-resolution 3-column vector/raster diagrams via --svg <path.svg> (render_ast_diff_svg, 2400px logical canvas) and --png <path.png> (render_ast_diff_png, 3600px wide at default --scale 3).
9. Declarative Rule Engine, Unbounded Causal Contagion Scanner & Jminor Sequence Matching¶
To provide < 50 ms inner-loop static verification for AI-assisted edits without JVM compilation latency (python3 scripts/repo_ast.py rules and python3 scripts/repo_ast.py scan [target], or MCP repo_ast_context("rules:<profile>") / repo_ast_context("scan:<target>")):
1. Three Declarative Rule Primitives & Quality Profiles (BUILTIN_SCAN_RULES, SCAN_PROFILES, resolve_scan_rules):
- default Profile (High-Signal Blockers + S-00x): CAUSAL-RACE (lock-set mismatch + $N$-hop transitive unlocked mutation), CAUSAL-MAIN-IO ($N$-hop synchronous chunk/file I/O reaching main/region entry points, S-005), CAUSAL-LEAK (intra/inter-method unclosed Closeable / ChunkTicket across early-return/throw paths, S-002), CAUSAL-SILENT-FAIL (empty catch / .exceptionally(ex -> null), S-004), ARCH-DAG-TIER (ADR-115 cross-tier import ban + Tier 4 platform UI reinvention), and CAUSAL-NULL ($N$-hop @nullable_return dereference without null guard).
- strict / Optional Profile Rules (--profile strict or --enable-rule <ID>): OPT-CHECK-THEN-ACT (evaluated against the lifted Jminor statement sequence rather than flat Hoare sets, verifying identical receiver <recv> and identical key expression <key> inside the conditional branch without a lock), OPT-LOCK-ORDER-ABBA (intra/inter-method lock acquisition order inversion lockA -> lockB vs lockB -> lockA), OPT-INTERRUPT-SWALLOW (InterruptedException caught without interrupt()), and OPT-COGNITIVE-COMPLEXITY.
- Strict Declarative Custom Rules (.corpus-atlas-rules.json / --rules-file): Validates custom rule JSON objects (id, kind in {"METHOD_SCOPE", "CLASS_STATE", "CAUSAL_CHAIN"}, severity in {"BLOCKER", "WARNING", "INFO"}, callee_pattern, jminor_pattern, forbidden_import_pattern, include_tiers, exclude_tiers, discharge_macros) with zero Python code changes.
2. Unbounded Upward Contagion Propagation up to Discharge (_propagate_upward_contagion_chains):
- Propagates causal contagion tags upward along callers (reverse_call_graph via cycle-safe BFS, supporting 3..15+ pass-through wrapper hops) until each branch either hits an explicit discharge guard (@scheduler_dispatch, required common lock in CAUSAL-RACE, try-with-resources/finally in CAUSAL-LEAK, or != null check in CAUSAL-NULL) -> DISCHARGED, or reaches a top-level entry point -> VIOLATED.
- Renders both a GitHub-native ```mermaid diagram (render_causal_scan_mermaid with CAUSAL CONTAGION & PROOF CHAINS) and high-resolution --svg / --png (3600px wide) visualizations.
3. RacerD / Bi-Abduction Boundary Oracles (_extract_method_effect_frame, _compute_class_shared_state_matrix, evaluate_causal_rules_on_sources):
- Entry-Point Concurrency & Region Serialization: Single-threaded lifecycle entry points (<init>, <clinit>, onLoad, onEnable, onDisable) are discharged against runtime lock sets, and fields whose runtime accessors all carry @folia_region_guard (isOwnedByCurrentRegion) are discharged as serialized on the same Folia regional thread queue.
- Syntactic Access Path vs. Parameter Aliasing: Method parameters that shadow a class field name without referencing this.<field> are filtered out of effect_frame so local/parameter mutations are never conflated with shared this.<field> state.
- Closed-World SPI Dynamic Dispatch Bridge: Bridges Caller -> SPI#method -> ConcreteImpl#method across implements/extends edges so causal chains propagate seamlessly through interface boundaries.
10. Directional Jminor Dataflow/Taint Slicing, Call-Hierarchy Path Finder, and Auto-Hydrated Gate 1 Failure Triage¶
- Directional Dataflow & Taint Slicing on
Jminor(_parse_slice_criterion,_slice_ir_statements_by_criterion): - Extends intra-method slicing beyond undirected
Class#method:varwith explicit directional selectors:Class#method@slice_backward:<var>(or:<-<var>) computes the transitive backward def-use slice back to parameters, fields, and allocations;Class#method@slice_forward:<var>(or:-><var>) computes the transitive forward taint slice from<var>to state mutations, collaborator calls, andreturn/throwsinks;Class#method@slice:<var>computes the bidirectional union. - Structural Call-Hierarchy Path Finder (
path:ClassA#m1->ClassB#m2,query_call_path): - Resolves the shortest $N$-hop call and closed-world SPI dispatch chain between
ClassA#m1andClassB#m2(or class-levelpath:ClassA->ClassB) with per-hop line spans, Hoareeffect_framesummaries, and aggregated discharge/hazard macros (@scheduler_dispatch,@folia_region_guard,@tracked_ticket,@sync_chunk_hazard), honoring|tx=<id>RYOW shadow reads. - Auto-Hydrated
Gate 1Failure Context (log:<path>,query_log_summary): - Automatically parses JUnit failure headers and stack traces in
log:<path>to hydrate both the failingTestClass#testMethod@sourceassertion window and the top in-repoTargetClass#methodJminorIR +@sourceslice in a single digest (honoring|tx=<id>RYOW). - Deterministic IDE Autofixes & Structural Refactorings in
repo_ast_project(autofix,change_signature,extract_method): action="autofix"(apply_deterministic_autofixes): Deterministically resolvesENCODING-BOM(strips leading UTF-8 BOM),JAVA-STACKED-JAVADOC(collapses consecutive/** ... */blocks),PSI-MISSING-IMPORT(auto-inserts unambiguous repository imports viaSemanticTypeIndex.suggest_import_for_symbolwhile enforcingADR-115tier boundaries), andPSI-MISSING-IMPLEMENTATION(synthesizes@Overridemethod stubs with type-safe default returns).action="change_signature"(ShadowTxManager.propagate_change_signature): Atomically evolves a method signature across its defining interface/class, allSemanticTypeIndex.get_subtypesimplementors (@Override), and 1-hop dependent call sites (injecting default argument expressions= <defaultExpr>) inside a CoW shadow transactiontx.action="extract_method"(extract_java_method_from_span): Computes live-in parameters and the live-out return variable across a line sliceClass:Lstart-Lend, replaces the span with the helper call, and synthesizes theprivatehelper method immediately after the enclosing method.
Alternatives Considered¶
| Alternative | Why Rejected |
|---|---|
Adding a 7th standalone MCP tool (repo_ast_method) |
Inflates the persistent MCP tool schema token footprint; overloading repo_ast_context with Class#method and Class#* keeps the 6-tool < 650-token budget intact. |
Storing full shorthand_ir text for all ~12,000 methods in doc-index.sqlite |
Bloats SQLite storage; computing shorthand_ir on demand for the queried class in < 5 ms while caching macros and proof_obligations in scope_facets_json gives optimal speed and size. |
| Jumping directly to unconstrained shorthand-to-Java code generation | Without first establishing deterministic Java -> Jlight -> Jminor comprehension and proof obligations, an LLM cannot inspect or verify the target IR grammar it is expected to emit. |
Consequences¶
- Positive:
- Compresses 35-50 line ceremonial Java methods (such as
BukkitCommandRegistrar#resolvePluginCommandandBukkitCommandRegistrar#getCommandMap) into~10-14lines ofJminorIR with explicitS-00x/ADR-026/ADR-115proof badges in< 10 ms. - Establishes the exact
Jlight/Jminorgrammar, symbol-table slice, and proof-checking predicates required for subsequent shorthand-to-Java AST synthesis. - Negative / Trade-offs:
- Adds
line_span,macros, andproof_obligationskeys to per-method entries incode_ast_synthesis.scope_facets_json.
References¶
ADR-115(docs/adr/ADR-115-package-dag-disentanglement-and-decision-preservation-hypergraph.md)corpus-atlas-ADR-001(corpus-atlas/docs/adr/corpus-atlas-ADR-001-scope-preserving-ast-synthesis-and-zero-open-cards.md)corpus-atlas/build_doc_index.py(_analyze_method_macros_and_proofs,_lift_method_body_to_shorthand_ir,extract_java_method_shorthand_cards)scripts/repo_ast.py(query_context,format_context_markdown)scripts/tests/test_repo_ast.py