@dataparade/cli 0.0.26 → 0.0.28

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 (108) hide show
  1. package/README.md +52 -12
  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.js +37 -37
  5. package/dist/src/discoveries/contract/ocsf-discovery-record.d.ts +1 -1
  6. package/dist/src/discoveries/load-ocsf-discoveries.d.ts +0 -8
  7. package/dist/src/discoveries/load-ocsf-discoveries.js +0 -31
  8. package/dist/src/discoveries/write-ocsf-discoveries.d.ts +0 -8
  9. package/dist/src/discoveries/write-ocsf-discoveries.js +0 -38
  10. package/dist/src/evals/run-model-matrix.js +0 -1
  11. package/dist/src/export/export-ocsf.d.ts +18 -0
  12. package/dist/src/export/export-ocsf.js +104 -0
  13. package/dist/src/export/register-export-commands.d.ts +2 -0
  14. package/dist/src/export/register-export-commands.js +30 -0
  15. package/dist/src/facts/apply-answers.d.ts +29 -0
  16. package/dist/src/facts/apply-answers.js +202 -0
  17. package/dist/src/facts/build-facts.d.ts +24 -0
  18. package/dist/src/facts/build-facts.js +198 -0
  19. package/dist/src/facts/io.d.ts +17 -0
  20. package/dist/src/facts/io.js +67 -0
  21. package/dist/src/facts/layout.d.ts +29 -0
  22. package/dist/src/facts/layout.js +38 -0
  23. package/dist/src/facts/schema.d.ts +265 -0
  24. package/dist/src/facts/schema.js +122 -0
  25. package/dist/src/facts/slug.d.ts +7 -0
  26. package/dist/src/facts/slug.js +47 -0
  27. package/dist/src/kb/brief.d.ts +1 -2
  28. package/dist/src/kb/brief.js +2 -4
  29. package/dist/src/kb/interview-record.d.ts +18 -0
  30. package/dist/src/kb/interview-record.js +70 -0
  31. package/dist/src/kb/kb-store.d.ts +24 -18
  32. package/dist/src/kb/kb-store.js +89 -28
  33. package/dist/src/kb/land.d.ts +32 -12
  34. package/dist/src/kb/land.js +97 -90
  35. package/dist/src/kb/migrate.d.ts +23 -0
  36. package/dist/src/kb/migrate.js +91 -0
  37. package/dist/src/kb/project-diagram.js +4 -4
  38. package/dist/src/kb/register-kb-commands.js +71 -20
  39. package/dist/src/observability/scan-sentry.js +0 -1
  40. package/dist/src/output/scan-output-excludes.d.ts +1 -1
  41. package/dist/src/output/scan-output-excludes.js +14 -5
  42. package/dist/src/output/write-scan-knowledge.d.ts +33 -0
  43. package/dist/src/output/write-scan-knowledge.js +115 -0
  44. package/dist/src/platform-api/estimate-scan-footprint.d.ts +31 -0
  45. package/dist/src/platform-api/estimate-scan-footprint.js +75 -2
  46. package/dist/src/ui/scan-progress-renderer.d.ts +2 -0
  47. package/dist/src/ui/scan-progress-renderer.js +10 -0
  48. package/dist/src/ui/teaching-lines.js +18 -6
  49. package/dist/src/upload/collect-scan-sidecars.d.ts +2 -27
  50. package/dist/src/upload/collect-scan-sidecars.js +25 -121
  51. package/dist/src/upload/run-upload.js +0 -3
  52. package/dist/tests/cli/cli.spec.js +30 -13
  53. package/dist/tests/helpers/facts-fixture.d.ts +9 -0
  54. package/dist/tests/helpers/facts-fixture.js +72 -0
  55. package/dist/tests/unit/export/export-ocsf.spec.js +72 -0
  56. package/dist/tests/unit/facts/apply-answers.spec.js +128 -0
  57. package/dist/tests/unit/facts/build-facts.spec.d.ts +1 -0
  58. package/dist/tests/unit/facts/build-facts.spec.js +161 -0
  59. package/dist/tests/unit/facts/slug.spec.d.ts +1 -0
  60. package/dist/tests/unit/facts/slug.spec.js +30 -0
  61. package/dist/tests/unit/kb/kb-interview-loop.spec.js +83 -35
  62. package/dist/tests/unit/kb/migrate.spec.d.ts +1 -0
  63. package/dist/tests/unit/kb/migrate.spec.js +108 -0
  64. package/dist/tests/unit/output/graphify-cache-dir.spec.d.ts +1 -0
  65. package/dist/tests/unit/output/graphify-cache-dir.spec.js +20 -0
  66. package/dist/tests/unit/output/scan-output-excludes.spec.js +4 -2
  67. package/dist/tests/unit/platform-api/estimate-scan-footprint.spec.js +77 -0
  68. package/dist/tests/unit/platform-api/upload-client.spec.js +2 -2
  69. package/dist/tests/unit/ui/teaching-lines.spec.js +16 -0
  70. package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +46 -46
  71. package/dist/tests/unit/upload/pack-scan-upload.spec.js +6 -6
  72. package/dist/vendor/scanner/dist/src/classifier/component-factory.js +6 -14
  73. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.d.ts +1 -0
  74. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.js +32 -1
  75. package/dist/vendor/scanner/dist/src/classifier/naming.d.ts +5 -0
  76. package/dist/vendor/scanner/dist/src/classifier/naming.js +8 -4
  77. package/dist/vendor/scanner/dist/src/core/pipeline/build-scan-personal-data-layers.js +26 -14
  78. package/dist/vendor/scanner/dist/src/core/pipeline/enrich-personal-data-layers.js +3 -1
  79. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.d.ts +18 -0
  80. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.js +125 -66
  81. package/dist/vendor/scanner/dist/src/index.d.ts +2 -0
  82. package/dist/vendor/scanner/dist/src/index.js +7 -2
  83. package/dist/vendor/scanner/dist/src/ingest/file-system.d.ts +5 -0
  84. package/dist/vendor/scanner/dist/src/ingest/file-system.js +5 -0
  85. package/dist/vendor/scanner/dist/src/ingest/gitignore.d.ts +17 -0
  86. package/dist/vendor/scanner/dist/src/ingest/gitignore.js +47 -9
  87. package/dist/vendor/scanner/dist/src/ingest/schema-files.d.ts +10 -2
  88. package/dist/vendor/scanner/dist/src/ingest/schema-files.js +24 -7
  89. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.d.ts +3 -0
  90. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.js +45 -0
  91. package/dist/vendor/scanner/dist/src/patterns/scan-exclusions.js +7 -0
  92. package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +8 -0
  93. package/dist/vendor/scanner/patterns/third-party.patterns.yaml +9 -0
  94. package/package.json +7 -7
  95. package/dist/src/discoveries/project-collected-diagram.d.ts +0 -7
  96. package/dist/src/discoveries/project-collected-diagram.js +0 -182
  97. package/dist/src/discoveries/project-ocsf-to-discoveries-document.d.ts +0 -16
  98. package/dist/src/discoveries/project-ocsf-to-discoveries-document.js +0 -269
  99. package/dist/src/discoveries/scan-result-to-discovery-input.d.ts +0 -13
  100. package/dist/src/discoveries/scan-result-to-discovery-input.js +0 -60
  101. package/dist/src/output/write-knowledge-graph.d.ts +0 -20
  102. package/dist/src/output/write-knowledge-graph.js +0 -53
  103. package/dist/src/output/write-scan-discoveries.d.ts +0 -17
  104. package/dist/src/output/write-scan-discoveries.js +0 -61
  105. package/dist/tests/unit/discoveries/project-collected-diagram.spec.js +0 -97
  106. package/dist/tests/unit/discoveries/rescan-replaces-scan-records.spec.js +0 -89
  107. /package/dist/tests/unit/{discoveries/project-collected-diagram.spec.d.ts → export/export-ocsf.spec.d.ts} +0 -0
  108. /package/dist/tests/unit/{discoveries/rescan-replaces-scan-records.spec.d.ts → facts/apply-answers.spec.d.ts} +0 -0
