fix: bootstrap plant plugins with startup script

This commit is contained in:
codex
2026-08-06 12:27:12 +03:00
parent f052dd0633
commit 5c812f87fd
+11 -15
View File
@@ -79,10 +79,12 @@ internal sealed class LocalParityLaunchService
var logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Promhimproekt", "PRecAnnot2026", "Logs", "runtime.jsonl"); var logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Promhimproekt", "PRecAnnot2026", "Logs", "runtime.jsonl");
var beforeLogLength = File.Exists(logPath) ? new FileInfo(logPath).Length : 0L; var beforeLogLength = File.Exists(logPath) ? new FileInfo(logPath).Length : 0L;
var psi = new ProcessStartInfo { FileName = product.ExecutablePath, WorkingDirectory = Path.GetDirectoryName(product.ExecutablePath)!, UseShellExecute = false }; var psi = new ProcessStartInfo { FileName = product.ExecutablePath, WorkingDirectory = Path.GetDirectoryName(product.ExecutablePath)!, UseShellExecute = false };
psi.ArgumentList.Add("/product"); psi.ArgumentList.Add("PLNT3D"); psi.ArgumentList.Add("/language"); psi.ArgumentList.Add("ru-RU"); psi.ArgumentList.Add("/s"); psi.ArgumentList.Add(Path.GetDirectoryName(prepared.StarterPath)!); psi.ArgumentList.Add("/product"); psi.ArgumentList.Add("PLNT3D"); psi.ArgumentList.Add("/language"); psi.ArgumentList.Add("ru-RU");
// Controlled-local only: accepted Plant runtime bootstrap. Keep /b and the owned SCR last.
psi.ArgumentList.Add("/b"); psi.ArgumentList.Add(prepared.StarterPath);
psi.Environment["P_REC_ANNOT_RUNTIME_MODE"] = "Smoke"; psi.Environment["P_REC_ANNOT_RUNTIME_MODE"] = "Smoke";
using var process = Process.Start(psi) ?? throw new InvalidOperationException("PLANT3D_PROCESS_NOT_CREATED"); using var process = Process.Start(psi) ?? throw new InvalidOperationException("PLANT3D_PROCESS_NOT_CREATED");
await Task.Delay(TimeSpan.FromSeconds(8), ct); await Task.Delay(TimeSpan.FromSeconds(30), ct);
var alive = !process.HasExited; var alive = !process.HasExited;
var marker = Path.Combine(Path.GetDirectoryName(prepared.StarterPath)!, "pxp-oa-netload.marker"); var marker = Path.Combine(Path.GetDirectoryName(prepared.StarterPath)!, "pxp-oa-netload.marker");
var markerConfirmed = File.Exists(marker); var markerConfirmed = File.Exists(marker);
@@ -93,29 +95,23 @@ internal sealed class LocalParityLaunchService
stream.Seek(beforeLogLength, SeekOrigin.Begin); stream.Seek(beforeLogLength, SeekOrigin.Begin);
using var reader = new StreamReader(stream, Encoding.UTF8); using var reader = new StreamReader(stream, Encoding.UTF8);
var newLog = await reader.ReadToEndAsync(ct); var newLog = await reader.ReadToEndAsync(ct);
runtimeConfirmed = newLog.Contains("AssemblyInitializeCompleted", StringComparison.Ordinal); runtimeConfirmed = newLog.Contains("AssemblyInitializeCompleted", StringComparison.Ordinal) && newLog.Contains($"\"ProcessId\":{process.Id}", StringComparison.Ordinal);
} }
var loaded = markerConfirmed || runtimeConfirmed; var loaded = runtimeConfirmed;
var terminal = alive && loaded ? "Succeeded" : "Blocked"; var terminal = alive && loaded ? "Succeeded" : "Blocked";
var evidence = new { schemaVersion = 1, launcherCommit = ThisCommit(), autodeskCommit = "68f5006", operationId, configuration = prepared.Profile.Name, selectedPattern = prepared.Profile.PatternName, orderedPluginIds = new[] { prepared.Requirement.PackageId }, exactPackage = new { prepared.Package.PackageId, prepared.Package.Version, prepared.Manifest.Product, prepared.Manifest.ProductYear, prepared.Manifest.Architecture, prepared.Manifest.RolloutChannel }, manifestSha256 = await HashAsync(Path.Combine(prepared.Package.LocalPackageRoot, "package.manifest.json"), ct), payloads = prepared.Manifest.Files.Select(x => new { path = x.Path, x.Length, x.Sha256 }), materialization = "MaterializedOrAlreadyPresentExact", activation = prepared.Activation.Outcome, pointerGeneration = prepared.Activation.Receipt?.PointerGeneration, plant = new { product = "Plant3D", year = 2026, executableFingerprint = Fingerprint(product.ExecutablePath, operationId), interactive = true, batchArgumentUsed = false }, starter = new { sha256 = prepared.StarterSha256, localOnly = true }, process = new { pid = process.Id, startupVerified = alive, packageLoadConfirmed = loaded, markerConfirmed, runtimeJournalConfirmed = runtimeConfirmed }, terminalState = terminal, sideEffects = new { corporateDfsUsed = false, corporateDfsWriteAttempted = false, directDfsExecutionAttempted = false, productionProjectAccessed = false, productionPointerMutationAttempted = false, productionDeploymentAttempted = false } }; var evidence = new { schemaVersion = 2, launcherCommit = ThisCommit(), autodeskCommit = "68f5006", operationId, configuration = prepared.Profile.Name, selectedPattern = prepared.Profile.PatternName, orderedPluginIds = new[] { prepared.Requirement.PackageId }, exactPackage = new { prepared.Package.PackageId, prepared.Package.Version, prepared.Manifest.Product, prepared.Manifest.ProductYear, prepared.Manifest.Architecture, prepared.Manifest.RolloutChannel }, manifestSha256 = await HashAsync(Path.Combine(prepared.Package.LocalPackageRoot, "package.manifest.json"), ct), payloads = prepared.Manifest.Files.Select(x => new { path = x.Path, x.Length, x.Sha256 }), materialization = "MaterializedOrAlreadyPresentExact", activation = prepared.Activation.Outcome, pointerGeneration = prepared.Activation.Receipt?.PointerGeneration, bootstrapMechanism="StartupScript", commandLineSwitch="/b", scriptWasLastArgument=true, scriptSha256=prepared.StarterSha256, plant = new { product = "Plant3D", year = 2026, executableFingerprint = Fingerprint(product.ExecutablePath, operationId), interactive = true, batchArgumentUsed = true }, process = new { pid = process.Id, newProcessCreated=true, startupVerified = alive, packageLoadConfirmed = loaded, markerConfirmed, runtimeJournalConfirmed = runtimeConfirmed, processInteractiveAfterScript=alive }, terminalState = terminal, sideEffects = new { corporateDfsUsed = false, corporateDfsWriteAttempted = false, directDfsExecutionAttempted = false, productionProjectAccessed = false, productionPointerMutationAttempted = false, machineWideSecurityChanged=false, productionDeploymentAttempted = false } };
var evidencePath = await WriteEvidenceAsync(evidenceDirectory, evidence, ct); var evidencePath = await WriteEvidenceAsync(evidenceDirectory, evidence, ct);
return new(process.Id, alive, loaded, evidencePath, terminal); return new(process.Id, alive, loaded, evidencePath, terminal);
} }
private static async Task<(string Path, string Sha256)> GenerateStarterAsync(LocalParityLaunchProfile profile, ImmutableLocalPackage package, PackageManifest manifest, CancellationToken ct) private static async Task<(string Path, string Sha256)> GenerateStarterAsync(LocalParityLaunchProfile profile, ImmutableLocalPackage package, PackageManifest manifest, CancellationToken ct)
{ {
var starterRoot = Under(profile.Root, "starter"); Directory.CreateDirectory(starterRoot); var starterRoot = Under(profile.Root, "bootstrap", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(starterRoot);
var entry = Under(package.LocalPackageRoot, manifest.EntryAssembly); var entry = Under(package.LocalPackageRoot, manifest.EntryAssembly);
if (!File.Exists(entry)) throw new InvalidOperationException("LOCAL_PARITY_ENTRY_MISSING"); if (!File.Exists(entry)) throw new InvalidOperationException("LOCAL_PARITY_ENTRY_MISSING");
var marker = Under(starterRoot, "pxp-oa-netload.marker"); var marker = Under(starterRoot, "pxp-oa-netload.marker");
var escapedEntry = entry.Replace("\\", "\\\\").Replace("\"", "\\\""); var content = "_.FILEDIA\r\n0\r\n_.CMDDIA\r\n0\r\n_.NETLOAD\r\n\"" + entry.Replace("\"", "\\\"") + "\"\r\n";
var escapedMarker = marker.Replace("\\", "\\\\").Replace("\"", "\\\""); var path = Under(starterRoot, "startup.scr");
var content = $"(vl-load-com)\n(command \"_.NETLOAD\" \"{escapedEntry}\")\n(setq parity-marker (open \"{escapedMarker}\" \"w\"))\n(write-line \"NETLOAD_RETURNED\" parity-marker)\n(close parity-marker)\n(princ)\n";
// AutoCAD loads acad.lsp at startup and acaddoc.lsp for each document.
// Both are identical and live solely in the local generated support directory.
var bootstrap = Under(starterRoot, "acad.lsp");
var path = Under(starterRoot, "acaddoc.lsp");
await File.WriteAllTextAsync(bootstrap, content, new UTF8Encoding(false), ct);
await File.WriteAllTextAsync(path, content, new UTF8Encoding(false), ct); await File.WriteAllTextAsync(path, content, new UTF8Encoding(false), ct);
return (path, await HashAsync(path, ct)); return (path, await HashAsync(path, ct));
} }
@@ -133,6 +129,6 @@ internal sealed class LocalParityLaunchService
private static string Under(string root, params string[] parts) { var result = Path.GetFullPath(Path.Combine(new[] { root }.Concat(parts).ToArray())); if (!UnderRoot(root, result) && !string.Equals(Path.GetFullPath(root), result, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("LOCAL_PARITY_PATH_ESCAPE"); return result; } private static string Under(string root, params string[] parts) { var result = Path.GetFullPath(Path.Combine(new[] { root }.Concat(parts).ToArray())); if (!UnderRoot(root, result) && !string.Equals(Path.GetFullPath(root), result, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("LOCAL_PARITY_PATH_ESCAPE"); return result; }
private static async Task<string> HashAsync(string path, CancellationToken ct) { await using var stream = File.OpenRead(path); return Convert.ToHexString(await SHA256.HashDataAsync(stream, ct)); } private static async Task<string> HashAsync(string path, CancellationToken ct) { await using var stream = File.OpenRead(path); return Convert.ToHexString(await SHA256.HashDataAsync(stream, ct)); }
private static string Fingerprint(string path, string salt) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(salt + "|" + path))); private static string Fingerprint(string path, string salt) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(salt + "|" + path)));
private static async Task<string> WriteEvidenceAsync(string directory, object value, CancellationToken ct) { var final = Path.Combine(directory, "controlled-local-parity-launch.json"); var temp = final + ".tmp"; await using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { await JsonSerializer.SerializeAsync(stream, value, cancellationToken: ct); await stream.FlushAsync(ct); } File.Move(temp, final); using var doc = JsonDocument.Parse(await File.ReadAllTextAsync(final, ct)); if (doc.RootElement.GetProperty("schemaVersion").GetInt32() != 1) throw new InvalidOperationException("LOCAL_PARITY_EVIDENCE_INVALID"); return final; } private static async Task<string> WriteEvidenceAsync(string directory, object value, CancellationToken ct) { var final = Path.Combine(directory, "controlled-local-parity-launch.json"); var temp = final + ".tmp"; await using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { await JsonSerializer.SerializeAsync(stream, value, cancellationToken: ct); await stream.FlushAsync(ct); } File.Move(temp, final); using var doc = JsonDocument.Parse(await File.ReadAllTextAsync(final, ct)); if (doc.RootElement.GetProperty("schemaVersion").GetInt32() != 2) throw new InvalidOperationException("LOCAL_PARITY_EVIDENCE_INVALID"); return final; }
private static string ThisCommit() { try { var start = new ProcessStartInfo("git", "rev-parse HEAD") { WorkingDirectory = AppContext.BaseDirectory, UseShellExecute = false, RedirectStandardOutput = true }; using var p = Process.Start(start); return p is null ? "unknown" : p.StandardOutput.ReadToEnd().Trim(); } catch { return "unknown"; } } private static string ThisCommit() { try { var start = new ProcessStartInfo("git", "rev-parse HEAD") { WorkingDirectory = AppContext.BaseDirectory, UseShellExecute = false, RedirectStandardOutput = true }; using var p = Process.Start(start); return p is null ? "unknown" : p.StandardOutput.ReadToEnd().Trim(); } catch { return "unknown"; } }
} }