@tpsdev-ai/flair 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -0,0 +1,203 @@
1
+ /**
2
+ * key-dir.ts — the keys-directory walk shared by `flair keys prune`,
3
+ * `flair doctor` and `flair status` (flair#3077).
4
+ *
5
+ * Prune retains its entry classification; mode checks cover every file with a
6
+ * location's key suffix, because signing can read any such file.
7
+ */
8
+ import { existsSync, lstatSync, readdirSync, realpathSync } from "node:fs";
9
+ import { join, resolve } from "node:path";
10
+ import { invalidAgentIdMessage, isValidAgentId } from "./agent-id-rule.js";
11
+ import { resolveHome } from "./home.js";
12
+ /** Read the keys directory, following a symlink at keysDir. The caller owns the
13
+ * "directory absent" decision; this reports only what readdir returned. */
14
+ export function scanKeyDir(keysDir) {
15
+ let dirents;
16
+ try {
17
+ dirents = readdirSync(keysDir, { withFileTypes: true });
18
+ }
19
+ catch (error) {
20
+ return { state: "unreadable", error };
21
+ }
22
+ return {
23
+ state: "ok",
24
+ entries: dirents.map((dirent) => {
25
+ if (dirent.isDirectory())
26
+ return { name: dirent.name, kind: "dir" };
27
+ if (!dirent.name.endsWith(".key"))
28
+ return { name: dirent.name, kind: "other" };
29
+ return { name: dirent.name, kind: "key" };
30
+ }),
31
+ };
32
+ }
33
+ /** The ordered locations `resolveKeyPath` tries for an agent id. Read at CALL
34
+ * time, so `FLAIR_KEY_DIR` set later in the process is seen. */
35
+ export function agentKeyLocations() {
36
+ const home = resolveHome();
37
+ const locations = [];
38
+ if (process.env.FLAIR_KEY_DIR) {
39
+ locations.push({ dir: process.env.FLAIR_KEY_DIR, suffix: ".key" });
40
+ }
41
+ locations.push({ dir: join(home, ".flair", "keys"), suffix: ".key" });
42
+ locations.push({ dir: join(home, ".tps", "secrets", "flair"), suffix: "-priv.key" });
43
+ return locations;
44
+ }
45
+ /** A refusal for an agent id that cannot name a key file: the id is checked
46
+ * before it is joined into a path. Callers map it to their own error style. */
47
+ export class AgentKeyPathRefusal extends Error {
48
+ code = "invalid_agent_id";
49
+ /** The CLI prints the message alone and exits 1 when a command lets it propagate. */
50
+ flairFriendly = true;
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = "AgentKeyPathRefusal";
54
+ }
55
+ }
56
+ /** Apply the shared agent-ID rule to an id a command is about to sign as. */
57
+ export function requireAgentId(agentId) {
58
+ if (!isValidAgentId(agentId))
59
+ throw new AgentKeyPathRefusal(invalidAgentIdMessage(agentId));
60
+ }
61
+ /**
62
+ * The private-key path for `agentId`; the shared agent-ID rule runs before
63
+ * the join.
64
+ */
65
+ export function agentKeyPath(keysDir, agentId) {
66
+ requireAgentId(agentId);
67
+ return join(keysDir, `${agentId}.key`);
68
+ }
69
+ /** The public-key path for `agentId`; the shared agent-ID rule runs before
70
+ * the join. */
71
+ export function agentPubKeyPath(keysDir, agentId) {
72
+ requireAgentId(agentId);
73
+ return join(keysDir, `${agentId}.pub`);
74
+ }
75
+ /** The path signing reads for `agentId` in `location`. */
76
+ export function keyPathIn(location, agentId) {
77
+ requireAgentId(agentId);
78
+ return join(location.dir, `${agentId}${location.suffix}`);
79
+ }
80
+ /** The legacy `~/.tps/secrets/flair/<id>-priv.key` signing key for `agentId`;
81
+ * the shared agent-ID rule runs before the join. */
82
+ export function legacyAgentKeyPath(agentId) {
83
+ requireAgentId(agentId);
84
+ return join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`);
85
+ }
86
+ function errorCode(error) {
87
+ const code = error?.code;
88
+ return typeof code === "string" ? code : "lstat failed";
89
+ }
90
+ /** lstat one key path and report a wide or uncheckable file. No content is read
91
+ * and no file is changed; entry symlinks are not followed. */
92
+ function keyModeFindingForPath(path) {
93
+ let stats;
94
+ try {
95
+ stats = lstatSync(path);
96
+ }
97
+ catch (error) {
98
+ return { kind: "not-checked", path, reason: errorCode(error) };
99
+ }
100
+ if (!stats.isFile()) {
101
+ return {
102
+ kind: "not-checked",
103
+ path,
104
+ reason: stats.isSymbolicLink() ? "symbolic link" : "not a regular file",
105
+ };
106
+ }
107
+ if (stats.mode & 0o077) {
108
+ return { kind: "wide", path, mode: (stats.mode & 0o777).toString(8).padStart(4, "0") };
109
+ }
110
+ return null;
111
+ }
112
+ function canonicalDir(dir) {
113
+ try {
114
+ return realpathSync(dir);
115
+ }
116
+ catch {
117
+ return resolve(dir);
118
+ }
119
+ }
120
+ /** Whether two key-location paths name the same directory entry after resolving symlinks. */
121
+ export function sameKeyDir(a, b) {
122
+ return canonicalDir(a) === canonicalDir(b);
123
+ }
124
+ /** The mode scan over the standard `resolveKeyPath` locations. A path reached
125
+ * through two locations (e.g. `FLAIR_KEY_DIR` pointing at the default
126
+ * directory) is reported once. */
127
+ export function scanAgentKeyModes(locations = agentKeyLocations()) {
128
+ const findings = [];
129
+ const unreadable = [];
130
+ const seenPaths = new Set();
131
+ const seenUnreadable = new Set();
132
+ for (const location of locations) {
133
+ const dirKey = canonicalDir(location.dir);
134
+ const scan = scanKeyDir(location.dir);
135
+ if (scan.state === "unreadable") {
136
+ const code = scan.error?.code;
137
+ if (code !== "ENOENT" && !seenUnreadable.has(dirKey)) {
138
+ seenUnreadable.add(dirKey);
139
+ unreadable.push({ dir: location.dir, code: code ?? "error" });
140
+ }
141
+ continue;
142
+ }
143
+ const names = scan.entries.map((e) => e.name).filter((name) => name.endsWith(location.suffix)).sort();
144
+ for (const name of names) {
145
+ const path = join(location.dir, name);
146
+ const pathKey = join(dirKey, name);
147
+ if (seenPaths.has(pathKey))
148
+ continue;
149
+ seenPaths.add(pathKey);
150
+ const finding = keyModeFindingForPath(path);
151
+ if (finding)
152
+ findings.push(finding);
153
+ }
154
+ }
155
+ return { findings, unreadable };
156
+ }
157
+ /** POSIX single-quoting for a path used in a command an operator will run. A
158
+ * relative path that starts with `-` is prefixed with `./`, so the command
159
+ * does not read it as an option. */
160
+ function shellQuotePath(path) {
161
+ const operand = path.startsWith("-") ? `./${path}` : path;
162
+ if (/^[A-Za-z0-9._\-/]+$/.test(operand))
163
+ return operand;
164
+ return `'${operand.replace(/'/g, `'\\''`)}'`;
165
+ }
166
+ /** The one rendering of a finding, so doctor and status cannot word it
167
+ * differently. The `chmod` remedy shell-quotes the path. */
168
+ export function formatKeyModeFinding(finding) {
169
+ if (finding.kind === "wide") {
170
+ return `agent key file ${finding.path} has mode ${finding.mode}, wider than owner-only — fix: chmod 600 ${shellQuotePath(finding.path)}`;
171
+ }
172
+ return `agent key file ${finding.path} not checked (${finding.reason})`;
173
+ }
174
+ /** Mode bits carry no owner-only meaning on Windows. */
175
+ export function keyModesUnsupported() {
176
+ return process.platform === "win32";
177
+ }
178
+ export const KEY_MODES_UNSUPPORTED_MESSAGE = "key file modes are not checked on Windows";
179
+ /** The keys directory `~/.flair/keys`, resolved at CALL time. */
180
+ export function defaultKeysDir() {
181
+ return join(resolveHome(), ".flair", "keys");
182
+ }
183
+ /** Node-shaped file ids. */
184
+ const NODE_KEY_ID_RE = /^flair_[0-9a-f]{8}$/;
185
+ /** Match node-shaped ids without a sibling .pub; file type is unproven. */
186
+ export function isNodeKeyId(id, keysDir) {
187
+ if (!NODE_KEY_ID_RE.test(id))
188
+ return false;
189
+ return !existsSync(agentPubKeyPath(keysDir, id));
190
+ }
191
+ /**
192
+ * Partition `.key`-derived ids by file name: an id that `isNodeKeyId` matches
193
+ * (node-shaped, no sibling `.pub`) goes to `nodeKeyIds`, every other id to
194
+ * `agentKeyIds`. Key contents are not read.
195
+ */
196
+ export function partitionKeyIds(ids, keysDir) {
197
+ const agentKeyIds = [];
198
+ const nodeKeyIds = [];
199
+ for (const id of ids) {
200
+ (isNodeKeyId(id, keysDir) ? nodeKeyIds : agentKeyIds).push(id);
201
+ }
202
+ return { agentKeyIds, nodeKeyIds };
203
+ }
@@ -26,9 +26,11 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
26
26
  "retrievalCount",
