@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.
- package/README.md +19 -20
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1800 -293
- package/dist/commands/agent.js +22 -15
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +214 -4
- package/dist/commands/federation.js +265 -38
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +179 -48
- 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/auth-resolve.js +46 -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/instance-identity-row.js +580 -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/redact-token-id.js +197 -0
- 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 +39 -2
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +299 -127
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +623 -86
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +23 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +214 -5
- package/dist/resources/MemoryGrant.js +19 -40
- 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 +55 -18
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +170 -89
- package/dist/resources/SemanticSearch.js +44 -19
- 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 +164 -50
- 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/bm25.js +13 -14
- 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-cleanup.js +289 -51
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +105 -22
- 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/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +97 -12
- package/dist/resources/mcp-handler.js +155 -51
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +28 -25
- 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/memory-visibility.js +10 -7
- 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/rate-limit.js +6 -4
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +44 -23
- 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 +26 -22
- package/dist/resources/semantic-retrieval-core.js +103 -4
- package/dist/resources/table-helpers.js +33 -0
- 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/instance-identity-row.js +580 -0
- package/dist/src/lib/memory-attributes.js +77 -0
- package/dist/src/lib/redact-token-id.js +197 -0
- package/docs/api-reference.md +80 -16
- package/docs/auth.md +5 -5
- package/docs/claude-code.md +137 -6
- package/docs/deploying-on-fabric.md +6 -3
- package/docs/deployment.md +1 -1
- package/docs/embedding-in-a-harper-app.md +3 -3
- package/docs/federation.md +17 -10
- package/docs/hosted-on-fabric.md +4 -3
- package/docs/integrations.md +28 -19
- package/docs/mcp-clients.md +26 -32
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +27 -18
- package/docs/openclaw.md +29 -28
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/spoke-bringup.md +14 -11
- package/docs/standalone-local.md +2 -2
- package/docs/supply-chain-policy.md +28 -10
- package/docs/system-requirements.md +1 -1
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +189 -63
- 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);
|
|
@@ -15,7 +15,7 @@ import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent,
|
|
|
15
15
|
// retrievalCount hit-tracking side effects (see resources/
|
|
16
16
|
// semantic-retrieval-core.ts's module doc for the full boundary).
|
|
17
17
|
import { retrieveCandidates, DEFAULT_SELECT } from "./semantic-retrieval-core.js";
|
|
18
|
-
import {
|
|
18
|
+
import { retrievalMode } from "./bm25.js";
|
|
19
19
|
import { buildTrustBlock } from "./trust-block.js";
|
|
20
20
|
import { bestSemanticSimilarity, evaluateAbstention } from "./abstention.js";
|
|
21
21
|
import { estimateTokens } from "./token-estimate.js";
|
|
@@ -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]" : "";
|
|
@@ -939,16 +943,23 @@ export class BootstrapMemories extends Resource {
|
|
|
939
943
|
if (currentTask && tokenBudget <= 0)
|
|
940
944
|
taskRetrievalHint = "Task retrieval skipped: no content budget remains.";
|
|
941
945
|
if (currentTask && tokenBudget > 0) {
|
|
946
|
+
// Resolve the mode ONCE here so the embedding guard and the core agree.
|
|
947
|
+
// The bm25-only arm ranks on the lexical leg alone and needs NO query
|
|
948
|
+
// embedding — gating it on one being available would skip the lexical
|
|
949
|
+
// search entirely and lose task-relevant memories for no reason.
|
|
950
|
+
const mode = retrievalMode();
|
|
942
951
|
let queryEmbedding = null;
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
952
|
+
if (mode !== "bm25-only") {
|
|
953
|
+
try {
|
|
954
|
+
// flair#504 Phase 2: 'query' — currentTask is the bootstrap's
|
|
955
|
+
// task-relevance search query, not stored content.
|
|
956
|
+
queryEmbedding = await getEmbedding(currentTask, "query");
|
|
957
|
+
}
|
|
958
|
+
catch { }
|
|
947
959
|
}
|
|
948
|
-
|
|
949
|
-
if (!queryEmbedding)
|
|
960
|
+
if (mode !== "bm25-only" && !queryEmbedding)
|
|
950
961
|
taskRetrievalHint = "Task retrieval skipped: query embedding unavailable.";
|
|
951
|
-
if (queryEmbedding) {
|
|
962
|
+
if (mode === "bm25-only" || queryEmbedding) {
|
|
952
963
|
// flair#1207 — exclude own memories ALREADY placed via the authoritative
|
|
953
964
|
// set (permanent + recent + predicted actually admitted). The old set was
|
|
954
965
|
// built positionally (recent.filter by index) AND omitted `predicted`, so
|
|
@@ -973,9 +984,9 @@ export class BootstrapMemories extends Resource {
|
|
|
973
984
|
limit: candidatePoolK,
|
|
974
985
|
// flair#1246 — ONE RANKER, ONE SCALE: this pass now invokes the
|
|
975
986
|
// core in the SAME mode memory_search does (hybrid + q via the
|
|
976
|
-
// shared
|
|
977
|
-
// kill-switch moves BOTH surfaces together —
|
|
978
|
-
// #1246 bug). HNSW-only here was an accident of early code, and it
|
|
987
|
+
// shared retrievalMode() selector, so the FLAIR_RETRIEVAL_MODE /
|
|
988
|
+
// FLAIR_HYBRID_RETRIEVAL kill-switch moves BOTH surfaces together —
|
|
989
|
+
// a split mode IS the #1246 bug). HNSW-only here was an accident of early code, and it
|
|
979
990
|
// made bootstrap's teammate picks diverge from search on the same
|
|
980
991
|
// store+query: a record whose task-relevance is LEXICAL (exact task
|
|
981
992
|
// terms in semantically-atypical prose) ranks BELOW bland-generic
|
|
@@ -987,7 +998,7 @@ export class BootstrapMemories extends Resource {
|
|
|
987
998
|
// fusion carries it to the top, same as search. Perf (Kern-ratified
|
|
988
999
|
// trade): the BM25 corpus scan this adds to the bootstrap path is
|
|
989
1000
|
// the same per-call scan every memory_search request already runs.
|
|
990
|
-
|
|
1001
|
+
mode,
|
|
991
1002
|
// The lexical leg — same query text the embedding was computed
|
|
992
1003
|
// from, so both legs rank the same question (parity with search,
|
|
993
1004
|
// where `q` drives BM25 and the keyword bump).
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { databases } from "harper";
|
|
2
2
|
import { resolveAgentAuth } from "./agent-auth.js";
|
|
3
3
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
4
|
-
import { makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
4
|
+
import { makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
5
5
|
import { RECORD_TYPES } from "./record-types.js";
|
|
6
6
|
// Parameterized from RECORD_TYPES.MemoryCandidate (record-types slice 2,
|
|
7
7
|
// flair#520) rather than a hand-typed "owner-only" literal — the registry is
|
|
@@ -11,6 +11,7 @@ import { RECORD_TYPES } from "./record-types.js";
|
|
|
11
11
|
// `.ownerField` against RECORD_TYPES.MemoryCandidate — not for any other
|
|
12
12
|
// runtime consumer.
|
|
13
13
|
export const memoryCandidateReadScope = makeReadScope(RECORD_TYPES.MemoryCandidate.readScope, RECORD_TYPES.MemoryCandidate.ownerField);
|
|
14
|
+
const memoryCandidateScopedSearch = makeScopedSearch(memoryCandidateReadScope);
|
|
14
15
|
const memoryCandidateByIdReadGate = makeByIdReadGate(memoryCandidateReadScope);
|
|
15
16
|
// See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
|
|
16
17
|
// prototype method below, never a class-field assignment.
|
|
@@ -97,16 +98,7 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
|
|
|
97
98
|
if (gate.kind === "unfiltered")
|
|
98
99
|
return super.search(query);
|
|
99
100
|
// Non-admin agent: scope to own candidates only.
|
|
100
|
-
|
|
101
|
-
const agentCondition = scope.condition;
|
|
102
|
-
if (!query?.conditions) {
|
|
103
|
-
return super.search({ conditions: [agentCondition], ...(query || {}) });
|
|
104
|
-
}
|
|
105
|
-
return super.search({
|
|
106
|
-
...query,
|
|
107
|
-
conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
|
|
108
|
-
operator: "and",
|
|
109
|
-
});
|
|
101
|
+
return memoryCandidateScopedSearch(gate.agentId, query, (q) => super.search(q));
|
|
110
102
|
}
|
|
111
103
|
/**
|
|
112
104
|
* No shipped CLI path calls POST today (the FLAIR-NIGHTLY-REM staging
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { Resource, databases } from "harper";
|
|
2
3
|
import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
|
|
3
4
|
import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
|
|
4
5
|
import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
|
|
5
6
|
import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
|
|
6
|
-
import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY } from "./memory-visibility.js";
|
|
7
|
+
import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
|
|
7
8
|
import { assertValidDurability } from "./memory-durability.js";
|
|
8
9
|
import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
|
|
9
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";
|
|
10
16
|
export class FeedMemories extends Resource {
|
|
11
17
|
// Self-authorize via the Ed25519 agent verify (the auth reshape removes the
|
|
12
18
|
// gate's admin elevation).
|
|
@@ -49,6 +55,13 @@ export class FeedMemories extends Resource {
|
|
|
49
55
|
if (existingRecord && existingRecord.agentId !== content.agentId) {
|
|
50
56
|
return FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
|
|
51
57
|
}
|
|
58
|
+
// Preserve stored visibility on updates before applying write policy
|
|
59
|
+
// (the same rule as Memory.put; only the two writable values).
|
|
60
|
+
if (existingRecord &&
|
|
61
|
+
(content.visibility === undefined || content.visibility === null) &&
|
|
62
|
+
(existingRecord.visibility === PRIVATE_VISIBILITY || existingRecord.visibility === SHARED_VISIBILITY)) {
|
|
63
|
+
content.visibility = existingRecord.visibility;
|
|
64
|
+
}
|
|
52
65
|
}
|
|
53
66
|
const agentId = content.agentId;
|
|
54
67
|
const body = String(content?.content ?? "");
|
|
@@ -135,7 +148,7 @@ export class FeedMemories extends Resource {
|
|
|
135
148
|
return existing;
|
|
136
149
|
const record = {
|
|
137
150
|
...content,
|
|
138
|
-
id: content.id ?? `${agentId}-${Date.now()}`,
|
|
151
|
+
id: content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`,
|
|
139
152
|
agentId,
|
|
140
153
|
content: body,
|
|
141
154
|
contentHash,
|
|
@@ -157,19 +170,215 @@ export class FeedMemories extends Resource {
|
|
|
157
170
|
if (record.durability === "ephemeral" && (record.visibility === undefined || record.visibility === null)) {
|
|
158
171
|
record.visibility = PRIVATE_VISIBILITY;
|
|
159
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);
|
|
160
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);
|
|
161
212
|
await databases.flair.Memory.put(record);
|
|
162
213
|
// flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
|
|
163
214
|
noteMemoryUpsert(record);
|
|
164
215
|
return record;
|
|
165
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
|
+
*/
|
|
166
260
|
async *connect(target, incomingMessages) {
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
169
|
-
|
|
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 });
|
|
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;
|
|
170
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;
|
|
171
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;
|
|
172
291
|
yield event;
|
|
173
292
|
}
|
|
174
293
|
}
|
|
175
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
|
+
}
|
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { databases } from "harper";
|
|
2
2
|
import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
|
|
3
3
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
4
|
+
import { makeByIdReadGate, makeScopedSearch } from "./record-type-kit.js";
|
|
5
|
+
// A grant is readable by either party: owner OR grantee. One scope object feeds
|
|
6
|
+
// both the shared by-id gate and the scoped search, so the collection scope is
|
|
7
|
+
// always the outermost AND and the by-id check reads the stored record.
|
|
8
|
+
const grantReadScope = Object.assign(async (agentId) => ({
|
|
9
|
+
condition: {
|
|
10
|
+
operator: "or",
|
|
11
|
+
conditions: [
|
|
12
|
+
{ attribute: "ownerId", comparator: "equals", value: agentId },
|
|
13
|
+
{ attribute: "granteeId", comparator: "equals", value: agentId },
|
|
14
|
+
],
|
|
15
|
+
},
|
|
16
|
+
isAllowed: (record) => !!record && (record.ownerId === agentId || record.granteeId === agentId),
|
|
17
|
+
}), { mode: "owner-only", ownerField: "ownerId" });
|
|
18
|
+
const grantByIdReadGate = makeByIdReadGate(grantReadScope);
|
|
19
|
+
const grantScopedSearch = makeScopedSearch(grantReadScope);
|
|
4
20
|
const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
5
21
|
const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
6
22
|
const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
|
|
@@ -38,31 +54,7 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
|
|
|
38
54
|
* to enumerate other agents' grant ids.
|
|
39
55
|
*/
|
|
40
56
|
async get(target) {
|
|
41
|
-
|
|
42
|
-
// `isCollection === true`, and are governed by search() (same owner/
|
|
43
|
-
// grantee scoping). Only a genuine by-id get is ownership-checked below
|
|
44
|
-
// — see Memory.ts's get() for the full rationale (same bug class).
|
|
45
|
-
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
46
|
-
return this.search(target);
|
|
47
|
-
}
|
|
48
|
-
const auth = await this._auth();
|
|
49
|
-
// Anonymous by-id read is already blocked at the allowRead() gate (403);
|
|
50
|
-
// this is defense-in-depth if get() is ever reached directly.
|
|
51
|
-
if (auth.kind === "anonymous") {
|
|
52
|
-
return NOT_FOUND();
|
|
53
|
-
}
|
|
54
|
-
// Trusted internal call or admin agent — unfiltered, unchanged behavior.
|
|
55
|
-
if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
|
|
56
|
-
return super.get(target);
|
|
57
|
-
}
|
|
58
|
-
// Non-admin agent: visible if it's the owner OR the grantee (parity with
|
|
59
|
-
// search()'s owner-OR-grantee scope).
|
|
60
|
-
const record = await super.get(target);
|
|
61
|
-
if (!record)
|
|
62
|
-
return NOT_FOUND();
|
|
63
|
-
if (record.ownerId !== auth.agentId && record.granteeId !== auth.agentId)
|
|
64
|
-
return NOT_FOUND();
|
|
65
|
-
return record;
|
|
57
|
+
return grantByIdReadGate.call(this, target, (t) => super.get(t));
|
|
66
58
|
}
|
|
67
59
|
async search(query) {
|
|
68
60
|
const auth = await this._auth();
|
|
@@ -71,21 +63,8 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
|
|
|
71
63
|
if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
|
|
72
64
|
return super.search(query);
|
|
73
65
|
}
|
|
74
|
-
// owner OR grantee
|
|
75
|
-
|
|
76
|
-
operator: "or",
|
|
77
|
-
conditions: [
|
|
78
|
-
{ attribute: "ownerId", comparator: "equals", value: auth.agentId },
|
|
79
|
-
{ attribute: "granteeId", comparator: "equals", value: auth.agentId },
|
|
80
|
-
],
|
|
81
|
-
};
|
|
82
|
-
if (query && typeof query === "object" && !Array.isArray(query)) {
|
|
83
|
-
const existing = query.conditions ?? [];
|
|
84
|
-
query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
|
|
85
|
-
return super.search(query);
|
|
86
|
-
}
|
|
87
|
-
const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
|
|
88
|
-
return super.search(conditions);
|
|
66
|
+
// owner OR grantee, as the outermost AND (makeScopedSearch).
|
|
67
|
+
return grantScopedSearch(auth.agentId, query, (q) => super.search(q));
|
|
89
68
|
}
|
|
90
69
|
async post(content, context) {
|
|
91
70
|
const denied = await this._enforceOwnerWrite(content);
|
|
@@ -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
|
+
}
|