Skip to content

v1.7.4 — Java Development Suite, Sub-Tasks, Semantic Refactoring

Latest

Choose a tag to compare

@Nefrols Nefrols released this 14 Mar 01:10

Release v1.7.4 — Java Development Suite, Sub-Tasks, Semantic Refactoring

Language / Язык: English | Русский


What's New

Java Development Suite

NTS now provides extended Java support beyond the general 12-language tree-sitter capabilities. Java gets dedicated high-level tools designed for maximum agent productivity with minimum cognitive load.

Profiler: High-Level API (nts_java_profiler)

Completely redesigned from 7-action lifecycle to 6 high-level actions:

  • discover — List attachable JVMs with PIDs, names, Java versions
  • profile — One call: attach → record → stop → parse → Markdown report
  • trace — Method-level timing/tracing with methodFilter (JDK 25+)
  • analyze — Re-analyze existing recording with different focus (saves tokens)
  • compare — Delta report between two recordings (before/after)
  • kill — Terminate a JVM process

Focus areas: cpu, cpu-time (JDK 25+), memory, contention, gc, io, or all.

Enhanced contention analysis:

  • JavaMonitorEnter — lock blocking (synchronized)
  • JavaMonitorWait — Object.wait() (notify-waiting)
  • ThreadPark — LockSupport.park (j.u.c.)
  • Contention call sites — where blocking actually occurs
  • Most blocked threads — ranked by total blocked time

Smart hints: NIO servers with empty IO data get NIO-specific guidance. ZGC with minimal pauses gets a pauseless collector note with memory tool suggestions.

Memory Analyzer (nts_java_memory)

New dedicated tool for heap and allocation analysis:

  • discover — List JVMs (independent from profiler)
  • snapshot — Instant class histogram via jcmd (milliseconds, no recording)
  • compare — Delta between two snapshots with auto leak verdict
  • alloc — JFR allocation recording — top types by rate with call sites

Leak detection workflow: snapshot → exercise code → snapshot → compare. Growth in compare = potential leak candidates.

Gradle Build Integration (nts_gradle_task)

  • Smart backend switching: gradlew → system gradle → auto-generate wrapper
  • Project initialization: task='init', initType='java-application'
  • Parsed output: compilation errors with file:line, test results with pass/fail/skip
  • Async builds with nts_process monitoring

Extended Java AST

  • Enum constants extracted as CONSTANT symbols in navigation
  • Constructor-aware rename — class rename automatically renames all constructors
  • Overload disambiguation via structured AST parameter matching
  • Symbol filtering: symbols(kind='method', brief=true) for compact output

Sub-Tasks for Parallel Agents

nts_init now supports sub-tasks for multiple agents working on the same codebase:

  • Parent calls nts_init() → receives parentTaskId
  • Sub-agent calls nts_init(parentTaskId=...) → isolated undo/redo stack
  • On success: nts_init(action='merge') → all edits become one grouped undo entry in parent
  • On failure: nts_init(action='rollback') → all edits reverted

Sub-tasks inherit workingDirectory/roots but have own tokens, TODO plans, and undo stack. CRC tokens prevent conflicts on same file regions.


Semantic Refactoring Overhaul

All 10 refactoring operations migrated to semantic resolution with SymbolHandle and ResolutionResult:

  • Rename: Byte-span rewrite (UTF-8 safe), overload-aware matching, constructor auto-rename for class renames, field scope guard against unrelated parameters
  • Extract Variable: Smart expression isolation from statements (variable declarations, return, if/while conditions, throw, yield)
  • Inline: Local variable fallback via AST scan when standard resolver doesn't index method-local vars
  • Delete: Default scope project when handleReferences='comment'|'remove' (was file)
  • Wrap: throw new RuntimeException(e) instead of e.printStackTrace() when wrapping return statements
  • Generate: options.overwrite=true to regenerate existing equals/hashCode/toString/builder
  • Change Signature: AST-rewrite of declarations and all call sites with automatic overload disambiguation

13 bug fixes across refactoring operations, verified by automated audit.


Code Navigation Improvements

  • Class vs constructor auto-resolution: References on Java classes no longer return "Ambiguous" error
  • Symbol filtering: kind parameter filters by symbol type (method, field, class, etc.)
  • Brief mode: brief=true outputs name + line only — reduces output on large files by 70%+
  • Strict mode: strict=true rejects fallback cursor resolution for safe autonomous edits
  • Structured contract: resolutionStatus, usedFallback, safeForAutonomousEdit, candidateCount

Schema & Hints Audit

