@thinkingai/ae-cli 6.1.33 → 6.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +2 -2
  2. package/README.zh.md +2 -6
  3. package/cli-installation-guide.md +14 -4
  4. package/dist/{ai-monitor-OHTSU6SV.js → ai-monitor-TVRFVZBH.js} +10 -9
  5. package/dist/ai-monitor.js +17 -16
  6. package/dist/{auth-2MOK4OI6.js → auth-JAXLMPBB.js} +25 -317
  7. package/dist/{automation-6L6IAYRK.js → automation-OQ647CSW.js} +7 -6
  8. package/dist/{capability-EMIHQJA3.js → capability-2Z4ZXTPD.js} +18 -16
  9. package/dist/chunk-2H3SFJE3.js +344 -0
  10. package/dist/{chunk-RC3PPCYD.js → chunk-3PZNM5KN.js} +3 -3
  11. package/dist/chunk-3ZQY7SLZ.js +147 -0
  12. package/dist/{chunk-NNK3JBH4.js → chunk-6E6HCTP2.js} +2 -2
  13. package/dist/{local-data-upload-client-YTWMAAGE.js → chunk-6IUTXRAD.js} +32 -4
  14. package/dist/{chunk-VLOGOM7N.js → chunk-CYZV5AXW.js} +8 -5
  15. package/dist/{chunk-O45NOIWR.js → chunk-DE5XHQQ6.js} +2 -2
  16. package/dist/{chunk-KD5UC33N.js → chunk-E5CJI7L3.js} +7 -5
  17. package/dist/{chunk-UCMO4LKL.js → chunk-EQMGH32F.js} +2 -2
  18. package/dist/{chunk-E3ONSFUN.js → chunk-FNACCKQR.js} +211 -12
  19. package/dist/{chunk-2I5SZ5DS.js → chunk-GD5JSAGV.js} +2 -2
  20. package/dist/{chunk-EFGUBGA6.js → chunk-GYODT7C4.js} +1 -1
  21. package/dist/chunk-HBI7IQH3.js +1207 -0
  22. package/dist/{chunk-AMURHMS3.js → chunk-IGU3R2JD.js} +4 -4
  23. package/dist/{chunk-YE6MJB5V.js → chunk-IWMDPHMI.js} +3 -3
  24. package/dist/{chunk-LFJ7N36I.js → chunk-L7MT53VM.js} +5 -3
  25. package/dist/{chunk-HIMOBNEY.js → chunk-LXRALNNA.js} +2 -2
  26. package/dist/{chunk-BQFLABJQ.js → chunk-M2OCZRVX.js} +7 -5
  27. package/dist/{chunk-R2SVAO4G.js → chunk-MTK4ZE7W.js} +3 -143
  28. package/dist/{chunk-7DHSB3FL.js → chunk-NK5PS5X7.js} +3 -3
  29. package/dist/{chunk-HQED4YB4.js → chunk-NPH5J65M.js} +1 -1
  30. package/dist/{chunk-EWVEAERM.js → chunk-Q764EZND.js} +78 -72
  31. package/dist/chunk-QOJXLXDJ.js +55 -0
  32. package/dist/{chunk-THTROEGD.js → chunk-QPUPWGZ3.js} +1 -1
  33. package/dist/{chunk-XZDKAR4N.js → chunk-RLPMXKDQ.js} +8921 -10119
  34. package/dist/{chunk-DWAG2QJM.js → chunk-S74XV3A6.js} +4 -4
  35. package/dist/{chunk-COOMXFUG.js → chunk-SHB7A2JE.js} +3 -3
  36. package/dist/{chunk-PLNS5J33.js → chunk-UWQXGF44.js} +17 -9
  37. package/dist/{data-integration-UNJ7EPW2.js → chunk-V6UKLIM6.js} +160 -2258
  38. package/dist/{chunk-4IQYPWCX.js → chunk-VPLRZSMY.js} +18 -10
  39. package/dist/{chunk-KA5WKR5P.js → chunk-Z6WSCIHM.js} +2 -2
  40. package/dist/{community-report-client-ULRNXLQV.js → community-report-client-5VNT6HCV.js} +4 -2
  41. package/dist/{compat-check-CADG7GND.js → compat-check-E7AQ7UCG.js} +5 -4
  42. package/dist/{config-PFD3KWQG.js → config-PGSUWIK5.js} +15 -11
  43. package/dist/{context-SOQDFZIB.js → context-Y2A6QIS3.js} +5 -4
  44. package/dist/conversion-4FR3RA45.js +16 -0
  45. package/dist/data-integration-EIF5QHYF.js +2138 -0
  46. package/dist/{evaluation-Q3AIGFOG.js → evaluation-OZM54MES.js} +6 -5
  47. package/dist/index.js +74 -51
  48. package/dist/local-data-upload-client-2U3LFD7Z.js +16 -0
  49. package/dist/{memory-HKNGUIPK.js → memory-6QMZS4HF.js} +7 -6
  50. package/dist/{metadata-GFWR5ZHC.js → metadata-7MZ3CJ2N.js} +10 -9
  51. package/dist/{model-NAKQWK4W.js → model-LEYRQKOS.js} +8 -7
  52. package/dist/{personal-semantic-preference-JCTKXLC3.js → personal-semantic-preference-SWOUNDWJ.js} +9 -8
  53. package/dist/{project-semantic-B2NWQOKK.js → project-semantic-M2DDPAMD.js} +9 -8
  54. package/dist/{sync-UQH4J4BD.js → sync-PWC63JCO.js} +16 -15
  55. package/dist/{te-agent-L6EYFQCC.js → te-agent-S7UH657Z.js} +11 -9
  56. package/dist/{te-analysis-U7NNOY66.js → te-analysis-BK6PE333.js} +281 -214
  57. package/dist/{te-community-3UQEW3KD.js → te-community-OLNTKGCW.js} +12 -10
  58. package/dist/{te-dataops-SUNYXF5G.js → te-dataops-XUWRIF5R.js} +12 -10
  59. package/dist/{te-engage-KMXZJ2KN.js → te-engage-I3I4FJOM.js} +9 -8
  60. package/dist/{te-experiment-IEYKP6VC.js → te-experiment-XSDUL4KH.js} +9 -8
  61. package/dist/{te-kb-MT3V5ZMH.js → te-kb-QFH3YLFQ.js} +15 -13
  62. package/dist/{te-system-F4ZU2HRQ.js → te-system-DB5Z3LLF.js} +7 -6
  63. package/dist/{te-team-M6E6XQ5H.js → te-team-UADF2HBO.js} +9 -8
  64. package/dist/{things-FRLBZV2Z.js → things-G2QFXDK7.js} +9 -8
  65. package/dist/{update-NULYHVE6.js → update-6I366ICW.js} +7 -8
  66. package/dist/web-runtime-3XFREWRF.js +2367 -0
  67. package/dist/{workspace-Z7L33OBQ.js → workspace-RZESYB6T.js} +7 -6
  68. package/package.json +4 -3
  69. package/skills/ae-analysis/SKILL.md +1 -1
  70. package/skills/ae-data-integration/references/ue-mapping.md +2 -0
  71. package/skills/ae-onboarding/SKILL.md +64 -0
  72. package/skills/ae-onboarding/references/business-sdk.md +8 -0
  73. package/skills/ae-onboarding/references/demo-operations.md +79 -0
  74. package/skills/ae-onboarding/references/import.md +19 -0
  75. package/skills/ae-onboarding/references/onboarding_experiment_launch.md +12 -0
  76. package/skills/ae-onboarding/references/onboarding_experiment_plan.md +14 -0
  77. package/skills/ae-onboarding/references/onboarding_growth.md +36 -0
  78. package/skills/ae-onboarding/references/onboarding_run.md +11 -0
  79. package/skills/ae-onboarding/references/onboarding_status.md +5 -0
  80. package/skills/ae-onboarding/scripts/experiment-preset.json +252 -0
  81. package/skills/ae-onboarding/scripts/experiment-requests.mjs +120 -0
  82. package/skills/ae-onboarding/scripts/generate.mjs +170 -0
  83. package/skills/ae-onboarding/scripts/resolve-experiment-preset.mjs +26 -0
  84. package/skills/ae-onboarding/scripts/web-journey.mjs +39 -0
  85. package/dist/chunk-6ZIQV5GW.js +0 -26
@@ -5,118 +5,31 @@ import {
5
5
  require_styles_xform,
6
6
  require_worksheet_reader,
7
7
  set_fs,
8
- utils,
9
- validateAndFix,
10
- validateDraft
11
- } from "./chunk-XZDKAR4N.js";
12
- import "./chunk-UCMO4LKL.js";
13
- import {
14
- require_archiver
15
- } from "./chunk-2I5SZ5DS.js";
16
- import "./chunk-HQED4YB4.js";
17
- import {
18
- getConfigDir
19
- } from "./chunk-AMURHMS3.js";
8
+ utils
9
+ } from "./chunk-RLPMXKDQ.js";
20
10
  import {
21
11
  CliValidationError,
22
- LocalDataUploadError,
23
12
  __toESM
24
- } from "./chunk-R2SVAO4G.js";
13
+ } from "./chunk-3ZQY7SLZ.js";
25
14
 
26
- // src/commands/data-integration/inspect.ts
27
- import { basename as basename3 } from "path";
28
-
29
- // src/commands/data-integration/estimate.ts
30
- var XLS_SIZE_WARN_BYTES = 100 * 1024 * 1024;
31
- var LARGE_FILE_WARN_BYTES = 1024 * 1024 * 1024;
32
- var XLS_HARD_LIMIT_BYTES = 1024 * 1024 * 1024;
33
- var THROUGHPUT_BYTES_PER_SECOND = {
34
- jsonl: 10 * 1024 * 1024,
35
- json: 8 * 1024 * 1024,
36
- csv: 4 * 1024 * 1024,
37
- tsv: 4 * 1024 * 1024,
38
- xlsx: 2 * 1024 * 1024,
39
- parquet: 8 * 1024 * 1024
40
- };
41
- var SLOW_ENCODINGS = /* @__PURE__ */ new Set(["gbk", "gb2312", "gb18030", "big5", "shift_jis", "euc-jp", "euc-kr"]);
42
- function estimateProcessingSeconds(format, sizeBytes, encoding) {
43
- if (format === "xls") return 0;
44
- let throughput = THROUGHPUT_BYTES_PER_SECOND[format];
45
- if (encoding && SLOW_ENCODINGS.has(encoding.toLowerCase())) throughput /= 2;
46
- return sizeBytes / throughput;
47
- }
48
- function formatDuration(seconds) {
49
- if (seconds < 60) {
50
- const low2 = Math.max(1, Math.round(seconds * 0.5));
51
- const high2 = Math.max(low2 + 1, Math.round(seconds * 1.5));
52
- return `roughly ${low2} to ${high2} seconds`;
53
- }
54
- const low = Math.max(1, Math.round(seconds / 60 * 0.5));
55
- const high = Math.max(low + 1, Math.round(seconds / 60 * 1.5));
56
- return `roughly ${low} to ${high} minutes`;
57
- }
58
- function humanSize(bytes) {
59
- if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
60
- return `${Math.round(bytes / (1024 * 1024))} MB`;
61
- }
62
- function xlsMemoryWarning(fileName, sizeBytes) {
63
- return `Warning: ${fileName} is ${humanSize(sizeBytes)} (XLS). The legacy XLS parser loads the entire workbook into memory, roughly 5-10x the file size. Prefer converting to XLSX or splitting the workbook first.`;
64
- }
65
- function largeFileTimeWarning(fileName, sizeBytes, format, encoding) {
66
- const duration = formatDuration(estimateProcessingSeconds(format, sizeBytes, encoding));
67
- return `Warning: ${fileName} is ${humanSize(sizeBytes)}; processing is estimated to take ${duration}. Consider splitting the file if that is too long.`;
68
- }
69
- function largeFileMemoryWarning(format) {
70
- if (format === "xlsx") {
71
- return "Memory risk: XLSX processing keeps the workbook's shared string table in memory, so peak memory can substantially exceed the file size.";
72
- }
73
- if (format === "json") {
74
- return "Memory risk: a JSON root object or a very large record may be materialized in memory during inspection, so peak memory can substantially exceed the file size.";
75
- }
76
- if (format === "parquet") {
77
- return "Memory risk: Parquet input is decoded whole-file into memory (the reader materializes the full table), so peak memory can be a multiple of the file size. Split large files by row group or partition.";
78
- }
79
- return null;
80
- }
81
- function assessFileSize(fileName, format, sizeBytes, encoding) {
82
- const baseAssessment = {
83
- size: humanSize(sizeBytes),
84
- estimatedDuration: null,
85
- warning: null,
86
- reason: null,
87
- memoryRisk: false,
88
- rejected: false
89
- };
90
- if (format === "xls") {
91
- if (sizeBytes > XLS_HARD_LIMIT_BYTES) {
92
- return {
93
- ...baseAssessment,
94
- reason: "XLS files larger than 1 GB are not supported; convert the workbook to XLSX or split it first.",
95
- memoryRisk: true,
96
- rejected: true
97
- };
98
- }
99
- if (sizeBytes > XLS_SIZE_WARN_BYTES) {
100
- return {
101
- ...baseAssessment,
102
- warning: xlsMemoryWarning(fileName, sizeBytes),
103
- memoryRisk: true
104
- };
105
- }
106
- return baseAssessment;
107
- }
108
- if (sizeBytes > LARGE_FILE_WARN_BYTES) {
109
- const memoryWarning = largeFileMemoryWarning(format);
110
- const timeWarning = largeFileTimeWarning(fileName, sizeBytes, format, encoding);
111
- return {
112
- ...baseAssessment,
113
- estimatedDuration: formatDuration(estimateProcessingSeconds(format, sizeBytes, encoding)),
114
- warning: memoryWarning ? `${timeWarning} ${memoryWarning}` : timeWarning,
115
- memoryRisk: Boolean(memoryWarning)
116
- };
117
- }
118
- return baseAssessment;
119
- }
15
+ // src/commands/data-integration/conversion.ts
16
+ import { randomInt as randomInt2, randomUUID } from "crypto";
17
+ import {
18
+ chmodSync,
19
+ createReadStream as createReadStream3,
20
+ createWriteStream,
21
+ existsSync,
22
+ mkdirSync,
23
+ readdirSync,
24
+ readFileSync as readFileSync4,
25
+ renameSync,
26
+ statSync as statSync2,
27
+ unlinkSync,
28
+ writeFileSync
29
+ } from "fs";
30
+ import { once } from "events";
31
+ import { basename as basename3, join, resolve } from "path";
32
+ import { createInterface as createInterface2 } from "readline";
120
33
 
121
34
  // src/commands/data-integration/input.ts
122
35
  var import_exceljs = __toESM(require_excel(), 1);
@@ -645,6 +558,98 @@ function isStrongDateTime(value) {
645
558
  return /^\d{4}[-/]\d{1,2}[-/]\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/.test(value.trim());
646
559
  }
647
560
 
