@indigoai-us/hq-cli 5.345.247 → 5.345.250

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 (284) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/assets/lanes-hooks/hq-lanes-drain.sh +1 -1
  3. package/contracts/host-canary-release.json +14 -0
  4. package/dist/command-catalog.generated.d.ts +1198 -0
  5. package/dist/command-catalog.generated.js +1476 -0
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/core-job-run-native.js +4 -0
  9. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  10. package/dist/commands/core-knowledge-prefs.js +1 -16
  11. package/dist/commands/core.js +0 -2
  12. package/dist/commands/daemon.js +21 -0
  13. package/dist/commands/lanes-hold.js +7 -7
  14. package/dist/commands/lanes-resume.js +2 -2
  15. package/dist/commands/lanes-review.js +1 -1
  16. package/dist/commands/lanes-session-start.d.ts +1 -1
  17. package/dist/commands/lanes-session-start.js +3 -3
  18. package/dist/commands/lanes-shared.d.ts +1 -1
  19. package/dist/commands/lanes.d.ts +2 -2
  20. package/dist/commands/lanes.js +50 -50
  21. package/dist/commands/mesh.d.ts +25 -0
  22. package/dist/commands/mesh.js +48 -8
  23. package/dist/commands/ontology-graph.d.ts +63 -0
  24. package/dist/commands/ontology-graph.js +470 -0
  25. package/dist/commands/sync-core.js +6 -0
  26. package/dist/fast-scaffold.js +1 -3
  27. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  28. package/dist/hq-cloud-sync-runner/package.json +1 -1
  29. package/dist/index.d.ts +8 -0
  30. package/dist/index.js +48 -1
  31. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  32. package/dist/lanes-monitor-check-argv.js +1 -1
  33. package/dist/lanes-monitor-check-fast.d.ts +1 -1
  34. package/dist/lanes-monitor-check-fast.js +1 -1
  35. package/dist/lanes-session-start-argv.d.ts +1 -1
  36. package/dist/lanes-session-start-argv.js +1 -1
  37. package/dist/lib/capacity/sign-in.d.ts +1 -1
  38. package/dist/lib/capacity/sign-in.js +1 -1
  39. package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
  40. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  41. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  42. package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
  43. package/dist/lib/daemon/lanes-monitor-state.js +2 -2
  44. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  45. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  46. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  47. package/dist/lib/daemon/machine-checks.js +10 -0
  48. package/dist/lib/daemon/merge-sections.d.ts +3 -3
  49. package/dist/lib/daemon/merge-sections.js +7 -7
  50. package/dist/lib/daemon/remote-control-pools.js +1 -1
  51. package/dist/lib/daemon/run.d.ts +3 -1
  52. package/dist/lib/daemon/run.js +49 -6
  53. package/dist/lib/daemon/state-file.d.ts +1 -1
  54. package/dist/lib/daemon/state-file.js +1 -1
  55. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  56. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  57. package/dist/lib/flag-snapshot-file.d.ts +2 -0
  58. package/dist/lib/flag-snapshot-file.js +118 -48
  59. package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
  60. package/dist/lib/hook-engine/canary-gate.js +138 -6
  61. package/dist/lib/hook-engine/coverage.d.ts +82 -13
  62. package/dist/lib/hook-engine/coverage.js +214 -18
  63. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  64. package/dist/lib/hook-engine/registration-identity.js +1 -1
  65. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  66. package/dist/lib/hook-engine/resolve.js +48 -1
  67. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  68. package/dist/lib/hook-engine/stable-heal.js +214 -0
  69. package/dist/lib/hot-channels/graph-context.d.ts +105 -0
  70. package/dist/lib/hot-channels/graph-context.js +380 -0
  71. package/dist/lib/hot-channels/signals-pass.js +27 -1
  72. package/dist/lib/lanes/claude-credential.d.ts +1 -1
  73. package/dist/lib/lanes/claude-credential.js +1 -1
  74. package/dist/lib/lanes/delivery-core.d.ts +1 -1
  75. package/dist/lib/lanes/delivery-core.js +1 -1
  76. package/dist/lib/lanes/delivery.d.ts +10 -10
  77. package/dist/lib/lanes/delivery.js +8 -8
  78. package/dist/lib/lanes/dropbox.d.ts +1 -1
  79. package/dist/lib/lanes/dropbox.js +1 -1
  80. package/dist/lib/lanes/hooks-install.js +2 -2
  81. package/dist/lib/lanes/index.d.ts +1 -1
  82. package/dist/lib/lanes/index.js +1 -1
  83. package/dist/lib/lanes/monitor.js +1 -1
  84. package/dist/lib/lanes/quota-notice.js +1 -1
  85. package/dist/lib/lanes/quota.d.ts +1 -1
  86. package/dist/lib/lanes/quota.js +1 -1
  87. package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
  88. package/dist/lib/lanes/repo-merge-hold.js +2 -2
  89. package/dist/lib/lanes/spawn.d.ts +4 -4
  90. package/dist/lib/lanes/spawn.js +5 -5
  91. package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
  92. package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
  93. package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
  94. package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
  95. package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
  96. package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
  97. package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
  98. package/dist/lib/mesh/live/daemon/run.js +35 -2
  99. package/dist/lib/mesh/live/direct-drain.js +1 -1
  100. package/dist/lib/mesh/live/emit.d.ts +3 -0
  101. package/dist/lib/mesh/live/emit.js +32 -9
  102. package/dist/lib/mesh/live/flush.d.ts +3 -0
  103. package/dist/lib/mesh/live/flush.js +115 -32
  104. package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
  105. package/dist/lib/mesh/live/liveness-carry.js +1 -1
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
  107. package/dist/lib/mesh/live/reporting-privacy.js +235 -11
  108. package/dist/lib/mesh/live/spool.d.ts +17 -2
  109. package/dist/lib/mesh/live/spool.js +22 -6
  110. package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
  111. package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
  112. package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
  113. package/dist/lib/ontology-graph/legacy/index.js +1150 -0
  114. package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
  115. package/dist/lib/ontology-graph/legacy/parse.js +126 -0
  116. package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
  117. package/dist/lib/ontology-graph/legacy/report.js +254 -0
  118. package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
  119. package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
  120. package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
  121. package/dist/lib/ontology-graph/lint/checks.js +717 -0
  122. package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
  123. package/dist/lib/ontology-graph/lint/coverage.js +241 -0
  124. package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
  125. package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
  126. package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
  127. package/dist/lib/ontology-graph/lint/index.js +176 -0
  128. package/dist/lib/ontology-graph/model/files.d.ts +20 -0
  129. package/dist/lib/ontology-graph/model/files.js +89 -0
  130. package/dist/lib/ontology-graph/model/index.d.ts +65 -0
  131. package/dist/lib/ontology-graph/model/index.js +100 -0
  132. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
  133. package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
  134. package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
  135. package/dist/lib/ontology-graph/model/pass.js +958 -0
  136. package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
  137. package/dist/lib/ontology-graph/model/runner.js +160 -0
  138. package/dist/lib/ontology-graph/model/step.d.ts +197 -0
  139. package/dist/lib/ontology-graph/model/step.js +526 -0
  140. package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
  141. package/dist/lib/ontology-graph/model/tasks.js +349 -0
  142. package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
  143. package/dist/lib/ontology-graph/not-implemented.js +8 -0
  144. package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
  145. package/dist/lib/ontology-graph/org/compare.js +239 -0
  146. package/dist/lib/ontology-graph/org/derive.d.ts +67 -0
  147. package/dist/lib/ontology-graph/org/derive.js +359 -0
  148. package/dist/lib/ontology-graph/org/index.d.ts +102 -0
  149. package/dist/lib/ontology-graph/org/index.js +630 -0
  150. package/dist/lib/ontology-graph/org/load.d.ts +31 -0
  151. package/dist/lib/ontology-graph/org/load.js +476 -0
  152. package/dist/lib/ontology-graph/org/role.d.ts +38 -0
  153. package/dist/lib/ontology-graph/org/role.js +268 -0
  154. package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
  155. package/dist/lib/ontology-graph/org/structure.js +437 -0
  156. package/dist/lib/ontology-graph/org/text.d.ts +97 -0
  157. package/dist/lib/ontology-graph/org/text.js +321 -0
  158. package/dist/lib/ontology-graph/org/types.d.ts +457 -0
  159. package/dist/lib/ontology-graph/org/types.js +80 -0
  160. package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
  161. package/dist/lib/ontology-graph/pages/index.js +193 -0
  162. package/dist/lib/ontology-graph/pages/render.d.ts +144 -0
  163. package/dist/lib/ontology-graph/pages/render.js +688 -0
  164. package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
  165. package/dist/lib/ontology-graph/proposals/apply.js +468 -0
  166. package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
  167. package/dist/lib/ontology-graph/proposals/group.js +232 -0
  168. package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
  169. package/dist/lib/ontology-graph/proposals/index.js +474 -0
  170. package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
  171. package/dist/lib/ontology-graph/proposals/model.js +196 -0
  172. package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
  173. package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
  174. package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
  175. package/dist/lib/ontology-graph/read/brief.js +254 -0
  176. package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
  177. package/dist/lib/ontology-graph/read/graph-index.js +198 -0
  178. package/dist/lib/ontology-graph/read/index.d.ts +59 -0
  179. package/dist/lib/ontology-graph/read/index.js +803 -0
  180. package/dist/lib/ontology-graph/read/member.d.ts +7 -0
  181. package/dist/lib/ontology-graph/read/member.js +34 -0
  182. package/dist/lib/ontology-graph/read/names.d.ts +49 -0
  183. package/dist/lib/ontology-graph/read/names.js +297 -0
  184. package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
  185. package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
  186. package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
  187. package/dist/lib/ontology-graph/read/test-graph.js +150 -0
  188. package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
  189. package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
  190. package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
  191. package/dist/lib/ontology-graph/replay/config.js +105 -0
  192. package/dist/lib/ontology-graph/replay/engine.d.ts +146 -0
  193. package/dist/lib/ontology-graph/replay/engine.js +1240 -0
  194. package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
  195. package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
  196. package/dist/lib/ontology-graph/replay/index.d.ts +91 -0
  197. package/dist/lib/ontology-graph/replay/index.js +220 -0
  198. package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
  199. package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
  200. package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
  201. package/dist/lib/ontology-graph/replay/member.js +65 -0
  202. package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
  203. package/dist/lib/ontology-graph/replay/mentions.js +239 -0
  204. package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
  205. package/dist/lib/ontology-graph/replay/readers.js +1251 -0
  206. package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
  207. package/dist/lib/ontology-graph/replay/rules.js +374 -0
  208. package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
  209. package/dist/lib/ontology-graph/replay/scope.js +115 -0
  210. package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
  211. package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
  212. package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
  213. package/dist/lib/ontology-graph/replay/util.js +256 -0
  214. package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
  215. package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
  216. package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
  217. package/dist/lib/ontology-graph/resolve/index.js +214 -0
  218. package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
  219. package/dist/lib/ontology-graph/resolve/machine.js +95 -0
  220. package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
  221. package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
  222. package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
  223. package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
  224. package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
  225. package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
  226. package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
  227. package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
  228. package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
  229. package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
  230. package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
  231. package/dist/lib/ontology-graph/resolve/roster.js +226 -0
  232. package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
  233. package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
  234. package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
  235. package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
  236. package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
  237. package/dist/lib/ontology-graph/resolve/writer.js +351 -0
  238. package/dist/lib/ontology-graph/schema/authority.d.ts +107 -0
  239. package/dist/lib/ontology-graph/schema/authority.js +186 -0
  240. package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
  241. package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
  242. package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
  243. package/dist/lib/ontology-graph/schema/grammar.js +409 -0
  244. package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
  245. package/dist/lib/ontology-graph/schema/index.js +10 -0
  246. package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
  247. package/dist/lib/ontology-graph/schema/validate.js +132 -0
  248. package/dist/lib/ontology-graph/store/files.d.ts +34 -0
  249. package/dist/lib/ontology-graph/store/files.js +207 -0
  250. package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
  251. package/dist/lib/ontology-graph/store/fs.js +101 -0
  252. package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
  253. package/dist/lib/ontology-graph/store/graph-store.js +520 -0
  254. package/dist/lib/ontology-graph/store/index.d.ts +18 -0
  255. package/dist/lib/ontology-graph/store/index.js +15 -0
  256. package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
  257. package/dist/lib/ontology-graph/store/ingest.js +323 -0
  258. package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
  259. package/dist/lib/ontology-graph/store/paths.js +232 -0
  260. package/dist/lib/ontology-graph/types.d.ts +1190 -0
  261. package/dist/lib/ontology-graph/types.js +131 -0
  262. package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
  263. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  264. package/dist/lib/sync-core/engine-holds.js +12 -2
  265. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  266. package/dist/lib/sync-core/hand-back.js +16 -2
  267. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  268. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  269. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  270. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  271. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  272. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  273. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  274. package/dist/lib/sync-core/reconcile.js +43 -3
  275. package/dist/utils/cli-telemetry.d.ts +1 -0
  276. package/dist/utils/cli-telemetry.js +6 -3
  277. package/dist/utils/frontmatter.d.ts +14 -0
  278. package/dist/utils/frontmatter.js +18 -0
  279. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  280. package/dist/utils/hook-engine-rollup.js +725 -0
  281. package/dist/utils/interactive-caller.js +1 -1
  282. package/package.json +9 -9
  283. package/scripts/install-hook-engine.mjs +4 -0
  284. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -0,0 +1,1150 @@
