@tpsdev-ai/flair 0.54.2 → 0.55.1

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 (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  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 +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
@@ -4,10 +4,13 @@ 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";
@@ -99,6 +102,33 @@ export function summarizeDoctorRun(found, fixed, autoFix) {
99
102
  exitCode: 1,
100
103
  };
101
104
  }
105
+ /**
106
+ * flair#1761 — the single place a Health-derived Metal finding becomes doctor
107
+ * output and exit-code weight. Extracted from the action callback so the
108
+ * detected-vs-env-vs-unrecognized severity is exercised on the real
109
+ * rendering/counting path (the action's Harper probe, console side effects
110
+ * and process.exit cannot be driven directly — see doctor-summary.test.ts for
111
+ * the same extraction convention).
112
+ *
113
+ * The finding carries its own icon and issue weight: a derived ("detected")
114
+ * Metal default is rendered as a persistent warning and does NOT increment
115
+ * the issue count, while an explicit request or an unrecognized source is a
116
+ * blocking `✗` that does. `lines` is returned for tests; production passes a
117
+ * writer (default: console.log).
118
+ */
119
+ export function renderEmbedGpuDoctorFinding(embedding, write = (line) => console.log(line)) {
120
+ const finding = describeEmbedGpuDoctorFinding(embedding);
121
+ if (!finding)
122
+ return { lines: [], issueDelta: 0 };
123
+ const icon = finding.icon === "warn" ? render.icons.warn : render.icons.error;
124
+ const lines = [
125
+ ` ${icon} ${finding.message}`,
126
+ ` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`,
127
+ ];
128
+ for (const line of lines)
129
+ write(line);
130
+ return { lines, issueDelta: finding.isIssue ? 1 : 0 };
131
+ }
102
132
  // ─── flair doctor ─────────────────────────────────────────────────────────────
103
133
  export function register(program) {
104
134
  const __pkgVersion = cli.__pkgVersion;
@@ -379,12 +409,14 @@ export function register(program) {
379
409
  // every other command) nudges about on stderr; doctor prints the full
380
410
  // picture here instead of a one-liner and `--fix` offers the restart.
381
411
  let runningVersion = null;
412
+ let embedGpuFromHealth;
382
413
  if (harperResponding) {
383
414
  try {
384
415
  const healthRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(3000) });
385
416
  if (healthRes.ok) {
386
417
  const body = (await healthRes.json());
387
418
  runningVersion = typeof body?.version === "string" ? body.version : null;
419
+ embedGpuFromHealth = body.embedding;
388
420
  }
389
421
  }
390
422
  catch { /* leave runningVersion null — reported below as "unknown" */ }
@@ -417,6 +449,12 @@ export function register(program) {
417
449
  else {
418
450
  console.log(` ${render.icons.warn} Could not determine the running server's version`);
419
451
  }
452
+ // flair#1437 (severity split flair#1761): Health states an unconfirmed
453
+ // Metal offload; operators read doctor. The finding carries its own
454
+ // severity — a derived ("detected") default is an advisory warning that
455
+ // does NOT fail the run, while an explicit request or an unrecognized
456
+ // source still fails closed. A stated CPU default is silent here.
457
+ issues += renderEmbedGpuDoctorFinding(embedGpuFromHealth).issueDelta;
420
458
  }
421
459
  // 2. Keys directory
422
460
  const keysDir = defaultKeysDir();
@@ -496,6 +534,25 @@ export function register(program) {
496
534
  }
497
535
  }
498
536
  catch { /* best-effort — don't fail doctor over a malformed harper-config.yaml */ }
