@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
@@ -0,0 +1,2138 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ validateAndFix,
4
+ validateDraft
5
+ } from "./chunk-HBI7IQH3.js";
6
+ import {
7
+ MAPPING_VERSION,
8
+ assessFileSize,
9
+ buildColumnUnion,
10
+ convertLocalData,
11
+ convertLocalDataMulti,
12
+ detectColumnTypeConflicts,
13
+ detectHeaderRow,
14
+ detectLeadingTitleRows,
15
+ inspectLocalDataInput,
16
+ peekDelimitedRecords,
17
+ peekXlsxRows,
18
+ profileLocalData,
19
+ readExcelSheetHeaders,
20
+ readLocalDataMapping,
21
+ readParquetSchema,
22
+ resolveLocalDataInputMeta,
23
+ selectDataSet,
24
+ sha256File,
25
+ sourceColumns
26
+ } from "./chunk-V6UKLIM6.js";
27
+ import "./chunk-RLPMXKDQ.js";
28
+ import "./chunk-EQMGH32F.js";
29
+ import {
30
+ require_archiver
31
+ } from "./chunk-GD5JSAGV.js";
32
+ import "./chunk-NPH5J65M.js";
33
+ import {
34
+ assembleSyncJsonBody,
35
+ resolveSyncJsonEndpoint
36
+ } from "./chunk-6IUTXRAD.js";
37
+ import {
38
+ getConfigDir
39
+ } from "./chunk-IGU3R2JD.js";
40
+ import "./chunk-MTK4ZE7W.js";
41
+ import {
42
+ CliValidationError,
43
+ LocalDataUploadError,
44
+ __toESM
45
+ } from "./chunk-3ZQY7SLZ.js";
46
+
47
+ // src/commands/data-integration/inspect.ts
48
+ import { basename } from "path";
49
+ 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.";
50
+ var dataIntegrationInspect = {
51
+ service: "data-integration",
52
+ command: "inspect",
53
+ usesAeHost: false,
54
+ description: "Stream one or more local CSV, TSV, TXT, JSON, JSONL, XLS, XLSX, or Parquet files and recommend a UE mapping.",
55
+ flags: [
56
+ { 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." },
57
+ { name: "data-set", type: "string", sensitive: true, desc: "Sheet or JSON Path ID returned by a discovery-only inspection." },
58
+ { name: "source-timezone", type: "string", default: "Asia/Shanghai", desc: "IANA timezone used to interpret source times without an offset." },
59
+ { name: "headers", type: "string", sensitive: true, desc: "Comma-separated explicit column names for a headerless file; the first row is data." },
60
+ { name: "headerless", type: "boolean", default: false, desc: "Treat the first row as data and auto-generate col_1..col_N names." },
61
+ { 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." },
62
+ { 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." },
63
+ { 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." }
64
+ ],
65
+ risk: "read",
66
+ validate: (ctx) => {
67
+ const skipRows = ctx.num("skip-rows");
68
+ if (!Number.isInteger(skipRows) || skipRows < 0) {
69
+ throw new CliValidationError("Skipped rows must be a non-negative integer.", {
70
+ code: "LOCAL_DATA_SKIP_ROWS_INVALID",
71
+ location: { field: "skip-rows" }
72
+ });
73
+ }
74
+ },
75
+ // Fast size/time pre-check (stat + format/encoding sniff only — no sha256, no profile).
76
+ // Lets agents surface the estimate before committing to a multi-minute full inspection.
77
+ dryRun: async (ctx) => {
78
+ const files = ctx.list("input-file").map((filePath) => {
79
+ const meta = resolveLocalDataInputMeta(filePath);
80
+ const assessment = assessFileSize(basename(filePath), meta.format, meta.sizeBytes, meta.encoding);
81
+ return {
82
+ file: basename(filePath),
83
+ format: meta.format,
84
+ size_bytes: meta.sizeBytes,
85
+ size: assessment.size,
86
+ ...assessment.estimatedDuration ? { estimated_duration: assessment.estimatedDuration } : {},
87
+ ...assessment.warning ? { warning: assessment.warning } : {},
88
+ ...assessment.reason ? { reason: assessment.reason } : {},
89
+ ...assessment.memoryRisk ? { memory_risk: true } : {},
90
+ ...assessment.rejected ? { rejected: true } : {}
91
+ };
92
+ });
93
+ return {
94
+ version: "ae-local-data-estimate/v1",
95
+ files,
96
+ has_large_file: files.some((file) => Boolean(file.warning) || file.rejected)
97
+ };
98
+ },
99
+ execute: async (ctx) => {
100
+ const inputFiles = ctx.list("input-file");
101
+ const headerNames = splitHeaders(ctx.str("headers"));
102
+ const noHeader = ctx.bool("headerless");
103
+ const sourceTimezone = ctx.str("source-timezone");
104
+ const requested = ctx.str("data-set").trim() || void 0;
105
+ const skipRows = ctx.num("skip-rows");
106
+ const fillMergedCells = ctx.bool("fill-merged-cells");
107
+ const excludeHiddenRows = ctx.bool("exclude-hidden-rows");
108
+ if (inputFiles.length === 1) {
109
+ const input = await inspectLocalDataInput(inputFiles[0]);
110
+ const headerConsistency = await readExcelHeaderConsistency(input);
111
+ const excludedSheets = summarizeExcludedSheets(input);
112
+ if (!requested && input.dataSets.length > 1) {
113
+ return {
114
+ version: "ae-local-data-profile/v1",
115
+ selection_required: true,
116
+ source: { format: input.format, size_bytes: input.sizeBytes, sha256: input.sha256 },
117
+ data_sets: input.dataSets,
118
+ ...excludedSheets,
119
+ ...headerConsistency ?? {},
120
+ next_step: "Run inspect again with --data-set, then review the recommended mapping."
121
+ };
122
+ }
123
+ const dataSet = selectDataSet(input, requested);
124
+ const headerPresence = headerNames || noHeader ? void 0 : detectHeaderPresence(input, skipRows);
125
+ const headerSignal = headerNames || noHeader ? void 0 : await detectHeaderSignal(input, dataSet, skipRows);
126
+ const profile = await profileLocalData(input, dataSet, sourceTimezone, {
127
+ collectSamples: true,
128
+ collectNestedTree: true,
129
+ headerNames,
130
+ noHeader: noHeader || Boolean(headerPresence),
131
+ skipRows,
132
+ fillMergedCells,
133
+ excludeHiddenRows
134
+ });
135
+ const annotated = headerPresence ? annotateHeaderless(profile, headerPresence) : profile;
136
+ return {
137
+ ...annotated,
138
+ ...excludedSheets,
139
+ ...headerConsistency ?? {},
140
+ ...annotateRowSkips(annotated.warnings, skipRows, headerSignal)
141
+ };
142
+ }
143
+ const files = [];
144
+ if (inputFiles.every((file) => resolveLocalDataInputMeta(file).format === "parquet")) {
145
+ const checked = await inspectParquetFiles(inputFiles, sourceTimezone);
146
+ if (checked) return checked;
147
+ }
148
+ for (const inputFile of inputFiles) {
149
+ const input = await inspectLocalDataInput(inputFile);
150
+ const dataSet = selectDataSet(input);
151
+ const headerPresence = headerNames || noHeader ? void 0 : detectHeaderPresence(input, skipRows);
152
+ const headerSignal = headerNames || noHeader ? void 0 : await detectHeaderSignal(input, dataSet, skipRows);
153
+ const profile = await profileLocalData(input, dataSet, sourceTimezone, {
154
+ collectSamples: true,
155
+ collectNestedTree: true,
156
+ headerNames,
157
+ noHeader: noHeader || Boolean(headerPresence),
158
+ skipRows,
159
+ fillMergedCells,
160
+ excludeHiddenRows
161
+ });
162
+ const annotated = headerPresence ? annotateHeaderless(profile, headerPresence) : profile;
163
+ const headerConsistency = await readExcelHeaderConsistency(input);
164
+ files.push({
165
+ file: basename(inputFile),
166
+ profile: {
167
+ ...annotated,
168
+ ...summarizeExcludedSheets(input),
169
+ ...headerConsistency ?? {},
170
+ ...annotateRowSkips(annotated.warnings, skipRows, headerSignal)
171
+ }
172
+ });
173
+ }
174
+ return {
175
+ version: "ae-local-data-profile/v1",
176
+ files: files.map((entry) => entry.profile),
177
+ conflicts: detectColumnTypeConflicts(files),
178
+ column_union: buildColumnUnion(files)
179
+ };
180
+ }
181
+ };
182
+ async function inspectParquetFiles(inputFiles, sourceTimezone) {
183
+ const firstPath = inputFiles[0];
184
+ const firstSchema = await readParquetSchema(firstPath);
185
+ const first = await inspectLocalDataInput(firstPath);
186
+ const profile = await profileLocalData(first, selectDataSet(first), sourceTimezone, {
187
+ collectSamples: true,
188
+ collectNestedTree: true
189
+ });
190
+ const files = [];
191
+ let totalRowCount = 0;
192
+ let totalSizeBytes = 0;
193
+ for (const inputFile of inputFiles) {
194
+ const meta = resolveLocalDataInputMeta(inputFile);
195
+ const schema = inputFile === firstPath ? firstSchema : await readParquetSchema(inputFile);
196
+ if (schema.signature !== firstSchema.signature) return void 0;
197
+ files.push({ file: basename(inputFile), row_count: schema.numRows, size_bytes: meta.sizeBytes });
198
+ totalRowCount += schema.numRows;
199
+ totalSizeBytes += meta.sizeBytes;
200
+ }
201
+ return {
202
+ version: "ae-local-data-profile/v1",
203
+ schema_checked: true,
204
+ representative: { file: basename(firstPath), profile },
205
+ files,
206
+ total_row_count: totalRowCount,
207
+ total_size_bytes: totalSizeBytes
208
+ };
209
+ }
210
+ function summarizeExcludedSheets(input) {
211
+ const excluded = input.excludedDataSets ?? [];
212
+ if (excluded.length === 0) return {};
213
+ return {
214
+ excluded_sheets: excluded.map((dataSet) => ({ name: dataSet.label, reason: "hidden", data_set: dataSet.id }))
215
+ };
216
+ }
217
+ async function readExcelHeaderConsistency(input) {
218
+ if (input.format !== "xls" && input.format !== "xlsx") return void 0;
219
+ return summarizeHeaderConsistency(await readExcelSheetHeaders(input.filePath, input.format));
220
+ }
221
+ function summarizeHeaderConsistency(sheets) {
222
+ if (sheets.length <= 1) return void 0;
223
+ const first = JSON.stringify(sheets[0].headers);
224
+ const allSame = sheets.every((sheet) => JSON.stringify(sheet.headers) === first);
225
+ return allSame ? { header_consistency: "all_same" } : { header_consistency: "different", header_details: sheets.map((sheet) => ({ name: sheet.name, headers: sheet.headers })) };
226
+ }
227
+ function detectHeaderPresence(input, skipRows = 0) {
228
+ if (input.format !== "csv" && input.format !== "tsv") return void 0;
229
+ const delimiter = input.delimiter ?? (input.format === "tsv" ? " " : ",");
230
+ const peeked = peekDelimitedRecords(input.filePath, { delimiter, encoding: input.encoding, limit: 10 + skipRows });
231
+ const records = peeked.slice(skipRows);
232
+ const detection = detectHeaderRow(records);
233
+ if (detection.hasHeaders) return void 0;
234
+ return {
235
+ detection,
236
+ autoHeaders: (records[0] ?? []).map((_, index) => `col_${index + 1}`)
237
+ };
238
+ }
239
+ async function detectHeaderSignal(input, dataSet, skipRows) {
240
+ const rows = await peekHeaderRows(input, dataSet, skipRows);
241
+ if (!rows || rows.length === 0) return void 0;
242
+ const titleRows = detectLeadingTitleRows(rows).map((title) => ({ ...title, row: title.row + skipRows }));
243
+ if (input.format !== "xlsx") return titleRows.length > 0 ? { titleRows } : void 0;
244
+ const detection = detectHeaderRow(rows.map((row) => row.map((value) => isEmptyCell(value) ? "" : String(value))));
245
+ if (detection.hasHeaders && titleRows.length === 0) return void 0;
246
+ return { ...detection.hasHeaders ? {} : { detection }, titleRows };
247
+ }
248
+ async function peekHeaderRows(input, dataSet, skipRows) {
249
+ if (input.format === "csv" || input.format === "tsv") {
250
+ const delimiter = input.delimiter ?? (input.format === "tsv" ? " " : ",");
251
+ return peekDelimitedRecords(input.filePath, { delimiter, encoding: input.encoding, limit: 10 + skipRows }).slice(skipRows);
252
+ }
253
+ if (input.format === "xlsx" && dataSet.kind === "sheet") {
254
+ return (await peekXlsxRows(input.filePath, dataSet.label, 10 + skipRows)).slice(skipRows);
255
+ }
256
+ return void 0;
257
+ }
258
+ function isEmptyCell(value) {
259
+ return value === null || value === void 0 || value === "";
260
+ }
261
+ 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.";
262
+ 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.";
263
+ function annotateRowSkips(warnings, skipRows, signal) {
264
+ const extra = [];
265
+ if (signal?.titleRows.length) extra.push(TITLE_ROW_WARNING);
266
+ if (signal?.detection) extra.push(EXCEL_HEADERLESS_WARNING);
267
+ return {
268
+ warnings: extra.length > 0 ? [...warnings, ...extra] : warnings,
269
+ ...skipRows > 0 ? { skipped_rows: skipRows } : {},
270
+ ...signal?.titleRows.length ? { leading_title_rows: signal.titleRows } : {},
271
+ ...signal?.detection ? { header_signal: signal.detection } : {}
272
+ };
273
+ }
274
+ function annotateHeaderless(profile, presence) {
275
+ return {
276
+ ...profile,
277
+ no_headers: true,
278
+ header_detection: presence.detection,
279
+ auto_headers: presence.autoHeaders,
280
+ warnings: [...profile.warnings, HEADERLESS_WARNING]
281
+ };
282
+ }
283
+ function splitHeaders(raw) {
284
+ const value = raw.trim();
285
+ if (!value) return void 0;
286
+ const headers = value.split(",").map((header) => header.trim()).filter((header) => header.length > 0);
287
+ return headers.length > 0 ? headers : void 0;
288
+ }
289
+
290
+ // src/commands/data-integration/plan.ts
291
+ import { writeFile } from "fs/promises";
292
+ var VALID_LOCALES = /* @__PURE__ */ new Set(["zh", "en", "ja", "ko"]);
293
+ var EVENT_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
294
+ function toPropType(type) {
295
+ switch (type) {
296
+ case "number":
297
+ return "number";
298
+ case "boolean":
299
+ return "bool";
300
+ case "datetime":
301
+ return "datetime";
302
+ case "list":
303
+ return "array_string";
304
+ case "object":
305
+ return "object";
306
+ case "array_row":
307
+ return "array_row";
308
+ case "string":
309
+ return "string";
310
+ }
311
+ }
312
+ function buildDraftFromMapping(options) {
313
+ const { mapping } = options;
314
+ const excluded = new Set(mapping.exclude_columns ?? []);
315
+ const properties = mapping.properties.filter((property) => !excluded.has(property.source) && !property.target.startsWith("#")).map((property) => {
316
+ const leaf = property.target.includes(".") ? property.target.split(".").pop() : void 0;
317
+ return {
318
+ name: property.target,
319
+ display_name: leaf ?? property.source,
320
+ desc: property.desc ?? leaf ?? property.source,
321
+ type: toPropType(property.type),
322
+ source: "data"
323
+ };
324
+ });
325
+ const propNames = properties.map((property) => property.name);
326
+ const eventNames = resolveEventNames(options);
327
+ const events = eventNames.map((eventName) => {
328
+ const meta = mapping.event_meta?.[eventName];
329
+ const sourceName = reverseEventSourceName(mapping, eventName) ?? eventName;
330
+ return {
331
+ event_name: eventName,
332
+ display_name: eventName,
333
+ event_desc: meta?.desc ?? sourceName,
334
+ event_tag: meta?.tag ?? sourceName,
335
+ source: "data",
336
+ prop_names: propNames
337
+ };
338
+ });
339
+ const isUserSet = mapping.mode === "user_set";
340
+ const isMixed = mapping.mode === "mixed";
341
+ return {
342
+ meta: {
343
+ app_type: options.appType,
344
+ sdk_integration_mode: "none",
345
+ plan_name: options.planName,
346
+ source_type: "data",
347
+ lang: options.lang,
348
+ ...options.projectId !== void 0 ? { project_id: options.projectId } : {}
349
+ },
350
+ events: isUserSet ? [] : events,
351
+ event_properties: isUserSet ? [] : properties,
352
+ common_event_properties: [],
353
+ user_properties: isUserSet || isMixed ? properties.map((property) => ({ ...property, update_type: "user_set" })) : []
354
+ };
355
+ }
356
+ function reverseEventSourceName(mapping, eventName) {
357
+ const eventMap = mapping.value_mapping?.event_name;
358
+ if (!eventMap) return void 0;
359
+ return Object.keys(eventMap).find((source) => eventMap[source] === eventName);
360
+ }
361
+ function resolveEventNames(options) {
362
+ const { mapping } = options;
363
+ if (mapping.mode === "user_set") return [];
364
+ if (options.eventNames.length > 0) {
365
+ const seen = /* @__PURE__ */ new Set();
366
+ for (const name of options.eventNames) {
367
+ if (!EVENT_NAME_RE.test(name)) {
368
+ throw new CliValidationError(`The event name "${name}" is not a legal AE event name.`, {
369
+ code: "LOCAL_DATA_PLAN_INVALID_EVENT_NAME",
370
+ hint: "Event names must match ^[A-Za-z][A-Za-z0-9_]*$.",
371
+ location: { field: "event-name" }
372
+ });
373
+ }
374
+ seen.add(name);
375
+ }
376
+ return [...seen];
377
+ }
378
+ if (mapping.default_event_name) return [mapping.default_event_name];
379
+ throw new CliValidationError("The mapping derives event names from a per-row column.", {
380
+ code: "LOCAL_DATA_PLAN_EVENT_NAMES_REQUIRED",
381
+ hint: "Pass --event-name for each concrete event name, or set default_event_name in the mapping.",
382
+ location: { field: "event-name" }
383
+ });
384
+ }
385
+ function summarize(draft) {
386
+ return {
387
+ plan_name: draft.meta.plan_name,
388
+ events: draft.events.length,
389
+ event_properties: draft.event_properties.length,
390
+ user_properties: draft.user_properties.length
391
+ };
392
+ }
393
+ function buildPlanDraft(ctx) {
394
+ const mapping = readLocalDataMapping(ctx.str("mapping"));
395
+ const lang = ctx.str("lang");
396
+ if (!VALID_LOCALES.has(lang)) {
397
+ throw new CliValidationError("lang must be one of zh, en, ja, ko.", {
398
+ code: "LOCAL_DATA_PLAN_INVALID_LANG",
399
+ location: { field: "lang" }
400
+ });
401
+ }
402
+ const draft = buildDraftFromMapping({
403
+ mapping,
404
+ planName: ctx.str("plan-name").trim() || mapping.default_event_name || "local-data",
405
+ eventNames: ctx.list("event-name"),
406
+ appType: ctx.str("app-type").trim() || "unknown",
407
+ lang,
408
+ projectId: ctx.optionalNum("project-id")
409
+ });
410
+ validateAndFix(draft);
411
+ try {
412
+ validateDraft(draft);
413
+ } catch (error) {
414
+ throw new CliValidationError("The tracking-plan draft is invalid.", {
415
+ code: "LOCAL_DATA_PLAN_INVALID_DRAFT",
416
+ hint: error instanceof Error ? error.message : String(error),
417
+ location: { field: "mapping" }
418
+ });
419
+ }
420
+ return draft;
421
+ }
422
+ var dataIntegrationPlan = {
423
+ service: "data-integration",
424
+ command: "plan",
425
+ usesAeHost: false,
426
+ description: "Convert a confirmed local-data mapping into a tracking-plan draft.json (source_type=data, sdk_integration_mode=none).",
427
+ flags: [
428
+ { name: "mapping", type: "string", required: true, sensitive: true, desc: `Confirmed ${MAPPING_VERSION} JSON, file path, or @file.` },
429
+ { name: "event-name", type: "string", variadic: true, desc: "Concrete event name (track/mixed without default_event_name). Repeat for multiple events." },
430
+ { name: "plan-name", type: "string", desc: 'Plan name. Default: the mapping default_event_name, else "local-data".' },
431
+ { name: "app-type", type: "string", default: "unknown", desc: "Application type recorded in draft meta (informational)." },
432
+ { name: "lang", type: "string", default: "zh", desc: "xlsx output language: zh / en / ja / ko." },
433
+ { name: "project-id", type: "number", desc: "AE project ID recorded in draft meta (informational)." },
434
+ { name: "out", type: "string", sensitive: true, desc: "Write draft.json to this file instead of stdout." }
435
+ ],
436
+ risk: "write",
437
+ dryRun: async (ctx) => {
438
+ const draft = buildPlanDraft(ctx);
439
+ return {
440
+ action: "plan_local_data",
441
+ plan_name: draft.meta.plan_name,
442
+ sdk_integration_mode: draft.meta.sdk_integration_mode,
443
+ source_type: draft.meta.source_type,
444
+ events: draft.events.map((event) => event.event_name),
445
+ event_properties: draft.events[0]?.prop_names ?? [],
446
+ user_properties: draft.user_properties.map((property) => property.name)
447
+ };
448
+ },
449
+ execute: async (ctx) => {
450
+ const draft = buildPlanDraft(ctx);
451
+ const outPath = ctx.str("out").trim() || void 0;
452
+ if (!outPath) return draft;
453
+ await writeFile(outPath, `${JSON.stringify(draft, null, 2)}
454
+ `, "utf8");
455
+ return { draft_path: outPath, ...summarize(draft) };
456
+ }
457
+ };
458
+
459
+ // src/commands/data-integration/convert.ts
460
+ var dataIntegrationConvert = {
461
+ service: "data-integration",
462
+ command: "convert",
463
+ usesAeHost: false,
464
+ description: "Convert one or more local data sets into validated UE JSONL and quarantine invalid rows.",
465
+ flags: [
466
+ { 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." },
467
+ { name: "mapping", type: "string", required: true, sensitive: true, desc: `${MAPPING_VERSION} JSON, file path, or @file.` },
468
+ { name: "output-dir", type: "string", sensitive: true, desc: "New or empty output directory. Default: .ae-cli/data-integration/runs/<run-id>." },
469
+ { name: "type-resolutions", type: "json", sensitive: true, desc: "JSON object resolving cross-file column type conflicts (unify, split, or skip)." },
470
+ { name: "merge-sheets", type: "boolean", default: false, desc: "Stream every worksheet in file order instead of a single selected sheet." },
471
+ { 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." }
472
+ ],
473
+ risk: "write",
474
+ dryRun: async (ctx) => {
475
+ const inputFiles = ctx.list("input-file");
476
+ const multi = inputFiles.length > 1;
477
+ const mapping = readLocalDataMapping(ctx.str("mapping"), { sourceWildcard: multi });
478
+ if (multi) {
479
+ return {
480
+ action: "convert_local_data_multi",
481
+ file_count: inputFiles.length,
482
+ source_sha256: mapping.source.sha256,
483
+ mode: mapping.mode,
484
+ property_count: mapping.properties.length,
485
+ type_resolutions: ctx.json("type-resolutions") ?? {},
486
+ source_files_unchanged: true
487
+ };
488
+ }
489
+ return {
490
+ action: "convert_local_data",
491
+ source_sha256: mapping.source.sha256,
492
+ data_set: mapping.source.data_set,
493
+ mode: mapping.mode,
494
+ property_count: mapping.properties.length,
495
+ salvage_from: ctx.str("salvage-from").trim() || void 0,
496
+ source_file_unchanged: true
497
+ };
498
+ },
499
+ execute: async (ctx) => {
500
+ const inputFiles = ctx.list("input-file");
501
+ const outputDir = ctx.str("output-dir").trim() || void 0;
502
+ if (inputFiles.length === 1) {
503
+ return convertLocalData({
504
+ inputFile: inputFiles[0],
505
+ mapping: readLocalDataMapping(ctx.str("mapping")),
506
+ outputDir,
507
+ mergeSheets: ctx.bool("merge-sheets"),
508
+ salvageFrom: ctx.str("salvage-from").trim() || void 0
509
+ });
510
+ }
511
+ return convertLocalDataMulti({
512
+ inputFiles,
513
+ mapping: readLocalDataMapping(ctx.str("mapping"), { sourceWildcard: true }),
514
+ typeResolutions: ctx.json("type-resolutions") ?? {},
515
+ outputDir
516
+ });
517
+ }
518
+ };
519
+
520
+ // src/commands/data-integration/upload.ts
521
+ import { createReadStream, readFileSync, statSync } from "fs";
522
+ import { basename as basename2, dirname, resolve } from "path";
523
+ import { createInterface } from "readline";
524
+ var DEFAULT_BATCH_SIZE = 500;
525
+ var MAX_BATCH_SIZE = 1e3;
526
+ var dataIntegrationUpload = {
527
+ service: "data-integration",
528
+ command: "upload",
529
+ usesAeHost: false,
530
+ description: "Sequentially submit validated UE JSONL to an explicit receiver /sync_json endpoint.",
531
+ flags: [
532
+ { name: "ue-file", type: "string", required: true, sensitive: true, desc: "Validated valid.ue.jsonl generated by ae-cli data-integration convert." },
533
+ { name: "manifest", type: "string", required: true, sensitive: true, desc: "Matching ae-local-data-manifest/v1 file." },
534
+ { name: "endpoint", type: "string", required: true, sensitive: true, desc: "Complete receiver URL ending in /sync_json. Unrelated to --host." },
535
+ { name: "appid", type: "string", required: true, sensitive: true, desc: "Destination project APPID. Never stored in generated artifacts or logs." },
536
+ { name: "batch-size", type: "number", default: DEFAULT_BATCH_SIZE, min: 1, max: MAX_BATCH_SIZE, desc: `Sequential records per request. Maximum: ${MAX_BATCH_SIZE}.` },
537
+ { name: "resume-from", type: "number", default: 0, min: 0, desc: "Zero-based record offset selected by the user after verifying an interrupted upload." },
538
+ { name: "allow-clean-subset", type: "boolean", default: false, desc: "Explicitly allow valid rows from a blocked manifest after reviewing quarantine statistics." },
539
+ { 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." },
540
+ { name: "compress", type: "string", default: "none", desc: "Request body compression: gzip or none." },
541
+ { 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." }
542
+ ],
543
+ risk: "write",
544
+ validate: (ctx) => {
545
+ resolveSyncJsonEndpoint(ctx.str("endpoint"));
546
+ const batchSize = ctx.num("batch-size");
547
+ const resumeFrom = ctx.num("resume-from");
548
+ const compress = ctx.str("compress").trim().toLowerCase();
549
+ if (compress !== "gzip" && compress !== "none") {
550
+ throw new CliValidationError("Compression must be gzip or none.", {
551
+ code: "LOCAL_DATA_COMPRESS_INVALID",
552
+ location: { field: "compress" }
553
+ });
554
+ }
555
+ if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > MAX_BATCH_SIZE) {
556
+ throw new CliValidationError(`Batch size must be an integer between 1 and ${MAX_BATCH_SIZE}.`, {
557
+ code: "LOCAL_DATA_BATCH_SIZE_INVALID",
558
+ location: { field: "batch-size" }
559
+ });
560
+ }
561
+ if (!Number.isInteger(resumeFrom) || resumeFrom < 0) {
562
+ throw new CliValidationError("Resume position must be a non-negative integer.", {
563
+ code: "LOCAL_DATA_RESUME_INVALID",
564
+ location: { field: "resume-from" }
565
+ });
566
+ }
567
+ },
568
+ dryRun: async (ctx) => {
569
+ const prepared = await prepareUpload(ctx, false);
570
+ return {
571
+ action: "upload_local_ue_data",
572
+ target: maskEndpoint(prepared.endpoint),
573
+ appid: maskAppid(prepared.appid),
574
+ file_sha256: prepared.manifest.output.valid_sha256,
575
+ record_count: prepared.recordCount,
576
+ resume_from: prepared.resumeFrom,
577
+ remaining_records: Math.max(0, prepared.recordCount - prepared.resumeFrom),
578
+ batch_size: prepared.batchSize,
579
+ batch_count: prepared.batchCount,
580
+ bytes: prepared.fileBytes,
581
+ manifest_status: prepared.manifest.status,
582
+ upload_allowed: prepared.manifest.status === "ready" || ctx.bool("allow-clean-subset"),
583
+ authentication_headers: false,
584
+ transport_retries: 3,
585
+ split_uncertain_batches: ctx.bool("retry"),
586
+ compression: ctx.str("compress").trim().toLowerCase() === "gzip" ? "gzip" : "none",
587
+ debug: ctx.bool("debug"),
588
+ persistence_verified: false
589
+ };
590
+ },
591
+ execute: async (ctx) => {
592
+ const prepared = await prepareUpload(ctx, true);
593
+ const salvageUncertain = ctx.bool("retry");
594
+ const compress = ctx.str("compress").trim().toLowerCase() === "gzip" ? "gzip" : void 0;
595
+ const debug = ctx.bool("debug");
596
+ const transportOptions = { retries: 3, retryDelayMs: 2e3, compress };
597
+ let submittedRecords = 0;
598
+ let submittedBatches = 0;
599
+ let processedRecords = 0;
600
+ let requestBytes = 0;
601
+ let responseBytes = 0;
602
+ const failedRecords = [];
603
+ for await (const batch of readUeBatches(prepared.ueFile, prepared.resumeFrom, prepared.batchSize)) {
604
+ const batchStart = prepared.resumeFrom + processedRecords;
605
+ const body = assembleSyncJsonBody(batch, prepared.appid, debug);
606
+ try {
607
+ const transport = await ctx.localDataUpload(prepared.endpoint, body, transportOptions);
608
+ submittedRecords += batch.length;
609
+ submittedBatches += 1;
610
+ requestBytes += transport.request_bytes;
611
+ responseBytes += transport.response_bytes;
612
+ } catch (error) {
613
+ if (!salvageUncertain || !(error instanceof LocalDataUploadError) || error.meta?.delivery_state !== "unknown") {
614
+ throw decorateBatchError(error, submittedRecords, submittedBatches, batchStart, batch.length);
615
+ }
616
+ for (let index = 0; index < batch.length; index += 1) {
617
+ const offset = batchStart + index;
618
+ try {
619
+ const single = await ctx.localDataUpload(
620
+ prepared.endpoint,
621
+ assembleSyncJsonBody([batch[index]], prepared.appid, debug),
622
+ transportOptions
623
+ );
624
+ submittedRecords += 1;
625
+ submittedBatches += 1;
626
+ requestBytes += single.request_bytes;
627
+ responseBytes += single.response_bytes;
628
+ } catch {
629
+ failedRecords.push(offset);
630
+ }
631
+ }
632
+ }
633
+ processedRecords += batch.length;
634
+ }
635
+ if (failedRecords.length > 0) {
636
+ return {
637
+ status: "partially_delivered",
638
+ code: 0,
639
+ delivery_state: "partially_delivered",
640
+ submitted_records: submittedRecords,
641
+ submitted_batches: submittedBatches,
642
+ resume_from: prepared.resumeFrom,
643
+ failed_records: failedRecords,
644
+ failed_count: failedRecords.length,
645
+ request_bytes: requestBytes,
646
+ response_bytes: responseBytes,
647
+ persistence_verified: false,
648
+ retry_attempted: true,
649
+ next_step: "Verify received data in AE before treating the upload as persisted."
650
+ };
651
+ }
652
+ return {
653
+ status: "receiver_accepted",
654
+ code: 0,
655
+ delivery_state: "receiver_accepted",
656
+ submitted_records: submittedRecords,
657
+ submitted_batches: submittedBatches,
658
+ resume_from: prepared.resumeFrom,
659
+ request_bytes: requestBytes,
660
+ response_bytes: responseBytes,
661
+ persistence_verified: false,
662
+ retry_attempted: false,
663
+ next_step: "Verify received data in AE before treating the upload as persisted."
664
+ };
665
+ }
666
+ };
667
+ async function prepareUpload(ctx, enforceReady) {
668
+ const endpoint = resolveSyncJsonEndpoint(ctx.str("endpoint"));
669
+ const appid = ctx.str("appid").trim();
670
+ if (!appid || appid.length > 256) {
671
+ throw new CliValidationError("APPID must be a non-empty value of at most 256 characters.", {
672
+ code: "LOCAL_DATA_APPID_INVALID",
673
+ location: { field: "appid" }
674
+ });
675
+ }
676
+ const manifestPath = resolve(ctx.str("manifest"));
677
+ const manifest = readManifest(manifestPath);
678
+ const ueFile = resolve(ctx.str("ue-file"));
679
+ const expectedFile = resolve(dirname(manifestPath), manifest.output.valid_file);
680
+ if (ueFile !== expectedFile) {
681
+ throw new CliValidationError("The UE file does not match the manifest output path.", {
682
+ code: "LOCAL_DATA_MANIFEST_FILE_MISMATCH",
683
+ location: { field: "ue-file" }
684
+ });
685
+ }
686
+ let fileBytes;
687
+ try {
688
+ fileBytes = statSync(ueFile).size;
689
+ } catch {
690
+ throw new CliValidationError("The UE JSONL file could not be read.", {
691
+ code: "LOCAL_DATA_UE_FILE_NOT_FOUND",
692
+ location: { field: "ue-file" }
693
+ });
694
+ }
695
+ if (await sha256File(ueFile) !== manifest.output.valid_sha256) {
696
+ throw new CliValidationError("The UE file fingerprint does not match the manifest.", {
697
+ code: "LOCAL_DATA_UE_FILE_CHANGED",
698
+ location: { field: "ue-file" }
699
+ });
700
+ }
701
+ const recordCount = await validateUeFile(ueFile);
702
+ if (recordCount !== manifest.output.valid_records) {
703
+ throw new CliValidationError("The UE record count does not match the manifest.", {
704
+ code: "LOCAL_DATA_UE_COUNT_MISMATCH",
705
+ location: { field: "ue-file" }
706
+ });
707
+ }
708
+ if (enforceReady && manifest.status === "blocked" && !ctx.bool("allow-clean-subset")) {
709
+ throw new CliValidationError("The manifest is blocked because rows were quarantined.", {
710
+ code: "LOCAL_DATA_CLEAN_SUBSET_CONFIRMATION_REQUIRED",
711
+ hint: "Review manifest and invalid.rows.jsonl statistics, then explicitly pass --allow-clean-subset if the valid subset may be uploaded.",
712
+ location: { field: "allow-clean-subset" }
713
+ });
714
+ }
715
+ const resumeFrom = ctx.num("resume-from");
716
+ if (resumeFrom > recordCount) {
717
+ throw new CliValidationError("Resume position exceeds the UE record count.", {
718
+ code: "LOCAL_DATA_RESUME_OUT_OF_RANGE",
719
+ location: { field: "resume-from" }
720
+ });
721
+ }
722
+ const batchSize = ctx.num("batch-size");
723
+ return {
724
+ endpoint,
725
+ appid,
726
+ ueFile,
727
+ manifest,
728
+ batchSize,
729
+ resumeFrom,
730
+ recordCount,
731
+ fileBytes,
732
+ batchCount: Math.ceil(Math.max(0, recordCount - resumeFrom) / batchSize)
733
+ };
734
+ }
735
+ function readManifest(path) {
736
+ let value;
737
+ try {
738
+ value = JSON.parse(readFileSync(path, "utf8"));
739
+ } catch {
740
+ throw new CliValidationError("The local-data manifest could not be read as JSON.", {
741
+ code: "LOCAL_DATA_MANIFEST_INVALID",
742
+ location: { field: "manifest" }
743
+ });
744
+ }
745
+ if (!isRecord(value) || value.version !== "ae-local-data-manifest/v1" || !isRecord(value.output) || typeof value.output.valid_file !== "string" || basename2(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") {
746
+ throw new CliValidationError("The manifest is not ae-local-data-manifest/v1.", {
747
+ code: "LOCAL_DATA_MANIFEST_INVALID",
748
+ location: { field: "manifest" }
749
+ });
750
+ }
751
+ return value;
752
+ }
753
+ async function validateUeFile(path) {
754
+ let count = 0;
755
+ const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
756
+ for await (const line of lines) {
757
+ if (!line.trim()) continue;
758
+ count += 1;
759
+ let value;
760
+ try {
761
+ value = JSON.parse(line);
762
+ } catch {
763
+ throw invalidUeFile(count);
764
+ }
765
+ if (!isRecord(value) || !isUeRecordType(value["#type"])) {
766
+ throw invalidUeFile(count);
767
+ }
768
+ }
769
+ return count;
770
+ }
771
+ var UE_RECORD_TYPES = /* @__PURE__ */ new Set([
772
+ "track",
773
+ "user_set",
774
+ "user_setOnce",
775
+ "user_add",
776
+ "user_unset",
777
+ "user_del",
778
+ "user_append",
779
+ "user_uniq_append"
780
+ ]);
781
+ function isUeRecordType(value) {
782
+ return typeof value === "string" && UE_RECORD_TYPES.has(value);
783
+ }
784
+ function decorateBatchError(error, completedRecords, completedBatches, batchStart, batchSize) {
785
+ if (!(error instanceof LocalDataUploadError)) return error;
786
+ const deliveryUnknown = error.meta?.delivery_state === "unknown";
787
+ return new LocalDataUploadError(error.message, {
788
+ code: error.code,
789
+ httpStatus: error.httpStatus,
790
+ hint: error.hint,
791
+ meta: {
792
+ ...error.meta,
793
+ completed_records: completedRecords,
794
+ completed_batches: completedBatches,
795
+ ...deliveryUnknown ? {
796
+ uncertain_batch_start: batchStart,
797
+ uncertain_batch_size: batchSize,
798
+ resume_from_after_verification: batchStart
799
+ } : {
800
+ failed_batch_start: batchStart,
801
+ failed_batch_size: batchSize
802
+ }
803
+ },
804
+ cause: error
805
+ });
806
+ }
807
+ async function* readUeBatches(path, offset, batchSize) {
808
+ let index = 0;
809
+ let batch = [];
810
+ const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
811
+ for await (const line of lines) {
812
+ if (!line.trim()) continue;
813
+ if (index++ < offset) continue;
814
+ batch.push(line);
815
+ if (batch.length >= batchSize) {
816
+ yield batch;
817
+ batch = [];
818
+ }
819
+ }
820
+ if (batch.length > 0) yield batch;
821
+ }
822
+ function invalidUeFile(record) {
823
+ return new CliValidationError("The UE JSONL file contains an invalid record.", {
824
+ code: "LOCAL_DATA_UE_FILE_INVALID",
825
+ location: { record }
826
+ });
827
+ }
828
+ function maskEndpoint(endpoint) {
829
+ const url = new URL(endpoint);
830
+ const parts = url.hostname.split(".");
831
+ const first = parts[0];
832
+ parts[0] = first.length <= 2 ? "**" : `${first[0]}***${first.at(-1)}`;
833
+ return `${url.protocol}//${parts.join(".")}${url.port ? `:${url.port}` : ""}/sync_json`;
834
+ }
835
+ function maskAppid(appid) {
836
+ return appid.length <= 4 ? "****" : `${"*".repeat(Math.min(8, appid.length - 4))}${appid.slice(-4)}`;
837
+ }
838
+ function isRecord(value) {
839
+ return value !== null && typeof value === "object" && !Array.isArray(value);
840
+ }
841
+
842
+ // src/commands/data-integration/handoff.ts
843
+ import { createHash } from "crypto";
844
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
845
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
846
+ import { tmpdir } from "os";
847
+
848
+ // src/commands/data-integration/archive.ts
849
+ var import_archiver = __toESM(require_archiver(), 1);
850
+ import { createWriteStream, readdirSync, statSync as statSync2 } from "fs";
851
+ import { join, relative, sep } from "path";
852
+ async function zipPackage(dir, zipPath) {
853
+ await new Promise((resolvePromise, rejectPromise) => {
854
+ const output = createWriteStream(zipPath, { mode: 384 });
855
+ const zip = (0, import_archiver.default)("zip", { zlib: { level: 9 } });
856
+ output.on("close", resolvePromise);
857
+ output.on("error", rejectPromise);
858
+ zip.on("error", rejectPromise);
859
+ zip.on("warning", (error) => {
860
+ if (error.code !== "ENOENT") rejectPromise(error);
861
+ });
862
+ zip.pipe(output);
863
+ const walk = (current) => {
864
+ for (const name of readdirSync(current)) {
865
+ if (name === ".DS_Store") continue;
866
+ const full = join(current, name);
867
+ const stats = statSync2(full);
868
+ if (stats.isDirectory()) {
869
+ walk(full);
870
+ } else {
871
+ const rel = relative(dir, full).split(sep).join("/");
872
+ zip.file(full, { name: rel, mode: stats.mode & 511 });
873
+ }
874
+ }
875
+ };
876
+ walk(dir);
877
+ void zip.finalize();
878
+ });
879
+ }
880
+
881
+ // src/commands/data-integration/relay.ts
882
+ var PIPELINE_VERSION = "ae-data-integration-pipeline/v1";
883
+ var SHAPE_VERSION = "ae-data-integration-shape/v1";
884
+ var DEFAULT_BATCH_SIZE2 = 500;
885
+ var ENV_FILE = ".local/target.env";
886
+ function buildPipelineDescriptor(entries, target = {}) {
887
+ const first = entries[0];
888
+ return {
889
+ version: PIPELINE_VERSION,
890
+ created_at: first?.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
891
+ source: { type: "local_file", params: { format: first?.format ?? "csv" } },
892
+ transform: { type: MAPPING_VERSION, refs: entries.map((entry) => entry.mapping_file) },
893
+ sink: {
894
+ type: "restful_sync_json",
895
+ params: {
896
+ batch_size: DEFAULT_BATCH_SIZE2,
897
+ env_file: ENV_FILE,
898
+ ...target.pushurl ? { pushurl: target.pushurl } : {},
899
+ ...target.project_id ? { project_id: target.project_id } : {}
900
+ }
901
+ }
902
+ };
903
+ }
904
+ function buildShapeBaseline(items) {
905
+ return {
906
+ version: SHAPE_VERSION,
907
+ entries: items.map(({ mapping, fingerprint }) => ({
908
+ fingerprint,
909
+ mode: mapping.mode,
910
+ data_set: mapping.source.data_set,
911
+ format: mapping.source.format,
912
+ columns: sourceColumns(mapping)
913
+ }))
914
+ };
915
+ }
916
+ function sh(...lines) {
917
+ return `${lines.join("\n")}
918
+ `;
919
+ }
920
+ function generateBinScripts() {
921
+ return [
922
+ { relPath: "bin/run.sh", content: runSh(), mode: 448 },
923
+ { relPath: "bin/upload.sh", content: uploadSh(), mode: 448 },
924
+ { relPath: "bin/bind_mapping.py", content: bindMappingPy(), mode: 448 },
925
+ { relPath: "bin/summarize.py", content: summarizePy(), mode: 448 },
926
+ { relPath: "bin/plan_check.py", content: planCheckPy(), mode: 448 },
927
+ { relPath: "bin/verify.py", content: verifyPy(), mode: 448 },
928
+ { relPath: "bin/resolve_appid.py", content: resolveAppidPy(), mode: 448 }
929
+ ];
930
+ }
931
+ function runSh() {
932
+ return sh(
933
+ "#!/usr/bin/env bash",
934
+ "# Generic pipeline executor: source -> transform -> plan. Never uploads (see upload.sh).",
935
+ "# Reads pipeline.json and dispatches each stage by its `type` to ae-cli subcommands.",
936
+ "set -euo pipefail",
937
+ 'SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"',
938
+ 'PKG_ROOT="$(dirname "$SCRIPT_DIR")"',
939
+ 'cd "$PKG_ROOT"',
940
+ "",
941
+ `SRC_TYPE="$(python3 -c 'import json; print(json.load(open("pipeline.json"))["source"]["type"])')"`,
942
+ 'case "$SRC_TYPE" in',
943
+ " local_file) ;;",
944
+ " *)",
945
+ ' echo "unsupported source type: $SRC_TYPE" >&2',
946
+ ' echo "re-run the full ae-data-integration pipeline (or upgrade ae-cli) for this source." >&2',
947
+ " exit 64",
948
+ " ;;",
949
+ "esac",
950
+ "",
951
+ 'INPUT="${1:-}"',
952
+ 'if [ -z "$INPUT" ]; then',
953
+ " shopt -s nullglob; FILES=(inbox/*); shopt -u nullglob",
954
+ ' if [ "${#FILES[@]}" -ne 1 ]; then',
955
+ ' echo "usage: bin/run.sh <input-file>" >&2',
956
+ ' echo " (or put exactly one file in inbox/)" >&2',
957
+ " exit 2",
958
+ " fi",
959
+ ' INPUT="${FILES[0]}"',
960
+ "fi",
961
+ "",
962
+ 'RUN_DIR="runs/$(date +%Y%m%d-%H%M%S)"',
963
+ 'mkdir -p "$RUN_DIR"',
964
+ 'echo "run: $RUN_DIR"',
965
+ "",
966
+ 'python3 bin/bind_mapping.py "$INPUT" "$RUN_DIR"',
967
+ "",
968
+ "while IFS= read -r ref; do",
969
+ ' ref_dir="$(dirname "$ref")"',
970
+ ' echo "convert: $ref_dir"',
971
+ " ae-cli data-integration convert \\",
972
+ ' --input-file "$INPUT" \\',
973
+ ' --mapping "$RUN_DIR/bound/$ref_dir/mapping.json" \\',
974
+ ' --output-dir "$RUN_DIR/$ref_dir" || exit $?',
975
+ `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`,
976
+ "",
977
+ 'python3 bin/summarize.py "$RUN_DIR"',
978
+ 'python3 bin/plan_check.py "$RUN_DIR"',
979
+ "",
980
+ "# Salvage hint: quarantined rows are never silently dropped. Re-process only",
981
+ "# them against the fixed mapping instead of re-uploading the whole file.",
982
+ "while IFS= read -r ref; do",
983
+ ' ref_dir="$(dirname "$ref")"',
984
+ ' inv="$RUN_DIR/$ref_dir/invalid.rows.jsonl"',
985
+ ' if [ -s "$inv" ]; then',
986
+ ' echo "note: $inv has quarantined rows \u2014 salvage them with:"',
987
+ ' 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""',
988
+ " fi",
989
+ `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`,
990
+ "",
991
+ 'echo "done. review the summary and plan check, then run: bin/upload.sh $RUN_DIR"'
992
+ );
993
+ }
994
+ function uploadSh() {
995
+ return sh(
996
+ "#!/usr/bin/env bash",
997
+ "# Sink executor. Dry-run by default; --confirm actually uploads.",
998
+ "# Resolves the recorded target from pipeline.json (pushurl + project_id), derives",
999
+ "# the APPID via `ae-cli project info get` (bin/resolve_appid.py), and falls back to",
1000
+ "# .local/target.env for explicit APPID / endpoint / project-id overrides.",
1001
+ "set -euo pipefail",
1002
+ 'SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"',
1003
+ 'PKG_ROOT="$(dirname "$SCRIPT_DIR")"',
1004
+ 'cd "$PKG_ROOT"',
1005
+ "",
1006
+ `SINK_TYPE="$(python3 -c 'import json; print(json.load(open("pipeline.json"))["sink"]["type"])')"`,
1007
+ 'case "$SINK_TYPE" in',
1008
+ " restful_sync_json) ;;",
1009
+ " *)",
1010
+ ' echo "unsupported sink type: $SINK_TYPE" >&2',
1011
+ ' echo "re-run the full ae-data-integration pipeline (or upgrade ae-cli) for this sink." >&2',
1012
+ " exit 64",
1013
+ " ;;",
1014
+ "esac",
1015
+ "",
1016
+ `SINK_PARAMS="$(python3 -c 'import json; print(json.dumps(json.load(open("pipeline.json"))["sink"]["params"]))')"`,
1017
+ `BATCH_SIZE="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("batch_size", 500))' "$SINK_PARAMS")"`,
1018
+ `ENV_FILE="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("env_file", ".local/target.env"))' "$SINK_PARAMS")"`,
1019
+ `PUSHURL="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("pushurl") or "")' "$SINK_PARAMS")"`,
1020
+ `PROJECT_ID="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]).get("project_id") or "")' "$SINK_PARAMS")"`,
1021
+ "",
1022
+ "CONFIRM=0",
1023
+ 'RUN_DIR=""',
1024
+ 'for arg in "$@"; do',
1025
+ ' case "$arg" in',
1026
+ " --confirm) CONFIRM=1 ;;",
1027
+ ' -*) echo "unknown flag: $arg" >&2; exit 2 ;;',
1028
+ ' *) RUN_DIR="$arg" ;;',
1029
+ " esac",
1030
+ "done",
1031
+ "",
1032
+ 'if [ -z "$RUN_DIR" ]; then',
1033
+ ' echo "usage: bin/upload.sh [--confirm] <runs/<run-id>>" >&2',
1034
+ " exit 2",
1035
+ "fi",
1036
+ "",
1037
+ "# .local/target.env is optional: the package may record the target itself.",
1038
+ "# Env values still win as explicit overrides (the documented fallback).",
1039
+ 'if [ -f "$ENV_FILE" ]; then set -a; . "$ENV_FILE"; set +a; fi',
1040
+ '[ -z "$PROJECT_ID" ] && PROJECT_ID="${AE_PROJECT_ID:-}"',
1041
+ "",
1042
+ "# Endpoint: the recorded pushurl (a receiver base URL; append /sync_json), else AE_ENDPOINT.",
1043
+ 'if [ -n "$PUSHURL" ]; then',
1044
+ ' case "$PUSHURL" in',
1045
+ ' */sync_json) ENDPOINT="$PUSHURL" ;;',
1046
+ ' *) ENDPOINT="${PUSHURL%/}/sync_json" ;;',
1047
+ " esac",
1048
+ "else",
1049
+ ' : "${AE_ENDPOINT:?set AE_ENDPOINT in .local/target.env (or record pushurl at handoff)}"',
1050
+ ' ENDPOINT="$AE_ENDPOINT"',
1051
+ "fi",
1052
+ "",
1053
+ "# APPID: explicit env wins, else derive from the recorded project via project info get.",
1054
+ 'APPID="${AE_APPID:-}"',
1055
+ 'if [ -z "$APPID" ] && [ -n "$PROJECT_ID" ]; then',
1056
+ ' APPID="$(python3 bin/resolve_appid.py "$PROJECT_ID")"',
1057
+ "fi",
1058
+ ': "${APPID:?set AE_APPID in .local/target.env (or record project_id at handoff)}"',
1059
+ "",
1060
+ "# Mask the APPID in anything this script prints \u2014 it must never land in logs.",
1061
+ "mask() {",
1062
+ ' local a="$1"',
1063
+ ' if [ "${#a}" -le 4 ]; then printf "%s" "****"; return; fi',
1064
+ ' printf "%s%s" "$(printf "%*s" "$(( ${#a} - 4 ))" "" | tr " " "*")" "${a: -4}"',
1065
+ "}",
1066
+ "display_args() {",
1067
+ ' local args=("$@") out=() i',
1068
+ " for ((i=0; i<${#args[@]}; i++)); do",
1069
+ ' if [ "${args[$i]}" = "--appid" ] && [ -n "${args[$((i+1))]:-}" ]; then',
1070
+ ' out+=("--appid" "$(mask "${args[$((i+1))]}")")',
1071
+ " i=$((i+1))",
1072
+ " else",
1073
+ ' out+=("${args[$i]}")',
1074
+ " fi",
1075
+ " done",
1076
+ ' printf "%s\\n" "${out[*]}"',
1077
+ "}",
1078
+ "",
1079
+ 'echo "target: project_id=${PROJECT_ID:-<unset>}"',
1080
+ 'echo " endpoint=$ENDPOINT"',
1081
+ 'echo " appid=$(mask "$APPID")"',
1082
+ 'if [ "$CONFIRM" -eq 0 ]; then',
1083
+ ' echo "dry-run \u2014 re-run with --confirm to upload to this address and project."',
1084
+ "else",
1085
+ ' echo "confirmed: uploading to the address and project shown above."',
1086
+ "fi",
1087
+ "",
1088
+ 'FLAGS=(--endpoint "$ENDPOINT" --appid "$APPID" --batch-size "$BATCH_SIZE")',
1089
+ 'if [ "$CONFIRM" -eq 0 ]; then FLAGS+=(--dry-run); fi',
1090
+ "",
1091
+ "while IFS= read -r ref; do",
1092
+ ' ref_dir="$(dirname "$ref")"',
1093
+ ' ue="$RUN_DIR/$ref_dir/valid.ue.jsonl"',
1094
+ ' manifest="$RUN_DIR/$ref_dir/manifest.json"',
1095
+ ' if [ ! -f "$ue" ]; then',
1096
+ ' echo "missing $ue (run bin/run.sh first)" >&2',
1097
+ " exit 2",
1098
+ " fi",
1099
+ ` status="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["status"])' "$manifest")"`,
1100
+ ' args=("${FLAGS[@]}" --ue-file "$ue" --manifest "$manifest")',
1101
+ ' if [ "$status" = "blocked" ]; then',
1102
+ ' echo "manifest $manifest is blocked (rows were quarantined)."',
1103
+ ' echo "Uploading passes only the valid subset (--allow-clean-subset); quarantined rows stay in invalid.rows.jsonl."',
1104
+ ' if [ "$CONFIRM" -eq 1 ]; then args+=(--allow-clean-subset); else echo " (dry-run) re-run with --confirm to accept the clean subset."; fi',
1105
+ " fi",
1106
+ ' echo "> ae-cli data-integration upload $(display_args "${args[@]}")"',
1107
+ ' ae-cli data-integration upload "${args[@]}" || exit $?',
1108
+ `done < <(python3 -c 'import json,sys; print("\\n".join(json.load(open("pipeline.json"))["transform"]["refs"]))')`
1109
+ );
1110
+ }
1111
+ function bindMappingPy() {
1112
+ return `#!/usr/bin/env python3
1113
+ """Source stage: rebind the frozen mappings to a new same-shape file.
1114
+
1115
+ Runs \`ae-cli data-integration inspect\` once, then for every mapping the
1116
+ pipeline references (pipeline.json's transform.refs) re-binds the frozen
1117
+ mapping's \`source.sha256\` and \`source.data_set\` to the new file (identity
1118
+ fields only \u2014 business logic is untouched), after checking the column set
1119
+ against shape.json. Historical index entries the pipeline does not run are
1120
+ left alone \u2014 the index accumulates across handoffs in the same directory.
1121
+
1122
+ Usage: bin/bind_mapping.py <input-file> <run-dir>
1123
+ """
1124
+ import json
1125
+ import os
1126
+ import subprocess
1127
+ import sys
1128
+
1129
+
1130
+ def fail(message):
1131
+ print(f"bind_mapping: {message}", file=sys.stderr)
1132
+ sys.exit(1)
1133
+
1134
+
1135
+ def pkg_root():
1136
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1137
+
1138
+
1139
+ def load_json(path):
1140
+ with open(path, "r", encoding="utf-8") as f:
1141
+ return json.load(f)
1142
+
1143
+
1144
+ def write_json(path, value):
1145
+ os.makedirs(os.path.dirname(path), exist_ok=True)
1146
+ with open(path, "w", encoding="utf-8") as f:
1147
+ json.dump(value, f, ensure_ascii=False, indent=2)
1148
+ f.write("\\n")
1149
+
1150
+
1151
+ def dataset_key(dataset):
1152
+ return dataset.get("id") or dataset.get("label") or ""
1153
+
1154
+
1155
+ def main():
1156
+ if len(sys.argv) != 3:
1157
+ fail("usage: bind_mapping.py <input-file> <run-dir>")
1158
+ input_file, run_dir = sys.argv[1], sys.argv[2]
1159
+ root = pkg_root()
1160
+
1161
+ pipeline = load_json(os.path.join(root, "pipeline.json"))
1162
+ if pipeline["source"]["type"] != "local_file":
1163
+ fail(f"unsupported source type: {pipeline['source']['type']}")
1164
+
1165
+ index = load_json(os.path.join(root, "index.json"))
1166
+ shape = load_json(os.path.join(root, "shape.json"))
1167
+ shape_by_fp = {entry["fingerprint"]: entry for entry in shape["entries"]}
1168
+ index_by_ref = {entry["mapping_file"]: entry for entry in index["entries"]}
1169
+
1170
+ inspect = run_inspect(input_file)
1171
+ datasets = extract_datasets(inspect)
1172
+ headers_by_dataset = extract_headers(inspect, datasets)
1173
+ sha = (inspect.get("source") or {}).get("sha256")
1174
+
1175
+ # Rebind only the mappings this pipeline runs (transform.refs). The index
1176
+ # accumulates entries across handoffs in the same directory; earlier entries
1177
+ # may have no shape baseline here and are never converted by run.sh, so
1178
+ # walking the whole index would fail on them.
1179
+ for ref in pipeline["transform"]["refs"]:
1180
+ entry = index_by_ref.get(ref)
1181
+ if entry is None:
1182
+ fail(f"index entry missing for {ref}; re-run the full pipeline")
1183
+ fingerprint = entry["fingerprint"]
1184
+ baseline = shape_by_fp.get(fingerprint)
1185
+ if baseline is None:
1186
+ fail(f"shape baseline missing for {fingerprint}; re-run the full pipeline")
1187
+ frozen = load_json(os.path.join(root, ref))
1188
+ data_set_id = match_dataset(frozen, baseline, datasets, headers_by_dataset)
1189
+ validate_headers(data_set_id, baseline, headers_by_dataset)
1190
+ frozen["source"]["sha256"] = sha
1191
+ frozen["source"]["data_set"] = data_set_id
1192
+ out = os.path.join(root, run_dir, "bound", os.path.dirname(ref), "mapping.json")
1193
+ write_json(out, frozen)
1194
+ print(f"rebound {os.path.dirname(ref)} -> data_set {data_set_id!r}")
1195
+ print("shape check passed")
1196
+
1197
+
1198
+ def run_inspect(input_file):
1199
+ proc = subprocess.run(
1200
+ ["ae-cli", "data-integration", "inspect", "--input-file", input_file],
1201
+ capture_output=True, text=True,
1202
+ )
1203
+ if proc.returncode != 0:
1204
+ fail(f"inspect failed: {proc.stderr.strip()}")
1205
+ try:
1206
+ parsed = json.loads(proc.stdout)
1207
+ except json.JSONDecodeError:
1208
+ fail("inspect returned non-JSON output")
1209
+ # ae-cli wraps every command result in { ok, data, error }; unwrap it.
1210
+ data = parsed.get("data") if isinstance(parsed, dict) else None
1211
+ if not isinstance(data, dict):
1212
+ fail("inspect returned no data payload")
1213
+ return data
1214
+
1215
+
1216
+ def extract_datasets(inspect):
1217
+ if inspect.get("selection_required"):
1218
+ return inspect.get("data_sets") or []
1219
+ data_set = inspect.get("data_set")
1220
+ return [data_set] if data_set else []
1221
+
1222
+
1223
+ def extract_headers(inspect, datasets):
1224
+ result = {}
1225
+ details = inspect.get("header_details")
1226
+ if details:
1227
+ for dataset in datasets:
1228
+ names = (dataset.get("label"), dataset.get("id"), dataset.get("selector"))
1229
+ for sheet in details:
1230
+ if sheet.get("name") in names:
1231
+ result[dataset_key(dataset)] = sheet.get("headers") or []
1232
+ break
1233
+ return result
1234
+ columns = inspect.get("columns")
1235
+ if columns and datasets:
1236
+ result[dataset_key(datasets[0])] = [column["name"] for column in columns]
1237
+ return result
1238
+
1239
+
1240
+ def match_dataset(frozen, baseline, datasets, headers_by_dataset):
1241
+ if not datasets:
1242
+ fail("inspect reported no data sets")
1243
+ wanted = frozen["source"]["data_set"]
1244
+ for dataset in datasets:
1245
+ if dataset.get("id") == wanted:
1246
+ return dataset.get("id")
1247
+ for dataset in datasets:
1248
+ if dataset.get("label") == wanted:
1249
+ return dataset.get("id")
1250
+ baseline_cols = set(baseline.get("columns") or [])
1251
+ if baseline_cols:
1252
+ for dataset in datasets:
1253
+ headers = headers_by_dataset.get(dataset_key(dataset))
1254
+ if headers and set(headers) == baseline_cols:
1255
+ return dataset.get("id")
1256
+ if len(datasets) == 1:
1257
+ return datasets[0].get("id")
1258
+ fail(f"cannot rebind data_set {wanted!r}: no exact or header match; re-run the full pipeline")
1259
+
1260
+
1261
+ def validate_headers(data_set_id, baseline, headers_by_dataset):
1262
+ baseline_cols = set(baseline.get("columns") or [])
1263
+ if not baseline_cols:
1264
+ return
1265
+ headers = headers_by_dataset.get(data_set_id)
1266
+ if headers is None:
1267
+ return
1268
+ if set(headers) != baseline_cols:
1269
+ missing = sorted(baseline_cols - set(headers))
1270
+ extra = sorted(set(headers) - baseline_cols)
1271
+ fail(
1272
+ f"shape mismatch for {data_set_id!r}: missing={missing} extra={extra} \u2014 "
1273
+ "re-run the full pipeline; do not edit the frozen mapping"
1274
+ )
1275
+
1276
+
1277
+ if __name__ == "__main__":
1278
+ main()
1279
+ `;
1280
+ }
1281
+ function summarizePy() {
1282
+ return `#!/usr/bin/env python3
1283
+ """Transform stage summary: print valid/quarantined counts per data set."""
1284
+ import json
1285
+ import os
1286
+ import sys
1287
+
1288
+
1289
+ def pkg_root():
1290
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1291
+
1292
+
1293
+ def main():
1294
+ if len(sys.argv) != 2:
1295
+ print("usage: summarize.py <run-dir>", file=sys.stderr)
1296
+ sys.exit(2)
1297
+ run_dir = sys.argv[1]
1298
+ root = pkg_root()
1299
+ with open(os.path.join(root, "pipeline.json"), "r", encoding="utf-8") as f:
1300
+ pipeline = json.load(f)
1301
+ total_valid = 0
1302
+ total_invalid = 0
1303
+ for ref in pipeline["transform"]["refs"]:
1304
+ ref_dir = os.path.dirname(ref)
1305
+ manifest_path = os.path.join(root, run_dir, ref_dir, "manifest.json")
1306
+ if not os.path.exists(manifest_path):
1307
+ continue
1308
+ with open(manifest_path, "r", encoding="utf-8") as f:
1309
+ manifest = json.load(f)
1310
+ output = manifest["output"]
1311
+ total_valid += output["valid_records"]
1312
+ total_invalid += output["invalid_records"]
1313
+ print(f"{ref_dir}: {output['valid_records']} valid / {output['invalid_records']} quarantined")
1314
+ for reason in manifest.get("blocked_reasons") or []:
1315
+ print(f" - {reason}")
1316
+ print(f"total: {total_valid} valid / {total_invalid} quarantined")
1317
+
1318
+
1319
+ if __name__ == "__main__":
1320
+ main()
1321
+ `;
1322
+ }
1323
+ function planCheckPy() {
1324
+ return `#!/usr/bin/env python3
1325
+ """Plan gate: every event and property produced must already exist in the frozen tracking plan."""
1326
+ import json
1327
+ import os
1328
+ import sys
1329
+
1330
+
1331
+ def pkg_root():
1332
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1333
+
1334
+
1335
+ def load_json(path):
1336
+ with open(path, "r", encoding="utf-8") as f:
1337
+ return json.load(f)
1338
+
1339
+
1340
+ def main():
1341
+ if len(sys.argv) != 2:
1342
+ print("usage: plan_check.py <run-dir>", file=sys.stderr)
1343
+ sys.exit(2)
1344
+ run_dir = sys.argv[1]
1345
+ root = pkg_root()
1346
+ pipeline = load_json(os.path.join(root, "pipeline.json"))
1347
+ new_events = []
1348
+ new_properties = []
1349
+ missing_plans = []
1350
+ for ref in pipeline["transform"]["refs"]:
1351
+ ref_dir = os.path.dirname(ref)
1352
+ plan_path = os.path.join(root, ref_dir, "plan.json")
1353
+ ue_path = os.path.join(root, run_dir, ref_dir, "valid.ue.jsonl")
1354
+ if not os.path.exists(plan_path):
1355
+ missing_plans.append(ref_dir)
1356
+ continue
1357
+ plan = load_json(plan_path)
1358
+ plan_events = {event["event_name"] for event in plan.get("events", [])}
1359
+ plan_properties = {prop["name"] for prop in plan.get("event_properties", [])}
1360
+ plan_properties |= {prop["name"] for prop in plan.get("common_event_properties", [])}
1361
+ plan_properties |= {prop["name"] for prop in plan.get("user_properties", [])}
1362
+ produced_events = set()
1363
+ produced_properties = set()
1364
+ if os.path.exists(ue_path):
1365
+ with open(ue_path, "r", encoding="utf-8") as f:
1366
+ for line in f:
1367
+ line = line.strip()
1368
+ if not line:
1369
+ continue
1370
+ record = json.loads(line)
1371
+ if record.get("#event_name"):
1372
+ produced_events.add(record["#event_name"])
1373
+ props = record.get("properties")
1374
+ if isinstance(props, dict):
1375
+ for key in props:
1376
+ if key.startswith("#"):
1377
+ continue
1378
+ produced_properties.add(key)
1379
+ new_events.extend(sorted(produced_events - plan_events))
1380
+ new_properties.extend(sorted(produced_properties - plan_properties))
1381
+ if missing_plans:
1382
+ print("no plan.json in package for: " + ", ".join(missing_plans), file=sys.stderr)
1383
+ print("run the Tracking plan step first \u2014 the plan gate cannot be skipped", file=sys.stderr)
1384
+ sys.exit(3)
1385
+ if new_events:
1386
+ print("new events not in the plan: " + ", ".join(new_events), file=sys.stderr)
1387
+ sys.exit(3)
1388
+ if new_properties:
1389
+ print("new properties not in the plan: " + ", ".join(new_properties), file=sys.stderr)
1390
+ sys.exit(3)
1391
+ print("plan coverage ok")
1392
+
1393
+
1394
+ if __name__ == "__main__":
1395
+ main()
1396
+ `;
1397
+ }
1398
+ function verifyPy() {
1399
+ return `#!/usr/bin/env python3
1400
+ """Persistence consistency check: submit-window counts vs the platform summary.
1401
+
1402
+ A soft check, not a hard gate. It computes what this run submitted from the local
1403
+ UE output (knowable), snapshots \`ae-cli tracking ingest summary\` over the submit
1404
+ window before and after upload, and prints both next to the expected counts. It
1405
+ does NOT parse the summary payload into per-event numbers: the capability's data
1406
+ shape is server-defined and not a stable CLI contract, and a shared project cannot
1407
+ attribute the window delta to this import alone. For a hard per-event SQL judge,
1408
+ overlay a project custom layer (see custom-layer.md in the ae-data-integration skill).
1409
+
1410
+ verify.py <run-dir> --baseline snapshot the summary before upload
1411
+ verify.py <run-dir> --check snapshot again and diff against the baseline
1412
+ """
1413
+ import json
1414
+ import os
1415
+ import subprocess
1416
+ import sys
1417
+
1418
+
1419
+ def pkg_root():
1420
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1421
+
1422
+
1423
+ def load_json(path):
1424
+ with open(path, "r", encoding="utf-8") as f:
1425
+ return json.load(f)
1426
+
1427
+
1428
+ def visit_window(record, lo, hi):
1429
+ raw = record.get("#time")
1430
+ if not isinstance(raw, str) or len(raw) < 19:
1431
+ return lo, hi
1432
+ stamp = raw[:19] # YYYY-MM-DD HH:mm:ss
1433
+ if lo is None or stamp < lo:
1434
+ lo = stamp
1435
+ if hi is None or stamp > hi:
1436
+ hi = stamp
1437
+ return lo, hi
1438
+
1439
+
1440
+ def main():
1441
+ if len(sys.argv) < 2:
1442
+ print("usage: verify.py <run-dir> [--baseline|--check]", file=sys.stderr)
1443
+ sys.exit(2)
1444
+ run_dir = sys.argv[1]
1445
+ mode = sys.argv[2] if len(sys.argv) > 2 else "--check"
1446
+ if mode not in ("--baseline", "--check"):
1447
+ print("usage: verify.py <run-dir> [--baseline|--check]", file=sys.stderr)
1448
+ sys.exit(2)
1449
+ root = pkg_root()
1450
+ pipeline = load_json(os.path.join(root, "pipeline.json"))
1451
+ project_id = pipeline["sink"]["params"].get("project_id") or os.environ.get("AE_PROJECT_ID") or "1"
1452
+
1453
+ expected_events = {}
1454
+ expected_users = 0
1455
+ lo = hi = None
1456
+ for ref in pipeline["transform"]["refs"]:
1457
+ ue = os.path.join(root, run_dir, os.path.dirname(ref), "valid.ue.jsonl")
1458
+ if not os.path.exists(ue):
1459
+ continue
1460
+ with open(ue, "r", encoding="utf-8") as f:
1461
+ for line in f:
1462
+ line = line.strip()
1463
+ if not line:
1464
+ continue
1465
+ record = json.loads(line)
1466
+ if record.get("#type") == "track" and record.get("#event_name"):
1467
+ expected_events[record["#event_name"]] = expected_events.get(record["#event_name"], 0) + 1
1468
+ else:
1469
+ expected_users += 1
1470
+ lo, hi = visit_window(record, lo, hi)
1471
+
1472
+ if lo is None:
1473
+ print("verify: no UE records found in " + run_dir, file=sys.stderr)
1474
+ sys.exit(2)
1475
+
1476
+ def run_summary():
1477
+ proc = subprocess.run(
1478
+ ["ae-cli", "tracking", "ingest", "summary",
1479
+ "-p", str(project_id), "--start-time", lo, "--end-time", hi],
1480
+ capture_output=True, text=True,
1481
+ )
1482
+ if proc.returncode != 0:
1483
+ return {"error": (proc.stderr or proc.stdout).strip()[:500]}
1484
+ try:
1485
+ return json.loads(proc.stdout)
1486
+ except json.JSONDecodeError:
1487
+ return {"raw": proc.stdout.strip()[:500]}
1488
+
1489
+ print("window " + lo + " .. " + hi + " project_id=" + str(project_id))
1490
+ print("expected (this run):")
1491
+ for event, count in sorted(expected_events.items()):
1492
+ print(" {:<20}{:>10,}".format(event, count))
1493
+ print(" {:<20}{:>10,}".format("<user rows>", expected_users))
1494
+ print()
1495
+
1496
+ baseline_path = os.path.join(root, run_dir, "baseline.json")
1497
+ if mode == "--baseline":
1498
+ payload = run_summary()
1499
+ with open(baseline_path, "w", encoding="utf-8") as f:
1500
+ json.dump(payload, f, ensure_ascii=False, indent=2)
1501
+ print("baseline recorded: " + baseline_path)
1502
+ print("platform summary (before):")
1503
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1504
+ sys.exit(0)
1505
+
1506
+ if not os.path.exists(baseline_path):
1507
+ print("no baseline.json \u2014 run \`verify.py <run-dir> --baseline\` before upload.", file=sys.stderr)
1508
+ print("falling back to a single after-upload summary:", file=sys.stderr)
1509
+ print(json.dumps(run_summary(), ensure_ascii=False, indent=2))
1510
+ sys.exit(1)
1511
+
1512
+ with open(baseline_path, "r", encoding="utf-8") as f:
1513
+ baseline = json.load(f)
1514
+ after = run_summary()
1515
+ print("platform summary before vs after:")
1516
+ print(json.dumps(baseline, ensure_ascii=False, indent=2))
1517
+ print("---")
1518
+ print(json.dumps(after, ensure_ascii=False, indent=2))
1519
+ print()
1520
+ print("summary changed: " + ("yes" if baseline != after else "no"))
1521
+ print()
1522
+ print("Boundary: the summary payload is server-defined and may under-report even")
1523
+ print("landed data; this check surfaces it for comparison, it does not auto-verify")
1524
+ print("per-event counts, and a shared project's window delta is not attributed to")
1525
+ print("this import. Cross-check with:")
1526
+ print(" ae-cli tracking live-data list -p " + str(project_id))
1527
+ print("For a hard SQL judge, add a project custom layer (custom-layer.md).")
1528
+ sys.exit(0)
1529
+
1530
+
1531
+ if __name__ == "__main__":
1532
+ main()
1533
+ `;
1534
+ }
1535
+ function resolveAppidPy() {
1536
+ return `#!/usr/bin/env python3
1537
+ """Derive the destination APPID from \`ae-cli project info get --project-id <id>\`.
1538
+
1539
+ \`project info get\` returns \`data.appid\` at the top level (verified against the
1540
+ AE demo host), so this helper reads that exact field and prints it to stdout. It
1541
+ prints nothing to stdout and reports the payload when the field is absent or not
1542
+ a non-empty string \u2014 the caller then falls back to AE_APPID.
1543
+
1544
+ Usage: bin/resolve_appid.py <project-id>
1545
+ """
1546
+ import json
1547
+ import subprocess
1548
+ import sys
1549
+
1550
+
1551
+ def main():
1552
+ if len(sys.argv) != 2:
1553
+ print("usage: resolve_appid.py <project-id>", file=sys.stderr)
1554
+ sys.exit(2)
1555
+ project_id = sys.argv[1]
1556
+ proc = subprocess.run(
1557
+ ["ae-cli", "project", "info", "get", "--project-id", project_id],
1558
+ capture_output=True, text=True,
1559
+ )
1560
+ if proc.returncode != 0:
1561
+ print("resolve_appid: project info get failed: " + (proc.stderr or proc.stdout).strip()[:300], file=sys.stderr)
1562
+ sys.exit(0)
1563
+ try:
1564
+ parsed = json.loads(proc.stdout)
1565
+ except json.JSONDecodeError:
1566
+ print("resolve_appid: project info get returned non-JSON output", file=sys.stderr)
1567
+ sys.exit(0)
1568
+ data = parsed.get("data") if isinstance(parsed, dict) else None
1569
+ appid = data.get("appid") if isinstance(data, dict) else None
1570
+ if not isinstance(appid, str) or not appid:
1571
+ print("resolve_appid: project info get returned no appid; set AE_APPID", file=sys.stderr)
1572
+ print(json.dumps(data, ensure_ascii=False, indent=2) if data is not None else "{}", file=sys.stderr)
1573
+ sys.exit(0)
1574
+ masked = appid if len(appid) <= 4 else ("*" * (len(appid) - 4)) + appid[-4:]
1575
+ print("resolve_appid: resolved APPID data.appid = " + masked, file=sys.stderr)
1576
+ print(appid)
1577
+
1578
+
1579
+ if __name__ == "__main__":
1580
+ main()
1581
+ `;
1582
+ }
1583
+ function generateReadme() {
1584
+ return `# AE Data Integration \u2014 handoff package
1585
+
1586
+ A frozen, reusable pipeline for importing a **same-shape** local file into AE,
1587
+ generated by \`ae-cli data-integration handoff\`. Source and Transform are frozen
1588
+ (the confirmed business logic); only the Tracking-plan and Sink gates still
1589
+ require human confirmation.
1590
+
1591
+ ## Quick start
1592
+
1593
+ \`\`\`bash
1594
+ cp <today's file> inbox/
1595
+ bin/run.sh # shape check -> convert -> plan check (no upload)
1596
+ bin/upload.sh runs/<latest> # dry-run
1597
+ bin/upload.sh runs/<latest> --confirm
1598
+ \`\`\`
1599
+
1600
+ Read [RUNBOOK.md](RUNBOOK.md) for the full flow, the four confirmation gates,
1601
+ and how to verify persistence.
1602
+
1603
+ ## Handing off to an agent
1604
+
1605
+ Import \`inbox/<today's file>\` through the ae-data-integration skill using this
1606
+ package. Tell it to follow RUNBOOK.md and stop for confirmation before uploading.
1607
+
1608
+ ## Package layout
1609
+
1610
+ | Path | Purpose |
1611
+ | --- | --- |
1612
+ | \`pipeline.json\` | Declarative source -> transform -> sink descriptor |
1613
+ | \`index.json\` | Structure-fingerprint index (reuse matching) |
1614
+ | \`shape.json\` | Column baseline used by the shape gate |
1615
+ | \`<fingerprint16>/\` | Frozen mapping + tracking plan + transform wrapper |
1616
+ | \`bin/run.sh\` | Source + Transform + Plan executor (never uploads) |
1617
+ | \`bin/upload.sh\` | Sink executor (dry-run by default; resolves the recorded target) |
1618
+ | \`bin/verify.py\` | Soft persistence check (submit window vs ingest summary) |
1619
+ | \`bin/resolve_appid.py\` | APPID derivation helper (project info get) |
1620
+ | \`.local/target.env\` | Upload target overrides (APPID / endpoint); only the template ships |
1621
+ | \`inbox/\` \`runs/\` | Daily input / per-run outputs |
1622
+
1623
+ ## Safety
1624
+
1625
+ The package records at most a destination \`pushurl\` and \`project_id\` (no APPID,
1626
+ tokens, or raw data values). \`bin/upload.sh\` always requires \`--confirm\` before
1627
+ sending, so the operator re-confirms the address and project on every reuse. Copy
1628
+ \`.local/target.env.example\` to \`.local/target.env\` for explicit overrides and
1629
+ never commit it.
1630
+ `;
1631
+ }
1632
+ function generateRunbook() {
1633
+ return `# RUNBOOK \u2014 same-shape file import
1634
+
1635
+ Run this when a file of the **same shape** arrives again (same sheets and
1636
+ headers as \`shape.json\`). If the headers changed, stop: re-run the full
1637
+ ae-data-integration pipeline instead of editing the frozen mapping.
1638
+
1639
+ ## Gates
1640
+
1641
+ 1. **Shape gate** \u2014 \`bin/run.sh\` rebinds the frozen mappings to the new file
1642
+ and compares the column set against \`shape.json\`. A mismatch fails fast on
1643
+ purpose: a different shape means the frozen business logic was never reviewed
1644
+ for it.
1645
+ 2. **Transform** \u2014 each frozen mapping runs through
1646
+ \`ae-cli data-integration convert\`. Quarantined rows land in
1647
+ \`invalid.rows.jsonl\`; they are never silently dropped.
1648
+ 3. **Tracking-plan gate** \u2014 \`bin/run.sh\` verifies every produced event and
1649
+ property already exists in the frozen \`plan.json\`. New events or properties
1650
+ make it exit with code 3: merge them into the project tracking plan first,
1651
+ then return here to upload.
1652
+ 4. **Sink gate** \u2014 \`bin/upload.sh\` is dry-run by default. Read
1653
+ \`record_count\`, \`batch_count\`, and \`manifest_status\` before adding
1654
+ \`--confirm\`. A \`blocked\` manifest means rows were quarantined;
1655
+ \`--confirm\` then uploads only the valid subset (\`--allow-clean-subset\`).
1656
+
1657
+ ## Destination
1658
+
1659
+ The package records the destination it was handed off for when \`handoff\` was run
1660
+ with \`--pushurl\` / \`--project-id\` (see \`pipeline.json\` \u2192 \`sink.params\`). Reuse
1661
+ defaults to that target, but \`bin/upload.sh\` never sends without \`--confirm\`, so
1662
+ the operator re-confirms the address and project every time.
1663
+
1664
+ Resolution order at upload time:
1665
+
1666
+ - endpoint: recorded \`pushurl\` (+ \`/sync_json\`), else \`AE_ENDPOINT\`.
1667
+ - APPID: \`AE_APPID\`, else derived via \`ae-cli project info get --project-id <id>\`
1668
+ (see \`bin/resolve_appid.py\`; it reads the \`data.appid\` field \u2014 set \`AE_APPID\`
1669
+ when that field is absent).
1670
+ - project id: recorded \`project_id\`, else \`AE_PROJECT_ID\`.
1671
+
1672
+ \`.local/target.env\` remains the explicit override for all three:
1673
+ \`AE_ENDPOINT\` (full receiver URL ending in \`/sync_json\`), \`AE_APPID\`, \`AE_PROJECT_ID\`.
1674
+
1675
+ ## Verify persistence
1676
+
1677
+ \`receiver_accepted\` is not persistence. About a minute after upload, confirm
1678
+ the data landed with ae-cli. The package ships a soft check that automates the
1679
+ before/after comparison:
1680
+
1681
+ \`\`\`bash
1682
+ bin/verify.py runs/<run-id> --baseline # before upload
1683
+ bin/upload.sh runs/<run-id> --confirm
1684
+ bin/verify.py runs/<run-id> --check # after upload
1685
+ \`\`\`
1686
+
1687
+ \`bin/verify.py\` prints the submit window and expected counts, then shows the
1688
+ \`tracking ingest summary\` payload before and after for comparison. It does not
1689
+ auto-verify per-event counts \u2014 the summary shape is server-defined, and a shared
1690
+ project's window delta is not attributed to this import. Cross-check with:
1691
+
1692
+ \`\`\`bash
1693
+ ae-cli tracking live-data list -p <AE_PROJECT_ID>
1694
+ ae-cli tracking ingest-error list -p <AE_PROJECT_ID> --data-name <name>
1695
+ \`\`\`
1696
+
1697
+ For a hard per-event SQL judge, overlay a project custom layer instead of editing
1698
+ this package (see \`custom-layer.md\` in the ae-data-integration skill).
1699
+
1700
+ ## Interrupted uploads
1701
+
1702
+ If a batch times out or loses the network, that batch's state is unknown. Stop:
1703
+ verify what actually landed, then follow the ae-data-integration skill to resume
1704
+ from the verified offset. Never re-run the whole upload blindly.
1705
+
1706
+ ## Files
1707
+
1708
+ See \`README.md\` for the package layout.
1709
+ `;
1710
+ }
1711
+ function generateEnvTemplate() {
1712
+ return [
1713
+ "# Upload target overrides. Copy this file to .local/target.env and fill only",
1714
+ "# what the package does not already record (pipeline.json sink.params).",
1715
+ "# AE_ENDPOINT: a full receiver URL ending in /sync_json (used when no pushurl is recorded).",
1716
+ "# AE_APPID: the destination project APPID (overrides the project info get derivation).",
1717
+ "# AE_PROJECT_ID: the destination project ID, used when no project_id is recorded.",
1718
+ "AE_ENDPOINT=",
1719
+ "AE_APPID=",
1720
+ "AE_PROJECT_ID=",
1721
+ ""
1722
+ ].join("\n");
1723
+ }
1724
+ function generateGitignore() {
1725
+ return ["inbox/", "runs/", ".local/target.env", ""].join("\n");
1726
+ }
1727
+
1728
+ // src/commands/data-integration/handoff.ts
1729
+ var HANDOFF_INDEX_VERSION = "ae-data-integration-index/v1";
1730
+ var HANDOFF_DIR_LEN = 16;
1731
+ function structureFingerprint(mapping) {
1732
+ const canonical = {
1733
+ mode: mapping.mode,
1734
+ format: mapping.source.format,
1735
+ columns: sourceColumns(mapping)
1736
+ };
1737
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
1738
+ }
1739
+ function upsertIndexEntry(index, entry) {
1740
+ const entries = index.entries.filter((item) => item.fingerprint !== entry.fingerprint);
1741
+ return { version: index.version, entries: [...entries, entry] };
1742
+ }
1743
+ function buildHandoffPackage(outDir, mapping, planFile) {
1744
+ const fingerprint = structureFingerprint(mapping);
1745
+ const dirName = fingerprint.slice(0, HANDOFF_DIR_LEN);
1746
+ const handoffDir = join2(outDir, dirName);
1747
+ const indexPath = join2(outDir, "index.json");
1748
+ const index = readHandoffIndex(indexPath);
1749
+ const reusedExisting = index.entries.some((item) => item.fingerprint === fingerprint);
1750
+ mkdirSync(handoffDir, { recursive: true, mode: 448 });
1751
+ chmodSync(handoffDir, 448);
1752
+ writeSecureJson(join2(handoffDir, "mapping.json"), mapping);
1753
+ writeSecureText(join2(handoffDir, "transform.mjs"), createHandoffScript());
1754
+ let planFileRel;
1755
+ if (planFile) {
1756
+ writeSecureJson(join2(handoffDir, "plan.json"), readPlanFile(planFile));
1757
+ planFileRel = `${dirName}/plan.json`;
1758
+ }
1759
+ const entry = {
1760
+ fingerprint,
1761
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
1762
+ source_sha256: mapping.source.sha256,
1763
+ format: mapping.source.format,
1764
+ data_set: mapping.source.data_set,
1765
+ mode: mapping.mode,
1766
+ property_count: mapping.properties.length,
1767
+ mapping_file: `${dirName}/mapping.json`,
1768
+ ...planFileRel ? { plan_file: planFileRel } : {}
1769
+ };
1770
+ writeAtomicJson(indexPath, upsertIndexEntry(index, entry));
1771
+ return { outDir, handoffDir, dirName, fingerprint, reusedExisting, planFile: planFileRel, entry };
1772
+ }
1773
+ function readHandoffIndex(path) {
1774
+ let raw;
1775
+ try {
1776
+ raw = readFileSync2(path, "utf8");
1777
+ } catch {
1778
+ return { version: HANDOFF_INDEX_VERSION, entries: [] };
1779
+ }
1780
+ let value;
1781
+ try {
1782
+ value = JSON.parse(raw);
1783
+ } catch {
1784
+ throw new CliValidationError("The handoff index is not valid JSON.", {
1785
+ code: "LOCAL_DATA_HANDOFF_INDEX_INVALID",
1786
+ location: { field: "out-dir" }
1787
+ });
1788
+ }
1789
+ if (!isRecord2(value) || value.version !== HANDOFF_INDEX_VERSION || !Array.isArray(value.entries)) {
1790
+ throw new CliValidationError("The handoff index is not ae-data-integration-index/v1.", {
1791
+ code: "LOCAL_DATA_HANDOFF_INDEX_INVALID",
1792
+ location: { field: "out-dir" }
1793
+ });
1794
+ }
1795
+ return value;
1796
+ }
1797
+ function readPlanFile(path) {
1798
+ let raw;
1799
+ try {
1800
+ raw = readFileSync2(path, "utf8");
1801
+ } catch {
1802
+ throw new CliValidationError("The tracking-plan file could not be read.", {
1803
+ code: "LOCAL_DATA_HANDOFF_PLAN_NOT_FOUND",
1804
+ location: { field: "plan-file" }
1805
+ });
1806
+ }
1807
+ try {
1808
+ return JSON.parse(raw);
1809
+ } catch {
1810
+ throw new CliValidationError("The tracking-plan file is not valid JSON.", {
1811
+ code: "LOCAL_DATA_HANDOFF_PLAN_INVALID",
1812
+ location: { field: "plan-file" }
1813
+ });
1814
+ }
1815
+ }
1816
+ function createHandoffScript() {
1817
+ return [
1818
+ "import { createHash } from 'node:crypto';",
1819
+ "import { createReadStream, readFileSync } from 'node:fs';",
1820
+ "import { spawnSync } from 'node:child_process';",
1821
+ "import { fileURLToPath } from 'node:url';",
1822
+ "import { dirname, join } from 'node:path';",
1823
+ "",
1824
+ "const [inputFile, outputDir] = process.argv.slice(2);",
1825
+ "if (!inputFile) { console.error('Usage: node transform.mjs <new-input-file> [<output-dir>]'); process.exit(2); }",
1826
+ "",
1827
+ "async function sha256Of(file) {",
1828
+ " const hash = createHash('sha256');",
1829
+ " for await (const chunk of createReadStream(file)) hash.update(chunk);",
1830
+ " return hash.digest('hex');",
1831
+ "}",
1832
+ "",
1833
+ "const here = dirname(fileURLToPath(import.meta.url));",
1834
+ "const mapping = JSON.parse(readFileSync(join(here, 'mapping.json'), 'utf8'));",
1835
+ "// Re-stamp the content fingerprint for this specific file; the transform logic is reused unchanged.",
1836
+ "mapping.source.sha256 = await sha256Of(inputFile);",
1837
+ "",
1838
+ "const args = ['data-integration', 'convert', '--input-file', inputFile, '--mapping', JSON.stringify(mapping)];",
1839
+ "if (outputDir) args.push('--output-dir', outputDir);",
1840
+ "const result = spawnSync('ae-cli', args, { stdio: 'inherit' });",
1841
+ "process.exit(result.status ?? 1);",
1842
+ ""
1843
+ ].join("\n");
1844
+ }
1845
+ function writeSecureJson(path, value) {
1846
+ writeSecureText(path, `${JSON.stringify(value, null, 2)}
1847
+ `);
1848
+ }
1849
+ function writeSecureText(path, content) {
1850
+ writeFileSync(path, content, { encoding: "utf8", mode: 384 });
1851
+ chmodSync(path, 384);
1852
+ }
1853
+ function writeAtomicJson(path, value) {
1854
+ writeSecureText(`${path}.tmp`, `${JSON.stringify(value, null, 2)}
1855
+ `);
1856
+ renameSync(`${path}.tmp`, path);
1857
+ chmodSync(path, 384);
1858
+ }
1859
+ function isRecord2(value) {
1860
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1861
+ }
1862
+ var dataIntegrationHandoff = {
1863
+ service: "data-integration",
1864
+ command: "handoff",
1865
+ usesAeHost: false,
1866
+ description: "Export a reusable handoff package (pipeline descriptor + frozen mappings + stage executors + docs) and a shareable zip.",
1867
+ flags: [
1868
+ { 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).` },
1869
+ { name: "plan-file", type: "string", sensitive: true, desc: "Tracking-plan draft.json to reference inside the handoff package." },
1870
+ { name: "out-dir", type: "string", sensitive: true, desc: "Handoff root directory. Default: .ae-cli/data-integration (project workspace)." },
1871
+ { 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." },
1872
+ { name: "project-id", type: "string", sensitive: true, desc: "Numeric destination project ID to record; upload derives the APPID from it via project info get." }
1873
+ ],
1874
+ risk: "write",
1875
+ dryRun: async (ctx) => {
1876
+ const mappings = ctx.list("mapping").map((source) => readLocalDataMapping(source));
1877
+ const outDir = resolve2(ctx.str("out-dir").trim() || join2(".ae-cli", "data-integration"));
1878
+ const planFile = ctx.str("plan-file").trim() || void 0;
1879
+ const pushurl = ctx.str("pushurl").trim() || void 0;
1880
+ const projectId = ctx.str("project-id").trim() || void 0;
1881
+ const fingerprints = mappings.map(structureFingerprint);
1882
+ return {
1883
+ action: "handoff_local_data",
1884
+ out_dir: outDir,
1885
+ mapping_count: mappings.length,
1886
+ fingerprints,
1887
+ target: { pushurl, project_id: projectId },
1888
+ files: handoffFileList(fingerprints, planFile),
1889
+ index_file: join2(outDir, "index.json"),
1890
+ pipeline_file: join2(outDir, "pipeline.json"),
1891
+ shape_file: join2(outDir, "shape.json"),
1892
+ zip_path: fingerprints[0] ? zipPathFor(outDir, fingerprints[0]) : void 0
1893
+ };
1894
+ },
1895
+ execute: async (ctx) => {
1896
+ const mappings = ctx.list("mapping").map((source) => readLocalDataMapping(source));
1897
+ const outDir = resolve2(ctx.str("out-dir").trim() || join2(".ae-cli", "data-integration"));
1898
+ const planFile = ctx.str("plan-file").trim() || void 0;
1899
+ const target = {
1900
+ pushurl: ctx.str("pushurl").trim() || void 0,
1901
+ project_id: ctx.str("project-id").trim() || void 0
1902
+ };
1903
+ const items = mappings.map((mapping) => ({
1904
+ mapping,
1905
+ build: buildHandoffPackage(outDir, mapping, planFile)
1906
+ }));
1907
+ const entries = items.map((item) => item.build.entry);
1908
+ const relayFiles = [
1909
+ { relPath: "pipeline.json", content: `${JSON.stringify(buildPipelineDescriptor(entries, target), null, 2)}
1910
+ `, mode: 384 },
1911
+ { relPath: "shape.json", content: `${JSON.stringify(buildShapeBaseline(items.map((item) => ({ mapping: item.mapping, fingerprint: item.build.fingerprint }))), null, 2)}
1912
+ `, mode: 384 },
1913
+ ...generateBinScripts(),
1914
+ { relPath: "README.md", content: generateReadme(), mode: 384 },
1915
+ { relPath: "RUNBOOK.md", content: generateRunbook(), mode: 384 },
1916
+ { relPath: ".local/target.env.example", content: generateEnvTemplate(), mode: 384 },
1917
+ { relPath: ".gitignore", content: generateGitignore(), mode: 384 },
1918
+ { relPath: "inbox/.gitkeep", content: "", mode: 384 },
1919
+ { relPath: "runs/.gitkeep", content: "", mode: 384 }
1920
+ ];
1921
+ for (const file of relayFiles) writeRelayFile(outDir, file);
1922
+ const zipPath = zipPathFor(outDir, entries[0].fingerprint);
1923
+ const stagingDir = stageScopedPackage(outDir, items.map((item) => item.build), entries, relayFiles);
1924
+ try {
1925
+ await zipPackage(stagingDir, zipPath);
1926
+ chmodSync(zipPath, 384);
1927
+ } finally {
1928
+ rmSync(stagingDir, { recursive: true, force: true });
1929
+ }
1930
+ return {
1931
+ out_dir: outDir,
1932
+ zip_path: zipPath,
1933
+ pipeline_file: join2(outDir, "pipeline.json"),
1934
+ shape_file: join2(outDir, "shape.json"),
1935
+ index_file: join2(outDir, "index.json"),
1936
+ handoff_dirs: items.map((item) => item.build.dirName),
1937
+ deliverables: buildDeliverables(outDir, relayFiles, items),
1938
+ next_steps: [
1939
+ `Review the pipeline descriptor and four confirmation gates: ${join2(outDir, "RUNBOOK.md")}.`,
1940
+ `Share the archive: ${zipPath}.`,
1941
+ `Next same-shape file: cd ${outDir} && bin/run.sh <new-file>, then bin/upload.sh runs/<run-id> --confirm.`
1942
+ ],
1943
+ reused_existing: items.some((item) => item.build.reusedExisting)
1944
+ };
1945
+ }
1946
+ };
1947
+ function zipPathFor(outDir, fingerprint) {
1948
+ return join2(dirname2(resolve2(outDir)), `ae-data-integration-handoff-${fingerprint.slice(0, 8)}.zip`);
1949
+ }
1950
+ var RELAY_FILE_PATHS = [
1951
+ "pipeline.json",
1952
+ "shape.json",
1953
+ "index.json",
1954
+ "README.md",
1955
+ "RUNBOOK.md",
1956
+ ".local/target.env.example",
1957
+ ".gitignore",
1958
+ "bin/run.sh",
1959
+ "bin/upload.sh",
1960
+ "bin/bind_mapping.py",
1961
+ "bin/summarize.py",
1962
+ "bin/plan_check.py",
1963
+ "bin/verify.py",
1964
+ "bin/resolve_appid.py",
1965
+ "inbox/.gitkeep",
1966
+ "runs/.gitkeep"
1967
+ ];
1968
+ function mappingDirFiles(dirName, planFile) {
1969
+ return [
1970
+ `${dirName}/mapping.json`,
1971
+ `${dirName}/transform.mjs`,
1972
+ ...planFile ? [`${dirName}/plan.json`] : []
1973
+ ];
1974
+ }
1975
+ function handoffFileList(fingerprints, planFile) {
1976
+ const perMapping = fingerprints.flatMap(
1977
+ (fingerprint) => mappingDirFiles(fingerprint.slice(0, HANDOFF_DIR_LEN), planFile)
1978
+ );
1979
+ return [...RELAY_FILE_PATHS, ...perMapping];
1980
+ }
1981
+ function buildDeliverables(outDir, relayFiles, items) {
1982
+ const relay = [
1983
+ { rel_path: "index.json", abs_path: join2(outDir, "index.json") },
1984
+ ...relayFiles.map((file) => ({ rel_path: file.relPath, abs_path: join2(outDir, file.relPath) }))
1985
+ ];
1986
+ const mappings = items.flatMap(
1987
+ (item) => mappingDirFiles(item.build.dirName, item.build.planFile).map((rel) => ({
1988
+ rel_path: rel,
1989
+ abs_path: join2(outDir, rel)
1990
+ }))
1991
+ );
1992
+ return [...relay, ...mappings];
1993
+ }
1994
+ function writeRelayFile(outDir, file) {
1995
+ const abs = join2(outDir, file.relPath);
1996
+ mkdirSync(dirname2(abs), { recursive: true, mode: 448 });
1997
+ writeFileSync(abs, file.content, { encoding: "utf8", mode: file.mode });
1998
+ chmodSync(abs, file.mode);
1999
+ }
2000
+ function stageScopedPackage(outDir, mappingDirs, entries, relayFiles) {
2001
+ const staging = mkdtempSync(join2(tmpdir(), "ae-handoff-"));
2002
+ writeSecureJson(join2(staging, "index.json"), { version: HANDOFF_INDEX_VERSION, entries });
2003
+ for (const file of relayFiles) writeRelayFile(staging, file);
2004
+ for (const { dirName, planFile } of mappingDirs) {
2005
+ for (const rel of mappingDirFiles(dirName, planFile)) {
2006
+ const dest = join2(staging, rel);
2007
+ mkdirSync(dirname2(dest), { recursive: true, mode: 448 });
2008
+ writeFileSync(dest, readFileSync2(join2(outDir, rel), "utf8"), { encoding: "utf8", mode: 384 });
2009
+ chmodSync(dest, 384);
2010
+ }
2011
+ }
2012
+ return staging;
2013
+ }
2014
+
2015
+ // src/commands/data-integration/reuse.ts
2016
+ import { readFileSync as readFileSync3 } from "fs";
2017
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "path";
2018
+
2019
+ // src/commands/data-integration/handoff-root.ts
2020
+ import { existsSync } from "fs";
2021
+ import { dirname as dirname3, join as join3, resolve as resolve3 } from "path";
2022
+ function globalHandoffDir() {
2023
+ const home = process.env.HOME;
2024
+ if (!home) return void 0;
2025
+ return join3(getConfigDir(), "data-integration");
2026
+ }
2027
+ function upwardHandoffDirs(startDir) {
2028
+ const dirs = [];
2029
+ let current = resolve3(startDir);
2030
+ for (; ; ) {
2031
+ const candidate = join3(current, ".ae-cli", "data-integration");
2032
+ if (!dirs.includes(candidate)) dirs.push(candidate);
2033
+ const parent = dirname3(current);
2034
+ if (parent === current) break;
2035
+ current = parent;
2036
+ }
2037
+ return dirs;
2038
+ }
2039
+ function reuseSearchPaths(startDir = process.cwd()) {
2040
+ const globalDir = globalHandoffDir();
2041
+ return globalDir ? [...upwardHandoffDirs(startDir), globalDir] : upwardHandoffDirs(startDir);
2042
+ }
2043
+ function findReuseRoot(startDir = process.cwd()) {
2044
+ for (const dir of upwardHandoffDirs(startDir)) {
2045
+ if (existsSync(join3(dir, "index.json"))) return dir;
2046
+ }
2047
+ return globalHandoffDir();
2048
+ }
2049
+
2050
+ // src/commands/data-integration/reuse.ts
2051
+ function detectReuse(mapping, outDir) {
2052
+ const fingerprint = structureFingerprint(mapping);
2053
+ const indexPath = join4(outDir, "index.json");
2054
+ const index = readHandoffIndex(indexPath);
2055
+ const entry = index.entries.find((item) => item.fingerprint === fingerprint);
2056
+ if (!entry) return { matched: false, fingerprint, index_file: indexPath };
2057
+ const mappingPath = join4(outDir, entry.mapping_file);
2058
+ const match = {
2059
+ fingerprint: entry.fingerprint,
2060
+ created_at: entry.created_at,
2061
+ format: entry.format,
2062
+ data_set: entry.data_set,
2063
+ mode: entry.mode,
2064
+ property_count: entry.property_count,
2065
+ mapping_file: entry.mapping_file,
2066
+ ...entry.plan_file ? { plan_file: entry.plan_file } : {},
2067
+ ...readFrozenEventName(mappingPath),
2068
+ run: `node ${join4(outDir, dirname4(entry.mapping_file), "transform.mjs")} <new-input-file> [<output-dir>]`
2069
+ };
2070
+ return { matched: true, fingerprint, index_file: indexPath, match };
2071
+ }
2072
+ function readFrozenEventName(path) {
2073
+ let value;
2074
+ try {
2075
+ value = JSON.parse(readFileSync3(path, "utf8"));
2076
+ } catch {
2077
+ return {};
2078
+ }
2079
+ if (isRecord3(value) && typeof value.default_event_name === "string" && value.default_event_name) {
2080
+ return { default_event_name: value.default_event_name };
2081
+ }
2082
+ return {};
2083
+ }
2084
+ function isRecord3(value) {
2085
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2086
+ }
2087
+ var dataIntegrationReuse = {
2088
+ service: "data-integration",
2089
+ command: "reuse",
2090
+ usesAeHost: false,
2091
+ description: "Match a candidate mapping against the .ae-cli/data-integration/ handoff index and propose a reusable package.",
2092
+ flags: [
2093
+ { name: "mapping", type: "string", required: true, sensitive: true, desc: `Candidate ${MAPPING_VERSION} JSON, file path, or @file (typically inspect recommended_mapping).` },
2094
+ { 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/." }
2095
+ ],
2096
+ risk: "read",
2097
+ dryRun: async (ctx) => {
2098
+ const mapping = readLocalDataMapping(ctx.str("mapping"));
2099
+ const outDir = resolveReuseOutDir(ctx);
2100
+ const result = detectReuse(mapping, outDir);
2101
+ return {
2102
+ action: "reuse_detect",
2103
+ fingerprint: result.fingerprint,
2104
+ matched: result.matched,
2105
+ index_file: result.index_file,
2106
+ searched_paths: searchedIndexPaths(ctx)
2107
+ };
2108
+ },
2109
+ execute: async (ctx) => {
2110
+ const mapping = readLocalDataMapping(ctx.str("mapping"));
2111
+ const outDir = resolveReuseOutDir(ctx);
2112
+ const result = detectReuse(mapping, outDir);
2113
+ return { ...result, searched_paths: searchedIndexPaths(ctx) };
2114
+ }
2115
+ };
2116
+ function resolveReuseOutDir(ctx) {
2117
+ const explicit = ctx.str("out-dir").trim();
2118
+ if (explicit) return resolve4(explicit);
2119
+ return findReuseRoot() ?? resolve4(join4(".ae-cli", "data-integration"));
2120
+ }
2121
+ function searchedIndexPaths(ctx) {
2122
+ const explicit = ctx.str("out-dir").trim();
2123
+ const dirs = explicit ? [resolve4(explicit)] : reuseSearchPaths();
2124
+ return dirs.map((dir) => join4(dir, "index.json"));
2125
+ }
2126
+
2127
+ // src/commands/data-integration/index.ts
2128
+ var commands = [dataIntegrationInspect, dataIntegrationPlan, dataIntegrationConvert, dataIntegrationUpload, dataIntegrationHandoff, dataIntegrationReuse];
2129
+ var data_integration_default = commands;
2130
+ export {
2131
+ dataIntegrationConvert,
2132
+ dataIntegrationHandoff,
2133
+ dataIntegrationInspect,
2134
+ dataIntegrationPlan,
2135
+ dataIntegrationReuse,
2136
+ dataIntegrationUpload,
2137
+ data_integration_default as default
2138
+ };