@tpsdev-ai/flair 0.58.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.
- package/README.md +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1030 -343
- package/dist/commands/agent.js +384 -45
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +601 -163
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +146 -53
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +27 -2
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1775 -338
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +103 -7
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +227 -64
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/OrgSkillAssignment.js +209 -0
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +120 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +6 -6
- package/docs/mcp-clients.md +10 -5
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +34 -28
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
|
@@ -18,6 +18,17 @@
|
|
|
18
18
|
* See test/unit/mcp-client-assertion.test.ts for a mirror of that
|
|
19
19
|
* verification, run against assertions this module produces.
|
|
20
20
|
*
|
|
21
|
+
* ── The audience form (RFC 7523bis transition switch) ───────────────────────
|
|
22
|
+
* RFC 7523bis makes the authorization server's issuer the sole `aud` and
|
|
23
|
+
* defines `typ: client-authentication+jwt`. The verifier's side of that
|
|
24
|
+
* (HarperFast/oauth #245) is merged upstream but NOT RELEASED, so the DEFAULT
|
|
25
|
+
* here stays the shape above and the issuer form is opt-in, via
|
|
26
|
+
* `FLAIR_MCP_CLIENT_ASSERTION_AUDIENCE` or `flair mcp token
|
|
27
|
+
* --assertion-audience`. The issuer form signs `aud` = the issuer read from
|
|
28
|
+
* the authorization server's metadata document — never derived from the
|
|
29
|
+
* token-endpoint URL — with `typ: "client-authentication+jwt"`. The default
|
|
30
|
+
* will be changed in a later PR after a compatible verifier release.
|
|
31
|
+
*
|
|
21
32
|
* ── oauth#161/#162/#163, shipped in @harperfast/oauth@2.2.0 ─────────────────
|
|
22
33
|
* The token-endpoint grant that CONSUMES this assertion
|
|
23
34
|
* (`grant_type=client_credentials`) shipped as HarperFast/oauth PR #170
|
|
@@ -65,6 +76,99 @@ export const CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-as
|
|
|
65
76
|
* assertion signed with a longer window would be rejected server-side.
|
|
66
77
|
*/
|
|
67
78
|
export const MAX_ASSERTION_LIFETIME_SECONDS = 60;
|
|
79
|
+
/** The switch's accepted values, in the order the refusal message lists them. */
|
|
80
|
+
export const CLIENT_ASSERTION_AUDIENCE_FORMS = [
|
|
81
|
+
"token-endpoint",
|
|
82
|
+
"issuer",
|
|
83
|
+
];
|
|
84
|
+
/**
|
|
85
|
+
* The switch's environment variable (`flair mcp token --assertion-audience`
|
|
86
|
+
* overrides it). Default `"token-endpoint"`; an unrecognised value is refused,
|
|
87
|
+
* never treated as the default.
|
|
88
|
+
*/
|
|
89
|
+
export const CLIENT_ASSERTION_AUDIENCE_ENV = "FLAIR_MCP_CLIENT_ASSERTION_AUDIENCE";
|
|
90
|
+
/**
|
|
91
|
+
* The configured audience form, from an explicit flag value (else from
|
|
92
|
+
* CLIENT_ASSERTION_AUDIENCE_ENV). Unset or empty: `"token-endpoint"`.
|
|
93
|
+
*/
|
|
94
|
+
export function clientAssertionAudienceForm(raw = process.env[CLIENT_ASSERTION_AUDIENCE_ENV]) {
|
|
95
|
+
const value = (raw ?? "").trim().toLowerCase();
|
|
96
|
+
if (!value)
|
|
97
|
+
return "token-endpoint";
|
|
98
|
+
if (value === "token-endpoint" || value === "issuer")
|
|
99
|
+
return value;
|
|
100
|
+
throw new Error(`Unknown client-assertion audience form ${JSON.stringify(raw)}: ${CLIENT_ASSERTION_AUDIENCE_ENV} ` +
|
|
101
|
+
`(or --assertion-audience) must be ${CLIENT_ASSERTION_AUDIENCE_FORMS.map((f) => `"${f}"`).join(" or ")}.`);
|
|
102
|
+
}
|
|
103
|
+
/** The header `typ` of the token-endpoint audience form. */
|
|
104
|
+
export const CLIENT_ASSERTION_TYP_JWT = "JWT";
|
|
105
|
+
/** RFC 7523bis §4 explicit `typ`: the header of the issuer audience form. */
|
|
106
|
+
export const CLIENT_ASSERTION_TYP_CLIENT_AUTHENTICATION = "client-authentication+jwt";
|
|
107
|
+
/**
|
|
108
|
+
* The metadata document URL for an authorization server origin — the discovery
|
|
109
|
+
* convention src/lib/mcp-enable.ts already uses.
|
|
110
|
+
*/
|
|
111
|
+
export function oauthMetadataUrl(origin) {
|
|
112
|
+
return `${origin.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`;
|
|
113
|
+
}
|
|
114
|
+
function isUsableIssuerUrl(value) {
|
|
115
|
+
try {
|
|
116
|
+
const url = new URL(value);
|
|
117
|
+
// RFC 8414 issuer identifiers cannot contain query or fragment components,
|
|
118
|
+
// including empty delimiters (`?` and `#`). URL.search/hash alone miss those.
|
|
119
|
+
return (url.protocol === "https:" || url.protocol === "http:") &&
|
|
120
|
+
!url.href.includes("?") && !url.href.includes("#");
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Read the `issuer` from the authorization server metadata document at
|
|
128
|
+
* `metadataUrl`. Refuses — naming the switch and the URL — when the document
|
|
129
|
+
* cannot be read, or carries no usable issuer.
|
|
130
|
+
*/
|
|
131
|
+
export async function fetchAuthorizationServerIssuer(metadataUrl, deps = {}) {
|
|
132
|
+
const setting = `${CLIENT_ASSERTION_AUDIENCE_ENV}=issuer (--assertion-audience issuer)`;
|
|
133
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
134
|
+
let res;
|
|
135
|
+
try {
|
|
136
|
+
res = await fetchImpl(metadataUrl, { signal: AbortSignal.timeout(15_000) });
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
throw new Error(`${setting}, but the metadata document at ${metadataUrl} could not be read: ${err?.message ?? err}`);
|
|
140
|
+
}
|
|
141
|
+
if (!res.ok)
|
|
142
|
+
throw new Error(`${setting}, but the metadata document at ${metadataUrl} returned HTTP ${res.status}`);
|
|
143
|
+
let body;
|
|
144
|
+
try {
|
|
145
|
+
body = await res.json();
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
throw new Error(`${setting}, but the metadata document at ${metadataUrl} did not return JSON`);
|
|
149
|
+
}
|
|
150
|
+
const issuer = body?.issuer;
|
|
151
|
+
if (typeof issuer !== "string" || !isUsableIssuerUrl(issuer)) {
|
|
152
|
+
throw new Error(`${setting}, but the metadata document at ${metadataUrl} has no usable issuer (got ${JSON.stringify(issuer)}).`);
|
|
153
|
+
}
|
|
154
|
+
return issuer;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Build the audience for a form. The token-endpoint form is today's shape. The
|
|
158
|
+
* issuer form reads the metadata document at `metadataUrl` and uses its
|
|
159
|
+
* `issuer` as the SOLE `aud` — never the token-endpoint URL, and never a value
|
|
160
|
+
* derived from it.
|
|
161
|
+
*/
|
|
162
|
+
export async function resolveClientAssertionAudience(params) {
|
|
163
|
+
if (params.form === "token-endpoint")
|
|
164
|
+
return { aud: params.tokenEndpoint, typ: CLIENT_ASSERTION_TYP_JWT };
|
|
165
|
+
if (!params.metadataUrl) {
|
|
166
|
+
throw new Error(`${CLIENT_ASSERTION_AUDIENCE_ENV}=issuer (--assertion-audience issuer) needs the authorization server's ` +
|
|
167
|
+
`metadata document: pass --issuer (or set FLAIR_MCP_ISSUER/FLAIR_PUBLIC_URL).`);
|
|
168
|
+
}
|
|
169
|
+
const issuer = await fetchAuthorizationServerIssuer(params.metadataUrl, params.fetchImpl ? { fetchImpl: params.fetchImpl } : {});
|
|
170
|
+
return { aud: issuer, typ: CLIENT_ASSERTION_TYP_CLIENT_AUTHENTICATION };
|
|
171
|
+
}
|
|
68
172
|
// ─── Key loading ────────────────────────────────────────────────────────────
|
|
69
173
|
/**
|
|
70
174
|
* Locate an agent's private key file. Search order mirrors `resolveKeyPath`
|
|
@@ -150,10 +254,13 @@ export function signClientAssertion(params) {
|
|
|
150
254
|
const iat = Math.floor(params.nowSeconds ?? Date.now() / 1000);
|
|
151
255
|
const exp = iat + expiresIn;
|
|
152
256
|
const jti = params.jti ?? randomUUID();
|
|
153
|
-
// header.typ is optional per RFC 7515 §4.1.9, but
|
|
154
|
-
// present
|
|
155
|
-
|
|
156
|
-
|
|
257
|
+
// header.typ is optional per RFC 7515 §4.1.9, but the verifier checks it
|
|
258
|
+
// when present — include it: "JWT" for the token-endpoint form (what the
|
|
259
|
+
// released verifier accepts when present), and "client-authentication+jwt" (RFC
|
|
260
|
+
// 7523bis) for the issuer form.
|
|
261
|
+
const audience = params.audience ?? { aud: tokenEndpoint, typ: CLIENT_ASSERTION_TYP_JWT };
|
|
262
|
+
const header = { alg: "EdDSA", typ: audience.typ };
|
|
263
|
+
const claims = { iss: clientId, sub: clientId, aud: audience.aud, exp, iat, jti };
|
|
157
264
|
const headerB64 = base64urlJson(header);
|
|
158
265
|
const payloadB64 = base64urlJson(claims);
|
|
159
266
|
const signingInput = `${headerB64}.${payloadB64}`;
|
|
@@ -319,6 +426,7 @@ export async function getMcpAccessToken(params) {
|
|
|
319
426
|
tokenEndpoint: params.tokenEndpoint,
|
|
320
427
|
privateKey: params.privateKey,
|
|
321
428
|
expiresInSeconds: params.expiresInSeconds,
|
|
429
|
+
audience: params.audience,
|
|
322
430
|
});
|
|
323
431
|
const form = buildTokenRequestForm({ clientId: params.clientId, assertion, resource: params.resource });
|
|
324
432
|
const token = await requestMcpAccessToken(form, params.tokenEndpoint, {
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/** Memory id and tier-count checks around a planned cluster operation. */
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, lstatSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { ALL_TIERS, normalizeTier, tallyByDurability } from "./lib/memory-integrity.js";
|
|
6
|
+
export const CHECKPOINT_VERSION = 1;
|
|
7
|
+
/** Written 0600 (flair#2218): ids + tier counts are operator-held, not world-readable. */
|
|
8
|
+
export const CHECKPOINT_MODE = 0o600;
|
|
9
|
+
export const CHECKPOINT_FILENAME = "memory-id-checkpoint.json";
|
|
10
|
+
/** Rows requested per operations-API page. */
|
|
11
|
+
export const MEMORY_PAGE_SIZE = 10_000;
|
|
12
|
+
/** A full final page at this cap is refused. */
|
|
13
|
+
export const MAX_MEMORY_PAGES = 100;
|
|
14
|
+
/** Per-request timeout for the admin read. Every operation is bounded. */
|
|
15
|
+
export const OPS_READ_TIMEOUT_MS = 30_000;
|
|
16
|
+
/** How many missing ids the failure report names. */
|
|
17
|
+
export const MISSING_SAMPLE_LIMIT = 10;
|
|
18
|
+
/** A read inconsistent with the exact count of the same range: a duplicate id or a size that differs. */
|
|
19
|
+
export class InconsistentReadError extends Error {
|
|
20
|
+
}
|
|
21
|
+
/** The default checkpoint file is under ~/.flair/. */
|
|
22
|
+
export function checkpointPath(home) {
|
|
23
|
+
return join(home, ".flair", CHECKPOINT_FILENAME);
|
|
24
|
+
}
|
|
25
|
+
/** Build a Basic-auth operations caller; omit response bodies from errors. */
|
|
26
|
+
export function buildOpsPost(target, user, password, timeoutMs = OPS_READ_TIMEOUT_MS) {
|
|
27
|
+
const base = `${target.replace(/\/+$/, "")}/`;
|
|
28
|
+
const headers = { "Content-Type": "application/json" };
|
|
29
|
+
if (user && password) {
|
|
30
|
+
headers.Authorization = `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`;
|
|
31
|
+
}
|
|
32
|
+
return async (body) => {
|
|
33
|
+
const res = await fetch(base, {
|
|
34
|
+
method: "POST",
|
|
35
|
+
headers,
|
|
36
|
+
body: JSON.stringify(body),
|
|
37
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
38
|
+
});
|
|
39
|
+
if (!res.ok)
|
|
40
|
+
throw new Error(`operations API read returned HTTP ${res.status}`);
|
|
41
|
+
return (await res.json());
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function asRows(body) {
|
|
45
|
+
if (Array.isArray(body))
|
|
46
|
+
return body;
|
|
47
|
+
const results = body?.results;
|
|
48
|
+
return Array.isArray(results) ? results : null;
|
|
49
|
+
}
|
|
50
|
+
function asTime(value) {
|
|
51
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Walk `flair.<table>` by primary key: `SELECT <select> ... [WHERE <filter> AND] id > cursor
|
|
55
|
+
* ORDER BY id LIMIT <pageSize>`, resuming strictly after the last id read. A duplicate id
|
|
56
|
+
* across pages, a full final page at the page cap, or a read that differs in size from
|
|
57
|
+
* `expected` refuses. Duplicates raise InconsistentReadError; size mismatches do too by
|
|
58
|
+
* default, but `mismatch` can return any Error. Errors from `opsPost` propagate unchanged.
|
|
59
|
+
*/
|
|
60
|
+
export async function readTableByIdPaged(opsPost, opts) {
|
|
61
|
+
const pageSize = opts.pageSize ?? MEMORY_PAGE_SIZE;
|
|
62
|
+
const maxPages = opts.maxPages ?? MAX_MEMORY_PAGES;
|
|
63
|
+
if (!Number.isSafeInteger(pageSize) || pageSize < 1 || !Number.isSafeInteger(maxPages) || maxPages < 1) {
|
|
64
|
+
throw new Error("invalid keyset paging bounds");
|
|
65
|
+
}
|
|
66
|
+
const mismatch = opts.mismatch ?? ((expected, read) => new InconsistentReadError(`${opts.table}: server reports ${expected} rows, integrity read ${read}`));
|
|
67
|
+
const rows = [];
|
|
68
|
+
let lastId;
|
|
69
|
+
const seen = new Set();
|
|
70
|
+
for (let page = 0; page < maxPages; page++) {
|
|
71
|
+
if (lastId?.includes("\\"))
|
|
72
|
+
throw new Error(`${opts.table} cursor contains an unsupported backslash`);
|
|
73
|
+
const where = [];
|
|
74
|
+
if (opts.filter)
|
|
75
|
+
where.push(`(${opts.filter})`);
|
|
76
|
+
if (lastId !== undefined)
|
|
77
|
+
where.push(`id > '${lastId.replace(/'/g, "''")}'`);
|
|
78
|
+
const clause = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
|
|
79
|
+
const body = await opsPost({
|
|
80
|
+
operation: "sql",
|
|
81
|
+
sql: `SELECT ${opts.select} FROM flair.${opts.table}${clause} ORDER BY id LIMIT ${pageSize}`,
|
|
82
|
+
});
|
|
83
|
+
const batch = asRows(body);
|
|
84
|
+
if (batch === null)
|
|
85
|
+
throw new Error(`${opts.table} search returned a body that is neither a row array nor { results: [...] }`);
|
|
86
|
+
for (const r of batch) {
|
|
87
|
+
if (!r || typeof r.id !== "string" || r.id.length === 0) {
|
|
88
|
+
throw new Error(`${opts.table} search returned a row without a usable id`);
|
|
89
|
+
}
|
|
90
|
+
if (seen.has(r.id))
|
|
91
|
+
throw new InconsistentReadError(`${opts.table} search returned duplicate id ${r.id} across pages`);
|
|
92
|
+
seen.add(r.id);
|
|
93
|
+
lastId = r.id;
|
|
94
|
+
rows.push(r);
|
|
95
|
+
}
|
|
96
|
+
if (batch.length < pageSize)
|
|
97
|
+
break;
|
|
98
|
+
if (page === maxPages - 1) {
|
|
99
|
+
throw new Error(`${opts.table} read reached the ${maxPages}-page cap`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (rows.length !== opts.expected)
|
|
103
|
+
throw mismatch(opts.expected, rows.length);
|
|
104
|
+
return rows;
|
|
105
|
+
}
|
|
106
|
+
/** Read id and durability (and, when asked, the stored row timestamps) in primary-key order. */
|
|
107
|
+
export async function readMemoryRowsPaged(opsPost, opts = {}) {
|
|
108
|
+
const withWriteTimes = opts.withWriteTimes ?? false;
|
|
109
|
+
const expected = opts.expected ?? await readMemoryRowCount(opsPost);
|
|
110
|
+
const raw = await readTableByIdPaged(opsPost, {
|
|
111
|
+
table: "Memory",
|
|
112
|
+
select: withWriteTimes ? "id, durability, createdAt, updatedAt" : "id, durability",
|
|
113
|
+
expected,
|
|
114
|
+
pageSize: opts.pageSize,
|
|
115
|
+
maxPages: opts.maxPages,
|
|
116
|
+
mismatch: () => new InconsistentReadError("writes during checkpoint"),
|
|
117
|
+
});
|
|
118
|
+
const after = await readMemoryRowCount(opsPost);
|
|
119
|
+
if (after !== expected) {
|
|
120
|
+
throw new InconsistentReadError("writes during checkpoint");
|
|
121
|
+
}
|
|
122
|
+
return raw.map((r) => withWriteTimes
|
|
123
|
+
? { id: r.id, durability: typeof r.durability === "string" ? r.durability : "standard", createdAt: asTime(r.createdAt), updatedAt: asTime(r.updatedAt) }
|
|
124
|
+
: { id: r.id, durability: typeof r.durability === "string" ? r.durability : "standard" });
|
|
125
|
+
}
|
|
126
|
+
/** The instance's own exact Memory row count (describe_table, exact_count). */
|
|
127
|
+
export async function readMemoryRowCount(opsPost) {
|
|
128
|
+
const body = (await opsPost({ operation: "describe_table", database: "flair", table: "Memory", exact_count: true }));
|
|
129
|
+
const n = body?.record_count;
|
|
130
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
131
|
+
throw new Error("Memory row count via the operations API: response carried no record_count");
|
|
132
|
+
}
|
|
133
|
+
return n;
|
|
134
|
+
}
|
|
135
|
+
// ─── Build / compare ────────────────────────────────────────────────────────
|
|
136
|
+
/** Reduce a row set to a checkpoint (sorted ids, tier counts, origin, time). */
|
|
137
|
+
export function buildCheckpoint(input) {
|
|
138
|
+
const node = normalizeOrigin(input.node);
|
|
139
|
+
const host = new URL(node).host;
|
|
140
|
+
const ids = input.rows.map((r) => r.id).slice().sort();
|
|
141
|
+
return {
|
|
142
|
+
version: CHECKPOINT_VERSION,
|
|
143
|
+
node,
|
|
144
|
+
host,
|
|
145
|
+
at: input.at,
|
|
146
|
+
ids,
|
|
147
|
+
byDurability: tallyByDurability(input.rows),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export function normalizeOrigin(value) {
|
|
151
|
+
const url = new URL(value);
|
|
152
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
|
|
153
|
+
throw new Error("node must be an HTTP(S) origin without credentials");
|
|
154
|
+
}
|
|
155
|
+
return url.origin;
|
|
156
|
+
}
|
|
157
|
+
/** Documented exit codes for `flair memory verify --help`. */
|
|
158
|
+
export const VERIFY_EXIT_CODES = {
|
|
159
|
+
verified: 0,
|
|
160
|
+
"integrity-failure": 2,
|
|
161
|
+
unknown: 3,
|
|
162
|
+
};
|
|
163
|
+
/** UNKNOWN — a check that could not be made is never verified. */
|
|
164
|
+
export function unknownVerify(reason) {
|
|
165
|
+
return { outcome: "unknown", reason, totalRows: 0, missing: [], tierDrops: [], detail: `unknown — ${reason}` };
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Compare the live rows against the checkpoint.
|
|
169
|
+
*
|
|
170
|
+
* - a checkpointed id that is gone → integrity failure;
|
|
171
|
+
* - a durability-tier count that dropped → integrity failure;
|
|
172
|
+
* - ids present with no tier-count drop → verified (new ids are fine).
|
|
173
|
+
*/
|
|
174
|
+
export function compareCheckpoint(checkpoint, rows) {
|
|
175
|
+
const present = new Set(rows.map((r) => r.id));
|
|
176
|
+
const missing = checkpoint.ids.filter((id) => !present.has(id)).sort();
|
|
177
|
+
const counts = tallyByDurability(rows);
|
|
178
|
+
const tierDrops = [];
|
|
179
|
+
for (const tier of ALL_TIERS) {
|
|
180
|
+
const dropped = (checkpoint.byDurability[tier] ?? 0) - counts[tier];
|
|
181
|
+
if (dropped > 0)
|
|
182
|
+
tierDrops.push({ tier, dropped });
|
|
183
|
+
}
|
|
184
|
+
if (missing.length > 0 || tierDrops.length > 0) {
|
|
185
|
+
const parts = [];
|
|
186
|
+
if (missing.length > 0) {
|
|
187
|
+
const sample = missing.slice(0, MISSING_SAMPLE_LIMIT);
|
|
188
|
+
parts.push(`${missing.length} of ${checkpoint.ids.length} checkpointed Memory id(s) missing` +
|
|
189
|
+
` (sample: ${sample.join(", ")}${missing.length > sample.length ? ", …" : ""})`);
|
|
190
|
+
}
|
|
191
|
+
for (const d of tierDrops)
|
|
192
|
+
parts.push(`${d.tier} tier dropped by ${d.dropped}`);
|
|
193
|
+
return {
|
|
194
|
+
outcome: "integrity-failure",
|
|
195
|
+
totalRows: rows.length,
|
|
196
|
+
missing,
|
|
197
|
+
tierDrops,
|
|
198
|
+
detail: `INTEGRITY FAILURE — ${parts.join("; ")}`,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
outcome: "verified",
|
|
203
|
+
totalRows: rows.length,
|
|
204
|
+
missing: [],
|
|
205
|
+
tierDrops: [],
|
|
206
|
+
detail: `verified — all ${checkpoint.ids.length} checkpointed Memory id(s) present; no tier-count drop; counts: ${ALL_TIERS.map((t) => `${t} ${counts[t]}`).join(", ")}`,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** Normalise a raw row's durability, exposed for callers that build rows themselves. */
|
|
210
|
+
export { normalizeTier };
|
|
211
|
+
/**
|
|
212
|
+
* Read a checkpoint. A missing file is `absent`; a present-but-unreadable or
|
|
213
|
+
* malformed file is `unreadable` — UNKNOWN, never treated as "no checkpoint".
|
|
214
|
+
*/
|
|
215
|
+
export function readCheckpointFile(path) {
|
|
216
|
+
try {
|
|
217
|
+
lstatSync(path);
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
if (err.code === "ENOENT")
|
|
221
|
+
return { kind: "absent" };
|
|
222
|
+
return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
|
|
223
|
+
}
|
|
224
|
+
let raw;
|
|
225
|
+
try {
|
|
226
|
+
raw = readFileSync(path, "utf-8");
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
const parsed = JSON.parse(raw);
|
|
233
|
+
if (!parsed || parsed.version !== CHECKPOINT_VERSION ||
|
|
234
|
+
typeof parsed.node !== "string" || parsed.node.length === 0 ||
|
|
235
|
+
typeof parsed.host !== "string" || parsed.host.length === 0 ||
|
|
236
|
+
typeof parsed.at !== "string" || parsed.at.length === 0 ||
|
|
237
|
+
!Array.isArray(parsed.ids) || !parsed.ids.every((id) => typeof id === "string" && id.length > 0) ||
|
|
238
|
+
!parsed.byDurability || !ALL_TIERS.every((t) => Number.isSafeInteger(parsed.byDurability[t]) && parsed.byDurability[t] >= 0)) {
|
|
239
|
+
return { kind: "unreadable", reason: "checkpoint is not a version-1 memory id checkpoint" };
|
|
240
|
+
}
|
|
241
|
+
const node = normalizeOrigin(parsed.node);
|
|
242
|
+
if (new URL(node).host !== parsed.host) {
|
|
243
|
+
return { kind: "unreadable", reason: "checkpoint host does not match its origin" };
|
|
244
|
+
}
|
|
245
|
+
// Built from the validated fields only: a key the file adds beyond the
|
|
246
|
+
// version-1 shape is not carried into the checkpoint.
|
|
247
|
+
const byDurability = Object.create(null);
|
|
248
|
+
for (const t of ALL_TIERS)
|
|
249
|
+
byDurability[t] = parsed.byDurability[t];
|
|
250
|
+
const checkpoint = Object.create(null);
|
|
251
|
+
checkpoint.version = CHECKPOINT_VERSION;
|
|
252
|
+
checkpoint.node = node;
|
|
253
|
+
checkpoint.host = parsed.host;
|
|
254
|
+
checkpoint.at = parsed.at;
|
|
255
|
+
checkpoint.ids = [...parsed.ids];
|
|
256
|
+
checkpoint.byDurability = byDurability;
|
|
257
|
+
return { kind: "ok", checkpoint };
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return { kind: "unreadable", reason: "checkpoint is not valid JSON or has an invalid origin" };
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Write the checkpoint atomically: a 0600 temp file beside it, then rename. A
|
|
265
|
+
* failure throws — the caller never claims a checkpoint landed.
|
|
266
|
+
*/
|
|
267
|
+
export function writeCheckpointFile(path, checkpoint) {
|
|
268
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
269
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
270
|
+
try {
|
|
271
|
+
writeFileSync(tmp, `${JSON.stringify(checkpoint)}\n`, { mode: CHECKPOINT_MODE });
|
|
272
|
+
chmodSync(tmp, CHECKPOINT_MODE);
|
|
273
|
+
renameSync(tmp, path);
|
|
274
|
+
}
|
|
275
|
+
catch (err) {
|
|
276
|
+
try {
|
|
277
|
+
rmSync(tmp, { force: true });
|
|
278
|
+
}
|
|
279
|
+
catch { /* best effort */ }
|
|
280
|
+
throw err;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Read the live instance and compare it against the checkpoint. Any read
|
|
285
|
+
* failure (unreachable instance, a page, or a short read) is UNKNOWN.
|
|
286
|
+
*/
|
|
287
|
+
export async function verifyCheckpoint(opts) {
|
|
288
|
+
try {
|
|
289
|
+
const target = normalizeOrigin(opts.opsTarget ?? opts.target);
|
|
290
|
+
const node = normalizeOrigin(opts.checkpoint.node);
|
|
291
|
+
if (target !== node) {
|
|
292
|
+
return unknownVerify(`checkpoint was taken from node ${node} but this target is ${target} — refusing to compare across origins`);
|
|
293
|
+
}
|
|
294
|
+
const opsPost = opts.opsPost ?? buildOpsPost(target, opts.user, opts.password);
|
|
295
|
+
const expected = await readMemoryRowCount(opsPost);
|
|
296
|
+
const rows = await readMemoryRowsPaged(opsPost, { expected, pageSize: opts.pageSize });
|
|
297
|
+
return compareCheckpoint(opts.checkpoint, rows);
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
return unknownVerify(err instanceof Error ? err.message : String(err));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Render the comparison report. */
|
|
304
|
+
export function renderVerifyHuman(result, checkpointPathShown) {
|
|
305
|
+
const lines = [];
|
|
306
|
+
lines.push(`Memory id checkpoint verify: ${result.outcome.toUpperCase()}`);
|
|
307
|
+
lines.push(` checkpoint: ${checkpointPathShown}`);
|
|
308
|
+
if (result.outcome === "unknown") {
|
|
309
|
+
lines.push(` ⚠️ UNKNOWN — ${result.reason ?? "the check could not be made"}; NOT verified`);
|
|
310
|
+
return lines.join("\n");
|
|
311
|
+
}
|
|
312
|
+
lines.push(` rows read now: ${result.totalRows}`);
|
|
313
|
+
if (result.outcome === "integrity-failure") {
|
|
314
|
+
if (result.missing.length > 0) {
|
|
315
|
+
lines.push(` ❌ ${result.missing.length} checkpointed Memory id(s) missing; sample (up to ${MISSING_SAMPLE_LIMIT}):`);
|
|
316
|
+
for (const id of result.missing.slice(0, MISSING_SAMPLE_LIMIT))
|
|
317
|
+
lines.push(` - ${id}`);
|
|
318
|
+
}
|
|
319
|
+
for (const d of result.tierDrops)
|
|
320
|
+
lines.push(` ❌ ${d.tier} tier dropped by ${d.dropped}`);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
lines.push(` ✓ every checkpointed Memory id present; no tier-count drop`);
|
|
324
|
+
}
|
|
325
|
+
return lines.join("\n");
|
|
326
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory-node-compare.ts — `flair memory compare-nodes` (flair#2216, slice 2 of
|
|
3
|
+
* #971).
|
|
4
|
+
*
|
|
5
|
+
* Compares observed Memory id sets of explicitly named physical nodes.
|
|
6
|
+
* Peers come only from `--node`, never Flair's federation peer table.
|
|
7
|
+
*
|
|
8
|
+
* Reads use the checkpoint's keyset paging and exact-count recheck, with the
|
|
9
|
+
* same admin credentials. Count checks cannot detect equal-count concurrent
|
|
10
|
+
* updates or replacements. An id absent on every named node is invisible
|
|
11
|
+
* without a reference set.
|
|
12
|
+
*
|
|
13
|
+
* Classes use stored timestamps: parseable `updatedAt`, else `createdAt`.
|
|
14
|
+
* `createdAt` can be caller-supplied and nodes can use different clocks;
|
|
15
|
+
* timestamp comparisons do not establish actual write order.
|
|
16
|
+
* - `in-sync` — observed ids equal the union of the other usable readings.
|
|
17
|
+
* - `lagging` — missing ids only, each with a timestamp greater than this
|
|
18
|
+
* node's maximum timestamp.
|
|
19
|
+
* - `divergent` — an extra id, or a missing id whose timestamp is at or below
|
|
20
|
+
* this node's maximum timestamp.
|
|
21
|
+
* - `unknown` — failed read, unusable row timestamp, no usable peer, or
|
|
22
|
+
* missing ids with no local timestamp to compare against.
|
|
23
|
+
* A missing id uses the maximum timestamp among usable peers holding it.
|
|
24
|
+
* The overall result is `healthy` only when every node is `in-sync`;
|
|
25
|
+
* any `unknown` makes the overall result `unknown`.
|
|
26
|
+
*/
|
|
27
|
+
import { buildOpsPost, normalizeOrigin, readMemoryRowCount, readMemoryRowsPaged, } from "./memory-id-checkpoint.js";
|
|
28
|
+
/** How many missing/extra ids the report names per node before it just counts. */
|
|
29
|
+
export const NODE_ID_SAMPLE_LIMIT = 10;
|
|
30
|
+
/** Documented exit codes for `flair memory compare-nodes --help`. */
|
|
31
|
+
export const COMPARE_EXIT_CODES = {
|
|
32
|
+
healthy: 0,
|
|
33
|
+
divergent: 2,
|
|
34
|
+
unknown: 3,
|
|
35
|
+
lagging: 4,
|
|
36
|
+
};
|
|
37
|
+
/** Parse a stored timestamp; absent or unparseable values yield null. */
|
|
38
|
+
export function parseWriteTime(value) {
|
|
39
|
+
if (typeof value !== "string" || value.length === 0)
|
|
40
|
+
return null;
|
|
41
|
+
const ms = Date.parse(value);
|
|
42
|
+
return Number.isFinite(ms) ? ms : null;
|
|
43
|
+
}
|
|
44
|
+
/** First parseable timestamp: `updatedAt`, then `createdAt`; null when neither parses. */
|
|
45
|
+
export function rowWriteTime(row) {
|
|
46
|
+
for (const value of [row.updatedAt, row.createdAt]) {
|
|
47
|
+
if (typeof value === "string" && value.length > 0 && Number.isFinite(Date.parse(value)))
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
function sample(ids) {
|
|
53
|
+
const sorted = [...ids].sort();
|
|
54
|
+
return { count: sorted.length, sample: sorted.slice(0, NODE_ID_SAMPLE_LIMIT) };
|
|
55
|
+
}
|
|
56
|
+
function prepare(reading) {
|
|
57
|
+
if (reading.kind === "failed") {
|
|
58
|
+
return { node: reading.node, ok: false, reason: reading.reason, rowCount: "UNAVAILABLE", idSet: new Set(), timeById: new Map(), newestMs: null };
|
|
59
|
+
}
|
|
60
|
+
const idSet = new Set();
|
|
61
|
+
const timeById = new Map();
|
|
62
|
+
let newestMs = null;
|
|
63
|
+
for (const row of reading.rows) {
|
|
64
|
+
idSet.add(row.id);
|
|
65
|
+
const ms = parseWriteTime(row.writeTime);
|
|
66
|
+
if (ms === null) {
|
|
67
|
+
// A row without a usable timestamp makes this reading unknown.
|
|
68
|
+
return { node: reading.node, ok: false, reason: `row ${row.id} has no usable stored timestamp`, rowCount: reading.rows.length, idSet, timeById, newestMs };
|
|
69
|
+
}
|
|
70
|
+
timeById.set(row.id, ms);
|
|
71
|
+
if (newestMs === null || ms > newestMs)
|
|
72
|
+
newestMs = ms;
|
|
73
|
+
}
|
|
74
|
+
return { node: reading.node, ok: true, rowCount: reading.rows.length, idSet, timeById, newestMs };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Classify the readings. Pure and deterministic: the caller supplies each
|
|
78
|
+
* node's rows or a read failure. Fewer than two nodes is a misuse.
|
|
79
|
+
*/
|
|
80
|
+
export function classifyNodeSets(readings) {
|
|
81
|
+
if (readings.length < 2)
|
|
82
|
+
throw new Error("compare-nodes needs at least two nodes to compare");
|
|
83
|
+
const prepared = readings.map(prepare);
|
|
84
|
+
const usable = prepared.filter((p) => p.ok);
|
|
85
|
+
const nodes = prepared.map((p) => {
|
|
86
|
+
if (!p.ok) {
|
|
87
|
+
return {
|
|
88
|
+
node: p.node,
|
|
89
|
+
verdict: "unknown",
|
|
90
|
+
reason: p.reason,
|
|
91
|
+
rowCount: p.rowCount,
|
|
92
|
+
newestWrite: "UNAVAILABLE",
|
|
93
|
+
missing: "UNAVAILABLE",
|
|
94
|
+
extra: "UNAVAILABLE",
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
// Compare only with other usable readings; no usable peer means unavailable differences.
|
|
98
|
+
const peers = usable.filter((q) => q !== p);
|
|
99
|
+
const base = { node: p.node, rowCount: p.rowCount, newestWrite: p.newestMs === null ? null : new Date(p.newestMs).toISOString() };
|
|
100
|
+
if (peers.length === 0) {
|
|
101
|
+
return {
|
|
102
|
+
...base,
|
|
103
|
+
verdict: "unknown",
|
|
104
|
+
reason: "no usable peer to compare against",
|
|
105
|
+
missing: "UNAVAILABLE",
|
|
106
|
+
extra: "UNAVAILABLE",
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const others = new Set();
|
|
110
|
+
for (const q of peers)
|
|
111
|
+
for (const id of q.idSet)
|
|
112
|
+
others.add(id);
|
|
113
|
+
const extra = [...p.idSet].filter((id) => !others.has(id));
|
|
114
|
+
const missing = [...others].filter((id) => !p.idSet.has(id));
|
|
115
|
+
if (extra.length > 0) {
|
|
116
|
+
return { ...base, verdict: "divergent", missing: sample(missing), extra: sample(extra) };
|
|
117
|
+
}
|
|
118
|
+
if (missing.length === 0) {
|
|
119
|
+
return { ...base, verdict: "in-sync", missing: sample([]), extra: sample([]) };
|
|
120
|
+
}
|
|
121
|
+
if (p.newestMs === null) {
|
|
122
|
+
// Missing ids with no local timestamp to compare against yield unknown.
|
|
123
|
+
return {
|
|
124
|
+
...base,
|
|
125
|
+
verdict: "unknown",
|
|
126
|
+
reason: `missing ${missing.length} id(s) but reports no stored timestamp to compare against`,
|
|
127
|
+
missing: sample(missing),
|
|
128
|
+
extra: sample([]),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
// A missing id's maximum peer timestamp at or below the local maximum
|
|
132
|
+
// counts as divergence, including equality.
|
|
133
|
+
const older = missing.filter((id) => {
|
|
134
|
+
let latest = null;
|
|
135
|
+
for (const q of peers) {
|
|
136
|
+
const ms = q.idSet.has(id) ? q.timeById.get(id) ?? null : null;
|
|
137
|
+
if (ms !== null && (latest === null || ms > latest))
|
|
138
|
+
latest = ms;
|
|
139
|
+
}
|
|
140
|
+
return latest !== null && latest <= p.newestMs;
|
|
141
|
+
});
|
|
142
|
+
if (older.length > 0) {
|
|
143
|
+
return { ...base, verdict: "divergent", missing: sample(missing), extra: sample([]) };
|
|
144
|
+
}
|
|
145
|
+
return { ...base, verdict: "lagging", missing: sample(missing), extra: sample([]) };
|
|
146
|
+
});
|
|
147
|
+
const verdict = nodes.some((n) => n.verdict === "unknown")
|
|
148
|
+
? "unknown"
|
|
149
|
+
: nodes.some((n) => n.verdict === "divergent")
|
|
150
|
+
? "divergent"
|
|
151
|
+
: nodes.some((n) => n.verdict === "lagging")
|
|
152
|
+
? "lagging"
|
|
153
|
+
: "healthy";
|
|
154
|
+
const counts = { "in-sync": 0, lagging: 0, divergent: 0, unknown: 0 };
|
|
155
|
+
for (const n of nodes)
|
|
156
|
+
counts[n.verdict]++;
|
|
157
|
+
const detail = verdict === "healthy"
|
|
158
|
+
? `healthy — all ${nodes.length} node(s) have the same observed Memory ids`
|
|
159
|
+
: `${verdict} — ${["in-sync", "lagging", "divergent", "unknown"]
|
|
160
|
+
.filter((c) => counts[c] > 0)
|
|
161
|
+
.map((c) => `${counts[c]} ${c}`)
|
|
162
|
+
.join(", ")}`;
|
|
163
|
+
return { verdict, nodes, detail };
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Read one node's Memory ids and stored timestamps through the admin operations API,
|
|
167
|
+
* using the checkpoint's read (keyset paging + exact-count recheck). A read
|
|
168
|
+
* failure is a `failed` reading, never an empty id set.
|
|
169
|
+
*/
|
|
170
|
+
export async function readNode(opsUrl, opts = {}) {
|
|
171
|
+
let node = opsUrl;
|
|
172
|
+
try {
|
|
173
|
+
node = normalizeOrigin(opsUrl);
|
|
174
|
+
const opsPost = opts.opsPost ?? buildOpsPost(node, opts.user, opts.password);
|
|
175
|
+
const expected = await readMemoryRowCount(opsPost);
|
|
176
|
+
const rows = await readMemoryRowsPaged(opsPost, { expected, pageSize: opts.pageSize, withWriteTimes: true });
|
|
177
|
+
return { kind: "read", node, rows: rows.map((row) => ({ id: row.id, writeTime: rowWriteTime(row) })) };
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
return { kind: "failed", node, reason: err instanceof Error ? err.message : String(err) };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// ─── Report ─────────────────────────────────────────────────────────────────
|
|
184
|
+
export function renderCompareNodesHuman(result) {
|
|
185
|
+
const lines = [];
|
|
186
|
+
lines.push(`Memory node comparison: ${result.verdict.toUpperCase()}`);
|
|
187
|
+
if (result.verdict !== "healthy")
|
|
188
|
+
lines.push(` ⚠️ ${result.detail}`);
|
|
189
|
+
for (const n of result.nodes) {
|
|
190
|
+
lines.push(` ${n.node} ${n.verdict.toUpperCase()} (${n.rowCount} id(s), maximum timestamp ${n.newestWrite ?? "none"})`);
|
|
191
|
+
if (n.verdict === "unknown")
|
|
192
|
+
lines.push(` ⚠️ ${n.reason ?? "the node could not be classified"}; NOT healthy`);
|
|
193
|
+
if (n.missing === "UNAVAILABLE") {
|
|
194
|
+
lines.push(" missing: UNAVAILABLE");
|
|
195
|
+
}
|
|
196
|
+
else if (n.missing.count > 0) {
|
|
197
|
+
lines.push(` missing ${n.missing.count} id(s): ${n.missing.sample.join(", ")}${n.missing.count > n.missing.sample.length ? ", …" : ""}`);
|
|
198
|
+
}
|
|
199
|
+
if (n.extra === "UNAVAILABLE") {
|
|
200
|
+
lines.push(" extra: UNAVAILABLE");
|
|
201
|
+
}
|
|
202
|
+
else if (n.extra.count > 0) {
|
|
203
|
+
lines.push(` holds ${n.extra.count} id(s) absent from the other usable readings: ${n.extra.sample.join(", ")}${n.extra.count > n.extra.sample.length ? ", …" : ""}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return lines.join("\n");
|
|
207
|
+
}
|