@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
@@ -4,15 +4,19 @@ import { markStale, sortOldestVersionFirst } from "../fleet-presence.js";
4
4
  import { hookSettingsPath, repinSessionStartHook, resolveHookAgentId } from "../hook-install.js";
5
5
  import { detectClients, wireAntigravity, wireClaudeCode, wireCodex, wireCursor, wireGemini } from "../install/clients.js";
6
6
  import { checkGlobalBinOnPath, resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
7
- import { buildEd25519Auth, defaultKeysDir, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
7
+ import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
8
8
  import { flairConfigYamlCandidates, readPortFromYamlFile, resolveFlairConfigYaml } from "../lib/doctor-config-path.js";
9
9
  import { collectFederationEnv, describeFederationDriverFinding, federationPeersConfigured, loadYamlDoc } from "../lib/doctor-federation-driver.js";
10
+ import { plistCarriesInlineAdminPassword } from "../lib/launchd-management.js";
10
11
  import { DOCTOR_CHECK_IDS, catalogIssueDelta, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
12
+ import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
13
+ import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
11
14
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
12
15
  import { flairCliVersion, unpinnedSpecWarning } from "../lib/mcp-spec.js";
13
16
  import { staleSessionStartHookPins } from "../lib/owned-pins.js";
14
17
  import * as render from "../render.js";
15
- import { checkVersion, formatVersionNudge, probeInstanceVersion } from "../version-check.js";
18
+ import { checkVersion, formatVersionNudge, probeInstanceVersion, FLAIR_PKG_NAME } from "../version-check.js";
19
+ import { resolveRegistryNotice } from "../lib/npm-registry.js";
16
20
  import { existsSync, readFileSync, statSync } from "node:fs";
17
21
  import { homedir } from "node:os";
18
22
  import { dirname, join } from "node:path";
@@ -187,6 +191,16 @@ export function register(program) {
187
191
  `Commands run through the CLI; the instance serves the data.`)}`);
188
192
  }
189
193
  }
194
+ // flair#1692: name the registry (and where it came from) on every doctor
195
+ // check, so a redirected mirror is visible to the operator.
196
+ const registryNotice = await resolveRegistryNotice(FLAIR_PKG_NAME);
197
+ if (registryNotice.line) {
198
+ console.log(` ${render.icons.info} ${render.wrap(render.c.dim, registryNotice.line)}`);
199
+ }
200
+ if (registryNotice.error) {
201
+ console.log(` ${render.icons.warn} ${render.wrap(render.c.yellow, registryNotice.error)}`);
202
+ issues++;
203
+ }
190
204
  // 0.5 npm global bin dir on PATH (flair#1134) — a user-prefix
191
205
  // `npm i -g` succeeds and then `flair` is command-not-found because
192
206
  // <prefix>/bin never made it into PATH. postinstall warns at install
@@ -368,12 +382,14 @@ export function register(program) {
368
382
  // every other command) nudges about on stderr; doctor prints the full
369
383
  // picture here instead of a one-liner and `--fix` offers the restart.
370
384
  let runningVersion = null;
385
+ let embedGpuFromHealth;
371
386
  if (harperResponding) {
372
387
  try {
373
388
  const healthRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(3000) });
374
389
  if (healthRes.ok) {
375
390
  const body = (await healthRes.json());
376
391
  runningVersion = typeof body?.version === "string" ? body.version : null;
392
+ embedGpuFromHealth = body.embedding;
377
393
  }
378
394
  }
379
395
  catch { /* leave runningVersion null — reported below as "unknown" */ }
@@ -406,6 +422,14 @@ export function register(program) {
406
422
  else {
407
423
  console.log(` ${render.icons.warn} Could not determine the running server's version`);
408
424
  }
425
+ // flair#1437: fail-loud Metal fallback. Health states it; operators
426
+ // read doctor. A stated CPU default is silent here.
427
+ const embedGpuFinding = describeEmbedGpuDoctorFinding(embedGpuFromHealth);
428
+ if (embedGpuFinding) {
429
+ console.log(` ${render.icons.error} ${embedGpuFinding.message}`);
430
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${embedGpuFinding.fixHint}`);
431
+ issues++;
432
+ }
409
433
  }
410
434
  // 2. Keys directory
411
435
  const keysDir = defaultKeysDir();
@@ -485,6 +509,25 @@ export function register(program) {
485
509
  }
486
510
  }
487
511
  catch { /* best-effort — don't fail doctor over a malformed harper-config.yaml */ }
512
+ // 3b2. Admin-pass vs persisted Harper user (flair#837) — report-only,
513
+ // never `--fix`. File missing + hdb_user still in the data dir is the
514
+ // state bare `init` used to "fix" by writing a fresh file that 401s.
515
+ // The remedy names the two exits: `--admin-pass-file` / `--reset-admin-pass`.
516
+ try {
517
+ const dataDir = defaultDataDir();
518
+ const finding = adminPassDesyncFinding({
519
+ adminPassFileExists: existsSync(defaultAdminPassPath()),
520
+ persistedAdminUser: detectPersistedAdminUser(dataDir),
521
+ dataDir,
522
+ adminPassPath: defaultAdminPassPath(),
523
+ });
524
+ if (finding?.flagged) {
525
+ console.log(` ${render.icons.error} ${finding.message}`);
526
+ console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
527
+ issues++;
528
+ }
529
+ }
530
+ catch { /* best-effort — a missing data dir is not a doctor crash */ }
488
531
  // 3c. Ops-socket permission posture (flair#763) — report-only, never
489
532
  // auto-fixed. Re-tightening a live socket needs a restart, so the remedy is
490
533
  // `flair init`/restart (which re-applies the posture), not a `doctor --fix`.
@@ -1231,6 +1274,13 @@ export function register(program) {
1231
1274
  // verify) is repairLaunchdManagement, which is the only place that
1232
1275
  // touches the real filesystem and launchctl.
1233
1276
  console.log(`\n ${render.wrap(render.c.bold, "Launchd management")}`);
1277
+ // #1693: an adopted/registered plist that embeds the admin password inline
1278
+ // is a FAIL even when launchd still reports the job managed — launchd keeps
1279
+ // the loaded definition, so the on-disk downgrade hides behind a healthy
1280
+ // job. The path is resolved BEFORE the repair for the no-fix arm and AFTER
1281
+ // it for the --fix arm, so a --fix that regenerated in pass-file mode (or
1282
+ // migrated the label) clears the finding.
1283
+ let launchdPlistForCheck;
1234
1284
  if (autoFix && !dryRun) {
1235
1285
  // Execute the repair directly; it re-derives the plan internally and
1236
1286
  // verifies via assessLaunchdManagement (fail-loud, never a silent pass).
@@ -1259,6 +1309,7 @@ export function register(program) {
1259
1309
  // Report only (no --fix, or --fix --dry-run): compute the plan, touch
1260
1310
  // nothing. A regenerate plan is drift; a refuse plan is a named refusal.
1261
1311
  const repairPlan = planLaunchdRepairFor(defaultDataDir(), effectivePort);
1312
+ launchdPlistForCheck = repairPlan.plistPath;
1262
1313
  switch (repairPlan.plan.kind) {
1263
1314
  case "no-op":
1264
1315
  console.log(` ${render.icons.ok} ${repairPlan.plan.detail}`);
@@ -1289,6 +1340,26 @@ export function register(program) {
1289
1340
  break;
1290
1341
  }
1291
1342
  }
1343
+ // flair#1693: the check itself (the shared plist writer that stops
1344
+ // init/doctor/upgrade producing this shape is #1693's own change). In the
1345
+ // --fix arm the plan was executed above, so resolve the (possibly
1346
+ // label-migrated) plist path now and read post-repair bytes.
1347
+ if (launchdPlistForCheck === undefined) {
1348
+ launchdPlistForCheck = planLaunchdRepairFor(defaultDataDir(), effectivePort).plistPath;
1349
+ }
1350
+ if (typeof launchdPlistForCheck === "string" && existsSync(launchdPlistForCheck)) {
1351
+ try {
1352
+ const raw = readFileSync(launchdPlistForCheck, "utf-8");
1353
+ if (plistCarriesInlineAdminPassword(raw)) {
1354
+ issues++;
1355
+ console.log(` ${render.icons.error} the launchd plist at ${launchdPlistForCheck} embeds HDB_ADMIN_PASSWORD inline instead of using the pass-file launcher`);
1356
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(regenerate in pass-file mode; #1693)")}`);
1357
+ }
1358
+ }
1359
+ catch {
1360
+ // Plist unreadable — the launchd plan above already reports presence.
1361
+ }
1362
+ }
1292
1363
  // 7a. Resolve which agent identities the two verified-read sections below
