@tangle-network/agent-app 0.45.20 → 0.45.22

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 (113) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +22 -5
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/{chunk-PAB253MA.js → chunk-7V2I3JGZ.js} +19 -3
  16. package/dist/chunk-7V2I3JGZ.js.map +1 -0
  17. package/dist/chunk-CCVG2TL6.js +327 -0
  18. package/dist/chunk-CCVG2TL6.js.map +1 -0
  19. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  20. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  21. package/dist/chunk-F7VH4G5C.js +283 -0
  22. package/dist/chunk-F7VH4G5C.js.map +1 -0
  23. package/dist/chunk-I24YIKHO.js +183 -0
  24. package/dist/chunk-I24YIKHO.js.map +1 -0
  25. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  26. package/dist/chunk-NZVBJM73.js.map +1 -0
  27. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  28. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  29. package/dist/chunk-PC2WYTK7.js +405 -0
  30. package/dist/chunk-PC2WYTK7.js.map +1 -0
  31. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  32. package/dist/chunk-TX6S7XXU.js.map +1 -0
  33. package/dist/chunk-UGWQLQDS.js +35 -0
  34. package/dist/chunk-UGWQLQDS.js.map +1 -0
  35. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  36. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  37. package/dist/design-canvas/index.d.ts +3 -3
  38. package/dist/design-canvas/index.js +2 -2
  39. package/dist/design-canvas-react/engine.js +4 -4
  40. package/dist/design-canvas-react/index.js +7 -7
  41. package/dist/design-canvas-react/lazy.js +1 -1
  42. package/dist/documents/index.d.ts +233 -0
  43. package/dist/documents/index.js +495 -0
  44. package/dist/documents/index.js.map +1 -0
  45. package/dist/documents/pdf-inspector.d.ts +60 -0
  46. package/dist/documents/pdf-inspector.js +100 -0
  47. package/dist/documents/pdf-inspector.js.map +1 -0
  48. package/dist/eval/index.d.ts +1 -1
  49. package/dist/fold-DACU7gtf.d.ts +320 -0
  50. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  51. package/dist/openui/index.d.ts +208 -0
  52. package/dist/openui/index.js +350 -0
  53. package/dist/openui/index.js.map +1 -0
  54. package/dist/openui-react/index.d.ts +119 -0
  55. package/dist/openui-react/index.js +149 -0
  56. package/dist/openui-react/index.js.map +1 -0
  57. package/dist/platform/index.js +2 -2
  58. package/dist/preset-cloudflare/index.d.ts +2 -2
  59. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  60. package/dist/record/drizzle.d.ts +682 -0
  61. package/dist/record/drizzle.js +579 -0
  62. package/dist/record/drizzle.js.map +1 -0
  63. package/dist/record/index.d.ts +16 -0
  64. package/dist/record/index.js +35 -0
  65. package/dist/record/index.js.map +1 -0
  66. package/dist/runtime/index.d.ts +3 -3
  67. package/dist/sandbox/index.d.ts +13 -4
  68. package/dist/sandbox/index.js +6 -3
  69. package/dist/sequences/index.d.ts +3 -3
  70. package/dist/sequences/index.js +1 -1
  71. package/dist/session-shell/index.d.ts +173 -1
  72. package/dist/session-shell/index.js +13 -1
  73. package/dist/teams/index.js +9 -9
  74. package/dist/teams/invitations-api.js +3 -3
  75. package/dist/tools/index.d.ts +5 -5
  76. package/dist/tools/index.js +3 -2
  77. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  78. package/dist/types-DrBidf3O.d.ts +123 -0
  79. package/dist/values-C7RidJuI.d.ts +156 -0
  80. package/dist/web/index.d.ts +197 -31
  81. package/dist/web/index.js +15 -3
  82. package/dist/web-react/async/index.d.ts +309 -0
  83. package/dist/web-react/async/index.js +327 -0
  84. package/dist/web-react/async/index.js.map +1 -0
  85. package/dist/web-react/index.d.ts +338 -2
  86. package/dist/web-react/index.js +52 -6
  87. package/dist/work-product/index.d.ts +1 -1
  88. package/dist/work-product/index.js +2 -1
  89. package/dist/work-product/index.js.map +1 -1
  90. package/dist/workspace-react/index.js +1 -1
  91. package/package.json +43 -3
  92. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  93. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  94. package/dist/chunk-AH3IOSWF.js.map +0 -1
  95. package/dist/chunk-GINKOZFD.js +0 -214
  96. package/dist/chunk-GINKOZFD.js.map +0 -1
  97. package/dist/chunk-J25RST7G.js +0 -126
  98. package/dist/chunk-J25RST7G.js.map +0 -1
  99. package/dist/chunk-PAB253MA.js.map +0 -1
  100. package/dist/chunk-WBHPN5DY.js +0 -158
  101. package/dist/chunk-WBHPN5DY.js.map +0 -1
  102. package/dist/chunk-YEFFHORB.js.map +0 -1
  103. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  104. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  105. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  106. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  107. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  108. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  109. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  110. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  111. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  112. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  113. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,579 @@
