@tpsdev-ai/flair 0.58.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 (46) hide show
  1. package/README.md +3 -2
  2. package/config.yaml +3 -0
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +42 -98
  5. package/dist/commands/agent.js +160 -2
  6. package/dist/commands/doctor.js +15 -23
  7. package/dist/commands/mcp.js +53 -22
  8. package/dist/lib/daemon-liveness.js +42 -0
  9. package/dist/lib/doctor-run.js +67 -0
  10. package/dist/lib/flair-agent-role.js +116 -0
  11. package/dist/lib/launchd-management.js +3 -2
  12. package/dist/lib/mcp-enable.js +667 -72
  13. package/dist/lib/process-start-time.js +32 -0
  14. package/dist/resources/Agent.js +27 -7
  15. package/dist/resources/AgentSeed.js +9 -0
  16. package/dist/resources/Federation.js +14 -2
  17. package/dist/resources/MemoryBootstrap.js +121 -29
  18. package/dist/resources/OrgSkillAssignment.js +209 -0
  19. package/dist/resources/XAA.js +40 -11
  20. package/dist/resources/agent-status-guard.js +63 -0
  21. package/dist/resources/auth-middleware.js +2 -1
  22. package/dist/resources/federation-classify.js +22 -0
  23. package/dist/resources/flair-agent-role-boot.js +26 -0
  24. package/dist/resources/health.js +10 -2
  25. package/dist/resources/key-lock.js +31 -0
  26. package/dist/resources/mcp-oauth.js +3 -6
  27. package/dist/resources/mcp-tools.js +22 -4
  28. package/dist/resources/multi-worker-guard.js +121 -0
  29. package/dist/resources/oauth-discovery.js +1 -0
  30. package/dist/resources/oauth-wellknown.js +8 -4
  31. package/dist/resources/record-types.js +16 -0
  32. package/dist/resources/replay-store.js +56 -9
  33. package/dist/resources/skill-manifest.js +181 -0
  34. package/dist/resources/skill-provenance.js +15 -10
  35. package/dist/src/lib/flair-agent-role.js +116 -0
  36. package/docs/access-control.md +667 -0
  37. package/docs/api-reference.md +6 -2
  38. package/docs/auth.md +4 -0
  39. package/docs/deepseek-harness.md +1 -1
  40. package/docs/integrations.md +1 -1
  41. package/docs/mcp-clients.md +5 -3
  42. package/docs/releasing.md +24 -24
  43. package/package.json +4 -3
  44. package/schemas/memory.graphql +31 -0
  45. package/schemas/oauth.graphql +8 -4
  46. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -5,6 +5,7 @@ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
6
  import { createRemoteJWKSet, jwtVerify } from "jose";
7
7
  import { stampOriginatorOnCreate } from "./originator-instance.js";
8
+ import { claimIdJagJti, ReplayStoreUnavailable } from "./replay-store.js";
8
9
  /**
9
10
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
10
11
  *
@@ -24,7 +25,25 @@ import { stampOriginatorOnCreate } from "./originator-instance.js";
24
25
  */
25
26
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
26
27
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
27
- const CLOCK_SKEW_MS = 30_000; // 30 seconds
28
+ export const CLOCK_SKEW_MS = 30_000; // 30 seconds
29
+ /**
30
+ * An assertion that carries a `jti` is refused unless its `exp` is at most this
31
+ * far ahead of now, plus CLOCK_SKEW_MS (flair#2073).
32
+ */
33
+ export const ID_JAG_MAX_VALIDITY_MS = 24 * 3600_000;
34
+ /**
35
+ * The longest an accepted assertion stays acceptable after its jti is recorded.
36
+ * jose compares exp with the current whole second, so it accepts an assertion
37
+ * only before exp + CLOCK_SKEW_MS + 1 s, and exp is at most
38
+ * ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS ahead when it is recorded.
39
+ */
40
+ export const ID_JAG_LONGEST_ACCEPTANCE_MS = ID_JAG_MAX_VALIDITY_MS + 2 * CLOCK_SKEW_MS + 1000;
41
+ /**
42
+ * Seconds a newly recorded jti row is kept: 25 h, longer than ID_JAG_LONGEST_ACCEPTANCE_MS.
43
+ * MUST equal `expiration:` on `type IdJagReplay` in schemas/oauth.graphql
44
+ * (both pinned by test/unit-isolated/xaa-jti-replay.test.ts).
45
+ */
46
+ export const ID_JAG_REPLAY_RETENTION_S = 90_000;
28
47
  // JWKS remote key set cache per issuer (jose handles caching internally)