27
27
  "lastRetrieved",
28
28
  "usageCount",
29
+ "writeBackWriteId",
29
30
  "promotionStatus",
30
31
  "promotedAt",
31
32
  "promotedBy",
33
+ "promotionContentHash",
32
34
  "archived",
33
35
  "archivedAt",
34
36
  "archivedBy",
@@ -0,0 +1,20 @@
1
+ /**
2
+ * open-live-row.ts — the skill writer's "open live" Memory-row predicate
3
+ * (flair#2662), shared so `flair doctor` asks the same question the writer
4
+ * answers. It checks the row's fields and the current time (for `expiresAt`). Deliberately imports nothing (resources
5
+ * importing this compiled helper require it to be load-free).
6
+ *
7
+ * A row is open-live when it is not archived, is not expired (`expiresAt`
8
+ * absent, or a string later than now), and carries no `validTo`.
9
+ */
10
+ export function isOpenLiveRow(row) {
11
+ if (!row || typeof row !== "object")
12
+ return false;
13
+ if (row.archived === true)
14
+ return false;
15
+ if (row.expiresAt != null && (typeof row.expiresAt !== "string" || !(Date.parse(row.expiresAt) > Date.now())))
16
+ return false;
17
+ if (typeof row.validTo === "string" && row.validTo.length > 0)
18
+ return false;
19
+ return true;
20
+ }
@@ -477,6 +477,19 @@ export function describeScheduledDriverFinding(f) {
477
477
  };
