@tpsdev-ai/flair 0.54.2 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
@@ -1,16 +1,39 @@
1
1
  /**
2
- * Owner stamp for harness scratch directories (flair#1032).
2
+ * Owner stamp for harness scratch directories (flair#1032 / flair#1372).
3
3
  *
4
4
  * Directory mtime is not a liveness signal: on Linux, appending to files
5
5
  * inside subdirectories does not update the parent. The stamp records the
6
- * creating process; a sweep may delete a tree only when that process is gone
7
- * (and, for Harper trees, when `hdb.pid` is gone too).
6
+ * creating process *and* its start time; a sweep may treat a tree as live
7
+ * only when that pid is still alive AND the live start time matches the
8
+ * stamp. A recycled pid therefore fails closed (dead), never "live forever".
9
+ *
10
+ * Harper identity (Kern A1) is the same model: `harperPid` + `harperStartedAt`.
11
+ * Start-time matching reuses `daemon-liveness` (`isStartTimeMatch`, ±2s) and
12
+ * `readProcessStartTimeMs` — no second parser.
13
+ *
14
+ * Invariant: a start-time **mismatch** verdict (`already-gone`) removes the
15
+ * tree and may leave a still-live process whose identity did not match —
16
+ * correct for pid recycling. That is safe only because the shared reader is
17
+ * zone-stable (darwin self-calibrates `ps lstart` against this process). A
18
+ * TZ-skewed parse that looked like a mismatch would delete the stamp and
19
+ * hide a real orphan from the next sweep (Kern #1708).
8
20
  */
9
21
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
22
  import { join } from "node:path";
23
+ import { isStartTimeMatch } from "./daemon-liveness.js";
24
+ import { readProcessStartTimeMs } from "./process-start-time.js";
11
25
  export const SCRATCH_OWNER_FILE = ".flair-scratch-owner";
