@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
@@ -1,5 +1,5 @@
1
1
  import { COMPONENT_ENV_FILENAME, PUBLIC_URL_KEY, describePublicUrlFinding, readEnvValue } from "../component-env.js";
2
- import { checkClaudeMdBootstrap, checkContinuityCaptureHooks, describeAgentGateFinding, effectiveFlairUrl, embeddingsSkipRemedy, fixClaudeMdBootstrap, fixCommandAgentHint, fixContinuityCaptureHooks, fixSessionStartHook, inspectSessionStartHook, partitionKeyIds, planAgentIterations, readClientMcpBlock, resolveFixAgentId, resolveWireFlairUrl, upgradeSessionStartHookCommand } from "../doctor-client.js";
2
+ import { checkClaudeMdBootstrap, checkContinuityCaptureHooks, continuityWriteBlockers, describeAgentGateFinding, effectiveFlairUrl, embeddingsSkipRemedy, fixClaudeMdBootstrap, fixCommandAgentHint, fixContinuityCaptureHooks, fixSessionStartHook, inspectSessionStartHook, partitionKeyIds, planAgentIterations, readClientMcpBlock, resolveFixAgentId, resolveWireFlairUrl, upgradeSessionStartHookCommand } from "../doctor-client.js";
3
3
  import { markStale, sortOldestVersionFirst } from "../fleet-presence.js";
4
4
  import { hookSettingsPath, resolveHookAgentId } from "../hook-install.js";
5
5
  import { ALL_CLIENTS, decideCodexPinOnly, decideJsonPinOnly, detectClients, wireAntigravity, wireClaudeCode, wireCodex, wireCursor, wireGemini } from "../install/clients.js";