29
48
  const jwksSetCache = new Map();
30
49
  function sha256(input) {
@@ -107,17 +126,21 @@ export async function validateIdJag(assertion, expectedAudience) {
107
126
  throw new Error(`domain required but no hd/tid claim present — consumer account rejected`);
108
127
  }
109
128
  }
110
- // Replay prevention (jti)
111
- if (payload.jti) {
112
- const existing = await databases.flair.IdJagReplay.get(payload.jti);
113
- if (existing)
129
+ // Replay prevention (jti): a jti claim, when present, must be a nonempty
130
+ // string, and is then recorded once per instance, under a per-key lock,
131
+ // before the grant has any effect. The record is kept
132
+ // ID_JAG_REPLAY_RETENTION_S, so the assertion's validity is bounded first.
133
+ if (payload.jti !== undefined) {
134
+ if (typeof payload.jti !== "string" || payload.jti === "")
135
+ throw new Error("jti claim must be a nonempty string");
136
+ if (typeof payload.exp !== "number" || payload.exp * 1000 > Date.now() + ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS) {
137
+ throw new Error(`an assertion with a jti must carry an exp at most ${ID_JAG_MAX_VALIDITY_MS / 3600_000} hours ahead`);
138
+ }
139
+ const claim = await claimIdJagJti(payload.jti, ID_JAG_LONGEST_ACCEPTANCE_MS);
140
+ if (claim === "replay")
114
141
  throw new Error("token replay detected");
115
- const now = Date.now();
116
- await databases.flair.IdJagReplay.put({
117
- id: payload.jti,
118
- expiresAt: futureISO(Math.max((payload.exp ?? 0) * 1000 - now + CLOCK_SKEW_MS, 300_000)),
119
- createdAt: nowISO(),
120
- });
142
+ if (claim !== "recorded")
143
+ throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
121
144
  }
122
145
  return { payload: payload, idpConfig };
123
146
  }
@@ -261,6 +284,12 @@ export async function handleJwtBearerGrant(data) {
261
284
  };
262
285
  }
