@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The markers Harper's protocol layers put on the call contexts they build,
3
+ * and the tests that read them. Shared by the caller resolver
4
+ * (resources/agent-auth.ts) and the table-subscription guard
5
+ * (resources/table-subscription-policy.ts), so both read a protocol-layer call
6
+ * the same way. Every test here accepts a shape or a marker; none establishes
7
+ * who built the object. The guard's boundary is protocol-layer callers, whose
8
+ * contexts Harper constructs; in-process code is trusted and may pass objects
9
+ * of any shape (see the policy module).
10
+ *
11
+ * Harper's MQTT layer gives every action of a session a context built by the
12
+ * session itself (server/DurableSubscriptionsSession.ts `createContext()`):
13
+ * `{ session, socket, user, authorize: true, request?, url?, headers? }`, where
14
+ * `session` is the MQTT session object and `request` is present only for MQTT
15
+ * over WebSocket (the upgrade request). Harper's native MCP resource
16
+ * subscriptions use `{ user, authorize: true, request: <RequestTarget> }`, a
17
+ * context with no HTTP request, and its native MCP application tools (get_,
18
+ * search_, create_, update_, delete_ and custom-method tools) use
19
+ * `{ user, authorize: true, checkPermission }`, a context with no request at
20
+ * all. flair has no verified bridge from that Harper user to a flair caller, so
21
+ * the resolver answers anonymous for both until one exists. Harper clears
22
+ * `authorize` once its first entry call has used it (resources/Resource.ts), so
23
+ * the MQTT session object, and on an application tool's context the
24
+ * `checkPermission` property, is the marker that stays on the context.
25
+ *
26
+ * A retained MQTT PUBLISH reaches a table's static put()/delete(), which
27
+ * ordinary writes also use. isDirectMqttSessionContext recognises the session's
28
+ * context there, and isLastWillReplayContext the copy of a stored will record
29
+ * Harper replays. Both accept a shape, and use descriptor and prototype reads
30
+ * only — the argument's own property descriptors, and for a session-marked
31
+ * argument descriptors along the nested session's prototype chain — so on a
32
+ * Harper-constructed or plain-object context they invoke no getter and no
33
+ * `getContext()`. An exotic object (a Proxy) observes those reads, and an
34
+ * error one throws propagates to the caller.
35
+ *
36
+ * This module has no imports, so it is unit-tested directly.
37
+ */
38
+ /**
39
+ * Whether `context` carries an MQTT session's markers: a `socket` key (own or
40
+ * inherited) and a `session` object with an `addSubscription` method, read
41
+ * with ordinary property access (getters run). Used by the caller resolver.
42
+ */
43
+ export function isMqttSessionContext(context) {
44
+ if (context == null || typeof context !== "object")
45
+ return false;
46
+ const c = context;
47
+ if (!("socket" in context) || c.session == null || typeof c.session !== "object")
48
+ return false;
49
+ return typeof c.session.addSubscription === "function";
50
+ }
51
+ /**
52
+ * An own data property's value; undefined for a missing key and for an
53
+ * accessor, which is never invoked.
54
+ */
55
+ function ownDataValue(target, key) {
56
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
57
+ return descriptor && "value" in descriptor ? descriptor.value : undefined;
58
+ }
59
+ /**
60
+ * A data property's value on `target` or its prototype chain; undefined for a
61
+ * missing key and for an accessor, which is never invoked.
62
+ */
63
+ function dataValueInChain(target, key) {
64
+ for (let o = target; o != null; o = Object.getPrototypeOf(o)) {
65
+ const descriptor = Object.getOwnPropertyDescriptor(o, key);
66
+ if (descriptor)
67
+ return "value" in descriptor ? descriptor.value : undefined;
68
+ }
69
+ return undefined;
70
+ }
71
+ /**
72
+ * Whether `value` has the shape of the context Harper's MQTT layer builds
73
+ * for a session's action: an own `socket` property (a data property or an
74
+ * accessor, which is not invoked) and an own data property `session` holding
75
+ * an object whose `addSubscription`, found as a data property along that
76
+ * object's prototype chain, is a function. Harper's `createContext()` returns
77
+ * a plain object literal of this shape, and a session's retained will copies
78
+ * it. This classifies by shape: it does not prove that Harper built the
79
+ * object. It reads the own property descriptor of `socket`; only when one
80
+ * exists, the own descriptor of `session`; and only when that holds an
81
+ * object, descriptors along the session's prototype chain (getPrototypeOf
82
+ * included) until it finds `addSubscription`. It invokes no getter or method
83
+ * of `value` or the session (no `getContext()`, no accessor). A descriptor or
84
+ * prototype read that throws propagates.
85
+ */
86
+ export function isDirectMqttSessionContext(value) {
87
+ if (value == null || typeof value !== "object")
88
+ return false;
89
+ if (!Object.getOwnPropertyDescriptor(value, "socket"))
90
+ return false;
91
+ const session = ownDataValue(value, "session");
92
+ if (session == null || typeof session !== "object")
93
+ return false;
94
+ return typeof dataValueInChain(session, "addSubscription") === "function";
95
+ }
96
+ /**
97
+ * Whether `value` has the shape of the context Harper uses when it replays
98
+ * the last-will messages still stored as its first worker starts (an instance
99
+ * start or a worker restart; server/DurableSubscriptionsSession.ts): a
100
+ * shallow copy of
101
+ * the stored will record (`{ id, topic, data, qos, retain, user }`) on which
102
+ * Harper sets `authorize: true`, passed to put()/delete() for a retained will.
103
+ * It carries no HTTP request and no credential flair verifies; its `user` is
104
+ * the name the session connected with, looked up again. Read from own property
105
+ * descriptors only — `authorize` true, then `topic` a string, then `retain`
106
+ * true, each read only while the previous one matches — so no getter is
107
+ * invoked; a descriptor read that throws propagates. It classifies by shape:
108
+ * an object of that shape is decided as a replayed will wherever it came
109
+ * from.
110
+ */
111
+ export function isLastWillReplayContext(value) {
112
+ if (value == null || typeof value !== "object")
113
+ return false;
114
+ return ownDataValue(value, "authorize") === true
115
+ && typeof ownDataValue(value, "topic") === "string"
116
+ && ownDataValue(value, "retain") === true;
117
+ }
118
+ /**
119
+ * Whether `value` has the shape of Harper's released-transaction sentinel.
120
+ * Harper's sentinel (resources/DatabaseTransaction.ts `RELEASED_TRANSACTION`)
121
+ * is one frozen object, which Harper treats as an absent argument by identity;
122
+ * flair cannot reach that instance. This matcher is broader: it accepts any
123
+ * object, frozen or not, whose own data properties include an `addWrite` and a
124
+ * `setContext` function and `open` 0, read from own property descriptors
125
+ * (`addWrite` first; the others only while the previous ones match). Callers
126
+ * use it only to read an argument both as given and as absent.
127
+ */
128
+ export function isReleasedTransactionPlaceholder(value) {
129
+ if (value == null || typeof value !== "object")
130
+ return false;
131
+ return typeof ownDataValue(value, "addWrite") === "function"
132
+ && typeof ownDataValue(value, "setContext") === "function"
133
+ && ownDataValue(value, "open") === 0;
134
+ }
135
+ /**
136
+ * Whether `value` carries a transaction-shaped object: an own data
137
+ * `transaction` property holding an object with a `commit` method (found as a
138
+ * data property along its prototype chain). Harper tests `instanceof
139
+ * DatabaseTransaction`, a class flair cannot reach; this shape test is
140
+ * broader. Uses descriptor and prototype reads only.
141
+ */
142
+ export function carriesTransaction(value) {
143
+ if (value == null || typeof value !== "object")
144
+ return false;
145
+ const transaction = ownDataValue(value, "transaction");
146
+ if (transaction == null || typeof transaction !== "object")
147
+ return false;
148
+ return typeof dataValueInChain(transaction, "commit") === "function";
149
+ }
150
+ /**
151
+ * Whether `value` has the shape of the context Harper's native MCP application
152
+ * tools build for each call (components/mcp/tools/application.ts
153
+ * `buildContext()`): `{ user, authorize: true, checkPermission }`, where
154
+ * `checkPermission` is the Harper user's role permission object (`{}` when the
155
+ * role has none). It carries no `request`. Harper clears `authorize` once its
156
+ * first entry call has used it (resources/Resource.ts) and leaves
157
+ * `checkPermission`, so `checkPermission` is the marker that stays on the
158
+ * context through the resource's authorization hooks and its handlers. The
159
+ * test: an own data property `checkPermission` whose value is neither null,
160
+ * undefined nor false, and no own data property `request` holding a value
161
+ * other than null or undefined (an accessor `request` is not invoked and does
162
+ * not count as a request). Read from own property descriptors only
163
+ * (`checkPermission` first, `request` only when it matches), so no getter is
164
+ * invoked; a descriptor read that throws propagates. It classifies by shape:
165
+ * it does not prove that Harper built the object.
166
+ */
167
+ export function isPermissionMarkedRequestlessContext(value) {
168
+ if (value == null || typeof value !== "object")
169
+ return false;
170
+ const permission = ownDataValue(value, "checkPermission");
171
+ if (permission == null || permission === false)
172
+ return false;
173
+ return ownDataValue(value, "request") == null;
174
+ }
175
+ /**
176
+ * Whether `context` carries a protocol layer's markers: an MQTT session's
177
+ * markers (isMqttSessionContext); `authorize: true`, which Harper's protocol
178
+ * layers set to ask for authorization and clear once it is used; or the
179
+ * requestless, permission-marked shape of a native MCP application tool's
180
+ * context (isPermissionMarkedRequestlessContext), which keeps its marker after
181
+ * `authorize` is cleared.
182
+ */
183
+ export function isProtocolLayerContext(context) {
184
+ if (context == null || typeof context !== "object")
185
+ return false;
186
+ return context.authorize === true
187
+ || isMqttSessionContext(context)
188
+ || isPermissionMarkedRequestlessContext(context);
189
+ }
@@ -136,10 +136,8 @@ function ownerOnlyReadScope(ownerField) {
136
136
  }
