@tearleads/client-sdk 0.1.208 → 0.1.210

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.
@@ -7,23 +7,32 @@ function restoreText(doc, text) {
7
7
  current.update(text);
8
8
  return true;
9
9
  }
10
+ /** A field's own value: never a method every object inherits. */
11
+ function ownField(fields, key) {
12
+ return Object.hasOwn(fields, key) ? fields[key] : undefined;
13
+ }
10
14
  function restoreStructuredFields(doc, target, registry) {
11
15
  const current = readStoredDocumentState(doc, registry);
12
16
  // A note has no structured fields to restore.
13
17
  if (current.documentKind === "note")
14
18
  return false;
15
- const patch = {};
19
+ // Read both sides by own key only. A field named `constructor` or
20
+ // `toString` that the restored version lacks would otherwise read as the
21
+ // inherited function, which is neither "absent" nor a value Loro can store.
22
+ const changes = [];
16
23
  for (const key of new Set([
17
24
  ...Object.keys(current.structuredFields),
18
25
  ...Object.keys(target),
19
26
  ])) {
20
- if (current.structuredFields[key] !== target[key]) {
21
- patch[key] = target[key];
27
+ const wanted = ownField(target, key);
28
+ if (ownField(current.structuredFields, key) !== wanted) {
29
+ changes.push([key, wanted]);
22
30
  }
23
31
  }
24
- if (Object.keys(patch).length === 0)
32
+ if (changes.length === 0)
25
33
  return false;
26
- writeStoredDocumentFields(doc, current.documentKind, patch, registry);
34
+ // fromEntries defines every key as an own property, `__proto__` included.
35
+ writeStoredDocumentFields(doc, current.documentKind, Object.fromEntries(changes), registry);
27
36
  return true;
28
37
  }
29
38
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"documentRestore.js","sourceRoot":"","sources":["documentRestore.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,EAEvB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,cAAc,EACd,mBAAmB,EAEnB,gBAAgB,EAChB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AA0B3B,SAAS,WAAW,CAAC,GAAuB,EAAE,IA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CAC3C,GAAG,EACH,OAAO,CAAC,gBAAgB,EACxB,QAAQ,CACT,CAAC;IACF,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAChE,OAAO,WAAW,IAAI,aAAa,IAAI,WAAW,CAAC;AACrD,CAAC","sourcesContent":["import {\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n type StructuredDocumentShape,\n writeStoredDocumentFields,\n} from \"./documentKinds\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n type DocumentRowAttribution,\n listDocumentRows,\n removeDocumentRow,\n replaceDocumentRowFields,\n} from \"./documentRowList\";\n\n/**\n * The content of a document that a restore writes back: its text, structured\n * fields, and rows. Attachments are not part of it. Their bytes are not kept\n * once detached, so a restore leaves the document's attachments as they are.\n */\nexport interface DocumentRestoreContent {\n readonly rows: ReadonlyArray<{\n readonly fields: Readonly<Record<string, string>>;\n readonly id: string;\n }>;\n readonly structuredFields: Readonly<Record<string, string>>;\n readonly text: string;\n}\n\ntype RestoreRow = DocumentRestoreContent[\"rows\"][number];\n\n/** A document whose text can be replaced, as a Loro document's can. */\ntype RestorableDocument = Omit<StructuredDocumentShape, \"getText\"> & {\n getText: (key: string) => {\n toString: () => string;\n update: (text: string) => void;\n };\n};\n\nfunction restoreText(doc: RestorableDocument, text: string): boolean {\n const current = doc.getText(\"text\");\n if (current.toString() === text) return false;\n current.update(text);\n return true;\n}\n\nfunction restoreStructuredFields(\n doc: StructuredDocumentShape,\n target: Readonly<Record<string, string>>,\n registry: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const current = readStoredDocumentState(doc, registry);\n // A note has no structured fields to restore.\n if (current.documentKind === \"note\") return false;\n const patch: Record<string, string | undefined> = {};\n for (const key of new Set([\n ...Object.keys(current.structuredFields),\n ...Object.keys(target),\n ])) {\n if (current.structuredFields[key] !== target[key]) {\n patch[key] = target[key];\n }\n }\n if (Object.keys(patch).length === 0) return false;\n writeStoredDocumentFields(doc, current.documentKind, patch, registry);\n return true;\n}\n\n/**\n * Make the document's rows equal `target`. A row that still exists is patched\n * cell by cell under its own id, a row that is gone from `target` is removed,\n * and a row the document no longer has is added back as a new row with a new\n * id, at the end.\n *\n * The new id is what keeps a restore safe to merge: two devices restoring the\n * same version at once each add their own copy, and both copies stay distinct\n * rows that can be edited or removed. Re-adding under the old id would leave\n * two rows sharing it, with writes reaching only the first. Row order is not\n * restored, because a row cannot be moved.\n */\nfunction restoreRows(\n doc: StructuredDocumentShape,\n target: ReadonlyArray<RestoreRow>,\n attribution: DocumentRowAttribution,\n): boolean {\n const current = listDocumentRows(doc);\n const targetById = new Map(target.map((row) => [row.id, row]));\n const currentIds = new Set(current.map((row) => row.id));\n let changed = false;\n for (const row of current) {\n const wanted = targetById.get(row.id);\n if (wanted === undefined) {\n changed = removeDocumentRow(doc, row.id) || changed;\n } else {\n changed =\n replaceDocumentRowFields(doc, row.id, wanted.fields, attribution) ||\n changed;\n }\n }\n for (const row of target) {\n if (!currentIds.has(row.id)) {\n addDocumentRow(doc, createDocumentRowId(), row.fields, attribution);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Write `content` into the document as ordinary edits and report whether\n * anything changed. Nothing is rewound: the document keeps its whole history\n * and gains the operations that carry it back to this content, so the restore\n * syncs and merges like any other edit.\n */\nexport function restoreDocumentContent(\n doc: RestorableDocument,\n content: DocumentRestoreContent,\n attribution: DocumentRowAttribution,\n registry?: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const textChanged = restoreText(doc, content.text);\n const fieldsChanged = restoreStructuredFields(\n doc,\n content.structuredFields,\n registry,\n );\n const rowsChanged = restoreRows(doc, content.rows, attribution);\n return textChanged || fieldsChanged || rowsChanged;\n}\n"]}
1
+ {"version":3,"file":"documentRestore.js","sourceRoot":"","sources":["documentRestore.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,EAEvB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,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QACzB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YAC5B,cAAc,CAAC,GAAG,EAAE,mBAAmB,EAAE,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;YACpE,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,GAAuB,EACvB,OAA+B,EAC/B,WAAmC,EACnC,QAAqD;IAErD,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,MAAM,aAAa,GAAG,uBAAuB,CAC3C,GAAG,EACH,OAAO,CAAC,gBAAgB,EACxB,QAAQ,CACT,CAAC;IACF,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAChE,OAAO,WAAW,IAAI,aAAa,IAAI,WAAW,CAAC;AACrD,CAAC","sourcesContent":["import {\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n type StructuredDocumentShape,\n writeStoredDocumentFields,\n} from \"./documentKinds\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n type DocumentRowAttribution,\n listDocumentRows,\n removeDocumentRow,\n replaceDocumentRowFields,\n} from \"./documentRowList\";\n\n/**\n * The content of a document that a restore writes back: its text, structured\n * fields, and rows. Attachments are not part of it. Their bytes are not kept\n * once detached, so a restore leaves the document's attachments as they are.\n */\nexport interface DocumentRestoreContent {\n readonly rows: ReadonlyArray<{\n readonly fields: Readonly<Record<string, string>>;\n readonly id: string;\n }>;\n readonly structuredFields: Readonly<Record<string, string>>;\n readonly text: string;\n}\n\ntype RestoreRow = DocumentRestoreContent[\"rows\"][number];\n\n/** A document whose text can be replaced, as a Loro document's can. */\ntype RestorableDocument = Omit<StructuredDocumentShape, \"getText\"> & {\n getText: (key: string) => {\n toString: () => string;\n update: (text: string) => void;\n };\n};\n\nfunction restoreText(doc: RestorableDocument, text: string): boolean {\n const current = doc.getText(\"text\");\n if (current.toString() === text) return false;\n current.update(text);\n return true;\n}\n\n/** A field's own value: never a method every object inherits. */\nfunction ownField(\n fields: Readonly<Record<string, string>>,\n key: string,\n): string | undefined {\n return Object.hasOwn(fields, key) ? fields[key] : undefined;\n}\n\nfunction restoreStructuredFields(\n doc: StructuredDocumentShape,\n target: Readonly<Record<string, string>>,\n registry: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const current = readStoredDocumentState(doc, registry);\n // A note has no structured fields to restore.\n if (current.documentKind === \"note\") return false;\n // Read both sides by own key only. A field named `constructor` or\n // `toString` that the restored version lacks would otherwise read as the\n // inherited function, which is neither \"absent\" nor a value Loro can store.\n const changes: Array<[string, string | undefined]> = [];\n for (const key of new Set([\n ...Object.keys(current.structuredFields),\n ...Object.keys(target),\n ])) {\n const wanted = ownField(target, key);\n if (ownField(current.structuredFields, key) !== wanted) {\n changes.push([key, wanted]);\n }\n }\n if (changes.length === 0) return false;\n // fromEntries defines every key as an own property, `__proto__` included.\n writeStoredDocumentFields(\n doc,\n current.documentKind,\n Object.fromEntries(changes),\n registry,\n );\n return true;\n}\n\n/**\n * Make the document's rows equal `target`. A row that still exists is patched\n * cell by cell under its own id, a row that is gone from `target` is removed,\n * and a row the document no longer has is added back as a new row with a new\n * id, at the end.\n *\n * The new id is what keeps a restore safe to merge: two devices restoring the\n * same version at once each add their own copy, and both copies stay distinct\n * rows that can be edited or removed. Re-adding under the old id would leave\n * two rows sharing it, with writes reaching only the first. Row order is not\n * restored, because a row cannot be moved.\n */\nfunction restoreRows(\n doc: StructuredDocumentShape,\n target: ReadonlyArray<RestoreRow>,\n attribution: DocumentRowAttribution,\n): boolean {\n const current = listDocumentRows(doc);\n const targetById = new Map(target.map((row) => [row.id, row]));\n const currentIds = new Set(current.map((row) => row.id));\n let changed = false;\n for (const row of current) {\n const wanted = targetById.get(row.id);\n if (wanted === undefined) {\n changed = removeDocumentRow(doc, row.id) || changed;\n } else {\n changed =\n replaceDocumentRowFields(doc, row.id, wanted.fields, attribution) ||\n changed;\n }\n }\n for (const row of target) {\n if (!currentIds.has(row.id)) {\n addDocumentRow(doc, createDocumentRowId(), row.fields, attribution);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Write `content` into the document as ordinary edits and report whether\n * anything changed. Nothing is rewound: the document keeps its whole history\n * and gains the operations that carry it back to this content, so the restore\n * syncs and merges like any other edit.\n */\nexport function restoreDocumentContent(\n doc: RestorableDocument,\n content: DocumentRestoreContent,\n attribution: DocumentRowAttribution,\n registry?: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const textChanged = restoreText(doc, content.text);\n const fieldsChanged = restoreStructuredFields(\n doc,\n content.structuredFields,\n registry,\n );\n const rowsChanged = restoreRows(doc, content.rows, attribution);\n return textChanged || fieldsChanged || rowsChanged;\n}\n"]}
@@ -5,7 +5,7 @@ import { documentProjectionTables } from "../../sqlite/schema/documentProjection
5
5
  import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
6
6
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
7
7
  import { ensureSqlTables, runSerializedSqlMutation, } from "../../sqlite/sqlSchema.js";
8
- import { enqueueDocumentLinkIntent, enqueueDocumentMoveIntent, enqueueDocumentUnlinkIntent, } from "./documentPlacementIntentEnqueue.js";
8
+ import { enqueueDocumentPlacementIntent, } from "./documentPlacementIntentEnqueue.js";
9
9
  export const DOCUMENT_MOVE_INTENT_TYPE = "document.move";
10
10
  const INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);
11
11
  /** Every listed intent's link targets, one keyed read per bind budget. */
@@ -86,15 +86,32 @@ function mapDocumentMoveIntentRecord(row) {
86
86
  updatedAt: row.updatedAt,
87
87
  };
88
88
  }
