@indigoai-us/hq-cli 5.345.251 → 5.345.252
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.
- package/CHANGELOG.md +112 -0
- package/assets/scaffold/core/scripts/hq-session.sh +9 -0
- package/contracts/host-canary-release.json +9 -3
- package/dist/command-catalog.generated.d.ts +121 -1
- package/dist/command-catalog.generated.js +148 -1
- package/dist/commands/bot.js +7 -2
- package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
- package/dist/commands/core-hq-session-binding.d.ts +140 -0
- package/dist/commands/core-hq-session-binding.js +363 -0
- package/dist/commands/core-hq-session-native.d.ts +23 -0
- package/dist/commands/core-hq-session-native.js +59 -9
- package/dist/commands/core-stop-autosave.js +1 -1
- package/dist/commands/core.js +10 -0
- package/dist/commands/doctor.d.ts +5 -1
- package/dist/commands/doctor.js +42 -5
- package/dist/commands/files.js +1 -1
- package/dist/commands/install-global.js +4 -2
- package/dist/commands/logout.js +4 -0
- package/dist/commands/ontology-graph.d.ts +2 -0
- package/dist/commands/ontology-graph.js +33 -0
- package/dist/commands/report.js +35 -2
- package/dist/commands/storage-gate.js +1 -1
- package/dist/commands/vault-retention-flag.js +2 -1
- package/dist/commands/whoami.js +1 -1
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/index.js +3 -1
- package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
- package/dist/lib/agent-kit/mcp/tools.js +48 -0
- package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
- package/dist/lib/bot/fleet-cron.d.ts +35 -0
- package/dist/lib/bot/fleet-cron.js +54 -12
- package/dist/lib/bot/fleet-local.d.ts +18 -0
- package/dist/lib/bot/fleet-local.js +51 -5
- package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
- package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
- package/dist/lib/bot/signals-engine-flag.js +1 -1
- package/dist/lib/cli-invite-nudge.js +1 -1
- package/dist/lib/client-version.d.ts +2 -0
- package/dist/lib/client-version.js +24 -0
- package/dist/lib/company-flag-gate.d.ts +30 -0
- package/dist/lib/company-flag-gate.js +104 -0
- package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
- package/dist/lib/daemon/flag.js +2 -1
- package/dist/lib/daemon/legacy-journal-gate.js +3 -1
- package/dist/lib/daemon/shared-flag-reads.js +1 -1
- package/dist/lib/doctor/checks/host-core.js +22 -4
- package/dist/lib/doctor/checks/jq.d.ts +27 -6
- package/dist/lib/doctor/checks/jq.js +46 -8
- package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
- package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
- package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
- package/dist/lib/flag-client-gate-headers.d.ts +38 -0
- package/dist/lib/flag-client-gate-headers.js +62 -0
- package/dist/lib/flag-client-headers.d.ts +15 -0
- package/dist/lib/flag-client-headers.js +25 -0
- package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
- package/dist/lib/flag-registry-worker-source.generated.js +1 -1
- package/dist/lib/flag-registry-worker.js +35 -0
- package/dist/lib/flag-registry.d.ts +1 -20
- package/dist/lib/flag-registry.js +5 -81
- package/dist/lib/hook-engine/adapter-core-pin.d.ts +29 -0
- package/dist/lib/hook-engine/adapter-core-pin.js +29 -0
- package/dist/lib/hook-engine/coverage.d.ts +50 -1
- package/dist/lib/hook-engine/coverage.js +111 -7
- package/dist/lib/hook-engine/reconcile.js +3 -2
- package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
- package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
- package/dist/lib/hot-channels/signal-changes.js +683 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
- package/dist/lib/hot-channels/signals-pass.js +232 -12
- package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
- package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
- package/dist/lib/lanes/registry-flag.js +2 -1
- package/dist/lib/lanes/spawn.js +11 -1
- package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
- package/dist/lib/mesh/live/binding-intent.js +201 -0
- package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
- package/dist/lib/mesh/live/binding-receipt.js +365 -0
- package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
- package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
- package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
- package/dist/lib/mesh/live/daemon/install.js +2 -1
- package/dist/lib/mesh/live/daemon/presence.js +9 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
- package/dist/lib/mesh/live/daemon/run.js +33 -1
- package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
- package/dist/lib/ontology-graph/lineage/index.js +1027 -0
- package/dist/lib/ontology-graph/model/index.d.ts +54 -0
- package/dist/lib/ontology-graph/model/index.js +112 -0
- package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
- package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
- package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
- package/dist/lib/ontology-graph/model/pass.js +9 -2
- package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
- package/dist/lib/ontology-graph/model/pending-items.js +24 -1
- package/dist/lib/ontology-graph/model/step.d.ts +1 -1
- package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
- package/dist/lib/ontology-graph/model/tasks.js +20 -7
- package/dist/lib/ontology-graph/read/brief.js +41 -6
- package/dist/lib/ontology-graph/read/index.d.ts +4 -0
- package/dist/lib/ontology-graph/read/index.js +173 -29
- package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
- package/dist/lib/ontology-graph/read/lineage.js +262 -0
- package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
- package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
- package/dist/lib/ontology-graph/replay/engine.js +213 -8
- package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
- package/dist/lib/ontology-graph/replay/extractors.js +25 -1
- package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
- package/dist/lib/ontology-graph/replay/index.js +9 -3
- package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
- package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
- package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
- package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
- package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
- package/dist/lib/ontology-graph/schema/index.js +1 -0
- package/dist/lib/ontology-graph/setup/index.js +13 -3
- package/dist/lib/search-index/index.d.ts +33 -1
- package/dist/lib/search-index/index.js +180 -25
- package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
- package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
- package/dist/lib/signals/adapters-catalog.js +1 -1
- package/dist/lib/sync-core/engine-holds.d.ts +1 -0
- package/dist/lib/sync-core/engine-holds.js +26 -0
- package/dist/lib/sync-core/engine-home.d.ts +3 -0
- package/dist/lib/sync-core/engine-home.js +41 -1
- package/dist/lib/sync-core/flag.js +2 -1
- package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
- package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
- package/dist/lib/sync-core/legacy-journal-export.js +120 -55
- package/dist/lib/sync-core/reconcile.d.ts +2 -1
- package/dist/lib/sync-core/reconcile.js +30 -5
- package/dist/lib/sync-invalid-entity-warning.js +2 -1
- package/dist/lib/windows/install-followup.d.ts +41 -0
- package/dist/lib/windows/install-followup.js +87 -0
- package/dist/lib/windows/jq.d.ts +59 -0
- package/dist/lib/windows/jq.js +154 -3
- package/dist/lib/windows/user-path.d.ts +5 -0
- package/dist/lib/windows/user-path.js +1 -1
- package/dist/lib/work-context/auto-bind.d.ts +12 -0
- package/dist/lib/work-context/auto-bind.js +49 -3
- package/dist/lib/work-context/organize.d.ts +4 -2
- package/dist/lib/work-context/organize.js +18 -8
- package/dist/lib/work-context/reconcile.js +16 -1
- package/dist/main.js +12 -1
- package/dist/utils/client-health-contract.d.ts +30 -0
- package/dist/utils/client-health-contract.js +111 -0
- package/dist/utils/client-health.d.ts +5 -2
- package/dist/utils/client-health.js +74 -5
- package/dist/utils/exclusive-lock.d.ts +5 -1
- package/dist/utils/exclusive-lock.js +9 -2
- package/dist/utils/host-registration.d.ts +7 -0
- package/dist/utils/host-registration.js +10 -1
- package/dist/utils/pid.d.ts +31 -0
- package/dist/utils/pid.js +65 -0
- package/dist/utils/resident-package-preload.js +12 -4
- package/dist/utils/sentry-fingerprint.js +3 -0
- package/package.json +8 -8
- package/scripts/install-hook-engine.mjs +5 -3
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq ontology lineage backfill`: decision lineage for decisions the signals
|
|
3
|
+
* pass never asked about, found in date order.
|
|
4
|
+
*
|
|
5
|
+
* A signal written since the signals pass learned `changes` says which earlier
|
|
6
|
+
* decision it replaces, and the rule `signal-changes` writes that to the graph
|
|
7
|
+
* (replay/signal-changes.ts). Decisions from before that have no such entry.
|
|
8
|
+
* This command asks a model about them, one day at a time, oldest first:
|
|
9
|
+
*
|
|
10
|
+
* 1. The decisions of the day whose signal states no change are taken, per
|
|
11
|
+
* audience folder.
|
|
12
|
+
* 2. For each, earlier decisions of the same audience that were still open on
|
|
13
|
+
* that day are scored by rule: the summed rarity of the words the two
|
|
14
|
+
* statements share, plus a bonus for a shared topic that is not a hub.
|
|
15
|
+
* Rarity is inverse document frequency over that audience's decision
|
|
16
|
+
* statements; a word in too many of them and a word of a person's name
|
|
17
|
+
* count for nothing. A candidate is listed at or above a score threshold,
|
|
18
|
+
* best first, at most `LINEAGE_MAX_CANDIDATES`. A decision with no topic is
|
|
19
|
+
* compared on words alone. A decision with no candidate is not sent.
|
|
20
|
+
* 3. The model is asked, in batches, whether the decision replaces or reverses
|
|
21
|
+
* any candidate, with a quote from each of the two statements. The host
|
|
22
|
+
* checks every entry (pass-tasks.ts, `validateLineageAnswer`).
|
|
23
|
+
* 4. The day's accepted pairs are written before the next day is read, so a
|
|
24
|
+
* decision replaced on one day is not offered as open on a later day.
|
|
25
|
+
*
|
|
26
|
+
* "Open on a day" means no row dated before that day says the decision ended:
|
|
27
|
+
* an open `superseded_by` edge, or an open status that `endsDecision` accepts
|
|
28
|
+
* (superseded, reversed, withdrawn, replaced), whoever wrote it. Rows this
|
|
29
|
+
* command writes on a day therefore change what later days are offered and
|
|
30
|
+
* nothing about that day itself, so a second walk over the same graph builds
|
|
31
|
+
* the same items, gets every answer from the cache and writes nothing.
|
|
32
|
+
*
|
|
33
|
+
* Candidates are dated on an earlier day than the decision. The graph holds a
|
|
34
|
+
* day for a decision and no time, and a signal file's `written_at` is when the
|
|
35
|
+
* signals pass wrote the file, not when the decision was made, so two
|
|
36
|
+
* decisions of one day have no order this command can rely on. The rule
|
|
37
|
+
* `signal-changes` handles a change inside one day, from the source text.
|
|
38
|
+
*
|
|
39
|
+
* What is written is of model authority and is a link only: one `supersedes`
|
|
40
|
+
* edge `by agent:<model>` at the confidence the supersession task uses, written
|
|
41
|
+
* through `applyIngest` like the rule's (the store writes `superseded_by` on
|
|
42
|
+
* the other end). No status row is written or closed. The readers show a
|
|
43
|
+
* model's link as `replaced` and take the status from the edge, and the rule
|
|
44
|
+
* `signal-changes` owns the status rows of a decision: it derives them from the
|
|
45
|
+
* whole set of stated changes and closes any other open status when it applies
|
|
46
|
+
* one. A model-written status would be closed by it or left behind when the
|
|
47
|
+
* rule closes a model link that points the other way. So:
|
|
48
|
+
*
|
|
49
|
+
* - `replaces` and `reverses` both become a link, and readers print `replaced`
|
|
50
|
+
* for it. The kind the model gave is kept in `.state/lineage-backfill.jsonl`.
|
|
51
|
+
* - A withdrawal (a decision dropped with nothing in its place) has no link
|
|
52
|
+
* and is only readable from a status the rule, a person or a record wrote.
|
|
53
|
+
* The model is not asked for one and an answer that gives one is dropped.
|
|
54
|
+
*
|
|
55
|
+
* A pair is left alone, and counted, when a person or a record wrote, on or
|
|
56
|
+
* after the newer decision's day, an open status on the earlier decision that
|
|
57
|
+
* says it stands (the precedence the rule and the readers use); when the
|
|
58
|
+
* earlier decision already ended (another decision replaced it, or an open
|
|
59
|
+
* status of any origin says so); when the link would close a loop; or when another model's
|
|
60
|
+
* open link already says the same pair (`already_linked`: no second link is written).
|
|
61
|
+
*
|
|
62
|
+
* With the rule: an entry a later signal states for the same pair is written
|
|
63
|
+
* beside the model's link and readers list the pair once, under the rule. An
|
|
64
|
+
* entry that points the other way closes the model's link in its own audience
|
|
65
|
+
* (`modelLinksClosed`). The rule removes only rows it wrote itself, so it never
|
|
66
|
+
* removes a row of this command.
|
|
67
|
+
*
|
|
68
|
+
* A pair never crosses audience folders: a decision is compared with, and
|
|
69
|
+
* linked to, decisions whose statement is in the same folder, and every row is
|
|
70
|
+
* written to that folder.
|
|
71
|
+
*
|
|
72
|
+
* The model step is the graph's own: the signed-in Claude login, the model in
|
|
73
|
+
* the company's `settings/ontology.yaml`, the call ledger, the reply cache and
|
|
74
|
+
* the daily cap. `model_tasks` in that file does not switch this command off:
|
|
75
|
+
* it runs only when someone runs it.
|
|
76
|
+
*
|
|
77
|
+
* A decision whose reply is unusable after the step's retry turn is not
|
|
78
|
+
* dropped: its day is not written and the walk stops there, and the next run
|
|
79
|
+
* sends it again. After `LINEAGE_MAX_ATTEMPTS` runs it is recorded as
|
|
80
|
+
* `unanswered` and its day is written without it (`--allow-unanswered` records
|
|
81
|
+
* it at once; `--retry-unanswered` sends the recorded ones again).
|
|
82
|
+
*
|
|
83
|
+
* `.state/lineage-backfill-cursor.json` holds what is settled: per decision the
|
|
84
|
+
* candidates it was asked with, the attempt counts and the unanswered
|
|
85
|
+
* decisions, keyed on the model, the prompt version and the retrieval-rule
|
|
86
|
+
* version. A decision that appears later, on any day, is not in it and is
|
|
87
|
+
* asked by the next run.
|
|
88
|
+
*
|
|
89
|
+
* `.state/lineage-backfill.jsonl` lists every link written, with the row ids.
|
|
90
|
+
* `hq ontology lineage undo` (`runLineageUndo`) removes exactly those rows and
|
|
91
|
+
* the state file. `hq ontology remodel` does not ask these links again.
|
|
92
|
+
*/
|
|
93
|
+
import { createHash } from "node:crypto";
|
|
94
|
+
import * as fs from "node:fs";
|
|
95
|
+
import * as path from "node:path";
|
|
96
|
+
import { CLI_OVERHEAD_TOKENS, LINEAGE_MAX_CANDIDATES, LINEAGE_PROMPT_VERSION, MODEL_STATE_PATHS, createModelStep as defaultCreateModelStep, estimateLineageTurns, lineageSpec, resolveModelStateDir, } from "../model/index.js";
|
|
97
|
+
import { compilePages as defaultCompilePages } from "../pages/index.js";
|
|
98
|
+
import { resolveDayBudget } from "../replay/index.js";
|
|
99
|
+
import { SIGNAL_CHANGES_RULE } from "../replay/signal-changes.js";
|
|
100
|
+
import { endsDecision, inverseEdge, isOpen, originTier, parseEntityRef, rowId } from "../schema/index.js";
|
|
101
|
+
import { appendJsonLine, applyIngest, assertGraphWritableFor, atomicWriteFile, claimGraphRootFor, graphPath, openGraphStore, readJsonLines, readTextIfExists } from "../store/index.js";
|
|
102
|
+
/** Where the walk stopped, relative to the graph folder. */
|
|
103
|
+
export const LINEAGE_CURSOR_RELATIVE = ".state/lineage-backfill-cursor.json";
|
|
104
|
+
/** One line per link this command wrote, with the ids of its rows. `hq ontology lineage undo` removes exactly those rows. */
|
|
105
|
+
export const LINEAGE_APPLIED_RELATIVE = ".state/lineage-backfill.jsonl";
|
|
106
|
+
/** The confidence of a model's reading of two decisions, as the supersession task writes it. */
|
|
107
|
+
export const LINEAGE_CONFIDENCE = 0.6;
|
|
108
|
+
/** How candidates are picked. Part of the state's key: a change here makes the next run walk again. */
|
|
109
|
+
export const LINEAGE_RETRIEVAL_VERSION = "rarity.v1";
|
|
110
|
+
export const DEFAULT_LINEAGE_RETRIEVAL = {
|
|
111
|
+
commonShare: 0.02,
|
|
112
|
+
commonMinDocs: 10,
|
|
113
|
+
hubShare: 0.05,
|
|
114
|
+
hubMinDocs: 20,
|
|
115
|
+
topicBonus: 1,
|
|
116
|
+
topicRarity: 1,
|
|
117
|
+
minScore: 1.7,
|
|
118
|
+
maxCandidates: LINEAGE_MAX_CANDIDATES,
|
|
119
|
+
corpusFloor: 50,
|
|
120
|
+
};
|
|
121
|
+
/** A statement needs this many distinct words to be compared at all. */
|
|
122
|
+
const MIN_WORDS = 3;
|
|
123
|
+
/** Output tokens a decision's answer is counted as in an estimate. */
|
|
124
|
+
export const LINEAGE_OUTPUT_TOKENS_PER_DECISION = 40;
|
|
125
|
+
const RULE_TIER = originTier(SIGNAL_CHANGES_RULE);
|
|
126
|
+
const openStatement = (rows) => rows.find((stored) => stored.row.kind === "F" && stored.row.field === "statement" && isOpen(stored.row));
|
|
127
|
+
const openEdges = (rows, verb) => rows.filter((stored) => stored.row.kind === "E" && stored.row.verb === verb && isOpen(stored.row));
|
|
128
|
+
/** Most decisions followed when a link is checked for a loop. */
|
|
129
|
+
const LOOP_WALK_LIMIT = 200;
|
|
130
|
+
/** True when `to` is reached from `from` over open `supersedes` edges of one audience folder. */
|
|
131
|
+
function supersedesPath(store, audience, from, to) {
|
|
132
|
+
const seen = new Set([from]);
|
|
133
|
+
const queue = [from];
|
|
134
|
+
while (queue.length > 0 && seen.size <= LOOP_WALK_LIMIT) {
|
|
135
|
+
const at = queue.shift();
|
|
136
|
+
if (at === to)
|
|
137
|
+
return true;
|
|
138
|
+
for (const stored of openEdges(store.readRows(at, { audiences: [audience], kinds: ["E"] }), "supersedes")) {
|
|
139
|
+
if (seen.has(stored.row.target))
|
|
140
|
+
continue;
|
|
141
|
+
seen.add(stored.row.target);
|
|
142
|
+
queue.push(stored.row.target);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Writes accepted pairs, in the order given: one `supersedes` edge each, of model authority. No
|
|
149
|
+
* status row is written or closed. A pair is left alone when the earlier decision already ended,
|
|
150
|
+
* when a person or a record said on or after the newer decision's day that it stands, or when the
|
|
151
|
+
* link would close a loop. Applying the same pairs again writes nothing.
|
|
152
|
+
*/
|
|
153
|
+
export function applyLineagePairs(store, pairs, options) {
|
|
154
|
+
const result = { applied: 0, alreadyApplied: 0, alreadyLinked: 0, links: 0, kinds: {}, rowsAdded: 0, skipped: {}, touched: [], closedTargets: [], records: [] };
|
|
155
|
+
const skip = (reason) => void (result.skipped[reason] = (result.skipped[reason] ?? 0) + 1);
|
|
156
|
+
const conf = options.conf ?? LINEAGE_CONFIDENCE;
|
|
157
|
+
const schema = store.schema();
|
|
158
|
+
const touched = new Set();
|
|
159
|
+
for (const pair of pairs) {
|
|
160
|
+
if (pair.kind !== "replaces" && pair.kind !== "reverses") {
|
|
161
|
+
skip("kind_not_applied");
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (pair.newer === pair.older) {
|
|
165
|
+
skip("target_is_itself");
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const olderRows = store.readRows(pair.older, { audiences: [pair.audience] });
|
|
169
|
+
const newerRows = store.readRows(pair.newer, { audiences: [pair.audience] });
|
|
170
|
+
// Both decisions must be stated in this audience folder: a row is never written where one of them is not readable.
|
|
171
|
+
if (!openStatement(olderRows) || !openStatement(newerRows)) {
|
|
172
|
+
skip("not_stated_in_this_audience");
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (openEdges(newerRows, "supersedes").some((stored) => stored.row.target === pair.older && stored.row.by === options.by)) {
|
|
176
|
+
result.alreadyApplied += 1;
|
|
177
|
+
result.closedTargets.push({ ref: pair.older, audience: pair.audience, day: pair.day });
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
// This command's link for the pair is there and was closed (by the rule, for a link that points the other way, or
|
|
181
|
+
// by a person's answer): it stays closed, whatever day this run is.
|
|
182
|
+
if (newerRows.some((stored) => stored.row.kind === "E" && stored.row.verb === "supersedes" && stored.row.target === pair.older && stored.row.by === options.by && !isOpen(stored.row))) {
|
|
183
|
+
skip("link_closed_earlier");
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
// Another model already linked this pair (the supersession task, or this command on an earlier model): one link says it.
|
|
187
|
+
if (openEdges(newerRows, "supersedes").some((stored) => stored.row.target === pair.older && stored.row.by !== options.by && stored.row.by.startsWith("agent:"))) {
|
|
188
|
+
result.alreadyLinked += 1;
|
|
189
|
+
result.closedTargets.push({ ref: pair.older, audience: pair.audience, day: pair.day });
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
// The earlier decision already leads to the new one over open links: writing this one would make a loop.
|
|
193
|
+
if (supersedesPath(store, pair.audience, pair.older, pair.newer)) {
|
|
194
|
+
skip("would_loop");
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (openEdges(olderRows, "superseded_by").some((stored) => stored.row.target !== pair.newer)) {
|
|
198
|
+
skip("target_already_replaced");
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const openStatus = olderRows.filter((stored) => stored.row.kind === "F" && stored.row.field === "status" && isOpen(stored.row));
|
|
202
|
+
// A person's or a record's status on or after the newer decision's day that says the earlier one stands decides,
|
|
203
|
+
// as it does for the rule `signal-changes` and for the readers. Checked first: it outranks any other status.
|
|
204
|
+
if (openStatus.some((stored) => originTier(stored.row.by) < RULE_TIER && stored.row.valid.from >= pair.day && !endsDecision(stored.row.value))) {
|
|
205
|
+
skip("status_held_by_a_record_or_a_person");
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
// A status of any origin that says the decision ended, with no link to this pair: it ended some other way.
|
|
209
|
+
// A link written by the rule or a person for this same pair is not that: the model's link is written beside it.
|
|
210
|
+
const samePair = openEdges(olderRows, "superseded_by").some((stored) => stored.row.target === pair.newer);
|
|
211
|
+
if (!samePair && openStatus.some((stored) => endsDecision(stored.row.value))) {
|
|
212
|
+
skip("target_already_ended");
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const edge = { kind: "E", verb: "supersedes", target: pair.older, valid: { from: pair.day }, src: pair.src, learned: options.learned, by: options.by, conf };
|
|
216
|
+
const applied = applyIngest(store, { input: pair.src, date: pair.day, entities: [], rows: [{ entity: pair.newer, audience: pair.audience, row: edge }] });
|
|
217
|
+
result.rowsAdded += applied.rowsAdded;
|
|
218
|
+
if (applied.rowsAdded === 0) {
|
|
219
|
+
result.alreadyApplied += 1;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
result.applied += 1;
|
|
223
|
+
result.links += 1;
|
|
224
|
+
result.kinds[pair.kind] = (result.kinds[pair.kind] ?? 0) + 1;
|
|
225
|
+
result.closedTargets.push({ ref: pair.older, audience: pair.audience, day: pair.day });
|
|
226
|
+
touched.add(pair.newer);
|
|
227
|
+
touched.add(pair.older);
|
|
228
|
+
const inverse = inverseEdge(schema, pair.newer, edge);
|
|
229
|
+
result.records.push({
|
|
230
|
+
...pair, by: options.by, learned: options.learned,
|
|
231
|
+
rows: [{ entity: pair.newer, id: rowId(edge) }, ...(inverse ? [{ entity: inverse.entity, id: rowId(inverse.row) }] : [])],
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
result.touched = [...touched].sort();
|
|
235
|
+
return result;
|
|
236
|
+
}
|
|
237
|
+
const STOP_WORDS = new Set([
|
|
238
|
+
"about", "after", "again", "also", "been", "before", "being", "both", "could", "does", "done", "each", "from", "have", "having", "here",
|
|
239
|
+
"into", "just", "more", "most", "much", "must", "need", "needs", "only", "other", "over", "said", "same", "should", "some", "such", "than",
|
|
240
|
+
"that", "their", "them", "then", "there", "these", "they", "this", "those", "through", "under", "until", "very", "want", "wants", "were",
|
|
241
|
+
"what", "when", "where", "which", "while", "will", "with", "would", "your",
|
|
242
|
+
]);
|
|
243
|
+
/** Distinct words of four letters or more, lower case, without the common ones. The signals pass compares on the same words. */
|
|
244
|
+
export function lineageWords(text) {
|
|
245
|
+
const out = new Set();
|
|
246
|
+
for (const word of text.toLowerCase().normalize("NFKD").split(/[^a-z0-9]+/)) {
|
|
247
|
+
if (word.length >= 4 && !STOP_WORDS.has(word))
|
|
248
|
+
out.add(word);
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
function byCode(a, b) {
|
|
253
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
254
|
+
}
|
|
255
|
+
/** Every decision with an open statement, once per audience folder that holds one, oldest first. */
|
|
256
|
+
export function loadLineageDecisions(store) {
|
|
257
|
+
const out = [];
|
|
258
|
+
const stated = new Map();
|
|
259
|
+
for (const ref of store.listEntities("decision")) {
|
|
260
|
+
const byAudience = new Map();
|
|
261
|
+
for (const stored of store.readRows(ref))
|
|
262
|
+
byAudience.set(stored.audience, [...(byAudience.get(stored.audience) ?? []), stored]);
|
|
263
|
+
for (const [audience, rows] of byAudience) {
|
|
264
|
+
for (const stored of rows) {
|
|
265
|
+
if (stored.row.kind === "T" || stored.row.by !== SIGNAL_CHANGES_RULE)
|
|
266
|
+
continue;
|
|
267
|
+
stated.set(audience, (stated.get(audience) ?? new Set()).add(stored.row.src));
|
|
268
|
+
}
|
|
269
|
+
const statement = openStatement(rows);
|
|
270
|
+
if (!statement)
|
|
271
|
+
continue;
|
|
272
|
+
const decidedOn = rows.find((stored) => stored.row.kind === "F" && stored.row.field === "decided_on" && isOpen(stored.row));
|
|
273
|
+
const day = decidedOn && /^\d{4}-\d{2}-\d{2}$/.test(decidedOn.row.value) ? decidedOn.row.value : statement.row.valid.from;
|
|
274
|
+
const topics = new Set();
|
|
275
|
+
let closedOn;
|
|
276
|
+
const close = (on) => void (closedOn = closedOn === undefined || on < closedOn ? on : closedOn);
|
|
277
|
+
for (const stored of rows) {
|
|
278
|
+
if (stored.row.kind === "T" || !isOpen(stored.row))
|
|
279
|
+
continue;
|
|
280
|
+
if (stored.row.kind === "F") {
|
|
281
|
+
if (stored.row.field === "status" && endsDecision(stored.row.value))
|
|
282
|
+
close(stored.row.valid.from);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (stored.row.verb === "superseded_by")
|
|
286
|
+
close(stored.row.valid.from);
|
|
287
|
+
if (stored.row.verb !== "about")
|
|
288
|
+
continue;
|
|
289
|
+
const type = parseEntityRef(stored.row.target)?.type;
|
|
290
|
+
// A person or a meeting is on too many decisions to say two of them are about the same thing.
|
|
291
|
+
if (type && type !== "person" && type !== "meeting" && type !== "decision")
|
|
292
|
+
topics.add(stored.row.target);
|
|
293
|
+
}
|
|
294
|
+
out.push({
|
|
295
|
+
ref, audience, day, text: statement.row.value, src: statement.row.src, topics, words: lineageWords(statement.row.value), hasChanges: false,
|
|
296
|
+
...(closedOn !== undefined ? { closedOn } : {}),
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
for (const decision of out)
|
|
301
|
+
decision.hasChanges = stated.get(decision.audience)?.has(decision.src) ?? false;
|
|
302
|
+
return out.sort((a, b) => byCode(a.day, b.day) || byCode(a.audience, b.audience) || byCode(a.ref, b.ref));
|
|
303
|
+
}
|
|
304
|
+
/** The words of every person's name and aliases in the graph. Two decisions that name the same person are not, by that, about the same thing. */
|
|
305
|
+
export function lineagePersonWords(store) {
|
|
306
|
+
const out = new Set();
|
|
307
|
+
for (const ref of store.listEntities("person")) {
|
|
308
|
+
const entity = store.readEntity(ref);
|
|
309
|
+
if (!entity)
|
|
310
|
+
continue;
|
|
311
|
+
for (const name of [entity.canonical_name, ...entity.aliases])
|
|
312
|
+
for (const word of lineageWords(name))
|
|
313
|
+
out.add(word);
|
|
314
|
+
}
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Rarity over one audience's decision statements: inverse document frequency, `ln(n / df) / ln(n)`, with `n` the
|
|
319
|
+
* number of statements (at least `corpusFloor`) and `df` the statements that hold the word. A word above the
|
|
320
|
+
* document-frequency cutoff and a word of a person's name weigh nothing.
|
|
321
|
+
*/
|
|
322
|
+
export function lineageCorpus(pool, personWords, rule = DEFAULT_LINEAGE_RETRIEVAL) {
|
|
323
|
+
const wordDocs = new Map();
|
|
324
|
+
const topicDocs = new Map();
|
|
325
|
+
for (const decision of pool) {
|
|
326
|
+
for (const word of decision.words)
|
|
327
|
+
wordDocs.set(word, (wordDocs.get(word) ?? 0) + 1);
|
|
328
|
+
for (const topic of decision.topics)
|
|
329
|
+
topicDocs.set(topic, (topicDocs.get(topic) ?? 0) + 1);
|
|
330
|
+
}
|
|
331
|
+
const size = pool.length;
|
|
332
|
+
const n = Math.max(size, rule.corpusFloor, 2);
|
|
333
|
+
const commonAbove = Math.max(rule.commonShare * size, rule.commonMinDocs);
|
|
334
|
+
const hubAbove = Math.max(rule.hubShare * size, rule.hubMinDocs);
|
|
335
|
+
const weights = new Map();
|
|
336
|
+
return {
|
|
337
|
+
size,
|
|
338
|
+
weight(word) {
|
|
339
|
+
const known = weights.get(word);
|
|
340
|
+
if (known !== undefined)
|
|
341
|
+
return known;
|
|
342
|
+
const docs = wordDocs.get(word) ?? 0;
|
|
343
|
+
const weight = docs === 0 || docs > commonAbove || personWords.has(word) ? 0 : Math.max(0, Math.log(n / docs) / Math.log(n));
|
|
344
|
+
weights.set(word, weight);
|
|
345
|
+
return weight;
|
|
346
|
+
},
|
|
347
|
+
hub: (topic) => (topicDocs.get(topic) ?? 0) > hubAbove,
|
|
348
|
+
topicWeight(topic) {
|
|
349
|
+
const docs = topicDocs.get(topic) ?? 0;
|
|
350
|
+
return docs === 0 || docs > hubAbove ? 0 : Math.max(0, Math.log(n / docs) / Math.log(n));
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** How much two decisions share: the summed rarity of their shared words, plus the bonus for a shared topic that is not a hub. */
|
|
355
|
+
export function lineageScore(decision, candidate, corpus, rule = DEFAULT_LINEAGE_RETRIEVAL) {
|
|
356
|
+
let score = 0;
|
|
357
|
+
for (const word of candidate.words)
|
|
358
|
+
if (decision.words.has(word))
|
|
359
|
+
score += corpus.weight(word);
|
|
360
|
+
let shared = false;
|
|
361
|
+
let rarest = 0;
|
|
362
|
+
for (const topic of candidate.topics) {
|
|
363
|
+
if (!decision.topics.has(topic) || corpus.hub(topic))
|
|
364
|
+
continue;
|
|
365
|
+
shared = true;
|
|
366
|
+
rarest = Math.max(rarest, corpus.topicWeight(topic));
|
|
367
|
+
}
|
|
368
|
+
return shared ? score + rule.topicBonus + rule.topicRarity * rarest : score;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The earlier decisions of the same audience that were open on the decision's day and may be what it
|
|
372
|
+
* changes: those that score at or above `minScore`, best first, at most `maxCandidates`.
|
|
373
|
+
* `pool` holds one audience's decisions, oldest first; `corpus` is that audience's.
|
|
374
|
+
*/
|
|
375
|
+
export function pickLineageCandidates(decision, pool, corpus, rule = DEFAULT_LINEAGE_RETRIEVAL) {
|
|
376
|
+
if (decision.words.size < MIN_WORDS)
|
|
377
|
+
return [];
|
|
378
|
+
const scored = [];
|
|
379
|
+
for (const candidate of pool) {
|
|
380
|
+
if (candidate.day >= decision.day)
|
|
381
|
+
break;
|
|
382
|
+
if (candidate.ref === decision.ref || candidate.words.size < MIN_WORDS)
|
|
383
|
+
continue;
|
|
384
|
+
if (candidate.closedOn !== undefined && candidate.closedOn < decision.day)
|
|
385
|
+
continue;
|
|
386
|
+
const score = lineageScore(decision, candidate, corpus, rule);
|
|
387
|
+
if (score < rule.minScore)
|
|
388
|
+
continue;
|
|
389
|
+
scored.push({ candidate, score });
|
|
390
|
+
}
|
|
391
|
+
scored.sort((a, b) => b.score - a.score || byCode(b.candidate.day, a.candidate.day) || byCode(a.candidate.ref, b.candidate.ref));
|
|
392
|
+
return scored.slice(0, rule.maxCandidates).map((entry) => entry.candidate);
|
|
393
|
+
}
|
|
394
|
+
// ---------------------------------------------------------------------------
|
|
395
|
+
// The walk's state, and the price of a run
|
|
396
|
+
// ---------------------------------------------------------------------------
|
|
397
|
+
/** Runs that may get an unusable reply for a decision before it is recorded as unanswered and its day is written without it. */
|
|
398
|
+
export const LINEAGE_MAX_ATTEMPTS = 3;
|
|
399
|
+
/** The share of turns an estimate's high figure counts a second time, for the retry turn an unusable reply costs. */
|
|
400
|
+
export const LINEAGE_RETRY_ALLOWANCE = 0.25;
|
|
401
|
+
const decisionKey = (audience, ref) => `${audience} ${ref}`;
|
|
402
|
+
/** Names the candidate list a decision was asked with, in order. A decision is asked again when the list changes. */
|
|
403
|
+
function signatureOf(candidates) {
|
|
404
|
+
if (candidates.length === 0)
|
|
405
|
+
return "-";
|
|
406
|
+
return createHash("sha256").update(candidates.map((candidate) => candidate.ref).join("\n")).digest("hex").slice(0, 10);
|
|
407
|
+
}
|
|
408
|
+
function sortedRecord(entries) {
|
|
409
|
+
return Object.fromEntries([...entries].sort((a, b) => byCode(a[0], b[0])));
|
|
410
|
+
}
|
|
411
|
+
/** The state of an earlier run on this model, prompt and retrieval rule, or null. An unreadable file, or one of another version, is no state. */
|
|
412
|
+
export function readLineageCursor(graphRoot, model) {
|
|
413
|
+
try {
|
|
414
|
+
const text = readTextIfExists(graphPath(graphRoot, LINEAGE_CURSOR_RELATIVE));
|
|
415
|
+
if (text === null)
|
|
416
|
+
return null;
|
|
417
|
+
const parsed = JSON.parse(text);
|
|
418
|
+
if (parsed.version !== 2 || parsed.model !== model || parsed.promptVersion !== LINEAGE_PROMPT_VERSION || parsed.retrievalVersion !== LINEAGE_RETRIEVAL_VERSION)
|
|
419
|
+
return null;
|
|
420
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
421
|
+
if (!isRecord(parsed.answered) || !isRecord(parsed.attempts) || !Array.isArray(parsed.unanswered))
|
|
422
|
+
return null;
|
|
423
|
+
const doneThrough = typeof parsed.doneThrough === "string" && /^\d{4}-\d{2}-\d{2}$/.test(parsed.doneThrough) ? parsed.doneThrough : null;
|
|
424
|
+
return {
|
|
425
|
+
version: 2, model, promptVersion: LINEAGE_PROMPT_VERSION, retrievalVersion: LINEAGE_RETRIEVAL_VERSION, doneThrough,
|
|
426
|
+
answered: sortedRecord(Object.entries(parsed.answered).filter((entry) => typeof entry[1] === "string")),
|
|
427
|
+
attempts: sortedRecord(Object.entries(parsed.attempts).filter((entry) => typeof entry[1] === "number" && entry[1] > 0)),
|
|
428
|
+
unanswered: parsed.unanswered.filter((key) => typeof key === "string").sort(byCode),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function ledgerLines(stateDir) {
|
|
436
|
+
const file = path.join(stateDir, ...MODEL_STATE_PATHS.callLedger.replace(/^\.state\//, "").split("/"));
|
|
437
|
+
try {
|
|
438
|
+
return readJsonLines(file);
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return [];
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* What a million input tokens cost on this model, from the list-price cost the CLI reported for the
|
|
446
|
+
* calls in the model step's ledger. The figure is blended: it holds the output of those calls too.
|
|
447
|
+
* Null when the ledger has no priced call of the model.
|
|
448
|
+
*/
|
|
449
|
+
export function ledgerRate(stateDir, model) {
|
|
450
|
+
let usd = 0;
|
|
451
|
+
let tokens = 0;
|
|
452
|
+
let calls = 0;
|
|
453
|
+
for (const line of ledgerLines(stateDir)) {
|
|
454
|
+
if (line.type !== "call" || line.model !== model || typeof line.costUsd !== "number" || !(line.costUsd > 0))
|
|
455
|
+
continue;
|
|
456
|
+
const input = Number(line.inputTokens) || 0;
|
|
457
|
+
if (input <= 0)
|
|
458
|
+
continue;
|
|
459
|
+
usd += line.costUsd;
|
|
460
|
+
tokens += input;
|
|
461
|
+
calls += 1;
|
|
462
|
+
}
|
|
463
|
+
return calls === 0 ? null : { usdPerMillionInputTokens: (usd / tokens) * 1_000_000, calls };
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Output tokens per decision, measured from the call ledger: this task's own calls on this model, else the
|
|
467
|
+
* supersession task's on this model, else the supersession task's on any model, else the fixed figure. Counted
|
|
468
|
+
* per decision and not per call, because the two tasks put a different number of decisions in a turn.
|
|
469
|
+
*/
|
|
470
|
+
export function ledgerOutput(stateDir, model) {
|
|
471
|
+
const lines = ledgerLines(stateDir).filter((line) => line.type === "call" && (line.outcome === "ok" || line.outcome === "partial") && Number(line.items) > 0 && Number(line.outputTokens) > 0);
|
|
472
|
+
const tries = [
|
|
473
|
+
{ kind: "decision-lineage", sameModel: true },
|
|
474
|
+
{ kind: "decision-supersession", sameModel: true },
|
|
475
|
+
{ kind: "decision-supersession", sameModel: false },
|
|
476
|
+
];
|
|
477
|
+
for (const { kind, sameModel } of tries) {
|
|
478
|
+
const calls = lines.filter((line) => line.kind === kind && (!sameModel || line.model === model));
|
|
479
|
+
if (calls.length === 0)
|
|
480
|
+
continue;
|
|
481
|
+
const items = calls.reduce((sum, line) => sum + Number(line.items), 0);
|
|
482
|
+
const output = calls.reduce((sum, line) => sum + Number(line.outputTokens), 0);
|
|
483
|
+
const mean = output / items;
|
|
484
|
+
const perCall = calls.map((line) => Number(line.outputTokens) / Number(line.items)).sort((a, b) => a - b);
|
|
485
|
+
const high = calls.length >= 5 ? perCall[Math.min(perCall.length - 1, Math.ceil(perCall.length * 0.9) - 1)] : mean * 2;
|
|
486
|
+
const models = new Set(calls.map((line) => line.model));
|
|
487
|
+
return { from: kind, model: sameModel ? model : models.size === 1 ? String([...models][0]) : null, calls: calls.length, tokensPerDecision: mean, highTokensPerDecision: Math.max(high, mean) };
|
|
488
|
+
}
|
|
489
|
+
return { from: "fixed", model: null, calls: 0, tokensPerDecision: LINEAGE_OUTPUT_TOKENS_PER_DECISION, highTokensPerDecision: LINEAGE_OUTPUT_TOKENS_PER_DECISION * 2 };
|
|
490
|
+
}
|
|
491
|
+
export async function runLineageBackfill(context, options, deps = {}) {
|
|
492
|
+
const env = deps.env ?? process.env;
|
|
493
|
+
// A folder stamped for another company, or one that could be anyone's, is not read for a dry run either.
|
|
494
|
+
if (!deps.store)
|
|
495
|
+
assertGraphWritableFor(context.graphRoot, context.company, context.companyRoot);
|
|
496
|
+
const dayBudget = resolveDayBudget(options);
|
|
497
|
+
const now = deps.now ?? (() => new Date());
|
|
498
|
+
const today = now().toISOString().slice(0, 10);
|
|
499
|
+
const run = `lineage-${now().toISOString().replace(/[-:.]/g, "").slice(0, 15)}Z-${String(process.pid)}`;
|
|
500
|
+
const step = deps.step ??
|
|
501
|
+
defaultCreateModelStep(context, {
|
|
502
|
+
budget: { inputTokens: dayBudget.inputTokens, outputTokens: dayBudget.outputTokens },
|
|
503
|
+
...(deps.runner ? { runner: deps.runner } : {}),
|
|
504
|
+
...(options.dryRun ? { dryRun: true, readOnly: true } : {}),
|
|
505
|
+
// The step would never send an item again after two unusable replies. This command keeps its own count and decides.
|
|
506
|
+
retryParked: true,
|
|
507
|
+
runId: run,
|
|
508
|
+
now,
|
|
509
|
+
});
|
|
510
|
+
const by = `agent:${step.model}`;
|
|
511
|
+
const store = deps.store ?? openGraphStore(context.graphRoot, { company: context.company });
|
|
512
|
+
const spec = lineageSpec(today);
|
|
513
|
+
const notes = [];
|
|
514
|
+
const decisions = loadLineageDecisions(store);
|
|
515
|
+
const personWords = lineagePersonWords(store);
|
|
516
|
+
const pools = new Map();
|
|
517
|
+
const index = new Map();
|
|
518
|
+
for (const decision of decisions) {
|
|
519
|
+
pools.set(decision.audience, [...(pools.get(decision.audience) ?? []), decision]);
|
|
520
|
+
index.set(`${decision.audience}\n${decision.ref}`, decision);
|
|
521
|
+
}
|
|
522
|
+
const corpora = new Map();
|
|
523
|
+
for (const [audience, pool] of pools)
|
|
524
|
+
corpora.set(audience, lineageCorpus(pool, personWords));
|
|
525
|
+
const eligible = decisions.filter((decision) => !decision.hasChanges);
|
|
526
|
+
const byDay = new Map();
|
|
527
|
+
for (const decision of eligible)
|
|
528
|
+
byDay.set(decision.day, [...(byDay.get(decision.day) ?? []), decision]);
|
|
529
|
+
const allDays = [...byDay.keys()].sort();
|
|
530
|
+
const days = allDays.filter((day) => (!options.from || day >= options.from) && (!options.to || day <= options.to));
|
|
531
|
+
// `--restart` starts from nothing: no decision settled, no attempt counted, none recorded as unanswered.
|
|
532
|
+
const held = options.restart ? null : readLineageCursor(context.graphRoot, step.model);
|
|
533
|
+
const answered = new Map(Object.entries(held?.answered ?? {}));
|
|
534
|
+
const attempts = new Map(Object.entries(held?.attempts ?? {}));
|
|
535
|
+
const unanswered = new Set(held?.unanswered ?? []);
|
|
536
|
+
const settled = (decision) => {
|
|
537
|
+
const key = decisionKey(decision.audience, decision.ref);
|
|
538
|
+
return answered.has(key) || unanswered.has(key);
|
|
539
|
+
};
|
|
540
|
+
/** Every day up to and including this one has no decision left to settle. */
|
|
541
|
+
const doneThrough = () => {
|
|
542
|
+
let done = null;
|
|
543
|
+
for (const day of allDays) {
|
|
544
|
+
if (!(byDay.get(day) ?? []).every(settled))
|
|
545
|
+
break;
|
|
546
|
+
done = day;
|
|
547
|
+
}
|
|
548
|
+
return done;
|
|
549
|
+
};
|
|
550
|
+
const before = doneThrough();
|
|
551
|
+
if (!options.dryRun && options.from && allDays.some((day) => day < options.from && !(byDay.get(day) ?? []).every(settled))) {
|
|
552
|
+
notes.push("The cursor is not moved: --from leaves earlier days unasked.");
|
|
553
|
+
}
|
|
554
|
+
const report = {
|
|
555
|
+
run, model: step.model, day: today, dryRun: options.dryRun, graphRoot: context.graphRoot,
|
|
556
|
+
range: { ...(options.from ? { from: options.from } : {}), ...(options.to ? { to: options.to } : {}) },
|
|
557
|
+
decisions: { total: decisions.length, audiences: pools.size, withChanges: decisions.length - eligible.length, inRange: 0, asked: 0, noCandidates: 0, settled: 0 },
|
|
558
|
+
days: { toWalk: 0, done: 0 },
|
|
559
|
+
batches: 0,
|
|
560
|
+
items: { cached: 0, answered: 0, pending: 0, parked: 0 },
|
|
561
|
+
unanswered: { total: unanswered.size, thisRun: 0, held: 0, recovered: 0, maxAttempts: LINEAGE_MAX_ATTEMPTS },
|
|
562
|
+
unansweredDecisions: { recorded: [...unanswered].sort(byCode), held: [] },
|
|
563
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
564
|
+
dropped: {},
|
|
565
|
+
pairs: { accepted: 0, applied: 0, alreadyApplied: 0, alreadyLinked: 0, skipped: {} },
|
|
566
|
+
written: { links: 0, replaces: 0, reverses: 0, rowsAdded: 0 },
|
|
567
|
+
cap: { dayInputTokens: dayBudget.inputTokens, dayOutputTokens: dayBudget.outputTokens, overridden: dayBudget.overridden },
|
|
568
|
+
cursor: { before, after: before, moved: false },
|
|
569
|
+
notes,
|
|
570
|
+
};
|
|
571
|
+
const estimate = { decisions: 0, batches: 0, inputTokens: 0 };
|
|
572
|
+
const touched = new Set();
|
|
573
|
+
let claimed = Boolean(deps.store);
|
|
574
|
+
/** What every writer does before its first write: the folder says whose it is from then on. */
|
|
575
|
+
const claim = () => {
|
|
576
|
+
if (claimed)
|
|
577
|
+
return;
|
|
578
|
+
claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
|
|
579
|
+
claimed = true;
|
|
580
|
+
};
|
|
581
|
+
const stateFile = graphPath(context.graphRoot, LINEAGE_CURSOR_RELATIVE);
|
|
582
|
+
/** Writes the state when it differs from the file. A run that settled nothing and found no file leaves none. */
|
|
583
|
+
const save = () => {
|
|
584
|
+
const state = {
|
|
585
|
+
version: 2, model: step.model, promptVersion: LINEAGE_PROMPT_VERSION, retrievalVersion: LINEAGE_RETRIEVAL_VERSION, doneThrough: doneThrough(),
|
|
586
|
+
answered: sortedRecord(answered), attempts: sortedRecord(attempts), unanswered: [...unanswered].sort(byCode),
|
|
587
|
+
};
|
|
588
|
+
const text = `${JSON.stringify(state)}\n`;
|
|
589
|
+
const onDisk = readTextIfExists(stateFile);
|
|
590
|
+
if (onDisk === text)
|
|
591
|
+
return;
|
|
592
|
+
if (onDisk === null && answered.size === 0 && attempts.size === 0 && unanswered.size === 0)
|
|
593
|
+
return;
|
|
594
|
+
claim();
|
|
595
|
+
atomicWriteFile(stateFile, text);
|
|
596
|
+
};
|
|
597
|
+
let stopped = false;
|
|
598
|
+
try {
|
|
599
|
+
for (const day of days) {
|
|
600
|
+
// What this day has left to settle: a decision an earlier run answered with the same candidates is not looked at again.
|
|
601
|
+
const work = [];
|
|
602
|
+
for (const decision of byDay.get(day) ?? []) {
|
|
603
|
+
const key = decisionKey(decision.audience, decision.ref);
|
|
604
|
+
if (unanswered.has(key) && !options.retryUnanswered)
|
|
605
|
+
continue;
|
|
606
|
+
const candidates = pickLineageCandidates(decision, pools.get(decision.audience) ?? [], corpora.get(decision.audience) ?? lineageCorpus([], personWords));
|
|
607
|
+
const signature = signatureOf(candidates);
|
|
608
|
+
if (!unanswered.has(key) && answered.get(key) === signature) {
|
|
609
|
+
report.decisions.settled += 1;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
work.push({ decision, candidates, key, signature });
|
|
613
|
+
}
|
|
614
|
+
if (work.length === 0)
|
|
615
|
+
continue;
|
|
616
|
+
report.days.toWalk += 1;
|
|
617
|
+
report.range.firstDay ??= day;
|
|
618
|
+
report.range.lastDay = day;
|
|
619
|
+
// After a stop the later days are counted and not asked.
|
|
620
|
+
if (stopped)
|
|
621
|
+
continue;
|
|
622
|
+
report.decisions.inRange += work.length;
|
|
623
|
+
const pairs = [];
|
|
624
|
+
let halt = null;
|
|
625
|
+
let heldToday = 0;
|
|
626
|
+
for (const audience of [...new Set(work.map((entry) => entry.decision.audience))].sort()) {
|
|
627
|
+
const items = [];
|
|
628
|
+
for (const { decision, candidates, key } of work) {
|
|
629
|
+
if (decision.audience !== audience)
|
|
630
|
+
continue;
|
|
631
|
+
if (candidates.length === 0) {
|
|
632
|
+
report.decisions.noCandidates += 1;
|
|
633
|
+
// Recorded as unanswered by an earlier run and with nothing to compare now: there is nothing left to ask.
|
|
634
|
+
if (unanswered.delete(key))
|
|
635
|
+
report.unanswered.recovered += 1;
|
|
636
|
+
attempts.delete(key);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
items.push({
|
|
640
|
+
ref: decision.ref, audience, date: decision.day, text: decision.text,
|
|
641
|
+
earlier: candidates.map((candidate) => ({ ref: candidate.ref, date: candidate.day, text: candidate.text })),
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
if (items.length === 0)
|
|
645
|
+
continue;
|
|
646
|
+
report.decisions.asked += items.length;
|
|
647
|
+
// One audience per call: a turn never holds decisions from two audience folders.
|
|
648
|
+
const asked = await step.runBatch(spec, items);
|
|
649
|
+
report.batches += asked.stats.calls;
|
|
650
|
+
report.usage.inputTokens += Math.round(asked.stats.usage.inputTokens);
|
|
651
|
+
report.usage.outputTokens += Math.round(asked.stats.usage.outputTokens);
|
|
652
|
+
const unsent = [];
|
|
653
|
+
for (const result of asked.results) {
|
|
654
|
+
const key = decisionKey(audience, result.item.ref);
|
|
655
|
+
if (result.status === "pending") {
|
|
656
|
+
report.items.pending += 1;
|
|
657
|
+
unsent.push(result.item);
|
|
658
|
+
halt ??= result.reason ?? "pending";
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (result.status === "parked") {
|
|
662
|
+
// No usable reply after the step's own retry turn. Counted across runs: the decision is sent again by the
|
|
663
|
+
// next run until it has had its attempts, and its day is not written before that.
|
|
664
|
+
report.items.parked += 1;
|
|
665
|
+
const count = (attempts.get(key) ?? 0) + 1;
|
|
666
|
+
attempts.set(key, count);
|
|
667
|
+
if (unanswered.has(key))
|
|
668
|
+
continue;
|
|
669
|
+
if (options.allowUnanswered || count >= LINEAGE_MAX_ATTEMPTS) {
|
|
670
|
+
unanswered.add(key);
|
|
671
|
+
report.unanswered.thisRun += 1;
|
|
672
|
+
}
|
|
673
|
+
else {
|
|
674
|
+
heldToday += 1;
|
|
675
|
+
report.unansweredDecisions.held.push(key);
|
|
676
|
+
}
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
if (unanswered.delete(key))
|
|
680
|
+
report.unanswered.recovered += 1;
|
|
681
|
+
attempts.delete(key);
|
|
682
|
+
if (result.status === "cached")
|
|
683
|
+
report.items.cached += 1;
|
|
684
|
+
else
|
|
685
|
+
report.items.answered += 1;
|
|
686
|
+
const answer = result.value;
|
|
687
|
+
if (!answer)
|
|
688
|
+
continue;
|
|
689
|
+
for (const [reason, count] of Object.entries(answer.dropped))
|
|
690
|
+
report.dropped[reason] = (report.dropped[reason] ?? 0) + (count ?? 0);
|
|
691
|
+
const newer = index.get(`${audience}\n${result.item.ref}`);
|
|
692
|
+
if (!newer)
|
|
693
|
+
continue;
|
|
694
|
+
for (const change of answer.changes) {
|
|
695
|
+
const older = result.item.earlier[change.older];
|
|
696
|
+
// Checked again against what the graph holds now: the answer may come from the cache of another run.
|
|
697
|
+
const known = older ? index.get(`${audience}\n${older.ref}`) : undefined;
|
|
698
|
+
if (!known || known.ref === newer.ref || !(known.day < newer.day)) {
|
|
699
|
+
report.dropped.target_not_older = (report.dropped.target_not_older ?? 0) + 1;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
pairs.push({ newer: newer.ref, older: known.ref, audience, kind: change.kind, day: newer.day, src: newer.src, quote: change.quote, oldQuote: change.oldQuote });
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
if (options.dryRun && unsent.length > 0) {
|
|
706
|
+
const turns = estimateLineageTurns(unsent, CLI_OVERHEAD_TOKENS);
|
|
707
|
+
estimate.decisions += unsent.length;
|
|
708
|
+
estimate.batches += turns.turns;
|
|
709
|
+
estimate.inputTokens += turns.inputTokens;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
if (options.dryRun)
|
|
713
|
+
continue;
|
|
714
|
+
if (halt !== null || heldToday > 0) {
|
|
715
|
+
// A day is written whole or not at all: what was answered stays in the cache for the next run.
|
|
716
|
+
report.unanswered.held += heldToday;
|
|
717
|
+
report.stopped = { reason: halt ?? "unanswered", day };
|
|
718
|
+
stopped = true;
|
|
719
|
+
save();
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
report.pairs.accepted += pairs.length;
|
|
723
|
+
if (pairs.length > 0) {
|
|
724
|
+
claim();
|
|
725
|
+
const applied = applyLineagePairs(store, pairs, { by, learned: today });
|
|
726
|
+
report.pairs.applied += applied.applied;
|
|
727
|
+
report.pairs.alreadyApplied += applied.alreadyApplied;
|
|
728
|
+
report.pairs.alreadyLinked += applied.alreadyLinked;
|
|
729
|
+
for (const [reason, count] of Object.entries(applied.skipped))
|
|
730
|
+
report.pairs.skipped[reason] = (report.pairs.skipped[reason] ?? 0) + count;
|
|
731
|
+
report.written.links += applied.links;
|
|
732
|
+
report.written.replaces += applied.kinds.replaces ?? 0;
|
|
733
|
+
report.written.reverses += applied.kinds.reverses ?? 0;
|
|
734
|
+
report.written.rowsAdded += applied.rowsAdded;
|
|
735
|
+
for (const ref of applied.touched)
|
|
736
|
+
touched.add(ref);
|
|
737
|
+
for (const record of applied.records)
|
|
738
|
+
appendJsonLine(graphPath(context.graphRoot, LINEAGE_APPLIED_RELATIVE), { run, ...record });
|
|
739
|
+
// Later days see the earlier decision as closed from this day on.
|
|
740
|
+
for (const target of applied.closedTargets) {
|
|
741
|
+
const known = index.get(`${target.audience}\n${target.ref}`);
|
|
742
|
+
if (known && (known.closedOn === undefined || target.day < known.closedOn))
|
|
743
|
+
known.closedOn = target.day;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
for (const entry of work)
|
|
747
|
+
if (!unanswered.has(entry.key))
|
|
748
|
+
answered.set(entry.key, entry.signature);
|
|
749
|
+
report.days.done += 1;
|
|
750
|
+
save();
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
finally {
|
|
754
|
+
// The state file is how this command resumes. A marker left in the step's pending file would be counted by `update` as its own follow-up work.
|
|
755
|
+
if (!options.dryRun)
|
|
756
|
+
step.dropPending(step.pending("decision-lineage").map((marker) => marker.id));
|
|
757
|
+
}
|
|
758
|
+
report.unanswered.total = unanswered.size;
|
|
759
|
+
report.unansweredDecisions = { recorded: [...unanswered].sort(byCode), held: [...new Set(report.unansweredDecisions.held)].sort(byCode) };
|
|
760
|
+
if (options.dryRun) {
|
|
761
|
+
report.items.pending = estimate.decisions;
|
|
762
|
+
const stateDir = resolveModelStateDir(context, undefined, env);
|
|
763
|
+
const rate = ledgerRate(stateDir, step.model);
|
|
764
|
+
const basis = ledgerOutput(stateDir, step.model);
|
|
765
|
+
const retry = 1 + LINEAGE_RETRY_ALLOWANCE;
|
|
766
|
+
const inputTokensHigh = Math.round(estimate.inputTokens * retry);
|
|
767
|
+
const outputTokens = Math.round(estimate.decisions * basis.tokensPerDecision);
|
|
768
|
+
const outputTokensHigh = Math.round(estimate.decisions * basis.highTokensPerDecision * retry);
|
|
769
|
+
const cost = (tokens) => (rate ? Math.round(((tokens * rate.usdPerMillionInputTokens) / 1_000_000) * 100) / 100 : null);
|
|
770
|
+
const roundUp = (tokens) => Math.ceil(tokens / 10_000) * 10_000;
|
|
771
|
+
const overCap = inputTokensHigh > dayBudget.inputTokens || outputTokensHigh > dayBudget.outputTokens;
|
|
772
|
+
report.estimate = {
|
|
773
|
+
...estimate,
|
|
774
|
+
inputTokensHigh,
|
|
775
|
+
outputTokens,
|
|
776
|
+
outputTokensHigh,
|
|
777
|
+
costUsd: cost(estimate.inputTokens),
|
|
778
|
+
costUsdHigh: cost(inputTokensHigh),
|
|
779
|
+
usdPerMillionInputTokens: rate ? Math.round(rate.usdPerMillionInputTokens * 100) / 100 : null,
|
|
780
|
+
pricedCalls: rate?.calls ?? 0,
|
|
781
|
+
outputBasis: { ...basis, tokensPerDecision: Math.round(basis.tokensPerDecision * 10) / 10, highTokensPerDecision: Math.round(basis.highTokensPerDecision * 10) / 10 },
|
|
782
|
+
retryAllowance: LINEAGE_RETRY_ALLOWANCE,
|
|
783
|
+
capFlags: overCap ? `--max-input-tokens ${String(Math.max(roundUp(inputTokensHigh), dayBudget.inputTokens))} --max-output-tokens ${String(Math.max(roundUp(outputTokensHigh), dayBudget.outputTokens))}` : null,
|
|
784
|
+
};
|
|
785
|
+
notes.push("The count of decisions to send is an upper bound: a dry run writes nothing, so later days are offered decisions an earlier day of the real run would have closed.");
|
|
786
|
+
return report;
|
|
787
|
+
}
|
|
788
|
+
save();
|
|
789
|
+
report.cursor.after = doneThrough();
|
|
790
|
+
report.cursor.moved = report.cursor.after !== report.cursor.before;
|
|
791
|
+
const halted = step.halted();
|
|
792
|
+
if (report.stopped && report.stopped.reason !== "unanswered" && halted && halted !== report.stopped.reason)
|
|
793
|
+
report.stopped.reason = halted;
|
|
794
|
+
if (touched.size > 0) {
|
|
795
|
+
store.appendLog({
|
|
796
|
+
date: today, op: "update", subject: run, touched: [...touched].sort(), rowsAdded: report.written.rowsAdded, rowsClosed: 0,
|
|
797
|
+
note: `lineage backfill: decisions compared in date order on ${step.model}`,
|
|
798
|
+
});
|
|
799
|
+
const compiler = deps.compilePages === undefined ? defaultCompilePages : deps.compilePages;
|
|
800
|
+
// No model is passed: pages are rendered from rows, and no summary is asked for.
|
|
801
|
+
if (compiler)
|
|
802
|
+
await compiler(context, { store: openGraphStore(context.graphRoot, { company: context.company }), day: today });
|
|
803
|
+
}
|
|
804
|
+
return report;
|
|
805
|
+
}
|
|
806
|
+
function plural(count, one, many = `${one}s`) {
|
|
807
|
+
return `${String(count)} ${count === 1 ? one : many}`;
|
|
808
|
+
}
|
|
809
|
+
function reasons(counts) {
|
|
810
|
+
return Object.entries(counts)
|
|
811
|
+
.filter(([, count]) => count > 0)
|
|
812
|
+
.sort((a, b) => byCode(a[0], b[0]))
|
|
813
|
+
.map(([reason, count]) => `${reason} ${String(count)}`)
|
|
814
|
+
.join(", ");
|
|
815
|
+
}
|
|
816
|
+
function span(low, high) {
|
|
817
|
+
return low === high ? String(low) : `${String(low)} to ${String(high)}`;
|
|
818
|
+
}
|
|
819
|
+
export function formatLineageBackfillReport(report) {
|
|
820
|
+
const lines = [
|
|
821
|
+
`lineage backfill${report.dryRun ? " (dry run, no model call, nothing written)" : ""}: decisions compared in date order on ${report.model}`,
|
|
822
|
+
`decisions: ${String(report.decisions.total)} in ${plural(report.decisions.audiences, "audience")}; ${String(report.decisions.withChanges)} left out (their signal already states a change)${report.decisions.settled > 0 ? `; ${String(report.decisions.settled)} settled by an earlier run` : ""}`,
|
|
823
|
+
report.days.toWalk === 0
|
|
824
|
+
? "nothing to walk: no decision left to settle in this range"
|
|
825
|
+
: `days: ${String(report.days.toWalk)} (${report.range.firstDay ?? ""} to ${report.range.lastDay ?? ""}), ${plural(report.decisions.inRange, "decision")}; ${String(report.decisions.asked)} with earlier open decisions to compare, ${String(report.decisions.noCandidates)} with none (not sent)`,
|
|
826
|
+
];
|
|
827
|
+
const unanswered = report.unanswered;
|
|
828
|
+
if (report.dryRun) {
|
|
829
|
+
const estimate = report.estimate;
|
|
830
|
+
lines.push(`already answered: ${plural(report.items.cached, "decision")} (0 tokens); to send: ${plural(estimate?.decisions ?? 0, "decision")} in ${plural(estimate?.batches ?? 0, "batch", "batches")}`);
|
|
831
|
+
if (estimate) {
|
|
832
|
+
const basis = estimate.outputBasis;
|
|
833
|
+
lines.push(`estimate: ${span(estimate.inputTokens, estimate.inputTokensHigh)} input tokens and ${span(estimate.outputTokens, estimate.outputTokensHigh)} output tokens (low: no retry turn, mean output; high: a retry turn for ${String(Math.round(estimate.retryAllowance * 100))}% of the batches, output at the 90th percentile)`);
|
|
834
|
+
lines.push(basis.from === "fixed"
|
|
835
|
+
? `output basis: ${String(basis.tokensPerDecision)} to ${String(basis.highTokensPerDecision)} tokens per decision, a fixed figure (the call ledger holds no call of this task or of decision-supersession)`
|
|
836
|
+
: `output basis: ${String(basis.tokensPerDecision)} to ${String(basis.highTokensPerDecision)} tokens per decision, measured over ${plural(basis.calls, "call")} of ${basis.from}${basis.model ? ` on ${basis.model}` : ""} in the call ledger`);
|
|
837
|
+
lines.push(estimate.costUsd === null || estimate.costUsdHigh === null
|
|
838
|
+
? `list-price cost: not estimated (the call ledger holds no priced call of ${report.model})`
|
|
839
|
+
: `list-price cost: about $${estimate.costUsd.toFixed(2)} to $${estimate.costUsdHigh.toFixed(2)} (estimate; $${(estimate.usdPerMillionInputTokens ?? 0).toFixed(2)} per million input tokens, blended over ${plural(estimate.pricedCalls, "priced call")} of ${report.model} in the call ledger)`);
|
|
840
|
+
lines.push(`daily cap for a run: ${String(report.cap.dayInputTokens)} input tokens, ${String(report.cap.dayOutputTokens)} output tokens`);
|
|
841
|
+
if (estimate.capFlags) {
|
|
842
|
+
lines.push(`The estimate is over the daily cap. A run stops at the cap and the next run carries on. To let the whole estimate through in one run, add: ${estimate.capFlags} (the cap also counts the day's other runs on this model).`);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (unanswered.total > 0)
|
|
846
|
+
lines.push(`unanswered: ${plural(unanswered.total, "decision")} recorded by earlier runs, not sent (--retry-unanswered sends them)`);
|
|
847
|
+
}
|
|
848
|
+
else {
|
|
849
|
+
lines.push(`days done ${String(report.days.done)} of ${String(report.days.toWalk)}; batches ${String(report.batches)}; answered ${String(report.items.answered)}, from cache ${String(report.items.cached)}, not usable ${String(report.items.parked)}; tokens in ${String(report.usage.inputTokens)} out ${String(report.usage.outputTokens)}`);
|
|
850
|
+
const written = report.written;
|
|
851
|
+
lines.push(`written: ${plural(written.links, "lineage link")} at model authority (the model said replaces for ${String(written.replaces)}, reverses for ${String(written.reverses)}; readers show each as replaced); no status row written or closed`);
|
|
852
|
+
if (report.pairs.alreadyApplied > 0)
|
|
853
|
+
lines.push(`${plural(report.pairs.alreadyApplied, "pair")} already in the graph: nothing written for ${report.pairs.alreadyApplied === 1 ? "it" : "them"}`);
|
|
854
|
+
if (report.pairs.alreadyLinked > 0)
|
|
855
|
+
lines.push(`${plural(report.pairs.alreadyLinked, "pair")} already linked by another model (already_linked): no second link written`);
|
|
856
|
+
if (reasons(report.pairs.skipped) !== "")
|
|
857
|
+
lines.push(`pairs left alone: ${reasons(report.pairs.skipped)}`);
|
|
858
|
+
if (unanswered.total > 0 || unanswered.thisRun > 0 || unanswered.held > 0 || unanswered.recovered > 0) {
|
|
859
|
+
lines.push(`unanswered: ${plural(unanswered.total, "decision")} recorded (${String(unanswered.thisRun)} by this run, after ${plural(unanswered.maxAttempts, "run")} with no usable reply or under --allow-unanswered); ${String(unanswered.held)} held to be sent again; ${String(unanswered.recovered)} answered on a retry. --retry-unanswered sends the recorded ones again.`);
|
|
860
|
+
}
|
|
861
|
+
lines.push(`cursor: ${report.cursor.after ?? "none"}${report.cursor.moved ? ` (was ${report.cursor.before ?? "none"})` : ""}`);
|
|
862
|
+
if (report.stopped?.reason === "unanswered") {
|
|
863
|
+
lines.push(`stopped (unanswered) on ${report.stopped.day}: ${plural(unanswered.held, "decision")} of that day got no usable reply, so that day and the days after it are not written. Run again: a decision is sent in up to ${String(unanswered.maxAttempts)} runs, then recorded as unanswered and its day written without it. --allow-unanswered records it at once.`);
|
|
864
|
+
}
|
|
865
|
+
else if (report.stopped) {
|
|
866
|
+
lines.push(`stopped (${report.stopped.reason}) on ${report.stopped.day}: that day and the days after it are not written. Run again to carry on.`);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
if (reasons(report.dropped) !== "")
|
|
870
|
+
lines.push(`entries dropped by the host's checks: ${reasons(report.dropped)}`);
|
|
871
|
+
lines.push(`graph: ${report.graphRoot}`);
|
|
872
|
+
for (const note of report.notes)
|
|
873
|
+
lines.push(`note: ${note}`);
|
|
874
|
+
return lines.join("\n");
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* `hq ontology lineage backfill`. Exit code 2 when the walk stopped before its last day (a cap, a usage limit, a
|
|
878
|
+
* sign-out, or a decision with no usable reply). Exit code 3 when the walk finished and a decision got no usable
|
|
879
|
+
* reply in this run, unless `--allow-unanswered` was passed.
|
|
880
|
+
*/
|
|
881
|
+
export async function lineageBackfillCommand(context, options, deps = {}) {
|
|
882
|
+
const report = await runLineageBackfill(context, options, deps);
|
|
883
|
+
const exitCode = report.stopped ? 2 : report.items.parked > 0 && !options.allowUnanswered ? 3 : 0;
|
|
884
|
+
return { text: formatLineageBackfillReport(report), json: report, ...(exitCode !== 0 ? { exitCode } : {}) };
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* `hq ontology lineage undo`: removes the rows `.state/lineage-backfill.jsonl` lists, the edge and its inverse of
|
|
888
|
+
* each link, and nothing else. The record file is not trusted: a row is removed only when the recorded origin is a
|
|
889
|
+
* model's (`agent:`) and the graph still holds the row under the recorded id, as an open `supersedes` or
|
|
890
|
+
* `superseded_by` edge of that origin. A line that names another origin (a rule, a person, a record) or a row of
|
|
891
|
+
* another kind removes nothing (`skipped_not_model_link`). A row that was closed since (by the rule
|
|
892
|
+
* `signal-changes`, for a signal that states the opposite) or differs in any other way is left and counted. When
|
|
893
|
+
* the graph holds none of the recorded rows, the record is of another graph: nothing is removed and the record file
|
|
894
|
+
* and the walk's state stay (`mismatch`). Otherwise the walk's state file is removed, so a later backfill starts
|
|
895
|
+
* clean. The reply cache is not touched.
|
|
896
|
+
*/
|
|
897
|
+
export async function runLineageUndo(context, options, deps = {}) {
|
|
898
|
+
if (!deps.store)
|
|
899
|
+
assertGraphWritableFor(context.graphRoot, context.company, context.companyRoot);
|
|
900
|
+
const now = deps.now ?? (() => new Date());
|
|
901
|
+
const today = now().toISOString().slice(0, 10);
|
|
902
|
+
const run = `lineage-undo-${now().toISOString().replace(/[-:.]/g, "").slice(0, 15)}Z-${String(process.pid)}`;
|
|
903
|
+
const store = deps.store ?? openGraphStore(context.graphRoot, { company: context.company });
|
|
904
|
+
const recordFile = graphPath(context.graphRoot, LINEAGE_APPLIED_RELATIVE);
|
|
905
|
+
const stateFile = graphPath(context.graphRoot, LINEAGE_CURSOR_RELATIVE);
|
|
906
|
+
const records = readTextIfExists(recordFile) === null ? [] : readJsonLines(recordFile);
|
|
907
|
+
const report = {
|
|
908
|
+
run, dryRun: options.dryRun, graphRoot: context.graphRoot, records: records.length, links: { removed: 0, kept: 0 },
|
|
909
|
+
rows: { removed: 0, missing: 0, changed: 0 }, changedBy: {}, mismatch: false, stateCleared: false, touched: [], notes: [],
|
|
910
|
+
};
|
|
911
|
+
const removeRows = store.removeRows?.bind(store);
|
|
912
|
+
if (!removeRows)
|
|
913
|
+
throw new Error("This graph store cannot remove rows, so the lineage backfill cannot be undone on it.");
|
|
914
|
+
if (!deps.store && !options.dryRun && (records.length > 0 || readTextIfExists(stateFile) !== null))
|
|
915
|
+
claimGraphRootFor(context.graphRoot, context.company, context.companyRoot);
|
|
916
|
+
const touched = new Set();
|
|
917
|
+
const kept = [];
|
|
918
|
+
const changed = (reason) => {
|
|
919
|
+
report.rows.changed += 1;
|
|
920
|
+
report.changedBy[reason] = (report.changedBy[reason] ?? 0) + 1;
|
|
921
|
+
};
|
|
922
|
+
for (const record of records) {
|
|
923
|
+
const rows = Array.isArray(record.rows) ? record.rows : [];
|
|
924
|
+
if (typeof record.audience !== "string" || typeof record.by !== "string" || rows.length === 0) {
|
|
925
|
+
changed("record_unreadable");
|
|
926
|
+
kept.push(record);
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
// Only a model writes a lineage link, so a line that names any other origin is not one of the backfill's.
|
|
930
|
+
const modelOrigin = record.by.startsWith("agent:");
|
|
931
|
+
let left = 0;
|
|
932
|
+
let removed = 0;
|
|
933
|
+
for (const listed of rows) {
|
|
934
|
+
const stored = store.readRows(listed.entity, { audiences: [record.audience] }).find((each) => each.id === listed.id);
|
|
935
|
+
if (!stored) {
|
|
936
|
+
report.rows.missing += 1;
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
const row = stored.row;
|
|
940
|
+
const reason = !modelOrigin || row.kind !== "E" || (row.verb !== "supersedes" && row.verb !== "superseded_by")
|
|
941
|
+
? "skipped_not_model_link"
|
|
942
|
+
: row.by !== record.by
|
|
943
|
+
? "origin_differs"
|
|
944
|
+
: !isOpen(row)
|
|
945
|
+
? "closed_since"
|
|
946
|
+
: null;
|
|
947
|
+
if (reason !== null) {
|
|
948
|
+
changed(reason);
|
|
949
|
+
left += 1;
|
|
950
|
+
continue;
|
|
951
|
+
}
|
|
952
|
+
if (!options.dryRun)
|
|
953
|
+
removeRows(listed.entity, record.audience, [listed.id]);
|
|
954
|
+
report.rows.removed += 1;
|
|
955
|
+
removed += 1;
|
|
956
|
+
touched.add(listed.entity);
|
|
957
|
+
}
|
|
958
|
+
if (left > 0) {
|
|
959
|
+
report.links.kept += 1;
|
|
960
|
+
kept.push(record);
|
|
961
|
+
}
|
|
962
|
+
else if (removed > 0) {
|
|
963
|
+
report.links.removed += 1;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
report.touched = [...touched].sort();
|
|
967
|
+
// Every row looked up was absent: the record was written for another graph. No row was removed (a row is removed
|
|
968
|
+
// only after it is found), and the record file and the walk's state are left for the graph they belong to.
|
|
969
|
+
if (report.rows.missing > 0 && report.rows.removed === 0 && report.rows.changed === 0) {
|
|
970
|
+
report.mismatch = true;
|
|
971
|
+
report.notes.push(`If the rows were taken out of this graph by hand, delete ${LINEAGE_APPLIED_RELATIVE} yourself; undo does not.`);
|
|
972
|
+
return report;
|
|
973
|
+
}
|
|
974
|
+
report.stateCleared = readTextIfExists(stateFile) !== null;
|
|
975
|
+
if (kept.length > 0)
|
|
976
|
+
report.notes.push(`${plural(kept.length, "line")} stay in ${LINEAGE_APPLIED_RELATIVE}: a row of each was left in the graph.`);
|
|
977
|
+
report.notes.push("The reply cache is not touched: a later backfill on the same model and prompt gets the same answers from it at no cost and writes the same links.");
|
|
978
|
+
if (options.dryRun)
|
|
979
|
+
return report;
|
|
980
|
+
if (records.length > 0) {
|
|
981
|
+
if (kept.length === 0)
|
|
982
|
+
fs.rmSync(recordFile, { force: true });
|
|
983
|
+
else
|
|
984
|
+
atomicWriteFile(recordFile, kept.map((record) => `${JSON.stringify(record)}\n`).join(""));
|
|
985
|
+
}
|
|
986
|
+
if (report.stateCleared)
|
|
987
|
+
fs.rmSync(stateFile, { force: true });
|
|
988
|
+
if (touched.size > 0) {
|
|
989
|
+
store.markDirty(report.touched);
|
|
990
|
+
store.appendLog({ date: today, op: "update", subject: run, touched: report.touched, rowsAdded: 0, rowsClosed: 0, note: `lineage undo: ${plural(report.rows.removed, "row")} of the lineage backfill removed` });
|
|
991
|
+
const compiler = deps.compilePages === undefined ? defaultCompilePages : deps.compilePages;
|
|
992
|
+
if (compiler)
|
|
993
|
+
await compiler(context, { store: openGraphStore(context.graphRoot, { company: context.company }), day: today });
|
|
994
|
+
}
|
|
995
|
+
return report;
|
|
996
|
+
}
|
|
997
|
+
export function formatLineageUndoReport(report) {
|
|
998
|
+
const verb = report.dryRun ? "would remove" : "removed";
|
|
999
|
+
const lines = [`lineage undo${report.dryRun ? " (dry run, nothing written)" : ""}: ${plural(report.records, "link")} listed in ${LINEAGE_APPLIED_RELATIVE}`];
|
|
1000
|
+
if (report.mismatch) {
|
|
1001
|
+
lines.push(`the record does not match this graph: none of its ${plural(report.rows.missing, "recorded row")} is in it. Nothing removed; the record file and the walk's state are kept.`);
|
|
1002
|
+
lines.push(`graph: ${report.graphRoot}`);
|
|
1003
|
+
for (const note of report.notes)
|
|
1004
|
+
lines.push(`note: ${note}`);
|
|
1005
|
+
return lines.join("\n");
|
|
1006
|
+
}
|
|
1007
|
+
lines.push(report.rows.missing > 0
|
|
1008
|
+
? `${verb} ${plural(report.rows.removed, "row")}; ${plural(report.rows.missing, "recorded row")} not found`
|
|
1009
|
+
: `${verb}: ${plural(report.links.removed, "link")}, ${plural(report.rows.removed, "row")} (each link is an edge and its inverse); 0 already gone`);
|
|
1010
|
+
const skipped = report.changedBy.skipped_not_model_link ?? 0;
|
|
1011
|
+
const changedSince = Object.fromEntries(Object.entries(report.changedBy).filter(([reason]) => reason !== "skipped_not_model_link"));
|
|
1012
|
+
if (report.rows.changed > skipped)
|
|
1013
|
+
lines.push(`left in the graph: ${plural(report.rows.changed - skipped, "row")}${skipped === 0 ? ` of ${plural(report.links.kept, "link")}` : ""}, changed since the backfill wrote them (${reasons(changedSince)})`);
|
|
1014
|
+
if (skipped > 0)
|
|
1015
|
+
lines.push(`skipped: ${plural(skipped, "row")} the record names that ${skipped === 1 ? "is" : "are"} not a model's lineage link (skipped_not_model_link); left in the graph`);
|
|
1016
|
+
lines.push(report.stateCleared ? `walk state: ${report.dryRun ? "would be cleared" : "cleared"} (a later backfill starts from the first day)` : "walk state: none to clear");
|
|
1017
|
+
lines.push(`graph: ${report.graphRoot}`);
|
|
1018
|
+
for (const note of report.notes)
|
|
1019
|
+
lines.push(`note: ${note}`);
|
|
1020
|
+
return lines.join("\n");
|
|
1021
|
+
}
|
|
1022
|
+
/** `hq ontology lineage undo`. Exit code 1 when the record file does not match this graph (none of its rows is here). */
|
|
1023
|
+
export async function lineageUndoCommand(context, options, deps = {}) {
|
|
1024
|
+
const report = await runLineageUndo(context, options, deps);
|
|
1025
|
+
return { text: formatLineageUndoReport(report), json: report, ...(report.mismatch ? { exitCode: 1 } : {}) };
|
|
1026
|
+
}
|
|
1027
|
+
//# sourceMappingURL=index.js.map
|