@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * mcp-handler.ts — the Model-2 custom MCP protocol handler.
3
3
  *
4
- * A minimal in-process MCP (JSON-RPC 2.0) handler serving the 12 curated flair
5
- * tools over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
4
+ * A minimal in-process MCP (JSON-RPC 2.0) handler serving the curated flair
5
+ * tools (resources/mcp-tools.ts's TOOLS) over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
6
6
  * `withMCPAuth` (see mcp-oauth.ts), which fails closed on any missing/invalid
7
7
  * Bearer token BEFORE this handler runs and, on success, sets
8
8
  * `request.mcp = { sub, client_id, aud, scope }` (verified RS256 JWT claims).
@@ -28,6 +28,8 @@ import { randomBytes } from "node:crypto";
28
28
  import { TOOLS, listToolDefs } from "./mcp-tools.js";
29
29
  import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.js";
30
30
  import { agentRecordIsAdmin } from "./agent-admin.js";
31
+ import { isPrincipalDeactivated } from "./agent-auth.js";
32
+ import { stampOriginatorOnCreate } from "./originator-instance.js";
31
33
  import { resolveVersion } from "./version.js";
32
34
  // The MCP protocol revision we implement (initialize handshake).
33
35
  const PROTOCOL_VERSION = "2025-06-18";
@@ -159,15 +161,35 @@ function jitProvisionEnabled() {
159
161
  * `undefined` — so existing callers/tests that don't pass one see the exact
160
162
  * same `{ agentId, isAdmin }` shape as before this field existed.
161
163
  *
164
+ * When a Credential maps the sub, the mapped principal must exist and be
165
+ * active — the rule the Ed25519 path applies (resources/agent-auth.ts,
166
+ * `isPrincipalDeactivated`) — and its record is read on every resolution, so a
167
+ * token minted while the principal was active stops resolving once the
168
+ * principal is deactivated. If that read fails, or the credential lookup itself
169
+ * fails, resolution is refused. An unreadable answer is never taken as
170
+ * "allowed", and never as "no mapping": JIT provisioning runs only for a
171
+ * subject the credential lookup answered for. Resolution writes nothing to an
172
+ * existing credential; the handler updates its `lastUsedAt`, best effort, after
173
+ * a tool has run (handleToolCall).
174
+ *
162
175
  * Returns:
163
- * - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an Agent.
176
+ * - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an
177
+ * existing, active Agent.
164
178
  * - null when no Credential maps the sub AND JIT-provisioning is disabled or
165
179
  * failed → the handler denies the tool call (sub is unresolvable).
180
+ *
181
+ * Throws `PrincipalRefusedError` (the handler returns its JSON-RPC error) when
182
+ * the mapped principal is deactivated or missing, or when the credential or
183
+ * principal could not be read.
166
184
  */
167
185
  export async function resolveAgentFromSub(sub, clientId) {
186
+ return (await resolveMapping(sub, clientId))?.agent ?? null;
187
+ }
188
+ async function resolveMapping(sub, clientId) {
168
189
  if (!sub)
169
190
  return null;
170
191
  // 1. Existing IdP credential → its principalId is the Agent id.
192
+ let mapped = null;
171
193
  try {
172
194
  for await (const cred of databases.flair.Credential.search({
173
195
  conditions: [
@@ -176,29 +198,33 @@ export async function resolveAgentFromSub(sub, clientId) {
176
198
  ],
177
199
  })) {
178
200
  if (cred?.principalId && cred.status !== "revoked") {
179
- // Touch lastUsedAt (best-effort; a failure here must not deny a valid call).
180
- try {
181
- await databases.flair.Credential.put({ ...cred, lastUsedAt: new Date().toISOString() });
182
- }
183
- catch { /* non-fatal */ }
184
- const resolved = { agentId: String(cred.principalId), isAdmin: await isAgentAdmin(cred.principalId) };
185
- if (clientId)
186
- resolved.clientId = clientId;
187
- return resolved;
201
+ mapped = cred;
202
+ break;
188
203
  }
189
204
  }
190
205
  }
191
- catch { /* Credential table empty / search error → fall through to JIT/deny */ }
206
+ catch {
207
+ throw new PrincipalRefusedError(-32000, "unavailable: the credential for this token's subject could not be read, so the call was refused. " +
208
+ "Retry; if this persists, an operator should check the flair server log.");
209
+ }
210
+ if (mapped) {
211
+ const principalId = String(mapped.principalId);
212
+ const principal = await requireActivePrincipal(principalId);
213
+ const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
214
+ if (clientId)
215
+ resolved.clientId = clientId;
216
+ return { agent: resolved, credential: mapped };
217
+ }
192
218
  // 2. No mapping. JIT-provision only behind the explicit trust anchor.
193
219
  if (!jitProvisionEnabled())
194
220
  return null;
195
221
  try {
196
- const principalId = await jitProvisionPrincipal(sub);
222
+ const { principalId, credential } = await jitProvisionPrincipal(sub);
197
223
  // A JIT-provisioned principal is a fresh, non-admin agent by construction.
198
224
  const resolved = { agentId: principalId, isAdmin: false };
199
225
  if (clientId)
200
226
  resolved.clientId = clientId;
201
- return resolved;
227
+ return { agent: resolved, credential };
202
228
  }
203
229
  catch {
204
230
  return null;
@@ -209,11 +235,15 @@ export async function resolveAgentFromSub(sub, clientId) {
209
235
  * token subject. Mirrors XAA.resolveOrCreatePrincipal's provisioning shape (the
210
236
  * `Credential.kind:"idp"` + `idpSubject` surface) but keyed on the MCP token sub.
211
237
  * The created agent is non-admin, `kind:"agent"`, unverified trust tier.
238
+ * Returns the principal id and the new credential, which is created without
239
+ * `lastUsedAt`.
212
240
  */
213
241
  async function jitProvisionPrincipal(sub) {
214
242
  const now = new Date().toISOString();
215
243
  const principalId = `agt_mcp_${sub.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 24)}_${randomBytes(4).toString("hex")}`;
216
- await databases.flair.Agent.put({
244
+ // flair#1965 r2: this is a raw Agent create (it bypasses the Agent resource's
245
+ // post()), so stamp the local instance id here — every create path carries it.
246
+ const principalRow = {
217
247
  id: principalId,
218
248
  name: principalId,
219
249
  displayName: principalId,
@@ -227,8 +257,10 @@ async function jitProvisionPrincipal(sub) {
227
257
  admin: false,
228
258
  createdAt: now,
229
259
  updatedAt: now,
230
- });
231
- await databases.flair.Credential.put({
260
+ };
261
+ await stampOriginatorOnCreate(principalRow);
262
+ await databases.flair.Agent.put(principalRow);
263
+ const credential = {
232
264
  id: `cred_mcp_${randomBytes(8).toString("hex")}`,
233
265
  principalId,
234
266
  kind: "idp",
@@ -237,32 +269,57 @@ async function jitProvisionPrincipal(sub) {
237
269
  idpProvider: "mcp-oauth",
238
270
  idpSubject: sub,
239
271
  createdAt: now,
240
- lastUsedAt: now,
241
- });
242
- return principalId;
272
+ };
273
+ await databases.flair.Credential.put(credential);
274
+ return { principalId, credential };
275
+ }
276
+ /**
277
+ * A token subject whose principal may not call tools. `rpcCode` and the message
278
+ * are the JSON-RPC error the handler returns. The message names the principal
279
+ * when there is one, and says what an operator has to do, or that the caller
280
+ * should retry after a failed read.
281
+ */
282
+ export class PrincipalRefusedError extends Error {
283
+ rpcCode;
284
+ constructor(rpcCode, message) {
285
+ super(message);
286
+ this.name = "PrincipalRefusedError";
287
+ this.rpcCode = rpcCode;
288
+ }
243
289
  }
244
290
  /**
245
- * Is this Principal a flair admin? A MCP-OAuth agent is NON-admin unless an
246
- * operator has explicitly marked its Agent record admin — the MCP surface never
247
- * elevates on its own.
291
+ * Read the mapped principal for this call and require it to exist and be
292
+ * active (`isPrincipalDeactivated`, the predicate the Ed25519 path uses: a
293
+ * record with no `status` field counts as active).
294
+ * Returns the principal record; throws `PrincipalRefusedError` otherwise,
295
+ * including when the record cannot be read.
248
296
  *
249
- * flair#941: this used to OR the two admin fields together while the primary
250
- * HTTP gate (resources/agent-auth.ts's isAdmin) read only `role`, so the same
251
- * record could be an administrator here and an ordinary agent there. It now
252
- * resolves through the one shared predicate, so both surfaces answer
253
- * identically. A record carrying `admin: true` alone — which no flair write
254
- * path produces, and which was never an admin on the HTTP gate — is no longer
255
- * an admin here either; see resources/agent-admin.ts for the remedy. This
256
- * surface is gated behind FLAIR_MCP_OAUTH and is default-OFF.
297
+ * Admin status is read from the same record, through the one shared predicate
298
+ * (resources/agent-admin.ts, flair#941): a MCP-OAuth agent is NON-admin unless
299
+ * an operator has set its Agent record's `role` to "admin" — the MCP surface
300
+ * never elevates on its own. This surface is gated behind FLAIR_MCP_OAUTH and is
301
+ * default-OFF.
257
302
  */
258
- async function isAgentAdmin(principalId) {
303
+ async function requireActivePrincipal(principalId) {
304
+ let principal;
259
305
  try {
260
- const agent = await databases.flair.Agent.get(principalId);
261
- return agentRecordIsAdmin(agent);
306
+ principal = await databases.flair.Agent.get(principalId);
262
307
  }
263
308
  catch {
264
- return false;
309
+ throw new PrincipalRefusedError(-32000, `unavailable: the status of principal '${principalId}' could not be read, so the call was refused. ` +
310
+ "Retry; if this persists, an operator should check the flair server log.");
311
+ }
312
+ if (principal == null) {
313
+ throw new PrincipalRefusedError(-32001, `forbidden: this token's subject maps to principal '${principalId}', which does not exist. ` +
314
+ "An operator must map the subject to an existing principal: a full `flair mcp enable` run against " +
315
+ "this instance, with --principal <agent-id> and --idp-subject <subject>, writes that mapping in its " +
316
+ "identity-mapping step.");
317
+ }
318
+ if (isPrincipalDeactivated(principal)) {
319
+ throw new PrincipalRefusedError(-32001, `forbidden: principal '${principalId}' is deactivated, so this token can no longer call tools. ` +
320
+ "An operator must reactivate the principal (set its status to \"active\") to restore access.");
265
321
  }
322
+ return principal;
266
323
  }
267
324
  // ─── MCP protocol dispatch ───────────────────────────────────────────────────
268
325
  /**
@@ -343,12 +400,26 @@ async function handleToolCall(request, id, params) {
343
400
  // turn a server-verified, stable id into caller-forgeable data landing in
344
401
  // stored provenance. Absent/non-string client_id → omitted, not invented.
345
402
  const clientId = typeof request?.mcp?.client_id === "string" ? request.mcp.client_id : undefined;
346
- const agent = await resolveAgentFromSub(String(sub), clientId);
347
- if (!agent) {
403
+ // For a call that resolves through an existing credential mapping, the
404
+ // principal's status is read here, on every such call (resolveMapping): a
405
+ // deactivated or missing principal, or one whose status cannot be read, is
406
+ // refused with the actionable error it carries.
407
+ let mapping;
408
+ try {
409
+ mapping = await resolveMapping(String(sub), clientId);
410
+ }
411
+ catch (err) {
412
+ if (err instanceof PrincipalRefusedError)
413
+ return rpcError(id, err.rpcCode, err.message);
414
+ return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
415
+ "Retry; if this persists, an operator should check the flair server log.");
416
+ }
417
+ if (!mapping) {
348
418
  // Sub verified by the AS but not mapped to a flair Agent (and JIT disabled /
349
419
  // failed). Deny — do NOT fall back to anonymous or admin.
350
420
  return rpcError(id, -32001, "forbidden: token subject is not a provisioned flair agent");
351
421
  }
422
+ const agent = mapping.agent;
352
423
  // The tool implementations are written for their declared argument types;
353
424
  // a value of another type is refused before the tool runs, and a null
354
425
  // optional argument is treated as absent rather than forwarded.
@@ -356,22 +427,47 @@ async function handleToolCall(request, id, params) {
356
427
  if (argError)
357
428
  return rpcError(id, -32602, `invalid arguments for ${toolName}: ${argError}`);
358
429
  const toolArgs = withoutNullArguments(args);
430
+ let result;
359
431
  try {
360
- const result = await entry.impl(agent, toolArgs);
361
- // MCP tools/call result: content blocks. Surface the handler's JSON payload
362
- // as a text block (structuredContent carries the raw object for programmatic
363
- // clients). A handler-level error object (from unwrap of a Response) is
364
- // reported as an MCP tool error (isError) rather than a JSON-RPC error, so
365
- // the client sees the structured message.
366
- const text = typeof result === "string" ? result : JSON.stringify(result);
367
- const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
368
- return rpcResult(id, {
369
- content: [{ type: "text", text }],
370
- structuredContent: typeof result === "object" ? result : { value: result },
371
- isError,
372
- });
432
+ result = await entry.impl(agent, toolArgs);
373
433
  }
374
434
  catch (err) {
375
435
  return rpcError(id, -32000, `tool execution failed: ${err?.message ?? String(err)}`);
376
436
  }
437
+ // The tool has run and returned (a tool-level error result included): only
438
+ // now is the mapping credential, a JIT-provisioned one included, marked used.
439
+ // A refused call, rejected arguments, or a tool that throws leave `lastUsedAt`
440
+ // as it was. Best effort: a failed write is ignored and does not change the
441
+ // answer.
442
+ await touchLastUsed(mapping.credential);
443
+ // MCP tools/call result: content blocks. Surface the handler's JSON payload
444
+ // as a text block (structuredContent carries the raw object for programmatic
445
+ // clients). A handler-level error object (from unwrap of a Response) is
446
+ // reported as an MCP tool error (isError) rather than a JSON-RPC error, so
447
+ // the client sees the structured message.
448
+ const text = typeof result === "string" ? result : JSON.stringify(result);
449
+ const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
450
+ return rpcResult(id, {
451
+ content: [{ type: "text", text }],
452
+ structuredContent: typeof result === "object" ? result : { value: result },
453
+ isError,
454
+ });
455
+ }
456
+ /**
457
+ * Mark the mapping credential used, once a tool has run (best-effort). The
458
+ * update writes `lastUsedAt` alone, as a field-level patch from an internal
459
+ * context (no request, no user), and is skipped when a read just before it
460
+ * finds no stored credential row.
461
+ */
462
+ async function touchLastUsed(credential) {
463
+ const credentialId = credential?.id;
464
+ if (credentialId == null)
465
+ return;
466
+ try {
467
+ const Credential = databases.flair.Credential;
468
+ if ((await Credential.get(credentialId, {})) == null)
469
+ return;
470
+ await Credential.patch(credentialId, { lastUsedAt: new Date().toISOString() }, {});
471
+ }
472
+ catch { /* non-fatal: a failure here does not change the call's answer */ }
377
473
  }
@@ -20,6 +20,7 @@
20
20
  import * as harper from "harper";
21
21
  import { mcpOAuthEnabled, mcpAuthConfig } from "./mcp-oauth-flag.js";
22
22
  import { checkMcpRateLimit } from "./rate-limit.js";
23
+ import { MULTI_WORKER_GUARD_HTTP_NAME } from "./multi-worker-guard.js";
23
24
  /**
24
25
  * Boot guard (flair#1021): when FLAIR_MCP_OAUTH is on, the @harperfast/oauth
25
26
  * component MUST be declared in config.yaml. Without it the authorization
@@ -181,14 +182,10 @@ export async function registerMcpOAuthRoute(deps = {}) {
181
182
  // module, not a static named export) so this module links cleanly even where a
182
183
  // stub build of harper lacks the export.
183
184
  const srv = deps.server ?? (harper.server);
184
- // Primary registration: urlPath subroute → own chain (flair's auth-middleware
185
- // does not run here). `getConfig` pins iss/resource to the AS's values so the
186
- // wrapper's iss/aud checks match the minted tokens even if this component
187
- // resolves a different node_modules copy of the plugin (docs/mcp-oauth.md
188
- // §"Using withMCPAuth from a different component").
185
+ // Mount /mcp after the guard.
189
186
  srv.http(withMCPAuth(rateLimitedMcpHandler(handler), {
190
187
  getConfig: () => mcpAuthConfig(),
191
- }), { urlPath: "/mcp" });
188
+ }), { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
192
189
  console.error(`[mcp-oauth] /mcp mounted (OAuth-guarded); issuer=${config.issuer}`);
193
190
  return decide({ mounted: true });
194
191
  }
@@ -362,8 +362,9 @@ function projectSkillCard(r) {
362
362
  * - the HNSW leg over the stored embedding — which for a skill row IS the
363
363
  * `trigger` embedding (#1543), so the task is ranked against "when to use";
364
364
  * - the 'query' inputType SemanticSearch already applies to the task string;
365
- * - resolveReadScope (own any-visibility + every non-private row) — NEVER
366
- * another agent's private skill.
365
+ * - Non-admin searches use resolveReadScope: own records at any visibility
366
+ * plus other agents' non-private records. Administrator searches can
367
+ * include private skills.
367
368
  * Identity is the RESOLVED agent; no body agentId is forwarded, so a caller can
368
369
  * never widen scope past its own read-scope (the SemanticSearch cross-agent
369
370
  * guard would 403 a mismatch anyway).
@@ -398,9 +399,9 @@ async function skillSearch(agent, args) {
398
399
  * skill_get — the full skill by id (flair#1546 component 2).
399
400
  *
400
401
  * A thin wrapper over Memory.get() — the SAME by-id read as memory_get, under
401
- * the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-owner
402
- * cannot read another agent's PRIVATE skill (it 404s), exactly as a private
403
- * memory does. skill_get is the disclosure step after skill_search's catalog:
402
+ * the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-admin
403
+ * caller cannot read another agent's private skill; administrators retain
404
+ * access, exactly as a private memory does. skill_get is the disclosure step after skill_search's catalog:
404
405
  * it returns the full procedure (`content`) + trigger + metadata.
405
406
  *
406
407
  * It is a SKILL tool, not a general reader: a readable id that is NOT a skill
@@ -541,10 +542,10 @@ async function memoryUpdate(agent, args) {
541
542
  // retrievable via memory_get and memory_search(includeArchived:true)). Restore
542
543
  // is the deliberate, GLOBAL inverse — it un-retires the memory for EVERY
543
544
  // session, not a session-local view (that is drawers, Deliverable B, which does
544
- // not exist yet). Both are writes scoped to the caller's own lane: the read
545
- // uses Memory.get()'s read-scope gate and the write uses Memory.put()'s
546
- // ownership gate (stampAttribution), so a caller can neither read nor write
547
- // another agent's memory here.
545
+ // not exist yet). Non-admin agent reads use Memory.get()'s owner-and-
546
+ // visibility scope; administrator and trusted internal reads are unfiltered.
547
+ // Mutating another agent's record requires administrator or trusted internal
548
+ // authority (Memory.put()'s stampAttribution gate).
548
549
  async function memoryBasement(agent, args) {
549
550
  const Cls = await handler("Memory");
550
551
  const id = args?.id;
@@ -596,7 +597,9 @@ async function memoryGet(agent, args) {
596
597
  // path the Ed25519 REST route takes: it loads the row, hands the override a
597
598
  // `RequestTarget` (never a bare string), and still dispatches through
598
599
  // Memory.get() → makeByIdReadGate → resolveReadScope, so the scope model is
599
- // unchanged (own + org-non-private only). See resources/in-process.ts:223.
600
+ // unchanged: non-admin agents can read their own and other agents'
601
+ // non-private records; administrator reads are unfiltered. See
602
+ // resources/in-process.ts:223.
600
603
  //
601
604
  // flair#744 slice 1 — opt-in inline trust block. The instance call passed
602
605
  // `includeTrust` as a 2nd positional opts arg to get(); the static form has
@@ -884,7 +887,7 @@ export const TOOLS = bindNativeTools({
884
887
  memory_search: {
885
888
  impl: memorySearch,
886
889
  contract: {
887
- summary: "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own and other agents' non-private memories; each hit carries content, never the raw embedding.",
890
+ summary: "{ results: MemoryRecord[] } — semantic hits subject to the caller's read scope; each hit carries content, never the raw embedding.",
888
891
  requiredFields: ["results"],
889
892
  fieldTypes: { results: "array" },
890
893
  invariants: {
@@ -920,8 +923,8 @@ export const TOOLS = bindNativeTools({
920
923
  impl: skillSearch,
921
924
  contract: {
922
925
  summary: "{ results: SkillCard[] } — the skill catalog (lightweight id/name/trigger/description/tags/agentId, " +
923
- "ranked by trigger match); the full procedure and the raw embedding are never on a card. Scoped to the " +
924
- "caller's own + non-private skills; another agent's private skill is never returned.",
926
+ "ranked by trigger match); the full procedure and the raw embedding are never on a card. Non-admin callers " +
927
+ "can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills.",
925
928
  requiredFields: ["results"],
926
929
  fieldTypes: { results: "array" },
927
930
  invariants: {
@@ -937,13 +940,14 @@ export const TOOLS = bindNativeTools({
937
940
  impl: skillGet,
938
941
  contract: {
939
942
  summary: "The full skill record { id, agentId, content, trigger, tags, durability, metadata, createdAt, ... } for a " +
940
- "skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-owner " +
941
- "cannot read another agent's private skill, and a readable non-skill id is not found (both 404).",
943
+ "skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-admin " +
944
+ "caller cannot read another agent's private skill; administrators retain access. A readable non-skill id " +
945
+ "is reported as not found.",
942
946
  requiredFields: ["id", "agentId", "content", "createdAt"],
943
947
  fieldTypes: { id: "string", agentId: "string", content: "string" },
944
948
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
945
949
  invariants: { fullyResolved: true },
946
- errorShape: { trigger: "get a non-skill / unreadable / another agent's private id (404)", fields: ["error", "status"] },
950
+ errorShape: { trigger: "get a non-skill or unreadable id (404)", fields: ["error", "status"] },
947
951
  },
948
952
  },
949
953
  memory_update: {
@@ -965,7 +969,7 @@ export const TOOLS = bindNativeTools({
965
969
  fieldTypes: { id: "string", archived: "boolean" },
966
970
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
967
971
  invariants: { fullyResolved: true },
968
- errorShape: { trigger: "basementing a non-existent or non-owned id", fields: ["error", "status"] },
972
+ errorShape: { trigger: "basementing a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
969
973
  },
970
974
  },
971
975
  memory_restore: {
@@ -976,24 +980,24 @@ export const TOOLS = bindNativeTools({
976
980
  fieldTypes: { id: "string", archived: "boolean" },
977
981
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
978
982
  invariants: { fullyResolved: true },
979
- errorShape: { trigger: "restoring a non-existent or non-owned id", fields: ["error", "status"] },
983
+ errorShape: { trigger: "restoring a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
980
984
  },
981
985
  },
982
986
  memory_get: {
983
987
  impl: memoryGet,
984
988
  contract: {
985
- summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the caller's own id — embedding + embeddingModel stripped by default.",
989
+ summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the requested ID, subject to the caller's read scope; embedding and embeddingModel are stripped by default.",
986
990
  requiredFields: ["id", "agentId", "content", "createdAt"],
987
991
  fieldTypes: { id: "string", agentId: "string", content: "string" },
988
992
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
989
993
  invariants: { fullyResolved: true },
990
- errorShape: { trigger: "get a non-existent / unowned id (makeByIdReadGate 404)", fields: ["error", "status"] },
994
+ errorShape: { trigger: "get a non-existent or unreadable id (makeByIdReadGate 404)", fields: ["error", "status"] },
991
995
  },
992
996
  },
993
997
  memory_delete: {
994
998
  impl: memoryDelete,
995
999
  contract: {
996
- summary: "Deletes the caller's own memory at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
1000
+ summary: "Deletes a memory by ID when authorized, at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
997
1001
  invariants: { fullyResolved: true },
998
1002
  errorShape: { trigger: "a non-admin deletes another agent's memory", fields: ["error", "status"] },
999
1003
  },
@@ -1009,11 +1013,15 @@ export const TOOLS = bindNativeTools({
1009
1013
  "memoriesTruncated", "teammateFindingsIncluded", "teammateFindingsTruncated",
1010
1014
  "teammateFindingsMatched", "context", "flairVersion",
1011
1015
  "eventWatermark", "eventsHasMore", "eventsRemaining",
1016
+ // flair#2141 S1b — the skills manifest, always present.
1017
+ "skills", "skillDiagnostics", "skillsTruncated", "skillDiagnosticsTruncated",
1012
1018
  // flair#1270 — the payload token LEDGER: every token-charged content
1013
1019
  // class has a counter, so tokenEstimate ≈ scaffoldTokens + soulTokens +
1014
- // memoryTokens + trustTokens + eventsTokens decomposes from the payload
1015
- // alone (see the identity block in MemoryBootstrap's response tail).
1020
+ // memoryTokens + trustTokens + eventsTokens + skillsTokens +
1021
+ // skillDiagnosticsTokens decomposes from the payload alone (see the
1022
+ // identity block in MemoryBootstrap's response tail).
1016
1023
  "soulTokens", "memoryTokens", "trustTokens", "eventsTokens", "scaffoldTokens",
1024
+ "skillsTokens", "skillDiagnosticsTokens",
1017
1025
  ],
1018
1026
  fieldTypes: {
1019
1027
  agentId: "string", soul: "object", memories: "array", predicted: "array",
@@ -1025,6 +1033,8 @@ export const TOOLS = bindNativeTools({
1025
1033
  soulTokens: "number", memoryTokens: "number", trustTokens: "number",
1026
1034
  eventsTokens: "number", scaffoldTokens: "number",
1027
1035
  eventWatermark: "string", eventsHasMore: "boolean", eventsRemaining: "number",
1036
+ skills: "array", skillDiagnostics: "array", skillsTruncated: "number",
1037
+ skillDiagnosticsTruncated: "number", skillsTokens: "number", skillDiagnosticsTokens: "number",
1028
1038
  },
1029
1039
  invariants: {
1030
1040
  // count == delivered — the historical count/charge/deliver drift.
@@ -1034,12 +1044,14 @@ export const TOOLS = bindNativeTools({
1034
1044
  { count: "teammateFindingsIncluded", containers: ["teammateFindings"] }, // #1199
1035
1045
  { count: "sections.events", containers: ["events"] }, // #1206
1036
1046
  { count: "sections.soul", containers: ["soul"] }, // #1371
1047
+ { count: "sections.skills", containers: ["skills"] }, // #2141
1037
1048
  ],
1038
1049
  // present + typed even when empty — never a bare {} / missing key (#1182).
1039
1050
  selfDescribingEmpty: [
1040
1051
  { path: "soul", type: "object" }, { path: "memories", type: "array" },
1041
1052
  { path: "predicted", type: "array" }, { path: "teammateFindings", type: "array" },
1042
1053
  { path: "events", type: "array" }, { path: "sections", type: "object" },
1054
+ { path: "skills", type: "array" }, { path: "skillDiagnostics", type: "array" }, // #2141
1043
1055
  ],
1044
1056
  // #1200 — dedup by the SEMANTIC content key (excludes id/createdAt, which
1045
1057
  // vary across physical duplicate rows). See ToolInvariants.dedupSignature.
@@ -1053,14 +1065,18 @@ export const TOOLS = bindNativeTools({
1053
1065
  // structured charge gap; uncounted content does not fit under it.
1054
1066
  budgetCap: { estimate: "tokenEstimate", budget: "maxTokens", tolerance: 0.25 },
1055
1067
  // flair#1290 step 4 — the #1270 token-ledger identity, enforced:
1056
- // tokenEstimate ≈ scaffold + soul + memory + trust + events, two-sided
1068
+ // tokenEstimate ≈ scaffold + soul + memory + trust + events + skills
1069
+ // + skillDiagnostics, two-sided
1057
1070
  // (constants sized in bootstrap-token-ledger-1270.test.ts, which reads
1058
1071
  // them from HERE — one identity, one tolerance definition). The upper
1059
1072
  // bound is waived when the request opted into the prose mirror
1060
1073
  // (includeContext), which legitimately widens the gap by design.
1061
1074
  tokenDecomposition: {
1062
1075
  total: "tokenEstimate",
1063
- terms: ["scaffoldTokens", "soulTokens", "memoryTokens", "trustTokens", "eventsTokens"],
1076
+ terms: [
1077
+ "scaffoldTokens", "soulTokens", "memoryTokens", "trustTokens", "eventsTokens",
1078
+ "skillsTokens", "skillDiagnosticsTokens", // #2141
1079
+ ],
1064
1080
  perItemContainers: ["memories", "predicted", "teammateFindings"],
1065
1081
  perItemGap: 60,
1066
1082
  fixedSlack: 150,
@@ -1107,6 +1123,12 @@ export const TOOLS = bindNativeTools({
1107
1123
  containerRules: [
1108
1124
  { container: "events", requiredFields: ["id", "kind", "summary", "createdAt"] },
1109
1125
  { container: "memories", requiredFields: ["id", "content"], forbiddenFields: INTERNAL_MEMORY_FIELDS },
1126
+ // #2141 — a manifest entry names a skill; the procedure is fetched with skill_get.
1127
+ {
1128
+ container: "skills",
1129
+ requiredFields: ["name", "skillId", "scope", "priority", "source"],
1130
+ forbiddenFields: ["content", "trigger", "metadata"],
1131
+ },
1110
1132
  ],
1111
1133
  fullyResolved: true, // #1182 — never a spread pending Promise collapsing to {flairVersion}.
1112
1134
  },
@@ -4,6 +4,7 @@
4
4
  // runtime (`databases` / `Resource`, storage init) and can't run outside a live
5
5
  // Harper; this module has no Harper dependency, so
6
6
  // test/unit/memory-consolidate.test.ts exercises the real shipped code.
7
+ import { stripInlinePointerFields } from "./host-source-visibility.js";
7
8
  export function parseDuration(s) {
8
9
  const m = s.match(/^(\d+)([dhm])$/);
9
10
  if (!m)
@@ -30,7 +31,8 @@ export function parseDuration(s) {
30
31
  * freshly-created memory is never an archive candidate regardless of retrieval
31
32
  * count: archival only considers memories that have had a fair chance to be read.
32
33
  */
33
- export function evaluate(record, now, olderThanMs) {
34
+ export function evaluate(rawRecord, now, olderThanMs) {
35
+ const record = stripInlinePointerFields(rawRecord);
34
36
  const ageMs = record.createdAt ? now - new Date(record.createdAt).getTime() : 0;
35
37
  const count = record.retrievalCount ?? 0;
36
38
  const lastUse = record.lastRetrieved ?? record.createdAt;