@tpsdev-ai/flair 0.63.0 → 0.63.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 (63) hide show
  1. package/README.md +8 -7
  2. package/SECURITY.md +55 -33
  3. package/dist/bridges/runtime/import-runner.js +4 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +243 -83
  6. package/dist/commands/agent.js +298 -72
  7. package/dist/commands/attention.js +2 -0
  8. package/dist/commands/bootstrap.js +2 -0
  9. package/dist/commands/bridge.js +10 -0
  10. package/dist/commands/doctor.js +87 -42
  11. package/dist/commands/export.js +141 -11
  12. package/dist/commands/import.js +36 -15
  13. package/dist/commands/init.js +373 -157
  14. package/dist/commands/keys.js +12 -8
  15. package/dist/commands/mcp.js +146 -62
  16. package/dist/commands/memory.js +5 -2
  17. package/dist/commands/migrate-harness-memory.js +9 -3
  18. package/dist/commands/principal.js +19 -14
  19. package/dist/commands/quality.js +23 -3
  20. package/dist/commands/reembed.js +468 -111
  21. package/dist/commands/search.js +2 -0
  22. package/dist/commands/service.js +25 -0
  23. package/dist/commands/status.js +130 -107
  24. package/dist/doctor-client.js +2 -23
  25. package/dist/federation/scheduler.js +148 -12
  26. package/dist/keystore.js +77 -10
  27. package/dist/lib/agent-key-file.js +509 -0
  28. package/dist/lib/agent-rotation-lock.js +249 -0
  29. package/dist/lib/atomic-write.js +2 -2
  30. package/dist/lib/auth-resolve.js +14 -14
  31. package/dist/lib/key-dir.js +203 -0
  32. package/dist/lib/launchd-management.js +7 -3
  33. package/dist/lib/local-instance-pair.js +8 -1
  34. package/dist/lib/node-alias-path.js +50 -2
  35. package/dist/lib/remote-admin-pass.js +157 -0
  36. package/dist/lib/scheduler-platform.js +13 -0
  37. package/dist/lib/service-repoint.js +13 -4
  38. package/dist/lib/skill-seed.js +35 -3
  39. package/dist/lib/terminal-text.js +32 -0
  40. package/dist/mcp-client-assertion.js +5 -4
  41. package/dist/resources/Memory.js +47 -3
  42. package/dist/resources/health.js +39 -22
  43. package/dist/resources/in-process-api.js +74 -11
  44. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  45. package/dist/resources/mcp-handler.js +40 -1
  46. package/dist/resources/mcp-oauth.js +17 -1
  47. package/dist/resources/mcp-tool-scopes.js +69 -0
  48. package/dist/resources/mcp-tools.js +10 -0
  49. package/dist/resources/skill-version-write.js +16 -0
  50. package/dist/src/keystore.js +77 -10
  51. package/dist/src/lib/atomic-write.js +2 -2
  52. package/dist/src/lib/key-dir.js +203 -0
  53. package/dist/src/lib/scheduler-platform.js +13 -0
  54. package/docs/access-control.md +21 -12
  55. package/docs/api-reference.md +35 -24
  56. package/docs/auth.md +31 -22
  57. package/docs/deploying-on-fabric.md +10 -2
  58. package/docs/embedding-in-a-harper-app.md +7 -7
  59. package/docs/entity-vocabulary.md +4 -5
  60. package/docs/hosted-on-fabric.md +1 -1
  61. package/docs/secrets-and-keys.md +8 -13
  62. package/docs/upgrade.md +15 -5
  63. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, renameSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import * as render from "../render.js";
4
+ import { scanKeyDir } from "../lib/key-dir.js";
4
5
  import { loadEd25519PrivateKeyFromFile } from "../mcp-client-assertion.js";
