@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,448 @@
1
+ /**
2
+ * launchd-domain-preflight.ts — can THIS process load and start this
3
+ * instance's launchd job, in the domain the job belongs to, right now?
4
+ * (flair#2040).
5
+ *
6
+ * THE INCIDENT. `flair doctor --fix` over ssh clean-stopped a HEALTHY instance,
7
+ * then failed to load the launchd job — leaving Flair down. From that ssh
8
+ * session the per-user GUI launchd domain was not reachable: `launchctl print
9
+ * gui/<uid>` returned `125: Domain does not support specified action` and
10
+ * `launchctl bootstrap user/<uid>` returned `5: Input/output error`. `flair
11
+ * init` had printed "Launchd service registered ✓" for a plist it wrote but
12
+ * never loaded.
13
+ *
14
+ * THE RULE this module serves, for the guarded launchd handoffs — `doctor
15
+ * --fix`'s adopt/regenerate, `flair init`'s replacement of a legacy job, and
16
+ * the launchd attempt in `flair start` and in the start leg of restart /
17
+ * upgrade / snapshot: nothing running is stopped or unloaded before every
18
+ * check that can be made from this session has passed, an UNKNOWN answer is a
19
+ * failed check, and every failure after a stop is followed by an attempt to
20
+ * bring back what was running, reporting the state it left (or that the state
21
+ * could not be established). `flair restart` itself stops the instance first
22
+ * — that is what it was asked to do — so its start leg's preflight decides
23
+ * only HOW it comes back (under launchd, or directly), not whether it stopped.
24
+ *
25
+ * WHAT IS CHECKED, AND HOW. Everything here is READ-ONLY:
26
+ *
27
+ * launchctl print gui/<uid> is the GUI domain reachable from here?
28
+ * launchctl print-disabled gui/<uid> is this job's label disabled there?
29
+ *
30
+ * `print` and `print-disabled` only read launchd's state; they never load,
31
+ * start, bootstrap, unload or enable anything. What they cannot do is PROVE a
32
+ * later `bootstrap` will succeed — only loading something proves that — so the
33
+ * callers treat a passed preflight as "allowed to try", and restore on failure.
34
+ *
35
+ * WHY THE LOAD COMMANDS NAME THE DOMAIN. The legacy subcommands `launchctl
36
+ * load/unload/start` act on whatever domain launchctl infers for the CALLING
37
+ * process. Over ssh that is not the GUI domain (`launchctl managername` reports
38
+ * `Background` in a session where `print gui/<uid>` still answers), so a
39
+ * successful `print gui/<uid>` said nothing about where `load` would put the
40
+ * job. The load sequence therefore uses the targeted forms:
41
+ *
42
+ * launchctl bootout gui/<uid>/<label>
43
+ * launchctl bootstrap gui/<uid> <plist>
44
+ * launchctl kickstart gui/<uid>/<label>
45
+ *
46
+ * so the preflight and the load are about the SAME domain, and a failure is
47
+ * reported by the command that failed, for that domain.
48
+ *
49
+ * Pure and injected: every runner is a seam, so a test never touches launchd.
50
+ */
51
+ /** Ceiling on a domain probe; a hung launchctl must not hang the CLI. */
52
+ export const DOMAIN_PROBE_TIMEOUT_MS = 5_000;
53
+ /** The GUI domain a per-user LaunchAgent must be loaded into. */
54
+ export function launchdGuiDomain(uid) {
55
+ return `gui/${uid}`;
56
+ }
57
+ function firstLine(text) {
58
+ return text.trim().split("\n")[0] ?? "";
59
+ }
60
+ function probeSummary(command, code, text) {
61
+ const detail = firstLine(text);
62
+ if (code === null)
63
+ return `launchctl ${command} did not run${detail ? `: ${detail}` : ""}`;
64
+ return `launchctl ${command} exited ${code}${detail ? `: ${detail}` : ""}`;
65
+ }
66
+ /**
67
+ * The signatures of a GUI domain that this session cannot load into. `125`
68
+ * ("Domain does not support specified action") is the code measured over ssh in
69
+ * flair#2040; `5` ("Input/output error") is what `bootstrap` returned in the
70
+ * same session. The text forms cover the other wordings launchd uses for an
71
+ * unreachable domain. Anything else non-zero is `unknown`, never `available`.
72
+ */
73
+ const UNREACHABLE_SIGNATURE = /domain does not support specified action|could not find domain|no such domain|unknown domain|input\/output error|operation not permitted|not permitted/i;
74
+ /**
75
+ * Is the target GUI domain reachable from this process? Runs the read-only
76
+ * `launchctl print gui/<uid>`. `code 0` is available; the unreachable
77
+ * signatures (and codes 125/5) are `unavailable`; anything else (spawn failure,
78
+ * an uninterpretable code) is `unknown`, which every caller treats as "do not
79
+ * stop anything".
80
+ */
81
+ export function assessLaunchdDomain(opts) {
82
+ if (opts.platform !== "darwin") {
83
+ return { state: "not-applicable", reason: `${opts.platform} does not use launchd` };
84
+ }
85
+ const target = launchdGuiDomain(opts.uid);
86
+ let res;
87
+ try {
88
+ res = opts.run();
89
+ }
90
+ catch (err) {
91
+ const message = err instanceof Error ? err.message : String(err);
92
+ return { state: "unknown", reason: `could not run launchctl print ${target}: ${message}` };
93
+ }
94
+ const text = `${res.stderr}\n${res.stdout}`.trim();
95
+ if (res.code === 0)
96
+ return { state: "available" };
97
+ if (res.code === 125 || res.code === 5 || UNREACHABLE_SIGNATURE.test(text)) {
98
+ return { state: "unavailable", reason: probeSummary(`print ${target}`, res.code, text) };
99
+ }
100
+ return { state: "unknown", reason: probeSummary(`print ${target}`, res.code, text) };
101
+ }
102
+ /**
103
+ * Is `label` disabled in the output of `launchctl print-disabled gui/<uid>`?
104
+ *
105
+ * Two output forms are in the wild: `"<label>" => disabled|enabled` (macOS 13
106
+ * and later) and `"<label>" => true|false` (earlier; `true` means disabled). A
107
+ * label that is not listed is enabled — launchd lists only overrides.
108
+ */
109
+ export function parsePrintDisabled(output, label) {
110
+ // Match the quoted label as plain text and read its value with a fixed
111
+ // pattern: no expression is built from the label.
112
+ const quoted = `"${label}"`;
113
+ for (const line of output.split("\n")) {
114
+ const at = line.indexOf(quoted);
115
+ if (at < 0)
116
+ continue;
117
+ const m = /^\s*=>\s*(\w+)/.exec(line.slice(at + quoted.length));
118
+ if (!m)
119
+ continue;
120
+ return m[1] === "disabled" || m[1] === "true";
121
+ }
122
+ return false;
123
+ }
124
+ /**
125
+ * The full read-only preflight for loading `label` into the GUI domain: the
126
+ * domain probe first, then — only when the domain answers — whether the label
127
+ * is disabled there. A failed `print-disabled` is `unknown` (fail closed).
128
+ */
129
+ export function assessLaunchdLoadability(opts) {
130
+ const domain = assessLaunchdDomain({ platform: opts.platform, uid: opts.uid, run: opts.printDomain });
131
+ if (domain.state !== "available")
132
+ return domain;
133
+ const target = launchdGuiDomain(opts.uid);
134
+ let res;
135
+ try {
136
+ res = opts.printDisabled();
137
+ }
138
+ catch (err) {
139
+ const message = err instanceof Error ? err.message : String(err);
140
+ return { state: "unknown", reason: `could not run launchctl print-disabled ${target}: ${message}` };
141
+ }
142
+ if (res.code !== 0) {
143
+ return { state: "unknown", reason: probeSummary(`print-disabled ${target}`, res.code, `${res.stderr}\n${res.stdout}`) };
144
+ }
145
+ // flair#2040: "not listed" means enabled only in output we RECOGNISE. An
146
+ // unrecognised listing (no `disabled services` block) is unknown, not a
147
+ // silent "enabled".
148
+ if (!/disabled services/i.test(res.stdout)) {
149
+ return {
150
+ state: "unknown",
151
+ reason: `launchctl print-disabled ${target} printed no "disabled services" listing, so whether ${opts.label} is disabled is unknown`,
152
+ };
153
+ }
154
+ if (parsePrintDisabled(res.stdout, opts.label)) {
155
+ return {
156
+ state: "disabled",
157
+ label: opts.label,
158
+ reason: `the launchd job ${opts.label} is disabled in ${target} (launchctl print-disabled ${target}), so launchd would refuse to load it`,
159
+ };
160
+ }
161
+ return { state: "available" };
162
+ }
163
+ /** True when the preflight allows an attempt (available, or not macOS). */
164
+ export function loadabilityAllowsAttempt(l) {
165
+ return l.state === "available" || l.state === "not-applicable";
166
+ }
167
+ /** One clause naming why launchd cannot be used from here (for the messages below). */
168
+ export function describeLoadabilityProblem(l) {
169
+ switch (l.state) {
170
+ case "unavailable":
171
+ return `the launchd GUI domain is unavailable from this session (${l.reason})`;
172
+ case "unknown":
173
+ return `the launchd GUI domain could not be verified from this session (${l.reason})`;
174
+ case "disabled":
175
+ return l.reason;
176
+ }
177
+ }
178
+ /** The remedy for a failed preflight: what the operator runs, and where. */
179
+ export function loadabilityRemedy(l, uid, rerun) {
180
+ if (l.state === "disabled") {
181
+ return `run 'launchctl enable ${launchdGuiDomain(uid)}/${l.label}', then '${rerun}'`;
182
+ }
183
+ return `run '${rerun}' from a console (GUI) login session on this Mac`;
184
+ }
185
+ /**
186
+ * The conditional sentence about RunAtLoad. It is what launchd MAY do — it
187
+ * reads the plist at the next console login and starts a job that sets
188
+ * RunAtLoad — not a guarantee: a plist that is invalid, points at a missing
189
+ * program, or whose job is disabled does not start.
190
+ */
191
+ export const RUN_AT_LOAD_NOTE = "launchd may also start the job at the next console login (the plist sets RunAtLoad), " +
192
+ "provided the plist is valid and the job is enabled";
193
+ /**
194
+ * What happens if launchd starts the job while a DIRECT process serves the same
195
+ * data directory: the product launcher finds the live pid in `<dataDir>/hdb.pid`
196
+ * and exits without starting a second Harper (templates/launchd/
197
+ * start-flair-with-admin-pass.sh).
198
+ */
199
+ export const DIRECT_PROCESS_GUARD_NOTE = "while a direct process serves this data directory, a launchd start of the job exits without starting a second instance";
200
+ // ─── doctor --fix ─────────────────────────────────────────────────────────
201
+ /**
202
+ * The `doctor --fix` refusal when the preflight fails. Actor + state + remedy,
203
+ * and an explicit statement that nothing was touched.
204
+ */
205
+ export function renderDomainUnavailableMessage(l, uid) {
206
+ return (`flair doctor --fix: refusing to repair launchd management — ${describeLoadabilityProblem(l)}. ` +
207
+ "Nothing was stopped, unloaded or rewritten; a running instance was left running. " +
208
+ `Fix: ${loadabilityRemedy(l, uid, "flair doctor --fix")}. ` +
209
+ `If this instance's plist is already on disk, ${RUN_AT_LOAD_NOTE}.`);
210
+ }
211
+ // ─── flair start / restart (direct-start fallback) ────────────────────────
212
+ /** Why `start` (or a restart's start leg) is not using launchd, before it starts directly. */
213
+ export function renderStartLaunchdUnavailable(actor, l) {
214
+ return `${actor}: launchd cannot start this instance's job from this session — ${describeLoadabilityProblem(l)}. Starting Flair directly instead.`;
215
+ }
216
+ /**
217
+ * The launchd attempt itself failed (load/start/health) AND the job was then
218
+ * verified absent from the domain (ensureLaunchdJobAbsent) — only then does the
219
+ * caller fall back to a direct start, and only then may it say so.
220
+ */
221
+ export function renderStartLaunchdFailed(actor, label, error) {
222
+ return `${actor}: launchd could not start the job ${label} (${error}). The job was unloaded again (verified absent); starting Flair directly instead.`;
223
+ }
224
+ /**
225
+ * The launchd attempt failed and the job could NOT be shown to be unloaded:
226
+ * launchd may still start it, and a direct start could run a second Harper on
227
+ * the same data directory. The caller does not start directly.
228
+ */
229
+ export function renderStartLaunchdUnloadUncertain(actor, target, error, uncertainty) {
230
+ return [
231
+ `${actor}: launchd could not start the job ${target} (${error}), and unloading it again could not be confirmed (${uncertainty}).`,
232
+ " Flair was NOT started directly: launchd may still start this job, and a direct start could run a second instance on the same data directory.",
233
+ ` Fix: unload it ('launchctl bootout ${target}'), confirm 'launchctl print ${target}' no longer finds it, then re-run the command.`,
234
+ ];
235
+ }
236
+ // ─── validation refusals (flair#2040) ─────────────────────────────────────
237
+ /**
238
+ * A launchd attempt refused by VALIDATION: a check made before any launchctl
239
+ * call that changes launchd's state failed (the plist's paths, its Label, its
240
+ * syntax, a legacy plist that could not be read). Nothing was loaded or
241
+ * unloaded, and no plist was written or removed.
242
+ *
243
+ * The start paths must tell this apart from a failed LOAD. After a failed load
244
+ * they unload what the attempt may have loaded. After a validation refusal the
245
+ * attempt loaded nothing, so there is nothing of its own to unload — and a job
246
+ * that IS loaded (a legacy job, say) is not the attempt's to boot out.
247
+ */
248
+ export class LaunchdValidationRefusal extends Error {
249
+ launchdValidationRefusal = true;
250
+ constructor(message) {
251
+ super(message);
252
+ this.name = "LaunchdValidationRefusal";
253
+ }
254
+ }
255
+ /** True when `err` is a LaunchdValidationRefusal (by marker, so a copied module still matches). */
256
+ export function isLaunchdValidationRefusal(err) {
257
+ return (err instanceof LaunchdValidationRefusal ||
258
+ (typeof err === "object" && err !== null && err.launchdValidationRefusal === true));
259
+ }
260
+ /**
261
+ * READ-ONLY (flair#2040): the first of `labels` that is loaded in `domain`, or
262
+ * whose presence cannot be read — a job launchd could start underneath a direct
263
+ * process. null only when every label is PROVEN absent. Issues nothing but
264
+ * `launchctl print <domain>/<label>`.
265
+ */
266
+ export function firstLaunchdJobNotProvenAbsent(run, domain, labels) {
267
+ for (const label of labels) {
268
+ const presence = launchdJobPresence(run, domain, label);
269
+ if (presence !== "absent")
270
+ return { target: `${domain}/${label}`, presence };
271
+ }
272
+ return null;
273
+ }
274
+ /**
275
+ * The launchd attempt was refused by validation, nothing was loaded or
276
+ * unloaded, and every job for the instance is PROVEN absent — so the caller
277
+ * starts directly, and says so.
278
+ */
279
+ export function renderStartLaunchdValidationRefused(actor, label, cause) {
280
+ return (`${actor}: did not load the launchd job ${label}: its plist failed a check made before anything was loaded (${cause}). ` +
281
+ "Nothing was loaded or unloaded, and no plist was written or removed. " +
282
+ "No launchd job for this instance is loaded (verified absent); starting Flair directly instead.");
283
+ }
284
+ /**
285
+ * The launchd attempt was refused by validation (nothing was loaded or
286
+ * unloaded), and a job for the instance is loaded — or its presence cannot be
287
+ * read. launchd could start it underneath a direct process, so the caller
288
+ * starts nothing, and leaves the job and the plists as they are.
289
+ */
290
+ export function renderStartLaunchdValidationBlocked(actor, label, cause, target, presence) {
291
+ const state = presence === "loaded" ? `${target} is loaded` : `whether ${target} is loaded could not be read`;
292
+ return [
293
+ `${actor}: did not load the launchd job ${label}: its plist failed a check made before anything was loaded (${cause}). ` +
294
+ "Nothing was loaded or unloaded, and no plist was written or removed.",
295
+ ` Flair was NOT started directly: ${state}, and launchd could start that job underneath a direct process — a second instance on the same data directory.`,
296
+ ` Fix: unload that job ('launchctl bootout ${target}'), confirm 'launchctl print ${target}' no longer finds it, and re-run the command; or correct the plist so the check passes, and re-run the command.`,
297
+ ];
298
+ }
299
+ /**
300
+ * The lines after a direct start that took the place of launchd: running
301
+ * directly, NOT launchd-managed — with what that costs and what to do.
302
+ */
303
+ export function renderDirectRunNotice(port, pid) {
304
+ return [
305
+ `✅ Flair started on port ${port} — running directly${pid ? ` (pid ${pid})` : ""}, NOT launchd-managed.`,
306
+ " launchd will not restart it if it exits. To hand it to launchd, run 'flair doctor --fix' from a console (GUI) login session.",
307
+ ` ${RUN_AT_LOAD_NOTE[0].toUpperCase()}${RUN_AT_LOAD_NOTE.slice(1)}; ${DIRECT_PROCESS_GUARD_NOTE}.`,
308
+ ];
309
+ }
310
+ export function bootoutCommand(domain, label) {
311
+ return `launchctl bootout ${domain}/${label}`;
312
+ }
313
+ export function bootstrapCommand(domain, plistPath) {
314
+ return `launchctl bootstrap ${domain} "${plistPath}"`;
315
+ }
316
+ export function kickstartCommand(domain, label) {
317
+ return `launchctl kickstart ${domain}/${label}`;
318
+ }
319
+ export function printJobCommand(domain, label) {
320
+ return `launchctl print ${domain}/${label}`;
321
+ }
322
+ /**
323
+ * Is `label` loaded in `domain`, per the read-only `launchctl print
324
+ * <domain>/<label>`? (flair#2040) Tri-state on purpose: "absent" only when
325
+ * launchctl SAYS so (exit 113 / "Could not find service"); any other failure is
326
+ * "unknown" — a probe that did not answer is not proof the job is gone.
327
+ */
328
+ export function launchdJobPresence(run, domain, label) {
329
+ try {
330
+ run(printJobCommand(domain, label));
331
+ return "loaded";
332
+ }
333
+ catch (err) {
334
+ const e = err;
335
+ const text = `${e && e.stderr != null ? String(e.stderr) : ""}\n${String(e?.message ?? err)}`;
336
+ if (e?.status === 113 || /could not find service/i.test(text))
337
+ return "absent";
338
+ return "unknown";
339
+ }
340
+ }
341
+ /**
342
+ * Boot `label` out of `domain` and VERIFY it is gone (flair#2040): `bootout`
343
+ * errors are not swallowed into "fine" — absence is re-read with the
344
+ * read-only presence probe — polled for up to `settleMs` after a bootout that
345
+ * launchctl accepted (or reports in progress), because `bootout` can return
346
+ * while launchd is still tearing the job down. Returns null when the job
347
+ * is PROVEN absent, or the reason absence could not be established. (A nullable
348
+ * result rather than a boolean-keyed union: src/cli.ts compiles without
349
+ * strictNullChecks, where such a union does not narrow.)
350
+ */
351
+ export function ensureLaunchdJobAbsent(opts) {
352
+ const { run, domain, label } = opts;
353
+ const settleMs = opts.settleMs ?? 5_000;
354
+ const sleep = opts.sleep ?? sleepSync;
355
+ let bootoutError = null;
356
+ if (launchdJobPresence(run, domain, label) === "absent")
357
+ return null;
358
+ try {
359
+ run(bootoutCommand(domain, label));
360
+ }
361
+ catch (err) {
362
+ bootoutError = errorText(err);
363
+ }
364
+ // Wait out launchd's asynchronous teardown only when there is one to wait
365
+ // for: a bootout launchctl accepted, or one it reports as still in
366
+ // progress. A bootout it REFUSED leaves the job where it was — re-read once.
367
+ const settling = bootoutError === null || /in progress|\b36\b/i.test(bootoutError);
368
+ const deadline = Date.now() + (settling ? settleMs : 0);
369
+ let presence = launchdJobPresence(run, domain, label);
370
+ while (presence !== "absent" && Date.now() < deadline) {
371
+ sleep(250);
372
+ presence = launchdJobPresence(run, domain, label);
373
+ }
374
+ if (presence === "absent")
375
+ return null;
376
+ return (`after launchctl bootout ${domain}/${label}${bootoutError ? ` (which failed: ${bootoutError})` : ""}, ` +
377
+ (presence === "loaded" ? "the job is still loaded" : "launchctl print could not say whether the job is loaded"));
378
+ }
379
+ function errorText(err) {
380
+ const e = err;
381
+ const stderr = e && e.stderr != null ? String(e.stderr).trim() : "";
382
+ if (stderr)
383
+ return firstLine(stderr);
384
+ return firstLine(String(e?.message ?? err));
385
+ }
386
+ /** Synchronous sleep for the short bootout settle wait (no event loop needed). */
387
+ function sleepSync(ms) {
388
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
389
+ }
390
+ /**
391
+ * Load and start `label` from `plistPath` in `domain`, with commands that name
392
+ * the domain: bootout (so a rewritten plist is re-read, flair#872) → bootstrap
393
+ * → kickstart.
394
+ *
395
+ * `bootout` of a job that is not loaded fails harmlessly and is ignored here:
396
+ * nothing below trusts it — a failed bootstrap is retried ONLY after the job is
397
+ * proven absent (launchdJobPresence). `bootout` is asynchronous, so a failed
398
+ * bootstrap waits (up to `settleMs`) for the job to leave the domain and
399
+ * retries ONCE. If the job is not proven gone:
400
+ * - `strict` (doctor, init): throw — the loaded definition is the old one,
401
+ * and a repair must not report the new one as loaded;
402
+ * - otherwise (start/restart): fall through to `kickstart`, which starts the
403
+ * definition launchd holds — the tolerance the old `load` step had.
404
+ * A `kickstart` failure always throws, naming the bootstrap failure too.
405
+ */
406
+ export function loadLaunchdJob(opts) {
407
+ const { run, domain, label, plistPath } = opts;
408
+ const settleMs = opts.settleMs ?? 5_000;
409
+ const sleep = opts.sleep ?? sleepSync;
410
+ try {
411
+ run(bootoutCommand(domain, label));
412
+ }
413
+ catch { /* not loaded — nothing to boot out */ }
414
+ let bootstrapError = null;
415
+ try {
416
+ run(bootstrapCommand(domain, plistPath));
417
+ }
418
+ catch (first) {
419
+ bootstrapError = errorText(first);
420
+ // Retry only once the job is PROVEN absent; "unknown" counts as still there.
421
+ const deadline = Date.now() + settleMs;
422
+ let presence = launchdJobPresence(run, domain, label);
423
+ while (presence !== "absent" && Date.now() < deadline) {
424
+ sleep(250);
425
+ presence = launchdJobPresence(run, domain, label);
426
+ }
427
+ if (presence === "absent") {
428
+ try {
429
+ run(bootstrapCommand(domain, plistPath));
430
+ bootstrapError = null;
431
+ }
432
+ catch (second) {
433
+ throw new Error(`launchctl bootstrap ${domain} ${plistPath} failed: ${errorText(second)}`);
434
+ }
435
+ }
436
+ else if (opts.strict) {
437
+ throw new Error(`launchctl bootstrap ${domain} ${plistPath} failed (${bootstrapError}) and ${domain}/${label} is still loaded ` +
438
+ "with its previous definition, so the rewritten plist was not loaded");
439
+ }
440
+ }
441
+ try {
442
+ run(kickstartCommand(domain, label));
443
+ }
444
+ catch (err) {
445
+ const why = bootstrapError ? ` (bootstrap had failed: ${bootstrapError})` : "";
446
+ throw new Error(`launchctl kickstart ${domain}/${label} failed: ${errorText(err)}${why}`);
447
+ }
448
+ }
@@ -45,7 +45,7 @@
45
45
  * extracted program/working-directory paths ever reach a message, and the
