feat(studio): improve compiler reliability and AI diagnostics
Preserve structured diagnostics, source attribution, phase outcomes and revision context through compiler, Studio, LSP, MCP and JavaFX. Add project service discovery and resilient VS Code reconnection. Correct all eight reproduced PBS production failures in expression context, sibling executable bindings and nominal owner identity. Consolidate specs, lessons, immutable baseline evidence and the maintained source-to-guest qualification runner. Validation: required Gradle gate recorded 724 tests, with 711 passed and 13 skipped. Full corpus passed 168 compilation observations and 108 guest runs (104 successes and four deliberate faults); supplemental controls passed 42 compilations and 16 guest runs. TypeScript compilation, two Node discovery tests and discussion validation passed.
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import { readFileSync, realpathSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export type Endpoint = { host: string; port: number; projectRoot: string; sessionId: string };
|
||||
|
||||
export function readEndpoint(root: string): Endpoint | undefined {
|
||||
const canonicalRoot = realpathSync(root);
|
||||
let text: string;
|
||||
try { text = readFileSync(join(canonicalRoot, ".studio", "lsp.json"), "utf8"); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
||||
const value = JSON.parse(text);
|
||||
if (!value || value.schemaVersion !== 1 || value.projectRoot !== canonicalRoot
|
||||
|| value.host !== "127.0.0.1" || !Number.isInteger(value.port) || value.port < 1 || value.port > 65535
|
||||
|| typeof value.sessionId !== "string" || !value.sessionId
|
||||
|| !Number.isSafeInteger(value.processId) || value.processId < 1) {
|
||||
throw new Error("Invalid project LSP discovery metadata. Reopen the project in Studio.");
|
||||
}
|
||||
try { process.kill(value.processId, 0); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return undefined; throw error; }
|
||||
return value as Endpoint;
|
||||
}
|
||||
|
||||
export function reconnectDelay(attempt: number): number {
|
||||
return Math.min(30000, 2000 * 2 ** Math.min(attempt, 4));
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
import { readEndpoint, reconnectDelay } from "./discovery";
|
||||
import * as net from "node:net";
|
||||
import * as vscode from "vscode";
|
||||
import { ExternalSources, externalScheme } from "./externalSources";
|
||||
@@ -7,6 +9,7 @@ import {
|
||||
ErrorAction,
|
||||
LanguageClient,
|
||||
LanguageClientOptions,
|
||||
RevealOutputChannelOn,
|
||||
ServerOptions,
|
||||
State,
|
||||
StreamInfo
|
||||
@@ -20,7 +23,30 @@ let stoppingClient = false;
|
||||
let lastAppliedThemeSignature: string | undefined;
|
||||
const externalSources = new ExternalSources();
|
||||
|
||||
const RECONNECT_DELAY_MS = 2000;
|
||||
let reconnectAttempt = 0;
|
||||
let connectionStatus: vscode.StatusBarItem;
|
||||
let lastStatus = "";
|
||||
let startPromise: Promise<void> | undefined;
|
||||
let restartQueue = Promise.resolve();
|
||||
let disposed = false;
|
||||
let endpointKey: string | undefined;
|
||||
let endpointSession: string | undefined;
|
||||
|
||||
function status(message: string): void {
|
||||
connectionStatus.text = `$(plug) Prometeu: ${message}`;
|
||||
connectionStatus.tooltip = message;
|
||||
connectionStatus.show();
|
||||
if (message !== lastStatus) { output.appendLine(message); lastStatus = message; }
|
||||
}
|
||||
|
||||
function restart(context: vscode.ExtensionContext): Promise<void> {
|
||||
restartQueue = restartQueue.then(async () => {
|
||||
await stopClient();
|
||||
reconnectAttempt = 0;
|
||||
if (!disposed) await startClient(context);
|
||||
}).catch(error => { status(String(error)); scheduleReconnect(); });
|
||||
return restartQueue;
|
||||
}
|
||||
|
||||
type PrometeuTokenStyle = {
|
||||
semanticKey: string;
|
||||
@@ -72,10 +98,35 @@ type PrometeuSemanticHostProjectionsPayload = {
|
||||
hostProjections: PrometeuSemanticHostProjection[];
|
||||
};
|
||||
|
||||
// The reconnect controller owns availability feedback; avoid languageclient's
|
||||
// forced error notifications for expected offline/obsolete discovery endpoints.
|
||||
class StudioLanguageClient extends LanguageClient {
|
||||
override async stop(timeout?: number): Promise<void> {
|
||||
// languageclient 9 invokes stop before its failed initialize has left
|
||||
// Starting. Wait for that start to settle before disposing the transport.
|
||||
if (this.state === State.Starting) await this.start().catch(() => undefined);
|
||||
await super.stop(timeout);
|
||||
}
|
||||
override error(message: string, _data?: unknown, _showNotification?: boolean | "force"): void {
|
||||
status(`Studio unavailable: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const VSCODE_HOST_ID = "vscode";
|
||||
|
||||
export function activate(context: vscode.ExtensionContext): void {
|
||||
disposed = false;
|
||||
reconnectContext = context;
|
||||
connectionStatus = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
|
||||
connectionStatus.command = "prometeu.restartStudioLsp";
|
||||
const watcher = vscode.workspace.createFileSystemWatcher("**/.studio/lsp.json");
|
||||
const changed = () => { void restart(context); };
|
||||
context.subscriptions.push(connectionStatus, watcher,
|
||||
watcher.onDidCreate(changed), watcher.onDidChange(changed), watcher.onDidDelete(changed),
|
||||
vscode.workspace.onDidChangeWorkspaceFolders(changed),
|
||||
vscode.workspace.onDidChangeConfiguration(event => {
|
||||
if (event.affectsConfiguration("prometeu.studio")) changed();
|
||||
}));
|
||||
output = vscode.window.createOutputChannel("Prometeu LSP");
|
||||
output.appendLine("Prometeu VS Code extension activated.");
|
||||
context.subscriptions.push(externalSources,
|
||||
@@ -94,6 +145,7 @@ export function activate(context: vscode.ExtensionContext): void {
|
||||
const connectCommand = vscode.commands.registerCommand(
|
||||
"prometeu.connectStudioLsp",
|
||||
async () => {
|
||||
reconnectAttempt = 0;
|
||||
await startClient(context);
|
||||
}
|
||||
);
|
||||
@@ -101,8 +153,7 @@ export function activate(context: vscode.ExtensionContext): void {
|
||||
const restartCommand = vscode.commands.registerCommand(
|
||||
"prometeu.restartStudioLsp",
|
||||
async () => {
|
||||
await stopClient();
|
||||
await startClient(context);
|
||||
await restart(context);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -112,11 +163,22 @@ export function activate(context: vscode.ExtensionContext): void {
|
||||
}
|
||||
|
||||
export async function deactivate(): Promise<void> {
|
||||
disposed = true;
|
||||
reconnectContext = undefined;
|
||||
clearReconnectTimer();
|
||||
await restartQueue;
|
||||
try { await externalSources.shutdown(); }
|
||||
finally { await stopClient(); }
|
||||
}
|
||||
|
||||
async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
if (disposed) return;
|
||||
if (startPromise) return startPromise;
|
||||
startPromise = startClientOnce(context).finally(() => { startPromise = undefined; });
|
||||
return startPromise;
|
||||
}
|
||||
|
||||
async function startClientOnce(context: vscode.ExtensionContext): Promise<void> {
|
||||
clearReconnectTimer();
|
||||
|
||||
if (client) {
|
||||
@@ -124,13 +186,44 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const config = vscode.workspace.getConfiguration("prometeu.studio");
|
||||
|
||||
const host = config.get<string>("host", "127.0.0.1");
|
||||
const port = config.get<number>("port", 7775);
|
||||
|
||||
output.show(true);
|
||||
output.appendLine(`Connecting to Prometeu Studio LSP at ${host}:${port}...`);
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (!folders || folders.length !== 1 || folders[0].uri.scheme !== "file") {
|
||||
status("Open one local Prometeu project folder.");
|
||||
return;
|
||||
}
|
||||
const folder = folders[0];
|
||||
const config = vscode.workspace.getConfiguration("prometeu.studio", folder.uri);
|
||||
let host: string;
|
||||
let port: number;
|
||||
let root: string;
|
||||
let session: string | undefined;
|
||||
try {
|
||||
root = realpathSync(folder.uri.fsPath);
|
||||
if (config.get<string>("connectionMode", "auto") === "manual") {
|
||||
host = config.get<string>("host", "127.0.0.1");
|
||||
port = config.get<number>("port", 7775);
|
||||
} else {
|
||||
const endpoint = readEndpoint(root);
|
||||
if (!endpoint) {
|
||||
status("Waiting for Studio — open this project in Studio.");
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
({ host, port } = endpoint);
|
||||
session = endpoint.sessionId;
|
||||
}
|
||||
} catch (error) {
|
||||
status(error instanceof Error ? error.message : String(error));
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
const key = `${root}:${host}:${port}`;
|
||||
if (endpointKey !== key || (session !== undefined && endpointSession !== session)) {
|
||||
externalSources.resetSession();
|
||||
}
|
||||
endpointKey = key;
|
||||
if (session !== undefined) endpointSession = session;
|
||||
status(`Connecting to ${host}:${port}`);
|
||||
|
||||
const serverOptions: ServerOptions = async (): Promise<StreamInfo> => {
|
||||
return new Promise<StreamInfo>((resolve, reject) => {
|
||||
@@ -178,6 +271,7 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
};
|
||||
|
||||
const clientOptions: LanguageClientOptions = {
|
||||
workspaceFolder: { ...folder, uri: vscode.Uri.file(root) },
|
||||
documentSelector: [
|
||||
{
|
||||
scheme: "file",
|
||||
@@ -195,6 +289,8 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
prometeuClientVersion: context.extension.packageJSON.version
|
||||
},
|
||||
outputChannel: output,
|
||||
revealOutputChannelOn: RevealOutputChannelOn.Never,
|
||||
initializationFailedHandler: () => false,
|
||||
middleware: {
|
||||
prepareRename: (document, position, token, next) => document.uri.scheme === externalScheme ? null : next(document, position, token),
|
||||
provideRenameEdits: (document, position, name, token, next) => document.uri.scheme === externalScheme ? null : next(document, position, name, token),
|
||||
@@ -210,13 +306,13 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
return { action: ErrorAction.Continue };
|
||||
},
|
||||
closed: () => {
|
||||
output.appendLine("Prometeu LSP transport closed.");
|
||||
return { action: CloseAction.DoNotRestart };
|
||||
status("Waiting for Studio — connection closed.");
|
||||
return { action: CloseAction.DoNotRestart, handled: true };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const nextClient = new LanguageClient(
|
||||
const nextClient = new StudioLanguageClient(
|
||||
"prometeuStudioLsp",
|
||||
"Prometeu Studio LSP",
|
||||
serverOptions,
|
||||
@@ -230,7 +326,6 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
initialize() {}, clear() {}, getState() { return { kind: "static" }; }
|
||||
});
|
||||
nextClient.onDidChangeState((event) => {
|
||||
output.appendLine(`Prometeu LSP state changed: ${State[event.oldState]} -> ${State[event.newState]}`);
|
||||
if (event.newState !== State.Stopped) {
|
||||
return;
|
||||
}
|
||||
@@ -248,8 +343,8 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
await externalSources.connected(nextClient);
|
||||
await applyPrometeuVisualTheme(nextClient.initializeResult);
|
||||
|
||||
output.appendLine("Prometeu Studio LSP client started.");
|
||||
vscode.window.showInformationMessage("Connected to Prometeu Studio LSP.");
|
||||
reconnectAttempt = 0;
|
||||
status(`Connected to Studio at ${host}:${port}`);
|
||||
} catch (error) {
|
||||
externalSources.resetSession();
|
||||
if (client === nextClient) {
|
||||
@@ -258,15 +353,19 @@ async function startClient(context: vscode.ExtensionContext): Promise<void> {
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
|
||||
output.appendLine(`Failed to start Prometeu LSP client: ${message}`);
|
||||
vscode.window.showErrorMessage(`Could not connect to Prometeu Studio LSP: ${message}`);
|
||||
status(`Studio unavailable: ${message}`);
|
||||
try { await nextClient.dispose(); } catch { /* transport already stopped */ }
|
||||
scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
async function stopClient(): Promise<void> {
|
||||
clearReconnectTimer();
|
||||
stoppingClient = true;
|
||||
if (startPromise) await startPromise;
|
||||
clearReconnectTimer();
|
||||
if (!client) {
|
||||
stoppingClient = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -288,17 +387,17 @@ async function stopClient(): Promise<void> {
|
||||
}
|
||||
|
||||
function scheduleReconnect(): void {
|
||||
if (!reconnectContext) {
|
||||
if (!reconnectContext || disposed || stoppingClient) {
|
||||
return;
|
||||
}
|
||||
if (reconnectTimer || client) {
|
||||
return;
|
||||
}
|
||||
output.appendLine(`Scheduling Prometeu LSP reconnect in ${RECONNECT_DELAY_MS}ms...`);
|
||||
const delay = reconnectDelay(reconnectAttempt++);
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = undefined;
|
||||
void startClient(reconnectContext!);
|
||||
}, RECONNECT_DELAY_MS);
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function clearReconnectTimer(): void {
|
||||
|
||||
@@ -54,7 +54,7 @@ export class ExternalSources implements vscode.TextDocumentContentProvider, vsco
|
||||
}
|
||||
|
||||
disconnected(): void { this.client = undefined; this.available.clear(); this.refreshStatus(); }
|
||||
resetSession(): void { this.disconnected(); this.consumerId = undefined; }
|
||||
resetSession(): void { this.disconnected(); this.consumerId = undefined; this.closed.clear(); }
|
||||
|
||||
private request(operation: string, uri: string): Promise<ExternalContent> {
|
||||
if (!this.client || !this.consumerId) return Promise.reject(new Error("External source unavailable: reconnect to Studio."));
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { test } from "node:test";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync, symlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { readEndpoint, reconnectDelay } from "../discovery";
|
||||
|
||||
test("project discovery rejects stale, malformed and misbound endpoints", () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "prometeu-lsp-")));
|
||||
try {
|
||||
assert.equal(readEndpoint(root), undefined);
|
||||
mkdirSync(join(root, ".studio"));
|
||||
const file = join(root, ".studio/lsp.json");
|
||||
const valid = { schemaVersion: 1, projectRoot: root, sessionId: "session", processId: process.pid, host: "127.0.0.1", port: 54321 };
|
||||
const publish = (value: unknown) => writeFileSync(file, JSON.stringify(value));
|
||||
publish(valid);
|
||||
assert.equal(readEndpoint(root)?.port, 54321);
|
||||
for (const invalid of [null, {}, { ...valid, schemaVersion: 2 }, { ...valid, projectRoot: "/wrong" },
|
||||
{ ...valid, host: "example.com" }, { ...valid, port: 0 }, { ...valid, port: 65536 },
|
||||
{ ...valid, port: 1.5 }, { ...valid, sessionId: "" }, { ...valid, processId: -1 }]) {
|
||||
publish(invalid);
|
||||
assert.throws(() => readEndpoint(root));
|
||||
}
|
||||
writeFileSync(file, "{");
|
||||
assert.throws(() => readEndpoint(root));
|
||||
publish({ ...valid, processId: 2147483647 });
|
||||
assert.equal(readEndpoint(root), undefined);
|
||||
publish({ ...valid, sessionId: "reopened", port: 54322 });
|
||||
assert.equal(readEndpoint(root)?.sessionId, "reopened");
|
||||
const alias = join(root, "alias");
|
||||
symlinkSync(root, alias);
|
||||
assert.equal(readEndpoint(alias)?.port, 54322);
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test("reconnection delays increase and stay capped", () => {
|
||||
assert.deepEqual([0, 1, 2, 3, 4, 50].map(reconnectDelay), [2000, 4000, 8000, 16000, 30000, 30000]);
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import * as assert from "node:assert/strict";
|
||||
import * as vscode from "vscode";
|
||||
import { ExternalSources, ExternalContent } from "../externalSources";
|
||||
@@ -50,6 +52,9 @@ export async function run(): Promise<void> {
|
||||
const root = vscode.workspace.workspaceFolders![0].uri;
|
||||
const project = await vscode.workspace.openTextDocument(vscode.Uri.joinPath(root, "src/main.pbs"));
|
||||
await vscode.window.showTextDocument(project);
|
||||
// Start offline, then discover a newly published endpoint without port settings.
|
||||
await vscode.extensions.getExtension("undefined_publisher.prometeu-vscode-extension")?.activate();
|
||||
writeFileSync(join(root.fsPath, ".studio/discover-request"), "ready");
|
||||
const use = project.positionAt(project.getText().indexOf("Gfx.clear") + 4);
|
||||
const definitions = await eventually(
|
||||
() => vscode.commands.executeCommand<vscode.Location[]>("vscode.executeDefinitionProvider", project.uri, use),
|
||||
@@ -90,10 +95,29 @@ export async function run(): Promise<void> {
|
||||
() => vscode.commands.executeCommand<vscode.Location[]>("vscode.executeDefinitionProvider", library.uri, nestedUse),
|
||||
result => !!result?.length);
|
||||
assert.equal(nested[0].range.start.line, 2);
|
||||
writeFileSync(join(root.fsPath, ".studio/restart-request"), "restart");
|
||||
const endpoint = await eventually(async () => {
|
||||
try { return JSON.parse(readFileSync(join(root.fsPath, ".studio/lsp.json"), "utf8")); }
|
||||
catch { return undefined; }
|
||||
}, value => value?.sessionId === "replacement");
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
// File replacement must reconnect the existing editor without a command.
|
||||
await eventually(
|
||||
() => vscode.commands.executeCommand<vscode.Hover[]>("vscode.executeHoverProvider", project.uri, use),
|
||||
result => !!result?.length);
|
||||
assert.equal(external.getText(), original);
|
||||
const refreshedDefinitions = await vscode.commands.executeCommand<vscode.Location[]>("vscode.executeDefinitionProvider", project.uri, use);
|
||||
const refreshedExternal = await vscode.workspace.openTextDocument(refreshedDefinitions[0].uri);
|
||||
await vscode.window.showTextDocument(refreshedExternal);
|
||||
const refreshedCall = refreshedExternal.positionAt(refreshedExternal.getText().indexOf("LowGfx.clear") + 7);
|
||||
// Explicit manual mode remains supported for separately hosted servers.
|
||||
const settings = vscode.workspace.getConfiguration("prometeu.studio");
|
||||
await settings.update("port", endpoint.port, vscode.ConfigurationTarget.Workspace);
|
||||
await settings.update("connectionMode", "manual", vscode.ConfigurationTarget.Workspace);
|
||||
await vscode.commands.executeCommand("prometeu.restartStudioLsp");
|
||||
assert.equal(external.getText(), original);
|
||||
const afterReconnect = await eventually(
|
||||
() => vscode.commands.executeCommand<vscode.Hover[]>("vscode.executeHoverProvider", external.uri, call),
|
||||
() => vscode.commands.executeCommand<vscode.Hover[]>("vscode.executeHoverProvider", refreshedExternal.uri, refreshedCall),
|
||||
result => !!result?.length);
|
||||
assert.ok(afterReconnect.flatMap(item => item.contents).some(content => (typeof content === "string" ? content : content.value).includes("clear")));
|
||||
// Project editing remains functional in the same editor session.
|
||||
@@ -101,5 +125,6 @@ export async function run(): Promise<void> {
|
||||
assert.equal(await projectEditor.edit(edit => edit.insert(new vscode.Position(0, 0), "// editable\n")), true);
|
||||
await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor");
|
||||
await vscode.commands.executeCommand("workbench.action.closeAllEditors");
|
||||
writeFileSync(join(root.fsPath, ".studio/finished"), "done");
|
||||
console.log("PLN-0141 VS Code development acceptance passed: readonly, syntax, positions, hover, continued definition, project editing.");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user