@indigoai-us/hq-cli 5.345.246 → 5.345.248

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 (256) hide show
  1. package/CHANGELOG.md +63 -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 +1116 -3
  5. package/dist/command-catalog.generated.js +1373 -3
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/install-global.d.ts +15 -0
  9. package/dist/commands/install-global.js +98 -4
  10. package/dist/commands/lanes-hold.js +7 -7
  11. package/dist/commands/lanes-resume.js +2 -2
  12. package/dist/commands/lanes-review.js +1 -1
  13. package/dist/commands/lanes-session-start.d.ts +1 -1
  14. package/dist/commands/lanes-session-start.js +3 -3
  15. package/dist/commands/lanes-shared.d.ts +1 -1
  16. package/dist/commands/lanes.d.ts +2 -2
  17. package/dist/commands/lanes.js +50 -50
  18. package/dist/commands/mcp-registration.d.ts +17 -0
  19. package/dist/commands/mcp-registration.js +119 -0
  20. package/dist/commands/mesh.d.ts +25 -0
  21. package/dist/commands/mesh.js +48 -8
  22. package/dist/commands/ontology-graph.d.ts +62 -0
  23. package/dist/commands/ontology-graph.js +439 -0
  24. package/dist/commands/pkg-install.js +1 -1
  25. package/dist/commands/reindex.js +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  28. package/dist/lanes-monitor-check-argv.js +1 -1
  29. package/dist/lanes-monitor-check-fast.d.ts +1 -1
  30. package/dist/lanes-monitor-check-fast.js +1 -1
  31. package/dist/lanes-session-start-argv.d.ts +1 -1
  32. package/dist/lanes-session-start-argv.js +1 -1
  33. package/dist/lib/capacity/sign-in.d.ts +1 -1
  34. package/dist/lib/capacity/sign-in.js +1 -1
  35. package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
  36. package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
  37. package/dist/lib/daemon/lanes-monitor-state.js +2 -2
  38. package/dist/lib/daemon/merge-sections.d.ts +3 -3
  39. package/dist/lib/daemon/merge-sections.js +7 -7
  40. package/dist/lib/daemon/remote-control-pools.js +1 -1
  41. package/dist/lib/daemon/run.js +1 -1
  42. package/dist/lib/daemon/state-file.d.ts +1 -1
  43. package/dist/lib/daemon/state-file.js +1 -1
  44. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +21 -0
  45. package/dist/lib/doctor/checks/antigravity-wiring.js +75 -0
  46. package/dist/lib/doctor/checks/anywhere.js +30 -0
  47. package/dist/lib/doctor/checks/runtime-probe.js +13 -0
  48. package/dist/lib/doctor/platform.d.ts +1 -1
  49. package/dist/lib/doctor/platform.js +5 -0
  50. package/dist/lib/doctor/registry.js +3 -0
  51. package/dist/lib/flag-snapshot-file.d.ts +2 -0
  52. package/dist/lib/flag-snapshot-file.js +118 -48
  53. package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
  54. package/dist/lib/hook-engine/canary-gate.js +138 -6
  55. package/dist/lib/hook-engine/coverage.d.ts +91 -0
  56. package/dist/lib/hook-engine/coverage.js +184 -0
  57. package/dist/lib/hot-channels/graph-context.d.ts +105 -0
  58. package/dist/lib/hot-channels/graph-context.js +377 -0
  59. package/dist/lib/hot-channels/signals-pass.js +27 -1
  60. package/dist/lib/install/antigravity-targets.d.ts +39 -0
  61. package/dist/lib/install/antigravity-targets.js +122 -0
  62. package/dist/lib/lanes/claude-credential.d.ts +1 -1
  63. package/dist/lib/lanes/claude-credential.js +1 -1
  64. package/dist/lib/lanes/delivery-core.d.ts +1 -1
  65. package/dist/lib/lanes/delivery-core.js +1 -1
  66. package/dist/lib/lanes/delivery.d.ts +10 -10
  67. package/dist/lib/lanes/delivery.js +8 -8
  68. package/dist/lib/lanes/dropbox.d.ts +1 -1
  69. package/dist/lib/lanes/dropbox.js +1 -1
  70. package/dist/lib/lanes/hooks-install.js +2 -2
  71. package/dist/lib/lanes/index.d.ts +1 -1
  72. package/dist/lib/lanes/index.js +1 -1
  73. package/dist/lib/lanes/monitor.js +1 -1
  74. package/dist/lib/lanes/quota-notice.js +1 -1
  75. package/dist/lib/lanes/quota.d.ts +1 -1
  76. package/dist/lib/lanes/quota.js +1 -1
  77. package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
  78. package/dist/lib/lanes/repo-merge-hold.js +2 -2
  79. package/dist/lib/lanes/spawn.d.ts +4 -4
  80. package/dist/lib/lanes/spawn.js +5 -5
  81. package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
  82. package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
  83. package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
  84. package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
  85. package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
  86. package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
  87. package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
  88. package/dist/lib/mesh/live/daemon/run.js +35 -2
  89. package/dist/lib/mesh/live/direct-drain.js +1 -1
  90. package/dist/lib/mesh/live/emit.d.ts +3 -0
  91. package/dist/lib/mesh/live/emit.js +32 -9
  92. package/dist/lib/mesh/live/flush.d.ts +3 -0
  93. package/dist/lib/mesh/live/flush.js +115 -32
  94. package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
  95. package/dist/lib/mesh/live/liveness-carry.js +1 -1
  96. package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
  97. package/dist/lib/mesh/live/reporting-privacy.js +235 -11
  98. package/dist/lib/mesh/live/spool.d.ts +17 -2
  99. package/dist/lib/mesh/live/spool.js +22 -6
  100. package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
  101. package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
  102. package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
  103. package/dist/lib/ontology-graph/legacy/index.js +1150 -0
  104. package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
  105. package/dist/lib/ontology-graph/legacy/parse.js +126 -0
  106. package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
  107. package/dist/lib/ontology-graph/legacy/report.js +254 -0
  108. package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
  109. package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
  110. package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
  111. package/dist/lib/ontology-graph/lint/checks.js +717 -0
  112. package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
  113. package/dist/lib/ontology-graph/lint/coverage.js +241 -0
  114. package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
  115. package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
  116. package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
  117. package/dist/lib/ontology-graph/lint/index.js +176 -0
  118. package/dist/lib/ontology-graph/model/files.d.ts +20 -0
  119. package/dist/lib/ontology-graph/model/files.js +89 -0
  120. package/dist/lib/ontology-graph/model/index.d.ts +65 -0
  121. package/dist/lib/ontology-graph/model/index.js +100 -0
  122. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
  123. package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
  124. package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
  125. package/dist/lib/ontology-graph/model/pass.js +958 -0
  126. package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
  127. package/dist/lib/ontology-graph/model/runner.js +160 -0
  128. package/dist/lib/ontology-graph/model/step.d.ts +195 -0
  129. package/dist/lib/ontology-graph/model/step.js +523 -0
  130. package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
  131. package/dist/lib/ontology-graph/model/tasks.js +349 -0
  132. package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
  133. package/dist/lib/ontology-graph/not-implemented.js +8 -0
  134. package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
  135. package/dist/lib/ontology-graph/org/compare.js +239 -0
  136. package/dist/lib/ontology-graph/org/derive.d.ts +65 -0
  137. package/dist/lib/ontology-graph/org/derive.js +352 -0
  138. package/dist/lib/ontology-graph/org/index.d.ts +73 -0
  139. package/dist/lib/ontology-graph/org/index.js +513 -0
  140. package/dist/lib/ontology-graph/org/load.d.ts +31 -0
  141. package/dist/lib/ontology-graph/org/load.js +476 -0
  142. package/dist/lib/ontology-graph/org/role.d.ts +38 -0
  143. package/dist/lib/ontology-graph/org/role.js +268 -0
  144. package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
  145. package/dist/lib/ontology-graph/org/structure.js +437 -0
  146. package/dist/lib/ontology-graph/org/text.d.ts +95 -0
  147. package/dist/lib/ontology-graph/org/text.js +315 -0
  148. package/dist/lib/ontology-graph/org/types.d.ts +452 -0
  149. package/dist/lib/ontology-graph/org/types.js +80 -0
  150. package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
  151. package/dist/lib/ontology-graph/pages/index.js +193 -0
  152. package/dist/lib/ontology-graph/pages/render.d.ts +142 -0
  153. package/dist/lib/ontology-graph/pages/render.js +682 -0
  154. package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
  155. package/dist/lib/ontology-graph/proposals/apply.js +468 -0
  156. package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
  157. package/dist/lib/ontology-graph/proposals/group.js +232 -0
  158. package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
  159. package/dist/lib/ontology-graph/proposals/index.js +474 -0
  160. package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
  161. package/dist/lib/ontology-graph/proposals/model.js +196 -0
  162. package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
  163. package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
  164. package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
  165. package/dist/lib/ontology-graph/read/brief.js +251 -0
  166. package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
  167. package/dist/lib/ontology-graph/read/graph-index.js +198 -0
  168. package/dist/lib/ontology-graph/read/index.d.ts +59 -0
  169. package/dist/lib/ontology-graph/read/index.js +792 -0
  170. package/dist/lib/ontology-graph/read/member.d.ts +7 -0
  171. package/dist/lib/ontology-graph/read/member.js +34 -0
  172. package/dist/lib/ontology-graph/read/names.d.ts +44 -0
  173. package/dist/lib/ontology-graph/read/names.js +292 -0
  174. package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
  175. package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
  176. package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
  177. package/dist/lib/ontology-graph/read/test-graph.js +150 -0
  178. package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
  179. package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
  180. package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
  181. package/dist/lib/ontology-graph/replay/config.js +105 -0
  182. package/dist/lib/ontology-graph/replay/engine.d.ts +100 -0
  183. package/dist/lib/ontology-graph/replay/engine.js +1174 -0
  184. package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
  185. package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
  186. package/dist/lib/ontology-graph/replay/index.d.ts +90 -0
  187. package/dist/lib/ontology-graph/replay/index.js +220 -0
  188. package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
  189. package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
  190. package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
  191. package/dist/lib/ontology-graph/replay/member.js +65 -0
  192. package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
  193. package/dist/lib/ontology-graph/replay/mentions.js +239 -0
  194. package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
  195. package/dist/lib/ontology-graph/replay/readers.js +1251 -0
  196. package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
  197. package/dist/lib/ontology-graph/replay/rules.js +374 -0
  198. package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
  199. package/dist/lib/ontology-graph/replay/scope.js +115 -0
  200. package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
  201. package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
  202. package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
  203. package/dist/lib/ontology-graph/replay/util.js +256 -0
  204. package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
  205. package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
  206. package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
  207. package/dist/lib/ontology-graph/resolve/index.js +214 -0
  208. package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
  209. package/dist/lib/ontology-graph/resolve/machine.js +95 -0
  210. package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
  211. package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
  212. package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
  213. package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
  214. package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
  215. package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
  216. package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
  217. package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
  218. package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
  219. package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
  220. package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
  221. package/dist/lib/ontology-graph/resolve/roster.js +226 -0
  222. package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
  223. package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
  224. package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
  225. package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
  226. package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
  227. package/dist/lib/ontology-graph/resolve/writer.js +351 -0
  228. package/dist/lib/ontology-graph/schema/authority.d.ts +73 -0
  229. package/dist/lib/ontology-graph/schema/authority.js +157 -0
  230. package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
  231. package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
  232. package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
  233. package/dist/lib/ontology-graph/schema/grammar.js +409 -0
  234. package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
  235. package/dist/lib/ontology-graph/schema/index.js +10 -0
  236. package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
  237. package/dist/lib/ontology-graph/schema/validate.js +132 -0
  238. package/dist/lib/ontology-graph/store/files.d.ts +34 -0
  239. package/dist/lib/ontology-graph/store/files.js +207 -0
  240. package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
  241. package/dist/lib/ontology-graph/store/fs.js +101 -0
  242. package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
  243. package/dist/lib/ontology-graph/store/graph-store.js +520 -0
  244. package/dist/lib/ontology-graph/store/index.d.ts +18 -0
  245. package/dist/lib/ontology-graph/store/index.js +15 -0
  246. package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
  247. package/dist/lib/ontology-graph/store/ingest.js +323 -0
  248. package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
  249. package/dist/lib/ontology-graph/store/paths.js +232 -0
  250. package/dist/lib/ontology-graph/types.d.ts +1183 -0
  251. package/dist/lib/ontology-graph/types.js +131 -0
  252. package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
  253. package/dist/utils/frontmatter.d.ts +14 -0
  254. package/dist/utils/frontmatter.js +18 -0
  255. package/dist/utils/interactive-caller.js +1 -1
  256. package/package.json +8 -8
