Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add language completion and selector candidate APIs

Yuechen Li372daf43841e
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs
new file mode 100644
index 00000000..f62e3689
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs
@@ -0,0 +1,42 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentLanguageServiceTests
+{
+ [Fact]
+ public void IncompleteHelix_OffersOwnerFieldsAndMissingRequiredFields()
+ {
+ const string source = "Model M { WireForm Spring { Helix Winding {\n Rad";
+ var result = FirmamentLanguageService.Complete(source, "spring.firmament", "draft-7", source.Length);
+ Assert.Equal("draft-7", result.Revision);
+ Assert.Equal("Helix", result.Context);
+ Assert.Equal("Rad", source.Substring(result.ReplaceStart, result.ReplaceLength));
+ var radius = Assert.Single(result.Fields);
+ Assert.Equal("Radius", radius.Name);
+ Assert.Equal("Length", radius.Type);
+ Assert.Contains("Radius", result.MissingRequiredFields);
+ Assert.Contains("Turns", result.MissingRequiredFields);
+ Assert.Contains("Pitch or Height", result.MissingRequiredFields);
+ }
+
+ [Fact]
+ public void LoftFields_UseParserAdmissionAndDoNotRepeatPresentFields()
+ {
+ const string source = "Model M { Loft<Hollow> Body {\nRearProfile: Rear\n ";
+ var result = FirmamentLanguageService.Complete(source, "loft.firmament", "1", source.Length);
+ Assert.Equal("Loft", result.Context);
+ Assert.DoesNotContain(result.Fields, field => field.Name == "RearProfile");
+ Assert.Contains(result.Fields, field => field.Name == "Thickness" && field.Required && field.Type == "Length");
+ Assert.Contains(result.Fields, field => field.Name == "Rule" && field.Choices!.SequenceEqual(["Ruled"]));
+ }
+
+ [Fact]
+ public void ValuePosition_DoesNotOfferFieldNames()
+ {
+ const string source = "Helix Winding {\n Radius: ";
+ var result = FirmamentLanguageService.Complete(source, "draft.firmament", "2", source.Length);
+ Assert.Equal("Value", result.Context);
+ Assert.Empty(result.Fields);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs
new file mode 100644
index 00000000..ac81213a
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs
@@ -0,0 +1,6 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>Compiler-owned, JSON-safe field help for a bounded authoring construct.</summary>
+public sealed record FirmamentAuthoringField(
+ string Name, string Type, bool Required, string Meaning,
+ string? Default = null, IReadOnlyList<string>? Choices = null);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs
new file mode 100644
index 00000000..9bec47f5
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs
@@ -0,0 +1,44 @@
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record FirmamentLanguageCompletion(
+ string Document, string Revision, string Context, int ReplaceStart, int ReplaceLength,
+ IReadOnlyList<FirmamentAuthoringField> Fields,
+ IReadOnlyList<string> MissingRequiredFields);
+
+/// <summary>Bounded authoring help from construct owners; no BRep or export work.</summary>
+public static class FirmamentLanguageService
+{
+ public static FirmamentLanguageCompletion Complete(string source, string document, string revision, int offset)
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ if (offset < 0 || offset > source.Length) throw new ArgumentOutOfRangeException(nameof(offset));
+ var prefixStart = offset;
+ while (prefixStart > 0 && (char.IsLetterOrDigit(source[prefixStart - 1]) || source[prefixStart - 1] == '_')) prefixStart--;
+ var prefix = source[prefixStart..offset];
+ var lineStart = prefixStart == 0 ? 0 : source.LastIndexOf('\n', prefixStart - 1) + 1;
+ var beforePrefix = source[lineStart..prefixStart];
+ if (beforePrefix.Contains(':')) return new(document, revision, "Value", prefixStart, prefix.Length, [], []);
+
+ IReadOnlyList<FirmamentAuthoringField> fields;
+ string context;
+ if (WireFormAuthoring.IsInsideHelix(source, offset))
+ {
+ fields = WireFormAuthoring.HelixFields;
+ context = "Helix";
+ }
+ else if (LoftAuthoringParser.TryGetAuthoringFields(source, offset, out fields)) context = "Loft";
+ else return new(document, revision, "Unsupported", prefixStart, prefix.Length, [], []);
+
+ var open = source.LastIndexOf('{', Math.Max(0, offset - 1));
+ var body = open >= 0 ? source[(open + 1)..offset] : string.Empty;
+ var present = fields.Where(field => Regex.IsMatch(body, $@"\b{Regex.Escape(field.Name)}\s*:", RegexOptions.CultureInvariant))
+ .Select(field => field.Name).ToHashSet(StringComparer.Ordinal);
+ var candidates = fields.Where(field => !present.Contains(field.Name) && field.Name.StartsWith(prefix, StringComparison.Ordinal)).ToArray();
+ var missing = fields.Where(field => field.Required && !present.Contains(field.Name)).Select(field => field.Name).ToList();
+ if (context == "Helix" && !present.Contains("Pitch") && !present.Contains("Height")) missing.Add("Pitch or Height");
+ return new(document, revision, context, prefixStart, prefix.Length, candidates, missing);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs
index 3cb829d1..15808963 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs
@@ -16,6 +16,37 @@ public static class LoftAuthoringParser
{
private static readonly Regex Header = new(@"\bLoft(?:\s*<\s*(?<kind>Hollow)\s*>)?\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ public static readonly IReadOnlyList<FirmamentAuthoringField> SolidFields =
+ [
+ new("RearProfile", "Profile", true, "Closed rear section profile."),
+ new("RearFrame", "ConstructionPlane", true, "Placement of the rear section."),
+ new("FrontProfile", "Profile", true, "Closed front section profile."),
+ new("FrontFrame", "ConstructionPlane", true, "Placement of the front section."),
+ new("Rule", "Enum", true, "Section interpolation rule.", null, ["Ruled"]),
+ new("Correspondence", "Enum", true, "Point correspondence between sections.", null, ["CommonRay"]),
+ new("Reference", "Vector3", false, "Reference ray for section correspondence."),
+ new("Twist", "Angle", false, "Relative section rotation.", "0deg")
+ ];
+ public static readonly IReadOnlyList<FirmamentAuthoringField> HollowFields =
+ [.. SolidFields,
+ new("Thickness", "Length", true, "Hollow wall thickness."),
+ new("SeamGap", "Angle", false, "Angular seam clearance.", "0.1deg")];
+
+ public static bool TryGetAuthoringFields(string source, int offset, out IReadOnlyList<FirmamentAuthoringField> fields)
+ {
+ fields = [];
+ foreach (Match match in Header.Matches(source))
+ {
+ var open = match.Index + match.Length - 1;
+ if (offset <= open) continue;
+ var close = MatchingBrace(source, open);
+ if (close >= 0 && offset > close) continue;
+ fields = match.Groups["kind"].Success ? HollowFields : SolidFields;
+ return true;
+ }
+ return false;
+ }
+
public static bool IsLoftSource(string source) => Header.IsMatch(source);
public static SectionChainAuthoringResult Compile(string source, bool materialize = true)
@@ -37,12 +68,7 @@ public static class LoftAuthoringParser
var body = source[(open + 1)..close];
var name = declaration.Groups["name"].Value;
var hollow = declaration.Groups["kind"].Success;
- var allowed = new HashSet<string>(StringComparer.Ordinal)
- {
- "RearProfile", "RearFrame", "FrontProfile", "FrontFrame", "Rule",
- "Correspondence", "Reference", "Twist"
- };
- if (hollow) { allowed.Add("Thickness"); allowed.Add("SeamGap"); }
+ var allowed = (hollow ? HollowFields : SolidFields).Select(field => field.Name).ToHashSet(StringComparer.Ordinal);
var fields = Regex.Matches(body, @"(?m)^\s*(?<key>[A-Za-z_]\w*)\s*:", RegexOptions.CultureInvariant)
.Cast<Match>().Select(match => match.Groups["key"].Value).ToArray();
foreach (var field in fields.Where(field => !allowed.Contains(field)))
diff --git a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs b/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs
index bef5084b..4066b2d7 100644
--- a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs
@@ -7,18 +7,35 @@ using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.Kernel.Firmament.Materializer;
internal static class WireCoilAuthoring
{
+ private const string RadiusField = "Radius";
+ private const string TurnsField = "Turns";
+ private const string PitchField = "Pitch";
+ private const string HeightField = "Height";
+ private const string HandednessField = "Handedness";
+ private const string StartPhaseField = "StartPhase";
+ // This is the same bounded Axis/Helix contract consumed by CreateAxis below.
+ internal static readonly IReadOnlyList<FirmamentAuthoringField> AxisFields =
+ [
+ new(RadiusField, "Length", true, "Centerline radius."),
+ new(TurnsField, "Scalar", true, "Number of complete winding turns."),
+ new(PitchField, "Length", false, "Axial distance per turn. Supply Pitch or Height."),
+ new(HeightField, "Length", false, "Total axial span. Supply Height or Pitch."),
+ new(HandednessField, "Enum", false, "Winding direction.", "RightHanded", ["RightHanded", "LeftHanded"]),
+ new(StartPhaseField, "Angle", false, "Rotation of the starting radial frame.", "0deg")
+ ];
private const double ApproximationTolerance = 0.01d;
internal static KernelResult<WireAxisCoilAir> CreateAxis(string name, int ordinal, string body, WireState input, double diameter)
{
- if (!Length(body, "Radius", out var radius) || radius <= 0d) return FailAxis("wireform-coil-radius-invalid", name, "Radius must be finite and greater than zero.");
- if (!Number(body, "Turns", out var turns) || turns <= 0d) return FailAxis("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");
- var hasPitch = Length(body, "Pitch", out var pitch); var hasHeight = Length(body, "Height", out var height);
+ if (!Length(body, RadiusField, out var radius) || radius <= 0d) return FailAxis("wireform-coil-radius-invalid", name, "Radius must be finite and greater than zero.");
+ if (!Number(body, TurnsField, out var turns) || turns <= 0d) return FailAxis("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");
+ var hasPitch = Length(body, PitchField, out var pitch); var hasHeight = Length(body, HeightField, out var height);
if (!hasPitch && !hasHeight) return FailAxis("wireform-coil-parameters-inconsistent", name, "Specify Turns and either Pitch or Height.");
if (hasPitch && pitch <= 0d || hasHeight && height <= 0d) return FailAxis("wireform-coil-parameters-inconsistent", name, "Pitch and Height must be greater than zero.");
if (!hasPitch) pitch = height / turns; else if (!hasHeight) height = pitch * turns;
@@ -134,8 +151,8 @@ internal static class WireCoilAuthoring
private static bool Length(string body, string name, out double value) => WireFormAuthoring.TryLength(WireFormAuthoring.Property(body, name), out value);
private static bool Angle(string body, string name, out double value) => WireFormAuthoring.TryAngle(WireFormAuthoring.Property(body, name), out value);
private static bool Number(string body, string name, out double value) => double.TryParse(WireFormAuthoring.Property(body, name), NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
- private static bool Hand(string body, out WireCoilHandedness hand) => Enum.TryParse(WireFormAuthoring.Property(body, "Handedness") ?? "RightHanded", false, out hand);
- private static bool Phase(string body, out double phase) { var text = WireFormAuthoring.Property(body, "StartPhase"); if (text is null) { phase = 0d; return true; } return WireFormAuthoring.TryAngle(text, out phase); }
+ private static bool Hand(string body, out WireCoilHandedness hand) => Enum.TryParse(WireFormAuthoring.Property(body, HandednessField) ?? "RightHanded", false, out hand);
+ private static bool Phase(string body, out double phase) { var text = WireFormAuthoring.Property(body, StartPhaseField); if (text is null) { phase = 0d; return true; } return WireFormAuthoring.TryAngle(text, out phase); }
private static int MatchingBrace(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }
private static Vector3D Rotate(Vector3D v, Vector3D a, double angle) => v * Math.Cos(angle) + WireFormAuthoring.Cross(a, v) * Math.Sin(angle) + a * (WireFormAuthoring.Dot(a, v) * (1d - Math.Cos(angle)));
private static KernelResult<WireAxisCoilAir> FailAxis(string code, string name, string message) => KernelResult<WireAxisCoilAir>.Failure([Diagnostic($"{code}:{name}: {message}")]);
diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
index 2b7f9c37..153493b4 100644
--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
@@ -8,6 +8,7 @@ using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Numerics;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.StandardLibrary.Materials;
namespace Aetheris.Kernel.Firmament.Materializer;
@@ -108,6 +109,28 @@ public static class WireFormAuthoring
private static readonly Regex Declaration = new(@"\bWireForm\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex Operation = new(@"\b(?<kind>Straight|Bend|Helix|AxisCoil|SurfaceCoil|Coil|Knot)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ public static IReadOnlyList<FirmamentAuthoringField> HelixFields => WireCoilAuthoring.AxisFields;
+
+ public static bool IsInsideHelix(string source, int offset)
+ {
+ foreach (Match wireForm in Declaration.Matches(source))
+ {
+ var wireOpen = wireForm.Index + wireForm.Length - 1;
+ var wireClose = MatchingBrace(source, wireOpen);
+ if (offset <= wireOpen || wireClose >= 0 && offset > wireClose) continue;
+ foreach (Match match in Operation.Matches(source))
+ {
+ if (match.Groups["kind"].Value != "Helix") continue;
+ var open = match.Index + match.Length - 1;
+ if (open <= wireOpen || wireClose >= 0 && open >= wireClose) continue;
+ if (offset <= open) continue;
+ var close = MatchingBrace(source, open);
+ if (close < 0 || offset <= close) return true;
+ }
+ }
+ return false;
+ }
+
public static bool IsWireFormSource(string source) => Declaration.IsMatch(source);
public static KernelResult<WireFormFeatureAir> Parse(string source)
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index ecaa955d..87889789 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -10,6 +10,7 @@ using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament;
using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.Web.Runtime;
@@ -33,6 +34,7 @@ public static partial class Program
{
"info" => Info(),
"compile" => Compile(request),
+ "languageComplete" => LanguageComplete(request),
"snapshot" => Session(request).Snapshot,
"setProperty" => SetProperty(request),
"setSource" => SetSource(request),
@@ -80,6 +82,14 @@ public static partial class Program
return result;
}
+ private static object LanguageComplete(WebRequest request)
+ {
+ if (request.Source is null || request.Offset is null || string.IsNullOrWhiteSpace(request.SourceRevision))
+ throw new WebRuntimeException("language-input-required", "languageComplete requires source, offset, and sourceRevision.");
+ return FirmamentLanguageService.Complete(request.Source, request.SourceName ?? "model.firmament",
+ request.SourceRevision, request.Offset.Value);
+ }
+
private static object SetProperty(WebRequest request)
{
var session = Session(request);
@@ -123,7 +133,8 @@ public static partial class Program
? session : throw new WebRuntimeException("session-not-found", "The model session was disposed or does not exist.");
private sealed record WebRequest(string Operation, string? SessionId = null, string? Source = null,
- string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null);
+ string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null,
+ string? SourceRevision = null, int? Offset = null);
private sealed class WebRuntimeException(string code, string message) : Exception(message)
{
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index b6975dcf..02ad153a 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -19,11 +19,16 @@ export interface RuntimeCapabilities { readonly compile: boolean; readonly solid
export interface RuntimeInfo { readonly packageVersion: string; readonly runtimeVersion: string; readonly contractVersion: 'aetheris/web-editor-contract/1'; readonly language: 'Firmament'; readonly capabilities: RuntimeCapabilities }
export interface OperationOptions { readonly signal?: AbortSignal }
export interface CompileOptions extends OperationOptions { readonly sourceName?: string }
+export interface LanguageOptions { readonly sourceName?: string; readonly sourceRevision: string }
+export interface LanguageField { readonly name: string; readonly type: string; readonly required: boolean; readonly meaning: string; readonly default?: string | null; readonly choices?: readonly string[] | null }
+export interface LanguageCompletion { readonly document: string; readonly revision: string; readonly context: string; readonly replaceStart: number; readonly replaceLength: number; readonly fields: readonly LanguageField[]; readonly missingRequiredFields: readonly string[] }
+export interface SelectorCandidate { readonly selector: string; readonly kind: string; readonly semanticKey: string | null; readonly outputRole: string | null; readonly source: SourceReference; readonly qualification: SourceAddressability; readonly buildRevision: number }
export interface AetherisOptions { readonly worker?: boolean; readonly wasmUrl?: string | URL; readonly diagnostics?: (diagnostics: readonly Diagnostic[]) => void }
export class AetherisError extends Error { readonly code: string; readonly details?: string }
export class Aetheris {
static create(options?: AetherisOptions): Promise<Aetheris>;
readonly runtimeInfo: RuntimeInfo;
+ readonly language: { complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion> };
info(): Promise<RuntimeInfo>;
capabilities(): Promise<RuntimeCapabilities>;
compile(source: string, options?: CompileOptions): Promise<{ model: ModelSession | null; diagnostics: readonly Diagnostic[] }>;
@@ -44,6 +49,7 @@ export class ModelSession {
selectionForSourceSymbol(symbol: string): readonly ({ definitionId: string } & MeshRange)[];
selectionForEntity(entityId: string): { occurrenceIds: readonly string[]; ranges: readonly ({ definitionId: string } & MeshRange)[] };
geometrySourceMap(): readonly { definitionId: string; topologyId: string; topologyKind: string; semanticKey: string | null; outputRole: string | null; originFeature: string | null; source: SourceReference | null; selector: string | null; qualification: SourceAddressability; buildRevision: number }[];
+ selectorCandidates(kind?: 'Face' | 'Edge'): readonly SelectorCandidate[];
exportSTEP(options?: OperationOptions): Promise<Uint8Array>;
exportSTEPBlob(options?: OperationOptions): Promise<Blob>;
dispose(): Promise<void>;
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index f6e3386e..93ebb855 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -53,7 +53,13 @@ export class Aetheris {
cad.runtimeInfo = await cad.info();
return cad;
}
- constructor(transport, diagnostics) { this.transport = transport; this.diagnostics = diagnostics; }
+ constructor(transport, diagnostics) {
+ this.transport = transport; this.diagnostics = diagnostics;
+ this.language = {
+ complete: (source, offset, options = {}) => this.transport.request({ operation: 'languageComplete', source, offset,
+ sourceName: options.sourceName, sourceRevision: options.sourceRevision })
+ };
+ }
info() { return this.transport.request({ operation: 'info' }); }
async capabilities() { return (await this.info()).capabilities; }
async compile(source, options = {}) {
@@ -147,6 +153,19 @@ export class ModelSession {
return { occurrenceIds, ranges };
}
geometrySourceMap() { return this._geometrySourceMap; }
+ selectorCandidates(kind = 'Face') {
+ const admitted = new Set(['AuthoredStable', 'DerivedStable', 'ImportedStable']);
+ const seen = new Set();
+ return this._geometrySourceMap.filter(item => {
+ if (item.topologyKind !== kind || !item.selector || !item.source || !admitted.has(item.qualification)) return false;
+ const key = `${item.selector}\u0000${item.semanticKey ?? ''}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ }).map(item => ({ selector: item.selector, kind: item.topologyKind, semanticKey: item.semanticKey,
+ outputRole: item.outputRole, source: item.source, qualification: item.qualification, buildRevision: item.buildRevision }))
+ .sort((a, b) => a.selector < b.selector ? -1 : a.selector > b.selector ? 1 : 0);
+ }
async exportSTEP(options = {}) {
throwIfAborted(options.signal);
const result = await this.transport.request({ operation: 'exportStep', sessionId: this.id });
diff --git a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs
new file mode 100644
index 00000000..424e9551
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs
@@ -0,0 +1,17 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { Aetheris } from '../src/index.js';
+
+test('public language completion sends source revision and offset through runtime transport', async () => {
+ const requests = [];
+ const cad = new Aetheris({ request: async request => {
+ requests.push(request);
+ return { document: request.sourceName, revision: request.sourceRevision, context: 'Helix',
+ replaceStart: request.offset - 3, replaceLength: 3, fields: [], missingRequiredFields: [] };
+ } });
+ const result = await cad.language.complete('Helix H { Rad', 13,
+ { sourceName: 'spring.firmament', sourceRevision: 'draft-3' });
+ assert.equal(result.revision, 'draft-3');
+ assert.deepEqual(requests, [{ operation: 'languageComplete', source: 'Helix H { Rad', offset: 13,
+ sourceName: 'spring.firmament', sourceRevision: 'draft-3' }]);
+});
diff --git a/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs b/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
index 54e7d793..be30f82f 100644
--- a/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
+++ b/Aetheris.Web.Runtime/sdk/tests/selection.test.mjs
@@ -17,6 +17,7 @@ test('display-only face identity never becomes a Firmament selector', () => {
assert.equal(selection.sourceAddressability, 'RuntimeOnly');
assert.equal(selection.selectorReason, 'No authored topology mapping');
assert.equal(session.describeSelection('definition', 2, 'occurrence'), null);
+ assert.deepEqual(session.selectorCandidates(), []);
});
test('construction-owned face identity reaches picking and reverse source lookup', () => {
@@ -39,6 +40,7 @@ test('construction-owned face identity reaches picking and reverse source lookup
assert.equal(session.selectionForSourceSymbol('Body').length, 1);
assert.equal(session.geometrySourceMap()[0].semanticKey, 'Body.face(+Z)');
assert.equal(session.geometrySourceMap()[0].source.start, 32);
+ assert.deepEqual(session.selectorCandidates().map(item => item.selector), ['face(+Z)']);
});
test('BRep edges preserve construction metadata without inventing source selectors', () => {
@@ -75,4 +77,5 @@ test('a feature face keeps its owner inside a body occurrence', () => {
assert.equal(picked.selector, 'face(H.Wall)');
assert.deepEqual(picked.source, source);
assert.equal(session.selectionForEntity('Body.H').ranges.length, 1);
+ assert.deepEqual(session.selectorCandidates().map(item => item.selector), ['face(H.Wall)']);
});
diff --git a/docs/public/web-sdk/api-reference.md b/docs/public/web-sdk/api-reference.md
index 80cdc102..0f645398 100644
--- a/docs/public/web-sdk/api-reference.md
+++ b/docs/public/web-sdk/api-reference.md
@@ -5,12 +5,14 @@ The stable preview contract is `aetheris/web-editor-contract/1`.
- `Aetheris.create(options?)` initializes the runtime. Options: `worker` (only `false`/omitted in X1), `wasmUrl`, and a diagnostics callback.
- `cad.info()` and `cad.capabilities()` report package/runtime/contract versions and support flags.
- `cad.compile(source, { sourceName?, signal? })` returns `{ model, diagnostics }`; compiler failures are values, not thrown private exceptions.
+- `cad.language.complete(source, offset, { sourceName?, sourceRevision })` returns bounded partial-source field help for Helix and Loft. The caller must provide a nonempty revision token. The JSON-safe result contains `document`, `revision`, `context`, `replaceStart`, `replaceLength`, `fields`, and `missingRequiredFields`. Each field has `name`, `type`, `required`, `meaning`, optional `default`, and optional `choices`. Unsupported contexts return no fields. This operation does not build geometry.
- `model.tree`, `properties`, `mesh`, `diagnostics`, `revision`, and `changes` are the current valid snapshot.
- `model.entity(id)` and `model.property(id)` inspect public records.
- `model.setProperty(id, { value, unit })` validates and rebuilds a source-backed scalar property.
- `model.setSource(source)` replaces source and rebuilds transactionally.
- `model.rebuild()` rebuilds the current source plus overrides.
- `model.resolveSelection(...)` and `selectionForEntity(...)` translate selection in both directions.
+- `model.selectorCandidates('Face' | 'Edge')` returns source-addressable selectors from the compiled geometry source map. Candidates carry the source reference, semantic key, output role, qualification, and build revision. Runtime-only, unstable, ambiguous, and selector-less topology is excluded. The candidates describe the last valid compiled snapshot, so an editor must not apply them to a different source revision.
- `model.exportSTEP()` returns `Uint8Array`; `exportSTEPBlob()` returns a browser `Blob`.
- `model.dispose()` and `cad.dispose()` release managed sessions.
diff --git a/docs/release/FIRMAMENT-LX-X0.md b/docs/release/FIRMAMENT-LX-X0.md
index 88a5b3b9..8b9b8431 100644
--- a/docs/release/FIRMAMENT-LX-X0.md
+++ b/docs/release/FIRMAMENT-LX-X0.md
@@ -1,49 +1,69 @@
-# Firmament LX-X0 — language experience and semantic selector contract
+# FIRMAMENT-LX-X0 — language experience contract
-**Verdict: Blocked.** The requested accepted contract cannot be implemented within the mission's own constraints against new Firmament syntax, a second language definition, and selectors derived from transient mesh IDs. This report records the precise boundary; no compiler, Web SDK, or Helios behavior was changed.
+## Executive verdict
-## Decisive witnesses
+**Meaningful progression.** Aetheris now provides partial-source, compiler-owned Helix and Loft field completion through the Web SDK, plus selector candidates derived from the qualified geometry source map. This is not enough for an unfamiliar user to author representative Firmament entirely inside Helios. The editor still uses a textarea and has no Monaco completion, hover, or live language diagnostics.
-| Required witness | Current authoritative behavior | Evidence |
-| --- | --- | --- |
-| `Helix H { ... }` completion and valid snippet | The Mechanical parser rejects `Helix` as an unknown canonical declaration. | `dotnet run --project Aetheris.CLI -- validate artifacts/local/lx-x0/helix-probe.firmament --json` returned fatal `firmament-v2-canonical-declaration-unknown:Helix`. `FirmamentV2Parser.ScanCanonicalTopLevelDeclarations` has no Helix admission. |
-| Existing helical authoring | `AxisCoil` is valid inside a `WireForm`, with Radius, Turns, Pitch or Height, Handedness, and optional StartPhase. It is a different admitted construct, not a `Helix` alias. | `dotnet run --project Aetheris.CLI -- validate fixtures/Canonical/WireForm/axis-coil.firmament --json` returned `status: valid`, 0 diagnostics, 1 operation. See `docs/public/firmament/wire-form.md`. |
-| Runtime face → source selector | The Web SDK emits `face:<FaceId.Value>` from tessellated/reimported B-rep faces and returns it from `resolveSelection`. It has no compiler-owned correspondence from that ID to an authored axis/name/selector. | `Aetheris.Web.Runtime/Program.cs`, `WebMeshBuilder.Build`; `Aetheris.Web.Runtime/sdk/src/index.js`, `ModelSession.resolveSelection`. |
-| Runtime edge → source selector | The V2 parser explicitly rejects `edge(...)` exposure selectors. | `FirmamentV2Parser.ParseExposures` adds `SelectorUnsupported` for `edge(...)`; `FirmamentV2ParserTests` qualifies that rejection. |
-| Geometry → precise source | The Web part snapshot gives the root and body the entire source range. Engineering feature nodes have `source: null`; mesh ranges carry the same body entity ID. | `Aetheris.Web.Runtime/Program.cs`, `WebModelSession.CompilePart`. |
-| Precise diagnostics | The Web runtime maps `KernelDiagnostic.Source` to `details` and assigns every diagnostic a synthetic `SourceRef(sourceName, 0, 0)` (line 1, column 1). `KernelDiagnostic` has no range field. | `Aetheris.Web.Runtime/Program.cs`, `Diagnostics`; `Aetheris.Kernel.Core/Diagnostics/KernelDiagnostic.cs`. |
+## Language inventory and authority
-## Language intelligence
+| Area | Current authority | Available now | Gap |
+| --- | --- | --- | --- |
+| Top-level and canonical primitives | `FirmamentV2Parser`, feature/template expanders, specialist parsers | Grammar and diagnostics for complete input | No shared construct catalog or recovery tree for partial input |
+| Helix | `WireFormAuthoring` operation admission and `WireCoilAuthoring.CreateAxis` | Radius, Turns, Pitch/Height, Handedness, StartPhase; type, default, choices, meaning, required state | No diagnostic ranges or value completion; Pitch/Height is an either-or requirement |
+| Loft | `LoftAuthoringParser` | Solid/hollow field lists reused for field admission and completion | Cross-field validity and referenced profile/frame symbols are not exposed |
+| Hole | `FirmamentV2Parser.ParseCanonicalHoles` and related semantic hole binders | Variant-specific field admission and named Hole lowering | No public authoring metadata or partial Hole completion |
+| Feature, Concept, Interface, Pattern, Set, Span | Existing expansion, parsing, and lowering owners | Complete-source semantics and canonical fixtures | No unified authoring metadata or same-document symbol/reference index |
+| Source selectors | `GeometrySourceMap`, construction correspondence, Web SDK mesh provenance | Stable qualified selectors including Box axis faces and simple Hole walls | Completion is snapshot-derived and not yet filtered by a parsed expected-selector position |
+| Diagnostics | Firmament parser/binder/build results | Build diagnostics | Existing Web runtime fallback source range is zero-length at document start; no lightweight language diagnostic route |
-The existing V2 parser and specialized authoring parsers remain authoritative, but there is no public partial-source language-service API. `FirmamentV2Parser.Parse` is a whole-document parse and returns diagnostic codes and a semantic document after expansion. Its canonical construct admission list is internal to the parser. Many constructs are governed by separate specialized parsers and frontend schemas. A separate TypeScript completion table would drift immediately; a new C# table that merely restates these parsers would also be a second language definition.
+The language service is `FirmamentLanguageService.Complete`. It asks `WireFormAuthoring` or `LoftAuthoringParser` for context/fields. It uses a bounded prefix/field-presence scan on incomplete source and does not run BRep construction. `LoftAuthoringParser` uses the same field metadata for parser admission. `WireCoilAuthoring` keeps Helix field names beside the actual binder checks. Web SDK `ModelSession.selectorCandidates` filters the existing compiler construction correspondence exposed by `geometrySourceMap()`; it does not infer source selectors from display IDs.
-Current Web SDK methods are `compile`, session rebuild/property/source operations, tree and mesh inspection, selection resolution, and STEP export. It exposes no completion, hover, signature help, symbol/definition/reference query, or partial-source diagnostic request. No LX result shape or latency is claimed. There is no measured completion/hover/selector latency because the APIs do not exist.
+## Public Web SDK contract
-## Selector semantics
+```ts
+const result = await cad.language.complete(source, cursorOffset, {
+ sourceName: 'spring.firmament', sourceRevision: 'draft-7'
+});
+// result: { document, revision, context, replaceStart, replaceLength,
+// fields: [{ name, type, required, meaning, default?, choices? }],
+// missingRequiredFields }
-The parser accepts semantic axis forms such as `face(+Z)` in supported contexts, and imported STEP uses `Body.face("#entity")` only where an imported topology map resolves that entity. These are source expressions. A browser `face:5` identity is neither form. Mapping a selected face to `face(+Z)` would require compiler-owned evidence that the selected topology is the unique source-addressable +Z face for the relevant authored body and revision. The Web export currently retains no such mapping. Mapping an edge needs an admitted source selector form first; the parser currently rejects it.
+const faces = model.selectorCandidates('Face');
+// Each item carries selector, semanticKey, outputRole, source,
+// qualification, and buildRevision from the last valid model snapshot.
+```
-Therefore source-addressability cannot be asserted from the current Web selection result. A conservative API could report `Ambiguous` or `RuntimeOnly` with no selector, but it would not satisfy the mandatory face/edge acceptance witnesses or the fresh-agent Copy Selector task. Returning fabricated text would make the user paste invalid Firmament.
+Results are JSON-safe and deterministic for the same source and offset. The caller owns source revision tokens. A model's selector candidates carry build revision and must be discarded when their compiled source is stale relative to the editor draft.
-## Helios implication
+## Coverage and Helios
-Helios should keep **Copy Semantic ID** distinct from **Copy Selector**. The prior DFH-X1 UI-only walkthrough confirmed why: a selected top face displayed `face:5`; using that value as a Hole `On` expression failed. Go to Source selected model-level line 1 rather than the Box declaration at line 3. Helios's hardcoded Box/Hole snippets are a narrow interim authoring aid, not an LX contract. Replacing them requires authoritative snippet/field metadata and a partial-source analysis path in Aetheris.
+| Construct | X0 completion/help status |
+| --- | --- |
+| Box | Existing compiled selector correspondence; no field completion |
+| Helix | Partial-source field completion and required field hints |
+| Hole | Existing qualified wall selector and insertion; no field completion |
+| Feature | No LX metadata or completion |
+| Concept | No LX metadata or completion |
+| Loft | Partial-source solid/hollow field completion and required field hints |
+| Other constructs | No LX field metadata or completion |
-## Required upstream decisions and work
+Helios currently consumes qualified picking, Go to Source, Copy Selector, Box/Hole commands, and rebuild diagnostics. It does **not** consume the new language completion API. Monaco integration, Problems markers, source hover, go-to-definition, and LX-sourced command snippets remain open. No Helios release note is claimed for this Aetheris-only substrate change.
-1. Decide whether LX-X0 targets the currently admitted **AxisCoil** helical workflow or authorizes a separate **Helix** language and geometry milestone. The present mission asks for Helix while prohibiting the syntax/geometry work needed to make it legal.
-2. Retain authored declaration spans and generated semantic-to-topology provenance through Firmament AIR, B-rep, STEP reimport, and the Web mesh. This must support one source construct to many faces/edges and distinguish addressable from generated/runtime-only topology.
-3. Define and admit source-valid selector forms for the intended face and edge classes. The formatter must consume the compiler's stable identities, not reimported face numbers or mesh indexes.
-4. Add parser-adjacent authoring metadata or reusable parser queries for fields, value kinds, snippets, and partial-source contexts; expose revision-tagged JSON-safe results through the Web SDK. Preserve the actual parser/binder as the only language authority.
-5. Carry precise source spans through diagnostics instead of assigning line 1 to every Web diagnostic. Then qualify incomplete-source completion and diagnostics without B-rep rebuild.
+## Verification and performance
-This is upstream semantic/compiler work, not a safe Helios-only patch. The existing single-source Web contract and missing project context remain additional limitations. No multi-file work, language redesign, or geometry test weakening was introduced.
+- `dotnet build Aetheris.slnx -c Release --no-restore -m:1`: passed; existing SQLite WASM warnings remain.
+- `dotnet test Aetheris.slnx -c Release --no-build --no-restore -m:1`: passed across the test projects (3,857 reported tests); the separate FrictionLab project reported no test count.
+- Full Firmament suite: 1,599 passed. Targeted language service, semantic hole, and parser lane: 138 passed.
+- SDK transport and source-map selection tests: 5 passed.
+- Helios Vitest suite: 28 passed in 5 files. This verifies existing behavior only; Helios does not call LX yet.
+- Headless Chrome using the packaged WebAssembly runtime returned `Radius: Length` for an incomplete Helix and legal remaining fields for an incomplete Loft. A compiled plain Box yielded all six axis selectors; a compiled through-Hole model yielded `face(H.Wall)` with no runtime ID suggestions.
+- In one browser run after runtime initialization, first Helix completion took 33.5 ms and median of ten subsequent calls took 0.4 ms; first Loft completion took 2.5 ms and warm median took 0.6 ms. These are local observations, not an SLA. Top-level completion, hover, and language diagnostics do not yet exist to measure.
+- Fresh-agent Box/Helix/Hole authoring tasks were not run. The missing Helios editor integration would make the requested in-editor tasks fail today.
-## Qualification performed
+| Fresh-agent task | Result | Time | Wrong turns | Missing tooling | Fix |
+| --- | --- | --- | --- | --- | --- |
+| Box / Helix / Hole authoring and Hole-wall reference | Not run as fresh-agent tests | Not measured | Not measured | Monaco LX providers and broader compiler metadata | Complete editor consumption and rerun independently |
-- Aetheris CLI help inspected before assumptions, per repository guidance.
-- Canonical AxisCoil fixture validated through the real CLI: valid, 0 diagnostics.
-- A Mechanical `Helix` probe under ignored `artifacts/local/lx-x0/` validated through the real CLI: fatal unknown declaration.
-- Existing parser test source confirms `edge(...)` rejection. No implementation files changed, so full solution/browser/Helios regression was not run for this blocked audit.
+## Next blocker
-**Decision boundary:** Resume implementation after the Helix versus AxisCoil target and stable face/edge selector semantics are explicitly admitted by the owning compiler. An editor contract can then project those authorities without duplicating Firmament.
+Most Firmament construct legality is embedded in several specialist parser/binder branches rather than a reusable authoring catalog. The current service only covers Helix and Loft. Expanding it responsibly requires each owner to expose fields/types/choices and a shared partial-source context layer before wiring Monaco. Copying those signatures into Helios would violate the single-language-authority contract. Source-range diagnostics, symbols, definitions/references, and selector-position filtering still require compiler-owned semantics. X0 acceptance criteria are not met.