diff --git a/README.md b/README.md
index 58c2243..67b7579 100644
--- a/README.md
+++ b/README.md
@@ -332,6 +332,26 @@ sources are additive: the file cannot re-include a built-in cache/vendor/output
excluded explicitly through `CheckOptions`. The cache identity includes the normalized root-file
path, its presence, and a SHA-256 fingerprint of its exact bytes, so edits invalidate cached graphs.
+### Zig workspaces and nested packages
+
+`ExtractionOptions.workspace.mode` selects one of three scopes: the located package (the compatible
+default), an explicit borrowed list of `WorkspacePackage` values, or every `build.zig.zon` package
+discovered below the located repository root. Explicit packages provide an `id` and root-relative
+`path`. Discovered ids are their normalized manifest-directory paths, with `.` naming a root
+package. Cache, VCS, output, documentation, dependency, symlink, and reparse-point trees are never
+entered during discovery.
+
+Workspace graph identifiers are `package_id::package-relative/path`, so `api::src/main.zig` and
+`worker::src/main.zig` cannot collapse. The single-package mode retains ordinary `src/main.zig`
+identifiers. Workspace `CompilationUnitOverride` values set `package_id`; a project-origin module
+mapping without its own `package_id` resolves inside that unit's package, while an explicit target
+package models a local cross-package alias. `root` always resolves in the selected unit's package.
+
+The workspace-root `.archignore` matches physical repository-relative paths, each selected package's
+own `.archignore` matches package-relative paths, and `ExtractionOptions.exclusions` matches qualified
+workspace identifiers. All are additive. Workspace cache keys include the selected mode/list and the
+resolved package identities, canonical paths, manifest fingerprints, and ignore fingerprints.
+
## Limitations
| Area | Current contract |
@@ -350,9 +370,10 @@ path, its presence, and a SHA-256 fingerprint of its exact bytes, so edits inval
## Configuration and diagnostics
`CheckOptions` carries the allocator, `std.Io`, working directory, empty-test policy, cache control,
-logging, and one `ExtractionOptions` value. Extraction options cover exclusions, strictness,
-resource/C-header inclusion, test-import inclusion, compilation-unit mappings, and the currently
-explicit-only build-graph mode. Every field that changes a graph participates in its cache key.
+logging, and one `ExtractionOptions` value. Extraction options cover exclusions, workspace scope,
+strictness, resource/C-header inclusion, test-import inclusion, compilation-unit mappings, and the
+currently explicit-only build-graph mode. Every field that changes a graph participates in its
+cache key.
Logging is disabled by default. A check can borrow an ordinary writer, structured `LogSink`, and/or
file sink with explicit output directory and prefix. Levels are `debug`, `info`, `warn`, and
diff --git a/docs-site/pages/extraction-modules.html b/docs-site/pages/extraction-modules.html
index d760e0d..e56b846 100644
--- a/docs-site/pages/extraction-modules.html
+++ b/docs-site/pages/extraction-modules.html
@@ -9,6 +9,10 @@
Only the root file is authoritative. Nested files do not override it, and its patterns are additive with explicit and built-in exclusions. Gitignore negation is intentionally unsupported; a line beginning with ! is an InvalidPattern error rather than an inert policy.
+The compatible default analyzes only the located package. Workspace mode can instead select an explicit list of package ids and root-relative paths, or discover every build.zig.zon below a repository root. Discovery prunes dependency, vendor, cache, VCS, output, documentation, symlink, and reparse-point trees.
+
@@ -38,7 +42,7 @@
Production graphs and colocated tests
Zig test declarations live beside production code, so their imports are visible by default. Set ExtractionOptions.include_test_imports = false when enforcing a production-only architecture. Ordinary comptime dependencies remain included.
Deterministic cache identity
-
Graph-cache keys encode the canonical project root and every extraction option, including ordered compilation-unit mappings and test-import behavior. They also encode the normalized root .archignore path, presence, and exact-content SHA-256 fingerprint, so edits invalidate prior results. Caller-owned caches are unsynchronized; the optional process cache is mutex-protected. Reads return clones, so clearing a cache cannot invalidate a graph already returned to a caller.
+
Graph-cache keys encode the canonical project root and every extraction option, including workspace selection, ordered compilation-unit mappings, and test-import behavior. They also encode root/package ignore fingerprints plus every selected manifest's canonical path and exact-content fingerprint, so edits or newly discovered packages invalidate prior results. Caller-owned caches are unsynchronized; the optional process cache is mutex-protected. Reads return clones, so clearing a cache cannot invalidate a graph already returned to a caller.
Local dependency suppressions
// archunit: ignore may suppress one intentional dependency occurrence. A trailing directive applies to calls on that line; a standalone directive applies only to the builtin on the next physical line. Optional target names are exact after Zig string decoding. Malformed directives are reported instead of silently changing the graph.
diff --git a/docs-site/pages/limitations.html b/docs-site/pages/limitations.html
index f827bf2..f4bac39 100644
--- a/docs-site/pages/limitations.html
+++ b/docs-site/pages/limitations.html
@@ -2,7 +2,7 @@
Current limitations and honest boundaries
ArchUnitZig prefers explicit missing behavior over apparent parity built on Zig concepts that do not exist or cannot be discovered reliably without running user code.
No automatic build.zig interpretation
-
Named module imports need a compilation-unit alias table. Zig build files are programs: their module graph can depend on target, options, environment, filesystem state, and control flow. ArchUnitZig does not run them or recognize a misleading subset. Provide CompilationUnitOverride values explicitly.
+
Named module imports need a compilation-unit alias table. Zig build files are programs: their module graph can depend on target, options, environment, filesystem state, and control flow. ArchUnitZig does not run them or recognize a misleading subset. Workspace discovery finds package boundaries from manifests; it does not infer compilation roots or aliases. Provide CompilationUnitOverride values explicitly.
Literal dependency calls only
The extractor records literal @import, @embedFile, and supported C-import forms. A computed dependency operand is a parser-policy error in strict mode because static analysis cannot name its target without execution.
diff --git a/docs/architecture.md b/docs/architecture.md
index 057d9b1..25dbaee 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -208,13 +208,19 @@ blank lines and full-line `#` comments are metadata; negation is deliberately un
nested `.archignore` files do not alter the root policy.
Extraction settings live in one `ExtractionOptions` value: exclusions, parser strictness,
-resource/C-header toggles, explicit compilation-unit mappings, and build-graph mode. Graph-cache
-keys use the canonical project root plus a length-delimited encoding of every field. They also encode
-the normalized root `.archignore` path, whether the file exists, and the SHA-256 fingerprint of its
-exact bytes. A schema test reflects over the options and nested module-mapping structs, so adding a
-field without acknowledging it in key construction fails the suite. Slice order is significant;
-this may conservatively miss an equivalent hit but cannot return a graph produced for different
-input.
+resource/C-header toggles, workspace scope, explicit compilation-unit mappings, and build-graph
+mode. Single-package scope retains package-relative identifiers. Explicit and discovered workspace
+scopes qualify every internal identifier as `package_id::package-relative/path`; discovered package
+ids are normalized manifest-directory paths and explicit ids are caller-owned labels. Nested
+manifests are package boundaries even while discovery continues below them to find deeper packages.
+
+Graph-cache keys use the canonical project root plus a length-delimited encoding of every field.
+They also encode the normalized root `.archignore` path, whether the file exists, and the SHA-256
+fingerprint of its exact bytes. Workspace keys additionally encode every resolved package's identity,
+canonical/relative paths, exact manifest fingerprint, and package-ignore fingerprint. A schema test
+reflects over options, workspace selections, and nested module-mapping structs, so adding a field
+without acknowledging it in key construction fails the suite. Slice order is significant; this may
+conservatively miss an equivalent hit but cannot return a graph produced for different input.
`GraphCache` instances own cloned keys and graphs and are deliberately not synchronized. Reads also
return clones, so clearing or destroying a cache never invalidates a caller's graph. The process-wide
diff --git a/docs/decisions.md b/docs/decisions.md
index 0ced6e4..d887a2a 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -1283,3 +1283,44 @@ Consequence: repositories can keep generated or vendored source out of every arc
without repeating options in each test; configuration errors are visible; Windows-authored patterns
stay portable; nested projects cannot silently override their parent's scan; and cached graphs never
outlive the exact root policy bytes that selected their source files.
+
+### D052 — Workspace identity is explicit and build scripts remain inert
+
+`ExtractionOptions.workspace.mode` is `single_package`, `explicit_packages`, or
+`discover_packages`. The compatible default preserves every existing package-relative identifier and
+stops at nested marked projects. Explicit mode requires a non-empty borrowed list of unique
+`WorkspacePackage { id, path }` values whose canonical directories remain below the located root and
+contain `build.zig.zon`. Discovery mode accepts no explicit list and finds the root manifest plus all
+nested manifests beneath the located repository root. It prunes the same cache, VCS, output,
+documentation, dependency, symlink, and reparse-point boundaries as source enumeration, but it keeps
+searching below one package to find deliberately nested packages.
+
+Workspace internal identifiers are `package_id::package-relative/path`. Explicit ids are validated
+non-empty labels without `::`; discovered ids are normalized manifest-directory paths and `.` names
+the root. This namespace is visible to selectors and reports, rather than hiding identity in cache-
+only metadata. Two packages may therefore own identical `src/main.zig` paths without creating one
+node or merging edges. Single-package consumers pay no migration cost.
+
+Workspace compilation units require `CompilationUnitOverride.package_id`. Root-source paths remain
+package-relative, and `@import("root")` resolves only inside that unit's package. A project-origin
+`ModuleOverride` without `package_id` targets the unit package; setting it names another selected
+package and models a local cross-package alias. Package-origin aliases remain external and cannot
+also name a workspace package. No `build.zig` code is executed and no alias table is guessed from
+manifest dependency declarations.
+
+Exclusions have three deliberate coordinate systems. The workspace-root `.archignore` is matched
+against physical repository-relative paths during discovery and corpus assembly. Each package-root
+`.archignore` is matched against its package-relative paths by the ordinary enumerator. Explicit
+`ExtractionOptions.exclusions` are matched against final qualified identifiers. All remain additive;
+built-in directory pruning applies both to discovery and per-package traversal.
+
+One owned workspace snapshot is shared by cache-key construction and extraction. It records sorted
+package ids, normalized relative and canonical paths, exact `build.zig.zon` SHA-256 fingerprints,
+and each package ignore path/presence/fingerprint. The cache key also encodes the workspace mode and
+ordered explicit selection input. Adding, removing, moving, renaming, or editing a selected manifest
+or policy therefore separates graphs without a read-key/read-scan race.
+
+Consequence: monorepos can analyze one package, a reviewed set, or all manifest packages; duplicate
+relative paths remain distinct; local module edges and `root` keep compilation context; dependency
+caches stay outside discovery; and workspace topology changes cannot reuse a stale single-package or
+multi-package cache entry.
diff --git a/src/common/extraction.zig b/src/common/extraction.zig
index 1666922..2e9d17f 100644
--- a/src/common/extraction.zig
+++ b/src/common/extraction.zig
@@ -7,6 +7,9 @@ pub const extractProjectGraphLogged = @import("extraction/project_graph.zig").ex
pub const GraphCache = @import("extraction/graph_cache.zig").GraphCache;
pub const GraphCacheKey = @import("extraction/graph_cache.zig").GraphCacheKey;
pub const ExtractionOptions = @import("extraction/extraction_options.zig").ExtractionOptions;
+pub const WorkspaceMode = @import("extraction/extraction_options.zig").WorkspaceMode;
+pub const WorkspaceOptions = @import("extraction/extraction_options.zig").WorkspaceOptions;
+pub const WorkspacePackage = @import("extraction/extraction_options.zig").WorkspacePackage;
pub const SourceReferences = @import("extraction/graph_normalizer.zig").SourceReferences;
pub const ImportKind = @import("extraction/import_kind.zig").ImportKind;
pub const ImportKinds = @import("extraction/import_kind.zig").ImportKinds;
@@ -18,6 +21,7 @@ pub const ModuleOverride = @import("extraction/module_resolver.zig").ModuleOverr
pub const ModuleResolutionOverrides = @import("extraction/module_resolver.zig").ModuleResolutionOverrides;
pub const ModuleResolutionStatus = @import("extraction/module_resolver.zig").ModuleResolutionStatus;
pub const ResolvedModuleReference = @import("extraction/module_resolver.zig").ResolvedModuleReference;
+pub const WorkspacePackageRoot = @import("extraction/module_resolver.zig").WorkspacePackageRoot;
pub const ProjectMarker = @import("extraction/project_locator.zig").ProjectMarker;
pub const EnumerationOptions = @import("extraction/source_files.zig").EnumerationOptions;
pub const FileResolutionInput = @import("extraction/classifier.zig").FileResolutionInput;
@@ -46,6 +50,7 @@ pub const parseSource = @import("extraction/source_parser.zig").parseSource;
pub const normalizeGraph = @import("extraction/graph_normalizer.zig").normalizeGraph;
pub const resolveRelativeReference = @import("extraction/relative_resolver.zig").resolveRelativeReference;
pub const resolveModuleReference = @import("extraction/module_resolver.zig").resolveModuleReference;
+pub const resolveWorkspaceModuleReference = @import("extraction/module_resolver.zig").resolveWorkspaceModuleReference;
pub const storeGraphInCache = @import("extraction/graph_cache.zig").storeGraphInCache;
pub const validateModuleResolutionOverrides = @import("extraction/module_resolver.zig").validateModuleResolutionOverrides;
pub const locateProject = @import("extraction/project_locator.zig").locateProject;
@@ -69,4 +74,6 @@ test {
_ = @import("extraction/source_files.zig");
_ = @import("extraction/source_parser.zig");
_ = @import("extraction/source_location.zig");
+ _ = @import("extraction/workspace.zig");
+ _ = @import("extraction/workspace_options.zig");
}
diff --git a/src/common/extraction/extraction_options.zig b/src/common/extraction/extraction_options.zig
index e3982cf..1de1600 100644
--- a/src/common/extraction/extraction_options.zig
+++ b/src/common/extraction/extraction_options.zig
@@ -1,16 +1,23 @@
const module_resolver = @import("module_resolver.zig");
const source_parser = @import("source_parser.zig");
+const workspace_options = @import("workspace_options.zig");
pub const BuildGraphMode = enum {
disabled,
explicit_only,
};
+pub const WorkspaceMode = workspace_options.WorkspaceMode;
+pub const WorkspaceOptions = workspace_options.WorkspaceOptions;
+pub const WorkspacePackage = workspace_options.WorkspacePackage;
+
/// Every option here changes extraction output and therefore belongs in `buildGraphCacheKey`.
/// All slices and nested module mappings are borrowed for the duration of extraction/key creation.
pub const ExtractionOptions = struct {
/// Additional project-relative globs beyond the enumerator defaults.
exclusions: []const []const u8 = &.{},
+ /// One located package by default, or an explicit/discovered manifest workspace.
+ workspace: WorkspaceOptions = .{},
/// Whether invalid source aborts extraction or becomes owned diagnostics.
strictness: source_parser.Strictness = .strict,
/// Whether `@embedFile` targets participate in the graph.
diff --git a/src/common/extraction/graph_cache.zig b/src/common/extraction/graph_cache.zig
index 5db084d..e961920 100644
--- a/src/common/extraction/graph_cache.zig
+++ b/src/common/extraction/graph_cache.zig
@@ -6,6 +6,8 @@ const common_path = @import("../path.zig");
const extraction_options = @import("extraction_options.zig");
const graph_module = @import("graph.zig");
const module_resolver = @import("module_resolver.zig");
+const workspace = @import("workspace.zig");
+const workspace_options = @import("workspace_options.zig");
const Allocator = std.mem.Allocator;
const Io = std.Io;
@@ -13,9 +15,10 @@ pub const BuildGraphMode = extraction_options.BuildGraphMode;
pub const ExtractionOptions = extraction_options.ExtractionOptions;
pub const Graph = graph_module.Graph;
-const cache_key_schema_version: u64 = 3;
+const cache_key_schema_version: u64 = 5;
const keyed_option_fields = [_][]const u8{
"exclusions",
+ "workspace",
"strictness",
"include_resources",
"include_c_imports",
@@ -23,9 +26,11 @@ const keyed_option_fields = [_][]const u8{
"module_resolution",
"build_graph_mode",
};
+const keyed_workspace_fields = [_][]const u8{ "mode", "packages" };
+const keyed_workspace_package_fields = [_][]const u8{ "id", "path" };
const keyed_module_resolution_fields = [_][]const u8{"compilation_units"};
-const keyed_compilation_unit_fields = [_][]const u8{ "id", "root_source_path", "modules" };
-const keyed_module_override_fields = [_][]const u8{ "name", "source_path", "origin" };
+const keyed_compilation_unit_fields = [_][]const u8{ "id", "package_id", "root_source_path", "modules" };
+const keyed_module_override_fields = [_][]const u8{ "name", "package_id", "source_path", "origin" };
/// Owned canonical cache identity. Hashes accelerate lookup; equality always compares full bytes.
pub const GraphCacheKey = struct {
@@ -58,11 +63,21 @@ pub fn buildGraphCacheKey(
defer allocator.free(canonical_root);
var root_policy = try archignore.load(allocator, io, canonical_root, diagnostics);
defer root_policy.deinit(allocator);
+ var topology = try workspace.load(
+ allocator,
+ io,
+ canonical_root,
+ options.workspace,
+ &root_policy,
+ diagnostics,
+ );
+ defer topology.deinit(allocator);
return buildCanonicalGraphCacheKey(
allocator,
canonical_root,
options,
&root_policy,
+ if (options.workspace.mode == .single_package) null else &topology,
diagnostics,
);
}
@@ -75,6 +90,35 @@ pub fn buildGraphCacheKeyWithArchIgnore(
options: ExtractionOptions,
root_policy: *const archignore.ArchIgnore,
diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!GraphCacheKey {
+ var topology = try workspace.load(
+ allocator,
+ io,
+ project_root,
+ options.workspace,
+ root_policy,
+ diagnostics,
+ );
+ defer topology.deinit(allocator);
+ return buildGraphCacheKeyWithContext(
+ allocator,
+ io,
+ project_root,
+ options,
+ root_policy,
+ if (options.workspace.mode == .single_package) null else &topology,
+ diagnostics,
+ );
+}
+
+pub fn buildGraphCacheKeyWithContext(
+ allocator: Allocator,
+ io: Io,
+ project_root: []const u8,
+ options: ExtractionOptions,
+ root_policy: *const archignore.ArchIgnore,
+ topology: ?*const workspace.Workspace,
+ diagnostics: *common_error.ErrorContext,
) common_error.ArchUnitError!GraphCacheKey {
const canonical_root = try canonicalProjectRoot(allocator, io, project_root, diagnostics);
defer allocator.free(canonical_root);
@@ -83,6 +127,7 @@ pub fn buildGraphCacheKeyWithArchIgnore(
canonical_root,
options,
root_policy,
+ topology,
diagnostics,
);
}
@@ -114,6 +159,7 @@ fn buildCanonicalGraphCacheKey(
canonical_root: []const u8,
options: ExtractionOptions,
root_policy: *const archignore.ArchIgnore,
+ topology: ?*const workspace.Workspace,
diagnostics: *common_error.ErrorContext,
) common_error.ArchUnitError!GraphCacheKey {
const normalized_root = common_path.normalize(allocator, canonical_root) catch {
@@ -123,7 +169,7 @@ fn buildCanonicalGraphCacheKey(
var encoded: std.ArrayList(u8) = .empty;
errdefer encoded.deinit(allocator);
- appendKey(allocator, &encoded, normalized_root, options, root_policy) catch {
+ appendKey(allocator, &encoded, normalized_root, options, root_policy, topology) catch {
return diagnostics.failTechnical(.out_of_memory, "graph_cache.build_key", canonical_root, error.OutOfMemory);
};
const bytes = encoded.toOwnedSlice(allocator) catch {
@@ -138,12 +184,35 @@ fn appendKey(
canonical_root: []const u8,
options: ExtractionOptions,
root_policy: *const archignore.ArchIgnore,
+ topology: ?*const workspace.Workspace,
) Allocator.Error!void {
try appendU64(allocator, encoded, cache_key_schema_version);
try appendString(allocator, encoded, canonical_root);
try appendString(allocator, encoded, root_policy.path);
try encoded.append(allocator, @intFromBool(root_policy.present));
try appendString(allocator, encoded, &root_policy.fingerprint);
+ try appendU64(allocator, encoded, @intFromEnum(options.workspace.mode));
+ try appendU64(allocator, encoded, options.workspace.packages.len);
+ for (options.workspace.packages) |package| {
+ try appendString(allocator, encoded, package.id);
+ try appendString(allocator, encoded, package.path);
+ }
+ if (topology) |resolved| {
+ try encoded.append(allocator, 1);
+ try appendU64(allocator, encoded, resolved.items().len);
+ for (resolved.items()) |package| {
+ try appendString(allocator, encoded, package.id);
+ try appendString(allocator, encoded, package.relative_path);
+ try appendString(allocator, encoded, package.path);
+ try appendString(allocator, encoded, package.manifest_path);
+ try appendString(allocator, encoded, &package.manifest_fingerprint);
+ try appendString(allocator, encoded, package.policy.path);
+ try encoded.append(allocator, @intFromBool(package.policy.present));
+ try appendString(allocator, encoded, &package.policy.fingerprint);
+ }
+ } else {
+ try encoded.append(allocator, 0);
+ }
try appendU64(allocator, encoded, @intFromEnum(options.strictness));
try encoded.append(allocator, @intFromBool(options.include_resources));
try encoded.append(allocator, @intFromBool(options.include_c_imports));
@@ -157,6 +226,12 @@ fn appendKey(
try appendU64(allocator, encoded, units.len);
for (units) |unit| {
try appendString(allocator, encoded, unit.id);
+ if (unit.package_id) |package_id| {
+ try encoded.append(allocator, 1);
+ try appendString(allocator, encoded, package_id);
+ } else {
+ try encoded.append(allocator, 0);
+ }
if (unit.root_source_path) |root_source_path| {
try encoded.append(allocator, 1);
try appendString(allocator, encoded, root_source_path);
@@ -166,6 +241,12 @@ fn appendKey(
try appendU64(allocator, encoded, unit.modules.len);
for (unit.modules) |module| {
try appendString(allocator, encoded, module.name);
+ if (module.package_id) |package_id| {
+ try encoded.append(allocator, 1);
+ try appendString(allocator, encoded, package_id);
+ } else {
+ try encoded.append(allocator, 0);
+ }
try appendString(allocator, encoded, module.source_path);
try appendU64(allocator, encoded, @intFromEnum(module.origin));
}
@@ -315,6 +396,10 @@ fn makeGraph(allocator: Allocator, target: []const u8) !Graph {
test "canonical roots produce equal keys and every option separates keys" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
+ try tmp.dir.writeFile(std.testing.io, .{
+ .sub_path = "build.zig.zon",
+ .data = ".{ .name = .fixture, .version = \"0.0.0\", .fingerprint = 0x3333333333333333 }",
+ });
const root = try temporaryRoot(&tmp);
defer std.testing.allocator.free(root);
const dotted_root = try std.fs.path.join(std.testing.allocator, &.{ root, "." });
@@ -341,8 +426,10 @@ test "canonical roots produce equal keys and every option separates keys" {
.root_source_path = "src/main.zig",
.modules = &modules,
}};
+ const packages = [_]workspace_options.WorkspacePackage{.{ .id = "root", .path = "." }};
const variants = [_]ExtractionOptions{
.{ .exclusions = &exclusions },
+ .{ .workspace = .{ .mode = .explicit_packages, .packages = &packages } },
.{ .strictness = .permissive },
.{ .include_resources = false },
.{ .include_c_imports = false },
@@ -401,6 +488,44 @@ test "cache keys encode root archignore path presence and exact content fingerpr
try std.testing.expect(!alpha.eql(bravo));
}
+test "workspace cache keys separate manifest edits and discovered topology" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDirPath(std.testing.io, "packages/api");
+ try tmp.dir.writeFile(std.testing.io, .{
+ .sub_path = "build.zig.zon",
+ .data = ".{ .name = .root, .version = \"0.0.0\", .fingerprint = 0x4444444444444444 }",
+ });
+ try tmp.dir.writeFile(std.testing.io, .{
+ .sub_path = "packages/api/build.zig.zon",
+ .data = ".{ .name = .api, .version = \"0.0.0\", .fingerprint = 0x5555555555555555 }",
+ });
+ const root = try temporaryRoot(&tmp);
+ defer std.testing.allocator.free(root);
+ var context = common_error.ErrorContext.init(std.testing.allocator);
+ defer context.deinit();
+ const options = ExtractionOptions{ .workspace = .{ .mode = .discover_packages } };
+
+ var baseline = try buildGraphCacheKey(std.testing.allocator, std.testing.io, root, options, &context);
+ defer baseline.deinit(std.testing.allocator);
+ try tmp.dir.writeFile(std.testing.io, .{
+ .sub_path = "packages/api/build.zig.zon",
+ .data = ".{ .name = .api, .version = \"0.0.1\", .fingerprint = 0x5555555555555555 }",
+ });
+ var edited = try buildGraphCacheKey(std.testing.allocator, std.testing.io, root, options, &context);
+ defer edited.deinit(std.testing.allocator);
+ try std.testing.expect(!baseline.eql(edited));
+
+ try tmp.dir.createDirPath(std.testing.io, "packages/shared");
+ try tmp.dir.writeFile(std.testing.io, .{
+ .sub_path = "packages/shared/build.zig.zon",
+ .data = ".{ .name = .shared, .version = \"0.0.0\", .fingerprint = 0x6666666666666666 }",
+ });
+ var added = try buildGraphCacheKey(std.testing.allocator, std.testing.io, root, options, &context);
+ defer added.deinit(std.testing.allocator);
+ try std.testing.expect(!edited.eql(added));
+}
+
test "every compilation-unit and module mapping field separates cache keys" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -411,28 +536,34 @@ test "every compilation-unit and module mapping field separates cache keys" {
const Mapping = struct {
unit_id: []const u8 = "app",
+ unit_package_id: ?[]const u8 = null,
root_source_path: ?[]const u8 = "src/main.zig",
module_name: []const u8 = "domain",
+ module_package_id: ?[]const u8 = null,
module_source_path: []const u8 = "src/domain/root.zig",
module_origin: module_resolver.ModuleOrigin = .project,
};
const baseline_mapping: Mapping = .{};
const variants = [_]Mapping{
.{ .unit_id = "tests" },
+ .{ .unit_package_id = "api" },
.{ .root_source_path = null },
.{ .root_source_path = "src/other.zig" },
.{ .module_name = "application" },
+ .{ .module_package_id = "shared" },
.{ .module_source_path = "src/application/root.zig" },
.{ .module_origin = .package },
};
const baseline_modules = [_]module_resolver.ModuleOverride{.{
.name = baseline_mapping.module_name,
+ .package_id = baseline_mapping.module_package_id,
.source_path = baseline_mapping.module_source_path,
.origin = baseline_mapping.module_origin,
}};
const baseline_units = [_]module_resolver.CompilationUnitOverride{.{
.id = baseline_mapping.unit_id,
+ .package_id = baseline_mapping.unit_package_id,
.root_source_path = baseline_mapping.root_source_path,
.modules = &baseline_modules,
}};
@@ -448,11 +579,13 @@ test "every compilation-unit and module mapping field separates cache keys" {
for (variants) |mapping| {
const modules = [_]module_resolver.ModuleOverride{.{
.name = mapping.module_name,
+ .package_id = mapping.module_package_id,
.source_path = mapping.module_source_path,
.origin = mapping.module_origin,
}};
const units = [_]module_resolver.CompilationUnitOverride{.{
.id = mapping.unit_id,
+ .package_id = mapping.unit_package_id,
.root_source_path = mapping.root_source_path,
.modules = &modules,
}};
@@ -560,6 +693,8 @@ fn expectKeySchemaCovers(comptime T: type, keyed_fields: []const []const u8) !vo
test "cache key schema lists every extraction and module-mapping option" {
try expectKeySchemaCovers(ExtractionOptions, &keyed_option_fields);
+ try expectKeySchemaCovers(workspace_options.WorkspaceOptions, &keyed_workspace_fields);
+ try expectKeySchemaCovers(workspace_options.WorkspacePackage, &keyed_workspace_package_fields);
try expectKeySchemaCovers(module_resolver.ModuleResolutionOverrides, &keyed_module_resolution_fields);
try expectKeySchemaCovers(module_resolver.CompilationUnitOverride, &keyed_compilation_unit_fields);
try expectKeySchemaCovers(module_resolver.ModuleOverride, &keyed_module_override_fields);
diff --git a/src/common/extraction/module_resolver.zig b/src/common/extraction/module_resolver.zig
index 2484e82..dae06aa 100644
--- a/src/common/extraction/module_resolver.zig
+++ b/src/common/extraction/module_resolver.zig
@@ -20,6 +20,8 @@ pub const ModuleOrigin = enum {
/// source happens to be stored below the analyzed project root.
pub const ModuleOverride = struct {
name: []const u8,
+ /// Workspace package containing a project mapping. `null` means the compilation unit's package.
+ package_id: ?[]const u8 = null,
source_path: []const u8,
origin: ModuleOrigin = .project,
};
@@ -27,10 +29,18 @@ pub const ModuleOverride = struct {
/// Borrowed module context for one library, executable, test, or other Zig compilation root.
pub const CompilationUnitOverride = struct {
id: []const u8,
+ /// Required for workspace extraction and ignored by compatible single-package extraction.
+ package_id: ?[]const u8 = null,
root_source_path: ?[]const u8 = null,
modules: []const ModuleOverride = &.{},
};
+/// Borrowed package identity and canonical root used by workspace-aware module resolution.
+pub const WorkspacePackageRoot = struct {
+ id: []const u8,
+ path: []const u8,
+};
+
/// Borrowed collection of independently validated compilation contexts.
pub const ModuleResolutionOverrides = struct {
compilation_units: []const CompilationUnitOverride = &.{},
@@ -116,6 +126,74 @@ pub fn resolveModuleReference(
};
}
+/// Resolves module-defined imports in a package-qualified workspace compilation context.
+/// Project mappings produce `package_id::package-relative/path` source identities, while
+/// package-origin mappings remain external to the analyzed workspace.
+pub fn resolveWorkspaceModuleReference(
+ allocator: Allocator,
+ io: Io,
+ packages: []const WorkspacePackageRoot,
+ source_package_id: []const u8,
+ unit: CompilationUnitOverride,
+ reference: DependencyReference,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!?ResolvedModuleReference {
+ if (!isModuleDefined(reference.kind)) return null;
+ try validateCompilationUnit(unit, diagnostics);
+ const unit_package_id = unit.package_id orelse
+ return diagnostics.failUser(.invalid_module_override, "module.validate_workspace_unit", unit.id, null);
+ if (!std.mem.eql(u8, unit_package_id, source_package_id)) {
+ return diagnostics.failUser(.invalid_module_override, "module.validate_workspace_unit", unit.id, null);
+ }
+ const source_package = findWorkspacePackage(packages, source_package_id) orelse
+ return diagnostics.failUser(.invalid_module_override, "module.validate_workspace_package", source_package_id, null);
+
+ return switch (reference.kind) {
+ .standard_library, .builtin_module => try makeResolved(
+ allocator,
+ reference,
+ null,
+ .compiler_provided,
+ diagnostics,
+ ),
+ .root_module => if (unit.root_source_path) |root_source_path|
+ try resolveWorkspaceProjectMapping(
+ allocator,
+ io,
+ packages,
+ unit_package_id,
+ root_source_path,
+ reference,
+ diagnostics,
+ )
+ else
+ try makeResolved(allocator, reference, null, .unresolved, diagnostics),
+ .named_module => if (findModule(unit.modules, reference.target)) |module|
+ switch (module.origin) {
+ .project => try resolveWorkspaceProjectMapping(
+ allocator,
+ io,
+ packages,
+ module.package_id orelse unit_package_id,
+ module.source_path,
+ reference,
+ diagnostics,
+ ),
+ .package => try resolvePackageMapping(
+ allocator,
+ io,
+ source_package.path,
+ module.source_path,
+ reference,
+ diagnostics,
+ ),
+ }
+ else
+ try makeResolved(allocator, reference, null, .unresolved, diagnostics),
+ .zig_file, .zon_file, .embedded_file, .c_header => unreachable,
+ };
+}
+
/// Validates every explicit context and rejects duplicate context identifiers.
pub fn validateModuleResolutionOverrides(
overrides: ModuleResolutionOverrides,
@@ -138,6 +216,9 @@ fn validateCompilationUnit(
if (unit.id.len == 0) {
return diagnostics.failUser(.invalid_module_override, "module.validate_unit", unit.id, null);
}
+ if (unit.package_id) |package_id| if (package_id.len == 0) {
+ return diagnostics.failUser(.invalid_module_override, "module.validate_package", unit.id, null);
+ };
if (unit.root_source_path) |root_source_path| if (root_source_path.len == 0) {
return diagnostics.failUser(.invalid_module_override, "module.validate_root", unit.id, null);
};
@@ -145,6 +226,11 @@ fn validateCompilationUnit(
if (module.name.len == 0 or module.source_path.len == 0 or isReservedModule(module.name)) {
return diagnostics.failUser(.invalid_module_override, "module.validate_alias", module.name, null);
}
+ if (module.package_id) |package_id| {
+ if (package_id.len == 0 or module.origin == .package) {
+ return diagnostics.failUser(.invalid_module_override, "module.validate_package", module.name, null);
+ }
+ }
for (unit.modules[0..index]) |prior| {
if (std.mem.eql(u8, prior.name, module.name)) {
return diagnostics.failUser(.invalid_module_override, "module.validate_alias", module.name, null);
@@ -153,6 +239,11 @@ fn validateCompilationUnit(
}
}
+fn findWorkspacePackage(packages: []const WorkspacePackageRoot, id: []const u8) ?WorkspacePackageRoot {
+ for (packages) |package| if (std.mem.eql(u8, package.id, id)) return package;
+ return null;
+}
+
fn findModule(modules: []const ModuleOverride, name: []const u8) ?ModuleOverride {
for (modules) |module| if (std.mem.eql(u8, module.name, name)) return module;
return null;
@@ -201,6 +292,36 @@ fn resolveProjectMapping(
return makeResolved(allocator, reference, file_resolution.target, status, diagnostics);
}
+fn resolveWorkspaceProjectMapping(
+ allocator: Allocator,
+ io: Io,
+ packages: []const WorkspacePackageRoot,
+ package_id: []const u8,
+ mapped_source_path: []const u8,
+ reference: DependencyReference,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!ResolvedModuleReference {
+ const package = findWorkspacePackage(packages, package_id) orelse
+ return diagnostics.failUser(.invalid_module_override, "module.validate_workspace_package", package_id, null);
+ var resolution = try resolveProjectMapping(
+ allocator,
+ io,
+ package.path,
+ mapped_source_path,
+ reference,
+ diagnostics,
+ );
+ errdefer resolution.deinit(allocator);
+ if (resolution.source_path) |source_path| {
+ const qualified = std.fmt.allocPrint(allocator, "{s}::{s}", .{ package_id, source_path }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "module.resolve_workspace", reference.target, error.OutOfMemory);
+ };
+ allocator.free(source_path);
+ resolution.source_path = qualified;
+ }
+ return resolution;
+}
+
fn resolvePackageMapping(
allocator: Allocator,
io: Io,
@@ -334,6 +455,101 @@ fn temporaryRoot(tmp: *std.testing.TmpDir, sub_path: []const u8) ![:0]u8 {
return tmp.dir.realPathFileAlloc(std.testing.io, sub_path, std.testing.allocator);
}
+test "workspace module contexts qualify roots and cross-package project aliases" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try writeFixture(tmp.dir, "apps/api/src/main.zig", "");
+ try writeFixture(tmp.dir, "libs/shared/src/root.zig", "");
+ const api_root = try temporaryRoot(&tmp, "apps/api");
+ defer std.testing.allocator.free(api_root);
+ const shared_root = try temporaryRoot(&tmp, "libs/shared");
+ defer std.testing.allocator.free(shared_root);
+ const packages = [_]WorkspacePackageRoot{
+ .{ .id = "api", .path = api_root },
+ .{ .id = "shared", .path = shared_root },
+ };
+ const modules = [_]ModuleOverride{.{
+ .name = "shared",
+ .package_id = "shared",
+ .source_path = "src/root.zig",
+ }};
+ const unit = CompilationUnitOverride{
+ .id = "api-executable",
+ .package_id = "api",
+ .root_source_path = "src/main.zig",
+ .modules = &modules,
+ };
+ var context = common_error.ErrorContext.init(std.testing.allocator);
+ defer context.deinit();
+
+ var root = (try resolveWorkspaceModuleReference(
+ std.testing.allocator,
+ std.testing.io,
+ &packages,
+ "api",
+ unit,
+ makeReference("root", .root_module),
+ &context,
+ )).?;
+ defer root.deinit(std.testing.allocator);
+ try std.testing.expectEqual(ModuleResolutionStatus.resolved_project, root.status);
+ try std.testing.expectEqualStrings("api::src/main.zig", root.source_path.?);
+
+ var shared = (try resolveWorkspaceModuleReference(
+ std.testing.allocator,
+ std.testing.io,
+ &packages,
+ "api",
+ unit,
+ makeReference("shared", .named_module),
+ &context,
+ )).?;
+ defer shared.deinit(std.testing.allocator);
+ try std.testing.expectEqual(ModuleResolutionStatus.resolved_project, shared.status);
+ try std.testing.expectEqualStrings("shared::src/root.zig", shared.source_path.?);
+}
+
+test "workspace module contexts reject missing and external package identities" {
+ var context = common_error.ErrorContext.init(std.testing.allocator);
+ defer context.deinit();
+ const packages = [_]WorkspacePackageRoot{.{ .id = "api", .path = "." }};
+ const missing_modules = [_]ModuleOverride{.{
+ .name = "missing",
+ .package_id = "unknown",
+ .source_path = "src/root.zig",
+ }};
+ const missing_unit = CompilationUnitOverride{
+ .id = "api",
+ .package_id = "api",
+ .modules = &missing_modules,
+ };
+ try std.testing.expectError(error.InvalidModuleOverride, resolveWorkspaceModuleReference(
+ std.testing.allocator,
+ std.testing.io,
+ &packages,
+ "api",
+ missing_unit,
+ makeReference("missing", .named_module),
+ &context,
+ ));
+
+ context.clear();
+ const external_modules = [_]ModuleOverride{.{
+ .name = "dependency",
+ .package_id = "api",
+ .source_path = ".zig-cache/p/dependency/root.zig",
+ .origin = .package,
+ }};
+ try std.testing.expectError(error.InvalidModuleOverride, validateModuleResolutionOverrides(
+ .{ .compilation_units = &.{.{
+ .id = "api",
+ .package_id = "api",
+ .modules = &external_modules,
+ }} },
+ &context,
+ ));
+}
+
test "resolves roots and local aliases per compilation unit without executing build.zig" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/src/common/extraction/project_graph.zig b/src/common/extraction/project_graph.zig
index b2359e1..2ff3d25 100644
--- a/src/common/extraction/project_graph.zig
+++ b/src/common/extraction/project_graph.zig
@@ -11,6 +11,7 @@ const project_locator = @import("project_locator.zig");
const relative_resolver = @import("relative_resolver.zig");
const source_files = @import("source_files.zig");
const source_parser = @import("source_parser.zig");
+const workspace = @import("workspace.zig");
const Allocator = std.mem.Allocator;
const Io = std.Io;
@@ -98,17 +99,32 @@ fn extractProjectGraphObserved(
defer project.deinit(allocator);
var root_policy = try archignore.load(allocator, io, project.path, diagnostics);
defer root_policy.deinit(allocator);
+ var topology_storage = try workspace.load(
+ allocator,
+ io,
+ project.path,
+ options.workspace,
+ &root_policy,
+ diagnostics,
+ );
+ defer topology_storage.deinit(allocator);
+ const topology: ?*const workspace.Workspace = if (options.workspace.mode == .single_package)
+ null
+ else
+ &topology_storage;
+ if (topology) |resolved| try validateWorkspaceContexts(resolved, options.module_resolution, diagnostics);
if (clear_cache) {
graph_cache.clearGraphCache();
try logger.logCache("cache cleared");
}
- var cache_key = try graph_cache.buildGraphCacheKeyWithArchIgnore(
+ var cache_key = try graph_cache.buildGraphCacheKeyWithContext(
allocator,
io,
project.path,
options,
&root_policy,
+ topology,
diagnostics,
);
defer cache_key.deinit(allocator);
@@ -121,14 +137,25 @@ fn extractProjectGraphObserved(
}
try logger.logCache("cache miss");
- var graph = try extractLocatedGraph(
- allocator,
- io,
- project.path,
- options,
- &root_policy,
- diagnostics,
- );
+ var graph = if (topology) |resolved|
+ try extractWorkspaceGraph(
+ allocator,
+ io,
+ project.path,
+ resolved,
+ options,
+ &root_policy,
+ diagnostics,
+ )
+ else
+ try extractLocatedGraph(
+ allocator,
+ io,
+ project.path,
+ options,
+ &root_policy,
+ diagnostics,
+ );
errdefer graph.deinit(allocator);
graph_cache.storeGraphInCache(cache_key, graph) catch {
return diagnostics.failTechnical(.out_of_memory, "project_graph.cache_put", project.path, error.OutOfMemory);
@@ -234,6 +261,259 @@ fn extractLocatedGraph(
};
}
+const WorkspaceSource = struct {
+ source_path: []u8,
+ references: std.ArrayList(classifier.ClassifiedReference) = .empty,
+
+ fn deinit(self: *WorkspaceSource, allocator: Allocator) void {
+ allocator.free(self.source_path);
+ for (self.references.items) |*reference| reference.deinit(allocator);
+ self.references.deinit(allocator);
+ self.* = undefined;
+ }
+};
+
+fn extractWorkspaceGraph(
+ allocator: Allocator,
+ io: Io,
+ workspace_root: []const u8,
+ topology: *const workspace.Workspace,
+ options: ExtractionOptions,
+ root_policy: *const archignore.ArchIgnore,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!Graph {
+ var root_exclusions = try source_files.ExclusionSet.init(allocator, root_policy.patterns(), diagnostics);
+ defer root_exclusions.deinit();
+ var option_exclusions = try source_files.ExclusionSet.init(allocator, options.exclusions, diagnostics);
+ defer option_exclusions.deinit();
+
+ const package_roots = allocator.alloc(module_resolver.WorkspacePackageRoot, topology.items().len) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.allocate_packages", workspace_root, error.OutOfMemory);
+ };
+ defer allocator.free(package_roots);
+ for (topology.items(), package_roots) |package, *root| {
+ root.* = .{ .id = package.id, .path = package.path };
+ }
+
+ var owned_sources: std.ArrayList(WorkspaceSource) = .empty;
+ defer {
+ for (owned_sources.items) |*source| source.deinit(allocator);
+ owned_sources.deinit(allocator);
+ }
+
+ for (topology.items()) |*package| {
+ var files = try source_files.enumerateSourceFilesWithArchIgnore(
+ allocator,
+ io,
+ package.path,
+ .{},
+ &package.policy,
+ diagnostics,
+ );
+ defer files.deinit(allocator);
+
+ for (files.items()) |package_relative| {
+ const physical_path = package.workspaceRelative(allocator, package_relative) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.workspace_path", package_relative, error.OutOfMemory);
+ };
+ defer allocator.free(physical_path);
+ if (root_exclusions.excludes(physical_path, false) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.match_root_exclusion", physical_path, error.OutOfMemory);
+ }) continue;
+
+ const qualified_path = package.qualify(allocator, package_relative) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.qualify_source", package_relative, error.OutOfMemory);
+ };
+ var keep_qualified = false;
+ defer if (!keep_qualified) allocator.free(qualified_path);
+ if (option_exclusions.excludes(qualified_path, false) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.match_exclusion", qualified_path, error.OutOfMemory);
+ }) continue;
+
+ owned_sources.append(allocator, .{ .source_path = qualified_path }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.append_source", qualified_path, error.OutOfMemory);
+ };
+ keep_qualified = true;
+ const source = &owned_sources.items[owned_sources.items.len - 1];
+ if (!std.mem.endsWith(u8, package_relative, ".zig")) continue;
+ try extractWorkspaceSourceReferences(
+ allocator,
+ io,
+ package,
+ package_roots,
+ package_relative,
+ source,
+ options,
+ diagnostics,
+ );
+ }
+ }
+
+ const sources = allocator.alloc(graph_normalizer.SourceReferences, owned_sources.items.len) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.allocate_sources", workspace_root, error.OutOfMemory);
+ };
+ defer allocator.free(sources);
+ for (owned_sources.items, sources) |*owned, *source| {
+ source.* = .{ .source_path = owned.source_path, .references = owned.references.items };
+ }
+ return graph_normalizer.normalizeGraph(allocator, sources) catch |failure| switch (failure) {
+ error.OutOfMemory => diagnostics.failTechnical(.out_of_memory, "project_graph.normalize", workspace_root, failure),
+ error.ConflictingExternalClassification => diagnostics.failTechnical(
+ .internal_invariant,
+ "project_graph.normalize",
+ workspace_root,
+ failure,
+ ),
+ };
+}
+
+fn extractWorkspaceSourceReferences(
+ allocator: Allocator,
+ io: Io,
+ package: *const workspace.Package,
+ package_roots: []const module_resolver.WorkspacePackageRoot,
+ package_relative: []const u8,
+ source: *WorkspaceSource,
+ options: ExtractionOptions,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!void {
+ const absolute_path = std.fs.path.join(allocator, &.{ package.path, package_relative }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.source_path", source.source_path, error.OutOfMemory);
+ };
+ defer allocator.free(absolute_path);
+ const contents = std.Io.Dir.cwd().readFileAllocOptions(
+ io,
+ absolute_path,
+ allocator,
+ .limited(std.math.maxInt(usize)),
+ .of(u8),
+ 0,
+ ) catch |failure| return mapReadFailure(diagnostics, source.source_path, failure);
+ defer allocator.free(contents);
+
+ var parsed = try source_parser.parseSource(
+ allocator,
+ source.source_path,
+ contents,
+ options.strictness,
+ diagnostics,
+ );
+ defer parsed.deinit(allocator);
+ for (parsed.references.items) |reference| {
+ if (reference.kind == .embedded_file and !options.include_resources) continue;
+ if (reference.kind == .c_header and !options.include_c_imports) continue;
+ if (reference.inside_test_declaration and !options.include_test_imports) continue;
+
+ var classified_reference = try classifyWorkspace(
+ allocator,
+ io,
+ package,
+ package_roots,
+ package_relative,
+ reference,
+ options,
+ diagnostics,
+ );
+ source.references.append(allocator, classified_reference) catch {
+ classified_reference.deinit(allocator);
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.append_reference", source.source_path, error.OutOfMemory);
+ };
+ }
+}
+
+fn classifyWorkspace(
+ allocator: Allocator,
+ io: Io,
+ package: *const workspace.Package,
+ package_roots: []const module_resolver.WorkspacePackageRoot,
+ source_path: []const u8,
+ reference: source_parser.DependencyReference,
+ options: ExtractionOptions,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!classifier.ClassifiedReference {
+ return switch (reference.kind) {
+ .zig_file, .zon_file, .embedded_file => blk: {
+ var resolution = (try relative_resolver.resolveRelativeReference(
+ allocator,
+ io,
+ package.path,
+ source_path,
+ reference,
+ diagnostics,
+ )).?;
+ defer resolution.deinit(allocator);
+ if (resolution.status != .outside_project) {
+ const qualified = package.qualify(allocator, resolution.target) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.qualify_target", resolution.target, error.OutOfMemory);
+ };
+ allocator.free(resolution.target);
+ resolution.target = qualified;
+ }
+ break :blk classifier.classifyReference(allocator, .{ .file = .{
+ .reference = reference,
+ .resolution = resolution,
+ } }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.classify", source_path, error.OutOfMemory);
+ };
+ },
+ .named_module, .standard_library, .builtin_module, .root_module => blk: {
+ const unit = compilationUnitForWorkspace(package.id, source_path, options.module_resolution) orelse {
+ break :blk classifier.classifyReference(allocator, .{ .raw = reference }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.classify", source_path, error.OutOfMemory);
+ };
+ };
+ var resolution = (try module_resolver.resolveWorkspaceModuleReference(
+ allocator,
+ io,
+ package_roots,
+ package.id,
+ unit,
+ reference,
+ diagnostics,
+ )).?;
+ defer resolution.deinit(allocator);
+ break :blk classifier.classifyReference(allocator, .{ .module = resolution }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.classify", source_path, error.OutOfMemory);
+ };
+ },
+ .c_header => classifier.classifyReference(allocator, .{ .raw = reference }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "project_graph.classify", source_path, error.OutOfMemory);
+ },
+ };
+}
+
+fn validateWorkspaceContexts(
+ topology: *const workspace.Workspace,
+ overrides: module_resolver.ModuleResolutionOverrides,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!void {
+ for (overrides.compilation_units) |unit| {
+ const package_id = unit.package_id orelse return diagnostics.failUser(
+ .invalid_module_override,
+ "module.validate_workspace_unit",
+ unit.id,
+ null,
+ );
+ if (topology.find(package_id) == null) return diagnostics.failUser(
+ .invalid_module_override,
+ "module.validate_workspace_package",
+ package_id,
+ null,
+ );
+ for (unit.modules) |module| {
+ if (module.origin != .project) continue;
+ if (module.package_id) |target_package_id| {
+ if (topology.find(target_package_id) == null) return diagnostics.failUser(
+ .invalid_module_override,
+ "module.validate_workspace_package",
+ target_package_id,
+ null,
+ );
+ }
+ }
+ }
+}
+
fn classify(
allocator: Allocator,
io: Io,
@@ -301,6 +581,27 @@ fn compilationUnitFor(
return null;
}
+/// Workspace selection is confined to one package. An exact compilation root wins; otherwise a
+/// package with exactly one declared unit may safely use that context for all of its sources.
+fn compilationUnitForWorkspace(
+ package_id: []const u8,
+ source_path: []const u8,
+ overrides: module_resolver.ModuleResolutionOverrides,
+) ?module_resolver.CompilationUnitOverride {
+ var only: ?module_resolver.CompilationUnitOverride = null;
+ var count: usize = 0;
+ for (overrides.compilation_units) |unit| {
+ const unit_package_id = unit.package_id orelse continue;
+ if (!std.mem.eql(u8, unit_package_id, package_id)) continue;
+ count += 1;
+ only = unit;
+ if (unit.root_source_path) |root_source_path| {
+ if (std.mem.eql(u8, source_path, root_source_path)) return unit;
+ }
+ }
+ return if (count == 1) only else null;
+}
+
fn mapReadFailure(
diagnostics: *common_error.ErrorContext,
source_path: []const u8,
@@ -347,6 +648,132 @@ test "project graph extracts real relative imports and returns independent cache
try std.testing.expect(first.items()[0].source.ptr != second.items()[0].source.ptr);
}
+test "discovered workspace graph preserves package identity and cross-package dependencies" {
+ graph_cache.clearGraphCache();
+ defer graph_cache.clearGraphCache();
+ var diagnostics = common_error.ErrorContext.init(std.testing.allocator);
+ defer diagnostics.deinit();
+ const root_modules = [_]module_resolver.ModuleOverride{.{
+ .name = "api",
+ .package_id = "packages/api",
+ .source_path = "src/root.zig",
+ }};
+ const api_modules = [_]module_resolver.ModuleOverride{.{
+ .name = "shared",
+ .package_id = "packages/shared",
+ .source_path = "src/root.zig",
+ }};
+ const units = [_]module_resolver.CompilationUnitOverride{
+ .{
+ .id = "workspace-root",
+ .package_id = ".",
+ .root_source_path = "src/root.zig",
+ .modules = &root_modules,
+ },
+ .{
+ .id = "api-library",
+ .package_id = "packages/api",
+ .root_source_path = "src/root.zig",
+ .modules = &api_modules,
+ },
+ };
+ const base_options = ExtractionOptions{
+ .workspace = .{ .mode = .discover_packages },
+ .module_resolution = .{ .compilation_units = &units },
+ };
+
+ var graph = try extractProjectGraph(
+ std.testing.allocator,
+ std.testing.io,
+ "test/fixtures/workspace-multi",
+ ".",
+ base_options,
+ false,
+ &diagnostics,
+ );
+ defer graph.deinit(std.testing.allocator);
+ try std.testing.expect(graph.find(".::src/root.zig", "packages/api::src/root.zig") != null);
+ try std.testing.expect(graph.find(
+ "packages/api::src/root.zig",
+ "packages/api::src/helper.zig",
+ ) != null);
+ const cross_package = graph.find(
+ "packages/api::src/root.zig",
+ "packages/shared::src/root.zig",
+ ) orelse return error.TestExpectedEqual;
+ try std.testing.expect(!cross_package.external);
+ try std.testing.expect(graph.find("packages/api::src/root.zig", "packages/api::src/root.zig") != null);
+ try std.testing.expect(graph.find("packages/shared::src/root.zig", "packages/shared::src/root.zig") != null);
+ try std.testing.expect(graph.find(
+ "packages/api::src/ignored_by_package.zig",
+ "packages/api::src/ignored_by_package.zig",
+ ) == null);
+ try std.testing.expect(graph.find(
+ "packages/shared::src/ignored_by_root.zig",
+ "packages/shared::src/ignored_by_root.zig",
+ ) == null);
+ try std.testing.expect(graph.find("tools/worker::src/root.zig", "tools/worker::src/root.zig") != null);
+
+ var without_worker = try extractProjectGraph(
+ std.testing.allocator,
+ std.testing.io,
+ "test/fixtures/workspace-multi",
+ ".",
+ .{
+ .workspace = base_options.workspace,
+ .module_resolution = base_options.module_resolution,
+ .exclusions = &.{"tools/worker::**"},
+ },
+ false,
+ &diagnostics,
+ );
+ defer without_worker.deinit(std.testing.allocator);
+ try std.testing.expect(without_worker.find(
+ "tools/worker::src/root.zig",
+ "tools/worker::src/root.zig",
+ ) == null);
+}
+
+test "explicit workspace selections use caller package identities" {
+ graph_cache.clearGraphCache();
+ defer graph_cache.clearGraphCache();
+ var diagnostics = common_error.ErrorContext.init(std.testing.allocator);
+ defer diagnostics.deinit();
+ const selections = [_]workspace.WorkspacePackage{
+ .{ .id = "api", .path = "packages/api" },
+ .{ .id = "shared", .path = "packages/shared" },
+ };
+ const modules = [_]module_resolver.ModuleOverride{.{
+ .name = "shared",
+ .package_id = "shared",
+ .source_path = "src/root.zig",
+ }};
+ const units = [_]module_resolver.CompilationUnitOverride{.{
+ .id = "api-library",
+ .package_id = "api",
+ .root_source_path = "src/root.zig",
+ .modules = &modules,
+ }};
+
+ var graph = try extractProjectGraph(
+ std.testing.allocator,
+ std.testing.io,
+ "test/fixtures/workspace-multi",
+ ".",
+ .{
+ .workspace = .{ .mode = .explicit_packages, .packages = &selections },
+ .module_resolution = .{ .compilation_units = &units },
+ },
+ true,
+ &diagnostics,
+ );
+ defer graph.deinit(std.testing.allocator);
+ try std.testing.expect(graph.find("api::src/root.zig", "api::src/helper.zig") != null);
+ try std.testing.expect(graph.find("api::src/root.zig", "shared::src/root.zig") != null);
+ try std.testing.expect(graph.find(".::src/root.zig", ".::src/root.zig") == null);
+ try std.testing.expect(graph.find("tools/worker::src/root.zig", "tools/worker::src/root.zig") == null);
+}
+
test "editing root archignore invalidates cached extraction without an explicit clear" {
graph_cache.clearGraphCache();
defer graph_cache.clearGraphCache();
diff --git a/src/common/extraction/source_files.zig b/src/common/extraction/source_files.zig
index 36c5b1d..3676d7f 100644
--- a/src/common/extraction/source_files.zig
+++ b/src/common/extraction/source_files.zig
@@ -37,6 +37,37 @@ pub const SourceFiles = struct {
}
};
+/// Owned compiled ArchUnit-glob exclusions shared by source and workspace traversal.
+pub const ExclusionSet = struct {
+ allocator: Allocator,
+ filters: std.ArrayList(matching.Filter) = .empty,
+
+ pub fn init(
+ allocator: Allocator,
+ patterns: []const []const u8,
+ diagnostics: *ErrorContext,
+ ) common_error.ArchUnitError!ExclusionSet {
+ return .{
+ .allocator = allocator,
+ .filters = try compileExclusions(allocator, patterns, diagnostics),
+ };
+ }
+
+ pub fn deinit(self: *ExclusionSet) void {
+ for (self.filters.items) |*filter| filter.deinit();
+ self.filters.deinit(self.allocator);
+ self.* = undefined;
+ }
+
+ pub fn excludes(
+ self: *const ExclusionSet,
+ relative: []const u8,
+ is_directory: bool,
+ ) Allocator.Error!bool {
+ return isCustomExcluded(self.allocator, relative, is_directory, self.filters.items);
+ }
+};
+
pub fn enumerateSourceFiles(
allocator: Allocator,
io: Io,
@@ -127,11 +158,8 @@ fn enumerateCanonicalSourceFiles(
combined_patterns.appendSliceAssumeCapacity(options.exclusions);
combined_patterns.appendSliceAssumeCapacity(root_policy.patterns());
- var exclusions = try compileExclusions(allocator, combined_patterns.items, diagnostics);
- defer {
- for (exclusions.items) |*filter| filter.deinit();
- exclusions.deinit(allocator);
- }
+ var exclusions = try ExclusionSet.init(allocator, combined_patterns.items, diagnostics);
+ defer exclusions.deinit();
var root_dir = std.Io.Dir.openDirAbsolute(io, canonical_root, .{
.iterate = true,
@@ -156,7 +184,7 @@ fn enumerateCanonicalSourceFiles(
if (entry.kind == .directory) {
if (options.include_default_exclusions and isDefaultExcluded(entry.basename)) continue;
- if (isCustomExcluded(allocator, relative, true, exclusions.items) catch {
+ if (exclusions.excludes(relative, true) catch {
return diagnostics.failTechnical(.out_of_memory, "project.match_exclusion", relative, error.OutOfMemory);
}) continue;
if (options.stop_at_nested_projects and hasNestedMarker(io, entry) catch |failure| {
@@ -170,7 +198,7 @@ fn enumerateCanonicalSourceFiles(
// Symlinks/reparse points and non-regular filesystem entries are never followed.
if (entry.kind != .file or !isAnalyzable(relative, options.include_zon)) continue;
- if (isCustomExcluded(allocator, relative, false, exclusions.items) catch {
+ if (exclusions.excludes(relative, false) catch {
return diagnostics.failTechnical(.out_of_memory, "project.match_exclusion", relative, error.OutOfMemory);
}) continue;
@@ -252,7 +280,7 @@ fn isCustomExcluded(
return false;
}
-fn isDefaultExcluded(basename: []const u8) bool {
+pub fn isDefaultExcluded(basename: []const u8) bool {
for (default_excluded_directories) |excluded| {
if (std.mem.eql(u8, basename, excluded)) return true;
}
diff --git a/src/common/extraction/workspace.zig b/src/common/extraction/workspace.zig
new file mode 100644
index 0000000..62209e3
--- /dev/null
+++ b/src/common/extraction/workspace.zig
@@ -0,0 +1,548 @@
+const std = @import("std");
+
+const archignore = @import("archignore.zig");
+const common_error = @import("../error.zig");
+const common_path = @import("../path.zig");
+const source_files = @import("source_files.zig");
+const workspace_options = @import("workspace_options.zig");
+
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+pub const WorkspaceMode = workspace_options.WorkspaceMode;
+pub const WorkspaceOptions = workspace_options.WorkspaceOptions;
+pub const WorkspacePackage = workspace_options.WorkspacePackage;
+
+pub const Package = struct {
+ id: []const u8,
+ relative_path: []const u8,
+ path: [:0]u8,
+ manifest_path: []const u8,
+ manifest_fingerprint: [32]u8,
+ policy: archignore.ArchIgnore,
+
+ pub fn deinit(self: *Package, allocator: Allocator) void {
+ allocator.free(self.id);
+ allocator.free(self.relative_path);
+ allocator.free(self.path);
+ allocator.free(self.manifest_path);
+ self.policy.deinit(allocator);
+ self.* = undefined;
+ }
+
+ pub fn qualify(self: *const Package, allocator: Allocator, relative: []const u8) Allocator.Error![]u8 {
+ const normalized = try common_path.normalize(allocator, relative);
+ defer allocator.free(normalized);
+ return std.fmt.allocPrint(allocator, "{s}::{s}", .{ self.id, normalized });
+ }
+
+ pub fn workspaceRelative(
+ self: *const Package,
+ allocator: Allocator,
+ package_relative: []const u8,
+ ) Allocator.Error![]u8 {
+ if (std.mem.eql(u8, self.relative_path, ".")) {
+ return common_path.normalize(allocator, package_relative);
+ }
+ const joined = try std.fs.path.join(allocator, &.{ self.relative_path, package_relative });
+ defer allocator.free(joined);
+ return common_path.normalize(allocator, joined);
+ }
+};
+
+pub const Workspace = struct {
+ packages: std.ArrayList(Package) = .empty,
+
+ pub fn deinit(self: *Workspace, allocator: Allocator) void {
+ for (self.packages.items) |*package| package.deinit(allocator);
+ self.packages.deinit(allocator);
+ self.* = undefined;
+ }
+
+ pub fn items(self: *const Workspace) []const Package {
+ return self.packages.items;
+ }
+
+ pub fn find(self: *const Workspace, id: []const u8) ?*const Package {
+ for (self.packages.items) |*package| {
+ if (std.mem.eql(u8, package.id, id)) return package;
+ }
+ return null;
+ }
+};
+
+/// Resolves an explicit or discovered workspace into one sorted, owned topology snapshot.
+pub fn load(
+ allocator: Allocator,
+ io: Io,
+ workspace_root: []const u8,
+ options: WorkspaceOptions,
+ root_policy: *const archignore.ArchIgnore,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!Workspace {
+ if (options.mode == .single_package) {
+ if (options.packages.len != 0) return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_options",
+ options.packages[0].path,
+ error.PackagesRequireExplicitMode,
+ );
+ return .{};
+ }
+ if (options.mode == .discover_packages and options.packages.len != 0) {
+ return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_options",
+ options.packages[0].path,
+ error.DiscoveryRejectsExplicitPackages,
+ );
+ }
+ if (options.mode == .explicit_packages and options.packages.len == 0) {
+ return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_options",
+ workspace_root,
+ error.EmptyWorkspace,
+ );
+ }
+
+ const canonical_root = canonicalDirectory(allocator, io, workspace_root, diagnostics) catch |failure| return failure;
+ defer allocator.free(canonical_root);
+ var result = Workspace{};
+ errdefer result.deinit(allocator);
+ switch (options.mode) {
+ .single_package => unreachable,
+ .explicit_packages => for (options.packages) |selection| {
+ try appendExplicitPackage(
+ allocator,
+ io,
+ canonical_root,
+ selection,
+ &result,
+ diagnostics,
+ );
+ },
+ .discover_packages => try discoverPackages(
+ allocator,
+ io,
+ canonical_root,
+ root_policy,
+ &result,
+ diagnostics,
+ ),
+ }
+ if (result.packages.items.len == 0) return diagnostics.failUser(
+ .invalid_options,
+ "workspace.load",
+ canonical_root,
+ error.NoPackageManifests,
+ );
+ sortPackages(&result);
+ try validateUniquePackages(&result, diagnostics);
+ return result;
+}
+
+fn appendExplicitPackage(
+ allocator: Allocator,
+ io: Io,
+ canonical_root: []const u8,
+ selection: WorkspacePackage,
+ result: *Workspace,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!void {
+ try validateIdentity(selection.id, diagnostics);
+ if (selection.path.len == 0) return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_package_path",
+ selection.path,
+ error.EmptyPackagePath,
+ );
+ const resolved = std.fs.path.resolve(allocator, &.{ canonical_root, selection.path }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.resolve_package", selection.path, error.OutOfMemory);
+ };
+ defer allocator.free(resolved);
+ const canonical_package = canonicalDirectory(allocator, io, resolved, diagnostics) catch |failure| return failure;
+ defer allocator.free(canonical_package);
+ const relative = try relativeInsideRoot(allocator, canonical_root, canonical_package, diagnostics);
+ defer allocator.free(relative);
+ const normalized_id = common_path.normalize(allocator, selection.id) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.validate_package_id", selection.id, error.OutOfMemory);
+ };
+ defer allocator.free(normalized_id);
+ try appendPackage(
+ allocator,
+ io,
+ canonical_root,
+ normalized_id,
+ relative,
+ result,
+ diagnostics,
+ );
+}
+
+fn discoverPackages(
+ allocator: Allocator,
+ io: Io,
+ canonical_root: []const u8,
+ root_policy: *const archignore.ArchIgnore,
+ result: *Workspace,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!void {
+ var exclusions = try source_files.ExclusionSet.init(allocator, root_policy.patterns(), diagnostics);
+ defer exclusions.deinit();
+ var root_dir = std.Io.Dir.openDirAbsolute(io, canonical_root, .{
+ .iterate = true,
+ .follow_symlinks = false,
+ }) catch |failure| return mapFileFailure(diagnostics, "workspace.discover", canonical_root, failure);
+ defer root_dir.close(io);
+ var walker = root_dir.walkSelectively(allocator) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.discover", canonical_root, error.OutOfMemory);
+ };
+ defer walker.deinit();
+
+ while (walker.next(io) catch |failure| {
+ return mapFileFailure(diagnostics, "workspace.discover", canonical_root, failure);
+ }) |entry| {
+ const relative = common_path.normalize(allocator, entry.path) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.discover", entry.path, error.OutOfMemory);
+ };
+ defer allocator.free(relative);
+ if (entry.kind == .directory) {
+ if (source_files.isDefaultExcluded(entry.basename)) continue;
+ if (exclusions.excludes(relative, true) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.match_exclusion", relative, error.OutOfMemory);
+ }) continue;
+ walker.enter(io, entry) catch |failure| {
+ return mapFileFailure(diagnostics, "workspace.discover", relative, failure);
+ };
+ continue;
+ }
+ if (entry.kind != .file or !std.mem.eql(u8, entry.basename, "build.zig.zon")) continue;
+ if (exclusions.excludes(relative, false) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.match_exclusion", relative, error.OutOfMemory);
+ }) continue;
+ const package_relative = std.fs.path.dirname(relative) orelse ".";
+ try appendPackage(
+ allocator,
+ io,
+ canonical_root,
+ package_relative,
+ package_relative,
+ result,
+ diagnostics,
+ );
+ }
+}
+
+fn appendPackage(
+ allocator: Allocator,
+ io: Io,
+ canonical_root: []const u8,
+ id: []const u8,
+ relative: []const u8,
+ result: *Workspace,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError!void {
+ try validateIdentity(id, diagnostics);
+ const resolved = std.fs.path.resolve(allocator, &.{ canonical_root, relative }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.resolve_package", relative, error.OutOfMemory);
+ };
+ defer allocator.free(resolved);
+ const canonical_package = canonicalDirectory(allocator, io, resolved, diagnostics) catch |failure| return failure;
+ errdefer allocator.free(canonical_package);
+ normalizeSeparators(canonical_package);
+ const manifest_native = std.fs.path.join(allocator, &.{ canonical_package, "build.zig.zon" }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.read_manifest", relative, error.OutOfMemory);
+ };
+ defer allocator.free(manifest_native);
+ const manifest_contents = std.Io.Dir.cwd().readFileAllocOptions(
+ io,
+ manifest_native,
+ allocator,
+ .limited(std.math.maxInt(usize)),
+ .of(u8),
+ 0,
+ ) catch |failure| return mapManifestFailure(diagnostics, manifest_native, failure);
+ defer allocator.free(manifest_contents);
+ var digest: [32]u8 = undefined;
+ var hash = std.crypto.hash.sha2.Sha256.init(.{});
+ hash.update(manifest_contents);
+ hash.final(&digest);
+
+ const owned_id = allocator.dupe(u8, id) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.load", id, error.OutOfMemory);
+ };
+ errdefer allocator.free(owned_id);
+ const normalized_relative = common_path.normalize(allocator, relative) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.load", relative, error.OutOfMemory);
+ };
+ errdefer allocator.free(normalized_relative);
+ const manifest_path = common_path.normalize(allocator, manifest_native) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.load", manifest_native, error.OutOfMemory);
+ };
+ errdefer allocator.free(manifest_path);
+ var policy = try archignore.load(allocator, io, canonical_package, diagnostics);
+ errdefer policy.deinit(allocator);
+ result.packages.append(allocator, .{
+ .id = owned_id,
+ .relative_path = normalized_relative,
+ .path = canonical_package,
+ .manifest_path = manifest_path,
+ .manifest_fingerprint = digest,
+ .policy = policy,
+ }) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.load", relative, error.OutOfMemory);
+ };
+}
+
+fn canonicalDirectory(
+ allocator: Allocator,
+ io: Io,
+ path: []const u8,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError![:0]u8 {
+ const canonical = std.Io.Dir.cwd().realPathFileAlloc(io, path, allocator) catch |failure| {
+ return mapFileFailure(diagnostics, "workspace.resolve_package", path, failure);
+ };
+ errdefer allocator.free(canonical);
+ const stat = std.Io.Dir.cwd().statFile(io, canonical, .{}) catch |failure| {
+ return mapFileFailure(diagnostics, "workspace.resolve_package", path, failure);
+ };
+ if (stat.kind != .directory) return diagnostics.failUser(
+ .invalid_project_path,
+ "workspace.resolve_package",
+ path,
+ error.NotDir,
+ );
+ return canonical;
+}
+
+fn relativeInsideRoot(
+ allocator: Allocator,
+ canonical_root: []const u8,
+ canonical_package: []const u8,
+ diagnostics: *common_error.ErrorContext,
+) common_error.ArchUnitError![]u8 {
+ const native = std.fs.path.relative(
+ allocator,
+ canonical_root,
+ null,
+ canonical_root,
+ canonical_package,
+ ) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.resolve_package", canonical_package, error.OutOfMemory);
+ };
+ defer allocator.free(native);
+ const normalized = common_path.normalize(allocator, native) catch {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.resolve_package", canonical_package, error.OutOfMemory);
+ };
+ if (std.mem.eql(u8, normalized, "..") or std.mem.startsWith(u8, normalized, "../") or std.fs.path.isAbsolute(normalized)) {
+ defer allocator.free(normalized);
+ return diagnostics.failUser(
+ .invalid_project_path,
+ "workspace.resolve_package",
+ canonical_package,
+ error.OutsideWorkspace,
+ );
+ }
+ return normalized;
+}
+
+fn validateIdentity(id: []const u8, diagnostics: *common_error.ErrorContext) common_error.ArchUnitError!void {
+ if (id.len == 0 or std.mem.indexOf(u8, id, "::") != null or std.mem.indexOfScalar(u8, id, 0) != null) {
+ return diagnostics.failUser(.invalid_options, "workspace.validate_package_id", id, error.InvalidPackageId);
+ }
+}
+
+fn validateUniquePackages(workspace: *const Workspace, diagnostics: *common_error.ErrorContext) common_error.ArchUnitError!void {
+ for (workspace.packages.items, 0..) |package, index| {
+ for (workspace.packages.items[0..index]) |prior| {
+ if (std.mem.eql(u8, prior.id, package.id)) return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_package_id",
+ package.id,
+ error.DuplicatePackageId,
+ );
+ if (std.mem.eql(u8, prior.path, package.path)) return diagnostics.failUser(
+ .invalid_options,
+ "workspace.validate_package_path",
+ package.relative_path,
+ error.DuplicatePackagePath,
+ );
+ }
+ }
+}
+
+fn sortPackages(workspace: *Workspace) void {
+ std.mem.sort(Package, workspace.packages.items, {}, struct {
+ fn lessThan(_: void, left: Package, right: Package) bool {
+ const id_order = std.mem.order(u8, left.id, right.id);
+ if (id_order != .eq) return id_order == .lt;
+ return std.mem.order(u8, left.relative_path, right.relative_path) == .lt;
+ }
+ }.lessThan);
+}
+
+fn mapManifestFailure(
+ diagnostics: *common_error.ErrorContext,
+ path: []const u8,
+ failure: anyerror,
+) common_error.ArchUnitError {
+ if (failure == error.OutOfMemory) {
+ return diagnostics.failTechnical(.out_of_memory, "workspace.read_manifest", path, failure);
+ }
+ return switch (failure) {
+ error.FileNotFound, error.NotDir => diagnostics.failUser(
+ .invalid_project_path,
+ "workspace.read_manifest",
+ path,
+ failure,
+ ),
+ else => diagnostics.failTechnical(.file_system, "workspace.read_manifest", path, failure),
+ };
+}
+
+fn mapFileFailure(
+ diagnostics: *common_error.ErrorContext,
+ operation: []const u8,
+ path: []const u8,
+ failure: anyerror,
+) common_error.ArchUnitError {
+ if (failure == error.OutOfMemory) return diagnostics.failTechnical(.out_of_memory, operation, path, failure);
+ return switch (failure) {
+ error.FileNotFound, error.NotDir => diagnostics.failUser(.invalid_project_path, operation, path, failure),
+ else => diagnostics.failTechnical(.file_system, operation, path, failure),
+ };
+}
+
+fn normalizeSeparators(path: []u8) void {
+ for (path) |*byte| if (byte.* == '\\') {
+ byte.* = '/';
+ };
+}
+
+fn writeManifest(dir: std.Io.Dir, path: []const u8, marker: u8) !void {
+ if (std.fs.path.dirname(path)) |parent| try dir.createDirPath(std.testing.io, parent);
+ const contents = try std.fmt.allocPrint(
+ std.testing.allocator,
+ ".{{ .name = .fixture_{c}, .version = \"0.0.0\", .fingerprint = 0x1111111111111111 }}",
+ .{marker},
+ );
+ defer std.testing.allocator.free(contents);
+ try dir.writeFile(std.testing.io, .{ .sub_path = path, .data = contents });
+}
+
+fn temporaryRoot(tmp: *std.testing.TmpDir) ![:0]u8 {
+ return tmp.dir.realPathFileAlloc(std.testing.io, ".", std.testing.allocator);
+}
+
+test "discovery finds nested manifests while pruning defaults and root policy" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try writeManifest(tmp.dir, "build.zig.zon", 'r');
+ try writeManifest(tmp.dir, "packages/api/build.zig.zon", 'a');
+ try writeManifest(tmp.dir, "packages/api/plugins/deep/build.zig.zon", 'd');
+ try writeManifest(tmp.dir, "packages/shared/build.zig.zon", 's');
+ try writeManifest(tmp.dir, "vendor/hidden/build.zig.zon", 'v');
+ try writeManifest(tmp.dir, ".zig-cache/hidden/build.zig.zon", 'c');
+ try writeManifest(tmp.dir, "ignored/build.zig.zon", 'i');
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = archignore.file_name, .data = "ignored/**\n" });
+ const root = try temporaryRoot(&tmp);
+ defer std.testing.allocator.free(root);
+ var diagnostics = common_error.ErrorContext.init(std.testing.allocator);
+ defer diagnostics.deinit();
+ var root_policy = try archignore.load(std.testing.allocator, std.testing.io, root, &diagnostics);
+ defer root_policy.deinit(std.testing.allocator);
+
+ var workspace = try load(
+ std.testing.allocator,
+ std.testing.io,
+ root,
+ .{ .mode = .discover_packages },
+ &root_policy,
+ &diagnostics,
+ );
+ defer workspace.deinit(std.testing.allocator);
+ const expected = [_][]const u8{ ".", "packages/api", "packages/api/plugins/deep", "packages/shared" };
+ try std.testing.expectEqual(expected.len, workspace.items().len);
+ for (expected, workspace.items()) |id, package| try std.testing.expectEqualStrings(id, package.id);
+ const qualified = try workspace.items()[1].qualify(std.testing.allocator, "src/main.zig");
+ defer std.testing.allocator.free(qualified);
+ try std.testing.expectEqualStrings("packages/api::src/main.zig", qualified);
+}
+
+test "explicit packages own caller ids and reject duplicate canonical roots" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try writeManifest(tmp.dir, "apps/api/build.zig.zon", 'a');
+ try writeManifest(tmp.dir, "libs/shared/build.zig.zon", 's');
+ const root = try temporaryRoot(&tmp);
+ defer std.testing.allocator.free(root);
+ var diagnostics = common_error.ErrorContext.init(std.testing.allocator);
+ defer diagnostics.deinit();
+ var root_policy = try archignore.load(std.testing.allocator, std.testing.io, root, &diagnostics);
+ defer root_policy.deinit(std.testing.allocator);
+ const selections = [_]WorkspacePackage{
+ .{ .id = "api", .path = "apps/api" },
+ .{ .id = "shared", .path = "libs/shared" },
+ };
+ var workspace = try load(
+ std.testing.allocator,
+ std.testing.io,
+ root,
+ .{ .mode = .explicit_packages, .packages = &selections },
+ &root_policy,
+ &diagnostics,
+ );
+ defer workspace.deinit(std.testing.allocator);
+ try std.testing.expect(workspace.find("api") != null);
+ try std.testing.expectEqualStrings("apps/api", workspace.find("api").?.relative_path);
+
+ const duplicate_paths = [_]WorkspacePackage{
+ .{ .id = "first", .path = "apps/api" },
+ .{ .id = "second", .path = "apps/api/." },
+ };
+ try std.testing.expectError(
+ error.InvalidOptions,
+ load(
+ std.testing.allocator,
+ std.testing.io,
+ root,
+ .{ .mode = .explicit_packages, .packages = &duplicate_paths },
+ &root_policy,
+ &diagnostics,
+ ),
+ );
+ try std.testing.expectEqualStrings("workspace.validate_package_path", diagnostics.diagnostic.?.operation);
+}
+
+fn exerciseAllocationFailures(allocator: Allocator, root: []const u8) !void {
+ var diagnostics = common_error.ErrorContext.init(allocator);
+ defer diagnostics.deinit();
+ var root_policy = try archignore.load(allocator, std.testing.io, root, &diagnostics);
+ defer root_policy.deinit(allocator);
+ var workspace = try load(
+ allocator,
+ std.testing.io,
+ root,
+ .{ .mode = .discover_packages },
+ &root_policy,
+ &diagnostics,
+ );
+ defer workspace.deinit(allocator);
+ try std.testing.expectEqual(@as(usize, 2), workspace.items().len);
+}
+
+test "workspace snapshots clean up every allocation failure" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try writeManifest(tmp.dir, "build.zig.zon", 'r');
+ try writeManifest(tmp.dir, "packages/api/build.zig.zon", 'a');
+ const root = try temporaryRoot(&tmp);
+ defer std.testing.allocator.free(root);
+ try std.testing.checkAllAllocationFailures(
+ std.testing.allocator,
+ exerciseAllocationFailures,
+ .{root},
+ );
+}
diff --git a/src/common/extraction/workspace_options.zig b/src/common/extraction/workspace_options.zig
new file mode 100644
index 0000000..eece9ce
--- /dev/null
+++ b/src/common/extraction/workspace_options.zig
@@ -0,0 +1,25 @@
+const std = @import("std");
+
+pub const WorkspaceMode = enum {
+ single_package,
+ explicit_packages,
+ discover_packages,
+};
+
+/// One borrowed package selection relative to the located workspace root.
+pub const WorkspacePackage = struct {
+ id: []const u8,
+ path: []const u8,
+};
+
+/// Workspace scope is opt-in so existing package-relative graph identifiers remain compatible.
+pub const WorkspaceOptions = struct {
+ mode: WorkspaceMode = .single_package,
+ packages: []const WorkspacePackage = &.{},
+};
+
+test "workspace options retain compatible single-package defaults" {
+ const options = WorkspaceOptions{};
+ try std.testing.expectEqual(WorkspaceMode.single_package, options.mode);
+ try std.testing.expectEqual(@as(usize, 0), options.packages.len);
+}
diff --git a/src/common/fluentapi/check_options.zig b/src/common/fluentapi/check_options.zig
index 521ef88..f0389a2 100644
--- a/src/common/fluentapi/check_options.zig
+++ b/src/common/fluentapi/check_options.zig
@@ -14,6 +14,9 @@ pub const LoggingOptions = logging.LoggingOptions;
pub const CompilationUnitOverride = module_resolver.CompilationUnitOverride;
pub const BuildGraphMode = extraction_options.BuildGraphMode;
pub const ExtractionOptions = extraction_options.ExtractionOptions;
+pub const WorkspaceMode = extraction_options.WorkspaceMode;
+pub const WorkspaceOptions = extraction_options.WorkspaceOptions;
+pub const WorkspacePackage = extraction_options.WorkspacePackage;
pub const ModuleOrigin = module_resolver.ModuleOrigin;
pub const ModuleOverride = module_resolver.ModuleOverride;
pub const ModuleResolutionOverrides = module_resolver.ModuleResolutionOverrides;
diff --git a/src/root.zig b/src/root.zig
index 0c657ac..7040a3d 100644
--- a/src/root.zig
+++ b/src/root.zig
@@ -89,6 +89,10 @@ pub const Checkable = fluentapi.Checkable;
pub const CompilationUnitOverride = extraction.CompilationUnitOverride;
pub const CycleProjectionError = projection.CycleProjectionError;
pub const ExtractionOptions = extraction.ExtractionOptions;
+pub const WorkspaceMode = extraction.WorkspaceMode;
+pub const WorkspaceOptions = extraction.WorkspaceOptions;
+pub const WorkspacePackage = extraction.WorkspacePackage;
+pub const WorkspacePackageRoot = extraction.WorkspacePackageRoot;
pub const Filter = matching.Filter;
pub const MatchingMode = matching.MatchingMode;
pub const MapFunction = projection.MapFunction;
@@ -106,6 +110,7 @@ pub const ModuleOrigin = extraction.ModuleOrigin;
pub const ModuleOverride = extraction.ModuleOverride;
pub const ModuleResolutionOverrides = extraction.ModuleResolutionOverrides;
pub const ModuleResolutionStatus = extraction.ModuleResolutionStatus;
+pub const resolveWorkspaceModuleReference = extraction.resolveWorkspaceModuleReference;
pub const Mood = assertion.Mood;
pub const MatchingViolation = assertion.MatchingViolation;
pub const MetricComparison = assertion.MetricComparison;
diff --git a/test/fixtures/workspace-multi/.archignore b/test/fixtures/workspace-multi/.archignore
new file mode 100644
index 0000000..84a2e67
--- /dev/null
+++ b/test/fixtures/workspace-multi/.archignore
@@ -0,0 +1,2 @@
+# The workspace-root policy addresses physical, root-relative paths.
+packages/shared/src/ignored_by_root.zig
diff --git a/test/fixtures/workspace-multi/build.zig.zon b/test/fixtures/workspace-multi/build.zig.zon
new file mode 100644
index 0000000..8e9c857
--- /dev/null
+++ b/test/fixtures/workspace-multi/build.zig.zon
@@ -0,0 +1,7 @@
+.{
+ .name = .workspace_fixture,
+ .version = "0.0.0",
+ .fingerprint = 0xa100000000000001,
+ .minimum_zig_version = "0.16.0",
+ .paths = .{ "build.zig.zon", "src", "packages", "tools" },
+}
diff --git a/test/fixtures/workspace-multi/packages/api/.archignore b/test/fixtures/workspace-multi/packages/api/.archignore
new file mode 100644
index 0000000..688ec70
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/api/.archignore
@@ -0,0 +1 @@
+src/ignored_by_package.zig
diff --git a/test/fixtures/workspace-multi/packages/api/build.zig.zon b/test/fixtures/workspace-multi/packages/api/build.zig.zon
new file mode 100644
index 0000000..10c825e
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/api/build.zig.zon
@@ -0,0 +1,7 @@
+.{
+ .name = .api,
+ .version = "0.0.0",
+ .fingerprint = 0xa100000000000002,
+ .minimum_zig_version = "0.16.0",
+ .paths = .{ "build.zig.zon", "src" },
+}
diff --git a/test/fixtures/workspace-multi/packages/api/src/helper.zig b/test/fixtures/workspace-multi/packages/api/src/helper.zig
new file mode 100644
index 0000000..29233bb
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/api/src/helper.zig
@@ -0,0 +1 @@
+pub fn touch() void {}
diff --git a/test/fixtures/workspace-multi/packages/api/src/ignored_by_package.zig b/test/fixtures/workspace-multi/packages/api/src/ignored_by_package.zig
new file mode 100644
index 0000000..7be310b
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/api/src/ignored_by_package.zig
@@ -0,0 +1,3 @@
+comptime {
+ @compileError("package-local .archignore must exclude this source");
+}
diff --git a/test/fixtures/workspace-multi/packages/api/src/root.zig b/test/fixtures/workspace-multi/packages/api/src/root.zig
new file mode 100644
index 0000000..a8df507
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/api/src/root.zig
@@ -0,0 +1,7 @@
+const helper = @import("helper.zig");
+const shared = @import("shared");
+
+pub fn run() void {
+ helper.touch();
+ shared.touch();
+}
diff --git a/test/fixtures/workspace-multi/packages/shared/build.zig.zon b/test/fixtures/workspace-multi/packages/shared/build.zig.zon
new file mode 100644
index 0000000..76e5c26
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/shared/build.zig.zon
@@ -0,0 +1,7 @@
+.{
+ .name = .shared,
+ .version = "0.0.0",
+ .fingerprint = 0xa100000000000003,
+ .minimum_zig_version = "0.16.0",
+ .paths = .{ "build.zig.zon", "src" },
+}
diff --git a/test/fixtures/workspace-multi/packages/shared/src/ignored_by_root.zig b/test/fixtures/workspace-multi/packages/shared/src/ignored_by_root.zig
new file mode 100644
index 0000000..3a69e51
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/shared/src/ignored_by_root.zig
@@ -0,0 +1,3 @@
+comptime {
+ @compileError("workspace-root .archignore must exclude this source");
+}
diff --git a/test/fixtures/workspace-multi/packages/shared/src/root.zig b/test/fixtures/workspace-multi/packages/shared/src/root.zig
new file mode 100644
index 0000000..29233bb
--- /dev/null
+++ b/test/fixtures/workspace-multi/packages/shared/src/root.zig
@@ -0,0 +1 @@
+pub fn touch() void {}
diff --git a/test/fixtures/workspace-multi/src/root.zig b/test/fixtures/workspace-multi/src/root.zig
new file mode 100644
index 0000000..faa3a37
--- /dev/null
+++ b/test/fixtures/workspace-multi/src/root.zig
@@ -0,0 +1,5 @@
+const api = @import("api");
+
+pub fn start() void {
+ api.run();
+}
diff --git a/test/fixtures/workspace-multi/tools/worker/build.zig.zon b/test/fixtures/workspace-multi/tools/worker/build.zig.zon
new file mode 100644
index 0000000..8b8e25a
--- /dev/null
+++ b/test/fixtures/workspace-multi/tools/worker/build.zig.zon
@@ -0,0 +1,7 @@
+.{
+ .name = .worker,
+ .version = "0.0.0",
+ .fingerprint = 0xa100000000000004,
+ .minimum_zig_version = "0.16.0",
+ .paths = .{ "build.zig.zon", "src" },
+}
diff --git a/test/fixtures/workspace-multi/tools/worker/src/root.zig b/test/fixtures/workspace-multi/tools/worker/src/root.zig
new file mode 100644
index 0000000..6263372
--- /dev/null
+++ b/test/fixtures/workspace-multi/tools/worker/src/root.zig
@@ -0,0 +1 @@
+pub fn work() void {}