@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.
- package/README.md +4 -4
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1685 -279
- package/dist/commands/doctor.js +162 -4
- package/dist/commands/federation.js +2 -1
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +150 -44
- package/dist/commands/memory.js +24 -2
- package/dist/commands/quality.js +26 -18
- package/dist/commands/service.js +137 -22
- package/dist/commands/status.js +114 -3
- package/dist/commands/upgrade.js +204 -84
- package/dist/doctor-client.js +50 -4
- package/dist/federation/scheduler.js +253 -4
- package/dist/install/clients.js +89 -23
- package/dist/install/global-bin-path.js +26 -6
- package/dist/lib/atomic-write.js +256 -0
- package/dist/lib/daemon-liveness.js +61 -0
- package/dist/lib/doctor-run.js +5 -0
- package/dist/lib/embed-gpu-doctor.js +49 -26
- package/dist/lib/federation-memory-attributes.js +15 -0
- package/dist/lib/init-admin-pass.js +4 -2
- package/dist/lib/init-listener-environ.js +38 -0
- package/dist/lib/init-occupied-listener.js +165 -0
- package/dist/lib/launchd-domain-preflight.js +448 -0
- package/dist/lib/launchd-management.js +176 -6
- package/dist/lib/launchd-repair.js +95 -0
- package/dist/lib/memory-attributes.js +77 -0
- package/dist/lib/node-alias-path.js +95 -0
- package/dist/lib/npm-registry.js +119 -6
- package/dist/lib/owned-pins.js +20 -6
- package/dist/lib/service-repoint-apply.js +267 -0
- package/dist/lib/service-repoint.js +575 -0
- package/dist/lib/toml-string-array.js +104 -0
- package/dist/lib/tree-divergence.js +716 -0
- package/dist/lib/upgrade-plain-tree.js +18 -8
- package/dist/lib/upgrade-prior-liveness.js +69 -0
- package/dist/lib/upgrade-rollback.js +116 -0
- package/dist/rem/runner.js +11 -0
- package/dist/resources/Agent.js +27 -14
- package/dist/resources/AgentSeed.js +35 -1
- package/dist/resources/Federation.js +70 -52
- package/dist/resources/Memory.js +567 -72
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +4 -0
- package/dist/resources/MemoryFeed.js +204 -3
- package/dist/resources/MemoryHostSource.js +90 -0
- package/dist/resources/MemoryMaintenance.js +121 -32
- package/dist/resources/MemoryReflect.js +4 -1
- package/dist/resources/MemoryReindex.js +7 -4
- package/dist/resources/MemoryUsage.js +53 -3
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +167 -78
- package/dist/resources/SemanticSearch.js +19 -6
- package/dist/resources/Soul.js +31 -19
- package/dist/resources/XAA.js +7 -3
- package/dist/resources/agent-auth.js +16 -10
- package/dist/resources/auth-middleware.js +135 -48
- package/dist/resources/auto-promote-lib.js +4 -4
- package/dist/resources/bm25-index-service.js +246 -32
- package/dist/resources/bm25-status.js +132 -0
- package/dist/resources/ed25519-auth.js +11 -54
- package/dist/resources/embed-gpu.js +262 -47
- package/dist/resources/embeddings-boot.js +52 -17
- package/dist/resources/federation-classify.js +12 -0
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +57 -14
- package/dist/resources/host-pointer/registry.js +35 -0
- package/dist/resources/host-pointer-adapter.js +15 -0
- package/dist/resources/host-source-visibility.js +167 -0
- package/dist/resources/host-source.js +151 -0
- package/dist/resources/instance-identity.js +3 -2
- package/dist/resources/mcp-handler.js +147 -51
- package/dist/resources/mcp-tools.js +25 -21
- package/dist/resources/memory-consolidate-lib.js +3 -1
- package/dist/resources/memory-declared-attributes.js +103 -0
- package/dist/resources/memory-feed-lib.js +5 -1
- package/dist/resources/memory-host-source.js +163 -0
- package/dist/resources/migrations/synthetic-test-migration.js +4 -1
- package/dist/resources/migrations/visibility-backfill.js +4 -1
- package/dist/resources/originator-instance.js +235 -0
- package/dist/resources/promotion-stamp.js +2 -0
- package/dist/resources/provenance.js +111 -11
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +9 -12
- package/dist/resources/record-types.js +6 -6
- package/dist/resources/relay-ops.js +28 -3
- package/dist/resources/replay-store.js +289 -0
- package/dist/resources/request-transaction.js +78 -0
- package/dist/resources/search-readiness.js +19 -21
- package/dist/resources/semantic-retrieval-core.js +5 -1
- package/dist/resources/table-patch-policy.js +109 -0
- package/dist/resources/table-patches.js +17 -0
- package/dist/resources/table-post-policy.js +138 -0
- package/dist/resources/table-posts.js +22 -0
- package/dist/resources/table-subscription-policy.js +135 -0
- package/dist/resources/table-subscriptions.js +19 -0
- package/dist/resources/tool-descriptors/index.js +15 -15
- package/dist/resources/trust-block.js +10 -3
- package/dist/resources/usage-recording.js +169 -41
- package/dist/src/lib/memory-attributes.js +77 -0
- package/docs/api-reference.md +79 -15
- package/docs/claude-code.md +132 -0
- package/docs/deployment.md +1 -1
- package/docs/federation.md +1 -1
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +11 -21
- package/docs/notes/mcp-oauth-model2.md +15 -1
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/supply-chain-policy.md +10 -5
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +187 -61
- package/package.json +9 -5
- package/schemas/agent.graphql +9 -6
- package/schemas/federation.graphql +2 -11
- package/schemas/memory.graphql +106 -17
- package/schemas/replay.graphql +18 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
- package/dist/resources/federation-nonce-store.js +0 -195
|
@@ -86,6 +86,15 @@ export class MemoryArchive extends Resource {
|
|
|
86
86
|
delete merged.archivedAt;
|
|
87
87
|
delete merged.archivedBy;
|
|
88
88
|
}
|
|
89
|
+
// flair#1940 A3 (item 9): the record we read was PROJECTED — for the author
|
|
90
|
+
// it carries the canonical pointer with the URL query/fragment STRIPPED,
|
|
91
|
+
// and for a non-author it may read "withheld". Writing any of that back
|
|
92
|
+
// would replace the stored pointer (losing the full URL) or store a bogus
|
|
93
|
+
// value, and would re-derive the scope. Omit every pointer field from the
|
|
94
|
+
// write-back so the stored pointer row, its full URL and its scope stand.
|
|
95
|
+
delete merged.hostSource;
|
|
96
|
+
delete merged.hostSourceScope;
|
|
97
|
+
delete merged.hostSourceVisibility;
|
|
89
98
|
// Write back — Memory.put()'s ownership gate applies (stampAttribution), so
|
|
90
99
|
// a non-admin caller cannot flip another agent's memory (403).
|
|
91
100
|
const result = await Memory.put(merged, ctx);
|
|
@@ -263,6 +263,10 @@ const MAX_CANDIDATE_POOL = 100;
|
|
|
263
263
|
// `m._source !== agentId` is the "is this a teammate's finding" check; own
|
|
264
264
|
// memories never carry `_source` at all.
|
|
265
265
|
function formatMemory(m, agentId) {
|
|
266
|
+
// flair#1940 A1' item 5: bootstrap does NOT render pointers in this slice.
|
|
267
|
+
// The pointer lives in MemoryHostSource and is joined only into Memory.get/
|
|
268
|
+
// search/SemanticSearch results; the bootstrap citation (A6) arrives in slice
|
|
269
|
+
// 4. So this surface leaves the record unchanged.
|
|
266
270
|
const tag = m.durability === "permanent" ? "🔒" : m.durability === "persistent" ? "📌" : "📝";
|
|
267
271
|
const date = m.createdAt ? ` (${m.createdAt.slice(0, 10)})` : "";
|
|
268
272
|
const chain = m.supersedes ? " [supersedes earlier decision]" : "";
|
|
@@ -8,6 +8,11 @@ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VI
|
|
|
8
8
|
import { assertValidDurability } from "./memory-durability.js";
|
|
9
9
|
import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
|
|
10
10
|
import { noteMemoryUpsert } from "./bm25-index-service.js";
|
|
11
|
+
import { extractPointerInputs } from "./memory-host-source.js";
|
|
12
|
+
import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
13
|
+
import { buildProvenance } from "./provenance.js";
|
|
14
|
+
import { applyFederationBookkeeping, applyOriginatorInstanceId } from "./originator-instance.js";
|
|
15
|
+
import { resolveReadScope } from "./memory-read-scope.js";
|
|
11
16
|
export class FeedMemories extends Resource {
|
|
12
17
|
// Self-authorize via the Ed25519 agent verify (the auth reshape removes the
|
|
13
18
|
// gate's admin elevation).
|
|
@@ -165,19 +170,215 @@ export class FeedMemories extends Resource {
|
|
|
165
170
|
if (record.durability === "ephemeral" && (record.visibility === undefined || record.visibility === null)) {
|
|
166
171
|
record.visibility = PRIVATE_VISIBILITY;
|
|
167
172
|
}
|
|
173
|
+
// flair#1940 A1' item 1: the feed ingest is a Memory writer too. Drop any
|
|
174
|
+
// pointer inputs (hostSource/hostSourceScope/hostSourceVisibility) and every
|
|
175
|
+
// undeclared attribute here. These paths discard the supplied pointer input
|
|
176
|
+
// and create no pointer row; an existing pointer row stays bound to the
|
|
177
|
+
// updated Memory.
|
|
178
|
+
extractPointerInputs(record);
|
|
179
|
+
stripUndeclaredMemoryAttributes(record);
|
|
168
180
|
stripAuthorityFields(record, "Memory");
|
|
181
|
+
// A1-iv items 1/3: the feed ingest is a Memory writer too — strip a
|
|
182
|
+
// caller-supplied server-stamped field (instanceToken, provenance), then
|
|
183
|
+
// PRESERVE the existing row's incarnation token, else generate one.
|
|
184
|
+
stripServerStampedFields(record);
|
|
185
|
+
// flair#1940 A1-iv item 1: a failed existing-row lookup must FAIL the write,
|
|
186
|
+
// not fall back to a fresh token — rotating the token would hide a still-
|
|
187
|
+
// stored pointer row that is bound to the stored token (the same fail-closed
|
|
188
|
+
// rule #1956 applies to put()). No `.catch`: the rejection propagates.
|
|
189
|
+
const priorById = await databases.flair.Memory.get(record.id);
|
|
190
|
+
record.instanceToken = priorById?.instanceToken ?? randomUUID();
|
|
191
|
+
// Feed ingest is a full-row write: it REPLACES the stored row, so a
|
|
192
|
+
// re-ingest with new content is a semantic re-authoring. Re-stamp
|
|
193
|
+
// provenance from the resolved (trusted) identity and ONE server clock read
|
|
194
|
+
// (inside buildProvenance) rather than carrying the stored blob forward — a
|
|
195
|
+
// legacy row whose `verified.timestamp` came from a client `createdAt` must
|
|
196
|
+
// not keep presenting that value after a new write (flair#1960 r2). The feed
|
|
197
|
+
// body's own `createdAt` is recorded only as the CLAIM
|
|
198
|
+
// `provenance.claimed.createdAt`, never as a verified timestamp. The
|
|
199
|
+
// incarnation token is still preserved above (a re-ingest is not a
|
|
200
|
+
// reincarnation), so only `provenance` is re-derived.
|
|
201
|
+
record.provenance = buildProvenance(auth, record.createdAt, content);
|
|
202
|
+
// flair#1965 r2: this raw table put REPLACES the row, bypassing the Memory
|
|
203
|
+
// resource's write methods, so the create/update rule is applied here
|
|
204
|
+
// explicitly: a CREATE (no stored row) stamps this instance's own id and
|
|
205
|
+
// ignores any body value; an UPDATE keeps the STORED value (a body value
|
|
206
|
+
// neither replaces nor clears it). The receiver-side federation bookkeeping
|
|
207
|
+
// (`_originatorInstanceId` et al.) is likewise unsettable from a body — it
|
|
208
|
+
// stands as stored, or is dropped on a create. See
|
|
209
|
+
// resources/originator-instance.ts.
|
|
210
|
+
await applyOriginatorInstanceId(record, priorById);
|
|
211
|
+
applyFederationBookkeeping(record, priorById);
|
|
169
212
|
await databases.flair.Memory.put(record);
|
|
170
213
|
// flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
|
|
171
214
|
noteMemoryUpsert(record);
|
|
172
215
|
return record;
|
|
173
216
|
}
|
|
217
|
+
// Subscription admission: verified agents, admins and trusted internal
|
|
218
|
+
// calls; anonymous HTTP is refused (the same gate as FeedSouls). Admission is
|
|
219
|
+
// decided here, by the caller's resolved identity, not by which Harper user
|
|
220
|
+
// the request carries. What a subscriber then RECEIVES is decided per record
|
|
221
|
+
// in connect() below.
|
|
222
|
+
async allowRead() {
|
|
223
|
+
return allowVerified(this.getContext?.());
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* A non-admin subscriber receives a Memory event only when
|
|
227
|
+
* `resolveReadScope(agentId).isAllowed(record)` allows the record the event
|
|
228
|
+
* is decided from: the predicate Memory.get()/search() use (the reader's own
|
|
229
|
+
* records at any visibility, plus every other agent's non-private records).
|
|
230
|
+
* Admin agents and trusted internal calls are unfiltered, as before. The
|
|
231
|
+
* request for a scoped subscription is built here from an allowlist of the
|
|
232
|
+
* caller's options (see SUBSCRIPTION_OPTIONS: the record id, descendants,
|
|
233
|
+
* and replay), and the server's `rowFilter` is set last; no caller-supplied
|
|
234
|
+
* filter, `rawEvents`, `select` or unknown option reaches it.
|
|
235
|
+
*
|
|
236
|
+
* Two layers decide what a non-admin subscriber receives:
|
|
237
|
+
*
|
|
238
|
+
* 1. Harper's synchronous `SubscriptionRequest.rowFilter`, set to the
|
|
239
|
+
* predicate. In the pinned Harper (5.2.8) the filter is evaluated on the
|
|
240
|
+
* full stored row for the rows replayed when the subscription opens, for
|
|
241
|
+
* every live change (an update is re-read from the primary store and
|
|
242
|
+
* delivered as a full-row `put`) and for reload re-deliveries; a history
|
|
243
|
+
* replay (`startTime`, `previousCount`) is evaluated on each earlier
|
|
244
|
+
* version of the row as it was stored. An event with no stored row (a delete tombstone, a published message,
|
|
245
|
+
* a raw event) is withheld from a filtered subscriber. This layer holds
|
|
246
|
+
* only where the host Harper honours `rowFilter`.
|
|
247
|
+
*
|
|
248
|
+
* 2. The loop below (see readableRowEvent()), which does not rely on
|
|
249
|
+
* `rowFilter`. It delivers only a `put` or `invalidate` event whose value
|
|
250
|
+
* is an object; every other event is withheld. When that object carries a
|
|
251
|
+
* string `agentId` and a defined `visibility`, the predicate decides from
|
|
252
|
+
* those two fields of the event. Otherwise the stored row is re-read by
|
|
253
|
+
* the event id and the predicate decides from the stored row; the event is
|
|
254
|
+
* withheld when it has no id, when the re-read throws, or when the re-read
|
|
255
|
+
* returns anything other than an object with a string `agentId`. When the
|
|
256
|
+
* subscription asked for `startTime` or `previousCount`, every event also
|
|
257
|
+
* needs the record's current stored row, re-read by id, to be readable
|
|
258
|
+
* (see storedRowReadable()).
|
|
259
|
+
*/
|
|
174
260
|
async *connect(target, incomingMessages) {
|
|
175
|
-
const
|
|
176
|
-
if (
|
|
177
|
-
|
|
261
|
+
const auth = await resolveAgentAuth(this.getContext?.());
|
|
262
|
+
if (auth.kind === "anonymous") {
|
|
263
|
+
// allowRead() refuses anonymous HTTP before connect() runs; this is the
|
|
264
|
+
// in-process backstop.
|
|
265
|
+
throw Object.assign(new Error("authentication required"), { statusCode: 401 });
|
|
178
266
|
}
|
|
267
|
+
if (auth.kind === "internal" || auth.isAdmin) {
|
|
268
|
+
const subscription = await databases.flair.Memory.subscribe(target);
|
|
269
|
+
if (!incomingMessages) {
|
|
270
|
+
return subscription;
|
|
271
|
+
}
|
|
272
|
+
for await (const event of subscription) {
|
|
273
|
+
yield event;
|
|
274
|
+
}
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const scope = await resolveReadScope(auth.agentId);
|
|
278
|
+
// The caller's subscription request is connect()'s second argument in
|
|
279
|
+
// instance mode and its first when loadAsInstance is false, the same choice
|
|
280
|
+
// Harper's own Resource.connect() makes.
|
|
281
|
+
const callerRequest = this.constructor.loadAsInstance === false ? target : incomingMessages;
|
|
282
|
+
const request = scopedSubscriptionRequest(callerRequest, (record) => scope.isAllowed(record));
|
|
283
|
+
const subscription = await databases.flair.Memory.subscribe(request);
|
|
284
|
+
const readStored = (id) => databases.flair.Memory.get(id);
|
|
285
|
+
const replaysHistory = request.startTime !== undefined || request.previousCount !== undefined;
|
|
179
286
|
for await (const event of subscription) {
|
|
287
|
+
if (!(await readableRowEvent(event, scope.isAllowed, readStored)))
|
|
288
|
+
continue;
|
|
289
|
+
if (replaysHistory && !(await storedRowReadable(event?.id, scope.isAllowed, readStored)))
|
|
290
|
+
continue;
|
|
180
291
|
yield event;
|
|
181
292
|
}
|
|
182
293
|
}
|
|
183
294
|
}
|
|
295
|
+
/**
|
|
296
|
+
* The options a non-admin caller's subscription request may carry into the
|
|
297
|
+
* table subscription, each with the type it must have. These are the options
|
|
298
|
+
* Harper's `Table.subscribe` reads to choose WHICH record ids it follows and
|
|
299
|
+
* WHAT it replays before live events: `id` (one record), `isCollection` and
|
|
300
|
+
* `onlyChildren` (a record's descendants), and `startTime`, `previousCount`
|
|
301
|
+
* and `omitCurrent` (the replay). None of them widens what the read predicate
|
|
302
|
+
* allows. Every other property is dropped, including any filter, `rowFilter`,
|
|
303
|
+
* `eventFilter`, `select`, `rawEvents`, `listener` and any unknown option.
|
|
304
|
+
*/
|
|
305
|
+
const SUBSCRIPTION_OPTIONS = Object.freeze({
|
|
306
|
+
id: (value) => typeof value === "string" ||
|
|
307
|
+
(typeof value === "number" && Number.isFinite(value)) ||
|
|
308
|
+
(Array.isArray(value) && value.every((part) => part === null || typeof part === "string" || typeof part === "number")),
|
|
309
|
+
isCollection: (value) => typeof value === "boolean",
|
|
310
|
+
onlyChildren: (value) => typeof value === "boolean",
|
|
311
|
+
startTime: (value) => typeof value === "number" && Number.isFinite(value),
|
|
312
|
+
previousCount: (value) => typeof value === "number" && Number.isFinite(value),
|
|
313
|
+
omitCurrent: (value) => typeof value === "boolean",
|
|
314
|
+
});
|
|
315
|
+
/**
|
|
316
|
+
* Build the scoped subscription request: the allowlisted options the caller
|
|
317
|
+
* supplied with the expected type, then the server-owned `rowFilter`, set last.
|
|
318
|
+
*/
|
|
319
|
+
function scopedSubscriptionRequest(callerRequest, rowFilter) {
|
|
320
|
+
const request = {};
|
|
321
|
+
if (callerRequest != null && typeof callerRequest === "object") {
|
|
322
|
+
for (const [option, hasExpectedType] of Object.entries(SUBSCRIPTION_OPTIONS)) {
|
|
323
|
+
const value = callerRequest[option];
|
|
324
|
+
if (value !== undefined && hasExpectedType(value))
|
|
325
|
+
request[option] = value;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
request.rowFilter = rowFilter;
|
|
329
|
+
return request;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* The scoped memory feed's second layer: may this event reach the reader?
|
|
333
|
+
*
|
|
334
|
+
* - Only a `put` or `invalidate` event whose value is an object is a
|
|
335
|
+
* candidate; every other event (a delete, a message, a `put` without an
|
|
336
|
+
* object value) is withheld.
|
|
337
|
+
* - The read predicate reads `agentId` and `visibility`. If the event's value
|
|
338
|
+
* carries a string `agentId` and a defined `visibility`, the predicate
|
|
339
|
+
* decides from those two fields.
|
|
340
|
+
* - Otherwise (a partial value, or a row stored without a `visibility` field)
|
|
341
|
+
* the stored row is re-read by the event id, and the predicate decides from
|
|
342
|
+
* the stored row. The event is withheld when it has no id, when the re-read
|
|
343
|
+
* throws, or when the re-read returns anything other than an object with a
|
|
344
|
+
* string `agentId`.
|
|
345
|
+
*
|
|
346
|
+
* The event itself is what is delivered; the stored row is only the input to
|
|
347
|
+
* the decision.
|
|
348
|
+
*/
|
|
349
|
+
async function readableRowEvent(event, isAllowed, readStored) {
|
|
350
|
+
if (!event || (event.type !== "put" && event.type !== "invalidate"))
|
|
351
|
+
return false;
|
|
352
|
+
const row = event.value;
|
|
353
|
+
if (row == null || typeof row !== "object")
|
|
354
|
+
return false;
|
|
355
|
+
if (typeof row.agentId === "string" && row.visibility !== undefined)
|
|
356
|
+
return isAllowed(row);
|
|
357
|
+
return storedRowReadable(event.id, isAllowed, readStored);
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Re-read the stored row by id and apply the read predicate to it. An absent
|
|
361
|
+
* id, a read that throws, or a result that is not an object with a string
|
|
362
|
+
* `agentId` returns false.
|
|
363
|
+
*
|
|
364
|
+
* Also used for every event of a subscription that asked for `startTime` or
|
|
365
|
+
* `previousCount`: Harper then replays earlier versions of a record, and each
|
|
366
|
+
* version carries its own `agentId` and `visibility`. Such an event reaches a
|
|
367
|
+
* non-admin subscriber only when the record's current stored row is readable
|
|
368
|
+
* too, so a record that is private or deleted now is not replayed from its
|
|
369
|
+
* earlier versions.
|
|
370
|
+
*/
|
|
371
|
+
async function storedRowReadable(id, isAllowed, readStored) {
|
|
372
|
+
if (id == null)
|
|
373
|
+
return false;
|
|
374
|
+
let stored;
|
|
375
|
+
try {
|
|
376
|
+
stored = await readStored(id);
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
if (stored == null || typeof stored !== "object" || typeof stored.agentId !== "string")
|
|
382
|
+
return false;
|
|
383
|
+
return isAllowed(stored);
|
|
384
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MemoryHostSource.ts — the resource class for the host-pointer table
|
|
3
|
+
* (flair#1940 slice 1 / A1' item 3). The pointer lives in its own table,
|
|
4
|
+
* keyed by memoryId. Supported writes store host pointers only in `MemoryHostSource`:
|
|
5
|
+
* a pointer reaches a non-admin reader only through the gated join. For non-admin
|
|
6
|
+
* `Memory.get`, `Memory.search`, and `SemanticSearch` results, the gated projection
|
|
7
|
+
* removes inline pointer fields and renders a pointer only from a bound
|
|
8
|
+
* `MemoryHostSource` row.
|
|
9
|
+
*
|
|
10
|
+
* READ — Direct resource reads permit admin agents and trusted in-process callers;
|
|
11
|
+
* non-admin agents cannot read this table directly. Bare `@export`
|
|
12
|
+
* (schemas/memory.graphql) would otherwise
|
|
13
|
+
* reach Harper's default allow-decision (super_user passthrough), reachable by
|
|
14
|
+
* the forged-loopback super_user and, once the global gate is non-rejecting, by
|
|
15
|
+
* a genuinely anonymous remote caller. So allowRead/get/search gate on the
|
|
16
|
+
* authenticated principal: internal calls and admin agents pass; a non-admin by-id
|
|
17
|
+
* get returns 404; search returns 403; neither reveals whether a particular
|
|
18
|
+
* pointer row exists. The author
|
|
19
|
+
* reads their own pointer only through the gated join INTO Memory results
|
|
20
|
+
* (resources/Memory.ts) — never from this table directly.
|
|
21
|
+
*
|
|
22
|
+
* WRITE — there are NO REST write verbs. post/put/patch and delete are refused
|
|
23
|
+
* for EVERY caller (admin included), with a message naming the Memory write
|
|
24
|
+
* path (A1'' item 3) — proved over real HTTP for non-admin AND admin (r4-http).
|
|
25
|
+
* Application pointer writes use `Memory.post` or `Memory.put`; trusted operator
|
|
26
|
+
* table operations remain available. A superuser Harper operation against the
|
|
27
|
+
* table (an operator export, backup
|
|
28
|
+
* or reseed) is the operator path, not gated by this resource.
|
|
29
|
+
*/
|
|
30
|
+
import { databases } from "harper";
|
|
31
|
+
import { resolveAgentAuth } from "./agent-auth.js";
|
|
32
|
+
import { resolveAuthGate, FORBIDDEN, UNAUTH, NOT_FOUND } from "./record-type-kit.js";
|
|
33
|
+
/** The admin-only read gate: internal calls and admin agents pass; every
|
|
34
|
+
* non-admin agent is denied. Wired as a genuine prototype method. */
|
|
35
|
+
async function adminOnlyReadGate() {
|
|
36
|
+
const auth = await resolveAgentAuth(this.getContext?.());
|
|
37
|
+
return auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin);
|
|
38
|
+
}
|
|
39
|
+
export class MemoryHostSource extends databases.flair.MemoryHostSource {
|
|
40
|
+
allowRead() {
|
|
41
|
+
return adminOnlyReadGate.call(this);
|
|
42
|
+
}
|
|
43
|
+
/** A by-id read: admin/internal pass; a non-admin agent gets NOT_FOUND
|
|
44
|
+
* (never a 403 existence oracle for "does this memory have a pointer"). */
|
|
45
|
+
async get(target) {
|
|
46
|
+
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
47
|
+
return this.search(target);
|
|
48
|
+
}
|
|
49
|
+
const gate = await resolveAuthGate(this.getContext?.(), UNAUTH());
|
|
50
|
+
if (gate.kind === "denied")
|
|
51
|
+
return gate.response;
|
|
52
|
+
if (gate.kind === "unfiltered")
|
|
53
|
+
return super.get(target);
|
|
54
|
+
return NOT_FOUND();
|
|
55
|
+
}
|
|
56
|
+
/** A collection read/search: admin/internal pass; a non-admin agent is
|
|
57
|
+
* refused (403). */
|
|
58
|
+
async search(query) {
|
|
59
|
+
const gate = await resolveAuthGate(this.getContext?.(), UNAUTH());
|
|
60
|
+
if (gate.kind === "denied")
|
|
61
|
+
return gate.response;
|
|
62
|
+
if (gate.kind === "unfiltered")
|
|
63
|
+
return super.search(query);
|
|
64
|
+
return FORBIDDEN("forbidden: MemoryHostSource is admin-only");
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* A1'' item 3 — MemoryHostSource has NO REST write verbs. A pointer row is
|
|
68
|
+
* written ONLY by Memory's own write path (POST/PUT /Memory), through the
|
|
69
|
+
* table object, inside the same request transaction. Every caller is refused
|
|
70
|
+
* here — admin included — with the same message naming that path, so no REST
|
|
71
|
+
* caller can plant a pointer on another agent's memory (which is what item 3
|
|
72
|
+
* replaces: the old resource-side stamp had no business existing).
|
|
73
|
+
*/
|
|
74
|
+
async post(_content) {
|
|
75
|
+
return writelessRefusal();
|
|
76
|
+
}
|
|
77
|
+
async put(_content) {
|
|
78
|
+
return writelessRefusal();
|
|
79
|
+
}
|
|
80
|
+
async patch(_content, _query) {
|
|
81
|
+
return writelessRefusal();
|
|
82
|
+
}
|
|
83
|
+
async delete(_id) {
|
|
84
|
+
return writelessRefusal();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** The fixed refusal every REST write verb on MemoryHostSource returns. */
|
|
88
|
+
function writelessRefusal() {
|
|
89
|
+
return FORBIDDEN("MemoryHostSource REST writes are disabled; use POST/PUT `/Memory` for application pointer writes");
|
|
90
|
+
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* POST /MemoryMaintenance — runs cleanup tasks:
|
|
5
5
|
* 1. Delete expired ephemeral memories (expiresAt < now)
|
|
6
|
-
* 2. Archive old session memories (> 30 days, standard durability)
|
|
6
|
+
* 2. Archive validTo-expired memories and old session memories (> 30 days, standard durability)
|
|
7
7
|
* 3. Report stats
|
|
8
8
|
*
|
|
9
9
|
* Designed to run periodically (daily cron, scheduler, or REM nightly cycle).
|
|
@@ -17,8 +17,23 @@
|
|
|
17
17
|
* to gate auth correctly.
|
|
18
18
|
*/
|
|
19
19
|
import { Resource, databases } from "harper";
|
|
20
|
+
import { MEMORY_HOST_SOURCE_TABLE } from "./memory-host-source.js";
|
|
21
|
+
/** Maintenance creates an owned transaction for each expiry or archive item;
|
|
22
|
+
* the Memory and pointer operations join that owned transaction (both tables
|
|
23
|
+
* in database flair). Failures are NOT swallowed: a throw propagates to the
|
|
24
|
+
* caller's error path. A missing pointer table is REPORTED (throws), never
|
|
25
|
+
* silently skipped — cleanup is hygiene, so its failure must be visible. */
|
|
26
|
+
async function deletePointerRowOrThrow(memoryId, ctx) {
|
|
27
|
+
const table = databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
|
|
28
|
+
if (!table?.delete) {
|
|
29
|
+
throw new Error("MemoryHostSource table unavailable");
|
|
30
|
+
}
|
|
31
|
+
await table.delete(memoryId, ctx);
|
|
32
|
+
}
|
|
20
33
|
import { isAdmin } from "./agent-auth.js";
|
|
21
34
|
import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
|
|
35
|
+
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
36
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
22
37
|
export class MemoryMaintenance extends Resource {
|
|
23
38
|
/** POST requires auth — either an agent acting on its own memories, or admin. */
|
|
24
39
|
allowCreate() {
|
|
@@ -48,7 +63,7 @@ export class MemoryMaintenance extends Resource {
|
|
|
48
63
|
});
|
|
49
64
|
}
|
|
50
65
|
const now = new Date();
|
|
51
|
-
const stats = { expired: 0, archived: 0, total: 0, errors: 0, agent: targetAgent || "all" };
|
|
66
|
+
const stats = { expired: 0, archived: 0, total: 0, errors: 0, orphans: 0, agent: targetAgent || "all" };
|
|
52
67
|
try {
|
|
53
68
|
for await (const record of databases.flair.Memory.search()) {
|
|
54
69
|
// Skip records not belonging to target agent (unless admin running fleet-wide).
|
|
@@ -65,14 +80,21 @@ export class MemoryMaintenance extends Resource {
|
|
|
65
80
|
new Date(record.expiresAt) < now) {
|
|
66
81
|
if (!dryRun) {
|
|
67
82
|
try {
|
|
68
|
-
|
|
83
|
+
// A1'' item 2 (0c): the raw expiry delete runs in its OWN
|
|
84
|
+
// transaction together with the pointer delete, so a failed
|
|
85
|
+
// pointer delete aborts both and nothing is deleted.
|
|
86
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
87
|
+
await databases.flair.Memory.delete(record.id, c);
|
|
88
|
+
await deletePointerRowOrThrow(record.id, c);
|
|
89
|
+
});
|
|
69
90
|
// flair#1357 — ephemeral expiry removes the row from what the
|
|
70
91
|
// lexical leg may score.
|
|
71
92
|
noteMemoryDelete(record.id);
|
|
72
93
|
stats.expired++;
|
|
73
94
|
}
|
|
74
|
-
catch {
|
|
95
|
+
catch (err) {
|
|
75
96
|
stats.errors++;
|
|
97
|
+
console.error("MemoryMaintenance: expiry delete failed (aborted, nothing deleted)", err);
|
|
76
98
|
}
|
|
77
99
|
}
|
|
78
100
|
else {
|
|
@@ -80,37 +102,91 @@ export class MemoryMaintenance extends Resource {
|
|
|
80
102
|
}
|
|
81
103
|
continue;
|
|
82
104
|
}
|
|
83
|
-
// 2. Archive
|
|
84
|
-
//
|
|
105
|
+
// 2. Archive memories whose validity ended, plus old standard session
|
|
106
|
+
// notes (> 30 days) that weren't promoted to persistent. Use one
|
|
107
|
+
// archive path so a row meeting both criteria is counted only once.
|
|
85
108
|
// Soft-archive removes them from search results but keeps the data.
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
record.createdAt)
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
else {
|
|
109
|
+
const validToExpired = record.validTo && new Date(record.validTo) < now;
|
|
110
|
+
const oldSession = record.durability === "standard" &&
|
|
111
|
+
record.type === "session" && record.createdAt &&
|
|
112
|
+
now.getTime() - new Date(record.createdAt).getTime() > 30 * 24 * 3600_000;
|
|
113
|
+
if (!record.archived && (validToExpired || oldSession)) {
|
|
114
|
+
if (!dryRun) {
|
|
115
|
+
try {
|
|
116
|
+
const archivedRow = {
|
|
117
|
+
...record,
|
|
118
|
+
archived: true,
|
|
119
|
+
archivedAt: now.toISOString(),
|
|
120
|
+
};
|
|
121
|
+
stripUndeclaredMemoryAttributes(archivedRow);
|
|
122
|
+
// A1'' item 2 (0c): the archive write and its pointer delete
|
|
123
|
+
// share ONE OWNED transaction; a failed pointer delete cannot
|
|
124
|
+
// still commit the archived row.
|
|
125
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
126
|
+
await databases.flair.Memory.update(record.id, archivedRow, c);
|
|
127
|
+
await deletePointerRowOrThrow(record.id, c);
|
|
128
|
+
});
|
|
129
|
+
// flair#1357 — an `archived` flip changes what the retrieval
|
|
130
|
+
// conditions (`archived not_equal true`) admit, so the lexical
|
|
131
|
+
// index has to see it, not just content writes.
|
|
132
|
+
noteMemoryUpsert(archivedRow);
|
|
112
133
|
stats.archived++;
|
|
113
134
|
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
stats.errors++;
|
|
137
|
+
console.error("MemoryMaintenance: archive failed (aborted, nothing archived)", err);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
stats.archived++;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// 3. Orphan sweep: pointer rows whose Memory is MISSING or ARCHIVED. An
|
|
146
|
+
// orphan is unreadable by construction (the only read path joins pointers
|
|
147
|
+
// INTO Memory results), but it should not be left behind either. A
|
|
148
|
+
// failed row read or delete is counted and the sweep continues; the
|
|
149
|
+
// incomplete run is reported below (HTTP 500), never silently ignored.
|
|
150
|
+
const pointerTable = databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
|
|
151
|
+
if (!dryRun && !pointerTable?.search) {
|
|
152
|
+
// Hygiene: a missing sweep table is REPORTED, never silently skipped.
|
|
153
|
+
throw new Error("MemoryHostSource table unavailable (orphan sweep)");
|
|
154
|
+
}
|
|
155
|
+
if (pointerTable?.search && !dryRun) {
|
|
156
|
+
for await (const ptr of pointerTable.search()) {
|
|
157
|
+
const memoryId = ptr?.memoryId;
|
|
158
|
+
if (typeof memoryId !== "string" || memoryId.length === 0)
|
|
159
|
+
continue;
|
|
160
|
+
try {
|
|
161
|
+
const mem = await databases.flair.Memory.get(memoryId, ctx);
|
|
162
|
+
if (mem && mem.archived !== true)
|
|
163
|
+
continue;
|
|
164
|
+
// 0d: RE-CHECK inside an OWNED transaction before deleting. The
|
|
165
|
+
// first read is outside it, so a new row reusing this id in
|
|
166
|
+
// between must not be orphan-deleted; the conditional re-read
|
|
167
|
+
// inside the transaction closes that read-to-delete gap. The
|
|
168
|
+
// re-read is passed the owned transaction `c` (Gauge pass-5 item 2).
|
|
169
|
+
//
|
|
170
|
+
// Round 22: one orphan's failure must abort only THAT orphan, not
|
|
171
|
+
// the whole sweep — catch it, count stats.errors, and continue (the
|
|
172
|
+
// item loops above already work this way). stats.orphans counts a
|
|
173
|
+
// row only AFTER its owned transaction COMMITS (the count moves out
|
|
174
|
+
// of the callback). Pinned by test/unit/memory-host-source.test.ts
|
|
175
|
+
// (r22-orphan-continues) — RED if the try/catch is removed.
|
|
176
|
+
let committed = false;
|
|
177
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
178
|
+
const again = await databases.flair.Memory.get(memoryId, c);
|
|
179
|
+
if (!again || again.archived === true) {
|
|
180
|
+
await deletePointerRowOrThrow(memoryId, c);
|
|
181
|
+
committed = true;
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
if (committed)
|
|
185
|
+
stats.orphans++;
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
stats.errors++;
|
|
189
|
+
console.error("MemoryMaintenance: orphan sweep failed (continuing)", err);
|
|
114
190
|
}
|
|
115
191
|
}
|
|
116
192
|
}
|
|
@@ -118,6 +194,18 @@ export class MemoryMaintenance extends Resource {
|
|
|
118
194
|
catch (err) {
|
|
119
195
|
return new Response(JSON.stringify({ error: err.message, stats }), { status: 500, headers: { "content-type": "application/json" } });
|
|
120
196
|
}
|
|
197
|
+
// A1-iv item 4 (cleanup is hygiene): if any item's cleanup FAILED, the run
|
|
198
|
+
// is NOT complete — report a failure naming the counts, never a
|
|
199
|
+
// "Maintenance complete" success. The work already committed stands; the
|
|
200
|
+
// response is about the run's honesty.
|
|
201
|
+
if (stats.errors > 0) {
|
|
202
|
+
return new Response(JSON.stringify({
|
|
203
|
+
error: "maintenance_incomplete",
|
|
204
|
+
message: `${stats.errors} cleanup error(s); see counts`,
|
|
205
|
+
stats, expired: stats.expired, archived: stats.archived, total: stats.total,
|
|
206
|
+
errors: stats.errors, orphans: stats.orphans,
|
|
207
|
+
}), { status: 500, headers: { "content-type": "application/json" } });
|
|
208
|
+
}
|
|
121
209
|
// Flatten the historical { stats } wrapper into the top level so callers
|
|
122
210
|
// can read `.expired` / `.archived` directly. The wrapper shape is kept
|
|
123
211
|
// for backward compatibility with `flair rem light`.
|
|
@@ -128,6 +216,7 @@ export class MemoryMaintenance extends Resource {
|
|
|
128
216
|
archived: stats.archived,
|
|
129
217
|
total: stats.total,
|
|
130
218
|
errors: stats.errors,
|
|
219
|
+
orphans: stats.orphans,
|
|
131
220
|
};
|
|
132
221
|
}
|
|
133
222
|
}
|
|
@@ -54,6 +54,7 @@ import { isAdmin, allowVerified } from "./agent-auth.js";
|
|
|
54
54
|
import { patchRecordSilent } from "./table-helpers.js";
|
|
55
55
|
import { buildReflectionPrompt, buildExecutePrompt, resolveReflectActor, generateCandidates, releaseRequestTransaction, runExecuteDistillation, dedupeCandidates, memoryMatchesReflectScope, buildStagedCandidateRow, isContinuityScopeTag, filterStaleSessionIntentCandidates, resolveCandidateVisibilityRuling, considerForOldestUnreflectedCap, isRemAbortRequested, resolveMaxMemoriesPerRun, shouldStampLastReflected, DEFAULT_STALE_INTENT_HORIZON_MS, REM_GATHER_YIELD_BUDGET_MS, } from "./memory-reflect-lib.js";
|
|
56
56
|
import { reflectModelsGenerate } from "./memory-reflect-models.js";
|
|
57
|
+
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
57
58
|
/** Same path `flair rem pause` writes. Duplicated across the src/ boundary. */
|
|
58
59
|
const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
|
|
59
60
|
const GATHER_SELECT = [
|
|
@@ -292,7 +293,9 @@ export class ReflectMemories extends Resource {
|
|
|
292
293
|
if (shouldStampLastReflected({ execute, generateSucceeded: true })) {
|
|
293
294
|
const now = new Date().toISOString();
|
|
294
295
|
for (const memory of memories) {
|
|
295
|
-
|
|
296
|
+
const reflectPatch = { lastReflected: now };
|
|
297
|
+
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
298
|
+
patchRecordSilent(databases.flair.Memory, memory.id, reflectPatch);
|
|
296
299
|
}
|
|
297
300
|
}
|
|
298
301
|
return {
|
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
* compares per-agent primary counts against per-agent secondary-index counts
|
|
12
12
|
* (an equals lookup on agentId). Any agent whose secondary count is below
|
|
13
13
|
* its primary count has unindexed records. Re-PUT every record with the
|
|
14
|
-
* _reindex escape hatch
|
|
15
|
-
*
|
|
14
|
+
* _reindex escape hatch: Memory.put() retains declared and named allowed
|
|
15
|
+
* fields, restores stored provenance and preserves an existing incarnation
|
|
16
|
+
* token (or generates an absent one). Other undeclared fields are stripped.
|
|
17
|
+
* No updatedAt bump, embedding regeneration or safety rescan is performed.
|
|
16
18
|
*
|
|
17
19
|
* Why this exists: Harper's background runIndexing() pass populates secondary
|
|
18
20
|
* indices only on schema changes that add a new indexed attribute. If that
|
|
@@ -102,8 +104,9 @@ export class MemoryReindex extends Resource {
|
|
|
102
104
|
stats,
|
|
103
105
|
};
|
|
104
106
|
}
|
|
105
|
-
// Pass 3: re-PUT every primary-store record with _reindex=true
|
|
106
|
-
//
|
|
107
|
+
// Pass 3: re-PUT every primary-store record with _reindex=true, retaining
|
|
108
|
+
// declared/named fields and stored provenance, stripping other undeclared
|
|
109
|
+
// fields and generating an absent token. The re-PUT forces Harper to re-insert
|
|
107
110
|
// into all secondary indices. Cheaper-than-sound variants (only re-PUT records
|
|
108
111
|
// that appear missing) would miss rows the primary scan sees fine but that
|
|
109
112
|
// Harper's read path can't locate via any index path.
|