89
- export const sqlDocumentMoveIntentPersistence = {
90
- async ensureSchema(execSql) {
91
- await ensureSqlTables(execSql, documentPlacementIntentTables);
92
- },
93
- enqueueMoveIntent: enqueueDocumentMoveIntent,
94
- enqueueLinkIntent: enqueueDocumentLinkIntent,
95
- enqueueUnlinkIntent: enqueueDocumentUnlinkIntent,
96
- async listPendingMoveIntents(execSql) {
97
- return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
89
+ /**
90
+ * The document placement intent lane, bound to one executor and clock.
91
+ * `markMoveIntentSynced` opens no transaction of its own: it runs inside the
92
+ * caller's relink commit, so build it from that commit's executor.
93
+ */
94
+ export class DocumentMoveIntentRepository {
95
+ execSql;
96
+ now;
97
+ constructor(execSql, now = () => new Date()) {
98
+ this.execSql = execSql;
99
+ this.now = now;
100
+ }
101
+ async ensureSchema() {
102
+ await ensureSqlTables(this.execSql, documentPlacementIntentTables);
103
+ }
104
+ enqueueMoveIntent(input) {
105
+ return enqueueDocumentPlacementIntent(this.execSql, input, "move", this.now);
106
+ }
107
+ enqueueLinkIntent(input) {
108
+ return enqueueDocumentPlacementIntent(this.execSql, input, "link", this.now);
109
+ }
110
+ enqueueUnlinkIntent(input) {
111
+ return enqueueDocumentPlacementIntent(this.execSql, input, "unlink", this.now);
112
+ }
113
+ async listPendingMoveIntents() {
114
+ return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
98
115
  await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);
99
116
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
100
117
  const rows = await tx
@@ -142,9 +159,9 @@ export const sqlDocumentMoveIntentPersistence = {
142
159
  });
143
160
  });
144
161
  });
