@indigoai-us/hq-cli 5.345.246 → 5.345.248

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/assets/lanes-hooks/hq-lanes-drain.sh +1 -1
  3. package/contracts/host-canary-release.json +14 -0
  4. package/dist/command-catalog.generated.d.ts +1116 -3
  5. package/dist/command-catalog.generated.js +1373 -3
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/install-global.d.ts +15 -0
  9. package/dist/commands/install-global.js +98 -4
  10. package/dist/commands/lanes-hold.js +7 -7
  11. package/dist/commands/lanes-resume.js +2 -2
  12. package/dist/commands/lanes-review.js +1 -1
  13. package/dist/commands/lanes-session-start.d.ts +1 -1
  14. package/dist/commands/lanes-session-start.js +3 -3
  15. package/dist/commands/lanes-shared.d.ts +1 -1
  16. package/dist/commands/lanes.d.ts +2 -2
  17. package/dist/commands/lanes.js +50 -50
  18. package/dist/commands/mcp-registration.d.ts +17 -0
  19. package/dist/commands/mcp-registration.js +119 -0
  20. package/dist/commands/mesh.d.ts +25 -0
  21. package/dist/commands/mesh.js +48 -8
  22. package/dist/commands/ontology-graph.d.ts +62 -0
  23. package/dist/commands/ontology-graph.js +439 -0
  24. package/dist/commands/pkg-install.js +1 -1
  25. package/dist/commands/reindex.js +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  28. package/dist/lanes-monitor-check-argv.js +1 -1
  29. package/dist/lanes-monitor-check-fast.d.ts +1 -1
  30. package/dist/lanes-monitor-check-fast.js +1 -1
  31. package/dist/lanes-session-start-argv.d.ts +1 -1
  32. package/dist/lanes-session-start-argv.js +1 -1
  33. package/dist/lib/capacity/sign-in.d.ts +1 -1
  34. package/dist/lib/capacity/sign-in.js +1 -1
  35. package/dist/lib/daemon/hook-requests-conduct-link.js +2 -2
  36. package/dist/lib/daemon/lanes-monitor-state.d.ts +2 -2
  37. package/dist/lib/daemon/lanes-monitor-state.js +2 -2
  38. package/dist/lib/daemon/merge-sections.d.ts +3 -3
  39. package/dist/lib/daemon/merge-sections.js +7 -7
  40. package/dist/lib/daemon/remote-control-pools.js +1 -1
  41. package/dist/lib/daemon/run.js +1 -1
  42. package/dist/lib/daemon/state-file.d.ts +1 -1
  43. package/dist/lib/daemon/state-file.js +1 -1
  44. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +21 -0
  45. package/dist/lib/doctor/checks/antigravity-wiring.js +75 -0
  46. package/dist/lib/doctor/checks/anywhere.js +30 -0
  47. package/dist/lib/doctor/checks/runtime-probe.js +13 -0
  48. package/dist/lib/doctor/platform.d.ts +1 -1
  49. package/dist/lib/doctor/platform.js +5 -0
  50. package/dist/lib/doctor/registry.js +3 -0
  51. package/dist/lib/flag-snapshot-file.d.ts +2 -0
  52. package/dist/lib/flag-snapshot-file.js +118 -48
  53. package/dist/lib/hook-engine/canary-gate.d.ts +57 -3
  54. package/dist/lib/hook-engine/canary-gate.js +138 -6
  55. package/dist/lib/hook-engine/coverage.d.ts +91 -0
  56. package/dist/lib/hook-engine/coverage.js +184 -0
  57. package/dist/lib/hot-channels/graph-context.d.ts +105 -0
  58. package/dist/lib/hot-channels/graph-context.js +377 -0
  59. package/dist/lib/hot-channels/signals-pass.js +27 -1
  60. package/dist/lib/install/antigravity-targets.d.ts +39 -0
  61. package/dist/lib/install/antigravity-targets.js +122 -0
  62. package/dist/lib/lanes/claude-credential.d.ts +1 -1
  63. package/dist/lib/lanes/claude-credential.js +1 -1
  64. package/dist/lib/lanes/delivery-core.d.ts +1 -1
  65. package/dist/lib/lanes/delivery-core.js +1 -1
  66. package/dist/lib/lanes/delivery.d.ts +10 -10
  67. package/dist/lib/lanes/delivery.js +8 -8
  68. package/dist/lib/lanes/dropbox.d.ts +1 -1
  69. package/dist/lib/lanes/dropbox.js +1 -1
  70. package/dist/lib/lanes/hooks-install.js +2 -2
  71. package/dist/lib/lanes/index.d.ts +1 -1
  72. package/dist/lib/lanes/index.js +1 -1
  73. package/dist/lib/lanes/monitor.js +1 -1
  74. package/dist/lib/lanes/quota-notice.js +1 -1
  75. package/dist/lib/lanes/quota.d.ts +1 -1
  76. package/dist/lib/lanes/quota.js +1 -1
  77. package/dist/lib/lanes/repo-merge-hold.d.ts +2 -2
  78. package/dist/lib/lanes/repo-merge-hold.js +2 -2
  79. package/dist/lib/lanes/spawn.d.ts +4 -4
  80. package/dist/lib/lanes/spawn.js +5 -5
  81. package/dist/lib/mesh/live/company-flag-refresh.d.ts +61 -0
  82. package/dist/lib/mesh/live/company-flag-refresh.js +159 -0
  83. package/dist/lib/mesh/live/company-reporting-gaps.d.ts +61 -0
  84. package/dist/lib/mesh/live/company-reporting-gaps.js +238 -0
  85. package/dist/lib/mesh/live/daemon/duplicate-unit.d.ts +156 -0
  86. package/dist/lib/mesh/live/daemon/duplicate-unit.js +616 -0
  87. package/dist/lib/mesh/live/daemon/run.d.ts +13 -0
  88. package/dist/lib/mesh/live/daemon/run.js +35 -2
  89. package/dist/lib/mesh/live/direct-drain.js +1 -1
  90. package/dist/lib/mesh/live/emit.d.ts +3 -0
  91. package/dist/lib/mesh/live/emit.js +32 -9
  92. package/dist/lib/mesh/live/flush.d.ts +3 -0
  93. package/dist/lib/mesh/live/flush.js +115 -32
  94. package/dist/lib/mesh/live/liveness-carry.d.ts +1 -1
  95. package/dist/lib/mesh/live/liveness-carry.js +1 -1
  96. package/dist/lib/mesh/live/reporting-privacy.d.ts +119 -3
  97. package/dist/lib/mesh/live/reporting-privacy.js +235 -11
  98. package/dist/lib/mesh/live/spool.d.ts +17 -2
  99. package/dist/lib/mesh/live/spool.js +22 -6
  100. package/dist/lib/ontology-graph/legacy/coverage.d.ts +67 -0
  101. package/dist/lib/ontology-graph/legacy/coverage.js +192 -0
  102. package/dist/lib/ontology-graph/legacy/index.d.ts +199 -0
  103. package/dist/lib/ontology-graph/legacy/index.js +1150 -0
  104. package/dist/lib/ontology-graph/legacy/parse.d.ts +49 -0
  105. package/dist/lib/ontology-graph/legacy/parse.js +126 -0
  106. package/dist/lib/ontology-graph/legacy/report.d.ts +14 -0
  107. package/dist/lib/ontology-graph/legacy/report.js +254 -0
  108. package/dist/lib/ontology-graph/legacy/verb-map.d.ts +35 -0
  109. package/dist/lib/ontology-graph/legacy/verb-map.js +84 -0
  110. package/dist/lib/ontology-graph/lint/checks.d.ts +140 -0
  111. package/dist/lib/ontology-graph/lint/checks.js +717 -0
  112. package/dist/lib/ontology-graph/lint/coverage.d.ts +106 -0
  113. package/dist/lib/ontology-graph/lint/coverage.js +241 -0
  114. package/dist/lib/ontology-graph/lint/daily-job.d.ts +259 -0
  115. package/dist/lib/ontology-graph/lint/daily-job.js +595 -0
  116. package/dist/lib/ontology-graph/lint/index.d.ts +65 -0
  117. package/dist/lib/ontology-graph/lint/index.js +176 -0
  118. package/dist/lib/ontology-graph/model/files.d.ts +20 -0
  119. package/dist/lib/ontology-graph/model/files.js +89 -0
  120. package/dist/lib/ontology-graph/model/index.d.ts +65 -0
  121. package/dist/lib/ontology-graph/model/index.js +100 -0
  122. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +156 -0
  123. package/dist/lib/ontology-graph/model/pass-tasks.js +345 -0
  124. package/dist/lib/ontology-graph/model/pass.d.ts +109 -0
  125. package/dist/lib/ontology-graph/model/pass.js +958 -0
  126. package/dist/lib/ontology-graph/model/runner.d.ts +50 -0
  127. package/dist/lib/ontology-graph/model/runner.js +160 -0
  128. package/dist/lib/ontology-graph/model/step.d.ts +195 -0
  129. package/dist/lib/ontology-graph/model/step.js +523 -0
  130. package/dist/lib/ontology-graph/model/tasks.d.ts +183 -0
  131. package/dist/lib/ontology-graph/model/tasks.js +349 -0
  132. package/dist/lib/ontology-graph/not-implemented.d.ts +5 -0
  133. package/dist/lib/ontology-graph/not-implemented.js +8 -0
  134. package/dist/lib/ontology-graph/org/compare.d.ts +28 -0
  135. package/dist/lib/ontology-graph/org/compare.js +239 -0
  136. package/dist/lib/ontology-graph/org/derive.d.ts +65 -0
  137. package/dist/lib/ontology-graph/org/derive.js +352 -0
  138. package/dist/lib/ontology-graph/org/index.d.ts +73 -0
  139. package/dist/lib/ontology-graph/org/index.js +513 -0
  140. package/dist/lib/ontology-graph/org/load.d.ts +31 -0
  141. package/dist/lib/ontology-graph/org/load.js +476 -0
  142. package/dist/lib/ontology-graph/org/role.d.ts +38 -0
  143. package/dist/lib/ontology-graph/org/role.js +268 -0
  144. package/dist/lib/ontology-graph/org/structure.d.ts +63 -0
  145. package/dist/lib/ontology-graph/org/structure.js +437 -0
  146. package/dist/lib/ontology-graph/org/text.d.ts +95 -0
  147. package/dist/lib/ontology-graph/org/text.js +315 -0
  148. package/dist/lib/ontology-graph/org/types.d.ts +452 -0
  149. package/dist/lib/ontology-graph/org/types.js +80 -0
  150. package/dist/lib/ontology-graph/pages/index.d.ts +64 -0
  151. package/dist/lib/ontology-graph/pages/index.js +193 -0
  152. package/dist/lib/ontology-graph/pages/render.d.ts +142 -0
  153. package/dist/lib/ontology-graph/pages/render.js +682 -0
  154. package/dist/lib/ontology-graph/proposals/apply.d.ts +109 -0
  155. package/dist/lib/ontology-graph/proposals/apply.js +468 -0
  156. package/dist/lib/ontology-graph/proposals/group.d.ts +63 -0
  157. package/dist/lib/ontology-graph/proposals/group.js +232 -0
  158. package/dist/lib/ontology-graph/proposals/index.d.ts +173 -0
  159. package/dist/lib/ontology-graph/proposals/index.js +474 -0
  160. package/dist/lib/ontology-graph/proposals/model.d.ts +162 -0
  161. package/dist/lib/ontology-graph/proposals/model.js +196 -0
  162. package/dist/lib/ontology-graph/proposals/org-chart.d.ts +82 -0
  163. package/dist/lib/ontology-graph/proposals/org-chart.js +340 -0
  164. package/dist/lib/ontology-graph/read/brief.d.ts +26 -0
  165. package/dist/lib/ontology-graph/read/brief.js +251 -0
  166. package/dist/lib/ontology-graph/read/graph-index.d.ts +76 -0
  167. package/dist/lib/ontology-graph/read/graph-index.js +198 -0
  168. package/dist/lib/ontology-graph/read/index.d.ts +59 -0
  169. package/dist/lib/ontology-graph/read/index.js +792 -0
  170. package/dist/lib/ontology-graph/read/member.d.ts +7 -0
  171. package/dist/lib/ontology-graph/read/member.js +34 -0
  172. package/dist/lib/ontology-graph/read/names.d.ts +44 -0
  173. package/dist/lib/ontology-graph/read/names.js +292 -0
  174. package/dist/lib/ontology-graph/read/reader-setting.d.ts +19 -0
  175. package/dist/lib/ontology-graph/read/reader-setting.js +62 -0
  176. package/dist/lib/ontology-graph/read/test-graph.d.ts +37 -0
  177. package/dist/lib/ontology-graph/read/test-graph.js +150 -0
  178. package/dist/lib/ontology-graph/replay/buffered-store.d.ts +33 -0
  179. package/dist/lib/ontology-graph/replay/buffered-store.js +50 -0
  180. package/dist/lib/ontology-graph/replay/config.d.ts +41 -0
  181. package/dist/lib/ontology-graph/replay/config.js +105 -0
  182. package/dist/lib/ontology-graph/replay/engine.d.ts +100 -0
  183. package/dist/lib/ontology-graph/replay/engine.js +1174 -0
  184. package/dist/lib/ontology-graph/replay/extractors.d.ts +59 -0
  185. package/dist/lib/ontology-graph/replay/extractors.js +1555 -0
  186. package/dist/lib/ontology-graph/replay/index.d.ts +90 -0
  187. package/dist/lib/ontology-graph/replay/index.js +220 -0
  188. package/dist/lib/ontology-graph/replay/listing-manifest.d.ts +66 -0
  189. package/dist/lib/ontology-graph/replay/listing-manifest.js +242 -0
  190. package/dist/lib/ontology-graph/replay/member.d.ts +19 -0
  191. package/dist/lib/ontology-graph/replay/member.js +65 -0
  192. package/dist/lib/ontology-graph/replay/mentions.d.ts +58 -0
  193. package/dist/lib/ontology-graph/replay/mentions.js +239 -0
  194. package/dist/lib/ontology-graph/replay/readers.d.ts +98 -0
  195. package/dist/lib/ontology-graph/replay/readers.js +1251 -0
  196. package/dist/lib/ontology-graph/replay/rules.d.ts +127 -0
  197. package/dist/lib/ontology-graph/replay/rules.js +374 -0
  198. package/dist/lib/ontology-graph/replay/scope.d.ts +35 -0
  199. package/dist/lib/ontology-graph/replay/scope.js +115 -0
  200. package/dist/lib/ontology-graph/replay/transcripts.d.ts +39 -0
  201. package/dist/lib/ontology-graph/replay/transcripts.js +224 -0
  202. package/dist/lib/ontology-graph/replay/util.d.ts +55 -0
  203. package/dist/lib/ontology-graph/replay/util.js +256 -0
  204. package/dist/lib/ontology-graph/resolve/entity-index.d.ts +159 -0
  205. package/dist/lib/ontology-graph/resolve/entity-index.js +652 -0
  206. package/dist/lib/ontology-graph/resolve/index.d.ts +113 -0
  207. package/dist/lib/ontology-graph/resolve/index.js +214 -0
  208. package/dist/lib/ontology-graph/resolve/machine.d.ts +34 -0
  209. package/dist/lib/ontology-graph/resolve/machine.js +95 -0
  210. package/dist/lib/ontology-graph/resolve/normalize.d.ts +35 -0
  211. package/dist/lib/ontology-graph/resolve/normalize.js +124 -0
  212. package/dist/lib/ontology-graph/resolve/org-chart.d.ts +107 -0
  213. package/dist/lib/ontology-graph/resolve/org-chart.js +578 -0
  214. package/dist/lib/ontology-graph/resolve/org-layer.d.ts +78 -0
  215. package/dist/lib/ontology-graph/resolve/org-layer.js +159 -0
  216. package/dist/lib/ontology-graph/resolve/org-seed.d.ts +141 -0
  217. package/dist/lib/ontology-graph/resolve/org-seed.js +631 -0
  218. package/dist/lib/ontology-graph/resolve/org-sources.d.ts +165 -0
  219. package/dist/lib/ontology-graph/resolve/org-sources.js +634 -0
  220. package/dist/lib/ontology-graph/resolve/roster.d.ts +76 -0
  221. package/dist/lib/ontology-graph/resolve/roster.js +226 -0
  222. package/dist/lib/ontology-graph/resolve/seed.d.ts +267 -0
  223. package/dist/lib/ontology-graph/resolve/seed.js +1198 -0
  224. package/dist/lib/ontology-graph/resolve/upsert.d.ts +58 -0
  225. package/dist/lib/ontology-graph/resolve/upsert.js +139 -0
  226. package/dist/lib/ontology-graph/resolve/writer.d.ts +128 -0
  227. package/dist/lib/ontology-graph/resolve/writer.js +351 -0
  228. package/dist/lib/ontology-graph/schema/authority.d.ts +73 -0
  229. package/dist/lib/ontology-graph/schema/authority.js +157 -0
  230. package/dist/lib/ontology-graph/schema/default-schema.d.ts +10 -0
  231. package/dist/lib/ontology-graph/schema/default-schema.js +242 -0
  232. package/dist/lib/ontology-graph/schema/grammar.d.ts +57 -0
  233. package/dist/lib/ontology-graph/schema/grammar.js +409 -0
  234. package/dist/lib/ontology-graph/schema/index.d.ts +12 -0
  235. package/dist/lib/ontology-graph/schema/index.js +10 -0
  236. package/dist/lib/ontology-graph/schema/validate.d.ts +13 -0
  237. package/dist/lib/ontology-graph/schema/validate.js +132 -0
  238. package/dist/lib/ontology-graph/store/files.d.ts +34 -0
  239. package/dist/lib/ontology-graph/store/files.js +207 -0
  240. package/dist/lib/ontology-graph/store/fs.d.ts +30 -0
  241. package/dist/lib/ontology-graph/store/fs.js +101 -0
  242. package/dist/lib/ontology-graph/store/graph-store.d.ts +14 -0
  243. package/dist/lib/ontology-graph/store/graph-store.js +520 -0
  244. package/dist/lib/ontology-graph/store/index.d.ts +18 -0
  245. package/dist/lib/ontology-graph/store/index.js +15 -0
  246. package/dist/lib/ontology-graph/store/ingest.d.ts +37 -0
  247. package/dist/lib/ontology-graph/store/ingest.js +323 -0
  248. package/dist/lib/ontology-graph/store/paths.d.ts +114 -0
  249. package/dist/lib/ontology-graph/store/paths.js +232 -0
  250. package/dist/lib/ontology-graph/types.d.ts +1183 -0
  251. package/dist/lib/ontology-graph/types.js +131 -0
  252. package/dist/lib/secret-scan/gitleaks-rules.generated.js +1 -1
  253. package/dist/utils/frontmatter.d.ts +14 -0
  254. package/dist/utils/frontmatter.js +18 -0
  255. package/dist/utils/interactive-caller.js +1 -1
  256. package/package.json +8 -8
