@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,427 @@
1
+ /**
2
+ * agent-home.ts — the CLI-side half of the Agent "home instance" rule
3
+ * (flair#2433).
4
+ *
5
+ * An Agent row's home is `originatorInstanceId`: the federation id of the
6
+ * instance that CREATED it. The Agent resource stamps it on every create
7
+ * (resources/Agent.ts via resources/originator-instance.ts, reading
8
+ * resources/instance-identity.ts's localInstanceId()). The Agent rows the CLI
9
+ * creates go through Harper's operations API, which bypasses the resource.
10
+ *
11
+ * The rule is the SAME one the server applies, not a second copy of it: this
12
+ * module resolves the target instance's own id through the shared decision
13
+ * (src/lib/instance-identity-row.ts's decideInstanceAnswer — exactly one
14
+ * Instance row is the identity), and stamps that. It never invents an id: no
15
+ * row, several rows, or a failed read resolves to null, the defined
16
+ * local-origin state the schema documents.
17
+ *
18
+ * Nothing here decides "which row SHOULD win" — a create stamps the local id
19
+ * and ignores any value the record already carries.
20
+ */
21
+ import { decideInstanceAnswer, readableInstanceRows, readInstanceRows, } from "./instance-identity-row.js";
22
+ import { isValidAgentId } from "./agent-id-rule.js";
23
+ import { AGENT_HOME_STAMP_FIELD, isHomeLessAgentRow, isSyncOriginatedAgentRow, } from "./agent-home-fields.js";
24
+ /** The operator command that back-fills the home on home-less rows that carry no federation-sync provenance. */
25
+ export const AGENT_HOME_STAMP_COMMAND = "flair agent stamp-home";
26
+ /** The remedy line doctor prints: the dry run is the bare command; only --apply writes. */
27
+ export const AGENT_HOME_STAMP_REMEDY = `${AGENT_HOME_STAMP_COMMAND} (dry run; add --apply to stamp)`;
28
+ /**
29
+ * The request-body control field the remedy sends to the Agent resource
30
+ * (flair#2472): a guarded home stamp. The resource reads it, applies the stamp
31
+ * inside a FRESH OWNED transaction (the request's own transaction is detached for
32
+ * that scope), and drops it before the write — it is a control field, not a
33
+ * stored column. Re-exported so callers of this module keep
34
+ * one import site; the implementations live in agent-home-fields.ts (the
35
+ * dependency-free module the Agent resource imports directly).
36
+ */
37
+ export { AGENT_HOME_FIELD, AGENT_HOME_STAMP_FIELD, AGENT_HOME_STAMP_PAUSE_POINT, AGENT_PRINCIPAL_WRITE_BACK_FIELD, AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR, AGENT_PRINCIPAL_WRITE_BACK_PAUSE_POINT, isForeignAgentHome, isHomeLessAgentRow, isSyncOriginatedAgentRow, pickPrincipalWriteBackFields, } from "./agent-home-fields.js";
38
+ /** The ops endpoint of an instance the CLI is about to write to. */
39
+ export function agentHomeEndpoint(opsPortOrUrl, adminUser, adminPass, fetchImpl) {
40
+ const opsUrl = typeof opsPortOrUrl === "number" ? `http://127.0.0.1:${opsPortOrUrl}` : opsPortOrUrl;
41
+ return {
42
+ opsUrl,
43
+ // A caller without a pass sends no Authorization header — same posture as
44
+ // the other ops-API seed helpers (loopback authorizeLocal).
45
+ ...(adminPass !== undefined ? { credentials: { user: adminUser, pass: adminPass } } : {}),
46
+ ...(fetchImpl ? { fetchImpl } : {}),
47
+ };
48
+ }
49
+ /**
50
+ * The TARGET instance's own federation id — the value a create stamps as the new
51
+ * Agent row's home. The ONE canonical Instance row, or null when there is not
52
+ * exactly one (no row yet, several rows, or a read that did not happen). A null
53
+ * is never a guess: it is the local-origin state, and it is what the server-side
54
+ * localInstanceId() returns in the same situations.
55
+ */
56
+ export async function resolveTargetInstanceId(endpoint) {
57
+ const identity = await resolveTargetInstanceIdentity(endpoint);
58
+ return identity.kind === "one" ? identity.id : null;
59
+ }
60
+ /** The decision behind `resolveTargetInstanceId`, with the reason a null id is null. */
61
+ export async function resolveTargetInstanceIdentity(endpoint) {
62
+ let rows;
63
+ try {
64
+ rows = await readInstanceRows(endpoint);
65
+ }
66
+ catch (err) {
67
+ // A read that FAILED is not a read that found no row. Stamp nothing (the
68
+ // local-origin state) rather than inventing an id; the row still gets a home
69
+ // on a later re-run once the table is readable.
70
+ console.error("Agent home: the target instance's Instance row could not be read, so the new row's home is left empty", {
71
+ opsUrl: endpoint.opsUrl,
72
+ err,
73
+ });
74
+ return { kind: "unreadable" };
75
+ }
76
+ const decision = decideInstanceAnswer(rows);
77
+ if (decision.kind === "answer")
78
+ return { kind: "one", id: decision.row.id };
79
+ if (decision.kind === "refuse-multiple")
80
+ return { kind: "multiple", count: decision.rows.length };
81
+ return { kind: "none" };
82
+ }
83
+ /**
84
+ * Every `flair.Instance` row an HTTP endpoint reports, read through its REST
85
+ * `/Instance/` resource with admin Basic auth. Throws on a non-2xx, a body that
86
+ * is not a row list, or an entry without a usable id — a read that established
87
+ * nothing, never a read of zero rows (the same rule `readInstanceRows` follows
88
+ * on the ops side). Uses the ONE reader (`readableInstanceRows`).
89
+ */
90
+ export async function readInstanceRowsViaHttp(httpBase, adminUser, adminPass, fetchImpl) {
91
+ const fetchFn = fetchImpl ?? fetch;
92
+ const res = await fetchFn(`${httpBase.replace(/\/+$/, "")}/Instance/`, {
93
+ headers: { Authorization: `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}` },
94
+ signal: AbortSignal.timeout(5000),
95
+ });
96
+ if (!res.ok)
97
+ throw new Error(`GET /Instance/ answered HTTP ${res.status}`);
98
+ const data = await res.json();
99
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
100
+ if (rows === null)
101
+ throw new Error("GET /Instance/ answered a body that is not a row list");
102
+ return readableInstanceRows(rows);
103
+ }
104
+ /**
105
+ * The instance identity an HTTP endpoint reports (flair#2483), decided by the
106
+ * SAME rule as the ops-API read: exactly one nameable `flair.Instance` row is an
107
+ * identity; no row, several rows, or a read that did not happen is not.
108
+ */
109
+ export async function readHttpInstanceIdentity(httpBase, adminUser, adminPass, fetchImpl) {
110
+ let rows;
111
+ try {
112
+ rows = await readInstanceRowsViaHttp(httpBase, adminUser, adminPass, fetchImpl);
113
+ }
114
+ catch {
115
+ return { kind: "unreadable" };
116
+ }
117
+ const decision = decideInstanceAnswer(rows);
118
+ if (decision.kind === "answer")
119
+ return { kind: "one", id: decision.row.id };
120
+ if (decision.kind === "refuse-multiple")
121
+ return { kind: "multiple", count: decision.rows.length };
122
+ return { kind: "none" };
123
+ }
124
+ /** A one-line description of a single endpoint's identity state, for a refusal reason. */
125
+ function describeIdentityState(id) {
126
+ switch (id.kind) {
127
+ case "one": return "one instance identity";
128
+ case "none": return "no instance identity";
129
+ case "multiple": return `${id.count} instance identity rows`;
130
+ case "unreadable": return "an instance identity it could not read";
131
+ }
132
+ }
133
+ /**
134
+ * The instance-identity comparison doctor adds to its configuration check
135
+ * before the roster and home reads (flair#2483): the identity the probed HTTP
136
+ * port reports against the identity the candidate ops endpoint reports. Only
137
+ * two SINGLE, EQUAL ids are `same`. Two different single ids are `different`.
138
+ * Anything else — no row (a fresh install), several rows, or an unreadable read
139
+ * on either side — is `unestablished`. The caller refuses only on `different`;
140
+ * the configuration check (src/lib/local-instance-pair.ts) decides the rest.
141
+ */
142
+ export function decideProbedPairIdentity(http, ops) {
143
+ if (http.kind === "one" && ops.kind === "one") {
144
+ return http.id === ops.id
145
+ ? { kind: "same", id: http.id }
146
+ : { kind: "different", httpId: http.id, opsId: ops.id };
147
+ }
148
+ return {
149
+ kind: "unestablished",
150
+ detail: `the probed HTTP port reports ${describeIdentityState(http)}, the ops endpoint reports ${describeIdentityState(ops)}`,
151
+ };
152
+ }
153
+ /**
154
+ * Stamp an Agent create record with the creating instance's id, ignoring any
155
+ * value the record already carries. `home` of null writes an explicit null (the
156
+ * local-origin state), never a stale body value.
157
+ */
158
+ export function stampAgentHome(record, home) {
159
+ record.originatorInstanceId = home;
160
+ }
161
+ /**
162
+ * Read every Agent row's home decision fields through the ops API. The read asks
163
+ * for the full row (`get_attributes: ["*"]`) rather than a projection: the
164
+ * receiver bookkeeping columns (`_syncedFrom`, `_originatorInstanceId`) are not
165
+ * in the Agent schema, so a `SELECT` of them is not a safe read, but a full row
166
+ * returns them where the federation merge wrote them. Returns null on a read
167
+ * that failed or whose body was not a row list — a failed read is never "no
168
+ * rows".
169
+ */
170
+ export async function readAgentHomeRows(args) {
171
+ const fetchImpl = args.fetchImpl ?? fetch;
172
+ try {
173
+ const res = await fetchImpl(args.opsUrl, {
174
+ method: "POST",
175
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
176
+ body: JSON.stringify({
177
+ operation: "search_by_value",
178
+ database: "flair",
179
+ table: "Agent",
180
+ search_attribute: "id",
181
+ search_value: "*",
182
+ get_attributes: ["*"],
183
+ }),
184
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
185
+ });
186
+ if (!res.ok)
187
+ return null;
188
+ const data = await res.json();
189
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
190
+ return rows;
191
+ }
192
+ catch {
193
+ return null;
194
+ }
195
+ }
196
+ /** A row's id as a string, or null when it carries no usable id. */
197
+ export function agentRowId(row) {
198
+ return typeof row?.id === "string" && row.id.length > 0 ? row.id : null;
199
+ }
200
+ /**
201
+ * Split the Agent roster into home-less rows and, of those, the ones the remedy
202
+ * may stamp: a home-less row with no sync provenance. A row carrying sync
203
+ * provenance arrived through federation and is listed only.
204
+ *
205
+ * PURE. `localInstanceId` is not used to decide the split — a null id only means
206
+ * the remedy has nothing to write.
207
+ */
208
+ export function planAgentHomeStamps(rows, _localInstanceId) {
209
+ const homeLessRows = (Array.isArray(rows) ? rows : []).filter((row) => row != null && typeof row === "object" && isHomeLessAgentRow(row));
210
+ const homeLess = homeLessRows.map(agentRowId).filter((id) => id !== null).sort();
211
+ const sync = homeLessRows
212
+ .filter((row) => isSyncOriginatedAgentRow(row))
213
+ .map(agentRowId)
214
+ .filter((id) => id !== null)
215
+ .sort();
216
+ const syncSet = new Set(sync);
217
+ return { homeLess, stampable: homeLess.filter((id) => !syncSet.has(id)), sync };
218
+ }
219
+ /** The named error for an ops-API write that would change a stored home. */
220
+ export const AGENT_HOME_IMMUTABLE_ERROR = "originator_instance_immutable";
221
+ /**
222
+ * The refusal for a write that would CHANGE an Agent row's stored home
223
+ * (flair#2433). The home is immutable after create: a later write may omit it
224
+ * (the stored value stands) or restate it, but may never replace it.
225
+ */
226
+ export function agentHomeChangeRefusal(id, stored, next) {
227
+ return (`${AGENT_HOME_IMMUTABLE_ERROR}: agent '${id}' already has a home instance (${stored}); ` +
228
+ `refusing to change it to ${next === null ? "(none)" : next}. ` +
229
+ "The home is immutable after create.");
230
+ }
231
+ /**
232
+ * Read one Agent row's stored home (`originatorInstanceId`) through the ops API.
233
+ * An unreadable read is its OWN state, never "absent": a write that would decide
234
+ * on it must refuse rather than treat a failed read as a row with no home.
235
+ */
236
+ export async function readStoredAgentHome(args) {
237
+ const fetchImpl = args.fetchImpl ?? fetch;
238
+ let res;
239
+ try {
240
+ res = await fetchImpl(args.opsUrl, {
241
+ method: "POST",
242
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
243
+ body: JSON.stringify({
244
+ operation: "search_by_id",
245
+ database: "flair",
246
+ table: "Agent",
247
+ ids: [args.id],
248
+ get_attributes: ["id", "originatorInstanceId"],
249
+ }),
250
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
251
+ });
252
+ }
253
+ catch (err) {
254
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
255
+ }
256
+ if (!res.ok)
257
+ return { state: "unreadable", reason: `HTTP ${res.status}` };
258
+ let data;
259
+ try {
260
+ data = await res.json();
261
+ }
262
+ catch (err) {
263
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
264
+ }
265
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
266
+ if (rows === null)
267
+ return { state: "unreadable", reason: "the read answered 200 with no row list" };
268
+ if (rows.length === 0)
269
+ return { state: "absent" };
270
+ const home = rows[0]?.originatorInstanceId;
271
+ return { state: "found", home: typeof home === "string" && home.length > 0 ? home : null };
272
+ }
273
+ /**
274
+ * Decide whether an ops-API Agent create/upsert may proceed, given the stored
275
+ * row that already carries this id (`existing`) and the home this instance would
276
+ * stamp (`home`, from resolveTargetInstanceId). PURE.
277
+ *
278
+ * Refuses — with a named error — when a non-null `home` differs from the stored
279
+ * one (a null `home` cannot change it, since no home is written over a found row), and
280
+ * when the stored row could not be read (an unreadable read is not "no home").
281
+ * Otherwise `stamp` is true only for an absent row (a create); over a found row
282
+ * the write must omit the home so the stored value, null or not, stands.
283
+ */
284
+ export function planAgentHomeWrite(existing, home, id) {
285
+ if (existing.state === "unreadable") {
286
+ return {
287
+ refuse: true,
288
+ message: `could not read agent '${id}' before writing it (${existing.reason}); no change was made.`,
289
+ };
290
+ }
291
+ if (existing.state === "found" && existing.home !== null && home !== null && existing.home !== home) {
292
+ return { refuse: true, message: agentHomeChangeRefusal(id, existing.home, home) };
293
+ }
294
+ return { refuse: false, stamp: existing.state === "absent", home };
295
+ }
296
+ /** The lines `flair agent stamp-home --apply` prints for the rows it left unwritten. */
297
+ export function stampLeftoverLines(result) {
298
+ return [
299
+ ...result.skipped.map((id) => ` not counted as stamped: ${id}`),
300
+ ...result.vanished.map((id) => ` skipped (no longer present): ${id}`),
301
+ ];
302
+ }
303
+ /** One Agent row in full (null when absent, "unreadable" when the read failed). */
304
+ async function readAgentRowForStamp(args) {
305
+ try {
306
+ const res = await args.fetchImpl(args.opsUrl, {
307
+ method: "POST",
308
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
309
+ body: JSON.stringify({ operation: "search_by_id", database: "flair", table: "Agent", ids: [args.id], get_attributes: ["*"] }),
310
+ signal: AbortSignal.timeout(args.timeoutMs),
311
+ });
312
+ if (!res.ok)
313
+ return "unreadable";
314
+ const data = await res.json();
315
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
316
+ if (rows === null)
317
+ return "unreadable";
318
+ return rows.length > 0 && rows[0] && typeof rows[0] === "object" ? rows[0] : null;
319
+ }
320
+ catch {
321
+ return "unreadable";
322
+ }
323
+ }
324
+ /**
325
+ * Back-fill the home on home-less Agent rows with no sync provenance
326
+ * (flair#2433, flair#2472). Reads the roster, plans the stamps, and — with
327
+ * `apply` — asks the Agent resource (a REST PATCH, `httpUrl`) to stamp each
328
+ * stampable row, then reads it back before counting it.
329
+ *
330
+ * The stamp's decision is made INSIDE the resource, in a FRESH OWNED transaction
331
+ * (the request's own transaction is detached for that scope): the resource reads
332
+ * the row there and stamps only when it is still home-less and carries no
333
+ * federation-sync provenance, writing the id the CURRENT `Instance` table names
334
+ * (failure to confirm a single canonical Instance row is refused by name); it then
335
+ * re-reads the committed row and aborts if that read sees a home, provenance, or
336
+ * no row. The CLI's own read is a plan/report, never the write's authority: a
337
+ * row the resource's reads see gain a home or provenance is left alone, and a
338
+ * row they find gone is reported vanished (a stamp never creates). A change
339
+ * committed after the resource's confirmation read and before its commit is not
340
+ * seen (flair#2478). A row is counted `stamped` only when the resource reports
341
+ * that it applied the stamp (`stamped: true`) AND the read-back shows this
342
+ * instance's home with no provenance.
343
+ *
344
+ * `localInstanceId` is the value resolved through the one shared rule; a null
345
+ * ends the run with no write (there is nothing to stamp).
346
+ */
347
+ export async function runAgentHomeStamp(args) {
348
+ const empty = { homeLess: [], stampable: [], sync: [] };
349
+ const rows = await readAgentHomeRows({
350
+ opsUrl: args.opsUrl,
351
+ authHeader: args.authHeader,
352
+ fetchImpl: args.fetchImpl,
353
+ timeoutMs: args.timeoutMs,
354
+ });
355
+ if (rows === null)
356
+ return { ok: false, reason: "roster-unreadable", plan: empty, stamped: [], skipped: [], vanished: [] };
357
+ const plan = planAgentHomeStamps(rows, args.localInstanceId);
358
+ if (!args.apply)
359
+ return { ok: true, plan, stamped: [], skipped: [], vanished: [] };
360
+ if (args.localInstanceId === null)
361
+ return { ok: false, reason: "no-canonical-id", plan, stamped: [], skipped: [], vanished: [] };
362
+ const fetchImpl = args.fetchImpl ?? fetch;
363
+ const timeoutMs = args.timeoutMs ?? 10_000;
364
+ const stampUrl = `${args.httpUrl.replace(/\/$/, "")}/Agent/`;
365
+ const stamped = [];
366
+ const skipped = [];
367
+ const vanished = [];
368
+ for (const id of plan.stampable) {
369
+ // The shared agent-ID rule owns an id outside it — the doctor's Agent-ID
370
+ // check reports such a row. A home stamp is not the place to rewrite it.
371
+ if (!isValidAgentId(id))
372
+ continue;
373
+ const current = await readAgentRowForStamp({ opsUrl: args.opsUrl, authHeader: args.authHeader, id, fetchImpl, timeoutMs });
374
+ if (current === "unreadable") {
375
+ throw new Error(`Could not re-read agent '${id}' before stamping it; no change was made to it.`);
376
+ }
377
+ if (current === null) {
378
+ vanished.push(id);
379
+ continue;
380
+ }
381
+ if (isSyncOriginatedAgentRow(current)) {
382
+ skipped.push(id);
383
+ continue;
384
+ }
385
+ if (!isHomeLessAgentRow(current)) {
386
+ // Gained a home since the plan read. Listed, never overwritten.
387
+ skipped.push(id);
388
+ continue;
389
+ }
390
+ // The guarded write: the Agent resource re-checks home-lessness and
391
+ // provenance inside a fresh owned transaction and stamps the id the current
392
+ // Instance table names. A 404 is reported as vanished.
393
+ const res = await fetchImpl(`${stampUrl}${encodeURIComponent(id)}`, {
394
+ method: "PATCH",
395
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
396
+ body: JSON.stringify({ id, originatorInstanceId: args.localInstanceId, [AGENT_HOME_STAMP_FIELD]: true }),
397
+ signal: AbortSignal.timeout(timeoutMs),
398
+ });
399
+ if (res.status === 404) {
400
+ vanished.push(id);
401
+ continue;
402
+ }
403
+ if (!res.ok) {
404
+ const text = await res.text().catch(() => "");
405
+ throw new Error(`Failed to stamp the home on agent '${id}' (${res.status}): ${text}`);
406
+ }
407
+ // The resource confirms whether IT applied the stamp (`stamped: true`), and
408
+ // the decision is made inside its fresh owned transaction. A read-back that
409
+ // merely shows this instance's home is NOT that confirmation: another writer
410
+ // may have set the same home, or a later merge may own the row. Count a row
411
+ // stamped only when the resource applied it AND the read-back still shows
412
+ // this instance's home with no provenance.
413
+ const body = (await res.json().catch(() => null));
414
+ const applied = body?.stamped === true;
415
+ const back = await readAgentRowForStamp({ opsUrl: args.opsUrl, authHeader: args.authHeader, id, fetchImpl, timeoutMs });
416
+ if (back === "unreadable") {
417
+ throw new Error(`The home stamp for agent '${id}' was not confirmed (the read-back failed).`);
418
+ }
419
+ if (applied && back !== null && !isSyncOriginatedAgentRow(back) && back.originatorInstanceId === args.localInstanceId) {
420
+ stamped.push(id);
421
+ }
422
+ else {
423
+ skipped.push(id);
424
+ }
425
+ }
426
+ return { ok: true, plan, stamped, skipped, vanished };
427
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * agent-id-rule.ts — the ONE agent-ID rule, shared by the CLI (src/) and the
3
+ * server (resources/).
4
+ *
5
+ * An agent ID is the key of an Agent row and is used in URLs, shell hooks and
6
+ * federation payloads, so Flair's paths that create an Agent reject ids outside
7
+ * this rule (`flair mcp grant` also applies a narrower naming policy: a leading
8
+ * letter or digit). Before this module the rule lived inline in
9
+ * resources/AgentSeed.ts only: the Agent resource's REST writes,
10
+ * `flair agent add` and the federation merge each accepted an id AgentSeed
11
+ * would have refused, and the JIT-principal writers (XAA / MCP) built an id
12
+ * from a token subject without checking it.
13
+ *
14
+ * This module is deliberately dependency-free (it imports nothing): the
15
+ * resource/CLI boundary guard (test/unit/resource-src-purity-1775.test.ts)
16
+ * requires every src/ module a resources/ file imports to emit no module
17
+ * loads, and src/ must never import harper.
18
+ *
19
+ * The rule: `^[a-zA-Z0-9_-]{1,64}$` — 1..64 characters of A-Z, a-z, 0-9, `_`
20
+ * or `-`.
21
+ */
22
+ /** The rule as text, for messages and docs. */
23
+ export const AGENT_ID_RULE = "^[a-zA-Z0-9_-]{1,64}$";
24
+ /** The maximum length of an agent ID. */
25
+ export const AGENT_ID_MAX_LENGTH = 64;
26
+ /** The rule as a matcher. */
27
+ export const AGENT_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
28
+ /** The named error the Agent resource's write paths and the federation merge
29
+ * refuse with. The CLI and JIT-principal writers refuse with the same message
30
+ * text but not this code. */
31
+ export const AGENT_ID_ERROR = "invalid_agent_id";
32
+ /**
33
+ * Is `id` an agent ID this rule accepts? A non-string, non-number value —
34
+ * including `null` — is never valid. A write path must distinguish an OMITTED
35
+ * id (nothing to check; Harper may generate one) from a SUPPLIED `null`, which
36
+ * this returns false for.
37
+ */
38
+ export function isValidAgentId(id) {
39
+ if (typeof id !== "string" && typeof id !== "number")
40
+ return false;
41
+ return AGENT_ID_PATTERN.test(String(id));
42
+ }
43
+ /** A human-readable refusal message naming the rule and the offending value. */
44
+ export function invalidAgentIdMessage(id) {
45
+ return `invalid agent id ${JSON.stringify(id)}: an agent id must match ${AGENT_ID_RULE} (1-64 characters: A-Z, a-z, 0-9, _ or -)`;
46
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * agent-roster.ts — the complete Agent roster read `flair doctor` uses for its
3
+ * agent-ID check (flair#2359).
4
+ *
5
+ * SQL is the ops-API operation that reads the whole table: `search_by_conditions`
6
+ * needs at least one condition, and any condition can hide a row.
7
+ */
8
+ /** The ops-API `sql` read of every Agent row's id. */
9
+ export const AGENT_ROSTER_SQL = "SELECT id FROM flair.Agent";
10
+ /**
11
+ * Read every Agent row's id through the operations API. Returns the row list on
12
+ * a successful read, or null when the call failed or its body was not a row
13
+ * list — a failed read is never "no rows". The caller validates each id.
14
+ */
15
+ export async function readAgentRoster(args) {
16
+ const fetchImpl = args.fetchImpl ?? fetch;
17
+ try {
18
+ const res = await fetchImpl(args.opsUrl, {
19
+ method: "POST",
20
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
21
+ body: JSON.stringify({ operation: "sql", sql: AGENT_ROSTER_SQL }),
22
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
23
+ });
24
+ if (!res.ok)
25
+ return null;
26
+ const data = await res.json();
27
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
28
+ return rows;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }