@tpsdev-ai/flair 0.57.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 (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -40,10 +40,25 @@
40
40
  * ledger is an audit trail, not a shared surface — there is no product need
41
41
  * to expose "which agent used which memory" cross-agent, and narrowing this
42
42
  * costs nothing.
43
+ *
44
+ * And within its own contributions, a non-admin agent sees a row only while
45
+ * the memory the row names exists and is in its Memory read scope
46
+ * (resolveReadScope — the rule Memory.get() applies to a non-admin reader).
47
+ * A row about a memory the reader cannot read reads exactly like a row that
48
+ * does not exist: 404 by id, absent from a collection read. A ledger row is
49
+ * therefore never evidence, to a non-admin reader, about a memory it cannot
50
+ * otherwise see. Admin and trusted internal reads are unfiltered (get() and
51
+ * search() below). The rule lives in
52
+ * ./usage-recording.ts (isLedgerRowVisible / readableLedgerRows), next to the
53
+ * write-side gate. Like Memory's reads, a non-admin read here ignores the
54
+ * caller's `select`/`property`, so the decision always sees the stored
55
+ * `memoryId`. A collection read filters after the owner-scoped query, so a
56
+ * `limit` can return fewer rows than it names.
43
57
  */
44
58
  import { databases } from "harper";
45
59
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
46
60
  import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
61
+ import { isLedgerRowVisible, readableLedgerRows } from "./usage-recording.js";
47
62
  // Owner-only read scope through the shared by-id gate and scoped search.
48
63
  const usageReadScope = makeReadScope("owner-only", "agentId");
49
64
  const usageByIdReadGate = makeByIdReadGate(usageReadScope);
@@ -51,21 +66,56 @@ const usageScopedSearch = makeScopedSearch(usageReadScope);
51
66
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
52
67
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
53
68
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
69
+ /** The caller's query without its `select`/`property` (a key deletion, not a
70
+ * selection parser — the same rule resources/Memory.ts applies to a
71
+ * non-admin read, so the read decision sees the stored row). */
72
+ function withoutCallerSelection(query) {
73
+ if (!query || typeof query !== "object")
74
+ return query;
75
+ if (query.select === undefined && query.property === undefined)
76
+ return query;
77
+ const copy = Array.isArray(query) ? query.slice() : { ...query };
78
+ delete copy.select;
79
+ delete copy.property;
80
+ return copy;
81
+ }
54
82
  export class MemoryUsage extends databases.flair.MemoryUsage {
55
83
  /** Self-authorize now that the global gate is non-rejecting — same pattern
56
84
  * as every other table resource in this codebase (Memory.ts/MemoryGrant.ts
57
85
  * etc.). Per-record scoping happens in get()/search() below. */
58
86
  allowRead() { return allowVerified(this.getContext?.()); }
59
87
  async get(target) {
60
- return usageByIdReadGate.call(this, target, (t) => super.get(t));
88
+ // Collection / query reads are governed by search() below.
89
+ if (!target || (typeof target === "object" && target.isCollection)) {
90
+ return this.search(target);
91
+ }
92
+ const ctx = this.getContext?.();
93
+ const auth = await resolveAgentAuth(ctx);
94
+ // Anonymous (404), trusted internal and admin (unfiltered): the shared gate.
95
+ if (auth.kind !== "agent" || auth.isAdmin) {
96
+ return usageByIdReadGate.call(this, target, (t) => super.get(t));
97
+ }
98
+ // Non-admin agent: the owner-only gate on the stored row (read by a plain
99
+ // id-only target, so the caller's select/property never shapes it), then
100
+ // the memory that row names must be readable by this agent. Both denials
101
+ // are the same 404 as a missing row.
102
+ const targetId = typeof target === "string" ? target : target?.id;
103
+ const row = await usageByIdReadGate.call(this, targetId != null ? { id: targetId } : {}, (t) => super.get(t));
104
+ if (!row || row instanceof Response)
105
+ return row ?? NOT_FOUND();
106
+ return (await isLedgerRowVisible(ctx, auth.agentId, row)) ? row : NOT_FOUND();
61
107
  }
62
108
  async search(query) {
63
- const auth = await resolveAgentAuth(this.getContext?.());
109
+ const ctx = this.getContext?.();
110
+ const auth = await resolveAgentAuth(ctx);
64
111
  if (auth.kind === "anonymous")
65
112
  return UNAUTH();
66
113
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
67
114
  return super.search(query);
68
- return usageScopedSearch(auth.agentId, query, (q) => super.search(q));
115
+ // Owner-only query (outermost AND), then only the rows about memories this
116
+ // agent can read — see the module doc.
117
+ const rows = await usageScopedSearch(auth.agentId, withoutCallerSelection(query), (q) => super.search(q));
118
+ return readableLedgerRows(ctx, auth.agentId, rows);
69
119
  }
70
120
  // Append-only ledger: rows are created via RecordUsage's RAW table call
71
121
  // (bypasses this class entirely — see module doc), never via this
@@ -39,7 +39,8 @@ import { fileURLToPath } from "node:url";
39
39
  import { createRequire } from "node:module";
40
40
  import { resolveAgentAuth, isPrincipalDeactivated } from "./agent-auth.js";
41
41
  import { agentRecordIsAdmin } from "./agent-admin.js";
42
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
42
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
43
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
43
44
  // ─── Constants ────────────────────────────────────────────────────────────────
44
45
  const CURRENT_TASK_MAX_LENGTH = 200;
45
46
  const VALID_ACTIVITIES = new Set(["coding", "reviewing", "planning", "debugging", "idle"]);
@@ -83,10 +84,10 @@ export function publicRosterEnabled() {
83
84
  *
84
85
  * GET /Presence/<id> is NOT on auth-middleware.ts's short-circuit list (only
85
86
  * the exact "/Presence" collection GET is). The middleware verifies the
86
- * TPS-Ed25519 signature and records the nonce in the ONE shared nonce store,
87
+ * TPS-Ed25519 signature and records the nonce in the ONE shared replay store,
87
88
  * annotating request.tpsAgent but NOT verifyAgentRequest's per-request memo.
88
89
  * Calling verifyAgentRequest() again would re-consume that same nonce, read as
89
- * a replay (isNonceReplay) and deny a legitimate agent. resolveAgentAuth()
90
+ * a replay (claimAgentNonce) and deny a legitimate agent. resolveAgentAuth()
90
91
  * consults the middleware's tpsAgent/tpsAnonymous annotations FIRST, and only
91
92
  * falls back to a header verify when the middleware never ran (the
92
93
  * short-circuited collection GET) — so it reuses the established verdict
@@ -200,11 +201,11 @@ export function buildPresenceRecord(agentId, now, currentTask, activity, existin
200
201
  };
201
202
  }
202
203
  // ─── Nonce replay + crypto helpers ─────────────────────────────────────────────
203
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
204
- // importEd25519Key all live in ./ed25519-auth.ts — the single
205
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
206
- // Presence.ts so a nonce recorded via any one of the three call sites is
207
- // visible to the other two, and the crypto/decoder logic can't drift.
204
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
205
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
206
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
207
+ // any one of the three call sites, on any worker thread, is refused by all of
208
+ // them, and the crypto/decoder logic can't drift.
208
209
  // ─── Status derivation (pure — exported for unit testing) ─────────────────────
209
210
  export function derivePresenceStatus(now, lastHeartbeatAt, idleMs, offlineMs) {
210
211
  const idle = idleMs ?? idleThresholdMs();
@@ -514,7 +515,9 @@ export class Presence extends databases.flair.Presence {
514
515
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS) {
515
516
  return new Response(JSON.stringify({ error: "timestamp_out_of_window" }), { status: 401, headers: { "Content-Type": "application/json" } });
516
517
  }
517
- if (isNonceReplay(headerAgentId, nonce, now)) {
518
+ // A nonce this thread already saw recorded is refused before any lookup.
519
+ // A miss proves nothing: claimAgentNonce below is the authoritative check.
520
+ if (isKnownAgentReplay(headerAgentId, nonce, now)) {
518
521
  return new Response(JSON.stringify({ error: "nonce_replay_detected" }), { status: 401, headers: { "Content-Type": "application/json" } });
519
522
  }
520
523
  const agent = await databases.flair.Agent.get(headerAgentId).catch(() => null);
@@ -536,7 +539,12 @@ export class Presence extends databases.flair.Presence {
536
539
  catch (e) {
537
540
  return new Response(JSON.stringify({ error: "signature_verification_failed", detail: e?.message }), { status: 401, headers: { "Content-Type": "application/json" } });
538
541
  }
539
- recordNonce(headerAgentId, nonce, ts);
542
+ // Record the nonce instance-wide now that the signature has verified, and
543
+ // before the heartbeat is written. A replay or an unusable store refuses.
544
+ const claim = await claimAgentNonce(headerAgentId, nonce);
545
+ if (!claim.ok) {
546
+ return new Response(JSON.stringify({ error: claim.error }), { status: claim.status, headers: { "Content-Type": "application/json" } });
547
+ }
540
548
  // Deactivation guard — same predicate as the middleware Basic branches.
541
549
  // A deactivated principal must not be allowed to heartbeat, even when
542
550
  // the Ed25519 signature is valid.
@@ -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