@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
@@ -26,10 +26,18 @@
26
26
  * migration nullable String field — no new schema needed) to a value that
27
27
  * encodes the migration id, so "is this row done" is answered entirely by
28
28
  * re-reading the row itself (invariant IV: state lives IN the data).
29
+ *
30
+ * The write runs under the row's per-id Memory write lock (flair#2478 slice
31
+ * 3b): one non-waiting acquisition per row, around the write-back's read,
32
+ * decision, write and commit. A held row, an unresolved write outcome on it or
33
+ * a table with no lock writes nothing and is logged; the next scan decides
34
+ * whether the row is still pending.
29
35
  */
30
36
  import { databases } from "harper";
31
37
  import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
32
38
  import { txnPausePoint } from "../txn-pause-point.js";
39
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
40
+ import { BatchOutcomeError } from "./types.js";
33
41
  export const SYNTHETIC_MIGRATION_ID = "synthetic-ci-schema-stamp";
34
42
  export const RESERVED_TEST_AGENT_ID = "__flair_migration_synthetic_test_agent__";
35
43
  export const SYNTHETIC_TARGET_MARKER = `${SYNTHETIC_MIGRATION_ID}-done`;
@@ -70,6 +78,12 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable, writ
70
78
  n++;
71
79
  return n;
72
80
  },
81
+ async checkUnconfirmed(id) {
82
+ const row = await getTable().get(id);
83
+ if (!row)
84
+ return "no-row";
85
+ return row.source === SYNTHETIC_TARGET_MARKER ? "at-target" : "pending";
86
+ },
73
87
  async run(batchSize) {
74
88
  const table = getTable();
75
89
  const candidates = [];
@@ -77,23 +91,75 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable, writ
77
91
  candidates.push(row);
78
92
  }
79
93
  const touchedIds = [];