@@ -1,32 +1,38 @@
1
- import type { OcsfDiscoveryRecord } from "../discoveries/contract/ocsf-discovery-record";
2
1
  import type { A0DiscoveriesDocument } from "../discoveries/contract/discoveries-document.schema";
2
+ import { SYSTEM_FACT_ID, type AppliedState } from "../facts/apply-answers";
3
+ import { type OutputLayout } from "../facts/layout";
4
+ import type { Answer, DataItemFile, FactsFile } from "../facts/schema";
3
5
  /**
4
- * A project knowledge base on disk: the directory a scan wrote `dataflow.json`
5
- * into (`dataparade scan <repo> -o <kb>/dataflow.json`).
6
+ * A project knowledge base on disk: the folder a scan wrote dataflow.json into
7
+ * (`dataparade scan <repo> -o <kb>/dataflow.json`, default `.dataparade/`).
6
8
  *
7
- * <kb>/ocsf-discoveries/ Discovery records (scan + interview), one OCSF file each
8
- * <kb>/briefs/<sha>.json KB snapshots that interview questions were asked from
9
- * <kb>/evidence/ unedited interview transcripts
10
- * <kb>/diagram.json latest projection for the viewer
9
+ * <kb>/facts.json Facts from the latest scan
10
+ * <kb>/data-items/ one file per data item, with its occurrences
11
+ * <kb>/answers.json people's decisions; a scan never changes it
12
+ * <kb>/briefs/<sha>.json KB snapshots that interview questions were asked from
13
+ * <kb>/evidence/ unedited interview transcripts
14
+ * <kb>/diagram.json latest projection for the viewer
11
15
  */
