@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Dependency-free credential redaction (flair#2067).
3
+ *
4
+ * Extracted verbatim from the pre-compaction record's redactor
5
+ * (./precompact.ts) so a second consumer — the PreToolUse action-recall cache,
6
+ * which stores memory excerpts on local disk — redacts with the SAME patterns
7
+ * rather than a second, drifting copy. This module imports nothing: it must be
8
+ * safe to load in a Bun entry point that has no client, no key and no network
9
+ * (./action-recall-hook.ts).
10
+ *
11
+ * THE LINE-BREAK SET. An Authorization-style value is redacted up to the first
12
+ * character of the set below and no further.
13
+ */
14
+ /** What a redacted secret is replaced with. */
15
+ export const REDACTED = "[redacted]";
16
+ /**
17
+ * Authorization-style values, redacted WHOLE: everything after the label or
18
+ * scheme word through the end of its line, whatever its characters (a
19
+ * credential can be any length and alphabet, and a scheme like Digest carries
20
+ * quoted parameters). The line ends at the first character of the line-break
21
+ * set below. The label or scheme word and one space stay; a value that is
22
+ * already exactly the placeholder is left alone, so redacting twice changes
23
+ * nothing. Applied before SECRET_PATTERNS:
24
+ * - an `Authorization` / `Proxy-Authorization` label (any case, then an
25
+ * optional quote and `:` or `=`), whatever scheme follows;
26
+ * - the scheme word `Bearer` (any case);
27
+ * - the scheme word `Basic` or `BASIC`. The lower-case word "basic" is
28
+ * ordinary English and is left alone unless an Authorization label
29
+ * precedes it.
30
+ * Each pattern is a literal word, a bounded or single-class run, then the rest
31
+ * of one line, so it stays linear on long input.
32
+ */
33
+ export const AUTHORIZATION_PATTERNS = [
34
+ /\b((?:proxy-)?authorization["']?[ \t]*[:=])([^\n\r\v\f\u0085\u2028\u2029]*)/gi,
35
+ /\b(bearer)[ \t]+([^\n\r\v\f\u0085\u2028\u2029]*)/gi,
36
+ /\b(Basic|BASIC)[ \t]+([^\n\r\v\f\u0085\u2028\u2029]*)/g,
37
+ ];
38
+ /**
39
+ * Credential shapes replaced in free text before it is stored or shown. They
40
+ * cover the families the auto-capture filter in packages/pi-flair detects
41
+ * (sk-, ghp_, pat_, Bearer, PEM private keys) and more. Best effort by design:
42
+ * a secret with no recognizable shape (a bare password in prose, a random
43
+ * string with no prefix) is NOT recognized. Every quantifier is bounded or
44
+ * runs over a single character class, so no pattern backtracks badly on long
45
+ * input.
46
+ */
47
+ export const SECRET_PATTERNS = [
48
+ // PEM private key blocks, whole, or to the end of the text when unterminated.
49
+ [/-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----([\s\S]*?)(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----|$)/g, REDACTED],
50
+ // Credentials in a URL's userinfo: scheme://user:password@host.
51
+ [/\b([a-z][a-z0-9+.-]{0,20}:\/\/)[^\s/:@]{1,256}:[^\s/@]{1,256}@/gi, `$1${REDACTED}@`],
52
+ // name=value / name: value where the name says it is a credential.
53
+ [
54
+ /\b([A-Za-z0-9_.-]{0,40}(?:password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|private[_-]?key|credential)[A-Za-z0-9_.-]{0,40})(\s{0,4}[:=]\s{0,4})("[^"\n]{1,512}"|'[^'\n]{1,512}'|[^\s"',;]{1,512})/gi,
55
+ `$1$2${REDACTED}`,
56
+ ],
57
+ // Token shapes with a recognizable prefix.
58
+ [/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}/g, REDACTED], // OpenAI / Anthropic style keys
59
+ [/\bgh[pousr]_[A-Za-z0-9]{20,}/g, REDACTED], // GitHub tokens
60
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, REDACTED], // GitHub fine-grained PATs
61
+ [/\bglpat-[A-Za-z0-9_-]{20,}/g, REDACTED], // GitLab PATs
62
+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, REDACTED], // Slack tokens
63
+ [/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, REDACTED], // AWS access key ids
64
+ [/\bAIza[A-Za-z0-9_-]{30,}/g, REDACTED], // Google API keys
65
+ [/\bnpm_[A-Za-z0-9]{36}\b/g, REDACTED], // npm tokens
66
+ [/\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g, REDACTED], // Stripe secret/restricted keys
67
+ [/\bhf_[A-Za-z0-9]{20,}/g, REDACTED], // Hugging Face tokens
68
+ [/\bgsk_[A-Za-z0-9]{20,}/g, REDACTED], // Groq keys
69
+ [/\bpypi-[A-Za-z0-9_-]{16,}/g, REDACTED], // PyPI tokens
70
+ [/\bpat_[A-Za-z0-9_.-]{16,}/g, REDACTED], // generic PATs (pi-flair's pattern)
71
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, REDACTED], // JWTs
72
+ ];
73
+ /** Replace every recognized credential shape in `text` with REDACTED. */
74
+ export function redactSecrets(text) {
75
+ return redactSecretsWithCount(text).text;
76
+ }
77
+ /**
78
+ * Expand a `$1`-style replacement against a `String.replace` callback's
79
+ * arguments (match, p1, p2, ...). The SECRET_PATTERNS replacements use only
80
+ * `$1`/`$2`, so this reproduces their string-replacement form exactly.
81
+ */
82
+ function expandReplacement(replacement, args) {
83
+ return replacement.replace(/\$(\d)/g, (_whole, digit) => String(args[Number(digit)] ?? ""));
84
+ }
85
+ /**
86
+ * The same redaction as `redactSecrets`, plus the number of matched values
87
+ * whose replacement differs from the matched text (flair#2407). A match that
88
+ * is already in redacted form (e.g. `API_KEY=[redacted]`) is left as it is and
89
+ * not counted. The server's explicit-Memory write paths use this so the write
90
+ * response can report how many values were replaced.
91
+ */
92
+ export function redactSecretsWithCount(text) {
93
+ let out = text;
94
+ let count = 0;
95
+ for (const pattern of AUTHORIZATION_PATTERNS) {
96
+ out = out.replace(pattern, (whole, head, value) => {
97
+ const v = value.trim();
98
+ const replaced = v === "" || v === REDACTED ? whole : `${head} ${REDACTED}`;
99
+ if (replaced !== whole)
100
+ count += 1;
101
+ return replaced;
102
+ });
103
+ }
104
+ for (const [pattern, replacement] of SECRET_PATTERNS) {
105
+ out = out.replace(pattern, (...args) => {
106
+ const replaced = replacement === REDACTED ? REDACTED : expandReplacement(replacement, args);
107
+ if (replaced !== args[0])
108
+ count += 1;
109
+ return replaced;
110
+ });
111
+ }
112
+ return { text: out, count };
113
+ }
@@ -22,6 +22,7 @@
22
22
  * scope here; the operator's agent can only restore its own memories.
