@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.
@@ -19,17 +19,38 @@
19
19
  // All paths are resolved cross-platform (Linux included) via standard
20
20
  // per-client locations under $HOME / $XDG_CONFIG_HOME.
21
21
  // ---- Detection helpers ----------------------------------------------------------
22
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
22
+ import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
23
23
  import { homedir } from "node:os";
24
24
  import { dirname, join } from "node:path";
25
- import { flairCliVersion, isResolvedVersion, mcpServerSpec } from "../lib/mcp-spec.js";
25
+ import { FLAIR_MCP_PACKAGE, flairCliVersion, isResolvedVersion, mcpServerSpec } from "../lib/mcp-spec.js";
26
+ import { decodeWiringSpec, wiringPinString } from "../lib/wiring-spec.js";
27
+ import { decidePinWrite } from "../lib/pin-write-guard.js";
28
+ import { pinWriteWouldLowerOrIsUnknown, comparePinVersions } from "../lib/upgrade-status.js";
29
+ import { withConfigCriticalSection } from "../lib/config-critical-section.js";
30
+ import { backupBytesTo, encodeConfig, encodeText, parseSettingsBytes } from "../lib/settings-bytes.js";
31
+ /**
32
+ * The JSON.parse reason embedded in the shared parser's
33
+ * `malformed JSON in <path> (<reason>)` text, so the client writers can keep
34
+ * their pre-migration `...: <reason>` lines byte-identical.
35
+ */
36
+ function jsonFailureReason(path, parseError) {
37
+ const prefix = `malformed JSON in ${path} (`;
38
+ return parseError.startsWith(prefix) && parseError.endsWith(")")
39
+ ? parseError.slice(prefix.length, parseError.length - 1)
40
+ : parseError;
41
+ }
42
+ /** The pre-migration manual-wiring line (kept byte-identical). */
43
+ function manualWireMessage(label, display, reason, env) {
44
+ return (`${label}: manual wiring needed (could not write ${display}: ${reason}).\n` +
45
+ ` Add this to ${display}:\n${indent(jsonSnippet(env))}`);
46
+ }
26
47
  /**
27
48
  * Resolve the user's home dir. Prefer the live HOME/USERPROFILE env over
28
49
  * os.homedir(), which caches the value at process start and so ignores a
29
50
  * runtime HOME override — same convention as src/cli.ts ("so tests can
30
51
  * override"). Production behavior is unchanged (HOME is set on every OS).
31
52
  */