537
+ // 3b2. Admin-pass vs persisted Harper user (flair#837) — report-only,
538
+ // never `--fix`. File missing + hdb_user still in the data dir is the
539
+ // state bare `init` used to "fix" by writing a fresh file that 401s.
540
+ // The remedy names the two exits: `--admin-pass-file` / `--reset-admin-pass`.
541
+ try {
542
+ const dataDir = defaultDataDir();
543
+ const finding = adminPassDesyncFinding({
544
+ adminPassFileExists: existsSync(defaultAdminPassPath()),
545
+ persistedAdminUser: detectPersistedAdminUser(dataDir),
546
+ dataDir,
547
+ adminPassPath: defaultAdminPassPath(),
548
+ });
549
+ if (finding?.flagged) {
550
+ console.log(` ${render.icons.error} ${finding.message}`);
551
+ console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
552
+ issues++;
553
+ }
554
+ }
555
+ catch { /* best-effort — a missing data dir is not a doctor crash */ }
499
556
  // 3c. Ops-socket permission posture (flair#763) — report-only, never
500
557
  // auto-fixed. Re-tightening a live socket needs a restart, so the remedy is
501
558
  // `flair init`/restart (which re-applies the posture), not a `doctor --fix`.
@@ -1242,6 +1299,13 @@ export function register(program) {
1242
1299
  // verify) is repairLaunchdManagement, which is the only place that
1243
1300
  // touches the real filesystem and launchctl.
1244
1301
  console.log(`\n ${render.wrap(render.c.bold, "Launchd management")}`);
1302
+ // #1693: an adopted/registered plist that embeds the admin password inline
1303
+ // is a FAIL even when launchd still reports the job managed — launchd keeps
1304
+ // the loaded definition, so the on-disk downgrade hides behind a healthy
1305
+ // job. The path is resolved BEFORE the repair for the no-fix arm and AFTER
1306
+ // it for the --fix arm, so a --fix that regenerated in pass-file mode (or
1307
+ // migrated the label) clears the finding.
1308
+ let launchdPlistForCheck;
1245
1309
  if (autoFix && !dryRun) {
1246
1310
  // Execute the repair directly; it re-derives the plan internally and
1247
1311
  // verifies via assessLaunchdManagement (fail-loud, never a silent pass).
@@ -1270,6 +1334,7 @@ export function register(program) {
1270
1334
  // Report only (no --fix, or --fix --dry-run): compute the plan, touch
1271
1335
  // nothing. A regenerate plan is drift; a refuse plan is a named refusal.
1272
1336
  const repairPlan = planLaunchdRepairFor(defaultDataDir(), effectivePort);
1337
+ launchdPlistForCheck = repairPlan.plistPath;
1273
1338
  switch (repairPlan.plan.kind) {
1274
1339
  case "no-op":
1275
1340
  console.log(` ${render.icons.ok} ${repairPlan.plan.detail}`);
@@ -1300,6 +1365,26 @@ export function register(program) {
1300
1365
  break;
1301
1366
  }
1302
1367
  }
1368
+ // flair#1693: the check itself (the shared plist writer that stops
1369
+ // init/doctor/upgrade producing this shape is #1693's own change). In the
1370
+ // --fix arm the plan was executed above, so resolve the (possibly
1371
+ // label-migrated) plist path now and read post-repair bytes.
1372
+ if (launchdPlistForCheck === undefined) {
1373
+ launchdPlistForCheck = planLaunchdRepairFor(defaultDataDir(), effectivePort).plistPath;
1374
+ }
1375
+ if (typeof launchdPlistForCheck === "string" && existsSync(launchdPlistForCheck)) {
1376
+ try {
1377
+ const raw = readFileSync(launchdPlistForCheck, "utf-8");
1378
+ if (plistCarriesInlineAdminPassword(raw)) {
1379
+ issues++;
1380
+ console.log(` ${render.icons.error} the launchd plist at ${launchdPlistForCheck} embeds HDB_ADMIN_PASSWORD inline instead of using the pass-file launcher`);
1381
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(regenerate in pass-file mode; #1693)")}`);
1382
+ }
1383
+ }
1384
+ catch {
1385
+ // Plist unreadable — the launchd plan above already reports presence.
1386
+ }
1387
+ }
1303
1388
  // 7a. Resolve which agent identities the two verified-read sections below
1304
1389
  // (Fleet presence, Migrations) iterate (flair#722). Previously both
1305
1390
  // 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("");