@indigoai-us/hq-cli 5.345.247 → 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 (239) hide show
  1. package/CHANGELOG.md +54 -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 +1113 -0
  5. package/dist/command-catalog.generated.js +1370 -0
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/lanes-hold.js +7 -7
  9. package/dist/commands/lanes-resume.js +2 -2
  10. package/dist/commands/lanes-review.js +1 -1
  11. package/dist/commands/lanes-session-start.d.ts +1 -1
  12. package/dist/commands/lanes-session-start.js +3 -3
  13. package/dist/commands/lanes-shared.d.ts +1 -1
  14. package/dist/commands/lanes.d.ts +2 -2
  15. package/dist/commands/lanes.js +50 -50
  16. package/dist/commands/mesh.d.ts +25 -0
  17. package/dist/commands/mesh.js +48 -8
  18. package/dist/commands/ontology-graph.d.ts +62 -0
  19. package/dist/commands/ontology-graph.js +439 -0
  20. package/dist/index.js +1 -1
  21. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  22. package/dist/lanes-monitor-check-argv.js +1 -1
  23. package/dist/lanes-monitor-check-fast.d.ts +1 -1
  24. package/dist/lanes-monitor-check-fast.js +1 -1
  25. package/dist/lanes-session-start-argv.d.ts +1 -1
  26. package/dist/lanes-session-start-argv.js +1 -1
  27. package/dist/lib/capacity/sign-in.d.ts +1 -1
  28. package/dist/lib/capacity/sign-in.js +1 -1
  29. package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
  30. package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
  31. package/dist/lib/daemon/lanes-monitor-state.js +2 -2
  32. package/dist/lib/daemon/merge-sections.d.ts +3 -3
  33. package/dist/lib/daemon/merge-sections.js +7 -7
  34. package/dist/lib/daemon/remote-control-pools.js +1 -1
  35. package/dist/lib/daemon/run.js +1 -1
  36. package/dist/lib/daemon/state-file.d.ts +1 -1
  37. package/dist/lib/daemon/state-file.js +1 -1
  38. package/dist/lib/flag-snapshot-file.d.ts +2 -0
  39. package/dist/lib/flag-snapshot-file.js +118 -48
  40. package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
  41. package/dist/lib/hook-engine/canary-gate.js +138 -6
  42. package/dist/lib/hot-channels/graph-context.d.ts +105 -0
  43. package/dist/lib/hot-channels/graph-context.js +377 -0
  44. package/dist/lib/hot-channels/signals-pass.js +27 -1
  45. package/dist/lib/lanes/claude-credential.d.ts +1 -1
  46. package/dist/lib/lanes/claude-credential.js +1 -1
  47. package/dist/lib/lanes/delivery-core.d.ts +1 -1
  48. package/dist/lib/lanes/delivery-core.js +1 -1
  49. package/dist/lib/lanes/delivery.d.ts +10 -10
  50. package/dist/lib/lanes/delivery.js +8 -8
  51. package/dist/lib/lanes/dropbox.d.ts +1 -1
  52. package/dist/lib/lanes/dropbox.js +1 -1
  53. package/dist/lib/lanes/hooks-install.js +2 -2
  54. package/dist/lib/lanes/index.d.ts +1 -1
  55. package/dist/lib/lanes/index.js +1 -1
  56. package/dist/lib/lanes/monitor.js +1 -1
  57. package/dist/lib/lanes/quota-notice.js +1 -1
  58. package/dist/lib/lanes/quota.d.ts +1 -1
  59. package/dist/lib/lanes/quota.js +1 -1
  60. package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
  61. package/dist/lib/lanes/repo-merge-hold.js +2 -2
  62. package/dist/lib/lanes/spawn.d.ts +4 -4
  63. package/dist/lib/lanes/spawn.js +5 -5
  64. package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
  65. package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
  66. package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
  67. package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
  68. package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
  69. package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
  71. package/dist/lib/mesh/live/daemon/run.js +35 -2
  72. package/dist/lib/mesh/live/direct-drain.js +1 -1
  73. package/dist/lib/mesh/live/emit.d.ts +3 -0
  74. package/dist/lib/mesh/live/emit.js +32 -9
  75. package/dist/lib/mesh/live/flush.d.ts +3 -0
  76. package/dist/lib/mesh/live/flush.js +115 -32
  77. package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
  78. package/dist/lib/mesh/live/liveness-carry.js +1 -1
  79. package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
  80. package/dist/lib/mesh/live/reporting-privacy.js +235 -11
  81. package/dist/lib/mesh/live/spool.d.ts +17 -2
  82. package/dist/lib/mesh/live/spool.js +22 -6
  83. package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
  84. package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
  85. package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
  86. package/dist/lib/ontology-graph/legacy/index.js +1150 -0
  87. package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
  88. package/dist/lib/ontology-graph/legacy/parse.js +126 -0
  89. package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
  90. package/dist/lib/ontology-graph/legacy/report.js +254 -0
  91. package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
  92. package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
  93. package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
  94. package/dist/lib/ontology-graph/lint/checks.js +717 -0
  95. package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
  96. package/dist/lib/ontology-graph/lint/coverage.js +241 -0
  97. package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
  98. package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
  99. package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
  100. package/dist/lib/ontology-graph/lint/index.js +176 -0
  101. package/dist/lib/ontology-graph/model/files.d.ts +20 -0
  102. package/dist/lib/ontology-graph/model/files.js +89 -0
  103. package/dist/lib/ontology-graph/model/index.d.ts +65 -0
  104. package/dist/lib/ontology-graph/model/index.js +100 -0
  105. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
  106. package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
  107. package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
  108. package/dist/lib/ontology-graph/model/pass.js +958 -0
  109. package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
  110. package/dist/lib/ontology-graph/model/runner.js +160 -0
  111. package/dist/lib/ontology-graph/model/step.d.ts +195 -0
  112. package/dist/lib/ontology-graph/model/step.js +523 -0
  113. package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
  114. package/dist/lib/ontology-graph/model/tasks.js +349 -0
  115. package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
  116. package/dist/lib/ontology-graph/not-implemented.js +8 -0
  117. package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
  118. package/dist/lib/ontology-graph/org/compare.js +239 -0
  119. package/dist/lib/ontology-graph/org/derive.d.ts +65 -0
  120. package/dist/lib/ontology-graph/org/derive.js +352 -0
  121. package/dist/lib/ontology-graph/org/index.d.ts +73 -0
  122. package/dist/lib/ontology-graph/org/index.js +513 -0
  123. package/dist/lib/ontology-graph/org/load.d.ts +31 -0
  124. package/dist/lib/ontology-graph/org/load.js +476 -0
  125. package/dist/lib/ontology-graph/org/role.d.ts +38 -0
  126. package/dist/lib/ontology-graph/org/role.js +268 -0
  127. package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
  128. package/dist/lib/ontology-graph/org/structure.js +437 -0
  129. package/dist/lib/ontology-graph/org/text.d.ts +95 -0
  130. package/dist/lib/ontology-graph/org/text.js +315 -0
  131. package/dist/lib/ontology-graph/org/types.d.ts +452 -0
  132. package/dist/lib/ontology-graph/org/types.js +80 -0
  133. package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
  134. package/dist/lib/ontology-graph/pages/index.js +193 -0
  135. package/dist/lib/ontology-graph/pages/render.d.ts +142 -0
  136. package/dist/lib/ontology-graph/pages/render.js +682 -0
  137. package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
  138. package/dist/lib/ontology-graph/proposals/apply.js +468 -0
  139. package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
  140. package/dist/lib/ontology-graph/proposals/group.js +232 -0
  141. package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
  142. package/dist/lib/ontology-graph/proposals/index.js +474 -0
  143. package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
  144. package/dist/lib/ontology-graph/proposals/model.js +196 -0
  145. package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
  146. package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
  147. package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
  148. package/dist/lib/ontology-graph/read/brief.js +251 -0
  149. package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
  150. package/dist/lib/ontology-graph/read/graph-index.js +198 -0
  151. package/dist/lib/ontology-graph/read/index.d.ts +59 -0
  152. package/dist/lib/ontology-graph/read/index.js +792 -0
  153. package/dist/lib/ontology-graph/read/member.d.ts +7 -0
  154. package/dist/lib/ontology-graph/read/member.js +34 -0
  155. package/dist/lib/ontology-graph/read/names.d.ts +44 -0
  156. package/dist/lib/ontology-graph/read/names.js +292 -0
  157. package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
  158. package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
  159. package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
  160. package/dist/lib/ontology-graph/read/test-graph.js +150 -0
  161. package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
  162. package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
  163. package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
  164. package/dist/lib/ontology-graph/replay/config.js +105 -0
  165. package/dist/lib/ontology-graph/replay/engine.d.ts +100 -0
  166. package/dist/lib/ontology-graph/replay/engine.js +1174 -0
  167. package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
  168. package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
  169. package/dist/lib/ontology-graph/replay/index.d.ts +90 -0
  170. package/dist/lib/ontology-graph/replay/index.js +220 -0
  171. package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
  172. package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
  173. package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
  174. package/dist/lib/ontology-graph/replay/member.js +65 -0
  175. package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
  176. package/dist/lib/ontology-graph/replay/mentions.js +239 -0
  177. package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
  178. package/dist/lib/ontology-graph/replay/readers.js +1251 -0
  179. package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
  180. package/dist/lib/ontology-graph/replay/rules.js +374 -0
  181. package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
  182. package/dist/lib/ontology-graph/replay/scope.js +115 -0
  183. package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
  184. package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
  185. package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
  186. package/dist/lib/ontology-graph/replay/util.js +256 -0
  187. package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
  188. package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
  189. package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
  190. package/dist/lib/ontology-graph/resolve/index.js +214 -0
  191. package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
  192. package/dist/lib/ontology-graph/resolve/machine.js +95 -0
  193. package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
  194. package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
  195. package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
  196. package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
  197. package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
  198. package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
  199. package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
  200. package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
  201. package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
  202. package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
  203. package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
  204. package/dist/lib/ontology-graph/resolve/roster.js +226 -0
  205. package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
  206. package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
  207. package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
  208. package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
  209. package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
  210. package/dist/lib/ontology-graph/resolve/writer.js +351 -0
  211. package/dist/lib/ontology-graph/schema/authority.d.ts +73 -0
  212. package/dist/lib/ontology-graph/schema/authority.js +157 -0
  213. package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
  214. package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
  215. package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
  216. package/dist/lib/ontology-graph/schema/grammar.js +409 -0
  217. package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
  218. package/dist/lib/ontology-graph/schema/index.js +10 -0
  219. package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
  220. package/dist/lib/ontology-graph/schema/validate.js +132 -0
  221. package/dist/lib/ontology-graph/store/files.d.ts +34 -0
  222. package/dist/lib/ontology-graph/store/files.js +207 -0
  223. package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
  224. package/dist/lib/ontology-graph/store/fs.js +101 -0
  225. package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
  226. package/dist/lib/ontology-graph/store/graph-store.js +520 -0
  227. package/dist/lib/ontology-graph/store/index.d.ts +18 -0
  228. package/dist/lib/ontology-graph/store/index.js +15 -0
  229. package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
  230. package/dist/lib/ontology-graph/store/ingest.js +323 -0
  231. package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
  232. package/dist/lib/ontology-graph/store/paths.js +232 -0
  233. package/dist/lib/ontology-graph/types.d.ts +1183 -0
  234. package/dist/lib/ontology-graph/types.js +131 -0
  235. package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
  236. package/dist/utils/frontmatter.d.ts +14 -0
  237. package/dist/utils/frontmatter.js +18 -0
  238. package/dist/utils/interactive-caller.js +1 -1
  239. package/package.json +8 -8
