@tpsdev-ai/flair 0.54.2 → 0.55.1

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 (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
@@ -0,0 +1,316 @@
1
+ /**
2
+ * init-admin-pass.ts — flair#837: the missing-file + persisted-Harper-user
3
+ * case that #827 could not close.
4
+ *
5
+ * #827 made `flair init` reuse `~/.flair/admin-pass` when the file is already
6
+ * present. The remaining footgun is the file MISSING while Harper's data dir
7
+ * already holds an admin user: `HDB_ADMIN_PASSWORD` only seeds a brand-new
8
+ * install, so generating a fresh file there desyncs from the stored hash and
9
+ * the next ops-API call 401s.
10
+ *
11
+ * This module is the single decision + the two exits that can actually be
12
+ * right: re-persist a supplied original credential, or rotate the stored
13
+ * hash through the ops-API domain socket (`alter_user`, no Authorization).
14
+ * Silent regeneration is never a decision here.
15
+ *
16
+ * Security property the rotate path relies on (flair#837 condition 2,
17
+ * #1704): the ops domain socket is a Harper `super_user` channel with no
18
+ * Authorization header (`bypassLocalAuth` is an else-if on "no header
19
+ * present"). That is safe ONLY because of the socket posture — parent dir
20
+ * 0700, socket 0600. The rotate path refuses if the socket is not
21
+ * owner-only. `--reset-admin-pass` is the only path that may rotate; it
22
+ * prints the user, socket, and destination file before doing it.
23
+ *
24
+ * Pure decision helpers are exported for unit tests. The socket POST is a
25
+ * thin `node:http` client against `dataDir/operations-server`.
26
+ */
27
+ import { request as httpRequest } from "node:http";
28
+ import { createConnection } from "node:net";
29
+ import { existsSync, statSync } from "node:fs";
30
+ import { dirname, join } from "node:path";
31
+ /** Copy-pasteable recovery commands. Tests assert these strings verbatim. */
32
+ export const INIT_RESET_ADMIN_PASS_COMMAND = "flair init --reset-admin-pass";
33
+ export const INIT_ADMIN_PASS_FILE_COMMAND = "flair init --admin-pass-file <path>";
34
+ export const INIT_STOP_FOREIGN_COMMAND = "flair stop";
35
+ /** Short doctor remedy — names the two exits as the fix (report-only). */
36
+ export const ADMIN_PASS_DESYNC_REMEDY = `Fix: ${INIT_ADMIN_PASS_FILE_COMMAND} (if you have the original) or ${INIT_RESET_ADMIN_PASS_COMMAND}`;
37
+ /**
38
+ * Decide the admin-password action for `flair init`.
39
+ *
40
+ * One-arg form (`adminPassFileExists`) is the #827 contract and must keep
41
+ * answering `reuse-existing` / `generate-new`. The optional second argument
42
+ * is the #837 persisted-user / foreign-instance / reset context. On a call
43
+ * that omits it, a missing file is still a fresh install.
44
+ */
45
+ export function resolveInitAdminPasswordSource(adminPassFileExists, ctx = {}) {
46
+ const persisted = !!ctx.persistedAdminUser;
47
+ const foreign = !!ctx.foreignInstanceOnPort;
48
+ const explicit = !!ctx.explicitCredential;
49
+ const reset = !!ctx.resetRequested;
50
+ const socketOk = ctx.opsSocketAvailable !== false;
51
+ if (foreign && !adminPassFileExists && !explicit) {
52
+ return "refuse";
53
+ }
54
+ if (adminPassFileExists && !reset) {
55
+ return "reuse-existing";
56
+ }
57
+ if (!adminPassFileExists && !persisted && !reset) {
58
+ return "generate-new";
59
+ }
60
+ if (persisted && explicit && !reset) {
61
+ return "re-persist";
62
+ }
63
+ // Rotate is production credential rotation. The ONLY way in is the
64
+ // explicit `--reset-admin-pass` flag — never a missing-file guess.
65
+ if (reset) {
66
+ return socketOk ? "rotate" : "refuse";
67
+ }
68
+ if (persisted && !adminPassFileExists) {
69
+ return "refuse";
70
+ }
71
+ return adminPassFileExists ? "reuse-existing" : "generate-new";
72
+ }
73
+ /** Why a `refuse` decision was reached — drives the exact recovery command. */
74
+ export function resolveInitAdminPasswordRefuseReason(adminPassFileExists, ctx = {}) {
75
+ if (resolveInitAdminPasswordSource(adminPassFileExists, ctx) !== "refuse")
76
+ return null;
77
+ if (ctx.foreignInstanceOnPort && !adminPassFileExists && !ctx.explicitCredential) {
78
+ return "foreign-instance";
79
+ }
80
+ if (ctx.resetRequested && ctx.opsSocketAvailable === false) {
81
+ return "reset-without-socket";
82
+ }
83
+ return "persisted-missing-file";
84
+ }
85
+ /**
86
+ * Harper's own install-validator signal that a rootPath already has a user
87
+ * record (`system/hdb_user/data.mdb` or the legacy `system/hdb_user.mdb`).
88
+ * Config presence alone is not enough — an interrupted install can write
89
+ * harper-config.yaml before the user hash lands.
90
+ */
91
+ export function detectPersistedAdminUser(dataDir) {
92
+ const dir = dataDir;
93
+ return (existsSync(join(dir, "system", "hdb_user", "data.mdb")) ||
94
+ existsSync(join(dir, "system", "hdb_user.mdb")));
95
+ }
96
+ export function initAdminPassRefusalMessage(reason, opts = {}) {
97
+ if (reason === "foreign-instance") {
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}`);
101
+ }
102
+ if (reason === "reset-without-socket") {
103
+ return (`Cannot rotate the admin password: Harper is not running and --skip-start was set, so the operations socket is unreachable. ` +
104
+ `Start the instance, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
105
+ }
106
+ if (reason === "socket-not-owner-only") {
107
+ const socket = opts.socketPath ?? "<data-dir>/operations-server";
108
+ return (`Refusing to rotate the admin password: the operations socket at ${socket} is not owner-only ` +
109
+ `(required: parent dir 0700 / socket 0600, flair#1704). The socket is a super_user channel ` +
110
+ `with no Authorization header, so a group/world-accessible socket would expose credential rotation. ` +
111
+ `Fix the posture, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
112
+ }
113
+ if (reason === "socket-not-ready") {
114
+ const socket = opts.socketPath ?? "<data-dir>/operations-server";
115
+ return (`Cannot rotate the admin password: the operations socket at ${socket} never became ready ` +
116
+ `to accept a connection. Harper can answer HTTP health before it binds that socket, and a ` +
117
+ `leftover inode that does not accept connections is not ready. Refusing before any alter_user ` +
118
+ `or pass-file write. Wait until the instance has bound the socket, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
119
+ }
120
+ const dataDir = opts.dataDir ?? "<data-dir>";
121
+ const passPath = opts.adminPassPath ?? "~/.flair/admin-pass";
122
+ return (`Harper already has an admin user in ${dataDir}, but ${passPath} is missing. ` +
123
+ `HDB_ADMIN_PASSWORD only seeds a brand-new install and will not rotate the stored hash, ` +
124
+ `so generating a new file would 401 every later ops-API call.\n` +
125
+ `If you have the original password:\n ${INIT_ADMIN_PASS_FILE_COMMAND}\n` +
126
+ `If you do not:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
127
+ }
128
+ /**
129
+ * Doctor / status finding for the disk-visible half of #837: file gone,
130
+ * user record still in the data dir. Live 401 probes (file present but
131
+ * wrong) are a separate authenticated check the caller can layer on.
132
+ */
133
+ export function adminPassDesyncFinding(input) {
134
+ if (input.adminPassFileExists || !input.persistedAdminUser)
135
+ return null;
136
+ return {
137
+ flagged: true,
138
+ message: "admin-pass file missing; Harper still has a persisted admin user",
139
+ remedy: ADMIN_PASS_DESYNC_REMEDY,
140
+ };
141
+ }
142
+ /**
143
+ * `--reset-admin-pass` is production credential rotation. Print this
144
+ * exactly — user, socket, destination file — before any alter_user.
145
+ */
146
+ export function formatAdminPasswordRotatePreflight(opts) {
147
+ return (`About to rotate Harper admin user '${opts.username}' via operations socket ${opts.socketPath} ` +
148
+ `(super_user channel, no Authorization header; safe only because the socket is owner-only: ` +
149
+ `0700 dir / 0600 socket, flair#1704). After alter_user succeeds the new password will be written to ${opts.adminPassPath}.`);
150
+ }
151
+ /** Rotate is reachable only from `--reset-admin-pass`. */
152
+ export function assertExplicitAdminPasswordRotate(resetRequested) {
153
+ if (!resetRequested) {
154
+ throw new Error("Refusing to rotate the admin password: --reset-admin-pass was not given. " +
155
+ "Bare init never rotates a persisted hash.");
156
+ }
157
+ }
158
+ /** Owner-only ops-socket posture (flair#1704): dir 0700, socket 0600. */
159
+ export function isOwnerOnlyOpsSocketPosture(dirMode, socketMode) {
160
+ return (dirMode & 0o777) === 0o700 && (socketMode & 0o777) === 0o600;
161
+ }
162
+ /**
163
+ * Refuse rotation unless the socket and its parent directory are owner-only.
164
+ * The socket is a super_user channel with no Authorization header.
165
+ */
166
+ export function assertOwnerOnlyOpsSocket(socketPath, stat = (p) => statSync(p)) {
167
+ const socket = stat(socketPath);
168
+ const dir = stat(dirname(socketPath));
169
+ if (!isOwnerOnlyOpsSocketPosture(dir.mode, socket.mode)) {
170
+ throw new Error(initAdminPassRefusalMessage("socket-not-owner-only", { socketPath }));
171
+ }
172
+ }
173
+ /**
174
+ * POST an operations payload over the domain socket. Sends NO Authorization
175
+ * header: Harper's socket `bypassLocalAuth` is an else-if on "no header
176
+ * present", so attaching Basic/Bearer opts out of the local-admin channel
177
+ * and 401s (harper `bin/cliOperations.ts`).
178
+ */
179
+ export function callOpsSocket(socketPath, body, timeoutMs = 10_000) {
180
+ const payload = JSON.stringify(body);
181
+ return new Promise((resolve, reject) => {
182
+ const req = httpRequest({
183
+ socketPath,
184
+ path: "/",
185
+ method: "POST",
186
+ headers: {
187
+ "Content-Type": "application/json",
188
+ "Content-Length": Buffer.byteLength(payload),
189
+ },
190
+ timeout: timeoutMs,
191
+ }, (res) => {
192
+ const chunks = [];
193
+ res.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
194
+ res.on("end", () => {
195
+ resolve({
196
+ status: res.statusCode ?? 0,
197
+ body: Buffer.concat(chunks).toString("utf8"),
198
+ });
199
+ });
200
+ });
201
+ req.on("error", reject);
202
+ req.on("timeout", () => {
203
+ req.destroy();
204
+ reject(new Error(`ops socket timed out after ${timeoutMs}ms`));
205
+ });
206
+ req.write(payload);
207
+ req.end();
208
+ });
209
+ }
210
+ /**
211
+ * Gate the rotate path: explicit `--reset-admin-pass` AND owner-only socket.
212
+ * Returns the preflight line the caller MUST print before `alter_user`.
213
+ */
214
+ export function prepareAdminPasswordRotate(opts) {
215
+ assertExplicitAdminPasswordRotate(opts.resetRequested);
216
+ assertOwnerOnlyOpsSocket(opts.socketPath, opts.stat);
217
+ return formatAdminPasswordRotatePreflight({
218
+ username: opts.username,
219
+ socketPath: opts.socketPath,
220
+ adminPassPath: opts.adminPassPath,
221
+ });
222
+ }
223
+ export async function rotateAdminPasswordViaOpsSocket(socketPath, username, password) {
224
+ const result = await callOpsSocket(socketPath, {
225
+ operation: "alter_user",
226
+ username,
227
+ password,
228
+ role: "super_user",
229
+ active: true,
230
+ });
231
+ if (result.status >= 400) {
232
+ throw new Error(`Operations socket alter_user failed (${result.status}): ${result.body || "(empty)"}`);
233
+ }
234
+ }
235
+ /** How long rotate waits for Harper to bind and accept on operations-server. */
236
+ export const OPS_SOCKET_ROTATE_TIMEOUT_MS = 10_000;
237
+ const OPS_SOCKET_ROTATE_POLL_MS = 50;
238
+ const OPS_SOCKET_ROTATE_PROBE_TIMEOUT_MS = 250;
239
+ /**
240
+ * True when something is accepting on `path`. A leftover inode that exists
241
+ * but accepts no connection is dead — not ready. HTTP /Health is not a
242
+ * substitute: Harper can answer HTTP before it bind()s this socket.
243
+ */
244
+ export function probeOpsSocketAccepting(socketPath, timeoutMs = OPS_SOCKET_ROTATE_PROBE_TIMEOUT_MS) {
245
+ return new Promise((resolve) => {
246
+ let settled = false;
247
+ const finish = (ok) => {
248
+ if (settled)
249
+ return;
250
+ settled = true;
251
+ sock.removeAllListeners();
252
+ sock.destroy();
253
+ resolve(ok);
254
+ };
255
+ const sock = createConnection(socketPath);
256
+ sock.setTimeout(timeoutMs);
257
+ sock.once("connect", () => finish(true));
258
+ sock.once("error", () => finish(false));
259
+ sock.once("timeout", () => finish(false));
260
+ });
261
+ }
262
+ /**
263
+ * Bounded wait until the operations socket accepts a connection.
264
+ * A missing path or a stale/dead inode is not-ready; this never unlinks
265
+ * and never falls through to the HTTP ops path.
266
+ */
267
+ export async function waitForOpsSocketReady(socketPath, opts = {}) {
268
+ const timeoutMs = opts.timeoutMs ?? OPS_SOCKET_ROTATE_TIMEOUT_MS;
269
+ const pollMs = opts.pollMs ?? OPS_SOCKET_ROTATE_POLL_MS;
270
+ const isLive = opts.isLive ?? ((p) => probeOpsSocketAccepting(p));
271
+ const now = opts.now ?? Date.now;
272
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
273
+ const deadline = now() + timeoutMs;
274
+ while (now() < deadline) {
275
+ if (await isLive(socketPath))
276
+ return true;
277
+ const remaining = deadline - now();
278
+ if (remaining <= 0)
279
+ break;
280
+ await sleep(Math.min(pollMs, remaining));
281
+ }
282
+ return false;
283
+ }
284
+ /**
285
+ * Rotate entry used by `flair init --reset-admin-pass`.
286
+ *
287
+ * Readiness is the operations socket accepting a connection, not HTTP
288
+ * health. Wait (bounded, real timeout) first. A dead leftover inode is
289
+ * not-ready. If the socket never becomes ready, refuse before any
290
+ * alter_user and before any pass-file write — never fall through to HTTP.
291
+ * On success: owner-only check, preflight, alter_user, then write.
292
+ */
293
+ export async function executeAdminPasswordRotate(opts) {
294
+ assertExplicitAdminPasswordRotate(opts.resetRequested);
295
+ const ready = await waitForOpsSocketReady(opts.socketPath, {
296
+ timeoutMs: opts.timeoutMs,
297
+ pollMs: opts.pollMs,
298
+ isLive: opts.isLive,
299
+ now: opts.now,
300
+ sleep: opts.sleep,
301
+ });
302
+ if (!ready) {
303
+ throw new Error(initAdminPassRefusalMessage("socket-not-ready", { socketPath: opts.socketPath }));
304
+ }
305
+ const preflight = prepareAdminPasswordRotate({
306
+ resetRequested: opts.resetRequested,
307
+ username: opts.username,
308
+ socketPath: opts.socketPath,
309
+ adminPassPath: opts.adminPassPath,
310
+ stat: opts.stat,
311
+ });
312
+ opts.onPreflight?.(preflight);
313
+ const rotate = opts.rotate ?? rotateAdminPasswordViaOpsSocket;
314
+ await rotate(opts.socketPath, opts.username, opts.password);
315
+ opts.writeAdminPassFile(opts.adminPassPath, opts.password + "\n");
316
+ }
@@ -88,6 +88,22 @@ export function readPlistProgramRefs(plistPath, read = (p) => readFileSync(p, "u
88
88
  const wd = raw.match(/<key>WorkingDirectory<\/key>\s*<string>([^<]*)<\/string>/);
89
89
  return { programArguments, workingDirectory: wd ? unescapeXml(wd[1]) : null };
90
90
  }
91
+ /**
92
+ * Does this plist embed the admin password inline?
93
+ *
94
+ * The flair#1573 pass-file shape never contains this key: the launcher reads the
95
+ * password from a 0600 file at start time. A plist with the key
96
+ * `<key>HDB_ADMIN_PASSWORD</key>` is the pre-#1573 inline shape — a secret
97
+ * written into a config file (world-readable), and a downgrade of an adopted
98
+ * instance (flair#1693).
99
+ *
100
+ * Deliberately key-presence only: the pass-file launcher's argv names the file
101
+ * but never the key, so there is no legitimate plist shape this misfires on. It
102
+ * never returns plist contents — only the boolean.
103
+ */
104
+ export function plistCarriesInlineAdminPassword(raw) {
105
+ return /<key>HDB_ADMIN_PASSWORD<\/key>/.test(raw);
106
+ }
91
107
  /**
92
108
  * Does this plist still point at things that exist?
93
109
  *
@@ -37,8 +37,13 @@
37
37
  * - config unreadable -> refuse.
38
38
  * - detached-and-running (ours) -> adopt (clean-stop -> regenerate -> load).
39
39
  * - detached-and-running (foreign) -> refuse (ownership guard).
40
+ * - no satisfiable admin-pass -> refuse (flair#1685; a pass-file plist
41
+ * whose launcher argv names a missing/unsafe file can never start). The
42
+ * plan carries the credential decision (`credential.writeAdminPassFile`)
43
+ * so the executor only writes when the planner says it is proven.
40
44
  */
41
45
  import { resolve } from "node:path";
46
+ import { preserveHttpPortValue, preserveSecurePort } from "./http-bind.js";
42
47
  /**
43
48
  * Classify the plist at `plistPath` against `dataDir`.
44
49
  *
@@ -62,6 +67,27 @@ export function classifyPlist(plistPath, dataDir, deps) {
62
67
  return "unattributable";
63
68
  return resolve(rootPath) === resolve(dataDir) ? "ours" : "foreign";
64
69
  }
70
+ /**
71
+ * Refuse an instance whose recorded bind values a repair cannot serialise,
72
+ * WITHOUT bouncing or writing anything. Returns the refusal detail, or null when
73
+ * the values are repairable.
74
+ *
75
+ * This must run during PLANNING. `buildRepairPlist` (the executor's writer) is
76
+ * the first caller of the preservation helpers and runs AFTER the adopt arm's
77
+ * clean-stop, so a throw there would leave the live instance DOWN with the
78
+ * circular remedy "flair doctor --fix" — the command that just bounced it.
79
+ */
80
+ export function validateRepairBindValues(values) {
81
+ try {
82
+ preserveHttpPortValue(values.httpPort);
83
+ preserveSecurePort(values.httpSecurePort);
84
+ preserveSecurePort(values.opsSecurePort);
85
+ return null;
86
+ }
87
+ catch (err) {
88
+ return err instanceof Error ? err.message : String(err);
89
+ }
90
+ }
65
91
  /**
66
92
  * Decide what `doctor --fix` may do about launchd management.
67
93
  *
@@ -71,7 +97,7 @@ export function classifyPlist(plistPath, dataDir, deps) {
71
97
  * refusal.
72
98
  */
73
99
  export function planLaunchdRepair(input) {
74
- const { observation, disposition, plistPath, directProcessRunning, configReadable } = input;
100
+ const { observation, disposition, plistPath, directProcessRunning, configReadable, adminPass, adminPassPath } = input;
75
101
  if (observation.state === "not-applicable") {
76
102
  return { kind: "no-op", reason: "not-applicable", detail: observation.detail };
77
103
  }
@@ -107,6 +133,24 @@ export function planLaunchdRepair(input) {
107
133
  plistPath,
108
134
  };
109
135
  }
136
+ // Bind values the executor could not serialise (ops-nv9d slice 2). Decided
137
+ // HERE, before any arm that stops the live instance, so an unsupported
138
+ // configuration refuses instead of bouncing first and refusing after.
139
+ if (input.configBindValues) {
140
+ const unsupported = validateRepairBindValues(input.configBindValues);
141
+ if (unsupported) {
142
+ return { kind: "refuse", reason: "unsupported-config", detail: unsupported, plistPath };
143
+ }
144
+ }
145
+ // Credential before plist (flair#1685). The plist this plan authorizes is
146
+ // ALWAYS pass-file mode, so its launcher cannot start unless
147
+ // `adminPassPath` exists and is safe. Never authorize a write the product
148
+ // has not itself made startable: reuse a valid file, materialize a proven
149
+ // env candidate, or refuse.
150
+ const credential = planCredential(adminPass, directProcessRunning, adminPassPath, plistPath);
151
+ if ("kind" in credential) {
152
+ return credential;
153
+ }
110
154
  // Detached-and-running (flair#1573 slice b2): a direct (non-launchd) process
111
155
  // is serving this instance. The plist is ours/absent/corrupt (the foreign and
112
156
  // unattributable cases were refused above), so the direct process is THIS
@@ -119,14 +163,91 @@ export function planLaunchdRepair(input) {
119
163
  detail: "the instance is running but not under launchd (direct-spawned) — adopting it into launchd " +
120
164
  "will clean-stop the live process (SIGTERM, wait for exit), regenerate the plist, and reload it. " +
121
165
  "This bounces the live instance.",
166
+ credential: credential,
122
167
  };
123
168
  }
124
169
  // Repairable: absent, corrupt, or ours, with no direct process in the way.
125
170
  return {
126
171
  kind: "regenerate",
127
172
  detail: "regenerating the launchd plist for this instance",
173
+ credential: credential,
128
174
  };
129
175
  }
176
+ /**
177
+ * Decide whether the pass-file launcher's argv is satisfiable, and how.
178
+ *
179
+ * - an existing valid file -> reuse it (never rewrite; flair#827)
180
+ * - an env candidate + live instance -> write it, after the executor proves
181
+ * it against the instance
182
+ * - an env candidate with no live instance, or nothing at all -> refuse
183
+ *
184
+ * A live instance is required to WRITE because the password is not recoverable
185
+ * from Harper (it stores a hash): the only safe source of the file's bytes is a
186
+ * credential that authenticates against THIS instance right now. Trusting an
187
+ * unverified env value would reintroduce the flair#827 desync this avoids.
188
+ */
189
+ function planCredential(adminPass, directProcessRunning, adminPassPath, plistPath) {
190
+ if (adminPass.kind === "existing-valid") {
191
+ return { writeAdminPassFile: false, source: "existing-file" };
192
+ }
193
+ if (adminPass.kind === "candidate") {
194
+ if (directProcessRunning)
195
+ return { writeAdminPassFile: true, source: "env" };
196
+ return {
197
+ kind: "refuse",
198
+ reason: "missing-credential",
199
+ detail: `refusing to repair the launchd plist at ${plistPath}: a credential is present in the environment, ` +
200
+ `but no running instance is available to prove it against, so ${adminPassPath} cannot be written ` +
201
+ "safely. Start the instance and re-run 'flair doctor --fix', or run 'flair init' to provision " +
202
+ `${adminPassPath}.`,
203
+ plistPath,
204
+ };
205
+ }
206
+ return {
207
+ kind: "refuse",
208
+ reason: "missing-credential",
209
+ detail: `refusing to repair the launchd plist at ${plistPath}: ${adminPass.detail}`,
210
+ plistPath,
211
+ };
212
+ }
213
+ /**
214
+ * Prove the adopted launchd job — not the old direct process — serves the
215
+ * instance (flair#1685). Port health ALONE is the green light that lied in
216
+ * #1684: the direct-spawned init instance answered 9926 the whole time the
217
+ * adopted job was failing to start. The proof is therefore about IDENTITY and
218
+ * CHANGE, not reachability:
219
+ *
220
+ * 1. the pre-adopt process must be dead (otherwise it is still answering);
221
+ * 2. the serving pid must have CHANGED from the pre-adopt pid;
222
+ * 3. the serving pid must be launchd's reported pid for the adopted label
223
+ * (the label's process owns the listener).
224
+ */
225
+ export function verifyAdoptServing(input) {
226
+ const { directPid, managedPid, servingPid, directPidAlive } = input;
227
+ if (directPid !== null && directPidAlive) {
228
+ return {
229
+ detail: `the pre-adopt process ${directPid} is still alive after the bounce, so whatever answers the port ` +
230
+ "may be that process, not the launchd job",
231
+ };
232
+ }
233
+ if (servingPid === null) {
234
+ return {
235
+ detail: "could not identify the process serving this instance after adoption (no hdb.pid and no port listener)",
236
+ };
237
+ }
238
+ if (directPid !== null && servingPid === directPid) {
239
+ return {
240
+ detail: `the serving process is still pid ${servingPid}, the pre-adopt process — adoption did not bounce the live instance`,
241
+ };
242
+ }
243
+ if (managedPid !== null && servingPid !== managedPid) {
244
+ return {
245
+ detail: `the instance is served by pid ${servingPid}, but launchd reports pid ${managedPid} for the adopted ` +
246
+ "job — the launchd job does not own the listener",
247
+ };
248
+ }
249
+ return null;
250
+ }
130
251
  // ─── the executor's pure helpers (slice b2) ───────────────────────────────
131
252
  /**
132
253
  * Map a throw from the executor arm to a named result (flair#1573 slice b2,
@@ -14,8 +14,10 @@
14
14
  * it here automatically — no second list to forget on the next upgrade.
15
15
  */
16
16
  import { existsSync, readFileSync } from "node:fs";
17
+ import { join } from "node:path";
17
18
  import { ALL_CLIENTS, clientConfigPath, } from "../install/clients.js";
18
- import { checkSessionStartHook, extractFlairMcpPin, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
19
+ import { checkSessionStartHook, extractFlairMcpPin, extractFlairPackagePins, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
20
+ import { isUnsafeAdapterPin } from "./stale-client-pin.js";
19
21
  import { hookInstallHint, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
20
22
  import { flairCliVersion, isResolvedVersion } from "./mcp-spec.js";
21
23
  function withHome(homeDir, fn) {
@@ -112,6 +114,57 @@ export function staleSessionStartHookPins(homeDir, expectedVersion = flairCliVer
112
114
  export function staleMcpClientPins(homeDir, expectedVersion = flairCliVersion()) {
113
115
  return staleOwnedPins(homeDir, expectedVersion).filter((r) => r.target.kind === "mcp-client");
114
116
  }
117
+ /**
118
+ * Read the pins that are actually installed in wired hosts' configs
119
+ * (and the cwd package.json) and return those older than 0.18.0.
120
+ */
121
+ export function findUnsafeWiredPins(homeDir, cwd) {
122
+ const found = [];
123
+ const seen = new Set();
124
+ const add = (pin) => {
125
+ const key = `${pin.source}:${pin.id}:${pin.package}@${pin.version}`;
126
+ if (seen.has(key))
127
+ return;
128
+ seen.add(key);
129
+ found.push(pin);
130
+ };
131
+ for (const target of listOwnedPinTargets(homeDir)) {
132
+ const reading = readOwnedPin(target, homeDir);
133
+ if (!reading.present)
134
+ continue;
135
+ const text = readFileText(target.path) ?? "";
136
+ const surface = target.kind === "mcp-client" ? "MCP server" : "SessionStart hook";
137
+ for (const pin of extractFlairPackagePins(text)) {
138
+ if (!isUnsafeAdapterPin(pin.version))
139
+ continue;
140
+ add({
141
+ source: target.kind,
142
+ id: target.id,
143
+ surface,
144
+ package: pin.package,
145
+ version: pin.version,
146
+ });
147
+ }
148
+ }
149
+ if (cwd) {
150
+ const pkgPath = join(cwd, "package.json");
151
+ const text = readFileText(pkgPath);
152
+ if (text) {
153
+ for (const pin of extractFlairPackagePins(text)) {
154
+ if (!isUnsafeAdapterPin(pin.version))
155
+ continue;
156
+ add({
157
+ source: "package.json",
158
+ id: "cwd",
159
+ surface: "package.json",
160
+ package: pin.package,
161
+ version: pin.version,
162
+ });
163
+ }
164
+ }
165
+ }
166
+ return found;
167
+ }
115
168
  /**
116
169
  * What `flair upgrade` prints from a refresh result.
117
170
  *
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Live-process start time in epoch ms.
3
+ *
4
+ * Parsers and the ±2s match live in `daemon-liveness.ts` (pure). This file
5
+ * is the I/O adapter those parsers need: Linux `/proc/<pid>/stat` field 22
6
+ * plus `/proc/uptime`, macOS `ps -o lstart=`. One reader for the production
7
+ * daemon identity check and the harness scratch-owner stamp (flair#1372).
8
+ *
9
+ * Darwin `ps -o lstart=` prints local time without a zone. `Date.parse` of
10
+ * that string uses the JS engine's zone — and `bun test` forces UTC even
11
+ * when the host is not (Kern on #1708: a PDT parent stamp vs a UTC sweep
12
+ * was 7h off). Self-calibrate against this process: parse our own lstart,
13
+ * subtract our true start (`Date.now() - process.uptime()*1000`), and apply
14
+ * that offset to the target. Kern wrote `offset = parse(ownLstart) - Date.now()`;
15
+ * without uptime that offset is process age, not zone skew, and owner
16
+ * stamps would drift. Uptime is what makes the offset the parser's zone
17
+ * error. Linux `/proc` is already zone-independent.
18
+ *
19
+ * A null answer is "unverified" — it never decides a verdict toward a
20
+ * destructive branch.
21
+ */
22
+ import { execFileSync } from "node:child_process";
23
+ import { readFileSync } from "node:fs";
24
+ import { parseProcStatStartTime, parsePsLstart, procStartTimeToEpochMs, } from "./daemon-liveness.js";
25
+ /**
26
+ * Undo a zone-skewed `parsePsLstart` using this process as the reference.
27
+ *
28
+ * `offset = ownParsedMs - ownTrueStartMs`. Subtract that from the target
29
+ * parse so a 7h PDT-vs-UTC bun-test skew (Kern #1708) cancels out.
30
+ */
31
+ export function applyLstartZoneOffset(targetParsedMs, ownParsedMs, ownTrueStartMs) {
32
+ return targetParsedMs - (ownParsedMs - ownTrueStartMs);
33
+ }
34
+ function readPsLstart(pid) {
35
+ try {
36
+ return execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
37
+ encoding: "utf-8",
38
+ env: { ...process.env, LC_ALL: "C" },
39
+ timeout: 2000,
40
+ });
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ export function readProcessStartTimeMs(pid) {
47
+ if (!Number.isInteger(pid) || pid <= 0)
48
+ return null;
49
+ if (process.platform === "linux") {
50
+ try {
51
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
52
+ const starttime = parseProcStatStartTime(stat);
53
+ if (starttime === null)
54
+ return null;
55
+ const uptimeRaw = readFileSync("/proc/uptime", "utf-8").trim().split(/\s+/)[0];
56
+ const uptime = Number(uptimeRaw);
57
+ if (!Number.isFinite(uptime))
58
+ return null;
59
+ return procStartTimeToEpochMs(starttime, uptime, Date.now());
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ if (process.platform === "darwin") {
66
+ const targetRaw = readPsLstart(pid);
67
+ if (targetRaw === null)
68
+ return null;
69
+ const targetParsed = parsePsLstart(targetRaw);
70
+ if (targetParsed === null)
71
+ return null;
72
+ const ownRaw = pid === process.pid ? targetRaw : readPsLstart(process.pid);
73
+ if (ownRaw === null)
74
+ return null;
75
+ const ownParsed = parsePsLstart(ownRaw);
76
+ if (ownParsed === null)
77
+ return null;
78
+ const ownTrueStartMs = Date.now() - process.uptime() * 1000;
79
+ return applyLstartZoneOffset(targetParsed, ownParsed, ownTrueStartMs);
80
+ }
81
+ return null;
82
+ }