94
+ const unconfirmedIds = [];
80
95
  for (const row of candidates) {
81
96
  const id = String(row.id ?? "");
82
97
  if (!id)
83
98
  continue;
84
- const outcome = await writeBackCommittedRow(table, id, (existing) => {
85
- if (!existing || existing.agentId !== RESERVED_TEST_AGENT_ID)
86
- return { skip: true };
87
- if (existing.source === SYNTHETIC_TARGET_MARKER)
88
- return { skip: true }; // already stamped — idempotent skip
89
- // Only `source`: an incremental update, never a
90
- // full-row put of the row read above (flair#2470).
91
- return { update: { source: SYNTHETIC_TARGET_MARKER } };
92
- }, { label: "synthetic-test-migration", pausePre: () => txnPausePoint("synthetic-test-pre"), pausePoint: () => txnPausePoint("synthetic-test"), expectedRow: row });
93
- if (!("skip" in outcome))
94
- touchedIds.push(id);
99
+ // flair#2840: the write-back reports an attempt whose committed effect
100
+ // its post-commit verification read did not show. The row is counted as
101
+ // done only if a later attempt's write is verified; otherwise it is
102
+ // reported by id.
103
+ let ownUnconfirmed = false;
104
+ try {
105
+ // flair#2478 slice 3b: an automatic writer. It takes the id's per-id
106
+ // Memory write lock with one non-waiting acquisition, so its read,
107
+ // decision, write and commit sit on one committed basis while an owner
108
+ // write holds the id. When the lock is refused (a held id, an id with an
109
+ // unresolved write outcome, or a table with no lock), nothing is written
110
+ // here and the refusal is reported. A write this attempt made but could
111
+ // not confirm is reported as unconfirmed (above) and may have committed.
112
+ // Either way, the next scan decides whether the row is still pending.
113
+ const locked = await withMemoryWriteLockOnce(table.primaryStore, [id], async () => {
114
+ const result = await writeBackCommittedRow(table, id, (existing) => {
115
+ if (!existing || existing.agentId !== RESERVED_TEST_AGENT_ID)
116
+ return { skip: true };
117
+ if (existing.source === SYNTHETIC_TARGET_MARKER)
118
+ return { skip: true }; // already stamped — idempotent skip
119
+ // Only `source`: an incremental update, never a
120
+ // full-row put of the row read above (flair#2470).
121
+ return { idempotent: true, update: { source: SYNTHETIC_TARGET_MARKER } };
122
+ }, {
123
+ label: "synthetic-test-migration",
124
+ pausePre: () => txnPausePoint("synthetic-test-pre"),
125
+ pausePoint: () => txnPausePoint("synthetic-test"),
126
+ pauseAfterStage: () => txnPausePoint("synthetic-test-staged"),
127
+ confirmPoint: () => txnPausePoint("synthetic-test-confirm"),
128
+ expectedRow: row,
129
+ onUnconfirmed: () => { ownUnconfirmed = true; },
130
+ });
131
+ // Test-only: the write-back committed and the lock is still held.
132
+ const committed = txnPausePoint("synthetic-test-committed");
133
+ if (committed)
134
+ await committed;
135
+ return result;
136
+ }, { phase: "synthetic-test-migration" });
137
+ if (locked.kind !== "done") {
138
+ console.warn("[synthetic-test-migration] %s: the per-id write lock answered %s; the row is left for the next scan", id, locked.kind);
139
+ continue;
140
+ }
141
+ if ("skip" in locked.value) {
142
+ // A skip is not a write this run verified. If it follows an attempt
143
+ // whose committed effect was unconfirmed, the row is reported as
144
+ // unconfirmed; otherwise this run wrote nothing to the row
145
+ // (flair#2840).
146
+ if (ownUnconfirmed)
147
+ unconfirmedIds.push(id);
148
+ }
149
+ else
150
+ touchedIds.push(id);
151
+ }
152
+ catch (err) {
153
+ // flair#2840: carry this batch's outcomes on the error — the runner
154
+ // has no RunBatchResult to read when run() throws.
155
+ if (ownUnconfirmed)
156
+ unconfirmedIds.push(id);
157
+ throw new BatchOutcomeError({ touchedIds, unconfirmedIds }, err);
158
+ }
95
159
  }
96
- return { processed: touchedIds.length, touchedIds };
160
+ return unconfirmedIds.length > 0
161
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
162
+ : { processed: touchedIds.length, touchedIds };
97
163
  },
98
164
  };
99
165
  }
@@ -6,4 +6,29 @@
6
6
  * refinements). Every migration registered in resources/migrations/registry.ts
7
7
  * implements the `Migration` interface below.
8
8
  */
9
- export {};
9
+ /**
10
+ * How many of a run's unconfirmed row ids are reported. During a run the
11
+ * runner holds the ids recorded in this run, and the listed ids it carried in,
12
+ * in a Set; the list written to the progress record and the state file is
13
+ * capped at this many. The count is not capped (flair#2840).
14
+ */
15
+ export const UNCONFIRMED_IDS_LIMIT = 100;
16
+ /**
17
+ * Thrown by a migration's run() on the paths that wrap the failure ending a
18
+ * batch (flair#2840): the synthetic write-back, the visibility backfill and
19
+ * embedding-stamp's `.content`-suffix retry read. It carries that batch's
20
+ * outcomes so far — the rows it touched and the rows it recorded as
21
+ * unconfirmed — so the runner can merge them into the unconfirmed record even
22
+ * though no {@link RunBatchResult} is returned. A throw from a path that does
23
+ * not wrap its batch carries no outcomes.
24
+ */
25
+ export class BatchOutcomeError extends Error {
26
+ touchedIds;
27
+ unconfirmedIds;
28
+ constructor(outcome, cause) {
29
+ super(cause?.message ?? String(cause), { cause });
30
+ this.name = "BatchOutcomeError";
31
+ this.touchedIds = [...outcome.touchedIds];
32
+ this.unconfirmedIds = [...outcome.unconfirmedIds];
33
+ }
34
+ }
@@ -4,8 +4,7 @@
4
4
  * which never stamped `visibility` at all. riskClass 'derived-only':