561
+ // src/commands/data-integration/estimate.ts
562
+ var XLS_SIZE_WARN_BYTES = 100 * 1024 * 1024;
563
+ var LARGE_FILE_WARN_BYTES = 1024 * 1024 * 1024;
564
+ var XLS_HARD_LIMIT_BYTES = 1024 * 1024 * 1024;
565
+ var THROUGHPUT_BYTES_PER_SECOND = {
566
+ jsonl: 10 * 1024 * 1024,
567
+ json: 8 * 1024 * 1024,
568
+ csv: 4 * 1024 * 1024,
569
+ tsv: 4 * 1024 * 1024,
570
+ xlsx: 2 * 1024 * 1024,
571
+ parquet: 8 * 1024 * 1024
572
+ };
573
+ var SLOW_ENCODINGS = /* @__PURE__ */ new Set(["gbk", "gb2312", "gb18030", "big5", "shift_jis", "euc-jp", "euc-kr"]);
574
+ function estimateProcessingSeconds(format, sizeBytes, encoding) {
575
+ if (format === "xls") return 0;
576
+ let throughput = THROUGHPUT_BYTES_PER_SECOND[format];
577
+ if (encoding && SLOW_ENCODINGS.has(encoding.toLowerCase())) throughput /= 2;
578
+ return sizeBytes / throughput;
579
+ }
580
+ function formatDuration(seconds) {
581
+ if (seconds < 60) {
582
+ const low2 = Math.max(1, Math.round(seconds * 0.5));
583
+ const high2 = Math.max(low2 + 1, Math.round(seconds * 1.5));
584
+ return `roughly ${low2} to ${high2} seconds`;
585
+ }
586
+ const low = Math.max(1, Math.round(seconds / 60 * 0.5));
587
+ const high = Math.max(low + 1, Math.round(seconds / 60 * 1.5));
588
+ return `roughly ${low} to ${high} minutes`;
589
+ }
590
+ function humanSize(bytes) {
591
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
592
+ return `${Math.round(bytes / (1024 * 1024))} MB`;
593
+ }
594
+ function xlsMemoryWarning(fileName, sizeBytes) {
595
+ return `Warning: ${fileName} is ${humanSize(sizeBytes)} (XLS). The legacy XLS parser loads the entire workbook into memory, roughly 5-10x the file size. Prefer converting to XLSX or splitting the workbook first.`;
596
+ }
597
+ function largeFileTimeWarning(fileName, sizeBytes, format, encoding) {
598
+ const duration = formatDuration(estimateProcessingSeconds(format, sizeBytes, encoding));
599
+ return `Warning: ${fileName} is ${humanSize(sizeBytes)}; processing is estimated to take ${duration}. Consider splitting the file if that is too long.`;
600
+ }
601
+ function largeFileMemoryWarning(format) {
602
+ if (format === "xlsx") {
603
+ return "Memory risk: XLSX processing keeps the workbook's shared string table in memory, so peak memory can substantially exceed the file size.";
604
+ }
605
+ if (format === "json") {
606
+ return "Memory risk: a JSON root object or a very large record may be materialized in memory during inspection, so peak memory can substantially exceed the file size.";
607
+ }
608
+ if (format === "parquet") {
609
+ return "Memory risk: Parquet input is decoded whole-file into memory (the reader materializes the full table), so peak memory can be a multiple of the file size. Split large files by row group or partition.";
610
+ }
611
+ return null;
612
+ }
613
+ function assessFileSize(fileName, format, sizeBytes, encoding) {
614
+ const baseAssessment = {
615
+ size: humanSize(sizeBytes),
616
+ estimatedDuration: null,
617
+ warning: null,
618
+ reason: null,
619
+ memoryRisk: false,
620
+ rejected: false
621
+ };
622
+ if (format === "xls") {
623
+ if (sizeBytes > XLS_HARD_LIMIT_BYTES) {
624
+ return {
625
+ ...baseAssessment,
626
+ reason: "XLS files larger than 1 GB are not supported; convert the workbook to XLSX or split it first.",
627
+ memoryRisk: true,
628
+ rejected: true
629
+ };
630
+ }
631
+ if (sizeBytes > XLS_SIZE_WARN_BYTES) {
632
+ return {
633
+ ...baseAssessment,
634
+ warning: xlsMemoryWarning(fileName, sizeBytes),
635
+ memoryRisk: true
636
+ };
637
+ }
638
+ return baseAssessment;
639
+ }
640
+ if (sizeBytes > LARGE_FILE_WARN_BYTES) {
641
+ const memoryWarning = largeFileMemoryWarning(format);
642
+ const timeWarning = largeFileTimeWarning(fileName, sizeBytes, format, encoding);
643
+ return {
644
+ ...baseAssessment,
645
+ estimatedDuration: formatDuration(estimateProcessingSeconds(format, sizeBytes, encoding)),
646
+ warning: memoryWarning ? `${timeWarning} ${memoryWarning}` : timeWarning,
647
+ memoryRisk: Boolean(memoryWarning)
648
+ };
649
+ }
650
+ return baseAssessment;
651
+ }
652
+
648
653
  // src/commands/data-integration/parquet.ts
649
654
  import { readFileSync as readFileSync2 } from "fs";