@@ -0,0 +1,792 @@
1
+ /**
2
+ * WP-E entry points: read commands and the always-on brief (design 4.2).
3
+ * Signatures are fixed by CONTRACT.md.
4
+ *
5
+ * All four read commands are read-only apart from the cache file
6
+ * `.state/read-index.json` (see graph-index.ts). Output is one line per fact
7
+ * or edge with its citation in square brackets: `[<src> <valid-from>]`, with
8
+ * ` @<key>` added when the row is not company-wide, and after it
9
+ * `file: <path from the HQ root>` when the source is a file on this machine,
10
+ * so a session can open what a line rests on.
11
+ *
12
+ * The graph is a way in, not the record. `about`, `discussed_in`, `mentions`
13
+ * and `related_to` say that two things appear in the same meeting, decision
14
+ * or document; they are counted and listed on request, never shown as a
15
+ * relationship and never followed by a walk unless named. `lookup` says so
16
+ * when it holds little on an entity, and a name it does not know is "not in
17
+ * the graph", not "not known".
18
+ *
19
+ * Audience: a caller sees `company` plus the keys in `context.member`, or the
20
+ * list passed as `audiences`. With neither, it sees every audience in the
21
+ * graph folder (the folder is built per member from files that member can
22
+ * read). The filter is applied to every row and every entity returned, and
23
+ * again at each hop of a walk.
24
+ */
25
+ import * as fs from "node:fs";
26
+ import * as path from "node:path";
27
+ import { filterPageLines } from "../pages/render.js";
28
+ import { effectiveFacts, originTier } from "../schema/index.js";
29
+ import { openGraphStore, pageFile } from "../store/index.js";
30
+ import { COMPANY_AUDIENCE, } from "../types.js";
31
+ import { graphExists, loadReadIndex, visible, } from "./graph-index.js";
32
+ import { indexedFacts, resolveName, searchIndex } from "./names.js";
33
+ export { briefCommand, buildBrief, estimateTokens, BRIEF_MAX_TOKENS } from "./brief.js";
34
+ export { graphReaderEnabled, readReaderSetting, readerSettingFile } from "./reader-setting.js";
35
+ export { loadReadIndex, forgetReadIndex, READ_INDEX_RELATIVE } from "./graph-index.js";
36
+ export { resolveName, searchIndex } from "./names.js";
37
+ export { resolveReadMember } from "./member.js";
38
+ /**
39
+ * Verbs that say two things appear together in a meeting, a decision or a
40
+ * document. They are evidence to open, not a relationship between the two.
41
+ */
42
+ export const CO_MENTION_VERBS = new Set(["about", "discussed_in", "mentions", "mentioned_in", "related_to"]);
43
+ /** Entities a path search opens before it gives up. */
44
+ export const PATH_EXPAND_LIMIT = 600;
45
+ /** Below this many rows of any kind, `lookup` says the graph holds little on the entity. */
46
+ export const THIN_ROW_COUNT = 5;
47
+ export const DEFAULT_EDGE_LIMIT = 40;
48
+ export const LOOKUP_EDGE_LIMIT = 12;
49
+ export const SIGNAL_LIMIT = 5;
50
+ export const LOOKUP_RECENT_LIMIT = 3;
51
+ export const WALK_NODE_LIMIT = 300;
52
+ /** Where a session can search when the graph does not answer. */
53
+ function vaultHint(context) {
54
+ return `Search the vault before answering: qmd or grep under companies/${context.company}/ (knowledge, policies, projects, sources, signals).`;
55
+ }
56
+ function signalFiles(session) {
57
+ if (session.signalFiles)
58
+ return session.signalFiles;
59
+ const found = new Map();
60
+ const root = path.join(session.context.companyRoot, "signals");
61
+ const list = (dir) => {
62
+ try {
63
+ return fs.readdirSync(dir, { withFileTypes: true });
64
+ }
65
+ catch {
66
+ return [];
67
+ }
68
+ };
69
+ // signals/<type>/<id>.md, signals/@<key>/<type>/<id>.md, signals/slack-dm/<type>/<id>.md
70
+ const walk = (dir, depth) => {
71
+ for (const entry of list(dir)) {
72
+ if (entry.name.startsWith(".") || entry.name.startsWith("_"))
73
+ continue;
74
+ const full = path.join(dir, entry.name);
75
+ if (entry.isDirectory()) {
76
+ if (depth < 3)
77
+ walk(full, depth + 1);
78
+ }
79
+ else if (/^[0-9a-f]{12,}\.md$/.test(entry.name)) {
80
+ const id = entry.name.slice(0, 12);
81
+ if (!found.has(id))
82
+ found.set(id, path.relative(session.context.hqRoot, full).split(path.sep).join("/"));
83
+ }
84
+ }
85
+ };
86
+ walk(root, 1);
87
+ session.signalFiles = found;
88
+ return found;
89
+ }
90
+ /**
91
+ * The file a source ref points at, as a path from the HQ root, or null when
92
+ * the ref is not a file on this machine (a record, an old entity id, a file
93
+ * that has gone). Only refs of rows the caller was shown are ever asked.
94
+ */
95
+ function fileOf(session, src) {
96
+ const known = session.files.get(src);
97
+ if (known !== undefined)
98
+ return known;
99
+ const { hqRoot, companyRoot } = session.context;
100
+ const colon = src.indexOf(":");
101
+ const kind = src.slice(0, colon);
102
+ const value = src.slice(colon + 1);
103
+ const rel = (absolute) => {
104
+ try {
105
+ return fs.statSync(absolute).isFile() ? path.relative(hqRoot, absolute).split(path.sep).join("/") : null;
106
+ }
107
+ catch {
108
+ return null;
109
+ }
110
+ };
111
+ let file = null;
112
+ if (kind === "signal")
113
+ file = signalFiles(session).get(value.slice(0, 12)) ?? null;
114
+ else if (kind === "session")
115
+ file = rel(path.join(hqRoot, "workspace", "threads", `${value}.json`));
116
+ else if ((kind === "source" || kind === "doc") && !value.includes("..") && !path.isAbsolute(value)) {
117
+ file = rel(path.join(companyRoot, ...value.split("/"))) ?? rel(path.join(hqRoot, ...value.split("/")));
118
+ }
119
+ session.files.set(src, file);
120
+ return file;
121
+ }
122
+ /** ` file: <path>` for a citation, or nothing. */
123
+ function fileNote(session, src) {
124
+ const file = fileOf(session, src);
125
+ return file ? ` file: ${file}` : "";
126
+ }
127
+ function fileJson(session, src) {
128
+ const file = fileOf(session, src);
129
+ return file ? { file } : {};
130
+ }
131
+ export function audienceFilterFor(context, extras = {}) {
132
+ if (extras.audiences)
133
+ return new Set(extras.audiences);
134
+ if (context.member)
135
+ return new Set([COMPANY_AUDIENCE, ...context.member.audienceKeys]);
136
+ return null;
137
+ }
138
+ function noGraph(context) {
139
+ return {
140
+ text: `ontology graph: no graph at ${context.graphRoot}. Build it with: hq ontology rebuild --company ${context.company}`,
141
+ json: { status: "no_graph", graphRoot: context.graphRoot },
142
+ exitCode: 1,
143
+ };
144
+ }
145
+ function open(context, extras) {
146
+ if (!extras.store && !graphExists(context.graphRoot))
147
+ return null;
148
+ const store = extras.store ?? openGraphStore(context.graphRoot, { company: context.company });
149
+ return {
150
+ context,
151
+ files: new Map(),
152
+ store,
153
+ schema: store.schema(),
154
+ index: loadReadIndex(context.graphRoot, { store }),
155
+ filter: audienceFilterFor(context, extras),
156
+ resolver: extras.resolver,
157
+ };
158
+ }
159
+ function readRows(session, ref, options = {}) {
160
+ const rows = session.store.readRows(ref, {
161
+ ...(session.filter === null ? {} : { audiences: [...session.filter] }),
162
+ ...(options.asOf ? { asOf: options.asOf } : {}),
163
+ ...(options.openOnly ? { openOnly: true } : {}),
164
+ });
165
+ // The store is asked for the allowed audiences; this second check holds even if a store ignores the option.
166
+ return session.filter === null ? rows : rows.filter((stored) => session.filter.has(stored.audience));
167
+ }
168
+ function scope(audience) {
169
+ return audience === COMPANY_AUDIENCE ? "" : ` @${audience}`;
170
+ }
171
+ function citeFact(stored) {
172
+ const row = stored.row;
173
+ return `[${row.src} ${row.valid.from} ${row.by} ${row.conf.toFixed(2)}${scope(stored.audience)}]`;
174
+ }
175
+ function citeEdge(stored) {
176
+ const row = stored.row;
177
+ const until = row.valid.to ? `..${row.valid.to}` : "";
178
+ return `[${row.src} ${row.valid.from}${until}${scope(stored.audience)}]`;
179
+ }
180
+ function nameOf(session, ref) {
181
+ const position = session.index.byId.get(ref);
182
+ return position === undefined ? "" : (session.index.entities[position]?.name ?? "");
183
+ }
184
+ function targetVisible(session, ref) {
185
+ const position = session.index.byId.get(ref);
186
+ const entity = position === undefined ? undefined : session.index.entities[position];
187
+ return entity !== undefined && visible(entity, session.filter);
188
+ }
189
+ function edgeRows(rows) {
190
+ return rows.filter((stored) => stored.row.kind === "E");
191
+ }
192
+ const CLASS_ORDER = { state: 0, event: 1, reference: 2 };
193
+ function verbClass(schema, verb) {
194
+ const spec = schema.link_types[verb];
195
+ return spec ? CLASS_ORDER[spec.class] : 2;
196
+ }
197
+ /** State edges first, then by authority, then newest. */
198
+ function byImportance(schema) {
199
+ return (a, b) => verbClass(schema, a.row.verb) - verbClass(schema, b.row.verb) ||
200
+ originTier(a.row.by) - originTier(b.row.by) ||
201
+ (a.row.valid.from < b.row.valid.from ? 1 : a.row.valid.from > b.row.valid.from ? -1 : 0) ||
202
+ (a.row.target < b.row.target ? -1 : a.row.target > b.row.target ? 1 : 0);
203
+ }
204
+ function candidateLine(session, entity) {
205
+ const facts = entityFactsFromIndex(session, entity).slice(0, 2);
206
+ const detail = facts.map((stored) => `${stored.row.field}: ${stored.row.value}`).join("; ");
207
+ return ` ${entity.id} | ${entity.name}${detail ? ` | ${detail}` : ""}`;
208
+ }
209
+ function entityFactsFromIndex(session, entity) {
210
+ return indexedFacts(session.index, session.schema, entity, session.filter);
211
+ }
212
+ function candidateJson(entity) {
213
+ return { id: entity.id, type: entity.type, name: entity.name };
214
+ }
215
+ /** The reply for a name that did not resolve to one entity. Never picks one. */
216
+ function unresolvedOutput(session, typed, answer) {
217
+ const candidates = answer.candidates;
218
+ const json = {
219
+ status: answer.status,
220
+ reason: answer.reason,
221
+ query: typed,
222
+ candidates: candidates.map(candidateJson),
223
+ };
224
+ if (answer.status === "ambiguous") {
225
+ return {
226
+ text: [
227
+ `ambiguous: "${typed}" matches ${String(candidates.length)} entities (${answer.reason}). Pick one id and ask again:`,
228
+ ...candidates.map((entity) => candidateLine(session, entity)),
229
+ ].join("\n"),
230
+ json,
231
+ };
232
+ }
233
+ if (answer.status === "refused") {
234
+ return { text: `refused: "${typed}" is not looked up by name (${answer.reason}). Use a full name or an id.`, json, exitCode: 1 };
235
+ }
236
+ return {
237
+ text: [
238
+ `no match: "${typed}" (${answer.reason}).`,
239
+ ...(candidates.length > 0 ? ["near matches, none selected:", ...candidates.map((entity) => candidateLine(session, entity))] : []),
240
+ // The graph not knowing a name is not the company not knowing it.
241
+ `Not in the graph is not "not known". ${vaultHint(session.context)}`,
242
+ ].join("\n"),
243
+ json,
244
+ exitCode: 1,
245
+ };
246
+ }
247
+ function resolve(session, typed) {
248
+ return preferInternalPerson(session, resolveName(session.index, session.schema, typed, {
249
+ filter: session.filter,
250
+ store: session.store,
251
+ ...(session.resolver !== undefined ? { resolver: session.resolver } : {}),
252
+ }));
253
+ }
254
+ /** One line saying which same-named entities the answer was chosen over, or nothing. */
255
+ function chosenLine(answer) {
256
+ if (!answer.entity || !answer.chosenOver || answer.chosenOver.length === 0)
257
+ return [];
258
+ return [
259
+ `chosen: ${answer.entity.id}, who works at the company, over ${answer.chosenOver.map((entity) => `${entity.id} (${entity.type})`).join(", ")} with the same name. Ask by id for the other.`,
260
+ ];
261
+ }
262
+ function edgeJson(session, stored) {
263
+ return {
264
+ verb: stored.row.verb,
265
+ target: stored.row.target,
266
+ name: nameOf(session, stored.row.target),
267
+ src: stored.row.src,
268
+ ...fileJson(session, stored.row.src),
269
+ valid_from: stored.row.valid.from,
270
+ ...(stored.row.valid.to ? { valid_to: stored.row.valid.to } : {}),
271
+ by: stored.row.by,
272
+ conf: stored.row.conf,
273
+ audience: stored.audience,
274
+ // False: the two appear in the same meeting, decision or document. Open the source; do not report a relationship.
275
+ relationship: !CO_MENTION_VERBS.has(stored.row.verb),
276
+ };
277
+ }
278
+ function edgeLine(session, stored) {
279
+ const name = nameOf(session, stored.row.target);
280
+ return `${stored.row.verb} -> ${stored.row.target}${name ? ` (${name})` : ""} ${citeEdge(stored)}${fileNote(session, stored.row.src)}`;
281
+ }
282
+ /** Counts per co-mention verb, as `discussed_in 40, about 3`. */
283
+ function coMentionSummary(edges) {
284
+ const counts = {};
285
+ for (const stored of edges)
286
+ counts[stored.row.verb] = (counts[stored.row.verb] ?? 0) + 1;
287
+ const text = Object.entries(counts).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([verb, count]) => `${verb} ${String(count)}`).join(", ");
288
+ return { text, counts };
289
+ }
290
+ /** The company the graph belongs to: the one with an open `relation = self` fact, else `company/<slug>`. */
291
+ function selfCompany(session) {
292
+ for (const entity of session.index.entities) {
293
+ if (entity.type !== "company")
294
+ continue;
295
+ if (entityFactsFromIndex(session, entity).some((stored) => stored.row.field === "relation" && stored.row.value === "self"))
296
+ return entity.id;
297
+ }
298
+ return `company/${session.context.company}`;
299
+ }
300
+ /**
301
+ * When a name matches several entities and exactly one of them is a person
302
+ * who works at the company itself, that person is the answer (a contact or
303
+ * account left over from the CRM often carries a team member's name). The
304
+ * reply names the entities it was chosen over, so nothing is picked silently.
305
+ */
306
+ function preferInternalPerson(session, answer) {
307
+ if (answer.status !== "ambiguous" || answer.candidates.length < 2 || answer.candidates.length > 6)
308
+ return answer;
309
+ const self = selfCompany(session);
310
+ const internal = answer.candidates.filter((candidate) => candidate.type === "person" &&
311
+ readRows(session, candidate.id, { openOnly: true }).some((stored) => stored.row.kind === "E" && stored.row.verb === "works_at" && stored.row.target === self));
312
+ if (internal.length !== 1)
313
+ return answer;
314
+ const chosen = internal[0];
315
+ const name = (entity) => entity.name.trim().toLowerCase().replace(/\s+/g, " ");
316
+ const others = answer.candidates.filter((candidate) => candidate.id !== chosen.id);
317
+ // Only when the others carry the very same name: two different people who share a first name stay a question.
318
+ const sameName = (entity) => name(entity) === name(chosen) || entity.aliases.some((alias) => alias.trim().toLowerCase().replace(/\s+/g, " ") === name(chosen));
319
+ if (!others.every((candidate) => candidate.type !== "person" && sameName(candidate)))
320
+ return answer;
321
+ return { status: "resolved", reason: "internal_person", entity: chosen, candidates: answer.candidates, chosenOver: others };
322
+ }
323
+ function visibleEdges(session, rows) {
324
+ return edgeRows(rows).filter((stored) => targetVisible(session, stored.row.target));
325
+ }
326
+ // ---------------------------------------------------------------------------
327
+ // lookup
328
+ // ---------------------------------------------------------------------------
329
+ /** `hq ontology lookup <name> [--as-of D]`. */
330
+ export async function lookupCommand(context, options) {
331
+ const session = open(context, options);
332
+ if (!session)
333
+ return noGraph(context);
334
+ const answer = resolve(session, options.name);
335
+ if (answer.status !== "resolved" || !answer.entity)
336
+ return unresolvedOutput(session, options.name, answer);
337
+ const entity = answer.entity;
338
+ if (options.page)
339
+ return pageOutput(session, entity, answer);
340
+ const rows = readRows(session, entity.id, options.asOf ? { asOf: options.asOf } : {});
341
+ const facts = effectiveFacts(session.schema, entity.type, rows, options.asOf);
342
+ const live = options.asOf ? visibleEdges(session, rows) : visibleEdges(session, rows).filter((stored) => !stored.row.valid.to);
343
+ // Relationships only. Appearing in the same meeting or decision is counted below, not listed as an edge.
344
+ const edges = live.filter((stored) => !CO_MENTION_VERBS.has(stored.row.verb)).sort(byImportance(session.schema));
345
+ const together = coMentionSummary(live.filter((stored) => CO_MENTION_VERBS.has(stored.row.verb)));
346
+ const limit = options.limit ?? LOOKUP_EDGE_LIMIT;
347
+ const shown = edges.slice(0, limit);
348
+ const timeline = rows
349
+ .filter((stored) => stored.row.kind === "T")
350
+ .sort((a, b) => (a.row.date < b.row.date ? 1 : a.row.date > b.row.date ? -1 : 0));
351
+ const recent = timeline.slice(0, LOOKUP_RECENT_LIMIT);
352
+ const thin = facts.length + edges.length + timeline.length < THIN_ROW_COUNT || (facts.length === 0 && edges.length === 0);
353
+ const lines = [
354
+ `${entity.id} | ${entity.name}${entity.aliases.length > 0 ? ` | aka ${entity.aliases.slice(0, 4).join(", ")}` : ""} | ${answer.reason}${options.asOf ? ` | as of ${options.asOf}` : ""}`,
355
+ ...chosenLine(answer),
356
+ ];
357
+ if (facts.length > 0) {
358
+ lines.push("facts:");
359
+ for (const stored of facts)
360
+ lines.push(` ${stored.row.field} = ${stored.row.value} ${citeFact(stored)}${fileNote(session, stored.row.src)}`);
361
+ }
362
+ else {
363
+ lines.push("facts: none recorded");
364
+ }
365
+ if (shown.length > 0) {
366
+ lines.push(`edges (${String(shown.length)} of ${String(edges.length)}):`);
367
+ for (const stored of shown)
368
+ lines.push(` ${edgeLine(session, stored)}`);
369
+ }
370
+ if (edges.length > shown.length)
371
+ lines.push(`more: hq ontology neighbors ${entity.id}`);
372
+ if (together.text) {
373
+ lines.push(`appears in the same meetings, decisions or documents as other things (not relationships): ${together.text}. To list the sources: hq ontology neighbors ${entity.id} --verb ${Object.keys(together.counts)[0]}`);
374
+ }
375
+ if (recent.length > 0) {
376
+ lines.push(`latest dated lines (${String(recent.length)} of ${String(timeline.length)}):`);
377
+ for (const stored of recent) {
378
+ lines.push(` ${stored.row.date} | ${stored.row.signalType} | ${clip(stored.row.text, 160)} [${stored.row.src}${scope(stored.audience)}]${fileNote(session, stored.row.src)}`);
379
+ }
380
+ }
381
+ if (thin) {
382
+ lines.push(`thin: the graph holds ${String(facts.length)} facts, ${String(edges.length)} relationships and ${String(timeline.length)} dated lines on ${entity.id}. That is not the whole record, and nothing here means "not known". ${vaultHint(session.context)}`);
383
+ }
384
+ return {
385
+ text: lines.join("\n"),
386
+ json: {
387
+ status: "resolved",
388
+ reason: answer.reason,
389
+ entity: { id: entity.id, type: entity.type, name: entity.name, aliases: entity.aliases },
390
+ ...(answer.chosenOver ? { chosenOver: answer.chosenOver.map(candidateJson) } : {}),
391
+ ...(options.asOf ? { asOf: options.asOf } : {}),
392
+ facts: facts.map((stored) => ({
393
+ field: stored.row.field,
394
+ value: stored.row.value,
395
+ src: stored.row.src,
396
+ ...fileJson(session, stored.row.src),
397
+ valid_from: stored.row.valid.from,
398
+ by: stored.row.by,
399
+ conf: stored.row.conf,
400
+ audience: stored.audience,
401
+ })),
402
+ edges: shown.map((stored) => edgeJson(session, stored)),
403
+ edgesTotal: edges.length,
404
+ coMentions: together.counts,
405
+ recent: recent.map((stored) => ({ date: stored.row.date, type: stored.row.signalType, text: stored.row.text, src: stored.row.src, ...fileJson(session, stored.row.src), audience: stored.audience })),
406
+ timelineTotal: timeline.length,
407
+ thin,
408
+ },
409
+ };
410
+ }
411
+ /** `lookup --page`: the compiled page, with every line the caller's audiences do not cover removed. */
412
+ function pageOutput(session, entity, answer) {
413
+ let text;
414
+ try {
415
+ text = fs.readFileSync(pageFile(session.context.graphRoot, entity.id), "utf8");
416
+ }
417
+ catch {
418
+ return {
419
+ text: `no compiled page for ${entity.id}. Compile pages with: hq ontology update --company ${session.context.company}. Meanwhile: hq ontology lookup ${entity.id}`,
420
+ json: { status: "no_page", entity: candidateJson(entity) },
421
+ exitCode: 1,
422
+ };
423
+ }
424
+ // The page file holds every audience of the member's own graph. What is printed is filtered line by line.
425
+ const audiences = session.filter === null ? session.store.listAudiences() : [...session.filter];
426
+ const filtered = filterPageLines(text, audiences);
427
+ return {
428
+ text: [...chosenLine({ entity, ...answer }), filtered.text].join("\n"),
429
+ json: { status: "page", entity: candidateJson(entity), kept: filtered.kept, removed: filtered.removed, audiences: [...audiences].sort(), page: filtered.text },
430
+ };
431
+ }
432
+ // ---------------------------------------------------------------------------
433
+ // neighbors
434
+ // ---------------------------------------------------------------------------
435
+ function verbList(schema, verb, verbs) {
436
+ const wanted = [...(verb ? verb.split(",") : []), ...(verbs ?? [])].map((entry) => entry.trim()).filter(Boolean);
437
+ const unknown = wanted.filter((entry) => !(entry in schema.link_types));
438
+ if (unknown.length > 0) {
439
+ return {
440
+ text: `unknown verb: ${unknown.join(", ")}. Verbs: ${Object.keys(schema.link_types).sort().join(", ")}`,
441
+ json: { status: "unknown_verb", unknown, verbs: Object.keys(schema.link_types).sort() },
442
+ exitCode: 1,
443
+ };
444
+ }
445
+ return [...new Set(wanted)];
446
+ }
447
+ /** `hq ontology neighbors <id> [--verb V] [--depth N] [--as-of D]`. */
448
+ export async function neighborsCommand(context, options) {
449
+ const session = open(context, options);
450
+ if (!session)
451
+ return noGraph(context);
452
+ const verbs = verbList(session.schema, options.verb, undefined);
453
+ if (!Array.isArray(verbs))
454
+ return verbs;
455
+ const answer = resolve(session, options.id);
456
+ if (answer.status !== "resolved" || !answer.entity)
457
+ return unresolvedOutput(session, options.id, answer);
458
+ const entity = answer.entity;
459
+ if ((options.depth ?? 1) > 1) {
460
+ return traverseCommand(context, {
461
+ ...options,
462
+ id: entity.id,
463
+ depth: options.depth ?? 1,
464
+ ...(verbs.length > 0 ? { verbs } : {}),
465
+ });
466
+ }
467
+ const rows = readRows(session, entity.id, options.asOf ? { asOf: options.asOf } : {});
468
+ const matching = visibleEdges(session, rows)
469
+ .filter((stored) => options.asOf !== undefined || !stored.row.valid.to)
470
+ .filter((stored) => verbs.length === 0 || verbs.includes(stored.row.verb))
471
+ .sort(byImportance(session.schema));
472
+ // With no verb named, only relationships are listed. Appearing in the same meeting or decision is counted.
473
+ const all = verbs.length > 0 ? matching : matching.filter((stored) => !CO_MENTION_VERBS.has(stored.row.verb));
474
+ const together = coMentionSummary(verbs.length > 0 ? [] : matching.filter((stored) => CO_MENTION_VERBS.has(stored.row.verb)));
475
+ const limit = options.limit ?? DEFAULT_EDGE_LIMIT;
476
+ const shown = all.slice(0, limit);
477
+ const signals = verbs.length > 0
478
+ ? []
479
+ : rows
480
+ .filter((stored) => stored.row.kind === "T")
481
+ .sort((a, b) => (a.row.date < b.row.date ? 1 : a.row.date > b.row.date ? -1 : 0))
482
+ .slice(0, SIGNAL_LIMIT);
483
+ const lines = [`${entity.id} | ${entity.name}${options.asOf ? ` | as of ${options.asOf}` : ""} | ${String(all.length)} edges`, ...chosenLine(answer)];
484
+ let lastVerb = "";
485
+ for (const stored of shown) {
486
+ if (stored.row.verb !== lastVerb) {
487
+ lastVerb = stored.row.verb;
488
+ lines.push(CO_MENTION_VERBS.has(lastVerb) ? `${lastVerb} (the two appear in the same source; not a relationship, open the file to see what was said):` : `${lastVerb}:`);
489
+ }
490
+ const name = nameOf(session, stored.row.target);
491
+ lines.push(` ${stored.row.target}${name ? ` (${name})` : ""} ${citeEdge(stored)}${fileNote(session, stored.row.src)}`);
492
+ }
493
+ if (all.length > shown.length) {
494
+ const rest = new Map();
495
+ for (const stored of all.slice(limit))
496
+ rest.set(stored.row.verb, (rest.get(stored.row.verb) ?? 0) + 1);
497
+ lines.push(`not shown: ${[...rest].map(([verb, count]) => `${verb} ${String(count)}`).join(", ")} (narrow with --verb)`);
498
+ }
499
+ if (together.text) {
500
+ lines.push(`appears in the same meetings, decisions or documents (not relationships): ${together.text}. To list the sources: --verb ${Object.keys(together.counts)[0]}`);
501
+ }
502
+ if (signals.length > 0) {
503
+ lines.push("recent signals:");
504
+ for (const stored of signals) {
505
+ lines.push(` ${stored.row.date} | ${stored.row.signalType} | ${stored.row.text} [${stored.row.src}${scope(stored.audience)}]${fileNote(session, stored.row.src)}`);
506
+ }
507
+ }
508
+ if (all.length === 0 && signals.length === 0) {
509
+ lines.push(`The graph holds no relationship for ${entity.id}. That does not mean there is none. ${vaultHint(context)}`);
510
+ }
511
+ return {
512
+ text: lines.join("\n"),
513
+ json: {
514
+ status: "resolved",
515
+ entity: candidateJson(entity),
516
+ ...(options.asOf ? { asOf: options.asOf } : {}),
517
+ edges: shown.map((stored) => edgeJson(session, stored)),
518
+ edgesTotal: all.length,
519
+ coMentions: together.counts,
520
+ signals: signals.map((stored) => ({
521
+ date: stored.row.date,
522
+ type: stored.row.signalType,
523
+ text: stored.row.text,
524
+ src: stored.row.src,
525
+ ...fileJson(session, stored.row.src),
526
+ audience: stored.audience,
527
+ })),
528
+ },
529
+ };
530
+ }
531
+ // ---------------------------------------------------------------------------
532
+ // search
533
+ // ---------------------------------------------------------------------------
534
+ /**
535
+ * `hq ontology search <text>`: names, aliases, identity keys and open facts,
536
+ * from the local index. qmd is not used: it skips dot folders and the graph
537
+ * lives in `.hq/` (correction C1).
538
+ */
539
+ export async function searchCommand(context, options) {
540
+ const session = open(context, options);
541
+ if (!session)
542
+ return noGraph(context);
543
+ const hits = searchIndex(session.index, session.schema, options.text, {
544
+ filter: session.filter,
545
+ limit: options.limit ?? 10,
546
+ });
547
+ if (hits.length === 0) {
548
+ return { text: `no results for "${options.text}"`, json: { status: "ok", query: options.text, results: [] } };
549
+ }
550
+ const lines = hits.map((hit) => {
551
+ const facts = hit.fact
552
+ ? [{ audience: hit.fact.audience, row: hit.fact.row }]
553
+ : entityFactsFromIndex(session, hit.entity).slice(0, 1).map((stored) => ({ audience: stored.audience, row: stored.row }));
554
+ const fact = facts[0];
555
+ const detail = fact ? ` | ${fact.row.field} = ${clip(fact.row.value, 80)} [${fact.row.src} ${fact.row.valid.from}${scope(fact.audience)}]` : "";
556
+ return `${hit.entity.id} | ${hit.entity.name} | ${hit.matched}${detail}`;
557
+ });
558
+ return {
559
+ text: lines.join("\n"),
560
+ json: {
561
+ status: "ok",
562
+ query: options.text,
563
+ results: hits.map((hit) => ({
564
+ ...candidateJson(hit.entity),
565
+ score: hit.score,
566
+ matched: hit.matched,
567
+ ...(hit.fact
568
+ ? { fact: { field: hit.fact.row.field, value: hit.fact.row.value, src: hit.fact.row.src, audience: hit.fact.audience } }
569
+ : {}),
570
+ })),
571
+ },
572
+ };
573
+ }
574
+ function clip(text, max) {
575
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
576
+ }
577
+ /**
578
+ * Breadth-first walk from `start`, at most `depth` hops and `WALK_NODE_LIMIT`
579
+ * nodes. Each hop reads only rows in the allowed audiences and only steps to
580
+ * an entity that is itself visible, so a path never crosses a hidden entity.
581
+ * With no verbs given, reference edges (mentions, related_to) and the verbs
582
+ * that only say two things share a meeting or decision (about, discussed_in)
583
+ * are not followed: a walk through them reaches the whole company in two hops
584
+ * and says nothing about how two things are related.
585
+ */
586
+ function stepEdges(session, ref, verbs, asOf) {
587
+ const rows = readRows(session, ref, asOf ? { asOf } : {});
588
+ return visibleEdges(session, rows)
589
+ .filter((stored) => asOf !== undefined || !stored.row.valid.to)
590
+ .filter((stored) => verbs.length > 0 ? verbs.includes(stored.row.verb) : verbClass(session.schema, stored.row.verb) < 2 && !CO_MENTION_VERBS.has(stored.row.verb))
591
+ .sort(byImportance(session.schema));
592
+ }
593
+ /**
594
+ * The shortest path between two entities, searched from both ends at once.
595
+ * A founder has hundreds of relationships and so has the other founder; from
596
+ * one end three hops is the whole graph, from both ends it is the two
597
+ * neighbourhoods. The smaller frontier is opened first. Gives up only after
598
+ * opening `PATH_EXPAND_LIMIT` entities, and says so.
599
+ */
600
+ function findPath(session, start, goal, depth, verbs, asOf) {
601
+ if (start === goal)
602
+ return { path: [], stopped: false, opened: 0 };
603
+ // A named relationship is followed in both directions: the row on the far end carries the inverse verb.
604
+ const both = verbs.length === 0 ? verbs : [...new Set(verbs.flatMap((verb) => [verb, session.schema.link_types[verb]?.inverse ?? verb]))];
605
+ // node -> the hop that reached it. On the goal side `hop.from` is the node nearer the goal.
606
+ const fromStart = new Map([[start, null]]);
607
+ const fromGoal = new Map([[goal, null]]);
608
+ let frontStart = [start];
609
+ let frontGoal = [goal];
610
+ let levels = 0;
611
+ let levelsStart = 0;
612
+ let levelsGoal = 0;
613
+ let opened = 0;
614
+ let stopped = false;
615
+ let meet = null;
616
+ while (meet === null && !stopped && levels < depth && frontStart.length > 0 && frontGoal.length > 0) {
617
+ // The smaller frontier; on a tie, the end that has been opened less, so neither end is starved.
618
+ const forward = frontStart.length !== frontGoal.length ? frontStart.length < frontGoal.length : levelsStart <= levelsGoal;
619
+ const mine = forward ? fromStart : fromGoal;
620
+ const other = forward ? fromGoal : fromStart;
621
+ const next = [];
622
+ search: for (const ref of forward ? frontStart : frontGoal) {
623
+ if (opened >= PATH_EXPAND_LIMIT) {
624
+ stopped = true;
625
+ break;
626
+ }
627
+ opened += 1;
628
+ for (const edge of stepEdges(session, ref, both, asOf)) {
629
+ const target = edge.row.target;
630
+ if (mine.has(target))
631
+ continue;
632
+ mine.set(target, { from: ref, edge, depth: levels + 1 });
633
+ if (other.has(target)) {
634
+ meet = target;
635
+ break search;
636
+ }
637
+ next.push(target);
638
+ }
639
+ }
640
+ if (forward) {
641
+ frontStart = next;
642
+ levelsStart += 1;
643
+ }
644
+ else {
645
+ frontGoal = next;
646
+ levelsGoal += 1;
647
+ }
648
+ levels += 1;
649
+ }
650
+ if (meet === null)
651
+ return { path: null, stopped, opened };
652
+ const path = [];
653
+ for (let at = meet; at !== start;) {
654
+ const hop = fromStart.get(at);
655
+ path.unshift(hop);
656
+ at = hop.from;
657
+ }
658
+ for (let at = meet; at !== goal;) {
659
+ const hop = fromGoal.get(at);
660
+ // The row as read from this node toward the goal; when only the other direction passes the verb filter, that row.
661
+ const here = at;
662
+ const outward = stepEdges(session, here, both, asOf).find((edge) => edge.row.target === hop.from);
663
+ path.push(outward ? { from: here, edge: outward, depth: 0 } : { from: hop.from, edge: hop.edge, depth: 0 });
664
+ at = hop.from;
665
+ }
666
+ return { path: path.map((hop, index) => ({ ...hop, depth: index + 1 })), stopped: false, opened };
667
+ }
668
+ /**
669
+ * Breadth-first walk outward from one entity (see above for what is followed).
670
+ */
671
+ function walk(session, start, depth, verbs, asOf, stopAt) {
672
+ const parents = new Map();
673
+ const hops = [];
674
+ const seen = new Set([start]);
675
+ let frontier = [start];
676
+ let truncated = false;
677
+ for (let level = 1; level <= depth && frontier.length > 0; level += 1) {
678
+ const next = [];
679
+ for (const ref of frontier) {
680
+ for (const edge of stepEdges(session, ref, verbs, asOf)) {
681
+ const target = edge.row.target;
682
+ if (seen.has(target))
683
+ continue;
684
+ if (seen.size >= WALK_NODE_LIMIT) {
685
+ truncated = true;
686
+ break;
687
+ }
688
+ seen.add(target);
689
+ const hop = { from: ref, edge, depth: level };
690
+ parents.set(target, hop);
691
+ hops.push(hop);
692
+ next.push(target);
693
+ if (stopAt !== undefined && target === stopAt)
694
+ return { hops, parents, truncated };
695
+ }
696
+ if (truncated)
697
+ break;
698
+ }
699
+ if (truncated)
700
+ break;
701
+ frontier = next;
702
+ }
703
+ return { hops, parents, truncated };
704
+ }
705
+ /**
706
+ * `hq ontology traverse <from> [<to>] [--verb V[,V]] [--depth 1-3]`.
707
+ * With `to`: the shortest path between two entities. Without: everything
708
+ * reachable from `from` along the verbs.
709
+ */
710
+ export async function traverseCommand(context, options) {
711
+ const session = open(context, options);
712
+ if (!session)
713
+ return noGraph(context);
714
+ const verbs = verbList(session.schema, options.verb, options.verbs);
715
+ if (!Array.isArray(verbs))
716
+ return verbs;
717
+ const depth = Math.min(3, Math.max(1, Math.trunc(options.depth) || 1));
718
+ const from = resolve(session, options.id);
719
+ if (from.status !== "resolved" || !from.entity)
720
+ return unresolvedOutput(session, options.id, from);
721
+ const start = from.entity;
722
+ if (options.to !== undefined) {
723
+ const to = resolve(session, options.to);
724
+ if (to.status !== "resolved" || !to.entity)
725
+ return unresolvedOutput(session, options.to, to);
726
+ const goal = to.entity;
727
+ const found = findPath(session, start.id, goal.id, depth, verbs, options.asOf);
728
+ const path = found.path ?? [];
729
+ if (found.path === null) {
730
+ if (found.stopped) {
731
+ // The search gave up at its limit: that is not the same as there being no path.
732
+ return {
733
+ text: [
734
+ `path search from ${start.id} to ${goal.id} stopped after opening ${String(found.opened)} entities without joining the two. That is not "no path".`,
735
+ `Name the relationships to follow, for example: --verb works_on,has_contributor or --verb attended,had_attendee`,
736
+ ].join("\n"),
737
+ json: { status: "search_stopped", from: start.id, to: goal.id, depth, searched: found.opened },
738
+ exitCode: 1,
739
+ };
740
+ }
741
+ return {
742
+ text: [
743
+ `no path from ${start.id} to ${goal.id} within ${String(depth)} hops${verbs.length > 0 ? ` along ${verbs.join(", ")}` : " along relationships"}.`,
744
+ ...(verbs.length > 0
745
+ ? []
746
+ : [`The two may still share meetings or decisions: add --verb about,discussed_in to find them. The graph not linking them is not "unrelated". ${vaultHint(context)}`]),
747
+ ].join("\n"),
748
+ json: { status: "no_path", from: start.id, to: goal.id, depth },
749
+ };
750
+ }
751
+ const shared = path.some((hop) => CO_MENTION_VERBS.has(hop.edge.row.verb));
752
+ return {
753
+ text: [
754
+ `${start.id} -> ${goal.id} | ${String(path.length)} hops`,
755
+ ...chosenLine(from),
756
+ ...chosenLine(to),
757
+ ...path.map((hop) => ` ${hop.from} ${edgeLine(session, hop.edge)}`),
758
+ ...(shared ? ["This path runs through a shared meeting, decision or document. It shows where the two appear together, not a relationship: open the file."] : []),
759
+ ].join("\n"),
760
+ json: {
761
+ status: "path",
762
+ from: start.id,
763
+ to: goal.id,
764
+ hops: path.map((hop) => ({ from: hop.from, ...edgeJson(session, hop.edge) })),
765
+ },
766
+ };
767
+ }
768
+ const result = walk(session, start.id, depth, verbs, options.asOf);
769
+ const limit = options.limit ?? 80;
770
+ const shown = result.hops.slice(0, limit);
771
+ const lines = [
772
+ `${start.id} | ${start.name} | depth ${String(depth)}${verbs.length > 0 ? ` | ${verbs.join(", ")}` : ""} | ${String(result.hops.length)} reached`,
773
+ ...shown.map((hop) => ` ${String(hop.depth)} ${hop.from} ${edgeLine(session, hop.edge)}`),
774
+ ];
775
+ if (result.hops.length > shown.length)
776
+ lines.push(`not shown: ${String(result.hops.length - shown.length)} (narrow with --verb)`);
777
+ if (result.truncated)
778
+ lines.push(`stopped at ${String(WALK_NODE_LIMIT)} entities`);
779
+ return {
780
+ text: lines.join("\n"),
781
+ json: {
782
+ status: "walk",
783
+ from: start.id,
784
+ depth,
785
+ verbs,
786
+ reached: result.hops.length,
787
+ truncated: result.truncated,
788
+ hops: shown.map((hop) => ({ depth: hop.depth, from: hop.from, ...edgeJson(session, hop.edge) })),
789
+ },
790
+ };
791
+ }
792
+ //# sourceMappingURL=index.js.map