5
5
  * `visibility` here is a derived stamp recomputable at any time from
6
6
  * `durability` (which remains on the row, untouched, forever) — never the
7
- * only copy of anything (invariant I) — and this migration only ever writes
8
- * into a field that is CURRENTLY EMPTY, so the cheapest posture applies:
7
+ * only copy of anything (invariant I). The plan requires an empty visibility:
9
8
  * metadata-only snapshot, no content-hash gate (row-count + stamp
10
9
  * convergence only, same as `embedding-stamp`/`graph-heal`).
11
10
  *
@@ -45,13 +44,8 @@
45
44
  * definition is the safer contract than a shared import with a landmine
46
45
  * behind it. If this rule ever changes, both copies must change together.
47
46
  *
48
- * NEVER OVERWRITES an existing `visibility` value — that is an explicit
49
- * author decision (their own call, even if it disagrees with what this
50
- * migration would have derived). Only rows where `visibility` is
51
- * null/undefined are eligible, and `run()` below re-verifies that on a
52
- * freshly-read record immediately before writing (the actual enforcement
53
- * of "never overwrite" — see the write-gate comment there), independent of
54
- * how precisely the candidate-selection query below narrowed things.
47
+ * The per-id Memory lock shared with owner PUT/PATCH protects the missing-
48
+ * visibility decision and write. Writers outside that lock are not serialized.
55
49
  *
56
50
  * THE CANDIDATE QUERY — why it looks different from `embedding-stamp`'s:
57
51
  * `visibility` is declared in `schemas/memory.graphql` but NOT `@indexed`
@@ -69,11 +63,11 @@
69
63
  * find. A NEGATED comparator does match them (`undefined !== "private"` is
70
64
  * true), so the pending condition here is `visibility not_equals "private"
71
65
  * AND visibility not_equals "shared"` — no separate `equals: null` leg
72
- * needed (unlike `embedding-stamp`, whose write path can leave an
73
- * intermediate explicit-null state on a failed HTTP regen; this migration's
74
- * write is a single in-process read-modify-write that either fully
75
- * succeeds or leaves the row in its exact prior state, so there is no
76
- * intermediate state to add a leg for). This exact `not_equal`-covers-
66
+ * needed (unlike `embedding-stamp`, whose pending condition carries an
67
+ * `equals: null` leg for rows whose `embeddingModel` is an explicit null; this
68
+ * migration's write stages only `{ visibility }` through an incremental
69
+ * `update`, so it creates no explicit-null state to add a leg for). This exact
70
+ * `not_equal`-covers-
77
71
  * absent-and-null-and-nothing-else-with-the-value-itself semantics is
78
72
  * already relied on, in production, by `resources/memory-read-scope.ts`'s
