@kamilio/wire 0.1.56 → 0.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +44 -1
  2. package/dist/adapters/document-shell.d.ts +7 -0
  3. package/dist/adapters/document-shell.d.ts.map +1 -0
  4. package/dist/adapters/document-shell.js +51 -0
  5. package/dist/adapters/document-shell.js.map +1 -0
  6. package/dist/adapters/root.d.ts.map +1 -1
  7. package/dist/adapters/root.js +69 -4
  8. package/dist/adapters/root.js.map +1 -1
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +8 -2
  11. package/dist/cli.js.map +1 -1
  12. package/dist/document-shell-engine.mjs +1880 -0
  13. package/dist/executable.js +1 -1
  14. package/dist/executable.js.map +1 -1
  15. package/dist/hooks.d.ts.map +1 -1
  16. package/dist/hooks.js +19 -19
  17. package/dist/hooks.js.map +1 -1
  18. package/node_modules/provider-asana/dist/asana-project.d.ts +8 -1
  19. package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
  20. package/node_modules/provider-asana/dist/asana-task.d.ts +8 -1
  21. package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
  22. package/node_modules/provider-asana/dist/index.d.ts +16 -2
  23. package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
  24. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +8 -1
  25. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
  26. package/node_modules/provider-chatgpt/dist/index.d.ts +8 -1
  27. package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
  28. package/node_modules/provider-gmail/dist/gmail.d.ts +8 -1
  29. package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
  30. package/node_modules/provider-gmail/dist/index.d.ts +8 -1
  31. package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
  32. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -1
  33. package/node_modules/provider-google-docs/dist/doc-blocks.js +6 -2
  34. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -1
  35. package/node_modules/provider-google-docs/dist/google-docs.d.ts +8 -1
  36. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  37. package/node_modules/provider-google-docs/dist/google-docs.js +31 -10
  38. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  39. package/node_modules/provider-google-docs/dist/google-forms.d.ts +8 -1
  40. package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
  41. package/node_modules/provider-google-docs/dist/index.d.ts +16 -2
  42. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  43. package/node_modules/provider-google-docs/src/doc-blocks.ts +8 -2
  44. package/node_modules/provider-google-docs/src/google-docs.ts +26 -10
  45. package/node_modules/provider-lattice/dist/index.d.ts +16 -2
  46. package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
  47. package/node_modules/provider-notion/dist/index.d.ts +8 -1
  48. package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
  49. package/node_modules/provider-notion/dist/notion-sync.d.ts +2 -2
  50. package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
  51. package/node_modules/provider-notion/dist/notion-sync.js +24 -15
  52. package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
  53. package/node_modules/provider-notion/dist/notion.d.ts +8 -1
  54. package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
  55. package/node_modules/provider-notion/dist/notion.js +1 -1
  56. package/node_modules/provider-notion/dist/notion.js.map +1 -1
  57. package/node_modules/provider-notion/src/notion-sync.ts +23 -15
  58. package/node_modules/provider-notion/src/notion.ts +1 -1
  59. package/node_modules/provider-slack/dist/index.d.ts +8 -1
  60. package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
  61. package/node_modules/provider-slack/dist/slack.d.ts +8 -1
  62. package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
  63. package/node_modules/provider-zoom/dist/index.d.ts +8 -1
  64. package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
  65. package/node_modules/provider-zoom/dist/zoom-hub.d.ts +8 -1
  66. package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
  67. package/node_modules/wire-core/dist/core/editor-receipts.d.ts +5 -0
  68. package/node_modules/wire-core/dist/core/editor-receipts.d.ts.map +1 -0
  69. package/node_modules/wire-core/dist/core/editor-receipts.js +9 -0
  70. package/node_modules/wire-core/dist/core/editor-receipts.js.map +1 -0
  71. package/node_modules/wire-core/dist/core/model.d.ts +6 -1
  72. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  73. package/node_modules/wire-core/dist/core/owner.d.ts +3 -0
  74. package/node_modules/wire-core/dist/core/owner.d.ts.map +1 -0
  75. package/node_modules/wire-core/dist/core/owner.js +16 -0
  76. package/node_modules/wire-core/dist/core/owner.js.map +1 -0
  77. package/node_modules/wire-core/dist/core/source.d.ts +4 -1
  78. package/node_modules/wire-core/dist/core/source.d.ts.map +1 -1
  79. package/node_modules/wire-core/dist/core/source.js +15 -2
  80. package/node_modules/wire-core/dist/core/source.js.map +1 -1
  81. package/node_modules/wire-core/dist/index.d.ts +1 -1
  82. package/node_modules/wire-core/dist/index.d.ts.map +1 -1
  83. package/node_modules/wire-core/dist/index.js +1 -1
  84. package/node_modules/wire-core/dist/index.js.map +1 -1
  85. package/node_modules/wire-core/dist/operations.d.ts +11 -2
  86. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  87. package/node_modules/wire-core/dist/operations.js +404 -31
  88. package/node_modules/wire-core/dist/operations.js.map +1 -1
  89. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts +17 -0
  90. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts.map +1 -0
  91. package/node_modules/wire-core/dist/storage/editor-receipts.js +27 -0
  92. package/node_modules/wire-core/dist/storage/editor-receipts.js.map +1 -0
  93. package/node_modules/wire-core/dist/storage/history-integrity.d.ts +4 -0
  94. package/node_modules/wire-core/dist/storage/history-integrity.d.ts.map +1 -0
  95. package/node_modules/wire-core/dist/storage/history-integrity.js +32 -0
  96. package/node_modules/wire-core/dist/storage/history-integrity.js.map +1 -0
  97. package/node_modules/wire-core/dist/storage/history.d.ts +93 -0
  98. package/node_modules/wire-core/dist/storage/history.d.ts.map +1 -0
  99. package/node_modules/wire-core/dist/storage/history.js +450 -0
  100. package/node_modules/wire-core/dist/storage/history.js.map +1 -0
  101. package/node_modules/wire-core/dist/storage/registry.d.ts +2 -2
  102. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  103. package/node_modules/wire-core/dist/storage/registry.js +34 -14
  104. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  105. package/node_modules/wire-core/dist/storage/workspace.d.ts.map +1 -1
  106. package/node_modules/wire-core/dist/storage/workspace.js +183 -40
  107. package/node_modules/wire-core/dist/storage/workspace.js.map +1 -1
  108. package/node_modules/wire-core/src/core/editor-receipts.ts +8 -0
  109. package/node_modules/wire-core/src/core/model.ts +6 -1
  110. package/node_modules/wire-core/src/core/owner.ts +16 -0
  111. package/node_modules/wire-core/src/core/source.ts +17 -1
  112. package/node_modules/wire-core/src/index.ts +1 -1
  113. package/node_modules/wire-core/src/operations.ts +344 -33
  114. package/node_modules/wire-core/src/storage/editor-receipts.ts +27 -0
  115. package/node_modules/wire-core/src/storage/history-integrity.ts +25 -0
  116. package/node_modules/wire-core/src/storage/history.ts +331 -0
  117. package/node_modules/wire-core/src/storage/registry.ts +22 -15
  118. package/node_modules/wire-core/src/storage/workspace.ts +129 -34
  119. package/package.json +6 -2
  120. package/src/adapters/document-shell.ts +43 -0
  121. package/src/adapters/root.ts +71 -4
  122. package/src/cli.ts +8 -2
  123. package/src/executable.ts +1 -1
  124. package/src/hooks.ts +19 -18
