@indigoai-us/hq-cli 5.345.250 → 5.345.251

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 (57) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/contracts/host-canary-release.json +3 -3
  3. package/dist/command-catalog.generated.d.ts +195 -1
  4. package/dist/command-catalog.generated.js +241 -1
  5. package/dist/commands/bot.js +5 -1
  6. package/dist/commands/lanes.d.ts +2 -0
  7. package/dist/commands/lanes.js +9 -4
  8. package/dist/commands/ontology-graph.d.ts +9 -2
  9. package/dist/commands/ontology-graph.js +97 -4
  10. package/dist/commands/sources.js +26 -8
  11. package/dist/lib/bot/fleet-cron.d.ts +2 -0
  12. package/dist/lib/bot/fleet-cron.js +5 -0
  13. package/dist/lib/hook-engine/coverage.d.ts +18 -7
  14. package/dist/lib/hook-engine/coverage.js +58 -20
  15. package/dist/lib/hook-engine/native-stop-compatibility.json +9 -4
  16. package/dist/lib/hot-channels/graph-context.d.ts +26 -1
  17. package/dist/lib/hot-channels/graph-context.js +76 -9
  18. package/dist/lib/hot-channels/run.d.ts +1 -0
  19. package/dist/lib/hot-channels/signals-pass.js +9 -4
  20. package/dist/lib/ontology-graph/model/files.d.ts +4 -0
  21. package/dist/lib/ontology-graph/model/files.js +23 -0
  22. package/dist/lib/ontology-graph/model/index.d.ts +11 -1
  23. package/dist/lib/ontology-graph/model/index.js +42 -18
  24. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +9 -1
  25. package/dist/lib/ontology-graph/model/pass-tasks.js +7 -4
  26. package/dist/lib/ontology-graph/model/pass.d.ts +5 -0
  27. package/dist/lib/ontology-graph/model/pass.js +8 -8
  28. package/dist/lib/ontology-graph/model/pending-items.d.ts +31 -0
  29. package/dist/lib/ontology-graph/model/pending-items.js +113 -0
  30. package/dist/lib/ontology-graph/model/step.d.ts +46 -1
  31. package/dist/lib/ontology-graph/model/step.js +202 -36
  32. package/dist/lib/ontology-graph/model/tasks.d.ts +17 -1
  33. package/dist/lib/ontology-graph/model/tasks.js +28 -8
  34. package/dist/lib/ontology-graph/pages/render.d.ts +1 -1
  35. package/dist/lib/ontology-graph/pages/render.js +4 -3
  36. package/dist/lib/ontology-graph/read/brief.d.ts +13 -3
  37. package/dist/lib/ontology-graph/read/brief.js +311 -64
  38. package/dist/lib/ontology-graph/read/index.d.ts +1 -1
  39. package/dist/lib/ontology-graph/read/index.js +1 -1
  40. package/dist/lib/ontology-graph/read/reader-setting.d.ts +2 -0
  41. package/dist/lib/ontology-graph/read/reader-setting.js +4 -1
  42. package/dist/lib/ontology-graph/remodel/index.d.ts +174 -0
  43. package/dist/lib/ontology-graph/remodel/index.js +450 -0
  44. package/dist/lib/ontology-graph/replay/index.js +113 -7
  45. package/dist/lib/ontology-graph/schema/authority.d.ts +14 -5
  46. package/dist/lib/ontology-graph/schema/authority.js +13 -3
  47. package/dist/lib/ontology-graph/schema/index.d.ts +1 -1
  48. package/dist/lib/ontology-graph/schema/index.js +1 -1
  49. package/dist/lib/ontology-graph/setup/index.d.ts +88 -0
  50. package/dist/lib/ontology-graph/setup/index.js +489 -0
  51. package/dist/lib/ontology-graph/types.d.ts +21 -0
  52. package/dist/lib/ontology-graph/types.js +5 -0
  53. package/dist/lib/signals/failure-alert.js +4 -5
  54. package/dist/lib/signals/steps/adapters.js +3 -0
  55. package/dist/utils/sync-person.d.ts +15 -0
  56. package/dist/utils/sync-person.js +74 -0
  57. package/package.json +7 -7
