@tpsdev-ai/flair 0.59.0 → 0.63.0

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 (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,11 +1,61 @@
1
+ /**
2
+ * rem.ts — `flair rem` command group (flair#1623 / epic #1618).
3
+ *
4
+ * Extracted from src/cli.ts with ZERO behavior change. This file owns the
5
+ * group's commander registration, action handlers, and group-specific
6
+ * inline helpers (candidate-line format, reflect-error classify, pause
7
+ * sentinel). Shared CLI helpers (api, credential flags, port resolve, …)
8
+ * stay in cli.ts and are bound before register().
9
+ *
10
+ * Compiled with the rest of src/ under tsconfig.check.src.json (strict).
11
+ * Do not import src/cli.ts from here — that would cycle and pull the
12
+ * non-strict entry into the strict check.
13
+ */
14
+ import { encodeRecordId } from "../lib/record-id-path.js";
1
15
  import { existsSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
2
16
  import { dirname, resolve } from "node:path";
3
17
  import * as render from "../render.js";
4
- 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";
5
19
  import { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, validateHumanReviewerId, structuralImbalance, hasTerminalPunctuation, } from "../rem/promote-policy.js";
6
20
  import { resolveHome } from "../lib/home.js";
7
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";
8
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
+ }
9
59
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
10
60
  export function bindCli(fns) {
11
61
  cli = fns;
@@ -16,9 +66,6 @@ function api(...args) {
16
66
  function resolveOpsPort(opts) {
17
67
  return cli.resolveOpsPort(opts);
18
68
  }
19
- function applyAdminPassFile(opts) {
20
- cli.applyAdminPassFile(opts);
21
- }
22
69
  function addSharedCredentialOptions(cmd) {
23
70
  return cli.addSharedCredentialOptions(cmd);
24
71
  }
@@ -28,6 +75,12 @@ function readPortFromConfig() {
28
75
  function resolveHttpPort(opts, mode = "address") {
29
76
  return cli.resolveHttpPort(opts, mode);
30
77
  }
78
+ function deriveOpsUrl(target) {
79
+ return cli.resolveOpsUrlFromTarget(target);
80
+ }
81
+ function resolvePair(opts) {
82
+ return cli.resolveAgentHomeTarget(opts);
83
+ }
31
84
  function humanBytes(n) {
32
85
  return cli.humanBytes(n);
33
86
  }
@@ -39,24 +92,245 @@ function relativeTime(iso) {
39
92
  * rem commands. `search_by_conditions` is an ops-API operation, not a Harper
40
93
  * REST route — Harper's REST dispatcher maps `POST /<table>` to
41
94
  * `resource.post()` and never routes a URL suffix, so `/MemoryCandidate/
42
- * search_by_conditions` 405s. Both the nightly pending-candidate count and
43
- * the restore-time candidate cleanup must reach the ops port this way.
44
- * `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.
45
99
  */
46
100
  export function buildOpsSearch(opts, fetchImpl = fetch) {
101
+ const root = (opts.opsUrl ?? `http://127.0.0.1:${opts.opsPort}`).replace(/\/+$/, "");
47
102
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${opts.adminPass}`).toString("base64")}`;
48
103
  return async (table, conditions, getAttributes) => {
49
- const res = await fetchImpl(`http://127.0.0.1:${opts.opsPort}/`, {
104
+ const res = await fetchImpl(`${root}/`, {
50
105
  method: "POST",
106
+ redirect: "error",
51
107
  headers: { "Content-Type": "application/json", Authorization: auth },
52
108
  body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions, get_attributes: getAttributes }),
53
109
  });
54
110
  if (!res.ok)
55
111
  throw new Error(`ops API failed (${res.status})`);
56
- const raw = await res.json();
57
- 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");
58
126
  };
59
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
+ }
60
334
  // ─── flair rem rapid — pure helpers ──────────────────────────────────────────
61
335
  // Extracted for testability, same pattern as validatePromoteOpts /
62
336
  // decideCandidateAction above: the action callback below spawns api() +
@@ -92,26 +366,42 @@ export function candidateIncompleteFlag(claim) {
92
366
  }
93
367
  /**
94
368
  * Classifies a thrown /ReflectMemories execute-mode error for CLI display.
95
- * `api()` throws `Error(responseBodyText)` for non-2xx responses (see api()
96
- * 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:
97
381
  * 503 no-backend: { error: "No generative backend configured..." }
98
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`.
99
386
  * Any other shape (network errors, the 400/403 actor-resolution errors
100
387
  * prompt mode shares) falls back to "other" — printed as a plain message,
101
- * 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.
102
390
  */
103
- export function describeReflectError(message) {
391
+ export function describeReflectError(err) {
392
+ const message = typeof err === "string" ? err : String(err?.message ?? err);
104
393
  try {
105
- const parsed = JSON.parse(message);
394
+ const parsed = JSON.parse(apiErrorRawBody(err) || message);
106
395
  if (parsed && typeof parsed === "object") {
107
396
  if (parsed.error === "distillation_failed") {
108
- 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) };
109
399
  }
110
400
  if (typeof parsed.error === "string" && parsed.error.startsWith("No generative backend configured")) {
111
- return { kind: "no-backend", text: parsed.error };
401
+ return { kind: "no-backend", text: boundErrorText(err, parsed.error) };
112
402
  }
113
403
  if (typeof parsed.error === "string") {
114
- return { kind: "other", text: parsed.error };
404
+ return { kind: "other", text: boundErrorText(err, parsed.error) };
115
405
  }
116
406
  }
117
407
  }
@@ -120,7 +410,42 @@ export function describeReflectError(message) {
120
410
  }
121
411
  return { kind: "other", text: message };
122
412
  }
413
+ /** Print skips, unknown outcomes and errors; errors alone set exit 1, an unknown outcome exit 3. */
414
+ export function summarizeNightlyOutcome(row) {
415
+ const lines = [];
416
+ if (row.errors.length > 0) {
417
+ lines.push("Errors:");
418
+ for (const e of row.errors)
419
+ lines.push(` - ${e}`);
420
+ }
421
+ if (row.skips.length > 0) {
422
+ lines.push("Skips:");
423
+ for (const s of row.skips)
424
+ lines.push(` - ${s}`);
425
+ }
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 };
437
+ }
123
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
+ }
124
449
  function writeRemPauseSentinel() {
125
450
  const dir = dirname(REM_PAUSE_FLAG);
126
451
  if (!existsSync(dir))
@@ -150,7 +475,7 @@ export function register(program) {
150
475
  const maint = await api("POST", "/MemoryMaintenance", {
151
476
  ...(agentId ? { agentId } : {}),
152
477
  dryRun,
153
- });
478
+ }, longRemRequestDeadline("POST", "/MemoryMaintenance"));
154
479
  if (maint.error) {
155
480
  console.error(`Maintenance error: ${maint.error}`);
156
481
  process.exit(1);
@@ -196,6 +521,8 @@ export function register(program) {
196
521
  console.log(`\nDone.${dryRun ? " No changes applied (dry run)." : ""}`);
197
522
  }
198
523
  catch (err) {
524
+ if (err instanceof ApiRequestOutcomeUnknown)
525
+ exitUnknownOutcome(err);
199
526
  console.error(`Error: ${err.message}`);
200
527
  process.exit(1);
201
528
  }
@@ -230,7 +557,7 @@ export function register(program) {
230
557
  if (opts.promptOnly) {
231
558
  // --prompt-only: EXACT pre-#710 behavior — prompt-return mode, unchanged.
232
559
  try {
233
- const result = await api("POST", "/ReflectMemories", body);
560
+ const result = await api("POST", "/ReflectMemories", body, longRemRequestDeadline("POST", "/ReflectMemories"));
234
561
  if (result.error) {
235
562
  console.error(`Reflection error: ${result.error}`);
236
563
  process.exit(1);
@@ -246,6 +573,8 @@ export function register(program) {
246
573
  console.log(" flair memory add --agent <id> --content <insight> --durability persistent --derived-from <source-ids>");
247
574
  }
248
575
  catch (err) {
576
+ if (err instanceof ApiRequestOutcomeUnknown)
577
+ exitUnknownOutcome(err);
249
578
  console.error(`Error: ${err.message}`);
250
579
  process.exit(1);
251
580
  }
@@ -253,7 +582,7 @@ export function register(program) {
253
582
  }
254
583
  // Default: execute mode — distill server-side, stage candidates.
255
584
  try {
256
- const result = await api("POST", "/ReflectMemories", { ...body, execute: true });
585
+ const result = await api("POST", "/ReflectMemories", { ...body, execute: true }, longRemRequestDeadline("POST", "/ReflectMemories"));
257
586
  const candidates = Array.isArray(result.candidates) ? result.candidates : [];
258
587
  console.log(`\nModel: ${result.model ?? "?"}`);
259
588
  console.log(`Candidates: ${result.count ?? candidates.length}`);
@@ -265,7 +594,9 @@ export function register(program) {
265
594
  console.log(`\nreview: flair rem candidates / flair rem promote <id>`);
266
595
  }
267
596
  catch (err) {
268
- const desc = describeReflectError(err.message ?? String(err));
597
+ if (err instanceof ApiRequestOutcomeUnknown)
598
+ exitUnknownOutcome(err);
599
+ const desc = describeReflectError(err);
269
600
  if (desc.kind === "no-backend") {
270
601
  console.error(`Reflection error: ${desc.text}`);
271
602
  console.error(`See docs/rem.md#configuration for how to point Flair at a models: backend.`);
@@ -298,7 +629,7 @@ export function register(program) {
298
629
  const maint = await api("POST", "/MemoryMaintenance", {
299
630
  ...(agentId ? { agentId } : {}),
300
631
  dryRun,
301
- });
632
+ }, longRemRequestDeadline("POST", "/MemoryMaintenance"));
302
633
  if (maint.error) {
303
634
  console.error(`Maintenance error: ${maint.error}`);
304
635
  process.exit(1);
@@ -337,7 +668,7 @@ export function register(program) {
337
668
  const reflect = await api("POST", "/ReflectMemories", {
338
669
  agentId,
339
670
  scope: "all",
340
- });
671
+ }, longRemRequestDeadline("POST", "/ReflectMemories"));
341
672
  if (reflect.error) {
342
673
  console.error(`Reflection error: ${reflect.error}`);
343
674
  process.exit(1);
@@ -356,6 +687,8 @@ export function register(program) {
356
687
  console.log(`\nRestorative cycle complete.${dryRun ? " No changes applied (dry run)." : ""}`);
357
688
  }
358
689
  catch (err) {
690
+ if (err instanceof ApiRequestOutcomeUnknown)
691
+ exitUnknownOutcome(err);
359
692
  console.error(`Error: ${err.message}`);
360
693
  process.exit(1);
361
694
  }
@@ -365,12 +698,11 @@ export function register(program) {
365
698
  // MemoryCandidate table. Empty until the nightly cycle (later slice) starts
366
699
  // populating. Per spec § 5: candidates are NEVER auto-promoted; this command
367
700
  // is the operator's review surface.
368
- rem
701
+ addAdminPassOptions(rem
369
702
  .command("candidates")
370
703
  .description("List staged memory candidates from the FLAIR-NIGHTLY-REM cycle (pending review)")
371
704
  .option("--port <port>", "Harper HTTP port")
372
- .option("--ops-port <port>", "Harper operations API port")
373
- .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)")
374
706
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
375
707
  .option("--agent <id>", "Agent ID (or FLAIR_AGENT_ID env)")
376
708
  .option("--status <s>", "Filter by status: pending | promoted | rejected (default: pending)")
@@ -517,7 +849,7 @@ export function register(program) {
517
849
  return;
518
850
  }
519
851
  // Fetch the candidate
520
- const candidate = await api("GET", `/MemoryCandidate/${encodeURIComponent(candidateId)}`);
852
+ const candidate = await api("GET", `/MemoryCandidate/${encodeRecordId(candidateId)}`);
521
853
  const candidateData = (candidate && !candidate.error) ? candidate : null;
522
854
  const decision = decideCandidateAction(candidateData, "promote");
523
855
  if (!decision.ok) {
@@ -542,7 +874,7 @@ export function register(program) {
542
874
  const sourceIds = Array.isArray(candidate.sourceMemoryIds) ? candidate.sourceMemoryIds : [];
543
875
  for (const sid of sourceIds) {
544
876
  try {
545
- const mem = await api("GET", `/Memory/${encodeURIComponent(String(sid))}`);
877
+ const mem = await api("GET", `/Memory/${encodeRecordId(String(sid))}`);
546
878
  if (mem && !mem.error) {
547
879
  sourceFetches.push({ ok: true, tags: Array.isArray(mem.tags) ? mem.tags : [] });
548
880
  }
@@ -572,7 +904,7 @@ export function register(program) {
572
904
  const decidedAt = new Date().toISOString();
573
905
  // Memory promotion is handled by the server workflow above.
574
906
  const soulId = `${candidate.agentId}-${opts.key}`;
575
- const soulWrite = await api("PUT", `/Soul/${encodeURIComponent(soulId)}`, {
907
+ const soulWrite = await api("PUT", `/Soul/${encodeRecordId(soulId)}`, {
576
908
  id: soulId,
577
909
  agentId: candidate.agentId,
578
910
  key: opts.key,
@@ -588,7 +920,7 @@ export function register(program) {
588
920
  }
589
921
  console.log(`✅ Wrote Soul ${soulId} (key=${opts.key})`);
590
922
  // Update the candidate row
591
- const upd = await api("PUT", `/MemoryCandidate/${encodeURIComponent(candidateId)}`, {
923
+ const upd = await api("PUT", `/MemoryCandidate/${encodeRecordId(candidateId)}`, {
592
924
  ...candidate,
593
925
  status: "promoted",
594
926
  target: opts.to,
@@ -602,6 +934,8 @@ export function register(program) {
602
934
  console.log(`✅ Candidate ${candidateId} marked promoted → ${opts.to}, reviewer=${reviewerId}`);
603
935
  }
604
936
  catch (err) {
937
+ if (err instanceof ApiRequestOutcomeUnknown)
938
+ exitUnknownOutcome(err);
605
939
  console.error(`Error: ${err.message}`);
606
940
  process.exit(1);
607
941
  }
@@ -625,7 +959,7 @@ export function register(program) {
625
959
  }
626
960
  const reviewerId = opts.reviewer || process.env.FLAIR_AGENT_ID || "admin";
627
961
  try {
628
- const candidate = await api("GET", `/MemoryCandidate/${encodeURIComponent(candidateId)}`);
962
+ const candidate = await api("GET", `/MemoryCandidate/${encodeRecordId(candidateId)}`);
629
963
  const candidateData = (candidate && !candidate.error) ? candidate : null;
630
964
  const decision = decideCandidateAction(candidateData, "reject");
631
965
  if (!decision.ok) {
@@ -638,7 +972,7 @@ export function register(program) {
638
972
  process.exit(1);
639
973
  }
640
974
  const decidedAt = new Date().toISOString();
641
- const upd = await api("PUT", `/MemoryCandidate/${encodeURIComponent(candidateId)}`, {
975
+ const upd = await api("PUT", `/MemoryCandidate/${encodeRecordId(candidateId)}`, {
642
976
  ...candidate,
643
977
  status: "rejected",
644
978
  reviewerId,
@@ -653,6 +987,8 @@ export function register(program) {
653
987
  console.log(` Reason: ${opts.reason}`);
654
988
  }
655
989
  catch (err) {
990
+ if (err instanceof ApiRequestOutcomeUnknown)
991
+ exitUnknownOutcome(err);
656
992
  console.error(`Error: ${err.message}`);
657
993
  process.exit(1);
658
994
  }
@@ -678,7 +1014,12 @@ export function register(program) {
678
1014
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
679
1015
  .option("--at <HH:MM>", "Local time to run nightly (default 03:00)", "03:00")
680
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)")
681
1018
  .action(async (opts) => {
1019
+ if (opts.adminPassFile === "") {
1020
+ console.error("Error: --admin-pass-file must not be empty");
1021
+ process.exit(1);
1022
+ }
682
1023
  const agentId = opts.agent || process.env.FLAIR_AGENT_ID;
683
1024
  if (!agentId) {
684
1025
  console.error("Error: --agent or FLAIR_AGENT_ID env required");
@@ -695,7 +1036,7 @@ export function register(program) {
695
1036
  const flairUrl = opts.flairUrl || process.env.FLAIR_URL || `http://127.0.0.1:${port}`;
696
1037
  const { enableScheduler, formatEnableReport } = await import("../rem/scheduler.js");
697
1038
  try {
698
- const r = enableScheduler({ agentId, flairUrl, hour, minute });
1039
+ const r = enableScheduler({ agentId, flairUrl, hour, minute, adminPassFile: opts.adminPassFile });
699
1040
  // formatEnableReport() owns the success-vs-failure decision (flair#850:
700
1041
  // do not print a success headline before activation is known to have
701
1042
  // succeeded) — see src/rem/scheduler.ts for the unit-tested logic.
@@ -755,12 +1096,24 @@ export function register(program) {
755
1096
  process.exit(1);
756
1097
  }
757
1098
  });
758
- remNightly
1099
+ addAdminPassOptions(remNightly
759
1100
  .command("run-once")
760
1101
  .description("Run one nightly cycle now (snapshot + log). Same code path the scheduler will use.")
761
1102
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
762
- .option("--ops-port <port>", "Harper operations API port")
763
- .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
+ })
764
1117
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
765
1118
  .option("--dry-run", "Log the row but skip the snapshot write")
766
1119
  .action(async (opts) => {
@@ -769,12 +1122,36 @@ export function register(program) {
769
1122
  console.error("Error: --agent or FLAIR_AGENT_ID env required");
770
1123
  process.exit(1);
771
1124
  }
772
- const { runNightlyCycle } = await import("../rem/runner.js");
1125
+ const { runNightlyCycle, RunnerLogWriteError, formatPendingCandidates, formatCount, formatAutoPromoted } = await import("../rem/runner.js");
773
1126
  // The runner is agent-authed and cannot reach the ops port itself. When
774
- // admin credentials are available, inject an ops-API `search_by_conditions`
775
- // helper so the pending-candidate count can be sampled; otherwise the count
776
- // is best-effort 0 (the cycle still runs).
777
- 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;
778
1155
  const opsSearch = adminPass
779
1156
  ? buildOpsSearch({ opsPort: resolveOpsPort(opts), adminUser: opts.adminUser, adminPass })
780
1157
  : undefined;
@@ -783,7 +1160,8 @@ export function register(program) {
783
1160
  const result = await runNightlyCycle({
784
1161
  agentId,
785
1162
  flairVersion: __pkgVersion,
786
- apiCall: api,
1163
+ apiCall: agentApiCall,
1164
+ adminApiCall,
787
1165
  opsSearch,
788
1166
  dryRun: !!opts.dryRun,
789
1167
  healthProbe: async (timeoutMs) => {
@@ -807,12 +1185,16 @@ export function register(program) {
807
1185
  if (result.snapshotPath) {
808
1186
  console.log(`Snapshot: ${result.snapshotPath}`);
809
1187
  }
810
- console.log(`Memories: ${row.memoryCount ?? "—"}`);
811
- console.log(`Souls: ${row.soulCount ?? "—"}`);
812
- 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)}`);
813
1191
  if (typeof row.archived === "number" || typeof row.expired === "number") {
814
- console.log(`Archived: ${row.archived ?? "—"}`);
815
- console.log(`Expired: ${row.expired ?? "—"}`);
1192
+ // #1503: `archived` counts validTo-expired and old-session rows the
1193
+ // pass soft-archived; `expired` counts ephemeral rows past their
1194
+ // expiresAt. Label each so "Expired: N, Archived: 0" cannot read as
1195
+ // the same row counted on two axes.
1196
+ console.log(`Archived: ${row.archived ?? "—"} (validTo-expired + old sessions)`);
1197
+ console.log(`Expired: ${row.expired ?? "—"} (ephemeral rows past expiresAt)`);
816
1198
  }
817
1199
  // row.candidates populates when step 5 (distillation) was attempted
818
1200
  // this cycle — see src/rem/runner.ts. Absent when dry-run skipped it.
@@ -825,27 +1207,37 @@ export function register(program) {
825
1207
  if (row.distill.aborted)
826
1208
  console.log(`Aborted: yes — in-flight distillation stopped (flair rem pause)`);
827
1209
  }
828
- // row.autoPromoted populates when step 5b (#1205b-2 ADK auto-promote) ran
829
- // 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).
830
1217
  if (row.autoPromoted) {
831
- console.log(`Auto-promoted: ${row.autoPromoted.promoted} to own memory (${row.autoPromoted.skipped} left pending)`);
1218
+ console.log(formatAutoPromoted(row.autoPromoted));
832
1219
  }
833
- // row.dedup populates when step 6 (instance-wide dedup-cluster stat,
834
- // flair-quality Slice 1c) succeeded this cycle. Absent on dry-run skip
835
- // or a non-fatal failure (see Errors below — e.g. non-admin caller).
836
- if (row.dedup) {
837
- console.log(`Dedup: ${row.dedup.clusterCount} cluster${row.dedup.clusterCount === 1 ? "" : "s"} (${row.dedup.totalMemoriesInClusters} memories, largest ${row.dedup.largestClusterSize})`);
1220
+ // A guard refusal carries null counts and the guard's named state.
1221
+ const dedupRow = row.dedup;
1222
+ if (dedupRow) {
1223
+ if ("embeddingSpace" in dedupRow) {
1224
+ console.log(`Dedup: not computed — embedding space ${dedupRow.embeddingSpace.state} (no new counts were written)`);
1225
+ }
1226
+ else {
1227
+ console.log(`Dedup: ${dedupRow.clusterCount} cluster${dedupRow.clusterCount === 1 ? "" : "s"} (${dedupRow.totalMemoriesInClusters} memories, largest ${dedupRow.largestClusterSize})`);
1228
+ }
838
1229
  }
839
1230
  console.log(`Duration: ${row.durationMs}ms`);
840
1231
  if (result.status === "refused") {
841
1232
  console.log(`\nNote: REM refused to start because /Health could not be served.`);
842
1233
  console.log(`Restore /Health before retrying, or \`flair rem pause\` to stop the scheduler.`);
843
1234
  }
844
- if (row.errors.length > 0) {
845
- console.log(`Errors:`);
846
- for (const e of row.errors)
847
- console.log(` - ${e}`);
848
- process.exit(1);
1235
+ if (row.errors.length > 0 || row.skips.length > 0 || (row.outcomeUnknown?.length ?? 0) > 0) {
1236
+ const outcome = summarizeNightlyOutcome(row);
1237
+ for (const line of outcome.lines)
1238
+ console.log(line);
1239
+ if (outcome.exitCode !== 0)
1240
+ process.exit(outcome.exitCode);
849
1241
  }
850
1242
  if (result.status === "paused") {
851
1243
  console.log(`\nNote: REM is paused (sentinel ~/.flair/rem.paused or FLAIR_REM_PAUSE env).`);
@@ -853,6 +1245,14 @@ export function register(program) {
853
1245
  }
854
1246
  }
855
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
+ }
856
1256
  console.error(`Error: ${err.message}`);
857
1257
  process.exit(1);
858
1258
  }
@@ -910,7 +1310,7 @@ export function register(program) {
910
1310
  .description("Restore from a REM snapshot (inspect by default; --apply rewinds Harper state)")
911
1311
  .option("--agent <id>", "Agent id (or FLAIR_AGENT_ID env)")
912
1312
  .option("--target <dir>", "Directory to extract into (default: <snapshot>.restored, only used without --apply)")
913
- .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)")
914
1314
  .option("--apply", "Live replay: rewind Harper state to the snapshot (irreversible without the pre-restore snapshot)")
915
1315
  .action(async (date, opts) => {
916
1316
  const { listSnapshots, extractSnapshot } = await import("../rem/snapshot.js");
@@ -943,17 +1343,28 @@ export function register(program) {
943
1343
  const match = matches[0];
944
1344
  // --apply path: live replay via src/rem/restore.ts
945
1345
  if (opts.apply) {
946
- const { applySnapshot } = await import("../rem/restore.js");
947
- applyAdminPassFile(opts);
948
- const restoreBase = process.env.FLAIR_URL || `http://127.0.0.1:${resolveHttpPort({})}`;
949
- // Candidates are only reachable through the ops port (Harper has no
950
- // REST search_by_conditions route), so the dry-run candidate count
951
- // needs admin creds too. Dry-run treats credential resolution as
952
- // best-effort — a plan-only command must not fail on a bad credential
953
- // 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.
954
1365
  let adminPass;
955
1366
  try {
956
- adminPass = resolveLocalAdminPass(opts.adminPass, !isLocalBase(restoreBase));
1367
+ adminPass = resolveLocalAdminPass(opts.adminPass, !isLocalBase(restoreTarget.baseUrl));
957
1368
  }
958
1369
  catch (err) {
959
1370
  if (!opts.dryRun)
@@ -961,25 +1372,40 @@ export function register(program) {
961
1372
  adminPass = undefined;
962
1373
  }
963
1374
  if (!opts.dryRun && !adminPass) {
964
- 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) ") +
965
1378
  "(Soul rewrite is operator-only; an agent key is refused).");
966
1379
  process.exit(1);
967
1380
  }
968
- const opsSearch = adminPass
969
- ? buildOpsSearch({ opsPort: resolveOpsPort(opts), adminUser: opts.adminUser, adminPass })
970
- : undefined;
971
- const soulApiCall = adminPass
972
- ? (method, path, body) => api(method, path, body, { explicitAdminPass: adminPass, adminUser: opts.adminUser, agentId: null })
973
- : 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;
974
1400
  try {
975
1401
  const result = await applySnapshot({
976
1402
  agentId,
977
1403
  snapshotPath: match.path,
978
1404
  flairVersion: __pkgVersion,
979
- apiCall: api,
980
- opsSearch,
1405
+ apiCall: targetApi,
981
1406
  soulApiCall,
982
1407
  dryRun: !!opts.dryRun,
1408
+ listCandidates: !!adminPass,
983
1409
  });
984
1410
  const verb = opts.dryRun ? "(dry-run) would" : "";
985
1411
  console.log(`${opts.dryRun ? "(dry-run) " : ""}flair rem restore --apply${opts.dryRun ? "" : ""}`);
@@ -991,6 +1417,32 @@ export function register(program) {
991
1417
  }
992
1418
  console.log(` Deleted: ${result.deleted.memories} memories, ${result.deleted.souls} souls, ${result.deleted.candidates} candidates`);
993
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
+ }
994
1446
  if (result.errors.length > 0) {
995
1447
  console.log(` Errors:`);
996
1448
  for (const e of result.errors)
@@ -998,6 +1450,11 @@ export function register(program) {
998
1450
  }
999
1451
  if (result.status === "failed")
1000
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);
1001
1458
  }
1002
1459
  catch (err) {
1003
1460
  console.error(`Error: ${err.message}`);