@tpsdev-ai/flair 0.55.1 → 0.56.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 (76) hide show
  1. package/README.md +3 -3
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +201 -95
  7. package/dist/commands/attention.js +2 -2
  8. package/dist/commands/backup.js +2 -2
  9. package/dist/commands/doctor.js +168 -37
  10. package/dist/commands/export.js +2 -2
  11. package/dist/commands/federation.js +229 -95
  12. package/dist/commands/hook.js +4 -4
  13. package/dist/commands/init.js +94 -70
  14. package/dist/commands/mcp.js +2 -2
  15. package/dist/commands/migrate-harness-memory.js +8 -8
  16. package/dist/commands/rem.js +31 -4
  17. package/dist/commands/service.js +25 -1
  18. package/dist/commands/session.js +2 -2
  19. package/dist/commands/uninstall.js +2 -2
  20. package/dist/commands/upgrade.js +88 -69
  21. package/dist/doctor-client.js +341 -161
  22. package/dist/engine-version.js +2 -2
  23. package/dist/federation/scheduler.js +5 -5
  24. package/dist/hook-install.js +359 -176
  25. package/dist/install/clients.js +908 -214
  26. package/dist/keystore.js +10 -2
  27. package/dist/lib/auth-resolve.js +5 -5
  28. package/dist/lib/config-critical-section.js +557 -0
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/doctor-run.js +107 -27
  31. package/dist/lib/flair-paths.js +29 -0
  32. package/dist/lib/home.js +60 -0
  33. package/dist/lib/launchd-repair.js +109 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +256 -94
  36. package/dist/lib/pin-write-guard.js +87 -0
  37. package/dist/lib/settings-bytes.js +85 -0
  38. package/dist/lib/socket-path-limit.js +120 -0
  39. package/dist/lib/uninstall-purge.js +2 -18
  40. package/dist/lib/upgrade-plain-tree.js +2 -2
  41. package/dist/lib/upgrade-status.js +164 -0
  42. package/dist/lib/wiring-spec.js +238 -0
  43. package/dist/mcp-client-assertion.js +3 -3
  44. package/dist/rem/promote-policy.js +102 -0
  45. package/dist/rem/runner.js +3 -3
  46. package/dist/rem/scheduler.js +5 -5
  47. package/dist/rem/snapshot.js +2 -2
  48. package/dist/resources/MemoryReflect.js +10 -0
  49. package/dist/resources/OAuth.js +62 -11
  50. package/dist/resources/Presence.js +135 -47
  51. package/dist/resources/admin-layout.js +7 -2
  52. package/dist/resources/auto-promote-lib.js +56 -0
  53. package/dist/resources/health.js +26 -0
  54. package/dist/resources/memory-reflect-lib.js +215 -6
  55. package/dist/resources/migrations/progress.js +17 -0
  56. package/dist/resources/migrations/runner.js +46 -27
  57. package/dist/resources/migrations/status.js +2 -1
  58. package/dist/src/keystore.js +10 -2
  59. package/dist/src/lib/home.js +60 -0
  60. package/dist/src/rem/promote-policy.js +102 -0
  61. package/dist/src/rem/scheduler.js +5 -5
  62. package/dist/version-check.js +2 -2
  63. package/dist/version-handshake.js +2 -2
  64. package/docs/api-reference.md +31 -6
  65. package/docs/auth.md +14 -2
  66. package/docs/deploying-on-fabric.md +5 -4
  67. package/docs/deployment.md +26 -37
  68. package/docs/embedding-in-a-harper-app.md +4 -2
  69. package/docs/entity-vocabulary.md +5 -5
  70. package/docs/federation.md +58 -19
  71. package/docs/hosted-on-fabric.md +7 -5
  72. package/docs/mcp-clients.md +29 -12
  73. package/docs/releasing.md +66 -22
  74. package/docs/spoke-bringup.md +41 -22
  75. package/docs/standalone-local.md +12 -16
  76. package/package.json +3 -1
@@ -22,8 +22,13 @@
22
22
  import { spawnSync } from "node:child_process";
23
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
24
  import { dirname, join } from "node:path";
25
+ import { withHome } from "./lib/home.js";
25
26
  import { ALL_CLIENTS, clientConfigPath, piSettingsPath, resolvePiExtensionPath, scanPiSettings, } from "./install/clients.js";
26
- import { FLAIR_MCP_PACKAGE, mcpServerSpec } from "./lib/mcp-spec.js";
27
+ import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
28
+ import { decidePinWrite } from "./lib/pin-write-guard.js";
29
+ import { withConfigCriticalSection } from "./lib/config-critical-section.js";
30
+ import { backupBytesTo, encodeConfig, parseSettingsBytes, } from "./lib/settings-bytes.js";
31
+ import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./lib/wiring-spec.js";
27
32
  // The exact substring `flair init` writes into CLAUDE.md (src/cli.ts, the
28
33
  // `init` action) and that the doctor check + fix both key off of.
29
34
  export const CLAUDE_MD_BOOTSTRAP_MARKER = "mcp__flair__bootstrap";
