@tpsdev-ai/flair 0.62.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -58,6 +58,7 @@ import { dirname, resolve } from "node:path";
58
58
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
59
59
  import { createSnapshot } from "./snapshot.js";
60
60
  import { resolveHome } from "../lib/home.js";
61
+ import { ApiRequestOutcomeUnknown, apiErrorRawBody, boundErrorText } from "../lib/auth-resolve.js";
61
62
  export const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
62
63
  export const REM_NIGHTLY_LOG = resolve(resolveHome(), ".flair", "logs", "rem-nightly.jsonl");
63
64
  // ─── ADK per-tag distillation (#1205b-1) ─────────────────────────────────────
@@ -197,6 +198,36 @@ export async function runHealthPreflight(apiCall, opts = {}) {
197
198
  export function formatHealthRefuseMessage(result, timeoutMs = DEFAULT_HEALTH_PREFLIGHT_MS) {
198
199
  return `GET /Health could not be served within ${timeoutMs}ms (${result.error ?? "unknown error"}). Refusing to start REM so this run cannot take the instance down. Restore /Health, or \`flair rem pause\` to keep the scheduler from retrying.`;
199
200
  }
201
+ export const PENDING_NO_ADMIN_REASON = "no admin credential for the operations API";
202
+ /** A count line's value: the count, `unknown (<reason>)`, or `—` when not reached. */
203
+ export function formatCount(count) {
204
+ if (count === undefined)
205
+ return "—";
206
+ return typeof count === "number" ? String(count) : `unknown (${count.reason})`;
207
+ }
208
+ /** The `Pending:` value run-once prints. */
209
+ export function formatPendingCandidates(count) {
210
+ return formatCount(count);
211
+ }
212
+ /**
213
+ * The `Auto-promoted:` line run-once prints for the auto-promote step's
214
+ * outcome. `skipped` is the server's `skipped` list. flair#2714: incomplete
215
+ * promotions (Memory written and stamped, candidate update threw, candidate
216
+ * read back pending) and unconfirmed ones (the same throw, but the read did
217
+ * not confirm the promotion on this row) are named on the line, never folded
218
+ * into the promoted or skipped counts. A log row written before those fields
219
+ * existed reads as 0.
220
+ */
221
+ export function formatAutoPromoted(outcome) {
222
+ let line = `Auto-promoted: ${outcome.promoted} to own memory (${outcome.skipped} skipped)`;
223
+ const incomplete = outcome.incomplete ?? 0;
224
+ const unconfirmed = outcome.unconfirmed ?? 0;
225
+ if (incomplete > 0)
226
+ line += `; ${incomplete} incomplete (memory written, candidate update threw, candidate read back pending)`;
227
+ if (unconfirmed > 0)
228
+ line += `; ${unconfirmed} unconfirmed (memory written, candidate update threw, promotion on this row not confirmed)`;
229
+ return line;
230
+ }
200
231
  function readPauseSentinel(path) {
201
232
  try {
202
233
  const contents = readFileSync(path, "utf-8");
@@ -207,11 +238,28 @@ function readPauseSentinel(path) {
207
238
  return false;
208
239
  }
209
240
  }
241
+ /**
242
+ * A failed append of the nightly audit row. The row is carried so the CLI can
243
+ * still report an unknown write outcome (exit 3) even though the log failed.
244
+ */
245
+ export class RunnerLogWriteError extends Error {
246
+ row;
247
+ constructor(row, cause) {
248
+ super(`could not append the nightly log row: ${cause?.message ?? String(cause)}`);
249
+ this.name = "RunnerLogWriteError";
250
+ this.row = row;
251
+ }
252
+ }
210
253
  function appendLogRow(logPath, row) {
211
254
  const dir = dirname(logPath);
212
- if (!existsSync(dir))
213
- mkdirSync(dir, { recursive: true, mode: 0o700 });
214
- appendFileSync(logPath, JSON.stringify(row) + "\n", { mode: 0o600 });
255
+ try {
256
+ if (!existsSync(dir))
257
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
258
+ appendFileSync(logPath, JSON.stringify(row) + "\n", { mode: 0o600 });
259
+ }
260
+ catch (err) {
261
+ throw new RunnerLogWriteError(row, err);
262
+ }
215
263
  }
216
264
  /**
217
265
  * Coerces a Harper REST list response into a flat array. The /Memory and
@@ -230,22 +278,50 @@ function asArray(raw) {
230
278
  }
231
279
  return [];
232
280
  }
281
+ /**
282
+ * A Memory or Soul read's rows. An unrecognised body is a failed read, not an
283
+ * empty result: `asArray` would report it as 0, which reads as an empty store.
284
+ */
285
+ function rowsFromRead(raw, label) {
286
+ if (Array.isArray(raw))
287
+ return raw;
288
+ if (raw && typeof raw === "object") {
289
+ const obj = raw;
290
+ if (Array.isArray(obj.results))
291
+ return obj.results;
292
+ if (Array.isArray(obj.items))
293
+ return obj.items;
294
+ }
295
+ throw new Error(`${label} returned an unexpected response shape`);
296
+ }
233
297
  /**
234
298
  * Best-effort extraction of a readable message out of a thrown API error.
235
- * `apiCall` implementations (see `api()` in src/cli.ts) throw
236
- * `Error(responseBodyText)` for non-2xx HTTP responses — /ReflectMemories's
237
- * 503 (no backend configured) and 502 (distillation_failed) bodies are JSON
238
- * `{ error: string, detail?: string }`. Unwraps that shape into a single
239
- * string so distinct failure modes read distinctly in the audit log instead
240
- * of as a raw JSON blob; falls back to the raw input for network errors or
241
- * any other shape.
299
+ * `api()` (src/cli.ts) throws an ApiHttpError for a non-2xx HTTP response
300
+ * (flair#2764). When that error was built from a non-empty response body
301
+ * (ApiHttpError.fromResponse), its unredacted text is parsed here
302
+ * (apiErrorRawBody); otherwise (the credential-less 403 and a refused redirect
303
+ * carry only a message, as does any other error) the message is parsed
304
+ * instead. /ReflectMemories's 503 (no backend configured) and 502
305
+ * (distillation_failed) bodies are JSON `{ error: string, detail?: string }`.
306
+ * A JSON object with a string `error` becomes one bounded line through
307
+ * boundErrorText, which redacts the credential values read from the request's
308
+ * Authorization header (credentialsInHeader) from the server's text within the
309
+ * scope stated on ApiHttpError, or withholds that text when the header's
310
+ * credential could not be read and the response text was non-empty, even when
311
+ * the text derived from it is empty (a prefix added when the line is written
312
+ * is outside the scope):
313
+ * `error: detail` when `detail` is a non-empty string and `error` alone
314
+ * otherwise, so distinct failure modes read distinctly in the audit log
315
+ * instead of as a raw JSON blob. Text that is not JSON, or JSON without a
316
+ * string `error`, falls back to the error's message.
242
317
  */
243
318
  function describeApiError(err) {
244
319
  const message = typeof err === "string" ? err : err?.message ?? String(err);
245
320
  try {
246
- const parsed = JSON.parse(message);
321
+ const parsed = JSON.parse(apiErrorRawBody(err) || message);
247
322
  if (parsed && typeof parsed === "object" && typeof parsed.error === "string") {
248
- return parsed.detail ? `${parsed.error}: ${parsed.detail}` : parsed.error;
323
+ const detail = typeof parsed.detail === "string" ? parsed.detail : "";
324
+ return boundErrorText(err, detail ? `${parsed.error}: ${detail}` : parsed.error);
249
325
  }
250
326
  }
251
327
  catch {
@@ -254,7 +330,7 @@ function describeApiError(err) {
254
330
  return message;
255
331
  }
256
332
  function structuredApiError(err) {
257
- const message = typeof err === "string" ? err : err?.message;
333
+ const message = apiErrorRawBody(err) || (typeof err === "string" ? err : err?.message);
258
334
  if (typeof message !== "string")
259
335
  return null;
260
336
  try {
@@ -305,22 +381,20 @@ export function hasAdkUserTags(memories, agentId) {
305
381
  *
306
382
  * Uses the ops-API `search_by_conditions` convention (admin-authed) via the
307
383
  * injected `opsSearch` helper — the same shape `flair rem candidates` uses.
308
- * Returns 0 when no `opsSearch` is available (the agent-authed runner carries
309
- * no admin creds) or on any error — the runner should not fail the cycle just
310
- * because the candidate count couldn't be sampled.
384
+ * A failed query returns `unknown` with the error (flair#2680).
311
385
  */
312
386
  async function fetchPendingCandidateCount(opsSearch, agentId) {
313
- if (!opsSearch)
314
- return 0;
315
387
  try {
316
388
  const rows = await opsSearch("MemoryCandidate", [
317
389
  { search_attribute: "agentId", search_type: "equals", search_value: agentId },
318
390
  { search_attribute: "status", search_type: "equals", search_value: "pending" },
319
391
  ], ["id"]);
392
+ if (!Array.isArray(rows))
393
+ return { state: "unknown", reason: "ops API returned an unexpected response shape" };
320
394
  return rows.length;
321
395
  }
322
- catch {
323
- return 0;
396
+ catch (err) {
397
+ return { state: "unknown", reason: err?.message || String(err) };
324
398
  }
325
399
  }
326
400
  /**
@@ -483,6 +557,9 @@ export async function runNightlyCycle(opts) {
483
557
  return { status: "paused", logRow: row };
484
558
  }
485
559
  const errors = [];
560
+ // A deadline expiry on a write can leave an effect behind: it is carried
561
+ // apart from `errors` and makes the cycle `unresolved`.
562
+ const outcomeUnknown = [];
486
563
  // flair#924 defect 1: deliberate skips (no backend / idle ADK / operator
487
564
  // pause) land here, not in `errors`. Dedup so a per-tag or per-stage repeat
488
565
  // of the same reason is recorded once.
@@ -511,38 +588,71 @@ export async function runNightlyCycle(opts) {
511
588
  let snapshotPath;
512
589
  let memoryCount = 0;
513
590
  let soulCount = 0;
514
- let pendingCandidates = 0;
591
+ let pendingCandidates;
515
592
  // #1205b-1: the memories fetched here (for the snapshot) are reused by the
516
593
  // step-5 tag enumeration — no second fetch. Hoisted so step 5 can read them.
517
594
  let fetchedMemories = [];
595
+ let memories;
596
+ let souls;
597
+ let readOrSnapshotFailed = false;
598
+ // The two reads are independent: when one fails the other still reports its
599
+ // exact count, and each failed read is named under `Errors:`.
518
600
  try {
519
- // Fetch agent data
520
- const memoriesRaw = await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`);
521
- const memories = asArray(memoriesRaw);
522
- fetchedMemories = memories;
601
+ memories = rowsFromRead(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`), "GET /Memory");
523
602
  memoryCount = memories.length;
524
- const soulRaw = await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`);
525
- const souls = asArray(soulRaw);
603
+ }
604
+ catch (err) {
605
+ const reason = err?.message ?? String(err);
606
+ memoryCount = { state: "unknown", reason };
607
+ errors.push(`memory-count: ${reason}`);
608
+ readOrSnapshotFailed = true;
609
+ }
610
+ try {
611
+ souls = rowsFromRead(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`), "GET /Soul");
526
612
  soulCount = souls.length;
527
- // For the snapshot's soul.json: keep the full multi-row shape if there
528
- // are multiple souls (different keys), or unwrap a single-row response.
529
- const soulForSnapshot = souls.length === 1 ? souls[0] : souls.length > 1 ? souls : null;
530
- pendingCandidates = await fetchPendingCandidateCount(opts.opsSearch, opts.agentId);
531
- if (!opts.dryRun) {
532
- const created = await createSnapshot({
533
- agentId: opts.agentId,
534
- flairVersion: opts.flairVersion,
535
- memories,
536
- soul: soulForSnapshot,
537
- pendingCandidateCount: pendingCandidates,
538
- rootOverride: opts.snapshotRoot,
539
- nowOverride: opts.nowOverride,
540
- });
541
- snapshotPath = created.path;
542
- }
543
613
  }
544
614
  catch (err) {
545
- errors.push(`snapshot: ${err?.message ?? String(err)}`);
615
+ const reason = err?.message ?? String(err);
616
+ soulCount = { state: "unknown", reason };
617
+ errors.push(`soul-count: ${reason}`);
618
+ readOrSnapshotFailed = true;
619
+ }
620
+ fetchedMemories = memories ?? [];
621
+ if (memories && souls) {
622
+ try {
623
+ // For the snapshot's soul.json: keep the full multi-row shape if there
624
+ // are multiple souls (different keys), or unwrap a single-row response.
625
+ const soulForSnapshot = souls.length === 1 ? souls[0] : souls.length > 1 ? souls : null;
626
+ // flair#2680: a failed count is a failed check (an `errors` entry), not 0.
627
+ // With no admin credential no query runs; when the cycle reaches this step
628
+ // the count is reported unknown.
629
+ if (opts.opsSearch) {
630
+ pendingCandidates = await fetchPendingCandidateCount(opts.opsSearch, opts.agentId);
631
+ if (typeof pendingCandidates !== "number")
632
+ errors.push(`pending-count: ${pendingCandidates.reason}`);
633
+ }
634
+ else {
635
+ pendingCandidates = { state: "unknown", reason: PENDING_NO_ADMIN_REASON };
636
+ }
637
+ if (!opts.dryRun) {
638
+ const created = await createSnapshot({
639
+ agentId: opts.agentId,
640
+ flairVersion: opts.flairVersion,
641
+ memories,
642
+ soul: soulForSnapshot,
643
+ pendingCandidateCount: typeof pendingCandidates === "number" ? pendingCandidates : null,
644
+ rootOverride: opts.snapshotRoot,
645
+ nowOverride: opts.nowOverride,
646
+ });
647
+ snapshotPath = created.path;
648
+ }
649
+ }
650
+ catch (err) {
651
+ errors.push(`snapshot: ${err?.message ?? String(err)}`);
652
+ readOrSnapshotFailed = true;
653
+ }
654
+ }
655
+ if (readOrSnapshotFailed) {
546
656
  const row = {
547
657
  ...baseRow,
548
658
  status: "failed",
@@ -564,10 +674,12 @@ export async function runNightlyCycle(opts) {
564
674
  let expired = 0;
565
675
  let sliceLabel = "2-maintenance";
566
676
  try {
567
- const maintRaw = await opts.apiCall("POST", "/MemoryMaintenance", {
568
- agentId: opts.agentId,
569
- dryRun: opts.dryRun ?? false,
570
- });
677
+ // Only an id is sent: an empty or absent agentId is omitted rather than
678
+ // sent as an empty string.
679
+ const maintBody = { dryRun: opts.dryRun ?? false };
680
+ if (opts.agentId)
681
+ maintBody.agentId = opts.agentId;
682
+ const maintRaw = await opts.apiCall("POST", "/MemoryMaintenance", maintBody);
571
683
  if (maintRaw && typeof maintRaw === "object") {
572
684
  const obj = maintRaw;
573
685
  if (obj.error) {
@@ -579,6 +691,26 @@ export async function runNightlyCycle(opts) {
579
691
  }
580
692
  }
581
693
  catch (err) {
694
+ if (err instanceof ApiRequestOutcomeUnknown) {
695
+ // The maintenance write may have landed. Do not continue writing state
696
+ // whose order depended on it, and do not report a plain failure.
697
+ outcomeUnknown.push(`maintenance: ${err.message}`);
698
+ const row = {
699
+ ...baseRow,
700
+ slice: sliceLabel,
701
+ status: "unresolved",
702
+ snapshotPath,
703
+ memoryCount,
704
+ soulCount,
705
+ pendingCandidates,
706
+ durationMs: Date.now() - startedMs,
707
+ errors,
708
+ outcomeUnknown,
709
+ skips,
710
+ };
711
+ appendLogRow(logPath, row);
712
+ return { status: "unresolved", logRow: row, snapshotPath };
713
+ }
582
714
  errors.push(`maintenance: ${err?.message ?? String(err)}`);
583
715
  const row = {
584
716
  ...baseRow,
@@ -691,6 +823,11 @@ export async function runNightlyCycle(opts) {
691
823
  }
692
824
  }
693
825
  catch (err) {
826
+ if (err instanceof ApiRequestOutcomeUnknown) {
827
+ // May have staged candidates; reported apart from `errors`.
828
+ outcomeUnknown.push(`distillation[${tag}]: ${describeApiError(err)}`);
829
+ continue;
830
+ }
694
831
  if (isNoBackendConfigured(err)) {
695
832
  pushSkipOnce(NO_BACKEND_SKIP);
696
833
  break;
@@ -700,7 +837,7 @@ export async function runNightlyCycle(opts) {
700
837
  distillAborted = true;
701
838
  break;
702
839
  }
703
- errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
840
+ errors.push(`distillation[${tag}]: ${describeApiError(err)}`);
704
841
  }
705
842
  }
706
843
  // `candidates` is defined (even if empty) whenever distillation was
@@ -740,7 +877,10 @@ export async function runNightlyCycle(opts) {
740
877
  // 3). Zero partial candidates is guaranteed server-side (all-or-
741
878
  // nothing staging in /ReflectMemories). rem_aborted IS fatal to the
742
879
  // rest of this cycle (no auto-promote / dedup).
743
- if (isNoBackendConfigured(err)) {
880
+ if (err instanceof ApiRequestOutcomeUnknown) {
881
+ outcomeUnknown.push(`distillation: ${describeApiError(err)}`);
882
+ }
883
+ else if (isNoBackendConfigured(err)) {
744
884
  pushSkipOnce(NO_BACKEND_SKIP);
745
885
  }
746
886
  else {
@@ -749,7 +889,7 @@ export async function runNightlyCycle(opts) {
749
889
  distillAborted = true;
750
890
  }
751
891
  else
752
- errors.push(`distillation: ${describeApiError(err?.message ?? err)}`);
892
+ errors.push(`distillation: ${describeApiError(err)}`);
753
893
  }
754
894
  }
755
895
  }
@@ -810,6 +950,11 @@ export async function runNightlyCycle(opts) {
810
950
  }
811
951
  }
812
952
  catch (err) {
953
+ if (err instanceof ApiRequestOutcomeUnknown) {
954
+ // May have staged candidates; reported apart from `errors`.
955
+ outcomeUnknown.push(`distillation[${tag}]: ${describeApiError(err)}`);
956
+ continue;
957
+ }
813
958
  if (isNoBackendConfigured(err)) {
814
959
  pushSkipOnce(NO_BACKEND_SKIP);
815
960
  break;
@@ -819,7 +964,7 @@ export async function runNightlyCycle(opts) {
819
964
  distillAborted = true;
820
965
  break;
821
966
  }
822
- errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
967
+ errors.push(`distillation[${tag}]: ${describeApiError(err)}`);
823
968
  }
824
969
  }
825
970
  continuitySessions = distilled;
@@ -851,11 +996,21 @@ export async function runNightlyCycle(opts) {
851
996
  else {
852
997
  const promotedCount = typeof obj.count === "number" ? obj.count : asArray(obj.promoted).length;
853
998
  const skippedCount = asArray(obj.skipped).length;
854
- autoPromoted = { promoted: promotedCount, skipped: skippedCount };
999
+ // flair#2714: a promotion whose candidate update threw is reported
1000
+ // apart from `promoted`; carry its counts instead of dropping them.
1001
+ const incompleteCount = asArray(obj.incomplete).length;
1002
+ const unconfirmedCount = asArray(obj.unconfirmed).length;
1003
+ autoPromoted = { promoted: promotedCount, skipped: skippedCount, incomplete: incompleteCount, unconfirmed: unconfirmedCount };
855
1004
  }
856
1005
  }
857
1006
  catch (err) {
858
- errors.push(`auto-promote: ${describeApiError(err?.message ?? err)}`);
1007
+ if (err instanceof ApiRequestOutcomeUnknown) {
1008
+ // The sweep may have promoted candidates; its outcome is unknown.
1009
+ outcomeUnknown.push(`auto-promote: ${describeApiError(err)}`);
1010
+ }
1011
+ else {
1012
+ errors.push(`auto-promote: ${describeApiError(err)}`);
1013
+ }
859
1014
  }
860
1015
  }
861
1016
  }
@@ -878,7 +1033,7 @@ export async function runNightlyCycle(opts) {
878
1033
  let dedup;
879
1034
  if (!opts.dryRun && !distillAborted) {
880
1035
  try {
881
- const dedupRaw = await opts.apiCall("POST", "/MemoryDedupStats", {});
1036
+ const dedupRaw = await (opts.adminApiCall ?? opts.apiCall)("POST", "/MemoryDedupStats", {});
882
1037
  const obj = (dedupRaw && typeof dedupRaw === "object") ? dedupRaw : {};
883
1038
  if (obj.error) {
884
1039
  errors.push(`dedup: ${describeApiError(obj.error)}`);
@@ -925,7 +1080,13 @@ export async function runNightlyCycle(opts) {
925
1080
  }
926
1081
  }
927
1082
  catch (err) {
928
- errors.push(`dedup: ${describeApiError(err?.message ?? err)}`);
1083
+ if (err instanceof ApiRequestOutcomeUnknown) {
1084
+ // The stat write may have persisted; its outcome is unknown.
1085
+ outcomeUnknown.push(`dedup: ${describeApiError(err)}`);
1086
+ }
1087
+ else {
1088
+ errors.push(`dedup: ${describeApiError(err)}`);
1089
+ }
929
1090
  }
930
1091
  }
931
1092
  // Step 7: log
@@ -940,7 +1101,7 @@ export async function runNightlyCycle(opts) {
940
1101
  const row = {
941
1102
  ...baseRow,
942
1103
  slice: sliceLabel,
943
- status: errors.length > 0 ? "failed" : opts.dryRun ? "dry-run" : "completed",
1104
+ status: outcomeUnknown.length > 0 ? "unresolved" : errors.length > 0 ? "failed" : opts.dryRun ? "dry-run" : "completed",
944
1105
  dryRun: opts.dryRun || undefined,
945
1106
  snapshotPath,
946
1107
  memoryCount,
@@ -955,8 +1116,9 @@ export async function runNightlyCycle(opts) {
955
1116
  dedup,
956
1117
  durationMs: Date.now() - startedMs,
957
1118
  errors,
1119
+ outcomeUnknown: outcomeUnknown.length > 0 ? outcomeUnknown : undefined,
958
1120
  skips,
959
- distilledAt: distillRan && !distillAborted && errors.length === 0 && skips.length === 0 ? baseRow.runAt : undefined,
1121
+ distilledAt: distillRan && !distillAborted && errors.length === 0 && outcomeUnknown.length === 0 && skips.length === 0 ? baseRow.runAt : undefined,
960
1122
  // `consolidated` remains undefined — this runner has no consolidation
961
1123
  // step; it's reserved for a future slice that adds one.
962
1124
  };
@@ -14,7 +14,7 @@
14
14
  * invokes `flair rem nightly run-once`, the runner module does the work.
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
- import { resolve, dirname } from "node:path";
17
+ import { resolve, dirname, join } from "node:path";
18
18
  import { spawn } from "node:child_process";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { escapeXml } from "../lib/xml-escape.js";
@@ -93,16 +93,26 @@ function validateSchedule(hour, minute) {
93
93
  throw new Error(`minute must be an integer 0-59, got ${minute}`);
94
94
  }
95
95
  }
96
+ /**
97
+ * Quote a value as ONE POSIX shell word. Embedded single quotes are closed,
98
+ * escaped, and reopened, so the shell reads the value literally and never
99
+ * interprets `$()`, backticks, or quotes inside it.
100
+ */
101
+ export function quoteShimArg(value) {
102
+ return `'${value.replace(/'/g, "'\\''")}'`;
103
+ }
96
104
  function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
97
105
  validateSchedule(opts.hour, opts.minute);
98
106
  if (!/^[a-zA-Z0-9_-]+$/.test(opts.agentId)) {
99
107
  throw new Error(`invalid agent id: ${opts.agentId}`);
100
108
  }
109
+ const home = opts.homeOverride ?? resolveHome();
101
110
  return {
102
111
  FLAIR_BIN: flairBin,
103
112
  NODE_BIN: nodeBin,
104
113
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? resolveHome(),
114
+ ADMIN_PASS_FILE: resolve(opts.adminPassFile ?? join(home, ".flair", "admin-pass")),
115
+ HOME: home,
106
116
  AGENT_ID: opts.agentId,
107
117
  FLAIR_URL: opts.flairUrl,
108
118
  HOUR: String(opts.hour),
@@ -369,8 +379,15 @@ export function enableScheduler(opts) {
369
379
  `\`flair rem nightly enable\`.`);
370
380
  }
371
381
  const stderrLogPath = resolve(logsDir, "rem-nightly.stderr.log");
372
- // 1. Deploy the shim (always — both platforms invoke it).
373
- const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), subs);
382
+ // 1. Deploy the shim (always — both platforms invoke it). Every path passed
383
+ // to the command is one POSIX single-quoted argument; none is double-quoted,
384
+ // so shell syntax inside a path stays literal.
385
+ const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), {
386
+ ...subs,
387
+ NODE_BIN: quoteShimArg(subs.NODE_BIN),
388
+ FLAIR_BIN: quoteShimArg(subs.FLAIR_BIN),
389
+ ADMIN_PASS_FILE: quoteShimArg(subs.ADMIN_PASS_FILE),
390
+ });
374
391
  writeFileWithDir(shimPath, shimContents, 0o700);
375
392
  chmodSync(shimPath, 0o700);
376
393
  // 2. Write the scheduler entry.