@tpsdev-ai/flair 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -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/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -2,8 +2,10 @@ import { databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
4
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
5
- import { localInstanceId } from "./instance-identity.js";
6
- import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
5
+ import { applyOriginatorInstanceId, resolveStoredRow } from "./originator-instance.js";
6
+ import { buildProvenance, makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
7
+ import { stripServerStampedFields } from "./memory-declared-attributes.js";
8
+ import { isSemanticPatch, RELATIONSHIP_SEMANTIC_FIELDS } from "./provenance.js";
7
9
  import { RECORD_TYPES } from "./record-types.js";
8
10
  // Parameterized from RECORD_TYPES.Relationship (record-types slice 2,
9
11
  // flair#520) rather than a hand-typed "owner-only" literal — the registry is
@@ -13,6 +15,7 @@ import { RECORD_TYPES } from "./record-types.js";
13
15
  // `.ownerField` against RECORD_TYPES.Relationship — not for any other
14
16
  // runtime consumer.
15
17
  export const relationshipReadScope = makeReadScope(RECORD_TYPES.Relationship.readScope, RECORD_TYPES.Relationship.ownerField);
18
+ const relationshipScopedSearch = makeScopedSearch(relationshipReadScope);
16
19
  const relationshipByIdReadGate = makeByIdReadGate(relationshipReadScope);
17
20
  // See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
18
21
  // prototype method below, never a class-field assignment — Harper's
@@ -75,16 +78,7 @@ export class Relationship extends databases.flair.Relationship {
75
78
  if (gate.kind === "unfiltered")
76
79
  return super.search(query);
77
80
  // Non-admin agent: scope to own relationships.
78
- const scope = await relationshipReadScope(gate.agentId);
79
- const agentCondition = scope.condition;
80
- if (!query?.conditions) {
81
- return super.search({ conditions: [agentCondition], ...(query || {}) });
82
- }
83
- return super.search({
84
- ...query,
85
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
86
- operator: "and",
87
- });
81
+ return relationshipScopedSearch(gate.agentId, query, (q) => super.search(q));
88
82
  }
89
83
  /**
90
84
  * ─── Auth reconcile (relationship-write-path, folded K&S refinement) ──────
@@ -127,89 +121,93 @@ export class Relationship extends databases.flair.Relationship {
127
121
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
128
122
  if (denial)
129
123
  return denial;
124
+ // flair#1960 r2: PATCH was the one Relationship writer that never touched
125
+ // `provenance`. The schema declares the field writable, so a caller could
126
+ // PATCH a forged `verified.agentId`/`verified.timestamp` straight onto the
127
+ // row, and stripping alone would let a stored value ride through. Mirror the
128
+ // Memory/put() contract: strip any body-supplied server-stamped field (so a
129
+ // body can never SET a `verified.*` field) and, when the patch changes the
130
+ // relationship's semantic identity (subject/predicate/object), re-stamp
131
+ // provenance from the resolved auth and ONE server clock read. A
132
+ // metadata-only patch (confidence/source/validTo) keeps the stored,
133
+ // previously-stamped blob. Claim inputs are captured before the guard so a
134
+ // `claimed.model`/`claimed.client` on the body is folded in like put().
135
+ const claimInputs = { model: content?.model, claimedClient: content?.claimedClient };
136
+ // flair#718 authorship-provenance — `claimedClient` is a WRITE-BODY-ONLY
137
+ // passthrough, already folded into `provenance.claimed.client` by
138
+ // buildProvenance (below, on a semantic PATCH). Delete it before delegating
139
+ // so it is NEVER persisted as a top-level row field — the SAME contract as
140
+ // put(), which deletes it before the table write. Without this the PATCH
141
+ // body's `claimedClient` rode through `super.patch()` onto the row.
142
+ delete content.claimedClient;
143
+ stripServerStampedFields(content);
144
+ // flair#1960 r3 + flair#1965 r2/r3: resolve the stored row ONCE (the shared
145
+ // resolveStoredRow), by the URL-BOUND target id — refusing a body `id` that
146
+ // disagrees with the address and refusing a lookup that FAILS (never read as
147
+ // "no stored row"). This ONE resolved row drives BOTH rule sets: the
148
+ // semantic-PATCH provenance decision below AND the originatorInstanceId
149
+ // create/update rule. The previous `.catch(() => null)` turned a read ERROR
150
+ // into "no stored row"; isSemanticPatch returns false for `null`, so the
151
+ // patch fell through to `super.patch()` as a METADATA-ONLY write and kept a
152
+ // legacy stored blob — including a caller-chosen `verified.timestamp` — in
153
+ // place. A read error is not a missing row: without the stored record we
154
+ // cannot tell a semantic PATCH from a metadata-only one, so fail closed and
155
+ // refuse rather than degrade to a blob-preserving decision.
156
+ const resolvedStored = await resolveStoredRow(this, "Relationship", content, () => super.get());
157
+ if (resolvedStored.denial)
158
+ return resolvedStored.denial;
159
+ const existing = resolvedStored.row;
160
+ if (isSemanticPatch(content, existing, RELATIONSHIP_SEMANTIC_FIELDS)) {
161
+ const auth = await resolveAgentAuth(this.getContext?.());
162
+ content.provenance = buildProvenance(auth, content.createdAt ?? existing?.createdAt, claimInputs);
163
+ }
164
+ // flair#1965 r2: an EXISTING row keeps its stored originatorInstanceId (a
165
+ // body value is dropped); a PATCH whose URL target has no stored row is a
166
+ // CREATE when it reaches the table and must stamp the local id (Harper's
167
+ // patch path does not require an existing row; only an administrator's or
168
+ // a trusted internal PATCH gets that far — resources/table-patch-policy.ts
169
+ // refuses the rest). The row is resolved by the URL-BOUND target id, never a
170
+ // body `id`. See resources/originator-instance.ts.
171
+ await applyOriginatorInstanceId(content, existing);
130
172
  return super.patch(content, query);
131
173
  }
174
+ /**
175
+ * POST (a collection create). Prepares the body with the same rules as put()
176
+ * before the row is created. For a verified non-admin agent, the owner is that
177
+ * agent (a body that names another agent is refused); an administrator or a
178
+ * trusted internal caller keeps the owner it supplies, and must supply one, as
179
+ * in put(). The preparation can refuse the write (401, 403, 429 or 400); a
180
+ * body that passes it is normalized, gets provenance built server-side, and
181
+ * has `originatorInstanceId` stamped as a create. A create that is otherwise
182
+ * admitted, valid and within the rate limit is refused with 409 when its id
183
+ * already exists, so a POST never updates a row.
184
+ */
185
+ async post(content, query) {
186
+ const denial = await prepareRelationshipWrite(this, content, RECORD_TYPES.Relationship.attribution.post);
187
+ if (denial)
188
+ return denial;
189
+ await applyOriginatorInstanceId(content, null);
190
+ return super.post(content, query);
191
+ }
132
192
  async put(content) {
133
193
  const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
134
194
  if (__ownerDenial)
135
195
  return __ownerDenial;
136
- const ctx = this.getContext?.();
137
- const auth = await resolveAgentAuth(ctx);
138
- if (auth.kind === "anonymous") {
139
- return UNAUTH();
140
- }
141
- // No-forge attribution — mode/field drawn from RECORD_TYPES.Relationship
142
- // (record-types slice 2, flair#520) rather than a hand-typed literal.
143
- // "stamp-strict" (see record-type-kit.ts's stampAttribution doc): reject
144
- // a PRESENT, mismatched agentId, else unconditionally stamp with the
145
- // verified identity. Admin/internal: content.agentId left as provided
146
- // (unfiltered) — see doc above.
147
- const attr = stampAttribution(auth, content, RECORD_TYPES.Relationship.ownerField, RECORD_TYPES.Relationship.attribution.put, "cannot write a relationship owned by another agent");
148
- if (attr.denied)
149
- return attr.denied;
150
- if (!content.agentId || typeof content.agentId !== "string") {
151
- return new Response(JSON.stringify({ error: "agentId is required" }), {
152
- status: 400, headers: { "content-type": "application/json" },
153
- });
154
- }
155
- // Rate limit keyed on the RESOLVED agentId (never a client-supplied one)
156
- // — matches Memory.post()'s intent, extended to cover every
157
- // resolveAgentAuth path (credentialed super_user, verifyAgentRequest
158
- // fallback), not just the gate's own `tpsAgent` annotation. Internal
159
- // calls have no per-agent identity to key on and are trusted, so they're
160
- // exempt — same as Memory.post()'s `if (authenticatedAgent)` guard.
161
- if (auth.kind === "agent") {
162
- const rl = checkRateLimit(auth.agentId);
163
- if (!rl.allowed)
164
- return rateLimitResponse(rl.retryAfterMs, "relationship");
165
- }
166
- // Validate required fields
167
- if (!content.subject || typeof content.subject !== "string") {
168
- return new Response(JSON.stringify({ error: "subject is required (string)" }), {
169
- status: 400, headers: { "content-type": "application/json" },
170
- });
171
- }
172
- if (!content.predicate || typeof content.predicate !== "string") {
173
- return new Response(JSON.stringify({ error: "predicate is required (string)" }), {
174
- status: 400, headers: { "content-type": "application/json" },
175
- });
176
- }
177
- if (!content.object || typeof content.object !== "string") {
178
- return new Response(JSON.stringify({ error: "object is required (string)" }), {
179
- status: 400, headers: { "content-type": "application/json" },
180
- });
181
- }
182
- // Normalize — lowercasing is load-bearing: MemoryBootstrap.ts's attention
183
- // read matches lowercased predicted subjects against subject/object.
184
- const now = new Date().toISOString();
185
- content.subject = content.subject.toLowerCase();
186
- content.predicate = content.predicate.toLowerCase();
187
- content.object = content.object.toLowerCase();
188
- content.createdAt = content.createdAt || now;
189
- content.updatedAt = now;
190
- content.validFrom = content.validFrom || now;
191
- // validTo left as null/undefined for active relationships
192
- content.confidence = content.confidence ?? 1.0;
193
- // Write-time provenance stamp (relationship-write-path, folded K&S
194
- // refinement) — reuses Memory's buildProvenance EXACTLY (./provenance.ts),
195
- // same `{v, verified, claimed?}` shape, no Relationship-specific format.
196
- // Additive/nullable on the schema side (schemas/memory.graphql) — a
197
- // pre-existing row with no provenance field reads back `undefined`,
198
- // unchanged behavior (migration-equivalence gate).
199
- content.provenance = buildProvenance(auth, content.createdAt, content);
200
- // flair#718 authorship-provenance — same contract as resources/Memory.ts's
201
- // post()/put(): `claimedClient` is a write-body-only passthrough, already
202
- // folded into `provenance.claimed.client` above. Strip it so it is NEVER
203
- // persisted as a row field.
204
- delete content.claimedClient;
205
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
206
- // 1) — see resources/Memory.ts's stampOriginatorInstanceId doc for the
207
- // full contract. No-op if already set (never fires for a genuine local
208
- // write; a federation-synced record never reaches this method — the
209
- // merge path writes via the raw table object, bypassing this class).
210
- if (content.originatorInstanceId == null) {
211
- content.originatorInstanceId = await localInstanceId();
212
- }
196
+ const denial = await prepareRelationshipWrite(this, content, RECORD_TYPES.Relationship.attribution.put);
197
+ if (denial)
198
+ return denial;
199
+ // Write-time originatorInstanceId (federation-edge-hardening slice 1): a
200
+ // CREATE (no stored row) stamps this instance's own id, ignoring any body
201
+ // value; an UPDATE keeps the STORED value — a body value neither replaces
202
+ // nor clears it. post() stamps its create itself; put() carries both. See
203
+ // resources/originator-instance.ts for the full contract (the federation
204
+ // merge is the raw table writer and never takes a request-body field).
205
+ // The row is resolved by the URL-BOUND target id, never a body `id` (Harper
206
+ // writes to the URL target); a mismatch or a failed read refuses the write.
207
+ const resolvedOriginRow = await resolveStoredRow(this, "Relationship", content, () => super.get());
208
+ if (resolvedOriginRow.denial)
209
+ return resolvedOriginRow.denial;
210
+ await applyOriginatorInstanceId(content, resolvedOriginRow.row);
213
211
  return super.put(content);
214
212
  }
215
213
  /**
@@ -241,3 +239,86 @@ export class Relationship extends databases.flair.Relationship {
241
239
  return super.delete(_);
242
240
  }
243
241
  }
242
+ /**
243
+ * The write preparation Relationship's post() and put() share, in order:
244
+ * resolve the caller (an anonymous verdict is refused with 401); apply the
245
+ * owner attribution for `mode` (a verified non-admin agent's own id is stamped;
246
+ * a body naming another agent is refused with 403); require an owner (400);
247
+ * rate-limit an agent caller (429); validate the triple (400); then normalize
248
+ * it and build provenance server-side. Returns the first refusal, or null when
249
+ * the body is ready to write.
250
+ * `originatorInstanceId` is the caller's to apply: a create stamp for post(),
251
+ * the stored-row rule for put().
252
+ */
253
+ async function prepareRelationshipWrite(resource, content, mode) {
254
+ const ctx = resource.getContext?.();
255
+ const auth = await resolveAgentAuth(ctx);
256
+ if (auth.kind === "anonymous") {
257
+ return UNAUTH();
258
+ }
259
+ // No-forge attribution — mode/field drawn from RECORD_TYPES.Relationship
260
+ // (record-types slice 2, flair#520) rather than a hand-typed literal.
261
+ // "stamp-strict" (see record-type-kit.ts's stampAttribution doc): reject
262
+ // a PRESENT, mismatched agentId, else unconditionally stamp with the
263
+ // verified identity. Admin/internal: content.agentId left as provided
264
+ // (unfiltered) — see the auth-reconcile doc on the Relationship class.
265
+ const attr = stampAttribution(auth, content, RECORD_TYPES.Relationship.ownerField, mode, "cannot write a relationship owned by another agent");
266
+ if (attr.denied)
267
+ return attr.denied;
268
+ if (!content.agentId || typeof content.agentId !== "string") {
269
+ return new Response(JSON.stringify({ error: "agentId is required" }), {
270
+ status: 400, headers: { "content-type": "application/json" },
271
+ });
272
+ }
273
+ // Rate limit keyed on the RESOLVED agentId (never a client-supplied one)
274
+ // — matches Memory.post()'s intent, extended to cover every
275
+ // resolveAgentAuth path (credentialed super_user, verifyAgentRequest
276
+ // fallback), not just the gate's own `tpsAgent` annotation. Internal
277
+ // calls have no per-agent identity to key on and are trusted, so they're
278
+ // exempt — same as Memory.post()'s `if (authenticatedAgent)` guard.
279
+ if (auth.kind === "agent") {
280
+ const rl = checkRateLimit(auth.agentId);
281
+ if (!rl.allowed)
282
+ return rateLimitResponse(rl.retryAfterMs, "relationship");
283
+ }
284
+ // Validate required fields
285
+ if (!content.subject || typeof content.subject !== "string") {
286
+ return new Response(JSON.stringify({ error: "subject is required (string)" }), {
287
+ status: 400, headers: { "content-type": "application/json" },
288
+ });
289
+ }
290
+ if (!content.predicate || typeof content.predicate !== "string") {
291
+ return new Response(JSON.stringify({ error: "predicate is required (string)" }), {
292
+ status: 400, headers: { "content-type": "application/json" },
293
+ });
294
+ }
295
+ if (!content.object || typeof content.object !== "string") {
296
+ return new Response(JSON.stringify({ error: "object is required (string)" }), {
297
+ status: 400, headers: { "content-type": "application/json" },
298
+ });
299
+ }
300
+ // Normalize — lowercasing is load-bearing: MemoryBootstrap.ts's attention
301
+ // read matches lowercased predicted subjects against subject/object.
302
+ const now = new Date().toISOString();
303
+ content.subject = content.subject.toLowerCase();
304
+ content.predicate = content.predicate.toLowerCase();
305
+ content.object = content.object.toLowerCase();
306
+ content.createdAt = content.createdAt || now;
307
+ content.updatedAt = now;
308
+ content.validFrom = content.validFrom || now;
309
+ // validTo left as null/undefined for active relationships
310
+ content.confidence = content.confidence ?? 1.0;
311
+ // Write-time provenance stamp (relationship-write-path, folded K&S
312
+ // refinement) — reuses Memory's buildProvenance EXACTLY (./provenance.ts),
313
+ // same `{v, verified, claimed?}` shape, no Relationship-specific format.
314
+ // Additive/nullable on the schema side (schemas/memory.graphql) — a
315
+ // pre-existing row with no provenance field reads back `undefined`,
316
+ // unchanged behavior (migration-equivalence gate).
317
+ content.provenance = buildProvenance(auth, content.createdAt, content);
318
+ // flair#718 authorship-provenance — same contract as resources/Memory.ts's
319
+ // post()/put(): `claimedClient` is a write-body-only passthrough, already
320
+ // folded into `provenance.claimed.client` above. Strip it so it is NEVER
321
+ // persisted as a row field.
322
+ delete content.claimedClient;
323
+ return null;
324
+ }
@@ -11,7 +11,7 @@ import { resolveReadScope } from "./memory-read-scope.js";
11
11
  // of 2026-07-08 (see ./bm25.ts's hybridEnabled() doc); set
12
12
  // FLAIR_HYBRID_RETRIEVAL=false to revert to the legacy HNSW + +0.05
13
13
  // keyword-bump path, byte-identical to the original pre-hybrid behavior.
14
- import { hybridEnabled } from "./bm25.js";
14
+ import { retrievalMode } from "./bm25.js";
15
15
  // The actual HNSW/BM25 retrieval + post-retrieval filtering (temporal/
16
16
  // supersede/isAllowed) now lives in the pure, side-effect-free
17
17
  // retrieveCandidates() core (flair-bootstrap-scale-fix, Kern-approved
@@ -19,6 +19,7 @@ import { hybridEnabled } from "./bm25.js";
19
19
  // tripping this file's rate-limit/hit-tracking side effects. See
20
20
  // resources/semantic-retrieval-core.ts's module doc for the full boundary.
21
21
  import { retrieveCandidates, DEFAULT_SELECT } from "./semantic-retrieval-core.js";
22
+ import { projectRowsThroughPointers } from "./memory-host-source.js";
22
23
  import { attachTrust } from "./trust-block.js";
23
24
  import { bestSemanticSimilarity, evaluateAbstention } from "./abstention.js";
24
25
  // Candidate multiplier: fetch more candidates than needed from the HNSW index
@@ -28,9 +29,9 @@ export class SemanticSearch extends Resource {
28
29
  // Self-authorize via the Ed25519 agent verify instead of relying on the auth
29
30
  // gate's admin super_user elevation (removed in the auth reshape). Any
30
31
  // cryptographically-verified agent may search; per-agent RESULT scoping is
31
- // enforced in post() below (an agent only sees its own memories, any
32
- // visibility, plus granted owners' SHARED memories — never their private
33
- // ones). Without this, Harper's default denies the POST for the
32
+ // enforced in post() below (an agent sees its own records at any visibility
33
+ // plus every other agent's non-private records; grants are not consulted on
34
+ // reads — resolveReadScope()). Without this, Harper's default denies the POST for the
34
35
  // least-privilege flair_agent role (AccessViolation 403).
35
36
  async allowCreate() {
36
37
  return allowVerified(this.getContext?.());
@@ -100,24 +101,33 @@ export class SemanticSearch extends Resource {
100
101
  error: "forbidden: agentId must match authenticated agent",
101
102
  }), { status: 403, headers: { "Content-Type": "application/json" } });
102
103
  }
103
- // Scope: non-admin agent → own (+ granted). Admin agent or trusted internal
104
- // call (no request) → honor the body-supplied agentId.
104
+ // Scope: non-admin agent → its own records at any visibility plus every
105
+ // other agent's non-private records (grants are not consulted on reads —
106
+ // resolveReadScope()). Admin agent or trusted internal call (no request) →
107
+ // honor the body-supplied agentId.
105
108
  const agentId = (authenticatedAgent && !callerIsAdmin)
106
109
  ? authenticatedAgent
107
110
  : bodyAgentId;
108
- // Read-scope: own (any visibility) + granted owners' SHARED memories only
109
- // (Layer 1). Centralized in resolveReadScope() — this used to be
111
+ // Read-scope: own records at any visibility + every other agent's
112
+ // non-private records (grants are not consulted on reads). Centralized in
113
+ // resolveReadScope() — this used to be
110
114
  // an inline grant-resolution loop here PLUS a `visibility === "office"`
111
115
  // global OR-clause below that leaked ANY authenticated agent's read of
112
116
  // ANY other agent's office-visible memories. Both are gone;
113
117
  // this is the ONE scoping resolution for this endpoint now.
114
118
  const scope = agentId ? await resolveReadScope(agentId) : null;
119
+ // Select the retrieval mode ONCE per request (bench-facing selector; see
120
+ // the flag doc in ./bm25.ts). Default (FLAIR_RETRIEVAL_MODE unset) follows
121
+ // the legacy FLAIR_HYBRID_RETRIEVAL boolean exactly.
122
+ const mode = retrievalMode();
115
123
  // Generate query embedding
116
124
  let qEmb = queryEmbedding;
117
- if (!qEmb && q) {
125
+ if (!qEmb && q && mode !== "bm25-only") {
118
126
  // Always attempt embedding generation — getEmbedding() handles init internally.
119
127
  // Don't gate on getMode() which may return "none" before init completes in worker threads.
120
128
  // flair#504 Phase 2: 'query' — this is a search query, not stored content.
129
+ // bm25-only: skipped — that arm ranks on the lexical leg alone and must
130
+ // perform NO embedding call (the core ignores any qEmb it is handed).
121
131
  try {
122
132
  qEmb = await getEmbedding(String(q).slice(0, 8000), "query");
123
133
  }
@@ -171,8 +181,9 @@ export class SemanticSearch extends Resource {
171
181
  }
172
182
  // ─── Build conditions for Harper query ──────────────────────────────────
173
183
  const conditions = [];
174
- // Agent scoping: own (any visibility) OR granted-owner's SHARED memories
175
- // (private-exclusion) — the centralized read-scope condition. No agentId
184
+ // Agent scoping: own records at any visibility OR every other agent's
185
+ // non-private records (grants are not consulted on reads — resolveReadScope())
186
+ // — the centralized read-scope condition. No agentId
176
187
  // → no scoping condition pushed (trusted internal call / admin without a
177
188
  // target agentId — matches the pre-existing unscoped fallback).
178
189
  if (scope) {
@@ -228,7 +239,9 @@ export class SemanticSearch extends Resource {
228
239
  scoring,
229
240
  };
230
241
  }
231
- const hybrid = hybridEnabled();
242
+ // (`mode` was resolved at the top of post(); the bm25-only arm has no
243
+ // embedding, so the HNSW-leg portion of the overfetch policy does not apply
244
+ // to it — the core ignores `queryEmbedding` on that branch.)
232
245
  // The overfetch policy (how many raw candidates to pull from the
233
246
  // HNSW/BM25 legs relative to what the caller ultimately wants) is THIS
234
247
  // wrapper's decision — retrieveCandidates() never multiplies its `limit`
@@ -254,13 +267,13 @@ export class SemanticSearch extends Resource {
254
267
  minScore,
255
268
  agentId,
256
269
  isAllowed: scope?.isAllowed,
257
- hybrid,
270
+ mode,
258
271
  ctx,
259
272
  onLegs: includeLegs ? (l) => { legs = l; } : undefined,
260
273
  // flair#744 slice 1: the trust block needs `provenance`, which the
261
274
  // default projection omits. Widen the select ONLY when the caller opts
262
275
  // in — passing undefined otherwise keeps the default (no `provenance`)
263
- // so a non-trust recall response stays byte-identical.
276
+ // so a non-trust recall uses DEFAULT_SELECT without provenance.
264
277
  //
265
278
  // flair#1332: same idiom for the client-writable `metadata` JSON blob
266
279
  // (ADK custom_metadata store-and-return). DEFAULT_SELECT deliberately
@@ -268,14 +281,17 @@ export class SemanticSearch extends Resource {
268
281
  // serves every consumer, and none of the others should pay result-size
269
282
  // for an opaque blob they never read); adk-flair opts in per-request
270
283
  // with `includeMetadata: true`. `subject` needs no widening — it is
271
- // already in DEFAULT_SELECT. Neither flag ⇒ select stays undefined ⇒
272
- // response bytes unchanged.
284
+ // already in DEFAULT_SELECT. Without these flags the core uses its
285
+ // default projection, including instanceToken for the pointer join.
273
286
  // flair#1546: `includeTrigger` opts the skill recall signal into the
274
287
  // projection. DEFAULT_SELECT deliberately omits `trigger` (a skill-only
275
288
  // column — the shared retrieval core must not grow it for every consumer,
276
289
  // same K&S projection ruling as `metadata`), so skill_search opts it in
277
- // per-request to return the trigger in its lightweight catalog. Neither
278
- // flag ⇒ select stays undefined ⇒ response bytes unchanged.
290
+ // per-request to return the trigger in its lightweight catalog. With no
291
+ // projection flag, select stays undefined and the core uses DEFAULT_SELECT.
292
+ // flair#1940 A3: the gated pointer join also needs `instanceToken`, which
293
+ // DEFAULT_SELECT already carries (see semantic-retrieval-core.ts), so both
294
+ // the default and this widened projection hand the join what it binds on.
279
295
  select: (includeTrust || includeMetadata || includeTrigger)
280
296
  ? [...DEFAULT_SELECT,
281
297
  ...(includeTrust ? ["provenance"] : []),
@@ -322,6 +338,15 @@ export class SemanticSearch extends Resource {
322
338
  // the response still shows the pre-hit count (same contract as the old
323
339
  // fire-and-forget Memory patch, which ran after the slice).
324
340
  const topResults = await Promise.all(filteredResults.slice(0, limit).map((r) => applyHitStats(r, ctx)));
341
+ // flair#1940 A1' item 4 (semantic-search surface): the gated join. Only a
342
+ // non-admin agent scoped to itself is a "reader" under the withheld rule;
343
+ // an admin/internal call stays unfiltered. Fetch pointers for the WHOLE
344
+ // result set in ONE batched query (never one per row), then project.
345
+ const hostSourceReader = authenticatedAgent && !callerIsAdmin ? authenticatedAgent : undefined;
346
+ let projected = topResults;
347
+ if (hostSourceReader) {
348
+ projected = await projectRowsThroughPointers(topResults, hostSourceReader);
349
+ }
325
350
  // Async hit tracking — MemoryHitStat only, never a Memory rewrite.
326
351
  const now = new Date().toISOString();
327
352
  noteSearchHits(topResults.map((r) => r.id), now, ctx);
@@ -338,7 +363,7 @@ export class SemanticSearch extends Resource {
338
363
  // off the record to classify `matchQuality`. attachTrust returns a shallow
339
364
  // copy carrying `trust` (and still-present `_semSimilarity`); the strip then
340
365
  // drops the internal field from the copy.
341
- const trusted = includeTrust ? topResults.map((r) => attachTrust(r, true)) : topResults;
366
+ const trusted = includeTrust ? projected.map((r) => attachTrust(r, true)) : projected;
342
367
  // flair#744 slice 2 + refinement: strip the internal `_semSimilarity`
343
368
  // confidence field from the consumer-facing results — it exists ONLY to feed
344
369
  // the abstention decision and the matchQuality classification, never the
@@ -1,6 +1,6 @@
1
1
  import { databases } from "harper";
2
2
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
3
- import { localInstanceId } from "./instance-identity.js";
3
+ import { applyOriginatorInstanceId, dropClientOriginator, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
4
4
  import { makeAuthGate, stampAttribution } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  import { authorizeSoulWrite, refuseSoulWriteContent, soulProvenance } from "./soul-write-policy.js";
@@ -50,14 +50,12 @@ export class Soul extends databases.flair.Soul {
50
50
  content.durability ||= "permanent";
51
51
  content.createdAt = new Date().toISOString();
52
52
  content.updatedAt = content.createdAt;
53
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
54
- // 1) — see resources/Memory.ts's stampOriginatorInstanceId doc for the
55
- // full contract. No-op if already set (never fires for a genuine local
56
- // write; a federation-synced record never reaches this method — the
57
- // merge path writes via the raw table object, bypassing this class).
58
- if (content.originatorInstanceId == null) {
59
- content.originatorInstanceId = await localInstanceId();
60
- }
53
+ // Write-time originatorInstanceId (federation-edge-hardening slice 1): a
54
+ // post() is a CREATE — stamp this instance's own id, ignoring any
55
+ // request-body value. See resources/originator-instance.ts for the full
56
+ // contract (create/update rule; the federation merge path is the raw
57
+ // table writer and never consults a body).
58
+ await stampOriginatorOnCreate(content);
61
59
  return super.post(content, context);
62
60
  }
63
61
  // PATCH must validate the merged value and retained legacy tags, rather
@@ -69,11 +67,17 @@ export class Soul extends databases.flair.Soul {
69
67
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
70
68
  if (denial)
71
69
  return denial;
72
- // Fail-closed, same as Memory's stored-state read: a throw aborts the
73
- // write; missing/unreadable stored state cannot authorize a PATCH that
74
- // typically omits agentId (that used to skip the content-provenance match).
75
- const existing = await super.get();
76
- if (!existing || typeof existing !== "object" || existing instanceof Response) {
70
+ // Fail-closed, same class as Memory's stored-state read: the stored row is
71
+ // resolved by the URL-BOUND target id, refusing a body id that disagrees
72
+ // with the address and refusing a lookup that FAILS (a failed read is never
73
+ // "no stored row"). A PATCH that typically omits agentId cannot be
74
+ // authorized without the stored state, so an absent row is refused too. See
75
+ // resources/originator-instance.ts's resolveStoredRow.
76
+ const resolvedStored = await resolveStoredRow(this, "Soul", content, () => super.get());
77
+ if (resolvedStored.denial)
78
+ return resolvedStored.denial;
79
+ const existing = resolvedStored.row;
80
+ if (!existing) {
77
81
  return new Response(JSON.stringify({ error: "soul_stored_state_unavailable" }), {
78
82
  status: 403,
79
83
  headers: { "Content-Type": "application/json" },
@@ -82,6 +86,10 @@ export class Soul extends databases.flair.Soul {
82
86
  const learnedDenied = await refuseSoulWriteContent({ ...existing, ...content });
83
87
  if (learnedDenied)
84
88
  return learnedDenied;
89
+ // flair#1965: originatorInstanceId is server-stamped — a PATCH body value is
90
+ // dropped so the stored value stands (a patch merges; see
91
+ // resources/originator-instance.ts).
92
+ dropClientOriginator(content);
85
93
  const skillSourceDenied = refuseSkillAssignmentWrite(content, existing);
86
94
  if (skillSourceDenied)
87
95
  return skillSourceDenied;
@@ -105,11 +113,15 @@ export class Soul extends databases.flair.Soul {
105
113
  if (ownerDenial)
106
114
  return ownerDenial;
107
115
  content.updatedAt = new Date().toISOString();
108
- // Write-time originatorInstanceId stamp — see post() above / Memory.ts's
109
- // stampOriginatorInstanceId doc. No-op if already set.
110
- if (content.originatorInstanceId == null) {
111
- content.originatorInstanceId = await localInstanceId();
112
- }
116
+ // Write-time originatorInstanceId — see post() above /
117
+ // resources/originator-instance.ts. A CREATE stamps the local id; an
118
+ // UPDATE keeps the stored value (a body value never replaces or clears it).
119
+ // The row is resolved by the URL-BOUND target id, never a body `id` (Harper
120
+ // writes to the URL target); a mismatch or a failed read refuses the write.
121
+ const resolvedOriginRow = await resolveStoredRow(this, "Soul", content, () => super.get());
122
+ if (resolvedOriginRow.denial)
123
+ return resolvedOriginRow.denial;
124
+ await applyOriginatorInstanceId(content, resolvedOriginRow.row);
113
125
  return super.put(content, context);
114
126
  }
115
127
  async delete(id) {
@@ -4,6 +4,7 @@ import { harperPortValue } from "../src/lib/harper-port-value.js";
4
4
  import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
6
  import { createRemoteJWKSet, jwtVerify } from "jose";
7
+ import { stampOriginatorOnCreate } from "./originator-instance.js";
7
8
  /**
8
9
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
9
10
  *
@@ -148,8 +149,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
148
149
  }
149
150
  const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
150
151
  const now = nowISO();
151
- // Create principal (via Agent table)
152
- await databases.flair.Agent.put({
152
+ // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
153
+ // stamp the local instance id (the Agent resource's post() does not run here).
154
+ const principalRow = {
153
155
  id: principalId,
154
156
  name: displayName,
155
157
  displayName,
@@ -161,7 +163,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
161
163
  admin: false,
162
164
  createdAt: now,
163
165
  updatedAt: now,
164
- });
166
+ };
167
+ await stampOriginatorOnCreate(principalRow);
168
+ await databases.flair.Agent.put(principalRow);
165
169
  // Create IdP credential
166
170
  await databases.flair.Credential.put({
167
171
  id: `cred_idp_${randomBytes(8).toString("hex")}`,
@@ -13,10 +13,12 @@
13
13
  * Auth model: an agent presents `Authorization: TPS-Ed25519 <id>:<ts>:<nonce>:<sig>`.
14
14
  * The signature covers `<id>:<ts>:<nonce>:<METHOD>:<pathname><search>` and is
15
15
  * verified against the agent's stored Ed25519 public key. Replay is bounded by a
16
- * 30s timestamp window + a per-(agent,nonce) seen-set pruned to that window.
16
+ * 30s timestamp window + an instance-wide record of each (agent, nonce)
17
+ * (resources/replay-store.ts).
17
18
  */
18
19
  import { databases } from "harper";
19
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
20
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
21
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
20
22
  import { ADMIN_ROLE, agentRecordIsAdmin } from "./agent-admin.js";
21
23
  /**
22
24
  * Shared Harper user that verified Ed25519 agents resolve to (least-privilege
@@ -53,11 +55,11 @@ export function isPrincipalDeactivated(agent) {
53
55
  return agent.status !== "active";
54
56
  }
55
57
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
56
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
57
- // importEd25519Key all live in ./ed25519-auth.ts — the single
58
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
59
- // Presence.ts so a nonce recorded via any one of the three call sites is
60
- // visible to the other two, and the crypto/decoder logic can't drift.
58
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
59
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
60
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
61
+ // any one of the three call sites, on any worker thread, is refused by all of
62
+ // them, and the crypto/decoder logic can't drift.
61
63
  // ─── Admin resolution ─────────────────────────────────────────────────────────
62
64
  // Admin agents come from FLAIR_ADMIN_AGENTS (comma-separated) OR Agent records
63
65
  // whose `role` is the admin sentinel. OR-combined, cached 60s. Distinct from
@@ -124,8 +126,9 @@ async function doVerify(request) {
124
126
  const now = Date.now();
125
127
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
126
128
  return null;
127
- // Reject replays within the window (isNonceReplay prunes expired entries first).
128
- if (isNonceReplay(agentId, nonce, now))
129
+ // A nonce this thread already saw recorded is refused before any lookup. A
130
+ // miss here proves nothing: claimAgentNonce below is the authoritative check.
131
+ if (isKnownAgentReplay(agentId, nonce, now))
129
132
  return null;
130
133
  const agent = await databases.flair.Agent.get(agentId).catch(() => null);
131
134
  if (!agent?.publicKey)
@@ -147,7 +150,10 @@ async function doVerify(request) {
147
150
  catch {
148
151
  return null;
149
152
  }
150
- recordNonce(agentId, nonce, ts);
153
+ // Record the nonce instance-wide now that the signature has verified, and
154
+ // before the request has any effect. A replay or an unusable store refuses.
155
+ if (!(await claimAgentNonce(agentId, nonce)).ok)
156
+ return null;
151
157
  return { agentId, isAdmin: await isAdmin(agentId) };
152
158
  }
153
159
  /**