@tpsdev-ai/flair 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -36,6 +36,7 @@
36
36
  * reads, `kill(pid, 0)`, the health probe, the start-time readers) live in
37
37
  * `src/cli.ts`, so every branch here is unit-testable without a daemon.
38
38
  */
39
+ import { REFUSED_CODES } from "./connect-phase.js";
39
40
  /**
40
41
  * Map the errno from a failed `kill(pid, 0)` to a `PidLiveness`. Pure so the
41
42
  * adapter's errno handling is unit-testable.
@@ -339,7 +340,7 @@ export function isFlairHealthBody(body) {
339
340
  */
340
341
  export function classifyHealthProbe(input) {
341
342
  if (input.kind === "network-error") {
342
- if (input.code === "ECONNREFUSED" || input.code === "ConnectionRefused") {
343
+ if (input.code !== undefined && REFUSED_CODES.includes(input.code)) {
343
344
  return { kind: "refused" };
344
345
  }
345
346
  return { kind: "unreachable" };
@@ -13,6 +13,7 @@
13
13
  * GET; later failures (token, hub POST, local Peer write) keep their
14
14
  * own messages unless the body is specifically a missing pairing role.
15
15
  */
16
+ import { apiErrorRawBody } from "./auth-resolve.js";
16
17
  export const FEDERATION_INSTANCE_PATH = "/FederationInstance";
17
18
  export const FEDERATION_PAIR_LOCAL_ACCESS_ERROR_NAME = "FederationPairLocalAccessError";
18
19
  export const FEDERATION_PAIR_HUB_ACCESS_ERROR_NAME = "FederationPairHubAccessError";
@@ -41,6 +42,9 @@ export class FederationPairHubAccessError extends Error {
41
42
  }
42
43
  }
43
44
  function errorText(err) {
45
+ const body = apiErrorRawBody(err);
46
+ if (body)
47
+ return body;
44
48
  if (err instanceof Error)
45
49
  return err.message;
46
50
  if (typeof err === "object" && err && "message" in err) {
@@ -0,0 +1,283 @@
1
+ /**
2
+ * federation-retry-queue.ts — the generic-Memory sender's retry bookkeeping.
3
+ *
4
+ * Pure and DB-free, so the backoff and the row transitions are unit-testable.
5
+ * `runFederationSyncOnce` (src/commands/federation.ts) reads and writes the
6
+ * `FederationRetry` table through its local operations endpoint; this module
7
+ * decides what a refusal means for one row.
8
+ *
9
+ * The receiver's response names each refused record and its reason
10
+ * (`refused`). A reason in {@link MEMORY_RETRY_REASONS} may clear on a later
11
+ * offer, so the sender keeps one pending row for that (hub, Memory, record)
12
+ * tuple and offers the record again on a later cycle while that pending row is
13
+ * due and the source row is still eligible, independent of its own cursor. A
14
+ * pending row can become private, disappear or fail validation before it is
15
+ * offered again. Any other reason is final: an existing pending row becomes
16
+ * `refused_terminal`, and the retry path in one sender run does not select a
17
+ * terminal row again (a later row update can still select it through the
18
+ * ordinary cursor; concurrent sender runs for one peer are not serialized — a
19
+ * separate issue).
20
+ */
21
+ import { isRetryResolution, retryEntryKey, retryRowProblem } from "./federation-retry-row.js";
22
+ /**
23
+ * The global retryable names the sender recognizes. Mirrors the
24
+ * `retryable` entries of SKIP_REASON_CLASS in resources/federation-classify.ts;
25
+ * not every name is raised by the generic Memory path
26
+ * (`presence_agent_not_replicated` comes from the Presence receipt path).
27
+ * test/unit/federation-retry-queue.test.ts fails when the two lists differ.
28
+ */
29
+ export const MEMORY_RETRY_REASONS = new Set([
30
+ "future_timestamp",
31
+ "unknown_originator_key",
32
+ "merge_target_changed",
33
+ "merge_target_busy",
34
+ "merge_error",
35
+ "presence_agent_not_replicated",
36
+ ]);
37
+ /** Every `lastReason` a pending Memory row may hold: a retryable refusal name,
38
+ * or the sender's own `retry_unknown`. */
39
+ export const MEMORY_PENDING_REASONS = new Set([
40
+ ...MEMORY_RETRY_REASONS,
41
+ "retry_unknown",
42
+ ]);
43
+ /** Every field the FederationRetry schema declares, in schema order. */
44
+ export const RETRY_ROW_FIELDS = [
45
+ "id",
46
+ "peerId",
47
+ "table",
48
+ "recordId",
49
+ "state",
50
+ "firstRefusedAt",
51
+ "attempts",
52
+ "episodeId",
53
+ "recordFingerprint",
54
+ "lastReason",
55
+ "lastAttemptSyncId",
56
+ "lastAttemptAt",
57
+ "completedAt",
58
+ "resolution",
59
+ "bound",
60
+ "createdAt",
61
+ "updatedAt",
62
+ ];
63
+ /**
64
+ * The fields a terminal outcome sets (terminalRetryRow) that a pending row
65
+ * leaves null. The operations-API `upsert` merges into the stored row, so the
66
+ * pending-row builders below write each of them as null.
67
+ */
68
+ export const RETRY_TERMINAL_FIELDS = ["resolution", "completedAt", "bound"];
69
+ /**
70
+ * Wait before offering a pending row again, by the number of attempts it has
71
+ * reserved. The first re-offer is immediate (the lock or change that refused
72
+ * it may already be gone); later ones back off. The last entry repeats.
73
+ */
74
+ export const MEMORY_RETRY_BACKOFF_MS = [0, 30_000, 300_000, 1_800_000];
75
+ export function retryBackoffMs(attempts) {
76
+ const index = Math.min(Math.max(attempts, 1), MEMORY_RETRY_BACKOFF_MS.length) - 1;
77
+ return MEMORY_RETRY_BACKOFF_MS[index];
78
+ }
79
+ export function retryOfferProblem(row, table = "Memory") {
80
+ if (row.state !== "pending")
81
+ return "wrong_state";
82
+ if (row.table !== table)
83
+ return "wrong_table";
84
+ if (typeof row.peerId !== "string" || typeof row.recordId !== "string")
85
+ return "id_mismatch";
86
+ try {
87
+ if (retryEntryKey(row.peerId, row.table, row.recordId) !== row.id)
88
+ return "id_mismatch";
89
+ }
90
+ catch {
91
+ return "id_mismatch";
92
+ }
93
+ // The reader and the transition call a pending row carrying an outcome
94
+ // malformed; the sender selects rows from the same table, so it applies
95
+ // that shared rule rather than deciding on its own fields alone.
96
+ const malformed = retryRowMalformedness(row);
97
+ if (malformed !== null) {
98
+ switch (malformed.problem) {
99
+ case "outcome_mismatch": return "outcome_mismatch";
100
+ case "id_mismatch": return "id_mismatch";
101
+ case "unknown_state": return "wrong_state";
102
+ case "unknown_reason": return "unknown_reason";
103
+ }
104
+ }
105
+ // `retry_unknown` is legitimate here and is not a SkipReason, so the sender
106
+ // keeps its own stricter pending-reason list.
107
+ if (typeof row.lastReason !== "string" || !MEMORY_PENDING_REASONS.has(row.lastReason))
108
+ return "unknown_reason";
109
+ return null;
110
+ }
111
+ /**
112
+ * Why a stored row breaks a sender convention and which field breaks it, or
113
+ * null when it keeps them. Unlike {@link retryOfferProblem} this does not
114
+ * require state `pending`: an outcome write reads the stored row in whatever
115
+ * state it is.
116
+ *
117
+ * The rules are the ones the sender already uses: `retryRowProblem`
118
+ * (src/lib/federation-retry-row.ts) with the sender's pending-reason list, and
119
+ * `retryRowConfirmation` for the terminal fields a pending row must leave
120
+ * null (flair#2882).
121
+ */
122
+ export function retryRowMalformedness(row) {
123
+ const isKnownReason = (value) => typeof value === "string" && MEMORY_PENDING_REASONS.has(value);
124
+ const problem = retryRowProblem(row, isKnownReason);
125
+ if (problem === "id_mismatch")
126
+ return { problem, field: "id" };
127
+ if (problem === "unknown_state")
128
+ return { problem, field: "state" };
129
+ if (problem === "unknown_reason")
130
+ return { problem, field: "lastReason" };
131
+ if (row.state === "pending") {
132
+ // The sender's pending rows always carry a reason it recognizes.
133
+ if (!isKnownReason(row.lastReason))
134
+ return { problem: "unknown_reason", field: "lastReason" };
135
+ // The read-back's terminal-field rule applies to every stored pending row,
136
+ // whether or not retryRowProblem also names an outcome: it does not check
137
+ // completedAt.
138
+ const field = retryRowConfirmation({}, row);
139
+ if (field !== null)
140
+ return { problem: "outcome_mismatch", field };
141
+ }
142
+ if (problem === "outcome_mismatch") {
143
+ return { problem, field: !isRetryResolution(row.resolution) ? "resolution" : "bound" };
144
+ }
145
+ return null;
146
+ }
147
+ /** The pending rows whose backoff has elapsed at `nowMs`. A malformed row is excluded by this retry selector. */
148
+ export function dueRetryRows(rows, nowMs, table = "Memory") {
149
+ return rows.filter((row) => {
150
+ const problem = retryOfferProblem(row, table);
151
+ if (problem !== null) {
152
+ // Reported by the caller, not silently treated as absent.
153
+ return false;
154
+ }
155
+ const attempts = typeof row.attempts === "number" && Number.isSafeInteger(row.attempts) && row.attempts > 0 ? row.attempts : 1;
156
+ const last = Date.parse(row.lastAttemptAt ?? "");
157
+ // A pending row with no readable last attempt is due: the alternative is
158
+ // never offering it again.
159
+ if (!Number.isFinite(last))
160
+ return true;
161
+ return nowMs >= last + retryBackoffMs(attempts);
162
+ });
163
+ }
164
+ /**
165
+ * The row to write for a retryable refusal. A first refusal creates a pending
166
+ * row with `attempts: 1`; a later one keeps `firstRefusedAt` and `createdAt`,
167
+ * increments `attempts` and moves `lastAttemptAt`, unless that offer already
168
+ * reserved its attempt before sending. `attempts` counts reserved attempts
169
+ * within one sender run per peer at a time, not wire sends; concurrent sender
170
+ * runs for one peer are not serialized (a separate issue).
171
+ */
172
+ export function retryRowForRefusal(input) {
173
+ const id = retryEntryKey(input.peerId, "Memory", input.recordId);
174
+ const prior = input.existing ?? null;
175
+ const priorAttempts = prior && typeof prior.attempts === "number" && Number.isSafeInteger(prior.attempts) && prior.attempts > 0
176
+ ? prior.attempts
177
+ : 0;
178
+ const row = {
179
+ id,
180
+ peerId: input.peerId,
181
+ table: "Memory",
182
+ recordId: input.recordId,
183
+ state: "pending",
184
+ firstRefusedAt: prior?.firstRefusedAt ?? input.nowIso,
185
+ attempts: priorAttempts + (input.attemptReserved ? 0 : 1),
186
+ lastReason: input.reason,
187
+ lastAttemptAt: input.nowIso,
188
+ createdAt: prior?.createdAt ?? input.nowIso,
189
+ updatedAt: input.nowIso,
190
+ };
191
+ for (const field of RETRY_TERMINAL_FIELDS)
192
+ row[field] = null;
193
+ return row;
194
+ }
195
+ /**
196
+ * The row that reserves one offer attempt before a pending row is sent. The
197
+ * caller persists it; an unconfirmed send keeps it, so the next cycle waits
198
+ * out this attempt's backoff instead of re-offering at once.
199
+ */
200
+ export function retryRowForAttempt(row, nowIso) {
201
+ const id = retryEntryKey(row.peerId, "Memory", row.recordId);
202
+ const priorAttempts = typeof row.attempts === "number" && Number.isSafeInteger(row.attempts) && row.attempts > 0
203
+ ? row.attempts
204
+ : 0;
205
+ const out = {
206
+ id,
207
+ peerId: row.peerId,
208
+ table: "Memory",
209
+ recordId: row.recordId,
210
+ state: "pending",
211
+ firstRefusedAt: row.firstRefusedAt ?? nowIso,
212
+ attempts: priorAttempts + 1,
213
+ lastAttemptAt: nowIso,
214
+ createdAt: row.createdAt ?? nowIso,
215
+ updatedAt: nowIso,
216
+ };
217
+ if (typeof row.lastReason === "string")
218
+ out.lastReason = row.lastReason;
219
+ for (const field of RETRY_TERMINAL_FIELDS)
220
+ out[field] = null;
221
+ return out;
222
+ }
223
+ /** The fields a persisted retry row must carry back for the obligation to hold. */
224
+ const CONFIRM_FIELDS = [
225
+ "id",
226
+ "peerId",
227
+ "table",
228
+ "recordId",
229
+ "state",
230
+ "attempts",
231
+ "lastReason",
232
+ "lastAttemptAt",
233
+ "firstRefusedAt",
234
+ "createdAt",
235
+ "resolution",
236
+ "completedAt",
237
+ "updatedAt",
238
+ "bound",
239
+ ];
240
+ /**
241
+ * The first of `id`, `peerId`, `table`, `recordId`, `state`, `attempts`,
242
+ * `lastReason`, `lastAttemptAt`, `firstRefusedAt`, `createdAt`, `resolution`,
243
+ * `completedAt`, `updatedAt` and `bound` (CONFIRM_FIELDS, in that order) that
244
+ * the written record carries and the stored row does not echo; then, for a
245
+ * stored row in state `pending`, the first of RETRY_TERMINAL_FIELDS it holds a
246
+ * non-null value for, whether or not the record names it; `row` when the
247
+ * stored row is null; otherwise null. A read-back that only agrees on `state`
248
+ * and `lastReason` can hide an attempt that was never incremented.
249
+ */
250
+ export function retryRowConfirmation(record, stored) {
251
+ if (stored === null)
252
+ return "row";
253
+ for (const field of CONFIRM_FIELDS) {
254
+ if (!(field in record))
255
+ continue;
256
+ const expected = record[field] ?? null;
257
+ const actual = stored[field] ?? null;
258
+ if (actual !== expected)
259
+ return field;
260
+ }
261
+ if (stored.state === "pending") {
262
+ for (const field of RETRY_TERMINAL_FIELDS) {
263
+ if ((stored[field] ?? null) !== null)
264
+ return field;
265
+ }
266
+ }
267
+ return null;
268
+ }
269
+ /** A pending row's terminal transition, carrying only declared fields. */
270
+ export function terminalRetryRow(row, resolution, nowIso) {
271
+ const out = { id: row.id };
272
+ for (const field of RETRY_ROW_FIELDS) {
273
+ const value = row[field];
274
+ if (value !== undefined)
275
+ out[field] = value;
276
+ }
277
+ out.state = "terminal";
278
+ out.resolution = resolution;
279
+ out.bound = null;
280
+ out.completedAt = nowIso;
281
+ out.updatedAt = nowIso;
282
+ return out;
283
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * federation-retry-row.ts — a federation retry row's key, outcome vocabulary
3
+ * and sender-convention check, in one module.
4
+ *
5
+ * Pure, DB-free and dependency-free: a resource imports it directly
6
+ * (resources/federation-retry-lib.ts re-exports it), and a src module that a
7
+ * resource imports must load no other module (test/unit/resource-src-purity-
8
+ * 1775.test.ts). The CLI build (src/) and the Harper resources share this one
9
+ * copy. The receiver's admin/read resources and the generic-Memory sender both
10
+ * classify rows with retryRowProblem: the retry selector excludes a malformed
11
+ * row, while an eligible cursor-selected source is still sent and its
12
+ * malformed retry row is left as stored. The reason vocabulary differs: the
13
+ * caller passes the predicate
14
+ * its own path uses (`isSkipReason` plus local reasons for a Harper resource;
15
+ * the sender's stricter pending-row list).
16
+ */
17
+ // ─── Key ───
18
+ /**
19
+ * Encode the (peerId, table, recordId) tuple as the row's primary key.
20
+ *
21
+ * A JSON array join, never a bare concatenation: a naive `${peerId}${table}
22
+ * ${recordId}` collides (peer `a` + table `bc` is peer `ab` + table `c`), and
23
+ * peer and record ids are arbitrary strings off the wire, including legacy
24
+ * `.content`-suffixed ids. JSON quotes and escapes each component, so distinct
25
+ * tuples encode to distinct strings and the components round-trip exactly.
26
+ *
27
+ * Every component must be a non-empty string; a missing component is a caller
28
+ * bug, not a row to write, so this THROWS rather than mint a malformed key.
29
+ */
30
+ export function retryEntryKey(peerId, table, recordId) {
31
+ for (const [name, value] of [
32
+ ["peerId", peerId],
33
+ ["table", table],
34
+ ["recordId", recordId],
35
+ ]) {
36
+ if (typeof value !== "string" || value.length === 0) {
37
+ throw new Error(`federation retry: ${name} must be a non-empty string`);
38
+ }
39
+ }
40
+ return JSON.stringify([peerId, table, recordId]);
41
+ }
42
+ /** Decode {@link retryEntryKey}'s output, or null when `id` is not a retry key. */
43
+ export function parseRetryEntryKey(id) {
44
+ let parsed;
45
+ try {
46
+ parsed = JSON.parse(id);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ if (!Array.isArray(parsed) || parsed.length !== 3)
52
+ return null;
53
+ const [peerId, table, recordId] = parsed;
54
+ if (typeof peerId !== "string" || typeof table !== "string" || typeof recordId !== "string")
55
+ return null;
56
+ if (peerId.length === 0 || table.length === 0 || recordId.length === 0)
57
+ return null;
58
+ return { peerId, table, recordId };
59
+ }
60
+ export const RETRY_RESOLUTIONS = new Set([
61
+ "merged",
62
+ "refused_terminal",
63
+ "source_deleted",
64
+ "source_ineligible",
65
+ "peer_unavailable",
66
+ "retry_exhausted",
67
+ ]);
68
+ export const RETRY_BOUNDS = new Set(["attempts", "age", "both"]);
69
+ export function isRetryResolution(value) {
70
+ return typeof value === "string" && RETRY_RESOLUTIONS.has(value);
71
+ }
72
+ export function isRetryBound(value) {
73
+ return typeof value === "string" && RETRY_BOUNDS.has(value);
74
+ }
75
+ export function retryRowProblem(row, isKnownReason) {
76
+ let expectedId = null;
77
+ try {
78
+ expectedId = retryEntryKey(row.peerId, row.table, row.recordId);
79
+ }
80
+ catch {
81
+ expectedId = null;
82
+ }
83
+ if (expectedId === null || row.id !== expectedId)
84
+ return "id_mismatch";
85
+ if (row.state !== "pending" && row.state !== "terminal")
86
+ return "unknown_state";
87
+ if (row.lastReason != null && !isKnownReason(row.lastReason))
88
+ return "unknown_reason";
89
+ if (row.state === "pending") {
90
+ if (row.resolution != null || row.bound != null)
91
+ return "outcome_mismatch";
92
+ }
93
+ else {
94
+ if (!isRetryResolution(row.resolution))
95
+ return "outcome_mismatch";
96
+ const exhausted = row.resolution === "retry_exhausted";
97
+ if (exhausted ? !isRetryBound(row.bound) : row.bound != null)
98
+ return "outcome_mismatch";
99
+ }
100
+ return null;
101
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * instruction-event-contract.ts — the shared reserved-event predicate
3
+ * (flair#2139 slice 3a). Kept in `src/lib` so both the OrgEvent resource and
4
+ * the `flair doctor` check import one definition without crossing the CLI
5
+ * build's rootDir.
6
+ */
7
+ export const RESERVED_EVENT_KINDS = Object.freeze(["soul.changed", "skill.changed"]);
8
+ export const RESERVED_EVENT_ID_PREFIX = "instruction-change:";
9
+ /** Whether a record carries a reserved kind or id prefix. Non-records are not reserved. */
10
+ export function isReservedEventRecord(record) {
11
+ if (record == null || typeof record !== "object" || Array.isArray(record))
12
+ return false;
13
+ const { kind, id } = record;
14
+ if (typeof kind === "string" && RESERVED_EVENT_KINDS.includes(kind))
15
+ return true;
16
+ return typeof id === "string" && id.startsWith(RESERVED_EVENT_ID_PREFIX);
17
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * instruction-event-doctor.ts — the `flair doctor` check for stored OrgEvents
3
+ * that carry a reserved marker but fail the reader rule
4
+ * (flair#2139 slice 3a).
5
+ *
6
+ * Main never refused reserved kinds or the `instruction-change:` id prefix, so
7
+ * a store may already hold rows that were written through the operations API.
8
+ * The reader rule is: the id carries the prefix, the kind is a reserved kind,
9
+ * the refId names an existing InstructionVersion, that version's id is the
10
+ * event id's suffix, and its subject type matches the kind.
11
+ *
12
+ * The decision is pure; the reads use the operations API and return null on a
13
+ * failed read (never an empty list).
14
+ */
15
+ import { RESERVED_EVENT_ID_PREFIX, RESERVED_EVENT_KINDS, isReservedEventRecord } from "./instruction-event-contract.js";
16
+ export const INSTRUCTION_EVENT_ROWS_SQL = "SELECT id, kind, refId FROM flair.OrgEvent";
17
+ export const INSTRUCTION_VERSION_ROWS_SQL = "SELECT id, subjectType FROM flair.InstructionVersion";
18
+ const KIND_SUBJECT = Object.freeze({
19
+ "soul.changed": "soul",
20
+ "skill.changed": "skill",
21
+ });
22
+ function instructionEventReaderFailure(event, version) {
23
+ const id = event.id;
24
+ const kind = event.kind;
25
+ if (typeof id !== "string" || !id.startsWith(RESERVED_EVENT_ID_PREFIX))
26
+ return "missing prefix";
27
+ if (typeof kind !== "string" || !RESERVED_EVENT_KINDS.includes(kind))
28
+ return "kind mismatch";
29
+ if (!version || typeof version.id !== "string")
30
+ return "no matching version";
31
+ if (version.id !== id.slice(RESERVED_EVENT_ID_PREFIX.length))
32
+ return "suffix mismatch";
33
+ if (version.subjectType !== KIND_SUBJECT[kind])
34
+ return "kind mismatch";
35
+ return null;
36
+ }
37
+ /** Whether a stored event satisfies the reader rule. */
38
+ export function instructionEventSatisfiesReaderRule(event, version) {
39
+ return instructionEventReaderFailure(event, version) === null;
40
+ }
41
+ /**
42
+ * Every stored event that carries a reserved marker but fails the reader rule,
43
+ * sorted by id. An event with neither marker is not an impostor.
44
+ */
45
+ function findInstructionEventFailures(events, versions) {
46
+ const byId = new Map();
47
+ for (const version of versions) {
48
+ if (typeof version.id === "string")
49
+ byId.set(version.id, version);
50
+ }
51
+ const impostors = [];
52
+ for (const event of events) {
53
+ const id = event.id;
54
+ if (!isReservedEventRecord(event))
55
+ continue;
56
+ const version = typeof event.refId === "string" ? byId.get(event.refId) : undefined;
57
+ const reason = instructionEventReaderFailure(event, version);
58
+ if (reason) {
59
+ impostors.push({ id: typeof id === "string" && id.length > 0 ? id : "(no id)", reason });
60
+ }
61
+ }
62
+ return impostors.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
63
+ }
64
+ export function findInstructionEventImpostors(events, versions) {
65
+ return findInstructionEventFailures(events, versions).map(({ id }) => id);
66
+ }
67
+ /** The doctor line for a stored impostor set: null when the store is clean. */
68
+ export function describeInstructionEventImpostors(events, versions) {
69
+ const impostors = findInstructionEventFailures(events, versions);
70
+ if (impostors.length === 0)
71
+ return null;
72
+ return `${impostors.length} stored OrgEvent ${impostors.length === 1 ? "row carries" : "rows carry"} a reserved kind or id but ${impostors.length === 1 ? "fails" : "fail"} the instruction-event reader rule: ${impostors.map(({ id, reason }) => `${id} (${reason})`).join(", ")}`;
73
+ }
74
+ /** Read both tables through the ops API; null when either read fails. */
75
+ export async function readInstructionEventTables(args) {
76
+ const fetchImpl = args.fetchImpl ?? fetch;
77
+ const read = async (sql) => {
78
+ try {
79
+ const res = await fetchImpl(args.opsUrl, {
80
+ method: "POST",
81
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
82
+ body: JSON.stringify({ operation: "sql", sql }),
83
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
84
+ });
85
+ if (!res.ok)
86
+ return null;
87
+ const data = await res.json();
88
+ return Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ };
94
+ const events = await read(INSTRUCTION_EVENT_ROWS_SQL);
95
+ const versions = await read(INSTRUCTION_VERSION_ROWS_SQL);
96
+ if (events === null || versions === null)
97
+ return null;
98
+ return {
99
+ events: events,
100
+ versions: versions,
101
+ };
102
+ }