1
+ /**
2
+ * WP-C entry point: import of the old `ontology/entities/` files and the verb
3
+ * map (design 2.4 and 3). Reads the old folder, never writes to it.
4
+ *
5
+ * Order of work:
6
+ * 1. The identity seed (people, roles, teams, repos, board owners, CRM
7
+ * accounts), so legacy names resolve against real identity anchors.
8
+ * 2. Every old entity file of an imported type, through the merge policy.
9
+ * 3. Its relationship lines, through the verb map.
10
+ *
11
+ * Every imported row is `by legacy`, cites `legacy:<old id>` or a signal both
12
+ * ends were referenced in, and carries a confidence of 0.50 or less.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import * as fs from "node:fs";
16
+ import * as path from "node:path";
17
+ import { COMPANY_AUDIENCE, } from "../types.js";
18
+ import { OntologyGraphNotImplementedError } from "../not-implemented.js";
19
+ import { DEFAULT_SCHEMA } from "../schema/index.js";
20
+ import { appendJsonLine, applyIngest, atomicWriteFile, graphPath, openGraphStore, readJsonLines, claimGraphRootFor } from "../store/index.js";
21
+ import { fileProposals, proposalsFromContradictions, rowLookup } from "../proposals/index.js";
22
+ import { applyIdentitySeed, buildIdentitySeed, createResolver, readLegacyMap, writeLegacyMap, writeSlackDirectory, } from "../resolve/index.js";
23
+ import { EntityIndex } from "../resolve/entity-index.js";
24
+ import { readOrgLayerCache, refreshOrgLayerCache } from "../resolve/org-layer.js";
25
+ import { graphQuality, orgCoverage } from "./coverage.js";
26
+ import { SHARED_MAIL_DOMAINS, isEmail, isRecordIdName, nameTokens, normalizeDomain, normalizeEmail, normalizeName, slackIdInside, slackIdOf, sortedUnique, } from "../resolve/normalize.js";
27
+ import { ORG_CHART_STATE, buildOrgChartDraft, orgChartProposals, readNameDescriptors } from "../resolve/org-chart.js";
28
+ import { Roster, readRosterFile, writeRosterFile } from "../resolve/roster.js";
29
+ import { isCopyName } from "../resolve/seed.js";
30
+ import { decideUpsert } from "../resolve/upsert.js";
31
+ import { GraphWriter, dayOf, edgeRow, factRow, typeOfRef } from "../resolve/writer.js";
32
+ import { replaceSlackIds } from "../replay/rules.js";
33
+ import { localAudienceKey } from "../replay/scope.js";
34
+ import { parseLegacyEntity } from "./parse.js";
35
+ import { planLegacyEdge, verbMapEntry } from "./verb-map.js";
36
+ export { parseLegacyEntity, parseLegacyTarget, parseRelationshipLine } from "./parse.js";
37
+ export { planLegacyEdge, verbMapEntry } from "./verb-map.js";
38
+ export { renderLegacyImportReport } from "./report.js";
39
+ export { graphQuality, orgCoverage } from "./coverage.js";
40
+ /**
41
+ * State edges an old entity file states with no date and no source. They are
42
+ * imported closed unless a signal from the last `LEGACY_CONFIRM_DAYS` days
43
+ * names both ends.
44
+ */
45
+ export const LEGACY_CLOSED_VERBS = new Set(["leads", "led_by", "owns", "owned_by", "works_at", "employs"]);
46
+ /** Reporting lines in old entity files were guessed by a model from one sentence. They are not imported. */
47
+ export const LEGACY_DROPPED_VERBS = new Set(["reports_to", "manages"]);
48
+ export const LEGACY_CONFIRM_DAYS = 120;
49
+ /** A project this many companies' old files say they use is a product the company sells. */
50
+ export const PRODUCT_MIN_COMPANIES = 3;
51
+ /** A company this many project, product or concept files say they run on is a vendor. */
52
+ export const VENDOR_MIN_LINES = 2;
53
+ const USED_BY_COMPANY_LABELS = new Set(["uses", "using", "customer of", "onboarding to", "evaluates", "considering", "interested in"]);
54
+ const RUNS_ON_LABELS = new Set(["uses", "using", "hosted on", "built on", "depends on", "powered by", "runs on", "deployed on"]);
55
+ const PROVIDES_LABELS = new Set(["used by", "provides", "provides infrastructure for", "provides models for", "provides sso for", "hosts"]);
56
+ const labelKey = (label) => label.trim().toLowerCase().replace(/\s+/g, " ");
57
+ /** Old entity types the import reads. */
58
+ export const LEGACY_IMPORT_TYPES = ["person", "company", "concept", "project", "tool", "product"];
59
+ /** Old entity types that belong to the accounting domain and stay in the old folder. */
60
+ export const LEGACY_ACCOUNTING_TYPES = ["account", "journal-entry", "ar-invoice", "ap-bill", "invoice"];
61
+ /** Where proposals wait when the proposals package is not there to take them. */
62
+ export const LEGACY_PENDING_PROPOSALS = ".state/legacy-import-proposals.jsonl";
63
+ function bump(record, key, by = 1) {
64
+ record[key] = (record[key] ?? 0) + by;
65
+ }
66
+ function id12(id) {
67
+ return id.slice(0, 12);
68
+ }
69
+ function walk(dir, prefix, out) {
70
+ let entries;
71
+ try {
72
+ entries = fs.readdirSync(dir, { withFileTypes: true });
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
78
+ if (entry.name.startsWith("."))
79
+ continue;
80
+ const rel = `${prefix}/${entry.name}`;
81
+ if (entry.isDirectory())
82
+ walk(path.join(dir, entry.name), rel, out);
83
+ else if (entry.name.endsWith(".md"))
84
+ out.push(rel);
85
+ }
86
+ }
87
+ function readSignalInfo(signalsDir, relPath) {
88
+ let text;
89
+ try {
90
+ text = fs.readFileSync(path.join(signalsDir, ...relPath.split("/")), "utf8");
91
+ }
92
+ catch {
93
+ return { exists: false, refs: new Set() };
94
+ }
95
+ const refs = new Set();
96
+ const start = text.indexOf("\nentity_refs:");
97
+ if (start >= 0) {
98
+ const lines = text.slice(start + 1).split("\n");
99
+ for (let index = 1; index < lines.length; index += 1) {
100
+ const match = /^\s+-\s+["']?([^"'\s]+)["']?\s*$/.exec(lines[index]);
101
+ if (!match)
102
+ break;
103
+ refs.add(match[1]);
104
+ }
105
+ }
106
+ return { exists: true, refs };
107
+ }
108
+ /** Signal id to the day it was written, from `signals/_index/<day>.json`. */
109
+ function readSignalDays(signalsDir) {
110
+ const days = new Map();
111
+ const dir = path.join(signalsDir, "_index");
112
+ let names;
113
+ try {
114
+ names = fs.readdirSync(dir);
115
+ }
116
+ catch {
117
+ return days;
118
+ }
119
+ for (const name of names.sort()) {
120
+ if (!name.endsWith(".json") || isCopyName(name))
121
+ continue;
122
+ let rows;
123
+ try {
124
+ rows = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
125
+ }
126
+ catch {
127
+ continue;
128
+ }
129
+ if (!Array.isArray(rows))
130
+ continue;
131
+ for (const row of rows) {
132
+ const entry = row;
133
+ const day = dayOf(entry?.written_at) ?? dayOf(name.slice(0, 10));
134
+ if (entry && typeof entry.signal_id === "string" && day && !days.has(entry.signal_id))
135
+ days.set(entry.signal_id, day);
136
+ }
137
+ }
138
+ return days;
139
+ }
140
+ const LEGACY_BATCH_REF = `legacy:${createHash("sha256").update("legacy-import").digest("hex").slice(0, 12)}`;
141
+ const SEED_BATCH_REF = "record:seed:identity";
142
+ /** Called once by `runRebuild` before the first replayed day. Idempotent. */
143
+ export async function importLegacy(context, options) {
144
+ const started = Date.now();
145
+ const now = options.now ?? new Date().toISOString();
146
+ const learned = options.learned;
147
+ const entitiesDir = options.entitiesDir ?? path.join(context.companyRoot, "ontology", "entities");
148
+ const signalsDir = options.signalsDir ?? path.join(context.companyRoot, "signals");
149
+ const timelineMode = options.timeline ?? "missing-only";
150
+ const member = options.seedOptions?.member ?? context.member;
151
+ const heldKeys = new Set(member?.audienceKeys ?? []);
152
+ /** Where a line from a signal with no audience key is filed (correction C7). Null with no member. */
153
+ const localKey = member?.personUid ? localAudienceKey(member.personUid) : null;
154
+ const store = options.store ?? openGraphStore(context.graphRoot, { company: context.company });
155
+ // An import run on its own is a writer (rows, the cache, the roster file): it claims the folder first.
156
+ // Inside a replay the store is handed in and the replay has claimed it.
157
+ if (!options.dryRun && !options.store)
158
+ claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
159
+ if (!options.dryRun)
160
+ store.init();
161
+ let schema;
162
+ try {
163
+ schema = store.schema();
164
+ }
165
+ catch {
166
+ schema = DEFAULT_SCHEMA;
167
+ }
168
+ // The index starts from what the graph already holds, so a second run finds its own entities.
169
+ let index;
170
+ let legacyMap;
171
+ try {
172
+ index = createResolver(store, schema).index;
173
+ legacyMap = readLegacyMap(store.root);
174
+ }
175
+ catch {
176
+ index = new EntityIndex(schema.refusals);
177
+ legacyMap = { byId: {}, byPath: {} };
178
+ }
179
+ const writer = new GraphWriter({ schema, index, store: options.dryRun ? null : store, apply: options.apply ?? applyIngest, now });
180
+ const report = {
181
+ filesRead: 0,
182
+ conflictCopiesSkipped: 0,
183
+ accountingSkipped: 0,
184
+ slackIdPeopleSkipped: 0,
185
+ entitiesCreated: 0,
186
+ rowsAdded: 0,
187
+ verbCounts: {},
188
+ seconds: 0,
189
+ dryRun: options.dryRun,
190
+ learned,
191
+ at: now,
192
+ entitiesInByType: {},
193
+ entitiesOutByType: {},
194
+ graphEntitiesByType: {},
195
+ merges: 0,
196
+ mergesByReason: {},
197
+ mergeExamples: {},
198
+ refusals: {},
199
+ slackIdPeople: 0,
200
+ slackIdPeopleResolved: 0,
201
+ slackIdAliasesKept: 0,
202
+ slackIdAliasesRejected: 0,
203
+ aliasesDropped: {},
204
+ otherTypesSkipped: {},
205
+ parseFailures: 0,
206
+ alreadyImported: 0,
207
+ labels: {},
208
+ distinctLabels: 0,
209
+ relationshipLines: 0,
210
+ rowsDropped: {},
211
+ edgesFlipped: 0,
212
+ edgesCoerced: 0,
213
+ edgesDowngraded: 0,
214
+ edgesCitingSignal: 0,
215
+ timeline: { written: 0, deferredToReplay: 0, personalScopeSkipped: 0, audienceSkipped: 0, noMemberSkipped: 0, slackIdsNamed: 0 },
216
+ rowsQueued: 0,
217
+ rowsByKind: {},
218
+ rowsRefused: 0,
219
+ rowsClosed: 0,
220
+ contradictions: 0,
221
+ contradictionProposalsFiled: 0,
222
+ proposals: 0,
223
+ proposalsByKind: {},
224
+ aliasHintsNotFiled: 0,
225
+ keysOfAnotherName: 0,
226
+ proposalsFiled: 0,
227
+ proposalsPending: 0,
228
+ unresolvedParked: 0,
229
+ seed: null,
230
+ orgLayer: { mode: "cache", status: "unavailable" },
231
+ coverage: null,
232
+ payingCustomersStated: null,
233
+ rosterMerges: {},
234
+ rosterMergeList: [],
235
+ machinesAsTools: 0,
236
+ machineExamples: [],
237
+ groupNamesDropped: 0,
238
+ companyNamesAsPeople: 0,
239
+ companiesHeld: 0,
240
+ typeChanges: {},
241
+ products: [],
242
+ edgesImportedClosed: {},
243
+ edgesConfirmedRecent: {},
244
+ reportingLinesDropped: 0,
245
+ vendorsMarked: 0,
246
+ signalCitationsMissing: 0,
247
+ quality: null,
248
+ orgChart: null,
249
+ orgChartProposals: 0,
250
+ };
251
+ // 0. The org chart people keep in HQ: read it when asked to, else use the kept answer.
252
+ const envMode = process.env.HQ_ONTOLOGY_ORG_LAYER;
253
+ const orgLayerMode = options.orgLayer ?? (envMode === "fetch" || envMode === "off" ? envMode : "cache");
254
+ if (orgLayerMode === "off") {
255
+ report.orgLayer = { mode: "off", status: "off" };
256
+ }
257
+ else {
258
+ if (orgLayerMode === "fetch" && !options.dryRun && options.seed !== false) {
259
+ const refreshed = await refreshOrgLayerCache(context, { ...(options.orgLayerFetcher ? { fetcher: options.orgLayerFetcher } : {}), now });
260
+ report.orgLayer = { mode: orgLayerMode, status: refreshed.status, ...(refreshed.reason ? { reason: refreshed.reason } : {}), ...(refreshed.fetchedAt ? { fetchedAt: refreshed.fetchedAt } : {}) };
261
+ }
262
+ else {
263
+ const kept = readOrgLayerCache(context.graphRoot);
264
+ report.orgLayer = kept ? { mode: orgLayerMode, status: "cached", fetchedAt: kept.fetchedAt } : { mode: orgLayerMode, status: "unavailable" };
265
+ }
266
+ }
267
+ // 1. Identity seed.
268
+ const seed = options.seed !== false
269
+ ? buildIdentitySeed(context, { ...(options.seedOptions ?? {}), ...(orgLayerMode === "off" ? { orgLayer: null } : {}), learned })
270
+ : null;
271
+ report.payingCustomersStated = seed?.org?.payingCustomers ?? null;
272
+ const seedApply = {
273
+ learned,
274
+ now,
275
+ ...(options.seedOptions?.minCommits !== undefined ? { minCommits: options.seedOptions.minCommits } : {}),
276
+ ...(options.seedOptions?.minChannelThreads !== undefined ? { minChannelThreads: options.seedOptions.minChannelThreads } : {}),
277
+ ...(options.seedOptions?.minEngineeringCommits !== undefined ? { minEngineeringCommits: options.seedOptions.minEngineeringCommits } : {}),
278
+ };
279
+ if (seed) {
280
+ report.seed = applyIdentitySeed(seed, writer, { ...seedApply, phase: "anchors" });
281
+ writer.flush(SEED_BATCH_REF, learned);
282
+ if (!options.dryRun)
283
+ writeSlackDirectory(store.root, seed.directory);
284
+ }
285
+ else if (!index.rosterOf()) {
286
+ // No seed in this run: the roster an earlier run kept still decides which names are the company's own people.
287
+ const kept = options.dryRun ? null : readRosterFile(store.root);
288
+ if (kept && kept.members.length > 0) {
289
+ index.setRoster(new Roster(kept.members, kept.ownWords));
290
+ index.setMachineCheck({ knownNames: new Set(kept.machineNames), ownWords: new Set(kept.ownWords) });
291
+ }
292
+ }
293
+ const selfNorm = normalizeName(seed?.self?.name ?? "");
294
+ const seedCreated = writer.counts.entitiesCreated;
295
+ const seedMerged = writer.counts.entitiesMerged;
296
+ const seedMergeReasons = { ...writer.counts.mergesByReason };
297
+ // 2. Read the old folder.
298
+ const files = [];
299
+ const readTypeDirs = () => {
300
+ try {
301
+ return fs.readdirSync(entitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith("."));
302
+ }
303
+ catch {
304
+ return [];
305
+ }
306
+ };
307
+ const typeDirs = readTypeDirs();
308
+ for (const dir of typeDirs.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
309
+ const relPaths = [];
310
+ walk(path.join(entitiesDir, dir.name), dir.name, relPaths);
311
+ if (LEGACY_ACCOUNTING_TYPES.includes(dir.name)) {
312
+ report.accountingSkipped += relPaths.length;
313
+ continue;
314
+ }
315
+ if (!LEGACY_IMPORT_TYPES.includes(dir.name)) {
316
+ bump(report.otherTypesSkipped, dir.name, relPaths.length);
317
+ continue;
318
+ }
319
+ for (const relPath of relPaths) {
320
+ if (isCopyName(path.basename(relPath))) {
321
+ report.conflictCopiesSkipped += 1;
322
+ continue;
323
+ }
324
+ const readOne = () => {
325
+ try {
326
+ return parseLegacyEntity(fs.readFileSync(path.join(entitiesDir, ...relPath.split("/")), "utf8"), relPath);
327
+ }
328
+ catch {
329
+ return null;
330
+ }
331
+ };
332
+ const parsed = readOne();
333
+ if (!parsed) {
334
+ report.parseFailures += 1;
335
+ continue;
336
+ }
337
+ report.filesRead += 1;
338
+ bump(report.entitiesInByType, parsed.dirType);
339
+ files.push(parsed);
340
+ }
341
+ }
342
+ // People with a full name first, bare first names next, Slack-id names last; shorter names before
343
+ // longer ones so a base project exists before its variants.
344
+ const rank = (file) => {
345
+ if (file.dirType !== "person")
346
+ return 0;
347
+ if (slackIdInside(file.name))
348
+ return 2;
349
+ return nameTokens(normalizeName(file.name)).length >= 2 ? 0 : 1;
350
+ };
351
+ files.sort((a, b) => (a.dirType < b.dirType ? -1 : a.dirType > b.dirType ? 1 : 0) ||
352
+ rank(a) - rank(b) ||
353
+ normalizeName(a.name).length - normalizeName(b.name).length ||
354
+ (a.fileSlug < b.fileSlug ? -1 : a.fileSlug > b.fileSlug ? 1 : 0) ||
355
+ (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
356
+ // Which old person files claim each Slack id as an alias.
357
+ const slackClaims = new Map();
358
+ for (const file of files) {
359
+ if (file.dirType !== "person")
360
+ continue;
361
+ for (const alias of file.aliases) {
362
+ const slackId = slackIdInside(alias);
363
+ if (!slackId)
364
+ continue;
365
+ let set = slackClaims.get(slackId);
366
+ if (!set)
367
+ slackClaims.set(slackId, (set = new Set()));
368
+ set.add(file.id);
369
+ }
370
+ }
371
+ // An alias that is another old file's own name (same type) is not an alias: it is a hint that the two
372
+ // may be one thing. It is left off the alias list and filed as a merge proposal.
373
+ const namesByType = new Map();
374
+ for (const file of files) {
375
+ const key = `${file.dirType}\u0000${normalizeName(file.name)}`;
376
+ namesByType.set(key, (namesByType.get(key) ?? new Set()).add(file.id));
377
+ }
378
+ const namesAnother = (file, alias) => {
379
+ const holders = namesByType.get(`${file.dirType}\u0000${normalizeName(alias)}`);
380
+ return holders !== undefined && [...holders].some((id) => id !== file.id);
381
+ };
382
+ const aliasHints = [];
383
+ // What the old files say about each other, read before any entity is made.
384
+ const targeted = new Set();
385
+ const usedByCompanies = new Map();
386
+ const companyNames = new Set(selfNorm !== "" ? [selfNorm] : []);
387
+ const toolNames = new Set();
388
+ const fileByPath = new Map();
389
+ index.reservePaths(files.map((file) => `${file.dirType}/${file.fileSlug}`));
390
+ for (const file of files) {
391
+ fileByPath.set(`${file.dirType}/${file.fileSlug}`, file);
392
+ if (file.dirType === "company")
393
+ companyNames.add(normalizeName(file.name));
394
+ if (file.dirType === "tool")
395
+ toolNames.add(normalizeName(file.name));
396
+ }
397
+ for (const file of files) {
398
+ for (const relationship of file.relationships) {
399
+ const target = relationship.target;
400
+ if (target.kind !== "entity")
401
+ continue;
402
+ targeted.add(target.path);
403
+ if (file.dirType === "company" && (target.type === "project" || target.type === "product") && USED_BY_COMPANY_LABELS.has(labelKey(relationship.label))) {
404
+ usedByCompanies.set(target.path, (usedByCompanies.get(target.path) ?? new Set()).add(file.id));
405
+ }
406
+ }
407
+ }
408
+ // A product: an old product file, a name the settings file lists, or a project that several companies' files say they use.
409
+ const productNames = new Set((seed?.settings?.products ?? []).map((name) => normalizeName(name)).filter((name) => name !== ""));
410
+ for (const [oldPath, companies] of usedByCompanies) {
411
+ const named = fileByPath.get(oldPath);
412
+ if (!named || companies.size < PRODUCT_MIN_COMPANIES)
413
+ continue;
414
+ productNames.add(normalizeName(named.name));
415
+ report.products.push(`${named.name} (${companies.size} company files say they use it)`);
416
+ }
417
+ productNames.delete(selfNorm);
418
+ const settingsVendors = new Set((seed?.settings?.vendors ?? []).map((name) => normalizeName(name)).filter((name) => name !== ""));
419
+ /** The type an old file is imported as. A tool and a company of one name are one tool; a product is a product whatever folder it sat in. */
420
+ const importType = (file) => {
421
+ const norm = normalizeName(file.name);
422
+ if (file.dirType !== "person" && file.dirType !== "product" && productNames.has(norm))
423
+ return { type: "product", changed: "product_same_name" };
424
+ if ((file.dirType === "company" || file.dirType === "concept") && toolNames.has(norm))
425
+ return { type: "tool", changed: "tool_same_name" };
426
+ return { type: file.dirType };
427
+ };
428
+ // 3. Entities.
429
+ const example = (file, decision, ref) => {
430
+ if (decision.action !== "merge")
431
+ return;
432
+ const list = (report.mergeExamples[`${file.dirType}, ${decision.reason}`] ??= []);
433
+ if (list.length < 8)
434
+ list.push(`${file.dirType}/${file.fileSlug} "${file.name}" -> ${ref}`);
435
+ };
436
+ const imported = [];
437
+ const pathToRef = new Map(Object.entries(legacyMap.byPath));
438
+ const outRefs = new Set();
439
+ for (const file of files) {
440
+ const typed = importType(file);
441
+ const type = typed.type;
442
+ const oldPath = `${file.dirType}/${file.fileSlug}`;
443
+ const evidence = `legacy:${id12(file.id)}`;
444
+ const firstDay = dayOf(file.firstSeen) ?? dayOf(file.lastUpdated) ?? learned;
445
+ const lastDay = dayOf(file.lastUpdated) ?? firstDay;
446
+ const legacyIds = sortedUnique([id12(file.id), ...file.legacyIds.map(id12)]);
447
+ const remember = (ref, extra = {}) => {
448
+ legacyMap.byId[id12(file.id)] = ref;
449
+ legacyMap.byPath[oldPath] = ref;
450
+ pathToRef.set(oldPath, ref);
451
+ // The index answers for the old path at once, so the seed's links resolve `person/<old slug>` on the first run as on a later one.
452
+ index.setLegacyPath(oldPath, ref);
453
+ outRefs.add(ref);
454
+ if (typed.changed && typeOfRef(ref) === type)
455
+ bump(report.typeChanges, typed.changed);
456
+ imported.push({ file, ref, firstDay, lastDay, emails: [], slackIds: [], domains: [], ...extra });
457
+ };
458
+ // A second run finds the entity by its old id and changes nothing.
459
+ const known = index.byKeys({ external_ids: [`legacy:${file.id}`] });
460
+ if (known.length === 1) {
461
+ report.alreadyImported += 1;
462
+ const entity = writer.entity(known[0]);
463
+ remember(known[0], {
464
+ emails: type === "person" && typeOfRef(known[0]) === "person" ? [...(entity?.keys.email ?? [])].filter((email) => file.aliases.some((alias) => normalizeEmail(alias) === email)) : [],
465
+ domains: type === "company" ? file.webDomains.map(normalizeDomain).filter((host) => host !== "" && !SHARED_MAIL_DOMAINS.has(host)) : [],
466
+ });
467
+ continue;
468
+ }
469
+ if (type === "person") {
470
+ const nameSlackId = slackIdInside(file.name);
471
+ if (nameSlackId) {
472
+ // A person named by a Slack id is never created. The id joins a real person through the Slack
473
+ // maps, or the mention is parked.
474
+ const hit = index.resolve({ text: nameSlackId, types: ["person"] });
475
+ if (hit.status === "resolved" && hit.entity) {
476
+ writer.enrich(hit.entity, { seen: firstDay, legacyIds });
477
+ report.slackIdPeopleResolved += 1;
478
+ report.merges += 1;
479
+ bump(report.mergesByReason, "slack_directory");
480
+ remember(hit.entity);
481
+ }
482
+ else {
483
+ report.slackIdPeopleSkipped += 1;
484
+ writer.park({ mention: file.name, reason: "unknown_slack_id", src: evidence, date: firstDay, audience: COMPANY_AUDIENCE, ...(hit.candidates.length > 0 ? { candidates: hit.candidates } : {}) });
485
+ }
486
+ continue;
487
+ }
488
+ const nameNorm = normalizeName(file.name);
489
+ const nameTokenSet = new Set(nameTokens(nameNorm));
490
+ const aliases = [];
491
+ const emails = [];
492
+ const claimed = [];
493
+ for (const alias of file.aliases) {
494
+ const slackId = slackIdInside(alias);
495
+ if (slackId) {
496
+ claimed.push(slackId);
497
+ continue;
498
+ }
499
+ if (isEmail(alias)) {
500
+ emails.push(normalizeEmail(alias));
501
+ continue;
502
+ }
503
+ const aliasNorm = normalizeName(alias);
504
+ const tokens = nameTokens(aliasNorm);
505
+ if (namesAnother(file, alias)) {
506
+ bump(report.aliasesDropped, "another_entitys_name");
507
+ aliasHints.push({ file, alias });
508
+ }
509
+ else if (alias.includes("/") || aliasNorm.length < 2)
510
+ bump(report.aliasesDropped, "not_a_name");
511
+ else if (index.isGeneric(aliasNorm) || index.isPlaceholderPerson(aliasNorm) || index.isJobTitle(alias))
512
+ bump(report.aliasesDropped, "generic_or_title");
513
+ else if (/['’]s$/.test(alias.trim()))
514
+ bump(report.aliasesDropped, "possessive");
515
+ else if (tokens.length >= 2 && !tokens.some((token) => nameTokenSet.has(token)))
516
+ bump(report.aliasesDropped, "another_persons_name");
517
+ else if (aliasNorm !== nameNorm)
518
+ aliases.push(alias);
519
+ }
520
+ // A Slack id listed as an alias is kept as a key only when the Slack maps agree it is this person,
521
+ // or nothing contradicts it and no other old file claims it.
522
+ const directory = index.slackDirectory();
523
+ const aliasNorms = new Set([nameNorm, ...aliases.map((alias) => normalizeName(alias))]);
524
+ const slackIds = [];
525
+ for (const slackId of sortedUnique(claimed)) {
526
+ const mappedEmail = directory.idToEmail[slackId];
527
+ const mappedName = directory.idToName[slackId];
528
+ const holders = index.byKeys({ slack_id: [slackId] }, ["person"]);
529
+ const agrees = (mappedEmail !== undefined && emails.includes(mappedEmail)) || (mappedName !== undefined && aliasNorms.has(normalizeName(mappedName)));
530
+ const unclaimed = mappedEmail === undefined && mappedName === undefined && holders.length === 0 && (slackClaims.get(slackId)?.size ?? 0) === 1;
531
+ if (agrees || unclaimed)
532
+ slackIds.push(slackId);
533
+ else
534
+ report.slackIdAliasesRejected += 1;
535
+ }
536
+ // An email or Slack id in an old alias list was written by a model, not by a record. It joins this
537
+ // file to a person only when the two names have a word in common.
538
+ const nameWords = new Set(nameTokens(nameNorm).filter((token) => token.length >= 2));
539
+ const holders = index.byKeys({ email: emails, slack_id: slackIds }, ["person"]);
540
+ const sharesName = (ref) => {
541
+ const holder = index.get(ref);
542
+ if (!holder)
543
+ return false;
544
+ return [holder.norm, ...holder.aliasNorms].some((known) => nameTokens(known).some((token) => nameWords.has(token)));
545
+ };
546
+ const strangers = holders.length > 0 && !holders.some(sharesName) ? holders : [];
547
+ if (strangers.length > 0) {
548
+ report.keysOfAnotherName += 1;
549
+ emails.length = 0;
550
+ slackIds.length = 0;
551
+ }
552
+ // Not a person: a bot, an agent or a service becomes a tool; a group name or a company's name becomes nothing.
553
+ // A name that is a variant of a roster person, or that carries a real person's key, is left to the merge policy.
554
+ const ownKeys = { email: sortedUnique(emails), slack_id: slackIds };
555
+ const isSomeone = index.rosterVariant(file.name, ownKeys) !== null || index.byKeys(ownKeys, ["person"]).length > 0 || index.findSameName("person", file.name).length > 0;
556
+ // A placeholder or a job title is refused by the merge policy under its own code.
557
+ const refusedAnyway = index.isGeneric(nameNorm) || index.isPlaceholderPerson(nameNorm) || index.isJobTitle(file.name);
558
+ const not = isSomeone || refusedAnyway ? null : index.notAPerson({ name: file.name, emails });
559
+ if (not === "machine_identity") {
560
+ const tool = writer.ensure({ type: "tool", name: file.name, seen: firstDay, lastSeen: lastDay, legacyIds, slugFallback: file.fileSlug, ownPath: `tool/${file.fileSlug}`, evidence, quietReasons: ["fuzzy", "alias"] });
561
+ if (tool.ref) {
562
+ remember(tool.ref);
563
+ report.machinesAsTools += 1;
564
+ if (report.machineExamples.length < 40)
565
+ report.machineExamples.push(`person/${file.fileSlug} "${file.name}" -> ${tool.ref}`);
566
+ }
567
+ continue;
568
+ }
569
+ if (not === "group_name") {
570
+ report.groupNamesDropped += 1;
571
+ bump(writer.counts.refusalsByReason, "group_name");
572
+ continue;
573
+ }
574
+ if (!isSomeone && nameTokenSet.size === 1 && companyNames.has(nameNorm)) {
575
+ report.companyNamesAsPeople += 1;
576
+ bump(writer.counts.refusalsByReason, "company_name_as_person");
577
+ continue;
578
+ }
579
+ const made = writer.ensure({
580
+ type,
581
+ name: file.name,
582
+ aliases,
583
+ keys: { email: sortedUnique(emails), slack_id: slackIds },
584
+ seen: firstDay,
585
+ lastSeen: lastDay,
586
+ legacyIds,
587
+ slugFallback: file.fileSlug,
588
+ ownPath: oldPath,
589
+ evidence,
590
+ });
591
+ if (made.ref) {
592
+ remember(made.ref, { emails: sortedUnique(emails), slackIds });
593
+ report.slackIdAliasesKept += slackIds.length;
594
+ example(file, made.decision, made.ref);
595
+ if (strangers.length > 0)
596
+ writer.proposeMerge(made.ref, strangers, "identity_key", evidence);
597
+ }
598
+ continue;
599
+ }
600
+ if (isRecordIdName(file.name, file.externalIds)) {
601
+ // A record named by its own id (a billing customer id, a UUID) has no name to resolve.
602
+ bump(writer.counts.refusalsByReason, "record_id_as_name");
603
+ continue;
604
+ }
605
+ const domains = sortedUnique(file.webDomains.map(normalizeDomain).filter((host) => host !== "" && !SHARED_MAIL_DOMAINS.has(host)));
606
+ const kept = [];
607
+ for (const alias of file.aliases) {
608
+ if (alias.includes("/") || normalizeName(alias).length < 2)
609
+ continue;
610
+ if (namesAnother(file, alias)) {
611
+ bump(report.aliasesDropped, "another_entitys_name");
612
+ aliasHints.push({ file, alias });
613
+ }
614
+ else
615
+ kept.push(alias);
616
+ }
617
+ // A company no relationship line names, that no other old file points at and that no other source made, is a
618
+ // CRM row and nothing else. It stays out of the graph until a second source names it.
619
+ if (type === "company" && file.relationships.length === 0 && !targeted.has(oldPath)) {
620
+ const decision = decideUpsert(index, { type, name: file.name, aliases: kept, keys: { external_ids: file.externalIds, web_domains: domains } });
621
+ if (decision.action !== "merge") {
622
+ report.companiesHeld += 1;
623
+ bump(writer.counts.refusalsByReason, "crm_only_company");
624
+ continue;
625
+ }
626
+ }
627
+ const made = writer.ensure({
628
+ type,
629
+ name: file.name,
630
+ aliases: kept,
631
+ keys: { external_ids: file.externalIds, web_domains: domains },
632
+ seen: firstDay,
633
+ lastSeen: lastDay,
634
+ legacyIds,
635
+ slugFallback: file.fileSlug,
636
+ // Under its import type: a company imported as a tool may take the tool's own path.
637
+ ownPath: `${type}/${file.fileSlug}`,
638
+ evidence,
639
+ // Concept and tool names overlap too freely for a name hint to be worth a person's time.
640
+ ...(type === "concept" || type === "tool" ? { quietReasons: ["fuzzy", "alias"] } : {}),
641
+ });
642
+ if (made.ref) {
643
+ remember(made.ref, { domains });
644
+ example(file, made.decision, made.ref);
645
+ }
646
+ }
647
+ // The seed's name-resolved links (managers, board owners, channel participants) run now, against
648
+ // every entity, so a second run resolves them the same way.
649
+ // Teams and roles the links create or find again belong to the seed, not to the old files.
650
+ const beforeLinks = { created: writer.counts.entitiesCreated, merged: writer.counts.entitiesMerged, reasons: { ...writer.counts.mergesByReason } };
651
+ if (seed && report.seed) {
652
+ report.seed = applyIdentitySeed(seed, writer, { ...seedApply, phase: "links", previous: report.seed });
653
+ writer.flush(SEED_BATCH_REF, learned);
654
+ }
655
+ const linksCreated = writer.counts.entitiesCreated - beforeLinks.created;
656
+ const linksMerged = writer.counts.entitiesMerged - beforeLinks.merged;
657
+ for (const [reason, count] of Object.entries(writer.counts.mergesByReason)) {
658
+ const fromLinks = count - (beforeLinks.reasons[reason] ?? 0);
659
+ if (fromLinks > 0)
660
+ seedMergeReasons[reason] = (seedMergeReasons[reason] ?? 0) + fromLinks;
661
+ }
662
+ for (const hint of aliasHints) {
663
+ // Concept and tool names overlap too freely for a hint to be worth a person's time.
664
+ if (hint.file.dirType === "concept" || hint.file.dirType === "tool") {
665
+ report.aliasHintsNotFiled += 1;
666
+ continue;
667
+ }
668
+ const from = legacyMap.byId[id12(hint.file.id)];
669
+ const named = index.findSameName(hint.file.dirType, hint.alias);
670
+ if (from && named.length > 0)
671
+ writer.proposeMerge(from, named, "alias", `legacy:${id12(hint.file.id)}`);
672
+ }
673
+ report.entitiesCreated = writer.counts.entitiesCreated - seedCreated - linksCreated;
674
+ report.merges += writer.counts.entitiesMerged - seedMerged - linksMerged;
675
+ for (const [reason, count] of Object.entries(writer.counts.mergesByReason)) {
676
+ const fromLegacy = count - (seedMergeReasons[reason] ?? 0);
677
+ if (fromLegacy > 0)
678
+ bump(report.mergesByReason, reason, fromLegacy);
679
+ }
680
+ for (const ref of outRefs)
681
+ bump(report.entitiesOutByType, typeOfRef(ref));
682
+ // 4. Rows.
683
+ const signalDays = readSignalDays(signalsDir);
684
+ const signalCache = new Map();
685
+ const signalInfo = (relPath) => {
686
+ let info = signalCache.get(relPath);
687
+ if (!info)
688
+ signalCache.set(relPath, (info = readSignalInfo(signalsDir, relPath)));
689
+ return info;
690
+ };
691
+ // Company-scope signals each entity was referenced in: an edge whose two ends share one cites it.
692
+ const signalsOf = new Map();
693
+ /** 12 hex of a signal id to its file under `signals/` and the day it was written. */
694
+ const signalFile = new Map();
695
+ const signalDay12 = new Map();
696
+ for (const [id, day] of signalDays)
697
+ signalDay12.set(id12(id), day);
698
+ for (const item of imported) {
699
+ for (const relationship of item.file.relationships) {
700
+ if (relationship.target.kind !== "signal" || relationship.target.scope !== COMPANY_AUDIENCE)
701
+ continue;
702
+ let set = signalsOf.get(item.ref);
703
+ if (!set)
704
+ signalsOf.set(item.ref, (set = new Set()));
705
+ set.add(id12(relationship.target.id));
706
+ signalFile.set(id12(relationship.target.id), relationship.target.relPath);
707
+ }
708
+ }
709
+ /** A signal both ends were referenced in whose file is in the vault: the newest when `recentFrom` is given, else the lowest id. */
710
+ const sharedSignal = (a, b, recentFrom) => {
711
+ const left = signalsOf.get(a);
712
+ const right = signalsOf.get(b);
713
+ if (!left || !right)
714
+ return null;
715
+ const [small, large] = left.size <= right.size ? [left, right] : [right, left];
716
+ let best = null;
717
+ let bestDay = "";
718
+ for (const id of small) {
719
+ if (!large.has(id))
720
+ continue;
721
+ const day = signalDay12.get(id) ?? "";
722
+ if (recentFrom !== undefined) {
723
+ if (day < recentFrom || (best !== null && day <= bestDay))
724
+ continue;
725
+ }
726
+ else if (best !== null && id >= best)
727
+ continue;
728
+ // A signal id with no file anywhere cannot be opened: it is never cited (request F7).
729
+ const relPath = signalFile.get(id);
730
+ if (!relPath || !signalInfo(relPath).exists)
731
+ continue;
732
+ best = id;
733
+ bestDay = day;
734
+ }
735
+ return best;
736
+ };
737
+ const confirmFrom = new Date(Date.parse(`${learned}T00:00:00Z`) - LEGACY_CONFIRM_DAYS * 86_400_000).toISOString().slice(0, 10);
738
+ /** Lines that say a project, product or concept runs on a company, by that company. */
739
+ const vendorLines = new Map();
740
+ const became = (label, what) => {
741
+ const entry = (report.labels[label] ??= { count: 0, became: {} });
742
+ entry.count += 1;
743
+ bump(entry.became, what);
744
+ };
745
+ const drop = (label, reason) => {
746
+ bump(report.rowsDropped, reason);
747
+ became(label, `dropped:${reason}`);
748
+ };
749
+ const slackNames = new Map();
750
+ /** The name for a Slack id: the person who holds it, else the real name Slack's directory gives. An email is not a name. */
751
+ const slackNameOf = (id) => {
752
+ if (slackNames.has(id))
753
+ return slackNames.get(id) ?? null;
754
+ const answer = index.resolve({ text: id, types: ["person"], keys: { slack_id: [id] } });
755
+ let name = answer.status === "resolved" && answer.entity ? (index.get(answer.entity)?.name ?? "") : "";
756
+ if (name === "" || /[UW][A-Z0-9]{7}/.test(name))
757
+ name = (index.slackDirectory().idToName[id] ?? "").trim();
758
+ const usable = name !== "" && !name.includes("@") && !/[UW][A-Z0-9]{7}/.test(name) ? name : null;
759
+ slackNames.set(id, usable);
760
+ return usable;
761
+ };
762
+ const timelineRow = (item, relationship) => {
763
+ const target = relationship.target;
764
+ if (target.kind !== "signal")
765
+ return;
766
+ bump(report.verbCounts, "timeline");
767
+ if (target.scope === "personal") {
768
+ report.timeline.personalScopeSkipped += 1;
769
+ became(relationship.label, "timeline:skipped_personal_scope");
770
+ return;
771
+ }
772
+ let audience = target.scope;
773
+ if (audience === COMPANY_AUDIENCE) {
774
+ // A signal with no audience key is not company-wide (correction C7): its line is filed under the
775
+ // member's local audience, and is not written at all when no member is given.
776
+ if (!localKey) {
777
+ report.timeline.noMemberSkipped += 1;
778
+ became(relationship.label, "timeline:skipped_no_member");
779
+ return;
780
+ }
781
+ audience = localKey;
782
+ }
783
+ else if (!heldKeys.has(audience)) {
784
+ report.timeline.audienceSkipped += 1;
785
+ became(relationship.label, "timeline:skipped_audience");
786
+ return;
787
+ }
788
+ const info = signalInfo(target.relPath);
789
+ const ownPath = `${item.file.dirType}/${item.file.fileSlug}`;
790
+ if (timelineMode === "missing-only" && info.exists && info.refs.has(ownPath)) {
791
+ report.timeline.deferredToReplay += 1;
792
+ became(relationship.label, "timeline:left_to_replay");
793
+ return;
794
+ }
795
+ const signalType = /^[a-z][a-z0-9_-]*$/.test(target.signalType) ? target.signalType : "signal";
796
+ const prefix = `${signalType}:`;
797
+ let text = relationship.text.replace(/\s+/g, " ").trim();
798
+ if (text.toLowerCase().startsWith(prefix))
799
+ text = text.slice(prefix.length).trim();
800
+ if (text === "")
801
+ text = "Referenced in a signal";
802
+ // A Slack id the graph or Slack's directory can name is written as that name; any other id stays as written.
803
+ text = replaceSlackIds(text, (id) => {
804
+ const name = slackNameOf(id);
805
+ if (name !== null)
806
+ report.timeline.slackIdsNamed += 1;
807
+ return name;
808
+ });
809
+ // A signal whose file is gone cannot be opened: the row cites the old entity file that remembered it (request F7).
810
+ if (!info.exists)
811
+ report.signalCitationsMissing += 1;
812
+ const written = writer.addRow(item.ref, audience, {
813
+ kind: "T",
814
+ date: signalDays.get(target.id) ?? item.lastDay,
815
+ signalType,
816
+ text,
817
+ src: info.exists ? `signal:${id12(target.id)}` : `legacy:${id12(item.file.id)}`,
818
+ });
819
+ if (written) {
820
+ report.timeline.written += 1;
821
+ became(relationship.label, "timeline");
822
+ }
823
+ else {
824
+ drop(relationship.label, "duplicate_row");
825
+ }
826
+ };
827
+ /** The edge as it was true when the old file was last touched: valid to that day, closed by the import. */
828
+ const closedEdge = (row, item, by) => {
829
+ const to = item.lastDay > row.valid.from ? item.lastDay : row.valid.from;
830
+ return { ...row, valid: { from: row.valid.from, to }, closed: { on: learned, by } };
831
+ };
832
+ // Typed edges are placed before `related_to`, so an untyped line for a pair that has a typed verb is dropped.
833
+ const typedPairs = new Set();
834
+ const pairKey = (a, b) => (a < b ? `${a}\n${b}` : `${b}\n${a}`);
835
+ const untyped = [];
836
+ const placeEdge = (pending, pass) => {
837
+ const { item, relationship, target } = pending;
838
+ const label = relationship.label;
839
+ const plan = planLegacyEdge(schema, label, typeOfRef(item.ref), typeOfRef(target));
840
+ const stamp = (conf, src) => ({ from: item.firstDay, src, learned, by: "legacy", conf });
841
+ const legacySrc = `legacy:${id12(item.file.id)}`;
842
+ if (plan.action === "skip") {
843
+ bump(report.verbCounts, "skip");
844
+ became(label, "skip");
845
+ return;
846
+ }
847
+ if (plan.action === "timeline") {
848
+ // `Referenced in` that points at an entity, not a signal: there is nothing to cite.
849
+ drop(label, "reference_to_entity");
850
+ return;
851
+ }
852
+ if (plan.action === "fact") {
853
+ const person = plan.on === "subject" ? item.ref : target;
854
+ const other = plan.on === "subject" ? target : item.ref;
855
+ if (writer.addRow(person, COMPANY_AUDIENCE, factRow(plan.field, plan.value, stamp(plan.conf, legacySrc)))) {
856
+ bump(report.verbCounts, "fact");
857
+ became(label, `fact:${plan.field}`);
858
+ }
859
+ else
860
+ drop(label, "duplicate_row");
861
+ // Holding a title at a company meant working there when the old file was written: imported closed.
862
+ if (typeOfRef(other) === "company" && writer.claimEdge(person, "works_at", other)) {
863
+ if (writer.addRow(person, COMPANY_AUDIENCE, closedEdge(edgeRow("works_at", other, stamp(plan.conf, legacySrc)), item, legacySrc))) {
864
+ bump(report.verbCounts, "works_at");
865
+ bump(report.edgesImportedClosed, "works_at");
866
+ }
867
+ }
868
+ typedPairs.add(pairKey(item.ref, target));
869
+ return;
870
+ }
871
+ // An old reporting line is not imported, as an edge or as a label on an untyped edge.
872
+ if (LEGACY_DROPPED_VERBS.has(plan.verb) || LEGACY_DROPPED_VERBS.has(labelKey(label).replace(/ /g, "_"))) {
873
+ report.reportingLinesDropped += 1;
874
+ drop(label, "legacy_reporting_line");
875
+ return;
876
+ }
877
+ const isRelated = plan.verb === schema.verb_map_default.verb;
878
+ if (pass === "typed" && isRelated) {
879
+ untyped.push(pending);
880
+ return;
881
+ }
882
+ const from = plan.flipped ? target : item.ref;
883
+ const to = plan.flipped ? item.ref : target;
884
+ if (isRelated && typedPairs.has(pairKey(from, to))) {
885
+ drop(label, "related_pair_already_typed");
886
+ return;
887
+ }
888
+ if (!writer.claimEdge(from, plan.verb, to)) {
889
+ drop(label, "duplicate_edge");
890
+ return;
891
+ }
892
+ // Who leads, owns or works where is stated by an old file with no date. It is imported closed unless a signal
893
+ // from the last 120 days names both ends.
894
+ const stateEdge = LEGACY_CLOSED_VERBS.has(plan.verb);
895
+ const recent = stateEdge ? sharedSignal(from, to, confirmFrom) : null;
896
+ const shared = recent ?? sharedSignal(from, to);
897
+ const src = shared ? `signal:${shared}` : legacySrc;
898
+ const built = edgeRow(plan.verb, to, stamp(plan.conf, src), plan.was);
899
+ if (!writer.addRow(from, COMPANY_AUDIENCE, stateEdge && !recent ? closedEdge(built, item, legacySrc) : built)) {
900
+ drop(label, "row_refused");
901
+ return;
902
+ }
903
+ if (stateEdge)
904
+ bump(recent ? report.edgesConfirmedRecent : report.edgesImportedClosed, plan.verb);
905
+ if (shared)
906
+ report.edgesCitingSignal += 1;
907
+ if (!isRelated)
908
+ typedPairs.add(pairKey(from, to));
909
+ bump(report.verbCounts, plan.verb);
910
+ became(label, plan.verb);
911
+ if (plan.flipped)
912
+ report.edgesFlipped += 1;
913
+ if (plan.via === "coerced")
914
+ report.edgesCoerced += 1;
915
+ if (plan.via === "downgraded")
916
+ report.edgesDowngraded += 1;
917
+ };
918
+ const factsWritten = new Set();
919
+ const identityFact = (item, field, value, stamp) => {
920
+ const key = `${item.ref}\n${field}\n${value}`;
921
+ if (factsWritten.has(key) || writer.hasFact(item.ref, field, value))
922
+ return;
923
+ factsWritten.add(key);
924
+ writer.addRow(item.ref, COMPANY_AUDIENCE, factRow(field, value, stamp));
925
+ };
926
+ for (const item of imported) {
927
+ const src = `legacy:${id12(item.file.id)}`;
928
+ const stamp = { from: item.firstDay, src, learned, by: "legacy", conf: 0.5 };
929
+ for (const email of item.emails)
930
+ identityFact(item, "email", email, stamp);
931
+ for (const slackId of item.slackIds)
932
+ identityFact(item, "slack_id", slackId, stamp);
933
+ // A company imported as a tool or a product carries no web domain fact.
934
+ if (typeOfRef(item.ref) === "company")
935
+ for (const domain of item.domains)
936
+ identityFact(item, "web_domain", domain, stamp);
937
+ for (const relationship of item.file.relationships) {
938
+ report.relationshipLines += 1;
939
+ const target = relationship.target;
940
+ if (target.kind === "signal") {
941
+ timelineRow(item, relationship);
942
+ continue;
943
+ }
944
+ const entry = verbMapEntry(schema, relationship.label);
945
+ if (entry?.action === "skip") {
946
+ bump(report.verbCounts, "skip");
947
+ became(relationship.label, "skip");
948
+ continue;
949
+ }
950
+ if (target.kind === "none") {
951
+ drop(relationship.label, "no_target");
952
+ continue;
953
+ }
954
+ const targetRef = pathToRef.get(target.path);
955
+ if (!targetRef) {
956
+ drop(relationship.label, "target_not_imported");
957
+ continue;
958
+ }
959
+ if (targetRef === item.ref) {
960
+ drop(relationship.label, "self_edge_after_merge");
961
+ continue;
962
+ }
963
+ const key = labelKey(relationship.label);
964
+ const builtThing = (ref) => ["project", "product", "concept"].includes(typeOfRef(ref));
965
+ if (RUNS_ON_LABELS.has(key) && builtThing(item.ref) && typeOfRef(targetRef) === "company")
966
+ vendorLines.set(targetRef, (vendorLines.get(targetRef) ?? 0) + 1);
967
+ if (PROVIDES_LABELS.has(key) && typeOfRef(item.ref) === "company" && builtThing(targetRef))
968
+ vendorLines.set(item.ref, (vendorLines.get(item.ref) ?? 0) + 1);
969
+ placeEdge({ item, relationship, target: targetRef }, "typed");
970
+ }
971
+ }
972
+ // An untyped line that carries an old label is placed before a plain `Related to` for the same pair,
973
+ // so the label survives.
974
+ const plain = (pending) => verbMapEntry(schema, pending.relationship.label)?.action === "related";
975
+ for (const pending of untyped)
976
+ if (!plain(pending))
977
+ placeEdge(pending, "untyped");
978
+ for (const pending of untyped)
979
+ if (plain(pending))
980
+ placeEdge(pending, "untyped");
981
+ // Vendors: a company several built things run on, or one the settings file lists. Never the company itself,
982
+ // and never a company a client folder already calls a customer or a prospect.
983
+ const selfRef = selfNorm !== "" ? (index.findSameName("company", seed?.self?.name ?? "")[0] ?? null) : null;
984
+ const vendorRefs = new Set([...vendorLines].filter(([, lines]) => lines >= VENDOR_MIN_LINES).map(([ref]) => ref));
985
+ for (const name of settingsVendors)
986
+ for (const ref of index.findSameName("company", name))
987
+ vendorRefs.add(ref);
988
+ for (const ref of sortedUnique(vendorRefs)) {
989
+ if (ref === selfRef || ["customer", "prospect", "former customer", "self"].some((relation) => writer.hasFact(ref, "relation", relation)))
990
+ continue;
991
+ const lines = vendorLines.get(ref) ?? 0;
992
+ const stamp = { from: learned, src: LEGACY_BATCH_REF, learned, by: lines >= VENDOR_MIN_LINES ? "rule:legacy-runs-on" : "record", conf: lines >= VENDOR_MIN_LINES ? 0.5 : 0.9 };
993
+ if (!writer.addRow(ref, COMPANY_AUDIENCE, factRow("relation", "vendor", stamp)))
994
+ continue;
995
+ report.vendorsMarked += 1;
996
+ if (selfRef && writer.claimEdge(ref, "vendor_of", selfRef))
997
+ writer.addRow(ref, COMPANY_AUDIENCE, edgeRow("vendor_of", selfRef, stamp));
998
+ }
999
+ // A product belongs to the company.
1000
+ if (selfRef) {
1001
+ for (const ref of sortedUnique(outRefs)) {
1002
+ if (typeOfRef(ref) !== "product" || !productNames.has(index.get(ref)?.norm ?? ""))
1003
+ continue;
1004
+ if (writer.claimEdge(ref, "part_of", selfRef))
1005
+ writer.addRow(ref, COMPANY_AUDIENCE, edgeRow("part_of", selfRef, { from: learned, src: LEGACY_BATCH_REF, learned, by: "rule:product-of-company", conf: 0.6 }));
1006
+ }
1007
+ }
1008
+ report.distinctLabels = Object.keys(report.labels).length;
1009
+ report.labels = Object.fromEntries(Object.entries(report.labels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1010
+ report.unresolvedParked = report.slackIdPeopleSkipped;
1011
+ writer.flush(LEGACY_BATCH_REF, learned);
1012
+ // 5. State, proposals, ledger.
1013
+ for (const ref of index.refs()) {
1014
+ bump(report.graphEntitiesByType, typeOfRef(ref));
1015
+ const entity = index.get(ref);
1016
+ if (entity?.type === "person" && (slackIdInside(entity.name) || slackIdOf(ref.slice(ref.indexOf("/") + 1).toUpperCase())))
1017
+ report.slackIdPeople += 1;
1018
+ }
1019
+ // The org chart draft: one proposed role, team and manager per roster person, each with its evidence. Proposals only.
1020
+ if (seed && report.seed?.roster && report.seed.roster.length > 0 && options.orgChart !== false) {
1021
+ // The company's own words, and the names of its products: `Acme/HQ co-founder` states the title `Co-founder`.
1022
+ const ownWords = new Set([...(index.machineCheck().ownWords ?? []), ...[...productNames].flatMap((name) => nameTokens(name))]);
1023
+ const draft = buildOrgChartDraft({
1024
+ company: context.company,
1025
+ selfName: seed.self?.name ?? "",
1026
+ roster: report.seed.roster,
1027
+ seed,
1028
+ result: report.seed,
1029
+ descriptors: readNameDescriptors(context.companyRoot, report.seed.roster.map((member) => member.name), ownWords),
1030
+ ownWords,
1031
+ learned,
1032
+ now,
1033
+ });
1034
+ report.orgChart = draft;
1035
+ // A line a person already confirmed in the org chart file is a fact, not a proposal.
1036
+ const confirmed = new Set();
1037
+ for (const row of seed.confirmedOrgChart?.people ?? []) {
1038
+ const norm = normalizeName(row.name);
1039
+ if (row.role !== "")
1040
+ confirmed.add(`${norm}\nrole`);
1041
+ if (row.team !== "")
1042
+ confirmed.add(`${norm}\nteam`);
1043
+ if (row.manager !== "")
1044
+ confirmed.add(`${norm}\nmanager`);
1045
+ }
1046
+ const nameOf = new Map(draft.lines.map((line) => [line.person, normalizeName(line.name)]));
1047
+ for (const proposal of orgChartProposals(draft)) {
1048
+ const what = /: (role|team|manager) "/.exec(proposal.summary)?.[1] ?? "";
1049
+ if (confirmed.has(`${nameOf.get(proposal.entity) ?? ""}\n${what}`) || writer.proposals.has(proposal.id))
1050
+ continue;
1051
+ writer.proposals.set(proposal.id, proposal);
1052
+ writer.counts.proposals += 1;
1053
+ bump(writer.proposalsByKind, `person, org_chart_draft_${what}`);
1054
+ report.orgChartProposals += 1;
1055
+ }
1056
+ if (!options.dryRun)
1057
+ atomicWriteFile(graphPath(store.root, ORG_CHART_STATE), `${JSON.stringify({ schema: 1, set: "org chart draft", ...draft }, null, 2)}\n`);
1058
+ }
1059
+ const proposals = [...writer.proposals.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
1060
+ report.aliasHintsNotFiled += writer.counts.hintsNotFiled;
1061
+ report.proposals = proposals.length;
1062
+ report.proposalsByKind = Object.fromEntries(Object.entries(writer.proposalsByKind).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1063
+ report.rowsQueued = writer.counts.rowsQueued;
1064
+ report.rowsByKind = Object.fromEntries(Object.entries(writer.rowsByKind).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1065
+ report.rowsRefused = writer.counts.rowsRefused;
1066
+ report.rowsAdded = writer.counts.rowsAdded;
1067
+ report.rowsClosed = writer.counts.rowsClosed;
1068
+ report.contradictions = writer.counts.contradictions;
1069
+ report.refusals = Object.fromEntries(Object.entries(writer.counts.refusalsByReason).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1070
+ if (!options.dryRun) {
1071
+ writeLegacyMap(store.root, legacyMap);
1072
+ if (writer.contradictions.length > 0) {
1073
+ try {
1074
+ const asProposals = proposalsFromContradictions(writer.contradictions, rowLookup(store));
1075
+ report.contradictionProposalsFiled = (options.fileProposals ?? fileProposals)(context, asProposals);
1076
+ }
1077
+ catch (error) {
1078
+ if (!(error instanceof OntologyGraphNotImplementedError))
1079
+ throw error;
1080
+ }
1081
+ }
1082
+ if (proposals.length > 0) {
1083
+ try {
1084
+ report.proposalsFiled = (options.fileProposals ?? fileProposals)(context, proposals);
1085
+ }
1086
+ catch (error) {
1087
+ if (!(error instanceof OntologyGraphNotImplementedError))
1088
+ throw error;
1089
+ // The proposals package is not there yet: keep them where the next run will file them from.
1090
+ const pendingFile = graphPath(store.root, LEGACY_PENDING_PROPOSALS);
1091
+ const waiting = new Set(readJsonLines(pendingFile).map((proposal) => proposal.id));
1092
+ for (const proposal of proposals) {
1093
+ if (waiting.has(proposal.id))
1094
+ continue;
1095
+ appendJsonLine(pendingFile, proposal);
1096
+ report.proposalsPending += 1;
1097
+ }
1098
+ }
1099
+ }
1100
+ }
1101
+ for (const merge of writer.rosterMerges) {
1102
+ bump(report.rosterMerges, merge.reason);
1103
+ report.rosterMergeList.push(`"${merge.name}" -> ${merge.into} (${merge.reason})`);
1104
+ }
1105
+ report.rosterMergeList = sortedUnique(report.rosterMergeList);
1106
+ report.rosterMerges = Object.fromEntries(Object.entries(report.rosterMerges).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1107
+ if (!options.dryRun) {
1108
+ const selfName = seed?.self?.name;
1109
+ const self = selfName ? (index.findSameName("company", selfName)[0] ?? null) : null;
1110
+ const roster = index.rosterOf();
1111
+ if (seed && report.seed?.roster) {
1112
+ writeRosterFile(store.root, {
1113
+ writtenAt: now,
1114
+ ownWords: [...(index.machineCheck().ownWords ?? [])],
1115
+ machineNames: seed.machineNames ?? [],
1116
+ members: report.seed.roster,
1117
+ });
1118
+ }
1119
+ report.coverage = orgCoverage(store, self);
1120
+ report.quality = graphQuality(store, { self, roster: roster ? roster.refs() : [], notAPerson: (name, emails) => index.notAPerson({ name, emails }) !== null });
1121
+ }
1122
+ report.seconds = Math.round((Date.now() - started) / 10) / 100;
1123
+ if (!options.dryRun && options.ledger === true) {
1124
+ store.appendLedger({
1125
+ run: `legacy-import-${now}`,
1126
+ command: "import",
1127
+ day: "legacy-import",
1128
+ inputs: { legacy: report.filesRead },
1129
+ rowsAdded: report.rowsAdded,
1130
+ rowsClosed: report.rowsClosed,
1131
+ entitiesCreated: writer.counts.entitiesCreated,
1132
+ modelCalls: 0,
1133
+ cacheHits: 0,
1134
+ inputTokens: 0,
1135
+ outputTokens: 0,
1136
+ pending: 0,
1137
+ seconds: report.seconds,
1138
+ at: now,
1139
+ counters: {
1140
+ legacy_merges: report.merges,
1141
+ legacy_conflict_copies_skipped: report.conflictCopiesSkipped,
1142
+ legacy_slack_id_people_parked: report.slackIdPeopleSkipped,
1143
+ legacy_related_to: report.verbCounts.related_to ?? 0,
1144
+ legacy_proposals: report.proposals,
1145
+ },
1146
+ });
1147
+ }
1148
+ return report;
1149
+ }
1150
+ //# sourceMappingURL=index.js.map