478
478
  }
479
479
  // Loaded from here down.
480
+ if (f.shimMissingNode) {
481
+ const m = f.shimMissingNode;
482
+ return {
483
+ state: "degraded",
484
+ icon: "error",
485
+ isIssue: true,
486
+ message: `${f.label} DEGRADED — the shim its unit file names execs a node binary that does not exist (${m.nodeBin})`,
487
+ detail: [
488
+ `${m.unitPath} names ${m.shimPath} as its program; the shim's exec line names ${m.nodeBin}, which does not exist.`,
489
+ `Fix: flair init # then check: ${f.statusCommand}`,
490
+ ],
491
+ };
492
+ }
480
493
  const le = f.lastExit;
481
494
  if (!le || le.state === "unavailable") {
482
495
  return {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Soul is scoped to an `agentId` and has no dedicated or enforced per-user
3
+ * scope field (schemas/memory.graphql).
4
+ * A write that would store a non-empty `scopeTag` or a non-empty `tags` array
5
+ * is refused by name when earlier guards permit the request, whatever the tag's
6
+ * prefix: POST and PUT check the request body, PATCH the merged row
7
+ * (flair#1540).
8
+ *
9
+ * The predicate runs in the server's write policy. The refusal name is
10
+ * imported by `flair import` and `flair restore`, which report a row refused
11
+ * with it; `flair rem restore` reports its generic HTTP error and imports
12
+ * neither.
13
+ */
14
+ /** The named refusal for a Soul write that would store a non-empty `scopeTag` or a non-empty `tags` array. */
15
+ export const SOUL_SCOPE_FIELDS_REFUSAL = "soul_scope_fields_not_writable";
16
+ /**
17
+ * Whether a row would carry a non-empty `scopeTag` or a non-empty `tags`
18
+ * array. POST and PUT pass the request body; PATCH passes the merged row.
19
+ */
20
+ export function suppliesSoulScopeFields(content) {
21
+ const scopeTag = content?.scopeTag;
22
+ if (scopeTag !== undefined && scopeTag !== null && scopeTag !== "")
23
+ return true;
24
+ const tags = content?.tags;
25
+ return Array.isArray(tags) && tags.length > 0;
26
+ }
@@ -207,9 +207,9 @@ export function validateHumanReviewerId(reviewerId) {
207
207
  // lives server-side in resources/auto-promote-lib.ts (decideAutoPromote — the
208
208
  // UNATTENDED path), which IMPORTS these from here. The direction is deliberate
209
209
  // and established in this repo: a server file may import a PURE helper from src/
210
- // (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts already
211
- // import this very module); it is a CLI file importing FROM resources/ that does
212
- // not survive npm packaging. Defining it here lets the CLI side
210
+ // (resources/PromoteMemoryCandidate.ts already imports this very module); it is
211
+ // a CLI file importing FROM resources/ that does not survive npm packaging.
212
+ // Defining it here lets the CLI side
213
213
  // (src/commands/rem.ts, `flair rem candidates`) and the server gate share ONE
214
214
  // implementation rather than a hand-kept pair.
215
215
  //
@@ -14,7 +14,7 @@
14
14
  * invokes `flair rem nightly run-once`, the runner module does the work.
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
- import { resolve, dirname } from "node:path";
17
+ import { resolve, dirname, join } from "node:path";
18
18
  import { spawn } from "node:child_process";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { escapeXml } from "../lib/xml-escape.js";
@@ -93,16 +93,26 @@ function validateSchedule(hour, minute) {
93
93
  throw new Error(`minute must be an integer 0-59, got ${minute}`);
94
94
  }
95
95
  }
96
+ /**
97
+ * Quote a value as ONE POSIX shell word. Embedded single quotes are closed,
98
+ * escaped, and reopened, so the shell reads the value literally and never
99
+ * interprets `$()`, backticks, or quotes inside it.
100
+ */
101
+ export function quoteShimArg(value) {
102
+ return `'${value.replace(/'/g, "'\\''")}'`;
103
+ }
96
104
  function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
97
105
  validateSchedule(opts.hour, opts.minute);
98
106
  if (!/^[a-zA-Z0-9_-]+$/.test(opts.agentId)) {
99
107
  throw new Error(`invalid agent id: ${opts.agentId}`);
100
108
  }
109
+ const home = opts.homeOverride ?? resolveHome();
101
110
  return {
102
111
  FLAIR_BIN: flairBin,
103
112
  NODE_BIN: nodeBin,
104
113
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? resolveHome(),
114
+ ADMIN_PASS_FILE: resolve(opts.adminPassFile ?? join(home, ".flair", "admin-pass")),
115
+ HOME: home,
106
116
  AGENT_ID: opts.agentId,
107
117
  FLAIR_URL: opts.flairUrl,
108
118
  HOUR: String(opts.hour),
@@ -369,8 +379,15 @@ export function enableScheduler(opts) {
369
379
  `\`flair rem nightly enable\`.`);
370
380
  }
371
381
  const stderrLogPath = resolve(logsDir, "rem-nightly.stderr.log");
372
- // 1. Deploy the shim (always — both platforms invoke it).
373
- const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), subs);
382
+ // 1. Deploy the shim (always — both platforms invoke it). Every path passed
383
+ // to the command is one POSIX single-quoted argument; none is double-quoted,
384
+ // so shell syntax inside a path stays literal.
385
+ const shimContents = renderTemplate(readTemplate(templateRoot, "bin/flair-rem-nightly.sh.tmpl"), {
386
+ ...subs,
387
+ NODE_BIN: quoteShimArg(subs.NODE_BIN),
388
+ FLAIR_BIN: quoteShimArg(subs.FLAIR_BIN),
389
+ ADMIN_PASS_FILE: quoteShimArg(subs.ADMIN_PASS_FILE),
390
+ });
374
391
  writeFileWithDir(shimPath, shimContents, 0o700);
375
392
  chmodSync(shimPath, 0o700);
376
393
  // 2. Write the scheduler entry.
@@ -27,12 +27,12 @@ server, which has them sign in at the identity provider configured under
27
27
  configures GitHub. The access token the app receives carries the login as its
28
28
  subject; for GitHub, that is the account's username.
29
29
 
30
- `/mcp` answers `initialize`, `ping` and `tools/list` for any valid token, and
31
- refuses a `tools/call` for an unknown tool name, before it looks at the mapping.
30
+ `/mcp` answers `initialize` and `ping` for any valid token, and refuses a
31
+ `tools/call` for an unknown tool name, before it looks at the mapping.
32
32
  On a `tools/call` for a known tool, Flair looks for a `Credential` of kind `idp`
33
33
  whose `idpSubject` is that login, that names a principal, and whose status is
34
- not `revoked`, and acts as that principal. There is no fallback to an anonymous
35
- or admin identity:
34
+ exactly `active`, and acts as that principal. There is no fallback to an
35
+ anonymous or admin identity:
36
36
 
37
37
  - **No mapping:** the call is refused. `/mcp` answers HTTP 200 with a JSON-RPC
38
38
  error:
@@ -41,6 +41,10 @@ or admin identity:
41
41
  {"jsonrpc":"2.0","id":1,"error":{"code":-32001,"message":"forbidden: token subject is not a provisioned flair agent"}}
42
42
  ```
43
43
 
44
+ - **The login's credentials are not `active` or name no principal:** refused
45
+ with code `-32001`. The message names one of those credentials and its stored
46
+ status (`revoked`, any other value, or no status), and says an operator must
47
+ re-link it.
44
48
  - **Mapped to a principal that does not exist:** refused with code `-32001` and
45
49
  a message naming the principal.
46
50
  - **Mapped to a deactivated principal:** refused; see
@@ -48,6 +52,10 @@ or admin identity:
48
52
  - **The credential or the principal could not be read:** refused with code
49
53
  `-32000` and a message starting `unavailable:`.
50
54
 
55
+ A `tools/list` reads the mapping the same way and answers each case above
56
+ except **No mapping** with the same error; with no mapping it returns a tool
57
+ list.
58
+
51
59
  ### Map a person to a principal
52
60
 
53
61
  `flair mcp enable` writes the mapping in its `identity-mapping` step:
@@ -123,8 +131,8 @@ both take the same `--instance` and `--admin-pass`.
123
131
 
124
132
  ### One mapping per login
125
133
 
126
- `flair mcp enable` and the resolver both count a login's `idp` credential unless
127
- its status is `revoked` (the resolver also skips one that names no principal).
134
+ `flair mcp enable` and the resolver both treat a login's `idp` credential as a
135
+ mapping only when its status is exactly `active` and it names a principal.
128
136
  `flair mcp enable` keeps one such credential per login, whatever the provider
129
137
  name:
130
138
 
@@ -133,9 +141,10 @@ name:
133
141
  says `re-pointed`. Calls from that login then act as the principal the
134
142
  credential names. Memories are not moved or merged; each principal keeps its
135
143
  own.
136
- - If the login has a credential that is not `revoked` under a different
137
- provider name, the run revokes it (the row stays, with status `revoked`) and
138
- prints its id after `SUPERSEDED:`.
144
+ - If the login has a credential under a different provider name whose status
145
+ is `active` and that names a principal, the run revokes it (the row stays,
146
+ with status `revoked`) and prints its id after `SUPERSEDED:`. A credential
147
+ whose status is anything else is not changed.
139
148
  - After writing, it requires exactly one resolvable (principal-bearing) active
140
149
  credential matching the written id and principal.
141
150
  Principal-less legacy rows are skipped and may remain active.
@@ -292,7 +301,7 @@ uses the token-endpoint URL as its audience, so the pinned `@harperfast/oauth`
292
301
  tokenEndpointAudience:
293
302
  clientIds:
294
303
  - https://chatgpt.com/oauth/client.json
295
- expiresAt: '2026-11-01T00:00:00Z'
304
+ expiresAt: '<future ISO 8601 expiry>'
296
305
  ```
297
306
 
298
307
  Use the exact client ID and an operator-chosen future ISO 8601 `expiresAt`;
@@ -314,6 +323,11 @@ A connection acts as its principal:
314
323
  - **Admin** authority applies to a `/mcp` connection only when the principal's
315
324
  Agent record has `role: admin`. The principals that `flair mcp enable` and
316
325
  just-in-time provisioning create are not admins.
326
+ - **Scopes** narrow a connection: each tool requires one OAuth scope (listed in
327
+ [auth.md](auth.md#scopes)), and a call whose access token does not grant it is
328
+ refused with `insufficient_scope`. A refreshed token keeps the scope of its
329
+ sign-in, so a connection that signed in without a tool's scope is refused
330
+ that tool until it signs in again requesting it.
317
331
 
318
332
  ### Tokens
319
333
 
@@ -322,7 +336,8 @@ A connection acts as its principal:
322
336
  the headless `client_credentials` grant is enabled, its access tokens last
323
337
  300 seconds unless `mcp.clientCredentials.accessTokenTtl` is set. A request
324
338
  with an expired or invalid token gets HTTP 401 with
325
- error `invalid_token` and a `WWW-Authenticate: Bearer resource_metadata="…"`
339
+ error `invalid_token` and a
340
+ `WWW-Authenticate: Bearer resource_metadata="…", scope="memory:read memory:write principal:read"`
326
341
  header.
327
342
  - With the shipped `config.yaml`, which does not set
328
343
  `mcp.refreshTokenRequiresOfflineAccess`, the app also gets a refresh token
@@ -655,20 +670,22 @@ and read `agentId` and `scope`.
655
670
  **Revoke:** `flair principal disable bob-the-bot` on the Flair host; its next
656
671
  request gets `{"error":"principal_deactivated"}`.
657
672
 
658
- `flair agent remove bob-the-bot`, also run on the Flair host, asks you to type
659
- `yes` (or takes `--force`), then:
673
+ `flair agent remove bob-the-bot`, also run on the Flair host, scans the agent's
674
+ `Memory` and `Soul` rows, asks you to type `yes` (or takes `--force`), then:
660
675
 
661
- - searches the agent's `Memory` and `Soul` rows and sends a delete for each one
662
- it finds, without checking whether each delete succeeded;
676
+ - purges scanned `Memory` rows when present and confirms the purge receipt,
677
+ deletes scanned `Soul` rows when present and checks each delete response,
678
+ then re-scans `Soul` to confirm no rows for the agent remain before deleting
679
+ the Agent record;
663
680
  - sends a delete for the `Agent` record, and stops with an error if the
664
681
  operations API rejects it;
665
682
  - unless you pass `--keep-keys`, attempts to delete the agent's key files
666
- (private, public and `.bak`) from the keys directory on the machine it runs
667
- on, ignoring any failure;
668
- - prints `Key files deleted.` (with `--keep-keys`,
683
+ (private, public, `.bak`, `<key>.bak.<UTC timestamp>` backups and
684
+ `.<agentId>.key.tmp-<hex>` staging keys) from the keys directory on the machine
685
+ it runs on, ignoring any failure;
686
+ - prints `Removed N key file(s).` (with `--keep-keys`,
669
687
  `Key files preserved (--keep-keys).`) and then
670
- `✅ Agent 'bob-the-bot' removed successfully`, without checking the Memory,
671
- Soul and key-file deletions.
688
+ `✅ Agent 'bob-the-bot' removed successfully`.
672
689
 
673
690
  Rows the agent owns in other tables, such as its workspace state, are left in
674
691
  place.
@@ -692,7 +709,8 @@ bytes). With `FLAIR_MCP_ISSUER=https://flair.example.com`, the document for
692
709
  "client_name": "bob-the-bot",
693
710
  "jwks": { "keys": [ { "kty": "OKP", "crv": "Ed25519", "x": "<public key>", "kid": "bob-the-bot" } ] },
694
711
  "token_endpoint_auth_method": "private_key_jwt",
695
- "grant_types": ["client_credentials"]
712
+ "grant_types": ["client_credentials"],
713
+ "scope": "memory:read memory:write principal:read"
696
714
  }
697
715
  ```
698
716