1
+ import {
2
+ RECORD_KEY_SENTINEL,
3
+ RECORD_PERIOD_SENTINEL,
4
+ canonicalRecordJson,
5
+ defaultRecordPeriodScope,
6
+ detectRecordConflict,
7
+ foldRecordEntries,
8
+ recordEntryVisibleInPeriod,
9
+ recordFail,
10
+ recordOk,
11
+ recordUlid,
12
+ resolveWriteReviewState,
13
+ validateRecordValue
14
+ } from "../chunk-I24YIKHO.js";
15
+
16
+ // src/record/drizzle/schema.ts
17
+ import { sql } from "drizzle-orm";
18
+ import { index, integer, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
19
+ var RECORD_STORE_COLUMNS = /* @__PURE__ */ new Set([
20
+ "id",
21
+ "scopeId",
22
+ "seq",
23
+ "dimension",
24
+ "period",
25
+ "path",
26
+ "itemKey",
27
+ "valueJson",
28
+ "affirmedEmpty",
29
+ "reviewState",
30
+ "conflict",
31
+ "supersededById",
32
+ "sourceKind",
33
+ "sourceRef",
34
+ "sourceLocator",
35
+ "sourceQuote",
36
+ "confidence",
37
+ "reviewedAt",
38
+ "reviewedBy",
39
+ "createdAt"
40
+ ]);
41
+ function buildRecordEntryTable(options) {
42
+ const { tableName, scopeTable, sourceTable, reviewerTable } = options;
43
+ const prefix = options.indexPrefix ?? tableName;
44
+ const extraColumns = options.extraColumns ?? {};
45
+ const collisions = Object.keys(extraColumns).filter((name) => RECORD_STORE_COLUMNS.has(name));
46
+ if (collisions.length > 0) {
47
+ throw new Error(
48
+ `createRecordTable('${tableName}'): extraColumns may not redefine the store's own columns \u2014 ${collisions.sort().join(", ")}`
49
+ );
50
+ }
51
+ const columns = {
52
+ /** ULID minted by the store — an atomic supersede needs the replacement
53
+ * id before the insert, so this has no column default. */
54
+ id: text("id").primaryKey(),
55
+ scopeId: text("scope_id").notNull().references(() => scopeTable.id, { onDelete: "cascade" }),
56
+ /** Per-scope monotonic write counter, assigned inside the insert
57
+ * statement. The fold's only ordering key. */
58
+ seq: integer("seq").notNull(),
59
+ /** Consumer-defined partition inside the scope; `''` when unused. */
60
+ dimension: text("dimension").notNull().default(""),
61
+ /** The period the assertion became true in; `0` when the consumer has no
62
+ * time dimension. */
63
+ period: integer("period").notNull().default(0),
64
+ /** The field this entry asserts. Validated against the consumer's schema
65
+ * map on every write. */
66
+ path: text("path").notNull(),
67
+ /** Which element of a collection the path belongs to; `''` when not
68
+ * applicable. */
69
+ itemKey: text("item_key").notNull().default(""),
70
+ /** Canonical JSON (sorted keys) of the validated value. */
71
+ valueJson: text("value_json").notNull(),
72
+ /** "There are none of these" — written against an affirmable path with
73
+ * `item_key = ''` and `value_json = 'null'`. */
74
+ affirmedEmpty: integer("affirmed_empty", { mode: "boolean" }).notNull().default(false),
75
+ reviewState: text("review_state").$type().notNull(),
76
+ /** Set when this entry disagreed with a live head from a different source
77
+ * kind at write time — surfaced for a human to resolve. */
78
+ conflict: integer("conflict", { mode: "boolean" }).notNull().default(false),
79
+ /** Audit link to the accepted entry that replaced this one; NULL marks a
80
+ * live head. */
81
+ supersededById: text("superseded_by_id"),
82
+ /** Stamped by the server call site, never accepted from model output. */
83
+ sourceKind: text("source_kind").notNull(),
84
+ sourceRef: sourceTable ? text("source_ref").references(() => sourceTable.id, { onDelete: "set null" }) : text("source_ref"),
85
+ /** JSON position inside the source. */
86
+ sourceLocator: text("source_locator", { mode: "json" }).$type(),
87
+ sourceQuote: text("source_quote"),
88
+ confidence: real("confidence"),
89
+ /** Epoch milliseconds. */
90
+ reviewedAt: integer("reviewed_at"),
91
+ reviewedBy: reviewerTable ? text("reviewed_by").references(() => reviewerTable.id, { onDelete: "set null" }) : text("reviewed_by"),
92
+ /** Epoch milliseconds. Display only — `seq` orders the fold. */
93
+ createdAt: integer("created_at").notNull().$defaultFn(() => Date.now())
94
+ };
95
+ const widened = columns;
96
+ for (const [name, column] of Object.entries(extraColumns)) widened[name] = column;
97
+ return sqliteTable(
98
+ tableName,
99
+ columns,
100
+ (table) => [
101
+ uniqueIndex(`${prefix}_scope_seq_uidx`).on(table.scopeId, table.seq),
102
+ uniqueIndex(`${prefix}_live_head_uidx`).on(table.scopeId, table.dimension, table.path, table.itemKey, table.period).where(sql`review_state = 'accepted' AND superseded_by_id IS NULL`),
103
+ index(`${prefix}_scope_period_idx`).on(table.scopeId, table.period),
104
+ index(`${prefix}_scope_review_idx`).on(table.scopeId, table.reviewState),
105
+ index(`${prefix}_scope_path_idx`).on(table.scopeId, table.path)
106
+ ]
107
+ );
108
+ }
109
+ function createRecordTable(options) {
110
+ return buildRecordEntryTable(options);
111
+ }
112
+
113
+ // src/record/drizzle/store.ts
114
+ import { and, asc, eq, getTableColumns, getTableName, isNull, lte, sql as sql2 } from "drizzle-orm";
115
+ var DEFAULT_WRITE_ATTEMPTS = 3;
116
+ function createRecordStore(options) {
117
+ const { db, table, policy } = options;
118
+ const tableName = getTableName(table);
119
+ const newId = options.newId ?? (() => recordUlid());
120
+ const now = options.now ?? (() => Date.now());
121
+ const attempts = options.maxWriteAttempts ?? DEFAULT_WRITE_ATTEMPTS;
122
+ const storePeriodScope = options.periodScope ?? defaultRecordPeriodScope;
123
+ const strategy = resolveAtomicStrategy(db);
124
+ const affirmable = new Set(policy.affirmablePaths ?? []);
125
+ const requireRef = new Set(policy.requireSourceRef ?? []);
126
+ const requireQuote = new Set(policy.requireSourceQuote ?? []);
127
+ const extraColumnNames = new Set(
128
+ Object.keys(getTableColumns(table)).filter((name) => !RECORD_STORE_COLUMNS.has(name))
129
+ );
130
+ function liveHeadWhere(scopeId, key) {
131
+ return and(
132
+ eq(table.scopeId, scopeId),
133
+ eq(table.dimension, key.dimension),
134
+ eq(table.path, key.path),
135
+ eq(table.itemKey, key.itemKey),
136
+ eq(table.period, key.period),
137
+ eq(table.reviewState, "accepted"),
138
+ isNull(table.supersededById)
139
+ );
140
+ }
141
+ async function loadLiveHead(scopeId, key) {
142
+ const rows = await db.select().from(table).where(liveHeadWhere(scopeId, key)).limit(1);
143
+ return rows[0];
144
+ }
145
+ function markHeadStatement(headId, replacementId, requireProposedId) {
146
+ const guards = [eq(table.id, headId), eq(table.reviewState, "accepted"), isNull(table.supersededById)];
147
+ if (requireProposedId !== void 0) {
148
+ guards.push(
149
+ sql2`EXISTS (SELECT 1 FROM ${sql2.identifier(tableName)} WHERE id = ${requireProposedId} AND review_state = 'proposed')`
150
+ );
151
+ }
152
+ return db.update(table).set({ supersededById: replacementId }).where(and(...guards)).returning({ id: table.id });
153
+ }
154
+ async function loadEntry(scopeId, entryId) {
155
+ const rows = await db.select().from(table).where(and(eq(table.id, entryId), eq(table.scopeId, scopeId))).limit(1);
156
+ return rows[0];
157
+ }
158
+ async function write(input) {
159
+ const validated = validateWrite(input);
160
+ if (!validated.succeeded) return validated;
161
+ const draft = validated.value;
162
+ let lastError = "";
163
+ for (let attempt = 0; attempt < attempts; attempt++) {
164
+ try {
165
+ const head = await loadLiveHead(input.scopeId, draft.key);
166
+ const conflict = detectRecordConflict(policy, head, draft);
167
+ const reviewState = conflict ? "proposed" : draft.reviewState;
168
+ const id = newId();
169
+ const values = insertValues(input, draft, id, reviewState, conflict);
170
+ if (reviewState === "accepted" && head !== void 0) {
171
+ const paired = await runGuardedPair(
172
+ db,
173
+ strategy,
174
+ markHeadStatement(head.id, id),
175
+ db.insert(table).values(values).returning()
176
+ );
177
+ if (!paired.guardMatched) {
178
+ if (paired.rolledBack) {
179
+ lastError = `write: lost the head race on '${draft.key.path}' (head ${head.id} changed underneath)`;
180
+ continue;
181
+ }
182
+ return recordFail(
183
+ "supersede-race",
184
+ `write: head ${head.id} on '${draft.key.path}' was not markable but the write committed \u2014 the live-head index is not enforcing`
185
+ );
186
+ }
187
+ const row2 = firstRow(paired.mainRows);
188
+ if (!row2) return recordFail("storage-failed", "write: insert returned no row");
189
+ return recordOk({ entry: row2, conflict: false, supersededEntryId: head.id });
190
+ }
191
+ const inserted = await db.insert(table).values(values).returning();
192
+ const row = firstRow(inserted);
193
+ if (!row) return recordFail("storage-failed", "write: insert returned no row");
194
+ return recordOk({ entry: row, conflict, supersededEntryId: null });
195
+ } catch (error) {
196
+ if (isUniqueViolation(error)) {
197
+ lastError = `write: concurrent head write on '${draft.key.path}' \u2014 ${errorMessage(error)}`;
198
+ continue;
199
+ }
200
+ return recordFail("storage-failed", `write: ${errorMessage(error)}`);
201
+ }
202
+ }
203
+ return recordFail("supersede-race", `${lastError} (gave up after ${attempts} attempts)`);
204
+ }
205
+ async function review(input) {
206
+ let existing;
207
+ try {
208
+ const rows = await db.select().from(table).where(and(eq(table.id, input.entryId), eq(table.scopeId, input.scopeId))).limit(1);
209
+ existing = rows[0];
210
+ } catch (error) {
211
+ return recordFail("storage-failed", `review: ${errorMessage(error)}`);
212
+ }
213
+ if (!existing) {
214
+ return recordFail("not-found", `review: entry '${input.entryId}' not found in scope '${input.scopeId}'`);
215
+ }
216
+ if (existing.reviewState !== "proposed") {
217
+ return recordFail(
218
+ "not-reviewable",
219
+ `review: entry '${input.entryId}' is '${existing.reviewState}' \u2014 only proposed entries are reviewable`
220
+ );
221
+ }
222
+ const reviewedAt = now();
223
+ const reviewedBy = input.reviewedBy ?? null;
224
+ if (input.action === "reject") {
225
+ try {
226
+ const updated = await db.update(table).set({ reviewState: "rejected", reviewedAt, reviewedBy }).where(and(eq(table.id, existing.id), eq(table.reviewState, "proposed"))).returning();
227
+ const row = firstRow(updated);
228
+ if (!row) {
229
+ return recordFail("not-reviewable", `review: entry '${input.entryId}' was reviewed concurrently`);
230
+ }
231
+ return recordOk(row);
232
+ } catch (error) {
233
+ return recordFail("storage-failed", `review: ${errorMessage(error)}`);
234
+ }
235
+ }
236
+ const key = {
237
+ dimension: existing.dimension,
238
+ path: existing.path,
239
+ itemKey: existing.itemKey,
240
+ period: existing.period
241
+ };
242
+ let lastError = "";
243
+ for (let attempt = 0; attempt < attempts; attempt++) {
244
+ try {
245
+ const head = await loadLiveHead(input.scopeId, key);
246
+ const acceptStatement = db.update(table).set({ reviewState: "accepted", conflict: false, reviewedAt, reviewedBy }).where(and(eq(table.id, existing.id), eq(table.reviewState, "proposed"))).returning();
247
+ if (head !== void 0) {
248
+ const paired = await runGuardedPair(
249
+ db,
250
+ strategy,
251
+ markHeadStatement(head.id, existing.id, existing.id),
252
+ acceptStatement
253
+ );
254
+ if (!paired.guardMatched && paired.mainMatched) {
255
+ return recordFail(
256
+ "supersede-race",
257
+ `review: head ${head.id} was not markable but the accept committed \u2014 the live-head index is not enforcing`
258
+ );
259
+ }
260
+ if (paired.guardMatched && !paired.mainMatched && !paired.rolledBack) {
261
+ return recordFail(
262
+ "supersede-race",
263
+ `review: head ${head.id} was marked superseded by '${input.entryId}' but the accept matched no row \u2014 the batch is not atomic`
264
+ );
265
+ }
266
+ if (!paired.guardMatched || !paired.mainMatched) {
267
+ const current = await loadEntry(input.scopeId, existing.id);
268
+ if (current === void 0 || current.reviewState !== "proposed") {
269
+ return recordFail("not-reviewable", `review: entry '${input.entryId}' was reviewed concurrently`);
270
+ }
271
+ lastError = `review: lost the head race accepting '${input.entryId}' (head ${head.id} changed underneath)`;
272
+ continue;
273
+ }
274
+ const row2 = firstRow(paired.mainRows);
275
+ if (!row2) return recordFail("not-reviewable", `review: entry '${input.entryId}' was reviewed concurrently`);
276
+ return recordOk(row2);
277
+ }
278
+ const accepted = await acceptStatement;
279
+ const row = firstRow(accepted);
280
+ if (!row) return recordFail("not-reviewable", `review: entry '${input.entryId}' was reviewed concurrently`);
281
+ return recordOk(row);
282
+ } catch (error) {
283
+ if (isUniqueViolation(error)) {
284
+ lastError = `review: concurrent head write accepting '${input.entryId}' \u2014 ${errorMessage(error)}`;
285
+ continue;
286
+ }
287
+ return recordFail("storage-failed", `review: ${errorMessage(error)}`);
288
+ }
289
+ }
290
+ return recordFail("supersede-race", `${lastError} (gave up after ${attempts} attempts)`);
291
+ }
292
+ async function list(input) {
293
+ if (input.period !== void 0 && !Number.isInteger(input.period)) {
294
+ return recordFail("invalid-input", `list: period must be an integer, got ${String(input.period)}`);
295
+ }
296
+ try {
297
+ const where = input.period === void 0 ? eq(table.scopeId, input.scopeId) : and(eq(table.scopeId, input.scopeId), lte(table.period, input.period));
298
+ const rows = await db.select().from(table).where(where).orderBy(asc(table.seq));
299
+ const visible = rows.filter((row) => {
300
+ if (input.period !== void 0 && !recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, input.period)) return false;
301
+ if (input.reviewState !== void 0) {
302
+ if (row.reviewState !== input.reviewState) return false;
303
+ } else if (!input.includeRejected && row.reviewState === "rejected") {
304
+ return false;
305
+ }
306
+ if (!input.includeSuperseded && row.supersededById !== null) return false;
307
+ return true;
308
+ });
309
+ return recordOk(visible);
310
+ } catch (error) {
311
+ return recordFail("storage-failed", `list: ${errorMessage(error)}`);
312
+ }
313
+ }
314
+ async function loadHeads(scopeId, period) {
315
+ return db.select().from(table).where(and(
316
+ eq(table.scopeId, scopeId),
317
+ eq(table.reviewState, "accepted"),
318
+ isNull(table.supersededById),
319
+ lte(table.period, period)
320
+ )).orderBy(asc(table.seq));
321
+ }
322
+ async function heads(input) {
323
+ const period = input.period ?? RECORD_PERIOD_SENTINEL;
324
+ if (!Number.isInteger(period)) {
325
+ return recordFail("invalid-input", `heads: period must be an integer, got ${String(period)}`);
326
+ }
327
+ try {
328
+ const rows = await loadHeads(input.scopeId, period);
329
+ return recordOk(rows.filter((row) => recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, period)));
330
+ } catch (error) {
331
+ return recordFail("storage-failed", `heads: ${errorMessage(error)}`);
332
+ }
333
+ }
334
+ async function materialize(input) {
335
+ const period = input.period ?? RECORD_PERIOD_SENTINEL;
336
+ if (!Number.isInteger(period)) {
337
+ return recordFail("invalid-input", `materialize: period must be an integer, got ${String(period)}`);
338
+ }
339
+ let loaded;
340
+ try {
341
+ loaded = await loadHeads(input.scopeId, period);
342
+ } catch (error) {
343
+ return recordFail("storage-failed", `materialize: ${errorMessage(error)}`);
344
+ }
345
+ const rules = input.rules.periodScope ? input.rules : { ...input.rules, periodScope: storePeriodScope };
346
+ const folded = foldRecordEntries(loaded.map(toFoldable), { rules, period });
347
+ if (!folded.succeeded) return folded;
348
+ const periodScope = rules.periodScope ?? storePeriodScope;
349
+ try {
350
+ const proposed = await db.select({ path: table.path, period: table.period, conflict: table.conflict }).from(table).where(and(
351
+ eq(table.scopeId, input.scopeId),
352
+ eq(table.reviewState, "proposed"),
353
+ lte(table.period, period)
354
+ ));
355
+ const visible = proposed.filter((row) => recordEntryVisibleInPeriod(periodScope(row.path), row.period, period));
356
+ return recordOk({
357
+ value: folded.value.value,
358
+ entryCount: folded.value.entryCount,
359
+ pendingProposed: visible.length,
360
+ conflicts: visible.filter((row) => row.conflict).length
361
+ });
362
+ } catch (error) {
363
+ return recordFail("storage-failed", `materialize: ${errorMessage(error)}`);
364
+ }
365
+ }
366
+ function validateWrite(input) {
367
+ const period = input.period ?? RECORD_PERIOD_SENTINEL;
368
+ const minPeriod = policy.minPeriod ?? RECORD_PERIOD_SENTINEL;
369
+ const maxPeriod = policy.maxPeriod ?? Number.MAX_SAFE_INTEGER;
370
+ if (!Number.isInteger(period) || period < minPeriod || period > maxPeriod) {
371
+ return recordFail(
372
+ "invalid-input",
373
+ `write: period must be an integer in [${minPeriod}, ${maxPeriod}], got ${String(period)}`
374
+ );
375
+ }
376
+ if (requireRef.has(input.sourceKind) && !input.sourceRef) {
377
+ return recordFail("invalid-input", `write: source kind '${input.sourceKind}' requires a sourceRef ('${input.path}')`);
378
+ }
379
+ if (requireQuote.has(input.sourceKind) && !input.sourceQuote) {
380
+ return recordFail("invalid-input", `write: source kind '${input.sourceKind}' requires a sourceQuote ('${input.path}')`);
381
+ }
382
+ const extras = input.extras ?? {};
383
+ for (const key of Object.keys(extras)) {
384
+ if (!extraColumnNames.has(key)) {
385
+ return recordFail(
386
+ "invalid-input",
387
+ `write: extras key '${key}' has no column on '${tableName}' \u2014 declare it in createRecordTable's extraColumns`
388
+ );
389
+ }
390
+ }
391
+ for (const key of policy.requireExtras?.[input.sourceKind] ?? []) {
392
+ const held = extras[key];
393
+ if (held === void 0 || held === null || held === "") {
394
+ return recordFail(
395
+ "invalid-input",
396
+ `write: source kind '${input.sourceKind}' requires extras.${key} ('${input.path}')`
397
+ );
398
+ }
399
+ }
400
+ if (input.confidence !== void 0 && input.confidence !== null && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {
401
+ return recordFail("invalid-input", `write: confidence must be in [0, 1], got ${String(input.confidence)}`);
402
+ }
403
+ const state = resolveWriteReviewState(policy, input.sourceKind);
404
+ if (!state.succeeded) return state;
405
+ const dimension = canonicalize(policy.canonicalizeDimension, input.path, input.dimension ?? RECORD_KEY_SENTINEL, "dimension");
406
+ if (!dimension.succeeded) return dimension;
407
+ if (input.affirmedEmpty === true) {
408
+ if (input.value !== void 0) {
409
+ return recordFail("invalid-input", `write: an affirmedEmpty entry must not carry a value ('${input.path}')`);
410
+ }
411
+ if (!affirmable.has(input.path)) {
412
+ return recordFail(
413
+ "unknown-path",
414
+ `write: '${input.path}' is not an affirmable path \u2014 affirmedEmpty targets a path declared in policy.affirmablePaths`
415
+ );
416
+ }
417
+ if ((input.itemKey ?? RECORD_KEY_SENTINEL) !== RECORD_KEY_SENTINEL) {
418
+ return recordFail(
419
+ "invalid-input",
420
+ `write: an affirmedEmpty entry uses the itemKey sentinel \u2014 it asserts that a whole path is empty ('${input.path}')`
421
+ );
422
+ }
423
+ return recordOk({
424
+ key: { dimension: dimension.value, path: input.path, itemKey: RECORD_KEY_SENTINEL, period },
425
+ valueJson: "null",
426
+ affirmedEmpty: true,
427
+ reviewState: state.value,
428
+ sourceKind: input.sourceKind
429
+ });
430
+ }
431
+ const validator = policy.schemas[input.path];
432
+ if (validator === void 0) {
433
+ return recordFail("unknown-path", `write: unknown path '${input.path}' \u2014 not a key of the policy's schema map`);
434
+ }
435
+ if (input.value === void 0) {
436
+ return recordFail("invalid-input", `write: a value is required unless affirmedEmpty is true ('${input.path}')`);
437
+ }
438
+ const parsed = validateRecordValue(validator, input.value);
439
+ if (!parsed.succeeded) {
440
+ return recordFail("invalid-value", `write: value for '${input.path}' failed validation \u2014 ${parsed.error}`);
441
+ }
442
+ const itemKey = canonicalize(policy.canonicalizeItemKey, input.path, input.itemKey ?? RECORD_KEY_SENTINEL, "itemKey");
443
+ if (!itemKey.succeeded) return itemKey;
444
+ return recordOk({
445
+ key: { dimension: dimension.value, path: input.path, itemKey: itemKey.value, period },
446
+ valueJson: canonicalRecordJson(parsed.value),
447
+ affirmedEmpty: false,
448
+ reviewState: state.value,
449
+ sourceKind: input.sourceKind
450
+ });
451
+ }
452
+ function insertValues(input, draft, id, reviewState, conflict) {
453
+ return {
454
+ // First, so a product column can never shadow a store-owned one even if
455
+ // the guards above were bypassed.
456
+ ...input.extras ?? {},
457
+ id,
458
+ scopeId: input.scopeId,
459
+ // Assigned inside the statement: SQLite executes one statement
460
+ // atomically, so MAX + 1 cannot race, and `(scope_id, seq)` unique
461
+ // backstops it.
462
+ seq: sql2`(SELECT COALESCE(MAX(seq), 0) + 1 FROM ${sql2.identifier(tableName)} WHERE scope_id = ${input.scopeId})`,
463
+ dimension: draft.key.dimension,
464
+ period: draft.key.period,
465
+ path: draft.key.path,
466
+ itemKey: draft.key.itemKey,
467
+ valueJson: draft.valueJson,
468
+ affirmedEmpty: draft.affirmedEmpty,
469
+ reviewState,
470
+ conflict,
471
+ supersededById: null,
472
+ sourceKind: input.sourceKind,
473
+ sourceRef: input.sourceRef ?? null,
474
+ sourceLocator: input.sourceLocator ?? null,
475
+ sourceQuote: input.sourceQuote ?? null,
476
+ confidence: input.confidence ?? null,
477
+ // A write that lands accepted by policy was not REVIEWED — nobody looked
478
+ // at it. `createdAt` records when it landed; these two stay null until an
479
+ // actual accept/reject.
480
+ reviewedAt: null,
481
+ reviewedBy: null
482
+ };
483
+ }
484
+ return { atomicStrategy: strategy, write, review, list, heads, materialize };
485
+ }
486
+ function toFoldable(row) {
487
+ return {
488
+ id: row.id,
489
+ seq: row.seq,
490
+ dimension: row.dimension,
491
+ period: row.period,
492
+ path: row.path,
493
+ itemKey: row.itemKey,
494
+ valueJson: row.valueJson,
495
+ affirmedEmpty: row.affirmedEmpty
496
+ };
497
+ }
498
+ function canonicalize(canonicalizer, path, raw, column) {
499
+ if (!canonicalizer) return recordOk(raw);
500
+ const result = canonicalizer(path, raw);
501
+ if (!result.succeeded) return recordFail("invalid-input", `write: '${path}' ${column} \u2014 ${result.error}`);
502
+ return result;
503
+ }
504
+ function firstRow(rows) {
505
+ return Array.isArray(rows) ? rows[0] : void 0;
506
+ }
507
+ function resolveAtomicStrategy(db) {
508
+ if (typeof db.batch === "function") return "batch";
509
+ if (typeof db.run === "function") return "begin-immediate";
510
+ throw new Error(
511
+ "createRecordStore: the injected driver exposes neither batch() nor run() \u2014 an atomic supersede is impossible on it"
512
+ );
513
+ }
514
+ async function runGuardedPair(db, strategy, guard, main) {
515
+ if (strategy === "batch") {
516
+ const batch = db.batch;
517
+ if (typeof batch !== "function") {
518
+ throw new Error("runGuardedPair: batch strategy resolved but the driver has no batch()");
519
+ }
520
+ const results = await batch.call(db, [guard, main]);
521
+ const guardRows = results[0];
522
+ const mainRows = Array.isArray(results[1]) ? results[1] : [];
523
+ return {
524
+ guardMatched: Array.isArray(guardRows) && guardRows.length === 1,
525
+ mainMatched: mainRows.length > 0,
526
+ rolledBack: false,
527
+ mainRows
528
+ };
529
+ }
530
+ await db.run(sql2`begin immediate`);
531
+ try {
532
+ const guardRows = await guard;
533
+ if (!Array.isArray(guardRows) || guardRows.length !== 1) {
534
+ await db.run(sql2`rollback`);
535
+ return { guardMatched: false, mainMatched: false, rolledBack: true, mainRows: [] };
536
+ }
537
+ const mainRows = await main;
538
+ if (!Array.isArray(mainRows) || mainRows.length === 0) {
539
+ await db.run(sql2`rollback`);
540
+ return { guardMatched: true, mainMatched: false, rolledBack: true, mainRows: [] };
541
+ }
542
+ await db.run(sql2`commit`);
543
+ return { guardMatched: true, mainMatched: true, rolledBack: false, mainRows };
544
+ } catch (error) {
545
+ await rollbackQuietly(db);
546
+ throw error;
547
+ }
548
+ }
549
+ async function rollbackQuietly(db) {
550
+ try {
551
+ await db.run(sql2`rollback`);
552
+ } catch {
553
+ }
554
+ }
555
+ function errorMessage(error) {
556
+ const parts = [];
557
+ let cursor = error;
558
+ for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {
559
+ parts.push(cursor.message);
560
+ cursor = cursor.cause;
561
+ }
562
+ return parts.length > 0 ? parts.join(" \u2014 ") : String(error);
563
+ }
564
+ function isUniqueViolation(error) {
565
+ let cursor = error;
566
+ for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {
567
+ if (cursor.message.includes("UNIQUE constraint failed")) return true;
568
+ cursor = cursor.cause;
569
+ }
570
+ return false;
571
+ }
572
+ export {
573
+ RECORD_STORE_COLUMNS,
574
+ createRecordStore,
575
+ createRecordTable,
576
+ resolveAtomicStrategy,
577
+ toFoldable
578
+ };
579
+ //# sourceMappingURL=drizzle.js.map