@@ -1,9 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { FileRegistry, SqliteRegistry } from "./storage/registry.js";
4
+ import { DocumentHistory, requireHistoryVolume, withHistoryLock, working } from "./storage/history.js";
5
+ import { editorFile, editorView, plainMarkdown } from "./storage/editor-receipts.js";
6
+ import { assertWireOwner } from "./core/owner.js";
3
7
  import { stableJsonCompact } from "./core/json.js";
4
8
  import { extractRelationships, markdownFilename } from "./core/transform.js";
5
9
  import { resourceId } from "./core/resource.js";
6
- import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
10
+ import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource, WireMergeConflict } from "./core/source.js";
7
11
  export const wireWatchHooks = Symbol("wireWatchHooks");
8
12
  async function wireRoot(dependencies, path) {
9
13
  const configured = await dependencies.workspace.configuredRoot(path, dependencies.home);
@@ -130,9 +134,35 @@ function errorMessage(error) {
130
134
  return JSON.stringify(error);
131
135
  return String(error);
132
136
  }
137
+ export { withHistoryLock };
138
+ export const sourceLock = (source) => source.service === "google-docs" && source.type === "document" ? "google-docs:" + String(source["document_id"] ?? source.identifier.split("#tab=")[0]) : resourceId(source);
133
139
  export function composeWire(dependencies) {
134
- const store = async (url, path, fetched, previousMarkdown, action, fixedOutputPath, summaryMarkdown, summaryAfterMarkdown) => {
140
+ const durable = (registry) => registry instanceof FileRegistry || registry instanceof SqliteRegistry;
141
+ const locked = async (root, registry, key, fn) => durable(registry) ? withHistoryLock(root, key, fn) : fn();
142
+ const owner = async (registry, source, url) => assertWireOwner(await registry.listResources(), source, dependencies.catalog.find(s => s.matches(new URL(url))));
143
+ const historyFor = async (root, registry, source) => durable(registry) ? DocumentHistory.load(root, resourceId(source), dependencies.now) : null;
144
+ const removeDetached = (registry) => async (before) => {
145
+ const current = (await registry.listResources()).find(r => r.id === before.id);
146
+ if (!current)
147
+ return;
148
+ if (stableJsonCompact(current) !== stableJsonCompact(before))
149
+ throw new Error("Registration changed during detach. The newer registration was kept.");
150
+ await registry.delete(before.id);
151
+ };
152
+ const restore = async (root, registry, source, path) => {
153
+ const history = await historyFor(root, registry, source);
154
+ await history?.recover(path, r => registry.put(r), removeDetached(registry));
155
+ return history;
156
+ };
157
+ const checkReceiptLink = (resource, h) => {
158
+ if (resource && (primaryLink(resource).data["editor_receipts"] === true) !== !!h?.refs.editorReceipts)
159
+ throw new Error("Missing Wire editor receipt history or link registration. Restore the link and its private history before syncing.");
160
+ };
161
+ const store = async (url, path, fetched, previousMarkdown, action, fixedOutputPath, summaryMarkdown, summaryAfterMarkdown, history, enableReceipts = false, expectedRaw) => {
135
162
  const source = parseSourceUrl(url, dependencies.catalog);
163
+ const service = dependencies.catalog.find(s => s.matches(new URL(url)));
164
+ if (service.owner !== undefined && (!jsonObject(fetched.data) || fetched.data["wire_owner"] !== service.owner))
165
+ throw new Error("Provider returned a snapshot without its registered owner. The existing registration was kept.");
136
166
  const root = await wireRoot(dependencies, path);
137
167
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
138
168
  const current = findResource(await registry.listResources(), source, dependencies.catalog);
@@ -147,34 +177,46 @@ export function composeWire(dependencies) {
147
177
  outputPath = await availableMarkdownPath(path, fetched.title, source.service, source.identifier, async (candidate) => await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
148
178
  }
149
179
  const relativePath = dependencies.workspace.relativePath(outputPath, root);
150
- const onDisk = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
180
+ checkReceiptLink(current, history);
181
+ plainMarkdown(fetched.markdown);
182
+ const raw = history ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
183
+ const view = raw === null ? null : history ? history.view(raw) : editorView(raw);
184
+ const onDisk = view?.markdown ?? null;
185
+ if (expectedRaw !== undefined && raw !== expectedRaw && (enableReceipts || history?.refs.editorReceipts))
186
+ throw new Error("Local file changed during sync; run wire sync again.");
187
+ if (!current && fixedOutputPath === undefined && onDisk !== null)
188
+ throw new Error("Another file appeared at the proposed attachment path; retry attach.");
151
189
  const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
152
190
  const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
153
191
  const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
154
192
  // Only advance the common base if the editor saw that version. Otherwise a retry
155
193
  // could mistake remote additions that never reached disk for local deletions.
156
- if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown)
194
+ if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) {
195
+ if (history) {
196
+ await history.observe(fetched);
197
+ await history.save();
198
+ }
157
199
  throw new Error(retry);
200
+ }
158
201
  if (action === "attached" && current !== null) {
159
202
  const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot").value;
160
- const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
203
+ const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data)) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
161
204
  if (baseMarkdown !== null && previous !== baseMarkdown)
162
205
  throw new Error(`Local edits exist for ${primaryLink(current).path}. Run \`wire sync ${primaryLink(current).path}\` before attaching this URL again.`);
163
206
  }
164
- if (!concurrentEdit && onDisk !== fetched.markdown)
165
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
166
207
  const id = resourceId(source);
167
208
  const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
209
+ const link = { path: relativePath, role: "primary", data: { ...(primary?.data ?? { format: "markdown" }), ...(enableReceipts ? { editor_receipts: true } : {}) } };
168
210
  const resource = {
169
211
  id,
170
212
  type: source.type,
171
213
  identifiers: [{ service: source.service, identifier: source.identifier }],
172
214
  urls: [url],
173
215
  filesystem_links: current === null
174
- ? [{ path: relativePath, role: "primary", data: { format: "markdown" } }]
216
+ ? [link]
175
217
  : [
176
218
  ...current.filesystem_links.filter((link) => !(link.path === relativePath && link.role === "primary")),
177
- primary ?? { path: relativePath, role: "primary", data: { format: "markdown" } },
219
+ link,
178
220
  ],
179
221
  data: [
180
222
  ...(current?.data.filter((item) => item.namespace !== "wire" && !(item.namespace === source.service && item.key === "snapshot")) ?? []),
@@ -184,16 +226,98 @@ export function composeWire(dependencies) {
184
226
  ],
185
227
  relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
186
228
  };
187
- const stored = await registry.put(resource);
229
+ let stored;
230
+ if (history) {
231
+ if (history.refs.conflict)
232
+ throw new Error("Unresolved Wire conflict. Review the saved revisions and use wire resolve.");
233
+ const currentBase = history.refs.base;
234
+ if (onDisk !== null && currentBase !== null && onDisk !== await history.text(currentBase) && (previousMarkdown === undefined || previousMarkdown === onDisk))
235
+ await history.captureLocal(onDisk, view?.shown ?? undefined);
236
+ const draft = history.refs.draft;
237
+ let next;
238
+ if (currentBase === null) {
239
+ const input = previousMarkdown === undefined || previousMarkdown === null || previousMarkdown === fetched.markdown ? null : await history.revision("local", previousMarkdown, []);
240
+ next = await history.revision("attach", fetched.markdown, [input]);
241
+ }
242
+ else if (draft !== null && draft !== currentBase && action !== "downloaded") {
243
+ const remote = history.refs.remote;
244
+ const merged = remote !== null && (remote !== currentBase || (view?.base != null && view.base !== currentBase));
245
+ next = await history.revision(merged ? "merge" : "local", fetched.markdown, merged ? [draft, remote] : [draft]);
246
+ }
247
+ else
248
+ next = await history.observe(fetched);
249
+ const refs = { ...history.refs, base: next, remote: next, draft: null, strict: false, resolution: null, resolutionParent: null, conflict: null };
250
+ delete refs.editorDraft;
251
+ // A confirmed push of the exact draft the editor already saw is safe to
252
+ // acknowledge even if another save arrived while it was in flight.
253
+ if (concurrentEdit && previousMarkdown === fetched.markdown) {
254
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
255
+ stored = await registry.get(resource.id);
256
+ }
257
+ else if (concurrentEdit) {
258
+ if (current !== null)
259
+ throw new Error(retry);
260
+ refs.base = previousMarkdown == null ? next : await history.revision("local", previousMarkdown, []);
261
+ refs.resolution = fetched;
262
+ refs.resolutionParent = next;
263
+ await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
264
+ stored = await registry.get(resource.id);
265
+ }
266
+ else {
267
+ if (enableReceipts || refs.editorReceipts)
268
+ refs.editorReceipts = { ...refs.editorReceipts };
269
+ const materialized = refs.editorReceipts ? editorFile(fetched.markdown, refs.editorReceipts, next, next) : fetched.markdown;
270
+ await history.publish(outputPath, raw, materialized, refs, resource, r => registry.put(r));
271
+ stored = await registry.get(resource.id);
272
+ }
273
+ }
274
+ else {
275
+ if (!concurrentEdit && onDisk !== fetched.markdown)
276
+ await dependencies.filesystem.writeText(outputPath, fetched.markdown);
277
+ stored = await registry.put(resource);
278
+ }
188
279
  if (concurrentEdit)
189
280
  throw new Error(retry);
190
281
  const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
191
282
  const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
192
283
  return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
193
284
  };
194
- const attach = async (url, path) => {
195
- const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
196
- return store(url, path, fetched, undefined, "attached", undefined, undefined, fetched.markdown);
285
+ const attach = async (url, path, editorReceipts = false) => {
286
+ return attachAt(url, path, undefined, editorReceipts);
287
+ };
288
+ const attachAt = async (url, path, fixed, editorReceipts = false) => {
289
+ const root = await wireRoot(dependencies, path), initial = await dependencies.workspace.openRegistry(root, dependencies.home);
290
+ const source = parseSourceUrl(url, dependencies.catalog);
291
+ return locked(root, initial, sourceLock(source), async () => {
292
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
293
+ await owner(registry, source, url);
294
+ const h = await restore(root, registry, source);
295
+ const current = findResource(await registry.listResources(), source, dependencies.catalog);
296
+ checkReceiptLink(current, h);
297
+ const service = dependencies.catalog.find(s => s.matches(new URL(url)));
298
+ if (editorReceipts && (!h || source.service !== "google-docs" || source.type !== "document" || (service.owner !== undefined && (!service.supportsEditorReceipts || fixed === undefined)))) {
299
+ throw new Error("Editor receipts require a Google Docs Markdown link with durable history. An owned provider must explicitly support receipts and adopt the existing file.");
300
+ }
301
+ if (current && fixed !== undefined && join(dirname(root), primaryLink(current).path) !== fixed)
302
+ throw new Error("This URL is already attached at another path.");
303
+ if (fixed !== undefined && (await registry.findByPath(dependencies.workspace.relativePath(fixed, root))).some(r => r.id !== resourceId(source)))
304
+ throw new Error("This file already has another registration.");
305
+ if (h && current)
306
+ await h.seed(markdownSnapshot(current.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
307
+ if (h?.refs.conflict)
308
+ throw new Error("Unresolved Wire conflict. Use wire resolve.");
309
+ if (h?.refs.strict)
310
+ throw new Error("Sync the pending Wire draft before attaching again.");
311
+ const trackedPath = current ? join(dirname(root), primaryLink(current).path) : fixed;
312
+ if (h)
313
+ await requireHistoryVolume(h.dir, trackedPath ? dirname(trackedPath) : path);
314
+ const raw = trackedPath && h ? await working(trackedPath) : undefined;
315
+ const existing = raw == null ? raw : h.view(raw).markdown;
316
+ const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
317
+ if (fixed !== undefined && (h ? existing : await dependencies.filesystem.readText(fixed)) !== fetched.markdown)
318
+ throw new Error("Cannot adopt: the existing file differs from the remote document.");
319
+ return store(url, path, fetched, fixed === undefined ? undefined : fetched.markdown, "attached", fixed, undefined, fetched.markdown, h, editorReceipts, raw);
320
+ });
197
321
  };
198
322
  const create = attach;
199
323
  const view = (url) => fetchSource(dependencies.fetchInput, url, dependencies.catalog);
@@ -283,31 +407,79 @@ export function composeWire(dependencies) {
283
407
  throw new Error(`Resource path not found: ${value}`);
284
408
  return registry.get(value);
285
409
  };
286
- const sync = async (value, path) => {
410
+ const syncInner = async (value, path) => {
287
411
  const candidatePath = resolve(path, value);
288
412
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
289
413
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
290
414
  const relativePath = dependencies.workspace.relativePath(candidatePath, root);
291
415
  const pathResources = await registry.findByPath(relativePath);
292
416
  if (pathResources.length === 0 && await dependencies.filesystem.exists(candidatePath)) {
293
- const markdown = await dependencies.filesystem.readText(candidatePath);
294
- const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, markdown, candidatePath);
295
- return store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown);
417
+ if (durable(registry))
418
+ await requireHistoryVolume(join(root, "history"), dirname(candidatePath));
419
+ const markdown = durable(registry) ? await working(candidatePath) : await dependencies.filesystem.readText(candidatePath);
420
+ if (markdown === null)
421
+ throw new Error("Cannot upload a missing Markdown file.");
422
+ const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, plainMarkdown(markdown), candidatePath);
423
+ const source = parseSourceUrl(uploaded.url, dependencies.catalog);
424
+ return locked(root, registry, sourceLock(source), async () => store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown, await restore(root, registry, source)));
296
425
  }
297
- const resource = await resolveResource(registry, value, root, path);
426
+ let resource = await resolveResource(registry, value, root, path);
298
427
  const outputPath = join(dirname(root), primaryLink(resource).path);
299
428
  const outputDirectory = dirname(outputPath);
300
429
  const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0], dependencies.catalog);