263
286
  catch (err) {
287
+ if (err instanceof ReplayStoreUnavailable) {
288
+ return new Response(JSON.stringify({
289
+ error: "temporarily_unavailable",
290
+ error_description: "replay_store_unavailable",
291
+ }), { status: 503, headers: { "content-type": "application/json" } });
292
+ }
264
293
  return new Response(JSON.stringify({
265
294
  error: "invalid_grant",
266
295
  error_description: err.message,
@@ -0,0 +1,63 @@
1
+ /**
2
+ * agent-status-guard.ts — the `Agent.status` write rule for the Agent resource.
3
+ *
4
+ * `status` is the principal's LIFECYCLE state: any present value other than
5
+ * "active" means deactivated, and a missing or undefined `status` is treated as
6
+ * active (resources/agent-auth.ts's isPrincipalDeactivated). So a principal that
7
+ * may write its own `status` can deactivate itself. Liveness belongs on the
8
+ * Presence beacon, not on this column.
9
+ *
10
+ * resources/Agent.ts's PUT and PATCH admit a trusted internal call and an
11
+ * administrator, and refuse anonymous and any verdict kind the auth resolver
12
+ * does not define. A non-admin agent's PUT or PATCH whose body carries the
13
+ * `status` key is refused whole, on any row including its own, so the other
14
+ * fields in that request are not written either; without `status`, it goes on
15
+ * to Agent.ts's other per-record rules. A non-admin agent's POST (create) is
16
+ * refused earlier, at allowCreate(). (A federation peer's record is merged
17
+ * through the raw table, not this resource; resources/Federation.ts skips an
18
+ * inbound Agent record whose `status` differs from an existing local
19
+ * principal's stored value.)
20
+ *
21
+ * Deliberately dependency-free (no `harper`, no resource) so resources/Agent.ts
22
+ * and the unit lane decide this from one place.
23
+ */
24
+ /** The lifecycle field this module guards. */
25
+ export const AGENT_STATUS_FIELD = "status";
26
+ /**
27
+ * The feature's lifecycle rule applied to a value: a principal's effective
28
+ * `status` is its stored value, or "active" when it is missing or undefined
29
+ * (resources/agent-auth.ts's isPrincipalDeactivated applies the same rule to a
30
+ * principal). Federation's status comparison uses it on both sides
31
+ * (resources/federation-classify.ts).
32
+ */
33
+ export function effectiveAgentStatus(status) {
34
+ return status === undefined ? "active" : status;
35
+ }
36
+ /** The refusal text: names the field, the internal exception, and Presence. */
37
+ export const AGENT_STATUS_ADMIN_ONLY_ERROR = "forbidden: status is administrator-only (a trusted internal call is excepted); report liveness through Presence";
38
+ /** True iff a write body carries the `status` field. */
39
+ export function writeIncludesStatus(content) {
40
+ return content != null && typeof content === "object" && Object.hasOwn(content, AGENT_STATUS_FIELD);
41
+ }
42
+ export function admitPrincipalWrite(auth) {
43
+ if (auth == null || typeof auth !== "object")
44
+ return "deny";
45
+ if (auth.kind === "internal")
46
+ return "internal";
47
+ if (auth.kind === "agent")
48
+ return auth.isAdmin === true ? "admin" : "non-admin";
49
+ return "deny";
50
+ }
51
+ /**
52
+ * The 403 for a write whose body includes `status` from a caller who is not an
53
+ * administrator, or null when the caller is an administrator or the body has no
54
+ * `status`. resources/Agent.ts admits a trusted internal call without calling
55
+ * this helper.
56
+ */
57
+ export function statusWriteRefusal(content, callerIsAdmin) {
58
+ if (callerIsAdmin || !writeIncludesStatus(content))
59
+ return null;
60
+ return new Response(JSON.stringify({ error: AGENT_STATUS_ADMIN_ONLY_ERROR }), {
61
+ status: 403, headers: { "content-type": "application/json" },
62
+ });
63
+ }
@@ -6,6 +6,7 @@ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header }
6
6
  import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
7
7
  import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
8
8
  import { checkHttpRateLimit } from "./rate-limit.js";
9
+ import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
9
10
  import { stripUndeclaredMemoryAttributes, DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
10
11
  // --- Non-admin Memory read: ignore the caller's selection --------------------
11
12
  //
@@ -757,4 +758,4 @@ server.http(async (request, nextLayer) => {
757
758
  backfillEmbedding(memoryId).catch(() => { });
758
759
  }
759
760
  return response;
760
- }, { runFirst: true });
761
+ }, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });
@@ -5,6 +5,7 @@
5
5
  * spinning up Harper's database module. The same SkipReason names are used
6
6
  * in SyncLog.skippedReasons so operators can grep for them.
7
7
  */