137
137
  /**
138
138
  * Resolve the read-scope resolver for a table, by mode:
139
- * - "owner-only": own records only, scoped on `ownerField` (defaults to
140
- * "agentId" — every current owner-only caller uses that field; the
141
- * parameter exists so a future owner-only type using a different field,
142
- * the way OrgEvent's WRITE path uses "authorId", isn't hardcoded out).
139
+ * - "owner-only": own records only, scoped on `ownerField`. The owner field
140
+ * defaults to "agentId"; Credential supplies "principalId".
143
141
  * - "open-within-org": delegates to the EXACT existing
144
142
  * resolveReadScope()/PRIVATE_VISIBILITY semantics in
145
143
  * ./memory-read-scope.ts — Memory's own module, untouched, not
@@ -13,7 +13,7 @@
13
13
  * Everything else is canonical, including `%2F` and `%5C` inside a segment, a
14
14
  * dot inside a segment (`a.b`), and any query string.
15
15
  *
16
- * PURE: string logic only, imports nothing.
16
+ * PURE: no imports and no I/O; the comparisons use the global `URL`.
17
17
  */
18
18
  /** The named error a non-canonical request target is refused with. */
19
19
  export const NON_CANONICAL_REQUEST_TARGET_ERROR = "non_canonical_request_target";
