@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
@@ -38,8 +38,8 @@ function sanitizeClaim(value) {
38
38
  * CLAIMS. Deliberately minimal — verified fields only:
39
39
  *
40
40
  * { v: 1,
41
- * verified: { agentId: <string|null>, timestamp: <ISO string> },
42
- * claimed?: { model?: <string>, client?: <string> } }
41
+ * verified: { agentId: <string|null>, timestamp: <ISO string>, receivedAt: <ISO string> },
42
+ * claimed?: { createdAt?: <string>, model?: <string>, client?: <string> } }
43
43
  *
44
44
  * - `verified.agentId` comes from the ALREADY-RESOLVED auth verdict
45
45
  * (resolveAgentAuth) — never from anything the caller can forge on the
@@ -48,10 +48,31 @@ function sanitizeClaim(value) {
48
48
  * with no per-agent identity to attribute) stamps `null` rather than
49
49
  * throwing; `kind: "anonymous"` never reaches here — every write path
50
50
  * already 401s it before this point.
51
- * - `verified.timestamp` reuses the server-clock `createdAt` the caller has
52
- * already computed by this point (never client-suppliable) — the same
53
- * "stamp a dynamic attribute the server controls" mechanism as e.g. the
54
- * `embeddingModel = getModelId()` stamp in resources/Memory.ts.
51
+ * - `verified.timestamp` is stamped from the SERVER clock at write time
52
+ * (flair#1960) — the SAME single clock read as `verified.receivedAt`, because
53
+ * both assert the server's write instant (a second read could differ by
54
+ * milliseconds and make the two fields disagree). Never client-suppliable:
55
+ * the caller's `createdAt` is a CLAIM and is recorded separately under
56
+ * `claimed.createdAt` (below), never here. Every field under `verified` is
57
+ * server-derived.
58
+ * The clock is an injectable `() => Date` (defaulting to the wall clock) so
59
+ * the "one read" contract is TESTABLE: a counting/advancing fake clock fails
60
+ * the test deterministically if a second read is ever added (flair#1960 r2 —
61
+ * comparing two wall-clock reads only catches a drift of >0 ms, and two reads
62
+ * almost always land in the SAME millisecond, so the old equality-only test
63
+ * CAUGHT a second read only ~7 times in 10,000 — it MISSED it the other
64
+ * ~9,993). Production callers never pass one.
65
+ * - The host pointer (`hostSource`) is NOT provenance (flair#1940 A5): it lives
66
+ * in its own `MemoryHostSource` table, is never part of this `{ v, verified,
67
+ * claimed }` blob, and is written on the Memory write path in the same
68
+ * transaction as the Memory row (t1/t2). `provenance` therefore stays a field
69
+ * the server controls and is never client-writable.
70
+ * - `claimed.createdAt` (flair#1960) is the caller's claim on the record's
71
+ * creation time — the `createdAt` the write carries, sanitized like the
72
+ * other claims (string-only, control-char strip, trim, 200-char cap,
73
+ * drop-if-empty). It is a CLAIM, never verified: the server's own write
74
+ * instant lives in `verified.timestamp`. The record's own `createdAt` field
75
+ * still carries the caller's value unchanged.
55
76
  * - `claimed.model` is an OPTIONAL, UNVERIFIED passthrough: included only
56
77
  * when the incoming write payload itself already carries a non-empty
57
78
  * string `model` field (sanitized via sanitizeClaim above). Never
@@ -71,8 +92,9 @@ function sanitizeClaim(value) {
71
92
  * OAuth path, the caller is required to source this from the verified
72
93
  * `client_id` token claim, never the user-controlled `client_name` — see
73
94
  * resources/mcp-handler.ts's handleToolCall for that stamp site.
74
- * - The `claimed` key is omitted entirely (not stamped as `{}`) when both
75
- * `model` and `client` are absent.
95
+ * - The `claimed` key is omitted entirely (not stamped as `{}`) when
96
+ * `createdAt`, `model` and `client` are ALL absent after sanitization (e.g.
97
+ * an empty or all-control-chars `createdAt` with no model/client claims).
76
98
  *
77
99
  * Originally introduced in resources/Memory.ts (Memory.post()/Memory.put());
78
100
  * extracted here so Relationship.ts (and any future write path) can reuse the
@@ -81,18 +103,33 @@ function sanitizeClaim(value) {
81
103
  * buildProvenance as-is," which this module makes literal (one function, one
82
104
  * shape, imported by every writer) instead of a copy that could drift.
83
105
  */
84
- export function buildProvenance(auth, createdAt, content) {
106
+ export function buildProvenance(auth, createdAt, content, clock = () => new Date()) {
107
+ // ONE clock read per write, shared by BOTH server-derived timestamps
108
+ // (flair#1960): `verified.timestamp` and `verified.receivedAt` assert the
109
+ // same server write instant, so a single `clock()` call keeps them identical
110
+ // instead of letting a second read drift them apart by milliseconds.
111
+ const serverNow = clock().toISOString();
85
112
  const provenance = {
86
113
  v: 1,
87
114
  verified: {
88
115
  agentId: auth.kind === "agent" ? auth.agentId : null,
89
- timestamp: createdAt,
116
+ // flair#1960: the server's write instant — NEVER the caller's `createdAt`.
117
+ timestamp: serverNow,
118
+ // flair#1940 A4: the server's RECEIPT time — same clock read as above.
119
+ receivedAt: serverNow,
90
120
  },
91
121
  };
122
+ // The caller's `createdAt` is their CLAIM on the record's creation time; it is
123
+ // recorded under `claimed` (sanitized like the other claims) so a reader can
124
+ // compare the claim against the server's `verified.timestamp`. The record's
125
+ // own `createdAt` field keeps the claim unchanged (flair#1960).
126
+ const claimedCreatedAt = sanitizeClaim(createdAt);
92
127
  const model = sanitizeClaim(content?.model);
93
128
  const client = sanitizeClaim(content?.claimedClient);
94
- if (model !== undefined || client !== undefined) {
129
+ if (claimedCreatedAt !== undefined || model !== undefined || client !== undefined) {
95
130
  provenance.claimed = {};
131
+ if (claimedCreatedAt !== undefined)
132
+ provenance.claimed.createdAt = claimedCreatedAt;
96
133
  if (model !== undefined)
97
134
  provenance.claimed.model = model;
98
135
  if (client !== undefined)
@@ -100,3 +137,66 @@ export function buildProvenance(auth, createdAt, content) {
100
137
  }
101
138
  return JSON.stringify(provenance);
102
139
  }
140
+ /**
141
+ * The fields whose change makes a memory write SEMANTIC — the text the record
142
+ * actually says, plus its creation claim. A PATCH that changes one of these is
143
+ * re-authoring content (and, for `createdAt`, re-authoring the creation claim),
144
+ * so it MUST re-stamp provenance from the resolved auth and the server clock
145
+ * rather than carry a previously stored `verified.*` value forward (flair#1960
146
+ * r2). `createdAt` is included (flair#1960 r4): a createdAt-only PATCH is
147
+ * allowed and reaches `super.patch`, so if it were NOT semantic the row's
148
+ * `createdAt` could change while `provenance.claimed.createdAt` kept the old
149
+ * value. Making it semantic means a changed creation claim re-stamps, and
150
+ * `claimed.createdAt` follows the row.
151
+ */
152
+ export const MEMORY_SEMANTIC_FIELDS = Object.freeze(["content", "subject", "summary", "createdAt"]);
153
+ /**
154
+ * The fields whose change makes a relationship write SEMANTIC — its identity
155
+ * (what it links), plus its creation claim. Same rule as MEMORY_SEMANTIC_FIELDS:
156
+ * a semantic PATCH re-stamps provenance; a metadata-only PATCH
157
+ * (confidence/source/etc.) leaves the stored, previously-stamped blob in place.
158
+ * `createdAt` is included (flair#1960 r4) for the same reason: a changed
159
+ * creation claim is a re-authored claim, so the PATCH re-stamps and
160
+ * `claimed.createdAt` follows the row.
161
+ */
162
+ export const RELATIONSHIP_SEMANTIC_FIELDS = Object.freeze(["subject", "predicate", "object", "createdAt"]);
163
+ /**
164
+ * True when `content` changes at least one of `fields` relative to the STORED
165
+ * record — the trigger for a provenance re-stamp on the update (PATCH) path.
166
+ *
167
+ * A value that is ABSENT from the write body is never a change (Harper PATCH
168
+ * merges; a missing key means "leave the stored value"), so this only looks at
169
+ * keys actually present in `content`. A non-object body, or a body whose target
170
+ * is not a string/primitive change, is not semantic.
171
+ */
172
+ export function isSemanticPatch(content, existing, fields) {
173
+ if (!content || typeof content !== "object" || Array.isArray(content))
174
+ return false;
175
+ if (!existing || typeof existing !== "object")
176
+ return false;
177
+ for (const field of fields) {
178
+ if (!Object.prototype.hasOwnProperty.call(content, field))
179
+ continue;
180
+ if (content[field] !== existing[field])
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+ /**
186
+ * The response a PATCH returns when its stored-row READ FAILS (flair#1960 r3).
187
+ *
188
+ * A read ERROR is not the same as "no stored row" (a `null`/`undefined`
189
+ * result). Both PATCH paths used to coalesce a thrown read into `null`; the
190
+ * semantic predicate then returns `false` for `null`, and the patch falls
191
+ * through to `super.patch()` as if it were a METADATA-ONLY write — which keeps
192
+ * a legacy stored blob (including a caller-chosen `verified.timestamp`) in
193
+ * place. Without the stored record there is no way to tell a semantic PATCH
194
+ * from a metadata-only one, so the only safe outcome is to REFUSE the write
195
+ * rather than fail open. 500: a server-side read fault, fail-closed.
196
+ */
197
+ export function storedRowReadFailedResponse(table) {
198
+ return new Response(JSON.stringify({
199
+ error: "stored_row_read_failed",
200
+ message: `cannot read the stored ${table} row; refusing the write`,
201
+ }), { status: 500, headers: { "content-type": "application/json" } });
202
+ }
@@ -54,13 +54,15 @@
54
54
  * - Anything at all if the operator sets `FLAIR_RATE_LIMIT=off`.
55
55
  *
56
56
  * ── The counter is consumed BEFORE any credential is looked at ──────────────
57
- * `checkHttpRateLimit` runs at the top of auth-middleware, before the request
58
- * body is parsed and before any grant, code, secret or token is evaluated. That
57
+ * `checkHttpRateLimit` runs near the top of auth-middleware (right after its
58
+ * HTTP method check; a request with a refused method never reaches it), before
59
+ * the request body is parsed and before any grant, code, secret or token is
60
+ * evaluated. That
59
61
  * is deliberate and it is a security property, not an implementation detail: if
60
62
  * the limiter only counted FAILURES, then "did this attempt consume budget"
61
63
  * would answer "was that credential valid" — an enumeration oracle strictly
62
- * better than the 400 the endpoint already returns. Counting unconditionally
63
- * means a 429 carries no information about the credential that accompanied it,
64
+ * better than the 400 the endpoint already returns. Counting every request
65
+ * that passes the method check, whatever its credential, means a 429 carries no information about the credential that accompanied it,
64
66
  * and a valid credential and a garbage one are byte-identical once limited.
65
67
  *
66
68
  * For the same reason nothing here emits `RateLimit-Limit`/`RateLimit-Remaining`
@@ -117,6 +117,10 @@ export const OWNER_GUARD_EXEMPT = Object.freeze({
117
117
  // resources/Agent.ts's shared write-authorization helper, which both its
118
118
  // put() and its patch() route through.
119
119
  Agent: "self-ownership by primary key; enforced in resources/Agent.ts for every verb",
120
+ // flair#1940 A1': MemoryHostSource refuses REST writes. Application pointer
121
+ // writes stamp `authorId` from the authenticated principal; direct resource
122
+ // reads permit admins and trusted internal callers.
123
+ MemoryHostSource: "REST writes refused; application writes stamp authorId; direct reads limited to admins and trusted internal callers",
120
124
  });
121
125
  /** The verbs that can mutate a record, and therefore need the rule applied. */
122
126
  export const MUTATING_METHODS = Object.freeze(["POST", "PUT", "PATCH", "DELETE"]);
@@ -175,6 +179,21 @@ export function isForbiddenOwnerMutation(record, ownerField, callerAgentId) {
175
179
  return true;
176
180
  return owner !== callerAgentId;
177
181
  }
182
+ /**
183
+ * The refusal for a write that names a stored record owned by another
184
+ * principal: 403 with a body that names only the table.
185
+ *
186
+ * One constructor for every place the rule is enforced — the auth middleware
187
+ * for `/<Table>/<id>` routes, and resources/relay-ops.ts for a Message POST to
188
+ * the collection that reuses an existing message id — so a refused caller gets
189
+ * the same response on either route, and it carries nothing from the stored
190
+ * row.
191
+ */
192
+ export function ownerMutationRefusal(table) {
193
+ return new Response(JSON.stringify({
194
+ error: `forbidden: cannot modify ${table} owned by another principal`,
195
+ }), { status: 403, headers: { "Content-Type": "application/json" } });
196
+ }
178
197
  /**
179
198
  * Decide whether a caller may CHANGE the owner field of an already-stored record.
180
199
  *
@@ -217,8 +217,17 @@ export function makeByIdReadGate(readScope) {
217
217
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
218
218
  return superGet(target);
219
219
  }
220
- // Non-admin agent: scoped per the table's own read-scope model.
221
- const record = await superGet(target);
220
+ // Non-admin agent: scoped per the table's own read-scope model. The scope
221
+ // is evaluated on the UNSELECTED row: the gate passes super.get a fresh plain
222
+ // object it builds itself, carrying only the id (or nothing, when the target
223
+ // has no id), and checks the row that returns. In Harper's default instance
224
+ // mode the resource is loaded by id before get runs, and get returns that
225
+ // whole record when the target carries no select or property. The caller's
226
+ // target, and anything its class does when constructed, never shapes the row
227
+ // the decision sees. A target that asks for a selection or a single property
228
+ // gets that shaped result only once the unselected row passes.
229
+ const shaped = typeof target === "object" && target !== null && (target.select != null || target.property != null);
230
+ const record = await superGet(targetId != null ? { id: targetId } : {});
222
231
  if (!record) {
223
232
  // Row did not load: either it genuinely does not exist, OR — the #1181
224
233
  // failure — a by-id read reached here on an unloaded instance and
@@ -237,7 +246,7 @@ export function makeByIdReadGate(readScope) {
237
246
  });
238
247
  return NOT_FOUND();
239
248
  }
240
- return record;
249
+ return shaped ? superGet(target) : record;
241
250
  };
242
251
  }
243
252
  // ─── (c) Scoped search — makeScopedSearch ────────────────────────────────
@@ -265,28 +274,40 @@ export function makeScopedSearch(readScope) {
265
274
  return async function scopedSearch(agentId, query, superSearch) {
266
275
  const scope = await readScope(agentId);
267
276
  const agentCondition = scope.condition;
268
- // Object with a conditions array — nest caller's conditions inside the
269
- // scope condition as the outermost AND block so a caller-supplied
270
- // `operator: "or"` cannot boolean-inject past the owner scope.
277
+ // The caller's conditions as an array. Harper accepts `conditions` as an
278
+ // array, any other iterable of conditions (it applies Array.from), or a
279
+ // single condition object; all are kept.
280
+ const isConditionIterable = (v) => !!v && typeof v === "object" && typeof v[Symbol.iterator] === "function" && !(v instanceof URLSearchParams);
281
+ const callerConditions = (list) => Array.isArray(list)
282
+ ? list
283
+ : isConditionIterable(list)
284
+ ? Array.from(list)
285
+ : list && typeof list === "object"
286
+ ? [list]
287
+ : [];
288
+ // The scope is always the OUTERMOST `and`, so a caller-supplied
289
+ // `operator: "or"` can only combine the caller's own conditions and never
290
+ // widens past the scope. A lone caller condition sits directly under that
291
+ // `and` (Harper's planner rejects a one-condition group); several keep the
292
+ // caller's operator inside their own group.
293
+ const compose = (conds, operator) => conds.length === 0
294
+ ? [agentCondition]
295
+ : conds.length === 1
296
+ ? [agentCondition, conds[0]]
297
+ : [agentCondition, { conditions: conds, operator: operator || "and" }];
298
+ // A bare iterable of conditions (not a RequestTarget, which is itself a
299
+ // URLSearchParams and carries its conditions on `.conditions`).
300
+ if (isConditionIterable(query) && !("conditions" in query)) {
301
+ return superSearch({ conditions: compose(Array.from(query), "and"), operator: "and" });
302
+ }
271
303
  if (query && typeof query === "object" && !Array.isArray(query)) {
272
- if (Array.isArray(query.conditions) && query.conditions.length > 0) {
273
- return superSearch({
274
- ...query,
275
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
276
- operator: "and",
277
- });
278
- }
279
- // No (or empty) conditions array — just scope, preserving other query
280
- // properties but NOT a caller-supplied operator (force "and").
281
- const { conditions: _c, operator: _o, ...rest } = query;
282
- return superSearch({ ...rest, conditions: [agentCondition], operator: "and" });
304
+ // Preserve other query properties (select, limit, sort, ...) but never a
305
+ // caller-supplied top-level operator.
306
+ const { conditions, operator, ...rest } = query;
307
+ return superSearch({ ...rest, conditions: compose(callerConditions(conditions), operator), operator: "and" });
283
308
  }
284
- // Plain array or no query — wrap in an object with operator "and" so
285
- // the scope condition is always the outermost AND.
286
- const conditions = Array.isArray(query) && query.length > 0
287
- ? [agentCondition, { conditions: query, operator: "and" }]
288
- : [agentCondition];
289
- return superSearch({ conditions, operator: "and" });
309
+ // Plain array or no query.
310
+ return superSearch({ conditions: compose(callerConditions(query), "and"), operator: "and" });
290
311
  };
291
312
  }
292
313
  export function stampAttribution(auth, content, field, mode, forbiddenMessage) {
@@ -101,9 +101,9 @@
101
101
  * explicitly deferred by Flint's post-slice-1 comment on #520 ("Sherlock
102
102
  * flagging stamp-default → stamp-strict convergence... Registry slice
103
103
  * follows" — convergence is a FUTURE decision, not made here). Each
104
- * sub-field is optional because not every table's write path calls
105
- * `stampAttribution` on both methods: Relationship has no post() override
106
- * at all (only `put`), so `attribution.post` is absent, not a placeholder.
104
+ * sub-field is optional because a table's write path need not call
105
+ * `stampAttribution` on both methods; an absent sub-field is not a
106
+ * placeholder.
107
107
  * The stamped attribute name is always `ownerField` above — no type uses a
108
108
  * different field for attribution vs. ownership scoping.
109
109
  *
@@ -291,9 +291,9 @@ export const RECORD_TYPES = {
291
291
  ownerField: "agentId",
292
292
  identity: "gated",
293
293
  readScope: "owner-only",
294
- // No `post` — Relationship.ts has no post() override at all; only
295
- // put() (upsert) calls stampAttribution.
296
- attribution: { put: "stamp-strict" },
294
+ // post() (a collection create) and put() (upsert) share one preparation
295
+ // (Relationship.ts's prepareRelationshipWrite), with the same mode.
296
+ attribution: { post: "stamp-strict", put: "stamp-strict" },
297
297
  provenance: true,
298
298
  remEligible: false,
299
299
  federation: "included",
@@ -9,6 +9,7 @@
9
9
  * All authorization decisions are made here against an already-resolved auth
10
10
  * verdict; the resource layer only resolves the verdict and forwards the call.
11
11
  */
12
+ import { isForbiddenOwnerMutation, ownerMutationRefusal, OWNER_FIELDS } from "./record-owner-guard.js";
12
13
  import { capDecision, computeContentHash, isUnconsumed, LOCAL_ORG_SENTINEL, reconcileState, sweepDecision, verifyMessageSignature, } from "./relay-lib.js";
13
14
  // ─── HTTP responses (Response is a web global, not a Harper import) ──────────
14
15
  const json = (status, obj) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json" } });
@@ -70,7 +71,11 @@ function acceptedView(row) {
70
71
  * per-sender sub-cap, and delivers. Returns the accepted envelope — the SAME
71
72
  * shape regardless of whether `to` exists (no existence oracle): the only
72
73
  * principal ever looked up is the sender (needed for its public key), which is
73
- * the authenticated caller and therefore always present.
74
+ * the authenticated caller and therefore always present. A send that reuses a
75
+ * stored message id is answered with that message's accepted view only when
76
+ * it has the same sender; any other sender gets the owner-guard 403
77
+ * (record-owner-guard.ts's ownerMutationRefusal), which carries no field of
78
+ * the stored message.
74
79
  */
75
80
  export async function relaySend(deps, auth, content) {
76
81
  if (auth.kind === "anonymous")
@@ -120,9 +125,29 @@ export async function relaySend(deps, auth, content) {
120
125
  // Retry-dedup: an identical resend — same primary id, or the same content
121
126
  // hash from this sender to this recipient — returns the already-accepted
122
127
  // envelope. No second row, and (critically) no second charge against the cap.
123
- const existingById = await Promise.resolve(deps.messages.get(String(content.id))).catch(() => null);
124
- if (existingById)
128
+ //
129
+ // The same-id answer is for the ORIGINAL SENDER only. A stored message is
130
+ // owned by its `from` (OWNER_FIELDS.Message), and this send's `from` is the
131
+ // verified signer. When the id is held by another sender, the send is
132
+ // refused with the owner-guard refusal — the same response the auth
133
+ // middleware gives a write to `/Message/<id>` for a message the caller does
134
+ // not own — and nothing from the stored row is returned. The rule is about
135
+ // the message, not the caller's role: an admin sending as X gets the same
136
+ // refusal for an id held by Y. The lookup fails CLOSED: if the stored row
137
+ // cannot be read, the send is refused the same way, never written over it.
138
+ let existingById;
139
+ try {
140
+ existingById = (await Promise.resolve(deps.messages.get(String(content.id)))) ?? null;
141
+ }
142
+ catch {
143
+ return ownerMutationRefusal("Message");
144
+ }
145
+ if (existingById) {
146
+ if (isForbiddenOwnerMutation(existingById, OWNER_FIELDS.Message, String(content.from))) {
147
+ return ownerMutationRefusal("Message");
148
+ }
125
149
  return acceptedView(existingById);
150
+ }
126
151
  // The recipient's inbox — queried by the @indexed `to`, never the whole table
127
152
  // (Sherlock P0). Serves both dedup (same content from this sender) and the cap.
128
153
  const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }]);