@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,31 @@
1
+ import type { EntityRef, GraphSchema } from "../types.js";
2
+ import type { PassTask } from "./pass.js";
3
+ import { type ModelTaskKind, type PendingMarker } from "./step.js";
4
+ /** `ModelStepConfig.pendingItem` for a graph with this schema. A payload its task cannot render makes the task throw; the step treats that as unknown. */
5
+ export declare function pendingItemRenderer(schema: GraphSchema): (marker: PendingMarker) => {
6
+ rendered: unknown;
7
+ kind: ModelTaskKind;
8
+ } | null;
9
+ /**
10
+ * True for a marker the graph pass left (its follow-up work): anything that is
11
+ * not one of the replay's own three tasks. The replay sends its own markers
12
+ * again from their payloads (`resumePending`); the pass builds its items from
13
+ * the graph, so its markers say where to look, not what to send.
14
+ */
15
+ export declare function isFollowUpMarker(marker: Pick<PendingMarker, "kind" | "promptVersion">): boolean;
16
+ /**
17
+ * The entities a follow-up marker is about. A pass scoped to them builds the
18
+ * marker's item again when the graph still asks the question. Empty for a
19
+ * marker that names none (a digest left before digests recorded their entities).
20
+ */
21
+ export declare function followUpEntities(marker: Pick<PendingMarker, "kind" | "promptVersion" | "payload" | "itemKey">): EntityRef[];
22
+ /** The pass task a follow-up marker belongs to, or null. */
23
+ export declare function followUpTask(marker: Pick<PendingMarker, "kind" | "promptVersion">): PassTask | null;
24
+ /** Every entity the follow-up markers in a list are about. */
25
+ export declare function followUpScope(markers: readonly Pick<PendingMarker, "kind" | "promptVersion" | "payload" | "itemKey">[]): Set<EntityRef>;
26
+ /**
27
+ * The markers of a pending file as they are on disk, without opening a step: a look that costs one
28
+ * read, for a run that has to decide whether there is anything to do. An unreadable file is empty.
29
+ */
30
+ export declare function peekPendingMarkers(file: string): PendingMarker[];
31
+ //# sourceMappingURL=pending-items.d.ts.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * WP-D: what a pending marker's item is, for every task that leaves markers.
3
+ *
4
+ * The step keeps markers by item, not by model (`pendingItemId` in step.ts).
5
+ * To give a marker its id, and to see that another model already answered the
6
+ * item, the step needs the item in the canonical form its task sends. The
7
+ * tasks know that form; this file maps a marker to its task by the family of
8
+ * its prompt version and renders the payload with that task's own `renderItem`.
9
+ *
10
+ * It also says which entities a follow-up marker (profile, retype, decision
11
+ * supersession, page summary, digest) is about, so an update with nothing new
12
+ * can still look for that work on those entities.
13
+ */
14
+ import { isEntityRef } from "../schema/index.js";
15
+ import { readTextIfPresent } from "./files.js";
16
+ import { digestSpec, profileSpec, retypeSpec, supersessionSpec } from "./pass-tasks.js";
17
+ import { promptFamily } from "./step.js";
18
+ import { extractSourceSpec, fuzzySpec, isReplayMarker, relationshipSpec, summarizeSpec } from "./tasks.js";
19
+ /** The day a spec charges its calls to plays no part in how it renders an item. */
20
+ const ANY_DAY = "1970-01-01";
21
+ /** `ModelStepConfig.pendingItem` for a graph with this schema. A payload its task cannot render makes the task throw; the step treats that as unknown. */
22
+ export function pendingItemRenderer(schema) {
23
+ const specs = new Map();
24
+ for (const spec of [
25
+ relationshipSpec(schema, ANY_DAY),
26
+ fuzzySpec(ANY_DAY),
27
+ extractSourceSpec(schema, ANY_DAY),
28
+ summarizeSpec(ANY_DAY),
29
+ digestSpec(ANY_DAY),
30
+ profileSpec(ANY_DAY),
31
+ retypeSpec(ANY_DAY),
32
+ supersessionSpec(ANY_DAY),
33
+ ]) {
34
+ specs.set(promptFamily(spec.promptVersion), spec);
35
+ }
36
+ return (marker) => {
37
+ const spec = specs.get(promptFamily(String(marker.promptVersion ?? "")));
38
+ if (!spec || marker.payload === null || typeof marker.payload !== "object")
39
+ return null;
40
+ return { rendered: spec.renderItem(marker.payload), kind: spec.kind };
41
+ };
42
+ }
43
+ /**
44
+ * True for a marker the graph pass left (its follow-up work): anything that is
45
+ * not one of the replay's own three tasks. The replay sends its own markers
46
+ * again from their payloads (`resumePending`); the pass builds its items from
47
+ * the graph, so its markers say where to look, not what to send.
48
+ */
49
+ export function isFollowUpMarker(marker) {
50
+ return !isReplayMarker(marker);
51
+ }
52
+ function refs(values) {
53
+ return values.filter((value) => typeof value === "string" && isEntityRef(value));
54
+ }
55
+ /**
56
+ * The entities a follow-up marker is about. A pass scoped to them builds the
57
+ * marker's item again when the graph still asks the question. Empty for a
58
+ * marker that names none (a digest left before digests recorded their entities).
59
+ */
60
+ export function followUpEntities(marker) {
61
+ if (!isFollowUpMarker(marker))
62
+ return [];
63
+ const payload = marker.payload !== null && typeof marker.payload === "object" ? marker.payload : {};
64
+ const family = promptFamily(String(marker.promptVersion ?? ""));
65
+ const inner = (value) => (value !== null && typeof value === "object" ? value.ref : undefined);
66
+ if (family === "profile-entity" || family === "summarize-page")
67
+ return refs([payload.ref, marker.itemKey]);
68
+ if (family === "retype-edge")
69
+ return refs([inner(payload.a), inner(payload.b)]);
70
+ if (family === "decision-supersession")
71
+ return refs(Array.isArray(payload.decisions) ? payload.decisions.map(inner) : []);
72
+ if (family === "digest-source")
73
+ return refs(Array.isArray(payload.entities) ? payload.entities : []);
74
+ return [];
75
+ }
76
+ const FOLLOW_UP_TASK = {
77
+ "digest-source": "digest",
78
+ "profile-entity": "profile",
79
+ "retype-edge": "retype",
80
+ "decision-supersession": "supersede",
81
+ "summarize-page": "summaries",
82
+ };
83
+ /** The pass task a follow-up marker belongs to, or null. */
84
+ export function followUpTask(marker) {
85
+ if (!isFollowUpMarker(marker))
86
+ return null;
87
+ return FOLLOW_UP_TASK[promptFamily(String(marker.promptVersion ?? ""))] ?? null;
88
+ }
89
+ /** Every entity the follow-up markers in a list are about. */
90
+ export function followUpScope(markers) {
91
+ const scope = new Set();
92
+ for (const marker of markers)
93
+ for (const ref of followUpEntities(marker))
94
+ scope.add(ref);
95
+ return scope;
96
+ }
97
+ /**
98
+ * The markers of a pending file as they are on disk, without opening a step: a look that costs one
99
+ * read, for a run that has to decide whether there is anything to do. An unreadable file is empty.
100
+ */
101
+ export function peekPendingMarkers(file) {
102
+ try {
103
+ const text = readTextIfPresent(file);
104
+ if (text === null)
105
+ return [];
106
+ const parsed = JSON.parse(text);
107
+ return Array.isArray(parsed.markers) ? parsed.markers.filter((marker) => marker !== null && typeof marker === "object") : [];
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ }
113
+ //# sourceMappingURL=pending-items.js.map
@@ -17,6 +17,10 @@
17
17
  * account is out of usage or signed out, calls stop and every unsent item
18
18
  * gets a pending marker (`.state/model-pending.json`) that the next run picks
19
19
  * up. A run never fails because of the model.
20
+ * - Pending markers are kept by item, not by model (`pendingItemId`): an item
21
+ * answered on any model is no longer pending. Opening the file drops every
22
+ * marker whose item some model has already answered, and joins the copies
23
+ * of one item that runs on different models left.
20
24
  * - Ledger: one line per call in `.state/model-ledger.jsonl` with input and
21
25
  * output tokens and wall time. Tokens are the CLI's numbers; when the CLI
22
26
  * reports none they are bytes / 4 and the line says `estimated: true`.
@@ -27,7 +31,12 @@ export type ModelTaskKind = ModelStepKind | "extract-source" | "digest-source" |
27
31
  export type PendingReason = "budget-day" | "budget-run" | "dry-run" | "usage-limit" | "logged-out" | "timeout" | "provider-error";
28
32
  /** Left for the next run when an item could not be sent. */
29
33
  export interface PendingMarker {
30
- /** The item's cache key. */
34
+ /**
35
+ * The item itself, whatever model was asked: `pendingItemId`. The file holds one marker per id. A marker
36
+ * written before markers were kept by item has none in the file and is given one when the file is opened.
37
+ */
38
+ id: string;
39
+ /** The item's cache key on the model that could not be asked. */
31
40
  key: string;
32
41
  kind: ModelTaskKind;
33
42
  /** The task's own id for the item (an entity ref, a pair id, a source ref). */
@@ -141,6 +150,18 @@ export interface RunTotals {
141
150
  cacheHitRate: number;
142
151
  /** Items this step left pending, by why. `budget-day` is the daily cap, `budget-run` the run's own cap. */
143
152
  pendingByReason: Partial<Record<PendingReason, number>>;
153
+ /** Items in the turns a cap or a dry run refused, and an estimate of the input tokens those turns would have sent. */
154
+ unsentItems: number;
155
+ unsentInputTokens: number;
156
+ }
157
+ /** What opening the pending file did. */
158
+ export interface PendingCleanup {
159
+ /** Markers in the file, after the copies of one item were joined. */
160
+ held: number;
161
+ /** Markers dropped because some model had already answered the item. */
162
+ finished: number;
163
+ /** Markers that were a second copy of an item another marker already named (the same item, left by another model). */
164
+ merged: number;
144
165
  }
145
166
  /** The step as this package's tasks use it. A superset of the contract's `ModelStep`. */
146
167
  export interface BatchModelStep extends ModelStep {
@@ -154,6 +175,11 @@ export interface BatchModelStep extends ModelStep {
154
175
  totals(): RunTotals;
155
176
  /** Why calls have stopped for the rest of this run, if they have. */
156
177
  halted(): PendingReason | null;
178
+ /** Ids (`PendingMarker.id`) of every item this step was handed since it was created, whatever became of it. */
179
+ seenItems(): ReadonlySet<string>;
180
+ /** Drops markers by id: items the graph no longer asks about. Returns how many were held. */
181
+ dropPending(ids: readonly string[]): number;
182
+ pendingCleanup(): PendingCleanup;
157
183
  }
158
184
  export interface ModelStepConfig {
159
185
  graphRoot: string;
@@ -177,7 +203,26 @@ export interface ModelStepConfig {
177
203
  stateDir?: string;
178
204
  /** Turns in flight at once. Default 1. */
179
205
  concurrency?: number;
206
+ /**
207
+ * The canonical form of a marker's item (what its task's `renderItem` gives for the payload) and the kind
208
+ * the task files under now, or null for a marker of no known task. With it, a marker written before markers
209
+ * were kept by item gets its id, and opening the file can tell that another model already answered an item.
210
+ */
211
+ pendingItem?: (marker: PendingMarker) => {
212
+ rendered: unknown;
213
+ kind: ModelTaskKind;
214
+ } | null;
215
+ /** Write no state file: no marker, no parked record. For a dry run that must leave the folder as it found it. */
216
+ readOnly?: boolean;
180
217
  }
218
+ /** `extract-source.v2+2e2d68fa` -> `extract-source`: the task a prompt belongs to, whatever its version. */
219
+ export declare function promptFamily(promptVersion: string): string;
220
+ /**
221
+ * What a pending marker is kept under: the task (the prompt's family) and a hash of the item's canonical
222
+ * input. No model name and no prompt version, so the same item is one marker whichever model could not be asked, and the marker is
223
+ * cleared whichever model answers.
224
+ */
225
+ export declare function pendingItemId(promptVersion: string, input: string): string;
181
226
  /** Tokens a `claude -p` turn adds on top of our prompt and input (system prompt). Measured at about 3,000. */
182
227
  export declare const CLI_OVERHEAD_TOKENS = 3000;
183
228
  /**
@@ -1,6 +1,22 @@
1
1
  import * as path from "node:path";
2
- import { MODEL_STATE_PATHS, appendJsonLineSync, estimateTokens, readJsonLinesSync, readTextIfPresent, sha256Hex, stableStringify, statePath, writeFileAtomicSync, } from "./files.js";
2
+ import { MODEL_STATE_PATHS, appendJsonLineSync, estimateTokens, fileStampSync, listFileNamesSync, readJsonLinesSync, readTextIfPresent, sha256Hex, stableStringify, statePath, writeFileAtomicSync, } from "./files.js";
3
3
  import { ModelRunnerError } from "./runner.js";
4
+ /** `extract-source.v2+2e2d68fa` -> `extract-source`: the task a prompt belongs to, whatever its version. */
5
+ export function promptFamily(promptVersion) {
6
+ const cut = /^(.+?)\.v\d+(?:[+.-].*)?$/.exec(promptVersion);
7
+ return cut ? cut[1] : promptVersion;
8
+ }
9
+ /**
10
+ * What a pending marker is kept under: the task (the prompt's family) and a hash of the item's canonical
11
+ * input. No model name and no prompt version, so the same item is one marker whichever model could not be asked, and the marker is
12
+ * cleared whichever model answers.
13
+ */
14
+ export function pendingItemId(promptVersion, input) {
15
+ const family = promptFamily(promptVersion);
16
+ return `${family}:${sha256Hex(`${family}\n${input}`).slice(0, 32)}`;
17
+ }
18
+ /** Id of a marker whose item cannot be rendered (no `pendingItem`, or a payload of no known task): its own cache key. */
19
+ const LEGACY_ID = "key:";
4
20
  /** Tokens a `claude -p` turn adds on top of our prompt and input (system prompt). Measured at about 3,000. */
5
21
  export const CLI_OVERHEAD_TOKENS = 3_000;
6
22
  const DEFAULT_MAX_ITEMS = 20;
@@ -52,36 +68,139 @@ export function createBatchModelStep(config) {
52
68
  // Per-day use, seeded from the ledger so the day cap holds across runs. The cap is per model: a
53
69
  // step on a stronger model for two small tasks is not refused because the cheap model's day is spent.
54
70
  const dayUsed = new Map();
71
+ /** Every model the call ledger names, and this one: the models that may hold a reply for an item. */
72
+ const knownModels = new Set([config.model]);
55
73
  for (const line of readJsonLinesSync(ledgerFile)) {
56
74
  if (line.type !== "call" || typeof line.day !== "string")
57
75
  continue;
76
+ if (typeof line.model === "string")
77
+ knownModels.add(line.model);
58
78
  if (typeof line.model === "string" && line.model !== config.model)
59
79
  continue;
60
80
  const used = dayUsed.get(line.day) ?? zero();
61
81
  add(used, { inputTokens: Number(line.inputTokens) || 0, outputTokens: Number(line.outputTokens) || 0 });
62
82
  dayUsed.set(line.day, used);
63
83
  }
64
- const pendingMarkers = new Map();
65
- const pendingText = readTextIfPresent(pendingFile);
66
- if (pendingText !== null) {
84
+ // ---- pending markers: one per item (`pendingItemId`), whatever model could not be asked ----
85
+ /** A marker's item as its task renders it. Memoised by cache key while the file is being opened. */
86
+ let renderMemo = new Map();
87
+ const renderMarker = (marker) => {
88
+ const known = renderMemo?.get(marker.key);
89
+ if (known !== undefined)
90
+ return known;
91
+ let out = null;
92
+ const payload = marker.payload;
93
+ if (payload !== null && typeof payload === "object") {
94
+ const keys = Object.keys(payload);
95
+ const input = payload.input;
96
+ if (keys.length === 1 && typeof input === "string")
97
+ out = { input, kind: marker.kind }; // left by `run`
98
+ else if (config.pendingItem) {
99
+ try {
100
+ const item = config.pendingItem(marker);
101
+ if (item)
102
+ out = { input: stableStringify(item.rendered), kind: item.kind };
103
+ }
104
+ catch {
105
+ // A payload its task cannot render: the marker keeps its own cache key as its id.
106
+ }
107
+ }
108
+ }
109
+ renderMemo?.set(marker.key, out);
110
+ return out;
111
+ };
112
+ const idOf = (marker) => {
113
+ // An id is of its own task: one that names another (a marker copied by hand) is worked out again.
114
+ if (typeof marker.id === "string" && marker.id.startsWith(`${promptFamily(String(marker.promptVersion ?? ""))}:`))
115
+ return marker.id;
116
+ const item = renderMarker(marker);
117
+ return item ? pendingItemId(String(marker.promptVersion ?? ""), item.input) : `${LEGACY_ID}${marker.key}`;
118
+ };
119
+ /** The file, one marker per item. Copies of one item (left by different models) are joined: earliest time, latest payload. */
120
+ const readPendingFile = () => {
121
+ const markers = new Map();
122
+ let merged = 0;
123
+ const text = readTextIfPresent(pendingFile);
124
+ if (text === null)
125
+ return { markers, merged };
67
126
  try {
68
- const parsed = JSON.parse(pendingText);
69
- for (const marker of parsed.markers ?? [])
70
- if (marker && typeof marker.key === "string")
71
- pendingMarkers.set(marker.key, marker);
127
+ const parsed = JSON.parse(text);
128
+ for (const marker of parsed.markers ?? []) {
129
+ if (!marker || typeof marker.key !== "string")
130
+ continue;
131
+ const id = idOf(marker);
132
+ const earlier = markers.get(id);
133
+ if (earlier)
134
+ merged += 1;
135
+ markers.set(id, { ...marker, id, at: earlier && earlier.at < marker.at ? earlier.at : marker.at });
136
+ }
72
137
  }
73
138
  catch {
74
139
  // An unreadable marker file loses nothing: callers submit their items again.
75
140
  }
141
+ return { markers, merged };
142
+ };
143
+ const opened = readPendingFile();
144
+ let pendingMarkers = opened.markers;
145
+ /** What this step set (a marker) or cleared (null) since it last wrote the file. */
146
+ const changes = new Map();
147
+ const cleanup = { held: pendingMarkers.size, finished: 0, merged: opened.merged };
148
+ if (pendingMarkers.size > 0) {
149
+ // An item some model has answered is not pending, whichever model the marker was left for.
150
+ const cacheNames = new Set(listFileNamesSync(cacheDir));
151
+ const answered = (marker) => {
152
+ if (cacheNames.has(`${marker.key}.json`))
153
+ return true;
154
+ const item = renderMarker(marker);
155
+ if (!item)
156
+ return false;
157
+ for (const model of knownModels) {
158
+ for (const kind of new Set([marker.kind, item.kind])) {
159
+ if (cacheNames.has(`${cacheKeyFor({ promptVersion: marker.promptVersion, kind, input: item.input, model })}.json`))
160
+ return true;
161
+ }
162
+ }
163
+ return false;
164
+ };
165
+ for (const [id, marker] of [...pendingMarkers]) {
166
+ if (!answered(marker))
167
+ continue;
168
+ pendingMarkers.delete(id);
169
+ changes.set(id, null);
170
+ cleanup.finished += 1;
171
+ }
76
172
  }
77
- let pendingDirty = false;
173
+ renderMemo = null;
174
+ let pendingStamp = fileStampSync(pendingFile);
175
+ let pendingDirty = cleanup.finished > 0 || cleanup.merged > 0;
176
+ /** Another step of this run (a second model for some tasks) may have written the file: start from it, then apply this step's changes. */
177
+ const syncPending = () => {
178
+ if (fileStampSync(pendingFile) === pendingStamp)
179
+ return;
180
+ const fresh = readPendingFile().markers;
181
+ for (const [id, marker] of changes) {
182
+ if (marker === null)
183
+ fresh.delete(id);
184
+ else
185
+ fresh.set(id, marker);
186
+ }
187
+ pendingMarkers = fresh;
188
+ pendingStamp = fileStampSync(pendingFile);
189
+ };
190
+ const sortedPending = () => [...pendingMarkers.values()].sort((a, b) => (a.at !== b.at ? (a.at < b.at ? -1 : 1) : a.key < b.key ? -1 : 1));
78
191
  const savePending = () => {
79
- if (!pendingDirty)
192
+ if (!pendingDirty || config.readOnly)
80
193
  return;
81
- const markers = [...pendingMarkers.values()].sort((a, b) => (a.at !== b.at ? (a.at < b.at ? -1 : 1) : a.key < b.key ? -1 : 1));
82
- writeFileAtomicSync(pendingFile, `${JSON.stringify({ version: 1, markers }, null, 1)}\n`);
194
+ syncPending();
195
+ writeFileAtomicSync(pendingFile, `${JSON.stringify({ version: 2, markers: sortedPending() }, null, 1)}\n`);
196
+ pendingStamp = fileStampSync(pendingFile);
197
+ changes.clear();
83
198
  pendingDirty = false;
84
199
  };
200
+ // The cleanup is written when the file is opened, so the next run (on any model) does not find the stale markers.
201
+ if (!config.dryRun)
202
+ savePending();
203
+ const seen = new Set();
85
204
  const parkedRecords = new Map();
86
205
  for (const record of readJsonLinesSync(parkedFile)) {
87
206
  if (record && typeof record.key === "string")
@@ -90,7 +209,7 @@ export function createBatchModelStep(config) {
90
209
  let window = {
91
210
  calls: 0, cacheHits: 0, pending: 0, errors: 0, used: zero(),
92
211
  };
93
- const total = { calls: 0, cacheHits: 0, pending: 0, parked: 0, errors: 0, used: zero(), estimatedCalls: 0, wallMs: 0, sent: 0 };
212
+ const total = { calls: 0, cacheHits: 0, pending: 0, parked: 0, errors: 0, used: zero(), estimatedCalls: 0, wallMs: 0, sent: 0, unsentItems: 0, unsentInputTokens: 0 };
94
213
  const pendingByReason = {};
95
214
  let haltReason = null;
96
215
  let budgetStopped = false;
@@ -111,24 +230,39 @@ export function createBatchModelStep(config) {
111
230
  const file = { v: 1, key, kind, promptVersion, model: config.model, at: now().toISOString(), output };
112
231
  writeFileAtomicSync(`${cacheDir}/${key}.json`, `${JSON.stringify(file)}\n`);
113
232
  };
114
- const clearPending = (key) => {
115
- if (pendingMarkers.delete(key))
116
- pendingDirty = true;
233
+ /** The item is answered (or parked): no marker for it stays, under its id or under the cache key of an unrendered marker. */
234
+ const clearPending = (id, cacheKey) => {
235
+ for (const each of [id, `${LEGACY_ID}${cacheKey}`]) {
236
+ // Recorded even when this step holds no such marker: the file may, from another step of the run.
237
+ changes.set(each, null);
238
+ if (pendingMarkers.delete(each))
239
+ pendingDirty = true;
240
+ }
117
241
  };
118
242
  const markPending = (marker) => {
119
- const existing = pendingMarkers.get(marker.key);
120
- pendingMarkers.set(marker.key, { ...marker, at: existing?.at ?? now().toISOString() });
243
+ const existing = pendingMarkers.get(marker.id);
244
+ const full = { ...marker, at: existing?.at ?? now().toISOString() };
245
+ pendingMarkers.set(marker.id, full);
246
+ changes.set(marker.id, full);
247
+ if (pendingMarkers.delete(`${LEGACY_ID}${marker.key}`))
248
+ changes.set(`${LEGACY_ID}${marker.key}`, null);
121
249
  pendingDirty = true;
122
250
  window.pending += 1;
123
251
  total.pending += 1;
124
252
  pendingByReason[marker.reason] = (pendingByReason[marker.reason] ?? 0) + 1;
125
253
  };
126
- const park = (record) => {
254
+ const park = (record, id) => {
127
255
  const full = { ...record, at: now().toISOString() };
128
256
  parkedRecords.set(record.key, full);
129
- appendJsonLineSync(parkedFile, full);
257
+ if (!config.readOnly)
258
+ appendJsonLineSync(parkedFile, full);
130
259
  total.parked += 1;
131
- clearPending(record.key);
260
+ clearPending(id, record.key);
261
+ };
262
+ /** A turn a cap or a dry run refused: counted, so a dry run can say what the work would cost. */
263
+ const noteUnsent = (items, estimateIn) => {
264
+ total.unsentItems += items;
265
+ total.unsentInputTokens += estimateIn;
132
266
  };
133
267
  // Once a cap refuses a call, calls stay stopped for that day (or the run), so
134
268
  // a smaller batch later in the same day does not slip past the cap.
@@ -237,19 +371,22 @@ export function createBatchModelStep(config) {
237
371
  });
238
372
  const run = async (request) => {
239
373
  const cacheKey = cacheKeyFor({ promptVersion: request.promptVersion, kind: request.kind, input: request.input, model: config.model });
374
+ const id = pendingItemId(request.promptVersion, request.input);
375
+ seen.add(id);
240
376
  const cached = readCache(cacheKey);
241
377
  if (cached !== null) {
242
378
  window.cacheHits += 1;
243
379
  total.cacheHits += 1;
244
- clearPending(cacheKey);
380
+ clearPending(id, cacheKey);
245
381
  savePending();
246
382
  return { status: "cached", cacheKey, output: cached, usage: zero() };
247
383
  }
248
384
  const estimateIn = estimateTokens(`${request.prompt}\n${request.input}`) + CLI_OVERHEAD_TOKENS;
249
385
  const refused = refusal(request.day, estimateIn);
250
386
  if (refused) {
387
+ noteUnsent(1, estimateIn);
251
388
  markPending({
252
- key: cacheKey, kind: request.kind, itemKey: cacheKey.slice(0, 12), day: request.day, reason: refused,
389
+ id, key: cacheKey, kind: request.kind, itemKey: id.slice(-12), day: request.day, reason: refused,
253
390
  promptVersion: request.promptVersion, payload: { input: request.input },
254
391
  });
255
392
  savePending();
@@ -259,14 +396,14 @@ export function createBatchModelStep(config) {
259
396
  const outcome = await call(request, request.prompt, request.input, 1, 1, () => "ok", request.maxOutputTokens);
260
397
  if (outcome.failure || outcome.output === undefined) {
261
398
  markPending({
262
- key: cacheKey, kind: request.kind, itemKey: cacheKey.slice(0, 12), day: request.day, reason: outcome.failure ?? "provider-error",
399
+ id, key: cacheKey, kind: request.kind, itemKey: id.slice(-12), day: request.day, reason: outcome.failure ?? "provider-error",
263
400
  promptVersion: request.promptVersion, payload: { input: request.input },
264
401
  });
265
402
  savePending();
266
403
  return { status: "error", cacheKey, usage: { inputTokens: outcome.usage.inputTokens, outputTokens: outcome.usage.outputTokens }, error: outcome.failure ?? "provider-error" };
267
404
  }
268
405
  writeCache(cacheKey, request.kind, request.promptVersion, outcome.output);
269
- clearPending(cacheKey);
406
+ clearPending(id, cacheKey);
270
407
  savePending();
271
408
  return { status: "ok", cacheKey, output: outcome.output, usage: { inputTokens: outcome.usage.inputTokens, outputTokens: outcome.usage.outputTokens } };
272
409
  };
@@ -275,18 +412,20 @@ export function createBatchModelStep(config) {
275
412
  const results = new Array(items.length);
276
413
  const batchStats = { items: items.length, cacheHits: 0, calls: 0, ok: 0, pending: 0, parked: 0, usage: zero(), estimated: false, seconds: 0 };
277
414
  const toSend = [];
278
- const seen = new Map();
415
+ const firstIndex = new Map();
279
416
  const duplicates = [];
280
417
  items.forEach((item, index) => {
281
418
  const input = stableStringify(spec.renderItem(item));
282
419
  const cacheKey = cacheKeyFor({ promptVersion: spec.promptVersion, kind: spec.kind, input, model: config.model });
283
420
  const itemKey = spec.itemKey(item);
284
- const first = seen.get(cacheKey);
421
+ const id = pendingItemId(spec.promptVersion, input);
422
+ seen.add(id);
423
+ const first = firstIndex.get(cacheKey);
285
424
  if (first !== undefined) {
286
425
  duplicates.push({ index, of: first });
287
426
  return;
288
427
  }
289
- seen.set(cacheKey, index);
428
+ firstIndex.set(cacheKey, index);
290
429
  const cached = readCache(cacheKey);
291
430
  if (cached !== null) {
292
431
  try {
@@ -294,7 +433,7 @@ export function createBatchModelStep(config) {
294
433
  window.cacheHits += 1;
295
434
  total.cacheHits += 1;
296
435
  batchStats.cacheHits += 1;
297
- clearPending(cacheKey);
436
+ clearPending(id, cacheKey);
298
437
  return;
299
438
  }
300
439
  catch {
@@ -307,15 +446,15 @@ export function createBatchModelStep(config) {
307
446
  batchStats.parked += 1;
308
447
  return;
309
448
  }
310
- toSend.push({ item, itemKey, cacheKey, input, bytes: Buffer.byteLength(input, "utf8"), index });
449
+ toSend.push({ item, itemKey, id, cacheKey, input, bytes: Buffer.byteLength(input, "utf8"), index });
311
450
  });
312
451
  const setPending = (entry, reason, usage) => {
313
- markPending({ key: entry.cacheKey, kind: spec.kind, itemKey: entry.itemKey, day: spec.day, reason, promptVersion: spec.promptVersion, payload: entry.item });
452
+ markPending({ id: entry.id, key: entry.cacheKey, kind: spec.kind, itemKey: entry.itemKey, day: spec.day, reason, promptVersion: spec.promptVersion, payload: entry.item });
314
453
  results[entry.index] = { item: entry.item, itemKey: entry.itemKey, cacheKey: entry.cacheKey, status: "pending", reason, usage };
315
454
  batchStats.pending += 1;
316
455
  };
317
456
  const setParked = (entry, reason, attempts, usage) => {
318
- park({ key: entry.cacheKey, kind: spec.kind, itemKey: entry.itemKey, day: spec.day, reason, attempts });
457
+ park({ key: entry.cacheKey, kind: spec.kind, itemKey: entry.itemKey, day: spec.day, reason, attempts }, entry.id);
319
458
  results[entry.index] = { item: entry.item, itemKey: entry.itemKey, cacheKey: entry.cacheKey, status: "parked", reason, usage };
320
459
  batchStats.parked += 1;
321
460
  };
@@ -338,9 +477,12 @@ export function createBatchModelStep(config) {
338
477
  /** Sends one turn. Returns each entry's parsed answer (or a reason), and what the turn cost per entry. */
339
478
  const sendTurn = async (entries, attempt, prompt) => {
340
479
  const input = `{"items":[${entries.map((entry, i) => `{"id":"i${i + 1}","data":${entry.input}}`).join(",")}]}`;
341
- const refused = refusal(spec.day, estimateTokens(`${prompt}\n${input}`) + CLI_OVERHEAD_TOKENS);
342
- if (refused)
480
+ const estimateIn = estimateTokens(`${prompt}\n${input}`) + CLI_OVERHEAD_TOKENS;
481
+ const refused = refusal(spec.day, estimateIn);
482
+ if (refused) {
483
+ noteUnsent(entries.length, estimateIn);
343
484
  return { refused };
485
+ }
344
486
  const answers = new Map();
345
487
  const state = { parsed: false };
346
488
  const judge = (output) => {
@@ -405,7 +547,7 @@ export function createBatchModelStep(config) {
405
547
  };
406
548
  const accept = (entry, value) => {
407
549
  writeCache(entry.cacheKey, spec.kind, spec.promptVersion, JSON.stringify(value));
408
- clearPending(entry.cacheKey);
550
+ clearPending(entry.id, entry.cacheKey);
409
551
  results[entry.index] = { item: entry.item, itemKey: entry.itemKey, cacheKey: entry.cacheKey, status: "ok", value, usage: spent.get(entry.index) ?? zero() };
410
552
  batchStats.ok += 1;
411
553
  };
@@ -496,7 +638,8 @@ export function createBatchModelStep(config) {
496
638
  return closed;
497
639
  },
498
640
  pending(kind) {
499
- const all = [...pendingMarkers.values()].sort((a, b) => (a.at !== b.at ? (a.at < b.at ? -1 : 1) : a.key < b.key ? -1 : 1));
641
+ syncPending();
642
+ const all = sortedPending();
500
643
  return kind ? all.filter((marker) => marker.kind === kind) : all;
501
644
  },
502
645
  parked(kind) {
@@ -516,11 +659,34 @@ export function createBatchModelStep(config) {
516
659
  wallMs: total.wallMs,
517
660
  cacheHitRate: asked === 0 ? 1 : total.cacheHits / asked,
518
661
  pendingByReason: { ...pendingByReason },
662
+ unsentItems: total.unsentItems,
663
+ unsentInputTokens: total.unsentInputTokens,
519
664
  };
520
665
  },
521
666
  halted() {
522
667
  return haltReason;
523
668
  },
669
+ seenItems() {
670
+ return seen;
671
+ },
672
+ dropPending(ids) {
673
+ syncPending();
674
+ let dropped = 0;
675
+ for (const id of ids) {
676
+ if (!pendingMarkers.delete(id))
677
+ continue;
678
+ changes.set(id, null);
679
+ dropped += 1;
680
+ }
681
+ if (dropped > 0) {
682
+ pendingDirty = true;
683
+ savePending();
684
+ }
685
+ return dropped;
686
+ },
687
+ pendingCleanup() {
688
+ return { ...cleanup };
689
+ },
524
690
  };
525
691
  }
526
692
  //# sourceMappingURL=step.js.map
@@ -7,6 +7,16 @@
7
7
  */
8
8
  import type { AudienceKey, Confidence, EntityRef, GraphEntityType, GraphSchema, IngestRow, IsoDate, SourceRef, Verb } from "../types.js";
9
9
  import type { BatchItemResult, BatchModelStep, BatchRunStats, BatchSpec, PendingMarker } from "./step.js";
10
+ /** Confidence an extraction falls back to when the model gave none it can use. Below the readers' unverified-guess line on purpose. */
11
+ export declare const DEFAULT_EXTRACTED_CONF: Confidence;
12
+ /**
13
+ * A confidence the model stated for one fact: a number from 0 to 1, kept to two
14
+ * decimals. Anything else (missing, text, not finite, outside the range) is not
15
+ * a statement of confidence and gets the default; a 7 is never read as 1.
16
+ */
17
+ export declare function statedConf(value: unknown, fallback?: Confidence): Confidence;
18
+ /** The rubric every extracting prompt gives for its confidence field, so the numbers mean the same thing across tasks. */
19
+ export declare const CONF_RUBRIC: string;
10
20
  /** Verbs the schema allows from a subject type to an object type. Reference verbs are left out unless asked for. */
11
21
  export declare function allowedVerbs(schema: GraphSchema, subject: GraphEntityType, object: GraphEntityType, includeReference?: boolean): Verb[];
12
22
  export interface TaskRun<I, O> {
@@ -90,12 +100,15 @@ export interface ExtractedFact {
90
100
  field: string;
91
101
  value: string;
92
102
  quote: string;
103
+ /** What the model said its confidence is; `DEFAULT_EXTRACTED_CONF` when it gave none. */
104
+ conf: Confidence;
93
105
  }
94
106
  export interface ExtractedEdge {
95
107
  subject: EntityRef;
96
108
  verb: Verb;
97
109
  target: EntityRef;
98
110
  quote: string;
111
+ conf: Confidence;
99
112
  }
100
113
  export interface ExtractedEvent {
101
114
  entity: EntityRef;
@@ -123,7 +136,10 @@ export declare function extractSourceSpec(schema: GraphSchema, day: IsoDate): Ba
123
136
  export declare function extractFromSources(step: BatchModelStep, schema: GraphSchema, items: readonly SourceExtractionItem[], options: {
124
137
  day: IsoDate;
125
138
  }): Promise<TaskRun<SourceExtractionItem, SourceExtraction>>;
126
- /** Forward rows for one extraction. Every row cites the source; `by` is `agent:<model>`. */
139
+ /**
140
+ * Forward rows for one extraction. Every row cites the source; `by` is `agent:<model>`. Each fact and
141
+ * edge keeps the confidence the model gave it; `stamp.conf` replaces them all when a caller sets it.
142
+ */
127
143
  export declare function extractionRows(extraction: SourceExtraction, stamp: {
128
144
  learned: IsoDate;
129
145
  model: string;