145
- },
146
- async markMoveIntentSynced(execSql, input) {
147
- return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
162
+ }
163
+ async markMoveIntentSynced(input) {
164
+ return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
148
165
  const deleted = await lockedExecSql(`DELETE FROM local_intents
149
166
  WHERE lane = ?
150
167
  AND subject_id = ?
@@ -166,10 +183,10 @@ export const sqlDocumentMoveIntentPersistence = {
166
183
  }
167
184
  return deleted.length > 0;
168
185
  });
169
- },
170
- async recordMoveIntentError(execSql, input) {
171
- await getClientSQLitePersistenceRuntime(execSql).guardedTransaction(async (db) => {
172
- const updatedAt = new Date().toISOString();
186
+ }
187
+ async recordMoveIntentError(input) {
188
+ await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(async (db) => {
189
+ const updatedAt = this.now().toISOString();
173
190
  await db
174
191
  .update(localIntents)
175
192
  .set({
@@ -193,18 +210,18 @@ export const sqlDocumentMoveIntentPersistence = {
193
210
  : [])))
194
211
  .run();
195
212
  }, input.stillCurrent ?? (() => true), { behavior: "immediate" });
196
- },
213
+ }
197
214
  /**
198
215
  * Evidence for the org-access-restored re-arm gate: a parked
199
216
  * permission-denied move proves a queued write was refused.
200
217
  */
201
- async hasDeniedMoveIntents(execSql, input) {
202
- await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);
203
- await ensureSqlTables(execSql, [
218
+ async hasDeniedMoveIntents(input) {
219
+ await this.ensureSchema();
220
+ await ensureSqlTables(this.execSql, [
204
221
  ...documentProjectionTables,
205
222
  ...containerTables,
206
223
  ]);
207
- const rows = await execSql(`SELECT intent.subject_id AS document_id
224
+ const rows = await this.execSql(`SELECT intent.subject_id AS document_id
208
225
  FROM local_intents intent
209
226
  ${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : ""}
210
227
  WHERE intent.lane = ?
@@ -217,19 +234,19 @@ export const sqlDocumentMoveIntentPersistence = {
217
234
  ...(input?.organizationId ? [input.organizationId] : []),
218
235
  ]);
219
236
  return rows.length > 0;
220
- },
237
+ }
221
238
  /**
222
239
  * Flip parked permission-denied moves back to pending so the re-armed
223
240
  * structural pass replays them (access restored, or a manual retry scoped
224
241
  * to one document).
225
242
  */
226
- async resetDeniedMoveIntents(execSql, input) {
227
- await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);
228
- await ensureSqlTables(execSql, [
243
+ async resetDeniedMoveIntents(input) {
244
+ await this.ensureSchema();
245
+ await ensureSqlTables(this.execSql, [
229
246
  ...documentProjectionTables,
230
247
  ...containerTables,
231
248
  ]);
232
- await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
249
+ await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
233
250
  // Organization scoping resolves each intent's organization through the
234
251
  // container joins above: restoring one organization's access must not
235
252
  // un-park moves that another organization still denies. Rows with no
@@ -249,7 +266,7 @@ export const sqlDocumentMoveIntentPersistence = {
249
266
  OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)
250
267
  )`
251
268
  : ""}`, [
252
- new Date().toISOString(),
269
+ this.now().toISOString(),
253
270
  LOCAL_INTENT_LANES.documentPlacement,
254
271
  ...DOCUMENT_PLACEMENT_INTENT_TYPES,
255
272
  ...(input?.localId ? [input.localId] : []),
@@ -258,6 +275,6 @@ export const sqlDocumentMoveIntentPersistence = {
258
275
  : []),
259
276
  ]);
260
277
  });
261
- },
262
- };
278
+ }
279
+ }
263
280
  //# sourceMappingURL=documentMoveIntentPersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntentPersistence.js","sourceRoot":"","sources":["documentMoveIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,eAAe,EACf,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EAAE,wBAAwB,EAAE,MAAM,8CAA8C,CAAC;AACxF,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,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kBAAkB,CAAC,iBAAiB;gBACpC,GAAG,+BAA+B;gBAClC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC1C,GAAG,CAAC,KAAK,EAAE,cAAc;oBACvB,CAAC,CAAC,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC;oBAC9D,CAAC,CAAC,EAAE,CAAC;aACR,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containerTables,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport { documentProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentLinkIntent,\n enqueueDocumentMoveIntent,\n enqueueDocumentUnlinkIntent,\n} from \"./documentPlacementIntentEnqueue\";\n\ntype DocumentIntentLinkTarget = {\n containerId: string;\n operation: \"link\" | \"unlink\";\n};\n\nexport const DOCUMENT_MOVE_INTENT_TYPE = \"document.move\";\nconst INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);\n\n/** Every listed intent's link targets, one keyed read per bind budget. */\nasync function loadLinkTargetsByIntent(\n tx: ClientSQLiteTransactionScope,\n intentIds: readonly string[],\n): Promise<ReadonlyMap<string, readonly DocumentIntentLinkTarget[]>> {\n const targetsByIntent = new Map<string, DocumentIntentLinkTarget[]>();\n const uniqueIds = [...new Set(intentIds)];\n for (\n let index = 0;\n index < uniqueIds.length;\n index += INTENT_IDS_PER_STATEMENT\n ) {\n const rows = await tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n intentId: documentIntentLinkTargets.intentId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n uniqueIds.slice(index, index + INTENT_IDS_PER_STATEMENT),\n ),\n );\n for (const { intentId, ...target } of rows) {\n const targets = targetsByIntent.get(intentId) ?? [];\n targets.push(target);\n targetsByIntent.set(intentId, targets);\n }\n }\n return targetsByIntent;\n}\nconst placementLane = inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement);\nexport const DOCUMENT_LINK_INTENT_TYPE = \"document.link\";\nconst DOCUMENT_PLACEMENT_INTENT_TYPES = [\n DOCUMENT_MOVE_INTENT_TYPE,\n DOCUMENT_LINK_INTENT_TYPE,\n];\n\n// Resolves the organization a parked move belongs to, in confidence order:\n// the move's target container, the document's preserved projection\n// attribution, then the container the document currently sits in. Normal\n// saves routinely leave projection attribution empty (deferred-tail\n// reporting resolves through the same container join), so the container rows\n// carry the common case; rows with no resolvable organization stay in every\n// scope (device-first shapes, matching orphan priming).\nconst DENIED_INTENT_ORGANIZATION_SQL = `COALESCE(\n NULLIF(target_container.organization_id, ''),\n NULLIF(projection.organization_id, ''),\n NULLIF(projection_container.organization_id, '')\n)`;\n\nconst DENIED_INTENT_ORGANIZATION_JOINS_SQL = `\n LEFT JOIN containers target_container\n ON target_container.id = intent.target_container_id\n LEFT JOIN document_projection projection\n ON projection.local_id = intent.local_id\n LEFT JOIN containers projection_container\n ON projection_container.id = projection.container_id`;\n\n/**\n * - `pending`: replays on every structural pass.\n * - `blocked`: the last pass could not proceed locally (missing local\n * document / destination); replays, since hydration can heal it.\n * - `denied`: parked on a 403 until the access-restored replay (row 7).\n * - `unavailable`: terminal — after a projection refresh the destination\n * itself is proven deleted (coded 404 on its own projection probe). No\n * mutation 409 is ever terminal: with the destination live it can only\n * name an ancestor or source, and the next pass's fresh paths outrun it.\n * Container ids never return, so no replay can commit the intent as\n * written; it leaves the replay set until the local container tombstone\n * cascade retargets it or the user re-enqueues the move.\n */\nexport type DocumentMoveIntentSyncStatus =\n | \"pending\"\n | \"blocked\"\n | \"denied\"\n | \"unavailable\";\n\nexport interface DocumentMoveIntentRecord {\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n id: string;\n documentId: string;\n intentType:\n | typeof DOCUMENT_MOVE_INTENT_TYPE\n | typeof DOCUMENT_LINK_INTENT_TYPE;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: DocumentMoveIntentSyncStatus;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedDocumentMoveIntentRecord {\n id: string | null;\n documentId: string;\n intentType: string;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string | null;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: string;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction parseDocumentMoveIntentSyncStatus(\n value: unknown,\n): DocumentMoveIntentSyncStatus {\n if (value === \"blocked\" || value === \"denied\" || value === \"unavailable\") {\n return value;\n }\n return \"pending\";\n}\n\nfunction resolveRecordedSyncStatus(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n unavailable?: boolean | undefined;\n}): DocumentMoveIntentSyncStatus {\n if (input.unavailable) return \"unavailable\";\n if (input.denied) return \"denied\";\n return input.blocked ? \"blocked\" : \"pending\";\n}\n\nfunction mapDocumentMoveIntentRecord(\n row: SelectedDocumentMoveIntentRecord,\n): DocumentMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n documentId: row.documentId,\n intentType:\n row.intentType === DOCUMENT_LINK_INTENT_TYPE\n ? DOCUMENT_LINK_INTENT_TYPE\n : DOCUMENT_MOVE_INTENT_TYPE,\n lastAttemptedAt: row.lastAttemptedAt,\n lastError: row.lastError,\n // Placement intents always carry their local document row.\n localId: row.localId ?? \"\",\n replaceLinkedContainers: Boolean(row.replaceLinkedContainers),\n sourceContainerId: row.sourceContainerId,\n syncStatus: parseDocumentMoveIntentSyncStatus(row.syncStatus),\n targetContainerId: row.targetContainerId,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport const sqlDocumentMoveIntentPersistence = {\n async ensureSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n },\n\n enqueueMoveIntent: enqueueDocumentMoveIntent,\n enqueueLinkIntent: enqueueDocumentLinkIntent,\n enqueueUnlinkIntent: enqueueDocumentUnlinkIntent,\n\n async listPendingMoveIntents(\n execSql: ExecSql,\n ): Promise<DocumentMoveIntentRecord[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const rows = await tx\n .select({\n id: localIntents.id,\n documentId: localIntents.subjectId,\n intentType: localIntents.intentType,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n lastError: localIntents.lastError,\n localId: localIntents.localId,\n replaceLinkedContainers: localIntents.replaceLinkedContainers,\n sourceContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n targetContainerId: localIntents.targetContainerId,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n // Blocked intents replay too: \"blocked\" names the reason the last\n // attempt could not proceed (missing local doc / destination), not a\n // terminal verdict. The blocking condition can heal after hydration or\n // recovery, and re-checking is cheap — a still-blocked intent simply\n // re-records its reason without counting as lane progress.\n // Unavailable intents never replay: the server proved a cited container\n // is gone, so every replay would re-issue the same doomed requests\n // (#2278 #4). Only the tombstone cascade or a re-enqueue revives them.\n .where(\n and(\n placementLane,\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n inArray(\n localIntents.intentType,\n DOCUMENT_PLACEMENT_INTENT_TYPES,\n ),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n const targetsByIntent = await loadLinkTargetsByIntent(\n tx,\n rows.map((row) => row.id ?? \"\"),\n );\n return rows.map((row) => {\n const targets = targetsByIntent.get(row.id ?? \"\") ?? [];\n const added = targets\n .filter((target) => target.operation === \"link\")\n .map((target) => target.containerId)\n .sort();\n const removed = targets\n .filter((target) => target.operation === \"unlink\")\n .map((target) => target.containerId)\n .sort();\n return {\n ...mapDocumentMoveIntentRecord(row),\n ...(added.length ? { additionalLinkContainerIds: added } : {}),\n ...(removed.length ? { removedLinkContainerIds: removed } : {}),\n };\n });\n },\n );\n });\n },\n\n async markMoveIntentSynced(\n execSql: ExecSql,\n input: {\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt: string;\n },\n ): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const deleted = await lockedExecSql(\n `DELETE FROM local_intents\n WHERE lane = ?\n AND subject_id = ?\n AND intent_type IN (?, ?)\n AND updated_at = ?\n ${input.expectedIntentId ? \"AND id = ?\" : \"\"}\n RETURNING id`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n input.documentId,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n input.expectedUpdatedAt,\n ...(input.expectedIntentId ? [input.expectedIntentId] : []),\n ],\n );\n for (const { id } of deleted) {\n await getClientSQLitePersistenceRuntime(lockedExecSql)\n .db.delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, String(id)))\n .run();\n }\n return deleted.length > 0;\n });\n },\n\n async recordMoveIntentError(\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n /**\n * A permission denial (403): the intent parks as `denied` — excluded\n * from routine structural replays — until the org-access-restored\n * signal or a manual retry flips it back to pending (edge-case row 7).\n */\n denied?: boolean | undefined;\n documentId: string;\n /** Exact intent revision read by the pass; preferred over wall-clock CAS. */\n expectedIntentId?: string | undefined;\n /**\n * Optimistic concurrency: when given, the error only records against\n * the intent revision the pass read — a re-enqueued move (new\n * updatedAt) is never parked by a stale in-flight failure.\n */\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n /**\n * Server proof that a cited container was deleted (coded 404 or\n * `container_unavailable` 409): the intent parks terminally as\n * `unavailable`, outside every replay, until the tombstone cascade\n * retargets it or a re-enqueue replaces it. Outranks `denied`: a\n * restored permission cannot revive a deleted container.\n */\n unavailable?: boolean | undefined;\n },\n ): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).guardedTransaction(\n async (db) => {\n const updatedAt = new Date().toISOString();\n await db\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: resolveRecordedSyncStatus(input),\n updatedAt,\n })\n .where(\n and(\n placementLane,\n eq(localIntents.subjectId, input.documentId),\n // Blocked/denied rows must stay updatable: a retried intent\n // records its fresh outcome, and a transient failure flips it\n // back to pending instead of freezing it forever.\n inArray(localIntents.syncStatus, [\n \"pending\",\n \"blocked\",\n \"denied\",\n ]),\n inArray(localIntents.intentType, DOCUMENT_PLACEMENT_INTENT_TYPES),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n },\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n },\n /**\n * Evidence for the org-access-restored re-arm gate: a parked\n * permission-denied move proves a queued write was refused.\n */\n async hasDeniedMoveIntents(\n execSql: ExecSql,\n input?: { organizationId?: string },\n ): Promise<boolean> {\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n const rows = await execSql(\n `SELECT intent.subject_id AS document_id\n FROM local_intents intent\n ${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : \"\"}\n WHERE intent.lane = ?\n AND intent.sync_status = 'denied'\n AND intent.intent_type IN (?, ?)\n ${input?.organizationId ? `AND (${DENIED_INTENT_ORGANIZATION_SQL} = ? OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)` : \"\"}\n LIMIT 1`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.organizationId ? [input.organizationId] : []),\n ],\n );\n return rows.length > 0;\n },\n /**\n * Flip parked permission-denied moves back to pending so the re-armed\n * structural pass replays them (access restored, or a manual retry scoped\n * to one document).\n */\n async resetDeniedMoveIntents(\n execSql: ExecSql,\n input?: { localId?: string; organizationId?: string },\n ): Promise<void> {\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // Organization scoping resolves each intent's organization through the\n // container joins above: restoring one organization's access must not\n // un-park moves that another organization still denies. Rows with no\n // resolvable organization are included (device-first shapes).\n await lockedExecSql(\n `UPDATE local_intents\n SET sync_status = 'pending', updated_at = ?\n WHERE lane = ?\n AND sync_status = 'denied'\n AND intent_type IN (?, ?)\n ${input?.localId ? \"AND local_id = ?\" : \"\"}\n ${\n input?.organizationId\n ? `AND local_id IN (\n SELECT intent.local_id FROM local_intents intent\n ${DENIED_INTENT_ORGANIZATION_JOINS_SQL}\n WHERE intent.lane = ?\n AND (${DENIED_INTENT_ORGANIZATION_SQL} = ?\n OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)\n )`\n : \"\"\n }`,\n [\n new Date().toISOString(),\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.localId ? [input.localId] : []),\n ...(input?.organizationId\n ? [LOCAL_INTENT_LANES.documentPlacement, input.organizationId]\n : []),\n ],\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"documentMoveIntentPersistence.js","sourceRoot":"","sources":["documentMoveIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,eAAe,EACf,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EAAE,wBAAwB,EAAE,MAAM,8CAA8C,CAAC;AACxF,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,8BAA8B,GAE/B,MAAM,kCAAkC,CAAC;AAO1C,MAAM,CAAC,MAAM,yBAAyB,GAAG,eAAe,CAAC;AACzD,MAAM,wBAAwB,GAAG,sBAAsB,CAAC,CAAC,CAAC,CAAC;AAE3D,0EAA0E;AAC1E,KAAK,UAAU,uBAAuB,CACpC,EAAgC,EAChC,SAA4B;IAE5B,MAAM,eAAe,GAAG,IAAI,GAAG,EAAsC,CAAC;IACtE,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAC1C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,SAAS,CAAC,MAAM,EACxB,KAAK,IAAI,wBAAwB,EACjC,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,EAAE;aAClB,MAAM,CAAC;YACN,WAAW,EAAE,yBAAyB,CAAC,WAAW;YAClD,QAAQ,EAAE,yBAAyB,CAAC,QAAQ;YAC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AC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC1C,GAAG,CAAC,KAAK,EAAE,cAAc;oBACvB,CAAC,CAAC,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC;oBAC9D,CAAC,CAAC,EAAE,CAAC;aACR,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containerTables,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport { documentProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentPlacementIntent,\n type PlacementIntentInput,\n} from \"./documentPlacementIntentEnqueue\";\n\ntype DocumentIntentLinkTarget = {\n containerId: string;\n operation: \"link\" | \"unlink\";\n};\n\nexport const DOCUMENT_MOVE_INTENT_TYPE = \"document.move\";\nconst INTENT_IDS_PER_STATEMENT = sqliteRowsPerStatement(1);\n\n/** Every listed intent's link targets, one keyed read per bind budget. */\nasync function loadLinkTargetsByIntent(\n tx: ClientSQLiteTransactionScope,\n intentIds: readonly string[],\n): Promise<ReadonlyMap<string, readonly DocumentIntentLinkTarget[]>> {\n const targetsByIntent = new Map<string, DocumentIntentLinkTarget[]>();\n const uniqueIds = [...new Set(intentIds)];\n for (\n let index = 0;\n index < uniqueIds.length;\n index += INTENT_IDS_PER_STATEMENT\n ) {\n const rows = await tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n intentId: documentIntentLinkTargets.intentId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n uniqueIds.slice(index, index + INTENT_IDS_PER_STATEMENT),\n ),\n );\n for (const { intentId, ...target } of rows) {\n const targets = targetsByIntent.get(intentId) ?? [];\n targets.push(target);\n targetsByIntent.set(intentId, targets);\n }\n }\n return targetsByIntent;\n}\nconst placementLane = inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement);\nexport const DOCUMENT_LINK_INTENT_TYPE = \"document.link\";\nconst DOCUMENT_PLACEMENT_INTENT_TYPES = [\n DOCUMENT_MOVE_INTENT_TYPE,\n DOCUMENT_LINK_INTENT_TYPE,\n];\n\n// Resolves the organization a parked move belongs to, in confidence order:\n// the move's target container, the document's preserved projection\n// attribution, then the container the document currently sits in. Normal\n// saves routinely leave projection attribution empty (deferred-tail\n// reporting resolves through the same container join), so the container rows\n// carry the common case; rows with no resolvable organization stay in every\n// scope (device-first shapes, matching orphan priming).\nconst DENIED_INTENT_ORGANIZATION_SQL = `COALESCE(\n NULLIF(target_container.organization_id, ''),\n NULLIF(projection.organization_id, ''),\n NULLIF(projection_container.organization_id, '')\n)`;\n\nconst DENIED_INTENT_ORGANIZATION_JOINS_SQL = `\n LEFT JOIN containers target_container\n ON target_container.id = intent.target_container_id\n LEFT JOIN document_projection projection\n ON projection.local_id = intent.local_id\n LEFT JOIN containers projection_container\n ON projection_container.id = projection.container_id`;\n\n/**\n * - `pending`: replays on every structural pass.\n * - `blocked`: the last pass could not proceed locally (missing local\n * document / destination); replays, since hydration can heal it.\n * - `denied`: parked on a 403 until the access-restored replay (row 7).\n * - `unavailable`: terminal — after a projection refresh the destination\n * itself is proven deleted (coded 404 on its own projection probe). No\n * mutation 409 is ever terminal: with the destination live it can only\n * name an ancestor or source, and the next pass's fresh paths outrun it.\n * Container ids never return, so no replay can commit the intent as\n * written; it leaves the replay set until the local container tombstone\n * cascade retargets it or the user re-enqueues the move.\n */\nexport type DocumentMoveIntentSyncStatus =\n | \"pending\"\n | \"blocked\"\n | \"denied\"\n | \"unavailable\";\n\nexport interface DocumentMoveIntentRecord {\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n id: string;\n documentId: string;\n intentType:\n | typeof DOCUMENT_MOVE_INTENT_TYPE\n | typeof DOCUMENT_LINK_INTENT_TYPE;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: DocumentMoveIntentSyncStatus;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedDocumentMoveIntentRecord {\n id: string | null;\n documentId: string;\n intentType: string;\n lastAttemptedAt: string | null;\n lastError: string | null;\n localId: string | null;\n replaceLinkedContainers: boolean;\n sourceContainerId: string | null;\n syncStatus: string;\n targetContainerId: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction parseDocumentMoveIntentSyncStatus(\n value: unknown,\n): DocumentMoveIntentSyncStatus {\n if (value === \"blocked\" || value === \"denied\" || value === \"unavailable\") {\n return value;\n }\n return \"pending\";\n}\n\nfunction resolveRecordedSyncStatus(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n unavailable?: boolean | undefined;\n}): DocumentMoveIntentSyncStatus {\n if (input.unavailable) return \"unavailable\";\n if (input.denied) return \"denied\";\n return input.blocked ? \"blocked\" : \"pending\";\n}\n\nfunction mapDocumentMoveIntentRecord(\n row: SelectedDocumentMoveIntentRecord,\n): DocumentMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n documentId: row.documentId,\n intentType:\n row.intentType === DOCUMENT_LINK_INTENT_TYPE\n ? DOCUMENT_LINK_INTENT_TYPE\n : DOCUMENT_MOVE_INTENT_TYPE,\n lastAttemptedAt: row.lastAttemptedAt,\n lastError: row.lastError,\n // Placement intents always carry their local document row.\n localId: row.localId ?? \"\",\n replaceLinkedContainers: Boolean(row.replaceLinkedContainers),\n sourceContainerId: row.sourceContainerId,\n syncStatus: parseDocumentMoveIntentSyncStatus(row.syncStatus),\n targetContainerId: row.targetContainerId,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\n/**\n * The document placement intent lane, bound to one executor and clock.\n * `markMoveIntentSynced` opens no transaction of its own: it runs inside the\n * caller's relink commit, so build it from that commit's executor.\n */\nexport class DocumentMoveIntentRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentPlacementIntentTables);\n }\n\n enqueueMoveIntent(input: PlacementIntentInput): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"move\",\n this.now,\n );\n }\n\n enqueueLinkIntent(\n input: PlacementIntentInput & { sourceContainerId: string },\n ): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"link\",\n this.now,\n );\n }\n\n enqueueUnlinkIntent(\n input: PlacementIntentInput & { removedContainerId: string },\n ): Promise<void> {\n return enqueueDocumentPlacementIntent(\n this.execSql,\n input,\n \"unlink\",\n this.now,\n );\n }\n\n async listPendingMoveIntents(): Promise<DocumentMoveIntentRecord[]> {\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const rows = await tx\n .select({\n id: localIntents.id,\n documentId: localIntents.subjectId,\n intentType: localIntents.intentType,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n lastError: localIntents.lastError,\n localId: localIntents.localId,\n replaceLinkedContainers: localIntents.replaceLinkedContainers,\n sourceContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n targetContainerId: localIntents.targetContainerId,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n // Blocked intents replay too: \"blocked\" names the reason the last\n // attempt could not proceed (missing local doc / destination), not a\n // terminal verdict. The blocking condition can heal after hydration or\n // recovery, and re-checking is cheap — a still-blocked intent simply\n // re-records its reason without counting as lane progress.\n // Unavailable intents never replay: the server proved a cited container\n // is gone, so every replay would re-issue the same doomed requests\n // (#2278 #4). Only the tombstone cascade or a re-enqueue revives them.\n .where(\n and(\n placementLane,\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n inArray(\n localIntents.intentType,\n DOCUMENT_PLACEMENT_INTENT_TYPES,\n ),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n const targetsByIntent = await loadLinkTargetsByIntent(\n tx,\n rows.map((row) => row.id ?? \"\"),\n );\n return rows.map((row) => {\n const targets = targetsByIntent.get(row.id ?? \"\") ?? [];\n const added = targets\n .filter((target) => target.operation === \"link\")\n .map((target) => target.containerId)\n .sort();\n const removed = targets\n .filter((target) => target.operation === \"unlink\")\n .map((target) => target.containerId)\n .sort();\n return {\n ...mapDocumentMoveIntentRecord(row),\n ...(added.length ? { additionalLinkContainerIds: added } : {}),\n ...(removed.length ? { removedLinkContainerIds: removed } : {}),\n };\n });\n },\n );\n });\n }\n\n async markMoveIntentSynced(input: {\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt: string;\n }): Promise<boolean> {\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n const deleted = await lockedExecSql(\n `DELETE FROM local_intents\n WHERE lane = ?\n AND subject_id = ?\n AND intent_type IN (?, ?)\n AND updated_at = ?\n ${input.expectedIntentId ? \"AND id = ?\" : \"\"}\n RETURNING id`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n input.documentId,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n input.expectedUpdatedAt,\n ...(input.expectedIntentId ? [input.expectedIntentId] : []),\n ],\n );\n for (const { id } of deleted) {\n await getClientSQLitePersistenceRuntime(lockedExecSql)\n .db.delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, String(id)))\n .run();\n }\n return deleted.length > 0;\n });\n }\n\n async recordMoveIntentError(input: {\n blocked?: boolean | undefined;\n /**\n * A permission denial (403): the intent parks as `denied` — excluded\n * from routine structural replays — until the org-access-restored\n * signal or a manual retry flips it back to pending (edge-case row 7).\n */\n denied?: boolean | undefined;\n documentId: string;\n /** Exact intent revision read by the pass; preferred over wall-clock CAS. */\n expectedIntentId?: string | undefined;\n /**\n * Optimistic concurrency: when given, the error only records against\n * the intent revision the pass read — a re-enqueued move (new\n * updatedAt) is never parked by a stale in-flight failure.\n */\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n /**\n * Server proof that a cited container was deleted (coded 404 or\n * `container_unavailable` 409): the intent parks terminally as\n * `unavailable`, outside every replay, until the tombstone cascade\n * retargets it or a re-enqueue replaces it. Outranks `denied`: a\n * restored permission cannot revive a deleted container.\n */\n unavailable?: boolean | undefined;\n }): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (db) => {\n const updatedAt = this.now().toISOString();\n await db\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: resolveRecordedSyncStatus(input),\n updatedAt,\n })\n .where(\n and(\n placementLane,\n eq(localIntents.subjectId, input.documentId),\n // Blocked/denied rows must stay updatable: a retried intent\n // records its fresh outcome, and a transient failure flips it\n // back to pending instead of freezing it forever.\n inArray(localIntents.syncStatus, [\n \"pending\",\n \"blocked\",\n \"denied\",\n ]),\n inArray(localIntents.intentType, DOCUMENT_PLACEMENT_INTENT_TYPES),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n },\n input.stillCurrent ?? (() => true),\n { behavior: \"immediate\" },\n );\n }\n\n /**\n * Evidence for the org-access-restored re-arm gate: a parked\n * permission-denied move proves a queued write was refused.\n */\n async hasDeniedMoveIntents(input?: {\n organizationId?: string;\n }): Promise<boolean> {\n await this.ensureSchema();\n await ensureSqlTables(this.execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n const rows = await this.execSql(\n `SELECT intent.subject_id AS document_id\n FROM local_intents intent\n ${input?.organizationId ? DENIED_INTENT_ORGANIZATION_JOINS_SQL : \"\"}\n WHERE intent.lane = ?\n AND intent.sync_status = 'denied'\n AND intent.intent_type IN (?, ?)\n ${input?.organizationId ? `AND (${DENIED_INTENT_ORGANIZATION_SQL} = ? OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)` : \"\"}\n LIMIT 1`,\n [\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.organizationId ? [input.organizationId] : []),\n ],\n );\n return rows.length > 0;\n }\n\n /**\n * Flip parked permission-denied moves back to pending so the re-armed\n * structural pass replays them (access restored, or a manual retry scoped\n * to one document).\n */\n async resetDeniedMoveIntents(input?: {\n localId?: string;\n organizationId?: string;\n }): Promise<void> {\n await this.ensureSchema();\n await ensureSqlTables(this.execSql, [\n ...documentProjectionTables,\n ...containerTables,\n ]);\n await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n // Organization scoping resolves each intent's organization through the\n // container joins above: restoring one organization's access must not\n // un-park moves that another organization still denies. Rows with no\n // resolvable organization are included (device-first shapes).\n await lockedExecSql(\n `UPDATE local_intents\n SET sync_status = 'pending', updated_at = ?\n WHERE lane = ?\n AND sync_status = 'denied'\n AND intent_type IN (?, ?)\n ${input?.localId ? \"AND local_id = ?\" : \"\"}\n ${\n input?.organizationId\n ? `AND local_id IN (\n SELECT intent.local_id FROM local_intents intent\n ${DENIED_INTENT_ORGANIZATION_JOINS_SQL}\n WHERE intent.lane = ?\n AND (${DENIED_INTENT_ORGANIZATION_SQL} = ?\n OR ${DENIED_INTENT_ORGANIZATION_SQL} IS NULL)\n )`\n : \"\"\n }`,\n [\n this.now().toISOString(),\n LOCAL_INTENT_LANES.documentPlacement,\n ...DOCUMENT_PLACEMENT_INTENT_TYPES,\n ...(input?.localId ? [input.localId] : []),\n ...(input?.organizationId\n ? [LOCAL_INTENT_LANES.documentPlacement, input.organizationId]\n : []),\n ],\n );\n });\n }\n}\n"]}
@@ -94,7 +94,7 @@ async function ensurePlacementIntentSchema(execSql) {
94
94
  await ensureSqlTables(execSql, documentPlacementIntentTables);
95
95
  await ensureSqlTables(execSql, documentContainerProjectionTables);
96
96
  }
97
- async function enqueuePlacementIntentRows(tx, input, operation) {
97
+ async function enqueuePlacementIntentRows(tx, input, operation, now) {
98
98
  const [previous] = await tx
99
99
  .select()
100
100
  .from(localIntents)
@@ -105,7 +105,7 @@ async function enqueuePlacementIntentRows(tx, input, operation) {
105
105
  : [];
106
106
  const targets = resolveTargets(input, previousTargets, operation, operation === "move" ? await loadSurvivingMoveTarget(tx, previous) : null);
107
107
  const id = input.id ?? crypto.randomUUID();
108
- const updatedAt = new Date().toISOString();
108
+ const updatedAt = now().toISOString();
109
109
  // An additive intent retains the active placement and any pending move.
110
110
  // Its targets are separate from the discovery projection: only explicit
111
111
  // user additions may be replayed, never stale server-discovered links.
@@ -143,21 +143,13 @@ async function enqueuePlacementIntentRows(tx, input, operation) {
143
143
  /** Only for a document commit side effect: failures must escape its transaction. */
144
144
  export async function enqueueDocumentPlacementIntentInTransaction(transactionExecSql, input, operation) {
145
145
  await ensurePlacementIntentSchema(transactionExecSql);
146
- await enqueuePlacementIntentRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, input, operation);
146
+ await enqueuePlacementIntentRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, input, operation, () => new Date());
147
147
  }
148
- async function enqueuePlacementIntent(execSql, input, operation) {
148
+ /** Serialized standalone enqueue: one plain transaction under the lock. */
149
+ export async function enqueueDocumentPlacementIntent(execSql, input, operation, now) {
149
150
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
150
151
  await ensurePlacementIntentSchema(lockedExecSql);
151
- await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) => enqueuePlacementIntentRows(tx, input, operation));
152
+ await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) => enqueuePlacementIntentRows(tx, input, operation, now));
152
153
  });
