@tpsdev-ai/flair 0.59.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/SECURITY.md +36 -0
- package/config.yaml +12 -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 +991 -248
- package/dist/commands/agent.js +224 -43
- 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 +592 -146
- 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 +97 -35
- 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 +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -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 +24 -0
- 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 +1168 -326
- 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 +76 -12
- 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 +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- 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 +110 -39
- 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/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 +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- 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 +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- 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 +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- 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/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 +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- 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 +20 -11
- 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 +4 -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 +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- 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 +5 -5
- package/docs/mcp-clients.md +5 -2
- 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 +12 -6
- 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 +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/** The provider whose block the shipped `config.yaml` declares. */
|
|
2
|
+
export const SHIPPED_IDP_PROVIDER = "github";
|
|
3
|
+
/** Suffixes of the three per-provider variables, matching `buildSecretsBundle`
|
|
4
|
+
* (src/lib/mcp-enable.ts) and the shipped `config.yaml`. */
|
|
5
|
+
export const IDP_CLIENT_ID_SUFFIX = "_CLIENT_ID";
|
|
6
|
+
export const IDP_CLIENT_SECRET_SUFFIX = "_CLIENT_SECRET";
|
|
7
|
+
export const IDP_REDIRECT_URI_SUFFIX = "_REDIRECT_URI";
|
|
8
|
+
/** `OAUTH_<PROVIDER>` — the prefix every IdP variable shares. */
|
|
9
|
+
export function idpEnvPrefix(provider = SHIPPED_IDP_PROVIDER) {
|
|
10
|
+
return `OAUTH_${provider.toUpperCase()}`;
|
|
11
|
+
}
|
|
12
|
+
/** The three variable NAMES for a provider. */
|
|
13
|
+
export function idpEnvNames(provider = SHIPPED_IDP_PROVIDER) {
|
|
14
|
+
const prefix = idpEnvPrefix(provider);
|
|
15
|
+
return {
|
|
16
|
+
clientId: `${prefix}${IDP_CLIENT_ID_SUFFIX}`,
|
|
17
|
+
clientSecret: `${prefix}${IDP_CLIENT_SECRET_SUFFIX}`,
|
|
18
|
+
redirectUri: `${prefix}${IDP_REDIRECT_URI_SUFFIX}`,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const PLACEHOLDER_RE = /^\$\{[^}]*\}$/;
|
|
22
|
+
/** Provider configuration checks treat blanks and whole-token `${VAR}` placeholders as missing. */
|
|
23
|
+
export function isUnresolvedEnvValue(value) {
|
|
24
|
+
if (value == null)
|
|
25
|
+
return true;
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
return trimmed === "" || PLACEHOLDER_RE.test(trimmed);
|
|
28
|
+
}
|
|
29
|
+
/** The strict read of `FLAIR_MCP_OAUTH` flair's own `/mcp` route uses
|
|
30
|
+
* (`resources/mcp-oauth-flag.ts`): 1/true/yes/on, case-insensitive. */
|
|
31
|
+
export function mcpOAuthEnabledIn(env) {
|
|
32
|
+
const raw = (env.FLAIR_MCP_OAUTH ?? "").trim().toLowerCase();
|
|
33
|
+
return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
|
|
34
|
+
}
|
|
35
|
+
export function issuerFromEnv(env) {
|
|
36
|
+
const raw = env.FLAIR_MCP_ISSUER;
|
|
37
|
+
return isUnresolvedEnvValue(raw) ? null : raw.trim();
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The locally inferred `FLAIR_MCP_OAUTH` for an instance, decided the way Harper's
|
|
41
|
+
* shipped `loadEnv` settings decide it: the component `.env` beside `config.yaml`
|
|
42
|
+
* (flair#1152 makes the on/off choice live there, not in the packed file),
|
|
43
|
+
* overlaid with the process environment, which wins.
|
|
44
|
+
*
|
|
45
|
+
* `envText` is the `.env` content or null when there is none; `overlay` is the
|
|
46
|
+
* environment to prefer (the operator's `process.env` for `flair doctor`). This
|
|
47
|
+
* decides only report severity. With no readable file, the overlay decides.
|
|
48
|
+
*/
|
|
49
|
+
export function mcpOAuthEnabledFromComponentEnv(envText, overlay = {}) {
|
|
50
|
+
const env = { ...parseMcpComponentEnv(envText ?? "") };
|
|
51
|
+
for (const [key, value] of Object.entries(overlay))
|
|
52
|
+
if (value !== undefined)
|
|
53
|
+
env[key] = value;
|
|
54
|
+
return mcpOAuthEnabledIn(env);
|
|
55
|
+
}
|
|
56
|
+
export function validateRedirectIssuer(issuer) {
|
|
57
|
+
if (isUnresolvedEnvValue(issuer))
|
|
58
|
+
return { redirect: null, reason: "missing-issuer" };
|
|
59
|
+
let url;
|
|
60
|
+
try {
|
|
61
|
+
url = new URL(issuer);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return { redirect: null, reason: "invalid-origin" };
|
|
65
|
+
}
|
|
66
|
+
if (url.username || url.password || /^[a-z]+:\/\/[^/?#]*@/i.test(issuer.trim()))
|
|
67
|
+
return { redirect: null, reason: "origin-has-userinfo" };
|
|
68
|
+
if (issuer.includes("\\"))
|
|
69
|
+
return { redirect: null, reason: "origin-has-path" };
|
|
70
|
+
if (url.search)
|
|
71
|
+
return { redirect: null, reason: "origin-has-query" };
|
|
72
|
+
if (url.hash)
|
|
73
|
+
return { redirect: null, reason: "origin-has-fragment" };
|
|
74
|
+
const suffix = /^[a-z]+:\/\/[^/?#]+(.*)$/i.exec(issuer.trim())?.[1];
|
|
75
|
+
if (suffix !== "" && suffix !== "/")
|
|
76
|
+
return { redirect: null, reason: "origin-has-path" };
|
|
77
|
+
const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(url.hostname);
|
|
78
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
|
|
79
|
+
return { redirect: null, reason: "origin-requires-https" };
|
|
80
|
+
}
|
|
81
|
+
return { redirect: `${url.origin}/oauth` };
|
|
82
|
+
}
|
|
83
|
+
export function redirectUriForIssuer(issuer) {
|
|
84
|
+
return validateRedirectIssuer(issuer).redirect;
|
|
85
|
+
}
|
|
86
|
+
export function readMcpProviderReadiness(env, provider = SHIPPED_IDP_PROVIDER) {
|
|
87
|
+
const names = idpEnvNames(provider);
|
|
88
|
+
return {
|
|
89
|
+
credentialsPresent: !isUnresolvedEnvValue(env[names.clientId]) && !isUnresolvedEnvValue(env[names.clientSecret]),
|
|
90
|
+
redirectPresent: !isUnresolvedEnvValue(env[names.redirectUri]),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export function guardMcpOAuthEnv(env, provider = SHIPPED_IDP_PROVIDER) {
|
|
94
|
+
const names = idpEnvNames(provider);
|
|
95
|
+
if (!isUnresolvedEnvValue(env[names.redirectUri]))
|
|
96
|
+
return { degraded: false, neutralizedVars: [] };
|
|
97
|
+
const credVars = [names.clientId, names.clientSecret];
|
|
98
|
+
const credentialsPresent = credVars.every((k) => !isUnresolvedEnvValue(env[k]));
|
|
99
|
+
if (!credentialsPresent)
|
|
100
|
+
return { degraded: false, neutralizedVars: [] };
|
|
101
|
+
for (const k of credVars)
|
|
102
|
+
delete env[k];
|
|
103
|
+
return {
|
|
104
|
+
degraded: true,
|
|
105
|
+
reason: `${names.redirectUri} is not set, so the ${provider} OAuth provider cannot be configured`,
|
|
106
|
+
neutralizedVars: credVars,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export function describeMcpRedirectFinding(readiness) {
|
|
110
|
+
if (!readiness)
|
|
111
|
+
return { isIssue: false, message: "MCP OAuth redirect: cannot verify target configuration" };
|
|
112
|
+
if (!readiness.credentialsPresent || readiness.redirectPresent)
|
|
113
|
+
return null;
|
|
114
|
+
const names = idpEnvNames();
|
|
115
|
+
return {
|
|
116
|
+
isIssue: true,
|
|
117
|
+
message: `${names.redirectUri} is missing from the target's github OAuth configuration`,
|
|
118
|
+
fixHint: `set ${names.redirectUri} in the instance environment, or re-run: flair mcp enable; then restart`,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export function parseMcpComponentEnv(text) {
|
|
122
|
+
const assignments = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
|
|
123
|
+
const values = {};
|
|
124
|
+
for (const match of text.replace(/\r\n?/g, "\n").matchAll(assignments)) {
|
|
125
|
+
let value = (match[2] ?? "").trim();
|
|
126
|
+
const quote = value[0];
|
|
127
|
+
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
|
|
128
|
+
if (quote === '"')
|
|
129
|
+
value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
|
|
130
|
+
values[match[1]] = value;
|
|
131
|
+
}
|
|
132
|
+
return values;
|
|
133
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { chmodSync, existsSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { SHIPPED_IDP_PROVIDER, idpEnvNames, isUnresolvedEnvValue, issuerFromEnv, mcpOAuthEnabledIn, validateRedirectIssuer, describeMcpRedirectFinding, parseMcpComponentEnv, } from "./mcp-oauth-env-core.js";
|
|
5
|
+
export { SHIPPED_IDP_PROVIDER, IDP_CLIENT_ID_SUFFIX, IDP_CLIENT_SECRET_SUFFIX, IDP_REDIRECT_URI_SUFFIX, idpEnvPrefix, idpEnvNames, isUnresolvedEnvValue, mcpOAuthEnabledIn, issuerFromEnv, mcpOAuthEnabledFromComponentEnv, redirectUriForIssuer, validateRedirectIssuer, readMcpProviderReadiness, guardMcpOAuthEnv, describeMcpRedirectFinding, } from "./mcp-oauth-env-core.js";
|
|
6
|
+
// ─── Component `.env` (the upgrade writer) ───────────────────────────────────
|
|
7
|
+
/** Search only the explicit path, or `./config.yaml` when no path is supplied. */
|
|
8
|
+
export function resolveInstanceConfigPath(explicitPath) {
|
|
9
|
+
const candidates = explicitPath
|
|
10
|
+
? [explicitPath]
|
|
11
|
+
: [join(process.cwd(), "config.yaml")];
|
|
12
|
+
for (const candidate of candidates) {
|
|
13
|
+
if (existsSync(candidate))
|
|
14
|
+
return candidate;
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
/** The `.env` beside a component `config.yaml` — the file Harper's `loadEnv`
|
|
19
|
+
* plugin reads (declared in the shipped config.yaml). Not created here. */
|
|
20
|
+
export function componentEnvPathForConfig(configPath) {
|
|
21
|
+
return join(dirname(configPath), ".env");
|
|
22
|
+
}
|
|
23
|
+
const ASSIGNMENT_RE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=|:\s+)/;
|
|
24
|
+
export function planRedirectMigration(deps = {}, provider = SHIPPED_IDP_PROVIDER) {
|
|
25
|
+
const names = idpEnvNames(provider);
|
|
26
|
+
const configPath = deps.configPath ?? resolveInstanceConfigPath();
|
|
27
|
+
const envPath = configPath ? componentEnvPathForConfig(configPath) : undefined;
|
|
28
|
+
const result = { redirectVar: names.redirectUri, envPath };
|
|
29
|
+
if (!envPath)
|
|
30
|
+
return { ...result, action: "refused", reason: "missing-config" };
|
|
31
|
+
let envText = "";
|
|
32
|
+
let mode = 0o600;
|
|
33
|
+
let existingFile = false;
|
|
34
|
+
try {
|
|
35
|
+
const stat = lstatSync(envPath);
|
|
36
|
+
existingFile = true;
|
|
37
|
+
if (!stat.isFile() || (stat.mode & 0o444) === 0)
|
|
38
|
+
return { ...result, action: "refused", reason: "unreadable-env" };
|
|
39
|
+
mode = stat.mode & 0o7777;
|
|
40
|
+
envText = readFileSync(envPath, "utf-8");
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
if (existingFile || err.code !== "ENOENT")
|
|
44
|
+
return { ...result, action: "refused", reason: "unreadable-env" };
|
|
45
|
+
}
|
|
46
|
+
const tracked = new Set(["FLAIR_MCP_OAUTH", "FLAIR_MCP_ISSUER", ...Object.values(names)]);
|
|
47
|
+
const assignments = new Set();
|
|
48
|
+
const envLines = envText.replace(/\r\n?/g, "\n").split("\n");
|
|
49
|
+
for (const line of envLines) {
|
|
50
|
+
const assignment = ASSIGNMENT_RE.exec(line);
|
|
51
|
+
const key = assignment?.[1];
|
|
52
|
+
if (!key || !tracked.has(key))
|
|
53
|
+
continue;
|
|
54
|
+
if (assignments.has(key))
|
|
55
|
+
return { ...result, action: "refused", reason: `ambiguous-env:${key}` };
|
|
56
|
+
const raw = line.slice(assignment[0].length).trim();
|
|
57
|
+
if ((raw.startsWith("\"") || raw.startsWith("\'") || raw.startsWith("`")) && raw.indexOf(raw[0], 1) < 0) {
|
|
58
|
+
return { ...result, action: "refused", reason: `multiline-env:${key}` };
|
|
59
|
+
}
|
|
60
|
+
assignments.add(key);
|
|
61
|
+
}
|
|
62
|
+
const fileEnv = parseMcpComponentEnv(envText);
|
|
63
|
+
const processEnv = deps.env ?? process.env;
|
|
64
|
+
if (processEnv[names.redirectUri] !== undefined && isUnresolvedEnvValue(processEnv[names.redirectUri])) {
|
|
65
|
+
return { ...result, action: "refused", reason: "redirect-env-masks-file" };
|
|
66
|
+
}
|
|
67
|
+
const env = { ...fileEnv };
|
|
68
|
+
for (const [key, value] of Object.entries(processEnv)) {
|
|
69
|
+
if (value !== undefined)
|
|
70
|
+
env[key] = value;
|
|
71
|
+
}
|
|
72
|
+
if (!isUnresolvedEnvValue(fileEnv[names.redirectUri]) || !isUnresolvedEnvValue(env[names.redirectUri])) {
|
|
73
|
+
return { ...result, action: "already-set" };
|
|
74
|
+
}
|
|
75
|
+
if (!mcpOAuthEnabledIn(env))
|
|
76
|
+
return { ...result, action: "not-enabled" };
|
|
77
|
+
if ([names.clientId, names.clientSecret].some(key => isUnresolvedEnvValue(env[key]))) {
|
|
78
|
+
return { ...result, action: "no-credentials" };
|
|
79
|
+
}
|
|
80
|
+
const issuer = issuerFromEnv(env);
|
|
81
|
+
const validation = validateRedirectIssuer(issuer);
|
|
82
|
+
if (!validation.redirect)
|
|
83
|
+
return { ...result, action: issuer ? "refused" : "no-issuer", reason: validation.reason };
|
|
84
|
+
const lines = envLines.filter(line => ASSIGNMENT_RE.exec(line)?.[1] !== names.redirectUri);
|
|
85
|
+
while (lines.at(-1) === "")
|
|
86
|
+
lines.pop();
|
|
87
|
+
lines.push(`${names.redirectUri}=${validation.redirect}`, "");
|
|
88
|
+
const tempPath = `${envPath}.${randomUUID()}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(tempPath, lines.join("\n"), { mode, flag: "wx" });
|
|
91
|
+
chmodSync(tempPath, mode);
|
|
92
|
+
renameSync(tempPath, envPath);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
rmSync(tempPath, { force: true });
|
|
96
|
+
}
|
|
97
|
+
return { ...result, action: "staged", wrote: true };
|
|
98
|
+
}
|
|
99
|
+
export async function readTargetMcpRedirectFinding(authenticatedRead) {
|
|
100
|
+
let readiness = null;
|
|
101
|
+
try {
|
|
102
|
+
const detail = await authenticatedRead();
|
|
103
|
+
const candidate = detail?.mcpOAuthProvider;
|
|
104
|
+
if (typeof candidate?.credentialsPresent === "boolean" && typeof candidate.redirectPresent === "boolean") {
|
|
105
|
+
readiness = { credentialsPresent: candidate.credentialsPresent, redirectPresent: candidate.redirectPresent };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch { /* target unavailable */ }
|
|
109
|
+
return describeMcpRedirectFinding(readiness);
|
|
110
|
+
}
|
|
111
|
+
/** One operator-facing line for a migration result. Never a value. */
|
|
112
|
+
export function renderRedirectMigration(result) {
|
|
113
|
+
switch (result.action) {
|
|
114
|
+
case "staged":
|
|
115
|
+
return `MCP OAuth: staged ${result.redirectVar} for the ${SHIPPED_IDP_PROVIDER} provider (${result.envPath}).`;
|
|
116
|
+
case "no-issuer":
|
|
117
|
+
return `MCP OAuth: ${result.redirectVar} is missing and FLAIR_MCP_ISSUER is missing — set ${result.redirectVar} in the instance environment, or re-run: flair mcp enable`;
|
|
118
|
+
case "refused":
|
|
119
|
+
return `MCP OAuth redirect migration refused: ${result.reason}. Set ${result.redirectVar} in the instance environment and restart.`;
|
|
120
|
+
case "not-enabled":
|
|
121
|
+
case "already-set":
|
|
122
|
+
case "no-credentials":
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
package/dist/lib/mcp-spec.js
CHANGED
|
@@ -53,6 +53,22 @@ export function resolveFlairCliVersion(startDir) {
|
|
|
53
53
|
return UNKNOWN_VERSION;
|
|
54
54
|
}
|
|
55
55
|
let cachedVersion;
|
|
56
|
+
/**
|
|
57
|
+
* The directory {@link flairCliVersion} walks up from. Normally the module's
|
|
58
|
+
* own directory. A test that simulates an in-process `npm install -g` (which
|
|
59
|
+
* rewrites package.json) points `FLAIR_TEST_VERSION_ROOT` at a TEMP copy
|
|
60
|
+
* instead — rewriting the repository's own package.json changes its mtime,
|
|
61
|
+
* and the dist-freshness gate watches that file (flair#2588).
|
|
62
|
+
*
|
|
63
|
+
* Inert unless the variable is set. TRUSTED-ENV ASSUMPTION: this seam is only
|
|
64
|
+
* as privileged as the environment it is set in. Anyone who can set
|
|
65
|
+
* `FLAIR_TEST_VERSION_ROOT` for a flair process can already set HOME / the
|
|
66
|
+
* `FLAIR_*` variables, so it grants no capability that was not already
|
|
67
|
+
* available to them.
|
|
68
|
+
*/
|
|
69
|
+
function versionResolutionRoot() {
|
|
70
|
+
return process.env.FLAIR_TEST_VERSION_ROOT || import.meta.dirname || __dirname;
|
|
71
|
+
}
|
|
56
72
|
/**
|
|
57
73
|
* This CLI's own version — the single source for `--version`, the CLI↔server
|
|
58
74
|
* handshake, `upgrade --check`, and the MCP pin. Cached: the answer normally
|
|
@@ -66,7 +82,7 @@ let cachedVersion;
|
|
|
66
82
|
*/
|
|
67
83
|
export function flairCliVersion() {
|
|
68
84
|
if (cachedVersion === undefined) {
|
|
69
|
-
cachedVersion = resolveFlairCliVersion(
|
|
85
|
+
cachedVersion = resolveFlairCliVersion(versionResolutionRoot());
|
|
70
86
|
}
|
|
71
87
|
return cachedVersion;
|
|
72
88
|
}
|
|
@@ -14,6 +14,7 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
|
|
|
14
14
|
"visibility",
|
|
15
15
|
"embedding",
|
|
16
16
|
"embeddingModel",
|
|
17
|
+
"embeddedContentHash",
|
|
17
18
|
"tags",
|
|
18
19
|
"durability",
|
|
19
20
|
"source",
|
|
@@ -45,6 +46,7 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
|
|
|
45
46
|
"originatorInstanceId",
|
|
46
47
|
"metadata",
|
|
47
48
|
"entities",
|
|
49
|
+
"skillSubjectId",
|
|
48
50
|
]);
|
|
49
51
|
/** Pre-existing UNDECLARED attributes the codebase deliberately stores on a
|
|
50
52
|
* Memory row and must keep (the guard's job is the POINTER, not these).
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory-id-policy.ts — the Memory record-id rule for the `.content` selector
|
|
3
|
+
* (flair#2199). PURE: string/decoding logic only. Deliberately imports nothing
|
|
4
|
+
* (resources importing this compiled helper require it to be load-free).
|
|
5
|
+
*/
|
|
6
|
+
export const MEMORY_CONTENT_SELECTOR_SUFFIX = ".content";
|
|
7
|
+
/**
|
|
8
|
+
* True when `id` is a Memory record id ending in the `.content` property
|
|
9
|
+
* suffix. Only a string can carry the suffix; a non-string id (Harper allows
|
|
10
|
+
* numeric ids) returns false.
|
|
11
|
+
*/
|
|
12
|
+
export function endsWithContentSelectorSuffix(id) {
|
|
13
|
+
return typeof id === "string" && id.endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* True when an id segment (the raw, still-percent-encoded last path segment of
|
|
17
|
+
* a Memory request) contains an encoded `/`, in any case (`%2F` / `%2f`).
|
|
18
|
+
*/
|
|
19
|
+
export function idSegmentHasEncodedSlash(segment) {
|
|
20
|
+
// Match an encoded slash in the segment as sent, and in its DECODED form — so
|
|
21
|
+
// a `%2f`/`%2F` in any case, and a slash encoded one level deeper
|
|
22
|
+
// (`%252F`, whose decoded form still carries `%2f`), both count. Deciding on
|
|
23
|
+
// the decoded segment is the same decode-then-scan the property-suffix rule
|
|
24
|
+
// uses, so the two agree on how a segment is read.
|
|
25
|
+
return /%2f/i.test(segment) || /%2f/i.test(decodeMemoryIdSegment(segment));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Decode one path segment the way Harper decodes a request path before its
|
|
29
|
+
* property parse (`RequestTarget` decodes the path). Returns the raw segment
|
|
30
|
+
* when it is not valid percent-encoding, so a caller here never throws on it.
|
|
31
|
+
* Such a Memory request whose last segment ends in `.content` is refused by
|
|
32
|
+
* the auth middleware with the named 400 (`memory_id_content_suffix`) before
|
|
33
|
+
* any auth branch; another malformed segment is left to Harper's own path
|
|
34
|
+
* handling.
|
|
35
|
+
*
|
|
36
|
+
* Shared so the resource-layer guard and the auth middleware decode a URL-bound
|
|
37
|
+
* id the SAME way (flair#2199 follow-up).
|
|
38
|
+
*/
|
|
39
|
+
export function decodeMemoryIdSegment(raw) {
|
|
40
|
+
try {
|
|
41
|
+
return decodeURIComponent(raw);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return raw;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory-integrity.ts — the out-of-store integrity watcher's checkpoint and
|
|
3
|
+
* comparison logic (flair#2213, slice 1 of #971; covers #1244's unnoticed-loss
|
|
4
|
+
* risk).
|
|
5
|
+
*
|
|
6
|
+
* The default checkpoint is `~/.flair/integrity-checkpoint.json` (mode 0600,
|
|
7
|
+
* written atomically); `--checkpoint` selects another path, which must stay
|
|
8
|
+
* outside Harper data. It stores per-tier counts and Memory ids (durability
|
|
9
|
+
* and instanceToken). `flair integrity check` compares the corpus to it:
|
|
10
|
+
*
|
|
11
|
+
* - a durable-tier id (permanent / persistent) missing, or with a changed or
|
|
12
|
+
* missing previously nonempty token, without new matching history, is an UNEXPLAINED LOSS.
|
|
13
|
+
* A row returning with its checkpointed token can make the next scan healthy.
|
|
14
|
+
* - a durable-tier id gone WITH a new matching deletion record is history-backed.
|
|
15
|
+
* - a present id with changed durability reports a TIER CHANGE, including replacements.
|
|
16
|
+
* - a durable-tier count decrease beyond the id-set diff is also an alert.
|
|
17
|
+
* - a scan that cannot read the corpus or checkpoint reports UNKNOWN, never
|
|
18
|
+
* healthy, and leaves the checkpoint unchanged.
|
|
19
|
+
*
|
|
20
|
+
* This module compares scans and reads and writes checkpoints.
|
|
21
|
+
*/
|
|
22
|
+
import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { dirname, join } from "node:path";
|
|
24
|
+
import { randomBytes } from "node:crypto";
|
|
25
|
+
export const INTEGRITY_CHECKPOINT_FILENAME = "integrity-checkpoint.json";
|
|
26
|
+
/** The tiers the watcher treats as durable — a loss here is the alert. */
|
|
27
|
+
export const DURABLE_TIERS = ["permanent", "persistent"];
|
|
28
|
+
export const ALL_TIERS = ["permanent", "persistent", "standard", "ephemeral"];
|
|
29
|
+
export function isDurableTier(tier) {
|
|
30
|
+
return tier === "permanent" || tier === "persistent";
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Margin (ms) applied to a checkpoint watermark on both sides of the
|
|
34
|
+
* deletion-history read and of retention.
|
|
35
|
+
*
|
|
36
|
+
* A row's `at` is stamped by `recordMemoryDeletion` when the delete records
|
|
37
|
+
* its history, inside the delete's transaction and therefore BEFORE it
|
|
38
|
+
* commits; the watcher only sees it once the commit is visible, up to a
|
|
39
|
+
* transaction later than `at`. The watcher's own clock (its `scannedAt`) is
|
|
40
|
+
* also a different clock from the instance's. The margin must exceed both the
|
|
41
|
+
* longest such delay and the largest clock difference between the two hosts.
|
|
42
|
+
* Five minutes is assumed to be above both for an operator-run scan, and the
|
|
43
|
+
* cost of a too-large margin is only re-reading a few minutes of history.
|
|
44
|
+
*/
|
|
45
|
+
export const DELETION_HISTORY_MARGIN_MS = 5 * 60_000;
|
|
46
|
+
/**
|
|
47
|
+
* The time from which the next scan must read deletion history, or null when
|
|
48
|
+
* the watermark is absent or unparseable (the caller must then read the whole
|
|
49
|
+
* table — never treat an unknown watermark as "nothing new").
|
|
50
|
+
*/
|
|
51
|
+
export function deletionReadSince(checkpoint, marginMs = DELETION_HISTORY_MARGIN_MS) {
|
|
52
|
+
const watermark = checkpoint?.watermark;
|
|
53
|
+
if (typeof watermark !== "string" || watermark.length === 0)
|
|
54
|
+
return null;
|
|
55
|
+
const ms = Date.parse(watermark);
|
|
56
|
+
if (!Number.isFinite(ms))
|
|
57
|
+
return null;
|
|
58
|
+
return new Date(ms - marginMs).toISOString();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The instant before which deletion history may be pruned: the OLDEST named
|
|
62
|
+
* checkpoint watermark, minus the margin. Returns null when there are no
|
|
63
|
+
* watermarks or any of them is absent or unparseable — the caller then prunes
|
|
64
|
+
* nothing and names the reason.
|
|
65
|
+
*
|
|
66
|
+
* A checkpoint's watermark is never later than the `at` of a history row it
|
|
67
|
+
* still needs (see `emptyCheckpoint`), so no row an older checkpoint needs is
|
|
68
|
+
* older than the oldest watermark — which is why the oldest, not the newest,
|
|
69
|
+
* watermark is the bound.
|
|
70
|
+
*/
|
|
71
|
+
export function retentionCutoff(watermarks, marginMs = DELETION_HISTORY_MARGIN_MS) {
|
|
72
|
+
if (watermarks.length === 0)
|
|
73
|
+
return null;
|
|
74
|
+
let oldest = null;
|
|
75
|
+
for (const watermark of watermarks) {
|
|
76
|
+
if (typeof watermark !== "string" || watermark.length === 0)
|
|
77
|
+
return null;
|
|
78
|
+
const ms = Date.parse(watermark);
|
|
79
|
+
if (!Number.isFinite(ms))
|
|
80
|
+
return null;
|
|
81
|
+
if (oldest === null || ms < oldest)
|
|
82
|
+
oldest = ms;
|
|
83
|
+
}
|
|
84
|
+
return new Date(oldest - marginMs).toISOString();
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The history rows retention may prune: rows strictly older than the cutoff,
|
|
88
|
+
* oldest first, at most `cap`. A row whose `at` is missing or unparseable is
|
|
89
|
+
* never selected — an unreadable age is not proof of age.
|
|
90
|
+
*/
|
|
91
|
+
export function historyRowsToPrune(rows, cutoffIso, cap) {
|
|
92
|
+
const cutoff = Date.parse(cutoffIso);
|
|
93
|
+
if (!Number.isFinite(cutoff))
|
|
94
|
+
return [];
|
|
95
|
+
return rows
|
|
96
|
+
.filter((row) => {
|
|
97
|
+
const ms = typeof row.at === "string" ? Date.parse(row.at) : NaN;
|
|
98
|
+
return Number.isFinite(ms) && ms < cutoff;
|
|
99
|
+
})
|
|
100
|
+
.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
|
|
101
|
+
.slice(0, Math.max(0, cap));
|
|
102
|
+
}
|
|
103
|
+
/** Coerce any stored value to a known tier; anything else buckets to `standard`. */
|
|
104
|
+
export function normalizeTier(durability) {
|
|
105
|
+
return typeof durability === "string" && ALL_TIERS.includes(durability)
|
|
106
|
+
? durability
|
|
107
|
+
: "standard";
|
|
108
|
+
}
|
|
109
|
+
/** A fresh per-tier tally of a row set. */
|
|
110
|
+
export function tallyByDurability(rows) {
|
|
111
|
+
const counts = { permanent: 0, persistent: 0, standard: 0, ephemeral: 0 };
|
|
112
|
+
for (const row of rows)
|
|
113
|
+
counts[normalizeTier(row.durability)]++;
|
|
114
|
+
return counts;
|
|
115
|
+
}
|
|
116
|
+
export function emptyCheckpoint(scannedAt, rows, deletions = [], seenHistoryIds = []) {
|
|
117
|
+
const ids = Object.create(null);
|
|
118
|
+
const instanceTokens = Object.create(null);
|
|
119
|
+
for (const row of rows) {
|
|
120
|
+
ids[row.id] = normalizeTier(row.durability);
|
|
121
|
+
instanceTokens[row.id] = typeof row.instanceToken === "string" && row.instanceToken.length > 0 ? row.instanceToken : null;
|
|
122
|
+
}
|
|
123
|
+
const seen = new Set(seenHistoryIds);
|
|
124
|
+
const historyIds = deletions
|
|
125
|
+
.filter(d => seen.has(d.id) && isDurableTier(ids[d.memoryId]) &&
|
|
126
|
+
!!instanceTokens[d.memoryId] && instanceTokens[d.memoryId] === d.memoryInstanceToken)
|
|
127
|
+
.map(d => d.id);
|
|
128
|
+
// The watermark is `scannedAt`, pulled back to the `at` of any retained
|
|
129
|
+
// history row this checkpoint still needs (a durable id whose nonempty token
|
|
130
|
+
// matches and that is not already absorbed). Those rows must be re-read by the
|
|
131
|
+
// next scan, and must survive retention, so the watermark may not pass them.
|
|
132
|
+
const absorbed = new Set(historyIds);
|
|
133
|
+
let watermark = scannedAt;
|
|
134
|
+
for (const d of deletions) {
|
|
135
|
+
if (absorbed.has(d.id) || !isDurableTier(ids[d.memoryId]))
|
|
136
|
+
continue;
|
|
137
|
+
const token = instanceTokens[d.memoryId];
|
|
138
|
+
if (!token || token !== d.memoryInstanceToken)
|
|
139
|
+
continue;
|
|
140
|
+
if (typeof d.at === "string" && d.at.length > 0 && d.at < watermark)
|
|
141
|
+
watermark = d.at;
|
|
142
|
+
}
|
|
143
|
+
return { version: 2, scannedAt, watermark, byDurability: tallyByDurability(rows), ids, instanceTokens, historyIds };
|
|
144
|
+
}
|
|
145
|
+
export function deletionRecordsToPrune(checkpoint, deletions) {
|
|
146
|
+
const seen = new Set(checkpoint.historyIds);
|
|
147
|
+
return deletions.filter(d => seen.has(d.id) || !isDurableTier(checkpoint.ids[d.memoryId]) ||
|
|
148
|
+
!checkpoint.instanceTokens[d.memoryId] || checkpoint.instanceTokens[d.memoryId] !== d.memoryInstanceToken).map(d => d.id);
|
|
149
|
+
}
|
|
150
|
+
/** UNKNOWN; `checkpointWritten` defaults to false. */
|
|
151
|
+
export function unknownVerdict(reason, scannedAt) {
|
|
152
|
+
return {
|
|
153
|
+
status: "unknown",
|
|
154
|
+
reason,
|
|
155
|
+
scannedAt,
|
|
156
|
+
total: 0,
|
|
157
|
+
counts: { permanent: 0, persistent: 0, standard: 0, ephemeral: 0 },
|
|
158
|
+
attributedDeletes: [],
|
|
159
|
+
tierChanges: [],
|
|
160
|
+
losses: [],
|
|
161
|
+
unexplainedDecrease: {},
|
|
162
|
+
checkpointWritten: false,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Compare the live corpus with the checkpoint; filter checkpoint-seen history here.
|
|
167
|
+
*/
|
|
168
|
+
export function compareScan(opts) {
|
|
169
|
+
const { checkpoint, rows, deletions, scannedAt } = opts;
|
|
170
|
+
const current = new Map();
|
|
171
|
+
for (const row of rows)
|
|
172
|
+
current.set(row.id, row);
|
|
173
|
+
const counts = tallyByDurability(rows);
|
|
174
|
+
const deletedTiers = new Map();
|
|
175
|
+
const seenHistory = new Set(checkpoint.historyIds);
|
|
176
|
+
for (const d of deletions) {
|
|
177
|
+
if (seenHistory.has(d.id))
|
|
178
|
+
continue;
|
|
179
|
+
const instanceToken = checkpoint.instanceTokens[d.memoryId];
|
|
180
|
+
if (!instanceToken || d.memoryInstanceToken !== instanceToken)
|
|
181
|
+
continue;
|
|
182
|
+
const prev = deletedTiers.get(d.memoryId);
|
|
183
|
+
if (!prev || d.at > prev.at)
|
|
184
|
+
deletedTiers.set(d.memoryId, d);
|
|
185
|
+
}
|
|
186
|
+
const attributedDeletes = [];
|
|
187
|
+
const tierChanges = [];
|
|
188
|
+
const losses = [];
|
|
189
|
+
for (const [id, cpTier] of Object.entries(checkpoint.ids)) {
|
|
190
|
+
const curRow = current.get(id);
|
|
191
|
+
const curToken = typeof curRow?.instanceToken === "string" && curRow.instanceToken.length > 0 ? curRow.instanceToken : null;
|
|
192
|
+
const cpToken = checkpoint.instanceTokens[id];
|
|
193
|
+
const replaced = curRow !== undefined && !!cpToken && curToken !== cpToken;
|
|
194
|
+
if (curRow === undefined || replaced) {
|
|
195
|
+
const record = deletedTiers.get(id);
|
|
196
|
+
if (record) {
|
|
197
|
+
attributedDeletes.push({ id, tier: cpTier, at: record.at });
|
|
198
|
+
}
|
|
199
|
+
else if (isDurableTier(cpTier)) {
|
|
200
|
+
losses.push({ id, tier: cpTier, ...(replaced ? { reason: "replaced" } : {}) });
|
|
201
|
+
}
|
|
202
|
+
// Non-durable losses without a record are out of the monitored set.
|
|
203
|
+
}
|
|
204
|
+
if (curRow === undefined)
|
|
205
|
+
continue;
|
|
206
|
+
const curTier = normalizeTier(curRow.durability);
|
|
207
|
+
if (curTier !== cpTier)
|
|
208
|
+
tierChanges.push({ id, from: cpTier, to: curTier });
|
|
209
|
+
}
|
|
210
|
+
// Named losses, attributions and tier changes account for the id-set diff.
|
|
211
|
+
const unexplainedDecrease = {};
|
|
212
|
+
for (const tier of DURABLE_TIERS) {
|
|
213
|
+
const attributedOut = attributedDeletes.filter((d) => d.tier === tier && !current.has(d.id)).length;
|
|
214
|
+
const lostOut = losses.filter((l) => l.tier === tier && !current.has(l.id)).length;
|
|
215
|
+
const changedOut = tierChanges.filter((c) => c.from === tier && c.to !== tier).length;
|
|
216
|
+
const changedIn = tierChanges.filter((c) => c.to === tier && c.from !== tier).length;
|
|
217
|
+
const explainedDrop = attributedOut + lostOut + changedOut - changedIn;
|
|
218
|
+
const actualDrop = checkpoint.byDurability[tier] - counts[tier];
|
|
219
|
+
const unexplained = actualDrop - explainedDrop;
|
|
220
|
+
if (unexplained > 0)
|
|
221
|
+
unexplainedDecrease[tier] = unexplained;
|
|
222
|
+
}
|
|
223
|
+
const alerting = losses.length > 0 || Object.keys(unexplainedDecrease).length > 0;
|
|
224
|
+
return {
|
|
225
|
+
status: alerting ? "alert" : "healthy",
|
|
226
|
+
scannedAt,
|
|
227
|
+
total: rows.length,
|
|
228
|
+
counts,
|
|
229
|
+
attributedDeletes,
|
|
230
|
+
tierChanges,
|
|
231
|
+
losses,
|
|
232
|
+
unexplainedDecrease,
|
|
233
|
+
checkpointWritten: false,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/** The default checkpoint path under the operator's flair config dir. */
|
|
237
|
+
export function integrityCheckpointPath(home) {
|
|
238
|
+
return join(home, ".flair", INTEGRITY_CHECKPOINT_FILENAME);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Read the checkpoint. A missing file is `absent` (the first scan establishes
|
|
242
|
+
* the baseline); a present-but-unreadable file is `unreadable` — UNKNOWN, never
|
|
243
|
+
* "no checkpoint". Never a silent default.
|
|
244
|
+
*/
|
|
245
|
+
export function readCheckpoint(path) {
|
|
246
|
+
try {
|
|
247
|
+
lstatSync(path);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
if (err.code === "ENOENT")
|
|
251
|
+
return { kind: "absent" };
|
|
252
|
+
return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
|
|
253
|
+
}
|
|
254
|
+
let raw;
|
|
255
|
+
try {
|
|
256
|
+
raw = readFileSync(path, "utf-8");
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const parsed = JSON.parse(raw);
|
|
263
|
+
if (parsed?.version !== 2 || typeof parsed.scannedAt !== "string" ||
|
|
264
|
+
(parsed.watermark !== undefined && (typeof parsed.watermark !== "string" || parsed.watermark.length === 0)) ||
|
|
265
|
+
typeof parsed.ids !== "object" || parsed.ids === null || Array.isArray(parsed.ids) ||
|
|
266
|
+
!Object.entries(parsed.ids).every(([id, tier]) => id.length > 0 && ALL_TIERS.includes(tier)) ||
|
|
267
|
+
typeof parsed.instanceTokens !== "object" || parsed.instanceTokens === null || Array.isArray(parsed.instanceTokens) ||
|
|
268
|
+
Object.keys(parsed.instanceTokens).length !== Object.keys(parsed.ids).length ||
|
|
269
|
+
!Object.keys(parsed.ids).every(id => Object.hasOwn(parsed.instanceTokens, id) &&
|
|
270
|
+
(parsed.instanceTokens[id] === null || (typeof parsed.instanceTokens[id] === "string" && parsed.instanceTokens[id].length > 0))) ||
|
|
271
|
+
!Array.isArray(parsed.historyIds) || !parsed.historyIds.every(id => typeof id === "string" && id.length > 0) ||
|
|
272
|
+
!parsed.byDurability || !ALL_TIERS.every(tier => Number.isSafeInteger(parsed.byDurability[tier]) && parsed.byDurability[tier] >= 0)) {
|
|
273
|
+
return { kind: "unreadable", reason: "checkpoint is not a version-2 integrity checkpoint" };
|
|
274
|
+
}
|
|
275
|
+
const ids = Object.create(null);
|
|
276
|
+
for (const [id, tier] of Object.entries(parsed.ids))
|
|
277
|
+
ids[id] = tier;
|
|
278
|
+
parsed.ids = ids;
|
|
279
|
+
const instanceTokens = Object.create(null);
|
|
280
|
+
for (const [id, instanceToken] of Object.entries(parsed.instanceTokens))
|
|
281
|
+
instanceTokens[id] = instanceToken;
|
|
282
|
+
parsed.instanceTokens = instanceTokens;
|
|
283
|
+
return { kind: "ok", checkpoint: parsed };
|
|
284
|
+
}
|
|
285
|
+
catch (err) {
|
|
286
|
+
return { kind: "unreadable", reason: `checkpoint is not valid JSON: ${err instanceof Error ? err.message : String(err)}` };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Write the checkpoint atomically: a 0600 temp file beside it, then rename. A
|
|
291
|
+
* failure throws — the caller reports it and never claims a checkpoint landed.
|
|
292
|
+
*/
|
|
293
|
+
export function writeCheckpoint(path, checkpoint) {
|
|
294
|
+
const dir = dirname(path);
|
|
295
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
296
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
297
|
+
try {
|
|
298
|
+
writeFileSync(tmp, `${JSON.stringify(checkpoint)}\n`, { mode: 0o600 });
|
|
299
|
+
chmodSync(tmp, 0o600);
|
|
300
|
+
renameSync(tmp, path);
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
try {
|
|
304
|
+
rmSync(tmp, { force: true });
|
|
305
|
+
}
|
|
306
|
+
catch { /* best effort */ }
|
|
307
|
+
throw err;
|
|
308
|
+
}
|
|
309
|
+
}
|