@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -0,0 +1,310 @@
1
+ /**
2
+ * memory-write-lock.ts — the per-memory-id write serialization protocol
3
+ * (flair#2478 slice 1). The ordinary owner PUT and PATCH (resources/Memory.ts)
4
+ * run under it; the other Memory writers convert in part 2.
5
+ *
6
+ * A writer that must make its read, decision and write on one committed basis
7
+ * runs under one key per ID of `Memory.primaryStore`'s lock: `["memory", fullStoredId]`.
8
+ * Within one Harper process the lock is per key and shared by its threads
9
+ * (resources/key-lock.ts). A caller opens and settles its owned transaction
10
+ * inside the callback, so the key is held across the commit. Two PUT paths can
11
+ * join a transaction they do not own, which then commits after the put returns
12
+ * and so after the key is released: a put composed into its caller's
13
+ * transaction (manual promotion, via withComposedWriteTransaction in
14
+ * resources/request-transaction.ts), and the admin `_reindex` re-PUT when the
15
+ * request carries an open transaction, which it joins as it did before the lock
16
+ * (with none open, it owns its transaction and commits before the release).
17
+ *
18
+ * A same-id writer that finds the key held waits and retries within its budget
19
+ * ({@link MEMORY_LOCK_ATTEMPTS} attempts with a {@link MEMORY_LOCK_WAIT_MS} ms
20
+ * wait between them — the bound resources/usage-recording.ts and
21
+ * resources/instruction-version-record.ts use). If the holder releases inside
22
+ * the budget, the writer takes the key, unless an attempt observes an
23
+ * outcome-unknown marker for the id (then it is refused `write_outcome_unknown`,
24
+ * below, even while the key is held). A writer that then opens a new owned
25
+ * transaction (the ordinary PUT and PATCH) reads the row as stored at that
26
+ * moment: the holder's committed row when the holder owned its transaction (a
27
+ * composed or `_reindex` holder that joined another transaction may release
28
+ * before that transaction commits). A composed or `_reindex` writer that joins
29
+ * an already-open request transaction reads from that transaction's snapshot
30
+ * instead, which can predate the acquisition. Otherwise it is refused:
31
+ *
32
+ * - `503 memory_busy` — the key stayed held for the whole budget. Nothing was
33
+ * written, so the request can be sent again unchanged. The body carries the
34
+ * caller id and nothing else: it is byte-identical whether the target id
35
+ * exists or not, so a lock miss never reveals stored-row state (Sherlock S7).
36
+ *
37
+ * Two more lock refusals, also `503`:
38
+ *
39
+ * - `memory_lock_unavailable` — `Memory.primaryStore` has no lock. The write
40
+ * is refused, never run unserialized, and nothing was written. There is no
41
+ * production fallback; a unit-test double supplies a lock on its mock table.
42
+ * - `write_outcome_unknown` — the id's last owned write settled with an
43
+ * unresolved outcome: its commit may have landed while its verification read
44
+ * failed. Do not replay that write blindly: read the row first, and treat a
45
+ * row that already holds it as written. {@link markMemoryWriteOutcomeUnknown}
46
+ * records the marker; until a process restart clears it (the fencing step),
47
+ * PUT/PATCH check the addressed id; DELETE also checks the resolved skill
48
+ * head. POST and background/nested writers do not check the marker.
49
+ *
50
+ * The marker is module state, so it is per Harper worker thread. That covers
51
+ * the whole instance only in the supported single-worker mode: flair refuses to
52
+ * serve on more than one worker thread (resources/multi-worker-guard.ts,
53
+ * flair#2059; every route but `/Health` and `/health` answers 503
54
+ * `multi_worker_unsupported`).
55
+ * Under the explicit `FLAIR_MULTI_WORKER_UNSAFE=1` opt-in, a marker set on one
56
+ * worker is not seen by another.
57
+ *
58
+ * The critical section contains the write paths' embedding calls — the ordinary
59
+ * PUT's regen (and its create-path dedup probe), the re-embed PATCH's compute
60
+ * and its recompute, and the PATCH embedding refresh — and each is bounded by
61
+ * {@link MEMORY_LOCKED_PROVIDER_TIMEOUT_MS} through {@link boundLockedProviderCall};
62
+ * a call still pending when the timeout callback runs, or one that settles after
63
+ * the bound, is refused with `503 memory_provider_timeout` and nothing is
64
+ * written. An in-process timeout cannot preempt a provider that never yields the
65
+ * event loop. A hold longer than
66
+ * {@link MEMORY_LOCK_HOLD_WATCHDOG_MS} is logged — the lock keys and the phase
67
+ * named in {@link MemoryWriteLockOptions.phase}, and elapsed time — when the
68
+ * timer runs or the callback settles. The watchdog never releases a key.
69
+ *
70
+ * Global lock order: a writer takes its sorted Memory id locks first, then the
71
+ * instruction-version lock (resources/instruction-version-record.ts), then the
72
+ * usage ledger (resources/usage-recording.ts). Part 2 converts the writers that
73
+ * take the instruction lock and write Memory to take their Memory id locks
74
+ * before it.
75
+ *
76
+ * Acquisition is sorted and deduplicated, so two writers that share ids take
77
+ * them in the same order. A partial acquisition is released before the wait, so
78
+ * a writer never blocks on the next key while holding one.
79
+ */
80
+ import { TEST_FAULT_INJECTION_ENV } from "./txn-pause-point.js";
81
+ /** The `Memory.primaryStore` key namespace (flair#2478). */
82
+ export const MEMORY_LOCK_NAMESPACE = "memory";
83
+ /** The owner-verb busy budget: {@link MEMORY_LOCK_ATTEMPTS} attempts, {@link MEMORY_LOCK_WAIT_MS} ms apart. */
84
+ export const MEMORY_LOCK_ATTEMPTS = 200;
85
+ export const MEMORY_LOCK_WAIT_MS = 10;
86
+ /** The lock-miss error code. */
87
+ export const MEMORY_BUSY_ERROR = "memory_busy";
88
+ /** The unresolved-outcome error code. */
89
+ export const WRITE_OUTCOME_UNKNOWN_ERROR = "write_outcome_unknown";
90
+ /** The no-lock error code: the store has no per-id lock, so the write is refused. */
91
+ export const MEMORY_LOCK_UNAVAILABLE_ERROR = "memory_lock_unavailable";
92
+ /** The provider-bound error code: an embedding call made under the lock outlasted its bound. */
93
+ export const MEMORY_PROVIDER_TIMEOUT_ERROR = "memory_provider_timeout";
94
+ /** The bound on one embedding provider call made while the per-id write lock is
95
+ * held (flair#2478). See {@link boundLockedProviderCall}. */
96
+ export const MEMORY_LOCKED_PROVIDER_TIMEOUT_MS = 20_000;
97
+ /** The observe-only hold watchdog's threshold (flair#2478). If the event loop
98
+ * cannot resume during a long hold, logging waits for settlement. No lock release. */
99
+ export const MEMORY_LOCK_HOLD_WATCHDOG_MS = 5_000;
100
+ /** Env overrides, honoured only under the fault-injection gate, that lower the
101
+ * two bounds for tests (a never-resolving stub or a long hold would otherwise
102
+ * cost the test its own bound). */
103
+ export const MEMORY_PROVIDER_TIMEOUT_ENV = "FLAIR_MEMORY_LOCK_PROVIDER_TIMEOUT_MS";
104
+ export const MEMORY_LOCK_HOLD_WATCHDOG_ENV = "FLAIR_MEMORY_LOCK_HOLD_WATCHDOG_MS";
105
+ /** A provider call still pending when the timeout callback runs, or settling after the bound, is refused with this error. */
106
+ export class MemoryProviderTimeout extends Error {
107
+ ms;
108
+ constructor(ms) {
109
+ super(`an embedding provider call made under the memory write lock did not settle within ${ms}ms`);
110
+ this.ms = ms;
111
+ this.name = "MemoryProviderTimeout";
112
+ }
113
+ }
114
+ /** The provider bound in force: {@link MEMORY_LOCKED_PROVIDER_TIMEOUT_MS}, or the
115
+ * test override when the fault-injection gate is on. */
116
+ export function memoryLockedProviderTimeoutMs(env = process.env) {
117
+ const override = testBound(env, MEMORY_PROVIDER_TIMEOUT_ENV);
118
+ return override ?? MEMORY_LOCKED_PROVIDER_TIMEOUT_MS;
119
+ }
120
+ /** The hold-watchdog threshold in force: {@link MEMORY_LOCK_HOLD_WATCHDOG_MS},
121
+ * or the test override when the fault-injection gate is on. */
122
+ export function memoryLockHoldWatchdogMs(env = process.env) {
123
+ const override = testBound(env, MEMORY_LOCK_HOLD_WATCHDOG_ENV);
124
+ return override ?? MEMORY_LOCK_HOLD_WATCHDOG_MS;
125
+ }
126
+ /** A positive, finite override read only under the fault-injection gate. */
127
+ function testBound(env, name) {
128
+ if (env[TEST_FAULT_INJECTION_ENV] !== "1")
129
+ return undefined;
130
+ const value = Number(env[name]);
131
+ return Number.isFinite(value) && value > 0 ? value : undefined;
132
+ }
133
+ /**
134
+ * Run one embedding provider call bounded by {@link memoryLockedProviderTimeoutMs}.
135
+ * `getEmbedding` takes no AbortSignal and swallows its own failures (returning
136
+ * null). A call still pending when the timeout callback runs, or one that settles
137
+ * after the bound (checked against elapsed time at settlement), rejects with
138
+ * {@link MemoryProviderTimeout}; the caller refuses 503 `memory_provider_timeout`
139
+ * without writing. The provider call itself is not cancelled, and a provider that
140
+ * never yields the event loop cannot be preempted.
141
+ */
142
+ export function boundLockedProviderCall(call, env = process.env) {
143
+ const ms = memoryLockedProviderTimeoutMs(env);
144
+ const started = performance.now();
145
+ return new Promise((resolve, reject) => {
146
+ const timer = setTimeout(() => reject(new MemoryProviderTimeout(ms)), ms);
147
+ timer.unref?.();
148
+ call().then((value) => {
149
+ clearTimeout(timer);
150
+ if (performance.now() - started > ms)
151
+ reject(new MemoryProviderTimeout(ms));
152
+ else
153
+ resolve(value);
154
+ }, (error) => {
155
+ clearTimeout(timer);
156
+ reject(performance.now() - started > ms ? new MemoryProviderTimeout(ms) : error);
157
+ });
158
+ });
159
+ }
160
+ /** Per-id unknown-outcome markers (Kern pin 2 / Flint decision). Module state:
161
+ * one set per worker thread, which is the whole instance in the supported
162
+ * single-worker mode (see the header). */
163
+ const outcomeUnknown = new Set();
164
+ /** The `["memory", fullStoredId]` lock key for one stored id. */
165
+ export function memoryLockKey(id) {
166
+ return [MEMORY_LOCK_NAMESPACE, String(id)];
167
+ }
168
+ /** Record that `id`'s last owned write settled with an unknown outcome. Cleared
169
+ * only by process restart — there is no production clear path. */
170
+ export function markMemoryWriteOutcomeUnknown(id) {
171
+ outcomeUnknown.add(String(id));
172
+ }
173
+ /** Is `id` marked outcome-unknown? A later writer checks this before acquiring. */
174
+ export function memoryWriteOutcomeUnknown(id) {
175
+ return outcomeUnknown.has(String(id));
176
+ }
177
+ /** TEST-ONLY: forget the marker for `id` so one test cannot leak into the next.
178
+ * Never called by production code (the production clear path is restart). */
179
+ export function resetMemoryWriteOutcomeUnknownForTest(id) {
180
+ outcomeUnknown.delete(String(id));
181
+ }
182
+ /** The sorted, deduplicated ids and their lock keys. */
183
+ function normalizeIds(ids) {
184
+ const seen = new Set();
185
+ const unique = [];
186
+ for (const id of ids) {
187
+ const text = String(id);
188
+ if (!seen.has(text)) {
189
+ seen.add(text);
190
+ unique.push(text);
191
+ }
192
+ }
193
+ unique.sort();
194
+ return { ids: unique, keys: unique.map(memoryLockKey) };
195
+ }
196
+ function lockStore(store) {
197
+ const lock = store;
198
+ if (typeof lock?.tryLock !== "function" || typeof lock?.unlock !== "function")
199
+ return undefined;
200
+ return lock;
201
+ }
202
+ function releaseAll(lock, acquired) {
203
+ for (let i = acquired.length - 1; i >= 0; i--)
204
+ lock.unlock(acquired[i]);
205
+ acquired.length = 0;
206
+ }
207
+ /**
208
+ * Run `fn` while holding every `["memory", id]` key for `ids` (sorted,
209
+ * deduplicated), up to {@link MEMORY_LOCK_ATTEMPTS} attempts spaced
210
+ * {@link MEMORY_LOCK_WAIT_MS}. Returns `busy` when the budget is exhausted;
211
+ * `unknown` when one of the ids carries an unknown-outcome marker; `unavailable`
212
+ * when the store has no lock or `ids` is empty. `fn` does not run in those cases.
213
+ */
214
+ export async function withMemoryWriteLock(store, ids, fn, options = {}) {
215
+ return acquire(lockStore(store), normalizeIds(ids), MEMORY_LOCK_ATTEMPTS, MEMORY_LOCK_WAIT_MS, fn, options);
216
+ }
217
+ /** One attempt, no wait. No writer calls it yet: it is the shape part 2's
218
+ * automatic writers take (flair#2478). A held lock or a marker answers
219
+ * `busy`/`unknown`. */
220
+ export async function withMemoryWriteLockOnce(store, ids, fn, options = {}) {
221
+ return acquire(lockStore(store), normalizeIds(ids), 1, 0, fn, options);
222
+ }
223
+ /** Start the observe-only watchdog; return its settlement check. */
224
+ function startHoldWatchdog(keys, phase) {
225
+ const ms = memoryLockHoldWatchdogMs();
226
+ const started = performance.now();
227
+ let logged = false;
228
+ const logHold = () => {
229
+ if (logged)
230
+ return;
231
+ logged = true;
232
+ console.warn(`[memory-write-lock] hold exceeded ${ms}ms: keys=${JSON.stringify(keys)} phase=${phase} elapsed=${Math.round(performance.now() - started)}ms`);
233
+ };
234
+ const timer = setTimeout(logHold, ms);
235
+ timer.unref?.();
236
+ return () => {
237
+ clearTimeout(timer);
238
+ if (performance.now() - started > ms)
239
+ logHold();
240
+ };
241
+ }
242
+ async function acquire(lock, normalized, attempts, waitMs, fn, options = {}) {
243
+ if (!lock || normalized.keys.length === 0)
244
+ return { kind: "unavailable" };
245
+ const scope = { keys: normalized.keys, ids: normalized.ids };
246
+ const acquired = [];
247
+ for (let attempt = 0; attempt < attempts; attempt++) {
248
+ const marked = normalized.ids.find((id) => memoryWriteOutcomeUnknown(id));
249
+ if (marked !== undefined)
250
+ return { kind: "unknown", id: marked };
251
+ let gotAll = true;
252
+ for (const key of normalized.keys) {
253
+ if (lock.tryLock(key))
254
+ acquired.push(key);
255
+ else {
256
+ gotAll = false;
257
+ break;
258
+ }
259
+ }
260
+ if (gotAll) {
261
+ const watchdog = startHoldWatchdog(normalized.keys, options.phase ?? "unknown");
262
+ try {
263
+ lock.resetReadTxn?.();
264
+ // The marker was checked at the top of this attempt; nothing between
265
+ // that check and here yields, so it cannot have changed.
266
+ return { kind: "done", value: await fn(scope) };
267
+ }
268
+ finally {
269
+ watchdog();
270
+ // Release only after `fn` returns. A callback that owns its transaction
271
+ // has settled it by then, so the lock spans that commit; a transaction
272
+ // the callback only joined commits later, after this release.
273
+ releaseAll(lock, acquired);
274
+ }
275
+ }
276
+ // Partial acquisition: release what we hold before waiting on the rest.
277
+ releaseAll(lock, acquired);
278
+ if (attempt + 1 < attempts && waitMs > 0)
279
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
280
+ }
281
+ return { kind: "busy" };
282
+ }
283
+ /** The lock-miss refusal: `503 memory_busy`, caller id only, no row state. */
284
+ export function memoryBusyResponse(callerId) {
285
+ return new Response(JSON.stringify({ error: MEMORY_BUSY_ERROR, caller: callerId }), {
286
+ status: 503,
287
+ headers: { "content-type": "application/json" },
288
+ });
289
+ }
290
+ /** The unresolved-outcome refusal: `503 write_outcome_unknown`. */
291
+ export function writeOutcomeUnknownResponse() {
292
+ return new Response(JSON.stringify({
293
+ error: WRITE_OUTCOME_UNKNOWN_ERROR,
294
+ message: "the write outcome is unknown. Read the affected row before writing again.",
295
+ }), { status: 503, headers: { "content-type": "application/json" } });
296
+ }
297
+ /** The provider-bound refusal: `503 memory_provider_timeout`. Nothing was written. */
298
+ export function memoryProviderTimeoutResponse() {
299
+ return new Response(JSON.stringify({
300
+ error: MEMORY_PROVIDER_TIMEOUT_ERROR,
301
+ message: "the embedding provider did not answer within its bound; nothing was written, retry",
302
+ }), { status: 503, headers: { "content-type": "application/json" } });
303
+ }
304
+ /** The no-lock refusal: `503 memory_lock_unavailable`. Nothing was written. */
305
+ export function memoryLockUnavailableResponse() {
306
+ return new Response(JSON.stringify({
307
+ error: MEMORY_LOCK_UNAVAILABLE_ERROR,
308
+ message: "this instance's Memory store has no per-id write lock, so the write was refused; nothing was written",
309
+ }), { status: 503, headers: { "content-type": "application/json" } });
310
+ }
@@ -0,0 +1,139 @@
1
+ /** Successful write replies with a body read named fields by type; no embedding field whatever storage returns. */
2
+ export const MEMORY_EMBEDDING_FIELDS = Object.freeze(["embedding", "embeddingModel"]);
3
+ export const FEED_RESPONSE_WRITE_FIELDS = Object.freeze([
4
+ "id",
5
+ "written",
6
+ "agentId",
7
+ "durability",
8
+ "visibility",
9
+ "createdAt",
10
+ "updatedAt",
11
+ "expiresAt",
12
+ "archived",
13
+ "supersedes",
14
+ "skillSubjectId",
15
+ "instanceToken",
16
+ "originatorInstanceId",
17
+ "provenance",
18
+ ]);
19
+ function isPlainRecord(value) {
20
+ return !!value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Response);
21
+ }
22
+ export function suppliedMemoryFields(body) {
23
+ if (!isPlainRecord(body))
24
+ return new Set();
25
+ return new Set(Object.keys(body).filter((key) => body[key] !== undefined && body[key] !== null));
26
+ }
27
+ export const WRITE_RESPONSE_WITHHELD = "write_response_withheld";
28
+ export const WRITE_RESPONSE_WITHHELD_MESSAGE = "the server does not report this write's result; read the row to see what is stored";
29
+ export function withheldWriteResult() {
30
+ return Response.json({ error: WRITE_RESPONSE_WITHHELD, message: WRITE_RESPONSE_WITHHELD_MESSAGE }, { status: 500 });
31
+ }
32
+ export function storageResult(value) {
33
+ return value instanceof Response ? withheldWriteResult() : value;
34
+ }
35
+ export function writeResultResponse(response) {
36
+ if (!response.ok)
37
+ return response;
38
+ return withheldWriteResult();
39
+ }
40
+ const SKIP = Symbol("skip");
41
+ function namedField(source, name) {
42
+ if (source === null || (typeof source !== "object" && typeof source !== "function"))
43
+ return undefined;
44
+ try {
45
+ return source[name];
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ function typedValue(value, rule) {
52
+ if (value === null)
53
+ return rule.type !== "object" && rule.type !== "stringArray" && rule.nullable === true ? null : SKIP;
54
+ switch (rule.type) {
55
+ case "string":
56
+ return typeof value === "string" ? value : SKIP;
57
+ case "integer":
58
+ return Number.isSafeInteger(value) ? value : SKIP;
59
+ case "number":
60
+ return typeof value === "number" && Number.isFinite(value) ? value : SKIP;
61
+ case "boolean":
62
+ return typeof value === "boolean" ? value : SKIP;
63
+ case "stringArray": {
64
+ // flair#2575: an array whose every entry is a string or null (a skill's
65
+ // `tags`, schema `[String]`), copied entry by entry; any other value or
66
+ // entry skips the field.
67
+ if (!Array.isArray(value))
68
+ return SKIP;
69
+ const length = namedField(value, "length");
70
+ if (!Number.isSafeInteger(length))
71
+ return SKIP;
72
+ const copy = [];
73
+ for (let i = 0; i < length; i++) {
74
+ const entry = namedField(value, String(i));
75
+ if (typeof entry !== "string" && entry !== null)
76
+ return SKIP;
77
+ copy.push(entry);
78
+ }
79
+ return copy;
80
+ }
81
+ case "object": {
82
+ if (!isPlainRecord(value))
83
+ return SKIP;
84
+ const built = buildFromAllowlist(value, rule.fields);
85
+ return built instanceof Response ? SKIP : built;
86
+ }
87
+ }
88
+ }
89
+ export function buildFromAllowlist(source, rules, names) {
90
+ const built = {};
91
+ for (const [name, rule] of Object.entries(rules)) {
92
+ if (names && !names.has(name))
93
+ continue;
94
+ const value = namedField(source, name);
95
+ const typed = value === undefined ? SKIP : typedValue(value, rule);
96
+ if (typed === SKIP) {
97
+ if (rule.required === true)
98
+ return withheldWriteResult();
99
+ continue;
100
+ }
101
+ Object.defineProperty(built, name, { value: typed, enumerable: true, writable: true, configurable: true });
102
+ }
103
+ return built;
104
+ }
105
+ const STRING = Object.freeze({ type: "string", nullable: true });
106
+ const INTEGER = Object.freeze({ type: "integer", nullable: true });
107
+ const BOOLEAN = Object.freeze({ type: "boolean", nullable: true });
108
+ export const FEED_FIELD_RULES = Object.freeze({
109
+ id: Object.freeze({ type: "string", required: true }),
110
+ agentId: STRING, content: STRING, contentHash: STRING, trigger: STRING, visibility: STRING,
111
+ durability: STRING, source: STRING, type: STRING, createdAt: STRING, updatedAt: STRING,
112
+ instanceToken: STRING, expiresAt: STRING, retrievalCount: INTEGER, lastRetrieved: STRING, usageCount: INTEGER,
113
+ promotionStatus: STRING, promotedAt: STRING, promotedBy: STRING, archived: BOOLEAN, archivedAt: STRING,
114
+ archivedBy: STRING, parentId: STRING, sessionId: STRING, lastReflected: STRING,
115
+ supersedes: STRING, subject: STRING, summary: STRING, validFrom: STRING, validTo: STRING,
116
+ provenance: STRING, originatorInstanceId: STRING, metadata: STRING, skillSubjectId: STRING,
117
+ kind: STRING, _originatorInstanceId: STRING, _syncedFrom: STRING, _syncedAt: STRING,
118
+ written: Object.freeze({ type: "boolean" }),
119
+ });
120
+ export const STORED_TEXT_RULES = Object.freeze({
121
+ content: Object.freeze({ type: "string" }),
122
+ summary: Object.freeze({ type: "string" }),
123
+ trigger: Object.freeze({ type: "string" }),
124
+ // flair#2575: a skill write's `stored` also names the skill fields its
125
+ // request supplied (resources/memory-redaction.ts, storedMemoryText).
126
+ name: Object.freeze({ type: "string" }),
127
+ description: Object.freeze({ type: "string" }),
128
+ tags: Object.freeze({ type: "stringArray" }),
129
+ });
130
+ export const REDACTION_RULES = Object.freeze({
131
+ redactedValues: Object.freeze({ type: "integer" }),
132
+ stored: Object.freeze({ type: "object", fields: STORED_TEXT_RULES }),
133
+ });
134
+ export function feedResponseFields(row, supplied) {
135
+ if (row instanceof Response)
136
+ return withheldWriteResult();
137
+ const names = new Set([...FEED_RESPONSE_WRITE_FIELDS, ...supplied]);
138
+ return buildFromAllowlist(row, FEED_FIELD_RULES, names);
139
+ }
@@ -59,7 +59,10 @@
59
59
  * lives, and reordering would silently relocate it (costing a
60
60
  * re-detect pass and orphaning the existing audit record) on instances
61
61
  * that have no problem at all. This fix is about instances where the
62
- * cycle cannot run, not about relocating ones where it can.
62
+ * cycle cannot run, not about relocating ones where it can. The
63
+ * default wins ahead of `ROOTPATH` when usable, regardless of which
64
+ * instance runs; an absent or unusable default loses. Set
65
+ * `FLAIR_MIGRATION_DATA_DIR` to separate custom migration state.
63
66
  * 4. `ROOTPATH` — Harper's real root path. The rescue candidate: it is
64
67
  * writable by definition on a running instance (Harper is writing its
65
68
  * own databases there), so a shape whose `homedir()` is unusable still
@@ -71,11 +74,11 @@
71
74
  * instead of the environment leaves candidate 4 empty — this covers
72
75
  * that case without guessing.
73
76
  *
74
- * "Usable" is probed by DOING THE REAL OPERATION the runner would do —
75
- * create `<dir>/.migrations` at 0700 and check it is writable — not by a
76
- * proxy check that could disagree with it. The probe is idempotent and, on
77
- * a healthy instance, is satisfied by the first candidate without touching
78
- * the others.
77
+ * The probe creates only `.migrations` non-recursively inside an existing
78
+ * candidate. It refuses symlinks present at the probe at either path.
79
+ * Node offers no openat-style handle; a swap after the check is not prevented.
80
+ * A refusal names the configured path and any resolved target (flair#2277).
81
+ * The first usable candidate wins.
79
82
  *
80
83
  * If NO candidate is usable, `resolveWritableMigrationDataDir` returns
81
84
  * `dataDir: null` WITH the per-candidate reasons, and the boot path turns
@@ -84,9 +87,9 @@
84
87
  * `flair quality`'s `instance.migrationsClean`. An instance that cannot run
85
88
  * migrations now says so; that silence was the actual defect.
86
89
  */
87
- import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
90
+ import { accessSync, constants, existsSync, lstatSync, mkdirSync, realpathSync, statSync } from "node:fs";
88
91
  import { homedir } from "node:os";
89
- import { basename, dirname, join } from "node:path";
92
+ import { basename, dirname, join, resolve } from "node:path";
90
93
  import { fileURLToPath } from "node:url";
91
94
  /** Explicit operator override for the migration data dir (see module doc). */
92
95
  export const MIGRATION_DATA_DIR_ENV = "FLAIR_MIGRATION_DATA_DIR";
@@ -141,17 +144,72 @@ export function migrationDataDirCandidates(env = process.env, moduleUrl = import
141
144
  add(deployedComponentRootPath(moduleUrl));
142
145
  return out;
143
146
  }
144
- /**
145
- * Probes a candidate by performing the exact operation the runner's lock
146
- * acquisition performs (`mkdir -p <dir>/.migrations` at 0700), then
147
- * confirming the result is writable. Idempotent: on an already-working
148
- * instance this is a no-op stat/mkdir against a directory that already
149
- * exists.
150
- */
147
+ /** Describes a refused link; surfaced when no candidate is usable. */
148
+ export function describeSymlinkedDataDirRefusal(configuredPath, which) {
149
+ let target = null;
150
+ let targetKind = "a target of unconfirmed type at";
151
+ let directory = false;
152
+ try {
153
+ target = realpathSync(configuredPath);
154
+ const stat = statSync(target);
155
+ directory = stat.isDirectory();
156
+ if (directory)
157
+ targetKind = "a directory at";
158
+ else if (stat.isFile())
159
+ targetKind = "a regular file at";
160
+ }
161
+ catch {
162
+ /* retain any resolved path without assuming its type */
163
+ }
164
+ let remedy = `stop Flair, remove the symbolic link at ${configuredPath} and replace it with a writable directory, then start Flair`;
165
+ if (directory) {
166
+ remedy = `only after verifying that the target is dedicated to this Flair instance and safe to relocate, stop Flair, remove the symbolic link at ${configuredPath}, move the directory at ${target} to ${configuredPath}, and start Flair`;
167
+ if (which === "data directory") {
168
+ remedy += `; if ownership is uncertain, leave the target in place and set ${MIGRATION_DATA_DIR_ENV}=${target} instead of the link, then restart`;
169
+ }
170
+ else {
171
+ remedy += "; if ownership is uncertain, leave the target in place and configure a different data directory with an unlinked .migrations child";
172
+ }
173
+ }
174
+ const link = target === null ? "a target that cannot be resolved" : `${targetKind} ${target}`;
175
+ return (`refusing ${configuredPath}: it is a symbolic link to ${link}, and Flair refuses a symlinked ${which} here — ` +
176
+ `the link can be re-pointed after this check. Remedy: ${remedy}.`);
177
+ }
178
+ /** Requires an existing directory, then creates only its `.migrations` child. */
151
179
  export function probeMigrationDataDir(dir) {
180
+ let candidate;
181
+ try {
182
+ candidate = lstatSync(resolve(dir));
183
+ }
184
+ catch (err) {
185
+ return {
186
+ dir,
187
+ ok: false,
188
+ reason: `${err?.message ?? String(err)}: cannot confirm the candidate is an existing directory — refusing to create it`,
189
+ };
190
+ }
191
+ if (candidate.isSymbolicLink()) {
192
+ return { dir, ok: false, reason: describeSymlinkedDataDirRefusal(dir, "data directory") };
193
+ }
194
+ if (!candidate.isDirectory()) {
195
+ return { dir, ok: false, reason: "not a directory" };
196
+ }
152
197
  const owned = join(dir, MIGRATIONS_SUBDIR);
153
198
  try {
154
- mkdirSync(owned, { recursive: true, mode: 0o700 });
199
+ try {
200
+ mkdirSync(owned, { mode: 0o700 });
201
+ }
202
+ catch (err) {
203
+ if (err.code !== "EEXIST")
204
+ throw err;
205
+ }
206
+ const ownedStat = lstatSync(owned);
207
+ if (ownedStat.isSymbolicLink()) {
208
+ return { dir, ok: false, reason: describeSymlinkedDataDirRefusal(owned, ".migrations directory") };
209
+ }
210
+ if (!ownedStat.isDirectory()) {
211
+ return { dir, ok: false, reason: ".migrations is not a directory" };
212
+ }
155
213
  accessSync(owned, constants.W_OK | constants.X_OK);
156
214
  return { dir, ok: true };
157
215
  }
@@ -48,7 +48,7 @@ export function verifySecureDir(dir) {
48
48
  */
49
49
  export function ensureSecureDir(dir) {
50
50
  if (!existsSync(dir)) {
51
- mkdirSync(dir, { recursive: true, mode: 0o700 });
51
+ mkdirSync(dir, { mode: 0o700 });
52
52
  }
53
53
  try {
54
54
  verifySecureDir(dir);