@@ -0,0 +1,682 @@
1
+ /**
2
+ * WP-D: renders one compiled entity page from rows (design 2.10, corrections C7
3
+ * and C8). Pure: no file access and no model call. The same rows and the same
4
+ * day always give the same bytes.
5
+ *
6
+ * A page leads with what a colleague asks first, by entity type:
7
+ * person role, employer, team, manager, reports; what they work on now; recent timeline
8
+ * project status, owner, lead; team; customer; the last 30 days; decisions
9
+ * company relation, stage; contacts; commitments; recent meetings; decisions
10
+ * meeting summary; decisions; action items; attendees; topics
11
+ * then the remaining facts and relationships, then history. Closed rows are
12
+ * hidden by default and counted.
13
+ *
14
+ * Every bullet line ends with ` | @<audience> | row <row id> | src <ref>`. The
15
+ * audience marker says which `facts/@<key>/` folder the row came from, so a
16
+ * reader can drop the lines a caller may not see (`filterPageLines`). No line
17
+ * mixes rows of two audiences.
18
+ */
19
+ import yaml from "js-yaml";
20
+ import { effectiveFacts, escapeText, formatConf, isOpen, isSingleValued, originTier } from "../schema/index.js";
21
+ import { sha256Hex } from "../model/files.js";
22
+ export const DEFAULT_PAGE_LIMITS = {
23
+ edgesPerVerb: 25, timeline: 30, summarySentences: 6, recentDays: 30, decisions: 12, commitments: 12, showClosed: false,
24
+ };
25
+ const CLASS_ORDER = { state: 0, event: 1, reference: 2 };
26
+ function sentence(text) {
27
+ const flat = text.replace(/\s+/g, " ").trim();
28
+ return /[.!?]$/.test(flat) ? flat : `${flat}.`;
29
+ }
30
+ function clip(text, max) {
31
+ const flat = text.replace(/\s+/g, " ").trim();
32
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
33
+ }
34
+ function label(token) {
35
+ const words = token.replace(/_/g, " ");
36
+ return words.charAt(0).toUpperCase() + words.slice(1);
37
+ }
38
+ function byCode(a, b) {
39
+ return a < b ? -1 : a > b ? 1 : 0;
40
+ }
41
+ function addDays(day, count) {
42
+ const date = new Date(`${day}T00:00:00Z`);
43
+ if (Number.isNaN(date.getTime()))
44
+ return day;
45
+ date.setUTCDate(date.getUTCDate() + count);
46
+ return date.toISOString().slice(0, 10);
47
+ }
48
+ /** `company` first, then audience keys, then `local`: the widest audience a row was filed under wins. */
49
+ function audienceRank(audience) {
50
+ return audience === "company" ? `0${audience}` : audience === "local" ? `2${audience}` : `1${audience}`;
51
+ }
52
+ function betterEdge(a, b) {
53
+ const tierA = originTier(a.row.by);
54
+ const tierB = originTier(b.row.by);
55
+ if (tierA !== tierB)
56
+ return tierA < tierB;
57
+ if (a.row.valid.from !== b.row.valid.from)
58
+ return a.row.valid.from > b.row.valid.from;
59
+ if (a.row.conf !== b.row.conf)
60
+ return a.row.conf > b.row.conf;
61
+ return a.id < b.id;
62
+ }
63
+ /** Fields that open the summary, per type, in order. Other fields follow alphabetically. */
64
+ const FACT_PRIORITY = {
65
+ person: ["role_title", "affiliation", "status"],
66
+ project: ["summary", "stage", "status", "target_date"],
67
+ product: ["summary", "status"],
68
+ company: ["relation", "stage", "owner", "crm_status"],
69
+ decision: ["statement", "status", "decided_on"],
70
+ meeting: ["title", "date"],
71
+ team: ["purpose", "status"],
72
+ role: ["title", "scope"],
73
+ };
74
+ /** Identity keys are listed under facts; they do not describe the entity, so the summary leaves them out. */
75
+ const IDENTITY_FIELDS = new Set(["email", "slack_id", "web_domain", "repo", "url", "channel"]);
76
+ const EDGE_PRIORITY = [
77
+ "reports_to", "works_at", "member_of", "leads", "owned_by", "led_by", "decided_by", "decided_in", "about",
78
+ "part_of", "works_on", "owns", "holds_role", "customer_of", "vendor_of", "partner_of", "manages", "has_contributor",
79
+ ];
80
+ function factSentence(name, type, fact) {
81
+ const value = fact.value;
82
+ switch (`${type}.${fact.field}`) {
83
+ case "person.role_title":
84
+ return sentence(`${name} is ${value}`);
85
+ case "person.affiliation":
86
+ return sentence(`${name} is affiliated with ${value}`);
87
+ case "project.summary":
88
+ case "product.summary":
89
+ case "decision.statement":
90
+ case "team.purpose":
91
+ return sentence(value);
92
+ case "project.stage":
93
+ case "company.stage":
94
+ return sentence(`${name} is at stage ${value}`);
95
+ case "company.relation":
96
+ return value === "self" ? sentence(`${name} is this company`) : sentence(`${name} is a ${value}`);
97
+ case "decision.decided_on":
98
+ return sentence(`Decided on ${value}`);
99
+ default:
100
+ return sentence(`${label(fact.field)} is ${value}`);
101
+ }
102
+ }
103
+ function words(text) {
104
+ return text.toLowerCase().replace(/…$/, "").replace(/[^a-z0-9]+/g, " ").trim().split(" ").filter((word) => word !== "");
105
+ }
106
+ /** True when two one-line texts say the same thing: equal, one a cut-off copy of the other, or nearly the same words. */
107
+ export function sameStatement(a, b) {
108
+ const wordsA = words(a);
109
+ const wordsB = words(b);
110
+ if (wordsA.length === 0 || wordsB.length === 0)
111
+ return false;
112
+ const [short, long] = wordsA.length <= wordsB.length ? [wordsA, wordsB] : [wordsB, wordsA];
113
+ if (short.length >= 4 && short.every((word, i) => long[i] === word || (i === short.length - 1 && long[i].startsWith(word))))
114
+ return true;
115
+ if (short.length < 5)
116
+ return short.length === long.length && short.join(" ") === long.join(" ");
117
+ const setLong = new Set(long);
118
+ const shared = new Set(short.filter((word) => setLong.has(word))).size;
119
+ const union = new Set([...short, ...long]).size;
120
+ return shared / union >= 0.8;
121
+ }
122
+ /** Folds entries that say the same thing on the same day in the same audience into one line with every citation. */
123
+ function foldSame(entries) {
124
+ const out = [];
125
+ for (const entry of entries) {
126
+ const twin = out.find((kept) => kept.date === entry.date && kept.row.audience === entry.row.audience && sameStatement(kept.text, entry.text));
127
+ if (!twin) {
128
+ out.push({ ...entry });
129
+ continue;
130
+ }
131
+ if (entry.row.id === twin.row.id || twin.also?.some((row) => row.id === entry.row.id))
132
+ continue;
133
+ twin.also = [...(twin.also ?? []), entry.row];
134
+ if (entry.text.replace(/…$/, "").length > twin.text.replace(/…$/, "").length)
135
+ twin.text = entry.text;
136
+ }
137
+ return out;
138
+ }
139
+ /** Builds everything the page shows from an entity's rows. `nameOf` gives a target's display name. */
140
+ export function buildPageModel(schema, entity, storedRows, nameOf, limits = DEFAULT_PAGE_LIMITS, options = {}) {
141
+ // The same row can sit in two audience folders; a page shows it once, under the widest audience.
142
+ const unique = new Map();
143
+ for (const stored of storedRows) {
144
+ const known = unique.get(stored.id);
145
+ if (!known || audienceRank(stored.audience) < audienceRank(known.audience))
146
+ unique.set(stored.id, stored);
147
+ }
148
+ const rows = [...unique.values()];
149
+ const audiences = [...new Set(storedRows.map((stored) => stored.audience))].sort();
150
+ const type = entity.type;
151
+ const name = entity.canonical_name;
152
+ // ---- facts ----
153
+ const facts = effectiveFacts(schema, type, rows).sort((a, b) => {
154
+ const tier = originTier(a.row.by) - originTier(b.row.by);
155
+ if (tier !== 0)
156
+ return tier;
157
+ return byCode(a.row.field, b.row.field) || byCode(a.row.value, b.row.value) || byCode(a.id, b.id);
158
+ });
159
+ const conflicts = [];
160
+ const openFacts = rows.filter((stored) => stored.row.kind === "F" && isOpen(stored.row));
161
+ for (const shown of facts) {
162
+ if (!isSingleValued(schema, type, shown.row))
163
+ continue;
164
+ const others = openFacts.filter((stored) => stored.row.field === shown.row.field && stored.row.value !== shown.row.value);
165
+ if (others.length > 0)
166
+ conflicts.push({ key: shown.row.field, shown, others: others.sort((a, b) => byCode(a.id, b.id)) });
167
+ }
168
+ const conflictOf = (key) => conflicts.find((conflict) => conflict.key === key);
169
+ // ---- edges ----
170
+ const openEdges = rows.filter((stored) => stored.row.kind === "E" && isOpen(stored.row));
171
+ let hiddenEdges = 0;
172
+ const byVerb = new Map();
173
+ for (const stored of openEdges) {
174
+ const spec = schema.link_types[stored.row.verb];
175
+ if (spec?.class === "reference" && stored.row.by === "legacy") {
176
+ hiddenEdges += 1;
177
+ continue;
178
+ }
179
+ const targets = byVerb.get(stored.row.verb) ?? new Map();
180
+ const slot = targets.get(stored.row.target);
181
+ if (!slot)
182
+ targets.set(stored.row.target, { best: stored, sources: new Set([stored.row.src]) });
183
+ else {
184
+ slot.sources.add(stored.row.src);
185
+ if (betterEdge(stored, slot.best))
186
+ slot.best = stored;
187
+ }
188
+ byVerb.set(stored.row.verb, targets);
189
+ }
190
+ const edgeGroups = [...byVerb.entries()]
191
+ .map(([verb, targets]) => {
192
+ let all = [...targets.values()].sort((a, b) => (betterEdge(a.best, b.best) ? -1 : 1));
193
+ // A single-valued verb with two open targets: the best one is shown and the page flags the rest.
194
+ if (schema.link_types[verb]?.cardinality === "single" && all.length > 1) {
195
+ conflicts.push({ key: verb, shown: all[0].best, others: all.slice(1).map((slot) => slot.best) });
196
+ all = all.slice(0, 1);
197
+ }
198
+ return { verb, total: all.length, shown: all.slice(0, limits.edgesPerVerb).map((slot) => ({ stored: slot.best, sources: slot.sources.size })) };
199
+ })
200
+ .sort((a, b) => {
201
+ const classA = CLASS_ORDER[schema.link_types[a.verb]?.class ?? "reference"] ?? 2;
202
+ const classB = CLASS_ORDER[schema.link_types[b.verb]?.class ?? "reference"] ?? 2;
203
+ if (classA !== classB)
204
+ return classA - classB;
205
+ return byCode(a.verb, b.verb);
206
+ });
207
+ const groupOf = (verb) => edgeGroups.find((group) => group.verb === verb);
208
+ // ---- timeline ----
209
+ const timelineRows = rows.filter((stored) => stored.row.kind === "T");
210
+ const newestFirst = (a, b) => byCode(b.date, a.date) || byCode(a.row.id, b.row.id);
211
+ const allEntries = timelineRows.map((stored) => ({ date: stored.row.date, kind: stored.row.signalType, text: stored.row.text, row: stored })).sort(newestFirst);
212
+ const today = limits.today ?? rows.reduce((max, stored) => {
213
+ const day = stored.row.kind === "T" ? stored.row.date : stored.row.valid.from;
214
+ return day > max ? day : max;
215
+ }, "0000-00-00");
216
+ const closedRows = rows.filter((stored) => stored.row.kind !== "T" && stored.row.valid.to !== undefined);
217
+ // ---- rules summary: one row per sentence, so every sentence has one audience ----
218
+ const summary = [];
219
+ const priority = FACT_PRIORITY[type] ?? [];
220
+ const rank = (field) => (priority.includes(field) ? priority.indexOf(field) : priority.length);
221
+ const factOrder = [...facts].sort((a, b) => rank(a.row.field) - rank(b.row.field) || originTier(a.row.by) - originTier(b.row.by) || byCode(a.row.field, b.row.field));
222
+ const usedFields = new Set();
223
+ for (const stored of factOrder) {
224
+ if (summary.length >= 3)
225
+ break;
226
+ if (usedFields.has(stored.row.field) || IDENTITY_FIELDS.has(stored.row.field))
227
+ continue;
228
+ usedFields.add(stored.row.field);
229
+ summary.push({ text: factSentence(name, type, stored.row), row: stored });
230
+ }
231
+ const edgeRank = (verb) => (EDGE_PRIORITY.includes(verb) ? EDGE_PRIORITY.indexOf(verb) : EDGE_PRIORITY.length);
232
+ let edgeSentences = 0;
233
+ for (const group of [...edgeGroups].sort((a, b) => edgeRank(a.verb) - edgeRank(b.verb) || byCode(a.verb, b.verb))) {
234
+ if (edgeSentences >= 3 || summary.length >= limits.summarySentences - 1)
235
+ break;
236
+ if (schema.link_types[group.verb]?.class !== "state")
237
+ continue;
238
+ const first = group.shown[0];
239
+ if (!first)
240
+ continue;
241
+ summary.push({ text: sentence(`${label(group.verb)} ${nameOf(first.stored.row.target)}`), row: first.stored });
242
+ edgeSentences += 1;
243
+ }
244
+ const latest = allEntries[0];
245
+ if (latest && summary.length < limits.summarySentences) {
246
+ summary.push({ text: sentence(`Latest, a ${latest.kind} on ${latest.date}: ${clip(latest.text, 160)}`), row: latest.row });
247
+ }
248
+ // ---- sections ----
249
+ const sections = [];
250
+ const usedFacts = new Set();
251
+ const usedVerbs = new Set();
252
+ const usedTimeline = new Set();
253
+ const flag = (key) => {
254
+ const conflict = conflictOf(key);
255
+ return conflict ? ` | conflict: ${new Set(conflict.others.map((other) => (other.row.kind === "E" ? other.row.target : other.row.kind === "F" ? other.row.value : ""))).size + 1} open values, showing the one with the highest authority, then the newest` : "";
256
+ };
257
+ const factLine = (title, stored) => {
258
+ usedFacts.add(stored.id);
259
+ return { text: `${title}: ${escapeText(stored.row.value)} | since ${stored.row.valid.from} | by ${stored.row.by}${flag(stored.row.field)}`, row: stored };
260
+ };
261
+ const factLines = (title, field) => facts.filter((stored) => stored.row.field === field).map((stored) => factLine(title, stored));
262
+ const edgeLines = (title, verb, max = limits.edgesPerVerb, only) => {
263
+ const group = groupOf(verb);
264
+ if (!group)
265
+ return [];
266
+ if (!only)
267
+ usedVerbs.add(verb);
268
+ return group.shown
269
+ .filter(({ stored }) => !only || only(stored.row.target))
270
+ .slice(0, max)
271
+ .map(({ stored, sources }) => ({
272
+ text: `${title}: ${escapeText(nameOf(stored.row.target))} (${stored.row.target}) | since ${stored.row.valid.from} | by ${stored.row.by}${sources > 1 ? ` | sources ${sources}` : ""}${flag(verb)}`,
273
+ row: stored,
274
+ }));
275
+ };
276
+ const noteOf = (stored) => {
277
+ const note = options.modelRows?.get(`${stored.entity}|${stored.id}`);
278
+ // The row's own origin first; the model's citation file adds the lines of the source it quoted.
279
+ const by = stored.row.kind === "T" ? (stored.row.by ?? note?.by) : note?.by;
280
+ if (!by)
281
+ return "";
282
+ return ` | by ${by}${note?.lines ? ` | lines ${note.lines[0]}-${note.lines[1]}` : ""}`;
283
+ };
284
+ const timelineLine = (entry) => {
285
+ usedTimeline.add(entry.row.id);
286
+ for (const row of entry.also ?? [])
287
+ usedTimeline.add(row.id);
288
+ return { text: `${entry.date} | ${entry.kind} | ${escapeText(entry.text)}${noteOf(entry.row)}`, row: entry.row, ...(entry.also ? { also: entry.also } : {}) };
289
+ };
290
+ const counted = (title, shown, total) => (shown < total ? `${title} (${shown} of ${total})` : `${title} (${total})`);
291
+ const add = (title, lines, level = 2) => {
292
+ if (lines.length > 0)
293
+ sections.push({ title, level, lines });
294
+ };
295
+ /** Decisions about this entity: timeline rows of type decision and edges to decision entities, duplicates folded. */
296
+ let decisionsListed = false;
297
+ const decisionSection = () => {
298
+ decisionsListed = true;
299
+ const items = allEntries.filter((entry) => entry.kind === "decision").slice(0, 200);
300
+ usedVerbs.add("produced_decision");
301
+ for (const verb of ["produced_decision", "discussed_in", "decided"]) {
302
+ for (const stored of openEdges) {
303
+ if (stored.row.verb !== verb || !stored.row.target.startsWith("decision/"))
304
+ continue;
305
+ items.push({ date: stored.row.valid.from, kind: "decision", text: nameOf(stored.row.target), row: stored });
306
+ }
307
+ }
308
+ if (items.length === 0)
309
+ return;
310
+ const folded = foldSame(items.sort(newestFirst));
311
+ const shown = folded.slice(0, limits.decisions);
312
+ add(counted("Decisions", shown.length, folded.length), shown.map(timelineLine));
313
+ for (const entry of folded) {
314
+ usedTimeline.add(entry.row.id);
315
+ for (const row of entry.also ?? [])
316
+ usedTimeline.add(row.id);
317
+ }
318
+ };
319
+ const timelineSection = (title, entries, max) => {
320
+ const folded = foldSame(entries);
321
+ const shown = folded.slice(0, max);
322
+ add(shown.length < folded.length ? `${title} (newest ${shown.length} of ${folded.length})` : `${title} (${folded.length})`, shown.map(timelineLine));
323
+ };
324
+ const remainingTimeline = () => allEntries.filter((entry) => !usedTimeline.has(entry.row.id));
325
+ if (type === "person") {
326
+ add("Role and organization", [
327
+ ...factLines("Role", "role_title"),
328
+ ...edgeLines("Employer", "works_at", 3),
329
+ ...(groupOf("works_at") ? [] : factLines("Affiliation", "affiliation")),
330
+ ...edgeLines("Holds role", "holds_role", 3),
331
+ ...edgeLines("Team", "member_of", 5),
332
+ ...edgeLines("Manager", "reports_to", 1),
333
+ ...edgeLines("Reports", "manages"),
334
+ ...factLines("Status", "status"),
335
+ ]);
336
+ const work = [];
337
+ for (const verb of ["leads", "owns", "works_on"]) {
338
+ const group = groupOf(verb);
339
+ if (!group)
340
+ continue;
341
+ usedVerbs.add(verb);
342
+ for (const { stored } of group.shown)
343
+ work.push({ stored, verb });
344
+ }
345
+ work.sort((a, b) => byCode(b.stored.row.valid.from, a.stored.row.valid.from) || byCode(a.stored.id, b.stored.id));
346
+ const total = ["leads", "owns", "works_on"].reduce((sum, verb) => sum + (groupOf(verb)?.total ?? 0), 0);
347
+ const shown = work.slice(0, 15);
348
+ add(counted("Working on now", shown.length, total), shown.map(({ stored, verb }) => ({
349
+ text: `${verb} ${escapeText(nameOf(stored.row.target))} (${stored.row.target}) | since ${stored.row.valid.from} | by ${stored.row.by}`,
350
+ row: stored,
351
+ })));
352
+ timelineSection("Recent timeline", allEntries, limits.timeline);
353
+ }
354
+ else if (type === "project" || type === "product") {
355
+ add("Status and ownership", [
356
+ ...factLines("Status", "status"),
357
+ ...factLines("Stage", "stage"),
358
+ ...edgeLines("Owner", "owned_by", 1),
359
+ ...edgeLines("Lead", "led_by", 3),
360
+ ...factLines("Summary", "summary"),
361
+ ...factLines("Started", "started"),
362
+ ...factLines("Target date", "target_date"),
363
+ ]);
364
+ add(counted("Team", Math.min(groupOf("has_contributor")?.total ?? 0, limits.edgesPerVerb), groupOf("has_contributor")?.total ?? 0), edgeLines("Contributor", "has_contributor"));
365
+ add("Customer", edgeLines("Customer", "part_of", 5, (target) => target.startsWith("company/")));
366
+ const since = addDays(today, -limits.recentDays);
367
+ const recent = allEntries.filter((entry) => entry.date >= since && entry.kind !== "decision");
368
+ timelineSection(`Last ${limits.recentDays} days to ${today}`, recent, limits.timeline);
369
+ decisionSection();
370
+ timelineSection("Earlier timeline", remainingTimeline(), limits.timeline);
371
+ }
372
+ else if (type === "company") {
373
+ // The org seed writes several relation values; the ones that say what the company is to us come first.
374
+ const relationRank = ["customer", "prospect", "former customer", "partner", "investor", "vendor", "self", "billing-account"];
375
+ const relationOrder = (value) => (relationRank.includes(value) ? relationRank.indexOf(value) : relationRank.length - 1);
376
+ add("Account", [
377
+ ...factLines("Relation", "relation").sort((a, b) => relationOrder(a.row.row.value) - relationOrder(b.row.row.value)),
378
+ ...factLines("Stage", "stage"),
379
+ ...factLines("CRM status", "crm_status"),
380
+ ...factLines("Account owner", "owner"),
381
+ ...edgeLines("Customer of", "customer_of", 3),
382
+ ]);
383
+ add(counted("Contacts", Math.min(groupOf("employs")?.total ?? 0, limits.edgesPerVerb), groupOf("employs")?.total ?? 0), edgeLines("Contact", "employs"));
384
+ const since = addDays(today, -90);
385
+ const commitments = allEntries.filter((entry) => (entry.kind === "commitment" || entry.kind === "action_item") && entry.date >= since);
386
+ if (commitments.length > 0)
387
+ timelineSection(`Commitments and action items, 90 days to ${today}`, commitments, limits.commitments);
388
+ const meetings = openEdges
389
+ .filter((stored) => stored.row.verb === "discussed_in" && stored.row.target.startsWith("meeting/"))
390
+ .sort((a, b) => byCode(b.row.valid.from, a.row.valid.from) || byCode(a.id, b.id));
391
+ const seenMeetings = new Set();
392
+ const meetingLines = [];
393
+ for (const stored of meetings) {
394
+ if (seenMeetings.has(stored.row.target))
395
+ continue;
396
+ seenMeetings.add(stored.row.target);
397
+ if (meetingLines.length < 10)
398
+ meetingLines.push({ text: `${stored.row.valid.from} | ${escapeText(nameOf(stored.row.target))} (${stored.row.target})`, row: stored });
399
+ }
400
+ add(counted("Recent meetings", meetingLines.length, seenMeetings.size), meetingLines);
401
+ decisionSection();
402
+ timelineSection("Recent timeline", remainingTimeline(), limits.timeline);
403
+ }
404
+ else if (type === "meeting") {
405
+ const pick = (kinds) => allEntries.filter((entry) => kinds.includes(entry.kind));
406
+ add("What was said", foldSame(pick(["summary"])).map(timelineLine));
407
+ decisionSection();
408
+ add("Action items", foldSame(pick(["action_item", "commitment"])).map(timelineLine));
409
+ add(counted("Attendees", Math.min(groupOf("had_attendee")?.total ?? 0, limits.edgesPerVerb), groupOf("had_attendee")?.total ?? 0), edgeLines("Attendee", "had_attendee"));
410
+ add(counted("Topics", Math.min(groupOf("about")?.total ?? 0, limits.edgesPerVerb), groupOf("about")?.total ?? 0), edgeLines("About", "about"));
411
+ add("Details", [...factLines("Date", "date"), ...factLines("Title", "title"), ...factLines("Channel", "channel")]);
412
+ timelineSection("Timeline", remainingTimeline(), limits.timeline);
413
+ }
414
+ else if (type === "team") {
415
+ add("Team", [...factLines("Purpose", "purpose"), ...edgeLines("Lead", "led_by", 3), ...factLines("Status", "status"), ...edgeLines("Part of", "part_of", 3)]);
416
+ add(counted("Members", Math.min(groupOf("has_member")?.total ?? 0, limits.edgesPerVerb), groupOf("has_member")?.total ?? 0), edgeLines("Member", "has_member"));
417
+ decisionSection();
418
+ timelineSection("Recent timeline", remainingTimeline(), limits.timeline);
419
+ }
420
+ else if (type === "role") {
421
+ add("Role", [...factLines("Title", "title"), ...factLines("Scope", "scope"), ...edgeLines("Held by", "held_by"), ...edgeLines("Part of", "part_of", 3)]);
422
+ timelineSection("Timeline", remainingTimeline(), limits.timeline);
423
+ }
424
+ else {
425
+ if (type !== "decision")
426
+ decisionSection();
427
+ timelineSection("Timeline", remainingTimeline(), limits.timeline);
428
+ }
429
+ const otherFacts = facts.filter((stored) => !usedFacts.has(stored.id));
430
+ add(sections.length === 0 || type === "decision" || !FACT_PRIORITY[type] ? "Facts" : "Other facts", otherFacts.map((stored) => ({
431
+ text: `${stored.row.field} = ${escapeText(stored.row.value)} | since ${stored.row.valid.from} | by ${stored.row.by} | conf ${formatConf(stored.row.conf)}${flag(stored.row.field)}`,
432
+ row: stored,
433
+ })));
434
+ // Links to decision entities are already under Decisions.
435
+ const inDecisions = (group) => decisionsListed && (group.verb === "discussed_in" || group.verb === "decided")
436
+ ? { ...group, shown: group.shown.filter(({ stored }) => !stored.row.target.startsWith("decision/")) }
437
+ : group;
438
+ const otherGroups = edgeGroups.filter((group) => !usedVerbs.has(group.verb)).map(inDecisions).filter((group) => group.shown.length > 0);
439
+ if (otherGroups.length > 0) {
440
+ sections.push({ title: usedVerbs.size > 0 ? "Other relationships" : "Relationships", level: 2, lines: [] });
441
+ for (const group of otherGroups) {
442
+ sections.push({
443
+ title: group.shown.length < group.total ? `${group.verb} (${group.shown.length} of ${group.total})` : `${group.verb} (${group.shown.length})`,
444
+ level: 3,
445
+ lines: group.shown.map(({ stored, sources }) => ({
446
+ text: `${stored.row.verb} -> ${stored.row.target} (${escapeText(nameOf(stored.row.target))}) | since ${stored.row.valid.from} | by ${stored.row.by} | conf ${formatConf(stored.row.conf)}${sources > 1 ? ` | sources ${sources}` : ""}${flag(group.verb)}`,
447
+ row: stored,
448
+ })),
449
+ });
450
+ }
451
+ }
452
+ if (closedRows.length > 0) {
453
+ const sorted = [...closedRows].sort((a, b) => byCode(b.row.valid.to ?? "", a.row.valid.to ?? "") || byCode(a.id, b.id));
454
+ sections.push({
455
+ title: limits.showClosed ? `History (${closedRows.length} closed rows)` : `History (${closedRows.length} closed rows hidden)`,
456
+ level: 2,
457
+ lines: !limits.showClosed
458
+ ? []
459
+ : sorted.map((stored) => {
460
+ const row = stored.row;
461
+ const what = row.kind === "F" ? `${row.field} = ${escapeText(row.value)}` : `${row.verb} -> ${row.target} (${escapeText(nameOf(row.target))})`;
462
+ return { text: `${what} | from ${row.valid.from} to ${row.valid.to ?? ""} | by ${row.by}`, row: stored };
463
+ }),
464
+ });
465
+ }
466
+ const rowsHash = sha256Hex(rows
467
+ .map((stored) => `${stored.id}:${stored.audience}:${stored.row.kind !== "T" && stored.row.valid.to !== undefined ? stored.row.valid.to : ""}`)
468
+ .sort()
469
+ .join("\n")).slice(0, 16);
470
+ const shownTimeline = foldSame(allEntries).slice(0, limits.timeline);
471
+ return {
472
+ entity,
473
+ audiences,
474
+ facts,
475
+ edgeGroups,
476
+ timeline: shownTimeline,
477
+ timelineTotal: allEntries.length,
478
+ signals: timelineRows.length,
479
+ counts: {
480
+ facts: rows.filter((stored) => stored.row.kind === "F").length,
481
+ edges: rows.filter((stored) => stored.row.kind === "E").length,
482
+ timeline: timelineRows.length,
483
+ },
484
+ hiddenEdges,
485
+ closedHidden: limits.showClosed ? 0 : closedRows.length,
486
+ conflicts,
487
+ rulesSummary: summary,
488
+ sections,
489
+ rowsHash,
490
+ };
491
+ }
492
+ /** `@company`, `@local` or `@<16 hex>`: the marker a page line carries for its audience. */
493
+ export function audienceMarker(audience) {
494
+ return `@${audience}`;
495
+ }
496
+ /** ` | @<audience> | row <id> | src <ref>`: the tail every bullet line of a page carries. */
497
+ export function citeTail(stored) {
498
+ return ` | ${audienceMarker(stored.audience)} | row ${stored.id} | src ${escapeText(stored.row.src)}`;
499
+ }
500
+ const SRC = "(?:signal|source|doc|session|record|legacy):\\S";
501
+ const CITED_LINE = new RegExp(`^- \\S.* \\| @(company|local|[0-9a-f]{16}) \\| row [0-9a-f]{12} \\| src ${SRC}.*$`);
502
+ const MARKER = / \| @(company|local|[0-9a-f]{16}) \| row [0-9a-f]{12} \| src /;
503
+ /** The audience a page line is marked with, or null for a line with no marker (a heading, or a line that must not be shown). */
504
+ export function pageLineAudience(line) {
505
+ const match = MARKER.exec(line);
506
+ return match ? match[1] : null;
507
+ }
508
+ /**
509
+ * Body lines of a page that are not cited. Headings and blank lines carry no
510
+ * claim; every other line must be a bullet ending in an audience marker, a row
511
+ * id and a source.
512
+ */
513
+ export function uncitedPageLines(pageText) {
514
+ const lines = pageText.split("\n");
515
+ let start = 0;
516
+ if (lines[0] === "---") {
517
+ const end = lines.indexOf("---", 1);
518
+ start = end === -1 ? lines.length : end + 1;
519
+ }
520
+ const out = [];
521
+ for (const line of lines.slice(start)) {
522
+ if (line.trim() === "" || line.startsWith("#"))
523
+ continue;
524
+ if (!CITED_LINE.test(line))
525
+ out.push(line);
526
+ }
527
+ return out;
528
+ }
529
+ /**
530
+ * The page as a caller with these audiences may see it. A bullet line is kept
531
+ * only when its marker is one of `audiences`; a line with no marker is dropped,
532
+ * so nothing unmarked is ever shown. A heading with no line left under it goes
533
+ * too, and when anything was removed the counts in headings and frontmatter
534
+ * are dropped with it, so the page does not say how much the caller cannot see.
535
+ */
536
+ export function filterPageLines(pageText, audiences) {
537
+ const allowed = new Set(audiences);
538
+ const lines = pageText.split("\n");
539
+ let start = 0;
540
+ let front = [];
541
+ if (lines[0] === "---") {
542
+ const end = lines.indexOf("---", 1);
543
+ start = end === -1 ? lines.length : end + 1;
544
+ front = lines.slice(0, start);
545
+ }
546
+ const blocks = [{ heading: null, level: 0, bullets: [] }];
547
+ let kept = 0;
548
+ let removed = 0;
549
+ for (const line of lines.slice(start)) {
550
+ if (line.trim() === "")
551
+ continue;
552
+ const heading = /^(#{1,6}) /.exec(line);
553
+ if (heading) {
554
+ blocks.push({ heading: line, level: heading[1].length, bullets: [] });
555
+ continue;
556
+ }
557
+ const audience = pageLineAudience(line);
558
+ if (audience !== null && allowed.has(audience)) {
559
+ blocks[blocks.length - 1].bullets.push(line);
560
+ kept += 1;
561
+ }
562
+ else
563
+ removed += 1;
564
+ }
565
+ const out = [];
566
+ blocks.forEach((block, i) => {
567
+ if (block.heading === null) {
568
+ out.push(...block.bullets);
569
+ return;
570
+ }
571
+ // A heading stays when it has a line, or a deeper heading under it has one.
572
+ let alive = block.bullets.length > 0 || block.level === 1;
573
+ for (let j = i + 1; !alive && j < blocks.length && blocks[j].level > block.level; j += 1)
574
+ alive = blocks[j].bullets.length > 0;
575
+ if (!alive)
576
+ return;
577
+ if (out.length > 0)
578
+ out.push("");
579
+ out.push(removed > 0 ? block.heading.replace(/ \([^()]*\)$/, "") : block.heading, ...block.bullets);
580
+ });
581
+ if (removed > 0 && front.length > 0) {
582
+ const parsed = yaml.load(front.slice(1, -1).join("\n"));
583
+ const keep = {};
584
+ for (const key of ["id", "type", "name", "aliases"])
585
+ if (parsed && parsed[key] !== undefined)
586
+ keep[key] = parsed[key];
587
+ keep.audiences = (Array.isArray(parsed?.audiences) ? parsed.audiences : []).filter((value) => typeof value === "string" && allowed.has(value));
588
+ keep.filtered = true;
589
+ front = ["---", yaml.dump(keep, { lineWidth: -1, noRefs: true, flowLevel: 1, sortKeys: false }).trimEnd(), "---"];
590
+ }
591
+ return { text: `${[...front, ...out].join("\n").replace(/\n+$/, "")}\n`, kept, removed };
592
+ }
593
+ /**
594
+ * The lines offered to the model summary, with the row behind each label. Only
595
+ * rows of one audience are offered (`company` when the entity has any, else its
596
+ * first audience), so a summary sentence can never carry words from a narrower
597
+ * audience under a wider marker.
598
+ */
599
+ export function summaryInput(model, nameOf) {
600
+ const lines = [];
601
+ const rows = new Map();
602
+ const present = new Set([...model.facts, ...model.edgeGroups.flatMap((group) => group.shown.map((shown) => shown.stored)), ...model.timeline.map((entry) => entry.row)].map((stored) => stored.audience));
603
+ // What an audience has to say beyond links to documents that mention the entity. A customer whose only
604
+ // company-wide rows are two knowledge documents is summarized from the audience that holds its account lines.
605
+ const weight = new Map();
606
+ const weigh = (key) => void weight.set(key, (weight.get(key) ?? 0) + 1);
607
+ for (const stored of model.facts)
608
+ if (!IDENTITY_FIELDS.has(stored.row.field))
609
+ weigh(stored.audience);
610
+ for (const group of model.edgeGroups)
611
+ for (const shown of group.shown)
612
+ weigh(shown.stored.audience);
613
+ for (const entry of model.timeline)
614
+ if (entry.kind !== "doc")
615
+ weigh(entry.row.audience);
616
+ const heaviest = [...weight].sort((x, y) => y[1] - x[1] || (x[0] < y[0] ? -1 : 1))[0]?.[0];
617
+ const audience = (weight.get("company") ?? 0) > 0 ? "company" : (heaviest ?? (present.has("company") ? "company" : ([...present].sort()[0] ?? null)));
618
+ model.facts.filter((stored) => stored.audience === audience && !IDENTITY_FIELDS.has(stored.row.field)).slice(0, 20).forEach((stored, i) => {
619
+ const key = `f${i + 1}`;
620
+ rows.set(key, stored);
621
+ lines.push({ label: key, text: `${stored.row.field} = ${clip(stored.row.value, 200)} (since ${stored.row.valid.from})` });
622
+ });
623
+ let e = 0;
624
+ for (const group of model.edgeGroups) {
625
+ for (const shown of group.shown.filter((entry) => entry.stored.audience === audience).slice(0, 5)) {
626
+ if (e >= 20)
627
+ break;
628
+ e += 1;
629
+ const key = `e${e}`;
630
+ rows.set(key, shown.stored);
631
+ lines.push({ label: key, text: `${group.verb} ${clip(nameOf(shown.stored.row.target), 60)} [${shown.stored.row.target.split("/")[0]}] since ${shown.stored.row.valid.from}` });
632
+ }
633
+ }
634
+ model.timeline.filter((entry) => entry.row.audience === audience).slice(0, 25).forEach((entry, i) => {
635
+ const key = `t${i + 1}`;
636
+ rows.set(key, entry.row);
637
+ lines.push({ label: key, text: `${entry.date} ${entry.kind}: ${clip(entry.text, 180)}` });
638
+ });
639
+ return { item: { ref: model.entity.id, name: model.entity.canonical_name, lines }, rows, audience };
640
+ }
641
+ /** The page text. `summary` is the optional model layer; without it the rules sentences are the summary. */
642
+ export function renderPage(model, nameOf, summary, state = "rules") {
643
+ void nameOf;
644
+ const entity = model.entity;
645
+ const frontmatter = {
646
+ id: entity.id,
647
+ type: entity.type,
648
+ name: entity.canonical_name,
649
+ aliases: entity.aliases,
650
+ first_seen: entity.first_seen,
651
+ last_updated: entity.last_updated,
652
+ audiences: model.audiences,
653
+ rows: model.counts,
654
+ signals: model.signals,
655
+ summary_by: summary ? summary.by : "rules",
656
+ ...(summary ? {} : state === "rules" ? {} : { model_summary: state }),
657
+ ...(model.hiddenEdges > 0 ? { hidden_legacy_reference_edges: model.hiddenEdges } : {}),
658
+ ...(model.closedHidden > 0 ? { closed_rows_hidden: model.closedHidden } : {}),
659
+ ...(model.conflicts.length > 0 ? { conflicts: model.conflicts.map((conflict) => conflict.key).sort() } : {}),
660
+ rows_hash: model.rowsHash,
661
+ };
662
+ const out = ["---", yaml.dump(frontmatter, { lineWidth: -1, noRefs: true, flowLevel: 1, sortKeys: false }).trimEnd(), "---", `# ${entity.canonical_name.replace(/\s+/g, " ")}`, ""];
663
+ const tail = (cited) => `${citeTail(cited.row)}${(cited.also ?? []).map((row) => ` | also row ${row.id} | src ${escapeText(row.row.src)}`).join("")}`;
664
+ // A summary sentence is plain text and is escaped here; a section line was put together from escaped values.
665
+ const bullet = (cited) => `- ${escapeText(cited.text)}${tail(cited)}`;
666
+ const line = (cited) => `- ${cited.text}${tail(cited)}`;
667
+ if (summary && summary.sentences.length > 0) {
668
+ out.push(`## Summary (by ${summary.by})`, ...summary.sentences.map(bullet), "");
669
+ if (model.rulesSummary.length > 0)
670
+ out.push("## At a glance", ...model.rulesSummary.map(bullet), "");
671
+ }
672
+ else if (model.rulesSummary.length > 0) {
673
+ out.push("## Summary", ...model.rulesSummary.map(bullet), "");
674
+ }
675
+ for (const section of model.sections) {
676
+ if (section.level === 3 && out[out.length - 1] === "")
677
+ out.pop();
678
+ out.push(`${"#".repeat(section.level)} ${section.title}`, ...section.lines.map(line), "");
679
+ }
680
+ return `${out.join("\n").replace(/\n+$/, "")}\n`;
681
+ }
682
+ //# sourceMappingURL=render.js.map