@tpsdev-ai/flair 0.57.0 → 0.58.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 (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -57,10 +57,14 @@
57
57
  * `flair federation sync --admin-pass-file`, which reads it through
58
58
  * readAdminPassFileSecure() and refuses a file that is not owner-only.
59
59
  */
60
- import { existsSync, chmodSync, rmSync, readFileSync, mkdirSync } from "node:fs";
61
- import { resolve, dirname } from "node:path";
60
+ import { existsSync, chmodSync, rmSync, readFileSync, mkdirSync, realpathSync } from "node:fs";
61
+ import { resolve, dirname, isAbsolute } from "node:path";
62
62
  import { fileURLToPath } from "node:url";
63
- import { escapeXml } from "../lib/xml-escape.js";
63
+ import { escapeXml, unescapeXml } from "../lib/xml-escape.js";
64
+ import { snapshotRegularFile, writeFilesAtomically } from "../lib/atomic-write.js";
65
+ import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
66
+ import { compareVersions, isNpmGlobalFlairTree } from "../lib/tree-divergence.js";
67
+ import { findFlairPackageDir } from "../lib/upgrade-exec-path.js";
64
68
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
65
69
  import { resolveHome } from "../lib/home.js";
66
70
  export const LAUNCHD_LABEL = "dev.flair.federation.sync";
@@ -167,7 +171,9 @@ export function enableScheduler(opts) {
167
171
  const plat = detectPlatform(opts.platformOverride);
168
172
  const resolvedFlair = resolveFlairBin(opts.flairBin);
169
173
  const flairBin = resolvedFlair.path;
170
- const nodeBin = resolveNodeBin(opts.nodeBin);
174
+ const nodeBin = opts.nodeBin
175
+ ? resolveNodeBin(opts.nodeBin)
176
+ : preferVersionManagerAlias(opts.defaultNodeBin ?? resolveNodeBin(), opts.aliasHooks);
171
177
  const shimPath = opts.shimPathOverride ?? SHIM_PATH_DEFAULT;
172
178
  const templateRoot = opts.templateRootOverride ?? defaultTemplateRoot();
173
179
  const subs = buildSubstitutions(opts, shimPath, flairBin, nodeBin);
@@ -624,3 +630,246 @@ export function formatStatusReport(s, a) {
624
630
  // `ok` reflects only whether the headline claims a working driver.
625
631
  return { lines, ok: a.verdict !== "driver-stalled" && a.verdict !== "driver-inactive" && a.verdict !== "no-driver" };
626
632
  }
633
+ const SHIM_MARKER = "# Deployed by `flair federation sync enable`";
634
+ const SHIM_EXEC_LINE_RE = /^exec "([^"\n]*)" "([^"\n]*)" federation sync "\$@"$/gm;
635
+ const UNSAFE_SHIM_VALUE = /["$`\\\n]/;
636
+ /** A shell command line of the shim (not blank, not a `#` comment at column 0). */
637
+ function shimCommandLines(text) {
638
+ return text
639
+ .split("\n")
640
+ .map((line, i) => ({ n: i + 1, line }))
641
+ .filter(({ line, n }) => n === 1 || (line !== "" && !line.startsWith("#")));
642
+ }
643
+ /**
644
+ * Does `shimText` run exactly the commands the enable template writes? The
645
+ * first line (the interpreter) and every non-comment line are compared, in
646
+ * order, with the template's; the exec line may differ only in its two quoted
647
+ * paths. Returns the reason it does not match (naming a line number, never the
648
+ * line's content — a hand edit may hold a secret), or null.
649
+ */
650
+ export function federationShimShapeProblem(shimText, templateText) {
651
+ const want = shimCommandLines(templateText);
652
+ const have = shimCommandLines(shimText);
653
+ const execTemplate = /^exec "\{\{NODE_BIN\}\}" "\{\{FLAIR_BIN\}\}" federation sync "\$@"$/;
654
+ for (let i = 0; i < Math.max(want.length, have.length); i++) {
655
+ const w = want[i];
656
+ const h = have[i];
657
+ if (!h)
658
+ return `it ends after line ${have.length ? have[have.length - 1].n : 0}, before the generated commands do`;
659
+ if (!w)
660
+ return `line ${h.n} is a command the generated shim does not have`;
661
+ const matches = execTemplate.test(w.line)
662
+ ? new RegExp(SHIM_EXEC_LINE_RE.source).test(h.line)
663
+ : h.line === w.line;
664
+ if (!matches)
665
+ return `line ${h.n} is not the generated command at that position`;
666
+ }
667
+ return null;
668
+ }
669
+ /** Does the federation-sync unit exec `shimPath`? Returns the reason it does not, or null. */
670
+ function federationUnitExecsShim(plat, text, shimPath) {
671
+ if (plat === "darwin") {
672
+ const label = /<key>Label<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
673
+ if (!label || unescapeXml(label[1]) !== LAUNCHD_LABEL)
674
+ return `its Label is not ${LAUNCHD_LABEL}`;
675
+ const block = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(text);
676
+ const args = block ? [...block[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unescapeXml(m[1])) : [];
677
+ if (args.length !== 1 || resolve(args[0]) !== resolve(shimPath)) {
678
+ return `its ProgramArguments are ${JSON.stringify(args)}, not [${JSON.stringify(shimPath)}]`;
679
+ }
680
+ return null;
681
+ }
682
+ let section = "";
683
+ const execs = [];
684
+ for (const raw of text.split(/\r?\n/)) {
685
+ const line = raw.trim();
686
+ if (line === "" || line.startsWith("#") || line.startsWith(";"))
687
+ continue;
688
+ if (line.startsWith("[")) {
689
+ section = line.slice(1).replace(/\].*$/, "").trim().toLowerCase();
690
+ continue;
691
+ }
692
+ if (section === "service" && /^ExecStart\s*=/.test(line))
693
+ execs.push(line.replace(/^ExecStart\s*=\s*/, "").replace(/^[-@:+!]+/, ""));
694
+ }
695
+ if (execs.length !== 1 || resolve(execs[0]) !== resolve(shimPath)) {
696
+ return `its ExecStart is ${JSON.stringify(execs)}, not ${JSON.stringify(shimPath)}`;
697
+ }
698
+ return null;
699
+ }
700
+ /**
701
+ * Re-point the federation-sync shim at this CLI's install tree. See the block
702
+ * comment above for what is — and is never — changed.
703
+ */
704
+ export function rewriteFederationSchedulerRuntime(opts = {}) {
705
+ const read = opts.read ?? ((p) => readFileSync(p, "utf-8"));
706
+ const exists = opts.exists ?? existsSync;
707
+ const realpath = opts.realpath ?? ((p) => realpathSync(p));
708
+ const canonical = (p) => {
709
+ try {
710
+ return realpath(p);
711
+ }
712
+ catch {
713
+ return resolve(p);
714
+ }
715
+ };
716
+ const packageOf = opts.packageOf ?? ((p) => {
717
+ try {
718
+ return findFlairPackageDir(realpath(p));
719
+ }
720
+ catch {
721
+ return null;
722
+ }
723
+ });
724
+ const plat = detectPlatform(opts.platformOverride);
725
+ const shimPath = opts.shimPathOverride ?? SHIM_PATH_DEFAULT;
726
+ const unitPath = plat === "darwin"
727
+ ? (opts.launchdPlistOverride ?? LAUNCHD_PLIST_PATH)
728
+ : (opts.systemdServiceOverride ?? SYSTEMD_SERVICE_PATH);
729
+ const base = { platform: plat, shimPath, unitPath };
730
+ const refused = (detail) => ({
731
+ ...base,
732
+ status: "refused",
733
+ detail: `${detail} The federation-sync shim was not changed; to regenerate the pair: flair federation sync enable`,
734
+ });
735
+ if (!exists(unitPath)) {
736
+ return {
737
+ ...base,
738
+ status: "not-enabled",
739
+ detail: `federation sync is not enabled (no ${unitPath})${exists(shimPath) ? `; the leftover shim ${shimPath} is left as it is` : ""}.`,
740
+ };
741
+ }
742
+ let unitText;
743
+ try {
744
+ unitText = read(unitPath);
745
+ }
746
+ catch (err) {
747
+ return refused(`could not read ${unitPath} (${err?.message ?? err}).`);
748
+ }
749
+ const notOurs = federationUnitExecsShim(plat, unitText, shimPath);
750
+ if (notOurs)
751
+ return refused(`${unitPath} does not exec the flair-generated shim: ${notOurs}.`);
752
+ if (!exists(shimPath))
753
+ return refused(`${unitPath} execs ${shimPath}, which does not exist.`);
754
+ // A regular file (never followed through a symlink), read once: the plan and
755
+ // the pre-rename re-check both use these bytes.
756
+ let planned;
757
+ try {
758
+ planned = snapshotRegularFile(shimPath, { lstat: opts.atomic?.lstat, readBytes: opts.atomic?.readBytes });
759
+ }
760
+ catch (err) {
761
+ return refused(`could not read ${shimPath} as a regular file (${err?.message ?? err}).`);
762
+ }
763
+ const shimText = planned.content;
764
+ const execLines = [...shimText.matchAll(SHIM_EXEC_LINE_RE)];
765
+ if (!shimText.includes(SHIM_MARKER) || execLines.length !== 1) {
766
+ return refused(`${shimPath} is not in the shape \`flair federation sync enable\` writes (one \`exec "<node>" "<flair>" federation sync\` line).`);
767
+ }
768
+ let templateText;
769
+ try {
770
+ templateText = readTemplate(opts.templateRootOverride ?? defaultTemplateRoot(), "bin/flair-federation-sync.sh.tmpl");
771
+ }
772
+ catch (err) {
773
+ return refused(`could not read the shim template to compare ${shimPath} with (${err?.message ?? err}).`);
774
+ }
775
+ const shapeProblem = federationShimShapeProblem(shimText, templateText);
776
+ if (shapeProblem) {
777
+ return refused(`${shimPath} does not run exactly the commands \`flair federation sync enable\` writes (${shapeProblem}), so it ` +
778
+ "was hand-changed and flair does not rewrite it.");
779
+ }
780
+ const oldNode = execLines[0][1];
781
+ const oldFlair = execLines[0][2];
782
+ if (!isAbsolute(oldNode) || !isAbsolute(oldFlair)) {
783
+ return refused(`${shimPath} names a relative node or flair path (${oldNode}, ${oldFlair}).`);
784
+ }
785
+ const newFlair = resolveFlairBin(opts.flairBin).path;
786
+ const newNode = opts.nodeBin ?? preferVersionManagerAlias(resolveNodeBin());
787
+ const newPkg = packageOf(newFlair);
788
+ const cliTree = opts.cliTree ?? newPkg?.dir ?? null;
789
+ const cliVersion = opts.cliVersion !== undefined ? opts.cliVersion : (newPkg?.version ?? null);
790
+ if (!cliTree)
791
+ return refused(`cannot tell which install tree this CLI's script ${newFlair} belongs to.`);
792
+ const oldPkg = exists(oldFlair) ? packageOf(oldFlair) : null;
793
+ const oldNodeMissing = !exists(oldNode);
794
+ let nextNode = oldNode;
795
+ let nextFlair = oldFlair;
796
+ if (oldPkg && canonical(oldPkg.dir) === canonical(cliTree)) {
797
+ // Same install tree as this CLI.
798
+ if (oldNodeMissing) {
799
+ nextNode = newNode;
800
+ }
801
+ else if (canonical(oldNode) === canonical(newNode)) {
802
+ return { ...base, status: "current", detail: `${shimPath} already runs this CLI's tree (${cliTree}).` };
803
+ }
804
+ else {
805
+ return {
806
+ ...base,
807
+ status: "pinned-node",
808
+ detail: `${shimPath} runs this CLI's tree with node ${oldNode} (this CLI runs ${newNode}); a deliberate runtime ` +
809
+ "pin is left as it is.",
810
+ };
811
+ }
812
+ }
813
+ else {
814
+ if (exists(oldFlair) && !oldPkg) {
815
+ return refused(`${shimPath} runs ${oldFlair}, which is not inside a @tpsdev-ai/flair install, so its tree cannot be judged.`);
816
+ }
817
+ if (oldPkg && !isNpmGlobalFlairTree(oldPkg.dir)) {
818
+ return {
819
+ ...base,
820
+ status: "separate",
821
+ detail: `${shimPath} runs flair from ${oldPkg.dir}, which is not an npm-global install (a plain tree or a checkout); ` +
822
+ "flair treats it as separately managed and does not re-point it.",
823
+ };
824
+ }
825
+ // Semver ordering (prereleases included). While the old tree is still
826
+ // installed, a version that cannot be read or is not strict semver cannot
827
+ // rule a downgrade out, so it is refused.
828
+ const order = oldPkg && oldPkg.version && cliVersion ? compareVersions(cliVersion, oldPkg.version) : null;
829
+ if (oldPkg && order === null) {
830
+ return refused(`${shimPath} runs flair from ${oldPkg.dir}; its version (${JSON.stringify(oldPkg.version)}) or this CLI's ` +
831
+ `(${JSON.stringify(cliVersion)}) is not a readable semver version, so a downgrade cannot be ruled out.`);
832
+ }
833
+ if (oldPkg && order !== null && order < 0) {
834
+ return refused(`${shimPath} runs flair ${oldPkg.version} from ${oldPkg.dir}; this CLI's tree has the older ${cliVersion}, so ` +
835
+ "re-pointing would downgrade it. Update this CLI's tree first (npm i -g @tpsdev-ai/flair).");
836
+ }
837
+ nextNode = newNode;
838
+ nextFlair = newFlair;
839
+ }
840
+ for (const [what, p] of [["node", nextNode], ["flair", nextFlair]]) {
841
+ if (!isAbsolute(p) || UNSAFE_SHIM_VALUE.test(p))
842
+ return refused(`the ${what} path ${JSON.stringify(p)} cannot be written into a shell shim safely.`);
843
+ if (!exists(p))
844
+ return refused(`the ${what} path ${p} does not exist.`);
845
+ }
846
+ const from = { nodeBin: oldNode, flairBin: oldFlair };
847
+ const to = { nodeBin: nextNode, flairBin: nextFlair };
848
+ const detail = `re-point ${shimPath}: node ${oldNode} → ${nextNode}` + (nextFlair !== oldFlair ? `, flair ${oldFlair} → ${nextFlair}` : "");
849
+ if (opts.dryRun)
850
+ return { ...base, status: "would-rewrite", detail, from, to };
851
+ const nextLine = `exec "${nextNode}" "${nextFlair}" federation sync "$@"`;
852
+ const execMatch = execLines[0];
853
+ const nextText = shimText.slice(0, execMatch.index) + nextLine + shimText.slice(execMatch.index + execMatch[0].length);
854
+ let mode = planned.mode;
855
+ if (opts.modeOf) {
856
+ try {
857
+ mode = opts.modeOf(shimPath);
858
+ }
859
+ catch { /* keep the snapshot's mode */ }
860
+ }
861
+ try {
862
+ writeFilesAtomically([{ path: shimPath, content: nextText, mode, expect: planned }], opts.atomic);
863
+ }
864
+ catch (err) {
865
+ return refused(`could not write ${shimPath}: ${err?.message ?? err}.`);
866
+ }
867
+ let after = "";
868
+ try {
869
+ after = read(shimPath);
870
+ }
871
+ catch { /* verified below */ }
872
+ if (after !== nextText)
873
+ return refused(`${shimPath} did not read back as written.`);
874
+ return { ...base, status: "rewritten", detail: detail.replace(/^re-point/, "re-pointed"), from, to };
875
+ }
@@ -28,6 +28,7 @@ import { decidePinWrite } from "../lib/pin-write-guard.js";
28
28
  import { pinWriteWouldLowerOrIsUnknown, comparePinVersions } from "../lib/upgrade-status.js";
29
29
  import { withConfigCriticalSection } from "../lib/config-critical-section.js";
30
30
  import { backupBytesTo, encodeConfig, encodeText, parseSettingsBytes } from "../lib/settings-bytes.js";
31
+ import { readTomlStringArray } from "../lib/toml-string-array.js";
31
32
  /**
32
33
  * The JSON.parse reason embedded in the shared parser's
33
34
  * `malformed JSON in <path> (<reason>)` text, so the client writers can keep
@@ -228,9 +229,30 @@ function codexFlairSectionText(raw) {
228
229
  const nextHeader = after.slice("[mcp_servers.flair]".length).search(/\n\[(?!mcp_servers\.flair\.)/);
229
230
  return nextHeader === -1 ? after : after.slice(0, "[mcp_servers.flair]".length + nextHeader);
230
231
  }
231
- function codexFlairSectionHasCurrentPin(raw) {
232
+ export function codexWiringPin(raw) {
233
+ const unknown = `${FLAIR_MCP_PACKAGE}@unknown`;
234
+ const headers = [...raw.matchAll(CODEX_FLAIR_HEADER_RE)];
235
+ if (headers.length !== 1 || headers[0].index !== raw.indexOf("[mcp_servers.flair]"))
236
+ return unknown;
237
+ const before = raw.slice(0, headers[0].index);
238
+ for (const quote of ['"', "'"]) {
239
+ if (countText(before, quote.repeat(3)) % 2 === 1)
240
+ return unknown;
241
+ }
242
+ // Match the section the writer replaces, including Flair's subtables.
243
+ // Multiline strings in later, unrelated tables cannot change its pin.
232
244
  const section = codexFlairSectionText(raw);
233
- return section !== null && section.includes(mcpServerSpec());
245
+ if (section === null)
246
+ return unknown;
247
+ const args = codexArgs(section);
248
+ // Only the captured args value may contain multiline string delimiters.
249
+ // A fence elsewhere can hide a fake header/assignment from this scanner.
250
+ if (!args || /"{3}|'{3}/.test(args.outside))
251
+ return unknown;
252
+ return args.spec.value;
253
+ }
254
+ function codexFlairSectionHasCurrentPin(raw) {
255
+ return codexWiringPin(raw) === mcpServerSpec();
234
256
  }
235
257
  /**
236
258
  * flair#1135: replace the existing `[mcp_servers.flair]` TOML section with a
@@ -297,7 +319,10 @@ function wireJsonMcpCore(configPath, label, env, opts = {}) {
297
319
  const decision = decidePinWrite({
298
320
  pkg: FLAIR_MCP_PACKAGE,
299
321
  entry: `${label} config ${display}`,
300
- existingText: existing ? JSON.stringify(existing) : null,
322
+ existingText: existing == null ? null : (() => {
323
+ const pin = classifyFlairEntryArgs(existing);
324
+ return pin.ok ? pin.arg : `${FLAIR_MCP_PACKAGE}@unknown`;
325
+ })(),
301
326
  runningVersion: flairCliVersion(),
302
327
  });
303
328
  if (decision.action !== "write") {
@@ -615,8 +640,48 @@ function countFlairPackageTokens(text) {
615
640
  return n;
616
641
  }
617
642
  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;
643
+ /** Capture the actual package string, decoded independently of TOML quoting. */
644
+ function codexArgs(section) {
645
+ const bodyStart = section.indexOf("\n") + 1;
646
+ const body = section.slice(bodyStart).split(/^[ \t]*\[/m)[0];
647
+ const assignments = [...body.matchAll(/^[ \t]*(?:args|"args"|'args')[ \t]*=[ \t]*/gm)];
648
+ if (assignments.length !== 1)
649
+ return null;
650
+ const assignment = assignments[0];
651
+ const valueStart = bodyStart + assignment.index + assignment[0].length;
652
+ const parsed = readTomlStringArray(section, valueStart);
653
+ if (!parsed)
654
+ return null;
655
+ const outside = section.slice(0, valueStart) + section.slice(parsed.end);
656
+ // An array opening on its own line can look like a table boundary to the
657
+ // initial locator. Count keys again with that whole value removed.
658
+ const outsideBody = outside.slice(bodyStart).split(/^[ \t]*\[/m)[0];
659
+ if ([...outsideBody.matchAll(/^[ \t]*(?:args|"args"|'args')[ \t]*=/gm)].length !== 1)
660
+ return null;
661
+ // Only recognize a direct npx invocation. Resolve its package operand
662
+ // after known boolean flags and an optional end-of-options marker; unknown
663
+ // options may consume a value, so hold rather than guess their arity.
664
+ const commands = [...outsideBody.matchAll(/^[ \t]*(?:command|"command"|'command')[ \t]*=[ \t]*(.*)$/gm)];
665
+ if (commands.length !== 1 || !/^(?:"npx"|'npx')[ \t]*(?:#.*)?\r?$/.test(commands[0][1]))
666
+ return null;
667
+ let packageIndex = 0;
668
+ while (["-y", "--yes"].includes(parsed.values[packageIndex]?.value ?? ""))
669
+ packageIndex++;
670
+ if (parsed.values[packageIndex]?.value === "--")
671
+ packageIndex++;
672
+ const packages = parsed.values.filter((arg) => argNamesFlairPackage(arg.value));
673
+ if (packages.length !== 1 || packages[0] !== parsed.values[packageIndex])
674
+ return null;
675
+ // An escape can decode into a token terminator. Never let the generic pin
676
+ // decoder approve only the version-looking prefix of that argument.
677
+ const spec = packages[0];
678
+ if (decodeWiringSpec(spec.value, FLAIR_MCP_PACKAGE)?.raw !== spec.value)
679
+ return null;
680
+ return {
681
+ spec,
682
+ outside,
683
+ };
684
+ }
620
685
  /**
621
686
  * A top-level header that CONTINUES the `[mcp_servers.flair]` section: the
622
687
  * exact header itself or one of its dotted subtables (`[mcp_servers.flair.env]`,
@@ -659,10 +724,10 @@ function activeCodexIdentity(section) {
659
724
  /**
660
725
  * Decide the pin-only re-pin for an already-wired Codex `[mcp_servers.flair]`
661
726
  * 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
727
+ * string span inside the `args` element; every other byte of
663
728
  * config.toml — env tables, other args, other servers, comments, quoting and
664
729
  * 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).
730
+ * table or package argument is ambiguous (flair#1834 A2 design item 3).
666
731
  */
667
732
  export function decideCodexPinOnly(raw, label) {
668
733
  const display = "~/.codex/config.toml";
@@ -708,28 +773,29 @@ export function decideCodexPinOnly(raw, label) {
708
773
  consumed += line.length + 1;
709
774
  }
710
775
  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
776
+ const args = codexArgs(section);
777
+ // 3b. No multiline-string fence outside the parsed args value between the
778
+ // header and section end (flair#1834 A2 round 4). A string that opens AND
713
779
  // closes inside the section can carry a line that looks like a flair
714
780
  // sub-table header and an `args` line; the scan above accepts that fake
715
781
  // sub-table as part of the section and the args match then rewrites the
716
782
  // 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)
783
+ // line that could be inside an unrelated multiline string, so those
784
+ // fences HOLD with the bytes untouched (the reason names the fence).
785
+ const outside = args?.outside ?? section;
786
+ if (countText(outside, '"""') > 0)
720
787
  return hold('a """ multiline string appears in [mcp_servers.flair] — refusing to rewrite it');
721
- if (countText(section, "'''") > 0)
788
+ if (countText(outside, "'''") > 0)
722
789
  return hold("a ''' multiline string appears in [mcp_servers.flair] — refusing to rewrite it");
723
790
  // 4. Exactly one package token, and it is the args element.
724
- const tokens = countFlairPackageTokens(section);
791
+ const tokens = args ? countFlairPackageTokens(outside) + 1 : countFlairPackageTokens(section);
725
792
  if (tokens === 0)
726
793
  return hold("no identifiable package argument in [mcp_servers.flair]");
727
794
  if (tokens > 1)
728
795
  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];
796
+ if (!args)
797
+ return hold("the [mcp_servers.flair] args has no unambiguous package string");
798
+ const spec = args.spec.value;
733
799
  if (!(spec === FLAIR_MCP_PACKAGE || spec.startsWith(`${FLAIR_MCP_PACKAGE}@`))) {
734
800
  return hold("the package string in [mcp_servers.flair] is not on the args line — refusing to rewrite it");
735
801
  }
@@ -743,10 +809,10 @@ export function decideCodexPinOnly(raw, label) {
743
809
  if (spec === newSpec)
744
810
  return { result: { kind: "noop", oldPin: spec, newPin: newSpec, noIdentity: false, line: `${label}: already pinned to ${newSpec}` } };
745
811
  // 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);
812
+ const specStart = headerIdx + args.spec.start;
813
+ const specEnd = headerIdx + args.spec.end;
814
+ const replacement = args.spec.quote + newSpec + args.spec.quote;
815
+ const newRaw = raw.slice(0, specStart) + replacement + raw.slice(specEnd);
750
816
  const noIdentity = activeCodexIdentity(section) === null;
751
817
  return { result: { kind: "repinned", oldPin: spec, newPin: newSpec, noIdentity, line: null }, write: encodeText(newRaw) };
752
818
  }
@@ -1261,7 +1327,7 @@ function _wireCodex(env) {
1261
1327
  const decision = decidePinWrite({
1262
1328
  pkg: FLAIR_MCP_PACKAGE,
1263
1329
  entry: `Codex config ${display}`,
1264
- existingText: hasSection ? codexFlairSectionText(raw) : null,
1330
+ existingText: hasSection ? codexWiringPin(raw) : null,
1265
1331
  runningVersion: flairCliVersion(),
1266
1332
  });
1267
1333
  if (decision.action !== "write") {
@@ -20,10 +20,10 @@
20
20
  // never "check your PATH". If we cannot VALIDATE the directory (the flair
21
21
  // bin is really there), we say nothing rather than print a wrong fix.
22
22
  //
23
- // Everything here is pure and dependency-injected except
23
+ // Filesystem checks use existsSync/realpathSync. The only subprocess is in
24
24
  // resolveNpmGlobalPrefix (spawns `npm prefix -g` for doctor).
25
25
  import { join } from "node:path";
26
- import { existsSync } from "node:fs";
26
+ import { existsSync, realpathSync } from "node:fs";
27
27
  // ─── path membership ────────────────────────────────────────────────────────
28
28
  /** Strip trailing separators ("/", and "\" on win32) without eating a bare root. */
29
29
  function stripTrailingSeps(p, win32) {
@@ -50,6 +50,8 @@ export function npmGlobalBinDir(prefix, platform = process.platform) {
50
50
  * Is `dir` one of the entries of `pathEnv`? Trailing slashes are ignored on
51
51
  * both sides; win32 compares case-insensitively with either separator and
52
52
  * splits on ";". Empty entries (historical "cwd" semantics) never match.
53
+ * Otherwise, compare real paths so version-manager aliases count too.
54
+ * Unresolvable paths (including broken links and unreadable entries) are ignored.
53
55
  */
54
56
  export function isDirOnPath(dir, pathEnv, platform = process.platform) {
55
57
  if (!pathEnv)
@@ -57,10 +59,28 @@ export function isDirOnPath(dir, pathEnv, platform = process.platform) {
57
59
  const win32 = platform === "win32";
58
60
  const delim = win32 ? ";" : ":";
59
61
  const want = normalizeEntry(dir, win32);
60
- return pathEnv
61
- .split(delim)
62
- .filter((e) => e.trim() !== "")
63
- .some((e) => normalizeEntry(e, win32) === want);
62
+ if (!want)
63
+ return false;
64
+ const entries = pathEnv.split(delim).filter((e) => e.trim() !== "");
65
+ // Preserve string matches, including paths that cannot currently be resolved.
66
+ if (entries.some((e) => normalizeEntry(e, win32) === want))
67
+ return true;
68
+ let realDir;
69
+ try {
70
+ realDir = normalizeEntry(realpathSync(dir.trim()), win32);
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ return entries.some((e) => {
76
+ try {
77
+ return normalizeEntry(realpathSync(e.trim()), win32) === realDir;
78
+ }
79
+ catch {
80
+ // A stale or inaccessible PATH entry must not hide a later valid alias.
81
+ return false;
82
+ }
83
+ });
64
84
  }
65
85
  /** basename of $SHELL, lowercased — "/usr/local/bin/zsh" → "zsh". */
66
86
  function shellFlavor(shell) {