@@ -208,6 +213,13 @@ export function isFlairHookCommand(command) {
208
213
  // never a failure (see checkContinuityCaptureHooks / cli.ts's rendering).
209
214
  /** The exact substring identifying a Flair continuity-capture hook command. */
210
215
  export const CONTINUITY_CAPTURE_HOOK_MARKER = "flair-continuity-capture";
216
+ /**
217
+ * The npx invocation of the continuity marker — pinned (`@tpsdev-ai/flair-mcp@<v>`)
218
+ * or the unpinned form. Used by the continuity report so BOTH the pinned form
219
+ * (a fresh provision, flair#1778 2c-i-a3) and the older unpinned form read as
220
+ * the current shape, while an unsilenced / non-`-p` hand-edit still reads stale.
221
+ */
222
+ const CONTINUITY_INVOCATION_RE = /npx -y -p @tpsdev-ai\/flair-mcp(?:@[^\s"']+)? flair-continuity-capture/;
211
223
  /**
212
224
  * The PostToolUse matcher written alongside our hook entry — the EXACT
213
225
  * mutating-tool allowlist the capture binary enforces internally
@@ -223,8 +235,14 @@ export const CONTINUITY_POST_TOOL_USE_MATCHER = "Write|Edit|NotebookEdit|Bash";
223
235
  * (PostToolUse and Stop run the same binary; the payload's hook_event_name
224
236
  * tells it which fired). Same strict value allow-list as the SessionStart
225
237
  * builder — throws rather than emitting a quoted approximation.
238
+ *
239
+ * `pin` is the version the entry's OWN pin state calls for (flair#1778 2c-i-a3,
240
+ * continuity-preserve): a concrete version re-emits it verbatim so a repair
241
+ * never UNPINS a pinned entry, and `null`/omitted keeps the pre-#1143 unpinned
242
+ * form an unpinned entry already has. A fresh (absent) entry is provisioned
243
+ * pinned to the running CLI by the caller, matching today's MCP policy.
226
244
  */
227
- export function buildContinuityCaptureHookCommand(agentId, flairUrl) {
245
+ export function buildContinuityCaptureHookCommand(agentId, flairUrl, pin) {
228
246
  if (!isHookCommandValueSafe(agentId)) {
229
247
  throw new Error(`agent id '${agentId}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
230
248
  }
@@ -232,7 +250,8 @@ export function buildContinuityCaptureHookCommand(agentId, flairUrl) {
232
250
  throw new Error(`Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
233
251
  }
234
252
  const env = flairUrl ? `FLAIR_AGENT_ID=${agentId} FLAIR_URL=${flairUrl}` : `FLAIR_AGENT_ID=${agentId}`;
235
- const invocation = `${env} npx -y -p @tpsdev-ai/flair-mcp ${CONTINUITY_CAPTURE_HOOK_MARKER}`;
253
+ const spec = pin ? `@tpsdev-ai/flair-mcp@${pin}` : "@tpsdev-ai/flair-mcp";
254
+ const invocation = `${env} npx -y -p ${spec} ${CONTINUITY_CAPTURE_HOOK_MARKER}`;
236
255
  return `sh -c '${invocation} >/dev/null 2>/dev/null || true'`;
237
256
  }
238
257
  /** Does this command invoke the Flair continuity-capture binary at all? */
@@ -267,7 +286,7 @@ function continuityEventReport(config, event) {
267
286
  const command = typeof hook?.command === "string" ? hook.command : "";
268
287
  const matcher = typeof found.group?.matcher === "string" ? found.group.matcher : undefined;
269
288
  const shapeOk = hook?.type === "command" &&
270
- command.includes(`npx -y -p @tpsdev-ai/flair-mcp ${CONTINUITY_CAPTURE_HOOK_MARKER}`) &&
289
+ CONTINUITY_INVOCATION_RE.test(command) &&
271
290
  hookCommandIsSilenced(command);
272
291
  const matcherOk = event !== "PostToolUse" || matcher === CONTINUITY_POST_TOOL_USE_MATCHER;
273
292
  return { present: true, command, matcher, currentForm: shapeOk && matcherOk };
@@ -302,6 +321,37 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
302
321
  state = "stale";
303
322
  return { path, postToolUse, stop, state };
304
323
  }
324
+ /**
325
+ * The never-lower decision for ONE continuity event's entry, in
326
+ * continuity-preserve mode (flair#1778 2c-i-a3).
327
+ *
328
+ * `decidePinWrite` (the SAME a2 primitive — no second comparison idiom here) is
329
+ * consulted for EVERY arm:
330
+ * • hold / refuse → propagated verbatim (an AHEAD pin, a range/tag/
331
+ * unsupported spec, or an unreadable running version);
332
+ * • write, absent → the running CLI's version (provision pinned to it,
333
+ * today's MCP policy);
334
+ * • write, existing → the ENTRY'S OWN pin state, preserved — a pinned entry
335
+ * keeps its version (a repair never UNPINS it: Kern's
336
+ * finding), an unpinned entry stays unpinned. Continuity
337
+ * never repins a BEHIND entry UP; it repairs shape only.
338
+ */
339
+ function decideContinuityWrite(existingCommand, entryLabel) {
340
+ const decision = decidePinWrite({
341
+ pkg: FLAIR_MCP_PACKAGE,
342
+ entry: entryLabel,
343
+ existingText: existingCommand,
344
+ runningVersion: flairCliVersion(),
345
+ });
346
+ if (decision.action !== "write")
347
+ return decision;
348
+ if (existingCommand === null)
349
+ return decision; // absent → provision at the running CLI
350
+ const spec = decodeWiringSpec(existingCommand, FLAIR_MCP_PACKAGE);
351
+ if (isComparableWiringPin(spec))
352
+ return { action: "write", pin: wiringPinString(spec), line: null };
353
+ return { action: "write", pin: null, line: null }; // unpinned → repair, stay unpinned
354
+ }
305
355
  /**
306
356
  * Pure merge of the continuity pair into a parsed settings object — the ONE
307
357
  * mutation core both write paths (`flair doctor --fix` via
@@ -311,15 +361,32 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
311
361
  * groups and keys are preserved byte-identical; a group we don't own keeps
312
362
  * its matcher (our binary's internal allowlist still filters — the matcher is
313
363
  * an efficiency, not the control).
364
+ *
365
+ * CONTINUITY-PRESERVE (flair#1778 2c-i-a3): the version written is the entry's
366
+ * OWN pin state, so repairing a pinned entry never silently unpins it, and the
367
+ * a2 never-lower guard is consulted on every entry the write would replace.
368
+ * A hold/refuse on EITHER event yields `decision` set and the ORIGINAL config
369
+ * returned, so both arrays stay byte-identical.
314
370
  */
315
371
  export function computeContinuityHookInstall(config, agentId, flairUrl) {
316
- const command = buildContinuityCaptureHookCommand(agentId, flairUrl);
317
- const newConfig = JSON.parse(JSON.stringify(config ?? {}));
372
+ const original = config ?? {};
373
+ const newConfig = JSON.parse(JSON.stringify(original));
318
374
  const actions = { PostToolUse: "noop", Stop: "noop" };
319
375
  let changed = false;
376
+ let decision = null;
320
377
  newConfig.hooks = newConfig.hooks && typeof newConfig.hooks === "object" && !Array.isArray(newConfig.hooks) ? newConfig.hooks : {};
321
378
  for (const event of CONTINUITY_HOOK_EVENTS) {
322
379
  const existing = findContinuityEntry(newConfig, event);
380
+ const existingCommand = existing && typeof existing.group?.hooks?.[existing.hookIndex]?.command === "string"
381
+ ? existing.group.hooks[existing.hookIndex].command
382
+ : null;
383
+ const eventDecision = decideContinuityWrite(existingCommand, `${event} continuity capture hook`);
384
+ if (eventDecision.action !== "write") {
385
+ if (decision === null || eventDecision.action === "refuse")
386
+ decision = eventDecision;
387
+ continue;
388
+ }
389
+ const command = buildContinuityCaptureHookCommand(agentId, flairUrl, eventDecision.pin);
323
390
  if (existing) {
324
391
  const hook = existing.group.hooks[existing.hookIndex];
325
392
  const soleOwner = existing.group.hooks.length === 1;
@@ -342,7 +409,15 @@ export function computeContinuityHookInstall(config, agentId, flairUrl) {
342
409
  actions[event] = "add";
343
410
  changed = true;
344
411
  }
345
- return { changed, actions, newConfig };
412
+ if (decision !== null) {
413
+ return {
414
+ changed: false,
415
+ actions: { PostToolUse: "noop", Stop: "noop" },
416
+ newConfig: original,
417
+ decision,
418
+ };
419
+ }
420
+ return { changed, actions, newConfig, decision: null };
346
421
  }
347
422
  /**
348
423
  * Pure removal of the continuity pair — deletes ONLY our entries (marker
@@ -373,11 +448,28 @@ export function computeContinuityHookRemoval(config) {
373
448
  }
374
449
  return { changed, actions, newConfig };
375
450
  }
451
+ /**
452
+ * The four doctor hook writers printed `could not write/update <path>:
453
+ * <reason>` before the flair#1778 2c-i-c migration, where <reason> was the
454
+ * JSON.parse failure message. The shared parser (./lib/settings-bytes.js)
455
+ * reports the SAME failure as `malformed JSON in <path> (<reason>)`. Peeling
456
+ * that wrapper lets each migrated writer keep its exact pre-migration line
457
+ * (the brief's "keep the existing line wherever one exists"). Falls back to
458
+ * the parser's text unchanged if the shape ever differs.
459
+ */
460
+ function jsonFailureReason(path, parseError) {
461
+ const prefix = `malformed JSON in ${path} (`;
462
+ return parseError.startsWith(prefix) && parseError.endsWith(")")
463
+ ? parseError.slice(prefix.length, parseError.length - 1)
464
+ : parseError;
465
+ }
376
466
  /**
377
467
  * `flair doctor --fix` write path: register (or repair to current form) the
378
468
  * continuity pair in ~/.claude/settings.json. Merge-safe read-parse-write,
379
469
  * mirroring fixSessionStartHook — creates the file if absent, refuses on a
380
- * file it cannot parse.
470
+ * file it cannot parse. The write is CONTINUITY-PRESERVE (flair#1778 2c-i-a3):
471
+ * it keeps each entry's own pin state and consults the never-lower guard, so a
472
+ * repair never unpins a pinned entry; a hold/refuse writes nothing.
381
473
  */
382
474
  export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
383
475
  const path = join(homeDir, ".claude", "settings.json");
@@ -405,18 +497,36 @@ export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
405
497
  message: `Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`,
406
498
  };
407
499
  }
500
+ // Parent creation stays OUTSIDE the primitive: it needs the resolved parent
501
+ // to exist before it can observe an absent destination (flair#1778 2c-i-b).
502
+ // Everything from here (observe → decide → write) is ONE critical section.
408
503
  try {
409
- let config = {};
410
- const raw = readTextFile(path);
411
- if (raw && raw.trim())
412
- config = JSON.parse(raw);
413
- const { changed, newConfig } = computeContinuityHookInstall(config, agentId, flairUrl);
414
- if (!changed) {
415
- return { ok: true, path, changed: false, message: `continuity capture hooks already current in ${path}` };
416
- }
417
504
  mkdirSync(dirname(path), { recursive: true });
418
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
419
- return { ok: true, path, changed: true, message: `wired the continuity capture hooks (PostToolUse + Stop) in ${path} (agent '${agentId}')` };
505
+ let outcome = null;
506
+ const result = withConfigCriticalSection(path, (bytes) => {
507
+ const read = parseSettingsBytes(bytes, path);
508
+ if (read.parseError) {
509
+ outcome = { ok: false, path, changed: false, message: `could not write ${path}: ${jsonFailureReason(path, read.parseError)}` };
510
+ return { hold: outcome.message };
511
+ }
512
+ const { changed, newConfig, decision } = computeContinuityHookInstall(read.parsed ?? {}, agentId, flairUrl);
513
+ if (decision) {
514
+ outcome = { ok: true, path, changed: false, message: decision.line };
515
+ return { hold: decision.line };
516
+ }
517
+ if (!changed) {
518
+ outcome = { ok: true, path, changed: false, message: `continuity capture hooks already current in ${path}` };
519
+ return { noop: outcome.message };
520
+ }
521
+ return { write: encodeConfig(newConfig) };
522
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
523
+ if (result.status === "written") {
524
+ return { ok: true, path, changed: true, message: `wired the continuity capture hooks (PostToolUse + Stop) in ${path} (agent '${agentId}')` };
525
+ }
526
+ const settled = outcome;
527
+ if (settled)
528
+ return settled;
529
+ return { ok: false, path, changed: false, message: result.message };
420
530
  }
421
531
  catch (err) {
422
532
  const reason = err instanceof Error ? err.message : String(err);
@@ -427,21 +537,42 @@ export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
427
537
  * Symmetric removal path (`flair doctor --fix` when disabling / `flair hook
428
538
  * uninstall --continuity`). A no-op when nothing is wired — never creates a
429
539
  * file that didn't exist, refuses on a file it cannot parse.
540
+ *
541
+ * NOT a version writer (flair#1778 2c-i-a3): it only DELETES our entries and
542
+ * preserves every other byte (see the merge-safe removal test) — it never
543
+ * writes a version-carrying spec, so it cannot lower a pin and needs no guard.
430
544
  */
431
545
  export function removeContinuityCaptureHooks(homeDir) {
432
546
  const path = join(homeDir, ".claude", "settings.json");
547
+ // A pre-lock existence/emptiness probe: this removal writer must keep its
548
+ // exact "not enabled" line and take no lock (and no backup) where there is
549
+ // nothing to remove at all.
433
550
  const raw = readTextFile(path);
434
551
  if (!raw || !raw.trim()) {
435
552
  return { ok: true, path, changed: false, message: `no ${path} — continuity capture hooks are not enabled` };
436
553
  }
437
554
  try {
438
- const config = JSON.parse(raw);
439
- const { changed, newConfig } = computeContinuityHookRemoval(config);
440
- if (!changed) {
441
- return { ok: true, path, changed: false, message: `no continuity capture hooks found in ${path} — nothing to remove` };
555
+ let outcome = null;
556
+ const result = withConfigCriticalSection(path, (bytes) => {
557
+ const read = parseSettingsBytes(bytes, path);
558
+ if (read.parseError) {
559
+ outcome = { ok: false, path, changed: false, message: `could not update ${path}: ${jsonFailureReason(path, read.parseError)}` };
560
+ return { hold: outcome.message };
561
+ }
562
+ const { changed, newConfig } = computeContinuityHookRemoval(read.parsed ?? {});
563
+ if (!changed) {
564
+ outcome = { ok: true, path, changed: false, message: `no continuity capture hooks found in ${path} — nothing to remove` };
565
+ return { noop: outcome.message };
566
+ }
567
+ return { write: encodeConfig(newConfig) };
568
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
569
+ if (result.status === "written") {
570
+ return { ok: true, path, changed: true, message: `removed the continuity capture hooks (PostToolUse + Stop) from ${path}` };
442
571
  }
443
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
444
- return { ok: true, path, changed: true, message: `removed the continuity capture hooks (PostToolUse + Stop) from ${path}` };
572
+ const settled = outcome;
573
+ if (settled)
574
+ return settled;
575
+ return { ok: false, path, changed: false, message: result.message };
445
576
  }
446
577
  catch (err) {
447
578
  const reason = err instanceof Error ? err.message : String(err);
@@ -449,29 +580,10 @@ export function removeContinuityCaptureHooks(homeDir) {
449
580
  }
450
581
  }
451
582
  // ── shared helpers ──────────────────────────────────────────────────────────
452
- /**
453
- * Run `fn` with process.env.HOME temporarily pointed at `homeDir`, then
454
- * restore it. clientConfigPath() (src/install/clients.ts) resolves the home
455
- * dir via HOME/USERPROFILE at call time (not cached), so this lets us reuse
456
- * that single source of truth for per-client config paths while keeping
457
- * doctor-client's own functions parameterized by an explicit homeDir for
458
- * tests — no test ever touches the real ~/.claude.json etc. The override is
459
- * synchronous and restored before this function returns, so it's safe even
460
- * though process.env is process-global.
461
- */
462
- function withHome(homeDir, fn) {
463
- const prev = process.env.HOME;
464
- process.env.HOME = homeDir;
465
- try {
466
- return fn();
467
- }
468
- finally {
469
- if (prev === undefined)
470
- delete process.env.HOME;
471
- else
472
- process.env.HOME = prev;
473
- }
474
- }
583
+ // `withHome()` (src/lib/home.ts) points HOME and USERPROFILE at an explicit
584
+ // homeDir for a synchronous callback; clientConfigPath() (src/install/clients.ts)
585
+ // resolves the home at call time, so doctor-client's explicit-homeDir functions
586
+ // reuse that single source of truth and no test touches the real ~/.claude.json.
475
587
  function readTextFile(path) {
476
588
  try {
477
589
  if (!existsSync(path))
@@ -524,23 +636,24 @@ export function readClientMcpBlock(clientId, homeDir) {
524
636
  function readJsonFlairBlock(configPath) {
525
637
  const raw = readTextFile(configPath);
526
638
  if (!raw || !raw.trim())
527
- return { present: false, configPath };
639
+ return { present: false, entryExists: false, configPath };
528
640
  try {
529
641
  const config = JSON.parse(raw);
530
642
  const flair = config?.mcpServers?.flair;
531
643
  if (!flair || typeof flair !== "object")
532
- return { present: false, configPath };
644
+ return { present: false, entryExists: false, configPath };
533
645
  const agentId = typeof flair.env?.FLAIR_AGENT_ID === "string" && flair.env.FLAIR_AGENT_ID ? flair.env.FLAIR_AGENT_ID : undefined;
534
646
  const flairUrl = typeof flair.env?.FLAIR_URL === "string" && flair.env.FLAIR_URL ? flair.env.FLAIR_URL : undefined;
535
647
  // FLAIR_URL optional — see readClientMcpBlock's doc (flair#1287). Any
536
648
  // extra fields the client's own tooling writes (e.g. `claude mcp add`'s
537
649
  // `type: "stdio"`) are irrelevant to presence and deliberately ignored.
538
650
  const present = !!agentId;
539
- return { present, configPath, agentId, flairUrl, urlDefaulted: present && !flairUrl };
651
+ // entryExists is true here: the flair key was found and is an object.
652
+ return { present, entryExists: true, configPath, agentId, flairUrl, urlDefaulted: present && !flairUrl };
540
653
  }
541
654
  catch {
542
655
  // Malformed JSON — treat as "not present", never throw.
543
- return { present: false, configPath };
656
+ return { present: false, entryExists: false, configPath };
544
657
  }
545
658
  }
546
659
  /**
@@ -565,9 +678,9 @@ function readJsonFlairBlock(configPath) {
565
678
  function readCodexFlairBlock(configPath) {
566
679
  const raw = readTextFile(configPath);
567
680
  if (!raw)
568
- return { present: false, configPath };
681
+ return { present: false, entryExists: false, configPath };
569
682
  const scanned = scanCodexFlairBlock(raw);
570
- return { present: scanned.present, configPath, agentId: scanned.agentId, flairUrl: scanned.flairUrl, urlDefaulted: scanned.urlDefaulted };
683
+ return { present: scanned.present, entryExists: scanned.entryExists, configPath, agentId: scanned.agentId, flairUrl: scanned.flairUrl, urlDefaulted: scanned.urlDefaulted };
571
684
  }
572
685
  /**
573
686
  * The two env keys the codex scanner ever looks for, each with LITERAL
@@ -620,7 +733,7 @@ function scanCodexEnvValue(block, key) {
620
733
  function scanCodexFlairBlock(raw) {
621
734
  const startMatch = raw.match(/^\[mcp_servers\.flair\]\s*$/m);
622
735
  if (!startMatch || startMatch.index === undefined)
623
- return { present: false };
736
+ return { present: false, entryExists: false };
624
737
  const rest = raw.slice(startMatch.index);
625
738
  const lines = rest.split("\n");
626
739
  const blockLines = [lines[0]];
@@ -636,7 +749,7 @@ function scanCodexFlairBlock(raw) {
636
749
  // FLAIR_URL optional — same contract as readJsonFlairBlock (flair#1287);
637
750
  // docs/mcp-clients.md's own Codex snippet sets only FLAIR_AGENT_ID.
638
751
  const present = !!agentId;
639
- return { present, agentId, flairUrl, urlDefaulted: present && !flairUrl };
752
+ return { present, entryExists: true, agentId, flairUrl, urlDefaulted: present && !flairUrl };
640
753
  }
641
754
  export function checkPiFlairWiring(homeDir, cwd) {
642
755
  const userPath = withHome(homeDir, () => piSettingsPath());
@@ -737,6 +850,10 @@ export function checkClaudeMdBootstrap(cwd, homeDir) {
737
850
  * Append the bootstrap instruction to `${cwd}/CLAUDE.md` (creating it if
738
851
  * absent). Idempotent — safe to call twice; a second call is a no-op that
739
852
  * still reports ok:true.
853
+ *
854
+ * NOT a version writer (flair#1778 2c-i-a3): it writes a CLAUDE.md prose line,
855
+ * not a wiring entry — the block carries no `<pkg>@<spec>`, so there is no pin
856
+ * to lower and nothing for the guard to decide.
740
857
  */
741
858
  export function fixClaudeMdBootstrap(cwd) {
742
859
  const path = join(cwd, "CLAUDE.md");
@@ -788,27 +905,16 @@ export function checkSessionStartHook(homeDir, settingsPath) {
788
905
  return { present: false, path };
789
906
  }
790
907
  }
791
- const FLAIR_AT_SPEC_RE = /@tpsdev-ai\/(flair-mcp|flair-client)@([0-9A-Za-z][^\s"'\],]*)/g;
792
- const FLAIR_JSON_DEP_RE = /"@tpsdev-ai\/(flair-mcp|flair-client)"\s*:\s*"([^"]+)"/g;
793
- /** Strip npm range / workspace prefixes so `^0.17.0` compares as `0.17.0`. */
794
- export function normalizeDeclaredPinVersion(raw) {
795
- if (typeof raw !== "string")
796
- return null;
797
- let v = raw.trim();
798
- if (!v)
799
- return null;
800
- v = v.replace(/^(workspace|npm):/, "");
801
- v = v.replace(/^[\^~>=<\s]+/, "");
802
- v = v.replace(/^v/, "");
803
- // Require X.Y.Z so `latest` / tags / bare names are not pins.
804
- const m = v.match(/^(\d+\.\d+\.\d+[^\s"'\],]*)/);
805
- return m ? m[1] : null;
806
- }
807
908
  /**
808
909
  * Every `@tpsdev-ai/flair-mcp` / `@tpsdev-ai/flair-client` pin in a wiring
809
- * string or package.json. Covers `pkg@<ver>` specs (MCP args, hook commands)
810
- * and `"pkg": "<ver>"` dependency fields. Bare / unpinned / `latest` specs
811
- * contribute nothing.
910
+ * string or package.json.
911
+ *
912
+ * flair#1778 slice 2c-i-a1: a THIN ADAPTER over the interim `WiringSpec` model
913
+ * (`./lib/wiring-spec.js`). For a concrete `version` token the result is
914
+ * byte-identical to before; for `range-or-tag` / `unsupported` / `malformed`
915
+ * the spec is now returned as its RAW token (PRESENT, not comparable) instead
916
+ * of being dropped as `null`/absent. `none` (unpinned) still contributes
917
+ * nothing. Callers that have migrated read `WiringSpec` directly.
812
918
  *
813
919
  * flair#1383: doctor must read the actual installed pins, not infer age
814
920
  * from "pin !== CLI version".
@@ -816,51 +922,51 @@ export function normalizeDeclaredPinVersion(raw) {
816
922
  export function extractFlairPackagePins(text) {
817
923
  if (typeof text !== "string")
818
924
  return [];
819
- const out = [];
925
+ const found = [];
820
926
  const seen = new Set();
821
- const add = (pkg, rawVer) => {
822
- const version = normalizeDeclaredPinVersion(rawVer);
823
- if (!version)
824
- return;
825
- const name = pkg;
826
- const key = `${name}@${version}`;
827
- if (seen.has(key))
828
- return;
829
- seen.add(key);
830
- out.push({ package: name, version });
831
- };
832
- for (const m of text.matchAll(FLAIR_AT_SPEC_RE))
833
- add(m[1], m[2]);
834
- for (const m of text.matchAll(FLAIR_JSON_DEP_RE))
835
- add(m[1], m[2]);
836
- return out;
927
+ for (const pkg of ["flair-mcp", "flair-client"]) {
928
+ for (const spec of decodeWiringSpecs(text, `@tpsdev-ai/${pkg}`)) {
929
+ const version = wiringPinString(spec);
930
+ if (version === null)
931
+ continue;
932
+ const key = `${pkg}@${version}`;
933
+ if (seen.has(key))
934
+ continue;
935
+ seen.add(key);
936
+ // Preserve the ORDER pins appear in the text (the old extractor's
937
+ // match-position order), not the order packages are enumerated.
938
+ const at = text.indexOf(spec.raw);
939
+ found.push({ at: at < 0 ? Number.MAX_SAFE_INTEGER : at, pin: { package: pkg, version } });
940
+ }
941
+ }
942
+ found.sort((a, b) => a.at - b.at);
943
+ return found.map((f) => f.pin);
837
944
  }
838
945
  /**
839
- * Extract a pinned `@tpsdev-ai/flair-mcp` version from any wiring string — a
840
- * client MCP `args` array, a Codex TOML args line, or a SessionStart hook
841
- * command. Returns the version when the spec is written
842
- * `@tpsdev-ai/flair-mcp@<ver>`; null for a bare/unpinned spec.
843
- *
844
- * SessionStart hooks written since flair#1143 carry the same pin as a
845
- * client MCP config (`mcpServerSpec()`). A pre-#1143 unpinned hook still
846
- * establishes that flair-mcp is wired but contributes no version.
946
+ * Extract the `@tpsdev-ai/flair-mcp` spec from any wiring string — a client MCP
947
+ * `args` array, a Codex TOML args line, or a SessionStart hook command. A
948
+ * concrete version returns its version; a range/tag/unsupported/malformed spec
949
+ * returns its RAW token (present-not-comparable); a bare/unpinned spec returns
950
+ * null.
847
951
  */
848
952
  export function extractFlairMcpPin(text) {
849
953
  return extractFlairPackagePins(text).find((p) => p.package === "flair-mcp")?.version ?? null;
850
954
  }
851
955
  export function detectWiredFlairMcp(homeDir) {
852
956
  let wired = false;
853
- let pinnedVersion = null;
957
+ // flair#1778 slice 2c-i-a1: decode EVERY wired entry into its own WiringSpec
958
+ // — one per entry, never collapsing to the first. A bare/unpinned entry still
959
+ // establishes `wired` (today's outcome) but contributes no spec.
960
+ const specs = [];
854
961
  // The package name only ever appears in a Flair MCP wiring block, so its
855
962
  // presence in a config's text is a reliable "flair-mcp is wired here" signal.
856
963
  const note = (text) => {
857
964
  if (!text || !text.includes(FLAIR_MCP_PACKAGE))
858
965
  return;
859
966
  wired = true;
860
- if (!pinnedVersion) {
861
- const pin = extractFlairMcpPin(text);
862
- if (pin)
863
- pinnedVersion = pin;
967
+ for (const spec of decodeWiringSpecs(text, FLAIR_MCP_PACKAGE)) {
968
+ if (spec.token.kind !== "none")
969
+ specs.push(spec);
864
970
  }
865
971
  };
866
972
  // 1. Every known client's MCP config — a wired flair block carries the spec.
@@ -884,6 +990,16 @@ export function detectWiredFlairMcp(homeDir) {
884
990
  if (hook.present && isFlairHookCommand(hook.command ?? ""))
885
991
  note(hook.command);
886
992
  }
993
+ // A concrete version wins (today's precedence, over the SAME ordered entry
994
+ // list); otherwise a present-not-comparable spec is reported as its raw token
995
+ // rather than dropped as absent. A bare entry alone leaves `pinnedVersion`
996
+ // null — unchanged.
997
+ const firstVersion = specs.find((s) => s.token.kind === "version");
998
+ const pinnedVersion = firstVersion
999
+ ? firstVersion.token.value
1000
+ : specs.length > 0
1001
+ ? wiringPinString(specs[0])
1002
+ : null;
887
1003
  return { wired, pinnedVersion };
888
1004
  }
889
1005
  /** The `@tpsdev-ai/flair-mcp` version pinned in a client's MCP config, or null
@@ -945,29 +1061,59 @@ export function fixSessionStartHook(homeDir, agentId, settingsPath) {
945
1061
  message: `agent id '${agentId}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`,
946
1062
  };
947
1063
  }
1064
+ // Parent creation stays OUTSIDE the primitive (flair#1778 2c-i-b): the
1065
+ // primitive needs the resolved parent to exist to observe an absent
1066
+ // destination. Everything from here is ONE critical section.
948
1067
  try {
949
- let config = {};
950
- const raw = readTextFile(path);
951
- if (raw && raw.trim())
952
- config = JSON.parse(raw);
953
- config.hooks = config.hooks && typeof config.hooks === "object" ? config.hooks : {};
954
- config.hooks.SessionStart = Array.isArray(config.hooks.SessionStart) ? config.hooks.SessionStart : [];
955
- const alreadyPresent = config.hooks.SessionStart.some((group) => Array.isArray(group?.hooks) &&
956
- group.hooks.some((h) => typeof h?.command === "string" && h.command.includes(SESSION_START_HOOK_MARKER)));
957
- if (alreadyPresent) {
958
- return { ok: true, path, message: `already present in ${path}` };
959
- }
960
- config.hooks.SessionStart.push({
961
- hooks: [
962
- {
963
- type: "command",
964
- command: buildSessionStartHookCommand(agentId, undefined, { harness: hookHarnessFromSettingsPath(path) }),
965
- },
966
- ],
967
- });
968
1068
  mkdirSync(dirname(path), { recursive: true });
969
- writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
970
- return { ok: true, path, message: `added SessionStart hook to ${path} (agent '${agentId}')` };
1069
+ let outcome = null;
1070
+ const result = withConfigCriticalSection(path, (bytes) => {
1071
+ const read = parseSettingsBytes(bytes, path);
1072
+ if (read.parseError) {
1073
+ outcome = { ok: false, message: `could not write ${path}: ${jsonFailureReason(path, read.parseError)}` };
1074
+ return { hold: outcome.message };
1075
+ }
1076
+ const config = read.parsed ?? {};
1077
+ config.hooks = config.hooks && typeof config.hooks === "object" ? config.hooks : {};
1078
+ config.hooks.SessionStart = Array.isArray(config.hooks.SessionStart) ? config.hooks.SessionStart : [];
1079
+ const alreadyPresent = config.hooks.SessionStart.some((group) => Array.isArray(group?.hooks) &&
1080
+ group.hooks.some((h) => typeof h?.command === "string" && h.command.includes(SESSION_START_HOOK_MARKER)));
1081
+ if (alreadyPresent) {
1082
+ outcome = { ok: true, message: `already present in ${path}` };
1083
+ return { noop: outcome.message };
1084
+ }
1085
+ // flair#1778 2c-i-a3: the ADD arm is a version-carrying write (the
1086
+ // command pins @tpsdev-ai/flair-mcp). Consult the ONE never-lower guard
1087
+ // with an ABSENT entry — on the IN-LOCK bytes, inside the critical
1088
+ // section — a healthy version still writes (pinned up to the running
1089
+ // CLI), an unreadable one refuses by name and creates nothing.
1090
+ const decision = decidePinWrite({
1091
+ pkg: FLAIR_MCP_PACKAGE,
1092
+ entry: `SessionStart hook in ${path}`,
1093
+ existingText: null,
1094
+ runningVersion: flairCliVersion(),
1095
+ });
1096
+ if (decision.action !== "write") {
1097
+ outcome = { ok: false, message: decision.line };
1098
+ return { hold: outcome.message };
1099
+ }
1100
+ config.hooks.SessionStart.push({
1101
+ hooks: [
1102
+ {
1103
+ type: "command",
1104
+ command: buildSessionStartHookCommand(agentId, undefined, { harness: hookHarnessFromSettingsPath(path) }),
1105
+ },
1106
+ ],
1107
+ });
1108
+ return { write: encodeConfig(config) };
1109
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1110
+ if (result.status === "written") {
1111
+ return { ok: true, path, message: `added SessionStart hook to ${path} (agent '${agentId}')` };
1112
+ }
1113
+ const settled = outcome;
1114
+ if (settled)
1115
+ return { ok: settled.ok, path, message: settled.message };
1116
+ return { ok: false, path, message: result.message };
971
1117
  }
972
1118
  catch (err) {
973
1119
  const reason = err instanceof Error ? err.message : String(err);
@@ -1144,47 +1290,81 @@ export function classifyHookReadiness(report) {
1144
1290
  */
1145
1291
  export function upgradeSessionStartHookCommand(homeDir, settingsPath) {
1146
1292
  const path = settingsPath ?? join(homeDir, ".claude", "settings.json");
1293
+ // A pre-lock existence/emptiness probe: this repair writer never creates the
1294
+ // file or its parent, and must keep its exact "no <path> to update" line and
1295
+ // take no lock (and no backup) where there is no destination at all.
1296
+ const raw = readTextFile(path);
1297
+ if (!raw || !raw.trim())
1298
+ return { ok: false, path, changed: false, message: `no ${path} to update` };
1147
1299
  try {
1148
- const raw = readTextFile(path);
1149
- if (!raw || !raw.trim())
1150
- return { ok: false, path, changed: false, message: `no ${path} to update` };
1151
- const config = JSON.parse(raw);
1152
- const groups = config?.hooks?.SessionStart;
1153
- if (!Array.isArray(groups))
1154
- return { ok: false, path, changed: false, message: `no SessionStart hooks in ${path}` };
1155
- for (const group of groups) {
1156
- const hooks = group?.hooks;
1157
- if (!Array.isArray(hooks))
1158
- continue;
1159
- for (const hook of hooks) {
1160
- if (typeof hook?.command !== "string" || !hook.command.includes(SESSION_START_HOOK_MARKER))
1300
+ let outcome = null;
1301
+ const result = withConfigCriticalSection(path, (bytes) => {
1302
+ const read = parseSettingsBytes(bytes, path);
1303
+ if (read.parseError) {
1304
+ outcome = { ok: false, path, changed: false, message: `could not update ${path}: ${jsonFailureReason(path, read.parseError)}` };
1305
+ return { hold: outcome.message };
1306
+ }
1307
+ const config = read.parsed ?? {};
1308
+ const groups = config?.hooks?.SessionStart;
1309
+ if (!Array.isArray(groups)) {
1310
+ outcome = { ok: false, path, changed: false, message: `no SessionStart hooks in ${path}` };
1311
+ return { hold: outcome.message };
1312
+ }
1313
+ for (const group of groups) {
1314
+ const hooks = group?.hooks;
1315
+ if (!Array.isArray(hooks))
1161
1316
  continue;
1162
- // Already absorbing its own failures — nothing to repair, whether we
1163
- // wrote it or the user did. Checked BEFORE the legacy match so a second
1164
- // run is a clean no-op rather than "that isn't the command we wrote".
1165
- if (hookCommandIsSilenced(hook.command)) {
1166
- return { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1167
- }
1168
- const legacy = parseLegacySessionStartHookCommand(hook.command);
1169
- if (!legacy) {
1170
- return {
1171
- ok: false,
1172
- path,
1173
- changed: false,
1174
- message: `the SessionStart hook in ${path} is not the command Flair wrote — leaving it untouched`,
1175
- };
1317
+ for (const hook of hooks) {
1318
+ if (typeof hook?.command !== "string" || !hook.command.includes(SESSION_START_HOOK_MARKER))
1319
+ continue;
1320
+ // Already absorbing its own failures — nothing to repair, whether we
1321
+ // wrote it or the user did. Checked BEFORE the legacy match so a second
1322
+ // run is a clean no-op rather than "that isn't the command we wrote".
1323
+ if (hookCommandIsSilenced(hook.command)) {
1324
+ outcome = { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1325
+ return { noop: outcome.message };
1326
+ }
1327
+ const legacy = parseLegacySessionStartHookCommand(hook.command);
1328
+ if (!legacy) {
1329
+ outcome = { ok: false, path, changed: false, message: `the SessionStart hook in ${path} is not the command Flair wrote — leaving it untouched` };
1330
+ return { hold: outcome.message };
1331
+ }
1332
+ // flair#1778 2c-i-a3: the repair rewrites the entry to a version-
1333
+ // carrying command, so it consults the never-lower guard first — on
1334
+ // the IN-LOCK bytes, inside the critical section. A hold (AHEAD /
1335
+ // not comparable) or a refuse (unreadable running version) writes
1336
+ // nothing.
1337
+ const decision = decidePinWrite({
1338
+ pkg: FLAIR_MCP_PACKAGE,
1339
+ entry: `SessionStart hook in ${path}`,
1340
+ existingText: hook.command,
1341
+ runningVersion: flairCliVersion(),
1342
+ });
1343
+ if (decision.action !== "write") {
1344
+ outcome = { ok: false, path, changed: false, message: decision.line };
1345
+ return { hold: outcome.message };
1346
+ }
1347
+ const next = buildSessionStartHookCommand(legacy.agentId, legacy.flairUrl, {
1348
+ harness: hookHarnessFromSettingsPath(path),
1349
+ });
1350
+ if (next === hook.command) {
1351
+ outcome = { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1352
+ return { noop: outcome.message };
1353
+ }
1354
+ hook.command = next;
1355
+ return { write: encodeConfig(config) };
1176
1356
  }
1177
- const next = buildSessionStartHookCommand(legacy.agentId, legacy.flairUrl, {
1178
- harness: hookHarnessFromSettingsPath(path),
1179
- });
1180
- if (next === hook.command)
1181
- return { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1182
- hook.command = next;
1183
- writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
1184
- return { ok: true, path, changed: true, message: `rewrote the SessionStart hook in ${path} so a failure to resolve stays silent` };
1185
1357
  }
1358
+ outcome = { ok: false, path, changed: false, message: `no Flair SessionStart hook found in ${path}` };
1359
+ return { hold: outcome.message };
1360
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1361
+ if (result.status === "written") {
1362
+ return { ok: true, path, changed: true, message: `rewrote the SessionStart hook in ${path} so a failure to resolve stays silent` };
1186
1363
  }
1187
- return { ok: false, path, changed: false, message: `no Flair SessionStart hook found in ${path}` };
1364
+ const settled = outcome;
1365
+ if (settled)
1366
+ return settled;
1367
+ return { ok: false, path, changed: false, message: result.message };
1188
1368
  }
1189
1369
  catch (err) {
1190
1370
  const reason = err instanceof Error ? err.message : String(err);