650
655
  var TypeId = {
@@ -1845,6 +1850,11 @@ var MAPPING_VERSION = "ae-data-integration-mapping/v1";
1845
1850
  var VALID_PROPERTY_NAME = /^[a-z][a-z0-9_]{0,49}$/;
1846
1851
  var VALID_CHILD_PROPERTY_NAME = /^[a-z][a-z0-9_]{0,49}(\.[a-z][a-z0-9_]{0,49})+$/;
1847
1852
  var VALID_EVENT_NAME = /^[A-Za-z][A-Za-z0-9_]{0,49}$/;
1853
+ var EXPOSURE_PROPERTY_TYPES = /* @__PURE__ */ new Map([
1854
+ ["#experiment_id", "string"],
1855
+ ["#experiment_group_id", "string"],
1856
+ ["#is_control_group", "boolean"]
1857
+ ]);
1848
1858
  var FLATTEN_SUPPORTED_FORMATS = ["csv", "tsv", "json", "jsonl", "xls", "xlsx"];
1849
1859
  var SKIP_ROWS_SUPPORTED_FORMATS = ["csv", "tsv", "xls", "xlsx"];
1850
1860
  var XLSX_STRUCTURE_SUPPORTED_FORMATS = ["xlsx"];
@@ -1911,7 +1921,7 @@ function validateMapping(value, options) {
1911
1921
  const targets = /* @__PURE__ */ new Set();
1912
1922
  const propertyTypes = /* @__PURE__ */ new Map();
1913
1923
  for (const property of value.properties) {
1914
- if (!isRecord(property) || typeof property.source !== "string" || typeof property.target !== "string" || !(VALID_PROPERTY_NAME.test(property.target) || VALID_CHILD_PROPERTY_NAME.test(property.target)) || !["number", "string", "boolean", "datetime", "list", "object", "array_row"].includes(String(property.type)) || property.transform !== void 0 && !["stringify", "number", "boolean", "json"].includes(String(property.transform)) || property.value_mapping !== void 0 && !isStringMap(property.value_mapping) || property.time_format !== void 0 && (typeof property.time_format !== "string" || !property.time_format.trim() || property.time_format.length > 64) || property.desc !== void 0 && (typeof property.desc !== "string" || !property.desc.trim() || property.desc.length > 200)) {
1924
+ if (!isRecord(property) || typeof property.source !== "string" || typeof property.target !== "string" || !["number", "string", "boolean", "datetime", "list", "object", "array_row"].includes(String(property.type)) || !(VALID_PROPERTY_NAME.test(property.target) || VALID_CHILD_PROPERTY_NAME.test(property.target) || value.mode === "track" && (value.event_name_field || value.default_event_name === "te_experiment_exposure" && !value.value_mapping?.event_name) && EXPOSURE_PROPERTY_TYPES.get(property.target) === property.type) || property.transform !== void 0 && !["stringify", "number", "boolean", "json"].includes(String(property.transform)) || property.value_mapping !== void 0 && !isStringMap(property.value_mapping) || property.time_format !== void 0 && (typeof property.time_format !== "string" || !property.time_format.trim() || property.time_format.length > 64) || property.desc !== void 0 && (typeof property.desc !== "string" || !property.desc.trim() || property.desc.length > 200)) {
1915
1925
  throw mappingError("Every property mapping needs a source, legal AE target name, and supported type.");
1916
1926
  }
1917
1927
  if (targets.has(property.target)) throw mappingError("Property target names must be unique.");
@@ -3094,452 +3104,24 @@ function dominantTimeFormat(column) {
3094
3104
  return best && bestCount >= total * 0.9 ? best : void 0;
3095
3105
  }
3096
3106
 
3097
- // src/commands/data-integration/inspect.ts
3098
- var HEADERLESS_WARNING = "The first row appears to be data, not a header; columns were auto-named col_1..col_N. Re-run with --headers to supply explicit names.";
3099
- var dataIntegrationInspect = {
3100
- service: "data-integration",
3101
- command: "inspect",
3102
- usesAeHost: false,
3103
- description: "Stream one or more local CSV, TSV, TXT, JSON, JSONL, XLS, XLSX, or Parquet files and recommend a UE mapping.",
3104
- flags: [
3105
- { name: "input-file", type: "string", required: true, sensitive: true, variadic: true, desc: "Local CSV, TSV, TXT, JSON, JSONL, XLS, XLSX, or Parquet file. Repeat for multiple files." },
3106
- { name: "data-set", type: "string", sensitive: true, desc: "Sheet or JSON Path ID returned by a discovery-only inspection." },
3107
- { name: "source-timezone", type: "string", default: "Asia/Shanghai", desc: "IANA timezone used to interpret source times without an offset." },
3108
- { name: "headers", type: "string", sensitive: true, desc: "Comma-separated explicit column names for a headerless file; the first row is data." },
3109
- { name: "headerless", type: "boolean", default: false, desc: "Treat the first row as data and auto-generate col_1..col_N names." },
3110
- { name: "skip-rows", type: "number", default: 0, desc: "Discard the first N rows before the header row is read, for exports with a title or banner above the header. Delimited and Excel only." },
3111
- { name: "fill-merged-cells", type: "boolean", default: false, desc: "Copy each merged block value into the cells its own range covers, so rows below the first row of a merged block keep the value Excel displays. XLSX only; off by default because those cells are empty in the file." },
3112
- { name: "exclude-hidden-rows", type: "boolean", default: false, desc: "Leave rows hidden in the source worksheet out of the profile. XLSX only; off by default because a hidden row may still be real data." }
3113
- ],
3114
- risk: "read",
3115
- validate: (ctx) => {
3116
- const skipRows = ctx.num("skip-rows");
3117
- if (!Number.isInteger(skipRows) || skipRows < 0) {
3118
- throw new CliValidationError("Skipped rows must be a non-negative integer.", {
3119
- code: "LOCAL_DATA_SKIP_ROWS_INVALID",
3120
- location: { field: "skip-rows" }
3121
- });
3122
- }
3123
- },
3124
- // Fast size/time pre-check (stat + format/encoding sniff only — no sha256, no profile).
3125
- // Lets agents surface the estimate before committing to a multi-minute full inspection.
3126
- dryRun: async (ctx) => {
3127
- const files = ctx.list("input-file").map((filePath) => {
3128
- const meta = resolveLocalDataInputMeta(filePath);
3129
- const assessment = assessFileSize(basename3(filePath), meta.format, meta.sizeBytes, meta.encoding);
3130
- return {
3131
- file: basename3(filePath),
3132
- format: meta.format,
3133
- size_bytes: meta.sizeBytes,
3134
- size: assessment.size,
3135
- ...assessment.estimatedDuration ? { estimated_duration: assessment.estimatedDuration } : {},
3136
- ...assessment.warning ? { warning: assessment.warning } : {},
3137
- ...assessment.reason ? { reason: assessment.reason } : {},
3138
- ...assessment.memoryRisk ? { memory_risk: true } : {},
3139
- ...assessment.rejected ? { rejected: true } : {}
3140
- };
3107
+ // src/commands/data-integration/conversion.ts
3108
+ var SORT_CHUNK_SIZE = 1e4;
3109
+ var THREE_YEARS_MS = 3 * 365 * 24 * 60 * 60 * 1e3;
3110
+ var THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1e3;
3111
+ async function convertLocalData(options) {
3112
+ const input = await inspectLocalDataInput(options.inputFile);
3113
+ if (input.format !== options.mapping.source.format) {
3114
+ throw new CliValidationError("The source file format does not match the mapping.", {
3115
+ code: "LOCAL_DATA_SOURCE_FORMAT_CHANGED",
3116
+ location: { field: "input-file" }
3141
3117
  });
3142
- return {
3143
- version: "ae-local-data-estimate/v1",
3144
- files,
3145
- has_large_file: files.some((file) => Boolean(file.warning) || file.rejected)
3146
- };
3147
- },
3148
- execute: async (ctx) => {
3149
- const inputFiles = ctx.list("input-file");
3150
- const headerNames = splitHeaders(ctx.str("headers"));
3151
- const noHeader = ctx.bool("headerless");
3152
- const sourceTimezone = ctx.str("source-timezone");
3153
- const requested = ctx.str("data-set").trim() || void 0;
3154
- const skipRows = ctx.num("skip-rows");
3155
- const fillMergedCells = ctx.bool("fill-merged-cells");
3156
- const excludeHiddenRows = ctx.bool("exclude-hidden-rows");
3157
- if (inputFiles.length === 1) {
3158
- const input = await inspectLocalDataInput(inputFiles[0]);
3159
- const headerConsistency = await readExcelHeaderConsistency(input);
3160
- const excludedSheets = summarizeExcludedSheets(input);
3161
- if (!requested && input.dataSets.length > 1) {
3162
- return {
3163
- version: "ae-local-data-profile/v1",
3164
- selection_required: true,
3165
- source: { format: input.format, size_bytes: input.sizeBytes, sha256: input.sha256 },
3166
- data_sets: input.dataSets,
3167
- ...excludedSheets,
3168
- ...headerConsistency ?? {},
3169
- next_step: "Run inspect again with --data-set, then review the recommended mapping."
3170
- };
3171
- }
3172
- const dataSet = selectDataSet(input, requested);
3173
- const headerPresence = headerNames || noHeader ? void 0 : detectHeaderPresence(input, skipRows);
3174
- const headerSignal = headerNames || noHeader ? void 0 : await detectHeaderSignal(input, dataSet, skipRows);
3175
- const profile = await profileLocalData(input, dataSet, sourceTimezone, {
3176
- collectSamples: true,
3177
- collectNestedTree: true,
3178
- headerNames,
3179
- noHeader: noHeader || Boolean(headerPresence),
3180
- skipRows,
3181
- fillMergedCells,
3182
- excludeHiddenRows
3183
- });
3184
- const annotated = headerPresence ? annotateHeaderless(profile, headerPresence) : profile;
3185
- return {
3186
- ...annotated,
3187
- ...excludedSheets,
3188
- ...headerConsistency ?? {},
3189
- ...annotateRowSkips(annotated.warnings, skipRows, headerSignal)
3190
- };
3191
- }
3192
- const files = [];
3193
- if (inputFiles.every((file) => resolveLocalDataInputMeta(file).format === "parquet")) {
3194
- const checked = await inspectParquetFiles(inputFiles, sourceTimezone);
3195
- if (checked) return checked;
3196
- }
3197
- for (const inputFile of inputFiles) {
3198
- const input = await inspectLocalDataInput(inputFile);
3199
- const dataSet = selectDataSet(input);
3200
- const headerPresence = headerNames || noHeader ? void 0 : detectHeaderPresence(input, skipRows);
3201
- const headerSignal = headerNames || noHeader ? void 0 : await detectHeaderSignal(input, dataSet, skipRows);
3202
- const profile = await profileLocalData(input, dataSet, sourceTimezone, {
3203
- collectSamples: true,
3204
- collectNestedTree: true,
3205
- headerNames,
3206
- noHeader: noHeader || Boolean(headerPresence),
3207
- skipRows,
3208
- fillMergedCells,
3209
- excludeHiddenRows
3210
- });
3211
- const annotated = headerPresence ? annotateHeaderless(profile, headerPresence) : profile;
3212
- const headerConsistency = await readExcelHeaderConsistency(input);
3213
- files.push({
3214
- file: basename3(inputFile),
3215
- profile: {
3216
- ...annotated,
3217
- ...summarizeExcludedSheets(input),
3218
- ...headerConsistency ?? {},
3219
- ...annotateRowSkips(annotated.warnings, skipRows, headerSignal)
3220
- }
3221
- });
3222
- }
3223
- return {
3224
- version: "ae-local-data-profile/v1",
3225
- files: files.map((entry) => entry.profile),
3226
- conflicts: detectColumnTypeConflicts(files),
3227
- column_union: buildColumnUnion(files)
3228
- };
3229
- }
3230
- };
3231
- async function inspectParquetFiles(inputFiles, sourceTimezone) {
3232
- const firstPath = inputFiles[0];
3233
- const firstSchema = await readParquetSchema(firstPath);
3234
- const first = await inspectLocalDataInput(firstPath);
3235
- const profile = await profileLocalData(first, selectDataSet(first), sourceTimezone, {
3236
- collectSamples: true,
3237
- collectNestedTree: true
3238
- });
3239
- const files = [];
3240
- let totalRowCount = 0;
3241
- let totalSizeBytes = 0;
3242
- for (const inputFile of inputFiles) {
3243
- const meta = resolveLocalDataInputMeta(inputFile);
3244
- const schema = inputFile === firstPath ? firstSchema : await readParquetSchema(inputFile);
3245
- if (schema.signature !== firstSchema.signature) return void 0;
3246
- files.push({ file: basename3(inputFile), row_count: schema.numRows, size_bytes: meta.sizeBytes });
3247
- totalRowCount += schema.numRows;
3248
- totalSizeBytes += meta.sizeBytes;
3249
- }
3250
- return {
3251
- version: "ae-local-data-profile/v1",
3252
- schema_checked: true,
3253
- representative: { file: basename3(firstPath), profile },
3254
- files,
3255
- total_row_count: totalRowCount,
3256
- total_size_bytes: totalSizeBytes
3257
- };
3258
- }
3259
- function summarizeExcludedSheets(input) {
3260
- const excluded = input.excludedDataSets ?? [];
3261
- if (excluded.length === 0) return {};
3262
- return {
3263
- excluded_sheets: excluded.map((dataSet) => ({ name: dataSet.label, reason: "hidden", data_set: dataSet.id }))
3264
- };
3265
- }
3266
- async function readExcelHeaderConsistency(input) {
3267
- if (input.format !== "xls" && input.format !== "xlsx") return void 0;
3268
- return summarizeHeaderConsistency(await readExcelSheetHeaders(input.filePath, input.format));
3269
- }
3270
- function summarizeHeaderConsistency(sheets) {
3271
- if (sheets.length <= 1) return void 0;
3272
- const first = JSON.stringify(sheets[0].headers);
3273
- const allSame = sheets.every((sheet) => JSON.stringify(sheet.headers) === first);
3274
- return allSame ? { header_consistency: "all_same" } : { header_consistency: "different", header_details: sheets.map((sheet) => ({ name: sheet.name, headers: sheet.headers })) };
3275
- }
3276
- function detectHeaderPresence(input, skipRows = 0) {
3277
- if (input.format !== "csv" && input.format !== "tsv") return void 0;
3278
- const delimiter = input.delimiter ?? (input.format === "tsv" ? " " : ",");
3279
- const peeked = peekDelimitedRecords(input.filePath, { delimiter, encoding: input.encoding, limit: 10 + skipRows });
3280
- const records = peeked.slice(skipRows);
3281
- const detection = detectHeaderRow(records);
3282
- if (detection.hasHeaders) return void 0;
3283
- return {
3284
- detection,
3285
- autoHeaders: (records[0] ?? []).map((_, index) => `col_${index + 1}`)
3286
- };
3287
- }
3288
- async function detectHeaderSignal(input, dataSet, skipRows) {
3289
- const rows = await peekHeaderRows(input, dataSet, skipRows);
3290
- if (!rows || rows.length === 0) return void 0;
3291
- const titleRows = detectLeadingTitleRows(rows).map((title) => ({ ...title, row: title.row + skipRows }));
3292
- if (input.format !== "xlsx") return titleRows.length > 0 ? { titleRows } : void 0;
3293
- const detection = detectHeaderRow(rows.map((row) => row.map((value) => isEmptyCell(value) ? "" : String(value))));
3294
- if (detection.hasHeaders && titleRows.length === 0) return void 0;
3295
- return { ...detection.hasHeaders ? {} : { detection }, titleRows };
3296
- }
3297
- async function peekHeaderRows(input, dataSet, skipRows) {
3298
- if (input.format === "csv" || input.format === "tsv") {
3299
- const delimiter = input.delimiter ?? (input.format === "tsv" ? " " : ",");
3300
- return peekDelimitedRecords(input.filePath, { delimiter, encoding: input.encoding, limit: 10 + skipRows }).slice(skipRows);
3301
3118
  }
3302
- if (input.format === "xlsx" && dataSet.kind === "sheet") {
3303
- return (await peekXlsxRows(input.filePath, dataSet.label, 10 + skipRows)).slice(skipRows);
3304
- }
3305
- return void 0;
3306
- }
3307
- function isEmptyCell(value) {
3308
- return value === null || value === void 0 || value === "";
3309
- }
3310
- var TITLE_ROW_WARNING = "The first rows here hold a single value each, which looks like a title or banner above the real header row; the header was still read from the first row. See leading_title_rows and re-run with --skip-rows N if that is what they are.";
3311
- var EXCEL_HEADERLESS_WARNING = "The first row of this worksheet looks like data rather than a header, but it was still used as the header. See header_signal, and re-run with --headers or --headerless if it is data.";
3312
- function annotateRowSkips(warnings, skipRows, signal) {
3313
- const extra = [];
3314
- if (signal?.titleRows.length) extra.push(TITLE_ROW_WARNING);
3315
- if (signal?.detection) extra.push(EXCEL_HEADERLESS_WARNING);
3316
- return {
3317
- warnings: extra.length > 0 ? [...warnings, ...extra] : warnings,
3318
- ...skipRows > 0 ? { skipped_rows: skipRows } : {},
3319
- ...signal?.titleRows.length ? { leading_title_rows: signal.titleRows } : {},
3320
- ...signal?.detection ? { header_signal: signal.detection } : {}
3321
- };
3322
- }
3323
- function annotateHeaderless(profile, presence) {
3324
- return {
3325
- ...profile,
3326
- no_headers: true,
3327
- header_detection: presence.detection,
3328
- auto_headers: presence.autoHeaders,
3329
- warnings: [...profile.warnings, HEADERLESS_WARNING]
3330
- };
3331
- }
3332
- function splitHeaders(raw) {
3333
- const value = raw.trim();
3334
- if (!value) return void 0;
3335
- const headers = value.split(",").map((header) => header.trim()).filter((header) => header.length > 0);
3336
- return headers.length > 0 ? headers : void 0;
3337
- }
3338
-
3339
- // src/commands/data-integration/plan.ts
3340
- import { writeFile } from "fs/promises";
3341
- var VALID_LOCALES = /* @__PURE__ */ new Set(["zh", "en", "ja", "ko"]);
3342
- var EVENT_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
3343
- function toPropType(type) {
3344
- switch (type) {
3345
- case "number":
3346
- return "number";
3347
- case "boolean":
3348
- return "bool";
3349
- case "datetime":
3350
- return "datetime";
3351
- case "list":
3352
- return "array_string";
3353
- case "object":
3354
- return "object";
3355
- case "array_row":
3356
- return "array_row";
3357
- case "string":
3358
- return "string";
3359
- }
3360
- }
3361
- function buildDraftFromMapping(options) {
3362
- const { mapping } = options;
3363
- const excluded = new Set(mapping.exclude_columns ?? []);
3364
- const properties = mapping.properties.filter((property) => !excluded.has(property.source)).map((property) => {
3365
- const leaf = property.target.includes(".") ? property.target.split(".").pop() : void 0;
3366
- return {
3367
- name: property.target,
3368
- display_name: leaf ?? property.source,
3369
- desc: property.desc ?? leaf ?? property.source,
3370
- type: toPropType(property.type),
3371
- source: "data"
3372
- };
3373
- });
3374
- const propNames = properties.map((property) => property.name);
3375
- const eventNames = resolveEventNames(options);
3376
- const events = eventNames.map((eventName) => {
3377
- const meta = mapping.event_meta?.[eventName];
3378
- const sourceName = reverseEventSourceName(mapping, eventName) ?? eventName;
3379
- return {
3380
- event_name: eventName,
3381
- display_name: eventName,
3382
- event_desc: meta?.desc ?? sourceName,
3383
- event_tag: meta?.tag ?? sourceName,
3384
- source: "data",
3385
- prop_names: propNames
3386
- };
3387
- });
3388
- const isUserSet = mapping.mode === "user_set";
3389
- const isMixed = mapping.mode === "mixed";
3390
- return {
3391
- meta: {
3392
- app_type: options.appType,
3393
- sdk_integration_mode: "none",
3394
- plan_name: options.planName,
3395
- source_type: "data",
3396
- lang: options.lang,
3397
- ...options.projectId !== void 0 ? { project_id: options.projectId } : {}
3398
- },
3399
- events: isUserSet ? [] : events,
3400
- event_properties: isUserSet ? [] : properties,
3401
- common_event_properties: [],
3402
- user_properties: isUserSet || isMixed ? properties.map((property) => ({ ...property, update_type: "user_set" })) : []
3403
- };
3404
- }
3405
- function reverseEventSourceName(mapping, eventName) {
3406
- const eventMap = mapping.value_mapping?.event_name;
3407
- if (!eventMap) return void 0;
3408
- return Object.keys(eventMap).find((source) => eventMap[source] === eventName);
3409
- }
3410
- function resolveEventNames(options) {
3411
- const { mapping } = options;
3412
- if (mapping.mode === "user_set") return [];
3413
- if (options.eventNames.length > 0) {
3414
- const seen = /* @__PURE__ */ new Set();
3415
- for (const name of options.eventNames) {
3416
- if (!EVENT_NAME_RE.test(name)) {
3417
- throw new CliValidationError(`The event name "${name}" is not a legal AE event name.`, {
3418
- code: "LOCAL_DATA_PLAN_INVALID_EVENT_NAME",
3419
- hint: "Event names must match ^[A-Za-z][A-Za-z0-9_]*$.",
3420
- location: { field: "event-name" }
3421
- });
3422
- }
3423
- seen.add(name);
3424
- }
3425
- return [...seen];
3426
- }
3427
- if (mapping.default_event_name) return [mapping.default_event_name];
3428
- throw new CliValidationError("The mapping derives event names from a per-row column.", {
3429
- code: "LOCAL_DATA_PLAN_EVENT_NAMES_REQUIRED",
3430
- hint: "Pass --event-name for each concrete event name, or set default_event_name in the mapping.",
3431
- location: { field: "event-name" }
3432
- });
3433
- }
3434
- function summarize(draft) {
3435
- return {
3436
- plan_name: draft.meta.plan_name,
3437
- events: draft.events.length,
3438
- event_properties: draft.event_properties.length,
3439
- user_properties: draft.user_properties.length
3440
- };
3441
- }
3442
- function buildPlanDraft(ctx) {
3443
- const mapping = readLocalDataMapping(ctx.str("mapping"));
3444
- const lang = ctx.str("lang");
3445
- if (!VALID_LOCALES.has(lang)) {
3446
- throw new CliValidationError("lang must be one of zh, en, ja, ko.", {
3447
- code: "LOCAL_DATA_PLAN_INVALID_LANG",
3448
- location: { field: "lang" }
3449
- });
3450
- }
3451
- const draft = buildDraftFromMapping({
3452
- mapping,
3453
- planName: ctx.str("plan-name").trim() || mapping.default_event_name || "local-data",
3454
- eventNames: ctx.list("event-name"),
3455
- appType: ctx.str("app-type").trim() || "unknown",
3456
- lang,
3457
- projectId: ctx.optionalNum("project-id")
3458
- });
3459
- validateAndFix(draft);
3460
- try {
3461
- validateDraft(draft);
3462
- } catch (error) {
3463
- throw new CliValidationError("The tracking-plan draft is invalid.", {
3464
- code: "LOCAL_DATA_PLAN_INVALID_DRAFT",
3465
- hint: error instanceof Error ? error.message : String(error),
3466
- location: { field: "mapping" }
3467
- });
3468
- }
3469
- return draft;
3470
- }
3471
- var dataIntegrationPlan = {
3472
- service: "data-integration",
3473
- command: "plan",
3474
- usesAeHost: false,
3475
- description: "Convert a confirmed local-data mapping into a tracking-plan draft.json (source_type=data, sdk_integration_mode=none).",
3476
- flags: [
3477
- { name: "mapping", type: "string", required: true, sensitive: true, desc: `Confirmed ${MAPPING_VERSION} JSON, file path, or @file.` },
3478
- { name: "event-name", type: "string", variadic: true, desc: "Concrete event name (track/mixed without default_event_name). Repeat for multiple events." },
3479
- { name: "plan-name", type: "string", desc: 'Plan name. Default: the mapping default_event_name, else "local-data".' },
3480
- { name: "app-type", type: "string", default: "unknown", desc: "Application type recorded in draft meta (informational)." },
3481
- { name: "lang", type: "string", default: "zh", desc: "xlsx output language: zh / en / ja / ko." },
3482
- { name: "project-id", type: "number", desc: "AE project ID recorded in draft meta (informational)." },
3483
- { name: "out", type: "string", sensitive: true, desc: "Write draft.json to this file instead of stdout." }
3484
- ],
3485
- risk: "write",
3486
- dryRun: async (ctx) => {
3487
- const draft = buildPlanDraft(ctx);
3488
- return {
3489
- action: "plan_local_data",
3490
- plan_name: draft.meta.plan_name,
3491
- sdk_integration_mode: draft.meta.sdk_integration_mode,
3492
- source_type: draft.meta.source_type,
3493
- events: draft.events.map((event) => event.event_name),
3494
- event_properties: draft.events[0]?.prop_names ?? [],
3495
- user_properties: draft.user_properties.map((property) => property.name)
3496
- };
3497
- },
3498
- execute: async (ctx) => {
3499
- const draft = buildPlanDraft(ctx);
3500
- const outPath = ctx.str("out").trim() || void 0;
3501
- if (!outPath) return draft;
3502
- await writeFile(outPath, `${JSON.stringify(draft, null, 2)}
3503
- `, "utf8");
3504
- return { draft_path: outPath, ...summarize(draft) };
3505
- }
3506
- };
3507
-
3508
- // src/commands/data-integration/conversion.ts
3509
- import { randomInt as randomInt2, randomUUID } from "crypto";
3510
- import {
3511
- chmodSync,
3512
- createReadStream as createReadStream3,
3513
- createWriteStream,
3514
- existsSync,
3515
- mkdirSync,
3516
- readdirSync,
3517
- readFileSync as readFileSync4,
3518
- renameSync,
3519
- statSync as statSync2,
3520
- unlinkSync,
3521
- writeFileSync
3522
- } from "fs";
3523
- import { once } from "events";
3524
- import { basename as basename4, join, resolve } from "path";
3525
- import { createInterface as createInterface2 } from "readline";
3526
- var SORT_CHUNK_SIZE = 1e4;
3527
- var THREE_YEARS_MS = 3 * 365 * 24 * 60 * 60 * 1e3;
3528
- var THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1e3;
3529
- async function convertLocalData(options) {
3530
- const input = await inspectLocalDataInput(options.inputFile);
3531
- if (input.format !== options.mapping.source.format) {
3532
- throw new CliValidationError("The source file format does not match the mapping.", {
3533
- code: "LOCAL_DATA_SOURCE_FORMAT_CHANGED",
3534
- location: { field: "input-file" }
3535
- });
3536
- }
3537
- if (input.sha256 !== options.mapping.source.sha256) {
3538
- throw new CliValidationError("The source file does not match the mapping fingerprint.", {
3539
- code: "LOCAL_DATA_SOURCE_CHANGED",
3540
- hint: "Run ae-cli data-integration inspect again and review the new mapping before conversion.",
3541
- location: { field: "input-file" }
3542
- });
3119
+ if (input.sha256 !== options.mapping.source.sha256) {
3120
+ throw new CliValidationError("The source file does not match the mapping fingerprint.", {
3121
+ code: "LOCAL_DATA_SOURCE_CHANGED",
3122
+ hint: "Run ae-cli data-integration inspect again and review the new mapping before conversion.",
3123
+ location: { field: "input-file" }
3124
+ });
3543
3125
  }
3544
3126
  const dataSet = options.mergeSheets ? { id: "all-sheets", kind: "sheet", label: "all-sheets", selector: "all-sheets" } : selectDataSet(input, options.mapping.source.data_set);
3545
3127
  const streamOptions = {
@@ -3675,7 +3257,7 @@ async function convertLocalData(options) {
3675
3257
  run_id: runId,
3676
3258
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
3677
3259
  status: blockedReasons.length > 0 ? "blocked" : "ready",
3678
- ...options.salvageFrom ? { salvage_from: basename4(options.salvageFrom) } : {},
3260
+ ...options.salvageFrom ? { salvage_from: basename3(options.salvageFrom) } : {},
3679
3261
  source: {
3680
3262
  sha256: input.sha256,
3681
3263
  format: input.format,
@@ -3683,9 +3265,9 @@ async function convertLocalData(options) {
3683
3265
  size_bytes: input.sizeBytes
3684
3266
  },
3685
3267
  output: {
3686
- valid_file: basename4(validPath),
3268
+ valid_file: basename3(validPath),
3687
3269
  valid_sha256: await sha256File(validPath),
3688
- invalid_file: basename4(invalidPath),
3270
+ invalid_file: basename3(invalidPath),
3689
3271
  source_rows: sourceRows,
3690
3272
  valid_records: validRecords,
3691
3273
  invalid_records: invalidRecords,
@@ -3719,7 +3301,7 @@ async function convertLocalDataMulti(options) {
3719
3301
  flattenRules: options.mapping.flatten_rules,
3720
3302
  warnRagged: false
3721
3303
  });
3722
- profiled.push({ file: basename4(inputFile), profile });
3304
+ profiled.push({ file: basename3(inputFile), profile });
3723
3305
  }
3724
3306
  const conflicts = detectColumnTypeConflicts(profiled);
3725
3307
  const resolutions = options.typeResolutions ?? {};
@@ -3817,6 +3399,7 @@ function convertRow(row, rowNumber, mapping, now) {
3817
3399
  const properties = {};
3818
3400
  for (const property of mapping.properties) {
3819
3401
  if (property.target.includes(".")) continue;
3402
+ if (property.target.startsWith("#") && eventName !== "te_experiment_exposure") continue;
3820
3403
  if (excluded.has(property.source)) continue;
3821
3404
  let value = stripQuotes(row[property.source]);
3822
3405
  if (isMissing2(value)) continue;
@@ -4222,1706 +3805,25 @@ function formatRunTimestamp(value) {
4222
3805
  return value.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
4223
3806
  }
4224
3807
 
4225
- // src/commands/data-integration/convert.ts
4226
- var dataIntegrationConvert = {
4227
- service: "data-integration",
4228
- command: "convert",
4229
- usesAeHost: false,
4230
- description: "Convert one or more local data sets into validated UE JSONL and quarantine invalid rows.",
4231
- flags: [
4232
- { name: "input-file", type: "string", required: true, sensitive: true, variadic: true, desc: "Source local data file. Repeat for multiple files (requires a wildcard mapping). The source is never modified." },
4233
- { name: "mapping", type: "string", required: true, sensitive: true, desc: `${MAPPING_VERSION} JSON, file path, or @file.` },
4234
- { name: "output-dir", type: "string", sensitive: true, desc: "New or empty output directory. Default: .ae-cli/data-integration/runs/<run-id>." },
4235
- { name: "type-resolutions", type: "json", sensitive: true, desc: "JSON object resolving cross-file column type conflicts (unify, split, or skip)." },
4236
- { name: "merge-sheets", type: "boolean", default: false, desc: "Stream every worksheet in file order instead of a single selected sheet." },
4237
- { name: "salvage-from", type: "string", sensitive: true, desc: "Re-process only the rows listed in a previous run's invalid.rows.jsonl, against the current (fixed) mapping. Single-file only." }
4238
- ],
4239
- risk: "write",
4240
- dryRun: async (ctx) => {
4241
- const inputFiles = ctx.list("input-file");
4242
- const multi = inputFiles.length > 1;
4243
- const mapping = readLocalDataMapping(ctx.str("mapping"), { sourceWildcard: multi });
4244
- if (multi) {
4245
- return {
4246
- action: "convert_local_data_multi",
4247
- file_count: inputFiles.length,
4248
- source_sha256: mapping.source.sha256,
4249
- mode: mapping.mode,
4250
- property_count: mapping.properties.length,
4251
- type_resolutions: ctx.json("type-resolutions") ?? {},
4252
- source_files_unchanged: true
4253
- };
4254
- }
4255
- return {
4256
- action: "convert_local_data",
4257
- source_sha256: mapping.source.sha256,
4258
- data_set: mapping.source.data_set,
4259
- mode: mapping.mode,
4260
- property_count: mapping.properties.length,
4261
- salvage_from: ctx.str("salvage-from").trim() || void 0,
4262
- source_file_unchanged: true
4263
- };
4264
- },
4265
- execute: async (ctx) => {
4266
- const inputFiles = ctx.list("input-file");
4267
- const outputDir = ctx.str("output-dir").trim() || void 0;
4268
- if (inputFiles.length === 1) {
4269
- return convertLocalData({
4270
- inputFile: inputFiles[0],
4271
- mapping: readLocalDataMapping(ctx.str("mapping")),
4272
- outputDir,
4273
- mergeSheets: ctx.bool("merge-sheets"),
4274
- salvageFrom: ctx.str("salvage-from").trim() || void 0
4275
- });
4276
- }
4277
- return convertLocalDataMulti({
4278
- inputFiles,
4279
- mapping: readLocalDataMapping(ctx.str("mapping"), { sourceWildcard: true }),
4280
- typeResolutions: ctx.json("type-resolutions") ?? {},
4281
- outputDir
4282
- });
4283
- }
4284
- };
4285
-
4286
- // src/commands/data-integration/upload.ts
4287
- import { createReadStream as createReadStream4, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
4288
- import { basename as basename5, dirname, resolve as resolve2 } from "path";
4289
- import { createInterface as createInterface3 } from "readline";
4290
- var DEFAULT_BATCH_SIZE = 500;
4291
- var MAX_BATCH_SIZE = 1e3;
4292
- var dataIntegrationUpload = {
4293
- service: "data-integration",
4294
- command: "upload",
4295
- usesAeHost: false,
4296
- description: "Sequentially submit validated UE JSONL to an explicit receiver /sync_json endpoint.",
4297
- flags: [
4298
- { name: "ue-file", type: "string", required: true, sensitive: true, desc: "Validated valid.ue.jsonl generated by ae-cli data-integration convert." },
4299
- { name: "manifest", type: "string", required: true, sensitive: true, desc: "Matching ae-local-data-manifest/v1 file." },
4300
- { name: "endpoint", type: "string", required: true, sensitive: true, desc: "Complete receiver URL ending in /sync_json. Unrelated to --host." },
4301
- { name: "appid", type: "string", required: true, sensitive: true, desc: "Destination project APPID. Never stored in generated artifacts or logs." },
4302
- { name: "batch-size", type: "number", default: DEFAULT_BATCH_SIZE, min: 1, max: MAX_BATCH_SIZE, desc: `Sequential records per request. Maximum: ${MAX_BATCH_SIZE}.` },
4303
- { name: "resume-from", type: "number", default: 0, min: 0, desc: "Zero-based record offset selected by the user after verifying an interrupted upload." },
4304
- { name: "allow-clean-subset", type: "boolean", default: false, desc: "Explicitly allow valid rows from a blocked manifest after reviewing quarantine statistics." },
4305
- { name: "retry", type: "boolean", default: false, desc: "After the default 3 transport retries, split a still-uncertain batch into single-record retries and report per-record failures." },
4306
- { name: "compress", type: "string", default: "none", desc: "Request body compression: gzip or none." },
4307
- { name: "debug", type: "boolean", default: false, desc: "Mark every sync_json record debug=1 so AE returns per-record validation details. Testing only; not for production." }
4308
- ],
4309
- risk: "write",
4310
- validate: (ctx) => {
4311
- resolveSyncJsonEndpoint(ctx.str("endpoint"));
4312
- const batchSize = ctx.num("batch-size");
4313
- const resumeFrom = ctx.num("resume-from");
4314
- const compress = ctx.str("compress").trim().toLowerCase();
4315
- if (compress !== "gzip" && compress !== "none") {
4316
- throw new CliValidationError("Compression must be gzip or none.", {
4317
- code: "LOCAL_DATA_COMPRESS_INVALID",
4318
- location: { field: "compress" }
4319
- });
4320
- }
4321
- if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > MAX_BATCH_SIZE) {
4322
- throw new CliValidationError(`Batch size must be an integer between 1 and ${MAX_BATCH_SIZE}.`, {
4323
- code: "LOCAL_DATA_BATCH_SIZE_INVALID",
4324
- location: { field: "batch-size" }
4325
- });
4326
- }
4327
- if (!Number.isInteger(resumeFrom) || resumeFrom < 0) {
4328
- throw new CliValidationError("Resume position must be a non-negative integer.", {
4329
- code: "LOCAL_DATA_RESUME_INVALID",
4330
- location: { field: "resume-from" }
4331
- });
4332
- }
4333
- },
4334
- dryRun: async (ctx) => {
4335
- const prepared = await prepareUpload(ctx, false);
4336
- return {
4337
- action: "upload_local_ue_data",
4338
- target: maskEndpoint(prepared.endpoint),
4339
- appid: maskAppid(prepared.appid),
4340
- file_sha256: prepared.manifest.output.valid_sha256,
4341
- record_count: prepared.recordCount,
4342
- resume_from: prepared.resumeFrom,
4343
- remaining_records: Math.max(0, prepared.recordCount - prepared.resumeFrom),
4344
- batch_size: prepared.batchSize,
4345
- batch_count: prepared.batchCount,
4346
- bytes: prepared.fileBytes,
4347
- manifest_status: prepared.manifest.status,
4348
- upload_allowed: prepared.manifest.status === "ready" || ctx.bool("allow-clean-subset"),
4349
- authentication_headers: false,
4350
- transport_retries: 3,
4351
- split_uncertain_batches: ctx.bool("retry"),
4352
- compression: ctx.str("compress").trim().toLowerCase() === "gzip" ? "gzip" : "none",
4353
- debug: ctx.bool("debug"),
4354
- persistence_verified: false
4355
- };
4356
- },
4357
- execute: async (ctx) => {
4358
- const prepared = await prepareUpload(ctx, true);
4359
- const salvageUncertain = ctx.bool("retry");
4360
- const compress = ctx.str("compress").trim().toLowerCase() === "gzip" ? "gzip" : void 0;
4361
- const debug = ctx.bool("debug");
4362
- const transportOptions = { retries: 3, retryDelayMs: 2e3, compress };
4363
- let submittedRecords = 0;
4364
- let submittedBatches = 0;
4365
- let processedRecords = 0;
4366
- let requestBytes = 0;
4367
- let responseBytes = 0;
4368
- const failedRecords = [];
4369
- for await (const batch of readUeBatches(prepared.ueFile, prepared.resumeFrom, prepared.batchSize)) {
4370
- const batchStart = prepared.resumeFrom + processedRecords;
4371
- const body = assembleSyncJsonBody(batch, prepared.appid, debug);
4372
- try {
4373
- const transport = await ctx.localDataUpload(prepared.endpoint, body, transportOptions);
4374
- submittedRecords += batch.length;
4375
- submittedBatches += 1;
4376
- requestBytes += transport.request_bytes;
4377
- responseBytes += transport.response_bytes;
4378
- } catch (error) {
4379
- if (!salvageUncertain || !(error instanceof LocalDataUploadError) || error.meta?.delivery_state !== "unknown") {
4380
- throw decorateBatchError(error, submittedRecords, submittedBatches, batchStart, batch.length);
4381
- }
4382
- for (let index = 0; index < batch.length; index += 1) {
4383
- const offset = batchStart + index;
4384
- try {
4385
- const single = await ctx.localDataUpload(
4386
- prepared.endpoint,
4387
- assembleSyncJsonBody([batch[index]], prepared.appid, debug),
4388
- transportOptions
4389
- );
4390
- submittedRecords += 1;
4391
- submittedBatches += 1;
4392
- requestBytes += single.request_bytes;
4393
- responseBytes += single.response_bytes;
4394
- } catch {
4395
- failedRecords.push(offset);
4396
- }
4397
- }
4398
- }
4399
- processedRecords += batch.length;
4400
- }
4401
- if (failedRecords.length > 0) {
4402
- return {
4403
- status: "partially_delivered",
4404
- code: 0,
4405
- delivery_state: "partially_delivered",
4406
- submitted_records: submittedRecords,
4407
- submitted_batches: submittedBatches,
4408
- resume_from: prepared.resumeFrom,
4409
- failed_records: failedRecords,
4410
- failed_count: failedRecords.length,
4411
- request_bytes: requestBytes,
4412
- response_bytes: responseBytes,
4413
- persistence_verified: false,
4414
- retry_attempted: true,
4415
- next_step: "Verify received data in AE before treating the upload as persisted."
4416
- };
4417
- }
4418
- return {
4419
- status: "receiver_accepted",
4420
- code: 0,
4421
- delivery_state: "receiver_accepted",
4422
- submitted_records: submittedRecords,
4423
- submitted_batches: submittedBatches,
4424
- resume_from: prepared.resumeFrom,
4425
- request_bytes: requestBytes,
4426
- response_bytes: responseBytes,
4427
- persistence_verified: false,
4428
- retry_attempted: false,
4429
- next_step: "Verify received data in AE before treating the upload as persisted."
4430
- };
4431
- }
4432
- };
4433
- function resolveSyncJsonEndpoint(raw) {
4434
- let url;
4435
- try {
4436
- url = new URL(raw.trim());
4437
- } catch {
4438
- throw endpointError();
4439
- }
4440
- const validProtocol = url.protocol === "http:" || url.protocol === "https:";
4441
- const forbidden = Boolean(url.username || url.password || url.search || url.hash);
4442
- if (!validProtocol || forbidden || !url.pathname.endsWith("/sync_json")) throw endpointError();
4443
- return url.toString();
4444
- }
4445
- function assembleSyncJsonBody(lines, appid, debug = false) {
4446
- const appidJson = JSON.stringify(appid);
4447
- const debugValue = debug ? 1 : 0;
4448
- return `[${lines.map((line) => `{"appid":${appidJson},"debug":${debugValue},"data":${line}}`).join(",")}]`;
4449
- }
4450
- async function prepareUpload(ctx, enforceReady) {
4451
- const endpoint = resolveSyncJsonEndpoint(ctx.str("endpoint"));
4452
- const appid = ctx.str("appid").trim();
4453
- if (!appid || appid.length > 256) {
4454
- throw new CliValidationError("APPID must be a non-empty value of at most 256 characters.", {
4455
- code: "LOCAL_DATA_APPID_INVALID",
4456
- location: { field: "appid" }
4457
- });
4458
- }
4459
- const manifestPath = resolve2(ctx.str("manifest"));
4460
- const manifest = readManifest(manifestPath);
4461
- const ueFile = resolve2(ctx.str("ue-file"));
4462
- const expectedFile = resolve2(dirname(manifestPath), manifest.output.valid_file);
4463
- if (ueFile !== expectedFile) {
4464
- throw new CliValidationError("The UE file does not match the manifest output path.", {
4465
- code: "LOCAL_DATA_MANIFEST_FILE_MISMATCH",
4466
- location: { field: "ue-file" }
4467
- });
4468
- }
4469
- let fileBytes;
4470
- try {
4471
- fileBytes = statSync3(ueFile).size;
4472
- } catch {
4473
- throw new CliValidationError("The UE JSONL file could not be read.", {
4474
- code: "LOCAL_DATA_UE_FILE_NOT_FOUND",
4475
- location: { field: "ue-file" }
4476
- });
4477
- }
4478
- if (await sha256File(ueFile) !== manifest.output.valid_sha256) {
4479
- throw new CliValidationError("The UE file fingerprint does not match the manifest.", {
4480
- code: "LOCAL_DATA_UE_FILE_CHANGED",
4481
- location: { field: "ue-file" }
4482
- });
4483
- }
4484
- const recordCount = await validateUeFile(ueFile);
4485
- if (recordCount !== manifest.output.valid_records) {
4486
- throw new CliValidationError("The UE record count does not match the manifest.", {
4487
- code: "LOCAL_DATA_UE_COUNT_MISMATCH",
4488
- location: { field: "ue-file" }
4489
- });
4490
- }
4491
- if (enforceReady && manifest.status === "blocked" && !ctx.bool("allow-clean-subset")) {
4492
- throw new CliValidationError("The manifest is blocked because rows were quarantined.", {
4493
- code: "LOCAL_DATA_CLEAN_SUBSET_CONFIRMATION_REQUIRED",
4494
- hint: "Review manifest and invalid.rows.jsonl statistics, then explicitly pass --allow-clean-subset if the valid subset may be uploaded.",
4495
- location: { field: "allow-clean-subset" }
4496
- });
4497
- }
4498
- const resumeFrom = ctx.num("resume-from");
4499
- if (resumeFrom > recordCount) {
4500
- throw new CliValidationError("Resume position exceeds the UE record count.", {
4501
- code: "LOCAL_DATA_RESUME_OUT_OF_RANGE",
4502
- location: { field: "resume-from" }
4503
- });
4504
- }
4505
- const batchSize = ctx.num("batch-size");
4506
- return {
4507
- endpoint,
4508
- appid,
4509
- ueFile,
4510
- manifest,
4511
- batchSize,
4512
- resumeFrom,
4513
- recordCount,
4514
- fileBytes,
4515
- batchCount: Math.ceil(Math.max(0, recordCount - resumeFrom) / batchSize)
4516
- };
4517
- }
4518
- function readManifest(path) {
4519
- let value;
4520
- try {
4521
- value = JSON.parse(readFileSync5(path, "utf8"));
4522
- } catch {
4523
- throw new CliValidationError("The local-data manifest could not be read as JSON.", {
4524
- code: "LOCAL_DATA_MANIFEST_INVALID",
4525
- location: { field: "manifest" }
4526
- });
4527
- }
4528
- if (!isRecord3(value) || value.version !== "ae-local-data-manifest/v1" || !isRecord3(value.output) || typeof value.output.valid_file !== "string" || basename5(value.output.valid_file) !== value.output.valid_file || typeof value.output.valid_sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(value.output.valid_sha256) || !Number.isInteger(value.output.valid_records) || value.output.valid_records < 0 || value.status !== "ready" && value.status !== "blocked") {
4529
- throw new CliValidationError("The manifest is not ae-local-data-manifest/v1.", {
4530
- code: "LOCAL_DATA_MANIFEST_INVALID",
4531
- location: { field: "manifest" }
4532
- });
4533
- }
4534
- return value;
4535
- }
4536
- async function validateUeFile(path) {
4537
- let count = 0;
4538
- const lines = createInterface3({ input: createReadStream4(path), crlfDelay: Infinity });
4539
- for await (const line of lines) {
4540
- if (!line.trim()) continue;
4541
- count += 1;
4542
- let value;
4543
- try {
4544
- value = JSON.parse(line);
4545
- } catch {
4546
- throw invalidUeFile(count);
4547
- }
4548
- if (!isRecord3(value) || !isUeRecordType(value["#type"])) {
4549
- throw invalidUeFile(count);
4550
- }
4551
- }
4552
- return count;
4553
- }
4554
- var UE_RECORD_TYPES = /* @__PURE__ */ new Set([
4555
- "track",
4556
- "user_set",
4557
- "user_setOnce",
4558
- "user_add",
4559
- "user_unset",
4560
- "user_del",
4561
- "user_append",
4562
- "user_uniq_append"
4563
- ]);
4564
- function isUeRecordType(value) {
4565
- return typeof value === "string" && UE_RECORD_TYPES.has(value);
4566
- }
4567
- function decorateBatchError(error, completedRecords, completedBatches, batchStart, batchSize) {
4568
- if (!(error instanceof LocalDataUploadError)) return error;
4569
- const deliveryUnknown = error.meta?.delivery_state === "unknown";
4570
- return new LocalDataUploadError(error.message, {
4571
- code: error.code,
4572
- httpStatus: error.httpStatus,
4573
- hint: error.hint,
4574
- meta: {
4575
- ...error.meta,
4576
- completed_records: completedRecords,
4577
- completed_batches: completedBatches,
4578
- ...deliveryUnknown ? {
4579
- uncertain_batch_start: batchStart,
4580
- uncertain_batch_size: batchSize,
4581
- resume_from_after_verification: batchStart
4582
- } : {
4583
- failed_batch_start: batchStart,
4584
- failed_batch_size: batchSize
4585
- }
4586
- },
4587
- cause: error
4588
- });
4589
- }
4590
- async function* readUeBatches(path, offset, batchSize) {
4591
- let index = 0;
4592
- let batch = [];
4593
- const lines = createInterface3({ input: createReadStream4(path), crlfDelay: Infinity });
4594
- for await (const line of lines) {
4595
- if (!line.trim()) continue;
4596
- if (index++ < offset) continue;
4597
- batch.push(line);
4598
- if (batch.length >= batchSize) {
4599
- yield batch;
4600
- batch = [];
4601
- }
4602
- }
4603
- if (batch.length > 0) yield batch;
4604
- }
4605
- function invalidUeFile(record) {
4606
- return new CliValidationError("The UE JSONL file contains an invalid record.", {
4607
- code: "LOCAL_DATA_UE_FILE_INVALID",
4608
- location: { record }
4609
- });
4610
- }
4611
- function endpointError() {
4612
- return new CliValidationError("A complete http(s) receiver endpoint ending in /sync_json is required.", {
4613
- code: "LOCAL_DATA_ENDPOINT_INVALID",
4614
- location: { field: "endpoint" }
4615
- });
4616
- }
4617
- function maskEndpoint(endpoint) {
4618
- const url = new URL(endpoint);
4619
- const parts = url.hostname.split(".");
4620
- const first = parts[0];
4621
- parts[0] = first.length <= 2 ? "**" : `${first[0]}***${first.at(-1)}`;
4622
- return `${url.protocol}//${parts.join(".")}${url.port ? `:${url.port}` : ""}/sync_json`;
4623
- }
4624
- function maskAppid(appid) {
4625
- return appid.length <= 4 ? "****" : `${"*".repeat(Math.min(8, appid.length - 4))}${appid.slice(-4)}`;
4626
- }
4627
- function isRecord3(value) {
4628
- return value !== null && typeof value === "object" && !Array.isArray(value);
4629
- }
4630
-
4631
- // src/commands/data-integration/handoff.ts
4632
- import { createHash as createHash3 } from "crypto";
4633
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync6, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
4634
- import { dirname as dirname2, join as join3, resolve as resolve3 } from "path";
4635
- import { tmpdir } from "os";
4636
-
4637
- // src/commands/data-integration/archive.ts
4638
- var import_archiver = __toESM(require_archiver(), 1);
4639
- import { createWriteStream as createWriteStream2, readdirSync as readdirSync2, statSync as statSync4 } from "fs";
4640
- import { join as join2, relative, sep } from "path";
4641
- async function zipPackage(dir, zipPath) {
4642
- await new Promise((resolvePromise, rejectPromise) => {
4643
- const output = createWriteStream2(zipPath, { mode: 384 });
4644
- const zip = (0, import_archiver.default)("zip", { zlib: { level: 9 } });
4645
- output.on("close", resolvePromise);
4646
- output.on("error", rejectPromise);
4647
- zip.on("error", rejectPromise);
4648
- zip.on("warning", (error) => {
4649
- if (error.code !== "ENOENT") rejectPromise(error);
4650
- });
4651
- zip.pipe(output);
4652
- const walk = (current) => {
4653
- for (const name of readdirSync2(current)) {
4654
- if (name === ".DS_Store") continue;
4655
- const full = join2(current, name);
4656
- const stats = statSync4(full);
4657
- if (stats.isDirectory()) {
4658
- walk(full);
4659
- } else {
4660
- const rel = relative(dir, full).split(sep).join("/");
4661
- zip.file(full, { name: rel, mode: stats.mode & 511 });
4662
- }
4663
- }
4664
- };
4665
- walk(dir);
4666
- void zip.finalize();
4667
- });
4668
- }
4669
-
4670
- // src/commands/data-integration/relay.ts
4671
- var PIPELINE_VERSION = "ae-data-integration-pipeline/v1";
4672
- var SHAPE_VERSION = "ae-data-integration-shape/v1";
4673
- var DEFAULT_BATCH_SIZE2 = 500;
4674
- var ENV_FILE = ".local/target.env";
4675
- function buildPipelineDescriptor(entries, target = {}) {
4676
- const first = entries[0];
4677
- return {
4678
- version: PIPELINE_VERSION,
4679
- created_at: first?.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
4680
- source: { type: "local_file", params: { format: first?.format ?? "csv" } },
4681
- transform: { type: MAPPING_VERSION, refs: entries.map((entry) => entry.mapping_file) },
4682
- sink: {
4683
- type: "restful_sync_json",
4684
- params: {
4685
- batch_size: DEFAULT_BATCH_SIZE2,
4686
- env_file: ENV_FILE,
4687
- ...target.pushurl ? { pushurl: target.pushurl } : {},
4688
- ...target.project_id ? { project_id: target.project_id } : {}
4689
- }
4690
- }
4691
- };
4692
- }
4693
- function buildShapeBaseline(items) {
4694
- return {
4695
- version: SHAPE_VERSION,
4696
- entries: items.map(({ mapping, fingerprint }) => ({
4697
- fingerprint,
4698
- mode: mapping.mode,
4699
- data_set: mapping.source.data_set,
4700
- format: mapping.source.format,
4701
- columns: sourceColumns(mapping)
4702
- }))
4703
- };
4704
- }
4705
- function sh(...lines) {
4706
- return `${lines.join("\n")}
4707
- `;
4708
- }
4709
- function generateBinScripts() {
4710
- return [
4711
- { relPath: "bin/run.sh", content: runSh(), mode: 448 },
4712
- { relPath: "bin/upload.sh", content: uploadSh(), mode: 448 },
4713
- { relPath: "bin/bind_mapping.py", content: bindMappingPy(), mode: 448 },
4714
- { relPath: "bin/summarize.py", content: summarizePy(), mode: 448 },
4715
- { relPath: "bin/plan_check.py", content: planCheckPy(), mode: 448 },
4716
- { relPath: "bin/verify.py", content: verifyPy(), mode: 448 },
4717
- { relPath: "bin/resolve_appid.py", content: resolveAppidPy(), mode: 448 }
4718
- ];
4719
- }
4720
- function runSh() {
4721
- return sh(
4722
- "#!/usr/bin/env bash",
4723
- "# Generic pipeline executor: source -> transform -> plan. Never uploads (see upload.sh).",
4724
- "# Reads pipeline.json and dispatches each stage by its `type` to ae-cli subcommands.",
4725
- "set -euo pipefail",
4726
- 'SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"',
4727
- 'PKG_ROOT="$(dirname "$SCRIPT_DIR")"',
4728
- 'cd "$PKG_ROOT"',
4729
- "",
4730
- `SRC_TYPE="$(python3 -c 'import json; print(json.load(open("pipeline.json"))["source"]["type"])')"`,
4731
- 'case "$SRC_TYPE" in',
4732
- " local_file) ;;",
4733
- " *)",
4734
- ' echo "unsupported source type: $SRC_TYPE" >&2',
4735
- ' echo "re-run the full ae-data-integration pipeline (or upgrade ae-cli) for this source." >&2',
4736
- " exit 64",
4737
- " ;;",
4738
- "esac",
4739
- "",
4740
- 'INPUT="${1:-}"',
4741
- 'if [ -z "$INPUT" ]; then',
4742
- " shopt -s nullglob; FILES=(inbox/*); shopt -u nullglob",
4743
- ' if [ "${#FILES[@]}" -ne 1 ]; then',
4744
- ' echo "usage: bin/run.sh <input-file>" >&2',
4745
- ' echo " (or put exactly one file in inbox/)" >&2',
4746
- " exit 2",
4747
- " fi",
4748
- ' INPUT="${FILES[0]}"',
4749
- "fi",
4750
- "",
4751
- 'RUN_DIR="runs/$(date +%Y%m%d-%H%M%S)"',
4752
- 'mkdir -p "$RUN_DIR"',
4753
- 'echo "run: $RUN_DIR"',
4754
- "",
4755
- 'python3 bin/bind_mapping.py "$INPUT" "$RUN_DIR"',
4756
- "",
4757
- "while IFS= read -r ref; do",
4758
- ' ref_dir="$(dirname "$ref")"',
4759
- ' echo "convert: $ref_dir"',
4760
- " ae-cli data-integration convert \\",
4761
- ' --input-file "$INPUT" \\',
4762
- ' --mapping "$RUN_DIR/bound/$ref_dir/mapping.json" \\',
4763
- ' --output-dir "$RUN_DIR/$ref_dir" || exit $?',
4764
- `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`,
4765
- "",
4766
- 'python3 bin/summarize.py "$RUN_DIR"',
4767
- 'python3 bin/plan_check.py "$RUN_DIR"',
4768
- "",
4769
- "# Salvage hint: quarantined rows are never silently dropped. Re-process only",
4770
- "# them against the fixed mapping instead of re-uploading the whole file.",
4771
- "while IFS= read -r ref; do",
4772
- ' ref_dir="$(dirname "$ref")"',
4773
- ' inv="$RUN_DIR/$ref_dir/invalid.rows.jsonl"',
4774
- ' if [ -s "$inv" ]; then',
4775
- ' echo "note: $inv has quarantined rows \u2014 salvage them with:"',
4776
- ' echo " ae-cli data-integration convert --input-file "$INPUT" --mapping "$RUN_DIR/bound/$ref_dir/mapping.json" --salvage-from "$inv" --output-dir "$RUN_DIR-salvage""',
4777
- " fi",
4778
- `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`,
4779
- "",
4780
- 'echo "done. review the summary and plan check, then run: bin/upload.sh $RUN_DIR"'
4781
- );
4782
- }
4783
- function uploadSh() {
4784
- return sh(
4785
- "#!/usr/bin/env bash",
4786
- "# Sink executor. Dry-run by default; --confirm actually uploads.",
4787
- "# Resolves the recorded target from pipeline.json (pushurl + project_id), derives",
4788
- "# the APPID via `ae-cli project info get` (bin/resolve_appid.py), and falls back to",
4789
- "# .local/target.env for explicit APPID / endpoint / project-id overrides.",
4790
- "set -euo pipefail",
4791
- 'SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"',
4792
- 'PKG_ROOT="$(dirname "$SCRIPT_DIR")"',
4793
- 'cd "$PKG_ROOT"',
4794
- "",
4795
- `SINK_TYPE="$(python3 -c 'import json; print(json.load(open("pipeline.json"))["sink"]["type"])')"`,
4796
- 'case "$SINK_TYPE" in',
4797
- " restful_sync_json) ;;",
4798
- " *)",
4799
- ' echo "unsupported sink type: $SINK_TYPE" >&2',
4800
- ' echo "re-run the full ae-data-integration pipeline (or upgrade ae-cli) for this sink." >&2',
4801
- " exit 64",
4802
- " ;;",
4803
- "esac",
4804
- "",
4805
- `SINK_PARAMS="$(python3 -c 'import json; print(json.dumps(json.load(open("pipeline.json"))["sink"]["params"]))')"`,
4806
- `BATCH_SIZE="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("batch_size", 500))' "$SINK_PARAMS")"`,
4807
- `ENV_FILE="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("env_file", ".local/target.env"))' "$SINK_PARAMS")"`,
4808
- `PUSHURL="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("pushurl") or "")' "$SINK_PARAMS")"`,
4809
- `PROJECT_ID="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("project_id") or "")' "$SINK_PARAMS")"`,
4810
- "",
4811
- "CONFIRM=0",
4812
- 'RUN_DIR=""',
4813
- 'for arg in "$@"; do',
4814
- ' case "$arg" in',
4815
- " --confirm) CONFIRM=1 ;;",
4816
- ' -*) echo "unknown flag: $arg" >&2; exit 2 ;;',
4817
- ' *) RUN_DIR="$arg" ;;',
4818
- " esac",
4819
- "done",
4820
- "",
4821
- 'if [ -z "$RUN_DIR" ]; then',
4822
- ' echo "usage: bin/upload.sh [--confirm] <runs/<run-id>>" >&2',
4823
- " exit 2",
4824
- "fi",
4825
- "",
4826
- "# .local/target.env is optional: the package may record the target itself.",
4827
- "# Env values still win as explicit overrides (the documented fallback).",
4828
- 'if [ -f "$ENV_FILE" ]; then set -a; . "$ENV_FILE"; set +a; fi',
4829
- '[ -z "$PROJECT_ID" ] && PROJECT_ID="${AE_PROJECT_ID:-}"',
4830
- "",
4831
- "# Endpoint: the recorded pushurl (a receiver base URL; append /sync_json), else AE_ENDPOINT.",
4832
- 'if [ -n "$PUSHURL" ]; then',
4833
- ' case "$PUSHURL" in',
4834
- ' */sync_json) ENDPOINT="$PUSHURL" ;;',
4835
- ' *) ENDPOINT="${PUSHURL%/}/sync_json" ;;',
4836
- " esac",
4837
- "else",
4838
- ' : "${AE_ENDPOINT:?set AE_ENDPOINT in .local/target.env (or record pushurl at handoff)}"',
4839
- ' ENDPOINT="$AE_ENDPOINT"',
4840
- "fi",
4841
- "",
4842
- "# APPID: explicit env wins, else derive from the recorded project via project info get.",
4843
- 'APPID="${AE_APPID:-}"',
4844
- 'if [ -z "$APPID" ] && [ -n "$PROJECT_ID" ]; then',
4845
- ' APPID="$(python3 bin/resolve_appid.py "$PROJECT_ID")"',
4846
- "fi",
4847
- ': "${APPID:?set AE_APPID in .local/target.env (or record project_id at handoff)}"',
4848
- "",
4849
- "# Mask the APPID in anything this script prints \u2014 it must never land in logs.",
4850
- "mask() {",
4851
- ' local a="$1"',
4852
- ' if [ "${#a}" -le 4 ]; then printf "%s" "****"; return; fi',
4853
- ' printf "%s%s" "$(printf "%*s" "$(( ${#a} - 4 ))" "" | tr " " "*")" "${a: -4}"',
4854
- "}",
4855
- "display_args() {",
4856
- ' local args=("$@") out=() i',
4857
- " for ((i=0; i<${#args[@]}; i++)); do",
4858
- ' if [ "${args[$i]}" = "--appid" ] && [ -n "${args[$((i+1))]:-}" ]; then',
4859
- ' out+=("--appid" "$(mask "${args[$((i+1))]}")")',
4860
- " i=$((i+1))",
4861
- " else",
4862
- ' out+=("${args[$i]}")',
4863
- " fi",
4864
- " done",
4865
- ' printf "%s\\n" "${out[*]}"',
4866
- "}",
4867
- "",
4868
- 'echo "target: project_id=${PROJECT_ID:-<unset>}"',
4869
- 'echo " endpoint=$ENDPOINT"',
4870
- 'echo " appid=$(mask "$APPID")"',
4871
- 'if [ "$CONFIRM" -eq 0 ]; then',
4872
- ' echo "dry-run \u2014 re-run with --confirm to upload to this address and project."',
4873
- "else",
4874
- ' echo "confirmed: uploading to the address and project shown above."',
4875
- "fi",
4876
- "",
4877
- 'FLAGS=(--endpoint "$ENDPOINT" --appid "$APPID" --batch-size "$BATCH_SIZE")',
4878
- 'if [ "$CONFIRM" -eq 0 ]; then FLAGS+=(--dry-run); fi',
4879
- "",
4880
- "while IFS= read -r ref; do",
4881
- ' ref_dir="$(dirname "$ref")"',
4882
- ' ue="$RUN_DIR/$ref_dir/valid.ue.jsonl"',
4883
- ' manifest="$RUN_DIR/$ref_dir/manifest.json"',
4884
- ' if [ ! -f "$ue" ]; then',
4885
- ' echo "missing $ue (run bin/run.sh first)" >&2',
4886
- " exit 2",
4887
- " fi",
4888
- ` status="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["status"])' "$manifest")"`,
4889
- ' args=("${FLAGS[@]}" --ue-file "$ue" --manifest "$manifest")',
4890
- ' if [ "$status" = "blocked" ]; then',
4891
- ' echo "manifest $manifest is blocked (rows were quarantined)."',
4892
- ' echo "Uploading passes only the valid subset (--allow-clean-subset); quarantined rows stay in invalid.rows.jsonl."',
4893
- ' if [ "$CONFIRM" -eq 1 ]; then args+=(--allow-clean-subset); else echo " (dry-run) re-run with --confirm to accept the clean subset."; fi',
4894
- " fi",
4895
- ' echo "> ae-cli data-integration upload $(display_args "${args[@]}")"',
4896
- ' ae-cli data-integration upload "${args[@]}" || exit $?',
4897
- `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`
4898
- );
4899
- }
4900
- function bindMappingPy() {
4901
- return `#!/usr/bin/env python3
4902
- """Source stage: rebind the frozen mappings to a new same-shape file.
4903
-
4904
- Runs \`ae-cli data-integration inspect\` once, then for every mapping the
4905
- pipeline references (pipeline.json's transform.refs) re-binds the frozen
4906
- mapping's \`source.sha256\` and \`source.data_set\` to the new file (identity
4907
- fields only \u2014 business logic is untouched), after checking the column set
4908
- against shape.json. Historical index entries the pipeline does not run are
4909
- left alone \u2014 the index accumulates across handoffs in the same directory.
4910
-
4911
- Usage: bin/bind_mapping.py <input-file> <run-dir>
4912
- """
4913
- import json
4914
- import os
4915
- import subprocess
4916
- import sys
4917
-
4918
-
4919
- def fail(message):
4920
- print(f"bind_mapping: {message}", file=sys.stderr)
4921
- sys.exit(1)
4922
-
4923
-
4924
- def pkg_root():
4925
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
4926
-
4927
-
4928
- def load_json(path):
4929
- with open(path, "r", encoding="utf-8") as f:
4930
- return json.load(f)
4931
-
4932
-
4933
- def write_json(path, value):
4934
- os.makedirs(os.path.dirname(path), exist_ok=True)
4935
- with open(path, "w", encoding="utf-8") as f:
4936
- json.dump(value, f, ensure_ascii=False, indent=2)
4937
- f.write("\\n")
4938
-
4939
-
4940
- def dataset_key(dataset):
4941
- return dataset.get("id") or dataset.get("label") or ""
4942
-
4943
-
4944
- def main():
4945
- if len(sys.argv) != 3:
4946
- fail("usage: bind_mapping.py <input-file> <run-dir>")
4947
- input_file, run_dir = sys.argv[1], sys.argv[2]
4948
- root = pkg_root()
4949
-
4950
- pipeline = load_json(os.path.join(root, "pipeline.json"))
4951
- if pipeline["source"]["type"] != "local_file":
4952
- fail(f"unsupported source type: {pipeline['source']['type']}")
4953
-
4954
- index = load_json(os.path.join(root, "index.json"))
4955
- shape = load_json(os.path.join(root, "shape.json"))
4956
- shape_by_fp = {entry["fingerprint"]: entry for entry in shape["entries"]}
4957
- index_by_ref = {entry["mapping_file"]: entry for entry in index["entries"]}
4958
-
4959
- inspect = run_inspect(input_file)
4960
- datasets = extract_datasets(inspect)
4961
- headers_by_dataset = extract_headers(inspect, datasets)
4962
- sha = (inspect.get("source") or {}).get("sha256")
4963
-
4964
- # Rebind only the mappings this pipeline runs (transform.refs). The index
4965
- # accumulates entries across handoffs in the same directory; earlier entries
4966
- # may have no shape baseline here and are never converted by run.sh, so
4967
- # walking the whole index would fail on them.
4968
- for ref in pipeline["transform"]["refs"]:
4969
- entry = index_by_ref.get(ref)
4970
- if entry is None:
4971
- fail(f"index entry missing for {ref}; re-run the full pipeline")
4972
- fingerprint = entry["fingerprint"]
4973
- baseline = shape_by_fp.get(fingerprint)
4974
- if baseline is None:
4975
- fail(f"shape baseline missing for {fingerprint}; re-run the full pipeline")
4976
- frozen = load_json(os.path.join(root, ref))
4977
- data_set_id = match_dataset(frozen, baseline, datasets, headers_by_dataset)
4978
- validate_headers(data_set_id, baseline, headers_by_dataset)
4979
- frozen["source"]["sha256"] = sha
4980
- frozen["source"]["data_set"] = data_set_id
4981
- out = os.path.join(root, run_dir, "bound", os.path.dirname(ref), "mapping.json")
4982
- write_json(out, frozen)
4983
- print(f"rebound {os.path.dirname(ref)} -> data_set {data_set_id!r}")
4984
- print("shape check passed")
4985
-
4986
-
4987
- def run_inspect(input_file):
4988
- proc = subprocess.run(
4989
- ["ae-cli", "data-integration", "inspect", "--input-file", input_file],
4990
- capture_output=True, text=True,
4991
- )
4992
- if proc.returncode != 0:
4993
- fail(f"inspect failed: {proc.stderr.strip()}")
4994
- try:
4995
- parsed = json.loads(proc.stdout)
4996
- except json.JSONDecodeError:
4997
- fail("inspect returned non-JSON output")
4998
- # ae-cli wraps every command result in { ok, data, error }; unwrap it.
4999
- data = parsed.get("data") if isinstance(parsed, dict) else None
5000
- if not isinstance(data, dict):
5001
- fail("inspect returned no data payload")
5002
- return data
5003
-
5004
-
5005
- def extract_datasets(inspect):
5006
- if inspect.get("selection_required"):
5007
- return inspect.get("data_sets") or []
5008
- data_set = inspect.get("data_set")
5009
- return [data_set] if data_set else []
5010
-
5011
-
5012
- def extract_headers(inspect, datasets):
5013
- result = {}
5014
- details = inspect.get("header_details")
5015
- if details:
5016
- for dataset in datasets:
5017
- names = (dataset.get("label"), dataset.get("id"), dataset.get("selector"))
5018
- for sheet in details:
5019
- if sheet.get("name") in names:
5020
- result[dataset_key(dataset)] = sheet.get("headers") or []
5021
- break
5022
- return result
5023
- columns = inspect.get("columns")
5024
- if columns and datasets:
5025
- result[dataset_key(datasets[0])] = [column["name"] for column in columns]
5026
- return result
5027
-
5028
-
5029
- def match_dataset(frozen, baseline, datasets, headers_by_dataset):
5030
- if not datasets:
5031
- fail("inspect reported no data sets")
5032
- wanted = frozen["source"]["data_set"]
5033
- for dataset in datasets:
5034
- if dataset.get("id") == wanted:
5035
- return dataset.get("id")
5036
- for dataset in datasets:
5037
- if dataset.get("label") == wanted:
5038
- return dataset.get("id")
5039
- baseline_cols = set(baseline.get("columns") or [])
5040
- if baseline_cols:
5041
- for dataset in datasets:
5042
- headers = headers_by_dataset.get(dataset_key(dataset))
5043
- if headers and set(headers) == baseline_cols:
5044
- return dataset.get("id")
5045
- if len(datasets) == 1:
5046
- return datasets[0].get("id")
5047
- fail(f"cannot rebind data_set {wanted!r}: no exact or header match; re-run the full pipeline")
5048
-
5049
-
5050
- def validate_headers(data_set_id, baseline, headers_by_dataset):
5051
- baseline_cols = set(baseline.get("columns") or [])
5052
- if not baseline_cols:
5053
- return
5054
- headers = headers_by_dataset.get(data_set_id)
5055
- if headers is None:
5056
- return
5057
- if set(headers) != baseline_cols:
5058
- missing = sorted(baseline_cols - set(headers))
5059
- extra = sorted(set(headers) - baseline_cols)
5060
- fail(
5061
- f"shape mismatch for {data_set_id!r}: missing={missing} extra={extra} \u2014 "
5062
- "re-run the full pipeline; do not edit the frozen mapping"
5063
- )
5064
-
5065
-
5066
- if __name__ == "__main__":
5067
- main()
5068
- `;
5069
- }
5070
- function summarizePy() {
5071
- return `#!/usr/bin/env python3
5072
- """Transform stage summary: print valid/quarantined counts per data set."""
5073
- import json
5074
- import os
5075
- import sys
5076
-
5077
-
5078
- def pkg_root():
5079
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5080
-
5081
-
5082
- def main():
5083
- if len(sys.argv) != 2:
5084
- print("usage: summarize.py <run-dir>", file=sys.stderr)
5085
- sys.exit(2)
5086
- run_dir = sys.argv[1]
5087
- root = pkg_root()
5088
- with open(os.path.join(root, "pipeline.json"), "r", encoding="utf-8") as f:
5089
- pipeline = json.load(f)
5090
- total_valid = 0
5091
- total_invalid = 0
5092
- for ref in pipeline["transform"]["refs"]:
5093
- ref_dir = os.path.dirname(ref)
5094
- manifest_path = os.path.join(root, run_dir, ref_dir, "manifest.json")
5095
- if not os.path.exists(manifest_path):
5096
- continue
5097
- with open(manifest_path, "r", encoding="utf-8") as f:
5098
- manifest = json.load(f)
5099
- output = manifest["output"]
5100
- total_valid += output["valid_records"]
5101
- total_invalid += output["invalid_records"]
5102
- print(f"{ref_dir}: {output['valid_records']} valid / {output['invalid_records']} quarantined")
5103
- for reason in manifest.get("blocked_reasons") or []:
5104
- print(f" - {reason}")
5105
- print(f"total: {total_valid} valid / {total_invalid} quarantined")
5106
-
5107
-
5108
- if __name__ == "__main__":
5109
- main()
5110
- `;
5111
- }
5112
- function planCheckPy() {
5113
- return `#!/usr/bin/env python3
5114
- """Plan gate: every event and property produced must already exist in the frozen tracking plan."""
5115
- import json
5116
- import os
5117
- import sys
5118
-
5119
-
5120
- def pkg_root():
5121
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5122
-
5123
-
5124
- def load_json(path):
5125
- with open(path, "r", encoding="utf-8") as f:
5126
- return json.load(f)
5127
-
5128
-
5129
- def main():
5130
- if len(sys.argv) != 2:
5131
- print("usage: plan_check.py <run-dir>", file=sys.stderr)
5132
- sys.exit(2)
5133
- run_dir = sys.argv[1]
5134
- root = pkg_root()
5135
- pipeline = load_json(os.path.join(root, "pipeline.json"))
5136
- new_events = []
5137
- new_properties = []
5138
- missing_plans = []
5139
- for ref in pipeline["transform"]["refs"]:
5140
- ref_dir = os.path.dirname(ref)
5141
- plan_path = os.path.join(root, ref_dir, "plan.json")
5142
- ue_path = os.path.join(root, run_dir, ref_dir, "valid.ue.jsonl")
5143
- if not os.path.exists(plan_path):
5144
- missing_plans.append(ref_dir)
5145
- continue
5146
- plan = load_json(plan_path)
5147
- plan_events = {event["event_name"] for event in plan.get("events", [])}
5148
- plan_properties = {prop["name"] for prop in plan.get("event_properties", [])}
5149
- plan_properties |= {prop["name"] for prop in plan.get("common_event_properties", [])}
5150
- plan_properties |= {prop["name"] for prop in plan.get("user_properties", [])}
5151
- produced_events = set()
5152
- produced_properties = set()
5153
- if os.path.exists(ue_path):
5154
- with open(ue_path, "r", encoding="utf-8") as f:
5155
- for line in f:
5156
- line = line.strip()
5157
- if not line:
5158
- continue
5159
- record = json.loads(line)
5160
- if record.get("#event_name"):
5161
- produced_events.add(record["#event_name"])
5162
- props = record.get("properties")
5163
- if isinstance(props, dict):
5164
- for key in props:
5165
- if key.startswith("#"):
5166
- continue
5167
- produced_properties.add(key)
5168
- new_events.extend(sorted(produced_events - plan_events))
5169
- new_properties.extend(sorted(produced_properties - plan_properties))
5170
- if missing_plans:
5171
- print("no plan.json in package for: " + ", ".join(missing_plans), file=sys.stderr)
5172
- print("run the Tracking plan step first \u2014 the plan gate cannot be skipped", file=sys.stderr)
5173
- sys.exit(3)
5174
- if new_events:
5175
- print("new events not in the plan: " + ", ".join(new_events), file=sys.stderr)
5176
- sys.exit(3)
5177
- if new_properties:
5178
- print("new properties not in the plan: " + ", ".join(new_properties), file=sys.stderr)
5179
- sys.exit(3)
5180
- print("plan coverage ok")
5181
-
5182
-
5183
- if __name__ == "__main__":
5184
- main()
5185
- `;
5186
- }
5187
- function verifyPy() {
5188
- return `#!/usr/bin/env python3
5189
- """Persistence consistency check: submit-window counts vs the platform summary.
5190
-
5191
- A soft check, not a hard gate. It computes what this run submitted from the local
5192
- UE output (knowable), snapshots \`ae-cli tracking ingest summary\` over the submit
5193
- window before and after upload, and prints both next to the expected counts. It
5194
- does NOT parse the summary payload into per-event numbers: the capability's data
5195
- shape is server-defined and not a stable CLI contract, and a shared project cannot
5196
- attribute the window delta to this import alone. For a hard per-event SQL judge,
5197
- overlay a project custom layer (see custom-layer.md in the ae-data-integration skill).
5198
-
5199
- verify.py <run-dir> --baseline snapshot the summary before upload
5200
- verify.py <run-dir> --check snapshot again and diff against the baseline
5201
- """
5202
- import json
5203
- import os
5204
- import subprocess
5205
- import sys
5206
-
5207
-
5208
- def pkg_root():
5209
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
5210
-
5211
-
5212
- def load_json(path):
5213
- with open(path, "r", encoding="utf-8") as f:
5214
- return json.load(f)
5215
-
5216
-
5217
- def visit_window(record, lo, hi):
5218
- raw = record.get("#time")
5219
- if not isinstance(raw, str) or len(raw) < 19:
5220
- return lo, hi
5221
- stamp = raw[:19] # YYYY-MM-DD HH:mm:ss
5222
- if lo is None or stamp < lo:
5223
- lo = stamp
5224
- if hi is None or stamp > hi:
5225
- hi = stamp
5226
- return lo, hi
5227
-
5228
-
5229
- def main():
5230
- if len(sys.argv) < 2:
5231
- print("usage: verify.py <run-dir> [--baseline|--check]", file=sys.stderr)
5232
- sys.exit(2)
5233
- run_dir = sys.argv[1]
5234
- mode = sys.argv[2] if len(sys.argv) > 2 else "--check"
5235
- if mode not in ("--baseline", "--check"):
5236
- print("usage: verify.py <run-dir> [--baseline|--check]", file=sys.stderr)
5237
- sys.exit(2)
5238
- root = pkg_root()
5239
- pipeline = load_json(os.path.join(root, "pipeline.json"))
5240
- project_id = pipeline["sink"]["params"].get("project_id") or os.environ.get("AE_PROJECT_ID") or "1"
5241
-
5242
- expected_events = {}
5243
- expected_users = 0
5244
- lo = hi = None
5245
- for ref in pipeline["transform"]["refs"]:
5246
- ue = os.path.join(root, run_dir, os.path.dirname(ref), "valid.ue.jsonl")
5247
- if not os.path.exists(ue):
5248
- continue
5249
- with open(ue, "r", encoding="utf-8") as f:
5250
- for line in f:
5251
- line = line.strip()
5252
- if not line:
5253
- continue
5254
- record = json.loads(line)
5255
- if record.get("#type") == "track" and record.get("#event_name"):
5256
- expected_events[record["#event_name"]] = expected_events.get(record["#event_name"], 0) + 1
5257
- else:
5258
- expected_users += 1
5259
- lo, hi = visit_window(record, lo, hi)
5260
-
5261
- if lo is None:
5262
- print("verify: no UE records found in " + run_dir, file=sys.stderr)
5263
- sys.exit(2)
5264
-
5265
- def run_summary():
5266
- proc = subprocess.run(
5267
- ["ae-cli", "tracking", "ingest", "summary",
5268
- "-p", str(project_id), "--start-time", lo, "--end-time", hi],
5269
- capture_output=True, text=True,
5270
- )
5271
- if proc.returncode != 0:
5272
- return {"error": (proc.stderr or proc.stdout).strip()[:500]}
5273
- try:
5274
- return json.loads(proc.stdout)
5275
- except json.JSONDecodeError:
5276
- return {"raw": proc.stdout.strip()[:500]}
5277
-
5278
- print("window " + lo + " .. " + hi + " project_id=" + str(project_id))
5279
- print("expected (this run):")
5280
- for event, count in sorted(expected_events.items()):
5281
- print(" {:<20}{:>10,}".format(event, count))
5282
- print(" {:<20}{:>10,}".format("<user rows>", expected_users))
5283
- print()
5284
-
5285
- baseline_path = os.path.join(root, run_dir, "baseline.json")
5286
- if mode == "--baseline":
5287
- payload = run_summary()
5288
- with open(baseline_path, "w", encoding="utf-8") as f:
5289
- json.dump(payload, f, ensure_ascii=False, indent=2)
5290
- print("baseline recorded: " + baseline_path)
5291
- print("platform summary (before):")
5292
- print(json.dumps(payload, ensure_ascii=False, indent=2))
5293
- sys.exit(0)
5294
-
5295
- if not os.path.exists(baseline_path):
5296
- print("no baseline.json \u2014 run \`verify.py <run-dir> --baseline\` before upload.", file=sys.stderr)
5297
- print("falling back to a single after-upload summary:", file=sys.stderr)
5298
- print(json.dumps(run_summary(), ensure_ascii=False, indent=2))
5299
- sys.exit(1)
5300
-
5301
- with open(baseline_path, "r", encoding="utf-8") as f:
5302
- baseline = json.load(f)
5303
- after = run_summary()
5304
- print("platform summary before vs after:")
5305
- print(json.dumps(baseline, ensure_ascii=False, indent=2))
5306
- print("---")
5307
- print(json.dumps(after, ensure_ascii=False, indent=2))
5308
- print()
5309
- print("summary changed: " + ("yes" if baseline != after else "no"))
5310
- print()
5311
- print("Boundary: the summary payload is server-defined and may under-report even")
5312
- print("landed data; this check surfaces it for comparison, it does not auto-verify")
5313
- print("per-event counts, and a shared project's window delta is not attributed to")
5314
- print("this import. Cross-check with:")
5315
- print(" ae-cli tracking live-data list -p " + str(project_id))
5316
- print("For a hard SQL judge, add a project custom layer (custom-layer.md).")
5317
- sys.exit(0)
5318
-
5319
-
5320
- if __name__ == "__main__":
5321
- main()
5322
- `;
5323
- }
5324
- function resolveAppidPy() {
5325
- return `#!/usr/bin/env python3
5326
- """Derive the destination APPID from \`ae-cli project info get --project-id <id>\`.
5327
-
5328
- \`project info get\` returns \`data.appid\` at the top level (verified against the
5329
- AE demo host), so this helper reads that exact field and prints it to stdout. It
5330
- prints nothing to stdout and reports the payload when the field is absent or not
5331
- a non-empty string \u2014 the caller then falls back to AE_APPID.
5332
-
5333
- Usage: bin/resolve_appid.py <project-id>
5334
- """
5335
- import json
5336
- import subprocess
5337
- import sys
5338
-
5339
-
5340
- def main():
5341
- if len(sys.argv) != 2:
5342
- print("usage: resolve_appid.py <project-id>", file=sys.stderr)
5343
- sys.exit(2)
5344
- project_id = sys.argv[1]
5345
- proc = subprocess.run(
5346
- ["ae-cli", "project", "info", "get", "--project-id", project_id],
5347
- capture_output=True, text=True,
5348
- )
5349
- if proc.returncode != 0:
5350
- print("resolve_appid: project info get failed: " + (proc.stderr or proc.stdout).strip()[:300], file=sys.stderr)
5351
- sys.exit(0)
5352
- try:
5353
- parsed = json.loads(proc.stdout)
5354
- except json.JSONDecodeError:
5355
- print("resolve_appid: project info get returned non-JSON output", file=sys.stderr)
5356
- sys.exit(0)
5357
- data = parsed.get("data") if isinstance(parsed, dict) else None
5358
- appid = data.get("appid") if isinstance(data, dict) else None
5359
- if not isinstance(appid, str) or not appid:
5360
- print("resolve_appid: project info get returned no appid; set AE_APPID", file=sys.stderr)
5361
- print(json.dumps(data, ensure_ascii=False, indent=2) if data is not None else "{}", file=sys.stderr)
5362
- sys.exit(0)
5363
- masked = appid if len(appid) <= 4 else ("*" * (len(appid) - 4)) + appid[-4:]
5364
- print("resolve_appid: resolved APPID data.appid = " + masked, file=sys.stderr)
5365
- print(appid)
5366
-
5367
-
5368
- if __name__ == "__main__":
5369
- main()
5370
- `;
5371
- }
5372
- function generateReadme() {
5373
- return `# AE Data Integration \u2014 handoff package
5374
-
5375
- A frozen, reusable pipeline for importing a **same-shape** local file into AE,
5376
- generated by \`ae-cli data-integration handoff\`. Source and Transform are frozen
5377
- (the confirmed business logic); only the Tracking-plan and Sink gates still
5378
- require human confirmation.
5379
-
5380
- ## Quick start
5381
-
5382
- \`\`\`bash
5383
- cp <today's file> inbox/
5384
- bin/run.sh # shape check -> convert -> plan check (no upload)
5385
- bin/upload.sh runs/<latest> # dry-run
5386
- bin/upload.sh runs/<latest> --confirm
5387
- \`\`\`
5388
-
5389
- Read [RUNBOOK.md](RUNBOOK.md) for the full flow, the four confirmation gates,
5390
- and how to verify persistence.
5391
-
5392
- ## Handing off to an agent
5393
-
5394
- Import \`inbox/<today's file>\` through the ae-data-integration skill using this
5395
- package. Tell it to follow RUNBOOK.md and stop for confirmation before uploading.
5396
-
5397
- ## Package layout
5398
-
5399
- | Path | Purpose |
5400
- | --- | --- |
5401
- | \`pipeline.json\` | Declarative source -> transform -> sink descriptor |
5402
- | \`index.json\` | Structure-fingerprint index (reuse matching) |
5403
- | \`shape.json\` | Column baseline used by the shape gate |
5404
- | \`<fingerprint16>/\` | Frozen mapping + tracking plan + transform wrapper |
5405
- | \`bin/run.sh\` | Source + Transform + Plan executor (never uploads) |
5406
- | \`bin/upload.sh\` | Sink executor (dry-run by default; resolves the recorded target) |
5407
- | \`bin/verify.py\` | Soft persistence check (submit window vs ingest summary) |
5408
- | \`bin/resolve_appid.py\` | APPID derivation helper (project info get) |
5409
- | \`.local/target.env\` | Upload target overrides (APPID / endpoint); only the template ships |
5410
- | \`inbox/\` \`runs/\` | Daily input / per-run outputs |
5411
-
5412
- ## Safety
5413
-
5414
- The package records at most a destination \`pushurl\` and \`project_id\` (no APPID,
5415
- tokens, or raw data values). \`bin/upload.sh\` always requires \`--confirm\` before
5416
- sending, so the operator re-confirms the address and project on every reuse. Copy
5417
- \`.local/target.env.example\` to \`.local/target.env\` for explicit overrides and
5418
- never commit it.
5419
- `;
5420
- }
5421
- function generateRunbook() {
5422
- return `# RUNBOOK \u2014 same-shape file import
5423
-
5424
- Run this when a file of the **same shape** arrives again (same sheets and
5425
- headers as \`shape.json\`). If the headers changed, stop: re-run the full
5426
- ae-data-integration pipeline instead of editing the frozen mapping.
5427
-
5428
- ## Gates
5429
-
5430
- 1. **Shape gate** \u2014 \`bin/run.sh\` rebinds the frozen mappings to the new file
5431
- and compares the column set against \`shape.json\`. A mismatch fails fast on
5432
- purpose: a different shape means the frozen business logic was never reviewed
5433
- for it.
5434
- 2. **Transform** \u2014 each frozen mapping runs through
5435
- \`ae-cli data-integration convert\`. Quarantined rows land in
5436
- \`invalid.rows.jsonl\`; they are never silently dropped.
5437
- 3. **Tracking-plan gate** \u2014 \`bin/run.sh\` verifies every produced event and
5438
- property already exists in the frozen \`plan.json\`. New events or properties
5439
- make it exit with code 3: merge them into the project tracking plan first,
5440
- then return here to upload.
5441
- 4. **Sink gate** \u2014 \`bin/upload.sh\` is dry-run by default. Read
5442
- \`record_count\`, \`batch_count\`, and \`manifest_status\` before adding
5443
- \`--confirm\`. A \`blocked\` manifest means rows were quarantined;
5444
- \`--confirm\` then uploads only the valid subset (\`--allow-clean-subset\`).
5445
-
5446
- ## Destination
5447
-
5448
- The package records the destination it was handed off for when \`handoff\` was run
5449
- with \`--pushurl\` / \`--project-id\` (see \`pipeline.json\` \u2192 \`sink.params\`). Reuse
5450
- defaults to that target, but \`bin/upload.sh\` never sends without \`--confirm\`, so
5451
- the operator re-confirms the address and project every time.
5452
-
5453
- Resolution order at upload time:
5454
-
5455
- - endpoint: recorded \`pushurl\` (+ \`/sync_json\`), else \`AE_ENDPOINT\`.
5456
- - APPID: \`AE_APPID\`, else derived via \`ae-cli project info get --project-id <id>\`
5457
- (see \`bin/resolve_appid.py\`; it reads the \`data.appid\` field \u2014 set \`AE_APPID\`
5458
- when that field is absent).
5459
- - project id: recorded \`project_id\`, else \`AE_PROJECT_ID\`.
5460
-
5461
- \`.local/target.env\` remains the explicit override for all three:
5462
- \`AE_ENDPOINT\` (full receiver URL ending in \`/sync_json\`), \`AE_APPID\`, \`AE_PROJECT_ID\`.
5463
-
5464
- ## Verify persistence
5465
-
5466
- \`receiver_accepted\` is not persistence. About a minute after upload, confirm
5467
- the data landed with ae-cli. The package ships a soft check that automates the
5468
- before/after comparison:
5469
-
5470
- \`\`\`bash
5471
- bin/verify.py runs/<run-id> --baseline # before upload
5472
- bin/upload.sh runs/<run-id> --confirm
5473
- bin/verify.py runs/<run-id> --check # after upload
5474
- \`\`\`
5475
-
5476
- \`bin/verify.py\` prints the submit window and expected counts, then shows the
5477
- \`tracking ingest summary\` payload before and after for comparison. It does not
5478
- auto-verify per-event counts \u2014 the summary shape is server-defined, and a shared
5479
- project's window delta is not attributed to this import. Cross-check with:
5480
-
5481
- \`\`\`bash
5482
- ae-cli tracking live-data list -p <AE_PROJECT_ID>
5483
- ae-cli tracking ingest-error list -p <AE_PROJECT_ID> --data-name <name>
5484
- \`\`\`
5485
-
5486
- For a hard per-event SQL judge, overlay a project custom layer instead of editing
5487
- this package (see \`custom-layer.md\` in the ae-data-integration skill).
5488
-
5489
- ## Interrupted uploads
5490
-
5491
- If a batch times out or loses the network, that batch's state is unknown. Stop:
5492
- verify what actually landed, then follow the ae-data-integration skill to resume
5493
- from the verified offset. Never re-run the whole upload blindly.
5494
-
5495
- ## Files
5496
-
5497
- See \`README.md\` for the package layout.
5498
- `;
5499
- }
5500
- function generateEnvTemplate() {
5501
- return [
5502
- "# Upload target overrides. Copy this file to .local/target.env and fill only",
5503
- "# what the package does not already record (pipeline.json sink.params).",
5504
- "# AE_ENDPOINT: a full receiver URL ending in /sync_json (used when no pushurl is recorded).",
5505
- "# AE_APPID: the destination project APPID (overrides the project info get derivation).",
5506
- "# AE_PROJECT_ID: the destination project ID, used when no project_id is recorded.",
5507
- "AE_ENDPOINT=",
5508
- "AE_APPID=",
5509
- "AE_PROJECT_ID=",
5510
- ""
5511
- ].join("\n");
5512
- }
5513
- function generateGitignore() {
5514
- return ["inbox/", "runs/", ".local/target.env", ""].join("\n");
5515
- }
5516
-
5517
- // src/commands/data-integration/handoff.ts
5518
- var HANDOFF_INDEX_VERSION = "ae-data-integration-index/v1";
5519
- var HANDOFF_DIR_LEN = 16;
5520
- function structureFingerprint(mapping) {
5521
- const canonical = {
5522
- mode: mapping.mode,
5523
- format: mapping.source.format,
5524
- columns: sourceColumns(mapping)
5525
- };
5526
- return createHash3("sha256").update(JSON.stringify(canonical)).digest("hex");
5527
- }
5528
- function upsertIndexEntry(index, entry) {
5529
- const entries = index.entries.filter((item) => item.fingerprint !== entry.fingerprint);
5530
- return { version: index.version, entries: [...entries, entry] };
5531
- }
5532
- function buildHandoffPackage(outDir, mapping, planFile) {
5533
- const fingerprint = structureFingerprint(mapping);
5534
- const dirName = fingerprint.slice(0, HANDOFF_DIR_LEN);
5535
- const handoffDir = join3(outDir, dirName);
5536
- const indexPath = join3(outDir, "index.json");
5537
- const index = readHandoffIndex(indexPath);
5538
- const reusedExisting = index.entries.some((item) => item.fingerprint === fingerprint);
5539
- mkdirSync2(handoffDir, { recursive: true, mode: 448 });
5540
- chmodSync2(handoffDir, 448);
5541
- writeSecureJson2(join3(handoffDir, "mapping.json"), mapping);
5542
- writeSecureText2(join3(handoffDir, "transform.mjs"), createHandoffScript());
5543
- let planFileRel;
5544
- if (planFile) {
5545
- writeSecureJson2(join3(handoffDir, "plan.json"), readPlanFile(planFile));
5546
- planFileRel = `${dirName}/plan.json`;
5547
- }
5548
- const entry = {
5549
- fingerprint,
5550
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
5551
- source_sha256: mapping.source.sha256,
5552
- format: mapping.source.format,
5553
- data_set: mapping.source.data_set,
5554
- mode: mapping.mode,
5555
- property_count: mapping.properties.length,
5556
- mapping_file: `${dirName}/mapping.json`,
5557
- ...planFileRel ? { plan_file: planFileRel } : {}
5558
- };
5559
- writeAtomicJson(indexPath, upsertIndexEntry(index, entry));
5560
- return { outDir, handoffDir, dirName, fingerprint, reusedExisting, planFile: planFileRel, entry };
5561
- }
5562
- function readHandoffIndex(path) {
5563
- let raw;
5564
- try {
5565
- raw = readFileSync6(path, "utf8");
5566
- } catch {
5567
- return { version: HANDOFF_INDEX_VERSION, entries: [] };
5568
- }
5569
- let value;
5570
- try {
5571
- value = JSON.parse(raw);
5572
- } catch {
5573
- throw new CliValidationError("The handoff index is not valid JSON.", {
5574
- code: "LOCAL_DATA_HANDOFF_INDEX_INVALID",
5575
- location: { field: "out-dir" }
5576
- });
5577
- }
5578
- if (!isRecord4(value) || value.version !== HANDOFF_INDEX_VERSION || !Array.isArray(value.entries)) {
5579
- throw new CliValidationError("The handoff index is not ae-data-integration-index/v1.", {
5580
- code: "LOCAL_DATA_HANDOFF_INDEX_INVALID",
5581
- location: { field: "out-dir" }
5582
- });
5583
- }
5584
- return value;
5585
- }
5586
- function readPlanFile(path) {
5587
- let raw;
5588
- try {
5589
- raw = readFileSync6(path, "utf8");
5590
- } catch {
5591
- throw new CliValidationError("The tracking-plan file could not be read.", {
5592
- code: "LOCAL_DATA_HANDOFF_PLAN_NOT_FOUND",
5593
- location: { field: "plan-file" }
5594
- });
5595
- }
5596
- try {
5597
- return JSON.parse(raw);
5598
- } catch {
5599
- throw new CliValidationError("The tracking-plan file is not valid JSON.", {
5600
- code: "LOCAL_DATA_HANDOFF_PLAN_INVALID",
5601
- location: { field: "plan-file" }
5602
- });
5603
- }
5604
- }
5605
- function createHandoffScript() {
5606
- return [
5607
- "import { createHash } from 'node:crypto';",
5608
- "import { createReadStream, readFileSync } from 'node:fs';",
5609
- "import { spawnSync } from 'node:child_process';",
5610
- "import { fileURLToPath } from 'node:url';",
5611
- "import { dirname, join } from 'node:path';",
5612
- "",
5613
- "const [inputFile, outputDir] = process.argv.slice(2);",
5614
- "if (!inputFile) { console.error('Usage: node transform.mjs <new-input-file> [<output-dir>]'); process.exit(2); }",
5615
- "",
5616
- "async function sha256Of(file) {",
5617
- " const hash = createHash('sha256');",
5618
- " for await (const chunk of createReadStream(file)) hash.update(chunk);",
5619
- " return hash.digest('hex');",
5620
- "}",
5621
- "",
5622
- "const here = dirname(fileURLToPath(import.meta.url));",
5623
- "const mapping = JSON.parse(readFileSync(join(here, 'mapping.json'), 'utf8'));",
5624
- "// Re-stamp the content fingerprint for this specific file; the transform logic is reused unchanged.",
5625
- "mapping.source.sha256 = await sha256Of(inputFile);",
5626
- "",
5627
- "const args = ['data-integration', 'convert', '--input-file', inputFile, '--mapping', JSON.stringify(mapping)];",
5628
- "if (outputDir) args.push('--output-dir', outputDir);",
5629
- "const result = spawnSync('ae-cli', args, { stdio: 'inherit' });",
5630
- "process.exit(result.status ?? 1);",
5631
- ""
5632
- ].join("\n");
5633
- }
5634
- function writeSecureJson2(path, value) {
5635
- writeSecureText2(path, `${JSON.stringify(value, null, 2)}
5636
- `);
5637
- }
5638
- function writeSecureText2(path, content) {
5639
- writeFileSync2(path, content, { encoding: "utf8", mode: 384 });
5640
- chmodSync2(path, 384);
5641
- }
5642
- function writeAtomicJson(path, value) {
5643
- writeSecureText2(`${path}.tmp`, `${JSON.stringify(value, null, 2)}
5644
- `);
5645
- renameSync2(`${path}.tmp`, path);
5646
- chmodSync2(path, 384);
5647
- }
5648
- function isRecord4(value) {
5649
- return value !== null && typeof value === "object" && !Array.isArray(value);
5650
- }
5651
- var dataIntegrationHandoff = {
5652
- service: "data-integration",
5653
- command: "handoff",
5654
- usesAeHost: false,
5655
- description: "Export a reusable handoff package (pipeline descriptor + frozen mappings + stage executors + docs) and a shareable zip.",
5656
- flags: [
5657
- { name: "mapping", type: "string", required: true, variadic: true, sensitive: true, desc: `Confirmed ${MAPPING_VERSION} JSON, file path, or @file. Repeat for multiple data sets (one sheet each).` },
5658
- { name: "plan-file", type: "string", sensitive: true, desc: "Tracking-plan draft.json to reference inside the handoff package." },
5659
- { name: "out-dir", type: "string", sensitive: true, desc: "Handoff root directory. Default: .ae-cli/data-integration (project workspace)." },
5660
- { name: "pushurl", type: "string", sensitive: true, desc: "Receiver base URL to record as the reuse upload target (sink endpoint = pushurl + /sync_json). Reuse still requires --confirm." },
5661
- { name: "project-id", type: "string", sensitive: true, desc: "Numeric destination project ID to record; upload derives the APPID from it via project info get." }
5662
- ],
5663
- risk: "write",
5664
- dryRun: async (ctx) => {
5665
- const mappings = ctx.list("mapping").map((source) => readLocalDataMapping(source));
5666
- const outDir = resolve3(ctx.str("out-dir").trim() || join3(".ae-cli", "data-integration"));
5667
- const planFile = ctx.str("plan-file").trim() || void 0;
5668
- const pushurl = ctx.str("pushurl").trim() || void 0;
5669
- const projectId = ctx.str("project-id").trim() || void 0;
5670
- const fingerprints = mappings.map(structureFingerprint);
5671
- return {
5672
- action: "handoff_local_data",
5673
- out_dir: outDir,
5674
- mapping_count: mappings.length,
5675
- fingerprints,
5676
- target: { pushurl, project_id: projectId },
5677
- files: handoffFileList(fingerprints, planFile),
5678
- index_file: join3(outDir, "index.json"),
5679
- pipeline_file: join3(outDir, "pipeline.json"),
5680
- shape_file: join3(outDir, "shape.json"),
5681
- zip_path: fingerprints[0] ? zipPathFor(outDir, fingerprints[0]) : void 0
5682
- };
5683
- },
5684
- execute: async (ctx) => {
5685
- const mappings = ctx.list("mapping").map((source) => readLocalDataMapping(source));
5686
- const outDir = resolve3(ctx.str("out-dir").trim() || join3(".ae-cli", "data-integration"));
5687
- const planFile = ctx.str("plan-file").trim() || void 0;
5688
- const target = {
5689
- pushurl: ctx.str("pushurl").trim() || void 0,
5690
- project_id: ctx.str("project-id").trim() || void 0
5691
- };
5692
- const items = mappings.map((mapping) => ({
5693
- mapping,
5694
- build: buildHandoffPackage(outDir, mapping, planFile)
5695
- }));
5696
- const entries = items.map((item) => item.build.entry);
5697
- const relayFiles = [
5698
- { relPath: "pipeline.json", content: `${JSON.stringify(buildPipelineDescriptor(entries, target), null, 2)}
5699
- `, mode: 384 },
5700
- { relPath: "shape.json", content: `${JSON.stringify(buildShapeBaseline(items.map((item) => ({ mapping: item.mapping, fingerprint: item.build.fingerprint }))), null, 2)}
5701
- `, mode: 384 },
5702
- ...generateBinScripts(),
5703
- { relPath: "README.md", content: generateReadme(), mode: 384 },
5704
- { relPath: "RUNBOOK.md", content: generateRunbook(), mode: 384 },
5705
- { relPath: ".local/target.env.example", content: generateEnvTemplate(), mode: 384 },
5706
- { relPath: ".gitignore", content: generateGitignore(), mode: 384 },
5707
- { relPath: "inbox/.gitkeep", content: "", mode: 384 },
5708
- { relPath: "runs/.gitkeep", content: "", mode: 384 }
5709
- ];
5710
- for (const file of relayFiles) writeRelayFile(outDir, file);
5711
- const zipPath = zipPathFor(outDir, entries[0].fingerprint);
5712
- const stagingDir = stageScopedPackage(outDir, items.map((item) => item.build), entries, relayFiles);
5713
- try {
5714
- await zipPackage(stagingDir, zipPath);
5715
- chmodSync2(zipPath, 384);
5716
- } finally {
5717
- rmSync(stagingDir, { recursive: true, force: true });
5718
- }
5719
- return {
5720
- out_dir: outDir,
5721
- zip_path: zipPath,
5722
- pipeline_file: join3(outDir, "pipeline.json"),
5723
- shape_file: join3(outDir, "shape.json"),
5724
- index_file: join3(outDir, "index.json"),
5725
- handoff_dirs: items.map((item) => item.build.dirName),
5726
- deliverables: buildDeliverables(outDir, relayFiles, items),
5727
- next_steps: [
5728
- `Review the pipeline descriptor and four confirmation gates: ${join3(outDir, "RUNBOOK.md")}.`,
5729
- `Share the archive: ${zipPath}.`,
5730
- `Next same-shape file: cd ${outDir} && bin/run.sh <new-file>, then bin/upload.sh runs/<run-id> --confirm.`
5731
- ],
5732
- reused_existing: items.some((item) => item.build.reusedExisting)
5733
- };
5734
- }
5735
- };
5736
- function zipPathFor(outDir, fingerprint) {
5737
- return join3(dirname2(resolve3(outDir)), `ae-data-integration-handoff-${fingerprint.slice(0, 8)}.zip`);
5738
- }
5739
- var RELAY_FILE_PATHS = [
5740
- "pipeline.json",
5741
- "shape.json",
5742
- "index.json",
5743
- "README.md",
5744
- "RUNBOOK.md",
5745
- ".local/target.env.example",
5746
- ".gitignore",
5747
- "bin/run.sh",
5748
- "bin/upload.sh",
5749
- "bin/bind_mapping.py",
5750
- "bin/summarize.py",
5751
- "bin/plan_check.py",
5752
- "bin/verify.py",
5753
- "bin/resolve_appid.py",
5754
- "inbox/.gitkeep",
5755
- "runs/.gitkeep"
5756
- ];
5757
- function mappingDirFiles(dirName, planFile) {
5758
- return [
5759
- `${dirName}/mapping.json`,
5760
- `${dirName}/transform.mjs`,
5761
- ...planFile ? [`${dirName}/plan.json`] : []
5762
- ];
5763
- }
5764
- function handoffFileList(fingerprints, planFile) {
5765
- const perMapping = fingerprints.flatMap(
5766
- (fingerprint) => mappingDirFiles(fingerprint.slice(0, HANDOFF_DIR_LEN), planFile)
5767
- );
5768
- return [...RELAY_FILE_PATHS, ...perMapping];
5769
- }
5770
- function buildDeliverables(outDir, relayFiles, items) {
5771
- const relay = [
5772
- { rel_path: "index.json", abs_path: join3(outDir, "index.json") },
5773
- ...relayFiles.map((file) => ({ rel_path: file.relPath, abs_path: join3(outDir, file.relPath) }))
5774
- ];
5775
- const mappings = items.flatMap(
5776
- (item) => mappingDirFiles(item.build.dirName, item.build.planFile).map((rel) => ({
5777
- rel_path: rel,
5778
- abs_path: join3(outDir, rel)
5779
- }))
5780
- );
5781
- return [...relay, ...mappings];
5782
- }
5783
- function writeRelayFile(outDir, file) {
5784
- const abs = join3(outDir, file.relPath);
5785
- mkdirSync2(dirname2(abs), { recursive: true, mode: 448 });
5786
- writeFileSync2(abs, file.content, { encoding: "utf8", mode: file.mode });
5787
- chmodSync2(abs, file.mode);
5788
- }
5789
- function stageScopedPackage(outDir, mappingDirs, entries, relayFiles) {
5790
- const staging = mkdtempSync(join3(tmpdir(), "ae-handoff-"));
5791
- writeSecureJson2(join3(staging, "index.json"), { version: HANDOFF_INDEX_VERSION, entries });
5792
- for (const file of relayFiles) writeRelayFile(staging, file);
5793
- for (const { dirName, planFile } of mappingDirs) {
5794
- for (const rel of mappingDirFiles(dirName, planFile)) {
5795
- const dest = join3(staging, rel);
5796
- mkdirSync2(dirname2(dest), { recursive: true, mode: 448 });
5797
- writeFileSync2(dest, readFileSync6(join3(outDir, rel), "utf8"), { encoding: "utf8", mode: 384 });
5798
- chmodSync2(dest, 384);
5799
- }
5800
- }
5801
- return staging;
5802
- }
5803
-
5804
- // src/commands/data-integration/reuse.ts
5805
- import { readFileSync as readFileSync7 } from "fs";
5806
- import { dirname as dirname4, join as join5, resolve as resolve5 } from "path";
5807
-
5808
- // src/commands/data-integration/handoff-root.ts
5809
- import { existsSync as existsSync2 } from "fs";
5810
- import { dirname as dirname3, join as join4, resolve as resolve4 } from "path";
5811
- function globalHandoffDir() {
5812
- const home = process.env.HOME;
5813
- if (!home) return void 0;
5814
- return join4(getConfigDir(), "data-integration");
5815
- }
5816
- function upwardHandoffDirs(startDir) {
5817
- const dirs = [];
5818
- let current = resolve4(startDir);
5819
- for (; ; ) {
5820
- const candidate = join4(current, ".ae-cli", "data-integration");
5821
- if (!dirs.includes(candidate)) dirs.push(candidate);
5822
- const parent = dirname3(current);
5823
- if (parent === current) break;
5824
- current = parent;
5825
- }
5826
- return dirs;
5827
- }
5828
- function reuseSearchPaths(startDir = process.cwd()) {
5829
- const globalDir = globalHandoffDir();
5830
- return globalDir ? [...upwardHandoffDirs(startDir), globalDir] : upwardHandoffDirs(startDir);
5831
- }
5832
- function findReuseRoot(startDir = process.cwd()) {
5833
- for (const dir of upwardHandoffDirs(startDir)) {
5834
- if (existsSync2(join4(dir, "index.json"))) return dir;
5835
- }
5836
- return globalHandoffDir();
5837
- }
5838
-
5839
- // src/commands/data-integration/reuse.ts
5840
- function detectReuse(mapping, outDir) {
5841
- const fingerprint = structureFingerprint(mapping);
5842
- const indexPath = join5(outDir, "index.json");
5843
- const index = readHandoffIndex(indexPath);
5844
- const entry = index.entries.find((item) => item.fingerprint === fingerprint);
5845
- if (!entry) return { matched: false, fingerprint, index_file: indexPath };
5846
- const mappingPath = join5(outDir, entry.mapping_file);
5847
- const match = {
5848
- fingerprint: entry.fingerprint,
5849
- created_at: entry.created_at,
5850
- format: entry.format,
5851
- data_set: entry.data_set,
5852
- mode: entry.mode,
5853
- property_count: entry.property_count,
5854
- mapping_file: entry.mapping_file,
5855
- ...entry.plan_file ? { plan_file: entry.plan_file } : {},
5856
- ...readFrozenEventName(mappingPath),
5857
- run: `node ${join5(outDir, dirname4(entry.mapping_file), "transform.mjs")} <new-input-file> [<output-dir>]`
5858
- };
5859
- return { matched: true, fingerprint, index_file: indexPath, match };
5860
- }
5861
- function readFrozenEventName(path) {
5862
- let value;
5863
- try {
5864
- value = JSON.parse(readFileSync7(path, "utf8"));
5865
- } catch {
5866
- return {};
5867
- }
5868
- if (isRecord5(value) && typeof value.default_event_name === "string" && value.default_event_name) {
5869
- return { default_event_name: value.default_event_name };
5870
- }
5871
- return {};
5872
- }
5873
- function isRecord5(value) {
5874
- return value !== null && typeof value === "object" && !Array.isArray(value);
5875
- }
5876
- var dataIntegrationReuse = {
5877
- service: "data-integration",
5878
- command: "reuse",
5879
- usesAeHost: false,
5880
- description: "Match a candidate mapping against the .ae-cli/data-integration/ handoff index and propose a reusable package.",
5881
- flags: [
5882
- { name: "mapping", type: "string", required: true, sensitive: true, desc: `Candidate ${MAPPING_VERSION} JSON, file path, or @file (typically inspect recommended_mapping).` },
5883
- { name: "out-dir", type: "string", sensitive: true, desc: "Handoff root directory. Default: nearest .ae-cli/data-integration/ upward from cwd, then ~/.ae-cli/data-integration/." }
5884
- ],
5885
- risk: "read",
5886
- dryRun: async (ctx) => {
5887
- const mapping = readLocalDataMapping(ctx.str("mapping"));
5888
- const outDir = resolveReuseOutDir(ctx);
5889
- const result = detectReuse(mapping, outDir);
5890
- return {
5891
- action: "reuse_detect",
5892
- fingerprint: result.fingerprint,
5893
- matched: result.matched,
5894
- index_file: result.index_file,
5895
- searched_paths: searchedIndexPaths(ctx)
5896
- };
5897
- },
5898
- execute: async (ctx) => {
5899
- const mapping = readLocalDataMapping(ctx.str("mapping"));
5900
- const outDir = resolveReuseOutDir(ctx);
5901
- const result = detectReuse(mapping, outDir);
5902
- return { ...result, searched_paths: searchedIndexPaths(ctx) };
5903
- }
5904
- };
5905
- function resolveReuseOutDir(ctx) {
5906
- const explicit = ctx.str("out-dir").trim();
5907
- if (explicit) return resolve5(explicit);
5908
- return findReuseRoot() ?? resolve5(join5(".ae-cli", "data-integration"));
5909
- }
5910
- function searchedIndexPaths(ctx) {
5911
- const explicit = ctx.str("out-dir").trim();
5912
- const dirs = explicit ? [resolve5(explicit)] : reuseSearchPaths();
5913
- return dirs.map((dir) => join5(dir, "index.json"));
5914
- }
5915
-
5916
- // src/commands/data-integration/index.ts
5917
- var commands = [dataIntegrationInspect, dataIntegrationPlan, dataIntegrationConvert, dataIntegrationUpload, dataIntegrationHandoff, dataIntegrationReuse];
5918
- var data_integration_default = commands;
5919
3808
  export {
5920
- dataIntegrationConvert,
5921
- dataIntegrationHandoff,
5922
- dataIntegrationInspect,
5923
- dataIntegrationPlan,
5924
- dataIntegrationReuse,
5925
- dataIntegrationUpload,
5926
- data_integration_default as default
3809
+ assessFileSize,
3810
+ readParquetSchema,
3811
+ resolveLocalDataInputMeta,
3812
+ inspectLocalDataInput,
3813
+ selectDataSet,
3814
+ sha256File,
3815
+ detectHeaderRow,
3816
+ peekDelimitedRecords,
3817
+ detectLeadingTitleRows,
3818
+ readExcelSheetHeaders,
3819
+ peekXlsxRows,
3820
+ MAPPING_VERSION,
3821
+ readLocalDataMapping,
3822
+ sourceColumns,
3823
+ detectColumnTypeConflicts,
3824
+ buildColumnUnion,
3825
+ profileLocalData,
3826
+ convertLocalData,
3827
+ convertLocalDataMulti,
3828
+ convertRow
5927
3829
  };