5
6
  import { defaultAdminPassPath, defaultKeysDir, isLocalBase, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
7
  import { probeInstanceIds } from "../lib/instance-identity-row.js";
@@ -35,23 +36,26 @@ function isValidPrivateKeySeedFile(keyPath) {
35
36
  export async function classifyKeysDir(keysDir, baseUrl, readInstanceIds) {
36
37
  if (!existsSync(keysDir))
37
38
  return { aborted: false, entries: [], orphanRead: null };
38
- const dirents = readdirSync(keysDir, { withFileTypes: true });
39
+ // One walk, shared with doctor and status (flair#3077).
40
+ const scan = scanKeyDir(keysDir);
41
+ if (scan.state === "unreadable")
42
+ throw scan.error;
39
43
  const entries = [];
40
44
  const candidates = [];
41
- for (const d of dirents) {
42
- if (d.isDirectory()) {
45
+ for (const e of scan.entries) {
46
+ if (e.kind === "dir") {
43
47
  entries.push({
44
- name: d.name,
48
+ name: e.name,
45
49
  class: "ignored",
46
- reason: d.name === PRUNED_DIR_NAME ? "prune archive directory" : "directory (not a key file)",
50
+ reason: e.name === PRUNED_DIR_NAME ? "prune archive directory" : "directory (not a key file)",
47
51
  });
48
52
  continue;
49
53
  }
50
- if (!d.name.endsWith(".key")) {
51
- entries.push({ name: d.name, class: "ignored", reason: "not a .key file" });
54
+ if (e.kind === "other") {
55
+ entries.push({ name: e.name, class: "ignored", reason: "not a .key file" });
52
56
  continue;
53
57
  }
54
- candidates.push({ name: d.name, agentId: d.name.slice(0, -".key".length) });
58
+ candidates.push({ name: e.name, agentId: e.name.slice(0, -".key".length) });
55
59
  }
56
60
  const { nodeKeyIds } = partitionKeyIds(candidates.map((c) => c.agentId), keysDir);
57
61
  const orphanRead = nodeKeyIds.length > 0 ? await readInstanceIds() : null;
@@ -1,4 +1,4 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import nacl from "tweetnacl";
4
4
  import * as render from "../render.js";
@@ -7,7 +7,9 @@ import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion
7
7
  import { enableMcp, refreshMcpOAuthFlag, disableMcp, mcpStatus, checkLocalOriginRefusal, fabricLoopbackRefusal, targetOriginRefusal, selfVerifyMcpMetadata, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } from "../lib/mcp-enable.js";
8
8
  import { resolveHome } from "../lib/home.js";
9
9
  import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
10
+ import { AgentKeyPathRefusal } from "../lib/key-dir.js";
10
11
  import { agentHomeEndpoint, resolveTargetInstanceId } from "../lib/agent-home.js";
12
+ import { createAgentKeyFile, ensureAgentKeysDir } from "../lib/agent-key-file.js";
11
13
  let cli;
12
14
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
13
15
  export function bindCli(fns) {
@@ -103,6 +105,30 @@ export class McpClientNotFoundError extends Error {
103
105
  this.name = "McpClientNotFoundError";
104
106
  }
105
107
  }
108
+ function preflightMcpGrantKeyPaths(name, keysDir) {
109
+ if (!isValidAgentId(name) || !/^[a-zA-Z0-9]/.test(name)) {
110
+ throw new Error(`Invalid machine client name '${name}' — ${invalidAgentIdMessage(name)}; must start with a letter or digit.`);
111
+ }
112
+ const privPath = privKeyPath(name, keysDir);
113
+ const pubPath = pubKeyPath(name, keysDir);
114
+ // An occupied path may retain an existing mode and contents; refuse it
115
+ // before key generation or network requests.
116
+ const existingKeyPaths = [];
117
+ for (const path of [privPath, pubPath]) {
118
+ try {
119
+ lstatSync(path);
120
+ existingKeyPaths.push(path);
121
+ }
122
+ catch (error) {
123
+ if (error.code !== "ENOENT")
124
+ throw error;
125
+ }
126
+ }
127
+ if (existingKeyPaths.length > 0) {
128
+ throw new Error(`Key file ${existingKeyPaths.join(", ")} already exists — remove it, or grant under another name.`);
129
+ }
130
+ return { privPath, pubPath };
131
+ }
106
132
  /**
107
133
  * Core, testable `flair mcp grant` orchestration — no process.exit, no
108
134
  * console output, so it's directly unit-testable with a mocked fetch and a
@@ -125,6 +151,7 @@ export async function grantMcpClient(params, deps = {}) {
125
151
  if (manifest.some((e) => e.name === name)) {
126
152
  throw new McpClientNameExistsError(name);
127
153
  }
154
+ const { privPath, pubPath } = preflightMcpGrantKeyPaths(name, keysDir);
128
155
  // Defense-in-depth: refuse to silently reuse/clobber an unrelated
129
156
  // pre-existing Agent id (e.g. a human-run principal sharing this name).
130
157
  const opsUrl = typeof opsPortOrUrl === "number" ? `http://127.0.0.1:${opsPortOrUrl}/` : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -147,71 +174,111 @@ export async function grantMcpClient(params, deps = {}) {
147
174
  throw new McpClientAgentIdCollisionError(name);
148
175
  }
149
176
  }
150
- mkdirSync(keysDir, { recursive: true });
151
- const privPath = privKeyPath(name, keysDir);
152
- const pubPath = pubKeyPath(name, keysDir);
177
+ ensureAgentKeysDir(keysDir);
153
178
  const kp = generateKeyPair();
154
179
  const seed = kp.secretKey.slice(0, 32);
155
180
  const pubKeyB64url = b64url(kp.publicKey);
156
- writeFileSync(privPath, Buffer.from(seed), { mode: 0o600 });
157
- chmodSync(privPath, 0o600);
158
- writeFileSync(pubPath, Buffer.from(kp.publicKey));
159
- const nowIso = now();
160
- // flair#2433 — the new Agent row's home is THIS instance's federation id,
161
- // resolved through the one shared rule; a create stamps it.
162
- const home = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass, fetchImpl));
163
- const insertRes = await fetchImpl(opsUrl, {
164
- method: "POST",
165
- headers: { "Content-Type": "application/json", Authorization: authHeader },
166
- body: JSON.stringify({
167
- operation: "insert",
168
- database: "flair",
169
- table: "Agent",
170
- records: [{
171
- id: name,
172
- name,
173
- type: "agent",
174
- kind: "agent",
175
- status: "active",
176
- displayName: name,
177
- admin: false,
178
- defaultTrustTier: "unverified",
179
- runtime: "headless",
180
- publicKey: pubKeyB64url,
181
- originatorInstanceId: home,
182
- createdAt: nowIso,
183
- updatedAt: nowIso,
184
- }],
185
- }),
186
- });
187
- if (!insertRes.ok) {
188
- // Roll back the key files we just wrote — nothing left behind locally
189
- // on a failed grant.
190
- for (const p of [privPath, pubPath]) {
191
- try {
192
- const { unlinkSync } = await import("node:fs");
193
- unlinkSync(p);
181
+ const createdKeyFiles = [];
182
+ const trackKeyFile = (path, identity) => {
183
+ createdKeyFiles.push({ path, dev: identity.dev, ino: identity.ino });
184
+ };
185
+ try {
186
+ createAgentKeyFile(privPath, Buffer.from(seed), trackKeyFile);
187
+ createAgentKeyFile(pubPath, Buffer.from(kp.publicKey), trackKeyFile);
188
+ const nowIso = now();
189
+ // flair#2433 — the new Agent row's home is THIS instance's federation id,
190
+ // resolved through the one shared rule; a create stamps it.
191
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass, fetchImpl));
192
+ const insertRes = await fetchImpl(opsUrl, {
193
+ method: "POST",
194
+ headers: { "Content-Type": "application/json", Authorization: authHeader },
195
+ body: JSON.stringify({
196
+ operation: "insert",
197
+ database: "flair",
198
+ table: "Agent",
199
+ records: [{
200
+ id: name,
201
+ name,
202
+ type: "agent",
203
+ kind: "agent",
204
+ status: "active",
205
+ displayName: name,
206
+ admin: false,
207
+ defaultTrustTier: "unverified",
208
+ runtime: "headless",
209
+ publicKey: pubKeyB64url,
210
+ originatorInstanceId: home,
211
+ createdAt: nowIso,
212
+ updatedAt: nowIso,
213
+ }],
214
+ }),
215
+ });
216
+ if (!insertRes.ok) {
217
+ const text = await insertRes.text().catch(() => "");
218
+ throw new Error(`Failed to create Agent '${name}' via operations API (${insertRes.status}): ${text}`);
219
+ }
220
+ const clientId = `${issuer.replace(/\/+$/, "")}/MCPClientMetadata/${name}`;
221
+ const entry = {
222
+ name,
223
+ agentId: name,
224
+ clientId,
225
+ keyFile: privPath,
226
+ pubKeyFile: pubPath,
227
+ issuer,
228
+ createdAt: nowIso,
229
+ status: "active",
230
+ };
231
+ writeMcpClientManifest(manifestPath, [...manifest, entry]);
232
+ const resource = `${issuer.replace(/\/+$/, "")}/mcp`;
233
+ const config = buildMcpGrantConfig({ name, resource, keyFile: privPath });
234
+ return { entry, config };
235
+ }
236
+ catch (error) {
237
+ // On failure, try to remove the key files this call created. File identity decides
238
+ // eligibility at the check: a path is removed (by path) only if, when
239
+ // checked, it still names the file this grant created. A path replaced
240
+ // between that check and the unlink can still be removed; a POSIX unlink by
241
+ // name cannot close that window. On POSIX the keys directory has no group or
242
+ // world permissions: a new directory requests 0700, and an existing narrower
243
+ // one keeps its mode. A path that no longer names the
244
+ // created file, or whose check or unlink fails with an error other than
245
+ // ENOENT, is named in the error; a created file moved to another name is
246
+ // not tracked.
247
+ if (createdKeyFiles.length > 0) {
248
+ const leftBehind = [];
249
+ for (const created of createdKeyFiles) {
250
+ let current;
251
+ try {
252
+ current = (deps.lstatKeyFile ?? lstatSync)(created.path);
253
+ }
254
+ catch (statError) {
255
+ const code = statError.code;
256
+ if (code !== "ENOENT") {
257
+ leftBehind.push(`${created.path} (not removed: could not check it (${code ?? "lstat failed"}))`);
258
+ }
259
+ continue;
260
+ }
261
+ if (!current.isFile() || current.dev !== created.dev || current.ino !== created.ino) {
262
+ leftBehind.push(`${created.path} (not removed: the path no longer names the file this grant created)`);
263
+ continue;
264
+ }
265
+ try {
266
+ (deps.unlinkKeyFile ?? unlinkSync)(created.path);
267
+ }
268
+ catch (cleanupError) {
269
+ const code = cleanupError.code;
270
+ if (code !== "ENOENT")
271
+ leftBehind.push(`${created.path} (not removed: ${code ?? "unlink failed"})`);
272
+ }
194
273
  }
195
- catch { /* best effort */ }
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ const cleanup = leftBehind.length === 0
276
+ ? "removed the key paths that still named this call's files when checked"
277
+ : `could not remove key file(s): ${leftBehind.join("; ")}`;
278
+ throw new Error(`${message}; ${cleanup}`, { cause: error });
196
279
  }
197
- const text = await insertRes.text().catch(() => "");
198
- throw new Error(`Failed to create Agent '${name}' via operations API (${insertRes.status}): ${text}`);
280
+ throw error;
199
281
  }
200
- const clientId = `${issuer.replace(/\/+$/, "")}/MCPClientMetadata/${name}`;
201
- const entry = {
202
- name,
203
- agentId: name,
204
- clientId,
205
- keyFile: privPath,
206
- pubKeyFile: pubPath,
207
- issuer,
208
- createdAt: nowIso,
209
- status: "active",
210
- };
211
- writeMcpClientManifest(manifestPath, [...manifest, entry]);
212
- const resource = `${issuer.replace(/\/+$/, "")}/mcp`;
213
- const config = buildMcpGrantConfig({ name, resource, keyFile: privPath });
214
- return { entry, config };
215
282
  }
216
283
  /**
217
284
  * Core, testable `flair mcp revoke` orchestration. SERVER-SIDE ack is
@@ -349,7 +416,17 @@ export function register(program) {
349
416
  .option("--json", "Print machine-readable JSON instead of a human summary")
350
417
  .action(async (opts) => {
351
418
  const agentId = opts.agentId;
352
- const keyPath = resolveAgentKeyPath(agentId, opts.keysDir);
419
+ let keyPath;
420
+ try {
421
+ keyPath = resolveAgentKeyPath(agentId, opts.keysDir);
422
+ }
423
+ catch (err) {
424
+ if (err instanceof AgentKeyPathRefusal) {
425
+ console.error(`Error: ${err.message}`);
426
+ process.exit(1);
427
+ }
428
+ throw err;
429
+ }
353
430
  if (!keyPath) {
354
431
  console.error(`Error: no private key found for agent '${agentId}'. Checked --keys-dir, FLAIR_KEY_DIR, ` +
355
432
  `~/.flair/keys, and ~/.tps/secrets/flair.`);
@@ -463,6 +540,14 @@ export function register(program) {
463
540
  "must be a stable, publicly-resolvable URL.");
464
541
  process.exit(1);
465
542
  }
543
+ const keysDir = opts.keysDir ?? defaultKeysDir();
544
+ try {
545
+ preflightMcpGrantKeyPaths(name, keysDir);
546
+ }
547
+ catch (err) {
548
+ console.error(`Error: ${err.message}`);
549
+ process.exit(1);
550
+ }
466
551
  // Workflow gate: proof `flair mcp enable` has actually run against this
467
552
  // instance — a live probe of the OAuth metadata endpoint (flair#756;
468
553
  // replaces the old DCR-gate-token presence check, which a CIMD-only
@@ -478,7 +563,6 @@ export function register(program) {
478
563
  "Set FLAIR_ADMIN_PASS, or make sure ~/.flair/admin-pass exists (created by `flair init`).");
479
564
  process.exit(1);
480
565
  }
481
- const keysDir = opts.keysDir ?? defaultKeysDir();
482
566
  const manifestPath = opts.manifest ?? defaultMcpClientManifestPath();
483
567
  const opsPort = resolveOpsPort(opts);
484
568
  try {
@@ -11,6 +11,7 @@
11
11
  * Do not import src/cli.ts from here — that would cycle and pull the
12
12
  * non-strict entry into the strict check.
13
13
  */
14
+ import { randomUUID } from "node:crypto";
14
15
  import { Option } from "commander";
15
16
  import * as render from "../render.js";
16
17
  import { resolveAdminUser, addAdminPassOptions } from "../lib/auth-resolve.js";
@@ -104,7 +105,9 @@ export function register(program) {
104
105
  console.error("error: --agent <id> required (or set FLAIR_AGENT_ID)");
105
106
  process.exit(2);
106
107
  }
107
- const memId = `${agentId}-${Date.now()}`;
108
+ // flair#3107: one id per command, random so same-millisecond adds do not
109
+ // collide; computed once so the retry loop below replays it.
110
+ const memId = `${agentId}-${randomUUID()}`;
108
111
  const body = {
109
112
  id: memId, agentId, content, durability: opts.durability || "standard",
110
113
  tags: opts.tags ? String(opts.tags).split(",").map((x) => x.trim()).filter(Boolean) : undefined,
@@ -217,7 +220,7 @@ export function register(program) {
217
220
  }
218
221
  const content = lines.join("\n");
219
222
  const { agentId, source } = resolveSigningAgentId(opts, "memory write-task-summary");
220
- const memId = `${opts.agent}-task-${opts.beads}-${Date.now()}`;
223
+ const memId = `${opts.agent}-task-${opts.beads}-${randomUUID()}`;
221
224
  const body = {
222
225
  id: memId,
223
226
  agentId: opts.agent,
@@ -4,6 +4,7 @@ import { randomUUID } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
5
5
  import { join, resolve, sep } from "node:path";
6
6
  import { resolveHome } from "../lib/home.js";
7
+ import { agentKeyPath } from "../lib/key-dir.js";
7
8
  import { encodeRecordId } from "../lib/record-id-path.js";
8
9
  let cli;
9
10
  /** Bind the cli-locals this module depends on. */
@@ -111,6 +112,14 @@ export function register(program) {
111
112
  const target = opts.target;
112
113
  const agentId = opts.agent;
113
114
  const dryRun = !!opts.dryRun;
115
+ let keyPath;
116
+ try {
117
+ keyPath = agentKeyPath(join(resolveHome(), ".flair", "keys"), agentId);
118
+ }
119
+ catch (err) {
120
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
121
+ process.exit(1);
122
+ }
114
123
  let memoryDir;
115
124
  try {
116
125
  memoryDir = resolveMemoryDir(target, agentId);
@@ -187,9 +196,6 @@ export function register(program) {
187
196
  console.log(` Writing to Flair...`);
188
197
  try {
189
198
  const httpUrl = `http://127.0.0.1:${resolveHttpPort({})}`;
190
- const agentKeyId = `${agentId}.key`;
191
- const keysDir = join(resolveHome(), ".flair", "keys");
192
- const keyPath = join(keysDir, agentKeyId);
193
199
  let authSuccess = false;
194
200
  if (existsSync(keyPath)) {
195
201
  const memoryId = `${agentId}-${randomUUID()}`;
@@ -1,7 +1,8 @@
1
1
  import nacl from "tweetnacl";
2
- import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "node:fs";
2
+ import { writeFileSync } from "node:fs";
3
3
  import * as render from "../render.js";
4
4
  import { defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, addAdminPassOptions, } from "../lib/auth-resolve.js";
5
+ import { ensureAgentKeysDir, readOrCreateAgentKey } from "../lib/agent-key-file.js";
5
6
  import { resolveOpsUrl } from "../lib/mcp-enable.js";
6
7
  import { writeConfirmed } from "../lib/instance-identity-row.js";
7
8
  import { agentHomeEndpoint, planAgentHomeWrite, readStoredAgentHome, resolveTargetInstanceId, AGENT_HOME_IMMUTABLE_ERROR, AGENT_PRINCIPAL_WRITE_BACK_FIELD, AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR } from "../lib/agent-home.js";
@@ -270,24 +271,28 @@ export function register(program) {
270
271
  process.exit(1);
271
272
  }
272
273
  // Generate Ed25519 keypair (agents always get one; humans get one for instance-attestation)
273
- mkdirSync(keysDir, { recursive: true });
274
274
  const privPath = privKeyPath(id, keysDir);
275
275
  const pubPath = pubKeyPath(id, keysDir);
276
276
  let pubKeyB64url;
277
- if (existsSync(privPath)) {
278
- console.log(`Reusing existing key: ${privPath}`);
279
- const seed = new Uint8Array(readFileSync(privPath));
280
- const kp = nacl.sign.keyPair.fromSeed(seed);
277
+ try {
278
+ ensureAgentKeysDir(keysDir);
279
+ const keyFile = readOrCreateAgentKey(privPath, () => {
280
+ const kp = nacl.sign.keyPair();
281
+ return Buffer.from(kp.secretKey.slice(0, 32));
282
+ });
283
+ const kp = nacl.sign.keyPair.fromSeed(new Uint8Array(keyFile.bytes));
281
284
  pubKeyB64url = b64url(kp.publicKey);
285
+ if (keyFile.created) {
286
+ writeFileSync(pubPath, Buffer.from(kp.publicKey));
287
+ console.log(`Keypair written: ${privPath}`);
288
+ }
289
+ else {
290
+ console.log(`Reusing existing key: ${privPath}`);
291
+ }
282
292
  }
283
- else {
284
- const kp = nacl.sign.keyPair();
285
- const seed = kp.secretKey.slice(0, 32);
286
- writeFileSync(privPath, Buffer.from(seed));
287
- chmodSync(privPath, 0o600);
288
- writeFileSync(pubPath, Buffer.from(kp.publicKey));
289
- pubKeyB64url = b64url(kp.publicKey);
290
- console.log(`Keypair written: ${privPath}`);
293
+ catch (err) {
294
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
295
+ process.exit(1);
291
296
  }
292
297
  // Insert via operations API with Principal fields
293
298
  const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
@@ -10,6 +10,7 @@ import { encodeRecordId } from "../lib/record-id-path.js";
10
10
  import { ApiRequestOutcomeUnknown } from "../lib/auth-resolve.js";
11
11
  import * as render from "../render.js";
12
12
  import { EMBEDDING_STAMP_ID, describeStampOutstanding, resolveCurrentModelId } from "../stamp-outstanding.js";
13
+ import { randomUUID } from "node:crypto";
13
14
  let cli;
14
15
  /** Bind the cli-locals this module depends on. */
15
16
  export function bindCli(fns) {
@@ -388,9 +389,19 @@ export function computeQualityReport(healthy, healthData, opts = {}) {
388
389
  // empty perAgent array (nothing to prove otherwise, and both scopes render
389
390
  // identically empty either way).
390
391
  const haveUsageCount = perAgentAll.every((r) => typeof r.usageCount === "number");
392
+ // Rows whose memoryCount or writes24h is absent or not a number carry no
393
+ // usable counts. A rate or a quiet verdict computed from either count would
394
+ // be a claim about data nobody read, so neither is reported.
395
+ const haveMemoryStats = perAgentAll.every((r) => typeof r.memoryCount === "number" && typeof r.writes24h === "number");
391
396
  // ── Signal density (write volume, + citation rate when the server supports it) ──
392
397
  let signalDensity = null;
393
- if (havePerAgent && haveUsageCount) {
398
+ if (havePerAgent && !haveMemoryStats) {
399
+ gaps.push({
400
+ metric: "signalDensity",
401
+ reason: "per-agent memory fields unavailable",
402
+ });
403
+ }
404
+ else if (havePerAgent && haveUsageCount) {
394
405
  signalDensity = {
395
406
  scope: "write-and-citation",
396
407
  perAgent: scopedAgents.map((r) => {
@@ -415,7 +426,13 @@ export function computeQualityReport(healthy, healthData, opts = {}) {
415
426
  }
416
427
  // ── Quiet agents (ops fact — not a trust signal) ──
417
428
  let quietAgents = null;
418
- if (havePerAgent) {
429
+ if (havePerAgent && !haveMemoryStats) {
430
+ gaps.push({
431
+ metric: "quietAgents",
432
+ reason: "per-agent memory fields unavailable",
433
+ });
434
+ }
435
+ else if (havePerAgent) {
419
436
  const rows = scopedAgents.map((r) => {
420
437
  const daysSinceLastWrite = r.lastWriteAt ? Math.floor((now - new Date(r.lastWriteAt).getTime()) / 86_400_000) : null;
421
438
  const quiet = daysSinceLastWrite === null ? true : daysSinceLastWrite >= QUALITY_QUIET_THRESHOLD_DAYS;
@@ -810,7 +827,10 @@ export async function fetchPreviousQualitySnapshot(agentId, baseUrl, subject, op
810
827
  * Throws on a write failure — the CLI action below is responsible for
811
828
  * surfacing that as a clear error, same as every other write path here. */
812
829
  async function storeQualitySnapshot(agentId, agentIdSource, baseUrl, subject, snapshot) {
813
- const memId = `${agentId}-quality-snapshot-${Date.now()}`;
830
+ // flair#3115: the PUT is an upsert, so a millisecond suffix made two --emit
831
+ // runs in the same millisecond overwrite one row; the uuid suffix keeps the
832
+ // two writes apart.
833
+ const memId = `${agentId}-quality-snapshot-${randomUUID()}`;
814
834
  const body = {
815
835
  id: memId,
816
836
  agentId,