using Microsoft.EntityFrameworkCore; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace PLCSharp.Models; public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId, string Name, string Path, string Before, string After, string Revision, string Status); public sealed class ProjectChanges { private readonly Dictionary drafts = new(); public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { if (operation == "preview") { string kind = (string)args["kind"], after = (string)args["comment"]; if (after == null || after.Length > 8192) throw new ArgumentException("Expected a comment of at most 8192 characters."); if (kind is not ("Recipes" or "Variables" or "SystemVariables" or "Workflows")) throw new ArgumentException("Unsupported comment target."); var id = Guid.Parse((string)args["id"]); lock (project.Data.Sync) { var target = ProjectInspection.Query(project, "get", args); var recipeId = kind == "Recipes" ? id : Guid.Parse((string)target["RecipeID"]); string path = kind is "Variables" or "SystemVariables" ? "configuration/variables.json" : $"recipes/{recipeId:D}/recipe.json"; string before = (string)target["Comment"]; var change = new ProjectChange(Guid.NewGuid(), project.Id, kind, id, recipeId, (string)target["Name"], path, before, after, project.Revision(path), "pending"); if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First()); drafts.Add(change.DraftId, change); return JsonSerializer.SerializeToNode(change); } } if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var draft) || draft.ProjectId != project.Id) throw new ArgumentException("Unknown or expired draft."); if (operation == "apply" && draft.Status == "pending") { if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview."); if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" }; else { try { project.ApplyComment(draft); } catch (ProjectConflictException) { drafts[draft.DraftId] = draft with { Status = "conflict" }; throw; } draft = draft with { Status = "saved" }; } drafts[draft.DraftId] = draft; } return JsonSerializer.SerializeToNode(draft); } } internal sealed class ProjectConflictException(string message) : System.IO.IOException(message); public sealed partial class ProjectDirectory { internal string Revision(string path) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(baseline[path]))); internal void ApplyComment(ProjectChange change) { lock (Data.Sync) { var id = change.ObjectId; var current = ProjectInspection.Query(this, "get", new() { ["kind"] = change.Kind, ["id"] = id.ToString() }); if (Revision(change.Path) != change.Revision || (string)current["Comment"] != change.Before) throw new ProjectConflictException("The target changed after preview. Create a new preview."); var document = JsonNode.Parse(baseline[change.Path]); var isVariable = change.Kind is "Variables" or "SystemVariables"; JsonNode target = change.Kind switch { "Recipes" => document, "Workflows" => document["workflows"].AsArray().Single(w => Guid.Parse((string)w["id"]) == id), _ => document[change.Kind].AsArray().Single(v => Guid.Parse((string)v["ID"]) == id) }; var field = isVariable ? "Comment" : "comment"; if ((string)target[field] != change.Before) throw new ProjectConflictException("Save the pending editor change to this comment first."); target[field] = change.After; var json = Serialize(document); var files = new Dictionary(baseline) { [change.Path] = json }; // Change only the approved column in the private working database. Other tracked drafts stay pending. using var transaction = isVariable ? Data.Database.BeginTransaction() : null; if (change.Kind == "Variables") Data.Variables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); if (change.Kind == "SystemVariables") Data.SystemVariables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After)); try { WriteFiles(Root, files, [change.Path]); } catch (System.IO.IOException) when (!System.IO.File.Exists(ProjectFile(Root, change.Path)) || System.IO.File.ReadAllText(ProjectFile(Root, change.Path)) != baseline[change.Path]) { throw new ProjectConflictException("The file changed outside the editor. Reopen the project and preview again."); } transaction?.Commit(); if (isVariable) { configuration[change.Path] = json; object entity = change.Kind == "Variables" ? Data.Variables.Local.First(v => v.ID == id) : Data.SystemVariables.Local.First(v => v.ID == id); var property = Data.Entry(entity).Property(field); if (entity is PLCSharp.VVMs.GlobalVariables.Variable variable) variable.Comment = change.After; else ((PLCSharp.VVMs.GlobalVariables.SystemVariable)entity).Comment = change.After; property.OriginalValue = change.After; } else if (change.Kind == "Recipes") Recipes.Single(r => r.ID == id).Comment = change.After; else Flows(change.RecipeId).Single(w => w.ID == id).Comment = change.After; } } }