@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
@@ -15,11 +15,47 @@ import { encodeRecordId } from "../lib/record-id-path.js";
15
15
  import { existsSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
16
16
  import { dirname, resolve } from "node:path";
17
17
  import * as render from "../render.js";
18
- import { isLocalBase, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
18
+ import { isLocalBase, resolveAdminUser, resolveLocalAdminPass, addAdminPassOptions, AdminPassSourceError, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_HELP, ApiRequestOutcomeUnknown, apiErrorRawBody, boundErrorText, resolveRemRequestDeadlineMs, DEFAULT_REM_REQUEST_DEADLINE_MS } from "../lib/auth-resolve.js";
19
19
  import { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, validateHumanReviewerId, structuralImbalance, hasTerminalPunctuation, } from "../rem/promote-policy.js";
20
20
  import { resolveHome } from "../lib/home.js";
21
21
  export { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, derivePromotedVisibility, validateHumanReviewerId, isMachineReviewerId, ADK_SCOPE_TAG_PREFIX, CONTINUITY_SCOPE_TAG_PREFIX, MACHINE_REVIEWER_PREFIX, MACHINE_REVIEWER_ADK_AUTO_PROMOTE, } from "../rem/promote-policy.js";
22
22
  let cli;
23
+ /** The REM work routes that share {@link REM_WORK_REQUEST_DEADLINE_MS}. */
24
+ const REM_WORK_ROUTES = new Set([
25
+ "/MemoryMaintenance",
26
+ "/ReflectMemories",
27
+ "/MemoryDedupStats",
28
+ "/AutoPromoteCandidates",
29
+ ]);
30
+ /**
31
+ * The single whole-request deadline for every REM work route: POST
32
+ * /MemoryMaintenance, POST /ReflectMemories, POST /MemoryDedupStats and POST
33
+ * /AutoPromoteCandidates. Its sizing basis is documented on
34
+ * {@link DEFAULT_REM_REQUEST_DEADLINE_MS}. FLAIR_REM_REQUEST_TIMEOUT_MS
35
+ * overrides it and is read only for these four routes, so an invalid value of
36
+ * that variable refuses only those requests, before they are sent. Every other
37
+ * request through the shared REST sender that passes no explicit deadline
38
+ * resolves FLAIR_REQUEST_TIMEOUT_MS, else the shared default; an explicit
39
+ * deadline is validated and returned before that variable is read, so an
40
+ * invalid value of it does not refuse a request that passes one.
41
+ */
42
+ export const REM_WORK_REQUEST_DEADLINE_MS = DEFAULT_REM_REQUEST_DEADLINE_MS;
43
+ /**
44
+ * `{ deadlineMs, deadlineSource }` for every REM work route, `{}` for every
45
+ * other request. The new-variable value is resolved per call, so an invalid
46
+ * FLAIR_REM_REQUEST_TIMEOUT_MS is refused for these routes before the request
47
+ * is sent. The source travels with the deadline so its expiry names the
48
+ * variable that governs it, whether the value came from the variable or the
49
+ * default.
50
+ */
51
+ export function longRemRequestDeadline(method, path, env = process.env) {
52
+ if (method !== "POST")
53
+ return {};
54
+ if (REM_WORK_ROUTES.has(path)) {
55
+ return { deadlineMs: resolveRemRequestDeadlineMs(env), deadlineSource: "rem" };
56
+ }
57
+ return {};
58
+ }
23
59
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
24
60
  export function bindCli(fns) {
25
61
  cli = fns;
@@ -30,9 +66,6 @@ function api(...args) {
30
66
  function resolveOpsPort(opts) {
31
67
  return cli.resolveOpsPort(opts);
32
68
  }
33
- function applyAdminPassFile(opts) {
34
- cli.applyAdminPassFile(opts);
35
- }
36
69
  function addSharedCredentialOptions(cmd) {
37
70
  return cli.addSharedCredentialOptions(cmd);
38
71
  }
@@ -42,6 +75,12 @@ function readPortFromConfig() {
42
75
  function resolveHttpPort(opts, mode = "address") {
43
76
  return cli.resolveHttpPort(opts, mode);
44
77
  }
78
+ function deriveOpsUrl(target) {
79
+ return cli.resolveOpsUrlFromTarget(target);
80
+ }
81
+ function resolvePair(opts) {
82
+ return cli.resolveAgentHomeTarget(opts);
83
+ }
45
84
  function humanBytes(n) {
46
85
  return cli.humanBytes(n);
47
86
  }
@@ -53,24 +92,245 @@ function relativeTime(iso) {
53
92
  * rem commands. `search_by_conditions` is an ops-API operation, not a Harper
54
93
  * REST route — Harper's REST dispatcher maps `POST /<table>` to
55
94
  * `resource.post()` and never routes a URL suffix, so `/MemoryCandidate/
56
- * search_by_conditions` 405s. Both the nightly pending-candidate count and
57
- * the restore-time candidate cleanup must reach the ops port this way.
58
- * `fetchImpl` is injectable for tests.
95
+ * search_by_conditions` 405s. The nightly pending-candidate count reaches the
96
+ * ops port this way. `opsUrl`, when given, takes precedence over `opsPort` (a
97
+ * loopback port). A redirect is refused, so the admin credential goes only to
98
+ * the URL built here. `fetchImpl` is injectable for tests.
59
99
  */
60
100
  export function buildOpsSearch(opts, fetchImpl = fetch) {
101
+ const root = (opts.opsUrl ?? `http://127.0.0.1:${opts.opsPort}`).replace(/\/+$/, "");
61
102
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${opts.adminPass}`).toString("base64")}`;
62
103
  return async (table, conditions, getAttributes) => {
63
- const res = await fetchImpl(`http://127.0.0.1:${opts.opsPort}/`, {
104
+ const res = await fetchImpl(`${root}/`, {
64
105
  method: "POST",
106
+ redirect: "error",
65
107
  headers: { "Content-Type": "application/json", Authorization: auth },
66
108
  body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions, get_attributes: getAttributes }),
67
109
  });
68
110
  if (!res.ok)
69
111
  throw new Error(`ops API failed (${res.status})`);
70
- const raw = await res.json();
71
- return Array.isArray(raw) ? raw : (raw?.results ?? []);
112
+ let raw;
113
+ try {
114
+ raw = await res.json();
115
+ }
116
+ catch {
117
+ throw new Error("ops API returned invalid JSON");
118
+ }
119
+ if (Array.isArray(raw))
120
+ return raw;
121
+ const results = raw?.results;
122
+ // flair#2680: an unrecognised body is an error, not zero rows.
123
+ if (Array.isArray(results))
124
+ return results;
125
+ throw new Error("ops API returned an unexpected response shape");
72
126
  };
73
127
  }
128
+ /**
129
+ * A URL as restore prints it: scheme, host, port and path. User info, a query
130
+ * and a fragment are never printed. A value that is not an http(s) URL prints
131
+ * as `placeholder`: its parts are hidden, so untrusted input is not echoed.
132
+ */
133
+ export function displayRestoreUrl(raw, placeholder) {
134
+ let u;
135
+ try {
136
+ u = new URL(raw);
137
+ }
138
+ catch {
139
+ return placeholder;
140
+ }
141
+ if (u.protocol !== "http:" && u.protocol !== "https:")
142
+ return placeholder;
143
+ return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, "")}`;
144
+ }
145
+ /** Whether a target URL names a loopback host: 127.0.0.1, localhost, or ::1 (`[::1]` in a URL). */
146
+ function isLoopbackTargetUrl(u) {
147
+ return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "[::1]";
148
+ }
149
+ /** A URL's port, or its scheme's default port when the URL names none. */
150
+ function effectivePort(u) {
151
+ if (u.port)
152
+ return Number(u.port);
153
+ return u.protocol === "https:" ? 443 : 80;
154
+ }
155
+ /** The paired resolver's message without its stamp-home remedy, which names flags restore does not have. */
156
+ function withoutPairRemedy(message) {
157
+ const remedy = cli?.INSTANCE_TARGET_REMEDY;
158
+ return remedy && message.endsWith(remedy) ? message.slice(0, -remedy.length).trimEnd() : message;
159
+ }
160
+ /**
161
+ * Resolves the restore target's base URL (flair#2708), plus the operations
162
+ * fields its FLAIR_OPS_PORT and FLAIR_OPS_TARGET checks name. Restore's reads,
163
+ * deletes, writes and candidate listing all use `baseUrl`.
164
+ *
165
+ * - With no FLAIR_URL, the target is the local instance: its port pair comes
166
+ * from the paired resolver (`resolveAgentHomeTarget`, flair#2474), which
167
+ * refuses FLAIR_OPS_PORT when no complete configured pair can show which
168
+ * HTTP port it belongs with.
169
+ * - With FLAIR_URL, the target is the resolved base URL (the URL's scheme,
170
+ * port and path, with a loopback host pinned to 127.0.0.1). Its HTTP port is
171
+ * the URL's port, or 80/443 when it names none. The operations port is
172
+ * FLAIR_OPS_PORT when set, else the conventional derivation from the target
173
+ * URL (`resolveOpsUrlFromTarget`); a target with no derivable operations
174
+ * port and no FLAIR_OPS_PORT is refused. For a loopback URL (127.0.0.1,
175
+ * localhost or [::1]) the two ports also go through the paired resolver,
176
+ * which refuses a pair that conflicts with this host's configured pair. Any
177
+ * other URL, including one with this machine's LAN address, is not compared
178
+ * with this host's configuration.
179
+ * - A FLAIR_URL carrying user info, a query or a fragment is refused, and the
180
+ * message prints none of their values.
181
+ * - FLAIR_OPS_TARGET does not select the listing endpoint. When it is set to
182
+ * anything but exactly the root URL of the operations API resolved here
183
+ * (compared as normalized root URLs, with no user info, query, fragment or
184
+ * path), restore refuses; a value of only whitespace is refused too. An
185
+ * empty value counts as unset, as FLAIR_URL and FLAIR_OPS_PORT do here.
186
+ */
187
+ export function resolveRestoreTarget(env, deps = {}) {
188
+ const resolvePairImpl = deps.resolvePair ?? resolvePair;
189
+ const deriveOpsUrlImpl = deps.deriveOpsUrl ?? deriveOpsUrl;
190
+ const opsPortEnv = env.opsPort;
191
+ const declared = opsPortEnv === undefined || opsPortEnv === "" ? null : Number(opsPortEnv);
192
+ if (declared !== null && (!Number.isInteger(declared) || declared < 1 || declared > 65535)) {
193
+ throw new Error(`invalid FLAIR_OPS_PORT ${JSON.stringify(opsPortEnv)}. Set it to the restore target instance's operations port (1-65535), or unset it.`);
194
+ }
195
+ let target;
196
+ if (!env.flairUrl) {
197
+ let pair;
198
+ try {
199
+ pair = resolvePairImpl(declared === null ? {} : { opsPort: declared });
200
+ }
201
+ catch (err) {
202
+ throw new Error(`the local restore target could not be paired: ${withoutPairRemedy(err?.message ?? String(err))} `
203
+ + "Set FLAIR_URL to the instance's base URL and FLAIR_OPS_PORT to its operations port, or unset FLAIR_OPS_PORT to use the configured pair.");
204
+ }
205
+ target = {
206
+ baseUrl: `http://127.0.0.1:${pair.httpPort}`,
207
+ opsUrl: `http://127.0.0.1:${pair.opsPort}`,
208
+ httpPort: pair.httpPort,
209
+ opsPort: pair.opsPort,
210
+ loopback: true,
211
+ };
212
+ }
213
+ else {
214
+ target = resolveUrlRestoreTarget(env.flairUrl, declared, resolvePairImpl, deriveOpsUrlImpl);
215
+ }
216
+ refuseOtherOpsTarget(env.opsTarget, target);
217
+ return target;
218
+ }
219
+ function resolveUrlRestoreTarget(raw, declared, resolvePairImpl, deriveOpsUrlImpl) {
220
+ const example = "for example http://127.0.0.1:19926";
221
+ let u;
222
+ try {
223
+ u = new URL(raw);
224
+ }
225
+ catch {
226
+ throw new Error(`FLAIR_URL is not a parseable URL, so restore has no instance to address. Set FLAIR_URL to the instance's base URL (${example}), or unset it to restore the local instance.`);
227
+ }
228
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
229
+ throw new Error(`FLAIR_URL is not an http:// or https:// URL, so restore has no instance to address. Set FLAIR_URL to the instance's base URL (${example}), or unset it to restore the local instance.`);
230
+ }
231
+ const shown = displayRestoreUrl(raw, "<FLAIR_URL>");
232
+ const carried = [];
233
+ if (u.username || u.password)
234
+ carried.push("user info");
235
+ if (u.search || raw.includes("?"))
236
+ carried.push("a query");
237
+ if (u.hash || raw.includes("#"))
238
+ carried.push("a fragment");
239
+ if (carried.length > 0) {
240
+ throw new Error(`FLAIR_URL ${shown} carries ${carried.join(" and ")}. Restore refuses a target URL that carries user info, a query or a fragment, and prints none of their values. `
241
+ + "Set FLAIR_URL to the instance's base URL (scheme, host and port), and pass the admin credential with --admin-pass or --admin-pass-file (FLAIR_ADMIN_PASS is read only for a loopback target).");
242
+ }
243
+ const base = shown;
244
+ const httpPort = effectivePort(u);
245
+ let opsPort;
246
+ if (declared !== null) {
247
+ opsPort = declared;
248
+ }
249
+ else {
250
+ let derived;
251
+ try {
252
+ derived = new URL(deriveOpsUrlImpl(base));
253
+ }
254
+ catch (err) {
255
+ throw new Error(`restore target ${shown} has no derivable operations API URL (${err?.message ?? String(err)}). `
256
+ + "Restore resolves an operations port for its target, from FLAIR_URL when FLAIR_OPS_PORT is unset. "
257
+ + "Set FLAIR_OPS_PORT to that instance's operations port, or set FLAIR_URL to the instance's base URL with its HTTP port.");
258
+ }
259
+ opsPort = effectivePort(derived);
260
+ }
261
+ const loopback = isLoopbackTargetUrl(u);
262
+ if (loopback) {
263
+ try {
264
+ resolvePairImpl({ port: httpPort, opsPort });
265
+ }
266
+ catch (err) {
267
+ throw new Error(`restore target ${shown} could not be paired with operations port ${opsPort}`
268
+ + `${declared === null ? " (derived from FLAIR_URL)" : " (FLAIR_OPS_PORT)"}: ${withoutPairRemedy(err?.message ?? String(err))} `
269
+ + `Set FLAIR_OPS_PORT to the operations port of the instance serving HTTP port ${httpPort}, or unset it to derive the operations port from FLAIR_URL.`);
270
+ }
271
+ // Both endpoints on 127.0.0.1, whichever loopback name the URL uses.
272
+ const pinned = new URL(base);
273
+ pinned.hostname = "127.0.0.1";
274
+ return { baseUrl: pinned.toString().replace(/\/$/, ""), opsUrl: `http://127.0.0.1:${opsPort}`, httpPort, opsPort, loopback };
275
+ }
276
+ const ops = new URL(base);
277
+ ops.port = String(opsPort);
278
+ ops.pathname = "";
279
+ return { baseUrl: base, opsUrl: ops.toString().replace(/\/$/, ""), httpPort, opsPort, loopback };
280
+ }
281
+ /** `scheme://host:port/` with the scheme's default port written out, for comparing two root URLs. */
282
+ function normalizedRoot(u) {
283
+ return `${u.protocol}//${u.hostname}:${effectivePort(u)}/`;
284
+ }
285
+ /**
286
+ * Refuses a FLAIR_OPS_TARGET that is not exactly the root URL of `target`'s
287
+ * operations API. The two are compared as normalized root URLs (scheme, host
288
+ * and port, with the default port written out). User info, a query, a fragment
289
+ * or a path other than `/` refuses even on the same scheme, host and port, and
290
+ * the message prints only the override's scheme, host and port. A value of
291
+ * only whitespace is set, not unset, and is refused; an empty value counts as
292
+ * unset. The setting does not select restore's listing endpoint, which is the
293
+ * target's base URL.
294
+ */
295
+ function refuseOtherOpsTarget(opsTargetEnv, target) {
296
+ if (opsTargetEnv === undefined || opsTargetEnv === "")
297
+ return;
298
+ const raw = opsTargetEnv.trim();
299
+ if (!raw) {
300
+ throw new Error(`FLAIR_OPS_TARGET is set but holds only whitespace, so it names no operations endpoint to compare with the one restore resolves for its target (${target.opsUrl}); `
301
+ + `nothing was sent. Unset FLAIR_OPS_TARGET for this command, or set it to ${target.opsUrl}.`);
302
+ }
303
+ let named;
304
+ try {
305
+ named = new URL(raw);
306
+ }
307
+ catch {
308
+ named = null;
309
+ }
310
+ const httpLike = named !== null && (named.protocol === "http:" || named.protocol === "https:");
311
+ const shown = httpLike ? `${named.protocol}//${named.host}` : "<not an http(s) URL>";
312
+ const remedy = `Unset FLAIR_OPS_TARGET for this command, or set it to ${target.opsUrl}.`;
313
+ if (named === null || !httpLike) {
314
+ throw new Error(`FLAIR_OPS_TARGET is not an http(s) URL, so it cannot be the operations API restore resolves for its target (${target.opsUrl}); nothing was sent to it. ${remedy}`);
315
+ }
316
+ const carried = [];
317
+ if (named.username || named.password)
318
+ carried.push("user info");
319
+ if (named.search || raw.includes("?"))
320
+ carried.push("a query");
321
+ if (named.hash || raw.includes("#"))
322
+ carried.push("a fragment");
323
+ if (named.pathname !== "/")
324
+ carried.push("a path other than /");
325
+ if (carried.length > 0) {
326
+ throw new Error(`FLAIR_OPS_TARGET ${shown} carries ${carried.join(" and ")}. Restore accepts FLAIR_OPS_TARGET only when it is exactly the root URL `
327
+ + `of the operations API it resolves for its target (${target.opsUrl}), prints none of its user info, path, query or fragment, and sent nothing to it. ${remedy}`);
328
+ }
329
+ if (normalizedRoot(named) !== normalizedRoot(new URL(target.opsUrl))) {
330
+ throw new Error(`FLAIR_OPS_TARGET names the operations endpoint ${shown}, but the operations API restore resolves `
331
+ + `from its own target ${target.baseUrl} is ${target.opsUrl}; nothing was sent to FLAIR_OPS_TARGET. ${remedy}`);
332
+ }
333
+ }
74
334
  // ─── flair rem rapid — pure helpers ──────────────────────────────────────────
75
335
  // Extracted for testability, same pattern as validatePromoteOpts /
76
336
  // decideCandidateAction above: the action callback below spawns api() +
@@ -106,26 +366,42 @@ export function candidateIncompleteFlag(claim) {
106
366
  }
107
367
  /**
108
368
  * Classifies a thrown /ReflectMemories execute-mode error for CLI display.
109
- * `api()` throws `Error(responseBodyText)` for non-2xx responses (see api()
110
- * above) — the two execute-mode failure bodies are:
369
+ * `api()` throws an ApiHttpError for a non-2xx response (flair#2764). The kind
370
+ * is read from its unredacted text (apiErrorRawBody) when the error was built
371
+ * from a non-empty response body (ApiHttpError.fromResponse), and from the
372
+ * message otherwise (the credential-less 403 and a refused redirect carry only
373
+ * a message, as does any other error); for a JSON error read either way, the
374
+ * text shown is derived from that text through boundErrorText, which
375
+ * redacts the credential values read from the request's Authorization header
376
+ * (credentialsInHeader) from the server's text within the scope stated on
377
+ * ApiHttpError, or withholds that text when the header's credential could not
378
+ * be read and the response text was non-empty, even when the text derived
379
+ * from it is empty (the prefix the caller prints is outside the scope). The two
380
+ * classified distillation failures are:
111
381
  * 503 no-backend: { error: "No generative backend configured..." }
112
382
  * 502 distillation_failed: { error: "distillation_failed", detail: "..." }
383
+ * The 503 pause refusal ({ error: "rem_aborted", detail: "..." }, sent while the
384
+ * pause sentinel or FLAIR_REM_PAUSE=1 is set) has no kind of its own: it reads
385
+ * as "other" with the text `rem_aborted`.
113
386
  * Any other shape (network errors, the 400/403 actor-resolution errors
114
387
  * prompt mode shares) falls back to "other" — printed as a plain message,
115
- * no docs pointer or retry hint attached since neither applies.
388
+ * no docs pointer or retry hint attached since neither applies. Accepts the
389
+ * thrown error or its message string.
116
390
  */
117
- export function describeReflectError(message) {
391
+ export function describeReflectError(err) {
392
+ const message = typeof err === "string" ? err : String(err?.message ?? err);
118
393
  try {
119
- const parsed = JSON.parse(message);
394
+ const parsed = JSON.parse(apiErrorRawBody(err) || message);
120
395
  if (parsed && typeof parsed === "object") {
121
396
  if (parsed.error === "distillation_failed") {
122
- return { kind: "distillation-failed", text: String(parsed.detail ?? parsed.error) };
397
+ const detail = typeof parsed.detail === "string" ? parsed.detail : "";
398
+ return { kind: "distillation-failed", text: boundErrorText(err, detail || parsed.error) };
123
399
  }
124
400
  if (typeof parsed.error === "string" && parsed.error.startsWith("No generative backend configured")) {
125
- return { kind: "no-backend", text: parsed.error };
401
+ return { kind: "no-backend", text: boundErrorText(err, parsed.error) };
126
402
  }
127
403
  if (typeof parsed.error === "string") {
128
- return { kind: "other", text: parsed.error };
404
+ return { kind: "other", text: boundErrorText(err, parsed.error) };
129
405
  }
130
406
  }
131
407
  }
@@ -134,7 +410,7 @@ export function describeReflectError(message) {
134
410
  }
135
411
  return { kind: "other", text: message };
136
412
  }
137
- /** Print skips and errors; errors alone set exit 1. */
413
+ /** Print skips, unknown outcomes and errors; errors alone set exit 1, an unknown outcome exit 3. */
138
414
  export function summarizeNightlyOutcome(row) {
139
415
  const lines = [];
140
416
  if (row.errors.length > 0) {
@@ -147,9 +423,29 @@ export function summarizeNightlyOutcome(row) {
147
423
  for (const s of row.skips)
148
424
  lines.push(` - ${s}`);
149
425
  }
150
- return { lines, exitCode: row.errors.length > 0 ? 1 : 0 };
426
+ if (row.outcomeUnknown && row.outcomeUnknown.length > 0) {
427
+ lines.push("Unknown outcome:");
428
+ for (const u of row.outcomeUnknown)
429
+ lines.push(` - ${u}`);
430
+ lines.push(" These writes may or may not have taken effect. Inspect what was staged before re-running this cycle, once the server has settled.");
431
+ }
432
+ // Exit 3 for an unknown write outcome, as `flair memory verify` and
433
+ // `memory compare-nodes` use 3 for "unknown": distinct from the 1 an
434
+ // ordinary failure exits with.
435
+ const exitCode = (row.outcomeUnknown?.length ?? 0) > 0 ? 3 : row.errors.length > 0 ? 1 : 0;
436
+ return { lines, exitCode };
151
437
  }
152
438
  const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
439
+ /**
440
+ * Print a write's unknown outcome and exit 3, the CLI's "unknown" code (as
441
+ * `flair memory verify` uses it), distinct from the 1 an ordinary failure
442
+ * exits with.
443
+ */
444
+ export function exitUnknownOutcome(err) {
445
+ console.error(`Unknown outcome: ${err.message}`);
446
+ console.error(`The request may or may not have taken effect; inspect the target before re-running.`);
447
+ process.exit(3);
448
+ }
153
449
  function writeRemPauseSentinel() {
154
450
  const dir = dirname(REM_PAUSE_FLAG);
155
451
  if (!existsSync(dir))
@@ -179,7 +475,7 @@ export function register(program) {
179
475
  const maint = await api("POST", "/MemoryMaintenance", {
180
476
  ...(agentId ? { agentId } : {}),
181
477
  dryRun,
182
- });
478
+ }, longRemRequestDeadline("POST", "/MemoryMaintenance"));
183
479
  if (maint.error) {
184
480
  console.error(`Maintenance error: ${maint.error}`);
185
481
  process.exit(1);
@@ -225,6 +521,8 @@ export function register(program) {
225
521
  console.log(`\nDone.${dryRun ? " No changes applied (dry run)." : ""}`);
226
522
  }
227
523
  catch (err) {
524
+ if (err instanceof ApiRequestOutcomeUnknown)
525
+ exitUnknownOutcome(err);
228
526
  console.error(`Error: ${err.message}`);
229
527
  process.exit(1);
230
528
  }
@@ -259,7 +557,7 @@ export function register(program) {
259
557
  if (opts.promptOnly) {
260
558
  // --prompt-only: EXACT pre-#710 behavior — prompt-return mode, unchanged.
261
559
  try {
262
- const result = await api("POST", "/ReflectMemories", body);
560
+ const result = await api("POST", "/ReflectMemories", body, longRemRequestDeadline("POST", "/ReflectMemories"));
263
561
  if (result.error) {
264
562
  console.error(`Reflection error: ${result.error}`);
265
563
  process.exit(1);
@@ -275,6 +573,8 @@ export function register(program) {
275
573
  console.log(" flair memory add --agent <id> --content <insight> --durability persistent --derived-from <source-ids>");
276
574
  }
277
575
  catch (err) {
576
+ if (err instanceof ApiRequestOutcomeUnknown)
577
+ exitUnknownOutcome(err);
278
578
  console.error(`Error: ${err.message}`);
279
579
  process.exit(1);
280
580
  }
@@ -282,7 +582,7 @@ export function register(program) {
282
582
  }
283
583
  // Default: execute mode — distill server-side, stage candidates.
284
584
  try {
285
- const result = await api("POST", "/ReflectMemories", { ...body, execute: true });
585
+ const result = await api("POST", "/ReflectMemories", { ...body, execute: true }, longRemRequestDeadline("POST", "/ReflectMemories"));
286
586
  const candidates = Array.isArray(result.candidates) ? result.candidates : [];
287
587
  console.log(`\nModel: ${result.model ?? "?"}`);
288
588
  console.log(`Candidates: ${result.count ?? candidates.length}`);
@@ -294,7 +594,9 @@ export function register(program) {
294
594
  console.log(`\nreview: flair rem candidates / flair rem promote <id>`);
295
595
  }
296
596
  catch (err) {
297
- const desc = describeReflectError(err.message ?? String(err));
597
+ if (err instanceof ApiRequestOutcomeUnknown)
598
+ exitUnknownOutcome(err);
599
+ const desc = describeReflectError(err);
298
600
  if (desc.kind === "no-backend") {
299
601
  console.error(`Reflection error: ${desc.text}`);
300
602
  console.error(`See docs/rem.md#configuration for how to point Flair at a models: backend.`);
@@ -327,7 +629,7 @@ export function register(program) {
327
629
  const maint = await api("POST", "/MemoryMaintenance", {
328
630
  ...(agentId ? { agentId } : {}),
329
631
  dryRun,
330
- });
632
+ }, longRemRequestDeadline("POST", "/MemoryMaintenance"));
331
633
  if (maint.error) {
332
634
  console.error(`Maintenance error: ${maint.error}`);
333
635
  process.exit(1);
@@ -366,7 +668,7 @@ export function register(program) {
366
668
  const reflect = await api("POST", "/ReflectMemories", {
367
669
  agentId,
368
670
  scope: "all",
369
- });
671
+ }, longRemRequestDeadline("POST", "/ReflectMemories"));
370
672
  if (reflect.error) {
371
673
  console.error(`Reflection error: ${reflect.error}`);
372
674
  process.exit(1);
@@ -385,6 +687,8 @@ export function register(program) {
385
687
  console.log(`\nRestorative cycle complete.${dryRun ? " No changes applied (dry run)." : ""}`);
386
688
  }
387
689
  catch (err) {
690
+ if (err instanceof ApiRequestOutcomeUnknown)
691
+ exitUnknownOutcome(err);
388
692
  console.error(`Error: ${err.message}`);
389
693
  process.exit(1);
390
694
  }
@@ -394,12 +698,11 @@ export function register(program) {
394
698
  // MemoryCandidate table. Empty until the nightly cycle (later slice) starts
395
699
  // populating. Per spec § 5: candidates are NEVER auto-promoted; this command
396
700
  // is the operator's review surface.
397
- rem
701
+ addAdminPassOptions(rem
398
702
  .command("candidates")
399
703
  .description("List staged memory candidates from the FLAIR-NIGHTLY-REM cycle (pending review)")
400
704
  .option("--port <port>", "Harper HTTP port")
401
- .option("--ops-port <port>", "Harper operations API port")
402
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
705
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS)")
403
706
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
404
707
  .option("--agent <id>", "Agent ID (or FLAIR_AGENT_ID env)")
405
708
  .option("--status <s>", "Filter by status: pending | promoted | rejected (default: pending)")
@@ -631,6 +934,8 @@ export function register(program) {
631
934
  console.log(`✅ Candidate ${candidateId} marked promoted → ${opts.to}, reviewer=${reviewerId}`);
632
935
  }
633
936
  catch (err) {
937
+ if (err instanceof ApiRequestOutcomeUnknown)
938
+ exitUnknownOutcome(err);
634
939
  console.error(`Error: ${err.message}`);
635
940
  process.exit(1);
636
941
  }
@@ -682,6 +987,8 @@ export function register(program) {
682
987
  console.log(` Reason: ${opts.reason}`);
683
988
  }
684
989
  catch (err) {
990
+ if (err instanceof ApiRequestOutcomeUnknown)
991
+ exitUnknownOutcome(err);
685
992
  console.error(`Error: ${err.message}`);
686
993
  process.exit(1);
687
994
  }
@@ -707,7 +1014,12 @@ export function register(program) {
707
1014
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
708
1015
  .option("--at <HH:MM>", "Local time to run nightly (default 03:00)", "03:00")
709
1016
  .option("--flair-url <url>", "Flair HTTP URL the runner will hit (default http://127.0.0.1:<port>)")
1017
+ .option(ADMIN_PASS_FILE_FLAG, "Absolute path of the owner-only admin-password file the shim passes to run-once (default: ~/.flair/admin-pass)")
710
1018
  .action(async (opts) => {
1019
+ if (opts.adminPassFile === "") {
1020
+ console.error("Error: --admin-pass-file must not be empty");
1021
+ process.exit(1);
1022
+ }
711
1023
  const agentId = opts.agent || process.env.FLAIR_AGENT_ID;
712
1024
  if (!agentId) {
713
1025
  console.error("Error: --agent or FLAIR_AGENT_ID env required");
@@ -724,7 +1036,7 @@ export function register(program) {
724
1036
  const flairUrl = opts.flairUrl || process.env.FLAIR_URL || `http://127.0.0.1:${port}`;
725
1037
  const { enableScheduler, formatEnableReport } = await import("../rem/scheduler.js");
726
1038
  try {
727
- const r = enableScheduler({ agentId, flairUrl, hour, minute });
1039
+ const r = enableScheduler({ agentId, flairUrl, hour, minute, adminPassFile: opts.adminPassFile });
728
1040
  // formatEnableReport() owns the success-vs-failure decision (flair#850:
729
1041
  // do not print a success headline before activation is known to have
730
1042
  // succeeded) — see src/rem/scheduler.ts for the unit-tested logic.
@@ -784,12 +1096,24 @@ export function register(program) {
784
1096
  process.exit(1);
785
1097
  }
786
1098
  });
787
- remNightly
1099
+ addAdminPassOptions(remNightly
788
1100
  .command("run-once")
789
1101
  .description("Run one nightly cycle now (snapshot + log). Same code path the scheduler will use.")
790
1102
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
791
- .option("--ops-port <port>", "Harper operations API port")
792
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
1103
+ .option("--ops-port <port>", "Harper operations API port"), ADMIN_PASS_HELP, {
1104
+ onAdminPassRefusal: (err, actionCommand) => {
1105
+ const refused = actionCommand.opts();
1106
+ const message = err.message;
1107
+ console.error(`Error: ${message}`);
1108
+ if (refused.adminPassFile !== undefined) {
1109
+ const remedy = err instanceof AdminPassSourceError
1110
+ ? ""
1111
+ : ` Provide an owner-only (chmod 600), non-empty admin password file${refused.adminPassFile === "" ? " via --admin-pass-file <path>" : ` at ${refused.adminPassFile}`}, then re-run \`flair rem nightly run-once\`.`;
1112
+ console.error(`Dedup: NOT RUN — ${message}${remedy}`);
1113
+ }
1114
+ process.exit(1);
1115
+ },
1116
+ })
793
1117
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
794
1118
  .option("--dry-run", "Log the row but skip the snapshot write")
795
1119
  .action(async (opts) => {
@@ -798,12 +1122,36 @@ export function register(program) {
798
1122
  console.error("Error: --agent or FLAIR_AGENT_ID env required");
799
1123
  process.exit(1);
800
1124
  }
801
- const { runNightlyCycle } = await import("../rem/runner.js");
1125
+ const { runNightlyCycle, RunnerLogWriteError, formatPendingCandidates, formatCount, formatAutoPromoted } = await import("../rem/runner.js");
802
1126
  // The runner is agent-authed and cannot reach the ops port itself. When
803
- // admin credentials are available, inject an ops-API `search_by_conditions`
804
- // helper so the pending-candidate count can be sampled; otherwise the count
805
- // is best-effort 0 (the cycle still runs).
806
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1127
+ // admin credentials are available, inject ops-API and admin-authed REST
1128
+ // helpers so the pending-candidate count and the admin-gated dedup step
1129
+ // can run. An explicit file or flag is applied by the pair's preAction
1130
+ // hook before any cycle work. A refused FILE is reported as `Dedup: NOT
1131
+ // RUN` rather than issuing an agent-authed call that an agent key cannot
1132
+ // authorize.
1133
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
1134
+ // Every agent-scoped call is signed by the selected agent and nothing
1135
+ // else: the identity is pinned here (never FLAIR_AGENT_ID), and
1136
+ // signedOnly refuses FLAIR_TOKEN / FLAIR_ADMIN_PASS / the local
1137
+ // admin-pass file. A selected agent with no key is refused, not
1138
+ // silently replaced by an ambient credential.
1139
+ //
1140
+ // The REM work calls can legitimately outrun the shared default:
1141
+ // maintenance scans its scoped rows with no run row cap, reflection
1142
+ // waits on a generative backend, the auto-promote sweep carries up to
1143
+ // DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE promotions, and the instance-wide
1144
+ // dedup sweep is sized from the fixture's 23.07 s over 403 live vectors
1145
+ // (test/bench/rem-responsiveness.md). All four REM work routes get the
1146
+ // one 1,800 s deadline from longRemRequestDeadline,
1147
+ // FLAIR_REM_REQUEST_TIMEOUT_MS overrides it, and every other call
1148
+ // through the shared REST sender that passes no explicit deadline
1149
+ // resolves FLAIR_REQUEST_TIMEOUT_MS when it is set, else the default.
1150
+ const remDeadline = longRemRequestDeadline;
1151
+ const agentApiCall = (method, path, body) => api(method, path, body, { agentId, agentIdSource: "flag", signedOnly: true, ...remDeadline(method, path) });
1152
+ const adminApiCall = adminPass
1153
+ ? (method, path, body) => api(method, path, body, { explicitAdminPass: adminPass, adminUser: opts.adminUser, agentId: null, ...remDeadline(method, path) })
1154
+ : undefined;
807
1155
  const opsSearch = adminPass
808
1156
  ? buildOpsSearch({ opsPort: resolveOpsPort(opts), adminUser: opts.adminUser, adminPass })
809
1157
  : undefined;
@@ -812,7 +1160,8 @@ export function register(program) {
812
1160
  const result = await runNightlyCycle({
813
1161
  agentId,
814
1162
  flairVersion: __pkgVersion,
815
- apiCall: api,
1163
+ apiCall: agentApiCall,
1164
+ adminApiCall,
816
1165
  opsSearch,
817
1166
  dryRun: !!opts.dryRun,
818
1167
  healthProbe: async (timeoutMs) => {
@@ -836,9 +1185,9 @@ export function register(program) {
836
1185
  if (result.snapshotPath) {
837
1186
  console.log(`Snapshot: ${result.snapshotPath}`);
838
1187
  }
839
- console.log(`Memories: ${row.memoryCount ?? "—"}`);
840
- console.log(`Souls: ${row.soulCount ?? "—"}`);
841
- console.log(`Pending: ${row.pendingCandidates ?? "—"}`);
1188
+ console.log(`Memories: ${formatCount(row.memoryCount)}`);
1189
+ console.log(`Souls: ${formatCount(row.soulCount)}`);
1190
+ console.log(`Pending: ${formatPendingCandidates(row.pendingCandidates)}`);
842
1191
  if (typeof row.archived === "number" || typeof row.expired === "number") {
843
1192
  // #1503: `archived` counts validTo-expired and old-session rows the
844
1193
  // pass soft-archived; `expired` counts ephemeral rows past their
@@ -858,10 +1207,15 @@ export function register(program) {
858
1207
  if (row.distill.aborted)
859
1208
  console.log(`Aborted: yes — in-flight distillation stopped (flair rem pause)`);
860
1209
  }
861
- // row.autoPromoted populates when step 5b (#1205b-2 ADK auto-promote) ran
862
- // this cycle — i.e. a non-dry-run cycle for an ADK agentId.
1210
+ // row.autoPromoted populates when step 5b (#1205b-2 auto-promote) ran
1211
+ // this cycle and the server returned a response without an error — i.e.
1212
+ // a non-aborted, non-dry-run
1213
+ // cycle with active ADK tags or selected settled continuity sessions
1214
+ // (flair#1257 slice 3); successful distillation is not required.
1215
+ // Incomplete and unconfirmed promotions are named on the line
1216
+ // (flair#2714).
863
1217
  if (row.autoPromoted) {
864
- console.log(`Auto-promoted: ${row.autoPromoted.promoted} to own memory (${row.autoPromoted.skipped} left pending)`);
1218
+ console.log(formatAutoPromoted(row.autoPromoted));
865
1219
  }
866
1220
  // A guard refusal carries null counts and the guard's named state.
867
1221
  const dedupRow = row.dedup;
@@ -878,7 +1232,7 @@ export function register(program) {
878
1232
  console.log(`\nNote: REM refused to start because /Health could not be served.`);
879
1233
  console.log(`Restore /Health before retrying, or \`flair rem pause\` to stop the scheduler.`);
880
1234
  }
881
- if (row.errors.length > 0 || row.skips.length > 0) {
1235
+ if (row.errors.length > 0 || row.skips.length > 0 || (row.outcomeUnknown?.length ?? 0) > 0) {
882
1236
  const outcome = summarizeNightlyOutcome(row);
883
1237
  for (const line of outcome.lines)
884
1238
  console.log(line);
@@ -891,6 +1245,14 @@ export function register(program) {
891
1245
  }
892
1246
  }
893
1247
  catch (err) {
1248
+ if (err instanceof RunnerLogWriteError && (err.row.outcomeUnknown?.length ?? 0) > 0) {
1249
+ console.log(`Status: ${err.row.status}`);
1250
+ const outcome = summarizeNightlyOutcome(err.row);
1251
+ for (const line of outcome.lines)
1252
+ console.log(line);
1253
+ console.error(`Log write failed: ${err.message}`);
1254
+ process.exit(3);
1255
+ }
894
1256
  console.error(`Error: ${err.message}`);
895
1257
  process.exit(1);
896
1258
  }
@@ -948,7 +1310,7 @@ export function register(program) {
948
1310
  .description("Restore from a REM snapshot (inspect by default; --apply rewinds Harper state)")
949
1311
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
950
1312
  .option("--target <dir>", "Directory to extract into (default: <snapshot>.restored, only used without --apply)")
951
- .option("--dry-run", "Plan-only — list contents or planned counts without writing")
1313
+ .option("--dry-run", "Plan-only — list contents or planned counts without writing; with --apply to a non-loopback target and no --admin-pass or --admin-pass-file, credentials are resolved signed-only (no Basic credential is sent)")
952
1314
  .option("--apply", "Live replay: rewind Harper state to the snapshot (irreversible without the pre-restore snapshot)")
953
1315
  .action(async (date, opts) => {
954
1316
  const { listSnapshots, extractSnapshot } = await import("../rem/snapshot.js");
@@ -981,17 +1343,28 @@ export function register(program) {
981
1343
  const match = matches[0];
982
1344
  // --apply path: live replay via src/rem/restore.ts
983
1345
  if (opts.apply) {
984
- const { applySnapshot } = await import("../rem/restore.js");
985
- applyAdminPassFile(opts);
986
- const restoreBase = process.env.FLAIR_URL || `http://127.0.0.1:${resolveHttpPort({})}`;
987
- // Candidates are only reachable through the ops port (Harper has no
988
- // REST search_by_conditions route), so the dry-run candidate count
989
- // needs admin creds too. Dry-run treats credential resolution as
990
- // best-effort — a plan-only command must not fail on a bad credential
991
- // file — while --apply requires creds (Soul rewrite) and fails loudly.
1346
+ const { applySnapshot, formatUnknownState } = await import("../rem/restore.js");
1347
+ let restoreTarget;
1348
+ try {
1349
+ restoreTarget = resolveRestoreTarget({
1350
+ flairUrl: process.env.FLAIR_URL,
1351
+ opsPort: process.env.FLAIR_OPS_PORT,
1352
+ opsTarget: process.env.FLAIR_OPS_TARGET,
1353
+ });
1354
+ }
1355
+ catch (err) {
1356
+ console.error(`Error: ${err.message}`);
1357
+ process.exit(1);
1358
+ }
1359
+ // The CLI lists candidates only with a resolved admin password, so the
1360
+ // dry-run candidate count needs one too. Dry-run treats reading the ambient
1361
+ // local admin-password file as best-effort (an unusable file leaves
1362
+ // it without an admin credential), while --apply requires creds (Soul
1363
+ // rewrite) and fails loudly. A bad --admin-pass-file given explicitly
1364
+ // is refused earlier, by the option pair's preAction hook, dry run or not.
992
1365
  let adminPass;
993
1366
  try {
994
- adminPass = resolveLocalAdminPass(opts.adminPass, !isLocalBase(restoreBase));
1367
+ adminPass = resolveLocalAdminPass(opts.adminPass, !isLocalBase(restoreTarget.baseUrl));
995
1368
  }
996
1369
  catch (err) {
997
1370
  if (!opts.dryRun)
@@ -999,25 +1372,40 @@ export function register(program) {
999
1372
  adminPass = undefined;
1000
1373
  }
1001
1374
  if (!opts.dryRun && !adminPass) {
1002
- console.error("Error: --admin-pass, --admin-pass-file, or FLAIR_ADMIN_PASS required for rem restore --apply " +
1375
+ console.error((isLocalBase(restoreTarget.baseUrl)
1376
+ ? "Error: --admin-pass, --admin-pass-file, FLAIR_ADMIN_PASS or the local admin-password file required for rem restore --apply "
1377
+ : "Error: --admin-pass or --admin-pass-file required for rem restore --apply to a non-loopback target (FLAIR_ADMIN_PASS and the local admin-password file are read only for a loopback target) ") +
1003
1378
  "(Soul rewrite is operator-only; an agent key is refused).");
1004
1379
  process.exit(1);
1005
1380
  }
1006
- const opsSearch = adminPass
1007
- ? buildOpsSearch({ opsPort: resolveOpsPort(opts), adminUser: opts.adminUser, adminPass })
1008
- : undefined;
1009
- const soulApiCall = adminPass
1010
- ? (method, path, body) => api(method, path, body, { explicitAdminPass: adminPass, adminUser: opts.adminUser, agentId: null })
1011
- : undefined;
1381
+ // Every Memory, Soul and candidate read, delete and write goes to the
1382
+ // resolved base URL: the candidate listing is
1383
+ // GET /AdminMemoryCandidates/{agentId} on that same endpoint. Without
1384
+ // an admin password (a dry run only) there is no candidate listing.
1385
+ // Every REST call below refuses redirects, so it stays at that target.
1386
+ // With a resolved admin credential (a live replay always has one; an
1387
+ // --apply --dry-run may not), every Memory, Soul and MemoryCandidate
1388
+ // read, delete and write sends it explicitly:
1389
+ // --admin-pass, --admin-pass-file, or the default resolveLocalAdminPass
1390
+ // fell back to. A dry run to a non-loopback target without one reads
1391
+ // signed-only: no Basic credential is sent, and FLAIR_ADMIN_PASS and the
1392
+ // local admin-password file are not read for a target this machine's
1393
+ // secret was not given for. A loopback dry run without one keeps the
1394
+ // shared resolver's own tiers.
1395
+ const signedOnly = !!opts.dryRun && !adminPass && !restoreTarget.loopback;
1396
+ const targetApi = (method, path, body) => api(method, path, body, adminPass
1397
+ ? { baseUrl: restoreTarget.baseUrl, explicitAdminPass: adminPass, adminUser: opts.adminUser, agentId: null, refuseRedirects: true }
1398
+ : { baseUrl: restoreTarget.baseUrl, refuseRedirects: true, ...(signedOnly ? { signedOnly: true } : {}) });
1399
+ const soulApiCall = adminPass ? targetApi : undefined;
1012
1400
  try {
1013
1401
  const result = await applySnapshot({
1014
1402
  agentId,
1015
1403
  snapshotPath: match.path,
1016
1404
  flairVersion: __pkgVersion,
1017
- apiCall: api,
1018
- opsSearch,
1405
+ apiCall: targetApi,
1019
1406
  soulApiCall,
1020
1407
  dryRun: !!opts.dryRun,
1408
+ listCandidates: !!adminPass,
1021
1409
  });
1022
1410
  const verb = opts.dryRun ? "(dry-run) would" : "";
1023
1411
  console.log(`${opts.dryRun ? "(dry-run) " : ""}flair rem restore --apply${opts.dryRun ? "" : ""}`);
@@ -1029,6 +1417,32 @@ export function register(program) {
1029
1417
  }
1030
1418
  console.log(` Deleted: ${result.deleted.memories} memories, ${result.deleted.souls} souls, ${result.deleted.candidates} candidates`);
1031
1419
  console.log(` Restored: ${result.restored.memories} memories, ${result.restored.souls} souls`);
1420
+ if (result.retried.memories.length > 0) {
1421
+ console.log(` Retried: ${result.retried.memories.length} memories (${result.retried.memories.join(", ")})`);
1422
+ }
1423
+ const unknownCount = result.unknown.memories.length + result.unknown.souls.length + result.unknown.candidates.length;
1424
+ if (unknownCount > 0) {
1425
+ console.log(` Unknown: ${unknownCount} ids ended at the request deadline; their write may or may not have taken effect, and no later write to the same table and record id was sent`);
1426
+ for (const id of result.unknown.memories) {
1427
+ const state = result.verified?.unknownStates.find((s) => s.entity === "memory" && s.id === id);
1428
+ console.log(` - ${state ? formatUnknownState(state) : `memory ${id}: post-restore verification did not complete; its state is unverified`}`);
1429
+ }
1430
+ for (const id of result.unknown.souls) {
1431
+ const state = result.verified?.unknownStates.find((s) => s.entity === "soul" && s.id === id);
1432
+ console.log(` - ${state ? formatUnknownState(state) : `soul ${id}: post-restore verification did not complete; its state is unverified`}`);
1433
+ }
1434
+ for (const id of result.unknown.candidates) {
1435
+ console.log(` - MemoryCandidate ${id}: verification does not read candidates back; its state is unverified`);
1436
+ }
1437
+ if (result.skippedAfterUnknownDelete.memories.length + result.skippedAfterUnknownDelete.souls.length > 0) {
1438
+ const ids = [...result.skippedAfterUnknownDelete.memories, ...result.skippedAfterUnknownDelete.souls];
1439
+ console.log(` - not written again after an unknown write to the same table and record id: ${ids.join(", ")} (a late write could still change the row)`);
1440
+ }
1441
+ if (!result.verified) {
1442
+ console.log(` - memory and soul state not checked: post-restore verification did not complete`);
1443
+ }
1444
+ console.log(` Re-run once the server has settled: \`flair rem restore ${date} --agent ${agentId} --apply\` (restore is re-runnable).`);
1445
+ }
1032
1446
  if (result.errors.length > 0) {
1033
1447
  console.log(` Errors:`);
1034
1448
  for (const e of result.errors)
@@ -1036,6 +1450,11 @@ export function register(program) {
1036
1450
  }
1037
1451
  if (result.status === "failed")
1038
1452
  process.exit(1);
1453
+ // Exit 3 for an unknown write outcome, as `flair memory verify` and
1454
+ // `memory compare-nodes` use 3 for "unknown": distinct from the 1 an
1455
+ // ordinary restore failure exits with.
1456
+ if (result.status === "unresolved")
1457
+ process.exit(3);
1039
1458
  }
1040
1459
  catch (err) {
1041
1460
  console.error(`Error: ${err.message}`);