@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,595 @@
1
+ /**
2
+ * WP-F: the daily job. Once a day, on each member's own machine:
3
+ *
4
+ * hq ontology update replay the days after the cursor (model calls capped by the day's token budget)
5
+ * hq ontology lint model-free checks; files proposals
6
+ * hq ontology brief rewrite brief.md
7
+ *
8
+ * Two parts:
9
+ *
10
+ * 1. `runDaily` is that sequence as one idempotent run (`hq ontology daily`).
11
+ * It takes a lock so two runs never write one graph folder, skips when no
12
+ * input changed since the last good run, and charges every run of a day
13
+ * against one token budget.
14
+ * 2. `installDailyJob` / `uninstallDailyJob` register it the way this install
15
+ * schedules a member's daily work: a no-agent cron job in the HQ Fleet
16
+ * Runtime of the member's Executive bot, the same mechanism as the 06:30
17
+ * signals run (`ensureFleetHotSignalSync` in src/lib/bot/fleet-cron.ts).
18
+ * The job runs a small script that calls `hq ontology daily`; no model turn
19
+ * is spent on the scheduling itself. `hq daemon` units are a fixed catalog
20
+ * with no clock time, `hq core jobs` are Outpost-only agent prompts, and
21
+ * the CLI installs no per-job LaunchAgent, so none of those fit.
22
+ *
23
+ * The script prints nothing on success, so the bot posts nothing. On failure
24
+ * it prints one line with the log path, which the runtime delivers to the
25
+ * owner like the signals job's failure line.
26
+ */
27
+ import { createHash } from "node:crypto";
28
+ import * as fs from "node:fs";
29
+ import * as path from "node:path";
30
+ import { createLockFile, lockIsStale, readLockFile, releaseLockFile } from "../../../utils/exclusive-lock.js";
31
+ import { GRAPH_PATHS, atomicWriteFile, claimGraphRootFor, graphPath, readTextIfExists } from "../store/index.js";
32
+ // ---------------------------------------------------------------------------
33
+ // The daily run
34
+ // ---------------------------------------------------------------------------
35
+ /** Daily cap on model input tokens (design section 5). It is what `hq ontology update --budget-tokens` counts. */
36
+ export const DAILY_BUDGET_TOKENS = 150_000;
37
+ /** Days between two lints of the whole graph by the daily job. In between it lints what each update touched. */
38
+ export const FULL_LINT_EVERY_DAYS = 7;
39
+ /** How far back the change check looks for new or changed inputs. */
40
+ export const CHANGE_WINDOW_DAYS = 14;
41
+ const STATE_FILE = `${GRAPH_PATHS.state}/daily.json`;
42
+ const LOCK_FILE = `${GRAPH_PATHS.state}/daily.lock`;
43
+ /** The member's calendar day: the job runs once per local day. */
44
+ function localDay(now) {
45
+ const pad = (value) => String(value).padStart(2, "0");
46
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
47
+ }
48
+ function shiftDay(day, days) {
49
+ return new Date(Date.parse(`${day}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
50
+ }
51
+ export function readDailyState(graphRoot) {
52
+ const text = readTextIfExists(graphPath(graphRoot, STATE_FILE));
53
+ if (text === null)
54
+ return null;
55
+ try {
56
+ const value = JSON.parse(text);
57
+ return typeof value?.day === "string" && typeof value?.lastRunAt === "string" ? value : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ function writeDailyState(graphRoot, state) {
64
+ atomicWriteFile(graphPath(graphRoot, STATE_FILE), `${JSON.stringify(state, null, 2)}\n`);
65
+ }
66
+ function processAlive(pid) {
67
+ try {
68
+ process.kill(pid, 0);
69
+ return true;
70
+ }
71
+ catch (error) {
72
+ return error.code === "EPERM";
73
+ }
74
+ }
75
+ function parseDailyLockOwner(content) {
76
+ const value = JSON.parse(content);
77
+ return typeof value?.pid === "number" && typeof value.at === "string" ? { pid: value.pid, at: value.at } : null;
78
+ }
79
+ /**
80
+ * A lock older than this is taken whatever its process id says. The scheduled
81
+ * script ends a run after 45 minutes, so a lock this old is not a run: its
82
+ * process id has been given to some other process, and without a limit that
83
+ * process would keep the daily run out for as long as it lives.
84
+ */
85
+ export const LOCK_MAX_AGE_MS = 6 * 60 * 60 * 1000;
86
+ /** With `--force`, a lock older than this is taken: past the 45 minutes a scheduled run may last, with room to spare. */
87
+ export const LOCK_FORCE_AGE_MS = 60 * 60 * 1000;
88
+ /** A takeover file with nothing readable in it yet is a run that has just created it: it is left alone for this long. */
89
+ export const TAKEOVER_GRACE_MS = 10_000;
90
+ /** A takeover is over in milliseconds. A takeover file older than this was left behind, whatever its process id says. */
91
+ export const TAKEOVER_MAX_AGE_MS = 60_000;
92
+ /** May the takeover file be cleared: its run is gone, or it was left behind. */
93
+ function takeoverIsStale(takeover, clock) {
94
+ let ageMs;
95
+ try {
96
+ ageMs = clock() - fs.statSync(takeover).mtimeMs;
97
+ }
98
+ catch {
99
+ // Gone already: the run that held it has finished. Nothing to clear.
100
+ return false;
101
+ }
102
+ if (lockIsStale({ kind: "age", maxAgeMs: TAKEOVER_MAX_AGE_MS }, { ageMs }))
103
+ return true;
104
+ const owner = readLockFile(takeover, (content) => (/^\d+$/.test(content.trim()) ? { pid: Number(content.trim()) } : null));
105
+ // Created and not yet written: the file exists before its content does. That is a live run, for a short while.
106
+ if (owner === null)
107
+ return lockIsStale({ kind: "age", maxAgeMs: TAKEOVER_GRACE_MS }, { ageMs });
108
+ return lockIsStale({ kind: "pid", alive: processAlive }, { owner });
109
+ }
110
+ /**
111
+ * Takes the run lock. Returns a release function, or null when a live run holds it.
112
+ *
113
+ * The lock is a file created exclusively (src/utils/exclusive-lock.ts). It is
114
+ * stale when its owner's process is gone, when it cannot be read, when this
115
+ * process left it behind, or when it is older than LOCK_MAX_AGE_MS (with
116
+ * `force`, LOCK_FORCE_AGE_MS). A stale lock is replaced under a second
117
+ * exclusive file, so of two runs that find the same stale lock one takes it
118
+ * and the other is told a run holds it. Release removes the lock only while it
119
+ * is still this run's.
120
+ */
121
+ export function acquireDailyLock(graphRoot, now, options = {}) {
122
+ const file = graphPath(graphRoot, LOCK_FILE);
123
+ fs.mkdirSync(path.dirname(file), { recursive: true });
124
+ const clock = options.clock ?? Date.now;
125
+ const mine = { pid: process.pid, at: now.toISOString() };
126
+ const body = JSON.stringify(mine);
127
+ const release = () => {
128
+ releaseLockFile(file, {
129
+ read: (lockPath) => readLockFile(lockPath, parseDailyLockOwner),
130
+ owns: (owner) => owner.pid === mine.pid && owner.at === mine.at,
131
+ remove: (lockPath) => fs.rmSync(lockPath, { force: true }),
132
+ });
133
+ };
134
+ if (createLockFile(file, body))
135
+ return release;
136
+ const maxAgeMs = options.force ? LOCK_FORCE_AGE_MS : LOCK_MAX_AGE_MS;
137
+ const stale = () => {
138
+ const owner = readLockFile(file, parseDailyLockOwner);
139
+ if (lockIsStale({ kind: "pid", alive: processAlive, self: process.pid }, { owner }))
140
+ return true;
141
+ // The owner's process id is alive. Past the age limit that process is not the run that wrote the lock.
142
+ return owner !== null && lockIsStale({ kind: "age", maxAgeMs }, { ageMs: now.getTime() - Date.parse(owner.at) });
143
+ };
144
+ if (!stale())
145
+ return null;
146
+ // Only the holder of the takeover file may replace a stale lock.
147
+ const takeover = `${file}.takeover`;
148
+ if (!createLockFile(takeover, String(process.pid))) {
149
+ // Another run is replacing the lock right now. A takeover file that was left behind is cleared for the next run.
150
+ if (takeoverIsStale(takeover, clock))
151
+ fs.rmSync(takeover, { force: true });
152
+ return null;
153
+ }
154
+ try {
155
+ // Judged again now that nobody else can replace it: another run may have taken the lock in between.
156
+ if (!stale())
157
+ return null;
158
+ fs.rmSync(file, { force: true });
159
+ return createLockFile(file, body) ? release : null;
160
+ }
161
+ finally {
162
+ fs.rmSync(takeover, { force: true });
163
+ }
164
+ }
165
+ /**
166
+ * Hash of every input dated in the last CHANGE_WINDOW_DAYS: kind, day, path,
167
+ * size and modified time. A new or edited signal, source, document or thread
168
+ * changes it; the graph's own files do not. Null when the readers cannot be
169
+ * created (no member identity, replay not available), which means "run".
170
+ */
171
+ export async function inputFingerprint(context, today, given) {
172
+ try {
173
+ // The listing the last run kept answers for every unchanged file, so this opens only what is new.
174
+ const readers = given ?? (await import("../replay/index.js")).createInputReaders(context, { incremental: true });
175
+ const hash = createHash("sha256");
176
+ const from = shiftDay(today, -CHANGE_WINDOW_DAYS);
177
+ for (const kind of Object.keys(readers).sort()) {
178
+ const reader = readers[kind];
179
+ if (!reader)
180
+ continue;
181
+ for (const day of reader.listDays({ from })) {
182
+ for (const input of reader.list(day)) {
183
+ let stamp = "";
184
+ if (input.path) {
185
+ try {
186
+ const stat = fs.statSync(input.path);
187
+ stamp = `${stat.size}:${Math.floor(stat.mtimeMs)}`;
188
+ }
189
+ catch {
190
+ stamp = "missing";
191
+ }
192
+ }
193
+ hash.update(`${kind}\u0000${day}\u0000${input.relPath}\u0000${input.ref}\u0000${stamp}\n`);
194
+ }
195
+ }
196
+ }
197
+ return hash.digest("hex");
198
+ }
199
+ catch {
200
+ return null;
201
+ }
202
+ }
203
+ async function defaultDeps() {
204
+ return {
205
+ // The update's own closing lint is switched off: the next step runs it.
206
+ update: async (context, options) => (await import("../replay/index.js")).runUpdate(context, options, { runLint: null }),
207
+ lint: async (context, options) => (await import("./index.js")).runLint(context, options),
208
+ brief: async (context, options) => (await import("../read/index.js")).briefCommand(context, options),
209
+ fingerprint: inputFingerprint,
210
+ };
211
+ }
212
+ /**
213
+ * One daily run: update, lint, brief. Idempotent: a second run on unchanged
214
+ * inputs does nothing and writes nothing. Never throws for a failed step; the
215
+ * result says `failed` and the state file keeps the error.
216
+ */
217
+ export async function runDaily(context, options = {}) {
218
+ const now = options.now ?? new Date();
219
+ const started = Date.now();
220
+ const day = localDay(now);
221
+ const deps = { ...(await defaultDeps()), ...(options.deps ?? {}) };
222
+ const budget = options.budgetTokens ?? DAILY_BUDGET_TOKENS;
223
+ const before = readDailyState(context.graphRoot);
224
+ const spentToday = before?.day === day ? before.tokensToday : 0;
225
+ const budgetLeft = Math.max(0, budget - spentToday);
226
+ const outputToday = before?.day === day ? (before.outputTokensToday ?? 0) : 0;
227
+ const base = { day, budgetLeft, tokensUsed: 0, outputTokensUsed: 0, briefWritten: false };
228
+ const elapsed = () => Math.round((Date.now() - started) / 10) / 100;
229
+ claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
230
+ const release = acquireDailyLock(context.graphRoot, now, { ...(options.force ? { force: true } : {}) });
231
+ if (!release)
232
+ return { ...base, status: "busy", reason: "another daily run holds the lock", seconds: elapsed() };
233
+ try {
234
+ const fingerprint = await deps.fingerprint(context, day);
235
+ if (!options.force && fingerprint !== null && before?.status === "ran" && before.fingerprint === fingerprint) {
236
+ return { ...base, status: "skipped", reason: `no input changed since ${before.lastRunAt}`, seconds: elapsed() };
237
+ }
238
+ let tokensUsed = 0;
239
+ let outputTokensUsed = 0;
240
+ try {
241
+ // With nothing left of the day's budget the update still runs its rules; a budget of 1 token stops every model call.
242
+ const update = await deps.update(context, { budgetTokens: Math.max(1, budgetLeft), dryRun: false });
243
+ tokensUsed = update.totals.inputTokens;
244
+ outputTokensUsed = update.totals.outputTokens;
245
+ // The whole graph is linted once a week (and on --force). On the other days only what the update
246
+ // touched is checked: the full lint reads every facts file and every page.
247
+ const touched = update.touched;
248
+ const lastFull = before?.lastFullLintDay;
249
+ const fullLint = options.force === true || touched === undefined || !lastFull || shiftDay(lastFull, FULL_LINT_EVERY_DAYS) <= day;
250
+ const lint = await deps.lint(context, { fileProposals: true, ...(fullLint ? {} : { entities: touched }) });
251
+ await deps.brief(context, { stdout: false });
252
+ const warnings = lint.findings.length - lint.errors;
253
+ writeDailyState(context.graphRoot, {
254
+ day,
255
+ lastRunAt: now.toISOString(),
256
+ status: "ran",
257
+ fingerprint,
258
+ lastFullLintDay: fullLint ? day : lastFull,
259
+ tokensToday: spentToday + tokensUsed,
260
+ outputTokensToday: outputToday + outputTokensUsed,
261
+ run: update.run,
262
+ rowsAdded: update.totals.rowsAdded,
263
+ lintErrors: lint.errors,
264
+ lintWarnings: warnings,
265
+ proposalsFiled: lint.proposalsFiled,
266
+ seconds: elapsed(),
267
+ });
268
+ return {
269
+ ...base,
270
+ status: "ran",
271
+ tokensUsed,
272
+ outputTokensUsed,
273
+ update: {
274
+ run: update.run,
275
+ days: update.days,
276
+ partial: update.partial,
277
+ ...(update.stoppedBecause ? { stoppedBecause: update.stoppedBecause } : {}),
278
+ rowsAdded: update.totals.rowsAdded,
279
+ rowsClosed: update.totals.rowsClosed,
280
+ pending: update.totals.pending,
281
+ },
282
+ lint: { errors: lint.errors, warnings, proposalsFiled: lint.proposalsFiled, scope: fullLint ? "all" : "touched" },
283
+ briefWritten: true,
284
+ seconds: elapsed(),
285
+ };
286
+ }
287
+ catch (error) {
288
+ const message = error instanceof Error ? error.message : String(error);
289
+ // Keep the last good fingerprint out of the state, so the next run does not skip.
290
+ writeDailyState(context.graphRoot, {
291
+ day,
292
+ lastRunAt: now.toISOString(),
293
+ status: "failed",
294
+ fingerprint: null,
295
+ tokensToday: spentToday + tokensUsed,
296
+ outputTokensToday: outputToday + outputTokensUsed,
297
+ seconds: elapsed(),
298
+ error: message,
299
+ });
300
+ return { ...base, status: "failed", tokensUsed, outputTokensUsed, error: message, seconds: elapsed() };
301
+ }
302
+ }
303
+ finally {
304
+ release();
305
+ }
306
+ }
307
+ /** `hq ontology daily [--force] [--budget-tokens N]`. Exit code 1 when a step failed. */
308
+ export async function dailyCommand(context, options = {}) {
309
+ const result = await runDaily(context, options);
310
+ const head = `Ontology daily run for ${context.company}: ${result.status}`;
311
+ const lines = [];
312
+ if (result.status === "ran") {
313
+ lines.push(`${head}.`, `Update: ${result.update?.days ?? 0} day${result.update?.days === 1 ? "" : "s"}, rows +${result.update?.rowsAdded ?? 0} closed ${result.update?.rowsClosed ?? 0}; model input tokens ${result.tokensUsed} of the ${result.budgetLeft} left today${result.update?.pending ? `; ${result.update.pending} model call${result.update.pending === 1 ? "" : "s"} held for tomorrow` : ""}.`, `Lint: ${result.lint?.errors ?? 0} errors, ${result.lint?.warnings ?? 0} warnings, ${result.lint?.proposalsFiled ?? 0} new proposals.`, "Brief written.");
314
+ if (result.update?.partial)
315
+ lines.push(`The update stopped early: ${result.update.stoppedBecause ?? "no reason given"}.`);
316
+ }
317
+ else if (result.status === "failed") {
318
+ lines.push(`${head}: ${result.error ?? "unknown error"}`);
319
+ }
320
+ else {
321
+ lines.push(`${head}: ${result.reason ?? ""}`.trim());
322
+ }
323
+ return { text: lines.join("\n"), json: result, ...(result.status === "failed" ? { exitCode: 1 } : {}) };
324
+ }
325
+ // ---------------------------------------------------------------------------
326
+ // The scheduled job (HQ Fleet Runtime cron, on the member's Executive bot)
327
+ // ---------------------------------------------------------------------------
328
+ export const ONTOLOGY_DAILY_JOB_NAME = "ontology-daily";
329
+ /** 07:10 local: after the 06:30 signals run, so the day's new signals are in. */
330
+ export const ONTOLOGY_DAILY_SCHEDULE = "10 7 * * *";
331
+ /** The script gives the run this long before it stops it. */
332
+ export const ONTOLOGY_DAILY_TIMEOUT_SECONDS = 45 * 60;
333
+ export function ontologyDailyScriptName(company) {
334
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(company))
335
+ throw new Error(`ontology daily job: not a company slug: ${company}`);
336
+ return `ontology-daily-${company}.py`;
337
+ }
338
+ export class DailyJobError extends Error {
339
+ constructor(message) {
340
+ super(message);
341
+ this.name = "DailyJobError";
342
+ }
343
+ }
344
+ async function executiveTarget() {
345
+ const { resolveExecutiveBot } = await import("../../bot/executive.js");
346
+ const bot = resolveExecutiveBot();
347
+ if (!bot)
348
+ return null;
349
+ const { fleetCronOps, fleetOwnerOrigin, fleetPnpmHqLauncher } = await import("../../bot/fleet-cron.js");
350
+ const { fleetLocalProfileDir } = await import("../../bot/fleet-local.js");
351
+ const { resolveHqBinary, resolveNodeBinary } = await import("../../mesh/live/daemon/install.js");
352
+ const hqBinary = resolveHqBinary();
353
+ const ops = fleetCronOps(bot.config.agentUid);
354
+ return {
355
+ botName: bot.name,
356
+ botDir: bot.dir,
357
+ agentUid: bot.config.agentUid,
358
+ ownerUid: bot.config.ownerUid,
359
+ profileDir: fleetLocalProfileDir(bot.config.agentUid),
360
+ ops: ops,
361
+ origin: (jobs) => fleetOwnerOrigin(bot.config.ownerUid, jobs),
362
+ nodeBinary: resolveNodeBinary(),
363
+ hqBinary,
364
+ launcher: fleetPnpmHqLauncher(hqBinary),
365
+ };
366
+ }
367
+ const NO_BOT = "There is no personal bot on this computer. The daily ontology job runs in the HQ Fleet Runtime of your Executive bot, " +
368
+ "the same place the 06:30 signals run lives. Create one with: hq bot create assistant. " +
369
+ "Until then, run it by hand: hq ontology daily --company <slug>";
370
+ async function target(deps) {
371
+ const found = await (deps.resolveTarget ?? executiveTarget)();
372
+ if (!found)
373
+ throw new DailyJobError(NO_BOT);
374
+ return found;
375
+ }
376
+ /** `HH:MM` (24 hour, local) to a daily cron expression. */
377
+ export function dailyCronAt(at) {
378
+ const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(at.trim());
379
+ if (!match)
380
+ throw new DailyJobError(`not a time of day: "${at}". Use HH:MM, 24 hour, for example 07:10`);
381
+ return `${Number(match[2])} ${Number(match[1])} * * *`;
382
+ }
383
+ /**
384
+ * The Python the Fleet runtime runs. It appends the run's output to the log
385
+ * and prints nothing unless the run failed. Finding `hq` follows the signals
386
+ * job: the entry this CLI was started from, then the stable pnpm launcher,
387
+ * then PATH. When the installed `hq` answers "unknown command" for
388
+ * `ontology daily` (an older CLI), it runs update, lint and brief one by one.
389
+ */
390
+ export function renderOntologyDailyScript(input) {
391
+ const failed = `The daily ontology update for ${input.company} did not finish: `;
392
+ return [
393
+ "import os, shutil, subprocess, sys, time",
394
+ `NODE = ${JSON.stringify(input.nodeBinary)}`,
395
+ `HQ = ${JSON.stringify(input.hqBinary)}`,
396
+ `LAUNCHER = ${JSON.stringify(input.launcher)}`,
397
+ `ARGS = ${JSON.stringify([...input.args])}`,
398
+ `STEPS = ${JSON.stringify(input.steps.map((step) => [...step]))}`,
399
+ `LOG = ${JSON.stringify(input.logFile)}`,
400
+ `CWD = ${JSON.stringify(input.hqRoot)}`,
401
+ `TIMEOUT = ${Math.floor(input.timeoutSeconds)}`,
402
+ "STARTED = time.localtime()",
403
+ "def hq_argv():",
404
+ " if os.path.isfile(HQ):",
405
+ " return [NODE, HQ]",
406
+ " if LAUNCHER and os.path.isfile(LAUNCHER):",
407
+ " return [LAUNCHER]",
408
+ " found = shutil.which('hq')",
409
+ " if found:",
410
+ " return [found]",
411
+ " home = os.path.expanduser('~')",
412
+ " for rel in ('Library/pnpm/bin/hq', '.local/share/pnpm/hq'):",
413
+ " p = os.path.join(home, rel)",
414
+ " if os.path.isfile(p):",
415
+ " return [p]",
416
+ " raise FileNotFoundError(HQ)",
417
+ "def alert(reason):",
418
+ ` sys.stdout.write(${JSON.stringify(failed)} + reason + '.\\n')`,
419
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
420
+ "def run(log, args, seconds):",
421
+ " result = subprocess.run(hq_argv() + args, stdout=log, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, cwd=CWD, timeout=max(1, seconds), encoding='utf-8', errors='replace')",
422
+ " log.write(result.stderr)",
423
+ " log.flush()",
424
+ " return result.returncode, result.stderr",
425
+ "try:",
426
+ " os.makedirs(os.path.dirname(LOG), exist_ok=True)",
427
+ " with open(LOG, 'a', encoding='utf-8') as log:",
428
+ " log.write('--- ontology-daily ' + time.strftime('%Y-%m-%d %H:%M:%S', STARTED) + '\\n')",
429
+ " log.flush()",
430
+ " deadline = time.time() + TIMEOUT",
431
+ " try:",
432
+ " code, err = run(log, ARGS, TIMEOUT)",
433
+ " if code != 0 and 'unknown command' in err:",
434
+ " log.write('--- this hq has no ontology daily command; running update, lint and brief one by one\\n')",
435
+ " for step in STEPS:",
436
+ " code, err = run(log, step, deadline - time.time())",
437
+ " if code != 0:",
438
+ " break",
439
+ " except subprocess.TimeoutExpired:",
440
+ " code = None",
441
+ " log.write('--- end ' + ('timeout' if code is None else 'exit %d' % code) + '\\n')",
442
+ " if code is None:",
443
+ " alert('it ran longer than %d minutes and was stopped' % (TIMEOUT // 60))",
444
+ " sys.exit(124)",
445
+ " if code != 0:",
446
+ " alert('exit %d' % code)",
447
+ " sys.exit(code if code > 0 else 1)",
448
+ "except OSError as exc:",
449
+ " alert('hq could not be started (' + type(exc).__name__ + ')')",
450
+ " sys.exit(127)",
451
+ "",
452
+ ].join("\n");
453
+ }
454
+ /**
455
+ * The flags every command of the job carries. With no `--member` given at
456
+ * install time none is written: each run then builds for whoever is signed in
457
+ * to the CLI on this machine, found the way `hq whoami` finds them
458
+ * (correction C5), so a member never types their own id.
459
+ */
460
+ function scopeArgs(context) {
461
+ return [
462
+ "--company",
463
+ context.company,
464
+ "--hq-root",
465
+ context.hqRoot,
466
+ ...(context.member
467
+ ? ["--member", context.member.personUid, ...context.member.audienceKeys.flatMap((key) => ["--audience-key", key])]
468
+ : []),
469
+ ];
470
+ }
471
+ /** The arguments the script passes to `hq`: the daily run for this company. */
472
+ export function dailyArgs(context, budgetTokens) {
473
+ return ["ontology", "daily", ...scopeArgs(context), ...(budgetTokens !== undefined ? ["--budget-tokens", String(budgetTokens)] : [])];
474
+ }
475
+ /** The same work as the three commands every `hq ontology` has. No shared day budget and no change check. */
476
+ export function dailySteps(context, budgetTokens) {
477
+ const scope = scopeArgs(context);
478
+ return [
479
+ ["ontology", "update", ...scope, "--budget-tokens", String(budgetTokens ?? DAILY_BUDGET_TOKENS)],
480
+ ["ontology", "lint", ...scope],
481
+ ["ontology", "brief", ...scope],
482
+ ];
483
+ }
484
+ function ownJobs(jobs, scriptName) {
485
+ return jobs.filter((job) => job.name === ONTOLOGY_DAILY_JOB_NAME && typeof job.script === "string" && path.basename(job.script) === scriptName);
486
+ }
487
+ /**
488
+ * Registers the daily job for this company on the member's Executive bot.
489
+ * Idempotent: the script is rewritten every time, the job is created once, and
490
+ * a different `--at` moves the existing job instead of adding a second one.
491
+ */
492
+ export async function installDailyJob(context, options = {}) {
493
+ const args = dailyArgs(context, options.budgetTokens);
494
+ const schedule = options.at ? dailyCronAt(options.at) : ONTOLOGY_DAILY_SCHEDULE;
495
+ const where = await target(options.deps ?? {});
496
+ const scriptName = ontologyDailyScriptName(context.company);
497
+ const scriptFile = path.join(where.profileDir, "scripts", scriptName);
498
+ const logFile = path.join(where.botDir, "logs", "ontology-daily.log");
499
+ fs.mkdirSync(path.dirname(scriptFile), { recursive: true, mode: 0o700 });
500
+ fs.mkdirSync(path.dirname(logFile), { recursive: true, mode: 0o700 });
501
+ const temporary = `${scriptFile}.${process.pid}.tmp`;
502
+ fs.writeFileSync(temporary, renderOntologyDailyScript({
503
+ company: context.company,
504
+ hqRoot: context.hqRoot,
505
+ nodeBinary: where.nodeBinary,
506
+ hqBinary: where.hqBinary,
507
+ launcher: where.launcher,
508
+ logFile,
509
+ args,
510
+ steps: dailySteps(context, options.budgetTokens),
511
+ timeoutSeconds: ONTOLOGY_DAILY_TIMEOUT_SECONDS,
512
+ }), { mode: 0o600 });
513
+ fs.renameSync(temporary, scriptFile);
514
+ const jobs = where.ops.list();
515
+ const [current, ...extra] = ownJobs(jobs, scriptName);
516
+ for (const job of extra)
517
+ where.ops.remove(job.id);
518
+ if (current) {
519
+ const moved = options.at !== undefined && current.schedule?.expr !== schedule;
520
+ const job = moved ? (where.ops.reschedule(current.id, schedule) ?? current) : current;
521
+ return { bot: where.botName, job, created: false, rescheduled: moved, schedule: moved ? schedule : (current.schedule?.expr ?? schedule), scriptFile, logFile };
522
+ }
523
+ const job = where.ops.create({
524
+ name: ONTOLOGY_DAILY_JOB_NAME,
525
+ prompt: `Run the daily ontology update for ${context.company} and post to the owner only when it fails.`,
526
+ schedule,
527
+ script: scriptName,
528
+ noAgent: true,
529
+ origin: where.origin(jobs),
530
+ workdir: context.hqRoot,
531
+ });
532
+ return { bot: where.botName, job, created: true, rescheduled: false, schedule, scriptFile, logFile };
533
+ }
534
+ /** Removes the job and its script. Idempotent. The graph folder and the log are left alone. */
535
+ export async function uninstallDailyJob(context, options = {}) {
536
+ const where = await target(options.deps ?? {});
537
+ const scriptName = ontologyDailyScriptName(context.company);
538
+ const removed = [];
539
+ for (const job of ownJobs(where.ops.list(), scriptName)) {
540
+ if (where.ops.remove(job.id))
541
+ removed.push(job.id);
542
+ }
543
+ const scriptFile = path.join(where.profileDir, "scripts", scriptName);
544
+ const scriptRemoved = fs.existsSync(scriptFile);
545
+ fs.rmSync(scriptFile, { force: true });
546
+ return { bot: where.botName, removed, scriptRemoved };
547
+ }
548
+ export async function dailyJobStatus(context, options = {}) {
549
+ const lastRun = readDailyState(context.graphRoot);
550
+ const where = await (options.deps?.resolveTarget ?? executiveTarget)();
551
+ if (!where)
552
+ return { bot: null, installed: false, job: null, lastRun };
553
+ const [job] = ownJobs(where.ops.list(), ontologyDailyScriptName(context.company));
554
+ return { bot: where.botName, installed: job !== undefined, job: job ?? null, lastRun };
555
+ }
556
+ /** `hq ontology job install [--at HH:MM] [--budget-tokens N]`. */
557
+ export async function jobInstallCommand(context, options = {}) {
558
+ const result = await installDailyJob(context, options);
559
+ const what = result.created ? "Registered" : result.rescheduled ? "Moved" : "Already registered:";
560
+ return {
561
+ text: [
562
+ `${what} the daily ontology job for ${context.company} on ${result.bot} (cron ${result.schedule}, local time).`,
563
+ `It runs: hq ontology daily --company ${context.company} (update, lint, brief). It skips when no input changed.`,
564
+ `Log: ${result.logFile}`,
565
+ `Remove it: hq ontology job uninstall --company ${context.company}`,
566
+ ].join("\n"),
567
+ json: result,
568
+ };
569
+ }
570
+ /** `hq ontology job uninstall`. */
571
+ export async function jobUninstallCommand(context, options = {}) {
572
+ const result = await uninstallDailyJob(context, options);
573
+ return {
574
+ text: result.removed.length > 0 || result.scriptRemoved
575
+ ? `Removed the daily ontology job for ${context.company} from ${result.bot}. The graph folder is untouched.`
576
+ : `No daily ontology job for ${context.company} on ${result.bot}. Nothing to remove.`,
577
+ json: result,
578
+ };
579
+ }
580
+ /** `hq ontology job status`. */
581
+ export async function jobStatusCommand(context, options = {}) {
582
+ const status = await dailyJobStatus(context, options);
583
+ const lines = [
584
+ status.bot === null
585
+ ? "No personal bot on this computer, so no daily job can be scheduled."
586
+ : status.installed
587
+ ? `The daily ontology job for ${context.company} is registered on ${status.bot} (cron ${status.job?.schedule?.expr ?? "unknown"}).`
588
+ : `No daily ontology job for ${context.company} on ${status.bot}. Add it: hq ontology job install --company ${context.company}`,
589
+ status.lastRun
590
+ ? `Last run: ${status.lastRun.lastRunAt}, ${status.lastRun.status}, model input tokens that day ${status.lastRun.tokensToday}.`
591
+ : "It has not run yet.",
592
+ ];
593
+ return { text: lines.join("\n"), json: status };
594
+ }
595
+ //# sourceMappingURL=daily-job.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * WP-F entry points: lint (design 2.6).
3
+ *
4
+ * hq ontology lint [--no-proposals] [--strict] [--json]
5
+ * hq ontology lint --coverage [--json] the org-coverage measures only (coverage.ts); writes nothing
6
+ *
7
+ * Model-free. Prints a count for every class and the findings row by row
8
+ * (`--json` has all of them). The exit code is 0 unless `--strict` is given:
9
+ * with `--strict` it is 1 when any error-class finding exists (a row without a
10
+ * source, a line that does not parse, a verb or field outside the schema, a
11
+ * dead link, an audience leak, a Slack-id person, a conflict copy). Warning
12
+ * classes never change the exit code.
13
+ *
14
+ * With proposals on (the default) each fixable finding is filed once in
15
+ * `proposals/open.jsonl`, and the run is noted in `log.md` and the ledger.
16
+ * After filing, pair proposals between name variants of one outside person at
17
+ * one company are folded into one proposal per person (proposals/group.ts).
18
+ * `--no-proposals` writes nothing at all.
19
+ */
20
+ import type { CommandOutput, GraphContext, IsoDate, LintOptions, LintReport } from "../types.js";
21
+ export { UNINFORMATIVE_STAGES, coverageCommand, lastMonths, measureCoverage, renderCoverage, runCoverage } from "./coverage.js";
22
+ export type { CoverageOptions, CoverageReport, CoverageShare } from "./coverage.js";
23
+ export { CLOSED_STATUS_VALUES, EXTRA_LINT_KINDS, LINT_CLASSES, STALE_AGE_DAYS, closedEntities, runChecks, scanGraph, sourceScope, } from "./checks.js";
24
+ export type { CheckOptions, Found, GraphLintKind, GraphScan, LintClass, ScannedRow } from "./checks.js";
25
+ /** Environment switch for `--strict`, for callers that cannot pass the flag. */
26
+ export declare const LINT_STRICT_ENV = "HQ_ONTOLOGY_LINT_STRICT";
27
+ export interface GraphLintOptions extends LintOptions {
28
+ /** Exit 1 when an error-class finding exists. Default false: lint never fails a run. */
29
+ strict?: boolean;
30
+ /** Default: the clock. */
31
+ now?: Date;
32
+ /** Overrides for `STALE_AGE_DAYS`, same keys. */
33
+ staleAgeDays?: Readonly<Record<string, number | null>>;
34
+ /** Most proposals filed per class in one run. Default 200. */
35
+ maxProposalsPerKind?: number;
36
+ /** Print the org-coverage measures instead of the findings (`--coverage`). Nothing is filed or written. */
37
+ coverage?: boolean;
38
+ }
39
+ /** `LintReport` plus what the contract type has no field for. */
40
+ export interface GraphLintReport extends LintReport {
41
+ graphRoot: string;
42
+ day: IsoDate;
43
+ /** Entities read. On a scoped run, the ones asked for that exist. */
44
+ entities: number;
45
+ /** `touched`: only `options.entities` were checked. `all`: the whole graph. */
46
+ scope: "all" | "touched";
47
+ rows: number;
48
+ audiences: string[];
49
+ /** Warning-class findings. `errors` counts the error-class ones. */
50
+ warnings: number;
51
+ /** Findings left out because a member answered "nope" to their proposal. */
52
+ declined: number;
53
+ /** Fixable findings whose proposal was held back by `maxProposalsPerKind`. */
54
+ proposalsHeld: number;
55
+ openProposals: number;
56
+ /** Name-variant groups filed by this run, and the pair proposals they took the place of. */
57
+ nameVariantGroups: number;
58
+ nameVariantPairsReplaced: number;
59
+ seconds: number;
60
+ }
61
+ /** Model-free. Runs at the end of every update. */
62
+ export declare function runLint(context: GraphContext, options: GraphLintOptions): Promise<GraphLintReport>;
63
+ /** `hq ontology lint`: a count per class and the findings; exit code 1 only with `--strict` and an error-class finding. */
64
+ export declare function lintCommand(context: GraphContext, options: GraphLintOptions): Promise<CommandOutput>;
65
+ //# sourceMappingURL=index.d.ts.map