@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -0,0 +1,53 @@
1
+ /**
2
+ * skill-subject.ts — the STABLE logical subject id of a skill lineage
3
+ * (flair#2139 S2). Pure: no Harper imports, so it is unit-testable and callable
4
+ * from every skill writer.
5
+ *
6
+ * Memory.skillSubjectId survives supersession and in-place writes.
7
+ *
8
+ * Derivation, in the one order the spec pins:
9
+ * 1. An EXPLICIT successor (`supersedes` set) inherits its predecessor's
10
+ * established subject, or — on first enrollment — adopts the predecessor's
11
+ * physical ID.
12
+ * 2. Otherwise the row's own stored `skillSubjectId` (carry-over) is used.
13
+ * 3. Otherwise first enrollment of an existing skill row uses that row's
14
+ * physical ID.
15
+ * 4. Otherwise a brand-new skill derives it from its FIRST physical Memory ID
16
+ * (the new row's own id).
17
+ *
18
+ * It is NEVER derived from a name, a content hash, client metadata, or a
19
+ * successor's fresh id when an established subject exists. A client- or
20
+ * body-supplied `skillSubjectId` is never read (see
21
+ * memory-declared-attributes.ts's SERVER_STAMPED_MEMORY_FIELDS, which strips it
22
+ * from every write body).
23
+ */
24
+ function nonEmptyString(value) {
25
+ return typeof value === "string" && value.length > 0 ? value : null;
26
+ }
27
+ /**
28
+ * The stable logical subject id for a skill write. Deterministic and total: as
29
+ * long as `newPhysicalId` is non-empty it returns a non-empty id.
30
+ */
31
+ export function deriveSkillSubjectId(input) {
32
+ const { newPhysicalId, storedHead, predecessor } = input;
33
+ const predecessorSubject = nonEmptyString(predecessor?.skillSubjectId);
34
+ if (predecessorSubject)
35
+ return predecessorSubject;
36
+ const predecessorId = nonEmptyString(predecessor?.id);
37
+ if (predecessorId)
38
+ return predecessorId;
39
+ const carried = nonEmptyString(storedHead?.skillSubjectId);
40
+ if (carried)
41
+ return carried;
42
+ const storedId = nonEmptyString(storedHead?.id);
43
+ if (storedId)
44
+ return storedId;
45
+ return newPhysicalId;
46
+ }
47
+ /** The subject id to stamp on a successor: the predecessor's established
48
+ * subject, else the predecessor's id, else its own (a fresh standalone row). */
49
+ export function carrySkillSubjectId(predecessor, fallbackId) {
50
+ return nonEmptyString(predecessor?.skillSubjectId)
51
+ ?? nonEmptyString(predecessor?.id)
52
+ ?? fallbackId;
53
+ }
@@ -0,0 +1,432 @@
1
+ import { normalizeEmptyEmbedding } from "./memory-embedding-value.js";
2
+ /** Skill writes share the ["flair-instruction-version", "skill"] lock. */
3
+ import { databases } from "harper";
4
+ import { storageResult } from "./memory-write-response.js";
5
+ import { randomUUID } from "node:crypto";
6
+ import { isDeepStrictEqual } from "node:util";
7
+ import { recordVersion, readHead, skillRefReadable, SKILL_SUBJECT_TYPE } from "./instruction-version-record.js";
8
+ import { SKILL_TAG, enforceSkillDurability, skillEmbedText, skillMetadataHasDuplicateKey } from "./skill-write.js";
9
+ import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
10
+ import { skillWriteSource } from "./skill-write-policy.js";
11
+ import { keepsSuppliedVector } from "./memory-supplied-vector.js";
12
+ import { FORBIDDEN } from "./record-type-kit.js";
13
+ import { PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
14
+ import { maybeThrowSkillWriteFault } from "./skill-write-fault.js";
15
+ import { supersedesTargetUnreadable } from "./memory-id-guard.js";
16
+ import { grantedCloseRevokedRefusal, writeGrantHeld } from "./write-back.js";
17
+ import { txnPausePoint } from "./txn-pause-point.js";
18
+ import { committedVisibilityDiffers, grantedSuccessorVisibilityDenial, predecessorVisibilityChangedRefusal } from "./grant-visibility.js";
19
+ /** Durability-keyed default visibility (mirrors Memory's write default). */
20
+ function defaultVisibilityForDurability(durability) {
21
+ return durability === "permanent" || durability === "persistent" ? "shared" : "private";
22
+ }
23
+ /**
24
+ * The effective visibility stamped on a skill version row (flair#2139 S2
25
+ * decision 3): the row's writable visibility, else the durability-keyed default.
26
+ * Never absent: a legacy row missing visibility is normalized at capture time
27
+ * rather than left to read as public.
28
+ */
29
+ export function skillVersionVisibility(row) {
30
+ const v = row?.visibility;
31
+ if (v === PRIVATE_VISIBILITY || v === SHARED_VISIBILITY)
32
+ return v;
33
+ return defaultVisibilityForDurability(row?.durability);
34
+ }
35
+ export async function closedSkillPayloadReadable(row, readerId, read = {}) {
36
+ if (!row || typeof row !== "object" || !rowIsSkill(row))
37
+ return true;
38
+ if (isOpenLiveRow(row))
39
+ return true;
40
+ if (!skillRefReadable({ agentId: row.agentId, visibility: row.visibility }, readerId))
41
+ return false;
42
+ const subjectId = typeof row.skillSubjectId === "string" && row.skillSubjectId.length > 0
43
+ ? row.skillSubjectId
44
+ : String(row.id);
45
+ const headOf = read.headOf ?? ((sid) => readHead(SKILL_SUBJECT_TYPE, sid));
46
+ let versionHead;
47
+ try {
48
+ versionHead = await headOf(subjectId);
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ if (!versionHead || versionHead.subjectType !== SKILL_SUBJECT_TYPE || versionHead.subjectId !== subjectId)
54
+ return false;
55
+ if (!skillRefReadable(versionHead, versionHead.agentId))
56
+ return false;
57
+ if (versionHead.kind === "delete") {
58
+ return versionHead.memoryId === null && skillRefReadable(versionHead, readerId);
59
+ }
60
+ if (versionHead.kind !== "create" && versionHead.kind !== "update")
61
+ return false;
62
+ if (typeof versionHead.memoryId !== "string" || versionHead.memoryId.length === 0)
63
+ return false;
64
+ const memoryGet = read.memoryGet ?? ((id) => databases.flair?.Memory?.get(id));
65
+ let live;
66
+ try {
67
+ live = await memoryGet(versionHead.memoryId);
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ if (!live || live.id !== versionHead.memoryId || live.skillSubjectId !== subjectId)
73
+ return false;
74
+ if (live.agentId !== versionHead.agentId || !rowIsSkill(live) || live.archived === true)
75
+ return false;
76
+ for (const end of [live.validTo, live.expiresAt]) {
77
+ if (end == null)
78
+ continue;
79
+ if (typeof end !== "string" || !(Date.parse(end) > Date.now()))
80
+ return false;
81
+ }
82
+ return skillRefReadable({ agentId: live.agentId, visibility: live.visibility }, readerId);
83
+ }
84
+ /**
85
+ * Build the successor Memory row for a superseded skill. Retains declared and explicitly allowed fields.
86
+ */
87
+ export function buildSkillSuccessorRow(args) {
88
+ const { auth, base, predecessorRow, successorId, subjectId, supersedes, now } = args;
89
+ const row = predecessorRow ? { ...predecessorRow, ...base } : { ...base };
90
+ if (!keepsSuppliedVector(auth)) {
91
+ for (const field of ["embedding", "embeddingModel"]) {
92
+ if (!Object.prototype.hasOwnProperty.call(base, field))
93
+ delete row[field];
94
+ }
95
+ }
96
+ row.id = successorId;
97
+ row.skillSubjectId = subjectId;
98
+ if (supersedes)
99
+ row.supersedes = supersedes;
100
+ else
101
+ delete row.supersedes;
102
+ row.updatedAt = now;
103
+ row.archived = false;
104
+ delete row.validTo;
105
+ delete row.archivedAt;
106
+ delete row.archivedBy;
107
+ if (!predecessorRow)
108
+ row.createdAt = typeof base.createdAt === "string" ? base.createdAt : now;
109
+ row.instanceToken = randomUUID();
110
+ enforceSkillDurability(row);
111
+ stripUndeclaredMemoryAttributes(row);
112
+ return row;
113
+ }
114
+ function okResponse() {
115
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "Content-Type": "application/json" } });
116
+ }
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
+ /** Is this row a skill-tagged Memory row? */
129
+ export function rowIsSkill(row) {
130
+ return !!row && Array.isArray(row.tags) && row.tags.includes(SKILL_TAG);
131
+ }
132
+ export function skillPayloadUnchanged(base, head) {
133
+ const bookkeeping = new Set([
134
+ "embedding", "embeddingModel", "embeddedContentHash", "contentHash", "updatedAt", "instanceToken",
135
+ "provenance", "skillSubjectId", "_safetyFlags", "_skillScan",
136
+ "retrievalCount", "lastRetrieved",
137
+ ]);
138
+ return Object.entries(base).every(([key, value]) => bookkeeping.has(key) || isDeepStrictEqual(value, head[key]));
139
+ }
140
+ export function skillWriteConflict(error) {
141
+ return Response.json({ error }, { status: 409 });
142
+ }
143
+ export async function prepareSkillBody(content, stored, auth) {
144
+ let predecessor = null;
145
+ if (typeof content.supersedes === "string" && content.supersedes.length > 0) {
146
+ // flair#2307: a failed read of the `supersedes` target refuses the write
147
+ // with a named error; it is never read as "no predecessor".
148
+ try {
149
+ predecessor = await databases.flair.Memory.get(content.supersedes);
150
+ }
151
+ catch (err) {
152
+ return supersedesTargetUnreadable(err);
153
+ }
154
+ }
155
+ if (!rowIsSkill(content) && !rowIsSkill(stored) && !rowIsSkill(predecessor)) {
156
+ return { content, predecessor };
157
+ }
158
+ if (content.supersedes && content.supersedes === content.id)
159
+ return skillWriteConflict("skill_self_supersede");
160
+ if (content.supersedes && !predecessor && content.supersedes !== stored?.supersedes) {
161
+ return skillWriteConflict("skill_predecessor_missing");
162
+ }
163
+ if (content.tags !== undefined && (!Array.isArray(content.tags) || !content.tags.includes(SKILL_TAG))) {
164
+ return Response.json({ error: "skill_lineage_tag_removed" }, { status: 400 });
165
+ }
166
+ if ((content.archived != null && content.archived !== false) || (content.validTo != null && content.validTo !== "")) {
167
+ return Response.json({ error: "skill_state_requires_delete" }, { status: 400 });
168
+ }
169
+ const source = stored ?? predecessor ?? {};
170
+ const effective = { ...source, ...content };
171
+ effective.tags = content.tags ?? (rowIsSkill(stored) ? stored.tags : predecessor?.tags);
172
+ if (skillMetadataHasDuplicateKey(effective.metadata)) {
173
+ return Response.json({ error: "skill_metadata_duplicate_key" }, { status: 400 });
174
+ }
175
+ const textUnchanged = skillEmbedText(effective) === skillEmbedText(source);
176
+ if (content.embedding === undefined && !textUnchanged) {
177
+ effective.embedding = null;
178
+ effective.embeddingModel = null;
179
+ }
180
+ // flair#2465: the successor keeps the stored `embeddedContentHash` only when
181
+ // the stored row has a vector, the body omits `embedding` (so that vector is
182
+ // carried), and the embedding text is unchanged; otherwise null. A body value
183
+ // is never kept. A Feed successor stores this value; Memory.post()/put() keep
184
+ // it when they store the carried vector, and otherwise set their own.
185
+ const sourceHasVector = Array.isArray(source.embedding) && source.embedding.length > 0;
186
+ // Non-admin writes keep a carried vector's stored stamp. Administrator and
187
+ // trusted in-process writes may replace it and may supply their own vector.
188
+ if (!keepsSuppliedVector(auth) && content.embedding === undefined && sourceHasVector && textUnchanged) {
189
+ if (source.embeddingModel === undefined)
190
+ delete effective.embeddingModel;
191
+ else
192
+ effective.embeddingModel = source.embeddingModel;
193
+ }
194
+ effective.embeddedContentHash = sourceHasVector && content.embedding === undefined && textUnchanged
195
+ ? (source.embeddedContentHash ?? null)
196
+ : null;
197
+ if (content.id === undefined)
198
+ delete effective.id;
199
+ return { content: effective, predecessor };
200
+ }
201
+ /** Select exactly one open row; ambiguity refuses. */
202
+ export async function resolveSkillHead(subjectId, addressedId, shared) {
203
+ const table = databases.flair?.Memory;
204
+ if (!table || typeof table.search !== "function")
205
+ throw new Error("flair: the Memory table is unavailable");
206
+ const live = new Map();
207
+ if (subjectId) {
208
+ for await (const row of table.search({
209
+ conditions: [{ attribute: "skillSubjectId", comparator: "equals", value: subjectId }],
210
+ }, shared)) {
211
+ if (isOpenLiveRow(row))
212
+ live.set(String(row.id), row);
213
+ }
214
+ }
215
+ if (addressedId) {
216
+ const row = await table.get(addressedId, shared);
217
+ if (isOpenLiveRow(row) && (!row.skillSubjectId || row.skillSubjectId === subjectId))
218
+ live.set(String(row.id), row);
219
+ }
220
+ if (live.size > 1)
221
+ throw new Error("skill_head_ambiguous");
222
+ return live.values().next().value ?? null;
223
+ }
224
+ export async function authorizeSkillOwners(ctx, auth, rows, shared) {
225
+ for (const row of rows.filter(Boolean)) {
226
+ if (typeof row.agentId !== "string" || !row.agentId.trim())
227
+ return FORBIDDEN("skill_owner_missing");
228
+ if (skillWriteSource(ctx, auth) !== "agent" || auth.kind !== "agent" || row.agentId === auth.agentId)
229
+ continue;
230
+ let granted = false;
231
+ for await (const grant of databases.flair.MemoryGrant.search({ conditions: [
232
+ { attribute: "granteeId", comparator: "equals", value: auth.agentId },
233
+ { attribute: "ownerId", comparator: "equals", value: row.agentId },
234
+ ] }, shared)) {
235
+ if (grant.scope === "write")
236
+ granted = true;
237
+ }
238
+ if (!granted)
239
+ return FORBIDDEN("forbidden: cannot write a skill owned by another agent without a write grant");
240
+ }
241
+ return null;
242
+ }
243
+ /**
244
+ * flair#2511: the "write" grant a cross-agent close of `closed` stands on, or
245
+ * null when the close is not a grant-authorized cross-agent one — an operator,
246
+ * internal or same-agent caller. The same predicate {@link authorizeSkillOwners}
247
+ * uses to demand the grant; the shared writer re-checks it on committed state
248
+ * after the close is staged. Every plan that closes a row passes this for the
249
+ * row it closes.
250
+ */
251
+ export function grantedSkillClose(closed, ctx, auth) {
252
+ if (!closed || typeof closed.agentId !== "string" || !closed.agentId.trim())
253
+ return null;
254
+ if (skillWriteSource(ctx, auth) !== "agent" || auth.kind !== "agent")
255
+ return null;
256
+ if (closed.agentId === auth.agentId)
257
+ return null;
258
+ return { granteeId: auth.agentId, ownerId: closed.agentId };
259
+ }
260
+ export async function validateSkillSnapshots(stored, predecessor, targetId, shared) {
261
+ for (const [id, expected] of [[targetId, stored], [predecessor?.id, predecessor]]) {
262
+ if (!id)
263
+ continue;
264
+ const current = await databases.flair.Memory.get(id, shared);
265
+ if (!isDeepStrictEqual(current ?? null, expected ?? null))
266
+ return skillWriteConflict("skill_target_changed");
267
+ }
268
+ return null;
269
+ }
270
+ /**
271
+ * The default Memory-table hooks: the successor is upserted and the predecessor
272
+ * is read-modify-written (full-record PUT, its stored fields preserved), both
273
+ * through the shared transaction so the helper's rollback covers them.
274
+ */
275
+ export const defaultSkillHooks = {
276
+ createSuccessor: async (successor, shared) => {
277
+ normalizeEmptyEmbedding(successor);
278
+ const result = storageResult(await databases.flair.Memory.put(successor, shared));
279
+ if (result instanceof Response)
280
+ return result;
281
+ return String(successor.id);
282
+ },
283
+ closePredecessor: async (predecessor, patch, shared) => {
284
+ const closed = { ...predecessor, ...patch };
285
+ normalizeEmptyEmbedding(closed);
286
+ const result = storageResult(await databases.flair.Memory.put(closed, shared));
287
+ if (result instanceof Response)
288
+ return result;
289
+ },
290
+ };
291
+ /**
292
+ * flair#2511: run once a close's write is staged — a supersede's predecessor
293
+ * close or a delete's head close. A grant-authorized cross-agent close stands on
294
+ * the grant read at authorization time; re-read it on committed state HERE,
295
+ * 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.
300
+ *
301
+ * For a grant-authorized supersede, `successor` is the planned successor row.
302
+ * Before the grant re-check, the predecessor's COMMITTED row (an empty-context
303
+ * read, as for the grant) must read with the successor's visibility: a write
304
+ * 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
307
+ * after this re-read and before the transaction commits is not seen by it.
308
+ */
309
+ async function afterCloseStaged(granted, supersede) {
310
+ // Test-only: inert unless armed — here the close write is staged, so a
311
+ // competing grant revocation or row change and the committed-state re-checks
312
+ // below can be exercised in either order (the skill-path counterpart of Memory's "granted-close-staged").
313
+ const stagedPause = txnPausePoint("skill-close-staged");
314
+ if (stagedPause)
315
+ await stagedPause;
316
+ if (!granted)
317
+ return null;
318
+ if (supersede) {
319
+ const committed = await databases.flair.Memory.get(supersede.predecessorId, {});
320
+ if (committedVisibilityDiffers(committed, supersede.successor.visibility))
321
+ return predecessorVisibilityChangedRefusal();
322
+ }
323
+ const held = await writeGrantHeld(databases.flair.MemoryGrant, granted.granteeId, granted.ownerId, {});
324
+ return held ? null : grantedCloseRevokedRefusal();
325
+ }
326
+ /**
327
+ * 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
329
+ * successor/close/pointer writes inside that same transaction.
330
+ */
331
+ export async function runSkillVersionWrite(args) {
332
+ // A raw table `create` inside the write (the InstructionVersion append, or
333
+ // the successor upsert) can set Harper's `createdResource` flag on the
334
+ // request context, which would surface as HTTP 201. The path a skill write
335
+ // replaces returned 200, so restore the flag's prior value on the way out.
336
+ const restoreCreated = captureCreatedFlag(args.ctx);
337
+ try {
338
+ return await runSkillVersionWriteInner(args);
339
+ }
340
+ finally {
341
+ restoreCreated();
342
+ }
343
+ }
344
+ /** Capture the `createdResource` flag on a context and its request, and return a
345
+ * restore callback that puts them back exactly as they were. */
346
+ export function captureCreatedFlag(ctx) {
347
+ const targets = [ctx, ctx?.request].filter((t) => !!t && typeof t === "object");
348
+ const before = targets.map((t) => [t, Object.prototype.hasOwnProperty.call(t, "createdResource"), t.createdResource]);
349
+ return () => {
350
+ for (const [t, had, value] of before) {
351
+ if (had)
352
+ t.createdResource = value;
353
+ else
354
+ delete t.createdResource;
355
+ }
356
+ };
357
+ }
358
+ async function runSkillVersionWriteInner(args) {
359
+ let plan = null;
360
+ let owner = "";
361
+ return recordVersion(args.ctx, {
362
+ subjectType: "skill",
363
+ prepare: async (shared) => {
364
+ const head = await args.head(shared);
365
+ const built = await args.plan(head, shared);
366
+ if (built === null)
367
+ return null;
368
+ if (built instanceof Response)
369
+ return built;
370
+ // A write grant does not include changing a record's visibility;
371
+ // visibility is set by the owner or an admin (grant-visibility.ts). The
372
+ // plan is checked here and again on committed state once the close is
373
+ // staged (afterCloseStaged).
374
+ const visibilityDenial = grantedSuccessorVisibilityDenial(built);
375
+ if (visibilityDenial)
376
+ return visibilityDenial;
377
+ plan = built;
378
+ const target = built.kind === "delete" ? built.predecessor : built.successor;
379
+ owner = String(target.agentId);
380
+ return {
381
+ subjectType: "skill",
382
+ subjectId: args.subjectId,
383
+ agentId: String(target.agentId),
384
+ key: null,
385
+ kind: built.kind,
386
+ rowId: String(target.id),
387
+ value: built.kind === "delete" ? null : built.value,
388
+ memoryId: built.kind === "delete" ? null : String(built.successor.id),
389
+ visibility: built.visibility,
390
+ expectedVersion: args.expectedVersion ?? null,
391
+ };
392
+ },
393
+ }, async (shared) => {
394
+ if (plan === null)
395
+ return okResponse();
396
+ const writePlan = plan;
397
+ if (writePlan.kind === "delete") {
398
+ maybeThrowSkillWriteFault("close", owner);
399
+ const closed = await args.hooks.closePredecessor(writePlan.predecessor, writePlan.closePatch, shared);
400
+ if (closed instanceof Response)
401
+ return storageResult(closed);
402
+ // flair#2511: the grant re-check, after the close is staged.
403
+ const revoked = await afterCloseStaged(writePlan.grantedClose);
404
+ if (revoked)
405
+ return revoked;
406
+ }
407
+ else {
408
+ maybeThrowSkillWriteFault("successor", owner);
409
+ const created = await args.hooks.createSuccessor(writePlan.successor, shared);
410
+ if (created instanceof Response)
411
+ return storageResult(created);
412
+ if (writePlan.predecessor) {
413
+ maybeThrowSkillWriteFault("close", owner);
414
+ const closed = await args.hooks.closePredecessor(writePlan.predecessor, writePlan.closePatch, shared);
415
+ if (closed instanceof Response)
416
+ return storageResult(closed);
417
+ // flair#2511: the grant re-check, after the close is staged, with the
418
+ // committed-visibility check for a grant-authorized successor.
419
+ const revoked = await afterCloseStaged(writePlan.grantedClose, {
420
+ predecessorId: String(writePlan.predecessor.id), successor: writePlan.successor,
421
+ });
422
+ if (revoked)
423
+ return revoked;
424
+ }
425
+ }
426
+ maybeThrowSkillWriteFault("pointer", owner);
427
+ const pointerDenial = await args.hooks.pointer?.(shared);
428
+ if (pointerDenial)
429
+ return pointerDenial;
430
+ return okResponse();
431
+ });
432
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * skill-write-fault.ts — the injection point for a per-step fault in the
3
+ * transactional skill writer (flair#2139 S2): successor write, predecessor
4
+ * close, pointer write, version append.
5
+ *
6
+ * The hook is null unless setSkillWriteFaultHook installs one. Nothing under
7
+ * resources/ or src/ calls it; the real-Harper suite installs it from
8
+ * test/fixtures/skill-write-fault-2139/probe.js, which is not in the package.
9
+ */
10
+ let hook = null;
11
+ export function setSkillWriteFaultHook(next) {
12
+ hook = next;
13
+ }
14
+ /** Run the installed hook for `step`; a no-op when none is installed. */
15
+ export function maybeThrowSkillWriteFault(step, agentId) {
16
+ hook?.(step, agentId);
17
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * skill-write-policy.ts — the shared skill-write CREDENTIAL classification
3
+ * (flair#2139 S2, implementing the flair#1741 fix).
4
+ *
5
+ * A skill is a Memory tagged "skill". Writes are the create/update/delete of
6
+ * that row and the FeedMemories ingest. Before this module, an admin agent key
7
+ * (a TPS-Ed25519 signature whose principal is in the admin set) was treated as
8
+ * an OPERATOR by record-type-kit.ts's stampAttribution and by Memory's
9
+ * supersede/delete guards — it could rewrite or delete ANY agent's skill
10
+ * (#1741). The adopted rule (soul-write-policy.ts's precedent) is: **role is
11
+ * not source**. An admin agent key or a delegated OAuth identity is still a
12
+ * RUNTIME credential. Only a verified Basic administrator enters the operator
13
+ * path, and only a deliberate internal call enters the internal path.
14
+ *
15
+ * Classification:
16
+ * - operator: an authenticated Basic administrator.
17
+ * - agent: any other verified runtime identity — Ed25519 or OAuth —
18
+ * whether or not `isAdmin` is set. It retains own-skill writes
19
+ * and the explicit write-grant supersede allowance.
20
+ * - internal: a deliberate in-process call (`__flairInternal`, no request).
21
+ * - null: anything else (anonymous — the caller is refused).
22
+ *
23
+ * The class is read from the raw Authorization header and the auth verdict,
24
+ * never from a body field or connector label. No Harper imports.
25
+ */
26
+ import { resolveAgentAuth } from "./agent-auth.js";
27
+ import { FORBIDDEN, UNAUTH } from "./record-type-kit.js";
28
+ /**
29
+ * The credential class of a skill write, or null when the caller may not write.
30
+ * `context` is the resource context (getContext()), carrying `request` (or the
31
+ * request itself) and — for the internal path — the deliberate marker.
32
+ */
33
+ export function skillWriteSource(context, auth) {
34
+ const request = context?.request ?? context;
35
+ // A deliberate internal call: no HTTP request at all and the marker set.
36
+ if (auth.kind === "internal" && context?.__flairInternal === true && !request?.headers)
37
+ return "internal";
38
+ const header = request?.headers?.get?.("authorization") ?? request?.headers?.asObject?.authorization ?? "";
39
+ // Role is not source: only verified Basic admin auth is the operator class.
40
+ if (auth.kind === "agent" && auth.isAdmin && /^Basic\s/i.test(header))
41
+ return "operator";
42
+ // Every other verified runtime identity is an agent, admin-or-not.
43
+ if (auth.kind === "agent")
44
+ return "agent";
45
+ return null;
46
+ }
47
+ /** Resolve the auth verdict and the credential class together. */
48
+ export async function classifySkillWrite(context) {
49
+ const auth = await resolveAgentAuth(context);
50
+ return { auth, source: skillWriteSource(context, auth) };
51
+ }
52
+ /**
53
+ * Authorize a skill version write. Returns the resolved verdict, the source
54
+ * class, and a denial Response when the caller may not write at all (anonymous
55
+ * → 401; an unrecognized principal → 403). This is the skill analog of
56
+ * soul-write-policy.ts's authorizeSoulWrite, used by the InstructionVersion
57
+ * append helper's subject-type dispatch.
58
+ */
59
+ export async function authorizeSkillVersionWrite(context) {
60
+ const { auth, source } = await classifySkillWrite(context);
61
+ const denied = auth.kind === "anonymous"
62
+ ? UNAUTH()
63
+ : source
64
+ ? null
65
+ : FORBIDDEN("skill_write_requires_verified_identity");
66
+ return { auth, source, denied };
67
+ }
@@ -40,16 +40,76 @@ export const SKILL_TAG = "skill";
40
40
  export function isSkillWrite(content) {
41
41
  return Array.isArray(content?.tags) && content.tags.includes(SKILL_TAG);
42
42
  }
43
+ /** Scan decoded top-level keys of a valid JSON object. */
44
+ export function skillMetadataHasDuplicateKey(metadata) {
45
+ if (typeof metadata !== "string")
46
+ return false;
47
+ try {
48
+ const parsed = JSON.parse(metadata);
49
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
50
+ return false;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ const keys = new Set();
56
+ let depth = 0;
57
+ let keyExpected = false;
58
+ for (let i = 0; i < metadata.length; i++) {
59
+ const char = metadata[i];
60
+ if (char === '"') {
61
+ const start = i;
62
+ while (++i < metadata.length) {
63
+ if (metadata[i] === "\\")
64
+ i++;
65
+ else if (metadata[i] === '"')
66
+ break;
67
+ }
68
+ if (depth === 1 && keyExpected) {
69
+ const key = JSON.parse(metadata.slice(start, i + 1));
70
+ if (keys.has(key))
71
+ return true;
72
+ keys.add(key);
73
+ keyExpected = false;
74
+ }
75
+ }
76
+ else if (char === "{" || char === "[") {
77
+ depth++;
78
+ if (depth === 1)
79
+ keyExpected = true;
80
+ }
81
+ else if (char === "}" || char === "]") {
82
+ depth--;
83
+ }
84
+ else if (char === "," && depth === 1) {
85
+ keyExpected = true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ /**
91
+ * Every field a Memory embedding can be computed from, across row kinds:
92
+ * `trigger` for a skill-tagged row whose trigger is a non-empty string, and
93
+ * `content` for every other row — including a skill-tagged row whose trigger is
94
+ * empty or absent (see embedTextField). A check that sees only a write body and
95
+ * not the row kind (resources/memory-redaction.ts) uses this whole set; a check
96
+ * that has the row uses embedTextField(row), the one field THAT row embeds from.
97
+ */
98
+ export const MEMORY_EMBEDDING_INPUT_FIELDS = Object.freeze(["content", "trigger"]);
43
99
  /**
44
- * The text a row embeds from. Skill-tagged rows embed from `trigger` (the
45
- * recall signal); every other row embeds from `content`. Returns `undefined`
46
- * only when there is no usable text at all.
100
+ * The field a row embeds from. A skill-tagged row with a non-empty string
101
+ * `trigger` embeds from `trigger` (the recall signal); every other row embeds
102
+ * from `content` — a non-skill row whatever its `trigger`, and a skill-tagged
103
+ * row whose trigger is empty or absent.
104
+ */
105
+ export function embedTextField(row) {
106
+ return isSkillWrite(row) && typeof row.trigger === "string" && row.trigger.length > 0 ? "trigger" : "content";
107
+ }
108
+ /**
109
+ * The value of embedTextField(row).
47
110
  */
48
111
  export function skillEmbedText(content) {
49
- if (isSkillWrite(content) && typeof content.trigger === "string" && content.trigger.length > 0) {
50
- return content.trigger;
51
- }
52
- return content.content;
112
+ return content[embedTextField(content)];
53
113
  }
54
114
  /**
55
115
  * Force a skill-tagged write to durability=persistent. Rejects an explicit