@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,363 @@
1
+ // instance-create-lock.ts — the critical section around the first-boot create in
2
+ // `GET /FederationInstance` (flair#1897 slice 1).
3
+ //
4
+ // WHY A FILESYSTEM LOCK, NOT AN IN-PROCESS ONE. A Harper store runs SEVERAL HTTP
5
+ // worker threads, each loading `dist/resources/*.js` in its own realm (Harper
6
+ // `server/threads/manageThreads.js` -> `new Worker(...)`; `threadServer.js` ->
7
+ // `loadRootComponents(true)`). `globalThis` is per worker, so an in-process chain
8
+ // does not serialise two GETs on two workers — both read `none`, both mint. On
9
+ // Linux Harper runs at least two workers by default (configValidator: threads
10
+ // count = cpus-1, floor 2), and Flair never writes that key. So the lock is a
11
+ // Flair-owned FILESYSTEM BAKERY LOCK, cross-worker AND cross-process, under the
12
+ // store root this process serves (`<rootPath>/flair-locks/instance-create/`) — NOT the keystore: flair#1233 requires an unusable `$HOME/.flair` to leave the read path working (the row is still created).
13
+ //
14
+ // WHAT IT COVERS. `findOrCreateInstance` holds the lock across: the read that
15
+ // found no row, the mint, the `put`, the keystore seed write, and a confirming
16
+ // re-read. A GET that already found a row never takes the lock, so reads stay
17
+ // concurrent.
18
+ //
19
+ // TICKET PROTOCOL — LAMPORT'S BAKERY ON FILES (Harper's own
20
+ // componentPreparationLock.ts is the reference for the pitfalls — not imported,
21
+ // it is not a package export). No timing assumption: only atomic `wx` create,
22
+ // atomic rename within one directory, and live-pid detection (`process.kill(pid,
23
+ // 0)`; ESRCH = dead, EPERM = alive).
24
+ // - CHOOSE: write the claim JSON to `tmp-<token>.json` (never listed), then
25
+ // `rename` it to `choosing-<pid>-<threadId>-<token>.json`. A visible claim is
26
+ // therefore ALWAYS complete — `writeFileSync` exposing a half-written file is
27
+ // closed off. Any visible claim that still fails to parse is treated as a LIVE
28
+ // BLOCKER (wait), never skipped; if that persists to the deadline the refusal
29
+ // names the file.
30
+ // - TICKET: list the directory; ticket = 1 + max(ticket of every visible
31
+ // `ticket-…` claim, dead or alive; 0 if none). Atomically rename `choosing-…`
32
+ // -> `ticket-<zero-padded ticket>-<pid>-<threadId>-<token>.json`.
33
+ // - WAIT: poll (LOCK_WAIT_POLL_MS); list; unlink `ticket-…` and `choosing-…`
34
+ // claims whose pid is dead (that file only); if ANY live `choosing-…` claim
35
+ // exists -> keep waiting; else the holder is the live `ticket-…` claim with
36
+ // the smallest (ticket, name); if it is mine -> HOLD; else wait. Deadline ->
37
+ // unlink my own claim(s) and REFUSE with the truth (the holder claim, or
38
+ // "a contender is still choosing: <file>").
39
+ // - CORRECTNESS. My ticket is chosen only AFTER my choosing marker is visible.
40
+ // Any contender that has already decided either saw my marker (and waits), or
41
+ // its ticket was visible when I chose — and then mine is strictly larger.
42
+ // Concurrent choosers see each other's markers, both wait, and the tie on
43
+ // equal tickets is broken by name. A crash between CHOOSE and TICKET leaves a
44
+ // dead-pid choosing claim that others unlink.
45
+ // - FAILURE MODE (fail closed). A dead WORKER THREAD inside a live process (or
46
+ // a reused pid / EPERM) leaves a claim that blocks every contender until the
47
+ // deadline -> refusals until the process restarts. `createdAt` stays
48
+ // informational; process-start identity is a possible later refinement, not
49
+ // this PR.
50
+ // - Release = unlink your own claim in `finally`.
51
+ // - The lock dir being unwritable (EACCES/ENOENT-on-create) -> REFUSE identity
52
+ // creation; never fall back to an in-process chain, never mint unlocked.
53
+ //
54
+ // SCOPE: this serialises the GET create path across the workers and processes
55
+ // that share one Flair home. `flair init --remote` (src/cli.ts) does not take the
56
+ // lock yet — the CLI writer must join it in slice 2.
57
+ import { readFileSync, readdirSync, mkdirSync, unlinkSync, writeFileSync, renameSync } from "node:fs";
58
+ import { join } from "node:path";
59
+ import { randomBytes } from "node:crypto";
60
+ import { threadId } from "node:worker_threads";
61
+ import { decideInstanceAnswer } from "../src/lib/instance-identity-row.js";
62
+ export const LOCK_DEADLINE_MS = 10_000;
63
+ export const LOCK_WAIT_POLL_MS = 25;
64
+ /** The keystore-write failure note (flair#1233) — a read path must not abort. */
65
+ export const KEYSTORE_FAILURE_NOTE = "[federation] Could not store the federation signing key seed in the keystore " +
66
+ "($HOME/.flair/keys, relative to the Harper process's HOME). The identity row was created and " +
67
+ "reads work, but this instance cannot sign — pair/sync will fail until the keystore is fixed. " +
68
+ "Remedy: make $HOME/.flair/keys a directory writable by the Harper process (mode 0700). " +
69
+ "The seed for THIS identity was never stored, so after fixing the keystore, re-key: delete the " +
70
+ "Instance row and re-pair to mint a fresh identity.";
71
+ /** The lock-dir remedy, in the same style as KEYSTORE_FAILURE_NOTE. */
72
+ export const LOCK_DIR_REMEDY = "Remedy: make the Flair home writable by the Harper process (a directory the process can create " +
73
+ "$HOME/.flair/locks with mode 0700). Identity creation is REFUSED while the lock dir is unusable.";
74
+ /**
75
+ * Harper's data root for THIS process — the `ROOTPATH` env var Harper sets for a
76
+ * component (read the same way `resources/models-dir.ts` reads it). The lock lives
77
+ * with the STORE it protects, never with the keystore.
78
+ */
79
+ export function harperRootPath(env = process.env) {
80
+ const root = (env.ROOTPATH ?? "").trim();
81
+ return root || process.cwd();
82
+ }
83
+ /**
84
+ * The identity-create lock directory. It lives with the STORE whose Instance table
85
+ * it protects — `<rootPath>/flair-locks/instance-create/` — NOT under the keystore's
86
+ * `$HOME/.flair`. WHY: flair#1233's contract is that an UNUSABLE keystore must not
87
+ * abort the read path (the identity row is still created and reads answer 200 with
88
+ * `signingKeyAvailable:false`); a lock under `$HOME/.flair` turned a FILE
89
+ * `HOME/.flair` into a 503. A store whose ROOT is unwritable cannot run Harper at
90
+ * all, so an unusable lock dir THERE is a genuine refusal and stays one.
91
+ * `lockRoot` is a TEST seam only; production never passes it.
92
+ */
93
+ export function instanceCreateLockDir(lockRoot) {
94
+ return join(lockRoot ?? harperRootPath(), "flair-locks", "instance-create");
95
+ }
96
+ /** `process.kill(pid, 0)`: ESRCH = dead, EPERM = alive (a live pid we can't signal). */
97
+ export function pidAlive(pid) {
98
+ if (!Number.isInteger(pid) || pid <= 0)
99
+ return false;
100
+ try {
101
+ process.kill(pid, 0);
102
+ return true;
103
+ }
104
+ catch (err) {
105
+ return err?.code === "EPERM";
106
+ }
107
+ }
108
+ const CHOOSING_RE = /^choosing-(\d+)-(\d+)-[0-9a-f]+\.json$/;
109
+ const TICKET_RE = /^ticket-(\d+)-(\d+)-(\d+)-[0-9a-f]+\.json$/;
110
+ /**
111
+ * Split the lock dir into: live claims, and BLOCKERS — recognised claim files
112
+ * whose BODY is missing, invalid, or whose `pid` disagrees with the pid in the
113
+ * FILENAME. A recognised claim's pid is taken FROM THE FILENAME; the body only
114
+ * corroborates it. A mismatch is a live BLOCKER (wait; the deadline names it) and
115
+ * is NEVER unlinked by another contender; only a claim whose FILENAME pid is
116
+ * provably dead (ESRCH) is unlinked. Stray names (not tmp-/choosing-/ticket-)
117
+ * stay ignored.
118
+ */
119
+ export function listClaims(dir) {
120
+ const claims = [];
121
+ const blockers = [];
122
+ let names = [];
123
+ try {
124
+ names = readdirSync(dir);
125
+ }
126
+ catch {
127
+ return { claims, blockers };
128
+ }
129
+ for (const name of names) {
130
+ const choosing = CHOOSING_RE.exec(name);
131
+ const ticket = TICKET_RE.exec(name);
132
+ if (!choosing && !ticket)
133
+ continue; // tmp-… and foreign files are not claims
134
+ // The pid is the FILENAME's: choosing-<pid>-<tid>-<token>; ticket-<n>-<pid>-<tid>-<token>.
135
+ const filePid = Number(choosing ? choosing[1] : ticket[2]);
136
+ let parsed;
137
+ try {
138
+ parsed = JSON.parse(readFileSync(join(dir, name), "utf8"));
139
+ }
140
+ catch {
141
+ // A visible claim whose body cannot be read is a LIVE BLOCKER.
142
+ blockers.push(name);
143
+ continue;
144
+ }
145
+ const bodyPid = Number(parsed?.pid);
146
+ if (!Number.isInteger(bodyPid) || bodyPid !== filePid) {
147
+ // Missing / invalid / filename-mismatched body: a LIVE BLOCKER, never "dead".
148
+ blockers.push(name);
149
+ continue;
150
+ }
151
+ if (pidAlive(filePid)) {
152
+ claims.push({ name, kind: choosing ? "choosing" : "ticket", pid: filePid, ticket: ticket ? Number(ticket[1]) : null });
153
+ }
154
+ else {
155
+ // Only a provably-dead FILENAME pid is reclaimed (that file only).
156
+ try {
157
+ unlinkSync(join(dir, name));
158
+ }
159
+ catch {
160
+ /* another contender removed it */
161
+ }
162
+ }
163
+ }
164
+ return { claims, blockers };
165
+ }
166
+ /** ticket = 1 + max(ticket of every visible ticket-… claim, dead or alive; 0 if none). */
167
+ export function nextTicket(dir) {
168
+ let max = 0;
169
+ let names = [];
170
+ try {
171
+ names = readdirSync(dir);
172
+ }
173
+ catch {
174
+ return 1;
175
+ }
176
+ for (const name of names) {
177
+ const m = TICKET_RE.exec(name);
178
+ if (m)
179
+ max = Math.max(max, Number(m[1]));
180
+ }
181
+ return max + 1;
182
+ }
183
+ /**
184
+ * Take the bakery lock: CHOOSE (write+rename a `choosing` marker), TICKET
185
+ * (rename to a `ticket` claim), then WAIT until mine is the smallest live ticket.
186
+ * Returns a release fn, or a refusal detail (deadline, or an unusable lock dir).
187
+ * Cross-worker and cross-process.
188
+ */
189
+ export async function acquireInstanceCreateLock(opts = {}) {
190
+ const dir = instanceCreateLockDir(opts.lockRoot);
191
+ const log = opts.log ?? ((m) => console.error(m));
192
+ try {
193
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
194
+ }
195
+ catch (err) {
196
+ return { ok: false, detail: `the identity-create lock dir is unusable (${dir}): ${err?.message ?? err}. ${LOCK_DIR_REMEDY}` };
197
+ }
198
+ const pid = process.pid;
199
+ const tid = threadId;
200
+ const token = randomBytes(8).toString("hex");
201
+ const tmpFile = join(dir, `tmp-${token}.json`);
202
+ const choosingFile = join(dir, `choosing-${pid}-${tid}-${token}.json`);
203
+ const payload = JSON.stringify({ pid, threadId: tid, token, createdAt: new Date().toISOString() });
204
+ // Every file this contender created. `release` unlinks them (ENOENT ignored) and
205
+ // is called on EVERY exit — a hold, a refusal, or a throw from a hook — so no
206
+ // claim is ever left behind by a contender that did not hold.
207
+ const mine = new Set();
208
+ const release = () => {
209
+ for (const f of [...mine]) {
210
+ try {
211
+ unlinkSync(f);
212
+ }
213
+ catch (err) {
214
+ if (err?.code !== "ENOENT") {
215
+ log(`[federation] identity-create lock: could not unlink ${f} on release (${err?.message ?? err}). ` +
216
+ `That claim's pid stays alive, so later identity creation refuses until this process exits.`);
217
+ }
218
+ }
219
+ mine.delete(f);
220
+ }
221
+ };
222
+ // The deadline starts BEFORE CHOOSE, so a contender held in the choosing state
223
+ // past it removes its marker and refuses too.
224
+ const deadline = Date.now() + (opts.deadlineMs ?? LOCK_DEADLINE_MS);
225
+ let ticketName = "";
226
+ try {
227
+ // CHOOSE: a visible claim is written complete (tmp then atomic rename).
228
+ try {
229
+ writeFileSync(tmpFile, payload, { flag: "wx", mode: 0o600 });
230
+ mine.add(tmpFile);
231
+ renameSync(tmpFile, choosingFile);
232
+ mine.delete(tmpFile);
233
+ mine.add(choosingFile);
234
+ }
235
+ catch (err) {
236
+ release();
237
+ return { ok: false, detail: `could not create the identity-create claim (${choosingFile}): ${err?.message ?? err}. ${LOCK_DIR_REMEDY}` };
238
+ }
239
+ await opts.hooks?.afterChoosing?.();
240
+ if (Date.now() >= deadline) {
241
+ release();
242
+ return {
243
+ ok: false,
244
+ detail: `could not acquire the identity-create lock within ${(opts.deadlineMs ?? LOCK_DEADLINE_MS) / 1000}s ` +
245
+ `(a contender is still choosing: ${choosingFile}). Remedy: retry; if it persists, restart the Harper process.`,
246
+ };
247
+ }
248
+ // TICKET: 1 + the max ticket any visible ticket claim carries.
249
+ const ticket = nextTicket(dir);
250
+ ticketName = `ticket-${String(ticket).padStart(12, "0")}-${pid}-${tid}-${token}.json`;
251
+ const ticketFile = join(dir, ticketName);
252
+ try {
253
+ renameSync(choosingFile, ticketFile);
254
+ mine.delete(choosingFile);
255
+ mine.add(ticketFile);
256
+ }
257
+ catch (err) {
258
+ release();
259
+ return { ok: false, detail: `could not create the identity-create ticket (${ticketFile}): ${err?.message ?? err}. ${LOCK_DIR_REMEDY}` };
260
+ }
261
+ await opts.hooks?.afterTicket?.();
262
+ for (;;) {
263
+ const { claims, blockers } = listClaims(dir);
264
+ const liveChoosing = claims.filter((c) => c.kind === "choosing");
265
+ const liveTickets = claims
266
+ .filter((c) => c.kind === "ticket")
267
+ .sort((a, b) => (a.ticket - b.ticket) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
268
+ if (blockers.length === 0 && liveChoosing.length === 0 && liveTickets[0]?.name === ticketName) {
269
+ return { ok: true, release };
270
+ }
271
+ if (Date.now() >= deadline) {
272
+ release();
273
+ const held = blockers.length > 0
274
+ ? `the blocking claim ${blockers[0]}`
275
+ : liveChoosing.length > 0
276
+ ? `the blocking claim ${liveChoosing[0].name} (still choosing)`
277
+ : liveTickets.length > 0
278
+ ? `holder claim ${liveTickets[0].name}, pid ${liveTickets[0].pid}`
279
+ : "no live holder claim";
280
+ return {
281
+ ok: false,
282
+ detail: `could not acquire the identity-create lock within ${(opts.deadlineMs ?? LOCK_DEADLINE_MS) / 1000}s ` +
283
+ `(${held}). Remedy: retry; if it persists, restart the Harper process — a stuck holder inside the ` +
284
+ `same process cannot be told from a live one.`,
285
+ };
286
+ }
287
+ await new Promise((r) => setTimeout(r, LOCK_WAIT_POLL_MS));
288
+ }
289
+ }
290
+ catch (err) {
291
+ // A throw anywhere (including from a hook) releases whatever we created.
292
+ release();
293
+ throw err;
294
+ }
295
+ }
296
+ /**
297
+ * Find the instance identity, minting one only when a read UNDER the ticket lock
298
+ * found no row. The lock is a filesystem bakery shared by every HTTP worker of
299
+ * this Harper process AND every process sharing this Flair home (flair#1897), so
300
+ * concurrent first-boot GETs mint ONE row and every caller is answered it.
301
+ */
302
+ export async function findOrCreateInstance(deps) {
303
+ const log = deps.log ?? ((m) => console.error(m));
304
+ const now = deps.now ?? (() => new Date().toISOString());
305
+ const lock = await acquireInstanceCreateLock({ lockRoot: deps.lockRoot, deadlineMs: deps.lockDeadlineMs, log, hooks: deps.hooks });
306
+ if (!lock.ok)
307
+ return { kind: "refuse-lock", detail: lock.detail };
308
+ try {
309
+ const rows = await deps.readAll();
310
+ const decision = decideInstanceAnswer(rows);
311
+ if (decision.kind === "refuse-multiple")
312
+ return { kind: "refuse-multiple", rows: decision.rows, putCommitted: false };
313
+ if (decision.kind === "answer")
314
+ return { kind: "row", row: decision.row, seeded: await deps.seedPresent(decision.row.id) };
315
+ // No row on a read taken UNDER the lock — the one state that may create.
316
+ const { id, publicKey, secretKey } = deps.mint();
317
+ const row = {
318
+ id,
319
+ publicKey,
320
+ role: "spoke",
321
+ status: "active",
322
+ createdAt: now(),
323
+ updatedAt: now(),
324
+ };
325
+ await deps.put(row);
326
+ let seeded = false;
327
+ try {
328
+ await deps.setSeed(id, secretKey.slice(0, 32));
329
+ seeded = true;
330
+ }
331
+ catch (err) {
332
+ log(`${KEYSTORE_FAILURE_NOTE} ${err?.constructor?.name ?? "Error"}: ${err?.message ?? err}`);
333
+ }
334
+ // Confirming re-read — what is actually there now is what we return.
335
+ const after = await deps.readAll();
336
+ const confirmed = decideInstanceAnswer(after);
337
+ if (confirmed.kind === "refuse-multiple") {
338
+ // This request's own detached put committed a row AND the table holds >1.
339
+ return { kind: "refuse-multiple", rows: confirmed.rows, putCommitted: true, mintedId: id };
340
+ }
341
+ if (confirmed.kind === "none") {
342
+ // The detached put COMMITS BEFORE IT RESOLVES, so a `none` re-read means
343
+ // the seam failed. NO retry — a retry can only mask it. Refuse (5xx).
344
+ return { kind: "refuse-unobservable", mintedId: id };
345
+ }
346
+ if (confirmed.row.id !== id) {
347
+ // A row written outside this lock. Practically unreachable now that the
348
+ // put commits under the lock — a cheap safety net, not an outside-writer
349
+ // claim.
350
+ return {
351
+ kind: "row",
352
+ row: confirmed.row,
353
+ seeded: await deps.seedPresent(confirmed.row.id),
354
+ warning: `GET /FederationInstance: this caller minted ${id} but the confirmed row is ${confirmed.row.id} — answering the survivor, deleting nothing.`,
355
+ };
356
+ }
357
+ // Return the RE-READ row (never the local object we minted).
358
+ return { kind: "row", row: confirmed.row, seeded };
359
+ }
360
+ finally {
361
+ lock.release();
362
+ }
363
+ }
@@ -0,0 +1,43 @@
1
+ import { databases } from "harper";
2
+ import { readableInstanceRows } from "../src/lib/instance-identity-row.js";
3
+ /**
4
+ * Every `flair.Instance` row on this instance, or a THROWN error.
5
+ *
6
+ * The ONE strict Instance reader, shared by every server-side reader that needs
7
+ * the whole table: `GET /FederationInstance` / `POST /FederationPair`
8
+ * (resources/Federation.ts, which re-exports this) and the local-instance
9
+ * write-time stamp (resources/instance-identity.ts, flair#1896). It lives in its
10
+ * own module so the write path does not pull the whole Federation resource and
11
+ * its imports into every process that writes a record; the reader itself is a
12
+ * single implementation, never copied.
13
+ *
14
+ * The readers used to take the first row `search()` yielded. `search()` order is
15
+ * not a fact about an identity: on a table with two rows one reader reported one
16
+ * identity and a pairing peer was handed the other, and which was which depended
17
+ * on the table's internal ordering (flair#1883 round 3).
18
+ *
19
+ * A read that FAILS must not look like a table with no rows: the callers treat
20
+ * it as its own outcome, because only a SUCCESSFUL read of zero rows may mint an
21
+ * identity (and the write-time stamp resolves to null).
22
+ *
23
+ * And neither must a row the reader cannot NAME (flair#1883 round 4): an entry
24
+ * without a usable id used to be skipped here, so a table serving one bad entry
25
+ * (or a good one beside it) read as "the rows I could name" — possibly zero — and
26
+ * the GET's create branch could mint a second identity from a read that never
27
+ * saw the table. `readableInstanceRows` throws instead, which the callers map to
28
+ * 5xx / a null, uncached local id.
29
+ */
30
+ export async function readAllInstanceRows() {
31
+ const raw = [];
32
+ for await (const i of databases.flair.Instance.search())
33
+ raw.push(i);
34
+ // Throws on the first entry without a usable id — before anything is
35
+ // normalized or reported.
36
+ return readableInstanceRows(raw).map((i) => ({
37
+ id: i.id,
38
+ role: i.role ?? null,
39
+ publicKey: i.publicKey ?? null,
40
+ status: i.status ?? null,
41
+ createdAt: i.createdAt ?? null,
42
+ }));
43
+ }
@@ -1,9 +1,11 @@
1
- import { databases } from "harper";
1
+ import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY } from "../src/lib/instance-identity-row.js";
2
+ import { readAllInstanceRows } from "./instance-identity-rows.js";
2
3
  /**
3
4
  * ─── Local instance identity (federation-edge-hardening slice 1) ────────────
4
5
  *
5
- * The write-time `originatorInstanceId` stamp (Memory.ts/Soul.ts/Agent.ts/
6
- * Relationship.ts post()/put()) needs to know THIS instance's own federation
6
+ * The write-time `originatorInstanceId` stamp (resources/originator-instance.ts,
7
+ * called by Memory.ts/Soul.ts/Agent.ts/Relationship.ts post()/put()/patch())
8
+ * needs to know THIS instance's own federation
7
9
  * identity — the same `id` FederationInstance.get() (resources/Federation.ts)
8
10
  * finds-or-creates on first boot and persists in the `Instance` table
9
11
  * (schemas/federation.graphql). Exactly one row is expected in a given
@@ -24,30 +26,113 @@ import { databases } from "harper";
24
26
  * cached, since that state can legitimately change later (federation gets
25
27
  * bootstrapped after this process already started serving writes) and the
26
28
  * cost of re-checking only applies to instances that have never federated.
29
+ *
30
+ * ─── Several Instance rows: stamp NOTHING (flair#1896) ──────────────────────
31
+ *
32
+ * The `Instance` table can hold more than one row (a legacy install, or init's
33
+ * detected race) — a state `flair doctor` reports and `flair init --remote`
34
+ * refuses to create. This used to take the first row of an unordered
35
+ * `Instance.search()` and cache that as THIS instance's id, so with several
36
+ * rows every local record was stamped with an arbitrary identity — one peers
37
+ * may never have pinned.
38
+ *
39
+ * With several rows this module now decides through the SAME shared rule the
40
+ * other readers use (`decideInstanceAnswer`, src/lib/instance-identity-row.ts)
41
+ * and stamps nothing: a null `originatorInstanceId` is the defined
42
+ * local-origin state (schemas/memory.graphql). It does NOT throw — a throw
43
+ * here would fail every local write on such an instance, and a legacy install
44
+ * could lose writes on upgrade.
45
+ *
46
+ * The refusal is cached for at most LOCAL_INSTANCE_REFUSAL_TTL_MS so a write
47
+ * in that state does not re-read the table on every call, and a prune takes
48
+ * effect within the window without a restart. ONE error naming the row count
49
+ * and the prune remedy is logged per refusal window — a bounded line, one per
50
+ * window rather than one per write.
51
+ *
52
+ * The read goes through the SAME strict reader the GET uses
53
+ * (`readAllInstanceRows`, resources/Federation.ts): an entry a reader cannot
54
+ * name is an UNREADABLE read, not a smaller list, and it follows the
55
+ * failed-read path here (null, uncached).
27
56
  */