153
154
  }
154
- export function enqueueDocumentMoveIntent(execSql, input) {
155
- return enqueuePlacementIntent(execSql, input, "move");
156
- }
157
- export function enqueueDocumentLinkIntent(execSql, input) {
158
- return enqueuePlacementIntent(execSql, input, "link");
159
- }
160
- export function enqueueDocumentUnlinkIntent(execSql, input) {
161
- return enqueuePlacementIntent(execSql, input, "unlink");
162
- }
163
155
  //# sourceMappingURL=documentPlacementIntentEnqueue.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"documentPlacementIntentEnqueue.js","sourceRoot":"","sources":["documentPlacementIntentEnqueue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAYhC,KAAK,UAAU,6BAA6B,CAC1C,EAAgC,EAChC,QAAgB;IAEhB,OAAO,EAAE;SACN,MAAM,CAAC;QACN,WAAW,EAAE,yBAAyB,CAAC,WAAW;QAClD,SAAS,EAAE,yBAAyB,CAAC,S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,CAAC,EAAE,EAAE,EAAE,CACxE,0BAA0B,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,CAAC,CACjD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,OAAgB,EAChB,KAA2B;IAE3B,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,OAAgB,EAChB,KAA2D;IAE3D,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,OAAgB,EAChB,KAA4D;IAE5D,OAAO,sBAAsB,CAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\ninterface PlacementIntentInput {\n id?: string | undefined;\n documentId: string;\n localId: string;\n replaceLinkedContainers?: boolean | undefined;\n removedContainerId?: string | undefined;\n sourceContainerId?: string | null | undefined;\n targetContainerId: string;\n}\n\nasync function loadDocumentIntentLinkTargets(\n tx: ClientSQLiteTransactionScope,\n intentId: string,\n) {\n return tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, intentId));\n}\n\ntype LinkTarget = { containerId: string; operation: \"link\" | \"unlink\" };\n\nasync function loadSurvivingMoveTarget(\n tx: ClientSQLiteTransactionScope,\n previous: typeof localIntents.$inferSelect | undefined,\n): Promise<string | null> {\n if (previous?.intentType !== \"document.move\") return null;\n const [link] = await tx\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(\n and(\n eq(documentContainerProjection.documentId, previous.subjectId),\n eq(documentContainerProjection.containerId, previous.targetContainerId),\n ),\n )\n .limit(1);\n return link?.containerId ?? null;\n}\n\nfunction resolveTargets(\n input: PlacementIntentInput,\n previous: LinkTarget[],\n operation: \"move\" | \"link\" | \"unlink\",\n previousMoveTarget: string | null,\n): LinkTarget[] {\n const targets = new Map(\n previous.map((target) => [target.containerId, target.operation]),\n );\n if (operation === \"link\") targets.set(input.targetContainerId, \"link\");\n else if (operation === \"unlink\") {\n if (!input.removedContainerId)\n throw new Error(\"Unlink intent requires a removed container\");\n targets.set(input.removedContainerId, \"unlink\");\n } else if (input.replaceLinkedContainers) targets.clear();\n else {\n if (\n previousMoveTarget &&\n previousMoveTarget !== input.sourceContainerId &&\n previousMoveTarget !== input.targetContainerId &&\n targets.get(previousMoveTarget) !== \"unlink\"\n ) {\n targets.set(previousMoveTarget, \"link\");\n }\n targets.delete(input.targetContainerId);\n if (\n input.sourceContainerId &&\n input.sourceContainerId !== input.targetContainerId\n )\n targets.set(input.sourceContainerId, \"unlink\");\n }\n return uniqueSortedStrings([...targets.keys()]).map((containerId) => ({\n containerId,\n operation: targets.get(containerId) ?? \"link\",\n }));\n}\n\nfunction placementIntentType(\n operation: \"move\" | \"link\" | \"unlink\",\n previous: typeof localIntents.$inferSelect | undefined,\n): \"document.move\" | \"document.link\" {\n return operation === \"move\" || previous?.intentType === \"document.move\"\n ? \"document.move\"\n : \"document.link\";\n}\n\nfunction resolveUnlinkPlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n) {\n return {\n sourceContainerId:\n previous?.intentType === \"document.move\"\n ? previous.sourceContainerId\n : input.targetContainerId,\n targetContainerId:\n previous?.intentType === \"document.move\" &&\n previous.targetContainerId !== input.removedContainerId\n ? previous.targetContainerId\n : input.targetContainerId,\n replaceLinkedContainers: previous?.replaceLinkedContainers ?? false,\n };\n}\n\nfunction resolvePlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n operation: \"move\" | \"link\" | \"unlink\",\n) {\n if (operation === \"unlink\") {\n return resolveUnlinkPlacement(input, previous);\n }\n const linkOnly = operation === \"link\";\n const sourceContainerId =\n previous?.intentType === \"document.move\"\n ? (previous.sourceContainerId ?? input.sourceContainerId ?? null)\n : (input.sourceContainerId ?? null);\n return {\n sourceContainerId: linkOnly\n ? (previous?.sourceContainerId ?? input.sourceContainerId ?? null)\n : sourceContainerId,\n targetContainerId: linkOnly\n ? (previous?.targetContainerId ??\n input.sourceContainerId ??\n input.targetContainerId)\n : input.targetContainerId,\n replaceLinkedContainers:\n previous?.replaceLinkedContainers ||\n (input.replaceLinkedContainers ?? false),\n };\n}\n\nasync function ensurePlacementIntentSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n}\n\nasync function enqueuePlacementIntentRows(\n tx: ClientSQLiteTransactionScope,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n const [previous] = await tx\n .select()\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, input.documentId),\n ),\n )\n .limit(1);\n const previousTargets = previous?.id\n ? await loadDocumentIntentLinkTargets(tx, previous.id)\n : [];\n const targets = resolveTargets(\n input,\n previousTargets,\n operation,\n operation === \"move\" ? await loadSurvivingMoveTarget(tx, previous) : null,\n );\n const id = input.id ?? crypto.randomUUID();\n const updatedAt = new Date().toISOString();\n // An additive intent retains the active placement and any pending move.\n // Its targets are separate from the discovery projection: only explicit\n // user additions may be replayed, never stale server-discovered links.\n const next = {\n id,\n lane: LOCAL_INTENT_LANES.documentPlacement,\n subjectId: input.documentId,\n localId: input.localId,\n intentType: placementIntentType(operation, previous),\n lastAttemptedAt: null,\n lastError: null,\n syncStatus: \"pending\",\n updatedAt,\n ...resolvePlacement(input, previous, operation),\n };\n await tx\n .insert(localIntents)\n .values({ ...next, createdAt: updatedAt })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: next,\n })\n .run();\n if (previous?.id)\n await tx\n .delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, previous.id))\n .run();\n if (targets.length)\n await tx\n .insert(documentIntentLinkTargets)\n .values(targets.map((target) => ({ intentId: id, ...target })))\n .run();\n}\n\n/** Only for a document commit side effect: failures must escape its transaction. */\nexport async function enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await ensurePlacementIntentSchema(transactionExecSql);\n await enqueuePlacementIntentRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n input,\n operation,\n );\n}\n\nasync function enqueuePlacementIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensurePlacementIntentSchema(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) =>\n enqueuePlacementIntentRows(tx, input, operation),\n );\n });\n}\n\nexport function enqueueDocumentMoveIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"move\");\n}\n\nexport function enqueueDocumentLinkIntent(\n execSql: ExecSql,\n input: PlacementIntentInput & { sourceContainerId: string },\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"link\");\n}\n\nexport function enqueueDocumentUnlinkIntent(\n execSql: ExecSql,\n input: PlacementIntentInput & { removedContainerId: string },\n): Promise<void> {\n return enqueuePlacementIntent(execSql, input, \"unlink\");\n}\n"]}
