@indigoai-us/hq-cli 5.345.247 → 5.345.250

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/assets/lanes-hooks/hq-lanes-drain.sh +1 -1
  3. package/contracts/host-canary-release.json +14 -0
  4. package/dist/command-catalog.generated.d.ts +1198 -0
  5. package/dist/command-catalog.generated.js +1476 -0
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/core-job-run-native.js +4 -0
  9. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  10. package/dist/commands/core-knowledge-prefs.js +1 -16
  11. package/dist/commands/core.js +0 -2
  12. package/dist/commands/daemon.js +21 -0
  13. package/dist/commands/lanes-hold.js +7 -7
  14. package/dist/commands/lanes-resume.js +2 -2
  15. package/dist/commands/lanes-review.js +1 -1
  16. package/dist/commands/lanes-session-start.d.ts +1 -1
  17. package/dist/commands/lanes-session-start.js +3 -3
  18. package/dist/commands/lanes-shared.d.ts +1 -1
  19. package/dist/commands/lanes.d.ts +2 -2
  20. package/dist/commands/lanes.js +50 -50
  21. package/dist/commands/mesh.d.ts +25 -0
  22. package/dist/commands/mesh.js +48 -8
  23. package/dist/commands/ontology-graph.d.ts +63 -0
  24. package/dist/commands/ontology-graph.js +470 -0
  25. package/dist/commands/sync-core.js +6 -0
  26. package/dist/fast-scaffold.js +1 -3
  27. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  28. package/dist/hq-cloud-sync-runner/package.json +1 -1
  29. package/dist/index.d.ts +8 -0
  30. package/dist/index.js +48 -1
  31. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  32. package/dist/lanes-monitor-check-argv.js +1 -1
  33. package/dist/lanes-monitor-check-fast.d.ts +1 -1
  34. package/dist/lanes-monitor-check-fast.js +1 -1
  35. package/dist/lanes-session-start-argv.d.ts +1 -1
  36. package/dist/lanes-session-start-argv.js +1 -1
  37. package/dist/lib/capacity/sign-in.d.ts +1 -1
  38. package/dist/lib/capacity/sign-in.js +1 -1
  39. package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
  40. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  41. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  42. package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
  43. package/dist/lib/daemon/lanes-monitor-state.js +2 -2
  44. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  45. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  46. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  47. package/dist/lib/daemon/machine-checks.js +10 -0
  48. package/dist/lib/daemon/merge-sections.d.ts +3 -3
  49. package/dist/lib/daemon/merge-sections.js +7 -7
  50. package/dist/lib/daemon/remote-control-pools.js +1 -1
  51. package/dist/lib/daemon/run.d.ts +3 -1
  52. package/dist/lib/daemon/run.js +49 -6
  53. package/dist/lib/daemon/state-file.d.ts +1 -1
  54. package/dist/lib/daemon/state-file.js +1 -1
  55. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  56. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  57. package/dist/lib/flag-snapshot-file.d.ts +2 -0
  58. package/dist/lib/flag-snapshot-file.js +118 -48
  59. package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
  60. package/dist/lib/hook-engine/canary-gate.js +138 -6
  61. package/dist/lib/hook-engine/coverage.d.ts +82 -13
  62. package/dist/lib/hook-engine/coverage.js +214 -18
  63. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  64. package/dist/lib/hook-engine/registration-identity.js +1 -1
  65. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  66. package/dist/lib/hook-engine/resolve.js +48 -1
  67. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  68. package/dist/lib/hook-engine/stable-heal.js +214 -0
  69. package/dist/lib/hot-channels/graph-context.d.ts +105 -0
  70. package/dist/lib/hot-channels/graph-context.js +380 -0
  71. package/dist/lib/hot-channels/signals-pass.js +27 -1
  72. package/dist/lib/lanes/claude-credential.d.ts +1 -1
  73. package/dist/lib/lanes/claude-credential.js +1 -1
  74. package/dist/lib/lanes/delivery-core.d.ts +1 -1
  75. package/dist/lib/lanes/delivery-core.js +1 -1
  76. package/dist/lib/lanes/delivery.d.ts +10 -10
  77. package/dist/lib/lanes/delivery.js +8 -8
  78. package/dist/lib/lanes/dropbox.d.ts +1 -1
  79. package/dist/lib/lanes/dropbox.js +1 -1
  80. package/dist/lib/lanes/hooks-install.js +2 -2
  81. package/dist/lib/lanes/index.d.ts +1 -1
  82. package/dist/lib/lanes/index.js +1 -1
  83. package/dist/lib/lanes/monitor.js +1 -1
  84. package/dist/lib/lanes/quota-notice.js +1 -1
  85. package/dist/lib/lanes/quota.d.ts +1 -1
  86. package/dist/lib/lanes/quota.js +1 -1
  87. package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
  88. package/dist/lib/lanes/repo-merge-hold.js +2 -2
  89. package/dist/lib/lanes/spawn.d.ts +4 -4
  90. package/dist/lib/lanes/spawn.js +5 -5
  91. package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
  92. package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
  93. package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
  94. package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
  95. package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
  96. package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
  97. package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
  98. package/dist/lib/mesh/live/daemon/run.js +35 -2
  99. package/dist/lib/mesh/live/direct-drain.js +1 -1
  100. package/dist/lib/mesh/live/emit.d.ts +3 -0
  101. package/dist/lib/mesh/live/emit.js +32 -9
  102. package/dist/lib/mesh/live/flush.d.ts +3 -0
  103. package/dist/lib/mesh/live/flush.js +115 -32
  104. package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
  105. package/dist/lib/mesh/live/liveness-carry.js +1 -1
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
  107. package/dist/lib/mesh/live/reporting-privacy.js +235 -11
  108. package/dist/lib/mesh/live/spool.d.ts +17 -2
  109. package/dist/lib/mesh/live/spool.js +22 -6
  110. package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
  111. package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
  112. package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
  113. package/dist/lib/ontology-graph/legacy/index.js +1150 -0
  114. package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
  115. package/dist/lib/ontology-graph/legacy/parse.js +126 -0
  116. package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
  117. package/dist/lib/ontology-graph/legacy/report.js +254 -0
  118. package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
  119. package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
  120. package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
  121. package/dist/lib/ontology-graph/lint/checks.js +717 -0
  122. package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
  123. package/dist/lib/ontology-graph/lint/coverage.js +241 -0
  124. package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
  125. package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
  126. package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
  127. package/dist/lib/ontology-graph/lint/index.js +176 -0
  128. package/dist/lib/ontology-graph/model/files.d.ts +20 -0
  129. package/dist/lib/ontology-graph/model/files.js +89 -0
  130. package/dist/lib/ontology-graph/model/index.d.ts +65 -0
  131. package/dist/lib/ontology-graph/model/index.js +100 -0
  132. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
  133. package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
  134. package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
  135. package/dist/lib/ontology-graph/model/pass.js +958 -0
  136. package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
  137. package/dist/lib/ontology-graph/model/runner.js +160 -0
  138. package/dist/lib/ontology-graph/model/step.d.ts +197 -0
  139. package/dist/lib/ontology-graph/model/step.js +526 -0
  140. package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
  141. package/dist/lib/ontology-graph/model/tasks.js +349 -0
  142. package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
  143. package/dist/lib/ontology-graph/not-implemented.js +8 -0
  144. package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
  145. package/dist/lib/ontology-graph/org/compare.js +239 -0
  146. package/dist/lib/ontology-graph/org/derive.d.ts +67 -0
  147. package/dist/lib/ontology-graph/org/derive.js +359 -0
  148. package/dist/lib/ontology-graph/org/index.d.ts +102 -0
  149. package/dist/lib/ontology-graph/org/index.js +630 -0
  150. package/dist/lib/ontology-graph/org/load.d.ts +31 -0
  151. package/dist/lib/ontology-graph/org/load.js +476 -0
  152. package/dist/lib/ontology-graph/org/role.d.ts +38 -0
  153. package/dist/lib/ontology-graph/org/role.js +268 -0
  154. package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
  155. package/dist/lib/ontology-graph/org/structure.js +437 -0
  156. package/dist/lib/ontology-graph/org/text.d.ts +97 -0
  157. package/dist/lib/ontology-graph/org/text.js +321 -0
  158. package/dist/lib/ontology-graph/org/types.d.ts +457 -0
  159. package/dist/lib/ontology-graph/org/types.js +80 -0
  160. package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
  161. package/dist/lib/ontology-graph/pages/index.js +193 -0
  162. package/dist/lib/ontology-graph/pages/render.d.ts +144 -0
  163. package/dist/lib/ontology-graph/pages/render.js +688 -0
  164. package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
  165. package/dist/lib/ontology-graph/proposals/apply.js +468 -0
  166. package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
  167. package/dist/lib/ontology-graph/proposals/group.js +232 -0
  168. package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
  169. package/dist/lib/ontology-graph/proposals/index.js +474 -0
  170. package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
  171. package/dist/lib/ontology-graph/proposals/model.js +196 -0
  172. package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
  173. package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
  174. package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
  175. package/dist/lib/ontology-graph/read/brief.js +254 -0
  176. package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
  177. package/dist/lib/ontology-graph/read/graph-index.js +198 -0
  178. package/dist/lib/ontology-graph/read/index.d.ts +59 -0
  179. package/dist/lib/ontology-graph/read/index.js +803 -0
  180. package/dist/lib/ontology-graph/read/member.d.ts +7 -0
  181. package/dist/lib/ontology-graph/read/member.js +34 -0
  182. package/dist/lib/ontology-graph/read/names.d.ts +49 -0
  183. package/dist/lib/ontology-graph/read/names.js +297 -0
  184. package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
  185. package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
  186. package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
  187. package/dist/lib/ontology-graph/read/test-graph.js +150 -0
  188. package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
  189. package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
  190. package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
  191. package/dist/lib/ontology-graph/replay/config.js +105 -0
  192. package/dist/lib/ontology-graph/replay/engine.d.ts +146 -0
  193. package/dist/lib/ontology-graph/replay/engine.js +1240 -0
  194. package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
  195. package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
  196. package/dist/lib/ontology-graph/replay/index.d.ts +91 -0
  197. package/dist/lib/ontology-graph/replay/index.js +220 -0
  198. package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
  199. package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
  200. package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
  201. package/dist/lib/ontology-graph/replay/member.js +65 -0
  202. package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
  203. package/dist/lib/ontology-graph/replay/mentions.js +239 -0
  204. package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
  205. package/dist/lib/ontology-graph/replay/readers.js +1251 -0
  206. package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
  207. package/dist/lib/ontology-graph/replay/rules.js +374 -0
  208. package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
  209. package/dist/lib/ontology-graph/replay/scope.js +115 -0
  210. package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
  211. package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
  212. package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
  213. package/dist/lib/ontology-graph/replay/util.js +256 -0
  214. package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
  215. package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
  216. package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
  217. package/dist/lib/ontology-graph/resolve/index.js +214 -0
  218. package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
  219. package/dist/lib/ontology-graph/resolve/machine.js +95 -0
  220. package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
  221. package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
  222. package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
  223. package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
  224. package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
  225. package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
  226. package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
  227. package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
  228. package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
  229. package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
  230. package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
  231. package/dist/lib/ontology-graph/resolve/roster.js +226 -0
  232. package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
  233. package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
  234. package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
  235. package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
  236. package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
  237. package/dist/lib/ontology-graph/resolve/writer.js +351 -0
  238. package/dist/lib/ontology-graph/schema/authority.d.ts +107 -0
  239. package/dist/lib/ontology-graph/schema/authority.js +186 -0
  240. package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
  241. package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
  242. package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
  243. package/dist/lib/ontology-graph/schema/grammar.js +409 -0
  244. package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
  245. package/dist/lib/ontology-graph/schema/index.js +10 -0
  246. package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
  247. package/dist/lib/ontology-graph/schema/validate.js +132 -0
  248. package/dist/lib/ontology-graph/store/files.d.ts +34 -0
  249. package/dist/lib/ontology-graph/store/files.js +207 -0
  250. package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
  251. package/dist/lib/ontology-graph/store/fs.js +101 -0
  252. package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
  253. package/dist/lib/ontology-graph/store/graph-store.js +520 -0
  254. package/dist/lib/ontology-graph/store/index.d.ts +18 -0
  255. package/dist/lib/ontology-graph/store/index.js +15 -0
  256. package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
  257. package/dist/lib/ontology-graph/store/ingest.js +323 -0
  258. package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
  259. package/dist/lib/ontology-graph/store/paths.js +232 -0
  260. package/dist/lib/ontology-graph/types.d.ts +1190 -0
  261. package/dist/lib/ontology-graph/types.js +131 -0
  262. package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
  263. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  264. package/dist/lib/sync-core/engine-holds.js +12 -2
  265. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  266. package/dist/lib/sync-core/hand-back.js +16 -2
  267. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  268. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  269. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  270. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  271. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  272. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  273. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  274. package/dist/lib/sync-core/reconcile.js +43 -3
  275. package/dist/utils/cli-telemetry.d.ts +1 -0
  276. package/dist/utils/cli-telemetry.js +6 -3
  277. package/dist/utils/frontmatter.d.ts +14 -0
  278. package/dist/utils/frontmatter.js +18 -0
  279. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  280. package/dist/utils/hook-engine-rollup.js +725 -0
  281. package/dist/utils/interactive-caller.js +1 -1
  282. package/package.json +9 -9
  283. package/scripts/install-hook-engine.mjs +4 -0
  284. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -0,0 +1,1555 @@
