@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.
- package/README.md +6 -6
- package/SECURITY.md +18 -10
- package/config.yaml +11 -11
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +66 -122
- package/dist/commands/agent.js +27 -65
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +37 -33
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/deploy.js +37 -7
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/export.js +3 -4
- package/dist/commands/federation.js +653 -68
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/idp.js +14 -19
- package/dist/commands/import.js +131 -19
- package/dist/commands/init.js +7 -7
- package/dist/commands/integrity.js +5 -6
- package/dist/commands/mcp.js +11 -17
- package/dist/commands/memory.js +33 -15
- package/dist/commands/orgevent.js +5 -10
- package/dist/commands/principal.js +13 -25
- package/dist/commands/quality.js +3 -0
- package/dist/commands/rem.js +484 -65
- package/dist/commands/restore.js +352 -44
- package/dist/commands/service.js +84 -2
- package/dist/commands/soul.js +0 -6
- package/dist/commands/status.js +51 -33
- package/dist/commands/test.js +4 -1
- package/dist/commands/upgrade.js +53 -22
- package/dist/commands/workspace.js +7 -8
- package/dist/deploy.js +59 -3
- package/dist/doctor-client.js +7 -2
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +269 -177
- package/dist/install/clients.js +171 -35
- package/dist/lib/agent-id-rule.js +44 -2
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1028 -52
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/daemon-liveness.js +2 -1
- package/dist/lib/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +14 -3
- package/dist/lib/mcp-enable.js +14 -15
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +1 -1
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed.js +91 -8
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/mcp-client-assertion.js +2 -10
- package/dist/memory-id-checkpoint.js +28 -7
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +302 -26
- package/dist/rem/runner.js +220 -58
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +155 -45
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +56 -22
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +232 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -84
- package/dist/resources/Credential.js +6 -8
- package/dist/resources/Federation.js +219 -57
- package/dist/resources/FederationRetry.js +4 -4
- package/dist/resources/InstructionVersion.js +1 -1
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +1303 -270
- package/dist/resources/MemoryArchive.js +149 -64
- package/dist/resources/MemoryBootstrap.js +12 -22
- package/dist/resources/MemoryCandidate.js +16 -2
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryFeed.js +360 -147
- package/dist/resources/MemoryMaintenance.js +290 -72
- package/dist/resources/MemoryPurge.js +138 -22
- package/dist/resources/MemoryReflect.js +68 -14
- package/dist/resources/MemoryReindex.js +91 -13
- package/dist/resources/Message.js +11 -2
- package/dist/resources/OAuth.js +156 -39
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +292 -29
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +31 -11
- package/dist/resources/PromoteMemoryCandidate.js +8 -2
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Soul.js +2 -0
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/XAA.js +36 -10
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +98 -68
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +166 -42
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/federation-classify.js +89 -0
- package/dist/resources/federation-retry-lib.js +6 -81
- package/dist/resources/health.js +43 -4
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instruction-version-record.js +251 -7
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/mcp-handler.js +106 -12
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +430 -53
- package/dist/resources/mcp-tools.js +60 -22
- package/dist/resources/memory-declared-attributes.js +1 -0
- package/dist/resources/memory-embed-hash.js +56 -0
- package/dist/resources/memory-host-source.js +5 -2
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-write-lock.js +202 -23
- package/dist/resources/memory-write-response.js +1 -1
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +16 -3
- package/dist/resources/migrations/dir-safety.js +60 -2
- package/dist/resources/migrations/embedding-stamp.js +315 -49
- package/dist/resources/migrations/graph-heal.js +9 -2
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +867 -80
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +78 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +111 -70
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +12 -5
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/owner-field-guard.js +1 -1
- package/dist/resources/owner-scoped-write-policy.js +65 -21
- package/dist/resources/owner-scoped-writes.js +37 -6
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +124 -33
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/request-target.js +28 -1
- package/dist/resources/request-transaction.js +11 -1
- package/dist/resources/seed-reservation.js +1 -2
- package/dist/resources/semantic-retrieval-core.js +7 -6
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +4 -3
- package/dist/resources/skill-version-write.js +384 -27
- package/dist/resources/skill-write-fault.js +6 -3
- package/dist/resources/skill-write-policy.js +2 -1
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +1 -1
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/txn-pause-point.js +122 -5
- package/dist/resources/usage-recording.js +54 -46
- package/dist/resources/write-back.js +176 -11
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/lib/agent-id-rule.js +44 -2
- package/dist/src/lib/atomic-write.js +1 -1
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +18 -9
- package/docs/api-reference.md +126 -28
- package/docs/auth.md +40 -18
- package/docs/claude-code.md +3 -3
- package/docs/deploying-on-fabric.md +108 -0
- package/docs/deployment.md +17 -0
- package/docs/embedding-in-a-harper-app.md +16 -14
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +29 -2
- package/docs/integrations.md +11 -11
- package/docs/mcp-clients.md +7 -5
- package/docs/notes/mcp-agent-auth-consumer.md +4 -9
- package/docs/notes/mcp-oauth-model2.md +6 -6
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +3 -3
- package/docs/releasing.md +13 -13
- package/docs/rem.md +24 -3
- package/docs/secrets-and-keys.md +2 -2
- package/docs/standalone-local.md +29 -2
- package/docs/supply-chain-policy.md +28 -20
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +14 -0
- package/package.json +18 -11
- package/schemas/agent.graphql +3 -3
- package/schemas/federation.graphql +10 -7
- package/schemas/memory.graphql +7 -2
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
package/dist/rem/restore.js
CHANGED
|
@@ -23,10 +23,37 @@
|
|
|
23
23
|
* Cross-agent restore is a 1.1+ feature.
|
|
24
24
|
*/
|
|
25
25
|
import { encodeRecordId } from "../lib/record-id-path.js";
|
|
26
|
+
import { suppliesSoulScopeFields } from "../lib/soul-scope-fields.js";
|
|
27
|
+
import { ApiHttpError, ApiRequestOutcomeUnknown } from "../lib/auth-resolve.js";
|
|
28
|
+
import { MEMORY_PROVIDER_RETRY_DELAY_MS, apiErrorCode, isProviderTimeoutRefusal, } from "../lib/memory-provider-timeout.js";
|
|
26
29
|
import { readFileSync, existsSync, rmSync, mkdtempSync } from "node:fs";
|
|
27
30
|
import { resolve } from "node:path";
|
|
28
31
|
import { tmpdir } from "node:os";
|
|
29
32
|
import { extractSnapshot, createSnapshot } from "./snapshot.js";
|
|
33
|
+
function delay(ms) {
|
|
34
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One line about an unknown-outcome id, from the post-restore read. Present
|
|
38
|
+
* does NOT mean restored: comparing ids alone cannot tell a row this restore
|
|
39
|
+
* wrote from a pre-existing row that already had the id.
|
|
40
|
+
*/
|
|
41
|
+
export function formatUnknownState(state) {
|
|
42
|
+
return state.present
|
|
43
|
+
? `${state.entity} ${state.id}: present in the verification read; an id-only check cannot tell whether this restore wrote the row or it was already present, so its state is unverified`
|
|
44
|
+
: `${state.entity} ${state.id}: absent from the verification read; the deadline fired before a complete response, so whether the write landed is unresolved and its state is unverified`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The server release that first serves `GET /AdminMemoryCandidates/{agentId}`. This is a server-capability
|
|
48
|
+
* minimum, not a package version, so its name does not end in "version": in the files it scans,
|
|
49
|
+
* check-version-sync treats a declaration whose identifier ends in "version" and holds the target release as
|
|
50
|
+
* a version site the release must bump.
|
|
51
|
+
*/
|
|
52
|
+
export const CANDIDATE_LIST_FIRST_SERVER_RELEASE = "0.63.0";
|
|
53
|
+
/** The page size restore asks the admin-only candidate route for. */
|
|
54
|
+
export const CANDIDATE_LIST_LIMIT = 500;
|
|
55
|
+
/** The most candidate-listing pages one restore requests before it refuses. */
|
|
56
|
+
export const CANDIDATE_LIST_MAX_PAGES = 2_000;
|
|
30
57
|
function asArray(raw) {
|
|
31
58
|
if (Array.isArray(raw))
|
|
32
59
|
return raw;
|
|
@@ -39,15 +66,136 @@ function asArray(raw) {
|
|
|
39
66
|
}
|
|
40
67
|
return [];
|
|
41
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* A live table listing for the pre-restore snapshot. Unlike `asArray`, which
|
|
71
|
+
* reads an unrecognised shape as an empty table, this refuses: an unreadable
|
|
72
|
+
* listing would look empty, so the pre-restore snapshot would miss the live
|
|
73
|
+
* rows, the scope preflight would see no live Souls, and the DELETE and PUT
|
|
74
|
+
* loops would run over a table this run never read (flair#2931).
|
|
75
|
+
*/
|
|
76
|
+
export function requireLiveListing(raw, table, agentId) {
|
|
77
|
+
if (Array.isArray(raw))
|
|
78
|
+
return raw;
|
|
79
|
+
if (raw && typeof raw === "object") {
|
|
80
|
+
const obj = raw;
|
|
81
|
+
if (Array.isArray(obj.results))
|
|
82
|
+
return obj.results;
|
|
83
|
+
if (Array.isArray(obj.items))
|
|
84
|
+
return obj.items;
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`live-listing-unreadable: GET /${table}?agentId=${agentId} returned a response that is not a list `
|
|
87
|
+
+ `(expected a JSON array, or an object with a "results" or "items" array); `
|
|
88
|
+
+ "refusing to restore until the live listing can be read — check the API response and that the agent id is correct.");
|
|
89
|
+
}
|
|
42
90
|
function soulWrite(opts) {
|
|
43
91
|
return opts.soulApiCall ?? opts.apiCall;
|
|
44
92
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Ids of Soul rows a whole-row replay would send that supply a non-empty
|
|
95
|
+
* `scopeTag` or `tags` array. The server refuses each such write (flair#1540),
|
|
96
|
+
* so a restore that deletes before writing one can leave a live row absent and
|
|
97
|
+
* a rollback to the pre-restore snapshot refused (flair#2931). Rows the DELETE
|
|
98
|
+
* and PUT loops skip (no usable id) are not written or deleted, so they are not
|
|
99
|
+
* checked here.
|
|
100
|
+
*/
|
|
101
|
+
function refusedSoulReplayIds(rows) {
|
|
102
|
+
const ids = [];
|
|
103
|
+
for (const row of rows) {
|
|
104
|
+
if (!row || typeof row !== "object" || Array.isArray(row) || !row.id)
|
|
105
|
+
continue;
|
|
106
|
+
if (suppliesSoulScopeFields(row))
|
|
107
|
+
ids.push(String(row.id));
|
|
108
|
+
}
|
|
109
|
+
return [...new Set(ids)];
|
|
110
|
+
}
|
|
111
|
+
function isCandidateRoute404(err) {
|
|
112
|
+
return err instanceof ApiHttpError && err.status === 404;
|
|
113
|
+
}
|
|
114
|
+
/** The refusal for a candidate listing restore could not read completely. */
|
|
115
|
+
function incompleteListing(agentId, state, remedy = "") {
|
|
116
|
+
return new Error(`the target's MemoryCandidate listing for agent ${agentId} could not be read completely: ${state}. `
|
|
117
|
+
+ `No target rows were deleted or written.${remedy ? ` ${remedy}` : ""}`);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* One agent's leftover candidates, read through the `apiCall` restore uses
|
|
121
|
+
* for its Memory reads, deletes and writes, its Soul reads and its
|
|
122
|
+
* MemoryCandidate deletes. Soul deletes and writes use `soulApiCall` when one
|
|
123
|
+
* is given; the CLI binds both calls to the same target. Each candidate object
|
|
124
|
+
* carries only an id; each reply also carries `hasMore`.
|
|
125
|
+
*
|
|
126
|
+
* Pages through the route with `after` set to the last id of the page before,
|
|
127
|
+
* until a page answers `hasMore: false`, and returns only that complete
|
|
128
|
+
* listing. A `hasMore: true` page with no candidates (the cursor cannot move),
|
|
129
|
+
* an id listed twice, or more than {@link CANDIDATE_LIST_MAX_PAGES} pages is
|
|
130
|
+
* refused.
|
|
131
|
+
*
|
|
132
|
+
* Exported for `flair restore --replace`, which lists the agent of each
|
|
133
|
+
* archived Soul row it will write a non-empty value for before any delete, so
|
|
134
|
+
* it can compare that agent's live candidate claims with the values it is
|
|
135
|
+
* about to write.
|
|
136
|
+
*/
|
|
137
|
+
export async function listAgentCandidates(apiCall, agentId) {
|
|
138
|
+
const listed = [];
|
|
139
|
+
const seen = new Set();
|
|
140
|
+
let after;
|
|
141
|
+
for (let page = 1; page <= CANDIDATE_LIST_MAX_PAGES; page++) {
|
|
142
|
+
const query = `?limit=${CANDIDATE_LIST_LIMIT}${after === undefined ? "" : `&after=${encodeURIComponent(after)}`}`;
|
|
143
|
+
let body;
|
|
144
|
+
try {
|
|
145
|
+
body = await apiCall("GET", `/AdminMemoryCandidates/${encodeURIComponent(agentId)}${query}`);
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
// Only this GET's 404 gets the candidate-route 404 guidance.
|
|
149
|
+
if (isCandidateRoute404(err))
|
|
150
|
+
throw new Error(candidateRoute404Guidance(err));
|
|
151
|
+
if (err instanceof ApiHttpError && apiErrorCode(err) === "candidate_id_unusable") {
|
|
152
|
+
throw incompleteListing(agentId, "GET /AdminMemoryCandidates answered candidate_id_unusable (a row has no usable id)", "Remove or repair that agent's MemoryCandidate row without a usable id on the target, then retry.");
|
|
153
|
+
}
|
|
154
|
+
throw incompleteListing(agentId, `GET /AdminMemoryCandidates failed: ${err?.message ?? String(err)}`);
|
|
155
|
+
}
|
|
156
|
+
const defect = candidateListDefect(body);
|
|
157
|
+
if (defect) {
|
|
158
|
+
throw incompleteListing(agentId, `GET /AdminMemoryCandidates returned an unexpected response shape: ${defect}`);
|
|
159
|
+
}
|
|
160
|
+
for (const entry of body.candidates) {
|
|
161
|
+
if (seen.has(entry.id)) {
|
|
162
|
+
throw incompleteListing(agentId, `GET /AdminMemoryCandidates listed candidate id ${entry.id} twice (candidate_id_repeated)`);
|
|
163
|
+
}
|
|
164
|
+
seen.add(entry.id);
|
|
165
|
+
listed.push({ id: entry.id });
|
|
166
|
+
}
|
|
167
|
+
if (body.hasMore === false)
|
|
168
|
+
return listed;
|
|
169
|
+
// A page that repeats the cursor's own id is refused above as a repeated id.
|
|
170
|
+
const last = body.candidates.at(-1)?.id;
|
|
171
|
+
if (last === undefined) {
|
|
172
|
+
throw incompleteListing(agentId, `page ${page} of GET /AdminMemoryCandidates answered hasMore: true with no candidates, so the cursor cannot move past ${after === undefined ? "the start" : after} (candidate_cursor_not_advancing)`);
|
|
173
|
+
}
|
|
174
|
+
after = last;
|
|
175
|
+
}
|
|
176
|
+
throw incompleteListing(agentId, `GET /AdminMemoryCandidates still answered hasMore: true after ${CANDIDATE_LIST_MAX_PAGES} pages of ${CANDIDATE_LIST_LIMIT}, the most restore requests (candidate_listing_page_limit)`);
|
|
177
|
+
}
|
|
178
|
+
/** The first required field a candidate-route body lacks or mistypes, or null when `candidates` and `hasMore` check out. */
|
|
179
|
+
function candidateListDefect(body) {
|
|
180
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
181
|
+
return "the body is not an object";
|
|
182
|
+
if (!Array.isArray(body.candidates))
|
|
183
|
+
return "candidates is not an array";
|
|
184
|
+
for (const [i, entry] of body.candidates.entries()) {
|
|
185
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
186
|
+
return `candidates[${i}] is not an object`;
|
|
187
|
+
if (typeof entry.id !== "string" || entry.id.length === 0)
|
|
188
|
+
return `candidates[${i}].id is not a non-empty string`;
|
|
189
|
+
}
|
|
190
|
+
if (typeof body.hasMore !== "boolean")
|
|
191
|
+
return "hasMore is missing or not a boolean";
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
/** The candidate-route 404 guidance: the operator message when GET /AdminMemoryCandidates answers 404. */
|
|
195
|
+
function candidateRoute404Guidance(err) {
|
|
196
|
+
return `restore lists leftover MemoryCandidate rows through GET /AdminMemoryCandidates on the restore target, and the target answered HTTP ${err.status}. `
|
|
197
|
+
+ `That route is part of Flair server ${CANDIDATE_LIST_FIRST_SERVER_RELEASE}; if the target runs an older server, upgrade it to ${CANDIDATE_LIST_FIRST_SERVER_RELEASE} or newer, then retry. `
|
|
198
|
+
+ "No target rows were deleted or written.";
|
|
51
199
|
}
|
|
52
200
|
function parseJsonlSafe(text) {
|
|
53
201
|
if (!text.trim())
|
|
@@ -66,12 +214,15 @@ function parseJsonlSafe(text) {
|
|
|
66
214
|
* 3. Verify metadata.agentId matches opts.agentId (prevents accidental
|
|
67
215
|
* cross-agent restore — the file might have been hand-copied).
|
|
68
216
|
* 4. Create a pre-restore snapshot of current state (skip in dry-run).
|
|
217
|
+
* 4b. Refuse before any delete when a snapshot Soul row or a live Soul row
|
|
218
|
+
* captured in the pre-restore snapshot supplies scope fields (flair#2931).
|
|
69
219
|
* 5. Fetch + delete current memories/souls/candidates for the agent (skip in dry-run).
|
|
70
220
|
* 6. PUT snapshot souls, then memories (skip in dry-run).
|
|
71
221
|
* 7. Return counts.
|
|
72
222
|
*
|
|
73
223
|
* On any error after step 4: the result reports `status: "failed"` with
|
|
74
|
-
* the pre-restore snapshot path included so the operator can roll back.
|
|
224
|
+
* the pre-restore snapshot path included so the operator can roll back. If any
|
|
225
|
+
* write's outcome is unknown, the status is `unresolved` instead.
|
|
75
226
|
*/
|
|
76
227
|
export async function applySnapshot(opts) {
|
|
77
228
|
const errors = [];
|
|
@@ -81,8 +232,17 @@ export async function applySnapshot(opts) {
|
|
|
81
232
|
snapshotPath: opts.snapshotPath,
|
|
82
233
|
deleted: { memories: 0, souls: 0, candidates: 0 },
|
|
83
234
|
restored: { memories: 0, souls: 0 },
|
|
235
|
+
retried: { memories: [] },
|
|
236
|
+
unknown: { memories: [], souls: [], candidates: [] },
|
|
237
|
+
skippedAfterUnknownDelete: { memories: [], souls: [] },
|
|
84
238
|
errors,
|
|
85
239
|
};
|
|
240
|
+
if (!opts.dryRun && opts.listCandidates === false) {
|
|
241
|
+
errors.push("listCandidates: false is accepted only with dryRun: a live restore lists leftover MemoryCandidate rows before any delete. "
|
|
242
|
+
+ "No request was sent to the target.");
|
|
243
|
+
result.status = "failed";
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
86
246
|
if (!existsSync(opts.snapshotPath)) {
|
|
87
247
|
errors.push(`snapshot does not exist: ${opts.snapshotPath}`);
|
|
88
248
|
result.status = "failed";
|
|
@@ -141,7 +301,9 @@ export async function applySnapshot(opts) {
|
|
|
141
301
|
try {
|
|
142
302
|
const currentMem = asArray(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`));
|
|
143
303
|
const currentSouls = asArray(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`));
|
|
144
|
-
const currentCandidates =
|
|
304
|
+
const currentCandidates = opts.listCandidates === false
|
|
305
|
+
? []
|
|
306
|
+
: await listAgentCandidates(opts.apiCall, opts.agentId);
|
|
145
307
|
result.deleted.memories = currentMem.length;
|
|
146
308
|
result.deleted.souls = currentSouls.length;
|
|
147
309
|
result.deleted.candidates = currentCandidates.length;
|
|
@@ -160,14 +322,14 @@ export async function applySnapshot(opts) {
|
|
|
160
322
|
let currentMem;
|
|
161
323
|
let currentSouls;
|
|
162
324
|
try {
|
|
163
|
-
currentMem =
|
|
164
|
-
currentSouls =
|
|
325
|
+
currentMem = requireLiveListing(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`), "Memory", opts.agentId);
|
|
326
|
+
currentSouls = requireLiveListing(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`), "Soul", opts.agentId);
|
|
165
327
|
const preRestore = await createSnapshot({
|
|
166
328
|
agentId: opts.agentId,
|
|
167
329
|
flairVersion: opts.flairVersion,
|
|
168
330
|
memories: currentMem,
|
|
169
331
|
soul: currentSouls.length === 1 ? currentSouls[0] : currentSouls.length > 1 ? currentSouls : null,
|
|
170
|
-
pendingCandidateCount:
|
|
332
|
+
pendingCandidateCount: null, // not counted at restore time (flair#2680)
|
|
171
333
|
rootOverride: opts.preRestoreSnapshotRoot,
|
|
172
334
|
runId: `rem-restore-pre-${(opts.nowOverride ?? new Date()).toISOString().replace(/[:.]/g, "-")}`,
|
|
173
335
|
nowOverride: opts.nowOverride,
|
|
@@ -180,46 +342,112 @@ export async function applySnapshot(opts) {
|
|
|
180
342
|
rmSync(tmp, { recursive: true, force: true });
|
|
181
343
|
return result;
|
|
182
344
|
}
|
|
345
|
+
// 4b. Scope-field preflight (flair#2931), before any DELETE: refuse when a
|
|
346
|
+
// snapshot Soul row this run would PUT, or a live Soul row captured in the
|
|
347
|
+
// pre-restore snapshot, supplies a non-empty `scopeTag` or `tags` array.
|
|
348
|
+
// The server refuses that write, so the replay cannot restore the row. When
|
|
349
|
+
// the row is live, deleting it first also makes the pre-restore rollback
|
|
350
|
+
// refuse it. Merge mode does not exist here; this restore always replaces
|
|
351
|
+
// the agent's rows.
|
|
352
|
+
const snapshotRefusedSouls = new Set(refusedSoulReplayIds(souls));
|
|
353
|
+
const liveRefusedSouls = new Set(refusedSoulReplayIds(currentSouls));
|
|
354
|
+
const refusedSouls = [...new Set([...snapshotRefusedSouls, ...liveRefusedSouls])];
|
|
355
|
+
if (refusedSouls.length > 0) {
|
|
356
|
+
for (const id of refusedSouls) {
|
|
357
|
+
const inSnapshot = snapshotRefusedSouls.has(id);
|
|
358
|
+
const inLive = liveRefusedSouls.has(id);
|
|
359
|
+
const source = inSnapshot && inLive
|
|
360
|
+
? "in the snapshot row and the live row"
|
|
361
|
+
: inSnapshot ? "in the snapshot row" : "in the live row";
|
|
362
|
+
const remedies = [];
|
|
363
|
+
if (inSnapshot)
|
|
364
|
+
remedies.push("Restore from a different snapshot, or edit that row in the snapshot file, then re-run.");
|
|
365
|
+
if (inLive) {
|
|
366
|
+
remedies.push(inSnapshot
|
|
367
|
+
? "Clear tags/scopeTag on the live row (PATCH) or delete it, then re-run."
|
|
368
|
+
: "Clear tags/scopeTag on that row (PATCH) or delete it, then re-run.");
|
|
369
|
+
}
|
|
370
|
+
errors.push(`soul-scope-preflight: Soul ${id} supplies a non-empty scopeTag or tags array ${source}, `
|
|
371
|
+
+ `which the Soul scope-field rule refuses; no target rows were deleted or written. ${remedies.join(" ")}`);
|
|
372
|
+
}
|
|
373
|
+
result.status = "failed";
|
|
374
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
375
|
+
return result;
|
|
376
|
+
}
|
|
183
377
|
// 5. Delete current memories, souls, and leftover candidates. Candidates
|
|
184
378
|
// are not in the snapshot, but refuseLearnedSoulWrite matches claim text,
|
|
185
|
-
// so a leftover row 403s Soul PUT after operator auth succeeds.
|
|
186
|
-
|
|
379
|
+
// so a leftover row 403s Soul PUT after operator auth succeeds. A failed
|
|
380
|
+
// candidate listing stops the restore before any delete.
|
|
381
|
+
let currentCandidates;
|
|
187
382
|
try {
|
|
188
|
-
currentCandidates = await listAgentCandidates(opts.
|
|
383
|
+
currentCandidates = await listAgentCandidates(opts.apiCall, opts.agentId);
|
|
189
384
|
}
|
|
190
385
|
catch (err) {
|
|
191
386
|
errors.push(`fetch-candidates: ${err?.message ?? String(err)}`);
|
|
387
|
+
result.status = "failed";
|
|
388
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
389
|
+
return result;
|
|
192
390
|
}
|
|
391
|
+
// Ids whose write outcome is unknown, per table. Once a table and record id
|
|
392
|
+
// appears here, no later write to that same table and record id in this run
|
|
393
|
+
// is sent: a late write could land after the restored row.
|
|
394
|
+
const unknownMemoryWrites = new Set();
|
|
395
|
+
const unknownSoulWrites = new Set();
|
|
396
|
+
const unknownCandidateWrites = new Set();
|
|
193
397
|
for (const m of currentMem) {
|
|
194
398
|
if (!m?.id)
|
|
195
399
|
continue;
|
|
400
|
+
const id = String(m.id);
|
|
401
|
+
if (unknownMemoryWrites.has(id))
|
|
402
|
+
continue;
|
|
196
403
|
try {
|
|
197
|
-
await opts.apiCall("DELETE", `/Memory/${encodeRecordId(
|
|
404
|
+
await opts.apiCall("DELETE", `/Memory/${encodeRecordId(id)}`);
|
|
198
405
|
result.deleted.memories++;
|
|
199
406
|
}
|
|
200
407
|
catch (err) {
|
|
408
|
+
if (err instanceof ApiRequestOutcomeUnknown) {
|
|
409
|
+
result.unknown.memories.push(id);
|
|
410
|
+
unknownMemoryWrites.add(id);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
201
413
|
errors.push(`delete-memory ${m.id}: ${err?.message ?? String(err)}`);
|
|
202
414
|
}
|
|
203
415
|
}
|
|
204
416
|
for (const s of currentSouls) {
|
|
205
417
|
if (!s?.id)
|
|
206
418
|
continue;
|
|
419
|
+
const id = String(s.id);
|
|
420
|
+
if (unknownSoulWrites.has(id))
|
|
421
|
+
continue;
|
|
207
422
|
try {
|
|
208
|
-
await soulWrite(opts)("DELETE", `/Soul/${encodeRecordId(
|
|
423
|
+
await soulWrite(opts)("DELETE", `/Soul/${encodeRecordId(id)}`);
|
|
209
424
|
result.deleted.souls++;
|
|
210
425
|
}
|
|
211
426
|
catch (err) {
|
|
427
|
+
if (err instanceof ApiRequestOutcomeUnknown) {
|
|
428
|
+
result.unknown.souls.push(id);
|
|
429
|
+
unknownSoulWrites.add(id);
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
212
432
|
errors.push(`delete-soul ${s.id}: ${err?.message ?? String(err)}`);
|
|
213
433
|
}
|
|
214
434
|
}
|
|
215
435
|
for (const c of currentCandidates) {
|
|
216
436
|
if (!c?.id)
|
|
217
437
|
continue;
|
|
438
|
+
const id = String(c.id);
|
|
439
|
+
if (unknownCandidateWrites.has(id))
|
|
440
|
+
continue;
|
|
218
441
|
try {
|
|
219
|
-
await opts.apiCall("DELETE", `/MemoryCandidate/${encodeRecordId(
|
|
442
|
+
await opts.apiCall("DELETE", `/MemoryCandidate/${encodeRecordId(id)}`);
|
|
220
443
|
result.deleted.candidates++;
|
|
221
444
|
}
|
|
222
445
|
catch (err) {
|
|
446
|
+
if (err instanceof ApiRequestOutcomeUnknown) {
|
|
447
|
+
result.unknown.candidates.push(id);
|
|
448
|
+
unknownCandidateWrites.add(id);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
223
451
|
errors.push(`delete-candidate ${c.id}: ${err?.message ?? String(err)}`);
|
|
224
452
|
}
|
|
225
453
|
}
|
|
@@ -229,30 +457,70 @@ export async function applySnapshot(opts) {
|
|
|
229
457
|
for (const s of souls) {
|
|
230
458
|
if (!s?.id)
|
|
231
459
|
continue;
|
|
460
|
+
const id = String(s.id);
|
|
461
|
+
if (unknownSoulWrites.has(id)) {
|
|
462
|
+
result.skippedAfterUnknownDelete.souls.push(id);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
232
465
|
try {
|
|
233
|
-
await soulWrite(opts)("PUT", `/Soul/${encodeRecordId(
|
|
466
|
+
await soulWrite(opts)("PUT", `/Soul/${encodeRecordId(id)}`, s);
|
|
234
467
|
result.restored.souls++;
|
|
235
468
|
}
|
|
236
469
|
catch (err) {
|
|
470
|
+
if (err instanceof ApiRequestOutcomeUnknown) {
|
|
471
|
+
result.unknown.souls.push(id);
|
|
472
|
+
unknownSoulWrites.add(id);
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
237
475
|
errors.push(`put-soul ${s.id}: ${err?.message ?? String(err)}`);
|
|
238
476
|
}
|
|
239
477
|
}
|
|
240
478
|
for (const m of memories) {
|
|
241
479
|
if (!m?.id)
|
|
242
480
|
continue;
|
|
481
|
+
const id = String(m.id);
|
|
482
|
+
if (unknownMemoryWrites.has(id)) {
|
|
483
|
+
result.skippedAfterUnknownDelete.memories.push(id);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
243
486
|
try {
|
|
244
|
-
|
|
487
|
+
try {
|
|
488
|
+
await opts.apiCall("PUT", `/Memory/${encodeRecordId(id)}`, m);
|
|
489
|
+
}
|
|
490
|
+
catch (err) {
|
|
491
|
+
// A write whose outcome is unknown may have committed, so it is
|
|
492
|
+
// recorded as unknown by the outer catch and never replayed.
|
|
493
|
+
if (err instanceof ApiRequestOutcomeUnknown)
|
|
494
|
+
throw err;
|
|
495
|
+
// The write-lock contract states a provider-bound refusal wrote
|
|
496
|
+
// nothing, so replaying this one PUT cannot double-write the row.
|
|
497
|
+
if (!isProviderTimeoutRefusal(err))
|
|
498
|
+
throw err;
|
|
499
|
+
result.retried.memories.push(id);
|
|
500
|
+
await delay(MEMORY_PROVIDER_RETRY_DELAY_MS);
|
|
501
|
+
// No client-side timer here: a request abandoned at a client deadline
|
|
502
|
+
// could still commit after this row was recorded failed. The whole
|
|
503
|
+
// request now carries the shared deadline, and its expiry is an
|
|
504
|
+
// ApiRequestOutcomeUnknown recorded as unknown by the outer catch.
|
|
505
|
+
await opts.apiCall("PUT", `/Memory/${encodeRecordId(id)}`, m);
|
|
506
|
+
}
|
|
245
507
|
result.restored.memories++;
|
|
246
508
|
}
|
|
247
509
|
catch (err) {
|
|
248
|
-
|
|
510
|
+
if (err instanceof ApiRequestOutcomeUnknown) {
|
|
511
|
+
result.unknown.memories.push(id);
|
|
512
|
+
unknownMemoryWrites.add(id);
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
errors.push(`put-memory ${id}: ${err?.message ?? String(err)}`);
|
|
249
516
|
}
|
|
250
517
|
}
|
|
251
518
|
// 7. Verify post-restore state (default on; opt-out via verifyPostRestore=false).
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
//
|
|
255
|
-
//
|
|
519
|
+
// Compares Memory and Soul ids only; candidates are not read back. When
|
|
520
|
+
// both reads succeed, it reports snapshot ids missing from the agent's rows
|
|
521
|
+
// and ids present that the snapshot does not hold; row content is not
|
|
522
|
+
// compared. Per-ID diff, not just counts — count parity can hide
|
|
523
|
+
// simultaneous PUT+DELETE failures that wash out numerically.
|
|
256
524
|
if (opts.verifyPostRestore !== false) {
|
|
257
525
|
try {
|
|
258
526
|
const verifyMem = asArray(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`));
|
|
@@ -265,10 +533,14 @@ export async function applySnapshot(opts) {
|
|
|
265
533
|
const expSoul = new Set(expectedSoulIds);
|
|
266
534
|
const actMem = new Set(actualMemoryIds);
|
|
267
535
|
const actSoul = new Set(actualSoulIds);
|
|
268
|
-
const missingMemoryIds = [...expMem].filter((id) => !actMem.has(id));
|
|
269
|
-
const missingSoulIds = [...expSoul].filter((id) => !actSoul.has(id));
|
|
536
|
+
const missingMemoryIds = [...expMem].filter((id) => !actMem.has(id) && !result.unknown.memories.includes(id));
|
|
537
|
+
const missingSoulIds = [...expSoul].filter((id) => !actSoul.has(id) && !result.unknown.souls.includes(id));
|
|
270
538
|
const extraMemoryIds = [...actMem].filter((id) => !expMem.has(id));
|
|
271
539
|
const extraSoulIds = [...actSoul].filter((id) => !expSoul.has(id));
|
|
540
|
+
const unknownStates = [
|
|
541
|
+
...result.unknown.memories.map((id) => ({ entity: "memory", id, present: actMem.has(id) })),
|
|
542
|
+
...result.unknown.souls.map((id) => ({ entity: "soul", id, present: actSoul.has(id) })),
|
|
543
|
+
];
|
|
272
544
|
result.verified = {
|
|
273
545
|
expectedMemoryIds,
|
|
274
546
|
expectedSoulIds,
|
|
@@ -278,6 +550,7 @@ export async function applySnapshot(opts) {
|
|
|
278
550
|
missingSoulIds,
|
|
279
551
|
extraMemoryIds,
|
|
280
552
|
extraSoulIds,
|
|
553
|
+
unknownStates,
|
|
281
554
|
};
|
|
282
555
|
if (missingMemoryIds.length > 0) {
|
|
283
556
|
errors.push(`post-restore-verify: ${missingMemoryIds.length} memory rows missing (e.g. ${missingMemoryIds.slice(0, 3).join(", ")})`);
|
|
@@ -300,5 +573,8 @@ export async function applySnapshot(opts) {
|
|
|
300
573
|
if (errors.length > 0) {
|
|
301
574
|
result.status = "failed";
|
|
302
575
|
}
|
|
576
|
+
if (result.unknown.memories.length > 0 || result.unknown.souls.length > 0 || result.unknown.candidates.length > 0) {
|
|
577
|
+
result.status = "unresolved";
|
|
578
|
+
}
|
|
303
579
|
return result;
|
|
304
580
|
}
|