1293
1364
  // (Fleet presence, Migrations) iterate (flair#722). Previously both
1294
1365
  // sections required --agent explicitly; doctor already enumerates every
@@ -5,6 +5,7 @@ import { keystore, keyPath as keystoreKeyPath } from "../keystore.js";
5
5
  import * as render from "../render.js";
6
6
  import { runFederationVerify } from "../federation-verify.js";
7
7
  import { resolveHubPeerIdentity } from "../lib/federation-pair-identity.js";
8
+ import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
8
9
  import { defaultAdminPassPath, isLocalBase, resolveAdminUser, } from "../lib/auth-resolve.js";
9
10
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
10
11
  let cli;
@@ -158,6 +159,79 @@ export function signRequestBody(body, secretKey) {
158
159
  }
159
160
  // Alias: signBodyFresh for clarity at call sites
160
161
  const signBodyFresh = signRequestBody;
162
+ function isCompletePeerRow(row) {
163
+ if (!row || typeof row !== "object")
164
+ return false;
165
+ const r = row;
166
+ return typeof r.id === "string" && r.id.length > 0
167
+ && typeof r.publicKey === "string" && r.publicKey.length > 0;
168
+ }
169
+ /**
170
+ * Persist last-contact on the local Peer row after confirmed hub contact.
171
+ *
172
+ * Callers must invoke this only after a FederationSync 200 (sendBatch or
173
+ * the no-change liveness ping). lastSyncAt is the value HealthDetail counts
174
+ * as `connected` (flair#1499 / flair#1146). A failed ping must leave the
175
+ * stamp untouched so the answer stays `unknown`.
176
+ *
177
+ * Why a full-row upsert rather than the `{id, lastSyncAt}` `update` that
178
+ * has shipped since #426: Kern probed that partial update on Harper 5.2.8
179
+ * and 5.1.22 — it already lands, `publicKey` intact. We keep read-then-upsert
180
+ * to harden against a future Harper that treats an incomplete upsert as
181
+ * replace. On search-miss we refuse to write rather than depend on merge.
182
+ */
183
+ export async function persistLocalPeerLastSyncAt(args) {
184
+ const headers = { "Content-Type": "application/json", Authorization: args.auth };
185
+ let existing = null;
186
+ try {
187
+ const searchRes = await fetch(`${args.opsEndpoint}/`, {
188
+ method: "POST",
189
+ headers,
190
+ body: JSON.stringify({
191
+ operation: "search_by_value",
192
+ schema: "flair",
193
+ table: "Peer",
194
+ search_attribute: "id",
195
+ search_type: "equals",
196
+ search_value: args.peerId,
197
+ get_attributes: ["*"],
198
+ }),
199
+ signal: AbortSignal.timeout(10_000),
200
+ });
201
+ if (searchRes.ok) {
202
+ const rows = await searchRes.json();
203
+ const row = Array.isArray(rows) ? rows[0] : rows;
204
+ if (isCompletePeerRow(row) && row.id === args.peerId)
205
+ existing = row;
206
+ }
207
+ }
208
+ catch {
209
+ // Search miss — refuse to upsert an incomplete Peer.
210
+ }
211
+ if (!existing) {
212
+ return { ok: false, status: 0, error: "peer row missing or incomplete — refused to upsert a partial Peer" };
213
+ }
214
+ const upsertRes = await fetch(`${args.opsEndpoint}/`, {
215
+ method: "POST",
216
+ headers,
217
+ body: JSON.stringify({
218
+ operation: "upsert",
219
+ database: "flair",
220
+ table: "Peer",
221
+ records: [{
222
+ ...existing,
223
+ id: args.peerId,
224
+ lastSyncAt: args.lastSyncAt,
225
+ updatedAt: args.lastSyncAt,
226
+ }],
227
+ }),
228
+ signal: AbortSignal.timeout(10_000),
229
+ });
230
+ if (upsertRes.ok)
231
+ return { ok: true, status: upsertRes.status };
232
+ const txt = await upsertRes.text().catch(() => "");
233
+ return { ok: false, status: upsertRes.status, error: txt.slice(0, 200) };
234
+ }
161
235
  /**
162
236
  * The most recent CONTACT with any peer (max of peer.lastSyncAt), or null.
163
237
  *
@@ -367,12 +441,13 @@ export async function runFederationSyncOnce(opts) {
367
441
  }
368
442
  console.log(`Syncing to hub: ${hub.id}...`);
369
443
  const since = hub.lastSyncAt ?? new Date(0).toISOString();
370
- // Capture sync start time BEFORE we query records. We advance the local
371
- // hub peer's lastSyncAt to this value after success so the next poll's
372
- // `since` cursor moves forward — fixes task #146 (federation peer
373
- // .lastSyncAt update bug). Records updated DURING this sync will have
374
- // updatedAt > syncStartedAt and be picked up next cycle, not missed.
375
- const syncStartedAt = new Date().toISOString();
444
+ // Capture queriedAt BEFORE the table queries (task #146 no-miss).
445
+ // Mid-sync writes have updatedAt > queriedAt and are re-sent next
446
+ // cycle. The stamp is still written only after confirmed FederationSync
447
+ // contact (flair#1146) — the gate is when we persist, not what value
448
+ // we persist. Completion time here would make those writes permanently
449
+ // unfederated.
450
+ const queriedAt = new Date().toISOString();
376
451
  const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
377
452
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
378
453
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
@@ -564,39 +639,31 @@ export async function runFederationSyncOnce(opts) {
564
639
  totalBatches++;
565
640
  }
566
641
  }
567
- // Advance the local hub peer's lastSyncAt cursor. The hub-side
568
- // FederationSync handler updates ITS view of the spoke peer, but the
569
- // spoke never updated its own view of the hub — so `since` stayed at
570
- // whatever value was on the peer record at pair time (often near-epoch),
571
- // and every poll re-queried `updatedAt > since` and re-sent every
572
- // memory ever written. The receiver-side contentHash gate in
573
- // Federation.ts prevents the actual blob re-write, but advancing the
574
- // cursor here stops the redundant network traffic + Lambda compute
575
- // entirely. Task #146. Even no-change runs should advance.
576
- try {
577
- const advanceRes = await fetch(`${opsEndpoint}/`, {
578
- method: "POST",
579
- headers: { "Content-Type": "application/json", Authorization: auth },
580
- body: JSON.stringify({
581
- operation: "update",
582
- database: "flair",
583
- table: "Peer",
584
- records: [{ id: hub.id, lastSyncAt: syncStartedAt }],
585
- }),
586
- signal: AbortSignal.timeout(10_000),
587
- });
588
- if (!advanceRes.ok) {
589
- const txt = await advanceRes.text().catch(() => "");
590
- console.warn(`⚠️ Local hub.lastSyncAt advance failed (${advanceRes.status}): ${txt.slice(0, 200)}. Next poll will re-send memories.`);
642
+ // lastSyncAt is contact, not "the driver ran" (flair#1146). Persist only
643
+ // after a FederationSync 200 — sendBatch already threw on non-ok, so
644
+ // totalBatches > 0 means the hub answered. The no-change path must ping
645
+ // first; a failed ping leaves the stamp untouched → unknown.
646
+ const stampLocalContact = async () => {
647
+ try {
648
+ const advanced = await persistLocalPeerLastSyncAt({
649
+ opsEndpoint,
650
+ auth,
651
+ peerId: hub.id,
652
+ lastSyncAt: queriedAt,
653
+ });
654
+ if (!advanced.ok) {
655
+ console.warn(`⚠️ Local hub.lastSyncAt advance failed (${advanced.status}): ${advanced.error ?? ""}. Next poll will re-send memories.`);
656
+ }
591
657
  }
592
- }
593
- catch (advErr) {
594
- console.warn(`⚠️ Local hub.lastSyncAt advance error: ${advErr?.message ?? advErr}. Next poll will re-send memories.`);
595
- }
658
+ catch (advErr) {
659
+ console.warn(`⚠️ Local hub.lastSyncAt advance error: ${advErr?.message ?? advErr}. Next poll will re-send memories.`);
660
+ }
661
+ };
596
662
  if (totalBatches === 0) {
597
663
  // No-change syncs must still ping the hub so it updates the
598
664
  // spoke's lastSyncAt (liveness). Without this, idle-but-alive spokes
599
665
  // look indistinguishable from dead ones on the hub dashboard.
666
+ let pingOk = false;
600
667
  try {
601
668
  if (!secretKey)
602
669
  secretKey = await loadInstanceSecretKey(instance.id, opts);
@@ -615,10 +682,15 @@ export async function runFederationSyncOnce(opts) {
615
682
  const txt = await pingRes.text().catch(() => "");
616
683
  console.warn(`⚠️ Liveness ping to hub failed (${pingRes.status}): ${txt.slice(0, 200)}. Hub won't update spoke liveness.`);
617
684
  }
685
+ else {
686
+ pingOk = true;
687
+ }
618
688
  }
619
689
  catch (pingErr) {
620
690
  console.warn(`⚠️ Liveness ping error: ${pingErr?.message ?? pingErr}. Hub won't update spoke liveness.`);
621
691
  }
692
+ if (pingOk)
693
+ await stampLocalContact();
622
694
  // flair#1232: "No changes" is true only when nothing was found since
623
695
  // the cursor. If rows were found and every one was withheld as private,
624
696
  // say so — count and reason only, never content. A zero withheld count
@@ -628,6 +700,7 @@ export async function runFederationSyncOnce(opts) {
628
700
  : "No changes since last sync.");
629
701
  return { pushed: 0, skipped: 0 };
630
702
  }
703
+ await stampLocalContact();
631
704
  console.log(`✅ Synced ${totalMerged} records (${totalSkipped} skipped) across ${totalBatches} batches`);
632
705
  return { pushed: totalMerged, skipped: totalSkipped };
633
706
  }
@@ -1053,9 +1126,26 @@ export function register(program) {
1053
1126
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")
1054
1127
  .action(async (hubUrl, opts) => {
1055
1128
  const target = resolveTarget(opts);
1056
- const baseUrl = target ? target.replace(/\/$/, "") : undefined;
1129
+ // One URL for the identity GET and the named error. resolveBaseUrl
1130
+ // honors --target / FLAIR_TARGET / FLAIR_URL / --port — the same host
1131
+ // the GET actually probes (do not cite resolveBaseUrl only in the
1132
+ // rewriter while api() falls through to resolveHttpPort({})).
1133
+ const identityUrl = resolveBaseUrl(opts).replace(/\/$/, "");
1057
1134
  try {
1058
- const instance = await api("GET", "/FederationInstance", undefined, baseUrl ? { baseUrl } : undefined);
1135
+ // flair#820: the identity GET is pair's first step and is allowAdmin.
1136
+ // A 403 here is LOCAL (or --target REMOTE), never the hub handshake.
1137
+ // Rewrite Harper's raw AccessViolation into a named role/grant error.
1138
+ let instance;
1139
+ try {
1140
+ instance = await api("GET", "/FederationInstance", undefined, { baseUrl: identityUrl });
1141
+ }
1142
+ catch (err) {
1143
+ throw rewriteFederationPairLocalAccessError(err, {
1144
+ url: identityUrl,
1145
+ side: target ? "REMOTE" : "LOCAL",
1146
+ agentId: process.env.FLAIR_AGENT_ID,
1147
+ });
1148
+ }
1059
1149
  console.log(`${target ? "Remote" : "Local"} instance: ${instance.id} (${instance.role})`);
1060
1150
  // Determine token source: --token-from wins if both specified
1061
1151
  if (opts.tokenFrom && opts.token) {
@@ -1105,6 +1195,11 @@ export function register(program) {
1105
1195
  });
1106
1196
  if (!res.ok) {
1107
1197
  const text = await res.text().catch(() => "");
1198
+ const hubDenial = rewriteFederationPairHubAccessError(res.status, hubUrl, text);
1199
+ if (hubDenial) {
1200
+ console.error(`Error: ${hubDenial.message}`);
1201
+ process.exit(1);
1202
+ }
1108
1203
  console.error(`Pairing failed: ${res.status} ${text}`);
1109
1204
  process.exit(1);
1110
1205
  }
@@ -1,8 +1,8 @@
1
1
  import { homedir } from "node:os";
2
2
  import * as render from "../render.js";
3
3
  import { unpinnedSpecWarning } from "../lib/mcp-spec.js";
4
- import { readClientMcpBlock } from "../doctor-client.js";
5
- import { installHook, uninstallHook, hookStatus, hookStatusIdentityLines, HOOK_STATUS_UNPARSED, installContinuityHooks, uninstallContinuityHooks, continuityHookStatus, isSupportedHarness, SUPPORTED_HARNESSES, hookInstallHint, harnessSupportsContinuity, resolveHookAgentId, } from "../hook-install.js";
4
+ import { probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
5
+ import { installHook, uninstallHook, hookStatus, hookStatusHeadline, hookStatusFailureLine, hookStatusIdentityLines, HOOK_STATUS_UNPARSED, installContinuityHooks, uninstallContinuityHooks, continuityHookStatus, isSupportedHarness, SUPPORTED_HARNESSES, hookInstallHint, harnessSupportsContinuity, resolveHookAgentId, } from "../hook-install.js";
6
6
  let cli;
7
7
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
8
8
  export function bindCli(fns) {
@@ -133,7 +133,9 @@ export function register(program) {
133
133
  .action((opts) => {
134
134
  const harness = requireSupportedHarness(opts.harness);
135
135
  const home = homedir();
136
- const status = hookStatus(home, harness);
136
+ const status = hookStatus(home, harness, {
137
+ deliveryProbe: (command) => probeSessionStartHookDelivery(command),
138
+ });
137
139
  // Continuity pair (flair#1257) — reported alongside the SessionStart
138
140
  // status in every branch below. "absent" is NOT a failure: installing the
139
141
  // pair is the opt-in, so absence renders as "not enabled".
@@ -163,13 +165,18 @@ export function register(program) {
163
165
  process.exit(1);
164
166
  }
165
167
  if (!status.wired) {
166
- console.log(` ${render.icons.error} not wired`);
168
+ console.log(` ${render.icons.error} ${hookStatusHeadline(status)}`);
167
169
  console.log(` ${render.wrap(render.c.dim, "Fix:")} ${hookInstallHint(status.harness)}`);
168
170
  renderContinuity();
169
171
  console.log("");
170
172
  process.exit(1);
171
173
  }
172
- console.log(` ${status.correctShape ? render.icons.ok : render.icons.warn} wired${status.correctShape ? "" : " (unexpected shape — was it hand-edited?)"}`);
174
+ const headline = hookStatusHeadline(status);
175
+ const verified = status.delivery === "verified" && status.correctShape;
176
+ console.log(` ${verified ? render.icons.ok : render.icons.warn} ${headline}${status.correctShape ? "" : " (unexpected shape — was it hand-edited?)"}`);
177
+ for (const reason of status.deliveryReasons) {
178
+ console.log(` ${render.wrap(render.c.dim, reason)}`);
179
+ }
173
180
  // flair#1325 — skip the URL line only when agentId was recovered
174
181
  // (the installer form that omits FLAIR_URL). A wired correct-shape
175
182
  // command with no env assignments still prints unknown, not a
@@ -179,13 +186,16 @@ export function register(program) {
179
186
  const value = line.value === HOOK_STATUS_UNPARSED ? render.wrap(render.c.dim, line.value) : line.value;
180
187
  console.log(` ${render.wrap(render.c.dim, label)} ${value}`);
181
188
  }
182
- // flair#1007 — whether a command that stopped resolving would fail quietly
183
- // or print an error on every session start.
184
- if (status.silenced) {
185
- console.log(` ${render.wrap(render.c.dim, "On failure:")} silent (exit 0, no output)`);
189
+ // flair#1007 / #1734 — session-continue vs stderr visibility.
190
+ const failure = hookStatusFailureLine(status);
191
+ if (status.stderrDiscarded) {
192
+ console.log(` ${render.wrap(render.c.dim, "On failure:")} ${failure}`);
193
+ }
194
+ else if (status.silenced) {
195
+ console.log(` ${render.wrap(render.c.dim, "On failure:")} ${failure}`);
186
196
  }
187
197
  else {
188
- console.log(` ${render.icons.warn} ${render.wrap(render.c.dim, "On failure:")} prints an error on every session — run \`${hookInstallHint(status.harness)}\` to adopt the silent form`);
198
+ console.log(` ${render.icons.warn} ${render.wrap(render.c.dim, "On failure:")} ${failure} — run \`${hookInstallHint(status.harness)}\` to adopt the silent form`);
189
199
  }
190
200
  renderContinuity();
191
201
  console.log("");