12
- export function writeScratchOwnerStamp(dir, pid = process.pid) {
13
- writeFileSync(join(dir, SCRATCH_OWNER_FILE), `${pid}\n`, { encoding: "utf-8" });
26
+ export function writeScratchOwnerStamp(dir, stamp = {}) {
27
+ const ownerPid = stamp.ownerPid ?? process.pid;
28
+ const ownerStartedAt = stamp.ownerStartedAt ?? readProcessStartTimeMs(ownerPid) ?? undefined;
29
+ const rec = { ownerPid };
30
+ if (ownerStartedAt != null)
31
+ rec.ownerStartedAt = ownerStartedAt;
32
+ if (stamp.harperPid != null)
33
+ rec.harperPid = stamp.harperPid;
34
+ if (stamp.harperStartedAt != null)
35
+ rec.harperStartedAt = stamp.harperStartedAt;
36
+ writeFileSync(join(dir, SCRATCH_OWNER_FILE), `${JSON.stringify(rec)}\n`, { encoding: "utf-8" });
14
37
  }
15
38
  export function isPidAlive(pid) {
16
39
  if (!Number.isInteger(pid) || pid <= 0)
@@ -32,18 +55,109 @@ function readPidFile(path) {
32
55
  return null;
33
56
  }
34
57
  }
58
+ function parseScratchOwnerStamp(content) {
59
+ const trimmed = content.trim();
60
+ if (!trimmed)
61
+ return null;
62
+ if (trimmed.startsWith("{")) {
63
+ try {
64
+ const obj = JSON.parse(trimmed);
65
+ const ownerPid = Number(obj.ownerPid);
66
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0)
67
+ return null;
68
+ const stamp = { ownerPid };
69
+ const ownerStartedAt = Number(obj.ownerStartedAt);
70
+ if (Number.isFinite(ownerStartedAt))
71
+ stamp.ownerStartedAt = ownerStartedAt;
72
+ const harperPid = Number(obj.harperPid);
73
+ if (Number.isInteger(harperPid) && harperPid > 0)
74
+ stamp.harperPid = harperPid;
75
+ const harperStartedAt = Number(obj.harperStartedAt);
76
+ if (Number.isFinite(harperStartedAt))
77
+ stamp.harperStartedAt = harperStartedAt;
78
+ return stamp;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ // Legacy pid-only stamp. No started-at → cannot verify identity.
85
+ const pid = Number(trimmed);
86
+ if (Number.isInteger(pid) && pid > 0)
87
+ return { ownerPid: pid };
88
+ return null;
89
+ }
90
+ export function readScratchOwnerStamp(dir) {
91
+ try {
92
+ return parseScratchOwnerStamp(readFileSync(join(dir, SCRATCH_OWNER_FILE), "utf-8"));
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
35
98
  export function readScratchOwnerPid(dir) {
36
- return readPidFile(join(dir, SCRATCH_OWNER_FILE));
99
+ return readScratchOwnerStamp(dir)?.ownerPid ?? null;
37
100
  }
38
101
  export function hasScratchOwnerStamp(dir) {
39
102
  return existsSync(join(dir, SCRATCH_OWNER_FILE));
40
103
  }
41
- /** True when the creating process is still alive. Unreadable stamp → not live. */
104
+ export function readHdbPid(dir) {
105
+ return readPidFile(join(dir, "hdb.pid"));
106
+ }
107
+ function pidMatchesStamp(pid, recordedStartedAt) {
108
+ if (recordedStartedAt == null)
109
+ return false;
110
+ const actual = readProcessStartTimeMs(pid);
111
+ if (actual == null)
112
+ return false;
113
+ return isStartTimeMatch(actual, recordedStartedAt);
114
+ }
115
+ /** True when the creating process is still alive AND its start time matches. */
42
116
  export function scratchOwnerIsLive(dir) {
43
- const pid = readScratchOwnerPid(dir);
44
- return pid !== null && isPidAlive(pid);
117
+ const stamp = readScratchOwnerStamp(dir);
118
+ if (!stamp || !isPidAlive(stamp.ownerPid))
119
+ return false;
120
+ return pidMatchesStamp(stamp.ownerPid, stamp.ownerStartedAt);
45
121
  }
46
122
  export function hdbPidIsLive(dir) {
47
- const pid = readPidFile(join(dir, "hdb.pid"));
123
+ const pid = readHdbPid(dir);
48
124
  return pid !== null && isPidAlive(pid);
49
125
  }
126
+ /**
127
+ * Whether a dead-owner tree's Harper pid may be killed.
128
+ *
129
+ * Kill only when `hdb.pid` (or stamped `harperPid`) is alive AND its start
130
+ * time matches `harperStartedAt`. A mismatch is already-gone (the original
131
+ * Harper is not that pid): the tree is removed and a live mismatched-identity
132
+ * process is left alone — correct for pid recycling, and safe only because
133
+ * the start-time reader is zone-stable. Disagreement between the two names,
134
+ * or a stampless tree with a live `hdb.pid`, is unverified — fail closed.
135
+ */
136
+ export function classifyOrphanHarperKill(dir) {
137
+ const stamp = readScratchOwnerStamp(dir);
138
+ const hdbPid = readHdbPid(dir);
139
+ if (!stamp) {
140
+ if (hdbPid !== null && isPidAlive(hdbPid)) {
141
+ return { kind: "unverified", reason: "stampless tree with live hdb.pid" };
142
+ }
143
+ return { kind: "already-gone" };
144
+ }
145
+ if (hdbPid !== null && stamp.harperPid != null && hdbPid !== stamp.harperPid) {
146
+ return { kind: "pid-disagreement", hdbPid, harperPid: stamp.harperPid };
147
+ }
148
+ const target = hdbPid ?? stamp.harperPid ?? null;
149
+ if (target === null || !isPidAlive(target)) {
150
+ return { kind: "already-gone" };
151
+ }
152
+ if (stamp.harperStartedAt == null) {
153
+ return { kind: "unverified", reason: "stamp has no harperStartedAt" };
154
+ }
155
+ const actual = readProcessStartTimeMs(target);
156
+ if (actual === null) {
157
+ return { kind: "unverified", reason: `could not read the start time of pid ${target}` };
158
+ }
159
+ if (!isStartTimeMatch(actual, stamp.harperStartedAt)) {
160
+ return { kind: "already-gone" };
161
+ }
162
+ return { kind: "kill", pid: target, startedAt: stamp.harperStartedAt };
163
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * stale-client-pin.ts — flair#1383
3
+ *
4
+ * `flair doctor` reads the actual `flair-mcp` / `flair-client` pins in
5
+ * wired host configs and cwd package.json. A pre-0.18.0 pin is not just
6
+ * "behind the CLI" — it silently drops writes, including against another
7
+ * agent's shared memories, and upgrading the *server* does not fix it.
8
+ *
9
+ * This helper is the loud, specific finding. Threshold matches
10
+ * `resources/client-version-gate.ts` (`MIN_SAFE_FLAIR_CLIENT`). Duplicated
11
+ * here because the CLI must not import server resources.
12
+ */
13
+ import { parseSemverCore, semverGte } from "../fabric-upgrade.js";
14
+ export const MIN_SAFE_FLAIR_ADAPTER = "0.18.0";
15
+ export const STALE_CLIENT_WRITE_HAZARD = "this adapter silently drops writes (including against another agent's shared memories). Upgrade the adapter, not the server";
16
+ /** True when `pin` is parseable and strictly older than 0.18.0. */
17
+ export function isUnsafeAdapterPin(pin) {
18
+ if (!pin)
19
+ return false;
20
+ if (!parseSemverCore(pin))
21
+ return false;
22
+ return !semverGte(pin, MIN_SAFE_FLAIR_ADAPTER);
23
+ }
24
+ export function unsafeAdapterPinDetail(surface, id, pin, pkg = "flair-mcp") {
25
+ return `${surface} (${id}): pinned to ${pkg}@${pin} — ${STALE_CLIENT_WRITE_HAZARD}`;
26
+ }
@@ -17,8 +17,8 @@
17
17
  * (b) — the exec-path mismatch warning — already shipped in #1560
18
18
  * (`upgrade-exec-path.ts`). This file does not change that wording.
19
19
  */
20
- import { existsSync, mkdirSync, renameSync, rmSync, cpSync, readdirSync, readFileSync, statSync, lstatSync, } from "node:fs";
21
- import { basename, dirname, join } from "node:path";
20
+ import { existsSync, mkdirSync, renameSync, rmSync, cpSync, readdirSync, readFileSync, statSync, lstatSync, realpathSync, } from "node:fs";
21
+ import { basename, dirname, join, resolve } from "node:path";
22
22
  import { homedir } from "node:os";
23
23
  import { execFileSync } from "node:child_process";
24
24
  import { extract as tarExtract } from "tar";
@@ -227,61 +227,302 @@ export function formatPlainTreePlan(plan) {
227
227
  function formatUnitRef(u) {
228
228
  return `${u.name} (${u.scope}: ${u.path})`;
229
229
  }
230
+ // ─── unit path operands (flair#1758) ────────────────────────────────────────
231
+ //
232
+ // Discovery compares the tree against the PATHS A UNIT ACTUALLY USES, not
233
+ // against arbitrary text. The original matcher scanned the whole file with only
234
+ // a trailing-boundary check, so a canonical path inside a COMMENT matched, and
235
+ // any unrelated value that merely CONTAINED the tree path matched too. Because
236
+ // the caller already canonicalizes the tree (readFlairPackageAt →
237
+ // canonicalPath), the "also try canonicalPath(treeDir)" variant here was dead
238
+ // code: the operand that needs resolving is the one read out of the unit file,
239
+ // not the tree.
240
+ //
241
+ // So: extract operands from ACTIVE `[Service]` `WorkingDirectory` and
242
+ // `ExecStart` directives, then compare canonical-to-canonical.
243
+ //
244
+ // - `WorkingDirectory` is a directory: its resolved path must EQUAL the tree.
245
+ // - `ExecStart` operands are executables/scripts/arguments: keep the original
246
+ // tree-DESCENDANT intent, on PATH-COMPONENT boundaries (so `/opt/flair-spoke`
247
+ // is not "inside" `/opt/flair`).
248
+ //
249
+ // Explicitly NOT done: the whole command line is never canonicalized as one
250
+ // string; quoted values are tokenized with systemd quoting rules rather than
251
+ // split on whitespace; and an operand carrying a systemd specifier (`%i`, `%n`)
252
+ // or a shell variable (`$VAR`) is not a literal host path, so it is skipped
253
+ // rather than matched.
254
+ //
255
+ // KNOWN LIMIT — `RootDirectory=`, `RootImage=` and service-specific bind mounts
256
+ // mean a unit can see DIFFERENT content at the same host pathname, so host
257
+ // `realpath` is not proof of service identity. Automatic matching stays scoped
258
+ // to host-path semantics; `FLAIR_SYSTEMD_UNIT` remains the escape hatch for
259
+ // namespaced configurations.
260
+ /** True when `child` is `root` itself or a path-component descendant of it. */
261
+ function isPathInside(child, root) {
262
+ if (child === root)
263
+ return true;
264
+ return child.startsWith(root.endsWith("/") ? root : `${root}/`);
265
+ }
266
+ /** Strip a leading systemd ExecStart/WorkingDirectory prefix (`-`, `@`, `+`, `!`, `:`). */
267
+ function stripSystemdExecPrefix(word) {
268
+ let i = 0;
269
+ while (i < word.length && "-@+!:".includes(word[i]))
270
+ i++;
271
+ return word.slice(i);
272
+ }
230
273
  /**
231
- * After a directory path, the next character must not continue the last
232
- * path segment. `/opt/flair` matches `WorkingDirectory=/opt/flair`,
233
- * `/opt/flair/`, and `/opt/flair/dist/cli.js` — not `/opt/flair-spoke`.
274
+ * Canonicalize a path even when its leaf — or a middle segment — does not
275
+ * exist, by realpath-ing the deepest EXISTING ancestor and re-appending the
276
+ * remainder.
277
+ *
278
+ * `canonicalPath` alone is not enough: `realpathSync("/opt/flair/flair")`
279
+ * throws when that file is absent, and its fallback returns the LEXICAL path,
280
+ * so a symlinked `/opt/flair` would never resolve for a unit naming a file
281
+ * inside it. Resolving the ancestor is what makes the unit operand and the tree
282
+ * comparable.
234
283
  *
235
- * String scan, not `new RegExp(variable)` — Semgrep
236
- * `detect-non-literal-regexp` (same reason `readHarperConfig` parses YAML
237
- * instead of interpolating a key into a regex).
284
+ * Only ABSOLUTE host paths are canonicalized — a relative operand is not a path
285
+ * into the tree. Returns null for anything that is not a literal host path
286
+ * (relative, or containing an unresolved `%`/`$`).
238
287
  */
239
- function isDirPathBoundary(next) {
240
- if (next === undefined)
241
- return true;
242
- switch (next) {
243
- case "/":
244
- case "\\":
245
- case "\"":
246
- case "'":
247
- case "=":
248
- case ":":
249
- case " ":
250
- case "\t":
251
- case "\n":
252
- case "\r":
253
- case "\f":
254
- case "\v":
255
- return true;
256
- default:
257
- return false;
288
+ function canonicalizeOperand(rawPath) {
289
+ const raw = rawPath.trim();
290
+ if (!raw.startsWith("/"))
291
+ return null;
292
+ if (raw.includes("%") || raw.includes("$"))
293
+ return null;
294
+ const abs = resolve(raw);
295
+ let cur = abs;
296
+ const tail = [];
297
+ for (;;) {
298
+ // `existsSync` is the STRICT check in both runtimes; gate `realpathSync` on
299
+ // it. Bun's `realpathSync` is lenient — for a path ending in a literal
300
+ // backslash it silently drops the backslash and returns the canonical dir,
301
+ // where Node throws ENOENT — so relying on `realpathSync` alone makes the
302
+ // matcher depend on the runtime (production ships Node, tests run Bun).
303
+ // With the gate, a backslash operand falls through to the ancestor walk on
304
+ // both, yielding `path + "\\"` (≠ the tree).
305
+ if (existsSync(cur)) {
306
+ let real = cur;
307
+ try {
308
+ real = realpathSync(cur);
309
+ }
310
+ catch { /* unreadable — fall back to the existing lexical prefix */ }
311
+ return tail.length > 0 ? join(real, ...tail.reverse()) : real;
312
+ }
313
+ const parent = dirname(cur);
314
+ if (parent === cur)
315
+ return abs; // nothing on this path exists — lexical
316
+ tail.push(basename(cur));
317
+ cur = parent;
258
318
  }
259
319
  }
260
- function textMentionsDir(text, dir) {
261
- let from = 0;
262
- while (from <= text.length) {
263
- const i = text.indexOf(dir, from);
264
- if (i < 0)
265
- return false;
266
- if (isDirPathBoundary(text[i + dir.length]))
267
- return true;
268
- from = i + 1;
320
+ /**
321
+ * Tokenize a systemd directive value the way systemd splits ExecStart /
322
+ * WorkingDirectory: whitespace-separated words, single quotes literal, double
323
+ * quotes literal except for `\"`, `\\`, `\$`, and backslash escaping outside
324
+ * quotes. No variable/specifier expansion — callers treat those as non-paths.
325
+ */
326
+ function splitSystemdWords(value) {
327
+ const words = [];
328
+ let cur = "";
329
+ let started = false;
330
+ let inSingle = false;
331
+ let inDouble = false;
332
+ for (let i = 0; i < value.length; i++) {
333
+ const ch = value[i];
334
+ if (inSingle) {
335
+ if (ch === "'")
336
+ inSingle = false;
337
+ else
338
+ cur += ch;
339
+ started = true;
340
+ continue;
341
+ }
342
+ if (inDouble) {
343
+ if (ch === "\\" && i + 1 < value.length && "\"\\$".includes(value[i + 1])) {
344
+ cur += value[++i];
345
+ started = true;
346
+ continue;
347
+ }
348
+ if (ch === "\"")
349
+ inDouble = false;
350
+ else
351
+ cur += ch;
352
+ started = true;
353
+ continue;
354
+ }
355
+ if (ch === "'") {
356
+ inSingle = true;
357
+ started = true;
358
+ continue;
359
+ }
360
+ if (ch === "\"") {
361
+ inDouble = true;
362
+ started = true;
363
+ continue;
364
+ }
365
+ if (ch === "\\" && i + 1 < value.length) {
366
+ cur += value[++i];
367
+ started = true;
368
+ continue;
369
+ }
370
+ if (ch === " " || ch === "\t") {
371
+ if (started) {
372
+ words.push(cur);
373
+ cur = "";
374
+ started = false;
375
+ }
376
+ continue;
377
+ }
378
+ cur += ch;
379
+ started = true;
269
380
  }
270
- return false;
381
+ if (started)
382
+ words.push(cur);
383
+ return words;
384
+ }
385
+ /**
386
+ * True when `line` ends in an unescaped backslash — systemd's continuation
387
+ * marker. Counts the run of trailing backslashes so an escaped `\\` is not
388
+ * treated as a continuation.
389
+ */
390
+ function endsWithUnescapedBackslash(line) {
391
+ const stripped = line.replace(/[ \t]+$/, "");
392
+ let n = 0;
393
+ for (let i = stripped.length - 1; i >= 0 && stripped[i] === "\\"; i--)
394
+ n++;
395
+ return n % 2 === 1;
396
+ }
397
+ /**
398
+ * Fold systemd line continuations into logical lines before parsing: a physical
399
+ * line ending in an unescaped backslash joins the next line (the backslash and
400
+ * the newline become a single space). Folding first means a directive whose
401
+ * value lands on the continuation line is still read as one directive —
402
+ * otherwise it looks like an empty (reset) assignment.
403
+ *
404
+ * Comment lines (`#`/`;`) are dropped BEFORE the continuation logic, matching
405
+ * systemd's `config_parse()` (`src/shared/conf-parser.c:358` skips a comment at
406
+ * the top of the loop and does NOT touch the pending `continuation`;
407
+ * `:372-401` appends only after that check; `:432` parses a leftover
408
+ * continuation at EOF). A comment block after a backslash-continued line is
409
+ * therefore IGNORED, and the continuation joins whatever follows it —
410
+ * `systemd.syntax(7)`:
411
+ * KeyThree=value 3\
412
+ * # this line is ignored
413
+ * ; this line is ignored too
414
+ * value 3 continued -> KeyThree=value 3 value 3 continued
415
+ */
416
+ function foldSystemdContinuations(unitText) {
417
+ const logical = [];
418
+ let acc = "";
419
+ let accumulating = false;
420
+ for (const raw of unitText.split(/\r?\n/)) {
421
+ // Comments first: systemd skips them before continuation handling, so a
422
+ // comment line must not terminate (or be flushed into) a pending fold.
423
+ if (raw.trimStart().startsWith("#") || raw.trimStart().startsWith(";"))
424
+ continue;
425
+ const line = accumulating ? raw.replace(/^[ \t]+/, "") : raw;
426
+ if (endsWithUnescapedBackslash(line)) {
427
+ acc += line.replace(/[ \t]+$/, "").slice(0, -1) + " ";
428
+ accumulating = true;
429
+ continue;
430
+ }
431
+ if (accumulating) {
432
+ logical.push(acc + line);
433
+ acc = "";
434
+ accumulating = false;
435
+ }
436
+ else {
437
+ logical.push(line);
438
+ }
439
+ }
440
+ if (accumulating)
441
+ logical.push(acc);
442
+ return logical;
443
+ }
444
+ /**
445
+ * The values of every active `key` directive inside `[Service]`. systemd's
446
+ * RESET semantics are honoured: a blank value (`WorkingDirectory=` /
447
+ * `ExecStart=`) clears the values collected so far for that key, and later
448
+ * non-blank values accumulate again. Comments, directives in other sections,
449
+ * and continued lines (folded first) are handled.
450
+ *
451
+ * Directive names are case-SENSITIVE. `config_item_table_lookup` matches with
452
+ * `streq` (`src/shared/conf-parser.c:67`) and the gperf table carries no
453
+ * `%ignore-case` (`src/core/load-fragment-gperf.gperf.in`), so a mis-cased key
454
+ * (e.g. `workingdirectory=`) is logged as "Unknown key … ignoring" and has NO
455
+ * effect. Matching it here would select a unit systemd does not configure.
456
+ *
457
+ * `opts.single` selects the storage rule for the key. systemd treats
458
+ * `WorkingDirectory` as SINGLE-valued (`config_parse_working_directory` does
459
+ * `free_and_replace`, so the LAST non-blank assignment wins) but `ExecStart` as
460
+ * a genuine LIST whose assignments accumulate. Sharing this scanner — rather
461
+ * than a second reader — keeps reset/continuation/comment handling identical.
462
+ */
463
+ function activeServiceDirectiveValues(unitText, key, opts = {}) {
464
+ const values = [];
465
+ let section = "";
466
+ for (const rawLine of foldSystemdContinuations(unitText)) {
467
+ const line = rawLine.trim();
468
+ if (line === "" || line.startsWith("#") || line.startsWith(";"))
469
+ continue;
470
+ if (line.startsWith("[")) {
471
+ section = line.slice(1).replace(/\].*$/, "").trim().toLowerCase();
472
+ continue;
473
+ }
474
+ if (section !== "service")
475
+ continue;
476
+ const eq = line.indexOf("=");
477
+ if (eq < 0)
478
+ continue;
479
+ // Exact case — systemd is case-sensitive for directive names (see above).
480
+ if (line.slice(0, eq).trim() !== key)
481
+ continue;
482
+ const value = line.slice(eq + 1).trim();
483
+ if (value === "") {
484
+ // Blank assignment RESETS the list for this key — it is NOT a no-op.
485
+ // Drop everything collected so far; later non-blank values accumulate.
486
+ values.length = 0;
487
+ continue;
488
+ }
489
+ // Single-valued key: the LAST non-blank assignment wins. List key: every
490
+ // non-blank value is an operand.
491
+ if (opts.single)
492
+ values.length = 0;
493
+ values.push(value);
494
+ }
495
+ return values;
271
496
  }
497
+ /**
498
+ * Does this unit's ACTIVE, parsed path operands name the tree? Canonicalizes the
499
+ * unit-side operand (resolving symlinks via its existing ancestor) and the tree,
500
+ * then compares. See the block comment above for what is deliberately excluded.
501
+ */
272
502
  export function unitTextMentionsTree(unitText, treeDir) {
273
- const variants = new Set();
274
- const add = (p) => {
275
- const trimmed = p.replace(/\/+$/, "");
276
- if (trimmed.length > 1)
277
- variants.add(trimmed);
278
- };
279
- add(treeDir);
280
- try {
281
- add(canonicalPath(treeDir));
503
+ const tree = canonicalPath(treeDir);
504
+ // WorkingDirectory: SINGLE-valued — only the last non-blank assignment counts
505
+ // — and its resolved path must BE the tree.
506
+ for (const value of activeServiceDirectiveValues(unitText, "WorkingDirectory", { single: true })) {
507
+ const [first] = splitSystemdWords(value);
508
+ if (first === undefined)
509
+ continue;
510
+ const resolved = canonicalizeOperand(stripSystemdExecPrefix(first));
511
+ if (resolved !== null && resolved === tree)
512
+ return true;
513
+ }
514
+ // ExecStart: a path operand that lives INSIDE the tree (executable / script /
515
+ // argument), on path-component boundaries.
516
+ for (const value of activeServiceDirectiveValues(unitText, "ExecStart")) {
517
+ const words = splitSystemdWords(value);
518
+ for (let i = 0; i < words.length; i++) {
519
+ const operand = i === 0 ? stripSystemdExecPrefix(words[i]) : words[i];
520
+ const resolved = canonicalizeOperand(operand);
521
+ if (resolved !== null && isPathInside(resolved, tree))
522
+ return true;
523
+ }
282
524
  }
283
- catch { /* lexical variants are enough */ }
284
- return [...variants].some((v) => textMentionsDir(unitText, v));
525
+ return false;
285
526
  }
286
527
  const SYSTEM_UNIT_DIRS = ["/etc/systemd/system"];
287
528
  export function userSystemdDir(home = homedir()) {
@@ -444,6 +685,10 @@ export async function applyPlainTreeUpgrade(plan, hooks = {}) {
444
685
  if (existsSync(plan.previousDir)) {
445
686
  rmSync(plan.previousDir, { recursive: true, force: true });
446
687
  }
688
+ // flair#1758: this rename moves the tree discovery matched. If a symlink in
689
+ // the tree's path is retargeted between discovery (upgrade.ts) and here, the
690
+ // restart can launch a different tree. Documented, not solved — fresh
691
+ // comparison is not locking.
447
692
  try {
448
693
  renameSync(plan.treeDir, plan.previousDir);
449
694
  }
@@ -863,7 +863,16 @@ export async function runNightlyCycle(opts) {
863
863
  const row = {
864
864
  ...baseRow,
865
865
  slice: sliceLabel,
866
- status: opts.dryRun ? "dry-run" : "completed",
866
+ // flair#924 (defect 1): a run whose recorded `errors[]` is non-empty must
867
+ // NOT report success. A core stage that could not run — distillation with
868
+ // no generative backend, a per-tag distill failure, the dedup stat, an
869
+ // operator-aborted distill — is already pushed into `errors`; if any error
870
+ // stands, the run FAILED. Before this, a distillation-disabled cycle logged
871
+ // `status: "completed"` next to a populated `Errors:` block while the CLI
872
+ // exited 1 (src/commands/rem.ts), so the one signal a service manager can
873
+ // act on disagreed with the reported status. A populated errors[] can never
874
+ // coexist with "completed" again (regression-tested in rem-runner.test.ts).
875
+ status: errors.length > 0 ? "failed" : opts.dryRun ? "dry-run" : "completed",
867
876
  dryRun: opts.dryRun || undefined,
868
877
  snapshotPath,
869
878
  memoryCount,
@@ -6,6 +6,8 @@ import { join, dirname } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { allowAdmin } from "./agent-auth.js";
9
+ import { harperPortValue } from "../src/lib/harper-port-value.js";
10
+ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
9
11
  /**
10
12
  * Resolve the public URL operators reach this Flair on.
11
13
  *
@@ -21,6 +23,10 @@ import { allowAdmin } from "./agent-auth.js";
21
23
  * — derives from how the operator actually reached the page
22
24
  * 3. `http://127.0.0.1:${HTTP_PORT}` — local-only installs fallback
23
25
  *
26
+ * Exported for direct unit testing: the Resource class pulls Harper at import
27
+ * time, so a test mocks `harper` and calls this pure resolver directly rather
28
+ * than re-deriving its predicate and drifting from it.
29
+ *
24
30
  * The request-header path closes the common case from flair#404:
25
31
  * remote/Fabric deployments without FLAIR_PUBLIC_URL set rendered
26
32
  * localhost URLs that operators couldn't copy-paste. Trusting the Host
@@ -28,7 +34,7 @@ import { allowAdmin } from "./agent-auth.js";
28
34
  * reverse proxy that doesn't set X-Forwarded-* headers correctly, the
29
35
  * operator should set FLAIR_PUBLIC_URL explicitly (which wins).
30
36
  */
31
- function resolvePublicUrl(request) {
37
+ export function resolvePublicUrl(request) {
32
38
  if (process.env.FLAIR_PUBLIC_URL) {
33
39
  return process.env.FLAIR_PUBLIC_URL.replace(/\/$/, "");
34
40
  }
@@ -58,7 +64,7 @@ function resolvePublicUrl(request) {
58
64
  const effectiveScheme = fwdProto ? scheme : (host.includes(":") ? "http" : scheme);
59
65
  return `${effectiveScheme}://${host}`;
60
66
  }
61
- return `http://127.0.0.1:${process.env.HTTP_PORT ?? "19926"}`;
67
+ return `http://127.0.0.1:${harperPortValue(process.env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
62
68
  }
63
69
  /**
64
70
  * Read the runtime package version from the bundled package.json so the