8
+ import { effectiveAgentStatus } from "./agent-status-guard.js";
8
9
  /**
9
10
  * Static policy for every table FederationSync will merge.
10
11
  *
@@ -151,3 +152,24 @@ export function classifyRecord(record, peerRole, receiverInstanceId, local, know
151
152
  }
152
153
  return { action: "merge", originator };
153
154
  }
155
+ /**
156
+ * flair#2108: does this inbound Agent record's effective status differ from an
157
+ * existing local principal's effective stored status (a record with no `status`
158
+ * field counts as "active")? True only when the record is for
159
+ * the Agent table, a local row exists, and the two differ under the feature's
160
+ * lifecycle rule, which `effectiveAgentStatus` (resources/agent-status-guard.ts)
161
+ * applies to both sides: a missing or undefined `status` is "active".
162
+ * `updatedAt` is not compared, so a record older than the stored row, which
163
+ * would lose the last-write-wins merge, is also true. The federation path
164
+ * carries no verified administrator authority for the principal (the batch is
165
+ * signed, and a record signature may also be present; neither is an admin
166
+ * claim), so a true answer skips the whole record before the raw put.
167
+ */
168
+ export function inboundChangesExistingPrincipalStatus(record, local) {
169
+ if (record.table !== "Agent" || local == null)
170
+ return false;
171
+ const data = record.data;
172
+ if (!data || typeof data !== "object")
173
+ return false;
174
+ return effectiveAgentStatus(data.status) !== effectiveAgentStatus(local.status);
175
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * flair-agent-role-boot.ts — at server start, attempts to bring an existing
3
+ * `flair_agent` role to this release's grants (flair#2141 S1).
4
+ *
5
+ * `flair init` writes the role. Each worker runs `alignFlairAgentRole` once,
6
+ * through Harper's in-process operations API; it never creates the role. A
7
+ * failure is logged with the `[flair-agent-role]` marker and the server keeps
8
+ * serving.
9
+ *
10
+ * Plain module (no Resource export), loaded at boot like
11
+ * resources/migration-boot.ts.
12
+ */
13
+ import { server } from "harper";
14
+ import { alignFlairAgentRole } from "../src/lib/flair-agent-role.js";
15
+ export function scheduleFlairAgentRoleAlign(op) {
16
+ const run = op ?? ((body) => server.operation(body, { user: null }, false));
17
+ setImmediate(() => {
18
+ alignFlairAgentRole(run).then((outcome) => {
19
+ if (outcome === "updated")
20
+ console.log("[flair-agent-role] the flair_agent role was updated to this release's grants");
21
+ }, (err) => {
22
+ console.error("[flair-agent-role] the flair_agent role could not be checked or updated, so it may lack the grants for tables added since it was set; restart the server to retry", { err: err instanceof Error ? err.message : String(err) });
23
+ });
24
+ });
25
+ }
26
+ scheduleFlairAgentRoleAlign();
@@ -4,6 +4,7 @@ import { homedir, platform } from "node:os";
4
4
  import { join, dirname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
7
+ import { multiWorkerCondition, multiWorkerHealthField } from "./multi-worker-guard.js";
7
8
  import { resolveBuildInfo } from "./build-info.js";
8
9
  import { getMigrationStatusSnapshot } from "./migrations/status.js";
9
10
  import { resolveMigrationDataDirForRead } from "./migrations/data-dir.js";
@@ -119,9 +120,16 @@ export class Health extends Resource {
119
120
  version: build?.version ?? resolveVersion(),
120
121
  buildCommit: build?.commit ?? null,
121
122
  }));