Complete schema audit across all 21 tools:

  • nts_edit_file: operations[]/edits[] sub-schemas expanded with 4+ missing params each. path no longer incorrectly required.
  • nts_code_refactor: +6 missing params (codePattern, accessModifier, returnType, targetClass, position, continueOnError). Fixed catchTypeexceptionType. what enum completed.
  • nts_init: Added description param for merge action
  • nts_file_read: Added force to bulk item schema
  • nts_git: Added init to command description
  • nts_batch_tools: Removed unsupported affectedFiles[0] interpolation from docs
  • ContextTool: Phantom nts_worker_finish reference replaced with valid nts_todo(action='close')
  • EditFileTool: autoIndent propagates from top-level to operations[]
  • BatchToolsTool: $LAST/$PREV_END work after nts_file_manage(create)

Agent Context Memory (nts_context)

New tool for structured, task-scoped agent memory:

  • HUD notes (kind='hud_note') — always-visible reminders in every tool response
  • Context notes (kind='note') — durable findings for recovery after compression
  • Snapshot recovery — full task picture in one call (TODO, files, journal, notes)
  • CRUD API — add, read, update, delete, list
  • Cross-tool integration — other tools nudge agent to save durable findings via TIPs

Infrastructure

  • nts_context — structured task memory with HUD integration
  • SymbolResolver — semantic resolution with SymbolHandle and ResolutionResult
  • CodeNavigateTool — strict mode and structured confidence metadata
  • PathSanitizer — symlink protection, dynamic roots, infrastructure file unblocking
  • McpIntegrator — Codex CLI (TOML) and OpenCode support
  • GradleTool/VerifyTool — structured build error diagnostics
  • JsonUtils — shared ObjectMapper + NtsErrorCode structured errors
  • TaskContext — sub-task API (createSubTask, mergeSubTask, rollbackSubTask)
  • README — restructured (Quick Start at top, languages separated, Java Suite section)

Stats

  • 20 commits, 125 files changed, +22,296 / -2,520 lines
  • 33 new files (production + tests)
  • 21 MCP tools (was 19): added nts_java_memory, nts_context
  • 13 refactoring bug fixes, verified by automated audit
  • Schema fixes across all 21 tools

Что нового (RU)

Комплект инструментов Java-разработки

NTS теперь предоставляет расширенную поддержку Java поверх общих возможностей tree-sitter для 12 языков. Java получает выделенные высокоуровневые инструменты, рассчитанные на максимальную продуктивность агента при минимальной когнитивной нагрузке.

Профайлер: высокоуровневый API (nts_java_profiler)

Полная переработка с 7-action lifecycle на 6 высокоуровневых действий:

  • discover — Список подключаемых JVM с PID, именами, версиями Java
  • profile — Один вызов: attach → запись → stop → парсинг → Markdown-отчёт
  • trace — Трассировка методов с фильтром (JDK 25+)
  • analyze — Повторный анализ записи с другим фокусом (экономия токенов)
  • compare — Дельта-отчёт между двумя записями (до/после)
  • kill — Завершение JVM-процесса

Области фокуса: cpu, cpu-time (JDK 25+), memory, contention, gc, io, all.

Усиленный contention-анализ:

  • JavaMonitorEnter — блокировка на мониторах (synchronized)
  • JavaMonitorWait — Object.wait() (ожидание notify)
  • ThreadPark — LockSupport.park (j.u.c.)
  • Call sites блокировок — конкретные места в стеке
  • Самые блокируемые потоки — ранжирование по суммарному времени

Умные хинты: NIO-серверы с пустым IO получают NIO-подсказку. ZGC с минимальными паузами — подсказку о pauseless-коллекторе с рекомендациями memory-инструмента.

Анализатор памяти (nts_java_memory)

Новый инструмент для анализа кучи и аллокаций:

  • discover — Список JVM (независим от профайлера)
  • snapshot — Мгновенная гистограмма классов через jcmd (миллисекунды, без записи)
  • compare — Дельта между снапшотами с автоматическим вердиктом утечки
  • alloc — JFR-запись аллокаций — top типов по скорости с call sites

Workflow обнаружения утечек: snapshot → нагрузить код → snapshot → compare. Рост = кандидаты на утечку.

Gradle Build Integration (nts_gradle_task)

  • Умное переключение бэкенда: gradlew → system gradle → автогенерация wrapper
  • Инициализация проекта: task='init', initType='java-application'
  • Парсинг вывода: ошибки компиляции с file:line, результаты тестов с pass/fail/skip
  • Асинхронные сборки с мониторингом через nts_process

