@tpsdev-ai/flair 0.62.0 → 0.63.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,10 +1,13 @@
1
+ import { WriteJournal, currentWriteJournal } from "./write-journal.js";
2
+ import { withKeyLock } from "./key-lock.js";
3
+ import { withMemoryWriteLock } from "./memory-write-lock.js";
1
4
  import { normalizeEmptyEmbedding } from "./memory-embedding-value.js";
2
5
  /** Skill writes share the ["flair-instruction-version", "skill"] lock. */
3
6
  import { databases } from "harper";
4
7
  import { storageResult } from "./memory-write-response.js";
5
8
  import { randomUUID } from "node:crypto";
6
9
  import { isDeepStrictEqual } from "node:util";
7
- import { recordVersion, readHead, skillRefReadable, SKILL_SUBJECT_TYPE } from "./instruction-version-record.js";
10
+ import { recordVersion, readHead, readVersionRecord, readVersionRecordAfter, skillRefReadable, SKILL_SUBJECT_TYPE } from "./instruction-version-record.js";
8
11
  import { SKILL_TAG, enforceSkillDurability, skillEmbedText, skillMetadataHasDuplicateKey } from "./skill-write.js";
9
12
  import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
10
13
  import { skillWriteSource } from "./skill-write-policy.js";
@@ -13,9 +16,11 @@ import { FORBIDDEN } from "./record-type-kit.js";
13
16
  import { PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
14
17
  import { maybeThrowSkillWriteFault } from "./skill-write-fault.js";
15
18
  import { supersedesTargetUnreadable } from "./memory-id-guard.js";
16
- import { grantedCloseRevokedRefusal, writeGrantHeld } from "./write-back.js";
19
+ import { grantedCloseRevokedRefusal, sameStoredRow, storedRowChangedRefusal, writeGrantHeld } from "./write-back.js";
20
+ import { isJoinableTransaction, withOwnedTransaction } from "./request-transaction.js";
17
21
  import { txnPausePoint } from "./txn-pause-point.js";
18
22
  import { committedVisibilityDiffers, grantedSuccessorVisibilityDenial, predecessorVisibilityChangedRefusal } from "./grant-visibility.js";
23
+ import { isOpenLiveRow } from "../src/lib/open-live-row.js";
19
24
  /** Durability-keyed default visibility (mirrors Memory's write default). */
20
25
  function defaultVisibilityForDurability(durability) {
21
26
  return durability === "permanent" || durability === "persistent" ? "shared" : "private";
@@ -114,17 +119,6 @@ export function buildSkillSuccessorRow(args) {
114
119
  function okResponse() {
115
120
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "Content-Type": "application/json" } });
116
121
  }
117
- function isOpenLiveRow(row) {
118
- if (!row || typeof row !== "object")
119
- return false;
120
- if (row.archived === true)
121
- return false;
122
- if (row.expiresAt != null && (typeof row.expiresAt !== "string" || !(Date.parse(row.expiresAt) > Date.now())))
123
- return false;
124
- if (typeof row.validTo === "string" && row.validTo.length > 0)
125
- return false;
126
- return true;
127
- }
128
122
  /** Is this row a skill-tagged Memory row? */