@@ -18,6 +18,8 @@ import { mcpClientPinFindings, refreshOwnedPins, repinSessionStartHookGuarded, s
18
18
  import * as render from "../render.js";
19
19
  import { checkVersion, formatVersionNudge, probeInstanceVersion, FLAIR_PKG_NAME } from "../version-check.js";
20
20
  import { resolveRegistryNotice } from "../lib/npm-registry.js";
21
+ import { formatServingTreeLine, formatTreeAssessmentLines } from "../lib/tree-divergence.js";
22
+ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
21
23
  import { existsSync, readFileSync, statSync } from "node:fs";
22
24
  import { dirname, join } from "node:path";
23
25
  import { resolveHome } from "../lib/home.js";
@@ -130,6 +132,133 @@ export function renderEmbedGpuDoctorFinding(embedding, write = (line) => console
130
132
  write(line);
131
133
  return { lines, issueDelta: finding.isIssue ? 1 : 0 };
132
134
  }
135
+ /**
136
+ * flair#2034 §2 — the "Install tree" doctor section: is the instance served
137
+ * from this CLI's install tree, and does the federation-sync shim run it?
138
+ *
139
+ * Runs in every `flair doctor` (it is not a catalog member, so it cannot be
140
+ * filtered out the way the catalog's launchd check is). Counting rules:
141
+ *
142
+ * - a PROVEN divergence is one issue; a deliberate runtime pin (a different
143
+ * node serving this CLI's own tree), a separately managed tree (a plain
144
+ * tree or checkout) and an unknown serving tree are reported, never counted;
145
+ * - `--fix` counts the divergence FIXED only after the unit was re-pointed,
146
+ * the instance restarted, and the serving tree re-proven to be this CLI's —
147
+ * "nothing to rewrite" or a failed restart is never a fix;
148
+ * - a federation-sync shim running another npm-global tree is one issue,
149
+ * fixed only when re-pointed AND re-read as current.
150
+ *
151
+ * Extracted from the action (like renderEmbedGpuDoctorFinding) so the counting
152
+ * is exercised directly; the action passes the real adapters.
153
+ */
154
+ export async function runInstallTreeDoctorSection(mode, deps, write = (line) => console.log(line)) {
155
+ let issues = 0;
156
+ let fixed = 0;
157
+ const ok = render.icons.ok;
158
+ const bad = render.icons.error;
159
+ const info = render.icons.info;
160
+ const warn = render.icons.warn;
161
+ let a = null;
162
+ try {
163
+ a = deps.assess();
164
+ }
165
+ catch (err) {
166
+ write(` ${warn} install tree: could not check ${render.wrap(render.c.dim, `(${err?.message ?? err})`)}`);
167
+ }
168
+ if (a?.state === "same") {
169
+ write(` ${ok} ${formatServingTreeLine(a)}`);
170
+ if (a.nodePin?.kind === "pinned")
171
+ write(` ${info} ${a.nodePin.message}`);
172
+ }
173
+ else if (a?.state === "unknown") {
174
+ write(` ${info} ${render.wrap(render.c.dim, formatServingTreeLine(a))}`);
175
+ }
176
+ else if (a?.state === "separate") {
177
+ for (const line of formatTreeAssessmentLines(a, { context: "doctor" }))
178
+ write(` ${line}`);
179
+ }
180
+ else if (a?.state === "diverged") {
181
+ issues++;
182
+ write(` ${bad} ${render.wrap(render.c.red, "the instance is served from a different install tree than this CLI")}`);
183
+ for (const line of formatTreeAssessmentLines(a, { context: "doctor" }))
184
+ write(` ${render.wrap(render.c.yellow, line)}`);
185
+ if (mode.autoFix && a.cliOlder) {
186
+ write(` ${bad} not re-pointed: this CLI's tree is older than what the instance runs — update it first (npm i -g @tpsdev-ai/flair), then re-run.`);
187
+ }
188
+ else if (mode.autoFix && mode.dryRun) {
189
+ const r = deps.repoint(true);
190
+ write(` ${info} ${render.wrap(render.c.dim, `[dry-run] ${r.detail}; then restart the instance and re-prove which tree serves it`)}`);
191
+ }
192
+ else if (mode.autoFix) {
193
+ const r = deps.repoint(false);
194
+ if (r.kind === "repointed" || r.kind === "current") {
195
+ if (r.kind === "repointed")
196
+ write(` ${ok} ${r.detail}`);
197
+ try {
198
+ await deps.restart();
199
+ const after = deps.assess();
200
+ if (after.state === "same") {
201
+ fixed++;
202
+ write(` ${ok} ${render.wrap(render.c.green, "restarted; verified")} — ${formatServingTreeLine(after)}`);
203
+ }
204
+ else {
205
+ write(` ${bad} restarted, but NOT fixed — ${formatServingTreeLine(after)}`);
206
+ }
207
+ }
208
+ catch (err) {
209
+ write(` ${bad} the restart failed (${err?.message ?? err}); the unit is re-pointed — run: flair restart`);
210
+ }
211
+ }
212
+ else {
213
+ write(` ${bad} not re-pointed — ${r.detail}`);
214
+ }
215
+ }
216
+ }
217
+ let f = null;
218
+ try {
219
+ f = deps.rewriteFederation(true);
220
+ }
221
+ catch (err) {
222
+ write(` ${warn} federation-sync shim: could not check ${render.wrap(render.c.dim, `(${err?.message ?? err})`)}`);
223
+ }
224
+ switch (f?.status) {
225
+ case "current":
226
+ write(` ${ok} federation-sync shim runs this CLI's tree`);
227
+ break;
228
+ case "pinned-node":
229
+ case "separate":
230
+ write(` ${info} federation-sync shim: ${f.detail}`);
231
+ break;
232
+ case "refused":
233
+ write(` ${warn} federation-sync shim: ${f.detail}`);
234
+ break;
235
+ case "would-rewrite": {
236
+ issues++;
237
+ write(` ${bad} the federation-sync shim runs another install tree — ${f.detail}`);
238
+ if (mode.autoFix && mode.dryRun) {
239
+ write(` ${info} ${render.wrap(render.c.dim, "[dry-run] would re-point the shim's exec line (the scheduler unit is not rewritten)")}`);
240
+ }
241
+ else if (mode.autoFix) {
242
+ const r = deps.rewriteFederation(false);
243
+ const verify = r.status === "rewritten" ? deps.rewriteFederation(true) : null;
244
+ if (verify?.status === "current") {
245
+ fixed++;
246
+ write(` ${ok} ${r.detail}`);
247
+ }
248
+ else {
249
+ write(` ${bad} federation-sync shim not re-pointed — ${verify ? verify.detail : r.detail}`);
250
+ }
251
+ }
252
+ else {
253
+ write(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(or flair init)")}`);
254
+ }
255
+ break;
256
+ }
257
+ default:
258
+ break; // not enabled: nothing to say
259
+ }
260
+ return { issues, fixed };
261
+ }
133
262
  // ─── flair doctor ─────────────────────────────────────────────────────────────
134
263
  export function register(program) {
135
264
  const __pkgVersion = cli.__pkgVersion;
@@ -1302,8 +1431,13 @@ export function register(program) {
1302
1431
  const continuityDetail = continuity.state === "partial"
1303
1432
  ? (!continuity.postToolUse.present ? "the PostToolUse entry is missing" : "the Stop entry is missing")
1304
1433
  : "an entry is not the current form (unsilenced, hand-altered, or a drifted PostToolUse matcher)";
1305
- console.log(` ${render.icons.warn} Continuity capture hooks: ${continuity.state} — ${continuityDetail}`);
1306
- if (autoFix) {
1434
+ const pinDetail = [
1435
+ continuity.postToolUse.reason && "PostToolUse " + continuity.postToolUse.reason,
1436
+ continuity.stop.reason && "Stop " + continuity.stop.reason,
1437
+ ].filter(Boolean).join("; ");
1438
+ const blockers = continuityWriteBlockers(continuity);
1439
+ console.log(` ${render.icons.warn} Continuity capture hooks: ${continuity.state} — ${continuityDetail}${pinDetail ? "; " + pinDetail : ""}`);
1440
+ if (autoFix && blockers.length === 0) {
1307
1441
  if (dryRun) {
1308
1442
  console.log(` ${render.wrap(render.c.dim, "Would rewrite the continuity capture hooks in")} ${continuity.path}`);
1309
1443
  }
@@ -1327,7 +1461,15 @@ export function register(program) {
1327
1461
  }
1328
1462
  }
1329
1463
  else {
1330
- console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(rewrites both entries to the current form — same agent, same instance)")}`);
1464
+ if (blockers.length > 0) {
1465
+ const advice = pinDetail
1466
+ ? "Resolve the listed non-version pin(s) manually; doctor cannot rewrite them."
1467
+ : "Continuity hook rewrite held or refused; resolve the listed reason(s) manually.";
1468
+ console.log(` ${advice} ${blockers.join(" ")}`);
1469
+ }
1470
+ else {
1471
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(rewrites both entries to the current form — same agent, same instance)")}`);
1472
+ }
1331
1473
  }
1332
1474
  issues++;
1333
1475
  }
@@ -1557,6 +1699,22 @@ export function register(program) {
1557
1699
  // Plist unreadable — the launchd plan above already reports presence.
1558
1700
  }
1559
1701
  }
1702
+ // 7c. Install tree (flair#2034 §2) — after launchd management, so a repair
1703
+ // above has settled which service owns the instance before this asks.
1704
+ console.log(`\n ${render.wrap(render.c.bold, "Install tree")}`);
1705
+ {
1706
+ const treeSection = await runInstallTreeDoctorSection({ autoFix, dryRun }, {
1707
+ assess: () => cli.assessInstallTree(defaultDataDir(), effectivePort, {
1708
+ local: true,
1709
+ runningVersion: effectivePort === port ? instanceVersion : null,
1710
+ }),
1711
+ repoint: (dry) => cli.repointMainServiceUnit(defaultDataDir(), effectivePort, { dryRun: dry }),
1712
+ restart: () => cli.restartFlair(effectivePort, defaultDataDir()),
1713
+ rewriteFederation: (dry) => rewriteFederationSchedulerRuntime({ dryRun: dry }),
1714
+ });
1715
+ issues += treeSection.issues;
1716
+ fixed += treeSection.fixed;
1717
+ }
1560
1718
  // 7a. Resolve which agent identities the two verified-read sections below
1561
1719
  // (Fleet presence, Migrations) iterate (flair#722). Previously both
1562
1720
  // sections required --agent explicitly; doctor already enumerates every
@@ -9,6 +9,7 @@ import { redactTokenMessage } from "../lib/redact-token-id.js";
9
9
  import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
10
10
  import { defaultAdminPassPath, isLocalBase, resolveAdminPassFromSources, resolveAdminUser, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, ADMIN_PASS_HELP, } from "../lib/auth-resolve.js";
11
11
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
12
+ import { FEDERATION_MEMORY_SELECT } from "../lib/federation-memory-attributes.js";
12
13
  import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
13
14
  let cli;
14
15
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -677,7 +678,7 @@ export async function runFederationSyncOnce(opts) {
677
678
  res = await fetch(`${opsEndpoint}/`, {
678
679
  method: "POST",
679
680
  headers: { "Content-Type": "application/json", Authorization: auth },
680
- body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: ["*"] }),
681
+ body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? [...FEDERATION_MEMORY_SELECT] : ["*"] }),
681
682
  signal: AbortSignal.timeout(15_000),
682
683
  });
