@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
@@ -0,0 +1,103 @@
1
+ /**
2
+ * memory-declared-attributes.ts — the declared Memory attributes guard
3
+ * (flair#1940 slice 1 / A1' item 1). PURE: data-only imports, so it is unit-
4
+ * testable and callable from every Memory writer.
5
+ *
6
+ * WHY: Harper stores an attribute that is not DECLARED in the schema (the
7
+ * `schemas/memory.graphql` ~32-35 note records this for `embeddingModel`; the
8
+ * pinned harper re-confirms it). So removing a field from the Memory schema
9
+ * does NOT stop a raw writer from persisting it — a
10
+ * `Memory.put({..., hostSource})` would still land. The one-shot real-Harper
11
+ * probe is `test/repro/harper-undeclared-attr-probe.ts`; the unit test checks
12
+ * whitelist behavior and schema drift. The named application write paths remove
13
+ * pointer fields before persisting Memory rows. Federation filters its outbound
14
+ * and inbound Memory rows separately. Trusted raw table operations remain
15
+ * outside these resource guards.
16
+ *
17
+ * The pointer inputs (`hostSource`, `hostSourceScope`, `hostSourceVisibility`)
18
+ * are NOT declared Memory attributes after A1'. Only `Memory.post()` and
19
+ * `Memory.put()` accept pointer inputs; the `MemoryHostSource` resource refuses
20
+ * every REST write verb. They are consumed BEFORE the content reaches this
21
+ * guard, so the guard strips them like any other undeclared key.
22
+ *
23
+ * DECLARED_MEMORY_ATTRIBUTES is the schema's field list. A drift tripwire
24
+ * (test/unit/memory-declared-attributes.test.ts) parses `type Memory` out of
25
+ * schemas/memory.graphql and fails if this constant and the schema disagree,
26
+ * so the whitelist can never silently fall behind the schema.
27
+ */
28
+ import { DECLARED_MEMORY_ATTRIBUTES, MEMORY_ATTRIBUTES } from "../src/lib/memory-attributes.js";
29
+ export { DECLARED_MEMORY_ATTRIBUTES, UNDECLARED_ALLOWED } from "../src/lib/memory-attributes.js";
30
+ const DECLARED = new Set(DECLARED_MEMORY_ATTRIBUTES);
31
+ const ALLOWED = new Set(MEMORY_ATTRIBUTES);
32
+ /** True when `key` is a declared Memory attribute. */
33
+ export function isDeclaredMemoryAttribute(key) {
34
+ return DECLARED.has(key);
35
+ }
36
+ /**
37
+ * Drop every UNDECLARED attribute from a Memory write body, IN PLACE, and
38
+ * return the list of keys removed. A non-object body is returned untouched.
39
+ * `id` is always kept (Harper assigns it when absent; a supplied id is the
40
+ * caller's own key, never an undeclared field).
41
+ */
42
+ export function stripUndeclaredMemoryAttributes(content) {
43
+ if (!content || typeof content !== "object" || Array.isArray(content))
44
+ return [];
45
+ const obj = content;
46
+ const removed = [];
47
+ for (const key of Object.keys(obj)) {
48
+ if (!ALLOWED.has(key)) {
49
+ delete obj[key];
50
+ removed.push(key);
51
+ }
52
+ }
53
+ return removed;
54
+ }
55
+ /**
56
+ * flair#1940 A1-iv item 3 — the SERVER-STAMPED fields a client body may never
57
+ * set. The declared-attributes whitelist KEEPS these (they are declared/named),
58
+ * so a whitelist alone does not stop forgery: a client could PUT a
59
+ * `provenance` or an `instanceToken` that then reads as if the server stamped
60
+ * it. Memory's REST write paths remove `instanceToken` and `provenance` from the
61
+ * request body. `post()`/`put()` re-stamp `provenance` (via `buildProvenance`)
62
+ * and `instanceToken` after the strip; the other writers strip and preserve the
63
+ * stored value.
64
+ *
65
+ * `originatorInstanceId` is NOT in this set (flair#1965): its write rule is
66
+ * create-vs-update — a CREATE stamps the local id, an UPDATE keeps the stored
67
+ * value — so it cannot simply be stripped and re-stamped here. It is handled by
68
+ * resources/originator-instance.ts, called from every Memory writer
69
+ * (post/put/patch/reindex). Leaving it out of this set also keeps the
70
+ * federation merge (resources/Federation.ts), which calls
71
+ * stripServerStampedFields on the merged Memory row, from deleting the
72
+ * originator's value.
73
+ */
74
+ export const SERVER_STAMPED_MEMORY_FIELDS = Object.freeze([
75
+ "instanceToken",
76
+ "provenance",
77
+ ]);
78
+ const SERVER_STAMPED = new Set(SERVER_STAMPED_MEMORY_FIELDS);
79
+ /** Strip every server-stamped field from a write body, IN PLACE. Returns removed keys. */
80
+ export function stripServerStampedFields(content) {
81
+ if (!content || typeof content !== "object" || Array.isArray(content))
82
+ return [];
83
+ const obj = content;
84
+ const removed = [];
85
+ for (const key of Object.keys(obj)) {
86
+ if (SERVER_STAMPED.has(key)) {
87
+ delete obj[key];
88
+ removed.push(key);
89
+ }
90
+ }
91
+ return removed;
92
+ }
93
+ /**
94
+ * flair#1940 A1'' item 8 — the SAME declare-only whitelist applied to an
95
+ * INBOUND federated Memory row before it is merged and written. A dirty pushed
96
+ * row (a legacy direct-insert, or a raw writer that slipped a pointer field
97
+ * past the writers) must not carry a pointer attribute onto the merged Memory
98
+ * row; the named federation bookkeeping fields survive. Named seam so the
99
+ * inbound direction is testable (resources/Federation.ts calls this).
100
+ */
101
+ export function stripInboundMemoryRow(row) {
102
+ return stripUndeclaredMemoryAttributes(row);
103
+ }
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { stripInlinePointerFields } from "./host-source-visibility.js";
2
3
  export function computeContentHash(agentId, content) {
3
4
  return createHash("sha256")
4
5
  .update(`${agentId}${content}`)
@@ -8,7 +9,10 @@ export function computeContentHash(agentId, content) {
8
9
  export async function findExistingMemoryByContentHash(records, agentId, contentHash) {
9
10
  for await (const record of records) {
10
11
  if (record?.agentId === agentId && record?.contentHash === contentHash) {
11
- return record;
12
+ // flair#1940 A1' item 1: a row returned to a caller must never carry an
13
+ // inline pointer field — drop any raw writer's leftovers with the same
14
+ // helper the read projection uses.
15
+ return stripInlinePointerFields(record);
12
16
  }
13
17
  }
14
18
  return null;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * memory-host-source.ts — the MemoryHostSource table's non-resource helpers
3
+ * (flair#1940 slice 1 / A1'). The pointer lives in its OWN table keyed by
4
+ * memoryId. Supported writes store host pointers only in `MemoryHostSource`: a pointer
5
+ * reaches a non-admin reader only through the gated join. For non-admin `Memory.get`,
6
+ * `Memory.search`, and `SemanticSearch` results, the gated projection removes inline
7
+ * pointer fields and renders a pointer only from a bound `MemoryHostSource` row.
8
+ *
9
+ * This module holds:
10
+ * - the WRITE-BODY-ONLY pointer inputs and their extraction; The named
11
+ * application write paths remove pointer fields before persisting Memory
12
+ * rows. Federation filters its outbound and inbound Memory rows separately.
13
+ * Trusted raw table operations remain outside these resource guards (A1' item 1);
14
+ * - the pointer row builder (canonical hostSource + scopeAtWrite +
15
+ * server-stamped authorId/receivedAt) (A1' items 1, 3);
16
+ * - the ONE batched pointer read the gated join uses (A1' item 4: never one
17
+ * query per row);
18
+ * - the federation refusal predicate (A1' item 5); The outbound reader
19
+ * projects declared Memory attributes. The inbound merge removes undeclared
20
+ * attributes except the named bookkeeping fields (A1'' item 8) (f1-out/f1-in).
21
+ */
22
+ import { databases } from "harper";
23
+ import { validateHostSource } from "./host-source.js";
24
+ import { projectHostSource, stripInlinePointerFields } from "./host-source-visibility.js";
25
+ /** The table name, so callers and tests never re-type it as a literal. */
26
+ export const MEMORY_HOST_SOURCE_TABLE = "MemoryHostSource";
27
+ /** The write-body-only pointer inputs (A1' item 1). Only `Memory.post()` and
28
+ * `Memory.put()` accept pointer inputs; the `MemoryHostSource` resource refuses
29
+ * every REST write verb. `hostSource` is
30
+ * the pointer; `hostSourceScope` is the write-time opt-in; a
31
+ * `hostSourceVisibility` supplied by a client is a FORGERY of the server's
32
+ * write-time stamp and is dropped (never read). */
33
+ export const POINTER_INPUT_KEYS = Object.freeze(["hostSource", "hostSourceScope", "hostSourceVisibility"]);
34
+ /**
35
+ * Consume the pointer inputs out of a Memory write body, IN PLACE, so they can
36
+ * never be persisted on the Memory row (A1' item 1). Returns what was found.
37
+ */
38
+ export function extractPointerInputs(content) {
39
+ const out = { hostSource: undefined, hostSourceScope: undefined, forgedVisibility: false };
40
+ if (!content || typeof content !== "object" || Array.isArray(content))
41
+ return out;
42
+ const obj = content;
43
+ out.hostSource = obj.hostSource;
44
+ out.hostSourceScope = obj.hostSourceScope;
45
+ out.forgedVisibility = obj.hostSourceVisibility !== undefined && obj.hostSourceVisibility !== null;
46
+ for (const key of POINTER_INPUT_KEYS)
47
+ delete obj[key];
48
+ return out;
49
+ }
50
+ /** Build the pointer row to persist alongside a Memory row. `scopeAtWrite` is
51
+ * the record's visibility at write when the write opted in with
52
+ * `hostSourceScope: "record"`, else null (author-only). `authorId`,
53
+ * `memoryInstanceToken` and `receivedAt` are SERVER-stamped (A1' item 3,
54
+ * A1-iv item 1) — never taken from the body. */
55
+ export function buildPointerRow(args) {
56
+ return {
57
+ memoryId: args.memoryId,
58
+ hostSource: args.canonical,
59
+ scopeAtWrite: args.scopeAtWrite ?? null,
60
+ authorId: args.authorId,
61
+ memoryInstanceToken: args.memoryInstanceToken ?? null,
62
+ receivedAt: args.receivedAt,
63
+ };
64
+ }
65
+ function pointerTable() {
66
+ return databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
67
+ }
68
+ /**
69
+ * flair#1940 A1'' item 6 (adjudication B, hardened in round 5/adjudication 0e)
70
+ * — is an incoming hostSource an ECHO of the STORED pointer? Preservation (do
71
+ * not replace the stored row) is a NARROW, unforgeable case:
72
+ * - the current writer MUST be the stored pointer row's `authorId` — a
73
+ * different writer echoing the value must not keep another agent's
74
+ * pointer; and
75
+ * - the incoming value must match the stored canonical EXACTLY, full URL
76
+ * included. Matching after DROPPING the query and fragment was forgeable:
77
+ * a value with a DIFFERENT query rendered identically and was wrongly
78
+ * treated as an echo, so a real change was masked. A different query is a
79
+ * new value, not an echo.
80
+ * (A rendered read strips the URL, so a client that wants the stored pointer
81
+ * kept echoes the stored value itself, not the stripped render.)
82
+ */
83
+ export function isPointerEchoOf(input, storedPointer, writerAuthorId) {
84
+ if (!storedPointer || typeof storedPointer.hostSource !== "string")
85
+ return false;
86
+ const author = typeof storedPointer.authorId === "string" && storedPointer.authorId.length > 0 ? storedPointer.authorId : null;
87
+ if (author === null || writerAuthorId == null || author !== writerAuthorId)
88
+ return false;
89
+ const incoming = validateHostSource(input);
90
+ if (!incoming.ok)
91
+ return false;
92
+ return incoming.canonical === storedPointer.hostSource;
93
+ }
94
+ /**
95
+ * Read the pointer rows for a WHOLE result set in ONE batched query (A1'
96
+ * item 4). Empty input issues no query. Returns memoryId -> row.
97
+ */
98
+ export async function loadPointerRows(ids) {
99
+ const wanted = [...new Set(ids.filter((id) => typeof id === "string" && id.length > 0))];
100
+ const map = new Map();
101
+ if (wanted.length === 0)
102
+ return map;
103
+ const table = pointerTable();
104
+ if (!table?.search)
105
+ return map;
106
+ // Harper refuses an `or` with fewer than two conditions, so a single id uses
107
+ // a plain equals condition and a set uses an `or`. Either way it is ONE call.
108
+ const query = wanted.length === 1
109
+ ? { conditions: [{ attribute: "memoryId", comparator: "equals", value: wanted[0] }] }
110
+ : { operator: "or", conditions: wanted.map((id) => ({ attribute: "memoryId", comparator: "equals", value: id })) };
111
+ const result = table.search(query);
112
+ for await (const row of result) {
113
+ if (row && typeof row.memoryId === "string")
114
+ map.set(row.memoryId, row);
115
+ }
116
+ return map;
117
+ }
118
+ /**
119
+ * flair#1940 A1-iv item 2 — the ONE reader helper. `Memory.get()`,
120
+ * `Memory.search()` and `SemanticSearch` render pointers through the pointer
121
+ * helper. Other Memory projections, bootstrap included, do not render pointers
122
+ * in this slice. It fetches the pointer rows for the WHOLE result set in ONE
123
+ * batched query and applies the join, so no reader can forget the join and no
124
+ * module needs to touch the MemoryHostSource table itself. `readerAgentId` is
125
+ * the non-admin reader; an admin/operator read is the named exception (see
126
+ * MemoryHostSource.ts).
127
+ *
128
+ * What the join receives differs by reader path, and both carry the binding
129
+ * fields it reads (`id`, `agentId`, `instanceToken`, `archived`,
130
+ * `visibility`). For a non-admin `Memory.get`/`Memory.search`, the join runs
131
+ * on the FULL stored row, not on whatever the caller asked for: those reads
132
+ * ignore the caller's `select`/`property` — the auth middleware drops the
133
+ * selection from a REST request URL before Harper parses it, and the direct
134
+ * contextual read drops it before the base read. `SemanticSearch` instead
135
+ * hands the join its server-owned retrieval projection (`DEFAULT_SELECT`,
136
+ * optionally widened with `provenance`/`metadata`/`trigger`), which is fixed
137
+ * server-side and not caller-shaped either; the binding fields are in that
138
+ * projection as well as in the full row. An inline pointer field on the Memory
139
+ * row is removed (or replaced by the gated rendering) before the projected row
140
+ * is returned, so no inline pointer field reaches a non-admin reader.
141
+ */
142
+ export async function projectRowsThroughPointers(rows, readerAgentId) {
143
+ const ids = rows.map((r) => r?.id).filter((id) => typeof id === "string" && id.length > 0);
144
+ const pointers = await loadPointerRows(ids);
145
+ return rows.map((row) => {
146
+ const id = row?.id;
147
+ return typeof id === "string" ? projectHostSource(row, readerAgentId, pointers.get(id) ?? null) : stripInlinePointerFields(row);
148
+ });
149
+ }
150
+ /** Read ONE stored pointer row (the write path's echo check). Kept here so the
151
+ * MemoryHostSource table is touched ONLY by this module. */
152
+ export async function loadStoredPointer(memoryId) {
153
+ return (await loadPointerRows([memoryId])).get(memoryId) ?? null;
154
+ }
155
+ /** The Memory attributes that would carry a pointer into an inbound federated
156
+ * row (A1' item 5). A record carrying any of these is refused, not merged. */
157
+ const FEDERATION_POINTER_FIELDS = ["hostSource", "hostSourceScope", "hostSourceVisibility"];
158
+ /** True when an inbound federated record's data carries a pointer field. */
159
+ export function inboundCarriesPointer(data) {
160
+ if (!data || typeof data !== "object")
161
+ return false;
162
+ return FEDERATION_POINTER_FIELDS.some((f) => data[f] !== undefined);
163
+ }
@@ -28,6 +28,7 @@
28
28
  * re-reading the row itself (invariant IV: state lives IN the data).
29
29
  */
30
30
  import { databases } from "harper";
31
+ import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
31
32
  export const SYNTHETIC_MIGRATION_ID = "synthetic-ci-schema-stamp";
32
33
  export const RESERVED_TEST_AGENT_ID = "__flair_migration_synthetic_test_agent__";
33
34
  export const SYNTHETIC_TARGET_MARKER = `${SYNTHETIC_MIGRATION_ID}-done`;
@@ -84,7 +85,9 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
84
85
  continue;
85
86
  if (existing.source === SYNTHETIC_TARGET_MARKER)
86
87
  continue; // already stamped — idempotent skip
87
- await table.put({ ...existing, source: SYNTHETIC_TARGET_MARKER });
88
+ const synthRow = { ...existing, source: SYNTHETIC_TARGET_MARKER };
89
+ stripUndeclaredMemoryAttributes(synthRow);
90
+ await table.put(synthRow);
88
91
  touchedIds.push(id);
89
92
  }
90
93
  return { processed: touchedIds.length, touchedIds };
@@ -134,6 +134,7 @@
134
134
  * omitting it.
135
135
  */
136
136
  import { databases } from "harper";
137
+ import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
137
138
  function defaultMemoryTable() {
138
139
  return databases.flair.Memory;
139
140
  }
@@ -223,7 +224,9 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
223
224
  if (derived !== "private" && derived !== "shared") {
224
225
  throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
225
226
  }
226
- await table.put({ ...existing, visibility: derived });
227
+ const backfillRow = { ...existing, visibility: derived };
228
+ stripUndeclaredMemoryAttributes(backfillRow);
229
+ await table.put(backfillRow);
227
230
  touchedIds.push(id);
228
231
  }
229
232
  return { processed: touchedIds.length, touchedIds };
@@ -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`