430
+ await owner(registry, source, resource.urls[0]);
431
+ const history = await restore(root, registry, source, outputPath);
432
+ resource = await registry.get(resource.id);
433
+ if (history)
434
+ await requireHistoryVolume(history.dir, outputDirectory);
435
+ if (history?.refs.conflict && !("editor" in history.refs.conflict))
436
+ throw new Error("Unresolved Wire conflict. Inspect wire conflicts and use wire resolve.");
301
437
  const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
302
438
  if (snapshot === undefined)
303
439
  throw new Error(`Missing saved snapshot for ${primaryLink(resource).path}. Keep the local file and download a separate copy to reconcile before syncing.`);
304
440
  if (!(await dependencies.filesystem.exists(outputPath)))
305
441
  throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
306
- const markdown = await dependencies.filesystem.readText(outputPath);
307
- const base = syncBase(source.service, snapshot, resource.data);
308
- const baseMarkdown = markdownSnapshot(base);
442
+ checkReceiptLink(resource, history);
443
+ let raw = history ? await working(outputPath) : await dependencies.filesystem.readText(outputPath);
444
+ if (raw === null)
445
+ throw new Error("Linked file missing: " + outputPath);
446
+ let view = history ? history.view(raw) : editorView(raw);
447
+ await history?.checkPendingDraft(view);
448
+ if (history?.refs.conflict && "editor" in history.refs.conflict) {
449
+ const c = history.refs.conflict;
450
+ const merge = dependencies.catalog.find(s => s.matches(new URL(resource.urls[0])))?.mergeDrafts;
451
+ const base = c.editorBase === c.shellBase ? history.commonAncestor(c.editor, c.shell) : null;
452
+ let merged;
453
+ // A user may already be reconciling the file. Never overwrite edits
454
+ // that arrived after the two local versions were captured.
455
+ const editor = await history.text(c.editor);
456
+ if (merge && base && view.markdown === editor && view.base === c.editorBase) {
457
+ const before = await history.text(base), shell = await history.text(c.shell);
458
+ try {
459
+ merged = merge(before, editor, shell);
460
+ }
461
+ catch { /* retain the saved conflict */ }
462
+ }
463
+ if (merged === undefined)
464
+ throw new Error("Unresolved Wire conflict. The editor save and shell draft are both local. Compare them with wire diff <resource> --from editor --to shell, then use wire resolve <resource> <choice>.");
465
+ const draft = await history.revision("merge", merged, [c.editor, c.shell]);
466
+ const receipts = { ...history.refs.editorReceipts };
467
+ const next = editorFile(merged, receipts, draft, c.editorBase);
468
+ await history.publish(outputPath, raw, next, { ...history.refs, conflict: null, editorReceipts: receipts, editorDraft: draft, draft, strict: true }, null, r => registry.put(r));
469
+ raw = next;
470
+ view = history.view(raw);
471
+ }
472
+ const markdown = view.markdown;
473
+ // A stale receipt proves Markdown ancestry, not native paragraph positions.
474
+ // Never attach a newer snapshot's verified revision or IDs to older bytes.
475
+ const base = view.base && history && view.base !== history.refs.base && view.base !== history.refs.resolutionParent
476
+ ? { markdown: await history.text(view.base) }
477
+ : history?.refs.resolution && (!view.base || view.base === history.refs.resolutionParent) ? storedSnapshot(history.refs.resolution) : syncBase(source.service, snapshot, resource.data);
478
+ if (history)
479
+ await history.seed(markdownSnapshot(snapshot));
480
+ const baseMarkdown = markdownSnapshot(base) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
309
481
  const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
