@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,575 @@
1
+ /**
2
+ * service-repoint.ts — re-point the instance's own service unit at this CLI's
3
+ * install tree, changing ONLY the runtime paths (flair#2034 §2).
4
+ *
5
+ * `flair init` used to leave an already-adopted launchd plist byte-for-byte
6
+ * unchanged (flair#1693: an adopted plist must never be downgraded), so after a
7
+ * Node bump the advised `flair init && flair restart` restarted the instance
8
+ * from the OLD tree. The fix is not to regenerate the unit — that would drop
9
+ * whatever the operator changed in it — but to replace the few values that name
10
+ * a runtime or an install tree and leave every other byte where it was.
11
+ *
12
+ * These are OPERATOR FILES, so the rule is REFUSE RATHER THAN HANDLE: a unit is
13
+ * written only when it is provably this instance's and exactly one of the
14
+ * shapes below, every operand in its runtime role. Anything else is refused
15
+ * with a message naming the file, what did not match, and the change to make by
16
+ * hand. No other shape is interpreted, and no operator argument is rewritten.
17
+ *
18
+ * - launchd — the pass-file plist `flair init` / `doctor --fix` write, for
19
+ * THIS instance, read as XML structure (readPlistStructure — a non-UTF-8
20
+ * declaration, a comment, CDATA or an unsupported XML element is refused): one Label (this
21
+ * data dir's label) at the top level, one ROOTPATH (this data dir) and one
22
+ * HOME (this user's home) in EnvironmentVariables, no `Program` key, one WorkingDirectory
23
+ * and a ProgramArguments array of exactly
24
+ * [<tree>/templates/launchd/start-flair-with-admin-pass.sh,
25
+ * <this instance's admin-pass file>, <…/node>,
26
+ * <tree>/node_modules/<harper>/dist/bin/harper.js].
27
+ * Re-pointed: the launcher, node, Harper entry and WorkingDirectory. The
28
+ * admin-pass path and every other key are untouched.
29
+ * - systemd user unit (Linux; flair writes none, so only these two shapes):
30
+ * ExecStart=[-]<…/node> <tree>/node_modules/<harper>/dist/bin/harper.js run .
31
+ * ExecStart=[-]<tree>/templates/launchd/start-flair-with-admin-pass.sh <admin-pass file> <…/node> <harper.js>
32
+ * with exactly one `WorkingDirectory=[-]<tree>` and one `ExecStart=` in
33
+ * [Service], no line continuation, no quoting, specifier, variable or
34
+ * ExecStart prefix other than `-`. Re-pointed: node, Harper entry, launcher,
35
+ * WorkingDirectory. The admin-pass argument is the operator's and is kept.
36
+ * A target path that would need quoting in a unit (a space, a quote, `%`,
37
+ * `$`, …) is refused, never written.
38
+ *
39
+ * WHEN a valid unit is re-pointed (the same rule for both):
40
+ *
41
+ * - it serves an npm-global install tree (`…/lib/node_modules/@tpsdev-ai/flair`)
42
+ * that is NOT this CLI's tree, whose flair version can be read and is not
43
+ * newer than this CLI's → node, Harper entry, launcher and tree move together;
44
+ * - it serves a plain tree or a checkout → never (`refuse`): separately managed;
45
+ * - the old tree's flair version (or this CLI's) cannot be read, is not strict
46
+ * semver, or is newer by semver ordering (0.57.0-beta.1 is older than 0.57.0)
47
+ * → refused: a downgrade cannot be ruled out;
48
+ * - it serves THIS CLI's tree with an existing, different node → a deliberate
49
+ * runtime pin, left as it is (`pinned-node`);
50
+ * - launchd only: it serves this CLI's tree and one of its runtime paths no
51
+ * longer exists → only the missing path is replaced (systemd: refused).
52
+ *
53
+ * Every refusal names the unit file, what did not match, and the remedy — the
54
+ * paths to set by hand, an update, or a reinstall.
55
+ *
56
+ * Pure: text in, text out. The callers own the reads, the atomic write (with
57
+ * the planned-from re-check) and the service-manager reload.
58
+ */
59
+ import { basename, isAbsolute, relative, sep } from "node:path";
60
+ import { escapeXml, unescapeXml } from "./xml-escape.js";
61
+ import { compareVersions, isExactSemver, isNpmGlobalFlairTree } from "./tree-divergence.js";
62
+ export const LAUNCHER_BASENAME = "start-flair-with-admin-pass.sh";
63
+ /** The launcher's path relative to an install tree. */
64
+ export const LAUNCHER_REL = "templates/launchd/start-flair-with-admin-pass.sh";
65
+ /** A Harper entry's path relative to an install tree (`harper`, `@harperfast/harper`, …). */
66
+ const HARPER_ENTRY_REL = /^node_modules\/(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+\/dist\/bin\/harper\.js$/;
67
+ /**
68
+ * The characters a path may contain to be written into a systemd unit as one
69
+ * unquoted word. A whitelist: anything else (a space, a quote, `%`, `$`, `\`,
70
+ * `;`, a control character) would need quoting or escaping, and is refused.
71
+ */
72
+ const SYSTEMD_SAFE_PATH = /^\/[A-Za-z0-9._@+~/-]*$/;
73
+ /** One unquoted word of a supported ExecStart= (the same whitelist, plus the relative `run` and `.`). */
74
+ const SYSTEMD_SAFE_WORD = /^[A-Za-z0-9._@+~/-]+$/;
75
+ function describeChanges(changes) {
76
+ return changes.map((c) => `${c.field}: ${c.from} → ${c.to}`).join("; ");
77
+ }
78
+ /** `p` relative to `tree` (both canonical, `/`-separated), or null when `p` is not strictly inside `tree`. */
79
+ function relInTree(tree, p, deps) {
80
+ if (!isAbsolute(p) || !isAbsolute(tree))
81
+ return null;
82
+ const rel = relative(deps.canonical(tree), deps.canonical(p));
83
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel))
84
+ return null;
85
+ return rel.split(sep).join("/");
86
+ }
87
+ function isNodeBinary(p) {
88
+ return isAbsolute(p) && basename(p) === "node";
89
+ }
90
+ /** The hand-edit remedy every refusal carries. */
91
+ function byHand(t, launcher) {
92
+ const parts = [
93
+ ...(launcher && t.launcher ? [`the launcher to ${t.launcher}`] : []),
94
+ `node to ${t.nodeBin}`,
95
+ `the Harper entry to ${t.harperBin}`,
96
+ `WorkingDirectory to ${t.workingDirectory}`,
97
+ ];
98
+ return ` To move it to this CLI's tree, set ${parts.join(", ")} by hand, then run: flair restart`;
99
+ }
100
+ /** Why this CLI's own targets cannot be written into the unit, or null. */
101
+ function targetProblem(t, deps, launcher, systemd) {
102
+ if (!isNodeBinary(t.nodeBin))
103
+ return `this CLI's node path ${t.nodeBin} is not an absolute path to a \`node\` binary.`;
104
+ const harperRel = relInTree(t.workingDirectory, t.harperBin, deps);
105
+ if (harperRel === null || !HARPER_ENTRY_REL.test(harperRel)) {
106
+ return `this CLI's Harper entry ${t.harperBin} is not inside its install tree ${t.workingDirectory}.`;
107
+ }
108
+ if (launcher) {
109
+ if (!t.launcher)
110
+ return "this CLI's launcher path is not known.";
111
+ if (relInTree(t.workingDirectory, t.launcher, deps) !== LAUNCHER_REL) {
112
+ return `this CLI's launcher ${t.launcher} is not ${LAUNCHER_REL} inside its install tree ${t.workingDirectory}.`;
113
+ }
114
+ }
115
+ if (systemd) {
116
+ for (const p of [t.workingDirectory, t.nodeBin, t.harperBin, ...(launcher && t.launcher ? [t.launcher] : [])]) {
117
+ if (!SYSTEMD_SAFE_PATH.test(p)) {
118
+ return (`this CLI's path ${JSON.stringify(p)} contains a character that would need quoting in a systemd unit, and flair ` +
119
+ "does not write quoted paths into a unit.");
120
+ }
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+ /**
126
+ * Shared decision: may a unit serving `oldTree` be moved to `t.workingDirectory`?
127
+ * Every refusal carries its remedy (a hand edit, an update, or a reinstall).
128
+ */
129
+ function treeGate(oldTree, t, deps, unit, launcher) {
130
+ if (!isNpmGlobalFlairTree(oldTree)) {
131
+ return (`${unit} serves ${oldTree}, which is not an npm-global install (a plain tree or a checkout), so flair treats it ` +
132
+ `as a separately managed deployment and does not re-point it.${byHand(t, launcher)}`);
133
+ }
134
+ // Semver ordering (prereleases included); a version that cannot be read or
135
+ // is not strict semver cannot rule a downgrade out, so it is refused.
136
+ const unusable = (v) => v === null ? "cannot be read" : isExactSemver(v) ? null : `(${JSON.stringify(v)}) is not a semver version`;
137
+ const oldVersion = deps.treeVersion(oldTree);
138
+ const oldBad = unusable(oldVersion);
139
+ if (oldBad) {
140
+ return (`${unit} serves ${oldTree}, whose flair version ${oldBad}, so flair cannot rule out that re-pointing would ` +
141
+ `downgrade the instance, and does not re-point it.${byHand(t, launcher)}`);
142
+ }
143
+ const cliBad = unusable(t.cliVersion);
144
+ if (cliBad) {
145
+ return (`this CLI's own flair version ${cliBad}, so flair cannot rule out that re-pointing ${unit} would downgrade ` +
146
+ `the instance, and does not re-point it.${byHand(t, launcher)}`);
147
+ }
148
+ if ((compareVersions(t.cliVersion, oldVersion) ?? -1) < 0) {
149
+ return (`${unit} serves flair ${oldVersion} from ${oldTree}; this CLI's tree has the older ${t.cliVersion}, so re-pointing ` +
150
+ "would downgrade the instance. Update this CLI's tree first (npm i -g @tpsdev-ai/flair), then re-run flair init.");
151
+ }
152
+ for (const p of [t.workingDirectory, t.harperBin, ...(t.launcher ? [t.launcher] : []), t.nodeBin]) {
153
+ if (!deps.exists(p)) {
154
+ return (`this CLI's tree is missing ${p}, so ${unit} cannot be re-pointed at it. Reinstall this CLI's tree ` +
155
+ "(npm i -g @tpsdev-ai/flair), then re-run flair init.");
156
+ }
157
+ }
158
+ return null;
159
+ }
160
+ // ─── launchd ──────────────────────────────────────────────────────────────
161
+ function keyCount(raw, key) {
162
+ return raw.split(`<key>${key}</key>`).length - 1;
163
+ }
164
+ /**
165
+ * Read a plist the way launchd would — as XML structure — or say why it is not
166
+ * the plain shape flair writes. REFUSED rather than interpreted: an XML
167
+ * declaration naming any encoding but UTF-8 (the bytes are read as UTF-8, so
168
+ * another declared encoding would be read wrongly), XML comments, CDATA,
169
+ * processing instructions after the declaration, a DOCTYPE with an internal
170
+ * subset, entity references beyond the five predefined ones, unsupported XML
171
+ * elements (the plist value elements are supported, including `real`, `date`
172
+ * and `data`, which flair does not write), text outside a value, duplicate keys
173
+ * in one dict, and anything after `</plist>`. Refusing comments (instead of skipping them) is what keeps
174
+ * the text rewrite below exact: with none, every literal `<key>…</key>` in the
175
+ * file is a real element, so the unique-key counts and the value splices
176
+ * address the same elements this reader placed.
177
+ */
178
+ export function readPlistStructure(raw) {
179
+ const TAG = /<(\/?)([A-Za-z]+)((?:\s+[A-Za-z]+="[^"<>&]*")*)\s*(\/?)>/y;
180
+ const TEXT = /[^<]*/y;
181
+ let i = raw.charCodeAt(0) === 0xfeff ? 1 : 0;
182
+ const fail = (why) => {
183
+ throw new Error(why);
184
+ };
185
+ const ws = () => {
186
+ while (i < raw.length && /\s/.test(raw[i]))
187
+ i++;
188
+ };
189
+ const tag = () => {
190
+ TAG.lastIndex = i;
191
+ const m = TAG.exec(raw);
192
+ if (!m)
193
+ fail(`unexpected content at offset ${i}`);
194
+ i = TAG.lastIndex;
195
+ return { close: m[1] === "/", name: m[2], attrs: m[3], empty: m[4] === "/" };
196
+ };
197
+ const text = () => {
198
+ TEXT.lastIndex = i;
199
+ const t = TEXT.exec(raw)[0];
200
+ i = TEXT.lastIndex;
201
+ if (/&(?!(?:amp|lt|gt|quot|apos);)/.test(t))
202
+ fail("an entity or character reference flair does not write");
203
+ return unescapeXml(t);
204
+ };
205
+ const end = (name) => {
206
+ const c = tag();
207
+ if (!c.close || c.name !== name || c.attrs !== "" || c.empty)
208
+ fail(`an unclosed <${name}>`);
209
+ };
210
+ const value = () => {
211
+ ws();
212
+ const o = tag();
213
+ if (o.close || o.attrs !== "")
214
+ fail(`an unexpected <${o.close ? "/" : ""}${o.name}>`);
215
+ switch (o.name) {
216
+ case "true":
217
+ case "false":
218
+ if (!o.empty)
219
+ end(o.name);
220
+ return { t: "scalar" };
221
+ case "string": {
222
+ if (o.empty)
223
+ return { t: "string", v: "" };
224
+ const v = text();
225
+ end("string");
226
+ return { t: "string", v };
227
+ }
228
+ case "integer":
229
+ case "real":
230
+ case "date":
231
+ case "data":
232
+ if (!o.empty) {
233
+ text();
234
+ end(o.name);
235
+ }
236
+ return { t: "scalar" };
237
+ case "array": {
238
+ const items = [];
239
+ if (o.empty)
240
+ return { t: "array", items };
241
+ for (;;) {
242
+ ws();
243
+ if (raw.startsWith("</array>", i)) {
244
+ i += "</array>".length;
245
+ return { t: "array", items };
246
+ }
247
+ items.push(value());
248
+ }
249
+ }
250
+ case "dict": {
251
+ const entries = new Map();
252
+ if (o.empty)
253
+ return { t: "dict", entries };
254
+ for (;;) {
255
+ ws();
256
+ if (raw.startsWith("</dict>", i)) {
257
+ i += "</dict>".length;
258
+ return { t: "dict", entries };
259
+ }
260
+ const k = tag();
261
+ if (k.close || k.name !== "key" || k.attrs !== "" || k.empty)
262
+ fail("a dict entry that does not start with <key>");
263
+ const key = text();
264
+ end("key");
265
+ if (entries.has(key))
266
+ fail(`the key ${JSON.stringify(key)} twice in one dict`);
267
+ entries.set(key, value());
268
+ }
269
+ }
270
+ default:
271
+ return fail(`an unsupported XML element <${o.name}>`);
272
+ }
273
+ };
274
+ try {
275
+ if (/<!--|<!\[CDATA\[/.test(raw))
276
+ fail("an XML comment or CDATA section");
277
+ ws();
278
+ if (raw.startsWith("<?xml", i)) {
279
+ const e = raw.indexOf("?>", i);
280
+ if (e < 0)
281
+ fail("an unterminated XML declaration");
282
+ // Absent, or UTF-8: the file's bytes are read as UTF-8.
283
+ const enc = /\sencoding\s*=\s*(["'])([^"']*)\1/.exec(raw.slice(i, e));
284
+ if (enc && enc[2].toLowerCase() !== "utf-8") {
285
+ fail(`an XML declaration of the encoding ${JSON.stringify(enc[2])} (only UTF-8 is read)`);
286
+ }
287
+ i = e + 2;
288
+ }
289
+ ws();
290
+ if (raw.startsWith("<!DOCTYPE", i)) {
291
+ const e = raw.indexOf(">", i);
292
+ if (e < 0 || raw.slice(i, e).includes("["))
293
+ fail("a DOCTYPE with an internal subset");
294
+ i = e + 1;
295
+ }
296
+ ws();
297
+ const root = tag();
298
+ if (root.close || root.name !== "plist" || root.empty)
299
+ fail("no <plist> root element");
300
+ const top = value();
301
+ if (top.t !== "dict")
302
+ fail("a <plist> whose value is not a dict");
303
+ ws();
304
+ end("plist");
305
+ ws();
306
+ if (i !== raw.length)
307
+ fail("content after </plist>");
308
+ return { top: top.entries };
309
+ }
310
+ catch (err) {
311
+ return { problem: err.message };
312
+ }
313
+ }
314
+ function plistString(v) {
315
+ return v?.t === "string" ? v.v : null;
316
+ }
317
+ /**
318
+ * Plan the re-point of an adopted pass-file plist. `raw` must be THIS
319
+ * instance's plist (see PlistOwnership) in the `buildLaunchdPlist` shape; see
320
+ * the module header for exactly what is checked and what is changed.
321
+ */
322
+ export function planPlistRuntimeRepoint(raw, t, deps, plistPath, owner) {
323
+ const unit = `the launchd plist ${plistPath}`;
324
+ const refuse = (what) => ({
325
+ kind: "refuse",
326
+ detail: `${unit} ${what}, so it is not re-pointed.${byHand(t, true)}`,
327
+ });
328
+ if (!t.launcher)
329
+ return { kind: "refuse", detail: "internal: no launcher path to write" };
330
+ // Read as structure: Label and the runtime keys in the top-level dict,
331
+ // ROOTPATH and HOME in its EnvironmentVariables dict.
332
+ const doc = readPlistStructure(raw);
333
+ if ("problem" in doc)
334
+ return refuse(`is not in the plain plist shape flair writes (it has ${doc.problem})`);
335
+ const top = doc.top;
336
+ const env = top.get("EnvironmentVariables");
337
+ if (env?.t !== "dict")
338
+ return refuse("has no EnvironmentVariables dict");
339
+ // One unambiguous declaration of each key this decision reads.
340
+ for (const key of ["Label", "ProgramArguments", "WorkingDirectory", "ROOTPATH", "HOME"]) {
341
+ if (keyCount(raw, key) !== 1)
342
+ return refuse(`does not declare exactly one ${key}`);
343
+ }
344
+ if (keyCount(raw, "Program") !== 0 || top.has("Program")) {
345
+ return refuse("declares a Program key, which launchd runs instead of ProgramArguments[0]");
346
+ }
347
+ const label = plistString(top.get("Label"));
348
+ if (label !== owner.label)
349
+ return refuse(`has the Label ${JSON.stringify(label)}, not this data directory's ${owner.label}`);
350
+ const rootPath = plistString(env.entries.get("ROOTPATH"));
351
+ if (rootPath === null || !deps.samePath(rootPath, owner.dataDir)) {
352
+ return refuse(`declares ROOTPATH ${JSON.stringify(rootPath)} in EnvironmentVariables, not this data directory ${owner.dataDir}`);
353
+ }
354
+ const home = plistString(env.entries.get("HOME"));
355
+ if (home === null || !deps.samePath(home, owner.home)) {
356
+ return refuse(`declares HOME ${JSON.stringify(home)} in EnvironmentVariables, not this user's home ${owner.home}`);
357
+ }
358
+ const parsedArgs = top.get("ProgramArguments");
359
+ const parsedWd = plistString(top.get("WorkingDirectory"));
360
+ const argsBlock = /(<key>ProgramArguments<\/key>\s*<array>)([\s\S]*?)(<\/array>)/.exec(raw);
361
+ const wd = /(<key>WorkingDirectory<\/key>\s*<string>)([^<]*)(<\/string>)/.exec(raw);
362
+ if (!argsBlock || !wd)
363
+ return refuse("does not have a ProgramArguments array and a WorkingDirectory string");
364
+ const inner = argsBlock[2];
365
+ const strings = [...inner.matchAll(/<string>([^<]*)<\/string>/g)];
366
+ if (strings.length !== 4 || inner.replace(/<string>[^<]*<\/string>/g, "").trim() !== "") {
367
+ return refuse("does not have the four-argument pass-file launcher ProgramArguments flair writes");
368
+ }
369
+ const args = strings.map((m) => unescapeXml(m[1]));
370
+ const oldTree = unescapeXml(wd[2]);
371
+ // The splice targets must be the very values the structure holds.
372
+ if (parsedArgs?.t !== "array" ||
373
+ parsedArgs.items.map((x) => plistString(x)).join("\u0000") !== args.join("\u0000") ||
374
+ parsedWd !== oldTree) {
375
+ return refuse("has a ProgramArguments or WorkingDirectory that is not a top-level value in the shape flair writes");
376
+ }
377
+ if (!isAbsolute(oldTree))
378
+ return refuse(`has a WorkingDirectory that is not an absolute path (${JSON.stringify(oldTree)})`);
379
+ if (relInTree(oldTree, args[0], deps) !== LAUNCHER_REL) {
380
+ return refuse(`runs ${args[0]} as its program, not ${LAUNCHER_REL} inside its WorkingDirectory ${oldTree}`);
381
+ }
382
+ if (!isAbsolute(args[1]) || !deps.samePath(args[1], owner.adminPassFile)) {
383
+ return refuse(`passes the admin-pass file ${args[1]}, not this instance's ${owner.adminPassFile}`);
384
+ }
385
+ if (!isNodeBinary(args[2]))
386
+ return refuse(`has ${args[2]} where the node binary goes`);
387
+ const harperRel = relInTree(oldTree, args[3], deps);
388
+ if (harperRel === null || !HARPER_ENTRY_REL.test(harperRel)) {
389
+ return refuse(`has ${args[3]} where the Harper entry inside its WorkingDirectory ${oldTree} goes`);
390
+ }
391
+ const targetBad = targetProblem(t, deps, true, false);
392
+ if (targetBad)
393
+ return { kind: "refuse", detail: `${unit} is not re-pointed: ${targetBad}${byHand(t, true)}` };
394
+ const current = { launcher: args[0], nodeBin: args[2], harperBin: args[3], workingDirectory: oldTree };
395
+ const next = { ...current };
396
+ const sameTree = deps.samePath(oldTree, t.workingDirectory);
397
+ if (sameTree) {
398
+ // Same tree: replace only what no longer exists; an existing different node is a deliberate pin.
399
+ if (!deps.exists(current.launcher))
400
+ next.launcher = t.launcher;
401
+ if (!deps.exists(current.harperBin))
402
+ next.harperBin = t.harperBin;
403
+ if (!deps.exists(current.nodeBin))
404
+ next.nodeBin = t.nodeBin;
405
+ }
406
+ else {
407
+ const refusal = treeGate(oldTree, t, deps, unit, true);
408
+ if (refusal)
409
+ return { kind: "refuse", detail: refusal };
410
+ next.launcher = t.launcher;
411
+ next.nodeBin = t.nodeBin;
412
+ next.harperBin = t.harperBin;
413
+ next.workingDirectory = t.workingDirectory;
414
+ }
415
+ const changes = [];
416
+ if (next.launcher !== current.launcher)
417
+ changes.push({ field: "launcher", from: current.launcher, to: next.launcher });
418
+ if (next.nodeBin !== current.nodeBin)
419
+ changes.push({ field: "node", from: current.nodeBin, to: next.nodeBin });
420
+ if (next.harperBin !== current.harperBin)
421
+ changes.push({ field: "Harper entry", from: current.harperBin, to: next.harperBin });
422
+ if (next.workingDirectory !== current.workingDirectory) {
423
+ changes.push({ field: "WorkingDirectory", from: current.workingDirectory, to: next.workingDirectory });
424
+ }
425
+ if (changes.length === 0) {
426
+ if (sameTree && deps.canonical(current.nodeBin) !== deps.canonical(t.nodeBin)) {
427
+ return {
428
+ kind: "pinned-node",
429
+ unitNodeBin: current.nodeBin,
430
+ detail: `${unit} serves this CLI's tree with node ${current.nodeBin} (this CLI runs ${t.nodeBin}); a deliberate ` +
431
+ `runtime pin is left as it is. To move it, change that node path to ${t.nodeBin} by hand, then run: flair restart`,
432
+ };
433
+ }
434
+ return { kind: "current", detail: `${unit} already serves this CLI's tree.` };
435
+ }
436
+ // Rebuild the array by index, keeping every byte between the strings.
437
+ const nextArgs = [next.launcher, args[1], next.nodeBin, next.harperBin];
438
+ let i = 0;
439
+ const nextInner = inner.replace(/<string>[^<]*<\/string>/g, (m) => {
440
+ const idx = i++;
441
+ return nextArgs[idx] === args[idx] ? m : `<string>${escapeXml(nextArgs[idx])}</string>`;
442
+ });
443
+ let text = raw.slice(0, argsBlock.index) + argsBlock[1] + nextInner + argsBlock[3] + raw.slice(argsBlock.index + argsBlock[0].length);
444
+ if (next.workingDirectory !== current.workingDirectory) {
445
+ const wd2 = /(<key>WorkingDirectory<\/key>\s*<string>)([^<]*)(<\/string>)/.exec(text);
446
+ text =
447
+ text.slice(0, wd2.index) + wd2[1] + escapeXml(next.workingDirectory) + wd2[3] + text.slice(wd2.index + wd2[0].length);
448
+ }
449
+ return { kind: "repoint", text, changes, detail: `re-pointed ${unit} (${describeChanges(changes)})` };
450
+ }
451
+ // ─── systemd (Linux user unit) ────────────────────────────────────────────
452
+ /**
453
+ * Plan the re-point of the systemd USER unit proven to own the serving process.
454
+ * `oldTree` is the tree the unit serves now. The whole supported shape is
455
+ * validated FIRST — before any `current`, `pinned-node` or `repoint` answer —
456
+ * and only the runtime operands, identified by their role, are replaced.
457
+ */
458
+ export function planSystemdUnitRuntimeRepoint(text, oldTree, t, deps, unitPath) {
459
+ const unit = `the systemd user unit ${unitPath}`;
460
+ let launcherShape = false;
461
+ const refuse = (what) => ({
462
+ kind: "refuse",
463
+ detail: `${unit} ${what}, so it is not re-pointed.${byHand(t, launcherShape)}`,
464
+ });
465
+ const lines = text.split("\n");
466
+ let section = "";
467
+ const wdIdx = [];
468
+ const execIdx = [];
469
+ for (let i = 0; i < lines.length; i++) {
470
+ const line = lines[i].replace(/\r$/, "");
471
+ const trimmed = line.trim();
472
+ if (trimmed === "" || trimmed.startsWith("#") || trimmed.startsWith(";"))
473
+ continue;
474
+ if (trimmed.startsWith("[")) {
475
+ section = trimmed.slice(1).replace(/\].*$/, "").trim().toLowerCase();
476
+ continue;
477
+ }
478
+ if (section !== "service")
479
+ continue;
480
+ if (/\\$/.test(line))
481
+ return refuse("uses a line continuation in [Service]");
482
+ const key = trimmed.slice(0, Math.max(0, trimmed.indexOf("="))).trim();
483
+ if (key === "WorkingDirectory")
484
+ wdIdx.push(i);
485
+ if (key === "ExecStart")
486
+ execIdx.push(i);
487
+ }
488
+ if (wdIdx.length !== 1 || execIdx.length !== 1) {
489
+ return refuse("does not have exactly one WorkingDirectory= and one ExecStart= in [Service]");
490
+ }
491
+ // WorkingDirectory=[-]<the tree it serves>
492
+ const wdLine = lines[wdIdx[0]];
493
+ const wdm = /^(\s*WorkingDirectory\s*=\s*)(-?)(\S+)(\s*)$/.exec(wdLine.replace(/\r$/, ""));
494
+ if (!wdm || !SYSTEMD_SAFE_PATH.test(wdm[3]) || !deps.samePath(wdm[3], oldTree)) {
495
+ return refuse(`has a WorkingDirectory= that is not the plain path of the tree it serves (${oldTree})`);
496
+ }
497
+ // ExecStart=[-]<one of the two supported argv shapes>
498
+ const execLine = lines[execIdx[0]];
499
+ const em = /^(\s*ExecStart\s*=\s*)([-@:+!]*)(.*?)(\s*)$/.exec(execLine.replace(/\r$/, ""));
500
+ if (!em)
501
+ return refuse("has an ExecStart= that could not be read");
502
+ if (em[2] !== "" && em[2] !== "-")
503
+ return refuse(`uses the ExecStart= prefix ${JSON.stringify(em[2])} (only "-" is supported)`);
504
+ const parts = em[3].split(/(\s+)/);
505
+ const words = parts.filter((_, idx) => idx % 2 === 0);
506
+ if (words.some((w) => w === "" || !SYSTEMD_SAFE_WORD.test(w))) {
507
+ return refuse("has an ExecStart= with quoting, a specifier, a variable or another character flair does not interpret");
508
+ }
509
+ const roles = words.length === 4 && words[2] === "run" && words[3] === "."
510
+ ? { node: 0, harper: 1 }
511
+ : words.length === 4 && basename(words[0]) === LAUNCHER_BASENAME
512
+ ? { launcher: 0, passFile: 1, node: 2, harper: 3 }
513
+ : null;
514
+ if (!roles) {
515
+ return refuse("has an ExecStart= that is neither `<node> <harper.js> run .` nor " +
516
+ "`<tree>/templates/launchd/start-flair-with-admin-pass.sh <admin-pass file> <node> <harper.js>`");
517
+ }
518
+ launcherShape = roles.launcher !== undefined;
519
+ const oldNode = words[roles.node];
520
+ const oldHarper = words[roles.harper];
521
+ if (!isNodeBinary(oldNode))
522
+ return refuse(`has ${oldNode} where the node binary goes`);
523
+ const harperRel = relInTree(oldTree, oldHarper, deps);
524
+ if (harperRel === null || !HARPER_ENTRY_REL.test(harperRel)) {
525
+ return refuse(`has ${oldHarper} where the Harper entry inside ${oldTree} goes`);
526
+ }
527
+ if (roles.launcher !== undefined && relInTree(oldTree, words[roles.launcher], deps) !== LAUNCHER_REL) {
528
+ return refuse(`runs ${words[roles.launcher]} instead of ${LAUNCHER_REL} inside ${oldTree}`);
529
+ }
530
+ if (roles.passFile !== undefined && !isAbsolute(words[roles.passFile])) {
531
+ return refuse(`passes an admin-pass file that is not an absolute path (${words[roles.passFile]})`);
532
+ }
533
+ const targetBad = targetProblem(t, deps, launcherShape, true);
534
+ if (targetBad)
535
+ return { kind: "refuse", detail: `${unit} is not re-pointed: ${targetBad}${byHand(t, launcherShape)}` };
536
+ // Only now, with the whole shape validated: is it already this CLI's tree?
537
+ if (deps.samePath(oldTree, t.workingDirectory)) {
538
+ const runtime = [oldNode, oldHarper, ...(roles.launcher !== undefined ? [words[roles.launcher]] : [])];
539
+ const missing = runtime.filter((p) => !deps.exists(p));
540
+ if (missing.length > 0) {
541
+ return refuse(`serves this CLI's tree but names ${missing.join(", ")}, which does not exist`);
542
+ }
543
+ if (deps.canonical(oldNode) !== deps.canonical(t.nodeBin)) {
544
+ return {
545
+ kind: "pinned-node",
546
+ unitNodeBin: oldNode,
547
+ detail: `${unit} serves this CLI's tree with node ${oldNode} (this CLI runs ${t.nodeBin}); a deliberate runtime pin ` +
548
+ `is left as it is. To move it, change that node path to ${t.nodeBin} by hand, then run: flair restart`,
549
+ };
550
+ }
551
+ return { kind: "current", detail: `${unit} already serves this CLI's tree.` };
552
+ }
553
+ const refusal = treeGate(oldTree, t, deps, unit, launcherShape);
554
+ if (refusal)
555
+ return { kind: "refuse", detail: refusal };
556
+ const changes = [];
557
+ const set = (role, to, field) => {
558
+ const from = words[role];
559
+ if (from === to)
560
+ return;
561
+ parts[role * 2] = to;
562
+ changes.push({ field, from, to });
563
+ };
564
+ if (roles.launcher !== undefined)
565
+ set(roles.launcher, t.launcher, "launcher");
566
+ if (deps.canonical(oldNode) !== deps.canonical(t.nodeBin))
567
+ set(roles.node, t.nodeBin, "node");
568
+ set(roles.harper, t.harperBin, "Harper entry");
569
+ const cr = (l) => (l.endsWith("\r") ? "\r" : "");
570
+ const next = [...lines];
571
+ next[wdIdx[0]] = `${wdm[1]}${wdm[2]}${t.workingDirectory}${wdm[4]}${cr(wdLine)}`;
572
+ changes.push({ field: "WorkingDirectory", from: wdm[3], to: t.workingDirectory });
573
+ next[execIdx[0]] = `${em[1]}${em[2]}${parts.join("")}${em[4]}${cr(execLine)}`;
574
+ return { kind: "repoint", text: next.join("\n"), changes, detail: `re-pointed ${unit} (${describeChanges(changes)})` };
575
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Read a TOML string array at `start`. Supports basic/literal strings, their
3
+ * multiline forms, escapes, comments and trailing commas. This is deliberately
4
+ * a value reader, not a table parser: callers establish the owning table and
5
+ * reject duplicate keys/fences outside the captured value before writing.
6
+ */
7
+ export function readTomlStringArray(text, start) {
8
+ let i = start;
9
+ function trivia() {
10
+ for (;;) {
11
+ while (/[ \t\r\n]/.test(text[i] ?? "!"))
12
+ i++;
13
+ if (text[i] !== "#")
14
+ return;
15
+ while (i < text.length && text[i] !== "\n")
16
+ i++;
17
+ }
18
+ }
19
+ function string() {
20
+ const start = i;
21
+ const q = text[i];
22
+ if (q !== '"' && q !== "'")
23
+ return null;
24
+ const multiline = text.startsWith(q.repeat(3), i);
25
+ const quote = q.repeat(multiline ? 3 : 1);
26
+ i += quote.length;
27
+ if (multiline) {
28
+ if (text.startsWith("\r\n", i))
29
+ i += 2;
30
+ else if (text[i] === "\n")
31
+ i++;
32
+ }
33
+ let value = "";
34
+ while (i < text.length) {
35
+ if (text.startsWith(quote, i)) {
36
+ i += quote.length;
37
+ // TOML permits one or two quote characters just before a multiline
38
+ // closing delimiter (four/five consecutive quotes).
39
+ if (multiline) {
40
+ for (let n = 0; n < 2 && text[i] === q; n++, i++)
41
+ value += q;
42
+ }
43
+ return { value, start, end: i, quote };
44
+ }
45
+ const ch = text[i++];
46
+ if (ch === "\\" && q === '"') {
47
+ if (multiline && /^[ \t]*(?:\r?\n)/.test(text.slice(i))) {
48
+ while (/[ \t\r\n]/.test(text[i] ?? "!"))
49
+ i++;
50
+ continue;
51
+ }
52
+ const escape = text[i++];
53
+ const simple = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" };
54
+ if (escape !== undefined && simple[escape] !== undefined)
55
+ value += simple[escape];
56
+ else if (escape === "u" || escape === "U") {
57
+ const length = escape === "u" ? 4 : 8;
58
+ const hex = text.slice(i, i + length);
59
+ if (hex.length !== length || !/^[0-9a-f]+$/i.test(hex))
60
+ return null;
61
+ const code = Number.parseInt(hex, 16);
62
+ if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))
63
+ return null;
64
+ value += String.fromCodePoint(code);
65
+ i += length;
66
+ }
67
+ else
68
+ return null;
69
+ }
70
+ else if (ch === "\r" && multiline && text[i] === "\n") {
71
+ value += "\n";
72
+ i++;
73
+ }
74
+ else {
75
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(ch) || (!multiline && ch === "\n"))
76
+ return null;
77
+ value += ch;
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ trivia();
83
+ if (text[i++] !== "[")
84
+ return null;
85
+ const values = [];
86
+ trivia();
87
+ while (text[i] !== "]") {
88
+ const value = string();
89
+ if (!value)
90
+ return null;
91
+ values.push(value);
92
+ trivia();
93
+ if (text[i] === "]")
94
+ break;
95
+ if (text[i++] !== ",")
96
+ return null;
97
+ trivia();
98
+ }
99
+ i++;
100
+ // No second value or command can trail the array on its assignment line.
101
+ if (!/^[ \t]*(?:#.*)?(?:\r?\n|$)/.test(text.slice(i)))
102
+ return null;
103
+ return { values, end: i };
104
+ }