28
57
  let cachedInstanceId = null;
58
+ /** While `Date.now() < refusalUntilMs` a several-rows refusal is cached. 0 = none. */
59
+ let refusalUntilMs = 0;
60
+ /** Whether the several-rows refusal has already been logged in the current
61
+ * refusal window. Re-armed when a window expires, so a table that stays
62
+ * multi-row logs again once per window rather than once per process. */
63
+ let refusalLogged = false;
64
+ /** The row count of the current refusal window, for the log line. */
65
+ let refusalRowCount = 0;
66
+ /**
67
+ * How long a several-rows refusal is remembered before the table is re-read.
68
+ * "At most a minute" (flair#1896): a write in that state does not pay a table
69
+ * read every call, and a prune takes effect within the window, no restart.
70
+ */
71
+ const LOCAL_INSTANCE_REFUSAL_TTL_MS = 60_000;
72
+ /**
73
+ * Emit the several-rows refusal line ONCE per refusal window. Called wherever
74
+ * the refusal is observed — the fresh read that arms the window and every
75
+ * cached answer inside it — so the once-per-window invariant holds on EVERY
76
+ * path, not just the first. A no-op after the window's first line.
77
+ */
78
+ function logRefusalOnce() {
79
+ if (refusalLogged)
80
+ return;
81
+ refusalLogged = true;
82
+ console.error(`[identity] this instance has ${refusalRowCount} Instance rows, so it has no single canonical identity to stamp on local writes — ` +
83
+ "records are written with no originatorInstanceId (the local-origin state) until the table is resolved. " +
84
+ `Keep one row and delete the rest with: ${INSTANCE_ROW_PRUNE_REMEDY}`);
85
+ }
29
86
  export async function localInstanceId() {
30
87
  if (cachedInstanceId)
31
88
  return cachedInstanceId;
89
+ const now = Date.now();
90
+ if (refusalUntilMs > now) {
91
+ // Cached refusal — no read this call. Still go through the guarded log:
92
+ // within a window it is a no-op, but the invariant is enforced here too.
93
+ logRefusalOnce();
94
+ return null;
95
+ }
96
+ // Past the window (or never armed): re-arm the once-per-window log line, so a
97
+ // table that is STILL multi-row after the window logs again exactly once.
98
+ refusalLogged = false;
99
+ let rows;
32
100
  try {
33
- for await (const row of databases.flair.Instance.search()) {
34
- if (row?.id) {
35
- cachedInstanceId = row.id;
36
- }
37
- break; // exactly one row expected — this instance's own identity
38
- }
101
+ rows = await readAllInstanceRows();
39
102
  }
40
103
  catch {
41
- // Instance table not present (test env / not yet migrated) — no local id.
104
+ // Instance table not present (test env / not yet migrated), a read that
105
+ // FAILED, or a read that returned an entry without a usable id (which the
106
+ // strict reader treats as unreadable) — no local id, uncached, exactly as
107
+ // a table with no rows. Any of these can change on the next call.
108
+ return null;
109
+ }
110
+ const decision = decideInstanceAnswer(rows);
111
+ if (decision.kind === "answer") {
112
+ cachedInstanceId = decision.row.id;
113
+ refusalUntilMs = 0;
114
+ return cachedInstanceId;
115
+ }
116
+ if (decision.kind === "refuse-multiple") {
117
+ refusalRowCount = decision.rows.length;
118
+ logRefusalOnce();
119
+ refusalUntilMs = now + LOCAL_INSTANCE_REFUSAL_TTL_MS;
120
+ return null;
42
121
  }
43
- return cachedInstanceId;
122
+ // "none" — a SUCCESSFUL read found no Instance row: null, uncached, as today.
123
+ return null;
44
124
  }
45
125
  /**
46
126
  * Test-only: force re-resolution on the next localInstanceId() call. The
47
127
  * module-level cache otherwise persists across test files that share the
48
128
  * same `bun test` process (same collision class documented in
49
- * memory-integrity.test.ts re: the Memory class singleton).
129
+ * memory-integrity.test.ts re: the Memory class singleton). Also clears the
130
+ * cached several-rows refusal and its one-per-window log, so a test can
131
+ * exercise each scenario from a clean slate.
50
132
  */
51
133
  export function _resetLocalInstanceIdCacheForTests() {
52
134
  cachedInstanceId = null;
135
+ refusalUntilMs = 0;
136
+ refusalLogged = false;
137
+ refusalRowCount = 0;
53
138
  }