lsp implementation
The five file-targeted tools use file_path: LspDiagnostics, LspGoToDefinition, LspFindReferences, LspHover and LspDocumentSymbol. LspWorkspaceSymbol searches by query and has no file target. The file argument passes through lspPath; host paths use host authorization, managed paths use guest POSIX rules, and computer paths use the selected target's OS rules. Protocol URIs use that same OS, including Windows drive and UNC paths. Document identifiers normalize drive-letter case and equivalent percent encoding before matching diagnostic publications. The tool schema baseline pins the new names without old-name aliases.
Declared HTTP patterns
The pure src/apiContract.ts exports apiRoutes for the three root-mounted registrations and compiles
to dist/apiContract.js. Descriptors own method, mount, access, summary, canonical Zod inputs or null,
existing credential policy and JSON transport; src/api.ts spreads them. No manager, installer,
handler or startup code enters the contract module.
The shared command schema runs lazily after manager selection. Missing, nonstring or blank commands retain the original 400 response; a nonblank command is not trimmed before exact server lookup. Malformed JSON still throws synchronously through the existing HTTP error boundary; it is not swallowed by a promise catch. Status has explicit null inputs. Account/admin admission, known-package mapping, selected-target lifetime, release-before-removal and unavailable-provider responses are unchanged.
The source manifest declares core 0.30.47 and shared API 16; that core floor alone does not prove the coordinated archive's contracts. Core matches GET /brain/lsp, POST /brain/lsp/install and POST /brain/lsp/uninstall as complete patterns. An undeclared suffix returns dispatcher 404; handlers receive an empty req.path and need no exact-path wrapper. Core retains user access for status and administrator access for package mutations. LSP retains manager availability and command validation.
Module ownership
Path resolution, allowed roots, access scope, administrator admission and manager selection await the live host authority. Tools and after-edit diagnostics finish these checks before acquiring a language server; asynchronous denials never become a host-path fallback.
Conversation settlement fences acquisitions in the existing slot map. When no slot exists yet because a path guard is still resolving, settlement records a null slot; the late acquisition consumes that fence and returns without constructing a manager. Existing builds retain their slot-identity fence. Service stop clears the map after cleanup, including settlement fences for conversations that never acquire. The settlement and reclamation release is contributed through registerSessionLifecycle({ releaseSession }); the lsp control keeps only diagnosticsEnabled, and the contribution adds no tool, file or process authority. Process cleanup uses the existing diagnostics service with scope: 'process' and disposeSync, not a plugin-owned process listener. The core service runner starts it in daemon and runner processes and awaits its ordinary stop. Its synchronous exit fallback fences new acquisitions and attempts disposal of inventory, active managers and managers in pending or failed releases, including scope replacement. The slot transfers its manager into the existing unconfirmed ownership before the first release await. Ownership ends only after confirmed close; synchronous disposal does not acknowledge asynchronous release or remote lease cleanup. SIGKILL cannot run this JavaScript fallback.
The manager's existing closing records carry both awaited close and synchronous disposal. Ordinary disable/shutdown joins pending closes and retains the existing failure/retry policy; final disposal retries those same owned transports immediately, continues after individual failures and reports the aggregate. It does not create another process registry.
registerSurfaceFact('brainStatus') publishes one generic chatRailSections entry: section lsp, data { enabled }, and CLI { title: 'LSP', text: 'Active' | 'Inactive', tone: 'success' | 'muted' }. The host stamps the registered plugin owner and applies its normal access filtering. The provider reads diagnosticsEnabled at request time, acquires no manager and emits no lspEnabled field. The existing browser renderer receives the unchanged { enabled } payload; core need not interpret the LSP setting.
Host root discovery and workspace filtering use realAbs and realPathWithin from elowen/dist/plugins/pathUtils.js. Core owns canonicalization, resolving existing ancestors of missing targets and rejecting dangling symlinks and non-ENOENT resolution failures. The plugin keeps project-marker discovery in src/paths.ts: LspManager calls projectRootForFile(path, boundary) before acquiring a server, never walks above the selected permitted root and never promotes an unbounded file to the filesystem root. Without a marker it uses that boundary or the file's own directory, never the daemon's working directory. Relative host candidates use the current turn's workDir. Containment selects scope, not access: file tools still enforce assertPathAllowed, and scoped non-admin sessions cannot perform unbounded symbol searches. Managed and connected-computer paths retain their target-side namespaces and injected path operations; host realpath is never used for them.
src/manager.ts owns acquisition, diagnostics queues, cancellation, crash budgets, idle eviction and unconfirmed closing attempts. Its diagnostic and intelligence outcomes share one failure-reason type, with no-response reserved for diagnostic checks. src/format.ts renders those outcomes and the raw location, hover and symbol results for src/tools.ts and src/afterEdit.ts. Diagnostic and intelligence explanations retain their distinct wording; diagnostics show up to 20 entries, locations and workspace symbols up to 30, and document symbols up to 50 per level.
src/client.ts owns the protocol, document versions and the document LRU cache. Both diagnostic checks and intelligence requests use its private document preparation operation, which creates the next version and invalidates the previous confirmed verdict without pushing that document. Diagnostics register their waiter before sending didOpen or didChange; intelligence requests send the prepared document before their request. Unchanged confirmed diagnostics and unchanged intelligence documents retain their separate cache checks. New documents evict the oldest idle entry and send didClose; active diagnostic documents remain protected until their checks settle.
All six tools in src/tools.ts wrap their final text with textResult(text) from elowen-plugin-shared/toolResult, producing one text block and empty details. Formatting, position validation, path refusals and stopped-manager wording stay in the plugin. The shared helper performs no I/O or error classification; existing caught path errors remain text and uncaught manager or transport failures still propagate.
Managed file reads
managedLspScope resolves the authoritative mount through Sandbox.projectFileRoot({project, accountUserId}). A turn's existing currentAccess().workRoot, when supplied, selects its managed work root instead. The resolved root is passed into ManagedLspManager and used for inventory cwd, server cwd, initialize rootUri/workspaceFolders, file-tool boundaries and cold LspWorkspaceSymbol searches; /workspace is not a fixed root. Conversation slot and diagnostic scope keys include the root, so a rename or work-root change retires the previous server even if the runtime generation is unchanged. API inventory probes use the same resolver. These roots select an LSP workspace, not a new filesystem isolation boundary between Project members. Provider, account and generation checks remain live, and unavailable root resolution propagates rather than launching on the host.
ManagedLspManager reads source with readGuestFile(files, guestLspPath(path), { maxBytes: GUEST_FILE_CHUNK_BYTES }) from elowen-plugin-shared/guestFiles. The 512 KiB language-server read limit remains unchanged. The client owns bounded paging, one content version and final multi-page validation. Its callback resolves and checks the live Sandbox authority on every operation, preserving the selected Project, acting account and expected runtime generation. Missing Sandbox or revoked access fails the request; the plugin constructs no guest operation literals. Process preparation, lease cleanup and protocol handling retain their existing owners. The source manifest requires core 0.30.47 and shared API 16; release acceptance must verify the shared client in the paired core archive. Editor and OneDrive consume the same shared client.
Local execution boundary
ManagedLspManager owns both managed and paired-computer streams. A local conversation selects it with { kind: 'local', projectId } and the authenticated account: the ref names the paired computer's Project, and core resolves that Project to the device. Its slot is isolated by conversation, account, Project and working directory. Automatic checks and all six tools resolve the same slot. Pending diagnostics carry that scope too, so switching account, computer or directory cannot deliver another scope's verdict.
The manager resolves Sandbox live before file reads, inventory, process preparation and warm workspace queries. localLspScope awaits the host's access descriptor, account, target metadata and working directory. The slot and API probe pass this resolved scope into the manager constructor; construction never reads asynchronous host authority synchronously. resolveLocalTarget supplies OS, connection and device metadata; its projectId must be the ref's Project, so a provider answering for another computer is refused before the first read or launch. localTargetPath from elowen-plugin-shared/localExecution supplies path semantics. The conversation's computer working directory is the workspace root; a file outside it uses its own directory. No computer path passes through daemon filesystem canonicalization or host marker discovery. The target authorizes each operation; lexical containment only selects the language-server workspace.
Source reads bind readGuestFile to Sandbox.localFiles({ target, accountUserId, sessionId, operation }) with the same 512 KiB limit as managed reads. Processes use Sandbox.prepareExecution({ projectRef, command: { type: 'argv', file, args }, cwd, leaseKind: 'protocol' }). The purpose is semantic, not an authority declaration: protocol is the argv protocol process purpose shared with MCP, and it adds no tool, file or shell mutation. Only a mode: 'local' stream for that Project and account is accepted. LSP reuses the managed session's framed stdin/stdout, heartbeat and confirmed cleanup. The server receives processId: null: the daemon PID cannot supervise a process on another computer. No alternative host launch is attempted.
Inventory and package changes execute on the computer through Sandbox.runCommand with the same semantic protocol purpose, Project, account, timeout, output bound and lease authority as the server launch. Windows queries PowerShell's application and script lookup and parses a JSON array; POSIX computers use sh and command -v with a bounded, allowlisted line list. Managed inventory retains its Python probe. Missing binaries remain an explicit not-installed result. The local executor owns Windows argv handling, including npm command shims; the LSP plugin does not wrap stdio in a second shell transport.
Socket loss ends the admitted stream, rejects its pending requests and releases its lease. A later explicit call may create a new server; no lost request or package mutation is replayed. An install/uninstall failure with an unknown outcome propagates unchanged. Conversation settlement, abort, idle expiry, target replacement and plugin shutdown retain the existing teardown path. There is no persistent local server record to restore after daemon restart. Without Sandbox, an account, a conversation binding or a connected target, local LSP is unavailable and never uses the daemon's files or binaries.
tests/lspLocalTarget.test.ts uses fake local process and file transports for tools, diagnostics, Windows URIs, scope replacement, authorization changes, cancellation, disconnect and unknown package outcomes. Core must admit LSP leases and keep the original process stream alive between turns. Release validation must also exercise npm shims and byte-preserving UTF-8 stdio on an actual Windows client.
Process integration verification
Managed inventory fixtures use tests/helpers/managedSession.ts::childSession. An EventEmitter child closes its PassThrough stdout and stderr when it emits close, supplying the EOF that a real ChildProcess owns. The host command runner waits for both output streams to drain as well as the exit verdict before releasing its lease; long-lived language-server fixtures retain open streams until their own close event. Real child pipes are never ended by the helper. The scripted language server discards a queued reply when cancellation has already ended its stdout, matching a terminated process rather than writing after EOF.
The dependency-free lspProcessServiceOwner.mjs fixture loads explicitly selected plugin and core service-owner entries. It starts runner-scoped services, opens a scripted Node stdio server with a descendant, then exercises orderly stop and forced exit while the first termination remains pending. The test captures the process tree and verifies every captured descendant exits. The source test uses the existing candidate resolver; release validation must repeat against the matched built entries and run the real-loader registration suite. Source success is not artifact-parity proof.
The real TypeScript runner-death integration test requires an existing installation selected with ELOWEN_LSP_DIR. Run tests/lspProcessLifetime.test.ts with that variable set after building this plugin; it checks semantic diagnostic 2322 and the exit of every captured descendant. Without an explicitly selected installation, that integration test is not run. The dependency-free process-group test always runs.
Server inventory and diagnostics bounds
Host install, uninstall, inventory probes and conversation server spawn use the same explicit npm prefix, join(ctx.dataDir(), 'npm'), through the existing manager spawn/exists dependencies. That prefix wins before PATH; administrator-installed toolchains on PATH remain available. Standalone resolver/transport callers that omit the prefix use PATH only. No runtime lookup reconstructs the old prefix from HOME or the instance root. Existing installations require the separately controlled offline prefix move before activation; runtime has no dual lookup.
The source checkout provides node plugins/lsp/scripts/migrate-prefix.mjs --source <absolute-old-prefix> --destination <absolute-new-prefix> for that offline move. Stop every owner of both prefixes and exclude concurrent writers before running it; this is an operator precondition, not a process-discovery or locking feature. Both paths must be absolute and disjoint, the destination parent must already be a real directory, and the destination itself must not exist, even as an empty directory or symlink. The source must be a real POSIX npm prefix with lib/node_modules and optional bin. The command validates top-level packages against the actual server catalog, their manifests and package-owned relative executable links; package payload contents remain opaque rather than recursively audited.
The only mutation is a same-filesystem directory rename. There is no cross-device copy fallback, destination overwrite, install, deletion or runtime discovery. A missing source reports source-missing, not a completed migration. Do not create the destination beforehand. If activation is separately authorized, verify the inventory and a real diagnostic afterwards; synthetic prefix fixtures do not prove runtime acceptance. To roll back, stop all owners again and reverse the two explicit paths with the old destination absent and the same filesystem constraint. This moves the entire current prefix back; it does not undo package changes made after the original move or restore an earlier snapshot.
Managed Projects and paired computers use their target's environment unchanged. A missing server skips that language for the request. The plugin installs the npm-based TypeScript, Pyright, Intelephense, YAML and Bash servers through its administrator-only /lsp picker and existing package routes; Go, Rust, Ruby, PHP, C/C++ and Lua servers come with their language toolchains. Core setup does not install a language server. In managed Projects, servers run in that Project's environment, separately for each account.
Diagnostics that wait for a conversation's next turn are kept for up to 20 files, and up to
50 conversations keep such pending results. Automatic checks consume file.changed after committed content writes and after existing tool hooks, using only the resolved path in the active target's namespace. Tool names, parameters and result-success fields are not inspected. Refused/no-op writes emit no event; this is not an OS watcher and external edits are checked only when a tool asks. Checks are non-blocking, session- and target-scoped, deduplicated, withdrawn after a clean verdict and cleared on session release. Unexpected background check failures are logged locally. If managed environment lookup fails, the host logs that failure and the successful edit remains unaffected.
Each durable conversation, including a delegated child, owns at most one server, acquired in the process executing that conversation. Changing the project root or the server language cancels old diagnostics and releases the old server before the replacement. Final run settlement, abort and session disposal release the whole process tree; a settle attempt that requests continuation does not. A release resolves only after every server it owns is confirmed closed. If one close fails, that release is rejected and the server stays tracked: the conversation continues with a new server, and the next release retries the unconfirmed one. The idle sweep runs every five seconds.
The TypeScript language server uses TypeScript 5.x with a 1024 MiB old-space allowance and no
separate syntax server. Automatic typings acquisition stays enabled for JavaScript projects.
The plugin declares no live configuration, so a saved setting or the /lsp toggle applies
after the restart it requests.
Next: Project Editor