@tpsdev-ai/flair 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,256 @@
1
+ /**
2
+ * atomic-write.ts — replace a set of files all together, or not at all
3
+ * (flair#2034 §2).
4
+ *
5
+ * The service re-pointing paths (`flair init`, `flair doctor --fix`) rewrite
6
+ * files an operator's service manager reads: a launchd plist, a systemd unit,
7
+ * the federation-sync shim. A write that truncates the file in place and then
8
+ * fails leaves a half-written unit; a two-file update that fails between the
9
+ * files leaves a pair that disagree. Either is worse than not writing at all.
10
+ *
11
+ * `writeFilesAtomically` stages every new file as a temp file in the target's
12
+ * own directory (same filesystem, so the final rename is atomic), fsyncs each
13
+ * one, and only then renames them over their targets. When a rename fails
14
+ * part-way, every target already replaced is restored from the bytes and mode
15
+ * it had before the call, and the remaining temp files are removed. The caller
16
+ * sees either the complete new set or the complete old set.
17
+ *
18
+ * PLANNED FROM THESE BYTES (flair#2034 §2, round 3). A caller that computed
19
+ * the new content FROM the file's current content passes the snapshot it
20
+ * planned from as `expect` (see snapshotRegularFile). Immediately before the
21
+ * rename, the target is lstat'ed and read again: it must still be a regular
22
+ * file (never a symlink — rename would replace the link itself, not the file
23
+ * it points to), the SAME file (device + inode), and hold exactly the planned
24
+ * bytes. Anything else — an operator's edit saved while flair was planning, a
25
+ * file swapped for a symlink — refuses the write and changes nothing. This is a
26
+ * re-check, not a lock: the window between the re-check and the rename is the
27
+ * one syscall apart, and a second flair writer planning from the same bytes
28
+ * computes the same content.
29
+ *
30
+ * BYTES, NOT DECODED TEXT (round 4). A snapshot is taken only of a file whose
31
+ * bytes survive a UTF-8 decode and re-encode unchanged; any other file is
32
+ * refused before anything is planned from it (two different invalid byte
33
+ * sequences decode to the same U+FFFD, so a rewrite would change bytes flair
34
+ * does not own). The re-check compares the file's BYTES with the encoding of
35
+ * the planned content, which is exact for such a file, and the new content is
36
+ * written as its UTF-8 encoding, so every byte outside the replaced values is
37
+ * the byte that was read.
38
+ *
39
+ * The filesystem primitives are injectable so a test can fail any step (a
40
+ * write, an fsync, the Nth rename) and prove the recovery, without a real
41
+ * failing disk.
42
+ */
43
+ import { closeSync, existsSync, fchmodSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync, } from "node:fs";
44
+ import { randomBytes } from "node:crypto";
45
+ import { basename, dirname, join } from "node:path";
46
+ function resolveHooks(h) {
47
+ return {
48
+ open: h.open ?? ((p, flags, mode) => openSync(p, flags, mode)),
49
+ write: h.write ?? ((fd, data) => {
50
+ const buf = Buffer.from(data, "utf-8");
51
+ let off = 0;
52
+ while (off < buf.length)
53
+ off += writeSync(fd, buf, off, buf.length - off);
54
+ }),
55
+ fchmod: h.fchmod ?? ((fd, mode) => fchmodSync(fd, mode)),
56
+ fsync: h.fsync ?? ((fd) => fsyncSync(fd)),
57
+ close: h.close ?? ((fd) => closeSync(fd)),
58
+ rename: h.rename ?? ((from, to) => renameSync(from, to)),
59
+ unlink: h.unlink ?? ((p) => unlinkSync(p)),
60
+ exists: h.exists ?? ((p) => existsSync(p)),
61
+ read: h.read ?? ((p) => readFileSync(p, "utf-8")),
62
+ readBytes: h.readBytes ?? ((p) => readFileSync(p)),
63
+ modeOf: h.modeOf ?? ((p) => statSync(p).mode & 0o7777),
64
+ lstat: h.lstat ?? ((p) => lstatSync(p)),
65
+ };
66
+ }
67
+ /** Why `st` is not a plain regular file, or null. */
68
+ function notRegular(path, st) {
69
+ if (st.isSymbolicLink())
70
+ return `${path} is a symbolic link`;
71
+ if (!st.isFile())
72
+ return `${path} is not a regular file`;
73
+ return null;
74
+ }
75
+ /**
76
+ * Read `path` for planning: it must be a regular file (lstat — a symlink is
77
+ * refused, never followed), it must be the same file before and after the
78
+ * read, and its bytes must be valid UTF-8 that re-encodes to exactly those
79
+ * bytes. Throws an Error naming the path and what did not hold.
80
+ */
81
+ export function snapshotRegularFile(path, hooks = {}) {
82
+ const lstat = hooks.lstat ?? ((p) => lstatSync(p));
83
+ const readBytes = hooks.readBytes ?? ((p) => readFileSync(p));
84
+ const before = lstat(path);
85
+ const bad = notRegular(path, before);
86
+ if (bad)
87
+ throw new Error(bad);
88
+ const bytes = readBytes(path);
89
+ const content = bytes.toString("utf-8");
90
+ if (!Buffer.from(content, "utf-8").equals(bytes)) {
91
+ throw new Error(`${path} is not valid UTF-8, so flair cannot rewrite it without changing bytes it does not own`);
92
+ }
93
+ const after = lstat(path);
94
+ if (notRegular(path, after) || after.dev !== before.dev || after.ino !== before.ino) {
95
+ throw new Error(`${path} was replaced while it was being read`);
96
+ }
97
+ return { path, content, dev: before.dev, ino: before.ino, mode: before.mode & 0o7777 };
98
+ }
99
+ /** The re-check before a rename: null when `path` is still the planned file with the planned bytes. */
100
+ function plannedFileProblem(fs, path, expect) {
101
+ let st;
102
+ try {
103
+ st = fs.lstat(path);
104
+ }
105
+ catch (err) {
106
+ return `${path} could not be checked again before replacing it (${err?.message ?? err})`;
107
+ }
108
+ const bad = notRegular(path, st);
109
+ if (bad)
110
+ return bad;
111
+ if (st.dev !== expect.dev || st.ino !== expect.ino)
112
+ return `${path} was replaced by another file since flair read it`;
113
+ let now;
114
+ try {
115
+ now = fs.readBytes(path);
116
+ }
117
+ catch (err) {
118
+ return `${path} could not be read again before replacing it (${err?.message ?? err})`;
119
+ }
120
+ if (!now.equals(Buffer.from(expect.content, "utf-8")))
121
+ return `${path} was changed since flair read it`;
122
+ return null;
123
+ }
124
+ function tempPathFor(target) {
125
+ return join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
126
+ }
127
+ /** Write `content` to a NEW temp file next to `target`, fsynced and closed. */
128
+ function stage(fs, target, content, mode) {
129
+ const tmp = tempPathFor(target);
130
+ const fd = fs.open(tmp, "wx", mode);
131
+ try {
132
+ fs.write(fd, content);
133
+ fs.fchmod(fd, mode);
134
+ fs.fsync(fd);
135
+ }
136
+ catch (err) {
137
+ try {
138
+ fs.close(fd);
139
+ }
140
+ catch { /* already failing */ }
141
+ try {
142
+ fs.unlink(tmp);
143
+ }
144
+ catch { /* best effort */ }
145
+ throw err;
146
+ }
147
+ fs.close(fd);
148
+ return tmp;
149
+ }
150
+ /** Best-effort directory fsync so the renames themselves are durable. */
151
+ function fsyncDir(dir) {
152
+ try {
153
+ const fd = openSync(dir, "r");
154
+ try {
155
+ fsyncSync(fd);
156
+ }
157
+ finally {
158
+ closeSync(fd);
159
+ }
160
+ }
161
+ catch {
162
+ /* not every platform allows fsync on a directory; the renames are still atomic */
163
+ }
164
+ }
165
+ /**
166
+ * Replace every file in `entries`, or none of them.
167
+ *
168
+ * Throws when the set could not be written. The error message says whether the
169
+ * originals were restored; in the (double-failure) case where a restore itself
170
+ * failed, it names every path that may now hold new content.
171
+ */
172
+ export function writeFilesAtomically(entries, hooks = {}) {
173
+ const fs = resolveHooks(hooks);
174
+ // 1. Remember what each target held, so a failed commit can put it back.
175
+ // A planned-from target must already be exactly what was planned from.
176
+ for (const e of entries) {
177
+ if (!e.expect)
178
+ continue;
179
+ const problem = plannedFileProblem(fs, e.path, e.expect);
180
+ if (problem)
181
+ throw new Error(`refusing to replace ${e.path}: ${problem}; nothing was changed`);
182
+ }
183
+ const originals = entries.map((e) => {
184
+ if (!fs.exists(e.path))
185
+ return { path: e.path, existed: false };
186
+ // A planned-from target is restored from the bytes it was re-checked to hold.
187
+ const content = e.expect ? e.expect.content : fs.read(e.path);
188
+ return { path: e.path, existed: true, content, mode: fs.modeOf(e.path) };
189
+ });
190
+ // 2. Stage every new file. Nothing visible has changed yet.
191
+ const staged = [];
192
+ try {
193
+ for (const e of entries)
194
+ staged.push(stage(fs, e.path, e.content, e.mode));
195
+ }
196
+ catch (err) {
197
+ for (const tmp of staged) {
198
+ try {
199
+ fs.unlink(tmp);
200
+ }
201
+ catch { /* best effort */ }
202
+ }
203
+ throw new Error(`could not stage the new ${entries.length === 1 ? "file" : "files"} (${err?.message ?? err}); ` +
204
+ `nothing was changed: ${entries.map((e) => e.path).join(", ")}`);
205
+ }
206
+ // 3. Commit: rename each staged file over its target.
207
+ const committed = [];
208
+ for (let i = 0; i < entries.length; i++) {
209
+ try {
210
+ // Re-check the planned-from target immediately before replacing it.
211
+ const expect = entries[i].expect;
212
+ const problem = expect ? plannedFileProblem(fs, entries[i].path, expect) : null;
213
+ if (problem)
214
+ throw new Error(`refusing to replace it: ${problem}`);
215
+ fs.rename(staged[i], entries[i].path);
216
+ committed.push(i);
217
+ }
218
+ catch (err) {
219
+ // Remove the temps not yet committed, then put back what was replaced.
220
+ for (let j = i; j < staged.length; j++) {
221
+ try {
222
+ fs.unlink(staged[j]);
223
+ }
224
+ catch { /* best effort */ }
225
+ }
226
+ const unrestored = [];
227
+ for (const k of committed.reverse()) {
228
+ const o = originals[k];
229
+ try {
230
+ if (o.existed) {
231
+ const tmp = stage(fs, o.path, o.content, o.mode);
232
+ fs.rename(tmp, o.path);
233
+ }
234
+ else {
235
+ fs.unlink(o.path);
236
+ }
237
+ }
238
+ catch {
239
+ unrestored.push(o.path);
240
+ }
241
+ }
242
+ const cause = err?.message ?? String(err);
243
+ if (unrestored.length > 0) {
244
+ throw new Error(`could not replace ${entries[i].path} (${cause}), and restoring the files already replaced failed for: ` +
245
+ `${unrestored.join(", ")} — those now hold the NEW content while the rest hold the old.`);
246
+ }
247
+ if (committed.length === 0) {
248
+ throw new Error(`could not replace ${entries[i].path} (${cause}); nothing was changed`);
249
+ }
250
+ throw new Error(`could not replace ${entries[i].path} (${cause}); every file was restored to its previous content: ` +
251
+ `${entries.map((e) => e.path).join(", ")}`);
252
+ }
253
+ }
254
+ for (const dir of new Set(entries.map((e) => dirname(e.path))))
255
+ fsyncDir(dir);
256
+ }
@@ -36,6 +36,23 @@
36
36
  * reads, `kill(pid, 0)`, the health probe, the start-time readers) live in
