@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
@@ -0,0 +1,760 @@
1
+ /**
2
+ * restore-archive.ts — admission checks for a `flair backup` archive
3
+ * (flair#2664 slice 1a).
4
+ *
5
+ * Pure: no I/O, no Harper, no network, no writes. A restore path hands this
6
+ * module an archive's exact bytes and gets back either a validated archive or
7
+ * a named refusal. `flair restore` runs parseRestoreArchive in its preflight
8
+ * (src/lib/backup-artifact.ts readBackupArtifact); it does not call the
9
+ * Memory admission checks below.
10
+ *
11
+ * One buffer. `parseRestoreArchive` copies its input once, hashes that copy
12
+ * (SHA-256, lowercase hex), decodes the same copy as strict UTF-8 and parses
13
+ * the decoded text exactly once. The returned digest is the digest of the
14
+ * bytes the returned archive was parsed from.
15
+ *
16
+ * Strict JSON. `parseStrictJson` accepts the RFC 8259 grammar JSON.parse
17
+ * accepts and builds the same value, except that an object naming one key
18
+ * twice, at any depth, is refused instead of keeping the last value. Keys are
19
+ * compared after escape decoding, so `"a"` and `"\u0061"` are the same key.
20
+ * The parser is iterative, so nesting depth does not bound it.
21
+ *
22
+ * Archive shape: the row checks `flair restore` applied inline before it
23
+ * used this parser (flair#2664 slice 1b) plus unique ids within each
24
+ * collection, over the document `flair backup` writes (src/commands/backup.ts).
25
+ *
26
+ * Schema admission (flair#2953): a row of a table restore writes is also
27
+ * checked against that table's GraphQL schema (schemas/*.graphql). A `!`
28
+ * column the row does not hold is refused, except a field the write supplies
29
+ * itself (RESTORE_WRITE_SUPPLIED_FIELDS: Agent copies createdAt and publicKey
30
+ * from the stored row and refuses when no stored row exists);
31
+ * every present non-null held column must hold the JS value its declared type
32
+ * names. Admission runs before any delete. After admission and preflight,
33
+ * a non-dry-run replace attempts the archived Memory DELETEs and, only if that
34
+ * stage completes without failure, the archived Soul DELETEs. A failed Soul
35
+ * DELETE is recorded and that row's PUT still runs.
36
+ *
37
+ * Archive diagnostics. `parseRestoreArchive` returns the first problem it
38
+ * finds as one refusal with a JSON Pointer `location`. Decoding and JSON-syntax
39
+ * refusals (`invalid-utf8`, `invalid-json`, `duplicate-key`) also carry a byte
40
+ * `offset` into the input; archive-shape refusals carry a location only.
41
+ * `parseStrictJson` reports a UTF-16 `index` into the decoded text, which
42
+ * `parseRestoreArchive` converts to that byte offset.
43
+ *
44
+ * Memory admission: `validateRestoreSelection` checks every selected row's
45
+ * content, and its promotion fields when present, against the binding readers
46
+ * enforce (resources/promotion-binding.ts). The binding hash comes from
47
+ * src/lib/promotion-content-hash.ts, the CLI-side implementation of the
48
+ * server's algorithm; a parity test pins the two together, because a resource
49
+ * may statically import only dependency-free `src/` helpers (flair#1775). It
50
+ * returns either every selected entry validated or a refusal; it
51
+ * never returns part of a selection. The refusal lists every unresolvable id
52
+ * and every failing row, with two single-problem cases: a malformed selection
53
+ * (not an array, empty, or an entry that is not a non-empty string) refuses as
54
+ * `invalid-selection` with no per-id failures, before any id is resolved; and a
55
+ * row whose shape is not restorable (not an object, or no usable id or
56
+ * agentId) reports that one `invalid-row` failure and is not checked further.
57
+ */
58
+ import { createHash } from "node:crypto";
59
+ import { promotionContentHash } from "./promotion-content-hash.js";
60
+ import { encodeRecordId } from "./record-id-path.js";
61
+ /** The archive format version `flair backup` writes. */
62
+ export const RESTORE_ARCHIVE_VERSION = 1;
63
+ /** The `Memory.promotionStatus` values schemas/memory.graphql declares. An
64
+ * absent or null status means the row carries no verdict. */
65
+ export const MEMORY_PROMOTION_STATUSES = Object.freeze(["pending", "approved", "rejected"]);
66
+ /** The archive collections, the table each restores into, and whether its rows
67
+ * carry an owning `agentId` — in `flair restore`'s order. */
68
+ const COLLECTIONS = [
69
+ { key: "agents", table: "Agent", owned: false },
70
+ { key: "souls", table: "Soul", owned: true },
71
+ { key: "memories", table: "Memory", owned: true },
72
+ ];
73
+ /**
74
+ * Every column of each table restore writes, in schema order, with the type
75
+ * and requiredness `schemas/agent.graphql` and `schemas/memory.graphql`
76
+ * declare. A hand table, like DECLARED_MEMORY_ATTRIBUTES: the CLI does not read
77
+ * the schema files at runtime. test/unit/restore-soul-admission-2953.test.ts
78
+ * reads each `type <Table> @table { … }` body as a token stream and pins this
79
+ * table to it; a field the parser cannot read fails there, naming the line.
80
+ */
81
+ export const RESTORE_TABLE_FIELDS = Object.freeze({
82
+ Agent: Object.freeze({
83
+ id: { type: "ID", required: false }, name: { type: "String", required: true },
84
+ role: { type: "String", required: false }, type: { type: "String", required: false },
85
+ kind: { type: "String", required: false }, displayName: { type: "String", required: false },
86
+ status: { type: "String", required: false }, publicKey: { type: "String", required: true },
87
+ defaultTrustTier: { type: "String", required: false }, admin: { type: "Boolean", required: false },
88
+ runtime: { type: "String", required: false }, runtimeEndpoint: { type: "String", required: false },
89
+ subjects: { type: "String[]", required: false }, createdAt: { type: "String", required: true },
90
+ updatedAt: { type: "String", required: false }, originatorInstanceId: { type: "String", required: false },
91
+ }),
92
+ Soul: Object.freeze({
93
+ id: { type: "ID", required: false }, agentId: { type: "String", required: true },
94
+ key: { type: "String", required: true }, value: { type: "String", required: true },
95
+ priority: { type: "String", required: false }, metadata: { type: "String", required: false },
96
+ provenance: { type: "String", required: false }, durability: { type: "String", required: false },
97
+ createdAt: { type: "String", required: true }, updatedAt: { type: "String", required: false },
98
+ originatorInstanceId: { type: "String", required: false },
99
+ }),
100
+ Memory: Object.freeze({
101
+ id: { type: "ID", required: false }, agentId: { type: "String", required: true },
102
+ content: { type: "String", required: true }, contentHash: { type: "String", required: false },
103
+ trigger: { type: "String", required: false }, visibility: { type: "String", required: false },
104
+ embedding: { type: "Float[]", required: false }, embeddingModel: { type: "String", required: false },
105
+ embeddedContentHash: { type: "String", required: false }, tags: { type: "String[]", required: false },
106
+ durability: { type: "String", required: false }, source: { type: "String", required: false },
107
+ type: { type: "String", required: false }, createdAt: { type: "String", required: true },
108
+ updatedAt: { type: "String", required: false }, instanceToken: { type: "String", required: false },
109
+ expiresAt: { type: "String", required: false }, retrievalCount: { type: "Int", required: false },
110
+ lastRetrieved: { type: "String", required: false }, usageCount: { type: "Int", required: false },
111
+ writeBackWriteId: { type: "String", required: false }, promotionStatus: { type: "String", required: false },
112
+ promotedAt: { type: "String", required: false }, promotedBy: { type: "String", required: false },
113
+ promotionContentHash: { type: "String", required: false }, archived: { type: "Boolean", required: false },
114
+ archivedAt: { type: "String", required: false }, archivedBy: { type: "String", required: false },
115
+ parentId: { type: "String", required: false }, derivedFrom: { type: "String[]", required: false },
116
+ sessionId: { type: "String", required: false }, lastReflected: { type: "String", required: false },
117
+ supersedes: { type: "String", required: false }, subject: { type: "String", required: false },
118
+ summary: { type: "String", required: false }, validFrom: { type: "String", required: false },
119
+ validTo: { type: "String", required: false }, _safetyFlags: { type: "String[]", required: false },
120
+ provenance: { type: "String", required: false }, originatorInstanceId: { type: "String", required: false },
121
+ metadata: { type: "String", required: false }, entities: { type: "String[]", required: false },
122
+ skillSubjectId: { type: "String", required: false },
123
+ }),
124
+ });
125
+ /**
126
+ * Required columns the write supplies, so an archived row may omit them:
127
+ * The admission test pins assignment on every path to Soul's validate,
128
+ * Agent's super.put or Memory's content table PUT through putLocked, plus
129
+ * Agent's stored-field copies and refusal when no stored row exists.
130
+ */
131
+ export const RESTORE_WRITE_SUPPLIED_FIELDS = Object.freeze({
132
+ Agent: new Set(["createdAt", "publicKey"]),
133
+ Soul: new Set(["createdAt"]),
134
+ Memory: new Set(["createdAt"]),
135
+ });
136
+ // ─── Shared helpers ──────────────────────────────────────────────────────────
137
+ function isRecord(value) {
138
+ return value !== null && typeof value === "object" && !Array.isArray(value);
139
+ }
140
+ /** An own property's value; an inherited property reads as absent. */
141
+ function ownValue(record, key) {
142
+ return Object.hasOwn(record, key) ? record[key] : undefined;
143
+ }
144
+ function escapePointer(segment) {
145
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
146
+ }
147
+ // ─── Strict JSON ─────────────────────────────────────────────────────────────
148
+ const QUOTE = 0x22;
149
+ const BACKSLASH = 0x5c;
150
+ const COMMA = 0x2c;
151
+ const COLON = 0x3a;
152
+ const LBRACE = 0x7b;
153
+ const RBRACE = 0x7d;
154
+ const LBRACKET = 0x5b;
155
+ const RBRACKET = 0x5d;
156
+ const NUMBER_TOKEN = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
157
+ const HEX4 = /^[0-9a-fA-F]{4}$/;
158
+ const SIMPLE_ESCAPES = new Map([
159
+ [0x22, "\""], [0x5c, "\\"], [0x2f, "/"], [0x62, "\b"],
160
+ [0x66, "\f"], [0x6e, "\n"], [0x72, "\r"], [0x74, "\t"],
161
+ ]);
162
+ class StrictJsonRefused extends Error {
163
+ code;
164
+ reason;
165
+ location;
166
+ index;
167
+ constructor(code, reason, location, index) {
168
+ super(reason);
169
+ this.code = code;
170
+ this.reason = reason;
171
+ this.location = location;
172
+ this.index = index;
173
+ }
174
+ }
175
+ /** Define an own data property, as JSON.parse does: `__proto__` stays a key. */
176
+ function defineMember(target, key, value) {
177
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
178
+ }
179
+ class StrictJsonParser {
180
+ text;
181
+ stack = [];
182
+ i = 0;
183
+ constructor(text) {
184
+ this.text = text;
185
+ }
186
+ parse() {
187
+ const { stack, text } = this;
188
+ for (;;) {
189
+ // Read one value, or open a container and continue with its first member.
190
+ let value;
191
+ this.skipWhitespace();
192
+ const c = text.charCodeAt(this.i);
193
+ if (c === LBRACE) {
194
+ const frame = { kind: "object", value: {}, pointer: this.childPointer(), keys: new Set(), key: "" };
195
+ this.i++;
196
+ this.skipWhitespace();
197
+ if (text.charCodeAt(this.i) !== RBRACE) {
198
+ stack.push(frame);
199
+ this.readKey(frame);
200
+ continue;
201
+ }
202
+ this.i++;
203
+ value = frame.value;
204
+ }
205
+ else if (c === LBRACKET) {
206
+ const frame = { kind: "array", value: [], pointer: this.childPointer() };
207
+ this.i++;
208
+ this.skipWhitespace();
209
+ if (text.charCodeAt(this.i) !== RBRACKET) {
210
+ stack.push(frame);
211
+ continue;
212
+ }
213
+ this.i++;
214
+ value = frame.value;
215
+ }
216
+ else {
217
+ value = this.readScalar(c);
218
+ }
219
+ // Attach the completed value, then close every container it completes.
220
+ for (;;) {
221
+ const top = stack[stack.length - 1];
222
+ if (top === undefined) {
223
+ this.skipWhitespace();
224
+ if (this.i < text.length)
225
+ throw this.refuse("unexpected data after the JSON document", "");
226
+ return value;
227
+ }
228
+ if (top.kind === "array")
229
+ top.value.push(value);
230
+ else
231
+ defineMember(top.value, top.key, value);
232
+ this.skipWhitespace();
233
+ const d = text.charCodeAt(this.i);
234
+ if (d === COMMA) {
235
+ this.i++;
236
+ if (top.kind === "object") {
237
+ this.skipWhitespace();
238
+ this.readKey(top);
239
+ }
240
+ break;
241
+ }
242
+ if (d === (top.kind === "array" ? RBRACKET : RBRACE)) {
243
+ this.i++;
244
+ stack.pop();
245
+ value = top.value;
246
+ continue;
247
+ }
248
+ throw this.refuse(top.kind === "array" ? "expected ',' or ']' after an array element" : "expected ',' or '}' after an object member", top.pointer);
249
+ }
250
+ }
251
+ }
252
+ refuse(reason, location, code = "invalid-json") {
253
+ return new StrictJsonRefused(code, reason, location, this.i);
254
+ }
255
+ skipWhitespace() {
256
+ const { text } = this;
257
+ for (;;) {
258
+ const c = text.charCodeAt(this.i);
259
+ if (c !== 0x20 && c !== 0x0a && c !== 0x0d && c !== 0x09)
260
+ return;
261
+ this.i++;
262
+ }
263
+ }
264
+ /** The pointer of the value about to be read inside the innermost container. */
265
+ childPointer() {
266
+ const top = this.stack[this.stack.length - 1];
267
+ if (top === undefined)
268
+ return "";
269
+ return `${top.pointer}/${escapePointer(top.kind === "array" ? String(top.value.length) : top.key)}`;
270
+ }
271
+ /** Read `"key" :` and refuse a key this object already holds. */
272
+ readKey(frame) {
273
+ if (this.text.charCodeAt(this.i) !== QUOTE)
274
+ throw this.refuse("expected a string object key", frame.pointer);
275
+ const start = this.i;
276
+ const key = this.readString(frame.pointer);
277
+ const location = `${frame.pointer}/${escapePointer(key)}`;
278
+ if (frame.keys.has(key)) {
279
+ this.i = start;
280
+ throw this.refuse(`duplicate object key ${JSON.stringify(key)}`, location, "duplicate-key");
281
+ }
282
+ frame.keys.add(key);
283
+ frame.key = key;
284
+ this.skipWhitespace();
285
+ if (this.text.charCodeAt(this.i) !== COLON)
286
+ throw this.refuse("expected ':' after an object key", location);
287
+ this.i++;
288
+ }
289
+ readScalar(c) {
290
+ const { text } = this;
291
+ const location = this.childPointer();
292
+ if (c === QUOTE)
293
+ return this.readString(location);
294
+ if (c === 0x74 && text.startsWith("true", this.i)) {
295
+ this.i += 4;
296
+ return true;
297
+ }
298
+ if (c === 0x66 && text.startsWith("false", this.i)) {
299
+ this.i += 5;
300
+ return false;
301
+ }
302
+ if (c === 0x6e && text.startsWith("null", this.i)) {
303
+ this.i += 4;
304
+ return null;
305
+ }
306
+ if (c === 0x2d || (c >= 0x30 && c <= 0x39)) {
307
+ NUMBER_TOKEN.lastIndex = this.i;
308
+ const match = NUMBER_TOKEN.exec(text);
309
+ if (match === null)
310
+ throw this.refuse("invalid number", location);
311
+ this.i += match[0].length;
312
+ return Number(match[0]);
313
+ }
314
+ if (this.i >= text.length)
315
+ throw this.refuse("unexpected end of input", location);
316
+ if (this.i === 0 && c === 0xfeff)
317
+ throw this.refuse("the document begins with a byte order mark", location);
318
+ throw this.refuse("unexpected character", location);
319
+ }
320
+ /** Read a string token starting at its opening quote. */
321
+ readString(location) {
322
+ const { text } = this;
323
+ let i = this.i + 1;
324
+ let start = i;
325
+ let out = "";
326
+ for (;;) {
327
+ if (i >= text.length) {
328
+ this.i = i;
329
+ throw this.refuse("unterminated string", location);
330
+ }
331
+ const c = text.charCodeAt(i);
332
+ if (c === QUOTE) {
333
+ this.i = i + 1;
334
+ return out + text.slice(start, i);
335
+ }
336
+ if (c === BACKSLASH) {
337
+ out += text.slice(start, i);
338
+ const escape = text.charCodeAt(i + 1);
339
+ if (escape === 0x75) {
340
+ const hex = text.slice(i + 2, i + 6);
341
+ if (!HEX4.test(hex)) {
342
+ this.i = i;
343
+ throw this.refuse("invalid \\u escape", location);
344
+ }
345
+ out += String.fromCharCode(parseInt(hex, 16));
346
+ i += 6;
347
+ }
348
+ else {
349
+ const simple = SIMPLE_ESCAPES.get(escape);
350
+ if (simple === undefined) {
351
+ this.i = i;
352
+ throw this.refuse("invalid escape sequence", location);
353
+ }
354
+ out += simple;
355
+ i += 2;
356
+ }
357
+ start = i;
358
+ continue;
359
+ }
360
+ if (c < 0x20) {
361
+ this.i = i;
362
+ throw this.refuse("unescaped control character in a string", location);
363
+ }
364
+ i++;
365
+ }
366
+ }
367
+ }
368
+ /**
369
+ * Parse `text` as one JSON document. A valid document without a repeated key
370
+ * yields the value JSON.parse returns; a repeated key in any object refuses
371
+ * with `duplicate-key`, and any other grammar violation with `invalid-json`.
372
+ */
373
+ export function parseStrictJson(text) {
374
+ try {
375
+ return { ok: true, value: new StrictJsonParser(text).parse() };
376
+ }
377
+ catch (error) {
378
+ if (!(error instanceof StrictJsonRefused))
379
+ throw error;
380
+ return { ok: false, code: error.code, reason: error.reason, location: error.location, index: error.index };
381
+ }
382
+ }
383
+ // ─── Strict UTF-8 ────────────────────────────────────────────────────────────
384
+ function strictUtf8Decoder() {
385
+ // `ignoreBOM: true` keeps a leading byte order mark in the text, so the
386
+ // parser sees (and refuses) it rather than the decoder dropping bytes the
387
+ // digest covers.
388
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
389
+ }
390
+ /** The first byte offset the strict decoder refuses, or the input length when
391
+ * the input ends inside a multi-byte sequence. */
392
+ function illFormedUtf8Offset(bytes) {
393
+ const acceptsPrefix = (end) => {
394
+ try {
395
+ strictUtf8Decoder().decode(bytes.subarray(0, end), { stream: true });
396
+ return true;
397
+ }
398
+ catch (error) {
399
+ if (error instanceof TypeError)
400
+ return false;
401
+ throw error;
402
+ }
403
+ };
404
+ if (acceptsPrefix(bytes.length))
405
+ return bytes.length;
406
+ // acceptsPrefix(lo) holds and acceptsPrefix(hi) does not; a refused prefix
407
+ // stays refused when extended, so the boundary is the first refused byte.
408
+ let lo = 0;
409
+ let hi = bytes.length;
410
+ while (hi - lo > 1) {
411
+ const mid = lo + Math.floor((hi - lo) / 2);
412
+ if (acceptsPrefix(mid))
413
+ lo = mid;
414
+ else
415
+ hi = mid;
416
+ }
417
+ return hi - 1;
418
+ }
419
+ function decodeStrictUtf8(bytes) {
420
+ try {
421
+ return { ok: true, text: strictUtf8Decoder().decode(bytes) };
422
+ }
423
+ catch (error) {
424
+ if (!(error instanceof TypeError))
425
+ throw error;
426
+ const offset = illFormedUtf8Offset(bytes);
427
+ return {
428
+ ok: false,
429
+ offset,
430
+ reason: offset === bytes.length
431
+ ? "the input ends inside a multi-byte UTF-8 sequence"
432
+ : "the input is not well-formed UTF-8",
433
+ };
434
+ }
435
+ }
436
+ // ─── Archive shape ───────────────────────────────────────────────────────────
437
+ /** Why `row` is not a restorable row; `field` names the refused field. */
438
+ function rowShapeProblem(row, owned) {
439
+ if (!isRecord(row))
440
+ return { reason: "the row is not a JSON object" };
441
+ const id = ownValue(row, "id");
442
+ if (typeof id !== "string" || id.length === 0)
443
+ return { reason: "the row id is not a non-empty string", field: "id" };
444
+ if (id.includes(".")) {
445
+ return {
446
+ reason: "the row id contains \".\", which admission conservatively refuses because a suffix such as "
447
+ + "\".json\" or \".content\" can be read as a content type or an attribute selector",
448
+ field: "id",
449
+ };
450
+ }
451
+ try {
452
+ encodeRecordId(id);
453
+ }
454
+ catch {
455
+ return { reason: "the row id does not address exactly one record path segment", field: "id" };
456
+ }
457
+ if (owned) {
458
+ const agentId = ownValue(row, "agentId");
459
+ if (typeof agentId !== "string" || agentId.length === 0) {
460
+ return { reason: "the row agentId is not a non-empty string", field: "agentId" };
461
+ }
462
+ }
463
+ return undefined;
464
+ }
465
+ /** What a column of this type must hold, in words. */
466
+ function expectedValue(type) {
467
+ switch (type) {
468
+ case "ID": return "a string";
469
+ case "String": return "a string";
470
+ case "Int": return "an integer";
471
+ case "Float": return "a number";
472
+ case "Boolean": return "a boolean";
473
+ case "String[]": return "an array of strings";
474
+ case "Float[]": return "an array of numbers";
475
+ }
476
+ }
477
+ /** Whether `value` is the JS value a column of this type holds. */
478
+ function holdsColumnType(value, type) {
479
+ switch (type) {
480
+ case "ID": return typeof value === "string";
481
+ case "String": return typeof value === "string";
482
+ case "Int": return typeof value === "number" && Number.isInteger(value);
483
+ case "Float": return typeof value === "number" && Number.isFinite(value);
484
+ case "Boolean": return typeof value === "boolean";
485
+ case "String[]": return Array.isArray(value) && value.every((item) => typeof item === "string");
486
+ case "Float[]": return Array.isArray(value) && value.every((item) => typeof item === "number" && Number.isFinite(item));
487
+ }
488
+ }
489
+ /**
490
+ * Why `row` does not match the schema of the table restore writes it to;
491
+ * `field` names the refused column. A column the row does not hold is refused
492
+ * only when the schema marks it `!` and the write does not supply it; a column
493
+ * it holds must match the declared type. Null reads as absent.
494
+ */
495
+ function rowSchemaProblem(row, table) {
496
+ for (const [field, column] of Object.entries(RESTORE_TABLE_FIELDS[table])) {
497
+ const value = ownValue(row, field);
498
+ if (value === undefined || value === null) {
499
+ if (column.required && !RESTORE_WRITE_SUPPLIED_FIELDS[table].has(field)) {
500
+ return { reason: `the row has no ${field} (the schema requires ${column.type})`, field };
501
+ }
502
+ continue;
503
+ }
504
+ if (holdsColumnType(value, column.type))
505
+ continue;
506
+ return { reason: `the row ${field} is not ${expectedValue(column.type)} (the schema declares ${column.type})`, field };
507
+ }
508
+ return undefined;
509
+ }
510
+ function archiveShapeRefusal(doc) {
511
+ if (!isRecord(doc))
512
+ return { code: "invalid-archive", reason: "the archive is not a JSON object", location: "" };
513
+ if (ownValue(doc, "version") !== RESTORE_ARCHIVE_VERSION) {
514
+ return { code: "unsupported-version", reason: `the archive version is not ${RESTORE_ARCHIVE_VERSION}`, location: "/version" };
515
+ }
516
+ for (const { key, table, owned } of COLLECTIONS) {
517
+ const rows = ownValue(doc, key);
518
+ if (!Array.isArray(rows)) {
519
+ return { code: "invalid-collection", reason: `the ${key} collection is missing or not an array`, location: `/${key}` };
520
+ }
521
+ const seen = new Map();
522
+ for (let index = 0; index < rows.length; index++) {
523
+ const row = rows[index];
524
+ const problem = rowShapeProblem(row, owned)
525
+ ?? rowSchemaProblem(row, table);
526
+ if (problem) {
527
+ return {
528
+ code: "invalid-row",
529
+ reason: `${table} row ${index}: ${problem.reason}`,
530
+ location: problem.field === undefined ? `/${key}/${index}` : `/${key}/${index}/${problem.field}`,
531
+ };
532
+ }
533
+ const id = row.id;
534
+ const first = seen.get(id);
535
+ if (first !== undefined) {
536
+ return {
537
+ code: "duplicate-id",
538
+ reason: `${table} id ${JSON.stringify(id)} appears more than once (first at /${key}/${first})`,
539
+ location: `/${key}/${index}/id`,
540
+ };
541
+ }
542
+ seen.set(id, index);
543
+ }
544
+ }
545
+ return undefined;
546
+ }
547
+ /**
548
+ * Hash, decode and parse one archive buffer. The input is copied once; the
549
+ * SHA-256 digest and the parse both read that copy. Refuses ill-formed UTF-8,
550
+ * a leading byte order mark, invalid JSON, a repeated object key at any depth,
551
+ * a version other than 1, a missing or non-array `agents`, `souls` or
552
+ * `memories` collection, a row that is not an object with a non-empty string
553
+ * id containing no `.` (Soul and Memory rows also need a non-empty string
554
+ * `agentId`), a row whose held columns do not match its table's schema or
555
+ * that omits a required one the write does not supply, and a repeated id
556
+ * within a collection.
557
+ * Decoding runs first, then the single parse, which reports whichever syntax
558
+ * error or repeated key it reaches first (a leading byte order mark is refused
559
+ * there). Then comes the version check, then each collection in turn
560
+ * (`agents`, `souls`, then `memories`): first that it is an array, then each
561
+ * row in array order, checking its shape and then that its id is not a
562
+ * repeat. The first problem found is returned as the one refusal. Every
563
+ * result, refusal included, carries the input's digest.
564
+ */
565
+ export function parseRestoreArchive(bytes) {
566
+ if (!(bytes instanceof Uint8Array)) {
567
+ throw new TypeError("parseRestoreArchive: expected the archive bytes as a Buffer or Uint8Array");
568
+ }
569
+ const input = new Uint8Array(bytes);
570
+ const sha256 = createHash("sha256").update(input).digest("hex");
571
+ const decoded = decodeStrictUtf8(input);
572
+ if (decoded.ok === false) {
573
+ return { ok: false, code: "invalid-utf8", reason: decoded.reason, location: "", offset: decoded.offset, sha256 };
574
+ }
575
+ const parsed = parseStrictJson(decoded.text);
576
+ if (parsed.ok === false) {
577
+ const offset = Buffer.byteLength(decoded.text.slice(0, parsed.index), "utf8");
578
+ return { ok: false, code: parsed.code, reason: parsed.reason, location: parsed.location, offset, sha256 };
579
+ }
580
+ const shape = archiveShapeRefusal(parsed.value);
581
+ if (shape)
582
+ return { ok: false, ...shape, sha256 };
583
+ return { ok: true, archive: parsed.value, sha256 };
584
+ }
585
+ // ─── Memory selection ────────────────────────────────────────────────────────
586
+ function selectionRefusal(reason) {
587
+ return { ok: false, code: "invalid-selection", reason, failures: [] };
588
+ }
589
+ function entriesRefused(failures) {
590
+ const ids = new Set(failures.map((failure) => failure.id));
591
+ return { ok: false, code: "entries-refused", reason: `${ids.size} selected Memory id(s) refused`, failures };
592
+ }
593
+ /** The selected rows in selection order (archive order when `ids` is
594
+ * omitted), and a failure for every selected id that does not resolve to
595
+ * exactly one archived Memory row. */
596
+ function resolveSelection(archive, ids) {
597
+ const memories = archive.memories;
598
+ if (!Array.isArray(memories))
599
+ return selectionRefusal("the archive has no memories collection");
600
+ const byId = new Map();
601
+ const repeated = new Set();
602
+ for (const row of memories) {
603
+ const id = isRecord(row) ? ownValue(row, "id") : undefined;
604
+ if (typeof id !== "string")
605
+ continue;
606
+ if (byId.has(id))
607
+ repeated.add(id);
608
+ else
609
+ byId.set(id, row);
610
+ }
611
+ const failures = [];
612
+ const repeatedFailure = (id) => ({ id, code: "duplicate-id", reason: "the archive holds this Memory id more than once" });
613
+ if (ids === undefined) {
614
+ for (const id of repeated)
615
+ failures.push(repeatedFailure(id));
616
+ return { rows: [...memories], failures };
617
+ }
618
+ if (!Array.isArray(ids))
619
+ return selectionRefusal("the selection is not an array of Memory ids");
620
+ if (ids.length === 0)
621
+ return selectionRefusal("the selection names no Memory ids; omit it to select every Memory row");
622
+ for (let index = 0; index < ids.length; index++) {
623
+ const id = ids[index];
624
+ if (typeof id !== "string" || id.length === 0)
625
+ return selectionRefusal(`selection entry ${index} is not a non-empty string`);
626
+ }
627
+ const rows = [];
628
+ const selected = new Set();
629
+ const named = new Set();
630
+ for (const id of ids) {
631
+ if (selected.has(id)) {
632
+ if (!named.has(id)) {
633
+ named.add(id);
634
+ failures.push({ id, code: "duplicate-selection", reason: "the selection names this Memory id more than once" });
635
+ }
636
+ continue;
637
+ }
638
+ selected.add(id);
639
+ const row = byId.get(id);
640
+ if (row === undefined)
641
+ failures.push({ id, code: "not-in-archive", reason: "the archive holds no Memory row with this id" });
642
+ else if (repeated.has(id))
643
+ failures.push(repeatedFailure(id));
644
+ else
645
+ rows.push(row);
646
+ }
647
+ return { rows, failures };
648
+ }
649
+ /**
650
+ * Resolve an optional selection of Memory ids against the archive. Omitted:
651
+ * every Memory row, in archive order. Given: the named rows in selection
652
+ * order. A selection that is not a non-empty array of non-empty strings
653
+ * refuses as `invalid-selection`, with no per-id failures and before any id
654
+ * is resolved. Otherwise an id the archive does not hold, or names twice,
655
+ * refuses the whole selection as `entries-refused`, listing every such id.
656
+ */
657
+ export function selectMemoryIds(archive, ids) {
658
+ const resolved = resolveSelection(archive, ids);
659
+ if ("ok" in resolved)
660
+ return resolved;
661
+ if (resolved.failures.length > 0)
662
+ return entriesRefused(resolved.failures);
663
+ return { ok: true, rows: resolved.rows };
664
+ }
665
+ // ─── Memory admission ────────────────────────────────────────────────────────
666
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
667
+ function isDeclaredStatus(value) {
668
+ return typeof value === "string" && MEMORY_PROMOTION_STATUSES.includes(value);
669
+ }
670
+ /**
671
+ * Validate one archived Memory row for restore. Requires a restorable row
672
+ * shape, string `content`, and promotion fields readers can interpret:
673
+ * - `promotionStatus`, when set, is a declared value;
674
+ * - `promotedAt` and `promotedBy`, when set, are strings, and are set only
675
+ * with a `promotionStatus`; an approved verdict has both, non-empty;
676
+ * - `promotionContentHash`, when set, is 64 lowercase hex characters, is set
677
+ * only with a `promotionStatus`, and equals `promotionContentHash(content)`.
678
+ * Null and absent fields are the same. A row whose shape is not restorable
679
+ * reports that one `invalid-row` failure and is not checked further;
680
+ * otherwise every content and promotion failure is listed. A valid row is
681
+ * classified as `bound`, `legacy-unbound` or `unpromoted`.
682
+ */
683
+ export function validateRestoreMemoryRow(row) {
684
+ const rawId = isRecord(row) ? ownValue(row, "id") : undefined;
685
+ const id = typeof rawId === "string" ? rawId : "";
686
+ const failures = [];
687
+ const fail = (code, reason, field) => {
688
+ failures.push(field === undefined ? { id, code, reason } : { id, code, reason, field });
689
+ };
690
+ const shape = rowShapeProblem(row, true);
691
+ if (shape) {
692
+ fail("invalid-row", shape.reason, shape.field);
693
+ return { ok: false, failures };
694
+ }
695
+ const record = row;
696
+ const content = ownValue(record, "content");
697
+ if (typeof content !== "string")
698
+ fail("content-not-string", "content is not a string", "content");
699
+ const status = ownValue(record, "promotionStatus") ?? null;
700
+ if (status !== null && !isDeclaredStatus(status)) {
701
+ fail("undeclared-promotion-status", `promotionStatus is not one of ${MEMORY_PROMOTION_STATUSES.join(", ")}`, "promotionStatus");
702
+ }
703
+ for (const field of ["promotedAt", "promotedBy"]) {
704
+ const value = ownValue(record, field) ?? null;
705
+ if (value !== null && typeof value !== "string")
706
+ fail("invalid-verdict-field", `${field} is not a string`, field);
707
+ else if (status === null && value !== null)
708
+ fail("verdict-without-status", `${field} is set without a promotionStatus`, field);
709
+ else if (status === "approved" && (value === null || value === "")) {
710
+ fail("approved-verdict-incomplete", `an approved verdict has no ${field}`, field);
711
+ }
712
+ }
713
+ const hash = ownValue(record, "promotionContentHash") ?? null;
714
+ if (hash !== null) {
715
+ const wellFormed = typeof hash === "string" && SHA256_HEX.test(hash);
716
+ if (!wellFormed) {
717
+ fail("invalid-binding-hash", "promotionContentHash is not 64 lowercase hex characters", "promotionContentHash");
718
+ }
719
+ if (status === null) {
720
+ fail("hash-without-verdict", "promotionContentHash is set without a promotionStatus", "promotionContentHash");
721
+ }
722
+ if (wellFormed && typeof content === "string" && hash !== promotionContentHash(content)) {
723
+ fail("binding-mismatch", "promotionContentHash does not bind the archived content", "promotionContentHash");
724
+ }
725
+ }
726
+ if (failures.length > 0)
727
+ return { ok: false, failures };
728
+ const kind = hash !== null ? "bound" : status !== null ? "legacy-unbound" : "unpromoted";
729
+ return {
730
+ ok: true,
731
+ entry: { id, agentId: record.agentId, kind, promotionStatus: status, row: record },
732
+ };
733
+ }
734
+ /**
735
+ * Validate a Memory restore selection before any write. Resolves the optional
736
+ * selection (see `selectMemoryIds`), validates every selected row (see
737
+ * `validateRestoreMemoryRow`), and returns either every selected entry
738
+ * validated, in selection order, or a refusal. A malformed selection returns
739
+ * the single `invalid-selection` refusal `selectMemoryIds` describes, and no
740
+ * row is validated. Otherwise the refusal lists every unresolvable id and
741
+ * every failing row's failures (one `invalid-row` failure for a row whose
742
+ * shape is not restorable). Unselected rows are not validated.
743
+ */
744
+ export function validateRestoreSelection(archive, ids) {
745
+ const resolved = resolveSelection(archive, ids);
746
+ if ("ok" in resolved)
747
+ return resolved;
748
+ const failures = [...resolved.failures];
749
+ const entries = [];
750
+ for (const row of resolved.rows) {
751
+ const result = validateRestoreMemoryRow(row);
752
+ if (result.ok === false)
753
+ failures.push(...result.failures);
754
+ else
755
+ entries.push(result.entry);
756
+ }
757
+ if (failures.length > 0)
758
+ return entriesRefused(failures);
759
+ return { ok: true, entries };
760
+ }