23
23
  * Cross-agent restore is a 1.1+ feature.
24
24
  */
25
+ import { encodeRecordId } from "../lib/record-id-path.js";
25
26
  import { readFileSync, existsSync, rmSync, mkdtempSync } from "node:fs";
26
27
  import { resolve } from "node:path";
27
28
  import { tmpdir } from "node:os";
@@ -193,7 +194,7 @@ export async function applySnapshot(opts) {
193
194
  if (!m?.id)
194
195
  continue;
195
196
  try {
196
- await opts.apiCall("DELETE", `/Memory/${encodeURIComponent(String(m.id))}`);
197
+ await opts.apiCall("DELETE", `/Memory/${encodeRecordId(String(m.id))}`);
197
198
  result.deleted.memories++;
198
199
  }
199
200
  catch (err) {
@@ -204,7 +205,7 @@ export async function applySnapshot(opts) {
204
205
  if (!s?.id)
205
206
  continue;
206
207
  try {
207
- await soulWrite(opts)("DELETE", `/Soul/${encodeURIComponent(String(s.id))}`);
208
+ await soulWrite(opts)("DELETE", `/Soul/${encodeRecordId(String(s.id))}`);
208
209
  result.deleted.souls++;
209
210
  }
210
211
  catch (err) {
@@ -215,7 +216,7 @@ export async function applySnapshot(opts) {
215
216
  if (!c?.id)
216
217
  continue;
217
218
  try {
218
- await opts.apiCall("DELETE", `/MemoryCandidate/${encodeURIComponent(String(c.id))}`);
219
+ await opts.apiCall("DELETE", `/MemoryCandidate/${encodeRecordId(String(c.id))}`);
219
220
  result.deleted.candidates++;
220
221
  }
221
222
  catch (err) {
@@ -229,7 +230,7 @@ export async function applySnapshot(opts) {
229
230
  if (!s?.id)
230
231
  continue;
231
232
  try {
232
- await soulWrite(opts)("PUT", `/Soul/${encodeURIComponent(String(s.id))}`, s);
233
+ await soulWrite(opts)("PUT", `/Soul/${encodeRecordId(String(s.id))}`, s);
233
234
  result.restored.souls++;
234
235
  }
235
236
  catch (err) {
@@ -240,7 +241,7 @@ export async function applySnapshot(opts) {
240
241
  if (!m?.id)
241
242
  continue;
242
243
  try {
243
- await opts.apiCall("PUT", `/Memory/${encodeURIComponent(String(m.id))}`, m);
244
+ await opts.apiCall("PUT", `/Memory/${encodeRecordId(String(m.id))}`, m);
244
245
  result.restored.memories++;
245
246
  }
246
247
  catch (err) {
@@ -38,8 +38,8 @@
38
38
  * - Step 6 (dedup-cluster stat, flair-quality Slice 1c): calls
39
39
  * `/MemoryDedupStats` after distillation. `dryRun` skips it (persisting
40
40
  * the stat file is a side effect); failure (e.g. the caller isn't admin
41
- * — the resource is admin-gated) is recorded in `errors` and does not
42
- * fail the cycle. See resources/MemoryDedupStats.ts for the server-side
41
+ * — the resource is admin-gated) is recorded in `errors` and fails
42
+ * the cycle (#809). See resources/MemoryDedupStats.ts for the server-side
43
43
  * computation and resources/dedup-cluster.ts for the stat's canonical
44
44
  * storage location (NOT this log — see those files' module docs for why).
45
45
  * - Step 7 shipped in slice-1 PR-1 (was step 6 before this PR).
@@ -47,9 +47,8 @@
47
47
  * The audit row's `slice` field tells readers which steps populated which
48
48
  * counts: `slice: "1"` rows have `archived`/`expired` undefined; `slice:
49
49
  * "2-maintenance"` rows populate them but distillation didn't run this cycle
50
- * (dry-run skip); `slice: "2"` rows had distillation attempted — check
51
- * `candidates` for staged ids on success, `errors` for a `distillation:`
52
- * entry on failure (maintenance results still stand either way).
50
+ * (dry-run skip); `slice: "2"` rows reached the non-dry-run distillation phase.
51
+ * An idle ADK skip can contain no `/ReflectMemories` attempt.
53
52
  *
54
53
  * Pure dependency injection so the runner is unit-testable without Harper.
55
54
  * The CLI wires the real `apiCall` + `pkgVersion`; tests pass stubs.
@@ -254,10 +253,26 @@ function describeApiError(err) {
254
253
  }
255
254
  return message;
256
255
  }
257
- /** True when /ReflectMemories (or the pause check) refused because the operator aborted. */
256
+ function structuredApiError(err) {
257
+ const message = typeof err === "string" ? err : err?.message;
258
+ if (typeof message !== "string")
259
+ return null;
260
+ try {
261
+ const body = JSON.parse(message);
262
+ return body && typeof body.error === "string" ? body.error : null;
263
+ }
264
+ catch {
265
+ return null;
266
+ }
267
+ }
268
+ /** The server's structured pause response. */
258
269
  export function isRemAbortedFailure(err) {
259
- const text = describeApiError(err);
260
- return text.includes("rem_aborted") || text.includes("REM distillation aborted");
270
+ return err?.status === 503 && structuredApiError(err) === "rem_aborted";
271
+ }
272
+ /** A missing generative backend alone no longer fails the run (#924). */
273
+ export function isNoBackendConfigured(err) {
274
+ return err?.status === 503
275
+ && structuredApiError(err) === "No generative backend configured. See the models configuration docs.";
261
276
  }
262
277
  /**
263
278
  * True when this agent owns any `adk:<app>:<user>` tag, regardless of
@@ -454,6 +469,7 @@ export async function runNightlyCycle(opts) {
454
469
  runAt: startedAt.toISOString(),
455
470
  slice: "1",
456
471
  errors: [],
472
+ skips: [],
457
473
  };
458
474
  // Step 1: pre-flight (pause)
459
475
  if (envPaused || (existsSync(pauseFlagPath) && readPauseSentinel(pauseFlagPath))) {
@@ -467,6 +483,15 @@ export async function runNightlyCycle(opts) {
467
483
  return { status: "paused", logRow: row };
468
484
  }
469
485
  const errors = [];
486
+ // flair#924 defect 1: deliberate skips (no backend / idle ADK / operator
487
+ // pause) land here, not in `errors`. Dedup so a per-tag or per-stage repeat
488
+ // of the same reason is recorded once.
489
+ const skips = [];
490
+ const pushSkipOnce = (reason) => {
491
+ if (!skips.includes(reason))
492
+ skips.push(reason);
493
+ };
494
+ const NO_BACKEND_SKIP = "distillation skipped: no generative backend configured";
470
495
  const healthTimeoutMs = opts.healthTimeoutMs ?? DEFAULT_HEALTH_PREFLIGHT_MS;
471
496
  const health = await runHealthPreflight(opts.apiCall, {
472
497
  probe: opts.healthProbe,
@@ -595,10 +620,20 @@ export async function runNightlyCycle(opts) {
595
620
  // #1515: aggregate gather stats from every /ReflectMemories call this cycle.
596
621
  let distill;
597
622
  let distillAborted = false;
623
+ let distillRan = false;
598
624
  const collectStagedIds = (obj) => asArray(obj.candidates)
599
625
  .map((c) => (c && typeof c === "object" ? c.id : c))
600
626
  .filter((id) => typeof id === "string");
601
627
  const noteGather = (obj, maxMemories) => {
628
+ if (!Array.isArray(obj.candidates) || obj.count !== obj.candidates.length
629
+ || typeof obj.model !== "string" || !obj.model.trim()
630
+ || !obj.candidates.every((c) => c && typeof c === "object" && typeof c.id === "string" && c.id.length > 0)
631
+ || !Number.isInteger(obj.gathered) || obj.gathered < 0
632
+ || !Number.isInteger(obj.unreflected) || obj.unreflected < 0
633
+ || (obj.gathered === 0 && obj.candidates.length > 0)) {
634
+ throw new Error("unexpected /ReflectMemories response shape");
635
+ }
636
+ distillRan ||= obj.gathered > 0;
602
637
  const gathered = typeof obj.gathered === "number" ? obj.gathered : 0;
603
638
  const unreflected = typeof obj.unreflected === "number" ? obj.unreflected : 0;
604
639
  if (!distill) {
@@ -634,7 +669,7 @@ export async function runNightlyCycle(opts) {
634
669
  for (const tag of tagsToRun) {
635
670
  if (cycleIsAborted()) {
636
671
  distillAborted = true;
637
- errors.push("distillation: aborted by operator (flair rem pause or FLAIR_REM_PAUSE=1)");
672
+ skips.push("distillation: aborted by operator (flair rem pause or FLAIR_REM_PAUSE=1)");
638
673
  break;
639
674
  }
640
675
  await yieldToEventLoop();
@@ -649,22 +684,23 @@ export async function runNightlyCycle(opts) {
649
684
  const obj = (reflectRaw && typeof reflectRaw === "object") ? reflectRaw : {};
650
685
  if (obj.error) {
651
686
  errors.push(`distillation[${tag}]: ${describeApiError(obj.error)}`);
652
- if (isRemAbortedFailure(obj.error)) {
653
- distillAborted = true;
654
- break;
655
- }
656
687
  }
657
688
  else {
658
- staged.push(...collectStagedIds(obj));
659
689
  noteGather(obj, maxMemories);
690
+ staged.push(...collectStagedIds(obj));
660
691
  }
661
692
  }
662
693
  catch (err) {
663
- errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
664
- if (isRemAbortedFailure(err?.message ?? err)) {
694
+ if (isNoBackendConfigured(err)) {
695
+ pushSkipOnce(NO_BACKEND_SKIP);
696
+ break;
697
+ }
698
+ if (isRemAbortedFailure(err)) {
699
+ pushSkipOnce("distillation: aborted by operator (rem_aborted)");
665
700
  distillAborted = true;
666
701
  break;
667
702
  }
703
+ errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
668
704
  }
669
705
  }
670
706
  // `candidates` is defined (even if empty) whenever distillation was
@@ -675,7 +711,7 @@ export async function runNightlyCycle(opts) {
675
711
  // ADK agentId whose users are all idle this window. Do NOT fall through
676
712
  // to scope:"all" — that mixes every user's backlog (#1205b bleed).
677
713
  // Active tags will be re-selected next cycle when they have recent rows.
678
- errors.push("distillation: ADK agent has no active adk tags this cycle; skipped agentId-wide distill to avoid cross-user bleed");
714
+ skips.push("distillation: ADK agent has no active adk tags this cycle; skipped agentId-wide distill to avoid cross-user bleed");
679
715
  }
680
716
  else {
681
717
  // AgentId-only path (non-ADK). scope:"all" + oldest-unreflected cap so
@@ -691,16 +727,11 @@ export async function runNightlyCycle(opts) {
691
727
  });
692
728
  const obj = (reflectRaw && typeof reflectRaw === "object") ? reflectRaw : {};
693
729
  if (obj.error) {
694
- // Defensive: a 200 response shouldn't carry { error }, since
695
- // MemoryReflect signals failure via HTTP status (503/502) — apiCall
696
- // implementations throw for those. Handled the same way regardless.
697
730
  errors.push(`distillation: ${describeApiError(obj.error)}`);
698
- if (isRemAbortedFailure(obj.error))
699
- distillAborted = true;
700
731
  }
701
732
  else {
702
- candidates = collectStagedIds(obj);
703
733
  noteGather(obj, maxMemories);
734
+ candidates = collectStagedIds(obj);
704
735
  }
705
736
  }
706
737
  catch (err) {
@@ -709,9 +740,17 @@ export async function runNightlyCycle(opts) {
709
740
  // 3). Zero partial candidates is guaranteed server-side (all-or-
710
741
  // nothing staging in /ReflectMemories). rem_aborted IS fatal to the
711
742
  // rest of this cycle (no auto-promote / dedup).
712
- errors.push(`distillation: ${describeApiError(err?.message ?? err)}`);
713
- if (isRemAbortedFailure(err?.message ?? err))
714
- distillAborted = true;
743
+ if (isNoBackendConfigured(err)) {
744
+ pushSkipOnce(NO_BACKEND_SKIP);
745
+ }
746
+ else {
747
+ if (isRemAbortedFailure(err)) {
748
+ pushSkipOnce("distillation: aborted by operator (rem_aborted)");
749
+ distillAborted = true;
750
+ }
751
+ else
752
+ errors.push(`distillation: ${describeApiError(err?.message ?? err)}`);
753
+ }
715
754
  }
716
755
  }
717
756
  // ── Step 5a (flair#1257 slice 3): continuity-session distillation ─────────
@@ -747,7 +786,7 @@ export async function runNightlyCycle(opts) {
747
786
  for (const tag of continuityToRun) {
748
787
  if (distillAborted || cycleIsAborted()) {
749
788
  distillAborted = true;
750
- errors.push("distillation: aborted by operator (flair rem pause or FLAIR_REM_PAUSE=1)");
789
+ skips.push("distillation: aborted by operator (flair rem pause or FLAIR_REM_PAUSE=1)");
751
790
  break;
752
791
  }
753
792
  await yieldToEventLoop();
@@ -763,23 +802,24 @@ export async function runNightlyCycle(opts) {
763
802
  const obj = (reflectRaw && typeof reflectRaw === "object") ? reflectRaw : {};
764
803
  if (obj.error) {
765
804
  errors.push(`distillation[${tag}]: ${describeApiError(obj.error)}`);
766
- if (isRemAbortedFailure(obj.error)) {
767
- distillAborted = true;
768
- break;
769
- }
770
805
  }
771
806
  else {
772
- candidates.push(...collectStagedIds(obj));
773
807
  noteGather(obj, maxMemories);
808
+ candidates.push(...collectStagedIds(obj));
774
809
  distilled++;
775
810
  }
776
811
  }
777
812
  catch (err) {
778
- errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
779
- if (isRemAbortedFailure(err?.message ?? err)) {
813
+ if (isNoBackendConfigured(err)) {
814
+ pushSkipOnce(NO_BACKEND_SKIP);
815
+ break;
816
+ }
817
+ if (isRemAbortedFailure(err)) {
818
+ pushSkipOnce("distillation: aborted by operator (rem_aborted)");
780
819
  distillAborted = true;
781
820
  break;
782
821
  }
822
+ errors.push(`distillation[${tag}]: ${describeApiError(err?.message ?? err)}`);
783
823
  }
784
824
  }
785
825
  continuitySessions = distilled;
@@ -846,7 +886,8 @@ export async function runNightlyCycle(opts) {
846
886
  else if (typeof obj.clusterCount === "number" &&
847
887
  typeof obj.largestClusterSize === "number" &&
848
888
  typeof obj.totalMemoriesInClusters === "number" &&
849
- typeof obj.computedAt === "string") {
889
+ typeof obj.computedAt === "string" &&
890
+ obj.embeddingSpace === undefined) {
850
891
  dedup = {
851
892
  clusterCount: obj.clusterCount,
852
893
  largestClusterSize: obj.largestClusterSize,
@@ -854,6 +895,31 @@ export async function runNightlyCycle(opts) {
854
895
  computedAt: obj.computedAt,
855
896
  };
856
897
  }
898
+ else if (
899
+ // Accept the guard's refusal only with null counts and a refusal state: any
900
+ // non-empty state other than "uniform" (a refusal claiming "uniform" is
901
+ // contradictory and stays an unexpected shape). Not an enumeration of
902
+ // today's states, so a new guard state is recorded rather than an error.
903
+ obj.clusterCount === null &&
904
+ obj.largestClusterSize === null &&
905
+ obj.totalMemoriesInClusters === null &&
906
+ typeof obj.computedAt === "string" &&
907
+ obj.embeddingSpace !== null && typeof obj.embeddingSpace === "object" &&
908
+ !Array.isArray(obj.embeddingSpace) &&
909
+ typeof obj.embeddingSpace.state === "string" &&
910
+ obj.embeddingSpace.state.length > 0 &&
911
+ obj.embeddingSpace.state !== "uniform" &&
912
+ (obj.embeddingSpace.reason === null ||
913
+ typeof obj.embeddingSpace.reason === "string")) {
914
+ const space = obj.embeddingSpace;
915
+ dedup = {
916
+ clusterCount: null,
917
+ largestClusterSize: null,
918
+ totalMemoriesInClusters: null,
919
+ computedAt: obj.computedAt,
920
+ embeddingSpace: { state: space.state, reason: space.reason },
921
+ };
922
+ }
857
923
  else {
858
924
  errors.push("dedup: unexpected /MemoryDedupStats response shape");
859
925
  }
@@ -874,15 +940,6 @@ export async function runNightlyCycle(opts) {
874
940
  const row = {
875
941
  ...baseRow,
876
942
  slice: sliceLabel,
877
- // flair#924 (defect 1): a run whose recorded `errors[]` is non-empty must
878
- // NOT report success. A core stage that could not run — distillation with
879
- // no generative backend, a per-tag distill failure, the dedup stat, an
880
- // operator-aborted distill — is already pushed into `errors`; if any error
881
- // stands, the run FAILED. Before this, a distillation-disabled cycle logged
882
- // `status: "completed"` next to a populated `Errors:` block while the CLI
883
- // exited 1 (src/commands/rem.ts), so the one signal a service manager can
884
- // act on disagreed with the reported status. A populated errors[] can never
885
- // coexist with "completed" again (regression-tested in rem-runner.test.ts).
886
943
  status: errors.length > 0 ? "failed" : opts.dryRun ? "dry-run" : "completed",
887
944
  dryRun: opts.dryRun || undefined,
888
945
  snapshotPath,
@@ -898,6 +955,8 @@ export async function runNightlyCycle(opts) {
898
955
  dedup,
899
956
  durationMs: Date.now() - startedMs,
900
957
  errors,
958
+ skips,
959
+ distilledAt: distillRan && !distillAborted && errors.length === 0 && skips.length === 0 ? baseRow.runAt : undefined,
901
960
  // `consolidated` remains undefined — this runner has no consolidation
902
961
  // step; it's reserved for a future slice that adds one.
903
962
  };