37
37
  * `src/cli.ts`, so every branch here is unit-testable without a daemon.
38
38
  */
39
+ /**
40
+ * Map the errno from a failed `kill(pid, 0)` to a `PidLiveness`. Pure so the
41
+ * adapter's errno handling is unit-testable.
42
+ *
43
+ * `gone` is returned ONLY for ESRCH — the one errno that says the pid does not
44
+ * exist. EPERM means it exists but is another user's. EVERY other errno
45
+ * (EINVAL, EACCES, ...) is `unknown`: the liveness was not determined, and
46
+ * unknown must never be read as "gone". A caller with the successful case (no
47
+ * error) passes through `alive` itself.
48
+ */
49
+ export function livenessFromKillError(code) {
50
+ if (code === "ESRCH")
51
+ return { kind: "gone" };
52
+ if (code === "EPERM")
53
+ return { kind: "eperm" };
54
+ return { kind: "unknown", reason: code ?? "the liveness probe failed" };
55
+ }
39
56
  /** Something accepted a TCP connection and spoke HTTP — flair or not. */
40
57
  export function healthIndicatesListener(health) {
41
58
  return health.kind === "ok" || health.kind === "foreign";
@@ -101,6 +118,15 @@ export function classifyDaemonState(ev, ctx) {
101
118
  detail: `the recorded pid ${pid} is alive, but its identity could not be verified (${reason}) — refusing to act on it`,
102
119
  };
103
120
  }
