@dataparade/cli 0.0.26 → 0.0.29

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 (120) hide show
  1. package/README.md +56 -13
  2. package/dist/package.json +7 -7
  3. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +0 -1
  4. package/dist/src/cli.d.ts +3 -0
  5. package/dist/src/cli.js +102 -68
  6. package/dist/src/discoveries/contract/ocsf-discovery-record.d.ts +1 -1
  7. package/dist/src/discoveries/load-ocsf-discoveries.d.ts +0 -8
  8. package/dist/src/discoveries/load-ocsf-discoveries.js +0 -31
  9. package/dist/src/discoveries/write-ocsf-discoveries.d.ts +0 -8
  10. package/dist/src/discoveries/write-ocsf-discoveries.js +0 -38
  11. package/dist/src/evals/run-model-matrix.js +0 -1
  12. package/dist/src/export/export-ocsf.d.ts +18 -0
  13. package/dist/src/export/export-ocsf.js +104 -0
  14. package/dist/src/export/register-export-commands.d.ts +2 -0
  15. package/dist/src/export/register-export-commands.js +30 -0
  16. package/dist/src/facts/apply-answers.d.ts +29 -0
  17. package/dist/src/facts/apply-answers.js +202 -0
  18. package/dist/src/facts/build-facts.d.ts +24 -0
  19. package/dist/src/facts/build-facts.js +198 -0
  20. package/dist/src/facts/io.d.ts +17 -0
  21. package/dist/src/facts/io.js +67 -0
  22. package/dist/src/facts/layout.d.ts +29 -0
  23. package/dist/src/facts/layout.js +38 -0
  24. package/dist/src/facts/schema.d.ts +265 -0
  25. package/dist/src/facts/schema.js +122 -0
  26. package/dist/src/facts/slug.d.ts +7 -0
  27. package/dist/src/facts/slug.js +47 -0
  28. package/dist/src/kb/brief.d.ts +1 -2
  29. package/dist/src/kb/brief.js +2 -4
  30. package/dist/src/kb/interview-record.d.ts +18 -0
  31. package/dist/src/kb/interview-record.js +70 -0
  32. package/dist/src/kb/kb-store.d.ts +24 -18
  33. package/dist/src/kb/kb-store.js +89 -28
  34. package/dist/src/kb/land.d.ts +32 -12
  35. package/dist/src/kb/land.js +97 -90
  36. package/dist/src/kb/migrate.d.ts +23 -0
  37. package/dist/src/kb/migrate.js +91 -0
  38. package/dist/src/kb/project-diagram.js +4 -4
  39. package/dist/src/kb/register-kb-commands.js +71 -20
  40. package/dist/src/observability/scan-sentry.js +0 -1
  41. package/dist/src/output/scan-output-excludes.d.ts +1 -1
  42. package/dist/src/output/scan-output-excludes.js +14 -5
  43. package/dist/src/output/write-scan-knowledge.d.ts +33 -0
  44. package/dist/src/output/write-scan-knowledge.js +115 -0
  45. package/dist/src/platform-api/estimate-scan-footprint.d.ts +31 -0
  46. package/dist/src/platform-api/estimate-scan-footprint.js +75 -2
  47. package/dist/src/platform-api/fetch-failure.d.ts +5 -0
  48. package/dist/src/platform-api/fetch-failure.js +13 -0
  49. package/dist/src/platform-api/upload-client.d.ts +5 -0
  50. package/dist/src/platform-api/upload-client.js +11 -1
  51. package/dist/src/ui/scan-progress-renderer.d.ts +16 -0
  52. package/dist/src/ui/scan-progress-renderer.js +29 -3
  53. package/dist/src/ui/teaching-lines.js +18 -6
  54. package/dist/src/upload/collect-scan-sidecars.d.ts +2 -27
  55. package/dist/src/upload/collect-scan-sidecars.js +25 -121
  56. package/dist/src/upload/run-upload.js +0 -3
  57. package/dist/tests/cli/cli.spec.js +30 -13
  58. package/dist/tests/helpers/facts-fixture.d.ts +9 -0
  59. package/dist/tests/helpers/facts-fixture.js +72 -0
  60. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.js +156 -0
  61. package/dist/tests/unit/export/export-ocsf.spec.js +72 -0
  62. package/dist/tests/unit/facts/apply-answers.spec.d.ts +1 -0
  63. package/dist/tests/unit/facts/apply-answers.spec.js +128 -0
  64. package/dist/tests/unit/facts/build-facts.spec.d.ts +1 -0
  65. package/dist/tests/unit/facts/build-facts.spec.js +161 -0
  66. package/dist/tests/unit/facts/slug.spec.d.ts +1 -0
  67. package/dist/tests/unit/facts/slug.spec.js +30 -0
  68. package/dist/tests/unit/kb/kb-interview-loop.spec.js +83 -35
  69. package/dist/tests/unit/kb/migrate.spec.d.ts +1 -0
  70. package/dist/tests/unit/kb/migrate.spec.js +108 -0
  71. package/dist/tests/unit/output/graphify-cache-dir.spec.d.ts +1 -0
  72. package/dist/tests/unit/output/graphify-cache-dir.spec.js +20 -0
  73. package/dist/tests/unit/output/scan-output-excludes.spec.js +4 -2
  74. package/dist/tests/unit/platform-api/estimate-scan-footprint.spec.js +77 -0
  75. package/dist/tests/unit/platform-api/upload-client.spec.js +2 -2
  76. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +21 -0
  77. package/dist/tests/unit/ui/teaching-lines.spec.js +16 -0
  78. package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +46 -46
  79. package/dist/tests/unit/upload/pack-scan-upload.spec.js +6 -6
  80. package/dist/vendor/scanner/dist/src/classifier/component-factory.js +6 -14
  81. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.d.ts +1 -0
  82. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.js +32 -1
  83. package/dist/vendor/scanner/dist/src/classifier/naming.d.ts +5 -0
  84. package/dist/vendor/scanner/dist/src/classifier/naming.js +8 -4
  85. package/dist/vendor/scanner/dist/src/core/pipeline/build-scan-personal-data-layers.js +26 -14
  86. package/dist/vendor/scanner/dist/src/core/pipeline/enrich-personal-data-layers.js +3 -1
  87. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.d.ts +18 -0
  88. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.js +125 -66
  89. package/dist/vendor/scanner/dist/src/index.d.ts +2 -0
  90. package/dist/vendor/scanner/dist/src/index.js +7 -2
  91. package/dist/vendor/scanner/dist/src/ingest/file-system.d.ts +5 -0
  92. package/dist/vendor/scanner/dist/src/ingest/file-system.js +5 -0
  93. package/dist/vendor/scanner/dist/src/ingest/gitignore.d.ts +17 -0
  94. package/dist/vendor/scanner/dist/src/ingest/gitignore.js +47 -9
  95. package/dist/vendor/scanner/dist/src/ingest/schema-files.d.ts +10 -2
  96. package/dist/vendor/scanner/dist/src/ingest/schema-files.js +24 -7
  97. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.d.ts +3 -0
  98. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.js +45 -0
  99. package/dist/vendor/scanner/dist/src/patterns/scan-exclusions.js +7 -0
  100. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.d.ts +24 -0
  101. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.js +19 -6
  102. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.js +5 -2
  103. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-aliases.js +5 -2
  104. package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +8 -0
  105. package/dist/vendor/scanner/patterns/third-party.patterns.yaml +9 -0
  106. package/package.json +7 -7
  107. package/dist/src/discoveries/project-collected-diagram.d.ts +0 -7
  108. package/dist/src/discoveries/project-collected-diagram.js +0 -182
  109. package/dist/src/discoveries/project-ocsf-to-discoveries-document.d.ts +0 -16
  110. package/dist/src/discoveries/project-ocsf-to-discoveries-document.js +0 -269
  111. package/dist/src/discoveries/scan-result-to-discovery-input.d.ts +0 -13
  112. package/dist/src/discoveries/scan-result-to-discovery-input.js +0 -60
  113. package/dist/src/output/write-knowledge-graph.d.ts +0 -20
  114. package/dist/src/output/write-knowledge-graph.js +0 -53
  115. package/dist/src/output/write-scan-discoveries.d.ts +0 -17
  116. package/dist/src/output/write-scan-discoveries.js +0 -61
  117. package/dist/tests/unit/discoveries/project-collected-diagram.spec.js +0 -97
  118. package/dist/tests/unit/discoveries/rescan-replaces-scan-records.spec.js +0 -89
  119. /package/dist/tests/unit/{discoveries/project-collected-diagram.spec.d.ts → cli/scan-ai-session-fallback.spec.d.ts} +0 -0
  120. /package/dist/tests/unit/{discoveries/rescan-replaces-scan-records.spec.d.ts → export/export-ocsf.spec.d.ts} +0 -0
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.migratedAnswerId = migratedAnswerId;
7
+ exports.migrateInterviewRecords = migrateInterviewRecords;
8
+ const crypto_1 = require("crypto");
9
+ const path_1 = __importDefault(require("path"));
10
+ const load_ocsf_discoveries_1 = require("../discoveries/load-ocsf-discoveries");
11
+ const scan_entity_uri_1 = require("../discoveries/scan-entity-uri");
12
+ const io_1 = require("../facts/io");
13
+ const kb_store_1 = require("./kb-store");
14
+ /** Same record, same id, so running migrate twice adds nothing. */
15
+ function migratedAnswerId(recordUid) {
16
+ return `ans_${(0, crypto_1.createHash)("sha256").update(recordUid).digest("hex").slice(0, 12)}`;
17
+ }
18
+ function storedValue(slot, text) {
19
+ if (slot === "data_categories") {
20
+ try {
21
+ const parsed = JSON.parse(text);
22
+ if (Array.isArray(parsed))
23
+ return parsed;
24
+ }
25
+ catch {
26
+ // Not a list; keep the text.
27
+ }
28
+ }
29
+ return text;
30
+ }
31
+ /**
32
+ * Convert the interview records in an old `ocsf-discoveries/` folder (CLI 0.0.26 and
33
+ * earlier) into entries of answers.json. Scan records are dropped; scanning again
34
+ * regenerates the Facts. The old folder is left as it is.
35
+ */
36
+ function migrateInterviewRecords(paths, options = {}) {
37
+ const from = path_1.default.resolve(options.from ?? path_1.default.join(paths.dir, "ocsf-discoveries"));
38
+ let records;
39
+ try {
40
+ records = (0, load_ocsf_discoveries_1.loadOcsfDiscoveriesFromDir)(from).records;
41
+ }
42
+ catch (error) {
43
+ if (error instanceof load_ocsf_discoveries_1.OcsfDiscoveryLoadError) {
44
+ throw new kb_store_1.KbError("NOTHING_TO_MIGRATE", `${error.message}. Pass --from <old ocsf-discoveries folder>.`);
45
+ }
46
+ throw error;
47
+ }
48
+ const existing = new Set((0, io_1.readAnswers)(paths).answers.map((a) => a.id));
49
+ const fresh = [];
50
+ let alreadyMigrated = 0;
51
+ let scanRecordsDropped = 0;
52
+ for (const record of records) {
53
+ const d = record.dataparade;
54
+ if (d.source !== "interview") {
55
+ if (d.source === "scan")
56
+ scanRecordsDropped += 1;
57
+ continue;
58
+ }
59
+ if (!d.asserted_slot || d.asserted_value === undefined)
60
+ continue;
61
+ const id = migratedAnswerId(record.metadata.uid);
62
+ if (existing.has(id)) {
63
+ alreadyMigrated += 1;
64
+ continue;
65
+ }
66
+ existing.add(id);
67
+ fresh.push({
68
+ id,
69
+ factId: (0, scan_entity_uri_1.parseScanEntityAsserts)(d.asserts)?.entityId ?? d.asserts,
70
+ action: "set",
71
+ property: d.asserted_slot,
72
+ value: storedValue(d.asserted_slot, d.asserted_value),
73
+ by: d.reviewer ?? "unknown",
74
+ at: d.reviewed_at ?? d.asserted_at,
75
+ source: "interview",
76
+ ...(d.raw_evidence_ref ? { evidence: d.raw_evidence_ref } : {}),
77
+ ...(d.brief_sha ? { briefSha: d.brief_sha } : {}),
78
+ ...(d.skill_sha ? { skillSha: d.skill_sha } : {}),
79
+ });
80
+ }
81
+ if (!options.dryRun && fresh.length > 0)
82
+ (0, io_1.appendAnswers)(paths, fresh);
83
+ return {
84
+ from,
85
+ migrated: fresh.length,
86
+ alreadyMigrated,
87
+ scanRecordsDropped,
88
+ answerIds: fresh.map((a) => a.id),
89
+ dryRun: Boolean(options.dryRun),
90
+ };
91
+ }
@@ -9,9 +9,9 @@ exports.pushKbDiagram = pushKbDiagram;
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const kb_store_1 = require("./kb-store");
11
11
  /**
12
- * Project the KB (scan + interview Discoveries) into the DiagramGraphJson the
12
+ * Project the KB (scan Facts + answers) into the DiagramGraphJson the
13
13
  * viewer renders. Diagrams are projections of KB facts (c4-from-kb.md): nothing
14
- * here is stored back, and every label traces to a Discovery.
14
+ * here is stored back, and every label traces to a Fact or an answer.
15
15
  */
