Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Project version history store

Egor Khindikaynenbb368f91204b
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 6a091b3f..c926d8d4 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -170,6 +170,17 @@ The dirty check captures with session names instead (`contentNames: false`) and
audio. Older bundles (`sample-N.wav`, `state-N.bin`) load as is and migrate on their next
save.
+**Version history** (`ProjectHistory`, port `IProjectHistory`) lives in `.history/` inside
+the bundle. A version is the bundle's top-level files — the manifest and its sidecars —
+stored by content hash in `.history/objects/` (Brotli), plus the list of binaries its
+manifest references. Binaries are not copied: being content-named, they stay in
+`samples/` / `plugin-states/` and are shared by every version that uses them.
+`.history/versions.json` holds the tree (parent links, head, labels, notes, stars).
+Checking a version out writes its top-level files back (manifest last) and moves the head;
+the next save on top of an older version branches. A save's prune keeps every binary some
+version references, and prunes nothing if the history can't be read. Deleting a version
+re-parents its children and collects objects and binaries nothing needs any more.
+
`analysis/` holds a cache of imported audio — each file's waveform overview (min/max per
512 frames) and detected tempo, as `<content fingerprint>.npk` — so re-importing a file
is instant. It is disposable: delete it and entries are rebuilt on the next import. While
diff --git a/src/managed/Nota.Application/Ports/IProjectHistory.cs b/src/managed/Nota.Application/Ports/IProjectHistory.cs
new file mode 100644
index 00000000..d295c540
--- /dev/null
+++ b/src/managed/Nota.Application/Ports/IProjectHistory.cs
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+
+namespace Nota.Application;
+
+/// <summary>One saved version of a project — a node of the history tree.</summary>
+/// <param name="Parent">The version this one was saved on top of (null for the root).</param>
+/// <param name="AddedBytes">Disk space this version added when it was saved (new audio,
+/// plugin states and manifests no earlier version had).</param>
+/// <param name="CanOpen">False when the version was saved by a newer Nota whose project
+/// format this build can't read.</param>
+public sealed record ProjectVersion(
+ string Id, string? Parent, DateTimeOffset CreatedAt,
+ string? Label, string? Note, bool Starred,
+ string AppVersion, int ProjectFormat, long AddedBytes, bool CanOpen);
+
+/// <summary>A project's history: every version (oldest first) and the one the working
+/// copy was last saved as or switched to.</summary>
+public sealed record ProjectHistoryState(IReadOnlyList<ProjectVersion> Versions, string? Head)
+{
+ public static readonly ProjectHistoryState Empty = new([], null);
+ public ProjectVersion? HeadVersion => Versions.FirstOrDefault(v => v.Id == Head);
+}
+
+/// <summary>Disk use of a project: <see cref="Total"/> is the whole bundle's audio, states
+/// and history; <see cref="HistoryOnly"/> is what only older versions need (freed by
+/// erasing the history).</summary>
+public readonly record struct ProjectHistorySize(long Total, long HistoryOnly);
+
+/// <summary>History is unreadable (damaged, or from a newer Nota) or a version can't be
+/// restored (its files are missing). The working copy is never touched when this is thrown.</summary>
+public sealed class ProjectHistoryException(string message, Exception? inner = null) : Exception(message, inner);
+
+/// <summary>Version history of a <c>.nota</c> bundle, kept inside the bundle. A version is
+/// recorded on each explicit save; switching restores a version's files into the bundle
+/// (the caller then reopens the project). Saving on top of an older version branches.</summary>
+public interface IProjectHistory
+{
+ /// <summary>All versions and the head. Empty when the bundle has no history yet.</summary>
+ ProjectHistoryState Read(string bundleDir);
+
+ /// <summary>Records the bundle's current (just saved) state as a child of the head.
+ /// Returns null when nothing changed since the head.</summary>
+ ProjectVersion? Commit(string bundleDir, string? note = null);
+
+ /// <summary>Restores <paramref name="versionId"/>'s files into the bundle and makes it
+ /// the head. The caller reloads the project afterwards.</summary>
+ void Checkout(string bundleDir, string versionId);
+
+ void SetLabel(string bundleDir, string versionId, string? label);
+ void SetNote(string bundleDir, string versionId, string? note);
+ void SetStarred(string bundleDir, string versionId, bool starred);
+
+ /// <summary>Deletes a version (not the head); its children move up to its parent.
+ /// Returns the bytes freed.</summary>
+ long Delete(string bundleDir, string versionId);
+
+ /// <summary>Deletes the whole history and every file only it needed.</summary>
+ long Erase(string bundleDir);
+
+ /// <summary>Carries the history, with every file its versions need, from one bundle to
+ /// another (Save As). No-op when <paramref name="fromBundle"/> has no history.</summary>
+ void CopyTo(string fromBundle, string toBundle);
+
+ ProjectHistorySize Size(string bundleDir);
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs b/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs
index 84fc2e3e..42bee241 100644
--- a/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs
@@ -85,27 +85,34 @@ internal static partial class BundleContent
}
}
- /// <summary>Deletes files in <c>samples/</c> and <c>plugin-states/</c> that the saved
- /// document no longer references: superseded content, legacy <c>sample-N.wav</c> /
- /// <c>state-N.bin</c> names, and temp files left by an interrupted save.</summary>
+ /// <summary>Deletes files in <c>samples/</c> and <c>plugin-states/</c> that neither the
+ /// saved document nor any version in the project's history references: superseded
+ /// content, legacy <c>sample-N.wav</c> / <c>state-N.bin</c> names, and temp files left by
+ /// an interrupted save. Prunes nothing when the history can't be read.</summary>
public static void PruneUnreferenced(string bundleDir, ProjectDocument doc)
{
- Prune(Path.Combine(bundleDir, SamplesDir), SamplesDir, doc.SampleRefs.ContainsKey, ".wav");
- Prune(Path.Combine(bundleDir, StatesDir), StatesDir, doc.StateBlobs.ContainsKey, ".bin");
+ if (ProjectHistory.PinnedBinaries(bundleDir) is not { } pinned) return;
+ bool Keep(string rel) => doc.SampleRefs.ContainsKey(rel) || doc.StateBlobs.ContainsKey(rel) || pinned.Contains(rel);
+ foreach (var relDir in new[] { SamplesDir, StatesDir })
+ {
+ string dir = Path.Combine(bundleDir, relDir);
+ if (!Directory.Exists(dir)) continue;
+ foreach (var file in Directory.EnumerateFiles(dir))
+ {
+ string name = Path.GetFileName(file);
+ if (!IsSaveOutput(name, relDir) || Keep($"{relDir}/{name}")) continue;
+ try { File.Delete(file); } catch { /* in use or read-only: leave it for the next save */ }
+ }
+ }
}
- private static void Prune(string dir, string relDir, Func<string, bool> referenced, string ext)
+ /// <summary>Is <paramref name="name"/> (in <paramref name="relDir"/>) a file a save writes —
+ /// a sample / state or its temp? Anything else in those folders isn't ours to delete.</summary>
+ public static bool IsSaveOutput(string name, string relDir)
{
- if (!Directory.Exists(dir)) return;
- foreach (var file in Directory.EnumerateFiles(dir))
- {
- string name = Path.GetFileName(file);
- // Only touch what a save writes; anything else in the folder isn't ours.
- if (!name.EndsWith(ext, StringComparison.OrdinalIgnoreCase)
- && !name.EndsWith(ext + ".tmp", StringComparison.OrdinalIgnoreCase)) continue;
- if (referenced($"{relDir}/{name}")) continue;
- try { File.Delete(file); } catch { /* in use or read-only: leave it for the next save */ }
- }
+ string ext = relDir == SamplesDir ? ".wav" : ".bin";
+ return name.EndsWith(ext, StringComparison.OrdinalIgnoreCase)
+ || name.EndsWith(ext + ".tmp", StringComparison.OrdinalIgnoreCase);
}
private static string Hex(ReadOnlySpan<byte> hash) => Convert.ToHexString(hash[..HashBytes]).ToLowerInvariant();
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectHistory.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectHistory.cs
new file mode 100644
index 00000000..7aeead5e
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectHistory.cs
@@ -0,0 +1,486 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Project version history, kept inside the bundle:
+//
+// MySong.nota/
+// project.json, *.json working copy: the manifest + sidecars
+// samples/<hash>.wav shared by every version (content-addressed, BundleContent)
+// plugin-states/<hash>.bin shared by every version
+// .history/
+// versions.json the tree: versions, parents, head
+// objects/ab/cdef….br manifests + sidecars of every version, Brotli
+//
+// A version is the set of top-level files (by content hash, stored in objects/) plus the
+// list of binaries its manifest references (left where they are — a save already names them
+// by content, so a sample shared by twenty versions is one file). Checkout writes a
+// version's top-level files back; the binaries are already there. A save prunes binaries no
+// version needs (BundleContent.PruneUnreferenced asks PinnedBinaries).
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Compression;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.RegularExpressions;
+
+namespace Nota.Infrastructure;
+
+public sealed partial class ProjectHistory : IProjectHistory
+{
+ public const string HistoryDir = ".history";
+ private const string VersionsFile = "versions.json";
+ private const string ObjectsDir = "objects";
+ private const int HistoryFormat = 1;
+
+ private static readonly object Gate = new();
+
+ private static readonly JsonSerializerOptions JsonOpts = new()
+ {
+ WriteIndented = true,
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
+ };
+
+ private readonly string _appVersion;
+
+ /// <param name="appVersion">Recorded on each version ("saved with Nota X").</param>
+ public ProjectHistory(string appVersion) => _appVersion = appVersion;
+
+ // --- on-disk model -----------------------------------------------------
+
+ private sealed class HistoryDoc
+ {
+ public int HistoryFormat { get; set; } = ProjectHistory.HistoryFormat;
+ public string? Head { get; set; }
+ public List<Node> Versions { get; set; } = new();
+ }
+
+ private sealed class Node
+ {
+ public string Id { get; set; } = "";
+ public string? Parent { get; set; }
+ public DateTimeOffset CreatedAt { get; set; }
+ public string? Label { get; set; }
+ public string? Note { get; set; }
+ public bool Starred { get; set; }
+ public string AppVersion { get; set; } = "";
+ public int ProjectFormat { get; set; }
+ public long AddedBytes { get; set; }
+ /// <summary>Top-level file name -> object hash.</summary>
+ public SortedDictionary<string, string> Files { get; set; } = new(StringComparer.Ordinal);
+ /// <summary>Bundle-relative binaries the manifest references (samples/…, plugin-states/…).</summary>
+ public List<string> Binaries { get; set; } = new();
+ }
+
+ // --- IProjectHistory ---------------------------------------------------
+
+ public ProjectHistoryState Read(string bundleDir)
+ {
+ lock (Gate)
+ {
+ var doc = Load(bundleDir);
+ if (doc is null) return ProjectHistoryState.Empty;
+ return new ProjectHistoryState(doc.Versions.Select(ToVersion).ToList(), doc.Head);
+ }
+ }
+
+ public ProjectVersion? Commit(string bundleDir, string? note = null)
+ {
+ lock (Gate)
+ {
+ var doc = Load(bundleDir) ?? new HistoryDoc();
+ var snap = TakeSnapshot(bundleDir);
+ var head = Find(doc, doc.Head);
+ if (head is not null && SameContent(head, snap)) return null;
+
+ // What this version adds to the disk: objects not stored yet + binaries no
+ // earlier version referenced (they'd have been pruned without this version).
+ long added = 0;
+ foreach (var (hash, bytes) in snap.Contents)
+ if (WriteObject(bundleDir, hash, bytes) is long written) added += written;
+ var known = new HashSet<string>(doc.Versions.SelectMany(v => v.Binaries), StringComparer.Ordinal);
+ foreach (var rel in snap.Binaries)
+ if (!known.Contains(rel)) added += FileSize(Path.Combine(bundleDir, rel));
+
+ var node = new Node
+ {
+ Id = NewId(doc),
+ Parent = head?.Id,
+ CreatedAt = DateTimeOffset.UtcNow,
+ Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim(),
+ AppVersion = _appVersion,
+ ProjectFormat = snap.ProjectFormat,
+ AddedBytes = added,
+ Files = snap.Files,
+ Binaries = snap.Binaries,
+ };
+ doc.Versions.Add(node);
+ doc.Head = node.Id;
+ Store(bundleDir, doc);
+ return ToVersion(node);
+ }
+ }
+
+ public void Checkout(string bundleDir, string versionId)
+ {
+ lock (Gate)
+ {
+ var doc = Load(bundleDir) ?? throw new ProjectHistoryException("This project has no version history.");
+ var node = Find(doc, versionId) ?? throw new ProjectHistoryException("That version no longer exists.");
+ if (node.ProjectFormat > ProjectService.CurrentFormatVersion)
+ throw new ProjectHistoryException(
+ $"This version was saved by Nota {node.AppVersion}, which is newer than this one. Update Nota to open it.");
+
+ // Read and check everything before touching the working copy.
+ var contents = new Dictionary<string, byte[]>(StringComparer.Ordinal);
+ int missing = 0;
+ foreach (var (name, hash) in node.Files)
+ {
+ var bytes = ReadObject(bundleDir, hash);
+ if (bytes is null) missing++;
+ else contents[name] = bytes;
+ }
+ missing += node.Binaries.Count(rel => !File.Exists(Path.Combine(bundleDir, rel)));
+ if (missing > 0)
+ throw new ProjectHistoryException($"This version can't be restored: {missing} of its files are missing.");
+
+ foreach (var name in SnapshotFileNames(bundleDir))
+ if (!contents.ContainsKey(name))
+ File.Delete(Path.Combine(bundleDir, name)); // a sidecar this version didn't have
+ foreach (var (name, bytes) in contents.Where(kv => kv.Key != ProjectService.ManifestName))
+ BundleContent.WriteAtomic(Path.Combine(bundleDir, name), tmp => File.WriteAllBytes(tmp, bytes));
+ // The manifest last: until it lands, the bundle still opens as the previous state.
+ if (contents.TryGetValue(ProjectService.ManifestName, out var manifest))
+ BundleContent.WriteAtomic(Path.Combine(bundleDir, ProjectService.ManifestName), tmp => File.WriteAllBytes(tmp, manifest));
+
+ doc.Head = node.Id;
+ Store(bundleDir, doc);
+ }
+ }
+
+ public void SetLabel(string bundleDir, string versionId, string? label)
+ => Edit(bundleDir, versionId, n => n.Label = string.IsNullOrWhiteSpace(label) ? null : label.Trim());
+
+ public void SetNote(string bundleDir, string versionId, string? note)
+ => Edit(bundleDir, versionId, n => n.Note = string.IsNullOrWhiteSpace(note) ? null : note.Trim());
+
+ public void SetStarred(string bundleDir, string versionId, bool starred)
+ => Edit(bundleDir, versionId, n => n.Starred = starred);
+
+ public long Delete(string bundleDir, string versionId)
+ {
+ lock (Gate)
+ {
+ var doc = Load(bundleDir) ?? throw new ProjectHistoryException("This project has no version history.");
+ var node = Find(doc, versionId) ?? throw new ProjectHistoryException("That version no longer exists.");
+ if (node.Id == doc.Head)
+ throw new ProjectHistoryException("The current version can't be deleted — switch to another one first.");
+ foreach (var child in doc.Versions.Where(v => v.Parent == node.Id)) child.Parent = node.Parent;
+ doc.Versions.Remove(node);
+ Store(bundleDir, doc);
+ return Collect(bundleDir, doc);
+ }
+ }
+
+ public long Erase(string bundleDir)
+ {
+ lock (Gate)
+ {
+ string dir = Path.Combine(bundleDir, HistoryDir);
+ long freed = Directory.Exists(dir) ? DirSize(dir) : 0;
+ if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
+ return freed + Collect(bundleDir, new HistoryDoc());
+ }
+ }
+
+ public void CopyTo(string fromBundle, string toBundle)
+ {
+ lock (Gate)
+ {
+ var doc = Load(fromBundle);
+ if (doc is null) return;
+ string src = Path.Combine(fromBundle, HistoryDir), dst = Path.Combine(toBundle, HistoryDir);
+ foreach (var file in Directory.EnumerateFiles(src, "*", SearchOption.AllDirectories))
+ {
+ string to = Path.Combine(dst, Path.GetRelativePath(src, file));
+ Directory.CreateDirectory(Path.GetDirectoryName(to)!);
+ if (!File.Exists(to)) File.Copy(file, to);
+ }
+ File.Copy(Path.Combine(src, VersionsFile), Path.Combine(dst, VersionsFile), overwrite: true);
+ foreach (var rel in doc.Versions.SelectMany(v => v.Binaries).Distinct())
+ {
+ string from = Path.Combine(fromBundle, rel), to = Path.Combine(toBundle, rel);
+ if (File.Exists(to) || !File.Exists(from)) continue;
+ Directory.CreateDirectory(Path.GetDirectoryName(to)!);
+ BundleContent.WriteAtomic(to, tmp => File.Copy(from, tmp));
+ }
+ }
+ }
+
+ public ProjectHistorySize Size(string bundleDir)
+ {
+ lock (Gate)
+ {
+ string hist = Path.Combine(bundleDir, HistoryDir);
+ long historyDir = Directory.Exists(hist) ? DirSize(hist) : 0;
+ var working = WorkingBinaries(bundleDir);
+ long binaries = 0, historyOnly = historyDir;
+ foreach (var (rel, size) in BinaryFiles(bundleDir))
+ {
+ binaries += size;
+ if (!working.Contains(rel)) historyOnly += size;
+ }
+ return new ProjectHistorySize(binaries + historyDir, historyOnly);
+ }
+ }
+
+ /// <summary>Binaries any version references, for the save's prune to keep. Empty when
+ /// there is no history; null when it can't be read — then nothing may be pruned.</summary>
+ internal static IReadOnlySet<string>? PinnedBinaries(string bundleDir)
+ {
+ lock (Gate)
+ {
+ try
+ {
+ var doc = Load(bundleDir);
+ return doc is null
+ ? new HashSet<string>()
+ : new HashSet<string>(doc.Versions.SelectMany(v => v.Binaries), StringComparer.Ordinal);
+ }
+ catch (ProjectHistoryException) { return null; }
+ }
+ }
+
+ // --- snapshot ----------------------------------------------------------
+
+ private sealed record Snapshot(
+ SortedDictionary<string, string> Files, List<string> Binaries, int ProjectFormat,
+ Dictionary<string, byte[]> Contents);
+
+ private static Snapshot TakeSnapshot(string bundleDir)
+ {
+ var files = new SortedDictionary<string, string>(StringComparer.Ordinal);
+ var contents = new Dictionary<string, byte[]>(StringComparer.Ordinal);
+ foreach (var name in SnapshotFileNames(bundleDir))
+ {
+ var bytes = File.ReadAllBytes(Path.Combine(bundleDir, name));
+ string hash = BundleContent.BlobHash(bytes);
+ files[name] = hash;
+ contents[hash] = bytes;
+ }
+ if (!files.ContainsKey(ProjectService.ManifestName))
+ throw new ProjectHistoryException("The project hasn't been saved yet.");
+
+ var manifest = ParseManifest(bundleDir);
+ var binaries = new List<string>();
+ foreach (var rel in ManifestBinaries(manifest).Distinct().Order(StringComparer.Ordinal))
+ {
+ // History relies on a name meaning one content forever (stage-1 bundles).
+ if (!ContentNamedRx().IsMatch(rel))
+ throw new ProjectHistoryException("Save the project once more before recording a version.");
+ if (File.Exists(Path.Combine(bundleDir, rel))) binaries.Add(rel); // a sample that failed to write stays missing
+ }
+ int format = manifest?["formatVersion"]?.GetValue<int>() ?? 1;
+ return new Snapshot(files, binaries, format, contents);
+ }
+
+ // Top-level files that make up a version: the manifest and its sidecars. Hidden files
+ // (.DS_Store), temp files and folders (samples/, analysis/, backups/, .history/) aren't.
+ private static IEnumerable<string> SnapshotFileNames(string bundleDir)
+ => Directory.EnumerateFiles(bundleDir)
+ .Select(Path.GetFileName)
+ .OfType<string>()
+ .Where(n => !n.StartsWith('.') && !n.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
+ .Order(StringComparer.Ordinal);
+
+ private static bool SameContent(Node head, Snapshot snap)
+ => head.Files.Count == snap.Files.Count
+ && head.Files.All(kv => snap.Files.TryGetValue(kv.Key, out var h) && h == kv.Value)
+ && head.Binaries.SequenceEqual(snap.Binaries, StringComparer.Ordinal);
+
+ private static JsonNode? ParseManifest(string bundleDir)
+ {
+ string path = Path.Combine(bundleDir, ProjectService.ManifestName);
+ try { return File.Exists(path) ? JsonNode.Parse(File.ReadAllText(path)) : null; }
+ catch (JsonException) { return null; }
+ }
+
+ // Every string in the manifest that points into samples/ or plugin-states/.
+ private static IEnumerable<string> ManifestBinaries(JsonNode? node)
+ {
+ switch (node)
+ {
+ case JsonObject o:
+ foreach (var (_, v) in o)
+ foreach (var s in ManifestBinaries(v)) yield return s;
+ break;
+ case JsonArray a:
+ foreach (var v in a)
+ foreach (var s in ManifestBinaries(v)) yield return s;
+ break;
+ case JsonValue v when v.TryGetValue(out string? s)
+ && (s.StartsWith(BundleContent.SamplesDir + "/", StringComparison.Ordinal)
+ || s.StartsWith(BundleContent.StatesDir + "/", StringComparison.Ordinal)):
+ yield return s;
+ break;
+ }
+ }
+
+ private static HashSet<string> WorkingBinaries(string bundleDir)
+ => new(ManifestBinaries(ParseManifest(bundleDir)), StringComparer.Ordinal);
+
+ // --- garbage collection ------------------------------------------------
+
+ // Deletes objects no version uses and binaries neither a version nor the working copy
+ // references. Returns the bytes freed.
+ private static long Collect(string bundleDir, HistoryDoc doc)
+ {
+ long freed = 0;
+ var liveObjects = new HashSet<string>(doc.Versions.SelectMany(v => v.Files.Values), StringComparer.Ordinal);
+ string objects = Path.Combine(bundleDir, HistoryDir, ObjectsDir);
+ if (Directory.Exists(objects))
+ foreach (var file in Directory.EnumerateFiles(objects, "*", SearchOption.AllDirectories))
+ {
+ string hash = Path.GetFileName(Path.GetDirectoryName(file)) + Path.GetFileNameWithoutExtension(file);
+ if (liveObjects.Contains(hash)) continue;
+ freed += FileSize(file);
+ TryDelete(file);
+ }
+
+ var liveBinaries = WorkingBinaries(bundleDir);
+ liveBinaries.UnionWith(doc.Versions.SelectMany(v => v.Binaries));
+ foreach (var (rel, size) in BinaryFiles(bundleDir))
+ {
+ if (liveBinaries.Contains(rel)) continue;
+ freed += size;
+ TryDelete(Path.Combine(bundleDir, rel));
+ }
+ return freed;
+ }
+
+ private static IEnumerable<(string Rel, long Size)> BinaryFiles(string bundleDir)
+ {
+ foreach (var dir in new[] { BundleContent.SamplesDir, BundleContent.StatesDir })
+ {
+ string full = Path.Combine(bundleDir, dir);
+ if (!Directory.Exists(full)) continue;
+ foreach (var file in Directory.EnumerateFiles(full))
+ {
+ string name = Path.GetFileName(file);
+ if (BundleContent.IsSaveOutput(name, dir)) yield return ($"{dir}/{name}", FileSize(file));
+ }
+ }
+ }
+
+ // --- objects -----------------------------------------------------------
+
+ private static string ObjectPath(string bundleDir, string hash)
+ => Path.Combine(bundleDir, HistoryDir, ObjectsDir, hash[..2], hash[2..] + ".br");
+
+ // Stores bytes under their hash unless already there. Returns the bytes written (null if present).
+ private static long? WriteObject(string bundleDir, string hash, byte[] bytes)
+ {
+ string path = ObjectPath(bundleDir, hash);
+ if (File.Exists(path)) return null;
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ BundleContent.WriteAtomic(path, tmp =>
+ {
+ using var fs = File.Create(tmp);
+ using var br = new BrotliStream(fs, CompressionLevel.Optimal);
+ br.Write(bytes);
+ });
+ return FileSize(path);
+ }
+
+ // The object's bytes, or null if missing or not matching its hash.
+ private static byte[]? ReadObject(string bundleDir, string hash)
+ {
+ string path = ObjectPath(bundleDir, hash);
+ if (!File.Exists(path)) return null;
+ try
+ {
+ using var fs = File.OpenRead(path);
+ using var br = new BrotliStream(fs, CompressionMode.Decompress);
+ using var ms = new MemoryStream();
+ br.CopyTo(ms);
+ var bytes = ms.ToArray();
+ return BundleContent.BlobHash(bytes) == hash ? bytes : null;
+ }
+ catch (Exception e) when (e is IOException or InvalidDataException) { return null; }
+ }
+
+ // --- versions.json -----------------------------------------------------
+
+ private static HistoryDoc? Load(string bundleDir)
+ {
+ string path = Path.Combine(bundleDir, HistoryDir, VersionsFile);
+ if (!File.Exists(path)) return null;
+ HistoryDoc? doc;
+ try { doc = JsonSerializer.Deserialize<HistoryDoc>(File.ReadAllText(path), JsonOpts); }
+ catch (Exception e) when (e is JsonException or IOException)
+ {
+ throw new ProjectHistoryException("The version history of this project is damaged.", e);
+ }
+ if (doc is null) throw new ProjectHistoryException("The version history of this project is damaged.");
+ if (doc.HistoryFormat > HistoryFormat)
+ throw new ProjectHistoryException("This project's version history was written by a newer Nota. Update Nota to use it.");
+ return doc;
+ }
+
+ private static void Store(string bundleDir, HistoryDoc doc)
+ {
+ string dir = Path.Combine(bundleDir, HistoryDir);
+ Directory.CreateDirectory(dir);
+ string json = JsonSerializer.Serialize(doc, JsonOpts);
+ BundleContent.WriteAtomic(Path.Combine(dir, VersionsFile), tmp => File.WriteAllText(tmp, json));
+ }
+
+ private void Edit(string bundleDir, string versionId, Action<Node> change)
+ {
+ lock (Gate)
+ {
+ var doc = Load(bundleDir) ?? throw new ProjectHistoryException("This project has no version history.");
+ var node = Find(doc, versionId) ?? throw new ProjectHistoryException("That version no longer exists.");
+ change(node);
+ Store(bundleDir, doc);
+ }
+ }
+
+ // --- helpers -----------------------------------------------------------
+
+ private static Node? Find(HistoryDoc doc, string? id)
+ => id is null ? null : doc.Versions.FirstOrDefault(v => v.Id == id);
+
+ private static ProjectVersion ToVersion(Node n)
+ => new(n.Id, n.Parent, n.CreatedAt, n.Label, n.Note, n.Starred, n.AppVersion, n.ProjectFormat, n.AddedBytes,
+ CanOpen: n.ProjectFormat <= ProjectService.CurrentFormatVersion);
+
+ private static string NewId(HistoryDoc doc)
+ {
+ string id;
+ do id = $"v-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Convert.ToHexString(RandomNumberGenerator.GetBytes(2)).ToLowerInvariant()}";
+ while (doc.Versions.Any(v => v.Id == id));
+ return id;
+ }
+
+ private static long FileSize(string path)
+ {
+ try { return new FileInfo(path).Length; }
+ catch (IOException) { return 0; }
+ }
+
+ private static long DirSize(string dir)
+ => Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories).Sum(FileSize);
+
+ private static void TryDelete(string path)
+ {
+ try { File.Delete(path); } catch { /* in use or read-only: the next collect retries */ }
+ }
+
+ [GeneratedRegex(@"^(samples/[0-9a-f]{32}\.wav|plugin-states/[0-9a-f]{32}\.bin)$")]
+ private static partial Regex ContentNamedRx();
+}
diff --git a/tests/Nota.SmokeTest/HistoryTests.cs b/tests/Nota.SmokeTest/HistoryTests.cs
new file mode 100644
index 00000000..232c0489
--- /dev/null
+++ b/tests/Nota.SmokeTest/HistoryTests.cs
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Project version history (.history/ inside the bundle): commits on save, no-op commits,
+// branching from an older version, checkout restoring the manifest + sidecars, samples
+// pinned by old versions surviving a save's prune, delete/collect, Save As carrying the
+// history, erase, and a damaged history never costing data.
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --history`.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class HistoryTests
+{
+ public static IEnumerable<(bool Ok, string Label)> Run()
+ {
+ string tmp = Path.GetTempPath();
+ string wav = Path.Combine(tmp, "nota_smoke_history_sine.wav");
+ WavWriter.WriteSine(wav, seconds: 1.0, freq: 220, sampleRate: 44100);
+ string dir = Path.Combine(tmp, "nota-smoke-history-" + Guid.NewGuid().ToString("N") + ".nota");
+ string copy = Path.Combine(tmp, "nota-smoke-history-copy-" + Guid.NewGuid().ToString("N") + ".nota");
+ var transport = new TransportState(120.0, 1.0, false, false);
+ IProjectHistory history = new ProjectHistory("0.0.0-test");
+ string manifest = Path.Combine(dir, ProjectService.ManifestName);
+ string sections = Path.Combine(dir, "sections.json");
+
+ void Save(NotaEngine e, string to) => ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), to, e);
+ string[] Samples(string bundle) => Directory.Exists(Path.Combine(bundle, "samples"))
+ ? Directory.GetFiles(Path.Combine(bundle, "samples"), "*.wav") : [];
+ int AudioClips(string bundle)
+ {
+ using var e = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(bundle), e, bundle);
+ int n = 0;
+ for (int i = 0; i < e.TrackCount; i++)
+ if (e.TryGetTrackInfo(i, out var ti) && ti.Type == 0) n += ti.ClipCount;
+ return n;
+ }
+
+ try
+ {
+ yield return (history.Read(dir).Versions.Count == 0, "a bundle without history reads as empty");
+
+ using var eng = new NotaEngine();
+ eng.AddInstrumentTrack();
+ Save(eng, dir);
+ File.WriteAllText(sections, "[{\"start\":0,\"length\":8,\"name\":\"Intro\"}]");
+ var v1 = history.Commit(dir, "first");
+ yield return (v1 is { Parent: null, Note: "first", AppVersion: "0.0.0-test" } && history.Read(dir).Head == v1.Id,
+ "first save records a root version and makes it the head");
+ yield return (history.Commit(dir) is null, "saving without changes records nothing");
+
+ eng.AddInstrumentTrack();
+ Save(eng, dir);
+ var v2 = history.Commit(dir);
+ yield return (v2?.Parent == v1!.Id && v2.AddedBytes < 64 * 1024, $"an edit records a child version (+{v2?.AddedBytes} B)");
+
+ int aTrk = eng.AddAudioTrack();
+ eng.AddAudioClipEx(aTrk, wav, startBeat: 0, sourceOffsetFrames: 0, lengthFrames: 0, gain: 1f);
+ File.Delete(sections);
+ Save(eng, dir);
+ var v3 = history.Commit(dir);
+ long wavBytes = Samples(dir).Sum(f => new FileInfo(f).Length);
+ yield return (v3 is not null && v3.AddedBytes >= wavBytes && wavBytes > 0,
+ $"a version with new audio accounts for it (+{v3?.AddedBytes} B, sample {wavBytes} B)");
+ string v3Manifest = File.ReadAllText(manifest);
+
+ // Drop the audio track and save: the sample is no longer in the working copy, but v3 pins it.
+ eng.RemoveTrack(aTrk);
+ Save(eng, dir);
+ yield return (Samples(dir).Length == 1, "a save keeps samples an older version needs");
+ var v4 = history.Commit(dir);
+
+ // Switch back to v3: manifest byte-identical, audio playable, the deleted sidecar stays absent.
+ history.Checkout(dir, v3!.Id);
+ yield return (File.ReadAllText(manifest) == v3Manifest && history.Read(dir).Head == v3.Id,
+ "checkout restores the version's manifest and moves the head");
+ yield return (!File.Exists(sections), "checkout removes a sidecar the version didn't have");
+ yield return (AudioClips(dir) == 1, "the restored version reloads with its audio clip");
+
+ history.Checkout(dir, v1.Id);
+ yield return (File.Exists(sections) && File.ReadAllText(sections).Contains("Intro"), "checkout brings a sidecar back");
+
+ // Save on top of v1 → a branch.
+ using (var e1 = new NotaEngine())
+ {
+ ProjectService.Apply(ProjectService.Load(dir), e1, dir);
+ e1.AddAudioTrack();
+ Save(e1, dir);
+ }
+ var v5 = history.Commit(dir);
+ var state = history.Read(dir);
+ yield return (v5?.Parent == v1.Id && state.Versions.Count(v => v.Parent == v1.Id) == 2,
+ "saving on top of an older version starts a branch");
+
+ history.SetLabel(dir, v3.Id, "With audio");
+ history.SetNote(dir, v3.Id, " bass take ");
+ history.SetStarred(dir, v3.Id, true);
+ var r3 = history.Read(dir).Versions.First(v => v.Id == v3.Id);
+ yield return (r3 is { Label: "With audio", Note: "bass take", Starred: true }, "label, note and star persist");
+
+ // Save As carries everything: history + the samples only old versions use.
+ Directory.CreateDirectory(copy);
+ using (var e2 = new NotaEngine())
+ {
+ ProjectService.Apply(ProjectService.Load(dir), e2, dir);
+ Save(e2, copy);
+ }
+ history.CopyTo(dir, copy);
+ yield return (history.Read(copy).Versions.Count == 5 && history.Read(copy).Head == v5!.Id,
+ "Save As carries the whole history");
+ history.Checkout(copy, v3.Id);
+ yield return (AudioClips(copy) == 1, "an old version opens from the copy (its audio came along)");
+
+ var size = history.Size(dir);
+ yield return (size.Total > size.HistoryOnly && size.HistoryOnly >= wavBytes,
+ $"size: {size.Total} B total, {size.HistoryOnly} B only for older versions");
+
+ // Delete: not the head; children move up; the sample goes once nothing needs it.
+ bool headRefused = false;
+ try { history.Delete(dir, v5.Id); } catch (ProjectHistoryException) { headRefused = true; }
+ yield return (headRefused, "the current version can't be deleted");
+ history.Delete(dir, v2!.Id);
+ yield return (history.Read(dir).Versions.First(v => v.Id == v3.Id).Parent == v1.Id,
+ "deleting a version re-parents its children");
+ history.Delete(dir, v4!.Id);
+ long freed = history.Delete(dir, v3.Id);
+ yield return (Samples(dir).Length == 0 && freed >= wavBytes, $"the last version using a sample frees it ({freed} B)");
+
+ // A missing object: checkout refuses and leaves the working copy alone.
+ string before = File.ReadAllText(manifest);
+ foreach (var f in Directory.GetFiles(Path.Combine(dir, ".history", "objects"), "*", SearchOption.AllDirectories))
+ File.Delete(f);
+ bool refused = false;
+ try { history.Checkout(dir, v1.Id); } catch (ProjectHistoryException) { refused = true; }
+ yield return (refused && File.ReadAllText(manifest) == before, "a version with missing files isn't restored");
+
+ // Damaged history: reads throw, and a save prunes nothing (the copy still has v3's audio).
+ File.WriteAllText(Path.Combine(copy, ".history", "versions.json"), "{ not json");
+ bool damaged = false;
+ try { history.Read(copy); } catch (ProjectHistoryException) { damaged = true; }
+ using (var e3 = new NotaEngine())
+ {
+ e3.AddInstrumentTrack();
+ Save(e3, copy);
+ }
+ yield return (damaged && Samples(copy).Length == 1, "a damaged history is reported and protects its files");
+
+ // Erase: history gone, only what the working copy uses is left.
+ long erased = history.Erase(dir);
+ yield return (!Directory.Exists(Path.Combine(dir, ".history")) && history.Read(dir).Versions.Count == 0 && erased > 0,
+ $"erasing deletes the history ({erased} B)");
+ }
+ finally
+ {
+ try { Directory.Delete(dir, true); } catch { }
+ try { Directory.Delete(copy, true); } catch { }
+ try { File.Delete(wav); } catch { }
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 7f470ae5..a30fae2a 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -141,6 +141,15 @@ if (args.Length >= 1 && args[0] == "--bundle")
return failures == 0 ? 0 : 1;
}
+// Project version history alone (fast iteration): `--history`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--history")
+{
+ Console.WriteLine("-- project: version history --");
+ foreach (var (ok, label) in HistoryTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "HISTORY PASSED" : $"HISTORY FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+
// Opt-in hosted-plugin check (M3-3): `--hostcheck <path-to-nota-scanworker>`.
// Loads a hosted AU instrument and effect and confirms audio flows through them.
if (args.Length >= 2 && args[0] == "--hostcheck")
@@ -13590,6 +13599,8 @@ foreach (var (ok, label) in AuditionTests.Run()) Check(ok, label);
// --- project: content-addressed bundle (samples / plugin states named by hash) ---
Console.WriteLine("-- project: content-addressed bundle --");
foreach (var (ok, label) in BundleContentTests.Run()) Check(ok, label);
+Console.WriteLine("-- project: version history --");
+foreach (var (ok, label) in HistoryTests.Run()) Check(ok, label);
// --- get plug-ins: registry index, install/uninstall from local archives ---
Console.WriteLine("-- get plug-ins: registry store --");