121
+ // Liveness could not be determined (an errno other than ESRCH/EPERM). This is
122
+ // NOT "gone": refusing is the only safe verdict (unknown never licenses an
123
+ // action — neither a stop nor a sidecar removal).
124
+ if (liveness?.kind === "unknown") {
125
+ return {
126
+ state: "UNKNOWN",
127
+ detail: `could not determine whether the recorded pid ${pid} is alive (${liveness.reason}) — refusing to act on it`,
128
+ };
129
+ }
104
130
  return { state: "UNKNOWN", detail: "could not determine whether Flair is running" };
105
131
  }
106
132
  /**
@@ -334,3 +360,38 @@ export function shouldAdoptMissingSidecar(input) {
334
360
  return false;
335
361
  return true;
336
362
  }
363
+ export function classifySidecarStaleness(sidecar, liveness) {
364
+ // Absent / unreadable is not a stale sidecar to drop; callers only ask about
365
+ // a sidecar they could read.
366
+ if (sidecar.kind !== "present")
367
+ return { kind: "live" };
368
+ if (liveness === null)
369
+ return { kind: "unknown" };
370
+ if (liveness.kind === "gone")
371
+ return { kind: "stale" };
372
+ if (liveness.kind === "alive" || liveness.kind === "eperm")
373
+ return { kind: "live" };
374
+ // liveness.kind === "unknown" — not stale.
375
+ return { kind: "unknown" };
376
+ }
377
+ /**
378
+ * The #2055 stop-time gate: remove the sidecar ONLY when the pid it names is
379
+ * CONFIRMED gone AND a fresh O_NOFOLLOW read still names that same pid.
380
+ *
381
+ * `observedPid` is the pid the sidecar named when the stop was observed;
382
+ * `observedPidLiveness` is that pid read AFTER the stop's wait — `gone` (ESRCH)
383
+ * is the confirmation. A process that survived, one owned by another user
384
+ * (EPERM), or one whose liveness could not be read removes nothing.
385
+ *
386
+ * `sidecar` is a fresh O_NOFOLLOW read taken after the stop. A sidecar another
387
+ * supervisor rewrote in between names a DIFFERENT pid and is left alone (the
388
+ * "still names that pid" check). A symlinked or malformed sidecar arrives here
389
+ * as `unreadable` (the read never followed the link) and is likewise not
390
+ * removed — removing on unknown evidence is the defect this gate exists to
391
+ * prevent.
392
+ */
393
+ export function shouldRemoveSidecarAfterStop(input) {
394
+ if (input.observedPidLiveness.kind !== "gone")
395
+ return false;
396
+ return input.sidecar.kind === "present" && input.sidecar.pid === input.observedPid;
397
+ }
@@ -348,6 +348,11 @@ function runLaunchdManagement(ctx) {
348
348
  if (m.state === "not-applicable" || m.state === "no-service") {
349
349
  return result(id, label, "skip", { detail: m.detail, launchd: m });
350
350
  }
351
+ // flair#2040: launchd runs the job but the serving process is unidentified —
352
+ // not an alarm (nothing shows it is detached), and never a pass.
353
+ if (m.state === "unverified") {
354
+ return result(id, label, "warn", { detail: m.detail, remedy: m.remedy?.join(" && "), launchd: m });
355
+ }
351
356
  // flair#1693: a registered plist that carries the admin password INLINE is a
352
357
  // downgrade from the flair#1573 pass-file shape — the secret lives in a
353
358
  // world-readable config file. The running job may be unaffected (launchd
@@ -1,17 +1,19 @@
1
1
  /**
2
- * embed-gpu-doctor.ts — the flair doctor line for an unconfirmed Metal offload
3
- * (flair#1437 PLAN ACCEPTED condition 1; severity split added by flair#1761).
2
+ * embed-gpu-doctor.ts — the flair doctor line for a Metal offload that is
3
+ * either engine-reported CPU or unconfirmed (flair#1437; severity split
4
+ * flair#1761; readback flair#2031).
4
5
  *
5
- * /Health already carries `embedding.fallback` when offload was requested
6
- * and the GPU log heuristic did not confirm Metal. Operators read
7
- * `flair doctor`, not Health. This is the single decision: given the public
8
- * Health embedding field, what (if anything) doctor prints, and whether it
9
- * weighs on doctor's exit code.
6
+ * /Health carries `embedding.fallback` only when the engine itself reports
7
+ * CPU after a GPU request, and `embedding.backend === "unconfirmed"` during
8
+ * warmup or when the engine exposed no GPU type or layer count. The pending
9
+ * marker distinguishes the normal warmup window. Operators read `flair
10
+ * doctor`, not Health. This is the single decision: given the public Health
11
+ * embedding field, what (if anything) doctor prints, and whether it weighs
12
+ * on doctor's exit code.
10
13
  *
11
- * flair#1761: the finding is NOT one severity. The fallback sentence is a log
12
- * heuristic, not an observation (it can err in both directions), and since
13
- * 0.55.0 the derived Metal default requests offload on every darwin-arm64
14
- * host without the operator asking. So the severity is read off `source`:
14
+ * flair#1761: the finding is NOT one severity. Since 0.55.0 the derived Metal
15
+ * default requests offload on every darwin-arm64 host without the operator
16
+ * asking. Severity is read off `source`:
15
17
  *
16
18
  * source === "detected" → the default chose for the operator; advisory
17
19
  * WARNING, does not count as an issue.
@@ -19,32 +21,48 @@
19
21
  * FLAIR_EMBED_GPU_LAYERS; blocking ERROR.
20
22
  * missing / unrecognized → FAIL CLOSED: blocking ERROR, exactly as before.
21
23
  * An unknown state is never softened to advisory.
24
+ *
25
+ * Unconfirmed is not worded as "did not engage; running CPU".
22
26
  */
23
27
  export const EMBED_GPU_DOCTOR_MARKER = "requested GPU offload; Metal did not engage";
24
- /** Advisory wording (flair#1761). We cannot observe engagement, only that it
25
- * was NOT confirmed — the old "did not engage" over-claimed. */
28
+ /** Advisory wording (flair#1761). A derived default stays a warning. */
26
29
  export const EMBED_GPU_DETECTED_MESSAGE = "Automatic Metal acceleration was requested, but engagement could not be verified.";
30
+ /**
31
+ * Blocking wording when the operator asked for offload and the engine
32
+ * exposed no readback (flair#2031). Does not claim the run is on CPU.
33
+ */
34
+ export const EMBED_GPU_UNCONFIRMED_DOCTOR_MESSAGE = "GPU offload was requested, but the embedding engine did not report whether Metal engaged.";
27
35
  /**
28
36
  * Doctor finding, or null when there is nothing to say.
29
- * Only the Health `fallback` sentence is a finding — a stated CPU default
30
- * or a confirmed Metal run is not an issue. The severity depends on
31
- * `source` (flair#1761): an operator-requested offload that was not
32
- * confirmed still fails loud, but the derived Metal default is advisory and
33
- * an unrecognized source fails closed.
37
+ * A stated CPU default or a confirmed Metal run is not an issue. A finding
38
+ * is the engine-reported CPU fallback, or `backend: "unconfirmed"`. The
39
+ * severity depends on `source` (flair#1761): the derived Metal default is
40
+ * advisory and an unrecognized source fails closed.
34
41
  */
35
42
  export function describeEmbedGpuDoctorFinding(embedding) {
36
43
  if (embedding == null || typeof embedding !== "object" || Array.isArray(embedding)) {
37
44
  return null;
38
45
  }
39
- const fallback = embedding.fallback;
40
- if (typeof fallback !== "string" || !fallback.includes(EMBED_GPU_DOCTOR_MARKER)) {
46
+ const record = embedding;
47
+ const fallback = record.fallback;
48
+ const cpuFallback = typeof fallback === "string" && fallback.includes(EMBED_GPU_DOCTOR_MARKER);
49
+ const unconfirmed = record.backend === "unconfirmed";
50
+ if (!cpuFallback && !unconfirmed)
41
51
  return null;
52
+ const source = record.source;
53
+ if (unconfirmed && !cpuFallback && record.pending === true) {
54
+ return {
55
+ isIssue: false,
56
+ icon: "warn",
57
+ message: "GPU offload was requested; embedding engine warmup is still running.",
58
+ fixHint: "Re-run flair doctor after warmup completes.",
59
+ };
42
60
  }
43
- const source = embedding.source;
44
61
  if (source === "detected") {
45
62
  // The Metal default requested offload for the operator; nothing was
46
- // chosen. Working embeddings on CPU is a standing, benign condition —
47
- // keep it visible as a persistent warning, never a blocking finding.
63
+ // chosen. Keep it visible as a persistent warning, never a blocking
64
+ // finding, and do not claim the process is on CPU when readback is
65
+ // missing.
48
66
  return {
49
67
  isIssue: false,
50
68
  icon: "warn",
@@ -53,11 +71,16 @@ export function describeEmbedGpuDoctorFinding(embedding) {
53
71
  };
54
72
  }
55
73
  // A source the operator set ("env"), or one we do not recognize at all
56
- // (missing/unknown) — fail closed and keep the existing fail-loud finding.
74
+ // (missing/unknown) — fail closed. Unconfirmed does not reuse the CPU
75
+ // sentence.
57
76
  return {
58
77
  isIssue: true,
59
78
  icon: "error",
60
- message: fallback,
61
- fixHint: "Pin CPU with FLAIR_EMBED_GPU_LAYERS=0, or restore @node-llama-cpp/mac-arm64-metal and flair restart.",
79
+ message: unconfirmed && !cpuFallback
80
+ ? EMBED_GPU_UNCONFIRMED_DOCTOR_MESSAGE
81
+ : fallback,
82
+ fixHint: unconfirmed && !cpuFallback
83
+ ? "Pin CPU with FLAIR_EMBED_GPU_LAYERS=0, or restart Flair so the embedding engine can report its backend."
84
+ : "Pin CPU with FLAIR_EMBED_GPU_LAYERS=0, or restore @node-llama-cpp/mac-arm64-metal and flair restart.",
62
85
  };
63
86
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The outbound federation projection uses the same declared and named Memory
3
+ * fields as the inbound guard. Pointer inputs are absent from that contract.
4
+ */
5
+ import { MEMORY_ATTRIBUTES, UNDECLARED_ALLOWED } from "./memory-attributes.js";
6
+ export const FEDERATION_MEMORY_ATTRIBUTES = MEMORY_ATTRIBUTES;
7
+ export const FEDERATION_MEMORY_UNDECLARED = UNDECLARED_ALLOWED;
8
+ /** Harper rejects undeclared names in a string projection. Its named object
9
+ * selectors can read these stored fields; the nested wildcard keeps the whole
10
+ * value of `meta` (including arbitrary journal keys), never the whole Memory
11
+ * row. Scalar values such as `kind` are returned directly. See Harper's
12
+ * searchValidator and Table.transformEntryForSelect. */
13
+ export const FEDERATION_MEMORY_SELECT = Object.freeze(FEDERATION_MEMORY_ATTRIBUTES.map((attribute) => FEDERATION_MEMORY_UNDECLARED.includes(attribute)
14
+ ? Object.freeze({ name: attribute, select: Object.freeze(["*"]) })
15
+ : attribute));
@@ -96,8 +96,10 @@ export function detectPersistedAdminUser(dataDir) {
96
96
  export function initAdminPassRefusalMessage(reason, opts = {}) {
97
97
  if (reason === "foreign-instance") {
98
98
  const port = opts.httpPort ?? 19926;
99
- return (`A Harper instance is already answering on port ${port} and this data directory has no persisted admin user. ` +
100
- `Stop that process before initializing a new instance:\n ${INIT_STOP_FOREIGN_COMMAND}`);
99
+ const head = `A Harper instance is already answering on port ${port} and this data directory has no persisted admin user.`;
100
+ if (opts.offerFlairStop === false)
101
+ return head;
102
+ return (`${head} Stop that process before initializing a new instance:\n ${INIT_STOP_FOREIGN_COMMAND}`);
101
103
  }
102
104
  if (reason === "reset-without-socket") {
103
105
  return (`Cannot rotate the admin password: Harper is not running and --skip-start was set, so the operations socket is unreachable. ` +
@@ -0,0 +1,38 @@
1
+ /**
2
+ * ROOTPATH of a process `flair init` did not start (flair#1749).
3
+ *
4
+ * Linux reads `/proc/<pid>/environ` (NUL-separated, so a space in the path
5
+ * stays part of the value). macOS `ps -E` output does not separate arguments
6
+ * from the environment, so it cannot establish ROOTPATH. On macOS, and on
7
+ * any failed read, the directory is unavailable. Init must not refuse
8
+ * before auth from a directory it cannot read, and must not invent one.
9
+ *
10
+ * Daemon sidecar recovery keeps its own reader. This module is init's.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { extractRootPath, parseNullSeparatedEnviron } from "./daemon-liveness.js";
14
+ const UNAVAILABLE = { rootPath: null, environReadable: false };
15
+ /**
16
+ * Platform gate. Anything other than Linux is unavailable and does not call
17
+ * `readLinuxProc` — macOS must not parse `ps -E` and then treat the result
18
+ * as a data directory.
19
+ */
20
+ export function listenerRootPathOnPlatform(platform, readLinuxProc) {
21
+ if (platform !== "linux")
22
+ return UNAVAILABLE;
23
+ return readLinuxProc();
24
+ }
25
+ /** Init-only. Linux `/proc/<pid>/environ`. Unavailable on every other platform. */
26
+ export function readInitListenerRootPath(pid) {
27
+ return listenerRootPathOnPlatform(process.platform, () => {
28
+ if (!Number.isInteger(pid) || pid <= 0)
29
+ return UNAVAILABLE;
30
+ try {
31
+ const raw = readFileSync(`/proc/${pid}/environ`, "utf-8");
32
+ return { rootPath: extractRootPath(parseNullSeparatedEnviron(raw)), environReadable: true };
33
+ }
34
+ catch {
35
+ return UNAVAILABLE;
36
+ }
37
+ });
38
+ }