1
+ /**
2
+ * WP-B rule extractors: one document in, one ingest batch out, no model.
3
+ *
4
+ * Every row cites the input it came from (`src`), carries the event day
5
+ * (`valid`, timeline date), the replay day (`learned`), an origin (`record`
6
+ * for a field copied from a system of record, `rule:<id>` otherwise), a
7
+ * confidence and the audience of its source. Names are never decided here:
8
+ * every name goes to WP-C's resolver, and a name it does not resolve becomes
9
+ * an unresolved mention, not an entity. New entities are made only from
10
+ * structured records (roster, PRD, board, meeting, decision, repo).
11
+ *
12
+ * Round 2 (corrections C7 and C8):
13
+ * - a source with no audience key is filed under the member's local audience,
14
+ * never `company`, unless its class is one the company publishes as a record;
15
+ * - a single-valued fact or edge is written once: not when the same value is
16
+ * already open, not when an open row outranks it;
17
+ * - a timeline line that repeats one already on the entity that day (the same
18
+ * statement, or a cut copy of it) is not written;
19
+ * - Slack ids the graph knows are written as names;
20
+ * - sessions attach to work by path, never by a word in a prompt.
21
+ */
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import { originTier, parseEntityRef, rowId, slugify, validateRow } from "../schema/index.js";
25
+ import { createEdgeMemo, resolveNamesInText } from "./mentions.js";
26
+ import { audienceForInput, cleanSubject, companyScopesIn, countMentions, endOfWorkNote, excerptAround, firstRealPrompt, isBoilerplatePrompt, isChatter, isLifecycleText, isTimelineRepeat, namesAnotherCompany, pathEvidence, plainLinks, replaceSlackIds, slackIdsIn, slackMessages, transcriptCandidates, transcriptTurns, worktreeRepoCandidates, } from "./rules.js";
27
+ import { localAudienceKey } from "./scope.js";
28
+ import { asList, asRecord, asString, firstDay, listFolders, nameFromSlug, oneLine, readJsonFile, readYamlFile, stringList, toDay } from "./util.js";
29
+ const registry = new WeakMap();
30
+ export function createExtractTools(store, options = {}) {
31
+ const known = new Map();
32
+ const memberUid = options.memberUid ?? null;
33
+ return {
34
+ selfName: options.selfName ?? null,
35
+ memberUid,
36
+ memberEmails: options.memberEmails ?? [],
37
+ localKey: options.localKey ?? (memberUid ? localAudienceKey(memberUid) : null),
38
+ edges: createEdgeMemo(store),
39
+ identityPass: false,
40
+ exists(ref) {
41
+ let value = known.get(ref);
42
+ if (value === undefined) {
43
+ value = store.readEntity(ref) !== null;
44
+ known.set(ref, value);
45
+ }
46
+ return value;
47
+ },
48
+ noteExists: (ref) => void known.set(ref, true),
49
+ counters: {},
50
+ companyRoot: null,
51
+ company: null,
52
+ singles: new Map(),
53
+ timelines: new Map(),
54
+ slackNames: new Map(),
55
+ slackDirectoryNames: null,
56
+ meetingsWithSignals: new Set(),
57
+ files: new Map(),
58
+ roster: null,
59
+ };
60
+ }
61
+ /**
62
+ * The real name Slack's directory gives for an id (`.state/slack-directory.json`, kept by the identity
63
+ * seed), or "" when it has none. Used for an id no person in the graph holds. An email is not a name.
64
+ */
65
+ export function slackDirectoryName(tools, graphRoot, id) {
66
+ if (!tools.slackDirectoryNames) {
67
+ const names = new Map();
68
+ const kept = asRecord(asRecord(readJsonFile(path.join(graphRoot, ".state", "slack-directory.json"))).idToName);
69
+ for (const [slackId, name] of Object.entries(kept)) {
70
+ const text = asString(name).trim();
71
+ if (text !== "" && !text.includes("@"))
72
+ names.set(slackId, text);
73
+ }
74
+ tools.slackDirectoryNames = names;
75
+ }
76
+ return tools.slackDirectoryNames.get(id) ?? "";
77
+ }
78
+ export function registerExtractTools(store, tools) {
79
+ registry.set(store, tools);
80
+ }
81
+ function toolsFor(context) {
82
+ let tools = registry.get(context.store);
83
+ if (!tools) {
84
+ tools = createExtractTools(context.store);
85
+ registry.set(context.store, tools);
86
+ }
87
+ return tools;
88
+ }
89
+ /** The source class of a document; inferred from the path for a plain `ReplayInput`. */
90
+ export function classOf(document) {
91
+ const cls = document.input.cls;
92
+ if (cls)
93
+ return cls;
94
+ const rel = document.input.relPath;
95
+ if (rel.startsWith("signals/slack-dm/"))
96
+ return "signals.legacy.slack-dm";
97
+ if (rel.startsWith("signals/@"))
98
+ return "signals.audience";
99
+ if (rel.startsWith("signals/"))
100
+ return "signals.legacy.meeting";
101
+ if (rel.startsWith("member-signals/"))
102
+ return "member-signals";
103
+ if (rel.startsWith("sources/meetings/"))
104
+ return "sources.meetings";
105
+ if (rel.startsWith("sources/slack-dm/"))
106
+ return "sources.slack-dm";
107
+ if (rel.startsWith("sources/slack/"))
108
+ return "sources.slack";
109
+ if (rel.startsWith("sources/"))
110
+ return "sources.events";
111
+ if (rel.endsWith("/prd.json"))
112
+ return "projects.prd";
113
+ if (rel === "board.json")
114
+ return "board";
115
+ if (rel.startsWith("people/"))
116
+ return "people";
117
+ if (rel === "crm-projection.json")
118
+ return "crm";
119
+ if (rel === "customer-kpis.json")
120
+ return "customers";
121
+ if (rel.startsWith("commitments/"))
122
+ return "commitments";
123
+ if (rel.startsWith("action-items/"))
124
+ return "action-items";
125
+ if (rel.startsWith("context/decisions/"))
126
+ return "context.decisions";
127
+ if (rel.startsWith("policies/"))
128
+ return "policies";
129
+ if (rel.startsWith("knowledge/"))
130
+ return "knowledge";
131
+ if (rel.startsWith("projects/") && rel.endsWith("/README.md"))
132
+ return "projects.readme";
133
+ if (rel.startsWith("clients/"))
134
+ return "clients.md";
135
+ if (rel.startsWith("meetings/notes/"))
136
+ return "meetings.notes";
137
+ if (rel.startsWith("workspace/sessions/"))
138
+ return "company.workspace.sessions";
139
+ if (rel.startsWith("workspace/threads/"))
140
+ return "hq.workspace.threads";
141
+ if (rel.startsWith("work-mesh/"))
142
+ return "work-mesh.cache";
143
+ if (rel.startsWith("transcripts/"))
144
+ return "claude.transcripts.main";
145
+ return "";
146
+ }
147
+ const CONTENT_TYPES = ["project", "product", "company", "concept", "tool", "team"];
148
+ const WORK_TYPES = ["project", "product"];
149
+ /**
150
+ * What a meeting transcript is searched for: the organization's own work and the companies it deals
151
+ * with. Tools and concepts are said in every meeting and say nothing about any one of them.
152
+ */
153
+ const DISCUSSED_TYPES = ["project", "product", "company", "person"];
154
+ const DISCUSSED_THINGS = ["project", "product", "company"];
155
+ /** A company with one of these relations is a supplier or the member's own company, not a topic. */
156
+ const NOT_A_TOPIC = new Set(["vendor", "self", "tool"]);
157
+ /** Signal types that belong on the page of the meeting they came from. */
158
+ const MEETING_PAGE_TYPES = new Set(["summary", "decision", "action_item", "commitment"]);
159
+ const CLEANED_FIELDS = new Set(["statement", "summary", "title"]);
160
+ const ABOUT_CAP = 8;
161
+ const DISCUSSED_CAP = 10;
162
+ /** Collects one input's entities, rows and unresolved mentions, and drops any row the schema would refuse. */
163
+ class Batch {
164
+ document;
165
+ context;
166
+ input;
167
+ cls;
168
+ audience;
169
+ day;
170
+ rule;
171
+ tools;
172
+ entities = new Map();
173
+ rows = [];
174
+ rowKeys = new Set();
175
+ unresolvedRows = new Map();
176
+ pendingLines = new Map();
177
+ pendingSingles = new Map();
178
+ constructor(document, context, ruleId, audience) {
179
+ this.document = document;
180
+ this.context = context;
181
+ this.input = document.input;
182
+ this.cls = classOf(document);
183
+ this.audience = audience;
184
+ this.day = this.input.eventDate ?? this.input.date;
185
+ this.rule = `rule:${ruleId}`;
186
+ this.tools = toolsFor(context);
187
+ this.learnCompanyRoot();
188
+ }
189
+ get schema() {
190
+ return this.context.schema;
191
+ }
192
+ /** The day being replayed. */
193
+ get replayDay() {
194
+ return this.context.day;
195
+ }
196
+ get store() {
197
+ return this.context.store;
198
+ }
199
+ /** The company folder is the input's path without its relative path. */
200
+ learnCompanyRoot() {
201
+ if (this.tools.companyRoot)
202
+ return;
203
+ const rel = this.input.relPath.split("/").join(path.sep);
204
+ if (!rel || !this.input.path.endsWith(`${path.sep}${rel}`))
205
+ return;
206
+ const root = this.input.path.slice(0, -rel.length - 1);
207
+ if (path.basename(path.dirname(root)) !== "companies")
208
+ return;
209
+ this.tools.companyRoot = root;
210
+ this.tools.company = path.basename(root);
211
+ }
212
+ count(name) {
213
+ this.tools.counters[name] = (this.tools.counters[name] ?? 0) + 1;
214
+ }
215
+ /** `company` is never an answer for a class the company does not publish (C7). Null drops the row. */
216
+ place(audience) {
217
+ return audienceForInput(this.cls, audience, this.tools.localKey);
218
+ }
219
+ /** The member's local audience, for a line of a published file that is not for everyone (a roster note). */
220
+ get local() {
221
+ return this.tools.localKey;
222
+ }
223
+ push(entity, requested, row) {
224
+ const audience = this.place(requested);
225
+ if (!audience) {
226
+ this.count("rows_without_audience");
227
+ return false;
228
+ }
229
+ if (validateRow(this.context.schema, entity, row, audience).length > 0) {
230
+ this.count("rows_refused_by_schema");
231
+ return false;
232
+ }
233
+ const key = `${entity}\u0001${audience}\u0001${JSON.stringify(row)}`;
234
+ if (this.rowKeys.has(key))
235
+ return false;
236
+ this.rowKeys.add(key);
237
+ this.rows.push({ entity, audience, row });
238
+ return true;
239
+ }
240
+ upsert(type, slug, name, extra = {}) {
241
+ const canonical = oneLine(name, 160);
242
+ if (!slug || !canonical || !parseEntityRef(`${type}/${slug}`))
243
+ return null;
244
+ const ref = `${type}/${slug}`;
245
+ const previous = this.entities.get(ref);
246
+ const keys = { ...(previous?.keys ?? {}) };
247
+ for (const [key, values] of Object.entries(extra.keys ?? {})) {
248
+ const clean = (values ?? []).map((value) => value.trim()).filter((value) => value !== "");
249
+ if (clean.length > 0)
250
+ keys[key] = [...new Set([...(keys[key] ?? []), ...clean])];
251
+ }
252
+ const aliases = [...new Set([...(previous?.aliases ?? []), ...(extra.aliases ?? [])])].filter((alias) => alias.trim() !== "" && alias !== canonical);
253
+ this.entities.set(ref, {
254
+ type,
255
+ slug,
256
+ canonical_name: previous?.canonical_name ?? canonical,
257
+ seen: this.day,
258
+ ...(aliases.length > 0 ? { aliases } : {}),
259
+ ...(Object.keys(keys).length > 0 ? { keys } : {}),
260
+ });
261
+ return ref;
262
+ }
263
+ // ---- single-valued fields and verbs: one open row, one source ref per fact ----
264
+ isSingle(entity, key) {
265
+ const type = entity.slice(0, entity.indexOf("/"));
266
+ if (key.startsWith("F:"))
267
+ return this.schema.entity_types[type]?.facts[key.slice(2)]?.cardinality === "single";
268
+ return this.schema.link_types[key.slice(2)]?.cardinality === "single";
269
+ }
270
+ openSingles(entity, audience) {
271
+ const id = `${entity}@${audience}`;
272
+ let known = this.tools.singles.get(id);
273
+ if (!known) {
274
+ known = new Map();
275
+ try {
276
+ for (const stored of this.store.readRows(entity, { audiences: [audience], kinds: ["F", "E"] })) {
277
+ const row = stored.row;
278
+ if (row.kind === "T" || row.valid.to !== undefined || row.closed)
279
+ continue;
280
+ const key = row.kind === "F" ? `F:${row.field}` : `E:${row.verb}`;
281
+ if (!this.isSingle(entity, key))
282
+ continue;
283
+ const list = known.get(key) ?? [];
284
+ list.push({ value: row.kind === "F" ? row.value : row.target, from: row.valid.from, tier: originTier(row.by) });
285
+ known.set(key, list);
286
+ }
287
+ }
288
+ catch {
289
+ // an unreadable facts file is lint's finding
290
+ }
291
+ this.tools.singles.set(id, known);
292
+ }
293
+ return known;
294
+ }
295
+ /**
296
+ * May a single-valued row be written. Not when the same value is already
297
+ * open (the fact is recorded; a second source ref would only double it),
298
+ * not when an open row of higher authority says otherwise, and not when an
299
+ * open row of the same authority and the same day says otherwise. The store
300
+ * would keep both rows open in each of those cases.
301
+ */
302
+ admitSingle(entity, audience, key, value, from, by) {
303
+ if (!this.isSingle(entity, key))
304
+ return true;
305
+ const slot = `${entity}@${audience}\u0001${key}`;
306
+ const inBatch = this.pendingSingles.get(slot);
307
+ if (inBatch !== undefined) {
308
+ if (inBatch !== `${from}\u0001${value}`)
309
+ this.count("single_value_second_in_input");
310
+ return inBatch === `${from}\u0001${value}`;
311
+ }
312
+ const open = this.openSingles(entity, audience).get(key) ?? [];
313
+ const tier = originTier(by);
314
+ if (open.some((row) => row.value === value)) {
315
+ this.count("single_value_already_open");
316
+ return false;
317
+ }
318
+ if (open.some((row) => tier > row.tier)) {
319
+ this.count("single_value_outranked");
320
+ return false;
321
+ }
322
+ if (open.some((row) => row.from === from && row.tier === tier)) {
323
+ this.count("single_value_same_day");
324
+ return false;
325
+ }
326
+ this.pendingSingles.set(slot, `${from}\u0001${value}`);
327
+ if (!this.tools.identityPass) {
328
+ // What the store will do: older open rows close; a newer open row closes the incoming one instead.
329
+ const newer = open.some((row) => row.from > from);
330
+ const kept = open.filter((row) => row.from > from);
331
+ if (!newer)
332
+ kept.push({ value, from, tier });
333
+ this.openSingles(entity, audience).set(key, kept);
334
+ }
335
+ return true;
336
+ }
337
+ // ---- text ----
338
+ slackName(id) {
339
+ const known = this.tools.slackNames.get(id);
340
+ if (known)
341
+ return known;
342
+ const answer = this.context.resolver.resolve({ text: id, types: ["person"], keys: { slack_id: [id] }, audiences: this.readAudiences() });
343
+ let name = answer.status === "resolved" && answer.entity ? (this.store.readEntity(answer.entity)?.canonical_name ?? "") : "";
344
+ // No person holds the id: the real name Slack's own directory gives for it is still better than the id.
345
+ if (name === "" || slackIdsIn(name).length > 0)
346
+ name = slackDirectoryName(this.tools, this.store.root, id);
347
+ if (name === "" || slackIdsIn(name).length > 0)
348
+ return null;
349
+ this.tools.slackNames.set(id, name);
350
+ return name;
351
+ }
352
+ /** Slack ids the graph or the Slack directory knows, written as names. An id neither knows is parked as unresolved. */
353
+ clean(text) {
354
+ if (!/[UW][A-Z0-9]{7}/.test(text))
355
+ return text;
356
+ return replaceSlackIds(text, (id) => {
357
+ const name = this.slackName(id);
358
+ if (name === null && id !== "") {
359
+ this.count("slack_ids_parked");
360
+ this.recordUnresolved(id, { status: "unresolved", reason: "unknown_slack_id", candidates: [], score: 0 });
361
+ }
362
+ return name;
363
+ });
364
+ }
365
+ readAudiences() {
366
+ return this.audience === "company" ? ["company"] : ["company", this.audience];
367
+ }
368
+ fact(entity, field, value, options = {}) {
369
+ let text = oneLine(typeof value === "number" ? String(value) : value, 400);
370
+ if (!entity || text === "")
371
+ return;
372
+ if (CLEANED_FIELDS.has(field))
373
+ text = oneLine(this.clean(text), 400);
374
+ const audience = this.place(options.audience ?? this.audience);
375
+ const from = options.from ?? this.day;
376
+ const by = options.by ?? this.rule;
377
+ if (!audience || !this.admitSingle(entity, audience, `F:${field}`, text, from, by))
378
+ return;
379
+ this.push(entity, audience, { kind: "F", field, value: text, valid: { from }, src: this.input.ref, learned: this.context.day, by, conf: options.conf ?? 0.8 });
380
+ }
381
+ edge(entity, verb, target, options = {}) {
382
+ if (!entity || !target || entity === target)
383
+ return;
384
+ const audience = this.place(options.audience ?? this.audience);
385
+ if (!audience)
386
+ return;
387
+ if (options.once) {
388
+ if (this.tools.edges.has(entity, audience, verb, target))
389
+ return;
390
+ }
391
+ const from = options.from ?? this.day;
392
+ const by = options.by ?? this.rule;
393
+ if (!this.admitSingle(entity, audience, `E:${verb}`, target, from, by))
394
+ return;
395
+ const added = this.push(entity, audience, { kind: "E", verb, target, valid: { from }, src: this.input.ref, learned: this.context.day, by, conf: options.conf ?? 0.8 });
396
+ if (added && options.once && !this.tools.identityPass)
397
+ this.tools.edges.add(entity, audience, verb, target);
398
+ }
399
+ /** Adds identity keys (and aliases) to an entity that already exists, keeping its name. */
400
+ addKeys(ref, keys, aliases = []) {
401
+ const parsed = ref ? parseEntityRef(ref) : null;
402
+ if (!ref || !parsed)
403
+ return;
404
+ if (!Object.values(keys).some((list) => (list ?? []).length > 0) && aliases.length === 0)
405
+ return;
406
+ const entity = this.context.store.readEntity(ref);
407
+ if (entity)
408
+ this.upsert(parsed.type, parsed.slug, entity.canonical_name, { keys, aliases });
409
+ }
410
+ linesOn(entity, date) {
411
+ let days = this.tools.timelines.get(entity);
412
+ if (!days) {
413
+ days = new Map();
414
+ try {
415
+ for (const stored of this.store.readRows(entity, { kinds: ["T"] })) {
416
+ if (stored.row.kind !== "T")
417
+ continue;
418
+ const list = days.get(stored.row.date) ?? [];
419
+ list.push(stored.row.text);
420
+ days.set(stored.row.date, list);
421
+ }
422
+ }
423
+ catch {
424
+ // an unreadable facts file is lint's finding
425
+ }
426
+ this.tools.timelines.set(entity, days);
427
+ }
428
+ let list = days.get(date);
429
+ if (!list) {
430
+ list = [];
431
+ days.set(date, list);
432
+ }
433
+ return list;
434
+ }
435
+ timeline(entity, signalType, text, options = {}) {
436
+ const line = oneLine(plainLinks(this.clean(oneLine(text, 2000))), 240);
437
+ if (!entity || line === "")
438
+ return;
439
+ // A line that points into another company's folder is never written (C7).
440
+ if (this.tools.company && namesAnotherCompany(companyScopesIn(line, { pathsOnly: true }), this.tools.company)) {
441
+ this.count("lines_naming_another_company");
442
+ return;
443
+ }
444
+ const type = signalType.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^[^a-z]+/, "") || "doc";
445
+ const date = options.date ?? this.day;
446
+ const row = { kind: "T", date, signalType: type, text: line, src: this.input.ref };
447
+ const stored = this.linesOn(entity, date);
448
+ const slot = `${entity}\u0001${date}`;
449
+ const pending = this.pendingLines.get(slot) ?? [];
450
+ // The same statement from the same input is the row itself: replaying it adds nothing either way.
451
+ if (stored.some((known) => known !== line && isTimelineRepeat(known, line)) || pending.some((known) => known !== line && isTimelineRepeat(known, line))) {
452
+ this.count("timeline_repeats_dropped");
453
+ return;
454
+ }
455
+ if (stored.includes(line) && !this.ownLine(entity, row)) {
456
+ this.count("timeline_repeats_dropped");
457
+ return;
458
+ }
459
+ if (!this.push(entity, options.audience ?? this.audience, row))
460
+ return;
461
+ pending.push(line);
462
+ this.pendingLines.set(slot, pending);
463
+ if (!this.tools.identityPass)
464
+ stored.push(line);
465
+ }
466
+ /** Is this exact row already stored (a replay of the same input), as opposed to the same words from another source. */
467
+ ownLine(entity, row) {
468
+ const id = rowId(row);
469
+ try {
470
+ return this.store.readRows(entity, { kinds: ["T"] }).some((stored) => stored.id === id);
471
+ }
472
+ catch {
473
+ return false;
474
+ }
475
+ }
476
+ recordUnresolved(mention, answer) {
477
+ const text = oneLine(mention, 120);
478
+ if (text === "" || this.unresolvedRows.has(text))
479
+ return;
480
+ this.unresolvedRows.set(text, {
481
+ mention: text,
482
+ reason: answer.reason,
483
+ src: this.input.ref,
484
+ date: this.day,
485
+ audience: this.audience,
486
+ ...(answer.candidates.length > 0 ? { candidates: answer.candidates.slice(0, 5) } : {}),
487
+ });
488
+ }
489
+ /** Asks the resolver. A miss is recorded unless `quiet`. */
490
+ resolve(text, types, keys, quiet = false) {
491
+ const name = text.trim();
492
+ if (name === "" && !keys)
493
+ return null;
494
+ const answer = this.context.resolver.resolve({ text: name, ...(types ? { types } : {}), ...(keys ? { keys } : {}), audiences: this.readAudiences() });
495
+ if (answer.status === "resolved" && answer.entity)
496
+ return answer.entity;
497
+ if (!quiet)
498
+ this.recordUnresolved(name || Object.values(keys ?? {}).flat().join(", "), answer);
499
+ return null;
500
+ }
501
+ /** An old `type/slug` ref (signal `entity_refs`, a wiki link into the old folder). */
502
+ oldRef(value) {
503
+ const cleaned = value.trim().replace(/^ontology\/entities\//, "").replace(/\.md$/, "");
504
+ const parsed = parseEntityRef(cleaned);
505
+ if (!parsed)
506
+ return null;
507
+ const ref = cleaned;
508
+ if (this.tools.exists(ref))
509
+ return ref;
510
+ // The resolver maps an old path to the entity it became in the legacy import.
511
+ return this.resolve(cleaned, [parsed.type], undefined, true) ?? this.resolve(nameFromSlug(parsed.slug), [parsed.type]);
512
+ }
513
+ /**
514
+ * The entity for a name from a structured record: the resolver's answer, or
515
+ * a new entity when it has no match. An ambiguous or refused name is recorded
516
+ * as unresolved and makes nothing.
517
+ */
518
+ ensure(type, name, keys = {}, aliases = []) {
519
+ const display = oneLine(name, 160);
520
+ if (display === "")
521
+ return null;
522
+ const answer = this.context.resolver.resolve({ text: display, types: [type], keys, audiences: this.readAudiences() });
523
+ if (answer.status === "resolved" && answer.entity) {
524
+ this.addKeys(answer.entity, keys);
525
+ return answer.entity;
526
+ }
527
+ if (answer.status === "ambiguous" || answer.status === "refused") {
528
+ this.recordUnresolved(display, answer);
529
+ return null;
530
+ }
531
+ const slug = slugify(display);
532
+ if (!slug)
533
+ return null;
534
+ return this.upsert(type, slug, display, { keys, aliases });
535
+ }
536
+ names(text, types, limit) {
537
+ return resolveNamesInText(this.context.resolver, text, { ...(types ? { types } : {}), audiences: this.readAudiences(), limit });
538
+ }
539
+ /** People whose Slack id appears in the text. */
540
+ slackPeople(text) {
541
+ const refs = [];
542
+ for (const id of slackIdsIn(text)) {
543
+ const person = this.resolve(id, ["person"], { slack_id: [id] }, true);
544
+ if (person && !refs.includes(person))
545
+ refs.push(person);
546
+ }
547
+ return refs;
548
+ }
549
+ /** The project a folder or repo name stands for; created when the resolver has no match. */
550
+ project(folder, display, keys = {}) {
551
+ const slug = slugify(folder);
552
+ if (!slug)
553
+ return null;
554
+ const existing = `project/${slug}`;
555
+ if (this.tools.exists(existing))
556
+ return existing;
557
+ const found = this.resolve(folder, WORK_TYPES, { external_ids: [`project:${slug}`], ...keys }, true)
558
+ ?? (display && display !== folder ? this.resolve(display, WORK_TYPES, undefined, true) : null);
559
+ if (found)
560
+ return found;
561
+ const name = display && display.trim() !== "" ? display : folder;
562
+ return this.upsert("project", slug, name, { aliases: name === folder ? [] : [folder], keys: { external_ids: [`project:${slug}`], ...keys } });
563
+ }
564
+ /** The project a folder, repo or id names, when there is one. Never creates. */
565
+ findProject(name) {
566
+ const slug = slugify(name);
567
+ if (!slug)
568
+ return null;
569
+ const direct = `project/${slug}`;
570
+ if (this.tools.exists(direct))
571
+ return direct;
572
+ return this.resolve(name, WORK_TYPES, { external_ids: [`project:${slug}`] }, true);
573
+ }
574
+ /** Projects named by paths: repo folders, worktree folders (longest repo name that fits) and project folders. */
575
+ projectsByPath(texts, limit = 4) {
576
+ const company = this.tools.company ?? "";
577
+ const evidence = pathEvidence(texts, company);
578
+ const refs = [];
579
+ const add = (ref) => {
580
+ if (ref && !refs.includes(ref) && refs.length < limit)
581
+ refs.push(ref);
582
+ };
583
+ for (const name of evidence.projects)
584
+ add(this.findProject(name));
585
+ for (const name of evidence.repos)
586
+ add(this.findProject(name));
587
+ for (const name of evidence.worktrees) {
588
+ for (const candidate of worktreeRepoCandidates(name)) {
589
+ const ref = this.findProject(candidate);
590
+ if (ref) {
591
+ add(ref);
592
+ break;
593
+ }
594
+ }
595
+ }
596
+ return refs;
597
+ }
598
+ memberPerson() {
599
+ if (!this.tools.memberUid)
600
+ return null;
601
+ return this.resolve(this.tools.memberEmails[0] ?? "", ["person"], { external_ids: [`hq:${this.tools.memberUid}`], email: [...this.tools.memberEmails] }, true);
602
+ }
603
+ selfCompany() {
604
+ return this.tools.selfName ? this.resolve(this.tools.selfName, ["company"], undefined, true) : null;
605
+ }
606
+ /** Is `text` the entity's own name or slug, as opposed to one of its aliases. */
607
+ isNamed(ref, text) {
608
+ const slug = slugify(text);
609
+ if (slug !== "" && ref.slice(ref.indexOf("/") + 1) === slug)
610
+ return true;
611
+ const name = this.store.readEntity(ref)?.canonical_name ?? "";
612
+ return name !== "" && slugify(name) === slug;
613
+ }
614
+ /** Does the entity carry an open `relation` fact with one of these values. */
615
+ hasRelation(ref, values) {
616
+ if (!ref.startsWith("company/"))
617
+ return false;
618
+ try {
619
+ return this.store.readRows(ref, { kinds: ["F"] }).some((stored) => stored.row.kind === "F" && stored.row.field === "relation" && stored.row.valid.to === undefined && values.has(stored.row.value.toLowerCase()));
620
+ }
621
+ catch {
622
+ return false;
623
+ }
624
+ }
625
+ /** A file the rules read once per run (the board, the CRM projection). */
626
+ file(file, load) {
627
+ if (!this.tools.files.has(file))
628
+ this.tools.files.set(file, load(file));
629
+ return this.tools.files.get(file);
630
+ }
631
+ /** The internal roster, for first-name owners. Empty until the company folder is known. */
632
+ roster() {
633
+ if (this.tools.roster)
634
+ return this.tools.roster;
635
+ const root = this.tools.companyRoot;
636
+ if (!root)
637
+ return [];
638
+ const people = [];
639
+ for (const slug of listFolders(path.join(root, "people"))) {
640
+ if (slug.startsWith("_"))
641
+ continue;
642
+ const meta = readYamlFile(path.join(root, "people", slug, "meta.yaml"));
643
+ const name = asString(meta.name);
644
+ if (!name || asString(meta.type) === "external")
645
+ continue;
646
+ people.push({ name, first: name.split(/\s+/)[0].toLowerCase(), uid: asString(asRecord(meta.handles).hq_person_uid), email: emailOf(asString(meta.email)) });
647
+ }
648
+ this.tools.roster = people;
649
+ return people;
650
+ }
651
+ /**
652
+ * The person an owner field names: an email, a person uid, a slug, a full
653
+ * name, or a first name that exactly one roster person has. An agent id and
654
+ * a first name two people share name nobody.
655
+ */
656
+ owner(value) {
657
+ const text = value.trim();
658
+ if (text === "" || /^agt_/i.test(text))
659
+ return null;
660
+ const email = emailOf(text);
661
+ if (email)
662
+ return this.resolve(email, ["person"], { email: [email] });
663
+ if (/^prs_[A-Za-z0-9]+$/.test(text))
664
+ return this.resolve(text, ["person"], { external_ids: [`hq:${text}`] });
665
+ const name = text.includes("-") && !text.includes(" ") ? nameFromSlug(text) : text;
666
+ if (!/\s/.test(name)) {
667
+ const matches = this.roster().filter((person) => person.first === name.toLowerCase());
668
+ if (matches.length !== 1) {
669
+ this.count(matches.length === 0 ? "owner_first_name_unknown" : "owner_first_name_shared");
670
+ return null;
671
+ }
672
+ const person = matches[0];
673
+ return this.resolve(person.name, ["person"], {
674
+ ...(person.email ? { email: [person.email] } : {}),
675
+ ...(person.uid ? { external_ids: [`hq:${person.uid}`] } : {}),
676
+ });
677
+ }
678
+ return this.resolve(name, ["person"]);
679
+ }
680
+ /**
681
+ * Closes the open rows of `entity` for the given verbs that began before
682
+ * `on`, and the inverse row on each target. Used when a record says a state
683
+ * ended on a day. Does nothing in the identity pass.
684
+ */
685
+ closeEdges(entity, verbs, on) {
686
+ if (this.tools.identityPass)
687
+ return 0;
688
+ let closed = 0;
689
+ const closure = { on, by: this.input.ref };
690
+ let rows;
691
+ try {
692
+ rows = this.store.readRows(entity, { kinds: ["E"] });
693
+ }
694
+ catch {
695
+ return 0;
696
+ }
697
+ for (const stored of rows) {
698
+ const row = stored.row;
699
+ if (row.kind !== "E" || !verbs.includes(row.verb) || row.valid.to !== undefined || row.closed || row.valid.from > on)
700
+ continue;
701
+ if (this.store.closeRow(entity, stored.audience, stored.id, closure))
702
+ closed += 1;
703
+ const inverse = this.schema.link_types[row.verb]?.inverse;
704
+ if (!inverse)
705
+ continue;
706
+ try {
707
+ for (const other of this.store.readRows(row.target, { audiences: [stored.audience], kinds: ["E"] })) {
708
+ const back = other.row;
709
+ if (back.kind !== "E" || back.verb !== inverse || back.target !== entity || back.valid.to !== undefined || back.closed || back.valid.from > on)
710
+ continue;
711
+ this.store.closeRow(row.target, other.audience, other.id, closure);
712
+ }
713
+ }
714
+ catch {
715
+ // the target's facts file is unreadable: lint reports it
716
+ }
717
+ }
718
+ if (closed > 0) {
719
+ this.tools.counters.edges_closed_by_record = (this.tools.counters.edges_closed_by_record ?? 0) + closed;
720
+ this.tools.singles.clear();
721
+ }
722
+ return closed;
723
+ }
724
+ /** Closes the open fact rows of one field that began before `on` and hold another value. */
725
+ closeFacts(entity, field, keep, on) {
726
+ if (this.tools.identityPass)
727
+ return;
728
+ try {
729
+ for (const stored of this.store.readRows(entity, { kinds: ["F"] })) {
730
+ const row = stored.row;
731
+ if (row.kind !== "F" || row.field !== field || row.value === keep || row.valid.to !== undefined || row.closed)
732
+ continue;
733
+ // A row that starts after the end day is closed on its own first day: it was never true.
734
+ this.store.closeRow(entity, stored.audience, stored.id, { on: row.valid.from > on ? row.valid.from : on, by: this.input.ref });
735
+ }
736
+ }
737
+ catch {
738
+ // lint reports an unreadable facts file
739
+ }
740
+ this.tools.singles.clear();
741
+ }
742
+ build() {
743
+ if (this.entities.size === 0 && this.rows.length === 0 && this.unresolvedRows.size === 0)
744
+ return null;
745
+ return {
746
+ input: this.input.ref,
747
+ date: this.input.date,
748
+ entities: [...this.entities.values()],
749
+ rows: this.rows,
750
+ ...(this.unresolvedRows.size > 0 ? { unresolved: [...this.unresolvedRows.values()] } : {}),
751
+ };
752
+ }
753
+ }
754
+ function extractor(id, classes, run) {
755
+ const set = new Set(classes);
756
+ return {
757
+ id,
758
+ applies: (document) => set.has(classOf(document)),
759
+ extract(document, context) {
760
+ const audience = audienceForInput(classOf(document), document.input.audience, toolsFor(context).localKey);
761
+ if (!audience)
762
+ return null;
763
+ const batch = new Batch(document, context, id, audience);
764
+ run(batch, document);
765
+ return batch.build();
766
+ },
767
+ };
768
+ }
769
+ function typeOf(ref) {
770
+ return ref.slice(0, ref.indexOf("/"));
771
+ }
772
+ function splitNames(text) {
773
+ return text.split(/\s*(?:,|;|&|\band\b|\/)\s*/i).map((name) => name.replace(/[*_`[\]()]/g, "").trim()).filter((name) => name !== "");
774
+ }
775
+ function labelled(body, label) {
776
+ const match = new RegExp(`\\*\\*${label}:?\\*\\*:?\\s*([^\\n*]+)|\\*\\*${label}:\\s*([^*\\n]+)\\*\\*`, "i").exec(body);
777
+ return (match?.[1] ?? match?.[2] ?? "").trim();
778
+ }
779
+ function emailOf(value) {
780
+ const match = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/.exec(value);
781
+ return match ? match[0].toLowerCase() : "";
782
+ }
783
+ function displayName(batch, ref) {
784
+ return batch.store.readEntity(ref)?.canonical_name ?? nameFromSlug(ref.slice(ref.indexOf("/") + 1));
785
+ }
786
+ // ---------------------------------------------------------------------------
787
+ const signals = extractor("signal-entity-refs", ["signals.legacy.meeting", "signals.legacy.slack-dm", "signals.audience", "member-signals"], (batch, { frontmatter: fm, body }) => {
788
+ const type = asString(fm.type) || "signal";
789
+ const content = oneLine(asString(fm.canonical_content) || body, 400);
790
+ if (content === "")
791
+ return;
792
+ const refs = [];
793
+ const add = (ref) => {
794
+ if (ref && !refs.includes(ref))
795
+ refs.push(ref);
796
+ };
797
+ for (const old of stringList(fm.entity_refs))
798
+ add(batch.oldRef(old));
799
+ if (refs.length === 0) {
800
+ // A signal with no entity refs (every hot-channel signal): the names are in its sentence and its body.
801
+ const text = `${content}\n${body.replace(/^##\s.*$/gm, " ")}`;
802
+ for (const ref of batch.slackPeople(text))
803
+ add(ref);
804
+ for (const ref of batch.names(text, [...CONTENT_TYPES, "person"], 10))
805
+ add(ref);
806
+ }
807
+ for (const ref of refs)
808
+ batch.timeline(ref, type, content);
809
+ // The meeting the signal came from carries its own summary, decisions and action items.
810
+ const source = parseEntityRef(asString(fm.__source_entity));
811
+ let meeting = null;
812
+ if (source && source.type === "meeting") {
813
+ const title = asString(fm.__source_title) || "Meeting";
814
+ const day = toDay(fm.__source_day);
815
+ meeting = batch.upsert("meeting", source.slug, day ? `${title} ${day}` : title);
816
+ if (meeting) {
817
+ batch.tools.meetingsWithSignals.add(meeting);
818
+ if (MEETING_PAGE_TYPES.has(type))
819
+ batch.timeline(meeting, type, content, { date: day ?? batch.day });
820
+ }
821
+ }
822
+ if (type !== "decision")
823
+ return;
824
+ const heading = /^##\s*Decision:?\s*(.+)$/im.exec(body)?.[1] ?? content.split(/\s+/).slice(0, 10).join(" ");
825
+ const id = batch.input.ref.slice("signal:".length, "signal:".length + 6);
826
+ const decision = batch.upsert("decision", `${slugify(heading).slice(0, 60).replace(/-+$/g, "")}-${id}`, oneLine(heading, 120));
827
+ if (!decision)
828
+ return;
829
+ batch.fact(decision, "statement", content);
830
+ batch.fact(decision, "decided_on", batch.day);
831
+ batch.fact(decision, "status", "decided");
832
+ const owner = labelled(body, "Owner");
833
+ if (owner)
834
+ batch.fact(decision, "owner", owner);
835
+ batch.timeline(decision, "decision", content);
836
+ for (const ref of refs)
837
+ if (typeOf(ref) !== "person" && typeOf(ref) !== "decision")
838
+ batch.edge(decision, "about", ref);
839
+ const deciders = labelled(body, "Decided by");
840
+ for (const name of splitNames(deciders))
841
+ batch.edge(decision, "decided_by", batch.resolve(name, ["person"]), { conf: 0.8 });
842
+ if (meeting)
843
+ batch.edge(decision, "decided_in", meeting, { conf: 0.9 });
844
+ });
845
+ const transcriptScans = new WeakMap();
846
+ /** The transcript of a meeting, split and searched once however many passes read the document. */
847
+ function scanTranscript(document) {
848
+ let scan = transcriptScans.get(document);
849
+ if (!scan) {
850
+ const turns = transcriptTurns(document.body);
851
+ scan = { turns, text: turns.map((turn) => turn.text).join("\n"), candidates: transcriptCandidates(turns) };
852
+ transcriptScans.set(document, scan);
853
+ }
854
+ return scan;
855
+ }
856
+ const meetings = extractor("meeting-frontmatter", ["sources.meetings"], (batch, document) => {
857
+ const { frontmatter: fm, input } = document;
858
+ const title = asString(fm.title) || "Meeting";
859
+ const parsed = parseEntityRef(asString(fm.__entity));
860
+ if (!parsed || parsed.type !== "meeting")
861
+ return;
862
+ const sourceId = asString(fm.source_id) || path.basename(input.relPath, ".md");
863
+ const meeting = batch.upsert("meeting", parsed.slug, `${title} ${batch.day}`, { keys: { external_ids: [`meeting:${sourceId}`] } });
864
+ if (!meeting)
865
+ return;
866
+ batch.fact(meeting, "date", batch.day, { by: "record", conf: 0.95 });
867
+ batch.fact(meeting, "title", title, { by: "record", conf: 0.95 });
868
+ const platform = asString(fm.meeting_platform);
869
+ if (platform)
870
+ batch.fact(meeting, "channel", platform, { by: "record", conf: 0.95 });
871
+ const scan = scanTranscript(document);
872
+ const attendees = [];
873
+ const labels = new Set();
874
+ const pattern = /^\*\*(.+?)\*\* · `\[/gm;
875
+ for (let match = pattern.exec(document.body); match; match = pattern.exec(document.body))
876
+ labels.add(match[1].trim());
877
+ for (const label of labels) {
878
+ const link = /^\[\[([^|\]]+)\|([^\]]+)\]\]$/.exec(label);
879
+ const person = link ? batch.oldRef(link[1]) ?? batch.resolve(link[2], ["person"]) : batch.resolve(label, ["person"]);
880
+ if (person && typeOf(person) === "person" && !attendees.includes(person))
881
+ attendees.push(person);
882
+ }
883
+ const recorder = asString(fm.person_uid);
884
+ if (recorder) {
885
+ const person = batch.resolve(asString(fm.person_email), ["person"], { external_ids: [`hq:${recorder}`], ...(emailOf(asString(fm.person_email)) ? { email: [emailOf(asString(fm.person_email))] } : {}) }, true);
886
+ if (person && !attendees.includes(person))
887
+ attendees.push(person);
888
+ }
889
+ for (const person of attendees)
890
+ batch.edge(meeting, "had_attendee", person, { conf: 0.85 });
891
+ const attendeeNames = attendees.map((person) => displayName(batch, person));
892
+ batch.timeline(meeting, "meeting", attendeeNames.length > 0
893
+ ? `${title}: ${attendeeNames.slice(0, 8).join(", ")}${attendeeNames.length > 8 ? ` and ${attendeeNames.length - 8} more` : ""}`
894
+ : `${title}: ${labels.size} speaker${labels.size === 1 ? "" : "s"}`);
895
+ // Each attendee's own page shows the meeting. A large call would repeat one line on every page, so it stops at 12.
896
+ if (attendees.length <= 12) {
897
+ attendees.forEach((person, index) => {
898
+ const others = attendeeNames.filter((_, other) => other !== index).slice(0, 4);
899
+ batch.timeline(person, "meeting", `Meeting: ${title}${others.length > 0 ? ` with ${others.join(", ")}` : ""}`);
900
+ });
901
+ }
902
+ // What the meeting was about: only what was actually said, most said first, eight at most.
903
+ const about = new Map();
904
+ const titleText = title.toLowerCase();
905
+ for (const entry of asList(fm.entities)) {
906
+ const row = asRecord(entry);
907
+ const name = asString(row.name);
908
+ if (!asString(row.path) || asString(row.type) === "person" || name === "")
909
+ continue;
910
+ const said = countMentions(scan.text, name);
911
+ const inTitle = name.length >= 3 && titleText.includes(name.toLowerCase());
912
+ if (said < 2 && !inTitle)
913
+ continue;
914
+ const ref = batch.oldRef(asString(row.path));
915
+ if (ref && typeOf(ref) !== "person")
916
+ about.set(ref, Math.max(about.get(ref) ?? 0, said + (inTitle ? 100 : 0)));
917
+ }
918
+ // A meeting no signal covers: the names said in it, each with the words around it.
919
+ const self = batch.selfCompany();
920
+ if (!batch.tools.meetingsWithSignals.has(meeting) && scan.turns.length > 0) {
921
+ const seen = new Set([...attendees, meeting, ...(self ? [self] : [])]);
922
+ let written = 0;
923
+ for (const candidate of scan.candidates) {
924
+ if (written >= DISCUSSED_CAP)
925
+ break;
926
+ // Said once is a passing word. Said twice, the meeting was in part about it.
927
+ if (candidate.count < 2)
928
+ continue;
929
+ const single = !candidate.text.includes(" ");
930
+ const ref = batch.resolve(candidate.text, single ? DISCUSSED_THINGS : DISCUSSED_TYPES, undefined, true);
931
+ if (!ref || seen.has(ref))
932
+ continue;
933
+ seen.add(ref);
934
+ // Only the entity's own name counts: an alias match on a common word would put the meeting on the wrong page.
935
+ if (!batch.isNamed(ref, candidate.text) || batch.hasRelation(ref, NOT_A_TOPIC))
936
+ continue;
937
+ const turn = scan.turns[candidate.best];
938
+ batch.timeline(ref, "discussed", `${title}: ${turn.speaker}: ${excerptAround(turn.text, candidate.text, 170)}`);
939
+ if (typeOf(ref) !== "person")
940
+ about.set(ref, Math.max(about.get(ref) ?? 0, candidate.count));
941
+ written += 1;
942
+ }
943
+ }
944
+ const ranked = [...about].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, ABOUT_CAP);
945
+ for (const [ref] of ranked)
946
+ batch.edge(meeting, "about", ref, { conf: 0.6 });
947
+ });
948
+ const slackThreads = extractor("slack-thread", ["sources.slack"], (batch, { frontmatter: fm, body }) => {
949
+ const channel = asString(fm.channel_name);
950
+ const profiles = new Map();
951
+ for (const entry of asList(fm.__profiles)) {
952
+ const row = asRecord(entry);
953
+ const name = asString(row.real_name) || asString(row.display_name);
954
+ if (asString(row.id) && name)
955
+ profiles.set(asString(row.id), name);
956
+ }
957
+ const ids = new Set(stringList(fm.participants));
958
+ for (const match of body.matchAll(/<@([UW][A-Z0-9]{6,})>/g))
959
+ ids.add(match[1]);
960
+ for (const match of body.matchAll(/^>?\s*###\s+([UW][A-Z0-9]{6,})\s+·/gm))
961
+ ids.add(match[1]);
962
+ const people = [];
963
+ for (const id of [...ids].sort()) {
964
+ let person = batch.resolve(id, ["person"], { slack_id: [id] }, true);
965
+ const name = profiles.get(id);
966
+ if (!person && name) {
967
+ // The Slack profile's real name is an identity anchor: an exact name match gains the Slack id.
968
+ person = batch.resolve(name, ["person"], undefined, true);
969
+ batch.addKeys(person, { slack_id: [id] });
970
+ }
971
+ if (!person)
972
+ batch.resolve(name ? `${id} (${name})` : id, ["person"], { slack_id: [id] });
973
+ else if (!people.includes(person))
974
+ people.push(person);
975
+ }
976
+ // One line per thread: its first message, or its longest when the first says nothing. Chatter writes no line.
977
+ const messages = slackMessages(body);
978
+ const title = oneLine(asString(fm.title).replace(/<(?!@)[^>]*>/g, " "), 200);
979
+ let said = title;
980
+ if (isChatter(said)) {
981
+ const longest = messages.map((message) => message.text).sort((a, b) => b.length - a.length)[0] ?? "";
982
+ said = oneLine(longest.replace(/<(?!@)[^>]*>/g, " "), 200);
983
+ }
984
+ if (isChatter(said)) {
985
+ batch.count("slack_chatter_threads");
986
+ return;
987
+ }
988
+ const replies = messages.length > 1 ? ` (${messages.length} messages)` : "";
989
+ const line = `${channel ? `#${channel}: ` : ""}${said}${replies}`;
990
+ for (const person of people)
991
+ batch.timeline(person, "slack", line);
992
+ const text = `${title} ${messages.map((message) => message.text).join(" ")}`;
993
+ for (const ref of batch.names(text, CONTENT_TYPES, 5))
994
+ batch.timeline(ref, "slack", line);
995
+ });
996
+ const slackDms = extractor("slack-dm", ["sources.slack-dm"], (batch, { frontmatter: fm, body }) => {
997
+ const messages = slackMessages(body);
998
+ let said = oneLine(asString(fm.title).replace(/<(?!@)[^>]*>/g, " "), 200);
999
+ if (isChatter(said))
1000
+ said = oneLine((messages.map((message) => message.text).sort((a, b) => b.length - a.length)[0] ?? "").replace(/<(?!@)[^>]*>/g, " "), 200);
1001
+ const line = isChatter(said) ? "" : `DM: ${said}`;
1002
+ if (line === "")
1003
+ batch.count("slack_chatter_threads");
1004
+ for (const entry of asList(fm.resolved_participants)) {
1005
+ const row = asRecord(entry);
1006
+ const uid = asString(row.person_uid);
1007
+ const email = emailOf(asString(row.email));
1008
+ const slack = asString(row.slack_user_id);
1009
+ const keys = {
1010
+ ...(email ? { email: [email] } : {}),
1011
+ ...(slack ? { slack_id: [slack] } : {}),
1012
+ ...(uid ? { external_ids: [`hq:${uid}`] } : {}),
1013
+ };
1014
+ const person = batch.resolve(email || slack || uid, ["person"], keys);
1015
+ if (!person)
1016
+ continue;
1017
+ // A resolved participant gains the other identity keys seen beside it.
1018
+ batch.addKeys(person, keys);
1019
+ if (uid !== batch.tools.memberUid)
1020
+ batch.timeline(person, "slack-dm", line);
1021
+ }
1022
+ for (const entry of asList(fm.unresolved_participants)) {
1023
+ const row = asRecord(entry);
1024
+ const email = emailOf(asString(row.email));
1025
+ const slack = asString(row.slack_user_id);
1026
+ if (!email && !slack)
1027
+ continue;
1028
+ const person = batch.resolve(email || slack, ["person"], { ...(email ? { email: [email] } : {}), ...(slack ? { slack_id: [slack] } : {}) });
1029
+ if (person)
1030
+ batch.timeline(person, "slack-dm", line);
1031
+ }
1032
+ });
1033
+ const events = extractor("event-envelope", ["sources.events"], (batch, { frontmatter: fm }) => {
1034
+ if (!asString(fm.what).startsWith("linear."))
1035
+ return;
1036
+ const identifier = asString(fm.identifier);
1037
+ const title = asString(fm.title).replace(identifier, "").trim();
1038
+ const state = asString(fm.state);
1039
+ const line = `${identifier} ${title}${state ? ` [${state}]` : ""}`.trim();
1040
+ const assignee = asString(fm.assignee);
1041
+ const person = assignee ? batch.resolve(assignee, ["person"]) : null;
1042
+ batch.timeline(person, "linear", line);
1043
+ // One tracker field does not make a team or a membership: a team needs two sources (WP-C's rule).
1044
+ // The line lands on a team that already stands.
1045
+ const teamName = asString(fm.team);
1046
+ const team = teamName ? batch.resolve(teamName, ["team"], { external_ids: [`linear-team:${slugify(teamName)}`] }, true) : null;
1047
+ batch.timeline(team, "linear", line);
1048
+ for (const ref of batch.names(`${title} ${asString(fm.project)}`, CONTENT_TYPES, 4))
1049
+ batch.timeline(ref, "linear", line);
1050
+ });
1051
+ const prds = extractor("prd", ["projects.prd"], (batch, { frontmatter: prd, input }) => {
1052
+ const folder = input.relPath.split("/")[1] ?? "";
1053
+ const name = asString(prd.name);
1054
+ const project = batch.project(folder, name || folder);
1055
+ if (!project)
1056
+ return;
1057
+ const metadata = asRecord(prd.metadata);
1058
+ const stories = asList(prd.userStories);
1059
+ const summary = asString(prd.description) || asString(metadata.goal);
1060
+ if (summary)
1061
+ batch.fact(project, "summary", oneLine(summary, 300), { by: "record", conf: 0.9 });
1062
+ const created = firstDay(metadata.createdAt);
1063
+ if (created)
1064
+ batch.fact(project, "started", created, { by: "record", conf: 0.9 });
1065
+ const repo = asString(metadata.repoPath);
1066
+ if (repo)
1067
+ batch.fact(project, "repo", path.posix.basename(repo.replace(/\/+$/, "")), { by: "record", conf: 0.9 });
1068
+ batch.timeline(project, "prd", `PRD created: ${name || folder} (${stories.length} stor${stories.length === 1 ? "y" : "ies"})`);
1069
+ });
1070
+ /** Objectives and initiatives of a board file, by id. An initiative an objective lists is the objective. */
1071
+ function boardGoals(file) {
1072
+ const board = asRecord(readJsonFile(file));
1073
+ const goals = new Map();
1074
+ for (const entry of asList(board.objectives)) {
1075
+ const row = asRecord(entry);
1076
+ const id = asString(row.id);
1077
+ const title = asString(row.title);
1078
+ if (!id || !title)
1079
+ continue;
1080
+ const goal = { id, title, description: asString(row.description), status: asString(row.status), also: stringList(row.initiative_ids), kind: "objective" };
1081
+ goals.set(id, goal);
1082
+ for (const initiative of goal.also)
1083
+ goals.set(initiative, goal);
1084
+ }
1085
+ for (const entry of asList(board.initiatives)) {
1086
+ const row = asRecord(entry);
1087
+ const id = asString(row.id);
1088
+ const title = asString(row.title);
1089
+ if (!id || !title || goals.has(id))
1090
+ continue;
1091
+ goals.set(id, { id, title, description: asString(row.description), status: asString(row.status), also: [], kind: "initiative" });
1092
+ }
1093
+ return goals;
1094
+ }
1095
+ const board = extractor("board", ["board"], (batch, { frontmatter: row }) => {
1096
+ const title = asString(row.title);
1097
+ const prdPath = asString(row.prd_path);
1098
+ const folder = /projects\/([^/]+)\//.exec(prdPath)?.[1] ?? /projects\/([^/]+)\//.exec(asString(row.brainstorm_path))?.[1] ?? slugify(title);
1099
+ const id = asString(row.id);
1100
+ const project = batch.project(folder, title || folder, id ? { external_ids: [`board:${id}`] } : {});
1101
+ if (!project)
1102
+ return;
1103
+ const phase = asString(row.__phase);
1104
+ const status = asString(row.status);
1105
+ const created = firstDay(row.created_at, row.updated_at);
1106
+ const latest = phase !== "created" || firstDay(row.updated_at) === created;
1107
+ if (phase === "created") {
1108
+ const description = asString(row.description);
1109
+ if (description && !fs.existsSync(path.join(path.dirname(batch.input.path), "projects", folder, "prd.json"))) {
1110
+ batch.fact(project, "summary", oneLine(description, 300), { by: "record", conf: 0.85 });
1111
+ }
1112
+ batch.timeline(project, "board", `Added to the board: ${title || folder}`);
1113
+ if (status && latest)
1114
+ batch.fact(project, "status", status, { by: "record", conf: 0.9 });
1115
+ }
1116
+ else if (status) {
1117
+ batch.fact(project, "status", status, { by: "record", conf: 0.9 });
1118
+ batch.timeline(project, "board", `Board status: ${status}`);
1119
+ }
1120
+ // The board holds one current owner, objective and app per project: they are true as of its last change.
1121
+ if (!latest)
1122
+ return;
1123
+ const ownerText = asString(row.owner);
1124
+ if (ownerText)
1125
+ batch.edge(project, "owned_by", batch.owner(ownerText), { by: "record", conf: 0.9 });
1126
+ const goals = batch.file(`board-goals:${batch.input.path}`, () => boardGoals(batch.input.path));
1127
+ const goal = goals.get(asString(row.objective_id)) ?? goals.get(asString(row.initiative_id));
1128
+ if (goal) {
1129
+ const label = goal.kind === "objective" ? "Objective" : "Initiative";
1130
+ const concept = batch.upsert("concept", `${goal.kind}-${slugify(goal.title)}`, `${label}: ${goal.title}`, {
1131
+ aliases: [goal.title],
1132
+ keys: { external_ids: [`board:${goal.id}`, ...goal.also.map((other) => `board:${other}`)] },
1133
+ });
1134
+ if (concept) {
1135
+ if (goal.description)
1136
+ batch.fact(concept, "summary", oneLine(`${goal.description}${goal.status ? ` Status: ${goal.status}.` : ""}`, 300), { by: "record", conf: 0.9 });
1137
+ batch.edge(project, "part_of", concept, { by: "record", conf: 0.9, once: true });
1138
+ }
1139
+ }
1140
+ const app = asString(row.app);
1141
+ if (app) {
1142
+ const parent = batch.findProject(app) ?? batch.project(app, app);
1143
+ if (parent && parent !== project)
1144
+ batch.edge(project, "part_of", parent, { by: "record", conf: 0.85, once: true });
1145
+ }
1146
+ });
1147
+ const WORK_VERBS = ["works_on", "leads", "owns"];
1148
+ const people = extractor("people-roster", ["people"], (batch, { frontmatter: meta }) => {
1149
+ const name = asString(meta.name);
1150
+ if (!name)
1151
+ return;
1152
+ const handles = asRecord(meta.handles);
1153
+ const email = emailOf(asString(meta.email));
1154
+ const uid = asString(handles.hq_person_uid);
1155
+ const github = asString(handles.github);
1156
+ const slack = asString(handles.slack);
1157
+ // Other addresses and accounts are the same person: they resolve to this entity. Only the login is an email fact.
1158
+ const others = asList(meta.other_addresses).map(asRecord);
1159
+ const otherEmails = others.map((entry) => emailOf(asString(entry.address))).filter((address) => address !== "" && address !== email);
1160
+ const otherAccounts = others.map((entry) => asString(entry.hq_account)).filter((account) => /^prs_/.test(account));
1161
+ const keys = {
1162
+ ...(email || otherEmails.length > 0 ? { email: [...(email ? [email] : []), ...otherEmails] } : {}),
1163
+ ...(slack ? { slack_id: [slack] } : {}),
1164
+ external_ids: [...(uid ? [`hq:${uid}`] : []), ...otherAccounts.map((account) => `hq:${account}`), ...(github ? [`github:${github.toLowerCase()}`] : [])],
1165
+ };
1166
+ const person = batch.ensure("person", name, keys);
1167
+ if (!person)
1168
+ return;
1169
+ const role = asString(meta.role);
1170
+ if (role)
1171
+ batch.fact(person, "role_title", role, { by: "record", conf: 0.9 });
1172
+ if (email)
1173
+ batch.fact(person, "email", email, { by: "record", conf: 0.95 });
1174
+ if (slack)
1175
+ batch.fact(person, "slack_id", slack, { by: "record", conf: 0.95 });
1176
+ // Notes: an end-of-work note ends the person's work edges on that day. The notes themselves are
1177
+ // working remarks about a colleague, so they are filed for the member only.
1178
+ const notes = asList(meta.notes).map(asRecord).map((note) => ({ date: toDay(note.date), text: asString(note.text) })).filter((note) => note.text !== "");
1179
+ let ended = null;
1180
+ for (const note of notes) {
1181
+ // A note about a day the replay has not reached says nothing yet.
1182
+ const end = endOfWorkNote(note.text);
1183
+ if (end && end.since <= batch.replayDay && (!ended || end.since > ended.since))
1184
+ ended = end;
1185
+ if (batch.local)
1186
+ batch.timeline(person, "note", `Roster note: ${note.text}`, { date: note.date ?? batch.day, audience: batch.local });
1187
+ }
1188
+ if (batch.local && email && otherEmails.length > 0) {
1189
+ const detail = others
1190
+ .filter((entry) => emailOf(asString(entry.address)) !== "" && emailOf(asString(entry.address)) !== email)
1191
+ .map((entry) => `${emailOf(asString(entry.address))}${asString(entry.purpose) ? ` (${asString(entry.purpose)})` : ""}`);
1192
+ batch.timeline(person, "note", `Primary email (the login this person reads): ${email}. Other addresses, not read: ${detail.join("; ")}`, { audience: batch.local });
1193
+ }
1194
+ const kind = asString(meta.type);
1195
+ if (kind === "internal") {
1196
+ if (ended) {
1197
+ const value = `inactive (off ${ended.what} since ${ended.since})`;
1198
+ batch.closeFacts(person, "status", value, ended.since);
1199
+ batch.fact(person, "status", value, { by: "record", conf: 0.9, from: ended.since });
1200
+ batch.closeEdges(person, WORK_VERBS, ended.since);
1201
+ }
1202
+ else {
1203
+ batch.fact(person, "status", "active", { by: "record", conf: 0.8 });
1204
+ }
1205
+ batch.edge(person, "works_at", batch.selfCompany(), { by: "record", conf: 0.9, once: true });
1206
+ }
1207
+ else if (kind === "external") {
1208
+ batch.fact(person, "status", "external", { by: "record", conf: 0.8 });
1209
+ const organization = asString(meta.organization);
1210
+ if (organization) {
1211
+ batch.fact(person, "affiliation", organization, { by: "record", conf: 0.85 });
1212
+ batch.edge(person, "works_at", batch.resolve(organization, ["company"]), { by: "record", conf: 0.8, once: true });
1213
+ }
1214
+ }
1215
+ });
1216
+ /** A value every account of the projection carries says nothing about any one of them. */
1217
+ function uniformCrmFields(file) {
1218
+ const accounts = asList(asRecord(readJsonFile(file)).accounts).map(asRecord);
1219
+ const uniform = new Set();
1220
+ if (accounts.length < 3)
1221
+ return uniform;
1222
+ for (const field of ["stage", "owner"]) {
1223
+ const values = new Set(accounts.map((account) => asString(account[field])));
1224
+ if (values.size === 1 && !values.has(""))
1225
+ uniform.add(field);
1226
+ }
1227
+ return uniform;
1228
+ }
1229
+ const crm = extractor("crm-account", ["crm"], (batch, { frontmatter: account }) => {
1230
+ const rawName = asString(account.name);
1231
+ const domain = asString(account.domain).toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
1232
+ const name = /^[0-9a-f]{8}-[0-9a-f]{4}-/.test(rawName) || /^cus_/i.test(rawName) ? domain : rawName;
1233
+ if (!name)
1234
+ return;
1235
+ const external = Object.entries(asRecord(account.external_ids)).map(([system, id]) => `${system}:${asString(id)}`).filter((id) => !id.endsWith(":"));
1236
+ // A CRM row alone never makes a company: the row lands on a company another source already made.
1237
+ const company = batch.resolve(name, ["company"], { ...(domain ? { web_domains: [domain] } : {}), ...(external.length > 0 ? { external_ids: external } : {}) }, true);
1238
+ if (!company) {
1239
+ batch.count("crm_rows_without_company");
1240
+ return;
1241
+ }
1242
+ batch.addKeys(company, { ...(domain ? { web_domains: [domain] } : {}), ...(external.length > 0 ? { external_ids: external } : {}) });
1243
+ const uniform = batch.file(`crm-uniform:${batch.input.path}`, () => uniformCrmFields(batch.input.path));
1244
+ const stage = asString(account.stage);
1245
+ if (stage && !uniform.has("stage"))
1246
+ batch.fact(company, "stage", stage, { by: "record", conf: 0.9 });
1247
+ if (domain)
1248
+ batch.fact(company, "web_domain", domain, { by: "record", conf: 0.95 });
1249
+ const pipeline = asRecord(asRecord(account.sources).pipeline);
1250
+ if (typeof pipeline.status === "string" && pipeline.status.trim() !== "")
1251
+ batch.fact(company, "crm_status", pipeline.status, { by: "record", conf: 0.9 });
1252
+ for (const entry of asList(account.timeline).slice(0, 12)) {
1253
+ const row = asRecord(entry);
1254
+ // A line made from a meeting is a cut copy of a signal the replay reads in full.
1255
+ if (asString(row.sourceMeetingRef) !== "")
1256
+ continue;
1257
+ const audience = asString(row.__audience) || batch.audience;
1258
+ batch.timeline(company, asString(row.type) || "crm", row.text, { date: toDay(row.__day) ?? batch.day, audience });
1259
+ }
1260
+ });
1261
+ const kpis = extractor("customer-kpis", ["customers"], (batch, { frontmatter: day }) => {
1262
+ const parts = [
1263
+ typeof day.payingCustomers === "number" ? `${day.payingCustomers} paying customers` : "",
1264
+ typeof day.subscribedMrr === "number" ? `MRR ${day.subscribedMrr} ${asString(day.currency)}`.trim() : "",
1265
+ typeof day.newCompanies === "number" ? `${day.newCompanies} new companies` : "",
1266
+ typeof day.newUsers === "number" ? `${day.newUsers} new users` : "",
1267
+ ].filter((part) => part !== "");
1268
+ if (parts.length > 0)
1269
+ batch.timeline(batch.selfCompany(), "kpi", parts.join(", "));
1270
+ });
1271
+ const commitments = extractor("commitment", ["commitments"], (batch, { frontmatter: fm }) => {
1272
+ const statement = asString(fm.statement);
1273
+ if (!statement)
1274
+ return;
1275
+ const status = asString(fm.status);
1276
+ const line = `${statement}${status ? ` [${status}]` : ""}`;
1277
+ for (const field of ["promised_by", "promised_to"]) {
1278
+ const value = asString(fm[field]).replace(/^person\//, "");
1279
+ if (!value)
1280
+ continue;
1281
+ const email = emailOf(value);
1282
+ const person = email ? batch.resolve(email, ["person"], { email: [email] }) : batch.resolve(nameFromSlug(value), ["person"]);
1283
+ batch.timeline(person, "commitment", `${field === "promised_by" ? "Promised" : "Was promised"}: ${line}`);
1284
+ }
1285
+ });
1286
+ const actionItems = extractor("action-item", ["action-items"], (batch, { frontmatter: fm }) => {
1287
+ const title = asString(fm.title);
1288
+ const owner = asString(fm.owner);
1289
+ if (!title || !owner)
1290
+ return;
1291
+ const status = asString(fm.status);
1292
+ batch.timeline(batch.resolve(owner, ["person"]), "action_item", `${title}${status ? ` [${status}]` : ""}`);
1293
+ });
1294
+ /** What the note under `## Source note` adds to the quote: who "he" is, what follows from it. */
1295
+ function sourceNote(body, quote) {
1296
+ const section = /^##\s*Source note\s*$([\s\S]*?)(?=^##\s|$(?![\s\S]))/im.exec(body)?.[1] ?? "";
1297
+ let note = oneLine(section, 1200);
1298
+ const at = quote ? note.indexOf(quote) : -1;
1299
+ if (at >= 0)
1300
+ note = note.slice(at + quote.length);
1301
+ return note.replace(/^['"’”\s.:;,]+/, "").trim();
1302
+ }
1303
+ const standingDecisions = extractor("standing-decision", ["context.decisions"], (batch, { frontmatter: fm, body }) => {
1304
+ const id = asString(fm.id);
1305
+ const quote = asString(fm.quote);
1306
+ const title = asString(fm.title) || quote;
1307
+ if (!id || !title)
1308
+ return;
1309
+ const decision = batch.upsert("decision", slugify(id), oneLine(title, 120));
1310
+ if (!decision)
1311
+ return;
1312
+ // The quote alone can be unreadable ("he's off the migration"); the source note says who and what.
1313
+ const note = sourceNote(body, quote);
1314
+ const scope = asString(fm.scope);
1315
+ const statement = `${quote || title}${note ? ` Note: ${note}` : ""}${scope ? ` [scope ${scope}]` : ""}`;
1316
+ batch.fact(decision, "statement", statement, { conf: 0.9 });
1317
+ batch.fact(decision, "decided_on", batch.day, { conf: 0.9 });
1318
+ const status = asString(fm.status);
1319
+ if (status)
1320
+ batch.fact(decision, "status", status, { conf: 0.9 });
1321
+ batch.timeline(decision, "decision", statement);
1322
+ const about = new Set();
1323
+ const scopeName = scope.includes(":") ? scope.slice(scope.indexOf(":") + 1) : scope;
1324
+ if (scopeName) {
1325
+ const ref = batch.resolve(scopeName, CONTENT_TYPES, undefined, true) ?? batch.resolve(nameFromSlug(scopeName), CONTENT_TYPES, undefined, true);
1326
+ if (ref)
1327
+ about.add(ref);
1328
+ }
1329
+ for (const ref of batch.names(`${title} ${quote} ${note}`, CONTENT_TYPES, 5))
1330
+ about.add(ref);
1331
+ for (const ref of about)
1332
+ batch.edge(decision, "about", ref, { conf: 0.6 });
1333
+ for (const ref of batch.names(note, ["person"], 4))
1334
+ batch.timeline(ref, "decision", statement);
1335
+ });
1336
+ const policies = extractor("policy", ["policies"], (batch, { frontmatter: fm }) => {
1337
+ const title = asString(fm.title) || asString(fm.id);
1338
+ if (!title)
1339
+ return;
1340
+ const text = `${title} ${asString(fm.trigger)} ${asString(fm.when).replace(/[&|()]/g, " ")}`;
1341
+ for (const ref of batch.names(text, ["project", "product", "tool", "company"], 4))
1342
+ batch.timeline(ref, "policy", `Policy: ${title}`);
1343
+ });
1344
+ const knowledge = extractor("knowledge-doc", ["knowledge", "clients.md"], (batch, { frontmatter: fm, body, input }) => {
1345
+ const heading = /^#\s+(.+)$/m.exec(body)?.[1] ?? "";
1346
+ const title = plainLinks(asString(fm.title) || heading || path.basename(input.relPath, ".md"));
1347
+ const refs = new Set();
1348
+ for (const entry of asList(fm.entities)) {
1349
+ const ref = asString(asRecord(entry).path) ? batch.oldRef(asString(asRecord(entry).path)) : null;
1350
+ if (ref)
1351
+ refs.add(ref);
1352
+ }
1353
+ for (const related of stringList(fm.relates_to)) {
1354
+ const ref = batch.resolve(related, undefined, undefined, true);
1355
+ if (ref)
1356
+ refs.add(ref);
1357
+ }
1358
+ if (batch.cls === "clients.md") {
1359
+ const client = input.relPath.split("/")[1] ?? "";
1360
+ const website = /^-\s*website:\s*(\S+)/m.exec(body)?.[1] ?? "";
1361
+ const domain = website.toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "").replace(/\/.*$/, "");
1362
+ const display = heading.replace(/\s+[—-]\s+.*$/, "").trim() || nameFromSlug(client);
1363
+ const company = batch.ensure("company", display, domain ? { web_domains: [domain] } : {}, [client]);
1364
+ if (company) {
1365
+ refs.add(company);
1366
+ if (input.relPath.endsWith("/engagement.md"))
1367
+ batch.fact(company, "relation", "customer", { conf: 0.8 });
1368
+ }
1369
+ }
1370
+ else {
1371
+ for (const ref of batch.names(title, CONTENT_TYPES, 4))
1372
+ refs.add(ref);
1373
+ }
1374
+ for (const ref of refs)
1375
+ batch.timeline(ref, "doc", title);
1376
+ });
1377
+ const readmes = extractor("project-readme", ["projects.readme"], (batch, { body, input }) => {
1378
+ const folder = input.relPath.split("/")[1] ?? "";
1379
+ const heading = (/^#\s+(.+)$/m.exec(body)?.[1] ?? "").trim();
1380
+ const project = batch.project(folder, heading && heading.length <= 80 ? heading : folder);
1381
+ if (!project)
1382
+ return;
1383
+ batch.timeline(project, "doc", `README: ${heading || folder}`);
1384
+ if (!fs.existsSync(path.join(path.dirname(input.path), "prd.json"))) {
1385
+ const paragraph = body.split(/\n\s*\n/).map((block) => block.trim()).find((block) => block !== "" && !/^[#>|\-*`<![]/.test(block));
1386
+ if (paragraph)
1387
+ batch.fact(project, "summary", oneLine(paragraph, 300), { conf: 0.6 });
1388
+ }
1389
+ });
1390
+ const standups = extractor("standup-notes", ["meetings.notes"], (batch, { body }) => {
1391
+ for (const match of body.matchAll(/^##\s+([^—\n]+?)\s+—\s+(.+)$/gm)) {
1392
+ const person = batch.resolve(match[1].trim(), ["person"], undefined, true);
1393
+ batch.timeline(person, "standup", match[2].trim());
1394
+ }
1395
+ });
1396
+ const sessions = extractor("session-record", ["company.workspace.sessions", "hq.workspace.threads"], (batch, { frontmatter: thread }) => {
1397
+ const metadata = asRecord(thread.metadata);
1398
+ const title = asString(metadata.title).replace(/^Handoff:\s*/i, "");
1399
+ const summary = oneLine(asString(thread.conversation_summary), 200);
1400
+ // A lifecycle record says nothing about the work.
1401
+ if (isLifecycleText(title) || isLifecycleText(summary) || isBoilerplatePrompt(`${title} ${summary}`)) {
1402
+ batch.count("session_boilerplate_dropped");
1403
+ return;
1404
+ }
1405
+ const paths = [asString(thread.cwd), asString(thread.workspace_root), asString(thread.changeset_path), ...stringList(thread.files_touched), ...stringList(asRecord(thread.git).worktree)];
1406
+ const company = batch.tools.company;
1407
+ if (company && namesAnotherCompany(companyScopesIn(paths.join("\n"), { pathsOnly: true }), company)) {
1408
+ batch.count("sessions_naming_another_company");
1409
+ return;
1410
+ }
1411
+ // Work is found by what the record names as its project or repo, and by the paths it touched. Never by a word.
1412
+ const projects = new Set();
1413
+ const names = new Set([...stringList(metadata.project), ...stringList(thread.project)]);
1414
+ for (const repo of [...stringList(metadata.repo), ...stringList(metadata.repos)])
1415
+ names.add(path.posix.basename(repo.replace(/\/+$/, "")));
1416
+ for (const name of names) {
1417
+ const ref = batch.findProject(name);
1418
+ if (ref)
1419
+ projects.add(ref);
1420
+ }
1421
+ for (const ref of batch.projectsByPath(paths))
1422
+ projects.add(ref);
1423
+ // A handoff titled with exactly a project's name is that project's handoff. A title that only contains the name is not.
1424
+ if (title !== "" && title.length <= 80) {
1425
+ const named = batch.findProject(title);
1426
+ if (named && batch.isNamed(named, title))
1427
+ projects.add(named);
1428
+ }
1429
+ const line = title && summary && !summary.startsWith(title) ? `${title}: ${summary}` : title || summary;
1430
+ // The member's own thread is the member's own work: it is on the member's page whatever it touched.
1431
+ const member = batch.cls === "hq.workspace.threads" ? batch.memberPerson() : null;
1432
+ batch.timeline(member, "session", line);
1433
+ for (const project of projects) {
1434
+ batch.timeline(project, "session", line || "Session");
1435
+ if (member)
1436
+ batch.edge(member, "works_on", project, { conf: 0.7, once: true });
1437
+ }
1438
+ });
1439
+ const git = extractor("git-authors", ["git.history"], (batch, { frontmatter: record }) => {
1440
+ const repo = asString(record.repo);
1441
+ if (!repo)
1442
+ return;
1443
+ const project = batch.project(repo, repo);
1444
+ if (!project)
1445
+ return;
1446
+ if (!batch.tools.exists(project))
1447
+ batch.fact(project, "repo", repo, { by: "record", conf: 0.95 });
1448
+ // One input is a repo's day, or a repo's whole week when the reader rolled the week up.
1449
+ const week = toDay(record.week);
1450
+ const span = week ? `, week of ${week}` : "";
1451
+ const authors = new Map();
1452
+ const subjects = [];
1453
+ for (const entry of asList(record.commits)) {
1454
+ const commit = asRecord(entry);
1455
+ const email = asString(commit.email);
1456
+ const key = email || asString(commit.name);
1457
+ const subject = cleanSubject(asString(commit.subject));
1458
+ if (subject && !subjects.includes(subject))
1459
+ subjects.push(subject);
1460
+ const known = authors.get(key);
1461
+ if (known) {
1462
+ known.count += 1;
1463
+ if (subject && known.subjects.length < 3 && !known.subjects.includes(subject))
1464
+ known.subjects.push(subject);
1465
+ }
1466
+ else
1467
+ authors.set(key, { name: asString(commit.name), email, count: 1, subjects: subject ? [subject] : [] });
1468
+ }
1469
+ const resolvedNames = [];
1470
+ for (const author of [...authors.values()].sort((a, b) => (a.email < b.email ? -1 : a.email > b.email ? 1 : 0))) {
1471
+ if (/\[bot\]|^dependabot|^github-actions/i.test(`${author.name} ${author.email}`))
1472
+ continue;
1473
+ const login = /^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/.exec(author.email)?.[1];
1474
+ const keys = {
1475
+ ...(author.email && !login ? { email: [author.email] } : {}),
1476
+ ...(login ? { external_ids: [`github:${login.toLowerCase()}`] } : {}),
1477
+ };
1478
+ const person = batch.resolve(author.name, ["person"], keys);
1479
+ if (!person)
1480
+ continue;
1481
+ if (!resolvedNames.includes(author.name))
1482
+ resolvedNames.push(author.name);
1483
+ batch.edge(person, "works_on", project, { conf: 0.8, once: true });
1484
+ const shown = author.subjects.slice(0, week ? 3 : 1).map((subject) => oneLine(subject, 90)).join("; ");
1485
+ batch.timeline(person, "commit", `${author.count} commit${author.count === 1 ? "" : "s"} to ${repo}${span}: ${shown}`);
1486
+ }
1487
+ const count = typeof record.count === "number" ? record.count : authors.size;
1488
+ const shown = subjects.slice(0, week ? 4 : 1).map((subject) => oneLine(subject, week ? 70 : 120)).join("; ");
1489
+ batch.timeline(project, "commit", `${count} commit${count === 1 ? "" : "s"}${resolvedNames.length > 0 ? ` by ${resolvedNames.slice(0, 4).join(", ")}` : ""}${span}: ${shown}`);
1490
+ });
1491
+ const mesh = extractor("work-mesh", ["work-mesh.cache"], (batch, { frontmatter: record }) => {
1492
+ if (record.__mesh === "contacts") {
1493
+ // The contact list spans every company the member belongs to and names none of them, so a contact
1494
+ // never makes a person here (C7). One who is already known gains the identity keys.
1495
+ for (const entry of asList(record.contacts)) {
1496
+ const contact = asRecord(entry);
1497
+ const uid = asString(contact.personUid);
1498
+ const email = emailOf(asString(contact.email));
1499
+ if (!uid.startsWith("prs_"))
1500
+ continue;
1501
+ const keys = { ...(email ? { email: [email] } : {}), external_ids: [`hq:${uid}`] };
1502
+ const person = batch.resolve(email || uid, ["person"], keys, true);
1503
+ if (person)
1504
+ batch.addKeys(person, keys);
1505
+ else
1506
+ batch.count("mesh_contacts_not_in_company");
1507
+ }
1508
+ return;
1509
+ }
1510
+ const id = asString(record.projectId);
1511
+ const project = id ? batch.findProject(id) : null;
1512
+ if (!project)
1513
+ return;
1514
+ const stories = asList(record.stories).map(asRecord);
1515
+ const done = stories.filter((story) => story.passes === true || /^(done|completed|merged)$/i.test(asString(story.status))).length;
1516
+ if (stories.length > 0)
1517
+ batch.timeline(project, "mesh", `Work mesh: ${done} of ${stories.length} stories done`);
1518
+ });
1519
+ const transcripts = extractor("session-transcript", ["claude.transcripts.main"], (batch, { frontmatter: extract }) => {
1520
+ const prompts = stringList(extract.prompts);
1521
+ if (prompts.length === 0)
1522
+ return;
1523
+ const cwds = stringList(extract.cwds);
1524
+ // The reader drops a session that names another company. This is the same check again, on what reached here.
1525
+ const company = asString(extract.__company) || batch.tools.company || "";
1526
+ const scopes = [...stringList(extract.companies), ...companyScopesIn([...cwds, ...prompts].join("\n"))];
1527
+ if (company === "" || namesAnotherCompany(scopes, company)) {
1528
+ batch.count("sessions_naming_another_company");
1529
+ return;
1530
+ }
1531
+ const prompt = firstRealPrompt(prompts);
1532
+ if (!prompt) {
1533
+ batch.count("session_boilerplate_dropped");
1534
+ return;
1535
+ }
1536
+ // The session is the member's own work, so it is on the member's page. It is on a project's page only
1537
+ // when its paths name the project: where it ran and the files its prompts point at.
1538
+ const projects = batch.projectsByPath([...cwds, ...prompts]);
1539
+ const line = `Session: ${oneLine(prompt, 180)}`;
1540
+ const member = batch.memberPerson();
1541
+ batch.timeline(member, "session", line);
1542
+ for (const project of projects) {
1543
+ batch.timeline(project, "session", line);
1544
+ if (member)
1545
+ batch.edge(member, "works_on", project, { conf: 0.6, once: true });
1546
+ }
1547
+ });
1548
+ /** The model-free extractors, in the order they run. */
1549
+ export function allRuleExtractors() {
1550
+ return [
1551
+ signals, prds, board, people, crm, kpis, commitments, actionItems, standingDecisions, policies, knowledge,
1552
+ readmes, standups, meetings, slackThreads, slackDms, events, sessions, git, mesh, transcripts,
1553
+ ];
1554
+ }
1555
+ //# sourceMappingURL=extractors.js.map