683
684
  }
@@ -1,6 +1,6 @@
1
1
  import * as render from "../render.js";
2
2
  import { unpinnedSpecWarning } from "../lib/mcp-spec.js";
3
- import { probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
3
+ import { continuityWriteBlockers, probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
4
4
  import { installHook, uninstallHook, hookStatus, hookStatusHeadline, hookStatusFailureLine, hookStatusIdentityLines, HOOK_STATUS_UNPARSED, installContinuityHooks, uninstallContinuityHooks, continuityHookStatus, isSupportedHarness, SUPPORTED_HARNESSES, hookInstallHint, harnessSupportsContinuity, resolveHookAgentId, } from "../hook-install.js";
5
5
  import { resolveHome } from "../lib/home.js";
6
6
  let cli;
@@ -153,7 +153,15 @@ export function register(program) {
153
153
  }
154
154
  else {
155
155
  const missing = !cont.postToolUse.present ? "PostToolUse missing" : !cont.stop.present ? "Stop missing" : "stale form";
156
- console.log(` ${render.icons.warn} continuity capture: ${cont.state} (${missing}) ${render.wrap(render.c.dim, `— re-run: ${hookInstallHint(harness, "--continuity")}`)}`);
156
+ const blockers = continuityWriteBlockers(cont);
157
+ let advice = `— re-run: ${hookInstallHint(harness, "--continuity")}`;
158
+ if (blockers.length > 0) {
159
+ const resolution = cont.postToolUse.reason || cont.stop.reason
160
+ ? "resolve the non-version pin manually"
161
+ : "rewrite held or refused; resolve the listed reason(s) manually";
162
+ advice = `— ${resolution}; ${blockers.join(" ")}`;
163
+ }
164
+ console.log(` ${render.icons.warn} continuity capture: ${cont.state} (${missing}) ${render.wrap(render.c.dim, advice)}`);
157
165
  }
158
166
  };
159
167
  console.log(`\n${render.wrap(render.c.bold, "🪝 flair hook status")}\n`);
@@ -6,13 +6,16 @@ import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefu
6
6
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
7
7
  import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
8
8
  import * as render from "../render.js";
9
- import { execSync, spawn } from "node:child_process";
9
+ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
10
+ import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
11
+ import { spawn } from "node:child_process";
10
12
  import { randomBytes, randomUUID } from "node:crypto";
11
13
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
14
  import { join, resolve } from "node:path";
13
15
  import nacl from "tweetnacl";
14
16
  import { httpCorsAccessList } from "../lib/http-bind.js";
15
17
  import { resolveHome } from "../lib/home.js";
18
+ import { foreignOccupiedListenerDetail, staleHarperBeforeAuthNotice, } from "../lib/init-occupied-listener.js";
16
19
  let cli;
17
20
  /** Bind the cli-locals this module depends on. */
18
21
  export function bindCli(fns) {
@@ -27,9 +30,6 @@ function b64url(...args) {
27
30
  function buildOperationsApiConfig(...args) {
28
31
  return cli.buildOperationsApiConfig(...args);
29
32
  }
30
- function cleanupLegacyLaunchdPlist(...args) {
31
- return cli.cleanupLegacyLaunchdPlist(...args);
32
- }
33
33
  function defaultDataDir(...args) {
34
34
  return cli.defaultDataDir(...args);
35
35
  }
@@ -114,6 +114,20 @@ function seedAgentViaOpsApi(...args) {
114
114
  function seedFederationInstanceViaOpsApi(...args) {
115
115
  return cli.seedFederationInstanceViaOpsApi(...args);
116
116
  }
117
+ function readOccupiedListener(port) {
118
+ return cli.readOccupiedListener(port);
119
+ }
120
+ /**
121
+ * Operations-port attribution for a later 401. `before` is taken now;
122
+ * `reread` runs only if the insert is rejected, so a holder that changed
123
+ * during the request is not named. The HTTP port's pids are not an input.
124
+ */
125
+ function operationsPortAttribution(port) {
126
+ return {
127
+ before: readOccupiedListener(port),
128
+ reread: () => readOccupiedListener(port),
129
+ };
130
+ }
117
131
  function shouldShowInlineSecretWarning(...args) {
118
132
  return cli.shouldShowInlineSecretWarning(...args);
119
133
  }
@@ -129,8 +143,11 @@ function waitForHealth(...args) {
129
143
  function writeDaemonSidecar(...args) {
130
144
  return cli.writeDaemonSidecar(...args);
131
145
  }
132
- function writeInitLaunchdPlist(...args) {
133
- return cli.writeInitLaunchdPlist(...args);
146
+ function registerInitLaunchdService(...args) {
147
+ return cli.registerInitLaunchdService(...args);
148
+ }
149
+ function repointMainServiceUnit(...args) {
150
+ return cli.repointMainServiceUnit(...args);
134
151
  }
135
152
  export function register(program) {
136
153
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
@@ -477,11 +494,30 @@ export function register(program) {
477
494
  const reason = resolveInitAdminPasswordRefuseReason(fileExists, passwordCtx);
478
495
  if (!reason)
479
496
  return;
480
- console.error(initAdminPassRefusalMessage(reason, {
497
+ const message = initAdminPassRefusalMessage(reason, {
481
498
  dataDir,
482
499
  httpPort,
483
500
  adminPassPath,
484
- }));
501
+ });
502
+ // The port is already taken and this data dir has no admin user.
503
+ // The unauthenticated /health probe already ran. This is one read of
504
+ // that port's listener — not the before-and-after 401 attribution.
505
+ // Name it and exit before any Authorization header is sent. Do not
506
+ // signal it. `flair stop` cannot be promised to act on this listener
507
+ // (flair#1749).
508
+ if (reason === "foreign-instance") {
509
+ const listener = readOccupiedListener(httpPort);
510
+ const head = initAdminPassRefusalMessage(reason, {
511
+ dataDir,
512
+ httpPort,
513
+ adminPassPath,
514
+ offerFlairStop: false,
515
+ });
516
+ console.error(`${head}\n${foreignOccupiedListenerDetail(listener, dataDir)}`);
517
+ }
518
+ else {
519
+ console.error(message);
520
+ }
485
521
  process.exit(1);
486
522
  };
487
523
  // Read from file if provided
@@ -601,9 +637,30 @@ export function register(program) {
601
637
  // The socket doesn't exist yet, so only the parent-dir mode is applied here.
602
638
  mkdirSync(dataDir, { recursive: true });
603
639
  readyOpsSocketPosture(dataDir);
640
+ // True only when the port was already answering and the single pre-auth
641
+ // read did not include a different data directory (that case exits
642
+ // below, before any authenticated request). An unreadable directory,
643
+ // including every macOS lookup, does not count as different. A later
644
+ // ops 401 is a separate before-and-after read of the operations port,
645
+ // not this HTTP observation (flair#1749).
646
+ let skippedOwnStart = false;
604
647
  if (!opts.skipStart) {
605
648
  if (alreadyRunning) {
606
649
  console.log(`Harper already running on port ${httpPort} — skipping start`);
650
+ // One read of the HTTP port that answered /health. When that read
651
+ // includes a ROOTPATH other than this init's, stop before
652
+ // waitForHealth, which would send Authorization. An unreadable
653
+ // directory is not treated as foreign. This is not the
654
+ // before-and-after check used for an operations-port 401. A
655
+ // different directory does not prove the passwords differ, and
656
+ // this init does not signal the process.
657
+ const httpListener = readOccupiedListener(httpPort);
658
+ const notice = staleHarperBeforeAuthNotice(dataDir, httpListener);
659
+ if (notice) {
660
+ console.error(notice);
661
+ process.exit(1);
662
+ }
663
+ skippedOwnStart = true;
607
664
  }
608
665
  if (!alreadyRunning) {
609
666
  const bin = harperBin();
@@ -758,8 +815,9 @@ export function register(program) {
758
815
  pendingAdminPassRotate = false;
759
816
  console.log(`Admin password saved to: ${adminPassPath}`);
760
817
  }
761
- // Register launchd service on macOS so Harper survives reboots
762
- // and `flair restart` / `flair stop` work via launchctl.
818
+ // Write this instance's launchd plist on macOS so launchd can own it
819
+ // (survive reboots; `flair restart` / `flair stop` via launchctl) — and
820
+ // report whether launchd ACTUALLY manages it (flair#2040).
763
821
  if (process.platform === "darwin") {
764
822
  const harperBinPath = harperBin();
765
823
  if (harperBinPath) {
@@ -767,19 +825,6 @@ export function register(program) {
767
825
  const plistDir = defaultLaunchAgentsDir();
768
826
  mkdirSync(plistDir, { recursive: true });
769
827
  const plistPath = launchdPlistPath(label, plistDir);
770
- // flair#693 + flair#966: a pre-flair#693 install registered under
771
- // the bare LEGACY_LAUNCHD_LABEL. init always writes fresh plist
772
- // content below (it has the current ports/creds in hand), so
773
- // migration here is just "clean up the old registration" —
774
- // unload + remove it BEFORE writing the new one, so re-running
775
- // init never leaves two services behind for this data dir.
776
- //
777
- // flair#966: the legacy plist is NOT scoped to this data dir —
778
- // it is a single global label. cleanupLegacyLaunchdPlist reads
779
- // ROOTPATH to establish ownership before touching it.
780
- cleanupLegacyLaunchdPlist(dataDir, plistDir, (cmd) => {
781
- execSync(cmd, { stdio: "pipe" });
782
- });
783
828
  const opsSocket = join(dataDir, "operations-server");
784
829
  // authorizeLocal: false (flair#654) — same posture as the initial spawn
785
830
  // above; the launchd-managed process must not diverge from it.
@@ -804,32 +849,86 @@ export function register(program) {
804
849
  // emits the pass-file launcher and never HDB_ADMIN_PASSWORD. It reuses
805
850
  // an existing valid ~/.flair/admin-pass, or proves the credential in
806
851
  // hand against this (now-healthy) instance and writes it 0600, or
807
- // refuses without writing a plist. An already-adopted instance is left
808
- // byte-for-byte unchanged rather than downgraded to the inline shape.
809
- const outcome = await writeInitLaunchdPlist({
852
+ // refuses without writing a plist. An already-adopted instance is never
853
+ // regenerated or downgraded to the inline shape; only its runtime paths
854
+ // are re-pointed, when it is provably this instance's plist serving
855
+ // another npm-global tree (flair#2034 — see src/lib/service-repoint.ts).
856
+ //
857
+ // flair#693 + flair#966 + flair#2040: a pre-flair#693 install
858
+ // registered under the bare LEGACY_LAUNCHD_LABEL is retired here, but
859
+ // only when ROOTPATH proves it is this data dir's — and when its job
860
+ // is the process SERVING this instance, retiring it stops Flair, so
861
+ // registerInitLaunchdService preflights the launchd domain and
862
+ // validates the replacement BEFORE unloading anything, loads and
863
+ // verifies the replacement, and restores the legacy job on failure.
864
+ //
865
+ // flair#2040: NEVER a check mark for a load that did not happen. The
866
+ // step reports "launchd-managed ✓" only when launchd is verified to
867
+ // run the process serving this instance; otherwise it says the plist
868
+ // is on disk and Flair runs directly, with the reason. The plist
869
+ // writer's own outcome (written / unchanged / re-pointed / not
870
+ // re-pointed, flair#2034) is reported in the same lines.
871
+ const launchdStep = await registerInitLaunchdService({
810
872
  dataDir,
811
- plistPath,
812
- label,
813
- adminPass,
814
- adminUser,
815
- modelsDir,
816
- execPath: process.execPath,
817
- harperBinPath,
818
- workingDirectory: flairPackageDir(),
819
- httpPort: httpBind.bindValue,
820
- opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
821
- setConfig,
822
873
  port: httpPort,
874
+ plistDir,
875
+ write: {
876
+ dataDir,
877
+ plistPath,
878
+ label,
879
+ adminPass,
880
+ adminUser,
881
+ modelsDir,
882
+ execPath: preferVersionManagerAlias(process.execPath),
883
+ harperBinPath,
884
+ workingDirectory: flairPackageDir(),
885
+ httpPort: httpBind.bindValue,
886
+ opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
887
+ setConfig,
888
+ port: httpPort,
889
+ },
823
890
  });
824
- if (outcome.kind === "refused") {
825
- console.error(`Error: ${outcome.detail}`);
891
+ for (const line of launchdStep.lines) {
892
+ (line.stream === "err" ? console.error : console.log)(line.text);
893
+ }
894
+ if (launchdStep.kind === "refused" || launchdStep.kind === "down" || launchdStep.kind === "uncertain") {
826
895
  process.exit(1);
827
896
  }
828
- console.log(outcome.kind === "unchanged"
829
- ? "Launchd service already managed — plist unchanged ✓"
830
- : "Launchd service registered ✓");
831
897
  }
832
898
  }
899
+ // flair#2034 §2: on Linux the instance's own service is the systemd
900
+ // USER unit proven to own the serving process (flair writes none). A
901
+ // unit that serves another npm-global tree is re-pointed — runtime paths
902
+ // only — and systemd is reloaded; anything else is left alone.
903
+ if (process.platform === "linux") {
904
+ const r = repointMainServiceUnit(dataDir, httpPort);
905
+ if (r.kind === "repointed") {
906
+ console.log(`Systemd user unit re-pointed at this CLI's install tree ✓ — ${r.detail}`);
907
+ console.log(" It takes effect when systemd next starts the unit: flair restart");
908
+ }
909
+ else if (r.kind === "refused") {
910
+ console.warn(`Systemd user unit left unchanged — ${r.detail}`);
911
+ }
912
+ else if (r.kind === "pinned-node") {
913
+ console.log(`Systemd user unit left as it is — ${r.detail}`);
914
+ }
915
+ }
916
+ // flair#2034 §2: the federation-sync shim bakes the node + flair paths
917
+ // of the runtime that enabled it. When it runs another npm-global tree,
918
+ // re-point its exec line (only that line; the scheduler unit is never
919
+ // rewritten). A machine that never enabled federation sync is left alone.
920
+ try {
921
+ const fed = rewriteFederationSchedulerRuntime();
922
+ if (fed.status === "rewritten") {
923
+ console.log(`Federation sync shim re-pointed at this CLI's install tree ✓ — ${fed.detail}`);
924
+ }
925
+ else if (fed.status === "refused") {
926
+ console.warn(`Federation sync shim left unchanged — ${fed.detail}`);
927
+ }
928
+ }
929
+ catch (err) {
930
+ console.warn(`Could not check the federation sync shim: ${err?.message ?? err}`);
931
+ }
833
932
  }
834
933
  if (pendingAdminPassRotate) {
835
934
  // Same gate as the post-health path: readiness is the operations
@@ -899,9 +998,16 @@ export function register(program) {
899
998
  pubKeyB64url = b64url(kp.publicKey);
900
999
  console.log(`Keypair written: ${privPath} ✓`);
901
1000
  }
902
- // Seed agent via operations API
1001
+ // Seed agent via operations API. Unlike the pre-auth observation,
1002
+ // which is one read, a 401 names a pid only when the read before the
1003
+ // insert and the read after the rejection are the same sole PID. The
1004
+ // HTTP port's holder is not an input and is not assumed to have caused
1005
+ // the rejection. Several holders, or a holder that changed during the
1006
+ // request, stay unattributed. Init started Harper itself → no listener,
1007
+ // and that 401 keeps the credential hint.
903
1008
  console.log(`Seeding agent '${agentId}' via operations API...`);
904
- await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass);
1009
+ const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1010
+ await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
905
1011
  console.log(`Agent '${agentId}' registered ✓`);
906
1012
  // Verify Ed25519 auth
907
1013
  console.log("Verifying Ed25519 auth...");
@@ -1,3 +1,17 @@
1
+ /**
2
+ * memory.ts — `flair memory` command group (flair#1621 / epic #1618).
3
+ *
4
+ * Extracted from src/cli.ts with ZERO behavior change. This file owns the
5
+ * group's commander registration, action handlers, and group-specific
6
+ * inline helpers (hygiene predicates). Shared CLI helpers (api,
7
+ * resolveSigningAgentId, credential flags, --entities parse, …) stay in
8
+ * cli.ts and are bound before register().
9
+ *
10
+ * Compiled with the rest of src/ under tsconfig.check.src.json (strict).
11
+ * Do not import src/cli.ts from here — that would cycle and pull the
12
+ * non-strict entry into the strict check.
13
+ */
14
+ import { Option } from "commander";
1
15
  import * as render from "../render.js";
2
16
  import { resolveAdminUser } from "../lib/auth-resolve.js";
3
17
  let cli;
@@ -127,7 +141,7 @@ export function register(program) {
127
141
  // before resetting the session.
128
142
  //
129
143
  // The shape of this row matters: tags=['task-summary','auto-on-reset'] +
130
- // subject='task:<beads-id>' + summary populated. Slice 3+4 (harness
144
+ // subject='task:<reference>' + summary when supplied. Slice 3+4 (harness
131
145
  // integrations) will call this as part of the reset pipeline; slice 5+6
132
146
  // (operator surfaces) will surface promote/restore controls. Today, this
133
147
  // command is independently useful — operator can capture a manual summary
@@ -138,13 +152,15 @@ export function register(program) {
138
152
  memory.command("write-task-summary")
139
153
  .description("Capture a structured task summary as a persistent Memory row (used by session-reset harness; standalone-callable by operators)")
140
154
  .requiredOption("--agent <id>", "Agent the summary belongs to")
141
- .requiredOption("--beads <ops-id>", "Bead/PR/task identifier this summary is about")
155
+ .option("--ref <ref>", "Task reference (optional)")
156
+ .addOption(new Option("--beads <ops-id>", "Deprecated alias for --ref").hideHelp())
142
157
  .requiredOption("--outcome <s>", "Outcome of the task: merged | rejected | abandoned")
143
158
  .option("--summary <text>", "Multi-sentence dense compression (populates Memory.summary; will be the agent's read-time view)")
144
159
  .option("--files-touched <csv>", "Comma-separated list of files touched during the task (becomes part of content)")
145
160
  .option("--lessons <text>", "Lessons learned during the task (becomes part of content)")
146
161
  .option("--derived-from <csv>", "Comma-separated list of source Memory IDs this summary was distilled from")
147
162
  .action(async (opts) => {
163
+ opts.beads = opts.ref ?? opts.beads ?? "unreferenced";
148
164
  const validOutcomes = new Set(["merged", "rejected", "abandoned"]);
149
165
  if (!validOutcomes.has(opts.outcome)) {
150
166
  console.error(`Error: --outcome must be one of: merged, rejected, abandoned (got: ${opts.outcome})`);
@@ -203,6 +219,7 @@ export function register(program) {
203
219
  .option("--agent <id>", "Agent ID (or set FLAIR_AGENT_ID env)")
204
220
  .option("--admin-pass <pass>", "Admin password — sign as admin while --agent names whose memories to search (flair#1500: a flag-pinned agent with no key no longer falls back to FLAIR_ADMIN_PASS)")
205
221
  .option("--q <query>", "search query (alias for positional arg)")
222
+ .option("--json", "Output raw JSON array")
206
223
  .option("--limit <n>", "Max results", "5")
207
224
  .option("--tag <tag>")
208
225
  .option("--include-archived", "Include basemented (archived) memories in results (default: excluded)")
@@ -227,6 +244,11 @@ export function register(program) {
227
244
  body.includeArchived = true;
228
245
  const baseUrl = resolveBaseUrl(opts);
229
246
  const res = await api("POST", "/SemanticSearch", body, { baseUrl, agentId, agentIdSource: source, explicitAdminPass: opts.adminPass });
247
+ if (opts.json) {
248
+ const results = res.results || res || [];
249
+ console.log(render.asJSON(Array.isArray(results) ? results : []));
250
+ return;
251
+ }
230
252
  console.log(JSON.stringify(res, null, 2));
231
253
  });
232
254
  // ─── flair memory basement / restore ────────────────────────────────────────