@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
@@ -0,0 +1,289 @@
1
+ import { writeJournalScope as active } from "./write-journal-context.js";
2
+ export { currentWriteJournal } from "./write-journal-context.js";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { databases } from "harper";
5
+ import { isMemoryHostSourceStore, loadStoredPointer, storedPointerIds } from "./memory-host-source.js";
6
+ import { restorePointerRowIfAbsent } from "./host-pointer-adapter.js";
7
+ import { txnPausePoint } from "./txn-pause-point.js";
8
+ function materialize(value, seen = new WeakMap()) {
9
+ if (value == null || typeof value !== "object")
10
+ return value;
11
+ if (seen.has(value))
12
+ return seen.get(value);
13
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Date || value instanceof RegExp) {
14
+ return structuredClone(value);
15
+ }
16
+ if (value instanceof Map) {
17
+ const result = new Map();
18
+ seen.set(value, result);
19
+ for (const [key, item] of value)
20
+ result.set(materialize(key, seen), materialize(item, seen));
21
+ return result;
22
+ }
23
+ if (value instanceof Set) {
24
+ const result = new Set();
25
+ seen.set(value, result);
26
+ for (const item of value)
27
+ result.add(materialize(item, seen));
28
+ return result;
29
+ }
30
+ const source = Object.keys(value).length === 0 && typeof value.toJSON === "function" ? value.toJSON() : value;
31
+ const result = Array.isArray(source) ? [] : {};
32
+ seen.set(value, result);
33
+ if (source !== value)
34
+ seen.set(source, result);
35
+ if (Array.isArray(source))
36
+ result.length = source.length;
37
+ for (const key of Object.keys(source)) {
38
+ Object.defineProperty(result, key, { value: materialize(source[key], seen), enumerable: true, writable: true, configurable: true });
39
+ }
40
+ return result;
41
+ }
42
+ const copy = (value) => value == null ? undefined : materialize(value);
43
+ const equal = (a, b) => isDeepStrictEqual(copy(a), copy(b));
44
+ function undoable(entry, current) {
45
+ if (!equal(current, entry.after))
46
+ return false;
47
+ if (entry.before !== undefined || !entry.after?.tags?.includes("skill"))
48
+ return true;
49
+ return current && current.archived !== true && !current.validTo &&
50
+ (current.expiresAt == null || (typeof current.expiresAt === "string" && Date.parse(current.expiresAt) > Date.now()));
51
+ }
52
+ /** Captures every addWrite in the owned transaction, including caller hooks. */
53
+ export class WriteJournal {
54
+ entries = [];
55
+ pointerChanged = false;
56
+ compensationAttempted = false;
57
+ staged = new Set();
58
+ transactions = new Set();
59
+ owners = new WeakMap();
60
+ assertCoverage() {
61
+ const recorded = new Set(this.entries.map((entry) => entry.operation));
62
+ for (const txn of this.transactions)
63
+ for (const operation of txn.writes ?? []) {
64
+ if (operation && !recorded.has(operation))
65
+ throw new Error("write journal: staged write has no inverse");
66
+ }
67
+ for (const operation of this.staged) {
68
+ if (!recorded.has(operation))
69
+ throw new Error("write journal: staged write has no inverse");
70
+ }
71
+ }
72
+ run(fn) {
73
+ return active.run(this, fn);
74
+ }
75
+ /** The Memory row ids this journal's writes touched, sorted. Undo holds
76
+ * these ids' per-id write lock around its checks and writes (flair#2950). */
77
+ memoryWriteIds() {
78
+ const store = databases?.flair?.Memory?.primaryStore;
79
+ if (!store)
80
+ return [];
81
+ const ids = new Set();
82
+ for (const entry of this.entries) {
83
+ if (entry.operation?.store === store && entry.operation.key != null) {
84
+ ids.add(String(entry.operation.key));
85
+ }
86
+ }
87
+ return [...ids].sort();
88
+ }
89
+ async transaction(ctx, fn) {
90
+ let callbackCompleted = false;
91
+ const releases = [];
92
+ const links = new Set();
93
+ const attach = (txn) => {
94
+ if (!txn || links.has(txn))
95
+ return;
96
+ if (typeof txn.addWrite !== "function")
97
+ throw new Error("write journal: transaction staging unavailable");
98
+ links.add(txn);
99
+ this.transactions.add(txn);
100
+ const addWrite = txn.addWrite;
101
+ const ownAddWrite = Object.getOwnPropertyDescriptor(txn, "addWrite");
102
+ txn.addWrite = (operation) => {
103
+ const entry = { operation, transaction: txn, before: copy(operation.entry?.value), applied: false };
104
+ this.entries.push(entry);
105
+ this.staged.add(operation);
106
+ this.owners.set(operation, txn);
107
+ const commit = operation.commit;
108
+ if (typeof commit !== "function" || !operation.store || operation.key == null) {
109
+ throw new Error("write journal: unsupported staged write");
110
+ }
111
+ operation.commit = (...args) => {
112
+ let prior = operation.priorWrite;
113
+ while (prior && !prior.stagedEntry)
114
+ prior = prior.priorWrite;
115
+ entry.before = copy((prior?.stagedEntry ?? args[1])?.value);
116
+ const result = commit.apply(operation, args);
117
+ if (result?.then)
118
+ throw new Error("write journal: asynchronous commit unsupported");
119
+ entry.applied = operation.stagedEntry !== undefined;
120
+ entry.after = copy(operation.stagedEntry?.value);
121
+ entry.version = args[0];
122
+ return result;
123
+ };
124
+ return addWrite.call(txn, operation);
125
+ };
126
+ const ownNext = Object.getOwnPropertyDescriptor(txn, "next");
127
+ let next = txn.next;
128
+ Object.defineProperty(txn, "next", {
129
+ configurable: true,
130
+ enumerable: ownNext?.enumerable ?? true,
131
+ get: () => next,
132
+ set: (value) => { attach(value); next = value; },
133
+ });
134
+ releases.push(() => {
135
+ if (ownAddWrite)
136
+ Object.defineProperty(txn, "addWrite", ownAddWrite);
137
+ else
138
+ delete txn.addWrite;
139
+ Object.defineProperty(txn, "next", { configurable: true, enumerable: ownNext?.enumerable ?? true, writable: true, value: next });
140
+ });
141
+ attach(next);
142
+ };
143
+ const capture = () => attach(ctx?.transaction);
144
+ try {
145
+ const result = await fn(capture, () => { callbackCompleted = true; });
146
+ this.assertCoverage();
147
+ return result;
148
+ }
149
+ catch (err) {
150
+ if (!callbackCompleted) {
151
+ for (const txn of links)
152
+ this.transactions.delete(txn);
153
+ for (let index = this.entries.length - 1; index >= 0; index--) {
154
+ if (links.has(this.entries[index].transaction))
155
+ this.entries.splice(index, 1);
156
+ }
157
+ for (const operation of this.staged) {
158
+ if (links.has(this.owners.get(operation)))
159
+ this.staged.delete(operation);
160
+ }
161
+ }
162
+ throw err;
163
+ }
164
+ finally {
165
+ for (const release of releases.reverse())
166
+ release();
167
+ }
168
+ }
169
+ async undo(ctx, transact) {
170
+ return active.run(null, async () => {
171
+ this.assertCoverage();
172
+ let confirmed = true;
173
+ const undone = new Map();
174
+ const versions = new Map();
175
+ for (const entry of [...this.entries].reverse()) {
176
+ if (!entry.applied)
177
+ continue;
178
+ const { operation } = entry;
179
+ const table = Object.values(databases).flatMap((db) => Object.values(db))
180
+ .find((t) => t?.primaryStore === operation.store);
181
+ const raw = Object.getPrototypeOf(table ?? {});
182
+ if (!table || !raw?.get || !raw?.put || !raw?.delete) {
183
+ confirmed = false;
184
+ continue;
185
+ }
186
+ const pointer = isMemoryHostSourceStore(operation.store);
187
+ const read = async (shared) => {
188
+ if (!pointer)
189
+ return raw.get.call(table, operation.key, shared);
190
+ await storedPointerIds([String(operation.key)], shared);
191
+ return loadStoredPointer(String(operation.key), shared);
192
+ };
193
+ const version = table === databases.flair.InstructionVersion;
194
+ const successor = table === databases.flair.Memory && entry.before === undefined && entry.after?.tags?.includes("skill");
195
+ const restore = pointer && entry.before !== undefined && entry.after === undefined;
196
+ const pause = async (pending) => { if (pending)
197
+ await pending; };
198
+ if (successor)
199
+ await pause(txnPausePoint("skill-update-successor-rollback-start"));
200
+ if (restore)
201
+ await pause(txnPausePoint("skill-update-pointer-restore-start"));
202
+ try {
203
+ const current = await read({});
204
+ if (!undoable(entry, current)) {
205
+ if (pointer && current?.hostSource != null)
206
+ this.pointerChanged = true;
207
+ confirmed = false;
208
+ continue;
209
+ }
210
+ const journal = this;
211
+ let undoVersion;
212
+ const expectedVersion = versions.get(operation.store)?.get(operation.key) ?? entry.version;
213
+ await transact(ctx, async (shared) => {
214
+ const stored = await read(shared);
215
+ if (!undoable(entry, stored))
216
+ throw new Error("write journal: undo target changed");
217
+ const guard = {
218
+ store: operation.store, key: operation.key, reloadCommitBase: true, entry: undefined,
219
+ commit(time, value) {
220
+ undoVersion = time;
221
+ if (!undoable(entry, value?.value) || (value && value.version !== expectedVersion)) {
222
+ if (pointer && value?.value?.hostSource != null)
223
+ journal.pointerChanged = true;
224
+ throw new Error("write journal: undo target changed");
225
+ }
226
+ },
227
+ };
228
+ shared.transaction.addWrite(guard);
229
+ if (guard.entry === undefined)
230
+ guard.entry = null;
231
+ if (entry.before === undefined)
232
+ await raw.delete.call(table, operation.key, shared);
233
+ else if (restore)
234
+ await restorePointerRowIfAbsent(copy(entry.before), shared);
235
+ else
236
+ await raw.put.call(table, copy(entry.before), shared);
237
+ if (version)
238
+ await pause(txnPausePoint("skill-journal-version-rollback-staged"));
239
+ if (restore)
240
+ await pause(txnPausePoint("skill-update-pointer-restore-staged"));
241
+ });
242
+ if (version)
243
+ await pause(txnPausePoint("skill-journal-version-rollback-committed"));
244
+ if (successor)
245
+ await pause(txnPausePoint("skill-update-successor-rollback-committed"));
246
+ if (!equal(await read({}), entry.before))
247
+ confirmed = false;
248
+ const committedEntry = operation.store.getEntry(operation.key, { uncachedRead: true });
249
+ if (committedEntry && committedEntry.version !== undoVersion)
250
+ confirmed = false;
251
+ let byKey = undone.get(operation.store);
252
+ if (!byKey)
253
+ undone.set(operation.store, byKey = new Map());
254
+ byKey.set(operation.key, { read, entry });
255
+ let byVersion = versions.get(operation.store);
256
+ if (!byVersion)
257
+ versions.set(operation.store, byVersion = new Map());
258
+ byVersion.set(operation.key, undoVersion);
259
+ }
260
+ catch {
261
+ confirmed = false;
262
+ try {
263
+ const current = await read({});
264
+ if (pointer && current?.hostSource != null && !equal(current, entry.before))
265
+ this.pointerChanged = true;
266
+ }
267
+ catch { }
268
+ }
269
+ }
270
+ for (const byKey of undone.values())
271
+ for (const { read, entry } of byKey.values()) {
272
+ try {
273
+ const current = await read({});
274
+ const stored = entry.operation.store.getEntry(entry.operation.key, { uncachedRead: true });
275
+ const version = versions.get(entry.operation.store)?.get(entry.operation.key);
276
+ if (!equal(current, entry.before) || (stored && stored.version !== version)) {
277
+ if (isMemoryHostSourceStore(entry.operation.store) && current?.hostSource != null)
278
+ this.pointerChanged = true;
279
+ confirmed = false;
280
+ }
281
+ }
282
+ catch {
283
+ confirmed = false;
284
+ }
285
+ }
286
+ return confirmed;
287
+ });
288
+ }
289
+ }
@@ -29,6 +29,18 @@ export const AGENT_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
29
29
  * refuse with. The CLI and JIT-principal writers refuse with the same message
