@tpsdev-ai/flair 0.55.2 → 0.57.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.
- package/README.md +18 -19
- package/dist/bridges/builtins/markdown.js +2 -2
- package/dist/bridges/discover.js +2 -2
- package/dist/bridges/runtime/allow-list.js +2 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +125 -26
- package/dist/commands/agent.js +22 -15
- package/dist/commands/attention.js +2 -2
- package/dist/commands/backup.js +2 -2
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +91 -28
- package/dist/commands/export.js +2 -2
- package/dist/commands/federation.js +441 -68
- package/dist/commands/hook.js +4 -4
- package/dist/commands/init.js +59 -12
- package/dist/commands/mcp.js +2 -2
- package/dist/commands/migrate-harness-memory.js +8 -8
- package/dist/commands/rem.js +2 -2
- package/dist/commands/service.js +25 -1
- package/dist/commands/session.js +2 -2
- package/dist/commands/uninstall.js +2 -2
- package/dist/commands/upgrade.js +3 -3
- package/dist/doctor-client.js +5 -23
- package/dist/engine-version.js +2 -2
- package/dist/federation/scheduler.js +5 -5
- package/dist/install/clients.js +5 -10
- package/dist/keystore.js +10 -2
- package/dist/lib/auth-resolve.js +51 -5
- package/dist/lib/doctor-config-path.js +2 -2
- package/dist/lib/flair-paths.js +29 -0
- package/dist/lib/home.js +60 -0
- package/dist/lib/instance-identity-row.js +580 -0
- package/dist/lib/launchd-repair.js +6 -0
- package/dist/lib/mcp-enable.js +4 -4
- package/dist/lib/owned-pins.js +1 -13
- package/dist/lib/redact-token-id.js +197 -0
- package/dist/lib/socket-path-limit.js +120 -0
- package/dist/lib/uninstall-purge.js +2 -18
- package/dist/lib/upgrade-plain-tree.js +2 -2
- package/dist/mcp-client-assertion.js +3 -3
- package/dist/rem/runner.js +3 -3
- package/dist/rem/scheduler.js +5 -5
- package/dist/rem/snapshot.js +2 -2
- package/dist/resources/AgentSeed.js +4 -1
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +232 -78
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +58 -16
- package/dist/resources/MemoryBootstrap.js +19 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +10 -2
- package/dist/resources/MemoryGrant.js +19 -40
- package/dist/resources/MemoryUsage.js +7 -20
- package/dist/resources/OAuth.js +62 -11
- package/dist/resources/Presence.js +135 -47
- package/dist/resources/Relationship.js +3 -11
- package/dist/resources/SemanticSearch.js +25 -13
- package/dist/resources/admin-layout.js +7 -2
- package/dist/resources/auth-middleware.js +32 -5
- package/dist/resources/bm25.js +13 -14
- package/dist/resources/federation-cleanup.js +289 -51
- package/dist/resources/health.js +48 -8
- package/dist/resources/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +94 -10
- package/dist/resources/mcp-handler.js +9 -1
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +4 -5
- package/dist/resources/memory-reflect-lib.js +17 -1
- package/dist/resources/memory-visibility.js +10 -7
- package/dist/resources/rate-limit.js +6 -4
- package/dist/resources/record-type-kit.js +47 -23
- package/dist/resources/search-readiness.js +7 -1
- package/dist/resources/semantic-retrieval-core.js +98 -3
- package/dist/resources/table-helpers.js +33 -0
- package/dist/resources/tool-descriptors/index.js +2 -2
- package/dist/src/keystore.js +10 -2
- package/dist/src/lib/home.js +60 -0
- package/dist/src/lib/instance-identity-row.js +580 -0
- package/dist/src/lib/redact-token-id.js +197 -0
- package/dist/src/rem/scheduler.js +5 -5
- package/dist/version-check.js +2 -2
- package/dist/version-handshake.js +2 -2
- package/docs/api-reference.md +32 -7
- package/docs/auth.md +19 -7
- package/docs/claude-code.md +5 -6
- package/docs/deploying-on-fabric.md +8 -4
- package/docs/deployment.md +26 -37
- package/docs/embedding-in-a-harper-app.md +4 -2
- package/docs/entity-vocabulary.md +5 -5
- package/docs/federation.md +48 -21
- package/docs/hosted-on-fabric.md +7 -4
- package/docs/integrations.md +24 -15
- package/docs/mcp-clients.md +44 -23
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +12 -17
- package/docs/openclaw.md +29 -28
- package/docs/spoke-bringup.md +44 -22
- package/docs/standalone-local.md +12 -16
- package/docs/supply-chain-policy.md +21 -8
- package/docs/system-requirements.md +1 -1
- package/docs/upgrade.md +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instance-identity.ts — the ONE canonical Instance identity row (flair#1883).
|
|
3
|
+
*
|
|
4
|
+
* A Flair instance's identity lives in `flair.Instance`: `id`, `publicKey`,
|
|
5
|
+
* `role`. Two writers disagreed about it. `GET /FederationInstance` FIND-OR-
|
|
6
|
+
* CREATES a row (`role: "spoke"`) on first read; `flair init --remote` INSERTed
|
|
7
|
+
* a SECOND row with a fresh random id. So a hub that had answered a GET before
|
|
8
|
+
* init finished carried a spoke row AND a hub row — and everything downstream
|
|
9
|
+
* that read "the first row of an unordered search()" answered differently
|
|
10
|
+
* depending on which row the table yielded first. On an affected hub the
|
|
11
|
+
* pairing-cleanup sweep found no `hub` role at all and stayed off, so expired
|
|
12
|
+
* bootstrap users accumulated.
|
|
13
|
+
*
|
|
14
|
+
* This module is the decision layer both writers and the cleanup sweep share:
|
|
15
|
+
* pure functions over the rows, plus the ops-API reads/writes the CLI needs.
|
|
16
|
+
* The rules (flair#1883):
|
|
17
|
+
*
|
|
18
|
+
* - exactly one row → that row IS the identity; `--remote` sets its role to
|
|
19
|
+
* `hub` and keeps its id and key (peers know it).
|
|
20
|
+
* - no row → `--remote` creates one, `role: "hub"`.
|
|
21
|
+
* - more than one row → a REFUSAL naming every row, never a silent pick.
|
|
22
|
+
* The READERS obey this too (flair#1883 round 3):
|
|
23
|
+
* `GET /FederationInstance` and `POST /FederationPair`
|
|
24
|
+
* answer a 409 that names the prune, rather than report
|
|
25
|
+
* whichever row the search happened to yield first.
|
|
26
|
+
*
|
|
27
|
+
* Nothing here reads "the first row". `search()` order is not a fact about an
|
|
28
|
+
* identity, and a decision built on it is a coin toss that reports as an answer.
|
|
29
|
+
*
|
|
30
|
+
* The read is unconditional (flair#1883 round 2): an ops-API
|
|
31
|
+
* `search_by_conditions` needs at least one condition, and the
|
|
32
|
+
* `createdAt > "1970-01-01"` one this module used to send EXCLUDED every row
|
|
33
|
+
* whose `createdAt` compares BELOW that string — a date before 1970, an empty
|
|
34
|
+
* string. The column is REQUIRED (`createdAt: String! @indexed`,
|
|
35
|
+
* schemas/federation.graphql), so no legal row omits it; the date-shaped filter
|
|
36
|
+
* was the wrong instrument regardless, because it could hide a row the table is
|
|
37
|
+
* allowed to hold. A row no reader can see is a row `init --remote` does not
|
|
38
|
+
* know about, and the second identity it then inserts is the defect this module
|
|
39
|
+
* exists to end.
|
|
40
|
+
*
|
|
41
|
+
* A read must also ESTABLISH something to be an answer (flair#1883 rounds 3-4).
|
|
42
|
+
* A read that FAILS is not an answer — `null` is its own state (see
|
|
43
|
+
* `decideSweepMode`, `probeInstanceIdentity`). A 200 whose body is not a row
|
|
44
|
+
* list is not a read of zero rows (`readInstanceRows` throws). And a row the
|
|
45
|
+
* reader cannot NAME — an entry with no usable id — makes the whole read
|
|
46
|
+
* unreadable (`readableInstanceRows`): such an entry may be one of several
|
|
47
|
+
* identity rows, and a reader that drops it cannot tell a table it saw from a
|
|
48
|
+
* table it only saw part of. Only a SUCCESSFUL read of zero rows may create.
|
|
49
|
+
*/
|
|
50
|
+
/** The role a properly-provisioned hub's identity row carries. */
|
|
51
|
+
export const HUB_ROLE = "hub";
|
|
52
|
+
/** The Harper role pairing bootstrap users hold; only meaningful on a hub. */
|
|
53
|
+
export const PAIR_INITIATOR_ROLE = "flair_pair_initiator";
|
|
54
|
+
/**
|
|
55
|
+
* The ONE command that resolves a multi-row Instance table. Named by init's
|
|
56
|
+
* refusal and by `flair doctor`, so an operator who reads either has the fix.
|
|
57
|
+
* `--keep <id>` is the row to keep; the rest are deleted (dry-run by default).
|
|
58
|
+
*/
|
|
59
|
+
export const INSTANCE_ROW_PRUNE_COMMAND = "flair federation instance prune";
|
|
60
|
+
/**
|
|
61
|
+
* The prune invocation to hand an operator, naming BOTH forms: the dry run is
|
|
62
|
+
* the command with no `--apply`, and only `--apply` deletes. A remedy that shows
|
|
63
|
+
* the bare command deletes nothing (flair#1883 round 2) — it prints what it
|
|
64
|
+
* WOULD delete and exits 0, which reads as a successful prune.
|
|
65
|
+
*/
|
|
66
|
+
export const INSTANCE_ROW_PRUNE_REMEDY = `${INSTANCE_ROW_PRUNE_COMMAND} --keep <id> (dry run; add --apply to delete)`;
|
|
67
|
+
/**
|
|
68
|
+
* Role comparison is case/space-insensitive: the value round-trips through
|
|
69
|
+
* YAML, JSON and the ops API, and `"Hub"` must not read as "not a hub" — a
|
|
70
|
+
* strict comparison there silently disables the sweep, which is the defect.
|
|
71
|
+
*/
|
|
72
|
+
export function normalizeRole(role) {
|
|
73
|
+
return typeof role === "string" ? role.trim().toLowerCase() : "";
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether a reader can NAME this entry: a non-null object with a non-empty
|
|
77
|
+
* string id. The ONE definition of "usable", shared by the pure decisions below
|
|
78
|
+
* (which filter rows already in hand) and by the readers (which refuse a read
|
|
79
|
+
* that returned an entry it cannot name — flair#1883 round 4).
|
|
80
|
+
*/
|
|
81
|
+
export function isUsableInstanceRow(entry) {
|
|
82
|
+
if (!entry || typeof entry !== "object")
|
|
83
|
+
return false;
|
|
84
|
+
const id = entry.id;
|
|
85
|
+
return typeof id === "string" && id.length > 0;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Rows that carry a usable id, in the order they were read.
|
|
89
|
+
*
|
|
90
|
+
* This DROPS an entry it cannot name, which is right for a decision over rows
|
|
91
|
+
* already in hand and WRONG for a read: `[{}]`, `{results: [null]}` and a good
|
|
92
|
+
* row beside a bad one would all become "the rows I could name". The readers use
|
|
93
|
+
* `readableInstanceRows` instead (flair#1883 round 4).
|
|
94
|
+
*/
|
|
95
|
+
export function usableInstanceRows(rows) {
|
|
96
|
+
if (!Array.isArray(rows))
|
|
97
|
+
return [];
|
|
98
|
+
return rows.filter((r) => isUsableInstanceRow(r));
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Every entry of a COMPLETED read, in order — or a thrown error naming the first
|
|
102
|
+
* entry the reader cannot name (flair#1883 round 4).
|
|
103
|
+
*
|
|
104
|
+
* A malformed row is not a missing row. Dropping it makes `[{}]`, or a good row
|
|
105
|
+
* beside a bad one, read as "the rows I could name" — a read that established
|
|
106
|
+
* nothing still looks like a read of one row (or none), and `flair init
|
|
107
|
+
* --remote` creates an identity on the strength of it while `flair doctor`
|
|
108
|
+
* prints "no rows" for a table it only part saw. An entry without a usable id
|
|
109
|
+
* may be one of several identity rows, so the read is UNREADABLE — the same
|
|
110
|
+
* outcome as a failed read: the callers answer 5xx / report the probe as
|
|
111
|
+
* unreadable, and NOTHING is created, changed or deleted on the strength of it.
|
|
112
|
+
*/
|
|
113
|
+
export function readableInstanceRows(entries) {
|
|
114
|
+
const out = [];
|
|
115
|
+
for (let i = 0; i < entries.length; i++) {
|
|
116
|
+
if (!isUsableInstanceRow(entries[i])) {
|
|
117
|
+
throw new Error(`Instance read: row ${i + 1} of ${entries.length} carries no usable id — treating the read as UNREADABLE. ` +
|
|
118
|
+
"An entry a reader cannot name may be one of several identity rows, and a read that cannot name every row it " +
|
|
119
|
+
"returned is not a read that found no rows: it must not license creating an identity.");
|
|
120
|
+
}
|
|
121
|
+
out.push(entries[i]);
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/** `id=… role=… createdAt=…` — every field named, never positionally. */
|
|
126
|
+
export function formatInstanceRow(row) {
|
|
127
|
+
const role = typeof row.role === "string" && row.role.length > 0 ? row.role : "(none)";
|
|
128
|
+
const createdAt = typeof row.createdAt === "string" && row.createdAt.length > 0 ? row.createdAt : "(unknown)";
|
|
129
|
+
return `id=${row.id} role=${role} createdAt=${createdAt}`;
|
|
130
|
+
}
|
|
131
|
+
/** The role of the canonical row, or null when there is not exactly one. */
|
|
132
|
+
export function canonicalInstanceRole(rows) {
|
|
133
|
+
const usable = usableInstanceRows(rows);
|
|
134
|
+
if (usable.length !== 1)
|
|
135
|
+
return null;
|
|
136
|
+
const role = normalizeRole(usable[0].role);
|
|
137
|
+
return role.length > 0 ? role : null;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* What `flair init --remote` must do to this instance's identity rows.
|
|
141
|
+
*
|
|
142
|
+
* `already-hub` is its own outcome, not a flavour of `update-role`: a re-run
|
|
143
|
+
* must not write anything (the issue's "re-running is a no-op").
|
|
144
|
+
*/
|
|
145
|
+
export function decideHubReconcile(rows) {
|
|
146
|
+
const usable = usableInstanceRows(rows);
|
|
147
|
+
if (usable.length === 0)
|
|
148
|
+
return { kind: "create" };
|
|
149
|
+
if (usable.length > 1)
|
|
150
|
+
return { kind: "refuse-multiple", rows: usable };
|
|
151
|
+
const row = usable[0];
|
|
152
|
+
return normalizeRole(row.role) === HUB_ROLE ? { kind: "already-hub", id: row.id } : { kind: "update-role", id: row.id };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* What a READER answers with, given every Instance row it could read.
|
|
156
|
+
*
|
|
157
|
+
* This is the server side of the same rule the writers follow, and it exists
|
|
158
|
+
* because two readers still answered with the first row of an unordered search:
|
|
159
|
+
* `GET /FederationInstance` (`resources/Federation.ts`) and the hub identity in
|
|
160
|
+
* the `POST /FederationPair` response, which a spoke PINS as its hub peer
|
|
161
|
+
* (`src/commands/federation.ts`) — so a coin toss there becomes the identity a
|
|
162
|
+
* peer keeps. More than one row is therefore a refusal, not a pick.
|
|
163
|
+
*
|
|
164
|
+
* `none` is a real outcome and is the caller's to interpret: `GET` creates its
|
|
165
|
+
* first identity from it, and `POST /FederationPair` reports `instance: null`
|
|
166
|
+
* (flair#839 — the spoke must error rather than store an empty key).
|
|
167
|
+
*
|
|
168
|
+
* A count of zero here means the read SUCCEEDED and found nothing. A read that
|
|
169
|
+
* failed never reaches this function (the caller answers 503 and writes
|
|
170
|
+
* nothing); a read that returned an unparseable body is a failure too (see
|
|
171
|
+
* `readInstanceRows`) — never a zero.
|
|
172
|
+
*/
|
|
173
|
+
export function decideInstanceAnswer(rows) {
|
|
174
|
+
const usable = usableInstanceRows(rows);
|
|
175
|
+
if (usable.length === 0)
|
|
176
|
+
return { kind: "none" };
|
|
177
|
+
if (usable.length > 1)
|
|
178
|
+
return { kind: "refuse-multiple", rows: usable };
|
|
179
|
+
return { kind: "answer", row: usable[0] };
|
|
180
|
+
}
|
|
181
|
+
/** The refusal for a multi-row Instance table: every row, then the remedy. */
|
|
182
|
+
export function multipleInstanceRowsMessage(rows, context = "flair init --remote") {
|
|
183
|
+
const usable = usableInstanceRows(rows);
|
|
184
|
+
return [
|
|
185
|
+
`${context} refused: this instance has ${usable.length} Instance rows, so it has no single canonical identity.`,
|
|
186
|
+
...usable.map((r) => ` ${formatInstanceRow(r)}`),
|
|
187
|
+
`Keep one row and delete the rest with: ${INSTANCE_ROW_PRUNE_REMEDY}`,
|
|
188
|
+
].join("\n");
|
|
189
|
+
}
|
|
190
|
+
export function verifyInstanceWrite(rows, expectedId) {
|
|
191
|
+
const decision = decideHubReconcile(rows);
|
|
192
|
+
if (decision.kind === "refuse-multiple")
|
|
193
|
+
return { kind: "refuse-multiple", rows: decision.rows };
|
|
194
|
+
if (decision.kind === "already-hub" && decision.id === expectedId)
|
|
195
|
+
return { kind: "verified" };
|
|
196
|
+
return { kind: "not-verified", found: usableInstanceRows(rows) };
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The refusal for a write the re-read did not confirm. It names the row(s) the
|
|
200
|
+
* re-read found, because an empty table ("the write did not land") and one other
|
|
201
|
+
* row ("the write landed elsewhere") are different operator problems.
|
|
202
|
+
*/
|
|
203
|
+
export function instanceWriteNotVerifiedMessage(expectedId, found) {
|
|
204
|
+
const rows = found.length === 0
|
|
205
|
+
? "the re-read found no rows at all"
|
|
206
|
+
: `the re-read found ${found.length === 1 ? "one row" : `${found.length} rows`}: ${found.map(formatInstanceRow).join("; ")}`;
|
|
207
|
+
return [
|
|
208
|
+
`flair init --remote refused: the write is not confirmed — expected one row, id=${expectedId} role=${HUB_ROLE}, and ${rows}.`,
|
|
209
|
+
"An absent or different identity is not a successful init, so this instance's identity is NOT being reported as reconciled.",
|
|
210
|
+
`Re-run \`flair init --remote\`. If the table holds rows that disagree, resolve them with: ${INSTANCE_ROW_PRUNE_REMEDY}`,
|
|
211
|
+
].join("\n");
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Whether the pairing-cleanup sweep should run, from the CURRENT rows.
|
|
215
|
+
*
|
|
216
|
+
* `unreadable` is its own state: an Instance read that failed is not a spoke.
|
|
217
|
+
* Both mean "do not sweep", but only one of them is worth a log line, and
|
|
218
|
+
* neither may be reported as the other.
|
|
219
|
+
*/
|
|
220
|
+
export function decideSweepMode(rows) {
|
|
221
|
+
if (rows === null)
|
|
222
|
+
return "unreadable";
|
|
223
|
+
const usable = usableInstanceRows(rows);
|
|
224
|
+
if (usable.length > 1)
|
|
225
|
+
return "multiple";
|
|
226
|
+
if (usable.length === 0)
|
|
227
|
+
return "not-hub";
|
|
228
|
+
return normalizeRole(usable[0].role) === HUB_ROLE ? "hub" : "not-hub";
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* What doctor prints when there is NO finding: the row facts, and — when the
|
|
232
|
+
* role list could not be read — that the pairing-role check is UNVERIFIED.
|
|
233
|
+
*
|
|
234
|
+
* A finding list that is empty because a read FAILED must not render like a
|
|
235
|
+
* finding list that is empty because the instance is consistent (flair#1883
|
|
236
|
+
* round 2): the rows were read, so the row facts are facts, but the pairing-role
|
|
237
|
+
* half of the check did not run.
|
|
238
|
+
*/
|
|
239
|
+
export function instanceIdentitySummary(input) {
|
|
240
|
+
const usable = usableInstanceRows(input.rows);
|
|
241
|
+
const described = usable.length === 0 ? "no rows" : `one row, role=${canonicalInstanceRole(usable) ?? "(none)"}`;
|
|
242
|
+
const unverified = instanceIdentityRoleCheckUnverified(input.roleNames);
|
|
243
|
+
if (unverified !== null) {
|
|
244
|
+
return { level: "unverified", text: `${described}; ${unverified}` };
|
|
245
|
+
}
|
|
246
|
+
return { level: "ok", text: described };
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The pairing-role half of the check as its OWN sentence, or null when that
|
|
250
|
+
* check ran (flair#1883 round 5).
|
|
251
|
+
*
|
|
252
|
+
* `instanceIdentitySummary` carried this sentence inline, which is how it
|
|
253
|
+
* became printable only on the no-finding path. The row facts and the
|
|
254
|
+
* pairing-role state are two facts; reporting one must never swallow the other.
|
|
255
|
+
*/
|
|
256
|
+
export function instanceIdentityRoleCheckUnverified(roleNames) {
|
|
257
|
+
if (roleNames !== null)
|
|
258
|
+
return null;
|
|
259
|
+
return `the ${PAIR_INITIATOR_ROLE} pairing-role check is UNVERIFIED (the role list could not be read)`;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Every Instance-identity line `flair doctor` prints, in order: one line per
|
|
263
|
+
* finding, then the state line.
|
|
264
|
+
*
|
|
265
|
+
* The state is INDEPENDENT of the findings (flair#1883 round 5). Before this,
|
|
266
|
+
* doctor printed the summary only when there was NO finding: several rows AND an
|
|
267
|
+
* unreadable role list reported the rows and said nothing about the pairing-role
|
|
268
|
+
* check that never ran. Here a row finding and the pairing-role UNVERIFIED
|
|
269
|
+
* status are two lines from one call, so neither can be dropped by the other.
|
|
270
|
+
*/
|
|
271
|
+
export function instanceIdentityLines(input) {
|
|
272
|
+
const findings = instanceIdentityFindings(input);
|
|
273
|
+
const lines = findings.map((finding) => {
|
|
274
|
+
const [text, fix] = instanceIdentityFindingLines(finding);
|
|
275
|
+
return { level: "fail", text, fix };
|
|
276
|
+
});
|
|
277
|
+
if (findings.length === 0) {
|
|
278
|
+
const summary = instanceIdentitySummary(input);
|
|
279
|
+
lines.push({ level: summary.level === "ok" ? "ok" : "warn", text: `Instance identity: ${summary.text}` });
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
const unverified = instanceIdentityRoleCheckUnverified(input.roleNames);
|
|
283
|
+
if (unverified !== null)
|
|
284
|
+
lines.push({ level: "warn", text: `Instance identity: ${unverified}` });
|
|
285
|
+
}
|
|
286
|
+
return lines;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* The findings `flair doctor` reports about this instance's identity.
|
|
290
|
+
*
|
|
291
|
+
* `rows: null` or `roleNames: null` means the read did not happen — every
|
|
292
|
+
* finding that would depend on it is omitted rather than guessed. A check that
|
|
293
|
+
* cannot see the state must be silent, never green.
|
|
294
|
+
*/
|
|
295
|
+
export function instanceIdentityFindings(input) {
|
|
296
|
+
const { rows, roleNames } = input;
|
|
297
|
+
if (rows === null)
|
|
298
|
+
return [];
|
|
299
|
+
const findings = [];
|
|
300
|
+
const usable = usableInstanceRows(rows);
|
|
301
|
+
const multiple = usable.length > 1;
|
|
302
|
+
if (multiple) {
|
|
303
|
+
findings.push({
|
|
304
|
+
code: "instance-multiple-rows",
|
|
305
|
+
status: "fail",
|
|
306
|
+
detail: `${usable.length} Instance rows (${usable.map((r) => formatInstanceRow(r)).join("; ")})`,
|
|
307
|
+
remedy: INSTANCE_ROW_PRUNE_REMEDY,
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
if (roleNames !== null) {
|
|
311
|
+
const hasPairRole = roleNames.some((name) => normalizeRole(name) === PAIR_INITIATOR_ROLE);
|
|
312
|
+
const canonicalRole = canonicalInstanceRole(usable);
|
|
313
|
+
if (hasPairRole && canonicalRole !== HUB_ROLE) {
|
|
314
|
+
const described = canonicalRole ?? (usable.length === 0 ? "no Instance row" : "no single Instance row");
|
|
315
|
+
findings.push({
|
|
316
|
+
code: "pair-role-not-hub",
|
|
317
|
+
status: "fail",
|
|
318
|
+
// With several rows present, `init --remote` refuses until the table is
|
|
319
|
+
// back to one row (its own refusal names the prune). The remedies are
|
|
320
|
+
// printed in the order they WORK: prune first, then init.
|
|
321
|
+
detail: `the ${PAIR_INITIATOR_ROLE} role exists while this instance is not a hub (${described})`,
|
|
322
|
+
remedy: multiple
|
|
323
|
+
? `${INSTANCE_ROW_PRUNE_REMEDY}, then flair init --remote`
|
|
324
|
+
: "flair init --remote",
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return findings;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* One finding as two printed lines (headline, then the fix), so the plain text
|
|
332
|
+
* is testable without doctor's colour wrapper. The caller prefixes the icon.
|
|
333
|
+
*/
|
|
334
|
+
export function instanceIdentityFindingLines(finding) {
|
|
335
|
+
return [`Instance identity: ${finding.detail}`, `Fix: ${finding.remedy}`];
|
|
336
|
+
}
|
|
337
|
+
function authHeaderFor(endpoint) {
|
|
338
|
+
const creds = endpoint.credentials;
|
|
339
|
+
if (!creds)
|
|
340
|
+
return undefined;
|
|
341
|
+
return `Basic ${Buffer.from(`${creds.user}:${creds.pass}`).toString("base64")}`;
|
|
342
|
+
}
|
|
343
|
+
function opsBaseUrl(opsUrl) {
|
|
344
|
+
return `${opsUrl.replace(/\/$/, "")}/`;
|
|
345
|
+
}
|
|
346
|
+
async function opsPost(endpoint, body, what) {
|
|
347
|
+
const fetchImpl = endpoint.fetchImpl ?? fetch;
|
|
348
|
+
const auth = authHeaderFor(endpoint);
|
|
349
|
+
const res = await fetchImpl(opsBaseUrl(endpoint.opsUrl), {
|
|
350
|
+
method: "POST",
|
|
351
|
+
headers: {
|
|
352
|
+
"Content-Type": "application/json",
|
|
353
|
+
...(auth ? { Authorization: auth } : {}),
|
|
354
|
+
},
|
|
355
|
+
body: JSON.stringify(body),
|
|
356
|
+
signal: AbortSignal.timeout(endpoint.timeoutMs ?? 10_000),
|
|
357
|
+
});
|
|
358
|
+
if (!res.ok) {
|
|
359
|
+
const text = await res.text().catch(() => "");
|
|
360
|
+
throw new Error(`${what} via ops API failed (${res.status}): ${text || "no body"}`);
|
|
361
|
+
}
|
|
362
|
+
return await res.json().catch(() => null);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Every Instance row on this instance, UNCONDITIONALLY — no WHERE clause, no
|
|
366
|
+
* comparator over a column a row may not carry. Never "the first one", and never
|
|
367
|
+
* "the ones that happen to have a createdAt": the caller decides, and a decision
|
|
368
|
+
* needs the whole set (flair#1883 round 2).
|
|
369
|
+
*
|
|
370
|
+
* SQL is the ops operation that can say "all": `search_by_conditions` requires at
|
|
371
|
+
* least one condition (Harper's searchValidator: `conditions` is `.min(1)`), and
|
|
372
|
+
* any single condition can hide a row.
|
|
373
|
+
*/
|
|
374
|
+
export const INSTANCE_ROWS_SQL = "SELECT id, role, publicKey, status, createdAt FROM flair.Instance";
|
|
375
|
+
export async function readInstanceRows(endpoint) {
|
|
376
|
+
const parsed = await opsPost(endpoint, { operation: "sql", sql: INSTANCE_ROWS_SQL }, "Instance read");
|
|
377
|
+
// A 200 whose body is not a row list is a read that established NOTHING
|
|
378
|
+
// (flair#1883 round 3). It used to become `[]`, which is the same value a
|
|
379
|
+
// successful read of zero rows returns — so `flair init --remote` would create
|
|
380
|
+
// an identity on the strength of a read it never made, and `flair doctor`
|
|
381
|
+
// would print "no rows" for a table it never saw. Unreadable is its own state
|
|
382
|
+
// and follows the failed-read path: throw. `opsPost` returns null for a body
|
|
383
|
+
// that does not parse at all, so both the invalid-JSON and the
|
|
384
|
+
// unexpected-shape case land here.
|
|
385
|
+
const rows = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
|
|
386
|
+
if (rows === null) {
|
|
387
|
+
throw new Error("Instance read via ops API answered 200 with a body that is neither a row array nor { results: [...] } — " +
|
|
388
|
+
"treating the read as UNREADABLE. A read that established nothing is not a read that found no rows, and it " +
|
|
389
|
+
"must not license creating an identity.");
|
|
390
|
+
}
|
|
391
|
+
// Every entry must be nameable (flair#1883 round 4): a body carrying an entry
|
|
392
|
+
// without a usable id established nothing about the table, and it follows the
|
|
393
|
+
// failed-read path rather than reporting the rows it could name.
|
|
394
|
+
return readableInstanceRows(rows);
|
|
395
|
+
}
|
|
396
|
+
/** Role names on this instance, or null when the read did not happen. */
|
|
397
|
+
export async function readRoleNames(endpoint) {
|
|
398
|
+
try {
|
|
399
|
+
const parsed = await opsPost(endpoint, { operation: "list_roles" }, "list_roles");
|
|
400
|
+
const roles = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.roles) ? parsed.roles : null;
|
|
401
|
+
if (roles === null)
|
|
402
|
+
return null;
|
|
403
|
+
return roles
|
|
404
|
+
.map((r) => (typeof r === "string" ? r : r?.role ?? r?.name))
|
|
405
|
+
.filter((name) => typeof name === "string");
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* What a Harper write result says actually happened, in ONE place.
|
|
413
|
+
*
|
|
414
|
+
* A `delete` answers 200 with the removed ids in `deleted_hashes`; an `update`
|
|
415
|
+
* reports the ids it changed as `update_hashes`. Both name an id they did NOT
|
|
416
|
+
* touch in `skipped_hashes`. HTTP status alone is not the contract (flair#1883):
|
|
417
|
+
* a skipped id is a write that did not happen. `changed` is null when the result
|
|
418
|
+
* body reports no ids at all — also a write that cannot be confirmed.
|
|
419
|
+
*/
|
|
420
|
+
export function readWriteResult(result, changedField) {
|
|
421
|
+
const body = (result ?? {});
|
|
422
|
+
const raw = body[changedField];
|
|
423
|
+
const skippedRaw = body.skipped_hashes;
|
|
424
|
+
return {
|
|
425
|
+
changed: Array.isArray(raw) ? raw : null,
|
|
426
|
+
skipped: Array.isArray(skippedRaw) ? skippedRaw.map(String).join(", ") : "unknown",
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Whether a Harper write result CONFIRMS that `id` was written: the result names
|
|
431
|
+
* it in the changed field, does not also name it in `skipped_hashes`, and carries
|
|
432
|
+
* no `error`. Anything else, including a contradictory result that names the id
|
|
433
|
+
* as both changed and skipped, is not a confirmation. One rule for every write
|
|
434
|
+
* this module and the cleanup sweep verify.
|
|
435
|
+
*/
|
|
436
|
+
export function writeConfirmed(result, changedField, id) {
|
|
437
|
+
const body = (result ?? {});
|
|
438
|
+
if (body.error !== undefined && body.error !== null)
|
|
439
|
+
return false;
|
|
440
|
+
const changed = body[changedField];
|
|
441
|
+
if (!Array.isArray(changed) || !changed.map(String).includes(id))
|
|
442
|
+
return false;
|
|
443
|
+
const skipped = body.skipped_hashes;
|
|
444
|
+
return !(Array.isArray(skipped) && skipped.map(String).includes(id));
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Set the canonical row's role, keeping its id and key. Verified against the
|
|
448
|
+
* result body: a Harper `update` answers 200 with the changed hashes in
|
|
449
|
+
* `update_hashes` and names a miss in `skipped_hashes`, so HTTP status alone
|
|
450
|
+
* would let a missing row read as a successful reconcile.
|
|
451
|
+
*/
|
|
452
|
+
export async function updateInstanceRole(endpoint, id, role) {
|
|
453
|
+
const parsed = await opsPost(endpoint, {
|
|
454
|
+
operation: "update",
|
|
455
|
+
database: "flair",
|
|
456
|
+
table: "Instance",
|
|
457
|
+
records: [{ id, role, updatedAt: new Date().toISOString() }],
|
|
458
|
+
}, `Instance role update for ${id}`);
|
|
459
|
+
const { skipped } = readWriteResult(parsed, "update_hashes");
|
|
460
|
+
if (!writeConfirmed(parsed, "update_hashes", id)) {
|
|
461
|
+
throw new Error(`Instance role update for ${id} changed no row (skipped: ${skipped}). ` +
|
|
462
|
+
`The row was deleted or replaced between the read and the write — re-run and check ${INSTANCE_ROW_PRUNE_COMMAND} for a second row.`);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Delete one Instance row. Used only by `flair federation instance prune`.
|
|
467
|
+
*
|
|
468
|
+
* Verified against the result body, like `updateInstanceRole` (flair#1883 round
|
|
469
|
+
* 5): a Harper `delete` answers 200 with the removed ids in `deleted_hashes` and
|
|
470
|
+
* names an id it did NOT remove in `skipped_hashes`. Status alone would let a
|
|
471
|
+
* skipped row read as deleted, and `prune --apply` would print a row it never
|
|
472
|
+
* removed as gone.
|
|
473
|
+
*/
|
|
474
|
+
export async function deleteInstanceRow(endpoint, id) {
|
|
475
|
+
// `hash_values` is the field Harper's delete schema REQUIRES (a list); the
|
|
476
|
+
// singular `hash_value` is refused with a 400. Verified against a live Harper
|
|
477
|
+
// in test/integration/init-remote-instance-identity.test.ts.
|
|
478
|
+
const parsed = await opsPost(endpoint, { operation: "delete", database: "flair", table: "Instance", hash_values: [id] }, `Instance delete for ${id}`);
|
|
479
|
+
const { skipped } = readWriteResult(parsed, "deleted_hashes");
|
|
480
|
+
if (!writeConfirmed(parsed, "deleted_hashes", id)) {
|
|
481
|
+
throw new Error(`Instance delete for ${id} removed no row (skipped: ${skipped}). ` +
|
|
482
|
+
`The row is still there — re-run ${INSTANCE_ROW_PRUNE_COMMAND} and check the rows it names.`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/** Every row this instance holds, or a thrown error. Doctor uses the probe. */
|
|
486
|
+
export async function listInstanceRows(endpoint) {
|
|
487
|
+
return await readInstanceRows(endpoint);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Read both identity facts doctor needs, degrading to `null` on failure.
|
|
491
|
+
*
|
|
492
|
+
* A read that did not happen must be distinguishable from a read that found
|
|
493
|
+
* nothing: doctor reports the first as unverified and the second as absent.
|
|
494
|
+
*/
|
|
495
|
+
export async function probeInstanceIdentity(endpoint) {
|
|
496
|
+
let rows = null;
|
|
497
|
+
try {
|
|
498
|
+
rows = await readInstanceRows(endpoint);
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
rows = null;
|
|
502
|
+
}
|
|
503
|
+
const roleNames = await readRoleNames(endpoint);
|
|
504
|
+
return { rows, roleNames };
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* What a prune prints when it is about to delete rows (flair#1883 round 3).
|
|
508
|
+
*
|
|
509
|
+
* A peer PINS this instance's identity when it pairs: it is handed `{ id,
|
|
510
|
+
* publicKey, role }` in the `POST /FederationPair` response and stores it as its
|
|
511
|
+
* hub peer. That response was read from the Instance table and — while the table
|
|
512
|
+
* held more than one row — it was whichever row the search yielded first, which
|
|
513
|
+
* is precisely the state a prune exists to resolve. A peer that paired in that
|
|
514
|
+
* state therefore pinned one of the rows, and WHICH one is not determinable
|
|
515
|
+
* here; this helper does not pretend otherwise.
|
|
516
|
+
*
|
|
517
|
+
* Round 2 named the row the hub answered `GET /FederationInstance` with. That
|
|
518
|
+
* was a guess dressed as a fact: with several rows the GET now refuses (409)
|
|
519
|
+
* rather than answer one, and a peer was never handed the GET's answer anyway.
|
|
520
|
+
* What is true, and what the operator needs, is simpler: every row being deleted
|
|
521
|
+
* is a row a paired peer MAY have pinned, and a peer paired with a deleted
|
|
522
|
+
* identity must re-pair.
|
|
523
|
+
*/
|
|
524
|
+
export function prunePeerWarningLines(input) {
|
|
525
|
+
const drop = usableInstanceRows(input.drop);
|
|
526
|
+
if (drop.length === 0)
|
|
527
|
+
return [];
|
|
528
|
+
return [
|
|
529
|
+
"Paired peers pinned this instance's identity from the POST /FederationPair response. While the table held " +
|
|
530
|
+
"more than one Instance row, that response was whichever row the search yielded first — so which row a " +
|
|
531
|
+
"given peer pinned cannot be determined here.",
|
|
532
|
+
`Any of the ${drop.length} row(s) being deleted may be the identity a paired peer pinned. ` +
|
|
533
|
+
"A peer paired with a deleted identity must re-pair.",
|
|
534
|
+
];
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* `flair federation instance prune --keep <id>` — delete every OTHER Instance
|
|
538
|
+
* row, so the instance is back to one canonical identity. The kept row is never
|
|
539
|
+
* touched: its id and key are what peers know.
|
|
540
|
+
*
|
|
541
|
+
* Refuses an id that names no row (a typo must not read as a successful prune).
|
|
542
|
+
*/
|
|
543
|
+
export async function pruneInstanceRows(endpoint, keepId) {
|
|
544
|
+
const rows = await readInstanceRows(endpoint);
|
|
545
|
+
const decision = decideInstancePrune(rows, keepId);
|
|
546
|
+
if (decision.kind === "unknown-id") {
|
|
547
|
+
throw new Error(`--keep ${keepId} names no Instance row on this instance. Rows present: ` +
|
|
548
|
+
decision.rows.map((r) => `\n ${formatInstanceRow(r)}`).join(""));
|
|
549
|
+
}
|
|
550
|
+
if (decision.kind === "nothing")
|
|
551
|
+
return { dropped: [] };
|
|
552
|
+
const dropped = [];
|
|
553
|
+
for (const row of decision.drop) {
|
|
554
|
+
await deleteInstanceRow(endpoint, row.id);
|
|
555
|
+
dropped.push(row.id);
|
|
556
|
+
}
|
|
557
|
+
return { dropped };
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Which rows `prune --keep <id>` deletes.
|
|
561
|
+
*
|
|
562
|
+
* An id that names no row is `unknown-id`, not `nothing`, at EVERY row count:
|
|
563
|
+
* "nothing to do" after a typo reads as a successful prune of the row the
|
|
564
|
+
* operator meant to keep.
|
|
565
|
+
*/
|
|
566
|
+
export function decideInstancePrune(rows, keepId) {
|
|
567
|
+
const usable = usableInstanceRows(rows);
|
|
568
|
+
const keep = usable.find((r) => r.id === keepId);
|
|
569
|
+
if (!keep) {
|
|
570
|
+
// Refused whatever the row count (flair#1883 round 2). With zero or one row
|
|
571
|
+
// there is nothing to delete either, but an id that names no row is a TYPO
|
|
572
|
+
// until proven otherwise, and "nothing to do" after a typo reads as a
|
|
573
|
+
// successful prune of the row the operator meant to keep.
|
|
574
|
+
return { kind: "unknown-id", rows: usable };
|
|
575
|
+
}
|
|
576
|
+
const drop = usable.filter((r) => r.id !== keepId);
|
|
577
|
+
if (drop.length === 0)
|
|
578
|
+
return { kind: "nothing" };
|
|
579
|
+
return { kind: "keep", keep, drop };
|
|
580
|
+
}
|