122
- if (readiness.status !== 200) {
123
+ const multiWorker = multiWorkerHealthField(multiWorkerCondition());
124
+ let status = readiness.status;
125
+ if (multiWorker) {
126
+ body.ok = false;
127
+ body.multiWorker = multiWorker;
128
+ status = 503;
129
+ }
130
+ if (status !== 200) {
123
131
  return new Response(JSON.stringify(body), {
124
- status: readiness.status,
132
+ status,
125
133
  headers: { "content-type": "application/json" },
126
134
  });
127
135
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * key-lock.ts — run a function while holding one key of a Harper table's
3
+ * primary-store lock (`tryLock` / `unlock`: per key, shared by the threads of
4
+ * one Harper process; resources/replay-store.ts uses the same primitive).
5
+ * No Harper imports.
6
+ */
7
+ /**
8
+ * Try the lock up to `attempts` times, `waitMs` apart. Holding it, drop the
9
+ * thread's cached read snapshot (when the store has one) and run `fn`; the
10
+ * lock is released when `fn` settles. "busy": the lock stayed held; "unavailable":
11
+ * the store has no lock. `fn` does not run in either case.
12
+ */
13
+ export async function withKeyLock(store, key, fn, attempts, waitMs) {
14
+ const lock = store;
15
+ if (typeof lock?.tryLock !== "function" || typeof lock?.unlock !== "function")
16
+ return { kind: "unavailable" };
17
+ for (let attempt = 0; attempt < attempts; attempt++) {
18
+ if (lock.tryLock(key)) {
19
+ try {
20
+ lock.resetReadTxn?.();
21
+ return { kind: "done", value: await fn() };
22
+ }
23
+ finally {
24
+ lock.unlock(key);
25
+ }
26
+ }
27
+ if (attempt + 1 < attempts)
28
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
29
+ }
30
+ return { kind: "busy" };
31
+ }
@@ -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
  }
@@ -1013,11 +1013,15 @@ export const TOOLS = bindNativeTools({
1013
1013
  "memoriesTruncated", "teammateFindingsIncluded", "teammateFindingsTruncated",
1014
1014
  "teammateFindingsMatched", "context", "flairVersion",
1015
1015
  "eventWatermark", "eventsHasMore", "eventsRemaining",
1016
+ // flair#2141 S1b — the skills manifest, always present.
1017
+ "skills", "skillDiagnostics", "skillsTruncated", "skillDiagnosticsTruncated",
1016
1018
  // flair#1270 — the payload token LEDGER: every token-charged content
1017
1019
  // class has a counter, so tokenEstimate ≈ scaffoldTokens + soulTokens +
1018
- // memoryTokens + trustTokens + eventsTokens decomposes from the payload
1019
- // 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).
1020
1023
  "soulTokens", "memoryTokens", "trustTokens", "eventsTokens", "scaffoldTokens",
1024
+ "skillsTokens", "skillDiagnosticsTokens",
1021
1025
  ],
1022
1026
  fieldTypes: {
1023
1027
  agentId: "string", soul: "object", memories: "array", predicted: "array",
@@ -1029,6 +1033,8 @@ export const TOOLS = bindNativeTools({
1029
1033
  soulTokens: "number", memoryTokens: "number", trustTokens: "number",
1030
1034
  eventsTokens: "number", scaffoldTokens: "number",
1031
1035
  eventWatermark: "string", eventsHasMore: "boolean", eventsRemaining: "number",
1036
+ skills: "array", skillDiagnostics: "array", skillsTruncated: "number",
1037
+ skillDiagnosticsTruncated: "number", skillsTokens: "number", skillDiagnosticsTokens: "number",
1032
1038
  },
1033
1039
  invariants: {
1034
1040
  // count == delivered — the historical count/charge/deliver drift.
@@ -1038,12 +1044,14 @@ export const TOOLS = bindNativeTools({
1038
1044
  { count: "teammateFindingsIncluded", containers: ["teammateFindings"] }, // #1199
1039
1045
  { count: "sections.events", containers: ["events"] }, // #1206
1040
1046
  { count: "sections.soul", containers: ["soul"] }, // #1371
1047
+ { count: "sections.skills", containers: ["skills"] }, // #2141
1041
1048
  ],
1042
1049
  // present + typed even when empty — never a bare {} / missing key (#1182).
1043
1050
  selfDescribingEmpty: [
1044
1051
  { path: "soul", type: "object" }, { path: "memories", type: "array" },
1045
1052
  { path: "predicted", type: "array" }, { path: "teammateFindings", type: "array" },
1046
1053
  { path: "events", type: "array" }, { path: "sections", type: "object" },
1054
+ { path: "skills", type: "array" }, { path: "skillDiagnostics", type: "array" }, // #2141
1047
1055
  ],
1048
1056
  // #1200 — dedup by the SEMANTIC content key (excludes id/createdAt, which
1049
1057
  // vary across physical duplicate rows). See ToolInvariants.dedupSignature.
@@ -1057,14 +1065,18 @@ export const TOOLS = bindNativeTools({
1057
1065
  // structured charge gap; uncounted content does not fit under it.
1058
1066
  budgetCap: { estimate: "tokenEstimate", budget: "maxTokens", tolerance: 0.25 },
1059
1067
  // flair#1290 step 4 — the #1270 token-ledger identity, enforced:
1060
- // tokenEstimate ≈ scaffold + soul + memory + trust + events, two-sided
1068
+ // tokenEstimate ≈ scaffold + soul + memory + trust + events + skills
1069
+ // + skillDiagnostics, two-sided
1061
1070
  // (constants sized in bootstrap-token-ledger-1270.test.ts, which reads
1062
1071
  // them from HERE — one identity, one tolerance definition). The upper
1063
1072
  // bound is waived when the request opted into the prose mirror
1064
1073
  // (includeContext), which legitimately widens the gap by design.
1065
1074
  tokenDecomposition: {
1066
1075
  total: "tokenEstimate",
1067
- terms: ["scaffoldTokens", "soulTokens", "memoryTokens", "trustTokens", "eventsTokens"],
1076
+ terms: [
1077
+ "scaffoldTokens", "soulTokens", "memoryTokens", "trustTokens", "eventsTokens",
1078
+ "skillsTokens", "skillDiagnosticsTokens", // #2141
1079
+ ],
1068
1080
  perItemContainers: ["memories", "predicted", "teammateFindings"],
1069
1081
  perItemGap: 60,
1070
1082
  fixedSlack: 150,
@@ -1111,6 +1123,12 @@ export const TOOLS = bindNativeTools({
1111
1123
  containerRules: [
1112
1124
  { container: "events", requiredFields: ["id", "kind", "summary", "createdAt"] },
1113
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
+ },
1114
1132
  ],
1115
1133
  fullyResolved: true, // #1182 — never a spread pending Promise collapsing to {flairVersion}.
1116
1134
  },
@@ -0,0 +1,121 @@
1
+ import { server } from "harper";
2
+ import * as harper from "harper";
3
+ export const MULTI_WORKER_REFUSED_STATE = "multi-worker-unsupported";
4
+ export const MULTI_WORKER_ERROR_NAME = "multi_worker_unsupported";
5
+ export const MULTI_WORKER_REMEDY = "THREADS_COUNT=1";
6
+ export const MULTI_WORKER_UNSAFE_ENV = "FLAIR_MULTI_WORKER_UNSAFE";
7
+ export const MULTI_WORKER_GUARD_HTTP_NAME = "flair-multi-worker-guard";
8
+ export const FLAIR_AUTH_MIDDLEWARE_HTTP_NAME = "flair-auth-middleware";
9
+ export function decideMultiWorkerState(workerCount, optIn) {
10
+ if (workerCount === null)
11
+ return "refused";
12
+ if (!(workerCount > 1))
13
+ return "single-worker";
14
+ return optIn ? "unsafe-opt-in" : "refused";
15
+ }
16
+ export function multiWorkerUnsafeOptIn(env = process.env) {
17
+ return env[MULTI_WORKER_UNSAFE_ENV] === "1";
18
+ }
19
+ function workerCountLabel(condition) {
20
+ return condition.workerCount === null
21
+ ? "the worker count is unreadable"
22
+ : `worker count=${condition.workerCount}`;
23
+ }
24
+ export function multiWorkerHealthField(condition) {
25
+ if (condition.state === "single-worker")
26
+ return null;
27
+ return {
28
+ state: condition.state,
29
+ workerCount: condition.workerCount,
30
+ remedy: condition.state === "refused" ? MULTI_WORKER_REMEDY : `${MULTI_WORKER_UNSAFE_ENV}=1`,
31
+ };
32
+ }
33
+ export function multiWorkerBootLine(condition) {
34
+ if (condition.state === "single-worker")
35
+ return null;
36
+ const reason = "the multi-worker readiness work (flair#2052) is not complete — a per-worker embedding " +
37
+ "engine and BM25 index";
38
+ if (condition.state === "refused") {
39
+ return (`[multi-worker] refused: ${workerCountLabel(condition)}; flair does not serve on more than one ` +
40
+ `Harper worker thread because ${reason}. Set ${MULTI_WORKER_REMEDY} and restart.`);
41
+ }
42
+ return (`[multi-worker] ${MULTI_WORKER_UNSAFE_ENV}=1 with ${workerCountLabel(condition)}: serving with ` +
43
+ `the multi-worker readiness work outstanding — ${reason}. Set ${MULTI_WORKER_REMEDY} and unset ` +
44
+ `${MULTI_WORKER_UNSAFE_ENV}.`);
45
+ }
46
+ export function multiWorkerRefusalBody(condition) {
47
+ return {
48
+ error: MULTI_WORKER_ERROR_NAME,
49
+ workerCount: condition.workerCount,
50
+ remedy: MULTI_WORKER_REMEDY,
51
+ detail: "flair does not serve on more than one Harper worker thread until the multi-worker readiness work lands.",
52
+ };
53
+ }
54
+ export function isMultiWorkerExemptPath(pathname) {
55
+ return pathname === "/Health" || pathname === "/health";
56
+ }
57
+ export function multiWorkerRefusalResponse(condition, pathname) {
58
+ if (condition.state !== "refused" || isMultiWorkerExemptPath(pathname))
59
+ return null;
60
+ return new Response(JSON.stringify(multiWorkerRefusalBody(condition)), {
61
+ status: 503,
62
+ headers: { "content-type": "application/json" },
63
+ });
64
+ }
65
+ let cached = null;
66
+ function readPositiveInteger(read) {
67
+ let raw;
68
+ try {
69
+ raw = read();
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1)
75
+ return null;
76
+ return raw;
77
+ }
78
+ export function readWorkerCount() {
79
+ const perThread = readPositiveInteger(() => server?.workerCount);
80
+ if (perThread !== null)
81
+ return perThread;
82
+ return readPositiveInteger(() => (server?.config)?.threads?.count);
83
+ }
84
+ export function resolveMultiWorkerCondition() {
85
+ if (cached)
86
+ return cached;
87
+ const workerCount = readWorkerCount();
88
+ cached = { state: decideMultiWorkerState(workerCount, multiWorkerUnsafeOptIn()), workerCount };
89
+ return cached;
90
+ }
91
+ export function multiWorkerCondition() {
92
+ return resolveMultiWorkerCondition();
93
+ }
94
+ export function announceMultiWorkerCondition(condition = resolveMultiWorkerCondition()) {
95
+ const line = multiWorkerBootLine(condition);
96
+ if (!line)
97
+ return;
98
+ const l = harper.logger;
99
+ if (typeof l?.error === "function")
100
+ l.error(line);
101
+ else
102
+ console.error(line);
103
+ }
104
+ export async function multiWorkerRequestGuard(request, nextLayer) {
105
+ const pathname = typeof request?.pathname === "string" ? request.pathname : "/";
106
+ const refusal = multiWorkerRefusalResponse(multiWorkerCondition(), pathname);
107
+ if (refusal)
108
+ return refusal;
109
+ return nextLayer(request);
110
+ }
111
+ export function _resetMultiWorkerGuardForTests() {
112
+ cached = null;
113
+ }
114
+ if (typeof server?.http === "function") {
115
+ server.http(multiWorkerRequestGuard, {
116
+ runFirst: true,
117
+ name: MULTI_WORKER_GUARD_HTTP_NAME,
118
+ before: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME,
119
+ });
120
+ }
121
+ announceMultiWorkerCondition();
@@ -34,6 +34,7 @@ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
34
34
  export const PRM_PATH = "/.well-known/oauth-protected-resource";
35
35
  /** RFC 8414 §3 — Authorization Server Metadata well-known path. */
36
36
  export const AS_METADATA_PATH = "/.well-known/oauth-authorization-server";
37
+ export const JWKS_PATH = "/.well-known/jwks.json";
37
38
  /**
38
39
  * The public origin every URL in every discovery document derives from.
39
40
  *
@@ -88,8 +88,9 @@
88
88
  * and the plugin is declared), so the discovery loop closes.
89
89
  */
90
90
  import { server } from "harper";
91
- import { AS_METADATA_PATH, PRM_PATH, asMetadataPathMatches, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, makeWellKnownHandler, prmPathMatches, } from "./oauth-discovery.js";
91
+ import { AS_METADATA_PATH, JWKS_PATH, PRM_PATH, asMetadataPathMatches, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, makeWellKnownHandler, prmPathMatches, } from "./oauth-discovery.js";
92
92
  import { mcpOAuthEnabled } from "./mcp-oauth-flag.js";
93
+ import { MULTI_WORKER_GUARD_HTTP_NAME, multiWorkerRequestGuard } from "./multi-worker-guard.js";
93
94
  /**
94
95
  * Mount both documents. Called once at module load, and directly from tests.
95
96
  * Returns the urlPaths mounted so a caller can assert on them.
@@ -99,9 +100,12 @@ export function registerOAuthWellKnownRoutes(deps = {}) {
99
100
  if (typeof srv?.http !== "function")
100
101
  return [];
101
102
  const enabled = deps.isMcpOAuthEnabled ?? mcpOAuthEnabled;
102
- srv.http(makeWellKnownHandler(prmPathMatches, buildProtectedResourceMetadata, enabled), { urlPath: PRM_PATH });
103
- srv.http(makeWellKnownHandler(asMetadataPathMatches, buildAuthorizationServerMetadata, enabled), { urlPath: AS_METADATA_PATH });
104
- return [PRM_PATH, AS_METADATA_PATH];
103
+ srv.http(makeWellKnownHandler(prmPathMatches, buildProtectedResourceMetadata, enabled), { urlPath: PRM_PATH, after: MULTI_WORKER_GUARD_HTTP_NAME });
104
+ srv.http(makeWellKnownHandler(asMetadataPathMatches, buildAuthorizationServerMetadata, enabled), { urlPath: AS_METADATA_PATH, after: MULTI_WORKER_GUARD_HTTP_NAME });
105
+ for (const path of [PRM_PATH, AS_METADATA_PATH, JWKS_PATH]) {
106
+ srv.http(multiWorkerRequestGuard, { urlPath: path, runFirst: true, name: MULTI_WORKER_GUARD_HTTP_NAME });
107
+ }
108
+ return [PRM_PATH, AS_METADATA_PATH, JWKS_PATH];
105
109
  }
106
110
  // Registered at module load, like resources/auth-middleware.ts. The opt-out
107
111
  // exists only so a unit test can import this module under a partial `harper`
@@ -363,6 +363,22 @@ export const RECORD_TYPES = {
363
363
  // same reasoning, not by omission.
364
364
  federation: "excluded",
365
365
  },
366
+ // OrgSkillAssignment — flair#2141 S1. Org-scope skill assignments, readable
367
+ // by any verified agent. resources/OrgSkillAssignment.ts gates each write
368
+ // verb itself on the operator or internal source (no record-type-kit
369
+ // attribution idiom). No principal owns a row: `ownerField` names the
370
+ // server-stamped `writer`, which no read scope or attribution mode uses.
371
+ // Instance-local.
372
+ OrgSkillAssignment: {
373
+ table: "OrgSkillAssignment",
374
+ ownerField: "writer",
375
+ identity: "gated",
376
+ readScope: "none",
377
+ attribution: {},
378
+ provenance: false,
379
+ remEligible: false,
380
+ federation: "excluded",
381
+ },
366
382
  };
367
383
  // ─── Composite MCP tools (the second, and only other, reviewed chokepoint) ─
368
384
  //