@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
@@ -11,13 +11,13 @@
11
11
  * REPLACES `retrievalBoost` in `compositeScore` outright (see that
12
12
  * function's doc).
13
13
  *
14
- * flair#744 slice A: the actual ledger-write core below (formerly this
15
- * class's private `_recordOne()`) has moved to ./usage-recording.ts's
16
- * `recordUsageContribution()` — a shared, single-implementation extraction
17
- * also used by citation-on-write (resources/Memory.ts's post()/put()) so
18
- * there is exactly ONE place the (agentId, memoryId) ledger logic lives.
19
- * This endpoint's own request handling (auth, rate limit, batch validation,
20
- * the no-enumeration response) is unchanged.
14
+ * flair#744 slice A: the ledger-write core lives in ./usage-recording.ts's
15
+ * `recordUsageContribution()` — one implementation shared with
16
+ * citation-on-write (resources/Memory.ts's post()/put()) so there is exactly
17
+ * ONE place the (agentId, memoryId) ledger logic lives. This endpoint owns
18
+ * its request handling (auth, rate limit, batch validation, the
19
+ * no-enumeration response) and hands the validated batch to
20
+ * ./usage-recording.ts's `recordUsageBatch()`.
21
21
  *
22
22
  * WHY THIS IS ITS OWN ENDPOINT, NOT `Memory.put()` (Sherlock, K&S verdict —
23
23
  * FLAIR-USAGE-FEEDBACK-SIGNAL.md): usage feedback is fundamentally a
@@ -32,18 +32,22 @@
32
32
  * ./usage-recording.ts's recordUsageContribution()) against the RAW
33
33
  * `Memory` table object, entirely bypassing the `Memory` RESOURCE class
34
34
  * (and its ownership gate) — its own auth model is verified-agent +
35
- * within-org + explicitly NO ownership requirement.
35
+ * within-org + the caller's READ SCOPE + explicitly NO ownership requirement.
36
36
  *
37
- * NO READ-SCOPE GATE — INTENTIONAL ASYMMETRY with citation-on-write
38
- * (flair#775): this endpoint deliberately does NOT validate reported ids
39
- * against the caller's read scope. Usage feedback is the cross-agent
40
- * contract described above (agent B reports using agent A's memory
41
- * regardless of A's visibility setting), and the no-enumeration response
42
- * below already denies existence probing on this surface. Citation-on-write
43
- * (./usage-recording.ts's recordCitations()) DOES scope-gate each cited id —
44
- * it is a separate write surface with a narrower threat model; see that
45
- * module's doc. Do not "unify" the two: the difference is a K&S binding
46
- * condition on the flair#775 locked design, not drift.
37
+ * READ SCOPE: usage is recorded only for a memory in the caller's read scope
38
+ * — `resolveReadScope(caller).isAllowed(record)`: the caller's own memories
39
+ * at any visibility, and every other agent's non-private memories. That is
40
+ * the scope Memory.get() applies to a NON-ADMIN by-id read; here it applies
41
+ * to admin callers too, although an admin's Memory reads are unfiltered.
42
+ * Agent B can report using agent A's shared memory; a memory outside B's
43
+ * scope is treated like an id that does not exist: the same response, and
44
+ * no change to that memory's counters. The ledger core checks the scope on
45
+ * its first read of the memory, before it writes B's ledger row, so a memory
46
+ * outside the scope there gets no row; a memory that leaves the scope before
47
+ * the re-read that precedes the count bump keeps the row already written,
48
+ * and the count is not bumped. The scope is resolved once per call and fails
49
+ * CLOSED (nothing is recorded if it cannot be resolved). Citation-on-write
50
+ * applies the same rule (./usage-recording.ts's module doc).
47
51
  *
48
52
  * WHY THIS ISN'T A @table-BACKED RESOURCE: the actual dedup ledger (one row
49
53
  * per (agentId, memoryId) contribution) lives in the `MemoryUsage` table
@@ -82,7 +86,8 @@
82
86
  * NO ID ENUMERATION (Sherlock): the response is IDENTICAL — `{ recorded:
83
87
  * true }` — for every syntactically-valid input, regardless of whether a
84
88
  * given id was a fresh increment, an already-counted no-op (this agent
85
- * already contributed), or a not-found no-op (no such memory). A caller
89
+ * already contributed), or a not-found no-op (no such memory, or one outside
90
+ * the caller's read scope — see READ SCOPE above). A caller
86
91
  * cannot distinguish "that id doesn't exist" from "you already used it" by
87
92
  * inspecting the response; per-id/per-batch success is deliberately never
88
93
  * reported (see RECORDED_RESPONSE's doc below for why even partial-batch
@@ -96,7 +101,7 @@
96
101
  import { Resource } from "harper";
97
102
  import { resolveAgentAuth } from "./agent-auth.js";
98
103
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
99
- import { recordUsageContribution, MAX_USAGE_IDS_PER_CALL } from "./usage-recording.js";
104
+ import { recordUsageBatch, MAX_USAGE_IDS_PER_CALL } from "./usage-recording.js";
100
105
  import { resolveRecordUsageIds } from "./usage-ids.js";
101
106
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
102
107
  const BAD_REQUEST = (msg) => new Response(JSON.stringify({ error: msg }), { status: 400, headers: { "Content-Type": "application/json" } });
@@ -176,26 +181,11 @@ export class RecordUsage extends Resource {
176
181
  const memoryIds = resolved.ids;
177
182
  const attribution = sanitizeAttribution(data?.attribution);
178
183
  const now = new Date().toISOString();
179
- for (const memoryId of memoryIds) {
180
- try {
181
- // flair#744 slice A: the ledger-write core now lives in
182
- // ./usage-recording.ts's recordUsageContribution() — a shared,
183
- // single-implementation extraction (also used by citation-on-write,
184
- // resources/Memory.ts's post()/put()). Byte-identical behavior to
185
- // the former private _recordOne() this replaced. Deliberately NO
186
- // read-scope check on memoryId here (flair#775 asymmetry — see the
187
- // module doc's NO READ-SCOPE GATE paragraph; citation-on-write's
188
- // recordCitations() is the surface that scope-gates).
189
- await recordUsageContribution(ctx, agentId, memoryId, attribution, now);
190
- }
191
- catch (err) {
192
- // Never let one bad id fail the whole batch, and never let an
193
- // internal error leak existence information either — log
194
- // server-side, collapse to the same no-op the response already
195
- // returns for every other outcome.
196
- console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
197
- }
198
- }
184
+ // Resolves the caller's read scope once, fails closed, and credits each id
185
+ // through the shared ledger core under that scope; per-id failures are
186
+ // logged server-side only (see the module doc's READ SCOPE paragraph and
187
+ // ./usage-recording.ts's recordUsageBatch()). Never throws.
188
+ await recordUsageBatch(ctx, agentId, memoryIds, attribution, now);
199
189
  // Deliberately does NOT report which ids succeeded / were already
200
190
  // counted / were not found — see RECORDED_RESPONSE's doc.
201
191
  return RECORDED_RESPONSE;
@@ -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";
5
+ import { applyOriginatorInstanceId, resolveStoredRow } from "./originator-instance.js";
6
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
@@ -119,89 +121,93 @@ export class Relationship extends databases.flair.Relationship {
119
121
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
120
122
  if (denial)
121
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);
122
172
  return super.patch(content, query);
123
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
+ }
124
192
  async put(content) {
125
193
  const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
126
194
  if (__ownerDenial)
127
195
  return __ownerDenial;
128
- const ctx = this.getContext?.();
129
- const auth = await resolveAgentAuth(ctx);
130
- if (auth.kind === "anonymous") {
131
- return UNAUTH();
132
- }
133
- // No-forge attribution — mode/field drawn from RECORD_TYPES.Relationship
134
- // (record-types slice 2, flair#520) rather than a hand-typed literal.
135
- // "stamp-strict" (see record-type-kit.ts's stampAttribution doc): reject
136
- // a PRESENT, mismatched agentId, else unconditionally stamp with the
137
- // verified identity. Admin/internal: content.agentId left as provided
138
- // (unfiltered) — see doc above.
139
- const attr = stampAttribution(auth, content, RECORD_TYPES.Relationship.ownerField, RECORD_TYPES.Relationship.attribution.put, "cannot write a relationship owned by another agent");
140
- if (attr.denied)
141
- return attr.denied;
142
- if (!content.agentId || typeof content.agentId !== "string") {
143
- return new Response(JSON.stringify({ error: "agentId is required" }), {
144
- status: 400, headers: { "content-type": "application/json" },
145
- });
146
- }
147
- // Rate limit keyed on the RESOLVED agentId (never a client-supplied one)
148
- // — matches Memory.post()'s intent, extended to cover every
149
- // resolveAgentAuth path (credentialed super_user, verifyAgentRequest
150
- // fallback), not just the gate's own `tpsAgent` annotation. Internal
151
- // calls have no per-agent identity to key on and are trusted, so they're
152
- // exempt — same as Memory.post()'s `if (authenticatedAgent)` guard.
153
- if (auth.kind === "agent") {
154
- const rl = checkRateLimit(auth.agentId);
155
- if (!rl.allowed)
156
- return rateLimitResponse(rl.retryAfterMs, "relationship");
157
- }
158
- // Validate required fields
159
- if (!content.subject || typeof content.subject !== "string") {
160
- return new Response(JSON.stringify({ error: "subject is required (string)" }), {
161
- status: 400, headers: { "content-type": "application/json" },
162
- });
163
- }
164
- if (!content.predicate || typeof content.predicate !== "string") {
165
- return new Response(JSON.stringify({ error: "predicate is required (string)" }), {
166
- status: 400, headers: { "content-type": "application/json" },
167
- });
168
- }
169
- if (!content.object || typeof content.object !== "string") {
170
- return new Response(JSON.stringify({ error: "object is required (string)" }), {
171
- status: 400, headers: { "content-type": "application/json" },
172
- });
173
- }
174
- // Normalize — lowercasing is load-bearing: MemoryBootstrap.ts's attention
175
- // read matches lowercased predicted subjects against subject/object.
176
- const now = new Date().toISOString();
177
- content.subject = content.subject.toLowerCase();
178
- content.predicate = content.predicate.toLowerCase();
179
- content.object = content.object.toLowerCase();
180
- content.createdAt = content.createdAt || now;
181
- content.updatedAt = now;
182
- content.validFrom = content.validFrom || now;
183
- // validTo left as null/undefined for active relationships
184
- content.confidence = content.confidence ?? 1.0;
185
- // Write-time provenance stamp (relationship-write-path, folded K&S
186
- // refinement) — reuses Memory's buildProvenance EXACTLY (./provenance.ts),
187
- // same `{v, verified, claimed?}` shape, no Relationship-specific format.
188
- // Additive/nullable on the schema side (schemas/memory.graphql) — a
189
- // pre-existing row with no provenance field reads back `undefined`,
190
- // unchanged behavior (migration-equivalence gate).
191
- content.provenance = buildProvenance(auth, content.createdAt, content);
192
- // flair#718 authorship-provenance — same contract as resources/Memory.ts's
193
- // post()/put(): `claimedClient` is a write-body-only passthrough, already
194
- // folded into `provenance.claimed.client` above. Strip it so it is NEVER
195
- // persisted as a row field.
196
- delete content.claimedClient;
197
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
198
- // 1) — see resources/Memory.ts's stampOriginatorInstanceId doc for the
199
- // full contract. No-op if already set (never fires for a genuine local
200
- // write; a federation-synced record never reaches this method — the
201
- // merge path writes via the raw table object, bypassing this class).
202
- if (content.originatorInstanceId == null) {
203
- content.originatorInstanceId = await localInstanceId();
204
- }
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);
205
211
  return super.put(content);
206
212
  }
207
213
  /**
@@ -233,3 +239,86 @@ export class Relationship extends databases.flair.Relationship {
233
239
  return super.delete(_);
234
240
  }
235
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
+ }
@@ -19,6 +19,7 @@ import { retrievalMode } 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
@@ -272,7 +273,7 @@ export class SemanticSearch extends Resource {
272
273
  // flair#744 slice 1: the trust block needs `provenance`, which the
273
274
  // default projection omits. Widen the select ONLY when the caller opts
274
275
  // in — passing undefined otherwise keeps the default (no `provenance`)
275
- // so a non-trust recall response stays byte-identical.
276
+ // so a non-trust recall uses DEFAULT_SELECT without provenance.
276
277
  //
277
278
  // flair#1332: same idiom for the client-writable `metadata` JSON blob
278
279
  // (ADK custom_metadata store-and-return). DEFAULT_SELECT deliberately
@@ -280,14 +281,17 @@ export class SemanticSearch extends Resource {
280
281
  // serves every consumer, and none of the others should pay result-size
281
282
  // for an opaque blob they never read); adk-flair opts in per-request
282
283
  // with `includeMetadata: true`. `subject` needs no widening — it is
283
- // already in DEFAULT_SELECT. Neither flag ⇒ select stays undefined ⇒
284
- // response bytes unchanged.
284
+ // already in DEFAULT_SELECT. Without these flags the core uses its
285
+ // default projection, including instanceToken for the pointer join.
285
286
  // flair#1546: `includeTrigger` opts the skill recall signal into the
286
287
  // projection. DEFAULT_SELECT deliberately omits `trigger` (a skill-only
287
288
  // column — the shared retrieval core must not grow it for every consumer,
288
289
  // same K&S projection ruling as `metadata`), so skill_search opts it in
289
- // per-request to return the trigger in its lightweight catalog. Neither
290
- // 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.
291
295
  select: (includeTrust || includeMetadata || includeTrigger)
292
296
  ? [...DEFAULT_SELECT,
293
297
  ...(includeTrust ? ["provenance"] : []),
@@ -334,6 +338,15 @@ export class SemanticSearch extends Resource {
334
338
  // the response still shows the pre-hit count (same contract as the old
335
339
  // fire-and-forget Memory patch, which ran after the slice).
336
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
+ }
337
350
  // Async hit tracking — MemoryHitStat only, never a Memory rewrite.
338
351
  const now = new Date().toISOString();
339
352
  noteSearchHits(topResults.map((r) => r.id), now, ctx);
@@ -350,7 +363,7 @@ export class SemanticSearch extends Resource {
350
363
  // off the record to classify `matchQuality`. attachTrust returns a shallow
351
364
  // copy carrying `trust` (and still-present `_semSimilarity`); the strip then
352
365
  // drops the internal field from the copy.
353
- const trusted = includeTrust ? topResults.map((r) => attachTrust(r, true)) : topResults;
366
+ const trusted = includeTrust ? projected.map((r) => attachTrust(r, true)) : projected;
354
367
  // flair#744 slice 2 + refinement: strip the internal `_semSimilarity`
355
368
  // confidence field from the consumer-facing results — it exists ONLY to feed
356
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,8 @@ 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";
8
+ import { claimIdJagJti, ReplayStoreUnavailable } from "./replay-store.js";
7
9
  /**
8
10
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
9
11
  *
@@ -23,7 +25,25 @@ import { createRemoteJWKSet, jwtVerify } from "jose";
23
25
  */
24
26
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
25
27
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
26
- 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;
27
47
  // JWKS remote key set cache per issuer (jose handles caching internally)
28
48
  const jwksSetCache = new Map();
29
49
  function sha256(input) {
@@ -106,17 +126,21 @@ export async function validateIdJag(assertion, expectedAudience) {
106
126
  throw new Error(`domain required but no hd/tid claim present — consumer account rejected`);
107
127
  }
108
128
  }
109
- // Replay prevention (jti)
110
- if (payload.jti) {
111
- const existing = await databases.flair.IdJagReplay.get(payload.jti);
112
- 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")
113
141
  throw new Error("token replay detected");
114
- const now = Date.now();
115
- await databases.flair.IdJagReplay.put({
116
- id: payload.jti,
117
- expiresAt: futureISO(Math.max((payload.exp ?? 0) * 1000 - now + CLOCK_SKEW_MS, 300_000)),
118
- createdAt: nowISO(),
119
- });
142
+ if (claim !== "recorded")
143
+ throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
120
144
  }
121
145
  return { payload: payload, idpConfig };
122
146
  }
@@ -148,8 +172,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
148
172
  }
149
173
  const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
150
174
  const now = nowISO();
151
- // Create principal (via Agent table)
152
- await databases.flair.Agent.put({
175
+ // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
176
+ // stamp the local instance id (the Agent resource's post() does not run here).
177
+ const principalRow = {
153
178
  id: principalId,
154
179
  name: displayName,
155
180
  displayName,
@@ -161,7 +186,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
161
186
  admin: false,
162
187
  createdAt: now,
163
188
  updatedAt: now,
164
- });
189
+ };
190
+ await stampOriginatorOnCreate(principalRow);
191
+ await databases.flair.Agent.put(principalRow);
165
192
  // Create IdP credential
166
193
  await databases.flair.Credential.put({
167
194
  id: `cred_idp_${randomBytes(8).toString("hex")}`,
@@ -257,6 +284,12 @@ export async function handleJwtBearerGrant(data) {
257
284
  };
258
285
  }
259
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
+ }
260
293
  return new Response(JSON.stringify({
261
294
  error: "invalid_grant",
262
295
  error_description: err.message,