@tpsdev-ai/flair 0.62.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.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -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
- let rows;
27
- try {
28
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
29
- method: "POST",
30
- headers: { "Content-Type": "application/json", Authorization: opsAuth },
31
- body: JSON.stringify({
32
- operation: "search_by_id",
33
- database: "flair",
34
- table: "Memory",
35
- ids: [id],
36
- get_attributes: ["id", "embeddingModel"],
37
- }),
38
- signal: AbortSignal.timeout(20_000),
39
- });
40
- if (!res.ok)
41
- return undefined;
42
- rows = await res.json();
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
- catch {
45
- return undefined;
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
- const row = Array.isArray(rows) ? rows.find((r) => r?.id === id) : undefined;
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
- let row;
59
- try {
60
- const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Memory/${encodeRecordId(id)}`);
61
- if (!res.ok)
62
- return undefined;
63
- row = await res.json();
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
- return record?.id === id ? record.embeddingModel : undefined;
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#2296: re-embed one stored row. The PATCH body names only the two
74
- * embedding fields; the server embeds the stored row and writes embedding,
75
- * embeddingModel and updatedAt.
76
- *
77
- * flair#2561: the server answers `{ id, updatedAt }`. The row counts as
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 reembedRow(baseUrl, agentId, keyPath, id, intendedModel, readStoredModel) {
82
- const res = await authFetch(baseUrl, agentId, keyPath, "PATCH", `/Memory/${encodeRecordId(id)}`, {
83
- embedding: null, embeddingModel: null,
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
- if (body?.id !== id)
95
- return false;
96
- return (await readStoredModel(id)) === intendedModel;
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 with stale rows)")
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 with stale rows");
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
- const opsPort = resolveOpsPort(opts);
246
- const opsAuth = `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPass}`).toString("base64")}`;
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
- // Harper rejects empty-value conditions ("not indexed for nulls"). Use
249
- // `createdAt > 1970-01-01` as the "select all" pattern: every Memory row
250
- // has a createdAt, the index is built, and the comparison is total.
251
- const searchRes = await fetch(`http://127.0.0.1:${opsPort}/`, {
252
- method: "POST",
253
- headers: { "Content-Type": "application/json", Authorization: opsAuth },
254
- body: JSON.stringify({
255
- operation: "search_by_conditions",
256
- database: "flair",
257
- table: "Memory",
258
- operator: "and",
259
- conditions: [{ search_attribute: "createdAt", search_type: "greater_than", search_value: "1970-01-01" }],
260
- get_attributes: ["*"],
261
- limit: 100000,
262
- }),
263
- signal: AbortSignal.timeout(60_000),
264
- });
265
- if (!searchRes.ok) {
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
- const raw = await searchRes.json();
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
- if (await reembedRow(baseUrl, agent, privPath, memory.id, currentModel, readStoredModel))
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
- console.log(`\n\n✅ Re-embedding complete: ${totalProcessed} updated, ${totalErrors} errors`);
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 = resolveOpsPort(opts);
674
+ const opsPort = agentPorts.ops;
346
675
  const opsAuth = `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPassSingle}`).toString("base64")}`;
347
676
  readStoredModel = opsStoredModelReader(opsPort, opsAuth);
348
- const searchRes = await fetch(`http://127.0.0.1:${opsPort}/`, {
349
- method: "POST",
350
- headers: { "Content-Type": "application/json", Authorization: opsAuth },
351
- body: JSON.stringify({
352
- operation: "search_by_value",
353
- database: "flair",
354
- table: "Memory",
355
- search_attribute: "agentId",
356
- search_value: agentId,
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
- const raw = await searchRes.json();
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: 10000,
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
- if (await reembedRow(baseUrl, agentId, privPath, memory.id, currentModel, readStoredModel))
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
- console.log(`\n\n✅ Re-embedding complete: ${processed} updated, ${errors} errors`);
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
  }