@indigoai-us/hq-cli 5.345.248 → 5.345.250

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 (79) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/contracts/host-canary-release.json +3 -3
  3. package/dist/command-catalog.generated.d.ts +93 -8
  4. package/dist/command-catalog.generated.js +114 -8
  5. package/dist/commands/core-job-run-native.js +4 -0
  6. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  7. package/dist/commands/core-knowledge-prefs.js +1 -16
  8. package/dist/commands/core.js +0 -2
  9. package/dist/commands/daemon.js +21 -0
  10. package/dist/commands/ontology-graph.d.ts +2 -1
  11. package/dist/commands/ontology-graph.js +41 -10
  12. package/dist/commands/sync-core.js +6 -0
  13. package/dist/fast-scaffold.js +1 -3
  14. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  15. package/dist/hq-cloud-sync-runner/package.json +1 -1
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.js +47 -0
  18. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  19. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  20. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  21. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  22. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  23. package/dist/lib/daemon/machine-checks.js +10 -0
  24. package/dist/lib/daemon/run.d.ts +3 -1
  25. package/dist/lib/daemon/run.js +48 -5
  26. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  27. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  28. package/dist/lib/hook-engine/coverage.d.ts +82 -13
  29. package/dist/lib/hook-engine/coverage.js +214 -18
  30. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  31. package/dist/lib/hook-engine/registration-identity.js +1 -1
  32. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  33. package/dist/lib/hook-engine/resolve.js +48 -1
  34. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  35. package/dist/lib/hook-engine/stable-heal.js +214 -0
  36. package/dist/lib/hot-channels/graph-context.js +4 -1
  37. package/dist/lib/ontology-graph/model/step.d.ts +2 -0
  38. package/dist/lib/ontology-graph/model/step.js +3 -0
  39. package/dist/lib/ontology-graph/org/derive.d.ts +2 -0
  40. package/dist/lib/ontology-graph/org/derive.js +9 -2
  41. package/dist/lib/ontology-graph/org/index.d.ts +35 -6
  42. package/dist/lib/ontology-graph/org/index.js +136 -19
  43. package/dist/lib/ontology-graph/org/text.d.ts +2 -0
  44. package/dist/lib/ontology-graph/org/text.js +6 -0
  45. package/dist/lib/ontology-graph/org/types.d.ts +5 -0
  46. package/dist/lib/ontology-graph/pages/render.d.ts +2 -0
  47. package/dist/lib/ontology-graph/pages/render.js +10 -4
  48. package/dist/lib/ontology-graph/read/brief.js +4 -1
  49. package/dist/lib/ontology-graph/read/index.js +13 -2
  50. package/dist/lib/ontology-graph/read/names.d.ts +6 -1
  51. package/dist/lib/ontology-graph/read/names.js +8 -3
  52. package/dist/lib/ontology-graph/replay/engine.d.ts +47 -1
  53. package/dist/lib/ontology-graph/replay/engine.js +68 -2
  54. package/dist/lib/ontology-graph/replay/index.d.ts +2 -1
  55. package/dist/lib/ontology-graph/replay/index.js +1 -1
  56. package/dist/lib/ontology-graph/schema/authority.d.ts +34 -0
  57. package/dist/lib/ontology-graph/schema/authority.js +29 -0
  58. package/dist/lib/ontology-graph/schema/index.d.ts +1 -1
  59. package/dist/lib/ontology-graph/schema/index.js +1 -1
  60. package/dist/lib/ontology-graph/types.d.ts +7 -0
  61. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  62. package/dist/lib/sync-core/engine-holds.js +12 -2
  63. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  64. package/dist/lib/sync-core/hand-back.js +16 -2
  65. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  66. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  67. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  68. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  69. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  70. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  71. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  72. package/dist/lib/sync-core/reconcile.js +43 -3
  73. package/dist/utils/cli-telemetry.d.ts +1 -0
  74. package/dist/utils/cli-telemetry.js +6 -3
  75. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  76. package/dist/utils/hook-engine-rollup.js +725 -0
  77. package/package.json +8 -8
  78. package/scripts/install-hook-engine.mjs +4 -0
  79. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -431,6 +431,11 @@ export interface OrgOptions {
431
431
  asOf?: IsoDate;
432
432
  /** Phrase each active person's role with one small model call. Default false. */
433
433
  model?: boolean;
434
+ /**
435
+ * Also show role lines, who appears to direct whom and stated claims. Default false:
436
+ * the output is about what people do, not about roles or reporting lines.
437
+ */
438
+ roles?: boolean;
434
439
  /** Write the derived rows. Default false: every command only prints unless this is set. */
435
440
  write?: boolean;
436
441
  /** Fold name variants of a roster member into that member. Default true. */
@@ -77,6 +77,8 @@ export interface PageModel {
77
77
  };
78
78
  /** Open legacy reference edges (`related_to`, `mentions`) left off the page. */
79
79
  hiddenEdges: number;
80
+ /** Open role and affiliation facts a model wrote under the confidence line, left off the page. */
81
+ leftOutGuesses: number;
80
82
  /** Closed F and E rows, hidden unless `showClosed`. */
81
83
  closedHidden: number;
82
84
  conflicts: PageConflict[];
@@ -17,7 +17,7 @@
17
17
  * mixes rows of two audiences.
18
18
  */
19
19
  import yaml from "js-yaml";
20
- import { effectiveFacts, escapeText, formatConf, isOpen, isSingleValued, originTier } from "../schema/index.js";
20
+ import { dropUnverifiedGuesses, effectiveFacts, escapeText, formatConf, isOpen, isSingleValued, originTier } from "../schema/index.js";
21
21
  import { sha256Hex } from "../model/files.js";
22
22
  export const DEFAULT_PAGE_LIMITS = {
23
23
  edgesPerVerb: 25, timeline: 30, summarySentences: 6, recentDays: 30, decisions: 12, commitments: 12, showClosed: false,
@@ -145,7 +145,11 @@ export function buildPageModel(schema, entity, storedRows, nameOf, limits = DEFA
145
145
  if (!known || audienceRank(stored.audience) < audienceRank(known.audience))
146
146
  unique.set(stored.id, stored);
147
147
  }
148
- const rows = [...unique.values()];
148
+ // An open role or affiliation a model wrote at low confidence is left off the page before any winner or
149
+ // conflict is worked out, and counted in the frontmatter. Row counts still count every row. Relationships
150
+ // stay: each relationship line names who wrote it, and a customer's contact list is built from them.
151
+ const everyRow = [...unique.values()];
152
+ const { rows, leftOut: leftOutGuesses } = dropUnverifiedGuesses(everyRow);
149
153
  const audiences = [...new Set(storedRows.map((stored) => stored.audience))].sort();
150
154
  const type = entity.type;
151
155
  const name = entity.canonical_name;
@@ -477,11 +481,12 @@ export function buildPageModel(schema, entity, storedRows, nameOf, limits = DEFA
477
481
  timelineTotal: allEntries.length,
478
482
  signals: timelineRows.length,
479
483
  counts: {
480
- facts: rows.filter((stored) => stored.row.kind === "F").length,
481
- edges: rows.filter((stored) => stored.row.kind === "E").length,
484
+ facts: everyRow.filter((stored) => stored.row.kind === "F").length,
485
+ edges: everyRow.filter((stored) => stored.row.kind === "E").length,
482
486
  timeline: timelineRows.length,
483
487
  },
484
488
  hiddenEdges,
489
+ leftOutGuesses,
485
490
  closedHidden: limits.showClosed ? 0 : closedRows.length,
486
491
  conflicts,
487
492
  rulesSummary: summary,
@@ -655,6 +660,7 @@ export function renderPage(model, nameOf, summary, state = "rules") {
655
660
  summary_by: summary ? summary.by : "rules",
656
661
  ...(summary ? {} : state === "rules" ? {} : { model_summary: state }),
657
662
  ...(model.hiddenEdges > 0 ? { hidden_legacy_reference_edges: model.hiddenEdges } : {}),
663
+ ...(model.leftOutGuesses > 0 ? { unconfirmed_model_guesses_left_out: model.leftOutGuesses } : {}),
658
664
  ...(model.closedHidden > 0 ? { closed_rows_hidden: model.closedHidden } : {}),
659
665
  ...(model.conflicts.length > 0 ? { conflicts: model.conflicts.map((conflict) => conflict.key).sort() } : {}),
660
666
  rows_hash: model.rowsHash,
@@ -10,7 +10,7 @@
10
10
  * `BRIEF_MAX_TOKENS` by a character estimate that overstates the count, and
11
11
  * by dropping list lines from the longest section until it fits.
12
12
  */
13
- import { originTier } from "../schema/index.js";
13
+ import { isUnverifiedGuess, originTier } from "../schema/index.js";
14
14
  import { GRAPH_PATHS, atomicWriteFile, graphPath, openGraphStore } from "../store/index.js";
15
15
  import { COMPANY_AUDIENCE, } from "../types.js";
16
16
  import { graphExists, loadReadIndex, rowVisible, visible, } from "./graph-index.js";
@@ -201,6 +201,9 @@ export function buildBrief(context, extras = {}) {
201
201
  continue;
202
202
  if (!rowVisible(entry.a, filter) || entry.row.by === "legacy")
203
203
  continue;
204
+ // A model's low-confidence guess at a role or affiliation is not reported as a change either.
205
+ if (isUnverifiedGuess(entry.row))
206
+ continue;
204
207
  if (entry.row.valid.from < cutoff || entry.row.valid.from > today)
205
208
  continue;
206
209
  if (schema.entity_types[entity.type].facts[entry.row.field]?.cardinality !== "single")
@@ -25,7 +25,7 @@
25
25
  import * as fs from "node:fs";
26
26
  import * as path from "node:path";
27
27
  import { filterPageLines } from "../pages/render.js";
28
- import { effectiveFacts, originTier } from "../schema/index.js";
28
+ import { dropUnverifiedGuesses, effectiveFacts, originTier, rowCoversDay } from "../schema/index.js";
29
29
  import { openGraphStore, pageFile } from "../store/index.js";
30
30
  import { COMPANY_AUDIENCE, } from "../types.js";
31
31
  import { graphExists, loadReadIndex, visible, } from "./graph-index.js";
@@ -337,7 +337,14 @@ export async function lookupCommand(context, options) {
337
337
  const entity = answer.entity;
338
338
  if (options.page)
339
339
  return pageOutput(session, entity, answer);
340
- const rows = readRows(session, entity.id, options.asOf ? { asOf: options.asOf } : {});
340
+ const asOf = options.asOf;
341
+ // A role, an affiliation or an employer a model wrote at low confidence is a guess, not a fact. It is
342
+ // left out before the winner of a field is chosen, so it cannot hide an older established row, and counted below.
343
+ // Employer relationships are included here because lookup prints a relationship with no origin beside it.
344
+ const { rows, leftOut: guesses } = dropUnverifiedGuesses(readRows(session, entity.id, asOf ? { asOf } : {}), {
345
+ edges: true,
346
+ ...(asOf ? { live: (row) => rowCoversDay(row, asOf) } : {}),
347
+ });
341
348
  const facts = effectiveFacts(session.schema, entity.type, rows, options.asOf);
342
349
  const live = options.asOf ? visibleEdges(session, rows) : visibleEdges(session, rows).filter((stored) => !stored.row.valid.to);
343
350
  // Relationships only. Appearing in the same meeting or decision is counted below, not listed as an edge.
@@ -362,6 +369,9 @@ export async function lookupCommand(context, options) {
362
369
  else {
363
370
  lines.push("facts: none recorded");
364
371
  }
372
+ if (guesses > 0) {
373
+ lines.push(`left out: ${String(guesses)} unconfirmed model ${guesses === 1 ? "guess" : "guesses"} at a role or affiliation. The graph does not establish the role or employer; read the sources.`);
374
+ }
365
375
  if (shown.length > 0) {
366
376
  lines.push(`edges (${String(shown.length)} of ${String(edges.length)}):`);
367
377
  for (const stored of shown)
@@ -405,6 +415,7 @@ export async function lookupCommand(context, options) {
405
415
  recent: recent.map((stored) => ({ date: stored.row.date, type: stored.row.signalType, text: stored.row.text, src: stored.row.src, ...fileJson(session, stored.row.src), audience: stored.audience })),
406
416
  timelineTotal: timeline.length,
407
417
  thin,
418
+ ...(guesses > 0 ? { leftOutGuesses: guesses } : {}),
408
419
  },
409
420
  };
410
421
  }
@@ -39,6 +39,11 @@ export interface SearchIndexOptions {
39
39
  * somewhere on the entity (name, alias, key or one open fact) to count.
40
40
  */
41
41
  export declare function searchIndex(index: ReadIndex, _schema: GraphSchema, text: string, options: SearchIndexOptions): SearchHit[];
42
- /** The facts that answer "what is true" for one indexed entity, limited to the allowed audiences. */
42
+ /**
43
+ * The facts that answer "what is true" for one indexed entity, limited to the allowed audiences.
44
+ * A model's low-confidence guess at a role or affiliation is left out before the winner of a
45
+ * field is chosen, so every reader built on this (lookup's candidates, the brief, the signals
46
+ * graph context) shows the established row or nothing.
47
+ */
43
48
  export declare function indexedFacts(index: ReadIndex, schema: GraphSchema, entity: IndexedEntity, filter: AudienceFilter): StoredRow<FactRow>[];
44
49
  //# sourceMappingURL=names.d.ts.map
@@ -11,7 +11,7 @@
11
11
  * `searchIndex` is the keyword and fuzzy search over names, aliases, identity
12
12
  * keys and open facts.
13
13
  */
14
- import { effectiveFacts, isEntityRef, slugify } from "../schema/index.js";
14
+ import { dropUnverifiedGuesses, effectiveFacts, isEntityRef, slugify } from "../schema/index.js";
15
15
  import { createResolver } from "../resolve/index.js";
16
16
  import { GRAPH_ENTITY_TYPES, } from "../types.js";
17
17
  import { allKeys, normalizeName, rowVisible, visible, } from "./graph-index.js";
@@ -276,7 +276,12 @@ export function searchIndex(index, _schema, text, options) {
276
276
  .sort((a, b) => b.score - a.score || b.entity.rows - a.entity.rows || (a.entity.id < b.entity.id ? -1 : 1))
277
277
  .slice(0, limit);
278
278
  }
279
- /** The facts that answer "what is true" for one indexed entity, limited to the allowed audiences. */
279
+ /**
280
+ * The facts that answer "what is true" for one indexed entity, limited to the allowed audiences.
281
+ * A model's low-confidence guess at a role or affiliation is left out before the winner of a
282
+ * field is chosen, so every reader built on this (lookup's candidates, the brief, the signals
283
+ * graph context) shows the established row or nothing.
284
+ */
280
285
  export function indexedFacts(index, schema, entity, filter) {
281
286
  const position = index.byId.get(entity.id);
282
287
  if (position === undefined)
@@ -287,6 +292,6 @@ export function indexedFacts(index, schema, entity, filter) {
287
292
  if (entry && rowVisible(entry.a, filter))
288
293
  rows.push({ id: entry.id, entity: entity.id, audience: entry.a, row: entry.row });
289
294
  }
290
- return effectiveFacts(schema, entity.type, rows);
295
+ return effectiveFacts(schema, entity.type, dropUnverifiedGuesses(rows).rows);
291
296
  }
292
297
  //# sourceMappingURL=names.js.map
@@ -1,6 +1,6 @@
1
1
  import { importLegacy as defaultImportLegacy } from "../legacy/index.js";
2
2
  import { compilePages as defaultCompilePages } from "../pages/index.js";
3
- import { type AudienceKey, type EntityRef, type GraphContext, type GraphSchema, type GraphStore, type IngestRow, type IsoDate, type LegacyImportResult, type MemberIdentity, type Contradiction, type ModelStep, type Origin, type RebuildOptions, type ReplayRunResult, type Resolver, type RuleExtractor, type SourceRef, type UpdateOptions } from "../types.js";
3
+ import { type AudienceKey, type EntityRef, type GraphContext, type GraphSchema, type GraphStore, type IngestRow, type IsoDate, type LegacyImportResult, type MemberIdentity, type Contradiction, type ModelRunner, type ModelStep, type Origin, type RebuildOptions, type ReplayRunResult, type Resolver, type RuleExtractor, type SourceRef, type UpdateOptions } from "../types.js";
4
4
  import { briefCommand as defaultBriefCommand } from "../read/index.js";
5
5
  import { type ClassedInput, type Corpus } from "./readers.js";
6
6
  export declare const TYPING_PROMPT_VERSION = "replay-typing-v1";
@@ -12,6 +12,46 @@ export declare const LISTING_MANIFEST_RELATIVE: string;
12
12
  export declare const NO_MODEL_ENV = "HQ_ONTOLOGY_REPLAY_NO_MODEL";
13
13
  /** Set to 1 to make `update` list the whole corpus again (the same as `--full-listing`). */
14
14
  export declare const FULL_LISTING_ENV = "HQ_ONTOLOGY_REPLAY_FULL_LISTING";
15
+ /** The model step's cap per day. The scheduled daily run uses exactly this; one run can raise it (`resolveDayBudget`). */
16
+ export declare const DEFAULT_DAY_BUDGET: {
17
+ readonly inputTokens: 150000;
18
+ readonly outputTokens: 20000;
19
+ };
20
+ /** Thrown for a daily cap that is not a whole number of 1 or more. */
21
+ export declare class DayBudgetError extends RangeError {
22
+ constructor(name: string, value: unknown);
23
+ }
24
+ /**
25
+ * The daily cap a run uses: the defaults, with either side replaced by the
26
+ * run's own `maxInputTokens` / `maxOutputTokens`. Absent options change
27
+ * nothing. Zero, a negative, a fraction or a non-number is refused: switching
28
+ * the model off is `--no-model`, not a cap of zero.
29
+ */
30
+ export declare function resolveDayBudget(options?: {
31
+ maxInputTokens?: number;
32
+ maxOutputTokens?: number;
33
+ }): {
34
+ inputTokens: number;
35
+ outputTokens: number;
36
+ overridden: boolean;
37
+ };
38
+ /** What the run's model step was allowed, what it used, and whether a cap stopped it. */
39
+ export interface ModelCapReport {
40
+ /** The cap per day this run ran under. */
41
+ dayInputTokens: number;
42
+ dayOutputTokens: number;
43
+ /** True when the run raised or lowered the default cap. */
44
+ overridden: boolean;
45
+ /** Tokens this run's model step used (not the day's earlier runs). */
46
+ usedInputTokens: number;
47
+ usedOutputTokens: number;
48
+ /** Items left pending because the daily cap was reached. */
49
+ pendingAtDayCap: number;
50
+ /** Items left pending because the run's own budget (`--budget-tokens`) was reached. */
51
+ pendingAtRunBudget: number;
52
+ /** Items left pending for any other reason (usage limit, sign-out, timeout, provider error). */
53
+ pendingOther: number;
54
+ }
15
55
  /** Seams for tests. Production passes nothing. */
16
56
  export interface ReplayDeps {
17
57
  now?: () => Date;
@@ -20,6 +60,8 @@ export interface ReplayDeps {
20
60
  /** Builds the resolver once the legacy import is done. Default: WP-C's `createResolver`. */
21
61
  createResolver?: (store: GraphStore, schema: GraphSchema) => Resolver;
22
62
  modelStep?: ModelStep | null;
63
+ /** Runner for the step the engine creates itself (when `modelStep` is not given). Default: the `claude -p` turn. */
64
+ modelRunner?: ModelRunner;
23
65
  /** Model name stamped on `by agent:<model>` rows. */
24
66
  modelName?: string;
25
67
  importLegacy?: typeof defaultImportLegacy | null;
@@ -83,6 +125,8 @@ export interface ReplayReport extends ReplayRunResult {
83
125
  wallMs: number;
84
126
  counters: Record<string, number>;
85
127
  notes: string[];
128
+ /** Present when the run had a model step that reports totals. */
129
+ modelCap?: ModelCapReport;
86
130
  }
87
131
  interface TypingItem {
88
132
  ref: SourceRef;
@@ -95,6 +139,8 @@ interface TypingItem {
95
139
  export declare function parseTypingReply(reply: string, items: readonly TypingItem[], learned: IsoDate, by: Origin): IngestRow[];
96
140
  export declare function runRebuildWith(context: GraphContext, options: RebuildOptions, deps?: ReplayDeps): Promise<ReplayReport>;
97
141
  export declare function runUpdateWith(context: GraphContext, options: UpdateOptions, deps?: ReplayDeps): Promise<ReplayReport>;
142
+ /** The lines of the run summary that say what the model step was allowed, what it used and why it stopped. */
143
+ export declare function modelCapLines(cap: ModelCapReport): string[];
98
144
  export declare function formatReport(report: ReplayReport): string;
99
145
  export {};
100
146
  //# sourceMappingURL=engine.d.ts.map
@@ -53,7 +53,33 @@ export const NO_MODEL_ENV = "HQ_ONTOLOGY_REPLAY_NO_MODEL";
53
53
  export const FULL_LISTING_ENV = "HQ_ONTOLOGY_REPLAY_FULL_LISTING";
54
54
  /** Sources with no signals sent to the model per replayed day, at most. */
55
55
  const EXTRACT_SOURCES_PER_DAY = 12;
56
- const DEFAULT_DAY_BUDGET = { inputTokens: 150_000, outputTokens: 20_000 };
56
+ /** The model step's cap per day. The scheduled daily run uses exactly this; one run can raise it (`resolveDayBudget`). */
57
+ export const DEFAULT_DAY_BUDGET = { inputTokens: 150_000, outputTokens: 20_000 };
58
+ /** Thrown for a daily cap that is not a whole number of 1 or more. */
59
+ export class DayBudgetError extends RangeError {
60
+ constructor(name, value) {
61
+ super(`${name} must be a whole number of 1 or more, got ${String(value)}`);
62
+ this.name = "DayBudgetError";
63
+ }
64
+ }
65
+ /**
66
+ * The daily cap a run uses: the defaults, with either side replaced by the
67
+ * run's own `maxInputTokens` / `maxOutputTokens`. Absent options change
68
+ * nothing. Zero, a negative, a fraction or a non-number is refused: switching
69
+ * the model off is `--no-model`, not a cap of zero.
70
+ */
71
+ export function resolveDayBudget(options = {}) {
72
+ const check = (name, value, fallback) => {
73
+ if (value === undefined)
74
+ return fallback;
75
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
76
+ throw new DayBudgetError(name, value);
77
+ return value;
78
+ };
79
+ const inputTokens = check("maxInputTokens", options.maxInputTokens, DEFAULT_DAY_BUDGET.inputTokens);
80
+ const outputTokens = check("maxOutputTokens", options.maxOutputTokens, DEFAULT_DAY_BUDGET.outputTokens);
81
+ return { inputTokens, outputTokens, overridden: options.maxInputTokens !== undefined || options.maxOutputTokens !== undefined };
82
+ }
57
83
  const MAX_IDENTITY_PASSES = 3;
58
84
  function fuzzyHooks(resolver) {
59
85
  return typeof resolver.setAdjudication === "function" ? resolver : null;
@@ -286,6 +312,8 @@ async function runReplay(command, context, options, deps) {
286
312
  context = withMember(context, deps.resolveMember ?? ((ctx) => resolveSignedInMemberFrom(ctx, env)));
287
313
  if (!context.member)
288
314
  throw new MemberIdentityRequiredError(command);
315
+ // Refused before anything is read or written.
316
+ const dayBudget = resolveDayBudget(options);
289
317
  const memberUid = context.member.personUid;
290
318
  const now = deps.now ?? (() => new Date());
291
319
  const started = Date.now();
@@ -503,7 +531,8 @@ async function runReplay(command, context, options, deps) {
503
531
  if (deps.modelStep === undefined && !modelOff) {
504
532
  try {
505
533
  model = defaultCreateModelStep(effective, {
506
- budget: DEFAULT_DAY_BUDGET,
534
+ budget: { inputTokens: dayBudget.inputTokens, outputTokens: dayBudget.outputTokens },
535
+ ...(deps.modelRunner ? { runner: deps.modelRunner } : {}),
507
536
  ...(budgetTokens ? { runBudget: { inputTokens: budgetTokens, outputTokens: Math.ceil(budgetTokens / 7.5) } } : {}),
508
537
  dryRun: options.dryRun,
509
538
  runId: run,
@@ -1118,6 +1147,23 @@ async function runReplay(command, context, options, deps) {
1118
1147
  bump("resolver_memo_hits", resolver.calls.memoHits);
1119
1148
  bump("resolver_resolved", resolver.calls.resolved);
1120
1149
  const totals = sumTotals([...entriesBefore, ...entries]);
1150
+ let modelCap;
1151
+ if (batchStep) {
1152
+ const stepTotals = batchStep.totals();
1153
+ const byReason = stepTotals.pendingByReason;
1154
+ const atDayCap = byReason["budget-day"] ?? 0;
1155
+ const atRunBudget = byReason["budget-run"] ?? 0;
1156
+ modelCap = {
1157
+ dayInputTokens: dayBudget.inputTokens,
1158
+ dayOutputTokens: dayBudget.outputTokens,
1159
+ overridden: dayBudget.overridden,
1160
+ usedInputTokens: stepTotals.used.inputTokens,
1161
+ usedOutputTokens: stepTotals.used.outputTokens,
1162
+ pendingAtDayCap: atDayCap,
1163
+ pendingAtRunBudget: atRunBudget,
1164
+ pendingOther: Math.max(0, stepTotals.pending - atDayCap - atRunBudget),
1165
+ };
1166
+ }
1121
1167
  return {
1122
1168
  run, command, days: entries.length,
1123
1169
  ...(entries.length > 0 ? { firstDay: entries[0].day, lastDay: entries[entries.length - 1].day } : {}),
@@ -1127,6 +1173,7 @@ async function runReplay(command, context, options, deps) {
1127
1173
  inputs: [...plan.values()].reduce((sum, bucket) => sum + bucket.length, 0),
1128
1174
  inputsByClass: corpus.stats.listed, excluded: corpus.stats.excluded, scanMs: corpus.stats.scanMs,
1129
1175
  wallMs: Date.now() - started, counters, notes,
1176
+ ...(modelCap ? { modelCap } : {}),
1130
1177
  ...(command === "update" ? { touched: [...touchedByRun].sort() } : {}),
1131
1178
  };
1132
1179
  }
@@ -1148,8 +1195,25 @@ export function runUpdateWith(context, options, deps = {}) {
1148
1195
  ...(options.noModel ? { noModel: true } : {}),
1149
1196
  ...(options.fullListing ? { fullListing: true } : {}),
1150
1197
  ...(options.input ? { input: options.input } : {}),
1198
+ ...(options.maxInputTokens !== undefined ? { maxInputTokens: options.maxInputTokens } : {}),
1199
+ ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),
1151
1200
  }, deps);
1152
1201
  }
1202
+ /** The lines of the run summary that say what the model step was allowed, what it used and why it stopped. */
1203
+ export function modelCapLines(cap) {
1204
+ const count = (n) => `${String(n)} item${n === 1 ? "" : "s"}`;
1205
+ const lines = [
1206
+ `model cap per day: in ${String(cap.dayInputTokens)} out ${String(cap.dayOutputTokens)} (${cap.overridden ? "set for this run" : "default"}); this run used in ${String(cap.usedInputTokens)} out ${String(cap.usedOutputTokens)}`,
1207
+ ];
1208
+ if (cap.pendingAtDayCap > 0) {
1209
+ lines.push(`stopped at the daily cap; ${count(cap.pendingAtDayCap)} pending. The next day's run carries on, or raise the cap for one run: hq ontology update --max-input-tokens <n> --max-output-tokens <n>`);
1210
+ }
1211
+ if (cap.pendingAtRunBudget > 0)
1212
+ lines.push(`stopped at the run budget (--budget-tokens); ${count(cap.pendingAtRunBudget)} pending. The next run carries on.`);
1213
+ if (cap.pendingOther > 0)
1214
+ lines.push(`${count(cap.pendingOther)} pending for another reason (usage limit, sign-out, timeout or provider error). The next run sends them again.`);
1215
+ return lines;
1216
+ }
1153
1217
  export function formatReport(report) {
1154
1218
  const lines = [
1155
1219
  `${report.command}${report.dryRun ? " (dry run, nothing written)" : ""}: ${report.days} day${report.days === 1 ? "" : "s"}${report.firstDay ? ` (${report.firstDay} to ${report.lastDay})` : ""}, ${report.inputs} inputs`,
@@ -1165,6 +1229,8 @@ export function formatReport(report) {
1165
1229
  const excluded = Object.entries(report.excluded).filter(([, value]) => value > 0);
1166
1230
  if (excluded.length > 0)
1167
1231
  lines.push(`left out: ${excluded.map(([reason, value]) => `${reason} ${value}`).join(", ")}`);
1232
+ if (report.modelCap)
1233
+ lines.push(...modelCapLines(report.modelCap));
1168
1234
  if (report.partial)
1169
1235
  lines.push(`stopped early: ${report.stoppedBecause ?? "unknown"}. Run again with --resume.`);
1170
1236
  for (const note of report.notes)
@@ -13,7 +13,8 @@ export { loadReplayConfig, REPLAY_CONFIG_RELATIVE } from "./config.js";
13
13
  export type { ReplayConfig } from "./config.js";
14
14
  export { resolveMemberScope } from "./scope.js";
15
15
  export type { MemberScope } from "./scope.js";
16
- export { FULL_LISTING_ENV, LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, PENDING_RELATIVE, TYPING_PROMPT_VERSION, formatReport, parseTypingReply } from "./engine.js";
16
+ export { DEFAULT_DAY_BUDGET, DayBudgetError, FULL_LISTING_ENV, LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, PENDING_RELATIVE, TYPING_PROMPT_VERSION, formatReport, modelCapLines, parseTypingReply, resolveDayBudget } from "./engine.js";
17
+ export type { ModelCapReport } from "./engine.js";
17
18
  export { LISTING_MANIFEST_VERSION, gitHeadCommit, openListingManifest } from "./listing-manifest.js";
18
19
  export type { ListingManifest, ListingManifestStats } from "./listing-manifest.js";
19
20
  export type { ReplayDeps, ReplayReport } from "./engine.js";
@@ -17,7 +17,7 @@ import { resolveSignedInMember, withMember } from "./member.js";
17
17
  export { scanCorpus, kindReaders, meetingSlug } from "./readers.js";
18
18
  export { loadReplayConfig, REPLAY_CONFIG_RELATIVE } from "./config.js";
19
19
  export { resolveMemberScope } from "./scope.js";
20
- export { FULL_LISTING_ENV, LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, PENDING_RELATIVE, TYPING_PROMPT_VERSION, formatReport, parseTypingReply } from "./engine.js";
20
+ export { DEFAULT_DAY_BUDGET, DayBudgetError, FULL_LISTING_ENV, LISTING_MANIFEST_RELATIVE, NO_MODEL_ENV, PENDING_RELATIVE, TYPING_PROMPT_VERSION, formatReport, modelCapLines, parseTypingReply, resolveDayBudget } from "./engine.js";
21
21
  export { LISTING_MANIFEST_VERSION, gitHeadCommit, openListingManifest } from "./listing-manifest.js";
22
22
  export { classOf, createExtractTools, registerExtractTools } from "./extractors.js";
23
23
  export { countingResolver, createFallbackResolver, nameCandidates } from "./mentions.js";
@@ -62,6 +62,40 @@ export interface SupersessionPlan {
62
62
  * incoming row is written closed on the open row's valid-from day.
63
63
  */
64
64
  export declare function planSupersession(schema: GraphSchema, entity: EntityRef, audience: AudienceKey, existing: readonly StoredRow[], incoming: Stamped): SupersessionPlan;
65
+ /** Fact fields where a model's low-confidence value reads as an established fact when printed beside record rows. */
66
+ export declare const GUESS_FIELDS: ReadonlySet<string>;
67
+ /** Relationships that say the same thing as an affiliation fact: who a person works for. */
68
+ export declare const GUESS_VERBS: ReadonlySet<string>;
69
+ /** A model row in those fields and verbs is shown as a fact only at or above this confidence. */
70
+ export declare const GUESS_CONFIDENCE_BELOW = 0.7;
71
+ export interface GuessOptions {
72
+ /**
73
+ * Also treat an employer relationship (`works_at`, `employs`) as a guess. For readers that
74
+ * print a relationship with no origin and no confidence beside it. Default false: a reader
75
+ * that prints `by agent:<model>` on the line leaves the relationship in.
76
+ */
77
+ edges?: boolean;
78
+ }
79
+ /**
80
+ * True for a role or an affiliation a model wrote (`by agent:<model>`) below the
81
+ * confidence line, and with `edges` for an employer relationship too. Record, rule,
82
+ * human and legacy rows are never guesses, whatever their confidence, and neither
83
+ * is a model row in any other field or verb.
84
+ */
85
+ export declare function isUnverifiedGuess(row: StoredRow["row"], options?: GuessOptions): boolean;
86
+ /**
87
+ * The rows a reader may present as fact: every row but the live unverified
88
+ * guesses, with how many were left out. Readers call this before they pick the
89
+ * winner of a field, so a newer guess never hides an older established row.
90
+ * `live` says which rows the reader is about to show (open rows by default; a
91
+ * reader answering for a past day passes `rowCoversDay`).
92
+ */
93
+ export declare function dropUnverifiedGuesses<T extends StoredRow>(rows: readonly T[], options?: GuessOptions & {
94
+ live?: (row: Stamped) => boolean;
95
+ }): {
96
+ rows: T[];
97
+ leftOut: number;
98
+ };
65
99
  /**
66
100
  * The facts that answer "what is true" for one entity (design 2.7): for a
67
101
  * single-valued field, the open row with the highest authority, then the
@@ -128,6 +128,35 @@ function better(a, b) {
128
128
  return a.row.conf > b.row.conf;
129
129
  return a.id < b.id;
130
130
  }
131
+ /** Fact fields where a model's low-confidence value reads as an established fact when printed beside record rows. */
132
+ export const GUESS_FIELDS = new Set(["role_title", "affiliation"]);
133
+ /** Relationships that say the same thing as an affiliation fact: who a person works for. */
134
+ export const GUESS_VERBS = new Set(["works_at", "employs"]);
135
+ /** A model row in those fields and verbs is shown as a fact only at or above this confidence. */
136
+ export const GUESS_CONFIDENCE_BELOW = 0.7;
137
+ /**
138
+ * True for a role or an affiliation a model wrote (`by agent:<model>`) below the
139
+ * confidence line, and with `edges` for an employer relationship too. Record, rule,
140
+ * human and legacy rows are never guesses, whatever their confidence, and neither
141
+ * is a model row in any other field or verb.
142
+ */
143
+ export function isUnverifiedGuess(row, options = {}) {
144
+ if (row.kind === "T" || !row.by.startsWith("agent:") || !(row.conf < GUESS_CONFIDENCE_BELOW))
145
+ return false;
146
+ return row.kind === "F" ? GUESS_FIELDS.has(row.field) : options.edges === true && GUESS_VERBS.has(row.verb);
147
+ }
148
+ /**
149
+ * The rows a reader may present as fact: every row but the live unverified
150
+ * guesses, with how many were left out. Readers call this before they pick the
151
+ * winner of a field, so a newer guess never hides an older established row.
152
+ * `live` says which rows the reader is about to show (open rows by default; a
153
+ * reader answering for a past day passes `rowCoversDay`).
154
+ */
155
+ export function dropUnverifiedGuesses(rows, options = {}) {
156
+ const live = options.live ?? isOpen;
157
+ const kept = rows.filter((stored) => stored.row.kind === "T" || !isUnverifiedGuess(stored.row, options) || !live(stored.row));
158
+ return { rows: kept, leftOut: rows.length - kept.length };
159
+ }
131
160
  /**
132
161
  * The facts that answer "what is true" for one entity (design 2.7): for a
133
162
  * single-valued field, the open row with the highest authority, then the
@@ -7,6 +7,6 @@ export type { RowParseResult } from "./grammar.js";
7
7
  export { DEFAULT_SCHEMA, parseSchemaYaml, renderSchemaYaml } from "./default-schema.js";
8
8
  export { SchemaError } from "./default-schema.js";
9
9
  export { validateEntityUpsert, validateRow } from "./validate.js";
10
- export { effectiveFacts, inverseEdge, isOpen, isSingleValued, planSupersession, rowCoversDay, singleValueKey, } from "./authority.js";
10
+ export { GUESS_CONFIDENCE_BELOW, GUESS_FIELDS, GUESS_VERBS, dropUnverifiedGuesses, effectiveFacts, isUnverifiedGuess, inverseEdge, isOpen, isSingleValued, planSupersession, rowCoversDay, singleValueKey, } from "./authority.js";
11
11
  export type { SupersessionPlan } from "./authority.js";
12
12
  //# sourceMappingURL=index.d.ts.map
@@ -6,5 +6,5 @@ export { RowGrammarError, compareRows, entityRef, escapeText, formatConf, format
6
6
  export { DEFAULT_SCHEMA, parseSchemaYaml, renderSchemaYaml } from "./default-schema.js";
7
7
  export { SchemaError } from "./default-schema.js";
8
8
  export { validateEntityUpsert, validateRow } from "./validate.js";
9
- export { effectiveFacts, inverseEdge, isOpen, isSingleValued, planSupersession, rowCoversDay, singleValueKey, } from "./authority.js";
9
+ export { GUESS_CONFIDENCE_BELOW, GUESS_FIELDS, GUESS_VERBS, dropUnverifiedGuesses, effectiveFacts, isUnverifiedGuess, inverseEdge, isOpen, isSingleValued, planSupersession, rowCoversDay, singleValueKey, } from "./authority.js";
10
10
  //# sourceMappingURL=index.js.map
@@ -1125,6 +1125,13 @@ export interface UpdateOptions {
1125
1125
  noModel?: boolean;
1126
1126
  /** List the whole corpus again instead of only new and changed files (`--full-listing`). */
1127
1127
  fullListing?: boolean;
1128
+ /**
1129
+ * Cap on model input tokens per day for this run (`--max-input-tokens`). The day's earlier calls on the
1130
+ * same model count toward it. Default 150,000.
1131
+ */
1132
+ maxInputTokens?: number;
1133
+ /** Cap on model output tokens per day for this run (`--max-output-tokens`). Default 20,000. */
1134
+ maxOutputTokens?: number;
1128
1135
  dryRun: boolean;
1129
1136
  }
1130
1137
  export interface LookupOptions {
@@ -25,6 +25,6 @@ export declare function writeHandbackKeep(home: string, vault: {
25
25
  /** Test seam: runs after the temp file is written, before the re-read that guards the rename. */
26
26
  beforeRename?: (attempt: number) => void): void;
27
27
  export declare function engineHoldFile(engineHome: string, vaultUid: string): string;
28
- export declare function readEngineHeldDeletes(engineHome: string, vaultUid: string): EngineHeldDeletes | "unreadable" | null;
28
+ export declare function readEngineHeldDeletes(engineHome: string, vaultUid: string, warn?: (line: string) => void): EngineHeldDeletes | "unreadable" | null;
29
29
  export declare function heldDeletesHandoverLine(vaultUid: string, held: EngineHeldDeletes | "unreadable", engineHome: string, home: string): string;
30
30
  //# sourceMappingURL=engine-holds.d.ts.map
@@ -78,7 +78,7 @@ function readTextOrNull(file) {
78
78
  export function engineHoldFile(engineHome, vaultUid) {
79
79
  return path.join(engineHome, ".hq", "sync-core", "holds", `${vaultUid}.json`);
80
80
  }
81
- export function readEngineHeldDeletes(engineHome, vaultUid) {
81
+ export function readEngineHeldDeletes(engineHome, vaultUid, warn = () => { }) {
82
82
  let text;
83
83
  try {
84
84
  const file = engineHoldFile(engineHome, vaultUid);
@@ -100,11 +100,21 @@ export function readEngineHeldDeletes(engineHome, vaultUid) {
100
100
  if (!hold || !Array.isArray(hold.groups))
101
101
  return "unreadable";
102
102
  const deletes = [];
103
+ const unknown = new Set();
103
104
  let count = 0;
104
105
  for (const value of hold.groups) {
105
106
  const group = record(value);
106
- if (!group || (group.direction !== "delete_local" && group.direction !== "delete_remote"))
107
+ if (!group || typeof group.direction !== "string")
107
108
  return "unreadable";
109
+ if (group.direction === "overwrite_local")
110
+ continue;
111
+ if (group.direction !== "delete_local" && group.direction !== "delete_remote") {
112
+ if (!unknown.has(group.direction)) {
113
+ unknown.add(group.direction);
114
+ warn(`${vaultUid}: the new sync engine's hold file ${engineHoldFile(engineHome, vaultUid)} has a kind of hold this hq does not know (direction ${JSON.stringify(group.direction.slice(0, 64))}); it is not passed to the current sync, the deletes held beside it are`);
115
+ }
116
+ continue;
117
+ }
108
118
  const paths = Array.isArray(group.paths) ? group.paths.filter((p) => typeof p === "string") : [];
109
119
  const declared = typeof group.count === "number" && Number.isSafeInteger(group.count) && group.count >= 0 ? group.count : 0;
110
120
  count += Math.max(paths.length, declared);
@@ -1,4 +1,5 @@
1
1
  import { legacySwitchRestorePatch, type VaultSyncSwitches } from "../vault-sync-switches.js";
2
+ import { removeLegacyJournalExport } from "./legacy-journal-export.js";
2
3
  export interface HandBackVault {
3
4
  uid: string;
4
5
  kind: "personal" | "company";
@@ -13,5 +14,5 @@ export declare function engineOwnsVault(home: string, uid: string): boolean;
13
14
  * has exited; the runner resumes a vault as soon as both are done. Throws
14
15
  * before removing any record when menubar.json cannot be written.
15
16
  */
16
- export declare function finishLegacyHandBack(home: string, vaults: readonly HandBackVault[], switches?: Pick<VaultSyncSwitches, "personalOff" | "offCompanies">): ReturnType<typeof legacySwitchRestorePatch>;
17
+ export declare function finishLegacyHandBack(home: string, vaults: readonly HandBackVault[], switches?: Pick<VaultSyncSwitches, "personalOff" | "offCompanies">, warn?: (line: string) => void, removeExport?: typeof removeLegacyJournalExport): ReturnType<typeof legacySwitchRestorePatch>;
17
18
  //# sourceMappingURL=hand-back.d.ts.map
@@ -2,6 +2,8 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { legacySwitchRestorePatch, writeVaultSyncSwitches } from "../vault-sync-switches.js";
4
4
  import { removeEngineOwnership, syncCoreEngineHome } from "./engine-home.js";
5
+ import { removeLegacyJournalExport } from "./legacy-journal-export.js";
6
+ const reportedRemovalFailures = new Set();
5
7
  export function engineOwnsVault(home, uid) {
6
8
  return fs.existsSync(path.join(syncCoreEngineHome(home, uid), ".hq", "sync-core", "owned", `${uid}.json`));
7
9
  }
@@ -12,12 +14,24 @@ export function engineOwnsVault(home, uid) {
12
14
  * has exited; the runner resumes a vault as soon as both are done. Throws
13
15
  * before removing any record when menubar.json cannot be written.
14
16
  */
15
- export function finishLegacyHandBack(home, vaults, switches) {
17
+ export function finishLegacyHandBack(home, vaults, switches, warn = (line) => void process.stderr.write(`${line}\n`), removeExport = removeLegacyJournalExport) {
16
18
  const patch = legacySwitchRestorePatch(vaults, switches);
17
19
  if (patch.personal || Object.keys(patch.companies).length > 0)
18
20
  writeVaultSyncSwitches(home, patch);
19
- for (const vault of vaults)
21
+ for (const vault of vaults) {
22
+ const key = `${home}\0${vault.uid}`;
23
+ try {
24
+ removeExport(home, vault);
25
+ reportedRemovalFailures.delete(key);
26
+ }
27
+ catch (error) {
28
+ if (!reportedRemovalFailures.has(key)) {
29
+ reportedRemovalFailures.add(key);
30
+ warn(`${vault.uid}: could not remove the copy of the current sync's record of ${vault.slug ?? vault.uid} kept for the new sync engine: ${error instanceof Error ? error.message : String(error)}`);
31
+ }
32
+ }
20
33
  removeEngineOwnership(home, vault.uid);
34
+ }
21
35
  return patch;
22
36
  }
23
37
  //# sourceMappingURL=hand-back.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=legacy-journal-export-child.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { bundledHqCloud, currentHqCloud } from "../daemon/hq-cloud.js";
2
+ import { daemonPaths } from "../daemon/paths.js";
3
+ import { writeLegacyJournalExport } from "./legacy-journal-export.js";
4
+ import { loadLegacyJournalReader } from "./legacy-journal-reader.js";
5
+ const [home, uid, slug, offSince] = process.argv.slice(2);
6
+ try {
7
+ if (!home || !uid || !slug)
8
+ throw new Error("usage: legacy-journal-export-child <home> <vault uid> <slug>");
9
+ const loaded = await loadLegacyJournalReader([currentHqCloud(daemonPaths(home, process.env).root), bundledHqCloud()]);
10
+ if (!loaded.reader)
11
+ throw new Error(loaded.reason);
12
+ writeLegacyJournalExport({
13
+ home,
14
+ vault: { uid, kind: "company", slug },
15
+ readJournal: loaded.reader,
16
+ ...(offSince && Number.isFinite(Date.parse(offSince)) ? { offSince: Date.parse(offSince) } : {}),
17
+ });
18
+ process.exit(0);
19
+ }
20
+ catch (error) {
21
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
22
+ process.exit(1);
23
+ }
24
+ //# sourceMappingURL=legacy-journal-export-child.js.map