@@ -0,0 +1,58 @@
1
+ /**
2
+ * WP-C: the merge policy used when an input wants to create an entity (the
3
+ * identity seed and the legacy import). It decides between "this is an entity
4
+ * we already have", "create it", "create it and file a merge proposal" and
5
+ * "refuse".
6
+ *
7
+ * Rules (design 2.5 and the builder brief):
8
+ * - An identity key (email, Slack id, external id, web domain) merges.
9
+ * - A person is never merged on a name alone. Two inputs with the same full
10
+ * name share one entity only when they do not carry different emails. Any
11
+ * other name evidence (alias, first name, fuzzy) files a proposal.
12
+ * - A person is never created from a Slack id, a job title, a generic word or
13
+ * a placeholder such as "Unknown team member".
14
+ * - Other types merge on the same normalized name (unless the two carry
15
+ * different record ids or web domains), on a name that is a recorded alias,
16
+ * and on a known variant suffix of a project name. A fuzzy match, or an
17
+ * alias carried by the candidate itself, files a proposal.
18
+ */
19
+ import type { EntityKeys, EntityRef, GraphEntityType, ResolutionReason } from "../types.js";
20
+ import type { EntityIndex } from "./entity-index.js";
21
+ import type { NotAPersonReason } from "./machine.js";
22
+ import type { RosterReason } from "./roster.js";
23
+ export interface UpsertCandidate {
24
+ type: GraphEntityType;
25
+ name: string;
26
+ aliases?: readonly string[];
27
+ keys?: Partial<EntityKeys>;
28
+ }
29
+ export type UpsertReason = ResolutionReason | "identical_name" | "variant" | RosterReason | "roster_same_name" | "tool_same_name" | "product_same_name";
30
+ /** Why a candidate became nothing. The last three are this package's own codes. */
31
+ export type RefusalReason = ResolutionReason | NotAPersonReason | "company_name_as_person";
32
+ export type UpsertDecision = {
33
+ action: "merge";
34
+ into: EntityRef;
35
+ reason: UpsertReason;
36
+ score: number;
37
+ propose?: EntityRef[];
38
+ } | {
39
+ action: "create";
40
+ propose?: {
41
+ candidates: EntityRef[];
42
+ reason: UpsertReason;
43
+ };
44
+ } | {
45
+ action: "refuse";
46
+ reason: RefusalReason;
47
+ };
48
+ /** A repo name without the trailing word that marks it as the source tree of a project the board names. */
49
+ export declare function repoProjectName(repo: string): string;
50
+ /** The base names a variant name may fold into, longest first. `hq core v1509 fix` yields `hq core v1509`, `hq core`. */
51
+ export declare function variantBases(normalized: string): string[];
52
+ export declare function decideUpsert(index: EntityIndex, candidate: UpsertCandidate): UpsertDecision;
53
+ /**
54
+ * A slug for a new entity that no other entity holds: `slugify(name)`, then
55
+ * the fallback, then a numeric suffix. Null when no slug can be made.
56
+ */
57
+ export declare function uniqueSlug(index: EntityIndex, type: GraphEntityType, name: string, fallback?: string, ownPath?: string): string | null;
58
+ //# sourceMappingURL=upsert.d.ts.map
@@ -0,0 +1,139 @@
1
+ import { slugify } from "../schema/index.js";
2
+ import { nameTokens, normalizeName, slackIdInside } from "./normalize.js";
3
+ /**
4
+ * Trailing words that make a project name a note about another project, not a
5
+ * project of its own: `hq-session-hooks-bug`, `hq-installer-win-pr-2`,
6
+ * `hq-cli-npm-package`, `hq-core-v16`.
7
+ */
8
+ const VARIANT_SUFFIXES = [
9
+ / (?:bug|fix|bugfix|bug fix|bug report|hotfix)$/,
10
+ / pr [0-9]+$/,
11
+ / v[0-9]+(?: [0-9]+)*$/,
12
+ / (?:npm package|repo|repository)$/,
13
+ // A repo's remote name beside the name the board uses: `hq-desktop-app-src` is `hq-desktop-app`.
14
+ / (?:src|source)$/,
15
+ // A copy saved under a content hash: `hq-desktop-activation-storyboard-d4014717ec12`.
16
+ / (?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{12}$/,
17
+ ];
18
+ /** A repo name without the trailing word that marks it as the source tree of a project the board names. */
19
+ export function repoProjectName(repo) {
20
+ const base = repo.replace(/[-_. ](?:src|source)$/i, "");
21
+ return base.trim() === "" ? repo : base;
22
+ }
23
+ const VARIANT_TYPES = new Set(["project", "product"]);
24
+ /** The base names a variant name may fold into, longest first. `hq core v1509 fix` yields `hq core v1509`, `hq core`. */
25
+ export function variantBases(normalized) {
26
+ const bases = [];
27
+ let current = normalized;
28
+ for (let guard = 0; guard < 4; guard += 1) {
29
+ const suffix = VARIANT_SUFFIXES.find((pattern) => pattern.test(current));
30
+ if (!suffix)
31
+ break;
32
+ current = current.replace(suffix, "");
33
+ if (nameTokens(current).length === 0)
34
+ break;
35
+ bases.push(current);
36
+ }
37
+ return bases;
38
+ }
39
+ export function decideUpsert(index, candidate) {
40
+ const { type, name } = candidate;
41
+ const norm = normalizeName(name);
42
+ const isPerson = type === "person";
43
+ if (isPerson && slackIdInside(name))
44
+ return { action: "refuse", reason: "unknown_slack_id" };
45
+ // Pass 1: identity keys.
46
+ const keyed = index.byKeys(candidate.keys, [type]);
47
+ if (keyed.length > 0) {
48
+ const sameName = keyed.find((ref) => index.get(ref)?.norm === norm);
49
+ const into = sameName ?? keyed[0];
50
+ const rest = keyed.filter((ref) => ref !== into);
51
+ return { action: "merge", into, reason: "identity_key", score: 1, ...(rest.length > 0 ? { propose: rest } : {}) };
52
+ }
53
+ if (norm === "")
54
+ return { action: "refuse", reason: "refused_short" };
55
+ if (isPerson || type === "company") {
56
+ if (index.isGeneric(norm))
57
+ return { action: "refuse", reason: "refused_generic" };
58
+ }
59
+ if (isPerson) {
60
+ if (index.isPlaceholderPerson(norm))
61
+ return { action: "refuse", reason: "refused_generic" };
62
+ if (index.isJobTitle(name))
63
+ return { action: "refuse", reason: "refused_job_title" };
64
+ // A first name, a misspelling or a cut-short form of exactly one roster person, with no key that says otherwise.
65
+ const variant = index.rosterVariant(name, candidate.keys);
66
+ if (variant)
67
+ return { action: "merge", into: variant.ref, reason: variant.reason, score: 0.9 };
68
+ // A bot, a service account or a group name is not a person.
69
+ const not = index.notAPerson({ name, emails: candidate.keys?.email ?? [], externalIds: candidate.keys?.external_ids ?? [] });
70
+ if (not && index.findSameName("person", name).length === 0)
71
+ return { action: "refuse", reason: not };
72
+ }
73
+ // The same label within one type is the same entity, unless two people carry different emails.
74
+ const same = index.findSameName(type, name);
75
+ if (same.length > 0) {
76
+ const into = same[0];
77
+ if (isPerson && index.emailsConflict(into, candidate.keys?.email)) {
78
+ return { action: "create", propose: { candidates: same, reason: "exact_name" } };
79
+ }
80
+ if (!isPerson && same.every((ref) => index.recordsConflict(ref, candidate.keys))) {
81
+ return { action: "create", propose: { candidates: same, reason: "exact_name" } };
82
+ }
83
+ const free = isPerson ? into : same.find((ref) => !index.recordsConflict(ref, candidate.keys));
84
+ return { action: "merge", into: free, reason: "identical_name", score: 1 };
85
+ }
86
+ const resolution = index.resolve({ text: name, types: [type] });
87
+ if (isPerson) {
88
+ // Name evidence never merges two people. It files a proposal.
89
+ if (resolution.candidates.length > 0) {
90
+ return { action: "create", propose: { candidates: resolution.candidates, reason: resolution.reason } };
91
+ }
92
+ return { action: "create" };
93
+ }
94
+ if (resolution.status === "resolved" && resolution.entity && resolution.reason !== "fuzzy" && !index.recordsConflict(resolution.entity, candidate.keys)) {
95
+ return { action: "merge", into: resolution.entity, reason: resolution.reason, score: resolution.score };
96
+ }
97
+ if (VARIANT_TYPES.has(type)) {
98
+ for (const base of variantBases(norm)) {
99
+ const hit = index.findSameName(type, base);
100
+ if (hit.length === 1)
101
+ return { action: "merge", into: hit[0], reason: "variant", score: 0.9 };
102
+ }
103
+ }
104
+ if (resolution.candidates.length > 0) {
105
+ return { action: "create", propose: { candidates: resolution.candidates, reason: resolution.reason } };
106
+ }
107
+ // The candidate's own aliases may name an entity we already have. That is a hint, not an identity.
108
+ for (const alias of candidate.aliases ?? []) {
109
+ if (nameTokens(normalizeName(alias)).length < 2)
110
+ continue;
111
+ const hit = index.findSameName(type, alias);
112
+ if (hit.length === 1)
113
+ return { action: "create", propose: { candidates: hit, reason: "alias" } };
114
+ }
115
+ return { action: "create" };
116
+ }
117
+ /**
118
+ * A slug for a new entity that no other entity holds: `slugify(name)`, then
119
+ * the fallback, then a numeric suffix. Null when no slug can be made.
120
+ */
121
+ export function uniqueSlug(index, type, name, fallback, ownPath) {
122
+ const base = slugify(name) || (fallback ? slugify(fallback) : "");
123
+ if (base === "" || !/^[a-z0-9]/.test(base))
124
+ return null;
125
+ // Free: no entity holds it, and it is not the old path of another old entity file.
126
+ const free = (slug) => {
127
+ const ref = `${type}/${slug}`;
128
+ return !index.has(ref) && (!index.isReserved(ref) || ref === ownPath);
129
+ };
130
+ if (free(base))
131
+ return base;
132
+ for (let suffix = 2; suffix < 1000; suffix += 1) {
133
+ const slug = `${base}-${suffix}`;
134
+ if (free(slug))
135
+ return slug;
136
+ }
137
+ return null;
138
+ }
139
+ //# sourceMappingURL=upsert.js.map
@@ -0,0 +1,128 @@
1
+ import type { AudienceKey, Contradiction, EdgeRow, EntityKeys, EntityRef, FactRow, GraphEntity, GraphEntityType, GraphRow, GraphSchema, GraphStore, IngestBatch, IngestResult, IsoDate, IsoTimestamp, Origin, Proposal, SourceRef, UnresolvedMention, Verb } from "../types.js";
2
+ import type { EntityIndex } from "./entity-index.js";
3
+ import { type UpsertCandidate, type UpsertDecision, type UpsertReason } from "./upsert.js";
4
+ export type ApplyIngest = (store: GraphStore, batch: IngestBatch) => IngestResult;
5
+ export interface WriterOptions {
6
+ schema: GraphSchema;
7
+ index: EntityIndex;
8
+ /** Null on a dry run. */
9
+ store: GraphStore | null;
10
+ apply: ApplyIngest;
11
+ /** Timestamp stamped on proposals, read from the clock by the caller. */
12
+ now: IsoTimestamp;
13
+ /** Rows per `applyIngest` batch. */
14
+ batchRows?: number;
15
+ }
16
+ export interface EnsureInput extends UpsertCandidate {
17
+ seen: IsoDate;
18
+ /** A later day the entity was also seen on. */
19
+ lastSeen?: IsoDate;
20
+ legacyIds?: readonly string[];
21
+ /** Used when the name makes no slug. */
22
+ slugFallback?: string;
23
+ /** The old `type/slug` path of the file this input came from: the one reserved path it may take as its id. */
24
+ ownPath?: string;
25
+ /** Cited on a proposal this input causes. */
26
+ evidence: SourceRef;
27
+ /** When true, a merge keeps the candidate's name out of the target's aliases. */
28
+ dropNameOnMerge?: boolean;
29
+ /** Reasons for which a possible match is counted and not filed as a proposal. */
30
+ quietReasons?: readonly UpsertReason[];
31
+ }
32
+ export interface EnsureResult {
33
+ ref: EntityRef | null;
34
+ decision: UpsertDecision;
35
+ created: boolean;
36
+ }
37
+ export interface WriterCounts {
38
+ entitiesCreated: number;
39
+ entitiesMerged: number;
40
+ mergesByReason: Record<string, number>;
41
+ refusalsByReason: Record<string, number>;
42
+ proposals: number;
43
+ /** Possible matches that were counted and not filed (`quietReasons`). */
44
+ hintsNotFiled: number;
45
+ rowsQueued: number;
46
+ rowsDuplicate: number;
47
+ rowsRefused: number;
48
+ rowsAdded: number;
49
+ rowsClosed: number;
50
+ contradictions: number;
51
+ batches: number;
52
+ }
53
+ export declare function proposalId(kind: string, entity: string, parts: readonly string[]): string;
54
+ export declare class GraphWriter {
55
+ readonly schema: GraphSchema;
56
+ readonly index: EntityIndex;
57
+ readonly counts: WriterCounts;
58
+ readonly proposals: Map<string, Proposal>;
59
+ readonly unresolved: UnresolvedMention[];
60
+ /** Contradictions `applyIngest` reported, for the proposals package. */
61
+ readonly contradictions: Contradiction[];
62
+ /** Proposals filed, by `<type>, <reason>`. */
63
+ readonly proposalsByKind: Record<string, number>;
64
+ /** Entities this writer created, by type. */
65
+ readonly createdByType: Record<string, number>;
66
+ /** Rows queued, by verb, fact field (`F:<field>`) or `timeline`. */
67
+ readonly rowsByKind: Record<string, number>;
68
+ /** Names folded into a roster person without a person deciding, each with its reason code and what was cited. */
69
+ readonly rosterMerges: {
70
+ name: string;
71
+ into: EntityRef;
72
+ reason: UpsertReason;
73
+ evidence: SourceRef;
74
+ }[];
75
+ readonly touched: Set<`company/${string}` | `person/${string}` | `tool/${string}` | `project/${string}` | `contract/${string}` | `team/${string}` | `role/${string}` | `decision/${string}` | `concept/${string}` | `product/${string}` | `contact/${string}` | `deal/${string}` | `invoice/${string}` | `meeting/${string}`>;
76
+ private readonly store;
77
+ private readonly apply;
78
+ private readonly now;
79
+ private readonly batchRows;
80
+ private readonly entities;
81
+ private readonly seenRows;
82
+ private queue;
83
+ constructor(options: WriterOptions);
84
+ get dryRun(): boolean;
85
+ entity(ref: EntityRef): GraphEntity | null;
86
+ private writeEntity;
87
+ /** Adds aliases or keys to an entity that exists. */
88
+ enrich(ref: EntityRef, input: {
89
+ aliases?: readonly string[];
90
+ keys?: Partial<EntityKeys>;
91
+ seen: IsoDate;
92
+ legacyIds?: readonly string[];
93
+ }): void;
94
+ /**
95
+ * Applies the merge policy to one candidate: merges it into an entity we
96
+ * have, creates it, creates it and files a proposal, or refuses it.
97
+ */
98
+ ensure(input: EnsureInput): EnsureResult;
99
+ /** Files a merge proposal: `from` may be the same thing as one of `candidates`. Never merges. */
100
+ proposeMerge(from: EntityRef, candidates: readonly EntityRef[], reason: UpsertReason, evidence: SourceRef): void;
101
+ park(mention: UnresolvedMention): void;
102
+ private rowKey;
103
+ /** Queues a row. Returns false when it is a duplicate or the schema refuses it. */
104
+ addRow(entity: EntityRef, audience: AudienceKey, row: GraphRow): boolean;
105
+ private readonly factValues;
106
+ /** True when this writer already queued this value for the field, from any source. */
107
+ hasFact(entity: EntityRef, field: string, value: string): boolean;
108
+ /** True when this edge, or its inverse from the other end, is already queued for any source. */
109
+ hasEdge(entity: EntityRef, verb: Verb, target: EntityRef): boolean;
110
+ private readonly edgePairs;
111
+ /** Notes an edge by its two ends, so the same statement from another source or the other end is dropped. */
112
+ claimEdge(entity: EntityRef, verb: Verb, target: EntityRef): boolean;
113
+ /** Writes queued rows through `applyIngest`. `input` and `date` become the log entry. */
114
+ flush(input: SourceRef, date: IsoDate): void;
115
+ }
116
+ export interface Stamp {
117
+ from: IsoDate;
118
+ src: SourceRef;
119
+ learned: IsoDate;
120
+ by: Origin;
121
+ conf: number;
122
+ }
123
+ export declare function factRow(field: string, value: string, stamp: Stamp): FactRow;
124
+ export declare function edgeRow(verb: Verb, target: EntityRef, stamp: Stamp, was?: string): EdgeRow;
125
+ /** `2026-06-25T01:36:02.367Z` or `2026-06-25` to `2026-06-25`. Null when the text holds no day. */
126
+ export declare function dayOf(value: unknown): IsoDate | null;
127
+ export declare function typeOfRef(ref: EntityRef): GraphEntityType;
128
+ //# sourceMappingURL=writer.d.ts.map
@@ -0,0 +1,351 @@
1
+ /**
2
+ * WP-C: the one path by which the identity seed and the legacy import put
3
+ * entities and rows into the graph. It applies the merge policy, keeps the
4
+ * index current, drops duplicate rows (including an edge stated from both
5
+ * ends), collects merge proposals and unresolved mentions, and hands rows to
6
+ * `applyIngest` in batches. On a dry run it does all of that in memory and
7
+ * writes nothing.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { inverseEdge, isIsoDate, rowId, validateEntityUpsert, validateRow } from "../schema/index.js";
11
+ import { sortedUnique } from "./normalize.js";
12
+ import { ROSTER_REASONS } from "./roster.js";
13
+ import { decideUpsert, uniqueSlug } from "./upsert.js";
14
+ function bump(record, key, by = 1) {
15
+ record[key] = (record[key] ?? 0) + by;
16
+ }
17
+ function mergeLists(a, b) {
18
+ return sortedUnique([...(a ?? []), ...(b ?? [])]);
19
+ }
20
+ export function proposalId(kind, entity, parts) {
21
+ return createHash("sha256").update([kind, entity, ...parts].join("\n")).digest("hex").slice(0, 12);
22
+ }
23
+ export class GraphWriter {
24
+ schema;
25
+ index;
26
+ counts = {
27
+ entitiesCreated: 0,
28
+ entitiesMerged: 0,
29
+ mergesByReason: {},
30
+ refusalsByReason: {},
31
+ proposals: 0,
32
+ hintsNotFiled: 0,
33
+ rowsQueued: 0,
34
+ rowsDuplicate: 0,
35
+ rowsRefused: 0,
36
+ rowsAdded: 0,
37
+ rowsClosed: 0,
38
+ contradictions: 0,
39
+ batches: 0,
40
+ };
41
+ proposals = new Map();
42
+ unresolved = [];
43
+ /** Contradictions `applyIngest` reported, for the proposals package. */
44
+ contradictions = [];
45
+ /** Proposals filed, by `<type>, <reason>`. */
46
+ proposalsByKind = {};
47
+ /** Entities this writer created, by type. */
48
+ createdByType = {};
49
+ /** Rows queued, by verb, fact field (`F:<field>`) or `timeline`. */
50
+ rowsByKind = {};
51
+ /** Names folded into a roster person without a person deciding, each with its reason code and what was cited. */
52
+ rosterMerges = [];
53
+ touched = new Set();
54
+ store;
55
+ apply;
56
+ now;
57
+ batchRows;
58
+ entities = new Map();
59
+ seenRows = new Set();
60
+ queue = [];
61
+ constructor(options) {
62
+ this.schema = options.schema;
63
+ this.index = options.index;
64
+ this.store = options.store;
65
+ this.apply = options.apply;
66
+ this.now = options.now;
67
+ this.batchRows = options.batchRows ?? 4000;
68
+ }
69
+ get dryRun() {
70
+ return this.store === null;
71
+ }
72
+ entity(ref) {
73
+ return this.entities.get(ref) ?? this.store?.readEntity(ref) ?? null;
74
+ }
75
+ writeEntity(input) {
76
+ const refusals = validateEntityUpsert(this.schema, input);
77
+ if (refusals.length > 0)
78
+ throw new Error(`ontology graph: entity refused: ${input.type}/${input.slug}: ${refusals[0].message}`);
79
+ let result;
80
+ if (this.store) {
81
+ result = this.store.upsertEntity(input);
82
+ }
83
+ else {
84
+ const ref = `${input.type}/${input.slug}`;
85
+ const existing = this.entities.get(ref) ?? null;
86
+ const canonical = existing?.canonical_name ?? input.canonical_name.trim();
87
+ const entity = {
88
+ id: ref,
89
+ type: input.type,
90
+ canonical_name: canonical,
91
+ slug: input.slug,
92
+ aliases: mergeLists(existing?.aliases, [...(input.aliases ?? []), input.canonical_name.trim()]).filter((alias) => alias !== canonical),
93
+ keys: {
94
+ email: mergeLists(existing?.keys.email, input.keys?.email?.map((value) => value.toLowerCase())),
95
+ slack_id: mergeLists(existing?.keys.slack_id, input.keys?.slack_id),
96
+ external_ids: mergeLists(existing?.keys.external_ids, input.keys?.external_ids),
97
+ web_domains: mergeLists(existing?.keys.web_domains, input.keys?.web_domains?.map((value) => value.toLowerCase())),
98
+ },
99
+ first_seen: existing && existing.first_seen < input.seen ? existing.first_seen : input.seen,
100
+ last_updated: existing && existing.last_updated > input.seen ? existing.last_updated : input.seen,
101
+ legacy_ids: mergeLists(existing?.legacy_ids, input.legacy_ids),
102
+ };
103
+ result = { entity, created: existing === null };
104
+ }
105
+ this.entities.set(result.entity.id, result.entity);
106
+ this.index.add(result.entity);
107
+ this.touched.add(result.entity.id);
108
+ return result;
109
+ }
110
+ /** Adds aliases or keys to an entity that exists. */
111
+ enrich(ref, input) {
112
+ const existing = this.entity(ref);
113
+ if (!existing)
114
+ return;
115
+ this.writeEntity({
116
+ type: existing.type,
117
+ slug: existing.slug,
118
+ canonical_name: existing.canonical_name,
119
+ aliases: [...(input.aliases ?? [])],
120
+ ...(input.keys ? { keys: input.keys } : {}),
121
+ seen: input.seen,
122
+ ...(input.legacyIds ? { legacy_ids: [...input.legacyIds] } : {}),
123
+ });
124
+ }
125
+ /**
126
+ * Applies the merge policy to one candidate: merges it into an entity we
127
+ * have, creates it, creates it and files a proposal, or refuses it.
128
+ */
129
+ ensure(input) {
130
+ const decision = decideUpsert(this.index, input);
131
+ if (decision.action === "refuse") {
132
+ bump(this.counts.refusalsByReason, decision.reason);
133
+ return { ref: null, decision, created: false };
134
+ }
135
+ // Aliases another entity already answers to would make later matches ambiguous: leave them out.
136
+ const freeAliases = (self) => [...(input.aliases ?? [])].filter((alias) => {
137
+ const holders = this.index.resolve({ text: alias }).candidates;
138
+ return holders.every((holder) => holder === self);
139
+ });
140
+ if (decision.action === "merge") {
141
+ const target = this.entity(decision.into);
142
+ if (!target)
143
+ throw new Error(`ontology graph: merge target is not in the store: ${decision.into}`);
144
+ const rosterVariant = ROSTER_REASONS.includes(decision.reason);
145
+ // A variant folded into a roster person is kept as an alias, so the next mention of it lands in the same place.
146
+ const sameLabel = decision.reason === "identical_name" || decision.reason === "identity_key" || rosterVariant;
147
+ if (rosterVariant)
148
+ this.rosterMerges.push({ name: input.name.trim(), into: decision.into, reason: decision.reason, evidence: input.evidence });
149
+ const aliases = freeAliases(decision.into);
150
+ if (!input.dropNameOnMerge && (sameLabel || target.type !== "person"))
151
+ aliases.push(input.name);
152
+ this.writeEntity({
153
+ type: target.type,
154
+ slug: target.slug,
155
+ canonical_name: target.canonical_name,
156
+ aliases,
157
+ ...(input.keys ? { keys: input.keys } : {}),
158
+ seen: input.seen,
159
+ ...(input.legacyIds ? { legacy_ids: [...input.legacyIds] } : {}),
160
+ });
161
+ if (input.lastSeen && input.lastSeen !== input.seen)
162
+ this.enrich(decision.into, { seen: input.lastSeen });
163
+ this.counts.entitiesMerged += 1;
164
+ bump(this.counts.mergesByReason, decision.reason);
165
+ for (const other of decision.propose ?? []) {
166
+ this.proposeMerge(other, [decision.into], "identity_key", input.evidence);
167
+ }
168
+ return { ref: decision.into, decision, created: false };
169
+ }
170
+ const slug = uniqueSlug(this.index, input.type, input.name, input.slugFallback, input.ownPath);
171
+ if (!slug) {
172
+ bump(this.counts.refusalsByReason, "no_slug");
173
+ return { ref: null, decision: { action: "refuse", reason: "refused_short" }, created: false };
174
+ }
175
+ const ref = `${input.type}/${slug}`;
176
+ const { entity } = this.writeEntity({
177
+ type: input.type,
178
+ slug,
179
+ canonical_name: input.name.trim(),
180
+ aliases: freeAliases(null),
181
+ ...(input.keys ? { keys: input.keys } : {}),
182
+ seen: input.seen,
183
+ ...(input.legacyIds ? { legacy_ids: [...input.legacyIds] } : {}),
184
+ });
185
+ if (input.lastSeen && input.lastSeen !== input.seen)
186
+ this.enrich(entity.id, { seen: input.lastSeen });
187
+ this.counts.entitiesCreated += 1;
188
+ bump(this.createdByType, input.type);
189
+ if (decision.propose) {
190
+ if (input.quietReasons?.includes(decision.propose.reason))
191
+ this.counts.hintsNotFiled += 1;
192
+ else
193
+ this.proposeMerge(ref, decision.propose.candidates, decision.propose.reason, input.evidence);
194
+ }
195
+ return { ref, decision, created: true };
196
+ }
197
+ /** Files a merge proposal: `from` may be the same thing as one of `candidates`. Never merges. */
198
+ proposeMerge(from, candidates, reason, evidence) {
199
+ const others = sortedUnique(candidates).filter((candidate) => candidate !== from);
200
+ if (others.length === 0)
201
+ return;
202
+ const id = proposalId("merge", from, others);
203
+ if (this.proposals.has(id))
204
+ return;
205
+ const name = this.entity(from)?.canonical_name ?? from;
206
+ this.proposals.set(id, {
207
+ id,
208
+ kind: "merge",
209
+ entity: from,
210
+ rows: [],
211
+ summary: others.length === 1
212
+ ? `"${name}" (${from}) may be the same as ${others[0]} (${reason}). Not merged.`
213
+ : `"${name}" (${from}) may be one of ${others.length} entities (${reason}): ${others.join(", ")}. Not merged.`,
214
+ action: others.length === 1 ? { type: "merge", from, into: others[0] } : { type: "none" },
215
+ evidence: [evidence],
216
+ filedAt: this.now,
217
+ });
218
+ this.counts.proposals += 1;
219
+ bump(this.proposalsByKind, `${typeOfRef(from)}, ${reason}`);
220
+ }
221
+ park(mention) {
222
+ this.unresolved.push(mention);
223
+ bump(this.counts.refusalsByReason, mention.reason);
224
+ }
225
+ rowKey(entity, audience, row) {
226
+ return `${audience}\n${entity}\n${rowId(row)}`;
227
+ }
228
+ /** Queues a row. Returns false when it is a duplicate or the schema refuses it. */
229
+ addRow(entity, audience, row) {
230
+ const refusals = validateRow(this.schema, entity, row, audience);
231
+ if (refusals.length > 0) {
232
+ this.counts.rowsRefused += 1;
233
+ bump(this.counts.refusalsByReason, `row_${refusals[0].code}`);
234
+ return false;
235
+ }
236
+ const keys = [this.rowKey(entity, audience, row)];
237
+ if (row.kind === "E") {
238
+ const inverse = inverseEdge(this.schema, entity, row);
239
+ if (inverse) {
240
+ if (validateRow(this.schema, inverse.entity, inverse.row, audience).length > 0) {
241
+ this.counts.rowsRefused += 1;
242
+ bump(this.counts.refusalsByReason, "row_bad_inverse");
243
+ return false;
244
+ }
245
+ keys.push(this.rowKey(inverse.entity, audience, inverse.row));
246
+ }
247
+ }
248
+ if (keys.some((key) => this.seenRows.has(key))) {
249
+ this.counts.rowsDuplicate += 1;
250
+ return false;
251
+ }
252
+ for (const key of keys)
253
+ this.seenRows.add(key);
254
+ if (row.kind === "F")
255
+ this.factValues.add(`${entity}\n${row.field}\n${row.value}`);
256
+ this.queue.push({ entity, audience, row });
257
+ this.counts.rowsQueued += 1;
258
+ bump(this.rowsByKind, row.kind === "E" ? row.verb : row.kind === "F" ? `F:${row.field}` : "timeline");
259
+ this.touched.add(entity);
260
+ this.index.noteAudience(entity, audience);
261
+ return true;
262
+ }
263
+ factValues = new Set();
264
+ /** True when this writer already queued this value for the field, from any source. */
265
+ hasFact(entity, field, value) {
266
+ return this.factValues.has(`${entity}\n${field}\n${value}`);
267
+ }
268
+ /** True when this edge, or its inverse from the other end, is already queued for any source. */
269
+ hasEdge(entity, verb, target) {
270
+ return this.edgePairs.has(`${verb}\n${entity}\n${target}`);
271
+ }
272
+ edgePairs = new Set();
273
+ /** Notes an edge by its two ends, so the same statement from another source or the other end is dropped. */
274
+ claimEdge(entity, verb, target) {
275
+ const forward = `${verb}\n${entity}\n${target}`;
276
+ if (this.edgePairs.has(forward))
277
+ return false;
278
+ this.edgePairs.add(forward);
279
+ const inverse = this.schema.link_types[verb]?.inverse;
280
+ if (inverse)
281
+ this.edgePairs.add(`${inverse}\n${target}\n${entity}`);
282
+ return true;
283
+ }
284
+ /** Writes queued rows through `applyIngest`. `input` and `date` become the log entry. */
285
+ flush(input, date) {
286
+ if (!isIsoDate(date))
287
+ throw new Error(`ontology graph: flush date is not a day: ${date}`);
288
+ const rows = this.queue;
289
+ const unresolved = this.unresolved.splice(0);
290
+ this.queue = [];
291
+ if (rows.length === 0 && unresolved.length === 0)
292
+ return;
293
+ if (!this.store) {
294
+ this.counts.rowsAdded += rows.length;
295
+ return;
296
+ }
297
+ for (let start = 0; start < Math.max(rows.length, 1); start += this.batchRows) {
298
+ const chunk = rows.slice(start, start + this.batchRows);
299
+ const result = this.apply(this.store, {
300
+ input,
301
+ date,
302
+ entities: [],
303
+ rows: chunk,
304
+ ...(start === 0 && unresolved.length > 0 ? { unresolved } : {}),
305
+ });
306
+ this.counts.rowsAdded += result.rowsAdded;
307
+ this.counts.rowsClosed += result.rowsClosed;
308
+ this.counts.contradictions += result.contradictions.length;
309
+ this.contradictions.push(...result.contradictions);
310
+ this.counts.batches += 1;
311
+ }
312
+ }
313
+ }
314
+ export function factRow(field, value, stamp) {
315
+ return {
316
+ kind: "F",
317
+ field,
318
+ value: value.replace(/\s+/g, " ").trim(),
319
+ valid: { from: stamp.from },
320
+ src: stamp.src,
321
+ learned: stamp.learned,
322
+ by: stamp.by,
323
+ conf: stamp.conf,
324
+ };
325
+ }
326
+ export function edgeRow(verb, target, stamp, was) {
327
+ return {
328
+ kind: "E",
329
+ verb,
330
+ target,
331
+ valid: { from: stamp.from },
332
+ src: stamp.src,
333
+ learned: stamp.learned,
334
+ by: stamp.by,
335
+ conf: stamp.conf,
336
+ ...(was !== undefined && was.trim() !== "" ? { was: was.replace(/\s+/g, " ").trim() } : {}),
337
+ };
338
+ }
339
+ /** `2026-06-25T01:36:02.367Z` or `2026-06-25` to `2026-06-25`. Null when the text holds no day. */
340
+ export function dayOf(value) {
341
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
342
+ return value.toISOString().slice(0, 10);
343
+ if (typeof value !== "string")
344
+ return null;
345
+ const match = /^(\d{4}-\d{2}-\d{2})(?:$|[T ])/.exec(value.trim());
346
+ return match && isIsoDate(match[1]) ? match[1] : null;
347
+ }
348
+ export function typeOfRef(ref) {
349
+ return ref.slice(0, ref.indexOf("/"));
350
+ }
351
+ //# sourceMappingURL=writer.js.map