@tpsdev-ai/flair 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -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
+ }
@@ -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
  }
@@ -38,8 +38,8 @@ function sanitizeClaim(value) {
38
38
  * CLAIMS. Deliberately minimal — verified fields only:
39
39
  *
40
40
  * { v: 1,
41
- * verified: { agentId: <string|null>, timestamp: <ISO string> },
42
- * claimed?: { model?: <string>, client?: <string> } }
41
+ * verified: { agentId: <string|null>, timestamp: <ISO string>, receivedAt: <ISO string> },
42
+ * claimed?: { createdAt?: <string>, model?: <string>, client?: <string> } }
43
43
  *
44
44
  * - `verified.agentId` comes from the ALREADY-RESOLVED auth verdict
45
45
  * (resolveAgentAuth) — never from anything the caller can forge on the
@@ -48,10 +48,31 @@ function sanitizeClaim(value) {
48
48
  * with no per-agent identity to attribute) stamps `null` rather than
49
49
  * throwing; `kind: "anonymous"` never reaches here — every write path
50
50
  * already 401s it before this point.
51
- * - `verified.timestamp` reuses the server-clock `createdAt` the caller has
52
- * already computed by this point (never client-suppliable) — the same
53
- * "stamp a dynamic attribute the server controls" mechanism as e.g. the
54
- * `embeddingModel = getModelId()` stamp in resources/Memory.ts.
51
+ * - `verified.timestamp` is stamped from the SERVER clock at write time
52
+ * (flair#1960) — the SAME single clock read as `verified.receivedAt`, because
53
+ * both assert the server's write instant (a second read could differ by
54
+ * milliseconds and make the two fields disagree). Never client-suppliable:
55
+ * the caller's `createdAt` is a CLAIM and is recorded separately under
56
+ * `claimed.createdAt` (below), never here. Every field under `verified` is
57
+ * server-derived.
58
+ * The clock is an injectable `() => Date` (defaulting to the wall clock) so
59
+ * the "one read" contract is TESTABLE: a counting/advancing fake clock fails
60
+ * the test deterministically if a second read is ever added (flair#1960 r2 —
61
+ * comparing two wall-clock reads only catches a drift of >0 ms, and two reads
62
+ * almost always land in the SAME millisecond, so the old equality-only test
63
+ * CAUGHT a second read only ~7 times in 10,000 — it MISSED it the other
64
+ * ~9,993). Production callers never pass one.
65
+ * - The host pointer (`hostSource`) is NOT provenance (flair#1940 A5): it lives
66
+ * in its own `MemoryHostSource` table, is never part of this `{ v, verified,
67
+ * claimed }` blob, and is written on the Memory write path in the same
68
+ * transaction as the Memory row (t1/t2). `provenance` therefore stays a field
69
+ * the server controls and is never client-writable.
70
+ * - `claimed.createdAt` (flair#1960) is the caller's claim on the record's
71
+ * creation time — the `createdAt` the write carries, sanitized like the
72
+ * other claims (string-only, control-char strip, trim, 200-char cap,
73
+ * drop-if-empty). It is a CLAIM, never verified: the server's own write
74
+ * instant lives in `verified.timestamp`. The record's own `createdAt` field
75
+ * still carries the caller's value unchanged.
55
76
  * - `claimed.model` is an OPTIONAL, UNVERIFIED passthrough: included only
56
77
  * when the incoming write payload itself already carries a non-empty
57
78
  * string `model` field (sanitized via sanitizeClaim above). Never
@@ -71,8 +92,9 @@ function sanitizeClaim(value) {
71
92
  * OAuth path, the caller is required to source this from the verified
72
93
  * `client_id` token claim, never the user-controlled `client_name` — see
73
94
  * resources/mcp-handler.ts's handleToolCall for that stamp site.
74
- * - The `claimed` key is omitted entirely (not stamped as `{}`) when both
75
- * `model` and `client` are absent.
95
+ * - The `claimed` key is omitted entirely (not stamped as `{}`) when
96
+ * `createdAt`, `model` and `client` are ALL absent after sanitization (e.g.
97
+ * an empty or all-control-chars `createdAt` with no model/client claims).
76
98
  *
77
99
  * Originally introduced in resources/Memory.ts (Memory.post()/Memory.put());
78
100
  * extracted here so Relationship.ts (and any future write path) can reuse the
@@ -81,18 +103,33 @@ function sanitizeClaim(value) {
81
103
  * buildProvenance as-is," which this module makes literal (one function, one
82
104
  * shape, imported by every writer) instead of a copy that could drift.
83
105
  */
84
- export function buildProvenance(auth, createdAt, content) {
106
+ export function buildProvenance(auth, createdAt, content, clock = () => new Date()) {
107
+ // ONE clock read per write, shared by BOTH server-derived timestamps
108
+ // (flair#1960): `verified.timestamp` and `verified.receivedAt` assert the
109
+ // same server write instant, so a single `clock()` call keeps them identical
110
+ // instead of letting a second read drift them apart by milliseconds.
111
+ const serverNow = clock().toISOString();
85
112
  const provenance = {
86
113
  v: 1,
87
114
  verified: {
88
115
  agentId: auth.kind === "agent" ? auth.agentId : null,
89
- timestamp: createdAt,
116
+ // flair#1960: the server's write instant — NEVER the caller's `createdAt`.
117
+ timestamp: serverNow,
118
+ // flair#1940 A4: the server's RECEIPT time — same clock read as above.
119
+ receivedAt: serverNow,
90
120
  },
91
121
  };
122
+ // The caller's `createdAt` is their CLAIM on the record's creation time; it is
123
+ // recorded under `claimed` (sanitized like the other claims) so a reader can
124
+ // compare the claim against the server's `verified.timestamp`. The record's
125
+ // own `createdAt` field keeps the claim unchanged (flair#1960).
126
+ const claimedCreatedAt = sanitizeClaim(createdAt);
92
127
  const model = sanitizeClaim(content?.model);
93
128
  const client = sanitizeClaim(content?.claimedClient);
94
- if (model !== undefined || client !== undefined) {
129
+ if (claimedCreatedAt !== undefined || model !== undefined || client !== undefined) {
95
130
  provenance.claimed = {};
131
+ if (claimedCreatedAt !== undefined)
132
+ provenance.claimed.createdAt = claimedCreatedAt;
96
133
  if (model !== undefined)
97
134
  provenance.claimed.model = model;
98
135
  if (client !== undefined)
@@ -100,3 +137,66 @@ export function buildProvenance(auth, createdAt, content) {
100
137
  }
101
138
  return JSON.stringify(provenance);
102
139
  }
140
+ /**
141
+ * The fields whose change makes a memory write SEMANTIC — the text the record
142
+ * actually says, plus its creation claim. A PATCH that changes one of these is
143
+ * re-authoring content (and, for `createdAt`, re-authoring the creation claim),
144
+ * so it MUST re-stamp provenance from the resolved auth and the server clock
145
+ * rather than carry a previously stored `verified.*` value forward (flair#1960
146
+ * r2). `createdAt` is included (flair#1960 r4): a createdAt-only PATCH is
147
+ * allowed and reaches `super.patch`, so if it were NOT semantic the row's
148
+ * `createdAt` could change while `provenance.claimed.createdAt` kept the old
149
+ * value. Making it semantic means a changed creation claim re-stamps, and
150
+ * `claimed.createdAt` follows the row.
151
+ */
152
+ export const MEMORY_SEMANTIC_FIELDS = Object.freeze(["content", "subject", "summary", "createdAt"]);
153
+ /**
154
+ * The fields whose change makes a relationship write SEMANTIC — its identity
155
+ * (what it links), plus its creation claim. Same rule as MEMORY_SEMANTIC_FIELDS:
156
+ * a semantic PATCH re-stamps provenance; a metadata-only PATCH
157
+ * (confidence/source/etc.) leaves the stored, previously-stamped blob in place.
158
+ * `createdAt` is included (flair#1960 r4) for the same reason: a changed
159
+ * creation claim is a re-authored claim, so the PATCH re-stamps and
160
+ * `claimed.createdAt` follows the row.
161
+ */
162
+ export const RELATIONSHIP_SEMANTIC_FIELDS = Object.freeze(["subject", "predicate", "object", "createdAt"]);
163
+ /**
164
+ * True when `content` changes at least one of `fields` relative to the STORED
165
+ * record — the trigger for a provenance re-stamp on the update (PATCH) path.
166
+ *
167
+ * A value that is ABSENT from the write body is never a change (Harper PATCH
168
+ * merges; a missing key means "leave the stored value"), so this only looks at
169
+ * keys actually present in `content`. A non-object body, or a body whose target
170
+ * is not a string/primitive change, is not semantic.
171
+ */
172
+ export function isSemanticPatch(content, existing, fields) {
173
+ if (!content || typeof content !== "object" || Array.isArray(content))
174
+ return false;
175
+ if (!existing || typeof existing !== "object")
176
+ return false;
177
+ for (const field of fields) {
178
+ if (!Object.prototype.hasOwnProperty.call(content, field))
179
+ continue;
180
+ if (content[field] !== existing[field])
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+ /**
186
+ * The response a PATCH returns when its stored-row READ FAILS (flair#1960 r3).
187
+ *
188
+ * A read ERROR is not the same as "no stored row" (a `null`/`undefined`
189
+ * result). Both PATCH paths used to coalesce a thrown read into `null`; the
190
+ * semantic predicate then returns `false` for `null`, and the patch falls
191
+ * through to `super.patch()` as if it were a METADATA-ONLY write — which keeps
192
+ * a legacy stored blob (including a caller-chosen `verified.timestamp`) in
193
+ * place. Without the stored record there is no way to tell a semantic PATCH
194
+ * from a metadata-only one, so the only safe outcome is to REFUSE the write
195
+ * rather than fail open. 500: a server-side read fault, fail-closed.
196
+ */
197
+ export function storedRowReadFailedResponse(table) {
198
+ return new Response(JSON.stringify({
199
+ error: "stored_row_read_failed",
200
+ message: `cannot read the stored ${table} row; refusing the write`,
201
+ }), { status: 500, headers: { "content-type": "application/json" } });
202
+ }
@@ -117,6 +117,10 @@ export const OWNER_GUARD_EXEMPT = Object.freeze({
117
117
  // resources/Agent.ts's shared write-authorization helper, which both its
118
118
  // put() and its patch() route through.
119
119
  Agent: "self-ownership by primary key; enforced in resources/Agent.ts for every verb",
120
+ // flair#1940 A1': MemoryHostSource refuses REST writes. Application pointer
121
+ // writes stamp `authorId` from the authenticated principal; direct resource
122
+ // reads permit admins and trusted internal callers.
123
+ MemoryHostSource: "REST writes refused; application writes stamp authorId; direct reads limited to admins and trusted internal callers",
120
124
  });
121
125
  /** The verbs that can mutate a record, and therefore need the rule applied. */
122
126
  export const MUTATING_METHODS = Object.freeze(["POST", "PUT", "PATCH", "DELETE"]);
@@ -175,6 +179,21 @@ export function isForbiddenOwnerMutation(record, ownerField, callerAgentId) {
175
179
  return true;
176
180
  return owner !== callerAgentId;
177
181
  }
182
+ /**
183
+ * The refusal for a write that names a stored record owned by another
184
+ * principal: 403 with a body that names only the table.
185
+ *
186
+ * One constructor for every place the rule is enforced — the auth middleware
187
+ * for `/<Table>/<id>` routes, and resources/relay-ops.ts for a Message POST to
188
+ * the collection that reuses an existing message id — so a refused caller gets
189
+ * the same response on either route, and it carries nothing from the stored
190
+ * row.
191
+ */
192
+ export function ownerMutationRefusal(table) {
193
+ return new Response(JSON.stringify({
194
+ error: `forbidden: cannot modify ${table} owned by another principal`,
195
+ }), { status: 403, headers: { "Content-Type": "application/json" } });
196
+ }
178
197
  /**
179
198
  * Decide whether a caller may CHANGE the owner field of an already-stored record.
180
199
  *