@@ -0,0 +1,489 @@
1
+ /**
2
+ * Setup commands: the two settings a member used to write by hand, and one
3
+ * screen that says what state this machine is in.
4
+ *
5
+ * hq ontology reader [graph|entities] --company <slug>
6
+ * hq ontology model [<model>] --company <slug>
7
+ * hq ontology status --company <slug>
8
+ *
9
+ * `reader` shows or sets `personal/settings/ontology-reader.yaml` (see
10
+ * read/reader-setting.ts). `model` shows or sets `model:` in the company's
11
+ * `settings/ontology.yaml` (see `resolveModel` in model/index.ts). `status`
12
+ * reads and writes nothing.
13
+ *
14
+ * None of the three opens a graph folder for reading rows through the store,
15
+ * and none stamps one. `reader graph` is refused unless the company's own
16
+ * graph folder exists and is stamped for that company, so a session is never
17
+ * pointed at a graph that is missing or is another company's. The isolation,
18
+ * audience and stamp rules of the other commands are unchanged.
19
+ */
20
+ import * as fs from "node:fs";
21
+ import * as path from "node:path";
22
+ import yaml from "js-yaml";
23
+ import { MODEL_STATE_PATHS, ONTOLOGY_MODEL_ENV, ONTOLOGY_SETTINGS_FILE, estimateTokens, isOntologyModelName, peekPendingMarkers, readModelSetting, resolveModelStateDir } from "../model/index.js";
24
+ import { DEFAULT_ONTOLOGY_MODEL } from "../model/runner.js";
25
+ import { graphExists } from "../read/graph-index.js";
26
+ import { READER_SETTING_RELATIVE, parseReaderSetting, readReaderSetting, readerSettingFile } from "../read/reader-setting.js";
27
+ import { GRAPH_PATHS, GRAPH_ROOT_RELATIVE, defaultGraphRoot, graphPath, readGraphCompany } from "../store/paths.js";
28
+ import { GRAPH_ENTITY_TYPES } from "../types.js";
29
+ /** A request the command refuses. The command file turns it into a usage error. */
30
+ export class OntologySetupError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "OntologySetupError";
34
+ }
35
+ }
36
+ /** The reader file is read by the session hook with shell builtins and by `readReaderSetting`, which ignores a file over this size. */
37
+ const MAX_READER_SETTING_BYTES = 4096;
38
+ const MAX_MODEL_SETTING_BYTES = 64 * 1024;
39
+ const NEW_READER_FILE_HEADER = [
40
+ "# Which ontology this machine reads. Written by `hq ontology reader`.",
41
+ "# reader: entities the old entity files (companies/<co>/ontology/entities). Default.",
42
+ "# reader: graph the graph (companies/<co>/.hq/ontology-graph).",
43
+ "# One \"key: value\" per line. Any value other than \"graph\", or no file, means the old reader.",
44
+ ];
45
+ const NEW_MODEL_FILE_HEADER = [
46
+ "# Model used by the ontology graph's model step for this company (rebuild, update, remodel).",
47
+ "# Written by `hq ontology model`. This file is per machine: settings/ is not synced.",
48
+ ];
49
+ function rel(hqRoot, file) {
50
+ const relative = path.relative(hqRoot, file);
51
+ return relative.startsWith("..") || path.isAbsolute(relative) ? file : relative.split(path.sep).join("/");
52
+ }
53
+ /** Temp file plus rename, in the same folder. */
54
+ function writeAtomic(file, text) {
55
+ fs.mkdirSync(path.dirname(file), { recursive: true });
56
+ const temp = `${file}.tmp-${String(process.pid)}-${String(Date.now())}`;
57
+ try {
58
+ fs.writeFileSync(temp, text, { flag: "wx" });
59
+ fs.renameSync(temp, file);
60
+ }
61
+ catch (error) {
62
+ fs.rmSync(temp, { force: true });
63
+ throw error;
64
+ }
65
+ }
66
+ /**
67
+ * The text of a settings file that a command may rewrite, or null when there
68
+ * is none. A symlink, a folder or a file over `maxBytes` is refused: the
69
+ * command writes only a plain file it can read whole.
70
+ */
71
+ function readOwnSettingFile(file, label, maxBytes) {
72
+ let stat;
73
+ try {
74
+ stat = fs.lstatSync(file);
75
+ }
76
+ catch (error) {
77
+ if (error.code === "ENOENT")
78
+ return null;
79
+ throw new OntologySetupError(`ontology: ${label} cannot be read (${error.code ?? "error"}); nothing was changed`);
80
+ }
81
+ if (!stat.isFile())
82
+ throw new OntologySetupError(`ontology: ${label} is not a plain file (a link or a folder); nothing was changed`);
83
+ if (stat.size > maxBytes)
84
+ throw new OntologySetupError(`ontology: ${label} is larger than ${String(maxBytes)} bytes; nothing was changed. Shorten it by hand and run again.`);
85
+ return fs.readFileSync(file, "utf8");
86
+ }
87
+ /** Says whether a graph folder exists and whose it says it is. Never throws and never writes. */
88
+ export function inspectGraphFolder(root, company) {
89
+ const present = graphExists(root);
90
+ if (!present)
91
+ return { root, present, stamp: null, state: "missing", detail: "no graph has been built here" };
92
+ let stamp;
93
+ try {
94
+ stamp = readGraphCompany(root);
95
+ }
96
+ catch (error) {
97
+ return { root, present, stamp: null, state: "unreadable", detail: error.message.replace(/^ontology graph: /, "") };
98
+ }
99
+ if (stamp === null)
100
+ return { root, present, stamp, state: "unstamped", detail: "the folder holds a graph and says no company" };
101
+ if (stamp !== company)
102
+ return { root, present, stamp, state: "other-company", detail: `the folder holds the graph of company ${stamp}` };
103
+ return { root, present, stamp, state: "ok", detail: `stamped for ${company}` };
104
+ }
105
+ /** The reader a session of this company gets: `graph` only when the one setting says graph for this company. */
106
+ function effectiveReader(setting, company) {
107
+ return setting.reader === "graph" && setting.company === company ? "graph" : "entities";
108
+ }
109
+ /**
110
+ * The setting text with `reader:` and `company:` set. Every other line is
111
+ * kept as it is (comments, `member:`). The first line of each key is
112
+ * replaced and a repeated one is dropped, so the two readers of the file
113
+ * (line by line in the shell hook, `parseReaderSetting` here) cannot disagree.
114
+ */
115
+ export function renderReaderSetting(existing, reader, company) {
116
+ const lines = existing === null ? [...NEW_READER_FILE_HEADER] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
117
+ const out = [];
118
+ const seen = { reader: false, company: false };
119
+ for (const line of lines) {
120
+ const key = /^(reader|company):/.exec(line)?.[1];
121
+ if (!key) {
122
+ out.push(line);
123
+ continue;
124
+ }
125
+ if (seen[key])
126
+ continue;
127
+ seen[key] = true;
128
+ out.push(key === "reader" ? `reader: ${reader}` : `company: ${company}`);
129
+ }
130
+ if (!seen.reader)
131
+ out.push(`reader: ${reader}`);
132
+ if (!seen.company)
133
+ out.push(`company: ${company}`);
134
+ return `${out.join("\n")}\n`;
135
+ }
136
+ function readerLines(context, setting, effective) {
137
+ const file = READER_SETTING_RELATIVE;
138
+ const lines = [`reader for ${context.company}: ${effective}`];
139
+ if (!setting.present)
140
+ lines.push(`setting: none (${file} is not there; the default is entities)`);
141
+ else if (setting.reader === "graph" && setting.company !== context.company) {
142
+ lines.push(`setting: graph for ${setting.company === "" ? "no company" : setting.company} (${file}); it does not apply to ${context.company}`);
143
+ }
144
+ else
145
+ lines.push(`setting: ${setting.reader}${setting.company ? ` for ${setting.company}` : ""} (${file})`);
146
+ return lines;
147
+ }
148
+ /** `hq ontology reader [graph|entities]`: show or set which ontology this machine's sessions read for the company. */
149
+ export async function readerCommand(context, options = {}) {
150
+ const file = readerSettingFile(context.hqRoot);
151
+ const before = readReaderSetting(context.hqRoot);
152
+ const was = effectiveReader(before, context.company);
153
+ const switchTo = (reader) => `hq ontology reader ${reader} --company ${context.company}`;
154
+ if (options.value === undefined) {
155
+ const lines = readerLines(context, before, was);
156
+ lines.push(was === "graph" ? `to switch back to the old files: ${switchTo("entities")}` : `to read the graph: ${switchTo("graph")}`);
157
+ return { text: lines.join("\n"), json: { company: context.company, reader: was, setting: { ...before, file: rel(context.hqRoot, file) }, changed: false } };
158
+ }
159
+ if (options.value !== "graph" && options.value !== "entities")
160
+ throw new OntologySetupError(`ontology: reader is graph or entities, not ${options.value}`);
161
+ const want = options.value;
162
+ if (want === "graph") {
163
+ // The sessions and the signals pass read the company's own folder, so that is the one checked.
164
+ const own = defaultGraphRoot(context.companyRoot);
165
+ const graph = inspectGraphFolder(own, context.company);
166
+ if (graph.state !== "ok") {
167
+ const where = `companies/${context.company}/${GRAPH_ROOT_RELATIVE}`;
168
+ const fix = graph.state === "missing"
169
+ ? `Build it first: hq ontology rebuild --company ${context.company}`
170
+ : graph.state === "unstamped"
171
+ ? `A build stamps it: hq ontology update --company ${context.company}`
172
+ : "It is not this company's graph and is not used.";
173
+ throw new OntologySetupError(`ontology: reader not set to graph: ${where}: ${graph.detail}. ${fix}`);
174
+ }
175
+ }
176
+ const base = { company: context.company, file: rel(context.hqRoot, file) };
177
+ if (want === was) {
178
+ // Already so. `entities` for a company the setting does not name leaves another company's setting alone.
179
+ const lines = [`reader for ${context.company}: ${want} (unchanged)`];
180
+ if (want === "entities" && before.reader === "graph" && before.company !== context.company) {
181
+ lines.push(`the setting says graph for ${before.company === "" ? "no company" : before.company} and was left as it is (${READER_SETTING_RELATIVE})`);
182
+ }
183
+ lines.push(want === "graph" ? `to switch back to the old files: ${switchTo("entities")}` : `to read the graph: ${switchTo("graph")}`);
184
+ return { text: lines.join("\n"), json: { ...base, reader: want, was, changed: false } };
185
+ }
186
+ const existing = readOwnSettingFile(file, READER_SETTING_RELATIVE, MAX_READER_SETTING_BYTES);
187
+ const text = renderReaderSetting(existing, want, context.company);
188
+ if (Buffer.byteLength(text) > MAX_READER_SETTING_BYTES)
189
+ throw new OntologySetupError(`ontology: ${READER_SETTING_RELATIVE} would be larger than ${String(MAX_READER_SETTING_BYTES)} bytes; nothing was changed`);
190
+ const check = parseReaderSetting(text);
191
+ if (check.reader !== want || check.company !== context.company)
192
+ throw new OntologySetupError(`ontology: ${READER_SETTING_RELATIVE} could not be rewritten safely; nothing was changed`);
193
+ writeAtomic(file, text);
194
+ const lines = [`reader for ${context.company}: ${want} (was ${was})`, `written: ${READER_SETTING_RELATIVE}`];
195
+ if (before.reader === "graph" && before.company !== "" && before.company !== context.company) {
196
+ lines.push(`the setting named ${before.company} before; one machine reads the graph of one company, so ${before.company} is back on the old files`);
197
+ if (before.member)
198
+ lines.push(`the member line (${before.member}) was kept; check that it is right for ${context.company}`);
199
+ }
200
+ if (want === "graph") {
201
+ lines.push("new sessions pick it up at start; this session is not changed");
202
+ lines.push(`to switch back to the old files: ${switchTo("entities")}`);
203
+ }
204
+ else {
205
+ lines.push("the graph folder is kept; nothing was deleted");
206
+ lines.push(`to read the graph again: ${switchTo("graph")}`);
207
+ }
208
+ return { text: lines.join("\n"), json: { ...base, reader: want, was, changed: true } };
209
+ }
210
+ function modelSettingFile(companyRoot) {
211
+ return path.join(companyRoot, ...ONTOLOGY_SETTINGS_FILE.split("/"));
212
+ }
213
+ /** The model the step would call on this machine and where that comes from. Reads only. */
214
+ export function readModelState(context, env = process.env) {
215
+ const setting = readModelSetting(context.companyRoot);
216
+ const rawEnv = env[ONTOLOGY_MODEL_ENV];
217
+ const fromEnv = isOntologyModelName(rawEnv) ? rawEnv.trim() : null;
218
+ if (fromEnv)
219
+ return { model: fromEnv, source: "env", setting, env: fromEnv };
220
+ if (setting)
221
+ return { model: setting, source: "setting", setting, env: null };
222
+ return { model: DEFAULT_ONTOLOGY_MODEL, source: "default", setting: null, env: null };
223
+ }
224
+ /**
225
+ * The settings text with the top-level `model:` set. Every other line is
226
+ * kept. A top-level `model:` wins over `ontology.model` when the step reads
227
+ * the file, so a file that only has the nested key gets the top-level one.
228
+ */
229
+ export function renderModelSetting(existing, model) {
230
+ const lines = existing === null ? [...NEW_MODEL_FILE_HEADER] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
231
+ const out = [];
232
+ let seen = false;
233
+ for (const line of lines) {
234
+ if (!/^model[ \t]*:/.test(line)) {
235
+ out.push(line);
236
+ continue;
237
+ }
238
+ if (seen)
239
+ continue;
240
+ seen = true;
241
+ out.push(`model: ${model}`);
242
+ }
243
+ if (!seen)
244
+ out.push(`model: ${model}`);
245
+ return `${out.join("\n")}\n`;
246
+ }
247
+ const PER_MACHINE_NOTE = "this setting is per machine: settings/ is not synced, so every teammate sets it on their own machine";
248
+ function sourceWords(state, company) {
249
+ if (state.source === "env")
250
+ return `from ${ONTOLOGY_MODEL_ENV} in this shell`;
251
+ if (state.source === "setting")
252
+ return `from companies/${company}/${ONTOLOGY_SETTINGS_FILE}`;
253
+ return `the default; companies/${company}/${ONTOLOGY_SETTINGS_FILE} names none`;
254
+ }
255
+ /** `hq ontology model [<model>]`: show or set the model the graph's model step calls for the company on this machine. */
256
+ export async function modelCommand(context, options = {}) {
257
+ const env = options.env ?? process.env;
258
+ const file = modelSettingFile(context.companyRoot);
259
+ const shown = `companies/${context.company}/${ONTOLOGY_SETTINGS_FILE}`;
260
+ const before = readModelState(context, env);
261
+ if (options.value === undefined) {
262
+ const lines = [`model for ${context.company}: ${before.model} (${sourceWords(before, context.company)})`];
263
+ if (before.source === "env" && before.setting)
264
+ lines.push(`setting: ${before.setting} (${shown}); ${ONTOLOGY_MODEL_ENV} wins over it in this shell`);
265
+ lines.push(PER_MACHINE_NOTE);
266
+ lines.push(`to set it: hq ontology model <model> --company ${context.company}`);
267
+ return { text: lines.join("\n"), json: { company: context.company, ...before, file: rel(context.hqRoot, file), perMachine: true, changed: false } };
268
+ }
269
+ const model = options.value.trim();
270
+ if (!isOntologyModelName(model)) {
271
+ throw new OntologySetupError("ontology: not a model name. Use a name the claude CLI takes, for example haiku, sonnet, opus or a full model id (letters, digits, dots, dashes and square brackets; 64 characters at most)");
272
+ }
273
+ const base = { company: context.company, file: rel(context.hqRoot, file), perMachine: true };
274
+ const envNote = before.env && before.env !== model ? `${ONTOLOGY_MODEL_ENV} is set to ${before.env} in this shell and wins over the setting until it is unset` : null;
275
+ if (before.setting === model) {
276
+ const lines = [`model for ${context.company}: ${model} (unchanged, ${shown})`, ...(envNote ? [envNote] : []), PER_MACHINE_NOTE];
277
+ return { text: lines.join("\n"), json: { ...base, model, was: before.setting, changed: false } };
278
+ }
279
+ const existing = readOwnSettingFile(file, shown, MAX_MODEL_SETTING_BYTES);
280
+ if (existing !== null) {
281
+ let parsed;
282
+ try {
283
+ parsed = yaml.load(existing);
284
+ }
285
+ catch {
286
+ throw new OntologySetupError(`ontology: ${shown} does not parse as YAML; nothing was changed. Fix it by hand and run again.`);
287
+ }
288
+ if (parsed !== null && parsed !== undefined && (typeof parsed !== "object" || Array.isArray(parsed))) {
289
+ throw new OntologySetupError(`ontology: ${shown} is not a list of keys; nothing was changed. Fix it by hand and run again.`);
290
+ }
291
+ }
292
+ const text = renderModelSetting(existing, model);
293
+ // The file as the step will read it: if it would not give this model, nothing is written.
294
+ let readBack;
295
+ try {
296
+ readBack = yaml.load(text)?.model;
297
+ }
298
+ catch {
299
+ readBack = undefined;
300
+ }
301
+ if (readBack !== model)
302
+ throw new OntologySetupError(`ontology: ${shown} could not be rewritten safely; nothing was changed`);
303
+ writeAtomic(file, text);
304
+ const lines = [`model for ${context.company}: ${model} (was ${before.setting ?? `${DEFAULT_ONTOLOGY_MODEL}, the default`})`, `written: ${shown}`];
305
+ if (envNote)
306
+ lines.push(envNote);
307
+ lines.push(PER_MACHINE_NOTE);
308
+ if (graphExists(defaultGraphRoot(context.companyRoot))) {
309
+ const old = before.setting ?? DEFAULT_ONTOLOGY_MODEL;
310
+ lines.push(`a graph is already built here: rows ${old} wrote stay until they are asked again (hq ontology remodel --company ${context.company} --from ${old} --dry-run shows how many)`);
311
+ }
312
+ else
313
+ lines.push(`next: hq ontology rebuild --company ${context.company}`);
314
+ return { text: lines.join("\n"), json: { ...base, model, was: before.setting, changed: true } };
315
+ }
316
+ function dirEntries(dir) {
317
+ try {
318
+ return fs.readdirSync(dir, { withFileTypes: true });
319
+ }
320
+ catch {
321
+ return [];
322
+ }
323
+ }
324
+ /**
325
+ * Counts entity files and row lines straight from the folder. It opens no
326
+ * store, builds no index and prints no row: only how many there are. Links
327
+ * are not followed.
328
+ */
329
+ export function countGraph(root) {
330
+ const counts = { entities: 0, entitiesByType: {}, rows: 0, facts: 0, relationships: 0, datedLines: 0, audienceFolders: 0 };
331
+ const types = new Set(GRAPH_ENTITY_TYPES);
332
+ for (const type of dirEntries(graphPath(root, GRAPH_PATHS.entities))) {
333
+ if (!type.isDirectory() || !types.has(type.name))
334
+ continue;
335
+ const files = dirEntries(path.join(root, GRAPH_PATHS.entities, type.name)).filter((entry) => entry.isFile() && entry.name.endsWith(".md")).length;
336
+ if (files === 0)
337
+ continue;
338
+ counts.entitiesByType[type.name] = files;
339
+ counts.entities += files;
340
+ }
341
+ const factsRoot = graphPath(root, GRAPH_PATHS.facts);
342
+ for (const audience of dirEntries(factsRoot)) {
343
+ if (!audience.isDirectory() || !audience.name.startsWith("@"))
344
+ continue;
345
+ counts.audienceFolders += 1;
346
+ for (const type of dirEntries(path.join(factsRoot, audience.name))) {
347
+ if (!type.isDirectory() || !types.has(type.name))
348
+ continue;
349
+ const dir = path.join(factsRoot, audience.name, type.name);
350
+ for (const entry of dirEntries(dir)) {
351
+ if (!entry.isFile() || !entry.name.endsWith(".md"))
352
+ continue;
353
+ let text;
354
+ try {
355
+ text = fs.readFileSync(path.join(dir, entry.name), "utf8");
356
+ }
357
+ catch {
358
+ continue;
359
+ }
360
+ for (let at = 0; at < text.length;) {
361
+ if (text.startsWith("- F ", at))
362
+ counts.facts += 1;
363
+ else if (text.startsWith("- E ", at))
364
+ counts.relationships += 1;
365
+ else if (text.startsWith("- T ", at))
366
+ counts.datedLines += 1;
367
+ const next = text.indexOf("\n", at);
368
+ if (next === -1)
369
+ break;
370
+ at = next + 1;
371
+ }
372
+ }
373
+ }
374
+ }
375
+ counts.rows = counts.facts + counts.relationships + counts.datedLines;
376
+ return counts;
377
+ }
378
+ function readCursorLook(root) {
379
+ try {
380
+ const parsed = JSON.parse(fs.readFileSync(graphPath(root, GRAPH_PATHS.cursor), "utf8"));
381
+ const days = Object.values(parsed.days ?? {}).filter((day) => typeof day === "string" && /^\d{4}-\d{2}-\d{2}$/.test(day)).sort();
382
+ return {
383
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : null,
384
+ lastDay: days.length > 0 ? days[days.length - 1] : null,
385
+ run: typeof parsed.run === "string" ? parsed.run : null,
386
+ };
387
+ }
388
+ catch {
389
+ return { updatedAt: null, lastDay: null, run: null };
390
+ }
391
+ }
392
+ function readBriefLook(root) {
393
+ const file = graphPath(root, GRAPH_PATHS.brief);
394
+ try {
395
+ const stat = fs.lstatSync(file);
396
+ if (!stat.isFile())
397
+ return { present: false, bytes: 0, tokens: 0, writtenAt: null };
398
+ const text = fs.readFileSync(file, "utf8");
399
+ return { present: true, bytes: stat.size, tokens: estimateTokens(text), writtenAt: stat.mtime.toISOString() };
400
+ }
401
+ catch {
402
+ return { present: false, bytes: 0, tokens: 0, writtenAt: null };
403
+ }
404
+ }
405
+ function pendingLook(context, env) {
406
+ const dir = resolveModelStateDir(context, undefined, env);
407
+ const file = path.join(dir, ...MODEL_STATE_PATHS.pending.replace(/^\.state\//, "").split("/"));
408
+ const byKind = {};
409
+ const markers = peekPendingMarkers(file);
410
+ for (const marker of markers) {
411
+ const kind = typeof marker.kind === "string" ? marker.kind : "other";
412
+ byKind[kind] = (byKind[kind] ?? 0) + 1;
413
+ }
414
+ return { items: markers.length, byKind };
415
+ }
416
+ const number = (value) => value.toLocaleString("en-US");
417
+ /** `hq ontology status`: reader, model, graph, counts, pending model work, last update and brief, on one screen. Reads only. */
418
+ export async function statusCommand(context, options = {}) {
419
+ const env = options.env ?? process.env;
420
+ const setting = readReaderSetting(context.hqRoot);
421
+ const reader = effectiveReader(setting, context.company);
422
+ const model = readModelState(context, env);
423
+ const graph = inspectGraphFolder(context.graphRoot, context.company);
424
+ // Nothing inside a folder that is another company's, or that cannot say whose it is, is counted or read.
425
+ const usable = graph.state === "ok" || (graph.state === "unstamped" && path.resolve(context.graphRoot) === path.resolve(defaultGraphRoot(context.companyRoot)));
426
+ const counts = usable ? countGraph(context.graphRoot) : null;
427
+ const cursor = usable ? readCursorLook(context.graphRoot) : null;
428
+ const brief = usable ? readBriefLook(context.graphRoot) : null;
429
+ const pending = usable ? pendingLook(context, env) : null;
430
+ const shownRoot = rel(context.hqRoot, context.graphRoot);
431
+ const next = [];
432
+ if (graph.state === "missing") {
433
+ if (model.source === "default")
434
+ next.push(`choose the model before the first build (the default is ${DEFAULT_ONTOLOGY_MODEL}): hq ontology model <model> --company ${context.company}`);
435
+ next.push(`build the graph: hq ontology rebuild --company ${context.company}`);
436
+ }
437
+ else if (!usable)
438
+ next.push("this folder is not used for this company; point --graph-root elsewhere or remove the folder by hand");
439
+ else {
440
+ if (graph.state === "unstamped")
441
+ next.push(`stamp the folder with a build: hq ontology update --company ${context.company}`);
442
+ if (pending && pending.items > 0)
443
+ next.push(`send pending model work: hq ontology update --company ${context.company} --follow-up`);
444
+ if (brief && !brief.present)
445
+ next.push(`write the brief: hq ontology brief --company ${context.company}`);
446
+ if (reader !== "graph" && graph.state === "ok")
447
+ next.push(`read the graph in sessions: hq ontology reader graph --company ${context.company}`);
448
+ }
449
+ const lines = [`ontology status for ${context.company}`];
450
+ lines.push(`reader: ${reader}${setting.present ? "" : " (no setting; the default)"}${setting.present && setting.reader === "graph" && setting.company !== context.company ? ` (the setting says graph for ${setting.company === "" ? "no company" : setting.company})` : ""}`);
451
+ lines.push(`model: ${model.model} (${sourceWords(model, context.company)}; per machine, not synced)`);
452
+ lines.push(`graph: ${graph.present ? "present" : "missing"}, ${graph.detail} (${shownRoot})`);
453
+ if (counts) {
454
+ const byType = Object.entries(counts.entitiesByType)
455
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
456
+ .map(([type, count]) => `${type} ${number(count)}`)
457
+ .join(", ");
458
+ lines.push(`entities: ${number(counts.entities)}${byType ? ` (${byType})` : ""}`);
459
+ lines.push(`rows: ${number(counts.rows)} (facts ${number(counts.facts)}, relationships ${number(counts.relationships)}, dated lines ${number(counts.datedLines)}) in ${number(counts.audienceFolders)} audience ${counts.audienceFolders === 1 ? "folder" : "folders"}`);
460
+ }
461
+ if (pending) {
462
+ const kinds = Object.entries(pending.byKind)
463
+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))
464
+ .map(([kind, count]) => `${kind} ${number(count)}`)
465
+ .join(", ");
466
+ lines.push(`pending: ${pending.items === 0 ? "no model work pending" : `${number(pending.items)} model ${pending.items === 1 ? "item" : "items"} pending (${kinds})`}`);
467
+ }
468
+ if (cursor)
469
+ lines.push(`updated: ${cursor.updatedAt ? `${cursor.updatedAt}${cursor.lastDay ? `, replayed through ${cursor.lastDay}` : ""}` : "never"}`);
470
+ if (brief)
471
+ lines.push(`brief: ${brief.present ? `${number(brief.bytes)} bytes, about ${number(brief.tokens)} tokens, written ${brief.writtenAt ?? "unknown"}` : "not written"}`);
472
+ for (const [index, step] of next.entries())
473
+ lines.push(`${index === 0 ? "next: " : " "} ${step}`);
474
+ return {
475
+ text: lines.join("\n"),
476
+ json: {
477
+ company: context.company,
478
+ reader: { effective: reader, setting: { ...setting, file: READER_SETTING_RELATIVE } },
479
+ model: { ...model, perMachine: true },
480
+ graph: { root: shownRoot, present: graph.present, stamp: graph.stamp, state: graph.state },
481
+ counts,
482
+ pending,
483
+ lastUpdate: cursor,
484
+ brief,
485
+ next,
486
+ },
487
+ };
488
+ }
489
+ //# sourceMappingURL=index.js.map
@@ -1114,6 +1114,13 @@ export interface RebuildOptions {
1114
1114
  budgetTokens?: number;
1115
1115
  /** Rules only: no model call is made and model work is left pending (`--no-model`). */
1116
1116
  noModel?: boolean;
1117
+ /**
1118
+ * Cap on model input tokens per day for this run (`--max-input-tokens`), as on `update`. The day's earlier
1119
+ * calls on the same model count toward it. Default 150,000.
1120
+ */
1121
+ maxInputTokens?: number;
1122
+ /** Cap on model output tokens per day for this run (`--max-output-tokens`). Default 20,000. */
1123
+ maxOutputTokens?: number;
1117
1124
  dryRun: boolean;
1118
1125
  }