@@ -26,6 +26,33 @@ export function requestPath(rawTarget) {
26
26
  const q = rawTarget.indexOf("?");
27
27
  return q === -1 ? rawTarget : rawTarget.slice(0, q);
28
28
  }
29
+ /** The query part of a raw request target: everything after the first `?` ("" when none). */
30
+ export function requestQuery(rawTarget) {
31
+ const q = rawTarget.indexOf("?");
32
+ return q === -1 ? "" : rawTarget.slice(q + 1);
33
+ }
34
+ /** True when the serialized WHATWG `pathname + search` equals `rawTarget`. */
35
+ export function whatwgUrlMatchesRawTarget(rawTarget) {
36
+ let url;
37
+ try {
38
+ url = new URL(rawTarget, "http://localhost");
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ return url.pathname + url.search === rawTarget;
44
+ }
45
+ /** True when the serialized WHATWG `search` without its leading `?` equals `requestQuery(rawTarget)`. */
46
+ export function whatwgQueryMatchesRawTarget(rawTarget) {
47
+ let url;
48
+ try {
49
+ url = new URL(rawTarget, "http://localhost");
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ return url.search.slice(1) === requestQuery(rawTarget);
55
+ }
29
56
  /** True when a raw request target is in canonical form (see the module header). */
30
57
  export function isCanonicalRequestTarget(rawTarget) {
31
58
  const path = requestPath(rawTarget);
@@ -1,3 +1,4 @@
1
+ import { currentWriteJournal } from "./write-journal-context.js";
1
2
  /**
2
3
  * request-transaction.ts — one shared write scope for the host-pointer path
3
4
  * (flair#1940 slice 1). A Memory row and its `MemoryHostSource` pointer row
@@ -54,7 +55,16 @@ export async function withSharedWriteTransaction(ctx, fn) {
54
55
  if (!txn) {
55
56
  throw new Error("flair: Harper's transaction() is unavailable — refusing to run a Memory/pointer write unwrapped (A7: no silent loss)");
56
57
  }
57
- return (await txn(shared, () => fn(shared)));
58
+ const journal = currentWriteJournal();
59
+ if (!journal)
60
+ return (await txn(shared, () => fn(shared)));
61
+ return journal.transaction(shared, (capture, complete) => txn(shared, async () => {
62
+ capture();
63
+ const result = await fn(shared);
64
+ journal.assertCoverage();
65
+ complete();
66
+ return result;
67
+ }));
58
68
  }
59
69
  /**
60
70
  * Run `fn` in a transaction this call OWNS even when `ctx` already carries an
@@ -29,8 +29,7 @@
29
29
  * FeedMemories check caller-chosen ids before writing; federation skips a
30
30
  * reserved id (`seed_id_not_federated`). Server bookkeeping is also allowed:
31
31
  * lastReflected and embedding backfill update their selected fields. Usage
32
- * recording intends to change only usageCount, but re-PUTs the stored row and
33
- * can receive an agent-supplied id. The coverage test classifies raw Memory
32
+ * recording can receive an agent-supplied id. The coverage test classifies raw Memory
34
33
  * write sites detected by its supported source patterns; it does not prove
35
34
  * that every possible write path is classified.
36
35
  */
@@ -64,6 +64,7 @@ import { isAllowedBm25Candidate } from "./bm25-filter.js";
64
64
  import { indexedBm25Ids } from "./bm25-index-service.js";
65
65
  import { byRecencyThenId } from "./sort-comparators.js";
66
66
  import { isTrustedVectorStamp, trustedVectorCondition } from "./embedding-space-guard.js";
67
+ import { applyPromotionBinding } from "./promotion-binding.js";
67
68
  /**
68
69
  * The only way a row enters the ranked pool. `_rank` is a required
69
70
  * argument — not an object property that `...any` can swallow — so a
@@ -98,7 +99,7 @@ function distanceToSimilarity(distance) {
98
99
  // a permitted reader would never see their pointer.
99
100
  export const DEFAULT_SELECT = ["id", "agentId", "content", "contentHash", "visibility", "instanceToken", "tags", "durability",
100
101
  "source", "createdAt", "updatedAt", "expiresAt", "retrievalCount", "usageCount", "lastRetrieved",
101
- "promotionStatus", "promotedAt", "promotedBy", "archived", "archivedAt", "archivedBy",
102
+ "promotionStatus", "promotedAt", "promotedBy", "promotionContentHash", "archived", "archivedAt", "archivedBy",
102
103
  "parentId", "derivedFrom", "sessionId", "lastReflected", "supersedes", "subject", "summary",
103
104
  "validFrom", "validTo", "_safetyFlags"];
104
105
  export async function retrieveCandidates(params) {
@@ -297,7 +298,7 @@ export async function retrieveCandidates(params) {
297
298
  const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
298
299
  const source = record.agentId !== agentId ? record.agentId : undefined;
299
300
  pushRanked(results, {
300
- ...record,
301
+ ...applyPromotionBinding(record),
301
302
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
302
303
  _score: Math.round(finalScore * 1000) / 1000,
303
304
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -357,7 +358,7 @@ export async function retrieveCandidates(params) {
357
358
  // composite mode (composite ordering is unchanged by #985 — its
358
359
  // rrfRaw input and result order are exactly the pre-#985 behavior).
359
360
  pushRanked(results, {
360
- ...record,
361
+ ...applyPromotionBinding(record),
361
362
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
362
363
  _score: Math.round(finalScore * 1000) / 1000,
363
364
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -458,7 +459,7 @@ export async function retrieveCandidates(params) {
458
459
  const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
459
460
  const source = record.agentId !== agentId ? record.agentId : undefined;
460
461
  pushRanked(results, {
461
- ...record,
462
+ ...applyPromotionBinding(record),
462
463
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
463
464
  _score: Math.round(finalScore * 1000) / 1000,
464
465
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -525,7 +526,7 @@ export async function retrieveCandidates(params) {
525
526
  // bump) is the abstention confidence signal on this legacy/bootstrap
526
527
  // (HNSW-leg-only) path.
527
528
  pushRanked(results, {
528
- ...rest,
529
+ ...applyPromotionBinding(rest),
529
530
  content: isFlagged ? wrapUntrusted(rest.content, source) : rest.content,
530
531
  _score: Math.round(finalScore * 1000) / 1000,
531
532
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -571,7 +572,7 @@ export async function retrieveCandidates(params) {
571
572
  const isFlagged = rest._safetyFlags && Array.isArray(rest._safetyFlags) && rest._safetyFlags.length > 0;
572
573
  const source = record.agentId !== agentId ? record.agentId : undefined;
573
574
  pushRanked(results, {
574
- ...rest,
575
+ ...applyPromotionBinding(rest),
575
576
  content: isFlagged ? wrapUntrusted(rest.content, source) : rest.content,
576
577
  _score: Math.round(finalScore * 1000) / 1000,
577
578
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -0,0 +1,71 @@
1
+ /**
2
+ * flair#2997 — validate a row the server built with its own table's validator
3
+ * before staging it, so a schema defect in server-built data is a server error,
4
+ * not a caller error.
5
+ *
6
+ * `databases.flair.<Table>` is the table class. The validator the commit path
7
+ * runs is the one on the class prototype: Harper's staged-write validate
8
+ * closure calls `this.validate(recordUpdate, !fullUpdate)` (harper 5.3.1,
9
+ * resources/Table.ts), and `this.validate` on a table instance resolves to that
10
+ * prototype method. The class itself has no static `validate`.
11
+ *
12
+ * On the pinned Harper a row refused here is refused at commit with the same
13
+ * issues (proven on a live instance for InstructionVersion and OrgEvent: the
14
+ * pre-validation and the staging path raised identical `errors` arrays and the
15
+ * accepted row stored byte-identical). A failure is therefore a server defect,
16
+ * not a caller error.
17
+ *
18
+ * The rows validated here are built by the server: the A2A and
19
+ * agent-key-register events coerce their caller-derived fields to the schema's
20
+ * types where they are assigned, the instruction-version event is built from
21
+ * version fields, with caller-derived values converted or serialized to the
22
+ * schema's types, and the migration-ledger and graph-heal rows come from
23
+ * migration data. A schema failure on one is therefore a server defect, not a
24
+ * caller error. A Memory successor or close row carries the caller's fields
25
+ * without that coercion, so it keeps the commit-time path: a defect in one of
26
+ * its fields, a server-stamped field included, answers the caller's 400 rather
27
+ * than 5xx.
28
+ */
29
+ export class ServerRowValidationError extends Error {
30
+ constructor(tableName, cause) {
31
+ super(`the server built an invalid ${tableName} row; the write was aborted`, { cause });
32
+ this.name = "ServerRowValidationError";
33
+ }
34
+ }
35
+ /**
36
+ * The table handle exposes no validator: a Harper change removed the entry
37
+ * point this check depends on. Distinct from {@link ServerRowValidationError}
38
+ * (an invalid row) so the reason is visible in the server log and a test can
39
+ * tell them apart. The write is still refused (fail closed).
40
+ */
41
+ export class ServerRowValidatorMissingError extends Error {
42
+ constructor(tableName) {
43
+ super(`the ${tableName} table handle exposes no validator; the write was aborted`);
44
+ this.name = "ServerRowValidatorMissingError";
45
+ }
46
+ }
47
+ /**
48
+ * Run the table's own `validate(record, patch)` on the exact object about to
49
+ * be staged. `patch` must be the commit's flag (`false` for the full-row
50
+ * creates/puts this helper serves).
51
+ *
52
+ * Throws {@link ServerRowValidationError} when the validator refuses the row
53
+ * and {@link ServerRowValidatorMissingError} when the handle exposes no
54
+ * validator — never a Harper `ValidationError`, so a caller-row 400 path cannot
55
+ * claim it. The caller's catch aborts the transaction and answers its 5xx
56
+ * shape.
57
+ */
58
+ export function validateServerRow(table, record, patch = false) {
59
+ const tableName = typeof table?.name === "string" && table.name.length > 0 ? table.name : "unknown";
60
+ const holder = table?.prototype && typeof table.prototype.validate === "function" ? table.prototype : table;
61
+ const validate = holder?.validate;
62
+ if (typeof validate !== "function")
63
+ throw new ServerRowValidatorMissingError(tableName);
64
+ try {
65
+ validate.call(table, record, patch);
66
+ }
67
+ catch (err) {
68
+ console.error("flair: a server-built row failed its table validator; the write was aborted (table %s)", tableName, err);
69
+ throw new ServerRowValidationError(tableName, err);
70
+ }
71
+ }
@@ -49,9 +49,10 @@ function isPast(value, now) {
49
49
  return typeof value === "string" && value.length > 0 && Date.parse(value) < now;
50
50
  }
51
51
  /**
52
- * The rows passed to resolveSkillRef: skill-tagged, readable by the target agent
53
- * (`isReadable`, the read-scope predicate `skill_get` applies), not archived,
54
- * and not closed (`validTo`) or expired (`expiresAt`).
52
+ * The rows passed to resolveSkillRef. Candidates must be skill-tagged, pass the
53
+ * supplied read-scope predicate (`isReadable`), be unarchived, and have neither
54
+ * `validTo` nor `expiresAt` parsing to a past time; this helper does not apply
55
+ * the closed-skill current-authority check.
55
56
  */
56
57
  export function resolvableSkillRows(rows, isReadable, now = Date.now()) {
57
58
  return rows.filter((row) => typeof row.id === "string"