Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Improve Firmament language tooling and editor integration
Yuechen Li8a747eee3149
diff --git a/Aetheris.CLI.Tests/DependencyLockTests.cs b/Aetheris.CLI.Tests/DependencyLockTests.csnew file mode 100644index 00000000..5dc49856--- /dev/null+++ b/Aetheris.CLI.Tests/DependencyLockTests.cs@@ -0,0 +1,45 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.CLI.Tests;++public sealed class DependencyLockTests+{+ [Fact]+ public void RealCliLocksValidatesAndBuildsWithoutMutatingTheReceipt()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var directory = Path.Combine(root!.FullName,"artifacts/local/imported-resource-modules/tests",Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var source = Path.Combine(directory,"main.firmasm");+ var asset = Path.Combine(directory,"bearing.step");+ File.WriteAllText(asset,Step242Exporter.ExportBody(BrepPrimitives.CreateBox(4,6,8).Value).Value);+ File.WriteAllText(source,"include bearing: Part = Step(\"bearing\"); Assembly Machine { <Assembly Machine><Part A = bearing>Placement { from: Origin; to: World; }</Part></Assembly> Anchor: Machine; }");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ int Run(params string[] args) { stdout.GetStringBuilder().Clear(); stderr.GetStringBuilder().Clear(); return CliRunner.Run(args,stdout,stderr); }+ Assert.Equal(1,Run("validate",source,"--locked","--json"));+ Assert.Contains("firmament-lock-required",stdout.ToString());+ Assert.Equal(0,Run("lock",source,"--json"));+ var path = Path.Combine(directory,"firmament.lock.toml");+ var receipt = File.ReadAllText(path);+ Assert.Equal(0,Run("validate",source,"--locked","--json"));+ Assert.Equal(0,Run("build",source,"--locked","--output",Path.Combine(directory,"machine.step"),"--json"));+ Assert.True(Step242AssemblyImporter.Import(File.ReadAllText(Path.Combine(directory,"machine.step"))).IsSuccess);+ Assert.Equal(receipt,File.ReadAllText(path));+ File.AppendAllText(asset,"\n");+ foreach (var command in new[]{"validate","build"})+ {+ Assert.Equal(1,Run(command,source,"--locked","--json"));+ using var result = JsonDocument.Parse(stdout.ToString());+ Assert.False(result.RootElement.GetProperty("success").GetBoolean());+ Assert.Contains(result.RootElement.GetProperty("diagnostics").EnumerateArray(),d => d.GetProperty("code").GetString()=="firmament-lock-dependency-mismatch");+ }+ Assert.Equal(1,Run("lock",source,"--json"));+ Assert.Equal(receipt,File.ReadAllText(path));+ Assert.Equal(0,Run("lock",source,"--update","--json"));+ Assert.NotEqual(receipt,File.ReadAllText(path));+ Assert.Equal(0,Run("validate",source,"--locked","--json"));+ }+}diff --git a/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs b/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.csindex 80ec7450..801e13ec 100644--- a/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs+++ b/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs@@ -5,7 +5,7 @@ namespace Aetheris.CLI.Tests;public sealed class FirmamentDirectiveCliTests{[Theory]- [InlineData("ignored-include", "firmament-v2-directive-unconsumed")]+ [InlineData("ignored-include", "assembly-include-file-not-found")][InlineData("malformed-include", "firmament-v2-directive-malformed")][InlineData("schema-inline-unknown", "firmament-schema-unknown")][InlineData("schema-comment-unknown", "firmament-schema-unknown")]diff --git a/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.cs b/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.csnew file mode 100644index 00000000..d15ed4c5--- /dev/null+++ b/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.cs@@ -0,0 +1,71 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class ImportedFeatureAssistanceTests+{+ [Fact]+ public void InspectSelectPlanValidateBuild_RequiresNoAuthoredFaceIdsOrBounds()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var input = Path.Combine(root!.FullName, "testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp");+ var directory = Path.Combine(root.FullName, "artifacts/local/imported-feature-assistance/tests", Guid.NewGuid().ToString("N"));+ var source = Path.Combine(directory, "revision.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["imported-features", "inspect", input, "--import-tolerance", ".01", "--json"], stdout, stderr));+ using var inventory = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("InspectionOnly", inventory.RootElement.GetProperty("admission").GetString());+ var candidates = inventory.RootElement.GetProperty("inspection").GetProperty("discovery").GetProperty("candidates").EnumerateArray();+ // Simulate selecting the upper-left diameter-25 through-hole from measured+ // facts, without knowing a STEP entity or BRep ordinal in advance.+ var selected = Assert.Single(candidates, c => c.GetProperty("canPlan").GetBoolean()+ && System.Math.Abs(c.GetProperty("diameter").GetDouble() - 25) < 1e-6+ && c.GetProperty("center").GetProperty("x").GetDouble() < 0+ && c.GetProperty("center").GetProperty("y").GetDouble() > 0);+ var id = selected.GetProperty("id").GetString()!;+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["imported-features", "plan", input, "--candidate", id, "--as", "MountHole", "--offset", "290", "0",+ "--geometry-only", "--import-tolerance", ".01", "--source-out", source, "--json"], stdout, stderr));+ Assert.Empty(stderr.ToString()); Assert.True(File.Exists(source));+ Assert.True(File.Exists(Path.Combine(directory,"firmament.lock.toml")));+ Assert.DoesNotContain("textSha256:",File.ReadAllText(source));+ using var plan = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("Built", plan.RootElement.GetProperty("plan").GetProperty("admission").GetString());+ Assert.Equal(.1, plan.RootElement.GetProperty("plan").GetProperty("authoringIncrementMillimetres").GetDouble());+ Assert.Contains("diameter: 25mm", File.ReadAllText(source));+ Assert.Equal(115, plan.RootElement.GetProperty("plan").GetProperty("revision").GetProperty("preservedFaces").GetInt32());+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["validate", source, "--json"], stdout, stderr));+ using var validation = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("Built", validation.RootElement.GetProperty("firmamentV2Validation").GetProperty("validationLevel").GetString());+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["build", source, "--output", Path.Combine(directory,"revision.step"), "--json"], stdout, stderr));+ using var build = JsonDocument.Parse(stdout.ToString());+ Assert.Equal(1, build.RootElement.GetProperty("featureCount").GetInt32());+ Assert.Single(build.RootElement.GetProperty("pmiExportEvidence").GetProperty("diameter").EnumerateArray());+ var blocked = Path.Combine(directory, "occupied.firmament");+ stdout.GetStringBuilder().Clear();+ Assert.Equal(1, CliRunner.Run(["imported-features", "plan", input, "--candidate", id, "--as", "MountHole", "--offset", "320", "0",+ "--geometry-only", "--import-tolerance", ".01", "--source-out", blocked, "--json"], stdout, stderr));+ Assert.False(File.Exists(blocked));+ using var refusal = JsonDocument.Parse(stdout.ToString());+ Assert.Contains(refusal.RootElement.GetProperty("diagnostics").EnumerateArray(),+ d => d.GetProperty("code").GetString() == "firmament-imported-hole-revision-rejected");+ // A byte change is enough to invalidate a bound source even when its+ // nominal geometry is unchanged. Updating a hash cannot rebind faces.+ var localInput = Path.Combine(directory,"changed.step");+ File.WriteAllText(localInput,File.ReadAllText(input));+ var localSource = Path.Combine(directory,"local.firmament");+ var isolated = Path.Combine(directory,"surgery"); Directory.CreateDirectory(isolated);+ localSource = Path.Combine(isolated,"local.firmament");+ File.WriteAllText(localSource,File.ReadAllText(source).Replace(Path.GetRelativePath(directory,input).Replace('\\','/'),"../changed.step"));+ Assert.Equal(0,CliRunner.Run(["lock",localSource,"--json"],new StringWriter(),stderr));+ var lockPath = Path.Combine(isolated,"firmament.lock.toml"); var receipt = File.ReadAllText(lockPath);+ File.AppendAllText(localInput,"\n");+ stdout.GetStringBuilder().Clear();+ Assert.Equal(1,CliRunner.Run(["lock",localSource,"--update","--json"],stdout,stderr));+ Assert.Contains("firmament-lock-rebind-required",stdout.ToString());+ Assert.Equal(receipt,File.ReadAllText(lockPath));+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 92522e4a..e39746fa 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -134,9 +134,9 @@ public static class CliRunnerstring? Classification = null,int? RigidRootCount = null);private const string TopLevelUsage = "Usage: aetheris <command> [options]";- private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--json]";+ private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--locked] [--json]";private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|glb|assembly-json] [--output <path>] [--debug-ir <path>] [--json] (glb: MeshState sources)";- private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--parse-only] [--explain] [--shadow [--ast]] [--json]";+ private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--locked] [--forge-pack <path>] [--parse-only] [--explain] [--shadow [--ast]] [--json]";private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";private const string InspectSpansUsage = "Usage: aetheris inspect-spans <file.firmament> --json";private const string InspectComposeUsage = "Usage: aetheris inspect-compose <file.firmament> --json [--materialize]";@@ -220,6 +220,8 @@ public static class CliRunner"validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),"frontend-shadow" => FrontendShadowCommand.Run(args.Skip(1).ToArray(), stdout, stderr),"format" => RunFormat(args.Skip(1).ToArray(), stdout, stderr),+ "imported-features" => ImportedFeaturesCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),+ "lock" => DependencyLockCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),"measure" => FirmamentMeasureCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"inspect-3dm" => ThreeDmCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),@@ -462,6 +464,7 @@ public static class CliRunnervar sourcePath = args[0];string? outPath = null;var json = false;+ var locked = false;for (var i = 1; i < args.Length; i++){@@ -479,6 +482,9 @@ public static class CliRunnercase "--json":json = true;break;+ case "--locked":+ locked = true;+ break;case "-h":case "--help":WriteBuildHelp(stdout);@@ -492,6 +498,7 @@ public static class CliRunnerif (File.Exists(sourcePath)){+ if (!DependencyLockCommand.Verify(sourcePath, locked, json, stdout, stderr, JsonOptions, "build")) return 1;var source = File.ReadAllText(sourcePath);var frontend = FirmamentFrontendSchemas.Select(source);if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, source, sourcePath, "build", json, stdout, stderr);@@ -2395,6 +2402,7 @@ Model CanonicalPanel {var json = false;var explain = false;var parseOnly = false;+ var locked = false;var shadow = false;var shadowAst = false;var forgePackPaths = new List<string>();@@ -2421,6 +2429,9 @@ Model CanonicalPanel {case "--parse-only":parseOnly = true;break;+ case "--locked":+ locked = true;+ break;case "--json":json = true;break;@@ -2442,6 +2453,7 @@ Model CanonicalPanel {}if (shadowAst && !shadow) { stderr.WriteLine("--ast requires --shadow."); return 1; }+ if (!DependencyLockCommand.Verify(sourcePath, locked, json, stdout, stderr, JsonOptions, "validate")) return 1;if (shadow){if (forgePackPaths.Count > 0 || parseOnly) { stderr.WriteLine("--shadow uses normal production validation; --forge-pack/--parse-only are not supported together with it."); return 1; }@@ -5329,6 +5341,8 @@ Model CanonicalPanel {stdout.WriteLine(" build Compile Firmament to exact STEP AP242.");stdout.WriteLine(" mesh Export a supported exact B-rep as STL or topology-preserving OBJ.");stdout.WriteLine(" view Build/open a model in Cadmata.");+ stdout.WriteLine(" imported-features Discover proved imported-hole candidates and build named revision plans.");+ stdout.WriteLine(" lock Generate or explicitly update firmament.lock.toml dependency receipts.");stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");stdout.WriteLine(" measure Measure a compiled part and print assertion templates without claiming its assertions passed.");stdout.WriteLine(" inspect-3dm Inventory local Rhino 3DM geometry and import blockers.");@@ -5393,6 +5407,7 @@ Model CanonicalPanel {stdout.WriteLine();stdout.WriteLine("Options:");stdout.WriteLine(" --output <path> Optional output STEP path; defaults to a .step file beside the source.");+ stdout.WriteLine(" --locked Require firmament.lock.toml; an existing lock is always checked.");stdout.WriteLine(" --json Emit machine-readable success/failure JSON.");stdout.WriteLine(" -h, --help Show this help.");stdout.WriteLine();@@ -5424,6 +5439,7 @@ Model CanonicalPanel {stdout.WriteLine(" --shadow Developer report with separate original-source AST, bounded comparison and normal production validation.");stdout.WriteLine(" --ast Include the detailed AST with --shadow. Structural parsing does not establish semantic admission.");stdout.WriteLine(" --parse-only Use an available static analyzer; success is labelled parsed-not-built.");+ stdout.WriteLine(" --locked Require firmament.lock.toml; an existing lock is always checked.");stdout.WriteLine(" --forge-pack <path> Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.");}diff --git a/Aetheris.CLI/DependencyLockCommand.cs b/Aetheris.CLI/DependencyLockCommand.csnew file mode 100644index 00000000..b8967bfe--- /dev/null+++ b/Aetheris.CLI/DependencyLockCommand.cs@@ -0,0 +1,66 @@+using System.Text;+using System.Text.Json;+using Aetheris.Kernel.Firmament.Modules;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.CLI;++internal static class DependencyLockCommand+{+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions options)+ {+ const string usage = "Usage: aetheris lock <root.firmament|root.firmasm> [--update] [--json]";+ if (args.Length == 0 || args[0] is "--help" or "-h")+ { (args.Length == 0 ? stderr : stdout).WriteLine(usage); return args.Length == 0 ? 1 : 0; }+ var json = args.Contains("--json");+ if (args.Skip(1).Any(a => a is not ("--update" or "--json"))) { stderr.WriteLine(usage); return 1; }+ var inspected = FirmamentDependencies.InspectFile(args[0], args.Contains("--update"));+ if (!inspected.IsSuccess)+ {+ var diagnostics = Present(inspected.Diagnostics, args[0]);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics }, options));+ else Write(diagnostics, stderr);+ return 1;+ }+ var path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(args[0]))!, FirmamentDependencyLock.FileName);+ // Inspect the complete graph before replacing the receipt; compilation never writes here.+ var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";+ try { File.WriteAllText(temporary, inspected.Manifest!.ToToml(), new UTF8Encoding(false)); File.Move(temporary, path, true); }+ finally { if (File.Exists(temporary)) File.Delete(temporary); }+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, path, dependencies = inspected.Manifest!.Dependencies }, options));+ else stdout.WriteLine("Locked dependencies: " + path);+ return 0;+ }++ internal static bool Verify(string source, bool required, bool json, TextWriter stdout, TextWriter stderr, JsonSerializerOptions options, string command)+ {+ var diagnostics = Present(FirmamentDependencies.VerifyFile(source, required), source);+ if (diagnostics.Count == 0) return true;+ if (json) stdout.WriteLine(command == "validate"+ ? JsonSerializer.Serialize(new { command, success = false, status = "invalid", diagnostics,+ firmamentV2Validation = new { status = "invalid", validationLevel = "Rejected", diagnostics } }, options)+ : JsonSerializer.Serialize(new { command, success = false, status = "invalid", diagnostics }, options));+ else Write(diagnostics, stderr);+ return false;+ }++ internal static IReadOnlyList<FirmamentV2ValidationDiagnostic> Present(IEnumerable<AssemblyDiagnostic> diagnostics, string source) => diagnostics.Select(d =>+ {+ var file = d.SourceSpan?.Source ?? source;+ var span = d.SourceSpan is {} s ? new FirmamentV2SourceSpan(s.Start,s.Length) : null;+ int? line = null, column = null;+ if (span is not null && File.Exists(file))+ {+ var prefix = File.ReadAllText(file); prefix = prefix[..Math.Min(span.Start,prefix.Length)];+ line = 1 + prefix.Count(c => c == '\n'); column = prefix.Length - prefix.LastIndexOf('\n');+ }+ return new FirmamentV2ValidationDiagnostic(d.Code,d.Severity.ToString().ToLowerInvariant(),d.Message)+ { SourceFile = file, SourceSpan = span, Line = line, Column = column, Stage = "Dependency binding", IsOriginalSource = true, LocationNote = d.LocationNote };+ }).ToArray();++ static void Write(IEnumerable<FirmamentV2ValidationDiagnostic> diagnostics, TextWriter writer)+ {+ foreach (var d in diagnostics) writer.WriteLine($"{d.SourceFile}:{d.Line?.ToString() ?? "?"}:{d.Column?.ToString() ?? "?"}: {d.Severity} {d.Code}: {d.Message}");+ }+}diff --git a/Aetheris.CLI/ImportedFeaturesCommand.cs b/Aetheris.CLI/ImportedFeaturesCommand.csnew file mode 100644index 00000000..bdb9077a--- /dev/null+++ b/Aetheris.CLI/ImportedFeaturesCommand.cs@@ -0,0 +1,131 @@+using System.Globalization;+using System.Text.Json;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Modules;++namespace Aetheris.CLI;++internal static class ImportedFeaturesCommand+{+ const string Usage = "Usage: aetheris imported-features inspect <part.step> [--import-tolerance <mm>] [--json]\n"+ + " aetheris imported-features plan <part.step> --candidate <id> --as <name> (--offset <dx> <dy> | --to <x> <y> <z>) --geometry-only [--clearance <mm>] [--source-out <file.firmament>] [--import-tolerance <mm>] [--json]";++ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions options)+ {+ if (args.Length == 0 || args[0] is "--help" or "-h")+ { (args.Length == 0 ? stderr : stdout).WriteLine(Usage); return args.Length == 0 ? 1 : 0; }+ var json = args.Contains("--json");+ try+ {+ if (args.Length < 2 || args[0] is not ("inspect" or "plan")) throw new ArgumentException(Usage);+ var input = Path.GetFullPath(args[1]);+ string? candidate = null, alias = null, output = null;+ Point3D? target = null; (double X, double Y)? offset = null;+ var geometryOnly = false; var tolerance = .001; var clearance = .1;+ var seen = new HashSet<string>();+ for (var i = 2; i < args.Length; i++)+ {+ var flag = args[i];+ if (!seen.Add(flag)) throw new ArgumentException("Duplicate option: " + flag);+ string Next() => ++i < args.Length ? args[i] : throw new ArgumentException("Missing value: " + flag);+ double Number() => double.TryParse(Next(), NumberStyles.Float, CultureInfo.InvariantCulture, out var n) && double.IsFinite(n)+ ? n : throw new ArgumentException("Expected finite millimetres: " + flag);+ switch (flag)+ {+ case "--json": break;+ case "--candidate": candidate = Next(); break;+ case "--as": alias = Next(); break;+ case "--source-out": output = Next(); break;+ case "--geometry-only": geometryOnly = true; break;+ case "--import-tolerance": tolerance = Number(); break;+ case "--clearance": clearance = Number(); break;+ case "--to": target = new(Number(), Number(), Number()); break;+ case "--offset": offset = (Number(), Number()); break;+ default: throw new ArgumentException("Unknown option: " + flag);+ }+ }+ if (args[0] == "inspect" && seen.Any(f => f is not ("--json" or "--import-tolerance")))+ throw new ArgumentException("Inspection does not consume edit options.");+ var inspected = FirmamentImportedFeatures.Inspect(File.ReadAllText(input), tolerance);+ if (!inspected.IsSuccess) return Failure(inspected.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, input)));+ var inspection = inspected.Value;+ if (args[0] == "inspect")+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, admission = "InspectionOnly", input, inspection }, options));+ else+ {+ stdout.WriteLine($"Source {inspection.SourceHash}; qualified: {inspection.Discovery.Qualified}");+ foreach (var c in inspection.Discovery.Candidates)+ stdout.WriteLine($"{c.Id}: diameter {c.Diameter:G9} mm; center {c.Center}; recognized {c.Recognized}; canPlan {c.CanPlan}. {string.Join(" | ", c.Diagnostics)}");+ }+ return 0;+ }+ if (candidate is null || alias is null || target.HasValue == offset.HasValue)+ throw new ArgumentException("Plan requires --candidate, --as and exactly one of --offset/--to.");+ if (offset is { } delta)+ {+ var selected = inspection.Discovery.Candidates.SingleOrDefault(c => c.Id == candidate);+ if (selected?.Center is not { } center) throw new ArgumentException("Candidate has no proved through-hole center; inspect again.");+ target = new(center.X + delta.X, center.Y + delta.Y, center.Z);+ }+ var outputPath = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "imported-features", "revision.firmament"));+ if (string.Equals(outputPath, input, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) throw new ArgumentException("Source output must not overwrite the imported STEP.");+ if (!Path.GetExtension(outputPath).Equals(".firmament", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("Source output must use .firmament extension.");+ var directory = Path.GetDirectoryName(outputPath)!;+ var plan = FirmamentImportedFeatures.PlanMove(inspection, candidate, alias, target!.Value, geometryOnly,+ Path.GetRelativePath(directory, input).Replace('\\', '/'), directory, clearance);+ if (!plan.IsSuccess) return Failure(plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision")));+ var dependencies = FirmamentDependencies.InspectSource(plan.Value.Source, outputPath);+ if (!dependencies.IsSuccess) return Failure(DependencyLockCommand.Present(dependencies.Diagnostics, outputPath));+ // The normal AST owns the field span; the generated source keeps+ // engineering intent while the generated receipt keeps byte identity.+ var pin = FirmamentSyntaxTraversal.Statements(FirmamentSyntaxParser.Parse(plan.Value.Source).Document)+ .OfType<FieldSyntax>().Single(f => f.Name.Text == "textSha256");+ var authored = plan.Value.Source.Remove(pin.Span.Start, pin.Span.Length);+ var lockPath = Path.Combine(directory, FirmamentDependencyLock.FileName);+ Directory.CreateDirectory(directory);+ var previousSource = File.Exists(outputPath) ? File.ReadAllBytes(outputPath) : null;+ var previousLock = File.Exists(lockPath) ? File.ReadAllBytes(lockPath) : null;+ var committed = false;+ var savedPlan = plan.Value;+ try+ {+ File.WriteAllText(lockPath, dependencies.Manifest!.ToToml());+ File.WriteAllText(outputPath, authored);+ var qualified = FirmamentBuildAndExport.CompileSource(authored, directory);+ if (!qualified.IsSuccess) return Failure(qualified.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, outputPath)));+ savedPlan = plan.Value with { Source = authored, Revision = qualified.Value.ImportedHoleRevision!, Export = qualified.Value };+ committed = true;+ }+ finally+ {+ if (!committed)+ {+ if (previousSource is null) File.Delete(outputPath); else File.WriteAllBytes(outputPath, previousSource);+ if (previousLock is null) File.Delete(lockPath); else File.WriteAllBytes(lockPath, previousLock);+ }+ }+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, input, sourcePath = outputPath, lockPath, plan = savedPlan,+ diagnostics = plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision")) }, options));+ else stdout.WriteLine($"Built plan for {alias}: {outputPath}\nOriginal source PMI excluded explicitly; replacement PMI is generated.");+ return 0;+ }+ catch (Exception error) when (error is ArgumentException or IOException or UnauthorizedAccessException)+ {+ var diagnostic = new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ "imported-feature-command-rejected: " + error.Message, "CLI.ImportedFeatures");+ return Failure(new[] { FirmamentBuildAdmissionValidation.Present(diagnostic, args.Length > 1 ? args[1] : "command") });+ }++ int Failure(object diagnostics)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics }, options));+ else stderr.WriteLine(JsonSerializer.Serialize(diagnostics, options));+ return 1;+ }+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.csindex 780302f0..e8f457b3 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.cs@@ -1,6 +1,9 @@using System.Text.Json;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Brep.Boolean;+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Numerics;using Aetheris.Kernel.Core.Import;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Core.Tests.Step242;@@ -17,6 +20,60 @@ public sealed class BrepThroughHoleRevisionTestsstatic ThroughHoleRevisionRequest Request => new("MountHole", [new(1), new(2)], new(98), new(-130, 45, 0), 25,new(new(-175, 30, -50), new(-115, 60, 0)), .01);+ [Fact]+ public void DestinationContainment_ExcludesEntireInteriorOfAnExistingOpening()+ {+ var cut = BrepBoolean.Subtract(BrepPrimitives.CreateBox(40, 40, 10).Value,+ StandardLibrary.StandardLibraryPrimitives.CreateSlotCut(16, 8, 24, 4).Value);+ Assert.True(cut.IsSuccess, string.Join(" | ", cut.Diagnostics.Select(d => d.Message)));+ var exported = Step242Exporter.ExportBody(cut.Value);+ Assert.True(exported.IsSuccess);+ var imported = Step242Importer.ImportBody(exported.Value);+ Assert.True(imported.IsSuccess);+ var body = imported.Value;+ var top = Assert.Single(body.Topology.Faces, f => body.GetFaceSurface(f.Id).Plane is { } p+ && System.Math.Abs(p.Origin.Z - 5) < 1e-6 && System.Math.Abs(p.Normal.Z) > .99);+ Assert.True(AnalyticPlanarFaceDomain.TryContainsInPlanarFace(body, top.Id, new(0, 0, 5), ToleranceContext.Default, default, out var inOpening));+ Assert.False(inOpening);+ Assert.True(AnalyticPlanarFaceDomain.TryContainsInPlanarFace(body, top.Id, new(15, 0, 5), ToleranceContext.Default, default, out var inStock));+ Assert.True(inStock);+ }++ [Fact, Trait("Category", "SlowCorpus")]+ public void Discovery_GroupsSplitWallsAndReportsUnsupportedCandidates()+ {+ var discovery = BrepThroughHoleRevision.Discover(Source.Value, .01);+ Assert.True(discovery.Qualified);+ var hole = Assert.Single(discovery.Candidates, c => c.WallFaces.Contains(1));+ Assert.Equal(new[] { 1, 2 }, hole.WallFaces);+ Assert.True(hole.CanPlan); Assert.Equal(50, hole.Depth); Assert.Equal(98, hole.EntryFace);+ Assert.Contains(discovery.Candidates, c => !c.Recognized && c.Diagnostics.Count > 0);+ Assert.Equal(discovery.Candidates.Select(c => c.Id), BrepThroughHoleRevision.Discover(Source.Value.Clone(), .01).Candidates.Select(c => c.Id));+ var strict = BrepThroughHoleRevision.Discover(Source.Value, .001);+ Assert.False(strict.Qualified); Assert.DoesNotContain(strict.Candidates, c => c.CanPlan);+ }++ [Fact, Trait("Category", "SlowCorpus")]+ public void TwoLocalRegions_MoveAcrossCentralBossWithoutEditingIt()+ {+ var source = Source.Value;+ var candidate = Assert.Single(BrepThroughHoleRevision.Discover(source, .01).Candidates, c => c.WallFaces.Contains(1));+ var plan = BrepThroughHoleRevision.PlanMove(source, candidate.Id, "MovedMount", new(130,45,0), .01);+ Assert.True(plan.IsSuccess, string.Join(" | ", plan.Diagnostics.Select(d => d.Message)));+ var request = plan.Value.Request; var result = plan.Value.Revision;+ Assert.NotNull(request.DestinationWithin);+ var sweptEnvelope = new ThroughHoleEditBounds(request.Within.Min, request.DestinationWithin.Max);+ Assert.False(BrepThroughHoleRevision.Execute(source, request with { Within = sweptEnvelope, DestinationWithin = null }).IsSuccess);+ Assert.Equal(115, result.PreservedFaces); Assert.Equal(312, result.PreservedEdges);+ foreach (var face in source.Topology.Faces.Where(f => !candidate.WallFaces.Contains(f.Id.Value)))+ Assert.Equal(source.GetFaceSurface(face.Id), result.Body.GetFaceSurface(face.Id));+ Assert.False(BrepThroughHoleRevision.PlanMove(source, candidate.Id, "Occupied", new(160,45,0), .01).IsSuccess);+ var outside = BrepThroughHoleRevision.PlanMove(source, candidate.Id, "Outside", new(1000,45,0), .01);+ Assert.False(outside.IsSuccess);+ Assert.Contains(outside.Diagnostics, d => d.Message.Contains("outside the support face"));+ Assert.False(BrepThroughHoleRevision.PlanMove(source, "missing", "Missing", new(130,45,0), .01).IsSuccess);+ }+[Fact, Trait("Category", "SlowCorpus")]public void Ctc01_ExplicitSourceAccuracy_QualifiesAllTrimsWithoutChangingGeometry(){diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.cs b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.csnew file mode 100644index 00000000..a092b09c--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.cs@@ -0,0 +1,95 @@+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++/// <summary>A measured cylinder group. Recognized proves the bounded through-hole+/// family, not original manufacturing history or clearance at a new destination.</summary>+public sealed record ThroughHoleCandidate(string Id, bool Recognized, bool CanPlan,+ IReadOnlyList<int> WallFaces, IReadOnlyList<int> StepFaceEntities,+ Point3D AxisOrigin, Vector3D Axis, double Diameter, Point3D? Center,+ double? Depth, int? EntryFace, int? ExitFace, IReadOnlyList<string> Diagnostics)+{+ public string Kind => Recognized ? "RoundThroughHole" : "CylindricalGroup";+ public string Status => !Recognized ? "UnsupportedFamily" : CanPlan ? "Recognized" : "BlockedByImportQualification";+}++public sealed record ThroughHoleDiscovery(bool Qualified, double ImportToleranceMillimetres,+ IReadOnlyList<ThroughHoleCandidate> Candidates, IReadOnlyList<string> Diagnostics);++public sealed record ThroughHoleMovePlan(ThroughHoleRevisionRequest Request,+ ThroughHoleRevisionResult Revision);++public static partial class BrepThroughHoleRevision+{+ public static ThroughHoleDiscovery Discover(BrepBody source, double importToleranceMillimetres = .001)+ {+ ArgumentNullException.ThrowIfNull(source);+ var diagnostics = new List<string>();+ try { RequireQualified(source, importToleranceMillimetres); }+ catch (Exception error) when (IsRecognitionFailure(error)) { diagnostics.Add(error.Message); }+ var qualified = diagnostics.Count == 0;+ var candidates = new List<ThroughHoleCandidate>();+ var visited = new HashSet<FaceId>();+ var incidence = Incidence(source);+ foreach (var face in source.Topology.Faces.OrderBy(f => f.Id.Value))+ {+ if (visited.Contains(face.Id) || !source.TryGetFaceSurfaceGeometry(face.Id, out var surface)+ || surface?.Cylinder is not { } cylinder) continue;+ var walls = ConnectedWalls(source, face.Id, cylinder, incidence);+ visited.UnionWith(walls);+ var ids = walls.Select(id => id.Value).Order().ToArray();+ var entities = walls.Select(id => source.Bindings.GetFaceBinding(id).SourceStepEntityId)+ .OfType<int>().Order().ToArray();+ // Identity is scoped to the pinned source and independent of enumeration,+ // destination, user alias and geometric coordinates.+ var id = entities.Length == ids.Length+ ? "through-hole:step-" + string.Join('+', entities)+ : "through-hole:face-" + string.Join('+', ids);+ Region? region = null;+ var reasons = new List<string>(diagnostics);+ try { region = Recognize(source, face.Id); }+ catch (Exception error) when (IsRecognitionFailure(error)) { reasons.Add(error.Message); }+ var entry = region?.Openings.MaxBy(o => Surface(source, o.Face.Id).Plane!.Value.Origin.Z).Face;+ var exit = region?.Openings.MinBy(o => Surface(source, o.Face.Id).Plane!.Value.Origin.Z).Face;+ candidates.Add(new(id, region is not null, qualified && region is not null, ids, entities,+ cylinder.Origin, cylinder.Axis.ToVector(), 2 * cylinder.Radius,+ region is null ? null : new(cylinder.Origin.X, cylinder.Origin.Y, region.HighZ),+ region is null ? null : region.HighZ - region.LowZ, entry?.Id.Value, exit?.Id.Value, reasons));+ }+ return new(qualified, importToleranceMillimetres, candidates, diagnostics);+ }++ /// <summary>Derives two local stock regions and executes the same production+ /// operation to prove admission. No swept movement corridor is required.</summary>+ public static KernelResult<ThroughHoleMovePlan> PlanMove(BrepBody source, string candidateId,+ string featureId, Point3D destination, double importToleranceMillimetres = .001,+ double clearanceMillimetres = .1)+ {+ if (!double.IsFinite(clearanceMillimetres) || clearanceMillimetres <= System.Math.Max(Tol, importToleranceMillimetres))+ return PlanFailure("Clearance must be finite and greater than the numerical import uncertainty.");+ var discovery = Discover(source, importToleranceMillimetres);+ var candidate = discovery.Candidates.SingleOrDefault(c => c.Id == candidateId);+ if (candidate is null) return PlanFailure("Candidate does not exist in this pinned source. Inspect the source again; no nearest-feature fallback is performed.");+ if (!candidate.CanPlan) return PlanFailure(string.Join(" | ", candidate.Diagnostics));+ var region = Recognize(source, new(candidate.WallFaces[0]));+ ThroughHoleEditBounds BoundsAt(Point3D center)+ {+ var r = candidate.Diameter / 2 + clearanceMillimetres;+ return new(new(center.X - r, center.Y - r, region.LowZ), new(center.X + r, center.Y + r, region.HighZ));+ }+ var request = new ThroughHoleRevisionRequest(featureId, candidate.WallFaces.Select(id => new FaceId(id)).ToArray(),+ new(candidate.EntryFace!.Value), destination, candidate.Diameter, BoundsAt(candidate.Center!.Value), importToleranceMillimetres)+ { DestinationWithin = BoundsAt(destination) };+ var executed = Execute(source, request);+ return executed.IsSuccess ? KernelResult<ThroughHoleMovePlan>.Success(new(request, executed.Value), executed.Diagnostics)+ : KernelResult<ThroughHoleMovePlan>.Failure(executed.Diagnostics);+ }++ static bool IsRecognitionFailure(Exception error) => error is ArgumentException or InvalidOperationException or KeyNotFoundException or NotSupportedException;+ static KernelResult<ThroughHoleMovePlan> PlanFailure(string reason) => KernelResult<ThroughHoleMovePlan>.Failure([+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ "firmament-imported-hole-plan-rejected: " + reason, "Brep.ThroughHoleRevision")]);+}diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.csindex c837cb63..6c3ae42a 100644--- a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs+++ b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs@@ -2,6 +2,8 @@ using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Numerics;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Results;using Aetheris.Kernel.Core.Topology;@@ -11,17 +13,23 @@ namespace Aetheris.Kernel.Core.Brep.Features;public sealed record ThroughHoleEditBounds(Point3D Min, Point3D Max);public sealed record ThroughHoleRevisionRequest(string FeatureId, IReadOnlyList<FaceId> WallFaces,FaceId EntryFace, Point3D Center, double Diameter, ThroughHoleEditBounds Within,- double ImportToleranceMillimetres = 1e-6);+ double ImportToleranceMillimetres = 1e-6)+{+ public ThroughHoleEditBounds? DestinationWithin { get; init; }+}public sealed record ThroughHoleRevisionResult(BrepBody Body, string FeatureId,IReadOnlyList<FaceId> RetiredWallFaces, IReadOnlyList<FaceId> WallFaces,FaceId EntryFace, FaceId ExitFace, Point3D Center, double Diameter, double Depth,ThroughHoleEditBounds Within, IReadOnlyDictionary<FaceId, FaceId> FaceCorrespondence,- int PreservedFaces, int PreservedEdges, double ImportToleranceMillimetres);+ int PreservedFaces, int PreservedEdges, double ImportToleranceMillimetres)+{+ public ThroughHoleEditBounds? DestinationWithin { get; init; }+}/// <summary>Atomic, same-size through-hole replacement in a certified constant-stock/// prism. It retains the residual BRep and constructs new analytic hole geometry./// The first admitted family is Z-axis, isolated, round and through two planar supports.</summary>-public static class BrepThroughHoleRevision+public static partial class BrepThroughHoleRevision{const double Tol = 1e-6;sealed record Region(HashSet<FaceId> Walls, (Face Face, Loop Loop)[] Openings,@@ -52,18 +60,34 @@ public static class BrepThroughHoleRevisionthrow new ArgumentException("This revision admits unchanged diameter only; resizing is unsupported.");if (!Finite(request.Center) || System.Math.Abs(request.Center.Z - Surface(source, entry.Id).Plane!.Value.Origin.Z) > Tol)throw new ArgumentException("The world-space center must lie on the selected entry plane.");- var box = new Box(request.Within.Min, request.Within.Max);- if (!Finite(box.Min) || !Finite(box.Max) || box.Min.X >= box.Max.X || box.Min.Y >= box.Max.Y- || System.Math.Abs(box.Min.Z - region.LowZ) > Tol || System.Math.Abs(box.Max.Z - region.HighZ) > Tol)- throw new ArgumentException("The edit envelope must be finite and span exactly the two support planes.");+ var sourceBox = new Box(request.Within.Min, request.Within.Max);+ var destination = request.DestinationWithin ?? request.Within;+ var destinationBox = new Box(destination.Min, destination.Max);+ foreach (var box in new[] { sourceBox, destinationBox })+ if (!Finite(box.Min) || !Finite(box.Max) || box.Min.X >= box.Max.X || box.Min.Y >= box.Max.Y+ || System.Math.Abs(box.Min.Z - region.LowZ) > Tol || System.Math.Abs(box.Max.Z - region.HighZ) > Tol)+ throw new ArgumentException("Each edit region must be finite and span exactly the two support planes.");var r = request.Diameter / 2;- foreach (var center in new[] { region.Cylinder.Origin, request.Center })+ foreach (var (center, box) in new[] { (region.Cylinder.Origin, sourceBox), (request.Center, destinationBox) })if (center.X - r <= box.Min.X + Tol || center.X + r >= box.Max.X - Tol || center.Y - r <= box.Min.Y + Tol || center.Y + r >= box.Max.Y - Tol)- throw new ArgumentException("The edit envelope must contain both complete holes with positive clearance.");+ throw new ArgumentException("The source/destination region must contain its complete hole with positive clearance.");var authorized = region.Walls.Concat(region.Openings.Select(o => o.Face.Id)).ToHashSet();- var conflicts = source.Topology.Faces.Where(f => !authorized.Contains(f.Id) && box.Overlaps(FaceBounds(source, f), System.Math.Max(Tol, request.ImportToleranceMillimetres))).Select(f => f.Id.Value).ToArray();+ var conflicts = source.Topology.Faces.Where(f => !authorized.Contains(f.Id)+ && new[] { sourceBox, destinationBox }.Any(box => box.Overlaps(FaceBounds(source, f), System.Math.Max(Tol, request.ImportToleranceMillimetres))))+ .Select(f => f.Id.Value).ToArray();if (conflicts.Length > 0)throw new ArgumentException($"The stock envelope may intersect unrelated boundary faces: {string.Join(',', conflicts)}. Narrow the operation or choose another destination.");+ if (request.DestinationWithin is not null)+ foreach (var opening in region.Openings)+ {+ // Boundary exclusion proves the entire destination prism has+ // constant stock only after anchoring it inside both supports.+ var probe = new Point3D(request.Center.X, request.Center.Y, Surface(source, opening.Face.Id).Plane!.Value.Origin.Z);+ var tolerance = new ToleranceContext(System.Math.Max(Tol, request.ImportToleranceMillimetres), 1e-9);+ if (!AnalyticPlanarFaceDomain.TryContainsInPlanarFace(source, opening.Face.Id, probe, tolerance, opening.Loop.Id, out var inside))+ throw new ArgumentException("Separate edit regions require proved line/circle trim boundaries on both planar supports; use one qualified envelope for other support outlines.");+ if (!inside) throw new ArgumentException("The destination is outside the support face material domain; no material column exists there.");+ }var patch = MaterializeHolePatch(source, region, request.Center, r);var suppressed = Suppress(source, region);RequireQualified(suppressed, request.ImportToleranceMillimetres);@@ -76,7 +100,7 @@ public static class BrepThroughHoleRevisionreturn KernelResult<ThroughHoleRevisionResult>.Success(new(body, request.FeatureId,region.Walls.OrderBy(id => id.Value).ToArray(), walls, entry.Id, exit, request.Center, request.Diameter,region.HighZ - region.LowZ, request.Within, map, source.Topology.Faces.Count() - region.Walls.Count,- source.Topology.Edges.Count() - region.Edges.Count, request.ImportToleranceMillimetres));+ source.Topology.Edges.Count() - region.Edges.Count, request.ImportToleranceMillimetres) { DestinationWithin = request.DestinationWithin });}catch (Exception error) when (error is ArgumentException or InvalidOperationException or KeyNotFoundException or NotSupportedException){@@ -102,21 +126,8 @@ public static class BrepThroughHoleRevision{var cylinder = Surface(body, seed).Cylinder ?? throw new ArgumentException("Seed must be cylindrical.");if (cylinder.Axis.ToVector().Cross(new Vector3D(0, 0, 1)).Length > Tol) throw new ArgumentException("Only Z-axis holes are admitted.");- var incidence = body.Topology.Faces.SelectMany(f => Edges(body, f).Select(e => (Edge: e, Face: f.Id)))- .GroupBy(x => x.Edge).ToDictionary(g => g.Key, g => g.Select(x => x.Face).Distinct().ToArray());- var walls = new HashSet<FaceId> { seed };- var queue = new Queue<FaceId>(); queue.Enqueue(seed);- while (queue.TryDequeue(out var id))- {- foreach (var adjacent in Edges(body, body.Topology.GetFace(id)).SelectMany(e => incidence[e]).Distinct())- {- if (walls.Contains(adjacent) || Surface(body, adjacent).Cylinder is not { } other) continue;- var d = other.Origin - cylinder.Origin;- if (System.Math.Abs(other.Radius - cylinder.Radius) > Tol || other.Axis.ToVector().Cross(cylinder.Axis.ToVector()).Length > Tol- || (d - cylinder.Axis.ToVector() * d.Dot(cylinder.Axis.ToVector())).Length > Tol) continue;- walls.Add(adjacent); queue.Enqueue(adjacent);- }- }+ var incidence = Incidence(body);+ var walls = ConnectedWalls(body, seed, cylinder, incidence);if (walls.Any(id => body.Bindings.GetFaceBinding(id).Orientation.IsAlignedWithSurface)) throw new ArgumentException("Not an inward cylindrical void wall.");var wallEdges = walls.SelectMany(id => Edges(body, body.Topology.GetFace(id))).ToHashSet();var openings = new List<(Face Face, Loop Loop)>();@@ -161,6 +172,28 @@ public static class BrepThroughHoleRevisionreturn new(walls, openings.ToArray(), wallEdges, vertices, cylinder, z[0], z[1]);}+ static Dictionary<EdgeId, FaceId[]> Incidence(BrepBody body) => body.Topology.Faces+ .SelectMany(f => Edges(body, f).Select(e => (Edge: e, Face: f.Id)))+ .GroupBy(x => x.Edge).ToDictionary(g => g.Key, g => g.Select(x => x.Face).Distinct().ToArray());++ static HashSet<FaceId> ConnectedWalls(BrepBody body, FaceId seed, CylinderSurface cylinder, Dictionary<EdgeId, FaceId[]> incidence)+ {+ var walls = new HashSet<FaceId> { seed };+ var queue = new Queue<FaceId>(); queue.Enqueue(seed);+ while (queue.TryDequeue(out var id))+ {+ foreach (var adjacent in Edges(body, body.Topology.GetFace(id)).SelectMany(e => incidence[e]).Distinct())+ {+ if (walls.Contains(adjacent) || Surface(body, adjacent).Cylinder is not { } other) continue;+ var d = other.Origin - cylinder.Origin;+ if (System.Math.Abs(other.Radius - cylinder.Radius) > Tol || other.Axis.ToVector().Cross(cylinder.Axis.ToVector()).Length > Tol+ || (d - cylinder.Axis.ToVector() * d.Dot(cylinder.Axis.ToVector())).Length > Tol) continue;+ walls.Add(adjacent); queue.Enqueue(adjacent);+ }+ }+ return walls;+ }+static BrepBody MaterializeHolePatch(BrepBody source, Region region, Point3D center, double radius){var changedCurves = region.Edges.Select(e => source.Bindings.GetEdgeBinding(e).CurveGeometryId).ToHashSet();diff --git a/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs b/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.csindex 7b9e30c7..7546afdb 100644--- a/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs+++ b/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs@@ -167,6 +167,62 @@ internal sealed class AnalyticPlanarFaceDomainreturn true;}+ // Unlike the display domain, admission never falls back to whole-body bounds.+ // Arc chords preserve winding only when the probe is separated by more than+ // their certified sag plus the imported endpoint uncertainty.+ internal static bool TryContainsInPlanarFace(BrepBody body, FaceId faceId,+ Point3D point, ToleranceContext tolerance, LoopId removedInnerLoop, out bool inside)+ {+ inside = false;+ var face = body.Topology.GetFace(faceId);+ if (face.LoopIds.Any(id => !body.Bindings.TryGetFaceBoundaryRoleBinding(id, out _))) return false;+ var outers = face.LoopIds.Where(id => body.Bindings.GetFaceBoundaryRoleBinding(id).Role == FaceBoundaryRole.Outer).ToArray();+ if (outers.Length != 1 || body.GetFaceSurface(faceId).Plane is not { } plane) return false;+ if (!TryClassifyLoop(outers[0], out inside)) return false;+ if (!inside) return true;+ foreach (var loopId in face.LoopIds.Where(id => id != outers[0] && id != removedInnerLoop))+ {+ if (body.Bindings.GetFaceBoundaryRoleBinding(loopId).Role != FaceBoundaryRole.Inner+ || !TryClassifyLoop(loopId, out var inHole)) return false;+ if (inHole) { inside = false; return true; }+ }+ return true;++ bool TryClassifyLoop(LoopId loopId, out bool contains)+ {+ contains = false;+ var points = new List<(double U, double V)>();+ var deviation = tolerance.Linear;+ foreach (var coedgeId in body.Topology.GetLoop(loopId).CoedgeIds)+ {+ var coedge = body.Topology.GetCoedge(coedgeId);+ var edge = body.Topology.GetEdge(coedge.EdgeId);+ if (!body.TryGetVertexPoint(coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId, out var start)+ || !body.TryGetVertexPoint(coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId, out var end)) return false;+ var curve = body.GetEdgeCurve(edge.Id);+ if (curve.Kind == CurveGeometryKind.Line3) points.Add(ProjectToPlane(start, plane));+ else if (curve.Circle3 is { } circle)+ {+ var binding = body.Bindings.GetEdgeBinding(edge.Id);+ if (binding.TrimInterval is not { } interval || System.Math.Abs(interval.End - interval.Start) > 2 * double.Pi + tolerance.Angular) return false;+ var samples = CurveSampler.SampleCircleArc(circle, interval.Start, interval.End - interval.Start).ToArray();+ if (coedge.IsReversed == binding.OrientedEdgeSense) Array.Reverse(samples);+ if ((samples[0] - start).Length > tolerance.Linear || (samples[^1] - end).Length > tolerance.Linear) return false;+ var step = System.Math.Abs(interval.End - interval.Start) / (samples.Length - 1);+ if (step > double.Pi) return false;+ deviation = System.Math.Max(deviation, circle.Radius * (1 - double.Cos(step / 2)) + tolerance.Linear);+ for (var i = 0; i < samples.Length - 1; i++) points.Add(ProjectToPlane(samples[i], plane));+ }+ else return false;+ }+ if (points.Count < 3) return false;+ var uv = ProjectToPlane(point, plane);+ if (Enumerable.Range(0, points.Count).Any(i => DistancePointToSegmentSquared(uv, points[i], points[(i + 1) % points.Count]) <= deviation * deviation)) return false;+ contains = ContainsPoint(points, uv, tolerance);+ return true;+ }+ }+public bool IsNearBoundary(Point3D point, ToleranceContext tolerance, out double boundaryDistance, out bool nearVertex){diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.csindex fc1811c8..a1bea811 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs@@ -61,7 +61,8 @@ public sealed class FirmamentProjectSnapshotTestsvar project = new FirmamentProjectSnapshot("main.firmasm", [KeyValuePair.Create("main.firmasm", "Assembly Root { <Assembly Root><Part External = ExternalStep<\"C:/secret.step\">></Part></Assembly> Anchor: Root; }")]);var result = new AssemblyM1Pipeline().CompileProject(project);- Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "assembly-profile-external-resource-unsupported");+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "assembly-include-outside-root");}[Fact]diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.csindex 42650dca..51e4ac3a 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs@@ -41,7 +41,7 @@ public sealed class FirmamentDirectiveAndCasingTests{var located = Assert.Single(parsed.SyntaxDiagnostics);Assert.Equal("include \"__missing_syntax_review__.firmament\"", source.Substring(located.SourceSpan!.Start, located.SourceSpan.Length));- Assert.Contains(build.Diagnostics, d => d.Message.Contains("standalone part compilation", StringComparison.Ordinal));+ Assert.Contains(build.Diagnostics, d => d.Message.Contains("assembly-include-file-not-found", StringComparison.Ordinal));var marker = Assert.Single(FirmamentLanguageAnalysisService.Analyze(source, Fixture(fixture), "1").Diagnostics);Assert.Equal(located.SourceSpan.Start, marker.Start);Assert.Contains("__missing_syntax_review__.firmament", marker.Message, StringComparison.Ordinal);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.csindex 2b9bf557..6a918040 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Firmament.FirmamentV2;@@ -18,6 +19,70 @@ public sealed class FirmamentImportedHoleRevisionTestsstatic FirmamentV2ValidationReport Validate(string source) => FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source, DirectoryPath), "ctc01-hole-move.firmament", sourceText: source), source, DirectoryPath);+ [Fact]+ public void RecoveryPlan_UsesNamedLayoutAndRebuildsAfterOnlyTargetChanges()+ {+ var inspection = FirmamentImportedFeatures.Inspect(File.ReadAllText(StepPath), .01).Value;+ var selected = Assert.Single(inspection.Discovery.Candidates, c => c.CanPlan && c.Center is {} p && System.Math.Abs(p.X+160)<1e-6 && System.Math.Abs(p.Y-45)<1e-6 && System.Math.Abs(c.Diameter-25)<1e-6);+ var planned = FirmamentImportedFeatures.PlanMove(inspection, selected.Id, "MountHole", new(130.04,45.0000000000001,-1e-14), true,+ clearanceMillimetres: .11);+ Assert.True(planned.IsSuccess, string.Join(" | ", planned.Diagnostics.Select(d => d.Message)));+ Assert.Equal("Built", planned.Value.Admission);+ Assert.Contains("center: RevisionLayout.Targets.MountHole", planned.Value.Source);+ Assert.Contains("MountHole: Point3(130mm, 45mm, 0mm)", planned.Value.Source);+ Assert.Contains("diameter: 25mm", planned.Value.Source);+ Assert.Contains("importTolerance: 0.01mm", planned.Value.Source);+ Assert.DoesNotContain("999999", planned.Value.Source);+ Assert.Equal(.1, planned.Value.AuthoringIncrementMillimetres);+ Assert.Equal(25, planned.Value.Revision.Diameter);+ Assert.Equal(-172.7, planned.Value.Revision.Within.Min.X);+ Assert.Equal(32.3, planned.Value.Revision.Within.Min.Y);+ Assert.Contains("MountHole.X - 12.7mm", planned.Value.Source);+ Assert.DoesNotContain("-0mm", planned.Value.Source);+ var physical = Step242Importer.ImportBody(planned.Value.Export.StepText).Value;+ var pmi = Assert.Single(Step242SemanticPmiInspector.Inspect(planned.Value.Export.StepText).Items, item => item.Kind == "Diameter");+ Assert.Equal(25, pmi.Value);+ Assert.All(pmi.GeometricFaceEntityIds, id =>+ {+ var face = Assert.Single(physical.Bindings.FaceBindings, b => b.SourceStepEntityId == id);+ var wall = physical.GetFaceSurface(face.FaceId).Cylinder!.Value;+ Assert.Equal(130, wall.Origin.X);+ Assert.Equal(45, wall.Origin.Y);+ Assert.Equal(12.5, wall.Radius);+ });+ Assert.NotNull(planned.Value.Revision.DestinationWithin);+ var edited = planned.Value.Source.Replace("MountHole: Point3(130mm, 45mm, 0mm)", "MountHole: Point3(-130mm, 45mm, 0mm)");+ Assert.NotEqual(planned.Value.Source, edited);+ var rebuilt = FirmamentBuildAndExport.CompileSource(edited, "", new Dictionary<string,string> { ["input.step"] = File.ReadAllText(StepPath) });+ Assert.True(rebuilt.IsSuccess, string.Join(" | ", rebuilt.Diagnostics.Select(d => d.Message)));+ Assert.Equal(-130, rebuilt.Value.ImportedHoleRevision!.DestinationWithin!.Min.X + (rebuilt.Value.ImportedHoleRevision.DestinationWithin.Max.X-rebuilt.Value.ImportedHoleRevision.DestinationWithin.Min.X)/2, 6);+ Assert.Equal(115, rebuilt.Value.ImportedHoleRevision.PreservedFaces);+ var occupied = planned.Value.Source.Replace("MountHole: Point3(130mm, 45mm, 0mm)", "MountHole: Point3(160mm, 45mm, 0mm)");+ var resources = new Dictionary<string, string> { ["input.step"] = File.ReadAllText(StepPath) };+ Assert.False(FirmamentBuildAndExport.CompileSource(occupied, "", resources).IsSuccess);+ Assert.False(FirmamentImportedFeatures.PlanMove(inspection, selected.Id, "MountHole", new(130,45,0), false).IsSuccess);+ Assert.False(FirmamentImportedFeatures.PlanMove(inspection, selected.Id, "Not.AnIdentifier", new(130,45,0), true).IsSuccess);+ }++ [Fact]+ public void RecoveredGoldenFixture_ValidateAndBuildAgree()+ {+ var source = File.ReadAllText(Path.Combine(DirectoryPath,"ctc01-recovered-hole-move.firmament"));+ Assert.Equal("valid", Validate(source).Status);+ var build = FirmamentBuildAndExport.CompileSource(source,DirectoryPath);+ Assert.True(build.IsSuccess,string.Join(" | ",build.Diagnostics.Select(d=>d.Message)));+ Assert.Equal(115,build.Value.ImportedHoleRevision!.PreservedFaces);+ var invalid = source.Replace("through-hole:step-764+765", "through-hole:step-stale");+ Assert.Equal("invalid",Validate(invalid).Status);+ Assert.False(FirmamentBuildAndExport.CompileSource(invalid,DirectoryPath).IsSuccess);+ var conflicting = source.Replace("kind: HoleShaft", "kind: HoleShaft\n faces: [1, 2]");+ Assert.Equal("invalid", Validate(conflicting).Status);+ Assert.False(FirmamentBuildAndExport.CompileSource(conflicting, DirectoryPath).IsSuccess);+ var missingBounds = source.Replace("within: [", "within: [null,");+ Assert.Equal("invalid", Validate(missingBounds).Status);+ Assert.False(FirmamentBuildAndExport.CompileSource(missingBounds, DirectoryPath).IsSuccess);+ }+[Fact]public void GoldenPath_AdmitsBuildsAndExportsQualifiedMovedHoleWithSemanticPmi(){@@ -123,7 +188,7 @@ public sealed class FirmamentImportedHoleRevisionTests[InlineData("field")][InlineData("bounds-field")][InlineData("import-field")]- [InlineData("pin-conflict")][InlineData("named-face")][InlineData("object-type")][InlineData("no-replacement")]+ [InlineData("pin-conflict")][InlineData("named-face")][InlineData("object-type")][InlineData("no-pin")][InlineData("notes")]public void InvalidIntent_ValidateAndBuildRejectWithLocatedDiagnostics(string change)@@ -142,7 +207,6 @@ public sealed class FirmamentImportedHoleRevisionTests"pin-conflict" => Source.Replace("textSha256:", "sha256: \"0000000000000000000000000000000000000000000000000000000000000000\"\n textSha256:"),"named-face" => Source.Replace("Source.Face(98)", "Source.Face(ignored: 98)"),"object-type" => Source.Replace("within: {", "within: Nonsense {"),- "no-replacement" => Source[..Source.IndexOf(" Replace Source.MountHole", StringComparison.Ordinal)] + "}\n","no-pin" => Source.Replace("textSha256:", "// textSha256:"),"notes" => Source.Replace("radius: 12.5mm", "notes: [12]\n radius: 12.5mm"),"bounds-field" => Source.Replace("min: Point3", "minimum: Point3"),diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentImportedResourceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedResourceTests.csnew file mode 100644index 00000000..7067e2fe--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedResourceTests.cs@@ -0,0 +1,182 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Modules;+using System.Security.Cryptography;+using System.Text;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentImportedResourceTests+{+ static readonly string Part = Step242Exporter.ExportBody(BrepPrimitives.CreateBox(4, 6, 8).Value).Value;+ const string Tree = "Assembly Machine { <Assembly Machine><Part A = bearing>Placement { from: Origin; to: World; }</Part><Part B = bearing>Placement { from: Origin; to: World; translateLocal: [50mm,0mm,0mm]; }</Part></Assembly> Anchor: Machine; }";+ static void Accepted(AssemblyM1CompilationResult result) => Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Code + ": " + d.Message)));+ static string Hash(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))).ToLowerInvariant();+ static string Lock(string root = "main.firmasm", string? part = null) => new FirmamentDependencyLock(root,+ [new("vendor/bearing.step", "step", "sha256-bytes", Hash(part ?? Part))]).ToToml();++ [Fact]+ public void TypedIncludeAndInventoryUseTheSameSnapshotGeometryAndIdentity()+ {+ const string include = "include bearing: Part = Step(\"vendor/bearing\"); ";+ var parsed = FirmamentSyntaxParser.Parse(include + Tree);+ Assert.True(parsed.IsSuccess);+ Assert.True(FirmamentSyntaxParser.Parse(FirmamentSyntaxWriter.Statements(parsed.Document.Statements)).IsSuccess);+ var shortForm = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", [new("main.firmasm", include + Tree), new("vendor/bearing.step", Part)]));+ Accepted(shortForm);+ var catalog = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", [+ new("main.firmasm", "Inventory Record Components { bearing: Part = Step(\"vendor/bearing\") } " + Tree.Replace("= bearing", "= Components.bearing")), new("vendor/bearing.step", Part)]));+ Accepted(catalog);+ Assert.Single(shortForm.Geometry!.DefinitionBodies);+ Assert.Equal(2, shortForm.Geometry.InstanceBodies.Count);+ Assert.Equal(catalog.Geometry!.DefinitionBodies.Keys, shortForm.Geometry.DefinitionBodies.Keys);+ Assert.Equal(new[] { -2d, -3, -4 }, Assert.Single(shortForm.Geometry.Artifact.Definitions).Metrics.Minimum);+ Assert.Contains(shortForm.Ir!.SourceDependencies!, d => d.Path == "vendor/bearing.step");+ }++ [Fact]+ public void StepAssemblyRetainsHierarchyTransformsAndSharedLeafGeometry()+ {+ var identity = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };+ var translated = (double[])identity.Clone(); translated[12] = 25;+ var asset = Step242AssemblyExporter.Export(new("Imported", "root", [new("bolt", "Bolt", BrepPrimitives.CreateBox(4,6,8).Value)], [+ new("root", "Root", null, null, identity), new("first", "First", "root", "bolt", identity), new("second", "Second", "root", "bolt", translated)]));+ Assert.True(asset.IsSuccess);+ var source = "include drive: Assembly = Step(\"vendor/drive\"); Assembly Machine { <Assembly Machine><Assembly Unit = drive>Placement { from: Origin; to: World; }</Assembly></Assembly> Anchor: Machine; }";+ var result = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", [new("main.firmasm", source), new("vendor/drive.step", asset.Value)]));+ Accepted(result);+ Assert.Single(result.Geometry!.DefinitionBodies);+ Assert.Equal(2, result.Geometry.InstanceBodies.Count);+ Assert.Contains(result.Ir!.Instances, i => i.Path.ToString() == "Machine.Unit.second" && i.ResolvedTransform!.Matrix[12] == 25);+ Assert.True(AssemblyIrAp242Exporter.Export(result).IsSuccess);+ }++ [Fact]+ public void NestedStepAssemblyPreservesLocalTransformsAndRepeatedGeometry()+ {+ double[] Matrix(double x) => [1,0,0,0,0,1,0,0,0,0,1,0,x,0,0,1];+ var asset = Step242AssemblyExporter.Export(new("Imported", "root", [new("bolt","Bolt",BrepPrimitives.CreateBox(4,6,8).Value)], [+ new("root","Root",null,null,Matrix(0)),new("unitA","Unit","root",null,Matrix(20)), new("unitB","Unit","root",null,Matrix(60)),+ new("boltA","Bolt","unitA","bolt",Matrix(5)),new("boltB","Bolt","unitB","bolt",Matrix(5))]));+ Assert.True(asset.IsSuccess);+ var source = "include drive: Assembly = Step(\"drive\"); Assembly Machine { <Assembly Machine><Assembly Drive = drive>Placement { from: Origin; to: World; }</Assembly></Assembly> Anchor: Machine; }";+ var result = new AssemblyM1Pipeline().CompileProject(new("main.firmasm",[new("main.firmasm",source),new("drive.step",asset.Value)]));+ Accepted(result);+ Assert.Single(result.Geometry!.DefinitionBodies);+ Assert.Equal(2,result.Geometry.InstanceBodies.Count);+ Assert.Contains(result.Ir!.Instances,i => i.Path.ToString().EndsWith("unitA.boltA",StringComparison.Ordinal) && i.ResolvedTransform!.Matrix[12] == 25);+ Assert.Contains(result.Ir.Instances,i => i.Path.ToString().EndsWith("unitB.boltB",StringComparison.Ordinal) && i.ResolvedTransform!.Matrix[12] == 65);+ Assert.True(Step242AssemblyImporter.Import(AssemblyIrAp242Exporter.Export(result).Value).IsSuccess);+ }++ [Fact]+ public void AnnotatedStepRequiresExplicitGeometryOnlyAdmission()+ {+ var annotated = Step242Exporter.ExportBody(BrepPrimitives.CreateBox(4,6,8).Value,+ [new Step242SemanticPmiDatum("Body","plane","A","+Z")]).Value;+ var source = "include bearing: Part = Step(\"vendor/bearing\"); " + Tree;+ AssemblyM1CompilationResult Build(string text) => new AssemblyM1Pipeline().CompileProject(new("main.firmasm",[new("main.firmasm",text),new("vendor/bearing.step",annotated)]));+ var refused = Build(source); Assert.False(refused.IsSuccess);+ Assert.Contains(refused.Diagnostics,d => d.Code == "firmament-step-source-pmi-unsupported");+ var admitted = Build(source.Replace("Step(\"vendor/bearing\")","Step(\"vendor/bearing\", geometryOnly: true)")); Accepted(admitted);+ Assert.True(Assert.Single(admitted.Ir!.InventoryBindings).GeometryOnly);+ Assert.Empty(Step242SemanticPmiInspector.Inspect(AssemblyIrAp242Exporter.Export(admitted).Value).Items);+ }++ [Fact]+ public void SnapshotLockIsOptionalButAnExistingReceiptCannotBeBypassed()+ {+ var source = "include bearing: Part = Step(\"vendor/bearing\"); " + Tree;+ var documents = new Dictionary<string,string> { ["main.firmasm"] = source, ["vendor/bearing.step"] = Part, [FirmamentDependencyLock.FileName] = Lock() };+ Accepted(new AssemblyM1Pipeline().CompileProject(new("main.firmasm", documents)));+ documents["vendor/bearing.step"] = Step242Exporter.ExportBody(BrepPrimitives.CreateBox(5,6,8).Value).Value;+ var changed = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", documents));+ Assert.False(changed.IsSuccess);+ Assert.Contains(changed.Diagnostics, d => d.Code == "firmament-lock-dependency-mismatch");+ documents["vendor/bearing.step"] = Part;+ documents[FirmamentDependencyLock.FileName] = Lock("another.firmasm");+ var wrongRoot = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", documents));+ Assert.False(wrongRoot.IsSuccess);+ Assert.Contains(wrongRoot.Diagnostics, d => d.Code == "firmament-lock-root-mismatch");+ // A real file with the source-only adapter's conventional name is still+ // a real root; special filenames cannot bypass root identity checking.+ var specialName = new AssemblyM1Pipeline().CompileProject(new("__provided_source.firmament",[+ new("__provided_source.firmament",source), new("vendor/bearing.step",Part), new(FirmamentDependencyLock.FileName,Lock("another.firmasm"))]));+ Assert.False(specialName.IsSuccess);+ Assert.Contains(specialName.Diagnostics,d => d.Code == "firmament-lock-root-mismatch");+ documents[FirmamentDependencyLock.FileName] = Lock() + "unexpected = true\n";+ Assert.False(new AssemblyM1Pipeline().CompileProject(new("main.firmasm", documents)).IsSuccess);+ }++ [Fact]+ public void StandaloneRootCanLockAnEmptyDependencySet()+ {+ var empty = new FirmamentDependencyLock("standalone.firmament", []);+ var parsed = FirmamentDependencyLock.Parse(empty.ToToml());+ Assert.Equal(empty.Root,parsed.Root);+ Assert.Empty(parsed.Dependencies);+ var invalid = Lock().Replace("vendor/bearing.step","../outside.step",StringComparison.Ordinal);+ Assert.Throws<ArgumentException>(() => FirmamentDependencyLock.Parse(invalid));+ }++ [Theory]+ [InlineData("from: bearing")]+ [InlineData("from: Components.bearing")]+ [InlineData("path: \"vendor/bearing.step\"")]+ public void InlineStepUsesLockedResourcesWithoutAuthoredHashes(string binding)+ {+ var prefix = binding.Contains("Components") ? "Inventory Record Components { bearing: Part = Step(\"vendor/bearing\") } "+ : binding.StartsWith("from:") ? "include bearing: Part = Step(\"vendor/bearing\"); " : "";+ var source = prefix + "Model Surgery { units: mm InlineStep Source { " + binding + "; geometryOnly: true } }";+ var resources = new Dictionary<string,string> { ["vendor/bearing.step"] = Part, [FirmamentDependencyLock.FileName] = Lock("surgery.firmament") };+ var result = FirmamentBuildAndExport.CompileSource(source, "", resources);+ Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Message)));+ Assert.Null(result.Value.ImportedHoleRevision);+ var imported = Step242Importer.ImportBody(result.Value.StepText);+ Assert.True(imported.IsSuccess);+ Assert.Equal(6, imported.Value.Topology.Faces.Count());+ Assert.Equal(12, imported.Value.Topology.Edges.Count());+ var vertices = imported.Value.Topology.Vertices.Select(v =>+ { Assert.True(imported.Value.TryGetVertexPoint(v.Id,out var point)); return point; }).ToArray();+ Assert.Equal(new[]{-2d,-3,-4},new[]{vertices.Min(p=>p.X),vertices.Min(p=>p.Y),vertices.Min(p=>p.Z)});+ Assert.Equal(new[]{2d,3,4},new[]{vertices.Max(p=>p.X),vertices.Max(p=>p.Y),vertices.Max(p=>p.Z)});+ resources["vendor/bearing.step"] = Part + "\n";+ Assert.False(FirmamentBuildAndExport.CompileSource(source, "", resources).IsSuccess);+ }++ [Fact]+ public void ImportMetadataBindsOrdinaryRecordsAndDoesNotAlterGeometry()+ {+ const string data = "Record VendorInfo { manufacturer: String revision: String } Static Receipt: VendorInfo { manufacturer: \"Acme\" revision: \"A\" } ";+ var source = data + "Inventory Record Components { bearing: Part = Step(\"vendor/bearing\", metadata: Receipt) } " + Tree.Replace("= bearing", "= Components.bearing");+ AssemblyM1CompilationResult Build(string text) => new AssemblyM1Pipeline().CompileProject(new("main.firmasm", [new("main.firmasm", text), new("vendor/bearing.step", Part)]));+ var before = Build(source); Accepted(before);+ var after = Build(source.Replace("revision: \"A\"", "revision: \"B\"")); Accepted(after);+ var receipt = Assert.Single(before.Ir!.InventoryBindings);+ Assert.Equal("VendorInfo", receipt.MetadataType);+ Assert.Equal("Acme", receipt.Metadata["manufacturer"]);+ Assert.Equal("B", Assert.Single(after.Ir!.InventoryBindings).Metadata["revision"]);+ Assert.Equal(before.Geometry!.Artifact.DeterministicSha256, after.Geometry!.Artifact.DeterministicSha256);+ Assert.False(Build(source.Replace("metadata: Receipt", "metadata: Missing")).IsSuccess);+ }++ [Fact]+ public void NestedReleaseRecordsUseTheOrdinaryTypedBinder()+ {+ var source = "Record Person { name: String role: String } Record ReleaseInfo { author: Person date: Date version: Version description: String } "+ + "Static Designer: Person { name: \"Engineer\" role: \"Designer\" } Static Release: ReleaseInfo { author: Designer date: 2026-10-21 version: 1.0.0 description: \"Review witness\" } "+ + "include bearing: Part = Step(\"vendor/bearing\"); " + Tree.Replace("Assembly Machine {", "Assembly Machine { provenance: Release;");+ var result = new AssemblyM1Pipeline().CompileProject(new("main.firmasm", [new("main.firmasm",source), new("vendor/bearing.step",Part)]));+ Accepted(result);+ Assert.Equal("Engineer", result.Ir!.Annotations!.Release!.Fields["Author"]);+ Assert.Equal("Designer", result.Ir.Annotations.Release.Fields["author.role"]);+ var exported = AssemblyIrAp242Exporter.Export(result);+ Assert.True(exported.IsSuccess);+ Assert.Contains("('Engineer')", exported.Value);+ }+}+++diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentInventoryTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentInventoryTests.csindex c0961cf0..224343d6 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentInventoryTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentInventoryTests.cs@@ -48,7 +48,7 @@ public sealed class FirmamentInventoryTests[InlineData("bracket: Part = Firmament(\"parts/bracket\").Missing","firmament-inventory-export-unresolved")][InlineData("bracket: Part = Firmament(\"parts/missing\").Bracket","assembly-include-file-not-found")][InlineData("bracket: Part = Unknown(\"parts/bracket\")","firmament-inventory-resource-invalid")]- [InlineData("bracket: Part = Step(\"bearing\")","assembly-profile-external-resource-unsupported")]+ [InlineData("bracket: Part = Step(\"bearing\")","assembly-include-file-not-found")][InlineData("bracket: Part = Firmament(\"parts/bracket\").Bracket bracket: Part = Firmament(\"parts/bracket\").Bracket","firmament-inventory-duplicate-field")]public void InvalidEntriesRejectAtTheirAuthoredField(string field,string code){@@ -235,12 +235,12 @@ public sealed class FirmamentInventoryTests}[Fact]- public void SnapshotCannotBypassTheBinaryAssetBoundaryThroughAnImportedPart()+ public void SnapshotCannotReadUnprovidedDiskAssetsThroughAnImportedPart(){- const string part="Model Bracket { units: mm InlineStep source { file: \"C:/unavailable.step\" } }";+ const string part="Model Bracket { units: mm InlineStep source { path: \"C:/unavailable.step\" } }";var result=new AssemblyM1Pipeline().CompileProject(new("main.firmasm",[KeyValuePair.Create("main.firmasm",Root),KeyValuePair.Create("parts/bracket.firmament",part)]));Assert.False(result.IsSuccess);- Assert.Contains(result.Diagnostics,d => d.Code=="assembly-profile-external-resource-unsupported" && d.SourceSpan?.Source=="parts/bracket.firmament");+ Assert.Contains(result.Diagnostics,d => d.Code=="assembly-include-outside-root" && d.SourceSpan?.Source=="parts/bracket.firmament");}[Fact]diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex 97948b7f..57fa2b3a 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -11,6 +11,7 @@<ItemGroup><PackageReference Include="Copeland.TS.Backend.Wgsl" Version="0.1.0-preview.1-a3.16c0ce996358af80" /><PackageReference Include="Machina.Typography.OpenFont" Version="1.0.0" />+ <PackageReference Include="Tomlyn" Version="2.10.1" /><ProjectReference Include="..\Aetheris.Firmament.SchemaGenerator\Aetheris.Firmament.SchemaGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /><ProjectReference Include="../Aetheris.Cloth3D/Aetheris.Cloth3D.csproj" /><ProjectReference Include="../Aetheris.Humanoid/Aetheris.Humanoid.csproj" />diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex cd11d3f1..cb0e5dd7 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -191,19 +191,21 @@ internal static partial class AssemblyDefinitionMaterializervar externalStep = System.Text.RegularExpressions.Regex.Match(definitionIdentity, "^ExternalStep<\\\"(?<path>[^\\\"]+)\\\">$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);if (externalStep.Success){+ string resolvedPath; string stepText;if (project is not null){- diagnostics.Add(new("assembly-profile-external-resource-unsupported", "ExternalStep is not a project source document and cannot be resolved from a Firmament project snapshot."));- return null;+ resolvedPath = FirmamentProjectSnapshot.NormalizePath(Path.Combine(Path.GetDirectoryName(sourceIdentity) ?? "", externalStep.Groups["path"].Value));+ if (!project.TryResolve(resolvedPath, out stepText!))+ { diagnostics.Add(new("assembly-profile-unresolved-resource", "Missing snapshot STEP asset: " + resolvedPath)); return null; }}- var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)) ?? Directory.GetCurrentDirectory();- var resolvedPath = Path.GetFullPath(Path.Combine(baseDirectory, externalStep.Groups["path"].Value.Replace('/', Path.DirectorySeparatorChar)));- if (!File.Exists(resolvedPath))+ else{- diagnostics.Add(new("assembly-profile-unresolved-resource", $"External STEP resource '{externalStep.Groups["path"].Value}' was not found at '{resolvedPath}'."));- return null;+ var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)) ?? Directory.GetCurrentDirectory();+ resolvedPath = Path.GetFullPath(Path.Combine(baseDirectory, externalStep.Groups["path"].Value.Replace('/', Path.DirectorySeparatorChar)));+ if (!File.Exists(resolvedPath))+ { diagnostics.Add(new("assembly-profile-unresolved-resource", "Missing STEP asset: " + resolvedPath)); return null; }+ stepText = File.ReadAllText(resolvedPath);}- var stepText = File.ReadAllText(resolvedPath);var externalImport = Step242Importer.ImportBody(stepText);if (!externalImport.IsSuccess || externalImport.Value is null){@@ -439,10 +441,6 @@ public sealed class AssemblyM1Pipelinereturn new(null, null, profile);AssemblyM0Parser.ParseResult parsed;using (BuildPerfTrace.Phase("assembly.parse-project")) parsed = new AssemblyM0Parser { PortCache = cache?.PublishedPorts }.ParseProject(project);- if (parsed.Source?.DefinitionSource is { } declarations &&- System.Text.RegularExpressions.Regex.IsMatch(declarations, @"\bInlineStep\b", System.Text.RegularExpressions.RegexOptions.CultureInvariant))- return new(null, null, [new AssemblyDiagnostic("assembly-profile-external-resource-unsupported",- "InlineStep requires an external STEP asset and is unsupported in a Firmament project snapshot.")]);return CompileParsed(parsed, null, project);}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.csindex 034e57bf..3d80d592 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs@@ -49,7 +49,7 @@ public static class Step242FirmasmPackageImporterreturn KernelResult<FirmasmImportPackageResult>.Success(new(firmasmPath, manifestPath, structure.Value, componentItems, Sha(source)), structure.Diagnostics);}- public static string GenerateSource(Step242ProductStructure structure, IReadOnlyDictionary<string, string> componentByDefinition, string provenance)+ public static string GenerateSource(Step242ProductStructure structure, IReadOnlyDictionary<string, string> componentByDefinition, string provenance, bool componentReferences = false){var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);@@ -80,7 +80,8 @@ public static class Step242FirmasmPackageImporterbuilder.AppendLine($"{padding}</Assembly>");return;}- builder.AppendLine($"{padding}<Part {id} = ExternalStep<\"{componentByDefinition[occurrence.DefinitionStableId]}\">>");+ var component = componentByDefinition[occurrence.DefinitionStableId];+ builder.AppendLine(componentReferences ? $"{padding}<Part {id} = {component}>" : $"{padding}<Part {id} = ExternalStep<\"{component}\">>");builder.AppendLine($"{padding} // STEP occurrence #{occurrence.StepEntityId}; Placement authority: ImportedOccurrence.");builder.AppendLine($"{padding} Placement ImportedOccurrence = [{string.Join(", ", occurrence.LocalTransform.Select(Number))}];");builder.AppendLine($"{padding}</Part>");diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.csindex 28031504..edff09f2 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs@@ -16,13 +16,6 @@ internal static partial class AssemblyDefinitionMaterializervar projection = reference.Module is null ? null : graph.ProjectSource(reference.Module, reference.Export, partContext: true);if (graph.Project is not null && reference.Module is { } module){- var inline = FirmamentSyntaxTraversal.Declarations(module.Syntax).FirstOrDefault(d => d.Type.Name.Text == "InlineStep");- if (inline is not null)- {- diagnostics.Add(new("assembly-profile-external-resource-unsupported", "InlineStep requires a binary asset, which a source-only project snapshot cannot supply.")- { SourceSpan = new(module.Path,inline.Span.Start,inline.Span.Length) });- return null;- }if (reference.Export is not null){var resource = FirmamentSyntaxTraversal.Expressions(module.Syntax).OfType<SpecializationSyntax>()@@ -39,12 +32,27 @@ internal static partial class AssemblyDefinitionMaterializerMaterializedAssemblyDefinition? Build(){MaterializedAssemblyDefinition? result;- if (reference.Module is null || reference.Export is null || reference.Export.Modifiers.Any(m => m.Name.Text == "Template"))+ if (reference.Module is null)+ {+ var text = graph.Asset(reference.Path);+ var imported = reference.ImportedBody is { } retained+ ? Aetheris.Kernel.Core.Results.KernelResult<Aetheris.Kernel.Core.Brep.BrepBody>.Success(retained.Clone()) : Step242Importer.ImportBody(text);+ if (!imported.IsSuccess)+ {+ diagnostics.AddRange(imported.Diagnostics.Select(d => new AssemblyDiagnostic("assembly-definition-reimport-failed", d.Message) { SourceSpan = reference.Origin }));+ return null;+ }+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text)));+ result = new(identity, "imported-step:" + hash[..16], imported.Value, [],+ new("", identity, "imported-step:" + hash[..16], hash, Metrics(imported.Value),+ [new SemanticProvenance("imported-step-definition", reference.Path, hash, reference.Origin)]), reference.ImportedBody is null ? text : null);+ }+ else if ( reference.Export is null || reference.Export.Modifiers.Any(m => m.Name.Text == "Template"))result = TryMaterialize(localIdentity, projection?.Text, reference.Path, diagnostics, graph.Project, cache is null ? null : cache.ImportCanonical);else{var source = AssemblyPublishedPorts.Strip(projection!.Text, diagnostics);- var compiled = FirmamentBuildAndExport.CompileSource(source, graph.Project is null ? Path.GetDirectoryName(reference.Path) : null);+ var compiled = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(reference.Path), graph.Project?.Documents);if (!compiled.IsSuccess || compiled.Value is null){foreach (var error in compiled.Diagnostics)@@ -71,6 +79,6 @@ internal static partial class AssemblyDefinitionMaterializerreturn result with { DefinitionIdentity = identity, DeclarationScope = null,Artifact = result.Artifact with { DefinitionIdentity = identity, StableId = stableId } };}- return cache is null ? Build() : cache.Materialize(identity, projection?.Text, reference.Path, diagnostics, graph.Project, Build);+ return cache is null || reference.Module is null ? Build() : cache.Materialize(identity, projection?.Text, reference.Path, diagnostics, graph.Project, Build);}}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.csindex 79ee5b5d..1b25e993 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs@@ -1,5 +1,4 @@using System.Text.Json;-using System.Text.RegularExpressions;using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Core.Step242;using Aetheris.Semantics;@@ -29,102 +28,78 @@ internal static class AssemblyPmiAuthoringinternal static AssemblyAnnotations Parse(ref string source, string identity, List<AssemblyDiagnostic> diagnostics){var original = source;- var mask = Mask(source);- var changes = new List<(int Start, int Length)>();+ var syntax = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);+ var roots = syntax.Document.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax>()+ .Where(d => d.Type.Name.Text == "Assembly" && !d.Modifiers.Any(m => m.Name.Text == "Template")).ToArray();+ if (roots.Length != 1 || roots[0].Body is null) return new(null, []);+ var changes = new List<FirmamentV2SourceSpan>();var notes = new List<AssemblyPmiNote>();AssemblyReleaseRecord? release = null;- // Template Assembly definitions have a '>' immediately before Assembly.- var roots = Regex.Matches(mask, @"\bAssembly\s+[A-Za-z_]\w*\s*\{").Cast<Match>()- .Where(m => Depth(mask, m.Index) == 0 && mask[..m.Index].TrimEnd().LastOrDefault() != '>').ToArray();- if (roots.Length != 1) return new(null, []); // The owning assembly parser diagnoses root structure.- var root = roots[0]; var rootEnd = End(mask, root.Index + root.Length - 1);- if (rootEnd < 0) return new(null, []);- var bodyStart = root.Index + root.Length;- var body = mask[bodyStart..rootEnd];- // Note text is opaque to the Record binder, too. It must never discover- // a fictional Record or Static declaration inside an annotation string.- var catalogChars = original.ToCharArray();- foreach (Match header in Regex.Matches(mask, @"\bPmi\s*\{"))+ var fields = roots[0].Body!.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FieldSyntax>()+ .Where(f => f.Name.Text is "Provenance" or "provenance").ToArray();+ if (fields.Length > 1) Error("provenance-selection-invalid", "Select one release Record.", roots[0].Span);+ foreach (var selection in fields){- var end = End(mask, header.Index + header.Length - 1);- if (end >= 0) Array.Fill(catalogChars, ' ', header.Index, end - header.Index + 1);- }- var catalog = new string(catalogChars);- var selections = Regex.Matches(body, @"\bProvenance\s*:\s*(?<name>[A-Za-z_]\w*)\s*;");- if (Regex.Matches(body, @"\bProvenance\s*:").Count != selections.Count || selections.Count > 1)- Error("provenance-selection-invalid", "Expected one Provenance: StaticRecord; in the root Assembly.");- foreach (Match selection in selections)- {- if (Depth(body, selection.Index) != 0) { Error("provenance-scope-invalid", "Provenance belongs to the root Assembly."); continue; }- var name = selection.Groups["name"].Value;- var recordDiagnostics = new List<string>();- var value = FirmamentV2TemplateExpansion.InspectStaticRecords(catalog, recordDiagnostics).SingleOrDefault(r => r.Name == name);- foreach (var diagnostic in recordDiagnostics) Error("provenance-record-invalid", diagnostic);- if (value is null) Error("provenance-record-unresolved", name);- else+ var errors = new List<string>();+ var value = Aetheris.Kernel.Firmament.Modules.FirmamentMetadata.Bind(original, selection.Value, errors);+ foreach (var error in errors) Error(error.StartsWith("firmament-metadata-record-unresolved:", StringComparison.Ordinal)+ ? "provenance-record-unresolved" : "provenance-record-invalid", error, selection.Span);+ if (value is null) continue;+ var projected = value.Fields.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);+ foreach (var (name, type) in new[] { ("Author", "String"), ("Date", "Date"), ("Version", "Version"), ("Description", "String") }){- var schema = FirmamentV2TemplateExpansion.InspectRecords(catalog, recordDiagnostics).Single(r => r.Name == value.TypeName);- foreach (var required in new[] { ("Author", "String"), ("Date", "Date"), ("Version", "Version"), ("Description", "String") })- if (schema.Fields.GetValueOrDefault(required.Item1) != required.Item2)- Error("provenance-field-invalid", $"{name}.{required.Item1} must have type {required.Item2}.");- if (schema.Fields.ContainsKey("Organization") && schema.Fields["Organization"] != "String")- Error("provenance-field-invalid", $"{name}.Organization must have type String.");- if (schema.Fields.Values.Any(t => t is not ("String" or "Date" or "Version" or "Length" or "Angle" or "Int" or "Float" or "Bool")))- Error("provenance-field-invalid", "Release records admit flat scalar engineering data.");- var fields = value.Fields.ToDictionary(p => p.Key, p => Unquote(p.Value), StringComparer.Ordinal);- if (fields.Values.Any(string.IsNullOrWhiteSpace)) Error("provenance-field-invalid", "Release fields must be non-empty.");- release = new(name, value.TypeName, fields, new(identity, bodyStart + selection.Index, selection.Length));- // Erase only the selected data from the material-definition source so metadata edits- // cannot invalidate the reusable geometry cache. The typed value is retained above.- foreach (Match declaration in Regex.Matches(mask, $@"\b(?:Record\s+{Regex.Escape(value.TypeName)}|Static\s+{Regex.Escape(name)}\s*:\s*{Regex.Escape(value.TypeName)})\s*\{{"))- {- var end = End(mask, declaration.Index + declaration.Length - 1);- if (end >= 0) changes.Add((declaration.Index, end - declaration.Index + 1));- }+ var preferred = char.ToLowerInvariant(name[0]) + name[1..];+ if (value.Fields.ContainsKey(name) && value.Fields.ContainsKey(preferred))+ { Error("provenance-field-invalid", "Duplicate metadata aliases: " + name + "/" + preferred, selection.Span); continue; }+ var key = value.Fields.ContainsKey(preferred) || value.Fields.ContainsKey(preferred + ".name") ? preferred : name;+ if (name == "Author" && value.FieldTypes.GetValueOrDefault(key) != "String" && value.Fields.ContainsKey(key + ".name")) key += ".name";+ if (value.FieldTypes.GetValueOrDefault(key) != type || string.IsNullOrWhiteSpace(value.Fields.GetValueOrDefault(key)))+ Error("provenance-field-invalid", value.Name + "." + preferred + " must provide " + type + ".", selection.Span);+ else projected[name] = value.Fields[key];}- changes.Add((bodyStart + selection.Index, selection.Length));+ if (value.Fields.ContainsKey("Organization") && value.Fields.ContainsKey("organization"))+ Error("provenance-field-invalid", "Duplicate metadata aliases: Organization/organization", selection.Span);+ var organizationKey = value.Fields.ContainsKey("organization") ? "organization" : "Organization";+ if (value.Fields.TryGetValue(organizationKey, out var organization))+ {+ if (value.FieldTypes.GetValueOrDefault(organizationKey) != "String") Error("provenance-field-invalid", "Release organization must provide String.", selection.Span);+ else projected["Organization"] = organization;+ }+ release = new(value.Name, value.Type, projected, new(identity, selection.Span.Start, selection.Span.Length));+ // Metadata is bound by the normal Record owner. Remove the selected+ // declaration/value by AST spans from the geometry-only projection.+ foreach (var d in syntax.Document.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax>()+ .Where(d => d.Name?.Text == value.Name && d.Type.Name.Text == "Static" || d.Name?.Text == value.Type && d.Type.Name.Text == "Record")) changes.Add(d.Span);+ changes.Add(selection.Span);}- foreach (Match header in Regex.Matches(body, @"\bPmi\s*\{"))+ foreach (var pmi in roots[0].Body!.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax>().Where(d => d.Type.Name.Text == "Pmi")){- var start = bodyStart + header.Index;- var end = End(mask, start + header.Length - 1);- if (end < 0) { Error("pmi-malformed", "Unclosed Pmi block."); continue; }- if (Depth(body, header.Index) != 0) Error("pmi-scope-invalid", "Assembly Pmi belongs to the root Assembly.");- var cursor = start + header.Length;- while (cursor < end)+ var scopeErrors = new List<string>();+ new Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxFields(pmi, scopeErrors).Complete(+ (pmi.Body?.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax>() ?? []).ToHashSet<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.StatementSyntax>());+ foreach (var error in scopeErrors) Error("pmi-note-invalid", error, pmi.Span);+ foreach (var statement in pmi.Body?.Statements ?? []){- while (cursor < end && char.IsWhiteSpace(mask[cursor])) cursor++;- if (cursor == end) break;- var note = Regex.Match(mask[cursor..end], @"^Note\s+(?<name>[A-Za-z_]\w*)\s*\{");- if (!note.Success) { Error("pmi-kind-unsupported", "Assembly Pmi currently admits only Note Name { Target: occurrence; Text: string; }."); break; }- var close = End(mask, cursor + note.Length - 1);- if (close < 0 || close >= end) { Error("pmi-malformed", note.Value); break; }- var fields = original[(cursor + note.Length)..close];- var parsed = Regex.Match(fields, "^\\s*Target\\s*:\\s*(?<target>[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*)\\s*;\\s*Text\\s*:\\s*(?<text>\"(?:\\\\.|[^\"\\\\])*\")\\s*;\\s*$", RegexOptions.Singleline);- if (!parsed.Success) Error("pmi-note-invalid", note.Groups["name"].Value);- else- {- try- {- using var literal = JsonDocument.Parse(parsed.Groups["text"].Value);- var text = literal.RootElement.GetString()!;- var name = note.Groups["name"].Value;- if (string.IsNullOrWhiteSpace(text) || text.Any(char.IsControl)) Error("pmi-note-invalid", name);- else if (notes.Any(n => n.Name == name)) Error("pmi-note-duplicate", name);- else notes.Add(new(name, parsed.Groups["target"].Value, text, new(identity, cursor, close - cursor + 1)));- }- catch (JsonException) { Error("pmi-note-invalid", note.Groups["name"].Value); }- }- cursor = close + 1;+ if (statement is not Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax { Type.Name.Text: "Note", Name: { } name, Body: { } body } note)+ { Error("pmi-kind-unsupported", "Assembly PMI currently admits Note declarations.", statement.Span); continue; }+ var errors = new List<string>();+ var owned = new Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxFields(note, errors);+ var target = owned.Reference("Target");+ var text = owned.Take("Text") is Aetheris.Kernel.Firmament.FirmamentV2.Syntax.LiteralSyntax { Kind: Aetheris.Kernel.Firmament.FirmamentV2.Syntax.LiteralKind.String } literal+ ? JsonSerializer.Deserialize<string>(literal.Raw) : null;+ owned.Complete();+ if (errors.Count > 0 || target is null || string.IsNullOrWhiteSpace(text) || text.Any(char.IsControl))+ Error("pmi-note-invalid", string.Join(" | ", errors), note.Span);+ else if (notes.Any(n => n.Name == name.Text)) Error("pmi-note-duplicate", name.Text, note.Span);+ else notes.Add(new(name.Text, target, text, new(identity, note.Span.Start, note.Span.Length)));}- changes.Add((start, end - start + 1));+ changes.Add(pmi.Span);}var chars = source.ToCharArray();- foreach (var change in changes) Array.Fill(chars, ' ', change.Start, change.Length);+ foreach (var span in changes) for (var i = span.Start; i < span.Start + span.Length; i++) if (chars[i] is not ('\r' or '\n')) chars[i] = ' ';source = new(chars);return new(release, notes);-- void Error(string code, string message) => diagnostics.Add(new("assembly-" + code, message));+ void Error(string code, string message, FirmamentV2SourceSpan span) => diagnostics.Add(new("assembly-" + code, message) { SourceSpan = new(identity, span.Start, span.Length) });}internal static void Validate(AssemblyAnnotations? annotations, IEnumerable<AssemblyInstanceIr> instances, List<AssemblyDiagnostic> diagnostics)@@ -139,10 +114,4 @@ internal static class AssemblyPmiAuthoringrelease.Fields["Date"] + "T00:00:00", release.Fields["Author"], release.Fields.GetValueOrDefault("Organization", "Aetheris"),"Aetheris.Kernel.Firmament", "Aetheris/Firmament", "");- private static string Unquote(string value) => value.StartsWith('"') ? value[1..^1] : value;- private static string Mask(string source) => Regex.Replace(source, "\"(?:\\\\.|[^\"\\\\])*\"|//[^\\r\\n]*", m => new string(' ', m.Length));- private static int Depth(string text, int end)- { var depth = 0; for (var i = 0; i < end; i++) { if (text[i] == '{') depth++; else if (text[i] == '}') depth--; } return depth; }- private static int End(string text, int opening)- { var depth = 0; for (var i = opening; i < text.Length; i++) { if (text[i] == '{') depth++; else if (text[i] == '}' && --depth == 0) return i; } return -1; }}diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.csindex 5cf1f8c2..edb2962c 100644--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs@@ -22,7 +22,7 @@ public sealed class FirmamentProjectSnapshotvar key = NormalizePath(path);if (!key.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase) &&!key.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase) &&- !IsStepAsset(key))+ !IsStepAsset(key) && !IsLockAsset(key))throw new ArgumentException($"Unsupported project document kind: '{key}'.", nameof(documents));if (!normalized.TryAdd(key, source ?? throw new ArgumentException($"Null source for '{key}'.", nameof(documents))))throw new ArgumentException($"Duplicate normalized project path: '{key}'.", nameof(documents));@@ -53,5 +53,6 @@ public sealed class FirmamentProjectSnapshotpublic bool TryResolve(string path, out string source) => documents.TryGetValue(NormalizePath(path), out source!);public static bool IsStepAsset(string path) => path.EndsWith(".step", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".stp", StringComparison.OrdinalIgnoreCase);- public IEnumerable<KeyValuePair<string, string>> SourceDocuments => documents.Where(d => !IsStepAsset(d.Key));+ public static bool IsLockAsset(string path) => Path.GetFileName(path).Equals("firmament.lock.toml", StringComparison.Ordinal);+ public IEnumerable<KeyValuePair<string, string>> SourceDocuments => documents.Where(d => !IsStepAsset(d.Key) && !IsLockAsset(d.Key));}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 4803216a..27065d72 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -42,6 +42,9 @@ public static partial class FirmamentBuildAndExportArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);var fullSourcePath = Path.GetFullPath(sourcePath);+ var lockDiagnostics = Modules.FirmamentDependencies.VerifyFile(fullSourcePath);+ if (lockDiagnostics.Count > 0) return KernelResult<FirmamentBuildAndExportResult>.Failure(+ lockDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());var sourceText = File.ReadAllText(fullSourcePath, Encoding.UTF8);var frontend = FirmamentFrontendSchemas.Select(sourceText);if (!frontend.IsSuccess) return KernelResult<FirmamentBuildAndExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());@@ -518,7 +521,9 @@ public static partial class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);}- if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null))+ if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null)+ && (v2Parse.Document.Solids.Count != 1 || v2Parse.Document.Replacements is { Count: > 0 }+ || v2Parse.Document.ModifyBlocks is { Count: > 0 }))return ExportPinnedImportedRevision(v2Parse.Document);if (TryExportV2StandaloneCubicLattice(v2Parse.Document) is { } latticeExport)@@ -2277,15 +2282,18 @@ public static partial class FirmamentBuildAndExport}var stepText = inlineStep.SourceText ?? File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);- if (Step242SemanticPmiInspector.Inspect(stepText).Items.Count > 0)+ if (!inlineStep.GeometryOnly && (!inlineStep.CanonicalInput || ImportedStepSemantics.HasAnnotations(stepText)))return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,- KernelDiagnosticSeverity.Error, "firmament-v2-inline-step-existing-pmi-unsupported: This STEP already contains semantic PMI. Importing that annotation layer is not yet qualified and must not silently discard it. Reopen the original Firmament/Helios workspace instead.", "FirmamentV2.InlineStep")]);- var import = Step242Importer.ImportBody(stepText);+ KernelDiagnosticSeverity.Error, "firmament-v2-inline-step-existing-pmi-unsupported: Source annotation passthrough is not qualified for this STEP. Use the original Firmament/Helios workspace, or explicitly request geometryOnly: true to exclude imported annotations without changing the original file.", "FirmamentV2.InlineStep")]);+ var import = inlineStep.RuntimeBody is { } admitted ? KernelResult<BrepBody>.Success(admitted.Clone()) : Step242Importer.ImportBody(stepText);if (!import.IsSuccess){return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);}+ if (inlineStep.SourceHashPin is not null && import.Value.ImportQualification?.GeometryStatus != Aetheris.Kernel.Core.Import.ImportQualificationStatus.Qualified)+ return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ "firmament-inline-step-import-unqualified: Pinned re-export requires qualified imported trims.", "FirmamentV2.InlineStep")]);var semanticPmiValidation = ValidateV2PmiExportSupport(document);if (!semanticPmiValidation.IsSuccess){@@ -2298,7 +2306,9 @@ public static partial class FirmamentBuildAndExportvar export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions{ProductName = solid.Name,- ApplicationName = "Aetheris.Firmament.InlineStep"+ ApplicationName = "Aetheris.Firmament.InlineStep",+ BrepExportPreflightMode = inlineStep.SourceHashPin is null ? BrepExportPreflightMode.Audit : BrepExportPreflightMode.Enforce,+ ImportedRecoveryToleranceMillimetres = inlineStep.ImportToleranceMillimetres ?? .001});if (!export.IsSuccess){@@ -2311,12 +2321,14 @@ public static partial class FirmamentBuildAndExportsolid.Name,0,"inline-step",- "aetheris-canonical-ap242",+ inlineStep.CanonicalInput ? "aetheris-canonical-ap242" : "qualified-import-ap242",DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],- InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: "canonical-reexport", residualSurgery: false),+ InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: inlineStep.CanonicalInput ? "canonical-reexport" : "qualified-import-reexport", residualSurgery: false),InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document))- { RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document });+ { RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document },+ inlineStep.GeometryOnly ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,+ "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : []);}private static KernelResult<FirmamentStepExportResult>? TryExportV2ControlledSideHoleBody(FirmamentV2Document document)diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.cs b/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.csnew file mode 100644index 00000000..fd976a56--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.cs@@ -0,0 +1,152 @@+using System.Globalization;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using System.Text.Json.Serialization;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament;++public sealed class ImportedFeatureInspection+{+ internal ImportedFeatureInspection(string text, BrepBody body, double tolerance)+ {+ SourceText = text; Body = body;+ SourceHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(+ text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n')))).ToLowerInvariant();+ Discovery = BrepThroughHoleRevision.Discover(body, tolerance);+ }+ internal string SourceText { get; }+ internal BrepBody Body { get; }+ public string SourceHash { get; }+ public string SourceHashKind => "sha256-utf8-lf";+ public double? SourceDistanceAccuracyMillimetres => Body.ImportQualification?.SourceDistanceAccuracyMillimetres;+ public ThroughHoleDiscovery Discovery { get; }+}++public sealed record ImportedFeatureMovePlan(string Source, string Candidate, string Alias,+ string SourceHash, string Admission, FirmamentImportedHoleRevisionReport Revision)+{+ public double AuthoringIncrementMillimetres => FirmamentImportedFeatures.AuthoringIncrementMillimetres;+ [JsonIgnore] public FirmamentStepExportResult Export { get; init; } = null!;+}++/// <summary>Agent-facing recovery assistance. Selection is explicit; geometric+/// admission belongs exclusively to the existing production kernel/compiler.</summary>+public static class FirmamentImportedFeatures+{+ public const double AuthoringIncrementMillimetres = .1;++ static double Nominal(double value)+ {+ var rounded = double.Round(value, 1, MidpointRounding.AwayFromZero);+ return rounded == 0 ? 0 : rounded;+ }++ static double Outward(double value, bool minimum)+ {+ // Remove arithmetic jitter at a grid boundary before directing the round.+ // Final compiler admission checks the actual emitted bounds against BRep.+ var grid = double.Round(value / AuthoringIncrementMillimetres, 8);+ return (minimum ? double.Floor(grid) : double.Ceiling(grid)) * AuthoringIncrementMillimetres;+ }++ public static KernelResult<ImportedFeatureInspection> Inspect(string stepText, double importToleranceMillimetres = .001)+ {+ ArgumentNullException.ThrowIfNull(stepText);+ if (!double.IsFinite(importToleranceMillimetres) || importToleranceMillimetres <= 0 || importToleranceMillimetres > .1)+ return Failure<ImportedFeatureInspection>("Import tolerance must be positive, finite and at most .1 mm.");+ var import = Step242Importer.ImportBody(stepText, new ImportPolicy(PcurveQualificationToleranceMillimetres: importToleranceMillimetres));+ return import.IsSuccess ? KernelResult<ImportedFeatureInspection>.Success(new(stepText, import.Value, importToleranceMillimetres), import.Diagnostics)+ : KernelResult<ImportedFeatureInspection>.Failure(import.Diagnostics);+ }++ public static KernelResult<ImportedFeatureMovePlan> PlanMove(ImportedFeatureInspection inspection,+ string candidateId, string alias, Point3D destination, bool geometryOnly,+ string sourceReference = "input.step", string? sourceDirectory = null, double clearanceMillimetres = .1)+ {+ ArgumentNullException.ThrowIfNull(inspection);+ if (!geometryOnly) return Failure<ImportedFeatureMovePlan>("Explicit geometry-only approval is required; source PMI migration is not admitted.");+ var name = FirmamentSyntaxParser.ParseExpression(alias);+ if (name.Diagnostics.Count > 0 || name.Expression is not ReferenceSyntax identifier || identifier.Name.Text != alias)+ return Failure<ImportedFeatureMovePlan>("Alias must be one Firmament identifier.");+ if (string.IsNullOrWhiteSpace(sourceReference) || Path.IsPathRooted(sourceReference)) return Failure<ImportedFeatureMovePlan>("The generated InlineStep path must be relative to its source document.");+ string? resourcePath = null;+ if (sourceDirectory is null)+ {+ try { resourcePath = Assembly.FirmamentProjectSnapshot.NormalizePath(sourceReference); }+ catch (ArgumentException) { return Failure<ImportedFeatureMovePlan>("Snapshot source reference must remain inside the resource project."); }+ }+ var authoredDestination = new Point3D(Nominal(destination.X), Nominal(destination.Y), Nominal(destination.Z));+ var planned = BrepThroughHoleRevision.PlanMove(inspection.Body, candidateId, alias, authoredDestination,+ inspection.Discovery.ImportToleranceMillimetres, clearanceMillimetres);+ if (!planned.IsSuccess) return KernelResult<ImportedFeatureMovePlan>.Failure(planned.Diagnostics);+ var request = planned.Value.Request;+ var entryEntity = inspection.Body.Bindings.GetFaceBinding(request.EntryFace).SourceStepEntityId;+ if (entryEntity is null) return Failure<ImportedFeatureMovePlan>("Entry support has no imported source entity binding.");+ var source = Emit(inspection, candidateId, alias, sourceReference, entryEntity.Value, request);+ // Resource snapshots use exactly the inspected immutable text. File-backed+ // callers re-enter the ordinary loader, which rechecks the persisted pin.+ IReadOnlyDictionary<string, string>? resources = sourceDirectory is null+ ? new Dictionary<string, string> { [resourcePath!] = inspection.SourceText } : null;+ var build = FirmamentBuildAndExport.CompileSource(source, sourceDirectory ?? "", resources);+ if (!build.IsSuccess) return KernelResult<ImportedFeatureMovePlan>.Failure(build.Diagnostics);+ return KernelResult<ImportedFeatureMovePlan>.Success(new(source, candidateId, alias, inspection.SourceHash,+ "Built", build.Value.ImportedHoleRevision!) { Export = build.Value }, build.Diagnostics);+ }++ static string Emit(ImportedFeatureInspection inspection, string candidate, string alias,+ string path, int entryEntity, ThroughHoleRevisionRequest request)+ {+ static string N(double value) => Nominal(value).ToString("0.#", CultureInfo.InvariantCulture);+ static string P(Point3D point) => $"Point3({N(point.X)}mm, {N(point.Y)}mm, {N(point.Z)}mm)";+ static string B(ThroughHoleEditBounds bounds) => $"{{ min: {P(new(Outward(bounds.Min.X, true), Outward(bounds.Min.Y, true), bounds.Min.Z))}; max: {P(new(Outward(bounds.Max.X, false), Outward(bounds.Max.Y, false), bounds.Max.Z))} }}";+ var target = "RevisionLayout.Targets." + alias;+ var pad = N(Outward(request.DestinationWithin!.Max.X - request.Center.X, false));+ var destinationBounds = $"{{ min: Point3({target}.X - {pad}mm, {target}.Y - {pad}mm, {N(request.Within.Min.Z)}mm); max: Point3({target}.X + {pad}mm, {target}.Y + {pad}mm, {N(request.Within.Max.Z)}mm) }}";+ var strings = new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };+ return $$"""+ // Recovery proves the admitted feature family, not the original modeling history.+ // Authored lengths use a 0.1mm grid; numerical import accuracy is separate.+ Model ImportedRevision {+ units: mm+ Concept Struct RevisionLayout {+ Points<Point3> Targets { {{alias}}: {{P(request.Center)}}; }+ }+ InlineStep Source {+ path: {{JsonSerializer.Serialize(path, strings)}}+ textSha256: "{{inspection.SourceHash}}"+ importTolerance: {{request.ImportToleranceMillimetres.ToString("R", CultureInfo.InvariantCulture)}}mm+ geometryOnly: true+ }+ Recognize Source {+ Region {{alias}} {+ kind: HoleShaft+ candidate: {{JsonSerializer.Serialize(candidate, strings)}}+ }+ }+ Replace Source.{{alias}} with Hole<Shaft> {{alias}} {+ on: Source.Face("#{{entryEntity}}")+ center: RevisionLayout.Targets.{{alias}}+ diameter: {{N(request.Diameter)}}mm+ end: ThroughAll+ within: [+ {{B(request.Within)}},+ {{destinationBounds}}+ ]+ }+ }+ """;+ }++ static KernelResult<T> Failure<T>(string message) => KernelResult<T>.Failure([+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ "firmament-imported-feature-assistance-rejected: " + message, "Firmament.ImportedFeatures")]);+}diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.csindex 38cae2f9..351e41ee 100644--- a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs+++ b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs@@ -13,7 +13,10 @@ public sealed record FirmamentImportedHoleRevisionReport(string Feature, stringstring Strategy, bool SourceSemanticsExcluded, double ImportToleranceMillimetres,IReadOnlyList<int> RetiredWallFaces, IReadOnlyList<int> WallFaces, int EntryFace, int ExitFace,double Diameter, double Depth, ThroughHoleEditBounds Within, int PreservedFaces, int PreservedEdges,- IReadOnlyDictionary<int, int> FaceCorrespondence);+ IReadOnlyDictionary<int, int> FaceCorrespondence)+{+ public ThroughHoleEditBounds? DestinationWithin { get; init; }+}public static partial class FirmamentBuildAndExport{@@ -58,7 +61,7 @@ public static partial class FirmamentBuildAndExportvar entry = marker >= 0 && end > marker ? Resolve(replacement.PlacementTarget[(marker + 1)..end]) : null;if (selected.Any(id => id is null) || entry is null) return Failure("firmament-imported-hole-selection-unresolved: Resolve every wall and the entry support in the pinned source.");var edit = BrepThroughHoleRevision.Execute(body, new(replacement.ReplacementFeatureName, selected.Select(id => id!.Value).ToArray(), entry.Value,- replacement.WorldCenter.Value, replacement.Radius * 2, replacement.Within, tolerance));+ replacement.WorldCenter.Value, replacement.Radius * 2, replacement.Within, tolerance) { DestinationWithin = replacement.DestinationWithin });if (!edit.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(edit.Diagnostics.Select(d => d with{SourceSpan = replacement.SourceSpan is { } span ? new(span.Start, span.Length) : null@@ -116,7 +119,7 @@ public static partial class FirmamentBuildAndExportRuntimeAdmissionDocument = bound,ImportedHoleRevision = new(replacement.ReplacementFeatureName, imported.SourceHashPin, imported.TextHashPin ? "sha256-utf8-lf" : "sha256-bytes", imported.SourceByteHash, "ThroughHoleSuppressionReinsertion", imported.GeometryOnly, tolerance,revised.RetiredWallFaces.Select(id => id.Value).ToArray(), revised.WallFaces.Select(id => id.Value).ToArray(), revised.EntryFace.Value, revised.ExitFace.Value,- revised.Diameter, revised.Depth, revised.Within, revised.PreservedFaces, revised.PreservedEdges, revised.FaceCorrespondence.ToDictionary(p => p.Key.Value, p => p.Value.Value))+ revised.Diameter, revised.Depth, revised.Within, revised.PreservedFaces, revised.PreservedEdges, revised.FaceCorrespondence.ToDictionary(p => p.Key.Value, p => p.Value.Value)) { DestinationWithin = revised.DestinationWithin }}, warnings);}}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 3f1c9307..a7b2e9c9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -193,6 +193,7 @@ public sealed record FirmamentV2ReplacementDecl(string ImportedBodyName, stringpublic string TargetSource => $"{ImportedBodyName}.region(\"{RecognizedRegionName}\")";public Aetheris.Kernel.Core.Math.Point3D? WorldCenter { get; init; }public Aetheris.Kernel.Core.Brep.Features.ThroughHoleEditBounds? Within { get; init; }+ public Aetheris.Kernel.Core.Brep.Features.ThroughHoleEditBounds? DestinationWithin { get; init; }public FirmamentV2SourceSpan? SourceSpan { get; init; }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.csindex cd1bef18..eb8d3fd2 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs@@ -22,6 +22,13 @@ public static partial class FirmamentV2Parservar textPin = bytePinExpression is null && textPinExpression is not null;var pin = StringValue(pinExpression);if (pinExpression is not null && (pin is null || pin.Length != 64 || pin.Any(c => !char.IsAsciiHexDigit(c)))) fields.Invalid(textPin ? "TextSha256" : "Sha256");+ Modules.FirmamentLockedDependency? locked = null;+ if (path is not null)+ {+ try { locked = Modules.FirmamentDependencyLock.StepPin(directory, resources, path); }+ catch (ArgumentException error) { diagnostics.Add("firmament-lock-invalid: " + error.Message); }+ }+ if (pinExpression is null && locked is not null) { pin = locked.Sha256; textPin = false; }var toleranceExpression = fields.Take("ImportTolerance");double? tolerance = null;if (toleranceExpression is not null)@@ -33,8 +40,12 @@ public static partial class FirmamentV2Parserif (geometryOnly && pin is null) diagnostics.Add("firmament-inline-step-source-pin-required: geometryOnly requires a pinned source.");fields.Complete();if (path is null || declaration.Name is null) { diagnostics.Add(InlineStepPathMissing); return null; }- return LoadInlineStep(declaration.Name.Text, path, diagnostics, directory, resources, pin, tolerance, textPin) is { } binding- ? binding with { Primitive = ((FirmamentV2InlineStepRecord)binding.Primitive) with { GeometryOnly = geometryOnly }, SourceSpan = declaration.Span, AuthoredFields = fields.AuthoredFields } : null;+ var binding = LoadInlineStep(declaration.Name.Text, path, diagnostics, directory, resources, pin, tolerance, textPin);+ if (binding is null) return null;+ var imported = (FirmamentV2InlineStepRecord)binding.Primitive;+ if (locked is not null && !locked.Sha256.Equals(imported.SourceByteHash, StringComparison.OrdinalIgnoreCase))+ { diagnostics.Add("firmament-lock-dependency-mismatch: The STEP differs from its lock entry; reinspect before updating it."); return null; }+ return binding with { Primitive = imported with { GeometryOnly = geometryOnly }, SourceSpan = declaration.Span, AuthoredFields = fields.AuthoredFields };}private static IReadOnlyList<FirmamentV2RecognizedRegion> BindImportedRegions(IEnumerable<DeclarationSyntax> declarations,@@ -59,8 +70,23 @@ public static partial class FirmamentV2Parserif (confidence is not ("low" or "medium" or "high" or "certain")) diagnostics.Add(InvalidRecognitionConfidence);var raw = fields.Take("StepFaceEntities");var friendly = fields.Take("Faces");+ var candidateValue = fields.Take("Candidate");var refs = new List<string>();- if (raw is not null && friendly is not null) diagnostics.Add(UnknownRecognitionFace);+ if (candidateValue is not null)+ {+ if (raw is not null || friendly is not null) fields.Invalid("Candidate");+ if (StringValue(candidateValue) is not { } candidateId || solid.InlineStep.SourceHashPin is null || solid.InlineStep.RuntimeBody is null)+ diagnostics.Add("firmament-imported-hole-candidate-invalid: candidate requires an exact discovered ID and a pinned InlineStep source.");+ else+ {+ var found = BrepThroughHoleRevision.Discover(solid.InlineStep.RuntimeBody, solid.InlineStep.ImportToleranceMillimetres ?? .001)+ .Candidates.SingleOrDefault(c => c.Id == candidateId);+ if (found is null || !found.CanPlan)+ diagnostics.Add("firmament-imported-hole-candidate-invalid: Candidate is absent or not admitted in this pinned source. " + string.Join(" | ", found?.Diagnostics ?? []));+ else refs.AddRange(found.StepFaceEntities.Select(id => "#" + id));+ }+ }+ else if (raw is not null && friendly is not null) diagnostics.Add(UnknownRecognitionFace);else if ((raw ?? friendly) is SequenceSyntax { Kind: SequenceKind.List } list){foreach (var argument in list.Items)@@ -150,15 +176,24 @@ public static partial class FirmamentV2Parservar hostValue = fields.Take("HostSize");var host = FirmamentSyntaxValues.Vector(hostValue, "mm", out var size) && size.Length == 3 && size.All(v => v > 0) ? size : [];ThroughHoleEditBounds? within = null;+ ThroughHoleEditBounds? destinationWithin = null;if (fields.Take("Within") is { } envelope){- if (envelope is ObjectSyntax obj)+ ThroughHoleEditBounds? ReadBounds(ExpressionSyntax value){+ if (value is not ObjectSyntax obj) { fields.Invalid("Within"); return null; }var bounds = ImportedObject(obj, "EditBounds", diagnostics);var min = Point(bounds.Take("Min")); var max = Point(bounds.Take("Max")); bounds.Complete();- if (min is not null && max is not null) within = new(min.Value, max.Value); else fields.Invalid("Within");+ if (min is not null && max is not null) return new(min.Value, max.Value);+ fields.Invalid("Within"); return null;+ }+ if (envelope is SequenceSyntax { Kind: SequenceKind.List, Items.Count: 2 } list+ && list.Items.All(a => a.Name is null && a.Default is null))+ {+ within = ReadBounds(list.Items[0].Value);+ destinationWithin = ReadBounds(list.Items[1].Value);}- else fields.Invalid("Within");+ else within = ReadBounds(envelope);if (world is null) fields.Invalid("Center");if (solid.InlineStep.SourceHashPin is null) diagnostics.Add("firmament-inline-step-source-pin-required: A local revision requires sha256 or textSha256 on InlineStep.");if (hostValue is not null) diagnostics.Add("firmament-imported-hole-host-size-conflict: within edits the retained BRep; HostSize is not admitted in this operation.");@@ -167,7 +202,7 @@ public static partial class FirmamentV2Parserfields.Complete();result.Add(new(solid.Name, target[1], kind, name, $"{solid.Name}.face(\"{faceEntity}\")", center, diameter / 2, "throughAll", host,source.Substring(declaration.Span.Start, declaration.Span.Length))- { WorldCenter = world, Within = within, SourceSpan = declaration.Span });+ { WorldCenter = world, Within = within, DestinationWithin = destinationWithin, SourceSpan = declaration.Span });}finally { capture(declaration, diagnosticStart); }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex be2e7116..02c63320 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -297,7 +297,8 @@ public static partial class FirmamentV2Parser// four times). The parser is a pure function of its text and directory, and its result is// immutable records, except InlineStep, which reads a STEP file; those, and parses with a// concept catalog, always run.- if (resources is not null || conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase))+ if (resources is not null || conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase)+ || Modules.FirmamentModuleGraph.HasImports(sourceText))return ParseWithDirectives(sourceText, sourceDirectory, conceptCatalog, expectedSchema, resources);var key = expectedSchema + "\0" + (sourceDirectory ?? string.Empty) + "\0" + sourceText;lock (RecentParses)@@ -332,6 +333,28 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Failure(["firmament-schema-context-conflict"]) with { OriginalSource = source,SyntaxDiagnostics = [FirmamentFrontendSchemas.Located(source, "firmament-schema-context-conflict", $"The authored schema {authored} conflicts with the caller's {expected} compilation context.", frontend.DirectiveSpan!)],ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true };+ Modules.FirmamentModuleGraph.Projection? moduleProjection = null;+ if (Modules.FirmamentModuleGraph.HasImports(frontend.Source) && (directory is not null || resources is not null))+ {+ var identity = resources is null ? Path.Combine(directory!, "__provided_source.firmament")+ : (string.IsNullOrEmpty(directory) ? "" : directory.Replace('\\', '/') + "/") + "__provided_source.firmament";+ Assembly.FirmamentProjectSnapshot? project = resources is null ? null : new(identity,+ resources.Where(p => p.Key != identity).Append(new(identity, frontend.Source)));+ var graph = Modules.FirmamentModuleGraph.Load(frontend.Source, identity, project, hasRootIdentity: false);+ if (graph.Diagnostics.Count > 0)+ return FirmamentV2ParseResult.Failure(graph.Diagnostics.Select(d => d.Code).ToArray()) with+ {+ OriginalSource = source, OwnsUnifiedAdmission = true, ParserRoute = "UnifiedModules",+ SyntaxDiagnostics = graph.Diagnostics.Select(d => new FirmamentV2ValidationDiagnostic(d.Code, "error", d.Message)+ {+ SourceFile = d.SourceSpan?.Source == identity ? null : d.SourceSpan?.Source,+ SourceSpan = d.SourceSpan is { } span ? new(span.Start, span.Length) : null,+ IsOriginalSource = true, Stage = "Module binding"+ }).ToArray()+ };+ moduleProjection = graph.ProjectSource(graph.Root);+ frontend = frontend with { Source = moduleProjection.Text };+ }var syntax = FirmamentSyntaxParser.Parse(frontend.Source);var pending = FirmamentSyntaxTraversal.Statements(syntax.Document).OfType<DirectiveSyntax>().Where(d => !syntax.Document.Statements.Contains(d) || !ProfileModificationTemplateLibrary.IsImport(d)).ToArray();@@ -344,6 +367,11 @@ public static partial class FirmamentV2Parser{ OriginalSource = source, SyntaxDiagnostics = reported, ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true };}var parsed = ParseUncached(frontend.Source, directory, catalog, resources);+ if (moduleProjection is not null)+ parsed = parsed with { SyntaxDiagnostics = parsed.SyntaxDiagnostics.Select(d => d.SourceSpan is { } span+ && moduleProjection.Original(span) is { } original ? d with { SourceSpan = new(original.Start, original.Length),+ SourceFile = original.Source == moduleProjection.SourceIdentity ? null : original.Source,+ IsOriginalSource = true } : d).ToArray() };if (parsed.IsSuccess && (frontend.Schema ?? expectedSchema) is { } schema&& FirmamentFrontendSchemas.DomainMismatch(schema, parsed.BoundSource ?? frontend.Source, admittedSchema: parsed.BoundSchema) is { } mismatch)return (frontend with { Diagnostics = [mismatch.Code], LocatedDiagnostics =diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.csindex d754cab2..17b0b78c 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs@@ -31,7 +31,7 @@ internal sealed class FirmamentDataBindinginternal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics { get; }internal bool IsChanged => edits.Count != 0;- internal FirmamentDataBinding(string source)+ internal FirmamentDataBinding(string source, bool moduleContext = false){OriginalSource = source;Source = source;@@ -81,7 +81,8 @@ internal sealed class FirmamentDataBindingif (statement is not DeclarationSyntax { Name: { } name } d) continue;if (d.Type.Name.Text == "Record" && d.Modifiers.Any(m => m.Name.Text == "Inventory")){- Error("firmament-module-context-required", $"Inventory Record '{name.Text}' requires an Assembly or Scene project loader. Reference this module from a consuming project; it is not an ordinary data Record.", d.Span, name.Text, "Module binding");+ scope.Values.Add(name.Text);+ if (!moduleContext) Error("firmament-module-context-required", $"Inventory Record '{name.Text}' requires a project loader. Reference this module from a consuming project; it is not an ordinary data Record.", d.Span, name.Text, "Module binding");continue;}var space = NamespaceFor(d);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.csindex f44ecebb..5c315b6a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs@@ -54,7 +54,10 @@ public sealed record DeclarationSyntax(TypeSyntax Type, IdentifierSyntax? Name,[JsonIgnore] public bool HasParameterList { get; init; }}public sealed record FieldSyntax(IdentifierSyntax Name, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);-public sealed record DirectiveSyntax(DirectiveKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);+public sealed record DirectiveSyntax(DirectiveKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span)+{+ public IdentifierSyntax? Name { get; init; }+}public sealed record ExpressionStatementSyntax(ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);public sealed record ReturnSyntax(ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);public sealed record StatementBlockSyntax(BlockSyntax Body, FirmamentV2SourceSpan Span) : StatementSyntax(Span);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 419ce6a8..72e2ec55 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -133,7 +133,15 @@ public static class FirmamentSyntaxParser{var kind = Current.Text switch { "schema" => DirectiveKind.Schema, "Use" => DirectiveKind.Use, _ => DirectiveKind.Include };at++;- try { return new DirectiveSyntax(kind, Expression(allowObject: false), Span(start)); }+ try+ {+ if (kind == DirectiveKind.Include && Current.Kind == SyntaxTokenKind.Identifier && Peek(1).Text == ":")+ {+ var name = Identifier(); Expect(":"); var type = Expression(allowObject: false); Expect("=");+ return new DirectiveSyntax(kind, new TypedValueSyntax(type, Expression(), Span(start)), Span(start)) { Name = name };+ }+ return new DirectiveSyntax(kind, Expression(allowObject: false), Span(start));+ }catch (ParseFailure){Error(kind == DirectiveKind.Schema ? "firmament-schema-malformed" : "firmament-v2-directive-malformed",diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.csindex 54a1704b..c7b46d7a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs@@ -18,7 +18,7 @@ internal sealed class FirmamentSyntaxWriter(string? source = null){DeclarationSyntax d => WriteDeclaration(d),FieldSyntax f => f.Name.Text + ": " + WriteExpression(f.Value) + ";",- DirectiveSyntax d => d.Kind.ToString().ToLowerInvariant() + " " + WriteExpression(d.Value),+ DirectiveSyntax d => d.Kind.ToString().ToLowerInvariant() + " " + (d.Name is null ? "" : d.Name.Text + ": ") + WriteExpression(d.Value),ExpressionStatementSyntax e => WriteExpression(e.Value),ReturnSyntax r => "return " + WriteExpression(r.Value),StatementBlockSyntax b => WriteBlock(b.Body),diff --git a/Aetheris.Kernel.Firmament/ImportedStepSemantics.cs b/Aetheris.Kernel.Firmament/ImportedStepSemantics.csnew file mode 100644index 00000000..a32a593b--- /dev/null+++ b/Aetheris.Kernel.Firmament/ImportedStepSemantics.cs@@ -0,0 +1,18 @@+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Firmament;++/// <summary>Detect annotation families before a geometry-only adapter can discard them.+/// This is not a foreign PMI interpreter or a promise of annotation passthrough.</summary>+internal static class ImportedStepSemantics+{+ internal static bool HasAnnotations(string text)+ {+ if (Step242SemanticPmiInspector.Inspect(text).Items.Count > 0) return true;+ var parsed = Step242SubsetParser.Parse(text);+ return parsed.IsSuccess && parsed.Value.Entities.Any(e => e.Name.EndsWith("_TOLERANCE", StringComparison.Ordinal)+ || e.Name.StartsWith("ANNOTATION_", StringComparison.Ordinal)+ || new[] { "DIMENSIONAL_SIZE", "DIMENSIONAL_LOCATION", "GEOMETRIC_TOLERANCE", "DATUM_FEATURE" }+ .Any(kind => Step242SubsetDecoder.TryGetConstructor(e.Instance, kind) is not null));+ }+}diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentDependencyLock.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentDependencyLock.csnew file mode 100644index 00000000..e1668d02--- /dev/null+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentDependencyLock.cs@@ -0,0 +1,85 @@+using System.Security.Cryptography;+using System.Text;+using Tomlyn;+using Tomlyn.Model;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Modules;++public sealed record FirmamentLockedDependency(string Path, string Format, string HashKind, string Sha256);++/// <summary>Dependency identity, never import policy or geometric admission.</summary>+public sealed record FirmamentDependencyLock(string Root, IReadOnlyList<FirmamentLockedDependency> Dependencies)+{+ public const string FileName = "firmament.lock.toml";+ public static FirmamentDependencyLock Parse(string text)+ {+ try+ {+ var table = TomlSerializer.Deserialize<TomlTable>(text) ?? throw new ArgumentException("Empty lock document.");+ Keys(table, "version", "root", "dependencies");+ if (table["version"] is not long version || version != 1) throw new ArgumentException("Unsupported lock version; expected 1.");+ var root = FirmamentProjectSnapshot.NormalizePath((string)table["root"]!);+ var items = table["dependencies"] as TomlTableArray;+ if (items is null && table["dependencies"] is TomlArray { Count: 0 }) items = new();+ if (items is null) throw new ArgumentException("Lock dependencies must be an array of tables.");+ var dependencies = new List<FirmamentLockedDependency>();+ foreach (var item in items)+ {+ Keys(item, "path", "format", "hashKind", "sha256");+ var path = FirmamentProjectSnapshot.NormalizePath((string)item["path"]!);+ var format = (string)item["format"]!; var kind = (string)item["hashKind"]!; var hash = (string)item["sha256"]!;+ if (format is not ("step" or "firmament") || kind != (format == "step" ? "sha256-bytes" : "sha256-utf8")+ || hash.Length != 64 || hash.Any(c => !char.IsAsciiHexDigit(c))) throw new ArgumentException("Invalid lock dependency format, hash kind or SHA-256.");+ if (dependencies.Any(d => d.Path == path)) throw new ArgumentException("Duplicate locked dependency: " + path);+ dependencies.Add(new(path, format, kind, hash.ToLowerInvariant()));+ }+ return new(root, dependencies);+ }+ catch (Exception error) when (error is TomlException or InvalidCastException or KeyNotFoundException or NullReferenceException)+ { throw new ArgumentException("Malformed Firmament lock: " + error.Message, error); }+ }++ public string ToToml()+ {+ var items = new TomlTableArray();+ foreach (var dependency in Dependencies.OrderBy(d => d.Path, StringComparer.Ordinal))+ items.Add(new TomlTable { ["path"] = dependency.Path, ["format"] = dependency.Format,+ ["hashKind"] = dependency.HashKind, ["sha256"] = dependency.Sha256.ToLowerInvariant() });+ var table = new TomlTable { ["version"] = 1L, ["root"] = Root, ["dependencies"] = items };+ // An empty array of tables has no TOML table declarations to emit.+ // Write an ordinary empty array so the required field remains present.+ if (items.Count == 0) table["dependencies"] = new TomlArray();+ return TomlSerializer.Serialize(table);+ }++ static void Keys(TomlTable table, params string[] names)+ {+ if (table.Keys.Except(names, StringComparer.Ordinal).Any() || names.Any(n => !table.ContainsKey(n)))+ throw new ArgumentException("Lock fields must be exactly: " + string.Join(", ", names));+ }+ internal static FirmamentLockedDependency? StepPin(string? directory, IReadOnlyDictionary<string, string>? resources, string path)+ {+ string? text; string relative;+ if (resources is not null)+ {+ var prefix = string.IsNullOrEmpty(directory) ? "" : directory.Replace('\\', '/') + "/";+ if (!resources.TryGetValue(prefix + FileName, out text) && !resources.TryGetValue(FileName, out text)) return null;+ relative = FirmamentProjectSnapshot.NormalizePath(prefix + path);+ }+ else+ {+ var folder = Path.GetFullPath(directory ?? Directory.GetCurrentDirectory());+ var lockPath = System.IO.Path.Combine(folder, FileName);+ if (!File.Exists(lockPath)) return null;+ text = File.ReadAllText(lockPath);+ var root = AssemblyM0Parser.FindAllowedSourceRoot(System.IO.Path.Combine(folder, "__provided_source.firmament"));+ relative = System.IO.Path.GetRelativePath(root, System.IO.Path.GetFullPath(System.IO.Path.Combine(folder, path))).Replace('\\', '/');+ }+ var manifest = Parse(text);+ var entry = manifest.Dependencies.SingleOrDefault(d => d.Path == relative);+ if (entry is not { Format: "step", HashKind: "sha256-bytes" }) throw new ArgumentException("STEP resource is missing an exact-byte lock entry: " + relative);+ return entry;+ }+ internal static string HashText(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant();+}diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentMetadata.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentMetadata.csnew file mode 100644index 00000000..683a5649--- /dev/null+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentMetadata.cs@@ -0,0 +1,36 @@+using System.Text.Json;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Modules;++internal sealed record FirmamentBoundMetadata(string Name, string Type,+ IReadOnlyDictionary<string, string> Fields, IReadOnlyDictionary<string, string> FieldTypes);++internal static class FirmamentMetadata+{+ internal static FirmamentBoundMetadata? Bind(string source, ExpressionSyntax expression, List<string> diagnostics)+ {+ if (expression is not ReferenceSyntax reference)+ { diagnostics.Add("firmament-metadata-record-required: Select a typed Static Record value."); return null; }+ var binding = new FirmamentDataBinding(source, moduleContext: true);+ diagnostics.AddRange(binding.Diagnostics.Select(d => d.Code + ": " + d.Message));+ var name = binding.ResolveIdentity("value", reference.Name.Text, expression.Span.Start);+ var value = FirmamentV2TemplateExpansion.InspectStaticRecords(binding.Source, diagnostics).SingleOrDefault(r => r.Name == name);+ if (value is null) { diagnostics.Add("firmament-metadata-record-unresolved: " + reference.Name.Text); return null; }+ var schemas = FirmamentV2TemplateExpansion.InspectRecords(binding.Source, diagnostics).ToDictionary(r => r.Name);+ string TypeOf(string path)+ {+ var type = value.TypeName;+ foreach (var component in path.Split('.'))+ {+ if (!schemas.TryGetValue(type, out var schema) || !schema.Fields.TryGetValue(component, out type!)) return "";+ }+ return type;+ }+ return new(reference.Name.Text, binding.DisplayName(value.TypeName),+ value.Fields.ToDictionary(p => p.Key, p => String(p.Value), StringComparer.Ordinal),+ value.Fields.ToDictionary(p => p.Key, p => TypeOf(p.Key), StringComparer.Ordinal));+ }+ internal static string String(string value) => value.StartsWith('"') ? JsonSerializer.Deserialize<string>(value)! : value;+}diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.csindex c2d66891..4d8fe430 100644--- a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs@@ -4,22 +4,30 @@ using Aetheris.Kernel.Firmament.Assembly;using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Semantics;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;namespace Aetheris.Kernel.Firmament.Modules;public sealed record FirmamentInventoryBinding(string Name, string Kind, string SourceFile, string Export,- string DefinitionIdentity, SemanticSourceSpan SourceSpan);+ string DefinitionIdentity, SemanticSourceSpan SourceSpan)+{+ public string? MetadataType { get; init; }+ public IReadOnlyDictionary<string, string> Metadata { get; init; } = new Dictionary<string, string>();+ public bool GeometryOnly { get; init; }+}/// <summary>Per-compilation dependency and export authority. Inventories bind module/// references, never inject imported declarations into the caller. Legacy includes/// retain their existing declaration composition through an explicitly mapped projection.</summary>[FirmamentConstruct("Inventory", "Inventory", Context = "Document", Entry = "Inventory Record Components { }",Description = "Compile-time catalog of typed Part, Subassembly, Assembly and Scene module references.")]-internal sealed class FirmamentModuleGraph+internal sealed partial class FirmamentModuleGraph{internal sealed class Module(string path, string text, DocumentSyntax syntax){internal string Path { get; } = path;+ internal bool Generated { get; set; }internal string Text { get; } = text;internal DocumentSyntax Syntax { get; } = syntax;internal List<Module> Includes { get; } = [];@@ -28,6 +36,7 @@ internal sealed class FirmamentModuleGraphinternal sealed record Reference(string Identity, string Kind, string Path, Module? Module,DeclarationSyntax? Export, string Definition, SemanticSourceSpan Origin){+ internal BrepBody? ImportedBody { get; init; }internal SemanticSourceSpan DeclarationOrigin { get; init; } = Export is null ? Origin : new(Path,Export.Span.Start,Export.Span.Length);}internal sealed record Edit(FirmamentV2SourceSpan Span, string Text);@@ -45,12 +54,33 @@ internal sealed class FirmamentModuleGraph{internal readonly Dictionary<string, Dictionary<string, Reference>> Inventories = new(StringComparer.Ordinal);internal readonly HashSet<string> Values = new(StringComparer.Ordinal);+ internal readonly Dictionary<string, Reference> Direct = new(StringComparer.Ordinal);+ internal Reference? ResolveDirect(string name) => Direct.GetValueOrDefault(name) ?? (Values.Contains(name) ? null : parent?.ResolveDirect(name));internal Dictionary<string, Reference>? Resolve(string name) => Inventories.GetValueOrDefault(name)?? (Values.Contains(name) ? null : parent?.Resolve(name));}private readonly Dictionary<string, Module> modules;private readonly Dictionary<string, Reference> references = new(StringComparer.Ordinal);private readonly List<string> active = [];+ private readonly Dictionary<string, string> assets = new(StringComparer.Ordinal);+ private readonly Dictionary<string, string> assetHashes = new(StringComparer.Ordinal);+ internal string Asset(string path)+ {+ if (assets.TryGetValue(path, out var text)) return text;+ if (Project is not null)+ {+ if (!Project.TryResolve(path, out text!)) throw new FileNotFoundException("Missing snapshot asset: " + path);+ }+ else+ {+ var bytes = File.ReadAllBytes(path);+ assetHashes[path] = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();+ using var reader = new StreamReader(new MemoryStream(bytes), Encoding.UTF8, true);+ text = reader.ReadToEnd();+ }+ assetHashes.TryAdd(path, FirmamentDependencyLock.HashText(text));+ return assets[path] = text;+ }private readonly string allowedRoot;private readonly string identityRoot;internal FirmamentProjectSnapshot? Project { get; }@@ -58,11 +88,12 @@ internal sealed class FirmamentModuleGraphinternal Module Root { get; private set; } = null!;internal bool HasModuleBindings => references.Count > 0;internal List<FirmamentInventoryBinding> InventoryBindings { get; } = [];- internal IReadOnlyList<AssemblySourceDependencyIr> Dependencies => modules.Values.Select(m =>+ internal IReadOnlyList<AssemblySourceDependencyIr> Dependencies => modules.Values.Where(m => !m.Generated).Select(m =>new AssemblySourceDependencyIr(m.Path, Hash(m.Text), ReferenceEquals(m, Root))).Concat(references.Values- .Where(r => r.Module is null && File.Exists(r.Path)).Select(r => new AssemblySourceDependencyIr(r.Path,- Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(r.Path))), false))).DistinctBy(d => d.Path).ToArray();+ .Where(r => r.Module is null).Select(r => new AssemblySourceDependencyIr(r.Path, AssetHash(r.Path), false)))+ .Concat(assets.Select(a => new AssemblySourceDependencyIr(a.Key, assetHashes[a.Key], false))).DistinctBy(d => d.Path).ToArray();+ internal string AssetHash(string path) { Asset(path); return assetHashes[path]; }private FirmamentModuleGraph(string root, FirmamentProjectSnapshot? project){Project = project;@@ -71,10 +102,12 @@ internal sealed class FirmamentModuleGraph: (root.Contains('/') ? root[..root.LastIndexOf('/')] : "");modules = new(project is null ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);}- internal static FirmamentModuleGraph Load(string text, string identity, FirmamentProjectSnapshot? project = null)+ internal static FirmamentModuleGraph Load(string text, string identity, FirmamentProjectSnapshot? project = null, bool validateLock = true, bool hasRootIdentity = true){var graph = new FirmamentModuleGraph(identity, project);+ graph.ReadLock();graph.Root = graph.Read(identity, text, null)!;+ if (validateLock && graph.Diagnostics.Count == 0) graph.CheckLock(hasRootIdentity);return graph;}internal static bool HasImports(string source) => FirmamentLanguageAnalysisService.Lex(source)@@ -124,6 +157,7 @@ internal sealed class FirmamentModuleGraphError("firmament-inventory-header-invalid", "Inventory must qualify a Record: Inventory Record Name { ... }.", At(module, malformed.Span));foreach (var directive in statements.OfType<DirectiveSyntax>().Where(d => d.Kind == DirectiveKind.Include)){+ if (directive.Name is not null) continue;if (directive.Value is not LiteralSyntax { Kind: LiteralKind.String }){ Error("firmament-module-include-invalid", "include requires a quoted Firmament locator.", At(module, directive.Span)); continue; }var locator = Locator(module,(LiteralSyntax)directive.Value);@@ -132,7 +166,12 @@ internal sealed class FirmamentModuleGraphif (childPath is not null && Read(childPath, null, At(module, directive.Span), include: true) is { } child) module.Includes.Add(child);module.Edits.Add(new(directive.Span, Blank(module.Text, directive.Span)));}- foreach (var inventory in statements.OfType<DeclarationSyntax>().Where(IsInventory))+ var directIncludes = statements.OfType<DirectiveSyntax>().Where(d => d.Kind == DirectiveKind.Include && d.Name is not null).ToArray();+ var shortInventories = directIncludes.Select(d => new DeclarationSyntax(+ new(new("Record", d.Span), [], d.Span), new("__Include_" + d.Span.Start, d.Span),+ [new(new("Inventory", d.Span), [], d.Span)], [], null, null, [], null,+ new BlockSyntax([new FieldSyntax(d.Name!, d.Value, d.Span)], d.Span), false, d.Span));+ foreach (var inventory in statements.OfType<DeclarationSyntax>().Where(IsInventory).Concat(shortInventories)){if (inventory.Name is null || inventory.Body is null || inventory.HasParameterList || inventory.Occurrence|| inventory.Annotation is not null || inventory.Initializer is not null || inventory.ResultType is not null@@ -152,15 +191,32 @@ internal sealed class FirmamentModuleGraphvar export = typed.Value is MemberSyntax member ? member.Member.Text : null;var value = typed.Value is MemberSyntax selected ? selected.Target : typed.Value;if (value is not CallSyntax { Target: ReferenceSyntax adapter } call || adapter.Name.Text is not ("Firmament" or "Step")- || call.Arguments.Count != 1 || call.Arguments[0].Name is not null+ || call.Arguments.Count is < 1 or > 3 || call.Arguments[0].Name is not null || call.Arguments.Any(a => a.Default is not null)+ || call.Arguments.Skip(1).Any(a => a.Name?.Text is not ("metadata" or "geometryOnly"))+ || call.Arguments.Skip(1).Select(a => a.Name!.Text).Distinct().Count() != call.Arguments.Count - 1|| call.Arguments[0].Value is not LiteralSyntax { Kind: LiteralKind.String }){ Error("firmament-inventory-resource-invalid", "Use Firmament(\"locator\").Export or Step(\"locator\").", origin); continue; }- if (adapter.Name.Text == "Firmament" && export is null || adapter.Name.Text == "Step" && (export is not null || kind.Name.Text != "Part"))- { Error("firmament-inventory-kind-mismatch", "Firmament requires a named export. Step currently supplies one Part, with no member selector.", origin); continue; }+ if (adapter.Name.Text == "Firmament" && export is null || adapter.Name.Text == "Step" && (export is not null || kind.Name.Text is not ("Part" or "Assembly")))+ { Error("firmament-inventory-kind-mismatch", "Firmament requires a named export. Step supplies a Part or explicit product-structure Assembly, with no member selector.", origin); continue; }+ FirmamentBoundMetadata? metadata = null;+ var metadataArgument = call.Arguments.SingleOrDefault(a => a.Name?.Text == "metadata");+ var geometryArgument = call.Arguments.SingleOrDefault(a => a.Name?.Text == "geometryOnly");+ var geometryOnly = geometryArgument is not null && FirmamentSyntaxWriter.Expression(geometryArgument.Value) == "true";+ if (geometryArgument is not null && (adapter.Name.Text != "Step" || FirmamentSyntaxWriter.Expression(geometryArgument.Value) is not ("true" or "false")))+ { Error("firmament-inventory-resource-invalid", "geometryOnly requires a Boolean on a Step resource.", origin); continue; }+ if (metadataArgument is not null)+ {+ var errors = new List<string>();+ metadata = FirmamentMetadata.Bind(module.Text, metadataArgument.Value, errors);+ foreach (var error in errors) Error("firmament-inventory-metadata-invalid", error, origin);+ if (metadata is null || errors.Count > 0) continue;+ }var locator = Locator(module,(LiteralSyntax)call.Arguments[0].Value);if (locator is null) continue;var path = Resolve(module, locator, adapter.Name.Text, origin);if (path is null) continue;+ if (adapter.Name.Text == "Step" && !geometryOnly && ImportedStepSemantics.HasAnnotations(Asset(path)))+ { Error("firmament-step-source-pmi-unsupported", "Imported annotation passthrough is not qualified. Explicitly request geometryOnly: true to exclude source PMI while retaining the original file.", origin); continue; }Module? child = null; DeclarationSyntax? declaration = null;if (adapter.Name.Text == "Firmament"){@@ -176,19 +232,40 @@ internal sealed class FirmamentModuleGraphif (declaration.Modifiers.Any(m => m.Name.Text == "Template") && actual is not ("Subassembly" or "Struct" or "Model" or "Part")){ Error("firmament-inventory-specialization-required", "Specialize this Template in its defining module and export its concrete Part, Subassembly, Assembly or Scene result.", origin); continue; }}+ if (adapter.Name.Text == "Step" && kind.Name.Text == "Assembly")+ {+ child = ImportStepAssembly(path, origin);+ if (child is null) continue;+ declaration = child.Syntax.Statements.OfType<DeclarationSyntax>().Single(d => d.Type.Name.Text == "Assembly");+ export = declaration.Name!.Text;+ }var identity = "__Module_" + Hash(IdentityPath(path) + "\0" + kind.Name.Text + "\0" + export)[..20];var reference = new Reference(identity, kind.Name.Text, path, child, declaration, export ?? "", origin){ DeclarationOrigin = declaration is null ? origin : DeclarationOrigin(declaration) };references.TryAdd(identity, reference);- InventoryBindings.Add(new(inventory.Name.Text+"."+field.Name.Text,kind.Name.Text,path,export ?? "",identity,origin));+ InventoryBindings.Add(new(inventory.Name.Text+"."+field.Name.Text,kind.Name.Text,path,export ?? "",identity,origin)+ { MetadataType = metadata?.Type, Metadata = metadata?.Fields ?? new Dictionary<string,string>(), GeometryOnly = geometryOnly });if (!fields.TryAdd(field.Name.Text, reference)) Error("firmament-inventory-duplicate-field", $"Inventory member '{field.Name.Text}' is repeated.", origin);+ if (directIncludes.Any(d => d.Span == inventory.Span))+ {+ InventoryBindings[^1] = InventoryBindings[^1] with { Name = field.Name.Text };+ if (scope.Values.Contains(field.Name.Text) || !scope.Direct.TryAdd(field.Name.Text, reference))+ Error("firmament-inventory-duplicate-name", $"Include '{field.Name.Text}' conflicts with another declaration.", origin);+ }}module.Edits.Add(new(inventory.Span, Blank(module.Text, inventory.Span)));}+ BindInlineSteps(module, statements, scope);foreach (var declaration in statements.OfType<DeclarationSyntax>().Where(d => !IsInventory(d))){if (declaration.Initializer is { } initializer){+ if (initializer is SpecializationSyntax { Target: ReferenceSyntax { Name.Text: "ExternalStep" }, Arguments: [{ Name: null, Value: LiteralSyntax { Kind: LiteralKind.String } legacyPath }] })+ {+ var locator = Locator(module, legacyPath);+ var path = locator is null ? null : Resolve(module, locator, "Step", At(module, initializer.Span));+ if (path is not null) Asset(path);+ }// Concise includes also expose concrete Parts under their authored// names. Existing Template applications keep their established owner.if (module.Includes.Count > 0 && declaration.Occurrence && declaration.Type.Name.Text == "Part" && initializer is ReferenceSyntax bare)@@ -206,6 +283,7 @@ internal sealed class FirmamentModuleGraph}}var target = initializer is SpecializationSyntax specialization ? specialization.Target : initializer;+ Reference? reference = target is ReferenceSyntax direct ? scope.ResolveDirect(direct.Name.Text) : null;if (target is MemberSyntax { Target: ReferenceSyntax owner } member){var fields = scope.Resolve(owner.Name.Text);@@ -215,12 +293,15 @@ internal sealed class FirmamentModuleGraphError("firmament-inventory-not-visible", $"Inventory '{owner.Name.Text}' is shadowed or not visible in this scope.", At(module, target.Span));continue;}+ if (!fields.TryGetValue(member.Member.Text, out reference))+ { Error("firmament-inventory-member-unresolved", $"Inventory '{owner.Name.Text}' has no member '{member.Member.Text}'.", At(module, member.Span)); continue; }+ }+ if (reference is not null)+ {if (!declaration.Occurrence)Error("firmament-inventory-use-unsupported", "Use an Inventory module reference as a Part, Assembly or Scene occurrence definition.", At(module, target.Span));- else if (!fields.TryGetValue(member.Member.Text, out var reference))- Error("firmament-inventory-member-unresolved", $"Inventory '{owner.Name.Text}' has no member '{member.Member.Text}'.", At(module, member.Span));else if (!(declaration.Type.Name.Text == "Assembly" ? reference.Kind is "Assembly" or "Subassembly" : declaration.Type.Name.Text == reference.Kind))- Error("firmament-inventory-kind-mismatch", $"A {declaration.Type.Name.Text} occurrence cannot use {reference.Kind} '{owner.Name.Text}.{member.Member.Text}'.", At(module, target.Span));+ Error("firmament-inventory-kind-mismatch", $"A {declaration.Type.Name.Text} occurrence cannot use {reference.Kind} '{FirmamentSyntaxWriter.Expression(target)}'.", At(module, target.Span));else if (initializer is SpecializationSyntax && reference.Export?.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments).Any(a => a.Value is TypeParameterSyntax) == true)Error("firmament-inventory-type-argument-unsupported", "Imported Templates currently accept compile-time values, not caller-defined types. Specialize type parameters in the defining module and export a concrete product.", At(module, initializer.Span));@@ -293,8 +374,6 @@ internal sealed class FirmamentModuleGraph}if (extension.Length > 0 && !extensions.Contains(extension, StringComparer.OrdinalIgnoreCase)){ Error(include ? "assembly-include-extension-invalid" : "firmament-inventory-extension-invalid", $"{adapter} resource '{locator}' requires {string.Join(" or ", extensions)}.", origin); return null; }- if (adapter == "Step" && Project is not null)- { Error("assembly-profile-external-resource-unsupported", "This project snapshot contains source documents only; provide STEP through a file-backed project.", origin); return null; }bool Exists(string candidate) => Project is null ? File.Exists(candidate) : Project.TryResolve(candidate, out _);var matches = extension.Length == 0 ? extensions.Select(e => path + e).Where(Exists).ToArray() : Exists(path) ? [path] : Array.Empty<string>();if (matches.Length != 1)@@ -339,6 +418,31 @@ internal sealed class FirmamentModuleGraphreturn new(text.ToString(), segments, module.Path);}+ private Module? ImportStepAssembly(string path, SemanticSourceSpan origin)+ {+ var virtualPath = path + ".firmament";+ if (modules.TryGetValue(virtualPath, out var existing)) return existing;+ var imported = Step242AssemblyImporter.Import(Asset(path));+ if (!imported.IsSuccess || imported.Diagnostics.Any(d => d.Source == "Importer.Assembly.MultiplicityNormalization"))+ {+ Error("firmament-step-assembly-import-rejected", "An explicit, qualified STEP product hierarchy is required. " + string.Join(" | ", imported.Diagnostics.Select(d => d.Message)), origin);+ return null;+ }+ var components = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var definition in imported.Value.Definitions.Where(d => d.Geometry is not null))+ {+ var identity = "__Module_" + Hash(IdentityPath(path) + "\0step-definition\0" + definition.StableId)[..20];+ references.TryAdd(identity, new(identity, "Part", path, null, null, definition.Name, origin) { ImportedBody = definition.Geometry });+ components[definition.StableId] = identity;+ }+ // Reuse the importer-owned hierarchy transport, retaining original BReps+ // in typed leaf references instead of exporting temporary child STEP files.+ var text = Step242FirmasmPackageImporter.GenerateSource(imported.Value, components, Path.GetFileName(path), componentReferences: true);+ var module = Read(virtualPath, text, origin);+ if (module is not null) module.Generated = true;+ return module;+ }+internal Reference LocalPart(Module module, string definition){if (TryReference(definition, out var existing)) return existing;@@ -385,7 +489,9 @@ internal sealed class FirmamentModuleGraph// honest enclosing origin rather than pretending generated spans are authored.projection = new(concrete, [new(0, concrete.Length, reference.DeclarationOrigin, false)], reference.Path);}- return new AssemblyM0Parser().ParseBound(projection.Text, reference.Path, this, reference.Module!, projection, reference.Export);+ var result = new AssemblyM0Parser().ParseBound(projection.Text, reference.Path, this, reference.Module!, projection, reference.Export);+ return reference.Module!.Generated ? result with { Diagnostics = result.Diagnostics.Select(d => d with {+ SourceSpan = reference.Origin, LocationNote = "Enclosing STEP import; hierarchy transport is generated from the imported product structure, without an authored Firmament span." }).ToArray() } : result;}internal AssemblyMemberSource QualifyParts(Module module, AssemblyMemberSource root) => root with{diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleResources.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleResources.csnew file mode 100644index 00000000..d085a4ea--- /dev/null+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleResources.cs@@ -0,0 +1,117 @@+using System.Text.Json;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Modules;++internal sealed partial class FirmamentModuleGraph+{+ internal FirmamentDependencyLock? Locked { get; private set; }+ internal HashSet<string> SurgicalAssets { get; } = new(StringComparer.Ordinal);+ internal string LockPath => Project is null ? Path.Combine(identityRoot, FirmamentDependencyLock.FileName)+ : (identityRoot.Length == 0 ? "" : identityRoot + "/") + FirmamentDependencyLock.FileName;+ internal string Relative(string path) => Project is null ? Path.GetRelativePath(allowedRoot, path).Replace('\\', '/') : path;++ private void ReadLock()+ {+ string? text = Project is null ? File.Exists(LockPath) ? File.ReadAllText(LockPath) : null+ : Project.TryResolve(LockPath, out var content) ? content : null;+ if (text is null) return;+ try { Locked = FirmamentDependencyLock.Parse(text); }+ catch (ArgumentException error) { Error("firmament-lock-invalid", error.Message, new(LockPath, 0, text.Length)); }+ }++ private void CheckLock(bool hasRootIdentity)+ {+ if (Locked is null) return;+ if (hasRootIdentity && Locked.Root != Relative(Root.Path))+ { Error("firmament-lock-root-mismatch", "The lock belongs to '" + Locked.Root + "', not this project root.", new(LockPath, 0, 0)); return; }+ foreach (var dependency in Dependencies.Where(d => !d.IsRoot))+ {+ var path = Relative(dependency.Path);+ var locked = Locked.Dependencies.SingleOrDefault(d => d.Path == path);+ var format = FirmamentProjectSnapshot.IsStepAsset(path) ? "step" : "firmament";+ var kind = format == "step" ? "sha256-bytes" : "sha256-utf8";+ if (locked is null || locked.Format != format || locked.HashKind != kind+ || !locked.Sha256.Equals(dependency.Sha256, StringComparison.OrdinalIgnoreCase))+ Error("firmament-lock-dependency-mismatch", "Dependency '" + path + "' differs from the lock or has no matching entry. Reinspect affected edits before updating it.", new(LockPath, 0, 0));+ }+ }++ private void BindInlineSteps(Module module, IReadOnlyList<StatementSyntax> statements, Scope scope)+ {+ foreach (var step in statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "InlineStep" && d.Body is not null))+ {+ var fields = step.Body!.Statements.OfType<FieldSyntax>().ToArray();+ var from = fields.Where(f => f.Name.Text is "from" or "From").ToArray();+ var paths = fields.Where(f => f.Name.Text is "path" or "Path").ToArray();+ string? path = null;+ if (from.Length > 0)+ {+ Reference? reference = from[0].Value is MemberSyntax { Target: ReferenceSyntax catalog } member+ ? scope.Resolve(catalog.Name.Text)?.GetValueOrDefault(member.Member.Text)+ : from[0].Value is ReferenceSyntax direct ? scope.ResolveDirect(direct.Name.Text) : null;+ if (from.Length != 1 || paths.Length > 0 || reference is not { Kind: "Part", Module: null, ImportedBody: null })+ { Error("firmament-inline-step-source-unresolved", "from requires one imported STEP Part reference and cannot coexist with path.", At(module, step.Span)); continue; }+ path = reference.Path;+ var folder = Path.GetDirectoryName(module.Path);+ var relative = Path.GetRelativePath(string.IsNullOrEmpty(folder) ? "." : folder, path).Replace('\\', '/');+ module.Edits.Add(new(from[0].Span, "path: " + JsonSerializer.Serialize(relative) + ";"));+ }+ else if (paths is [{ Value: LiteralSyntax { Kind: LiteralKind.String } literal }])+ {+ var locator = Locator(module, literal);+ if (locator is not null) path = Resolve(module, locator, "Step", At(module, paths[0].Span));+ }+ if (path is null) continue;+ Asset(path);+ if (statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text is "Recognize" or "Replace" or "Remove"+ && (d.Name?.Text == step.Name?.Text || d.Name?.Text.StartsWith(step.Name!.Text + ".", StringComparison.Ordinal) == true))) SurgicalAssets.Add(Relative(path));+ var locked = Locked?.Dependencies.SingleOrDefault(d => d.Path == Relative(path));+ if (locked is not null && !fields.Any(f => f.Name.Text is "sha256" or "Sha256" or "textSha256" or "TextSha256"))+ module.Edits.Add(new(new(step.Body.Span.Start + 1, 0), "\nsha256: " + JsonSerializer.Serialize(locked.Sha256) + ";\n"));+ }+ }+}++public sealed record FirmamentDependencyInspection(FirmamentDependencyLock? Manifest,+ IReadOnlyList<string> SurgicalAssets, IReadOnlyList<AssemblyDiagnostic> Diagnostics)+{+ public bool IsSuccess => Manifest is not null && Diagnostics.Count == 0;+}++public static class FirmamentDependencies+{+ /// <summary>Checks the same dependency graph used by compilation. Never writes or refreshes a lock.</summary>+ public static IReadOnlyList<AssemblyDiagnostic> VerifyFile(string path, bool requireLock = false)+ {+ var full = Path.GetFullPath(path);+ var lockPath = Path.Combine(Path.GetDirectoryName(full)!, FirmamentDependencyLock.FileName);+ if (!File.Exists(lockPath)) return requireLock+ ? [new("firmament-lock-required", "Locked compilation requires " + lockPath) { SourceSpan = new(full, 0, 0) }] : [];+ return FirmamentModuleGraph.Load(File.ReadAllText(full), full).Diagnostics;+ }++ public static FirmamentDependencyInspection InspectFile(string path, bool update = false)+ => InspectSource(File.ReadAllText(path), path, update);++ public static FirmamentDependencyInspection InspectSource(string source, string path, bool update = false)+ {+ var full = Path.GetFullPath(path);+ var graph = FirmamentModuleGraph.Load(source, full, validateLock: false);+ if (graph.Diagnostics.Count > 0) return new(null, graph.SurgicalAssets.ToArray(), graph.Diagnostics);+ var entries = graph.Dependencies.Where(d => !d.IsRoot).Select(d => new FirmamentLockedDependency(graph.Relative(d.Path),+ FirmamentProjectSnapshot.IsStepAsset(d.Path) ? "step" : "firmament",+ FirmamentProjectSnapshot.IsStepAsset(d.Path) ? "sha256-bytes" : "sha256-utf8", d.Sha256.ToLowerInvariant())).ToArray();+ if (graph.Locked is { } previous)+ {+ if (previous.Root != graph.Relative(full)) return new(null, graph.SurgicalAssets.ToArray(), [new("firmament-lock-root-mismatch", "The existing lock belongs to another root document.")]);+ var changed = entries.Where(d => previous.Dependencies.SingleOrDefault(old => old.Path == d.Path)?.Sha256 != d.Sha256).ToArray();+ if (!update && changed.Length > 0) return new(null, graph.SurgicalAssets.ToArray(), [new("firmament-lock-update-required", "Use an explicit lock update for changed dependencies.")]);+ if (changed.Any(d => graph.SurgicalAssets.Contains(d.Path)))+ return new(null, graph.SurgicalAssets.ToArray(), [new("firmament-lock-rebind-required", "A changed STEP source has bound surgery. Reinspect and regenerate its selections before replacing the lock; a hash update cannot rebind authoring intent.")]);+ }+ return new(new(graph.Relative(full), entries), graph.SurgicalAssets.ToArray(), []);+ }+}diff --git a/docs/development/architecture/imported-hole-revisions.md b/docs/development/architecture/imported-hole-revisions.mdindex ca1105be..4e14a50d 100644--- a/docs/development/architecture/imported-hole-revisions.md+++ b/docs/development/architecture/imported-hole-revisions.md@@ -45,7 +45,14 @@ than project onto XY. Authored confidence never overrides geometric proof.The destination is a world Point3 on the selected support. Diameter is unchanged;ThroughAll resolves against that support pair, not global body bounds. The typed`within` prism spans both supports and contains both complete old/new holes with-positive clearance. Every unrelated boundary face must be excluded using+positive clearance. The optional second bounds object gives separate suppression+and insertion prisms. For that form, the existing planar domain owner proves the+destination is inside each support's trimmed material domain, excluding only the+opening being suppressed. Line/circle loops use a certified chord-deviation bound;+the display-oriented whole-body-bounds fallback is not an admission proof.+Spline/unresolved trim boundaries and ambiguous probes reject this form. Boundary+exclusion alone is insufficient for a disconnected prism entirely outside the part+or inside an existing opening. Every unrelated boundary face must be excluded usingconservative plane/cylinder/cone support bounds, finite line/circle/B-spline curvehulls and the import uncertainty budget. Unsupported bounds reject. This canrefuse physically possible edits; it cannot choose a permissive fallback.@@ -110,3 +117,29 @@ intersecting, threaded or blended holes, broader stock bounds, multiple edits peModel, generic source PMI migration, and UI recognition/editing affordances.Independent STEP producers beyond the admitted geometric family need their ownqualification; CTC-01 is a golden witness, not universal import certification.++## Recovery assistance++`BrepThroughHoleRevision.Discover` uses the same connected-wall traversal and+recognition certificate as `Execute`. It exposes measured cylinder groups,+proved through-hole facts and import-qualification refusal reasons. Candidate IDs+use sorted original STEP wall entities and are scoped to the explicit source pin;+they are not cross-revision feature tracking or inferred construction history.+`CanPlan` says nothing about a destination's clearance.++Core `PlanMove` derives two local bounds and executes the production operation.+`FirmamentImportedFeatures.PlanMove` then emits ordinary unified-AST Firmament,+including `Region` candidate selection, an explicit source pin and named Concept+Struct Point3, and compiles that source through normal build/export admission.+It does not bypass export roundtrip or annotation policy. The SDK can retain an+immutable resource snapshot; the CLI's file-backed mode rereads through the pinned+loader. Candidate selection has no nearest-hole recovery or implicit ambiguity+resolution. The CLI's `--as` chooses an existing Region/Feature name rather than+introducing another language construct. Diagnostics use the compiler's canonical+structured presentation; unavailable original STEP source spans are disclosed.++The two-region CTC-01 witness moves the upper-left hole +290 mm across the central+boss. A single enclosing corridor rejects on the intervening boundaries. Residual+geometry, topology identities and generated semantic PMI remain under the same+production revision owner. This is agent assistance for the admitted family,+not a general feature recognizer or geometry repair system.diff --git a/docs/public/firmament/imported-feature-recognition.md b/docs/public/firmament/imported-feature-recognition.mdindex a03cb794..b09970f3 100644--- a/docs/public/firmament/imported-feature-recognition.md+++ b/docs/public/firmament/imported-feature-recognition.md@@ -40,7 +40,9 @@ Model Revision {```Put the unmodified CTC-01 STEP beside this example as `ctc01.stp`, or use the-repository fixture's relative path. Choose exactly one pin:+repository fixture's relative path. Prefer `aetheris lock revision.firmament` to+generate a dependency receipt, then omit the source hash field. For a source-only+specimen, choose exactly one explicit pin:- `sha256` checks exact file bytes. Obtain it with PowerShell`Get-FileHash file.stp -Algorithm SHA256`.@@ -53,6 +55,87 @@ There is no fallback between these modes. Build JSON records the chosen hash kinand actual input byte hash (UTF-8 resource hash for browser snapshots). Re-inspectentity selectors before intentionally updating a pin after an upstream revision.+## Discover, name and plan a revision++Agents do not need to author BRep ordinals or guess edit bounds. Start with the+actual imported geometry:++```shell+aetheris imported-features inspect ctc01.stp --import-tolerance .01 --json+```++The report is explicitly `InspectionOnly`. It returns measured cylindrical groups,+original STEP wall entities, axis, diameter, and, when proved, through-depth,+entry/exit faces and center. `Recognized` means the bounded through-hole proof+passed. `CanPlan` additionally requires import qualification; it does **not**+certify a new destination. Unsupported groups carry rejection reasons. Strict+.001 mm inspection of CTC-01 still reports measurements but blocks planning.+No original design history or manufacturing process is inferred.++Select one candidate using these facts, then pass its exact ID. For the pinned+CTC-01 source, the upper-left diameter-25 hole has this ID:++```shell+aetheris imported-features plan ctc01.stp --candidate "through-hole:step-764+765" --as MountHole --offset 290 0 --geometry-only --import-tolerance .01 --source-out artifacts/local/imported-features/revision.firmament --json+aetheris validate artifacts/local/imported-features/revision.firmament --json+aetheris build artifacts/local/imported-features/revision.firmament --output artifacts/local/imported-features/revised.step --json+```++`--offset dx dy` uses imported-body XY coordinates from the proved upper opening;+`--to x y z` supplies an absolute Point3 instead. All numbers are millimetres.+Exactly one placement mode is required. `--clearance` defaults to .1 mm and must+exceed import uncertainty. The plan qualifies its generated source through normal+build admission before committing outputs; a refused plan leaves no new source file.++`--as MountHole` names the existing `Region` and replacement feature. There is no+additional Firmament `as` grammar. The emitted declaration is:++```firmament+Recognize Source {+ Region MountHole {+ kind: HoleShaft+ candidate: "through-hole:step-764+765"+ }+}+```++`candidate` is mutually exclusive with `faces` and `stepFaceEntities`. Candidate+IDs are stable within the pinned source, not across arbitrary STEP re-exports or+entity renumbering. A missing or unsupported candidate rejects; the compiler never+chooses a nearby hole. CLI planning writes `firmament.lock.toml` alongside the+hash-free revision source, and qualifies that saved source through the normal+compiler before reporting success. Previous source/lock files are restored on a+qualification failure. An existing receipt for another root rejects. Re-inspect+and review a changed STEP in a new revision/project; a lock update cannot rebind+surgery selections. The SDK source-only `PlanMove` result retains its explicit+`textSha256` pin for compatibility and immutable resource planning.++Generated geometry dimensions and coordinates use a **0.1 mm authoring grid**:+nearest tenth for nominal lengths and positions, midpoint ties away from zero.+Safety bounds and radial padding round outward. For example, imported arithmetic+noise `24.9999999999998mm` becomes authored `25mm`, and `45.0000000000001mm`+becomes `45mm`. This changes the authored nominal geometry and replacement PMI,+not merely their display formatting. The JSON plan records+`authoringIncrementMillimetres: 0.1`.++The numerical `importTolerance` budget keeps its own precision (`0.01mm` in this+fixture); rounding it to zero or widening it would change import admission.+The emitted, rounded source must still build. Genuine resizing or moving off the+proved support plane remains subject to the current capability checks. The grid+does not invent a manufacturing tolerance annotation or modify retained STEP+geometry. Explicit `tol` requirements remain the source of manufacturing limits.++The destination is a named `Concept Struct` Point3; destination bounds reference+its `.X` and `.Y` components. Editing that one point moves the requested hole and+reruns clearance checks without duplicating coordinates. The executable+[recovered fixture](../../../fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmament)+moves the hole across the central boss to (130,45) mm without editing the boss.++The .NET SDK exposes the same path through `FirmamentImportedFeatures.Inspect`+and `PlanMove`. Snapshot planning uses the immutable inspected resource text;+file-backed planning rechecks the pin through the ordinary loader. Explicit+geometry-only approval remains required in both paths.+## What the fields mean`stepFaceEntities` selects original STEP entity IDs. `faces` is the historical@@ -67,8 +150,14 @@ face 98 is the plane at Z=0. `center` is a Point3 in imported-body coordinates,which coincide with Model world coordinates in this single-body workflow. Itmust lie on the selected plane. Imported UV origins are not inferred from a Point2.-`within` authorizes the local edit volume. Its Point3 min/max must contain both-holes with positive clearance and span the support planes. The compiler proves+`within` authorizes the local edit volume. One bounds object must contain both+holes with positive clearance and span the support planes. Alternatively,+`within: [sourceBounds, destinationBounds]` takes exactly two bounds objects,+each `{ min: Point3(...); max: Point3(...) }`. They authorize suppression and+reinsertion separately; no swept movement corridor is edited. Separate regions+currently require provable line/circle support trim boundaries, and the+destination must be inside both material domains, excluding other openings.+An exterior destination cannot manufacture stock. The compiler provesthat no other boundary can interfere. A conservative refusal means the currentplanner cannot prove that envelope safe; it is not necessarily a physicallyimpossible edit. Support faces can extend outside the box: their support surfaces,@@ -102,9 +191,10 @@ The current family is one isolated round Z-axis through-hole, unchanged diameterand depth, between two parallel planar supports in one qualified closed orientedbody. Blind, intersecting, breakout, threaded, blended-entry, counterbore,countersink and non-Z-axis revisions reject. Unknown fields and placements reject.-No arbitrary-body Boolean fallback or general healing is performed. Pinned imports-currently require this one bounded replacement; standalone pinned re-export and-additional Modify operations reject rather than bypassing revision admission.+No arbitrary-body Boolean fallback or general healing is performed. An unedited+pinned body can be re-exported through the qualified import owner; a pin does not+imply a replacement operation. Additional Modify operations still reject rather+than bypassing revision admission.The operation suppresses the old wall/openings, materializes fresh analytic holegeometry and reinserts it with fresh topology IDs. Unchanged topology keeps its@@ -128,3 +218,6 @@ Use the pinned `within` form for the qualified production operation.See the [production closeout](../../release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md)for test evidence and the [design contract](../../development/architecture/imported-hole-revisions.md)for ownership and limits.++See the [recovery-assistance qualification](../../release/IMPORTED-FEATURE-ASSISTANCE-2026-10-21.md)+for the cross-boss revision and admission evidence.diff --git a/docs/public/firmament/inventory.md b/docs/public/firmament/inventory.mdindex 74c88e7d..83960b30 100644--- a/docs/public/firmament/inventory.md+++ b/docs/public/firmament/inventory.md@@ -4,6 +4,19 @@ Use `include` for a short composition whose declarations can share names in onemodule. Use an `Inventory Record` when named, qualified dependencies make a largerAssembly or Scene easier to organize. Neither form has a one- or two-part limit.+For a short typed import, name the resource directly:++```firmament+include bearing: Part = Step("vendor/bearing");+include drive: Assembly = Step("vendor/drive");+include bracket: Part = Firmament("parts/bracket").Bracket;+```++Use `bearing`, `drive` or `bracket` as an occurrence's initializer. These are+module references, with the same admission and identity rules as catalog members.+They do not inject the imported module's private declarations into the caller.+The original `include "parts/bolt";` remains declaration composition.+Firmament's importable module kinds are Part, Subassembly, Assembly and Scene.Inventory references inside occurrence Patterns bind before expansion.An Inventory member is a reference to an exported definition or admitted typed family. Adding it to a catalog@@ -18,14 +31,23 @@ Inventory Record Components {machine: Assembly = Firmament("assemblies/machine").Machinelaboratory: Scene = Firmament("scenes/laboratory").Laboratorybearing: Part = Step("vendor/bearing")+ gearbox: Assembly = Step("vendor/gearbox")}```This is a declaration fragment: provide the named files and exports in your project.`Firmament(...)` selects a named root declaration; `Step(...)` supplies one exact-Part through the existing STEP importer. Missing or ambiguous exports and kind-mismatches reject. STEP assemblies and multi-body assets must satisfy the existing-single-Part importer contract; there is no implicit first-body selection.+Part through the existing STEP importer. An explicit `Assembly = Step(...)`+retains the imported product tree, local occurrence transforms and shared leaf+geometry. Foreign hierarchy must be trustworthy: this form rejects the importer's+fallback that normalizes ambiguous multiplicity to a flat assembly. Missing or+ambiguous exports and kind mismatches reject. A Part still requires one body;+there is no implicit first-body selection.++Imported annotation passthrough is not qualified. A STEP resource containing PMI+rejects unless the binding explicitly says `Step("vendor/gearbox", geometryOnly:+true)`. That exclusion is retained in the binding receipt; the original file is+untouched. This permission does not relax geometry admission.The normal spelling omits the extension. `Firmament("parts/bracket")` resolves`.firmament` or `.firmasm`; `Step("vendor/bearing")` resolves `.step` or `.stp`.@@ -35,8 +57,8 @@ package registry chooses a resource behind the author's back.Locators resolve relative to the document containing the declaration and muststay inside the existing allowed source root. Source snapshots resolve from their-provided document map, without reading files from disk. Snapshots currently hold-Firmament source only; a STEP Inventory entry requires a file-backed project.+provided document map, without reading files from disk. Snapshots can include+`.step`/`.stp` text assets and the optional lock alongside Firmament source.## Place the referenced definitions@@ -125,3 +147,86 @@ claim complete generated-source provenance across every domain lowerer.Unused Inventory entries are resolved and kind-checked; engineering geometry isconstructed for placed occurrences. Inventory availability does not imply anoccurrence count or a bill of materials.++## Typed resource metadata++Use ordinary typed Records, not another metadata dictionary syntax:++```firmament+Record VendorInfo { manufacturer: String partNumber: String revision: String }+Static BearingInfo: VendorInfo {+ manufacturer: "Example supplier"+ partNumber: "BRG-01"+ revision: "B"+}+Inventory Record Components {+ bearing: Part = Step("vendor/bearing", metadata: BearingInfo)+}+```++`metadata:` also works on `Firmament(...)` and typed short includes. The normal+Record binder checks the selected Static value. The binding receipt exposes its+type and flattened fields in Assembly IR. Resource metadata is descriptive; it+does not infer fits, manufacturing tolerances, materials or PMI, and it is not+automatically translated into vendor-specific AP242 properties. Two aliases for+the same imported Part retain one geometry definition even with different receipts.++Assembly `provenance: Release;` selects a typed release Record for the existing+AP242 header and product annotations. Canonical fields are `author: String`+(or a nested Record with `name: String`), `date: Date`, `version: Version`, and+`description: String`; `organization: String` is optional. Nested values refer to+other typed Static Records. Additional typed fields remain inspectable. Legacy+PascalCase fields remain accepted; providing both aliases rejects. Authors and+approval states must be supplied truthfully; the compiler invents neither.++## Optional dependency lock++Run `aetheris lock main.firmasm` to generate `firmament.lock.toml` beside the root.+Commit it with a reproducible project. Normal builds work without one; if a lock+exists, both validation and compilation enforce it. `aetheris validate main.firmasm+--locked` and `aetheris build main.firmasm --locked` additionally require its presence.+Compilation never rewrites the lock. Use `aetheris lock main.firmasm --update` for+an intentional dependency refresh.++Version 1 receipts contain the root identity and sorted dependency entries with+`path`, `format`, `hashKind` and `sha256`. STEP hashes cover exact file bytes;+Firmament hashes cover decoded UTF-8 source text. Snapshot STEP text is represented+by its UTF-8 bytes, so byte-identical receipts require identical encoding/BOM and+line endings. Paths use the loader's allowed source root: the Aetheris repository+root for repository files, otherwise the root document's directory; snapshot paths+are relative to the supplied project. A receipt belongs to one compilation root.+Unknown TOML fields, missing entries, changed dependencies and a different root+reject. Unused old entries are tolerated, and a lock command refresh removes them.++A changed STEP with bound `Recognize`/`Replace`/`Remove` intent refuses even an+explicit update. Reinspect and regenerate its selections in a new reviewed+revision/project receipt. Refreshing a hash cannot establish that a face still+has the same engineering meaning. Locks establish identity, not geometric quality+or permission to discard PMI. This version uses one conventional sidecar name;+custom lock locations and cross-root lock workspaces are outside this pass.++## InlineStep: local annotation and surgery++For mixed products, use Part/Assembly imports. Use `InlineStep` when a Model needs+to annotate or revise one imported body. It can select an existing STEP Part binding:++```firmament+Inventory Record Components { housing: Part = Step("vendor/housing", geometryOnly: true) }+Model Revision {+ units: mm+ InlineStep Source {+ from: Components.housing+ geometryOnly: true+ importTolerance: 0.01mm+ }+}+```++This fragment requires a matching generated lock. `from` and `path` are mutually+exclusive; `from` admits a STEP Part reference, not a native Firmament Part or+STEP Assembly. Direct `path: "vendor/housing.step"` remains supported. Explicit+`sha256` and `textSha256` remain compatible for self-contained pinned source;+the lock can supply the pin instead. Import tolerance is a numerical budget,+separate from authored dimensions. A locked, qualified body can be re-exported+unchanged without pretending to perform a replacement. Surgery still uses the+bounded [Recognize/Replace contracts](imported-feature-recognition.md).diff --git a/docs/public/firmament/project-snapshots.md b/docs/public/firmament/project-snapshots.mdindex 2fcd9c36..b7a5e498 100644--- a/docs/public/firmament/project-snapshots.md+++ b/docs/public/firmament/project-snapshots.md@@ -1,9 +1,9 @@# In-memory Firmament project snapshots-`FirmamentProjectSnapshot` accepts one explicit `.firmasm` or `.firmament` root and a finite map of project-relative `.firmasm` and `.firmament` source documents. `AssemblyM1Pipeline.CompileProject(snapshot)` resolves `Include` declarations and `LoftFile`/`SectionChainFile` sources from that map. Paths use `/`, normalize `.` and `..`, and reject paths outside the project root. The local `CompileFile` path remains available for CLI use.+`FirmamentProjectSnapshot` accepts one explicit `.firmasm` or `.firmament` root and a finite map of project-relative Firmament source, STEP text assets and an optional `firmament.lock.toml`. `AssemblyM1Pipeline.CompileProject(snapshot)` resolves `Include` declarations and `LoftFile`/`SectionChainFile` sources from that map. Paths use `/`, normalize `.` and `..`, and reject paths outside the project root. The local `CompileFile` path remains available for CLI use.This compiler entry point can materialize the canonical Cartesian lamp assembly and its shade from two in-memory source strings. The browser SDK now accepts `projectDocuments` beside `sourceName` for Assembly and Scene compilation, routing to the existing retained compilation owners. Helios's local showcase uses that path for the canonical ATLAS, guitar and house projects. Browser language analysis also accepts `projectRoot` and `projectDocuments` for Assembly project context. This source-snapshot API does not introduce multi-file cloud persistence.-The module graph resolves `.firmament` and `.firmasm` dependencies, including extensionless locators and typed [Inventory Records](inventory.md). Inventory locators resolve relative to the declaring document. Existing snapshot project-root-relative include spellings remain a fallback when the document-relative target is absent. `ExternalStep` and `InlineStep` are rejected for snapshot compilation because the snapshot contains source documents, not binary STEP assets.+The module graph resolves `.firmament` and `.firmasm` dependencies, including extensionless locators, typed short includes and [Inventory Records](inventory.md). Inventory locators resolve relative to the declaring document. Existing snapshot project-root-relative include spellings remain a fallback when the document-relative target is absent. Supplied `.step`/`.stp` text assets work with STEP Part/Assembly imports, `ExternalStep` occurrences and `InlineStep`. Missing assets reject; compilation never falls back to the local filesystem. Optional `firmament.lock.toml` text is included in the same immutable map and enforced by the module loader. A snapshot represents STEP text as UTF-8 bytes, not an arbitrary original binary encoding.An AST-owned dependency graph replaces regex include discovery. Legacy includes retain declaration composition through a source-mapped adapter; Inventory imports bind named exports in separate modules. Dependency hashes identify all resolved source documents, and Inventory/resource/syntax diagnostics retain their declaring file and span. Downstream engineering readers still contain source adapters, so complete generated-source navigation across every lowerer is not yet qualified.diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.mdindex 394a0ed9..8d68d986 100644--- a/docs/public/firmament/step-import.md+++ b/docs/public/firmament/step-import.md@@ -3,6 +3,14 @@Use [surface and trim inspection](surface-inspection.md) in Cadmata or Helios to compare filled geometry, BRep wire, translucent overlays and isolated source faces without changing the camera.Direct STEP inspection is available through the native CLI/Cadmata workflows.+For mixed Part/Assembly products, prefer typed `include` or an+[Inventory Record](inventory.md). `Step("vendor/drive")` can supply an explicit+Assembly with its existing hierarchy and transforms. `InlineStep` is the local+annotation/surgery binding for one body; it can use `from: Components.housing`+or a direct path. An optional generated dependency lock supplies its source pin,+so authors do not need to write SHA-256 strings. See the Inventory guide for lock+commands, metadata and the explicit exclusion of imported PMI.+Helios also provides **Import STEP** for the bounded canonical `InlineStep` partworkflow described below. It retains the input as an immutable text asset andcreates a Firmament annotation layer. This is not arbitrary vendor STEP ordiff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 4934533d..b7debbc9 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -377,7 +377,17 @@ for new hole construction. `Recognize` names a region of imported geometry. Thequalified imported-hole revision form pins the STEP with `sha256` (exact bytes)or `textSha256` (explicit UTF-8/LF text normalization), proves acomplete through-hole and uses `Replace ... with Hole<Shaft>` plus explicit-`within` bounds to move it while retaining the residual BRep. The first family is+`within` bounds to move it while retaining the residual BRep. A Region can select+an inspected, revision-scoped `candidate: "through-hole:step-764+765"` instead of+manual face selectors. `aetheris imported-features inspect` supplies the measured+candidates; `plan --as MountHole` names the Region and emits a fully built revision+using a named Concept Struct destination. Generated nominal lengths and positions+use a 0.1 mm authoring grid, with outward rounding for safety bounds. Numerical+`importTolerance` retains its separate accuracy; the rounded source is admitted+through normal build. `within` accepts one enclosing bounds+object or `[sourceBounds, destinationBounds]` for two separately proved local+regions. Two regions require line/circle support trim boundaries; there is+no swept travel corridor. The first family issame-size, Z-axis and between parallel planar supports. This first pinned revisionworkflow requires explicit `geometryOnly: true`; source annotation exclusion isreported, not silently assumed.@@ -1189,7 +1199,8 @@ STEP-based `view`/`verify` commands explicitly reject mesh-only outputs.### Inventory: organize module dependencies-Use a short `include "parts/bolt";` when shared declarations are convenient. For+Use `include bolt: Part = Step("vendor/bolt");` for a short typed resource+reference, or `include "parts/bolt";` when shared declarations are convenient. Forlarger compositions, give Part, Subassembly, Assembly and Scene dependencies typednames in an Inventory Record:@@ -1198,6 +1209,7 @@ Inventory Record Components {bracket: Part = Firmament("parts/bracket").Bracketdrive: Subassembly = Firmament("assemblies/drive").Drivebearing: Part = Step("vendor/bearing")+ gearbox: Assembly = Step("vendor/gearbox")}```@@ -1210,7 +1222,14 @@ named arguments at the occurrence. Definition-private names remain in the definimodule. Assembly and Scene entries currently import concrete exports.Inventory follows lexical scope and retains imported file identity. Existing-`include` remains the concise, unqualified composition form. See+untyped `include` remains the concise declaration-composition form. A typed+include follows the same reference rules as an Inventory member. STEP Assembly+imports retain product hierarchy and transforms; no implicit flattening occurs.+Optional `metadata:` selects an ordinary typed Static Record. An optional generated+`firmament.lock.toml` pins dependencies; existing locks are enforced without+automatic refresh. `InlineStep { from: Components.housing }` binds one STEP Part+for local annotation or surgery, with a lock-supplied or explicit source pin.+Use `geometryOnly: true` explicitly when excluding imported PMI. See[Inventory Records](inventory.md) for complete projects, source snapshots, STEPboundaries and extension resolution.diff --git a/docs/release/IMPORTED-FEATURE-ASSISTANCE-2026-10-21.md b/docs/release/IMPORTED-FEATURE-ASSISTANCE-2026-10-21.mdnew file mode 100644index 00000000..d23e2523--- /dev/null+++ b/docs/release/IMPORTED-FEATURE-ASSISTANCE-2026-10-21.md@@ -0,0 +1,158 @@+# Imported feature recovery assistance — 2026-10-21++## Contract++Agents can inspect an imported STEP, select a proved round through-hole from+measured facts, give it a semantic name and generate an executable Firmament+revision. This is bounded feature recovery, not reconstruction of the original+feature history. The existing production revision owner remains authoritative.++The [public workflow](../public/firmament/imported-feature-recognition.md) documents+CLI and SDK use. The [recovered CTC-01 fixture](../../fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmament)+is source evidence. Generated output and detailed logs remain ignored under+`artifacts/local/imported-feature-assistance/`.++## Decisions and ownership++- Reuse named `Region` as the semantic alias. CLI `--as MountHole` chooses that+ Region and replacement feature name; no additional Firmament keyword is needed.+- A Region's `candidate` selects an exact inspected handle, mutually exclusive+ with raw/sequential face selectors. Handles use sorted source wall entities,+ scoped to the explicit source pin. Stale IDs reject; there is no closest match.+- Discovery shares the production connected-wall traversal and recognition proof.+ Measured groups that fail recognition remain visible with reasons. Inspection+ is explicitly `InspectionOnly`; `CanPlan` requires family and import admission,+ but does not claim destination clearance.+- SDK `FirmamentImportedFeatures.Inspect` retains an immutable source snapshot.+ `PlanMove` derives local bounds, executes Core, emits ordinary Firmament and+ compiles it through normal build/export admission. File-backed planning rechecks+ the source pin through the existing loader.+- Destination intent is one named Concept Struct Point3. Generated destination+ bounds reference its components. Changing that point rechecks stock and collision+ admission, including failures, without duplicating absolute coordinates.+- `within` accepts either the existing single envelope or exactly two local bounds+ objects for suppression and reinsertion. No geometry is swept between them.+ Every unrelated boundary is excluded from both regions with import uncertainty.+ A separate destination must also be inside both trimmed support material domains+ (excluding only the hole being suppressed). The+ existing planar-domain owner handles line/circle outlines with an explicit+ chord-sag/endpoint-error bound; unresolved outlines and ambiguous probes refuse.+ It never uses display-oriented whole-body bounding boxes as containment proof.++## Motivating witness and safety++The CTC-01 upper-left diameter-25 hole moves from (-160,45,0) to (130,45,0) mm,+across the central boss. A single enclosing prism rejects on the intervening+boundaries; two local prisms admit the edit without modifying the boss.+The tests assert retained surfaces, 115 surviving faces and 312 surviving edges.+Existing production tests retain full residual bindings, topology, pcurves,+qualified STEP roundtrip and new diameter/depth semantic PMI associations.++An occupied destination and an entirely exterior destination both reject.+The latter exposed why boundary exclusion alone is insufficient for disconnected+regions; the new support-domain proof refuses before materialization rather than+relying on a later roundtrip failure. A separate synthetic STEP regression proves+that the full interior of an existing prismatic opening is excluded even when its+walls are outside a local probe. Tests also exercise exact candidate identity,+stale selectors, conflicting selection fields, malformed region lists and edited+named targets. Validate and build use the same compiler admission path.++Original STEP text is untouched. `textSha256` changes line endings only for the+explicit pin calculation; import consumes original text. CTC-01 still needs an+explicit .01 mm numerical import budget; strict .001 mm is not silently relaxed.+`geometryOnly: true` remains required and reported. New hole PMI is generated;+original vendor PMI is excluded, not claimed as preserved.++## Qualification++Final qualification passed:++| Check | Result |+| --- | --- |+| Full Release solution build | Passed; 0 errors, 34 warnings in existing code |+| Focused kernel revision cases | 10 passed |+| Existing production-owner harness | 8 passed: 3 accepted moves, 5 refusals |+| Fast kernel lane, excluding SlowCorpus | 1,088 passed |+| Complete solution lane, including corpus and editable V8 | 5,844 passed in 20 non-empty test assemblies; 0 failures/skips |+| Real CLI inspect → fact-based selection → plan → validate → build → analyze | Passed |+| Strict import inspection | Measured groups reported; 0 candidates admitted for planning at .001 mm |+| Exterior/occupied destination plans | Rejected; no new source file written |+| Golden source versus emitter | Identical except relative import path |+| Documentation local links / diff whitespace | Passed |++The CLI inspection reports 47 cylindrical groups, of which 8 pass current family+and import admission at .01 mm. Revised STEP analysis reports one enclosed+manifold body, 117 faces, 318 edges, 206 vertices and 636 pcurves. Build evidence+confirms replacement diameter PMI. The original STEP byte hash remains+`85a5752da05f53c456ca3a9e038c90358e1d5a3141d1f0d6e5f0970f2356e821`.+No source geometry was changed to obtain import qualification.++Reproduction lanes:++```shell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 -nr:false --filter "Category!=SlowCorpus" -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+```++The first full test run was deliberately superseded after strengthening the+trimmed-material containment proof; the reported total comes solely from the+complete final run. Superseded task-owned runtime hosts were stopped before+rebuilding. Existing nullable/obsolete/platform/trimming/WASM interop warnings+remain outside this change's scope. FrictionLab discovers no tests, as before.++## Engineering authoring precision follow-up++Generated nominal lengths and coordinates now round to a 0.1 mm grid, using+nearest-tenth rounding with midpoint ties away from zero. Bounds/padding round+outward, eliminating imported floating-point noise from editable source.+Negative zero is normalized. The new diameter and semantic PMI are genuinely+25 mm, and a requested X=130.04 mm is authored and built at X=130 mm.++This is authoring policy, not a change to kernel epsilon or a claim that the+source carried a particular manufacturing tolerance. Numerical import accuracy+still emits .01 mm where requested. The rounded program re-enters normal+admission; unsupported resizing or off-plane placement rejects. Original source+and residual geometry remain untouched. The recovered fixture is regenerated+through the real CLI, and its STEP/PMI witnesses verify the rounded values.++Follow-up qualification passed: full Release solution build (0 errors, 25 warnings+in existing code), the focused rounding/STEP/PMI regression, the 1,088-test fast+lane and all 5,844 solution tests across 20 non-empty assemblies, with no failures+or skips. The real CLI regenerated the fixture, validated, built and analyzed the+rounded revision. It retained 115 faces and 312 edges and emitted nominal 25 mm+hole PMI. Logs and artifacts are under `artifacts/local/imported-feature-rounding/`.++Code review confirmed that rounding belongs to authoring/emission, while ordinary+compiler admission and numerical import qualification retain their existing+contracts. No kernel accuracy threshold or general formatter was relaxed.++## Code-quality review++Recognition traversal and legality remain shared with Core execution. Validate,+build and generated plans use the ordinary compiler owner. The change adds no+whole-document parser, rewrite pass, error-code fatality allowlist, alternate+geometry engine, global parser state or product-specific validation path.+The planar containment query explicitly refuses unavailable evidence rather than+using display bounds. CLI failures use the existing diagnostic presentation owner.+New output defaults to ignored local artifacts; only the durable source witness+and compact documentation are added for review.++## Verdict++**Success for the bounded recovery-assistance slice.** A candidate chosen from+measured geometry becomes a named, pinned, executable Firmament revision. Both+its acceptance and refusal go through the existing production owner. Geometry,+provenance and annotation boundaries remain explicit.++## Remaining limits++One isolated same-size Z-axis round through-hole between two planar supports in+one qualified body. No resizing, arbitrary frames, counterbores/countersinks,+blind/intersecting/blended/threaded families, multiple atomic edits, vendor PMI+migration or UI editing. Separate local regions currently require line/circle+support trim boundaries with a resolvable containment probe. Other producers need their+own qualification; this fixture is not universal imported-feature certification.++The next useful expansion is qualification against more independent STEP+producers and bounded families, retaining exact selection and refusal evidence.diff --git a/docs/release/IMPORTED-RESOURCE-MODULES-2026-10-21.md b/docs/release/IMPORTED-RESOURCE-MODULES-2026-10-21.mdnew file mode 100644index 00000000..c43cd9af--- /dev/null+++ b/docs/release/IMPORTED-RESOURCE-MODULES-2026-10-21.md@@ -0,0 +1,202 @@+# Imported resources, metadata and dependency locks++Date: 2026-10-21++## Result++**Success.** The real module, snapshot and CLI paths admit the new import forms,+enforce optional dependency receipts, and preserve the qualified geometry. The+complete final solution lane passed after the root-identity hardening.++This pass separates product composition from local imported-body editing. Typed+short includes and Inventory members share the existing AST module graph. No+new whole-document parser, source macro system, geometry strategy or UI validator+was introduced.++## Authoring decisions++- `include bearing: Part = Step("vendor/bearing");` is the short named form.+ `Inventory Record Components { bearing: Part = Step("vendor/bearing") }` is the+ organized catalog form. Native `Firmament("path").Export` supports both.+- Part, Subassembly, Assembly and Scene remain product/module kinds. An import+ alone does not create an occurrence, placement or mate.+- `Part = Step(...)` consumes one body. `Assembly = Step(...)` explicitly requests+ product structure, retaining occurrence hierarchy, local transforms and shared+ leaf geometry. Ambiguous multiplicity-to-flat-assembly fallback rejects here.+- `InlineStep` is the local annotation/surgery binding. `from: Components.part`+ selects a STEP Part; `path` remains compatible. Both fields together reject.+ A hash is source identity, not an instruction to perform surgery: an unchanged+ qualified pinned body now re-exports without a fictitious replacement.+- The conventional optional receipt is `firmament.lock.toml`, one compilation+ root per sidecar. Ordinary compilation without a receipt remains supported.+ An existing receipt is enforced; `validate/build --locked` require it.+ Compilation never refreshes it. `aetheris lock root.firmasm [--update]` writes it.+- Locks contain dependency identity only. STEP is hashed as exact bytes;+ Firmament source as decoded UTF-8 text. Import tolerance and explicit source-PMI+ exclusion remain authoring policy. A changed STEP used by Recognize/Replace/+ Remove refuses even an explicit refresh; reinspect and bind a reviewed revision.+- Existing `sha256` and normalized `textSha256` remain compatible. CLI recovery+ now emits hash-free source plus a generated lock, then compiles that saved pair.+ A failed qualification restores previous output source and receipt. The SDK's+ source-only plan keeps its explicit text pin for existing consumers.+- `metadata:` selects an ordinary typed Static Record. There is no parallel+ metadata field schema. Import receipts retain type/flattened fields separately+ from geometry identity. They do not invent materials, fits, PMI or vendor AP242+ properties.+- Assembly `provenance: Release;` now uses the ordinary Record binder. Canonical+ release fields use camelCase. Nested author Records are supported via their+ `name: String`; legacy PascalCase fields retain compatibility. Supplied author,+ dates, version, description and extra typed metadata remain inspectable.+- `.firmasm` can contain modern textual Assembly DSL. The extension alone is not+ a V1 marker; existing explicit JSON assembly compatibility is unchanged.++## Ownership and diagnostics++The unified syntax parser owns the typed include production. A short include is+adapted to the same Inventory binding operation in memory, not a second resource+resolver. The existing module graph owns dependency resolution, source snapshots,+locks, asset hashes and InlineStep reference projection. Core STEP import owns+BRep admission and product-structure interpretation. Imported assemblies reuse+the existing hierarchy transport with retained BReps, without temporary STEP parts.++Snapshot compilation now consumes supplied `.step`/`.stp` text and lock documents.+It never reads a missing resource from the host filesystem. File-backed import+hashes and import text come from the same byte snapshot. Existing parse caching+is bypassed for import-dependent sources.++New source/resource failures retain stable codes, severity and readable messages.+Lock CLI failures use the existing structured frontend diagnostic record. AST+locations point at the authored import or field; lock-wide mismatches identify+the lock document. Generated STEP hierarchy failures identify the enclosing import+and disclose the absence of an authored Firmament span. Existing downstream+engineering adapters still use enclosing Part locations where exact provenance+is unavailable.++Imported PMI passthrough remains unqualified. New Step bindings reject detected+annotation families unless `geometryOnly: true` explicitly excludes them. The+receipt retains that decision. InlineStep keeps its stricter explicit exclusion+contract for foreign pinned inputs, and reports exclusion. Original files remain+untouched. New annotations still follow the existing explicit PMI owner.++TOML uses Tomlyn 2.10.1 rather than a new hand-written configuration parser.+Unknown keys, malformed receipts, wrong roots, missing entries and mismatched+hashes reject. Empty dependency sets are admitted. Unused old entries are allowed+until an explicit lock command prunes them.++## Regression classification++The first complete run exposed historical negative-test expectations, not accepted+geometry differences:++| Specimen | Former assertion | Current contract |+| --- | --- | --- |+| Missing include in standalone file compilation | Includes unsupported | Includes resolve through the module graph; missing file rejects at the original directive |+| Snapshot ExternalStep with `C:/secret.step` | All STEP resources unsupported | Provided text assets are supported; absolute/root-escaping paths still reject before disk access |+| Imported Part snapshot with absolute InlineStep path | All InlineStep unsupported | Invalid path rejects at the original imported file |+| Pinned source with no replacement | Pin implies mandatory surgery | Unchanged qualified body can re-export; actual surgery still uses its bounded owner |++The original failing source specimens were retained. Tests now assert the correct+owner's rejection, without converting missing resources or invalid paths into+success. The old malformed `file:` field in the filesystem-leak test was replaced+with the legitimate `path:` field so the test exercises path isolation itself.++## Qualification evidence++Run-local logs and generated artifacts: `artifacts/local/imported-resource-modules/`.+Recovery CLI witnesses also use `artifacts/local/imported-feature-assistance/tests/`.++Commands:++```powershell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 -nr:false --filter "Category!=SlowCorpus" -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+```++Focused evidence covers typed include/catalog equivalence, shared geometry+identities, nested STEP transforms, AP242 re-import, explicit annotation exclusion,+snapshot lock presence/mismatch/root/unknown fields, InlineStep path/direct/catalog+bindings without authored hashes, and metadata-only geometry parity. Real CLI+tests generate receipts, validate/build with `--locked`, demonstrate stale-source+refusal, and prove that a hash update cannot rebind CTC-01 surgery.++Manual CLI witness:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll lock artifacts/local/imported-resource-modules/witness/revision.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate artifacts/local/imported-resource-modules/witness/revision.firmament --locked --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build artifacts/local/imported-resource-modules/witness/revision.firmament --locked --output artifacts/local/imported-resource-modules/witness/revised.step --json+```++This source combines an Inventory STEP Part, typed `ImportedAssetInfo` metadata,+`InlineStep from: Components.ctc`, and the bounded CTC-01 recovered-hole revision.+It contains no authored source hash. Validation reports `Built` / `UnifiedMechanical`+/ `V2`. Build retains 115 faces and 312 edges, with diameter 25 mm, depth 50 mm and+the expected two local safety regions. The exact-byte source receipt is+`85a5752da05f53c456ca3a9e038c90358e1d5a3141d1f0d6e5f0970f2356e821`.++The new witness and the separately qualified source-only recovery CLI specimen+emit byte-identical STEP:+`9841594caec194ae1e349476da20b54178190697cf95455e1576ce1c36541863`.+Resource organization and metadata did not change that engineering artifact.++Final qualification:++| Lane | Result |+| --- | --- |+| Release solution build, including WASM runtime | Passed, 0 errors; existing nullable and SQLite WASM import warnings remain |+| Core fast lane | 1,088 passed |+| Final focused resource/directive/snapshot checks | 35 passed |+| Focused CLI lock/recovery/directive checks | 8 passed |+| Final full solution | 5,855 passed, 0 failed, 0 skipped across 20 nonempty test assemblies |+| Full Core corpus | 1,230 passed, included in full total |+| Full Firmament suite | 3,104 passed, included in full total |+| Editable V8 | 7 passed, included in full total |+| CTC-01 CLI witness | Locked validation at Built, successful export, byte-identical STEP parity |+| Diff whitespace check | Passed |++`Aetheris.FrictionLab.Tests` reports no discoverable tests; it contributes no+tests to the total. The canonical fixture, assembly, sheet-metal, interchange,+PMI and scene coverage in the complete lane remained green, including the+Guitar provenance/geometry tests. No test source was rewritten to conceal a+geometry difference. The historical diagnostic reclassifications above and the+empty-lock serialization repair are the explicit qualification changes.++## Code-quality review++Imports, receipts and InlineStep reference binding reuse one module dependency+owner. Metadata uses ordinary Record checking. New frontend work adds no regex+dispatch or broad text rewrite; source projection uses existing AST spans. Root+identity availability is an explicit context flag, not a magic-filename exemption.+A real file named `__provided_source.firmament` still receives normal root checks.+No global mutable lock or resource state was introduced. The compiler's existing+engineering lowerers and kernel planners retain their authority.++Build/test lanes ran serially with shared compilation and node reuse disabled.+The large Firmament test host was observed around 1.9–2.56 GB during corpus+execution and exited between lanes. Final process inspection found no remaining+dotnet, testhost, MSBuild or VBCSCompiler hosts. This is bounded run evidence,+not a general memory-leak proof.++## Explicit boundaries++- No general source-PMI migration, foreign mate recovery or imported modeling+ history reconstruction. Non-leaf foreign product-definition entity IDs are not+ promised as an AP242 byte-for-byte roundtrip contract.+- STEP snapshot text has UTF-8 byte identity; arbitrary original byte encodings+ and BOMs require byte-identical representation or file-backed compilation.+ Portable committed locks require stable dependency encoding/line endings.+- One conventional sidecar per root. Custom lock paths and composition of several+ independently locked workspace roots are not implemented. Directory-only+ `CompileSource` has no real root-document identity; exact root checks use the+ file/project entry points. Its STEP identity is still checked.+- Native concrete Parts with other file-only adapters retain their explicit+ unsupported snapshot-context diagnostic. This pass does not invent context for+ every future external format.+- Import metadata is retained in compiler receipts; automatic arbitrary-vendor+ AP242 property projection is not claimed. The qualified Assembly release+ header/annotation path is separate.+- .NET snapshot and CLI qualification plus WASM compilation do not constitute+ browser interaction or multi-file persistence qualification.++No new user decision is required for these bounded defaults.diff --git a/fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmament b/fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmamentnew file mode 100644index 00000000..37ca50c2--- /dev/null+++ b/fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmament@@ -0,0 +1,30 @@+// Recovery proves the admitted feature family, not the original modeling history.+// Authored lengths use a 0.1mm grid; numerical import accuracy is separate.+Model ImportedRevision {+ units: mm+ Concept Struct RevisionLayout {+ Points<Point3> Targets { MountHole: Point3(130mm, 45mm, 0mm); }+ }+ InlineStep Source {+ path: "../../../../testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"+ textSha256: "341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745"+ importTolerance: 0.01mm+ geometryOnly: true+ }+ Recognize Source {+ Region MountHole {+ kind: HoleShaft+ candidate: "through-hole:step-764+765"+ }+ }+ Replace Source.MountHole with Hole<Shaft> MountHole {+ on: Source.Face("#861")+ center: RevisionLayout.Targets.MountHole+ diameter: 25mm+ end: ThroughAll+ within: [+ { min: Point3(-172.6mm, 32.4mm, -50mm); max: Point3(-147.4mm, 57.6mm, 0mm) },+ { min: Point3(RevisionLayout.Targets.MountHole.X - 12.6mm, RevisionLayout.Targets.MountHole.Y - 12.6mm, -50mm); max: Point3(RevisionLayout.Targets.MountHole.X + 12.6mm, RevisionLayout.Targets.MountHole.Y + 12.6mm, 0mm) }+ ]+ }+}