@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
@@ -535,26 +535,35 @@ export function register(program) {
535
535
  const bm25Line = formatBm25StatusLine(healthData?.bm25);
536
536
  if (bm25Line)
537
537
  console.log(render.kv("BM25 index", bm25Line));
538
- if (agents && agents.count > 0) {
539
- console.log(`\n${render.wrap(render.c.bold, "Agents")}`);
540
- const nameStr = agents.names?.length > 0 ? ` ${render.wrap(render.c.dim, "—")} ${agents.names.join(render.wrap(render.c.dim, ", "))}` : "";
541
- console.log(render.kv("Total", `${render.wrap(render.c.bold, String(agents.count))}${nameStr}`));
542
- if (agents.count > 1 && Array.isArray(agents.perAgent) && agents.perAgent.length > 0) {
543
- const hasDeep = agents.perAgent.some((r) => typeof r.hashFallback === "number" || typeof r.writes24h === "number");
544
- const cols = hasDeep
545
- ? [
546
- { label: "id", key: "id" },
547
- { label: "memories", key: "memoryCount", align: "right" },
548
- { label: "hash_fb", key: "hashFallback", align: "right", format: (v) => (typeof v === "number" ? String(v) : "—") },
549
- { label: "24h", key: "writes24h", align: "right", format: (v) => (typeof v === "number" ? String(v) : "—") },
550
- { label: "last_write", key: "lastWriteAt", format: (v) => render.relativeTime(v) },
551
- ]
552
- : [
553
- { label: "id", key: "id" },
554
- { label: "memories", key: "memoryCount", align: "right" },
555
- { label: "last_write", key: "lastWriteAt", format: (v) => render.relativeTime(v) },
556
- ];
557
- console.log(render.table(cols, agents.perAgent));
538
+ if (agents) {
539
+ if (agents.count > 0) {
540
+ console.log(`\n${render.wrap(render.c.bold, "Agents")}`);
541
+ const nameStr = agents.names?.length > 0 ? ` ${render.wrap(render.c.dim, "—")} ${agents.names.join(render.wrap(render.c.dim, ", "))}` : "";
542
+ console.log(render.kv("Total", `${render.wrap(render.c.bold, String(agents.count))}${nameStr}`));
543
+ if (Array.isArray(agents.perAgent) && agents.perAgent.length > 0) {
544
+ const hasDeep = agents.perAgent.some((r) => typeof r.hashFallback === "number" || typeof r.writes24h === "number");
545
+ const cols = hasDeep
546
+ ? [
547
+ { label: "id", key: "id" },
548
+ { label: "memories", key: "memoryCount", align: "right" },
549
+ { label: "hash_fb", key: "hashFallback", align: "right", format: (v) => (typeof v === "number" ? String(v) : "—") },
550
+ { label: "24h", key: "writes24h", align: "right", format: (v) => (typeof v === "number" ? String(v) : "—") },
551
+ { label: "last_write", key: "lastWriteAt", format: (v) => render.relativeTime(v) },
552
+ ]
553
+ : [
554
+ { label: "id", key: "id" },
555
+ { label: "memories", key: "memoryCount", align: "right" },
556
+ { label: "last_write", key: "lastWriteAt", format: (v) => render.relativeTime(v) },
557
+ ];
558
+ console.log(render.table(cols, agents.perAgent));
559
+ }
560
+ }
561
+ if (agents.unregisteredMemoryAuthors === null) {
562
+ console.log(render.kv("Unregistered memory owners", render.wrap(render.c.dim, "unavailable — memory scan did not complete")));
563
+ }
564
+ else if (Array.isArray(agents.unregisteredMemoryAuthors) && agents.unregisteredMemoryAuthors.length > 0) {
565
+ const owners = agents.unregisteredMemoryAuthors.map((r) => `${r.id} (${r.memoryCount} ${r.memoryCount === 1 ? "memory" : "memories"})`);
566
+ console.log(render.kv("Unregistered memory owners", owners.join(render.wrap(render.c.dim, ", "))));
558
567
  }
559
568
  }
560
569
  if (healthData?.relationships) {
@@ -992,20 +1001,29 @@ export function register(program) {
992
1001
  if (bm25DeepLine)
993
1002
  console.log(`BM25 index: ${bm25DeepLine}`);
994
1003
  const agents = healthData?.agents;
995
- if (agents && agents.count > 0) {
996
- console.log("\n═══ Agents ═══════════════════════════════════════");
997
- console.log(`Total: ${agents.count}`);
998
- if (Array.isArray(agents.names) && agents.names.length > 0) {
999
- console.log(`Names: ${agents.names.join(", ")}`);
1000
- }
1001
- if (Array.isArray(agents.perAgent) && agents.perAgent.length > 0) {
1002
- const idW = Math.max(2, ...agents.perAgent.map((r) => (r.id ?? "").length));
1003
- console.log(`\n ${"id".padEnd(idW)} memories hash_fb 24h last_write`);
1004
- for (const r of agents.perAgent) {
1005
- const fb = typeof r.hashFallback === "number" ? String(r.hashFallback) : "—";
1006
- const w24 = typeof r.writes24h === "number" ? String(r.writes24h) : "—";
1007
- console.log(` ${(r.id ?? "").padEnd(idW)} ${String(r.memoryCount).padStart(8)} ${fb.padStart(7)} ${w24.padStart(3)} ${relativeTime(r.lastWriteAt)}`);
1004
+ if (agents) {
1005
+ if (agents.count > 0) {
1006
+ console.log("\n═══ Agents ═══════════════════════════════════════");
1007
+ console.log(`Total: ${agents.count}`);
1008
+ if (Array.isArray(agents.names) && agents.names.length > 0) {
1009
+ console.log(`Names: ${agents.names.join(", ")}`);
1008
1010
  }
1011
+ if (Array.isArray(agents.perAgent) && agents.perAgent.length > 0) {
1012
+ const idW = Math.max(2, ...agents.perAgent.map((r) => (r.id ?? "").length));
1013
+ console.log(`\n ${"id".padEnd(idW)} memories hash_fb 24h last_write`);
1014
+ for (const r of agents.perAgent) {
1015
+ const fb = typeof r.hashFallback === "number" ? String(r.hashFallback) : "—";
1016
+ const w24 = typeof r.writes24h === "number" ? String(r.writes24h) : "—";
1017
+ console.log(` ${(r.id ?? "").padEnd(idW)} ${String(r.memoryCount).padStart(8)} ${fb.padStart(7)} ${w24.padStart(3)} ${relativeTime(r.lastWriteAt)}`);
1018
+ }
1019
+ }
1020
+ }
1021
+ if (agents.unregisteredMemoryAuthors === null) {
1022
+ console.log("Unregistered memory owners: unavailable — memory scan did not complete");
1023
+ }
1024
+ else if (Array.isArray(agents.unregisteredMemoryAuthors) && agents.unregisteredMemoryAuthors.length > 0) {
1025
+ const owners = agents.unregisteredMemoryAuthors.map((r) => `${r.id} (${r.memoryCount} ${r.memoryCount === 1 ? "memory" : "memories"})`);
1026
+ console.log(`Unregistered memory owners: ${owners.join(", ")}`);
1009
1027
  }
1010
1028
  }
1011
1029
  // Bootstrap context section — always printed so users see how to opt in.
@@ -1,5 +1,6 @@
1
1
  import * as render from "../render.js";
2
2
  import { encodeRecordId } from "../lib/record-id-path.js";
3
+ import { ApiRequestOutcomeUnknown } from "../lib/auth-resolve.js";
3
4
  let cli;
4
5
  /** Bind the cli-locals this module depends on. */
5
6
  export function bindCli(fns) {
@@ -45,13 +46,15 @@ export function register(program) {
45
46
  }
46
47
  }
47
48
  catch (e) {
49
+ if (e instanceof ApiRequestOutcomeUnknown)
50
+ throw e;
48
51
  const message = e instanceof Error ? e.message : String(e);
49
52
  console.log(` ${render.icons.error} ${render.wrap(render.c.red, "FAIL")} ${name}: ${render.wrap(render.c.dim, message?.slice(0, 120))}`);
50
53
  failed++;
51
54
  }
52
55
  };
53
56
  // 1. Write a test memory via PUT /Memory/<id>.
54
- // Schema only exposes PUT — POST returns 'Memory does not have a post method implemented'.
57
+ // The CLI writes through PUT /Memory/<id>; a bare POST /Memory reaches Memory.post() too.
55
58
  await check("Write test memory (PUT /Memory/<id>)", async () => {
56
59
  const id = `flair-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
57
60
  const body = {
@@ -1,6 +1,7 @@
1
1
  import { detectWiredFlairMcp } from "../doctor-client.js";
2
2
  import { UPGRADE_SNAPSHOT_ROOT, fetchDeclaredHarperVersion, readInstalledHarperVersion } from "../engine-version.js";
3
3
  import { fabricUpgrade } from "../fabric-upgrade.js";
4
+ import { deployUrlRefusal, safeUrl } from "../mqtt-off-deploy.js";
4
5
  import { renderFleetSweepTable, sweepFleet } from "../fleet-verify.js";
5
6
  import { resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
6
7
  import { defaultKeysDir } from "../lib/auth-resolve.js";
@@ -136,6 +137,39 @@ function upgradeStatusSuffix(...args) {
136
137
  function verifyAuthedGet(...args) {
137
138
  return cli.verifyAuthedGet(...args);
138
139
  }
140
+ /**
141
+ * The options `flair upgrade --target` hands fabricUpgrade(), from the
142
+ * command's options and resolved credentials. `opsUrl` is what every remote
143
+ * command resolves (`resolveOpsUrl`: --ops-target / FLAIR_OPS_TARGET, else
144
+ * derived from --target); deploy() sends the MQTT-off configuration, restart and read-back
145
+ * there.
146
+ */
147
+ export function buildFabricUpgradeOptions(opts, creds, resolveOpsUrl) {
148
+ return {
149
+ target: opts.target,
150
+ project: opts.project,
151
+ // flair#926: `--flair-version`, never `opts.version` — that attribute name
152
+ // belongs to the program's `-v, --version` and never reaches this action.
153
+ version: opts.flairVersion,
154
+ harperVersion: opts.harperVersion,
155
+ fabricUser: creds.fabricUser,
156
+ fabricPassword: creds.fabricPassword,
157
+ check: opts.check ?? false,
158
+ restart: opts.restart !== false,
159
+ replicated: opts.replicated !== false,
160
+ keepMqttConfig: opts.keepMqttConfig ?? false,
161
+ // --no-verify reaches deploy(): it skips the served-API verification and
162
+ // the post-restart MQTT step there too.
163
+ verify: opts.verify !== false,
164
+ opsUrl: resolveOpsUrl({ target: opts.target, opsTarget: opts.opsTarget }),
165
+ // flair#878 — previously unreachable from this command; see
166
+ // FabricUpgradeOptions.
167
+ deployRetries: Number(opts.deployRetries ?? 0),
168
+ ignoreReplicationErrors: opts.ignoreReplicationErrors ?? false,
169
+ convergenceCheck: opts.convergenceCheck !== false,
170
+ convergenceTimeoutMs: opts.convergenceTimeout != null ? Number(opts.convergenceTimeout) : undefined,
171
+ };
172
+ }
139
173
  async function runFabricUpgrade(opts) {
140
174
  const green = (s) => `\x1b[32m${s}\x1b[0m`;
141
175
  const red = (s) => `\x1b[31m${s}\x1b[0m`;
@@ -165,26 +199,8 @@ async function runFabricUpgrade(opts) {
165
199
  // resolver's own warning strings.
166
200
  for (const w of credWarnings)
167
201
  console.error(dim(w));
168
- const upgradeOpts = {
169
- target: opts.target,
170
- project: opts.project,
171
- // flair#926: `--flair-version`, never `opts.version` — that attribute name
172
- // belongs to the program's `-v, --version` and never reaches this action.
173
- version: opts.flairVersion,
174
- harperVersion: opts.harperVersion,
175
- fabricUser,
176
- fabricPassword,
177
- check,
178
- restart: opts.restart !== false,
179
- replicated: opts.replicated !== false,
180
- // flair#878 — previously unreachable from this command; see
181
- // FabricUpgradeOptions.
182
- deployRetries: Number(opts.deployRetries ?? 0),
183
- ignoreReplicationErrors: opts.ignoreReplicationErrors ?? false,
184
- convergenceCheck: opts.convergenceCheck !== false,
185
- convergenceTimeoutMs: opts.convergenceTimeout != null ? Number(opts.convergenceTimeout) : undefined,
186
- };
187
- console.log(`${green("→")} Upgrading Fabric Flair at ${upgradeOpts.target}`);
202
+ const upgradeOpts = buildFabricUpgradeOptions(opts, { fabricUser, fabricPassword }, cli.resolveEffectiveOpsUrl);
203
+ console.log(`${green("→")} Upgrading Fabric Flair at ${safeUrl(upgradeOpts.target)}`);
188
204
  if (check)
189
205
  console.log(dim(" (--check: plan only, no deploy)"));
190
206
  try {
@@ -194,7 +210,7 @@ async function runFabricUpgrade(opts) {
194
210
  if (!check && !opts.yes && process.stdin.isTTY) {
195
211
  const { createInterface } = await import("node:readline");
196
212
  const rl = createInterface({ input: process.stdin, output: process.stdout });
197
- const answer = await new Promise((res) => rl.question(`Deploy a fresh ${green("@tpsdev-ai/flair")} to ${upgradeOpts.target}? [y/N] `, (a) => { rl.close(); res(a); }));
213
+ const answer = await new Promise((res) => rl.question(`Deploy a fresh ${green("@tpsdev-ai/flair")} to ${safeUrl(upgradeOpts.target)}? [y/N] `, (a) => { rl.close(); res(a); }));
198
214
  if (!/^y(es)?$/i.test(answer.trim())) {
199
215
  console.log("Aborted.");
200
216
  return;
@@ -751,7 +767,7 @@ export function register(program) {
751
767
  .option("--tree <dir>", "Upgrade this extracted package tree in place (npm pack / plain-tree lane). Default: the serving instance's packed tree when that is not the npm-global install")
752
768
  .option("--restart", "[deprecated] no-op — restart now happens automatically after upgrade; use --no-restart to opt out")
753
769
  .option("--no-restart", "Skip the restart after upgrade (stage new packages now, restart later)")
754
- .option("--no-verify", "Skip post-restart health/version/auth verification (default: verify — so a broken upgrade can't report success; see flair#635)")
770
+ .option("--no-verify", "Skip post-restart health/version/auth verification (default: verify — so a broken upgrade can't report success; see flair#635); with --target, also skips deploy()'s served-API verification and its post-restart MQTT step")
755
771
  .option("--snapshot", "Take a pre-upgrade ~/.flair/data snapshot before the package swap, keep-last-3 retention (default: off — see `flair snapshot create` to take one by hand, or `flair backup` for a logical export; flair#637)")
756
772
  .option("--no-engine-snapshot", "Skip the pre-upgrade snapshot even when the Harper engine version is changing (flair#1047). The snapshot is automatic on engine-version changes because the tested-downgrade guarantee does not hold across engine boundaries. Opting out prints what is being given up.")
757
773
  .option("--all", "Show transitive packages (e.g. flair-client) in the listing — verbose mode for debugging dep versions")
@@ -774,6 +790,8 @@ export function register(program) {
774
790
  .option("--harper-version <semver>", "Pin harper to this version for --target (default: registry latest, floored at the flair#513 fix)")
775
791
  .option("--project <name>", "Fabric component name for --target", "flair")
776
792
  .option("--no-replicated", "Disable cluster-wide replication for --target (default: replicated=true)")
793
+ .option("--keep-mqtt-config", "For --target: leave the target's MQTT configuration as it is (default: set every MQTT listener off in the target's configuration before deploying, then, after the deploy's restart, request the shared workers' restart for an isolated application and read the saved configuration back; --no-restart and --no-verify skip those two; the listeners are not probed)")
794
+ .option("--ops-target <url>", "For --target: operations API URL for the MQTT-off configuration, restart and read-back (env: FLAIR_OPS_TARGET; default: derived from --target)")
777
795
  .option("--yes", "Skip the confirmation prompt for --target")
778
796
  .option("--install-hooks", "Consent to installing missing SessionStart hooks (claude-code / Codex) during upgrade. The hook executes at every session start — upgrade will not write it unprompted. Interactive runs prompt; non-interactive runs state the gap and withhold ✅ unless this flag is passed.")
779
797
  .option("--no-fleet-verify", "Skip the automatic post-upgrade fleet convergence sweep for --target (default: sweep runs — see flair#636)")
@@ -788,6 +806,19 @@ export function register(program) {
788
806
  .action(async (opts) => {
789
807
  // ── Fabric-upgrade branch ───────────────────────────────────────────────
790
808
  if (opts.target) {
809
+ // Every URL the Fabric upgrade takes is checked before anything is
810
+ // printed: a user name, password, query or fragment is refused. An
811
+ // operations API URL derived from a target that passes keeps its scheme,
812
+ // host and path with the operations port (fabricUpgrade() and deploy()
813
+ // check it again).
814
+ const refusal = deployUrlRefusal([
815
+ [opts.target, "deploy target URL (--target)"],
816
+ [opts.opsTarget || process.env.FLAIR_OPS_TARGET, "operations API URL (--ops-target / FLAIR_OPS_TARGET)"],
817
+ ]);
818
+ if (refusal) {
819
+ console.error(`\x1b[31m${refusal}\x1b[0m`);
820
+ process.exit(1);
821
+ }
791
822
  if (!opts.check)
792
823
  console.log("OAuth redirect migration is local-only; --target requires target-side OAuth environment configuration.");
793
824
  await runFabricUpgrade(opts);
@@ -23,14 +23,13 @@ function parseEntitiesOptionOrExit(csv) {
23
23
  // (WorkspaceState.put(), resources/WorkspaceState.ts), so this is a
24
24
  // self-declaration the server verifies 1:1, not attribution-from-body.
25
25
  //
26
- // (flair#679, measured against a real spawned Harper): table-backed resources
27
- // only accept writes via PUT /<Table>/<id> — a bare POST /WorkspaceState 405s
28
- // ("does not have a post method implemented to handle HTTP method POST"),
29
- // same restriction documented in resources/Memory.ts and already fixed for
30
- // `soul set` (#498). WorkspaceState.ts DOES define a post() method, but
31
- // Harper's REST layer never routes a real HTTP POST to it — post() is only
32
- // reachable via in-process resource instantiation, never the wire. put(),
33
- // unlike post(), does NOT default createdAt/timestamp/agentId — the CLI
26
+ // (flair#679, measured against a real spawned Harper): through Harper 5.1.x a
27
+ // bare POST /WorkspaceState 405'd ("does not have a post method implemented to
28
+ // handle HTTP method POST"); the Harper this repo now pins routes it to
29
+ // WorkspaceState.post() and accepts it (harper#1956; the sanity test in
30
+ // test/integration/workspace-orgevent-cli-e2e.test.ts asserts 201). The CLI
31
+ // writes with PUT /<Table>/<id>, which works on both, as `soul set` does (#498).
32
+ // put(), unlike post(), does NOT default createdAt/timestamp/agentId — the CLI
34
33
  // supplies them all explicitly below.
35
34
  export const MAX_WORKSPACE_FIELD_LENGTH = 2000;
36
35
  /** Register the `flair workspace` command group (flair#1635). */
package/dist/deploy.js CHANGED
@@ -10,6 +10,8 @@ import { DEFAULT_STAMP_VERIFY_TIMEOUT_MS, verifyStampMigrationConverged } from "
10
10
  import { FABRIC_NPM_INSTALL_COMMAND } from "./fabric-npm-install.js";
11
11
  import { discriminateMcpOAuthDiscovery, reportMcpOAuthDiscovery } from "./lib/mcp-enable.js";
12
12
  import { mcpOAuthEnabledFromComponentEnv } from "./lib/mcp-oauth-env.js";
13
+ import { applyMqttOffConfiguration, assertSafeUrl, completeMqttOff, sharedWorkerRestartInstruction } from "./mqtt-off-deploy.js";
14
+ import { resolveOpsUrlFromTarget } from "./lib/ops-url.js";
13
15
  // Files that must be PRESENT for a deploy root to be usable at all — a
14
16
  // preflight sanity check, not the payload definition.
15
17
  //
@@ -373,9 +375,9 @@ export function describeDeployFailure(failures, convergence) {
373
375
  // their last message immediately before process.exit() — had been received,
374
376
  // so REPLICATION_FAILURE_RE silently missed a match it should have made and
375
377
  // runHarperDeploy fell through to the generic "exited with code N" error.
376
- function spawnHarperCaptured(bin, args, cwd, env) {
378
+ function spawnHarperCaptured(bin, args, cwd, env, runtime = process.execPath) {
377
379
  return new Promise((resolveP, rejectP) => {
378
- const p = spawn(process.execPath, [bin, ...args], {
380
+ const p = spawn(runtime, [bin, ...args], {
379
381
  cwd,
380
382
  stdio: ["inherit", "pipe", "pipe"],
381
383
  env,
@@ -416,7 +418,7 @@ async function runHarperDeploy(bin, args, cwd, env, opts, targetUrl, project) {
416
418
  const failures = [];
417
419
  let lastConvergence = null;
418
420
  for (let attempt = 1; attempt <= totalAttempts; attempt++) {
419
- const { code, output } = await spawnHarperCaptured(bin, args, cwd, env);
421
+ const { code, output } = await spawnHarperCaptured(bin, args, cwd, env, opts.harperRuntime);
420
422
  if (code === 0)
421
423
  return { replicationWarning: false, convergedAfterReplicationError: false };
422
424
  const isReplicationFailure = REPLICATION_FAILURE_RE.test(output);
@@ -920,6 +922,9 @@ export async function verifyDeployedMcpDiscovery(o) {
920
922
  o.onProgress?.(line);
921
923
  }
922
924
  }
925
+ // The MQTT-off step of this channel lives in src/mqtt-off-deploy.ts; these
926
+ // re-exports keep it reachable from the deploy module.
927
+ export { applyMqttOffConfiguration, buildMqttOffOperation, completeMqttOff } from "./mqtt-off-deploy.js";
923
928
  export async function deploy(opts) {
924
929
  const errors = validateOptions(opts);
925
930
  if (errors.length) {
@@ -931,6 +936,12 @@ export async function deploy(opts) {
931
936
  const version = opts.version ?? pkg.version;
932
937
  const project = opts.project ?? "flair";
933
938
  const url = buildTargetUrl(opts);
939
+ // Every URL the channel uses is http or https with a host, and scheme, host,
940
+ // port and path only: anything else is refused before anything is sent or
941
+ // printed (src/mqtt-off-deploy.ts assertSafeUrl).
942
+ assertSafeUrl(url, "deploy target URL");
943
+ const opsUrl = opts.opsUrl ?? resolveOpsUrlFromTarget(url);
944
+ assertSafeUrl(opsUrl, "operations API URL");
934
945
  if (opts.dryRun) {
935
946
  return { url, project, version, packageRoot, dryRun: true };
936
947
  }
@@ -941,6 +952,27 @@ export async function deploy(opts) {
941
952
  }
942
953
  const harperBin = resolveHarperBin(packageRoot);
943
954
  const args = buildHarperDeployArgs(opts, url, project);
955
+ // MQTT off on the target's configuration before anything is deployed
956
+ // (src/mqtt-off-deploy.ts, step 1); read back after the deploy's restart below.
957
+ let mqttPeers = [];
958
+ if (opts.keepMqttConfig) {
959
+ opts.onProgress?.("--keep-mqtt-config: leaving the target's MQTT configuration as it is");
960
+ }
961
+ else {
962
+ ({ peers: mqttPeers } = await applyMqttOffConfiguration({
963
+ url: opsUrl,
964
+ fabricUser: opts.fabricUser,
965
+ fabricPassword: opts.fabricPassword,
966
+ replicated: opts.replicated !== false,
967
+ fetchImpl: opts.operationsFetch,
968
+ onProgress: opts.onProgress,
969
+ }));
970
+ if (opts.restart === false) {
971
+ const notice = `--no-restart: the MQTT-off configuration takes effect when the target's worker threads restart; ${sharedWorkerRestartInstruction(opsUrl)}`;
972
+ console.warn(`⚠ flair deploy: ${notice}`);
973
+ opts.onProgress?.(notice);
974
+ }
975
+ }
944
976
  // Credentials go via env, not argv, so they don't appear in `ps` output
945
977
  // for the lifetime of the Harper child process. Harper's cliOperations
946
978
  // reads CLI_TARGET_USERNAME / CLI_TARGET_PASSWORD as env fallbacks.
@@ -989,6 +1021,30 @@ export async function deploy(opts) {
989
1021
  }
990
1022
  staged.cleanup();
991
1023
  }
1024
+ // After the deploy's restart: read the saved configuration back and, for an
1025
+ // isolated application, request the shared workers' restart
1026
+ // (src/mqtt-off-deploy.ts, step 2). It reports what was set and requested;
1027
+ // it does not probe the listeners.
1028
+ if (!opts.keepMqttConfig && opts.restart !== false) {
1029
+ if (opts.mqttCheck ?? opts.verify !== false) {
1030
+ await completeMqttOff({
1031
+ url: opsUrl,
1032
+ project,
1033
+ fabricUser: opts.fabricUser,
1034
+ fabricPassword: opts.fabricPassword,
1035
+ replicated: opts.replicated !== false,
1036
+ peers: mqttPeers,
1037
+ fetchImpl: opts.operationsFetch,
1038
+ onProgress: opts.onProgress,
1039
+ });
1040
+ }
1041
+ else {
1042
+ const notice = `the post-restart MQTT step did not run${opts.mqttCheck === false ? "" : " (--no-verify)"}: the saved configuration was not read back, ` +
1043
+ `and no restart of the shared worker threads was requested for an isolated application; ${sharedWorkerRestartInstruction(opsUrl)} if Flair is isolated there`;
1044
+ console.warn(`⚠ flair deploy: ${notice}`);
1045
+ opts.onProgress?.(notice);
1046
+ }
1047
+ }
992
1048
  // harper can print "Successfully deployed" for a component that isn't
993
1049
  // actually serving anything (the incident this closes: an empty deploy,
994
1050
  // reported success, /Memory 404ing in prod). Verify by curling the served
@@ -2183,8 +2183,13 @@ export function describeAgentIdRuleFinding(rows) {
2183
2183
  message: `${invalidIds.length} stored agent id(s) are outside the agent-ID rule (${AGENT_ID_RULE}): ` +
2184
2184
  invalidIds.join(", "),
2185
2185
  fixHint: "after any needed data migration and registration with `flair agent add <new-id>`, " +
2186
- "remove the old row with `flair agent remove <id>`, or remove it alone if stale; " +
2187
- "`flair agent remove` also deletes the agent's Memory and Soul data, but not the key files of an id outside the rule — clean those up manually",
2186
+ "remove the old row with `flair agent remove <id>`, or remove it alone if stale — " +
2187
+ "`flair agent remove` also deletes the agent's Memory and Soul rows, but not the key files of an id outside the rule, so clean those up manually; " +
2188
+ "to maintain that agent's rows, run its own authenticated non-admin maintenance when the stored id " +
2189
+ "can authenticate (the signed TPS-Ed25519 header cannot carry a colon or whitespace); that run deletes " +
2190
+ "the agent's expired ephemeral Memory rows. For an id the header cannot represent, run fleet-wide " +
2191
+ "maintenance, which reaches that agent's rows and also expires and archives other agents' eligible rows — an " +
2192
+ "admin-scoped run needs an id that matches the rule",
2188
2193
  };
2189
2194
  }
2190
2195
  /**
@@ -31,6 +31,7 @@ import { join } from "node:path";
31
31
  import { tmpdir } from "node:os";
32
32
  import { createRequire } from "node:module";
33
33
  import { createRegistryNoticePrinter, fetchDeclaredDependencies, fetchLatestVersion } from "./lib/npm-registry.js";
34
+ import { assertSafeUrl, safeUrl } from "./mqtt-off-deploy.js";
34
35
  /**
35
36
  * Minimum harper version whose component packager works when the
36
37
  * package root is under node_modules (flair#513 — the empty-tarball fix landed
@@ -346,9 +347,15 @@ export async function planFabricUpgrade(opts, deps) {
346
347
  export async function fabricUpgrade(opts, injected) {
347
348
  const deps = { ...defaultDeps(), ...injected };
348
349
  const log = deps.log ?? (() => { });
350
+ // Every URL the upgrade uses has an allowed scheme and a host, and is
351
+ // scheme, host, port and path only; anything else is refused before
352
+ // anything is fetched or printed.
353
+ assertSafeUrl(opts.target, "deploy target URL");
354
+ if (opts.opsUrl !== undefined)
355
+ assertSafeUrl(opts.opsUrl, "operations API URL");
349
356
  // Step 1 + diff.
350
357
  const plan = await planFabricUpgrade(opts, deps);
351
- log(`Fabric: ${plan.target}`);
358
+ log(`Fabric: ${safeUrl(plan.target)}`);
352
359
  log(`Project: ${plan.project}`);
353
360
  log(`Version: ${plan.currentVersion ?? "(unknown)"} → ${plan.targetVersion}` +
354
361
  (plan.upToDate ? " (already up to date)" : ""));
@@ -378,7 +385,7 @@ export async function fabricUpgrade(opts, injected) {
378
385
  log(`✓ Staged ${HARPER_PKG}@${stagedHarper} (>= ${MIN_HARPER_VERSION})`);
379
386
  const packageRoot = resolveStagedFlairRoot(stagingDir);
380
387
  // Step 3: REUSE deploy() — do not reimplement packaging/spawn.
381
- log(`Deploying ${plan.project} ${plan.targetVersion} to ${plan.target} ...`);
388
+ log(`Deploying ${plan.project} ${plan.targetVersion} to ${safeUrl(plan.target)} ...`);
382
389
  const result = await deps.deploy({
383
390
  target: opts.target,
384
391
  project: plan.project,
@@ -386,7 +393,10 @@ export async function fabricUpgrade(opts, injected) {
386
393
  fabricUser: opts.fabricUser,
387
394
  fabricPassword: opts.fabricPassword,
388
395
  restart: opts.restart,
396
+ verify: opts.verify,
389
397
  replicated: opts.replicated,
398
+ keepMqttConfig: opts.keepMqttConfig,
399
+ opsUrl: opts.opsUrl,
390
400
  packageRoot,
391
401
  // flair#878 — see FabricUpgradeOptions: these used to stop at this
392
402
  // boundary, which is why the upgrade path could not act on harper's own
@@ -0,0 +1,139 @@
1
+ /**
2
+ * presence-send.ts — the sender-side selection rules for Presence replication
3
+ * (flair#2578 slice 2: office-wide Presence). PURE: no Harper import, so every
4
+ * rule here is unit-testable without a live Harper.
5
+ *
6
+ * The CLI scans the local Presence table (bounded at one row per agent) and
7
+ * passes the rows here. The Presence table has no `updatedAt`/`createdAt`, so the
8
+ * generic sync cursor cannot select it: a row is selected by its OWN cursor —
9
+ * the later of `lastHeartbeatAt` and `activityUpdatedAt` — compared against a
10
+ * per-table effective watermark, less a 30 s re-scan overlap. Only rows
11
+ * stamped with this instance as their originator are sent.
12
+ *
13
+ * Sender-side support for spoke-to-hub Presence replication, behind its own
14
+ * default-off flag. The receiver side (slice 1) is resources/presence-receipt.
15
+ */
16
+ /** The send flag (default OFF). */
17
+ export const PRESENCE_SEND_FLAG_ENV = "FLAIR_FEDERATION_PRESENCE_SEND";
18
+ /** The allowance the receiver grants an inbound Presence stamp ahead of its own
19
+ * clock. The send side applies the same value to its scan time, so a row
20
+ * stamped further ahead is left out of the batch. A unit test asserts it equals
21
+ * the receiver's PRESENCE_FUTURE_ALLOWANCE_MS (resources/presence-receipt.ts),
22
+ * which src/ cannot import. */
23
+ export const PRESENCE_SEND_FUTURE_ALLOWANCE_MS = 5 * 60 * 1000;
24
+ /** Re-scan overlap behind the effective watermark. */
25
+ export const PRESENCE_SEND_OVERLAP_MS = 30 * 1000;
26
+ /** The receiver skip reasons a later re-offer of the same row can clear, so the
27
+ * sender must not let its per-table watermark pass a row refused for one.
28
+ * Mirrors the `retryable` subset of the receiver's SKIP_REASON_CLASS
29
+ * (resources/federation-classify.ts), which src/ cannot import; a unit test
30
+ * asserts the two sets are equal. */
31
+ export const PRESENCE_SEND_RETRYABLE_SKIP_REASONS = new Set([
32
+ "future_timestamp",
33
+ "unknown_originator_key",
34
+ "merge_target_changed",
35
+ "merge_target_busy",
36
+ "merge_error",
37
+ "presence_agent_not_replicated",
38
+ ]);
39
+ /** The receiver skip reason for a Presence record that arrives while the hub's
40
+ * receive flag is off. The receiver classes it non_retryable, but the hub can
41
+ * enable receipt after this batch, so the sender caps its watermark at a row
42
+ * refused for it and offers that row again on a later sync. Mirrors the reason
43
+ * name in resources/federation-classify.ts, which src/ cannot import; a unit
44
+ * test asserts the receiver knows it as a non_retryable reason. */
45
+ export const PRESENCE_SEND_RECEIVE_DISABLED_SKIP_REASON = "presence_receive_disabled";
46
+ /** Truthy: `1` / `true` / `yes` / `on`. Anything else — unset, empty, `false`,
47
+ * `0`, garbage — is OFF, so the default sends no Presence records. Same
48
+ * vocabulary as the receive flag (resources/presence-receipt). */
49
+ export function presenceSendEnabled(env = process.env) {
50
+ const raw = (env[PRESENCE_SEND_FLAG_ENV] ?? "").trim().toLowerCase();
51
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
52
+ }
53
+ /** Normalize a Presence timestamp column to a finite unix-ms number.
54
+ * A row read from Harper may hand a BigInt back as a bigint or a numeric
55
+ * string, not a JS number. */
56
+ function toMs(value) {
57
+ if (typeof value === "number")
58
+ return Number.isFinite(value) ? value : null;
59
+ if (typeof value === "bigint") {
60
+ const n = Number(value);
61
+ return Number.isFinite(n) ? n : null;
62
+ }
63
+ if (typeof value === "string" && value.trim() !== "") {
64
+ const n = Number(value);
65
+ return Number.isFinite(n) ? n : null;
66
+ }
67
+ return null;
68
+ }
69
+ /**
70
+ * The Presence row's own cursor: the later of `lastHeartbeatAt` and
71
+ * `activityUpdatedAt`, as unix ms. Null for an unusable Date cursor — a
72
+ * row with no cursor cannot be placed against a watermark and is never sent.
73
+ */
74
+ export function presenceCursorMs(row) {
75
+ const heartbeat = toMs(row?.lastHeartbeatAt);
76
+ const activity = toMs(row?.activityUpdatedAt);
77
+ const cursor = heartbeat == null ? activity : activity == null ? heartbeat : Math.max(heartbeat, activity);
78
+ return cursor != null && Number.isFinite(new Date(cursor).getTime()) ? cursor : null;
79
+ }
80
+ /** The stored per-table watermark (an ISO string) as unix ms, or 0 when it is
81
+ * absent or unparseable — 0 selects every home row whose cursor is positive,
82
+ * which is the intended first-sync behaviour. */
83
+ export function presenceWatermarkMs(value) {
84
+ if (typeof value !== "string" || value.trim() === "")
85
+ return 0;
86
+ const ms = Date.parse(value);
87
+ return Number.isFinite(ms) ? ms : 0;
88
+ }
89
+ /**
90
+ * The rows this instance may send: HOME rows (originatorInstanceId is this
91
+ * instance — slice 1 stamps it on a local create) whose own cursor is past the
92
+ * supplied floor. The caller passes the effective watermark less the re-scan
93
+ * overlap, floored at zero. A replicated row, a
94
+ * row with no stamp, a row with no cursor, and a row at or below the floor are
95
+ * all excluded.
96
+ */
97
+ export function selectPresenceRowsToSend(rows, instanceId, watermarkMs) {
98
+ const selected = [];
99
+ for (const row of rows) {
100
+ if (row?.originatorInstanceId !== instanceId)
101
+ continue;
102
+ const cursor = presenceCursorMs(row);
103
+ if (cursor == null || cursor <= watermarkMs)
104
+ continue;
105
+ selected.push(row);
106
+ }
107
+ return selected;
108
+ }
109
+ /**
110
+ * The unsigned wire record for one Presence row. This table keys on `agentId`,
111
+ * so the record's `id` and `data.id` are the row's `agentId` (the shared batch
112
+ * key check wants `data.id === record.id`) and `data.agentId` carries the same
113
+ * value. `updatedAt` is the row's own cursor: the receiver's future-timestamp
114
+ * bound (classifyRecord's `future_timestamp`) is applied to it.
115
+ * Null for an unusable key or timestamp.
116
+ */
117
+ export function presenceWireRecord(row, instanceId) {
118
+ const agentId = typeof row?.agentId === "string" && row.agentId.length > 0 ? row.agentId : null;
119
+ const cursor = presenceCursorMs(row);
120
+ if (!agentId || cursor == null)
121
+ return null;
122
+ const data = { ...row, id: agentId, agentId };
123
+ for (const field of ["lastHeartbeatAt", "activityUpdatedAt", "receivedAt"]) {
124
+ if (field !== "lastHeartbeatAt" && data[field] == null)
125
+ continue;
126
+ const timestamp = toMs(data[field]);
127
+ if (timestamp == null)
128
+ return null;
129
+ data[field] = timestamp;
130
+ }
131
+ return {
132
+ v: 2,
133
+ table: "Presence",
134
+ id: agentId,
135
+ data,
136
+ updatedAt: new Date(cursor).toISOString(),
137
+ originatorInstanceId: instanceId,
138
+ };
139
+ }