@native-sdk/cli 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/build/app.zig +265 -65
  2. package/build/ts_run.mjs +6 -8
  3. package/build.zig +292 -349
  4. package/package.json +13 -11
  5. package/packages/core/compile-surface/core.ts +559 -0
  6. package/packages/core/package-lock.json +375 -12
  7. package/packages/core/package.json +9 -6
  8. package/packages/core/scripts/compiler_typecheck.mjs +58 -0
  9. package/packages/core/scripts/gen_case_tables.mjs +130 -0
  10. package/packages/core/scripts/gen_declarations.mjs +97 -0
  11. package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
  12. package/packages/core/scripts/stage_external_core.mjs +148 -0
  13. package/packages/core/sdk/core.d.ts +363 -0
  14. package/packages/core/sdk/events.d.ts +65 -0
  15. package/packages/core/sdk/text.d.ts +51 -0
  16. package/packages/core/src/checker.ts +3 -3
  17. package/packages/core/src/cli.ts +40 -38
  18. package/packages/core/src/contract.ts +749 -0
  19. package/packages/core/src/devhost.ts +4 -3
  20. package/packages/core/src/diagnostics.ts +5 -7
  21. package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
  22. package/packages/core/src/infer.ts +1 -1
  23. package/packages/core/src/typed_ast.ts +16 -15
  24. package/packages/core/src/wyhash.ts +79 -0
  25. package/skill-data/ts-core/SKILL.md +29 -29
  26. package/src/runtime/ts_core_host.zig +38 -38
  27. package/src/runtime/ts_ui_app.zig +12 -12
  28. package/src/tooling/manifest.zig +32 -0
  29. package/src/tooling/raw_manifest.zig +4 -0
  30. package/src/tooling/templates.zig +25 -20
  31. package/src/tooling/ts_core.zig +55 -34
  32. package/src/tooling/verbs.zig +1 -1
  33. package/tools/corewire/core_abi.zig +169 -0
  34. package/tools/corewire/emit.zig +2418 -0
  35. package/tools/corewire/emit_facade.zig +3984 -0
  36. package/tools/corewire/emit_profile.zig +501 -0
  37. package/tools/corewire/main.zig +561 -0
  38. package/tools/corewire/shim_rt.zig +632 -0
  39. package/tools/corewire/sidecar.zig +2507 -0
  40. package/packages/core/rt/rt.zig +0 -1986
  41. package/packages/core/src/emitter.ts +0 -11898
