CLI extension composition
Status: composition and local process packages
The CLI has validated metadata, six shared built-in tool families, and explicitly installed local process packages. This is not a backend-free distribution or a runtime Java classloader. Numerical, graph and document dependencies have not yet been fully extracted from cli-main. Completed lightweight boundaries are kompile-graph-model and kompile-code-index-core, described below. The latter can index/query without model libraries, but neither makes the full CLI model-free.
Existing indexing, configured learning, launch behavior, endpoint selection, MCP profiles, permissions and product-policy freezes remain in place. A capability means installed implementation support, not a running model, compatible weights, backend readiness or permission to execute.
API and discovery
kompile-cli-plugin-api contains only JDK/Picocli production dependencies:
CliExtension: descriptor and optional command contributions.CliExtensionDescriptor: identity/version, API compatibility, provided/required capabilities, commands and tool ownership.CliToolDescriptor: tool/action requirements and conditional capabilities.CliExtensionCatalog: deeply immutable captured metadata; rejects duplicate extension/tool/command IDs, unsupported APIs and missing mandatory extension requirements before invoking contribution factories or command registration.
kompile-cli-tool-api adds the host-independent tool execution/provider contract. Its production dependencies are plugin-api/Picocli and Jackson, not CLI-main, CLI-common, graph engines, model libraries or JNI:
ExtensionTool<C>supplies tool metadata and execution.ToolInvocationContextexposes only session ID, working directory, cancellation, permission checking and path resolution; it does not expose the agent loop, model manager or host registry.CliToolProvidercontributesProvidedToolvalues usingToolProviderContext(endpoints, mapper, working directory and CHAT/MCP surface).ToolResult,ToolExecutionExceptionandMcpToolAnnotationsretain their existing FQNs for compatibility but are owned by tool-api.
New compiled providers implement CliToolProvider and register through the same CliExtension service entry. The host snapshots metadata, validates declared ownership/completeness before exposure, constructs factories lazily, and adapts portable tools through its permission, resolved-target mandate and cancellation checks. Providers may request additional permissions through their invocation context. Compiled Java providers are trusted in-process code, not a sandbox.
The existing host-specific CliToolExtension remains supported. Legacy CliTool keeps its concrete execute(JsonNode, ToolContext) method while extending the portable generic contract; ToolContext implements the narrow invocation interface. A provider must not implement both factory SPIs: that ambiguous composition is rejected. This API separation does not move the six heavy built-in families out of CLI-main or make its default registry model-free.
ToolProviderNativeImageTest independently compiles a service provider using only production tool-api classes and its runtime dependencies. It discovers metadata without constructing tools, then invokes a contributed tool on both CHAT/MCP surfaces, on a separate JVM and a real GraalVM21/Linux image. The explicit gate passed with all nine API/value/isolation tests (10 tests total, no skips); both processes emitted PORTABLE_TOOL_PROVIDER_NATIVE_OK. This proves the standalone provider contract, not full native CLI registration, host wrappers or native interactive permission enforcement. Custom extension types still need their own native reachability metadata when reflection is used.
To reproduce after installing plugin-api:
mvn -o -pl :kompile-cli-tool-api install dependency:build-classpath -DincludeScope=runtime -Dmdep.outputFile=target/native-runtime-classpath.txt
mvn -o -pl :kompile-cli-tool-api -Dtest=ToolProviderNativeImageTest -Dkompile.nativeImageExecutable=/path/to/graalvm/bin/native-image testLegacyToolBinaryCompatibilityTest compiles an explicit prior-ABI fixture and loads only its implementation against the actual current interfaces; it checks concrete and generic dispatch and unique ownership of the three moved value classes. The fixture runs javac in an owned, bounded subprocess: invoking the compiler API inside the full host JVM can accidentally load GraalVM build-time filesystem providers. The final 136-test host gate passed with no failures, errors or skips, including the legacy ABI fixture, portable-provider permissions/mandates/cancellation, catalog validation, registry and configured-learning regressions. This is JVM host coverage, not a substituted native-host proof.
CliExtensionDiscovery uses ServiceLoader<CliExtension>. Providers must already be on the JVM classpath or included in the native build. It does not scan plugin folders or load unknown Java code into a native executable. InstalledCliExtensions combines these providers with explicitly selected user process packages before a single metadata validation. Discovery never scans the working directory or starts plugin processes.
New-style command registration uses a staging Picocli root. Actual names, including aliases, must match declared names and cannot collide with the existing root. All contributions are validated before attachment. Extensions should use explicit services rather than depending on a concrete host root object. Legacy CliCommandRegistrar behavior remains unchanged.
Inspect metadata without constructing tools/loading models:
kompile extension
kompile extension builtin.code --jsonJSON includes runtimeReadinessChecked: false; inspection is not a model-readiness check. A catalog with selected process packages reports composition compiled-and-installed-process.
Explicitly trusted process packages
kompile extension install /path/to/package
kompile extension install /path/to/new-version --replace
kompile extension inspect demo --json
kompile extension remove demoInstallation copies a local directory without executing its programs. No network fetching or archive extraction is implemented. Immutable payload versions live at ~/.kompile/extensions/packages/<id>/<version>; an atomically published installed.json selects active versions. Replacement switches versions or selects identical existing bytes, never overwrites payloads. Removal deactivates selection but retains payloads for running sessions; automatic garbage collection is deferred.
The store rejects symlinks/nonregular files, traversal/absolute launch paths, malformed metadata, overlapping source/store directories and active command collisions. Size/depth/count bounds apply. Registry writes use a cross-process lock; capabilities and reserved host commands are rechecked against the actual staged selection under that lock. The owning user's installed directory remains trusted code, not a signing scheme or an OS sandbox.
A package contains extension.json and its executable/JAR, for example:
{
"schemaVersion": 1,
"apiVersion": 1,
"id": "demo",
"version": "1.0",
"timeoutSeconds": 60,
"commands": {
"demo-command": {"kind": "executable", "path": "bin/demo", "args": ["--cli"]}
},
"mcp": {"kind": "executable", "path": "bin/demo", "args": ["--mcp"]},
"tools": [{"name": "echo", "description": "Echo a message", "inputSchema": {"type": "object"}}]
}kind: jar uses an installed runnable JAR plus the existing Java runtime locator; executable packages need no plugin JVM. Launch argv is literal, with no shell or variable interpolation. Commands append caller arguments. Targets are revalidated inside their selected package. Children receive KOMPILE_EXTENSION_ID, KOMPILE_EXTENSION_VERSION and KOMPILE_EXTENSION_ROOT.
MCP tools are exported as mcp__extension_<id>__<name> with permission key mcp.extension-<id>. Metadata/schema lookup starts nothing. Execution checks normal permissions and resolved-target mandates before launching the existing MCP stdio client. All declared exports must match advertised object schemas, extra remote tools confer no authority, and nested custom-MCP loading is bounded. The strict schema path is opt-in; legacy MCP server normalization is unchanged. A malformed call result never establishes completion: post-dispatch transport/format failures remain unknown outcomes even after the worker is killed.
The bridge currently owns one short-lived process per invocation, including startup, timeout/cancellation and teardown. Do not move weight-loading inference or fine-grained per-node RPC loops onto this bridge: persistent/coarse-job lifecycle support must be qualified before heavy numerical migration.
Normal composition fails closed on invalid selected metadata. Root extension management loads compiled commands only, so a broken payload can be deactivated without loading it. A malformed selection registry itself still requires repair.
Tool ownership
| Extension | Tools |
|---|---|
builtin.code | code_search, code_graph, local_code_index |
builtin.knowledge | knowledge_search, knowledge_status, rag_search, graph_search |
builtin.graph | Existing graph CRUD/grounding/reasoning/analytics/process-mining family |
builtin.crawl | crawl_source, crawl_documents, crawl_discover, crawl_control, crawl_result |
builtin.model | model_runtime, subprocess_watchdog, chat-only vlm_model_definition |
builtin.pipeline | pipeline |
CliToolExtension and its small construction context currently live in the host module. The broad execution ToolContext has not been moved into plugin-api.
Both chat/exec and MCP use ToolExtensionLoader. Factories run lazily per family, after metadata validation. Returned IDs must be declared by that family and cannot be duplicated or silently dropped. Surface omissions must be explicitly declared by omittedTools (currently MCP's VLM definition omission). Existing order and routes are retained. Additional composed providers can add tools, but cannot shadow non-extension host tools. Chat retains the existing per-tool resource guards; MCP retains its existing registration/hooks/context wrappers.
Activation groups are presentation sets, not installation/dependency units. This slice does not remove all remaining non-extension registrations. It does not change stdio's trusted-tool permission model. Plugins are trusted code; a separate process is crash isolation, not an OS security sandbox.
Code intelligence and conditional learning
Structural parsing and the inspected ranked/blended retrieval paths do not invoke a text encoder. They now live in kompile-code-index-core. The host's index lifecycle still publishes a graph and can run configured graph learning; read-triggered maintenance can schedule it too. Production MEBN learning uses SameDiff. Nine store-agnostic graph DTO/contracts now live in kompile-graph-model, which has no production dependencies. Archive readers and inference/learning implementations remain in heavier modules.
- Explicit
code_graph learnrequiresgraph.learning. - Index/build/read maintenance may use learning when configured; it is conditional, not an unconditional structural-index prerequisite.
- Learning configuration inspection does not itself require a trained model.
- Querying persisted learned artifacts is distinct from retraining.
conditionalCapabilities entries named invoke describe tools without a named action. Metadata is diagnostic, not a complete pipeline planner or permission gate. Future extraction must evaluate configuration and artifact generations before work. Missing optional implementations must never silently discard requested learning.
Native-image qualification
Providers are registered under META-INF/services/ai.kompile.cli.plugin.api.CliExtension; the existing shade service transformer merges that resource. In-process providers and their native metadata must be present at image build time. Changing that implementation set requires a new conventional native image.
The opt-in native test compiles the actual discovery/command bridge and a service provider with only plugin-api and Picocli, builds with --no-fallback, then runs metadata lookup and execution of a contributed command handler. It does not load models or substitute a JVM. The fixture compiler is a separate toolchain process, so the full CLI test classpath's service providers cannot contaminate qualification.
/home/agibsonccc/dev-apps/mvn/bin/mvn -o -pl :kompile-cli-main \
-Dtest=CliExtensionNativeImageTest \
-Dkompile.nativeImageExecutable=/path/to/graalvm/bin/native-image \
-Dexec.skip=true testLogs/artifacts are under kompile-cli-main/target/native-extension-smoke. This qualifies the lightweight SPI/bridge, not the full CLI image or all built-ins.
ProcessExtensionNativeImageTest is a second opt-in gate. It builds an isolated native host from the actual manifest/store/command-runner sources with API and Jackson dependencies only, then compiles an unrelated C executable after that host image exists. The host installs its package and executes the selected managed target without rebuilding or loading Java plugin classes. This is a native process package/launch qualification, not full native CLI/MCP tool transport qualification.
/home/agibsonccc/dev-apps/mvn/bin/mvn -o -pl :kompile-cli-main \
-Dtest=ProcessExtensionNativeImageTest \
-Dkompile.nativeImageExecutable=/path/to/graalvm/bin/native-image \
-Dexec.skip=true testIt requires the native toolchain's adjacent javac and a C compiler (cc, override with -Dkompile.testCCompiler=...) on Linux/macOS. Native fixture logs are under target/native-process-extension-smoke.
ProcessExtensionProductionNativeTest is the production-image acceptance gate, enabled with -Dkompile.nativeCliExecutable=/absolute/path/to/kompile-cli-main. It compiles an independent C MCP worker after the image exists, installs its package in a private user home, inspects the descriptor, starts the real CLI mcp-stdio, checks the tools/list export, invokes tools/call, checks the returned plugin marker and child cleanup, then deactivates the package. Optional -Dkompile.nativeCliLibDirectory=/absolute/path/to/lib selects staged JNI libraries. The test terminates its owned host before closing a potentially blocked RPC reader; NativeProcessRpcCleanupTest exercises that failure path without a native build. A successful image build or isolated fixture alone does not satisfy this gate. The full CLI still has its broad dependency closure; graph-contract extraction alone is not a native remote-only distribution.
ProcessExtensionProductionNativeTest is the production-image acceptance gate, enabled with -Dkompile.nativeCliExecutable=/absolute/path/to/kompile-cli-main. It compiles an independent C MCP worker after the image exists, installs its package in a private user home, inspects the descriptor, starts the real CLI mcp-stdio, checks the tools/list export, and exercises successful tools/call, cancellation, and malformed-result/unknown-outcome behavior. Cancellation checks child termination and a fresh ping, with no late response for the retired request. Each scenario checks cleanup and deactivates its package. Optional -Dkompile.nativeCliLibDirectory=/absolute/path/to/lib selects staged JNI libraries. The host is terminated before closing a potentially blocked RPC reader; NativeProcessRpcCleanupTest exercises that failure path without a native build. Stdio retains its trusted-tool permission model; native interactive permission-denial coverage is not implied by this test.
The full CLI still has its broad dependency closure; graph-contract extraction alone is not a native remote-only distribution. The first CPU/GraalVM21 production image qualification used the existing reasoning artifact before the same-FQN model split; the split was then validated separately with current installed artifacts and CLI regressions. Repackaging/rebuilding the final native distribution against its new artifact topology remains a distinct release gate.
Graph-model extraction
kompile-graph-model owns these existing types with their package/FQN preserved: GraphEntity, GraphRelation, their two builders, SimpleGraphEntity, SimpleGraphRelation, TemporalInterval, ReasoningGraph and MutableReasoningGraph. Their production imports form a JDK-only closure. kompile-graph-reasoning depends on that module; temporal views, archive/query code, engines and numerical learners remain in reasoning. The model module has no compile/runtime dependency closure; inherited test dependencies are not part of its production artifact.
The three existing contract tests moved with the types (29 tests). Reasoning's remaining temporal tests (66 tests) still pass against the extracted model. When rebuilding the reasoning module after this source relocation, clean that Java module's target before installing it; otherwise stale class files can duplicate moved classes in both JARs. This is not an instruction to clean DL4J/native build trees.
This extraction changes artifact ownership, not code-index learning policy, projection generations, public graph packages, pretrained-model requirements, or subprocess routes. A CLI that still depends on reasoning/embedding/crawl is not model-free merely because the value types now have a lightweight module.
Structural code-index extraction
kompile-code-index-core owns 30 existing index/storage/search classes plus SearchExclusions, preserving their packages/FQNs. The boundary includes parsing, SQLite/FTS graph storage, compressed shard/fingerprint persistence, relation extraction, structural ranking/blended search, signatures, analysis helpers, watcher primitives and learning configuration. Ten existing test classes moved with those implementations. The core does not execute configured graph learning.
| Layer | Ownership / dependency |
|---|---|
| Structural core | Common/utils, Jackson and SQLite; no graph engine, encoder, DL4J or CLI-main dependency |
| CLI lifecycle | BackgroundIndexService, FileContextService, LocalCodeKGraphPublisher, CodeIndexCommand, CodeIndexGraphCommand, CodeIndexSessionBrief, CodeSearchEngine remain in CLI-main |
| Graph publication / learning | Host orchestration and existing learner implementations; configured triggers, generations and cancellation remain intact |
builtin.code tools | Host adapters still depend on the above layers; no standalone installable code-tool package is claimed yet |
Model-free does not mean JNI-free: the runtime closure still contains SQLite and Zstd, plus common logging/CLI utilities. Optional Git-derived ranking signals are unchanged; the native qualification passes a null optional root to disable those signals without invoking Git.
The module owns native reflection metadata for IndexFileStore.FileShard, IndexFileStore.FileFingerprint and CodeGraphReasoningConfig. Its standalone GraalVM21/Linux qualification compiled production classes and runtime-only dependencies, with no host/graph/model classes or substitute implementations. It indexed a real source file, reopened SQLite search and compressed shards, ran ranked/blended retrieval, and round-tripped an enabled learning configuration without executing a learner. The explicit native run and all moved/isolation tests passed: 231 tests, no skips. This is not native watcher/Git/learning qualification.
Reproduce the opt-in native core gate from the repository root after installing current common/utils dependencies:
mvn -o -pl :kompile-code-index-core install dependency:build-classpath -DincludeScope=runtime -Dmdep.outputFile=target/native-runtime-classpath.txt
mvn -o -pl :kompile-code-index-core -Dtest=CodeIndexCoreNativeImageTest -Dkompile.nativeImageExecutable=/path/to/graalvm/bin/native-image testAfter source moves, clear CLI-main's stale Java output before downstream tests; otherwise old target/classes or target/test-classes can mask the dependency boundary. Do not remove a qualified native executable or its staged lib directory just to clear Java output. StructuralCoreClasspathTest checks that all 31 moved classes have one definition owned by the new module and the seven lifecycle facades remain host-owned. After scoped Java-output cleanup, 124 downstream tests passed with no skips, including configured-learning/projection policy and process MCP success, cancellation and malformed-result handling. The process tests reused the previously built production image; they do not qualify its new artifact topology. Deploy this ownership change with a freshly assembled, dependency-inclusive bundle: incremental CLI-main-only overlays are insufficient. No installed distribution has been changed by these qualification runs.
Shared remote transport and request-only executable
kompile-cli-remote-transport owns working request-body assembly, JDK HTTP exchange and the OpenAI-compatible SSE decoder previously embedded in DirectLlmClient. The existing host now calls that implementation, retaining authentication, headers, provider-specific settings, usage normalization, classification, continuation and history policy. This is shared production code, not a copied alternate client.
kompile-cli-remote packages a thin kompile-remote request executable. Its complete runtime closure is transport/Jackson/Picocli/JDK, with no CLI-main, CLI-common, app-core, graph/model components, DL4J or JNI bootstrap. It sends one explicitly configured custom Chat Completions request with caller-owned prepared history. Returned tool envelopes are data and always report toolsExecuted: false. There is no agent loop, tool runner, MCP server or reuse of full chat configuration here; unsupported providers fail instead of being reinterpreted as custom endpoints. It is not a replacement for chat exec or the completed remote-agent goal.
Qualification: 19 transport + 11 CLI + 216 existing-host tests passed, plus one production-image test running 22 serialized invocations against loopback HTTP on the actual shaded JAR and GraalVM21/Linux binary (247 JUnit tests total, no skips). Blocked headers and blocked bodies are cancelled by closing the active future/body. Native build: 56 seconds, 2 GiB heap/two threads, 2.18 GiB peak RSS. The follow-up HTTPS gate then ran on a rebuilt production JAR/image: a fresh GraalVM21 image was qualified against loopback HTTP (RemoteNativeImageTest) and RemoteNativeHttpsTest verified trusted HTTPS with an explicit per-fixture trust store, untrusted-CA and hostname-mismatch rejection before any HTTP delivery, and body-deadline cancellation that closes the peer connection — both processes green, no global trust changes. Persistent model lifetimes and agent execution remain unqualified by these receipts. See request CLI usage.
The compatibility gate exposed missing actual-output flags in common stream and protocol failure handling (including the unchanged Codex route). History was checked before diagnosis. Output evidence is now captured before diagnostics and retained across continuations; the replay predicate was not weakened or changed back to checking diagnostic text. Both no-replay-after-output and admission-time failover tests pass. A stale adjacent ladder-status test was aligned with the already-established bare-wizard/explicit-status contract; production UI was unchanged.
The first safe agent-loop packet is an in-place extraction of the actual iteration driver and its tool-batch loop, not another loop implementation. That extraction is now in place: AgenticChatLoop contains a static IterationDriver with typed TurnState/ToolAttempt and TurnHost phase callbacks, and host classes (enforcer, deflection, direction, queue, approval, workflow) keep their policy bodies. Parity was proven behaviorally: AgenticChatLoopDriverParityTest passed 8/8 compiled against the preserved pre-refactor bytecode and 8/8 again after recompiling the refactored main, and the full 13-class pre-refactor harness passed 135/135 with no skips. Public API is unchanged; the driver is deliberately still host-coupled — its outgoing host types are not yet a closed lightweight module. The final remote-exec and release-image gates remain open.
The driver's outgoing wire value types were then extracted into a new dependency-free kompile-cli-chat-contract module (same config package, split only across modules): FailureKind, ProviderActivityListener, ToolCallOutput, ToolCallResultInput, ReplayedToolCallInput, AttachmentInput, ConnectivityEvent, TokenCountResult. StreamResult stayed on DirectLlmClient deliberately: it still carries OAuth grant, HttpHeaders and ClaudeNativeSession fields, so moving it would either duplicate the FQN (illegal in a split package) or drag auth/session types into the contract. Its strip-down is the follow-up boundary. The extraction re-validated 235/235 across parity, iteration, ladder, failover and attachment tests, and the downstream modules (tool-api, remote-transport, remote, code-index-core) build against the new topology.
Remaining extraction
- Extend process packages for persistent/coarse jobs and native interactive-policy qualification beyond the completed production stdio transport gate. Rebuild the release image against the final extracted artifact topology.
- Move host code-tool/lifecycle adapters behind explicit extension services, preserving generations, staleness, configured/background triggers and cancellation. Do not treat archive extraction as established: current archive APIs expose query-engine directions and materialize unified graphs coupled to learned embedding state.
- Launch native workers from their owning extension artifact. Host self-reexec is valid only when the requested worker is compiled into that host.
- Deliver a runnable remote-
execvertical slice using the existing agent loop: inject a direct-session contract and tool-provider assembly rather than entering the monolithicMainCommand. Separate local-serving transport/pool/bootstrap from remote configuration/client types. Its full source/dependency closure must exclude CLI-main, app-core, model-manager, embedding/crawl implementations and DL4J; merely adding SPIs or trimming a POM does not satisfy this gate. - Move actual graph projection, file-context archive queries and learning execution behind a code-runtime service with engine-free request/result types. Preserve generation checks, automatic receipts versus manual execution, superseded retries and configured triggers. Missing runtime must report unavailable, not disabled.
- Compose remote-agent installers/redeploy/doctor with backend
none. - Qualify full JVM/native distributions and process installation, permissions, schema parity, cancellation, launch failures and artifact compatibility.