Release v1.7.4 — Java Development Suite, Sub-Tasks, Semantic Refactoring
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_processmonitoring
Extended Java AST
- Enum constants extracted as
CONSTANTsymbols 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
projectwhenhandleReferences='comment'|'remove'(wasfile) - Wrap:
throw new RuntimeException(e)instead ofe.printStackTrace()when wrapping return statements - Generate:
options.overwrite=trueto 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:
kindparameter filters by symbol type (method, field, class, etc.) - Brief mode:
brief=trueoutputs name + line only — reduces output on large files by 70%+ - Strict mode:
strict=truerejects 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.pathno longer incorrectly required. - nts_code_refactor: +6 missing params (
codePattern,accessModifier,returnType,targetClass,position,continueOnError). FixedcatchType→exceptionType.whatenum completed. - nts_init: Added
descriptionparam for merge action - nts_file_read: Added
forceto bulk item schema - nts_git: Added
initto command description - nts_batch_tools: Removed unsupported
affectedFiles[0]interpolation from docs - ContextTool: Phantom
nts_worker_finishreference replaced with validnts_todo(action='close') - EditFileTool:
autoIndentpropagates from top-level tooperations[] - BatchToolsTool:
$LAST/$PREV_ENDwork afternts_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 параметров. Исправлено
catchType→exceptionType. Дополнен enumwhat. - nts_init: Параметр
descriptionдля merge action - nts_file_read:
forceв bulk items - nts_git:
initв описании command - nts_batch_tools: Убраны несуществующие
affectedFiles[0]ссылки - ContextTool: Фантомный
nts_worker_finish→nts_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 инструмента