@@ -0,0 +1,561 @@
1
+ //! corewire — the contract-sidecar shim generator.
2
+ //!
3
+ //! corewire --sidecar core.contract.json --out core_shim.zig
4
+ //! corewire --sidecar core.contract.json --facade core_facade.ts --profile core_profile.json --effective-sidecar effective.contract.json
5
+ //! corewire --sidecar core.contract.json --check
6
+ //!
7
+ //! Reads the JSON contract sidecar a core-mode compile emits beside the
8
+ //! compiled object, validates it (schema rules V1-V14, teaching
9
+ //! refusals with exact field paths on stderr), and writes the Zig
10
+ //! mirror module the app wiring imports (see emit.zig for what the
11
+ //! mirror carries). `--facade` writes the TypeScript projection,
12
+ //! `--profile` the library-mode compiler profile that builds it
13
+ //! (emit_profile.zig). `--check` validates and stops — the checker-tier
14
+ //! entry point.
15
+ //!
16
+ //! The build stages the output beside tools/corewire/shim_rt.zig and
17
+ //! tools/corewire/core_abi.zig; the generated module imports both
18
+ //! relatively, the way transpiler output imports its staged rt.zig.
19
+
20
+ const std = @import("std");
21
+ const sidecar_mod = @import("sidecar.zig");
22
+ const emit_mod = @import("emit.zig");
23
+ const emit_facade_mod = @import("emit_facade.zig");
24
+ const emit_profile_mod = @import("emit_profile.zig");
25
+
26
+ const usage =
27
+ \\usage: corewire --sidecar <core.contract.json> (--out <core_shim.zig> | --facade <core_facade.ts> | --profile <core_profile.json> | --effective-sidecar <effective.contract.json> | --check) [--f64-slot <path>]...
28
+ \\
29
+ \\Generate the Zig mirror module (core_shim.zig), the TypeScript
30
+ \\projection (core_facade.ts), the library-mode compiler profile
31
+ \\(core_profile.json), and/or the effective sidecar after projection
32
+ \\overrides for a compiled core, or validate the input sidecar alone
33
+ \\(--check). Generation outputs combine; --check stands alone.
34
+ \\
35
+ \\--f64-slot <path> carries the named attested integer slot as f64 for
36
+ \\this whole invocation (facade, profile, and mirror alike): a slot
37
+ \\whose values reach the f64-exact boundary (2^53) has no honest i64
38
+ \\declaration on the compiled side, so the caller states the demotion
39
+ \\explicitly and every projection stays consistent. The path must name
40
+ \\an attested slot — a misspelling would silently demote nothing.
41
+ \\
42
+ ;
43
+
44
+ pub fn main(init: std.process.Init) !void {
45
+ const arena = init.arena.allocator();
46
+ const args = try init.minimal.args.toSlice(arena);
47
+
48
+ var stderr_buffer: [4096]u8 = undefined;
49
+ var stderr_writer = std.Io.File.stderr().writerStreaming(init.io, &stderr_buffer);
50
+ const stderr = &stderr_writer.interface;
51
+
52
+ var sidecar_path: ?[]const u8 = null;
53
+ var out_path: ?[]const u8 = null;
54
+ var facade_path: ?[]const u8 = null;
55
+ var profile_path: ?[]const u8 = null;
56
+ var effective_sidecar_path: ?[]const u8 = null;
57
+ var check_only = false;
58
+ var f64_slots: std.ArrayListUnmanaged([]const u8) = .empty;
59
+ var index: usize = 1;
60
+ while (index < args.len) : (index += 1) {
61
+ const arg = args[index];
62
+ if (std.mem.eql(u8, arg, "--sidecar") and index + 1 < args.len) {
63
+ index += 1;
64
+ sidecar_path = args[index];
65
+ } else if (std.mem.eql(u8, arg, "--out") and index + 1 < args.len) {
66
+ index += 1;
67
+ out_path = args[index];
68
+ } else if (std.mem.eql(u8, arg, "--facade") and index + 1 < args.len) {
69
+ index += 1;
70
+ facade_path = args[index];
71
+ } else if (std.mem.eql(u8, arg, "--profile") and index + 1 < args.len) {
72
+ index += 1;
73
+ profile_path = args[index];
74
+ } else if (std.mem.eql(u8, arg, "--effective-sidecar") and index + 1 < args.len) {
75
+ index += 1;
76
+ effective_sidecar_path = args[index];
77
+ } else if (std.mem.eql(u8, arg, "--f64-slot") and index + 1 < args.len) {
78
+ index += 1;
79
+ try f64_slots.append(arena, args[index]);
80
+ } else if (std.mem.eql(u8, arg, "--check")) {
81
+ check_only = true;
82
+ } else {
83
+ try stderr.print("corewire: unknown argument \"{s}\"\n\n{s}", .{ arg, usage });
84
+ try stderr.flush();
85
+ std.process.exit(2);
86
+ }
87
+ }
88
+ const input = sidecar_path orelse {
89
+ try stderr.print("{s}", .{usage});
90
+ try stderr.flush();
91
+ std.process.exit(2);
92
+ };
93
+ // Either validate-only, or at least one generation target — never
94
+ // both (a checker that writes files is not a checker).
95
+ const generates = out_path != null or facade_path != null or profile_path != null or effective_sidecar_path != null;
96
+ if (generates == check_only) {
97
+ try stderr.print("{s}", .{usage});
98
+ try stderr.flush();
99
+ std.process.exit(2);
100
+ }
101
+ // Distinct paths only: the projections must not overwrite each
102
+ // other, and no output may destroy the input contract. Compared
103
+ // lexically normalized (cwd-resolved, `.`/`..` folded) — filesystem
104
+ // identities beyond spelling (symlinks, hard links) stay the
105
+ // caller's responsibility.
106
+ const input_resolved = try canonicalSpelling(init.io, arena, input);
107
+ // The staging PREFIX spellings join the checked set: outputs land
108
+ // by rename from exclusively-created `<path>.corewire-tmp.<nonce>`
109
+ // files, and a sidecar sitting on the prefix spelling is close
110
+ // enough to a claimed name to refuse outright.
111
+ const paths = [_]?[]const u8{
112
+ out_path,
113
+ facade_path,
114
+ profile_path,
115
+ effective_sidecar_path,
116
+ if (out_path) |path| try std.fmt.allocPrint(arena, "{s}.corewire-tmp", .{path}) else null,
117
+ if (facade_path) |path| try std.fmt.allocPrint(arena, "{s}.corewire-tmp", .{path}) else null,
118
+ if (profile_path) |path| try std.fmt.allocPrint(arena, "{s}.corewire-tmp", .{path}) else null,
119
+ if (effective_sidecar_path) |path| try std.fmt.allocPrint(arena, "{s}.corewire-tmp", .{path}) else null,
120
+ };
121
+ var resolved: [paths.len]?[]const u8 = @splat(null);
122
+ for (paths, 0..) |maybe_path, path_index| {
123
+ const path = maybe_path orelse continue;
124
+ resolved[path_index] = try canonicalSpelling(init.io, arena, path);
125
+ }
126
+ for (resolved, 0..) |maybe_path, path_index| {
127
+ const path = maybe_path orelse continue;
128
+ // Case-insensitively: the default volumes on two of the three
129
+ // desktop platforms fold case, so differently-cased spellings
130
+ // of one file must count as aliases everywhere (refusing a
131
+ // case-only distinction on a case-sensitive volume costs
132
+ // nothing anyone wants).
133
+ if (std.ascii.eqlIgnoreCase(path, input_resolved)) {
134
+ try stderr.print("corewire: output {s} names the sidecar itself — generating would destroy the input contract\n", .{path});
135
+ try stderr.flush();
136
+ std.process.exit(2);
137
+ }
138
+ // Spelling checks cannot see every filesystem aliasing (Unicode
139
+ // case folding, links), so ask the filesystem: an output whose
140
+ // path already resolves to the sidecar's own file is the same
141
+ // refusal, whatever the spelling.
142
+ if (sameExistingFile(init.io, path, input_resolved)) {
143
+ try stderr.print("corewire: output {s} resolves to the sidecar's own file — generating would destroy the input contract\n", .{path});
144
+ try stderr.flush();
145
+ std.process.exit(2);
146
+ }
147
+ for (resolved[path_index + 1 ..]) |maybe_other| {
148
+ const other = maybe_other orelse continue;
149
+ if (std.ascii.eqlIgnoreCase(path, other) or sameExistingFile(init.io, path, other)) {
150
+ try stderr.print("corewire: two outputs name one file ({s}) — the later projection would overwrite the earlier\n", .{path});
151
+ try stderr.flush();
152
+ std.process.exit(2);
153
+ }
154
+ }
155
+ }
156
+
157
+ const source = std.Io.Dir.cwd().readFileAlloc(init.io, input, arena, .limited(sidecar_mod.max_sidecar_bytes)) catch |err| {
158
+ try stderr.print("corewire: cannot read {s}: {t}\n", .{ input, err });
159
+ try stderr.flush();
160
+ std.process.exit(1);
161
+ };
162
+
163
+ var diags = sidecar_mod.Diagnostics{ .arena = arena };
164
+ var parsed = sidecar_mod.read(arena, source, &diags) catch |err| switch (err) {
165
+ error.Refused => {
166
+ try diags.write(input, stderr);
167
+ try stderr.flush();
168
+ std.process.exit(1);
169
+ },
170
+ error.OutOfMemory => return err,
171
+ };
172
+
173
+ // Caller-stated f64 demotions apply to the parsed contract before
174
+ // any projection, so the facade's encoders, the profile's
175
+ // declarations, and the attestation list stay consistent by
176
+ // construction: the slot's type-table spelling rewrites to f64 and
177
+ // its attestation entry drops.
178
+ if (f64_slots.items.len > 0) {
179
+ var kept: std.ArrayListUnmanaged(sidecar_mod.IntegerSlot) = .empty;
180
+ for (f64_slots.items) |slot_path| {
181
+ const listed = for (parsed.integer_slots) |slot| {
182
+ if (std.mem.eql(u8, slot.slot, slot_path)) break true;
183
+ } else false;
184
+ if (!listed) {
185
+ try stderr.print("corewire: --f64-slot {s} names no attested integer slot of this contract — a misspelling would silently demote nothing; check the contract's integer_slots\n", .{slot_path});
186
+ try stderr.flush();
187
+ std.process.exit(2);
188
+ }
189
+ if (!demoteSlotToF64(parsed, slot_path)) {
190
+ try stderr.print("corewire: --f64-slot {s} does not name a record field slot (Container.field) — only record-field slots demote today; a message-arm or helper slot demotion needs its own emitter support\n", .{slot_path});
191
+ try stderr.flush();
192
+ std.process.exit(2);
193
+ }
194
+ }
195
+ for (parsed.integer_slots) |slot| {
196
+ const demoted = for (f64_slots.items) |slot_path| {
197
+ if (std.mem.eql(u8, slot.slot, slot_path)) break true;
198
+ } else false;
199
+ if (!demoted) try kept.append(arena, slot);
200
+ }
201
+ parsed.integer_slots = kept.items;
202
+ }
203
+
204
+ // `--check` runs the FULL pipeline (every projection) and discards
205
+ // the text: a sidecar must never pass the checker and then refuse at
206
+ // generate time (emitter-level rules — emission-name collisions
207
+ // above all — are part of the contract's validity).
208
+ const generated: []const u8 = emit_mod.emit(arena, parsed, &diags) catch |err| switch (err) {
209
+ error.Refused => {
210
+ try diags.write(input, stderr);
211
+ try stderr.flush();
212
+ std.process.exit(1);
213
+ },
214
+ error.OutOfMemory => return err,
215
+ };
216
+ // The profile targets the facade module as its entry, so emitting a
217
+ // profile runs the facade emitter's own refusal checks even when no
218
+ // facade file is written — a sidecar must never yield a profile
219
+ // whose referenced facade then refuses to generate.
220
+ const facade: ?[]const u8 = if (check_only or facade_path != null or profile_path != null)
221
+ emit_facade_mod.emitFacade(arena, parsed, &diags) catch |err| switch (err) {
222
+ error.Refused => {
223
+ try diags.write(input, stderr);
224
+ try stderr.flush();
225
+ std.process.exit(1);
226
+ },
227
+ error.OutOfMemory => return err,
228
+ }
229
+ else
230
+ null;
231
+ // The profile names the facade module as its entry, resolved
232
+ // against the profile file's own directory (the compilation root):
233
+ // when both are generated in one invocation the emitted spelling is
234
+ // the --facade path made profile-relative, and the conventional
235
+ // name otherwise.
236
+ const profile: ?[]const u8 = if (check_only or profile_path != null) blk: {
237
+ const entry = if (facade_path != null and profile_path != null)
238
+ profileRelativeEntry(init, stderr, profile_path.?, facade_path.?) catch |err| switch (err) {
239
+ error.Unrelatable => std.process.exit(2),
240
+ else => return err,
241
+ }
242
+ else if (facade_path) |path|
243
+ std.fs.path.basename(path)
244
+ else
245
+ emit_profile_mod.default_entry;
246
+ // The profile is a JSON document, and JSON text carries UTF-8
247
+ // only: a filename with other bytes would not survive the trip
248
+ // through any conforming consumer, so it refuses here instead
249
+ // of naming a file nothing can find.
250
+ if (!std.unicode.utf8ValidateSlice(entry)) {
251
+ try stderr.print("corewire: the profile's entry spelling \"{s}\" is not valid UTF-8 — the profile is a JSON document and JSON text carries UTF-8 only; rename the facade file\n", .{entry});
252
+ try stderr.flush();
253
+ std.process.exit(2);
254
+ }
255
+ break :blk emit_profile_mod.emitProfile(arena, parsed, entry, &diags) catch |err| switch (err) {
256
+ error.Refused => {
257
+ try diags.write(input, stderr);
258
+ try stderr.flush();
259
+ std.process.exit(1);
260
+ },
261
+ error.OutOfMemory => return err,
262
+ };
263
+ } else null;
264
+
265
+ // The staged contract twin: preserve the input document's complete
266
+ // additive vocabulary while applying the same explicit demotions the
267
+ // typed projections above consumed. This is the sidecar that truthfully
268
+ // belongs beside a generated facade/profile pair.
269
+ const effective_sidecar: ?[]const u8 = if (effective_sidecar_path != null)
270
+ try sidecar_mod.projectF64SlotsJson(arena, source, f64_slots.items)
271
+ else
272
+ null;
273
+
274
+ // Warnings (unknown additive fields) surface even on success.
275
+ try diags.write(input, stderr);
276
+ try stderr.flush();
277
+
278
+ // Stage-then-commit: ALL projections write completely into
279
+ // exclusively-created staging files before any rename, so a write
280
+ // failure can never leave a fresh shim beside a stale sibling. The
281
+ // renames remain separate filesystem operations — a failure between
282
+ // them reports the files as a possibly skewed set and the nonzero
283
+ // exit makes the caller regenerate; concurrent invocations aimed at
284
+ // ONE output path are the caller's serialization to provide (the
285
+ // build graph never shares output directories between steps).
286
+ const Output = struct {
287
+ flag: []const u8,
288
+ path: []const u8,
289
+ data: []const u8,
290
+ staged: []const u8 = "",
291
+ };
292
+ var outputs_buffer: [4]Output = undefined;
293
+ var output_count: usize = 0;
294
+ if (out_path) |path| {
295
+ outputs_buffer[output_count] = .{ .flag = "--out", .path = path, .data = generated };
296
+ output_count += 1;
297
+ }
298
+ if (facade_path) |path| {
299
+ outputs_buffer[output_count] = .{ .flag = "--facade", .path = path, .data = facade.? };
300
+ output_count += 1;
301
+ }
302
+ if (profile_path) |path| {
303
+ outputs_buffer[output_count] = .{ .flag = "--profile", .path = path, .data = profile.? };
304
+ output_count += 1;
305
+ }
306
+ if (effective_sidecar_path) |path| {
307
+ outputs_buffer[output_count] = .{ .flag = "--effective-sidecar", .path = path, .data = effective_sidecar.? };
308
+ output_count += 1;
309
+ }
310
+ const outputs = outputs_buffer[0..output_count];
311
+
312
+ for (outputs, 0..) |*output, output_index| {
313
+ // Earlier staging files exist now, so a filesystem-level alias
314
+ // of two output paths (Unicode case folding, links) gets one
315
+ // more net before any rename.
316
+ for (outputs[0..output_index]) |earlier| {
317
+ if (sameExistingFile(init.io, output.path, earlier.path)) {
318
+ for (outputs[0..output_index]) |staged| std.Io.Dir.cwd().deleteFile(init.io, staged.staged) catch {};
319
+ try stderr.print("corewire: {s} {s} resolves to the {s} file — the later projection would overwrite the earlier\n", .{ output.flag, output.path, earlier.flag });
320
+ try stderr.flush();
321
+ std.process.exit(2);
322
+ }
323
+ }
324
+ output.staged = stageOutput(init, stderr, output.path, output.data) catch |err| {
325
+ // Sibling projections were already staged; leave no stray
326
+ // staging file behind ANY failure shape.
327
+ for (outputs[0..output_index]) |staged| std.Io.Dir.cwd().deleteFile(init.io, staged.staged) catch {};
328
+ switch (err) {
329
+ error.Staging => std.process.exit(1),
330
+ else => return err,
331
+ }
332
+ };
333
+ }
334
+
335
+ for (outputs, 0..) |output, output_index| {
336
+ // Committed outputs now EXIST, so aliases no spelling check can
337
+ // see (filesystem Unicode normalization above all) finally
338
+ // resolve: a target that reaches a just-committed sibling
339
+ // refuses instead of replacing it.
340
+ for (outputs[0..output_index]) |earlier| {
341
+ if (sameExistingFile(init.io, output.path, earlier.path)) {
342
+ for (outputs[output_index..]) |staged| std.Io.Dir.cwd().deleteFile(init.io, staged.staged) catch {};
343
+ try stderr.print("corewire: {s} {s} resolves to the file {s} just wrote — the later projection would overwrite the earlier\n", .{ output.flag, output.path, earlier.flag });
344
+ try stderr.flush();
345
+ std.process.exit(2);
346
+ }
347
+ }
348
+ std.Io.Dir.cwd().rename(output.staged, std.Io.Dir.cwd(), output.path, init.io) catch |err| {
349
+ for (outputs[output_index..]) |staged| std.Io.Dir.cwd().deleteFile(init.io, staged.staged) catch {};
350
+ if (output_index > 0) {
351
+ try stderr.print("corewire: cannot write {s}: {t} — earlier projections were already replaced, so the outputs on disk may be from different generations; re-run to restore the set\n", .{ output.path, err });
352
+ } else {
353
+ try stderr.print("corewire: cannot write {s}: {t}\n", .{ output.path, err });
354
+ }
355
+ try stderr.flush();
356
+ std.process.exit(1);
357
+ };
358
+ }
359
+ }
360
+
361
+ /// Rewrite one record-field slot's type-table spelling from i64 to f64
362
+ /// (through one optional wrapper). Returns false when the path is not a
363
+ /// `Container.field` record slot whose field spells i64.
364
+ fn demoteSlotToF64(sidecar: sidecar_mod.Sidecar, slot_path: []const u8) bool {
365
+ const dot = std.mem.indexOfScalar(u8, slot_path, '.') orelse return false;
366
+ const container = slot_path[0..dot];
367
+ const field_name = slot_path[dot + 1 ..];
368
+ if (std.mem.indexOfScalar(u8, field_name, '.') != null) return false;
369
+ for (sidecar.types.structs) |entry| {
370
+ if (!std.mem.eql(u8, entry.name, container)) continue;
371
+ for (entry.fields) |*field| {
372
+ if (!std.mem.eql(u8, field.name, field_name)) continue;
373
+ const mutable: *sidecar_mod.Field = @constCast(field);
374
+ switch (field.type) {
375
+ .i64 => {
376
+ mutable.type = .f64;
377
+ return true;
378
+ },
379
+ .optional => |inner| {
380
+ if (inner.* != .i64) return false;
381
+ const mutable_inner: *sidecar_mod.TypeRef = @constCast(inner);
382
+ mutable_inner.* = .f64;
383
+ return true;
384
+ },
385
+ else => return false,
386
+ }
387
+ }
388
+ }
389
+ return false;
390
+ }
391
+
392
+ /// The facade path as the profile's entry spelling: relative to the
393
+ /// profile file's directory (the compilation root a profile consumer
394
+ /// resolves against), POSIX separators. A pair that cannot relate
395
+ /// (distinct roots) refuses with a teaching — a wrong spelling would
396
+ /// point the consumer at a file that does not exist.
397
+ fn profileRelativeEntry(init: std.process.Init, stderr: *std.Io.Writer, profile_path: []const u8, facade_path: []const u8) ![]const u8 {
398
+ const arena = init.arena.allocator();
399
+ const profile_dir = std.fs.path.dirname(profile_path) orelse ".";
400
+ var buffer: [std.fs.max_path_bytes]u8 = undefined;
401
+ const cwd_len = std.Io.Dir.cwd().realPath(init.io, &buffer) catch 0;
402
+ const cwd: []const u8 = if (cwd_len == 0) "." else buffer[0..cwd_len];
403
+ // The environment rides along for the Windows resolver: a
404
+ // drive-RELATIVE spelling (C:foo) resolves against that drive's own
405
+ // working directory, which lives in the environment.
406
+ const related = try std.fs.path.relative(arena, cwd, init.environ_map, profile_dir, facade_path);
407
+ // Paths on distinct roots have no relative spelling (the resolver
408
+ // hands back an absolute path instead): a profile consumer resolves
409
+ // the entry against the profile's directory, so an unreachable
410
+ // facade refuses rather than emitting a spelling that names nothing.
411
+ if (related.len == 0 or std.fs.path.isAbsolute(related)) {
412
+ try stderr.print("corewire: --facade {s} has no path relative to the --profile directory {s} — the profile's entry must reach the facade from beside the profile; emit them under one root\n", .{ facade_path, profile_dir });
413
+ try stderr.flush();
414
+ return error.Unrelatable;
415
+ }
416
+ // Separator conversion is a WINDOWS translation only: on POSIX a
417
+ // backslash is an ordinary filename byte and must ride verbatim.
418
+ if (std.fs.path.sep != std.fs.path.sep_windows) return related;
419
+ const posix = try arena.dupe(u8, related);
420
+ for (posix) |*char| {
421
+ if (char.* == std.fs.path.sep_windows) char.* = std.fs.path.sep_posix;
422
+ }
423
+ return posix;
424
+ }
425
+
426
+ /// A path spelling fit for alias comparison: components canonicalize
427
+ /// one at a time against the filesystem, so `..` applies to the REAL
428
+ /// parent (never lexically across a symlink), symlinked or case-folded
429
+ /// ancestors land on one spelling, and a not-yet-existing tail rides
430
+ /// verbatim — two spellings of one future file compare equal even
431
+ /// before the file exists.
432
+ fn canonicalSpelling(io: std.Io, arena: std.mem.Allocator, path: []const u8) ![]const u8 {
433
+ var buffer: [std.fs.max_path_bytes]u8 = undefined;
434
+ // Platform-aware parsing: the component iterator understands the
435
+ // native roots and separators (drive and UNC spellings included),
436
+ // so two spellings of one root land on one prefix.
437
+ var components = std.fs.path.componentIterator(path);
438
+ const root = components.root();
439
+ if (root != null and !std.fs.path.isAbsolute(path)) {
440
+ // A drive-RELATIVE spelling (C:foo) names a file under that
441
+ // drive's own working directory, which this process cannot
442
+ // resolve portably; folding it under the drive root would
443
+ // manufacture false aliases against drive-absolute spellings.
444
+ // Keep it lexical — the existence-based nets and rename landing
445
+ // still guard the writes.
446
+ return std.fs.path.resolve(arena, &.{path});
447
+ }
448
+ var base: []const u8 = if (root) |prefix|
449
+ try arena.dupe(u8, prefix)
450
+ else blk: {
451
+ const len = std.Io.Dir.cwd().realPath(io, &buffer) catch break :blk try arena.dupe(u8, ".");
452
+ break :blk try arena.dupe(u8, buffer[0..len]);
453
+ };
454
+ var exists = true;
455
+ while (components.next()) |component| {
456
+ if (std.mem.eql(u8, component.name, ".")) continue;
457
+ if (std.mem.eql(u8, component.name, "..")) {
458
+ // `base` carries no symlinks once canonical, so its lexical
459
+ // parent IS its real parent; a `..` under a nonexistent
460
+ // tail unwinds the tail it just added — and may land back
461
+ // on EXISTING ground, so canonicalization must resume (a
462
+ // symlink after the pop would otherwise ride unresolved).
463
+ base = std.fs.path.dirname(base) orelse base;
464
+ if (!exists) {
465
+ if (std.Io.Dir.cwd().realPathFile(io, base, &buffer)) |len| {
466
+ base = try arena.dupe(u8, buffer[0..len]);
467
+ exists = true;
468
+ } else |_| {}
469
+ }
470
+ continue;
471
+ }
472
+ const candidate = try std.fs.path.join(arena, &.{ base, component.name });
473
+ if (exists) {
474
+ if (std.Io.Dir.cwd().realPathFile(io, candidate, &buffer)) |len| {
475
+ base = try arena.dupe(u8, buffer[0..len]);
476
+ continue;
477
+ } else |_| {
478
+ exists = false;
479
+ }
480
+ }
481
+ base = candidate;
482
+ }
483
+ return base;
484
+ }
485
+
486
+ /// Whether two paths currently resolve to one existing file, by asking
487
+ /// the filesystem for canonical paths: the alias net behind the lexical
488
+ /// checks (Unicode case folding, symlinks — a canonical path is unique
489
+ /// per volume, so distinct files can never compare equal). Nonexistent
490
+ /// paths are distinct. Hard links carry distinct canonical paths and
491
+ /// pass this check — harmless by construction, because outputs land by
492
+ /// rename (writeOutput), which replaces a directory entry and never
493
+ /// writes through one.
494
+ fn sameExistingFile(io: std.Io, a: []const u8, b: []const u8) bool {
495
+ var buffer_a: [std.fs.max_path_bytes]u8 = undefined;
496
+ var buffer_b: [std.fs.max_path_bytes]u8 = undefined;
497
+ const len_a = std.Io.Dir.cwd().realPathFile(io, a, &buffer_a) catch return false;
498
+ const len_b = std.Io.Dir.cwd().realPathFile(io, b, &buffer_b) catch return false;
499
+ if (std.mem.eql(u8, buffer_a[0..len_a], buffer_b[0..len_b])) return true;
500
+ // Distinct canonical paths can still name one DIRECTORY ENTRY where
501
+ // a mount exposes a directory twice (bind mounts) — the case the
502
+ // rename landing cannot save, because replacing the entry through
503
+ // either spelling replaces it for both. A hard link is the
504
+ // opposite: two entries for one file, and the rename replaces only
505
+ // the named entry, so it must NOT trip this check. Same entry means
506
+ // same parent directory and same on-disk basename; the portable
507
+ // stat carries no device id, so parent identity is inferred from
508
+ // full metadata agreement (a coincidental match across volumes
509
+ // merely refuses a spelling nobody needs).
510
+ const canon_a = buffer_a[0..len_a];
511
+ const canon_b = buffer_b[0..len_b];
512
+ if (!std.mem.eql(u8, std.fs.path.basename(canon_a), std.fs.path.basename(canon_b))) return false;
513
+ const parent_a = std.fs.path.dirname(canon_a) orelse return false;
514
+ const parent_b = std.fs.path.dirname(canon_b) orelse return false;
515
+ const stat_a = std.Io.Dir.cwd().statFile(io, parent_a, .{}) catch return false;
516
+ const stat_b = std.Io.Dir.cwd().statFile(io, parent_b, .{}) catch return false;
517
+ return stat_a.inode == stat_b.inode and stat_a.kind == stat_b.kind and
518
+ stat_a.size == stat_b.size and stat_a.nlink == stat_b.nlink and
519
+ stat_a.mtime.nanoseconds == stat_b.mtime.nanoseconds and
520
+ stat_a.ctime.nanoseconds == stat_b.ctime.nanoseconds;
521
+ }
522
+
523
+ /// Write `data` into an exclusively-created, uniquely-named staging
524
+ /// file beside `out` and return its path; the caller commits by rename.
525
+ /// Exclusive creation can never truncate an existing entry (whatever it
526
+ /// links to), and the unique suffix keeps concurrent invocations off
527
+ /// each other's bytes. Failures print their teaching and return
528
+ /// error.Staging so the caller can delete sibling staging files.
529
+ fn stageOutput(init: std.process.Init, stderr: *std.Io.Writer, out: []const u8, data: []const u8) ![]const u8 {
530
+ if (std.fs.path.dirname(out)) |dir| {
531
+ std.Io.Dir.cwd().createDirPath(init.io, dir) catch {};
532
+ }
533
+ const arena = init.arena.allocator();
534
+ var nonce: [8]u8 = undefined;
535
+ init.io.random(&nonce);
536
+ const temp_path = try std.fmt.allocPrint(arena, "{s}.corewire-tmp.{x}", .{ out, &nonce });
537
+ const staging = std.Io.Dir.cwd().createFile(init.io, temp_path, .{ .exclusive = true }) catch |err| {
538
+ try stderr.print("corewire: cannot stage {s}: {t}\n", .{ temp_path, err });
539
+ try stderr.flush();
540
+ return error.Staging;
541
+ };
542
+ var write_failed = false;
543
+ {
544
+ defer staging.close(init.io);
545
+ var buffer: [4096]u8 = undefined;
546
+ var writer = staging.writerStreaming(init.io, &buffer);
547
+ writer.interface.writeAll(data) catch {
548
+ write_failed = true;
549
+ };
550
+ if (!write_failed) writer.interface.flush() catch {
551
+ write_failed = true;
552
+ };
553
+ }
554
+ if (write_failed) {
555
+ std.Io.Dir.cwd().deleteFile(init.io, temp_path) catch {};
556
+ try stderr.print("corewire: cannot write {s}\n", .{temp_path});
557
+ try stderr.flush();
558
+ return error.Staging;
559
+ }
560
+ return temp_path;
561
+ }