Расширенный Java AST

  • Enum constants извлекаются как символы CONSTANT в навигации
  • Constructor-aware rename — переименование класса автоматически переименовывает конструкторы
  • Disambiguация перегрузок через структурированные AST-параметры
  • Фильтрация символов: symbols(kind='method', brief=true) для компактного вывода

Под-задачи для параллельных агентов

nts_init теперь поддерживает под-задачи для нескольких агентов на одной кодовой базе:

  • Родитель вызывает nts_init() → получает parentTaskId
  • Суб-агент вызывает nts_init(parentTaskId=...) → изолированный undo/redo стек
  • Успех: nts_init(action='merge') → все правки = одна grouped undo запись в родителе
  • Неудача: nts_init(action='rollback') → все правки откатываются

Под-задачи наследуют workingDirectory/roots, но имеют собственные токены, TODO планы и undo стек. CRC-токены предотвращают конфликты на одних участках файлов.


Переработка семантического рефакторинга

Все 10 операций рефакторинга переведены на семантическое разрешение с SymbolHandle и ResolutionResult:

  • Rename: Byte-span перезапись (UTF-8 safe), overload-aware, авто-rename конструкторов, guard от unrelated параметров
  • Extract Variable: Умная изоляция выражений из statement-ов (объявления, return, if/while, throw, yield)
  • Inline: Fallback поиск локальных переменных через AST-скан
  • Delete: Scope по умолчанию project при handleReferences='comment'|'remove'
  • Wrap: throw new RuntimeException(e) вместо e.printStackTrace() при оборачивании return
  • Generate: options.overwrite=true для перегенерации существующих методов
  • Change Signature: AST-перезапись объявлений и call sites с disambiguацией перегрузок

13 багфиксов в операциях рефакторинга, верифицированных автоматическим аудитом.


Улучшения навигации по коду

  • Авторазрешение class vs constructor: References на Java-классы больше не возвращают "Ambiguous"
  • Фильтрация символов: kind фильтрует по типу (method, field, class и т.д.)
  • Компактный режим: brief=true — только имя + строка, сокращение вывода на 70%+
  • Strict mode: strict=true отклоняет fallback cursor resolution для безопасных автономных правок
  • Структурированный контракт: resolutionStatus, usedFallback, safeForAutonomousEdit, candidateCount

Аудит схем и хинтов

Полный аудит схем всех 21 инструмента:

  • nts_edit_file: operations[]/edits[] sub-schemas расширены на 4+ недостающих параметра. path больше не помечен как required.
  • nts_code_refactor: +6 параметров. Исправлено catchTypeexceptionType. Дополнен enum what.
  • nts_init: Параметр description для merge action
  • nts_file_read: force в bulk items
  • nts_git: init в описании command
  • nts_batch_tools: Убраны несуществующие affectedFiles[0] ссылки
  • ContextTool: Фантомный nts_worker_finishnts_todo(action='close')
  • EditFileTool: autoIndent пробрасывается в operations[]
  • BatchToolsTool: $LAST/$PREV_END после nts_file_manage(create)

Контекстная память агента (nts_context)

Новый инструмент для структурированной task-scoped памяти агента:

  • HUD-заметки (kind='hud_note') — всегда видимые напоминания в каждом ответе
  • Контекстные заметки (kind='note') — устойчивые находки для recovery после сжатия
  • Snapshot recovery — полная картина задачи одним вызовом
  • CRUD API — add, read, update, delete, list
  • Кросс-инструментальная интеграция — другие инструменты подталкивают к сохранению находок через TIPs

Инфраструктура

  • nts_context — структурированная память задачи с HUD-интеграцией
  • SymbolResolver — семантическое разрешение с SymbolHandle и ResolutionResult
  • CodeNavigateTool — strict mode и structured confidence metadata
  • PathSanitizer — защита от symlink, динамические roots, разблокировка инфра-файлов
  • McpIntegrator — поддержка Codex CLI (TOML) и OpenCode
  • GradleTool/VerifyTool — структурированная диагностика ошибок сборки
  • JsonUtils — shared ObjectMapper + NtsErrorCode
  • TaskContext — API под-задач (createSubTask, mergeSubTask, rollbackSubTask)
  • README — реструктуризация (Quick Start наверх, языки разделены, Java Suite секция)

Статистика

  • 20 коммитов, 125 файлов изменено, +22 296 / -2 520 строк
  • 33 новых файла (production + тесты)
  • 21 MCP-инструмент (было 19): добавлены nts_java_memory, nts_context
  • 13 багфиксов в рефакторинге, верифицированных автоматическим аудитом
  • Аудит схем всех 21 инструмента