@tpsdev-ai/flair 0.54.1 → 0.55.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 (69) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +73 -2
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +80 -8
  10. package/dist/commands/upgrade.js +41 -5
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/engine-version.js +12 -4
  13. package/dist/fabric-upgrade.js +30 -15
  14. package/dist/hook-install.js +170 -16
  15. package/dist/lib/doctor-run.js +49 -3
  16. package/dist/lib/embed-gpu-doctor.js +30 -0
  17. package/dist/lib/federation-pair-access.js +118 -0
  18. package/dist/lib/harper-port-value.js +43 -0
  19. package/dist/lib/http-bind.js +227 -0
  20. package/dist/lib/init-admin-pass.js +316 -0
  21. package/dist/lib/launchd-management.js +16 -0
  22. package/dist/lib/launchd-repair.js +122 -1
  23. package/dist/lib/npm-registry.js +578 -0
  24. package/dist/lib/owned-pins.js +54 -1
  25. package/dist/lib/process-start-time.js +82 -0
  26. package/dist/lib/scratch-owner.js +124 -10
  27. package/dist/lib/stale-client-pin.js +26 -0
  28. package/dist/rem/runner.js +10 -1
  29. package/dist/resources/AdminInstance.js +8 -2
  30. package/dist/resources/Memory.js +36 -1
  31. package/dist/resources/MemoryBootstrap.js +23 -32
  32. package/dist/resources/MemoryFeed.js +4 -1
  33. package/dist/resources/MemoryReflect.js +121 -93
  34. package/dist/resources/SkillScan.js +13 -11
  35. package/dist/resources/Soul.js +15 -1
  36. package/dist/resources/XAA.js +16 -1
  37. package/dist/resources/a2a-url.js +5 -2
  38. package/dist/resources/client-version-gate.js +144 -0
  39. package/dist/resources/embed-gpu.js +241 -0
  40. package/dist/resources/embeddings-boot.js +34 -42
  41. package/dist/resources/federation-peer-liveness.js +7 -1
  42. package/dist/resources/health.js +12 -3
  43. package/dist/resources/mcp-tools.js +8 -3
  44. package/dist/resources/memory-reflect-lib.js +66 -0
  45. package/dist/resources/memory-reflect-models.js +9 -0
  46. package/dist/resources/migrations/embedding-stamp.js +32 -4
  47. package/dist/resources/oauth-discovery.js +3 -1
  48. package/dist/resources/record-type-kit.js +59 -0
  49. package/dist/resources/scan/skill-markdown.js +166 -0
  50. package/dist/resources/scan/skill-scanner.js +89 -68
  51. package/dist/resources/skill-provenance.js +273 -0
  52. package/dist/resources/skill-write.js +26 -7
  53. package/{node_modules/@tpsdev-ai/flair-tool-descriptors/dist → dist/resources/tool-descriptors}/index.js +4 -0
  54. package/dist/src/lib/harper-port-value.js +43 -0
  55. package/dist/version-check.js +29 -8
  56. package/docs/api-reference.md +35 -2
  57. package/docs/deployment.md +1 -1
  58. package/docs/federation.md +18 -7
  59. package/docs/mcp-clients.md +19 -6
  60. package/docs/releasing.md +96 -24
  61. package/docs/rem.md +1 -1
  62. package/docs/secrets-and-keys.md +1 -0
  63. package/docs/standalone-local.md +1 -1
  64. package/docs/troubleshooting.md +17 -0
  65. package/package.json +4 -9
  66. package/node_modules/@tpsdev-ai/flair-tool-descriptors/LICENSE +0 -19
  67. package/node_modules/@tpsdev-ai/flair-tool-descriptors/README.md +0 -22
  68. package/node_modules/@tpsdev-ai/flair-tool-descriptors/dist/index.d.ts +0 -70
  69. package/node_modules/@tpsdev-ai/flair-tool-descriptors/package.json +0 -46
@@ -1,7 +1,8 @@
1
1
  import { resolveAdminUser } from "../lib/auth-resolve.js";
2
2
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
3
3
  import * as render from "../render.js";
4
- import { checkVersion, formatVersionNudge } from "../version-check.js";
4
+ import { checkVersion, formatVersionNudge, FLAIR_PKG_NAME } from "../version-check.js";
5
+ import { resolveRegistryNotice } from "../lib/npm-registry.js";
5
6
  let cli;
6
7
  /** Bind the cli-locals this module depends on. */
