@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,165 @@
1
+ /**
2
+ * init-occupied-listener.ts — flair#1749
3
+ *
4
+ * `flair init` used to treat "something already answered /health" as "our
5
+ * Harper is up", skip its own start, and then explain an operations-API 401
6
+ * as a wrong `--admin-pass`. Two claims that message must not make:
7
+ *
8
+ * - A different data directory does not prove the admin passwords differ.
9
+ * - The process holding the HTTP port is not necessarily the one that
10
+ * rejected an operations-port request. Those ports are resolved separately
11
+ * and can have different owners.
12
+ *
13
+ * Init can name a different data directory only when that one read could
14
+ * read one. An unreadable ROOTPATH is not proof of a foreign instance.
15
+ * On macOS the directory is unavailable, so init does not refuse before
16
+ * auth from a parsed ROOTPATH.
17
+ *
18
+ * That pre-auth observation is a single read. It is not the operations-port
19
+ * 401 check. A 401 names a pid only when the read before the insert and the
20
+ * read after the 401 are the same sole PID. Several holders, or a holder
21
+ * that changed during the request, stay "a Harper instance this init did
22
+ * not start".
23
+ *
24
+ * These messages do not offer `flair stop`. `flair stop` cannot be promised
25
+ * to act on this listener. The remedy is `kill <pid>` when one process is
26
+ * named. Init never signals a process it did not start.
27
+ */
28
+ import { canonicalLexicalPath } from "./daemon-liveness.js";
29
+ /**
30
+ * One observation of who is listening. An unreadable ROOTPATH is omitted,
31
+ * so it cannot become a pre-auth refusal. Does not decide `flair stop`.
32
+ */
33
+ export function listenerFromLookup(port, lookup) {
34
+ const pids = lookup.pids(port) ?? [];
35
+ const dataDirs = [];
36
+ for (const pid of pids) {
37
+ const read = lookup.rootPath(pid);
38
+ if (read.environReadable && read.rootPath && !dataDirs.includes(read.rootPath))
39
+ dataDirs.push(read.rootPath);
40
+ }
41
+ return { port, pids, dataDirs };
42
+ }
43
+ /**
44
+ * The process a 401 can be tied to.
45
+ *
46
+ * One pid, the same sole PID on both sides of the insert: that holder. Zero
47
+ * pids, several pids, or a different pid after the 401: nobody. The
48
+ * fallback does not keep data directories from a set of processes the 401
49
+ * was not tied to. This is not the pre-auth observation, which is one read.
50
+ */
51
+ export function stableAnsweredHolder(before, after) {
52
+ const sameSingle = before.pids.length === 1 &&
53
+ after.pids.length === 1 &&
54
+ before.pids[0] === after.pids[0];
55
+ if (!sameSingle) {
56
+ return { port: after.port, pids: [], dataDirs: [] };
57
+ }
58
+ return {
59
+ port: after.port,
60
+ pids: [after.pids[0]],
61
+ dataDirs: after.dataDirs,
62
+ };
63
+ }
64
+ const UNATTRIBUTED = "a Harper instance this init did not start";
65
+ /**
66
+ * Name the listener for an operator. A pid is included only when exactly one
67
+ * was read — several holders are not a kill list. Pid and data directory
68
+ * when both were read; whichever was read, plus the fallback phrase, when
69
+ * only one was; the fallback phrase alone when neither was.
70
+ */
71
+ export function describeOccupiedListener(listener) {
72
+ const pid = listener.pids.length === 1 ? `pid ${listener.pids[0]}` : null;
73
+ const dir = listener.dataDirs.length > 0 ? `data dir ${listener.dataDirs.join(", ")}` : null;
74
+ if (pid && dir)
75
+ return `${pid}, ${dir}`;
76
+ if (pid || dir)
77
+ return `${pid ?? dir} (${UNATTRIBUTED})`;
78
+ return UNATTRIBUTED;
79
+ }
80
+ /** Sentence carried wherever a different directory might be misread as a password fact. */
81
+ export const DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD = "A different data directory does not prove the admin passwords differ.";
82
+ /** Sentence carried on an operations-port rejection. The HTTP holder is a different fact. */
83
+ export const HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT = "The process holding the HTTP port is not necessarily the one that rejected the operations request.";
84
+ function foreignDataDirs(expectedDataDir, dataDirs) {
85
+ const expected = canonicalLexicalPath(expectedDataDir);
86
+ return dataDirs.filter((dir) => canonicalLexicalPath(dir) !== expected);
87
+ }
88
+ /**
89
+ * Printed from the single pre-auth read of the HTTP listener, when that
90
+ * read included a ROOTPATH other than this init's data directory. Init
91
+ * exits on it — before the authenticated health request and before the
92
+ * operations insert. This is not the before-and-after 401 attribution.
93
+ * A different directory is not proof the passwords differ. Returns null
94
+ * when the directory matches or could not be read: an unreadable lookup
95
+ * is not a foreign instance.
96
+ */
97
+ export function staleHarperBeforeAuthNotice(expectedDataDir, listener) {
98
+ const foreign = foreignDataDirs(expectedDataDir, listener.dataDirs);
99
+ if (foreign.length === 0)
100
+ return null;
101
+ const who = describeOccupiedListener({ pids: listener.pids, dataDirs: foreign });
102
+ const lines = [
103
+ `Harper on port ${listener.port} is ${who}, not this init's data dir ${expectedDataDir}.`,
104
+ ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
105
+ ` This init will not send its admin password to that process.`,
106
+ ` This init will not stop a process it did not start.`,
107
+ ];
108
+ appendRemedy(lines, listener);
109
+ return lines.join("\n");
110
+ }
111
+ /**
112
+ * Appended when init refuses before start because the port is already
113
+ * answering and this data directory has no persisted admin user. Names only
114
+ * what was read. Does not claim the passwords differ.
115
+ */
116
+ export function foreignOccupiedListenerDetail(listener, expectedDataDir) {
117
+ const lines = [
118
+ `The process listening on port ${listener.port} is ${describeOccupiedListener(listener)}.`,
119
+ `This init will not send its admin password to a process it did not start.`,
120
+ ];
121
+ if (expectedDataDir && foreignDataDirs(expectedDataDir, listener.dataDirs).length > 0) {
122
+ lines.push(DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD);
123
+ }
124
+ lines.push(`This init will not stop a process it did not start.`);
125
+ appendRemedy(lines, listener);
126
+ return lines.join("\n");
127
+ }
128
+ /**
129
+ * The operations-API 401 after init skipped its own start. Unlike the
130
+ * pre-auth notice, which is one read, `listener` here is the before-and-after
131
+ * attribution for the operations port: the same sole PID on both sides,
132
+ * or the unattributed fallback. Do not pass the HTTP port's pids through.
133
+ * The rejection is not proof the passwords differ, and it is not proof the
134
+ * HTTP listener caused it. The message does not offer `flair stop`.
135
+ */
136
+ export function occupiedListenerAuthFailure(input) {
137
+ const who = describeOccupiedListener(input.listener);
138
+ const lines = [
139
+ `${input.lead}${input.bodyText}`,
140
+ ` The operations port ${input.listener.port} rejected this init's admin credentials.`,
141
+ ` ${HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT}`,
142
+ ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
143
+ ` The process holding the operations port is ${who}.`,
144
+ ` This init will not stop a process it did not start.`,
145
+ ];
146
+ appendRemedy(lines, input.listener);
147
+ return lines.join("\n");
148
+ }
149
+ /**
150
+ * `kill` only for the one pid this message named. `flair stop` cannot be
151
+ * promised to act on this listener.
152
+ */
153
+ function appendRemedy(lines, listener) {
154
+ if (listener.pids.length === 1)
155
+ lines.push(` kill ${listener.pids[0]}`);
156
+ for (const dir of listener.dataDirs) {
157
+ lines.push(` flair init --data-dir ${commandArg(dir)}`);
158
+ }
159
+ }
160
+ /** Quote a path that would split on the shell. Numbers and plain paths stay bare. */
161
+ function commandArg(value) {
162
+ if (/^[A-Za-z0-9_./:@+-]+$/.test(value))
163
+ return value;
164
+ return `'${value.replace(/'/g, `'\\''`)}'`;
165
+ }
@@ -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
+ }