@tpsdev-ai/flair 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +194 -377
  2. package/dist/cli.js +1355 -281
  3. package/dist/deploy.js +212 -24
  4. package/dist/fabric-upgrade.js +16 -1
  5. package/dist/federation/scheduler.js +500 -0
  6. package/dist/install/clients.js +111 -53
  7. package/dist/lib/mcp-spec.js +128 -0
  8. package/dist/lib/safe-snapshot-extract.js +231 -0
  9. package/dist/lib/scheduler-platform.js +128 -0
  10. package/dist/lib/xml-escape.js +54 -0
  11. package/dist/rem/scheduler.js +35 -87
  12. package/dist/rem/snapshot.js +13 -0
  13. package/dist/replication-convergence.js +505 -0
  14. package/dist/resources/MemoryBootstrap.js +7 -8
  15. package/dist/resources/SemanticSearch.js +17 -45
  16. package/dist/resources/abstention.js +1 -1
  17. package/dist/resources/embeddings-boot.js +10 -12
  18. package/dist/resources/embeddings-provider.js +10 -7
  19. package/dist/resources/health.js +24 -19
  20. package/dist/resources/in-process.js +225 -0
  21. package/dist/resources/mcp-tools.js +23 -17
  22. package/dist/resources/migration-boot.js +80 -10
  23. package/dist/resources/migrations/data-dir.js +205 -0
  24. package/dist/resources/migrations/progress.js +33 -0
  25. package/dist/resources/migrations/runner.js +29 -2
  26. package/dist/resources/migrations/state.js +13 -2
  27. package/dist/resources/models-dir.js +18 -9
  28. package/dist/resources/semantic-retrieval-core.js +5 -4
  29. package/dist/src/lib/scheduler-platform.js +128 -0
  30. package/dist/src/lib/xml-escape.js +54 -0
  31. package/dist/src/rem/scheduler.js +35 -87
  32. package/docs/deploying-on-fabric.md +267 -0
  33. package/docs/deployment.md +5 -0
  34. package/docs/embedding-in-a-harper-app.md +299 -0
  35. package/docs/federation.md +61 -4
  36. package/docs/integrations.md +3 -0
  37. package/docs/mcp-clients.md +16 -7
  38. package/docs/quickstart.md +80 -54
  39. package/docs/releasing.md +72 -38
  40. package/docs/supply-chain-policy.md +36 -0
  41. package/docs/troubleshooting.md +24 -0
  42. package/docs/upgrade.md +98 -3
  43. package/package.json +1 -11
  44. package/templates/bin/flair-federation-sync.sh.tmpl +28 -0
  45. package/templates/launchd/dev.flair.federation.sync.plist.tmpl +47 -0
  46. package/templates/systemd/flair-federation-sync.service.tmpl +21 -0
  47. package/templates/systemd/flair-federation-sync.timer.tmpl +16 -0
  48. package/dist/resources/rerank-provider.js +0 -569
  49. package/docs/rerank-provisioning.md +0 -101
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Platform-scheduler primitives shared by every Flair-managed background job.
3
+ *
4
+ * Two modules install user-session scheduler entries today:
5
+ * - src/rem/scheduler.ts (`flair rem nightly enable`)
6
+ * - src/federation/scheduler.ts (`flair federation sync enable`)
7
+ *
8
+ * They differ in what they schedule and how often; they do NOT differ in how
9
+ * you ask launchd/systemd whether a job is really loaded, how you read the
10
+ * answer, or how you render a template into a unit file. This module exists so
11
+ * there is exactly ONE implementation of those — same reason src/lib/xml-escape.ts
12
+ * exists (#918): the second copy of a subtle rule is where it goes wrong.
13
+ *
14
+ * `interpretActiveResult()` in particular encodes a production lesson
15
+ * (flair#850) that took a real outage to learn. It must not be re-derived.
16
+ */
17
+ import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
18
+ import { resolve, dirname } from "node:path";
19
+ import { platform } from "node:os";
20
+ import { spawnSync } from "node:child_process";
21
+ /**
22
+ * 30s ceiling on launchctl/systemctl invocations so a hung service manager
23
+ * can't block the CLI indefinitely. Sherlock #415 follow-up.
24
+ */
25
+ export const SPAWN_TIMEOUT_MS = 30_000;
26
+ /**
27
+ * Status-check spawns (launchctl print / systemctl is-active) return
28
+ * near-instantly when the service manager is reachable, and fail fast (no
29
+ * hang) when it isn't (e.g. "Failed to connect to bus"). A short ceiling
30
+ * keeps status commands and the Health endpoint responsive even when the
31
+ * query is inconclusive.
32
+ */
33
+ export const STATUS_CHECK_TIMEOUT_MS = 5_000;
34
+ export function detectPlatform(label, override) {
35
+ if (override)
36
+ return override;
37
+ const p = platform();
38
+ if (p === "darwin")
39
+ return "darwin";
40
+ if (p === "linux")
41
+ return "linux";
42
+ throw new Error(`unsupported platform for ${label}: ${p} (only darwin and linux)`);
43
+ }
44
+ export function spawnReport(cmd, timeoutMs = SPAWN_TIMEOUT_MS) {
45
+ const r = spawnSync(cmd[0], cmd.slice(1), {
46
+ encoding: "buffer",
47
+ timeout: timeoutMs,
48
+ });
49
+ return {
50
+ code: r.status,
51
+ stdout: r.stdout?.toString("utf-8") ?? "",
52
+ stderr: r.stderr?.toString("utf-8") ?? "",
53
+ };
54
+ }
55
+ /**
56
+ * Interprets the result of a `launchctl print` / `systemctl --user is-active`
57
+ * probe. Shared by the sync (CLI) and async (server) callers of both
58
+ * schedulers.
59
+ *
60
+ * - true — the service manager confirms the job is loaded/active.
61
+ * - false — confirmed NOT active. This includes the "no session bus" case
62
+ * (flair#850): when `systemctl --user` can't reach a bus, it fails
63
+ * before printing a status word ("Failed to connect to bus: No medium
64
+ * found") — but nothing CAN be running without a bus, so `false` is the
65
+ * honest answer, not "unknown".
66
+ * - null — genuinely inconclusive (the command itself couldn't run at
67
+ * all — e.g. the binary is missing — with no output to interpret).
68
+ */
69
+ export function interpretActiveResult(plat, code, stdout, stderr) {
70
+ const noOutput = !stdout.trim() && !stderr.trim();
71
+ if (plat === "darwin") {
72
+ if (code === 0)
73
+ return true;
74
+ if (code === null && noOutput)
75
+ return null; // spawn itself failed — inconclusive
76
+ return false; // launchctl ran and reported not-loaded
77
+ }
78
+ const out = stdout.trim();
79
+ if (out === "active" || out === "activating")
80
+ return true;
81
+ if (out === "inactive" || out === "failed" || out === "unknown")
82
+ return false;
83
+ if (code === null && noOutput)
84
+ return null; // spawn itself failed — inconclusive
85
+ return false; // covers the no-bus case: empty stdout, nonzero/failed exit
86
+ }
87
+ /**
88
+ * Human remedy text for a failed scheduler-load attempt (flair#850). Covers
89
+ * the one root cause traced so far: a missing systemd user session bus,
90
+ * which blocks `systemctl --user` entirely in ssh-without-lingering,
91
+ * container, and CI contexts. Returns null when the failure doesn't match a
92
+ * known pattern — the caller already prints the raw stderr, so the operator
93
+ * still has something to go on.
94
+ *
95
+ * `enableCommand` is the caller's own enable invocation, named in the remedy
96
+ * so the operator is told to re-run the command they actually ran.
97
+ */
98
+ export function describeLoadFailure(plat, loadResult, enableCommand) {
99
+ const stderr = loadResult.stderr || "";
100
+ if (plat === "linux" && /failed to connect to bus/i.test(stderr)) {
101
+ return ("No systemd user session bus is available in this session (common over ssh without lingering, " +
102
+ "in containers, or under CI). Fix: enable lingering for this user — `loginctl enable-linger <user>` " +
103
+ `— then re-run \`${enableCommand}\`.`);
104
+ }
105
+ return null;
106
+ }
107
+ /** Single-pass `{{KEY}}` substitution, with a per-value escape hook. */
108
+ export function renderTemplateWith(text, subs, escape) {
109
+ return text.replace(/\{\{([A-Z_]+)\}\}/g, (_, key) => {
110
+ const value = subs[key];
111
+ if (value === undefined)
112
+ throw new Error(`unknown template placeholder: ${key}`);
113
+ return escape(String(value));
114
+ });
115
+ }
116
+ export function readTemplate(rootDir, relativePath) {
117
+ const full = resolve(rootDir, relativePath);
118
+ if (!existsSync(full)) {
119
+ throw new Error(`template not found: ${full}`);
120
+ }
121
+ return readFileSync(full, "utf-8");
122
+ }
123
+ export function writeFileWithDir(path, contents, mode = 0o600) {
124
+ const dir = dirname(path);
125
+ if (!existsSync(dir))
126
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
127
+ writeFileSync(path, contents, { mode });
128
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * XML entity escaping for the launchd plists this CLI generates.
3
+ *
4
+ * A launchd plist is XML, so ANY value interpolated into one has to be
5
+ * escaped or the document is malformed — and `launchctl load` rejects a
6
+ * malformed plist outright, so the service silently never registers.
7
+ *
8
+ * Two independent writers generate plists, and both go through here:
9
+ * - buildLaunchdPlist() in src/cli.ts (the Harper service, `flair init`)
10
+ * - renderPlistTemplate() in src/rem/scheduler.ts (`flair rem nightly enable`)
11
+ *
12
+ * This module exists so there is exactly ONE implementation to get right.
13
+ * Anything that interpolates into plist XML imports it rather than
14
+ * hand-rolling a `.replace()` chain at the call site — a local chain is how
15
+ * this class of bug got in (and how it stayed partial: the original one
16
+ * covered three of the five entities).
17
+ */
18
+ /** The five XML predefined entities, in the order they must be replaced. */
19
+ const XML_ESCAPES = [
20
+ // `&` MUST be first: replacing it after `<` would turn the `&` of an
21
+ // already-emitted `&lt;` into `&amp;lt;` and corrupt the value.
22
+ [/&/g, "&amp;"],
23
+ [/</g, "&lt;"],
24
+ [/>/g, "&gt;"],
25
+ [/"/g, "&quot;"],
26
+ [/'/g, "&apos;"],
27
+ ];
28
+ /**
29
+ * Escape the five XML predefined entities for use inside an XML text node.
30
+ *
31
+ * Safe to apply to any string, including one with no special characters.
32
+ * The result round-trips exactly through unescapeXml().
33
+ */
34
+ export function escapeXml(s) {
35
+ let out = s;
36
+ for (const [pattern, replacement] of XML_ESCAPES)
37
+ out = out.replace(pattern, replacement);
38
+ return out;
39
+ }
40
+ /**
41
+ * Inverse of escapeXml(), for reading a value back out of a document we wrote.
42
+ *
43
+ * `&amp;` MUST be decoded LAST, mirroring escapeXml()'s ordering: decoding it
44
+ * first would turn `&amp;lt;` (the escaping of a literal "&lt;") into `<`
45
+ * instead of back into `&lt;`.
46
+ */
47
+ export function unescapeXml(s) {
48
+ return s
49
+ .replace(/&lt;/g, "<")
50
+ .replace(/&gt;/g, ">")
51
+ .replace(/&quot;/g, '"')
52
+ .replace(/&apos;/g, "'")
53
+ .replace(/&amp;/g, "&");
54
+ }
@@ -13,25 +13,25 @@
13
13
  * No daemon code lives here — the scheduler invokes the shim, the shim
14
14
  * invokes `flair rem nightly run-once`, the runner module does the work.
15
15
  */
16
- import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, rmSync } from "node:fs";
16
+ import { existsSync, chmodSync, rmSync } from "node:fs";
17
17
  import { resolve, dirname } from "node:path";
18
- import { homedir, platform } from "node:os";
19
- import { spawn, spawnSync } from "node:child_process";
18
+ import { homedir } from "node:os";
19
+ import { spawn } from "node:child_process";
20
20
  import { fileURLToPath } from "node:url";
21
+ import { escapeXml } from "../lib/xml-escape.js";
22
+ import { detectPlatform as detectPlatformFor, spawnReport, readTemplate as readTemplateFrom, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
23
+ // Re-exported so this module's public surface is unchanged by the extraction
24
+ // into src/lib/scheduler-platform.ts (a second scheduler — `flair federation
25
+ // sync enable` — needs the identical launchctl/systemctl interpretation, and
26
+ // flair#850's lesson must have exactly one implementation).
27
+ export { interpretActiveResult };
21
28
  export const SHIM_PATH_DEFAULT = resolve(homedir(), ".flair", "bin", "flair-rem-nightly");
22
29
  export const LAUNCHD_PLIST_PATH = resolve(homedir(), "Library", "LaunchAgents", "dev.flair.rem.nightly.plist");
23
30
  export const SYSTEMD_USER_DIR = resolve(homedir(), ".config", "systemd", "user");
24
31
  export const SYSTEMD_TIMER_PATH = resolve(SYSTEMD_USER_DIR, "flair-rem-nightly.timer");
25
32
  export const SYSTEMD_SERVICE_PATH = resolve(SYSTEMD_USER_DIR, "flair-rem-nightly.service");
26
33
  function detectPlatform(override) {
27
- if (override)
28
- return override;
29
- const p = platform();
30
- if (p === "darwin")
31
- return "darwin";
32
- if (p === "linux")
33
- return "linux";
34
- throw new Error(`unsupported platform for REM nightly scheduler: ${p} (only darwin and linux)`);
34
+ return detectPlatformFor("REM nightly scheduler", override);
35
35
  }
36
36
  function defaultTemplateRoot() {
37
37
  // Templates live alongside dist/ in the published package and alongside
@@ -50,19 +50,30 @@ function defaultTemplateRoot() {
50
50
  throw new Error(`unable to locate templates directory (looked in: ${candidates.join(", ")})`);
51
51
  }
52
52
  export function renderTemplate(text, subs) {
53
- return text.replace(/\{\{([A-Z_]+)\}\}/g, (_, key) => {
54
- const value = subs[key];
55
- if (value === undefined)
56
- throw new Error(`unknown template placeholder: ${key}`);
57
- return String(value);
58
- });
53
+ return renderTemplateWith(text, { ...subs }, (v) => v);
54
+ }
55
+ /**
56
+ * renderTemplate() for the launchd plist template specifically: substituted
57
+ * values are XML-escaped.
58
+ *
59
+ * A launchd plist is XML, so a substitution carrying `&`, `<`, `>`, `"` or
60
+ * `'` makes it malformed and `launchctl bootstrap` rejects it — the timer
61
+ * silently never registers. FLAIR_URL is the realistic carrier (a URL with
62
+ * more than one query parameter contains `&`), but HOME and SHIM_PATH are
63
+ * arbitrary paths and equally capable of it. HOUR/MINUTE and AGENT_ID are
64
+ * validated upstream in buildSubstitutions(), but they are escaped too
65
+ * rather than exempted — the point of a chokepoint is that no value gets to
66
+ * argue it is special.
67
+ *
68
+ * Deliberately NOT folded into renderTemplate(): the same substitutions are
69
+ * rendered into the systemd unit files and the shell shim, where XML
70
+ * escaping would be corruption rather than a fix.
71
+ */
72
+ export function renderPlistTemplate(text, subs) {
73
+ return renderTemplateWith(text, { ...subs }, escapeXml);
59
74
  }
60
75
  export function readTemplate(rootDir, relativePath) {
61
- const full = resolve(rootDir, relativePath);
62
- if (!existsSync(full)) {
63
- throw new Error(`template not found: ${full}`);
64
- }
65
- return readFileSync(full, "utf-8");
76
+ return readTemplateFrom(rootDir, relativePath);
66
77
  }
67
78
  /**
68
79
  * Validates the hour:minute schedule. Throws on invalid input rather than
@@ -93,32 +104,6 @@ function buildSubstitutions(opts, shimPath, flairBin) {
93
104
  MINUTE_PAD: String(opts.minute).padStart(2, "0"),
94
105
  };
95
106
  }
96
- function writeFileWithDir(path, contents, mode = 0o600) {
97
- const dir = dirname(path);
98
- if (!existsSync(dir))
99
- mkdirSync(dir, { recursive: true, mode: 0o700 });
100
- writeFileSync(path, contents, { mode });
101
- }
102
- // 30s ceiling on launchctl/systemctl invocations so a hung service manager
103
- // can't block the CLI indefinitely. Sherlock #415 follow-up.
104
- const SPAWN_TIMEOUT_MS = 30_000;
105
- // Status-check spawns (launchctl print / systemctl is-active) return
106
- // near-instantly when the service manager is reachable, and fail fast (no
107
- // hang) when it isn't (e.g. "Failed to connect to bus"). A short ceiling
108
- // keeps `flair rem nightly status` and the Health endpoint responsive even
109
- // when the query is inconclusive.
110
- const STATUS_CHECK_TIMEOUT_MS = 5_000;
111
- function spawnReport(cmd, timeoutMs = SPAWN_TIMEOUT_MS) {
112
- const r = spawnSync(cmd[0], cmd.slice(1), {
113
- encoding: "buffer",
114
- timeout: timeoutMs,
115
- });
116
- return {
117
- code: r.status,
118
- stdout: r.stdout?.toString("utf-8") ?? "",
119
- stderr: r.stderr?.toString("utf-8") ?? "",
120
- };
121
- }
122
107
  /**
123
108
  * Command to genuinely query the platform scheduler's active/loaded state
124
109
  * for a given install (as opposed to the shape of `loadCommand`, which
@@ -131,37 +116,6 @@ function activeCheckCommand(plat) {
131
116
  }
132
117
  return ["systemctl", "--user", "is-active", "flair-rem-nightly.timer"];
133
118
  }
134
- /**
135
- * Interprets the result of `activeCheckCommand()`. Shared by the sync
136
- * (CLI) and async (server) callers.
137
- *
138
- * - true — the service manager confirms the job is loaded/active.
139
- * - false — confirmed NOT active. This includes the "no session bus" case
140
- * (flair#850): when `systemctl --user` can't reach a bus, it fails
141
- * before printing a status word ("Failed to connect to bus: No medium
142
- * found") — but nothing CAN be running without a bus, so `false` is the
143
- * honest answer, not "unknown".
144
- * - null — genuinely inconclusive (the command itself couldn't run at
145
- * all — e.g. the binary is missing — with no output to interpret).
146
- */
147
- export function interpretActiveResult(plat, code, stdout, stderr) {
148
- const noOutput = !stdout.trim() && !stderr.trim();
149
- if (plat === "darwin") {
150
- if (code === 0)
151
- return true;
152
- if (code === null && noOutput)
153
- return null; // spawn itself failed — inconclusive
154
- return false; // launchctl ran and reported not-loaded
155
- }
156
- const out = stdout.trim();
157
- if (out === "active" || out === "activating")
158
- return true;
159
- if (out === "inactive" || out === "failed" || out === "unknown")
160
- return false;
161
- if (code === null && noOutput)
162
- return null; // spawn itself failed — inconclusive
163
- return false; // covers the no-bus case: empty stdout, nonzero/failed exit
164
- }
165
119
  /**
166
120
  * Synchronous active-state check for CLI use (`flair rem nightly status`).
167
121
  * Blocking is fine here — this is a one-shot process and the caller wants
@@ -220,13 +174,7 @@ export async function queryActiveStateAsync(plat, timeoutMs = STATUS_CHECK_TIMEO
220
174
  * still has something to go on.
221
175
  */
222
176
  export function describeLoadFailure(plat, loadResult) {
223
- const stderr = loadResult.stderr || "";
224
- if (plat === "linux" && /failed to connect to bus/i.test(stderr)) {
225
- return ("No systemd user session bus is available in this session (common over ssh without lingering, " +
226
- "in containers, or under CI). Fix: enable lingering for this user — `loginctl enable-linger <user>` " +
227
- "— then re-run `flair rem nightly enable`.");
228
- }
229
- return null;
177
+ return describeLoadFailureFor(plat, loadResult, "flair rem nightly enable");
230
178
  }
231
179
  /**
232
180
  * Formats the `flair rem nightly enable` report from an `EnableResult`.
@@ -330,7 +278,7 @@ export function enableScheduler(opts) {
330
278
  // 2. Write the scheduler entry.
331
279
  if (plat === "darwin") {
332
280
  const plistPath = opts.launchdPlistOverride ?? LAUNCHD_PLIST_PATH;
333
- const plistContents = renderTemplate(readTemplate(templateRoot, "launchd/dev.flair.rem.nightly.plist.tmpl"), subs);
281
+ const plistContents = renderPlistTemplate(readTemplate(templateRoot, "launchd/dev.flair.rem.nightly.plist.tmpl"), subs);
334
282
  writeFileWithDir(plistPath, plistContents, 0o600);
335
283
  const loadCommand = ["launchctl", "bootstrap", `gui/${process.getuid?.() ?? ""}`, plistPath];
336
284
  let loadResult;
@@ -134,6 +134,19 @@ export async function extractSnapshot(opts) {
134
134
  throw new Error(`target directory already exists: ${targetDir}`);
135
135
  }
136
136
  mkdirSync(targetDir, { recursive: true, mode: 0o700 });
137
+ // Deliberately NOT preservePaths, and deliberately NOT routed through
138
+ // src/lib/safe-snapshot-extract.ts. The snapshot path comes from the
139
+ // operator, so provenance here is no more controlled than the data-dir
140
+ // restore's — the difference is the flag, not the trust. With node-tar's
141
+ // defaults its own containment applies: it strips a leading "/" from entry
142
+ // paths, drops ".." entries, and refuses to write through a symlink,
143
+ // including one created earlier in the same archive. Verified against the
144
+ // pinned tar (7.5.20) on all four cases — absolute path, ".." traversal,
145
+ // in-archive symlink, pre-existing symlink in the target — each contained,
146
+ // with a benign control entry landing to prove the archives were valid.
147
+ // If `preservePaths` is ever added here, that containment is gone and this
148
+ // call MUST move to extractSnapshotSafely, which is why the data-dir
149
+ // restore needs the wrapper and this does not.
137
150
  await tarExtract({ file: opts.snapshotPath, cwd: targetDir });
138
151
  return { targetDir, entries };
139
152
  }