-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathxlings.cppm
More file actions
1620 lines (1418 loc) · 68.1 KB
/
Copy pathxlings.cppm
File metadata and controls
1620 lines (1418 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// mcpp.xlings — unified abstraction layer for all xlings (external package
// manager) interactions. Consolidates NDJSON event parsing, subprocess
// command building, path helpers, and bootstrap progress types that were
// previously scattered across config.cppm, package_fetcher.cppm, cli.cppm,
// flags.cppm, ninja_backend.cppm, and stdmod.cppm.
//
// This module is a LEAF dependency: it only imports `std` and
// `mcpp.pm.compat`. It must NOT import mcpp.config or any other mcpp module.
module;
#include <cstdio> // stderr
#include <cstdlib>
export module mcpp.xlings;
import std;
import mcpp.pm.compat;
import mcpp.pm.index_contract;
import mcpp.pm.index_snapshot;
import mcpp.platform;
import mcpp.log;
export namespace mcpp::xlings {
// ─── Env: resolved xlings binary + home directory ───────────────────
struct Env {
std::filesystem::path binary; // xlings binary path
std::filesystem::path home; // XLINGS_HOME directory
std::filesystem::path projectDir; // XLINGS_PROJECT_DIR (empty = global mode)
};
// ─── Pinned version constants ───────────────────────────────────────
namespace pinned {
inline constexpr std::string_view kPatchelfVersion = "0.18.0";
inline constexpr std::string_view kNinjaVersion = "1.12.1";
// The xlings a release bundles at <install>/registry/bin/xlings, and the
// version `mcpp self env` reports.
//
// This is the SOURCE OF TRUTH for every xlings pin in .github/, and
// `.github/tools/check_version_pins.sh` enforces that — CI fails if any
// pin disagrees. This comment used to instead name three files to keep
// in lock-step by hand; that list was already missing both composite
// actions, which is how CI's sandbox sat on 0.4.30 unnoticed while
// everything else had moved on. Don't reintroduce a hand-maintained list.
inline constexpr std::string_view kXlingsVersion = "2026.8.7.1";
inline constexpr std::string_view kNasmVersion = "3.02";
}
// ─── Path helpers (pure functions, no subprocess) ───────────────────
namespace paths {
// xpkgs base: env.home / "data" / "xpkgs"
std::filesystem::path xpkgs_base(const Env& env);
// sandbox bin: env.home / "subos" / "default" / "bin"
std::filesystem::path sandbox_bin(const Env& env);
// sandbox sysroot: env.home / "subos" / "default"
std::filesystem::path sysroot(const Env& env);
// xim tool root: xpkgs_base / "xim-x-<tool>"
std::filesystem::path xim_tool_root(const Env& env, std::string_view tool);
// xim tool versioned: xpkgs_base / "xim-x-<tool>" / "<version>"
std::filesystem::path xim_tool(const Env& env, std::string_view tool,
std::string_view version);
// From compiler binary, climb parent dirs to find "xpkgs" directory.
// Replaces 3 duplicate implementations in flags.cppm, ninja_backend.cppm,
// stdmod.cppm.
std::optional<std::filesystem::path>
xpkgs_from_compiler(const std::filesystem::path& compilerBin);
// The subos a TOOLCHAIN belongs to (mcpp#352).
//
// Derived from the compiler rather than from a global: a build already
// knows which home its toolchain came from, and asking a second source
// would let the two disagree — the "one question, several answerers" shape
// that the same investigation found four times over on the xlings side.
//
// A PURE derivation, with no environment override in it. That is not an
// omission: this value gets written into the build cache, and an override
// means "for this invocation", not "for this build from now on". Caching
// one would make a single `MCPP_SUBOS_DIR=… mcpp run` silently change
// where every later run looked. Which subos a RUN should use is a
// different question, answered in execute.cppm.
//
// Empty when the toolchain is not sandbox-resident — a system compiler is
// the user's explicit choice of the host world, and there is no subos
// speaking for it.
std::optional<std::filesystem::path>
subos_dir_of(const std::filesystem::path& compilerBin);
// Find a sibling xim tool relative to a compiler binary.
// e.g. find_sibling_tool(gcc_bin, "binutils") returns highest version
// dir of xim-x-binutils.
std::optional<std::filesystem::path>
find_sibling_tool(const std::filesystem::path& compilerBin,
std::string_view tool);
// Find a binary inside a sibling tool (e.g. binutils/bin/ar,
// ninja/ninja).
std::optional<std::filesystem::path>
find_sibling_binary(const std::filesystem::path& compilerBin,
std::string_view tool,
std::string_view binaryRelPath);
// Find a sibling package across all index prefixes.
// e.g. find_sibling_package(gcc_bin, "linux-headers") searches for
// xim-x-linux-headers, scode-x-linux-headers, etc.
// Metadata-only dirs (.xim-installed/.xpkg.lua husks left by delegating
// index packages) never qualify; when requiredRelPath is given, only a
// version dir containing it qualifies (the payload may live under a
// different prefix than the husk — issue #120).
std::optional<std::filesystem::path>
find_sibling_package(const std::filesystem::path& compilerBin,
std::string_view packageName,
std::string_view requiredRelPath = {});
// xpkgs root of the ACTIVE mcpp home ($MCPP_HOME or ~/.mcpp). Payload
// discovery consults this in addition to compiler siblings: an
// inherited/symlinked compiler resolves into its owner home, while the
// active home may own (or have just installed) the sysroot payloads.
std::optional<std::filesystem::path> active_home_xpkgs();
// Like find_sibling_tool, but anchored at the active home's xpkgs.
// Searches across index prefixes (xim-x-, scode-x-, …) with the same
// husk/requiredRelPath rules as find_sibling_package.
std::optional<std::filesystem::path>
find_home_tool(std::string_view tool,
std::string_view requiredRelPath = {});
// index data root: env.home / "data"
std::filesystem::path index_data(const Env& env);
// sandbox init marker: env.home / "subos" / "default" / ".xlings.json"
std::filesystem::path sandbox_init_marker(const Env& env);
} // namespace paths
// ─── Shell quoting ──────────────────────────────────────────────────
// Shell-escape (single-quote) a string for the command line.
std::string shq(std::string_view s);
// ─── Shell command builders ─────────────────────────────────────────
// Build the standard xlings command prefix with proper env vars.
// cd '<home>' && env -u XLINGS_PROJECT_DIR PATH=<sandbox_bin>:"$PATH"
// XLINGS_HOME='<home>' '<binary>'
std::string build_command_prefix(const Env& env);
// Build full xlings interface command.
// <prefix> interface <capability> --args '<argsJson>' 2>/dev/null
std::string build_interface_command(const Env& env,
std::string_view capability,
std::string_view argsJson);
// ─── NDJSON event types ─────────────────────────────────────────────
struct ProgressEvent {
std::string phase; // "download", "extract", "configure", ...
int percent; // 0..100
std::string message;
};
struct LogEvent {
std::string level; // "debug" | "info" | "warn" | "error"
std::string message;
};
struct DataEvent {
std::string dataKind; // "install_plan", "styled_list", ...
std::string payloadJson;// raw JSON (let caller parse)
};
struct ErrorEvent {
std::string code;
std::string message;
std::string hint;
bool recoverable = false;
};
struct ResultEvent {
int exitCode = 0;
std::string dataJson; // additional payload, may be empty
};
using Event = std::variant<ProgressEvent, LogEvent, DataEvent,
ErrorEvent, ResultEvent>;
// Parse one NDJSON line into an Event.
std::optional<Event> parse_event_line(std::string_view line);
// ─── JSON extraction helpers (for NDJSON parsing) ───────────────────
std::string extract_string(std::string_view text, std::string_view key);
std::optional<long long> extract_int(std::string_view text, std::string_view key);
std::optional<bool> extract_bool(std::string_view text, std::string_view key);
std::string extract_object(std::string_view text, std::string_view key);
// ─── Subprocess call ────────────────────────────────────────────────
struct CallResult {
int exitCode = 0;
std::vector<DataEvent> dataEvents;
std::optional<ErrorEvent> error;
std::string resultJson;
};
struct EventHandler {
virtual ~EventHandler() = default;
virtual void on_progress(const ProgressEvent&) {}
virtual void on_log (const LogEvent&) {}
virtual void on_data (const DataEvent&) {}
virtual void on_error (const ErrorEvent&) {}
virtual void on_result (const ResultEvent&) {}
};
std::expected<CallResult, std::string>
call(const Env& env, std::string_view capability,
std::string_view argsJson, EventHandler* handler = nullptr);
// ─── Bootstrap progress types ───────────────────────────────────────
struct BootstrapFile {
std::string name; // xim package id, e.g. "xim:patchelf@0.18.0"
double downloadedBytes = 0;
double totalBytes = 0;
bool started = false;
bool finished = false;
};
struct BootstrapProgress {
std::vector<BootstrapFile> files;
double elapsedSec = 0;
};
using BootstrapProgressCallback = std::function<void(const BootstrapProgress&)>;
// Run xlings install with progress callback (used by bootstrap functions).
// When not `quiet` and stderr is a TTY, an elapsed-time spinner is shown
// during the (otherwise silent) direct install so first-run doesn't look
// frozen.
int install_with_progress(const Env& env, std::string_view target,
const BootstrapProgressCallback& cb,
bool quiet = false);
// Run direct `xlings install <target> -y`.
// Used as a fallback when the NDJSON interface install path fails.
int install_direct(const Env& env, std::string_view target, bool quiet = false);
// ─── Sandbox lifecycle ──────────────────────────────────────────────
// Write .xlings.json seed file.
//
// The `mirror` default is "auto": xlings' own adaptive mirror module
// (xlings.core.mirror.adaptive — latency-probed with per-download failover and
// failure penalisation) then picks the best reachable host per download. This
// replaces the historic hardcoded "CN", which FORCED the CN mirror and disabled
// that mechanism — stranding overseas users and GitHub-hosted CI on a
// slow/unreachable gitcode. An explicit `mcpp self config --mirror CN|GLOBAL`
// still writes that fixed value (config priority). Mirror selection is xlings'
// responsibility; mcpp just declines to override it by default.
// The project's build-environment payload (L-1), materialized 1:1 into the
// `.xlings.json` keys xlings already understands. Plain types (no manifest
// dependency); the caller fills it from a manifest's [xlings] section.
struct ProjectEnv {
std::vector<std::string> deps; // → "deps"
std::vector<std::pair<std::string,std::string>> workspace; // → "workspace"
std::string subos; // → "subos"
std::vector<std::pair<std::string,std::string>> envs; // → "envs"
bool empty() const {
return deps.empty() && workspace.empty() && subos.empty() && envs.empty();
}
};
// One index_repos entry for seed_xlings_json. `artifact`/`source` are the
// xlings >= 0.4.68 per-repo artifact-sync fields (#269); empty means "do not
// emit the key", which keeps pre-artifact output byte-identical and matches
// xlings' "undeclared = plain git" semantics. Older xlings ignores both keys.
struct SeedRepo {
std::string name;
std::string url;
std::string artifact; // artifact source base, e.g. https://github.com/xlings-res/mcpp-index
std::string source; // "auto" | "artifact" | "git"
};
void seed_xlings_json(const Env& env,
std::span<const SeedRepo> repos,
std::string_view mirror = "auto",
const ProjectEnv& penv = {});
// Persist the xlings mirror selection in .xlings.json via xlings itself.
int config_show(const Env& env);
int config_set_mirror(const Env& env, std::string_view mirror, bool quiet = false);
// Run xlings self init.
void ensure_init(const Env& env, bool quiet);
// Ensure patchelf is installed.
void ensure_patchelf(const Env& env, bool quiet,
const BootstrapProgressCallback& cb);
// Ensure ninja is installed.
void ensure_ninja(const Env& env, bool quiet,
const BootstrapProgressCallback& cb);
// Fast, side-effect-free probe for a usable nasm (>= 2.16): PATH first (CI
// images ship one), the mcpp sandbox second. NEVER triggers an install —
// pure lookup. A build that needs to *provision* nasm goes through the
// toolchain's synchronous fetcher gate
// (mcpp::pm::Fetcher::resolve_xpkg_path("xim:nasm@<version>", autoInstall,
// ...)) from mcpp.build.prepare, the same gate the compiler toolchain uses:
// this module is a LEAF dependency and must not import mcpp.config /
// mcpp.fetcher (#232 — the old bespoke `ensure_nasm` install path skipped
// the index refresh and downgraded install failure to a warning).
std::optional<std::filesystem::path> find_usable_nasm(const Env& env);
// Locate an already-installed nasm inside the mcpp sandbox
// ($XLINGS_HOME/data/xpkgs/xim-x-nasm/<version>/...). Pure lookup: no PATH
// probe, no install. Called lazily — only when a build plan actually
// contains .asm units — after a provisioning gate has landed the package;
// the caller HARD-FAILS on nullopt, never silently skips assembly sources.
std::optional<std::filesystem::path> find_sandbox_nasm(const Env& env);
// ─── Index freshness ────────────────────────────────────────────────
// How long a just-completed index sync suppresses the next one.
//
// Re-running a multi-repo sync because a SECOND package is also missing cannot
// help: the first sync already fetched everything upstream had, so a package
// still absent afterwards is absent upstream. Lives here, in the leaf module,
// because both users need it and the policy layer (mcpp.pm.index_refresh)
// imports this module — the reverse would be a cycle.
inline constexpr std::int64_t kIndexRefreshDebounceSeconds = 120;
// Check whether the default mcpplibs index data exists and is fresh
// (within ttlSeconds).
// Returns true if index is present and fresh, false otherwise.
bool is_index_fresh(const Env& env, std::int64_t ttlSeconds);
// Check whether xlings' official xim index data exists and is fresh.
// This is separate from mcpp's default mcpplibs index because xlings
// toolchains live in xim-pkgindex, while modular libraries live in mcpplibs.
bool is_official_index_fresh(const Env& env, std::int64_t ttlSeconds);
// Check whether a specific package file exists in xlings' official xim index
// and the index is fresh. This catches restored CI caches that have an index
// directory and marker but predate a package added later.
bool is_official_package_index_fresh(const Env& env,
std::string_view packageName,
std::int64_t ttlSeconds);
// Run `xlings update` to refresh all index repos. Streams output to stdout.
// Returns the xlings exit code.
int update_index(const Env& env, bool quiet = false);
// Ensure the local index is present and fresh. Runs `xlings update` if
// the index is missing or older than ttlSeconds. Idempotent and quiet
// when no update is needed.
void ensure_index_fresh(const Env& env, std::int64_t ttlSeconds, bool quiet = false);
// Ensure xlings' official xim index is present and fresh.
void ensure_official_index_fresh(const Env& env, std::int64_t ttlSeconds, bool quiet = false);
// Ensure a specific package file exists in xlings' official xim index.
void ensure_official_package_index_fresh(const Env& env,
std::string_view packageName,
std::int64_t ttlSeconds,
bool quiet = false);
// ─── Index status (read-only, offline) ──────────────────────────────
// Snapshot of a local index directory — computed without touching the
// network, for `mcpp index status`.
struct IndexStatus {
std::filesystem::path dir; // on-disk index directory
bool present; // pkgs/ tree exists locally
bool fresh; // refreshed within ttlSeconds
std::int64_t ageSeconds; // since last refresh marker, -1 if unknown
std::optional<std::string> rev; // index CONTENT identity, nullopt if absent
};
IndexStatus default_index_status(const Env& env, std::int64_t ttlSeconds);
IndexStatus official_index_status(const Env& env, std::int64_t ttlSeconds);
// The index's own content identity, as written by xlings into
// `<indexDir>/.xlings-index-version` when it materializes the tree.
//
// OPAQUE BY CONTRACT. Observed values are a 7-char short sha for the artifact-
// distributed indexes (`mcpp-index-8d67478.tar.gz` → `8d67478`) but a DATE
// VERSION for the sub-indexes (`xim-index-awesome-2026.7.30.1.tar.gz` →
// `2026.7.30.1`). Never parse it, never assume a length — only compare it for
// equality and print it. Returns nullopt when the file is missing (a local
// `path` index has none) or blank; callers must degrade, never hard-fail.
std::optional<std::string> index_revision(const std::filesystem::path& indexDir);
// ─── run_capture utility ────────────────────────────────────────────
std::expected<std::string, std::string> run_capture(const std::string& cmd);
} // namespace mcpp::xlings
// ═══════════════════════════════════════════════════════════════════════
// Implementation
// ═══════════════════════════════════════════════════════════════════════
namespace mcpp::xlings {
namespace {
// Right-pad a verb to 12 columns for bootstrap status lines.
void print_status(std::string_view verb, std::string_view msg) {
constexpr std::size_t W = 12;
if (verb.size() >= W) {
std::println("{} {}", verb, msg);
} else {
std::println("{}{} {}", std::string(W - verb.size(), ' '), verb, msg);
}
}
std::filesystem::path default_index_dir(const Env& env) {
return paths::index_data(env) / "mcpplibs";
}
std::filesystem::path official_index_dir(const Env& env) {
return paths::index_data(env) / "xim-pkgindex";
}
std::filesystem::path index_pkgs_dir(const std::filesystem::path& indexDir) {
return indexDir / "pkgs";
}
std::filesystem::path index_refresh_marker(const std::filesystem::path& indexDir) {
return indexDir / ".mcpp-index-updated";
}
std::filesystem::path index_version_file(const std::filesystem::path& indexDir) {
return indexDir / ".xlings-index-version";
}
std::filesystem::path official_package_file(const Env& env, std::string_view packageName) {
if (packageName.empty()) return {};
std::string name(packageName);
return official_index_dir(env) / "pkgs" / std::string(1, name[0]) / (name + ".lua");
}
std::string json_escaped_path_probe(std::filesystem::path path) {
auto value = path.string();
std::string escaped;
escaped.reserve(value.size() * 2);
for (char c : value) {
if (c == '\\') escaped += "\\\\";
else escaped.push_back(c);
}
return escaped;
}
bool official_index_cache_matches_package_file(const Env& env,
std::string_view packageName) {
auto cache = official_index_dir(env) / ".xlings-index-cache.json";
if (!std::filesystem::exists(cache)) return true;
auto pkg = official_package_file(env, packageName);
if (pkg.empty()) return false;
std::ifstream is(cache);
if (!is) return false;
std::string body((std::istreambuf_iterator<char>(is)), {});
auto rawPath = pkg.string();
return body.find(rawPath) != std::string::npos
|| body.find(json_escaped_path_probe(pkg)) != std::string::npos;
}
void mark_index_refreshed(const std::filesystem::path& indexDir) {
if (!std::filesystem::exists(index_pkgs_dir(indexDir))) return;
std::error_code ec;
std::filesystem::create_directories(indexDir, ec);
auto marker = index_refresh_marker(indexDir);
{
std::ofstream os(marker, std::ios::trunc);
if (!os) return;
os << "ok\n";
}
std::filesystem::last_write_time(
marker, std::filesystem::file_time_type::clock::now(), ec);
}
void mark_known_indexes_refreshed(const Env& env) {
// Project-scoped envs used to return early here, which left the global
// indexes unmarked whenever a project with custom `[indices]` triggered the
// sync — so `mcpp index status` reported "unknown" forever on exactly the
// machines that refresh most. The marker is advisory (it debounces and it
// dates the status line; it is NOT what decides whether a refresh is
// needed), so marking it from either env is both safe and more accurate.
mark_index_refreshed(default_index_dir(env));
mark_index_refreshed(official_index_dir(env));
}
bool is_index_dir_fresh(const std::filesystem::path& indexDir, std::int64_t ttlSeconds) {
std::error_code ec;
if (!std::filesystem::exists(index_pkgs_dir(indexDir))) return false;
auto marker = index_refresh_marker(indexDir);
if (!std::filesystem::exists(marker)) return false;
auto newest = std::filesystem::last_write_time(marker, ec);
if (ec) return false;
auto now = std::filesystem::file_time_type::clock::now();
auto age = std::chrono::duration_cast<std::chrono::seconds>(now - newest);
// A marker stamped in the FUTURE yields a negative age, which the plain
// `age < ttl` test read as "fresh" — and stayed fresh until the wall clock
// caught up, potentially for years. Future timestamps are routine: clock
// skew in containers/VMs, a tar that preserved mtimes, a restored CI cache.
// An unusable timestamp means "unknown", and unknown must mean stale.
if (age.count() < 0) return false;
return age.count() < ttlSeconds;
}
// Seconds since the index's refresh marker was last touched, or -1 if the
// marker is missing/unreadable. Read-only — no network, no side effects.
std::int64_t index_age_seconds(const std::filesystem::path& indexDir) {
std::error_code ec;
auto marker = index_refresh_marker(indexDir);
auto newest = std::filesystem::last_write_time(marker, ec);
if (ec) return -1;
auto now = std::filesystem::file_time_type::clock::now();
auto age = std::chrono::duration_cast<std::chrono::seconds>(now - newest).count();
return age < 0 ? -1 : age; // future stamp → "unknown", same rule as above
}
// Defined inside the anonymous namespace so `index_status_for` (also here) can
// use it; the exported `index_revision` below forwards to it.
std::optional<std::string> read_index_revision(const std::filesystem::path& indexDir) {
std::ifstream is(index_version_file(indexDir), std::ios::binary);
if (!is) return std::nullopt;
std::string body((std::istreambuf_iterator<char>(is)), {});
// The observed files carry no trailing newline, but trim anyway: this value
// is compared for equality and printed, and a stray \r from a Windows-side
// writer would otherwise turn "same rev" into "changed rev" every run.
auto isSpace = [](unsigned char c) { return std::isspace(c) != 0; };
while (!body.empty() && isSpace(static_cast<unsigned char>(body.back())))
body.pop_back();
std::size_t b = 0;
while (b < body.size() && isSpace(static_cast<unsigned char>(body[b]))) ++b;
body.erase(0, b);
if (body.empty()) return std::nullopt;
return body;
}
IndexStatus index_status_for(const std::filesystem::path& indexDir,
std::int64_t ttlSeconds) {
std::error_code ec;
bool present = std::filesystem::exists(index_pkgs_dir(indexDir), ec) && !ec;
return IndexStatus{
.dir = indexDir,
.present = present,
.fresh = is_index_dir_fresh(indexDir, ttlSeconds),
.ageSeconds = index_age_seconds(indexDir),
.rev = read_index_revision(indexDir),
};
}
void write_file(const std::filesystem::path& p, std::string_view content) {
std::error_code ec;
std::filesystem::create_directories(p.parent_path(), ec);
std::ofstream os(p);
os << content;
}
std::string json_escape(std::string_view value) {
std::string out;
out.reserve(value.size());
for (unsigned char ch : value) {
switch (ch) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (ch < 0x20) {
out += std::format("\\u{:04x}", static_cast<unsigned>(ch));
} else {
out.push_back(static_cast<char>(ch));
}
}
}
return out;
}
// LineScan: cheap field extraction for bootstrap install progress lines.
// Handles flat JSON; no nested array/object — the keys we extract are
// all leaves.
struct LineScan {
std::string_view s;
std::string find_str(std::string_view key) const {
std::string n = std::format("\"{}\":\"", key);
auto p = s.find(n);
if (p == std::string_view::npos) return "";
p += n.size();
std::string out;
while (p < s.size() && s[p] != '"') {
if (s[p] == '\\' && p + 1 < s.size()) {
out.push_back(s[p+1]); p += 2; continue;
}
out.push_back(s[p++]);
}
return out;
}
double find_num(std::string_view key) const {
std::string n = std::format("\"{}\":", key);
auto p = s.find(n);
if (p == std::string_view::npos) return 0;
p += n.size();
auto e = p;
while (e < s.size()
&& (std::isdigit(static_cast<unsigned char>(s[e]))
|| s[e] == '.' || s[e] == '-' || s[e] == '+'
|| s[e] == 'e' || s[e] == 'E')) ++e;
try { return std::stod(std::string(s.substr(p, e - p))); }
catch (...) { return 0; }
}
bool find_bool(std::string_view key) const {
std::string n = std::format("\"{}\":", key);
auto p = s.find(n);
if (p == std::string_view::npos) return false;
p += n.size();
return s.size() - p >= 4 && s.substr(p, 4) == "true";
}
};
} // anonymous namespace
// ─── Index identity ─────────────────────────────────────────────────
std::optional<std::string> index_revision(const std::filesystem::path& indexDir) {
return read_index_revision(indexDir);
}
// ─── run_capture ────────────────────────────────────────────────────
std::expected<std::string, std::string> run_capture(const std::string& cmd) {
auto r = mcpp::platform::process::capture(cmd);
if (r.exit_code != 0 && r.output.empty())
return std::unexpected("command failed: " + cmd);
return r.output;
}
// ─── Shell quoting ──────────────────────────────────────────────────
std::string shq(std::string_view s) {
return mcpp::platform::shell::quote(s);
}
// ─── Path helpers ───────────────────────────────────────────────────
namespace paths {
std::filesystem::path xpkgs_base(const Env& env) {
return env.home / "data" / "xpkgs";
}
std::filesystem::path sandbox_bin(const Env& env) {
return env.home / "subos" / "default" / "bin";
}
std::filesystem::path sysroot(const Env& env) {
return env.home / "subos" / "default";
}
std::filesystem::path xim_tool_root(const Env& env, std::string_view tool) {
return xpkgs_base(env) / std::format("xim-x-{}", tool);
}
std::filesystem::path xim_tool(const Env& env, std::string_view tool,
std::string_view version) {
return xpkgs_base(env) / std::format("xim-x-{}", tool) / std::string(version);
}
std::optional<std::filesystem::path>
xpkgs_from_compiler(const std::filesystem::path& compilerBin) {
for (auto p = compilerBin.parent_path();
p.has_parent_path() && p != p.root_path();
p = p.parent_path()) {
if (p.filename() == "xpkgs") return p;
}
return std::nullopt;
}
std::optional<std::filesystem::path>
subos_dir_of(const std::filesystem::path& compilerBin) {
auto xpkgs = xpkgs_from_compiler(compilerBin);
if (!xpkgs) return std::nullopt;
// <home>/data/xpkgs → <home>/subos/default. Spelled from the xpkgs dir
// rather than from Env so a toolchain inherited from ANOTHER home resolves
// to that home's subos, which is the one whose payloads the binary was
// actually linked against.
auto home = xpkgs->parent_path().parent_path();
if (home.empty()) return std::nullopt;
return home / "subos" / "default";
}
std::optional<std::filesystem::path>
find_sibling_tool(const std::filesystem::path& compilerBin,
std::string_view tool) {
auto xpkgs = xpkgs_from_compiler(compilerBin);
if (!xpkgs) return std::nullopt;
auto root = *xpkgs / std::format("xim-x-{}", tool);
std::error_code ec;
if (!std::filesystem::exists(root, ec)) return std::nullopt;
// The first version dir readdir yields. ORDER IS UNDEFINED -- this does
// NOT return the highest, and the comment that said so was wrong for as
// long as it stood. With two versions installed the answer varies by
// filesystem, so a caller that needs a SPECIFIC version must name it;
// see probe.cppm, where the version comes from the resolved runtime
// binding rather than from this scan.
//
// A test asserting the old "highest" claim was attempted and removed: it
// passed or failed by directory order, which makes both outcomes
// uninformative.
for (auto& v : std::filesystem::directory_iterator(root, ec)) {
if (v.is_directory(ec)) return v.path();
}
return std::nullopt;
}
std::optional<std::filesystem::path> active_home_xpkgs() {
std::filesystem::path home;
if (const char* h = std::getenv("MCPP_HOME"); h && *h) {
home = h;
} else if (const char* u = std::getenv("HOME"); u && *u) {
home = std::filesystem::path(u) / ".mcpp";
} else {
return std::nullopt;
}
auto xpkgs = home / "registry" / "data" / "xpkgs";
std::error_code ec;
if (!std::filesystem::exists(xpkgs, ec)) return std::nullopt;
return xpkgs;
}
namespace {
// A version dir qualifies as a payload only if it has real content —
// dot-prefixed entries (.xim-installed, .xpkg.lua) are install metadata,
// and a dir holding nothing else is the husk a delegating index package
// leaves behind (the payload lives under another prefix; issue #120).
// When requiredRelPath is given, the dir must also contain that path.
bool payload_dir_qualifies(const std::filesystem::path& versionDir,
std::string_view requiredRelPath) {
std::error_code ec;
bool hasContent = false;
for (auto& f : std::filesystem::directory_iterator(versionDir, ec)) {
if (!f.path().filename().string().starts_with(".")) {
hasContent = true;
break;
}
}
if (!hasContent) return false;
if (!requiredRelPath.empty()
&& !std::filesystem::exists(versionDir / requiredRelPath, ec))
return false;
return true;
}
// Scan an xpkgs root across index prefixes (xim-x-, scode-x-, compat-x-, …)
// for the first qualifying version dir of `packageName`.
std::optional<std::filesystem::path>
find_package_in_xpkgs(const std::filesystem::path& xpkgs,
std::string_view packageName,
std::string_view requiredRelPath) {
std::error_code ec;
std::string suffix = std::format("-x-{}", packageName);
for (auto& entry : std::filesystem::directory_iterator(xpkgs, ec)) {
if (!entry.is_directory(ec)) continue;
auto name = entry.path().filename().string();
if (!name.ends_with(suffix)) continue;
for (auto& v : std::filesystem::directory_iterator(entry.path(), ec)) {
if (!v.is_directory(ec)) continue;
if (payload_dir_qualifies(v.path(), requiredRelPath))
return v.path();
}
}
return std::nullopt;
}
} // namespace
std::optional<std::filesystem::path>
find_home_tool(std::string_view tool, std::string_view requiredRelPath) {
auto xpkgs = active_home_xpkgs();
if (!xpkgs) return std::nullopt;
return find_package_in_xpkgs(*xpkgs, tool, requiredRelPath);
}
std::optional<std::filesystem::path>
find_sibling_binary(const std::filesystem::path& compilerBin,
std::string_view tool,
std::string_view binaryRelPath) {
auto xpkgs = xpkgs_from_compiler(compilerBin);
if (!xpkgs) return std::nullopt;
auto root = *xpkgs / std::format("xim-x-{}", tool);
std::error_code ec;
if (!std::filesystem::exists(root, ec)) return std::nullopt;
for (auto& v : std::filesystem::directory_iterator(root, ec)) {
auto candidate = v.path() / std::string(binaryRelPath);
if (std::filesystem::exists(candidate, ec))
return candidate;
}
return std::nullopt;
}
std::optional<std::filesystem::path>
find_sibling_package(const std::filesystem::path& compilerBin,
std::string_view packageName,
std::string_view requiredRelPath) {
auto xpkgs = xpkgs_from_compiler(compilerBin);
if (!xpkgs) return std::nullopt;
// Search across index prefixes: xim-x-, scode-x-, compat-x-, etc.
if (auto found = find_package_in_xpkgs(*xpkgs, packageName, requiredRelPath))
return found;
// Also check ~/.xlings/data/xpkgs/ (xlings global home) as fallback.
std::error_code ec;
const char* home = std::getenv("HOME");
if (home) {
auto xlingsXpkgs = std::filesystem::path(home) / ".xlings" / "data" / "xpkgs";
if (xlingsXpkgs != *xpkgs && std::filesystem::exists(xlingsXpkgs, ec))
return find_package_in_xpkgs(xlingsXpkgs, packageName, requiredRelPath);
}
return std::nullopt;
}
std::filesystem::path index_data(const Env& env) {
return env.home / "data";
}
std::filesystem::path sandbox_init_marker(const Env& env) {
return env.home / "subos" / "default" / ".xlings.json";
}
} // namespace paths
// ─── Shell command builders ─────────────────────────────────────────
std::string build_command_prefix(const Env& env) {
auto xvmBin = paths::sandbox_bin(env).string();
if constexpr (mcpp::platform::is_windows) {
mcpp::platform::env::set("XLINGS_HOME", env.home.string());
mcpp::platform::env::set("XLINGS_PROJECT_DIR",
env.projectDir.empty() ? "" : env.projectDir.string());
mcpp::platform::windows::prepend_path(xvmBin);
return env.binary.string();
} else {
if (env.projectDir.empty()) {
// Global mode: unset XLINGS_PROJECT_DIR (existing behavior).
return std::format(
"cd {} && env -u XLINGS_PROJECT_DIR PATH={}:\"$PATH\" XLINGS_HOME={} {}",
shq(env.home.string()),
shq(xvmBin),
shq(env.home.string()),
shq(env.binary.string()));
}
// Project-level mode: set XLINGS_PROJECT_DIR so xlings uses
// additive project repos alongside global repos.
return std::format(
"cd {} && env PATH={}:\"$PATH\" XLINGS_HOME={} XLINGS_PROJECT_DIR={} {}",
shq(env.home.string()),
shq(xvmBin),
shq(env.home.string()),
shq(env.projectDir.string()),
shq(env.binary.string()));
}
}
std::string build_interface_command(const Env& env,
std::string_view capability,
std::string_view argsJson) {
return std::format("{} interface {} --args {} {}",
build_command_prefix(env), capability, shq(argsJson),
mcpp::platform::null_redirect);
}
// ─── JSON extraction helpers ────────────────────────────────────────
std::string extract_string(std::string_view text, std::string_view key) {
auto needle = std::string{"\""} + std::string(key) + "\":\"";
auto p = text.find(needle);
if (p == std::string_view::npos) return "";
p += needle.size();
std::string out;
while (p < text.size()) {
char c = text[p++];
if (c == '\\' && p < text.size()) {
char nc = text[p++];
switch (nc) {
case 'n': out.push_back('\n'); break;
case 't': out.push_back('\t'); break;
case 'r': out.push_back('\r'); break;
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
default: out.push_back(nc);
}
} else if (c == '"') {
return out;
} else {
out.push_back(c);
}
}
return out;
}
std::optional<long long> extract_int(std::string_view text, std::string_view key) {
auto needle = std::string{"\""} + std::string(key) + "\":";
auto p = text.find(needle);
if (p == std::string_view::npos) return std::nullopt;
p += needle.size();
while (p < text.size() && text[p] == ' ') ++p;
bool neg = false;
if (p < text.size() && text[p] == '-') { neg = true; ++p; }
long long n = 0;
bool any = false;
while (p < text.size() && std::isdigit(static_cast<unsigned char>(text[p]))) {
n = n * 10 + (text[p++] - '0');
any = true;
}
if (!any) return std::nullopt;
return neg ? -n : n;
}
std::optional<bool> extract_bool(std::string_view text, std::string_view key) {
auto needle = std::string{"\""} + std::string(key) + "\":";
auto p = text.find(needle);
if (p == std::string_view::npos) return std::nullopt;
p += needle.size();
while (p < text.size() && text[p] == ' ') ++p;
if (text.substr(p, 4) == "true") return true;
if (text.substr(p, 5) == "false") return false;
return std::nullopt;
}
std::string extract_object(std::string_view text, std::string_view key) {
auto needle = std::string{"\""} + std::string(key) + "\":";
auto p = text.find(needle);
if (p == std::string_view::npos) return "";
p += needle.size();
while (p < text.size() && text[p] == ' ') ++p;
if (p >= text.size() || (text[p] != '{' && text[p] != '[')) return "";
char open = text[p];
char close = (open == '{') ? '}' : ']';
int depth = 0;
std::size_t start = p;
bool in_string = false;
while (p < text.size()) {
char c = text[p];
if (in_string) {
if (c == '\\' && p + 1 < text.size()) { p += 2; continue; }
if (c == '"') in_string = false;
++p; continue;
}
if (c == '"') { in_string = true; ++p; continue; }
if (c == open) { ++depth; }
else if (c == close) {
--depth;
if (depth == 0) return std::string(text.substr(start, p - start + 1));
}
++p;
}
return "";
}
// ─── NDJSON event parser ────────────────────────────────────────────
std::optional<Event> parse_event_line(std::string_view line) {
auto kind = extract_string(line, "kind");
if (kind == "progress") {
ProgressEvent e;
e.phase = extract_string(line, "phase");
e.percent = static_cast<int>(extract_int(line, "percent").value_or(0));
e.message = extract_string(line, "message");
return e;
}
if (kind == "log") {
LogEvent e;
e.level = extract_string(line, "level");
e.message = extract_string(line, "message");
return e;
}