@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,450 @@
1
+ /**
2
+ * `hq ontology remodel`: replace the rows one model wrote with what the model
3
+ * in use now says.
4
+ *
5
+ * Rows by two models are of the same authority, so running the pass again on a
6
+ * better model adds its rows beside the weaker model's and leaves those open.
7
+ * This command asks again, on the configured model, the questions behind the
8
+ * open rows written `by agent:<from>`, and closes those rows through the
9
+ * store's own closure (`closeRow`: the row keeps its id and its line, with
10
+ * `closed <day> by <ref>`; nothing is deleted).
11
+ *
12
+ * What it can ask again is what the graph pass wrote and recorded in
13
+ * `.state/model-rows.jsonl`: digests of meetings and threads, and profiles
14
+ * (role, employer, stage, contacts). For each of those rows it knows the item
15
+ * that produced it. A row is closed only when that item was answered in this
16
+ * run; an item the budget did not reach keeps its rows open for the next run.
17
+ * Rows the replay wrote (typed relationships, extractions), retyped edges and
18
+ * decision supersessions are counted and left as they are.
19
+ *
20
+ * Order: ask (model turns, nothing written), close the old rows of the
21
+ * answered items, write the new rows from the cached answers. The old rows are
22
+ * out of the way before the new ones arrive, so the new model's value is never
23
+ * written closed behind a weaker model's newer row.
24
+ *
25
+ * Closing and writing are two steps, so the run writes down what it is about to
26
+ * do first (`.state/remodel-intent.json`: the rows to close, the items behind
27
+ * them, the model). A run that is killed between the two leaves that file. The
28
+ * next run finishes the job before it does anything else: it closes what was
29
+ * not yet closed, writes the new rows from the cached answers, and reopens any
30
+ * row whose item has no usable answer after all. Only then is the file marked
31
+ * finished. A row is therefore never left closed with nothing asked in its place.
32
+ */
33
+ import { createModelStep as defaultCreateModelStep, readModelRowCitations, runModelPass as defaultRunModelPass, } from "../model/index.js";
34
+ import { compilePages as defaultCompilePages } from "../pages/index.js";
35
+ import { briefCommand as defaultBriefCommand } from "../read/index.js";
36
+ import { DEFAULT_DAY_BUDGET, resolveDayBudget, resolveSignedInMember, withMember } from "../replay/index.js";
37
+ import { inverseEdge, isOpen, isSingleValued, parseEntityRef, rowId } from "../schema/index.js";
38
+ import { assertGraphWritableFor, atomicWriteFile, claimGraphRootFor, graphPath, openGraphStore, readTextIfExists } from "../store/index.js";
39
+ import { MemberIdentityRequiredError, } from "../types.js";
40
+ /** Where a run writes what it is about to close and write, relative to the graph folder. */
41
+ export const REMODEL_INTENT_RELATIVE = ".state/remodel-intent.json";
42
+ /** The intent of a run that did not finish, or null. An unreadable file is no intent: nothing in it can be trusted to close a row. */
43
+ export function readUnfinishedRemodel(graphRoot) {
44
+ try {
45
+ const text = readTextIfExists(graphPath(graphRoot, REMODEL_INTENT_RELATIVE));
46
+ if (text === null)
47
+ return null;
48
+ const parsed = JSON.parse(text);
49
+ if (parsed.version !== 1 || parsed.finished || !Array.isArray(parsed.closures) || !Array.isArray(parsed.only) || !Array.isArray(parsed.tasks))
50
+ return null;
51
+ if (typeof parsed.model !== "string" || typeof parsed.from !== "string" || typeof parsed.day !== "string" || typeof parsed.run !== "string")
52
+ return null;
53
+ return parsed;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ /** Thrown for a request the command cannot carry out as given. */
60
+ export class RemodelUsageError extends Error {
61
+ constructor(message) {
62
+ super(message);
63
+ this.name = "RemodelUsageError";
64
+ }
65
+ }
66
+ const MODEL_NAME = /^[a-z0-9][a-z0-9.[\]-]{0,63}$/i;
67
+ const ASKABLE = ["digest", "profile"];
68
+ const MEETING_SOURCE = /^source:sources\/meetings\//;
69
+ /** Every source a remodel may read again, however old: the rows to replace are not limited to the last 90 days. */
70
+ const ANY_AGE_DAYS = 36_500;
71
+ const PASS_CONCURRENCY = 4;
72
+ function typeOf(ref) {
73
+ return parseEntityRef(ref)?.type ?? "";
74
+ }
75
+ function kindOf(row) {
76
+ return row.kind === "F" ? row.field : row.verb;
77
+ }
78
+ function later(a, b) {
79
+ return a > b ? a : b;
80
+ }
81
+ /** The item of the pass that wrote a row, as the pass names it (`itemKey`). A contact row is also covered by the company's profile. */
82
+ function itemKeys(target) {
83
+ if (target.task === "digest")
84
+ return [target.row.src];
85
+ const keys = [`profile:${target.entity}`];
86
+ if (target.row.kind === "E" && target.row.verb === "works_at")
87
+ keys.push(`profile:${target.row.target}`);
88
+ return keys;
89
+ }
90
+ /** True when an open row by the new model on the same entity and audience says the same kind of thing. */
91
+ function restated(store, schema, target, by) {
92
+ const type = typeOf(target.entity);
93
+ const single = isSingleValued(schema, type, target.row);
94
+ return store.readRows(target.entity, { audiences: [target.audience], openOnly: true }).some((stored) => {
95
+ const row = stored.row;
96
+ if (row.kind === "T" || row.by !== by || row.kind !== target.row.kind)
97
+ return false;
98
+ if (row.kind === "F" && target.row.kind === "F")
99
+ return row.field === target.row.field && (single || row.value === target.row.value);
100
+ if (row.kind === "E" && target.row.kind === "E")
101
+ return row.verb === target.row.verb && (single || row.target === target.row.target);
102
+ return false;
103
+ });
104
+ }
105
+ /**
106
+ * Carries an intent out, from wherever an earlier attempt stopped: closes the listed rows that are still
107
+ * open, writes the new rows from the answers, reopens a row whose item has no usable answer, and marks the
108
+ * intent finished. Every step can be repeated: closing a closed row and writing a row already on file do nothing.
109
+ */
110
+ async function complete(context, scoped, intent, step, deps, now) {
111
+ claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
112
+ const open = () => openGraphStore(context.graphRoot, { company: context.company });
113
+ const out = { closed: 0, reopened: 0, rowsAdded: 0, replaced: 0, notRestated: 0, touched: [], seconds: 0, usage: { inputTokens: 0, outputTokens: 0, calls: 0 } };
114
+ const touched = new Set();
115
+ const writing = open();
116
+ for (const closure of intent.closures) {
117
+ // The row's own source is cited: it was read again, by the model in use.
118
+ const at = { on: closure.on, by: closure.by };
119
+ if (writing.closeRow(closure.entity, closure.audience, closure.id, at))
120
+ out.closed += 1;
121
+ touched.add(closure.entity);
122
+ if (!closure.inverse)
123
+ continue;
124
+ if (writing.closeRow(closure.inverse.entity, closure.audience, closure.inverse.id, at))
125
+ out.closed += 1;
126
+ touched.add(closure.inverse.entity);
127
+ }
128
+ writing.markDirty([...touched]);
129
+ deps.afterClose?.();
130
+ const usable = new Set();
131
+ const written = await defaultRunModelPass(scoped, {
132
+ step, tasks: intent.tasks, only: new Set(intent.only), day: intent.day, apply: true, windowDays: ANY_AGE_DAYS, store: open(),
133
+ onResult: (_task, record) => {
134
+ if (record.status === "ok" || record.status === "cached")
135
+ usable.add(record.key);
136
+ },
137
+ });
138
+ out.seconds = written.seconds;
139
+ for (const task of written.tasks) {
140
+ out.rowsAdded += task.rowsNew;
141
+ out.usage.calls += task.stats.calls;
142
+ out.usage.inputTokens += Math.round(task.stats.usage.inputTokens);
143
+ out.usage.outputTokens += Math.round(task.stats.usage.outputTokens);
144
+ }
145
+ // A row whose item has no usable answer now (the cache was lost, the cap was reached on a resumed run) is not
146
+ // left closed with nothing in its place: it is open again, and a later run asks about it.
147
+ const after = open();
148
+ const schema = after.schema();
149
+ const by = `agent:${intent.model}`;
150
+ for (const closure of intent.closures) {
151
+ if (!closure.items.some((key) => usable.has(key))) {
152
+ if (after.reopenRow?.(closure.entity, closure.audience, closure.id))
153
+ out.reopened += 1;
154
+ if (closure.inverse && after.reopenRow?.(closure.inverse.entity, closure.audience, closure.inverse.id))
155
+ out.reopened += 1;
156
+ continue;
157
+ }
158
+ const stored = after.readRows(closure.entity, { audiences: [closure.audience] }).find((row) => row.id === closure.id);
159
+ if (!stored || stored.row.kind === "T")
160
+ continue;
161
+ if (restated(after, schema, { entity: closure.entity, audience: closure.audience, row: stored.row }, by))
162
+ out.replaced += 1;
163
+ else
164
+ out.notRestated += 1;
165
+ }
166
+ if (out.reopened > 0)
167
+ after.markDirty([...touched]);
168
+ out.touched = [...touched].sort();
169
+ atomicWriteFile(graphPath(context.graphRoot, REMODEL_INTENT_RELATIVE), `${JSON.stringify({ ...intent, finished: now().toISOString() })}\n`);
170
+ return out;
171
+ }
172
+ export async function runRemodel(context, options, deps = {}) {
173
+ const env = deps.env ?? process.env;
174
+ const name = options.from.trim().replace(/^agent:/, "");
175
+ if (!MODEL_NAME.test(name))
176
+ throw new RemodelUsageError(`remodel: --from is not a model name: ${options.from}`);
177
+ const from = `agent:${name}`;
178
+ const scoped = withMember(context, deps.resolveMember ?? ((ctx) => resolveSignedInMember(ctx, env)));
179
+ if (!scoped.member)
180
+ throw new MemberIdentityRequiredError("remodel");
181
+ // A folder stamped for another company, or one that could be anyone's, is not read for a dry run either.
182
+ assertGraphWritableFor(context.graphRoot, context.company, context.companyRoot);
183
+ // Refused before anything is read: a cap of zero, a fraction or a negative.
184
+ const dayBudget = resolveDayBudget(options);
185
+ const now = deps.now ?? (() => new Date());
186
+ const day = now().toISOString().slice(0, 10);
187
+ const run = `remodel-${now().toISOString().replace(/[-:.]/g, "").slice(0, 15)}Z-${String(process.pid)}`;
188
+ const kinds = [...new Set((options.kinds ?? []).map((kind) => kind.trim()).filter((kind) => kind !== ""))].sort();
189
+ const notes = [];
190
+ const step = deps.step ??
191
+ defaultCreateModelStep(scoped, {
192
+ budget: { inputTokens: dayBudget.inputTokens, outputTokens: dayBudget.outputTokens },
193
+ ...(options.budgetTokens ? { runBudget: { inputTokens: options.budgetTokens, outputTokens: Math.ceil(options.budgetTokens / 7.5) } } : {}),
194
+ ...(deps.runner ? { runner: deps.runner } : {}),
195
+ ...(options.dryRun ? { dryRun: true, readOnly: true } : {}),
196
+ concurrency: PASS_CONCURRENCY,
197
+ runId: run,
198
+ now,
199
+ });
200
+ const by = `agent:${step.model}`;
201
+ if (by === from) {
202
+ throw new RemodelUsageError(`remodel: ${name} is the model in use, so there is nothing to replace its rows with. Set the model to use (HQ_ONTOLOGY_MODEL, or model: in settings/ontology.yaml) and run again.`);
203
+ }
204
+ // ---- an earlier run that stopped between closing and writing is finished first ----
205
+ const unfinished = readUnfinishedRemodel(context.graphRoot);
206
+ let resumed;
207
+ if (unfinished && options.dryRun) {
208
+ notes.push(`An earlier run (${unfinished.run}, rows by ${unfinished.from} asked on ${unfinished.model}) was interrupted after it closed rows and before it wrote the new ones. The next run without --dry-run finishes it first.`);
209
+ }
210
+ else if (unfinished) {
211
+ // On the model the interrupted run asked: its answers are in the cache under that model's name.
212
+ const resumeStep = deps.step ??
213
+ (unfinished.model === step.model
214
+ ? step
215
+ : defaultCreateModelStep(scoped, {
216
+ budget: { inputTokens: dayBudget.inputTokens, outputTokens: dayBudget.outputTokens },
217
+ ...(deps.runner ? { runner: deps.runner } : {}),
218
+ model: unfinished.model, concurrency: PASS_CONCURRENCY, runId: run, now,
219
+ }));
220
+ const done = await complete(context, scoped, unfinished, resumeStep, { ...deps, afterClose: undefined }, now);
221
+ resumed = { run: unfinished.run, from: unfinished.from, model: unfinished.model, closed: done.closed, rowsAdded: done.rowsAdded, reopened: done.reopened };
222
+ notes.push(`Finished an interrupted run first (${unfinished.run}, rows by ${unfinished.from} asked on ${unfinished.model}): ${String(done.rowsAdded)} rows written, ${String(done.closed)} more closed, ${String(done.reopened)} reopened.`);
223
+ openGraphStore(context.graphRoot, { company: context.company }).appendLog({
224
+ date: day, op: "update", subject: unfinished.run, touched: done.touched, rowsAdded: done.rowsAdded, rowsClosed: done.closed,
225
+ note: `remodel: interrupted run finished; rows by ${unfinished.from} asked again on ${unfinished.model}`,
226
+ });
227
+ }
228
+ // ---- which rows, and which item of the pass wrote each ----
229
+ const reading = openGraphStore(context.graphRoot, { company: context.company });
230
+ const schema = reading.schema();
231
+ const citations = readModelRowCitations(context.graphRoot);
232
+ const wanted = (row) => {
233
+ if (kinds.length === 0)
234
+ return true;
235
+ if (kinds.includes(kindOf(row)))
236
+ return true;
237
+ const inverse = row.kind === "E" ? schema.link_types[row.verb]?.inverse : undefined;
238
+ return inverse !== undefined && kinds.includes(inverse);
239
+ };
240
+ const report = {
241
+ from, model: step.model, day, dryRun: options.dryRun, kinds,
242
+ rows: { open: 0, byKind: {}, askable: 0, noRecord: 0, otherTask: 0, sameItem: 0 },
243
+ items: { total: 0, byTask: {}, answered: 0, cached: 0, pending: 0 },
244
+ closed: 0, replaced: 0, notRestated: 0, leftOpen: 0, rowsAdded: 0,
245
+ usage: { inputTokens: 0, outputTokens: 0, calls: 0 }, reopened: 0,
246
+ cap: { dayInputTokens: dayBudget.inputTokens, dayOutputTokens: dayBudget.outputTokens, overridden: dayBudget.overridden, ...(options.budgetTokens ? { runInputTokens: options.budgetTokens } : {}) },
247
+ halted: null, notes,
248
+ ...(resumed ? { resumed } : {}),
249
+ };
250
+ let targets = [];
251
+ /** Askable rows of a kind that was not picked: replaced only when a picked row shares their item. */
252
+ const others = [];
253
+ const meetingOf = new Map();
254
+ for (const ref of reading.listEntities()) {
255
+ const isMeeting = typeOf(ref) === "meeting";
256
+ for (const stored of reading.readRows(ref)) {
257
+ if (isMeeting && MEETING_SOURCE.test(stored.row.src) && !meetingOf.has(stored.row.src))
258
+ meetingOf.set(stored.row.src, ref);
259
+ const row = stored.row;
260
+ if (row.kind === "T" || row.by !== from || !isOpen(row))
261
+ continue;
262
+ if (!wanted(row)) {
263
+ const task = citations.get(`${ref}|${stored.id}`)?.task;
264
+ if (task && ASKABLE.includes(task))
265
+ others.push({ entity: ref, audience: stored.audience, id: stored.id, row, task });
266
+ continue;
267
+ }
268
+ report.rows.open += 1;
269
+ report.rows.byKind[`${row.kind} ${kindOf(row)}`] = (report.rows.byKind[`${row.kind} ${kindOf(row)}`] ?? 0) + 1;
270
+ const citation = citations.get(`${ref}|${stored.id}`);
271
+ if (!citation) {
272
+ // The other end of a relationship the pass wrote is closed with it, and is not a row of its own to ask about.
273
+ const forward = row.kind === "E" ? inverseEdge(schema, ref, row) : null;
274
+ const forwardTask = forward && forward.row.verb ? citations.get(`${forward.entity}|${rowId(forward.row)}`)?.task : undefined;
275
+ if (!forwardTask)
276
+ report.rows.noRecord += 1;
277
+ else if (ASKABLE.includes(forwardTask))
278
+ report.rows.askable += 1;
279
+ else
280
+ report.rows.otherTask += 1;
281
+ continue;
282
+ }
283
+ if (!ASKABLE.includes(citation.task)) {
284
+ report.rows.otherTask += 1;
285
+ continue;
286
+ }
287
+ report.rows.askable += 1;
288
+ targets.push({ entity: ref, audience: stored.audience, id: stored.id, row, task: citation.task });
289
+ }
290
+ }
291
+ if (others.length > 0 && targets.length > 0) {
292
+ const picked = new Set(targets.flatMap((target) => itemKeys(target).slice(0, 1)));
293
+ const same = others.filter((other) => picked.has(itemKeys(other)[0]));
294
+ report.rows.sameItem = same.length;
295
+ targets = [...targets, ...same];
296
+ }
297
+ const tasks = ASKABLE.filter((task) => targets.some((target) => target.task === task));
298
+ const only = new Set();
299
+ const wantedItems = new Map();
300
+ for (const target of targets) {
301
+ only.add(target.entity);
302
+ if (target.row.kind === "E")
303
+ only.add(target.row.target);
304
+ const meeting = target.task === "digest" ? meetingOf.get(target.row.src) : undefined;
305
+ if (meeting)
306
+ only.add(meeting);
307
+ for (const key of itemKeys(target))
308
+ wantedItems.set(key, target.task);
309
+ }
310
+ if (report.rows.noRecord > 0) {
311
+ notes.push(`${String(report.rows.noRecord)} rows have no record of the task that wrote them (the replay's typed relationships and extractions): left as they are. A rebuild asks those again on the model in use.`);
312
+ }
313
+ if (report.rows.otherTask > 0)
314
+ notes.push(`${String(report.rows.otherTask)} rows are retyped edges or decision supersessions, which cannot be asked again from the graph: left as they are.`);
315
+ if (targets.length === 0)
316
+ return report;
317
+ // ---- ask: model turns, nothing written to the graph ----
318
+ const answered = new Set();
319
+ const built = new Map();
320
+ const asked = await defaultRunModelPass(scoped, {
321
+ step, tasks, only, day, apply: false, windowDays: ANY_AGE_DAYS,
322
+ store: reading,
323
+ onResult: (task, record) => {
324
+ // Only the items behind a row to replace count; the scope can hold other work of the same entities.
325
+ if (!wantedItems.has(record.key))
326
+ return;
327
+ built.set(record.key, task);
328
+ if (record.status === "ok" || record.status === "cached")
329
+ answered.add(record.key);
330
+ if (record.status === "cached")
331
+ report.items.cached += 1;
332
+ if (record.status === "pending")
333
+ report.items.pending += 1;
334
+ },
335
+ });
336
+ report.items.total = built.size;
337
+ for (const task of built.values())
338
+ report.items.byTask[task] = (report.items.byTask[task] ?? 0) + 1;
339
+ report.items.answered = answered.size;
340
+ for (const task of asked.tasks) {
341
+ report.usage.calls += task.stats.calls;
342
+ report.usage.inputTokens += Math.round(task.stats.usage.inputTokens);
343
+ report.usage.outputTokens += Math.round(task.stats.usage.outputTokens);
344
+ }
345
+ report.halted = step.halted();
346
+ const notBuilt = [...wantedItems.keys()].filter((key) => !built.has(key)).length;
347
+ if (notBuilt > 0)
348
+ notes.push(`${String(notBuilt)} items could not be built again (the source file is not on this machine, a signal covers the source now, or the entity no longer has lines that state a role): their rows are left as they are.`);
349
+ const covered = targets.filter((target) => itemKeys(target).some((key) => answered.has(key)));
350
+ // Both ends of a relationship counted, as in `rows.askable`.
351
+ report.leftOpen = targets.filter((target) => !covered.includes(target)).reduce((sum, target) => sum + (target.row.kind === "E" ? 2 : 1), 0);
352
+ if (options.dryRun) {
353
+ const totals = step.totals();
354
+ report.estimate = { itemsToSend: totals.unsentItems, inputTokens: totals.unsentInputTokens };
355
+ return report;
356
+ }
357
+ if (covered.length === 0)
358
+ return report;
359
+ // ---- write down what is about to happen, close the old rows of the answered items, write the new ones ----
360
+ const intent = {
361
+ version: 1, run, from, model: step.model, day, tasks: [...tasks], only: [...only].sort(),
362
+ closures: covered.map((target) => {
363
+ const inverse = target.row.kind === "E" ? inverseEdge(schema, target.entity, target.row) : null;
364
+ return {
365
+ entity: target.entity, audience: target.audience, id: target.id,
366
+ on: later(day, target.row.valid.from), by: target.row.src, items: itemKeys(target),
367
+ ...(inverse && inverse.row.verb ? { inverse: { entity: inverse.entity, id: rowId(inverse.row) } } : {}),
368
+ };
369
+ }),
370
+ };
371
+ claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
372
+ atomicWriteFile(graphPath(context.graphRoot, REMODEL_INTENT_RELATIVE), `${JSON.stringify(intent)}\n`);
373
+ const done = await complete(context, scoped, intent, step, deps, now);
374
+ report.closed = done.closed - done.reopened;
375
+ report.reopened = done.reopened;
376
+ report.rowsAdded = done.rowsAdded;
377
+ report.replaced = done.replaced;
378
+ report.notRestated = done.notRestated;
379
+ report.usage.calls += done.usage.calls;
380
+ report.usage.inputTokens += done.usage.inputTokens;
381
+ report.usage.outputTokens += done.usage.outputTokens;
382
+ if (done.reopened > 0)
383
+ notes.push(`${String(done.reopened)} rows were opened again: their item had no usable answer when the new rows were written.`);
384
+ const touched = new Set(done.touched);
385
+ const written = { seconds: done.seconds };
386
+ const after = openGraphStore(context.graphRoot, { company: context.company });
387
+ after.appendLog({
388
+ date: day, op: "update", subject: run, touched: [...touched].sort(), rowsAdded: report.rowsAdded, rowsClosed: report.closed,
389
+ note: `remodel: rows by ${from} asked again on ${step.model}`,
390
+ });
391
+ after.appendLedger({
392
+ run, command: "update", day: "remodel", inputs: {}, rowsAdded: report.rowsAdded, rowsClosed: report.closed, entitiesCreated: 0,
393
+ modelCalls: report.usage.calls, cacheHits: report.items.cached, inputTokens: report.usage.inputTokens, outputTokens: report.usage.outputTokens,
394
+ pending: report.items.pending, seconds: Math.round(asked.seconds + written.seconds), at: now().toISOString(),
395
+ counters: { remodel_rows_closed: report.closed, remodel_rows_replaced: report.replaced, remodel_rows_not_restated: report.notRestated, remodel_rows_left_open: report.leftOpen },
396
+ });
397
+ const compiler = deps.compilePages === undefined ? defaultCompilePages : deps.compilePages;
398
+ if (compiler)
399
+ await compiler(scoped, { store: openGraphStore(context.graphRoot, { company: context.company }), day, model: step });
400
+ const brief = deps.brief === undefined ? defaultBriefCommand : deps.brief;
401
+ if (brief) {
402
+ try {
403
+ await brief(scoped, { stdout: false });
404
+ }
405
+ catch (error) {
406
+ notes.push(`Brief was not written (${error.name}).`);
407
+ }
408
+ }
409
+ return report;
410
+ }
411
+ export function formatRemodelReport(report) {
412
+ const rows = (n) => `${String(n)} row${n === 1 ? "" : "s"}`;
413
+ const items = (n) => `${String(n)} item${n === 1 ? "" : "s"}`;
414
+ const byTask = Object.entries(report.items.byTask).map(([task, count]) => `${task} ${String(count)}`).join(", ");
415
+ const lines = [
416
+ `remodel${report.dryRun ? " (dry run, no model call, nothing written)" : ""}: rows by ${report.from}, asked again on ${report.model}${report.kinds.length > 0 ? `, kinds ${report.kinds.join(", ")}` : ""}`,
417
+ `open rows by ${report.from}: ${String(report.rows.open)} (can be asked again ${String(report.rows.askable)}, no record of the task ${String(report.rows.noRecord)}, other tasks ${String(report.rows.otherTask)})`,
418
+ `items behind them: ${String(report.items.total)}${byTask ? ` (${byTask})` : ""}`,
419
+ ];
420
+ if (report.rows.sameItem > 0)
421
+ lines.push(`${rows(report.rows.sameItem)} of other kinds come from the same items and are replaced with them.`);
422
+ if (report.dryRun) {
423
+ const estimate = report.estimate ?? { itemsToSend: 0, inputTokens: 0 };
424
+ lines.push(`already answered by ${report.model}: ${items(report.items.cached)} (0 tokens); to send: ${items(estimate.itemsToSend)}, about ${String(estimate.inputTokens)} input tokens (estimate)`);
425
+ if (estimate.itemsToSend > report.items.pending)
426
+ lines.push(`(${items(estimate.itemsToSend - report.items.pending)} of those are other digests and profiles of the same entities, which the pass asks with them.)`);
427
+ }
428
+ else {
429
+ lines.push(`answered ${items(report.items.answered)} (${String(report.items.cached)} from the cache), pending ${String(report.items.pending)}; model calls ${String(report.usage.calls)}, tokens in ${String(report.usage.inputTokens)} out ${String(report.usage.outputTokens)}`);
430
+ lines.push(`closed ${rows(report.closed)} by ${report.from} (history kept): ${String(report.replaced)} stated again by ${report.model}, ${String(report.notRestated)} not stated again; rows added ${String(report.rowsAdded)}`);
431
+ }
432
+ if (report.leftOpen > 0 && !report.dryRun)
433
+ lines.push(`${rows(report.leftOpen)} still open: their item was not answered in this run. Run again to carry on.`);
434
+ lines.push(`model cap per day: in ${String(report.cap.dayInputTokens)} out ${String(report.cap.dayOutputTokens)} (${report.cap.overridden ? "set for this run" : "default"})${report.cap.runInputTokens !== undefined ? `; this run: in ${String(report.cap.runInputTokens)}` : ""}`);
435
+ const overCap = report.dryRun && (report.estimate?.inputTokens ?? 0) > report.cap.dayInputTokens;
436
+ if (overCap || report.items.pending > 0) {
437
+ lines.push(`The daily cap (default in ${String(DEFAULT_DAY_BUDGET.inputTokens)}) stops the run when it is reached; the next day's run carries on, or raise it for one run: hq ontology remodel --from ${report.from.replace(/^agent:/, "")} --max-input-tokens <n> --max-output-tokens <n>`);
438
+ }
439
+ if (report.halted)
440
+ lines.push(`stopped (${report.halted}): what was not asked is left open for the next run.`);
441
+ for (const note of report.notes)
442
+ lines.push(`note: ${note}`);
443
+ return lines.join("\n");
444
+ }
445
+ /** `hq ontology remodel`. */
446
+ export async function remodelCommand(context, options, deps = {}) {
447
+ const report = await runRemodel(context, options, deps);
448
+ return { text: formatRemodelReport(report), json: report };
449
+ }
450
+ //# sourceMappingURL=index.js.map
@@ -4,14 +4,15 @@
4
4
  * classes in readers.ts, the rules in extractors.ts.
5
5
  */
6
6
  import { runLint as defaultRunLint } from "../lint/index.js";
7
- import { DEFAULT_ONTOLOGY_MODEL, PASS_TASK_MODELS, createModelStep as defaultCreateModelStep, resolveModel, runModelPass as defaultRunModelPass, } from "../model/index.js";
7
+ import * as path from "node:path";
8
+ import { DEFAULT_ONTOLOGY_MODEL, MODEL_STATE_PATHS, PASS_TASK_MODELS, createModelStep as defaultCreateModelStep, followUpEntities, followUpScope, followUpTask, peekPendingMarkers, resolveModel, resolveModelStateDir, runModelPass as defaultRunModelPass, } from "../model/index.js";
8
9
  import { OntologyGraphNotImplementedError } from "../not-implemented.js";
9
10
  import { compilePages as defaultCompilePages, summaryItemsFor } from "../pages/index.js";
10
11
  import { briefCommand as defaultBriefCommand } from "../read/index.js";
11
12
  import { graphPath, openGraphStore } from "../store/index.js";
12
13
  import { MemberIdentityRequiredError, } from "../types.js";
13
14
  import { kindReaders, scanCorpus } from "./readers.js";
14
- import { LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, TRANSCRIPT_CACHE_RELATIVE, formatReport, runRebuildWith, runUpdateWith } from "./engine.js";
15
+ import { LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, TRANSCRIPT_CACHE_RELATIVE, formatReport, resolveDayBudget, runRebuildWith, runUpdateWith } from "./engine.js";
15
16
  import { allRuleExtractors } from "./extractors.js";
16
17
  import { resolveSignedInMember, withMember } from "./member.js";
17
18
  export { scanCorpus, kindReaders, meetingSlug } from "./readers.js";
@@ -30,6 +31,12 @@ export const PASS_RUN_BUDGET = {
30
31
  /** A rebuild: one full pass over a vault of about 50,000 inputs, with room. Replies already cached cost nothing. */
31
32
  rebuild: { inputTokens: 8_000_000, outputTokens: 4_000_000 },
32
33
  };
34
+ /** Why a follow-up marker its task did not build again is dropped, by task. Said in the run summary with the count. */
35
+ const DROP_REASON = {
36
+ profile: "the entity no longer has recent lines that state a role, employer or stage",
37
+ retype: "the link is no longer an open untyped link with a dated line that names both ends",
38
+ supersede: "the decisions about the topic have changed since, and the new group was asked instead",
39
+ };
33
40
  /** The cap per model per day, whatever the runs: a loop of updates stops here. */
34
41
  const PASS_DAY_BUDGET = { inputTokens: 12_000_000, outputTokens: 6_000_000 };
35
42
  const PASS_CONCURRENCY = 4;
@@ -50,6 +57,12 @@ function passIsOff(options, deps) {
50
57
  * dirty, then the brief. Replies are cached by content beside the graph folder
51
58
  * (`.hq/ontology-graph-model`), which no rebuild touches, so a second run over
52
59
  * unchanged sources makes no call.
60
+ *
61
+ * An update also looks again at the follow-up work an earlier run left pending
62
+ * (profiles, retypes, decisions that replace each other, page summaries,
63
+ * digests), whether or not it found anything new: the pass is scoped to what
64
+ * the run touched and to the entities those markers name. A marker whose item
65
+ * the graph no longer builds is dropped.
53
66
  */
54
67
  async function replayThenPass(command, context, options, deps, run) {
55
68
  if (passIsOff(options, deps))
@@ -62,8 +75,42 @@ async function replayThenPass(command, context, options, deps, run) {
62
75
  const scoped = withMember(context, deps.resolveMember ?? ((ctx) => resolveSignedInMember(ctx, env)));
63
76
  const day = (deps.now ?? (() => new Date()))().toISOString().slice(0, 10);
64
77
  const changed = report.days > 0 || report.totals.rowsAdded > 0 || report.totals.rowsClosed > 0;
65
- // A stopped run is finished by the next one. An update that found nothing new has nothing to send.
66
- if (report.partial || (command === "update" && !changed))
78
+ // A stopped run is finished by the next one.
79
+ if (report.partial)
80
+ return report;
81
+ // Follow-up work an earlier run left pending (profiles, retyped links, decisions, summaries, digests) is sent
82
+ // only when the run asks for it (`--follow-up`): a plain update with nothing new makes no model call, as
83
+ // before. Without the flag the summary says how many items wait. A look at the file decides whether there is
84
+ // anything to count, so a quiet day with nothing pending still costs the listing and nothing else.
85
+ const isUpdate = command === "update";
86
+ const wantFollowUp = isUpdate && options.followUp === true;
87
+ const pendingFile = path.join(resolveModelStateDir(scoped, undefined, env), ...MODEL_STATE_PATHS.pending.replace(/^\.state\//, "").split("/"));
88
+ const followUpOf = (markers) => markers.filter((marker) => followUpTask(marker) !== null);
89
+ /** The follow-up markers that are really pending: the file's, less what any model has already answered. */
90
+ const pendingFollowUp = () => {
91
+ if (deps.passStep)
92
+ return followUpOf(deps.passStep.pending());
93
+ if (followUpOf(peekPendingMarkers(pendingFile)).length === 0)
94
+ return [];
95
+ // A step that writes nothing: opening it applies the same cleanup a real run would, in memory.
96
+ return followUpOf(defaultCreateModelStep(scoped, { budget: PASS_DAY_BUDGET, dryRun: true, readOnly: true }).pending());
97
+ };
98
+ const sayPending = (markers) => {
99
+ if (markers.length === 0)
100
+ return;
101
+ const byTask = new Map();
102
+ for (const marker of markers)
103
+ byTask.set(followUpTask(marker), (byTask.get(followUpTask(marker)) ?? 0) + 1);
104
+ report.counters.pass_follow_up_pending = markers.length;
105
+ const detail = [...byTask].sort().map(([task, count]) => `${task} ${String(count)}`).join(", ");
106
+ report.notes.push(`${String(markers.length)} follow-up ${markers.length === 1 ? "item is" : "items are"} pending from earlier runs (${detail}) and ${markers.length === 1 ? "was" : "were"} not sent. To send them within the daily cap: hq ontology update --follow-up`);
107
+ };
108
+ if (isUpdate && !changed && !wantFollowUp) {
109
+ sayPending(pendingFollowUp());
110
+ return report;
111
+ }
112
+ let followUp = new Set();
113
+ if (isUpdate && !changed && pendingFollowUp().length === 0)
67
114
  return report;
68
115
  const dirtyBefore = new Set(openGraphStore(context.graphRoot, { company: context.company }).readDirty());
69
116
  const cap = options.budgetTokens;
@@ -75,9 +122,22 @@ async function replayThenPass(command, context, options, deps, run) {
75
122
  else {
76
123
  const runBudget = left === undefined ? PASS_RUN_BUDGET[command] : { inputTokens: left, outputTokens: Math.ceil(left / 2) };
77
124
  try {
78
- const make = (model) => defaultCreateModelStep(scoped, { budget: PASS_DAY_BUDGET, runBudget, concurrency: PASS_CONCURRENCY, runId: report.run, ...(deps.now ? { now: deps.now } : {}), ...(model ? { model } : {}) });
125
+ // A pass that exists only for follow-up work stays inside the daily cap of the model step (150,000 input
126
+ // tokens a day unless the run raises it), counted from the call ledger with the day's other runs.
127
+ const dayCap = resolveDayBudget(options);
128
+ const budget = isUpdate && !changed ? { inputTokens: dayCap.inputTokens, outputTokens: dayCap.outputTokens } : PASS_DAY_BUDGET;
129
+ const make = (model) => defaultCreateModelStep(scoped, { budget, runBudget, concurrency: PASS_CONCURRENCY, runId: report.run, ...(deps.now ? { now: deps.now } : {}), ...(model ? { model } : {}) });
79
130
  const step = deps.passStep ?? make();
80
131
  passStep = step;
132
+ // Opening the step dropped the markers another model had already answered: the scope is what is left.
133
+ const waiting = isUpdate ? followUpOf(step.pending()) : [];
134
+ if (wantFollowUp)
135
+ followUp = followUpScope(waiting);
136
+ const only = isUpdate ? new Set([...(report.touched ?? []), ...followUp]) : undefined;
137
+ if (only && followUp.size > 0)
138
+ report.counters.pass_follow_up_entities = followUp.size;
139
+ // A digest queued while its source was inside the window is still asked when the source has aged past it.
140
+ const keepSources = new Set(wantFollowUp ? waiting.filter((marker) => followUpTask(marker) === "digest").map((marker) => marker.itemKey) : []);
81
141
  let taskSteps = deps.passTaskSteps;
82
142
  if (!taskSteps && !deps.passStep && resolveModel(scoped) === DEFAULT_ONTOLOGY_MODEL) {
83
143
  // The cheapest model was measured wrong too often on these tasks; a member who raised the model keeps theirs.
@@ -92,8 +152,9 @@ async function replayThenPass(command, context, options, deps, run) {
92
152
  const pass = await (deps.runModelPass ?? defaultRunModelPass)(scoped, {
93
153
  step,
94
154
  day,
95
- // An update asks about what it touched; a rebuild about everything.
96
- ...(report.touched ? { only: new Set(report.touched) } : {}),
155
+ // An update asks about what it touched and what an earlier run left pending; a rebuild about everything.
156
+ ...(only ? { only } : {}),
157
+ ...(keepSources.size > 0 ? { keepSources } : {}),
97
158
  ...(taskSteps ? { taskSteps } : {}),
98
159
  summaryItems: (refs) => summaryItemsFor(openGraphStore(context.graphRoot, { company: context.company }), refs),
99
160
  });
@@ -113,6 +174,49 @@ async function replayThenPass(command, context, options, deps, run) {
113
174
  report.totals.rowsAdded += task.rowsNew;
114
175
  }
115
176
  report.counters.pass_ms = Math.round(pass.seconds * 1000);
177
+ if (only && wantFollowUp) {
178
+ // A follow-up marker inside the scope whose task ran and did not build its item again. For a profile,
179
+ // a retype or a decision group that means the graph no longer asks the question, and the marker is
180
+ // dropped, counted and named in the summary. A digest is never dropped: its source may only be off
181
+ // this machine for now. Page summaries are left to the page compiler, which sends its own.
182
+ const ran = new Set(pass.tasks.map((task) => task.task));
183
+ const seen = new Set();
184
+ for (const entry of steps)
185
+ for (const id of entry.seenItems())
186
+ seen.add(id);
187
+ const notBuilt = step.pending().filter((marker) => {
188
+ const task = followUpTask(marker);
189
+ if (!task || task === "summaries" || !ran.has(task) || seen.has(marker.id))
190
+ return false;
191
+ const refs = followUpEntities(marker);
192
+ return refs.length > 0 && refs.every((ref) => only.has(ref));
193
+ });
194
+ const dropped = new Map();
195
+ let keptDigests = 0;
196
+ for (const marker of notBuilt) {
197
+ const task = followUpTask(marker);
198
+ if (task === "digest")
199
+ keptDigests += 1;
200
+ else
201
+ dropped.set(task, [...(dropped.get(task) ?? []), marker]);
202
+ }
203
+ for (const [task, markers] of [...dropped].sort()) {
204
+ const count = step.dropPending(markers.map((marker) => marker.id));
205
+ report.counters[`pass_pending_dropped_${task}`] = count;
206
+ report.notes.push(`Dropped ${String(count)} pending ${task} ${count === 1 ? "item" : "items"}: ${DROP_REASON[task] ?? "the graph no longer builds the item"}.`);
207
+ }
208
+ if (keptDigests > 0) {
209
+ report.counters.pass_pending_digests_not_built = keptDigests;
210
+ report.notes.push(`${String(keptDigests)} pending ${keptDigests === 1 ? "digest was" : "digests were"} not built this run (the source file is not on this machine, or a signal covers the source now): kept pending, not dropped.`);
211
+ }
212
+ if (!changed) {
213
+ const sent = pass.tasks.reduce((sum, task) => sum + task.stats.calls, 0);
214
+ report.notes.push(`Nothing new; follow-up work from earlier runs was looked at again on ${String(followUp.size)} ${followUp.size === 1 ? "entity" : "entities"} (${String(sent)} model ${sent === 1 ? "call" : "calls"}).`);
215
+ }
216
+ }
217
+ else if (isUpdate) {
218
+ sayPending(followUpOf(step.pending()));
219
+ }
116
220
  if (halted)
117
221
  report.notes.push(`Model pass stopped (${halted}): what was not sent is left pending for the next run.`);
118
222
  }
@@ -123,6 +227,8 @@ async function replayThenPass(command, context, options, deps, run) {
123
227
  }
124
228
  }
125
229
  // What the pass changed joins what the replay changed, so the closing lint of an update sees both.
230
+ if (command === "update" && !report.touched)
231
+ report.touched = [];
126
232
  if (report.touched) {
127
233
  const byPass = openGraphStore(context.graphRoot, { company: context.company }).readDirty().filter((ref) => !dirtyBefore.has(ref));
128
234
  report.touched = [...new Set([...report.touched, ...byPass])].sort();