46
46
  * extractor below reads exactly those keys rather than returning the document.
47
47
  */
48
- import { existsSync, readFileSync } from "node:fs";
48
+ import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
49
49
  import { unescapeXml } from "./xml-escape.js";
50
50
  /**
51
51
  * Ceiling on the `launchctl list` spawn. A status query answers instantly when
@@ -158,6 +158,133 @@ export function diagnoseLaunchdPlistPaths(plistPath, deps = {}) {
158
158
  }
159
159
  return null;
160
160
  }
161
+ /**
162
+ * Validate a plist's CONTENT before it is written or loaded (flair#2040) —
163
+ * the check that must pass before any command stops the running instance to
164
+ * put this plist in its place.
165
+ *
166
+ * `diagnoseLaunchdPlistPaths` reads a plist that is already on disk and words
167
+ * its finding as drift ("no longer exists"). This reads the document the caller
168
+ * is ABOUT to install and answers a stricter question: can launchd run it?
169
+ *
170
+ * - every absolute ProgramArguments entry exists;
171
+ * - ProgramArguments[0] — what launchd execs — is executable;
172
+ * - for the pass-file shape (`<launcher> <admin-pass-file> <node> <harper>`),
173
+ * the node binary the launcher execs is executable;
174
+ * - WorkingDirectory is an existing directory;
175
+ * - ROOTPATH (the data directory) is an existing directory.
176
+ *
177
+ * Returns one line naming the offending key and path, or null. Never returns
178
+ * plist content — only the extracted paths (the plist may name the pass file).
179
+ */
180
+ export function checkLaunchdPlistBeforeLoad(content, deps = {}) {
181
+ const exists = deps.exists ?? existsSync;
182
+ const isExecutable = deps.isExecutable ?? ((p) => {
183
+ try {
184
+ accessSync(p, constants.X_OK);
185
+ return true;
186
+ }
187
+ catch {
188
+ return false;
189
+ }
190
+ });
191
+ const isDirectory = deps.isDirectory ?? ((p) => {
192
+ try {
193
+ return statSync(p).isDirectory();
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ });
199
+ const refs = readPlistProgramRefs("<content>", () => content);
200
+ if (!refs || refs.programArguments.length === 0)
201
+ return "the plist has no ProgramArguments";
202
+ for (const arg of refs.programArguments) {
203
+ if (arg.startsWith("/") && !exists(arg))
204
+ return `ProgramArguments names ${arg}, which does not exist`;
205
+ }
206
+ const program = refs.programArguments[0];
207
+ if (!program.startsWith("/"))
208
+ return `ProgramArguments[0] (${program}) is not an absolute path`;
209
+ if (!isExecutable(program))
210
+ return `ProgramArguments[0] (${program}) is not executable, so launchd cannot exec it`;
211
+ if (refs.programArguments.length >= 4 && refs.programArguments[0].endsWith(".sh")) {
212
+ const node = refs.programArguments[2];
213
+ if (node.startsWith("/") && !isExecutable(node))
214
+ return `the node binary the launcher execs (${node}) is not executable`;
215
+ }
216
+ const wd = refs.workingDirectory;
217
+ if (wd === null)
218
+ return "the plist has no WorkingDirectory";
219
+ if (!isDirectory(wd))
220
+ return `WorkingDirectory ${wd} is not an existing directory`;
221
+ const root = content.match(/<key>ROOTPATH<\/key>\s*<string>([^<]*)<\/string>/);
222
+ if (!root)
223
+ return "the plist has no ROOTPATH";
224
+ const rootPath = unescapeXml(root[1]);
225
+ if (!isDirectory(rootPath))
226
+ return `ROOTPATH ${rootPath} (the data directory) is not an existing directory`;
227
+ return null;
228
+ }
229
+ function realpathOr(p, realpath) {
230
+ try {
231
+ return realpath(p);
232
+ }
233
+ catch {
234
+ return p;
235
+ }
236
+ }
237
+ export function classifyServiceNodePin(input, deps = {}) {
238
+ const exists = deps.exists ?? existsSync;
239
+ const realpath = deps.realpath ?? ((p) => realpathSync(p));
240
+ const { unitNodeBin, unitTree, currentNodeBin, cliTree, unitDescription } = input;
241
+ if (!unitNodeBin || !unitTree)
242
+ return null;
243
+ if (!exists(unitNodeBin))
244
+ return null; // the missing path is diagnoseLaunchdPlistPaths's
245
+ if (realpathOr(unitNodeBin, realpath) === realpathOr(currentNodeBin, realpath))
246
+ return null;
247
+ if (realpathOr(unitTree, realpath) === realpathOr(cliTree, realpath)) {
248
+ return {
249
+ kind: "pinned",
250
+ unitNodeBin,
251
+ currentNodeBin,
252
+ // `flair init` never rewrites a pin (it reports `pinned-node` and writes
253
+ // nothing), so the only way to move it is by hand — said as such.
254
+ message: `${unitDescription} pins node ${unitNodeBin} while this CLI runs ${currentNodeBin}, and it serves this ` +
255
+ `CLI's own install tree (${unitTree}). That is treated as a deliberate runtime pin and left as it is; ` +
256
+ "`flair init` does not change it. To move the service to this CLI's runtime, change that node path to " +
257
+ `${currentNodeBin} in the unit by hand, then run: flair restart`,
258
+ remedy: [],
259
+ };
260
+ }
261
+ return {
262
+ kind: "erroneous",
263
+ unitNodeBin,
264
+ currentNodeBin,
265
+ message: `${unitDescription} runs node ${unitNodeBin} from the install tree ${unitTree}, but this CLI runs node ` +
266
+ `${currentNodeBin} from ${cliTree}. Both were baked at an earlier runtime, so the service keeps serving ` +
267
+ "the old tree while the CLI runs from the current one.",
268
+ remedy: ["flair init", "flair restart"],
269
+ };
270
+ }
271
+ /**
272
+ * `classifyServiceNodePin` for a launchd plist: reads the node argument and the
273
+ * WorkingDirectory out of the plist and classifies them against this CLI.
274
+ */
275
+ export function diagnoseLaunchdNodePath(plistPath, currentNodeBin, cliTree, deps = {}) {
276
+ const refs = readPlistProgramRefs(plistPath, deps.read);
277
+ if (!refs)
278
+ return null;
279
+ const unitNodeBin = refs.programArguments.find((a) => a.startsWith("/") && /(^|[/\\])node$/.test(a)) ?? null;
280
+ return classifyServiceNodePin({
281
+ unitDescription: `the launchd plist at ${plistPath}`,
282
+ unitNodeBin,
283
+ unitTree: refs.workingDirectory,
284
+ currentNodeBin,
285
+ cliTree,
286
+ }, deps);
287
+ }
161
288
  /**
162
289
  * Parse `launchctl list <label>` output.
163
290
  *
@@ -205,15 +332,35 @@ export function readLaunchctlJobState(label, list) {
205
332
  * PID is no evidence, so it is discarded and the port listener answers instead.
206
333
  */
207
334
  export function pickInstancePid(input) {
208
- const { pidFilePid, isAlive, listeningPids } = input;
209
- if (pidFilePid !== null && isAlive(pidFilePid))
335
+ const { pidFilePid, isAlive, listeningPids, isPidFileEvidence } = input;
336
+ if (pidFilePid !== null && isAlive(pidFilePid) && (isPidFileEvidence === undefined || isPidFileEvidence(pidFilePid))) {
210
337
  return pidFilePid;
338
+ }
211
339
  return listeningPids.length > 0 ? listeningPids[0] : null;
212
340
  }
213
341
  /** True when the instance is running outside the service manager that is registered to own it. */
214
342
  export function isDetached(m) {
215
343
  return m.state === "detached";
216
344
  }
345
+ /**
346
+ * The STRICT verifier every success claim goes through (flair#2040): a
347
+ * launchd check mark from `flair start` or `flair init`, and `doctor --fix`'s
348
+ * "repaired". Verified ONLY when launchd reported a pid, a serving pid was
349
+ * IDENTIFIED, and they are the same number. An unknown serving pid is never
350
+ * verified — unknown evidence must not license a success claim.
351
+ *
352
+ * `assessLaunchdManagement` is the observer (status, warnings); this decides
353
+ * what may be claimed.
354
+ */
355
+ export function verifyLaunchdManagement(m) {
356
+ if (m.state === "managed" &&
357
+ typeof m.launchdPid === "number" &&
358
+ typeof m.servingPid === "number" &&
359
+ m.launchdPid === m.servingPid) {
360
+ return { verified: true, pid: m.launchdPid, detail: m.detail };
361
+ }
362
+ return { verified: false, detail: m.detail, remedy: m.remedy };
363
+ }
217
364
  /**
218
365
  * Is this instance under launchd right now?
219
366
  *
@@ -232,10 +379,11 @@ export function isDetached(m) {
232
379
  * - launchd reports a PID that is not the instance's PID ⇒ **detached**, and
233
380
  * this is the exact shape the incident produced: launchd holds a job that
234
381
  * is failing, while a directly-spawned process answers on the port.
235
- * - launchd reports a PID and we cannot read the instance's own ⇒ **managed**.
236
- * A live job under this instance's label is positive evidence; refusing to
237
- * believe it because `hdb.pid` was unreadable would warn on healthy
238
- * installs, which is its own defect.
382
+ * - launchd reports a PID and we cannot identify the instance's own ⇒
383
+ * **unverified** (flair#2040). Warning on it would alarm healthy installs,
384
+ * which is its own defect; calling it managed would be a claim without
385
+ * proof. It is neither: no warning, and no success claim
386
+ * (verifyLaunchdManagement refuses it).
239
387
  *
240
388
  * A parent-process check is NOT used, and that is worth stating because it is
241
389
  * the obvious first idea: the direct-start fallback spawns `detached: true` and
@@ -292,9 +440,32 @@ export function assessLaunchdManagement(input) {
292
440
  detail: `this instance is served by process ${instancePid}, but launchd's job ${label} is process ${job.pid} — ` +
293
441
  `the running instance is not the one launchd manages.${because}`,
294
442
  remedy,
443
+ launchdPid: job.pid,
444
+ servingPid: instancePid,
295
445
  };
296
446
  }
297
- return { state: "managed", label, detail: `launchd job ${label} is running as process ${job.pid}` };
447
+ if (instancePid === null) {
448
+ // flair#2040: launchd runs SOMETHING, but nothing identifies the process
449
+ // serving this instance. Not detached (no evidence of that, and a warning
450
+ // on a healthy install trains operators to skip warnings) — and not
451
+ // managed either: an unknown serving pid is not proof.
452
+ return {
453
+ state: "unverified",
454
+ label,
455
+ detail: `launchd job ${label} is running as process ${job.pid}, but the process serving this instance could not be ` +
456
+ "identified (no live hdb.pid, and no listener found on its port), so launchd management is NOT verified",
457
+ remedy: ["flair restart"],
458
+ launchdPid: job.pid,
459
+ servingPid: null,
460
+ };
461
+ }
462
+ return {
463
+ state: "managed",
464
+ label,
465
+ detail: `launchd job ${label} is running as process ${job.pid}`,
466
+ launchdPid: job.pid,
467
+ servingPid: instancePid,
468
+ };
298
469
  }
299
470
  /**
300
471
  * The lines to print for a degraded (detached) outcome.