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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
//! pleme-doc-gen — typed Rust replacement for the M0 Python
//! _gen-patterns.py + _gen-docs.py scripts in pleme-io/actions.
//!
//! Per the ★★ NO-SHELL prime directive
//! (https://github.com/pleme-io/blackmatter-pleme/blob/main/skills/pleme-io-pattern-core/SKILL.md):
//! build-time generators belong in Rust, not Python.
//!
//! Subcommands:
//! patterns emit substrate/lib/release/patterns-full.nix from action.yml files
//! docs emit README.md per action from action.yml
//! index emit root README.md catalog index
#![warn(clippy::pedantic)]
use clap::{Parser, Subcommand};
use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;
mod ast;
mod caixa;
mod category;
mod cmake_ast;
mod consume_gh_org;
mod consume_monorepo;
mod control_ast;
mod discover;
mod await_ci;
mod caixa_deps;
mod caixa_naming;
mod docs;
mod eat;
mod eat_and_ship;
mod ecosystems;
mod elixir_ast;
mod fidelity;
mod file_capture;
mod instantiate;
mod fleet;
mod github_client;
mod green_ci;
mod inventory_init;
mod json_ast;
mod kotlin_ast;
mod lined_ast;
mod lua_ast;
mod manifest_io;
mod meson_ast;
mod oss_conversion;
mod patterns;
mod python_ast;
mod render_health;
mod reverse;
mod ruby_ast;
mod scaffold;
mod scala_ast;
mod search_consume;
mod sexp_ast;
mod ship;
mod swift_ast;
mod toml_ast;
mod validator;
mod xml_ast;
mod zig_ast;
mod yaml;
mod yaml_ast;
#[derive(Parser)]
#[command(name = "pleme-doc-gen", version, about = "pleme-io actions docs + catalog generator")]
struct Cli {
/// Path to the pleme-io/actions repo root (defaults to CWD)
#[arg(long, default_value = ".")]
actions_dir: PathBuf,
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// Emit substrate/lib/release/patterns-full.nix to stdout
Patterns,
/// Write per-action README.md files in-place
Docs,
/// Write root README.md catalog index
Index,
/// Write all three (docs + index + patterns)
All {
/// Where to write the patterns-full.nix output
#[arg(long)]
patterns_out: Option<PathBuf>,
},
/// Render a (defcaixa ...) source into the target repo's
/// adoption surface (Cargo.toml + .pleme-io-release.toml +
/// 3 .github/workflows shims). M3 proof — currently supports
/// :ecosystem :rust-single-crate; other ecosystems land as
/// follow-up commits per the canonical pattern.
Caixa {
/// Path to the .caixa.lisp source
#[arg(long)]
source: PathBuf,
/// Where to render the artifacts (default: CWD)
#[arg(long, default_value = ".")]
out: PathBuf,
/// Overwrite existing files (default: skip)
#[arg(long)]
force: bool,
},
/// Generate a complete .caixa.lisp source from a minimal spec.
/// Pair with `caixa --source <file>` to render the full repo
/// scaffold downstream. The unit of operator effort drops to
/// a handful of CLI flags per new ecosystem-aware repo.
Scaffold {
/// Repo / package name (becomes :name and default repository slug)
#[arg(long)]
name: String,
/// Ecosystem keyword (e.g. rust-single-crate, npm, python, helm)
#[arg(long)]
ecosystem: String,
/// Kind override (Biblioteca | Binario | Aplicacao | Servico)
#[arg(long)]
kind: Option<String>,
/// Initial version
#[arg(long)]
version: Option<String>,
/// One-line description
#[arg(long)]
description: Option<String>,
/// SPDX license identifier (default per-ecosystem; MIT/Apache-2.0/…)
#[arg(long)]
license: Option<String>,
/// Repository URL (defaults to https://github.com/pleme-io/<name>)
#[arg(long)]
repository: Option<String>,
/// Author string (Cargo: name <email>, npm: name)
#[arg(long)]
authors: Option<String>,
/// Maven/Gradle group-id
#[arg(long)]
group_id: Option<String>,
/// Write to file instead of stdout
#[arg(long)]
out: Option<PathBuf>,
},
/// One-shot: scaffold a .caixa.lisp, render it, optionally git-init.
/// Collapses scaffold + caixa render into a single operator action.
/// The output directory becomes a fully-staged repo ready to
/// `git push` into a fresh GitHub remote.
Forge {
/// Repo / package name
#[arg(long)]
name: String,
/// Ecosystem keyword
#[arg(long)]
ecosystem: String,
/// Kind override
#[arg(long)]
kind: Option<String>,
/// One-line description
#[arg(long)]
description: Option<String>,
/// SPDX license identifier
#[arg(long)]
license: Option<String>,
/// Output directory (default: ./<name>)
#[arg(long)]
out: Option<PathBuf>,
/// Run `git init` + first commit after rendering
#[arg(long)]
git_init: bool,
},
/// Discover the ecosystem of an OSS repository — either a local clone
/// (`--path`) or a GitHub slug (`--url owner/repo`, no clone needed,
/// uses `gh api`). Closes the loop with `gh-publish`: discover →
/// scaffold → forge → push → autorelease.
Discover {
/// Path to inspect (a local clone of an OSS repository)
#[arg(long, default_value = ".")]
path: PathBuf,
/// GitHub slug (owner/repo) — inspects via `gh api` without cloning.
/// Overrides --path when set.
#[arg(long)]
url: Option<String>,
},
/// Ecosystems — list every supported ecosystem + its typed
/// capabilities across the 5 substrate orchestration surfaces
/// (forge / reverse / validate / green-ci / url-discover).
/// Operator-facing self-description of the substrate's typed
/// surface; agent-facing dispatch table.
Ecosystems {
/// Filter to one ecosystem keyword (default: list all)
#[arg(long)]
ecosystem: Option<String>,
/// Emit JSON instead of a text table
#[arg(long)]
json: bool,
/// Show only fully-capable ecosystems (all 5 surfaces present)
#[arg(long)]
full_only: bool,
},
/// Caixa-init — one-call bootstrap of an OSS-consumption inventory
/// repo. Lays down the .github/workflows/convert-and-publish.yml
/// workflow + example .ossconv.lisp + example .fleet.lisp +
/// README + .gitignore.
///
/// With --gh-create --yes: one CLI call goes end-to-end —
/// scaffold + git init + first commit + `gh repo create` + push.
/// The pushed repo's CI fires immediately on free GH compute.
CaixaInit {
/// Inventory repo name (becomes the README header + workflow
/// cargo-install version pin + GH repo slug)
#[arg(long)]
name: String,
/// Output directory (default: ./<name>)
#[arg(long)]
out: Option<PathBuf>,
/// GH org or user for the created repo (default: pleme-io)
#[arg(long, default_value = "pleme-io")]
org: String,
/// After scaffolding: git init + first commit + gh repo create + push.
/// Requires --yes (irreversible operator action).
#[arg(long)]
gh_create: bool,
/// Required when --gh-create is set
#[arg(long)]
r#yes: bool,
/// Make the GH repo private (default: public for OSS cascade)
#[arg(long)]
private: bool,
},
/// Lint — structural integrity check on a forged or candidate
/// repo. Auto-detects ecosystem + runs the matching Validator
/// (or the SubstrateOnlyValidator floor for unknown ecosystems).
/// Prints typed issues to stdout; exit 0 on clean, exit 1 with
/// per-issue lines on problems.
Lint {
/// Path to lint (a forged repo or any directory containing a manifest)
#[arg(long, default_value = ".")]
path: PathBuf,
},
/// Measure-fidelity — run reverse → render against an original
/// repo + report typed per-field fidelity (perfect / lossy / gap /
/// na) + overall score 0–1000 permille. Operator's quality
/// compass for the consumption pipeline.
MeasureFidelity {
/// Path to the original repo
#[arg(long)]
path: PathBuf,
},
/// Consume GitHub org — list <org>'s public repos via gh CLI,
/// shallow-clone each into a work dir, run discover + reverse +
/// optional render per clone. Mass-absorb an entire org's repo
/// set into typed caixas in ONE substrate call.
ConsumeGhOrg {
/// GitHub org or user namespace (e.g. pleme-io)
#[arg(long)]
org: String,
/// Output directory (one <repo>.caixa.lisp per consumed repo)
#[arg(long)]
out: PathBuf,
/// Work directory for shallow clones (default: /tmp/<org>-clones)
#[arg(long)]
work_dir: Option<PathBuf>,
/// Max repos to fetch (gh API limit, default: 100)
#[arg(long, default_value_t = 100)]
limit: usize,
/// Also render each .caixa.lisp to a typed scaffold
#[arg(long)]
render_too: bool,
/// Include archived repos in the listing
#[arg(long)]
include_archived: bool,
/// Also measure fidelity per repo (compares original clone to
/// rendered output, populates aggregate + per-ecosystem score).
/// Implies --render-too.
#[arg(long)]
measure_fidelity: bool,
/// Also verify rendered scaffold completeness (manifest +
/// auto-release workflow + test stub). Implies --render-too.
#[arg(long)]
verify_rendered: bool,
},
/// Search-and-consume — GitHub search → consume + measure.
/// Wraps `gh search repos <query>` + the per-repo pipeline so
/// operators can absorb arbitrary external corpora into typed
/// caixas in one substrate call. With --measure-fidelity, the
/// aggregate score reveals how well the substrate's extractors
/// generalize to third-party shapes.
SearchAndConsume {
/// GitHub-search query (passes to `gh search repos`)
/// Examples: "language:rust stars:>500 cli",
/// "topic:helm-chart language:yaml"
#[arg(long)]
query: String,
/// Output directory (one <repo>.caixa.lisp per consumed result)
#[arg(long)]
out: PathBuf,
/// Work dir for shallow clones
#[arg(long)]
work_dir: Option<PathBuf>,
/// Max results to fetch
#[arg(long, default_value_t = 30)]
limit: usize,
/// Also render each .caixa.lisp to a typed scaffold
#[arg(long)]
render_too: bool,
/// Also measure fidelity per repo (implies --render-too)
#[arg(long)]
measure_fidelity: bool,
},
/// Consume monorepo — walk subdirs of <path>, dispatch discover +
// (eat verb's --include-binaries flag is on the Cmd::Eat variant below.)
/// Eat — substrate composes absorb + reverse + render + restore.
/// One call against a source path produces three typed artifacts:
/// <out>/<name>.caixa.lisp — typed manifest
/// <out>/<name>.files.json — typed file-content manifest
/// <out>/<name>-rendered/ — working copy (original source
/// overlaid with substrate's CI
/// scaffolding)
/// The first stage of the eat → verify-tests → ship → await-ci →
/// published lifecycle.
Eat {
/// Path to the repo / directory to eat
#[arg(long)]
path: PathBuf,
/// Output directory (defaults to ./eaten/)
#[arg(long, default_value = "eaten")]
out: PathBuf,
/// Per-file byte cap for file capture (default: 8 MB)
#[arg(long, default_value_t = 8_388_608)]
max_file_bytes: usize,
/// Whole-tree byte cap (default: 100 MB)
#[arg(long, default_value_t = 104_857_600)]
max_total_bytes: usize,
/// Also capture binary files (PNGs, fonts, archives, encoding
/// fixtures, etc) as base64 :binaries slot. Default false —
/// keeps lisp sources tractable for code-only absorption.
#[arg(long)]
include_binaries: bool,
},
/// eat-and-ship — chain the full lifecycle: eat + verify-tests +
/// ship + await-ci. One verb takes a source path + target slug,
/// produces the published caixa (or stops at any failed gate).
///
/// Default target follows the substrate convention:
/// pleme-io/caixa-<basename of source path>. Pass --target to
/// override.
///
/// Dry-run by default — passes through to ship's dry-run plan +
/// skips await-ci. --yes to actually push + await.
EatAndShip {
/// Path to the source repo to eat
#[arg(long)]
path: PathBuf,
/// Output dir for eaten artifacts (default: ./eaten/)
#[arg(long, default_value = "eaten")]
out: PathBuf,
/// Target slug (default: pleme-io/caixa-<basename>)
#[arg(long)]
target: Option<String>,
/// Skip local verify-tests stage
#[arg(long)]
skip_verify: bool,
/// Skip ship + await-ci (eat-only mode)
#[arg(long)]
skip_ship: bool,
/// Skip await-ci after ship (push-only mode)
#[arg(long)]
skip_await: bool,
/// Repo visibility (public | private | internal)
#[arg(long, default_value = "public")]
visibility: String,
/// Description for the new repo
#[arg(long, default_value = "Eaten by pleme-doc-gen substrate")]
description: String,
/// Initial commit message
#[arg(long, default_value = "feat: initial eat from substrate")]
commit_message: String,
/// Default branch
#[arg(long, default_value = "main")]
branch: String,
/// Per-file byte cap (default: 8 MB)
#[arg(long, default_value_t = 8_388_608)]
max_file_bytes: usize,
/// Whole-tree byte cap (default: 100 MB)
#[arg(long, default_value_t = 104_857_600)]
max_total_bytes: usize,
/// await-ci max wait seconds (default: 900 = 15 min)
#[arg(long, default_value_t = 900)]
await_timeout: u64,
/// await-ci poll seconds (default: 15)
#[arg(long, default_value_t = 15)]
await_poll: u64,
/// Actually execute (no --yes = dry-run plan only, no push)
#[arg(long)]
yes: bool,
},
/// ship — push an eaten/rendered dir to a new pleme-io GH repo.
/// Creates the repo via `gh repo create`, initializes git, commits,
/// pushes. The push triggers the auto-release.yml workflow on the
/// remote; observe via `await-ci`.
///
/// Default target follows the substrate convention:
/// pleme-io/caixa-<basename of rendered path's parent's
/// last-segment-without-rendered-suffix>. Pass --target to override.
///
/// SAFETY: requires --yes to actually execute. Default is dry-run
/// mode (prints the plan + exits). High blast-radius — operator
/// must opt in.
Ship {
/// Target slug (default: pleme-io/caixa-<inferred-basename>)
#[arg(long)]
target: Option<String>,
/// Path to the eaten/rendered dir
#[arg(long)]
rendered: PathBuf,
/// Repo visibility (public | private | internal)
#[arg(long, default_value = "public")]
visibility: String,
/// Description for the new repo
#[arg(long, default_value = "Eaten by pleme-doc-gen substrate")]
description: String,
/// Initial commit message
#[arg(long, default_value = "feat: initial eat from substrate")]
commit_message: String,
/// Default branch
#[arg(long, default_value = "main")]
branch: String,
/// Actually execute (no --yes = dry-run plan only)
#[arg(long)]
yes: bool,
},
/// instantiate — reliable one-shot consumer cycle.
/// Composes: render → caixa-deps-resolve → re-render (so the
/// substrate auto-wires Cargo path deps for materialized
/// :depends-on entries) → verify-tests. Idempotent across
/// re-runs — operator-edited source preserved via the typed
/// "Replace this stub" marker check in render's write_if_needed.
///
/// Use this whenever your .caixa.lisp has :depends-on. After
/// running, the rendered dir builds cleanly + the deps are
/// auto-wired as Cargo path deps (rust-*) — operator just
/// writes their consumer code and `cargo build`.
Instantiate {
/// Consumer .caixa.lisp source
#[arg(long)]
source: PathBuf,
/// Output / rendered dir
#[arg(long)]
out: PathBuf,
/// Skip verify-tests at the end
#[arg(long)]
skip_verify: bool,
/// Skip caixa-deps-resolve (deps already materialized)
#[arg(long)]
skip_resolve: bool,
/// Force re-clone of deps in resolve stage
#[arg(long)]
force_resolve: bool,
},
/// caixa-deps-resolve — fetch + materialize :depends-on deps.
/// Reads <path>/.caixa-deps/MANIFEST.txt, clones each owner/repo
/// @rev to <path>/.caixa-deps/<safe-name>/clone/, finds its
/// .caixa.lisp at root, renders into a working tree at
/// <path>/.caixa-deps/<safe-name>/working/. With --transitive,
/// recurses into each dep's own .caixa-deps. Closes the typed
/// inheritance loop.
CaixaDepsResolve {
/// Path to a rendered/eaten dir containing .caixa-deps/
#[arg(long)]
path: PathBuf,
/// Force re-clone + re-render existing dep dirs
#[arg(long)]
force: bool,
/// Recurse into materialized deps' own manifests
#[arg(long, default_value_t = true)]
transitive: bool,
/// Max recursion depth for transitive resolution
#[arg(long, default_value_t = 5)]
max_depth: usize,
},
/// await-ci — poll gh until the latest auto-release workflow run
/// completes. Reports success/failure + run URL. The final
/// lifecycle verification: did the substrate's pipeline actually
/// build + test + publish on GitHub-Actions OSS compute?
AwaitCi {
/// Repo slug to poll (e.g. pleme-io/my-eaten-repo)
#[arg(long)]
repo: String,
/// Workflow file name (default: auto-release.yml)
#[arg(long, default_value = "auto-release.yml")]
workflow: String,
/// Max wait seconds (default: 900 = 15 min)
#[arg(long, default_value_t = 900)]
timeout: u64,
/// Poll interval seconds (default: 15)
#[arg(long, default_value_t = 15)]
poll: u64,
},
/// verify-tests — run ecosystem-appropriate tests on an eaten dir.
/// Detects ecosystem; runs cargo test / pytest / etc. Exit 0 only
/// when tests pass. The pre-ship local-CI gate.
VerifyTests {
/// Path to the rendered scaffold (typically <eaten>/<name>-rendered)
#[arg(long)]
rendered: PathBuf,
/// Override the auto-detected ecosystem (rare)
#[arg(long)]
ecosystem: Option<String>,
},
/// Absorb — byte-perfect file-content capture into a typed manifest.
/// Walks <path>, captures every text file (filtered via skip-dirs +
/// binary heuristics + size cap), emits a typed JSON manifest with
/// per-file content + sha256. Companion to `restore` — together
/// they prove complete-absorption round-trip works at the substrate
/// level.
Absorb {
/// Path to the repo / directory to absorb
#[arg(long)]
path: PathBuf,
/// Output JSON manifest path (default: ./absorbed.json)
#[arg(long, default_value = "absorbed.json")]
out: PathBuf,
/// Per-file byte cap (default: 8 MB)
#[arg(long, default_value_t = 8_388_608)]
max_file_bytes: usize,
/// Whole-tree byte cap (default: 100 MB)
#[arg(long, default_value_t = 104_857_600)]
max_total_bytes: usize,
},
/// Restore — reconstitute a directory tree from an absorb manifest.
/// Reads the JSON manifest, writes every captured file byte-
/// identical at its original relative path under <out>. Round-trip
/// from absorb is mechanically verifiable via sha256.
Restore {
/// Absorb manifest path
#[arg(long)]
manifest: PathBuf,
/// Output directory
#[arg(long)]
out: PathBuf,
/// Verify each restored file matches its captured sha256
#[arg(long)]
verify: bool,
},
/// reverse per subdir, emit one .caixa.lisp per detected subdir
/// into <out>. With --render-too, also runs caixa::render per
/// .caixa.lisp into <out>/<name>-rendered/. Mass-absorption of
/// any monorepo into typed sources in ONE substrate call.
ConsumeMonorepo {
/// Path to the monorepo root (each subdir is consumed)
#[arg(long)]
path: PathBuf,
/// Output directory (one <name>.caixa.lisp per consumed subdir)
#[arg(long)]
out: PathBuf,
/// Subdir names to skip (comma-separated)
#[arg(long, default_value = "")]
skip: String,
/// Also render each .caixa.lisp to a typed scaffold
#[arg(long)]
render_too: bool,
/// Also measure fidelity per subdir (compares original to
/// rendered output, populates aggregate score). Implies
/// --render-too.
#[arg(long)]
measure_fidelity: bool,
},
/// Reverse — given an existing OSS clone, emit the typed
/// (defcaixa …) source that describes it. Closes the OSS-absorption
/// loop: discover identifies the ecosystem; reverse extracts the
/// manifest fields into a typed lisp source the operator can edit
/// + re-render via `caixa --source` to migrate the repo to
/// caixa-native shape.
Reverse {
/// Path to inspect (a local clone of an OSS repository)
#[arg(long, default_value = ".")]
path: PathBuf,
/// Write to file instead of stdout
#[arg(long)]
out: Option<PathBuf>,
},
/// Fleet forge — read a (defcaixa-fleet …) tatara-lisp source
/// describing N caixas + explode N forges in one operator action.
/// Each member lands under <out>/<member-name>/; emits a typed
/// JSON report to stdout with per-member success/failure.
FleetForge {
/// Path to the .fleet.lisp source
#[arg(long)]
source: PathBuf,
/// Output root — each member lands under <out>/<member-name>/
#[arg(long, default_value = "./fleet")]
out: PathBuf,
},
/// One-shot OSS conversion — read a (defossconv …) tatara-lisp
/// source, run the 6-step agent workflow (parse / discover /
/// gate-A / forge / gate-B / publish), emit a typed JSON
/// attestation to stdout. The agent-facing primitive that
/// collapses the caixa-oss-conversion-agent skill's shell recipe
/// into a single substrate call.
Convert {
/// Path to the .ossconv.lisp source
#[arg(long)]
source: PathBuf,
/// Output root — forge artifacts land at <out>/<wrapper>
#[arg(long, default_value = "./conversions")]
out: PathBuf,
/// Required for :public / :private modes; refuses to push
/// without it. :dry-run mode ignores --yes (always safe).
#[arg(long)]
r#yes: bool,
},
/// Bulk discovery: read a YAML list of GitHub slugs OR run a GH
/// search query, and emit a publish-bulk-compatible inventory.yaml
/// with detected ecosystems + names. The closed-loop entry point —
/// feed the substrate a list (or search), get a typed inventory
/// ready to mass-publish typed wrappers.
///
/// Either --slugs or --gh-query must be set (--gh-query takes
/// precedence when both are given).
DiscoverBulk {
/// Path to a YAML file with a top-level list of slugs:
/// - owner/repo
/// - owner/another-repo
#[arg(long)]
slugs: Option<PathBuf>,
/// GH search query string (`gh search repos <Q>` syntax).
/// Example: "topic:rust-async stars:>500 archived:false"
/// → substrate finds matching OSS + emits typed inventory.
#[arg(long)]
gh_query: Option<String>,
/// Max search results when --gh-query is used (default: 50)
#[arg(long, default_value_t = 50)]
gh_limit: usize,
/// Optional output path for the generated inventory.yaml
/// (default: stdout)
#[arg(long)]
out: Option<PathBuf>,
/// Description template — uses `{slug}` as a placeholder
#[arg(long, default_value = "pleme-io typed wrapper for {slug}")]
description: String,
},
/// Bulk mass-generation: read a YAML inventory OR a GH search
/// query (--gh-query "...") and loop `gh-publish` for each result.
/// Inventory format (a list at the top level):
/// - name: my-crate
/// ecosystem: rust-single-crate
/// description: "..."
/// license: MIT # optional
/// kind: Biblioteca # optional
/// Requires `--yes` for the irreversible-action gate (same as gh-publish).
///
/// With --gh-query: the substrate runs discover-bulk inline to
/// synthesize the inventory + publishes the result in one call.
/// The most-automated consumption path — operator hands one
/// search string, substrate handles search → discover → forge →
/// push → autopublish for every match.
PublishBulk {
/// Path to the YAML inventory (mutually exclusive with --gh-query)
#[arg(long)]
inventory: Option<PathBuf>,
/// GH search query — when set, substrate runs discover-bulk
/// inline + publishes every detected match.
#[arg(long)]
gh_query: Option<String>,
/// Max search results when --gh-query is used (default: 25)
#[arg(long, default_value_t = 25)]
gh_limit: usize,
/// GitHub org or user namespace (default: pleme-io)
#[arg(long, default_value = "pleme-io")]
org: String,
/// Output directory (each repo lands under <out>/<name>)
#[arg(long, default_value = "./fleet")]
out: PathBuf,
/// Required: pass --yes to confirm bulk irreversible action
#[arg(long)]
r#yes: bool,
/// Make the created repos private (default: public for OSS cascade)
#[arg(long)]
private: bool,
/// Skip `gh repo create` + push — only render + git-init locally.
/// Useful for dry-run verification before mass-publishing.
#[arg(long)]
no_push: bool,
},
/// One-shot END-TO-END: forge a repo + `gh repo create` + push to
/// GitHub, kicking off the substrate auto-release.yml workflow on
/// first push. The operator's irreversible action — must pass
/// `--yes` explicitly to confirm. Sails directly into upstream
/// registry (crates.io / npm / pypi / etc.) within minutes.
GhPublish {
/// Repo / package name
#[arg(long)]
name: String,
/// Ecosystem keyword
#[arg(long)]
ecosystem: String,
/// Kind override
#[arg(long)]
kind: Option<String>,
/// One-line description
#[arg(long)]
description: Option<String>,
/// SPDX license identifier
#[arg(long)]
license: Option<String>,
/// GitHub org or user namespace (default: pleme-io)
#[arg(long, default_value = "pleme-io")]
org: String,
/// Output directory (default: ./<name>)
#[arg(long)]
out: Option<PathBuf>,
/// Required: pass --yes to confirm the irreversible repo create
#[arg(long)]
r#yes: bool,
/// Make the GitHub repo private (default: public for OSS cascade)
#[arg(long)]
private: bool,
},
}
/// Per-ecosystem test runner command. Returns the argv vector to spawn
/// in the rendered dir. None when the ecosystem has no standardized
/// in-repo test runner.
fn test_command_for(eco: &str) -> Option<Vec<String>> {
let argv: &[&str] = match eco {
"rust-single-crate" | "rust-workspace" => &["cargo", "test", "--lib", "--quiet"],
"npm" | "js-pnpm" => &["npm", "test"],
"js-deno" => &["deno", "test"],
"python" | "python-pdm" | "python-pipenv" => &["python", "-m", "pytest", "-q"],
"go" => &["go", "test", "./..."],
"helm" => &["helm", "lint", "."],
"github-action" => &["yamllint", "action.yml"],
"nix-flake" => &["nix", "flake", "check", "--no-build", "--accept-flake-config"],
"java-gradle-kts" => &["gradle", "test"],
"java-maven" => &["mvn", "test"],
"elixir-mix" => &["mix", "test"],
"ruby-gem" => &["bundle", "exec", "rspec"],
"zig" => &["zig", "build", "test"],
_ => return None,
};
Some(argv.iter().map(|s| s.to_string()).collect())
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let actions = scan(&cli.actions_dir)?;
match cli.cmd {
Cmd::Patterns => {
print!("{}", patterns::emit(&actions));
}
Cmd::Docs => {
let written = docs::write_per_action(&cli.actions_dir, &actions)?;
eprintln!("wrote {written} per-action READMEs");
}
Cmd::Index => {
let path = cli.actions_dir.join("README.md");
fs::write(&path, docs::emit_index(&actions))?;
eprintln!("wrote {}", path.display());
}
Cmd::All { patterns_out } => {
let docs_written = docs::write_per_action(&cli.actions_dir, &actions)?;
eprintln!("wrote {docs_written} per-action READMEs");
let index_path = cli.actions_dir.join("README.md");
fs::write(&index_path, docs::emit_index(&actions))?;
eprintln!("wrote {}", index_path.display());
let patterns_text = patterns::emit(&actions);
if let Some(out) = patterns_out {
fs::write(&out, &patterns_text)?;
eprintln!("wrote {}", out.display());
} else {
print!("{patterns_text}");
}
}
Cmd::Scaffold { name, ecosystem, kind, version, description, license,
repository, authors, group_id, out } => {
use crate::ast::Render;
let mut spec = scaffold::ScaffoldSpec::new(&name, &ecosystem);
spec.kind = kind;
spec.version = version;
spec.description = description;
spec.license = license;
spec.repository = repository;
spec.authors = authors;
spec.group_id = group_id;
let text = scaffold::build(&spec).render();
if let Some(path) = out {
fs::write(&path, &text)?;
eprintln!("scaffolded {} → {}", spec.ecosystem, path.display());
} else {
print!("{text}");
}
}
Cmd::Forge { name, ecosystem, kind, description, license, out, git_init } => {
use crate::ast::Render;
let target = out.unwrap_or_else(|| PathBuf::from(&name));
fs::create_dir_all(&target)?;
let mut spec = scaffold::ScaffoldSpec::new(&name, &ecosystem);
spec.kind = kind;
spec.description = description;
spec.license = license;
let src = scaffold::build(&spec).render();
// Persist the source itself for round-trip auditability.
let caixa_path = target.join(format!("{name}.caixa.lisp"));
fs::write(&caixa_path, &src)?;
let written = caixa::render(&src, &target, true)?;
eprintln!("forged {} files into {}", written.len(), target.display());
if git_init {
// 3-line shell glue — sandbox-allowed per the NO-SHELL rule.
let _ = std::process::Command::new("git")
.arg("init").arg("-q").current_dir(&target).status()?;
let _ = std::process::Command::new("git")
.args(["add", "-A"]).current_dir(&target).status()?;
let _ = std::process::Command::new("git")
.args(["commit", "-q", "-m", "init: caixa-forge scaffold"])
.current_dir(&target).status()?;
eprintln!("git initialized + first commit in {}", target.display());
}
}
Cmd::Ecosystems { ecosystem, json, full_only } => {
let mut caps = if let Some(eco) = ecosystem {
vec![ecosystems::query(&eco)]
} else {
ecosystems::query_all()
};
if full_only {
caps.retain(|c| c.fully_capable());
}
if json {
print!("{}", ecosystems::to_json(&caps));
} else {
print!("{}", ecosystems::to_text_table(&caps));
}
}
Cmd::CaixaInit { name, out, org, gh_create, r#yes, private } => {
let target = out.unwrap_or_else(|| PathBuf::from(&name));
let written = inventory_init::init(&target, &name)?;
eprintln!("✓ initialized {} files in {}", written.len(), target.display());
if gh_create {
if !r#yes {
anyhow::bail!(
"--gh-create requires --yes (creates a real GH repo at \
{org}/{name} and pushes)"
);
}
let _ = std::process::Command::new("git").arg("init").arg("-q")
.current_dir(&target).status()?;
std::process::Command::new("git").args(["add", "-A"])
.current_dir(&target).status()?;
std::process::Command::new("git")
.args(["commit", "-q", "-m", "init: caixa-forge inventory bootstrap"])
.current_dir(&target).status()?;
eprintln!("✓ git initialized + first commit");
let visibility = if private { "--private" } else { "--public" };
let mut slug = String::from(&org);
slug.push('/'); slug.push_str(&name);
let st = std::process::Command::new("gh")
.args(["repo", "create", &slug, visibility, "--source=.", "--push"])
.current_dir(&target).status()?;
anyhow::ensure!(st.success(), "gh repo create failed for {slug}");
eprintln!("✓ {slug} created on GitHub + pushed");
eprintln!();
eprintln!(" Watch: gh run watch -R {slug}");
eprintln!(" Add inventory entries: cd {} && vim inventory/...", target.display());
} else {
eprintln!();
eprintln!(" Next steps (manual):");
eprintln!(" cd {} && git init && git add -A", target.display());
eprintln!(" gh repo create {}/{} --public --source=. --push", org, name);
eprintln!(" # OR re-run with --gh-create --yes to do this automatically");
eprintln!(" # then add real .ossconv.lisp entries under inventory/ + push");
}
}
Cmd::Lint { path } => {
match validator::validate_dir(&path) {
Some((eco, issues)) => {
if issues.is_empty() {
println!("✓ {} — clean ({})", path.display(), eco);
} else {
eprintln!("✗ {} — {} issue(s) in {}", path.display(), issues.len(), eco);
for i in &issues {
eprintln!(" [{:?}] {}", i.kind, i.message);
}
std::process::exit(1);
}
}
None => {
eprintln!("no ecosystem detected in {}", path.display());
std::process::exit(2);
}
}
}
Cmd::MeasureFidelity { path } => {
let report = fidelity::measure_via_reverse_render(&path)?;
print!("{}", report.to_json());
if report.gap_count > 0 || report.lossy_count > 0 {
std::process::exit(1);
}
}
Cmd::ConsumeGhOrg { org, out, work_dir, limit, render_too, include_archived, measure_fidelity, verify_rendered } => {
let work_dir = work_dir.unwrap_or_else(|| {
let mut p = std::env::temp_dir();
p.push(format!("{org}-clones"));
p
});
// --measure-fidelity and --verify-rendered both imply --render-too.
let render = render_too || measure_fidelity || verify_rendered;
let report = consume_gh_org::consume_org(
&org, &out, &work_dir, limit, render, include_archived,
measure_fidelity, verify_rendered,
)?;
print!("{}", report.to_json());
if report.failed > 0 { std::process::exit(1); }
}
Cmd::SearchAndConsume { query, out, work_dir, limit, render_too, measure_fidelity } => {
let safe_q = query.replace(|c: char| !c.is_ascii_alphanumeric(), "_");
let work_dir = work_dir.unwrap_or_else(||
std::env::temp_dir().join(format!("search-clones-{safe_q}")));
let render = render_too || measure_fidelity;
let report = search_consume::search_and_consume(
&query, &out, &work_dir, limit, render, measure_fidelity)?;
print!("{}", report.to_json());
if report.failed > 0 { std::process::exit(1); }
}
Cmd::Instantiate { source, out, skip_verify, skip_resolve, force_resolve } => {
let cfg = instantiate::InstantiateConfig {
verify: !skip_verify, skip_resolve, force_resolve,
};
let report = instantiate::instantiate(&source, &out, &cfg)?;
print!("{}", report.to_json());
eprintln!("\ninstantiate: {}", report.final_status);
if !report.is_success() { std::process::exit(1); }
}
Cmd::CaixaDepsResolve { path, force, transitive, max_depth } => {
let cfg = caixa_deps::ResolveConfig { force, transitive, max_depth };
let report = caixa_deps::resolve(&path, &cfg)?;
print!("{}", report.to_json());
eprintln!("\nresolved {} deps ({} ok, {} failed)",
report.resolved.len(), report.success_count, report.failure_count);
if report.failure_count > 0 { std::process::exit(1); }
}
Cmd::EatAndShip {
path, out, target, skip_verify, skip_ship, skip_await,
visibility, description, commit_message, branch,
max_file_bytes, max_total_bytes,
await_timeout, await_poll, yes,
} => {
// Default target per substrate convention: pleme-io/caixa-<basename>
let target = target.unwrap_or_else(|| caixa_naming::default_target_slug(&path));
let vis = match visibility.as_str() {
"public" => ship::Visibility::Public,
"private" => ship::Visibility::Private,
"internal" => ship::Visibility::Internal,
other => return Err(anyhow::anyhow!(
"unknown visibility `{other}` (use public|private|internal)")),
};
let cfg = eat_and_ship::LifecycleConfig {
skip_verify, skip_ship, skip_await,
ship: ship::ShipConfig { visibility: vis, description, commit_message, branch },
await_cfg: await_ci::AwaitConfig {
timeout_seconds: await_timeout, poll_seconds: await_poll,
workflow: "auto-release.yml".to_string(),
},
capture: file_capture::CaptureConfig {
max_file_bytes, max_total_bytes,
..file_capture::CaptureConfig::default()
},
};
let report = eat_and_ship::eat_and_ship(&path, &out, &target, &cfg, !yes)?;
print!("{}", report.to_json());
eprintln!("\nlifecycle: {} (stages: {})",
report.final_status, report.stages_completed.join(" → "));
if !report.is_success() {
std::process::exit(1);
}
}
Cmd::Ship { target, rendered, visibility, description, commit_message, branch, yes } => {
// Default target: derive from rendered dir's basename.
// Convention strips a trailing `-rendered` suffix (eat
// creates dirs like `caixa-fd-rendered` → caixa-fd).
let target = target.unwrap_or_else(|| {
let base = rendered.file_name()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
let trimmed = base.strip_suffix("-rendered").unwrap_or(base);
format!("{}/{}{}", caixa_naming::DEFAULT_OWNER,
caixa_naming::CAIXA_PREFIX,
caixa_naming::sanitize_repo_name(trimmed))
});
let vis = match visibility.as_str() {
"public" => ship::Visibility::Public,
"private" => ship::Visibility::Private,
"internal" => ship::Visibility::Internal,
other => return Err(anyhow::anyhow!(
"unknown visibility `{other}` (use public|private|internal)")),
};
let cfg = ship::ShipConfig {
visibility: vis, description, commit_message, branch,
};
let report = ship::ship(&target, &rendered, &cfg, !yes)?;
print!("{}", report.to_json());
if report.dry_run {
eprintln!("\nDRY-RUN — pass --yes to execute. {} steps planned.",
report.steps_executed.len());
} else {
eprintln!("\nshipped → {}", report.repo_url.as_deref().unwrap_or("?"));
}
}
Cmd::AwaitCi { repo, workflow, timeout, poll } => {
let cfg = await_ci::AwaitConfig {
timeout_seconds: timeout, poll_seconds: poll, workflow,
};
let report = await_ci::await_ci(&repo, &cfg)?;
print!("{}", report.to_json());
if !report.is_success() {
eprintln!("\nawait-ci: NOT SUCCESS (status={} conclusion={:?})",
report.status, report.conclusion);
std::process::exit(1);
}
eprintln!("\nawait-ci: SUCCESS in {}s ({} polls)",
report.waited_seconds, report.polls);
}
Cmd::Eat { path, out, max_file_bytes, max_total_bytes, include_binaries } => {
let cfg = file_capture::CaptureConfig {
max_file_bytes, max_total_bytes, include_binaries,
..file_capture::CaptureConfig::default()
};
let report = eat::eat(&path, &out, &cfg)?;
print!("{}", report.to_json());
eprintln!("\neaten: {} files ({} bytes) → {} → {} artifacts",
report.captured_file_count, report.captured_bytes,
report.caixa_lisp_path.display(),
report.rendered_artifact_count);
}
Cmd::VerifyTests { rendered, ecosystem } => {
let eco = match ecosystem {
Some(e) => e,
None => discover::detect(&rendered)
.map(|d| d.ecosystem.to_string())
.ok_or_else(|| anyhow::anyhow!(
"could not detect ecosystem at {} — pass --ecosystem",
rendered.display()))?,
};
let cmd_str = test_command_for(&eco)
.ok_or_else(|| anyhow::anyhow!(
"no test runner configured for ecosystem `{eco}`"))?;
eprintln!("verify-tests [{eco}]: running `{}` in {}",
cmd_str.join(" "), rendered.display());
let status = std::process::Command::new(&cmd_str[0])
.args(&cmd_str[1..])
.current_dir(&rendered)
.status()
.map_err(|e| anyhow::anyhow!("spawn {}: {e}", cmd_str[0]))?;
if !status.success() {
eprintln!("verify-tests: FAILED (exit {})",
status.code().unwrap_or(-1));
std::process::exit(status.code().unwrap_or(1));
}
eprintln!("verify-tests: PASSED");
}
Cmd::Absorb { path, out, max_file_bytes, max_total_bytes } => {
let cfg = file_capture::CaptureConfig {
max_file_bytes, max_total_bytes,
..file_capture::CaptureConfig::default()
};
let report = file_capture::capture(&path, &cfg)?;
// Serialize via serde_json to a JSON manifest. Each file
// becomes {path, sha256, size, body}.
let entries: Vec<serde_json::Value> = report.files.iter().map(|f| {
serde_json::json!({
"path": f.path,
"sha256": f.sha256,
"size": f.size,
"body": f.body,
})
}).collect();
let root = serde_json::json!({
"source": path.to_string_lossy(),
"file_count": report.files.len(),
"total_bytes": report.total_bytes,
"skipped_binary": report.skipped_binary,
"skipped_too_large": report.skipped_too_large,
"skipped_dir": report.skipped_dir,
"skipped_total_cap": report.skipped_total_cap,
"files": entries,
});
fs::write(&out, serde_json::to_string_pretty(&root)?)?;
eprintln!("absorbed {} files ({} bytes) → {}",
report.files.len(), report.total_bytes, out.display());
}
Cmd::Restore { manifest, out, verify } => {
let text = fs::read_to_string(&manifest)?;
let root: serde_json::Value = serde_json::from_str(&text)?;
let files = root.get("files").and_then(|v| v.as_array())
.ok_or_else(|| anyhow::anyhow!("manifest missing :files array"))?;
let captured: Vec<file_capture::CapturedFile> = files.iter().filter_map(|f| {
let path = f.get("path")?.as_str()?.to_string();
let sha256 = f.get("sha256")?.as_str()?.to_string();
let size = f.get("size")?.as_u64()? as usize;
let body = f.get("body")?.as_str()?.to_string();
Some(file_capture::CapturedFile { path, sha256, size, body })
}).collect();
let written = file_capture::restore(&out, &captured)?;
eprintln!("restored {} files → {}", written.len(), out.display());
if verify {
let mut mismatches = 0;
for f in &captured {
let p = out.join(&f.path);
let bytes = fs::read(&p)?;
let actual = file_capture::hash_bytes(&bytes);
if actual != f.sha256 {
mismatches += 1;
eprintln!("MISMATCH {}: expected {} got {}", f.path, f.sha256, actual);
}
}
if mismatches > 0 {
eprintln!("verify: {} mismatched files of {}", mismatches, captured.len());
std::process::exit(1);
}
eprintln!("verify: all {} files byte-identical", captured.len());
}
}
Cmd::ConsumeMonorepo { path, out, skip, render_too, measure_fidelity } => {
let skip_list: Vec<String> = skip
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
// --measure-fidelity implies --render-too since fidelity
// measurement compares the original to the rendered output.
let render = render_too || measure_fidelity;
let report = consume_monorepo::consume(
&path, &out, &skip_list, render, measure_fidelity)?;
print!("{}", report.to_json());
if report.failed > 0 { std::process::exit(1); }
}
Cmd::Reverse { path, out } => {
use crate::ast::Render;
let forms = reverse::reverse_from_path(&path)?;
let text = forms.render();
if let Some(p) = out {
fs::write(&p, &text)?;
eprintln!("reversed {} → {}", path.display(), p.display());
} else {
print!("{text}");
}
}
Cmd::FleetForge { source, out } => {
let text = fs::read_to_string(&source)
.map_err(|e| anyhow::anyhow!("read {}: {e}", source.display()))?;
let spec = fleet::parse_str(&text)?;
let report = fleet::execute(&spec, &out);
print!("{}", report.to_json());
if !report.failed.is_empty() {
std::process::exit(1);
}
}
Cmd::Convert { source, out, r#yes } => {
let text = fs::read_to_string(&source)
.map_err(|e| anyhow::anyhow!("read {}: {e}", source.display()))?;
let spec = oss_conversion::parse_str(&text)?;
fs::create_dir_all(&out)?;
let att = oss_conversion::execute(&spec, &out, r#yes);
print!("{}", att.to_json());
// Exit code reflects gates: 0 = both pass, 1 = any failure.
if att.error.is_some() || !att.gate_a || !att.gate_b {
std::process::exit(1);
}
}
Cmd::Discover { path, url } => {
let detected = match url {
Some(slug) => discover::detect_github_url(&slug),
None => discover::detect(&path),
};
match detected {
Some(d) => {
println!("ecosystem: {}", d.ecosystem);
println!("name: {}", d.name);
println!("name-source: {}", d.name_source);
}
None => {
eprintln!("no ecosystem detected");
std::process::exit(2);
}
}
}
Cmd::DiscoverBulk { slugs, gh_query, gh_limit, out, description } => {
// Resolve input source: GH search takes precedence; falls
// back to YAML slug list.
let slug_list: Vec<String> = if let Some(q) = gh_query {
eprintln!("discover-bulk: searching GH for {q:?} (limit {gh_limit})");
let client = github_client::GhCliClient;
use github_client::GithubClient;
client.search_repos(&q, gh_limit)
.ok_or_else(|| anyhow::anyhow!("gh search returned no results / failed"))?
} else {
let p = slugs.ok_or_else(|| anyhow::anyhow!(
"either --slugs <yaml> or --gh-query <Q> must be set"
))?;
let text = fs::read_to_string(&p)?;
let list: Vec<String> = serde_yaml::from_str(&text)
.map_err(|e| anyhow::anyhow!("slugs YAML parse: {e}"))?;
eprintln!("discover-bulk: {} slugs from {}", list.len(), p.display());
list
};
// Emit each row as a typed inventory entry. Persist via
// a typed yaml_ast::Value::Map to keep the prime
// directive (no format!() of code/manifest text).
let mut rows = crate::yaml_ast::Value::arr([]);
let mut detected_count = 0;
for slug in &slug_list {
eprintln!(" · {slug}");
let det = discover::detect_github_url(slug);
let mut row = crate::yaml_ast::Value::map();
let name = slug.rsplit('/').next().unwrap_or(slug);
row.insert("name", crate::yaml_ast::Value::s(name));
if let Some(d) = det {
row.insert("ecosystem", crate::yaml_ast::Value::s(d.ecosystem));
detected_count += 1;
} else {
row.insert("ecosystem", crate::yaml_ast::Value::s("UNKNOWN"));
eprintln!(" ⚠ no ecosystem detected (left as UNKNOWN — manually set before publish-bulk)");
}
let mut desc = description.clone();
desc = desc.replace("{slug}", slug);
row.insert("description", crate::yaml_ast::Value::s(desc));
row.insert("upstream", crate::yaml_ast::Value::s(slug));
if let crate::yaml_ast::Value::Array(items) = &mut rows {
items.push(row);
}
}
let yaml_text = crate::ast::Render::render(&rows);
if let Some(p) = out {
fs::write(&p, &yaml_text)?;
eprintln!("\n✓ wrote inventory for {detected_count}/{} repos → {}", slug_list.len(), p.display());
} else {
print!("{yaml_text}");
eprintln!("\n✓ detected {detected_count}/{} repos", slug_list.len());
}
}
Cmd::PublishBulk { inventory, gh_query, gh_limit, org, out, r#yes, private, no_push } => {
let push = !no_push;
use crate::ast::Render;
use serde::Deserialize;
#[derive(Deserialize)]
struct Row {
name: String,
ecosystem: String,
#[serde(default)]
description: Option<String>,
#[serde(default)]
license: Option<String>,
#[serde(default)]
kind: Option<String>,
}
if !r#yes && push {
anyhow::bail!(
"publish-bulk creates real GitHub repos + pushes — \
pass --yes to confirm (or --no-push to only render locally)"
);
}
// Resolve rows: gh-query takes precedence; falls back to
// inventory YAML. With gh-query, every discovered slug
// becomes a Row with auto-detected ecosystem + default
// description template.
let rows: Vec<Row> = if let Some(q) = gh_query {
eprintln!("publish-bulk: searching GH for {q:?} (limit {gh_limit})");
let client = github_client::GhCliClient;
use github_client::GithubClient;
let slugs = client.search_repos(&q, gh_limit)
.ok_or_else(|| anyhow::anyhow!("gh search returned no results / failed"))?;
eprintln!(" found {} candidates", slugs.len());
let mut out_rows = Vec::new();
for slug in &slugs {
let name = slug.rsplit('/').next().unwrap_or(slug).to_string();
let det = discover::detect_github_url(slug);
let Some(d) = det else {
eprintln!(" ⚠ skip {slug}: no ecosystem detected");
continue;
};
let mut desc = String::from("pleme-io typed wrapper for ");
desc.push_str(slug);
out_rows.push(Row {
name,
ecosystem: d.ecosystem.to_string(),
description: Some(desc),
license: None,
kind: None,
});
}
eprintln!(" → {} typed rows ready to publish", out_rows.len());
out_rows
} else {
let p = inventory.ok_or_else(|| anyhow::anyhow!(
"either --inventory <yaml> or --gh-query <Q> must be set"
))?;
let text = fs::read_to_string(&p)?;
let list: Vec<Row> = serde_yaml::from_str(&text)
.map_err(|e| anyhow::anyhow!("inventory parse: {e}"))?;
eprintln!("publish-bulk: {} rows from {}", list.len(), p.display());
list
};
fs::create_dir_all(&out)?;
let mut ok: usize = 0;
let mut failed: Vec<String> = Vec::new();
for (i, row) in rows.iter().enumerate() {
let n = i + 1;
let total = rows.len();
eprintln!("\n── [{n}/{total}] {} ({}) ──", row.name, row.ecosystem);
let target = out.join(&row.name);
let res = (|| -> anyhow::Result<()> {
fs::create_dir_all(&target)?;
let mut repo_url = String::from("https://github.com/");
repo_url.push_str(&org); repo_url.push('/'); repo_url.push_str(&row.name);
let mut spec = scaffold::ScaffoldSpec::new(&row.name, &row.ecosystem);
spec.kind = row.kind.clone();
spec.description = row.description.clone();
spec.license = row.license.clone();
spec.repository = Some(repo_url);
let src = scaffold::build(&spec).render();
fs::write(target.join(format!("{}.caixa.lisp", row.name)), &src)?;
let written = caixa::render(&src, &target, true)?;
eprintln!(" ✓ forged {} files", written.len());
std::process::Command::new("git").arg("init").arg("-q")
.current_dir(&target).status()?;
std::process::Command::new("git").args(["add", "-A"])
.current_dir(&target).status()?;
std::process::Command::new("git")
.args(["commit", "-q", "-m", "init: caixa-forge scaffold"])
.current_dir(&target).status()?;
eprintln!(" ✓ git initialized");
if push {
let visibility = if private { "--private" } else { "--public" };
let mut slug = String::from(&org);
slug.push('/'); slug.push_str(&row.name);
let st = std::process::Command::new("gh")
.args(["repo", "create", &slug, visibility, "--source=.", "--push"])
.current_dir(&target).status()?;
anyhow::ensure!(st.success(), "gh repo create failed");
eprintln!(" ✓ pushed to {slug}");
}
Ok(())
})();
match res {
Ok(()) => ok += 1,
Err(e) => {
eprintln!(" ✗ {e}");
failed.push(row.name.clone());
}
}
}
eprintln!("\nbulk complete: {ok} ok, {} failed", failed.len());
if !failed.is_empty() {
eprintln!("failed rows: {}", failed.join(", "));
std::process::exit(1);
}
}
Cmd::GhPublish { name, ecosystem, kind, description, license,
org, out, r#yes, private } => {
use crate::ast::Render;
if !r#yes {
anyhow::bail!(
"gh-publish creates a real GitHub repo + pushes — \
pass --yes to confirm. (org={org}, name={name})"
);
}
let target = out.unwrap_or_else(|| PathBuf::from(&name));
fs::create_dir_all(&target)?;
// Build repository URL eagerly so the scaffold has the right
// :repository — substrate's auto-release uses this.
let mut repo_url = String::from("https://github.com/");
repo_url.push_str(&org); repo_url.push('/'); repo_url.push_str(&name);
let mut spec = scaffold::ScaffoldSpec::new(&name, &ecosystem);
spec.kind = kind;
spec.description = description;
spec.license = license;
spec.repository = Some(repo_url.clone());
let src = scaffold::build(&spec).render();
let caixa_path = target.join(format!("{name}.caixa.lisp"));
fs::write(&caixa_path, &src)?;
let written = caixa::render(&src, &target, true)?;
eprintln!("✓ forged {} files into {}", written.len(), target.display());
// git init + first commit
let git_status = std::process::Command::new("git")
.arg("init").arg("-q").current_dir(&target).status()?;
anyhow::ensure!(git_status.success(), "git init failed");
std::process::Command::new("git")
.args(["add", "-A"]).current_dir(&target).status()?;
std::process::Command::new("git")
.args(["commit", "-q", "-m", "init: caixa-forge scaffold"])
.current_dir(&target).status()?;
eprintln!("✓ git initialized + first commit");
// gh repo create + push (--source=. --push handles both)
let visibility = if private { "--private" } else { "--public" };
let mut slug = String::from(&org);
slug.push('/'); slug.push_str(&name);
let gh_status = std::process::Command::new("gh")
.args(["repo", "create", &slug, visibility, "--source=.", "--push"])
.current_dir(&target).status()?;
anyhow::ensure!(gh_status.success(), "gh repo create failed for {slug}");
eprintln!("✓ {slug} created on GitHub + pushed");
eprintln!();
eprintln!(" Substrate auto-release.yml will fire on the push, auto-bump");
eprintln!(" to v0.1.0, and publish to the {ecosystem} upstream registry.");
eprintln!(" Watch: gh run watch -R {slug}");
}
Cmd::Caixa { source, out, force } => {
let src = fs::read_to_string(&source)?;
let written = caixa::render(&src, &out, force)?;
eprintln!("rendered {} artifact(s) from {}:", written.len(), source.display());
for f in &written {
eprintln!(" {}", f.display());
}
}
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct Action {
pub name: String,
pub description: String,
pub inputs: BTreeMap<String, InputSpec>,
pub outputs: BTreeMap<String, String>,
pub category: String,
pub backend: String,
}
#[derive(Debug, Clone, Default)]
pub struct InputSpec {
pub required: bool,
pub default: Option<String>,
pub description: Option<String>,
}
fn scan(dir: &std::path::Path) -> anyhow::Result<Vec<Action>> {
let mut out = vec![];
for entry in fs::read_dir(dir)? {
let entry = entry?;
let name = entry.file_name().into_string().unwrap_or_default();
if name.starts_with('_') || name.starts_with('.') {
continue;
}
let action_yml = entry.path().join("action.yml");
if !action_yml.exists() {
continue;
}
let yml = fs::read_to_string(&action_yml)?;
let parsed = yaml::parse(&yml);
let category = category::categorize(&name).into();
let backend = if entry.path().join("run.tlisp").exists() {
"tatara-lisp".into()
} else {
"shell".into()
};
out.push(Action {
name,
description: parsed.description,
inputs: parsed.inputs,
outputs: parsed.outputs,
category,
backend,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
}