310
- if (localChanged && !serviceCanSynchronize(resource.urls[0], dependencies.catalog))
482
+ if (localChanged && !history?.refs.strict && !serviceCanSynchronize(resource.urls[0], dependencies.catalog))
311
483
  throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
312
484
  if (source.service === "google-docs" && source["document_tab"] === "t.0") {
313
485
  const registered = findResource(await registry.listResources(), source, dependencies.catalog);
@@ -321,33 +493,123 @@ export function composeWire(dependencies) {
321
493
  await registry.rekey(registered, { service: source.service, identifier: source.identifier });
322
494
  }
323
495
  }
324
- const fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog, base, markdown, outputPath);
496
+ if (history && (localChanged || history.refs.draft !== null))
497
+ await history.captureLocal(markdown, view.shown ?? undefined);
498
+ const strict = (history?.refs.strict === true || view.base !== null) && localChanged;
499
+ if (history && strict && source.service !== "notion" && !(source.service === "google-docs" && source.type === "document")) {
500
+ const remote = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
501
+ await history.observe(remote);
502
+ await history.save();
503
+ if (remote.markdown !== markdown)
504
+ throw new Error("This provider cannot conditionally publish a Wire draft. The local revision was kept. Apply it in the provider, then sync to verify.");
505
+ return store(resource.urls[0], outputDirectory, remote, markdown, "synced", undefined, undefined, remote.markdown, history);
506
+ }
507
+ const observed = {};
508
+ let observations = Promise.resolve();
509
+ const fork = view.base ?? (history?.refs.resolution ? history.refs.resolutionParent : history?.refs.base);
510
+ let fetched;
511
+ try {
512
+ fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog, base, markdown, outputPath, remote => {
513
+ plainMarkdown(remote.markdown);
514
+ observed.remote = remote;
515
+ observations = observations.then(async () => { if (history) {
516
+ await history.observe(remote);
517
+ await history.save();
518
+ } });
519
+ return observations;
520
+ }, strict, raw);
521
+ await observations;
522
+ }
523
+ catch (error) {
524
+ await observations;
525
+ if (history && error instanceof WireMergeConflict && observed.remote && history.refs.draft && history.refs.remote) {
526
+ if (fork) {
527
+ history.refs.conflict = { base: fork, local: history.refs.draft, remote: history.refs.remote };
528
+ history.refs.resolution = observed.remote;
529
+ history.refs.resolutionParent = history.refs.remote;
530
+ await history.save();
531
+ throw new Error("Unresolved Wire conflict. " + error.message + " Inspect wire conflicts and use wire resolve.", { cause: error });
532
+ }
533
+ }
534
+ throw error;
535
+ }
536
+ if (history && !observed.remote && fetched.markdown !== markdown) {
537
+ await history.observe(fetched);
538
+ await history.save();
539
+ }
325
540
  const uploaded = fetched.wroteRemote ?? (localChanged && fetched.markdown !== baseMarkdown);
