@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
@@ -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
+ }
@@ -308,12 +308,17 @@ export function readLaunchctlJobState(label, list) {
308
308
  res = list(label);
309
309
  }
310
310
  catch {
311
- return { registered: false, pid: null, lastExitStatus: null };
311
+ return { registered: false, readable: false, pid: null, lastExitStatus: null };
312
312
  }
313
+ // 113 is launchd's "service not found": an ANSWER that the job is not
314
+ // loaded. Any other non-zero code is a failed lookup, which must not be read
315
+ // as "not loaded" by a caller that acts on the answer (flair#3067).
316
+ if (res.code === 113)
317
+ return { registered: false, readable: true, pid: null, lastExitStatus: null };
313
318
  if (res.code !== 0)
314
- return { registered: false, pid: null, lastExitStatus: null };
319
+ return { registered: false, readable: false, pid: null, lastExitStatus: null };
315
320
  const { pid, lastExitStatus } = parseLaunchctlList(res.stdout);
316
- return { registered: true, pid, lastExitStatus };
321
+ return { registered: true, readable: true, pid, lastExitStatus };
317
322
  }
318
323
  /**
319
324
  * Which PID to treat as "the process serving this instance".
@@ -400,6 +405,7 @@ export function assessLaunchdManagement(input) {
400
405
  return { state: "no-service", detail: `no launchd service is registered for this instance (${plistPath})` };
401
406
  }
402
407
  const job = readLaunchctlJobState(label, list);
408
+ const jobLoaded = !job.readable ? "unknown" : job.registered ? "loaded" : "not-loaded";
403
409
  const diagnose = input.diagnose ?? ((p) => diagnoseLaunchdPlistPaths(p));
404
410
  const detachedRemedy = () => {
405
411
  const stale = diagnose(plistPath);
@@ -416,6 +422,7 @@ export function assessLaunchdManagement(input) {
416
422
  return {
417
423
  state: "detached",
418
424
  label,
425
+ jobLoaded,
419
426
  detail: `the launchd service ${label} is registered on disk but not loaded, so launchd is not managing this instance.${because}`,
420
427
  remedy,
421
428
  };
@@ -428,6 +435,7 @@ export function assessLaunchdManagement(input) {
428
435
  return {
429
436
  state: "detached",
430
437
  label,
438
+ jobLoaded,
431
439
  detail: `the launchd job ${label} is loaded but not running, so whatever is serving this instance was not started by launchd.${exit}${because}`,
432
440
  remedy,
433
441
  };
@@ -437,6 +445,7 @@ export function assessLaunchdManagement(input) {
437
445
  return {
438
446
  state: "detached",
439
447
  label,
448
+ jobLoaded,
440
449
  detail: `this instance is served by process ${instancePid}, but launchd's job ${label} is process ${job.pid} — ` +
441
450
  `the running instance is not the one launchd manages.${because}`,
442
451
  remedy,
@@ -452,6 +461,7 @@ export function assessLaunchdManagement(input) {
452
461
  return {
453
462
  state: "unverified",
454
463
  label,
464
+ jobLoaded,
455
465
  detail: `launchd job ${label} is running as process ${job.pid}, but the process serving this instance could not be ` +
456
466
  "identified (no live hdb.pid, and no listener found on its port), so launchd management is NOT verified",
457
467
  remedy: ["flair restart"],
@@ -462,6 +472,7 @@ export function assessLaunchdManagement(input) {
462
472
  return {
463
473
  state: "managed",
464
474
  label,
475
+ jobLoaded,
465
476
  detail: `launchd job ${label} is running as process ${job.pid}`,
466
477
  launchdPid: job.pid,
467
478
  servingPid: instancePid,
@@ -486,14 +486,15 @@ export function buildMcpOAuthConfigBlock(params) {
486
486
  },
487
487
  mcp: {
488
488
  // flair#1152: whole-token env reference — same flag flair's in-process
489
- // route gates on. ASYMMETRY (load-bearing, measured on oauth 2.5.0):
490
- // the component's coerceConfigBoolean accepts ONLY "true"/"false" and
491
- // DELETES any other string (unresolved placeholder, "1", "yes",
492
- // garbage) so its disabled default applies; flair's mcpOAuthEnabled()
493
- // (resources/mcp-oauth-flag.ts) accepts 1/true/yes/on. So "true" is
494
- // the one value that enables BOTH; "1"/"yes"/"on" flip flair's /mcp
495
- // handler on while the component AS stays off (fail-closed broken-on:
496
- // all 401, no AS advertised); garbage/unset disable both. On oauth
489
+ // route gates on. ASYMMETRY (load-bearing, measured on
490
+ // @harperfast/oauth 2.9.0): the component's coerceConfigBoolean trims
491
+ // and lowercases, mapping "true"/"false" to a boolean, and
492
+ // normalizeBooleanField deletes strings it cannot coerce (unresolved
493
+ // placeholder, "1", "yes", garbage), so its disabled default applies
494
+ // (dist/lib/config.js); flair's mcpOAuthEnabled()
495
+ // (resources/mcp-oauth-flag.ts) accepts 1/true/yes/on. Both readers
496
+ // accept "true". "1"/"yes"/"on" leave the component AS off; /mcp is
497
+ // not mounted. Garbage and an unset variable disable both. On oauth
497
498
  // <2.5.0 there is NO normalization and an unresolved placeholder is a
498
499
  // truthy string (fail-open) — which is why the resolved-version
499
500
  // assertion in mcp-oauth-boot-safety.test.ts exists. If component
@@ -940,13 +941,11 @@ export function buildSecretsBundle(params) {
940
941
  throw new IdpRedirectOriginError(envPrefix);
941
942
  }
942
943
  return {
943
- // "true" is the ONLY value both readers of this flag accept (flair#1152,
944
- // measured against oauth 2.5.0): flair's strict mcpOAuthEnabled() takes
945
- // 1/true/yes/on, but the component's coerceConfigBoolean takes ONLY
946
- // "true"/"false" and DELETES anything else (disabled default applies).
947
- // Staging "1" here would flip flair's /mcp handler ON while the
948
- // component's AS stays OFF — fail-closed but broken-on (every request
949
- // 401s, no AS is advertised). Keep this "true".
944
+ // "true" is the recommended value both readers of this flag accept
945
+ // (flair#1152): flair's strict mcpOAuthEnabled() takes 1/true/yes/on, but
946
+ // the component's coerceConfigBoolean maps only true/false strings
947
+ // (trimmed, any case) to a boolean and returns undefined otherwise, and
948
+ // normalizeBooleanField then deletes the field (disabled default applies).
950
949
  FLAIR_MCP_OAUTH: "true",
951
950
  FLAIR_MCP_ISSUER: params.issuer.replace(/\/+$/, ""),
952
951
  [`${envPrefix}_CLIENT_ID`]: params.idpClientId,
@@ -26,9 +26,11 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
26
26
  "retrievalCount",
27
27
  "lastRetrieved",
28
28
  "usageCount",
29
+ "writeBackWriteId",
29
30
  "promotionStatus",
30
31
  "promotedAt",
31
32
  "promotedBy",
33
+ "promotionContentHash",
32
34
  "archived",
33
35
  "archivedAt",
34
36
  "archivedBy",