12
- export interface KbPaths {
13
- root: string;
14
- discoveriesDir: string;
15
- briefsDir: string;
16
- evidenceDir: string;
17
- diagramPath: string;
18
- }
16
+ export type KbPaths = OutputLayout;
19
17
  export declare function resolveKbPaths(kbDir: string): KbPaths;
20
18
  export declare class KbError extends Error {
21
19
  readonly code: string;
22
20
  constructor(code: string, message: string);
23
21
  }
24
- export declare function loadKbRecords(paths: KbPaths): OcsfDiscoveryRecord[];
25
22
  export interface KbState {
26
- records: OcsfDiscoveryRecord[];
23
+ facts: FactsFile;
24
+ /** Data item files as the scan wrote them. */
25
+ dataItemFiles: DataItemFile[];
26
+ /** Everything in answers.json. */
27
+ answers: Answer[];
28
+ /** The scan with the answers applied. */
29
+ applied: AppliedState;
30
+ /** The applied state in the shape the brief and the diagram projection read. */
27
31
  document: A0DiscoveriesDocument;
28
- /** Interview answers about entities the latest scan no longer has. Kept on disk, not projected. */
29
- orphans: OcsfDiscoveryRecord[];
32
+ /** Answers about Facts the latest scan no longer has. Kept on disk, not projected. */
33
+ orphans: Answer[];
30
34
  }
35
+ export declare function appliedStateToDocument(applied: AppliedState): A0DiscoveriesDocument;
31
36
  export declare function loadKbState(paths: KbPaths): KbState;
32
37
  export declare function ensureDir(dir: string): void;
38
+ export { SYSTEM_FACT_ID };
@@ -3,25 +3,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.KbError = void 0;
6
+ exports.SYSTEM_FACT_ID = exports.KbError = void 0;
7
7
  exports.resolveKbPaths = resolveKbPaths;
8
- exports.loadKbRecords = loadKbRecords;
8
+ exports.appliedStateToDocument = appliedStateToDocument;
9
9
  exports.loadKbState = loadKbState;
10
10
  exports.ensureDir = ensureDir;
11
11
  const fs_1 = __importDefault(require("fs"));
12
- const path_1 = __importDefault(require("path"));
13
- const load_ocsf_discoveries_1 = require("../discoveries/load-ocsf-discoveries");
14
- const project_ocsf_to_discoveries_document_1 = require("../discoveries/project-ocsf-to-discoveries-document");
15
- const write_scan_discoveries_1 = require("../output/write-scan-discoveries");
12
+ const apply_answers_1 = require("../facts/apply-answers");
13
+ Object.defineProperty(exports, "SYSTEM_FACT_ID", { enumerable: true, get: function () { return apply_answers_1.SYSTEM_FACT_ID; } });
14
+ const io_1 = require("../facts/io");
15
+ const layout_1 = require("../facts/layout");
16
16
  function resolveKbPaths(kbDir) {
17
- const root = path_1.default.resolve(kbDir);
18
- return {
19
- root,
20
- discoveriesDir: path_1.default.join(root, write_scan_discoveries_1.SCAN_OCSF_DISCOVERIES_DIRNAME),
21
- briefsDir: path_1.default.join(root, "briefs"),
22
- evidenceDir: path_1.default.join(root, "evidence"),
23
- diagramPath: path_1.default.join(root, "diagram.json"),
24
- };
17
+ return (0, layout_1.layoutForDir)(kbDir);
25
18
  }
