@tpsdev-ai/flair 0.55.1 → 0.56.0

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