79
73
  * cross-agent read-scope condition on this SAME field (`visibility !=
@@ -100,29 +94,25 @@
100
94
  * don't-brick (invariant II), and worth surfacing loudly if it ever
101
95
  * happens, since a garbage `visibility` value is itself a bug worth seeing.
102
96
  *
103
- * THE WRITE PATH — deliberately NOT `embedding-stamp`'s loopback-HTTP
104
- * `PUT /Memory/:id` trick. That mechanism exists ONLY because
105
- * `embedding-stamp` needs `resources/Memory.ts`'s SUBCLASS override (the
106
- * `content.content && !content.embedding` regen branch) to actually fire,
107
- * and the raw `databases.flair.Memory` reference (what this migration and
108
- * that one both get via their table accessor) resolves to the RAW
109
- * underlying table, silently skipping every subclass override — see that
110
- * file's module doc for the full, empirically-confirmed mechanism. This
111
- * migration needs NO subclass business logic (no dedup, no regen, no
112
- * provenance stamping, no rate limiting) — it is a narrow, single-field
113
- * patch, which is exactly the shape `resources/table-helpers.ts`'s
114
- * `patchRecord` documents and this codebase already uses directly against
115
- * the RAW table for the same kind of narrow metadata write:
116
- * `resources/auth-middleware.ts`'s `backfillEmbedding()` (patches
117
- * `embedding`), `resources/MemoryReflect.ts` and `resources/Memory.ts`
118
- * itself (both patch `lastReflected` this exact way). Per that file's own
119
- * warning, Harper's raw `.put()` is FULL RECORD REPLACEMENT — a partial
120
- * object silently deletes every field not included — so `run()` below
121
- * always spreads the freshly-read `existing` record before adding
122
- * `visibility`, the same read-modify-write shape `patchRecord` implements
123
- * (inlined here rather than calling that helper directly only because
124
- * `run()` already needs its own `.get()` for the write-gate check above,
125
- * and re-using that same read avoids a second, redundant round-trip).
97
+ * THE WRITE PATH — a single-field incremental `update`, not
98
+ * `embedding-stamp`'s loopback HTTP request. For ordinary row ids,
99
+ * embedding-stamp sends a loopback `PATCH /Memory/:id` with
100
+ * `{ embedding: null, embeddingModel: null }`, invoking Memory.patch()'s
101
+ * re-embed path, because it needs `resources/Memory.ts`'s SUBCLASS logic: the raw
102
+ * `databases.flair.Memory` reference (what this migration and that one both
103
+ * get via their table accessor) resolves to the RAW underlying table, silently
104
+ * skipping every subclass override — see that file's module doc for the full,
105
+ * empirically-confirmed mechanism. This migration needs NO subclass business
106
+ * logic (no dedup, no regen, no provenance stamping, no rate limiting): it
107
+ * writes only `visibility`, through `writeBackCommittedRow`
108
+ * (`resources/write-back.ts`), whose `update` plan calls the table's
109
+ * incremental `update` with `{ visibility }` and refuses when the table has
110
+ * none (`applyFieldUpdate`). Nothing spreads the stored row into a full-record
111
+ * `put`, so the full-record-replacement hazard `resources/table-helpers.ts`'s
112
+ * `patchRecord` warns about does not arise here. `run()` hands the candidate
113
+ * from its search to the write-back as `expectedRow`; the write-back re-reads
114
+ * the row inside its owned transaction, requires the row's identity fields to
115
+ * still match that basis, and confirms the committed row after staging.
126
116
  *
127
117
  * NO `recheckPending()`: that hook exists specifically to catch a stale
128
118
  * SECONDARY INDEX diverging from live values (flair#807, `embedding-stamp`
@@ -134,12 +124,17 @@
134
124
  * omitting it.
135
125
  */
136
126
  import { databases } from "harper";
137
- import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
138
127
  import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
139
128
  import { txnPausePoint } from "../txn-pause-point.js";
129
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
130
+ import { BatchOutcomeError } from "./types.js";
140
131
  function defaultMemoryTable() {
141
132
  return databases.flair.Memory;
142
133
  }
134
+ /** The per-id lock the backfill's writes run under (flair#2478 slice 2). */
135
+ function defaultMemoryLockStore() {
136
+ return databases?.flair?.Memory?.primaryStore;
137
+ }
143
138
  export const VISIBILITY_BACKFILL_ID = "visibility-backfill";
144
139
  /**
145
140
  * flair#509's rule, reused verbatim (see module doc for why this is a
@@ -166,13 +161,13 @@ function pendingCondition() {
166
161
  ];
167
162
  }
168
163
  /**
169
- * `getTable` is injectable so unit tests exercise this migration's full
170
- * detect/countPending/run logic against an in-memory fake table (matching
171
- * `embedding-stamp.ts`'s DI style) — no real Harper needed. Unlike
172
- * `embedding-stamp`, there is no separate HTTP mechanism to inject: the
173
- * write IS the table's own `.put()`, already covered by the same fake.
164
+ * `getTable` and the write-back are injectable so unit tests exercise this
165
+ * migration's full detect/countPending/run logic against an in-memory fake
166
+ * table and a fake write-back (matching `embedding-stamp.ts`'s DI style) — no
167
+ * real Harper needed. The default write-back is the real helper; an `update`
168
+ * plan needs the table's incremental `update`.
174
169
  */
175
- export function createVisibilityBackfillMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl) {
170
+ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl, getLockStore = defaultMemoryLockStore) {
176
171
  return {
177
172
  id: VISIBILITY_BACKFILL_ID,
178
173
  riskClass: "derived-only",
@@ -191,6 +186,17 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable,
191
186
  n++;
192
187
  return n;
193
188
  },
189
+ async checkUnconfirmed(id) {
190
+ const row = await getTable().get(id);
191
+ if (!row)
192
+ return "no-row";
193
+ // This migration only fills an absent visibility (flair#2840): once any
194
+ // value is present, run() never writes the row again, so the unconfirmed
195
+ // record is cleared. An owner's later value supersedes the unconfirmed
196
+ // write.
197
+ const visibility = row.visibility;
198
+ return visibility !== undefined && visibility !== null ? "at-target" : "pending";
199
+ },
194
200
  async run(batchSize) {
195
201
  const table = getTable();
196
202
  const candidates = [];
@@ -198,38 +204,73 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable,
198
204
  candidates.push(row);
199
205
  }
200
206
  const touchedIds = [];
207
+ const unconfirmedIds = [];
201
208
  for (const row of candidates) {
202
209
  const id = String(row.id ?? "");
203
210
  if (!id)
204
211
  continue;
205
- const outcome = await writeBackCommittedRow(table, id, (existing) => {
206
- if (!existing)
207
- return { skip: true }; // deleted since the search above — nothing to fix
208
- // The write-gate: this is what actually enforces "never overwrite an
209
- // existing visibility value", independent of how precisely the
210
- // candidate query above narrowed things (see module doc — a
211
- // garbage third value would still be pulled in as a candidate).
212
- if (existing.visibility !== undefined && existing.visibility !== null)
213
- return { skip: true };
214
- const derived = deriveVisibilityFromDurability(existing.durability);
215
- // Never-widen invariant, asserted, not just tested: the only two
216
- // values `deriveVisibilityFromDurability` can ever produce are
217
- // "private"/"shared" (see its own doc), so this can never fire
218
- // today — it exists to fail loudly (halting this migration via the
219
- // runner's mid-batch-throw path, never a silent bad write) if a
220
- // future edit to that function ever widens its return type or is
221
- // bypassed via a type-unsafe call.
222
- if (derived !== "private" && derived !== "shared") {
223
- throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
212
+ // flair#2840: the write-back reports an attempt whose committed effect
213
+ // its post-commit verification read did not show. The row is counted as
214
+ // done only if a later attempt's write is verified; otherwise it is
215
+ // reported by id.
216
+ let ownUnconfirmed = false;
217
+ try {
218
+ // The decision and the write run under the per-id memory write lock
219
+ // (flair#2478 slice 2). One attempt: a held id is left for the next
220
+ // cycle, never written unserialized and never waited on unboundedly.
221
+ const outcome = await withMemoryWriteLockOnce(getLockStore(), [id], async () => {
222
+ const result = await writeBackCommittedRow(table, id, (existing) => {
223
+ if (!existing)
224
+ return { skip: true }; // deleted since the search above — nothing to fix
225
+ // Under the per-id Memory lock shared with owner PUT/PATCH,
226
+ // fill only an absent visibility.
227
+ if (existing.visibility !== undefined && existing.visibility !== null)
228
+ return { skip: true };
229
+ const derived = deriveVisibilityFromDurability(existing.durability);
230
+ // Never-widen invariant, asserted, not just tested: the only two
231
+ // values `deriveVisibilityFromDurability` can ever produce are
232
+ // "private"/"shared" (see its own doc), so this can never fire
233
+ // today — it exists to fail loudly (halting this migration via the
234
+ // runner's mid-batch-throw path, never a silent bad write) if a
235
+ // future edit to that function ever widens its return type or is
236
+ // bypassed via a type-unsafe call.
237
+ if (derived !== "private" && derived !== "shared") {
238
+ throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
239
+ }
240
+ // Idempotent: once visibility is committed, a fresh plan sees it
241
+ // present and skips, so re-applying leaves the same committed row.
242
+ return { idempotent: true, update: { visibility: derived } };
243
+ }, { label: "visibility-backfill", pausePre: () => txnPausePoint("visibility-backfill-pre"), pausePoint: () => txnPausePoint("visibility-backfill"), confirmPoint: () => txnPausePoint("visibility-backfill-confirmed"), expectedRow: row, onUnconfirmed: () => { ownUnconfirmed = true; } });
244
+ // Test-only: the write-back committed and the lock is still held.
245
+ const committed = txnPausePoint("visibility-backfill-committed");
246
+ if (committed)
247
+ await committed;
248
+ return result;
249
+ }, { phase: "visibility-backfill" });
250
+ if (outcome.kind !== "done")
251
+ continue;
252
+ if ("skip" in outcome.value) {
253
+ // A skip is not a write this run verified. If it follows an attempt
254
+ // whose committed effect was unconfirmed, the row is reported as
255
+ // unconfirmed; otherwise this run wrote nothing to the row
256
+ // (flair#2840).
257
+ if (ownUnconfirmed)
258
+ unconfirmedIds.push(id);
224
259
  }
225
- const backfillRow = { ...existing, visibility: derived };
226
- stripUndeclaredMemoryAttributes(backfillRow);
227
- return { write: backfillRow };
228
- }, { label: "visibility-backfill", pausePre: () => txnPausePoint("visibility-backfill-pre"), pausePoint: () => txnPausePoint("visibility-backfill"), expectedRow: row });
229
- if ("write" in outcome)
230
- touchedIds.push(id);
260
+ else if ("update" in outcome.value)
261
+ touchedIds.push(id);
262
+ }
263
+ catch (err) {
264
+ // flair#2840: carry this batch's outcomes on the error — the runner
265
+ // has no RunBatchResult to read when run() throws.
266
+ if (ownUnconfirmed)
267
+ unconfirmedIds.push(id);
268
+ throw new BatchOutcomeError({ touchedIds, unconfirmedIds }, err);
269
+ }
231
270
  }
232
- return { processed: touchedIds.length, touchedIds };
271
+ return unconfirmedIds.length > 0
272
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
273
+ : { processed: touchedIds.length, touchedIds };
233
274
  },
234
275
  };
235
276
  }
@@ -47,11 +47,6 @@ export function oauthPublicBaseUrl() {
47
47
  /**
48
48
  * The RFC 8707 resource identifier of flair's MCP surface: `<base>/mcp`.
49
49
  *
50
- * Matches `mcpResource()` in resources/mcp-oauth-flag.ts by construction —
51
- * that is the URI `withMCPAuth` audience-binds tokens to when the Model-2
52
- * surface is enabled, so the protected-resource document must name the same
53
- * string or a client would audience-bind its token to something `/mcp` rejects.
54
- *
55
50
  * It names `/mcp` even when `FLAIR_MCP_OAUTH` is off and `/mcp` therefore
56
51
  * 404s. That is a coherent state, not a lie: RFC 9728 metadata describes how a
57
52
  * resource WOULD be authorized; a client that discovers the authorization
@@ -10,18 +10,25 @@ export const BODY_MUST_BE_OBJECT_ERROR = "body_must_be_object";
10
10
  function isObjectRecord(value) {
11
11
  return value !== null && typeof value === "object" && !Array.isArray(value);
12
12
  }
13
- /** 400 for a write body that is neither a JSON object nor an allowed array of them. Echoes nothing. */
14
- export function bodyMustBeObject() {
13
+ /**
14
+ * 400 for a write body that is neither a JSON object nor an allowed array of
15
+ * them. Echoes nothing. The message follows `allowArrayObjects`: an
16
+ * array-admitting caller is told arrays are allowed, a caller that refuses
17
+ * them is not.
18
+ */
19
+ export function bodyMustBeObject(allowArrayObjects = false) {
15
20
  return new Response(JSON.stringify({
16
21
  error: BODY_MUST_BE_OBJECT_ERROR,
17
- message: "the write body must be a JSON object, or an array of them for a collection write",
22
+ message: allowArrayObjects
23
+ ? "the write body must be a JSON object, or an array of them for a collection write"
24
+ : "the write body must be a JSON object",
18
25
  }), { status: 400, headers: { "Content-Type": "application/json" } });
19
26
  }
20
27
  /**
21
28
  * Refuse a write body that is neither an object nor an allowed array of records.
22
29
  *
23
30
  * @param content the parsed request body
24
- * @param opts `allowArrayObjects: true` admits arrays of records
31
+ * @param opts `allowArrayObjects: true` admits arrays of records and says so in the message
25
32
  * @returns the 400 `Response` to send, or null to proceed
26
33
  */
27
34
  export function guardObjectBody(content, opts = {}) {
@@ -29,5 +36,5 @@ export function guardObjectBody(content, opts = {}) {
29
36
  return null;
30
37
  if (opts.allowArrayObjects && Array.isArray(content) && content.every(isObjectRecord))
31
38
  return null;
32
- return bodyMustBeObject();
39
+ return bodyMustBeObject(opts.allowArrayObjects === true);
33
40
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * org-event-reserved.ts — the reserved-event contract for OrgEvent writes
3
+ * (flair#2139 slice 3a).
4
+ *
5
+ * Resource writes check proposed and stored reserved markers. Stored checks
6
+ * and writes share an owned transaction; fresh reads confirm the outcome.
7
+ * Create/update allow hooks resolve their body argument before checking markers;
8
+ * allowDelete checks the target id prefix. Operations writes bypass this resource.
9
+ *
10
+ * The predicate is pure so both the resource guards and the doctor check share
11
+ * one definition. A record is reserved when its `kind` is `soul.changed` or
12
+ * `skill.changed`, or its `id` starts with `instruction-change:`.
13
+ */
14
+ import { RESERVED_EVENT_ID_PREFIX, RESERVED_EVENT_KINDS, isReservedEventRecord, } from "../src/lib/instruction-event-contract.js";
15
+ export { RESERVED_EVENT_ID_PREFIX, RESERVED_EVENT_KINDS, isReservedEventRecord };
16
+ export const RESERVED_EVENT_ERROR = "reserved_event";
17
+ export const RESERVED_EVENT_CHECK_UNAVAILABLE_ERROR = "reserved_event_check_unavailable";
18
+ /** 403 for a mutation of a reserved event. Echoes no submitted value. */
19
+ export function reservedEventRefusal() {
20
+ return new Response(JSON.stringify({
21
+ error: RESERVED_EVENT_ERROR,
22
+ message: "reserved events cannot be written through this API; this write is refused",
23
+ }), { status: 403, headers: { "Content-Type": "application/json" } });
24
+ }
25
+ /**
26
+ * 503 when the stored-record read this guard depends on fails. Unknown evidence
27
+ * never admits a write: the refusal names the failed check.
28
+ */
29
+ export function reservedEventCheckUnavailable(err) {
30
+ console.error("org-event-reserved: the stored event could not be read, so the write was refused", { err });
31
+ return new Response(JSON.stringify({
32
+ error: RESERVED_EVENT_CHECK_UNAVAILABLE_ERROR,
33
+ message: "the stored event could not be read; the write was refused",
34
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
35
+ }
36
+ /** Whether `id` is a key the stored-record read can address (the shared id rule). */
37
+ function readableId(id) {
38
+ if (typeof id === "string")
39
+ return id !== "";
40
+ return Array.isArray(id) && id.length > 0 && id.every((part) => typeof part === "string");
41
+ }
42
+ /** Refuse a write whose proposed records already carry a reserved marker. */
43
+ export function reservedEventProposedRefusal(content) {
44
+ const records = Array.isArray(content) ? content : [content];
45
+ for (const record of records) {
46
+ if (isReservedEventRecord(record))
47
+ return reservedEventRefusal();
48
+ }
49
+ return null;
50
+ }
51
+ /**
52
+ * Refuse a write whose proposed records, or the stored rows they land on, are
53
+ * reserved. Iterates the whole body first: any reserved element refuses the
54
+ * request before anything is written. Non-record elements are skipped here; the
55
+ * id and body-shape checks own their own refusals.
56
+ */
57
+ export async function reservedEventWriteRefusal(content, readStored) {
58
+ const proposed = reservedEventProposedRefusal(content);
59
+ if (proposed)
60
+ return proposed;
61
+ const records = Array.isArray(content) ? content : [content];
62
+ for (const record of records) {
63
+ if (record == null || typeof record !== "object" || Array.isArray(record))
64
+ continue;
65
+ const id = record.id;
66
+ if (!readableId(id))
67
+ continue;
68
+ let stored;
69
+ try {
70
+ stored = await readStored(id);
71
+ }
72
+ catch (err) {
73
+ return reservedEventCheckUnavailable(err);
74
+ }
75
+ if (isReservedEventRecord(stored))
76
+ return reservedEventRefusal();
77
+ }
78
+ return null;
79
+ }
80
+ /** Refuse a write that lands on one already-stored reserved row. */
81
+ export async function reservedEventStoredRefusal(id, readStored) {
82
+ if (!readableId(id))
83
+ return null;
84
+ let stored;
85
+ try {
86
+ stored = await readStored(id);
87
+ }
88
+ catch (err) {
89
+ return reservedEventCheckUnavailable(err);
90
+ }
91
+ return isReservedEventRecord(stored) ? reservedEventRefusal() : null;
92
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * org-event-write-fault.ts — the injection point for a per-site fault in the
3
+ * selected server-built OrgEvent writers (flair#3002): the A2A
4
+ * message/send event, the agent-key-register event and the graph-heal event.
5
+ *
6
+ * The hook is null unless setOrgEventWriteFaultHook installs one. Nothing
7
+ * under resources/ or src/ calls it; the real-Harper suite installs it from
8
+ * test/fixtures/org-event-write-fault-3002/probe.js, which is not in the
9
+ * package. The row is the exact object about to be validated and staged, so a
10
+ * test fixture can hand the writer a row its table's validator must refuse.
11
+ */
12
+ let hook = null;
13
+ export function setOrgEventWriteFaultHook(next) {
14
+ hook = next;
15
+ }
16
+ /** Run the installed hook for `site`; a no-op when none is installed. */
17
+ export function maybeFaultOrgEventRow(site, row) {
18
+ hook?.(site, row);
19
+ }
@@ -33,7 +33,7 @@
33
33
  * For addressed single-record HTTP PUT/PATCH, Harper loads the row through
34
34
  * `Table.getResource` → `resource._loadRecord` before the resource method runs;
35
35
  * a no-argument `super.get()` then returns the cached row. If reached before
36
- * that load, the non-admin write guard checks string or number body ids before stored ownership.
36
+ * that load, the non-admin write guard checks the body id before stored ownership.
37
37
  * Its stored-row read failure returns `owner_check_unavailable`. The
38
38
  * real-Harper test injects an initial load failure: a non-admin agent gets that
39
39
  * named refusal, and an administrator gets Harper's own 500. It does not cover