@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
@@ -0,0 +1,103 @@
1
+ /**
2
+ * memory-declared-attributes.ts — the declared Memory attributes guard
3
+ * (flair#1940 slice 1 / A1' item 1). PURE: data-only imports, so it is unit-
4
+ * testable and callable from every Memory writer.
5
+ *
6
+ * WHY: Harper stores an attribute that is not DECLARED in the schema (the
7
+ * `schemas/memory.graphql` ~32-35 note records this for `embeddingModel`; the
8
+ * pinned harper re-confirms it). So removing a field from the Memory schema
9
+ * does NOT stop a raw writer from persisting it — a
10
+ * `Memory.put({..., hostSource})` would still land. The one-shot real-Harper
11
+ * probe is `test/repro/harper-undeclared-attr-probe.ts`; the unit test checks
12
+ * whitelist behavior and schema drift. The named application write paths remove
13
+ * pointer fields before persisting Memory rows. Federation filters its outbound
14
+ * and inbound Memory rows separately. Trusted raw table operations remain
15
+ * outside these resource guards.
16
+ *
17
+ * The pointer inputs (`hostSource`, `hostSourceScope`, `hostSourceVisibility`)
18
+ * are NOT declared Memory attributes after A1'. Only `Memory.post()` and
19
+ * `Memory.put()` accept pointer inputs; the `MemoryHostSource` resource refuses
20
+ * every REST write verb. They are consumed BEFORE the content reaches this
21
+ * guard, so the guard strips them like any other undeclared key.
22
+ *
23
+ * DECLARED_MEMORY_ATTRIBUTES is the schema's field list. A drift tripwire
24
+ * (test/unit/memory-declared-attributes.test.ts) parses `type Memory` out of
25
+ * schemas/memory.graphql and fails if this constant and the schema disagree,
26
+ * so the whitelist can never silently fall behind the schema.
27
+ */
28
+ import { DECLARED_MEMORY_ATTRIBUTES, MEMORY_ATTRIBUTES } from "../src/lib/memory-attributes.js";
29
+ export { DECLARED_MEMORY_ATTRIBUTES, UNDECLARED_ALLOWED } from "../src/lib/memory-attributes.js";
30
+ const DECLARED = new Set(DECLARED_MEMORY_ATTRIBUTES);
31
+ const ALLOWED = new Set(MEMORY_ATTRIBUTES);
32
+ /** True when `key` is a declared Memory attribute. */
33
+ export function isDeclaredMemoryAttribute(key) {
34
+ return DECLARED.has(key);
35
+ }
36
+ /**
37
+ * Drop every UNDECLARED attribute from a Memory write body, IN PLACE, and
38
+ * return the list of keys removed. A non-object body is returned untouched.
39
+ * `id` is always kept (Harper assigns it when absent; a supplied id is the
40
+ * caller's own key, never an undeclared field).
41
+ */
42
+ export function stripUndeclaredMemoryAttributes(content) {
43
+ if (!content || typeof content !== "object" || Array.isArray(content))
44
+ return [];
45
+ const obj = content;
46
+ const removed = [];
47
+ for (const key of Object.keys(obj)) {
48
+ if (!ALLOWED.has(key)) {
49
+ delete obj[key];
50
+ removed.push(key);
51
+ }
52
+ }
53
+ return removed;
54
+ }
55
+ /**
56
+ * flair#1940 A1-iv item 3 — the SERVER-STAMPED fields a client body may never
57
+ * set. The declared-attributes whitelist KEEPS these (they are declared/named),
58
+ * so a whitelist alone does not stop forgery: a client could PUT a
59
+ * `provenance` or an `instanceToken` that then reads as if the server stamped
60
+ * it. Memory's REST write paths remove `instanceToken` and `provenance` from the
61
+ * request body. `post()`/`put()` re-stamp `provenance` (via `buildProvenance`)
62
+ * and `instanceToken` after the strip; the other writers strip and preserve the
63
+ * stored value.
64
+ *
65
+ * `originatorInstanceId` is NOT in this set (flair#1965): its write rule is
66
+ * create-vs-update — a CREATE stamps the local id, an UPDATE keeps the stored
67
+ * value — so it cannot simply be stripped and re-stamped here. It is handled by
68
+ * resources/originator-instance.ts, called from every Memory writer
69
+ * (post/put/patch/reindex). Leaving it out of this set also keeps the
70
+ * federation merge (resources/Federation.ts), which calls
71
+ * stripServerStampedFields on the merged Memory row, from deleting the
72
+ * originator's value.
73
+ */
74
+ export const SERVER_STAMPED_MEMORY_FIELDS = Object.freeze([
75
+ "instanceToken",
76
+ "provenance",
77
+ ]);
78
+ const SERVER_STAMPED = new Set(SERVER_STAMPED_MEMORY_FIELDS);
79
+ /** Strip every server-stamped field from a write body, IN PLACE. Returns removed keys. */
80
+ export function stripServerStampedFields(content) {
81
+ if (!content || typeof content !== "object" || Array.isArray(content))
82
+ return [];
83
+ const obj = content;
84
+ const removed = [];
85
+ for (const key of Object.keys(obj)) {
86
+ if (SERVER_STAMPED.has(key)) {
87
+ delete obj[key];
88
+ removed.push(key);
89
+ }
90
+ }
91
+ return removed;
92
+ }
93
+ /**
94
+ * flair#1940 A1'' item 8 — the SAME declare-only whitelist applied to an
95
+ * INBOUND federated Memory row before it is merged and written. A dirty pushed
96
+ * row (a legacy direct-insert, or a raw writer that slipped a pointer field
97
+ * past the writers) must not carry a pointer attribute onto the merged Memory
98
+ * row; the named federation bookkeeping fields survive. Named seam so the
99
+ * inbound direction is testable (resources/Federation.ts calls this).
100
+ */
101
+ export function stripInboundMemoryRow(row) {
102
+ return stripUndeclaredMemoryAttributes(row);
103
+ }
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { stripInlinePointerFields } from "./host-source-visibility.js";
2
3
  export function computeContentHash(agentId, content) {
3
4
  return createHash("sha256")
4
5
  .update(`${agentId}${content}`)
@@ -8,7 +9,10 @@ export function computeContentHash(agentId, content) {
8
9
  export async function findExistingMemoryByContentHash(records, agentId, contentHash) {
9
10
  for await (const record of records) {
10
11
  if (record?.agentId === agentId && record?.contentHash === contentHash) {
11
- return record;
12
+ // flair#1940 A1' item 1: a row returned to a caller must never carry an
13
+ // inline pointer field — drop any raw writer's leftovers with the same
14
+ // helper the read projection uses.
15
+ return stripInlinePointerFields(record);
12
16
  }
13
17
  }
14
18
  return null;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * memory-host-source.ts — the MemoryHostSource table's non-resource helpers
3
+ * (flair#1940 slice 1 / A1'). The pointer lives in its OWN table keyed by
4
+ * memoryId. Supported writes store host pointers only in `MemoryHostSource`: a pointer
5
+ * reaches a non-admin reader only through the gated join. For non-admin `Memory.get`,
6
+ * `Memory.search`, and `SemanticSearch` results, the gated projection removes inline
7
+ * pointer fields and renders a pointer only from a bound `MemoryHostSource` row.
8
+ *
9
+ * This module holds:
10
+ * - the WRITE-BODY-ONLY pointer inputs and their extraction; The named
11
+ * application write paths remove pointer fields before persisting Memory
12
+ * rows. Federation filters its outbound and inbound Memory rows separately.
13
+ * Trusted raw table operations remain outside these resource guards (A1' item 1);
14
+ * - the pointer row builder (canonical hostSource + scopeAtWrite +
15
+ * server-stamped authorId/receivedAt) (A1' items 1, 3);
16
+ * - the ONE batched pointer read the gated join uses (A1' item 4: never one
17
+ * query per row);
18
+ * - the federation refusal predicate (A1' item 5); The outbound reader
19
+ * projects declared Memory attributes. The inbound merge removes undeclared
20
+ * attributes except the named bookkeeping fields (A1'' item 8) (f1-out/f1-in).
21
+ */
22
+ import { databases } from "harper";
23
+ import { validateHostSource } from "./host-source.js";
24
+ import { projectHostSource, stripInlinePointerFields } from "./host-source-visibility.js";
25
+ /** The table name, so callers and tests never re-type it as a literal. */
26
+ export const MEMORY_HOST_SOURCE_TABLE = "MemoryHostSource";
27
+ /** The write-body-only pointer inputs (A1' item 1). Only `Memory.post()` and
28
+ * `Memory.put()` accept pointer inputs; the `MemoryHostSource` resource refuses
29
+ * every REST write verb. `hostSource` is
30
+ * the pointer; `hostSourceScope` is the write-time opt-in; a
31
+ * `hostSourceVisibility` supplied by a client is a FORGERY of the server's
32
+ * write-time stamp and is dropped (never read). */
33
+ export const POINTER_INPUT_KEYS = Object.freeze(["hostSource", "hostSourceScope", "hostSourceVisibility"]);
34
+ /**
35
+ * Consume the pointer inputs out of a Memory write body, IN PLACE, so they can
36
+ * never be persisted on the Memory row (A1' item 1). Returns what was found.
37
+ */
38
+ export function extractPointerInputs(content) {
39
+ const out = { hostSource: undefined, hostSourceScope: undefined, forgedVisibility: false };
40
+ if (!content || typeof content !== "object" || Array.isArray(content))
41
+ return out;
42
+ const obj = content;
43
+ out.hostSource = obj.hostSource;
44
+ out.hostSourceScope = obj.hostSourceScope;
45
+ out.forgedVisibility = obj.hostSourceVisibility !== undefined && obj.hostSourceVisibility !== null;
46
+ for (const key of POINTER_INPUT_KEYS)
47
+ delete obj[key];
48
+ return out;
49
+ }
50
+ /** Build the pointer row to persist alongside a Memory row. `scopeAtWrite` is
51
+ * the record's visibility at write when the write opted in with
52
+ * `hostSourceScope: "record"`, else null (author-only). `authorId`,
53
+ * `memoryInstanceToken` and `receivedAt` are SERVER-stamped (A1' item 3,
54
+ * A1-iv item 1) — never taken from the body. */
55
+ export function buildPointerRow(args) {
56
+ return {
57
+ memoryId: args.memoryId,
58
+ hostSource: args.canonical,
59
+ scopeAtWrite: args.scopeAtWrite ?? null,
60
+ authorId: args.authorId,
61
+ memoryInstanceToken: args.memoryInstanceToken ?? null,
62
+ receivedAt: args.receivedAt,
63
+ };
64
+ }
65
+ function pointerTable() {
66
+ return databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
67
+ }
68
+ /**
69
+ * flair#1940 A1'' item 6 (adjudication B, hardened in round 5/adjudication 0e)
70
+ * — is an incoming hostSource an ECHO of the STORED pointer? Preservation (do
71
+ * not replace the stored row) is a NARROW, unforgeable case:
72
+ * - the current writer MUST be the stored pointer row's `authorId` — a
73
+ * different writer echoing the value must not keep another agent's
74
+ * pointer; and
75
+ * - the incoming value must match the stored canonical EXACTLY, full URL
76
+ * included. Matching after DROPPING the query and fragment was forgeable:
77
+ * a value with a DIFFERENT query rendered identically and was wrongly
78
+ * treated as an echo, so a real change was masked. A different query is a
79
+ * new value, not an echo.
80
+ * (A rendered read strips the URL, so a client that wants the stored pointer
81
+ * kept echoes the stored value itself, not the stripped render.)
82
+ */
83
+ export function isPointerEchoOf(input, storedPointer, writerAuthorId) {
84
+ if (!storedPointer || typeof storedPointer.hostSource !== "string")
85
+ return false;
86
+ const author = typeof storedPointer.authorId === "string" && storedPointer.authorId.length > 0 ? storedPointer.authorId : null;
87
+ if (author === null || writerAuthorId == null || author !== writerAuthorId)
88
+ return false;
89
+ const incoming = validateHostSource(input);
90
+ if (!incoming.ok)
91
+ return false;
92
+ return incoming.canonical === storedPointer.hostSource;
93
+ }
94
+ /**
95
+ * Read the pointer rows for a WHOLE result set in ONE batched query (A1'
96
+ * item 4). Empty input issues no query. Returns memoryId -> row.
97
+ */
98
+ export async function loadPointerRows(ids) {
99
+ const wanted = [...new Set(ids.filter((id) => typeof id === "string" && id.length > 0))];
100
+ const map = new Map();
101
+ if (wanted.length === 0)
102
+ return map;
103
+ const table = pointerTable();
104
+ if (!table?.search)
105
+ return map;
106
+ // Harper refuses an `or` with fewer than two conditions, so a single id uses
107
+ // a plain equals condition and a set uses an `or`. Either way it is ONE call.
108
+ const query = wanted.length === 1
109
+ ? { conditions: [{ attribute: "memoryId", comparator: "equals", value: wanted[0] }] }
110
+ : { operator: "or", conditions: wanted.map((id) => ({ attribute: "memoryId", comparator: "equals", value: id })) };
111
+ const result = table.search(query);
112
+ for await (const row of result) {
113
+ if (row && typeof row.memoryId === "string")
114
+ map.set(row.memoryId, row);
115
+ }
116
+ return map;
117
+ }
118
+ /**
119
+ * flair#1940 A1-iv item 2 — the ONE reader helper. `Memory.get()`,
120
+ * `Memory.search()` and `SemanticSearch` render pointers through the pointer
121
+ * helper. Other Memory projections, bootstrap included, do not render pointers
122
+ * in this slice. It fetches the pointer rows for the WHOLE result set in ONE
123
+ * batched query and applies the join, so no reader can forget the join and no
124
+ * module needs to touch the MemoryHostSource table itself. `readerAgentId` is
125
+ * the non-admin reader; an admin/operator read is the named exception (see
126
+ * MemoryHostSource.ts).
127
+ *
128
+ * What the join receives differs by reader path, and both carry the binding
129
+ * fields it reads (`id`, `agentId`, `instanceToken`, `archived`,
130
+ * `visibility`). For a non-admin `Memory.get`/`Memory.search`, the join runs
131
+ * on the FULL stored row, not on whatever the caller asked for: those reads
132
+ * ignore the caller's `select`/`property` — the auth middleware drops the
133
+ * selection from a REST request URL before Harper parses it, and the direct
134
+ * contextual read drops it before the base read. `SemanticSearch` instead
135
+ * hands the join its server-owned retrieval projection (`DEFAULT_SELECT`,
136
+ * optionally widened with `provenance`/`metadata`/`trigger`), which is fixed
137
+ * server-side and not caller-shaped either; the binding fields are in that
138
+ * projection as well as in the full row. An inline pointer field on the Memory
139
+ * row is removed (or replaced by the gated rendering) before the projected row
140
+ * is returned, so no inline pointer field reaches a non-admin reader.
141
+ */
142
+ export async function projectRowsThroughPointers(rows, readerAgentId) {
143
+ const ids = rows.map((r) => r?.id).filter((id) => typeof id === "string" && id.length > 0);
144
+ const pointers = await loadPointerRows(ids);
145
+ return rows.map((row) => {
146
+ const id = row?.id;
147
+ return typeof id === "string" ? projectHostSource(row, readerAgentId, pointers.get(id) ?? null) : stripInlinePointerFields(row);
148
+ });
149
+ }
150
+ /** Read ONE stored pointer row (the write path's echo check). Kept here so the
151
+ * MemoryHostSource table is touched ONLY by this module. */
152
+ export async function loadStoredPointer(memoryId) {
153
+ return (await loadPointerRows([memoryId])).get(memoryId) ?? null;
154
+ }
155
+ /** The Memory attributes that would carry a pointer into an inbound federated
156
+ * row (A1' item 5). A record carrying any of these is refused, not merged. */
157
+ const FEDERATION_POINTER_FIELDS = ["hostSource", "hostSourceScope", "hostSourceVisibility"];
158
+ /** True when an inbound federated record's data carries a pointer field. */
159
+ export function inboundCarriesPointer(data) {
160
+ if (!data || typeof data !== "object")
161
+ return false;
162
+ return FEDERATION_POINTER_FIELDS.some((f) => data[f] !== undefined);
163
+ }
@@ -66,8 +66,8 @@ export function isPrivateVisibility(visibility) {
66
66
  * would fall back to the durability-keyed default, which for a permanent or
67
67
  * persistent write is `shared` — the same wrong outcome, arrived at quietly.
68
68
  *
69
- * `undefined`/`null` are accepted: omitting the field is how a caller asks for
70
- * the durability-keyed default, and that is a documented, intentional path.
69
+ * `undefined`/`null` are accepted: on a new record, omitting the field asks for
70
+ * the durability-keyed default; on an update, it keeps the stored visibility.
71
71
  */
72
72
  export function assertValidVisibility(visibility) {
73
73
  if (visibility === undefined || visibility === null)
@@ -76,8 +76,9 @@ export function assertValidVisibility(visibility) {
76
76
  return null;
77
77
  }
78
78
  return (`visibility must be ${WRITABLE_VISIBILITIES.map((v) => `"${v}"`).join(" or ")} ` +
79
- `(got: ${JSON.stringify(visibility)}). Omit it to use the durability-keyed default: ` +
80
- `permanent/persistent -> shared, standard/ephemeral -> private.`);
79
+ `(got: ${JSON.stringify(visibility)}). Omit it to use the durability-keyed default on a new ` +
80
+ `memory (permanent/persistent -> shared, standard/ephemeral -> private); on an update, ` +
81
+ `omitting it keeps a stored private or shared visibility.`);
81
82
  }
82
83
  /** Deliberately a LOCAL literal, not an import from memory-durability.ts: this
83
84
  * module's zero-imports property is load-bearing (see the header — src/cli.ts
@@ -101,7 +102,8 @@ export const EPHEMERAL_DURABILITY = "ephemeral";
101
102
  * NOT "refuse ephemeral+shared": on the read side any value other than the
102
103
  * literal "private" resolves to non-private (the migration invariant above),
103
104
  * so an unknown value on an ephemeral row would leak exactly like "shared".
104
- * assertValidVisibility refuses unknowns first at both call sites, but this
105
+ * assertValidVisibility refuses unknowns first at every call site (post, put,
106
+ * patch), but this
105
107
  * guard must stay fail-closed on its own — unknown means refused, not allowed.
106
108
  *
107
109
  * Absent (`undefined`/`null`) is accepted: it resolves through the
@@ -123,7 +125,8 @@ export function assertVisibilityAllowedForDurability(durability, visibility) {
123
125
  }
124
126
  return (`ephemeral memories are private-only (continuity journal tier, flair#1257): ` +
125
127
  `durability "${EPHEMERAL_DURABILITY}" cannot be written with visibility ${JSON.stringify(visibility)}. ` +
126
- `Omit visibility (the durability-keyed default is "${PRIVATE_VISIBILITY}") or set it to ` +
127
- `"${PRIVATE_VISIBILITY}"; for a memory other agents should read, use durability ` +
128
+ `Set visibility to "${PRIVATE_VISIBILITY}" (for a new memory, omitting it also gives ` +
129
+ `"${PRIVATE_VISIBILITY}"; an update keeps the record's stored visibility); for a memory ` +
130
+ `other agents should read, use durability ` +
128
131
  `"standard", "persistent", or "permanent".`);
129
132
  }
@@ -28,6 +28,7 @@
28
28
  * re-reading the row itself (invariant IV: state lives IN the data).
29
29
  */
30
30
  import { databases } from "harper";
31
+ import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
31
32
  export const SYNTHETIC_MIGRATION_ID = "synthetic-ci-schema-stamp";
32
33
  export const RESERVED_TEST_AGENT_ID = "__flair_migration_synthetic_test_agent__";
33
34
  export const SYNTHETIC_TARGET_MARKER = `${SYNTHETIC_MIGRATION_ID}-done`;
@@ -84,7 +85,9 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
84
85
  continue;
85
86
  if (existing.source === SYNTHETIC_TARGET_MARKER)
86
87
  continue; // already stamped — idempotent skip
87
- await table.put({ ...existing, source: SYNTHETIC_TARGET_MARKER });
88
+ const synthRow = { ...existing, source: SYNTHETIC_TARGET_MARKER };
89
+ stripUndeclaredMemoryAttributes(synthRow);
90
+ await table.put(synthRow);
88
91
  touchedIds.push(id);
89
92
  }
90
93
  return { processed: touchedIds.length, touchedIds };
@@ -134,6 +134,7 @@
134
134
  * omitting it.
135
135
  */
136
136
  import { databases } from "harper";
137
+ import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
137
138
  function defaultMemoryTable() {
138
139
  return databases.flair.Memory;
139
140
  }
@@ -223,7 +224,9 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
223
224
  if (derived !== "private" && derived !== "shared") {
224
225
  throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
225
226
  }
226
- await table.put({ ...existing, visibility: derived });
227
+ const backfillRow = { ...existing, visibility: derived };
228
+ stripUndeclaredMemoryAttributes(backfillRow);
229
+ await table.put(backfillRow);
227
230
  touchedIds.push(id);
228
231
  }
229
232
  return { processed: touchedIds.length, touchedIds };
@@ -0,0 +1,235 @@
1
+ import { databases } from "harper";
2
+ import { localInstanceId } from "./instance-identity.js";
3
+ /**
4
+ * originator-instance.ts — the single resource-layer delegate that enforces the
5
+ * server-stamped `originatorInstanceId` contract on every REST write path
6
+ * (flair#1965).
7
+ *
8
+ * ─── The contract ────────────────────────────────────────────────────────────
9
+ *
10
+ * `originatorInstanceId` names the federation instance that AUTHORED a record
11
+ * (schemas/memory.graphql, agent.graphql): it is stamped server-side and is
12
+ * never client-writable. Before this module each of Memory/Soul/Agent/
13
+ * Relationship only stamped it when the request body's value was null
14
+ * (`content.originatorInstanceId == null`), so a caller could supply or change
15
+ * it on create AND on update. The rule enforced now is:
16
+ *
17
+ * - CREATE (`post()`, and a `put()`/`patch()` that lands on a row with no
18
+ * stored counterpart): the local instance id is stamped; ANY request-body
19
+ * value is ignored.
20
+ * - UPDATE (`put()`/`patch()` over an existing row): the STORED value
21
+ * stands. A body value neither replaces nor clears it, and omitting the
22
+ * field leaves it exactly as stored (a legacy row with no value is left
23
+ * without one — the field is additive, never invented on update).
24
+ * - FEDERATION MERGE: unchanged. The trusted apply path
25
+ * (resources/Federation.ts's `FederationSync.post()`) merges a peer's row
26
+ * through the RAW table handle — `(databases as any).flair.Memory.put(
27
+ * mergedData)`, i.e. Harper's static table-level put — never through a
28
+ * resource's post()/put()/patch(). The originator's own value carried in
29
+ * `record.data` (selected by `mergeRecord`'s LWW, or the inbound row for a
30
+ * new one) is therefore preserved verbatim. `_originatorInstanceId` (the
31
+ * underscore form) is the separate RECEIVER-side bookkeeping stamp that
32
+ * same path writes.
33
+ *
34
+ * The wire field is server-stamped on EVERY application write. The federation
35
+ * merge is the one path that carries a peer's value, and it is not
36
+ * "body-less": `POST /FederationSync` IS REST-reachable and parses a request
37
+ * body, but that body is trusted only because the handler verifies a batch
38
+ * signature against the sending PAIRED PEER's pinned public key (and each
39
+ * record's own signature against its claimed originator's pinned key) before
40
+ * the raw-table merge. No unauthenticated caller reaches the raw write, and the
41
+ * merge never reads a request-body field into the stored `originatorInstanceId`
42
+ * — it takes the value from the already-authenticated `record.data`.
43
+ *
44
+ * `localInstanceId()` resolves to null on an instance that has never been
45
+ * federation-bootstrapped (no single Instance row yet) — the field is nullable
46
+ * by design, so a create stamps null rather than inventing an id.
47
+ */
48
+ function isPlainObject(value) {
49
+ return !!value && typeof value === "object" && !Array.isArray(value);
50
+ }
51
+ /** A stored row is a plain object; a `Response` (a refusal the caller's own
52
+ * get() produced) or anything else is not. */
53
+ function isStoredRow(value) {
54
+ return isPlainObject(value) && !(value instanceof Response);
55
+ }
56
+ /**
57
+ * CREATE path — stamp this instance's own federation id, ignoring any value the
58
+ * request body carried. Used by `post()` (always a create) and by a
59
+ * `put()`/`patch()` whose target id has no stored row yet.
60
+ */
61
+ export async function stampOriginatorOnCreate(content) {
62
+ if (!isPlainObject(content))
63
+ return;
64
+ content.originatorInstanceId = await localInstanceId();
65
+ }
66
+ /**
67
+ * UPDATE path — the STORED value stands. A body value is dropped (neither
68
+ * replaces nor clears it); when the stored row carries no value the field is
69
+ * left off the write so a legacy row stays un-stamped rather than gaining a
70
+ * fresh local id.
71
+ *
72
+ * `stored` is the row this write is over. For a `put()` (which REPLACES the
73
+ * row) the stored value is re-asserted explicitly; for a merging `patch()` the
74
+ * field is simply removed from the body so the stored value survives. Both use
75
+ * this one function so the two verbs cannot drift.
76
+ */
77
+ export function keepStoredOriginator(content, stored) {
78
+ if (!isPlainObject(content))
79
+ return;
80
+ if (isPlainObject(stored) && stored.originatorInstanceId !== undefined) {
81
+ content.originatorInstanceId = stored.originatorInstanceId;
82
+ }
83
+ else {
84
+ delete content.originatorInstanceId;
85
+ }
86
+ }
87
+ /**
88
+ * Apply the full create/update rule: `stored` is the row this write is over
89
+ * (null/undefined ⇒ a create). This is the one call a `put()` or `patch()` needs
90
+ * after it has resolved the pre-existing row.
91
+ */
92
+ export async function applyOriginatorInstanceId(content, stored) {
93
+ if (isStoredRow(stored)) {
94
+ keepStoredOriginator(content, stored);
95
+ }
96
+ else {
97
+ await stampOriginatorOnCreate(content);
98
+ }
99
+ }
100
+ /**
101
+ * PATCH path — a patch MERGES into the stored row (Harper partial update), so a
102
+ * body value can be dropped and the stored value stands untouched.
103
+ */
104
+ export function dropClientOriginator(content) {
105
+ if (isPlainObject(content))
106
+ delete content.originatorInstanceId;
107
+ }
108
+ /**
109
+ * ─── Federation bookkeeping (the underscore receiver stamps) ────────────────
110
+ *
111
+ * `_originatorInstanceId`, `_syncedFrom` and `_syncedAt` are the RECEIVER-side
112
+ * bookkeeping written by resources/Federation.ts's merge (through the RAW table
113
+ * handle) on every synced row, and rendered by resources/AdminMemory.ts's
114
+ * admin provenance pane. They are on the Memory writer whitelist so the merge
115
+ * can write them, but they are NOT client-settable: a write body must never
116
+ * pass one through (a forged value would dress a local row up as a synced one
117
+ * in the admin pane). The federation merge writes them AFTER its whitelist
118
+ * pass, so it is unaffected by the application-side strip below.
119
+ */
120
+ const FEDERATION_BOOKKEEPING_FIELDS = ["_originatorInstanceId", "_syncedFrom", "_syncedAt"];
121
+ /** CREATE path — drop any client-supplied receiver bookkeeping. */
122
+ export function dropClientFederationBookkeeping(content) {
123
+ if (!isPlainObject(content))
124
+ return;
125
+ for (const field of FEDERATION_BOOKKEEPING_FIELDS)
126
+ delete content[field];
127
+ }
128
+ /** UPDATE path (full replace) — the STORED receiver stamps stand. */
129
+ export function keepStoredFederationBookkeeping(content, stored) {
130
+ if (!isPlainObject(content))
131
+ return;
132
+ for (const field of FEDERATION_BOOKKEEPING_FIELDS) {
133
+ if (isPlainObject(stored) && stored[field] !== undefined) {
134
+ content[field] = stored[field];
135
+ }
136
+ else {
137
+ delete content[field];
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * Apply the create/update rule for the receiver bookkeeping: `stored` ⇒ keep its
143
+ * values (re-asserted onto a full-replace put); no stored row ⇒ a client body
144
+ * may not set them.
145
+ */
146
+ export function applyFederationBookkeeping(content, stored) {
147
+ if (isStoredRow(stored)) {
148
+ keepStoredFederationBookkeeping(content, stored);
149
+ }
150
+ else {
151
+ dropClientFederationBookkeeping(content);
152
+ }
153
+ }
154
+ /** The URL-bound target id of a resource instance: `getId()` on a real Harper
155
+ * resource. Only a scalar id is usable; anything else (no method, a thrown
156
+ * call, a non-scalar id) means "no URL target to consult". */
157
+ function urlTargetId(resource) {
158
+ try {
159
+ const getId = resource?.getId;
160
+ const id = typeof getId === "function" ? getId.call(resource) : undefined;
161
+ if (typeof id === "string" || typeof id === "number")
162
+ return id;
163
+ }
164
+ catch {
165
+ /* getId() threw — fall back to the body id below */
166
+ }
167
+ return null;
168
+ }
169
+ /** A 400 for a body `id` that disagrees with the address the write was sent to:
170
+ * Harper writes to the URL-bound target and rewrites the row's primary key to
171
+ * it, so a mismatching body id names a row this write does NOT land on. */
172
+ function idTargetMismatchDenial(bodyId, targetId) {
173
+ return new Response(JSON.stringify({
174
+ error: "id_target_mismatch",
175
+ message: `the request body id ${JSON.stringify(bodyId)} does not match the address it was sent to (${JSON.stringify(targetId)})`,
176
+ }), { status: 400, headers: { "content-type": "application/json" } });
177
+ }
178
+ /** A 500 for a stored-row lookup that FAILED. A lookup failure is never read as
179
+ * "no stored row": treating it as a create would let an existing row be
180
+ * re-stamped when the read fails but the write succeeds. */
181
+ function storedRowLookupFailure(tableName, err) {
182
+ // Constant format string + a structured data object: a template literal here
183
+ // would let anything interpolated into the format position forge the log
184
+ // (semgrep javascript.lang.security.audit.unsafe-formatstring).
185
+ console.error("originator-instance: the stored row could not be read, so the write was refused", { table: tableName, err });
186
+ return new Response(JSON.stringify({
187
+ error: "stored_row_lookup_failed",
188
+ message: "the existing record could not be read, so the write was refused",
189
+ }), { status: 500, headers: { "content-type": "application/json" } });
190
+ }
191
+ /**
192
+ * Resolve the stored row a `put()`/`patch()` is over, for the create/update
193
+ * decision.
194
+ *
195
+ * The authoritative id is the URL-BOUND target (`resource.getId()`), NEVER the
196
+ * request body's `id`: Harper writes to the URL target and rewrites the stored
197
+ * primary key to it (dist/resources/Table.js `_writeUpdate`), so a body id is
198
+ * not the row this write lands on. Reading the stored row by a body id let a
199
+ * caller borrow another row's stored originator — or, via a nonexistent id,
200
+ * force a "create" that re-stamped an existing row.
201
+ *
202
+ * Rules:
203
+ * - a body `id` that disagrees with the URL target id is REFUSED;
204
+ * - the stored row is read by the URL target id (via the raw table reader,
205
+ * falling back to the resource's own bound-record read when the table
206
+ * exposes no static reader — an in-process harness);
207
+ * - a read FAILURE refuses the write — it is never read as "no stored row".
208
+ *
209
+ * An in-process call with no URL-bound id (a direct `new Resource().put(body)`)
210
+ * falls back to the body `id`, which IS the write key on that path.
211
+ */
212
+ export async function resolveStoredRow(resource, tableName, content, getUrlBound) {
213
+ const targetId = urlTargetId(resource);
214
+ const bodyId = isPlainObject(content) && content.id != null ? content.id : undefined;
215
+ if (targetId != null && bodyId !== undefined && String(bodyId) !== String(targetId)) {
216
+ return { row: null, denial: idTargetMismatchDenial(bodyId, targetId) };
217
+ }
218
+ const id = targetId ?? bodyId;
219
+ if (id == null)
220
+ return { row: null };
221
+ try {
222
+ const table = databases.flair?.[tableName];
223
+ if (table && typeof table.get === "function") {
224
+ const row = await table.get(id);
225
+ return { row: isStoredRow(row) ? row : null };
226
+ }
227
+ // No static table reader (an in-process harness): read the resource's own
228
+ // URL-bound record instead — the row this write lands on.
229
+ const bound = await getUrlBound();
230
+ return { row: isStoredRow(bound) ? bound : null };
231
+ }
232
+ catch (err) {
233
+ return { row: null, denial: storedRowLookupFailure(tableName, err) };
234
+ }
235
+ }
@@ -1,5 +1,6 @@
1
1
  import { withDetachedTxn } from "./table-helpers.js";
2
2
  import { databases } from "harper";
3
+ import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
3
4
  import { noteMemoryUpsert } from "./bm25-index-service.js";
4
5
  // Called only after the promotion workflow has authorized and written a Memory
5
6
  // through its resource (safety, embedding, ownership and provenance still run).
@@ -12,6 +13,7 @@ export async function stampMemoryPromotion(id, reviewerId, decidedAt, enumeratio
12
13
  if (!stored)
13
14
  throw new Error(`Promotion memory ${id} was not written`);
14
15
  const row = { ...stored, promotionStatus: "approved", promotedBy: reviewerId, promotedAt: decidedAt };
16
+ stripUndeclaredMemoryAttributes(row);
15
17
  await withDetachedTxn(enumerationContext, () => table.put(row));
16
18
  noteMemoryUpsert(row);
17
19
  }