129
123
  export function rowIsSkill(row) {
130
124
  return !!row && Array.isArray(row.tags) && row.tags.includes(SKILL_TAG);
@@ -198,7 +192,7 @@ export async function prepareSkillBody(content, stored, auth) {
198
192
  delete effective.id;
199
193
  return { content: effective, predecessor };
200
194
  }
201
- /** Select exactly one open row; ambiguity refuses. */
195
+ /** Return the sole live head, or null if none; refuse ambiguity. */
202
196
  export async function resolveSkillHead(subjectId, addressedId, shared) {
203
197
  const table = databases.flair?.Memory;
204
198
  if (!table || typeof table.search !== "function")
@@ -275,6 +269,11 @@ export async function validateSkillSnapshots(stored, predecessor, targetId, shar
275
269
  export const defaultSkillHooks = {
276
270
  createSuccessor: async (successor, shared) => {
277
271
  normalizeEmptyEmbedding(successor);
272
+ // Not pre-validated: this row carries the caller's fields without that
273
+ // coercion, so a defect in it — a server-stamped field included — stays a
274
+ // caller error (400) at commit. Pre-validation covers the A2A,
275
+ // agent-key-register and instruction-version writer events and the
276
+ // migration rows (resources/server-row-validation.ts).
278
277
  const result = storageResult(await databases.flair.Memory.put(successor, shared));
279
278
  if (result instanceof Response)
280
279
  return result;
@@ -283,6 +282,8 @@ export const defaultSkillHooks = {
283
282
  closePredecessor: async (predecessor, patch, shared) => {
284
283
  const closed = { ...predecessor, ...patch };
285
284
  normalizeEmptyEmbedding(closed);
285
+ // Not pre-validated: a close carries the caller's row; its defects stay a
286
+ // caller error at commit (see the successor note above).
286
287
  const result = storageResult(await databases.flair.Memory.put(closed, shared));
287
288
  if (result instanceof Response)
288
289
  return result;
@@ -293,20 +294,17 @@ export const defaultSkillHooks = {
293
294
  * close or a delete's head close. A grant-authorized cross-agent close stands on
294
295
  * the grant read at authorization time; re-read it on committed state HERE,
295
296
  * after the close is staged, through the shared write-back helper the non-skill
296
- * close uses (Memory.ts closeSupersededRecord, flair#2333 H10). Returns the named
297
- * 409 when the grant is gone — the caller returns it, so the whole transaction
298
- * rolls back: no close, no successor, no version — else null. A plan with no
299
- * grant (same-agent, operator, internal) reads nothing.
297
+ * close uses (Memory.ts closeSupersededRecord, flair#2333 H10).
300
298
  *
301
299
  * For a grant-authorized supersede, `successor` is the planned successor row.
302
300
  * Before the grant re-check, the predecessor's COMMITTED row (an empty-context
303
301
  * read, as for the grant) must read with the successor's visibility: a write
304
302
  * grant does not include changing a record's visibility (grant-visibility.ts).
305
- * A mismatch returns the named 409 predecessor_visibility_changed, and the
306
- * whole write rolls back the same way. As with the grant, a change committed
303
+ * A mismatch returns the named 409 predecessor_visibility_changed.
304
+ * As with the grant, a change committed
307
305
  * after this re-read and before the transaction commits is not seen by it.
308
306
  */
309
- async function afterCloseStaged(granted, supersede) {
307
+ export async function afterCloseStaged(granted, supersede) {
310
308
  // Test-only: inert unless armed — here the close write is staged, so a
311
309
  // competing grant revocation or row change and the committed-state re-checks
312
310
  // below can be exercised in either order (the skill-path counterpart of Memory's "granted-close-staged").
@@ -323,9 +321,280 @@ async function afterCloseStaged(granted, supersede) {
323
321
  const held = await writeGrantHeld(databases.flair.MemoryGrant, granted.granteeId, granted.ownerId, {});
324
322
  return held ? null : grantedCloseRevokedRefusal();
325
323
  }
324
+ /** Attempts at re-applying a skill update's close whose committed write did not land (flair#2645). */
325
+ const SKILL_UPDATE_CLOSE_ATTEMPTS = 3;
326
+ /** No caller-held Memory ids. */
327
+ const NO_HELD_IDS = new Set();
328
+ /**
329
+ * Acquire missing Memory ids in sorted order. Inline compensation skips
330
+ * caller-held ids; deferred confirmation and compensation reacquire after
331
+ * release (flair#2950).
332
+ * Returns `locked: false` when a missing id's lock could not be taken.
333
+ */
334
+ async function withSkillMemoryLocks(ids, held, fn) {
335
+ const missing = [...new Set(ids.map((id) => String(id)))].filter((id) => !held.has(id)).sort();
336
+ if (missing.length === 0)
337
+ return { locked: true, value: await fn() };
338
+ const outcome = await withMemoryWriteLock(databases?.flair?.Memory?.primaryStore, missing, fn, {
339
+ phase: "skill-version-write",
340
+ });
341
+ return outcome.kind === "done" ? { locked: true, value: outcome.value } : { locked: false };
342
+ }
343
+ /** The named 500 when the skill update cannot be confirmed. */
344
+ function skillUpdateUnconfirmedFailure() {
345
+ return Response.json({
346
+ error: "skill_update_unconfirmed",
347
+ message: "the skill update could not be confirmed",
348
+ }, { status: 500 });
349
+ }
350
+ /** The named 409 for an update whose close still is not visible after the bounded re-applies. */
351
+ function skillUpdateNotClosedRefusal(attempts) {
352
+ return Response.json({
353
+ error: "skill_update_not_closed",
354
+ message: `the skill version close was not applied after ${attempts} attempts; not updated`,
355
+ }, { status: 409 });
356
+ }
357
+ /** The named 409 when neither a sole live successor nor ordered supersession is confirmed. */
358
+ function skillUpdateNotConfirmedRefusal() {
359
+ return Response.json({
360
+ error: "skill_update_not_confirmed",
361
+ message: "the committed store confirms neither this update's successor as the only live head nor its closure with this request's version record present, the record with the next sequence number linked to it by hash, and that later version deleting the successor or its row naming the successor as superseded",
362
+ }, { status: 409 });
363
+ }
364
+ /** The named 500 when compensation cannot be confirmed. */
365
+ function skillUpdateCompensationFailure(message) {
366
+ return Response.json({ error: "skill_update_compensation_failed", message }, { status: 500 });
367
+ }
368
+ async function compensateUnlandedSkillUpdate(args) {
369
+ args.journal.compensationAttempted = true;
370
+ try {
371
+ const table = databases.flair?.InstructionVersion;
372
+ // Memory id locks before the instruction-version lock (the global order),
373
+ // so the undo's Memory writes are serialized with the other per-id-locked
374
+ // writers of those ids, not just the version append (flair#2950).
375
+ const locked = await withSkillMemoryLocks(args.journal.memoryWriteIds(), args.held ?? NO_HELD_IDS, async () => withKeyLock(table?.primaryStore, ["flair-instruction-version", "skill"], async () => {
376
+ const appended = [...args.journal.entries].reverse().find((entry) => entry.after?.subjectType === "skill");
377
+ if (appended) {
378
+ const head = await readHead(SKILL_SUBJECT_TYPE, appended.after.subjectId, {});
379
+ if (head && String(head.id) !== String(appended.after.id))
380
+ return false;
381
+ }
382
+ return args.journal.undo(args.ctx, withOwnedTransaction);
383
+ }, 200, 10));
384
+ if (!locked.locked)
385
+ throw new Error("the Memory write lock could not be acquired for the skill write's undo");
386
+ const result = locked.value;
387
+ if (result.kind === "done" && result.value)
388
+ return null;
389
+ }
390
+ catch (err) {
391
+ console.error("skill-version-write: update undo could not be confirmed", err);
392
+ }
393
+ return skillUpdateCompensationFailure("the skill write's undo could not be confirmed; check its outcome, because its version and event may persist" +
394
+ (args.journal.pointerChanged ? "; a different host-pointer row was left in place" : ""));
395
+ }
396
+ /**
397
+ * flair#2645 — confirm a closed successor only when this request's update
398
+ * record is present, the record with the next sequence number links to it by
399
+ * hash, and that later version either deletes this successor (its `rowId`) or
400
+ * has a row that names this successor as superseded.
401
+ */
402
+ async function confirmSupersededInOrder(args) {
403
+ if (!args.appendedVersionId)
404
+ return skillUpdateNotConfirmedRefusal();
405
+ let appended;
406
+ let following;
407
+ try {
408
+ appended = await readVersionRecord(SKILL_SUBJECT_TYPE, args.subjectId, args.appendedVersionId, {});
409
+ following = appended
410
+ ? await readVersionRecordAfter(SKILL_SUBJECT_TYPE, args.subjectId, appended.version, {})
411
+ : null;
412
+ }
413
+ catch {
414
+ return skillUpdateUnconfirmedFailure();
415
+ }
416
+ if (!appended || appended.kind !== "update" || String(appended.memoryId) !== String(args.successor.id)) {
417
+ return skillUpdateNotConfirmedRefusal();
418
+ }
419
+ if (!following || following.previousVersionHash !== appended.recordHash)
420
+ return skillUpdateNotConfirmedRefusal();
421
+ if (following.kind === "delete") {
422
+ return String(following.rowId ?? "") === String(args.successor.id) ? null : skillUpdateNotConfirmedRefusal();
423
+ }
424
+ if (following.kind !== "update")
425
+ return skillUpdateNotConfirmedRefusal();
426
+ const followingId = typeof following.memoryId === "string" ? following.memoryId : null;
427
+ if (!followingId)
428
+ return skillUpdateNotConfirmedRefusal();
429
+ let followingRow;
430
+ try {
431
+ followingRow = await args.memory.get(followingId, {});
432
+ }
433
+ catch {
434
+ return skillUpdateUnconfirmedFailure();
435
+ }
436
+ if (!followingRow || String(followingRow.supersedes ?? "") !== String(args.successor.id)) {
437
+ return skillUpdateNotConfirmedRefusal();
438
+ }
439
+ return null;
440
+ }
441
+ /**
442
+ * flair#2645 — confirm a skill close in a fresh committed read, then answer
443
+ * success only when the committed store shows it. Harper can resolve the
444
+ * close's commit while skipping the queued full put (it loses to a newer write
445
+ * of the same row) and still commit the request's other writes. A close that
446
+ * did not land is re-applied from a fresh read, re-checking the row's identity
447
+ * and the caller's authority. Exhausted retries run compensation before the
448
+ * named refusal; unconfirmed compensation returns a named 500.
449
+ * Returns null only when the close and any caller-supplied effect are confirmed.
450
+ */
451
+ export async function confirmSkillClose(args) {
452
+ const journal = currentWriteJournal() ?? new WriteJournal();
453
+ return journal.run(async () => {
454
+ const result = await confirmSkillCloseInner(args, journal);
455
+ if (result && !journal.compensationAttempted && journal.entries.some((entry) => entry.applied)) {
456
+ return (await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal, held: args.held })) ?? result;
457
+ }
458
+ return result;
459
+ });
460
+ }
461
+ async function confirmSkillCloseInner(args, journal) {
462
+ const { ctx, table, expected, closePatch, authorize, afterStaged, confirmEffect, refusal, unconfirmed } = args;
463
+ const compensate = () => compensateUnlandedSkillUpdate({ ctx, journal, held: args.held });
464
+ const attempts = args.attempts ?? SKILL_UPDATE_CLOSE_ATTEMPTS;
465
+ const id = String(expected.id);
466
+ for (let attempt = 1;; attempt++) {
467
+ let committed;
468
+ try {
469
+ committed = await table.get(id, {});
470
+ }
471
+ catch {
472
+ return unconfirmed();
473
+ }
474
+ if (!committed) {
475
+ const denied = args.missing?.() ?? storedRowChangedRefusal("Memory");
476
+ return (await compensate()) ?? denied;
477
+ }
478
+ if (!sameStoredRow(committed, expected)) {
479
+ // Replaced between the reads: not the row the caller meant.
480
+ return (await compensate()) ?? storedRowChangedRefusal("Memory");
481
+ }
482
+ if (typeof committed.validTo === "string" && committed.validTo.length > 0) {
483
+ const denied = confirmEffect ? await confirmEffect() : null;
484
+ return denied ? (await compensate()) ?? denied : null;
485
+ }
486
+ if (attempt > attempts)
487
+ break;
488
+ let applied;
489
+ try {
490
+ // Hold the row's id across the retry's fresh transaction (flair#2950).
491
+ const locked = await withSkillMemoryLocks([id], args.held ?? NO_HELD_IDS, () => withOwnedTransaction(ctx, async (c) => {
492
+ const stored = await table.get(id, c);
493
+ if (!stored)
494
+ return "staged";
495
+ if (!sameStoredRow(stored, expected))
496
+ return storedRowChangedRefusal("Memory");
497
+ const denied = await authorize(stored, c);
498
+ if (denied)
499
+ return denied;
500
+ const closed = { ...stored, ...closePatch };
501
+ normalizeEmptyEmbedding(closed);
502
+ const result = storageResult(await table.put(closed, c));
503
+ if (result instanceof Response)
504
+ throw result;
505
+ const revoked = await afterStaged?.(stored, attempt);
506
+ if (revoked)
507
+ throw revoked;
508
+ return "staged";
509
+ }));
510
+ if (!locked.locked)
511
+ return unconfirmed();
512
+ applied = locked.value;
513
+ }
514
+ catch (err) {
515
+ if (err instanceof Response)
516
+ applied = err;
517
+ else
518
+ return unconfirmed();
519
+ }
520
+ if (applied instanceof Response)
521
+ return (await compensate()) ?? applied;
522
+ }
523
+ return (await compensate()) ?? refusal();
524
+ }
525
+ /**
526
+ * flair#2645 — confirm the predecessor close and either this request's
527
+ * successor as the subject's only live head or its ordered supersession while closed.
528
+ */
529
+ async function confirmSkillUpdate(args) {
530
+ const { ctx, subjectId, predecessor, closePatch, successor, grantedClose, authorize } = args;
531
+ const table = databases.flair?.Memory;
532
+ if (!table || typeof table.get !== "function" || typeof table.put !== "function") {
533
+ return skillUpdateUnconfirmedFailure();
534
+ }
535
+ const confirmsSingleHead = async () => {
536
+ let successorCommitted;
537
+ try {
538
+ successorCommitted = await table.get(String(successor.id), {});
539
+ }
540
+ catch {
541
+ return skillUpdateUnconfirmedFailure();
542
+ }
543
+ if (!successorCommitted || !sameStoredRow(successorCommitted, successor)) {
544
+ return skillUpdateNotConfirmedRefusal();
545
+ }
546
+ if (!isOpenLiveRow(successorCommitted)) {
547
+ if (typeof successorCommitted.validTo !== "string" || successorCommitted.validTo.length === 0) {
548
+ return skillUpdateNotConfirmedRefusal();
549
+ }
550
+ // The successor is closed; confirm the ordered supersession.
551
+ return confirmSupersededInOrder({
552
+ subjectId,
553
+ successor,
554
+ appendedVersionId: args.appendedVersionId,
555
+ memory: table,
556
+ });
557
+ }
558
+ if (typeof table.search !== "function")
559
+ return skillUpdateUnconfirmedFailure();
560
+ const live = [];
561
+ try {
562
+ for await (const row of table.search({ conditions: [
563
+ { attribute: "skillSubjectId", comparator: "equals", value: subjectId },
564
+ ] }, {})) {
565
+ if (isOpenLiveRow(row))
566
+ live.push(String(row.id));
567
+ }
568
+ }
569
+ catch {
570
+ return skillUpdateUnconfirmedFailure();
571
+ }
572
+ return live.length === 1 && live[0] === String(successor.id) ? null : skillUpdateNotConfirmedRefusal();
573
+ };
574
+ return confirmSkillClose({
575
+ ctx,
576
+ table,
577
+ expected: predecessor,
578
+ closePatch,
579
+ authorize,
580
+ afterStaged: async (_row, attempt) => {
581
+ const pause = attempt === 1 ? txnPausePoint("skill-update-retry-first")
582
+ : attempt === 2 ? txnPausePoint("skill-update-retry-second")
583
+ : txnPausePoint("skill-update-retry-third");
584
+ if (pause)
585
+ await pause;
586
+ return afterCloseStaged(grantedClose, { predecessorId: String(predecessor.id), successor });
587
+ },
588
+ confirmEffect: confirmsSingleHead,
589
+ missing: () => storedRowChangedRefusal("Memory"),
590
+ refusal: () => skillUpdateNotClosedRefusal(SKILL_UPDATE_CLOSE_ATTEMPTS),
591
+ unconfirmed: skillUpdateUnconfirmedFailure,
592
+ held: args.held,
593
+ });
594
+ }
326
595
  /**
327
596
  * Run one skill version write atomically. The append helper owns the lock, the
328
- * transaction and the version row; this function performs the Memory-side
597
+ * version row; this function performs the Memory-side
329
598
  * successor/close/pointer writes inside that same transaction.
330
599
  */
331
600
  export async function runSkillVersionWrite(args) {
@@ -334,8 +603,33 @@ export async function runSkillVersionWrite(args) {
334
603
  // request context, which would surface as HTTP 201. The path a skill write
335
604
  // replaces returned 200, so restore the flag's prior value on the way out.
336
605
  const restoreCreated = captureCreatedFlag(args.ctx);
606
+ const held = new Set((args.heldMemoryIds ?? []).map((id) => String(id)));
337
607
  try {
338
- return await runSkillVersionWriteInner(args);
608
+ const journal = new WriteJournal();
609
+ const result = await journal.run(async () => {
610
+ const r = await runSkillVersionWriteInner(args);
611
+ if (!r.ok && !journal.compensationAttempted && journal.entries.some((entry) => entry.applied)) {
612
+ const failure = await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal, held });
613
+ if (failure)
614
+ return { ok: false, response: failure };
615
+ }
616
+ return r;
617
+ });
618
+ if (result.ok && result.confirm) {
619
+ const confirm = result.confirm;
620
+ return {
621
+ ...result,
622
+ confirm: async () => {
623
+ const denial = await confirm();
624
+ if (!denial)
625
+ return null;
626
+ // The caller released the write's Memory locks before this ran.
627
+ const failure = await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal });
628
+ return failure ?? denial;
629
+ },
630
+ };
631
+ }
632
+ return result;
339
633
  }
340
634
  finally {
341
635
  restoreCreated();
@@ -355,18 +649,42 @@ export function captureCreatedFlag(ctx) {
355
649
  }
356
650
  };
357
651
  }
652
+ /** A plan whose success {@link confirmSkillUpdate} checks after the commit. */
653
+ function supersedesPredecessor(plan) {
654
+ return plan.kind === "update" && !!plan.predecessor;
655
+ }
656
+ /** A joined attempt's signal that its plan needs a commit this write owns. */
657
+ const OWNED_COMMIT_REQUIRED = Symbol("skill-version-write.owned-commit-required");
358
658
  async function runSkillVersionWriteInner(args) {
659
+ const joined = args.joinCallerTransaction === true && isJoinableTransaction(args.ctx);
660
+ const first = await runSkillVersionAttempt(args, joined);
661
+ if (first !== OWNED_COMMIT_REQUIRED)
662
+ return first;
663
+ // flair#2645: the update is confirmed against the committed store after its
664
+ // commit, which a joined write leaves to the caller. The joined attempt
665
+ // stopped before staging a write; plan again from a fresh head, owned.
666
+ const owned = await runSkillVersionAttempt(args, false);
667
+ if (owned === OWNED_COMMIT_REQUIRED)
668
+ throw new Error("skill-version-write: an owned attempt cannot require an owned commit");
669
+ return owned;
670
+ }
671
+ async function runSkillVersionAttempt(args, joined) {
359
672
  let plan = null;
360
673
  let owner = "";
361
- return recordVersion(args.ctx, {
674
+ let ownedCommitRequired = false;
675
+ const outcome = await recordVersion(args.ctx, {
362
676
  subjectType: "skill",
363
677
  prepare: async (shared) => {
364
678
  const head = await args.head(shared);
365
- const built = await args.plan(head, shared);
679
+ const built = await args.plan(head, shared, { joined });
366
680
  if (built === null)
367
681
  return null;
368
682
  if (built instanceof Response)
369
683
  return built;
684
+ if (joined && supersedesPredecessor(built)) {
685
+ ownedCommitRequired = true;
686
+ return skillUpdateUnconfirmedFailure();
687
+ }
370
688
  // A write grant does not include changing a record's visibility;
371
689
  // visibility is set by the owner or an admin (grant-visibility.ts). The
372
690
  // plan is checked here and again on committed state once the close is
@@ -405,7 +723,7 @@ async function runSkillVersionWriteInner(args) {
405
723
  return revoked;
406
724
  }
407
725
  else {
408
- maybeThrowSkillWriteFault("successor", owner);
726
+ maybeThrowSkillWriteFault("successor", owner, writePlan.successor);
409
727
  const created = await args.hooks.createSuccessor(writePlan.successor, shared);
410
728
  if (created instanceof Response)
411
729
  return storageResult(created);
@@ -428,5 +746,44 @@ async function runSkillVersionWriteInner(args) {
428
746
  if (pointerDenial)
429
747
  return pointerDenial;
430
748
  return okResponse();
431
- });
749
+ }, joined);
750
+ if (ownedCommitRequired)
751
+ return OWNED_COMMIT_REQUIRED;
752
+ if (!outcome.ok || plan === null)
753
+ return outcome;
754
+ const writePlan = plan;
755
+ if (!supersedesPredecessor(writePlan))
756
+ return outcome;
757
+ const confirm = async () => {
758
+ // Test-only: inert unless armed. Pauses between the committed write and the
759
+ // confirmation read, so a later update of the same subject can complete.
760
+ // The pause stays outside the confirmation's lock acquisition.
761
+ const confirmPause = txnPausePoint("skill-update-confirm");
762
+ if (confirmPause)
763
+ await confirmPause;
764
+ const authorize = args.hooks.authorizeClose ?? (async () => skillUpdateUnconfirmedFailure());
765
+ // A deferred confirmation runs after the verb released its Memory locks; an
766
+ // inline one runs under the locks the caller still holds (flair#2950).
767
+ const held = args.deferConfirmation ? NO_HELD_IDS : new Set((args.heldMemoryIds ?? []).map(String));
768
+ // flair#2645: the owned transaction has committed, but its success is not
769
+ // proof that the queued close was applied. Confirm against the committed
770
+ // store before answering success.
771
+ return await confirmSkillUpdate({
772
+ ctx: args.ctx,
773
+ subjectId: args.subjectId,
774
+ predecessor: writePlan.predecessor,
775
+ closePatch: writePlan.closePatch,
776
+ successor: writePlan.successor,
777
+ grantedClose: writePlan.grantedClose,
778
+ authorize,
779
+ held,
780
+ appendedVersionId: outcome.version || null,
781
+ });
782
+ };
783
+ if (args.deferConfirmation)
784
+ return { ...outcome, confirm };
785
+ const confirmation = await confirm();
786
+ if (confirmation)
787
+ return { ok: false, response: confirmation };
788
+ return outcome;
432
789
  }
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * skill-write-fault.ts — the injection point for a per-step fault in the
3
3
  * transactional skill writer (flair#2139 S2): successor write, predecessor
4
- * close, pointer write, version append.
4
+ * close, pointer write, version append, instruction event.
5
5
  *
6
6
  * The hook is null unless setSkillWriteFaultHook installs one. Nothing under
7
7
  * resources/ or src/ calls it; the real-Harper suite installs it from
8
8
  * test/fixtures/skill-write-fault-2139/probe.js, which is not in the package.
9
+ * The optional third argument is the exact row about to be staged, so a test
10
+ * fixture can hand the writer a row its table's validator must refuse
11
+ * (flair#2997); the hook returns void and the writer does not read the row back.
9
12
  */
10
13
  let hook = null;
11
14
  export function setSkillWriteFaultHook(next) {
12
15
  hook = next;
13
16
  }
14
17
  /** Run the installed hook for `step`; a no-op when none is installed. */
15
- export function maybeThrowSkillWriteFault(step, agentId) {
16
- hook?.(step, agentId);
18
+ export function maybeThrowSkillWriteFault(step, agentId, record) {
19
+ hook?.(step, agentId, record);
17
20
  }
@@ -24,6 +24,7 @@
24
24
  * never from a body field or connector label. No Harper imports.
25
25
  */
26
26
  import { resolveAgentAuth } from "./agent-auth.js";
27
+ import { isDeliberateInternalVerdict } from "./internal-authority.js";
27
28
  import { FORBIDDEN, UNAUTH } from "./record-type-kit.js";
28
29
  /**
29
30
  * The credential class of a skill write, or null when the caller may not write.
@@ -33,7 +34,7 @@ import { FORBIDDEN, UNAUTH } from "./record-type-kit.js";
33
34
  export function skillWriteSource(context, auth) {
34
35
  const request = context?.request ?? context;
35
36
  // A deliberate internal call: no HTTP request at all and the marker set.
36
- if (auth.kind === "internal" && context?.__flairInternal === true && !request?.headers)
37
+ if (isDeliberateInternalVerdict(context, auth))
37
38
  return "internal";
38
39
  const header = request?.headers?.get?.("authorization") ?? request?.headers?.asObject?.authorization ?? "";
39
40
  // Role is not source: only verified Basic admin auth is the operator class.
@@ -1,15 +1,16 @@
1
1
  import { resolveAgentAuth } from "./agent-auth.js";
2
+ import { isDeliberateInternalVerdict } from "./internal-authority.js";
2
3
  import { FORBIDDEN, UNAUTH } from "./record-type-kit.js";
3
4
  import { buildProvenance } from "./provenance.js";
4
5
  import { databases } from "harper";
5
- import { refuseAdkSourcedSoulWrite } from "./soul-adk-guard.js";
6
+ import { SOUL_SCOPE_FIELDS_REFUSAL, suppliesSoulScopeFields } from "../src/lib/soul-scope-fields.js";
6
7
  // Role is not source: an admin agent key or delegated OAuth identity is still
7
8
  // a runtime credential. Only verified Basic admin auth enters the operator path.
8
9
  // Callers cannot choose this class via body fields or connector-supplied labels.
9
10
  export function soulWriteSource(context, auth) {
10
11
  const request = context?.request ?? context;
11
12
  // Internal path needs a deliberate __flairInternal marker; a contextless call is refused.
12
- if (auth.kind === "internal" && context?.__flairInternal === true && !request?.headers)
13
+ if (isDeliberateInternalVerdict(context, auth))
13
14
  return "internal";
14
15
  const header = request?.headers?.get?.("authorization") ?? request?.headers?.asObject?.authorization ?? "";
15
16
  if (auth.kind === "agent" && auth.isAdmin && /^Basic\s/i.test(header))
@@ -23,6 +24,15 @@ export async function authorizeSoulWrite(context) {
23
24
  : source ? null : FORBIDDEN("soul_write_requires_operator: use authenticated operator credentials");
24
25
  return { auth, source, denied };
25
26
  }
27
+ /**
28
+ * Whether this context's soul write would pass source authorization: the
29
+ * decision {@link authorizeSoulWrite} returns, so a surface that must decide
30
+ * BEFORE a write (the /mcp `tools/list` gate) asks the write's
31
+ * source-authorization question instead of restating the rule.
32
+ */
33
+ export async function soulWriteAllowed(context) {
34
+ return (await authorizeSoulWrite(context)).denied === null;
35
+ }
26
36
  export function soulProvenance(auth, source, now) {
27
37
  const provenance = JSON.parse(buildProvenance(auth, now, {}));
28
38
  provenance.verified.sourceClass = source;
@@ -53,11 +63,20 @@ export async function refuseLearnedSoulWrite(content) {
53
63
  }
54
64
  return null;
55
65
  }
56
- /** Content guards after source authorization: dated vendor-tag bridge, then the
57
- * generic learned-content backstop. New connectors need no Soul-side branch. */
66
+ /** Refuse a write that would store a non-empty `scopeTag` or a non-empty
67
+ * `tags` array: Soul has no dedicated or enforced per-user scope field (flair#1540). */
68
+ export function refuseSoulScopeFields(content) {
69
+ return suppliesSoulScopeFields(content) ? FORBIDDEN(SOUL_SCOPE_FIELDS_REFUSAL) : null;
70
+ }
71
+ /** Content guards after source authorization: the vendor-neutral scope-field
72
+ * refusal, then the generic learned-content backstop. New connectors need no
73
+ * Soul-side branch.
74
+ *
75
+ * `content` is the row this write would store: POST and PUT pass the request
76
+ * body, PATCH the merged row, so a stored row's scope fields decide a PATCH. */
58
77
  export async function refuseSoulWriteContent(content) {
59
- const adk = await refuseAdkSourcedSoulWrite(content);
60
- if (adk)
61
- return adk;
78
+ const scope = refuseSoulScopeFields(content);
79
+ if (scope)
80
+ return scope;
62
81
  return refuseLearnedSoulWrite(content);
63
82
  }
@@ -17,7 +17,7 @@ export async function patchRecord(table, id, patch, opts = {}) {
17
17
  if (!existing)
18
18
  throw new Error(`Record ${id} not found`);
19
19
  // The lastReflected stamp updates only the patch's fields.
20
- return { update: patch };
20
+ return { idempotent: true, update: patch };
21
21
  }, { ...opts, label: opts.label ?? "patchRecord" });
22
22
  }
23
23
  /**