326
541
  const action = uploaded ? "uploaded" : fetched.markdown === markdown || (localChanged && fetched.markdown === baseMarkdown) ? "synced" : "downloaded";
327
- return store(resource.urls[0], outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
542
+ return store(resource.urls[0], outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown, history, false, raw);
328
543
  };
329
- const download = async (value, path) => {
544
+ const underResourceLock = async (value, path, fn) => {
545
+ const candidate = resolve(path, value);
546
+ const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : path), registry = await dependencies.workspace.openRegistry(root, dependencies.home);
547
+ const ids = await registry.findByPath(dependencies.workspace.relativePath(candidate, root));
548
+ const key = !ids.length && await dependencies.filesystem.exists(candidate) ? "path:" + dependencies.workspace.relativePath(candidate, root) : sourceLock(parseSourceUrl((await resolveResource(registry, value, root, path)).urls[0], dependencies.catalog));
549
+ return locked(root, registry, key, fn);
550
+ };
551
+ const sync = (v, p) => underResourceLock(v, p, () => syncInner(v, p));
552
+ const downloadInner = async (value, path) => {
330
553
  const candidatePath = resolve(path, value);
331
554
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
332
555
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
333
556
  const resource = await resolveResource(registry, value, root, path);
334
557
  const outputPath = join(dirname(root), primaryLink(resource).path);
335
- const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
558
+ const source = parseSourceUrl(resource.urls[0], dependencies.catalog);
559
+ await owner(registry, source, resource.urls[0]);
560
+ const h = await restore(root, registry, source, outputPath);
561
+ await h?.seed(markdownSnapshot(resource.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
562
+ if (h?.refs.conflict)
563
+ throw new Error("Unresolved Wire conflict. Use wire resolve.");
564
+ checkReceiptLink(resource, h);
565
+ const raw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
566
+ const markdown = raw === null ? null : (h ? h.view(raw) : editorView(raw)).markdown;
567
+ if (h?.refs.strict && h.refs.draft)
568
+ throw new Error("Sync the pending Wire draft before downloading over it.");
336
569
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
337
- return store(resource.urls[0], dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
570
+ return store(resource.urls[0], dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown, h, false, raw);
338
571
  };
339
- const detach = async (value, path) => {
572
+ const download = (v, p) => underResourceLock(v, p, () => downloadInner(v, p));
573
+ const detachInner = async (value, path) => {
340
574
  const candidatePath = resolve(path, value);
341
575
  const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
342
576
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
343
577
  const resource = await resolveResource(registry, value, root, path);
344
578
  const outputPath = join(dirname(root), primaryLink(resource).path);
345
- const previous = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "";
579
+ const source = parseSourceUrl(resource.urls[0], dependencies.catalog);
580
+ await owner(registry, source, resource.urls[0]);
581
+ const h = await historyFor(root, registry, source);
582
+ const recovered = await h?.recover(outputPath, r => registry.put(r), removeDetached(registry));
583
+ if (recovered) {
584
+ const markdown = await h.text(h.refs.base);
585
+ return { resource: recovered, path: outputPath, markdown, summary: { action: "detached", added: 0, modified: 0, removed: 0, remote: recovered.urls[0], local: outputPath } };
586
+ }
587
+ checkReceiptLink(resource, h);
588
+ const initialRaw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
589
+ const previousView = initialRaw === null ? null : (h ? h.view(initialRaw) : editorView(initialRaw));
590
+ const previous = previousView?.markdown ?? "";
591
+ if (h?.refs.conflict || h?.refs.strict)
592
+ throw new Error("Resolve and sync the Wire draft before detaching.");
346
593
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0], dependencies.catalog);
347
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
348
- await registry.delete(resource.id);
594
+ if (h) {
595
+ const onDisk = await working(outputPath);
596
+ if (onDisk !== initialRaw)
597
+ throw new Error("Local file changed during detach; retry.");
598
+ if (previousView)
599
+ await h.captureLocal(previousView.markdown, previousView.shown ?? undefined);
600
+ const next = await h.observe(fetched);
601
+ const { editorReceipts, ...plainRefs } = h.refs;
602
+ if (editorReceipts)
603
+ plainRefs.retiredEditorReceipts = { ...plainRefs.retiredEditorReceipts, ...editorReceipts };
604
+ await h.detach(outputPath, onDisk, fetched.markdown, { ...plainRefs, base: next, remote: next, draft: null }, resource, removeDetached(registry));
605
+ }
606
+ else {
607
+ await dependencies.filesystem.writeText(outputPath, fetched.markdown);
608
+ await registry.delete(resource.id);
609
+ }
349
610
  return { resource, path: outputPath, markdown: fetched.markdown, summary: { action: "detached", ...changeSummary(previous, fetched.markdown), remote: resource.urls[0], local: outputPath } };
350
611
  };
612
+ const detach = (v, p) => underResourceLock(v, p, () => detachInner(v, p));
351
613
  const unlink = detach;
352
614
  const runWatchHooks = async (hooks, command, result) => {
353
615
  let current = result;
@@ -386,6 +648,12 @@ export function composeWire(dependencies) {
386
648
  continue;
387
649
  const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
388
650
  lastSyncedMarkdown = result.markdown;
651
+ if (primaryLink(result.resource).data["editor_receipts"] === true) {
652
+ const h = await historyFor(root, registry, parseSourceUrl(result.resource.urls[0], dependencies.catalog));
653
+ if (h?.refs.editorReceipts && h.refs.base && await h.text(h.refs.base) === result.markdown) {
654
+ lastSyncedMarkdown = editorFile(result.markdown, h.refs.editorReceipts, h.refs.base, h.refs.base);
655
+ }
656
+ }
389
657
  }
390
658
  catch (error) {
391
659
  console.warn(`Wire watch: ${errorMessage(error)}`);
@@ -466,8 +734,113 @@ export function composeWire(dependencies) {
466
734
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
467
735
  return resolveResource(registry, value, root, path);
468
736
  };
737
+ const withDocument = async (v, p, run) => underResourceLock(v, p, async () => {
738
+ const candidate = resolve(p, v), root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : p);
739
+ const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
740
+ let r = await resolveResource(registry, v, root, p);
741
+ const path = join(dirname(root), primaryLink(r).path);
742
+ const source = parseSourceUrl(r.urls[0], dependencies.catalog);
743
+ const h = await restore(root, registry, source, path);
744
+ if (!h)
745
+ throw new Error("This registry does not provide durable document history.");
746
+ r = await registry.get(r.id);
747
+ checkReceiptLink(r, h);
748
+ await h.seed(markdownSnapshot(r.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
749
+ return run(h, path, registry, r);
750
+ });
751
+ const historyStatus = (v, p) => withDocument(v, p, async (h, path) => {
752
+ const raw = await working(path);
753
+ if (raw !== null)
754
+ await h.checkPendingDraft(h.view(raw));
755
+ return h.status(path);
756
+ });
757
+ const historyLog = (v, p) => withDocument(v, p, h => h.log());
758
+ const historyDiff = (v, p, from = "base", to = "working") => withDocument(v, p, async (h, path) => {
759
+ const raw = await working(path);
760
+ const current = raw === null ? null : h.view(raw).markdown;
761
+ const text = async (ref) => {
762
+ if (ref === "working") {
763
+ if (current === null)
764
+ throw new Error("Linked Markdown is missing.");
765
+ return current;
766
+ }
767
+ const c = h.refs.conflict;
768
+ const id = c && "editor" in c && (ref === "editor" || ref === "shell") ? c[ref]
769
+ : ref === "base" ? (c && "base" in c ? c.base : h.refs.base)
770
+ : ref === "remote" ? h.refs.remote : ref === "local" ? (c && "local" in c ? c.local : h.refs.draft ?? h.refs.base) : ref;
771
+ if (!id)
772
+ throw new Error("No saved " + ref + " revision.");
773
+ return h.text(id);
774
+ };
775
+ return { from, to, before: await text(from), after: await text(to), token: h.token(raw) };
776
+ });
777
+ const checkpoint = (v, p, expected, markdown, token) => withDocument(v, p, async (h, path, reg) => {
778
+ const raw = await working(path);
779
+ const view = raw === null ? null : h.view(raw);
780
+ if (!view || view.markdown !== expected || token !== h.token(raw))
781
+ throw new Error("Stale shell edit. The document changed; rerun the command.");
782
+ if (expected !== markdown) {
783
+ await h.checkPendingDraft(view);
784
+ if (h.refs.conflict && "editor" in h.refs.conflict)
785
+ throw new Error("Unresolved Wire conflict. Edit the working file and run wire resolve <resource> working, or choose editor or shell before using wire shell.");
786
+ plainMarkdown(markdown);
787
+ const prior = await h.captureLocal(expected, view.shown ?? undefined);
788
+ const draft = await h.revision("local", markdown, [prior]);
789
+ const refs = { ...h.refs, draft, strict: true, ...(view.base ? { editorDraft: draft } : {}) };
790
+ if (refs.editorReceipts)
791
+ refs.editorReceipts = { ...refs.editorReceipts };
792
+ const next = refs.editorReceipts && view.base ? editorFile(markdown, refs.editorReceipts, draft, view.base) : markdown;
793
+ await h.publish(path, raw, next, refs, null, r => reg.put(r));
794
+ }
795
+ return h.status(path);
796
+ });
797
+ const resolveConflict = (v, p, choice) => withDocument(v, p, async (h, path, reg) => {
798
+ const raw = await working(path);
799
+ if (raw === null)
800
+ throw new Error("Linked Markdown is missing.");
801
+ const view = h.view(raw), current = view.markdown;
802
+ await h.checkPendingDraft(view);
803
+ const conflict = h.refs.conflict;
804
+ if (!conflict)
805
+ throw new Error("No saved conflict for this document.");
806
+ let next, basis, parents;
807
+ if ("editor" in conflict) {
808
+ if (!["working", "editor", "shell"].includes(choice))
809
+ throw new Error("Both drafts are local. Choose editor, shell or working.");
810
+ if (choice !== "working" && current !== await h.text(conflict.editor))
811
+ throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
812
+ // The file being reconciled is the editor branch. Keep its remote basis
813
+ // for an edited working resolution; never silently adopt a later base.
814
+ basis = choice === "shell" ? conflict.shellBase : conflict.editorBase;
815
+ if (choice === "working" && view.base !== conflict.editorBase)
816
+ throw new Error("The working file has a different receipt. Restore the conflicted editor receipt before resolving.");
817
+ next = choice === "working" ? current : await h.text(choice === "shell" ? conflict.shell : conflict.editor);
818
+ parents = [conflict.editor, conflict.shell];
819
+ }
820
+ else {
821
+ if (!h.refs.resolution)
822
+ throw new Error("Missing saved provider conflict snapshot.");
823
+ if (!["working", "local", "remote"].includes(choice))
824
+ throw new Error("Choose local, remote or working.");
825
+ const local = await h.text(conflict.local);
826
+ if (choice !== "working" && current !== local)
827
+ throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
828
+ next = choice === "working" ? current : choice === "local" ? local : await h.text(conflict.remote);
829
+ basis = conflict.remote;
830
+ parents = [conflict.local, conflict.remote];
831
+ }
832
+ const draft = await h.revision("resolve", next, parents);
833
+ const refs = { ...h.refs, draft, strict: true, conflict: null, ...(h.refs.editorReceipts ? { editorDraft: draft } : {}) };
834
+ if (refs.editorReceipts)
835
+ refs.editorReceipts = { ...refs.editorReceipts };
836
+ const materialized = refs.editorReceipts ? editorFile(next, refs.editorReceipts, draft, basis) : next;
837
+ await h.publish(path, raw, materialized, refs, null, r => reg.put(r));
838
+ return h.status(path);
839
+ });
469
840
  return Object.freeze({
470
841
  attach,
842
+ adopt: (url, path, editorReceipts = false) => attachAt(url, dirname(resolve(path)), resolve(path), editorReceipts),
843
+ historyStatus, historyDiff, historyLog, checkpoint, resolveConflict,
471
844
  create,
472
845
  view,
473
846
  downloadSource,