7
8
  export function bindCli(fns) {
@@ -28,6 +29,9 @@ function defaultDataDir(...args) {
28
29
  function readHarperConfig(...args) {
29
30
  return cli.readHarperConfig(...args);
30
31
  }
32
+ function readPortFromConfig() {
33
+ return cli.readPortFromConfig();
34
+ }
31
35
  /**
32
36
  * Local install-health warnings that `flair doctor` also checks (flair#852).
33
37
  *
@@ -110,6 +114,51 @@ function oauthDetailLines(o) {
110
114
  // 19926: current default (DEFAULT_PORT)
111
115
  // 19925: ops-anvil VM secondary
112
116
  const LOCAL_FLAIR_PROBE_PORTS = [9926, 19926, 19925];
117
+ /**
118
+ * The unreachable-path guidance for a localhost target, as printable lines.
119
+ *
120
+ * flair#1719: the old message asserted "Your config points at <resolved URL>"
121
+ * without ever reading the config, and then told the user to "set port: N" in
122
+ * a file that may already say exactly that — a remedy that cannot work. This
123
+ * reads the per-user config and only names it when it actually disagrees with
124
+ * the running daemon; when the config is already correct it points at the
125
+ * command that reconciles the instance record instead of the file.
126
+ *
127
+ * Pure so the wording is pinned by a unit test (the daemon is not required).
128
+ */
129
+ export function formatPortDriftGuidance(args) {
130
+ const lines = [];
131
+ if (args.discoveredPort == null) {
132
+ if (args.configuredPort != null) {
133
+ lines.push(`\n ~/.flair/config.yaml records port ${args.configuredPort}, but nothing answered there.`);
134
+ }
135
+ lines.push(`\n Run: flair start or flair doctor`);
136
+ return lines;
137
+ }
138
+ const altUrl = `http://127.0.0.1:${args.discoveredPort}`;
139
+ lines.push(`\n ⚠ Found a Flair daemon listening on port ${args.discoveredPort} (URL: ${altUrl}).`);
140
+ if (args.configuredPort === args.discoveredPort) {
141
+ // The config already names the running port. The divergence is in the
142
+ // instance's own record, not the operator's config — do not send them to
143
+ // edit a file that is already right.
144
+ lines.push(` ~/.flair/config.yaml already records port ${args.configuredPort}; the resolved URL (${args.baseUrl}) is not that port.`);
145
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
146
+ lines.push(` Permanent fix: flair doctor (reconcile the instance's recorded port with the running daemon)`);
147
+ }
148
+ else if (args.configuredPort != null) {
149
+ lines.push(` ~/.flair/config.yaml records port ${args.configuredPort}; the daemon is on ${args.discoveredPort}.`);
150
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
151
+ lines.push(` Permanent fix: edit ~/.flair/config.yaml to set port: ${args.discoveredPort}`);
152
+ lines.push(` Or: flair doctor`);
153
+ }
154
+ else {
155
+ lines.push(` No port is recorded in ~/.flair/config.yaml.`);
156
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
157
+ lines.push(` Permanent fix: edit ~/.flair/config.yaml to set port: ${args.discoveredPort}`);
158
+ lines.push(` Or: flair doctor`);
159
+ }
160
+ return lines;
161
+ }
113
162
  export function isLocalhostUrl(url) {
114
163
  try {
115
164
  const u = new URL(url);
@@ -193,6 +242,10 @@ export function register(program) {
193
242
  // fact is current (flair#1341). Independent of Harper health; runs either way.
194
243
  const versionCheckResult = await checkVersion(__pkgVersion);
195
244
  const versionNudge = formatVersionNudge(versionCheckResult);
245
+ // flair#1692: name the registry (and where it came from) on every status
246
+ // check, so a redirected mirror is never silent — including when the
247
+ // version answer came from cache and no network request was made.
248
+ const registryNotice = await resolveRegistryNotice(FLAIR_PKG_NAME);
196
249
  if (opts.json) {
197
250
  const out = { healthy, url: baseUrl, flairVersion: __pkgVersion, ...healthData };
198
251
  if (localWarnings.length > 0) {
@@ -205,6 +258,10 @@ export function register(program) {
205
258
  out.discoveredPort = discoveredPort;
206
259
  if (versionCheckResult.latest)
207
260
  out.latestVersion = versionCheckResult.latest;
261
+ if (registryNotice.line)
262
+ out.registry = registryNotice.line;
263
+ if (registryNotice.error)
264
+ out.registryError = registryNotice.error;
208
265
  console.log(JSON.stringify(out, null, 2));
209
266
  if (!healthy)
210
267
  process.exit(1);
@@ -213,16 +270,27 @@ export function register(program) {
213
270
  if (!healthy) {
214
271
  console.log(`Flair v${__pkgVersion} — 🔴 unreachable`);
215
272
  console.log(` URL: ${baseUrl}`);
273
+ if (registryNotice.line)
274
+ console.log(` ${registryNotice.line}`);
275
+ if (registryNotice.error)
276
+ console.log(` ⚠ ${registryNotice.error}`);
216
277
  if (discoveredPort != null) {
217
- const altUrl = `http://127.0.0.1:${discoveredPort}`;
218
- console.log(`\n ⚠ Found a Flair daemon listening on port ${discoveredPort} (URL: ${altUrl}).`);
219
- console.log(` Your config points at ${baseUrl} — drift detected.`);
220
- console.log(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
221
- console.log(` Permanent fix: edit ~/.flair/config.yaml to set port: ${discoveredPort}`);
222
- console.log(` Or: flair doctor (when port-drift detection lands there)`);
278
+ for (const line of formatPortDriftGuidance({
279
+ baseUrl,
280
+ discoveredPort,
281
+ configuredPort: readPortFromConfig(),
282
+ })) {
283
+ console.log(line);
284
+ }
223
285
  }
224
286
  else {
225
- console.log(`\n Run: flair start or flair doctor`);
287
+ for (const line of formatPortDriftGuidance({
288
+ baseUrl,
289
+ discoveredPort: null,
290
+ configuredPort: readPortFromConfig(),
291
+ })) {
292
+ console.log(line);
293
+ }
226
294
  }
227
295
  if (versionNudge) {
228
296
  const color = versionNudge.severity === "red" ? render.c.red : render.c.yellow;
@@ -288,6 +356,10 @@ export function register(program) {
288
356
  const metaParts = [pidPart, uptimePart].filter(Boolean).join(render.wrap(render.c.dim, " · "));
289
357
  console.log(`${versionStr} ${render.wrap(render.c.dim, "—")} ${runStatus}${metaParts ? ` ${metaParts}` : ""}`);
290
358
  console.log(render.kv("URL", baseUrl));
359
+ if (registryNotice.line)
360
+ console.log(render.kv("Registry", registryNotice.line.replace(/^registry:\s*/, "")));
361
+ if (registryNotice.error)
362
+ console.log(` ${render.icons.warn} ${render.wrap(render.c.yellow, registryNotice.error)}`);
291
363
  if (versionNudge) {
292
364
  const color = versionNudge.severity === "red" ? render.c.red : render.c.yellow;
293
365
  console.log(`\n ${render.wrap(color, "⚠")} ${render.wrap(color, versionNudge.message)}`);
@@ -7,6 +7,7 @@ import { defaultKeysDir } from "../lib/auth-resolve.js";
7
7
  import { renderVerifiedSummary } from "../lib/doctor-run.js";
8
8
  import { isDetached, renderDetachedWarning } from "../lib/launchd-management.js";
9
9
  import { FLAIR_MCP_PACKAGE, clearFlairCliVersionCache } from "../lib/mcp-spec.js";
10
+ import { createRegistryNoticePrinter, fetchLatestVersion, isStrictSemver } from "../lib/npm-registry.js";
10
11
  import { ownedPinRefreshShouldReport, refreshOwnedPins } from "../lib/owned-pins.js";
11
12
  import { extractSnapshotSafely, validateSnapshotArchive } from "../lib/safe-snapshot-extract.js";
12
13
  import { collectUpgradeExecPathWarning, findFlairPackageDir, resolveNpmGlobalFlairPackage, resolveServingFlairPackage } from "../lib/upgrade-exec-path.js";
@@ -836,17 +837,36 @@ export function register(program) {
836
837
  },
837
838
  ];
838
839
  const findings = [];
840
+ // flair#1692: name the registry (and where it came from) the moment it is
841
+ // resolved, so a redirected registry is visible to the operator before
842
+ // anything is fetched or installed. One line per distinct registry.
843
+ const noticeRegistry = createRegistryNoticePrinter();
839
844
  for (const { name, probe, kind, transitive } of packages) {
840
845
  if (transitive && !showAll)
841
846
  continue;
842
847
  try {
843
848
  let registryLatest = null;
844
849
  try {
845
- const res = await fetch(`https://registry.npmjs.org/${name}/latest`, { signal: AbortSignal.timeout(5000) });
846
- if (res.ok) {
847
- const data = await res.json();
848
- registryLatest = typeof data.version === "string" && data.version ? data.version : null;
850
+ // flair#1688: resolve the registry npm is configured to use for this
851
+ // package (scope mapping + .npmrc + env) instead of a hardcoded host.
852
+ // flair#1692: print it, refuse disallowed schemes, disable redirects,
853
+ // and validate the returned value as strict semver before it can be
854
+ // used as an `npm install` spec.
855
+ const lookup = await fetchLatestVersion(name, {
856
+ timeoutMs: 5000,
857
+ onRegistry: noticeRegistry,
858
+ });
859
+ if (lookup.kind === "ok") {
860
+ registryLatest = lookup.version;
861
+ }
862
+ else if (lookup.kind === "invalid") {
863
+ console.error(` ⚠ ${name}: registry returned a non-semver "latest" (${JSON.stringify(lookup.value)}) ` +
864
+ `from ${lookup.registry.url} — refusing to use it as an install spec.`);
849
865
  }
866
+ else if (lookup.kind === "refused") {
867
+ console.error(lookup.message);
868
+ }
869
+ // kind === "unavailable": offline/timed out — the pin path must still work.
850
870
  }
851
871
  catch { /* /latest timed out or failed — pin path must still work */ }
852
872
  let latest;
@@ -867,7 +887,14 @@ export function register(program) {
867
887
  continue;
868
888
  latest = registryLatest;
869
889
  }
870
- if (name === FLAIR_PKG_NAME && latest !== "unknown") {
890
+ // flair#1692: a non-semver target must never reach an install spec
891
+ // (npm treats `pkg@<url>` as a remote tarball). This also covers the
892
+ // operator pin on the plain-tree lane.
893
+ if (!isStrictSemver(latest)) {
894
+ console.error(` ⚠ ${name}: refusing non-semver install target ${JSON.stringify(latest)} — expected a version like 1.2.3.`);
895
+ continue;
896
+ }
897
+ if (name === FLAIR_PKG_NAME) {
871
898
  try {
872
899
  primeVersionCheckCache(latest);
873
900
  }
@@ -1225,6 +1252,15 @@ export function register(program) {
1225
1252
  let flairInstallFailed = false;
1226
1253
  for (const { pkg, latest } of npmUpgrades) {
1227
1254
  try {
1255
+ // flair#1692 backstop: the listing validated this, but the install is
1256
+ // the point of no return. npm accepts `pkg@<url>` as a remote-tarball
1257
+ // spec, so a non-semver target must never reach this argv.
1258
+ if (!isStrictSemver(latest)) {
1259
+ console.error(` ❌ ${pkg} upgrade skipped: non-semver target ${JSON.stringify(latest)}`);
1260
+ if (pkg === FLAIR_PKG_NAME)
1261
+ flairInstallFailed = true;
1262
+ continue;
1263
+ }
1228
1264
  if (treePlan && pkg === FLAIR_PKG_NAME) {
1229
1265
  console.log(` Fetching ${pkg}@${latest} (npm pack) and swapping ${treePlan.treeDir}...`);
1230
1266
  await applyPlainTreeUpgrade(treePlan);
@@ -106,25 +106,35 @@ const HOOK_VALUE_SAFE_RE = /^[A-Za-z0-9._:/-]+$/;
106
106
  export function isHookCommandValueSafe(value) {
107
107
  return typeof value === "string" && HOOK_VALUE_SAFE_RE.test(value);
108
108
  }
109
- /**
110
- * Build the exact `command` string to register as a SessionStart hook.
111
- * Throws (rather than emitting a quoted approximation) when a value cannot be
112
- * represented safely — see HOOK_VALUE_SAFE_RE.
113
- */
114
- export function buildSessionStartHookCommand(agentId, flairUrl) {
109
+ export function buildSessionStartHookCommand(agentId, flairUrl, opts) {
115
110
  if (!isHookCommandValueSafe(agentId)) {
116
111
  throw new Error(`agent id '${agentId}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
117
112
  }
118
113
  if (flairUrl != null && flairUrl !== "" && !isHookCommandValueSafe(flairUrl)) {
119
114
  throw new Error(`Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
120
115
  }
121
- const env = flairUrl ? `FLAIR_AGENT_ID=${agentId} FLAIR_URL=${flairUrl}` : `FLAIR_AGENT_ID=${agentId}`;
116
+ const harness = opts?.harness ?? "claude-code";
117
+ const envParts = harness === "codex" ? [`FLAIR_HOOK_HARNESS=${harness}`] : [];
118
+ envParts.push(`FLAIR_AGENT_ID=${agentId}`);
119
+ if (flairUrl)
120
+ envParts.push(`FLAIR_URL=${flairUrl}`);
121
+ const env = envParts.join(" ");
122
122
  // Same pin as user-local MCP client configs (mcpServerSpec / flair#907).
123
123
  // Public plugin mcp.json stays unpinned (flair#1308) — that is a scraped
124
124
  // listing, not a machine we just wired.
125
125
  const invocation = `${env} npx -y -p ${mcpServerSpec()} ${SESSION_START_HOOK_MARKER}`;
126
+ // Codex: keep `|| true` so a missing binary cannot brick session start
127
+ // (#1007) but do not swallow stderr — an auth_error must be visible (#1734).
128
+ if (harness === "codex") {
129
+ return `sh -c 'out=$(${invocation}) && printf %s "$out" || true'`;
130
+ }
126
131
  return `sh -c 'out=$(${invocation} 2>/dev/null) && printf %s "$out" || true'`;
127
132
  }
133
+ /** Infer harness from the settings path `flair hook install` / doctor write. */
134
+ export function hookHarnessFromSettingsPath(settingsPath) {
135
+ const normalized = settingsPath.replace(/\\/g, "/");
136
+ return normalized.includes("/.codex/hooks.json") ? "codex" : "claude-code";
137
+ }
128
138
  /**
129
139
  * The `npx -y -p` invocation that runs `flair-session-start` — pinned
130
140
  * (`@tpsdev-ai/flair-mcp@<ver>`) or the pre-#1143 unpinned form. Used by
@@ -137,17 +147,20 @@ export function isSessionStartHookInvocation(command) {
137
147
  return typeof command === "string" && SESSION_START_HOOK_INVOCATION_RE.test(command);
138
148
  }
139
149
  /**
140
- * Does this command absorb a failure instead of surfacing it? Checked as two
141
- * independent PROPERTIES (stderr discarded, non-zero exit absorbed) rather
142
- * than by string equality with what we currently emit, so a hand-rolled
143
- * command that genuinely achieves both is not nagged about.
150
+ * Does this command absorb a failure so the harness session still starts?
151
+ * flair#1734: "silenced" means `|| true` (won't brick the session), not
152
+ * "stderr discarded". Codex's installer keeps stderr visible on purpose.
144
153
  */
145
154
  export function hookCommandIsSilenced(command) {
146
155
  if (typeof command !== "string")
147
156
  return false;
148
- const discardsStderr = command.includes("2>/dev/null") || command.includes("2>&-");
149
- const absorbsFailure = /\|\|\s*(?:true|:)(?:\s|'|$)/.test(command) || /;\s*(?:true|:)\s*'?\s*$/.test(command);
150
- return discardsStderr && absorbsFailure;
157
+ return /\|\|\s*(?:true|:)(?:\s|'|$)/.test(command) || /;\s*(?:true|:)\s*'?\s*$/.test(command);
158
+ }
159
+ /** Does the command discard stderr? Codex's installer must not (flair#1734). */
160
+ export function hookCommandDiscardsStderr(command) {
161
+ if (typeof command !== "string")
162
+ return false;
163
+ return command.includes("2>/dev/null") || command.includes("2>&-");
151
164
  }
152
165
  /**
153
166
  * The EXACT unwrapped shape Flair wrote before #1007. Recognising it precisely
@@ -775,14 +788,53 @@ export function checkSessionStartHook(homeDir, settingsPath) {
775
788
  return { present: false, path };
776
789
  }
777
790
  }
778
- // ── flair-mcp presence by WIRING, not global install (flair#1208) ───────────
779
- //
780
- // flair-mcp is zero-install via npx by design (#1168): a correctly-wired
781
- // machine invokes it as `npx -y -p @tpsdev-ai/flair-mcp` and NEVER installs it
782
- // globally, so `flair upgrade`'s global bin/lib probe finds nothing and
783
- // mis-reports it "not detected." Its real "installed version" is the pin its
784
- // wiring carries — the mcpServerSpec() written into a client's MCP config
785
- // (pinned since #1135). Detect it there instead.
791
+ const FLAIR_AT_SPEC_RE = /@tpsdev-ai\/(flair-mcp|flair-client)@([0-9A-Za-z][^\s"'\],]*)/g;
792
+ const FLAIR_JSON_DEP_RE = /"@tpsdev-ai\/(flair-mcp|flair-client)"\s*:\s*"([^"]+)"/g;
793
+ /** Strip npm range / workspace prefixes so `^0.17.0` compares as `0.17.0`. */
794
+ export function normalizeDeclaredPinVersion(raw) {
795
+ if (typeof raw !== "string")
796
+ return null;
797
+ let v = raw.trim();
798
+ if (!v)
799
+ return null;
800
+ v = v.replace(/^(workspace|npm):/, "");
801
+ v = v.replace(/^[\^~>=<\s]+/, "");
802
+ v = v.replace(/^v/, "");
803
+ // Require X.Y.Z so `latest` / tags / bare names are not pins.
804
+ const m = v.match(/^(\d+\.\d+\.\d+[^\s"'\],]*)/);
805
+ return m ? m[1] : null;
806
+ }
807
+ /**
808
+ * Every `@tpsdev-ai/flair-mcp` / `@tpsdev-ai/flair-client` pin in a wiring
809
+ * string or package.json. Covers `pkg@<ver>` specs (MCP args, hook commands)
810
+ * and `"pkg": "<ver>"` dependency fields. Bare / unpinned / `latest` specs
811
+ * contribute nothing.
812
+ *
813
+ * flair#1383: doctor must read the actual installed pins, not infer age
814
+ * from "pin !== CLI version".
815
+ */
816
+ export function extractFlairPackagePins(text) {
817
+ if (typeof text !== "string")
818
+ return [];
819
+ const out = [];
820
+ const seen = new Set();
821
+ const add = (pkg, rawVer) => {
822
+ const version = normalizeDeclaredPinVersion(rawVer);
823
+ if (!version)
824
+ return;
825
+ const name = pkg;
826
+ const key = `${name}@${version}`;
827
+ if (seen.has(key))
828
+ return;
829
+ seen.add(key);
830
+ out.push({ package: name, version });
831
+ };
832
+ for (const m of text.matchAll(FLAIR_AT_SPEC_RE))
833
+ add(m[1], m[2]);
834
+ for (const m of text.matchAll(FLAIR_JSON_DEP_RE))
835
+ add(m[1], m[2]);
836
+ return out;
837
+ }
786
838
  /**
787
839
  * Extract a pinned `@tpsdev-ai/flair-mcp` version from any wiring string — a
788
840
  * client MCP `args` array, a Codex TOML args line, or a SessionStart hook
@@ -794,12 +846,7 @@ export function checkSessionStartHook(homeDir, settingsPath) {
794
846
  * establishes that flair-mcp is wired but contributes no version.
795
847
  */
796
848
  export function extractFlairMcpPin(text) {
797
- if (typeof text !== "string")
798
- return null;
799
- // `@tpsdev-ai/flair-mcp@<version>`; the version token runs until the first
800
- // character that can't appear in a spec embedded in JSON args / TOML.
801
- const m = text.match(/@tpsdev-ai\/flair-mcp@([0-9A-Za-z][^\s"'\],]*)/);
802
- return m ? m[1] : null;
849
+ return extractFlairPackagePins(text).find((p) => p.package === "flair-mcp")?.version ?? null;
803
850
  }
804
851
  export function detectWiredFlairMcp(homeDir) {
805
852
  let wired = false;
@@ -914,7 +961,7 @@ export function fixSessionStartHook(homeDir, agentId, settingsPath) {
914
961
  hooks: [
915
962
  {
916
963
  type: "command",
917
- command: buildSessionStartHookCommand(agentId),
964
+ command: buildSessionStartHookCommand(agentId, undefined, { harness: hookHarnessFromSettingsPath(path) }),
918
965
  },
919
966
  ],
920
967
  });
@@ -969,6 +1016,43 @@ const defaultProbeRunner = (command, timeoutMs) => {
969
1016
  spawnError: res.error && !timedOut ? res.error.message : null,
970
1017
  };
971
1018
  };
1019
+ /**
1020
+ * Delivery probe (flair#1734): run the registered command so we can classify
1021
+ * SessionStart additionalContext. Must NOT set FLAIR_HOOK_PROBE — that path
1022
+ * prints inert `{}` and would make every status look undelivered.
1023
+ */
1024
+ export function probeSessionStartHookDelivery(command, opts = {}) {
1025
+ const timeoutMs = opts.timeoutMs ?? 8_000;
1026
+ const runner = opts.runner ?? ((cmd, ms) => {
1027
+ const res = spawnSync("/bin/sh", ["-c", cmd], {
1028
+ input: "{}",
1029
+ encoding: "utf-8",
1030
+ timeout: ms,
1031
+ env: {
1032
+ ...process.env,
1033
+ FLAIR_HOOK_PROBE: "0",
1034
+ FLAIR_HOOK_DELIVERY_PROBE: "1",
1035
+ FLAIR_HOOK_TIMEOUT_MS: "4000",
1036
+ FLAIR_PRESENCE_TIMEOUT_MS: "1",
1037
+ },
1038
+ });
1039
+ const timedOut = res.signal === "SIGTERM" && res.status === null;
1040
+ return {
1041
+ exitCode: res.status,
1042
+ stdout: res.stdout ?? "",
1043
+ stderr: res.stderr ?? "",
1044
+ timedOut,
1045
+ spawnError: res.error && !timedOut ? res.error.message : null,
1046
+ };
1047
+ });
1048
+ try {
1049
+ return runner(command, timeoutMs);
1050
+ }
1051
+ catch (err) {
1052
+ const reason = err instanceof Error ? err.message : String(err);
1053
+ return { exitCode: null, stdout: "", stderr: "", timedOut: false, spawnError: reason };
1054
+ }
1055
+ }
972
1056
  /**
973
1057
  * Run a registered hook command once, bounded, with probe-mode env set.
974
1058
  * Only ever called for commands isFlairHookCommand() recognises — doctor does
@@ -1090,7 +1174,9 @@ export function upgradeSessionStartHookCommand(homeDir, settingsPath) {
1090
1174
  message: `the SessionStart hook in ${path} is not the command Flair wrote — leaving it untouched`,
1091
1175
  };
1092
1176
  }
1093
- const next = buildSessionStartHookCommand(legacy.agentId, legacy.flairUrl);
1177
+ const next = buildSessionStartHookCommand(legacy.agentId, legacy.flairUrl, {
1178
+ harness: hookHarnessFromSettingsPath(path),
1179
+ });
1094
1180
  if (next === hook.command)
1095
1181
  return { ok: true, path, changed: false, message: `SessionStart hook in ${path} is already current` };
1096
1182
  hook.command = next;
@@ -1137,8 +1223,8 @@ function sessionStartHookHint(agentId, path) {
1137
1223
  {
1138
1224
  type: "command",
1139
1225
  command: isHookCommandValueSafe(agentId)
1140
- ? buildSessionStartHookCommand(agentId)
1141
- : buildSessionStartHookCommand("me"),
1226
+ ? buildSessionStartHookCommand(agentId, undefined, { harness: hookHarnessFromSettingsPath(path) })
1227
+ : buildSessionStartHookCommand("me", undefined, { harness: hookHarnessFromSettingsPath(path) }),
1142
1228
  },
1143
1229
  ],
1144
1230
  },
@@ -19,6 +19,7 @@
19
19
  import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
20
20
  import { join, resolve } from "node:path";
21
21
  import { homedir } from "node:os";
22
+ import { fetchDeclaredDependencies } from "./lib/npm-registry.js";
22
23
  /** Filename of the engine-version stamp inside the data directory. */
23
24
  export const ENGINE_VERSION_STAMP = "engine-version.txt";
24
25
  /** Root directory for pre-upgrade snapshots (~/.flair/upgrade-snapshots). */
@@ -47,11 +48,18 @@ export function readInstalledHarperVersion(packageRoot) {
47
48
  */
48
49
  export async function fetchDeclaredHarperVersion(flairVersion) {
49
50
  try {
50
- const res = await fetch(`https://registry.npmjs.org/@tpsdev-ai/flair/${flairVersion}`, { signal: AbortSignal.timeout(5000) });
51
- if (!res.ok)
51
+ // flair#1688: resolve the configured registry rather than assuming npmjs —
52
+ // the engine-version decision must look at the same package the upgrade
53
+ // will actually install. flair#1692: the same scheme allowlist, redirect
54
+ // refusal, npm transport, and non-default-registry handling apply.
55
+ const result = await fetchDeclaredDependencies("@tpsdev-ai/flair", flairVersion, { timeoutMs: 5000 });
56
+ if (result.kind === "refused") {
57
+ console.error(result.message);
52
58
  return null;
53
- const data = await res.json();
54
- return data.dependencies?.harper ?? data.dependencies?.["@harperfast/harper"] ?? null;
59
+ }
60
+ if (result.kind !== "ok")
61
+ return null;
62
+ return result.dependencies?.harper ?? result.dependencies?.["@harperfast/harper"] ?? null;
55
63
  }
56
64
  catch {
57
65
  return null;
@@ -30,6 +30,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "no
30
30
  import { join } from "node:path";
31
31
  import { tmpdir } from "node:os";
32
32
  import { createRequire } from "node:module";
33
+ import { createRegistryNoticePrinter, fetchDeclaredDependencies, fetchLatestVersion } from "./lib/npm-registry.js";
33
34
  /**
34
35
  * Minimum harper version whose component packager works when the
35
36
  * package root is under node_modules (flair#513 — the empty-tarball fix landed
@@ -154,30 +155,44 @@ export function buildDeployablePackageJson(flairVersion, pin) {
154
155
  return pkg;
155
156
  }
156
157
  // ─── Default (real) dependency implementations ──────────────────────────────
157
- const REGISTRY = "https://registry.npmjs.org";
158
+ // flair#1692: one printer per process, so a Fabric upgrade names the registry
159
+ // (and source) it stages from without repeating the line per lookup.
160
+ const noticeRegistry = createRegistryNoticePrinter();
158
161
  async function defaultFetchLatestFlairVersion() {
159
- const res = await fetch(`${REGISTRY}/${FLAIR_PKG}/latest`, {
160
- signal: AbortSignal.timeout(10_000),
161
- });
162
- if (!res.ok) {
163
- throw new Error(`npm registry returned ${res.status} for ${FLAIR_PKG}/latest`);
162
+ // flair#1688: the configured registry (scoped `@tpsdev-ai:registry`,
163
+ // project/user/global .npmrc, env `npm_config_registry`), not a hardcoded
164
+ // host — a Fabric upgrade must stage the package from the mirror the
165
+ // operator configured, or fail rather than silently use the public one.
166
+ // flair#1692: the value is validated as strict semver before it is used as
167
+ // `dependencies` in the staged package.json (npm accepts `pkg@<url>` as a
168
+ // remote-tarball spec, so an unvalidated value is an arbitrary-install
169
+ // primitive).
170
+ const result = await fetchLatestVersion(FLAIR_PKG, { timeoutMs: 10_000, onRegistry: noticeRegistry });
171
+ if (result.kind === "ok")
172
+ return result.version;
173
+ if (result.kind === "refused")
174
+ throw new Error(result.message);
175
+ if (result.kind === "invalid") {
176
+ throw new Error(`npm registry returned a non-semver latest version (${JSON.stringify(result.value)}) for ${FLAIR_PKG} ` +
177
+ `from ${result.registry.url} (source: ${result.registry.source}) — refusing to use it`);
164
178
  }
165
- const data = (await res.json());
166
- if (!data.version)
167
- throw new Error(`No version in registry response for ${FLAIR_PKG}`);
168
- return data.version;
179
+ throw new Error(`Could not determine ${FLAIR_PKG}/latest: ${result.message}`);
169
180
  }
170
181
  async function defaultFetchDeclaredHarperVersion(flairVersion) {
171
- const res = await fetch(`${REGISTRY}/${FLAIR_PKG}/${flairVersion}`, {
172
- signal: AbortSignal.timeout(10_000),
182
+ const result = await fetchDeclaredDependencies(FLAIR_PKG, flairVersion, {
183
+ timeoutMs: 10_000,
184
+ onRegistry: noticeRegistry,
173
185
  });
174
- if (!res.ok)
186
+ if (result.kind === "refused") {
187
+ console.error(result.message);
188
+ return null;
189
+ }
190
+ if (result.kind !== "ok")
175
191
  return null;
176
- const data = (await res.json());
177
192
  // Either package name (flair#870) — pre-rename flair versions declare the
178
193
  // scoped one, and those are precisely the versions that may need an override.
179
194
  for (const name of HARPER_PKG_NAMES) {
180
- const declared = data.dependencies?.[name];
195
+ const declared = result.dependencies?.[name];
181
196
  if (declared)
182
197
  return declared;
183
198
  }