@tpsdev-ai/flair 0.55.1 → 0.55.2

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.
@@ -23,7 +23,11 @@ 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
25
  import { ALL_CLIENTS, clientConfigPath, piSettingsPath, resolvePiExtensionPath, scanPiSettings, } from "./install/clients.js";
26
- import { FLAIR_MCP_PACKAGE, mcpServerSpec } from "./lib/mcp-spec.js";
26
+ import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
27
+ import { decidePinWrite } from "./lib/pin-write-guard.js";
28
+ import { withConfigCriticalSection } from "./lib/config-critical-section.js";
29
+ import { backupBytesTo, encodeConfig, parseSettingsBytes, } from "./lib/settings-bytes.js";
30
+ import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./lib/wiring-spec.js";
27
31
  // The exact substring `flair init` writes into CLAUDE.md (src/cli.ts, the
28
32
  // `init` action) and that the doctor check + fix both key off of.
29
33
  export const CLAUDE_MD_BOOTSTRAP_MARKER = "mcp__flair__bootstrap";
@@ -208,6 +212,13 @@ export function isFlairHookCommand(command) {
208
212
  // never a failure (see checkContinuityCaptureHooks / cli.ts's rendering).
209
213
  /** The exact substring identifying a Flair continuity-capture hook command. */
210
214
  export const CONTINUITY_CAPTURE_HOOK_MARKER = "flair-continuity-capture";
215
+ /**
216
+ * The npx invocation of the continuity marker — pinned (`@tpsdev-ai/flair-mcp@<v>`)
217
+ * or the unpinned form. Used by the continuity report so BOTH the pinned form
218
+ * (a fresh provision, flair#1778 2c-i-a3) and the older unpinned form read as
219
+ * the current shape, while an unsilenced / non-`-p` hand-edit still reads stale.
220
+ */
221
+ const CONTINUITY_INVOCATION_RE = /npx -y -p @tpsdev-ai\/flair-mcp(?:@[^\s"']+)? flair-continuity-capture/;
211
222
  /**
212
223
  * The PostToolUse matcher written alongside our hook entry — the EXACT
213
224
  * mutating-tool allowlist the capture binary enforces internally
@@ -223,8 +234,14 @@ export const CONTINUITY_POST_TOOL_USE_MATCHER = "Write|Edit|NotebookEdit|Bash";
223
234
  * (PostToolUse and Stop run the same binary; the payload's hook_event_name
224
235
  * tells it which fired). Same strict value allow-list as the SessionStart
225
236
  * builder — throws rather than emitting a quoted approximation.
237
+ *
238
+ * `pin` is the version the entry's OWN pin state calls for (flair#1778 2c-i-a3,
239
+ * continuity-preserve): a concrete version re-emits it verbatim so a repair
240
+ * never UNPINS a pinned entry, and `null`/omitted keeps the pre-#1143 unpinned
241
+ * form an unpinned entry already has. A fresh (absent) entry is provisioned
242
+ * pinned to the running CLI by the caller, matching today's MCP policy.
226
243
  */
227
- export function buildContinuityCaptureHookCommand(agentId, flairUrl) {
244
+ export function buildContinuityCaptureHookCommand(agentId, flairUrl, pin) {
228
245
  if (!isHookCommandValueSafe(agentId)) {
229
246
  throw new Error(`agent id '${agentId}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
230
247
  }
@@ -232,7 +249,8 @@ export function buildContinuityCaptureHookCommand(agentId, flairUrl) {
232
249
  throw new Error(`Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
233
250
  }
234
251
  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}`;
252
+ const spec = pin ? `@tpsdev-ai/flair-mcp@${pin}` : "@tpsdev-ai/flair-mcp";
253
+ const invocation = `${env} npx -y -p ${spec} ${CONTINUITY_CAPTURE_HOOK_MARKER}`;
236
254
  return `sh -c '${invocation} >/dev/null 2>/dev/null || true'`;
237
255
  }
238
256
  /** Does this command invoke the Flair continuity-capture binary at all? */
@@ -267,7 +285,7 @@ function continuityEventReport(config, event) {
267
285
  const command = typeof hook?.command === "string" ? hook.command : "";
268
286
  const matcher = typeof found.group?.matcher === "string" ? found.group.matcher : undefined;
269
287
  const shapeOk = hook?.type === "command" &&
270
- command.includes(`npx -y -p @tpsdev-ai/flair-mcp ${CONTINUITY_CAPTURE_HOOK_MARKER}`) &&
288
+ CONTINUITY_INVOCATION_RE.test(command) &&
271
289
  hookCommandIsSilenced(command);
272
290
  const matcherOk = event !== "PostToolUse" || matcher === CONTINUITY_POST_TOOL_USE_MATCHER;
273
291
  return { present: true, command, matcher, currentForm: shapeOk && matcherOk };
@@ -302,6 +320,37 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
302
320
  state = "stale";
303
321
  return { path, postToolUse, stop, state };
304
322
  }
323
+ /**
324
+ * The never-lower decision for ONE continuity event's entry, in
325
+ * continuity-preserve mode (flair#1778 2c-i-a3).
326
+ *
327
+ * `decidePinWrite` (the SAME a2 primitive — no second comparison idiom here) is
328
+ * consulted for EVERY arm:
329
+ * • hold / refuse → propagated verbatim (an AHEAD pin, a range/tag/
330
+ * unsupported spec, or an unreadable running version);
331
+ * • write, absent → the running CLI's version (provision pinned to it,
332
+ * today's MCP policy);
333
+ * • write, existing → the ENTRY'S OWN pin state, preserved — a pinned entry
334
+ * keeps its version (a repair never UNPINS it: Kern's
335
+ * finding), an unpinned entry stays unpinned. Continuity
336
+ * never repins a BEHIND entry UP; it repairs shape only.
337
+ */
338
+ function decideContinuityWrite(existingCommand, entryLabel) {
339
+ const decision = decidePinWrite({
340
+ pkg: FLAIR_MCP_PACKAGE,
341
+ entry: entryLabel,
342
+ existingText: existingCommand,
343
+ runningVersion: flairCliVersion(),
344
+ });
345
+ if (decision.action !== "write")
346
+ return decision;
347
+ if (existingCommand === null)
348
+ return decision; // absent → provision at the running CLI
349
+ const spec = decodeWiringSpec(existingCommand, FLAIR_MCP_PACKAGE);
350
+ if (isComparableWiringPin(spec))
351
+ return { action: "write", pin: wiringPinString(spec), line: null };
352
+ return { action: "write", pin: null, line: null }; // unpinned → repair, stay unpinned
353
+ }
305
354
  /**
306
355
  * Pure merge of the continuity pair into a parsed settings object — the ONE
307
356
  * mutation core both write paths (`flair doctor --fix` via
@@ -311,15 +360,32 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
311
360
  * groups and keys are preserved byte-identical; a group we don't own keeps
312
361
  * its matcher (our binary's internal allowlist still filters — the matcher is
313
362
  * an efficiency, not the control).
363
+ *
364
+ * CONTINUITY-PRESERVE (flair#1778 2c-i-a3): the version written is the entry's
365
+ * OWN pin state, so repairing a pinned entry never silently unpins it, and the
366
+ * a2 never-lower guard is consulted on every entry the write would replace.
367
+ * A hold/refuse on EITHER event yields `decision` set and the ORIGINAL config
368
+ * returned, so both arrays stay byte-identical.
314
369
  */
315
370
  export function computeContinuityHookInstall(config, agentId, flairUrl) {
316
- const command = buildContinuityCaptureHookCommand(agentId, flairUrl);
317
- const newConfig = JSON.parse(JSON.stringify(config ?? {}));
371
+ const original = config ?? {};
372
+ const newConfig = JSON.parse(JSON.stringify(original));
318
373
  const actions = { PostToolUse: "noop", Stop: "noop" };
319
374
  let changed = false;
375
+ let decision = null;
320
376
  newConfig.hooks = newConfig.hooks && typeof newConfig.hooks === "object" && !Array.isArray(newConfig.hooks) ? newConfig.hooks : {};
321
377
  for (const event of CONTINUITY_HOOK_EVENTS) {
322
378
  const existing = findContinuityEntry(newConfig, event);
379
+ const existingCommand = existing && typeof existing.group?.hooks?.[existing.hookIndex]?.command === "string"
380
+ ? existing.group.hooks[existing.hookIndex].command
381
+ : null;
382
+ const eventDecision = decideContinuityWrite(existingCommand, `${event} continuity capture hook`);
383
+ if (eventDecision.action !== "write") {
384
+ if (decision === null || eventDecision.action === "refuse")
385
+ decision = eventDecision;
386
+ continue;
387
+ }
388
+ const command = buildContinuityCaptureHookCommand(agentId, flairUrl, eventDecision.pin);
323
389
  if (existing) {
324
390
  const hook = existing.group.hooks[existing.hookIndex];
325
391
  const soleOwner = existing.group.hooks.length === 1;
@@ -342,7 +408,15 @@ export function computeContinuityHookInstall(config, agentId, flairUrl) {
342
408
  actions[event] = "add";
343
409
  changed = true;
344
410
  }
345
- return { changed, actions, newConfig };
411
+ if (decision !== null) {
412
+ return {
413
+ changed: false,
414
+ actions: { PostToolUse: "noop", Stop: "noop" },
415
+ newConfig: original,
416
+ decision,
417
+ };
418
+ }
419
+ return { changed, actions, newConfig, decision: null };
346
420
  }
347
421
  /**
348
422
  * Pure removal of the continuity pair — deletes ONLY our entries (marker
@@ -373,11 +447,28 @@ export function computeContinuityHookRemoval(config) {
373
447
  }
374
448
  return { changed, actions, newConfig };
375
449
  }
450
+ /**
451
+ * The four doctor hook writers printed `could not write/update <path>:
452
+ * <reason>` before the flair#1778 2c-i-c migration, where <reason> was the
453
+ * JSON.parse failure message. The shared parser (./lib/settings-bytes.js)
454
+ * reports the SAME failure as `malformed JSON in <path> (<reason>)`. Peeling
455
+ * that wrapper lets each migrated writer keep its exact pre-migration line
456
+ * (the brief's "keep the existing line wherever one exists"). Falls back to
457
+ * the parser's text unchanged if the shape ever differs.
458
+ */
459
+ function jsonFailureReason(path, parseError) {
460
+ const prefix = `malformed JSON in ${path} (`;
461
+ return parseError.startsWith(prefix) && parseError.endsWith(")")
462
+ ? parseError.slice(prefix.length, parseError.length - 1)
463
+ : parseError;
464
+ }
376
465
  /**
377
466
  * `flair doctor --fix` write path: register (or repair to current form) the
378
467
  * continuity pair in ~/.claude/settings.json. Merge-safe read-parse-write,
379
468
  * mirroring fixSessionStartHook — creates the file if absent, refuses on a
380
- * file it cannot parse.
469
+ * file it cannot parse. The write is CONTINUITY-PRESERVE (flair#1778 2c-i-a3):
470
+ * it keeps each entry's own pin state and consults the never-lower guard, so a
471
+ * repair never unpins a pinned entry; a hold/refuse writes nothing.
381
472
  */
382
473
  export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
383
474
  const path = join(homeDir, ".claude", "settings.json");
@@ -405,18 +496,36 @@ export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
405
496
  message: `Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`,
406
497
  };
407
498
  }
499
+ // Parent creation stays OUTSIDE the primitive: it needs the resolved parent
500
+ // to exist before it can observe an absent destination (flair#1778 2c-i-b).
501
+ // Everything from here (observe → decide → write) is ONE critical section.
408
502
  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
503
  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}')` };
504
+ let outcome = null;
505
+ const result = withConfigCriticalSection(path, (bytes) => {
506
+ const read = parseSettingsBytes(bytes, path);
507
+ if (read.parseError) {
508
+ outcome = { ok: false, path, changed: false, message: `could not write ${path}: ${jsonFailureReason(path, read.parseError)}` };
509
+ return { hold: outcome.message };
510
+ }
511
+ const { changed, newConfig, decision } = computeContinuityHookInstall(read.parsed ?? {}, agentId, flairUrl);
512
+ if (decision) {
513
+ outcome = { ok: true, path, changed: false, message: decision.line };
514
+ return { hold: decision.line };
515
+ }
516
+ if (!changed) {
517
+ outcome = { ok: true, path, changed: false, message: `continuity capture hooks already current in ${path}` };
518
+ return { noop: outcome.message };
519
+ }
520
+ return { write: encodeConfig(newConfig) };
521
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
522
+ if (result.status === "written") {
523
+ return { ok: true, path, changed: true, message: `wired the continuity capture hooks (PostToolUse + Stop) in ${path} (agent '${agentId}')` };
524
+ }
525
+ const settled = outcome;
526
+ if (settled)
527
+ return settled;
528
+ return { ok: false, path, changed: false, message: result.message };
420
529
  }
421
530
  catch (err) {
422
531
  const reason = err instanceof Error ? err.message : String(err);
@@ -427,21 +536,42 @@ export function fixContinuityCaptureHooks(homeDir, agentId, flairUrl) {
427
536
  * Symmetric removal path (`flair doctor --fix` when disabling / `flair hook
428
537
  * uninstall --continuity`). A no-op when nothing is wired — never creates a
429
538
  * file that didn't exist, refuses on a file it cannot parse.
539
+ *
540
+ * NOT a version writer (flair#1778 2c-i-a3): it only DELETES our entries and
541
+ * preserves every other byte (see the merge-safe removal test) — it never
542
+ * writes a version-carrying spec, so it cannot lower a pin and needs no guard.
430
543
  */
431
544
  export function removeContinuityCaptureHooks(homeDir) {
432
545
  const path = join(homeDir, ".claude", "settings.json");
546
+ // A pre-lock existence/emptiness probe: this removal writer must keep its
547
+ // exact "not enabled" line and take no lock (and no backup) where there is
548
+ // nothing to remove at all.
433
549
  const raw = readTextFile(path);
434
550
  if (!raw || !raw.trim()) {
435
551
  return { ok: true, path, changed: false, message: `no ${path} — continuity capture hooks are not enabled` };
436
552
  }
437
553
  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` };
554
+ let outcome = null;
555
+ const result = withConfigCriticalSection(path, (bytes) => {
556
+ const read = parseSettingsBytes(bytes, path);
557
+ if (read.parseError) {
558
+ outcome = { ok: false, path, changed: false, message: `could not update ${path}: ${jsonFailureReason(path, read.parseError)}` };
559
+ return { hold: outcome.message };
560
+ }
561
+ const { changed, newConfig } = computeContinuityHookRemoval(read.parsed ?? {});
562
+ if (!changed) {
563
+ outcome = { ok: true, path, changed: false, message: `no continuity capture hooks found in ${path} — nothing to remove` };
564
+ return { noop: outcome.message };
565
+ }
566
+ return { write: encodeConfig(newConfig) };
567
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
568
+ if (result.status === "written") {
569
+ return { ok: true, path, changed: true, message: `removed the continuity capture hooks (PostToolUse + Stop) from ${path}` };
442
570
  }
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}` };
571
+ const settled = outcome;
572
+ if (settled)
573
+ return settled;
574
+ return { ok: false, path, changed: false, message: result.message };
445
575
  }
446
576
  catch (err) {
447
577
  const reason = err instanceof Error ? err.message : String(err);
@@ -524,23 +654,24 @@ export function readClientMcpBlock(clientId, homeDir) {
524
654
  function readJsonFlairBlock(configPath) {
525
655
  const raw = readTextFile(configPath);
526
656
  if (!raw || !raw.trim())
527
- return { present: false, configPath };
657
+ return { present: false, entryExists: false, configPath };
528
658
  try {
529
659
  const config = JSON.parse(raw);
530
660
  const flair = config?.mcpServers?.flair;
531
661
  if (!flair || typeof flair !== "object")
532
- return { present: false, configPath };
662
+ return { present: false, entryExists: false, configPath };
533
663
  const agentId = typeof flair.env?.FLAIR_AGENT_ID === "string" && flair.env.FLAIR_AGENT_ID ? flair.env.FLAIR_AGENT_ID : undefined;
534
664
  const flairUrl = typeof flair.env?.FLAIR_URL === "string" && flair.env.FLAIR_URL ? flair.env.FLAIR_URL : undefined;
535
665
  // FLAIR_URL optional — see readClientMcpBlock's doc (flair#1287). Any
536
666
  // extra fields the client's own tooling writes (e.g. `claude mcp add`'s
537
667
  // `type: "stdio"`) are irrelevant to presence and deliberately ignored.
538
668
  const present = !!agentId;
539
- return { present, configPath, agentId, flairUrl, urlDefaulted: present && !flairUrl };
669
+ // entryExists is true here: the flair key was found and is an object.
670
+ return { present, entryExists: true, configPath, agentId, flairUrl, urlDefaulted: present && !flairUrl };
540
671
  }
541
672
  catch {
542
673
  // Malformed JSON — treat as "not present", never throw.
543
- return { present: false, configPath };
674
+ return { present: false, entryExists: false, configPath };
544
675
  }
545
676
  }
546
677
  /**
@@ -565,9 +696,9 @@ function readJsonFlairBlock(configPath) {
565
696
  function readCodexFlairBlock(configPath) {
566
697
  const raw = readTextFile(configPath);
567
698
  if (!raw)
568
- return { present: false, configPath };
699
+ return { present: false, entryExists: false, configPath };
569
700
  const scanned = scanCodexFlairBlock(raw);
570
- return { present: scanned.present, configPath, agentId: scanned.agentId, flairUrl: scanned.flairUrl, urlDefaulted: scanned.urlDefaulted };
701
+ return { present: scanned.present, entryExists: scanned.entryExists, configPath, agentId: scanned.agentId, flairUrl: scanned.flairUrl, urlDefaulted: scanned.urlDefaulted };
571
702
  }
572
703
  /**
573
704
  * The two env keys the codex scanner ever looks for, each with LITERAL
@@ -620,7 +751,7 @@ function scanCodexEnvValue(block, key) {
620
751
  function scanCodexFlairBlock(raw) {
621
752
  const startMatch = raw.match(/^\[mcp_servers\.flair\]\s*$/m);
622
753
  if (!startMatch || startMatch.index === undefined)
623
- return { present: false };
754
+ return { present: false, entryExists: false };
624
755
  const rest = raw.slice(startMatch.index);
625
756
  const lines = rest.split("\n");
626
757
  const blockLines = [lines[0]];
@@ -636,7 +767,7 @@ function scanCodexFlairBlock(raw) {
636
767
  // FLAIR_URL optional — same contract as readJsonFlairBlock (flair#1287);
637
768
  // docs/mcp-clients.md's own Codex snippet sets only FLAIR_AGENT_ID.
638
769
  const present = !!agentId;
639
- return { present, agentId, flairUrl, urlDefaulted: present && !flairUrl };
770
+ return { present, entryExists: true, agentId, flairUrl, urlDefaulted: present && !flairUrl };
640
771
  }
641
772
  export function checkPiFlairWiring(homeDir, cwd) {
642
773
  const userPath = withHome(homeDir, () => piSettingsPath());
@@ -737,6 +868,10 @@ export function checkClaudeMdBootstrap(cwd, homeDir) {
737
868
  * Append the bootstrap instruction to `${cwd}/CLAUDE.md` (creating it if
738
869
  * absent). Idempotent — safe to call twice; a second call is a no-op that
739
870
  * still reports ok:true.
871
+ *
872
+ * NOT a version writer (flair#1778 2c-i-a3): it writes a CLAUDE.md prose line,
873
+ * not a wiring entry — the block carries no `<pkg>@<spec>`, so there is no pin
874
+ * to lower and nothing for the guard to decide.
740
875
  */
741
876
  export function fixClaudeMdBootstrap(cwd) {
742
877
  const path = join(cwd, "CLAUDE.md");
@@ -788,27 +923,16 @@ export function checkSessionStartHook(homeDir, settingsPath) {
788
923
  return { present: false, path };
789
924
  }
790
925
  }
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
926
  /**
808
927
  * 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.
928
+ * string or package.json.
929
+ *
930
+ * flair#1778 slice 2c-i-a1: a THIN ADAPTER over the interim `WiringSpec` model
931
+ * (`./lib/wiring-spec.js`). For a concrete `version` token the result is
932
+ * byte-identical to before; for `range-or-tag` / `unsupported` / `malformed`
933
+ * the spec is now returned as its RAW token (PRESENT, not comparable) instead
934
+ * of being dropped as `null`/absent. `none` (unpinned) still contributes
935
+ * nothing. Callers that have migrated read `WiringSpec` directly.
812
936
  *
813
937
  * flair#1383: doctor must read the actual installed pins, not infer age
814
938
  * from "pin !== CLI version".
@@ -816,51 +940,51 @@ export function normalizeDeclaredPinVersion(raw) {
816
940
  export function extractFlairPackagePins(text) {
817
941
  if (typeof text !== "string")
818
942
  return [];
819
- const out = [];
943
+ const found = [];
820
944
  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;
945
+ for (const pkg of ["flair-mcp", "flair-client"]) {
946
+ for (const spec of decodeWiringSpecs(text, `@tpsdev-ai/${pkg}`)) {
947
+ const version = wiringPinString(spec);
948
+ if (version === null)
949
+ continue;
950
+ const key = `${pkg}@${version}`;
951
+ if (seen.has(key))
952
+ continue;
953
+ seen.add(key);
954
+ // Preserve the ORDER pins appear in the text (the old extractor's
955
+ // match-position order), not the order packages are enumerated.
956
+ const at = text.indexOf(spec.raw);
957
+ found.push({ at: at < 0 ? Number.MAX_SAFE_INTEGER : at, pin: { package: pkg, version } });
958
+ }
959
+ }
960
+ found.sort((a, b) => a.at - b.at);
961
+ return found.map((f) => f.pin);
837
962
  }
838
963
  /**
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.
964
+ * Extract the `@tpsdev-ai/flair-mcp` spec from any wiring string — a client MCP
965
+ * `args` array, a Codex TOML args line, or a SessionStart hook command. A
966
+ * concrete version returns its version; a range/tag/unsupported/malformed spec
967
+ * returns its RAW token (present-not-comparable); a bare/unpinned spec returns
968
+ * null.
847
969
  */
848
970
  export function extractFlairMcpPin(text) {
849
971
  return extractFlairPackagePins(text).find((p) => p.package === "flair-mcp")?.version ?? null;
850
972
  }
851
973
  export function detectWiredFlairMcp(homeDir) {
852
974
  let wired = false;
853
- let pinnedVersion = null;
975
+ // flair#1778 slice 2c-i-a1: decode EVERY wired entry into its own WiringSpec
976
+ // — one per entry, never collapsing to the first. A bare/unpinned entry still
977
+ // establishes `wired` (today's outcome) but contributes no spec.
978
+ const specs = [];
854
979
  // The package name only ever appears in a Flair MCP wiring block, so its
855
980
  // presence in a config's text is a reliable "flair-mcp is wired here" signal.
856
981
  const note = (text) => {
857
982
  if (!text || !text.includes(FLAIR_MCP_PACKAGE))
858
983
  return;
859
984
  wired = true;
860
- if (!pinnedVersion) {
861
- const pin = extractFlairMcpPin(text);
862
- if (pin)
863
- pinnedVersion = pin;
985
+ for (const spec of decodeWiringSpecs(text, FLAIR_MCP_PACKAGE)) {
986
+ if (spec.token.kind !== "none")
987
+ specs.push(spec);
864
988
  }
865
989
  };
866
990
  // 1. Every known client's MCP config — a wired flair block carries the spec.
@@ -884,6 +1008,16 @@ export function detectWiredFlairMcp(homeDir) {
884
1008
  if (hook.present && isFlairHookCommand(hook.command ?? ""))
885
1009
  note(hook.command);
886
1010
  }
1011
+ // A concrete version wins (today's precedence, over the SAME ordered entry
1012
+ // list); otherwise a present-not-comparable spec is reported as its raw token
1013
+ // rather than dropped as absent. A bare entry alone leaves `pinnedVersion`
1014
+ // null — unchanged.
1015
+ const firstVersion = specs.find((s) => s.token.kind === "version");
1016
+ const pinnedVersion = firstVersion
1017
+ ? firstVersion.token.value
1018
+ : specs.length > 0
1019
+ ? wiringPinString(specs[0])
1020
+ : null;
887
1021
  return { wired, pinnedVersion };
888
1022
  }
889
1023
  /** The `@tpsdev-ai/flair-mcp` version pinned in a client's MCP config, or null
@@ -945,29 +1079,59 @@ export function fixSessionStartHook(homeDir, agentId, settingsPath) {
945
1079
  message: `agent id '${agentId}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`,
946
1080
  };
947
1081
  }
1082
+ // Parent creation stays OUTSIDE the primitive (flair#1778 2c-i-b): the
1083
+ // primitive needs the resolved parent to exist to observe an absent
1084
+ // destination. Everything from here is ONE critical section.
948
1085
  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
1086
  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}')` };
1087
+ let outcome = null;
1088
+ const result = withConfigCriticalSection(path, (bytes) => {
1089
+ const read = parseSettingsBytes(bytes, path);
1090
+ if (read.parseError) {
1091
+ outcome = { ok: false, message: `could not write ${path}: ${jsonFailureReason(path, read.parseError)}` };
1092
+ return { hold: outcome.message };
1093
+ }
1094
+ const config = read.parsed ?? {};
1095
+ config.hooks = config.hooks && typeof config.hooks === "object" ? config.hooks : {};
1096
+ config.hooks.SessionStart = Array.isArray(config.hooks.SessionStart) ? config.hooks.SessionStart : [];
1097
+ const alreadyPresent = config.hooks.SessionStart.some((group) => Array.isArray(group?.hooks) &&
1098
+ group.hooks.some((h) => typeof h?.command === "string" && h.command.includes(SESSION_START_HOOK_MARKER)));
1099
+ if (alreadyPresent) {
1100
+ outcome = { ok: true, message: `already present in ${path}` };
1101
+ return { noop: outcome.message };
1102
+ }
1103
+ // flair#1778 2c-i-a3: the ADD arm is a version-carrying write (the
1104
+ // command pins @tpsdev-ai/flair-mcp). Consult the ONE never-lower guard
1105
+ // with an ABSENT entry — on the IN-LOCK bytes, inside the critical
1106
+ // section — a healthy version still writes (pinned up to the running
1107
+ // CLI), an unreadable one refuses by name and creates nothing.
1108
+ const decision = decidePinWrite({
1109
+ pkg: FLAIR_MCP_PACKAGE,
1110
+ entry: `SessionStart hook in ${path}`,
1111
+ existingText: null,
1112
+ runningVersion: flairCliVersion(),
1113
+ });
1114
+ if (decision.action !== "write") {
1115
+ outcome = { ok: false, message: decision.line };
1116
+ return { hold: outcome.message };
1117
+ }
1118
+ config.hooks.SessionStart.push({
1119
+ hooks: [
1120
+ {
1121
+ type: "command",
1122
+ command: buildSessionStartHookCommand(agentId, undefined, { harness: hookHarnessFromSettingsPath(path) }),
1123
+ },
1124
+ ],
1125
+ });
1126
+ return { write: encodeConfig(config) };
1127
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1128
+ if (result.status === "written") {
1129
+ return { ok: true, path, message: `added SessionStart hook to ${path} (agent '${agentId}')` };
1130
+ }
1131
+ const settled = outcome;
1132
+ if (settled)
1133
+ return { ok: settled.ok, path, message: settled.message };
1134
+ return { ok: false, path, message: result.message };
971
1135
  }
972
1136
  catch (err) {
973
1137
  const reason = err instanceof Error ? err.message : String(err);
@@ -1144,47 +1308,81 @@ export function classifyHookReadiness(report) {
1144
1308
  */
1145
1309
  export function upgradeSessionStartHookCommand(homeDir, settingsPath) {
1146
1310
  const path = settingsPath ?? join(homeDir, ".claude", "settings.json");
1311
+ // A pre-lock existence/emptiness probe: this repair writer never creates the
1312
+ // file or its parent, and must keep its exact "no <path> to update" line and
1313
+ // take no lock (and no backup) where there is no destination at all.
1314
+ const raw = readTextFile(path);
1315
+ if (!raw || !raw.trim())
1316
+ return { ok: false, path, changed: false, message: `no ${path} to update` };
1147
1317
  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))
1318
+ let outcome = null;
1319
+ const result = withConfigCriticalSection(path, (bytes) => {
1320
+ const read = parseSettingsBytes(bytes, path);
1321
+ if (read.parseError) {
1322
+ outcome = { ok: false, path, changed: false, message: `could not update ${path}: ${jsonFailureReason(path, read.parseError)}` };
1323
+ return { hold: outcome.message };
1324
+ }
1325
+ const config = read.parsed ?? {};
1326
+ const groups = config?.hooks?.SessionStart;
1327
+ if (!Array.isArray(groups)) {
1328
+ outcome = { ok: false, path, changed: false, message: `no SessionStart hooks in ${path}` };
1329
+ return { hold: outcome.message };
1330
+ }
1331
+ for (const group of groups) {
1332
+ const hooks = group?.hooks;
1333
+ if (!Array.isArray(hooks))
1161
1334
  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
- };
1335
+ for (const hook of hooks) {
1336
+ if (typeof hook?.command !== "string" || !hook.command.includes(SESSION_START_HOOK_MARKER))
1337
+ continue;
1338
+ // Already absorbing its own failures — nothing to repair, whether we
1339
+ // wrote it or the user did. Checked BEFORE the legacy match so a second
1340
+ // run is a clean no-op rather than "that isn't the command we wrote".
1341
+ if (hookCommandIsSilenced(hook.command)) {
1342
+ outcome = { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1343
+ return { noop: outcome.message };
1344
+ }
1345
+ const legacy = parseLegacySessionStartHookCommand(hook.command);
1346
+ if (!legacy) {
1347
+ outcome = { ok: false, path, changed: false, message: `the SessionStart hook in ${path} is not the command Flair wrote — leaving it untouched` };
1348
+ return { hold: outcome.message };
1349
+ }
1350
+ // flair#1778 2c-i-a3: the repair rewrites the entry to a version-
1351
+ // carrying command, so it consults the never-lower guard first — on
1352
+ // the IN-LOCK bytes, inside the critical section. A hold (AHEAD /
1353
+ // not comparable) or a refuse (unreadable running version) writes
1354
+ // nothing.
1355
+ const decision = decidePinWrite({
1356
+ pkg: FLAIR_MCP_PACKAGE,
1357
+ entry: `SessionStart hook in ${path}`,
1358
+ existingText: hook.command,
1359
+ runningVersion: flairCliVersion(),
1360
+ });
1361
+ if (decision.action !== "write") {
1362
+ outcome = { ok: false, path, changed: false, message: decision.line };
1363
+ return { hold: outcome.message };
1364
+ }
1365
+ const next = buildSessionStartHookCommand(legacy.agentId, legacy.flairUrl, {
1366
+ harness: hookHarnessFromSettingsPath(path),
1367
+ });
1368
+ if (next === hook.command) {
1369
+ outcome = { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1370
+ return { noop: outcome.message };
1371
+ }
1372
+ hook.command = next;
1373
+ return { write: encodeConfig(config) };
1176
1374
  }
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
1375
  }
1376
+ outcome = { ok: false, path, changed: false, message: `no Flair SessionStart hook found in ${path}` };
1377
+ return { hold: outcome.message };
1378
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1379
+ if (result.status === "written") {
1380
+ return { ok: true, path, changed: true, message: `rewrote the SessionStart hook in ${path} so a failure to resolve stays silent` };
1186
1381
  }
1187
- return { ok: false, path, changed: false, message: `no Flair SessionStart hook found in ${path}` };
1382
+ const settled = outcome;
1383
+ if (settled)
1384
+ return settled;
1385
+ return { ok: false, path, changed: false, message: result.message };
1188
1386
  }
1189
1387
  catch (err) {
1190
1388
  const reason = err instanceof Error ? err.message : String(err);