30
30
  * text but not this code. */
31
31
  export const AGENT_ID_ERROR = "invalid_agent_id";
32
+ /** The remedy for an id that cannot be used as a JSON integer: a BigInt, which
33
+ * cannot be JSON-serialized, or an integral number outside the safe-integer
34
+ * range, whose value can no longer be trusted to round-trip. */
35
+ export const AGENT_ID_STRING_REMEDY = "send the agent id as a string";
36
+ /** True for an id Harper delivered from a JSON integer whose value JavaScript
37
+ * cannot trust to round-trip. A BigInt is never an agent ID; an unsafe number
38
+ * cannot be trusted when compared or stored, so isValidAgentId refuses it
39
+ * too. */
40
+ export function isUnsafeAgentIdWireValue(id) {
41
+ return (typeof id === "bigint" ||
42
+ (typeof id === "number" && Number.isInteger(id) && !Number.isSafeInteger(id)));
43
+ }
32
44
  /**
33
45
  * Is `id` an agent ID this rule accepts? A non-string, non-number value —
34
46
  * including `null` — is never valid. A write path must distinguish an OMITTED
@@ -38,9 +50,39 @@ export const AGENT_ID_ERROR = "invalid_agent_id";
38
50
  export function isValidAgentId(id) {
39
51
  if (typeof id !== "string" && typeof id !== "number")
40
52
  return false;
53
+ if (typeof id === "number" && !Number.isSafeInteger(id))
54
+ return false;
41
55
  return AGENT_ID_PATTERN.test(String(id));
42
56
  }
43
- /** A human-readable refusal message naming the rule and the offending value. */
57
+ /** A human-readable refusal. A BigInt or an unsafe integer gets the string
58
+ * remedy alone (no rule). Every other value gets
59
+ * "invalid agent id <shown>: <rule>", where a Symbol or a non-finite number
60
+ * or undefined is shown as String(id) and anything else as JSON.stringify(id); after
61
+ * those branches, if Array.isArray (for a revoked Proxy) or JSON.stringify
62
+ * throws, or JSON.stringify returns undefined, the value is reported by type:
63
+ * "invalid agent id (<type> that cannot be serialized): <rule>"
64
+ * instead. */
44
65
  export function invalidAgentIdMessage(id) {
45
- return `invalid agent id ${JSON.stringify(id)}: an agent id must match ${AGENT_ID_RULE} (1-64 characters: A-Z, a-z, 0-9, _ or -)`;
66
+ if (isUnsafeAgentIdWireValue(id))
67
+ return AGENT_ID_STRING_REMEDY;
68
+ const rule = `an agent id must match ${AGENT_ID_RULE} (1-64 characters: A-Z, a-z, 0-9, _ or -)`;
69
+ let shown;
70
+ let isArray = false;
71
+ if (id === undefined || typeof id === "symbol" || (typeof id === "number" && !Number.isFinite(id))) {
72
+ shown = String(id);
73
+ }
74
+ else {
75
+ try {
76
+ isArray = Array.isArray(id);
77
+ shown = JSON.stringify(id);
78
+ }
79
+ catch {
80
+ // Array.isArray (for a revoked Proxy) or JSON.stringify can throw; report by type below.
81
+ }
82
+ }
83
+ if (shown === undefined) {
84
+ const type = isArray ? "an array" : typeof id === "object" ? "an object" : `a ${typeof id}`;
85
+ return `invalid agent id (${type} that cannot be serialized): ${rule}`;
86
+ }
87
+ return `invalid agent id ${shown}: ${rule}`;
46
88
  }