16
16
  const NODE_TYPE = {
17
17
  asset: "asset",
@@ -113,7 +113,7 @@ function projectKbDiagram(document, options = {}) {
113
113
  }
114
114
  function projectNameFromScan(paths) {
115
115
  try {
116
- const dataflow = JSON.parse(fs_1.default.readFileSync(`${paths.root}/dataflow.json`, "utf8"));
116
+ const dataflow = JSON.parse(fs_1.default.readFileSync(paths.dataflowPath, "utf8"));
117
117
  return dataflow.metadata?.projectName;
118
118
  }
119
119
  catch {
@@ -124,7 +124,7 @@ function writeKbDiagram(paths, options = {}) {
124
124
  const state = (0, kb_store_1.loadKbState)(paths);
125
125
  const wrapper = projectKbDiagram(state.document, {
126
126
  projectName: options.projectName ?? projectNameFromScan(paths),
127
- interviewAnswerCount: state.records.filter((r) => r.dataparade.source === "interview").length,
127
+ interviewAnswerCount: state.answers.filter((a) => a.source === "interview").length,
128
128
  orphanCount: state.orphans.length,
129
129
  });
130
130
  fs_1.default.writeFileSync(paths.diagramPath, `${JSON.stringify(wrapper, null, 2)}\n`, "utf8");
@@ -1,15 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerKbCommands = registerKbCommands;
4
+ const layout_1 = require("../facts/layout");
4
5
  const brief_1 = require("./brief");
5
6
  const kb_store_1 = require("./kb-store");
7
+ const migrate_1 = require("./migrate");
6
8
  const land_1 = require("./land");
7
9
  const project_diagram_1 = require("./project-diagram");
8
10
  const slot_shapes_1 = require("./slot-shapes");
9
- const DEFAULT_KB_DIR = ".dataparade";
11
+ const DEFAULT_KB_DIR = layout_1.DEFAULT_OUTPUT_DIRNAME;
10
12
  /** All kb commands print one JSON object so agents can parse results. */
11
13
  function print(result) {
12
- // eslint-disable-next-line no-console
13
14
  console.log(JSON.stringify(result, null, 2));
14
15
  }
15
16
  function fail(error) {
@@ -20,7 +21,7 @@ function fail(error) {
20
21
  function registerKbCommands(program) {
21
22
  const kb = program
22
23
  .command("kb")
23
- .description("Knowledge base: interview briefs, confirmed answers (Discoveries), and diagram projection");
24
+ .description("Knowledge base: interview briefs, confirmed answers (answers.json), and diagram projection");
24
25
  kb.command("brief")
25
26
  .description("Snapshot the KB as a brief: what is known, and the open interview questions in asking order")
26
27
  .option("--kb <dir>", "Knowledge base directory (where scan wrote dataflow.json)", DEFAULT_KB_DIR)
@@ -44,29 +45,79 @@ function registerKbCommands(program) {
44
45
  }
45
46
  });
46
47
  kb.command("land")
47
- .description("Land one developer-confirmed interview answer as a source=interview Discovery")
48
- .requiredOption("--brief <sha>", "brief_sha the question was asked from (from 'kb brief')")
49
- .requiredOption("--target <id>", "Entity asked about: asserts URI or id from the brief, or dp:a0/system")
50
- .requiredOption("--slot <slot>", "in_scope | actor_kind | data_categories | purpose")
51
- .requiredOption("--value <value>", "Ontology value (data_categories: comma list or JSON array)")
48
+ .description("Land one confirmed answer in answers.json: an interview answer, or a reviewer's set/remove of a Fact")
49
+ .option("--source <source>", "interview (default) or review", "interview")
50
+ .option("--brief <sha>", "interview: brief_sha the question was asked from (from 'kb brief')")
51
+ .requiredOption("--target <id>", "The Fact asked about: its id from the brief or facts.json, or dp:a0/system")
52
+ .option("--slot <slot>", "interview: in_scope | actor_kind | data_categories | purpose")
53
+ .option("--action <action>", "review: set (default) or remove", "set")
54
+ .option("--property <name>", "review set: the property to override")
55
+ .option("--value <value>", "The value (interview data_categories: comma list or JSON array)")
52
56
  .requiredOption("--reviewer <email>", "The developer who confirmed this answer")
53
- .requiredOption("--evidence <path>", "Unedited interview transcript (relative to the KB dir, or absolute)")
54
- .requiredOption("--skill-sha <sha>", "Full SHA of the interview skill (e.g. git hash-object SKILL.md)")
57
+ .option("--evidence <path>", "interview: unedited transcript (relative to the KB dir, or absolute); review: a note or path")
58
+ .option("--skill-sha <sha>", "interview: full SHA of the interview skill (e.g. git hash-object SKILL.md)")
55
59
  .option("--kb <dir>", "Knowledge base directory", DEFAULT_KB_DIR)
56
60
  .option("--dry-run", "Validate without writing")
57
61
  .action((options) => {
58
62
  try {
59
- const landed = (0, land_1.landInterviewAnswer)((0, kb_store_1.resolveKbPaths)(options.kb), {
60
- briefSha: options.brief,
61
- target: options.target,
62
- slot: options.slot,
63
- value: options.value,
64
- reviewer: options.reviewer,
65
- evidence: options.evidence,
66
- skillSha: options.skillSha,
67
- dryRun: options.dryRun,
63
+ const paths = (0, kb_store_1.resolveKbPaths)(options.kb);
64
+ if (options.source === "review") {
65
+ if (options.action !== "set" && options.action !== "remove") {
66
+ throw new kb_store_1.KbError("BAD_ANSWER", `--action must be set or remove; got '${options.action}'.`);
67
+ }
68
+ print({
69
+ ok: true,
70
+ ...(0, land_1.landReviewAnswer)(paths, {
71
+ target: options.target,
72
+ action: options.action,
73
+ property: options.property ?? options.slot,
74
+ value: options.value,
75
+ reviewer: options.reviewer,
76
+ evidence: options.evidence,
77
+ dryRun: options.dryRun,
78
+ }),
79
+ });
80
+ return;
81
+ }
82
+ if (options.source !== "interview") {
83
+ throw new kb_store_1.KbError("BAD_ANSWER", `--source must be interview or review; got '${options.source}'.`);
84
+ }
85
+ for (const [flag, value] of [
86
+ ["--brief", options.brief],
87
+ ["--slot", options.slot],
88
+ ["--value", options.value],
89
+ ["--evidence", options.evidence],
90
+ ["--skill-sha", options.skillSha],
91
+ ]) {
92
+ if (!value)
93
+ throw new kb_store_1.KbError("BAD_ANSWER", `${flag} is required for an interview answer.`);
94
+ }
95
+ print({
96
+ ok: true,
97
+ ...(0, land_1.landInterviewAnswer)(paths, {
98
+ briefSha: options.brief,
99
+ target: options.target,
100
+ slot: options.slot,
101
+ value: options.value,
102
+ reviewer: options.reviewer,
103
+ evidence: options.evidence,
104
+ skillSha: options.skillSha,
105
+ dryRun: options.dryRun,
106
+ }),
68
107
  });
69
- print({ ok: true, ...landed });
108
+ }
109
+ catch (error) {
110
+ fail(error);
111
+ }
112
+ });
113
+ kb.command("migrate")
114
+ .description("Convert interview records from an old ocsf-discoveries/ folder (CLI 0.0.26 and earlier) into answers.json")
115
+ .option("--kb <dir>", "Knowledge base directory", DEFAULT_KB_DIR)
116
+ .option("--from <dir>", "Old OCSF folder (default: <kb>/ocsf-discoveries)")
117
+ .option("--dry-run", "Count what would be migrated without writing")
118
+ .action((options) => {
119
+ try {
120
+ print({ ok: true, ...(0, migrate_1.migrateInterviewRecords)((0, kb_store_1.resolveKbPaths)(options.kb), { from: options.from, dryRun: options.dryRun }) });
70
121
  }
71
122
  catch (error) {
72
123
  fail(error);
@@ -111,7 +111,6 @@ async function reportScanCliError(input) {
111
111
  }
112
112
  catch (reportErr) {
113
113
  const detail = reportErr instanceof Error ? reportErr.message : String(reportErr);
114
- // eslint-disable-next-line no-console
115
114
  console.warn(`[scan] failed to report error to Sentry: ${detail}`);
116
115
  }
117
116
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Exclude globs that keep a scan from reading its own previous output when the
3
3
  * output (the knowledge base) lives inside the scanned repo, e.g. `.dataparade/`.
4
- * Without this, a re-scan ingests thousands of Discovery files as source.
4
+ * Without this, a re-scan ingests its own Facts as source.
5
5
  */
6
6
  export declare function scanOutputExcludes(scanRoot: string, dataflowOutputPath: string): string[];
@@ -5,23 +5,32 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.scanOutputExcludes = scanOutputExcludes;
7
7
  const path_1 = __importDefault(require("path"));
8
- /** Everything a scan writes next to dataflow.json (plus the KB folders `dataparade kb` adds). */
8
+ /**
9
+ * Everything a scan (and `dataparade kb`) writes next to dataflow.json, for when the
10
+ * output folder is the scan root itself. Older versions' files are included so a folder
11
+ * scanned by an earlier CLI is not read back in as source.
12
+ */
9
13
  const SCAN_OUTPUT_ENTRIES = [
10
14
  "dataflow.json",
15
+ "facts.json",
16
+ "data-items/**",
17
+ "graphify.json",
18
+ "answers.json",
19
+ "diagram.json",
20
+ "briefs/**",
21
+ "evidence/**",
22
+ // Written by CLI 0.0.26 and earlier.
11
23
  "dataparade.json",
12
24
  "dataparade-graph.json",
13
25
  "discoveries-diagram.json",
14
26
  "discoveries-diagram.d2",
15
- "diagram.json",
16
27
  "ocsf-discoveries/**",
17
28
  "graphify-out/**",
18
- "briefs/**",
19
- "evidence/**",
20
29
  ];
21
30
  /**
22
31
  * Exclude globs that keep a scan from reading its own previous output when the
23
32
  * output (the knowledge base) lives inside the scanned repo, e.g. `.dataparade/`.
24
- * Without this, a re-scan ingests thousands of Discovery files as source.
33
+ * Without this, a re-scan ingests its own Facts as source.
25
34
  */
26
35
  function scanOutputExcludes(scanRoot, dataflowOutputPath) {
27
36
  const root = path_1.default.resolve(scanRoot);
@@ -0,0 +1,33 @@
1
+ import { type DataParadeGraph, type OrchestratorScanResult } from '../../vendor/scanner/dist/src/index.js';
2
+ import type { OutputLayout } from '../facts/layout';
3
+ import { type DataflowHierarchy } from './c4-hierarchy';
4
+ /**
5
+ * Where Graphify keeps its working files and cache between scans, outside the output
6
+ * folder: `~/.cache/dataparade/graphify/<hash of the scan root>`.
7
+ */
8
+ export declare function graphifyCacheDir(scanRoot: string, env?: NodeJS.ProcessEnv): string;
9
+ export interface ScanKnowledge {
10
+ /** The scan result with Graphify's info attached, when Graphify ran. */
11
+ result: OrchestratorScanResult;
12
+ /** The knowledge graph, in memory only. Undefined when it could not be built. */
13
+ graph?: DataParadeGraph;
14
+ }
15
+ /**
16
+ * Run Graphify (unless disabled), copy its graph to graphify.json, and build the knowledge
17
+ * graph. A stale graphify.json from an earlier scan is removed first.
18
+ */
19
+ export declare function prepareScanKnowledge(result: OrchestratorScanResult, scanRoot: string, layout: OutputLayout, options: {
20
+ structureGraph: boolean;
21
+ }): Promise<ScanKnowledge>;
22
+ /** C4 hierarchy for `dataflow.json` metadata, from the knowledge graph. */
23
+ export declare function buildScanHierarchy(graph: DataParadeGraph | undefined, graphNodeIds: Iterable<string>): DataflowHierarchy | undefined;
24
+ export interface WriteScanFactsOptions {
25
+ knowledge: ScanKnowledge;
26
+ scanRoot: string;
27
+ projectName: string;
28
+ cliVersion: string;
29
+ scannerVersion: string;
30
+ scannedAt?: string;
31
+ }
32
+ /** Write facts.json and data-items/. answers.json is not touched. */
33
+ export declare function writeScanFacts(layout: OutputLayout, options: WriteScanFactsOptions): import("../facts/build-facts").BuiltFacts;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.graphifyCacheDir = graphifyCacheDir;
7
+ exports.prepareScanKnowledge = prepareScanKnowledge;
8
+ exports.buildScanHierarchy = buildScanHierarchy;
9
+ exports.writeScanFacts = writeScanFacts;
10
+ /**
11
+ * What a scan writes besides dataflow.json (DATAP-735):
12
+ *
13
+ * facts.json Facts from this scan, replaced on every scan
14
+ * data-items/*.json one file per data item, with its occurrences
15
+ * graphify.json Graphify's code-structure graph (graph.json, renamed)
16
+ *
17
+ * Graphify (https://github.com/Graphify-Labs/graphify) maps the code; the scanner's
18
+ * knowledge graph links Facts to those code nodes. The graph is built in memory and only
19
+ * feeds facts.json (code refs, relations) and the C4 hierarchy. Problems here are
20
+ * warnings; they never fail the scan or block dataflow.json.
21
+ */
22
+ const crypto_1 = require("crypto");
23
+ const fs_1 = __importDefault(require("fs"));
24
+ const os_1 = __importDefault(require("os"));
25
+ const path_1 = __importDefault(require("path"));
26
+ const scanner_1 = require("../../vendor/scanner/dist/src/index.js");
27
+ const build_facts_1 = require("../facts/build-facts");
28
+ const io_1 = require("../facts/io");
29
+ const c4_hierarchy_1 = require("./c4-hierarchy");
30
+ function warn(message) {
31
+ console.warn(`[scan] ${message}`);
32
+ }
33
+ /**
34
+ * Where Graphify keeps its working files and cache between scans, outside the output
35
+ * folder: `~/.cache/dataparade/graphify/<hash of the scan root>`.
36
+ */
37
+ function graphifyCacheDir(scanRoot, env = process.env) {
38
+ const base = env.DATAPARADE_CACHE_DIR?.trim() ||
39
+ path_1.default.join(env.XDG_CACHE_HOME?.trim() || path_1.default.join(os_1.default.homedir(), '.cache'), 'dataparade');
40
+ const hash = (0, crypto_1.createHash)('sha256')
41
+ .update(path_1.default.resolve(scanRoot))
42
+ .digest('hex')
43
+ .slice(0, 16);
44
+ return path_1.default.join(base, 'graphify', hash);
45
+ }
46
+ /** The cache folder, or a temporary one when the home folder is not writable (e.g. Lambda). */
47
+ function usableGraphifyCacheDir(scanRoot) {
48
+ const preferred = graphifyCacheDir(scanRoot);
49
+ try {
50
+ fs_1.default.mkdirSync(preferred, { recursive: true });
51
+ return preferred;
52
+ }
53
+ catch {
54
+ return fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'dataparade-graphify-'));
55
+ }
56
+ }
57
+ /**
58
+ * Run Graphify (unless disabled), copy its graph to graphify.json, and build the knowledge
59
+ * graph. A stale graphify.json from an earlier scan is removed first.
60
+ */
61
+ async function prepareScanKnowledge(result, scanRoot, layout, options) {
62
+ fs_1.default.rmSync(layout.graphifyPath, { force: true });
63
+ let enriched = result;
64
+ if (options.structureGraph) {
65
+ try {
66
+ const structure = await (0, scanner_1.runGraphify)(scanRoot, {
67
+ outDir: usableGraphifyCacheDir(scanRoot),
68
+ });
69
+ for (const warning of structure.warnings)
70
+ warn(warning);
71
+ if (structure.info) {
72
+ fs_1.default.mkdirSync(path_1.default.dirname(layout.graphifyPath), { recursive: true });
73
+ fs_1.default.copyFileSync(structure.info.path, layout.graphifyPath);
74
+ enriched = { ...result, structureGraph: structure.info };
75
+ console.log(`[scan] code-structure graph (graphify ${structure.info.version}) written to ${layout.graphifyPath}`);
76
+ }
77
+ }
78
+ catch (error) {
79
+ warn(`warning: code-structure graph not written: ${error instanceof Error ? error.message : String(error)}`);
80
+ }
81
+ }
82
+ try {
83
+ return { result: enriched, graph: await (0, scanner_1.buildDataParadeGraph)(enriched) };
84
+ }
85
+ catch (error) {
86
+ warn(`warning: knowledge graph not built: ${error instanceof Error ? error.message : String(error)}`);
87
+ return { result: enriched };
88
+ }
89
+ }
90
+ /** C4 hierarchy for `dataflow.json` metadata, from the knowledge graph. */
91
+ function buildScanHierarchy(graph, graphNodeIds) {
92
+ if (!graph)
93
+ return undefined;
94
+ try {
95
+ return (0, c4_hierarchy_1.buildDataflowHierarchy)(graph, graphNodeIds);
96
+ }
97
+ catch (error) {
98
+ warn(`warning: C4 hierarchy not computed: ${error instanceof Error ? error.message : String(error)}`);
99
+ return undefined;
100
+ }
101
+ }
102
+ /** Write facts.json and data-items/. answers.json is not touched. */
103
+ function writeScanFacts(layout, options) {
104
+ const built = (0, build_facts_1.buildFacts)({
105
+ result: options.knowledge.result,
106
+ graph: options.knowledge.graph,
107
+ scanRoot: options.scanRoot,
108
+ projectName: options.projectName,
109
+ cliVersion: options.cliVersion,
110
+ scannerVersion: options.scannerVersion,
111
+ scannedAt: options.scannedAt,
112
+ });
113
+ (0, io_1.writeFactsOutput)(layout, built.facts, built.dataItemFiles);
114
+ return built;
115
+ }
@@ -2,7 +2,38 @@ export type ScanFootprintEstimate = {
2
2
  fileCount: number;
3
3
  bytesIngested: number;
4
4
  };
5
+ /** Files and folders the scan will walk, with the share of each top-level folder. */
6
+ export type ScanTreeSummary = {
7
+ fileCount: number;
8
+ directoryCount: number;
9
+ bytes: number;
10
+ /** True when the walk stopped at {@link MAX_FILES_TO_MEASURE} files. */
11
+ capped: boolean;
12
+ /** Top-level folders under the scan root, largest file count first. */
13
+ topLevelFolders: {
14
+ name: string;
15
+ fileCount: number;
16
+ bytes: number;
17
+ }[];
18
+ };
5
19
  /**
6
20
  * Cheap footprint for platform quota preflight (same idea as hosted zip/git estimates).
7
21
  */
8
22
  export declare function estimateScanFootprint(scanRootDir: string, excludePaths?: string[]): Promise<ScanFootprintEstimate>;
23
+ /**
24
+ * Count the files and folders a scan walks. Prunes the same directories as the scanner's
25
+ * ingest: default excluded names, hidden folders, `--exclude` patterns and `.gitignore`.
26
+ */
27
+ export declare function summarizeScanTree(scanRootDir: string, excludePaths?: string[]): Promise<ScanTreeSummary>;
28
+ /**
29
+ * The scanner reads at most 20,000 files and 200 MB of source per scan (its ingest caps,
30
+ * DEFAULT_MAX_FILE_COUNT and DEFAULT_MAX_TOTAL_BYTES). A tree above either limit is
31
+ * scanned only in part and needs the most time and memory, so it gets a warning.
32
+ */
33
+ export declare const LARGE_TREE_FILE_COUNT = 20000;
34
+ export declare const LARGE_TREE_BYTES: number;
35
+ /** One line with the counts, plus a warning when the tree is very large. */
36
+ export declare function describeScanTree(summary: ScanTreeSummary): {
37
+ line: string;
38
+ warning?: string;
39
+ };
@@ -33,7 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.LARGE_TREE_BYTES = exports.LARGE_TREE_FILE_COUNT = void 0;
36
37
  exports.estimateScanFootprint = estimateScanFootprint;
38
+ exports.summarizeScanTree = summarizeScanTree;
39
+ exports.describeScanTree = describeScanTree;
37
40
  const fs_1 = require("fs");
38
41
  const path = __importStar(require("path"));
39
42
  const scanner_1 = require("../../vendor/scanner/dist/src/index.js");
@@ -83,6 +86,7 @@ async function walkFootprint(currentDir, rootDir, accumulatedRules, excludePaths
83
86
  }
84
87
  if ((0, scanner_1.isPathIgnored)(entryPath, true, rules))
85
88
  continue;
89
+ state.directoryCount += 1;
86
90
  await walkFootprint(entryPath, rootDir, rules, excludePaths, state);
87
91
  }
88
92
  else if (entry.isFile()) {
@@ -94,8 +98,17 @@ async function walkFootprint(currentDir, rootDir, accumulatedRules, excludePaths
94
98
  continue;
95
99
  try {
96
100
  const stat = await fs_1.promises.stat(entryPath);
101
+ const size = Math.max(0, stat.size);
97
102
  state.fileCount += 1;
98
- state.bytesIngested += Math.max(0, stat.size);
103
+ state.bytesIngested += size;
104
+ const slash = relativePath.indexOf("/");
105
+ if (slash > 0) {
106
+ const name = relativePath.slice(0, slash);
107
+ const folder = state.topLevel.get(name) ?? { fileCount: 0, bytes: 0 };
108
+ folder.fileCount += 1;
109
+ folder.bytes += size;
110
+ state.topLevel.set(name, folder);
111
+ }
99
112
  if (state.fileCount >= MAX_FILES_TO_MEASURE) {
100
113
  state.capped = true;
101
114
  }
@@ -106,14 +119,74 @@ async function walkFootprint(currentDir, rootDir, accumulatedRules, excludePaths
106
119
  }
107
120
  }
108
121
  }
122
+ function newWalkState() {
123
+ return {
124
+ fileCount: 0,
125
+ bytesIngested: 0,
126
+ directoryCount: 0,
127
+ capped: false,
128
+ topLevel: new Map(),
129
+ };
130
+ }
109
131
  /**
110
132
  * Cheap footprint for platform quota preflight (same idea as hosted zip/git estimates).
111
133
  */
112
134
  async function estimateScanFootprint(scanRootDir, excludePaths = []) {
113
- const state = { fileCount: 0, bytesIngested: 0, capped: false };
135
+ const state = newWalkState();
114
136
  await walkFootprint(scanRootDir, scanRootDir, [], excludePaths, state);
115
137
  return {
116
138
  fileCount: Math.max(1, state.fileCount),
117
139
  bytesIngested: Math.max(0, state.bytesIngested),
118
140
  };
119
141
  }
142
+ /**
143
+ * Count the files and folders a scan walks. Prunes the same directories as the scanner's
144
+ * ingest: default excluded names, hidden folders, `--exclude` patterns and `.gitignore`.
145
+ */
146
+ async function summarizeScanTree(scanRootDir, excludePaths = []) {
147
+ const state = newWalkState();
148
+ await walkFootprint(scanRootDir, scanRootDir, [], [...scanner_1.DEFAULT_EXCLUDED_FILE_GLOBS, ...excludePaths], state);
149
+ return {
150
+ fileCount: state.fileCount,
151
+ directoryCount: state.directoryCount,
152
+ bytes: state.bytesIngested,
153
+ capped: state.capped,
154
+ topLevelFolders: [...state.topLevel.entries()]
155
+ .map(([name, folder]) => ({ name, ...folder }))
156
+ .sort((a, b) => b.fileCount - a.fileCount || a.name.localeCompare(b.name)),
157
+ };
158
+ }
159
+ /**
160
+ * The scanner reads at most 20,000 files and 200 MB of source per scan (its ingest caps,
161
+ * DEFAULT_MAX_FILE_COUNT and DEFAULT_MAX_TOTAL_BYTES). A tree above either limit is
162
+ * scanned only in part and needs the most time and memory, so it gets a warning.
163
+ */
164
+ exports.LARGE_TREE_FILE_COUNT = 20_000;
165
+ exports.LARGE_TREE_BYTES = 200 * 1024 * 1024;
166
+ function formatCount(n) {
167
+ return n.toLocaleString("en-US");
168
+ }
169
+ function formatMegabytes(bytes) {
170
+ return `${Math.round(bytes / (1024 * 1024))} MB`;
171
+ }
172
+ /** One line with the counts, plus a warning when the tree is very large. */
173
+ function describeScanTree(summary) {
174
+ const files = `${formatCount(summary.fileCount)}${summary.capped ? "+" : ""}`;
175
+ const line = `Scanning ${files} files in ${formatCount(summary.directoryCount)} folders (${formatMegabytes(summary.bytes)}).`;
176
+ const large = summary.capped ||
177
+ summary.fileCount > exports.LARGE_TREE_FILE_COUNT ||
178
+ summary.bytes > exports.LARGE_TREE_BYTES;
179
+ if (!large)
180
+ return { line };
181
+ const biggest = summary.topLevelFolders.slice(0, 3);
182
+ const named = biggest
183
+ .map((folder) => `${folder.name}/ (${formatCount(folder.fileCount)} files)`)
184
+ .join(", ");
185
+ const example = biggest.map((folder) => `'${folder.name}/**'`).join(" ");
186
+ const warning = `This is a large tree: the scan reads at most ${formatCount(exports.LARGE_TREE_FILE_COUNT)} files and ` +
187
+ `${formatMegabytes(exports.LARGE_TREE_BYTES)}, and may be slow or run out of memory.` +
188
+ (biggest.length > 0
189
+ ? ` The biggest folders are ${named}. If they hold no application code, skip them with --exclude ${example}.`
190
+ : "");
191
+ return { line, warning };
192
+ }
@@ -9,3 +9,8 @@ export declare function toApiReachabilityError(err: unknown, url: string, method
9
9
  * already attach the request target.
10
10
  */
11
11
  export declare function describeThrownError(err: unknown): string;
12
+ /**
13
+ * Short reason for an optional platform step (AI session, upload) that failed,
14
+ * for a one-line "… unavailable (<reason>)" message.
15
+ */
16
+ export declare function describeUnavailableReason(err: unknown): string;
@@ -5,6 +5,7 @@ exports.fetchFailureDetail = fetchFailureDetail;
5
5
  exports.describeRequestTarget = describeRequestTarget;
6
6
  exports.toApiReachabilityError = toApiReachabilityError;
7
7
  exports.describeThrownError = describeThrownError;
8
+ exports.describeUnavailableReason = describeUnavailableReason;
8
9
  const TRANSIENT_CAUSE_CODES = new Set([
9
10
  'ECONNRESET',
10
11
  'ECONNREFUSED',
@@ -83,3 +84,15 @@ function describeThrownError(err) {
83
84
  }
84
85
  return `Could not reach the DataParade API: ${detail}. Run the scan again.`;
85
86
  }
87
+ /**
88
+ * Short reason for an optional platform step (AI session, upload) that failed,
89
+ * for a one-line "… unavailable (<reason>)" message.
90
+ */
91
+ function describeUnavailableReason(err) {
92
+ if (!(err instanceof Error))
93
+ return 'unknown error';
94
+ if (isTransientFetchError(err)) {
95
+ return `could not reach the DataParade API: ${fetchFailureDetail(err)}`;
96
+ }
97
+ return err.message.trim().replace(/\.$/, '') || 'unknown error';
98
+ }
@@ -1,6 +1,11 @@
1
1
  import type { ScanUploadFile } from '../upload/collect-scan-sidecars';
2
2
  import type { CliAnonymousUploadPreviewResponse, CliUploadPreviewInput, CliUploadPreviewResponse } from './upload.types';
3
3
  export type { CliAnonymousUploadPreviewResponse, CliUploadPreviewInput, CliUploadPreviewResponse, } from './upload.types';
4
+ /** Upload rejected by the API; `status` is the HTTP status (429 = rate limit). */
5
+ export declare class CliUploadError extends Error {
6
+ readonly status: number;
7
+ constructor(message: string, status: number);
8
+ }
4
9
  export declare function cliUploadAnonymousPreview(input: {
5
10
  dataflow: unknown;
6
11
  projectName?: string;