@indigoai-us/hq-cli 5.345.248 → 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 (114) hide show
  1. package/CHANGELOG.md +143 -0
  2. package/contracts/host-canary-release.json +3 -3
  3. package/dist/command-catalog.generated.d.ts +288 -9
  4. package/dist/command-catalog.generated.js +355 -9
  5. package/dist/commands/bot.js +5 -1
  6. package/dist/commands/core-job-run-native.js +4 -0
  7. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  8. package/dist/commands/core-knowledge-prefs.js +1 -16
  9. package/dist/commands/core.js +0 -2
  10. package/dist/commands/daemon.js +21 -0
  11. package/dist/commands/lanes.d.ts +2 -0
  12. package/dist/commands/lanes.js +9 -4
  13. package/dist/commands/ontology-graph.d.ts +11 -3
  14. package/dist/commands/ontology-graph.js +138 -14
  15. package/dist/commands/sources.js +26 -8
  16. package/dist/commands/sync-core.js +6 -0
  17. package/dist/fast-scaffold.js +1 -3
  18. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  19. package/dist/hq-cloud-sync-runner/package.json +1 -1
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.js +47 -0
  22. package/dist/lib/bot/fleet-cron.d.ts +2 -0
  23. package/dist/lib/bot/fleet-cron.js +5 -0
  24. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  25. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  26. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  27. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  28. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  29. package/dist/lib/daemon/machine-checks.js +10 -0
  30. package/dist/lib/daemon/run.d.ts +3 -1
  31. package/dist/lib/daemon/run.js +48 -5
  32. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  33. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  34. package/dist/lib/hook-engine/coverage.d.ts +99 -19
  35. package/dist/lib/hook-engine/coverage.js +269 -35
  36. package/dist/lib/hook-engine/native-stop-compatibility.json +9 -4
  37. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  38. package/dist/lib/hook-engine/registration-identity.js +1 -1
  39. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  40. package/dist/lib/hook-engine/resolve.js +48 -1
  41. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  42. package/dist/lib/hook-engine/stable-heal.js +214 -0
  43. package/dist/lib/hot-channels/graph-context.d.ts +26 -1
  44. package/dist/lib/hot-channels/graph-context.js +80 -10
  45. package/dist/lib/hot-channels/run.d.ts +1 -0
  46. package/dist/lib/hot-channels/signals-pass.js +9 -4
  47. package/dist/lib/ontology-graph/model/files.d.ts +4 -0
  48. package/dist/lib/ontology-graph/model/files.js +23 -0
  49. package/dist/lib/ontology-graph/model/index.d.ts +11 -1
  50. package/dist/lib/ontology-graph/model/index.js +42 -18
  51. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +9 -1
  52. package/dist/lib/ontology-graph/model/pass-tasks.js +7 -4
  53. package/dist/lib/ontology-graph/model/pass.d.ts +5 -0
  54. package/dist/lib/ontology-graph/model/pass.js +8 -8
  55. package/dist/lib/ontology-graph/model/pending-items.d.ts +31 -0
  56. package/dist/lib/ontology-graph/model/pending-items.js +113 -0
  57. package/dist/lib/ontology-graph/model/step.d.ts +48 -1
  58. package/dist/lib/ontology-graph/model/step.js +205 -36
  59. package/dist/lib/ontology-graph/model/tasks.d.ts +17 -1
  60. package/dist/lib/ontology-graph/model/tasks.js +28 -8
  61. package/dist/lib/ontology-graph/org/derive.d.ts +2 -0
  62. package/dist/lib/ontology-graph/org/derive.js +9 -2
  63. package/dist/lib/ontology-graph/org/index.d.ts +35 -6
  64. package/dist/lib/ontology-graph/org/index.js +136 -19
  65. package/dist/lib/ontology-graph/org/text.d.ts +2 -0
  66. package/dist/lib/ontology-graph/org/text.js +6 -0
  67. package/dist/lib/ontology-graph/org/types.d.ts +5 -0
  68. package/dist/lib/ontology-graph/pages/render.d.ts +2 -0
  69. package/dist/lib/ontology-graph/pages/render.js +11 -4
  70. package/dist/lib/ontology-graph/read/brief.d.ts +13 -3
  71. package/dist/lib/ontology-graph/read/brief.js +312 -62
  72. package/dist/lib/ontology-graph/read/index.d.ts +1 -1
  73. package/dist/lib/ontology-graph/read/index.js +14 -3
  74. package/dist/lib/ontology-graph/read/names.d.ts +6 -1
  75. package/dist/lib/ontology-graph/read/names.js +8 -3
  76. package/dist/lib/ontology-graph/read/reader-setting.d.ts +2 -0
  77. package/dist/lib/ontology-graph/read/reader-setting.js +4 -1
  78. package/dist/lib/ontology-graph/remodel/index.d.ts +174 -0
  79. package/dist/lib/ontology-graph/remodel/index.js +450 -0
  80. package/dist/lib/ontology-graph/replay/engine.d.ts +47 -1
  81. package/dist/lib/ontology-graph/replay/engine.js +68 -2
  82. package/dist/lib/ontology-graph/replay/index.d.ts +2 -1
  83. package/dist/lib/ontology-graph/replay/index.js +114 -8
  84. package/dist/lib/ontology-graph/schema/authority.d.ts +43 -0
  85. package/dist/lib/ontology-graph/schema/authority.js +39 -0
  86. package/dist/lib/ontology-graph/schema/index.d.ts +1 -1
  87. package/dist/lib/ontology-graph/schema/index.js +1 -1
  88. package/dist/lib/ontology-graph/setup/index.d.ts +88 -0
  89. package/dist/lib/ontology-graph/setup/index.js +489 -0
  90. package/dist/lib/ontology-graph/types.d.ts +28 -0
  91. package/dist/lib/ontology-graph/types.js +5 -0
  92. package/dist/lib/signals/failure-alert.js +4 -5
  93. package/dist/lib/signals/steps/adapters.js +3 -0
  94. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  95. package/dist/lib/sync-core/engine-holds.js +12 -2
  96. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  97. package/dist/lib/sync-core/hand-back.js +16 -2
  98. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  99. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  100. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  101. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  102. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  103. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  104. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  105. package/dist/lib/sync-core/reconcile.js +43 -3
  106. package/dist/utils/cli-telemetry.d.ts +1 -0
  107. package/dist/utils/cli-telemetry.js +6 -3
  108. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  109. package/dist/utils/hook-engine-rollup.js +725 -0
  110. package/dist/utils/sync-person.d.ts +15 -0
  111. package/dist/utils/sync-person.js +74 -0
  112. package/package.json +8 -8
  113. package/scripts/install-hook-engine.mjs +4 -0
  114. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -0,0 +1,174 @@
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 { type BatchModelStep, type PassTask } from "../model/index.js";
34
+ import { compilePages as defaultCompilePages } from "../pages/index.js";
35
+ import { briefCommand as defaultBriefCommand } from "../read/index.js";
36
+ import { type AudienceKey, type CommandOutput, type EntityRef, type GraphContext, type IsoDate, type MemberIdentity, type ModelRunner, type Origin, type RowId, type SourceRef } from "../types.js";
37
+ export interface RemodelOptions {
38
+ /** The model whose rows to replace: `haiku`, or `agent:haiku`. */
39
+ from: string;
40
+ /**
41
+ * Fact fields and verbs that pick what is asked again (`role_title`, `affiliation`, `works_at`). Default: every
42
+ * kind. An item is asked as a whole, so every row the old model wrote from the same source or the same profile
43
+ * is replaced with the rows that were picked.
44
+ */
45
+ kinds?: readonly string[];
46
+ /** Cap on model input tokens for this run. */
47
+ budgetTokens?: number;
48
+ /** The daily cap for this run, as on `update` (`--max-input-tokens`, `--max-output-tokens`). */
49
+ maxInputTokens?: number;
50
+ maxOutputTokens?: number;
51
+ /** Count and estimate; call no model and write nothing. */
52
+ dryRun: boolean;
53
+ }
54
+ /** Seams for tests. Production passes nothing. */
55
+ export interface RemodelDeps {
56
+ runner?: ModelRunner;
57
+ /** The step to ask through. Default: a step on the configured model with the run's caps. */
58
+ step?: BatchModelStep;
59
+ now?: () => Date;
60
+ env?: NodeJS.ProcessEnv;
61
+ resolveMember?: (context: GraphContext) => MemberIdentity | null;
62
+ compilePages?: typeof defaultCompilePages | null;
63
+ brief?: typeof defaultBriefCommand | null;
64
+ /** Called after the old rows are closed and before the new ones are written. A test throws here, as a kill would. */
65
+ afterClose?: () => void;
66
+ }
67
+ /** Where a run writes what it is about to close and write, relative to the graph folder. */
68
+ export declare const REMODEL_INTENT_RELATIVE = ".state/remodel-intent.json";
69
+ interface IntentClosure {
70
+ entity: EntityRef;
71
+ audience: AudienceKey;
72
+ id: RowId;
73
+ on: IsoDate;
74
+ by: SourceRef;
75
+ /** The items of the pass that cover the row (`itemKeys`). */
76
+ items: string[];
77
+ /** The other end of a relationship, closed and reopened with it. */
78
+ inverse?: {
79
+ entity: EntityRef;
80
+ id: RowId;
81
+ };
82
+ }
83
+ /** What one run is about to close and write. On file from before the first row is closed until the last row is written. */
84
+ export interface RemodelIntent {
85
+ version: 1;
86
+ run: string;
87
+ from: Origin;
88
+ model: string;
89
+ day: IsoDate;
90
+ tasks: PassTask[];
91
+ only: EntityRef[];
92
+ closures: IntentClosure[];
93
+ /** Set when the run is complete. A file with it is history, not work to finish. */
94
+ finished?: string;
95
+ }
96
+ /** 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. */
97
+ export declare function readUnfinishedRemodel(graphRoot: string): RemodelIntent | null;
98
+ /** Thrown for a request the command cannot carry out as given. */
99
+ export declare class RemodelUsageError extends Error {
100
+ constructor(message: string);
101
+ }
102
+ export interface RemodelReport {
103
+ from: Origin;
104
+ /** The model asked now. */
105
+ model: string;
106
+ day: IsoDate;
107
+ dryRun: boolean;
108
+ kinds: string[];
109
+ rows: {
110
+ /** Open fact and relationship rows by the old model (and of the kinds asked for), both ends of a relationship counted. */
111
+ open: number;
112
+ byKind: Record<string, number>;
113
+ /** Of those, rows the pass wrote as a digest or a profile: the ones this command can ask about again. */
114
+ askable: number;
115
+ /** Rows with no record of the task that wrote them: the replay's typed relationships and extractions. */
116
+ noRecord: number;
117
+ /** Rows of a task that cannot be asked again from the graph (retyped edges, decision supersessions). */
118
+ otherTask: number;
119
+ /** With `kinds`: rows of other kinds that the same items wrote, replaced with them. */
120
+ sameItem: number;
121
+ };
122
+ /** Items (one source to digest, one entity to profile) behind the askable rows. */
123
+ items: {
124
+ total: number;
125
+ byTask: Partial<Record<PassTask, number>>;
126
+ answered: number;
127
+ cached: number;
128
+ pending: number;
129
+ };
130
+ /** Dry run: what asking would send. Input tokens are an estimate from the size of the turns. */
131
+ estimate?: {
132
+ itemsToSend: number;
133
+ inputTokens: number;
134
+ };
135
+ /** Rows of answered items, closed. Both ends of a relationship counted. */
136
+ closed: number;
137
+ /** Closed rows the new model stated again (same field, or same relationship). */
138
+ replaced: number;
139
+ /** Closed rows the new model did not state again when it read the same source. */
140
+ notRestated: number;
141
+ /** Askable rows whose item was not answered in this run (budget, usage limit): still open. */
142
+ leftOpen: number;
143
+ rowsAdded: number;
144
+ usage: {
145
+ inputTokens: number;
146
+ outputTokens: number;
147
+ calls: number;
148
+ };
149
+ /** Rows closed for an item that turned out to have no usable answer when the new rows were written: open again. */
150
+ reopened: number;
151
+ /** An earlier run that was interrupted between closing and writing, finished by this one before anything else. */
152
+ resumed?: {
153
+ run: string;
154
+ from: Origin;
155
+ model: string;
156
+ closed: number;
157
+ rowsAdded: number;
158
+ reopened: number;
159
+ };
160
+ cap: {
161
+ dayInputTokens: number;
162
+ dayOutputTokens: number;
163
+ overridden: boolean;
164
+ runInputTokens?: number;
165
+ };
166
+ halted: string | null;
167
+ notes: string[];
168
+ }
169
+ export declare function runRemodel(context: GraphContext, options: RemodelOptions, deps?: RemodelDeps): Promise<RemodelReport>;
170
+ export declare function formatRemodelReport(report: RemodelReport): string;
171
+ /** `hq ontology remodel`. */
172
+ export declare function remodelCommand(context: GraphContext, options: RemodelOptions, deps?: RemodelDeps): Promise<CommandOutput>;
173
+ export {};
174
+ //# sourceMappingURL=index.d.ts.map
@@ -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