@tpsdev-ai/flair 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -44,7 +44,7 @@ export const RESTORE_PRESERVED_FIELDS = Object.freeze({
44
44
  "id", "agentId", "content", "contentHash", "trigger", "visibility",
45
45
  "tags", "durability", "source", "type",
46
46
  "createdAt", "expiresAt", "usageCount", "promotionStatus", "promotedAt",
47
- "promotedBy", "archived", "archivedAt", "archivedBy", "parentId",
47
+ "promotedBy", "promotionContentHash", "archived", "archivedAt", "archivedBy", "parentId",
48
48
  "derivedFrom", "sessionId", "lastReflected", "supersedes", "subject",
49
49
  "summary", "validFrom", "validTo", "metadata", "entities",
50
50
  "meta", "kind",
@@ -0,0 +1,159 @@
1
+ /**
2
+ * skill-assignment-preflight.ts — the CLI-side copy of the server's
3
+ * `refuseSkillAssignmentWrite` (resources/skill-provenance.ts) used by
4
+ * non-dry-run `flair restore --replace` before any delete.
5
+ *
6
+ * A copy, not an import: `src/` must not import `resources/` (those imports do
7
+ * not survive npm packaging). test/unit/skill-assignment-preflight.test.ts
8
+ * pins this copy to the server module over a shared fixture table.
9
+ */
10
+ import { tmpdir } from "node:os";
11
+ import { isAbsolute, resolve, sep } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ export const SKILL_ASSIGNMENT_KEY = "skill-assignment";
14
+ export function parseSkillMetadata(metadata) {
15
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) {
16
+ return metadata;
17
+ }
18
+ if (typeof metadata === "string" && metadata.length > 0) {
19
+ try {
20
+ const parsed = JSON.parse(metadata);
21
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
22
+ return parsed;
23
+ }
24
+ }
25
+ catch {
26
+ /* opaque / corrupt blob — no source */
27
+ }
28
+ }
29
+ return {};
30
+ }
31
+ export function skillSourceOf(record) {
32
+ const src = parseSkillMetadata(record.metadata).source;
33
+ return typeof src === "string" && src.trim().length > 0 ? src.trim() : undefined;
34
+ }
35
+ const SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
36
+ function isWindowsDrivePath(source) {
37
+ return /^[a-zA-Z]:[\\/]/.test(source);
38
+ }
39
+ /**
40
+ * If `source` names a filesystem path (absolute, relative, or `file:` URL),
41
+ * return that path. Scheme-bearing identifiers (`npm:`, `https:`, …) are
42
+ * not filesystem paths. A bare name is not a path.
43
+ */
44
+ export function filesystemPathFromSkillSource(source) {
45
+ const trimmed = source.trim();
46
+ if (!trimmed)
47
+ return null;
48
+ if (trimmed.startsWith("file:")) {
49
+ try {
50
+ return fileURLToPath(trimmed);
51
+ }
52
+ catch {
53
+ const rest = trimmed.replace(/^file:\/\//, "").replace(/^file:/, "");
54
+ return rest.length > 0 ? rest : null;
55
+ }
56
+ }
57
+ if (SCHEME.test(trimmed) && !isWindowsDrivePath(trimmed))
58
+ return null;
59
+ if (isAbsolute(trimmed) || trimmed.startsWith(".") || /[\\/]/.test(trimmed)) {
60
+ return trimmed;
61
+ }
62
+ return null;
63
+ }
64
+ function tempRoots() {
65
+ const roots = new Set();
66
+ const add = (p) => {
67
+ if (!p || typeof p !== "string" || p.length === 0)
68
+ return;
69
+ try {
70
+ roots.add(resolve(p));
71
+ }
72
+ catch {
73
+ /* ignore unresolvable */
74
+ }
75
+ };
76
+ add(tmpdir());
77
+ add("/tmp");
78
+ add("/private/tmp");
79
+ add("/var/tmp");
80
+ add(process.env.TMPDIR);
81
+ add(process.env.TMP);
82
+ add(process.env.TEMP);
83
+ return [...roots];
84
+ }
85
+ export function isNonDurableFilesystemPath(fsPath) {
86
+ let resolved;
87
+ try {
88
+ resolved = resolve(fsPath);
89
+ }
90
+ catch {
91
+ return true;
92
+ }
93
+ for (const root of tempRoots()) {
94
+ if (resolved === root || resolved.startsWith(root + sep))
95
+ return true;
96
+ }
97
+ return false;
98
+ }
99
+ export function isDurableSkillSource(source) {
100
+ const fsPath = filesystemPathFromSkillSource(source);
101
+ if (fsPath == null)
102
+ return true;
103
+ return !isNonDurableFilesystemPath(fsPath);
104
+ }
105
+ /**
106
+ * Whether `record` is a skill-assignment row whose source is a filesystem path.
107
+ * Parsing the source is environment-independent; the durability verdict for a
108
+ * filesystem path is not (it reads this process's temp roots).
109
+ */
110
+ export function skillSourceIsFilesystemPath(record) {
111
+ if (record.key !== SKILL_ASSIGNMENT_KEY)
112
+ return false;
113
+ const source = skillSourceOf(record);
114
+ return source !== undefined && filesystemPathFromSkillSource(source) !== null;
115
+ }
116
+ export function registerSkillAssignment(input) {
117
+ const key = typeof input.key === "string" ? input.key : SKILL_ASSIGNMENT_KEY;
118
+ if (key !== SKILL_ASSIGNMENT_KEY)
119
+ return { ok: true };
120
+ const source = skillSourceOf(input);
121
+ if (!source)
122
+ return { ok: true };
123
+ if (isDurableSkillSource(source))
124
+ return { ok: true };
125
+ return {
126
+ ok: false,
127
+ error: "skill_source_not_durable",
128
+ path: source,
129
+ message: `skill source is not durable: ${source}`,
130
+ };
131
+ }
132
+ function assignmentKey(content, existing) {
133
+ const key = content?.key ?? existing?.key;
134
+ return typeof key === "string" ? key : undefined;
135
+ }
136
+ /** Soul post/put/patch gate. `existing` supplies omitted fields on PATCH. */
137
+ export function refuseSkillAssignmentWrite(content, existing) {
138
+ if (assignmentKey(content, existing) !== SKILL_ASSIGNMENT_KEY)
139
+ return null;
140
+ const metadata = content?.metadata !== undefined ? content.metadata : existing?.metadata;
141
+ // flair#2141 S1: `metadata.optOut`, when present, is a boolean.
142
+ const parsed = parseSkillMetadata(metadata);
143
+ if (Object.hasOwn(parsed, "optOut") && typeof parsed.optOut !== "boolean") {
144
+ return new Response(JSON.stringify({ error: "skill_opt_out_not_boolean", message: "metadata.optOut must be true or false" }), { status: 400, headers: { "content-type": "application/json" } });
145
+ }
146
+ const result = registerSkillAssignment({
147
+ key: SKILL_ASSIGNMENT_KEY,
148
+ value: content?.value ?? existing?.value,
149
+ priority: content?.priority ?? existing?.priority,
150
+ metadata,
151
+ });
152
+ if (!("error" in result))
153
+ return null;
154
+ return new Response(JSON.stringify({
155
+ error: result.error,
156
+ path: result.path,
157
+ message: result.message,
158
+ }), { status: 400, headers: { "content-type": "application/json" } });
159
+ }
@@ -58,7 +58,8 @@ export const SEED_ASSIGNMENT_PRIORITY = "standard";
58
58
  */
59
59
  export const SEED_REQUEST_TIMEOUT_MS = 15_000;
60
60
  /**
61
- * The bound on the skill row's write. The instance embeds a skill row as it
61
+ * The bound on the skill row's write, counted from its first attempt (see
62
+ * runSkillSeed for the retries it bounds). The instance embeds a skill row as it
62
63
  * writes it (`Memory.put` awaits `getEmbedding`), and the first embed awaits
63
64
  * the embedding model's readiness: the model may need to download (~80 MB) or
64
65
  * load in the background, and Harper can report healthy before that ends. So
@@ -70,6 +71,20 @@ export const SEED_REQUEST_TIMEOUT_MS = 15_000;
70
71
  export const SEED_SKILL_WRITE_TIMEOUT_MS = 180_000;
71
72
  /** How long the skill row's write runs before init says what it is waiting on. */
72
73
  export const SEED_SKILL_WRITE_NOTICE_MS = 5_000;
74
+ /**
75
+ * The wait before the seed tries the skill row's write again after the
76
+ * instance refused it with 503 `memory_provider_timeout`, which states nothing
77
+ * was written. The seed tries again only while the skill-write bound
78
+ * ({@link SEED_SKILL_WRITE_TIMEOUT_MS} by default), counted from the first
79
+ * attempt, leaves time for this wait.
80
+ */
81
+ export const SEED_SKILL_WRITE_RETRY_BACKOFF_MS = 2_000;
82
+ /** The server's error code for an embedding call that outlasted its bound. */
83
+ const MEMORY_PROVIDER_TIMEOUT = "memory_provider_timeout";
84
+ const REAL_CLOCK = {
85
+ now: () => Date.now(),
86
+ pause: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
87
+ };
73
88
  /** The shipped `using-flair` skill as this build defines it. */
74
89
  export function currentSeed() {
75
90
  return {
@@ -144,8 +159,48 @@ const ROW_REMEDY = `Inspect it (GET ${ROW_PATH}), delete it with the operator's
144
159
  "then re-run 'flair init'";
145
160
  const ASSIGNMENT_REMEDY = `Inspect it (GET ${ASSIGNMENT_PATH}), correct or delete it with the operator's Basic credentials, ` +
146
161
  "then re-run 'flair init'";
147
- /** Apply the seed rule over `io`. Preflight reads and checks pass before either write. */
148
- export async function runSkillSeed(io, current) {
162
+ /**
163
+ * Apply the seed rule over `io`. Preflight reads and checks pass before either
164
+ * write. When the instance refuses the skill row's write with 503
165
+ * `memory_provider_timeout`, the seed waits {@link SEED_SKILL_WRITE_RETRY_BACKOFF_MS}
166
+ * and runs the whole pass again, reads and checks included, while the io's
167
+ * skill-write bound, counted from the first attempt, leaves time for that wait.
168
+ * Each attempt's write waits at most the time left in that bound. When the
169
+ * bound leaves no time for another wait, passes before a retried pass's write,
170
+ * or ends a write that got no answer, the refusal names the attempts and the
171
+ * time spent.
172
+ */
173
+ export async function runSkillSeed(io, current, clock = REAL_CLOCK) {
174
+ const boundMs = io.skillWriteTimeoutMs ?? SEED_SKILL_WRITE_TIMEOUT_MS;
175
+ let firstWriteAt;
176
+ const rowWriteBudget = () => {
177
+ firstWriteAt ??= clock.now();
178
+ return firstWriteAt + boundMs - clock.now();
179
+ };
180
+ let attempts = 0;
181
+ const boundPassed = (end) => refused("skill_seed_write_failed", `writing the "${SEED_SKILL_ID}" skill row did not finish within its ${seconds(boundMs)} bound: ${attempts} ` +
182
+ `${attempts === 1 ? "attempt" : "attempts"} over ${seconds(clock.now() - (firstWriteAt ?? clock.now()))}; ` +
183
+ `${end}; the org assignment was not written. Re-run 'flair init'`);
184
+ const refusedEach = () => `${attempts === 1 ? "it was" : "each was"} refused with 503 memory_provider_timeout`;
185
+ for (;;) {
186
+ const outcome = await seedPass(io, current, rowWriteBudget);
187
+ if (outcome.kind === "no_time") {
188
+ return boundPassed(`${refusedEach()}, and the bound passed while the seed re-read the instance`);
189
+ }
190
+ if (outcome.kind === "no_answer") {
191
+ attempts++;
192
+ return boundPassed(`${attempts === 1 ? "it" : "the last"} got ${outcome.detail}`);
193
+ }
194
+ if (outcome.kind !== "provider_timeout")
195
+ return outcome;
196
+ attempts++;
197
+ if (clock.now() - (firstWriteAt ?? clock.now()) + SEED_SKILL_WRITE_RETRY_BACKOFF_MS >= boundMs) {
198
+ return boundPassed(`${refusedEach()}, and no time is left for another (last: ${outcome.detail})`);
199
+ }
200
+ await clock.pause(SEED_SKILL_WRITE_RETRY_BACKOFF_MS);
201
+ }
202
+ }
203
+ async function seedPass(io, current, rowWriteBudget) {
149
204
  const rowRead = await io.readRow();
150
205
  if (!rowRead.ok) {
151
206
  return refused("skill_seed_row_unreadable", `the "${SEED_SKILL_ID}" Memory row could not be read (${rowRead.detail ?? "no detail"}); ${NOTHING_WRITTEN}. ` +
@@ -190,8 +245,16 @@ export async function runSkillSeed(io, current) {
190
245
  }
191
246
  const action = decideSkillSeed(storedContent, current.content, current.hashes);
192
247
  if (action === "create" || action === "replace") {
193
- const write = await io.putRow();
248
+ const budgetMs = rowWriteBudget();
249
+ if (budgetMs <= 0)
250
+ return { kind: "no_time" };
251
+ const write = await io.putRow(budgetMs);
194
252
  if (!write.ok) {
253
+ if (write.status === 503 && write.code === MEMORY_PROVIDER_TIMEOUT) {
254
+ return { kind: "provider_timeout", detail: write.detail ?? "no detail" };
255
+ }
256
+ if (write.timedOut)
257
+ return { kind: "no_answer", detail: write.detail ?? "no detail" };
195
258
  return refused("skill_seed_write_failed", `writing the "${SEED_SKILL_ID}" skill row failed (${write.detail ?? "no detail"}); the org assignment was not ` +
196
259
  "written. Re-run 'flair init'");
197
260
  }
@@ -245,6 +308,16 @@ function detailOf(err) {
245
308
  function isTimeout(err) {
246
309
  return typeof err === "object" && err !== null && err.name === "TimeoutError";
247
310
  }
311
+ /** The string `error` field of a JSON object body, or undefined. */
312
+ function errorCodeOf(text) {
313
+ try {
314
+ const body = JSON.parse(text);
315
+ return body && typeof body === "object" && typeof body.error === "string" ? body.error : undefined;
316
+ }
317
+ catch {
318
+ return undefined;
319
+ }
320
+ }
248
321
  function seconds(ms) {
249
322
  return `${Math.round(ms / 100) / 10} s`;
250
323
  }
@@ -312,12 +385,17 @@ export function skillSeedRestIo(opts, current = currentSeed()) {
312
385
  }
313
386
  catch (err) {
314
387
  if (isTimeout(err))
315
- return { ok: false, detail: onTimeout(timeoutMs) };
388
+ return { ok: false, detail: onTimeout(timeoutMs), timedOut: true };
316
389
  return { ok: false, detail: `the request failed: ${detailOf(err)}` };
317
390
  }
318
391
  if (!res.ok) {
319
392
  const text = await res.text().catch(() => "");
320
- return { ok: false, detail: `HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}` };
393
+ return {
394
+ ok: false,
395
+ detail: `HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`,
396
+ status: res.status,
397
+ code: errorCodeOf(text),
398
+ };
321
399
  }
322
400
  return { ok: true };
323
401
  };
@@ -327,14 +405,18 @@ export function skillSeedRestIo(opts, current = currentSeed()) {
327
405
  // instance, which may still land it. The id is fixed, so a re-run updates
328
406
  // that row rather than adding one; a re-run started while the first write is
329
407
  // still pending can send a second PUT to the same id.
330
- const putRow = async () => {
408
+ let noticed = false;
409
+ const putRow = async (timeoutMs = skillWriteMs) => {
331
410
  const notice = setTimeout(() => {
411
+ if (noticed)
412
+ return;
413
+ noticed = true;
332
414
  opts.notify?.(`using-flair skill: still writing "${SEED_SKILL_ID}" — the instance embeds a skill row as it writes it, ` +
333
415
  `and it may need to download (~80 MB) or load the embedding model first; waiting up to ${seconds(skillWriteMs)}`);
334
416
  }, skillNoticeMs);
335
417
  notice.unref?.();
336
418
  try {
337
- return await putById("Memory", SEED_SKILL_ID, seedSkillBody(opts.user, current), skillWriteMs, (ms) => `no answer within ${seconds(ms)} — the instance embeds a skill row as it writes it, so this write also ` +
419
+ return await putById("Memory", SEED_SKILL_ID, seedSkillBody(opts.user, current), timeoutMs, (ms) => `no answer within ${seconds(ms)} — the instance embeds a skill row as it writes it, so this write also ` +
338
420
  `waits for its embedding model, which may need to download or load; 'flair doctor' reports embeddings. The write may ` +
339
421
  `still land; the id is fixed, so a re-run updates that row rather than adding one`);
340
422
  }
@@ -348,6 +430,7 @@ export function skillSeedRestIo(opts, current = currentSeed()) {
348
430
  readAssignment: () => readById("OrgSkillAssignment", SEED_ASSIGNMENT_ID),
349
431
  readOperatorAgent: () => readById("Agent", opts.user),
350
432
  putRow,
433
+ skillWriteTimeoutMs: skillWriteMs,
351
434
  putAssignment: () => putById("OrgSkillAssignment", SEED_ASSIGNMENT_ID, {
352
435
  skillName: current.name,
353
436
  skillRef: SEED_SKILL_ID,
@@ -0,0 +1,133 @@
1
+ /**
2
+ * skill-tombstone-doctor.ts — the `flair doctor` check for skill subjects whose
3
+ * newest InstructionVersion is a `delete` tombstone while the skill's Memory
4
+ * row is still open-live (flair#2662).
5
+ *
6
+ * A skill DELETE appends a tombstone and closes the live Memory row. When the
7
+ * post-commit confirmation cannot read the close, the tombstone can commit
8
+ * while the row stays open-live. This check reports that inconsistency; it
9
+ * never repairs it.
10
+ *
11
+ * "Open-live" is the skill writer's own predicate (isOpenLiveRow): not
12
+ * archived, not expired, and no `validTo`. An archived or expired row under a
13
+ * tombstone is not reported.
14
+ *
15
+ * The decision reads only the row fields and the current time. The reads use the operations API and return null on a
16
+ * failed read (never an empty list), so a doctor that cannot read the tables
17
+ * reports the check as unrun rather than passed when this section runs. When
18
+ * Harper is not responding, the enclosing gate skips the section and doctor
19
+ * reports the server problem elsewhere.
20
+ */
21
+ import { isOpenLiveRow } from "./open-live-row.js";
22
+ export const SKILL_TOMBSTONE_VERSION_ROWS_SQL = "SELECT id, subjectType, subjectId, version, kind, rowId FROM flair.InstructionVersion WHERE subjectType = 'skill'";
23
+ export const SKILL_TOMBSTONE_MEMORY_ROWS_SQL = "SELECT id, skillSubjectId, validTo, archived, expiresAt FROM flair.Memory";
24
+ function versionSequence(value) {
25
+ if (typeof value === "bigint")
26
+ return value;
27
+ if (typeof value === "number")
28
+ return Number.isInteger(value) ? BigInt(value) : null;
29
+ if (typeof value === "string" && /^\d+$/.test(value))
30
+ return BigInt(value);
31
+ return null;
32
+ }
33
+ /** The skill writer's open-live predicate, applied to a row read from Memory. */
34
+ function memoryRowIsOpenLive(row) {
35
+ return isOpenLiveRow(row);
36
+ }
37
+ function rowIdOf(row) {
38
+ return typeof row.id === "string" && row.id.length > 0 ? row.id : null;
39
+ }
40
+ /**
41
+ * Every skill subject whose newest InstructionVersion is a `delete` tombstone
42
+ * and whose Memory row is still open-live, sorted by subject id. A closed,
43
+ * archived, expired or absent Memory row passes.
44
+ */
45
+ export function findLiveSkillTombstones(versions, memories) {
46
+ const heads = new Map();
47
+ for (const row of versions) {
48
+ if (!row || typeof row !== "object" || row.subjectType !== "skill")
49
+ continue;
50
+ if (typeof row.subjectId !== "string" || row.subjectId.length === 0)
51
+ continue;
52
+ const version = versionSequence(row.version);
53
+ if (version === null)
54
+ continue;
55
+ const current = heads.get(row.subjectId);
56
+ if (!current || version > current.version)
57
+ heads.set(row.subjectId, { version, row });
58
+ }
59
+ const liveRowIdBySubject = new Map();
60
+ const liveRowsById = new Map();
61
+ for (const memory of memories) {
62
+ if (!memory || typeof memory !== "object" || !memoryRowIsOpenLive(memory))
63
+ continue;
64
+ const id = rowIdOf(memory);
65
+ if (id === null)
66
+ continue;
67
+ liveRowsById.set(id, memory);
68
+ if (typeof memory.skillSubjectId !== "string")
69
+ continue;
70
+ const current = liveRowIdBySubject.get(memory.skillSubjectId);
71
+ if (current === undefined || id < current)
72
+ liveRowIdBySubject.set(memory.skillSubjectId, id);
73
+ }
74
+ const findings = [];
75
+ for (const [subjectId, { row }] of heads) {
76
+ if (row.kind !== "delete")
77
+ continue;
78
+ const tombstoneRowId = typeof row.rowId === "string" && row.rowId.length > 0 ? row.rowId : null;
79
+ let liveRowId = liveRowIdBySubject.get(subjectId);
80
+ if (tombstoneRowId !== null && liveRowsById.has(tombstoneRowId) &&
81
+ (liveRowId === undefined || tombstoneRowId < liveRowId))
82
+ liveRowId = tombstoneRowId;
83
+ if (liveRowId === undefined)
84
+ continue;
85
+ findings.push({
86
+ subjectId,
87
+ tombstoneId: rowIdOf(row) ?? "(no id)",
88
+ liveRowId,
89
+ });
90
+ }
91
+ return findings.sort((a, b) => (a.subjectId < b.subjectId ? -1 : a.subjectId > b.subjectId ? 1 : 0));
92
+ }
93
+ /** The doctor line for a live-tombstone set: null when the store is clean. */
94
+ export function describeLiveSkillTombstones(versions, memories) {
95
+ const findings = findLiveSkillTombstones(versions, memories);
96
+ if (findings.length === 0)
97
+ return null;
98
+ const rows = findings
99
+ .map(({ subjectId, tombstoneId, liveRowId }) => `${subjectId} (tombstone ${tombstoneId}, live row ${liveRowId})`)
100
+ .join(", ");
101
+ const noun = findings.length === 1 ? "subject" : "subjects";
102
+ const verb = findings.length === 1 ? "has" : "have";
103
+ return `${findings.length} skill ${noun} whose newest InstructionVersion is a delete tombstone still ${verb} an open-live Memory row: ${rows}`;
104
+ }
105
+ /** Read both tables through the ops API; null when either read fails. */
106
+ export async function readSkillTombstoneTables(args) {
107
+ const fetchImpl = args.fetchImpl ?? fetch;
108
+ const read = async (sql) => {
109
+ try {
110
+ const res = await fetchImpl(args.opsUrl, {
111
+ method: "POST",
112
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
113
+ body: JSON.stringify({ operation: "sql", sql }),
114
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
115
+ });
116
+ if (!res.ok)
117
+ return null;
118
+ const data = await res.json();
119
+ return Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ };
125
+ const versions = await read(SKILL_TOMBSTONE_VERSION_ROWS_SQL);
126
+ const memories = await read(SKILL_TOMBSTONE_MEMORY_ROWS_SQL);
127
+ if (versions === null || memories === null)
128
+ return null;
129
+ return {
130
+ versions: versions,
131
+ memories: memories,
132
+ };
133
+ }
@@ -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
+ }