@@ -148,7 +148,7 @@ function stage(fs, target, content, mode) {
148
148
  return tmp;
149
149
  }
150
150
  /** Best-effort directory fsync so the renames themselves are durable. */
151
- function fsyncDir(dir) {
151
+ export function fsyncDir(dir) {
152
152
  try {
153
153
  const fd = openSync(dir, "r");
154
154
  try {
@@ -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
+ }
@@ -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",
@@ -0,0 +1,20 @@
1
+ /**
2
+ * open-live-row.ts — the skill writer's "open live" Memory-row predicate
3
+ * (flair#2662), shared so `flair doctor` asks the same question the writer
4
+ * answers. It checks the row's fields and the current time (for `expiresAt`). Deliberately imports nothing (resources
5
+ * importing this compiled helper require it to be load-free).
6
+ *
7
+ * A row is open-live when it is not archived, is not expired (`expiresAt`
8
+ * absent, or a string later than now), and carries no `validTo`.
9
+ */
10
+ export function isOpenLiveRow(row) {
11
+ if (!row || typeof row !== "object")
12
+ return false;
13
+ if (row.archived === true)
14
+ return false;
15
+ if (row.expiresAt != null && (typeof row.expiresAt !== "string" || !(Date.parse(row.expiresAt) > Date.now())))
16
+ return false;
17
+ if (typeof row.validTo === "string" && row.validTo.length > 0)
18
+ return false;
19
+ return true;
20
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Soul is scoped to an `agentId` and has no dedicated or enforced per-user
3
+ * scope field (schemas/memory.graphql).
4
+ * A write that would store a non-empty `scopeTag` or a non-empty `tags` array
5
+ * is refused by name when earlier guards permit the request, whatever the tag's
6
+ * prefix: POST and PUT check the request body, PATCH the merged row
7
+ * (flair#1540).
8
+ *
9
+ * The predicate runs in the server's write policy. The refusal name is
10
+ * imported by `flair import` and `flair restore`, which report a row refused
11
+ * with it; `flair rem restore` reports its generic HTTP error and imports
12
+ * neither.
13
+ */
14
+ /** The named refusal for a Soul write that would store a non-empty `scopeTag` or a non-empty `tags` array. */
15
+ export const SOUL_SCOPE_FIELDS_REFUSAL = "soul_scope_fields_not_writable";
16
+ /**
17
+ * Whether a row would carry a non-empty `scopeTag` or a non-empty `tags`
18
+ * array. POST and PUT pass the request body; PATCH passes the merged row.
19
+ */
20
+ export function suppliesSoulScopeFields(content) {
21
+ const scopeTag = content?.scopeTag;
22
+ if (scopeTag !== undefined && scopeTag !== null && scopeTag !== "")
23
+ return true;
24
+ const tags = content?.tags;
25
+ return Array.isArray(tags) && tags.length > 0;
26
+ }
@@ -207,9 +207,9 @@ export function validateHumanReviewerId(reviewerId) {
207
207
  // lives server-side in resources/auto-promote-lib.ts (decideAutoPromote — the
208
208
  // UNATTENDED path), which IMPORTS these from here. The direction is deliberate
209
209
  // and established in this repo: a server file may import a PURE helper from src/
210
- // (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts already
211
- // import this very module); it is a CLI file importing FROM resources/ that does
212
- // not survive npm packaging. Defining it here lets the CLI side
210
+ // (resources/PromoteMemoryCandidate.ts already imports this very module); it is
211
+ // a CLI file importing FROM resources/ that does not survive npm packaging.
212
+ // Defining it here lets the CLI side
213
213
  // (src/commands/rem.ts, `flair rem candidates`) and the server gate share ONE
214
214
  // implementation rather than a hand-kept pair.
215
215
  //
@@ -14,7 +14,7 @@
14
14
  * invokes `flair rem nightly run-once`, the runner module does the work.
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
- import { resolve, dirname } from "node:path";
17
+ import { resolve, dirname, join } from "node:path";
18
18
  import { spawn } from "node:child_process";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { escapeXml } from "../lib/xml-escape.js";
@@ -93,16 +93,26 @@ function validateSchedule(hour, minute) {
93
93
  throw new Error(`minute must be an integer 0-59, got ${minute}`);
94
94
  }
95
95
  }
96
+ /**
97
+ * Quote a value as ONE POSIX shell word. Embedded single quotes are closed,
98
+ * escaped, and reopened, so the shell reads the value literally and never
99
+ * interprets `$()`, backticks, or quotes inside it.
100
+ */
101
+ export function quoteShimArg(value) {
102
+ return `'${value.replace(/'/g, "'\\''")}'`;
103
+ }
96
104
  function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
97
105
  validateSchedule(opts.hour, opts.minute);
98
106
  if (!/^[a-zA-Z0-9_-]+$/.test(opts.agentId)) {
99
107
  throw new Error(`invalid agent id: ${opts.agentId}`);
100
108
  }
109
+ const home = opts.homeOverride ?? resolveHome();
101
110
  return {
102
111
  FLAIR_BIN: flairBin,
103
112
  NODE_BIN: nodeBin,
104
113
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? resolveHome(),
114
+ ADMIN_PASS_FILE: resolve(opts.adminPassFile ?? join(home, ".flair", "admin-pass")),
115
+ HOME: home,
106
116
  AGENT_ID: opts.agentId,
107
117
  FLAIR_URL: opts.flairUrl,
108
118
  HOUR: String(opts.hour),
@@ -369,8 +379,15 @@ export function enableScheduler(opts) {
369
379
  `\`flair rem nightly enable\`.`);
370
380
  }
371
381
  const stderrLogPath = resolve(logsDir, "rem-nightly.stderr.log");
372
- // 1. Deploy the shim (always — both platforms invoke it).
373
- const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), subs);
382
+ // 1. Deploy the shim (always — both platforms invoke it). Every path passed
383
+ // to the command is one POSIX single-quoted argument; none is double-quoted,
384
+ // so shell syntax inside a path stays literal.
385
+ const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), {
386
+ ...subs,
387
+ NODE_BIN: quoteShimArg(subs.NODE_BIN),
388
+ FLAIR_BIN: quoteShimArg(subs.FLAIR_BIN),
389
+ ADMIN_PASS_FILE: quoteShimArg(subs.ADMIN_PASS_FILE),
390
+ });
374
391
  writeFileWithDir(shimPath, shimContents, 0o700);
375
392
  chmodSync(shimPath, 0o700);
376
393
  // 2. Write the scheduler entry.