26
19
  class KbError extends Error {
27
20
  constructor(code, message) {
@@ -31,26 +24,94 @@ class KbError extends Error {
31
24
  }
32
25
  }
33
26
  exports.KbError = KbError;
34
- function loadKbRecords(paths) {
27
+ /** An override may arrive as a list, or as the JSON text of one. */
28
+ function asStringList(value) {
29
+ if (Array.isArray(value))
30
+ return value.filter((v) => typeof v === "string");
31
+ if (typeof value === "string" && value.startsWith("[")) {
32
+ try {
33
+ return asStringList(JSON.parse(value));
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ return undefined;
40
+ }
41
+ function asString(value) {
42
+ return typeof value === "string" && value ? value : undefined;
43
+ }
44
+ function appliedStateToDocument(applied) {
45
+ const itemsByComponent = new Map();
46
+ for (const item of applied.facts.dataItems) {
47
+ for (const group of item.groups) {
48
+ for (const componentId of group.handledBy) {
49
+ const set = itemsByComponent.get(componentId) ?? new Set();
50
+ set.add(item.id);
51
+ itemsByComponent.set(componentId, set);
52
+ }
53
+ }
54
+ }
55
+ const inScope = asString(applied.system.in_scope);
56
+ return {
57
+ components: applied.facts.components.map((c) => {
58
+ const extra = c;
59
+ const actorKind = asString(extra.actor_kind);
60
+ return {
61
+ id: c.id,
62
+ name: c.name,
63
+ type: c.type,
64
+ subType: c.subType,
65
+ confidence: c.confidence,
66
+ sourceLocations: c.sourceLocations,
67
+ dataItemIds: [...(itemsByComponent.get(c.id) ?? [])].sort(),
68
+ ...(actorKind ? { actor_kind: actorKind } : {}),
69
+ };
70
+ }),
71
+ dataFlows: applied.facts.dataFlows.map((f) => {
72
+ const extra = f;
73
+ const categories = asStringList(extra.data_categories);
74
+ const purpose = asString(extra.purpose);
75
+ return {
76
+ id: f.id,
77
+ sourceComponentId: f.sourceComponentId,
78
+ targetComponentId: f.targetComponentId,
79
+ type: f.type,
80
+ confidence: f.confidence,
81
+ ...(f.targetScope !== undefined ? { targetScope: f.targetScope } : {}),
82
+ ...(categories ? { data_categories: categories } : {}),
83
+ ...(purpose ? { purpose } : {}),
84
+ };
85
+ }),
86
+ dataItems: applied.dataItemFiles.map((file) => ({
87
+ id: file.id,
88
+ occurrenceIds: file.occurrences.map((o) => o.id),
89
+ })),
90
+ occurrences: applied.dataItemFiles.flatMap((file) => file.occurrences.map((o) => ({
91
+ id: o.id,
92
+ filePath: o.filePath,
93
+ startLine: o.startLine,
94
+ endLine: o.endLine,
95
+ ...(o.code !== undefined ? { code: o.code } : {}),
96
+ }))),
97
+ ...(inScope ? { system: { in_scope: inScope } } : {}),
98
+ };
99
+ }
100
+ function loadKbState(paths) {
101
+ let facts;
35
102
  try {
36
- return (0, load_ocsf_discoveries_1.loadOcsfDiscoveriesFromDir)(paths.discoveriesDir).records;
103
+ facts = (0, io_1.readFacts)(paths);
37
104
  }
38
105
  catch (error) {
39
- if (error instanceof load_ocsf_discoveries_1.OcsfDiscoveryLoadError && ["EMPTY_DIRECTORY", "MISSING_DIRECTORY"].includes(error.code)) {
40
- throw new KbError("NO_KB", `No knowledge base at ${paths.root}. Scan first: dataparade scan <repo> -o ${path_1.default.join(paths.root, "dataflow.json")}`);
106
+ if (error instanceof io_1.FactsError && error.code === "NO_KB") {
107
+ throw new KbError("NO_KB", error.message);
41
108
  }
42
109
  throw error;
43
110
  }
44
- }
45
- function loadKbState(paths) {
46
- const records = loadKbRecords(paths);
47
- const orphans = [];
48
- const document = (0, project_ocsf_to_discoveries_document_1.projectOcsfToDiscoveriesDocument)({
49
- records,
50
- orphanInterviewRecords: "skip",
51
- onOrphanInterviewRecord: (record) => orphans.push(record),
52
- });
53
- return { records, document, orphans };
111
+ const dataItemFiles = (0, io_1.readDataItemFiles)(paths, facts);
112
+ const answers = (0, io_1.readAnswers)(paths).answers;
113
+ const applied = (0, apply_answers_1.applyAnswers)(facts, dataItemFiles, answers);
114
+ return { facts, dataItemFiles, answers, applied, document: appliedStateToDocument(applied), orphans: applied.orphans };
54
115
  }
55
116
  function ensureDir(dir) {
56
117
  fs_1.default.mkdirSync(dir, { recursive: true });
@@ -1,8 +1,8 @@
1
+ import type { Answer } from "../facts/schema";
1
2
  import { type KbPaths } from "./kb-store";
2
- import { type InterviewSlot } from "./slot-shapes";
3
3
  export interface LandInterviewAnswerInput {
4
4
  briefSha: string;
5
- /** A scan entity URI from the brief, a bare entity id (`flow_ab12…`), or `dp:a0/system`. */
5
+ /** A Fact id from the brief (`flow_ab12…`), or `dp:a0/system`. */
6
6
  target: string;
7
7
  slot: string;
8
8
  value: string;
@@ -15,19 +15,39 @@ export interface LandInterviewAnswerInput {
15
15
  now?: Date;
16
16
  dryRun?: boolean;
17
17
  }
18
- export interface LandedInterviewAnswer {
19
- uid: string;
18
+ export interface LandedAnswer {
19
+ /** The id of the new entry in answers.json. */
20
+ id: string;
21
+ /** answers.json, or null on a dry run. */
20
22
  path: string | null;
21
- asserts: string;
22
- slot: InterviewSlot;
23
- value: string;
23
+ answer: Answer;
24
+ /** The id of the earlier answer for the same Fact and property that this one replaces. */
24
25
  supersedes: string | null;
25
26
  dryRun: boolean;
26
27
  }
28
+ export type LandedInterviewAnswer = LandedAnswer;
29
+ /**
30
+ * Land one developer-confirmed interview answer in answers.json (`source=interview`).
31
+ * Every check from the write-back rules runs here so an agent can't land an invented
32
+ * value, an unconfirmed answer, or a fact the scan owns.
33
+ */
34
+ export declare function landInterviewAnswer(paths: KbPaths, input: LandInterviewAnswerInput): LandedAnswer;
35
+ export interface LandReviewAnswerInput {
36
+ /** The Fact the decision is about (a component, flow, data item, group or occurrence id). */
37
+ target: string;
38
+ action: "set" | "remove";
39
+ /** For `set`: the property to override. */
40
+ property?: string;
41
+ /** For `set`: the new value. A value starting with `[` or `{` is read as JSON, anything else is text. */
42
+ value?: string;
43
+ reviewer: string;
44
+ /** Why: a note, a link, or a path relative to the KB root. */
45
+ evidence?: string;
46
+ now?: Date;
47
+ dryRun?: boolean;
48
+ }
27
49
  /**
28
- * Land one confirmed interview answer as an OCSF Architecture Discovery
29
- * (`source=interview`). Every check from the write-back rules runs here so an
30
- * agent can't land an invented value, an unconfirmed answer, or a fact the
31
- * scan owns.
50
+ * Land a reviewer's decision about a scan Fact: override one property (`set`) or drop the
51
+ * Fact (`remove`). Interview answers go through {@link landInterviewAnswer} instead.
32
52
  */
33
- export declare function landInterviewAnswer(paths: KbPaths, input: LandInterviewAnswerInput): LandedInterviewAnswer;
53
+ export declare function landReviewAnswer(paths: KbPaths, input: LandReviewAnswerInput): LandedAnswer;
@@ -4,12 +4,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.landInterviewAnswer = landInterviewAnswer;
7
+ exports.landReviewAnswer = landReviewAnswer;
8
+ const crypto_1 = require("crypto");
7
9
  const fs_1 = __importDefault(require("fs"));
8
10
  const path_1 = __importDefault(require("path"));
9
- const ocsf_pins_1 = require("../discoveries/contract/ocsf-pins");
10
- const ontology_pins_1 = require("../discoveries/contract/ontology-pins");
11
- const scan_entity_uri_1 = require("../discoveries/scan-entity-uri");
12
- const write_ocsf_discoveries_1 = require("../discoveries/write-ocsf-discoveries");
11
+ const apply_answers_1 = require("../facts/apply-answers");
12
+ const io_1 = require("../facts/io");
13
13
  const brief_1 = require("./brief");
14
14
  const kb_store_1 = require("./kb-store");
15
15
  const slot_shapes_1 = require("./slot-shapes");
@@ -17,115 +17,122 @@ const slot_shapes_1 = require("./slot-shapes");
17
17
  const AUTO_REVIEWER_RE = /^(gpt|claude|composer|model|agent|auto|rubric|the room|coding agent)/i;
18
18
  /** Eval artifacts and mapped/scripted transcripts are never landable evidence. */
19
19
  const REJECTED_EVIDENCE_RE = /experiments\/datap-|\/eval\/|fixtures\/|mapped-transcript|stakeholder-script|discovery-export-bundle|raw-model-transcript/i;
20
+ function newAnswerId(now) {
21
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "");
22
+ return `ans_${stamp}_${(0, crypto_1.randomBytes)(3).toString("hex")}`;
23
+ }
24
+ function requireHumanReviewer(reviewer) {
25
+ const value = reviewer.trim();
26
+ if (!value || AUTO_REVIEWER_RE.test(value) || !value.includes("@")) {
27
+ throw new kb_store_1.KbError("REVIEWER_NOT_HUMAN", `reviewer must be the developer who confirmed the answer (an email address); got '${reviewer}'.`);
28
+ }
29
+ return value;
30
+ }
20
31
  function resolveTarget(target, brief, slot) {
21
- if (target === slot_shapes_1.SYSTEM_ASSERTS_URI || target.startsWith("dp:"))
32
+ if (target === slot_shapes_1.SYSTEM_ASSERTS_URI)
33
+ return target;
34
+ if (brief.questions.some((q) => q.slot === slot && q.asserts === target))
22
35
  return target;
23
- const matches = brief.questions.filter((q) => q.slot === slot && q.asserts !== slot_shapes_1.SYSTEM_ASSERTS_URI && (0, scan_entity_uri_1.parseScanEntityAsserts)(q.asserts)?.entityId === target);
24
- if (matches.length === 1)
25
- return matches[0].asserts;
26
- if (matches.length > 1) {
27
- throw new kb_store_1.KbError("AMBIGUOUS_TARGET", `${target} exists under several scan paths; pass the full asserts URI from the brief.`);
28
- }
29
36
  throw new kb_store_1.KbError("NOT_ASKABLE", `${target} has no '${slot}' question in this brief; check the id against 'dataparade kb brief'.`);
30
37
  }
31
- function landDate(now) {
32
- return now.toISOString().slice(0, 10).replace(/-/g, "");
38
+ /** The latest earlier answer for the same Fact and property. */
39
+ function previousAnswerId(answers, factId, property) {
40
+ const earlier = answers.filter((a) => a.factId === factId && a.action === "set" && a.property === property);
41
+ return earlier.sort((a, b) => Date.parse(b.at) - Date.parse(a.at))[0]?.id ?? null;
42
+ }
43
+ function store(paths, answer, supersedes, dryRun) {
44
+ if (!dryRun)
45
+ (0, io_1.appendAnswers)(paths, [answer]);
46
+ return { id: answer.id, path: dryRun ? null : paths.answersPath, answer, supersedes, dryRun: Boolean(dryRun) };
47
+ }
48
+ /** The slot value as answers.json keeps it: a list for data_categories, text otherwise. */
49
+ function storedSlotValue(slot, normalized) {
50
+ return slot === "data_categories" ? JSON.parse(normalized) : normalized;
33
51
  }
34
52
  /**
35
- * Land one confirmed interview answer as an OCSF Architecture Discovery
36
- * (`source=interview`). Every check from the write-back rules runs here so an
37
- * agent can't land an invented value, an unconfirmed answer, or a fact the
38
- * scan owns.
53
+ * Land one developer-confirmed interview answer in answers.json (`source=interview`).
54
+ * Every check from the write-back rules runs here so an agent can't land an invented
55
+ * value, an unconfirmed answer, or a fact the scan owns.
39
56
  */
40
57
  function landInterviewAnswer(paths, input) {
41
58
  if (!(0, slot_shapes_1.isInterviewSlot)(input.slot)) {
42
- throw new kb_store_1.KbError("SLOT_NOT_LANDABLE", `'${input.slot}' can't land from an interview. Landable slots: ${Object.keys(slot_shapes_1.SHAPE_FOR_SLOT).join(", ")}. Scan-asserted facts (names, endpoints, merges) need a human override instead.`);
59
+ throw new kb_store_1.KbError("SLOT_NOT_LANDABLE", `'${input.slot}' can't land from an interview. Landable slots: ${Object.keys(slot_shapes_1.SHAPE_FOR_SLOT).join(", ")}. Scan-asserted facts (names, endpoints, merges) need a human review instead (kb land --source review).`);
43
60
  }
44
61
  const slot = input.slot;
45
62
  const brief = (0, brief_1.readKbBrief)(paths, input.briefSha);
46
- const asserts = resolveTarget(input.target, brief, slot);
47
- if (!brief.questions.some((q) => q.asserts === asserts && q.slot === slot)) {
48
- throw new kb_store_1.KbError("NOT_ASKABLE", `Brief ${input.briefSha} has no '${slot}' question for ${asserts}.`);
49
- }
63
+ const factId = resolveTarget(input.target, brief, slot);
50
64
  const value = (0, slot_shapes_1.normalizeSlotValue)(slot, input.value);
51
- const reviewer = input.reviewer.trim();
52
- if (!reviewer || AUTO_REVIEWER_RE.test(reviewer) || !reviewer.includes("@")) {
53
- throw new kb_store_1.KbError("REVIEWER_NOT_HUMAN", `reviewer must be the developer who confirmed the answer (an email address); got '${input.reviewer}'.`);
54
- }
65
+ const reviewer = requireHumanReviewer(input.reviewer);
55
66
  if (!/^[0-9a-f]{40}$/.test(input.skillSha)) {
56
67
  throw new kb_store_1.KbError("BAD_SKILL_SHA", `skill SHA must be 40 hex characters; got '${input.skillSha}'.`);
57
68
  }
58
- const evidencePath = path_1.default.resolve(paths.root, input.evidence);
69
+ const evidencePath = path_1.default.resolve(paths.dir, input.evidence);
59
70
  if (!fs_1.default.existsSync(evidencePath) || !fs_1.default.statSync(evidencePath).isFile()) {
60
71
  throw new kb_store_1.KbError("NO_EVIDENCE", `Evidence transcript not found: ${evidencePath}`);
61
72
  }
62
- const evidenceRef = path_1.default.relative(paths.root, evidencePath).split(path_1.default.sep).join("/");
73
+ const evidenceRef = path_1.default.relative(paths.dir, evidencePath).split(path_1.default.sep).join("/");
63
74
  if (REJECTED_EVIDENCE_RE.test(evidenceRef)) {
64
75
  throw new kb_store_1.KbError("EVIDENCE_NOT_LANDABLE", `Eval or scripted transcripts can't be landing evidence: ${evidenceRef}`);
65
76
  }
66
- // A correction supersedes the latest earlier answer for the same slot.
67
- const existing = (0, kb_store_1.loadKbRecords)(paths).filter((r) => r.dataparade.source === "interview" && r.dataparade.asserts === asserts && r.dataparade.asserted_slot === slot);
68
- const supersededUids = new Set(existing.map((r) => r.dataparade.supersedes).filter(Boolean));
69
- const current = existing
70
- .filter((r) => !supersededUids.has(r.metadata.uid))
71
- .sort((a, b) => Date.parse(b.dataparade.asserted_at) - Date.parse(a.dataparade.asserted_at))[0];
77
+ const state = (0, kb_store_1.loadKbState)(paths);
72
78
  const now = input.now ?? new Date();
73
- const assertedAt = now.toISOString();
74
- const baseUid = `dp:discovery/interview/${(0, write_ocsf_discoveries_1.slugifyDiscoveryId)(asserts)}/${slot}/${landDate(now)}`;
75
- const takenUids = new Set(existing.map((r) => r.metadata.uid));
76
- let uid = baseUid;
77
- for (let n = 2; takenUids.has(uid); n++)
78
- uid = `${baseUid}-${n}`;
79
- const parsed = (0, scan_entity_uri_1.parseScanEntityAsserts)(asserts);
80
- const record = {
81
- class_name: "Architecture Discovery",
82
- class_uid: ocsf_pins_1.OCSF_ARCHITECTURE_DISCOVERY_CLASS_UID,
83
- category_name: "Architecture",
84
- category_uid: ocsf_pins_1.OCSF_ARCHITECTURE_CATEGORY_UID,
85
- activity_id: 1,
86
- activity_name: "Create",
87
- type_uid: ocsf_pins_1.OCSF_ARCHITECTURE_DISCOVERY_TYPE_UID,
88
- time: Math.floor(now.getTime() / 1000),
89
- metadata: {
90
- version: ocsf_pins_1.PINNED_OCSF_BASE_VERSION,
91
- uid,
92
- extension: { name: ocsf_pins_1.PINNED_OCSF_EXTENSION_NAME, version: ocsf_pins_1.PINNED_OCSF_EXTENSION_VERSION },
93
- product: { name: "dataparade-cli", vendor_name: "DataParade" },
94
- profiles: ["architecture_privacy"],
95
- },
96
- resources: [
97
- {
98
- uid: asserts,
99
- name: parsed?.entityId ?? asserts,
100
- type: asserts === slot_shapes_1.SYSTEM_ASSERTS_URI ? "system" : "entity",
101
- },
102
- ],
103
- dataparade: {
104
- record_kind: "discovery",
105
- ontology_version: ontology_pins_1.PINNED_ONTOLOGY_VERSION,
106
- source: "interview",
107
- asserted_at: assertedAt,
108
- asserts,
109
- asserted_slot: slot,
110
- asserted_value: value,
111
- eligible_shape: slot_shapes_1.SHAPE_FOR_SLOT[slot].shape,
112
- raw_evidence_ref: evidenceRef,
113
- reviewer,
114
- reviewed_at: assertedAt,
115
- brief_sha: input.briefSha,
116
- skill_sha: input.skillSha,
117
- ...(current ? { supersedes: current.metadata.uid } : {}),
118
- ...(parsed ? { related_resource_refs: [parsed.entityId] } : {}),
119
- },
79
+ const answer = {
80
+ id: newAnswerId(now),
81
+ factId,
82
+ action: "set",
83
+ property: slot,
84
+ value: storedSlotValue(slot, value),
85
+ by: reviewer,
86
+ at: now.toISOString(),
87
+ source: "interview",
88
+ evidence: evidenceRef,
89
+ briefSha: input.briefSha,
90
+ skillSha: input.skillSha,
120
91
  };
121
- const written = input.dryRun ? [] : (0, write_ocsf_discoveries_1.writeOcsfDiscoveryRecordsToDir)([record], paths.discoveriesDir);
122
- return {
123
- uid,
124
- path: written[0] ?? null,
125
- asserts,
126
- slot,
127
- value,
128
- supersedes: current?.metadata.uid ?? null,
129
- dryRun: Boolean(input.dryRun),
92
+ return store(paths, answer, previousAnswerId(state.answers, factId, slot), input.dryRun);
93
+ }
94
+ function parseReviewValue(value) {
95
+ const trimmed = value.trim();
96
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
97
+ try {
98
+ return JSON.parse(trimmed);
99
+ }
100
+ catch {
101
+ throw new kb_store_1.KbError("BAD_VALUE", `value looks like JSON but does not parse: ${value}`);
102
+ }
103
+ }
104
+ return value;
105
+ }
106
+ /**
107
+ * Land a reviewer's decision about a scan Fact: override one property (`set`) or drop the
108
+ * Fact (`remove`). Interview answers go through {@link landInterviewAnswer} instead.
109
+ */
110
+ function landReviewAnswer(paths, input) {
111
+ const reviewer = requireHumanReviewer(input.reviewer);
112
+ if (input.action === "set" && (!input.property || input.value === undefined)) {
113
+ throw new kb_store_1.KbError("BAD_ANSWER", "a 'set' answer needs both a property and a value.");
114
+ }
115
+ if (input.action === "remove" && (input.property || input.value !== undefined)) {
116
+ throw new kb_store_1.KbError("BAD_ANSWER", "a 'remove' answer takes no property or value.");
117
+ }
118
+ const state = (0, kb_store_1.loadKbState)(paths);
119
+ const now = input.now ?? new Date();
120
+ const answer = {
121
+ id: newAnswerId(now),
122
+ factId: input.target,
123
+ action: input.action,
124
+ ...(input.action === "set" ? { property: input.property, value: parseReviewValue(input.value ?? "") } : {}),
125
+ by: reviewer,
126
+ at: now.toISOString(),
127
+ source: "review",
128
+ ...(input.evidence ? { evidence: input.evidence } : {}),
130
129
  };
130
+ const trial = (0, apply_answers_1.applyAnswers)(state.facts, state.dataItemFiles, [answer]);
131
+ if (trial.orphans.length > 0) {
132
+ throw new kb_store_1.KbError("NO_SUCH_FACT", `${input.target} is not a Fact in this scan. Check the id in facts.json or the data item file.`);
133
+ }
134
+ if (trial.ignored.length > 0) {
135
+ throw new kb_store_1.KbError("NOT_LANDABLE", `'${input.property ?? "remove"}' can't be changed on ${input.target}.`);
136
+ }
137
+ return store(paths, answer, input.action === "set" ? previousAnswerId(state.answers, input.target, input.property) : null, input.dryRun);
131
138
  }
@@ -0,0 +1,23 @@
1
+ import { type KbPaths } from "./kb-store";
2
+ export interface MigrateResult {
3
+ from: string;
4
+ /** Interview records turned into answers. */
5
+ migrated: number;
6
+ /** Interview records already in answers.json from an earlier run. */
7
+ alreadyMigrated: number;
8
+ /** Scan records left behind: a scan regenerates them. */
9
+ scanRecordsDropped: number;
10
+ answerIds: string[];
11
+ dryRun: boolean;
12
+ }
13
+ /** Same record, same id, so running migrate twice adds nothing. */
14
+ export declare function migratedAnswerId(recordUid: string): string;
15
+ /**
16
+ * Convert the interview records in an old `ocsf-discoveries/` folder (CLI 0.0.26 and
17
+ * earlier) into entries of answers.json. Scan records are dropped; scanning again
18
+ * regenerates the Facts. The old folder is left as it is.
19
+ */
20
+ export declare function migrateInterviewRecords(paths: KbPaths, options?: {
21
+ from?: string;
22
+ dryRun?: boolean;
23
+ }): MigrateResult;
@@ -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");