@tpsdev-ai/flair 0.63.0 → 0.63.1
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/README.md +8 -7
- package/SECURITY.md +55 -33
- package/dist/bridges/runtime/import-runner.js +4 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +243 -83
- package/dist/commands/agent.js +298 -72
- package/dist/commands/attention.js +2 -0
- package/dist/commands/bootstrap.js +2 -0
- package/dist/commands/bridge.js +10 -0
- package/dist/commands/doctor.js +87 -42
- package/dist/commands/export.js +141 -11
- package/dist/commands/import.js +36 -15
- package/dist/commands/init.js +373 -157
- package/dist/commands/keys.js +12 -8
- package/dist/commands/mcp.js +146 -62
- package/dist/commands/memory.js +5 -2
- package/dist/commands/migrate-harness-memory.js +9 -3
- package/dist/commands/principal.js +19 -14
- package/dist/commands/quality.js +23 -3
- package/dist/commands/reembed.js +468 -111
- package/dist/commands/search.js +2 -0
- package/dist/commands/service.js +25 -0
- package/dist/commands/status.js +130 -107
- package/dist/doctor-client.js +2 -23
- package/dist/federation/scheduler.js +148 -12
- package/dist/keystore.js +77 -10
- package/dist/lib/agent-key-file.js +509 -0
- package/dist/lib/agent-rotation-lock.js +249 -0
- package/dist/lib/atomic-write.js +2 -2
- package/dist/lib/auth-resolve.js +14 -14
- package/dist/lib/key-dir.js +203 -0
- package/dist/lib/launchd-management.js +7 -3
- package/dist/lib/local-instance-pair.js +8 -1
- package/dist/lib/node-alias-path.js +50 -2
- package/dist/lib/remote-admin-pass.js +157 -0
- package/dist/lib/scheduler-platform.js +13 -0
- package/dist/lib/service-repoint.js +13 -4
- package/dist/lib/skill-seed.js +35 -3
- package/dist/lib/terminal-text.js +32 -0
- package/dist/mcp-client-assertion.js +5 -4
- package/dist/resources/Memory.js +47 -3
- package/dist/resources/health.js +39 -22
- package/dist/resources/in-process-api.js +74 -11
- package/dist/resources/mcp-client-metadata-fields.js +4 -0
- package/dist/resources/mcp-handler.js +40 -1
- package/dist/resources/mcp-oauth.js +17 -1
- package/dist/resources/mcp-tool-scopes.js +69 -0
- package/dist/resources/mcp-tools.js +10 -0
- package/dist/resources/skill-version-write.js +16 -0
- package/dist/src/keystore.js +77 -10
- package/dist/src/lib/atomic-write.js +2 -2
- package/dist/src/lib/key-dir.js +203 -0
- package/dist/src/lib/scheduler-platform.js +13 -0
- package/docs/access-control.md +21 -12
- package/docs/api-reference.md +35 -24
- package/docs/auth.md +31 -22
- package/docs/deploying-on-fabric.md +10 -2
- package/docs/embedding-in-a-harper-app.md +7 -7
- package/docs/entity-vocabulary.md +4 -5
- package/docs/hosted-on-fabric.md +1 -1
- package/docs/secrets-and-keys.md +8 -13
- package/docs/upgrade.md +15 -5
- package/package.json +1 -1
package/dist/commands/reembed.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { authFetch, defaultKeysDir, resolveAdminUser } from "../lib/auth-resolve.js";
|
|
2
2
|
import { encodeRecordId } from "../lib/record-id-path.js";
|
|
3
|
+
import { agentHomeEndpoint, decideProbedPairIdentity, readHttpInstanceIdentity, resolveTargetInstanceIdentity, } from "../lib/agent-home.js";
|
|
4
|
+
import { IncompleteInstancePairError, proveLocalInstancePair } from "../lib/local-instance-pair.js";
|
|
3
5
|
import { MEMORY_REEMBED_PATCH_CAPABILITY, healthVersion, parseHealthCapabilities, reembedUnsupportedMessage, reembedUnverifiedMessage, } from "../lib/reembed-server-support.js";
|
|
4
6
|
import { existsSync } from "node:fs";
|
|
7
|
+
import { agentKeyPath } from "../lib/key-dir.js";
|
|
5
8
|
let cli;
|
|
6
9
|
/** Bind the cli-locals this module depends on. */
|
|
7
10
|
export function bindCli(fns) {
|
|
@@ -16,6 +19,12 @@ function resolveHttpPort(...args) {
|
|
|
16
19
|
function resolveOpsPort(...args) {
|
|
17
20
|
return cli.resolveOpsPort(...args);
|
|
18
21
|
}
|
|
22
|
+
function resolveAgentHomeTarget(...args) {
|
|
23
|
+
return cli.resolveAgentHomeTarget(...args);
|
|
24
|
+
}
|
|
25
|
+
function ambiguousInstanceTargetError() {
|
|
26
|
+
return cli.ambiguousInstanceTargetError;
|
|
27
|
+
}
|
|
19
28
|
/**
|
|
20
29
|
* A StoredModelReader over the Harper operations API with the administrator
|
|
21
30
|
* credentials `flair reembed` lists the rows with: `search_by_id` for the row's
|
|
@@ -23,31 +32,142 @@ function resolveOpsPort(...args) {
|
|
|
23
32
|
*/
|
|
24
33
|
export function opsStoredModelReader(opsPort, opsAuth) {
|
|
25
34
|
return async (id) => {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
headers: { "Content-Type": "application/json", Authorization: opsAuth },
|
|
38
|
+
body: JSON.stringify({
|
|
39
|
+
operation: "search_by_id",
|
|
40
|
+
database: "flair",
|
|
41
|
+
table: "Memory",
|
|
42
|
+
ids: [id],
|
|
43
|
+
get_attributes: ["id", "embeddingModel"],
|
|
44
|
+
}),
|
|
45
|
+
signal: AbortSignal.timeout(20_000),
|
|
46
|
+
});
|
|
47
|
+
if (!res.ok)
|
|
48
|
+
throw new Error(`HTTP ${res.status}`);
|
|
49
|
+
const rows = await res.json();
|
|
50
|
+
if (!Array.isArray(rows)) {
|
|
51
|
+
throw new Error(`search_by_id answered ${describeJsonShape(rows)}, not a row array`);
|
|
52
|
+
}
|
|
53
|
+
if (rows.length === 0) {
|
|
54
|
+
throw new Error(`search_by_id answered an empty row array for id ${id}`);
|
|
43
55
|
}
|
|
44
|
-
|
|
45
|
-
|
|
56
|
+
const row = rows.find((r) => r?.id === id);
|
|
57
|
+
if (row === undefined) {
|
|
58
|
+
throw new Error(`search_by_id answered ${rows.length} row(s) without the requested id`);
|
|
46
59
|
}
|
|
47
|
-
|
|
48
|
-
return row?.embeddingModel;
|
|
60
|
+
return row.embeddingModel;
|
|
49
61
|
};
|
|
50
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Rows per `search_by_conditions` page when reading Memory for a re-embed.
|
|
65
|
+
* Passed as `readAllMemoryRows`'s `pageSize` so tests can use a small page.
|
|
66
|
+
*/
|
|
67
|
+
export const REEMBED_READ_PAGE_SIZE = 1000;
|
|
68
|
+
/** Row limit of the single keyless `POST /SemanticSearch` listing. */
|
|
69
|
+
export const KEYLESS_SEARCH_LIMIT = 10_000;
|
|
70
|
+
/** One line naming what the keyless listing read and the remedy. */
|
|
71
|
+
export function keylessTruncationNotice(read) {
|
|
72
|
+
return `⚠️ Read ${read} memories via /SemanticSearch; more rows may exist. Set FLAIR_ADMIN_PASS so reembed reads through the operations API.`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Default and largest page cap for the keyset loop: 10,000 pages. The CLI reads
|
|
76
|
+
* pages of REEMBED_READ_PAGE_SIZE (1,000) rows; a caller may pass a smaller
|
|
77
|
+
* `maxPages` and any positive whole `pageSize`. The read refuses when page
|
|
78
|
+
* `maxPages` holds at least `pageSize` rows, because more rows may follow; a
|
|
79
|
+
* shorter page at that bound is a complete read.
|
|
80
|
+
*/
|
|
81
|
+
const MAX_MEMORY_READ_PAGES = 10_000;
|
|
82
|
+
/**
|
|
83
|
+
* Read the Memory rows matching `conditions`, one page at a time (flair#3086).
|
|
84
|
+
* Keyset paging on the primary key: from the second page on, each page asks for
|
|
85
|
+
* rows whose `id` is greater than the last id seen, sorted by `id`, so a row
|
|
86
|
+
* inserted or deleted between pages does not shift the rows after it or repeat
|
|
87
|
+
* one already read.
|
|
88
|
+
*
|
|
89
|
+
* Harper's operations API forwards `limit`, `offset` and `sort` to Table.search
|
|
90
|
+
* (node_modules/harper/dataLayer/harperBridge/ResourceBridge.ts:109-113); the
|
|
91
|
+
* conditions search accepts `sort: { attribute, descending }`
|
|
92
|
+
* (node_modules/harper/validation/searchValidator.ts:38-48); a primary-key
|
|
93
|
+
* sort scans the primary store in key order
|
|
94
|
+
* (node_modules/harper/resources/Table.ts:5919-5921). A page that is not an
|
|
95
|
+
* array of rows with a non-empty string `id`, a non-empty string `agentId` and
|
|
96
|
+
* a string `content`, or whose ids do not strictly increase, throws, so an
|
|
97
|
+
* error object or a malformed page does not read as an empty result. The whole
|
|
98
|
+
* read finishes before the first re-embed write, and it refuses when page
|
|
99
|
+
* `maxPages` (default MAX_MEMORY_READ_PAGES) holds at least `pageSize` rows.
|
|
100
|
+
*/
|
|
101
|
+
export async function readAllMemoryRows(opts) {
|
|
102
|
+
const pageSize = opts.pageSize ?? REEMBED_READ_PAGE_SIZE;
|
|
103
|
+
const maxPages = opts.maxPages ?? MAX_MEMORY_READ_PAGES;
|
|
104
|
+
if (!Number.isInteger(pageSize) || pageSize < 1) {
|
|
105
|
+
throw new Error(`invalid page size ${pageSize}`);
|
|
106
|
+
}
|
|
107
|
+
if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > MAX_MEMORY_READ_PAGES) {
|
|
108
|
+
throw new Error(`invalid page cap ${maxPages}: must be a whole number from 1 to ${MAX_MEMORY_READ_PAGES}`);
|
|
109
|
+
}
|
|
110
|
+
const rows = [];
|
|
111
|
+
let lastId;
|
|
112
|
+
let pages = 0;
|
|
113
|
+
while (pages < maxPages) {
|
|
114
|
+
pages++;
|
|
115
|
+
const conditions = [...opts.conditions];
|
|
116
|
+
if (lastId !== undefined) {
|
|
117
|
+
conditions.push({ search_attribute: "id", search_type: "greater_than", search_value: lastId });
|
|
118
|
+
}
|
|
119
|
+
const res = await fetch(`http://127.0.0.1:${opts.opsPort}/`, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { "Content-Type": "application/json", Authorization: opts.opsAuth },
|
|
122
|
+
body: JSON.stringify({
|
|
123
|
+
operation: "search_by_conditions",
|
|
124
|
+
database: "flair",
|
|
125
|
+
table: "Memory",
|
|
126
|
+
operator: "and",
|
|
127
|
+
conditions,
|
|
128
|
+
sort: { attribute: "id" },
|
|
129
|
+
// Not "*": every page would carry every row's embedding vector.
|
|
130
|
+
get_attributes: ["id", "agentId", "content", "embeddingModel"],
|
|
131
|
+
limit: pageSize,
|
|
132
|
+
}),
|
|
133
|
+
signal: AbortSignal.timeout(60_000),
|
|
134
|
+
});
|
|
135
|
+
if (!res.ok)
|
|
136
|
+
throw new Error(`HTTP ${res.status}`);
|
|
137
|
+
const raw = await res.json();
|
|
138
|
+
const page = Array.isArray(raw)
|
|
139
|
+
? raw
|
|
140
|
+
: raw !== null && typeof raw === "object" && Array.isArray(raw.results)
|
|
141
|
+
? raw.results
|
|
142
|
+
: null;
|
|
143
|
+
if (page === null) {
|
|
144
|
+
throw new Error(`page ${pages}: response is neither an array nor an object with a results array`);
|
|
145
|
+
}
|
|
146
|
+
const seen = [];
|
|
147
|
+
for (const row of page) {
|
|
148
|
+
const id = row?.id;
|
|
149
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
150
|
+
throw new Error(`page ${pages}: row without a non-empty string id`);
|
|
151
|
+
}
|
|
152
|
+
const rowAgentId = row?.agentId;
|
|
153
|
+
if (typeof rowAgentId !== "string" || rowAgentId.length === 0) {
|
|
154
|
+
throw new Error(`page ${pages}: row without a non-empty string agentId`);
|
|
155
|
+
}
|
|
156
|
+
if (typeof row?.content !== "string") {
|
|
157
|
+
throw new Error(`page ${pages}: row without a string content`);
|
|
158
|
+
}
|
|
159
|
+
if (lastId !== undefined && Buffer.compare(Buffer.from(id), Buffer.from(lastId)) <= 0) {
|
|
160
|
+
throw new Error(`page ${pages}: ids do not strictly increase`);
|
|
161
|
+
}
|
|
162
|
+
lastId = id;
|
|
163
|
+
seen.push(row);
|
|
164
|
+
}
|
|
165
|
+
rows.push(...seen);
|
|
166
|
+
if (page.length < pageSize)
|
|
167
|
+
return { rows, pages };
|
|
168
|
+
}
|
|
169
|
+
throw new Error(`stopped after ${maxPages} pages`);
|
|
170
|
+
}
|
|
51
171
|
/**
|
|
52
172
|
* A StoredModelReader that reads the row with a signed `GET /Memory/<id>` as
|
|
53
173
|
* the agent whose key signs the re-embed PATCH (the single-agent path without
|
|
@@ -55,45 +175,127 @@ export function opsStoredModelReader(opsPort, opsAuth) {
|
|
|
55
175
|
*/
|
|
56
176
|
export function agentStoredModelReader(baseUrl, agentId, keyPath) {
|
|
57
177
|
return async (id) => {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
catch {
|
|
66
|
-
return undefined;
|
|
178
|
+
const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Memory/${encodeRecordId(id)}`);
|
|
179
|
+
if (!res.ok)
|
|
180
|
+
throw new Error(`HTTP ${res.status}`);
|
|
181
|
+
const row = await res.json();
|
|
182
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) {
|
|
183
|
+
throw new Error(`GET /Memory/${encodeRecordId(id)} answered ${describeJsonShape(row)}, not a record`);
|
|
67
184
|
}
|
|
68
185
|
const record = row;
|
|
69
|
-
|
|
186
|
+
if (record.id !== id) {
|
|
187
|
+
throw new Error(`GET /Memory/${encodeRecordId(id)} answered a record that does not name the requested id`);
|
|
188
|
+
}
|
|
189
|
+
return record.embeddingModel;
|
|
70
190
|
};
|
|
71
191
|
}
|
|
192
|
+
export async function reembedRowOutcome(baseUrl, agentId, keyPath, id, intendedModel, readStoredModel) {
|
|
193
|
+
let res;
|
|
194
|
+
try {
|
|
195
|
+
res = await authFetch(baseUrl, agentId, keyPath, "PATCH", `/Memory/${encodeRecordId(id)}`, {
|
|
196
|
+
embedding: null, embeddingModel: null,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
return { ok: false, reason: `PATCH failed: ${oneLine(errorText(err))}` };
|
|
201
|
+
}
|
|
202
|
+
return reembedOutcomeFromResponse(res, id, intendedModel, readStoredModel);
|
|
203
|
+
}
|
|
72
204
|
/**
|
|
73
|
-
* flair#
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* re-embedded when that response names this row and the stored row then
|
|
79
|
-
* carries `intendedModel`, read with `readStoredModel`.
|
|
205
|
+
* flair#3128: the same re-embed PATCH and readback with the administrator
|
|
206
|
+
* credential the all-agent run lists rows with. Its two-field body is
|
|
207
|
+
* identical to `reembedRowOutcome`'s, so it changes only the embedding, the
|
|
208
|
+
* model stamp, `updatedAt`, the embedded-text hash and a missing legacy
|
|
209
|
+
* `instanceToken`; it never needs, or looks for, the owner's key.
|
|
80
210
|
*/
|
|
81
|
-
export async function
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
211
|
+
export async function adminReembedRowOutcome(baseUrl, opsAuth, id, intendedModel, readStoredModel) {
|
|
212
|
+
let res;
|
|
213
|
+
try {
|
|
214
|
+
res = await fetch(`${baseUrl}/Memory/${encodeRecordId(id)}`, {
|
|
215
|
+
method: "PATCH",
|
|
216
|
+
headers: { "Content-Type": "application/json", Authorization: opsAuth },
|
|
217
|
+
body: JSON.stringify({ embedding: null, embeddingModel: null }),
|
|
218
|
+
signal: AbortSignal.timeout(20_000),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
return { ok: false, reason: `PATCH failed: ${oneLine(errorText(err))}` };
|
|
223
|
+
}
|
|
224
|
+
return reembedOutcomeFromResponse(res, id, intendedModel, readStoredModel);
|
|
225
|
+
}
|
|
226
|
+
/** The readback and reason classification both re-embed paths share. */
|
|
227
|
+
async function reembedOutcomeFromResponse(res, id, intendedModel, readStoredModel) {
|
|
85
228
|
if (!res.ok)
|
|
86
|
-
return false;
|
|
229
|
+
return { ok: false, reason: `HTTP ${res.status}` };
|
|
87
230
|
let body;
|
|
88
231
|
try {
|
|
89
232
|
body = await res.json();
|
|
90
233
|
}
|
|
91
234
|
catch {
|
|
92
|
-
return false;
|
|
235
|
+
return { ok: false, reason: "PATCH response was not JSON" };
|
|
236
|
+
}
|
|
237
|
+
if (body?.id !== id) {
|
|
238
|
+
return { ok: false, reason: "PATCH response did not name the row" };
|
|
93
239
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
240
|
+
let stored;
|
|
241
|
+
try {
|
|
242
|
+
stored = await readStoredModel(id);
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
return { ok: false, reason: `stored model read failed: ${oneLine(errorText(err))}` };
|
|
246
|
+
}
|
|
247
|
+
if (stored === intendedModel)
|
|
248
|
+
return { ok: true };
|
|
249
|
+
const shown = typeof stored === "string" && stored.length > 0 ? stored : "missing";
|
|
250
|
+
return { ok: false, reason: `stored embeddingModel is ${oneLine(shown)}` };
|
|
251
|
+
}
|
|
252
|
+
/** `reembedRow` as a boolean: true when the PATCH succeeded, the response names the row, and the stored stamp matches. */
|
|
253
|
+
export async function reembedRow(baseUrl, agentId, keyPath, id, intendedModel, readStoredModel) {
|
|
254
|
+
return (await reembedRowOutcome(baseUrl, agentId, keyPath, id, intendedModel, readStoredModel)).ok;
|
|
255
|
+
}
|
|
256
|
+
function errorText(err) {
|
|
257
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
258
|
+
return message.length > 0 ? message : "unknown error";
|
|
259
|
+
}
|
|
260
|
+
/** A short name for a JSON value's shape, for a read that answered something else. */
|
|
261
|
+
function describeJsonShape(value) {
|
|
262
|
+
if (value === null)
|
|
263
|
+
return "null";
|
|
264
|
+
if (Array.isArray(value))
|
|
265
|
+
return "an array";
|
|
266
|
+
if (typeof value === "object")
|
|
267
|
+
return "an object";
|
|
268
|
+
if (typeof value === "undefined")
|
|
269
|
+
return "undefined";
|
|
270
|
+
return `a ${typeof value}`;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* A failure reason on ONE line (flair#3128): a stored model string or an error
|
|
274
|
+
* message can carry CR, LF or another control character, which would split the
|
|
275
|
+
* reason across output lines and break the per-reason summary.
|
|
276
|
+
*/
|
|
277
|
+
function oneLine(text) {
|
|
278
|
+
return text.replace(/\\/g, "\\\\").replace(/[\u0000-\u001f\u007f-\u009f]/g, (ch) => {
|
|
279
|
+
if (ch === "\n")
|
|
280
|
+
return "\\n";
|
|
281
|
+
if (ch === "\r")
|
|
282
|
+
return "\\r";
|
|
283
|
+
if (ch === "\t")
|
|
284
|
+
return "\\t";
|
|
285
|
+
return `\\x${ch.charCodeAt(0).toString(16).padStart(2, "0")}`;
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/** One line per distinct failure reason, with the rows that share it (flair#3128). */
|
|
289
|
+
function failureReasonLines(reasons, remedy) {
|
|
290
|
+
return [...reasons].map(([reason, count]) => ` ❌ ${count} row(s) update unconfirmed: ${reason} — ${remedy}`);
|
|
291
|
+
}
|
|
292
|
+
function retryRemedy(agentId, httpPort, opsPort) {
|
|
293
|
+
const ports = `--port ${httpPort} --ops-port ${opsPort}`;
|
|
294
|
+
if (agentId && /[\u0000-\u001f\u007f-\u009f]/.test(agentId)) {
|
|
295
|
+
return `fix the cause, then re-run with the same agent ID and ${ports}`;
|
|
296
|
+
}
|
|
297
|
+
const agent = agentId ? ` --agent '${agentId.replace(/'/g, "'\\''")}'` : "";
|
|
298
|
+
return `re-run \`flair reembed${agent} ${ports}\` after fixing the cause`;
|
|
97
299
|
}
|
|
98
300
|
/**
|
|
99
301
|
* flair#2337: refuse before the first write when the running server does not
|
|
@@ -129,6 +331,81 @@ export async function reembedServerSupportError(baseUrl) {
|
|
|
129
331
|
return null;
|
|
130
332
|
return reembedUnsupportedMessage(healthVersion(body));
|
|
131
333
|
}
|
|
334
|
+
/** The remedy for a one-sided target: which side was supplied, which is missing (flair#3128). */
|
|
335
|
+
function oneSidedTargetRemedy(supplied, missing) {
|
|
336
|
+
return `Only the ${supplied} port was supplied; the ${missing} port is missing. `
|
|
337
|
+
+ "Pass the other port too (--port or FLAIR_URL with FLAIR_OPS_PORT), or complete ~/.flair/config.yaml.";
|
|
338
|
+
}
|
|
339
|
+
const REEMBED_LISTENER_UNAVAILABLE_REMEDY = "This CLI could not read the OS listener table; run flair reembed where it can read Harper's listeners.";
|
|
340
|
+
/** The remedy for a proven pair that differs from a target configuration bound (flair#3135). */
|
|
341
|
+
const REEMBED_PAIR_MISMATCH_REMEDY = "The configured pair does not match the running instance; check ~/.flair/config.yaml (or the data directory's harper-config.yaml).";
|
|
342
|
+
/** The remedy for a proven pair that differs from two named ports (flair#3135). */
|
|
343
|
+
const REEMBED_NAMED_PAIR_REMEDY = "The named ports do not match the running instance; correct the --port or FLAIR_URL and FLAIR_OPS_PORT overrides.";
|
|
344
|
+
/** The remedy for a proven pair that differs from a derived target (flair#3128). */
|
|
345
|
+
const REEMBED_DERIVED_TARGET_REMEDY = "No port was named and the configuration names no complete pair; name the instance (--port or FLAIR_URL with FLAIR_OPS_PORT) or complete ~/.flair/config.yaml.";
|
|
346
|
+
/** The remedy for two ports that report different instance ids (flair#3128). */
|
|
347
|
+
const REEMBED_IDENTITY_MISMATCH_REMEDY = "The two ports report different instance ids; point both at one instance.";
|
|
348
|
+
/** The remedy for a target whose HTTP and ops ports are the same port. */
|
|
349
|
+
const REEMBED_EQUAL_PORTS_REMEDY = "The HTTP and ops ports must differ; pass --port and FLAIR_OPS_PORT with two different ports.";
|
|
350
|
+
/** Picks the remedy for each ReembedTargetRefusalReason; one remedy per condition. (A conflict raised while resolving the target exits through the resolver's own error.) */
|
|
351
|
+
export function reembedTargetRefusalRemedy(reason) {
|
|
352
|
+
switch (reason.kind) {
|
|
353
|
+
case "one-sided":
|
|
354
|
+
return oneSidedTargetRemedy(reason.supplied, reason.missing);
|
|
355
|
+
case "listener-table-unavailable":
|
|
356
|
+
return REEMBED_LISTENER_UNAVAILABLE_REMEDY;
|
|
357
|
+
case "pair-mismatch":
|
|
358
|
+
return reason.source === "configured" ? REEMBED_PAIR_MISMATCH_REMEDY
|
|
359
|
+
: reason.source === "named" ? REEMBED_NAMED_PAIR_REMEDY
|
|
360
|
+
: REEMBED_DERIVED_TARGET_REMEDY;
|
|
361
|
+
case "identity-mismatch":
|
|
362
|
+
return REEMBED_IDENTITY_MISMATCH_REMEDY;
|
|
363
|
+
case "equal-ports":
|
|
364
|
+
return REEMBED_EQUAL_PORTS_REMEDY;
|
|
365
|
+
case "unproven":
|
|
366
|
+
return reason.remedy ?? "This CLI could not prove the local port pair; check the ops endpoint's configuration and listener visibility.";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* flair#3135: the administrator's Basic credential goes to the HTTP port only
|
|
371
|
+
* after `proveLocalInstancePair` has proven, from the ops port and the OS
|
|
372
|
+
* listener table, that one Harper process listens on that ops port and on the
|
|
373
|
+
* HTTP port this run targets. This runs before any request to the HTTP port, so
|
|
374
|
+
* every refusal precedes any PATCH. After the proof, the two endpoints'
|
|
375
|
+
* reported instance identities are a second check: two different ids refuse.
|
|
376
|
+
* `source` is the remedy classification (configuration-bound, named and
|
|
377
|
+
* unbound, or derived), so a proven-pair mismatch gets the remedy for that
|
|
378
|
+
* classification (flair#3128).
|
|
379
|
+
*/
|
|
380
|
+
async function reembedTargetPairRefusal(target, adminUser, adminPass, source) {
|
|
381
|
+
const refusal = (detail, reason) => `❌ flair reembed stopped before its first write: ${ambiguousInstanceTargetError()} — ${detail}\n ${reembedTargetRefusalRemedy(reason)}`;
|
|
382
|
+
if (target.httpPort === target.opsPort) {
|
|
383
|
+
return refusal(`the target names HTTP port ${target.httpPort} and ops port ${target.opsPort}, which are the same port`, { kind: "equal-ports" });
|
|
384
|
+
}
|
|
385
|
+
const authorization = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
|
|
386
|
+
const proof = await proveLocalInstancePair(target.opsPort, authorization);
|
|
387
|
+
if (proof.kind !== "proven") {
|
|
388
|
+
return refusal(`the ops port ${target.opsPort} is not proven to pair with an HTTP port on this host: ${proof.detail}`, proof.reason === "listener-table-unavailable" ? { kind: "listener-table-unavailable" } : { kind: "unproven", remedy: proof.remedy });
|
|
389
|
+
}
|
|
390
|
+
if (proof.httpPort !== target.httpPort) {
|
|
391
|
+
return refusal(`the ops port ${target.opsPort} is proven to pair with HTTP port ${proof.httpPort}, not ${target.httpPort}`, { kind: "pair-mismatch", source });
|
|
392
|
+
}
|
|
393
|
+
const [httpIdentity, opsIdentity] = await Promise.all([
|
|
394
|
+
readHttpInstanceIdentity(`http://127.0.0.1:${target.httpPort}`, adminUser, adminPass),
|
|
395
|
+
resolveTargetInstanceIdentity(agentHomeEndpoint(target.opsPort, adminUser, adminPass)),
|
|
396
|
+
]);
|
|
397
|
+
const decision = decideProbedPairIdentity(httpIdentity, opsIdentity);
|
|
398
|
+
if (decision.kind === "different") {
|
|
399
|
+
return refusal(`the HTTP port reports instance ${decision.httpId}, the ops API reports instance ${decision.opsId}`, { kind: "identity-mismatch" });
|
|
400
|
+
}
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
/** Whether the caller named both ports of the all-agent target (flair#3128). */
|
|
404
|
+
function bothTargetPortsNamed(opts) {
|
|
405
|
+
const httpNamed = (opts.port !== undefined && opts.port !== null) || /:\d+/.test(process.env.FLAIR_URL ?? "");
|
|
406
|
+
const opsNamed = (opts.opsPort !== undefined && opts.opsPort !== null) || Boolean(process.env.FLAIR_OPS_PORT);
|
|
407
|
+
return httpNamed && opsNamed;
|
|
408
|
+
}
|
|
132
409
|
export function register(program) {
|
|
133
410
|
// ─── flair reembed ────────────────────────────────────────────────────────────
|
|
134
411
|
//
|
|
@@ -156,20 +433,28 @@ export function register(program) {
|
|
|
156
433
|
program
|
|
157
434
|
.command("reembed")
|
|
158
435
|
.description("Re-generate embeddings for memories with stale or missing model tags")
|
|
159
|
-
.option("--agent <id>", "Agent ID to re-embed memories for (defaults to all agents
|
|
436
|
+
.option("--agent <id>", "Agent ID to re-embed memories for (defaults to all agents; add --stale-only to skip up-to-date rows)")
|
|
160
437
|
.option("--stale-only", "Only re-embed memories with mismatched model tag")
|
|
161
438
|
.option("--dry-run", "Show count without modifying")
|
|
162
439
|
.option("--port <port>", "Harper HTTP port")
|
|
440
|
+
.option("--ops-port <port>", "Harper operations API port")
|
|
163
441
|
.option("--batch-size <n>", "Records per batch", "50")
|
|
164
442
|
.option("--delay-ms <ms>", "Delay between batches (ms)", "100")
|
|
165
443
|
.action(async (opts) => {
|
|
166
|
-
const port = resolveHttpPort(opts);
|
|
167
|
-
const baseUrl = `http://127.0.0.1:${port}`;
|
|
168
444
|
const agentId = opts.agent;
|
|
169
445
|
const staleOnly = opts.staleOnly ?? false;
|
|
170
446
|
const dryRun = opts.dryRun ?? false;
|
|
171
447
|
const batchSize = Number(opts.batchSize);
|
|
172
448
|
const delayMs = Number(opts.delayMs);
|
|
449
|
+
if (agentId !== undefined) {
|
|
450
|
+
try {
|
|
451
|
+
agentKeyPath(defaultKeysDir(), agentId);
|
|
452
|
+
}
|
|
453
|
+
catch (err) {
|
|
454
|
+
console.error(`❌ ${err instanceof Error ? err.message : String(err)}`);
|
|
455
|
+
process.exit(1);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
173
458
|
// A call with neither --agent nor an admin password is a usage error; report
|
|
174
459
|
// it before the server check below so the existing message is not masked.
|
|
175
460
|
const adminPassEnv = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
|
|
@@ -177,6 +462,38 @@ export function register(program) {
|
|
|
177
462
|
console.error("❌ Admin password required when --agent is not specified (set FLAIR_ADMIN_PASS or HDB_ADMIN_PASSWORD)");
|
|
178
463
|
process.exit(1);
|
|
179
464
|
}
|
|
465
|
+
// flair#3135: the all-agent run sends the administrator's Basic credential to
|
|
466
|
+
// the HTTP port, so it resolves that port and the ops port as ONE target
|
|
467
|
+
// (`resolveAgentHomeTarget`'s pairing rule) — never independently. The
|
|
468
|
+
// single-agent PATCH is signed, so its HTTP port stays `resolveHttpPort`.
|
|
469
|
+
let target = null;
|
|
470
|
+
let baseUrl;
|
|
471
|
+
let agentPorts = null;
|
|
472
|
+
if (agentId) {
|
|
473
|
+
agentPorts = { http: resolveHttpPort(opts), ops: resolveOpsPort(opts) };
|
|
474
|
+
baseUrl = `http://127.0.0.1:${agentPorts.http}`;
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
try {
|
|
478
|
+
target = resolveAgentHomeTarget(opts);
|
|
479
|
+
}
|
|
480
|
+
catch (err) {
|
|
481
|
+
console.error(err instanceof IncompleteInstancePairError
|
|
482
|
+
? `❌ ${ambiguousInstanceTargetError()} — ${reembedTargetRefusalRemedy({ kind: "one-sided", supplied: err.reason.supplied, missing: err.reason.missing })}`
|
|
483
|
+
: `❌ ${errorText(err)}`);
|
|
484
|
+
process.exit(1);
|
|
485
|
+
}
|
|
486
|
+
baseUrl = `http://127.0.0.1:${target.httpPort}`;
|
|
487
|
+
// Prove the pair before a write run contacts HTTP with the administrator credential.
|
|
488
|
+
if (!dryRun) {
|
|
489
|
+
const source = target.pairBound ? "configured" : bothTargetPortsNamed(opts) ? "named" : "derived";
|
|
490
|
+
const pairRefusal = await reembedTargetPairRefusal(target, resolveAdminUser(undefined), adminPassEnv, source);
|
|
491
|
+
if (pairRefusal) {
|
|
492
|
+
console.error(pairRefusal);
|
|
493
|
+
process.exit(1);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
180
497
|
// flair#2337: require the advertised token before either PATCH loop.
|
|
181
498
|
const supportError = await reembedServerSupportError(baseUrl);
|
|
182
499
|
if (supportError) {
|
|
@@ -222,7 +539,7 @@ export function register(program) {
|
|
|
222
539
|
console.log(`Re-embedding memories for agent: ${agentId}`);
|
|
223
540
|
}
|
|
224
541
|
else {
|
|
225
|
-
console.log("Re-embedding memories for all agents
|
|
542
|
+
console.log("Re-embedding memories for all agents");
|
|
226
543
|
}
|
|
227
544
|
console.log(`Current model: ${currentModel}`);
|
|
228
545
|
if (staleOnly)
|
|
@@ -242,32 +559,34 @@ export function register(program) {
|
|
|
242
559
|
// vector index — exactly what we need when the goal is to replace every
|
|
243
560
|
// embedding with a freshly-computed one. Without this path, `flair
|
|
244
561
|
// reembed` could not recover from the very condition it exists to fix.
|
|
245
|
-
|
|
246
|
-
|
|
562
|
+
// Reads the pages before the first write (flair#3086). The read refuses
|
|
563
|
+
// when its last page (MAX_MEMORY_READ_PAGES) comes back full, and the
|
|
564
|
+
// command exits non-zero without writing.
|
|
565
|
+
const opsPort = target.opsPort;
|
|
566
|
+
const adminUser = resolveAdminUser(undefined);
|
|
567
|
+
const opsAuth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
|
|
247
568
|
const readStoredModel = opsStoredModelReader(opsPort, opsAuth);
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
//
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
})
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
console.error(`❌ Failed to fetch memories via ops API: ${searchRes.status}`);
|
|
569
|
+
// The first page selects every row by id alone. An empty condition list
|
|
570
|
+
// is refused (node_modules/harper/validation/searchValidator.ts:50-51), and
|
|
571
|
+
// Harper's own select-all is the primary key above the bottom of its key
|
|
572
|
+
// order (node_modules/harper/resources/Table.ts:5975-5976). `id > 0` is
|
|
573
|
+
// that bound: the key encoding ranks strings above positive numbers (the
|
|
574
|
+
// ordered-binary bundled with Harper, index.js:2-11), so every string id
|
|
575
|
+
// is admitted, whatever its createdAt.
|
|
576
|
+
let allMemories;
|
|
577
|
+
let readPages;
|
|
578
|
+
try {
|
|
579
|
+
({ rows: allMemories, pages: readPages } = await readAllMemoryRows({
|
|
580
|
+
opsPort,
|
|
581
|
+
opsAuth,
|
|
582
|
+
conditions: [{ search_attribute: "id", search_type: "greater_than", search_value: 0 }],
|
|
583
|
+
}));
|
|
584
|
+
}
|
|
585
|
+
catch (err) {
|
|
586
|
+
console.error(`❌ Failed to fetch memories via ops API: ${err.message}`);
|
|
267
587
|
process.exit(1);
|
|
268
588
|
}
|
|
269
|
-
|
|
270
|
-
const allMemories = Array.isArray(raw) ? raw : (raw?.results ?? []);
|
|
589
|
+
console.log(`Read ${allMemories.length} memories in ${readPages} page(s)`);
|
|
271
590
|
// Group by agentId
|
|
272
591
|
const byAgent = new Map();
|
|
273
592
|
for (const m of allMemories) {
|
|
@@ -280,21 +599,19 @@ export function register(program) {
|
|
|
280
599
|
byAgent.set(agent, []);
|
|
281
600
|
byAgent.get(agent).push(m);
|
|
282
601
|
}
|
|
283
|
-
// Process each agent
|
|
602
|
+
// Process each agent. The run already holds the administrator credential
|
|
603
|
+
// that listed these rows, and the re-embed PATCH changes no owner,
|
|
604
|
+
// provenance or authority field, so the same credential authorizes every
|
|
605
|
+
// row's write; no agent key is needed.
|
|
284
606
|
let totalProcessed = 0;
|
|
285
607
|
let totalErrors = 0;
|
|
608
|
+
const errorsByReason = new Map();
|
|
286
609
|
const agentCount = byAgent.size;
|
|
287
610
|
let agentIndex = 0;
|
|
288
611
|
for (const [agent, memories] of byAgent) {
|
|
289
612
|
agentIndex++;
|
|
290
613
|
console.log(`\nAgent ${agentIndex}/${agentCount}: ${agent}`);
|
|
291
614
|
console.log(` Memories to re-embed: ${memories.length}`);
|
|
292
|
-
const keysDir = defaultKeysDir();
|
|
293
|
-
const privPath = privKeyPath(agent, keysDir);
|
|
294
|
-
if (!existsSync(privPath)) {
|
|
295
|
-
console.error(` ❌ Key not found: ${privPath} — skipping`);
|
|
296
|
-
continue;
|
|
297
|
-
}
|
|
298
615
|
if (dryRun)
|
|
299
616
|
continue;
|
|
300
617
|
let processed = 0;
|
|
@@ -303,13 +620,19 @@ export function register(program) {
|
|
|
303
620
|
const batch = memories.slice(i, i + batchSize);
|
|
304
621
|
for (const memory of batch) {
|
|
305
622
|
try {
|
|
306
|
-
|
|
623
|
+
const outcome = await adminReembedRowOutcome(baseUrl, opsAuth, memory.id, currentModel, readStoredModel);
|
|
624
|
+
if (outcome.ok)
|
|
307
625
|
processed++;
|
|
308
|
-
else
|
|
626
|
+
else {
|
|
627
|
+
const reason = outcome.reason ?? "unknown failure";
|
|
309
628
|
errors++;
|
|
629
|
+
errorsByReason.set(reason, (errorsByReason.get(reason) ?? 0) + 1);
|
|
630
|
+
}
|
|
310
631
|
}
|
|
311
|
-
catch {
|
|
632
|
+
catch (err) {
|
|
312
633
|
errors++;
|
|
634
|
+
const reason = `unexpected error: ${oneLine(errorText(err))}`;
|
|
635
|
+
errorsByReason.set(reason, (errorsByReason.get(reason) ?? 0) + 1);
|
|
313
636
|
}
|
|
314
637
|
}
|
|
315
638
|
const pct = Math.round(((i + batch.length) / memories.length) * 100);
|
|
@@ -317,11 +640,16 @@ export function register(program) {
|
|
|
317
640
|
if (i + batchSize < memories.length)
|
|
318
641
|
await new Promise(r => setTimeout(r, delayMs));
|
|
319
642
|
}
|
|
320
|
-
console.log(`\n ✅ Agent ${agent}: ${processed} updated, ${errors} errors`);
|
|
643
|
+
console.log(`\n ${errors > 0 ? "❌" : "✅"} Agent ${agent}: ${processed} updated, ${errors} errors`);
|
|
321
644
|
totalProcessed += processed;
|
|
322
645
|
totalErrors += errors;
|
|
323
646
|
}
|
|
324
|
-
|
|
647
|
+
const failed = totalErrors > 0;
|
|
648
|
+
console.log(`\n\n${failed ? "❌" : "✅"} Re-embedding complete: ${totalProcessed} updated, ${totalErrors} errors`);
|
|
649
|
+
for (const line of failureReasonLines(errorsByReason, retryRemedy(undefined, target.httpPort, opsPort)))
|
|
650
|
+
console.log(line);
|
|
651
|
+
if (failed)
|
|
652
|
+
process.exitCode = 1;
|
|
325
653
|
return;
|
|
326
654
|
}
|
|
327
655
|
// Single-agent path. Same rationale as above: fetch via the ops API
|
|
@@ -337,37 +665,31 @@ export function register(program) {
|
|
|
337
665
|
}
|
|
338
666
|
const adminPassSingle = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
|
|
339
667
|
let allMemories = [];
|
|
668
|
+
let readPages = 0;
|
|
340
669
|
// flair#2561: the stamp of each re-embedded row is read back the way the
|
|
341
670
|
// rows were listed: the operations API with administrator credentials,
|
|
342
671
|
// else a signed GET as this agent.
|
|
343
672
|
let readStoredModel = agentStoredModelReader(baseUrl, agentId, privPath);
|
|
344
673
|
if (adminPassSingle) {
|
|
345
|
-
const opsPort =
|
|
674
|
+
const opsPort = agentPorts.ops;
|
|
346
675
|
const opsAuth = `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPassSingle}`).toString("base64")}`;
|
|
347
676
|
readStoredModel = opsStoredModelReader(opsPort, opsAuth);
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
get_attributes: ["*"],
|
|
358
|
-
}),
|
|
359
|
-
signal: AbortSignal.timeout(60_000),
|
|
360
|
-
});
|
|
361
|
-
if (!searchRes.ok) {
|
|
362
|
-
console.error(`❌ Failed to fetch memories via ops API: ${searchRes.status}`);
|
|
677
|
+
try {
|
|
678
|
+
({ rows: allMemories, pages: readPages } = await readAllMemoryRows({
|
|
679
|
+
opsPort,
|
|
680
|
+
opsAuth,
|
|
681
|
+
conditions: [{ search_attribute: "agentId", search_type: "equals", search_value: agentId }],
|
|
682
|
+
}));
|
|
683
|
+
}
|
|
684
|
+
catch (err) {
|
|
685
|
+
console.error(`❌ Failed to fetch memories via ops API: ${err.message}`);
|
|
363
686
|
process.exit(1);
|
|
364
687
|
}
|
|
365
|
-
|
|
366
|
-
allMemories = Array.isArray(raw) ? raw : (raw?.results ?? []);
|
|
688
|
+
console.log(`Read ${allMemories.length} memories in ${readPages} page(s)`);
|
|
367
689
|
}
|
|
368
690
|
else {
|
|
369
691
|
const searchRes = await authFetch(baseUrl, agentId, privPath, "POST", "/SemanticSearch", {
|
|
370
|
-
agentId, limit:
|
|
692
|
+
agentId, limit: KEYLESS_SEARCH_LIMIT,
|
|
371
693
|
});
|
|
372
694
|
if (!searchRes.ok) {
|
|
373
695
|
console.error(`❌ Failed to fetch memories: ${searchRes.status}`);
|
|
@@ -376,6 +698,22 @@ export function register(program) {
|
|
|
376
698
|
const data = await searchRes.json();
|
|
377
699
|
allMemories = data.results ?? [];
|
|
378
700
|
}
|
|
701
|
+
// The keyless /SemanticSearch call has no paging parameter (see
|
|
702
|
+
// resources/SemanticSearch.ts): exactly `KEYLESS_SEARCH_LIMIT` rows means
|
|
703
|
+
// the listing may have been cut off, so the run must say so and fail.
|
|
704
|
+
const keylessTruncated = !adminPassSingle && allMemories.length === KEYLESS_SEARCH_LIMIT;
|
|
705
|
+
// flair#3129: the keyless listing's read scope includes every other agent's
|
|
706
|
+
// non-private rows (resources/memory-read-scope.ts). Only this agent's rows
|
|
707
|
+
// are candidates — a PATCH as a non-admin agent to another agent's row is
|
|
708
|
+
// refused (an admin agent's signed PATCH passes the owner guard; the CLI
|
|
709
|
+
// filter still applies) — so drop the others before the candidate and
|
|
710
|
+
// up-to-date counts.
|
|
711
|
+
const keylessListed = allMemories.length;
|
|
712
|
+
let otherAgentRows = 0;
|
|
713
|
+
if (!adminPassSingle) {
|
|
714
|
+
allMemories = allMemories.filter((m) => m.agentId === agentId);
|
|
715
|
+
otherAgentRows = keylessListed - allMemories.length;
|
|
716
|
+
}
|
|
379
717
|
const candidates = allMemories.filter((m) => {
|
|
380
718
|
if (!m.content)
|
|
381
719
|
return false;
|
|
@@ -385,29 +723,41 @@ export function register(program) {
|
|
|
385
723
|
});
|
|
386
724
|
const total = candidates.length;
|
|
387
725
|
const skipped = allMemories.length - total;
|
|
388
|
-
console.log(`Total memories: ${allMemories.length}`);
|
|
389
726
|
console.log(`Candidates for re-embedding: ${total}`);
|
|
727
|
+
if (otherAgentRows > 0)
|
|
728
|
+
console.log(`Skipped (other agents): ${otherAgentRows}`);
|
|
390
729
|
if (skipped > 0)
|
|
391
730
|
console.log(`Skipped (up-to-date): ${skipped}`);
|
|
392
731
|
if (dryRun || total === 0) {
|
|
393
|
-
if (total === 0)
|
|
732
|
+
if (total === 0 && !keylessTruncated)
|
|
394
733
|
console.log("\n✅ All memories are up-to-date!");
|
|
734
|
+
if (keylessTruncated) {
|
|
735
|
+
console.log(keylessTruncationNotice(keylessListed));
|
|
736
|
+
process.exitCode = 1;
|
|
737
|
+
}
|
|
395
738
|
return;
|
|
396
739
|
}
|
|
397
740
|
console.log("");
|
|
398
741
|
let processed = 0;
|
|
399
742
|
let errors = 0;
|
|
743
|
+
const errorsByReason = new Map();
|
|
400
744
|
for (let i = 0; i < candidates.length; i += batchSize) {
|
|
401
745
|
const batch = candidates.slice(i, i + batchSize);
|
|
402
746
|
for (const memory of batch) {
|
|
403
747
|
try {
|
|
404
|
-
|
|
748
|
+
const outcome = await reembedRowOutcome(baseUrl, agentId, privPath, memory.id, currentModel, readStoredModel);
|
|
749
|
+
if (outcome.ok)
|
|
405
750
|
processed++;
|
|
406
|
-
else
|
|
751
|
+
else {
|
|
752
|
+
const reason = outcome.reason ?? "unknown failure";
|
|
407
753
|
errors++;
|
|
754
|
+
errorsByReason.set(reason, (errorsByReason.get(reason) ?? 0) + 1);
|
|
755
|
+
}
|
|
408
756
|
}
|
|
409
|
-
catch {
|
|
757
|
+
catch (err) {
|
|
410
758
|
errors++;
|
|
759
|
+
const reason = `unexpected error: ${oneLine(errorText(err))}`;
|
|
760
|
+
errorsByReason.set(reason, (errorsByReason.get(reason) ?? 0) + 1);
|
|
411
761
|
}
|
|
412
762
|
}
|
|
413
763
|
const pct = Math.round(((i + batch.length) / total) * 100);
|
|
@@ -415,6 +765,13 @@ export function register(program) {
|
|
|
415
765
|
if (i + batchSize < candidates.length)
|
|
416
766
|
await new Promise(r => setTimeout(r, delayMs));
|
|
417
767
|
}
|
|
418
|
-
|
|
768
|
+
const failed = errors > 0 || keylessTruncated;
|
|
769
|
+
console.log(`\n\n${failed ? "❌" : "✅"} Re-embedding complete: ${processed} updated, ${errors} errors`);
|
|
770
|
+
for (const line of failureReasonLines(errorsByReason, retryRemedy(agentId, agentPorts.http, agentPorts.ops)))
|
|
771
|
+
console.log(line);
|
|
772
|
+
if (keylessTruncated)
|
|
773
|
+
console.log(keylessTruncationNotice(keylessListed));
|
|
774
|
+
if (failed)
|
|
775
|
+
process.exitCode = 1;
|
|
419
776
|
});
|
|
420
777
|
}
|