1119
1126
  export interface UpdateOptions {
@@ -1132,6 +1139,12 @@ export interface UpdateOptions {
1132
1139
  maxInputTokens?: number;
1133
1140
  /** Cap on model output tokens per day for this run (`--max-output-tokens`). Default 20,000. */
1134
1141
  maxOutputTokens?: number;
1142
+ /**
1143
+ * Also send the follow-up model work an earlier run left pending (`--follow-up`): profiles, retyped links,
1144
+ * decisions that replace each other, page summaries, digests. Off by default, so an update with nothing
1145
+ * new makes no model call; the summary says how many items are pending.
1146
+ */
1147
+ followUp?: boolean;
1135
1148
  dryRun: boolean;
1136
1149
  }
1137
1150
  export interface LookupOptions {
@@ -1154,9 +1167,17 @@ export interface TraverseOptions {
1154
1167
  depth: number;
1155
1168
  asOf?: IsoDate;
1156
1169
  }
1170
+ /**
1171
+ * The two shapes of the brief. `map` (the default): what the graph holds, how to look things up, and names
1172
+ * worth looking up, with no facts. `full`: the earlier summary, which prints facts.
1173
+ */
1174
+ export declare const BRIEF_STYLES: readonly ["map", "full"];
1175
+ export type BriefStyle = (typeof BRIEF_STYLES)[number];
1157
1176
  export interface BriefOptions {
1158
1177
  /** Print the brief without writing brief.md. */
1159
1178
  stdout: boolean;
1179
+ /** Default: `brief_style` in the reader setting, else `map`. */
1180
+ style?: BriefStyle;
1160
1181
  }
1161
1182
  export interface LintOptions {
1162
1183
  /** File a proposal per finding. Default true. */
@@ -128,4 +128,9 @@ export class MemberIdentityRequiredError extends Error {
128
128
  this.name = "MemberIdentityRequiredError";
129
129
  }
130
130
  }
131
+ /**
132
+ * The two shapes of the brief. `map` (the default): what the graph holds, how to look things up, and names
133
+ * worth looking up, with no facts. `full`: the earlier summary, which prints facts.
134
+ */
135
+ export const BRIEF_STYLES = ["map", "full"];
131
136
  //# sourceMappingURL=types.js.map
@@ -25,7 +25,7 @@ import * as path from "node:path";
25
25
  import { audienceKey } from "../hot-channels/audience.js";
26
26
  import { SIGNED_OUT_SIGNALS_CODES, findSignalsFailures, formatSignalsFailureAlert, raiseSignalsFailureAlerts, signalsAlertKey, signalsAlertStatePath, } from "../hot-channels/alert.js";
27
27
  import { assertAllowedPath } from "./write-guard.js";
28
- import { resolveUploadAuthor } from "../../utils/upload-author.js";
28
+ import { resolveSyncPerson } from "../../utils/sync-person.js";
29
29
  import { readSignalsPassDetail } from "./steps/types.js";
30
30
  /**
31
31
  * Extract skips that are not a stall: no source channel to read, or the
@@ -37,11 +37,10 @@ export const EXTRACT_SKIPS_WITHOUT_ALERT = new Set(["no-sources", "ontology-work
37
37
  export const SIGNALS_RUN_ALERT_ADAPTER = "signals-run";
38
38
  /** The signed-in person, as `runCompanyHotChannelSync` resolves them; null when no one is signed in. */
39
39
  export function resolveSignedInAlertPerson() {
40
- const author = resolveUploadAuthor();
41
- // A sub-only upload author (machine token with no email) is not a person
42
- // this alert can address.
43
- if (!author?.email)
40
+ const person = resolveSyncPerson();
41
+ if (person.kind !== "person")
44
42
  return null;
43
+ const author = person.author;
45
44
  return { personKey: audienceKey([author.email]), personName: author.email, personUid: author.userSub };
46
45
  }
47
46
  function firstStep(record, name) {
@@ -166,6 +166,9 @@ const TOKEN_LEVEL_ADAPTERS = new Set(["attio", "gmail"]);
166
166
  * document cap left queued (`pass.deferred`) make the step `partial` too.
167
167
  */
168
168
  export function mapSyncReport(report, pass) {
169
+ if (report.signInRequired && report.noPersonIdentity) {
170
+ return { status: "skipped", itemsIn: 0, itemsOut: 0, skippedReason: "no-person-identity", byAdapter: {}, errorKind: "config" };
171
+ }
169
172
  if (report.signInRequired) {
170
173
  return { status: "skipped", itemsIn: 0, itemsOut: 0, skippedReason: "no-login", byAdapter: {}, errorKind: "signed-out" };
171
174
  }
@@ -0,0 +1,15 @@
1
+ export interface SyncPersonAuthor {
2
+ email: string;
3
+ userSub: string;
4
+ }
5
+ export type SyncPerson = {
6
+ kind: "person";
7
+ author: SyncPersonAuthor;
8
+ } | {
9
+ kind: "no-person";
10
+ } | {
11
+ kind: "signed-out";
12
+ };
13
+ export declare function syncPersonFromIdToken(idToken: string | undefined): SyncPerson;
14
+ export declare function resolveSyncPerson(env?: NodeJS.ProcessEnv, home?: string): SyncPerson;
15
+ //# sourceMappingURL=sync-person.d.ts.map
@@ -0,0 +1,74 @@
1
+ import * as os from "node:os";
2
+ import { loadMachineCachedTokens, readPersonTokenFile, wantsMachineCognitoTokens, } from "./cognito-session.js";
3
+ const COGNITO_SUB_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+ const OUTPOST_UID_RE = /^out_[0-9A-HJKMNP-TV-Z]{26}$/;
5
+ const EMAIL_RE = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
6
+ const MAX_EMAIL_LENGTH = 2048;
7
+ const OUTPOST_MARKER_CLAIMS = ["custom:delegatedSub", "custom:delegatedEmail", "custom:authClientId"];
8
+ const COMPANY_OUTPOST_MARKER_CLAIMS = ["custom:ownerCompanyUid", "custom:companyOutpostId"];
9
+ function decodeClaims(idToken) {
10
+ const parts = idToken.split(".");
11
+ if (parts.length !== 3)
12
+ return undefined;
13
+ try {
14
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
15
+ return claims !== null && typeof claims === "object" && !Array.isArray(claims)
16
+ ? claims
17
+ : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ function nonEmptyString(value) {
24
+ return typeof value === "string" && value.length > 0 ? value : undefined;
25
+ }
26
+ function hasClaim(claims, key) {
27
+ return Object.prototype.hasOwnProperty.call(claims, key);
28
+ }
29
+ function isCompanyOutpost(claims) {
30
+ return claims["custom:entityType"] === "company-outpost" || COMPANY_OUTPOST_MARKER_CLAIMS.some((key) => hasClaim(claims, key));
31
+ }
32
+ function hasOutpostMarkers(claims) {
33
+ return (isCompanyOutpost(claims) ||
34
+ claims["custom:entityType"] === "outpost" ||
35
+ nonEmptyString(claims["custom:entityUid"])?.startsWith("out_") === true ||
36
+ OUTPOST_MARKER_CLAIMS.some((key) => hasClaim(claims, key)));
37
+ }
38
+ function outpostOwner(claims) {
39
+ if (isCompanyOutpost(claims) || claims["custom:entityType"] !== "outpost")
40
+ return undefined;
41
+ if (!nonEmptyString(claims.sub))
42
+ return undefined;
43
+ const entityUid = nonEmptyString(claims["custom:entityUid"]);
44
+ const delegatedSub = nonEmptyString(claims["custom:delegatedSub"]);
45
+ const delegatedEmail = nonEmptyString(claims["custom:delegatedEmail"]);
46
+ if (!entityUid || !OUTPOST_UID_RE.test(entityUid))
47
+ return undefined;
48
+ if (!delegatedSub || !COGNITO_SUB_RE.test(delegatedSub))
49
+ return undefined;
50
+ if (!delegatedEmail || delegatedEmail.length > MAX_EMAIL_LENGTH || !EMAIL_RE.test(delegatedEmail))
51
+ return undefined;
52
+ return { email: delegatedEmail.toLowerCase(), userSub: delegatedSub };
53
+ }
54
+ export function syncPersonFromIdToken(idToken) {
55
+ if (!idToken)
56
+ return { kind: "signed-out" };
57
+ const claims = decodeClaims(idToken);
58
+ const sub = claims ? nonEmptyString(claims.sub) : undefined;
59
+ if (!claims || !sub)
60
+ return { kind: "signed-out" };
61
+ if (hasOutpostMarkers(claims)) {
62
+ const owner = outpostOwner(claims);
63
+ return owner ? { kind: "person", author: owner } : { kind: "no-person" };
64
+ }
65
+ const email = nonEmptyString(claims.email);
66
+ return email ? { kind: "person", author: { email, userSub: sub } } : { kind: "no-person" };
67
+ }
68
+ export function resolveSyncPerson(env = process.env, home = os.homedir()) {
69
+ const tokens = wantsMachineCognitoTokens({}, env)
70
+ ? loadMachineCachedTokens(home, env)
71
+ : readPersonTokenFile(home, env);
72
+ return syncPersonFromIdToken(tokens?.idToken);
73
+ }
74
+ //# sourceMappingURL=sync-person.js.map