32
- function resolveHome() {
53
+ export function resolveHome() {
33
54
  return process.env.HOME || process.env.USERPROFILE || homedir();
34
55
  }
35
56
  /**
@@ -116,8 +137,13 @@ function detectBin(bin) {
116
137
  * Code array fallback were all wired unpinned while only the inline Claude
117
138
  * Code path in cli.ts got the pin it was documented to get (flair#907).
118
139
  */
119
- function flairMcpEntry(env) {
140
+ function flairMcpEntry(env, opts = {}) {
120
141
  return {
142
+ // flair#1778 2c-i-d1: Claude Code's own writer (init) has always written
143
+ // `type: "stdio"`; the shared entry builder KEEPS it for Claude Code so
144
+ // neither writer strips it from users' files. It is optional for Claude
145
+ // Code (an omitted type defaults to stdio) — see the JSON-client docs.
146
+ ...(opts.stdioType ? { type: "stdio" } : {}),
121
147
  command: "npx",
122
148
  args: ["-y", mcpServerSpec()],
123
149
  env: {
@@ -196,17 +222,20 @@ export function removeCodexFlairBlock(raw) {
196
222
  * CURRENT pinned mcpServerSpec()? Pure string scan — no TOML parser needed
197
223
  * (same rationale as codexConfigHasFlairSection).
198
224
  */
199
- function codexFlairSectionHasCurrentPin(raw) {
225
+ function codexFlairSectionText(raw) {
200
226
  const idx = raw.indexOf("[mcp_servers.flair]");
201
227
  if (idx === -1)
202
- return false;
228
+ return null;
203
229
  const after = raw.slice(idx);
204
230
  // Find the end of the section: the next top-level [header] that is NOT a
205
231
  // sub-table of mcp_servers.flair (e.g. [mcp_servers.flair.env] is part of
206
232
  // the same logical section and must not terminate the scan).
207
233
  const nextHeader = after.slice("[mcp_servers.flair]".length).search(/\n\[(?!mcp_servers\.flair\.)/);
208
- const section = nextHeader === -1 ? after : after.slice(0, "[mcp_servers.flair]".length + nextHeader);
209
- return section.includes(mcpServerSpec());
234
+ return nextHeader === -1 ? after : after.slice(0, "[mcp_servers.flair]".length + nextHeader);
235
+ }
236
+ function codexFlairSectionHasCurrentPin(raw) {
237
+ const section = codexFlairSectionText(raw);
238
+ return section !== null && section.includes(mcpServerSpec());
210
239
  }
211
240
  /**
212
241
  * flair#1135: replace the existing `[mcp_servers.flair]` TOML section with a
@@ -225,56 +254,569 @@ function replaceCodexFlairBlock(raw, env) {
225
254
  const sep = rest.length === 0 ? "" : rest.startsWith("\n") ? "" : "\n";
226
255
  return before + newBlock + sep + rest;
227
256
  }
257
+ /** Resolve the display form (~/...) of a config path against the live home. */
258
+ function displayPath(configPath) {
259
+ const home = resolveHome();
260
+ return configPath.startsWith(home) ? "~" + configPath.slice(home.length) : configPath;
261
+ }
228
262
  /**
229
- * Merge the Flair MCP server into a JSON config file with an `mcpServers` map.
263
+ * Merge the Flair MCP server into a JSON config file with an `mcpServers` map,
264
+ * as ONE critical section: observe → decide on the IN-LOCK bytes → write.
230
265
  * Creates the file (and parent dir) if absent; preserves existing servers and
231
- * any other top-level keys. Returns ok:true only when the file was written.
266
+ * any other top-level keys.
232
267
  */
268
+ function wireJsonMcpCore(configPath, label, env, opts = {}) {
269
+ const display = displayPath(configPath);
270
+ const state = { existed: false, entryPresent: false, refreshed: false };
271
+ let settled = null;
272
+ // Parent creation stays OUTSIDE the primitive (it needs the resolved parent
273
+ // to observe an absent destination). Everything from here — observe → decide
274
+ // on the IN-LOCK bytes → write — is ONE critical section (flair#1778 2c-i-d1).
275
+ try {
276
+ mkdirSync(dirname(configPath), { recursive: true });
277
+ const result = withConfigCriticalSection(configPath, (bytes) => {
278
+ state.existed = bytes !== null;
279
+ const read = parseSettingsBytes(bytes, configPath);
280
+ if (read.parseError) {
281
+ settled = { kind: "manual", existed: state.existed, entryPresent: false, refreshed: false, line: null, reason: jsonFailureReason(configPath, read.parseError) };
282
+ return { hold: settled.reason };
283
+ }
284
+ const config = read.parsed ?? {};
285
+ config.mcpServers = config.mcpServers || {};
286
+ const existing = config.mcpServers.flair;
287
+ state.entryPresent = existing !== undefined && existing !== null;
288
+ const currentSpec = mcpServerSpec();
289
+ const existingArgs = existing?.args;
290
+ const argsMatch = Array.isArray(existingArgs) && existingArgs.includes(currentSpec);
291
+ const urlAgentMatch = existing && existing.env?.FLAIR_URL === env.FLAIR_URL && existing.env?.FLAIR_AGENT_ID === env.FLAIR_AGENT_ID;
292
+ // flair#1135: the pin in `args` must match the current mcpServerSpec().
293
+ // A matching pin stays a no-op (idempotent); only a stale pin triggers a re-write.
294
+ if (urlAgentMatch && argsMatch) {
295
+ settled = { kind: "already", existed: state.existed, entryPresent: state.entryPresent, refreshed: false, line: null, reason: null };
296
+ return { noop: `${label}: already wired in ${display}` };
297
+ }
298
+ // flair#1778 slice 2c-i-a2: a mismatch above is NOT automatically a
299
+ // re-write — never LOWER the existing pin, and never overwrite a
300
+ // range/tag/unsupported spec (see pin-write-guard.ts for the matrix).
301
+ // The guard runs on the IN-LOCK parse, inside the critical section.
302
+ const decision = decidePinWrite({
303
+ pkg: FLAIR_MCP_PACKAGE,
304
+ entry: `${label} config ${display}`,
305
+ existingText: existing ? JSON.stringify(existing) : null,
306
+ runningVersion: flairCliVersion(),
307
+ });
308
+ if (decision.action !== "write") {
309
+ settled = {
310
+ kind: decision.action === "hold" ? "held" : "refused",
311
+ existed: state.existed,
312
+ entryPresent: state.entryPresent,
313
+ refreshed: false,
314
+ line: decision.line,
315
+ reason: null,
316
+ };
317
+ return { hold: decision.line };
318
+ }
319
+ state.refreshed = !!urlAgentMatch;
320
+ config.mcpServers.flair = flairMcpEntry(env, opts);
321
+ return { write: encodeConfig(config) };
322
+ }, { backup: (bytes) => backupBytesTo(configPath, bytes) });
323
+ if (result.status === "written") {
324
+ return { kind: "written", existed: state.existed, entryPresent: true, refreshed: state.refreshed, line: null, reason: null };
325
+ }
326
+ const s = settled;
327
+ if (s)
328
+ return s;
329
+ // held (observation change) or refused (lock / backup): the pre-migration
330
+ // manual-wiring line, naming the reason.
331
+ return { kind: "manual", existed: state.existed, entryPresent: state.entryPresent, refreshed: false, line: null, reason: result.message };
332
+ }
333
+ catch (err) {
334
+ const reason = err instanceof Error ? err.message : String(err);
335
+ return { kind: "manual", existed: state.existed, entryPresent: state.entryPresent, refreshed: false, line: null, reason };
336
+ }
337
+ }
338
+ /** The pre-migration ok/message collapse of `wireJsonMcpCore`, unchanged for
339
+ * the Gemini / Cursor / Antigravity (and Claude Code array-fallback) callers. */
233
340
  function wireJsonMcp(configPath, label, env,
234
341
  // The parenthetical appended to a successful wire/refresh message. Defaults to
235
342
  // the confident "restart <label> to pick it up". A client whose end-to-end
236
343
  // pickup Flair has NOT verified (Antigravity — flair#1209) passes an honest
237
344
  // note instead, so the message claims only what it did (wrote the config), not
238
345
  // that the client will read it.
239
- pickupNote) {
240
- const home = resolveHome();
241
- const display = configPath.startsWith(home) ? "~" + configPath.slice(home.length) : configPath;
346
+ pickupNote, opts = {}) {
347
+ const display = displayPath(configPath);
242
348
  const note = pickupNote ?? `restart ${label} to pick it up`;
243
- try {
244
- let config = {};
245
- if (existsSync(configPath)) {
246
- const raw = readFileSync(configPath, "utf-8").trim();
247
- if (raw)
248
- config = JSON.parse(raw);
249
- }
250
- config.mcpServers = config.mcpServers || {};
251
- const existing = config.mcpServers.flair;
252
- const currentSpec = mcpServerSpec();
253
- const existingArgs = existing?.args;
254
- const argsMatch = Array.isArray(existingArgs) && existingArgs.includes(currentSpec);
255
- const urlAgentMatch = existing && existing.env?.FLAIR_URL === env.FLAIR_URL && existing.env?.FLAIR_AGENT_ID === env.FLAIR_AGENT_ID;
256
- // flair#1135: the pin in `args` must match the current mcpServerSpec().
257
- // A matching pin stays a no-op (idempotent); only a stale pin triggers a re-write.
258
- if (urlAgentMatch && argsMatch) {
349
+ const r = wireJsonMcpCore(configPath, label, env, opts);
350
+ switch (r.kind) {
351
+ case "written":
352
+ return { ok: true, message: `${label}: ${r.refreshed ? "refreshed pin in" : "wired"} ${display} (${note})` };
353
+ case "already":
259
354
  return { ok: true, message: `${label}: already wired in ${display}` };
355
+ case "held":
356
+ case "refused":
357
+ return { ok: true, message: r.line };
358
+ case "manual":
359
+ return { ok: false, message: manualWireMessage(label, display, r.reason, env) };
360
+ }
361
+ }
362
+ function indent(s) {
363
+ return s.split("\n").map((l) => ` ${l}`).join("\n");
364
+ }
365
+ // ── Pin-only JSON MCP re-pin (flair#1834 A1) ────────────────────────────────
366
+ //
367
+ // `flair upgrade`'s refresh and `flair doctor --fix`'s targeted re-pin must
368
+ // change ONLY the `@tpsdev-ai/flair-mcp` element of an already-wired entry's
369
+ // `args`. The full wire functions (`wireJsonMcpCore` above) REBUILD the whole
370
+ // entry from a `WireEnv`, so using one for a refresh rewrote FLAIR_AGENT_ID,
371
+ // FLAIR_URL and every other key from a host-wide guess — flair#1834's defect
372
+ // (a 0.55.1 deploy rewrote every wired client's agent id to the first key in
373
+ // ~/.lair/keys). This writer never takes an identity: it locates the one
374
+ // package argument, guards it against lowering, replaces just that array
375
+ // element, and leaves every other byte of the parsed entry deep-equal.
376
+ /**
377
+ * flair#1834 A1 round 2 (Kern): detect duplicate object keys by DECODED key
378
+ * name, per object, on the path root → mcpServers → flair entry → env.
379
+ *
380
+ * A literal raw scan (`/"flair"\s*:/`) counts ZERO for a Unicode-escaped key
381
+ * (`"\u0066lair"` decodes to `flair`). `JSON.parse` keeps the last duplicate,
382
+ * so the writer would re-pin and silently DROP the shadowed entry's bytes,
383
+ * evading the "duplicate → HOLD, bytes untouched" contract. A `JSON.parse`
384
+ * reviver cannot see it either — the duplicates are already collapsed. So this
385
+ * walks the raw text with an escape-aware tokenizer.
386
+ *
387
+ * Returns the path of the offending object (e.g. "mcpServers.flair") or null.
388
+ */
389
+ function findDuplicateOnPath(raw) {
390
+ const IN_SCOPE = (path) => path.length === 0 ||
391
+ (path.length === 1 && path[0] === "mcpServers") ||
392
+ (path.length === 2 && path[0] === "mcpServers" && path[1] === "flair") ||
393
+ (path.length === 3 && path[0] === "mcpServers" && path[1] === "flair" && path[2] === "env");
394
+ let i = 0;
395
+ const n = raw.length;
396
+ let found = null;
397
+ const ws = () => { while (i < n && /\s/.test(raw[i]))
398
+ i++; };
399
+ const readString = () => {
400
+ const start = i;
401
+ i++; // opening quote
402
+ while (i < n) {
403
+ const c = raw[i];
404
+ if (c === "\\") {
405
+ i += 2;
406
+ continue;
407
+ }
408
+ if (c === '"') {
409
+ i++;
410
+ break;
411
+ }
412
+ i++;
413
+ }
414
+ const token = raw.slice(start, i);
415
+ try {
416
+ return JSON.parse(token);
417
+ }
418
+ catch {
419
+ return token.slice(1, -1);
420
+ }
421
+ };
422
+ const parseValue = (path) => {
423
+ ws();
424
+ const c = raw[i];
425
+ if (c === "{")
426
+ return parseObject(path);
427
+ if (c === "[")
428
+ return parseArray(path);
429
+ if (c === '"') {
430
+ readString();
431
+ return;
432
+ }
433
+ while (i < n && !",}]".includes(raw[i]) && !/\s/.test(raw[i]))
434
+ i++;
435
+ };
436
+ const parseArray = (path) => {
437
+ i++; // [
438
+ ws();
439
+ if (raw[i] === "]") {
440
+ i++;
441
+ return;
442
+ }
443
+ for (;;) {
444
+ parseValue(path);
445
+ ws();
446
+ if (raw[i] === ",") {
447
+ i++;
448
+ continue;
449
+ }
450
+ if (raw[i] === "]") {
451
+ i++;
452
+ break;
453
+ }
454
+ return; // malformed — let the parser report it
455
+ }
456
+ };
457
+ const parseObject = (path) => {
458
+ i++; // {
459
+ const seen = new Set();
460
+ let dup = false;
461
+ ws();
462
+ if (raw[i] === "}") {
463
+ i++;
464
+ return;
465
+ }
466
+ for (;;) {
467
+ ws();
468
+ if (raw[i] !== '"')
469
+ return; // malformed
470
+ const key = readString();
471
+ ws();
472
+ if (raw[i] !== ":")
473
+ return;
474
+ i++;
475
+ if (seen.has(key))
476
+ dup = true;
477
+ else
478
+ seen.add(key);
479
+ parseValue([...path, key]);
480
+ ws();
481
+ if (raw[i] === ",") {
482
+ i++;
483
+ continue;
484
+ }
485
+ if (raw[i] === "}") {
486
+ i++;
487
+ break;
488
+ }
489
+ return; // malformed
490
+ }
491
+ if (dup && IN_SCOPE(path) && found === null)
492
+ found = path.length === 0 ? "(root)" : path.join(".");
493
+ };
494
+ parseValue([]);
495
+ return found;
496
+ }
497
+ /** True when an `args` element names the Flair MCP package (bare or pinned). */
498
+ function argNamesFlairPackage(arg) {
499
+ return arg === FLAIR_MCP_PACKAGE || arg.startsWith(`${FLAIR_MCP_PACKAGE}@`);
500
+ }
501
+ /** True when an `args` element looks like some OTHER scoped npm package — a
502
+ * signal we cannot safely assume the entry is ours to touch (design item 4:
503
+ * "any other scoped package name → HOLD"). */
504
+ function argIsOtherScopedPackage(arg) {
505
+ return /^@[^/\s]+\/[A-Za-z0-9._-]+(?:@[^\s]*)?$/.test(arg) && !argNamesFlairPackage(arg);
506
+ }
507
+ /** The shape policy (design item 4) for one already-present JSON flair entry:
508
+ * exactly one identifiable package argument in `args`, no sibling scoped
509
+ * package. Anything else is a HOLD with a reason. */
510
+ function classifyFlairEntryArgs(entry) {
511
+ const args = entry?.args;
512
+ if (!Array.isArray(args)) {
513
+ return { ok: false, reason: "the flair entry has no args array" };
514
+ }
515
+ const matches = [];
516
+ for (let i = 0; i < args.length; i++) {
517
+ const a = args[i];
518
+ if (typeof a !== "string")
519
+ continue;
520
+ if (argNamesFlairPackage(a)) {
521
+ matches.push(i);
522
+ }
523
+ else if (argIsOtherScopedPackage(a)) {
524
+ return { ok: false, reason: `the flair entry's args name another package (${a})` };
260
525
  }
261
- config.mcpServers.flair = flairMcpEntry(env);
262
- mkdirSync(dirname(configPath), { recursive: true });
263
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
264
- const action = urlAgentMatch ? "refreshed pin in" : "wired";
265
- return { ok: true, message: `${label}: ${action} ${display} (${note})` };
526
+ }
527
+ if (matches.length === 0) {
528
+ return { ok: false, reason: "the flair entry has no identifiable package argument" };
529
+ }
530
+ if (matches.length > 1) {
531
+ return { ok: false, reason: "the flair entry names the package more than once" };
532
+ }
533
+ return { ok: true, index: matches[0], arg: args[matches[0]] };
534
+ }
535
+ /** The never-lower hold reason for a MCP entry, phrased for the caller to
536
+ * prefix. Mirrors owned-pins.ts's `heldPinMessage` wording (the hook path
537
+ * keeps that one); kept here so this writer owns its own guard's reason. */
538
+ function heldMcpPinReason(pin, runningCli) {
539
+ if (comparePinVersions(pin, runningCli) === null) {
540
+ return `keeping pinned ${pin} (the pin is not a version I can compare to running CLI ${runningCli} — a pin is never lowered)`;
541
+ }
542
+ return `keeping pinned ${pin} (running CLI ${runningCli} is older — a pin is never lowered)`;
543
+ }
544
+ /**
545
+ * Decide the pin-only re-pin for an already-wired JSON MCP entry, from the raw
546
+ * file text. Pure (no I/O); the writer calls it on the IN-LOCK bytes, and
547
+ * doctor's dry-run calls it on the file it reads — the SAME classification.
548
+ */
549
+ export function decideJsonPinOnly(raw, label, configPath) {
550
+ const display = displayPath(configPath);
551
+ const hold = (line) => ({ result: { kind: "hold", oldPin: null, newPin: null, noIdentity: false, line } });
552
+ const failed = (line) => ({ result: { kind: "failed", oldPin: null, newPin: null, noIdentity: false, line } });
553
+ const skip = (line) => ({ result: { kind: "skip", oldPin: null, newPin: null, noIdentity: false, line } });
554
+ // 1. Raw duplicate scan BEFORE parse, by DECODED key name (design item 5;
555
+ // round 2 — an escaped duplicate must not evade the HOLD). Scoped to
556
+ // root → mcpServers → flair → env.
557
+ const dupAt = findDuplicateOnPath(raw);
558
+ if (dupAt !== null) {
559
+ return hold(`the config carries a duplicate key at ${dupAt} — refusing to rewrite it`);
560
+ }
561
+ const read = parseSettingsBytes(Buffer.from(raw, "utf-8"), configPath);
562
+ if (read.parseError)
563
+ return failed(jsonFailureReason(configPath, read.parseError));
564
+ const config = read.parsed ?? {};
565
+ const entry = config?.mcpServers?.flair;
566
+ if (entry === undefined || entry === null)
567
+ return skip(`${label}: not wired in ${display} — skip`);
568
+ if (typeof entry !== "object" || Array.isArray(entry))
569
+ return hold("the flair entry is not an object — refusing to rewrite it");
570
+ const classified = classifyFlairEntryArgs(entry);
571
+ if ("reason" in classified)
572
+ return hold(classified.reason);
573
+ const { index, arg } = classified;
574
+ const wouldWrite = flairCliVersion();
575
+ const pinStr = wiringPinString(decodeWiringSpec(arg, FLAIR_MCP_PACKAGE));
576
+ // 2. The never-lower / unknown-pin guard.
577
+ if (pinWriteWouldLowerOrIsUnknown(pinStr, wouldWrite)) {
578
+ return { result: { kind: "hold", oldPin: arg, newPin: mcpServerSpec(), noIdentity: false, line: heldMcpPinReason(pinStr, wouldWrite) } };
579
+ }
580
+ const newArg = mcpServerSpec();
581
+ if (arg === newArg)
582
+ return { result: { kind: "noop", oldPin: arg, newPin: newArg, noIdentity: false, line: `${label}: already pinned to ${newArg}` } };
583
+ // 3. Mutate ONLY the one array element; everything else is deep-equal.
584
+ const noIdentity = !(typeof entry.env?.FLAIR_AGENT_ID === "string" && entry.env.FLAIR_AGENT_ID);
585
+ config.mcpServers.flair.args[index] = newArg;
586
+ return { result: { kind: "repinned", oldPin: arg, newPin: newArg, noIdentity, line: null }, write: encodeConfig(config) };
587
+ }
588
+ /** How many times `needle` occurs in `text` (non-overlapping). */
589
+ function countText(text, needle) {
590
+ let n = 0;
591
+ let from = 0;
592
+ for (;;) {
593
+ const i = text.indexOf(needle, from);
594
+ if (i === -1)
595
+ break;
596
+ n++;
597
+ from = i + needle.length;
598
+ }
599
+ return n;
600
+ }
601
+ /**
602
+ * Standalone `<pkg>` tokens (bare OR pinned) in `text`. A scoped sibling like
603
+ * `@tpsdev-ai/flair-mcp-extra` does NOT count (the char before the match is part
604
+ * of a longer name), matching `wiring-spec`'s token-start rule.
605
+ */
606
+ function countFlairPackageTokens(text) {
607
+ const pkg = FLAIR_MCP_PACKAGE;
608
+ let n = 0;
609
+ let from = 0;
610
+ for (;;) {
611
+ const i = text.indexOf(pkg, from);
612
+ if (i === -1)
613
+ break;
614
+ from = i + pkg.length;
615
+ const before = i === 0 ? "" : text[i - 1];
616
+ if (before !== "" && /[A-Za-z0-9_./-]/.test(before))
617
+ continue;
618
+ n++;
619
+ }
620
+ return n;
621
+ }
622
+ const CODEX_FLAIR_HEADER_RE = /^\[mcp_servers\.flair\]\s*$/gm;
623
+ /** A builder-emitted single-line args element: `args = ["-y", "<spec>"]`. */
624
+ const CODEX_ARGS_LINE_RE = /^[ \t]*args[ \t]*=[ \t]*\[[ \t]*"-y"[ \t]*,[ \t]*"([^"]*)"[ \t]*\][ \t]*$/m;
625
+ /**
626
+ * A top-level header that CONTINUES the `[mcp_servers.flair]` section: the
627
+ * exact header itself or one of its dotted subtables (`[mcp_servers.flair.env]`,
628
+ * `[mcp_servers.flair.env.x]`), optionally followed by a comment. A SIBLING
629
+ * table — `[mcp_servers.flair2]`, `[mcp_servers.flair-x]` — is NOT part of the
630
+ * section. Matching a sibling (as a bare `^\[mcp_servers\.flair` prefix does)
631
+ * let the args line of the sibling be read as this section's, so a re-pin could
632
+ * replace the WRONG span and report a Flair re-pin (flair#1834 A2 round 3).
633
+ */
634
+ const CODEX_FLAIR_SECTION_HEADER_RE = /^\[mcp_servers\.flair(?:\.[^\]]+)?\]\s*(?:#.*)?$/;
635
+ /**
636
+ * The ACTIVE, non-empty `FLAIR_AGENT_ID` value a `[mcp_servers.flair]` section
637
+ * configures, or null when it configures none. Decides "no identity" from the
638
+ * value the section actually sets: a commented `# FLAIR_AGENT_ID = "x"` and an
639
+ * explicit `FLAIR_AGENT_ID = ""` are both "no identity", not an identity
640
+ * (flair#1834 A2 round 3).
641
+ */
642
+ function activeCodexIdentity(section) {
643
+ for (const raw of section.split("\n")) {
644
+ const m = raw.match(/^[ \t]*FLAIR_AGENT_ID[ \t]*=[ \t]*(.*)$/);
645
+ if (!m)
646
+ continue;
647
+ const rhs = m[1].trim();
648
+ if (rhs === "" || rhs.startsWith("#"))
649
+ continue; // absent value, or the whole assignment is commented out
650
+ let value;
651
+ if (rhs.startsWith('"') || rhs.startsWith("'")) {
652
+ const quote = rhs[0];
653
+ const end = rhs.indexOf(quote, 1);
654
+ value = end === -1 ? rhs.slice(1) : rhs.slice(1, end);
655
+ }
656
+ else {
657
+ value = rhs.split(/[\s#]/, 1)[0];
658
+ }
659
+ if (value !== "")
660
+ return value;
661
+ }
662
+ return null;
663
+ }
664
+ /**
665
+ * Decide the pin-only re-pin for an already-wired Codex `[mcp_servers.flair]`
666
+ * TOML section, from the raw file text. Changes ONLY the `@tpsdev-ai/flair-mcp`
667
+ * string span inside the single-line `args` element; every other byte of
668
+ * config.toml — env tables, other args, other servers, comments, quoting and
669
+ * line endings — is identical. Fail-closed HOLDs (bytes untouched) when the
670
+ * shape is not the builder-emitted one (flair#1834 A2 design item 3).
671
+ */
672
+ export function decideCodexPinOnly(raw, label) {
673
+ const display = "~/.codex/config.toml";
674
+ const hold = (line) => ({ result: { kind: "hold", oldPin: null, newPin: null, noIdentity: false, line } });
675
+ // 1. Exactly one header (the locator is otherwise fence-blind).
676
+ const headers = [...raw.matchAll(CODEX_FLAIR_HEADER_RE)];
677
+ if (headers.length === 0)
678
+ return { result: { kind: "skip", oldPin: null, newPin: null, noIdentity: false, line: `${label}: not wired in ${display} — skip` } };
679
+ if (headers.length > 1)
680
+ return hold("more than one [mcp_servers.flair] header — refusing to rewrite it");
681
+ const headerIdx = headers[0].index;
682
+ // 2. No unmatched multiline-string fence before the header (a fake header
683
+ // inside another server's `"""` / `'''` string).
684
+ if (countText(raw.slice(0, headerIdx), '"""') % 2 === 1)
685
+ return hold('an unmatched """ fence precedes [mcp_servers.flair] — refusing to rewrite it');
686
+ if (countText(raw.slice(0, headerIdx), "'''") % 2 === 1)
687
+ return hold("an unmatched ''' fence precedes [mcp_servers.flair] — refusing to rewrite it");
688
+ // 3. Locate the section: its end is a clean top-level header line (a flair
689
+ // sub-table is part of the section). An array-of-tables boundary, an
690
+ // array header inside the section, or a comment that looks like a header
691
+ // is a HOLD (not a clean boundary).
692
+ const headerLineEnd = raw.indexOf("\n", headerIdx);
693
+ const bodyStart = headerLineEnd === -1 ? raw.length : headerLineEnd + 1;
694
+ const lines = raw.slice(bodyStart).split("\n");
695
+ let consumed = 0;
696
+ let sectionEnd = raw.length;
697
+ for (let li = 0; li < lines.length; li++) {
698
+ const line = lines[li];
699
+ if (/^\[/.test(line)) {
700
+ if (CODEX_FLAIR_SECTION_HEADER_RE.test(line)) {
701
+ consumed += line.length + 1;
702
+ continue;
703
+ }
704
+ if (/^\[\[/.test(line))
705
+ return hold("the section ends at an array-of-tables header ([[...]]) — refusing to rewrite it");
706
+ sectionEnd = bodyStart + consumed;
707
+ break;
708
+ }
709
+ if (/^[ \t]*\[\[/.test(line))
710
+ return hold("the section contains an array-of-tables header ([[...]]) — refusing to rewrite it");
711
+ if (/^[ \t]*#.*\[/.test(line))
712
+ return hold("the section contains a comment that looks like a header — refusing to rewrite it");
713
+ consumed += line.length + 1;
714
+ }
715
+ const section = raw.slice(headerIdx, sectionEnd);
716
+ // 3b. No multiline-string fence ANYWHERE between the header and the section
717
+ // end (flair#1834 A2 round 4). A `"""` / `'''` string that opens AND
718
+ // closes inside the section can carry a line that looks like a flair
719
+ // sub-table header and an `args` line; the scan above accepts that fake
720
+ // sub-table as part of the section and the args match then rewrites the
721
+ // STRING's content — a wrong-span write. The editor never interprets a
722
+ // line that could be inside a multiline string, so any such fence HOLDs
723
+ // with the bytes untouched (the reason names the fence).
724
+ if (countText(section, '"""') > 0)
725
+ return hold('a """ multiline string appears in [mcp_servers.flair] — refusing to rewrite it');
726
+ if (countText(section, "'''") > 0)
727
+ return hold("a ''' multiline string appears in [mcp_servers.flair] — refusing to rewrite it");
728
+ // 4. Exactly one package token, and it is the args element.
729
+ const tokens = countFlairPackageTokens(section);
730
+ if (tokens === 0)
731
+ return hold("no identifiable package argument in [mcp_servers.flair]");
732
+ if (tokens > 1)
733
+ return hold("the package appears more than once in [mcp_servers.flair] — refusing to rewrite it");
734
+ const argsMatch = section.match(CODEX_ARGS_LINE_RE);
735
+ if (!argsMatch || argsMatch.index === undefined)
736
+ return hold("the [mcp_servers.flair] args is not a single-line double-quoted element");
737
+ const spec = argsMatch[1];
738
+ if (!(spec === FLAIR_MCP_PACKAGE || spec.startsWith(`${FLAIR_MCP_PACKAGE}@`))) {
739
+ return hold("the package string in [mcp_servers.flair] is not on the args line — refusing to rewrite it");
740
+ }
741
+ // 5. Guard (never lower / unknown) — the SAME guard the JSON path uses.
742
+ const wouldWrite = flairCliVersion();
743
+ const pinStr = wiringPinString(decodeWiringSpec(spec, FLAIR_MCP_PACKAGE));
744
+ if (pinWriteWouldLowerOrIsUnknown(pinStr, wouldWrite)) {
745
+ return { result: { kind: "hold", oldPin: spec, newPin: mcpServerSpec(), noIdentity: false, line: heldMcpPinReason(pinStr, wouldWrite) } };
746
+ }
747
+ const newSpec = mcpServerSpec();
748
+ if (spec === newSpec)
749
+ return { result: { kind: "noop", oldPin: spec, newPin: newSpec, noIdentity: false, line: `${label}: already pinned to ${newSpec}` } };
750
+ // 6. Replace ONLY the quoted spec span on the args line.
751
+ const lineAbsStart = headerIdx + argsMatch.index;
752
+ const lineAbsEnd = lineAbsStart + argsMatch[0].length;
753
+ const newLine = argsMatch[0].replace(`"${spec}"`, () => `"${newSpec}"`);
754
+ const newRaw = raw.slice(0, lineAbsStart) + newLine + raw.slice(lineAbsEnd);
755
+ const noIdentity = activeCodexIdentity(section) === null;
756
+ return { result: { kind: "repinned", oldPin: spec, newPin: newSpec, noIdentity, line: null }, write: encodeText(newRaw) };
757
+ }
758
+ /**
759
+ * Re-pin an ALREADY-WIRED JSON MCP entry to the running CLI's spec, changing
760
+ * ONLY the one `@tpsdev-ai/flair-mcp` element of `args`. Preserves every other
761
+ * field, every sibling server and every other top-level key; never takes an
762
+ * identity, so it cannot rewrite FLAIR_AGENT_ID/FLAIR_URL. Never wires a
763
+ * missing entry. Fail-closed: a duplicated flair key or FLAIR_AGENT_ID, an
764
+ * unreadable/ambiguous shape, or a pin the never-lower guard cannot prove safe
765
+ * is a HOLD with the bytes untouched.
766
+ */
767
+ export function repinJsonMcpPin(configPath, label, testHooks) {
768
+ return repinPinOnly(configPath, label, (raw, l) => decideJsonPinOnly(raw, l, configPath), testHooks);
769
+ }
770
+ /**
771
+ * Re-pin an ALREADY-WIRED Codex `[mcp_servers.flair]` TOML section to the
772
+ * running CLI's spec, changing ONLY the `@tpsdev-ai/flair-mcp` span inside the
773
+ * single-line `args` element (flair#1834 A2). Reuses A1's in-lock helper and
774
+ * structured hold seam; never wires a missing section.
775
+ */
776
+ export function repinCodexPin(configPath, label, testHooks) {
777
+ return repinPinOnly(configPath, label, (raw, l) => decideCodexPinOnly(raw, l), testHooks);
778
+ }
779
+ /** The shared in-lock wrapper: observe in-lock bytes → classify → write-or-not. */
780
+ function repinPinOnly(configPath, label, decide, testHooks) {
781
+ const empty = (kind, line = null) => ({ kind, oldPin: null, newPin: null, noIdentity: false, line });
782
+ let settled = null;
783
+ try {
784
+ const result = withConfigCriticalSection(configPath, (bytes) => {
785
+ const raw = bytes === null ? "" : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf-8");
786
+ const dec = decide(raw, label);
787
+ settled = dec.result;
788
+ if (dec.write)
789
+ return { write: dec.write };
790
+ return dec.result.kind === "skip" ? { noop: dec.result.line } : { hold: dec.result.line ?? "refusing to rewrite this entry" };
791
+ }, { backup: (bytes) => backupBytesTo(configPath, bytes), testHooks });
792
+ if (result.status === "written") {
793
+ return settled ?? { kind: "repinned", oldPin: null, newPin: mcpServerSpec(), noIdentity: false, line: null };
794
+ }
795
+ const s = settled;
796
+ // A decided re-pin is truthful ONLY once the write COMMITS. Here nothing was
797
+ // written, so a stored "repinned" means atomicReplace refused AFTER the
798
+ // decision — a failed write, which must be a FAILURE (skip, ok false, loud),
799
+ // never a success. Hold/skip verdicts stand; an absent result (a lock /
800
+ // backup / IO refusal, or an observation change) is a failure too.
801
+ if (s && s.kind !== "repinned")
802
+ return s;
803
+ return empty("failed", result.message);
266
804
  }
267
805
  catch (err) {
268
806
  const reason = err instanceof Error ? err.message : String(err);
269
- return {
270
- ok: false,
271
- message: `${label}: manual wiring needed (could not write ${display}: ${reason}).\n` +
272
- ` Add this to ${display}:\n${indent(jsonSnippet(env))}`,
273
- };
807
+ return empty("failed", reason);
274
808
  }
275
809
  }
276
- function indent(s) {
277
- return s.split("\n").map((l) => ` ${l}`).join("\n");
810
+ /** The pre-migration pi manual-wiring line (kept byte-identical). */
811
+ function piManualMessage(display, reason, envHint) {
812
+ return (`pi: manual wiring needed (could not update ${display}: ${reason}).\n` +
813
+ ` Add this to ${display} (${envHint}):\n${indent(piJsonSnippet())}`);
814
+ }
815
+ /** Decode the primitive's IN-LOCK bytes as UTF-8 TEXT (flair#1778 2c-i-d2):
816
+ * Codex's config.toml is not JSON, so it is read as text — never parsed with
817
+ * parseSettingsBytes. `null` (an absent destination) decodes to "". */
818
+ function decodeText(bytes) {
819
+ return bytes === null ? "" : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf-8");
278
820
  }
279
821
  // ---- Per-client config paths (cross-platform, Linux included) --------------------
280
822
  /** Cursor: ~/.cursor/mcp.json on every OS. */
@@ -369,13 +911,18 @@ export function isPiFlairNpmSource(source) {
369
911
  const spec = source.slice("npm:".length).trim();
370
912
  return spec === PI_FLAIR_PACKAGE || spec.startsWith(`${PI_FLAIR_PACKAGE}@`);
371
913
  }
372
- /** The version text of a pinned pi-flair npm source, or null when bare. */
914
+ /**
915
+ * The version text of a pinned pi-flair npm source, or null when bare.
916
+ *
917
+ * flair#1778 slice 2c-i-a1: read the spec through the ONE wiring decoder. A
918
+ * concrete version returns as before; a range/tag/unsupported/malformed spec is
919
+ * PRESENT-but-not-comparable (its raw token) instead of being dropped as null;
920
+ * a bare `npm:<pkg>` stays null.
921
+ */
373
922
  export function extractPiFlairPin(source) {
374
923
  if (!isPiFlairNpmSource(source))
375
924
  return null;
376
- const spec = source.slice("npm:".length).trim();
377
- const version = spec.slice(`${PI_FLAIR_PACKAGE}@`.length);
378
- return spec.startsWith(`${PI_FLAIR_PACKAGE}@`) && version ? version : null;
925
+ return wiringPinString(decodeWiringSpec(source, PI_FLAIR_PACKAGE));
379
926
  }
380
927
  /**
381
928
  * Does this `extensions` entry point at pi-flair BY PATH (the documented
@@ -468,101 +1015,155 @@ function piJsonSnippet() {
468
1015
  * wiring carried them.
469
1016
  */
470
1017
  function _wirePi(env) {
1018
+ // pi's settings.json `packages` entry (the @tpsdev-ai/pi-flair native
1019
+ // extension — pi has no MCP client support). flair#1778 2c-i-d3: ONE critical
1020
+ // section — observe → decide on the IN-LOCK bytes (parseSettingsBytes) →
1021
+ // decidePinWrite for the pi-flair pin inside decide → write via temp + fsync +
1022
+ // atomic rename, with a 0600 `.bak` of the in-lock bytes. The pure helpers are
1023
+ // unchanged, so the bytes written are exactly today's.
471
1024
  const path = piSettingsPath();
472
1025
  const home = resolveHome();
473
- const display = path.startsWith(home) ? "~" + path.slice(home.length) : path;
1026
+ const display = displayUnderHome(path);
474
1027
  const spec = piFlairSpec();
475
1028
  const envHint = `pi settings carry no env — export FLAIR_AGENT_ID=${env.FLAIR_AGENT_ID} in the shell that launches pi`;
476
1029
  try {
477
- let config = {};
478
- if (existsSync(path)) {
479
- const raw = readFileSync(path, "utf-8").trim();
480
- if (raw)
481
- config = JSON.parse(raw);
482
- }
483
- if (!config || typeof config !== "object" || Array.isArray(config)) {
484
- throw new Error("settings.json is not a JSON object");
485
- }
486
- if (config.packages !== undefined && !Array.isArray(config.packages)) {
487
- throw new Error(`"packages" exists but is not an array — not rewriting it`);
488
- }
489
- if (config.extensions !== undefined && !Array.isArray(config.extensions)) {
490
- throw new Error(`"extensions" exists but is not an array — not rewriting it`);
491
- }
492
- // The #1346 trap: npm: pi-flair specs under `extensions`. Collect + drop.
493
- let movedFromExtensions = false;
494
- if (Array.isArray(config.extensions)) {
495
- const kept = config.extensions.filter((e) => !(typeof e === "string" && isPiFlairNpmSource(e)));
496
- movedFromExtensions = kept.length !== config.extensions.length;
497
- if (movedFromExtensions)
498
- config.extensions = kept;
499
- }
500
- // Existing packages entry?
501
- let entryIndex = -1;
502
- let entrySource = null;
503
- if (Array.isArray(config.packages)) {
504
- for (let i = 0; i < config.packages.length; i++) {
505
- const source = piPackageEntrySource(config.packages[i]);
506
- if (source && isPiFlairNpmSource(source)) {
507
- entryIndex = i;
508
- entrySource = source;
509
- break;
1030
+ // Parent creation stays OUTSIDE the primitive (it needs the resolved parent
1031
+ // to observe an absent destination).
1032
+ mkdirSync(dirname(path), { recursive: true });
1033
+ let settled = null;
1034
+ let success = null;
1035
+ const result = withConfigCriticalSection(path, (bytes) => {
1036
+ const read = parseSettingsBytes(bytes, path);
1037
+ if (read.parseError) {
1038
+ settled = { ok: false, message: piManualMessage(display, jsonFailureReason(path, read.parseError), envHint) };
1039
+ return { hold: settled.message };
1040
+ }
1041
+ const config = read.parsed ?? {};
1042
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
1043
+ settled = { ok: false, message: piManualMessage(display, "settings.json is not a JSON object", envHint) };
1044
+ return { hold: settled.message };
1045
+ }
1046
+ if (config.packages !== undefined && !Array.isArray(config.packages)) {
1047
+ settled = { ok: false, message: piManualMessage(display, `"packages" exists but is not an array — not rewriting it`, envHint) };
1048
+ return { hold: settled.message };
1049
+ }
1050
+ if (config.extensions !== undefined && !Array.isArray(config.extensions)) {
1051
+ settled = { ok: false, message: piManualMessage(display, `"extensions" exists but is not an array — not rewriting it`, envHint) };
1052
+ return { hold: settled.message };
1053
+ }
1054
+ // The #1346 trap: npm: pi-flair specs under `extensions`. pi treats an
1055
+ // `npm:` entry there as a PATH, fails existsSync, and drops it silently —
1056
+ // so a wired pi must MOVE it to `packages`. Collect WITHOUT mutating: the
1057
+ // move rewrites the pin on record, so it goes through the same guard as
1058
+ // every other write, and a hold/refuse leaves BOTH arrays exactly as read.
1059
+ let keptExtensions = null;
1060
+ const movedSources = [];
1061
+ if (Array.isArray(config.extensions)) {
1062
+ const kept = config.extensions.filter((e) => !(typeof e === "string" && isPiFlairNpmSource(e)));
1063
+ keptExtensions = kept;
1064
+ if (kept.length !== config.extensions.length) {
1065
+ for (const e of config.extensions) {
1066
+ if (typeof e === "string" && isPiFlairNpmSource(e))
1067
+ movedSources.push(e);
1068
+ }
510
1069
  }
511
1070
  }
512
- }
513
- if (!movedFromExtensions && entrySource === spec) {
514
- return { ok: true, message: `pi: already wired in ${display} (${spec})` };
515
- }
516
- if (!movedFromExtensions && entryIndex === -1) {
517
- // No packages entry and nothing misplaced — honor a working file-path
518
- // extensions entry (pre-0.49 workaround) instead of double-wiring.
519
- const scan = scanPiSettings(JSON.stringify(config));
520
- const workingPath = scan.extensionFilePaths.find((p) => existsSync(resolvePiExtensionPath(p, home, piAgentDir())));
521
- if (workingPath) {
522
- return {
523
- ok: true,
524
- message: `pi: already wired via a file-path extension in ${display} (${workingPath}) — ` +
525
- `the pre-0.49 workaround; the canonical form is a "packages" entry: ${spec}`,
526
- };
1071
+ const movedFromExtensions = movedSources.length > 0;
1072
+ let entryIndex = -1;
1073
+ let entrySource = null;
1074
+ if (Array.isArray(config.packages)) {
1075
+ for (let i = 0; i < config.packages.length; i++) {
1076
+ const source = piPackageEntrySource(config.packages[i]);
1077
+ if (source && isPiFlairNpmSource(source)) {
1078
+ entryIndex = i;
1079
+ entrySource = source;
1080
+ break;
1081
+ }
1082
+ }
527
1083
  }
528
- }
529
- config.packages = Array.isArray(config.packages) ? config.packages : [];
530
- let action;
531
- if (entryIndex >= 0) {
532
- const entry = config.packages[entryIndex];
533
- if (typeof entry === "string")
534
- config.packages[entryIndex] = spec;
535
- else
536
- entry.source = spec; // object entry: refresh source, keep filters
537
- action = movedFromExtensions
538
- ? `moved ${PI_FLAIR_PACKAGE} out of "extensions" and refreshed the "packages" pin in`
539
- : "refreshed pin in";
540
- }
541
- else if (movedFromExtensions) {
542
- config.packages.push(spec);
543
- action = `moved ${PI_FLAIR_PACKAGE} from "extensions" to "packages" in`;
544
- }
545
- else {
546
- config.packages.push(spec);
547
- action = "wired";
548
- }
549
- mkdirSync(dirname(path), { recursive: true });
550
- writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
551
- const trapNote = movedFromExtensions
552
- ? ` — pi silently ignores npm: specs under "extensions" (flair#1346)`
553
- : "";
554
- return {
555
- ok: true,
556
- message: `pi: ${action} ${display} (${spec} — pi installs the package on next launch; ${envHint})${trapNote}`,
557
- };
1084
+ if (!movedFromExtensions && entrySource === spec) {
1085
+ settled = { ok: true, message: `pi: already wired in ${display} (${spec})` };
1086
+ return { noop: settled.message };
1087
+ }
1088
+ if (!movedFromExtensions && entryIndex === -1) {
1089
+ const scan = scanPiSettings(JSON.stringify(config));
1090
+ const workingPath = scan.extensionFilePaths.find((p) => existsSync(resolvePiExtensionPath(p, home, piAgentDir())));
1091
+ if (workingPath) {
1092
+ settled = {
1093
+ ok: true,
1094
+ message: `pi: already wired via a file-path extension in ${display} (${workingPath}) — ` +
1095
+ `the pre-0.49 workaround; the canonical form is a "packages" entry: ${spec}`,
1096
+ };
1097
+ return { noop: settled.message };
1098
+ }
1099
+ }
1100
+ // The ONE guard, on EVERY write this function makes (the packages
1101
+ // refresh, the #1346 MOVE, the create-when-absent push) — on the IN-LOCK
1102
+ // parse. A packages entry governs; else the misplaced extensions sources
1103
+ // (the highest comparable governs, any non-comparable holds); else ABSENT
1104
+ // (null → an unreadable version REFUSES rather than creating unpinned).
1105
+ const pinTexts = [];
1106
+ if (entrySource !== null)
1107
+ pinTexts.push({ text: entrySource, entry: `pi packages entry in ${display}` });
1108
+ for (const text of movedSources) {
1109
+ pinTexts.push({ text, entry: `pi "extensions" entry in ${display}` });
1110
+ }
1111
+ if (pinTexts.length === 0)
1112
+ pinTexts.push({ text: null, entry: `pi packages entry in ${display}` });
1113
+ let held = null;
1114
+ for (const { text, entry } of pinTexts) {
1115
+ const decision = decidePinWrite({
1116
+ pkg: PI_FLAIR_PACKAGE,
1117
+ entry,
1118
+ existingText: text,
1119
+ runningVersion: flairCliVersion(),
1120
+ });
1121
+ if (decision.action !== "write" && (held === null || decision.action === "refuse")) {
1122
+ held = decision;
1123
+ }
1124
+ }
1125
+ if (held) {
1126
+ settled = { ok: true, message: held.line };
1127
+ return { hold: held.line };
1128
+ }
1129
+ if (keptExtensions !== null)
1130
+ config.extensions = keptExtensions;
1131
+ config.packages = Array.isArray(config.packages) ? config.packages : [];
1132
+ let action;
1133
+ if (entryIndex >= 0) {
1134
+ const entry = config.packages[entryIndex];
1135
+ if (typeof entry === "string")
1136
+ config.packages[entryIndex] = spec;
1137
+ else
1138
+ entry.source = spec; // object entry: refresh source, keep filters
1139
+ action = movedFromExtensions
1140
+ ? `moved ${PI_FLAIR_PACKAGE} out of "extensions" and refreshed the "packages" pin in`
1141
+ : "refreshed pin in";
1142
+ }
1143
+ else if (movedFromExtensions) {
1144
+ config.packages.push(spec);
1145
+ action = `moved ${PI_FLAIR_PACKAGE} from "extensions" to "packages" in`;
1146
+ }
1147
+ else {
1148
+ config.packages.push(spec);
1149
+ action = "wired";
1150
+ }
1151
+ const trapNote = movedFromExtensions
1152
+ ? ` — pi silently ignores npm: specs under "extensions" (flair#1346)`
1153
+ : "";
1154
+ success = `pi: ${action} ${display} (${spec} — pi installs the package on next launch; ${envHint})${trapNote}`;
1155
+ return { write: encodeConfig(config) };
1156
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1157
+ if (result.status === "written")
1158
+ return { ok: true, message: success };
1159
+ const s = settled;
1160
+ if (s)
1161
+ return s;
1162
+ return { ok: false, message: piManualMessage(display, result.message, envHint) };
558
1163
  }
559
1164
  catch (err) {
560
1165
  const reason = err instanceof Error ? err.message : String(err);
561
- return {
562
- ok: false,
563
- message: `pi: manual wiring needed (could not update ${display}: ${reason}).\n` +
564
- ` Add this to ${display} (${envHint}):\n${indent(piJsonSnippet())}`,
565
- };
1166
+ return { ok: false, message: piManualMessage(display, reason, envHint) };
566
1167
  }
567
1168
  }
568
1169
  /**
@@ -611,15 +1212,26 @@ export function clientConfigPath(id) {
611
1212
  }
612
1213
  // ---- Internal wiring functions --------------------------------------------------
613
1214
  //
614
- // Claude Code wiring lives inline in src/cli.ts (it writes ~/.claude.json, the
615
- // one client the CLI safely edits, cross-platform). _wireClaudeCode here is the
616
- // fallback used when something calls the array form; it returns the snippet for
617
- // ~/.claude.json so the message is unambiguous and correct on every OS.
1215
+ // Claude Code wiring lives in src/commands/init.ts (it writes ~/.claude.json, the
1216
+ // one client the CLI safely edits, cross-platform), and DELEGATES to the same
1217
+ // JSON writer here (flair#1778 2c-i-d1). _wireClaudeCode is the array-form entry
1218
+ // (used by doctor --fix and the owned-pin refresh); it writes the same bytes.
618
1219
  function _wireClaudeCode(env) {
619
- // The real auto-wire is inline in cli.ts. If reached via the array, point at
620
- // the correct cross-platform path (~/.claude.json — same on macOS/Linux/Win)
621
- // and give the exact snippet. Never emit macOS-only paths here.
622
- return wireJsonMcp(join(resolveHome(), ".claude.json"), "Claude Code", env);
1220
+ // Point at the correct cross-platform path (~/.claude.json — same on
1221
+ // macOS/Linux/Win). Never emit macOS-only paths here. `type: "stdio"` is
1222
+ // KEPT (init has always written it); the shared entry builder owns it.
1223
+ return wireJsonMcp(join(resolveHome(), ".claude.json"), "Claude Code", env, undefined, { stdioType: true });
1224
+ }
1225
+ /** flair#1778 2c-i-d1: the STRUCTURED Claude Code wire `flair init` renders its
1226
+ * own lines from — ONE writer for ~/.claude.json shared with `wireClaudeCode`,
1227
+ * so init and doctor/upgrade cannot drift on its bytes. */
1228
+ export function wireClaudeCodeJson(env) {
1229
+ return wireJsonMcpCore(join(resolveHome(), ".claude.json"), "Claude Code", env, { stdioType: true });
1230
+ }
1231
+ /** The Claude Code MCP entry (with the stdio type), built by the ONE shared
1232
+ * entry builder — for init's copy-paste snippet fallback. */
1233
+ export function claudeCodeMcpEntry(env) {
1234
+ return flairMcpEntry(env, { stdioType: true });
623
1235
  }
624
1236
  function _wireCodex(env) {
625
1237
  // Codex uses TOML with a [mcp_servers.flair] table. We don't carry a TOML
@@ -630,25 +1242,63 @@ function _wireCodex(env) {
630
1242
  //
631
1243
  // flair#1135: the "already wired" check is now version-aware — a section
632
1244
  // with a stale pin triggers a re-write instead of a no-op.
1245
+ //
1246
+ // flair#1778 2c-i-d2: ONE critical section — observe → decide on the IN-LOCK
1247
+ // TEXT → write via temp + fsync + rename (the primitive), with a 0600 `.bak`
1248
+ // of the in-lock bytes. The three former write arms (append / replace /
1249
+ // create) are ONE decide with three outcomes; the pure TOML helpers are
1250
+ // unchanged, so the bytes written are exactly today's.
633
1251
  const path = codexConfigPath();
634
1252
  const display = "~/.codex/config.toml";
1253
+ // Parent creation stays OUTSIDE the primitive (it needs the resolved parent
1254
+ // to observe an absent destination).
635
1255
  try {
636
- if (existsSync(path)) {
637
- const raw = readFileSync(path, "utf-8");
638
- if (codexFlairSectionHasCurrentPin(raw)) {
639
- return { ok: true, message: `Codex: already wired in ${display}` };
640
- }
641
- if (codexConfigHasFlairSection(raw)) {
642
- // Section exists but pin is stale — replace it.
643
- writeFileSync(path, replaceCodexFlairBlock(raw, env));
644
- return { ok: true, message: `Codex: refreshed pin in ${display} (restart Codex to pick it up)` };
645
- }
646
- writeFileSync(path, appendCodexFlairBlock(raw, env));
647
- return { ok: true, message: `Codex: wired ${display} (restart Codex to pick it up)` };
648
- }
649
1256
  mkdirSync(dirname(path), { recursive: true });
650
- writeFileSync(path, tomlSnippet(env) + "\n");
651
- return { ok: true, message: `Codex: wired ${display} (restart Codex to pick it up)` };
1257
+ let settled = null;
1258
+ let success = null;
1259
+ const result = withConfigCriticalSection(path, (bytes) => {
1260
+ const raw = decodeText(bytes);
1261
+ const hasSection = codexConfigHasFlairSection(raw);
1262
+ // flair#1778 2c-i-a2 (fix round): the decision runs FIRST, on EVERY
1263
+ // path below — including the section-absent append and the absent-file
1264
+ // create, which used to be written unguarded. Nothing is written until
1265
+ // the decision says `write`; an unreadable running version REFUSES.
1266
+ const decision = decidePinWrite({
1267
+ pkg: FLAIR_MCP_PACKAGE,
1268
+ entry: `Codex config ${display}`,
1269
+ existingText: hasSection ? codexFlairSectionText(raw) : null,
1270
+ runningVersion: flairCliVersion(),
1271
+ });
1272
+ if (decision.action !== "write") {
1273
+ settled = { ok: true, message: decision.line };
1274
+ return { hold: decision.line };
1275
+ }
1276
+ if (hasSection) {
1277
+ // A pinned section that already carries the current spec is an
1278
+ // idempotent no-op; otherwise (BEHIND or equal) replace it.
1279
+ if (codexFlairSectionHasCurrentPin(raw)) {
1280
+ settled = { ok: true, message: `Codex: already wired in ${display}` };
1281
+ return { noop: settled.message };
1282
+ }
1283
+ success = `Codex: refreshed pin in ${display} (restart Codex to pick it up)`;
1284
+ return { write: encodeText(replaceCodexFlairBlock(raw, env)) };
1285
+ }
1286
+ // Section absent (or file absent, where raw === "" IS the create
1287
+ // case): the decision above was consulted with an ABSENT entry, and a
1288
+ // `write` here is today's plain append.
1289
+ success = `Codex: wired ${display} (restart Codex to pick it up)`;
1290
+ return { write: encodeText(appendCodexFlairBlock(raw, env)) };
1291
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1292
+ if (result.status === "written")
1293
+ return { ok: true, message: success };
1294
+ const s = settled;
1295
+ if (s)
1296
+ return s;
1297
+ return {
1298
+ ok: false,
1299
+ message: `Codex: manual wiring needed (could not write ${display}: ${result.message}).\n` +
1300
+ ` Add this block to ${display}:\n${indent(tomlSnippet(env))}`,
1301
+ };
652
1302
  }
653
1303
  catch (err) {
654
1304
  const reason = err instanceof Error ? err.message : String(err);
@@ -692,24 +1342,36 @@ function unwireJsonMcp(configPath, label) {
692
1342
  return { ok: true, removed: false, message: `${label}: no config at ${display}` };
693
1343
  }
694
1344
  try {
695
- const raw = readFileSync(configPath, "utf-8").trim();
696
- if (!raw) {
697
- return { ok: true, removed: false, message: `${label}: no Flair MCP entry in ${display}` };
698
- }
699
- const config = JSON.parse(raw);
700
- if (!config || typeof config !== "object" || Array.isArray(config)) {
701
- return { ok: false, removed: false, message: `${label}: refusing to modify a non-object config at ${display}` };
702
- }
703
- const servers = config.mcpServers;
704
- if (!servers || typeof servers !== "object" || Array.isArray(servers) || !("flair" in servers)) {
705
- return { ok: true, removed: false, message: `${label}: no Flair MCP entry in ${display}` };
706
- }
707
- delete servers.flair;
708
- if (Object.keys(servers).length === 0) {
709
- delete config.mcpServers;
1345
+ let outcome = null;
1346
+ const result = withConfigCriticalSection(configPath, (bytes) => {
1347
+ const read = parseSettingsBytes(bytes, configPath);
1348
+ if (read.parseError) {
1349
+ outcome = { ok: false, removed: false, message: `${label}: could not unwire ${display}: ${jsonFailureReason(configPath, read.parseError)}` };
1350
+ return { hold: outcome.message };
1351
+ }
1352
+ const config = read.parsed ?? {};
1353
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
1354
+ outcome = { ok: false, removed: false, message: `${label}: refusing to modify a non-object config at ${display}` };
1355
+ return { hold: outcome.message };
1356
+ }
1357
+ const servers = config.mcpServers;
1358
+ if (!servers || typeof servers !== "object" || Array.isArray(servers) || !("flair" in servers)) {
1359
+ outcome = { ok: true, removed: false, message: `${label}: no Flair MCP entry in ${display}` };
1360
+ return { noop: outcome.message };
1361
+ }
1362
+ delete servers.flair;
1363
+ if (Object.keys(servers).length === 0) {
1364
+ delete config.mcpServers;
1365
+ }
1366
+ return { write: encodeConfig(config) };
1367
+ }, { backup: (bytes) => backupBytesTo(configPath, bytes) });
1368
+ if (result.status === "written") {
1369
+ return { ok: true, removed: true, message: `${label}: unwired ${display}` };
710
1370
  }
711
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
712
- return { ok: true, removed: true, message: `${label}: unwired ${display}` };
1371
+ const settled = outcome;
1372
+ if (settled)
1373
+ return settled;
1374
+ return { ok: false, removed: false, message: `${label}: could not unwire ${display}: ${result.message}` };
713
1375
  }
714
1376
  catch (err) {
715
1377
  const reason = err instanceof Error ? err.message : String(err);
@@ -720,18 +1382,37 @@ function _unwireClaudeCode() {
720
1382
  return unwireJsonMcp(join(resolveHome(), ".claude.json"), "Claude Code");
721
1383
  }
722
1384
  function _unwireCodex() {
1385
+ // flair#1778 2c-i-d2: ONE critical section — observe → decide on the IN-LOCK
1386
+ // text → write via temp + fsync + rename, with a 0600 `.bak` of the in-lock
1387
+ // bytes. The absent-file short-circuit stays OUTSIDE (no lock for a file that
1388
+ // does not exist), matching the JSON unwire.
723
1389
  const path = codexConfigPath();
724
1390
  const display = "~/.codex/config.toml";
725
1391
  if (!existsSync(path)) {
726
1392
  return { ok: true, removed: false, message: `Codex: no config at ${display}` };
727
1393
  }
728
1394
  try {
729
- const raw = readFileSync(path, "utf-8");
730
- if (!codexConfigHasFlairSection(raw)) {
731
- return { ok: true, removed: false, message: `Codex: no Flair MCP entry in ${display}` };
732
- }
733
- writeFileSync(path, removeCodexFlairBlock(raw));
734
- return { ok: true, removed: true, message: `Codex: unwired ${display}` };
1395
+ let settled = null;
1396
+ const result = withConfigCriticalSection(path, (bytes) => {
1397
+ if (bytes === null) {
1398
+ const s = { ok: true, removed: false, message: `Codex: no config at ${display}` };
1399
+ settled = s;
1400
+ return { noop: s.message };
1401
+ }
1402
+ const raw = decodeText(bytes);
1403
+ if (!codexConfigHasFlairSection(raw)) {
1404
+ const s = { ok: true, removed: false, message: `Codex: no Flair MCP entry in ${display}` };
1405
+ settled = s;
1406
+ return { noop: s.message };
1407
+ }
1408
+ return { write: encodeText(removeCodexFlairBlock(raw)) };
1409
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1410
+ if (result.status === "written")
1411
+ return { ok: true, removed: true, message: `Codex: unwired ${display}` };
1412
+ const s = settled;
1413
+ if (s)
1414
+ return s;
1415
+ return { ok: false, removed: false, message: `Codex: could not unwire ${display}: ${result.message}` };
735
1416
  }
736
1417
  catch (err) {
737
1418
  const reason = err instanceof Error ? err.message : String(err);
@@ -748,48 +1429,66 @@ function _unwireAntigravity() {
748
1429
  return unwireJsonMcp(antigravityConfigPath(), "Antigravity");
749
1430
  }
750
1431
  function _unwirePi() {
1432
+ // flair#1778 2c-i-d3: ONE critical section — observe → decide on the IN-LOCK
1433
+ // bytes → write via temp + fsync + rename, with a 0600 `.bak`. The absent-file
1434
+ // short-circuit stays OUTSIDE (no lock for a file that does not exist).
751
1435
  const path = piSettingsPath();
752
1436
  const display = displayUnderHome(path);
753
1437
  if (!existsSync(path)) {
754
1438
  return { ok: true, removed: false, message: `pi: no config at ${display}` };
755
1439
  }
756
1440
  try {
757
- const raw = readFileSync(path, "utf-8").trim();
758
- if (!raw) {
759
- return { ok: true, removed: false, message: `pi: no Flair extension in ${display}` };
760
- }
761
- const config = JSON.parse(raw);
762
- if (!config || typeof config !== "object" || Array.isArray(config)) {
763
- return { ok: false, removed: false, message: `pi: refusing to modify a non-object config at ${display}` };
764
- }
765
- let changed = false;
766
- if (Array.isArray(config.packages)) {
767
- const kept = config.packages.filter((entry) => {
768
- const source = piPackageEntrySource(entry);
769
- return !(source && isPiFlairNpmSource(source));
770
- });
771
- if (kept.length !== config.packages.length) {
772
- config.packages = kept;
773
- changed = true;
1441
+ let settled = null;
1442
+ const result = withConfigCriticalSection(path, (bytes) => {
1443
+ if (bytes === null) {
1444
+ settled = { ok: true, removed: false, message: `pi: no config at ${display}` };
1445
+ return { noop: settled.message };
774
1446
  }
775
- }
776
- if (Array.isArray(config.extensions)) {
777
- const kept = config.extensions.filter((entry) => {
778
- if (typeof entry === "string" && (isPiFlairNpmSource(entry) || isPiFlairExtensionPath(entry))) {
779
- return false;
1447
+ const read = parseSettingsBytes(bytes, path);
1448
+ if (read.parseError) {
1449
+ settled = { ok: false, removed: false, message: `pi: could not unwire ${display}: ${jsonFailureReason(path, read.parseError)}` };
1450
+ return { hold: settled.message };
1451
+ }
1452
+ const config = read.parsed ?? {};
1453
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
1454
+ settled = { ok: false, removed: false, message: `pi: refusing to modify a non-object config at ${display}` };
1455
+ return { hold: settled.message };
1456
+ }
1457
+ let changed = false;
1458
+ if (Array.isArray(config.packages)) {
1459
+ const kept = config.packages.filter((entry) => {
1460
+ const source = piPackageEntrySource(entry);
1461
+ return !(source && isPiFlairNpmSource(source));
1462
+ });
1463
+ if (kept.length !== config.packages.length) {
1464
+ config.packages = kept;
1465
+ changed = true;
780
1466
  }
781
- return true;
782
- });
783
- if (kept.length !== config.extensions.length) {
784
- config.extensions = kept;
785
- changed = true;
786
1467
  }
787
- }
788
- if (!changed) {
789
- return { ok: true, removed: false, message: `pi: no Flair extension in ${display}` };
790
- }
791
- writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
792
- return { ok: true, removed: true, message: `pi: unwired ${display}` };
1468
+ if (Array.isArray(config.extensions)) {
1469
+ const kept = config.extensions.filter((entry) => {
1470
+ if (typeof entry === "string" && (isPiFlairNpmSource(entry) || isPiFlairExtensionPath(entry))) {
1471
+ return false;
1472
+ }
1473
+ return true;
1474
+ });
1475
+ if (kept.length !== config.extensions.length) {
1476
+ config.extensions = kept;
1477
+ changed = true;
1478
+ }
1479
+ }
1480
+ if (!changed) {
1481
+ settled = { ok: true, removed: false, message: `pi: no Flair extension in ${display}` };
1482
+ return { noop: settled.message };
1483
+ }
1484
+ return { write: encodeConfig(config) };
1485
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1486
+ if (result.status === "written")
1487
+ return { ok: true, removed: true, message: `pi: unwired ${display}` };
1488
+ const s = settled;
1489
+ if (s)
1490
+ return s;
1491
+ return { ok: false, removed: false, message: `pi: could not unwire ${display}: ${result.message}` };
793
1492
  }
794
1493
  catch (err) {
795
1494
  const reason = err instanceof Error ? err.message : String(err);