1
+ {"version":3,"file":"documentPlacementIntentEnqueue.js","sourceRoot":"","sources":["documentPlacementIntentEnqueue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAYhC,KAAK,UAAU,6BAA6B,CAC1C,EAAgC,EAChC,QAAgB;IAEhB,OAAO,EAAE;SACN,MAAM,CAAC;QACN,WAAW,EAAE,yBAAyB,CAAC,WAAW;QAClD,SAAS,EAAE,yBAAyB,CAAC,SAAS;KAC/C,CAAC;SACD,IAAI,CAAC,yBAAyB,CAAC;SAC/B,KAAK,CAAC,EAAE,CAAC,yBAAyB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC7D,CAAC;AAID,KAAK,UAAU,uBAAuB,CACpC,EAAgC,EAChC,QAAsD;IAEtD,IAAI,QAAQ,EAAE,UAAU,KAAK,eAAe;QAAE,OAAO,IAAI,CAAC;IAC1D,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,EAAE;SACpB,MAAM,CAAC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AAE;aACL,MAAM,CAAC,yBAAyB,CAAC;aACjC,KAAK,CAAC,EAAE,CAAC,yBAAyB,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;aAC1D,GAAG,EAAE,CAAC;IACX,IAAI,OAAO,CAAC,MAAM;QAChB,MAAM,EAAE;aACL,MAAM,CAAC,yBAAyB,CAAC;aACjC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC;aAC9D,GAAG,EAAE,CAAC;AACb,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,2CAA2C,CAC/D,kBAA2B,EAC3B,KAA2B,EAC3B,SAAqC;IAErC,MAAM,2BAA2B,CAAC,kBAAkB,CAAC,CAAC;IACtD,MAAM,0BAA0B,CAC9B,iCAAiC,CAAC,kBAAkB,CAAC,CAAC,EAAE,EACxD,KAAK,EACL,SAAS,EACT,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CACjB,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,OAAgB,EAChB,KAA2B,EAC3B,SAAqC,EACrC,GAAe;IAEf,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC9D,MAAM,2BAA2B,CAAC,aAAa,CAAC,CAAC;QACjD,MAAM,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CACxE,0BAA0B,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,CAAC,CACtD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\nexport interface PlacementIntentInput {\n id?: string | undefined;\n documentId: string;\n localId: string;\n replaceLinkedContainers?: boolean | undefined;\n removedContainerId?: string | undefined;\n sourceContainerId?: string | null | undefined;\n targetContainerId: string;\n}\n\nasync function loadDocumentIntentLinkTargets(\n tx: ClientSQLiteTransactionScope,\n intentId: string,\n) {\n return tx\n .select({\n containerId: documentIntentLinkTargets.containerId,\n operation: documentIntentLinkTargets.operation,\n })\n .from(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, intentId));\n}\n\ntype LinkTarget = { containerId: string; operation: \"link\" | \"unlink\" };\n\nasync function loadSurvivingMoveTarget(\n tx: ClientSQLiteTransactionScope,\n previous: typeof localIntents.$inferSelect | undefined,\n): Promise<string | null> {\n if (previous?.intentType !== \"document.move\") return null;\n const [link] = await tx\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(\n and(\n eq(documentContainerProjection.documentId, previous.subjectId),\n eq(documentContainerProjection.containerId, previous.targetContainerId),\n ),\n )\n .limit(1);\n return link?.containerId ?? null;\n}\n\nfunction resolveTargets(\n input: PlacementIntentInput,\n previous: LinkTarget[],\n operation: \"move\" | \"link\" | \"unlink\",\n previousMoveTarget: string | null,\n): LinkTarget[] {\n const targets = new Map(\n previous.map((target) => [target.containerId, target.operation]),\n );\n if (operation === \"link\") targets.set(input.targetContainerId, \"link\");\n else if (operation === \"unlink\") {\n if (!input.removedContainerId)\n throw new Error(\"Unlink intent requires a removed container\");\n targets.set(input.removedContainerId, \"unlink\");\n } else if (input.replaceLinkedContainers) targets.clear();\n else {\n if (\n previousMoveTarget &&\n previousMoveTarget !== input.sourceContainerId &&\n previousMoveTarget !== input.targetContainerId &&\n targets.get(previousMoveTarget) !== \"unlink\"\n ) {\n targets.set(previousMoveTarget, \"link\");\n }\n targets.delete(input.targetContainerId);\n if (\n input.sourceContainerId &&\n input.sourceContainerId !== input.targetContainerId\n )\n targets.set(input.sourceContainerId, \"unlink\");\n }\n return uniqueSortedStrings([...targets.keys()]).map((containerId) => ({\n containerId,\n operation: targets.get(containerId) ?? \"link\",\n }));\n}\n\nfunction placementIntentType(\n operation: \"move\" | \"link\" | \"unlink\",\n previous: typeof localIntents.$inferSelect | undefined,\n): \"document.move\" | \"document.link\" {\n return operation === \"move\" || previous?.intentType === \"document.move\"\n ? \"document.move\"\n : \"document.link\";\n}\n\nfunction resolveUnlinkPlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n) {\n return {\n sourceContainerId:\n previous?.intentType === \"document.move\"\n ? previous.sourceContainerId\n : input.targetContainerId,\n targetContainerId:\n previous?.intentType === \"document.move\" &&\n previous.targetContainerId !== input.removedContainerId\n ? previous.targetContainerId\n : input.targetContainerId,\n replaceLinkedContainers: previous?.replaceLinkedContainers ?? false,\n };\n}\n\nfunction resolvePlacement(\n input: PlacementIntentInput,\n previous: typeof localIntents.$inferSelect | undefined,\n operation: \"move\" | \"link\" | \"unlink\",\n) {\n if (operation === \"unlink\") {\n return resolveUnlinkPlacement(input, previous);\n }\n const linkOnly = operation === \"link\";\n const sourceContainerId =\n previous?.intentType === \"document.move\"\n ? (previous.sourceContainerId ?? input.sourceContainerId ?? null)\n : (input.sourceContainerId ?? null);\n return {\n sourceContainerId: linkOnly\n ? (previous?.sourceContainerId ?? input.sourceContainerId ?? null)\n : sourceContainerId,\n targetContainerId: linkOnly\n ? (previous?.targetContainerId ??\n input.sourceContainerId ??\n input.targetContainerId)\n : input.targetContainerId,\n replaceLinkedContainers:\n previous?.replaceLinkedContainers ||\n (input.replaceLinkedContainers ?? false),\n };\n}\n\nasync function ensurePlacementIntentSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n}\n\nasync function enqueuePlacementIntentRows(\n tx: ClientSQLiteTransactionScope,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n now: () => Date,\n): Promise<void> {\n const [previous] = await tx\n .select()\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, input.documentId),\n ),\n )\n .limit(1);\n const previousTargets = previous?.id\n ? await loadDocumentIntentLinkTargets(tx, previous.id)\n : [];\n const targets = resolveTargets(\n input,\n previousTargets,\n operation,\n operation === \"move\" ? await loadSurvivingMoveTarget(tx, previous) : null,\n );\n const id = input.id ?? crypto.randomUUID();\n const updatedAt = now().toISOString();\n // An additive intent retains the active placement and any pending move.\n // Its targets are separate from the discovery projection: only explicit\n // user additions may be replayed, never stale server-discovered links.\n const next = {\n id,\n lane: LOCAL_INTENT_LANES.documentPlacement,\n subjectId: input.documentId,\n localId: input.localId,\n intentType: placementIntentType(operation, previous),\n lastAttemptedAt: null,\n lastError: null,\n syncStatus: \"pending\",\n updatedAt,\n ...resolvePlacement(input, previous, operation),\n };\n await tx\n .insert(localIntents)\n .values({ ...next, createdAt: updatedAt })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: next,\n })\n .run();\n if (previous?.id)\n await tx\n .delete(documentIntentLinkTargets)\n .where(eq(documentIntentLinkTargets.intentId, previous.id))\n .run();\n if (targets.length)\n await tx\n .insert(documentIntentLinkTargets)\n .values(targets.map((target) => ({ intentId: id, ...target })))\n .run();\n}\n\n/** Only for a document commit side effect: failures must escape its transaction. */\nexport async function enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n): Promise<void> {\n await ensurePlacementIntentSchema(transactionExecSql);\n await enqueuePlacementIntentRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n input,\n operation,\n () => new Date(),\n );\n}\n\n/** Serialized standalone enqueue: one plain transaction under the lock. */\nexport async function enqueueDocumentPlacementIntent(\n execSql: ExecSql,\n input: PlacementIntentInput,\n operation: \"move\" | \"link\" | \"unlink\",\n now: () => Date,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensurePlacementIntentSchema(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction((tx) =>\n enqueuePlacementIntentRows(tx, input, operation, now),\n );\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.208",
3
+ "version": "0.1.210",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,8 +1,8 @@
1
- import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
1
+ import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
2
  export async function recordPendingDocumentMoveIntentError(input) {
3
3
  if (!input.isCurrent())
4
4
  return false;
5
- await sqlDocumentMoveIntentPersistence.recordMoveIntentError(input.state.runtime.infra.execSql, {
5
+ await new DocumentMoveIntentRepository(input.state.runtime.infra.execSql).recordMoveIntentError({
6
6
  blocked: input.blocked,
7
7
  denied: input.denied,
8
8
  documentId: input.documentId,
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntentErrors.js","sourceRoot":"","sources":["documentMoveIntentErrors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAG9H,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAU1D;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,gCAAgC,CAAC,qBAAqB,CAC1D,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC;QACE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,SAAS;QAC7B,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CACF,CAAC;IACF,OAAO,KAAK,CAAC,SAAS,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport async function recordPendingDocumentMoveIntentError(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n isCurrent: () => boolean;\n message: string;\n state: { runtime: ContainerContentsWorkflowRuntime };\n unavailable?: boolean | undefined;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n await sqlDocumentMoveIntentPersistence.recordMoveIntentError(\n input.state.runtime.infra.execSql,\n {\n blocked: input.blocked,\n denied: input.denied,\n documentId: input.documentId,\n expectedIntentId: input.expectedIntentId,\n expectedUpdatedAt: input.expectedUpdatedAt,\n message: input.message,\n stillCurrent: input.isCurrent,\n unavailable: input.unavailable,\n },\n );\n return input.isCurrent();\n}\n"]}
1
+ {"version":3,"file":"documentMoveIntentErrors.js","sourceRoot":"","sources":["documentMoveIntentErrors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAG1H,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAU1D;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,IAAI,4BAA4B,CACpC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAClC,CAAC,qBAAqB,CAAC;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,SAAS;QAC7B,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,SAAS,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport async function recordPendingDocumentMoveIntentError(input: {\n blocked?: boolean | undefined;\n denied?: boolean | undefined;\n documentId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n isCurrent: () => boolean;\n message: string;\n state: { runtime: ContainerContentsWorkflowRuntime };\n unavailable?: boolean | undefined;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n await new DocumentMoveIntentRepository(\n input.state.runtime.infra.execSql,\n ).recordMoveIntentError({\n blocked: input.blocked,\n denied: input.denied,\n documentId: input.documentId,\n expectedIntentId: input.expectedIntentId,\n expectedUpdatedAt: input.expectedUpdatedAt,\n message: input.message,\n stillCurrent: input.isCurrent,\n unavailable: input.unavailable,\n });\n return input.isCurrent();\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { replaceDocumentLinksInTransaction } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
- import { sqlDocumentMoveIntentPersistence, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
+ import { DocumentMoveIntentRepository, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
3
3
  import { loadDocumentMovePlacement } from "../../../data/persistence/container-contents/documentPlacement.js";
4
4
  import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
5
5
  /** Called inside the relink commit; a refusal must roll that entire commit back. */
@@ -13,7 +13,8 @@ export async function settleDocumentMoveIntent(input) {
13
13
  throw new Error("Document move intent was superseded before local settlement");
14
14
  return;
15
15
  }
16
- const settled = await sqlDocumentMoveIntentPersistence.markMoveIntentSynced(input.execSql, {
16
+ // The relink transaction's executor: settlement commits with the relink.
17
+ const settled = await new DocumentMoveIntentRepository(input.execSql).markMoveIntentSynced({
17
18
  documentId: input.intent.documentId,
18
19
  expectedIntentId: input.intent.id,
19
20
  expectedUpdatedAt: input.intent.updatedAt,
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntentSettlement.js","sourceRoot":"","sources":["documentMoveIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,qFAAqF,CAAC;AACxI,OAAO,EAEL,gCAAgC,GACjC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gEAAgE,CAAC;AAC3G,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAGlG,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAM9C;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,GAAG,MAAM,yBAAyB,CAC5C,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,EACnD,KAAK,CAAC,MAAM,CAAC,UAAU,CACxB,CAAC;QACF,IAAI,MAAM,EAAE,EAAE,KAAK,KAAK,CAAC,MAAM,CAAC,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;QACJ,OAAO;IACT,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,gCAAgC,CAAC,oBAAoB,CACzE,KAAK,CAAC,OAAO,EACb;QACE,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,gBAAgB,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE;QACjC,iBAAiB,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;KAC1C,CACF,CAAC;IACF,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IACD,MAAM,iCAAiC,CACrC,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,KAAK,CAAC,kBAAkB,CACzB,CAAC;AACJ,CAAC","sourcesContent":["import { replaceDocumentLinksInTransaction } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type DocumentMoveIntentRecord,\n sqlDocumentMoveIntentPersistence,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { loadDocumentMovePlacement } from \"../../../data/persistence/container-contents/documentPlacement\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/** Called inside the relink commit; a refusal must roll that entire commit back. */\nexport async function settleDocumentMoveIntent(input: {\n execSql: ExecSql;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n linkedContainerIds: readonly string[];\n partial: boolean;\n}): Promise<void> {\n if (!input.isCurrent()) {\n throw new Error(\"Document move generation changed before local settlement\");\n }\n if (input.partial) {\n const intent = await loadDocumentMovePlacement(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n input.intent.documentId,\n );\n if (intent?.id !== input.intent.id)\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n return;\n }\n const settled = await sqlDocumentMoveIntentPersistence.markMoveIntentSynced(\n input.execSql,\n {\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n },\n );\n if (!settled || !input.isCurrent()) {\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n }\n await replaceDocumentLinksInTransaction(\n input.execSql,\n input.intent.documentId,\n input.linkedContainerIds,\n );\n}\n"]}
1
+ {"version":3,"file":"documentMoveIntentSettlement.js","sourceRoot":"","sources":["documentMoveIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,qFAAqF,CAAC;AACxI,OAAO,EAEL,4BAA4B,GAC7B,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gEAAgE,CAAC;AAC3G,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAGlG,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAM9C;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,GAAG,MAAM,yBAAyB,CAC5C,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,EACnD,KAAK,CAAC,MAAM,CAAC,UAAU,CACxB,CAAC;QACF,IAAI,MAAM,EAAE,EAAE,KAAK,KAAK,CAAC,MAAM,CAAC,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;QACJ,OAAO;IACT,CAAC;IACD,yEAAyE;IACzE,MAAM,OAAO,GAAG,MAAM,IAAI,4BAA4B,CACpD,KAAK,CAAC,OAAO,CACd,CAAC,oBAAoB,CAAC;QACrB,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,gBAAgB,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE;QACjC,iBAAiB,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;KAC1C,CAAC,CAAC;IACH,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IACD,MAAM,iCAAiC,CACrC,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,KAAK,CAAC,kBAAkB,CACzB,CAAC;AACJ,CAAC","sourcesContent":["import { replaceDocumentLinksInTransaction } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type DocumentMoveIntentRecord,\n DocumentMoveIntentRepository,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { loadDocumentMovePlacement } from \"../../../data/persistence/container-contents/documentPlacement\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\n/** Called inside the relink commit; a refusal must roll that entire commit back. */\nexport async function settleDocumentMoveIntent(input: {\n execSql: ExecSql;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n linkedContainerIds: readonly string[];\n partial: boolean;\n}): Promise<void> {\n if (!input.isCurrent()) {\n throw new Error(\"Document move generation changed before local settlement\");\n }\n if (input.partial) {\n const intent = await loadDocumentMovePlacement(\n getClientSQLitePersistenceRuntime(input.execSql).db,\n input.intent.documentId,\n );\n if (intent?.id !== input.intent.id)\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n return;\n }\n // The relink transaction's executor: settlement commits with the relink.\n const settled = await new DocumentMoveIntentRepository(\n input.execSql,\n ).markMoveIntentSynced({\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n });\n if (!settled || !input.isCurrent()) {\n throw new Error(\n \"Document move intent was superseded before local settlement\",\n );\n }\n await replaceDocumentLinksInTransaction(\n input.execSql,\n input.intent.documentId,\n input.linkedContainerIds,\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { reportAndRethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
2
- import { DOCUMENT_LINK_INTENT_TYPE, sqlDocumentMoveIntentPersistence, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
+ import { DOCUMENT_LINK_INTENT_TYPE, DocumentMoveIntentRepository, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
3
3
  import { errorMessage } from "../../../data/shared/errorMessage.js";
4
4
  import { defaultDocumentsPersistence, } from "../../documents/index.js";
5
5
  import { availableDocumentLinkIntent } from "../documentLinks/availableDocumentLinkIntent.js";
@@ -294,13 +294,14 @@ export async function syncPendingDocumentMoveIntents(input) {
294
294
  const lifecycleState = input.state;
295
295
  const state = { ...lifecycleState };
296
296
  const execSql = state.runtime.infra.execSql;
297
+ const moveIntents = new DocumentMoveIntentRepository(execSql);
297
298
  if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {
298
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql);
299
+ await moveIntents.resetDeniedMoveIntents();
299
300
  if (!input.isCurrent())
300
301
  return 0;
301
302
  markDeniedReplayGeneration(lifecycleState, execSql);
302
303
  }
303
- const pendingIntents = await sqlDocumentMoveIntentPersistence.listPendingMoveIntents(execSql);
304
+ const pendingIntents = await moveIntents.listPendingMoveIntents();
304
305
  if (!input.isCurrent())
305
306
  return 0;
306
307
  let movedCount = 0;
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntentSync.js","sourceRoot":"","sources":["documentMoveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EACL,yBAAyB,EAEzB,gCAAgC,GACjC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,2BAA2B,EAAE,MAAM,oCAAoC,CAAC;AAOjF,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,4BAA4B,GAC7B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAyBjF,KAAK,UAAU,wBAAwB,CAAW,KAMjD;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,aAAa,GAAG,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC;QACjD,WAAW,EAAE,KAAK,CAAC,iBAAiB;QACpC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU;QACnC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO;KAC9B,CAAC,CAAC;IACH,IAAI,CAAC,CAAC,MAAM,aAAa,CAAC,iBAAiB,EAA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CAAC;QAC5D,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,CAAC,CAAC;QACvE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;YAAE,OAAO,CAAC,CAAC;QACjC,0BAA0B,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IACD,MAAM,cAAc,GAClB,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,CAAC,CAAC;IACzE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,CAAC,CAAC;IACjC,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,KAAK,MAAM,MAAM,IAAI,cAAc,EAAE,CAAC;QACpC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;YAAE,OAAO,UAAU,CAAC;QAC1C,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC;YACpD,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM;YACN,KAAK;SACN,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,WAAW;YAAE,OAAO,UAAU,CAAC;QAC9C,0EAA0E;QAC1E,qEAAqE;QACrE,sEAAsE;QACtE,yEAAyE;QACzE,kCAAkC;QAClC,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,UAAU,IAAI,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport {\n DOCUMENT_LINK_INTENT_TYPE,\n type DocumentMoveIntentRecord,\n sqlDocumentMoveIntentPersistence,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentLinkSetFailureHandler,\n type DocumentRecord,\n defaultDocumentsPersistence,\n} from \"../../documents\";\nimport { availableDocumentLinkIntent } from \"../documentLinks/availableDocumentLinkIntent\";\nimport { moveRemoteContainerDocument } from \"../documentLinks/documentLinksMove\";\nimport type {\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRelinkInput,\n} from \"../documentQueries/documentStructureTypes\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../projectionKeys\";\nimport type { ContainerState } from \"../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../remoteHydration/reconciliation\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n deniedReplayMatchesGeneration,\n markDeniedReplayGeneration,\n} from \"./documentMoveDeniedReplay\";\nimport {\n type DocumentMoveFailureState,\n describeRejectedDocumentMove,\n} from \"./documentMoveFailure\";\nimport { recordPendingDocumentMoveIntentError } from \"./documentMoveIntentErrors\";\nimport { settleDocumentMoveIntent } from \"./documentMoveIntentSettlement\";\nimport { moveWithRotationProof } from \"./documentMoveRotationProof\";\nimport { moveWithVanishedContainerRefresh } from \"./documentMoveVanishedRefresh\";\n\ntype DocumentMoveIntentReplayResult =\n | \"abandoned\"\n | \"moved\"\n | \"partial\"\n | \"blocked\"\n | \"failed\";\n\nexport interface DocumentMoveIntentSyncHost<TRuntime> {\n documentWorkflowRuntime: (containerId: string) => TRuntime;\n openDocumentStore: (input: {\n containerId: string;\n documentId: string | null;\n localId: string;\n }) => DocumentStructuralMutationLocalStore<TRuntime>;\n}\n\ninterface DocumentMoveIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n runtime: ContainerContentsWorkflowRuntime;\n}\n\nasync function relinkMovedDocumentStore<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n relinkInput: DocumentStructuralMutationRelinkInput;\n targetContainerId: string;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n const documentStore = input.host.openDocumentStore({\n containerId: input.targetContainerId,\n documentId: input.intent.documentId,\n localId: input.intent.localId,\n });\n if (!(await documentStore.ensureInitialized()) || !input.isCurrent()) {\n return false;\n }\n\n const relinked = await documentStore.relink({\n ...input.relinkInput,\n stillCurrent: input.isCurrent,\n });\n if (!relinked || !input.isCurrent()) {\n return false;\n }\n\n documentStore.updateRuntime(\n input.host.documentWorkflowRuntime(input.targetContainerId),\n );\n return input.isCurrent();\n}\n\nasync function persistMovedDocumentReplay<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n state.runtime.infra.execSql,\n intent.localId,\n );\n if (!input.isCurrent() || !existingDocument) {\n return false;\n }\n\n const targetContainerId =\n intent.intentType === DOCUMENT_LINK_INTENT_TYPE &&\n existingDocument.containerId &&\n moved.linkedContainerIds.includes(existingDocument.containerId)\n ? existingDocument.containerId\n : moved.nextContainerId;\n\n const relinkInput: DocumentStructuralMutationRelinkInput = {\n accessEpoch: moved.accessEpoch ?? existingDocument.accessEpoch,\n ...(moved.accessStateHash === null\n ? {}\n : { accessStateHash: moved.accessStateHash }),\n containerId: targetContainerId,\n documentId: intent.documentId,\n localId: intent.localId,\n ...(moved.remoteState ?? {}),\n commitSideEffect: (transactionExecSql) =>\n settleDocumentMoveIntent({\n execSql: transactionExecSql,\n intent,\n isCurrent: input.isCurrent,\n linkedContainerIds: moved.linkedContainerIds,\n partial: moved.status === \"partial\",\n }),\n };\n\n return relinkMovedDocumentStore({\n host,\n isCurrent: input.isCurrent,\n intent,\n relinkInput,\n targetContainerId,\n });\n}\n\nasync function movePendingDocumentIntent<TRuntime>(input: {\n existingContainerId: string | null | undefined;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n onFailure: DocumentLinkSetFailureHandler;\n state: DocumentMoveIntentSyncState;\n}) {\n // Adding links keeps the content key and needs no full-history rotation proof.\n const linkOnly = input.intent.intentType === DOCUMENT_LINK_INTENT_TYPE;\n const move = (\n rotationSnapshot: Uint8Array,\n onFailure: DocumentLinkSetFailureHandler,\n ) =>\n moveRemoteContainerDocument({\n linkOnly,\n additionalLinkContainerIds: input.intent.additionalLinkContainerIds,\n removedLinkContainerIds: input.intent.removedLinkContainerIds,\n currentContainerId:\n input.intent.sourceContainerId ??\n input.existingContainerId ??\n input.intent.targetContainerId,\n documentId: input.intent.documentId,\n isCurrent: input.isCurrent,\n noteId: input.intent.localId,\n onFailure,\n replaceLinkedContainers: input.intent.replaceLinkedContainers,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.state.runtime,\n targetContainerId: input.intent.targetContainerId,\n });\n if (linkOnly && !input.intent.removedLinkContainerIds?.length) {\n return move(new Uint8Array(), input.onFailure);\n }\n return moveWithRotationProof({\n ...input,\n attempt: move,\n log: (message) => input.state.runtime.util.log(message),\n });\n}\n\nasync function resolveMoveIntentPreflight(input: {\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<\n | { existingDocument: DocumentRecord; result?: undefined }\n | { existingDocument?: undefined; result: DocumentMoveIntentReplayResult }\n> {\n const { intent, state } = input;\n const execSql = state.runtime.infra.execSql;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n execSql,\n intent.localId,\n );\n if (!input.isCurrent()) return { result: \"abandoned\" };\n if (!existingDocument || existingDocument.documentId !== intent.documentId) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move intent references a missing local document\",\n state,\n });\n return { result: \"blocked\" };\n }\n\n for (const targetId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n const targetState = state.containersById.get(targetId);\n if (!targetState) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Document move intent references a missing destination container\",\n state,\n });\n return { result: \"blocked\" };\n }\n if (input.isRemoteSyncBlocked(targetState.container.organizationId)) {\n return { result: \"blocked\" };\n }\n if (\n !hasRemoteContainerMetadataState(targetState) ||\n input.isCreatePending(targetId)\n ) {\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move destination container is not synced yet\",\n state,\n });\n return { result: \"failed\" };\n }\n }\n return { existingDocument };\n}\n\nasync function recordRejectedDocumentMove(input: {\n failure: DocumentMoveFailureState;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<void> {\n await recordPendingDocumentMoveIntentError({\n // A permission denial parks the intent for the access-restored signal\n // instead of replaying on every structural pass (row 7).\n denied: input.failure.sawPermissionDenial,\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n isCurrent: input.isCurrent,\n message: describeRejectedDocumentMove(input.failure),\n state: input.state,\n // Terminal only after the vanished-container refresh proved the\n // destination itself gone: the intent can never commit as written and\n // nothing on this device can heal it, so it leaves the replay set instead\n // of re-issuing doomed requests every pass. The tombstone cascade\n // retargets it once hydration tears the deleted container down locally.\n // Every other vanished verdict stays pending for the next pass.\n unavailable: input.unavailable,\n });\n}\n\nfunction logSyncedDocumentMove(\n intent: DocumentMoveIntentRecord,\n state: DocumentMoveIntentSyncState,\n): void {\n state.runtime.util.log(\n `Container contents: synced queued document move ${intent.documentId}`,\n );\n}\n\nasync function settleMovedDocumentIntent<TRuntime>(input: {\n failure: DocumentMoveFailureState;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { intent, moved, state } = input;\n if (\n !(await persistMovedDocumentReplay({\n host: input.host,\n intent,\n isCurrent: input.isCurrent,\n moved,\n state,\n }))\n ) {\n if (!input.isCurrent()) return \"abandoned\";\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move replay could not relink the local document\",\n state,\n });\n return \"failed\";\n }\n if (moved.status === \"partial\") {\n await recordPendingDocumentMoveIntentError({\n // An unlink refused for permissions parks like any other denied\n // move (row 7); other partials keep row 15's replay.\n denied: input.failure.sawPermissionDenial,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Remote document move partially applied; retry required\",\n state,\n // Terminal only when the refresh proved the destination itself gone\n // after the link had already landed; a vanished unlink alone stays\n // pending with its live link for the next pass to revoke.\n unavailable: input.unavailable,\n });\n return \"partial\";\n }\n\n logSyncedDocumentMove(intent, state);\n return \"moved\";\n}\n\nasync function trySyncPendingDocumentMoveIntent<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { host, intent, state } = input;\n const available = availableDocumentLinkIntent(intent, (id) =>\n state.containersById.has(id),\n );\n const preflight = await resolveMoveIntentPreflight({\n ...input,\n intent: available.intent,\n });\n if (preflight.result !== undefined) {\n return preflight.result;\n }\n const { existingDocument } = preflight;\n\n try {\n const outcome = await moveWithVanishedContainerRefresh({\n apiClient: state.runtime.apiClient,\n attempt: (onFailure) =>\n movePendingDocumentIntent({\n existingContainerId: existingDocument.containerId,\n host,\n isCurrent: input.isCurrent,\n intent: available.intent,\n onFailure,\n state,\n }),\n execSql: state.runtime.infra.execSql,\n existingContainerId: existingDocument.containerId,\n intent: available.intent,\n isCurrent: input.isCurrent,\n });\n if (outcome === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!outcome.moved) {\n await recordRejectedDocumentMove({\n failure: outcome.failure,\n intent,\n isCurrent: input.isCurrent,\n state,\n unavailable: outcome.unavailable,\n });\n return \"failed\";\n }\n return await settleMovedDocumentIntent({\n failure: outcome.failure,\n host,\n intent,\n isCurrent: input.isCurrent,\n moved: available.deferred\n ? { ...outcome.moved, status: \"partial\" }\n : outcome.moved,\n state,\n unavailable: outcome.unavailable,\n });\n } catch (error: unknown) {\n if (!input.isCurrent()) return \"abandoned\";\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.documentId,\n objectKind: \"document\",\n operation: \"document.move.replay\",\n },\n );\n if (!input.isCurrent()) return \"abandoned\";\n const message = errorMessage(error);\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: `Failed to sync document move: ${message}`,\n state,\n });\n return \"failed\";\n }\n}\n\nexport async function syncPendingDocumentMoveIntents<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n /** A destination whose create has not settled takes no document yet. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: DocumentMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) return 0;\n const lifecycleState = input.state;\n const state = { ...lifecycleState };\n const execSql = state.runtime.infra.execSql;\n if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql);\n if (!input.isCurrent()) return 0;\n markDeniedReplayGeneration(lifecycleState, execSql);\n }\n const pendingIntents =\n await sqlDocumentMoveIntentPersistence.listPendingMoveIntents(execSql);\n if (!input.isCurrent()) return 0;\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) return movedCount;\n const result = await trySyncPendingDocumentMoveIntent({\n host: input.host,\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n state,\n });\n if (result === \"abandoned\") return movedCount;\n // A \"partial\" result (link applied, unlink still pending) must not count:\n // the caller re-arms this same structural lane whenever the count is\n // positive, so a deterministically failing unlink hot-looped the pump\n // (issue #1744). The intent row stays pending; event-driven, manual, and\n // startup lane requests retry it.\n if (result === \"moved\") {\n movedCount += 1;\n }\n }\n\n return movedCount;\n}\n"]}
1
+ {"version":3,"file":"documentMoveIntentSync.js","sourceRoot":"","sources":["documentMoveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EACL,yBAAyB,EAEzB,4BAA4B,GAC7B,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,2BAA2B,EAAE,MAAM,oCAAoC,CAAC;AAOjF,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC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U,CAAC;QAC1C,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC;YACpD,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM;YACN,KAAK;SACN,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,WAAW;YAAE,OAAO,UAAU,CAAC;QAC9C,0EAA0E;QAC1E,qEAAqE;QACrE,sEAAsE;QACtE,yEAAyE;QACzE,kCAAkC;QAClC,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,UAAU,IAAI,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport {\n DOCUMENT_LINK_INTENT_TYPE,\n type DocumentMoveIntentRecord,\n DocumentMoveIntentRepository,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentLinkSetFailureHandler,\n type DocumentRecord,\n defaultDocumentsPersistence,\n} from \"../../documents\";\nimport { availableDocumentLinkIntent } from \"../documentLinks/availableDocumentLinkIntent\";\nimport { moveRemoteContainerDocument } from \"../documentLinks/documentLinksMove\";\nimport type {\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRelinkInput,\n} from \"../documentQueries/documentStructureTypes\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../projectionKeys\";\nimport type { ContainerState } from \"../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../remoteHydration/reconciliation\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n deniedReplayMatchesGeneration,\n markDeniedReplayGeneration,\n} from \"./documentMoveDeniedReplay\";\nimport {\n type DocumentMoveFailureState,\n describeRejectedDocumentMove,\n} from \"./documentMoveFailure\";\nimport { recordPendingDocumentMoveIntentError } from \"./documentMoveIntentErrors\";\nimport { settleDocumentMoveIntent } from \"./documentMoveIntentSettlement\";\nimport { moveWithRotationProof } from \"./documentMoveRotationProof\";\nimport { moveWithVanishedContainerRefresh } from \"./documentMoveVanishedRefresh\";\n\ntype DocumentMoveIntentReplayResult =\n | \"abandoned\"\n | \"moved\"\n | \"partial\"\n | \"blocked\"\n | \"failed\";\n\nexport interface DocumentMoveIntentSyncHost<TRuntime> {\n documentWorkflowRuntime: (containerId: string) => TRuntime;\n openDocumentStore: (input: {\n containerId: string;\n documentId: string | null;\n localId: string;\n }) => DocumentStructuralMutationLocalStore<TRuntime>;\n}\n\ninterface DocumentMoveIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n runtime: ContainerContentsWorkflowRuntime;\n}\n\nasync function relinkMovedDocumentStore<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n relinkInput: DocumentStructuralMutationRelinkInput;\n targetContainerId: string;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n const documentStore = input.host.openDocumentStore({\n containerId: input.targetContainerId,\n documentId: input.intent.documentId,\n localId: input.intent.localId,\n });\n if (!(await documentStore.ensureInitialized()) || !input.isCurrent()) {\n return false;\n }\n\n const relinked = await documentStore.relink({\n ...input.relinkInput,\n stillCurrent: input.isCurrent,\n });\n if (!relinked || !input.isCurrent()) {\n return false;\n }\n\n documentStore.updateRuntime(\n input.host.documentWorkflowRuntime(input.targetContainerId),\n );\n return input.isCurrent();\n}\n\nasync function persistMovedDocumentReplay<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n state.runtime.infra.execSql,\n intent.localId,\n );\n if (!input.isCurrent() || !existingDocument) {\n return false;\n }\n\n const targetContainerId =\n intent.intentType === DOCUMENT_LINK_INTENT_TYPE &&\n existingDocument.containerId &&\n moved.linkedContainerIds.includes(existingDocument.containerId)\n ? existingDocument.containerId\n : moved.nextContainerId;\n\n const relinkInput: DocumentStructuralMutationRelinkInput = {\n accessEpoch: moved.accessEpoch ?? existingDocument.accessEpoch,\n ...(moved.accessStateHash === null\n ? {}\n : { accessStateHash: moved.accessStateHash }),\n containerId: targetContainerId,\n documentId: intent.documentId,\n localId: intent.localId,\n ...(moved.remoteState ?? {}),\n commitSideEffect: (transactionExecSql) =>\n settleDocumentMoveIntent({\n execSql: transactionExecSql,\n intent,\n isCurrent: input.isCurrent,\n linkedContainerIds: moved.linkedContainerIds,\n partial: moved.status === \"partial\",\n }),\n };\n\n return relinkMovedDocumentStore({\n host,\n isCurrent: input.isCurrent,\n intent,\n relinkInput,\n targetContainerId,\n });\n}\n\nasync function movePendingDocumentIntent<TRuntime>(input: {\n existingContainerId: string | null | undefined;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n onFailure: DocumentLinkSetFailureHandler;\n state: DocumentMoveIntentSyncState;\n}) {\n // Adding links keeps the content key and needs no full-history rotation proof.\n const linkOnly = input.intent.intentType === DOCUMENT_LINK_INTENT_TYPE;\n const move = (\n rotationSnapshot: Uint8Array,\n onFailure: DocumentLinkSetFailureHandler,\n ) =>\n moveRemoteContainerDocument({\n linkOnly,\n additionalLinkContainerIds: input.intent.additionalLinkContainerIds,\n removedLinkContainerIds: input.intent.removedLinkContainerIds,\n currentContainerId:\n input.intent.sourceContainerId ??\n input.existingContainerId ??\n input.intent.targetContainerId,\n documentId: input.intent.documentId,\n isCurrent: input.isCurrent,\n noteId: input.intent.localId,\n onFailure,\n replaceLinkedContainers: input.intent.replaceLinkedContainers,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.state.runtime,\n targetContainerId: input.intent.targetContainerId,\n });\n if (linkOnly && !input.intent.removedLinkContainerIds?.length) {\n return move(new Uint8Array(), input.onFailure);\n }\n return moveWithRotationProof({\n ...input,\n attempt: move,\n log: (message) => input.state.runtime.util.log(message),\n });\n}\n\nasync function resolveMoveIntentPreflight(input: {\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<\n | { existingDocument: DocumentRecord; result?: undefined }\n | { existingDocument?: undefined; result: DocumentMoveIntentReplayResult }\n> {\n const { intent, state } = input;\n const execSql = state.runtime.infra.execSql;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n execSql,\n intent.localId,\n );\n if (!input.isCurrent()) return { result: \"abandoned\" };\n if (!existingDocument || existingDocument.documentId !== intent.documentId) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move intent references a missing local document\",\n state,\n });\n return { result: \"blocked\" };\n }\n\n for (const targetId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n const targetState = state.containersById.get(targetId);\n if (!targetState) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Document move intent references a missing destination container\",\n state,\n });\n return { result: \"blocked\" };\n }\n if (input.isRemoteSyncBlocked(targetState.container.organizationId)) {\n return { result: \"blocked\" };\n }\n if (\n !hasRemoteContainerMetadataState(targetState) ||\n input.isCreatePending(targetId)\n ) {\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move destination container is not synced yet\",\n state,\n });\n return { result: \"failed\" };\n }\n }\n return { existingDocument };\n}\n\nasync function recordRejectedDocumentMove(input: {\n failure: DocumentMoveFailureState;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<void> {\n await recordPendingDocumentMoveIntentError({\n // A permission denial parks the intent for the access-restored signal\n // instead of replaying on every structural pass (row 7).\n denied: input.failure.sawPermissionDenial,\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n isCurrent: input.isCurrent,\n message: describeRejectedDocumentMove(input.failure),\n state: input.state,\n // Terminal only after the vanished-container refresh proved the\n // destination itself gone: the intent can never commit as written and\n // nothing on this device can heal it, so it leaves the replay set instead\n // of re-issuing doomed requests every pass. The tombstone cascade\n // retargets it once hydration tears the deleted container down locally.\n // Every other vanished verdict stays pending for the next pass.\n unavailable: input.unavailable,\n });\n}\n\nfunction logSyncedDocumentMove(\n intent: DocumentMoveIntentRecord,\n state: DocumentMoveIntentSyncState,\n): void {\n state.runtime.util.log(\n `Container contents: synced queued document move ${intent.documentId}`,\n );\n}\n\nasync function settleMovedDocumentIntent<TRuntime>(input: {\n failure: DocumentMoveFailureState;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { intent, moved, state } = input;\n if (\n !(await persistMovedDocumentReplay({\n host: input.host,\n intent,\n isCurrent: input.isCurrent,\n moved,\n state,\n }))\n ) {\n if (!input.isCurrent()) return \"abandoned\";\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move replay could not relink the local document\",\n state,\n });\n return \"failed\";\n }\n if (moved.status === \"partial\") {\n await recordPendingDocumentMoveIntentError({\n // An unlink refused for permissions parks like any other denied\n // move (row 7); other partials keep row 15's replay.\n denied: input.failure.sawPermissionDenial,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Remote document move partially applied; retry required\",\n state,\n // Terminal only when the refresh proved the destination itself gone\n // after the link had already landed; a vanished unlink alone stays\n // pending with its live link for the next pass to revoke.\n unavailable: input.unavailable,\n });\n return \"partial\";\n }\n\n logSyncedDocumentMove(intent, state);\n return \"moved\";\n}\n\nasync function trySyncPendingDocumentMoveIntent<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { host, intent, state } = input;\n const available = availableDocumentLinkIntent(intent, (id) =>\n state.containersById.has(id),\n );\n const preflight = await resolveMoveIntentPreflight({\n ...input,\n intent: available.intent,\n });\n if (preflight.result !== undefined) {\n return preflight.result;\n }\n const { existingDocument } = preflight;\n\n try {\n const outcome = await moveWithVanishedContainerRefresh({\n apiClient: state.runtime.apiClient,\n attempt: (onFailure) =>\n movePendingDocumentIntent({\n existingContainerId: existingDocument.containerId,\n host,\n isCurrent: input.isCurrent,\n intent: available.intent,\n onFailure,\n state,\n }),\n execSql: state.runtime.infra.execSql,\n existingContainerId: existingDocument.containerId,\n intent: available.intent,\n isCurrent: input.isCurrent,\n });\n if (outcome === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!outcome.moved) {\n await recordRejectedDocumentMove({\n failure: outcome.failure,\n intent,\n isCurrent: input.isCurrent,\n state,\n unavailable: outcome.unavailable,\n });\n return \"failed\";\n }\n return await settleMovedDocumentIntent({\n failure: outcome.failure,\n host,\n intent,\n isCurrent: input.isCurrent,\n moved: available.deferred\n ? { ...outcome.moved, status: \"partial\" }\n : outcome.moved,\n state,\n unavailable: outcome.unavailable,\n });\n } catch (error: unknown) {\n if (!input.isCurrent()) return \"abandoned\";\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.documentId,\n objectKind: \"document\",\n operation: \"document.move.replay\",\n },\n );\n if (!input.isCurrent()) return \"abandoned\";\n const message = errorMessage(error);\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: `Failed to sync document move: ${message}`,\n state,\n });\n return \"failed\";\n }\n}\n\nexport async function syncPendingDocumentMoveIntents<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n /** A destination whose create has not settled takes no document yet. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: DocumentMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) return 0;\n const lifecycleState = input.state;\n const state = { ...lifecycleState };\n const execSql = state.runtime.infra.execSql;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {\n await moveIntents.resetDeniedMoveIntents();\n if (!input.isCurrent()) return 0;\n markDeniedReplayGeneration(lifecycleState, execSql);\n }\n const pendingIntents = await moveIntents.listPendingMoveIntents();\n if (!input.isCurrent()) return 0;\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) return movedCount;\n const result = await trySyncPendingDocumentMoveIntent({\n host: input.host,\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n state,\n });\n if (result === \"abandoned\") return movedCount;\n // A \"partial\" result (link applied, unlink still pending) must not count:\n // the caller re-arms this same structural lane whenever the count is\n // positive, so a deterministically failing unlink hot-looped the pump\n // (issue #1744). The intent row stays pending; event-driven, manual, and\n // startup lane requests retry it.\n if (result === \"moved\") {\n movedCount += 1;\n }\n }\n\n return movedCount;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { DOCUMENTS_APP_KIND } from "../../../data/documents/documentConstants.js";
2
2
  import { CONTAINER_METADATA_APP_KIND } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
3
- import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
3
+ import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
4
4
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
5
5
  import { clearDocumentSyncFailure, resetDocumentPendingUpdateRekeyBudget, } from "../../../data/persistence/documents/records/index.js";
6
6
  import { documentPlacementIntentTables, LOCAL_INTENT_LANES, } from "../../../data/sqlite/schema/index.js";
@@ -26,7 +26,7 @@ export function carriesLocalWrites(item) {
26
26
  export async function listPendingWrites(execSql) {
27
27
  await defaultContainerContentsPersistence.ensureSchema(execSql);
28
28
  await sqlDocumentsPersistence.ensureSchema(execSql);
29
- await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);
29
+ await new DocumentMoveIntentRepository(execSql).ensureSchema();
30
30
  const [persisted, deferred] = await Promise.all([
31
31
  listPersistedPendingWriteCandidates(execSql),
32
32
  listDeferredPendingWriteCandidates(execSql),
@@ -59,7 +59,7 @@ export async function resetPendingWriteRetryState(execSql, input) {
59
59
  // A deliberate retry is the rate-limited signal that conditions changed:
60
60
  // a parked permission-denied move (row 7) replays once, like row 11's
61
61
  // re-key budget reset.
62
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {
62
+ await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({
63
63
  localId: input.localId,
64
64
  });
65
65
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,kDAAkD,CAAC;AAElF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,mCAAmC,EAAE,MAAM,WAAW,CAAC;AAWhE;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAA2B;IAC5D,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC;AAChF,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAgB;IAEhB,MAAM,mCAAmC,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAChE,MAAM,uBAAuB,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,gCAAgC,CAAC,YAAY,CAAC,O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IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,kDAAkD,CAAC;AAElF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,mCAAmC,EAAE,MAAM,WAAW,CAAC;AAWhE;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAA2B;IAC5D,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC;AAChF,CAAC;AA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K,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,sEAAsE;IACtE,wEAAwE;IACxE,yEAAyE;IACzE,IAAI,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC;QAC7C,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await new DocumentMoveIntentRepository(execSql).ensureSchema();\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
1
+ import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
2
  import { requestDormantMetadataRestorationSweeps } from "../../../data/persistence/container-contents/dormantMetadataSweep.js";
3
3
  import { hasRecordedTerminalSyncFailures } from "../../../data/persistence/documents/records/index.js";
4
4
  import { requestAllDomainSyncLanes, requestDomainSyncLane, } from "../../../data/sync/syncCoordinator.js";
@@ -8,6 +8,7 @@ export async function recoverOrganizationAccess(input) {
8
8
  const { domainScope, execSql, organizationId, stillCurrent, userId } = input;
9
9
  if (!stillCurrent())
10
10
  return;
11
+ const moveIntents = new DocumentMoveIntentRepository(execSql);
11
12
  // The evidence gate: re-arm only when some queued write actually
12
13
  // recorded a terminal failure. A transient denial during bootstrap
13
14
  // (e.g. a read-model 403 before grants propagate) also flips the
@@ -15,15 +16,11 @@ export async function recoverOrganizationAccess(input) {
15
16
  // A failed pass (`undefined`) proves nothing about restored access,
16
17
  // so it must not re-arm either.
17
18
  if (((await hasRecordedTerminalSyncFailures(execSql)) ||
18
- (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {
19
- organizationId,
20
- }))) &&
19
+ (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&
21
20
  stillCurrent()) {
22
21
  // Parked permission-denied moves (row 7) only replay once flipped
23
22
  // back to pending; restore them before re-arming the lanes.
24
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {
25
- organizationId,
26
- });
23
+ await moveIntents.resetDeniedMoveIntents({ organizationId });
27
24
  if (stillCurrent())
28
25
  requestAllDomainSyncLanes(domainScope);
29
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAG9F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,gCAAgC,CAAC,oBAAoB,CAAC,OAAO,EAAE;YACpE,cAAc;SACf,CAAC,CAAC,CAAC;QACN,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,EAAE;YACrE,cAAc;SACf,CAAC,CAAC;QACH,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {\n organizationId,\n }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n organizationId,\n });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAG9F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,MAAM,WAAW,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IAC9D,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,WAAW,CAAC,oBAAoB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;QAC/D,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,WAAW,CAAC,sBAAsB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC;QAC7D,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await moveIntents.resetDeniedMoveIntents({ organizationId });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}